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.
@@ -0,0 +1,142 @@
1
+ # imctl — Control your iPhone from macOS
2
+
3
+ > Ships inside [noracu](https://github.com/sgInnora/noracu) (`imctl/`) as the driver behind its
4
+ > `phone_*` MCP tools; it also works standalone from this directory.
5
+
6
+ `imctl` drives the **iPhone Mirroring** app on macOS (Sequoia and later)
7
+ from the command line: tap, swipe, type, OCR the screen, and open apps —
8
+ all locally, no network, no API keys.
9
+
10
+ ```
11
+ $ imctl status
12
+ $ imctl tap 0.5 0.5
13
+ $ imctl home
14
+ $ imctl type "hello"
15
+ $ imctl ocr
16
+ (0.50,0.06) 'Settings'
17
+ (0.18,0.31) 'FaceTime'
18
+ ...
19
+ $ imctl open Photos
20
+ ```
21
+
22
+ ## How it works
23
+
24
+ ```
25
+ ┌────────────┐ CGEvent (HID tap) ┌───────────────────┐
26
+ │ imctl │ ────────────────────▶ │ iPhone Mirroring │
27
+ │ │ │ (video stream) │
28
+ │ Vision ◀──┼─── screencapture ─────│ │
29
+ │ OCR │ └─────────┬─────────┘
30
+ └────────────┘ │ Continuity
31
+ ▼
32
+ ┌─────────┐
33
+ │ iPhone │
34
+ └─────────┘
35
+ ```
36
+
37
+ - **Input** — synthesized CoreGraphics mouse/keyboard events posted to
38
+ the HID event tap. iPhone Mirroring translates them into touches.
39
+ - **Vision** — the macOS Vision framework runs OCR locally on a
40
+ window screenshot (captured by CGWindow id, so it is the window's own
41
+ pixels even when covered) and returns text with normalized coordinates.
42
+ - **Verification** — every gesture can be followed by a downsampled
43
+ pixel-hash comparison to confirm the screen actually changed.
44
+
45
+ ## Why these specific parameters
46
+
47
+ Every constant in `input.py` is backed by empirical testing against
48
+ the mirroring gesture recognizer:
49
+
50
+ | Parameter | Value | Why |
51
+ |-----------|-------|-----|
52
+ | tap down-up interval | 50 ms | shorter intervals are sometimes dropped |
53
+ | swipe steps | 20 | single-shot drags are **not** recognized as swipes |
54
+ | initial nudge | 3 px | disambiguates swipe from icon long-press-drag |
55
+ | swipe curve | quadratic ease-in-out | stays inside the recognizer's velocity window |
56
+ | home gesture start | 0.95 height | higher start points are treated as in-app scrolls |
57
+ | text input | clipboard + Cmd+V | direct keystroke synthesis breaks under CJK IMEs |
58
+
59
+ ## Requirements
60
+
61
+ - macOS 15 (Sequoia) or later with **iPhone Mirroring** configured
62
+ (iPhone signed into the same Apple Account, Bluetooth + Wi-Fi on)
63
+ - Python 3.10+ with pyobjc: `python3 -m pip install pyobjc-framework-Quartz pyobjc-framework-Vision pyobjc-framework-AppKit`
64
+ (Apple's `/usr/bin/python3` usually lacks it; Homebrew's `python3` is the common working choice)
65
+ - **Accessibility** and **Screen Recording** permissions granted to
66
+ your terminal app (System Settings → Privacy & Security)
67
+
68
+ ## Install
69
+
70
+ ```bash
71
+ cd imctl
72
+ pip install -e . # or: pip install -e ".[pyobjc]" if pyobjc missing
73
+ imctl status
74
+ ```
75
+
76
+ ## Commands
77
+
78
+ | Command | Description |
79
+ |---------|-------------|
80
+ | `status` | session + window info (JSON: running, window, window_id, onscreen, frontmost, live, overlay, paused) |
81
+ | `screenshot [PATH]` | capture the mirroring window to PNG by window id (works when covered) |
82
+ | `resume` | click Resume when the window shows Connection Paused |
83
+ | `launch` | ensure mirroring is running and frontmost |
84
+ | `tap X Y` | tap at normalized coords (0-1) |
85
+ | `longpress X Y [D]` | long-press (default 0.8s) |
86
+ | `swipe FX FY TX TY [--ms]` | eased swipe between two points |
87
+ | `home` | home gesture (bottom-edge swipe up) |
88
+ | `app-switcher` | swipe up and hold |
89
+ | `scroll up/down [D]` | scroll by normalized distance |
90
+ | `page left/right` | home-screen paging |
91
+ | `type TEXT` | type text (clipboard-based, IME-safe) |
92
+ | `key K` | return / delete / up / down / left / right |
93
+ | `ocr` | OCR the screen with coordinates |
94
+ | `find TEXT` | locate text on screen |
95
+ | `open APP` | open an app via Spotlight + OCR + tap |
96
+ | `verify ACTION` | run a gesture and verify the screen changed |
97
+
98
+ ## Python API
99
+
100
+ ```python
101
+ from imctl import gestures, input, vision
102
+
103
+ gestures.launch()
104
+ gestures.home()
105
+
106
+ input.tap(0.5, 0.5)
107
+ input.swipe(0.5, 0.8, 0.5, 0.2)
108
+ input.type_text("hello")
109
+
110
+ hits = vision.read_screen()
111
+ for h in hits:
112
+ print(h.nx, h.ny, h.text)
113
+ ```
114
+
115
+ ## Design notes
116
+
117
+ **Dynamic window tracking.** Window bounds are re-resolved before every
118
+ gesture — the window can move, close, or be re-created between actions.
119
+ A cached position means tapping the wrong screen region.
120
+
121
+ **Observe → act → re-observe.** `verify.verify_action()` implements the
122
+ observe → act → re-observe discipline: an action is only considered
123
+ successful when the screen content actually changed. Dropped events are
124
+ common enough with synthesized input that silent failure is the default
125
+ assumption.
126
+
127
+ **Local-only.** No telemetry, no network calls, no API keys. OCR runs
128
+ through the Vision framework on-device.
129
+
130
+ ## Limitations
131
+
132
+ - The iPhone must stay **locked** and near the Mac — iPhone Mirroring only
133
+ runs while the phone is locked, and unlocking it ends the session. The
134
+ mirror pauses after inactivity; `status` reports `paused` and `resume`
135
+ clicks Resume. iPhone Mirroring is unavailable in the EU (Apple).
136
+ - Drag-and-drop between Mac and iPhone is not supported.
137
+ - Multi-display setups: the window is located by AX query, so it works
138
+ on any display, but coordinates are always screen-global.
139
+
140
+ ## License
141
+
142
+ MIT — see [LICENSE](LICENSE).
@@ -0,0 +1,37 @@
1
+ [build-system]
2
+ requires = ["setuptools>=68"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "imctl"
7
+ version = "0.1.0"
8
+ description = "Control iPhone Mirroring on macOS from the CLI — CGEvent input, Vision OCR, pixel verification"
9
+ readme = "README.md"
10
+ license = { text = "MIT" }
11
+ requires-python = ">=3.10"
12
+ authors = [{ name = "imctl contributors" }]
13
+ keywords = ["iphone", "mirroring", "macos", "automation", "cgevent", "vision-ocr"]
14
+ classifiers = [
15
+ "Development Status :: 4 - Beta",
16
+ "Environment :: MacOS X",
17
+ "Intended Audience :: Developers",
18
+ "License :: OSI Approved :: MIT License",
19
+ "Programming Language :: Python :: 3",
20
+ "Topic :: Utilities",
21
+ ]
22
+ # pyobjc comes with macOS system Python; declare as optional to avoid
23
+ # clobbering a user's pyobjc installation.
24
+ dependencies = []
25
+
26
+ [project.optional-dependencies]
27
+ pyobjc = [
28
+ "pyobjc-framework-Quartz>=10.0",
29
+ "pyobjc-framework-Vision>=10.0",
30
+ "pyobjc-framework-AppKit>=10.0",
31
+ ]
32
+
33
+ [project.scripts]
34
+ imctl = "imctl.cli:main"
35
+
36
+ [tool.setuptools.packages.find]
37
+ where = ["src"]
@@ -0,0 +1,31 @@
1
+ """imctl — Control your iPhone from macOS via iPhone Mirroring.
2
+
3
+ A CLI tool that drives the iPhone Mirroring app on macOS with
4
+ CGEvent input, Vision OCR, and pixel-level verification.
5
+
6
+ Architecture:
7
+
8
+ - window.py — AX-based dynamic window tracking (never assume position)
9
+ - input.py — CGEvent engine: tap / long-press / swipe / scroll / key
10
+ - vision.py — macOS Vision framework OCR with normalized coordinates
11
+ - verify.py — pixel-hash diff to confirm actions took effect
12
+ - gestures.py — composed high-level gestures (home, app switcher, ...)
13
+ - cli.py — argparse CLI entry point
14
+
15
+ Key design decisions (each backed by empirical testing):
16
+
17
+ 1. Swipe uses 20-step ease-in-out interpolation with an initial 3px
18
+ nudge. Single-shot drags are dropped by iPhone Mirroring's gesture
19
+ recognizer; stepped drags are recognized reliably.
20
+ 2. Text input goes through the clipboard (Cmd+V) to bypass IME
21
+ interference, restoring the user's clipboard afterwards.
22
+ 3. Tap uses a 50ms down-up interval (empirically the minimum that
23
+ iPhone Mirroring registers reliably).
24
+ 4. OCR runs locally via the Vision framework — no network, no API
25
+ keys, and returns normalized (0-1) coordinates ready for tap().
26
+ 5. Every window lookup is dynamic: the window may move or close
27
+ between actions, so we re-resolve bounds before each gesture.
28
+ """
29
+
30
+ __version__ = "0.1.0"
31
+ __all__ = ["cli", "window", "input", "vision", "verify", "gestures"]
@@ -0,0 +1,297 @@
1
+ """imctl CLI — control iPhone Mirroring from the command line.
2
+
3
+ Usage:
4
+ imctl status # session + window info
5
+ imctl tap 0.5 0.5 # tap center
6
+ imctl longpress 0.5 0.5 1.0 # long-press center for 1s
7
+ imctl swipe 0.5 0.8 0.5 0.2 # swipe up
8
+ imctl home # home gesture
9
+ imctl app-switcher # app switcher
10
+ imctl scroll down 0.5 # scroll down half a screen
11
+ imctl page left # next home page
12
+ imctl type "hello world" # type text (clipboard-based)
13
+ imctl key return # press a key
14
+ imctl ocr # OCR the screen
15
+ imctl find "Settings" # find text on screen
16
+ imctl open "Photos" # open app via Spotlight
17
+ imctl verify home # run a gesture with verification
18
+ """
19
+
20
+ from __future__ import annotations
21
+
22
+ import argparse
23
+ import json
24
+ import sys
25
+
26
+ from . import gestures, input, verify, vision
27
+ from .window import WindowError, get_overlay
28
+
29
+
30
+ def _require_live() -> int | None:
31
+ """Refuse phone input while the mirror shows an overlay instead of the phone stream.
32
+
33
+ Returns exit code 3 after printing a `mirror_not_live:` line when the mirror is
34
+ verifiably not live; returns None (allow) when live or unknown (fail-open).
35
+ """
36
+ overlay = get_overlay()
37
+ if overlay["live"] is False:
38
+ label = overlay["overlay"] or "overlay shown"
39
+ print(
40
+ f"mirror_not_live: {label} — call phone_launch (or imctl resume) first",
41
+ file=sys.stderr,
42
+ )
43
+ return 3
44
+ return None
45
+
46
+
47
+ def _warn_if_not_live() -> None:
48
+ """Print a heads-up before ocr/find output when the mirror is not live.
49
+
50
+ The captured pixels then show the overlay (paused/connecting notice), not the phone.
51
+ """
52
+ overlay = get_overlay()
53
+ if overlay["live"] is False:
54
+ print(
55
+ f"warning: mirror not live (overlay: {overlay['overlay'] or 'unknown'}) — "
56
+ "the text below comes from the overlay, not the phone; call phone_launch"
57
+ )
58
+
59
+
60
+ def _cmd_status(_args) -> int:
61
+ print(json.dumps(gestures.status(), indent=2))
62
+ return 0
63
+
64
+
65
+ def _cmd_tap(args) -> int:
66
+ guard = _require_live()
67
+ if guard is not None:
68
+ return guard
69
+ input.tap(args.x, args.y)
70
+ print(f"tapped ({args.x}, {args.y})")
71
+ return 0
72
+
73
+
74
+ def _cmd_longpress(args) -> int:
75
+ guard = _require_live()
76
+ if guard is not None:
77
+ return guard
78
+ input.long_press(args.x, args.y, args.duration)
79
+ print(f"long-pressed ({args.x}, {args.y}) for {args.duration}s")
80
+ return 0
81
+
82
+
83
+ def _cmd_swipe(args) -> int:
84
+ guard = _require_live()
85
+ if guard is not None:
86
+ return guard
87
+ input.swipe(args.fx, args.fy, args.tx, args.ty, args.ms)
88
+ print(f"swiped ({args.fx},{args.fy}) -> ({args.tx},{args.ty})")
89
+ return 0
90
+
91
+
92
+ def _cmd_home(_args) -> int:
93
+ gestures.home()
94
+ print("home gesture sent")
95
+ return 0
96
+
97
+
98
+ def _cmd_app_switcher(_args) -> int:
99
+ gestures.app_switcher()
100
+ print("app switcher opened")
101
+ return 0
102
+
103
+
104
+ def _cmd_scroll(args) -> int:
105
+ guard = _require_live()
106
+ if guard is not None:
107
+ return guard
108
+ if args.direction == "down":
109
+ gestures.scroll_down(args.distance)
110
+ else:
111
+ gestures.scroll_up(args.distance)
112
+ print(f"scrolled {args.direction} {args.distance}")
113
+ return 0
114
+
115
+
116
+ def _cmd_page(args) -> int:
117
+ guard = _require_live()
118
+ if guard is not None:
119
+ return guard
120
+ if args.direction == "left":
121
+ gestures.page_left()
122
+ else:
123
+ gestures.page_right()
124
+ print(f"paged {args.direction}")
125
+ return 0
126
+
127
+
128
+ def _cmd_type(args) -> int:
129
+ guard = _require_live()
130
+ if guard is not None:
131
+ return guard
132
+ input.type_text(args.text)
133
+ print(f"typed {args.text!r}")
134
+ return 0
135
+
136
+
137
+ def _cmd_key(args) -> int:
138
+ guard = _require_live()
139
+ if guard is not None:
140
+ return guard
141
+ input.press_key(args.key)
142
+ print(f"pressed {args.key}")
143
+ return 0
144
+
145
+
146
+ def _cmd_ocr(_args) -> int:
147
+ _warn_if_not_live()
148
+ hits = gestures.read_text()
149
+ for h in hits:
150
+ print(h)
151
+ print(f"-- {len(hits)} hits")
152
+ return 0
153
+
154
+
155
+ def _cmd_find(args) -> int:
156
+ _warn_if_not_live()
157
+ hit = vision.find(args.text, exact=args.exact)
158
+ if hit is None:
159
+ print(f"not found: {args.text!r}", file=sys.stderr)
160
+ return 1
161
+ print(hit)
162
+ return 0
163
+
164
+
165
+ def _cmd_open(args) -> int:
166
+ guard = _require_live()
167
+ if guard is not None:
168
+ return guard
169
+ # Open Spotlight here (not inside open_app) so a failure can be
170
+ # reported as its own condition instead of a bogus "app not found".
171
+ if not gestures.open_spotlight():
172
+ print("spotlight unavailable")
173
+ return 1
174
+ ok = gestures.open_app(args.app, spotlight_open=True)
175
+ print(f"opened {args.app!r}" if ok else f"app not found: {args.app!r}")
176
+ return 0 if ok else 1
177
+
178
+
179
+ def _cmd_verify(args) -> int:
180
+ actions = {
181
+ "home": gestures.home,
182
+ "app-switcher": gestures.app_switcher,
183
+ "page-left": gestures.page_left,
184
+ "page-right": gestures.page_right,
185
+ }
186
+ if args.action not in actions:
187
+ print(f"unknown action: {args.action}", file=sys.stderr)
188
+ return 2
189
+ ok = verify.verify_action(actions[args.action])
190
+ print("screen changed: yes" if ok else "screen changed: NO (action may have been dropped)")
191
+ return 0 if ok else 1
192
+
193
+
194
+ def _cmd_launch(_args) -> int:
195
+ gestures.launch()
196
+ print("iPhone Mirroring ready")
197
+ return 0
198
+
199
+
200
+ def _cmd_screenshot(args) -> int:
201
+ path = vision.capture_window(args.path)
202
+ print(path)
203
+ return 0
204
+
205
+
206
+ def _cmd_resume(_args) -> int:
207
+ ok = gestures.resume()
208
+ print("resumed" if ok else "still paused (unlock the iPhone, then retry)")
209
+ return 0 if ok else 1
210
+
211
+
212
+ def build_parser() -> argparse.ArgumentParser:
213
+ p = argparse.ArgumentParser(
214
+ prog="imctl",
215
+ description="Control iPhone Mirroring on macOS from the CLI",
216
+ )
217
+ sub = p.add_subparsers(dest="command", required=True)
218
+
219
+ sub.add_parser("status", help="show session status").set_defaults(func=_cmd_status)
220
+ sp = sub.add_parser("screenshot", help="capture the mirroring window to PNG (by window id, works when covered)")
221
+ sp.add_argument("path", nargs="?", default=None)
222
+ sp.set_defaults(func=_cmd_screenshot)
223
+ sub.add_parser("resume", help="click Resume when the session is paused").set_defaults(func=_cmd_resume)
224
+ sub.add_parser("launch", help="ensure mirroring is running and frontmost").set_defaults(func=_cmd_launch)
225
+
226
+ sp = sub.add_parser("tap", help="tap at normalized coords")
227
+ sp.add_argument("x", type=float)
228
+ sp.add_argument("y", type=float)
229
+ sp.set_defaults(func=_cmd_tap)
230
+
231
+ sp = sub.add_parser("longpress", help="long-press at normalized coords")
232
+ sp.add_argument("x", type=float)
233
+ sp.add_argument("y", type=float)
234
+ sp.add_argument("--duration", type=float, default=0.8)
235
+ sp.set_defaults(func=_cmd_longpress)
236
+
237
+ sp = sub.add_parser("swipe", help="swipe between two normalized points")
238
+ sp.add_argument("fx", type=float)
239
+ sp.add_argument("fy", type=float)
240
+ sp.add_argument("tx", type=float)
241
+ sp.add_argument("ty", type=float)
242
+ sp.add_argument("--ms", type=int, default=300)
243
+ sp.set_defaults(func=_cmd_swipe)
244
+
245
+ sub.add_parser("home", help="home gesture").set_defaults(func=_cmd_home)
246
+ sub.add_parser("app-switcher", help="open app switcher").set_defaults(func=_cmd_app_switcher)
247
+
248
+ sp = sub.add_parser("scroll", help="scroll up/down")
249
+ sp.add_argument("direction", choices=["up", "down"])
250
+ sp.add_argument("distance", type=float, nargs="?", default=0.5)
251
+ sp.set_defaults(func=_cmd_scroll)
252
+
253
+ sp = sub.add_parser("page", help="page left/right on home screen")
254
+ sp.add_argument("direction", choices=["left", "right"])
255
+ sp.set_defaults(func=_cmd_page)
256
+
257
+ sp = sub.add_parser("type", help="type text (clipboard-based, IME-safe)")
258
+ sp.add_argument("text")
259
+ sp.set_defaults(func=_cmd_type)
260
+
261
+ sp = sub.add_parser("key", help="press a key (return/delete/up/down/left/right)")
262
+ sp.add_argument("key")
263
+ sp.set_defaults(func=_cmd_key)
264
+
265
+ sub.add_parser("ocr", help="OCR the screen").set_defaults(func=_cmd_ocr)
266
+
267
+ sp = sub.add_parser("find", help="find text on screen")
268
+ sp.add_argument("text")
269
+ sp.add_argument("--exact", action="store_true")
270
+ sp.set_defaults(func=_cmd_find)
271
+
272
+ sp = sub.add_parser("open", help="open an app via Spotlight")
273
+ sp.add_argument("app")
274
+ sp.set_defaults(func=_cmd_open)
275
+
276
+ sp = sub.add_parser("verify", help="run a gesture and verify the screen changed")
277
+ sp.add_argument("action", choices=["home", "app-switcher", "page-left", "page-right"])
278
+ sp.set_defaults(func=_cmd_verify)
279
+
280
+ return p
281
+
282
+
283
+ def main(argv: list[str] | None = None) -> int:
284
+ parser = build_parser()
285
+ args = parser.parse_args(argv)
286
+ try:
287
+ return args.func(args)
288
+ except WindowError as exc:
289
+ print(f"window error: {exc}", file=sys.stderr)
290
+ return 3
291
+ except input.InputError as exc:
292
+ print(f"input error: {exc}", file=sys.stderr)
293
+ return 4
294
+
295
+
296
+ if __name__ == "__main__":
297
+ sys.exit(main())