openlogi_core/binding/action.rs
1//! The action vocabulary a button can bind to, plus workflow steps.
2
3use serde::{Deserialize, Serialize};
4
5use super::application_target::ApplicationTarget;
6use super::category::Category;
7use super::key_combo::KeyCombo;
8
9/// What pressing a [`ButtonId`] should do.
10///
11/// Serialization uses serde's default external tagging: unit variants
12/// serialize as a bare string (`"BrowserBack"`) and the tuple variant
13/// serializes as a single-key table (`{ CustomShortcut = "my chord" }`).
14///
15/// **Stability contract:** existing variant *names* are frozen — they form the
16/// on-disk `config.toml` schema. New variants may be appended freely; removing
17/// or renaming a variant requires a `schema_version` bump and a migration.
18///
19/// This type is pure config data: OS-level event synthesis for each variant
20/// lives in the `openlogi-inject` crate (`openlogi_inject::execute`), keeping
21/// this crate platform- and IO-free.
22#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
23pub enum Action {
24 // ── System ───────────────────────────────────────────────────────────────
25 /// Suppress the input entirely — the button or wheel direction is captured
26 /// but no OS event is synthesised, so the physical input does nothing.
27 None,
28
29 // ── Mouse ────────────────────────────────────────────────────────────────
30 /// Primary mouse button.
31 LeftClick,
32 /// Secondary mouse button.
33 RightClick,
34 /// Middle mouse button (wheel click).
35 MiddleClick,
36 /// Mouse "back" side button (extra button 4). Synthesizes the real mouse
37 /// button event, which browsers and most apps interpret as "navigate back"
38 /// natively — unlike [`Action::BrowserBack`], which sends ⌘[ and is ignored
39 /// by many apps.
40 MouseBack,
41 /// Mouse "forward" side button (extra button 5). Native counterpart to
42 /// [`Action::MouseBack`]; see [`Action::BrowserForward`] for the ⌘] form.
43 MouseForward,
44
45 // ── Editing ──────────────────────────────────────────────────────────────
46 /// Copy the current selection (⌘C / Ctrl+C).
47 Copy,
48 /// Paste from the clipboard (⌘V / Ctrl+V).
49 Paste,
50 /// Cut the current selection (⌘X / Ctrl+X).
51 Cut,
52 /// Undo the last action (⌘Z / Ctrl+Z).
53 Undo,
54 /// Redo the last undone action (⌘⇧Z on macOS / Ctrl+Shift+Z on Linux).
55 ///
56 /// Note: Ctrl+Y is the dominant redo shortcut in LibreOffice and many GTK
57 /// apps. Ctrl+Shift+Z is used here because it mirrors the macOS convention
58 /// and works in GNOME text fields, browsers, and Electron apps. If Ctrl+Y
59 /// coverage is needed, a `CustomShortcut` binding is the escape hatch.
60 Redo,
61 /// Select all content (⌘A / Ctrl+A).
62 SelectAll,
63 /// Open the find / search bar (⌘F / Ctrl+F).
64 Find,
65 /// Save the current document (⌘S / Ctrl+S).
66 Save,
67
68 // ── Browser / Navigation ──────────────────────────────────────────────────
69 /// Navigate backward in browser history.
70 BrowserBack,
71 /// Navigate forward in browser history.
72 BrowserForward,
73 /// Open a new tab (⌘T / Ctrl+T).
74 NewTab,
75 /// Close the current tab (⌘W / Ctrl+W).
76 CloseTab,
77 /// Reopen the last closed tab (⌘⇧T / Ctrl+Shift+T).
78 ReopenTab,
79 /// Switch to the next tab (⌃⇥ / Ctrl+Tab).
80 NextTab,
81 /// Switch to the previous tab (⌃⇧⇥ / Ctrl+Shift+Tab).
82 PrevTab,
83 /// Reload the current page (⌘R / Ctrl+R).
84 ReloadPage,
85
86 // ── Navigation / Window ───────────────────────────────────────────────────
87 /// macOS Mission Control (⌃↑).
88 MissionControl,
89 /// macOS App Exposé — all windows for the current app (⌃↓).
90 AppExpose,
91 /// Switch to the previous desktop / Space.
92 PreviousDesktop,
93 /// Switch to the next desktop / Space.
94 NextDesktop,
95 /// Show the desktop (hide all windows).
96 ShowDesktop,
97 /// Open Launchpad.
98 LaunchpadShow,
99
100 // ── System ────────────────────────────────────────────────────────────────
101 /// Lock the screen (⌘⌃Q on macOS).
102 ///
103 /// On Linux, calls `org.freedesktop.login1.Manager.LockSession($XDG_SESSION_ID)`
104 /// on the system bus (current session only). Falls back to Super+L when
105 /// `$XDG_SESSION_ID` is unset or on non-systemd systems.
106 LockScreen,
107 /// Capture a screenshot.
108 Screenshot,
109 /// Capture a selected screen region to the clipboard.
110 ///
111 /// macOS uses Cmd+Shift+Ctrl+4; Windows uses Win+Shift+S. Linux delegates
112 /// to the desktop environment's screenshot handler via Print Screen.
113 CaptureRegion,
114
115 // ── Media ────────────────────────────────────────────────────────────────
116 /// Toggle media play/pause.
117 PlayPause,
118 /// Skip to the next track.
119 NextTrack,
120 /// Go back to the previous track.
121 PrevTrack,
122 /// Increase system volume.
123 VolumeUp,
124 /// Decrease system volume.
125 VolumeDown,
126 /// Toggle system mute.
127 MuteVolume,
128
129 // ── DPI ──────────────────────────────────────────────────────────────────
130 /// Step through the configured DPI preset list (P1.7).
131 CycleDpiPresets,
132 /// Jump to a specific zero-based preset in the device's DPI preset list.
133 /// Out-of-range indices clamp to the list length at fire time (P1.7).
134 SetDpiPreset(u8),
135 /// Toggle the HID++ SmartShift ratchet/free-spin wheel mode (P1.1).
136 ToggleSmartShift,
137
138 // ── Scroll ───────────────────────────────────────────────────────────────
139 /// Synthesise a vertical scroll-up tick.
140 ScrollUp,
141 /// Synthesise a vertical scroll-down tick.
142 ScrollDown,
143 /// Synthesise a horizontal scroll-left tick.
144 HorizontalScrollLeft,
145 /// Synthesise a horizontal scroll-right tick.
146 HorizontalScrollRight,
147
148 // ── Custom ───────────────────────────────────────────────────────────────
149 /// Replay an arbitrary recorded key chord (P1.3).
150 ///
151 /// Holds the structured chord data so `openlogi_inject::execute` can post the
152 /// real keystroke (macOS: CGEventPost with the encoded modifier flags).
153 /// The `display` field is used by [`Action::label`] so the popover
154 /// shows the user-friendly chord name.
155 CustomShortcut(KeyCombo),
156
157 // ── System (appended) ────────────────────────────────────────────────────
158 /// Put the computer to sleep. Appended after `CustomShortcut` because the
159 /// serde variant index is the wire format (see the stability contract
160 /// above) — new variants only ever go at the end.
161 Sleep,
162 /// Type an arbitrary string by emitting unicode characters (macOS
163 /// `CGEventKeyboardSetUnicodeString`). Used for macro text. Power-user
164 /// escape hatch — excluded from the default catalog.
165 TypeText(String),
166 /// Run an AppleScript via `osascript -e <source>`. Power-user escape hatch.
167 RunAppleScript(String),
168 /// Run a shell command via `/bin/sh -c <command>`. Power-user escape hatch.
169 RunShellCommand(String),
170 /// Run a timed, ordered sequence of steps — the native, no-code version of
171 /// "type 'bite me', wait 5s, press Enter, wait 5s, type more, Escape". Each
172 /// step is one of the power-user actions or a `Delay`. The sequencer
173 /// (`openlogi-inject`) runs them in order, awaiting `Delay`s. Power-user
174 /// escape hatch — excluded from the default catalog.
175 Workflow(Vec<WorkflowStep>),
176 /// Open the configured Actions Ring at the current pointer position.
177 /// The agent handles the ring session rather than the OS injector.
178 ShowActionsRing,
179 /// Open an application, folder, filesystem path, or platform URL.
180 OpenApplication(ApplicationTarget),
181}
182
183/// One step in a [`Action::Workflow`]. A workflow is a `Vec<WorkflowStep>`
184/// executed in order by the inject layer; `Delay` introduces a pause between
185/// the surrounding steps.
186///
187/// `PressKey` reuses [`KeyCombo`] (the same model as [`Action::CustomShortcut`])
188/// so a step can press a key chord. The other variants mirror their standalone
189/// [`Action`] counterparts.
190#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
191pub enum WorkflowStep {
192 /// Type a unicode string (see [`Action::TypeText`]).
193 TypeText(String),
194 /// Press a key chord (see [`Action::CustomShortcut`] / [`KeyCombo`]).
195 PressKey(KeyCombo),
196 /// Wait `millis` milliseconds before the next step.
197 Delay {
198 /// Pause length in milliseconds.
199 millis: u64,
200 },
201 /// Run an AppleScript (see [`Action::RunAppleScript`]).
202 RunAppleScript(String),
203 /// Run a shell command (see [`Action::RunShellCommand`]).
204 RunShellCommand(String),
205}
206
207/// X-macro table of every payload-free [`Action`] variant.
208///
209/// Each row is `Variant "Label" Category Icon`, optionally followed by
210/// `not_pickable` for a row [`Action::catalog`] must omit. This is the single
211/// place a plain action is declared; payload-carrying variants (`SetDpiPreset`,
212/// `CustomShortcut`, …) build their label/category/icon from their payload and
213/// keep hand-written arms alongside the generated ones instead.
214///
215/// `macro_rules!` can only emit items into the module it is invoked from, so
216/// this table doesn't generate code itself — it forwards its rows verbatim to
217/// a `$callback!` macro chosen by the caller. `action.rs` (below) uses it to
218/// derive [`Action::label`], [`Action::category`], and [`Action::catalog`];
219/// `action_ring::icon` uses it to derive [`ActionRingIcon::for_action`](
220/// super::action_ring::ActionRingIcon::for_action). Row order is
221/// [`Action::catalog`]'s output order, grouped by category to match the
222/// popover section layout — edit rows here only, never in a callback's match.
223macro_rules! for_each_unit_action {
224 ($callback:ident) => {
225 $callback! {
226 // Mouse
227 LeftClick "Left Click" Mouse Pointer,
228 RightClick "Right Click" Mouse Pointer,
229 MiddleClick "Middle Click" Mouse Mouse,
230 MouseBack "Back (Button 4)" Mouse MouseBack,
231 MouseForward "Forward (Button 5)" Mouse MouseForward,
232 // Editing
233 Copy "Copy" Editing Copy,
234 Paste "Paste" Editing Paste,
235 Cut "Cut" Editing Cut,
236 Undo "Undo" Editing Undo,
237 Redo "Redo" Editing Redo,
238 SelectAll "Select All" Editing SelectAll,
239 Find "Find" Editing Search,
240 Save "Save" Editing Save,
241 // Browser
242 BrowserBack "Browser Back" Browser ArrowLeft,
243 BrowserForward "Browser Forward" Browser ArrowRight,
244 NewTab "New Tab" Browser NewTab,
245 CloseTab "Close Tab" Browser CloseTab,
246 ReopenTab "Reopen Tab" Browser ReopenTab,
247 NextTab "Next Tab" Browser NextTab,
248 PrevTab "Previous Tab" Browser PreviousTab,
249 ReloadPage "Reload Page" Browser Reload,
250 // Navigation
251 MissionControl "Mission Control" Navigation Grid,
252 AppExpose "App Exposé" Navigation Layers,
253 PreviousDesktop "Previous Desktop" Navigation PreviousDesktop,
254 NextDesktop "Next Desktop" Navigation NextDesktop,
255 ShowDesktop "Show Desktop" Navigation Monitor,
256 LaunchpadShow "Launchpad" Navigation Applications,
257 // System
258 None "Do Nothing" System Ban,
259 LockScreen "Lock Screen" System Lock,
260 Screenshot "Screenshot" System Camera,
261 CaptureRegion "Capture Region" System Camera,
262 Sleep "Sleep" System Monitor,
263 ShowActionsRing "Actions Ring" System Grid not_pickable,
264 // Media
265 PlayPause "Play / Pause" Media Play,
266 NextTrack "Next Track" Media NextTrack,
267 PrevTrack "Previous Track" Media PreviousTrack,
268 VolumeUp "Volume Up" Media Volume,
269 VolumeDown "Volume Down" Media VolumeDown,
270 MuteVolume "Mute" Media Mute,
271 // DPI
272 CycleDpiPresets "Cycle DPI Presets" Dpi Gauge,
273 ToggleSmartShift "Toggle SmartShift" Dpi Refresh,
274 // Scroll
275 ScrollUp "Scroll Up" Scroll ArrowUp,
276 ScrollDown "Scroll Down" Scroll ArrowDown,
277 HorizontalScrollLeft "Scroll Left" Scroll ScrollLeft,
278 HorizontalScrollRight "Scroll Right" Scroll ScrollRight,
279 }
280 };
281}
282pub(super) use for_each_unit_action;
283
284/// Builds `label`, `category`, and `catalog` from [`for_each_unit_action!`]'s
285/// rows, splicing in the hand-written arms for payload-carrying variants so
286/// each generated `match` still covers every [`Action`] variant exhaustively.
287macro_rules! derive_action_core {
288 ( $( $variant:ident $label:literal $category:ident $icon:ident $( $tag:ident )? ),* $(,)? ) => {
289 impl Action {
290 /// Display label for the popover row.
291 ///
292 /// Returns `String` rather than `&str` so parameterized variants (e.g.
293 /// `SetDpiPreset(i)`, `CustomShortcut(s)`) can build a label that
294 /// includes their payload.
295 #[must_use]
296 pub fn label(&self) -> String {
297 match self {
298 $( Action::$variant => $label.into(), )*
299 Action::SetDpiPreset(i) => format!("DPI Preset {}", i + 1),
300 Action::CustomShortcut(combo) => combo.rendered_label(),
301 Action::TypeText(s) => format!("Type \"{s}\""),
302 Action::RunAppleScript(_) => "Run AppleScript".into(),
303 Action::RunShellCommand(_) => "Run Command".into(),
304 Action::Workflow(steps) => format!("Workflow ({} steps)", steps.len()),
305 Action::OpenApplication(target) => format!("Open {}", target.display_name()),
306 }
307 }
308
309 /// Which [`Category`] this action belongs to, used for popover grouping.
310 #[must_use]
311 pub fn category(&self) -> Category {
312 match self {
313 $( Action::$variant => Category::$category, )*
314 // CustomShortcut is assigned to Editing so it doesn't need a
315 // separate arm (it's not in the picker catalog).
316 Action::CustomShortcut(_)
317 | Action::TypeText(_)
318 | Action::RunAppleScript(_)
319 | Action::RunShellCommand(_)
320 | Action::Workflow(_) => Category::Editing,
321 Action::SetDpiPreset(_) => Category::Dpi,
322 Action::OpenApplication(_) => Category::System,
323 }
324 }
325
326 /// All pickable actions in a deterministic order.
327 ///
328 /// [`Action::CustomShortcut`] is intentionally excluded — it is opened via
329 /// "Record shortcut…" (P1.3), not selected from the catalog. Table rows
330 /// tagged `not_pickable` (currently only [`Action::ShowActionsRing`], the
331 /// fixed default for [`ButtonId::HapticPanel`](super::ButtonId::HapticPanel))
332 /// are excluded from the catalog the same way.
333 #[must_use]
334 pub fn catalog() -> Vec<Action> {
335 [ $( derive_action_core!(@item $variant $( $tag )?) ),* ]
336 .into_iter()
337 .flatten()
338 .collect()
339 }
340 }
341 };
342 (@item $variant:ident) => {
343 Some(Action::$variant)
344 };
345 (@item $variant:ident not_pickable) => {
346 None
347 };
348}
349
350for_each_unit_action!(derive_action_core);