noracu 0.1.0 → 0.1.2
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.
- package/CHANGELOG.md +77 -2
- package/README.md +28 -15
- package/README.zh-CN.md +27 -14
- package/SECURITY.md +5 -1
- package/docs/architecture.md +7 -5
- package/docs/tools.md +15 -15
- package/docs/usage.md +61 -5
- package/imctl/LICENSE +21 -0
- package/imctl/README.md +142 -0
- package/imctl/pyproject.toml +37 -0
- package/imctl/src/imctl/__init__.py +31 -0
- package/imctl/src/imctl/cli.py +297 -0
- package/imctl/src/imctl/gestures.py +317 -0
- package/imctl/src/imctl/input.py +325 -0
- package/imctl/src/imctl/verify.py +77 -0
- package/imctl/src/imctl/vision.py +138 -0
- package/imctl/src/imctl/window.py +352 -0
- package/package.json +11 -4
- package/src/server.mjs +58 -32
|
@@ -0,0 +1,317 @@
|
|
|
1
|
+
"""High-level gestures composed from the input engine.
|
|
2
|
+
|
|
3
|
+
These map to standard iOS interactions. Coordinates are normalized
|
|
4
|
+
(0-1) within the mirroring window. Gesture start points were chosen to
|
|
5
|
+
match iOS conventions (e.g. home swipe starts at the very bottom edge).
|
|
6
|
+
|
|
7
|
+
Phone-level actions that the mirroring app exposes as menu commands
|
|
8
|
+
(Spotlight, Home Screen) are triggered through those menus rather than
|
|
9
|
+
synthesized touch gestures — see the menu-command section below.
|
|
10
|
+
"""
|
|
11
|
+
|
|
12
|
+
from __future__ import annotations
|
|
13
|
+
|
|
14
|
+
import subprocess
|
|
15
|
+
import time
|
|
16
|
+
|
|
17
|
+
from . import input as inp
|
|
18
|
+
from . import vision
|
|
19
|
+
from .window import WindowError, ensure_frontmost, ensure_running, get_bounds
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
class GestureError(RuntimeError):
|
|
23
|
+
"""Raised when a composed gesture cannot complete."""
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def home() -> None:
|
|
27
|
+
"""Swipe up from near the bottom edge: go to the home screen.
|
|
28
|
+
|
|
29
|
+
Starts at 0.90 height: the bottom ~7% of the mirroring window is
|
|
30
|
+
macOS window chrome (rounded corners / resize area), not the video
|
|
31
|
+
surface — events there never reach the phone. 0.90 is the lowest
|
|
32
|
+
point that reliably lands on the iOS home-indicator zone.
|
|
33
|
+
"""
|
|
34
|
+
inp.swipe(0.5, 0.90, 0.5, 0.10, duration_ms=300)
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def app_switcher() -> None:
|
|
38
|
+
"""Swipe up and hold: open the app switcher."""
|
|
39
|
+
b = get_bounds()
|
|
40
|
+
from Quartz import (
|
|
41
|
+
CGEventCreateMouseEvent, CGEventPost, CGEventSourceCreate,
|
|
42
|
+
kCGEventLeftMouseDown, kCGEventLeftMouseUp, kCGEventLeftMouseDragged,
|
|
43
|
+
kCGEventSourceStateHIDSystemState, kCGHIDEventTap, kCGMouseButtonLeft,
|
|
44
|
+
)
|
|
45
|
+
import time
|
|
46
|
+
|
|
47
|
+
x0, y0 = b.denormalize(0.5, 0.90)
|
|
48
|
+
x1, y1 = b.denormalize(0.5, 0.45)
|
|
49
|
+
src = CGEventSourceCreate(kCGEventSourceStateHIDSystemState)
|
|
50
|
+
|
|
51
|
+
def ev(kind, x, y):
|
|
52
|
+
CGEventPost(kCGHIDEventTap,
|
|
53
|
+
CGEventCreateMouseEvent(src, kind, (x, y), kCGMouseButtonLeft))
|
|
54
|
+
|
|
55
|
+
ev(kCGEventLeftMouseDown, x0, y0)
|
|
56
|
+
time.sleep(0.02)
|
|
57
|
+
# Eased drag to mid-screen.
|
|
58
|
+
steps = 15
|
|
59
|
+
for i in range(1, steps + 1):
|
|
60
|
+
t = i / steps
|
|
61
|
+
e = t * t * (3 - 2 * t) # smoothstep
|
|
62
|
+
ev(kCGEventLeftMouseDragged, x0 + (x1 - x0) * e, y0 + (y1 - y0) * e)
|
|
63
|
+
time.sleep(0.016)
|
|
64
|
+
time.sleep(0.55) # hold to trigger the switcher
|
|
65
|
+
ev(kCGEventLeftMouseUp, x1, y1)
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
# Wheel pixels per window point of list movement, measured on iPhone Mirroring
|
|
69
|
+
# (Settings list, 524 pt window: between 1.1 and 1.6 px/pt across runs).
|
|
70
|
+
_SCROLL_PX_PER_PT = 1.3
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
def scroll_down(distance: float = 0.5) -> None:
|
|
74
|
+
"""Reveal content further down a list by about `distance` window heights.
|
|
75
|
+
|
|
76
|
+
Uses trackpad-style scroll events; a vertical mouse drag does not scroll
|
|
77
|
+
lists in iPhone Mirroring (F16). Swipes stay for gestures such as paging.
|
|
78
|
+
"""
|
|
79
|
+
b = get_bounds()
|
|
80
|
+
inp.scroll_trackpad(-distance * b.height * _SCROLL_PX_PER_PT, bounds=b)
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
def scroll_up(distance: float = 0.5) -> None:
|
|
84
|
+
"""Reveal content further up a list by about `distance` window heights."""
|
|
85
|
+
b = get_bounds()
|
|
86
|
+
inp.scroll_trackpad(distance * b.height * _SCROLL_PX_PER_PT, bounds=b)
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
def page_left() -> None:
|
|
90
|
+
"""Swipe right-to-left: go to the next home-screen page."""
|
|
91
|
+
inp.swipe(0.8, 0.5, 0.2, 0.5, duration_ms=280)
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
def page_right() -> None:
|
|
95
|
+
"""Swipe left-to-right: go to the previous home-screen page."""
|
|
96
|
+
inp.swipe(0.2, 0.5, 0.8, 0.5, duration_ms=280)
|
|
97
|
+
|
|
98
|
+
|
|
99
|
+
def pull_down_search() -> None:
|
|
100
|
+
"""Swipe down from mid-screen (DEPRECATED — never use for Spotlight).
|
|
101
|
+
|
|
102
|
+
F13: iOS sometimes reads this swipe as an icon long-press-drag, which
|
|
103
|
+
drops the home screen into edit (jiggle) mode — a stray tap on a "−"
|
|
104
|
+
badge there offers to DELETE apps. open_spotlight() replaces it.
|
|
105
|
+
Kept only as a raw gesture primitive; nothing in imctl calls it.
|
|
106
|
+
"""
|
|
107
|
+
inp.swipe(0.5, 0.25, 0.5, 0.75, duration_ms=280)
|
|
108
|
+
|
|
109
|
+
|
|
110
|
+
# --- iPhone Mirroring menu commands -----------------------------------------
|
|
111
|
+
#
|
|
112
|
+
# The View menu of iPhone Mirroring exposes phone-level actions (Home
|
|
113
|
+
# Screen, App Switcher, Spotlight) as real menu commands, which iOS
|
|
114
|
+
# cannot misread as touch gestures. We trigger them by keyboard shortcut
|
|
115
|
+
# when one is readable — language-independent, because the shortcut
|
|
116
|
+
# character (AXMenuItemCmdChar), not the localized menu title, drives
|
|
117
|
+
# it — and fall back to clicking the English menu item.
|
|
118
|
+
|
|
119
|
+
# Static AppleScript only (invariant 1): script text is fixed; the menu
|
|
120
|
+
# item name travels as an osascript argument, never interpolated.
|
|
121
|
+
_MENU_SHORTCUT_SCRIPT = '''
|
|
122
|
+
on run(argv)
|
|
123
|
+
tell application "System Events"
|
|
124
|
+
tell process "iPhone Mirroring"
|
|
125
|
+
set cc to ""
|
|
126
|
+
set cm to ""
|
|
127
|
+
try
|
|
128
|
+
set cc to (value of attribute "AXMenuItemCmdChar" of menu item (item 1 of argv) of menu 1 of menu bar item "View" of menu bar 1) as text
|
|
129
|
+
end try
|
|
130
|
+
try
|
|
131
|
+
set cm to (value of attribute "AXMenuItemCmdModifiers" of menu item (item 1 of argv) of menu 1 of menu bar item "View" of menu bar 1) as text
|
|
132
|
+
end try
|
|
133
|
+
return cc & "," & cm
|
|
134
|
+
end tell
|
|
135
|
+
end tell
|
|
136
|
+
end run
|
|
137
|
+
'''
|
|
138
|
+
|
|
139
|
+
_CLICK_MENU_ITEM_SCRIPT = '''
|
|
140
|
+
on run(argv)
|
|
141
|
+
tell application "System Events"
|
|
142
|
+
tell process "iPhone Mirroring"
|
|
143
|
+
click menu item (item 1 of argv) of menu 1 of menu bar item "View" of menu bar 1
|
|
144
|
+
end tell
|
|
145
|
+
end tell
|
|
146
|
+
end run
|
|
147
|
+
'''
|
|
148
|
+
|
|
149
|
+
|
|
150
|
+
def _run_osascript(script: str, args: list[str] | None = None) -> str:
|
|
151
|
+
"""Run a static AppleScript; runtime values go through argv only."""
|
|
152
|
+
cmd = ["osascript", "-e", script]
|
|
153
|
+
if args:
|
|
154
|
+
cmd += ["--"] + args
|
|
155
|
+
result = subprocess.run(cmd, capture_output=True, text=True, timeout=10)
|
|
156
|
+
if result.returncode != 0:
|
|
157
|
+
raise GestureError(f"osascript failed: {result.stderr.strip()}")
|
|
158
|
+
return result.stdout.strip()
|
|
159
|
+
|
|
160
|
+
|
|
161
|
+
def _view_menu_shortcut(item: str) -> tuple[str, int] | None:
|
|
162
|
+
"""Read a View menu item's shortcut — read-only, never clicks.
|
|
163
|
+
|
|
164
|
+
Returns (cmdChar, cmdModifiers), or None when unreadable.
|
|
165
|
+
AXMenuItemCmdModifiers uses the Carbon menu-modifier bits: 0 means
|
|
166
|
+
the Command key alone (Spotlight is Cmd+3 here), 1 adds Shift,
|
|
167
|
+
8 means no key equivalent at all.
|
|
168
|
+
"""
|
|
169
|
+
try:
|
|
170
|
+
raw = _run_osascript(_MENU_SHORTCUT_SCRIPT, [item])
|
|
171
|
+
except (GestureError, OSError, subprocess.TimeoutExpired):
|
|
172
|
+
return None
|
|
173
|
+
char, sep, mods = raw.partition(",")
|
|
174
|
+
if not sep:
|
|
175
|
+
return None
|
|
176
|
+
try:
|
|
177
|
+
return char, int(mods.strip())
|
|
178
|
+
except ValueError: # "missing value" / empty — no usable shortcut
|
|
179
|
+
return None
|
|
180
|
+
|
|
181
|
+
|
|
182
|
+
def _run_view_menu_command(item: str) -> bool:
|
|
183
|
+
"""Trigger a View menu command of iPhone Mirroring.
|
|
184
|
+
|
|
185
|
+
Primary: the item's shortcut as a real Command chord (works on any
|
|
186
|
+
UI language). Fallback: clicking the English menu item. Returns
|
|
187
|
+
False when neither path works (app not running, localized menus…).
|
|
188
|
+
"""
|
|
189
|
+
shortcut = _view_menu_shortcut(item)
|
|
190
|
+
if shortcut is not None:
|
|
191
|
+
char, mods = shortcut
|
|
192
|
+
keycode = inp.keycode_for_char(char) if mods == 0 else None
|
|
193
|
+
if keycode is not None:
|
|
194
|
+
try:
|
|
195
|
+
ensure_frontmost()
|
|
196
|
+
inp._cmd_chord(keycode)
|
|
197
|
+
return True
|
|
198
|
+
except (inp.InputError, WindowError):
|
|
199
|
+
pass # fall through to clicking the menu item
|
|
200
|
+
try:
|
|
201
|
+
ensure_frontmost()
|
|
202
|
+
_run_osascript(_CLICK_MENU_ITEM_SCRIPT, [item])
|
|
203
|
+
return True
|
|
204
|
+
except (GestureError, OSError, subprocess.TimeoutExpired, WindowError):
|
|
205
|
+
return False
|
|
206
|
+
|
|
207
|
+
|
|
208
|
+
def open_spotlight() -> bool:
|
|
209
|
+
"""Open the phone's Spotlight search (View ▸ Spotlight).
|
|
210
|
+
|
|
211
|
+
Never a swipe: the old pull-down could be misread by iOS as a
|
|
212
|
+
long-press-drag that triggers home-screen edit mode (F13).
|
|
213
|
+
"""
|
|
214
|
+
return _run_view_menu_command("Spotlight")
|
|
215
|
+
|
|
216
|
+
|
|
217
|
+
def choose_app_hit(hits: list, name: str) -> vision.OCRHit | None:
|
|
218
|
+
"""Pick the Spotlight result row for ``name`` from OCR hits.
|
|
219
|
+
|
|
220
|
+
iOS 26 draws the Spotlight search field at the BOTTOM of the screen
|
|
221
|
+
(ny ≈ 0.95) and echoes the typed query inside it, so a plain text
|
|
222
|
+
match finds the field itself. A result row must:
|
|
223
|
+
- equal ``name`` case-insensitively after stripping whitespace, and
|
|
224
|
+
- lie above the bottom search-field zone (ny < 0.88).
|
|
225
|
+
When several rows match, the topmost (smallest ny) wins. Returns
|
|
226
|
+
None when nothing qualifies.
|
|
227
|
+
"""
|
|
228
|
+
want = name.strip().lower()
|
|
229
|
+
best = None
|
|
230
|
+
for hit in hits:
|
|
231
|
+
if hit.text.strip().lower() != want:
|
|
232
|
+
continue
|
|
233
|
+
if hit.ny >= 0.88:
|
|
234
|
+
continue # the search field echoing the query
|
|
235
|
+
if best is None or hit.ny < best.ny:
|
|
236
|
+
best = hit
|
|
237
|
+
return best
|
|
238
|
+
|
|
239
|
+
|
|
240
|
+
def open_app(name: str, *, spotlight_open: bool = False) -> bool:
|
|
241
|
+
"""Open an app by name: Spotlight → type → OCR → tap the result row.
|
|
242
|
+
|
|
243
|
+
``spotlight_open`` lets a caller that already ran open_spotlight()
|
|
244
|
+
itself (to tell "spotlight unavailable" apart from "app not found")
|
|
245
|
+
skip the internal call. Returns True when a row matching ``name``
|
|
246
|
+
was tapped; False when Spotlight could not be opened or no row
|
|
247
|
+
matched (after returning to the home screen).
|
|
248
|
+
|
|
249
|
+
The top hit is never opened with Return — it may belong to a
|
|
250
|
+
different app than the requested one.
|
|
251
|
+
"""
|
|
252
|
+
if not spotlight_open and not open_spotlight():
|
|
253
|
+
return False
|
|
254
|
+
time.sleep(1.0)
|
|
255
|
+
inp.type_text(name)
|
|
256
|
+
time.sleep(1.5) # wait for Spotlight results
|
|
257
|
+
|
|
258
|
+
hit = choose_app_hit(vision.read_screen(), name)
|
|
259
|
+
if hit is None:
|
|
260
|
+
# Leave the phone tidy: back to the home screen (View ▸ Home Screen).
|
|
261
|
+
_run_view_menu_command("Home Screen")
|
|
262
|
+
return False
|
|
263
|
+
inp.tap(hit.nx, hit.ny)
|
|
264
|
+
time.sleep(1.0)
|
|
265
|
+
return True
|
|
266
|
+
|
|
267
|
+
|
|
268
|
+
def read_text() -> list:
|
|
269
|
+
"""OCR the current screen; returns vision.OCRHit list."""
|
|
270
|
+
return vision.read_screen()
|
|
271
|
+
|
|
272
|
+
|
|
273
|
+
def status() -> dict:
|
|
274
|
+
"""Return a status dict for the mirroring session.
|
|
275
|
+
|
|
276
|
+
Keys: running; and when running: window {x,y,w,h} (AX bounds), window_id, onscreen, frontmost,
|
|
277
|
+
live (True/False/null — is the phone stream up), overlay (text shown over the stream when not
|
|
278
|
+
live, e.g. a paused/connecting notice), paused (True/False, or null when the state is unknown).
|
|
279
|
+
"""
|
|
280
|
+
from .window import (
|
|
281
|
+
get_overlay, get_window_info, is_frontmost, is_paused, is_running,
|
|
282
|
+
)
|
|
283
|
+
|
|
284
|
+
running = is_running()
|
|
285
|
+
info = {"running": running}
|
|
286
|
+
if running:
|
|
287
|
+
try:
|
|
288
|
+
b = get_bounds()
|
|
289
|
+
info["window"] = {"x": b.x, "y": b.y, "w": b.width, "h": b.height}
|
|
290
|
+
except Exception as exc:
|
|
291
|
+
info["window_error"] = str(exc)
|
|
292
|
+
wi = get_window_info()
|
|
293
|
+
if wi:
|
|
294
|
+
info["window_id"] = wi["id"]
|
|
295
|
+
info["onscreen"] = wi["onscreen"]
|
|
296
|
+
info["frontmost"] = is_frontmost()
|
|
297
|
+
overlay = get_overlay()
|
|
298
|
+
info["live"] = overlay["live"]
|
|
299
|
+
info["overlay"] = overlay["overlay"]
|
|
300
|
+
info["paused"] = is_paused(overlay)
|
|
301
|
+
return info
|
|
302
|
+
|
|
303
|
+
|
|
304
|
+
def resume() -> bool:
|
|
305
|
+
"""Resume a paused mirroring session (clicks Resume). Returns True when not paused afterwards."""
|
|
306
|
+
from .window import resume as _resume
|
|
307
|
+
|
|
308
|
+
return _resume()
|
|
309
|
+
|
|
310
|
+
|
|
311
|
+
def launch() -> None:
|
|
312
|
+
"""Ensure iPhone Mirroring is running, frontmost, and not paused."""
|
|
313
|
+
ensure_running()
|
|
314
|
+
from .window import ensure_frontmost, resume as _resume
|
|
315
|
+
|
|
316
|
+
ensure_frontmost()
|
|
317
|
+
_resume()
|
|
@@ -0,0 +1,325 @@
|
|
|
1
|
+
"""CGEvent input engine for iPhone Mirroring.
|
|
2
|
+
|
|
3
|
+
All input is delivered as synthesized CoreGraphics events posted to the
|
|
4
|
+
HID event tap. The iPhone Mirroring app translates these into touch
|
|
5
|
+
events on the phone.
|
|
6
|
+
|
|
7
|
+
Empirically-validated parameters (see project README for the test
|
|
8
|
+
methodology):
|
|
9
|
+
|
|
10
|
+
- TAP_INTERVAL_S = 0.05 — minimum down/up interval that the mirroring
|
|
11
|
+
gesture recognizer registers reliably. Faster taps are sometimes
|
|
12
|
+
dropped.
|
|
13
|
+
- SWIPE_STEPS = 20 — number of interpolated drag points. A single
|
|
14
|
+
dd/dm/du drag (e.g. via cliclick) is NOT recognized as a swipe by
|
|
15
|
+
iPhone Mirroring; stepped drags are.
|
|
16
|
+
- SWIPE_NUDGE_PX = 3 — an initial small movement right after
|
|
17
|
+
mouse-down. Without it, the recognizer sometimes classifies the
|
|
18
|
+
gesture as an icon long-press-drag instead of a scroll swipe.
|
|
19
|
+
- Ease-in-out curve — quadratic ease matches how a human finger
|
|
20
|
+
decelerates, which keeps the gesture inside the recognizer's
|
|
21
|
+
velocity window.
|
|
22
|
+
"""
|
|
23
|
+
|
|
24
|
+
from __future__ import annotations
|
|
25
|
+
|
|
26
|
+
import time
|
|
27
|
+
|
|
28
|
+
from Quartz import (
|
|
29
|
+
CGEventCreateMouseEvent,
|
|
30
|
+
CGEventPost,
|
|
31
|
+
CGEventSetIntegerValueField,
|
|
32
|
+
CGEventSourceCreate,
|
|
33
|
+
kCGEventLeftMouseDown,
|
|
34
|
+
kCGEventLeftMouseUp,
|
|
35
|
+
kCGEventLeftMouseDragged,
|
|
36
|
+
kCGEventSourceStateHIDSystemState,
|
|
37
|
+
kCGHIDEventTap,
|
|
38
|
+
kCGMouseButtonLeft,
|
|
39
|
+
kCGEventFlagMaskCommand,
|
|
40
|
+
CGEventCreateKeyboardEvent,
|
|
41
|
+
CGEventSetFlags,
|
|
42
|
+
)
|
|
43
|
+
|
|
44
|
+
from .window import WindowBounds, ensure_frontmost, get_bounds
|
|
45
|
+
|
|
46
|
+
TAP_INTERVAL_S = 0.05
|
|
47
|
+
LONG_PRESS_S = 0.8
|
|
48
|
+
SWIPE_STEPS = 20
|
|
49
|
+
SWIPE_NUDGE_PX = 3
|
|
50
|
+
SWIPE_DEFAULT_MS = 300
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
class InputError(RuntimeError):
|
|
54
|
+
"""Raised when a synthesized input event cannot be delivered."""
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
def _source():
|
|
58
|
+
return CGEventSourceCreate(kCGEventSourceStateHIDSystemState)
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
def scroll_steps(total_px: float, steps: int = 24) -> list[int]:
|
|
62
|
+
"""Split a scroll distance (wheel pixels) into per-event integer deltas that sum to it."""
|
|
63
|
+
steps = max(4, int(steps))
|
|
64
|
+
target = int(round(total_px))
|
|
65
|
+
out: list[int] = []
|
|
66
|
+
for i in range(1, steps + 1):
|
|
67
|
+
out.append(int(round(target * i / steps)) - sum(out))
|
|
68
|
+
return out
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
def scroll_trackpad(total_px: float, nx: float = 0.5, ny: float = 0.6,
|
|
72
|
+
bounds: WindowBounds | None = None) -> None:
|
|
73
|
+
"""Scroll like a two-finger trackpad swipe: continuous wheel events with phases.
|
|
74
|
+
|
|
75
|
+
iPhone Mirroring turns these into a touch scroll of the list under the cursor
|
|
76
|
+
(F16: a mouse drag scrolls nothing in a list, and a bare wheel event without a
|
|
77
|
+
phase is ignored). Negative total_px moves the content up, revealing what is
|
|
78
|
+
below. The cursor is moved over the mirror first, because scroll events go to
|
|
79
|
+
the window under the cursor.
|
|
80
|
+
"""
|
|
81
|
+
from Quartz import (CGEventCreateScrollWheelEvent, CGEventSetLocation,
|
|
82
|
+
kCGEventMouseMoved, kCGScrollEventUnitPixel,
|
|
83
|
+
kCGScrollWheelEventIsContinuous, kCGScrollWheelEventScrollPhase)
|
|
84
|
+
|
|
85
|
+
ensure_frontmost()
|
|
86
|
+
b = bounds or get_bounds()
|
|
87
|
+
x, y = b.denormalize(nx, ny)
|
|
88
|
+
src = _source()
|
|
89
|
+
_mouse_event(kCGEventMouseMoved, x, y, src)
|
|
90
|
+
time.sleep(0.12)
|
|
91
|
+
deltas = scroll_steps(total_px)
|
|
92
|
+
last = len(deltas) - 1
|
|
93
|
+
for i, d in enumerate(deltas):
|
|
94
|
+
event = CGEventCreateScrollWheelEvent(src, kCGScrollEventUnitPixel, 1, d)
|
|
95
|
+
if event is None:
|
|
96
|
+
raise InputError("CGEventCreateScrollWheelEvent returned None")
|
|
97
|
+
CGEventSetLocation(event, (x, y))
|
|
98
|
+
CGEventSetIntegerValueField(event, kCGScrollWheelEventIsContinuous, 1)
|
|
99
|
+
# NSEvent phases: 1 = began, 2 = changed, 4 = ended
|
|
100
|
+
CGEventSetIntegerValueField(event, kCGScrollWheelEventScrollPhase,
|
|
101
|
+
1 if i == 0 else (4 if i == last else 2))
|
|
102
|
+
CGEventPost(kCGHIDEventTap, event)
|
|
103
|
+
time.sleep(0.016)
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
def _mouse_event(kind: int, x: float, y: float, source) -> None:
|
|
107
|
+
event = CGEventCreateMouseEvent(
|
|
108
|
+
source, kind, (x, y), kCGMouseButtonLeft
|
|
109
|
+
)
|
|
110
|
+
if event is None:
|
|
111
|
+
raise InputError(f"CGEventCreateMouseEvent returned None for {kind}")
|
|
112
|
+
CGEventPost(kCGHIDEventTap, event)
|
|
113
|
+
|
|
114
|
+
|
|
115
|
+
def _key_event(keycode: int, down: bool, source) -> None:
|
|
116
|
+
event = CGEventCreateKeyboardEvent(source, keycode, down)
|
|
117
|
+
if event is None:
|
|
118
|
+
raise InputError(f"CGEventCreateKeyboardEvent returned None for {keycode}")
|
|
119
|
+
CGEventPost(kCGHIDEventTap, event)
|
|
120
|
+
|
|
121
|
+
|
|
122
|
+
# --- Pointer primitives ---------------------------------------------------
|
|
123
|
+
|
|
124
|
+
|
|
125
|
+
def tap(nx: float = 0.5, ny: float = 0.5, bounds: WindowBounds | None = None) -> None:
|
|
126
|
+
"""Tap at normalized coordinates (0-1) within the mirroring window."""
|
|
127
|
+
ensure_frontmost()
|
|
128
|
+
b = bounds or get_bounds()
|
|
129
|
+
x, y = b.denormalize(nx, ny)
|
|
130
|
+
src = _source()
|
|
131
|
+
_mouse_event(kCGEventLeftMouseDown, x, y, src)
|
|
132
|
+
time.sleep(TAP_INTERVAL_S)
|
|
133
|
+
_mouse_event(kCGEventLeftMouseUp, x, y, src)
|
|
134
|
+
|
|
135
|
+
|
|
136
|
+
def long_press(nx: float = 0.5, ny: float = 0.5, duration_s: float = LONG_PRESS_S,
|
|
137
|
+
bounds: WindowBounds | None = None) -> None:
|
|
138
|
+
"""Press and hold at normalized coordinates."""
|
|
139
|
+
ensure_frontmost()
|
|
140
|
+
b = bounds or get_bounds()
|
|
141
|
+
x, y = b.denormalize(nx, ny)
|
|
142
|
+
src = _source()
|
|
143
|
+
_mouse_event(kCGEventLeftMouseDown, x, y, src)
|
|
144
|
+
time.sleep(duration_s)
|
|
145
|
+
_mouse_event(kCGEventLeftMouseUp, x, y, src)
|
|
146
|
+
|
|
147
|
+
|
|
148
|
+
def _ease_in_out(t: float) -> float:
|
|
149
|
+
"""Quadratic ease-in-out: slow start, fast middle, slow end."""
|
|
150
|
+
if t < 0.5:
|
|
151
|
+
return 2.0 * t * t
|
|
152
|
+
return 1.0 - ((-2.0 * t + 2.0) ** 2) / 2.0
|
|
153
|
+
|
|
154
|
+
|
|
155
|
+
def swipe(from_x: float, from_y: float, to_x: float, to_y: float,
|
|
156
|
+
duration_ms: int = SWIPE_DEFAULT_MS,
|
|
157
|
+
bounds: WindowBounds | None = None) -> None:
|
|
158
|
+
"""Swipe between two normalized points with eased interpolation.
|
|
159
|
+
|
|
160
|
+
The gesture is: mouse-down, 3px nudge, 20 eased drag steps,
|
|
161
|
+
mouse-up. This is the shape iPhone Mirroring's recognizer accepts.
|
|
162
|
+
"""
|
|
163
|
+
ensure_frontmost()
|
|
164
|
+
b = bounds or get_bounds()
|
|
165
|
+
x0, y0 = b.denormalize(from_x, from_y)
|
|
166
|
+
x1, y1 = b.denormalize(to_x, to_y)
|
|
167
|
+
|
|
168
|
+
src = _source()
|
|
169
|
+
step_delay = (duration_ms / 1000.0) / SWIPE_STEPS
|
|
170
|
+
|
|
171
|
+
_mouse_event(kCGEventLeftMouseDown, x0, y0, src)
|
|
172
|
+
time.sleep(0.02)
|
|
173
|
+
|
|
174
|
+
# Initial nudge: disambiguates swipe from long-press-drag.
|
|
175
|
+
dx = 1 if x1 >= x0 else -1
|
|
176
|
+
dy = 1 if y1 >= y0 else -1
|
|
177
|
+
_mouse_event(kCGEventLeftMouseDragged, x0 + dx * SWIPE_NUDGE_PX,
|
|
178
|
+
y0 + dy * SWIPE_NUDGE_PX, src)
|
|
179
|
+
time.sleep(0.01)
|
|
180
|
+
|
|
181
|
+
for i in range(1, SWIPE_STEPS + 1):
|
|
182
|
+
t = i / SWIPE_STEPS
|
|
183
|
+
e = _ease_in_out(t)
|
|
184
|
+
cx = x0 + (x1 - x0) * e
|
|
185
|
+
cy = y0 + (y1 - y0) * e
|
|
186
|
+
_mouse_event(kCGEventLeftMouseDragged, cx, cy, src)
|
|
187
|
+
time.sleep(step_delay)
|
|
188
|
+
|
|
189
|
+
_mouse_event(kCGEventLeftMouseUp, x1, y1, src)
|
|
190
|
+
|
|
191
|
+
|
|
192
|
+
def scroll(dy_pixels: int, nx: float = 0.5, ny: float = 0.5,
|
|
193
|
+
bounds: WindowBounds | None = None) -> None:
|
|
194
|
+
"""Scroll vertically at a position. Positive dy scrolls up."""
|
|
195
|
+
from Quartz import CGEventCreateScrollWheelEvent
|
|
196
|
+
|
|
197
|
+
ensure_frontmost()
|
|
198
|
+
b = bounds or get_bounds()
|
|
199
|
+
x, y = b.denormalize(nx, ny)
|
|
200
|
+
src = _source()
|
|
201
|
+
# Axis 1 = vertical; pixel units; negative = scroll down (content up).
|
|
202
|
+
event = CGEventCreateScrollWheelEvent(
|
|
203
|
+
src, kCGScrollEventUnitPixel, 1, dy_pixels
|
|
204
|
+
)
|
|
205
|
+
if event is None:
|
|
206
|
+
raise InputError("CGEventCreateScrollWheelEvent returned None")
|
|
207
|
+
CGEventPost(kCGHIDEventTap, event)
|
|
208
|
+
|
|
209
|
+
|
|
210
|
+
# --- Keyboard primitives ----------------------------------------------------
|
|
211
|
+
|
|
212
|
+
# macOS virtual keycodes used by this module.
|
|
213
|
+
_VK_RETURN = 36
|
|
214
|
+
_VK_DELETE = 51
|
|
215
|
+
_VK_ARROW_KEYS = {"up": 126, "down": 125, "left": 123, "right": 124}
|
|
216
|
+
_VK_V = 9
|
|
217
|
+
_VK_A = 0
|
|
218
|
+
_VK_COMMAND = 55
|
|
219
|
+
|
|
220
|
+
# ANSI keycodes for digits and letters — the characters a menu-item
|
|
221
|
+
# shortcut can use as its command char (AXMenuItemCmdChar). Translates
|
|
222
|
+
# a shortcut such as Cmd+3 into a keycode for _cmd_chord().
|
|
223
|
+
_ANSI_KEYCODES = {
|
|
224
|
+
"0": 29, "1": 18, "2": 19, "3": 20, "4": 21, "5": 23, "6": 22,
|
|
225
|
+
"7": 26, "8": 28, "9": 25,
|
|
226
|
+
"a": 0, "b": 11, "c": 8, "d": 2, "e": 14, "f": 3, "g": 5, "h": 4,
|
|
227
|
+
"i": 34, "j": 38, "k": 40, "l": 37, "m": 46, "n": 45, "o": 31,
|
|
228
|
+
"p": 35, "q": 12, "r": 15, "s": 1, "t": 17, "u": 32, "v": 9,
|
|
229
|
+
"w": 13, "x": 7, "y": 16, "z": 6,
|
|
230
|
+
}
|
|
231
|
+
|
|
232
|
+
|
|
233
|
+
def keycode_for_char(char: str) -> int | None:
|
|
234
|
+
"""ANSI virtual keycode for a single digit/letter, else None."""
|
|
235
|
+
if len(char) != 1:
|
|
236
|
+
return None
|
|
237
|
+
return _ANSI_KEYCODES.get(char.lower())
|
|
238
|
+
|
|
239
|
+
|
|
240
|
+
def _cmd_chord(keycode: int) -> None:
|
|
241
|
+
"""Send a real Command chord: ⌘ down → key down → key up → ⌘ up.
|
|
242
|
+
|
|
243
|
+
iPhone Mirroring forwards the *state* of the physical modifier
|
|
244
|
+
keys, not the per-event flag bits: a target-key event that merely
|
|
245
|
+
carries kCGEventFlagMaskCommand arrives on the phone as an
|
|
246
|
+
unmodified keystroke (F14 — a "Cmd+V" paste typed a literal "v").
|
|
247
|
+
The chord therefore presses the Command key itself, keeps the
|
|
248
|
+
flag set on every event, and releases Command last. ~30ms between
|
|
249
|
+
steps, all events from one shared source.
|
|
250
|
+
"""
|
|
251
|
+
ensure_frontmost()
|
|
252
|
+
src = _source()
|
|
253
|
+
|
|
254
|
+
def post(code: int, down: bool, flags: int) -> None:
|
|
255
|
+
event = CGEventCreateKeyboardEvent(src, code, down)
|
|
256
|
+
if event is None:
|
|
257
|
+
raise InputError(f"CGEventCreateKeyboardEvent returned None for {code}")
|
|
258
|
+
CGEventSetFlags(event, flags)
|
|
259
|
+
CGEventPost(kCGHIDEventTap, event)
|
|
260
|
+
|
|
261
|
+
post(_VK_COMMAND, True, kCGEventFlagMaskCommand)
|
|
262
|
+
time.sleep(0.03)
|
|
263
|
+
post(keycode, True, kCGEventFlagMaskCommand)
|
|
264
|
+
time.sleep(0.03)
|
|
265
|
+
post(keycode, False, kCGEventFlagMaskCommand)
|
|
266
|
+
time.sleep(0.03)
|
|
267
|
+
post(_VK_COMMAND, False, 0)
|
|
268
|
+
|
|
269
|
+
|
|
270
|
+
def press_key(key: str) -> None:
|
|
271
|
+
"""Press a single key: 'return', 'delete', 'up', 'down', 'left', 'right'."""
|
|
272
|
+
ensure_frontmost()
|
|
273
|
+
keymap = {"return": _VK_RETURN, "delete": _VK_DELETE, **_VK_ARROW_KEYS}
|
|
274
|
+
if key not in keymap:
|
|
275
|
+
raise InputError(f"unsupported key: {key!r} (supported: {sorted(keymap)})")
|
|
276
|
+
src = _source()
|
|
277
|
+
_key_event(keymap[key], True, src)
|
|
278
|
+
time.sleep(0.02)
|
|
279
|
+
_key_event(keymap[key], False, src)
|
|
280
|
+
|
|
281
|
+
|
|
282
|
+
def type_text(text: str) -> None:
|
|
283
|
+
"""Type text via clipboard paste (IME-safe).
|
|
284
|
+
|
|
285
|
+
Direct CGEvent keystroke synthesis breaks under CJK IMEs and is
|
|
286
|
+
slow for long strings. Instead we:
|
|
287
|
+
1. save the user's pasteboard,
|
|
288
|
+
2. write the text,
|
|
289
|
+
3. Cmd+V into the focused field,
|
|
290
|
+
4. restore the pasteboard.
|
|
291
|
+
|
|
292
|
+
Requires the calling terminal to have Accessibility permission
|
|
293
|
+
(same as every other imctl input).
|
|
294
|
+
"""
|
|
295
|
+
from AppKit import NSPasteboard
|
|
296
|
+
|
|
297
|
+
ensure_frontmost()
|
|
298
|
+
pb = NSPasteboard.generalPasteboard()
|
|
299
|
+
saved = pb.dataForType_("public.utf8-plain-text")
|
|
300
|
+
saved_change = pb.changeCount()
|
|
301
|
+
|
|
302
|
+
try:
|
|
303
|
+
pb.clearContents()
|
|
304
|
+
pb.setString_forType_(text, "public.utf8-plain-text")
|
|
305
|
+
time.sleep(0.05)
|
|
306
|
+
|
|
307
|
+
_cmd_chord(_VK_V) # real ⌘ chord — flags alone reach the phone as "v" (F14)
|
|
308
|
+
time.sleep(0.15) # let the paste land before restoring
|
|
309
|
+
finally:
|
|
310
|
+
# Restore the user's clipboard only if nothing else changed it.
|
|
311
|
+
if pb.changeCount() == saved_change + 1:
|
|
312
|
+
pb.clearContents()
|
|
313
|
+
if saved is not None:
|
|
314
|
+
pb.setData_forType_(saved, "public.utf8-plain-text")
|
|
315
|
+
|
|
316
|
+
|
|
317
|
+
def clear_text() -> None:
|
|
318
|
+
"""Select-all and delete in the focused field."""
|
|
319
|
+
ensure_frontmost()
|
|
320
|
+
_cmd_chord(_VK_A) # Cmd+A — real chord, same reason as type_text
|
|
321
|
+
time.sleep(0.05)
|
|
322
|
+
src = _source()
|
|
323
|
+
_key_event(_VK_DELETE, True, src)
|
|
324
|
+
time.sleep(0.02)
|
|
325
|
+
_key_event(_VK_DELETE, False, src)
|