poor-mans-macropad 0.1.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- macropad/README.md +410 -0
- macropad/__init__.py +8 -0
- macropad/__main__.py +4 -0
- macropad/actions.py +130 -0
- macropad/assets/macropad.svg +18 -0
- macropad/cli/__init__.py +161 -0
- macropad/cli/doctor.py +26 -0
- macropad/cli/init.py +234 -0
- macropad/cli/listen.py +180 -0
- macropad/cli/monitor.py +99 -0
- macropad/cli/profile_files.py +63 -0
- macropad/cli/service.py +159 -0
- macropad/cli/status.py +46 -0
- macropad/cli/validate.py +18 -0
- macropad/config.py +127 -0
- macropad/diagnostics.py +290 -0
- macropad/handlers.py +286 -0
- macropad/interceptor.py +391 -0
- macropad/logging_config.py +48 -0
- macropad/notifications.py +38 -0
- macropad/profile_watcher.py +87 -0
- macropad/profiles.py +458 -0
- macropad/runtime_status.py +263 -0
- macropad/service_unit.py +133 -0
- macropad/supervisor.py +321 -0
- macropad/validation.py +91 -0
- macropad/worker.py +75 -0
- poor_mans_macropad-0.1.0.dist-info/METADATA +541 -0
- poor_mans_macropad-0.1.0.dist-info/RECORD +32 -0
- poor_mans_macropad-0.1.0.dist-info/WHEEL +4 -0
- poor_mans_macropad-0.1.0.dist-info/entry_points.txt +3 -0
- poor_mans_macropad-0.1.0.dist-info/licenses/LICENSE +21 -0
macropad/README.md
ADDED
|
@@ -0,0 +1,410 @@
|
|
|
1
|
+
# Macropad Runtime Architecture
|
|
2
|
+
|
|
3
|
+
This directory contains the complete runtime implementation for Macropad. Runtime domains use a
|
|
4
|
+
flat module layout, while the `cli/` package groups command-specific orchestration behind a small
|
|
5
|
+
argument-parsing and dispatch boundary.
|
|
6
|
+
|
|
7
|
+
This document is the architecture reference for contributors. Update it whenever module ownership,
|
|
8
|
+
dependency direction, process lifecycle, or the profile and event flows change.
|
|
9
|
+
|
|
10
|
+
## Module Map
|
|
11
|
+
|
|
12
|
+
| Module | Responsibility |
|
|
13
|
+
|------------------------|----------------------------------------------------------------------------------------------------------------------------------------|
|
|
14
|
+
| `__main__.py` | Implements the `python -m macropad` entry point by delegating to `cli.main()`. |
|
|
15
|
+
| `cli/__init__.py` | Parses arguments, dispatches commands, and handles process-wide command errors. |
|
|
16
|
+
| `cli/listen.py` | Coordinates listener startup, profile reloads, the parent supervision loop, and top-level shutdown. |
|
|
17
|
+
| `cli/doctor.py` | Renders read-only environment diagnostics and returns status based on blocking results. |
|
|
18
|
+
| `cli/init.py` | Orchestrates guided input checks, device/key capture, collision-safe fragment creation, and generated-profile validation. |
|
|
19
|
+
| `cli/monitor.py` | Lists readable devices and renders non-grabbing key-event streams. |
|
|
20
|
+
| `cli/status.py` | Queries and renders live parent, worker, device, retry, and configuration state. |
|
|
21
|
+
| `cli/validate.py` | Resolves validation inputs and delegates the standalone validation workflow. |
|
|
22
|
+
| `cli/profile_files.py` | Owns the default configuration path and discovers unique profile files for CLI commands. |
|
|
23
|
+
| `cli/service.py` | Runs service command actions through explicit `systemctl --user` and `journalctl --user` invocations. |
|
|
24
|
+
| `service_unit.py` | Resolves installed executable and XDG unit paths, renders generated units, and safely installs or removes owned unit files. |
|
|
25
|
+
| `profile_watcher.py` | Adapts Watchdog events, manages the polling observer, and schedules trailing-edge profile reloads. |
|
|
26
|
+
| `runtime_status.py` | Owns the secured local Unix status endpoint, client transport, and runtime path resolution. |
|
|
27
|
+
| `diagnostics.py` | Classifies input access, profiles, notifications, installation paths, and environment checks. |
|
|
28
|
+
| `validation.py` | Loads complete validation candidates, collects file and merged errors, and renders validation reports. |
|
|
29
|
+
| `config.py` | Defines the deeply immutable, picklable profile configuration model and validation error type. |
|
|
30
|
+
| `profiles.py` | Loads strict YAML and validates, normalizes, groups, and merges profile configurations. |
|
|
31
|
+
| `supervisor.py` | Reconciles desired profiles with worker slots, owns child processes, applies restart backoff, and enforces bounded shutdown. |
|
|
32
|
+
| `worker.py` | Defines the child-process entry point, installs the worker signal handler, constructs the keyboard handler, and owns handler shutdown. |
|
|
33
|
+
| `interceptor.py` | Discovers evdev devices, detects newly connected keyboards, grabs matching event nodes, and forwards input events to a handler. |
|
|
34
|
+
| `handlers.py` | Resolves key events, tap and hold sequences, layers, and internal handler commands into action submissions. |
|
|
35
|
+
| `actions.py` | Starts trusted shell actions as detached processes and enforces the per-worker concurrency limit. |
|
|
36
|
+
| `notifications.py` | Initializes optional desktop notifications and sends notifications without making them a runtime requirement. |
|
|
37
|
+
| `logging_config.py` | Selects normal, verbose, or debug levels and renders structured context fields consistently. |
|
|
38
|
+
| `assets/` | Contains package resources, currently the desktop notification icon. |
|
|
39
|
+
|
|
40
|
+
## Dependency Diagram
|
|
41
|
+
|
|
42
|
+
```mermaid
|
|
43
|
+
flowchart TD
|
|
44
|
+
Entrypoints[macropad and python -m macropad] --> CLI[cli/__init__.py]
|
|
45
|
+
CLI --> Listen[cli/listen.py]
|
|
46
|
+
CLI --> Doctor[cli/doctor.py]
|
|
47
|
+
CLI --> Init[cli/init.py]
|
|
48
|
+
CLI --> Monitor[cli/monitor.py]
|
|
49
|
+
CLI --> Status[cli/status.py]
|
|
50
|
+
CLI --> ValidateCommand[cli/validate.py]
|
|
51
|
+
CLI --> Service[cli/service.py]
|
|
52
|
+
|
|
53
|
+
Listen --> ProfileFiles[cli/profile_files.py]
|
|
54
|
+
Listen --> ProfileWatcher[profile_watcher.py]
|
|
55
|
+
Listen --> Supervisor[supervisor.py]
|
|
56
|
+
Listen --> Notifications[notifications.py]
|
|
57
|
+
Listen --> RuntimeStatus[runtime_status.py]
|
|
58
|
+
|
|
59
|
+
Doctor --> Diagnostics[diagnostics.py]
|
|
60
|
+
Doctor --> ProfileFiles
|
|
61
|
+
Doctor --> Service
|
|
62
|
+
Diagnostics --> Interceptor[interceptor.py]
|
|
63
|
+
Diagnostics --> Notifications
|
|
64
|
+
|
|
65
|
+
Init --> Diagnostics
|
|
66
|
+
Init --> Interceptor
|
|
67
|
+
Init --> ProfileFiles
|
|
68
|
+
Init --> Profiles
|
|
69
|
+
Init --> Validation
|
|
70
|
+
Init --> Service
|
|
71
|
+
|
|
72
|
+
Monitor --> Interceptor
|
|
73
|
+
Status --> RuntimeStatus
|
|
74
|
+
Status --> Service
|
|
75
|
+
|
|
76
|
+
ValidateCommand --> ProfileFiles
|
|
77
|
+
ValidateCommand --> Validation[validation.py]
|
|
78
|
+
|
|
79
|
+
Supervisor --> Profiles
|
|
80
|
+
Supervisor --> Worker[worker.py]
|
|
81
|
+
Supervisor --> Interceptor
|
|
82
|
+
|
|
83
|
+
Validation --> Profiles
|
|
84
|
+
Validation --> Config
|
|
85
|
+
Profiles --> Config[config.py]
|
|
86
|
+
ProfileWatcher --> Watchdog[watchdog]
|
|
87
|
+
Service --> Systemd[systemctl]
|
|
88
|
+
Service --> Journal[journalctl]
|
|
89
|
+
Service --> ServiceUnit[service_unit.py]
|
|
90
|
+
ServiceUnit --> UnitFile[generated user unit]
|
|
91
|
+
|
|
92
|
+
Worker --> Handler[handlers.py]
|
|
93
|
+
Worker --> Interceptor
|
|
94
|
+
Worker --> Actions
|
|
95
|
+
Worker --> StatusQueue[worker status queue]
|
|
96
|
+
Supervisor --> StatusQueue
|
|
97
|
+
|
|
98
|
+
Handler --> Config
|
|
99
|
+
Handler --> Actions[actions.py]
|
|
100
|
+
Handler --> Notifications
|
|
101
|
+
|
|
102
|
+
Interceptor --> Evdev[evdev]
|
|
103
|
+
Actions --> Shell[detached shell processes]
|
|
104
|
+
Notifications --> Notify2[notify2 and DBus]
|
|
105
|
+
```
|
|
106
|
+
|
|
107
|
+
Dependencies should continue to point inward toward immutable configuration and outward toward
|
|
108
|
+
system adapters. In particular:
|
|
109
|
+
|
|
110
|
+
- `profiles.py` must remain independent of worker, handler, process, and device state.
|
|
111
|
+
- `profile_watcher.py` owns filesystem event filtering and reload timing but never reloads profiles.
|
|
112
|
+
- `diagnostics.py` classifies checks but leaves evdev and systemd resource ownership in their
|
|
113
|
+
existing adapters.
|
|
114
|
+
- `cli/service.py` owns systemd and journal subprocess invocation but no daemon runtime state;
|
|
115
|
+
`service_unit.py` owns unit rendering and filesystem changes without invoking systemd.
|
|
116
|
+
- `supervisor.py` owns processes but does not process keyboard events.
|
|
117
|
+
- `worker.py` is the boundary where immutable configuration becomes mutable runtime state.
|
|
118
|
+
- `interceptor.py` owns evdev resources but does not construct or shut down handlers.
|
|
119
|
+
- `handlers.py` may submit actions and notifications but must not manage worker processes.
|
|
120
|
+
- `actions.py`, `notifications.py`, and `interceptor.py` are adapters to operating-system services.
|
|
121
|
+
|
|
122
|
+
## Process Model
|
|
123
|
+
|
|
124
|
+
The CLI runs in the parent process. `ProfileSupervisor` maintains one worker slot for each configured
|
|
125
|
+
keyboard name. Each slot has its own `multiprocessing.Process`, shutdown event, restart counters, and
|
|
126
|
+
retry deadline.
|
|
127
|
+
|
|
128
|
+
Only immutable `ProfileConfig` data, logging option booleans, a worker generation ID, and the shared
|
|
129
|
+
status queue cross the process boundary. The
|
|
130
|
+
parent does not construct a `KeyboardHandler` or `ActionExecutor`. The child enters through
|
|
131
|
+
`worker.run()`, configures its own logging so non-fork start methods behave consistently, installs its
|
|
132
|
+
SIGTERM handler, constructs the executor and handler, and then enters the interception loop. This
|
|
133
|
+
keeps mutable resources owned by the process that uses them and avoids requiring runtime objects to
|
|
134
|
+
be serialized.
|
|
135
|
+
|
|
136
|
+
The project is Linux-only. Device identity is the evdev keyboard name, and one worker attaches to all
|
|
137
|
+
current `/dev/input/event*` nodes with that name.
|
|
138
|
+
|
|
139
|
+
## Startup Flow
|
|
140
|
+
|
|
141
|
+
1. `cli.main()` parses global logging options, configures normal, verbose, or debug logging, and
|
|
142
|
+
dispatches to the focused `doctor`, `init`, `listen`, `monitor`, `validate`, or `service` command
|
|
143
|
+
module.
|
|
144
|
+
2. `cli.listen.run()` initializes optional notifications and installs the parent SIGTERM handler.
|
|
145
|
+
3. `cli.profile_files` resolves explicit profile paths and all `.yml` files in requested profile
|
|
146
|
+
directories.
|
|
147
|
+
4. `ProfileSupervisor.start()` calls `prepare_profiles()` before starting any process.
|
|
148
|
+
5. Every YAML file is loaded and validated before fragments are merged by keyboard name.
|
|
149
|
+
6. The supervisor creates one worker slot per merged `ProfileConfig` and starts `worker.run()` in a
|
|
150
|
+
child process, forwarding logging level and action-output options.
|
|
151
|
+
7. The worker configures logging, constructs `ActionExecutor` and `KeyboardHandler`, then calls
|
|
152
|
+
`interceptor.listen()`.
|
|
153
|
+
8. The interceptor waits for matching devices, opens and grabs every matching event node, and begins
|
|
154
|
+
forwarding input events.
|
|
155
|
+
9. The worker publishes deduplicated state transitions to the parent, which serves snapshots through
|
|
156
|
+
the local runtime status socket.
|
|
157
|
+
|
|
158
|
+
`cli.profile_files` resolves the default directory from an absolute `XDG_CONFIG_HOME`, falling back
|
|
159
|
+
to `~/.config` when it is unset or invalid. If a custom XDG profile directory is absent but the
|
|
160
|
+
legacy `~/.config/macropad/profiles/` directory exists, the legacy path remains active until the XDG
|
|
161
|
+
directory is created. No files are migrated automatically.
|
|
162
|
+
|
|
163
|
+
If the resolved default configuration directory contains profiles, the CLI automatically enables
|
|
164
|
+
profile watching. If it does not exist or contains no YAML files, startup fails with profile-format
|
|
165
|
+
guidance without creating directories or example files.
|
|
166
|
+
|
|
167
|
+
The validation command module delegates to `validation.run()`, which uses the same complete load,
|
|
168
|
+
validation, grouping, and merge path as worker startup, but never initializes notifications,
|
|
169
|
+
constructs a supervisor, or opens an input device. Semantic checks that depend on the complete device
|
|
170
|
+
configuration, including layer references, run after fragments for that device are merged.
|
|
171
|
+
|
|
172
|
+
## Guided Initialization Flow
|
|
173
|
+
|
|
174
|
+
`cli.init` is interactive orchestration over existing adapters and profile APIs; it does not own
|
|
175
|
+
evdev handles or duplicate profile merge rules.
|
|
176
|
+
|
|
177
|
+
1. Read systemd service state and render the blocking input checks from `diagnostics.py`.
|
|
178
|
+
2. Ask the user to disconnect the target, then call the non-grabbing `interceptor.detect()` under a
|
|
179
|
+
monotonic timeout while the user reconnects it and presses a key.
|
|
180
|
+
3. Load and merge current default-directory profiles. For an already-profiled device, list its
|
|
181
|
+
fragment paths and require confirmation before proposing another fragment.
|
|
182
|
+
4. If that key's release event is already bound, call `interceptor.capture_key()` to wait for release
|
|
183
|
+
and capture a different key from the same device.
|
|
184
|
+
5. Validate the proposed fragment together with all loaded profiles in memory.
|
|
185
|
+
6. Select a slug-based filename with a numeric collision suffix, create it exclusively, and run the
|
|
186
|
+
normal complete validation workflow against the on-disk directory.
|
|
187
|
+
7. Remove only the generated file on cancellation or any write or validation failure. On success,
|
|
188
|
+
report the exact path, refresh service state, qualify watch behavior when effective arguments are
|
|
189
|
+
unknown, and show the next foreground or service command.
|
|
190
|
+
|
|
191
|
+
## Input And Action Flow
|
|
192
|
+
|
|
193
|
+
```mermaid
|
|
194
|
+
sequenceDiagram
|
|
195
|
+
participant Device as evdev device
|
|
196
|
+
participant Interceptor as interceptor.listen
|
|
197
|
+
participant Handler as KeyboardHandler
|
|
198
|
+
participant Executor as ActionExecutor
|
|
199
|
+
participant Shell as detached shell process
|
|
200
|
+
|
|
201
|
+
Device->>Interceptor: InputEvent
|
|
202
|
+
Interceptor->>Handler: handle(event)
|
|
203
|
+
Interceptor->>Handler: tick()
|
|
204
|
+
Handler->>Handler: resolve key, tap, hold, and layer state
|
|
205
|
+
Handler->>Executor: submit(command)
|
|
206
|
+
Executor->>Shell: Popen(shell=True, start_new_session=True)
|
|
207
|
+
Interceptor->>Handler: tick on later loop iterations
|
|
208
|
+
Handler->>Executor: tick()
|
|
209
|
+
Executor->>Executor: reap completed actions
|
|
210
|
+
```
|
|
211
|
+
|
|
212
|
+
Simple `up` or `down` bindings can execute immediately. Bindings involving hold, double-tap, or
|
|
213
|
+
triple-tap resolution use monotonic deadlines and are advanced by `KeyboardHandler.tick()` on the
|
|
214
|
+
listener thread. Layer timeouts use the same threadless mechanism.
|
|
215
|
+
|
|
216
|
+
Actions are trusted shell strings. Each worker may have at most eight active actions; additional
|
|
217
|
+
actions are dropped rather than queued and logged with the active count and limit. Action processes
|
|
218
|
+
are detached and are not terminated when a worker reloads or stops. Normal mode routes stdout and
|
|
219
|
+
stderr to `/dev/null`; action-debug mode inherits the worker streams so foreground output remains in
|
|
220
|
+
the terminal and service output reaches the journal.
|
|
221
|
+
|
|
222
|
+
The handler passes resolved device, key, event, and base or named layer context into each submission.
|
|
223
|
+
The executor retains that trigger context through command start, process ID, exit status, and
|
|
224
|
+
concurrency rejection records, including when identical commands run concurrently. Debug startup
|
|
225
|
+
logging reports only the action working directory, `PATH`, display names, DBus presence, and output
|
|
226
|
+
mode rather than dumping the full environment or DBus address.
|
|
227
|
+
|
|
228
|
+
The generated systemd user unit gives actions a deterministic `PATH` containing `~/bin`,
|
|
229
|
+
`~/.local/bin`, and standard system command directories. It invokes the console script from the
|
|
230
|
+
environment that installed the unit and intentionally does not start Macropad through a login shell.
|
|
231
|
+
|
|
232
|
+
## Service Installation Flow
|
|
233
|
+
|
|
234
|
+
`cli.service.install()` asks `service_unit.py` to resolve the console script beside the active Python
|
|
235
|
+
environment, resolve the user unit path from an absolute `XDG_CONFIG_HOME` or `~/.config`, and render
|
|
236
|
+
the unit. The unit file is replaced atomically only when absent, marked as generated by Macropad, or
|
|
237
|
+
explicitly forced. The CLI then reloads systemd, enables the unit, and starts it.
|
|
238
|
+
|
|
239
|
+
Uninstall validates the same marker before stopping anything, stops and disables the unit, removes
|
|
240
|
+
it, and reloads systemd. It never removes package files or profiles. Development checkouts and
|
|
241
|
+
installed tools use this same path; `make test-systemd` only validates production renderer output.
|
|
242
|
+
|
|
243
|
+
## Device Lifecycle
|
|
244
|
+
|
|
245
|
+
`matching_device_paths()` enumerates evdev paths, opens each path long enough to inspect its name, and
|
|
246
|
+
closes every probe. Paths that disappear during enumeration are ignored. Permission failures and
|
|
247
|
+
other open errors are logged once per unresolved operation and path rather than silently treated as
|
|
248
|
+
an absent device or repeatedly flooding the journal.
|
|
249
|
+
|
|
250
|
+
The listener opens and exclusively grabs all paths matching the configured keyboard name. When a
|
|
251
|
+
path reports `ENODEV`, it is closed and removed. The listener rescans only after every matching path
|
|
252
|
+
has gone; it intentionally does not acquire an additional path while another matching path remains
|
|
253
|
+
connected.
|
|
254
|
+
|
|
255
|
+
`probe_device_access()` briefly opens, grabs, ungrabs, and closes each current event device for
|
|
256
|
+
`macropad doctor`. It records `EACCES`, `EBUSY`, `ENODEV`, and other operation failures as data so the
|
|
257
|
+
diagnostic workflow can provide remediation without leaking handles. Runtime grab conflicts and
|
|
258
|
+
permission failures are logged distinctly before a worker exits or continues scanning.
|
|
259
|
+
An `EBUSY` probe is a nonblocking warning when the Macropad user service is active and a blocking
|
|
260
|
+
failure otherwise; stopping the service and rerunning the check disambiguates ownership.
|
|
261
|
+
|
|
262
|
+
`interceptor.monitor()` opens every current path matching an exact device name without calling
|
|
263
|
+
`grab()`. It rescans while other paths remain connected, reports each connection and disconnection,
|
|
264
|
+
and reacquires matching paths after reconnect. This monitoring behavior is independent from the
|
|
265
|
+
listener's intentional policy of rescanning only after all matching paths are gone.
|
|
266
|
+
The command reports when the Macropad service is active because its configured devices are already
|
|
267
|
+
exclusively grabbed and cannot deliver events to the non-grabbing monitor until the service stops.
|
|
268
|
+
|
|
269
|
+
`interceptor.listen()` reports `opening` before attempting handles, `listening` only after successful
|
|
270
|
+
grabs, `waiting` after all grabbed paths disappear, and path-specific input errors. `worker.run()`
|
|
271
|
+
adds initial `waiting`, fatal `error`, and cooperative `shutting_down` transitions. Each message
|
|
272
|
+
contains the worker generation ID so updates from a replaced process cannot overwrite its successor.
|
|
273
|
+
|
|
274
|
+
## Runtime Status Flow
|
|
275
|
+
|
|
276
|
+
The parent owns the only external endpoint. Workers cannot accept status clients and status clients
|
|
277
|
+
cannot mutate daemon state.
|
|
278
|
+
|
|
279
|
+
```mermaid
|
|
280
|
+
sequenceDiagram
|
|
281
|
+
participant Worker
|
|
282
|
+
participant Queue as Multiprocessing status queue
|
|
283
|
+
participant Parent as ProfileSupervisor
|
|
284
|
+
participant Socket as Local Unix socket
|
|
285
|
+
participant Client as macropad status
|
|
286
|
+
|
|
287
|
+
Worker->>Queue: waiting/opening/listening/error update
|
|
288
|
+
Parent->>Queue: Drain generation-tagged updates
|
|
289
|
+
Parent->>Parent: Merge process, retry, profile, and reload state
|
|
290
|
+
Parent->>Socket: Publish immutable snapshot before blocking transitions
|
|
291
|
+
Client->>Socket: Connect read-only
|
|
292
|
+
Socket-->>Client: Parent and worker status
|
|
293
|
+
```
|
|
294
|
+
|
|
295
|
+
The socket lives under `$XDG_RUNTIME_DIR/macropad/status.sock`, falling back to a user-specific
|
|
296
|
+
temporary directory. Runtime directories are verified as user-owned and forced to mode `0700`; the
|
|
297
|
+
socket and lifetime lock use mode `0600`. The lock serializes listener startup. Stale and owned socket
|
|
298
|
+
cleanup keeps an `O_PATH` descriptor open while comparing device/inode identity, preventing inode
|
|
299
|
+
recycling from making a replacement look like the original; a regular file is never removed as a
|
|
300
|
+
stale socket. A small read-only server thread keeps the latest parent-published snapshot available
|
|
301
|
+
while the parent waits for workers to stop. Closing the parent attempts to remove only the socket
|
|
302
|
+
inode it created; cleanup errors are logged without preventing socket and lock handles from closing.
|
|
303
|
+
|
|
304
|
+
The internal `detect()` helper snapshots existing paths, waits for a new path even when another
|
|
305
|
+
device disappears at the same time, and returns the new keyboard's name, event path, and first
|
|
306
|
+
pressed `KEY_*` name. One monotonic deadline bounds both reconnect and key capture. `capture_key()`
|
|
307
|
+
uses the same non-grabbing handle lifecycle for another key on a known device, but waits for held keys
|
|
308
|
+
to be released before accepting another press. Probe handles are always closed before either helper
|
|
309
|
+
returns or times out. These helpers are used by guided initialization rather than exposed as
|
|
310
|
+
standalone commands.
|
|
311
|
+
|
|
312
|
+
## Profile Reload Flow
|
|
313
|
+
|
|
314
|
+
The Watchdog polling observer runs in a background thread, but it never reloads configuration itself.
|
|
315
|
+
It inspects both source and destination paths for each event and places every relevant `.yml` path
|
|
316
|
+
into a queue owned by `cli.listen`. This catches direct writes, create/delete events, profile renames,
|
|
317
|
+
and atomic saves that move a temporary file onto a profile.
|
|
318
|
+
|
|
319
|
+
```mermaid
|
|
320
|
+
sequenceDiagram
|
|
321
|
+
participant Watchdog
|
|
322
|
+
participant Queue as Reload queue
|
|
323
|
+
participant CLI as cli.listen parent loop
|
|
324
|
+
participant Scheduler as Reload scheduler
|
|
325
|
+
participant Supervisor as ProfileSupervisor
|
|
326
|
+
|
|
327
|
+
Watchdog->>Queue: Changed source/destination .yml path
|
|
328
|
+
CLI->>Queue: Drain pending paths
|
|
329
|
+
Queue-->>CLI: Event burst
|
|
330
|
+
CLI->>Scheduler: Add paths at monotonic time
|
|
331
|
+
Note over Scheduler: Deduplicate paths and reset one-second deadline
|
|
332
|
+
CLI->>Scheduler: Check deadline each supervision cycle
|
|
333
|
+
Scheduler-->>CLI: Paths after a quiet second
|
|
334
|
+
CLI->>Supervisor: Reload complete current profile set
|
|
335
|
+
```
|
|
336
|
+
|
|
337
|
+
The scheduler is owned by the parent loop. Every new batch moves its monotonic deadline forward, so
|
|
338
|
+
reload happens only after one quiet second. The resulting changed-path list is deduplicated and
|
|
339
|
+
included in reload success and failure logs.
|
|
340
|
+
|
|
341
|
+
Reload follows a validate-then-reconcile model:
|
|
342
|
+
|
|
343
|
+
1. Load and validate the complete candidate file set.
|
|
344
|
+
2. Merge all fragments by keyboard name.
|
|
345
|
+
3. Leave workers with equal immutable configuration running, updating only their source paths.
|
|
346
|
+
4. Stop workers for removed or changed configurations.
|
|
347
|
+
5. Start workers for added or changed configurations.
|
|
348
|
+
6. Preserve independent failure and restart state for unchanged workers.
|
|
349
|
+
|
|
350
|
+
An invalid candidate fails before reconciliation, so currently running workers remain intact.
|
|
351
|
+
|
|
352
|
+
## Failure And Shutdown Behavior
|
|
353
|
+
|
|
354
|
+
The supervisor checks workers once per parent loop iteration. A failed worker receives exponential
|
|
355
|
+
restart backoff from one second up to thirty seconds. After thirty stable seconds, its failure count
|
|
356
|
+
is reset. One failed keyboard does not restart healthy workers.
|
|
357
|
+
|
|
358
|
+
Parent shutdown sets every worker shutdown event and waits up to five seconds across the worker set.
|
|
359
|
+
Workers cooperatively leave the listener loop, close all evdev handles, and shut down their handler.
|
|
360
|
+
Processes that do not stop are killed and joined for one additional second. A process that survives
|
|
361
|
+
the kill is reported as a shutdown failure.
|
|
362
|
+
|
|
363
|
+
Desktop notification initialization and delivery are both optional. Failures are logged and never
|
|
364
|
+
prevent headless startup or event handling.
|
|
365
|
+
|
|
366
|
+
## Configuration Ownership
|
|
367
|
+
|
|
368
|
+
`config.py` contains only immutable value objects:
|
|
369
|
+
|
|
370
|
+
- `ProfileConfig` owns the device name, profile version, keyboard configuration, diagnostic source,
|
|
371
|
+
and deferred layer-reference paths used by merged validation.
|
|
372
|
+
- `KeyboardConfig` owns base bindings and named layers.
|
|
373
|
+
- `LayerConfig` owns layer bindings.
|
|
374
|
+
- `BindingConfig` maps event names to command tuples.
|
|
375
|
+
- `FrozenDict` prevents nested mutation while keeping configurations comparable, hashable, and
|
|
376
|
+
picklable.
|
|
377
|
+
|
|
378
|
+
`profiles.py` is the only module that converts untrusted YAML-shaped data into these objects. Keep
|
|
379
|
+
source names and field paths in every validation error because reload diagnostics depend on them.
|
|
380
|
+
|
|
381
|
+
## Extension Guidelines
|
|
382
|
+
|
|
383
|
+
- Add profile schema behavior in `profiles.py` and immutable values in `config.py`.
|
|
384
|
+
- Add keyboard event semantics in `handlers.py` and use fake monotonic clocks in tests.
|
|
385
|
+
- Add evdev discovery or handle behavior in `interceptor.py` without moving process policy there.
|
|
386
|
+
- Add worker process setup or cleanup in `worker.py`.
|
|
387
|
+
- Add live worker state transitions in `worker.py` and `interceptor.py`, parent snapshots in
|
|
388
|
+
`supervisor.py`, and local transport behavior in `runtime_status.py`.
|
|
389
|
+
- Add reconciliation, restart, or bounded-shutdown policy in `supervisor.py`.
|
|
390
|
+
- Add Watchdog event handling, observer lifecycle, or reload debounce behavior in
|
|
391
|
+
`profile_watcher.py`.
|
|
392
|
+
- Add systemd lifecycle or journal command behavior in `cli/service.py`.
|
|
393
|
+
- Add guided profile-creation policy in `cli/init.py`, reusing diagnostics, interceptor, and profile
|
|
394
|
+
validation APIs rather than moving their ownership into the command module.
|
|
395
|
+
- Add diagnostic checks and remediation in `diagnostics.py`, keeping command rendering in
|
|
396
|
+
`cli/doctor.py` and operating-system resource handling in the owning adapter.
|
|
397
|
+
- Add device and key presentation in `cli/monitor.py`, keeping evdev resources and reconnect behavior
|
|
398
|
+
in `interceptor.py`.
|
|
399
|
+
- Add argument parsing and dispatch in `cli/__init__.py`, and command-specific orchestration in a
|
|
400
|
+
focused module under `cli/`.
|
|
401
|
+
- Add global logging level behavior in `logging_config.py` and pass action-output policy through the
|
|
402
|
+
supervisor to the worker-owned `ActionExecutor`.
|
|
403
|
+
- Add validation workflow or report behavior in `validation.py`, keeping schema and merge rules in
|
|
404
|
+
`profiles.py`.
|
|
405
|
+
- Keep operating-system adapters optional or failure-tolerant where the service can continue without
|
|
406
|
+
them.
|
|
407
|
+
|
|
408
|
+
Unit tests mirror flat runtime modules under `tests/test_*.py` and CLI modules under `tests/cli/`.
|
|
409
|
+
Packaging and lifecycle smoke tests live under `tests/integration/` and are intentionally excluded
|
|
410
|
+
from normal unit-test discovery.
|
macropad/__init__.py
ADDED
macropad/__main__.py
ADDED
macropad/actions.py
ADDED
|
@@ -0,0 +1,130 @@
|
|
|
1
|
+
import logging
|
|
2
|
+
import os
|
|
3
|
+
import subprocess
|
|
4
|
+
from dataclasses import dataclass
|
|
5
|
+
|
|
6
|
+
DEFAULT_MAX_CONCURRENT_ACTIONS = 8
|
|
7
|
+
logger = logging.getLogger(__name__)
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
@dataclass
|
|
11
|
+
class RunningAction:
|
|
12
|
+
command: str
|
|
13
|
+
process: subprocess.Popen
|
|
14
|
+
context: dict
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
class ActionExecutor:
|
|
18
|
+
def __init__(
|
|
19
|
+
self,
|
|
20
|
+
max_concurrent=DEFAULT_MAX_CONCURRENT_ACTIONS,
|
|
21
|
+
process_factory=None,
|
|
22
|
+
device=None,
|
|
23
|
+
debug_output=False,
|
|
24
|
+
):
|
|
25
|
+
if max_concurrent < 1:
|
|
26
|
+
raise ValueError('max_concurrent must be at least 1')
|
|
27
|
+
self.max_concurrent = max_concurrent
|
|
28
|
+
self._process_factory = process_factory or subprocess.Popen
|
|
29
|
+
self.device = device
|
|
30
|
+
self.debug_output = debug_output
|
|
31
|
+
self._running_actions: list[RunningAction] = []
|
|
32
|
+
logger.debug(
|
|
33
|
+
'action execution configured',
|
|
34
|
+
extra=self._context(
|
|
35
|
+
cwd='/',
|
|
36
|
+
action_path=os.environ.get('PATH'),
|
|
37
|
+
display=os.environ.get('DISPLAY'),
|
|
38
|
+
wayland_display=os.environ.get('WAYLAND_DISPLAY'),
|
|
39
|
+
session_bus='set' if os.environ.get('DBUS_SESSION_BUS_ADDRESS') else 'unset',
|
|
40
|
+
mode='inherited output' if debug_output else 'discarded output',
|
|
41
|
+
),
|
|
42
|
+
)
|
|
43
|
+
|
|
44
|
+
@property
|
|
45
|
+
def active_count(self) -> int:
|
|
46
|
+
return len(self._running_actions)
|
|
47
|
+
|
|
48
|
+
def submit(
|
|
49
|
+
self,
|
|
50
|
+
command: str,
|
|
51
|
+
*,
|
|
52
|
+
key: str | None = None,
|
|
53
|
+
event: str | None = None,
|
|
54
|
+
layer: str | None = None,
|
|
55
|
+
) -> bool:
|
|
56
|
+
self.tick()
|
|
57
|
+
trigger_context = {
|
|
58
|
+
name: value
|
|
59
|
+
for name, value in (('key', key), ('event', event), ('layer', layer))
|
|
60
|
+
if value is not None
|
|
61
|
+
}
|
|
62
|
+
if self.active_count >= self.max_concurrent:
|
|
63
|
+
logger.warning(
|
|
64
|
+
'action rejected at concurrency limit',
|
|
65
|
+
extra=self._context(
|
|
66
|
+
command=command,
|
|
67
|
+
count=self.active_count,
|
|
68
|
+
limit=self.max_concurrent,
|
|
69
|
+
**trigger_context,
|
|
70
|
+
),
|
|
71
|
+
)
|
|
72
|
+
return False
|
|
73
|
+
|
|
74
|
+
try:
|
|
75
|
+
process = self._process_factory(
|
|
76
|
+
command,
|
|
77
|
+
shell=True,
|
|
78
|
+
cwd='/',
|
|
79
|
+
stdin=subprocess.DEVNULL,
|
|
80
|
+
stdout=None if self.debug_output else subprocess.DEVNULL,
|
|
81
|
+
stderr=None if self.debug_output else subprocess.DEVNULL,
|
|
82
|
+
close_fds=True,
|
|
83
|
+
start_new_session=True,
|
|
84
|
+
)
|
|
85
|
+
except OSError as error:
|
|
86
|
+
logger.error(
|
|
87
|
+
'action failed to start',
|
|
88
|
+
extra=self._context(command=command, error=str(error), **trigger_context),
|
|
89
|
+
)
|
|
90
|
+
return False
|
|
91
|
+
|
|
92
|
+
self._running_actions.append(RunningAction(command, process, trigger_context))
|
|
93
|
+
logger.info(
|
|
94
|
+
'action started',
|
|
95
|
+
extra=self._context(command=command, pid=process.pid, **trigger_context),
|
|
96
|
+
)
|
|
97
|
+
return True
|
|
98
|
+
|
|
99
|
+
def tick(self) -> None:
|
|
100
|
+
running_actions = []
|
|
101
|
+
for action in self._running_actions:
|
|
102
|
+
exit_status = action.process.poll()
|
|
103
|
+
if exit_status is None:
|
|
104
|
+
running_actions.append(action)
|
|
105
|
+
continue
|
|
106
|
+
log_method = logger.info if exit_status == 0 else logger.warning
|
|
107
|
+
log_method(
|
|
108
|
+
'action exited',
|
|
109
|
+
extra=self._context(
|
|
110
|
+
command=action.command,
|
|
111
|
+
pid=action.process.pid,
|
|
112
|
+
exit_status=exit_status,
|
|
113
|
+
**action.context,
|
|
114
|
+
),
|
|
115
|
+
)
|
|
116
|
+
self._running_actions = running_actions
|
|
117
|
+
|
|
118
|
+
def shutdown(self) -> None:
|
|
119
|
+
self.tick()
|
|
120
|
+
if self._running_actions:
|
|
121
|
+
logger.info(
|
|
122
|
+
'detaching running actions during worker shutdown',
|
|
123
|
+
extra=self._context(count=len(self._running_actions)),
|
|
124
|
+
)
|
|
125
|
+
self._running_actions.clear()
|
|
126
|
+
|
|
127
|
+
def _context(self, **values) -> dict:
|
|
128
|
+
if self.device is not None:
|
|
129
|
+
values['device'] = self.device
|
|
130
|
+
return values
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
<svg width="400" height="400" viewBox="0 0 400 400" xmlns="http://www.w3.org/2000/svg">
|
|
2
|
+
<rect x="20" y="20" width="280" height="280" rx="12" ry="12"
|
|
3
|
+
fill="#fff" stroke="#333" stroke-width="2"/>
|
|
4
|
+
|
|
5
|
+
<g id="keys" fill="#333" stroke="#555" stroke-width="2">
|
|
6
|
+
<rect x="50" y="50" width="60" height="60" rx="6"/>
|
|
7
|
+
<rect x="130" y="50" width="60" height="60" rx="6"/>
|
|
8
|
+
<rect x="210" y="50" width="60" height="60" rx="6"/>
|
|
9
|
+
|
|
10
|
+
<rect x="50" y="130" width="60" height="60" rx="6"/>
|
|
11
|
+
<rect x="130" y="130" width="60" height="60" rx="6"/>
|
|
12
|
+
<rect x="210" y="130" width="60" height="60" rx="6"/>
|
|
13
|
+
|
|
14
|
+
<rect x="50" y="210" width="60" height="60" rx="6"/>
|
|
15
|
+
<rect x="130" y="210" width="60" height="60" rx="6"/>
|
|
16
|
+
<rect x="210" y="210" width="60" height="60" rx="6"/>
|
|
17
|
+
</g>
|
|
18
|
+
</svg>
|