Repository navigation
Expand file tree
/
Copy pathcapture.py
More file actions
975 lines (820 loc) · 33.7 KB
/
Copy pathcapture.py
File metadata and controls
975 lines (820 loc) · 33.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
#!/usr/bin/env python3
"""
VisionUX capture.py — keyboard-triggered screen capture for macOS.
Hotkeys (defaults):
ctrl+shift+1 Full-screen screenshot
ctrl+shift+2 App-specific screenshot (prompts for app name)
ctrl+shift+3 Full-screen video toggle (start / stop)
ctrl+shift+4 Region video toggle (prompts for region on first press)
ctrl+shift+q Quit
Override hotkeys via ~/.visionux.json or --config FILE.
Region formats accepted when prompted:
"100,200 800,600" corners A → B
"100,200 400x300" top-left + WxH
"400,400 200x150 center" center point + WxH
"""
from __future__ import annotations
import argparse
import json
import re
import subprocess
import sys
import tempfile
import threading
import time
from collections import deque
from dataclasses import dataclass, field
from datetime import datetime
from pathlib import Path
from typing import Optional
import mss
import mss.tools
import numpy as np
import cv2
from pynput import keyboard
# ---------------------------------------------------------------------------
# Constants / config
# ---------------------------------------------------------------------------
DEFAULT_HOTKEYS: dict[str, str] = {
"screenshot_fullscreen": "<ctrl>+<shift>+1",
"screenshot_app": "<ctrl>+<shift>+2",
"video_fullscreen": "<ctrl>+<shift>+3",
"video_region": "<ctrl>+<shift>+4",
"quit": "<ctrl>+<shift>+q",
}
DEFAULT_OUTPUT_DIR = Path.home() / "Desktop" / "VisionUX_Captures"
DEFAULT_FPS = 15
DEFAULT_BUFFER_SECONDS = 65 # how long the ring buffer holds
DEFAULT_SAVE_SECONDS = 60 # how many seconds to write on trigger
# ---------------------------------------------------------------------------
# Swift snippet — CoreGraphics window enumeration (no pyobjc needed)
# ---------------------------------------------------------------------------
_WINDOW_SWIFT = """\
import CoreGraphics
import Foundation
let opts = CGWindowListOption(arrayLiteral: .optionOnScreenOnly)
guard let wins = CGWindowListCopyWindowInfo(opts, kCGNullWindowID) as? [[String: Any]] else {
exit(0)
}
for w in wins {
guard
let name = w[kCGWindowOwnerName as String] as? String,
let wid = w[kCGWindowNumber as String] as? Int,
let layer = w[kCGWindowLayer as String] as? Int, layer == 0,
let bounds = w[kCGWindowBounds as String] as? [String: Any]
else { continue }
let x = Int(bounds["X"] as? Double ?? 0)
let y = Int(bounds["Y"] as? Double ?? 0)
let ww = Int(bounds["Width"] as? Double ?? 0)
let hh = Int(bounds["Height"] as? Double ?? 0)
print("\\(name)|\\(wid)|\\(x)|\\(y)|\\(ww)|\\(hh)")
}
"""
# ---------------------------------------------------------------------------
# Data types
# ---------------------------------------------------------------------------
class Rect:
"""Screen region in logical pixels."""
__slots__ = ("x", "y", "w", "h")
def __init__(self, x: int, y: int, w: int, h: int) -> None:
self.x, self.y, self.w, self.h = x, y, w, h
def __repr__(self) -> str:
return f"Rect(x={self.x}, y={self.y}, w={self.w}, h={self.h})"
def to_mss_monitor(self) -> dict:
return {"top": self.y, "left": self.x, "width": self.w, "height": self.h}
@dataclass
class BufferSession:
"""Ring-buffer recording session for region capture (Ctrl+Shift+4)."""
thread: threading.Thread
stop_event: threading.Event
frame_buffer: deque # JPEG-encoded bytes per frame
phys_w: int
phys_h: int
fps: int
output_dir: Path
save_seconds: int
def save_and_stop(self) -> None:
"""Stop capture loop, snapshot the buffer, write file in background."""
self.stop_event.set()
self.thread.join(timeout=10)
frames_snapshot = list(self.frame_buffer)
threading.Thread(
target=_write_buffer_to_file,
args=(frames_snapshot, self.fps, self.phys_w, self.phys_h,
self.output_dir, self.save_seconds),
daemon=False,
).start()
@dataclass
class RecordingSession:
thread: threading.Thread
stop_event: threading.Event
output_path: Path
def stop(self) -> None:
self.stop_event.set()
self.thread.join(timeout=10)
print(f"[capture] Recording saved → {self.output_path}")
# ---------------------------------------------------------------------------
# Config
# ---------------------------------------------------------------------------
def load_config(path: Optional[Path] = None) -> dict:
candidates = [path, Path.home() / ".visionux.json"]
for p in candidates:
if p and p.exists():
try:
return json.loads(p.read_text())
except Exception as e:
print(f"[capture] Warning: could not read config {p}: {e}")
return {}
def resolve_hotkeys(config: dict) -> dict[str, str]:
hk = dict(DEFAULT_HOTKEYS)
hk.update(config.get("hotkeys", {}))
return hk
# ---------------------------------------------------------------------------
# Region parsing
# ---------------------------------------------------------------------------
def _flush_stdin() -> None:
"""Discard characters buffered in stdin (e.g. from hotkey key events)."""
try:
import termios
termios.tcflush(sys.stdin.fileno(), termios.TCIFLUSH)
except Exception:
pass
_RE_CORNERS = re.compile(r"^(\d+),(\d+)\s+(\d+),(\d+)$")
_RE_TOPLEFT = re.compile(r"^(\d+),(\d+)\s+(\d+)[xX](\d+)$")
_RE_CENTER = re.compile(r"^(\d+),(\d+)\s+(\d+)[xX](\d+)\s+center$", re.IGNORECASE)
def parse_region(text: str) -> Rect:
"""
Parse a region string into a Rect.
Supported formats:
"x1,y1 x2,y2" two corners
"x,y WxH" top-left + size
"cx,cy WxH center" center + size
"""
text = text.strip()
m = _RE_CENTER.match(text)
if m:
cx, cy, w, h = int(m.group(1)), int(m.group(2)), int(m.group(3)), int(m.group(4))
return Rect(cx - w // 2, cy - h // 2, w, h)
m = _RE_TOPLEFT.match(text)
if m:
x, y, w, h = int(m.group(1)), int(m.group(2)), int(m.group(3)), int(m.group(4))
return Rect(x, y, w, h)
m = _RE_CORNERS.match(text)
if m:
x1, y1, x2, y2 = int(m.group(1)), int(m.group(2)), int(m.group(3)), int(m.group(4))
return Rect(min(x1, x2), min(y1, y2), abs(x2 - x1), abs(y2 - y1))
raise ValueError(
f"Cannot parse region {text!r}.\n"
"Use one of:\n"
" x1,y1 x2,y2 (two corners)\n"
" x,y WxH (top-left + size)\n"
" cx,cy WxH center (center + size)"
)
def parse_gemma_bbox(
json_str: str,
screen_w_phys: int,
screen_h_phys: int,
scale: float,
) -> Rect:
"""
Convert Gemma 4 bounding box JSON into a Rect (logical pixels).
Gemma returns a JSON array: [{"box_2d": [y1, x1, y2, x2], "label": "..."}]
Coordinates are normalized integers 0-1000 on a 1000×1000 grid, Y-first.
screen_w_phys / screen_h_phys should be the physical pixel dimensions of
the screenshot that was sent to Gemma (from mss). scale is the HiDPI
factor so the result is in logical pixels as expected by Rect / _record_loop.
"""
try:
data = json.loads(json_str)
item = data[0] if isinstance(data, list) else data
y1_n, x1_n, y2_n, x2_n = item["box_2d"]
except (json.JSONDecodeError, KeyError, IndexError, TypeError, ValueError) as exc:
raise ValueError(
f"Cannot parse Gemma bbox JSON: {exc}\n"
'Expected format: [{"box_2d": [y1, x1, y2, x2], "label": "..."}]'
) from exc
# Normalised → physical pixels
x1_p = round((x1_n / 1000) * screen_w_phys)
y1_p = round((y1_n / 1000) * screen_h_phys)
x2_p = round((x2_n / 1000) * screen_w_phys)
y2_p = round((y2_n / 1000) * screen_h_phys)
# Physical → logical pixels
x1 = round(x1_p / scale)
y1 = round(y1_p / scale)
x2 = round(x2_p / scale)
y2 = round(y2_p / scale)
w, h = abs(x2 - x1), abs(y2 - y1)
if w == 0 or h == 0:
raise ValueError(
f"Gemma bbox has zero area after conversion "
f"(box_2d={[y1_n,x1_n,y2_n,x2_n]}, screen={screen_w_phys}×{screen_h_phys}, scale={scale})"
)
label = item.get("label", "") if isinstance(item, dict) else ""
if label:
print(f"[capture] Gemma label: '{label}'")
return Rect(min(x1, x2), min(y1, y2), w, h)
def prompt_region(timeout: int = 60, scale: float = 1.0) -> Optional[Rect]:
"""Prompt the user to enter a region string; return None on timeout or cancel."""
print("\n[capture] Enter region (or press Enter to cancel, timeout {}s):".format(timeout))
print(" [1] Two corners: x1,y1 x2,y2 e.g. 100,200 800,600")
print(" [2] Top-left+size: x,y WxH e.g. 100,200 400x300")
print(" [3] Center+size: cx,cy WxH center e.g. 400,400 200x150 center")
print(' [4] Gemma JSON: paste Gemma 4 output e.g. [{"box_2d":[171,75,245,308],"label":"..."}]')
print("> ", end="", flush=True)
result: list[Optional[str]] = [None]
done = threading.Event()
def _read():
try:
time.sleep(0.2) # let hotkey key events drain from stdin
_flush_stdin() # discard any buffered chars
result[0] = sys.stdin.readline().strip()
except Exception:
pass
done.set()
t = threading.Thread(target=_read, daemon=True)
t.start()
done.wait(timeout=timeout)
if not result[0]:
print("[capture] Region prompt cancelled.")
return None
text = result[0]
if text.startswith("[") or text.startswith("{"):
# Gemma JSON path
try:
with mss.mss() as sct:
m = sct.monitors[1]
return parse_gemma_bbox(text, m["width"], m["height"], scale)
except ValueError as e:
print(f"[capture] Gemma bbox error: {e}")
return None
else:
try:
return parse_region(text)
except ValueError as e:
print(f"[capture] {e}")
return None
def prompt_app_name(timeout: int = 30) -> Optional[str]:
"""Prompt for an application name."""
print("\n[capture] Enter application name (or press Enter to cancel): ", end="", flush=True)
result: list[Optional[str]] = [None]
done = threading.Event()
def _read():
try:
time.sleep(0.2) # let hotkey key events drain from stdin
_flush_stdin() # discard any buffered chars
result[0] = sys.stdin.readline().strip()
except Exception:
pass
done.set()
t = threading.Thread(target=_read, daemon=True)
t.start()
done.wait(timeout=timeout)
if not result[0]:
print("[capture] App name prompt cancelled.")
return None
return result[0]
# ---------------------------------------------------------------------------
# Window utilities (macOS CoreGraphics via Swift subprocess)
# ---------------------------------------------------------------------------
def list_windows() -> list[dict]:
"""Return a list of on-screen windows as dicts with keys: name, id, x, y, w, h."""
with tempfile.NamedTemporaryFile(suffix=".swift", mode="w", delete=False) as f:
f.write(_WINDOW_SWIFT)
tmppath = f.name
try:
result = subprocess.run(
["swift", tmppath],
capture_output=True, text=True, timeout=10
)
windows = []
for line in result.stdout.splitlines():
parts = line.split("|")
if len(parts) == 6:
name, wid, x, y, w, h = parts
windows.append({
"name": name,
"id": int(wid),
"x": int(x), "y": int(y),
"w": int(w), "h": int(h),
})
return windows
except subprocess.TimeoutExpired:
print("[capture] Warning: window enumeration timed out.")
return []
except FileNotFoundError:
print("[capture] Warning: 'swift' not found — app screenshots unavailable.")
return []
finally:
Path(tmppath).unlink(missing_ok=True)
def find_window_by_name(app_name: str) -> Optional[dict]:
"""Return the first on-screen window whose owner name matches app_name (case-insensitive)."""
for w in list_windows():
if w["name"].lower() == app_name.lower():
return w
return None
# ---------------------------------------------------------------------------
# Screenshot operations
# ---------------------------------------------------------------------------
def _timestamp() -> str:
return datetime.now().strftime("%Y%m%d_%H%M%S")
def screenshot_fullscreen(output_dir: Path) -> Path:
output_dir.mkdir(parents=True, exist_ok=True)
out = output_dir / f"screenshot_fullscreen_{_timestamp()}.png"
with mss.mss() as sct:
monitor = sct.monitors[1] # primary display
img = sct.grab(monitor)
mss.tools.to_png(img.rgb, img.size, output=str(out))
print(f"[capture] Screenshot saved → {out}")
return out
def screenshot_app(app_name: str, output_dir: Path) -> Optional[Path]:
output_dir.mkdir(parents=True, exist_ok=True)
win = find_window_by_name(app_name)
if not win:
print(f"[capture] No on-screen window found for '{app_name}'.")
return None
safe_name = re.sub(r"[^\w\-]", "_", app_name)
out = output_dir / f"screenshot_app_{safe_name}_{_timestamp()}.png"
result = subprocess.run(
["screencapture", "-l", str(win["id"]), "-x", str(out)],
capture_output=True, text=True
)
if result.returncode != 0:
print(f"[capture] screencapture failed: {result.stderr.strip()}")
return None
print(f"[capture] App screenshot saved → {out}")
return out
# ---------------------------------------------------------------------------
# Video recording engine
# ---------------------------------------------------------------------------
def _record_loop(
rect: Rect,
output_path: Path,
stop_event: threading.Event,
fps: int,
scale: float,
) -> None:
"""Frame capture loop. Runs in a background thread."""
# Apply HiDPI scale factor to the region coordinates
phys = Rect(
int(rect.x * scale), int(rect.y * scale),
int(rect.w * scale), int(rect.h * scale),
)
monitor = phys.to_mss_monitor()
size = (phys.w, phys.h)
# Try mp4v first, fall back to MJPG
fourcc = cv2.VideoWriter_fourcc(*"mp4v")
out_str = str(output_path)
writer = cv2.VideoWriter(out_str, fourcc, fps, size)
if not writer.isOpened():
avi_path = output_path.with_suffix(".avi")
fourcc = cv2.VideoWriter_fourcc(*"MJPG")
writer = cv2.VideoWriter(str(avi_path), fourcc, fps, size)
output_path = avi_path
frame_interval = 1.0 / fps
with mss.mss() as sct:
while not stop_event.is_set():
t0 = time.monotonic()
raw = sct.grab(monitor)
frame = np.array(raw)
bgr = cv2.cvtColor(frame, cv2.COLOR_BGRA2BGR)
writer.write(bgr)
elapsed = time.monotonic() - t0
sleep_for = frame_interval - elapsed
if sleep_for > 0:
time.sleep(sleep_for)
writer.release()
def _detect_scale(logical_rect: Optional[Rect] = None) -> float:
"""Detect HiDPI scale factor by comparing mss physical width to monitor logical width."""
try:
with mss.mss() as sct:
m = sct.monitors[1]
phys_w = m["width"]
# On Retina, CGWindowListCopyWindowInfo returns logical points.
# mss returns physical pixels. Typical factors: 1.0 or 2.0.
# We use the ratio of mss width to the screen's logical width from AppKit via
# a tiny Swift call — fall back to 1.0 if Swift is unavailable.
result = subprocess.run(
["swift", "-e",
"import AppKit; print(Int(NSScreen.main!.frame.width))"],
capture_output=True, text=True, timeout=5
)
if result.returncode == 0:
logical_w = int(result.stdout.strip())
if logical_w > 0:
return phys_w / logical_w
except Exception:
pass
return 1.0
def start_recording(rect: Rect, output_dir: Path, fps: int, scale: float) -> RecordingSession:
output_dir.mkdir(parents=True, exist_ok=True)
out = output_dir / f"recording_{_timestamp()}.mov"
stop_event = threading.Event()
t = threading.Thread(
target=_record_loop,
args=(rect, out, stop_event, fps, scale),
daemon=True,
)
t.start()
print(f"[capture] Recording started → {out} (press hotkey again to stop)")
return RecordingSession(thread=t, stop_event=stop_event, output_path=out)
# ---------------------------------------------------------------------------
# Ring buffer engine (region recording)
# ---------------------------------------------------------------------------
def _buffer_loop(
rect: Rect,
frame_buffer: deque,
stop_event: threading.Event,
fps: int,
scale: float,
) -> None:
"""Continuously capture frames into a JPEG-compressed ring buffer."""
phys = Rect(
int(rect.x * scale), int(rect.y * scale),
int(rect.w * scale), int(rect.h * scale),
)
monitor = phys.to_mss_monitor()
interval = 1.0 / fps
enc_params = [cv2.IMWRITE_JPEG_QUALITY, 85]
with mss.mss() as sct:
while not stop_event.is_set():
t0 = time.monotonic()
raw = sct.grab(monitor)
bgr = cv2.cvtColor(np.array(raw), cv2.COLOR_BGRA2BGR)
_, jpeg = cv2.imencode(".jpg", bgr, enc_params)
frame_buffer.append(jpeg.tobytes())
spare = interval - (time.monotonic() - t0)
if spare > 0:
time.sleep(spare)
def _write_buffer_to_file(
frames: list,
fps: int,
phys_w: int,
phys_h: int,
output_dir: Path,
save_seconds: int,
) -> None:
"""Decode JPEG ring-buffer snapshot and write the last save_seconds to disk."""
n = min(len(frames), fps * save_seconds)
if n == 0:
print("[capture] Buffer empty — nothing to save.")
return
frames = frames[-n:]
output_dir.mkdir(parents=True, exist_ok=True)
out = output_dir / f"recording_region_{_timestamp()}.mov"
fourcc = cv2.VideoWriter_fourcc(*"mp4v")
writer = cv2.VideoWriter(str(out), fourcc, fps, (phys_w, phys_h))
if not writer.isOpened():
out = out.with_suffix(".avi")
fourcc = cv2.VideoWriter_fourcc(*"MJPG")
writer = cv2.VideoWriter(str(out), fourcc, fps, (phys_w, phys_h))
for jpeg_bytes in frames:
arr = np.frombuffer(jpeg_bytes, dtype=np.uint8)
frame = cv2.imdecode(arr, cv2.IMREAD_COLOR)
if frame is not None:
writer.write(frame)
writer.release()
print(f"[capture] Buffer saved ({n // fps}s) → {out}")
def start_buffer_recording(
rect: Rect,
output_dir: Path,
fps: int,
scale: float,
buffer_seconds: int,
save_seconds: int,
) -> BufferSession:
phys_w = int(rect.w * scale)
phys_h = int(rect.h * scale)
frame_buffer = deque(maxlen=fps * buffer_seconds)
stop_event = threading.Event()
t = threading.Thread(
target=_buffer_loop,
args=(rect, frame_buffer, stop_event, fps, scale),
daemon=True,
)
t.start()
print(
f"[capture] Ring buffer started "
f"(window={buffer_seconds}s, saves last {save_seconds}s) "
f"→ press hotkey again to save"
)
return BufferSession(
thread=t, stop_event=stop_event,
frame_buffer=frame_buffer,
phys_w=phys_w, phys_h=phys_h,
fps=fps, output_dir=output_dir,
save_seconds=save_seconds,
)
# ---------------------------------------------------------------------------
# ScreenKit — importable class-based API
# ---------------------------------------------------------------------------
class ScreenKit:
"""
Importable class-based API wrapping all capture and recording functionality.
Example:
from capture import ScreenKit
sk = ScreenKit()
path = sk.screenshot_fullscreen()
sk.start_region_recording("100,200 800x600")
# ... later ...
sk.stop_region_recording()
"""
def __init__(
self,
output_dir: Path = DEFAULT_OUTPUT_DIR,
fps: int = DEFAULT_FPS,
buffer_seconds: int = DEFAULT_BUFFER_SECONDS,
save_seconds: int = DEFAULT_SAVE_SECONDS,
) -> None:
self.output_dir = Path(output_dir)
self.fps = fps
self.buffer_seconds = buffer_seconds
self.save_seconds = save_seconds
self._scale = _detect_scale()
self._lock = threading.Lock()
self._fullscreen_session: Optional[RecordingSession] = None
self._region_session: Optional[BufferSession] = None
# ---- Screenshot ----------------------------------------------------------
def screenshot_fullscreen(self) -> Path:
"""Capture a full-screen screenshot. Returns the saved file path."""
return screenshot_fullscreen(self.output_dir)
def screenshot_app(self, app_name: str) -> Optional[Path]:
"""Capture a screenshot of a specific application window."""
return screenshot_app(app_name, self.output_dir)
# ---- Window utilities ----------------------------------------------------
def list_windows(self) -> list[dict]:
"""Return on-screen windows as dicts with keys: name, id, x, y, w, h."""
return list_windows()
def find_window(self, app_name: str) -> Optional[dict]:
"""Return the first on-screen window matching app_name (case-insensitive)."""
return find_window_by_name(app_name)
# ---- Region parsing ------------------------------------------------------
def parse_region(self, text: str) -> Rect:
"""Parse a region string ("x1,y1 x2,y2", "x,y WxH", "cx,cy WxH center") into a Rect."""
return parse_region(text)
def parse_gemma_bbox(self, json_str: str) -> Rect:
"""
Convert Gemma 4 bounding box JSON into a Rect (logical pixels).
Automatically queries current screen dimensions from mss.
"""
with mss.mss() as sct:
m = sct.monitors[1]
return parse_gemma_bbox(json_str, m["width"], m["height"], self._scale)
# ---- Full-screen recording -----------------------------------------------
def start_fullscreen_recording(self) -> None:
"""
Start full-screen recording. Raises RuntimeError if already recording.
Stop with stop_fullscreen_recording().
"""
with self._lock:
if self._fullscreen_session is not None:
raise RuntimeError(
"Full-screen recording already active. "
"Call stop_fullscreen_recording() first."
)
with mss.mss() as sct:
m = sct.monitors[1]
rect = Rect(0, 0, int(m["width"] / self._scale), int(m["height"] / self._scale))
session = start_recording(rect, self.output_dir, self.fps, self._scale)
with self._lock:
self._fullscreen_session = session
def stop_fullscreen_recording(self) -> Optional[Path]:
"""Stop full-screen recording. Returns the output file path, or None if not recording."""
with self._lock:
session = self._fullscreen_session
self._fullscreen_session = None
if session is None:
return None
session.stop()
return session.output_path
def is_recording_fullscreen(self) -> bool:
"""Return True if a full-screen recording is currently active."""
with self._lock:
return self._fullscreen_session is not None
# ---- Region recording (ring buffer) --------------------------------------
def start_region_recording(self, region: "str | Rect") -> Rect:
"""
Start ring-buffer region recording. Raises RuntimeError if already recording.
Args:
region: A Rect, or a region string / Gemma JSON string.
Returns:
The Rect that was parsed and is being recorded.
"""
with self._lock:
if self._region_session is not None:
raise RuntimeError(
"Region recording already active. "
"Call stop_region_recording() first."
)
if isinstance(region, Rect):
rect = region
elif isinstance(region, str) and (region.startswith("[") or region.startswith("{")):
rect = self.parse_gemma_bbox(region)
else:
rect = parse_region(str(region))
session = start_buffer_recording(
rect, self.output_dir, self.fps, self._scale,
self.buffer_seconds, self.save_seconds,
)
with self._lock:
self._region_session = session
return rect
def stop_region_recording(self) -> None:
"""
Stop region recording and save the buffered video to disk.
The file write happens asynchronously in a background thread.
"""
with self._lock:
session = self._region_session
self._region_session = None
if session is None:
return
session.save_and_stop()
def is_recording_region(self) -> bool:
"""Return True if a region (ring buffer) recording is currently active."""
with self._lock:
return self._region_session is not None
# ---- Combined ------------------------------------------------------------
def stop_all(self) -> None:
"""Stop all active recordings."""
self.stop_fullscreen_recording()
self.stop_region_recording()
# ---------------------------------------------------------------------------
# Startup permission checks
# ---------------------------------------------------------------------------
def check_screen_recording() -> bool:
"""Try a 1×1 grab; return True if Screen Recording permission is granted."""
try:
with mss.mss() as sct:
sct.grab({"top": 0, "left": 0, "width": 1, "height": 1})
return True
except Exception:
return False
def print_startup_info(hotkeys: dict[str, str]) -> None:
print("=" * 60)
print(" VisionUX — Screen Capture")
print("=" * 60)
print(f" Output dir : {DEFAULT_OUTPUT_DIR}")
print()
print(" Hotkeys:")
print(f" {hotkeys['screenshot_fullscreen']:<28} Full-screen screenshot")
print(f" {hotkeys['screenshot_app']:<28} App screenshot (prompts)")
print(f" {hotkeys['video_fullscreen']:<28} Full-screen video toggle")
print(f" {hotkeys['video_region']:<28} Region video toggle (prompts)")
print(f" {hotkeys['quit']:<28} Quit")
print()
print(" Permissions required:")
print(" • Accessibility → System Settings > Privacy & Security > Accessibility")
print(" (grant to your terminal app so hotkeys are detected globally)")
print(" • Screen Recording → System Settings > Privacy & Security > Screen Recording")
print()
if not check_screen_recording():
print(" [WARNING] Screen Recording permission may not be granted.")
print(" Grant it in System Settings and restart the script.")
print()
print(" Ready. Waiting for hotkeys…")
print("=" * 60)
# ---------------------------------------------------------------------------
# CLI argument parsing
# ---------------------------------------------------------------------------
def parse_args() -> argparse.Namespace:
p = argparse.ArgumentParser(
description="VisionUX keyboard-triggered screen capture for macOS."
)
p.add_argument("--config", type=Path, metavar="FILE",
help="Path to JSON config file (default: ~/.visionux.json)")
p.add_argument("--app", metavar="NAME",
help="App name for app screenshot (skips prompt)")
p.add_argument("--region", metavar="STR",
help='Region for video e.g. "100,200 400x300" (skips prompt)')
p.add_argument("--gemma", metavar="JSON",
help='Region from Gemma 4 JSON e.g. \'[{"box_2d":[171,75,245,308],"label":"..."}]\'')
p.add_argument("--output-dir", type=Path, metavar="DIR",
help=f"Output directory (default: {DEFAULT_OUTPUT_DIR})")
p.add_argument("--fps", type=int, default=DEFAULT_FPS, metavar="N",
help=f"Frames per second for video (default: {DEFAULT_FPS})")
p.add_argument("--buffer-seconds", type=int, default=DEFAULT_BUFFER_SECONDS, metavar="N",
help=f"Ring buffer window in seconds (default: {DEFAULT_BUFFER_SECONDS})")
p.add_argument("--save-seconds", type=int, default=DEFAULT_SAVE_SECONDS, metavar="N",
help=f"Seconds to save on trigger (default: {DEFAULT_SAVE_SECONDS})")
p.add_argument("--list-windows", action="store_true",
help="Print on-screen windows and exit")
return p.parse_args()
# ---------------------------------------------------------------------------
# Main / hotkey wiring
# ---------------------------------------------------------------------------
def main() -> None:
args = parse_args()
if args.list_windows:
wins = list_windows()
if not wins:
print("No on-screen windows found (check Screen Recording permission).")
else:
print(f"{'App Name':<35} {'Window ID':>10} Bounds")
print("-" * 70)
for w in wins:
print(f"{w['name']:<35} {w['id']:>10} "
f"{w['x']},{w['y']} {w['w']}×{w['h']}")
return
config = load_config(args.config)
hotkeys = resolve_hotkeys(config)
output_dir = args.output_dir or Path(config.get("output_dir", DEFAULT_OUTPUT_DIR))
fps = args.fps
buffer_seconds = args.buffer_seconds
save_seconds = args.save_seconds
print_startup_info(hotkeys)
# Detect HiDPI scale once at startup
scale = _detect_scale()
if scale != 1.0:
print(f"[capture] Retina display detected: scale factor {scale:.1f}x")
# Shared mutable state — protected by a lock
_lock = threading.Lock()
_active_fullscreen_session: list[Optional[RecordingSession]] = [None]
_active_region_session: list[Optional[BufferSession]] = [None]
_preset_region: list[Optional[Rect]] = [None]
# Guard: --region and --gemma are mutually exclusive
if args.region and args.gemma:
print("[capture] Error: --region and --gemma cannot be used together.")
sys.exit(1)
# Pre-parse --region if supplied
if args.region:
try:
_preset_region[0] = parse_region(args.region)
print(f"[capture] Region preset: {_preset_region[0]}")
except ValueError as e:
print(f"[capture] --region error: {e}")
sys.exit(1)
# Pre-parse --gemma if supplied
if args.gemma:
try:
with mss.mss() as sct:
m = sct.monitors[1]
_preset_region[0] = parse_gemma_bbox(args.gemma, m["width"], m["height"], scale)
print(f"[capture] Gemma region preset: {_preset_region[0]}")
except ValueError as e:
print(f"[capture] --gemma error: {e}")
sys.exit(1)
# ---- Action handlers (called from pynput background thread) ----
def action_screenshot_fullscreen() -> None:
screenshot_fullscreen(output_dir)
def action_screenshot_app() -> None:
app_name = args.app or prompt_app_name()
if app_name:
screenshot_app(app_name, output_dir)
def action_video_fullscreen_toggle() -> None:
with _lock:
session = _active_fullscreen_session[0]
if session is not None:
session.stop()
_active_fullscreen_session[0] = None
return
# Get full-screen rect
with mss.mss() as sct:
m = sct.monitors[1]
rect = Rect(0, 0, int(m["width"] / scale), int(m["height"] / scale))
new_session = start_recording(rect, output_dir, fps, scale)
with _lock:
_active_fullscreen_session[0] = new_session
def action_video_region_toggle() -> None:
with _lock:
session = _active_region_session[0]
if session is not None:
session.save_and_stop()
_active_region_session[0] = None
return
# Determine region — consume any CLI preset once, then always prompt
with _lock:
rect = _preset_region[0]
_preset_region[0] = None # clear so next press prompts
if rect is None:
rect = prompt_region(scale=scale)
if rect is None:
return
new_session = start_buffer_recording(rect, output_dir, fps, scale, buffer_seconds, save_seconds)
with _lock:
_active_region_session[0] = new_session
def action_quit() -> None:
print("\n[capture] Quitting…")
# Stop any active recordings cleanly
with _lock:
fs = _active_fullscreen_session[0]
rg = _active_region_session[0]
if fs:
fs.stop()
if rg:
rg.save_and_stop()
sys.exit(0)
# ---- Build GlobalHotKeys mapping ----
hk_map = {
hotkeys["screenshot_fullscreen"]: action_screenshot_fullscreen,
hotkeys["screenshot_app"]: action_screenshot_app,
hotkeys["video_fullscreen"]: action_video_fullscreen_toggle,
hotkeys["video_region"]: action_video_region_toggle,
hotkeys["quit"]: action_quit,
}
try:
with keyboard.GlobalHotKeys(hk_map) as listener:
listener.join()
except KeyboardInterrupt:
action_quit()
if __name__ == "__main__":
main()