Initial commit: Sourizz, a Linux cursor highlighter
Spotlight, ring, trails, click effects, keystroke display and on-screen annotation for X11 and Wayland, written in Rust. One drawing engine (engine.rs) shared by an X11 backend (override-redirect ARGB windows, XInput2 raw events) and a Wayland backend (wlr-layer-shell, evdev input, Hyprland/KWin pointer sources), plus a tray, a CLI socket and an egui settings window. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
@@ -0,0 +1,2 @@
|
|||||||
|
target/
|
||||||
|
*.png.tmp
|
||||||
@@ -0,0 +1,51 @@
|
|||||||
|
# CLAUDE.md
|
||||||
|
|
||||||
|
This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository.
|
||||||
|
|
||||||
|
## What this is
|
||||||
|
|
||||||
|
Sourizz is a Linux cursor highlighter (spotlight, ring, trails, click effects, keystroke display, on-screen drawing) for X11 and Wayland, written in Rust. It is an independent re-implementation of the idea behind the macOS app Mouzz. READMEs exist in English (`README.md`) and French (`README.fr.md`); keep them in sync. Licensed `AGPL-3.0-or-later` (`LICENSE`): new dependencies must be licence-compatible (MIT/Apache-2.0/BSD-style are fine).
|
||||||
|
|
||||||
|
## Commands
|
||||||
|
|
||||||
|
```sh
|
||||||
|
cargo build --release # daemon + settings window (first build is slow: egui)
|
||||||
|
cargo build --release --no-default-features # daemon only
|
||||||
|
cargo test # 57 unit/property tests, ~3 s
|
||||||
|
cargo test --lib engine::tests::shake # one test (name filter)
|
||||||
|
cargo clippy --all-targets && cargo fmt # both must stay clean (rustfmt.toml: max_width 140)
|
||||||
|
cargo run --release -- demo out/ # render every effect to PNG, no display needed
|
||||||
|
cargo run -- -vv --no-tray # run the daemon verbosely (-vv = debug for the sourizz crate only)
|
||||||
|
./install.sh [--uninstall] # user install into ~/.local
|
||||||
|
```
|
||||||
|
|
||||||
|
`examples/x11_probe.rs` is an end-to-end check against a running X11 daemon (also `fake_keys`, `mover` helpers). Run the daemon with an isolated config: `XDG_CONFIG_HOME=<tmp> sourizz --no-tray`. The probe only touches its own test window, but a human moving the real mouse during the run makes it fail.
|
||||||
|
|
||||||
|
## Architecture
|
||||||
|
|
||||||
|
One drawing engine, two display backends, shared daemon core.
|
||||||
|
|
||||||
|
- `engine.rs` — **all** effect state and painting, no I/O. Input: `handle(now, InputEvent)`; output: `begin_frame(now) -> FramePlan{damage: Vec<IRect>, next_in}` then `paint(pixmap, region, now)`. Time is a caller-supplied `f64`, so it is fully testable. Sub-modules: `annot.rs` (strokes, toolbar, annotation-mode input), `keyviz.rs` (keystroke chips), `fx.rs` (tiny-skia primitives), `text.rs` (fontdue, font found via `fc-match`).
|
||||||
|
- `canvas.rs` — `Layer`: one per monitor, converts RGBA→premultiplied BGRA for damaged rects only. X11 uses a *streaming* layer (server keeps the pixels); Wayland a *retained* one (full buffer each commit).
|
||||||
|
- `x11.rs` — override-redirect ARGB32 window per monitor, empty XShape input region (click-through), XInput2 *raw* events for global input, `XGrabKey` hotkeys, real pointer+keyboard grab in annotation mode.
|
||||||
|
- `wayland.rs` — wlr-layer-shell surface per output, `wl_shm`, frame-callback pacing. Pointer position comes from `wlsrc.rs` (Hyprland IPC / dead-reckoning estimate) or `kwin.rs` (KWin script → D-Bus service `org.sourizz.Daemon`); clicks/keys from `evdev_in.rs`; layouts via `xkb.rs` (libxkbcommon through dlopen).
|
||||||
|
- `core.rs` — owns `Engine` + live `Config`; applies `Command`s (from tray `tray.rs`, CLI socket `ipc.rs`, hotkeys), hot-reloads the config file, plays sounds (`audio.rs`), keeps the tray in sync. `control.rs` has `Command`, `Hub` (channel + wake pipe) and `set_option`.
|
||||||
|
- `src/bin/settings.rs` — egui settings window; edits `config.toml`, the daemon reloads it. Gated by the default `gui` feature.
|
||||||
|
|
||||||
|
Adding a config option touches: `config.rs` (struct, `Default`, `sanitize`), `i18n.rs` (strings; enum values need an `opt.<id>` entry — a test enforces it), `settings.rs`, and both READMEs if user-visible.
|
||||||
|
|
||||||
|
## Gotchas learned the hard way
|
||||||
|
|
||||||
|
- **No `-dev` packages on the dev machine.** Keep the build pure Rust: `smithay-client-toolkit` has `default-features = false` (its `xkbcommon` feature needs `xkbcommon.pc`), keyboard handling is done by hand with `xkbcommon-dl`. `zbus` is pinned to 5 to match `ksni`.
|
||||||
|
- **x11rb queues events when you read a reply.** Always `poll_for_event()` once more right before sleeping in `poll(2)`, or events sit unseen for up to the idle timeout.
|
||||||
|
- **Damage model:** `Engine::bounds` returns `[IRect; 3]` slots; each slot is unioned with *its own* previous value so a moving edge (spotlight bar) covers the gap in between. Any change that alters pixels outside the reported bounds (monitor switch, config change) must force a full redraw. `canvas.rs` has a property test that incremental painting equals a full repaint — keep it green.
|
||||||
|
- After any command or config reload `Core::pump()` returns true; backends must repaint on it (forgetting this left changes invisible until the mouse moved).
|
||||||
|
- tiny-skia: `fill_rect` with a transform or anti-aliasing falls off its fast path (use `fx::fill_rect_fast`); `Rect::from_ltrb` accepts zero width and then fills a 1 px sliver; anti-aliasing is not perfectly translation-invariant (hence the tolerance in the canvas property test).
|
||||||
|
- evdev codes + 8 = xkb/X keycodes. The `wl_keyboard` keymap fd shares its file offset with the compositor: read it with `read_exact_at(.., 0)`.
|
||||||
|
- **egui ids must be unique on screen.** Two `ComboBox`es sharing an id (e.g. both labelled "Style") act as one control and their popups close each other, so the lists could not be opened. `combo()` in `settings.rs` takes an explicit id — never derive it from the label. `examples/click_at.rs` drives the real settings window through XTEST for such checks (it refuses to click unless the pointer is over our own window).
|
||||||
|
- Process name `sourizz-settings` is truncated to 15 chars by the kernel: use `pgrep -x sourizz-setting`, and never `pgrep -f` from a shell whose own command line contains the pattern.
|
||||||
|
|
||||||
|
## Testing Wayland without a Wayland session
|
||||||
|
|
||||||
|
Run a private compositor with its own bus and a *short* runtime dir (socket paths are limited to 108 bytes):
|
||||||
|
`XDG_RUNTIME_DIR=/tmp/x dbus-run-session -- kwin_wayland --virtual --socket sz --no-lockscreen --no-global-shortcuts --width 1280 --height 720`, then start `sourizz --backend wayland --no-tray` with `WAYLAND_DISPLAY=sz`, the same `XDG_RUNTIME_DIR`, the nested `DBUS_SESSION_BUS_ADDRESS` and (no input devices there) `SOURIZZ_FAKE_POINTER=640,360`. `spectacle -b -n -f -o file.png` in that environment screenshots the nested compositor. Real input devices (the evdev path) cannot be tested this way.
|
||||||
@@ -0,0 +1,52 @@
|
|||||||
|
[package]
|
||||||
|
name = "sourizz"
|
||||||
|
version = "0.1.0"
|
||||||
|
edition = "2024"
|
||||||
|
description = "Cursor highlighter for Linux: spotlight, ring, trails, click effects, keystrokes and on-screen drawing (X11 and Wayland)"
|
||||||
|
license = "AGPL-3.0-or-later"
|
||||||
|
readme = "README.md"
|
||||||
|
keywords = ["cursor", "highlighter", "screencast", "wayland", "x11"]
|
||||||
|
categories = ["accessibility", "gui"]
|
||||||
|
|
||||||
|
[dependencies]
|
||||||
|
anyhow = "1.0.104"
|
||||||
|
clap = { version = "4.6.7", features = ["derive"] }
|
||||||
|
eframe = { version = "0.37.0", default-features = false, features = ["glow", "x11", "wayland", "default_fonts"], optional = true }
|
||||||
|
env_logger = "0.11.11"
|
||||||
|
evdev = "0.13.2"
|
||||||
|
fontdue = "0.9.5"
|
||||||
|
ksni = { version = "0.3.7", default-features = false, features = ["async-io", "blocking"] }
|
||||||
|
log = "0.4.34"
|
||||||
|
rustix = { version = "1.1.6", features = ["event", "pipe", "net", "fs"] }
|
||||||
|
serde = { version = "1.0.229", features = ["derive"] }
|
||||||
|
signal-hook = "0.4.5"
|
||||||
|
smithay-client-toolkit = { version = "0.21.1", default-features = false }
|
||||||
|
tiny-skia = { version = "0.12.0", features = ["png-format"] }
|
||||||
|
toml = "1.1.8"
|
||||||
|
wayland-client = "0.31.15"
|
||||||
|
x11rb = { version = "0.14.0", features = ["shape", "randr", "xinput", "xtest", "xfixes", "xkb", "render"] }
|
||||||
|
xkbcommon-dl = "0.4.2"
|
||||||
|
zbus = { version = "5", default-features = false, features = ["async-io", "blocking-api"] }
|
||||||
|
|
||||||
|
|
||||||
|
[features]
|
||||||
|
default = ["gui"]
|
||||||
|
gui = ["dep:eframe"]
|
||||||
|
|
||||||
|
[[bin]]
|
||||||
|
name = "sourizz"
|
||||||
|
path = "src/main.rs"
|
||||||
|
|
||||||
|
[[bin]]
|
||||||
|
name = "sourizz-settings"
|
||||||
|
path = "src/bin/settings.rs"
|
||||||
|
required-features = ["gui"]
|
||||||
|
|
||||||
|
[profile.release]
|
||||||
|
lto = "thin"
|
||||||
|
codegen-units = 4
|
||||||
|
strip = true
|
||||||
|
opt-level = 3
|
||||||
|
|
||||||
|
[profile.test]
|
||||||
|
opt-level = 1
|
||||||
@@ -0,0 +1,661 @@
|
|||||||
|
GNU AFFERO GENERAL PUBLIC LICENSE
|
||||||
|
Version 3, 19 November 2007
|
||||||
|
|
||||||
|
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
|
||||||
|
Everyone is permitted to copy and distribute verbatim copies
|
||||||
|
of this license document, but changing it is not allowed.
|
||||||
|
|
||||||
|
Preamble
|
||||||
|
|
||||||
|
The GNU Affero General Public License is a free, copyleft license for
|
||||||
|
software and other kinds of works, specifically designed to ensure
|
||||||
|
cooperation with the community in the case of network server software.
|
||||||
|
|
||||||
|
The licenses for most software and other practical works are designed
|
||||||
|
to take away your freedom to share and change the works. By contrast,
|
||||||
|
our General Public Licenses are 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.
|
||||||
|
|
||||||
|
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.
|
||||||
|
|
||||||
|
Developers that use our General Public Licenses protect your rights
|
||||||
|
with two steps: (1) assert copyright on the software, and (2) offer
|
||||||
|
you this License which gives you legal permission to copy, distribute
|
||||||
|
and/or modify the software.
|
||||||
|
|
||||||
|
A secondary benefit of defending all users' freedom is that
|
||||||
|
improvements made in alternate versions of the program, if they
|
||||||
|
receive widespread use, become available for other developers to
|
||||||
|
incorporate. Many developers of free software are heartened and
|
||||||
|
encouraged by the resulting cooperation. However, in the case of
|
||||||
|
software used on network servers, this result may fail to come about.
|
||||||
|
The GNU General Public License permits making a modified version and
|
||||||
|
letting the public access it on a server without ever releasing its
|
||||||
|
source code to the public.
|
||||||
|
|
||||||
|
The GNU Affero General Public License is designed specifically to
|
||||||
|
ensure that, in such cases, the modified source code becomes available
|
||||||
|
to the community. It requires the operator of a network server to
|
||||||
|
provide the source code of the modified version running there to the
|
||||||
|
users of that server. Therefore, public use of a modified version, on
|
||||||
|
a publicly accessible server, gives the public access to the source
|
||||||
|
code of the modified version.
|
||||||
|
|
||||||
|
An older license, called the Affero General Public License and
|
||||||
|
published by Affero, was designed to accomplish similar goals. This is
|
||||||
|
a different license, not a version of the Affero GPL, but Affero has
|
||||||
|
released a new version of the Affero GPL which permits relicensing under
|
||||||
|
this license.
|
||||||
|
|
||||||
|
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 Affero 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. Remote Network Interaction; Use with the GNU General Public License.
|
||||||
|
|
||||||
|
Notwithstanding any other provision of this License, if you modify the
|
||||||
|
Program, your modified version must prominently offer all users
|
||||||
|
interacting with it remotely through a computer network (if your version
|
||||||
|
supports such interaction) an opportunity to receive the Corresponding
|
||||||
|
Source of your version by providing access to the Corresponding Source
|
||||||
|
from a network server at no charge, through some standard or customary
|
||||||
|
means of facilitating copying of software. This Corresponding Source
|
||||||
|
shall include the Corresponding Source for any work covered by version 3
|
||||||
|
of the GNU General Public License that is incorporated pursuant to the
|
||||||
|
following paragraph.
|
||||||
|
|
||||||
|
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 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 work with which it is combined will remain governed by version
|
||||||
|
3 of the GNU General Public License.
|
||||||
|
|
||||||
|
14. Revised Versions of this License.
|
||||||
|
|
||||||
|
The Free Software Foundation may publish revised and/or new versions of
|
||||||
|
the GNU Affero 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 Affero 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 Affero 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 Affero 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 Affero 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 Affero General Public License for more details.
|
||||||
|
|
||||||
|
You should have received a copy of the GNU Affero General Public License
|
||||||
|
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||||
|
|
||||||
|
Also add information on how to contact you by electronic and paper mail.
|
||||||
|
|
||||||
|
If your software can interact with users remotely through a computer
|
||||||
|
network, you should also make sure that it provides a way for users to
|
||||||
|
get its source. For example, if your program is a web application, its
|
||||||
|
interface could display a "Source" link that leads users to an archive
|
||||||
|
of the code. There are many ways you could offer source, and different
|
||||||
|
solutions will be better for different programs; see section 13 for the
|
||||||
|
specific requirements.
|
||||||
|
|
||||||
|
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 AGPL, see
|
||||||
|
<https://www.gnu.org/licenses/>.
|
||||||
@@ -0,0 +1,220 @@
|
|||||||
|
# Sourizz
|
||||||
|
|
||||||
|
[English](README.md) · **Français**
|
||||||
|
|
||||||
|
Une mise en valeur du curseur pour Linux. Placez un **projecteur**, un **anneau**, une **traînée** ou une **ondulation de clic** sur votre pointeur, affichez vos **frappes au clavier** et **dessinez sur l'écran** — pour des présentations, des tutoriels, des captures vidéo, ou simplement pour ne plus perdre votre curseur sur un grand écran. Fonctionne sous **X11 et Wayland**.
|
||||||
|
|
||||||
|
Sourizz est une réécriture indépendante pour Linux de l'idée de [Mouzz](https://mouzz.dev) sur macOS. Il ne partage ni code ni ressources avec lui et n'est ni affilié à son auteur ni approuvé par lui.
|
||||||
|
|
||||||
|

|
||||||
|
|
||||||
|
## Fonctionnalités
|
||||||
|
|
||||||
|
| | |
|
||||||
|
|---|---|
|
||||||
|
| **Projecteur** | Assombrit tout sauf un cercle, une barre horizontale ou une barre verticale aux bords doux autour du pointeur. Rayon, opacité, douceur et couleur réglables. |
|
||||||
|
| **Anneau de curseur** | Un anneau qui suit le pointeur, avec une légère pulsation. Style Classique ou Néon ; taille, épaisseur, couleur, remplissage et vitesse de pulsation réglables. |
|
||||||
|
| **Traînées** | Sept styles : Comète, Points, Ruban, Arc-en-ciel, Étoiles, Kawaii, Paillettes. |
|
||||||
|
| **Effets de clic** | Anneau simple, ondulation, éclat ou pulsation, avec une couleur différente pour les boutons gauche, du milieu et droit. Peut aussi se déclencher à la demande par un appui bref sur une touche ou un raccourci. |
|
||||||
|
| **Sons de clic** | Un clic synthétisé intégré, ou votre propre fichier WAV. |
|
||||||
|
| **Secouer pour localiser** | Secouez la souris et l'anneau grossit pour retrouver le pointeur. |
|
||||||
|
| **Dessiner à l'écran** | Maintenez une touche et bougez le pointeur pour tracer des traits qui s'effacent. Ou ouvrez le **mode annotation** : stylo, surligneur, texte, pastilles numérotées, gomme, annuler. |
|
||||||
|
| **Visualiseur de frappes** | Six styles (Classique, Verre, Touches, Néon, Dégradé, Minimal). La saisie est regroupée en une pastille de texte ; les raccourcis s'affichent sous la forme `Ctrl + Shift + T`. Une option « seulement les raccourcis » masque la saisie ordinaire. |
|
||||||
|
| **Mode focus** | Assombrit tout sauf la fenêtre active (X11 uniquement pour l'instant). |
|
||||||
|
| **Le reste** | Icône de zone de notification avec bascules et choix de styles, fenêtre de réglages, raccourcis globaux, ligne de commande pour l'automatisation, interface en français et en anglais. Les réglages s'appliquent en direct. |
|
||||||
|
|
||||||
|

|
||||||
|

|
||||||
|

|
||||||
|

|
||||||
|

|
||||||
|
|
||||||
|
### Comparaison avec Mouzz
|
||||||
|
|
||||||
|
Sourizz couvre les fonctions de la version gratuite de Mouzz (projecteur, anneau, traînées, effets et sons de clic, secouer pour localiser, dessin, raccourcis globaux, contrôle depuis la barre de menus / zone de notification) et, parmi celles de sa version Pro, le visualiseur de frappes, le mode focus et les outils d'annotation surligneur, texte et pastilles numérotées.
|
||||||
|
|
||||||
|
Différences et manques :
|
||||||
|
|
||||||
|
- **Touche de dessin maintenue.** Mouzz utilise la touche `Fn`, que les claviers Linux ne signalent généralement pas (c'est le micrologiciel qui la gère). Ici, la valeur par défaut est la touche `Ctrl` de droite, modifiable dans les réglages.
|
||||||
|
- **Non implémentés :** l'enregistreur d'écran, les sous-titres automatiques, la bulle caméra, le zoom en direct / zoom automatique au clic et la loupe. Sous Linux, ce sont d'autres outils (OBS, `wf-recorder`, l'effet Zoom de KDE…).
|
||||||
|
- **Le mode focus** a besoin de la géométrie de la fenêtre active, que seul X11 fournit à tous les programmes.
|
||||||
|
|
||||||
|
## Installation
|
||||||
|
|
||||||
|
Il faut une [chaîne d'outils Rust](https://rustup.rs) stable récente (développé avec la 1.98 ; le projet utilise l'édition 2024). **Aucun paquet `-dev` n'est nécessaire** : la compilation est en Rust pur et charge `libxkbcommon` à l'exécution. La première compilation prend quelques minutes car la fenêtre de réglages embarque egui ; `cargo build --release --no-default-features` compile le démon seul.
|
||||||
|
|
||||||
|
```sh
|
||||||
|
git clone <ce dépôt> sourizz && cd sourizz
|
||||||
|
./install.sh # installe dans ~/.local (--uninstall pour retirer)
|
||||||
|
sourizz doctor # vérifie votre système
|
||||||
|
sourizz # lance le démon (une icône apparaît dans la zone de notification)
|
||||||
|
sourizz autostart enable # facultatif : lancement à l'ouverture de session
|
||||||
|
```
|
||||||
|
|
||||||
|
Prérequis à l'exécution :
|
||||||
|
|
||||||
|
- **X11 :** un gestionnaire de fenêtres avec composition (KWin, Mutter, Xfwm4, Picom…) pour que la surcouche puisse être transparente. Le serveur X doit offrir XInput2, RandR et Shape (tous standards).
|
||||||
|
- **Wayland :** un compositeur qui implémente `wlr-layer-shell` — voir le [tableau de compatibilité](#x11-et-wayland).
|
||||||
|
- **Facultatif :** `pw-play`, `paplay` ou `aplay` pour les sons de clic ; une zone de notification compatible avec le standard StatusNotifierItem (KDE l'est — testé ; GNOME demande l'extension *AppIndicator* ; ailleurs cela dépend de votre tableau de bord — sans zone de notification, tout fonctionne quand même via la ligne de commande, les raccourcis et la fenêtre de réglages) ; OpenGL pour la fenêtre de réglages.
|
||||||
|
|
||||||
|
## Utilisation
|
||||||
|
|
||||||
|
**Icône de notification.** Un clic gauche active/désactive tout ; un clic droit ouvre le menu avec chaque effet, le choix des styles, le mode annotation, les réglages et « Quitter ».
|
||||||
|
|
||||||
|
**Fenêtre de réglages.** `sourizz settings` (ou le menu de l'icône). Les changements sont appliqués immédiatement au démon en cours d'exécution et enregistrés automatiquement.
|
||||||
|
|
||||||
|

|
||||||
|
|
||||||
|
**Raccourcis** (X11 ; modifiables). Sous Wayland, associez plutôt les [commandes ci-dessous](#ligne-de-commande) dans les raccourcis de votre bureau — voir la [configuration Wayland](#configuration-wayland).
|
||||||
|
|
||||||
|
| Par défaut | Action |
|
||||||
|
|---|---|
|
||||||
|
| `Ctrl+Alt+Shift+M` | Interrupteur général |
|
||||||
|
| `Ctrl+Alt+Shift+S` | Projecteur |
|
||||||
|
| `Ctrl+Alt+Shift+R` | Anneau |
|
||||||
|
| `Ctrl+Alt+Shift+T` | Traînée |
|
||||||
|
| `Ctrl+Alt+Shift+C` | Effets de clic |
|
||||||
|
| `Ctrl+Alt+Shift+K` | Frappes |
|
||||||
|
| `Ctrl+Alt+Shift+F` | Mode focus |
|
||||||
|
| `Ctrl+Alt+Shift+A` | Mode annotation |
|
||||||
|
| `Ctrl+Alt+Shift+X` | Effacer les annotations |
|
||||||
|
|
||||||
|
**Dessiner.** Maintenez la touche `Ctrl` de droite et bougez le pointeur : un trait suit, puis s'efface après le relâchement. Pour plus de contrôle, ouvrez le **mode annotation** : une barre d'outils apparaît et la surcouche capture la souris et le clavier.
|
||||||
|
|
||||||
|
En mode annotation : `P` stylo, `H` surligneur, `T` texte, `N` pastille numérotée, `E` gomme, `1`–`6` couleur, `+`/`-` épaisseur, `Ctrl+Z` ou `Retour arrière` annuler, `Suppr` tout effacer, `Échap` quitter. Pendant la saisie d'un texte, `Entrée` valide.
|
||||||
|
|
||||||
|
### Ligne de commande
|
||||||
|
|
||||||
|
Tout ce que fait l'icône est scriptable ; c'est aussi ainsi qu'on associe des raccourcis sous Wayland.
|
||||||
|
|
||||||
|
```sh
|
||||||
|
sourizz toggle spotlight # all, spotlight, ring, trail, clicks, sound, shake,
|
||||||
|
sourizz on trail # annotate, keystrokes, focus
|
||||||
|
sourizz off keystrokes
|
||||||
|
sourizz set ring.size 90 # n'importe quelle option du fichier de configuration
|
||||||
|
sourizz set trail.style stars
|
||||||
|
sourizz annotate # bascule le mode annotation (annotate clear : effacer)
|
||||||
|
sourizz show-click # joue l'effet de clic à l'emplacement du pointeur
|
||||||
|
sourizz status # affiche l'état courant
|
||||||
|
sourizz settings | reload | quit
|
||||||
|
sourizz config # affiche le chemin du fichier de configuration (--defaults : valeurs par défaut)
|
||||||
|
sourizz doctor # diagnostique votre installation
|
||||||
|
```
|
||||||
|
|
||||||
|
### Configuration
|
||||||
|
|
||||||
|
`~/.config/sourizz/config.toml` ; chaque clé est facultative. Le fichier est surveillé : les modifications s'appliquent instantanément. `sourizz config --defaults` affiche la liste complète.
|
||||||
|
|
||||||
|
```toml
|
||||||
|
[ring]
|
||||||
|
style = "neon" # classic | neon
|
||||||
|
size = 64.0
|
||||||
|
color = "#00E5FF"
|
||||||
|
|
||||||
|
[spotlight]
|
||||||
|
enabled = true
|
||||||
|
shape = "circle" # circle | hbar | vbar
|
||||||
|
radius = 200.0
|
||||||
|
opacity = 0.7
|
||||||
|
|
||||||
|
[trail]
|
||||||
|
enabled = true
|
||||||
|
style = "kawaii" # comet | dots | ribbon | rainbow | stars | kawaii | sparkles
|
||||||
|
|
||||||
|
[clicks]
|
||||||
|
style = "ripple_wave" # single_ring | ripple_wave | burst | pulse
|
||||||
|
show_on_clicks = true
|
||||||
|
tap_key = "Control_L" # affiche aussi l'effet quand on tape brièvement cette touche (vide = désactivé)
|
||||||
|
|
||||||
|
[annotate]
|
||||||
|
hold_key = "Control_R" # maintenir + bouger pour dessiner ; vide = désactivé
|
||||||
|
|
||||||
|
[hotkeys]
|
||||||
|
spotlight = "Ctrl+Alt+Shift+S"
|
||||||
|
```
|
||||||
|
|
||||||
|
## X11 et Wayland
|
||||||
|
|
||||||
|
Sourizz a un seul moteur de dessin et deux backends d'affichage ; il choisit le bon automatiquement (`--backend x11|wayland` ou `general.backend` pour en imposer un).
|
||||||
|
|
||||||
|
| Session | Surcouche | Position du pointeur | Clics et touches | Mode focus |
|
||||||
|
|---|---|---|---|---|
|
||||||
|
| **X11** (tout gestionnaire avec composition) | oui | exacte | oui, via XInput2 | oui |
|
||||||
|
| **KDE Plasma, Wayland** | oui | exacte, via un script KWin | demande le groupe `input` | – |
|
||||||
|
| **Hyprland** | oui | exacte, via son socket IPC | demande le groupe `input` | – |
|
||||||
|
| sway, river, niri, labwc, COSMIC… | oui | *estimée* (voir ci-dessous) | demande le groupe `input` | – |
|
||||||
|
| **GNOME, Wayland** | **non** — Mutter n'a pas de layer-shell | – | – | – |
|
||||||
|
|
||||||
|
Sous GNOME, ouvrez une session **« GNOME sur Xorg »**, ou utilisez un autre bureau. (Une extension GNOME Shell pourrait le faire nativement ; elle n'est pas encore écrite.)
|
||||||
|
|
||||||
|
### Choisir le backend
|
||||||
|
|
||||||
|
Par défaut, Sourizz suit votre session : il utilise Wayland si `WAYLAND_DISPLAY` est défini et que `$XDG_SESSION_TYPE` n'est pas `x11`, et X11 sinon. `sourizz doctor` affiche la session et le backend qui sera utilisé (`echo $XDG_SESSION_TYPE` indique aussi dans quelle session vous êtes).
|
||||||
|
|
||||||
|
Pour en imposer un, utilisez `sourizz --backend x11` ou `--backend wayland`, ou écrivez `backend = "x11"` (`"wayland"`, `"auto"`) sous `[general]` dans le fichier de configuration — la fenêtre de réglages l'offre dans l'onglet *Général*. L'option de la ligne de commande l'emporte sur le fichier. Le backend est choisi au démarrage : **relancez le démon** après l'avoir changé. Imposer X11 dans une session Wayland est rarement utile : un programme X11 n'y voit généralement le pointeur que lorsqu'il est au-dessus d'autres fenêtres X11.
|
||||||
|
|
||||||
|
La session elle-même se choisit sur l'écran de connexion (par exemple « Plasma (X11) » ou « Plasma (Wayland) »).
|
||||||
|
|
||||||
|
**Pourquoi Wayland est plus difficile.** Par conception, un programme Wayland ne voit ni le pointeur ni le clavier quand une autre fenêtre les a. Sourizz contourne cela sans aucun assistant privilégié :
|
||||||
|
|
||||||
|
- la surcouche est une surface `wlr-layer-shell` traversable (une région d'entrée vide laisse passer tous les clics) ;
|
||||||
|
- la **position du pointeur** vient du compositeur quand il sait la donner (KWin, Hyprland) ; sinon elle est *estimée* en additionnant le mouvement relatif de la souris, ce qui dérive car le compositeur applique une accélération que Sourizz ne voit pas. Considérez-la comme approximative dans ce cas ;
|
||||||
|
- les **clics et frappes** sont lus dans `/dev/input/event*` ;
|
||||||
|
- la **disposition du clavier** pour les libellés vient de `XKB_DEFAULT_LAYOUT`, de `/etc/default/keyboard` ou du `kxkbrc` de KDE ;
|
||||||
|
- le **mode annotation** prend une vraie capture du pointeur et du clavier : il est donc exact sur tous les compositeurs.
|
||||||
|
|
||||||
|
### Configuration Wayland
|
||||||
|
|
||||||
|
1. Autorisez Sourizz à lire les périphériques d'entrée (nécessaire seulement pour les effets et sons de clic, le visualiseur de frappes, le dessin à touche maintenue et les raccourcis internes ; l'anneau, le projecteur et la traînée fonctionnent sans cela sous KDE et Hyprland) :
|
||||||
|
|
||||||
|
```sh
|
||||||
|
sudo usermod -aG input "$USER" # puis fermez et rouvrez la session
|
||||||
|
```
|
||||||
|
|
||||||
|
> **Note de sécurité.** Les membres de `input` peuvent lire chaque frappe de la machine, donc n'importe quel programme que vous lancez le pourrait. Sourizz ne transforme les événements qu'en effets à l'écran et en raccourcis : il ne stocke rien, n'écrit rien dans des journaux et n'a aucun code réseau — mais vous accordez cette permission à tout votre compte. Si vous préférez ne pas le faire, sautez cette étape : la surcouche et tout ce qui dépend de la position du pointeur fonctionnent quand même sous KDE et Hyprland, et le mode annotation n'en a jamais besoin.
|
||||||
|
|
||||||
|
2. Associez des raccourcis dans votre bureau, car Wayland n'offre pas d'API de raccourcis globaux aux programmes ordinaires (Sourizz reconnaît aussi vos raccourcis configurés à partir du clavier brut quand il y a accès, mais cela ne peut pas *consommer* la frappe) :
|
||||||
|
- **KDE :** Configuration du système → Clavier → Raccourcis → Ajouter une commande → `sourizz toggle spotlight`
|
||||||
|
- **Hyprland :** `bind = SUPER SHIFT, S, exec, sourizz toggle spotlight`
|
||||||
|
- **sway :** `bindsym $mod+Shift+s exec sourizz toggle spotlight`
|
||||||
|
|
||||||
|
3. `sourizz doctor` vous indique ce qui manque.
|
||||||
|
|
||||||
|
Limite connue : sur les sorties HiDPI avec un facteur d'échelle supérieur à 1, la surcouche est dessinée en 1× puis agrandie par le compositeur, ce qui la rend légèrement floue (les positions restent correctes).
|
||||||
|
|
||||||
|
## Ce qui a été testé
|
||||||
|
|
||||||
|
En toute honnêteté sur la vérification :
|
||||||
|
|
||||||
|
- **Automatisé :** 57 tests unitaires (configuration, moteur, suivi des zones à redessiner, invariants de rendu, gestion des touches avec de vraies dispositions AZERTY/QWERTY, traduction evdev, analyse des commandes). En particulier, un test de propriété vérifie que le redessin incrémental est identique au pixel près à un redessin complet pour chaque forme de projecteur, style de traînée et effet de clic.
|
||||||
|
- **X11 :** éprouvé en conditions réelles sous Debian 13, KDE Plasma 6.3, deux écrans — fenêtres de surcouche, traversée des clics, dessin de l'anneau / des clics / des traînées, aucun pixel fantôme après un mouvement rapide, raccourci global, ligne de commande, rechargement de la configuration en direct, menu de l'icône via D-Bus, fenêtre de réglages.
|
||||||
|
- **Wayland :** éprouvé contre un compositeur **KWin 6.3** imbriqué — surcouche layer-shell, rendu de l'anneau / du projecteur / de la barre d'annotation, capture du mode annotation, script KWin de position du pointeur. **Non testé** avec de vrais périphériques souris et clavier (le chemin evdev n'a que des tests unitaires), en vrai HiDPI, ni sous Hyprland, sway, niri ou d'autres compositeurs.
|
||||||
|
|
||||||
|
Considérez la prise en charge de Wayland comme une première version solide qui demande davantage de tests sur le terrain ; les rapports de bogues accompagnés de la sortie de `sourizz -vv` sont bienvenus.
|
||||||
|
|
||||||
|
## Vie privée
|
||||||
|
|
||||||
|
Tout s'exécute en local. Sourizz n'ouvre aucune connexion réseau et n'écrit rien d'autre que son fichier de configuration (et quelques fichiers d'exécution : le socket de contrôle, un petit WAV de clic et le script KWin dans `$XDG_RUNTIME_DIR`).
|
||||||
|
|
||||||
|
Le visualiseur de frappes affiche ce que vous tapez ; il est **désactivé par défaut**. Lors d'un partage d'écran, préférez « seulement les raccourcis » pour ne jamais afficher de mot de passe.
|
||||||
|
|
||||||
|
## Développement
|
||||||
|
|
||||||
|
```sh
|
||||||
|
cargo test # tests unitaires et de propriété
|
||||||
|
cargo run --release -- demo out/ # rend chaque effet en PNG, sans écran
|
||||||
|
cargo run --example x11_probe -- out/ # vérification X11 de bout en bout sur un démon lancé
|
||||||
|
RUST_LOG=sourizz=debug cargo run -- -vv # démon verbeux
|
||||||
|
```
|
||||||
|
|
||||||
|
Organisation : `engine.rs` (état + dessin, sans E/S), `canvas.rs` (tampons par écran limités aux zones abîmées), `x11.rs` / `wayland.rs` (backends), `core.rs` (configuration, commandes, icône, son), `evdev_in.rs` / `wlsrc.rs` / `kwin.rs` / `xkb.rs` (entrées Wayland), `src/bin/settings.rs` (fenêtre de réglages egui). Voir `CLAUDE.md` pour les pièges.
|
||||||
|
|
||||||
|
Pour tester Wayland sans session Wayland, on peut lancer un compositeur privé : `dbus-run-session -- kwin_wayland --virtual --socket sz --width 1280 --height 720` avec son propre `XDG_RUNTIME_DIR`, puis démarrer Sourizz avec `WAYLAND_DISPLAY=sz` et `SOURIZZ_FAKE_POINTER=640,360`.
|
||||||
|
|
||||||
|
## Licence
|
||||||
|
|
||||||
|
Sourizz est un logiciel libre, publié sous la **GNU Affero General Public License, version 3 ou (à votre choix) toute version ultérieure** (`AGPL-3.0-or-later`). Voir [LICENSE](LICENSE) (texte officiel en anglais).
|
||||||
|
|
||||||
|
En bref : vous pouvez l'utiliser, l'étudier, le modifier et le partager, y compris commercialement, tant que tout ce que vous distribuez — ou proposez aux utilisateurs via un réseau — et qui en dérive reste sous la même licence, avec son code source disponible.
|
||||||
|
|
||||||
|
Mouzz est un produit de son propriétaire ; son nom n'est utilisé ici que pour décrire ce qui inspire Sourizz.
|
||||||
@@ -0,0 +1,220 @@
|
|||||||
|
# Sourizz
|
||||||
|
|
||||||
|
**English** · [Français](README.fr.md)
|
||||||
|
|
||||||
|
A cursor highlighter for Linux. Put a **spotlight**, a **ring**, a **trail** or a **click ripple** on your pointer, show your **keystrokes**, and **draw on the screen** — for presentations, tutorials, screencasts, or just to stop losing your cursor on a big monitor. Works on **X11 and Wayland**.
|
||||||
|
|
||||||
|
Sourizz is an independent Linux re-implementation of the idea behind [Mouzz](https://mouzz.dev) for macOS. It shares no code or assets with it and is not affiliated with or endorsed by its author.
|
||||||
|
|
||||||
|

|
||||||
|
|
||||||
|
## Features
|
||||||
|
|
||||||
|
| | |
|
||||||
|
|---|---|
|
||||||
|
| **Spotlight** | Dims everything except a soft-edged circle, horizontal bar or vertical bar around the pointer. Radius, opacity, softness and colour are adjustable. |
|
||||||
|
| **Ring cursor** | A ring that follows the pointer, with a gentle pulse. Classic or Neon style; size, thickness, colour, fill and pulse speed are adjustable. |
|
||||||
|
| **Trails** | Seven styles: Comet, Dots, Ribbon, Rainbow, Stars, Kawaii, Sparkles. |
|
||||||
|
| **Click effects** | Single ring, ripple wave, burst or pulse, with a different colour for left, middle and right button. Can also be triggered on demand by a key tap or a hotkey. |
|
||||||
|
| **Click sounds** | A built-in synthesised click, or your own WAV file. |
|
||||||
|
| **Shake to locate** | Shake the mouse and the ring swells so you can find the pointer. |
|
||||||
|
| **Draw on screen** | Hold a key and move the pointer to draw fading strokes. Or open the **annotation mode**: pen, highlighter, text, numbered callouts, eraser, undo. |
|
||||||
|
| **Keystroke visualiser** | Six styles (Classic, Glass, Keycaps, Neon, Gradient, Minimal). Typing is merged into a running text chip; shortcuts show as `Ctrl + Shift + T`. An "only shortcuts" option hides plain typing. |
|
||||||
|
| **Focus mode** | Dims everything except the active window (X11 only for now). |
|
||||||
|
| **Everything else** | System tray icon with toggles and style pickers, a settings window, global hotkeys, a command line for scripting, English and French UI. Settings apply live. |
|
||||||
|
|
||||||
|

|
||||||
|

|
||||||
|

|
||||||
|

|
||||||
|

|
||||||
|
|
||||||
|
### Compared with Mouzz
|
||||||
|
|
||||||
|
Sourizz covers Mouzz's free feature set (spotlight, ring, trails, click effects and sounds, shake-to-locate, drawing, global hotkeys, menu-bar/tray control) and, from its Pro tier, the keystroke visualiser, focus mode, and the highlighter, text and numbered-callout annotation tools.
|
||||||
|
|
||||||
|
Differences and gaps:
|
||||||
|
|
||||||
|
- **Hold-to-draw key.** Mouzz uses the `Fn` key, which Linux keyboards usually do not report at all (the firmware handles it). The default here is the right `Ctrl` key, configurable in the settings.
|
||||||
|
- **Not implemented:** the screen recorder, automatic captions, camera bubble, live zoom / auto-zoom on click and the loupe magnifier. They are separate products on Linux (OBS, `wf-recorder`, KDE's Zoom effect…).
|
||||||
|
- **Focus mode** needs the active window's geometry, which only X11 provides to every program.
|
||||||
|
|
||||||
|
## Install
|
||||||
|
|
||||||
|
You need a recent stable [Rust toolchain](https://rustup.rs) (developed with 1.98; the crate uses edition 2024). **No `-dev` packages are required**: the build is pure Rust and loads `libxkbcommon` at run time. The first build takes a few minutes because the settings window pulls in egui; `cargo build --release --no-default-features` builds the daemon alone.
|
||||||
|
|
||||||
|
```sh
|
||||||
|
git clone <this repository> sourizz && cd sourizz
|
||||||
|
./install.sh # installs into ~/.local (add --uninstall to remove)
|
||||||
|
sourizz doctor # checks your system
|
||||||
|
sourizz # start the daemon (a tray icon appears)
|
||||||
|
sourizz autostart enable # optional: launch at login
|
||||||
|
```
|
||||||
|
|
||||||
|
Run-time requirements:
|
||||||
|
|
||||||
|
- **X11:** a compositing window manager (KWin, Mutter, Xfwm4, Picom…) so the overlay can be transparent. The X server needs XInput2, RandR and Shape (all standard).
|
||||||
|
- **Wayland:** a compositor that implements `wlr-layer-shell` — see the [compatibility table](#x11-and-wayland).
|
||||||
|
- **Optional:** `pw-play`, `paplay` or `aplay` for click sounds; a system tray that understands the StatusNotifierItem standard (KDE does — tested; GNOME needs the *AppIndicator* extension; elsewhere it depends on your panel — without a tray everything still works through the command line, hotkeys and the settings window); OpenGL for the settings window.
|
||||||
|
|
||||||
|
## Using it
|
||||||
|
|
||||||
|
**Tray icon.** Left click toggles everything; right click opens the menu with every effect, style pickers, annotation mode, settings and quit.
|
||||||
|
|
||||||
|
**Settings window.** `sourizz settings` (or the tray menu). Changes are applied to the running daemon immediately and saved automatically.
|
||||||
|
|
||||||
|

|
||||||
|
|
||||||
|
**Hotkeys** (X11; configurable). On Wayland, bind the [commands below](#command-line) in your desktop's shortcut settings instead — see [Wayland setup](#wayland-setup).
|
||||||
|
|
||||||
|
| Default | Action |
|
||||||
|
|---|---|
|
||||||
|
| `Ctrl+Alt+Shift+M` | Master switch |
|
||||||
|
| `Ctrl+Alt+Shift+S` | Spotlight |
|
||||||
|
| `Ctrl+Alt+Shift+R` | Ring |
|
||||||
|
| `Ctrl+Alt+Shift+T` | Trail |
|
||||||
|
| `Ctrl+Alt+Shift+C` | Click effects |
|
||||||
|
| `Ctrl+Alt+Shift+K` | Keystrokes |
|
||||||
|
| `Ctrl+Alt+Shift+F` | Focus mode |
|
||||||
|
| `Ctrl+Alt+Shift+A` | Annotation mode |
|
||||||
|
| `Ctrl+Alt+Shift+X` | Clear annotations |
|
||||||
|
|
||||||
|
**Drawing.** Hold the right `Ctrl` key and move the pointer: a stroke follows and fades away after you release. For more control open the **annotation mode**: a toolbar appears and the overlay captures the mouse and keyboard.
|
||||||
|
|
||||||
|
In annotation mode: `P` pen, `H` highlighter, `T` text, `N` numbered callout, `E` eraser, `1`–`6` colour, `+`/`-` width, `Ctrl+Z` or `Backspace` undo, `Delete` clear, `Esc` leave. While typing text, `Enter` validates.
|
||||||
|
|
||||||
|
### Command line
|
||||||
|
|
||||||
|
Everything the tray does is scriptable; this is also how you bind shortcuts on Wayland.
|
||||||
|
|
||||||
|
```sh
|
||||||
|
sourizz toggle spotlight # all, spotlight, ring, trail, clicks, sound, shake,
|
||||||
|
sourizz on trail # annotate, keystrokes, focus
|
||||||
|
sourizz off keystrokes
|
||||||
|
sourizz set ring.size 90 # any option from the config file
|
||||||
|
sourizz set trail.style stars
|
||||||
|
sourizz annotate # toggle annotation mode (annotate clear: erase)
|
||||||
|
sourizz show-click # play the click effect at the pointer
|
||||||
|
sourizz status # print the current state
|
||||||
|
sourizz settings | reload | quit
|
||||||
|
sourizz config # print the config file path (--defaults: the defaults)
|
||||||
|
sourizz doctor # diagnose your setup
|
||||||
|
```
|
||||||
|
|
||||||
|
### Configuration
|
||||||
|
|
||||||
|
`~/.config/sourizz/config.toml`; every key is optional. The file is watched, so edits apply instantly. `sourizz config --defaults` prints the complete list.
|
||||||
|
|
||||||
|
```toml
|
||||||
|
[ring]
|
||||||
|
style = "neon" # classic | neon
|
||||||
|
size = 64.0
|
||||||
|
color = "#00E5FF"
|
||||||
|
|
||||||
|
[spotlight]
|
||||||
|
enabled = true
|
||||||
|
shape = "circle" # circle | hbar | vbar
|
||||||
|
radius = 200.0
|
||||||
|
opacity = 0.7
|
||||||
|
|
||||||
|
[trail]
|
||||||
|
enabled = true
|
||||||
|
style = "kawaii" # comet | dots | ribbon | rainbow | stars | kawaii | sparkles
|
||||||
|
|
||||||
|
[clicks]
|
||||||
|
style = "ripple_wave" # single_ring | ripple_wave | burst | pulse
|
||||||
|
show_on_clicks = true
|
||||||
|
tap_key = "Control_L" # also show the effect when this key is tapped (empty = off)
|
||||||
|
|
||||||
|
[annotate]
|
||||||
|
hold_key = "Control_R" # hold + move to draw; empty = off
|
||||||
|
|
||||||
|
[hotkeys]
|
||||||
|
spotlight = "Ctrl+Alt+Shift+S"
|
||||||
|
```
|
||||||
|
|
||||||
|
## X11 and Wayland
|
||||||
|
|
||||||
|
Sourizz has one drawing engine and two display backends; it picks the right one automatically (`--backend x11|wayland` or `general.backend` to force one).
|
||||||
|
|
||||||
|
| Session | Overlay | Pointer position | Clicks and keys | Focus mode |
|
||||||
|
|---|---|---|---|---|
|
||||||
|
| **X11** (any compositing WM) | yes | exact | yes, via XInput2 | yes |
|
||||||
|
| **KDE Plasma, Wayland** | yes | exact, via a KWin script | needs the `input` group | – |
|
||||||
|
| **Hyprland** | yes | exact, via its IPC socket | needs the `input` group | – |
|
||||||
|
| sway, river, niri, labwc, COSMIC… | yes | *estimated* (see below) | needs the `input` group | – |
|
||||||
|
| **GNOME, Wayland** | **no** — Mutter has no layer-shell | – | – | – |
|
||||||
|
|
||||||
|
On GNOME, log in with a **"GNOME on Xorg"** session, or use another desktop. (A GNOME Shell extension could do it natively; that is not written yet.)
|
||||||
|
|
||||||
|
### Choosing the backend
|
||||||
|
|
||||||
|
By default Sourizz follows your session: it uses Wayland when `WAYLAND_DISPLAY` is set and `$XDG_SESSION_TYPE` is not `x11`, and X11 otherwise. `sourizz doctor` prints the session and the backend that will be used (`echo $XDG_SESSION_TYPE` also tells you which session you are in).
|
||||||
|
|
||||||
|
To force one, use `sourizz --backend x11` or `--backend wayland`, or set `backend = "x11"` (`"wayland"`, `"auto"`) under `[general]` in the config file — the settings window has it in the *General* tab. The command-line flag wins over the file. The backend is chosen at start-up, so **restart the daemon** after changing it. Forcing X11 inside a Wayland session is rarely useful: an X11 program there generally only sees the pointer while it is over other X11 windows.
|
||||||
|
|
||||||
|
The session itself is chosen at the login screen (for example "Plasma (X11)" or "Plasma (Wayland)").
|
||||||
|
|
||||||
|
**Why Wayland is harder.** By design a Wayland program cannot see the pointer or the keyboard while another window has them. Sourizz works around this without any privileged helper:
|
||||||
|
|
||||||
|
- the overlay is a click-through `wlr-layer-shell` surface (an empty input region lets every click pass);
|
||||||
|
- the **pointer position** comes from the compositor when it offers a way (KWin, Hyprland); otherwise it is *estimated* by adding up relative mouse motion, which drifts because the compositor applies pointer acceleration Sourizz cannot see. Treat it as approximate there;
|
||||||
|
- **clicks and keystrokes** are read from `/dev/input/event*`;
|
||||||
|
- the **keyboard layout** for key labels is read from `XKB_DEFAULT_LAYOUT`, `/etc/default/keyboard` or KDE's `kxkbrc`;
|
||||||
|
- **annotation mode** takes a real pointer and keyboard grab, so it is exact on every compositor.
|
||||||
|
|
||||||
|
### Wayland setup
|
||||||
|
|
||||||
|
1. Allow Sourizz to read input devices (only needed for click effects, click sounds, the keystroke visualiser, hold-to-draw and in-app hotkeys; the ring, spotlight and trail work without it on KDE and Hyprland):
|
||||||
|
|
||||||
|
```sh
|
||||||
|
sudo usermod -aG input "$USER" # then log out and back in
|
||||||
|
```
|
||||||
|
|
||||||
|
> **Security note.** Members of `input` can read every keystroke on the machine, so any program you run could. Sourizz only turns events into on-screen effects and hotkey matches — it stores nothing, logs nothing and has no network code — but you are granting the permission to your whole user account. If you would rather not, skip this step: the overlay and everything driven by the pointer position still works on KDE and Hyprland, and annotation mode never needs it.
|
||||||
|
|
||||||
|
2. Bind shortcuts in your desktop, because Wayland has no global-hotkey API for plain programs (Sourizz also matches your configured hotkeys from the raw keyboard when it has access, but that cannot *consume* the key press):
|
||||||
|
- **KDE:** System Settings → Keyboard → Shortcuts → Add Command → `sourizz toggle spotlight`
|
||||||
|
- **Hyprland:** `bind = SUPER SHIFT, S, exec, sourizz toggle spotlight`
|
||||||
|
- **sway:** `bindsym $mod+Shift+s exec sourizz toggle spotlight`
|
||||||
|
|
||||||
|
3. `sourizz doctor` tells you what is missing.
|
||||||
|
|
||||||
|
Known limitation: on HiDPI outputs with a scale above 1 the overlay is drawn at 1× and upscaled by the compositor, so it looks slightly soft (positions are correct).
|
||||||
|
|
||||||
|
## What was tested
|
||||||
|
|
||||||
|
Being honest about verification:
|
||||||
|
|
||||||
|
- **Automated:** 57 unit tests (config, engine, damage tracking, rendering invariants, key handling with real AZERTY/QWERTY layouts, evdev translation, IPC parsing). Notably, a property test checks that incremental repainting is pixel-identical to a full repaint for every spotlight shape, trail style and click effect.
|
||||||
|
- **X11:** exercised live on Debian 13, KDE Plasma 6.3, two monitors — overlay windows, click-through, ring/click/trail drawing, no ghost pixels after fast motion, global hotkey, CLI, live config reload, tray menu over D-Bus, settings window.
|
||||||
|
- **Wayland:** exercised against a nested **KWin 6.3** compositor — layer-shell overlay, ring/spotlight/annotation toolbar rendering, annotation mode capture, the KWin pointer script. **Not tested** with real mouse and keyboard devices (the evdev path has unit tests only), on real HiDPI, or on Hyprland, sway, niri or other compositors.
|
||||||
|
|
||||||
|
Treat Wayland support as a solid first version that needs more field testing; bug reports with `sourizz -vv` output are welcome.
|
||||||
|
|
||||||
|
## Privacy
|
||||||
|
|
||||||
|
Everything runs locally. Sourizz makes no network connections and writes nothing but its config file (and a few runtime files: the control socket, a small click WAV and the KWin script under `$XDG_RUNTIME_DIR`).
|
||||||
|
|
||||||
|
The keystroke visualiser shows what you type; it is **off by default**. When screen-sharing, prefer "only shortcuts" so passwords are never displayed.
|
||||||
|
|
||||||
|
## Development
|
||||||
|
|
||||||
|
```sh
|
||||||
|
cargo test # unit + property tests
|
||||||
|
cargo run --release -- demo out/ # render every effect to PNGs, no display needed
|
||||||
|
cargo run --example x11_probe -- out/ # end-to-end X11 check against a running daemon
|
||||||
|
RUST_LOG=sourizz=debug cargo run -- -vv # verbose daemon
|
||||||
|
```
|
||||||
|
|
||||||
|
Layout: `engine.rs` (state + drawing, no I/O), `canvas.rs` (damage-limited per-monitor buffers), `x11.rs` / `wayland.rs` (backends), `core.rs` (config, commands, tray, sound), `evdev_in.rs` / `wlsrc.rs` / `kwin.rs` / `xkb.rs` (Wayland input), `src/bin/settings.rs` (egui settings window). See `CLAUDE.md` for the gotchas.
|
||||||
|
|
||||||
|
To test Wayland without a Wayland session you can run a private compositor: `dbus-run-session -- kwin_wayland --virtual --socket sz --width 1280 --height 720` with its own `XDG_RUNTIME_DIR`, then start Sourizz with `WAYLAND_DISPLAY=sz` and `SOURIZZ_FAKE_POINTER=640,360`.
|
||||||
|
|
||||||
|
## License
|
||||||
|
|
||||||
|
Sourizz is free software, released under the **GNU Affero General Public License, version 3 or (at your option) any later version** (`AGPL-3.0-or-later`). See [LICENSE](LICENSE).
|
||||||
|
|
||||||
|
In short: you may use, study, modify and share it, including commercially, as long as anything you distribute — or offer to users over a network — built on it stays under the same licence with its source available.
|
||||||
|
|
||||||
|
Mouzz is a product of its respective owner; the name is used here only to describe what Sourizz is inspired by.
|
||||||
|
After Width: | Height: | Size: 24 KiB |
|
After Width: | Height: | Size: 26 KiB |
|
After Width: | Height: | Size: 35 KiB |
|
After Width: | Height: | Size: 5.3 KiB |
|
After Width: | Height: | Size: 53 KiB |
|
After Width: | Height: | Size: 54 KiB |
|
After Width: | Height: | Size: 49 KiB |
@@ -0,0 +1,39 @@
|
|||||||
|
//! Click inside a window of ours, given its X id and a position relative to its client area:
|
||||||
|
//! click_at <window-id-hex> <x> <y>
|
||||||
|
//! It first checks the pointer really ends up over that window (so a stray click can never hit
|
||||||
|
//! another application) and refuses otherwise.
|
||||||
|
use x11rb::connection::Connection;
|
||||||
|
use x11rb::protocol::xproto::{self, ConnectionExt as _};
|
||||||
|
use x11rb::protocol::xtest::ConnectionExt as _;
|
||||||
|
|
||||||
|
fn main() {
|
||||||
|
let a: Vec<String> = std::env::args().collect();
|
||||||
|
let win = u32::from_str_radix(a[1].trim_start_matches("0x"), 16).expect("window id");
|
||||||
|
let (rx, ry): (i16, i16) = (a[2].parse().unwrap(), a[3].parse().unwrap());
|
||||||
|
let (conn, sn) = x11rb::connect(None).unwrap();
|
||||||
|
let root = conn.setup().roots[sn].root;
|
||||||
|
let tr = conn.translate_coordinates(win, root, rx, ry).unwrap().reply().unwrap();
|
||||||
|
// The window manager wraps our window in frames; the one directly under the root is what
|
||||||
|
// `query_pointer().child` reports.
|
||||||
|
let mut top = win;
|
||||||
|
loop {
|
||||||
|
let parent = conn.query_tree(top).unwrap().reply().unwrap().parent;
|
||||||
|
if parent == root || parent == 0 {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
top = parent;
|
||||||
|
}
|
||||||
|
conn.xtest_fake_input(xproto::MOTION_NOTIFY_EVENT, 0, 0, root, tr.dst_x, tr.dst_y, 0).unwrap();
|
||||||
|
conn.flush().unwrap();
|
||||||
|
std::thread::sleep(std::time::Duration::from_millis(120));
|
||||||
|
let q = conn.query_pointer(root).unwrap().reply().unwrap();
|
||||||
|
if q.child != top {
|
||||||
|
eprintln!("REFUSED: pointer is over {:#x}, not our window {:#x} (top-level {:#x})", q.child, win, top);
|
||||||
|
std::process::exit(2);
|
||||||
|
}
|
||||||
|
for t in [xproto::BUTTON_PRESS_EVENT, xproto::BUTTON_RELEASE_EVENT] {
|
||||||
|
conn.xtest_fake_input(t, 1, 0, root, 0, 0, 0).unwrap();
|
||||||
|
conn.flush().unwrap();
|
||||||
|
std::thread::sleep(std::time::Duration::from_millis(60));
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,31 @@
|
|||||||
|
//! Press a chord through XTEST: `fake_keys Control_L Alt_L Shift_L F9` (last key is the main one).
|
||||||
|
use x11rb::connection::Connection;
|
||||||
|
use x11rb::protocol::xproto::{self, ConnectionExt as _};
|
||||||
|
use x11rb::protocol::xtest::ConnectionExt as _;
|
||||||
|
|
||||||
|
fn main() {
|
||||||
|
let names: Vec<String> = std::env::args().skip(1).collect();
|
||||||
|
let (conn, sn) = x11rb::connect(None).unwrap();
|
||||||
|
let root = conn.setup().roots[sn].root;
|
||||||
|
let (min, max) = (conn.setup().min_keycode, conn.setup().max_keycode);
|
||||||
|
let map = conn.get_keyboard_mapping(min, max - min + 1).unwrap().reply().unwrap();
|
||||||
|
let per = map.keysyms_per_keycode as usize;
|
||||||
|
let code = |name: &str| -> u8 {
|
||||||
|
let sym = sourizz::keysym::from_name(name).unwrap_or_else(|| panic!("unknown key {name}"));
|
||||||
|
(0..(map.keysyms.len() / per))
|
||||||
|
.find(|r| map.keysyms[r * per] == sym)
|
||||||
|
.map(|r| min + r as u8)
|
||||||
|
.unwrap_or_else(|| panic!("{name} not on keyboard"))
|
||||||
|
};
|
||||||
|
let codes: Vec<u8> = names.iter().map(|n| code(n)).collect();
|
||||||
|
for c in &codes {
|
||||||
|
conn.xtest_fake_input(xproto::KEY_PRESS_EVENT, *c, 0, root, 0, 0, 0).unwrap();
|
||||||
|
conn.flush().unwrap();
|
||||||
|
std::thread::sleep(std::time::Duration::from_millis(30));
|
||||||
|
}
|
||||||
|
for c in codes.iter().rev() {
|
||||||
|
conn.xtest_fake_input(xproto::KEY_RELEASE_EVENT, *c, 0, root, 0, 0, 0).unwrap();
|
||||||
|
conn.flush().unwrap();
|
||||||
|
std::thread::sleep(std::time::Duration::from_millis(30));
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,17 @@
|
|||||||
|
//! Move the pointer in circles for N seconds (default 4) to generate load.
|
||||||
|
use x11rb::connection::Connection;
|
||||||
|
use x11rb::protocol::xproto::{self};
|
||||||
|
use x11rb::protocol::xtest::ConnectionExt as _;
|
||||||
|
fn main() {
|
||||||
|
let secs: f64 = std::env::args().nth(1).and_then(|s| s.parse().ok()).unwrap_or(4.0);
|
||||||
|
let (conn, sn) = x11rb::connect(None).unwrap();
|
||||||
|
let root = conn.setup().roots[sn].root;
|
||||||
|
let t0 = std::time::Instant::now();
|
||||||
|
while t0.elapsed().as_secs_f64() < secs {
|
||||||
|
let t = t0.elapsed().as_secs_f64() * 3.0;
|
||||||
|
let (x, y) = (960.0 + 400.0 * t.cos(), 540.0 + 250.0 * (t * 1.3).sin());
|
||||||
|
conn.xtest_fake_input(xproto::MOTION_NOTIFY_EVENT, 0, 0, root, x as i16, y as i16, 0).unwrap();
|
||||||
|
conn.flush().unwrap();
|
||||||
|
std::thread::sleep(std::time::Duration::from_millis(8));
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,205 @@
|
|||||||
|
//! End-to-end check of the X11 backend against a running `sourizz` daemon.
|
||||||
|
//!
|
||||||
|
//! It only ever acts on its own test window: the pointer is moved over it and the
|
||||||
|
//! click lands on it (which also proves the overlay is click-through).
|
||||||
|
//!
|
||||||
|
//! cargo run --example x11_probe -- /path/to/output-dir
|
||||||
|
|
||||||
|
#![allow(clippy::chunks_exact_to_as_chunks)]
|
||||||
|
|
||||||
|
use std::time::Duration;
|
||||||
|
use x11rb::connection::Connection;
|
||||||
|
use x11rb::protocol::Event;
|
||||||
|
use x11rb::protocol::shape::{self, ConnectionExt as _};
|
||||||
|
use x11rb::protocol::xproto::{self, ConnectionExt as _};
|
||||||
|
use x11rb::protocol::xtest::ConnectionExt as _;
|
||||||
|
|
||||||
|
type R<T> = Result<T, Box<dyn std::error::Error>>;
|
||||||
|
|
||||||
|
struct Overlay {
|
||||||
|
id: u32,
|
||||||
|
x: i16,
|
||||||
|
y: i16,
|
||||||
|
w: u16,
|
||||||
|
h: u16,
|
||||||
|
}
|
||||||
|
|
||||||
|
fn wait(ms: u64) {
|
||||||
|
std::thread::sleep(Duration::from_millis(ms));
|
||||||
|
}
|
||||||
|
|
||||||
|
fn main() -> R<()> {
|
||||||
|
let out = std::env::args().nth(1).expect("usage: x11_probe <outdir>");
|
||||||
|
std::fs::create_dir_all(&out)?;
|
||||||
|
let (conn, sn) = x11rb::connect(None)?;
|
||||||
|
let root = conn.setup().roots[sn].root;
|
||||||
|
let net_wm_name = conn.intern_atom(false, b"_NET_WM_NAME")?.reply()?.atom;
|
||||||
|
let mut failures = 0;
|
||||||
|
let mut check = |name: &str, ok: bool, detail: String| {
|
||||||
|
println!(
|
||||||
|
"[{}] {name}{}",
|
||||||
|
if ok { " ok " } else { "FAIL" },
|
||||||
|
if detail.is_empty() { String::new() } else { format!(" ({detail})") }
|
||||||
|
);
|
||||||
|
if !ok {
|
||||||
|
failures += 1;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
// 1. The overlay windows exist and look right.
|
||||||
|
let mut overlays = Vec::new();
|
||||||
|
for child in conn.query_tree(root)?.reply()?.children {
|
||||||
|
let name = conn.get_property(false, child, net_wm_name, xproto::AtomEnum::ANY, 0, 64)?.reply()?.value;
|
||||||
|
if name == b"sourizz-overlay" {
|
||||||
|
let g = conn.get_geometry(child)?.reply()?;
|
||||||
|
let a = conn.get_window_attributes(child)?.reply()?;
|
||||||
|
let rects = conn.shape_get_rectangles(child, shape::SK::INPUT)?.reply()?.rectangles;
|
||||||
|
check(
|
||||||
|
&format!("overlay {child:#x} is override-redirect, depth 32, mapped"),
|
||||||
|
a.override_redirect && g.depth == 32 && a.map_state == xproto::MapState::VIEWABLE,
|
||||||
|
format!("{}x{}+{}+{} depth {}", g.width, g.height, g.x, g.y, g.depth),
|
||||||
|
);
|
||||||
|
check(&format!("overlay {child:#x} input region is empty (click-through)"), rects.is_empty(), format!("{} rects", rects.len()));
|
||||||
|
overlays.push(Overlay { id: child, x: g.x, y: g.y, w: g.width, h: g.height });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
check("at least one overlay window", !overlays.is_empty(), String::new());
|
||||||
|
let Some(ov) = overlays.first() else { std::process::exit(1) };
|
||||||
|
|
||||||
|
// 2. A test window of our own, placed on the first overlay's monitor.
|
||||||
|
let (tx, ty, tw, th) = (ov.x + 400, ov.y + 400, 240u16, 140u16);
|
||||||
|
let win = conn.generate_id()?;
|
||||||
|
conn.create_window(
|
||||||
|
x11rb::COPY_DEPTH_FROM_PARENT,
|
||||||
|
win,
|
||||||
|
root,
|
||||||
|
tx,
|
||||||
|
ty,
|
||||||
|
tw,
|
||||||
|
th,
|
||||||
|
0,
|
||||||
|
xproto::WindowClass::INPUT_OUTPUT,
|
||||||
|
0,
|
||||||
|
&xproto::CreateWindowAux::new()
|
||||||
|
.override_redirect(1)
|
||||||
|
.background_pixel(0x00305080)
|
||||||
|
.event_mask(xproto::EventMask::BUTTON_PRESS | xproto::EventMask::BUTTON_RELEASE),
|
||||||
|
)?;
|
||||||
|
conn.map_window(win)?;
|
||||||
|
conn.flush()?;
|
||||||
|
wait(200);
|
||||||
|
|
||||||
|
let grab = |ov: &Overlay| -> R<Vec<u8>> {
|
||||||
|
let img = conn.get_image(xproto::ImageFormat::Z_PIXMAP, ov.id, 0, 0, ov.w, ov.h, !0)?.reply()?;
|
||||||
|
Ok(img.data)
|
||||||
|
};
|
||||||
|
let alpha_at = |data: &[u8], ov: &Overlay, x: i32, y: i32| -> u8 {
|
||||||
|
let (lx, ly) = (x - ov.x as i32, y - ov.y as i32);
|
||||||
|
data[((ly as usize * ov.w as usize) + lx as usize) * 4 + 3]
|
||||||
|
};
|
||||||
|
let count = |data: &[u8]| data.chunks(4).filter(|p| p[3] > 0).count();
|
||||||
|
// Move the pointer and make sure it arrived (a real mouse movement could otherwise
|
||||||
|
// fight with the synthetic one and make the checks below meaningless).
|
||||||
|
let warp = |x: i16, y: i16| -> R<()> {
|
||||||
|
for _ in 0..25 {
|
||||||
|
conn.xtest_fake_input(xproto::MOTION_NOTIFY_EVENT, 0, 0, root, x, y, 0)?;
|
||||||
|
conn.flush()?;
|
||||||
|
wait(40);
|
||||||
|
let q = conn.query_pointer(root)?.reply()?;
|
||||||
|
if q.root_x == x && q.root_y == y {
|
||||||
|
return Ok(());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Err("pointer would not stay where the probe put it (is the mouse being moved?)".into())
|
||||||
|
};
|
||||||
|
|
||||||
|
// 3. Pointer at the test window centre: the ring must appear around it.
|
||||||
|
let (cx, cy) = (tx as i32 + 120, ty as i32 + 70);
|
||||||
|
warp(cx as i16, cy as i16)?;
|
||||||
|
wait(250);
|
||||||
|
let before = grab(ov)?;
|
||||||
|
let ring_px = count(&before);
|
||||||
|
// Default ring: 56px diameter, so the stroke is at radius ~28 from the pointer.
|
||||||
|
let on_ring = alpha_at(&before, ov, cx + 28, cy);
|
||||||
|
let centre = alpha_at(&before, ov, cx, cy);
|
||||||
|
let far = alpha_at(&before, ov, cx + 150, cy);
|
||||||
|
check(
|
||||||
|
"ring is drawn around the pointer",
|
||||||
|
on_ring > 150 && centre == 0 && far == 0,
|
||||||
|
format!("ring a={on_ring}, centre a={centre}, far a={far}, {ring_px} px"),
|
||||||
|
);
|
||||||
|
save_png(&format!("{out}/overlay_ring.png"), ov, &before)?;
|
||||||
|
|
||||||
|
// 4. Click-through: the pointer's window is ours, and a click reaches it.
|
||||||
|
let q = conn.query_pointer(root)?.reply()?;
|
||||||
|
check("pointer is over the test window, not the overlay", q.child == win, format!("child={:#x}", q.child));
|
||||||
|
conn.xtest_fake_input(xproto::BUTTON_PRESS_EVENT, 1, 0, root, 0, 0, 0)?;
|
||||||
|
conn.flush()?;
|
||||||
|
wait(120);
|
||||||
|
let during = grab(ov)?;
|
||||||
|
conn.xtest_fake_input(xproto::BUTTON_RELEASE_EVENT, 1, 0, root, 0, 0, 0)?;
|
||||||
|
conn.flush()?;
|
||||||
|
wait(60);
|
||||||
|
let mut got_click = false;
|
||||||
|
while let Some(ev) = conn.poll_for_event()? {
|
||||||
|
if matches!(ev, Event::ButtonPress(_)) {
|
||||||
|
got_click = true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
check("click reached the window beneath the overlay", got_click, String::new());
|
||||||
|
check("click effect adds pixels", count(&during) > ring_px + 20, format!("{} -> {}", ring_px, count(&during)));
|
||||||
|
save_png(&format!("{out}/overlay_click.png"), ov, &during)?;
|
||||||
|
|
||||||
|
// 5. The ripple finishes and disappears.
|
||||||
|
wait(900);
|
||||||
|
let after = grab(ov)?;
|
||||||
|
check("click effect is gone afterwards", count(&after).abs_diff(ring_px) < 40, format!("{} px vs {}", count(&after), ring_px));
|
||||||
|
|
||||||
|
// 6. Moving the pointer moves the ring and erases the old one.
|
||||||
|
let (nx, ny) = (cx + 60, cy + 30);
|
||||||
|
warp(nx as i16, ny as i16)?;
|
||||||
|
wait(250);
|
||||||
|
let moved = grab(ov)?;
|
||||||
|
check("ring followed the pointer", alpha_at(&moved, ov, nx + 28, ny) > 150, String::new());
|
||||||
|
check("old ring position was erased", alpha_at(&moved, ov, cx + 28, cy) == 0 && alpha_at(&moved, ov, cx - 28, cy) == 0, String::new());
|
||||||
|
|
||||||
|
// 7. Fast sweep: no stale ring pixels left along the path.
|
||||||
|
for i in 0..40 {
|
||||||
|
warp((cx + 40 + i * 5) as i16, (cy - 40 + i) as i16)?;
|
||||||
|
wait(8);
|
||||||
|
}
|
||||||
|
let (ex, ey) = (cx + 40 + 39 * 5, cy - 40 + 39);
|
||||||
|
wait(300);
|
||||||
|
let swept = grab(ov)?;
|
||||||
|
let ring_after = count(&swept);
|
||||||
|
check(
|
||||||
|
"no ghost pixels after a fast sweep",
|
||||||
|
ring_after.abs_diff(ring_px) < 60,
|
||||||
|
format!("{ring_after} px vs {ring_px} for a single ring"),
|
||||||
|
);
|
||||||
|
check("ring is at the sweep end", alpha_at(&swept, ov, ex + 28, ey) > 150, String::new());
|
||||||
|
|
||||||
|
conn.destroy_window(win)?;
|
||||||
|
conn.flush()?;
|
||||||
|
if failures > 0 {
|
||||||
|
eprintln!("{failures} check(s) failed");
|
||||||
|
std::process::exit(1);
|
||||||
|
}
|
||||||
|
println!("all checks passed");
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn save_png(path: &str, ov: &Overlay, bgra: &[u8]) -> R<()> {
|
||||||
|
let mut pm = tiny_skia::Pixmap::new(ov.w as u32, ov.h as u32).ok_or("pixmap")?;
|
||||||
|
for (d, s) in pm.data_mut().chunks_exact_mut(4).zip(bgra.chunks_exact(4)) {
|
||||||
|
d.copy_from_slice(&[s[2], s[1], s[0], s[3]]);
|
||||||
|
}
|
||||||
|
// Crop around the pointer area so the image stays small.
|
||||||
|
let (x, y, w, h) = (300u32, 300u32, 520u32, 340u32);
|
||||||
|
let crop = pm.clone_rect(tiny_skia::IntRect::from_xywh(x as i32, y as i32, w, h).ok_or("rect")?).ok_or("crop")?;
|
||||||
|
let mut bg = tiny_skia::Pixmap::new(w, h).ok_or("bg")?;
|
||||||
|
bg.fill(tiny_skia::Color::from_rgba8(70, 80, 100, 255));
|
||||||
|
bg.draw_pixmap(0, 0, crop.as_ref(), &tiny_skia::PixmapPaint::default(), tiny_skia::Transform::identity(), None);
|
||||||
|
bg.save_png(path)?;
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
@@ -0,0 +1,41 @@
|
|||||||
|
#!/usr/bin/env bash
|
||||||
|
# Install Sourizz for the current user (no root needed).
|
||||||
|
# ./install.sh build and install into ~/.local
|
||||||
|
# PREFIX=/usr/local ./install.sh (run as root) system-wide
|
||||||
|
# ./install.sh --uninstall
|
||||||
|
set -euo pipefail
|
||||||
|
|
||||||
|
PREFIX="${PREFIX:-$HOME/.local}"
|
||||||
|
BIN="$PREFIX/bin"
|
||||||
|
APPS="$PREFIX/share/applications"
|
||||||
|
ICONS="$PREFIX/share/icons/hicolor/scalable/apps"
|
||||||
|
DOCS="$PREFIX/share/licenses/sourizz"
|
||||||
|
cd "$(dirname "$0")"
|
||||||
|
|
||||||
|
if [[ "${1:-}" == "--uninstall" ]]; then
|
||||||
|
rm -fv "$BIN/sourizz" "$BIN/sourizz-settings" "$APPS/sourizz.desktop" "$APPS/sourizz-settings.desktop" "$ICONS/sourizz.svg" "$DOCS/LICENSE"
|
||||||
|
rmdir "$DOCS" 2>/dev/null || true
|
||||||
|
rm -fv "${XDG_CONFIG_HOME:-$HOME/.config}/autostart/sourizz.desktop"
|
||||||
|
echo "Uninstalled. Your settings in ${XDG_CONFIG_HOME:-$HOME/.config}/sourizz were kept."
|
||||||
|
exit 0
|
||||||
|
fi
|
||||||
|
|
||||||
|
command -v cargo >/dev/null || { echo "Rust is required: https://rustup.rs" >&2; exit 1; }
|
||||||
|
|
||||||
|
cargo build --release
|
||||||
|
install -Dm755 target/release/sourizz "$BIN/sourizz"
|
||||||
|
install -Dm755 target/release/sourizz-settings "$BIN/sourizz-settings"
|
||||||
|
install -Dm644 packaging/sourizz.svg "$ICONS/sourizz.svg"
|
||||||
|
install -Dm644 LICENSE "$DOCS/LICENSE"
|
||||||
|
# Use absolute paths so the launchers work even when ~/.local/bin is not on the desktop's PATH.
|
||||||
|
install -d "$APPS"
|
||||||
|
sed "s|^Exec=sourizz\$|Exec=$BIN/sourizz|" packaging/sourizz.desktop > "$APPS/sourizz.desktop"
|
||||||
|
sed "s|^Exec=sourizz-settings\$|Exec=$BIN/sourizz-settings|" packaging/sourizz-settings.desktop > "$APPS/sourizz-settings.desktop"
|
||||||
|
command -v update-desktop-database >/dev/null && update-desktop-database "$APPS" 2>/dev/null || true
|
||||||
|
|
||||||
|
echo
|
||||||
|
echo "Installed to $BIN"
|
||||||
|
case ":$PATH:" in *":$BIN:"*) ;; *) echo "Note: $BIN is not in your PATH." ;; esac
|
||||||
|
echo "Start it with: sourizz"
|
||||||
|
echo "Launch at login: sourizz autostart enable"
|
||||||
|
echo "Check your setup: sourizz doctor"
|
||||||
@@ -0,0 +1,10 @@
|
|||||||
|
[Desktop Entry]
|
||||||
|
Type=Application
|
||||||
|
Name=Sourizz Settings
|
||||||
|
Name[fr]=Réglages de Sourizz
|
||||||
|
Comment=Configure the Sourizz cursor highlighter
|
||||||
|
Comment[fr]=Configurer la mise en valeur du curseur Sourizz
|
||||||
|
Exec=sourizz-settings
|
||||||
|
Icon=sourizz
|
||||||
|
Terminal=false
|
||||||
|
Categories=Settings;Utility;
|
||||||
@@ -0,0 +1,12 @@
|
|||||||
|
[Desktop Entry]
|
||||||
|
Type=Application
|
||||||
|
Name=Sourizz
|
||||||
|
GenericName=Cursor highlighter
|
||||||
|
GenericName[fr]=Mise en valeur du curseur
|
||||||
|
Comment=Spotlight, ring, trails, click effects and annotations for your pointer
|
||||||
|
Comment[fr]=Projecteur, anneau, traînées, effets de clic et annotations pour votre pointeur
|
||||||
|
Exec=sourizz
|
||||||
|
Icon=sourizz
|
||||||
|
Terminal=false
|
||||||
|
Categories=Utility;Accessibility;
|
||||||
|
Keywords=cursor;mouse;pointer;highlight;spotlight;presentation;screencast;curseur;souris;
|
||||||
@@ -0,0 +1,5 @@
|
|||||||
|
<svg xmlns="http://www.w3.org/2000/svg" width="128" height="128" viewBox="0 0 128 128">
|
||||||
|
<circle cx="64" cy="64" r="60" fill="#1e2028"/>
|
||||||
|
<circle cx="64" cy="64" r="34" fill="none" stroke="#ffc107" stroke-width="14"/>
|
||||||
|
<circle cx="64" cy="64" r="5" fill="#ffc107"/>
|
||||||
|
</svg>
|
||||||
|
After Width: | Height: | Size: 276 B |
@@ -0,0 +1,2 @@
|
|||||||
|
max_width = 140
|
||||||
|
use_small_heuristics = "Max"
|
||||||
@@ -0,0 +1,608 @@
|
|||||||
|
//! Screen annotations.
|
||||||
|
//!
|
||||||
|
//! Two ways to draw:
|
||||||
|
//! * **hold key** (config `annotate.hold_key`): hold the key and move the pointer.
|
||||||
|
//! Needs no input capture, so it works on every backend. Strokes fade after release.
|
||||||
|
//! * **annotation mode** (hotkey): the overlay captures pointer and keyboard and shows a
|
||||||
|
//! toolbar with pen, highlighter, text, numbered callouts and an eraser.
|
||||||
|
|
||||||
|
use crate::config::{Annotate, Color};
|
||||||
|
use crate::fx;
|
||||||
|
use crate::geom::IRect;
|
||||||
|
use crate::input::{Button, KeyEvent};
|
||||||
|
use crate::text::Fonts;
|
||||||
|
use tiny_skia::{LineCap, LineJoin, Paint, PathBuilder, Pixmap, Stroke, Transform};
|
||||||
|
|
||||||
|
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||||
|
pub enum Tool {
|
||||||
|
Pen,
|
||||||
|
Highlighter,
|
||||||
|
Text,
|
||||||
|
Callout,
|
||||||
|
Eraser,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Clone, Debug)]
|
||||||
|
pub enum Item {
|
||||||
|
Stroke {
|
||||||
|
pts: Vec<(f32, f32)>,
|
||||||
|
color: Color,
|
||||||
|
width: f32,
|
||||||
|
highlighter: bool,
|
||||||
|
/// Set when a fading stroke is released.
|
||||||
|
released_at: Option<f64>,
|
||||||
|
fade: bool,
|
||||||
|
bbox: IRect,
|
||||||
|
},
|
||||||
|
Text {
|
||||||
|
x: f32,
|
||||||
|
y: f32,
|
||||||
|
text: String,
|
||||||
|
color: Color,
|
||||||
|
size: f32,
|
||||||
|
},
|
||||||
|
Callout {
|
||||||
|
x: f32,
|
||||||
|
y: f32,
|
||||||
|
n: u32,
|
||||||
|
color: Color,
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
const CALLOUT_R: f32 = 16.0;
|
||||||
|
|
||||||
|
impl Item {
|
||||||
|
fn bbox(&self, fonts: &mut Fonts) -> IRect {
|
||||||
|
match self {
|
||||||
|
Item::Stroke { bbox, .. } => *bbox,
|
||||||
|
Item::Text { x, y, text, size, .. } => {
|
||||||
|
let w = fonts.measure(text, *size).max(*size * 0.6) + 8.0;
|
||||||
|
IRect::around(*x - 4.0, *y - *size, *x + w, *y + *size * 0.4, 4.0)
|
||||||
|
}
|
||||||
|
Item::Callout { x, y, .. } => IRect::centered(*x, *y, CALLOUT_R + 4.0),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||||
|
enum Btn {
|
||||||
|
Tool(Tool),
|
||||||
|
Color(usize),
|
||||||
|
Undo,
|
||||||
|
Clear,
|
||||||
|
Close,
|
||||||
|
}
|
||||||
|
|
||||||
|
pub const PALETTE: [Color; 6] = [
|
||||||
|
Color::rgb(0xFF, 0x3B, 0x30),
|
||||||
|
Color::rgb(0xFF, 0x95, 0x00),
|
||||||
|
Color::rgb(0xFF, 0xEB, 0x3B),
|
||||||
|
Color::rgb(0x34, 0xC7, 0x59),
|
||||||
|
Color::rgb(0x0A, 0x84, 0xFF),
|
||||||
|
Color::rgb(0xFF, 0xFF, 0xFF),
|
||||||
|
];
|
||||||
|
|
||||||
|
pub struct Annotator {
|
||||||
|
pub items: Vec<Item>,
|
||||||
|
/// Capture mode: overlay owns the pointer and keyboard.
|
||||||
|
pub active: bool,
|
||||||
|
pub tool: Tool,
|
||||||
|
pub color_idx: usize,
|
||||||
|
pub width: f32,
|
||||||
|
drawing: bool,
|
||||||
|
editing: Option<usize>,
|
||||||
|
next_callout: u32,
|
||||||
|
toolbar: IRect,
|
||||||
|
buttons: Vec<(IRect, Btn)>,
|
||||||
|
/// Index of the stroke currently being drawn with the hold key.
|
||||||
|
hold_stroke: Option<usize>,
|
||||||
|
close_requested: bool,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Default for Annotator {
|
||||||
|
fn default() -> Self {
|
||||||
|
Self {
|
||||||
|
items: Vec::new(),
|
||||||
|
active: false,
|
||||||
|
tool: Tool::Pen,
|
||||||
|
color_idx: 0,
|
||||||
|
width: 5.0,
|
||||||
|
drawing: false,
|
||||||
|
editing: None,
|
||||||
|
next_callout: 1,
|
||||||
|
toolbar: IRect::new(0, 0, 0, 0),
|
||||||
|
buttons: Vec::new(),
|
||||||
|
hold_stroke: None,
|
||||||
|
close_requested: false,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn stroke_bbox(pts: &[(f32, f32)], width: f32) -> IRect {
|
||||||
|
let mut r = IRect::new(i32::MAX, i32::MAX, i32::MIN, i32::MIN);
|
||||||
|
for &(x, y) in pts {
|
||||||
|
r = r.union(IRect::centered(x, y, width * 0.5 + 2.0));
|
||||||
|
}
|
||||||
|
r
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Annotator {
|
||||||
|
pub fn is_empty(&self) -> bool {
|
||||||
|
self.items.is_empty()
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn clear(&mut self) {
|
||||||
|
self.items.clear();
|
||||||
|
self.hold_stroke = None;
|
||||||
|
self.editing = None;
|
||||||
|
self.next_callout = 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn undo(&mut self) {
|
||||||
|
self.editing = None;
|
||||||
|
self.hold_stroke = None;
|
||||||
|
if let Some(Item::Callout { .. }) = self.items.pop() {
|
||||||
|
self.next_callout = self.next_callout.saturating_sub(1).max(1);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn color(&self) -> Color {
|
||||||
|
PALETTE[self.color_idx % PALETTE.len()]
|
||||||
|
}
|
||||||
|
|
||||||
|
// ------------------------------------------------------------- hold-key drawing
|
||||||
|
|
||||||
|
pub fn hold_begin(&mut self, cfg: &Annotate, pos: (f32, f32)) {
|
||||||
|
self.hold_end(0.0, cfg);
|
||||||
|
self.items.push(Item::Stroke {
|
||||||
|
pts: vec![pos],
|
||||||
|
color: cfg.color,
|
||||||
|
width: cfg.width,
|
||||||
|
highlighter: false,
|
||||||
|
released_at: None,
|
||||||
|
fade: cfg.fade,
|
||||||
|
bbox: stroke_bbox(&[pos], cfg.width),
|
||||||
|
});
|
||||||
|
self.hold_stroke = Some(self.items.len() - 1);
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn hold_move(&mut self, pos: (f32, f32)) {
|
||||||
|
if let Some(i) = self.hold_stroke {
|
||||||
|
self.push_point(i, pos);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn hold_end(&mut self, now: f64, _cfg: &Annotate) {
|
||||||
|
if let Some(i) = self.hold_stroke.take() {
|
||||||
|
if let Some(Item::Stroke { released_at, .. }) = self.items.get_mut(i) {
|
||||||
|
*released_at = Some(now);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// True while a text box is being typed into (its caret blinks, so frames are needed).
|
||||||
|
pub fn editing(&self) -> bool {
|
||||||
|
self.active && self.editing.is_some()
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn holding(&self) -> bool {
|
||||||
|
self.hold_stroke.is_some()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn push_point(&mut self, i: usize, pos: (f32, f32)) {
|
||||||
|
if let Some(Item::Stroke { pts, bbox, width, .. }) = self.items.get_mut(i) {
|
||||||
|
if let Some(&(lx, ly)) = pts.last() {
|
||||||
|
if (lx - pos.0).hypot(ly - pos.1) < 1.5 {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
pts.push(pos);
|
||||||
|
*bbox = bbox.union(IRect::centered(pos.0, pos.1, *width * 0.5 + 2.0));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Drop strokes that finished fading. Returns true while something is still fading.
|
||||||
|
pub fn expire(&mut self, now: f64, cfg: &Annotate) -> bool {
|
||||||
|
let fade = cfg.fade_ms as f64 / 1000.0;
|
||||||
|
let mut fading = false;
|
||||||
|
self.items.retain(|it| match it {
|
||||||
|
Item::Stroke { released_at: Some(t), fade: true, .. } => {
|
||||||
|
fading = true;
|
||||||
|
now - *t < fade
|
||||||
|
}
|
||||||
|
_ => true,
|
||||||
|
});
|
||||||
|
// Indices may have shifted; hold_stroke is only set for unreleased strokes, which are never removed.
|
||||||
|
if let Some(i) = self.hold_stroke {
|
||||||
|
if i >= self.items.len() {
|
||||||
|
self.hold_stroke = None;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if self.editing.is_some_and(|i| i >= self.items.len()) {
|
||||||
|
self.editing = None;
|
||||||
|
}
|
||||||
|
fading
|
||||||
|
}
|
||||||
|
|
||||||
|
// ------------------------------------------------------------- capture mode
|
||||||
|
|
||||||
|
pub fn begin_capture(&mut self, monitor: IRect, cfg: &Annotate) {
|
||||||
|
self.active = true;
|
||||||
|
self.drawing = false;
|
||||||
|
self.editing = None;
|
||||||
|
self.width = cfg.width;
|
||||||
|
self.layout_toolbar(monitor);
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn end_capture(&mut self) {
|
||||||
|
self.commit_text();
|
||||||
|
self.active = false;
|
||||||
|
self.drawing = false;
|
||||||
|
self.buttons.clear();
|
||||||
|
self.toolbar = IRect::new(0, 0, 0, 0);
|
||||||
|
}
|
||||||
|
|
||||||
|
fn layout_toolbar(&mut self, mon: IRect) {
|
||||||
|
let (bw, gap, pad) = (38i32, 6i32, 10i32);
|
||||||
|
let wide = 62i32;
|
||||||
|
let tools = [Tool::Pen, Tool::Highlighter, Tool::Text, Tool::Callout, Tool::Eraser];
|
||||||
|
let width = pad * 2 + tools.len() as i32 * (bw + gap) + 10 + PALETTE.len() as i32 * (30 + gap) + 10 + 3 * (wide + gap) - gap;
|
||||||
|
let height = bw + pad * 2;
|
||||||
|
let x0 = mon.x0 + (mon.width() - width) / 2;
|
||||||
|
let y0 = mon.y0 + 18;
|
||||||
|
self.toolbar = IRect::from_xywh(x0, y0, width, height);
|
||||||
|
self.buttons.clear();
|
||||||
|
let mut x = x0 + pad;
|
||||||
|
let y = y0 + pad;
|
||||||
|
for t in tools {
|
||||||
|
self.buttons.push((IRect::from_xywh(x, y, bw, bw), Btn::Tool(t)));
|
||||||
|
x += bw + gap;
|
||||||
|
}
|
||||||
|
x += 10;
|
||||||
|
for i in 0..PALETTE.len() {
|
||||||
|
self.buttons.push((IRect::from_xywh(x, y + 4, 30, 30), Btn::Color(i)));
|
||||||
|
x += 30 + gap;
|
||||||
|
}
|
||||||
|
x += 10;
|
||||||
|
for b in [Btn::Undo, Btn::Clear, Btn::Close] {
|
||||||
|
self.buttons.push((IRect::from_xywh(x, y, wide, bw), b));
|
||||||
|
x += wide + gap;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn pointer_down(&mut self, fonts: &mut Fonts, pos: (f32, f32), button: Button) {
|
||||||
|
if button != Button::Left {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if self.toolbar.contains(pos.0, pos.1) {
|
||||||
|
let hit = self.buttons.iter().find(|(r, _)| r.contains(pos.0, pos.1)).map(|(_, b)| *b);
|
||||||
|
match hit {
|
||||||
|
Some(Btn::Tool(t)) => {
|
||||||
|
self.commit_text();
|
||||||
|
self.tool = t;
|
||||||
|
}
|
||||||
|
Some(Btn::Color(i)) => self.color_idx = i,
|
||||||
|
Some(Btn::Undo) => self.undo(),
|
||||||
|
Some(Btn::Clear) => self.clear(),
|
||||||
|
Some(Btn::Close) => self.close_requested = true,
|
||||||
|
None => {}
|
||||||
|
}
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
self.commit_text();
|
||||||
|
match self.tool {
|
||||||
|
Tool::Pen | Tool::Highlighter => {
|
||||||
|
let hl = self.tool == Tool::Highlighter;
|
||||||
|
let (mut color, width) = (self.color(), if hl { self.width * 4.5 } else { self.width });
|
||||||
|
if hl {
|
||||||
|
color.a = 255;
|
||||||
|
}
|
||||||
|
self.items.push(Item::Stroke {
|
||||||
|
pts: vec![pos],
|
||||||
|
color,
|
||||||
|
width,
|
||||||
|
highlighter: hl,
|
||||||
|
released_at: None,
|
||||||
|
fade: false,
|
||||||
|
bbox: stroke_bbox(&[pos], width),
|
||||||
|
});
|
||||||
|
self.drawing = true;
|
||||||
|
}
|
||||||
|
Tool::Text => {
|
||||||
|
self.items.push(Item::Text { x: pos.0, y: pos.1, text: String::new(), color: self.color(), size: 12.0 + self.width * 3.0 });
|
||||||
|
self.editing = Some(self.items.len() - 1);
|
||||||
|
}
|
||||||
|
Tool::Callout => {
|
||||||
|
self.items.push(Item::Callout { x: pos.0, y: pos.1, n: self.next_callout, color: self.color() });
|
||||||
|
self.next_callout += 1;
|
||||||
|
}
|
||||||
|
Tool::Eraser => {
|
||||||
|
self.drawing = true;
|
||||||
|
self.erase_at(fonts, pos);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn pointer_move(&mut self, fonts: &mut Fonts, pos: (f32, f32)) {
|
||||||
|
if !self.drawing {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
match self.tool {
|
||||||
|
Tool::Pen | Tool::Highlighter => {
|
||||||
|
if let Some(i) = self.items.len().checked_sub(1) {
|
||||||
|
self.push_point(i, pos);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Tool::Eraser => self.erase_at(fonts, pos),
|
||||||
|
_ => {}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// True once if the toolbar's Done button was pressed.
|
||||||
|
pub fn take_close_request(&mut self) -> bool {
|
||||||
|
std::mem::take(&mut self.close_requested)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn pointer_up(&mut self, button: Button) {
|
||||||
|
if button == Button::Left {
|
||||||
|
self.drawing = false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn erase_at(&mut self, fonts: &mut Fonts, pos: (f32, f32)) {
|
||||||
|
let r = 14.0;
|
||||||
|
let probe = IRect::centered(pos.0, pos.1, r);
|
||||||
|
self.items.retain(|it| {
|
||||||
|
let hit = match it {
|
||||||
|
Item::Stroke { pts, width, .. } => pts.iter().any(|p| (p.0 - pos.0).hypot(p.1 - pos.1) < r + width * 0.5),
|
||||||
|
other => !other.bbox(fonts).intersect(probe).is_empty(),
|
||||||
|
};
|
||||||
|
!hit
|
||||||
|
});
|
||||||
|
self.editing = None;
|
||||||
|
self.hold_stroke = None;
|
||||||
|
}
|
||||||
|
|
||||||
|
fn commit_text(&mut self) {
|
||||||
|
if let Some(i) = self.editing.take() {
|
||||||
|
if matches!(self.items.get(i), Some(Item::Text { text, .. }) if text.is_empty()) {
|
||||||
|
self.items.remove(i);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Returns true when the user asked to leave annotation mode.
|
||||||
|
pub fn key(&mut self, ev: &KeyEvent) -> bool {
|
||||||
|
if !ev.pressed {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
if let Some(i) = self.editing {
|
||||||
|
match ev.name.as_str() {
|
||||||
|
"Escape" => {
|
||||||
|
self.commit_text();
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
"Return" | "KP_Enter" => {
|
||||||
|
self.commit_text();
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
"BackSpace" => {
|
||||||
|
if let Some(Item::Text { text, .. }) = self.items.get_mut(i) {
|
||||||
|
text.pop();
|
||||||
|
}
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
_ => {
|
||||||
|
if let (Some(ch), Some(Item::Text { text, .. })) = (ev.text, self.items.get_mut(i)) {
|
||||||
|
if !ch.is_control() && ev.mods & !crate::config::MOD_SHIFT == 0 {
|
||||||
|
text.push(ch);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if ev.mods & crate::config::MOD_CTRL != 0 && ev.name.eq_ignore_ascii_case("z") {
|
||||||
|
self.undo();
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
match ev.name.as_str() {
|
||||||
|
"Escape" => return true,
|
||||||
|
"Delete" => self.clear(),
|
||||||
|
"BackSpace" => self.undo(),
|
||||||
|
"p" | "P" => self.tool = Tool::Pen,
|
||||||
|
"h" | "H" => self.tool = Tool::Highlighter,
|
||||||
|
"t" | "T" => self.tool = Tool::Text,
|
||||||
|
"n" | "N" => self.tool = Tool::Callout,
|
||||||
|
"e" | "E" => self.tool = Tool::Eraser,
|
||||||
|
"plus" | "KP_Add" => self.width = (self.width + 1.0).min(40.0),
|
||||||
|
"minus" | "KP_Subtract" => self.width = (self.width - 1.0).max(1.0),
|
||||||
|
n if n.len() == 1 && ('1'..='6').contains(&n.chars().next().unwrap()) => {
|
||||||
|
self.color_idx = n.chars().next().unwrap() as usize - '1' as usize;
|
||||||
|
}
|
||||||
|
_ => {}
|
||||||
|
}
|
||||||
|
false
|
||||||
|
}
|
||||||
|
|
||||||
|
// ------------------------------------------------------------- geometry & painting
|
||||||
|
|
||||||
|
pub fn bounds(&self, fonts: &mut Fonts) -> IRect {
|
||||||
|
let mut r = IRect::new(0, 0, 0, 0);
|
||||||
|
for it in &self.items {
|
||||||
|
r = r.union(it.bbox(fonts));
|
||||||
|
}
|
||||||
|
if self.active {
|
||||||
|
r = r.union(self.toolbar.translate(0, 0));
|
||||||
|
r = IRect::new(r.x0 - 8, r.y0 - 8, r.x1 + 8, r.y1 + 8);
|
||||||
|
}
|
||||||
|
r
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn paint(&mut self, pm: &mut Pixmap, tf: Transform, fonts: &mut Fonts, now: f64, cfg: &Annotate) {
|
||||||
|
let fade = cfg.fade_ms as f32 / 1000.0;
|
||||||
|
let editing = self.editing;
|
||||||
|
for (i, it) in self.items.iter().enumerate() {
|
||||||
|
match it {
|
||||||
|
Item::Stroke { pts, color, width, highlighter, released_at, fade: fades, .. } => {
|
||||||
|
let mut alpha = 1.0;
|
||||||
|
if let (Some(t), true) = (released_at, *fades) {
|
||||||
|
alpha = (1.0 - (now - *t) as f32 / fade).clamp(0.0, 1.0);
|
||||||
|
alpha *= alpha.sqrt();
|
||||||
|
}
|
||||||
|
let (c, w) = if *highlighter { (color.sk(0.38 * alpha), *width) } else { (color.sk(alpha), *width) };
|
||||||
|
draw_stroke(pm, tf, pts, w, c, *highlighter);
|
||||||
|
}
|
||||||
|
Item::Text { x, y, text, color, size } => {
|
||||||
|
let shown = if editing == Some(i) {
|
||||||
|
let blink = if (now * 2.0) as i64 % 2 == 0 { "|" } else { " " };
|
||||||
|
format!("{text}{blink}")
|
||||||
|
} else {
|
||||||
|
text.clone()
|
||||||
|
};
|
||||||
|
let (ox, oy) = (tf.tx, tf.ty);
|
||||||
|
// Soft shadow keeps the text readable on any background.
|
||||||
|
fonts.draw(pm, &shown, *x + ox + 1.5, *y + oy + 1.5, *size, Color { r: 0, g: 0, b: 0, a: 140 }, 1.0);
|
||||||
|
fonts.draw(pm, &shown, *x + ox, *y + oy, *size, *color, 1.0);
|
||||||
|
}
|
||||||
|
Item::Callout { x, y, n, color } => {
|
||||||
|
fx::fill_circle(pm, tf, *x, *y, CALLOUT_R + 2.0, tiny_skia::Color::from_rgba8(255, 255, 255, 230));
|
||||||
|
fx::fill_circle(pm, tf, *x, *y, CALLOUT_R, color.sk(1.0));
|
||||||
|
let label = n.to_string();
|
||||||
|
let px = 18.0;
|
||||||
|
let w = fonts.measure(&label, px);
|
||||||
|
let lum = 0.299 * color.r as f32 + 0.587 * color.g as f32 + 0.114 * color.b as f32;
|
||||||
|
let ink = if lum > 150.0 { Color::rgb(20, 20, 20) } else { Color::rgb(255, 255, 255) };
|
||||||
|
fonts.draw(pm, &label, *x + tf.tx - w / 2.0, *y + tf.ty + px * 0.34, px, ink, 1.0);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if self.active {
|
||||||
|
self.paint_toolbar(pm, tf, fonts);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn paint_toolbar(&self, pm: &mut Pixmap, tf: Transform, fonts: &mut Fonts) {
|
||||||
|
let t = self.toolbar;
|
||||||
|
let bg = fx::solid(tiny_skia::Color::from_rgba8(24, 24, 28, 232));
|
||||||
|
fx::fill_rrect(pm, tf, t.x0 as f32, t.y0 as f32, t.width() as f32, t.height() as f32, 16.0, &bg);
|
||||||
|
fx::stroke_rrect(
|
||||||
|
pm,
|
||||||
|
tf,
|
||||||
|
t.x0 as f32 + 0.5,
|
||||||
|
t.y0 as f32 + 0.5,
|
||||||
|
t.width() as f32 - 1.0,
|
||||||
|
t.height() as f32 - 1.0,
|
||||||
|
16.0,
|
||||||
|
1.0,
|
||||||
|
tiny_skia::Color::from_rgba8(255, 255, 255, 40),
|
||||||
|
);
|
||||||
|
let accent = tiny_skia::Color::from_rgba8(59, 130, 246, 255);
|
||||||
|
let ink = Color::rgb(235, 235, 240);
|
||||||
|
let (ox, oy) = (tf.tx, tf.ty);
|
||||||
|
for (r, b) in &self.buttons {
|
||||||
|
let (x, y, w, h) = (r.x0 as f32, r.y0 as f32, r.width() as f32, r.height() as f32);
|
||||||
|
let (cx, cy) = (x + w / 2.0, y + h / 2.0);
|
||||||
|
match *b {
|
||||||
|
Btn::Tool(tool) => {
|
||||||
|
if tool == self.tool {
|
||||||
|
fx::fill_rrect(pm, tf, x, y, w, h, 10.0, &fx::solid(accent));
|
||||||
|
} else {
|
||||||
|
fx::fill_rrect(pm, tf, x, y, w, h, 10.0, &fx::solid(tiny_skia::Color::from_rgba8(255, 255, 255, 18)));
|
||||||
|
}
|
||||||
|
let white = tiny_skia::Color::from_rgba8(255, 255, 255, 255);
|
||||||
|
match tool {
|
||||||
|
Tool::Pen => {
|
||||||
|
fx::stroke_line(
|
||||||
|
pm,
|
||||||
|
tf,
|
||||||
|
(cx - 8.0, cy + 8.0),
|
||||||
|
(cx + 7.0, cy - 7.0),
|
||||||
|
4.0,
|
||||||
|
white,
|
||||||
|
tiny_skia::BlendMode::SourceOver,
|
||||||
|
);
|
||||||
|
fx::fill_circle(pm, tf, cx - 9.0, cy + 9.0, 2.2, white);
|
||||||
|
}
|
||||||
|
Tool::Highlighter => {
|
||||||
|
fx::stroke_line(
|
||||||
|
pm,
|
||||||
|
tf,
|
||||||
|
(cx - 9.0, cy + 6.0),
|
||||||
|
(cx + 9.0, cy - 6.0),
|
||||||
|
11.0,
|
||||||
|
tiny_skia::Color::from_rgba8(255, 235, 59, 190),
|
||||||
|
tiny_skia::BlendMode::SourceOver,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
Tool::Text => {
|
||||||
|
let w = fonts.measure("T", 22.0);
|
||||||
|
fonts.draw(pm, "T", cx + ox - w / 2.0, cy + oy + 8.0, 22.0, Color::rgb(255, 255, 255), 1.0);
|
||||||
|
}
|
||||||
|
Tool::Callout => {
|
||||||
|
fx::fill_circle(pm, tf, cx, cy, 11.0, white);
|
||||||
|
let w = fonts.measure("1", 15.0);
|
||||||
|
fonts.draw(pm, "1", cx + ox - w / 2.0, cy + oy + 5.0, 15.0, Color::rgb(24, 24, 28), 1.0);
|
||||||
|
}
|
||||||
|
Tool::Eraser => {
|
||||||
|
fx::fill_rrect(pm, tf, cx - 10.0, cy - 6.0, 20.0, 12.0, 3.0, &fx::solid(white));
|
||||||
|
fx::fill_rrect(
|
||||||
|
pm,
|
||||||
|
tf,
|
||||||
|
cx - 10.0,
|
||||||
|
cy - 6.0,
|
||||||
|
8.0,
|
||||||
|
12.0,
|
||||||
|
3.0,
|
||||||
|
&fx::solid(tiny_skia::Color::from_rgba8(255, 130, 130, 255)),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Btn::Color(i) => {
|
||||||
|
let c = PALETTE[i];
|
||||||
|
if i == self.color_idx {
|
||||||
|
fx::fill_circle(pm, tf, cx, cy, 15.5, tiny_skia::Color::from_rgba8(255, 255, 255, 255));
|
||||||
|
fx::fill_circle(pm, tf, cx, cy, 13.0, tiny_skia::Color::from_rgba8(24, 24, 28, 255));
|
||||||
|
}
|
||||||
|
fx::fill_circle(pm, tf, cx, cy, 11.0, c.sk(1.0));
|
||||||
|
}
|
||||||
|
Btn::Undo | Btn::Clear | Btn::Close => {
|
||||||
|
fx::fill_rrect(pm, tf, x, y, w, h, 10.0, &fx::solid(tiny_skia::Color::from_rgba8(255, 255, 255, 18)));
|
||||||
|
let label = match *b {
|
||||||
|
Btn::Undo => "Undo",
|
||||||
|
Btn::Clear => "Clear",
|
||||||
|
_ => "Done",
|
||||||
|
};
|
||||||
|
let tw = fonts.measure(label, 14.0);
|
||||||
|
fonts.draw(pm, label, cx + ox - tw / 2.0, cy + oy + 5.0, 14.0, ink, 1.0);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn draw_stroke(pm: &mut Pixmap, tf: Transform, pts: &[(f32, f32)], width: f32, c: tiny_skia::Color, flat: bool) {
|
||||||
|
let paint: Paint = fx::solid(c);
|
||||||
|
if pts.len() == 1 {
|
||||||
|
fx::fill_circle(pm, tf, pts[0].0, pts[0].1, width * 0.5, c);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
let mut pb = PathBuilder::new();
|
||||||
|
pb.move_to(pts[0].0, pts[0].1);
|
||||||
|
for w in pts.windows(2) {
|
||||||
|
let mid = ((w[0].0 + w[1].0) / 2.0, (w[0].1 + w[1].1) / 2.0);
|
||||||
|
pb.quad_to(w[0].0, w[0].1, mid.0, mid.1);
|
||||||
|
}
|
||||||
|
let last = pts[pts.len() - 1];
|
||||||
|
pb.line_to(last.0, last.1);
|
||||||
|
if let Some(path) = pb.finish() {
|
||||||
|
let s = Stroke {
|
||||||
|
width: width.max(0.5),
|
||||||
|
line_cap: if flat { LineCap::Butt } else { LineCap::Round },
|
||||||
|
line_join: LineJoin::Round,
|
||||||
|
..Stroke::default()
|
||||||
|
};
|
||||||
|
pm.stroke_path(&path, &paint, &s, tf, None);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,191 @@
|
|||||||
|
//! Click sounds.
|
||||||
|
//!
|
||||||
|
//! There is no audio library dependency: a short click is synthesised into a
|
||||||
|
//! WAV file and played by whatever sound player the system has (PipeWire,
|
||||||
|
//! PulseAudio or ALSA). Players are spawned per click and reaped lazily.
|
||||||
|
|
||||||
|
use crate::config::Sound;
|
||||||
|
use crate::input::Button;
|
||||||
|
use std::path::PathBuf;
|
||||||
|
use std::process::{Child, Command, Stdio};
|
||||||
|
|
||||||
|
const RATE: u32 = 44_100;
|
||||||
|
|
||||||
|
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||||
|
enum Player {
|
||||||
|
PwPlay,
|
||||||
|
Paplay,
|
||||||
|
Aplay,
|
||||||
|
}
|
||||||
|
|
||||||
|
pub struct Audio {
|
||||||
|
player: Option<Player>,
|
||||||
|
dir: PathBuf,
|
||||||
|
children: Vec<Child>,
|
||||||
|
warned: bool,
|
||||||
|
}
|
||||||
|
|
||||||
|
fn have(cmd: &str) -> bool {
|
||||||
|
std::env::var_os("PATH").is_some_and(|p| std::env::split_paths(&p).any(|d| d.join(cmd).is_file()))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 16-bit mono WAV of a short click.
|
||||||
|
pub fn synth_click(button: Button, pressed: bool, volume: f32) -> Vec<u8> {
|
||||||
|
let (freq, decay, len_ms, amp) = match (pressed, button) {
|
||||||
|
(true, Button::Right) => (1050.0f32, 0.011f32, 70.0f32, 0.85f32),
|
||||||
|
(true, Button::Middle) => (1900.0, 0.009, 60.0, 0.8),
|
||||||
|
(true, _) => (1500.0, 0.010, 65.0, 0.85),
|
||||||
|
(false, _) => (2500.0, 0.005, 35.0, 0.45),
|
||||||
|
};
|
||||||
|
let n = (RATE as f32 * len_ms / 1000.0) as usize;
|
||||||
|
let mut rng = 0x2545_F491u32;
|
||||||
|
let mut pcm = Vec::with_capacity(n * 2);
|
||||||
|
for i in 0..n {
|
||||||
|
let t = i as f32 / RATE as f32;
|
||||||
|
rng ^= rng << 13;
|
||||||
|
rng ^= rng >> 17;
|
||||||
|
rng ^= rng << 5;
|
||||||
|
let noise = (rng as f32 / u32::MAX as f32) * 2.0 - 1.0;
|
||||||
|
let tone = (std::f32::consts::TAU * freq * t).sin() * (-t / decay).exp();
|
||||||
|
let tick = noise * (-t / 0.0014).exp() * 0.35;
|
||||||
|
let fade_out = ((n - i) as f32 / (RATE as f32 * 0.004)).min(1.0);
|
||||||
|
let s = ((tone * 0.55 + tick) * amp * volume.clamp(0.0, 1.0) * fade_out).clamp(-1.0, 1.0);
|
||||||
|
pcm.extend_from_slice(&((s * 32767.0) as i16).to_le_bytes());
|
||||||
|
}
|
||||||
|
let mut wav = Vec::with_capacity(44 + pcm.len());
|
||||||
|
wav.extend_from_slice(b"RIFF");
|
||||||
|
wav.extend_from_slice(&(36 + pcm.len() as u32).to_le_bytes());
|
||||||
|
wav.extend_from_slice(b"WAVEfmt ");
|
||||||
|
wav.extend_from_slice(&16u32.to_le_bytes());
|
||||||
|
wav.extend_from_slice(&1u16.to_le_bytes()); // PCM
|
||||||
|
wav.extend_from_slice(&1u16.to_le_bytes()); // mono
|
||||||
|
wav.extend_from_slice(&RATE.to_le_bytes());
|
||||||
|
wav.extend_from_slice(&(RATE * 2).to_le_bytes());
|
||||||
|
wav.extend_from_slice(&2u16.to_le_bytes());
|
||||||
|
wav.extend_from_slice(&16u16.to_le_bytes());
|
||||||
|
wav.extend_from_slice(b"data");
|
||||||
|
wav.extend_from_slice(&(pcm.len() as u32).to_le_bytes());
|
||||||
|
wav.extend_from_slice(&pcm);
|
||||||
|
wav
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Default for Audio {
|
||||||
|
fn default() -> Self {
|
||||||
|
Self::new()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Audio {
|
||||||
|
pub fn new() -> Self {
|
||||||
|
let player = if have("pw-play") {
|
||||||
|
Some(Player::PwPlay)
|
||||||
|
} else if have("paplay") {
|
||||||
|
Some(Player::Paplay)
|
||||||
|
} else if have("aplay") {
|
||||||
|
Some(Player::Aplay)
|
||||||
|
} else {
|
||||||
|
None
|
||||||
|
};
|
||||||
|
let dir = std::env::var_os("XDG_RUNTIME_DIR")
|
||||||
|
.map(PathBuf::from)
|
||||||
|
.filter(|p| p.is_dir())
|
||||||
|
.unwrap_or_else(std::env::temp_dir)
|
||||||
|
.join("sourizz");
|
||||||
|
Self { player, dir, children: Vec::new(), warned: false }
|
||||||
|
}
|
||||||
|
|
||||||
|
fn wav_for(&self, button: Button, pressed: bool, volume: f32) -> Option<PathBuf> {
|
||||||
|
let kind = match (pressed, button) {
|
||||||
|
(false, _) => "up",
|
||||||
|
(true, Button::Right) => "right",
|
||||||
|
(true, Button::Middle) => "middle",
|
||||||
|
(true, _) => "left",
|
||||||
|
};
|
||||||
|
let path = self.dir.join(format!("click-{kind}-{}.wav", (volume * 100.0).round() as u32));
|
||||||
|
if !path.is_file() {
|
||||||
|
std::fs::create_dir_all(&self.dir).ok()?;
|
||||||
|
std::fs::write(&path, synth_click(button, pressed, volume)).ok()?;
|
||||||
|
}
|
||||||
|
Some(path)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn play(&mut self, cfg: &Sound, button: Button, pressed: bool) {
|
||||||
|
self.children.retain_mut(|c| matches!(c.try_wait(), Ok(None)));
|
||||||
|
if self.children.len() >= 6 {
|
||||||
|
return; // a burst of clicks: skipping some is better than a fork storm
|
||||||
|
}
|
||||||
|
let Some(player) = self.player else {
|
||||||
|
if !self.warned {
|
||||||
|
log::warn!("click sound enabled but no player found (install pipewire-bin, pulseaudio-utils or alsa-utils)");
|
||||||
|
self.warned = true;
|
||||||
|
}
|
||||||
|
return;
|
||||||
|
};
|
||||||
|
let custom = (!cfg.file.is_empty()).then(|| PathBuf::from(&cfg.file)).filter(|p| p.is_file());
|
||||||
|
let file = match custom.clone().or_else(|| self.wav_for(button, pressed, cfg.volume)) {
|
||||||
|
Some(f) => f,
|
||||||
|
None => return,
|
||||||
|
};
|
||||||
|
// The built-in WAV already has the volume baked in; custom files get player-side volume.
|
||||||
|
let vol = if custom.is_some() { cfg.volume } else { 1.0 };
|
||||||
|
let mut cmd = match player {
|
||||||
|
Player::PwPlay => {
|
||||||
|
let mut c = Command::new("pw-play");
|
||||||
|
c.arg("--volume").arg(format!("{vol:.2}")).arg(&file);
|
||||||
|
c
|
||||||
|
}
|
||||||
|
Player::Paplay => {
|
||||||
|
let mut c = Command::new("paplay");
|
||||||
|
c.arg(format!("--volume={}", (vol * 65536.0) as u32)).arg(&file);
|
||||||
|
c
|
||||||
|
}
|
||||||
|
Player::Aplay => {
|
||||||
|
let mut c = Command::new("aplay");
|
||||||
|
c.arg("-q").arg(&file);
|
||||||
|
c
|
||||||
|
}
|
||||||
|
};
|
||||||
|
cmd.stdin(Stdio::null()).stdout(Stdio::null()).stderr(Stdio::null());
|
||||||
|
match cmd.spawn() {
|
||||||
|
Ok(child) => self.children.push(child),
|
||||||
|
Err(e) => log::warn!("cannot start {player:?}: {e}"),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Drop for Audio {
|
||||||
|
fn drop(&mut self) {
|
||||||
|
for c in &mut self.children {
|
||||||
|
let _ = c.kill();
|
||||||
|
let _ = c.wait();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn wav_is_well_formed() {
|
||||||
|
let w = synth_click(Button::Left, true, 0.5);
|
||||||
|
assert_eq!(&w[0..4], b"RIFF");
|
||||||
|
assert_eq!(&w[8..12], b"WAVE");
|
||||||
|
let data_len = u32::from_le_bytes(w[40..44].try_into().unwrap()) as usize;
|
||||||
|
assert_eq!(w.len(), 44 + data_len);
|
||||||
|
assert_eq!(u32::from_le_bytes(w[4..8].try_into().unwrap()) as usize, w.len() - 8);
|
||||||
|
}
|
||||||
|
|
||||||
|
fn peak(w: &[u8]) -> i16 {
|
||||||
|
w[44..].chunks(2).map(|b| i16::from_le_bytes([b[0], b[1]]).abs()).max().unwrap()
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn volume_scales_amplitude_and_zero_is_silent() {
|
||||||
|
let loud = peak(&synth_click(Button::Left, true, 1.0));
|
||||||
|
let quiet = peak(&synth_click(Button::Left, true, 0.25));
|
||||||
|
assert!(loud > 2 * quiet, "{loud} vs {quiet}");
|
||||||
|
assert_eq!(peak(&synth_click(Button::Left, true, 0.0)), 0);
|
||||||
|
assert!(loud < 32767);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,333 @@
|
|||||||
|
//! Settings window. It edits `~/.config/sourizz/config.toml`; the running daemon notices the
|
||||||
|
//! file change and applies it live, so every slider acts as a preview.
|
||||||
|
|
||||||
|
use eframe::egui;
|
||||||
|
use sourizz::config::*;
|
||||||
|
use sourizz::i18n::{Lang, opt, t};
|
||||||
|
use sourizz::ipc;
|
||||||
|
use std::time::{Duration, Instant, SystemTime};
|
||||||
|
|
||||||
|
#[derive(Clone, Copy, PartialEq, Eq)]
|
||||||
|
enum Tab {
|
||||||
|
Effects,
|
||||||
|
Clicks,
|
||||||
|
Draw,
|
||||||
|
Keys,
|
||||||
|
Hotkeys,
|
||||||
|
General,
|
||||||
|
}
|
||||||
|
|
||||||
|
struct Settings {
|
||||||
|
cfg: Config,
|
||||||
|
saved: Config,
|
||||||
|
tab: Tab,
|
||||||
|
lang: Lang,
|
||||||
|
last_save: Instant,
|
||||||
|
last_poll: Instant,
|
||||||
|
file_mtime: Option<SystemTime>,
|
||||||
|
daemon_up: bool,
|
||||||
|
save_error: Option<String>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Settings {
|
||||||
|
fn new() -> Self {
|
||||||
|
let cfg = Config::load();
|
||||||
|
Self {
|
||||||
|
lang: Lang::resolve(&cfg.general.language),
|
||||||
|
saved: cfg.clone(),
|
||||||
|
cfg,
|
||||||
|
tab: Tab::Effects,
|
||||||
|
last_save: Instant::now(),
|
||||||
|
last_poll: Instant::now() - Duration::from_secs(10),
|
||||||
|
file_mtime: Config::mtime(),
|
||||||
|
daemon_up: ipc::is_running(),
|
||||||
|
save_error: None,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn save_if_changed(&mut self) {
|
||||||
|
if self.cfg == self.saved || self.last_save.elapsed() < Duration::from_millis(120) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
self.cfg.sanitize();
|
||||||
|
match self.cfg.save() {
|
||||||
|
Ok(()) => {
|
||||||
|
self.saved = self.cfg.clone();
|
||||||
|
self.file_mtime = Config::mtime();
|
||||||
|
self.save_error = None;
|
||||||
|
}
|
||||||
|
Err(e) => self.save_error = Some(e.to_string()),
|
||||||
|
}
|
||||||
|
self.last_save = Instant::now();
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Pick up edits made elsewhere (tray toggles, hotkeys, a text editor) when we have none pending.
|
||||||
|
fn poll_external(&mut self) {
|
||||||
|
if self.last_poll.elapsed() < Duration::from_millis(500) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
self.last_poll = Instant::now();
|
||||||
|
self.daemon_up = ipc::is_running();
|
||||||
|
let m = Config::mtime();
|
||||||
|
if m != self.file_mtime && self.cfg == self.saved {
|
||||||
|
self.file_mtime = m;
|
||||||
|
let fresh = Config::load();
|
||||||
|
self.saved = fresh.clone();
|
||||||
|
self.cfg = fresh;
|
||||||
|
}
|
||||||
|
self.lang = Lang::resolve(&self.cfg.general.language);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ------------------------------------------------------------------ small widgets
|
||||||
|
|
||||||
|
fn slider(ui: &mut egui::Ui, label: &str, v: &mut f32, range: std::ops::RangeInclusive<f32>) {
|
||||||
|
ui.horizontal(|ui| {
|
||||||
|
ui.add(egui::Slider::new(v, range).text(label));
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
fn slider_u32(ui: &mut egui::Ui, label: &str, v: &mut u32, range: std::ops::RangeInclusive<u32>) {
|
||||||
|
ui.horizontal(|ui| {
|
||||||
|
ui.add(egui::Slider::new(v, range).text(label));
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
fn color(ui: &mut egui::Ui, label: &str, c: &mut Color) {
|
||||||
|
ui.horizontal(|ui| {
|
||||||
|
let mut rgb = [c.r, c.g, c.b];
|
||||||
|
if ui.color_edit_button_srgb(&mut rgb).changed() {
|
||||||
|
(c.r, c.g, c.b) = (rgb[0], rgb[1], rgb[2]);
|
||||||
|
}
|
||||||
|
ui.label(label);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/// `id` must be unique on screen: egui treats two combo boxes with the same id as one control
|
||||||
|
/// (their popups close each other), which made the ring and trail style lists impossible to open
|
||||||
|
/// when both used the same "Style" label as their id.
|
||||||
|
fn combo<T: Copy + PartialEq + 'static>(
|
||||||
|
ui: &mut egui::Ui,
|
||||||
|
lang: Lang,
|
||||||
|
id: &str,
|
||||||
|
label: &str,
|
||||||
|
v: &mut T,
|
||||||
|
all: &[T],
|
||||||
|
name: fn(T) -> &'static str,
|
||||||
|
) {
|
||||||
|
ui.horizontal(|ui| {
|
||||||
|
egui::ComboBox::from_id_salt(id).selected_text(opt(lang, name(*v))).show_ui(ui, |ui| {
|
||||||
|
for &x in all {
|
||||||
|
ui.selectable_value(v, x, opt(lang, name(x)));
|
||||||
|
}
|
||||||
|
});
|
||||||
|
ui.label(label);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
fn text(ui: &mut egui::Ui, label: &str, s: &mut String) {
|
||||||
|
ui.horizontal(|ui| {
|
||||||
|
ui.add(egui::TextEdit::singleline(s).desired_width(220.0));
|
||||||
|
ui.label(label);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
fn section<R>(ui: &mut egui::Ui, title: &str, enabled: &mut bool, body: impl FnOnce(&mut egui::Ui) -> R) {
|
||||||
|
ui.add_space(6.0);
|
||||||
|
ui.group(|ui| {
|
||||||
|
ui.checkbox(enabled, egui::RichText::new(title).strong().size(15.0));
|
||||||
|
ui.add_enabled_ui(*enabled, |ui| {
|
||||||
|
ui.add_space(2.0);
|
||||||
|
body(ui);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
// ------------------------------------------------------------------ tabs
|
||||||
|
|
||||||
|
impl Settings {
|
||||||
|
fn tab_effects(&mut self, ui: &mut egui::Ui) {
|
||||||
|
let l = self.lang;
|
||||||
|
let c = &mut self.cfg;
|
||||||
|
section(ui, t(l, "spotlight"), &mut c.spotlight.enabled, |ui| {
|
||||||
|
combo(ui, l, "spotlight.shape", t(l, "f.shape"), &mut c.spotlight.shape, SpotShape::ALL, SpotShape::id);
|
||||||
|
slider(ui, t(l, "f.radius"), &mut c.spotlight.radius, 20.0..=800.0);
|
||||||
|
slider(ui, t(l, "f.opacity"), &mut c.spotlight.opacity, 0.0..=1.0);
|
||||||
|
slider(ui, t(l, "f.softness"), &mut c.spotlight.softness, 0.0..=1.0);
|
||||||
|
color(ui, t(l, "f.color"), &mut c.spotlight.color);
|
||||||
|
});
|
||||||
|
section(ui, t(l, "ring"), &mut c.ring.enabled, |ui| {
|
||||||
|
combo(ui, l, "ring.style", t(l, "f.style"), &mut c.ring.style, RingStyle::ALL, RingStyle::id);
|
||||||
|
slider(ui, t(l, "f.size"), &mut c.ring.size, 16.0..=300.0);
|
||||||
|
slider(ui, t(l, "f.thickness"), &mut c.ring.thickness, 1.0..=24.0);
|
||||||
|
slider(ui, t(l, "f.opacity"), &mut c.ring.opacity, 0.0..=1.0);
|
||||||
|
slider(ui, t(l, "f.fill"), &mut c.ring.fill, 0.0..=1.0);
|
||||||
|
slider(ui, t(l, "f.pulse"), &mut c.ring.pulse_speed, 0.0..=4.0);
|
||||||
|
color(ui, t(l, "f.color"), &mut c.ring.color);
|
||||||
|
});
|
||||||
|
section(ui, t(l, "trail"), &mut c.trail.enabled, |ui| {
|
||||||
|
combo(ui, l, "trail.style", t(l, "f.style"), &mut c.trail.style, TrailStyle::ALL, TrailStyle::id);
|
||||||
|
slider(ui, t(l, "f.size"), &mut c.trail.size, 4.0..=60.0);
|
||||||
|
slider_u32(ui, t(l, "f.lifetime"), &mut c.trail.lifetime_ms, 150..=3000);
|
||||||
|
color(ui, t(l, "f.color"), &mut c.trail.color);
|
||||||
|
});
|
||||||
|
section(ui, t(l, "shake"), &mut c.shake.enabled, |ui| {
|
||||||
|
slider(ui, t(l, "f.sensitivity"), &mut c.shake.sensitivity, 0.0..=1.0);
|
||||||
|
slider(ui, t(l, "f.scale"), &mut c.shake.scale, 1.5..=6.0);
|
||||||
|
slider_u32(ui, t(l, "f.duration"), &mut c.shake.duration_ms, 400..=5000);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
fn tab_clicks(&mut self, ui: &mut egui::Ui) {
|
||||||
|
let l = self.lang;
|
||||||
|
let c = &mut self.cfg;
|
||||||
|
section(ui, t(l, "clicks"), &mut c.clicks.enabled, |ui| {
|
||||||
|
ui.checkbox(&mut c.clicks.show_on_clicks, t(l, "f.show_on_clicks"));
|
||||||
|
combo(ui, l, "clicks.style", t(l, "f.style"), &mut c.clicks.style, ClickStyle::ALL, ClickStyle::id);
|
||||||
|
slider(ui, t(l, "f.size"), &mut c.clicks.size, 24.0..=300.0);
|
||||||
|
slider(ui, t(l, "f.thickness"), &mut c.clicks.thickness, 1.0..=20.0);
|
||||||
|
slider_u32(ui, t(l, "f.duration"), &mut c.clicks.duration_ms, 200..=2500);
|
||||||
|
color(ui, t(l, "f.left"), &mut c.clicks.left_color);
|
||||||
|
color(ui, t(l, "f.middle"), &mut c.clicks.middle_color);
|
||||||
|
color(ui, t(l, "f.right"), &mut c.clicks.right_color);
|
||||||
|
text(ui, t(l, "f.tap_key"), &mut c.clicks.tap_key);
|
||||||
|
});
|
||||||
|
section(ui, t(l, "sound"), &mut c.sound.enabled, |ui| {
|
||||||
|
slider(ui, t(l, "f.volume"), &mut c.sound.volume, 0.0..=1.0);
|
||||||
|
ui.checkbox(&mut c.sound.on_release, t(l, "f.on_release"));
|
||||||
|
text(ui, t(l, "f.sound_file"), &mut c.sound.file);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
fn tab_draw(&mut self, ui: &mut egui::Ui) {
|
||||||
|
let l = self.lang;
|
||||||
|
let a = &mut self.cfg.annotate;
|
||||||
|
section(ui, t(l, "annotate"), &mut a.enabled, |ui| {
|
||||||
|
text(ui, t(l, "f.hold_key"), &mut a.hold_key);
|
||||||
|
slider(ui, t(l, "f.width"), &mut a.width, 1.0..=30.0);
|
||||||
|
color(ui, t(l, "f.color"), &mut a.color);
|
||||||
|
ui.checkbox(&mut a.fade, t(l, "f.fade"));
|
||||||
|
ui.add_enabled_ui(a.fade, |ui| slider_u32(ui, t(l, "f.fade_ms"), &mut a.fade_ms, 300..=10000));
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
fn tab_keys(&mut self, ui: &mut egui::Ui) {
|
||||||
|
let l = self.lang;
|
||||||
|
let c = &mut self.cfg;
|
||||||
|
section(ui, t(l, "keystrokes"), &mut c.keystrokes.enabled, |ui| {
|
||||||
|
combo(ui, l, "keystrokes.style", t(l, "f.style"), &mut c.keystrokes.style, KeyStyle::ALL, KeyStyle::id);
|
||||||
|
combo(ui, l, "keystrokes.position", t(l, "f.position"), &mut c.keystrokes.position, KeyPosition::ALL, KeyPosition::id);
|
||||||
|
slider(ui, t(l, "f.size"), &mut c.keystrokes.size, 14.0..=72.0);
|
||||||
|
slider_u32(ui, t(l, "f.duration"), &mut c.keystrokes.duration_ms, 500..=8000);
|
||||||
|
color(ui, t(l, "f.accent"), &mut c.keystrokes.accent);
|
||||||
|
ui.checkbox(&mut c.keystrokes.only_shortcuts, t(l, "f.only_shortcuts"));
|
||||||
|
});
|
||||||
|
section(ui, t(l, "focus"), &mut c.focus.enabled, |ui| {
|
||||||
|
slider(ui, t(l, "f.opacity"), &mut c.focus.opacity, 0.0..=1.0);
|
||||||
|
color(ui, t(l, "f.color"), &mut c.focus.color);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
fn tab_hotkeys(&mut self, ui: &mut egui::Ui) {
|
||||||
|
let l = self.lang;
|
||||||
|
let h = &mut self.cfg.hotkeys;
|
||||||
|
ui.add_space(6.0);
|
||||||
|
ui.label(egui::RichText::new(t(l, "hotkeys.help")).weak());
|
||||||
|
ui.add_space(8.0);
|
||||||
|
text(ui, t(l, "hk.toggle_all"), &mut h.toggle_all);
|
||||||
|
text(ui, t(l, "spotlight"), &mut h.spotlight);
|
||||||
|
text(ui, t(l, "ring"), &mut h.ring);
|
||||||
|
text(ui, t(l, "trail"), &mut h.trail);
|
||||||
|
text(ui, t(l, "clicks"), &mut h.clicks);
|
||||||
|
text(ui, t(l, "keystrokes"), &mut h.keystrokes);
|
||||||
|
text(ui, t(l, "focus"), &mut h.focus);
|
||||||
|
text(ui, t(l, "hk.annotate_mode"), &mut h.annotate_mode);
|
||||||
|
text(ui, t(l, "hk.clear_annotations"), &mut h.clear_annotations);
|
||||||
|
text(ui, t(l, "hk.show_click"), &mut h.show_click);
|
||||||
|
}
|
||||||
|
|
||||||
|
fn tab_general(&mut self, ui: &mut egui::Ui) {
|
||||||
|
let l = self.lang;
|
||||||
|
let g = &mut self.cfg.general;
|
||||||
|
ui.add_space(6.0);
|
||||||
|
ui.checkbox(&mut g.enabled, egui::RichText::new(t(l, "enabled")).strong());
|
||||||
|
ui.add_space(6.0);
|
||||||
|
ui.horizontal(|ui| {
|
||||||
|
egui::ComboBox::from_id_salt("lang").selected_text(g.language.clone()).show_ui(ui, |ui| {
|
||||||
|
for v in ["auto", "en", "fr"] {
|
||||||
|
ui.selectable_value(&mut g.language, v.to_string(), v);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
ui.label(t(l, "f.language"));
|
||||||
|
});
|
||||||
|
combo(ui, l, "general.backend", t(l, "f.backend"), &mut g.backend, BackendKind::ALL, BackendKind::id);
|
||||||
|
slider_u32(ui, t(l, "f.fps"), &mut g.fps, 15..=144);
|
||||||
|
ui.add_space(12.0);
|
||||||
|
if ui.button(t(l, "reset")).clicked() {
|
||||||
|
self.cfg = Config::default();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl eframe::App for Settings {
|
||||||
|
fn ui(&mut self, ui: &mut egui::Ui, _frame: &mut eframe::Frame) {
|
||||||
|
self.poll_external();
|
||||||
|
let l = self.lang;
|
||||||
|
|
||||||
|
egui::Panel::top("tabs").show(ui, |ui| {
|
||||||
|
ui.add_space(4.0);
|
||||||
|
ui.horizontal_wrapped(|ui| {
|
||||||
|
for (tab, key) in [
|
||||||
|
(Tab::Effects, "tab.effects"),
|
||||||
|
(Tab::Clicks, "tab.clicks"),
|
||||||
|
(Tab::Draw, "tab.draw"),
|
||||||
|
(Tab::Keys, "tab.keys"),
|
||||||
|
(Tab::Hotkeys, "tab.hotkeys"),
|
||||||
|
(Tab::General, "tab.general"),
|
||||||
|
] {
|
||||||
|
ui.selectable_value(&mut self.tab, tab, t(l, key));
|
||||||
|
}
|
||||||
|
});
|
||||||
|
ui.add_space(4.0);
|
||||||
|
});
|
||||||
|
|
||||||
|
egui::Panel::bottom("status").show(ui, |ui| {
|
||||||
|
ui.add_space(4.0);
|
||||||
|
if let Some(e) = &self.save_error {
|
||||||
|
ui.colored_label(egui::Color32::LIGHT_RED, e);
|
||||||
|
} else if !self.daemon_up {
|
||||||
|
ui.colored_label(egui::Color32::from_rgb(255, 190, 80), t(l, "daemon_down"));
|
||||||
|
} else {
|
||||||
|
ui.label(egui::RichText::new(t(l, "saved")).weak());
|
||||||
|
}
|
||||||
|
ui.add_space(4.0);
|
||||||
|
});
|
||||||
|
|
||||||
|
egui::CentralPanel::default().show(ui, |ui| {
|
||||||
|
egui::ScrollArea::vertical().auto_shrink([false, false]).show(ui, |ui| match self.tab {
|
||||||
|
Tab::Effects => self.tab_effects(ui),
|
||||||
|
Tab::Clicks => self.tab_clicks(ui),
|
||||||
|
Tab::Draw => self.tab_draw(ui),
|
||||||
|
Tab::Keys => self.tab_keys(ui),
|
||||||
|
Tab::Hotkeys => self.tab_hotkeys(ui),
|
||||||
|
Tab::General => self.tab_general(ui),
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
self.save_if_changed();
|
||||||
|
ui.ctx().request_repaint_after(Duration::from_millis(250));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn main() -> eframe::Result {
|
||||||
|
let lang = Lang::resolve(&Config::load().general.language);
|
||||||
|
let options = eframe::NativeOptions {
|
||||||
|
viewport: egui::ViewportBuilder::default()
|
||||||
|
.with_inner_size([560.0, 700.0])
|
||||||
|
.with_min_inner_size([420.0, 420.0])
|
||||||
|
.with_title(t(lang, "app.title"))
|
||||||
|
.with_app_id("sourizz-settings"),
|
||||||
|
..Default::default()
|
||||||
|
};
|
||||||
|
eframe::run_native("sourizz-settings", options, Box::new(|_cc| Ok(Box::new(Settings::new()))))
|
||||||
|
}
|
||||||
@@ -0,0 +1,233 @@
|
|||||||
|
//! A per-monitor pixel layer in the layout windowing systems want
|
||||||
|
//! (premultiplied BGRA, i.e. `ARGB32` on little-endian machines).
|
||||||
|
//!
|
||||||
|
//! The engine paints in RGBA; [`Layer::repaint`] renders only the damaged rectangles and
|
||||||
|
//! converts them, so a mostly static overlay costs almost nothing per frame.
|
||||||
|
//!
|
||||||
|
//! X11 keeps window contents server-side, so it uses a *streaming* layer that retains
|
||||||
|
//! nothing. Wayland has to hand over a whole buffer every commit, so it uses a
|
||||||
|
//! *retained* layer that accumulates the full image.
|
||||||
|
|
||||||
|
use crate::engine::Engine;
|
||||||
|
use crate::geom::IRect;
|
||||||
|
use tiny_skia::Pixmap;
|
||||||
|
|
||||||
|
/// Scratch pixmaps above this many pixels are dropped after use instead of cached.
|
||||||
|
const KEEP_SCRATCH_PIXELS: u32 = 256 * 256;
|
||||||
|
|
||||||
|
/// A freshly painted rectangle: `rect` is layer-local, `data` is tightly packed BGRA.
|
||||||
|
pub struct Patch {
|
||||||
|
pub rect: IRect,
|
||||||
|
pub data: Vec<u8>,
|
||||||
|
}
|
||||||
|
|
||||||
|
pub struct Layer {
|
||||||
|
/// Position of this layer in global (virtual desktop) coordinates.
|
||||||
|
pub rect: IRect,
|
||||||
|
pub w: usize,
|
||||||
|
pub h: usize,
|
||||||
|
/// Full image; empty for streaming layers.
|
||||||
|
pub bgra: Vec<u8>,
|
||||||
|
retain: bool,
|
||||||
|
scratch: Option<Pixmap>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Layer {
|
||||||
|
pub fn new(rect: IRect, retain: bool) -> Self {
|
||||||
|
let (w, h) = (rect.width().max(1) as usize, rect.height().max(1) as usize);
|
||||||
|
Self { rect, w, h, bgra: if retain { vec![0; w * h * 4] } else { Vec::new() }, retain, scratch: None }
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Repaint the intersection of each `damage` rectangle with this layer.
|
||||||
|
pub fn repaint(&mut self, engine: &mut Engine, damage: &[IRect], now: f64) -> Vec<Patch> {
|
||||||
|
let mut out = Vec::new();
|
||||||
|
for &d in damage {
|
||||||
|
let g = d.intersect(self.rect);
|
||||||
|
if g.is_empty() {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
let (gw, gh) = (g.width() as u32, g.height() as u32);
|
||||||
|
let mut pm = match self.scratch.take() {
|
||||||
|
Some(p) if p.width() == gw && p.height() == gh => p,
|
||||||
|
_ => match Pixmap::new(gw, gh) {
|
||||||
|
Some(p) => p,
|
||||||
|
None => continue,
|
||||||
|
},
|
||||||
|
};
|
||||||
|
engine.paint(&mut pm, g, now);
|
||||||
|
let local = g.translate(-self.rect.x0, -self.rect.y0);
|
||||||
|
let mut data = vec![0u8; gw as usize * gh as usize * 4];
|
||||||
|
for (dp, sp) in data.chunks_exact_mut(4).zip(pm.data().chunks_exact(4)) {
|
||||||
|
dp[0] = sp[2];
|
||||||
|
dp[1] = sp[1];
|
||||||
|
dp[2] = sp[0];
|
||||||
|
dp[3] = sp[3];
|
||||||
|
}
|
||||||
|
if self.retain {
|
||||||
|
let row = gw as usize * 4;
|
||||||
|
for y in 0..gh as usize {
|
||||||
|
let o = ((local.y0 as usize + y) * self.w + local.x0 as usize) * 4;
|
||||||
|
self.bgra[o..o + row].copy_from_slice(&data[y * row..(y + 1) * row]);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if gw * gh <= KEEP_SCRATCH_PIXELS {
|
||||||
|
self.scratch = Some(pm);
|
||||||
|
}
|
||||||
|
out.push(Patch { rect: local, data });
|
||||||
|
}
|
||||||
|
out
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
use crate::config::Config;
|
||||||
|
use crate::input::InputEvent;
|
||||||
|
use crate::text::Fonts;
|
||||||
|
|
||||||
|
fn setup() -> (Engine, Vec<IRect>) {
|
||||||
|
let mut c = Config::default();
|
||||||
|
c.ring.pulse_speed = 0.0;
|
||||||
|
let mut e = Engine::new(c, Fonts::none());
|
||||||
|
e.set_monitors(vec![IRect::new(0, 0, 200, 100), IRect::new(200, 0, 400, 100)]);
|
||||||
|
e.handle(0.0, InputEvent::Pointer { x: 100.0, y: 50.0 });
|
||||||
|
let d = e.begin_frame(0.0).damage;
|
||||||
|
(e, d)
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn layer_converts_to_bgra_and_only_touches_its_monitor() {
|
||||||
|
let (mut e, d) = setup();
|
||||||
|
let mut left = Layer::new(IRect::new(0, 0, 200, 100), true);
|
||||||
|
let mut right = Layer::new(IRect::new(200, 0, 400, 100), true);
|
||||||
|
assert!(!left.repaint(&mut e, &d, 0.0).is_empty());
|
||||||
|
assert!(!right.repaint(&mut e, &d, 0.0).is_empty(), "full redraw reaches every monitor");
|
||||||
|
assert!(left.bgra.chunks(4).any(|p| p[3] > 0), "ring is on the left monitor");
|
||||||
|
assert!(right.bgra.chunks(4).all(|p| p[3] == 0), "right monitor stays empty");
|
||||||
|
// Default ring colour is amber #FFC107: in BGRA the blue byte is small, red is large.
|
||||||
|
let px = left.bgra.chunks(4).max_by_key(|p| p[3]).unwrap();
|
||||||
|
assert!(px[3] > 200 && px[2] > 200 && px[0] < 60, "BGRA order, got {px:?}");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn streaming_layer_retains_nothing_but_returns_the_same_pixels() {
|
||||||
|
let (mut e, d) = setup();
|
||||||
|
let mut retained = Layer::new(IRect::new(0, 0, 200, 100), true);
|
||||||
|
let mut streaming = Layer::new(IRect::new(0, 0, 200, 100), false);
|
||||||
|
let a = retained.repaint(&mut e, &d, 0.0);
|
||||||
|
let b = streaming.repaint(&mut e, &d, 0.0);
|
||||||
|
assert!(streaming.bgra.is_empty());
|
||||||
|
assert_eq!(a.len(), b.len());
|
||||||
|
for (x, y) in a.iter().zip(&b) {
|
||||||
|
assert_eq!(x.rect, y.rect);
|
||||||
|
assert_eq!(x.data, y.data);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn repaint_outside_layer_yields_nothing() {
|
||||||
|
let mut e = Engine::new(Config::default(), Fonts::none());
|
||||||
|
let mut l = Layer::new(IRect::new(0, 0, 100, 100), false);
|
||||||
|
assert!(l.repaint(&mut e, &[IRect::new(500, 500, 600, 600)], 0.0).is_empty());
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The property that matters: painting only the reported damage must give exactly the
|
||||||
|
/// same picture as repainting everything. A mismatch means ghost pixels or stale edges.
|
||||||
|
fn assert_incremental_matches_full(mut cfg: Config, label: &str) {
|
||||||
|
use crate::input::Button;
|
||||||
|
cfg.ring.pulse_speed = 0.0;
|
||||||
|
let mons = vec![IRect::new(0, 0, 320, 240), IRect::new(320, 0, 640, 240)];
|
||||||
|
let mut e = Engine::new(cfg, Fonts::none());
|
||||||
|
e.set_monitors(mons.clone());
|
||||||
|
let mut layers: Vec<Layer> = mons.iter().map(|m| Layer::new(*m, true)).collect();
|
||||||
|
let mut rng = 0x1234_5678u32;
|
||||||
|
let mut next = |m: u32| {
|
||||||
|
rng ^= rng << 13;
|
||||||
|
rng ^= rng >> 17;
|
||||||
|
rng ^= rng << 5;
|
||||||
|
rng % m
|
||||||
|
};
|
||||||
|
let (mut x, mut y) = (100.0f32, 100.0f32);
|
||||||
|
for step in 0..70 {
|
||||||
|
let t = step as f64 * 0.016;
|
||||||
|
match next(12) {
|
||||||
|
0 => {
|
||||||
|
// Jump, sometimes to the other monitor.
|
||||||
|
x = next(640) as f32;
|
||||||
|
y = next(240) as f32;
|
||||||
|
}
|
||||||
|
1 if step % 3 == 0 => e.handle(t, InputEvent::Button { button: Button::Left, pressed: true }),
|
||||||
|
_ => {
|
||||||
|
x = (x + next(41) as f32 - 20.0).clamp(0.0, 639.0);
|
||||||
|
y = (y + next(41) as f32 - 20.0).clamp(0.0, 239.0);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
e.handle(t, InputEvent::Pointer { x, y });
|
||||||
|
let plan = e.begin_frame(t);
|
||||||
|
for l in &mut layers {
|
||||||
|
l.repaint(&mut e, &plan.damage, t);
|
||||||
|
}
|
||||||
|
for l in &layers {
|
||||||
|
let mut full = Layer::new(l.rect, true);
|
||||||
|
full.repaint(&mut e, &[l.rect], t);
|
||||||
|
// tiny-skia's anti-aliasing is not perfectly translation-invariant: an isolated
|
||||||
|
// edge pixel can differ by up to ~35/255 depending on the clip rectangle. A real
|
||||||
|
// damage bug (a ghost or a stale edge) shows up as many pixels, far off.
|
||||||
|
let diffs: Vec<(usize, u8)> = l
|
||||||
|
.bgra
|
||||||
|
.chunks_exact(4)
|
||||||
|
.zip(full.bgra.chunks_exact(4))
|
||||||
|
.enumerate()
|
||||||
|
.map(|(i, (a, b))| (i, a.iter().zip(b).map(|(p, q)| p.abs_diff(*q)).max().unwrap()))
|
||||||
|
.filter(|(_, d)| *d > 2)
|
||||||
|
.collect();
|
||||||
|
let worst = diffs.iter().map(|(_, d)| *d).max().unwrap_or(0);
|
||||||
|
assert!(
|
||||||
|
diffs.len() <= 12 && worst <= 48,
|
||||||
|
"{label}: step {step}: {} pixels differ from a full repaint (worst {worst}), first at ({},{}) on monitor {:?}; pointer=({x},{y}) damage={:?} alpha incremental/full = {:?}",
|
||||||
|
diffs.len(),
|
||||||
|
diffs.first().map_or(0, |(i, _)| i % l.w),
|
||||||
|
diffs.first().map_or(0, |(i, _)| i / l.w),
|
||||||
|
l.rect,
|
||||||
|
plan.damage,
|
||||||
|
diffs.first().map(|(i, _)| (l.bgra[i * 4 + 3], full.bgra[i * 4 + 3]))
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn incremental_equals_full_for_every_spotlight_shape() {
|
||||||
|
use crate::config::SpotShape;
|
||||||
|
for shape in SpotShape::ALL {
|
||||||
|
let mut c = Config::default();
|
||||||
|
c.spotlight.enabled = true;
|
||||||
|
c.spotlight.shape = *shape;
|
||||||
|
c.spotlight.radius = if *shape == SpotShape::Circle { 70.0 } else { 30.0 };
|
||||||
|
assert_incremental_matches_full(c, &format!("spotlight {shape:?}"));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn incremental_equals_full_with_trails_clicks_and_ring() {
|
||||||
|
use crate::config::TrailStyle;
|
||||||
|
for style in TrailStyle::ALL {
|
||||||
|
let mut c = Config::default();
|
||||||
|
c.trail.enabled = true;
|
||||||
|
c.trail.style = *style;
|
||||||
|
c.trail.lifetime_ms = 400;
|
||||||
|
assert_incremental_matches_full(c, &format!("trail {style:?}"));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn incremental_equals_full_with_everything_on() {
|
||||||
|
let mut c = Config::default();
|
||||||
|
c.spotlight.enabled = true;
|
||||||
|
c.spotlight.radius = 50.0;
|
||||||
|
c.trail.enabled = true;
|
||||||
|
c.ring.style = crate::config::RingStyle::Neon;
|
||||||
|
assert_incremental_matches_full(c, "all effects");
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,548 @@
|
|||||||
|
//! Persistent configuration (`~/.config/sourizz/config.toml`).
|
||||||
|
//!
|
||||||
|
//! Every field has a default, so a partial or empty file is valid. The daemon
|
||||||
|
//! watches the file's modification time and reloads it live, which is how the
|
||||||
|
//! settings window and hand edits take effect without a restart.
|
||||||
|
|
||||||
|
use serde::{Deserialize, Deserializer, Serialize, Serializer};
|
||||||
|
use std::path::PathBuf;
|
||||||
|
use std::time::SystemTime;
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------- Color
|
||||||
|
|
||||||
|
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||||
|
pub struct Color {
|
||||||
|
pub r: u8,
|
||||||
|
pub g: u8,
|
||||||
|
pub b: u8,
|
||||||
|
pub a: u8,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Color {
|
||||||
|
pub const fn rgb(r: u8, g: u8, b: u8) -> Self {
|
||||||
|
Self { r, g, b, a: 255 }
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Accepts `#RGB`, `#RRGGBB` and `#RRGGBBAA` (the `#` is optional).
|
||||||
|
pub fn parse(s: &str) -> Option<Self> {
|
||||||
|
let h = s.trim().trim_start_matches('#');
|
||||||
|
let byte = |i: usize| u8::from_str_radix(h.get(i..i + 2)?, 16).ok();
|
||||||
|
match h.len() {
|
||||||
|
3 => {
|
||||||
|
let n = |i: usize| u8::from_str_radix(h.get(i..i + 1)?, 16).ok().map(|v| v * 17);
|
||||||
|
Some(Self::rgb(n(0)?, n(1)?, n(2)?))
|
||||||
|
}
|
||||||
|
6 => Some(Self::rgb(byte(0)?, byte(2)?, byte(4)?)),
|
||||||
|
8 => Some(Self { r: byte(0)?, g: byte(2)?, b: byte(4)?, a: byte(6)? }),
|
||||||
|
_ => None,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn to_hex(self) -> String {
|
||||||
|
if self.a == 255 {
|
||||||
|
format!("#{:02X}{:02X}{:02X}", self.r, self.g, self.b)
|
||||||
|
} else {
|
||||||
|
format!("#{:02X}{:02X}{:02X}{:02X}", self.r, self.g, self.b, self.a)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Convert to a tiny-skia colour, multiplying the alpha by `alpha`.
|
||||||
|
pub fn sk(self, alpha: f32) -> tiny_skia::Color {
|
||||||
|
let a = (self.a as f32 / 255.0 * alpha).clamp(0.0, 1.0);
|
||||||
|
tiny_skia::Color::from_rgba(self.r as f32 / 255.0, self.g as f32 / 255.0, self.b as f32 / 255.0, a)
|
||||||
|
.unwrap_or(tiny_skia::Color::TRANSPARENT)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn as_f32(self) -> [f32; 3] {
|
||||||
|
[self.r as f32 / 255.0, self.g as f32 / 255.0, self.b as f32 / 255.0]
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn from_f32(c: [f32; 3]) -> Self {
|
||||||
|
let q = |v: f32| (v.clamp(0.0, 1.0) * 255.0).round() as u8;
|
||||||
|
Self::rgb(q(c[0]), q(c[1]), q(c[2]))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Serialize for Color {
|
||||||
|
fn serialize<S: Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
|
||||||
|
s.serialize_str(&self.to_hex())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<'de> Deserialize<'de> for Color {
|
||||||
|
fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
|
||||||
|
let s = String::deserialize(d)?;
|
||||||
|
Color::parse(&s).ok_or_else(|| serde::de::Error::custom(format!("invalid colour {s:?}")))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------- Enums
|
||||||
|
|
||||||
|
macro_rules! string_enum {
|
||||||
|
($(#[$m:meta])* $name:ident { $($variant:ident => $s:literal),+ $(,)? }) => {
|
||||||
|
$(#[$m])*
|
||||||
|
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||||
|
pub enum $name { $(#[serde(rename = $s)] $variant),+ }
|
||||||
|
impl $name {
|
||||||
|
pub const ALL: &'static [$name] = &[$($name::$variant),+];
|
||||||
|
pub fn id(self) -> &'static str { match self { $($name::$variant => $s),+ } }
|
||||||
|
}
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
string_enum!(BackendKind { Auto => "auto", X11 => "x11", Wayland => "wayland" });
|
||||||
|
string_enum!(SpotShape { Circle => "circle", HBar => "hbar", VBar => "vbar" });
|
||||||
|
string_enum!(RingStyle { Classic => "classic", Neon => "neon" });
|
||||||
|
string_enum!(TrailStyle {
|
||||||
|
Comet => "comet", Dots => "dots", Ribbon => "ribbon", Rainbow => "rainbow",
|
||||||
|
Stars => "stars", Kawaii => "kawaii", Sparkles => "sparkles",
|
||||||
|
});
|
||||||
|
string_enum!(ClickStyle {
|
||||||
|
SingleRing => "single_ring", RippleWave => "ripple_wave", Burst => "burst", Pulse => "pulse",
|
||||||
|
});
|
||||||
|
string_enum!(KeyStyle {
|
||||||
|
Classic => "classic", Glass => "glass", Keycaps => "keycaps",
|
||||||
|
Neon => "neon", Gradient => "gradient", Minimal => "minimal",
|
||||||
|
});
|
||||||
|
string_enum!(KeyPosition {
|
||||||
|
BottomCenter => "bottom_center", BottomLeft => "bottom_left", BottomRight => "bottom_right",
|
||||||
|
TopCenter => "top_center",
|
||||||
|
});
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------- Sections
|
||||||
|
|
||||||
|
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||||
|
#[serde(default)]
|
||||||
|
pub struct General {
|
||||||
|
/// Master switch: when false nothing is drawn.
|
||||||
|
pub enabled: bool,
|
||||||
|
pub backend: BackendKind,
|
||||||
|
/// `auto`, `en` or `fr`.
|
||||||
|
pub language: String,
|
||||||
|
/// Maximum animation frame rate.
|
||||||
|
pub fps: u32,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||||
|
#[serde(default)]
|
||||||
|
pub struct Spotlight {
|
||||||
|
pub enabled: bool,
|
||||||
|
pub shape: SpotShape,
|
||||||
|
/// Radius of the lit circle, or half-thickness of the lit bar, in pixels.
|
||||||
|
pub radius: f32,
|
||||||
|
/// How dark the surroundings are, 0..1.
|
||||||
|
pub opacity: f32,
|
||||||
|
pub color: Color,
|
||||||
|
/// Edge softness, 0 (sharp) .. 1 (very soft).
|
||||||
|
pub softness: f32,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||||
|
#[serde(default)]
|
||||||
|
pub struct Ring {
|
||||||
|
pub enabled: bool,
|
||||||
|
pub style: RingStyle,
|
||||||
|
pub size: f32,
|
||||||
|
pub thickness: f32,
|
||||||
|
pub color: Color,
|
||||||
|
pub opacity: f32,
|
||||||
|
/// Translucent disc inside the ring, 0..1.
|
||||||
|
pub fill: f32,
|
||||||
|
/// Pulse animation speed, 0 = static.
|
||||||
|
pub pulse_speed: f32,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||||
|
#[serde(default)]
|
||||||
|
pub struct Trail {
|
||||||
|
pub enabled: bool,
|
||||||
|
pub style: TrailStyle,
|
||||||
|
pub lifetime_ms: u32,
|
||||||
|
pub size: f32,
|
||||||
|
pub color: Color,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||||
|
#[serde(default)]
|
||||||
|
pub struct Clicks {
|
||||||
|
pub enabled: bool,
|
||||||
|
/// Show the effect on real mouse clicks (otherwise only on demand, see `tap_key`).
|
||||||
|
pub show_on_clicks: bool,
|
||||||
|
pub style: ClickStyle,
|
||||||
|
pub size: f32,
|
||||||
|
pub thickness: f32,
|
||||||
|
pub duration_ms: u32,
|
||||||
|
pub left_color: Color,
|
||||||
|
pub middle_color: Color,
|
||||||
|
pub right_color: Color,
|
||||||
|
/// Key whose *tap* triggers the effect at the pointer, e.g. `Control_L`. Empty = off.
|
||||||
|
pub tap_key: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||||
|
#[serde(default)]
|
||||||
|
pub struct Sound {
|
||||||
|
pub enabled: bool,
|
||||||
|
pub volume: f32,
|
||||||
|
/// Optional custom WAV file. Empty = built-in click.
|
||||||
|
pub file: String,
|
||||||
|
/// Also play on button release.
|
||||||
|
pub on_release: bool,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||||
|
#[serde(default)]
|
||||||
|
pub struct Shake {
|
||||||
|
pub enabled: bool,
|
||||||
|
/// 0..1, higher triggers more easily.
|
||||||
|
pub sensitivity: f32,
|
||||||
|
/// How much the pointer marker grows while locating.
|
||||||
|
pub scale: f32,
|
||||||
|
pub duration_ms: u32,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||||
|
#[serde(default)]
|
||||||
|
pub struct Annotate {
|
||||||
|
pub enabled: bool,
|
||||||
|
/// Hold this key and move the pointer to draw. Empty = off.
|
||||||
|
pub hold_key: String,
|
||||||
|
pub color: Color,
|
||||||
|
pub width: f32,
|
||||||
|
/// Strokes drawn with the hold key fade away after release.
|
||||||
|
pub fade: bool,
|
||||||
|
pub fade_ms: u32,
|
||||||
|
pub highlighter_color: Color,
|
||||||
|
pub highlighter_width: f32,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||||
|
#[serde(default)]
|
||||||
|
pub struct Keystrokes {
|
||||||
|
pub enabled: bool,
|
||||||
|
pub style: KeyStyle,
|
||||||
|
pub position: KeyPosition,
|
||||||
|
pub size: f32,
|
||||||
|
pub duration_ms: u32,
|
||||||
|
/// Only show combinations that include Ctrl/Alt/Super (never plain typing).
|
||||||
|
pub only_shortcuts: bool,
|
||||||
|
pub accent: Color,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||||
|
#[serde(default)]
|
||||||
|
pub struct Focus {
|
||||||
|
pub enabled: bool,
|
||||||
|
pub opacity: f32,
|
||||||
|
pub color: Color,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Global hotkeys written as `Ctrl+Alt+Shift+S`. An empty string disables one.
|
||||||
|
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||||
|
#[serde(default)]
|
||||||
|
pub struct Hotkeys {
|
||||||
|
pub toggle_all: String,
|
||||||
|
pub spotlight: String,
|
||||||
|
pub ring: String,
|
||||||
|
pub trail: String,
|
||||||
|
pub clicks: String,
|
||||||
|
pub keystrokes: String,
|
||||||
|
pub focus: String,
|
||||||
|
pub annotate_mode: String,
|
||||||
|
pub clear_annotations: String,
|
||||||
|
pub show_click: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Default)]
|
||||||
|
#[serde(default)]
|
||||||
|
pub struct Config {
|
||||||
|
pub general: General,
|
||||||
|
pub spotlight: Spotlight,
|
||||||
|
pub ring: Ring,
|
||||||
|
pub trail: Trail,
|
||||||
|
pub clicks: Clicks,
|
||||||
|
pub sound: Sound,
|
||||||
|
pub shake: Shake,
|
||||||
|
pub annotate: Annotate,
|
||||||
|
pub keystrokes: Keystrokes,
|
||||||
|
pub focus: Focus,
|
||||||
|
pub hotkeys: Hotkeys,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Default for General {
|
||||||
|
fn default() -> Self {
|
||||||
|
Self { enabled: true, backend: BackendKind::Auto, language: "auto".into(), fps: 60 }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
impl Default for Spotlight {
|
||||||
|
fn default() -> Self {
|
||||||
|
Self { enabled: false, shape: SpotShape::Circle, radius: 170.0, opacity: 0.65, color: Color::rgb(0, 0, 0), softness: 0.25 }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
impl Default for Ring {
|
||||||
|
fn default() -> Self {
|
||||||
|
Self {
|
||||||
|
enabled: true,
|
||||||
|
style: RingStyle::Classic,
|
||||||
|
size: 56.0,
|
||||||
|
thickness: 4.0,
|
||||||
|
color: Color::rgb(0xFF, 0xC1, 0x07),
|
||||||
|
opacity: 0.95,
|
||||||
|
fill: 0.0,
|
||||||
|
pulse_speed: 1.0,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
impl Default for Trail {
|
||||||
|
fn default() -> Self {
|
||||||
|
Self { enabled: false, style: TrailStyle::Comet, lifetime_ms: 650, size: 16.0, color: Color::rgb(0x3D, 0xA5, 0xFF) }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
impl Default for Clicks {
|
||||||
|
fn default() -> Self {
|
||||||
|
Self {
|
||||||
|
enabled: true,
|
||||||
|
show_on_clicks: true,
|
||||||
|
style: ClickStyle::SingleRing,
|
||||||
|
size: 72.0,
|
||||||
|
thickness: 5.0,
|
||||||
|
duration_ms: 600,
|
||||||
|
left_color: Color::rgb(0x3B, 0x82, 0xF6),
|
||||||
|
middle_color: Color::rgb(0x22, 0xC5, 0x5E),
|
||||||
|
right_color: Color::rgb(0xF4, 0x3F, 0x5E),
|
||||||
|
tap_key: String::new(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
impl Default for Sound {
|
||||||
|
fn default() -> Self {
|
||||||
|
Self { enabled: false, volume: 0.5, file: String::new(), on_release: false }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
impl Default for Shake {
|
||||||
|
fn default() -> Self {
|
||||||
|
Self { enabled: true, sensitivity: 0.6, scale: 3.2, duration_ms: 1400 }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
impl Default for Annotate {
|
||||||
|
fn default() -> Self {
|
||||||
|
Self {
|
||||||
|
enabled: true,
|
||||||
|
hold_key: "Control_R".into(),
|
||||||
|
color: Color::rgb(0xFF, 0x3B, 0x30),
|
||||||
|
width: 5.0,
|
||||||
|
fade: true,
|
||||||
|
fade_ms: 1800,
|
||||||
|
highlighter_color: Color::rgb(0xFF, 0xEB, 0x3B),
|
||||||
|
highlighter_width: 24.0,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
impl Default for Keystrokes {
|
||||||
|
fn default() -> Self {
|
||||||
|
Self {
|
||||||
|
enabled: false,
|
||||||
|
style: KeyStyle::Classic,
|
||||||
|
position: KeyPosition::BottomCenter,
|
||||||
|
size: 28.0,
|
||||||
|
duration_ms: 1800,
|
||||||
|
only_shortcuts: false,
|
||||||
|
accent: Color::rgb(0x3B, 0x82, 0xF6),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
impl Default for Focus {
|
||||||
|
fn default() -> Self {
|
||||||
|
Self { enabled: false, opacity: 0.6, color: Color::rgb(0, 0, 0) }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
impl Default for Hotkeys {
|
||||||
|
fn default() -> Self {
|
||||||
|
let k = |c: &str| format!("Ctrl+Alt+Shift+{c}");
|
||||||
|
Self {
|
||||||
|
toggle_all: k("M"),
|
||||||
|
spotlight: k("S"),
|
||||||
|
ring: k("R"),
|
||||||
|
trail: k("T"),
|
||||||
|
clicks: k("C"),
|
||||||
|
keystrokes: k("K"),
|
||||||
|
focus: k("F"),
|
||||||
|
annotate_mode: k("A"),
|
||||||
|
clear_annotations: k("X"),
|
||||||
|
show_click: String::new(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------- Load / save
|
||||||
|
|
||||||
|
impl Config {
|
||||||
|
/// Clamp values to sane ranges so a hand-edited file can never break rendering.
|
||||||
|
pub fn sanitize(&mut self) {
|
||||||
|
let c = |v: &mut f32, lo: f32, hi: f32| *v = if v.is_finite() { v.clamp(lo, hi) } else { lo };
|
||||||
|
c(&mut self.spotlight.radius, 8.0, 4000.0);
|
||||||
|
c(&mut self.spotlight.opacity, 0.0, 1.0);
|
||||||
|
c(&mut self.spotlight.softness, 0.0, 1.0);
|
||||||
|
c(&mut self.ring.size, 8.0, 800.0);
|
||||||
|
c(&mut self.ring.thickness, 0.5, 60.0);
|
||||||
|
c(&mut self.ring.opacity, 0.0, 1.0);
|
||||||
|
c(&mut self.ring.fill, 0.0, 1.0);
|
||||||
|
c(&mut self.ring.pulse_speed, 0.0, 10.0);
|
||||||
|
c(&mut self.trail.size, 2.0, 120.0);
|
||||||
|
c(&mut self.clicks.size, 8.0, 800.0);
|
||||||
|
c(&mut self.clicks.thickness, 0.5, 60.0);
|
||||||
|
c(&mut self.sound.volume, 0.0, 1.0);
|
||||||
|
c(&mut self.shake.sensitivity, 0.0, 1.0);
|
||||||
|
c(&mut self.shake.scale, 1.0, 10.0);
|
||||||
|
c(&mut self.annotate.width, 1.0, 80.0);
|
||||||
|
c(&mut self.annotate.highlighter_width, 2.0, 200.0);
|
||||||
|
c(&mut self.keystrokes.size, 10.0, 120.0);
|
||||||
|
c(&mut self.focus.opacity, 0.0, 1.0);
|
||||||
|
self.trail.lifetime_ms = self.trail.lifetime_ms.clamp(100, 5000);
|
||||||
|
self.clicks.duration_ms = self.clicks.duration_ms.clamp(100, 5000);
|
||||||
|
self.shake.duration_ms = self.shake.duration_ms.clamp(300, 8000);
|
||||||
|
self.annotate.fade_ms = self.annotate.fade_ms.clamp(200, 30000);
|
||||||
|
self.keystrokes.duration_ms = self.keystrokes.duration_ms.clamp(300, 15000);
|
||||||
|
self.general.fps = self.general.fps.clamp(15, 240);
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn dir() -> PathBuf {
|
||||||
|
let base = std::env::var_os("XDG_CONFIG_HOME")
|
||||||
|
.map(PathBuf::from)
|
||||||
|
.filter(|p| p.is_absolute())
|
||||||
|
.or_else(|| std::env::var_os("HOME").map(|h| PathBuf::from(h).join(".config")))
|
||||||
|
.unwrap_or_else(|| PathBuf::from("."));
|
||||||
|
base.join("sourizz")
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn path() -> PathBuf {
|
||||||
|
Self::dir().join("config.toml")
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Load the config; a missing file yields defaults, a broken one is reported and ignored.
|
||||||
|
pub fn load() -> Self {
|
||||||
|
Self::load_from(&Self::path())
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn load_from(path: &std::path::Path) -> Self {
|
||||||
|
let mut cfg = match std::fs::read_to_string(path) {
|
||||||
|
Ok(text) => match toml::from_str::<Config>(&text) {
|
||||||
|
Ok(c) => c,
|
||||||
|
Err(e) => {
|
||||||
|
log::error!("{}: {e} — using defaults", path.display());
|
||||||
|
Config::default()
|
||||||
|
}
|
||||||
|
},
|
||||||
|
Err(_) => Config::default(),
|
||||||
|
};
|
||||||
|
cfg.sanitize();
|
||||||
|
cfg
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Write atomically (temp file + rename) so the daemon never reads a half-written file.
|
||||||
|
pub fn save(&self) -> anyhow::Result<()> {
|
||||||
|
self.save_to(&Self::path())
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn save_to(&self, path: &std::path::Path) -> anyhow::Result<()> {
|
||||||
|
if let Some(dir) = path.parent() {
|
||||||
|
std::fs::create_dir_all(dir)?;
|
||||||
|
}
|
||||||
|
let tmp = path.with_extension("toml.tmp");
|
||||||
|
std::fs::write(&tmp, toml::to_string_pretty(self)?)?;
|
||||||
|
std::fs::rename(&tmp, path)?;
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn mtime() -> Option<SystemTime> {
|
||||||
|
std::fs::metadata(Self::path()).and_then(|m| m.modified()).ok()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------- Hotkey chords
|
||||||
|
|
||||||
|
pub const MOD_CTRL: u8 = 1;
|
||||||
|
pub const MOD_SHIFT: u8 = 2;
|
||||||
|
pub const MOD_ALT: u8 = 4;
|
||||||
|
pub const MOD_SUPER: u8 = 8;
|
||||||
|
|
||||||
|
/// A parsed hotkey: modifier mask plus a key name (`S`, `F5`, `space`, …).
|
||||||
|
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||||
|
pub struct Chord {
|
||||||
|
pub mods: u8,
|
||||||
|
pub key: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Chord {
|
||||||
|
pub fn parse(s: &str) -> Option<Chord> {
|
||||||
|
let mut mods = 0u8;
|
||||||
|
let mut key = None;
|
||||||
|
for part in s.split('+').map(str::trim).filter(|p| !p.is_empty()) {
|
||||||
|
match part.to_ascii_lowercase().as_str() {
|
||||||
|
"ctrl" | "control" | "ctl" => mods |= MOD_CTRL,
|
||||||
|
"shift" => mods |= MOD_SHIFT,
|
||||||
|
"alt" | "meta" => mods |= MOD_ALT,
|
||||||
|
"super" | "win" | "windows" | "logo" | "cmd" => mods |= MOD_SUPER,
|
||||||
|
_ => {
|
||||||
|
if key.replace(part.to_string()).is_some() {
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
key.map(|key| Chord { mods, key })
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn color_roundtrip() {
|
||||||
|
assert_eq!(Color::parse("#fc0"), Some(Color::rgb(0xff, 0xcc, 0)));
|
||||||
|
assert_eq!(Color::parse("FFC107"), Some(Color::rgb(0xFF, 0xC1, 0x07)));
|
||||||
|
let c = Color { r: 1, g: 2, b: 3, a: 4 };
|
||||||
|
assert_eq!(Color::parse(&c.to_hex()), Some(c));
|
||||||
|
assert_eq!(Color::parse("#12345"), None);
|
||||||
|
assert_eq!(Color::parse("zzzzzz"), None);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn empty_and_partial_files_are_valid() {
|
||||||
|
let c: Config = toml::from_str("").unwrap();
|
||||||
|
assert_eq!(c, Config::default());
|
||||||
|
let c: Config = toml::from_str("[ring]\nsize = 90.0\n").unwrap();
|
||||||
|
assert_eq!(c.ring.size, 90.0);
|
||||||
|
assert_eq!(c.ring.thickness, Ring::default().thickness);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn default_roundtrips_through_toml() {
|
||||||
|
let c = Config::default();
|
||||||
|
let back: Config = toml::from_str(&toml::to_string_pretty(&c).unwrap()).unwrap();
|
||||||
|
assert_eq!(c, back);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn sanitize_clamps_garbage() {
|
||||||
|
let mut c = Config::default();
|
||||||
|
c.ring.size = f32::NAN;
|
||||||
|
c.spotlight.opacity = 7.0;
|
||||||
|
c.general.fps = 0;
|
||||||
|
c.sanitize();
|
||||||
|
assert!(c.ring.size >= 8.0);
|
||||||
|
assert_eq!(c.spotlight.opacity, 1.0);
|
||||||
|
assert_eq!(c.general.fps, 15);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn chords() {
|
||||||
|
let c = Chord::parse("Ctrl+Alt+Shift+S").unwrap();
|
||||||
|
assert_eq!(c.mods, MOD_CTRL | MOD_ALT | MOD_SHIFT);
|
||||||
|
assert_eq!(c.key, "S");
|
||||||
|
assert!(Chord::parse("").is_none());
|
||||||
|
assert!(Chord::parse("Ctrl+").is_none());
|
||||||
|
assert!(Chord::parse("A+B").is_none());
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,218 @@
|
|||||||
|
//! Commands that steer the running daemon, from the tray, the CLI socket or hotkeys.
|
||||||
|
|
||||||
|
use crate::config::Config;
|
||||||
|
use rustix::fd::{AsFd, OwnedFd};
|
||||||
|
use std::sync::Arc;
|
||||||
|
use std::sync::mpsc::{Receiver, Sender};
|
||||||
|
|
||||||
|
pub enum Command {
|
||||||
|
Toggle(String),
|
||||||
|
Set(String, bool),
|
||||||
|
/// Generic `section.key value` setter (used by the tray's radio items and `sourizz set`).
|
||||||
|
SetOption(String, String),
|
||||||
|
ShowClick,
|
||||||
|
AnnotateToggle,
|
||||||
|
AnnotateClear,
|
||||||
|
Reload,
|
||||||
|
/// Reply with a one-line status.
|
||||||
|
Status(Sender<String>),
|
||||||
|
Settings,
|
||||||
|
Quit,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Names accepted by `toggle`, `on` and `off`.
|
||||||
|
pub const EFFECTS: &[&str] = &["all", "spotlight", "ring", "trail", "clicks", "sound", "shake", "annotate", "keystrokes", "focus"];
|
||||||
|
|
||||||
|
/// Cloneable handle other threads use to talk to the backend loop.
|
||||||
|
#[derive(Clone)]
|
||||||
|
pub struct Hub {
|
||||||
|
tx: Sender<Command>,
|
||||||
|
wake: Arc<OwnedFd>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Hub {
|
||||||
|
/// Returns the hub, the command receiver and the read end of the wake pipe the
|
||||||
|
/// backend must poll (it becomes readable whenever a command is queued).
|
||||||
|
pub fn new() -> std::io::Result<(Hub, Receiver<Command>, OwnedFd)> {
|
||||||
|
let (tx, rx) = std::sync::mpsc::channel();
|
||||||
|
let (r, w) = rustix::pipe::pipe_with(rustix::pipe::PipeFlags::CLOEXEC | rustix::pipe::PipeFlags::NONBLOCK)?;
|
||||||
|
Ok((Hub { tx, wake: Arc::new(w) }, rx, r))
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn send(&self, c: Command) {
|
||||||
|
if self.tx.send(c).is_ok() {
|
||||||
|
self.poke();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Wake the backend loop without sending a command.
|
||||||
|
pub fn poke(&self) {
|
||||||
|
let _ = rustix::io::write(self.wake.as_fd(), &[1u8]);
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn wake_fd(&self) -> Arc<OwnedFd> {
|
||||||
|
self.wake.clone()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Drain the wake pipe so poll() stops reporting it as readable.
|
||||||
|
pub fn drain(fd: &OwnedFd) {
|
||||||
|
let mut buf = [0u8; 64];
|
||||||
|
while matches!(rustix::io::read(fd, &mut buf), Ok(n) if n > 0) {}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn flag<'a>(cfg: &'a mut Config, name: &str) -> Option<&'a mut bool> {
|
||||||
|
Some(match name {
|
||||||
|
"all" | "enabled" => &mut cfg.general.enabled,
|
||||||
|
"spotlight" => &mut cfg.spotlight.enabled,
|
||||||
|
"ring" => &mut cfg.ring.enabled,
|
||||||
|
"trail" => &mut cfg.trail.enabled,
|
||||||
|
"clicks" | "click" => &mut cfg.clicks.enabled,
|
||||||
|
"sound" => &mut cfg.sound.enabled,
|
||||||
|
"shake" => &mut cfg.shake.enabled,
|
||||||
|
"annotate" | "annotations" => &mut cfg.annotate.enabled,
|
||||||
|
"keystrokes" | "keys" => &mut cfg.keystrokes.enabled,
|
||||||
|
"focus" => &mut cfg.focus.enabled,
|
||||||
|
_ => return None,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Set `section.key` to `value` (parsed as bool, integer, float, then string).
|
||||||
|
pub fn set_option(cfg: &Config, key: &str, value: &str) -> Result<Config, String> {
|
||||||
|
let mut doc = toml::Value::try_from(cfg).map_err(|e| e.to_string())?;
|
||||||
|
let (section, field) = key.split_once('.').ok_or_else(|| format!("expected section.key, got {key:?}"))?;
|
||||||
|
let table = doc.get_mut(section).and_then(|v| v.as_table_mut()).ok_or_else(|| format!("unknown section {section:?}"))?;
|
||||||
|
let old = table.get(field).ok_or_else(|| format!("unknown option {key:?}"))?;
|
||||||
|
let new = match old {
|
||||||
|
toml::Value::Boolean(_) => toml::Value::Boolean(matches!(value, "true" | "1" | "on" | "yes")),
|
||||||
|
toml::Value::Integer(_) => toml::Value::Integer(value.parse().map_err(|_| format!("{value:?} is not an integer"))?),
|
||||||
|
toml::Value::Float(_) => toml::Value::Float(value.parse().map_err(|_| format!("{value:?} is not a number"))?),
|
||||||
|
_ => toml::Value::String(value.to_string()),
|
||||||
|
};
|
||||||
|
table.insert(field.to_string(), new);
|
||||||
|
let mut out: Config = doc.try_into().map_err(|e: toml::de::Error| format!("invalid value for {key}: {e}"))?;
|
||||||
|
out.sanitize();
|
||||||
|
Ok(out)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Parse one line of the control protocol.
|
||||||
|
pub fn parse_line(line: &str) -> Result<Command, String> {
|
||||||
|
let mut it = line.split_whitespace();
|
||||||
|
let verb = it.next().ok_or("empty command")?;
|
||||||
|
let arg = it.next();
|
||||||
|
let known = |a: Option<&str>| -> Result<String, String> {
|
||||||
|
let a = a.ok_or("missing effect name")?;
|
||||||
|
if EFFECTS.contains(&a) || matches!(a, "enabled" | "click" | "annotations" | "keys") {
|
||||||
|
Ok(a.to_string())
|
||||||
|
} else {
|
||||||
|
Err(format!("unknown effect {a:?} (try: {})", EFFECTS.join(", ")))
|
||||||
|
}
|
||||||
|
};
|
||||||
|
Ok(match verb {
|
||||||
|
"toggle" => Command::Toggle(known(arg)?),
|
||||||
|
"on" => Command::Set(known(arg)?, true),
|
||||||
|
"off" => Command::Set(known(arg)?, false),
|
||||||
|
"set" => {
|
||||||
|
let key = arg.ok_or("usage: set <section.key> <value>")?;
|
||||||
|
let value: Vec<&str> = it.collect();
|
||||||
|
if value.is_empty() {
|
||||||
|
return Err("usage: set <section.key> <value>".into());
|
||||||
|
}
|
||||||
|
Command::SetOption(key.to_string(), value.join(" "))
|
||||||
|
}
|
||||||
|
"show-click" => Command::ShowClick,
|
||||||
|
"annotate" => match arg {
|
||||||
|
None | Some("toggle") => Command::AnnotateToggle,
|
||||||
|
Some("clear") => Command::AnnotateClear,
|
||||||
|
Some(o) => return Err(format!("unknown annotate action {o:?} (toggle, clear)")),
|
||||||
|
},
|
||||||
|
"reload" => Command::Reload,
|
||||||
|
"settings" => Command::Settings,
|
||||||
|
"quit" => Command::Quit,
|
||||||
|
"status" => return Err("status needs a reply channel".into()),
|
||||||
|
other => return Err(format!("unknown command {other:?}")),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The configured global hotkeys as `(action name, parsed chord)`; invalid or empty ones are skipped.
|
||||||
|
pub fn hotkey_table(h: &crate::config::Hotkeys) -> Vec<(&'static str, crate::config::Chord)> {
|
||||||
|
[
|
||||||
|
("toggle_all", &h.toggle_all),
|
||||||
|
("spotlight", &h.spotlight),
|
||||||
|
("ring", &h.ring),
|
||||||
|
("trail", &h.trail),
|
||||||
|
("clicks", &h.clicks),
|
||||||
|
("keystrokes", &h.keystrokes),
|
||||||
|
("focus", &h.focus),
|
||||||
|
("annotate_mode", &h.annotate_mode),
|
||||||
|
("clear_annotations", &h.clear_annotations),
|
||||||
|
("show_click", &h.show_click),
|
||||||
|
]
|
||||||
|
.into_iter()
|
||||||
|
.filter_map(|(name, s)| match crate::config::Chord::parse(s) {
|
||||||
|
Some(c) => Some((name, c)),
|
||||||
|
None => {
|
||||||
|
if !s.trim().is_empty() {
|
||||||
|
log::warn!("hotkeys.{name}: cannot parse {s:?}");
|
||||||
|
}
|
||||||
|
None
|
||||||
|
}
|
||||||
|
})
|
||||||
|
.collect()
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn hotkey_command(name: &str) -> Option<Command> {
|
||||||
|
Some(match name {
|
||||||
|
"toggle_all" => Command::Toggle("all".into()),
|
||||||
|
"annotate_mode" => Command::AnnotateToggle,
|
||||||
|
"clear_annotations" => Command::AnnotateClear,
|
||||||
|
"show_click" => Command::ShowClick,
|
||||||
|
n @ ("spotlight" | "ring" | "trail" | "clicks" | "keystrokes" | "focus") => Command::Toggle(n.into()),
|
||||||
|
_ => return None,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn parses_commands() {
|
||||||
|
assert!(matches!(parse_line("toggle ring"), Ok(Command::Toggle(n)) if n == "ring"));
|
||||||
|
assert!(matches!(parse_line("off spotlight"), Ok(Command::Set(n, false)) if n == "spotlight"));
|
||||||
|
assert!(matches!(parse_line("annotate clear"), Ok(Command::AnnotateClear)));
|
||||||
|
assert!(matches!(parse_line("annotate"), Ok(Command::AnnotateToggle)));
|
||||||
|
assert!(matches!(parse_line("set ring.size 80"), Ok(Command::SetOption(k, v)) if k == "ring.size" && v == "80"));
|
||||||
|
assert!(parse_line("toggle nonsense").is_err());
|
||||||
|
assert!(parse_line("").is_err());
|
||||||
|
assert!(parse_line("frobnicate").is_err());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn set_option_types_and_errors() {
|
||||||
|
let c = Config::default();
|
||||||
|
let c2 = set_option(&c, "ring.size", "90").unwrap();
|
||||||
|
assert_eq!(c2.ring.size, 90.0);
|
||||||
|
let c3 = set_option(&c, "trail.style", "stars").unwrap();
|
||||||
|
assert_eq!(c3.trail.style, crate::config::TrailStyle::Stars);
|
||||||
|
let c4 = set_option(&c, "ring.color", "#00ff00").unwrap();
|
||||||
|
assert_eq!(c4.ring.color, crate::config::Color::rgb(0, 255, 0));
|
||||||
|
let c5 = set_option(&c, "spotlight.enabled", "on").unwrap();
|
||||||
|
assert!(c5.spotlight.enabled);
|
||||||
|
assert!(set_option(&c, "trail.style", "nope").is_err());
|
||||||
|
assert!(set_option(&c, "ring.size", "abc").is_err());
|
||||||
|
assert!(set_option(&c, "ring.bogus", "1").is_err());
|
||||||
|
assert!(set_option(&c, "bogus.size", "1").is_err());
|
||||||
|
// Out-of-range values are clamped rather than rejected.
|
||||||
|
assert_eq!(set_option(&c, "ring.size", "99999").unwrap().ring.size, 800.0);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn flags_cover_all_effects() {
|
||||||
|
let mut c = Config::default();
|
||||||
|
for e in EFFECTS {
|
||||||
|
assert!(flag(&mut c, e).is_some(), "{e}");
|
||||||
|
}
|
||||||
|
assert!(flag(&mut c, "nope").is_none());
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,204 @@
|
|||||||
|
//! Backend-independent daemon core: owns the engine and the live config, applies
|
||||||
|
//! commands, hot-reloads the config file, plays sounds and keeps the tray in sync.
|
||||||
|
|
||||||
|
use crate::audio::Audio;
|
||||||
|
use crate::config::Config;
|
||||||
|
use crate::control::{self, Command, Hub};
|
||||||
|
use crate::engine::Engine;
|
||||||
|
use crate::i18n::Lang;
|
||||||
|
use crate::input::{Action, InputEvent};
|
||||||
|
use crate::text::Fonts;
|
||||||
|
use crate::tray::TrayIcon;
|
||||||
|
use std::process::Child;
|
||||||
|
use std::sync::mpsc::Receiver;
|
||||||
|
use std::time::{Instant, SystemTime};
|
||||||
|
|
||||||
|
pub struct Core {
|
||||||
|
pub engine: Engine,
|
||||||
|
pub cfg: Config,
|
||||||
|
pub quit: bool,
|
||||||
|
rx: Receiver<Command>,
|
||||||
|
hub: Hub,
|
||||||
|
start: Instant,
|
||||||
|
cfg_mtime: Option<SystemTime>,
|
||||||
|
next_cfg_check: f64,
|
||||||
|
audio: Audio,
|
||||||
|
tray: Option<ksni::blocking::Handle<TrayIcon>>,
|
||||||
|
settings: Option<Child>,
|
||||||
|
term: Option<std::sync::Arc<std::sync::atomic::AtomicBool>>,
|
||||||
|
/// Set whenever a command or config reload may have changed what must be drawn.
|
||||||
|
changed: bool,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Core {
|
||||||
|
pub fn new(cfg: Config, hub: Hub, rx: Receiver<Command>) -> Self {
|
||||||
|
Self {
|
||||||
|
engine: Engine::new(cfg.clone(), Fonts::load()),
|
||||||
|
cfg_mtime: Config::mtime(),
|
||||||
|
cfg,
|
||||||
|
quit: false,
|
||||||
|
rx,
|
||||||
|
hub,
|
||||||
|
start: Instant::now(),
|
||||||
|
next_cfg_check: 0.0,
|
||||||
|
audio: Audio::new(),
|
||||||
|
tray: None,
|
||||||
|
settings: None,
|
||||||
|
term: None,
|
||||||
|
changed: false,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Quit when this flag is set (SIGINT/SIGTERM handlers raise it).
|
||||||
|
pub fn set_term_flag(&mut self, f: std::sync::Arc<std::sync::atomic::AtomicBool>) {
|
||||||
|
self.term = Some(f);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Seconds on the daemon's monotonic clock.
|
||||||
|
pub fn now(&self) -> f64 {
|
||||||
|
self.start.elapsed().as_secs_f64()
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn hub(&self) -> Hub {
|
||||||
|
self.hub.clone()
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn start_tray(&mut self) {
|
||||||
|
use ksni::blocking::TrayMethods;
|
||||||
|
let tray = TrayIcon { cfg: self.cfg.clone(), lang: Lang::resolve(&self.cfg.general.language), hub: self.hub.clone() };
|
||||||
|
match tray.spawn() {
|
||||||
|
Ok(h) => self.tray = Some(h),
|
||||||
|
Err(e) => log::warn!("no system tray ({e}); control the daemon with the `sourizz` CLI or hotkeys"),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn sync_tray(&self) {
|
||||||
|
if let Some(h) = &self.tray {
|
||||||
|
let (cfg, lang) = (self.cfg.clone(), Lang::resolve(&self.cfg.general.language));
|
||||||
|
let _ = h.update(move |t: &mut TrayIcon| {
|
||||||
|
t.cfg = cfg;
|
||||||
|
t.lang = lang;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Process queued commands and reload the config file if it changed. Call every loop turn.
|
||||||
|
/// Returns true when something happened that needs a repaint.
|
||||||
|
pub fn pump(&mut self) -> bool {
|
||||||
|
if self.term.as_ref().is_some_and(|t| t.load(std::sync::atomic::Ordering::Relaxed)) {
|
||||||
|
self.quit = true;
|
||||||
|
}
|
||||||
|
while let Ok(cmd) = self.rx.try_recv() {
|
||||||
|
self.apply(cmd);
|
||||||
|
}
|
||||||
|
let now = self.now();
|
||||||
|
if now >= self.next_cfg_check {
|
||||||
|
self.next_cfg_check = now + 0.4;
|
||||||
|
let m = Config::mtime();
|
||||||
|
if m != self.cfg_mtime {
|
||||||
|
self.cfg_mtime = m;
|
||||||
|
self.reload();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
std::mem::take(&mut self.changed)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn reload(&mut self) {
|
||||||
|
let cfg = Config::load();
|
||||||
|
if cfg != self.cfg {
|
||||||
|
log::info!("config reloaded");
|
||||||
|
self.changed = true;
|
||||||
|
self.cfg = cfg;
|
||||||
|
self.engine.set_config(self.cfg.clone());
|
||||||
|
self.sync_tray();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Apply the in-memory config to the engine and persist it.
|
||||||
|
fn commit(&mut self) {
|
||||||
|
self.cfg.sanitize();
|
||||||
|
self.engine.set_config(self.cfg.clone());
|
||||||
|
if let Err(e) = self.cfg.save() {
|
||||||
|
log::warn!("cannot save config: {e}");
|
||||||
|
}
|
||||||
|
self.cfg_mtime = Config::mtime();
|
||||||
|
self.sync_tray();
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn apply(&mut self, cmd: Command) {
|
||||||
|
self.changed = true;
|
||||||
|
let now = self.now();
|
||||||
|
match cmd {
|
||||||
|
Command::Toggle(name) => match control::flag(&mut self.cfg, &name) {
|
||||||
|
Some(f) => {
|
||||||
|
*f = !*f;
|
||||||
|
self.commit();
|
||||||
|
}
|
||||||
|
None => log::warn!("unknown effect {name}"),
|
||||||
|
},
|
||||||
|
Command::Set(name, v) => match control::flag(&mut self.cfg, &name) {
|
||||||
|
Some(f) if *f != v => {
|
||||||
|
*f = v;
|
||||||
|
self.commit();
|
||||||
|
}
|
||||||
|
Some(_) => {}
|
||||||
|
None => log::warn!("unknown effect {name}"),
|
||||||
|
},
|
||||||
|
Command::SetOption(k, v) => match control::set_option(&self.cfg, &k, &v) {
|
||||||
|
Ok(c) => {
|
||||||
|
self.cfg = c;
|
||||||
|
self.commit();
|
||||||
|
}
|
||||||
|
Err(e) => log::warn!("set {k}: {e}"),
|
||||||
|
},
|
||||||
|
Command::ShowClick => self.engine.show_click(now),
|
||||||
|
Command::AnnotateToggle => self.engine.toggle_annotation_mode(),
|
||||||
|
Command::AnnotateClear => self.engine.clear_annotations(),
|
||||||
|
Command::Reload => self.reload(),
|
||||||
|
Command::Status(tx) => {
|
||||||
|
let _ = tx.send(format!("running {} backend-config={}", self.engine.summary(), self.cfg.general.backend.id()));
|
||||||
|
}
|
||||||
|
Command::Settings => self.open_settings(),
|
||||||
|
Command::Quit => self.quit = true,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn handle_input(&mut self, ev: InputEvent) {
|
||||||
|
let now = self.now();
|
||||||
|
self.engine.handle(now, ev);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Run the sound side effects and hand everything else (capture changes) to the backend.
|
||||||
|
pub fn drain_actions(&mut self) -> Vec<Action> {
|
||||||
|
let mut rest = Vec::new();
|
||||||
|
for a in self.engine.take_actions() {
|
||||||
|
match a {
|
||||||
|
Action::PlayClick(b, pressed) => self.audio.play(&self.cfg.sound, b, pressed),
|
||||||
|
other => rest.push(other),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
rest
|
||||||
|
}
|
||||||
|
|
||||||
|
fn open_settings(&mut self) {
|
||||||
|
if let Some(c) = &mut self.settings {
|
||||||
|
if matches!(c.try_wait(), Ok(None)) {
|
||||||
|
return; // already open
|
||||||
|
}
|
||||||
|
}
|
||||||
|
let sibling = std::env::current_exe().ok().map(|p| p.with_file_name("sourizz-settings")).filter(|p| p.is_file());
|
||||||
|
let program = sibling.unwrap_or_else(|| "sourizz-settings".into());
|
||||||
|
match std::process::Command::new(&program).spawn() {
|
||||||
|
Ok(c) => self.settings = Some(c),
|
||||||
|
Err(e) => log::warn!("cannot start {}: {e} (is the settings window installed?)", program.display()),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Drop for Core {
|
||||||
|
fn drop(&mut self) {
|
||||||
|
if let Some(c) = &mut self.settings {
|
||||||
|
let _ = c.kill();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,200 @@
|
|||||||
|
//! Headless renderer: draws each effect over a sample background and writes PNGs.
|
||||||
|
//! Used for visual checks and for the screenshots in the README.
|
||||||
|
|
||||||
|
use crate::annot::Tool;
|
||||||
|
use crate::config::*;
|
||||||
|
use crate::engine::Engine;
|
||||||
|
use crate::geom::IRect;
|
||||||
|
use crate::input::{Button, InputEvent, KeyEvent};
|
||||||
|
use crate::text::Fonts;
|
||||||
|
use anyhow::{Context, Result};
|
||||||
|
use std::path::Path;
|
||||||
|
use tiny_skia::{Pixmap, PixmapPaint, Transform};
|
||||||
|
|
||||||
|
const W: u32 = 760;
|
||||||
|
const H: u32 = 300;
|
||||||
|
|
||||||
|
fn background() -> Pixmap {
|
||||||
|
let mut bg = Pixmap::new(W, H).unwrap();
|
||||||
|
let data = bg.data_mut();
|
||||||
|
for y in 0..H as usize {
|
||||||
|
for x in 0..W as usize {
|
||||||
|
let i = (y * W as usize + x) * 4;
|
||||||
|
let t = x as f32 / W as f32;
|
||||||
|
// Soft slate gradient with a faint grid, vaguely like a document or desktop.
|
||||||
|
let grid = if x % 40 == 0 || y % 40 == 0 { 14.0 } else { 0.0 };
|
||||||
|
data[i] = (52.0 + 40.0 * t + grid) as u8;
|
||||||
|
data[i + 1] = (62.0 + 36.0 * t + grid) as u8;
|
||||||
|
data[i + 2] = (84.0 + 50.0 * (1.0 - t) + grid) as u8;
|
||||||
|
data[i + 3] = 255;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
bg
|
||||||
|
}
|
||||||
|
|
||||||
|
fn key(name: &str, label: &str, text: Option<char>, mods: u8, pressed: bool) -> KeyEvent {
|
||||||
|
KeyEvent { pressed, name: name.into(), label: label.into(), text, mods, is_modifier: modifier_name(name), repeat: false }
|
||||||
|
}
|
||||||
|
|
||||||
|
fn modifier_name(n: &str) -> bool {
|
||||||
|
crate::input::modifier_bit(n).is_some()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Run `script` against a fresh engine and save the resulting frame at `t_end`.
|
||||||
|
fn shot(dir: &Path, name: &str, cfg: Config, t_end: f64, script: impl FnOnce(&mut Engine)) -> Result<()> {
|
||||||
|
let mut e = Engine::new(cfg, Fonts::load());
|
||||||
|
e.set_monitors(vec![IRect::new(0, 0, W as i32, H as i32)]);
|
||||||
|
script(&mut e);
|
||||||
|
let _ = e.begin_frame(t_end);
|
||||||
|
let mut layer = Pixmap::new(W, H).unwrap();
|
||||||
|
e.paint(&mut layer, IRect::new(0, 0, W as i32, H as i32), t_end);
|
||||||
|
let mut out = background();
|
||||||
|
out.draw_pixmap(0, 0, layer.as_ref(), &PixmapPaint::default(), Transform::identity(), None);
|
||||||
|
let path = dir.join(format!("{name}.png"));
|
||||||
|
out.save_png(&path).with_context(|| format!("writing {}", path.display()))?;
|
||||||
|
println!("{}", path.display());
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A smooth sweep from left to right, used by the trail shots.
|
||||||
|
fn sweep(e: &mut Engine, t0: f64, n: usize) {
|
||||||
|
for i in 0..n {
|
||||||
|
let f = i as f32 / (n - 1) as f32;
|
||||||
|
let x = 90.0 + f * 520.0;
|
||||||
|
let y = 150.0 + (f * 6.0).sin() * 70.0;
|
||||||
|
e.handle(t0 + i as f64 * 0.012, InputEvent::Pointer { x, y });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn run(dir: &Path) -> Result<()> {
|
||||||
|
std::fs::create_dir_all(dir)?;
|
||||||
|
let base = || {
|
||||||
|
let mut c = Config::default();
|
||||||
|
c.ring.pulse_speed = 0.0;
|
||||||
|
c
|
||||||
|
};
|
||||||
|
|
||||||
|
// Ring styles.
|
||||||
|
for style in RingStyle::ALL {
|
||||||
|
let mut c = base();
|
||||||
|
c.ring.style = *style;
|
||||||
|
shot(dir, &format!("ring_{}", style.id()), c, 0.0, |e| e.handle(0.0, InputEvent::Pointer { x: 380.0, y: 150.0 }))?;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Spotlight shapes.
|
||||||
|
for shape in SpotShape::ALL {
|
||||||
|
let mut c = base();
|
||||||
|
c.spotlight.enabled = true;
|
||||||
|
c.spotlight.shape = *shape;
|
||||||
|
c.spotlight.radius = if *shape == SpotShape::Circle { 110.0 } else { 55.0 };
|
||||||
|
shot(dir, &format!("spotlight_{}", shape.id()), c, 0.0, |e| e.handle(0.0, InputEvent::Pointer { x: 380.0, y: 150.0 }))?;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Trails.
|
||||||
|
for style in TrailStyle::ALL {
|
||||||
|
let mut c = base();
|
||||||
|
c.trail.enabled = true;
|
||||||
|
c.trail.style = *style;
|
||||||
|
c.trail.lifetime_ms = 900;
|
||||||
|
c.trail.size = if matches!(style, TrailStyle::Stars | TrailStyle::Kawaii | TrailStyle::Sparkles) { 26.0 } else { 20.0 };
|
||||||
|
shot(dir, &format!("trail_{}", style.id()), c, 0.62, |e| sweep(e, 0.0, 50))?;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Click effects, mid-animation.
|
||||||
|
for style in ClickStyle::ALL {
|
||||||
|
let mut c = base();
|
||||||
|
c.clicks.style = *style;
|
||||||
|
c.clicks.size = 150.0;
|
||||||
|
c.clicks.thickness = 7.0;
|
||||||
|
c.ring.enabled = false;
|
||||||
|
shot(dir, &format!("click_{}", style.id()), c, 0.2, |e| {
|
||||||
|
e.handle(0.0, InputEvent::Pointer { x: 380.0, y: 150.0 });
|
||||||
|
e.handle(0.0, InputEvent::Button { button: Button::Left, pressed: true });
|
||||||
|
})?;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Shake to locate.
|
||||||
|
{
|
||||||
|
let c = base();
|
||||||
|
shot(dir, "shake", c, 0.7, |e| {
|
||||||
|
for i in 0..16 {
|
||||||
|
let x = if i % 2 == 0 { 220.0 } else { 520.0 };
|
||||||
|
e.handle(0.5 + i as f64 * 0.02, InputEvent::Pointer { x, y: 150.0 });
|
||||||
|
}
|
||||||
|
})?;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Keystroke visualiser styles.
|
||||||
|
for style in KeyStyle::ALL {
|
||||||
|
let mut c = base();
|
||||||
|
c.keystrokes.enabled = true;
|
||||||
|
c.keystrokes.style = *style;
|
||||||
|
c.keystrokes.size = 24.0;
|
||||||
|
c.ring.enabled = false;
|
||||||
|
shot(dir, &format!("keys_{}", style.id()), c, 0.5, |e| {
|
||||||
|
e.handle(0.0, InputEvent::Pointer { x: 380.0, y: 100.0 });
|
||||||
|
for (i, ch) in "hello".chars().enumerate() {
|
||||||
|
e.handle(0.05 * i as f64, InputEvent::Key(key(&ch.to_string(), &ch.to_uppercase().to_string(), Some(ch), 0, true)));
|
||||||
|
}
|
||||||
|
e.handle(0.3, InputEvent::Key(key("t", "T", Some('t'), MOD_CTRL | MOD_SHIFT, true)));
|
||||||
|
e.handle(0.4, InputEvent::Key(key("Return", "Enter", None, 0, true)));
|
||||||
|
})?;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Annotation mode with every tool.
|
||||||
|
{
|
||||||
|
let mut c = base();
|
||||||
|
c.ring.enabled = false;
|
||||||
|
shot(dir, "annotate", c, 1.0, |e| {
|
||||||
|
e.handle(0.0, InputEvent::Pointer { x: 100.0, y: 200.0 });
|
||||||
|
e.toggle_annotation_mode();
|
||||||
|
let down = |e: &mut Engine, t: f64| e.handle(t, InputEvent::Button { button: Button::Left, pressed: true });
|
||||||
|
let up = |e: &mut Engine, t: f64| e.handle(t, InputEvent::Button { button: Button::Left, pressed: false });
|
||||||
|
// Pen scribble.
|
||||||
|
down(e, 0.1);
|
||||||
|
for i in 0..40 {
|
||||||
|
let f = i as f32 / 39.0;
|
||||||
|
e.handle(0.1 + f as f64 * 0.2, InputEvent::Pointer { x: 100.0 + f * 260.0, y: 200.0 + (f * 9.0).sin() * 30.0 });
|
||||||
|
}
|
||||||
|
up(e, 0.4);
|
||||||
|
// Highlighter underline.
|
||||||
|
e.annot.tool = Tool::Highlighter;
|
||||||
|
e.annot.color_idx = 2;
|
||||||
|
e.handle(0.5, InputEvent::Pointer { x: 400.0, y: 130.0 });
|
||||||
|
down(e, 0.5);
|
||||||
|
e.handle(0.6, InputEvent::Pointer { x: 560.0, y: 132.0 });
|
||||||
|
e.handle(0.7, InputEvent::Pointer { x: 700.0, y: 130.0 });
|
||||||
|
up(e, 0.7);
|
||||||
|
// Callouts.
|
||||||
|
e.annot.tool = Tool::Callout;
|
||||||
|
e.annot.color_idx = 4;
|
||||||
|
for (i, (x, y)) in [(420.0, 220.0), (500.0, 240.0), (580.0, 220.0)].iter().enumerate() {
|
||||||
|
e.handle(0.8, InputEvent::Pointer { x: *x, y: *y });
|
||||||
|
down(e, 0.8 + i as f64 * 0.01);
|
||||||
|
up(e, 0.81 + i as f64 * 0.01);
|
||||||
|
}
|
||||||
|
// Text.
|
||||||
|
e.annot.tool = Tool::Text;
|
||||||
|
e.annot.color_idx = 0;
|
||||||
|
e.handle(0.9, InputEvent::Pointer { x: 130.0, y: 270.0 });
|
||||||
|
down(e, 0.9);
|
||||||
|
up(e, 0.91);
|
||||||
|
for ch in "Look here!".chars() {
|
||||||
|
e.handle(0.92, InputEvent::Key(key(&ch.to_string(), &ch.to_string(), Some(ch), 0, true)));
|
||||||
|
}
|
||||||
|
e.handle(0.93, InputEvent::Key(key("Return", "Enter", None, 0, true)));
|
||||||
|
})?;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Focus mode.
|
||||||
|
{
|
||||||
|
let mut c = base();
|
||||||
|
c.focus.enabled = true;
|
||||||
|
c.ring.enabled = false;
|
||||||
|
shot(dir, "focus", c, 0.0, |e| {
|
||||||
|
e.handle(0.0, InputEvent::Pointer { x: 380.0, y: 150.0 });
|
||||||
|
e.set_focus_rect(Some(IRect::new(180, 60, 580, 240)));
|
||||||
|
})?;
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
@@ -0,0 +1,210 @@
|
|||||||
|
//! Global pointer and keyboard events on Wayland, read straight from `/dev/input/event*`.
|
||||||
|
//!
|
||||||
|
//! Wayland deliberately hides input that happens in other applications, so this is the one
|
||||||
|
//! compositor-independent way to see clicks and keystrokes. It needs read access to the
|
||||||
|
//! input devices, i.e. membership of the `input` group (a real security trade-off: any
|
||||||
|
//! program running as that user could then read keystrokes, which is why this is opt-in
|
||||||
|
//! and documented in the README).
|
||||||
|
//!
|
||||||
|
//! Devices report *relative* motion, never an absolute position; see `wlsrc` for how the
|
||||||
|
//! pointer position is obtained.
|
||||||
|
|
||||||
|
use crate::input::Button;
|
||||||
|
use rustix::fd::{AsFd, BorrowedFd};
|
||||||
|
use std::path::PathBuf;
|
||||||
|
|
||||||
|
pub const EV_KEY: u16 = 1;
|
||||||
|
pub const EV_REL: u16 = 2;
|
||||||
|
pub const EV_ABS: u16 = 3;
|
||||||
|
pub const REL_X: u16 = 0;
|
||||||
|
pub const REL_Y: u16 = 1;
|
||||||
|
pub const BTN_LEFT: u16 = 0x110;
|
||||||
|
pub const BTN_RIGHT: u16 = 0x111;
|
||||||
|
pub const BTN_MIDDLE: u16 = 0x112;
|
||||||
|
|
||||||
|
#[derive(Clone, Debug, PartialEq)]
|
||||||
|
pub enum Raw {
|
||||||
|
/// Relative motion in device units.
|
||||||
|
Motion(f32, f32),
|
||||||
|
/// The pointer moved but this device (a touchpad) cannot say by how much.
|
||||||
|
MotionHint,
|
||||||
|
Button(Button, bool),
|
||||||
|
/// Keyboard key by evdev code (add 8 for the X/xkb keycode).
|
||||||
|
Key {
|
||||||
|
code: u32,
|
||||||
|
pressed: bool,
|
||||||
|
repeat: bool,
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Map a Linux button code to ours.
|
||||||
|
pub fn button_from_code(code: u16) -> Option<Button> {
|
||||||
|
match code {
|
||||||
|
BTN_LEFT => Some(Button::Left),
|
||||||
|
BTN_RIGHT => Some(Button::Right),
|
||||||
|
BTN_MIDDLE => Some(Button::Middle),
|
||||||
|
0x113..=0x117 => Some(Button::Other),
|
||||||
|
_ => None,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Turn a batch of raw `(type, code, value)` triples into our events, in order, merging
|
||||||
|
/// consecutive relative motion into one event.
|
||||||
|
pub fn translate(events: impl IntoIterator<Item = (u16, u16, i32)>) -> Vec<Raw> {
|
||||||
|
let mut out = Vec::new();
|
||||||
|
let (mut dx, mut dy) = (0f32, 0f32);
|
||||||
|
let mut hint = false;
|
||||||
|
let flush = |out: &mut Vec<Raw>, dx: &mut f32, dy: &mut f32, hint: &mut bool| {
|
||||||
|
if *dx != 0.0 || *dy != 0.0 {
|
||||||
|
out.push(Raw::Motion(*dx, *dy));
|
||||||
|
} else if *hint {
|
||||||
|
out.push(Raw::MotionHint);
|
||||||
|
}
|
||||||
|
(*dx, *dy, *hint) = (0.0, 0.0, false);
|
||||||
|
};
|
||||||
|
for (ty, code, value) in events {
|
||||||
|
match ty {
|
||||||
|
EV_REL if code == REL_X => dx += value as f32,
|
||||||
|
EV_REL if code == REL_Y => dy += value as f32,
|
||||||
|
EV_ABS if code <= 1 => hint = true,
|
||||||
|
EV_KEY => {
|
||||||
|
flush(&mut out, &mut dx, &mut dy, &mut hint);
|
||||||
|
if let Some(b) = button_from_code(code) {
|
||||||
|
if value != 2 {
|
||||||
|
out.push(Raw::Button(b, value == 1));
|
||||||
|
}
|
||||||
|
} else if code < 0x100 {
|
||||||
|
out.push(Raw::Key { code: code as u32, pressed: value != 0, repeat: value == 2 });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
_ => {}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
flush(&mut out, &mut dx, &mut dy, &mut hint);
|
||||||
|
out
|
||||||
|
}
|
||||||
|
|
||||||
|
pub struct Devices {
|
||||||
|
devs: Vec<(PathBuf, evdev::Device)>,
|
||||||
|
/// Devices that exist but could not be opened (permission denied).
|
||||||
|
pub denied: usize,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Devices {
|
||||||
|
pub fn scan() -> Devices {
|
||||||
|
let mut d = Devices { devs: Vec::new(), denied: 0 };
|
||||||
|
d.rescan();
|
||||||
|
d
|
||||||
|
}
|
||||||
|
|
||||||
|
fn interesting(dev: &evdev::Device) -> bool {
|
||||||
|
use evdev::{KeyCode, RelativeAxisCode};
|
||||||
|
let keys = dev.supported_keys();
|
||||||
|
let pointer = keys.is_some_and(|k| k.contains(KeyCode::BTN_LEFT))
|
||||||
|
&& (dev.supported_relative_axes().is_some_and(|a| a.contains(RelativeAxisCode::REL_X))
|
||||||
|
|| dev.supported_absolute_axes().is_some());
|
||||||
|
let keyboard = keys.is_some_and(|k| k.contains(KeyCode::KEY_A) && k.contains(KeyCode::KEY_SPACE));
|
||||||
|
pointer || keyboard
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Open any readable input device we do not have yet (cheap enough to call every few seconds).
|
||||||
|
pub fn rescan(&mut self) {
|
||||||
|
let Ok(dir) = std::fs::read_dir("/dev/input") else { return };
|
||||||
|
let mut denied = 0;
|
||||||
|
for entry in dir.flatten() {
|
||||||
|
let path = entry.path();
|
||||||
|
let is_event = path.file_name().and_then(|n| n.to_str()).is_some_and(|n| n.starts_with("event"));
|
||||||
|
if !is_event || self.devs.iter().any(|(p, _)| *p == path) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
match evdev::Device::open(&path) {
|
||||||
|
Ok(dev) if Self::interesting(&dev) => {
|
||||||
|
if dev.set_nonblocking(true).is_ok() {
|
||||||
|
log::debug!("input device {} ({})", path.display(), dev.name().unwrap_or("?"));
|
||||||
|
self.devs.push((path, dev));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Ok(_) => {}
|
||||||
|
Err(e) if e.kind() == std::io::ErrorKind::PermissionDenied => denied += 1,
|
||||||
|
Err(_) => {}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if self.devs.is_empty() {
|
||||||
|
self.denied = denied;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn len(&self) -> usize {
|
||||||
|
self.devs.len()
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn is_empty(&self) -> bool {
|
||||||
|
self.devs.is_empty()
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn fds(&self) -> Vec<BorrowedFd<'_>> {
|
||||||
|
self.devs.iter().map(|(_, d)| d.as_fd()).collect()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Drain device `i`. A device that disappeared (unplugged) is dropped.
|
||||||
|
pub fn read(&mut self, i: usize) -> Vec<Raw> {
|
||||||
|
let Some((path, dev)) = self.devs.get_mut(i) else { return Vec::new() };
|
||||||
|
let result = dev.fetch_events().map(|it| it.map(|e| (e.event_type().0, e.code(), e.value())).collect::<Vec<_>>());
|
||||||
|
match result {
|
||||||
|
Ok(events) => translate(events),
|
||||||
|
Err(e) if e.kind() == std::io::ErrorKind::WouldBlock => Vec::new(),
|
||||||
|
Err(e) => {
|
||||||
|
log::debug!("dropping input device {}: {e}", path.display());
|
||||||
|
self.devs.remove(i);
|
||||||
|
Vec::new()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn relative_motion_is_summed_and_ordered_with_buttons() {
|
||||||
|
let evs =
|
||||||
|
[(EV_REL, REL_X, 3), (EV_REL, REL_Y, -2), (EV_REL, REL_X, 4), (EV_KEY, BTN_LEFT, 1), (EV_REL, REL_X, 1), (EV_KEY, BTN_LEFT, 0)];
|
||||||
|
assert_eq!(
|
||||||
|
translate(evs),
|
||||||
|
vec![Raw::Motion(7.0, -2.0), Raw::Button(Button::Left, true), Raw::Motion(1.0, 0.0), Raw::Button(Button::Left, false),]
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn keys_and_repeats() {
|
||||||
|
let evs = [(EV_KEY, 30, 1), (EV_KEY, 30, 2), (EV_KEY, 30, 0), (EV_KEY, BTN_RIGHT, 1), (EV_KEY, BTN_RIGHT, 2)];
|
||||||
|
assert_eq!(
|
||||||
|
translate(evs),
|
||||||
|
vec![
|
||||||
|
Raw::Key { code: 30, pressed: true, repeat: false },
|
||||||
|
Raw::Key { code: 30, pressed: true, repeat: true },
|
||||||
|
Raw::Key { code: 30, pressed: false, repeat: false },
|
||||||
|
Raw::Button(Button::Right, true),
|
||||||
|
],
|
||||||
|
"button auto-repeat (value 2) is ignored, key repeat is flagged"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn touchpad_motion_is_only_a_hint() {
|
||||||
|
assert_eq!(translate([(EV_ABS, 0, 1200), (EV_ABS, 1, 800)]), vec![Raw::MotionHint]);
|
||||||
|
assert_eq!(translate([(EV_ABS, 0, 1200), (EV_REL, REL_X, 2)]), vec![Raw::Motion(2.0, 0.0)]);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn unrelated_events_are_dropped() {
|
||||||
|
assert!(translate([(0, 0, 0), (EV_REL, 8, 1), (EV_KEY, 0x14a, 1)]).is_empty());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn side_buttons_map_to_other() {
|
||||||
|
assert_eq!(button_from_code(0x113), Some(Button::Other));
|
||||||
|
assert_eq!(button_from_code(0x118), None);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,236 @@
|
|||||||
|
//! Drawing primitives shared by the effects (all on premultiplied tiny-skia pixmaps).
|
||||||
|
|
||||||
|
use tiny_skia::{
|
||||||
|
FillRule, GradientStop, LineCap, LineJoin, LinearGradient, Paint, Path, PathBuilder, Pixmap, Point, RadialGradient, Rect, SpreadMode,
|
||||||
|
Stroke, Transform,
|
||||||
|
};
|
||||||
|
|
||||||
|
pub fn solid(c: tiny_skia::Color) -> Paint<'static> {
|
||||||
|
let mut p = Paint::default();
|
||||||
|
p.set_color(c);
|
||||||
|
p.anti_alias = true;
|
||||||
|
p
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Fill an axis-aligned rect given in global coordinates. The rect is translated by hand and
|
||||||
|
/// drawn with an identity transform and no anti-aliasing: tiny-skia then takes its fast
|
||||||
|
/// span-blitting path instead of converting the rect to an anti-aliased path (several times
|
||||||
|
/// slower, and these fills cover large areas every frame).
|
||||||
|
fn fill_rect_fast(pm: &mut Pixmap, tf: Transform, rect: Rect, mut paint: Paint) {
|
||||||
|
if rect.width() <= 0.0 || rect.height() <= 0.0 {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
paint.anti_alias = false;
|
||||||
|
if let Some(local) = rect.transform(Transform::from_translate(tf.tx, tf.ty)) {
|
||||||
|
pm.fill_rect(local, &paint, Transform::identity(), None);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn circle(cx: f32, cy: f32, r: f32) -> Option<Path> {
|
||||||
|
PathBuilder::from_circle(cx, cy, r.max(0.01))
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn fill_circle(pm: &mut Pixmap, tf: Transform, cx: f32, cy: f32, r: f32, c: tiny_skia::Color) {
|
||||||
|
if let Some(p) = circle(cx, cy, r) {
|
||||||
|
pm.fill_path(&p, &solid(c), FillRule::Winding, tf, None);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn stroke_circle(pm: &mut Pixmap, tf: Transform, cx: f32, cy: f32, r: f32, width: f32, c: tiny_skia::Color) {
|
||||||
|
if let Some(p) = circle(cx, cy, r) {
|
||||||
|
let s = Stroke { width: width.max(0.1), ..Stroke::default() };
|
||||||
|
pm.stroke_path(&p, &solid(c), &s, tf, None);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn stroke_line(
|
||||||
|
pm: &mut Pixmap,
|
||||||
|
tf: Transform,
|
||||||
|
a: (f32, f32),
|
||||||
|
b: (f32, f32),
|
||||||
|
width: f32,
|
||||||
|
c: tiny_skia::Color,
|
||||||
|
blend: tiny_skia::BlendMode,
|
||||||
|
) {
|
||||||
|
let mut pb = PathBuilder::new();
|
||||||
|
pb.move_to(a.0, a.1);
|
||||||
|
pb.line_to(b.0, b.1);
|
||||||
|
if let Some(p) = pb.finish() {
|
||||||
|
let mut paint = solid(c);
|
||||||
|
paint.blend_mode = blend;
|
||||||
|
let s = Stroke { width: width.max(0.1), line_cap: LineCap::Round, line_join: LineJoin::Round, ..Stroke::default() };
|
||||||
|
pm.stroke_path(&p, &paint, &s, tf, None);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Regular star with `points` tips.
|
||||||
|
pub fn star(cx: f32, cy: f32, r_out: f32, r_in: f32, points: u32, rot: f32) -> Option<Path> {
|
||||||
|
let mut pb = PathBuilder::new();
|
||||||
|
for i in 0..points * 2 {
|
||||||
|
let a = rot + std::f32::consts::PI * i as f32 / points as f32 - std::f32::consts::FRAC_PI_2;
|
||||||
|
let r = if i % 2 == 0 { r_out } else { r_in };
|
||||||
|
let (x, y) = (cx + r * a.cos(), cy + r * a.sin());
|
||||||
|
if i == 0 {
|
||||||
|
pb.move_to(x, y);
|
||||||
|
} else {
|
||||||
|
pb.line_to(x, y);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
pb.close();
|
||||||
|
pb.finish()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Concave four-pointed sparkle.
|
||||||
|
pub fn sparkle(cx: f32, cy: f32, r: f32, rot: f32) -> Option<Path> {
|
||||||
|
let mut pb = PathBuilder::new();
|
||||||
|
let pt = |ang: f32, rad: f32| (cx + rad * (ang + rot).cos(), cy + rad * (ang + rot).sin());
|
||||||
|
let tips = [0.0f32, 90.0, 180.0, 270.0].map(f32::to_radians);
|
||||||
|
let (x, y) = pt(tips[0], r);
|
||||||
|
pb.move_to(x, y);
|
||||||
|
for i in 0..4 {
|
||||||
|
let mid = tips[i] + std::f32::consts::FRAC_PI_4;
|
||||||
|
let next = tips[(i + 1) % 4];
|
||||||
|
let (cx2, cy2) = pt(mid, r * 0.12);
|
||||||
|
let (nx, ny) = pt(next, r);
|
||||||
|
pb.quad_to(cx2, cy2, nx, ny);
|
||||||
|
}
|
||||||
|
pb.close();
|
||||||
|
pb.finish()
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn heart(cx: f32, cy: f32, s: f32) -> Option<Path> {
|
||||||
|
// Unit heart scaled so its width is roughly 2*s.
|
||||||
|
let mut pb = PathBuilder::new();
|
||||||
|
pb.move_to(cx, cy + s * 0.95);
|
||||||
|
pb.cubic_to(cx - s * 1.6, cy - s * 0.1, cx - s * 0.7, cy - s * 1.15, cx, cy - s * 0.35);
|
||||||
|
pb.cubic_to(cx + s * 0.7, cy - s * 1.15, cx + s * 1.6, cy - s * 0.1, cx, cy + s * 0.95);
|
||||||
|
pb.close();
|
||||||
|
pb.finish()
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn rounded_rect(x: f32, y: f32, w: f32, h: f32, r: f32) -> Option<Path> {
|
||||||
|
let r = r.min(w / 2.0).min(h / 2.0).max(0.0);
|
||||||
|
let k = r * 0.5523;
|
||||||
|
let mut pb = PathBuilder::new();
|
||||||
|
pb.move_to(x + r, y);
|
||||||
|
pb.line_to(x + w - r, y);
|
||||||
|
pb.cubic_to(x + w - r + k, y, x + w, y + r - k, x + w, y + r);
|
||||||
|
pb.line_to(x + w, y + h - r);
|
||||||
|
pb.cubic_to(x + w, y + h - r + k, x + w - r + k, y + h, x + w - r, y + h);
|
||||||
|
pb.line_to(x + r, y + h);
|
||||||
|
pb.cubic_to(x + r - k, y + h, x, y + h - r + k, x, y + h - r);
|
||||||
|
pb.line_to(x, y + r);
|
||||||
|
pb.cubic_to(x, y + r - k, x + r - k, y, x + r, y);
|
||||||
|
pb.close();
|
||||||
|
pb.finish()
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn fill_rrect(pm: &mut Pixmap, tf: Transform, x: f32, y: f32, w: f32, h: f32, r: f32, paint: &Paint) {
|
||||||
|
if let Some(p) = rounded_rect(x, y, w, h, r) {
|
||||||
|
pm.fill_path(&p, paint, FillRule::Winding, tf, None);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn stroke_rrect(pm: &mut Pixmap, tf: Transform, x: f32, y: f32, w: f32, h: f32, r: f32, width: f32, c: tiny_skia::Color) {
|
||||||
|
if let Some(p) = rounded_rect(x, y, w, h, r) {
|
||||||
|
let s = Stroke { width, ..Stroke::default() };
|
||||||
|
pm.stroke_path(&p, &solid(c), &s, tf, None);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// HSV (h in degrees, s/v in 0..1) → linear-ish sRGB triple in 0..1.
|
||||||
|
pub fn hsv(h: f32, s: f32, v: f32) -> [f32; 3] {
|
||||||
|
let h = h.rem_euclid(360.0) / 60.0;
|
||||||
|
let c = v * s;
|
||||||
|
let x = c * (1.0 - (h % 2.0 - 1.0).abs());
|
||||||
|
let (r, g, b) = match h as u32 {
|
||||||
|
0 => (c, x, 0.0),
|
||||||
|
1 => (x, c, 0.0),
|
||||||
|
2 => (0.0, c, x),
|
||||||
|
3 => (0.0, x, c),
|
||||||
|
4 => (x, 0.0, c),
|
||||||
|
_ => (c, 0.0, x),
|
||||||
|
};
|
||||||
|
let m = v - c;
|
||||||
|
[r + m, g + m, b + m]
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn rgba(rgb: [f32; 3], a: f32) -> tiny_skia::Color {
|
||||||
|
tiny_skia::Color::from_rgba(rgb[0].clamp(0.0, 1.0), rgb[1].clamp(0.0, 1.0), rgb[2].clamp(0.0, 1.0), a.clamp(0.0, 1.0))
|
||||||
|
.unwrap_or(tiny_skia::Color::TRANSPARENT)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn with_alpha(c: tiny_skia::Color, a: f32) -> tiny_skia::Color {
|
||||||
|
tiny_skia::Color::from_rgba(c.red(), c.green(), c.blue(), a.clamp(0.0, 1.0)).unwrap_or(tiny_skia::Color::TRANSPARENT)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Fill `area` with `dim`, leaving a soft-edged round hole at (cx, cy).
|
||||||
|
pub fn dim_with_circle(pm: &mut Pixmap, tf: Transform, area: Rect, cx: f32, cy: f32, radius: f32, softness: f32, dim: tiny_skia::Color) {
|
||||||
|
let feather = (radius * softness * 0.9).max(0.5);
|
||||||
|
let r_out = radius + feather * 0.5;
|
||||||
|
let r_in = (radius - feather * 0.5).max(0.0);
|
||||||
|
let stops = vec![
|
||||||
|
GradientStop::new(0.0, with_alpha(dim, 0.0)),
|
||||||
|
GradientStop::new((r_in / r_out).clamp(0.0, 0.999), with_alpha(dim, 0.0)),
|
||||||
|
GradientStop::new(1.0, dim),
|
||||||
|
];
|
||||||
|
let c = Point::from_xy(cx, cy);
|
||||||
|
// The shader lives in global coordinates; `tf` maps them into this pixmap.
|
||||||
|
if let Some(shader) = RadialGradient::new(c, 0.0, c, r_out, stops, SpreadMode::Pad, tf) {
|
||||||
|
fill_rect_fast(pm, tf, area, Paint { shader, ..Paint::default() });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Fill `area` with `dim`, leaving a soft-edged lit band centred on `centre`.
|
||||||
|
/// `horizontal` is a band that spans the width (varies with y). The band only exists inside
|
||||||
|
/// `span` (the pointer's monitor); everything else stays dimmed.
|
||||||
|
pub fn dim_with_bar(
|
||||||
|
pm: &mut Pixmap,
|
||||||
|
tf: Transform,
|
||||||
|
area: Rect,
|
||||||
|
span: Rect,
|
||||||
|
horizontal: bool,
|
||||||
|
centre: f32,
|
||||||
|
half: f32,
|
||||||
|
softness: f32,
|
||||||
|
dim: tiny_skia::Color,
|
||||||
|
) {
|
||||||
|
fill_rect_fast(pm, tf, area, solid(dim));
|
||||||
|
let (l, t) = (area.left().max(span.left()), area.top().max(span.top()));
|
||||||
|
let (r, b) = (area.right().min(span.right()), area.bottom().min(span.bottom()));
|
||||||
|
// Rect::from_ltrb accepts zero-width rects and tiny-skia then fills a 1px sliver.
|
||||||
|
if r <= l || b <= t {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
let Some(clip) = Rect::from_ltrb(l, t, r, b) else { return };
|
||||||
|
let feather = (half * softness * 0.9).max(0.5);
|
||||||
|
let h_out = half + feather * 0.5;
|
||||||
|
let edge = (feather / (2.0 * h_out)).clamp(0.0, 0.49);
|
||||||
|
let stops = vec![
|
||||||
|
GradientStop::new(0.0, dim),
|
||||||
|
GradientStop::new(edge, with_alpha(dim, 0.0)),
|
||||||
|
GradientStop::new(1.0 - edge, with_alpha(dim, 0.0)),
|
||||||
|
GradientStop::new(1.0, dim),
|
||||||
|
];
|
||||||
|
let (a, c) = if horizontal {
|
||||||
|
(Point::from_xy(0.0, centre - h_out), Point::from_xy(0.0, centre + h_out))
|
||||||
|
} else {
|
||||||
|
(Point::from_xy(centre - h_out, 0.0), Point::from_xy(centre + h_out, 0.0))
|
||||||
|
};
|
||||||
|
if let Some(shader) = LinearGradient::new(a, c, stops, SpreadMode::Pad, tf) {
|
||||||
|
// Source replaces the flat dim underneath, so the lit centre really becomes transparent.
|
||||||
|
fill_rect_fast(pm, tf, clip, Paint { shader, blend_mode: tiny_skia::BlendMode::Source, ..Paint::default() });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Fill `area` with `dim`, leaving a rounded-rect hole (even-odd).
|
||||||
|
pub fn dim_with_rect(pm: &mut Pixmap, tf: Transform, area: Rect, hole: Rect, corner: f32, dim: tiny_skia::Color) {
|
||||||
|
let mut pb = PathBuilder::new();
|
||||||
|
pb.push_rect(area);
|
||||||
|
if let Some(h) = rounded_rect(hole.x(), hole.y(), hole.width(), hole.height(), corner) {
|
||||||
|
pb.push_path(&h);
|
||||||
|
}
|
||||||
|
if let Some(p) = pb.finish() {
|
||||||
|
pm.fill_path(&p, &solid(dim), FillRule::EvenOdd, tf, None);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,79 @@
|
|||||||
|
//! Small integer-rectangle helper used for damage tracking and monitor layout.
|
||||||
|
|
||||||
|
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||||
|
pub struct IRect {
|
||||||
|
pub x0: i32,
|
||||||
|
pub y0: i32,
|
||||||
|
pub x1: i32,
|
||||||
|
pub y1: i32,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl IRect {
|
||||||
|
pub const fn new(x0: i32, y0: i32, x1: i32, y1: i32) -> Self {
|
||||||
|
Self { x0, y0, x1, y1 }
|
||||||
|
}
|
||||||
|
|
||||||
|
pub const fn from_xywh(x: i32, y: i32, w: i32, h: i32) -> Self {
|
||||||
|
Self { x0: x, y0: y, x1: x + w, y1: y + h }
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Smallest integer rect containing the float box `(l, t, r, b)`, padded by `pad`.
|
||||||
|
pub fn around(l: f32, t: f32, r: f32, b: f32, pad: f32) -> Self {
|
||||||
|
Self { x0: (l - pad).floor() as i32, y0: (t - pad).floor() as i32, x1: (r + pad).ceil() as i32, y1: (b + pad).ceil() as i32 }
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn centered(cx: f32, cy: f32, radius: f32) -> Self {
|
||||||
|
Self::around(cx, cy, cx, cy, radius)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn width(&self) -> i32 {
|
||||||
|
self.x1 - self.x0
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn height(&self) -> i32 {
|
||||||
|
self.y1 - self.y0
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn is_empty(&self) -> bool {
|
||||||
|
self.x1 <= self.x0 || self.y1 <= self.y0
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn union(self, o: IRect) -> IRect {
|
||||||
|
if self.is_empty() {
|
||||||
|
return o;
|
||||||
|
}
|
||||||
|
if o.is_empty() {
|
||||||
|
return self;
|
||||||
|
}
|
||||||
|
IRect::new(self.x0.min(o.x0), self.y0.min(o.y0), self.x1.max(o.x1), self.y1.max(o.y1))
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn intersect(self, o: IRect) -> IRect {
|
||||||
|
IRect::new(self.x0.max(o.x0), self.y0.max(o.y0), self.x1.min(o.x1), self.y1.min(o.y1))
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn contains(&self, x: f32, y: f32) -> bool {
|
||||||
|
x >= self.x0 as f32 && x < self.x1 as f32 && y >= self.y0 as f32 && y < self.y1 as f32
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn translate(self, dx: i32, dy: i32) -> IRect {
|
||||||
|
IRect::new(self.x0 + dx, self.y0 + dy, self.x1 + dx, self.y1 + dy)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn union_and_intersect() {
|
||||||
|
let a = IRect::new(0, 0, 10, 10);
|
||||||
|
let b = IRect::new(5, 5, 20, 8);
|
||||||
|
assert_eq!(a.union(b), IRect::new(0, 0, 20, 10));
|
||||||
|
assert_eq!(a.intersect(b), IRect::new(5, 5, 10, 8));
|
||||||
|
assert!(a.intersect(IRect::new(11, 0, 12, 1)).is_empty());
|
||||||
|
let empty = IRect::new(0, 0, 0, 0);
|
||||||
|
assert_eq!(empty.union(a), a);
|
||||||
|
assert_eq!(a.union(empty), a);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,192 @@
|
|||||||
|
//! English / French UI strings (tray menu and settings window).
|
||||||
|
|
||||||
|
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||||
|
pub enum Lang {
|
||||||
|
En,
|
||||||
|
Fr,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Lang {
|
||||||
|
/// Resolve the `general.language` setting (`auto`, `en`, `fr`) against the environment.
|
||||||
|
pub fn resolve(setting: &str) -> Lang {
|
||||||
|
match setting {
|
||||||
|
"fr" => Lang::Fr,
|
||||||
|
"en" => Lang::En,
|
||||||
|
_ => {
|
||||||
|
let env = ["LC_ALL", "LC_MESSAGES", "LANG", "LANGUAGE"]
|
||||||
|
.iter()
|
||||||
|
.find_map(|k| std::env::var(k).ok().filter(|v| !v.is_empty()))
|
||||||
|
.unwrap_or_default();
|
||||||
|
if env.to_ascii_lowercase().starts_with("fr") { Lang::Fr } else { Lang::En }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const TABLE: &[(&str, &str, &str)] = &[
|
||||||
|
// tray + general
|
||||||
|
("enabled", "Enabled", "Activé"),
|
||||||
|
("spotlight", "Spotlight", "Projecteur"),
|
||||||
|
("ring", "Ring cursor", "Anneau de curseur"),
|
||||||
|
("trail", "Cursor trail", "Traînée du curseur"),
|
||||||
|
("clicks", "Click effects", "Effets de clic"),
|
||||||
|
("sound", "Click sound", "Son de clic"),
|
||||||
|
("shake", "Shake to locate", "Secouer pour localiser"),
|
||||||
|
("annotate", "Hold-key drawing", "Dessin en maintenant une touche"),
|
||||||
|
("keystrokes", "Show keystrokes", "Afficher les frappes"),
|
||||||
|
("focus", "Focus mode", "Mode focus"),
|
||||||
|
("annotation_mode", "Annotation mode", "Mode annotation"),
|
||||||
|
("clear_annotations", "Clear annotations", "Effacer les annotations"),
|
||||||
|
("show_click", "Show click effect", "Afficher l'effet de clic"),
|
||||||
|
("settings", "Settings…", "Réglages…"),
|
||||||
|
("quit", "Quit", "Quitter"),
|
||||||
|
("effects", "Effects", "Effets"),
|
||||||
|
("styles", "Styles", "Styles"),
|
||||||
|
("spot_shape", "Spotlight shape", "Forme du projecteur"),
|
||||||
|
("ring_style", "Ring style", "Style de l'anneau"),
|
||||||
|
("trail_style", "Trail style", "Style de la traînée"),
|
||||||
|
("click_style", "Click effect", "Effet de clic"),
|
||||||
|
("key_style", "Keystroke style", "Style des frappes"),
|
||||||
|
// option values
|
||||||
|
("opt.circle", "Circle", "Cercle"),
|
||||||
|
("opt.hbar", "Horizontal bar", "Barre horizontale"),
|
||||||
|
("opt.vbar", "Vertical bar", "Barre verticale"),
|
||||||
|
("opt.classic", "Classic", "Classique"),
|
||||||
|
("opt.neon", "Neon", "Néon"),
|
||||||
|
("opt.comet", "Comet", "Comète"),
|
||||||
|
("opt.dots", "Dots", "Points"),
|
||||||
|
("opt.ribbon", "Ribbon", "Ruban"),
|
||||||
|
("opt.rainbow", "Rainbow", "Arc-en-ciel"),
|
||||||
|
("opt.stars", "Stars", "Étoiles"),
|
||||||
|
("opt.kawaii", "Kawaii", "Kawaii"),
|
||||||
|
("opt.sparkles", "Sparkles", "Paillettes"),
|
||||||
|
("opt.single_ring", "Single ring", "Anneau simple"),
|
||||||
|
("opt.ripple_wave", "Ripple wave", "Ondulation"),
|
||||||
|
("opt.burst", "Burst", "Éclat"),
|
||||||
|
("opt.pulse", "Pulse", "Pulsation"),
|
||||||
|
("opt.glass", "Glass", "Verre"),
|
||||||
|
("opt.keycaps", "Keycaps", "Touches"),
|
||||||
|
("opt.gradient", "Gradient", "Dégradé"),
|
||||||
|
("opt.minimal", "Minimal", "Minimal"),
|
||||||
|
("opt.auto", "Automatic", "Automatique"),
|
||||||
|
("opt.x11", "X11", "X11"),
|
||||||
|
("opt.wayland", "Wayland", "Wayland"),
|
||||||
|
("opt.bottom_center", "Bottom centre", "Bas centre"),
|
||||||
|
("opt.bottom_left", "Bottom left", "Bas gauche"),
|
||||||
|
("opt.bottom_right", "Bottom right", "Bas droite"),
|
||||||
|
("opt.top_center", "Top centre", "Haut centre"),
|
||||||
|
// settings window
|
||||||
|
("app.title", "Sourizz settings", "Réglages de Sourizz"),
|
||||||
|
("tab.effects", "Effects", "Effets"),
|
||||||
|
("tab.clicks", "Clicks & sound", "Clics et son"),
|
||||||
|
("tab.draw", "Drawing", "Dessin"),
|
||||||
|
("tab.keys", "Keystrokes & focus", "Frappes et focus"),
|
||||||
|
("tab.hotkeys", "Hotkeys", "Raccourcis"),
|
||||||
|
("tab.general", "General", "Général"),
|
||||||
|
("f.size", "Size", "Taille"),
|
||||||
|
("f.radius", "Radius", "Rayon"),
|
||||||
|
("f.thickness", "Thickness", "Épaisseur"),
|
||||||
|
("f.color", "Colour", "Couleur"),
|
||||||
|
("f.opacity", "Opacity", "Opacité"),
|
||||||
|
("f.softness", "Edge softness", "Douceur du bord"),
|
||||||
|
("f.fill", "Fill", "Remplissage"),
|
||||||
|
("f.pulse", "Pulse speed", "Vitesse de pulsation"),
|
||||||
|
("f.shape", "Shape", "Forme"),
|
||||||
|
("f.style", "Style", "Style"),
|
||||||
|
("f.lifetime", "Lifetime (ms)", "Durée (ms)"),
|
||||||
|
("f.duration", "Duration (ms)", "Durée (ms)"),
|
||||||
|
("f.show_on_clicks", "Show on mouse clicks", "Afficher aux clics de souris"),
|
||||||
|
("f.tap_key", "Tap key triggers effect", "Touche qui déclenche l'effet (appui bref)"),
|
||||||
|
("f.left", "Left button", "Bouton gauche"),
|
||||||
|
("f.middle", "Middle button", "Bouton du milieu"),
|
||||||
|
("f.right", "Right button", "Bouton droit"),
|
||||||
|
("f.volume", "Volume", "Volume"),
|
||||||
|
("f.sound_file", "Custom sound file (WAV)", "Fichier son personnalisé (WAV)"),
|
||||||
|
("f.on_release", "Also play on release", "Jouer aussi au relâchement"),
|
||||||
|
("f.sensitivity", "Sensitivity", "Sensibilité"),
|
||||||
|
("f.scale", "Enlarge by", "Agrandir de"),
|
||||||
|
("f.hold_key", "Hold key to draw", "Touche à maintenir pour dessiner"),
|
||||||
|
("f.width", "Pen width", "Épaisseur du stylo"),
|
||||||
|
("f.fade", "Fade strokes after release", "Faire disparaître les traits"),
|
||||||
|
("f.fade_ms", "Fade time (ms)", "Temps de disparition (ms)"),
|
||||||
|
("f.position", "Position", "Position"),
|
||||||
|
("f.only_shortcuts", "Only show shortcuts (hide plain typing)", "Seulement les raccourcis (masquer la saisie)"),
|
||||||
|
("f.accent", "Accent colour", "Couleur d'accent"),
|
||||||
|
("f.language", "Language", "Langue"),
|
||||||
|
("f.backend", "Display backend", "Serveur d'affichage"),
|
||||||
|
("f.fps", "Max frame rate", "Images/s maximum"),
|
||||||
|
(
|
||||||
|
"hotkeys.help",
|
||||||
|
"Format: Ctrl+Alt+Shift+S. Leave empty to disable. On Wayland, bind `sourizz toggle …` in your desktop's shortcut settings instead.",
|
||||||
|
"Format : Ctrl+Alt+Shift+S. Laisser vide pour désactiver. Sous Wayland, associez plutôt `sourizz toggle …` dans les raccourcis de votre bureau.",
|
||||||
|
),
|
||||||
|
("hk.toggle_all", "Toggle everything", "Tout activer / désactiver"),
|
||||||
|
("hk.annotate_mode", "Annotation mode", "Mode annotation"),
|
||||||
|
("hk.clear_annotations", "Clear annotations", "Effacer les annotations"),
|
||||||
|
("hk.show_click", "Show click effect", "Afficher l'effet de clic"),
|
||||||
|
(
|
||||||
|
"saved",
|
||||||
|
"Changes apply instantly and are saved automatically.",
|
||||||
|
"Les changements s'appliquent immédiatement et sont enregistrés automatiquement.",
|
||||||
|
),
|
||||||
|
(
|
||||||
|
"daemon_down",
|
||||||
|
"The Sourizz daemon is not running — start it with `sourizz`.",
|
||||||
|
"Le démon Sourizz n'est pas lancé — démarrez-le avec `sourizz`.",
|
||||||
|
),
|
||||||
|
("reset", "Reset to defaults", "Rétablir les valeurs par défaut"),
|
||||||
|
];
|
||||||
|
|
||||||
|
/// Look up a UI string; unknown keys come back as themselves so gaps are visible, not fatal.
|
||||||
|
pub fn t(lang: Lang, key: &'static str) -> &'static str {
|
||||||
|
TABLE.iter().find(|(k, _, _)| *k == key).map(|(_, en, fr)| if lang == Lang::Fr { *fr } else { *en }).unwrap_or(key)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Label for an enum value id such as `stars` or `ripple_wave`.
|
||||||
|
pub fn opt(lang: Lang, id: &str) -> String {
|
||||||
|
TABLE
|
||||||
|
.iter()
|
||||||
|
.find(|(k, _, _)| k.strip_prefix("opt.") == Some(id))
|
||||||
|
.map(|(_, en, fr)| (if lang == Lang::Fr { *fr } else { *en }).to_string())
|
||||||
|
.unwrap_or_else(|| id.to_string())
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
use crate::config::*;
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn keys_unique_and_filled() {
|
||||||
|
let mut seen = std::collections::HashSet::new();
|
||||||
|
for (k, en, fr) in TABLE {
|
||||||
|
assert!(seen.insert(*k), "duplicate key {k}");
|
||||||
|
assert!(!en.is_empty() && !fr.is_empty(), "empty text for {k}");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn every_enum_value_is_translated() {
|
||||||
|
let ids: Vec<&str> = BackendKind::ALL
|
||||||
|
.iter()
|
||||||
|
.map(|v| v.id())
|
||||||
|
.chain(SpotShape::ALL.iter().map(|v| v.id()))
|
||||||
|
.chain(RingStyle::ALL.iter().map(|v| v.id()))
|
||||||
|
.chain(TrailStyle::ALL.iter().map(|v| v.id()))
|
||||||
|
.chain(ClickStyle::ALL.iter().map(|v| v.id()))
|
||||||
|
.chain(KeyStyle::ALL.iter().map(|v| v.id()))
|
||||||
|
.chain(KeyPosition::ALL.iter().map(|v| v.id()))
|
||||||
|
.collect();
|
||||||
|
for id in ids {
|
||||||
|
assert_ne!(opt(Lang::En, id), id, "missing translation for option {id}");
|
||||||
|
assert_ne!(opt(Lang::Fr, id), id, "missing French translation for option {id}");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn french_differs() {
|
||||||
|
assert_eq!(t(Lang::En, "quit"), "Quit");
|
||||||
|
assert_eq!(t(Lang::Fr, "quit"), "Quitter");
|
||||||
|
assert_eq!(t(Lang::En, "no such key"), "no such key");
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,139 @@
|
|||||||
|
//! Backend-neutral input events fed to the effect engine.
|
||||||
|
|
||||||
|
use crate::config::{MOD_ALT, MOD_CTRL, MOD_SHIFT, MOD_SUPER};
|
||||||
|
|
||||||
|
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||||
|
pub enum Button {
|
||||||
|
Left,
|
||||||
|
Middle,
|
||||||
|
Right,
|
||||||
|
Other,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Clone, Debug)]
|
||||||
|
pub struct KeyEvent {
|
||||||
|
pub pressed: bool,
|
||||||
|
/// Key name in X keysym style (`Control_R`, `a`, `F5`, `Return`). Used to match config keys.
|
||||||
|
pub name: String,
|
||||||
|
/// Human-friendly label (`Ctrl`, `A`, `Enter`).
|
||||||
|
pub label: String,
|
||||||
|
/// Character the key produces right now, if it is printable.
|
||||||
|
pub text: Option<char>,
|
||||||
|
/// Modifier mask (`MOD_*`) held when the event happened, *excluding* this key itself.
|
||||||
|
pub mods: u8,
|
||||||
|
pub is_modifier: bool,
|
||||||
|
pub repeat: bool,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Clone, Debug)]
|
||||||
|
pub enum InputEvent {
|
||||||
|
/// Pointer position in global (virtual desktop) pixels.
|
||||||
|
Pointer {
|
||||||
|
x: f32,
|
||||||
|
y: f32,
|
||||||
|
},
|
||||||
|
Button {
|
||||||
|
button: Button,
|
||||||
|
pressed: bool,
|
||||||
|
},
|
||||||
|
Key(KeyEvent),
|
||||||
|
}
|
||||||
|
|
||||||
|
/// What the engine asks the backend to do.
|
||||||
|
#[derive(Clone, Debug, PartialEq)]
|
||||||
|
pub enum Action {
|
||||||
|
/// Play the click sound for this button (`true` = press, `false` = release).
|
||||||
|
PlayClick(Button, bool),
|
||||||
|
/// Enter or leave annotation capture mode (the overlay must take pointer + keyboard).
|
||||||
|
Capture(bool),
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Modifier bit for a keysym name, if it is a modifier key.
|
||||||
|
pub fn modifier_bit(name: &str) -> Option<u8> {
|
||||||
|
match name {
|
||||||
|
"Control_L" | "Control_R" => Some(MOD_CTRL),
|
||||||
|
"Shift_L" | "Shift_R" => Some(MOD_SHIFT),
|
||||||
|
"Alt_L" | "Alt_R" | "Meta_L" | "Meta_R" => Some(MOD_ALT),
|
||||||
|
"Super_L" | "Super_R" | "Hyper_L" | "Hyper_R" => Some(MOD_SUPER),
|
||||||
|
_ => None,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Display label for a keysym name.
|
||||||
|
pub fn label_for(name: &str) -> String {
|
||||||
|
let l = match name {
|
||||||
|
"Control_L" | "Control_R" => "Ctrl",
|
||||||
|
"Shift_L" | "Shift_R" => "Shift",
|
||||||
|
"Alt_L" | "Meta_L" | "Meta_R" => "Alt",
|
||||||
|
"Alt_R" | "ISO_Level3_Shift" => "AltGr",
|
||||||
|
"Super_L" | "Super_R" | "Hyper_L" | "Hyper_R" => "Super",
|
||||||
|
"Return" | "KP_Enter" => "Enter",
|
||||||
|
"BackSpace" => "Backspace",
|
||||||
|
"Escape" => "Esc",
|
||||||
|
"Tab" | "ISO_Left_Tab" => "Tab",
|
||||||
|
"space" => "Space",
|
||||||
|
"Delete" => "Del",
|
||||||
|
"Insert" => "Ins",
|
||||||
|
"Prior" => "PgUp",
|
||||||
|
"Next" => "PgDn",
|
||||||
|
"Home" => "Home",
|
||||||
|
"End" => "End",
|
||||||
|
"Left" => "←",
|
||||||
|
"Right" => "→",
|
||||||
|
"Up" => "↑",
|
||||||
|
"Down" => "↓",
|
||||||
|
"Caps_Lock" => "Caps",
|
||||||
|
"Num_Lock" => "Num",
|
||||||
|
"Scroll_Lock" => "ScrLk",
|
||||||
|
"Print" => "PrtSc",
|
||||||
|
"Pause" => "Pause",
|
||||||
|
"Menu" => "Menu",
|
||||||
|
"minus" => "-",
|
||||||
|
"plus" => "+",
|
||||||
|
"equal" => "=",
|
||||||
|
"comma" => ",",
|
||||||
|
"period" => ".",
|
||||||
|
"slash" => "/",
|
||||||
|
"backslash" => "\\",
|
||||||
|
"semicolon" => ";",
|
||||||
|
"apostrophe" => "'",
|
||||||
|
"grave" => "`",
|
||||||
|
"bracketleft" => "[",
|
||||||
|
"bracketright" => "]",
|
||||||
|
"asterisk" => "*",
|
||||||
|
"KP_Add" => "+",
|
||||||
|
"KP_Subtract" => "-",
|
||||||
|
"KP_Multiply" => "*",
|
||||||
|
"KP_Divide" => "/",
|
||||||
|
other => {
|
||||||
|
if let Some(d) = other.strip_prefix("KP_") {
|
||||||
|
return d.to_string();
|
||||||
|
}
|
||||||
|
if other.chars().count() == 1 {
|
||||||
|
return other.to_uppercase();
|
||||||
|
}
|
||||||
|
return other.to_string();
|
||||||
|
}
|
||||||
|
};
|
||||||
|
l.to_string()
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn labels() {
|
||||||
|
assert_eq!(label_for("Control_R"), "Ctrl");
|
||||||
|
assert_eq!(label_for("a"), "A");
|
||||||
|
assert_eq!(label_for("F5"), "F5");
|
||||||
|
assert_eq!(label_for("Return"), "Enter");
|
||||||
|
assert_eq!(label_for("KP_5"), "5");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn modifiers() {
|
||||||
|
assert_eq!(modifier_bit("Shift_L"), Some(MOD_SHIFT));
|
||||||
|
assert_eq!(modifier_bit("a"), None);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,107 @@
|
|||||||
|
//! Tiny line protocol over a Unix socket so the CLI (and your desktop's custom
|
||||||
|
//! shortcuts, which is how global hotkeys work on Wayland) can drive the daemon.
|
||||||
|
|
||||||
|
use crate::control::{Command, Hub, parse_line};
|
||||||
|
use std::io::{BufRead, BufReader, Write};
|
||||||
|
use std::os::unix::fs::PermissionsExt;
|
||||||
|
use std::os::unix::net::{UnixListener, UnixStream};
|
||||||
|
use std::path::PathBuf;
|
||||||
|
use std::sync::mpsc;
|
||||||
|
use std::time::Duration;
|
||||||
|
|
||||||
|
pub fn socket_path() -> PathBuf {
|
||||||
|
match std::env::var_os("XDG_RUNTIME_DIR").map(PathBuf::from).filter(|p| p.is_dir()) {
|
||||||
|
Some(d) => d.join("sourizz.sock"),
|
||||||
|
None => PathBuf::from(format!("/tmp/sourizz-{}.sock", rustix::process::getuid().as_raw())),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Send one command line to the running daemon and return its reply.
|
||||||
|
pub fn send(line: &str) -> std::io::Result<String> {
|
||||||
|
let mut s = UnixStream::connect(socket_path())?;
|
||||||
|
s.set_read_timeout(Some(Duration::from_secs(3)))?;
|
||||||
|
s.set_write_timeout(Some(Duration::from_secs(3)))?;
|
||||||
|
writeln!(s, "{}", line.trim())?;
|
||||||
|
let mut reply = String::new();
|
||||||
|
BufReader::new(s).read_line(&mut reply)?;
|
||||||
|
Ok(reply.trim().to_string())
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn is_running() -> bool {
|
||||||
|
UnixStream::connect(socket_path()).is_ok()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Start the control server in a background thread.
|
||||||
|
pub fn serve(hub: Hub) -> std::io::Result<()> {
|
||||||
|
let path = socket_path();
|
||||||
|
let listener = match UnixListener::bind(&path) {
|
||||||
|
Ok(l) => l,
|
||||||
|
Err(e) if e.kind() == std::io::ErrorKind::AddrInUse => {
|
||||||
|
if is_running() {
|
||||||
|
return Err(std::io::Error::new(std::io::ErrorKind::AddrInUse, "sourizz is already running"));
|
||||||
|
}
|
||||||
|
// Stale socket left by a crash.
|
||||||
|
let _ = std::fs::remove_file(&path);
|
||||||
|
UnixListener::bind(&path)?
|
||||||
|
}
|
||||||
|
Err(e) => return Err(e),
|
||||||
|
};
|
||||||
|
let _ = std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o600));
|
||||||
|
std::thread::Builder::new().name("ipc".into()).spawn(move || {
|
||||||
|
for conn in listener.incoming().flatten() {
|
||||||
|
let hub = hub.clone();
|
||||||
|
// One short-lived thread per client keeps a stuck client from blocking others.
|
||||||
|
let _ = std::thread::Builder::new().name("ipc-client".into()).spawn(move || handle(conn, hub));
|
||||||
|
}
|
||||||
|
})?;
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn cleanup() {
|
||||||
|
let _ = std::fs::remove_file(socket_path());
|
||||||
|
}
|
||||||
|
|
||||||
|
fn handle(mut conn: UnixStream, hub: Hub) {
|
||||||
|
let _ = conn.set_read_timeout(Some(Duration::from_secs(2)));
|
||||||
|
let mut line = String::new();
|
||||||
|
// Bound the line so a rogue local client cannot make us buffer without limit.
|
||||||
|
let mut reader = BufReader::new((&conn).take_bytes(1024));
|
||||||
|
if reader.read_line(&mut line).is_err() {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
let reply = match line.split_whitespace().next() {
|
||||||
|
Some("status") => {
|
||||||
|
let (tx, rx) = mpsc::channel();
|
||||||
|
hub.send(Command::Status(tx));
|
||||||
|
rx.recv_timeout(Duration::from_secs(1)).unwrap_or_else(|_| "error: daemon busy".into())
|
||||||
|
}
|
||||||
|
_ => match parse_line(&line).and_then(validate) {
|
||||||
|
Ok(cmd) => {
|
||||||
|
hub.send(cmd);
|
||||||
|
"ok".to_string()
|
||||||
|
}
|
||||||
|
Err(e) => format!("error: {e}"),
|
||||||
|
},
|
||||||
|
};
|
||||||
|
let _ = writeln!(conn, "{reply}");
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Reject bad `set` values here so the CLI can report them, instead of the daemon only logging.
|
||||||
|
fn validate(cmd: Command) -> Result<Command, String> {
|
||||||
|
if let Command::SetOption(k, v) = &cmd {
|
||||||
|
crate::control::set_option(&crate::config::Config::default(), k, v)?;
|
||||||
|
}
|
||||||
|
Ok(cmd)
|
||||||
|
}
|
||||||
|
|
||||||
|
trait TakeBytes {
|
||||||
|
fn take_bytes(self, n: u64) -> std::io::Take<Self>
|
||||||
|
where
|
||||||
|
Self: Sized;
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<R: std::io::Read> TakeBytes for R {
|
||||||
|
fn take_bytes(self, n: u64) -> std::io::Take<Self> {
|
||||||
|
std::io::Read::take(self, n)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,152 @@
|
|||||||
|
//! X11 keysym <-> name/char helpers, shared by the X11 and Wayland keyboard paths.
|
||||||
|
|
||||||
|
const NAMED: &[(u32, &str)] = &[
|
||||||
|
(0x0020, "space"),
|
||||||
|
(0xff08, "BackSpace"),
|
||||||
|
(0xff09, "Tab"),
|
||||||
|
(0xfe20, "ISO_Left_Tab"),
|
||||||
|
(0xff0d, "Return"),
|
||||||
|
(0xff13, "Pause"),
|
||||||
|
(0xff14, "Scroll_Lock"),
|
||||||
|
(0xff1b, "Escape"),
|
||||||
|
(0xff50, "Home"),
|
||||||
|
(0xff51, "Left"),
|
||||||
|
(0xff52, "Up"),
|
||||||
|
(0xff53, "Right"),
|
||||||
|
(0xff54, "Down"),
|
||||||
|
(0xff55, "Prior"),
|
||||||
|
(0xff56, "Next"),
|
||||||
|
(0xff57, "End"),
|
||||||
|
(0xff61, "Print"),
|
||||||
|
(0xff63, "Insert"),
|
||||||
|
(0xff67, "Menu"),
|
||||||
|
(0xff7f, "Num_Lock"),
|
||||||
|
(0xff8d, "KP_Enter"),
|
||||||
|
(0xffaa, "KP_Multiply"),
|
||||||
|
(0xffab, "KP_Add"),
|
||||||
|
(0xffad, "KP_Subtract"),
|
||||||
|
(0xffae, "KP_Decimal"),
|
||||||
|
(0xffaf, "KP_Divide"),
|
||||||
|
(0xffe1, "Shift_L"),
|
||||||
|
(0xffe2, "Shift_R"),
|
||||||
|
(0xffe3, "Control_L"),
|
||||||
|
(0xffe4, "Control_R"),
|
||||||
|
(0xffe5, "Caps_Lock"),
|
||||||
|
(0xffe7, "Meta_L"),
|
||||||
|
(0xffe8, "Meta_R"),
|
||||||
|
(0xffe9, "Alt_L"),
|
||||||
|
(0xffea, "Alt_R"),
|
||||||
|
(0xffeb, "Super_L"),
|
||||||
|
(0xffec, "Super_R"),
|
||||||
|
(0xffed, "Hyper_L"),
|
||||||
|
(0xffee, "Hyper_R"),
|
||||||
|
(0xffff, "Delete"),
|
||||||
|
(0xfe03, "ISO_Level3_Shift"),
|
||||||
|
];
|
||||||
|
|
||||||
|
/// Canonical name for a keysym (`a`, `F5`, `Control_R`, `KP_3`, `eacute`-style chars as the char).
|
||||||
|
pub fn name(sym: u32) -> String {
|
||||||
|
if let Some((_, n)) = NAMED.iter().find(|(s, _)| *s == sym) {
|
||||||
|
return (*n).to_string();
|
||||||
|
}
|
||||||
|
match sym {
|
||||||
|
0xffbe..=0xffd5 => format!("F{}", sym - 0xffbe + 1),
|
||||||
|
0xffb0..=0xffb9 => format!("KP_{}", sym - 0xffb0),
|
||||||
|
_ => match to_char(sym) {
|
||||||
|
Some(c) => c.to_string(),
|
||||||
|
None => format!("0x{sym:x}"),
|
||||||
|
},
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Printable character for a keysym, if it has one.
|
||||||
|
pub fn to_char(sym: u32) -> Option<char> {
|
||||||
|
match sym {
|
||||||
|
0x20..=0x7e | 0xa0..=0xff => char::from_u32(sym),
|
||||||
|
0x0100_0000..=0x0110_ffff => char::from_u32(sym - 0x0100_0000),
|
||||||
|
0xffb0..=0xffb9 => char::from_u32('0' as u32 + sym - 0xffb0),
|
||||||
|
0xffaa => Some('*'),
|
||||||
|
0xffab => Some('+'),
|
||||||
|
0xffad => Some('-'),
|
||||||
|
0xffae => Some('.'),
|
||||||
|
0xffaf => Some('/'),
|
||||||
|
_ => None,
|
||||||
|
}
|
||||||
|
.filter(|c| !c.is_control())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Keysym for a config/hotkey key name: `S`, `5`, `F9`, `space`, `Return`, `Control_R`, …
|
||||||
|
pub fn from_name(n: &str) -> Option<u32> {
|
||||||
|
if let Some((s, _)) = NAMED.iter().find(|(_, nm)| nm.eq_ignore_ascii_case(n)) {
|
||||||
|
return Some(*s);
|
||||||
|
}
|
||||||
|
let lower = n.to_ascii_lowercase();
|
||||||
|
if let Some(num) = lower.strip_prefix('f').and_then(|d| d.parse::<u32>().ok()) {
|
||||||
|
if (1..=24).contains(&num) {
|
||||||
|
return Some(0xffbe + num - 1);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
let mut chars = n.chars();
|
||||||
|
let (c, rest) = (chars.next()?, chars.next());
|
||||||
|
if rest.is_some() {
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
let c = c.to_lowercase().next()?;
|
||||||
|
let cp = c as u32;
|
||||||
|
Some(if (0x20..=0x7e).contains(&cp) || (0xa0..=0xff).contains(&cp) { cp } else { 0x0100_0000 + cp })
|
||||||
|
}
|
||||||
|
|
||||||
|
/// True for keys that only change modifier state and should not be shown as keystrokes.
|
||||||
|
pub fn is_modifier(name: &str) -> bool {
|
||||||
|
matches!(
|
||||||
|
name,
|
||||||
|
"Shift_L"
|
||||||
|
| "Shift_R"
|
||||||
|
| "Control_L"
|
||||||
|
| "Control_R"
|
||||||
|
| "Alt_L"
|
||||||
|
| "Alt_R"
|
||||||
|
| "Meta_L"
|
||||||
|
| "Meta_R"
|
||||||
|
| "Super_L"
|
||||||
|
| "Super_R"
|
||||||
|
| "Hyper_L"
|
||||||
|
| "Hyper_R"
|
||||||
|
| "Caps_Lock"
|
||||||
|
| "Num_Lock"
|
||||||
|
| "Scroll_Lock"
|
||||||
|
| "ISO_Level3_Shift"
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn names_roundtrip() {
|
||||||
|
for n in ["Control_R", "Return", "F5", "F12", "space", "a", "Escape", "KP_Enter"] {
|
||||||
|
let sym = from_name(n).unwrap_or_else(|| panic!("no keysym for {n}"));
|
||||||
|
assert_eq!(name(sym).to_lowercase(), n.to_lowercase());
|
||||||
|
}
|
||||||
|
assert_eq!(from_name("S"), Some('s' as u32));
|
||||||
|
assert_eq!(from_name("é"), Some(0xe9));
|
||||||
|
assert_eq!(from_name("nonsense"), None);
|
||||||
|
assert_eq!(from_name("F99"), None);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn chars() {
|
||||||
|
assert_eq!(to_char('a' as u32), Some('a'));
|
||||||
|
assert_eq!(to_char(0xe9), Some('é'));
|
||||||
|
assert_eq!(to_char(0x0100_20ac), Some('€'));
|
||||||
|
assert_eq!(to_char(0xff0d), None);
|
||||||
|
assert_eq!(to_char(0xffb5), Some('5'));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn modifiers() {
|
||||||
|
assert!(is_modifier("Control_R"));
|
||||||
|
assert!(!is_modifier("a"));
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,318 @@
|
|||||||
|
//! Keystroke visualiser: shows recent key presses as chips near a screen edge.
|
||||||
|
//!
|
||||||
|
//! Plain typing is merged into one running text chip; shortcuts (`Ctrl+Shift+T`)
|
||||||
|
//! and special keys each get their own chip.
|
||||||
|
|
||||||
|
use crate::config::{Color, KeyPosition, KeyStyle, Keystrokes, MOD_ALT, MOD_CTRL, MOD_SHIFT, MOD_SUPER};
|
||||||
|
use crate::fx;
|
||||||
|
use crate::geom::IRect;
|
||||||
|
use crate::input::KeyEvent;
|
||||||
|
use crate::text::Fonts;
|
||||||
|
use tiny_skia::{GradientStop, LinearGradient, Paint, Pixmap, Point, SpreadMode, Transform};
|
||||||
|
|
||||||
|
const MAX_CHIPS: usize = 6;
|
||||||
|
const MAX_RUN: usize = 28;
|
||||||
|
|
||||||
|
#[derive(Clone, Debug)]
|
||||||
|
pub struct Chip {
|
||||||
|
pub parts: Vec<String>,
|
||||||
|
/// A run of ordinary typed characters, extended by further typing.
|
||||||
|
pub run: bool,
|
||||||
|
pub born: f64,
|
||||||
|
pub last: f64,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Default)]
|
||||||
|
pub struct KeyViz {
|
||||||
|
pub chips: Vec<Chip>,
|
||||||
|
}
|
||||||
|
|
||||||
|
struct Placed {
|
||||||
|
x: f32,
|
||||||
|
y: f32,
|
||||||
|
w: f32,
|
||||||
|
h: f32,
|
||||||
|
alpha: f32,
|
||||||
|
idx: usize,
|
||||||
|
}
|
||||||
|
|
||||||
|
fn mod_parts(mods: u8) -> Vec<String> {
|
||||||
|
let mut v = Vec::new();
|
||||||
|
if mods & MOD_CTRL != 0 {
|
||||||
|
v.push("Ctrl".to_string());
|
||||||
|
}
|
||||||
|
if mods & MOD_ALT != 0 {
|
||||||
|
v.push("Alt".to_string());
|
||||||
|
}
|
||||||
|
if mods & MOD_SHIFT != 0 {
|
||||||
|
v.push("Shift".to_string());
|
||||||
|
}
|
||||||
|
if mods & MOD_SUPER != 0 {
|
||||||
|
v.push("Super".to_string());
|
||||||
|
}
|
||||||
|
v
|
||||||
|
}
|
||||||
|
|
||||||
|
impl KeyViz {
|
||||||
|
pub fn key(&mut self, now: f64, ev: &KeyEvent, cfg: &Keystrokes) {
|
||||||
|
if !ev.pressed || ev.is_modifier {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
let shortcut = ev.mods & (MOD_CTRL | MOD_ALT | MOD_SUPER) != 0;
|
||||||
|
if cfg.only_shortcuts && !shortcut {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
// Ordinary typing: extend the running text chip.
|
||||||
|
if !shortcut {
|
||||||
|
if let Some(ch) = ev.text.filter(|c| !c.is_control() && *c != ' ') {
|
||||||
|
if let Some(last) = self.chips.last_mut() {
|
||||||
|
if last.run && now - last.last < 1.4 && last.parts[0].chars().count() < MAX_RUN {
|
||||||
|
last.parts[0].push(ch);
|
||||||
|
last.last = now;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
self.push(Chip { parts: vec![ch.to_string()], run: true, born: now, last: now });
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
let mut parts = mod_parts(ev.mods);
|
||||||
|
parts.push(ev.label.clone());
|
||||||
|
// Auto-repeat of the same combo refreshes instead of stacking.
|
||||||
|
if let Some(last) = self.chips.last_mut() {
|
||||||
|
if !last.run && last.parts == parts && now - last.last < 0.6 {
|
||||||
|
last.last = now;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
self.push(Chip { parts, run: false, born: now, last: now });
|
||||||
|
}
|
||||||
|
|
||||||
|
fn push(&mut self, c: Chip) {
|
||||||
|
self.chips.push(c);
|
||||||
|
if self.chips.len() > MAX_CHIPS {
|
||||||
|
self.chips.remove(0);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Drop expired chips; true while any remain (needs animation frames for the fade).
|
||||||
|
pub fn expire(&mut self, now: f64, cfg: &Keystrokes) -> bool {
|
||||||
|
let life = cfg.duration_ms as f64 / 1000.0;
|
||||||
|
self.chips.retain(|c| now - c.last < life);
|
||||||
|
!self.chips.is_empty()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn layout(&self, fonts: &mut Fonts, cfg: &Keystrokes, mon: IRect, now: f64) -> Vec<Placed> {
|
||||||
|
if !fonts.available() || self.chips.is_empty() {
|
||||||
|
return Vec::new();
|
||||||
|
}
|
||||||
|
let px = cfg.size;
|
||||||
|
let h = (px * 1.75).round();
|
||||||
|
let pad = px * 0.65;
|
||||||
|
let gap = (px * 0.45).round();
|
||||||
|
let life = cfg.duration_ms as f64 / 1000.0;
|
||||||
|
let mut items: Vec<(usize, f32)> = Vec::new();
|
||||||
|
for (i, c) in self.chips.iter().enumerate() {
|
||||||
|
let w = match cfg.style {
|
||||||
|
KeyStyle::Keycaps => {
|
||||||
|
let caps: f32 = c.parts.iter().map(|p| fonts.measure(p, px).max(px * 0.6) + pad * 1.1).sum();
|
||||||
|
caps + (c.parts.len().saturating_sub(1)) as f32 * 6.0
|
||||||
|
}
|
||||||
|
_ => fonts.measure(&c.parts.join(" + "), px) + pad * 2.0,
|
||||||
|
};
|
||||||
|
items.push((i, w.round()));
|
||||||
|
}
|
||||||
|
let total: f32 = items.iter().map(|(_, w)| *w).sum::<f32>() + gap * (items.len().saturating_sub(1)) as f32;
|
||||||
|
let margin_y = (px * 2.2).round();
|
||||||
|
let y = match cfg.position {
|
||||||
|
KeyPosition::TopCenter => mon.y0 as f32 + margin_y,
|
||||||
|
_ => mon.y1 as f32 - margin_y - h,
|
||||||
|
};
|
||||||
|
let mut x = match cfg.position {
|
||||||
|
KeyPosition::BottomLeft => mon.x0 as f32 + 40.0,
|
||||||
|
KeyPosition::BottomRight => mon.x1 as f32 - 40.0 - total,
|
||||||
|
_ => mon.x0 as f32 + (mon.width() as f32 - total) / 2.0,
|
||||||
|
};
|
||||||
|
let mut out = Vec::new();
|
||||||
|
for (i, w) in items {
|
||||||
|
let c = &self.chips[i];
|
||||||
|
let age = (now - c.last) / life;
|
||||||
|
let fade = if age > 0.7 { (1.0 - (age - 0.7) / 0.3).clamp(0.0, 1.0) as f32 } else { 1.0 };
|
||||||
|
let pop = (((now - c.born) / 0.12) as f32).clamp(0.0, 1.0);
|
||||||
|
let dy = (1.0 - pop) * 8.0;
|
||||||
|
out.push(Placed { x, y: y + dy, w, h, alpha: fade * pop.max(0.2), idx: i });
|
||||||
|
x += w + gap;
|
||||||
|
}
|
||||||
|
out
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn bounds(&self, fonts: &mut Fonts, cfg: &Keystrokes, mon: IRect, now: f64) -> IRect {
|
||||||
|
let mut r = IRect::new(0, 0, 0, 0);
|
||||||
|
for p in self.layout(fonts, cfg, mon, now) {
|
||||||
|
r = r.union(IRect::around(p.x, p.y - 8.0, p.x + p.w, p.y + p.h + 12.0, 12.0));
|
||||||
|
}
|
||||||
|
r
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn paint(&self, pm: &mut Pixmap, tf: Transform, fonts: &mut Fonts, cfg: &Keystrokes, mon: IRect, now: f64) {
|
||||||
|
let px = cfg.size;
|
||||||
|
let (ox, oy) = (tf.tx, tf.ty);
|
||||||
|
for p in self.layout(fonts, cfg, mon, now) {
|
||||||
|
let chip = &self.chips[p.idx];
|
||||||
|
let a = p.alpha;
|
||||||
|
let (x, y, w, h) = (p.x, p.y, p.w, p.h);
|
||||||
|
let r = h * 0.28;
|
||||||
|
let base = y + h / 2.0 + px * 0.34;
|
||||||
|
let text = chip.parts.join(" + ");
|
||||||
|
let tw = fonts.measure(&text, px);
|
||||||
|
let tx = x + (w - tw) / 2.0;
|
||||||
|
let accent = cfg.accent;
|
||||||
|
match cfg.style {
|
||||||
|
KeyStyle::Classic => {
|
||||||
|
fx::fill_rrect(pm, tf, x, y, w, h, r, &fx::solid(tiny_skia::Color::from_rgba8(22, 22, 26, (a * 225.0) as u8)));
|
||||||
|
fonts.draw(pm, &text, tx + ox, base + oy, px, Color::rgb(245, 245, 247), a);
|
||||||
|
}
|
||||||
|
KeyStyle::Glass => {
|
||||||
|
fx::fill_rrect(pm, tf, x, y, w, h, r, &fx::solid(tiny_skia::Color::from_rgba8(30, 30, 40, (a * 120.0) as u8)));
|
||||||
|
fx::fill_rrect(pm, tf, x, y, w, h * 0.5, r, &fx::solid(tiny_skia::Color::from_rgba8(255, 255, 255, (a * 38.0) as u8)));
|
||||||
|
fx::stroke_rrect(
|
||||||
|
pm,
|
||||||
|
tf,
|
||||||
|
x + 0.5,
|
||||||
|
y + 0.5,
|
||||||
|
w - 1.0,
|
||||||
|
h - 1.0,
|
||||||
|
r,
|
||||||
|
1.2,
|
||||||
|
tiny_skia::Color::from_rgba8(255, 255, 255, (a * 110.0) as u8),
|
||||||
|
);
|
||||||
|
fonts.draw(pm, &text, tx + ox, base + oy, px, Color::rgb(255, 255, 255), a);
|
||||||
|
}
|
||||||
|
KeyStyle::Neon => {
|
||||||
|
fx::fill_rrect(pm, tf, x, y, w, h, r, &fx::solid(tiny_skia::Color::from_rgba8(10, 10, 16, (a * 235.0) as u8)));
|
||||||
|
for (grow, al) in [(7.0f32, 0.07), (4.0, 0.12), (2.0, 0.22)] {
|
||||||
|
fx::stroke_rrect(
|
||||||
|
pm,
|
||||||
|
tf,
|
||||||
|
x - grow / 2.0,
|
||||||
|
y - grow / 2.0,
|
||||||
|
w + grow,
|
||||||
|
h + grow,
|
||||||
|
r + grow / 2.0,
|
||||||
|
grow,
|
||||||
|
accent.sk(al * a),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
fx::stroke_rrect(pm, tf, x, y, w, h, r, 2.0, accent.sk(a));
|
||||||
|
fonts.draw(pm, &text, tx + ox, base + oy, px, accent, a);
|
||||||
|
}
|
||||||
|
KeyStyle::Gradient => {
|
||||||
|
let c2 = {
|
||||||
|
let [r0, g0, b0] = accent.as_f32();
|
||||||
|
Color::from_f32([b0 * 0.9 + 0.1, r0 * 0.6, g0 * 0.4 + 0.6])
|
||||||
|
};
|
||||||
|
let stops = vec![GradientStop::new(0.0, accent.sk(a)), GradientStop::new(1.0, c2.sk(a))];
|
||||||
|
if let Some(shader) = LinearGradient::new(
|
||||||
|
Point::from_xy(x, y),
|
||||||
|
Point::from_xy(x + w, y + h),
|
||||||
|
stops,
|
||||||
|
SpreadMode::Pad,
|
||||||
|
Transform::identity(),
|
||||||
|
) {
|
||||||
|
let paint = Paint { shader, anti_alias: true, ..Paint::default() };
|
||||||
|
fx::fill_rrect(pm, tf, x, y, w, h, r, &paint);
|
||||||
|
}
|
||||||
|
fonts.draw(pm, &text, tx + ox, base + oy, px, Color::rgb(255, 255, 255), a);
|
||||||
|
}
|
||||||
|
KeyStyle::Minimal => {
|
||||||
|
fonts.draw(pm, &text, tx + ox + 2.0, base + oy + 2.0, px * 1.15, Color { r: 0, g: 0, b: 0, a: 170 }, a);
|
||||||
|
fonts.draw(pm, &text, tx + ox, base + oy, px * 1.15, Color::rgb(255, 255, 255), a);
|
||||||
|
}
|
||||||
|
KeyStyle::Keycaps => {
|
||||||
|
let mut cx = x;
|
||||||
|
for part in &chip.parts {
|
||||||
|
let cw = fonts.measure(part, px).max(px * 0.6) + px * 0.65 * 1.1;
|
||||||
|
fx::fill_rrect(
|
||||||
|
pm,
|
||||||
|
tf,
|
||||||
|
cx,
|
||||||
|
y + 4.0,
|
||||||
|
cw,
|
||||||
|
h - 2.0,
|
||||||
|
r * 0.8,
|
||||||
|
&fx::solid(tiny_skia::Color::from_rgba8(70, 70, 76, (a * 255.0) as u8)),
|
||||||
|
);
|
||||||
|
fx::fill_rrect(
|
||||||
|
pm,
|
||||||
|
tf,
|
||||||
|
cx,
|
||||||
|
y,
|
||||||
|
cw,
|
||||||
|
h - 5.0,
|
||||||
|
r * 0.8,
|
||||||
|
&fx::solid(tiny_skia::Color::from_rgba8(240, 240, 243, (a * 255.0) as u8)),
|
||||||
|
);
|
||||||
|
let pw = fonts.measure(part, px);
|
||||||
|
fonts.draw(
|
||||||
|
pm,
|
||||||
|
part,
|
||||||
|
cx + (cw - pw) / 2.0 + ox,
|
||||||
|
y + (h - 5.0) / 2.0 + px * 0.34 + oy,
|
||||||
|
px,
|
||||||
|
Color::rgb(30, 30, 34),
|
||||||
|
a,
|
||||||
|
);
|
||||||
|
cx += cw + 6.0;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
|
||||||
|
fn ev(name: &str, label: &str, text: Option<char>, mods: u8) -> KeyEvent {
|
||||||
|
KeyEvent { pressed: true, name: name.into(), label: label.into(), text, mods, is_modifier: false, repeat: false }
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn typing_merges_into_one_run() {
|
||||||
|
let cfg = Keystrokes::default();
|
||||||
|
let mut kv = KeyViz::default();
|
||||||
|
for (i, c) in "hello".chars().enumerate() {
|
||||||
|
kv.key(i as f64 * 0.1, &ev(&c.to_string(), &c.to_uppercase().to_string(), Some(c), 0), &cfg);
|
||||||
|
}
|
||||||
|
assert_eq!(kv.chips.len(), 1);
|
||||||
|
assert_eq!(kv.chips[0].parts[0], "hello");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn shortcut_gets_its_own_chip() {
|
||||||
|
let cfg = Keystrokes::default();
|
||||||
|
let mut kv = KeyViz::default();
|
||||||
|
kv.key(0.0, &ev("t", "T", Some('t'), MOD_CTRL | MOD_SHIFT), &cfg);
|
||||||
|
assert_eq!(kv.chips[0].parts, vec!["Ctrl", "Shift", "T"]);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn only_shortcuts_hides_plain_typing() {
|
||||||
|
let cfg = Keystrokes { only_shortcuts: true, ..Keystrokes::default() };
|
||||||
|
let mut kv = KeyViz::default();
|
||||||
|
kv.key(0.0, &ev("a", "A", Some('a'), 0), &cfg);
|
||||||
|
assert!(kv.chips.is_empty());
|
||||||
|
kv.key(0.1, &ev("a", "A", Some('a'), MOD_CTRL), &cfg);
|
||||||
|
assert_eq!(kv.chips.len(), 1);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn chips_expire() {
|
||||||
|
let cfg = Keystrokes::default();
|
||||||
|
let mut kv = KeyViz::default();
|
||||||
|
kv.key(0.0, &ev("Return", "Enter", None, 0), &cfg);
|
||||||
|
assert!(kv.expire(1.0, &cfg));
|
||||||
|
assert!(!kv.expire(10.0, &cfg));
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,114 @@
|
|||||||
|
//! Exact pointer position on KDE Plasma (Wayland), through a tiny KWin script.
|
||||||
|
//!
|
||||||
|
//! KWin exposes `workspace.cursorPos` to its scripts but offers no D-Bus call for it. So the
|
||||||
|
//! daemon owns a D-Bus name (`org.sourizz.Daemon`), loads a script into KWin through the
|
||||||
|
//! `org.kde.KWin /Scripting` interface, and the script calls our `Pos(x, y)` method whenever
|
||||||
|
//! the pointer moved. Nothing is sent while the pointer is still.
|
||||||
|
|
||||||
|
use crate::control::Hub;
|
||||||
|
use std::path::PathBuf;
|
||||||
|
use std::sync::{Arc, Mutex};
|
||||||
|
|
||||||
|
const SCRIPT_NAME: &str = "sourizz-pointer";
|
||||||
|
|
||||||
|
/// The KWin script (KWin 6 JavaScript API: `workspace`, `callDBus`, `QTimer`).
|
||||||
|
pub const SCRIPT: &str = r#"
|
||||||
|
var last = { x: -1000000, y: -1000000 };
|
||||||
|
function send() {
|
||||||
|
var p = workspace.cursorPos;
|
||||||
|
if (p.x === last.x && p.y === last.y) { return; }
|
||||||
|
last = { x: p.x, y: p.y };
|
||||||
|
callDBus("org.sourizz.Daemon", "/Pointer", "org.sourizz.Pointer", "Pos", p.x | 0, p.y | 0);
|
||||||
|
}
|
||||||
|
// The signal gives low latency; the timer is a safety net should the signal not fire.
|
||||||
|
workspace.cursorPosChanged.connect(send);
|
||||||
|
var poll = new QTimer();
|
||||||
|
poll.interval = 16;
|
||||||
|
poll.timeout.connect(send);
|
||||||
|
poll.start();
|
||||||
|
send();
|
||||||
|
"#;
|
||||||
|
|
||||||
|
struct PointerService {
|
||||||
|
latest: Arc<Mutex<Option<(f32, f32)>>>,
|
||||||
|
hub: Hub,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[zbus::interface(name = "org.sourizz.Pointer")]
|
||||||
|
impl PointerService {
|
||||||
|
fn pos(&self, x: i32, y: i32) {
|
||||||
|
if let Ok(mut l) = self.latest.lock() {
|
||||||
|
*l = Some((x as f32, y as f32));
|
||||||
|
}
|
||||||
|
self.hub.poke();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub struct KwinFeed {
|
||||||
|
latest: Arc<Mutex<Option<(f32, f32)>>>,
|
||||||
|
conn: zbus::blocking::Connection,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl KwinFeed {
|
||||||
|
/// Try to hook into KWin. Returns `None` on any other desktop (or when scripting is off).
|
||||||
|
pub fn start(hub: Hub) -> Option<KwinFeed> {
|
||||||
|
let latest = Arc::new(Mutex::new(None));
|
||||||
|
let conn = zbus::blocking::connection::Builder::session()
|
||||||
|
.ok()?
|
||||||
|
.name("org.sourizz.Daemon")
|
||||||
|
.ok()?
|
||||||
|
.serve_at("/Pointer", PointerService { latest: latest.clone(), hub })
|
||||||
|
.ok()?
|
||||||
|
.build()
|
||||||
|
.ok()?;
|
||||||
|
let feed = KwinFeed { latest, conn };
|
||||||
|
match feed.load_script() {
|
||||||
|
Ok(()) => Some(feed),
|
||||||
|
Err(e) => {
|
||||||
|
log::debug!("KWin script not loaded: {e}");
|
||||||
|
None
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn script_path() -> PathBuf {
|
||||||
|
std::env::var_os("XDG_RUNTIME_DIR")
|
||||||
|
.map(PathBuf::from)
|
||||||
|
.filter(|p| p.is_dir())
|
||||||
|
.unwrap_or_else(std::env::temp_dir)
|
||||||
|
.join("sourizz")
|
||||||
|
.join("pointer.js")
|
||||||
|
}
|
||||||
|
|
||||||
|
fn scripting(&self, method: &str, body: &(impl serde::Serialize + zbus::zvariant::DynamicType)) -> zbus::Result<zbus::Message> {
|
||||||
|
self.conn.call_method(Some("org.kde.KWin"), "/Scripting", Some("org.kde.kwin.Scripting"), method, body)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn load_script(&self) -> Result<(), String> {
|
||||||
|
let path = Self::script_path();
|
||||||
|
std::fs::create_dir_all(path.parent().unwrap()).map_err(|e| e.to_string())?;
|
||||||
|
std::fs::write(&path, SCRIPT).map_err(|e| e.to_string())?;
|
||||||
|
// A previous run that crashed may have left the script loaded.
|
||||||
|
let _ = self.scripting("unloadScript", &(SCRIPT_NAME,));
|
||||||
|
let reply = self.scripting("loadScript", &(path.to_string_lossy().to_string(), SCRIPT_NAME)).map_err(|e| e.to_string())?;
|
||||||
|
let id: i32 = reply.body().deserialize().map_err(|e| e.to_string())?;
|
||||||
|
if id < 0 {
|
||||||
|
return Err("KWin refused to load the script".into());
|
||||||
|
}
|
||||||
|
self.conn
|
||||||
|
.call_method(Some("org.kde.KWin"), format!("/Scripting/Script{id}").as_str(), Some("org.kde.kwin.Script"), "run", &())
|
||||||
|
.map_err(|e| e.to_string())?;
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The most recent position reported by the script, if it changed since the last call.
|
||||||
|
pub fn take_latest(&self) -> Option<(f32, f32)> {
|
||||||
|
self.latest.lock().ok().and_then(|mut l| l.take())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Drop for KwinFeed {
|
||||||
|
fn drop(&mut self) {
|
||||||
|
let _ = self.scripting("unloadScript", &(SCRIPT_NAME,));
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,30 @@
|
|||||||
|
//! Sourizz — cursor highlighter for Linux (X11 and Wayland).
|
||||||
|
|
||||||
|
// Style lints we deliberately do not follow: nested `if let` reads better than let-chains in the
|
||||||
|
// event handlers, the drawing helpers take plain geometry parameters, and the RGBA<->BGRA loops
|
||||||
|
// are clearer with `chunks_exact`.
|
||||||
|
#![allow(clippy::collapsible_if, clippy::too_many_arguments, clippy::chunks_exact_to_as_chunks)]
|
||||||
|
|
||||||
|
pub mod annot;
|
||||||
|
pub mod audio;
|
||||||
|
pub mod canvas;
|
||||||
|
pub mod config;
|
||||||
|
pub mod control;
|
||||||
|
pub mod core;
|
||||||
|
pub mod demo;
|
||||||
|
pub mod engine;
|
||||||
|
pub mod evdev_in;
|
||||||
|
pub mod fx;
|
||||||
|
pub mod geom;
|
||||||
|
pub mod i18n;
|
||||||
|
pub mod input;
|
||||||
|
pub mod ipc;
|
||||||
|
pub mod keysym;
|
||||||
|
pub mod keyviz;
|
||||||
|
pub mod kwin;
|
||||||
|
pub mod text;
|
||||||
|
pub mod tray;
|
||||||
|
pub mod wayland;
|
||||||
|
pub mod wlsrc;
|
||||||
|
pub mod x11;
|
||||||
|
pub mod xkb;
|
||||||
@@ -0,0 +1,258 @@
|
|||||||
|
use anyhow::{Context, Result, bail};
|
||||||
|
use clap::{Parser, Subcommand, ValueEnum};
|
||||||
|
use sourizz::config::{BackendKind, Config};
|
||||||
|
use sourizz::control::Hub;
|
||||||
|
use sourizz::core::Core;
|
||||||
|
use sourizz::{demo, ipc, wayland, x11};
|
||||||
|
use std::path::PathBuf;
|
||||||
|
use std::sync::Arc;
|
||||||
|
use std::sync::atomic::AtomicBool;
|
||||||
|
|
||||||
|
#[derive(Parser)]
|
||||||
|
#[command(
|
||||||
|
name = "sourizz",
|
||||||
|
version,
|
||||||
|
about = "Cursor highlighter for Linux: spotlight, ring, trails, click effects and annotations (X11 and Wayland).\nRun without a subcommand to start the daemon; the other subcommands control a running daemon."
|
||||||
|
)]
|
||||||
|
struct Cli {
|
||||||
|
#[command(subcommand)]
|
||||||
|
cmd: Option<Cmd>,
|
||||||
|
/// Display backend (overrides the config file).
|
||||||
|
#[arg(long, value_enum, global = false)]
|
||||||
|
backend: Option<BackendArg>,
|
||||||
|
/// Do not create a system tray icon.
|
||||||
|
#[arg(long)]
|
||||||
|
no_tray: bool,
|
||||||
|
/// More log output (-v info, -vv debug).
|
||||||
|
#[arg(short, long, action = clap::ArgAction::Count)]
|
||||||
|
verbose: u8,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Clone, Copy, ValueEnum)]
|
||||||
|
enum BackendArg {
|
||||||
|
Auto,
|
||||||
|
X11,
|
||||||
|
Wayland,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Subcommand)]
|
||||||
|
enum Cmd {
|
||||||
|
/// Start the daemon (same as running with no subcommand).
|
||||||
|
Run,
|
||||||
|
/// Flip an effect: all, spotlight, ring, trail, clicks, sound, shake, annotate, keystrokes, focus.
|
||||||
|
Toggle { effect: String },
|
||||||
|
/// Turn an effect on.
|
||||||
|
On { effect: String },
|
||||||
|
/// Turn an effect off.
|
||||||
|
Off { effect: String },
|
||||||
|
/// Set any option, e.g. `sourizz set ring.size 80` or `sourizz set trail.style stars`.
|
||||||
|
Set { key: String, value: Vec<String> },
|
||||||
|
/// Play the click effect at the pointer.
|
||||||
|
ShowClick,
|
||||||
|
/// Annotation mode: `toggle` (default) or `clear`.
|
||||||
|
Annotate { action: Option<String> },
|
||||||
|
/// Re-read the config file.
|
||||||
|
Reload,
|
||||||
|
/// Print the daemon's state.
|
||||||
|
Status,
|
||||||
|
/// Open the settings window.
|
||||||
|
Settings,
|
||||||
|
/// Stop the daemon.
|
||||||
|
Quit,
|
||||||
|
/// Print the config file path, or its defaults with `--defaults`.
|
||||||
|
Config {
|
||||||
|
#[arg(long)]
|
||||||
|
defaults: bool,
|
||||||
|
},
|
||||||
|
/// Start or stop launching Sourizz at login.
|
||||||
|
Autostart { action: AutostartAction },
|
||||||
|
/// Check this system for everything Sourizz needs.
|
||||||
|
Doctor,
|
||||||
|
/// Render every effect to PNG files in a directory (no display needed).
|
||||||
|
#[command(hide = true)]
|
||||||
|
Demo { dir: PathBuf },
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Clone, Copy, ValueEnum)]
|
||||||
|
enum AutostartAction {
|
||||||
|
Enable,
|
||||||
|
Disable,
|
||||||
|
}
|
||||||
|
|
||||||
|
fn main() {
|
||||||
|
if let Err(e) = real_main() {
|
||||||
|
eprintln!("sourizz: {e:#}");
|
||||||
|
std::process::exit(1);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn real_main() -> Result<()> {
|
||||||
|
let cli = Cli::parse();
|
||||||
|
match cli.cmd {
|
||||||
|
None | Some(Cmd::Run) => run_daemon(&cli),
|
||||||
|
Some(Cmd::Toggle { effect }) => remote(&format!("toggle {effect}")),
|
||||||
|
Some(Cmd::On { effect }) => remote(&format!("on {effect}")),
|
||||||
|
Some(Cmd::Off { effect }) => remote(&format!("off {effect}")),
|
||||||
|
Some(Cmd::Set { key, value }) => remote(&format!("set {key} {}", value.join(" "))),
|
||||||
|
Some(Cmd::ShowClick) => remote("show-click"),
|
||||||
|
Some(Cmd::Annotate { action }) => remote(&format!("annotate {}", action.unwrap_or_default())),
|
||||||
|
Some(Cmd::Reload) => remote("reload"),
|
||||||
|
Some(Cmd::Status) => remote("status"),
|
||||||
|
Some(Cmd::Quit) => remote("quit"),
|
||||||
|
Some(Cmd::Settings) => settings(),
|
||||||
|
Some(Cmd::Config { defaults }) => {
|
||||||
|
if defaults {
|
||||||
|
print!("{}", toml::to_string_pretty(&Config::default())?);
|
||||||
|
} else {
|
||||||
|
println!("{}", Config::path().display());
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
Some(Cmd::Autostart { action }) => autostart(action),
|
||||||
|
Some(Cmd::Doctor) => doctor(),
|
||||||
|
Some(Cmd::Demo { dir }) => demo::run(&dir),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn remote(line: &str) -> Result<()> {
|
||||||
|
match ipc::send(line) {
|
||||||
|
Ok(reply) => {
|
||||||
|
if let Some(err) = reply.strip_prefix("error:") {
|
||||||
|
bail!("{}", err.trim());
|
||||||
|
}
|
||||||
|
if reply != "ok" {
|
||||||
|
println!("{reply}");
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
Err(e) if matches!(e.kind(), std::io::ErrorKind::NotFound | std::io::ErrorKind::ConnectionRefused) => {
|
||||||
|
bail!("the daemon is not running — start it with `sourizz`")
|
||||||
|
}
|
||||||
|
Err(e) => Err(e).context("talking to the daemon"),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn settings() -> Result<()> {
|
||||||
|
let sibling = std::env::current_exe()?.with_file_name("sourizz-settings");
|
||||||
|
let program = if sibling.is_file() { sibling } else { PathBuf::from("sourizz-settings") };
|
||||||
|
let err = std::os::unix::process::CommandExt::exec(std::process::Command::new(&program).arg0("sourizz-settings"));
|
||||||
|
bail!("cannot start {}: {err}", program.display())
|
||||||
|
}
|
||||||
|
|
||||||
|
use std::os::unix::process::CommandExt as _;
|
||||||
|
|
||||||
|
fn session_is_wayland() -> bool {
|
||||||
|
std::env::var_os("WAYLAND_DISPLAY").is_some() && std::env::var("XDG_SESSION_TYPE").map(|s| s != "x11").unwrap_or(true)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn pick_backend(cli: &Cli, cfg: &Config) -> BackendKind {
|
||||||
|
let want = match cli.backend {
|
||||||
|
Some(BackendArg::X11) => BackendKind::X11,
|
||||||
|
Some(BackendArg::Wayland) => BackendKind::Wayland,
|
||||||
|
Some(BackendArg::Auto) => BackendKind::Auto,
|
||||||
|
None => cfg.general.backend,
|
||||||
|
};
|
||||||
|
match want {
|
||||||
|
BackendKind::Auto if session_is_wayland() => BackendKind::Wayland,
|
||||||
|
BackendKind::Auto => BackendKind::X11,
|
||||||
|
other => other,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn run_daemon(cli: &Cli) -> Result<()> {
|
||||||
|
let level = match cli.verbose {
|
||||||
|
0 => "warn",
|
||||||
|
1 => "info",
|
||||||
|
_ => "debug",
|
||||||
|
};
|
||||||
|
// Only our own crate follows -v; zbus & co. stay quiet unless RUST_LOG says otherwise.
|
||||||
|
let mut b = env_logger::Builder::new();
|
||||||
|
b.filter_level(log::LevelFilter::Warn).filter_module("sourizz", level.parse().unwrap_or(log::LevelFilter::Warn)).format_timestamp(None);
|
||||||
|
if let Ok(spec) = std::env::var("RUST_LOG") {
|
||||||
|
b.parse_filters(&spec);
|
||||||
|
}
|
||||||
|
b.init();
|
||||||
|
|
||||||
|
let cfg = Config::load();
|
||||||
|
if ipc::is_running() {
|
||||||
|
bail!("sourizz is already running (use `sourizz quit` to stop it)");
|
||||||
|
}
|
||||||
|
let (hub, rx, wake) = Hub::new()?;
|
||||||
|
ipc::serve(hub.clone()).context("starting the control socket")?;
|
||||||
|
|
||||||
|
let term = Arc::new(AtomicBool::new(false));
|
||||||
|
for sig in [signal_hook::consts::SIGINT, signal_hook::consts::SIGTERM, signal_hook::consts::SIGHUP] {
|
||||||
|
signal_hook::flag::register(sig, term.clone())?;
|
||||||
|
let w = rustix::io::fcntl_dupfd_cloexec(&*hub.wake_fd(), 0)?;
|
||||||
|
signal_hook::low_level::pipe::register(sig, w)?;
|
||||||
|
}
|
||||||
|
|
||||||
|
let backend = pick_backend(cli, &cfg);
|
||||||
|
let mut core = Core::new(cfg, hub, rx);
|
||||||
|
core.set_term_flag(term);
|
||||||
|
if !cli.no_tray {
|
||||||
|
core.start_tray();
|
||||||
|
}
|
||||||
|
log::info!("starting with the {} backend", backend.id());
|
||||||
|
let result = match backend {
|
||||||
|
BackendKind::Wayland => wayland::run(core, &wake),
|
||||||
|
_ => x11::run(&mut core, &wake),
|
||||||
|
};
|
||||||
|
ipc::cleanup();
|
||||||
|
result
|
||||||
|
}
|
||||||
|
|
||||||
|
fn autostart_path() -> PathBuf {
|
||||||
|
Config::dir().parent().map(|p| p.join("autostart")).unwrap_or_else(|| PathBuf::from(".config/autostart")).join("sourizz.desktop")
|
||||||
|
}
|
||||||
|
|
||||||
|
fn autostart(action: AutostartAction) -> Result<()> {
|
||||||
|
let path = autostart_path();
|
||||||
|
match action {
|
||||||
|
AutostartAction::Enable => {
|
||||||
|
let exe = std::env::current_exe()?;
|
||||||
|
std::fs::create_dir_all(path.parent().unwrap())?;
|
||||||
|
std::fs::write(
|
||||||
|
&path,
|
||||||
|
format!(
|
||||||
|
"[Desktop Entry]\nType=Application\nName=Sourizz\nComment=Cursor highlighter\nExec={}\nIcon=input-mouse\nTerminal=false\nX-GNOME-Autostart-enabled=true\n",
|
||||||
|
exe.display()
|
||||||
|
),
|
||||||
|
)?;
|
||||||
|
println!("autostart enabled: {}", path.display());
|
||||||
|
}
|
||||||
|
AutostartAction::Disable => match std::fs::remove_file(&path) {
|
||||||
|
Ok(()) => println!("autostart disabled"),
|
||||||
|
Err(e) if e.kind() == std::io::ErrorKind::NotFound => println!("autostart was not enabled"),
|
||||||
|
Err(e) => return Err(e.into()),
|
||||||
|
},
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn doctor() -> Result<()> {
|
||||||
|
let ok = |b: bool| if b { "ok " } else { "MISSING" };
|
||||||
|
let env = |k: &str| std::env::var(k).unwrap_or_else(|_| "-".into());
|
||||||
|
println!("session : {} ({})", env("XDG_SESSION_TYPE"), env("XDG_CURRENT_DESKTOP"));
|
||||||
|
println!("DISPLAY : {} WAYLAND_DISPLAY: {}", env("DISPLAY"), env("WAYLAND_DISPLAY"));
|
||||||
|
println!("backend : {}", pick_backend(&Cli::parse_from(["sourizz"]), &Config::load()).id());
|
||||||
|
println!("fonts : {}", ok(sourizz::text::Fonts::load().available()));
|
||||||
|
let have = |c: &str| std::env::var_os("PATH").is_some_and(|p| std::env::split_paths(&p).any(|d| d.join(c).is_file()));
|
||||||
|
println!("sound player : {}", ok(have("pw-play") || have("paplay") || have("aplay")));
|
||||||
|
if session_is_wayland() {
|
||||||
|
let groups = std::process::Command::new("id")
|
||||||
|
.arg("-nG")
|
||||||
|
.output()
|
||||||
|
.map(|o| String::from_utf8_lossy(&o.stdout).to_string())
|
||||||
|
.unwrap_or_default();
|
||||||
|
println!("input group : {} (needed on Wayland for global clicks and keys)", ok(groups.split_whitespace().any(|g| g == "input")));
|
||||||
|
} else {
|
||||||
|
match x11::X11::connect() {
|
||||||
|
Ok(_) => println!("X11 : ok (XInput2, RandR, Shape, 32-bit visual)"),
|
||||||
|
Err(e) => println!("X11 : MISSING ({e:#})"),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
println!("config : {}", Config::path().display());
|
||||||
|
println!("daemon : {}", if ipc::is_running() { "running" } else { "not running" });
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
@@ -0,0 +1,123 @@
|
|||||||
|
//! Minimal text rendering on top of fontdue, with a per-size glyph cache.
|
||||||
|
//!
|
||||||
|
//! The font is discovered at runtime through fontconfig (`fc-match`) so no
|
||||||
|
//! font has to be bundled. If none is found, text silently measures as zero
|
||||||
|
//! width and draws nothing — every other effect keeps working.
|
||||||
|
|
||||||
|
use crate::config::Color;
|
||||||
|
use std::collections::HashMap;
|
||||||
|
use std::path::PathBuf;
|
||||||
|
use tiny_skia::Pixmap;
|
||||||
|
|
||||||
|
pub struct Fonts {
|
||||||
|
font: Option<fontdue::Font>,
|
||||||
|
cache: HashMap<(char, u32), (fontdue::Metrics, Vec<u8>)>,
|
||||||
|
}
|
||||||
|
|
||||||
|
fn find_font() -> Option<PathBuf> {
|
||||||
|
for pattern in ["sans-serif:bold", "sans-serif", "DejaVu Sans:bold"] {
|
||||||
|
if let Ok(out) = std::process::Command::new("fc-match").args(["-f", "%{file}", pattern]).output() {
|
||||||
|
let p = PathBuf::from(String::from_utf8_lossy(&out.stdout).trim().to_string());
|
||||||
|
if out.status.success() && p.is_file() {
|
||||||
|
return Some(p);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
[
|
||||||
|
"/usr/share/fonts/truetype/dejavu/DejaVuSans-Bold.ttf",
|
||||||
|
"/usr/share/fonts/truetype/liberation/LiberationSans-Bold.ttf",
|
||||||
|
"/usr/share/fonts/TTF/DejaVuSans-Bold.ttf",
|
||||||
|
"/usr/share/fonts/noto/NotoSans-Bold.ttf",
|
||||||
|
"/usr/share/fonts/truetype/noto/NotoSans-Bold.ttf",
|
||||||
|
]
|
||||||
|
.iter()
|
||||||
|
.map(PathBuf::from)
|
||||||
|
.find(|p| p.is_file())
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Fonts {
|
||||||
|
pub fn load() -> Self {
|
||||||
|
let font = find_font().and_then(|p| {
|
||||||
|
// fontdue cannot read .ttc collections by index 0 reliably, so just try.
|
||||||
|
let data = std::fs::read(&p).ok()?;
|
||||||
|
match fontdue::Font::from_bytes(data, fontdue::FontSettings::default()) {
|
||||||
|
Ok(f) => {
|
||||||
|
log::debug!("font: {}", p.display());
|
||||||
|
Some(f)
|
||||||
|
}
|
||||||
|
Err(e) => {
|
||||||
|
log::warn!("cannot parse font {}: {e}", p.display());
|
||||||
|
None
|
||||||
|
}
|
||||||
|
}
|
||||||
|
});
|
||||||
|
if font.is_none() {
|
||||||
|
log::warn!("no usable font found: keystrokes, text and callout numbers will not be drawn");
|
||||||
|
}
|
||||||
|
Self { font, cache: HashMap::new() }
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn none() -> Self {
|
||||||
|
Self { font: None, cache: HashMap::new() }
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn available(&self) -> bool {
|
||||||
|
self.font.is_some()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn glyph(&mut self, ch: char, px: f32) -> Option<&(fontdue::Metrics, Vec<u8>)> {
|
||||||
|
let font = self.font.as_ref()?;
|
||||||
|
let key = (ch, (px * 4.0) as u32);
|
||||||
|
Some(self.cache.entry(key).or_insert_with(|| font.rasterize(ch, px)))
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn measure(&mut self, text: &str, px: f32) -> f32 {
|
||||||
|
text.chars().map(|c| self.glyph(c, px).map_or(0.0, |g| g.0.advance_width)).sum()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// (ascent, descent) in pixels for the given size; descent is positive.
|
||||||
|
pub fn vmetrics(&self, px: f32) -> (f32, f32) {
|
||||||
|
self.font.as_ref().and_then(|f| f.horizontal_line_metrics(px)).map_or((px * 0.8, px * 0.2), |m| (m.ascent, -m.descent))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Draw `text` with its left edge at `x` and baseline at `baseline`.
|
||||||
|
pub fn draw(&mut self, pm: &mut Pixmap, text: &str, x: f32, baseline: f32, px: f32, color: Color, alpha: f32) {
|
||||||
|
let (w, h) = (pm.width() as i32, pm.height() as i32);
|
||||||
|
let base_a = color.a as f32 / 255.0 * alpha;
|
||||||
|
if base_a <= 0.0 {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
let mut pen = x;
|
||||||
|
for ch in text.chars() {
|
||||||
|
let Some((m, bitmap)) = self.glyph(ch, px).map(|g| (g.0, g.1.clone())) else { return };
|
||||||
|
let gx = (pen + m.xmin as f32).round() as i32;
|
||||||
|
let gy = (baseline - m.ymin as f32 - m.height as f32).round() as i32;
|
||||||
|
let data = pm.data_mut();
|
||||||
|
for row in 0..m.height as i32 {
|
||||||
|
let py = gy + row;
|
||||||
|
if py < 0 || py >= h {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
for col in 0..m.width as i32 {
|
||||||
|
let pxl = gx + col;
|
||||||
|
if pxl < 0 || pxl >= w {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
let cov = bitmap[(row * m.width as i32 + col) as usize];
|
||||||
|
if cov == 0 {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
let a = cov as f32 / 255.0 * base_a;
|
||||||
|
let i = ((py * w + pxl) * 4) as usize;
|
||||||
|
let inv = 1.0 - a;
|
||||||
|
// Pixmap data is premultiplied RGBA.
|
||||||
|
data[i] = (color.r as f32 * a + data[i] as f32 * inv).round().min(255.0) as u8;
|
||||||
|
data[i + 1] = (color.g as f32 * a + data[i + 1] as f32 * inv).round().min(255.0) as u8;
|
||||||
|
data[i + 2] = (color.b as f32 * a + data[i + 2] as f32 * inv).round().min(255.0) as u8;
|
||||||
|
data[i + 3] = (255.0 * a + data[i + 3] as f32 * inv).round().min(255.0) as u8;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
pen += m.advance_width;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,162 @@
|
|||||||
|
//! System tray icon (StatusNotifierItem, the KDE/freedesktop standard).
|
||||||
|
//! Works natively on KDE, XFCE, Cinnamon, MATE…; GNOME needs the AppIndicator extension.
|
||||||
|
|
||||||
|
use crate::config::*;
|
||||||
|
use crate::control::{Command, Hub};
|
||||||
|
use crate::i18n::{Lang, opt, t};
|
||||||
|
use ksni::menu::{CheckmarkItem, MenuItem, RadioGroup, RadioItem, StandardItem, SubMenu};
|
||||||
|
use tiny_skia::{Color as Sk, FillRule, Paint, PathBuilder, Pixmap, Stroke, Transform};
|
||||||
|
|
||||||
|
pub struct TrayIcon {
|
||||||
|
pub cfg: Config,
|
||||||
|
pub lang: Lang,
|
||||||
|
pub hub: Hub,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 32×32 ring icon drawn at runtime so no icon theme or asset file is needed.
|
||||||
|
fn icon(size: u32) -> ksni::Icon {
|
||||||
|
let mut pm = Pixmap::new(size, size).unwrap();
|
||||||
|
let s = size as f32;
|
||||||
|
let mut bg = Paint::default();
|
||||||
|
bg.set_color(Sk::from_rgba8(30, 32, 40, 235));
|
||||||
|
bg.anti_alias = true;
|
||||||
|
if let Some(p) = PathBuilder::from_circle(s / 2.0, s / 2.0, s * 0.47) {
|
||||||
|
pm.fill_path(&p, &bg, FillRule::Winding, Transform::identity(), None);
|
||||||
|
}
|
||||||
|
let mut ring = Paint::default();
|
||||||
|
ring.set_color(Sk::from_rgba8(255, 193, 7, 255));
|
||||||
|
ring.anti_alias = true;
|
||||||
|
if let Some(p) = PathBuilder::from_circle(s / 2.0, s / 2.0, s * 0.27) {
|
||||||
|
let st = Stroke { width: s * 0.11, ..Stroke::default() };
|
||||||
|
pm.stroke_path(&p, &ring, &st, Transform::identity(), None);
|
||||||
|
}
|
||||||
|
// StatusNotifierItem wants straight (non-premultiplied) ARGB32, big-endian.
|
||||||
|
let mut data = Vec::with_capacity((size * size * 4) as usize);
|
||||||
|
for px in pm.pixels() {
|
||||||
|
let c = px.demultiply();
|
||||||
|
data.extend_from_slice(&[c.alpha(), c.red(), c.green(), c.blue()]);
|
||||||
|
}
|
||||||
|
ksni::Icon { width: size as i32, height: size as i32, data }
|
||||||
|
}
|
||||||
|
|
||||||
|
impl TrayIcon {
|
||||||
|
fn check(&self, key: &'static str, checked: bool, effect: &'static str) -> MenuItem<Self> {
|
||||||
|
CheckmarkItem {
|
||||||
|
label: t(self.lang, key).into(),
|
||||||
|
checked,
|
||||||
|
activate: Box::new(move |this: &mut Self| this.hub.send(Command::Toggle(effect.into()))),
|
||||||
|
..Default::default()
|
||||||
|
}
|
||||||
|
.into()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn radio<T: Copy + PartialEq + Send + Sync + 'static>(
|
||||||
|
&self,
|
||||||
|
title: &'static str,
|
||||||
|
all: &'static [T],
|
||||||
|
current: T,
|
||||||
|
id: fn(T) -> &'static str,
|
||||||
|
key: &'static str,
|
||||||
|
) -> MenuItem<Self> {
|
||||||
|
let lang = self.lang;
|
||||||
|
SubMenu {
|
||||||
|
label: t(lang, title).into(),
|
||||||
|
submenu: vec![
|
||||||
|
RadioGroup {
|
||||||
|
selected: all.iter().position(|v| *v == current).unwrap_or(0),
|
||||||
|
select: Box::new(move |this: &mut Self, i| {
|
||||||
|
if let Some(v) = all.get(i) {
|
||||||
|
this.hub.send(Command::SetOption(key.into(), id(*v).into()));
|
||||||
|
}
|
||||||
|
}),
|
||||||
|
options: all.iter().map(|v| RadioItem { label: opt(lang, id(*v)), ..Default::default() }).collect(),
|
||||||
|
}
|
||||||
|
.into(),
|
||||||
|
],
|
||||||
|
..Default::default()
|
||||||
|
}
|
||||||
|
.into()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl ksni::Tray for TrayIcon {
|
||||||
|
fn id(&self) -> String {
|
||||||
|
"sourizz".into()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn title(&self) -> String {
|
||||||
|
"Sourizz".into()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn icon_pixmap(&self) -> Vec<ksni::Icon> {
|
||||||
|
vec![icon(22), icon(32), icon(48)]
|
||||||
|
}
|
||||||
|
|
||||||
|
fn icon_name(&self) -> String {
|
||||||
|
String::new()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Left click toggles everything.
|
||||||
|
fn activate(&mut self, _x: i32, _y: i32) {
|
||||||
|
self.hub.send(Command::Toggle("all".into()));
|
||||||
|
}
|
||||||
|
|
||||||
|
fn menu(&self) -> Vec<MenuItem<Self>> {
|
||||||
|
let c = &self.cfg;
|
||||||
|
let l = self.lang;
|
||||||
|
vec![
|
||||||
|
self.check("enabled", c.general.enabled, "all"),
|
||||||
|
MenuItem::Separator,
|
||||||
|
self.check("spotlight", c.spotlight.enabled, "spotlight"),
|
||||||
|
self.check("ring", c.ring.enabled, "ring"),
|
||||||
|
self.check("trail", c.trail.enabled, "trail"),
|
||||||
|
self.check("clicks", c.clicks.enabled, "clicks"),
|
||||||
|
self.check("sound", c.sound.enabled, "sound"),
|
||||||
|
self.check("shake", c.shake.enabled, "shake"),
|
||||||
|
self.check("annotate", c.annotate.enabled, "annotate"),
|
||||||
|
self.check("keystrokes", c.keystrokes.enabled, "keystrokes"),
|
||||||
|
self.check("focus", c.focus.enabled, "focus"),
|
||||||
|
MenuItem::Separator,
|
||||||
|
SubMenu {
|
||||||
|
label: t(l, "styles").into(),
|
||||||
|
submenu: vec![
|
||||||
|
self.radio("spot_shape", SpotShape::ALL, c.spotlight.shape, SpotShape::id, "spotlight.shape"),
|
||||||
|
self.radio("ring_style", RingStyle::ALL, c.ring.style, RingStyle::id, "ring.style"),
|
||||||
|
self.radio("trail_style", TrailStyle::ALL, c.trail.style, TrailStyle::id, "trail.style"),
|
||||||
|
self.radio("click_style", ClickStyle::ALL, c.clicks.style, ClickStyle::id, "clicks.style"),
|
||||||
|
self.radio("key_style", KeyStyle::ALL, c.keystrokes.style, KeyStyle::id, "keystrokes.style"),
|
||||||
|
],
|
||||||
|
..Default::default()
|
||||||
|
}
|
||||||
|
.into(),
|
||||||
|
MenuItem::Separator,
|
||||||
|
StandardItem {
|
||||||
|
label: t(l, "annotation_mode").into(),
|
||||||
|
activate: Box::new(|this: &mut Self| this.hub.send(Command::AnnotateToggle)),
|
||||||
|
..Default::default()
|
||||||
|
}
|
||||||
|
.into(),
|
||||||
|
StandardItem {
|
||||||
|
label: t(l, "clear_annotations").into(),
|
||||||
|
activate: Box::new(|this: &mut Self| this.hub.send(Command::AnnotateClear)),
|
||||||
|
..Default::default()
|
||||||
|
}
|
||||||
|
.into(),
|
||||||
|
MenuItem::Separator,
|
||||||
|
StandardItem {
|
||||||
|
label: t(l, "settings").into(),
|
||||||
|
icon_name: "preferences-system".into(),
|
||||||
|
activate: Box::new(|this: &mut Self| this.hub.send(Command::Settings)),
|
||||||
|
..Default::default()
|
||||||
|
}
|
||||||
|
.into(),
|
||||||
|
StandardItem {
|
||||||
|
label: t(l, "quit").into(),
|
||||||
|
icon_name: "application-exit".into(),
|
||||||
|
activate: Box::new(|this: &mut Self| this.hub.send(Command::Quit)),
|
||||||
|
..Default::default()
|
||||||
|
}
|
||||||
|
.into(),
|
||||||
|
]
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,678 @@
|
|||||||
|
//! Wayland backend (wlroots layer-shell: KDE Plasma, Hyprland, sway, river, niri, COSMIC…).
|
||||||
|
//!
|
||||||
|
//! GNOME's Mutter does not implement layer-shell, so it cannot host the overlay; use an X11
|
||||||
|
//! session there (see the README).
|
||||||
|
//!
|
||||||
|
//! * One full-output layer surface per monitor on the `overlay` layer, with an *empty input
|
||||||
|
//! region* so every click passes through.
|
||||||
|
//! * Software rendering into `wl_shm` buffers; only damaged rectangles are reported.
|
||||||
|
//! * Global clicks and keystrokes come from evdev, the pointer position from the compositor
|
||||||
|
//! when it can tell us (see [`crate::wlsrc`]).
|
||||||
|
//! * Annotation mode temporarily gives one layer a full input region and exclusive keyboard
|
||||||
|
//! focus, and then real Wayland pointer/keyboard events are used.
|
||||||
|
|
||||||
|
use crate::canvas::Layer;
|
||||||
|
use crate::config::Chord;
|
||||||
|
use crate::control::{self, Command};
|
||||||
|
use crate::core::Core;
|
||||||
|
use crate::evdev_in::{self, Devices, Raw};
|
||||||
|
use crate::geom::IRect;
|
||||||
|
use crate::input::{Action, InputEvent};
|
||||||
|
use crate::keysym;
|
||||||
|
use crate::kwin::KwinFeed;
|
||||||
|
use crate::wlsrc::{Estimate, Hyprland};
|
||||||
|
use crate::xkb::{self, Xkb};
|
||||||
|
use anyhow::{Context, Result, anyhow};
|
||||||
|
use rustix::event::{PollFd, PollFlags, Timespec, poll};
|
||||||
|
use rustix::fd::{BorrowedFd, OwnedFd};
|
||||||
|
use smithay_client_toolkit::{
|
||||||
|
compositor::{CompositorHandler, CompositorState, FrameCallbackData, Region},
|
||||||
|
delegate_registry,
|
||||||
|
dispatch2::Dispatch2,
|
||||||
|
output::{OutputHandler, OutputState},
|
||||||
|
registry::{ProvidesRegistryState, RegistryState},
|
||||||
|
registry_handlers,
|
||||||
|
seat::{
|
||||||
|
Capability, SeatHandler, SeatState,
|
||||||
|
pointer::{PointerEvent, PointerEventKind, PointerHandler},
|
||||||
|
},
|
||||||
|
shell::{
|
||||||
|
WaylandSurface,
|
||||||
|
wlr_layer::{Anchor, KeyboardInteractivity, Layer as WlrLayer, LayerShell, LayerShellHandler, LayerSurface, LayerSurfaceConfigure},
|
||||||
|
},
|
||||||
|
shm::{Shm, ShmHandler, slot::SlotPool},
|
||||||
|
};
|
||||||
|
use wayland_client::{
|
||||||
|
Connection, QueueHandle, WEnum,
|
||||||
|
globals::registry_queue_init,
|
||||||
|
protocol::{wl_keyboard, wl_output, wl_pointer, wl_seat, wl_shm, wl_surface},
|
||||||
|
};
|
||||||
|
|
||||||
|
/// Marks our `wl_keyboard` objects so events are routed to [`Dispatch2`] below.
|
||||||
|
struct KbData;
|
||||||
|
|
||||||
|
enum Source {
|
||||||
|
Hyprland(Hyprland),
|
||||||
|
/// KDE Plasma: a KWin script pushes the position to us.
|
||||||
|
Kwin(KwinFeed),
|
||||||
|
/// Position is dead-reckoned from relative evdev motion.
|
||||||
|
Estimate,
|
||||||
|
}
|
||||||
|
|
||||||
|
struct OutputLayer {
|
||||||
|
output: wl_output::WlOutput,
|
||||||
|
layer: LayerSurface,
|
||||||
|
canvas: Layer,
|
||||||
|
rect: IRect,
|
||||||
|
configured: bool,
|
||||||
|
frame_pending: bool,
|
||||||
|
pending: Vec<IRect>,
|
||||||
|
}
|
||||||
|
|
||||||
|
struct App {
|
||||||
|
registry_state: RegistryState,
|
||||||
|
seat_state: SeatState,
|
||||||
|
output_state: OutputState,
|
||||||
|
compositor: CompositorState,
|
||||||
|
layer_shell: LayerShell,
|
||||||
|
shm: Shm,
|
||||||
|
pool: SlotPool,
|
||||||
|
layers: Vec<OutputLayer>,
|
||||||
|
core: Core,
|
||||||
|
|
||||||
|
pointer: Option<wl_pointer::WlPointer>,
|
||||||
|
keyboard: Option<wl_keyboard::WlKeyboard>,
|
||||||
|
/// Layer index that currently owns input (annotation mode).
|
||||||
|
capture: Option<usize>,
|
||||||
|
/// Compositor keymap, used only while annotation mode has keyboard focus.
|
||||||
|
cap_xkb: Option<Xkb>,
|
||||||
|
|
||||||
|
devices: Devices,
|
||||||
|
/// Layout-based translation for global (evdev) key events.
|
||||||
|
kb_xkb: Option<Xkb>,
|
||||||
|
source: Source,
|
||||||
|
estimate: Estimate,
|
||||||
|
hotkeys: Vec<(&'static str, Chord)>,
|
||||||
|
hotkeys_for: crate::config::Hotkeys,
|
||||||
|
|
||||||
|
last_pos: Option<(f32, f32)>,
|
||||||
|
moved: bool,
|
||||||
|
dirty: bool,
|
||||||
|
next_frame: Option<f64>,
|
||||||
|
last_frame: f64,
|
||||||
|
next_pos_poll: f64,
|
||||||
|
monitors_dirty: bool,
|
||||||
|
exit: bool,
|
||||||
|
}
|
||||||
|
|
||||||
|
// ------------------------------------------------------------------ SCTK handlers
|
||||||
|
|
||||||
|
impl CompositorHandler for App {
|
||||||
|
fn scale_factor_changed(&mut self, _: &Connection, _: &QueueHandle<Self>, _: &wl_surface::WlSurface, _: i32) {}
|
||||||
|
fn transform_changed(&mut self, _: &Connection, _: &QueueHandle<Self>, _: &wl_surface::WlSurface, _: wl_output::Transform) {}
|
||||||
|
fn surface_enter(&mut self, _: &Connection, _: &QueueHandle<Self>, _: &wl_surface::WlSurface, _: &wl_output::WlOutput) {}
|
||||||
|
fn surface_leave(&mut self, _: &Connection, _: &QueueHandle<Self>, _: &wl_surface::WlSurface, _: &wl_output::WlOutput) {}
|
||||||
|
|
||||||
|
fn frame(&mut self, _: &Connection, qh: &QueueHandle<Self>, surface: &wl_surface::WlSurface, _: u32) {
|
||||||
|
if let Some(i) = self.layers.iter().position(|l| l.layer.wl_surface() == surface) {
|
||||||
|
log::debug!("frame callback for layer {i}, pending damage: {}", self.layers[i].pending.len());
|
||||||
|
self.layers[i].frame_pending = false;
|
||||||
|
if !self.layers[i].pending.is_empty() {
|
||||||
|
self.commit_layer(i, qh);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl OutputHandler for App {
|
||||||
|
fn output_state(&mut self) -> &mut OutputState {
|
||||||
|
&mut self.output_state
|
||||||
|
}
|
||||||
|
|
||||||
|
fn new_output(&mut self, _: &Connection, qh: &QueueHandle<Self>, output: wl_output::WlOutput) {
|
||||||
|
self.add_layer(qh, output);
|
||||||
|
}
|
||||||
|
|
||||||
|
fn update_output(&mut self, _: &Connection, _: &QueueHandle<Self>, _: wl_output::WlOutput) {
|
||||||
|
self.monitors_dirty = true;
|
||||||
|
}
|
||||||
|
|
||||||
|
fn output_destroyed(&mut self, _: &Connection, _: &QueueHandle<Self>, output: wl_output::WlOutput) {
|
||||||
|
self.layers.retain(|l| l.output != output);
|
||||||
|
self.monitors_dirty = true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl LayerShellHandler for App {
|
||||||
|
fn closed(&mut self, _: &Connection, _: &QueueHandle<Self>, layer: &LayerSurface) {
|
||||||
|
self.layers.retain(|l| l.layer.wl_surface() != layer.wl_surface());
|
||||||
|
self.monitors_dirty = true;
|
||||||
|
}
|
||||||
|
|
||||||
|
fn configure(&mut self, _: &Connection, _: &QueueHandle<Self>, layer: &LayerSurface, configure: LayerSurfaceConfigure, _serial: u32) {
|
||||||
|
let Some(i) = self.layers.iter().position(|l| l.layer.wl_surface() == layer.wl_surface()) else { return };
|
||||||
|
let info = self.output_state.info(&self.layers[i].output);
|
||||||
|
let (mut w, mut h) = (configure.new_size.0 as i32, configure.new_size.1 as i32);
|
||||||
|
if w == 0 || h == 0 {
|
||||||
|
if let Some((lw, lh)) = info.as_ref().and_then(|o| o.logical_size) {
|
||||||
|
(w, h) = (lw, lh);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if w == 0 || h == 0 {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
let (x, y) = info.as_ref().and_then(|o| o.logical_position).or(info.as_ref().map(|o| o.location)).unwrap_or((0, 0));
|
||||||
|
let l = &mut self.layers[i];
|
||||||
|
let rect = IRect::from_xywh(x, y, w, h);
|
||||||
|
if rect != l.rect || !l.configured {
|
||||||
|
l.rect = rect;
|
||||||
|
l.canvas = Layer::new(rect, true);
|
||||||
|
l.pending.clear();
|
||||||
|
l.frame_pending = false;
|
||||||
|
}
|
||||||
|
l.configured = true;
|
||||||
|
self.monitors_dirty = true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl SeatHandler for App {
|
||||||
|
fn seat_state(&mut self) -> &mut SeatState {
|
||||||
|
&mut self.seat_state
|
||||||
|
}
|
||||||
|
|
||||||
|
fn new_seat(&mut self, _: &Connection, _: &QueueHandle<Self>, _: wl_seat::WlSeat) {}
|
||||||
|
|
||||||
|
fn new_capability(&mut self, _: &Connection, qh: &QueueHandle<Self>, seat: wl_seat::WlSeat, cap: Capability) {
|
||||||
|
if cap == Capability::Pointer && self.pointer.is_none() {
|
||||||
|
self.pointer = self.seat_state.get_pointer(qh, &seat).ok();
|
||||||
|
}
|
||||||
|
if cap == Capability::Keyboard && self.keyboard.is_none() {
|
||||||
|
self.keyboard = Some(seat.get_keyboard(qh, KbData));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn remove_capability(&mut self, _: &Connection, _: &QueueHandle<Self>, _: wl_seat::WlSeat, cap: Capability) {
|
||||||
|
if cap == Capability::Pointer {
|
||||||
|
if let Some(p) = self.pointer.take() {
|
||||||
|
p.release();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if cap == Capability::Keyboard {
|
||||||
|
if let Some(k) = self.keyboard.take() {
|
||||||
|
k.release();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn remove_seat(&mut self, _: &Connection, _: &QueueHandle<Self>, _: wl_seat::WlSeat) {}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl PointerHandler for App {
|
||||||
|
fn pointer_frame(&mut self, _: &Connection, _: &QueueHandle<Self>, _: &wl_pointer::WlPointer, events: &[PointerEvent]) {
|
||||||
|
let Some(ci) = self.capture else { return };
|
||||||
|
for ev in events {
|
||||||
|
let Some(l) = self.layers.get(ci) else { return };
|
||||||
|
if &ev.surface != l.layer.wl_surface() {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
let (x, y) = (l.rect.x0 as f32 + ev.position.0 as f32, l.rect.y0 as f32 + ev.position.1 as f32);
|
||||||
|
self.estimate.sync((x, y));
|
||||||
|
match ev.kind {
|
||||||
|
PointerEventKind::Enter { .. } | PointerEventKind::Motion { .. } => self.feed(InputEvent::Pointer { x, y }),
|
||||||
|
PointerEventKind::Press { button, .. } | PointerEventKind::Release { button, .. } => {
|
||||||
|
let pressed = matches!(ev.kind, PointerEventKind::Press { .. });
|
||||||
|
if let Some(b) = evdev_in::button_from_code(button as u16) {
|
||||||
|
self.feed(InputEvent::Pointer { x, y });
|
||||||
|
self.feed(InputEvent::Button { button: b, pressed });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
_ => {}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl ShmHandler for App {
|
||||||
|
fn shm_state(&mut self) -> &mut Shm {
|
||||||
|
&mut self.shm
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Dispatch2<wl_keyboard::WlKeyboard, App> for KbData {
|
||||||
|
fn event(&self, app: &mut App, _: &wl_keyboard::WlKeyboard, event: wl_keyboard::Event, _: &Connection, _: &QueueHandle<App>) {
|
||||||
|
use wl_keyboard::Event;
|
||||||
|
match event {
|
||||||
|
Event::Keymap { fd, size, .. } => {
|
||||||
|
// The descriptor shares its file offset with the compositor, which has just
|
||||||
|
// written the text and left the offset at the end: read from 0 explicitly.
|
||||||
|
let mut buf = vec![0u8; size as usize];
|
||||||
|
let file = std::fs::File::from(fd);
|
||||||
|
if std::os::unix::fs::FileExt::read_exact_at(&file, &mut buf, 0).is_ok() {
|
||||||
|
app.cap_xkb = Xkb::from_keymap_string(&String::from_utf8_lossy(&buf));
|
||||||
|
if app.cap_xkb.is_none() {
|
||||||
|
log::warn!("could not parse the compositor's keyboard layout; annotation text entry is disabled");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Event::Enter { keys, .. } => {
|
||||||
|
// Replay keys already held (e.g. the hotkey that opened annotation mode) so
|
||||||
|
// the modifier state is right.
|
||||||
|
if let Some(x) = app.cap_xkb.as_mut() {
|
||||||
|
x.reset();
|
||||||
|
for chunk in keys.chunks_exact(4) {
|
||||||
|
let code = u32::from_ne_bytes([chunk[0], chunk[1], chunk[2], chunk[3]]);
|
||||||
|
let _ = x.event(code, true, false);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Event::Key { key, state, .. } if app.capture.is_some() => {
|
||||||
|
let pressed = matches!(state, WEnum::Value(wl_keyboard::KeyState::Pressed));
|
||||||
|
if let Some(x) = app.cap_xkb.as_mut() {
|
||||||
|
let ev = x.event(key, pressed, false);
|
||||||
|
if pressed {
|
||||||
|
app.run_hotkey_for(&ev, key);
|
||||||
|
}
|
||||||
|
app.feed(InputEvent::Key(ev));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
_ => {}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
delegate_registry!(App);
|
||||||
|
smithay_client_toolkit::delegate_dispatch2!(App);
|
||||||
|
|
||||||
|
impl ProvidesRegistryState for App {
|
||||||
|
fn registry(&mut self) -> &mut RegistryState {
|
||||||
|
&mut self.registry_state
|
||||||
|
}
|
||||||
|
registry_handlers![OutputState, SeatState];
|
||||||
|
}
|
||||||
|
|
||||||
|
// ------------------------------------------------------------------ App logic
|
||||||
|
|
||||||
|
impl App {
|
||||||
|
fn feed(&mut self, ev: InputEvent) {
|
||||||
|
if let InputEvent::Pointer { x, y } = ev {
|
||||||
|
self.last_pos = Some((x, y));
|
||||||
|
}
|
||||||
|
self.core.handle_input(ev);
|
||||||
|
self.dirty = true;
|
||||||
|
}
|
||||||
|
|
||||||
|
fn add_layer(&mut self, qh: &QueueHandle<Self>, output: wl_output::WlOutput) {
|
||||||
|
if self.layers.iter().any(|l| l.output == output) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
let surface = self.compositor.create_surface(qh);
|
||||||
|
let layer = self.layer_shell.create_layer_surface(qh, surface, WlrLayer::Overlay, Some("sourizz"), Some(&output));
|
||||||
|
layer.set_anchor(Anchor::TOP | Anchor::BOTTOM | Anchor::LEFT | Anchor::RIGHT);
|
||||||
|
layer.set_exclusive_zone(-1);
|
||||||
|
layer.set_keyboard_interactivity(KeyboardInteractivity::None);
|
||||||
|
layer.set_size(0, 0);
|
||||||
|
self.make_click_through(&layer);
|
||||||
|
layer.commit();
|
||||||
|
self.layers.push(OutputLayer {
|
||||||
|
output,
|
||||||
|
layer,
|
||||||
|
canvas: Layer::new(IRect::new(0, 0, 1, 1), true),
|
||||||
|
rect: IRect::new(0, 0, 0, 0),
|
||||||
|
configured: false,
|
||||||
|
frame_pending: false,
|
||||||
|
pending: Vec::new(),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
fn make_click_through(&self, layer: &LayerSurface) {
|
||||||
|
// An empty (but present) input region means "no part of this surface takes input".
|
||||||
|
if let Ok(region) = Region::new(&self.compositor) {
|
||||||
|
layer.set_input_region(Some(region.wl_region()));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn rebuild_monitors(&mut self) {
|
||||||
|
self.monitors_dirty = false;
|
||||||
|
let rects: Vec<IRect> = self.layers.iter().filter(|l| l.configured).map(|l| l.rect).collect();
|
||||||
|
if rects.is_empty() {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
let all = rects.iter().fold(IRect::new(0, 0, 0, 0), |a, r| a.union(*r));
|
||||||
|
self.estimate.set_bounds(all);
|
||||||
|
self.core.engine.set_monitors(rects);
|
||||||
|
self.core.engine.request_full_redraw();
|
||||||
|
for l in &mut self.layers {
|
||||||
|
l.pending.clear();
|
||||||
|
if l.configured {
|
||||||
|
l.pending.push(IRect::from_xywh(0, 0, l.rect.width(), l.rect.height()));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
self.dirty = true;
|
||||||
|
}
|
||||||
|
|
||||||
|
fn commit_layer(&mut self, i: usize, qh: &QueueHandle<Self>) {
|
||||||
|
let l = &mut self.layers[i];
|
||||||
|
let (w, h) = (l.canvas.w as i32, l.canvas.h as i32);
|
||||||
|
log::debug!("commit layer {i}: {w}x{h}, {} damage rect(s)", l.pending.len());
|
||||||
|
let Ok((buffer, canvas)) = self.pool.create_buffer(w, h, w * 4, wl_shm::Format::Argb8888) else {
|
||||||
|
log::warn!("cannot allocate a {w}x{h} buffer");
|
||||||
|
return;
|
||||||
|
};
|
||||||
|
canvas.copy_from_slice(&l.canvas.bgra);
|
||||||
|
let surface = l.layer.wl_surface().clone();
|
||||||
|
for r in l.pending.drain(..) {
|
||||||
|
surface.damage_buffer(r.x0, r.y0, r.width(), r.height());
|
||||||
|
}
|
||||||
|
surface.frame(qh, FrameCallbackData(surface.clone()));
|
||||||
|
if buffer.attach_to(&surface).is_ok() {
|
||||||
|
l.layer.commit();
|
||||||
|
l.frame_pending = true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn frame(&mut self, qh: &QueueHandle<Self>) {
|
||||||
|
let now = self.core.now();
|
||||||
|
self.last_frame = now;
|
||||||
|
self.dirty = false;
|
||||||
|
let plan = self.core.engine.begin_frame(now);
|
||||||
|
for i in 0..self.layers.len() {
|
||||||
|
if !self.layers[i].configured {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
let patches = self.layers[i].canvas.repaint(&mut self.core.engine, &plan.damage, now);
|
||||||
|
self.layers[i].pending.extend(patches.iter().map(|p| p.rect));
|
||||||
|
log::debug!("frame: layer {i} pending={} frame_pending={}", self.layers[i].pending.len(), self.layers[i].frame_pending);
|
||||||
|
if !self.layers[i].pending.is_empty() && !self.layers[i].frame_pending {
|
||||||
|
self.commit_layer(i, qh);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
self.next_frame = plan.next_in.map(|dt| now + dt);
|
||||||
|
}
|
||||||
|
|
||||||
|
fn sync_pointer(&mut self) {
|
||||||
|
if self.capture.is_some() {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
let pos = match &self.source {
|
||||||
|
Source::Hyprland(h) => h.cursor_pos(),
|
||||||
|
Source::Kwin(k) => k.take_latest(),
|
||||||
|
Source::Estimate => Some(self.estimate.pos()),
|
||||||
|
};
|
||||||
|
if let Some((x, y)) = pos {
|
||||||
|
if self.last_pos != Some((x, y)) {
|
||||||
|
self.estimate.sync((x, y));
|
||||||
|
self.feed(InputEvent::Pointer { x, y });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn handle_raw(&mut self, raws: Vec<Raw>) {
|
||||||
|
for raw in raws {
|
||||||
|
if self.capture.is_some() {
|
||||||
|
continue; // real Wayland events are used while annotating
|
||||||
|
}
|
||||||
|
match raw {
|
||||||
|
Raw::Motion(dx, dy) => {
|
||||||
|
self.estimate.motion(dx, dy);
|
||||||
|
self.moved = true;
|
||||||
|
}
|
||||||
|
Raw::MotionHint => self.moved = true,
|
||||||
|
Raw::Button(button, pressed) => {
|
||||||
|
self.sync_pointer();
|
||||||
|
self.feed(InputEvent::Button { button, pressed });
|
||||||
|
}
|
||||||
|
Raw::Key { code, pressed, repeat } => {
|
||||||
|
let Some(x) = self.kb_xkb.as_mut() else { continue };
|
||||||
|
let ev = x.event(code, pressed, repeat);
|
||||||
|
if pressed && !repeat {
|
||||||
|
self.run_hotkey_for(&ev, code);
|
||||||
|
}
|
||||||
|
self.feed(InputEvent::Key(ev));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if self.moved {
|
||||||
|
self.moved = false;
|
||||||
|
self.sync_pointer();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Fire a configured global hotkey if this key press completes one.
|
||||||
|
fn run_hotkey_for(&mut self, ev: &crate::input::KeyEvent, evdev_code: u32) {
|
||||||
|
if self.hotkeys_for != self.core.cfg.hotkeys {
|
||||||
|
self.hotkeys = control::hotkey_table(&self.core.cfg.hotkeys);
|
||||||
|
self.hotkeys_for = self.core.cfg.hotkeys.clone();
|
||||||
|
}
|
||||||
|
let base = self.kb_xkb.as_ref().map(|x| x.base_keysym(evdev_code)).unwrap_or(0);
|
||||||
|
let base = if base == 0 { keysym::from_name(&ev.name).unwrap_or(0) } else { base };
|
||||||
|
let hit = self.hotkeys.iter().find(|(_, c)| c.mods == ev.mods && keysym::from_name(&c.key) == Some(base)).map(|(n, _)| *n);
|
||||||
|
if let Some(cmd) = hit.and_then(control::hotkey_command) {
|
||||||
|
self.core.apply(cmd);
|
||||||
|
self.dirty = true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn process_actions(&mut self) {
|
||||||
|
for action in self.core.drain_actions() {
|
||||||
|
match action {
|
||||||
|
Action::Capture(true) => self.begin_capture(),
|
||||||
|
Action::Capture(false) => self.end_capture(),
|
||||||
|
Action::PlayClick(..) => {}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn begin_capture(&mut self) {
|
||||||
|
let at = self.last_pos.or(Some(self.estimate.pos()));
|
||||||
|
let idx = at
|
||||||
|
.and_then(|(x, y)| self.layers.iter().position(|l| l.configured && l.rect.contains(x, y)))
|
||||||
|
.or_else(|| self.layers.iter().position(|l| l.configured));
|
||||||
|
let Some(i) = idx else {
|
||||||
|
self.core.apply(Command::AnnotateToggle);
|
||||||
|
return;
|
||||||
|
};
|
||||||
|
let l = &self.layers[i];
|
||||||
|
l.layer.set_keyboard_interactivity(KeyboardInteractivity::Exclusive);
|
||||||
|
l.layer.set_input_region(None); // the whole surface takes input
|
||||||
|
l.layer.commit();
|
||||||
|
self.capture = Some(i);
|
||||||
|
if let Some(x) = self.cap_xkb.as_mut() {
|
||||||
|
x.reset();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn end_capture(&mut self) {
|
||||||
|
if let Some(i) = self.capture.take() {
|
||||||
|
if let Some(l) = self.layers.get(i) {
|
||||||
|
l.layer.set_keyboard_interactivity(KeyboardInteractivity::None);
|
||||||
|
self.make_click_through(&l.layer);
|
||||||
|
l.layer.commit();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
self.dirty = true;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// One pass of non-blocking work between waits.
|
||||||
|
fn tick(&mut self, qh: &QueueHandle<Self>) {
|
||||||
|
if self.core.pump() {
|
||||||
|
self.dirty = true;
|
||||||
|
}
|
||||||
|
if self.monitors_dirty {
|
||||||
|
self.rebuild_monitors();
|
||||||
|
}
|
||||||
|
self.process_actions();
|
||||||
|
// KWin pushes positions to us (and wakes the loop); apply the newest one.
|
||||||
|
if matches!(self.source, Source::Kwin(_)) {
|
||||||
|
self.sync_pointer();
|
||||||
|
}
|
||||||
|
// Hyprland can be asked for the position; poll it when evdev cannot tell us it moved.
|
||||||
|
let now = self.core.now();
|
||||||
|
if matches!(self.source, Source::Hyprland(_)) && self.devices.is_empty() && now >= self.next_pos_poll {
|
||||||
|
self.next_pos_poll = now + 0.033;
|
||||||
|
self.sync_pointer();
|
||||||
|
}
|
||||||
|
let min_interval = 1.0 / self.core.cfg.general.fps as f64;
|
||||||
|
let due = self.dirty || self.next_frame.is_some_and(|t| now >= t);
|
||||||
|
if due && now - self.last_frame >= min_interval {
|
||||||
|
if !self.dirty && matches!(self.source, Source::Hyprland(_)) {
|
||||||
|
self.sync_pointer();
|
||||||
|
}
|
||||||
|
self.frame(qh);
|
||||||
|
self.process_actions();
|
||||||
|
}
|
||||||
|
if self.core.quit {
|
||||||
|
self.exit = true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn wait_timeout(&self) -> f64 {
|
||||||
|
let now = self.core.now();
|
||||||
|
let mut t = 0.5f64;
|
||||||
|
let min_interval = 1.0 / self.core.cfg.general.fps as f64;
|
||||||
|
if self.dirty {
|
||||||
|
t = t.min((self.last_frame + min_interval - now).max(0.0));
|
||||||
|
} else if let Some(n) = self.next_frame {
|
||||||
|
t = t.min((n - now).max(0.0));
|
||||||
|
}
|
||||||
|
if matches!(self.source, Source::Hyprland(_)) && self.devices.is_empty() {
|
||||||
|
t = t.min((self.next_pos_poll - now).max(0.0));
|
||||||
|
}
|
||||||
|
t
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn run(core: Core, wake: &OwnedFd) -> Result<()> {
|
||||||
|
let conn = Connection::connect_to_env().context("cannot connect to the Wayland compositor (is WAYLAND_DISPLAY set?)")?;
|
||||||
|
let (globals, mut queue) = registry_queue_init(&conn).context("reading the Wayland registry")?;
|
||||||
|
let qh = queue.handle();
|
||||||
|
|
||||||
|
let compositor = CompositorState::bind(&globals, &qh).context("compositor lacks wl_compositor")?;
|
||||||
|
let layer_shell = LayerShell::bind(&globals, &qh).map_err(|_| {
|
||||||
|
anyhow!(
|
||||||
|
"this compositor does not support wlr-layer-shell, which Sourizz needs to draw its overlay.\n\
|
||||||
|
GNOME (Mutter) is the usual case: log in with a \"GNOME on Xorg\" session, or use KDE Plasma, Hyprland, sway, …"
|
||||||
|
)
|
||||||
|
})?;
|
||||||
|
let shm = Shm::bind(&globals, &qh).context("compositor lacks wl_shm")?;
|
||||||
|
let pool = SlotPool::new(1 << 20, &shm).context("creating the shared-memory pool")?;
|
||||||
|
|
||||||
|
let devices = Devices::scan();
|
||||||
|
if devices.is_empty() {
|
||||||
|
log::warn!(
|
||||||
|
"no readable input devices ({} denied): global clicks and keystrokes are unavailable. \
|
||||||
|
Add yourself to the `input` group and log in again — see the README.",
|
||||||
|
devices.denied
|
||||||
|
);
|
||||||
|
}
|
||||||
|
let (layout, variant, options) = xkb::detect_layout();
|
||||||
|
let kb_xkb = Xkb::from_names(&layout, &variant, &options);
|
||||||
|
if kb_xkb.is_none() {
|
||||||
|
log::warn!("libxkbcommon not available: keystroke labels and hotkeys from the keyboard are disabled");
|
||||||
|
}
|
||||||
|
let source = if let Some(h) = Hyprland::detect() {
|
||||||
|
log::info!("pointer position: Hyprland IPC");
|
||||||
|
Source::Hyprland(h)
|
||||||
|
} else if let Some(k) = KwinFeed::start(core.hub()) {
|
||||||
|
log::info!("pointer position: KWin script");
|
||||||
|
Source::Kwin(k)
|
||||||
|
} else {
|
||||||
|
log::warn!("pointer position: estimated from relative mouse motion (approximate; exact on KDE Plasma and Hyprland)");
|
||||||
|
Source::Estimate
|
||||||
|
};
|
||||||
|
|
||||||
|
let mut app = App {
|
||||||
|
registry_state: RegistryState::new(&globals),
|
||||||
|
seat_state: SeatState::new(&globals, &qh),
|
||||||
|
output_state: OutputState::new(&globals, &qh),
|
||||||
|
compositor,
|
||||||
|
layer_shell,
|
||||||
|
shm,
|
||||||
|
pool,
|
||||||
|
layers: Vec::new(),
|
||||||
|
core,
|
||||||
|
pointer: None,
|
||||||
|
keyboard: None,
|
||||||
|
capture: None,
|
||||||
|
cap_xkb: None,
|
||||||
|
devices,
|
||||||
|
kb_xkb,
|
||||||
|
source,
|
||||||
|
estimate: Estimate::new(IRect::new(0, 0, 1920, 1080)),
|
||||||
|
hotkeys: Vec::new(),
|
||||||
|
hotkeys_for: crate::config::Hotkeys { toggle_all: "\0".into(), ..Default::default() },
|
||||||
|
last_pos: None,
|
||||||
|
moved: false,
|
||||||
|
dirty: true,
|
||||||
|
next_frame: None,
|
||||||
|
last_frame: f64::NEG_INFINITY,
|
||||||
|
next_pos_poll: 0.0,
|
||||||
|
monitors_dirty: false,
|
||||||
|
exit: false,
|
||||||
|
};
|
||||||
|
|
||||||
|
// Learn the outputs and get the first configure events.
|
||||||
|
queue.roundtrip(&mut app)?;
|
||||||
|
queue.roundtrip(&mut app)?;
|
||||||
|
if app.layers.is_empty() {
|
||||||
|
return Err(anyhow!("the compositor reported no outputs"));
|
||||||
|
}
|
||||||
|
log::info!("Wayland backend ready ({} output(s))", app.layers.len());
|
||||||
|
// Diagnostic hook: pretend the pointer is at x,y (useful on a compositor without input devices).
|
||||||
|
if let Some((x, y)) = std::env::var("SOURIZZ_FAKE_POINTER").ok().and_then(|v| {
|
||||||
|
let (a, b) = v.split_once(',')?;
|
||||||
|
Some((a.trim().parse::<f32>().ok()?, b.trim().parse::<f32>().ok()?))
|
||||||
|
}) {
|
||||||
|
app.rebuild_monitors();
|
||||||
|
app.estimate.sync((x, y));
|
||||||
|
app.feed(InputEvent::Pointer { x, y });
|
||||||
|
}
|
||||||
|
|
||||||
|
let mut last_scan = 0.0;
|
||||||
|
while !app.exit {
|
||||||
|
queue.dispatch_pending(&mut app)?;
|
||||||
|
app.tick(&qh);
|
||||||
|
if app.exit {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
conn.flush()?;
|
||||||
|
let Some(guard) = queue.prepare_read() else { continue };
|
||||||
|
|
||||||
|
let timeout = app.wait_timeout();
|
||||||
|
let ts = Timespec { tv_sec: timeout as i64, tv_nsec: (timeout.fract() * 1e9) as _ };
|
||||||
|
let wl_fd: BorrowedFd = guard.connection_fd();
|
||||||
|
let dev_fds = app.devices.fds();
|
||||||
|
let mut fds = vec![PollFd::new(&wl_fd, PollFlags::IN), PollFd::new(wake, PollFlags::IN)];
|
||||||
|
fds.extend(dev_fds.iter().map(|f| PollFd::new(f, PollFlags::IN)));
|
||||||
|
let _ = poll(&mut fds, Some(&ts));
|
||||||
|
let ready: Vec<bool> = fds.iter().map(|f| f.revents().intersects(PollFlags::IN | PollFlags::HUP | PollFlags::ERR)).collect();
|
||||||
|
drop(fds);
|
||||||
|
drop(dev_fds);
|
||||||
|
|
||||||
|
if ready[0] {
|
||||||
|
match guard.read() {
|
||||||
|
Ok(_) => {}
|
||||||
|
Err(wayland_client::backend::WaylandError::Io(e)) if e.kind() == std::io::ErrorKind::WouldBlock => {}
|
||||||
|
Err(e) => return Err(e).context("lost the connection to the compositor"),
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
drop(guard);
|
||||||
|
}
|
||||||
|
if ready[1] {
|
||||||
|
control::drain(wake);
|
||||||
|
}
|
||||||
|
// Highest index first: a device that vanished is removed from the list while reading.
|
||||||
|
for (n, r) in ready.iter().enumerate().skip(2).rev() {
|
||||||
|
if *r {
|
||||||
|
let raws = app.devices.read(n - 2);
|
||||||
|
app.handle_raw(raws);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
let now = app.core.now();
|
||||||
|
if now - last_scan > 3.0 {
|
||||||
|
last_scan = now;
|
||||||
|
app.devices.rescan();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
app.end_capture();
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
@@ -0,0 +1,121 @@
|
|||||||
|
//! Where the Wayland backend gets the pointer's absolute position from.
|
||||||
|
//!
|
||||||
|
//! Wayland gives a client no way to ask "where is the pointer?" unless the pointer is over
|
||||||
|
//! one of its own surfaces. Our overlay must stay click-through, so it never is. The options:
|
||||||
|
//!
|
||||||
|
//! * **Hyprland**: ask its IPC socket (exact).
|
||||||
|
//! * **KDE Plasma** (KWin): a small KWin script feeds us `workspace.cursorPos` (exact).
|
||||||
|
//! * **Anything else**: integrate the relative motion read from evdev (approximate: the
|
||||||
|
//! compositor applies pointer acceleration we cannot see, so it drifts; it is clamped to
|
||||||
|
//! the screen and re-synchronised whenever the pointer touches an annotation surface).
|
||||||
|
|
||||||
|
use crate::geom::IRect;
|
||||||
|
use std::io::{Read, Write};
|
||||||
|
use std::os::unix::net::UnixStream;
|
||||||
|
use std::path::PathBuf;
|
||||||
|
use std::time::Duration;
|
||||||
|
|
||||||
|
/// Parse the reply of Hyprland's `j/cursorpos` (`{"x": 123, "y": 456}`, numbers may be floats).
|
||||||
|
pub fn parse_cursorpos(json: &str) -> Option<(f32, f32)> {
|
||||||
|
let num = |key: &str| -> Option<f32> {
|
||||||
|
let i = json.find(&format!("\"{key}\""))? + key.len() + 2;
|
||||||
|
let rest = json[i..].trim_start().strip_prefix(':')?.trim_start();
|
||||||
|
let end =
|
||||||
|
rest.find(|c: char| !(c.is_ascii_digit() || c == '-' || c == '.' || c == 'e' || c == 'E' || c == '+')).unwrap_or(rest.len());
|
||||||
|
rest[..end].parse().ok()
|
||||||
|
};
|
||||||
|
Some((num("x")?, num("y")?))
|
||||||
|
}
|
||||||
|
|
||||||
|
pub struct Hyprland {
|
||||||
|
path: PathBuf,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Hyprland {
|
||||||
|
pub fn detect() -> Option<Hyprland> {
|
||||||
|
let sig = std::env::var("HYPRLAND_INSTANCE_SIGNATURE").ok()?;
|
||||||
|
let rt = std::env::var_os("XDG_RUNTIME_DIR").map(PathBuf::from)?;
|
||||||
|
let path = [rt.join("hypr").join(&sig).join(".socket.sock"), PathBuf::from("/tmp/hypr").join(&sig).join(".socket.sock")]
|
||||||
|
.into_iter()
|
||||||
|
.find(|p| p.exists())?;
|
||||||
|
Some(Hyprland { path })
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn cursor_pos(&self) -> Option<(f32, f32)> {
|
||||||
|
let mut s = UnixStream::connect(&self.path).ok()?;
|
||||||
|
s.set_read_timeout(Some(Duration::from_millis(60))).ok()?;
|
||||||
|
s.set_write_timeout(Some(Duration::from_millis(60))).ok()?;
|
||||||
|
s.write_all(b"j/cursorpos").ok()?;
|
||||||
|
let mut reply = String::new();
|
||||||
|
s.read_to_string(&mut reply).ok()?;
|
||||||
|
parse_cursorpos(&reply)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Dead-reckoning pointer position from relative evdev motion.
|
||||||
|
pub struct Estimate {
|
||||||
|
pos: (f32, f32),
|
||||||
|
bounds: IRect,
|
||||||
|
/// Multiplier from device counts to logical pixels.
|
||||||
|
pub gain: f32,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Estimate {
|
||||||
|
pub fn new(bounds: IRect) -> Self {
|
||||||
|
Self { pos: ((bounds.x0 + bounds.x1) as f32 / 2.0, (bounds.y0 + bounds.y1) as f32 / 2.0), bounds, gain: 1.0 }
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn set_bounds(&mut self, b: IRect) {
|
||||||
|
self.bounds = b;
|
||||||
|
self.pos = self.clamp(self.pos);
|
||||||
|
}
|
||||||
|
|
||||||
|
fn clamp(&self, p: (f32, f32)) -> (f32, f32) {
|
||||||
|
(
|
||||||
|
p.0.clamp(self.bounds.x0 as f32, (self.bounds.x1 - 1).max(self.bounds.x0) as f32),
|
||||||
|
p.1.clamp(self.bounds.y0 as f32, (self.bounds.y1 - 1).max(self.bounds.y0) as f32),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn motion(&mut self, dx: f32, dy: f32) -> (f32, f32) {
|
||||||
|
self.pos = self.clamp((self.pos.0 + dx * self.gain, self.pos.1 + dy * self.gain));
|
||||||
|
self.pos
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Replace the estimate with a position known to be right.
|
||||||
|
pub fn sync(&mut self, p: (f32, f32)) {
|
||||||
|
self.pos = self.clamp(p);
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn pos(&self) -> (f32, f32) {
|
||||||
|
self.pos
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn parses_hyprland_replies() {
|
||||||
|
assert_eq!(parse_cursorpos("{\"x\": 123, \"y\": 456}"), Some((123.0, 456.0)));
|
||||||
|
assert_eq!(parse_cursorpos("{\"x\":12.5,\"y\":-3.25}"), Some((12.5, -3.25)));
|
||||||
|
assert_eq!(parse_cursorpos("{\n\t\"x\": 1920,\n\t\"y\": 0\n}"), Some((1920.0, 0.0)));
|
||||||
|
assert_eq!(parse_cursorpos("error"), None);
|
||||||
|
assert_eq!(parse_cursorpos("{\"x\": 1}"), None);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn estimate_integrates_clamps_and_syncs() {
|
||||||
|
let mut e = Estimate::new(IRect::new(0, 0, 100, 50));
|
||||||
|
assert_eq!(e.pos(), (50.0, 25.0));
|
||||||
|
assert_eq!(e.motion(10.0, -5.0), (60.0, 20.0));
|
||||||
|
assert_eq!(e.motion(1000.0, -1000.0), (99.0, 0.0), "clamped to the last pixel");
|
||||||
|
e.sync((10.0, 10.0));
|
||||||
|
assert_eq!(e.pos(), (10.0, 10.0));
|
||||||
|
e.gain = 2.0;
|
||||||
|
assert_eq!(e.motion(3.0, 0.0), (16.0, 10.0));
|
||||||
|
e.set_bounds(IRect::new(0, 0, 8, 8));
|
||||||
|
assert_eq!(e.pos(), (7.0, 7.0));
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,689 @@
|
|||||||
|
//! X11 backend.
|
||||||
|
//!
|
||||||
|
//! One override-redirect 32-bit ARGB window per monitor, made click-through with an
|
||||||
|
//! empty XShape *input* region. Global input comes from XInput2 *raw* events (they are
|
||||||
|
//! delivered no matter which client has the focus or a grab). Hotkeys use passive key
|
||||||
|
//! grabs. Annotation mode takes a real pointer + keyboard grab while it is active.
|
||||||
|
//!
|
||||||
|
//! A compositing manager is required for the transparency to show (KWin, Mutter,
|
||||||
|
//! Xfwm4, Picom… all provide it); without one the windows would render as opaque.
|
||||||
|
|
||||||
|
use crate::canvas::{Layer, Patch};
|
||||||
|
use crate::config::*;
|
||||||
|
use crate::control::{self, Command};
|
||||||
|
use crate::core::Core;
|
||||||
|
use crate::geom::IRect;
|
||||||
|
use crate::input::*;
|
||||||
|
use crate::keysym;
|
||||||
|
use anyhow::{Context, Result, anyhow};
|
||||||
|
use rustix::event::{PollFd, PollFlags, Timespec, poll};
|
||||||
|
use rustix::fd::{AsFd, OwnedFd};
|
||||||
|
use x11rb::connection::{Connection, RequestConnection};
|
||||||
|
use x11rb::protocol::Event;
|
||||||
|
use x11rb::protocol::randr::{self, ConnectionExt as _};
|
||||||
|
use x11rb::protocol::shape::{self, ConnectionExt as _};
|
||||||
|
use x11rb::protocol::xinput::{self, ConnectionExt as _};
|
||||||
|
use x11rb::protocol::xproto::{self, ConnectionExt as _};
|
||||||
|
use x11rb::rust_connection::RustConnection;
|
||||||
|
use x11rb::wrapper::ConnectionExt as _;
|
||||||
|
|
||||||
|
const SHIFT: u16 = 0x01;
|
||||||
|
const LOCK: u16 = 0x02;
|
||||||
|
const CONTROL: u16 = 0x04;
|
||||||
|
const MOD1: u16 = 0x08;
|
||||||
|
const MOD2: u16 = 0x10; // NumLock
|
||||||
|
const MOD4: u16 = 0x40;
|
||||||
|
const MOD5: u16 = 0x80; // AltGr on most layouts
|
||||||
|
const REAL_MODS: u16 = SHIFT | CONTROL | MOD1 | MOD4;
|
||||||
|
|
||||||
|
struct Atoms {
|
||||||
|
net_wm_name: xproto::Atom,
|
||||||
|
utf8: xproto::Atom,
|
||||||
|
active_window: xproto::Atom,
|
||||||
|
frame_extents: xproto::Atom,
|
||||||
|
cm_owner: xproto::Atom,
|
||||||
|
}
|
||||||
|
|
||||||
|
struct Overlay {
|
||||||
|
id: xproto::Window,
|
||||||
|
layer: Layer,
|
||||||
|
}
|
||||||
|
|
||||||
|
struct Keymap {
|
||||||
|
min: u8,
|
||||||
|
per: usize,
|
||||||
|
syms: Vec<u32>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Keymap {
|
||||||
|
fn sym(&self, keycode: u8, col: usize) -> u32 {
|
||||||
|
if keycode < self.min || col >= self.per {
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
self.syms.get((keycode - self.min) as usize * self.per + col).copied().unwrap_or(0)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// First keycode producing `sym` in any of the first four columns.
|
||||||
|
fn keycode_for(&self, sym: u32) -> Option<u8> {
|
||||||
|
let rows = self.syms.len() / self.per.max(1);
|
||||||
|
(0..rows).find(|&r| (0..self.per.min(4)).any(|c| self.syms[r * self.per + c] == sym)).map(|r| self.min + r as u8)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
struct Binding {
|
||||||
|
action: &'static str,
|
||||||
|
keycode: u8,
|
||||||
|
mods: u16,
|
||||||
|
}
|
||||||
|
|
||||||
|
pub struct X11 {
|
||||||
|
conn: RustConnection,
|
||||||
|
root: xproto::Window,
|
||||||
|
visual: u32,
|
||||||
|
colormap: u32,
|
||||||
|
gc: Option<u32>,
|
||||||
|
atoms: Atoms,
|
||||||
|
overlays: Vec<Overlay>,
|
||||||
|
keymap: Keymap,
|
||||||
|
bindings: Vec<Binding>,
|
||||||
|
bound: Hotkeys,
|
||||||
|
cursor: u32,
|
||||||
|
grabbed: bool,
|
||||||
|
moved: bool,
|
||||||
|
max_req: usize,
|
||||||
|
warned_cm: bool,
|
||||||
|
}
|
||||||
|
|
||||||
|
fn mods_from_state(state: u16) -> u8 {
|
||||||
|
let mut m = 0;
|
||||||
|
if state & SHIFT != 0 {
|
||||||
|
m |= MOD_SHIFT;
|
||||||
|
}
|
||||||
|
if state & CONTROL != 0 {
|
||||||
|
m |= MOD_CTRL;
|
||||||
|
}
|
||||||
|
if state & MOD1 != 0 {
|
||||||
|
m |= MOD_ALT;
|
||||||
|
}
|
||||||
|
if state & MOD4 != 0 {
|
||||||
|
m |= MOD_SUPER;
|
||||||
|
}
|
||||||
|
m
|
||||||
|
}
|
||||||
|
|
||||||
|
fn chord_mask(mods: u8) -> u16 {
|
||||||
|
let mut m = 0;
|
||||||
|
if mods & MOD_SHIFT != 0 {
|
||||||
|
m |= SHIFT;
|
||||||
|
}
|
||||||
|
if mods & MOD_CTRL != 0 {
|
||||||
|
m |= CONTROL;
|
||||||
|
}
|
||||||
|
if mods & MOD_ALT != 0 {
|
||||||
|
m |= MOD1;
|
||||||
|
}
|
||||||
|
if mods & MOD_SUPER != 0 {
|
||||||
|
m |= MOD4;
|
||||||
|
}
|
||||||
|
m
|
||||||
|
}
|
||||||
|
|
||||||
|
impl X11 {
|
||||||
|
pub fn connect() -> Result<X11> {
|
||||||
|
let (conn, screen_num) = x11rb::connect(None).context("cannot connect to the X server (is DISPLAY set?)")?;
|
||||||
|
let screen = conn.setup().roots[screen_num].clone();
|
||||||
|
let root = screen.root;
|
||||||
|
|
||||||
|
for (name, ext) in
|
||||||
|
[("SHAPE", shape::X11_EXTENSION_NAME), ("RANDR", randr::X11_EXTENSION_NAME), ("XInputExtension", xinput::X11_EXTENSION_NAME)]
|
||||||
|
{
|
||||||
|
conn.extension_information(ext)?.ok_or_else(|| anyhow!("X server lacks the {name} extension"))?;
|
||||||
|
}
|
||||||
|
let v = conn.xinput_xi_query_version(2, 2)?.reply().context("XInput2 is required for global pointer events")?;
|
||||||
|
log::debug!("XInput {}.{}", v.major_version, v.minor_version);
|
||||||
|
|
||||||
|
let visual = screen
|
||||||
|
.allowed_depths
|
||||||
|
.iter()
|
||||||
|
.filter(|d| d.depth == 32)
|
||||||
|
.flat_map(|d| d.visuals.iter())
|
||||||
|
.find(|v| {
|
||||||
|
v.class == xproto::VisualClass::TRUE_COLOR
|
||||||
|
&& v.red_mask == 0x00ff_0000
|
||||||
|
&& v.green_mask == 0x0000_ff00
|
||||||
|
&& v.blue_mask == 0x0000_00ff
|
||||||
|
})
|
||||||
|
.map(|v| v.visual_id)
|
||||||
|
.ok_or_else(|| anyhow!("no 32-bit ARGB visual: transparent overlays are not possible on this X server"))?;
|
||||||
|
let colormap = conn.generate_id()?;
|
||||||
|
conn.create_colormap(xproto::ColormapAlloc::NONE, colormap, root, visual)?;
|
||||||
|
|
||||||
|
let intern = |n: &str| -> Result<xproto::Atom> { Ok(conn.intern_atom(false, n.as_bytes())?.reply()?.atom) };
|
||||||
|
let atoms = Atoms {
|
||||||
|
net_wm_name: intern("_NET_WM_NAME")?,
|
||||||
|
utf8: intern("UTF8_STRING")?,
|
||||||
|
active_window: intern("_NET_ACTIVE_WINDOW")?,
|
||||||
|
frame_extents: intern("_NET_FRAME_EXTENTS")?,
|
||||||
|
cm_owner: intern(&format!("_NET_WM_CM_S{screen_num}"))?,
|
||||||
|
};
|
||||||
|
|
||||||
|
// Global, grab-independent input.
|
||||||
|
let mask = xinput::XIEventMask::RAW_MOTION
|
||||||
|
| xinput::XIEventMask::RAW_BUTTON_PRESS
|
||||||
|
| xinput::XIEventMask::RAW_BUTTON_RELEASE
|
||||||
|
| xinput::XIEventMask::RAW_KEY_PRESS
|
||||||
|
| xinput::XIEventMask::RAW_KEY_RELEASE;
|
||||||
|
conn.xinput_xi_select_events(root, &[xinput::EventMask { deviceid: 1, mask: vec![mask] }])?;
|
||||||
|
conn.randr_select_input(root, randr::NotifyMask::SCREEN_CHANGE)?;
|
||||||
|
conn.change_window_attributes(root, &xproto::ChangeWindowAttributesAux::new().event_mask(xproto::EventMask::PROPERTY_CHANGE))?;
|
||||||
|
|
||||||
|
// Crosshair cursor for annotation mode.
|
||||||
|
let font = conn.generate_id()?;
|
||||||
|
conn.open_font(font, b"cursor")?;
|
||||||
|
let cursor = conn.generate_id()?;
|
||||||
|
conn.create_glyph_cursor(cursor, font, font, 34, 35, 0xffff, 0xffff, 0xffff, 0, 0, 0)?;
|
||||||
|
conn.close_font(font)?;
|
||||||
|
|
||||||
|
let max_req = conn.maximum_request_bytes();
|
||||||
|
let mut x = X11 {
|
||||||
|
conn,
|
||||||
|
root,
|
||||||
|
visual,
|
||||||
|
colormap,
|
||||||
|
gc: None,
|
||||||
|
atoms,
|
||||||
|
overlays: Vec::new(),
|
||||||
|
keymap: Keymap { min: 8, per: 1, syms: Vec::new() },
|
||||||
|
bindings: Vec::new(),
|
||||||
|
bound: Hotkeys { toggle_all: "\0".into(), ..Hotkeys::default() },
|
||||||
|
cursor,
|
||||||
|
grabbed: false,
|
||||||
|
moved: false,
|
||||||
|
max_req,
|
||||||
|
warned_cm: false,
|
||||||
|
};
|
||||||
|
x.reload_keymap()?;
|
||||||
|
x.conn.flush()?;
|
||||||
|
Ok(x)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn reload_keymap(&mut self) -> Result<()> {
|
||||||
|
let setup = self.conn.setup();
|
||||||
|
let (min, max) = (setup.min_keycode, setup.max_keycode);
|
||||||
|
let r = self.conn.get_keyboard_mapping(min, max - min + 1)?.reply()?;
|
||||||
|
self.keymap = Keymap { min, per: r.keysyms_per_keycode as usize, syms: r.keysyms };
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
// ------------------------------------------------------------------ windows
|
||||||
|
|
||||||
|
fn monitors(&self) -> Vec<IRect> {
|
||||||
|
let mut out: Vec<IRect> = Vec::new();
|
||||||
|
if let Ok(Ok(r)) = self.conn.randr_get_monitors(self.root, true).map(|c| c.reply()) {
|
||||||
|
for m in r.monitors {
|
||||||
|
let rect = IRect::from_xywh(m.x as i32, m.y as i32, m.width as i32, m.height as i32);
|
||||||
|
if !rect.is_empty() && !out.contains(&rect) {
|
||||||
|
out.push(rect);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if out.is_empty() {
|
||||||
|
if let Ok(Ok(g)) = self.conn.get_geometry(self.root).map(|c| c.reply()) {
|
||||||
|
out.push(IRect::from_xywh(0, 0, g.width as i32, g.height as i32));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
out
|
||||||
|
}
|
||||||
|
|
||||||
|
fn create_overlay(&mut self, rect: IRect) -> Result<Overlay> {
|
||||||
|
let id = self.conn.generate_id()?;
|
||||||
|
let aux = xproto::CreateWindowAux::new().background_pixel(0).border_pixel(0).override_redirect(1).colormap(self.colormap);
|
||||||
|
self.conn.create_window(
|
||||||
|
32,
|
||||||
|
id,
|
||||||
|
self.root,
|
||||||
|
rect.x0 as i16,
|
||||||
|
rect.y0 as i16,
|
||||||
|
rect.width() as u16,
|
||||||
|
rect.height() as u16,
|
||||||
|
0,
|
||||||
|
xproto::WindowClass::INPUT_OUTPUT,
|
||||||
|
self.visual,
|
||||||
|
&aux,
|
||||||
|
)?;
|
||||||
|
// Empty input region: every click goes straight through to the windows below.
|
||||||
|
self.conn.shape_rectangles(shape::SO::SET, shape::SK::INPUT, xproto::ClipOrdering::UNSORTED, id, 0, 0, &[])?;
|
||||||
|
self.conn.change_property8(
|
||||||
|
xproto::PropMode::REPLACE,
|
||||||
|
id,
|
||||||
|
xproto::AtomEnum::WM_NAME,
|
||||||
|
xproto::AtomEnum::STRING,
|
||||||
|
b"sourizz-overlay",
|
||||||
|
)?;
|
||||||
|
self.conn.change_property8(xproto::PropMode::REPLACE, id, self.atoms.net_wm_name, self.atoms.utf8, b"sourizz-overlay")?;
|
||||||
|
self.conn.change_property8(
|
||||||
|
xproto::PropMode::REPLACE,
|
||||||
|
id,
|
||||||
|
xproto::AtomEnum::WM_CLASS,
|
||||||
|
xproto::AtomEnum::STRING,
|
||||||
|
b"sourizz\0Sourizz\0",
|
||||||
|
)?;
|
||||||
|
if self.gc.is_none() {
|
||||||
|
let gc = self.conn.generate_id()?;
|
||||||
|
self.conn.create_gc(gc, id, &xproto::CreateGCAux::new())?;
|
||||||
|
self.gc = Some(gc);
|
||||||
|
}
|
||||||
|
self.conn.map_window(id)?;
|
||||||
|
Ok(Overlay { id, layer: Layer::new(rect, false) })
|
||||||
|
}
|
||||||
|
|
||||||
|
fn rebuild_overlays(&mut self, core: &mut Core) -> Result<()> {
|
||||||
|
for o in self.overlays.drain(..) {
|
||||||
|
let _ = self.conn.destroy_window(o.id);
|
||||||
|
}
|
||||||
|
let mons = self.monitors();
|
||||||
|
for r in &mons {
|
||||||
|
let o = self.create_overlay(*r)?;
|
||||||
|
self.overlays.push(o);
|
||||||
|
}
|
||||||
|
core.engine.set_monitors(mons);
|
||||||
|
core.engine.request_full_redraw();
|
||||||
|
self.conn.flush()?;
|
||||||
|
if !self.warned_cm && self.conn.get_selection_owner(self.atoms.cm_owner)?.reply()?.owner == 0 {
|
||||||
|
log::warn!("no compositing manager is running: the overlay cannot be transparent. Enable compositing in your window manager.");
|
||||||
|
self.warned_cm = true;
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn raise_overlays(&mut self) {
|
||||||
|
let Ok(Ok(tree)) = self.conn.query_tree(self.root).map(|c| c.reply()) else { return };
|
||||||
|
let n = self.overlays.len();
|
||||||
|
let top: Vec<u32> = tree.children.iter().rev().take(n).copied().collect();
|
||||||
|
if self.overlays.iter().all(|o| top.contains(&o.id)) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
for o in &self.overlays {
|
||||||
|
let _ = self.conn.configure_window(o.id, &xproto::ConfigureWindowAux::new().stack_mode(xproto::StackMode::ABOVE));
|
||||||
|
}
|
||||||
|
let _ = self.conn.flush();
|
||||||
|
}
|
||||||
|
|
||||||
|
fn upload(&self, idx: usize, patch: &Patch) -> Result<()> {
|
||||||
|
let Some(gc) = self.gc else { return Ok(()) };
|
||||||
|
let local = patch.rect;
|
||||||
|
let w = local.width() as usize;
|
||||||
|
let row = w * 4;
|
||||||
|
let max_rows = (self.max_req.saturating_sub(64) / row).max(1);
|
||||||
|
let id = self.overlays[idx].id;
|
||||||
|
for (n, chunk) in patch.data.chunks(max_rows * row).enumerate() {
|
||||||
|
let rows = chunk.len() / row;
|
||||||
|
let y = local.y0 + (n * max_rows) as i32;
|
||||||
|
self.conn.put_image(xproto::ImageFormat::Z_PIXMAP, id, gc, w as u16, rows as u16, local.x0 as i16, y as i16, 0, 32, chunk)?;
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn frame(&mut self, core: &mut Core) -> Result<Option<f64>> {
|
||||||
|
let now = core.now();
|
||||||
|
let plan = core.engine.begin_frame(now);
|
||||||
|
if !plan.damage.is_empty() {
|
||||||
|
for i in 0..self.overlays.len() {
|
||||||
|
for patch in self.overlays[i].layer.repaint(&mut core.engine, &plan.damage, now) {
|
||||||
|
self.upload(i, &patch)?;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
self.conn.flush()?;
|
||||||
|
}
|
||||||
|
Ok(plan.next_in)
|
||||||
|
}
|
||||||
|
|
||||||
|
// ------------------------------------------------------------------ input helpers
|
||||||
|
|
||||||
|
fn pointer(&self) -> Result<(f32, f32, u16)> {
|
||||||
|
let r = self.conn.query_pointer(self.root)?.reply()?;
|
||||||
|
Ok((r.root_x as f32, r.root_y as f32, u16::from(r.mask)))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn key_event(&self, keycode: u8, state: u16, pressed: bool, repeat: bool) -> KeyEvent {
|
||||||
|
let base = self.keymap.sym(keycode, 0);
|
||||||
|
let name = keysym::name(base);
|
||||||
|
let is_modifier = keysym::is_modifier(&name);
|
||||||
|
let mut state = state;
|
||||||
|
// Raw events can arrive before the server updates the modifier state; never count ourselves.
|
||||||
|
if let Some(bit) = modifier_bit(&name) {
|
||||||
|
state &= !match bit {
|
||||||
|
MOD_SHIFT => SHIFT,
|
||||||
|
MOD_CTRL => CONTROL,
|
||||||
|
MOD_ALT => MOD1,
|
||||||
|
_ => MOD4,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
let mods = mods_from_state(state);
|
||||||
|
let shift = state & SHIFT != 0;
|
||||||
|
let altgr = state & MOD5 != 0;
|
||||||
|
let letter = base < 0x80 && (base as u8 as char).is_ascii_lowercase();
|
||||||
|
let eff_shift = shift ^ (state & LOCK != 0 && letter);
|
||||||
|
let col = usize::from(eff_shift) + if altgr { 2 } else { 0 };
|
||||||
|
let sym = match self.keymap.sym(keycode, col) {
|
||||||
|
0 => base,
|
||||||
|
s => s,
|
||||||
|
};
|
||||||
|
// Shortcuts are labelled with the shifted symbol only when Shift is part of them.
|
||||||
|
let label_sym = match self.keymap.sym(keycode, usize::from(shift)) {
|
||||||
|
0 => base,
|
||||||
|
s => s,
|
||||||
|
};
|
||||||
|
let text = if mods & (MOD_CTRL | MOD_ALT | MOD_SUPER) == 0 { keysym::to_char(sym) } else { None };
|
||||||
|
KeyEvent { pressed, name: name.clone(), label: label_for(&keysym::name(label_sym)), text, mods, is_modifier, repeat }
|
||||||
|
}
|
||||||
|
|
||||||
|
fn match_hotkey(&self, keycode: u8, state: u16) -> Option<&'static str> {
|
||||||
|
let m = state & REAL_MODS;
|
||||||
|
self.bindings.iter().find(|b| b.keycode == keycode && b.mods == m).map(|b| b.action)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn grab_hotkeys(&mut self, hk: &Hotkeys) {
|
||||||
|
let _ = self.conn.ungrab_key(0, self.root, xproto::ModMask::ANY);
|
||||||
|
self.bindings.clear();
|
||||||
|
for (action, chord) in control::hotkey_table(hk) {
|
||||||
|
let Some(sym) = keysym::from_name(&chord.key) else {
|
||||||
|
log::warn!("hotkey {action}: unknown key {:?}", chord.key);
|
||||||
|
continue;
|
||||||
|
};
|
||||||
|
let Some(keycode) = self.keymap.keycode_for(sym) else {
|
||||||
|
log::warn!("hotkey {action}: key {:?} is not on this keyboard layout", chord.key);
|
||||||
|
continue;
|
||||||
|
};
|
||||||
|
let mods = chord_mask(chord.mods);
|
||||||
|
let mut ok = true;
|
||||||
|
for lock in [0, LOCK, MOD2, LOCK | MOD2] {
|
||||||
|
let res = self
|
||||||
|
.conn
|
||||||
|
.grab_key(
|
||||||
|
false,
|
||||||
|
self.root,
|
||||||
|
xproto::ModMask::from(mods | lock),
|
||||||
|
keycode,
|
||||||
|
xproto::GrabMode::ASYNC,
|
||||||
|
xproto::GrabMode::ASYNC,
|
||||||
|
)
|
||||||
|
.map_err(anyhow::Error::from)
|
||||||
|
.and_then(|c| c.check().map_err(anyhow::Error::from));
|
||||||
|
if res.is_err() {
|
||||||
|
ok = false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if ok {
|
||||||
|
self.bindings.push(Binding { action, keycode, mods });
|
||||||
|
} else {
|
||||||
|
log::warn!("hotkey {action} ({}+{}) is already used by another program", chord.mods, chord.key);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
self.bound = hk.clone();
|
||||||
|
let _ = self.conn.flush();
|
||||||
|
}
|
||||||
|
|
||||||
|
// ------------------------------------------------------------------ capture (annotation mode)
|
||||||
|
|
||||||
|
fn begin_capture(&mut self) -> bool {
|
||||||
|
let Some(win) = self.overlays.first().map(|o| o.id) else { return false };
|
||||||
|
let ev = xproto::EventMask::BUTTON_PRESS | xproto::EventMask::BUTTON_RELEASE | xproto::EventMask::POINTER_MOTION;
|
||||||
|
let p = self
|
||||||
|
.conn
|
||||||
|
.grab_pointer(false, win, ev, xproto::GrabMode::ASYNC, xproto::GrabMode::ASYNC, 0u32, self.cursor, x11rb::CURRENT_TIME)
|
||||||
|
.ok()
|
||||||
|
.and_then(|c| c.reply().ok());
|
||||||
|
if !matches!(p, Some(r) if r.status == xproto::GrabStatus::SUCCESS) {
|
||||||
|
log::warn!("annotation mode: cannot grab the pointer (another program holds it)");
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
let k = self
|
||||||
|
.conn
|
||||||
|
.grab_keyboard(false, win, x11rb::CURRENT_TIME, xproto::GrabMode::ASYNC, xproto::GrabMode::ASYNC)
|
||||||
|
.ok()
|
||||||
|
.and_then(|c| c.reply().ok());
|
||||||
|
if !matches!(k, Some(r) if r.status == xproto::GrabStatus::SUCCESS) {
|
||||||
|
log::warn!("annotation mode: cannot grab the keyboard");
|
||||||
|
let _ = self.conn.ungrab_pointer(x11rb::CURRENT_TIME);
|
||||||
|
let _ = self.conn.flush();
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
self.grabbed = true;
|
||||||
|
let _ = self.conn.flush();
|
||||||
|
true
|
||||||
|
}
|
||||||
|
|
||||||
|
fn end_capture(&mut self) {
|
||||||
|
if self.grabbed {
|
||||||
|
let _ = self.conn.ungrab_pointer(x11rb::CURRENT_TIME);
|
||||||
|
let _ = self.conn.ungrab_keyboard(x11rb::CURRENT_TIME);
|
||||||
|
let _ = self.conn.flush();
|
||||||
|
self.grabbed = false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ------------------------------------------------------------------ focus mode
|
||||||
|
|
||||||
|
fn focus_rect(&self) -> Option<IRect> {
|
||||||
|
let p = self.conn.get_property(false, self.root, self.atoms.active_window, xproto::AtomEnum::WINDOW, 0, 1).ok()?.reply().ok()?;
|
||||||
|
let win = p.value32()?.next().filter(|w| *w != 0)?;
|
||||||
|
if self.overlays.iter().any(|o| o.id == win) {
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
let attrs = self.conn.get_window_attributes(win).ok()?.reply().ok()?;
|
||||||
|
if attrs.map_state != xproto::MapState::VIEWABLE {
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
let geo = self.conn.get_geometry(win).ok()?.reply().ok()?;
|
||||||
|
let tr = self.conn.translate_coordinates(win, self.root, 0, 0).ok()?.reply().ok()?;
|
||||||
|
let (mut x0, mut y0) = (tr.dst_x as i32, tr.dst_y as i32);
|
||||||
|
let (mut x1, mut y1) = (x0 + geo.width as i32, y0 + geo.height as i32);
|
||||||
|
if let Some(e) = self
|
||||||
|
.conn
|
||||||
|
.get_property(false, win, self.atoms.frame_extents, xproto::AtomEnum::CARDINAL, 0, 4)
|
||||||
|
.ok()
|
||||||
|
.and_then(|c| c.reply().ok())
|
||||||
|
.and_then(|r| r.value32().map(|v| v.collect::<Vec<u32>>()))
|
||||||
|
.filter(|v| v.len() == 4)
|
||||||
|
{
|
||||||
|
x0 -= e[0] as i32;
|
||||||
|
x1 += e[1] as i32;
|
||||||
|
y0 -= e[2] as i32;
|
||||||
|
y1 += e[3] as i32;
|
||||||
|
}
|
||||||
|
Some(IRect::new(x0, y0, x1, y1))
|
||||||
|
}
|
||||||
|
|
||||||
|
// ------------------------------------------------------------------ main loop
|
||||||
|
|
||||||
|
pub fn run(&mut self, core: &mut Core, wake: &OwnedFd) -> Result<()> {
|
||||||
|
self.rebuild_overlays(core)?;
|
||||||
|
let grab_cfg = core.cfg.hotkeys.clone();
|
||||||
|
self.grab_hotkeys(&grab_cfg);
|
||||||
|
if let Ok((x, y, _)) = self.pointer() {
|
||||||
|
core.handle_input(InputEvent::Pointer { x, y });
|
||||||
|
}
|
||||||
|
|
||||||
|
let mut dirty = true;
|
||||||
|
let mut last_frame = f64::NEG_INFINITY;
|
||||||
|
let mut next_frame: Option<f64> = None;
|
||||||
|
let mut last_focus = f64::NEG_INFINITY;
|
||||||
|
let mut last_raise = 0.0;
|
||||||
|
|
||||||
|
while !core.quit {
|
||||||
|
if core.pump() {
|
||||||
|
dirty = true;
|
||||||
|
}
|
||||||
|
if core.quit {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
if core.cfg.hotkeys != self.bound {
|
||||||
|
let hk = core.cfg.hotkeys.clone();
|
||||||
|
self.grab_hotkeys(&hk);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Drain every pending X event before drawing.
|
||||||
|
while let Some(event) = self.conn.poll_for_event()? {
|
||||||
|
self.on_event(core, event, &mut dirty)?;
|
||||||
|
}
|
||||||
|
if self.moved && !self.grabbed {
|
||||||
|
self.moved = false;
|
||||||
|
if let Ok((x, y, _)) = self.pointer() {
|
||||||
|
core.handle_input(InputEvent::Pointer { x, y });
|
||||||
|
dirty = true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
for action in core.drain_actions() {
|
||||||
|
match action {
|
||||||
|
Action::Capture(true) => {
|
||||||
|
if !self.begin_capture() {
|
||||||
|
core.apply(Command::AnnotateToggle);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Action::Capture(false) => self.end_capture(),
|
||||||
|
Action::PlayClick(..) => {}
|
||||||
|
}
|
||||||
|
dirty = true;
|
||||||
|
}
|
||||||
|
|
||||||
|
let now = core.now();
|
||||||
|
if core.cfg.focus.enabled && now - last_focus >= 0.25 {
|
||||||
|
last_focus = now;
|
||||||
|
core.engine.set_focus_rect(self.focus_rect());
|
||||||
|
dirty = true;
|
||||||
|
} else if !core.cfg.focus.enabled {
|
||||||
|
core.engine.set_focus_rect(None);
|
||||||
|
}
|
||||||
|
if now - last_raise > 2.0 {
|
||||||
|
last_raise = now;
|
||||||
|
self.raise_overlays();
|
||||||
|
}
|
||||||
|
|
||||||
|
let min_interval = 1.0 / core.cfg.general.fps as f64;
|
||||||
|
let due = dirty || next_frame.is_some_and(|t| now >= t);
|
||||||
|
if due && now - last_frame >= min_interval {
|
||||||
|
if next_frame.is_some() && !dirty {
|
||||||
|
// Animation tick: pick up warps / pointer moves the raw events can miss.
|
||||||
|
if let (false, Ok((x, y, _))) = (self.grabbed, self.pointer()) {
|
||||||
|
core.handle_input(InputEvent::Pointer { x, y });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
last_frame = now;
|
||||||
|
dirty = false;
|
||||||
|
next_frame = self.frame(core)?.map(|dt| core.now() + dt);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Replies read above (query_pointer, ...) may have queued events inside x11rb behind
|
||||||
|
// our back; poll() on the socket would never report those, so look before sleeping.
|
||||||
|
if let Some(ev) = self.conn.poll_for_event()? {
|
||||||
|
self.on_event(core, ev, &mut dirty)?;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Sleep until the next thing that needs doing.
|
||||||
|
let now = core.now();
|
||||||
|
let mut timeout = 0.5f64;
|
||||||
|
if dirty {
|
||||||
|
timeout = timeout.min((last_frame + min_interval - now).max(0.0));
|
||||||
|
} else if let Some(t) = next_frame {
|
||||||
|
timeout = timeout.min((t - now).max(0.0));
|
||||||
|
}
|
||||||
|
if core.cfg.focus.enabled {
|
||||||
|
timeout = timeout.min((last_focus + 0.25 - now).max(0.0));
|
||||||
|
}
|
||||||
|
self.wait(wake, timeout);
|
||||||
|
control::drain(wake);
|
||||||
|
}
|
||||||
|
self.end_capture();
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn wait(&self, wake: &OwnedFd, timeout: f64) {
|
||||||
|
let ts = Timespec { tv_sec: timeout as i64, tv_nsec: (timeout.fract() * 1e9) as _ };
|
||||||
|
let x = self.conn.stream().as_fd();
|
||||||
|
let mut fds = [PollFd::new(&x, PollFlags::IN), PollFd::new(wake, PollFlags::IN)];
|
||||||
|
let _ = poll(&mut fds, Some(&ts));
|
||||||
|
}
|
||||||
|
|
||||||
|
fn on_event(&mut self, core: &mut Core, event: Event, dirty: &mut bool) -> Result<()> {
|
||||||
|
match event {
|
||||||
|
Event::XinputRawMotion(_) => self.moved = true,
|
||||||
|
Event::XinputRawButtonPress(e) | Event::XinputRawButtonRelease(e) if !self.grabbed => {
|
||||||
|
let pressed = e.event_type == xinput::RAW_BUTTON_PRESS_EVENT;
|
||||||
|
let button = match e.detail {
|
||||||
|
1 => Button::Left,
|
||||||
|
2 => Button::Middle,
|
||||||
|
3 => Button::Right,
|
||||||
|
4..=7 => return Ok(()), // scroll wheel
|
||||||
|
_ => Button::Other,
|
||||||
|
};
|
||||||
|
if let Ok((x, y, _)) = self.pointer() {
|
||||||
|
core.handle_input(InputEvent::Pointer { x, y });
|
||||||
|
}
|
||||||
|
core.handle_input(InputEvent::Button { button, pressed });
|
||||||
|
self.moved = false;
|
||||||
|
*dirty = true;
|
||||||
|
}
|
||||||
|
Event::XinputRawKeyPress(e) | Event::XinputRawKeyRelease(e) if !self.grabbed => {
|
||||||
|
let pressed = e.event_type == xinput::RAW_KEY_PRESS_EVENT;
|
||||||
|
let repeat = u32::from(e.flags) & (1 << 16) != 0;
|
||||||
|
let state = self.pointer().map(|p| p.2).unwrap_or(0);
|
||||||
|
let ev = self.key_event(e.detail as u8, state, pressed, repeat);
|
||||||
|
core.handle_input(InputEvent::Key(ev));
|
||||||
|
*dirty = true;
|
||||||
|
}
|
||||||
|
Event::KeyPress(e) => {
|
||||||
|
if let Some(action) = self.match_hotkey(e.detail, e.state.into()) {
|
||||||
|
if let Some(cmd) = control::hotkey_command(action) {
|
||||||
|
core.apply(cmd);
|
||||||
|
*dirty = true;
|
||||||
|
}
|
||||||
|
} else if self.grabbed {
|
||||||
|
let ev = self.key_event(e.detail, e.state.into(), true, false);
|
||||||
|
core.handle_input(InputEvent::Key(ev));
|
||||||
|
*dirty = true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Event::KeyRelease(e) if self.grabbed => {
|
||||||
|
let ev = self.key_event(e.detail, e.state.into(), false, false);
|
||||||
|
core.handle_input(InputEvent::Key(ev));
|
||||||
|
}
|
||||||
|
Event::MotionNotify(e) if self.grabbed => {
|
||||||
|
core.handle_input(InputEvent::Pointer { x: e.root_x as f32, y: e.root_y as f32 });
|
||||||
|
*dirty = true;
|
||||||
|
}
|
||||||
|
Event::ButtonPress(e) | Event::ButtonRelease(e) if self.grabbed => {
|
||||||
|
let pressed = e.response_type & 0x7f == xproto::BUTTON_PRESS_EVENT;
|
||||||
|
let button = match e.detail {
|
||||||
|
1 => Button::Left,
|
||||||
|
2 => Button::Middle,
|
||||||
|
3 => Button::Right,
|
||||||
|
_ => return Ok(()),
|
||||||
|
};
|
||||||
|
core.handle_input(InputEvent::Pointer { x: e.root_x as f32, y: e.root_y as f32 });
|
||||||
|
core.handle_input(InputEvent::Button { button, pressed });
|
||||||
|
*dirty = true;
|
||||||
|
}
|
||||||
|
Event::MappingNotify(m) if m.request == xproto::Mapping::KEYBOARD => {
|
||||||
|
self.reload_keymap()?;
|
||||||
|
let hk = core.cfg.hotkeys.clone();
|
||||||
|
self.grab_hotkeys(&hk);
|
||||||
|
}
|
||||||
|
Event::RandrScreenChangeNotify(_) => {
|
||||||
|
self.rebuild_overlays(core)?;
|
||||||
|
*dirty = true;
|
||||||
|
}
|
||||||
|
Event::Error(e) => log::debug!("X error: {e:?}"),
|
||||||
|
_ => {}
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn run(core: &mut Core, wake: &OwnedFd) -> Result<()> {
|
||||||
|
let mut x = X11::connect()?;
|
||||||
|
log::info!("X11 backend ready ({} monitor(s))", x.monitors().len());
|
||||||
|
x.run(core, wake)
|
||||||
|
}
|
||||||
@@ -0,0 +1,278 @@
|
|||||||
|
//! Keyboard layout handling for Wayland, through libxkbcommon loaded at run time
|
||||||
|
//! (`dlopen`), so no development headers are needed to build and nothing breaks when
|
||||||
|
//! the library is missing: callers just get `None` and fall back.
|
||||||
|
//!
|
||||||
|
//! Wayland does not tell clients what is typed elsewhere, so global key labels come from
|
||||||
|
//! raw evdev key codes translated with the user's layout (see [`detect_layout`]). While
|
||||||
|
//! annotation mode owns the keyboard, the compositor's own keymap is used instead.
|
||||||
|
|
||||||
|
use crate::config::{MOD_ALT, MOD_CTRL, MOD_SHIFT, MOD_SUPER};
|
||||||
|
use crate::input::{KeyEvent, label_for};
|
||||||
|
use crate::keysym;
|
||||||
|
use std::ffi::{CString, c_char};
|
||||||
|
use xkbcommon_dl::{
|
||||||
|
XkbCommon, xkb_context, xkb_context_flags, xkb_key_direction, xkb_keymap, xkb_keymap_compile_flags, xkb_keymap_format, xkb_rule_names,
|
||||||
|
xkb_state, xkb_state_component,
|
||||||
|
};
|
||||||
|
|
||||||
|
pub struct Xkb {
|
||||||
|
lib: &'static XkbCommon,
|
||||||
|
ctx: *mut xkb_context,
|
||||||
|
keymap: *mut xkb_keymap,
|
||||||
|
state: *mut xkb_state,
|
||||||
|
}
|
||||||
|
|
||||||
|
// The raw pointers are only ever used from the thread that owns the `Xkb`.
|
||||||
|
unsafe impl Send for Xkb {}
|
||||||
|
|
||||||
|
/// Read `layout`, `variant` and `options` from a `KEY=value` style file such as
|
||||||
|
/// `/etc/default/keyboard` or KDE's `kxkbrc`. The layout is required; the rest default to empty.
|
||||||
|
fn parse_layout_file(text: &str, keys: [&str; 3], sep: char) -> Option<(String, String, String)> {
|
||||||
|
let get = |k: &str| {
|
||||||
|
text.lines().find_map(|l| {
|
||||||
|
let (name, val) = l.split_once(sep)?;
|
||||||
|
(name.trim() == k).then(|| val.trim().trim_matches('"').to_string())
|
||||||
|
})
|
||||||
|
};
|
||||||
|
let layout = get(keys[0]).filter(|l| !l.is_empty())?;
|
||||||
|
Some((layout, get(keys[1]).unwrap_or_default(), get(keys[2]).unwrap_or_default()))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Keyboard layout (`layout`, `variant`, `options`) for the evdev path.
|
||||||
|
///
|
||||||
|
/// Order of precedence: `XKB_DEFAULT_*` environment variables, `/etc/default/keyboard`,
|
||||||
|
/// KDE's `kxkbrc`, then plain `us`.
|
||||||
|
pub fn detect_layout() -> (String, String, String) {
|
||||||
|
let env = |k: &str| std::env::var(k).ok().filter(|v| !v.is_empty());
|
||||||
|
if let Some(l) = env("XKB_DEFAULT_LAYOUT") {
|
||||||
|
return (l, env("XKB_DEFAULT_VARIANT").unwrap_or_default(), env("XKB_DEFAULT_OPTIONS").unwrap_or_default());
|
||||||
|
}
|
||||||
|
if let Ok(t) = std::fs::read_to_string("/etc/default/keyboard") {
|
||||||
|
if let Some(r) = parse_layout_file(&t, ["XKBLAYOUT", "XKBVARIANT", "XKBOPTIONS"], '=') {
|
||||||
|
return r;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if let Some(home) = std::env::var_os("HOME") {
|
||||||
|
if let Ok(t) = std::fs::read_to_string(std::path::Path::new(&home).join(".config/kxkbrc")) {
|
||||||
|
if let Some(r) = parse_layout_file(&t, ["LayoutList", "VariantList", "Options"], '=') {
|
||||||
|
return r;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
("us".into(), String::new(), String::new())
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Xkb {
|
||||||
|
pub fn available() -> bool {
|
||||||
|
xkbcommon_dl::xkbcommon_option().is_some()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn with_keymap(lib: &'static XkbCommon, ctx: *mut xkb_context, keymap: *mut xkb_keymap) -> Option<Xkb> {
|
||||||
|
if keymap.is_null() {
|
||||||
|
unsafe { (lib.xkb_context_unref)(ctx) };
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
let state = unsafe { (lib.xkb_state_new)(keymap) };
|
||||||
|
if state.is_null() {
|
||||||
|
unsafe {
|
||||||
|
(lib.xkb_keymap_unref)(keymap);
|
||||||
|
(lib.xkb_context_unref)(ctx);
|
||||||
|
}
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
Some(Xkb { lib, ctx, keymap, state })
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn from_names(layout: &str, variant: &str, options: &str) -> Option<Xkb> {
|
||||||
|
let lib = xkbcommon_dl::xkbcommon_option()?;
|
||||||
|
let ctx = unsafe { (lib.xkb_context_new)(xkb_context_flags::XKB_CONTEXT_NO_FLAGS) };
|
||||||
|
if ctx.is_null() {
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
let c = |s: &str| CString::new(s).ok();
|
||||||
|
let (layout, variant, options) = (c(layout)?, c(variant)?, c(options)?);
|
||||||
|
let names = xkb_rule_names {
|
||||||
|
rules: std::ptr::null(),
|
||||||
|
model: std::ptr::null(),
|
||||||
|
layout: layout.as_ptr(),
|
||||||
|
variant: variant.as_ptr(),
|
||||||
|
options: options.as_ptr(),
|
||||||
|
};
|
||||||
|
let keymap = unsafe { (lib.xkb_keymap_new_from_names)(ctx, &names, xkb_keymap_compile_flags::XKB_KEYMAP_COMPILE_NO_FLAGS) };
|
||||||
|
Self::with_keymap(lib, ctx, keymap)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Build from the keymap text a Wayland compositor sends in `wl_keyboard.keymap`.
|
||||||
|
pub fn from_keymap_string(text: &str) -> Option<Xkb> {
|
||||||
|
let lib = xkbcommon_dl::xkbcommon_option()?;
|
||||||
|
let ctx = unsafe { (lib.xkb_context_new)(xkb_context_flags::XKB_CONTEXT_NO_FLAGS) };
|
||||||
|
if ctx.is_null() {
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
let text = CString::new(text.trim_end_matches('\0')).ok()?;
|
||||||
|
let keymap = unsafe {
|
||||||
|
(lib.xkb_keymap_new_from_string)(
|
||||||
|
ctx,
|
||||||
|
text.as_ptr(),
|
||||||
|
xkb_keymap_format::XKB_KEYMAP_FORMAT_TEXT_V1,
|
||||||
|
xkb_keymap_compile_flags::XKB_KEYMAP_COMPILE_NO_FLAGS,
|
||||||
|
)
|
||||||
|
};
|
||||||
|
Self::with_keymap(lib, ctx, keymap)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Forget all pressed keys and modifiers (used when keyboard focus changes).
|
||||||
|
pub fn reset(&mut self) {
|
||||||
|
unsafe {
|
||||||
|
(self.lib.xkb_state_unref)(self.state);
|
||||||
|
self.state = (self.lib.xkb_state_new)(self.keymap);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn mod_active(&self, name: &[u8]) -> bool {
|
||||||
|
debug_assert!(name.ends_with(&[0]));
|
||||||
|
unsafe {
|
||||||
|
(self.lib.xkb_state_mod_name_is_active)(
|
||||||
|
self.state,
|
||||||
|
name.as_ptr() as *const c_char,
|
||||||
|
xkb_state_component::XKB_STATE_MODS_EFFECTIVE,
|
||||||
|
) > 0
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn base_sym(&self, kc: u32) -> u32 {
|
||||||
|
let mut syms: *const u32 = std::ptr::null();
|
||||||
|
let n = unsafe { (self.lib.xkb_keymap_key_get_syms_by_level)(self.keymap, kc, 0, 0, &mut syms) };
|
||||||
|
if n > 0 && !syms.is_null() { unsafe { *syms } } else { 0 }
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Level-0 keysym of an evdev key code (what a hotkey chord names).
|
||||||
|
pub fn base_keysym(&self, evdev_code: u32) -> u32 {
|
||||||
|
self.base_sym(evdev_code + 8)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Translate one evdev key event, updating the modifier state.
|
||||||
|
///
|
||||||
|
/// `mods` in the result are the modifiers held *before* this key, like on X11.
|
||||||
|
pub fn event(&mut self, evdev_code: u32, pressed: bool, repeat: bool) -> KeyEvent {
|
||||||
|
let kc = evdev_code + 8;
|
||||||
|
let base = self.base_sym(kc);
|
||||||
|
let name = keysym::name(base);
|
||||||
|
let is_modifier = keysym::is_modifier(&name);
|
||||||
|
let shift = self.mod_active(b"Shift\0");
|
||||||
|
let mut mods = 0u8;
|
||||||
|
if shift {
|
||||||
|
mods |= MOD_SHIFT;
|
||||||
|
}
|
||||||
|
if self.mod_active(b"Control\0") {
|
||||||
|
mods |= MOD_CTRL;
|
||||||
|
}
|
||||||
|
if self.mod_active(b"Mod1\0") {
|
||||||
|
mods |= MOD_ALT;
|
||||||
|
}
|
||||||
|
if self.mod_active(b"Mod4\0") {
|
||||||
|
mods |= MOD_SUPER;
|
||||||
|
}
|
||||||
|
let sym = unsafe { (self.lib.xkb_state_key_get_one_sym)(self.state, kc) };
|
||||||
|
let utf32 = unsafe { (self.lib.xkb_state_key_get_utf32)(self.state, kc) };
|
||||||
|
let label_sym = if shift && sym != 0 { sym } else { base };
|
||||||
|
let text = if mods & (MOD_CTRL | MOD_ALT | MOD_SUPER) == 0 { char::from_u32(utf32).filter(|c| !c.is_control()) } else { None };
|
||||||
|
if !repeat {
|
||||||
|
let dir = if pressed { xkb_key_direction::XKB_KEY_DOWN } else { xkb_key_direction::XKB_KEY_UP };
|
||||||
|
unsafe { (self.lib.xkb_state_update_key)(self.state, kc, dir) };
|
||||||
|
}
|
||||||
|
KeyEvent { pressed, name, label: label_for(&keysym::name(label_sym)), text, mods, is_modifier, repeat }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Drop for Xkb {
|
||||||
|
fn drop(&mut self) {
|
||||||
|
unsafe {
|
||||||
|
(self.lib.xkb_state_unref)(self.state);
|
||||||
|
(self.lib.xkb_keymap_unref)(self.keymap);
|
||||||
|
(self.lib.xkb_context_unref)(self.ctx);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
|
||||||
|
// evdev codes
|
||||||
|
const KEY_Q: u32 = 16;
|
||||||
|
const KEY_A: u32 = 30;
|
||||||
|
const KEY_LEFTSHIFT: u32 = 42;
|
||||||
|
const KEY_LEFTCTRL: u32 = 29;
|
||||||
|
const KEY_RIGHTCTRL: u32 = 97;
|
||||||
|
const KEY_1: u32 = 2;
|
||||||
|
|
||||||
|
fn xkb(layout: &str) -> Option<Xkb> {
|
||||||
|
if !Xkb::available() {
|
||||||
|
eprintln!("libxkbcommon not installed: skipping");
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
Some(Xkb::from_names(layout, "", "").expect("layout compiles"))
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn azerty_and_qwerty_label_the_same_key_differently() {
|
||||||
|
let (Some(mut fr), Some(mut us)) = (xkb("fr"), xkb("us")) else { return };
|
||||||
|
// The physical key right of Tab: 'a' on AZERTY, 'q' on QWERTY.
|
||||||
|
let e = fr.event(KEY_Q, true, false);
|
||||||
|
assert_eq!(e.name, "a");
|
||||||
|
assert_eq!(e.text, Some('a'));
|
||||||
|
let e = us.event(KEY_Q, true, false);
|
||||||
|
assert_eq!(e.name, "q");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn shift_changes_text_and_digits_on_azerty() {
|
||||||
|
let Some(mut fr) = xkb("fr") else { return };
|
||||||
|
let plain = fr.event(KEY_1, true, false);
|
||||||
|
assert_eq!(plain.text, Some('&'), "AZERTY digit row is symbols without Shift");
|
||||||
|
fr.event(KEY_1, false, false);
|
||||||
|
let sh = fr.event(KEY_LEFTSHIFT, true, false);
|
||||||
|
assert!(sh.is_modifier);
|
||||||
|
let e = fr.event(KEY_1, true, false);
|
||||||
|
assert_eq!(e.text, Some('1'));
|
||||||
|
assert_eq!(e.mods, MOD_SHIFT);
|
||||||
|
assert_eq!(e.label, "1");
|
||||||
|
fr.event(KEY_1, false, false);
|
||||||
|
fr.event(KEY_LEFTSHIFT, false, false);
|
||||||
|
assert_eq!(fr.event(KEY_1, true, false).text, Some('&'), "shift released");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn ctrl_hides_text_and_reports_modifiers() {
|
||||||
|
let Some(mut us) = xkb("us") else { return };
|
||||||
|
us.event(KEY_LEFTCTRL, true, false);
|
||||||
|
let e = us.event(KEY_A, true, false);
|
||||||
|
assert_eq!(e.text, None);
|
||||||
|
assert_eq!(e.mods, MOD_CTRL);
|
||||||
|
assert_eq!(e.name, "a");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn modifier_key_names_match_config_values() {
|
||||||
|
let Some(mut us) = xkb("us") else { return };
|
||||||
|
assert_eq!(us.event(KEY_RIGHTCTRL, true, false).name, "Control_R");
|
||||||
|
assert_eq!(us.base_keysym(KEY_A), 'a' as u32);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn layout_files_are_parsed() {
|
||||||
|
let debian = "XKBMODEL=\"pc105\"\nXKBLAYOUT=\"fr\"\nXKBVARIANT=\"oss\"\nXKBOPTIONS=\"ctrl:nocaps\"\n";
|
||||||
|
assert_eq!(
|
||||||
|
parse_layout_file(debian, ["XKBLAYOUT", "XKBVARIANT", "XKBOPTIONS"], '='),
|
||||||
|
Some(("fr".into(), "oss".into(), "ctrl:nocaps".into()))
|
||||||
|
);
|
||||||
|
let kde = "[Layout]\nLayoutList=fr,us\nUse=true\n";
|
||||||
|
assert_eq!(
|
||||||
|
parse_layout_file(kde, ["LayoutList", "VariantList", "Options"], '='),
|
||||||
|
Some(("fr,us".into(), String::new(), String::new()))
|
||||||
|
);
|
||||||
|
assert_eq!(parse_layout_file("XKBLAYOUT=\"\"\n", ["XKBLAYOUT", "XKBVARIANT", "XKBOPTIONS"], '='), None);
|
||||||
|
assert_eq!(parse_layout_file("nothing here", ["XKBLAYOUT", "XKBVARIANT", "XKBOPTIONS"], '='), None);
|
||||||
|
}
|
||||||
|
}
|
||||||