pixelcoords-core 0.4.0

Platform-free core of pixelcoords: screen geometry, HiDPI and multi-monitor coordinate spaces, the session.json schema, template relocation, point verdicts, click-point resolution, region diffing, and click-code emitters. Cross-platform (macOS, Windows, Linux), no unsafe
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
//! Hotkey binding grammar: `KEY=ACTION[,EDGE][,WHEN]`.
//!
//! Ported from the predecessor's config grammar, minus Win32 virtual-key
//! codes: keys are platform-neutral names the binary maps from its window
//! system's key events. Parsing is strict — unknown actions, edges, or
//! conditions are errors, not silently dropped.

use thiserror::Error;

#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum KeyName {
    /// A single printable character, stored uppercase.
    Character(char),
    Tab,
    CapsLock,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum Edge {
    #[default]
    Press,
    Release,
    Repeat,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum When {
    HasSelection,
    CursorInShape,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Action {
    Quit,
    Save,
    NextTool,
    DeleteAtCursor,
    LabelEditAtCursor,
    Undo,
    /// Re-apply the most recently undone edit.
    Redo,
    /// Send the topmost shape under the cursor to the bottom of the
    /// stack, so overlapped shapes become reachable.
    CycleOverlap,
    /// Show or hide the control panel.
    TogglePanel,
    /// Open the session-name editor.
    NameSession,
    /// Rotate the shape under the cursor counterclockwise.
    RotateCcw,
    /// Rotate the shape under the cursor clockwise.
    RotateCw,
    /// Unfreeze the monitor under the cursor and close its overlay window,
    /// leaving the others frozen. The only way to reach this: the overlay
    /// windows are borderless and undecorated, so no close button exists
    /// and `CloseRequested` never fires from a user action.
    ReleaseMonitor,
    /// Accepted by the grammar for forward compatibility; snapshot mode has
    /// no themes, so the binary treats it as a no-op.
    NextTheme,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Binding {
    pub key: KeyName,
    pub action: Action,
    pub edge: Edge,
    pub when: Option<When>,
}

/// Everything a binding condition can observe about the app.
#[derive(Debug, Clone, Copy, Default)]
pub struct OverlayState {
    pub has_selection: bool,
    pub cursor_in_shape: bool,
}

#[derive(Debug, Error, PartialEq, Eq)]
pub enum HotkeyError {
    #[error("binding '{0}' is not KEY=ACTION[,EDGE][,WHEN]")]
    Malformed(String),
    #[error("unknown key '{0}' (single character, 'tab', or 'capslock')")]
    UnknownKey(String),
    #[error("unknown action '{0}'")]
    UnknownAction(String),
    #[error("unknown edge '{0}' (press, release, or repeat)")]
    UnknownEdge(String),
    #[error("unknown condition '{0}' (has_selection or cursor_in)")]
    UnknownWhen(String),
}

pub fn parse_key(s: &str) -> Result<KeyName, HotkeyError> {
    let t = s.trim();
    match t.to_ascii_lowercase().as_str() {
        "tab" => Ok(KeyName::Tab),
        "capslock" | "caps_lock" | "caps" => Ok(KeyName::CapsLock),
        _ => {
            let mut chars = t.chars();
            match (chars.next(), chars.next()) {
                (Some(c), None) if !c.is_whitespace() => {
                    Ok(KeyName::Character(c.to_ascii_uppercase()))
                }
                _ => Err(HotkeyError::UnknownKey(t.to_string())),
            }
        }
    }
}

pub fn parse_action(s: &str) -> Result<Action, HotkeyError> {
    match s.trim().to_ascii_lowercase().as_str() {
        "quit" => Ok(Action::Quit),
        "save" => Ok(Action::Save),
        "next_tool" => Ok(Action::NextTool),
        "delete_at_cursor" | "delete_selection_at_cursor" => Ok(Action::DeleteAtCursor),
        "label_edit_at_cursor" => Ok(Action::LabelEditAtCursor),
        "undo" => Ok(Action::Undo),
        "redo" => Ok(Action::Redo),
        "cycle_overlap" => Ok(Action::CycleOverlap),
        "toggle_panel" => Ok(Action::TogglePanel),
        "name_session" => Ok(Action::NameSession),
        "rotate_ccw" => Ok(Action::RotateCcw),
        "rotate_cw" => Ok(Action::RotateCw),
        "release_monitor" => Ok(Action::ReleaseMonitor),
        "next_theme" => Ok(Action::NextTheme),
        other => Err(HotkeyError::UnknownAction(other.to_string())),
    }
}

impl Binding {
    /// Parse one `KEY=ACTION[,EDGE][,WHEN]` spec. EDGE and WHEN may appear
    /// in either order, matching the predecessor's CLI.
    pub fn parse(spec: &str) -> Result<Self, HotkeyError> {
        let (key_part, rest) = spec
            .split_once('=')
            .ok_or_else(|| HotkeyError::Malformed(spec.to_string()))?;
        let mut parts = rest.split(',');
        let action_part = parts.next().unwrap_or_default();
        if action_part.trim().is_empty() {
            return Err(HotkeyError::Malformed(spec.to_string()));
        }
        let key = parse_key(key_part)?;
        let action = parse_action(action_part)?;
        let mut edge = Edge::default();
        let mut when = None;
        for part in parts {
            let t = part.trim().to_ascii_lowercase();
            match t.as_str() {
                "press" => edge = Edge::Press,
                "release" => edge = Edge::Release,
                "repeat" => edge = Edge::Repeat,
                "has_selection" => when = Some(When::HasSelection),
                "cursor_in" => when = Some(When::CursorInShape),
                "hold" | "down" | "up" => return Err(HotkeyError::UnknownEdge(t)),
                _ => return Err(HotkeyError::UnknownWhen(t)),
            }
        }
        Ok(Self {
            key,
            action,
            edge,
            when,
        })
    }

    const fn condition_met(self, state: OverlayState) -> bool {
        match self.when {
            None => true,
            Some(When::HasSelection) => state.has_selection,
            Some(When::CursorInShape) => state.cursor_in_shape,
        }
    }
}

/// Default bindings; user config and CLI `--bind` entries are appended after
/// these, and the *last* matching binding wins, so later sources override.
pub fn default_bindings() -> Vec<Binding> {
    [
        // The left hand covers everything, game-cluster style: QE turn,
        // WASD does the rest, Z undoes. Quit lives on Esc in the app, so
        // no letter is spent on it.
        "w=next_tool",
        "tab=next_tool",
        "a=label_edit_at_cursor,release,cursor_in",
        "s=save,has_selection",
        "d=delete_at_cursor,press,cursor_in",
        "z=undo",
        "c=cycle_overlap,press,cursor_in",
        "h=toggle_panel",
        "n=name_session",
        // The only trigger for releasing one display; see Action::ReleaseMonitor.
        "r=release_monitor",
        // Rotation binds press AND repeat so holding the key keeps turning.
        "q=rotate_ccw,press,cursor_in",
        "q=rotate_ccw,repeat,cursor_in",
        "e=rotate_cw,press,cursor_in",
        "e=rotate_cw,repeat,cursor_in",
    ]
    .into_iter()
    .map(|s| Binding::parse(s).expect("default bindings are valid"))
    .collect()
}

/// Resolve a key event against the binding list. Later bindings shadow
/// earlier ones for the same key + edge; a shadowing binding whose condition
/// fails suppresses the shadowed one rather than falling through.
pub fn match_event(
    bindings: &[Binding],
    key: KeyName,
    edge: Edge,
    state: OverlayState,
) -> Option<Action> {
    bindings
        .iter()
        .rev()
        .find(|b| b.key == key && b.edge == edge)
        .filter(|b| b.condition_met(state))
        .map(|b| b.action)
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn parses_full_form() {
        let b = Binding::parse("E=label_edit_at_cursor,release,cursor_in").unwrap();
        assert_eq!(b.key, KeyName::Character('E'));
        assert_eq!(b.action, Action::LabelEditAtCursor);
        assert_eq!(b.edge, Edge::Release);
        assert_eq!(b.when, Some(When::CursorInShape));
    }

    #[test]
    fn edge_defaults_to_press() {
        let b = Binding::parse("q=quit").unwrap();
        assert_eq!(b.edge, Edge::Press);
        assert_eq!(b.when, None);
    }

    #[test]
    fn edge_and_when_order_is_flexible() {
        let a = Binding::parse("w=save,has_selection,release").unwrap();
        let b = Binding::parse("w=save,release,has_selection").unwrap();
        assert_eq!(a, b);
    }

    #[test]
    fn key_is_case_insensitive_and_uppercased() {
        assert_eq!(parse_key("q").unwrap(), KeyName::Character('Q'));
        assert_eq!(parse_key("Q").unwrap(), KeyName::Character('Q'));
        assert_eq!(parse_key(" TAB ").unwrap(), KeyName::Tab);
        assert_eq!(parse_key("caps_lock").unwrap(), KeyName::CapsLock);
    }

    #[test]
    fn rejects_unknown_pieces() {
        assert_eq!(
            Binding::parse("qq=quit").unwrap_err(),
            HotkeyError::UnknownKey("qq".into())
        );
        assert_eq!(
            Binding::parse("q=fly").unwrap_err(),
            HotkeyError::UnknownAction("fly".into())
        );
        assert_eq!(
            Binding::parse("q=quit,hold").unwrap_err(),
            HotkeyError::UnknownEdge("hold".into())
        );
        assert_eq!(
            Binding::parse("q=quit,when_happy").unwrap_err(),
            HotkeyError::UnknownWhen("when_happy".into())
        );
        assert_eq!(
            Binding::parse("just_a_key").unwrap_err(),
            HotkeyError::Malformed("just_a_key".into())
        );
        assert_eq!(
            Binding::parse("q=").unwrap_err(),
            HotkeyError::Malformed("q=".into())
        );
    }

    #[test]
    fn legacy_action_alias_accepted() {
        assert_eq!(
            parse_action("delete_selection_at_cursor").unwrap(),
            Action::DeleteAtCursor
        );
    }

    #[test]
    fn match_requires_edge() {
        let bindings = default_bindings();
        let state = OverlayState::default();
        assert_eq!(
            match_event(&bindings, KeyName::Character('Z'), Edge::Press, state),
            Some(Action::Undo)
        );
        assert_eq!(
            match_event(&bindings, KeyName::Character('Z'), Edge::Release, state),
            None
        );
    }

    #[test]
    fn match_gates_on_conditions() {
        let bindings = default_bindings();
        let none = OverlayState::default();
        assert_eq!(
            match_event(&bindings, KeyName::Character('S'), Edge::Press, none),
            None
        );
        assert_eq!(
            match_event(
                &bindings,
                KeyName::Character('S'),
                Edge::Press,
                OverlayState {
                    has_selection: true,
                    ..none
                }
            ),
            Some(Action::Save)
        );
        assert_eq!(
            match_event(&bindings, KeyName::Character('D'), Edge::Press, none),
            None
        );
        assert_eq!(
            match_event(
                &bindings,
                KeyName::Character('D'),
                Edge::Press,
                OverlayState {
                    cursor_in_shape: true,
                    ..none
                }
            ),
            Some(Action::DeleteAtCursor)
        );
    }

    #[test]
    fn later_binding_shadows_earlier() {
        let mut bindings = default_bindings();
        bindings.push(Binding::parse("q=undo").unwrap());
        assert_eq!(
            match_event(
                &bindings,
                KeyName::Character('Q'),
                Edge::Press,
                OverlayState::default()
            ),
            Some(Action::Undo)
        );
    }

    #[test]
    fn shadowing_binding_with_failed_condition_suppresses() {
        let mut bindings = default_bindings();
        bindings.push(Binding::parse("q=save,has_selection").unwrap());
        // The rebind of Q is conditional and the condition fails: Q does
        // nothing rather than falling back to quit.
        assert_eq!(
            match_event(
                &bindings,
                KeyName::Character('Q'),
                Edge::Press,
                OverlayState::default()
            ),
            None
        );
    }

    #[test]
    fn rotation_defaults_fire_on_press_and_repeat() {
        let bindings = default_bindings();
        let state = OverlayState {
            cursor_in_shape: true,
            ..OverlayState::default()
        };
        for edge in [Edge::Press, Edge::Repeat] {
            assert_eq!(
                match_event(&bindings, KeyName::Character('Q'), edge, state),
                Some(Action::RotateCcw)
            );
            assert_eq!(
                match_event(&bindings, KeyName::Character('E'), edge, state),
                Some(Action::RotateCw)
            );
        }
        // Not over a shape: no rotation.
        assert_eq!(
            match_event(
                &bindings,
                KeyName::Character('Q'),
                Edge::Press,
                OverlayState::default()
            ),
            None
        );
    }

    #[test]
    fn defaults_cover_expected_keys() {
        let bindings = default_bindings();
        assert_eq!(bindings.len(), 14);
        assert_eq!(
            match_event(
                &bindings,
                KeyName::Character('R'),
                Edge::Press,
                OverlayState::default()
            ),
            Some(Action::ReleaseMonitor),
            "R releases a monitor — the only trigger, since undecorated \
             overlay windows have no close button"
        );
        // W and Tab both cycle the tool; Z undoes; quit is not in the
        // table at all — it lives on Esc in the app.
        for key in [KeyName::Character('W'), KeyName::Tab] {
            assert_eq!(
                match_event(&bindings, key, Edge::Press, OverlayState::default()),
                Some(Action::NextTool)
            );
        }
        assert_eq!(
            match_event(
                &bindings,
                KeyName::Character('Z'),
                Edge::Press,
                OverlayState::default()
            ),
            Some(Action::Undo)
        );
        assert!(
            !bindings.iter().any(|b| b.action == Action::Quit),
            "quit is Esc's job, not a letter's"
        );
    }
}