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>
This commit is contained in:
2026-10-30 08:41:11 +01:00
commit fee42ae92d
49 changed files with 13094 additions and 0 deletions
+608
View File
@@ -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);
}
}
+191
View File
@@ -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);
}
}
+333
View File
@@ -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()))))
}
+233
View File
@@ -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");
}
}
+548
View File
@@ -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());
}
}
+218
View File
@@ -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());
}
}
+204
View File
@@ -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();
}
}
}
+200
View File
@@ -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(())
}
+1162
View File
File diff suppressed because it is too large Load Diff
+210
View File
@@ -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);
}
}
+236
View File
@@ -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);
}
}
+79
View File
@@ -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);
}
}
+192
View File
@@ -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");
}
}
+139
View File
@@ -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);
}
}
+107
View File
@@ -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)
}
}
+152
View File
@@ -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"));
}
}
+318
View File
@@ -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));
}
}
+114
View File
@@ -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,));
}
}
+30
View File
@@ -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;
+258
View File
@@ -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(())
}
+123
View File
@@ -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;
}
}
}
+162
View File
@@ -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(),
]
}
}
+678
View File
@@ -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(())
}
+121
View File
@@ -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));
}
}
+689
View File
@@ -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)
}
+278
View File
@@ -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);
}
}