forked from lukmay/QuickAudioRecorder
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgui.py
More file actions
1940 lines (1709 loc) · 66.5 KB
/
Copy pathgui.py
File metadata and controls
1940 lines (1709 loc) · 66.5 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
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import ctypes
import json
import os
import shutil
import sys
import tempfile
import time
from ctypes import wintypes
from typing import ClassVar
import keyboard
import psutil
from PyQt6.QtCore import QEvent, QObject, QPoint, QSize, Qt, QTimer, pyqtSignal
from PyQt6.QtGui import QAction, QBrush, QColor, QIcon, QImage, QPainter, QPixmap
from PyQt6.QtWidgets import (
QCheckBox,
QComboBox,
QDialog,
QFileDialog,
QFormLayout,
QGroupBox,
QHBoxLayout,
QLabel,
QLineEdit,
QListWidget,
QListWidgetItem,
QMainWindow,
QMenu,
QMessageBox,
QPushButton,
QScrollArea,
QSystemTrayIcon,
QVBoxLayout,
QWidget,
)
from audio_recorder import (
FORMAT_CONFIG,
SAMPLE_RATE_CONFIG,
AudioRecorder,
describe_output_profile,
device_cache,
get_devices,
)
from clipboard_utils import copy_file_to_clipboard
from process_utils import (
get_active_applications,
get_foreground_pid,
get_foreground_window_info,
)
CONFIG_FILE = "QuickAudioRecorder.settings.json"
def window_thumbnail(hwnd, width=48, height=32):
"""Capture a small screenshot of the given window as a QIcon.
Mirrors how OBS captures windows: the primary method is a GDI ``BitBlt`` of
the window's own device context (captures the real window, never the
desktop, with no cropping or overlap). A desktop-DC crop at the window's
exact rectangle is used only as a fallback for windows where that BitBlt
comes back blank (e.g. GPU-composited content). Returns None when the window
can't be captured.
"""
if not hwnd:
return None
# PrintWindow with PW_RENDERFULLCONTENT is the OBS "Windows 10" capture
# method: it asks the target to paint its full content (including GPU
# composited clients like Chrome/Vivaldi/Discord) into our DC, so it captures
# the real window -- never the desktop -- with no cropping or overlap, and
# works while the window is behind others. This is prioritized over BitBlt,
# which returns a blank bitmap for most modern windows.
image = _printwindow_image(hwnd, width, height)
if _is_good_image(image):
return QIcon(QPixmap.fromImage(image))
image = _bitblt_window_image(hwnd, width, height)
if _is_good_image(image):
return QIcon(QPixmap.fromImage(image))
image = _bitblt_desktop_rect(hwnd, width, height)
if _is_good_image(image):
return QIcon(QPixmap.fromImage(image))
return None
def _is_good_image(image):
"""True when ``image`` is a usable, non-blank capture."""
return image is not None and not image.isNull() and not _is_uniform_image(image)
def _bitblt_window_image(hwnd, width, height):
"""Capture ``hwnd`` by BitBlt-ing its window device context.
This is the OBS-proven GDI method: ``GetWindowDC`` + ``BitBlt`` of the
window's own content into a memory bitmap, converted to a ``QImage``. It
captures the actual window (never the desktop) and works across monitors.
Returns None on any failure so callers fall back to the desktop-DC crop.
"""
try:
import win32con
import win32gui
import win32ui
except Exception:
return None
try:
if win32gui.IsIconic(hwnd):
rect = win32gui.GetWindowPlacement(hwnd)[4]
else:
rect = win32gui.GetWindowRect(hwnd)
w = max(1, rect[2] - rect[0])
h = max(1, rect[3] - rect[1])
hwnd_dc = win32gui.GetWindowDC(hwnd)
if not hwnd_dc:
return None
try:
mfc_dc = win32ui.CreateDCFromHandle(hwnd_dc)
save_dc = mfc_dc.CreateCompatibleDC()
bitmap = win32ui.CreateBitmap()
bitmap.CreateCompatibleBitmap(mfc_dc, w, h)
save_dc.SelectObject(bitmap)
save_dc.BitBlt((0, 0), (w, h), mfc_dc, (0, 0), win32con.SRCCOPY)
bmp_info = bitmap.GetInfo()
bmp_str = bitmap.GetBitmapBits(True)
finally:
win32gui.ReleaseDC(hwnd, hwnd_dc)
try:
mfc_dc.DeleteDC()
except Exception:
pass
try:
save_dc.DeleteDC()
except Exception:
pass
if not bmp_str:
return None
image = QImage(
bmp_str,
w,
h,
bmp_info["bmWidthBytes"],
QImage.Format.Format_RGB32,
)
if image.isNull():
return None
return image.scaled(
width,
height,
Qt.AspectRatioMode.KeepAspectRatio,
Qt.TransformationMode.SmoothTransformation,
)
except Exception:
return None
def _printwindow_image(hwnd, width, height):
"""Capture ``hwnd`` with ``PrintWindow`` (PW_RENDERFULLCONTENT).
This is the technique OBS and Chromium use for windows where a GDI
``BitBlt`` hands back a blank bitmap -- GPU-composited clients (Chrome,
Discord, Vivaldi), occluded, or minimized windows. ``PrintWindow`` asks the
target to paint its full content (including the client area) into our memory
DC, so it captures the real window and not the desktop, with no cropping or
overlap, and works even when the window is behind others.
pywin32 does not expose ``PrintWindow``, so we call ``user32.PrintWindow``
directly via ctypes.
Returns None on any failure.
"""
hwnd = int(hwnd)
try:
import ctypes
import win32gui
import win32ui
user32 = ctypes.windll.user32
user32.PrintWindow.argtypes = [ctypes.c_void_p, ctypes.c_void_p, ctypes.c_uint]
user32.PrintWindow.restype = ctypes.c_int
except Exception:
return None
try:
if win32gui.IsIconic(hwnd):
rect = win32gui.GetWindowPlacement(hwnd)[4]
else:
rect = win32gui.GetWindowRect(hwnd)
w = max(1, rect[2] - rect[0])
h = max(1, rect[3] - rect[1])
hwnd_dc = win32gui.GetWindowDC(hwnd)
if not hwnd_dc:
return None
try:
mfc_dc = win32ui.CreateDCFromHandle(hwnd_dc)
save_dc = mfc_dc.CreateCompatibleDC()
bitmap = win32ui.CreateBitmap()
bitmap.CreateCompatibleBitmap(mfc_dc, w, h)
save_dc.SelectObject(bitmap)
dest = int(save_dc.GetSafeHdc())
# PW_RENDERFULLCONTENT (2) asks the app to render its full client
# area; fall back to the plain (0) variant if it is unsupported.
if not user32.PrintWindow(hwnd, dest, 2) and not user32.PrintWindow(
hwnd, dest, 0
):
return None
bmp_info = bitmap.GetInfo()
bmp_str = bitmap.GetBitmapBits(True)
finally:
win32gui.ReleaseDC(hwnd, hwnd_dc)
try:
mfc_dc.DeleteDC()
except Exception:
pass
try:
save_dc.DeleteDC()
except Exception:
pass
if not bmp_str:
return None
image = QImage(
bmp_str,
w,
h,
bmp_info["bmWidthBytes"],
QImage.Format.Format_RGB32,
)
if image.isNull():
return None
return image.scaled(
width,
height,
Qt.AspectRatioMode.KeepAspectRatio,
Qt.TransformationMode.SmoothTransformation,
)
except Exception:
return None
def _is_uniform_image(image):
"""Return True when ``image`` is blank (a single solid colour).
PrintWindow frequently hands back an all-black or all-white bitmap for
GPU-composited windows; such a result should be discarded in favour of a
screen grab.
"""
if image is None or image.isNull():
return True
try:
converted = image.convertToFormat(QImage.Format.Format_RGB32)
except Exception:
return True
width = converted.width()
height = converted.height()
if width == 0 or height == 0:
return True
first = converted.pixelColor(0, 0)
target = (first.red(), first.green(), first.blue())
for y in range(height):
for x in range(width):
color = converted.pixelColor(x, y)
if (color.red(), color.green(), color.blue()) != target:
return False
return True
def _bitblt_desktop_rect(hwnd, width, height):
"""Fallback capture: BitBlt the desktop DC at the window's exact rect.
When a direct ``BitBlt`` of the window's own DC comes back blank (GPU
composited windows, etc.) the desktop device context still holds the
composited result for the region the window occupies, so sampling that
region recovers the content. The crop is the window's real rectangle, so it
is accurate with no overlap or guesswork.
Returns None on any failure.
"""
try:
import win32con
import win32gui
import win32ui
except Exception:
return None
try:
if win32gui.IsIconic(hwnd):
rect = win32gui.GetWindowPlacement(hwnd)[4]
else:
rect = win32gui.GetWindowRect(hwnd)
left, top = rect[0], rect[1]
w = max(1, rect[2] - rect[0])
h = max(1, rect[3] - rect[1])
desktop_dc = win32gui.GetDC(0)
if not desktop_dc:
return None
try:
mfc_dc = win32ui.CreateDCFromHandle(desktop_dc)
save_dc = mfc_dc.CreateCompatibleDC()
bitmap = win32ui.CreateBitmap()
bitmap.CreateCompatibleBitmap(mfc_dc, w, h)
save_dc.SelectObject(bitmap)
save_dc.BitBlt((0, 0), (w, h), mfc_dc, (left, top), win32con.SRCCOPY)
bmp_info = bitmap.GetInfo()
bmp_str = bitmap.GetBitmapBits(True)
finally:
win32gui.ReleaseDC(0, desktop_dc)
try:
mfc_dc.DeleteDC()
except Exception:
pass
try:
save_dc.DeleteDC()
except Exception:
pass
if not bmp_str:
return None
image = QImage(
bmp_str,
w,
h,
bmp_info["bmWidthBytes"],
QImage.Format.Format_RGB32,
)
if image.isNull():
return None
return image.scaled(
width,
height,
Qt.AspectRatioMode.KeepAspectRatio,
Qt.TransformationMode.SmoothTransformation,
)
except Exception:
return None
def resource_path(relative_path):
try:
base_path = sys._MEIPASS
except Exception:
base_path = os.path.abspath(".")
return os.path.join(base_path, relative_path)
WINDOWS_MODIFIER_KEYS = {
"alt": 0x0001,
"ctrl": 0x0002,
"control": 0x0002,
"shift": 0x0004,
"windows": 0x0008,
"win": 0x0008,
}
WINDOWS_SPECIAL_KEYS = {
"backspace": 0x08,
"tab": 0x09,
"enter": 0x0D,
"return": 0x0D,
"esc": 0x1B,
"escape": 0x1B,
"space": 0x20,
"left": 0x25,
"up": 0x26,
"right": 0x27,
"down": 0x28,
"delete": 0x2E,
"plus": 0xBB,
"comma": 0xBC,
"-": 0xBD,
"minus": 0xBD,
".": 0xBE,
"period": 0xBE,
"/": 0xBF,
"slash": 0xBF,
}
for number in range(1, 13):
WINDOWS_SPECIAL_KEYS[f"f{number}"] = 0x70 + number - 1
def parse_windows_hotkey(hotkey):
parts = [part.strip().lower() for part in (hotkey or "").split("+") if part.strip()]
if not parts:
return None
modifiers = 0
keys = []
for part in parts:
modifier = WINDOWS_MODIFIER_KEYS.get(part)
if modifier:
modifiers |= modifier
else:
keys.append(part)
if len(keys) != 1:
return None
key = keys[0]
if len(key) == 1 and "a" <= key <= "z":
virtual_key = ord(key.upper())
elif len(key) == 1 and "0" <= key <= "9":
virtual_key = ord(key)
else:
virtual_key = WINDOWS_SPECIAL_KEYS.get(key)
if not virtual_key:
return None
return modifiers, virtual_key
class KBDLLHOOKSTRUCT(ctypes.Structure):
_fields_ = [
("vkCode", wintypes.DWORD),
("scanCode", wintypes.DWORD),
("flags", wintypes.DWORD),
("time", wintypes.DWORD),
("dwExtraInfo", ctypes.c_void_p),
]
LowLevelKeyboardProc = ctypes.WINFUNCTYPE(
wintypes.LPARAM, ctypes.c_int, wintypes.WPARAM, wintypes.LPARAM
)
class KeyboardHotkeyManager:
def clear(self):
try:
keyboard.unhook_all_hotkeys()
except Exception:
pass
def register(self, hotkey, callback):
keyboard.add_hotkey(hotkey, callback)
return True
class WindowsLowLevelHotkeyManager:
WH_KEYBOARD_LL = 13
WM_KEYDOWN = 0x0100
WM_KEYUP = 0x0101
WM_SYSKEYDOWN = 0x0104
WM_SYSKEYUP = 0x0105
KEY_DOWN_MESSAGES: ClassVar[set] = {WM_KEYDOWN, WM_SYSKEYDOWN}
KEY_UP_MESSAGES: ClassVar[set] = {WM_KEYUP, WM_SYSKEYUP}
VK_TO_MODIFIER: ClassVar[dict] = {
0x10: WINDOWS_MODIFIER_KEYS["shift"],
0xA0: WINDOWS_MODIFIER_KEYS["shift"],
0xA1: WINDOWS_MODIFIER_KEYS["shift"],
0x11: WINDOWS_MODIFIER_KEYS["ctrl"],
0xA2: WINDOWS_MODIFIER_KEYS["ctrl"],
0xA3: WINDOWS_MODIFIER_KEYS["ctrl"],
0x12: WINDOWS_MODIFIER_KEYS["alt"],
0xA4: WINDOWS_MODIFIER_KEYS["alt"],
0xA5: WINDOWS_MODIFIER_KEYS["alt"],
0x5B: WINDOWS_MODIFIER_KEYS["windows"],
0x5C: WINDOWS_MODIFIER_KEYS["windows"],
}
def __init__(self, install_hook=True, fallback=None):
self.fallback = fallback or KeyboardHotkeyManager()
self.callbacks = {}
self.active_modifiers = 0
self.active_hotkeys = set()
self.hook = None
self.user32 = None
self.kernel32 = None
self.hook_callback = None
if sys.platform == "win32":
self.user32 = ctypes.WinDLL("user32", use_last_error=True)
self.kernel32 = ctypes.WinDLL("kernel32", use_last_error=True)
self.configure_api()
self.hook_callback = LowLevelKeyboardProc(self.low_level_keyboard_proc)
if install_hook:
self.install_hook()
def configure_api(self):
assert self.user32 is not None
self.user32.SetWindowsHookExW.argtypes = [
ctypes.c_int,
LowLevelKeyboardProc,
wintypes.HINSTANCE,
wintypes.DWORD,
]
self.user32.SetWindowsHookExW.restype = wintypes.HHOOK
self.user32.UnhookWindowsHookEx.argtypes = [wintypes.HHOOK]
self.user32.UnhookWindowsHookEx.restype = wintypes.BOOL
self.user32.CallNextHookEx.argtypes = [
wintypes.HHOOK,
ctypes.c_int,
wintypes.WPARAM,
wintypes.LPARAM,
]
self.user32.CallNextHookEx.restype = wintypes.LPARAM
assert self.kernel32 is not None
self.kernel32.GetModuleHandleW.argtypes = [wintypes.LPCWSTR]
self.kernel32.GetModuleHandleW.restype = wintypes.HMODULE
def install_hook(self):
if self.user32 is None or self.hook:
return bool(self.hook)
assert self.kernel32 is not None
self.hook = self.user32.SetWindowsHookExW(
self.WH_KEYBOARD_LL,
self.hook_callback,
self.kernel32.GetModuleHandleW(None),
0,
)
if not self.hook:
print(f"Failed to install low-level hotkey hook: {ctypes.get_last_error()}")
return bool(self.hook)
def clear(self):
self.callbacks.clear()
self.active_modifiers = 0
self.active_hotkeys.clear()
try:
self.fallback.clear()
except Exception as e:
print(f"Failed to clear fallback hotkeys: {e}")
def register(self, hotkey, callback):
parsed = parse_windows_hotkey(hotkey)
if parsed is None:
return self.fallback.register(hotkey, callback)
if self.user32 is not None and not self.install_hook():
return self.fallback.register(hotkey, callback)
self.callbacks.setdefault(parsed, []).append(callback)
return True
def low_level_keyboard_proc(self, n_code, w_param, l_param):
try:
if n_code >= 0:
event = ctypes.cast(l_param, ctypes.POINTER(KBDLLHOOKSTRUCT)).contents
self.process_key_event(int(w_param), int(event.vkCode))
except Exception as e:
print(f"Failed to handle low-level hotkey event: {e}")
return self.user32.CallNextHookEx(None, n_code, w_param, l_param)
def process_key_event(self, message, virtual_key):
if message in self.KEY_DOWN_MESSAGES:
self.handle_key_down(virtual_key)
elif message in self.KEY_UP_MESSAGES:
self.handle_key_up(virtual_key)
def handle_key_down(self, virtual_key):
modifier = self.VK_TO_MODIFIER.get(virtual_key)
if modifier:
self.active_modifiers |= modifier
return
hotkey = (self.active_modifiers, virtual_key)
if hotkey in self.callbacks and hotkey not in self.active_hotkeys:
self.active_hotkeys.add(hotkey)
for callback in list(self.callbacks[hotkey]):
callback()
def handle_key_up(self, virtual_key):
modifier = self.VK_TO_MODIFIER.get(virtual_key)
if modifier:
self.active_modifiers &= ~modifier
self.active_hotkeys.clear()
return
for hotkey in list(self.active_hotkeys):
if hotkey[1] == virtual_key:
self.active_hotkeys.discard(hotkey)
def create_hotkey_manager(app):
if sys.platform == "win32":
return WindowsLowLevelHotkeyManager()
return KeyboardHotkeyManager()
class SignalManager(QObject):
recording_finished = pyqtSignal(object, str)
class HotkeyEdit(QLineEdit):
"""
Custom widget to capture hotkeys by pressing them.
Maps Qt events to 'keyboard' library compatible strings.
"""
CAPTURE_PROMPT = "Press shortcut..."
sequence_captured = pyqtSignal(str)
capture_cancelled = pyqtSignal()
def __init__(self, parent=None):
super().__init__(parent)
self.setPlaceholderText("Click to set hotkey...")
self.setReadOnly(True)
self.current_sequence = None
self.is_capturing = False
self._previous_text = ""
self._keyboard_hook = None
self._modifier_scan_codes = {
"ctrl": set(),
"alt": set(),
"shift": set(),
"windows": set(),
}
self._modifier_names_by_scan_code = self.build_modifier_scan_code_lookup()
self.sequence_captured.connect(self.finish_capture)
self.capture_cancelled.connect(self.cancel_capture)
def begin_capture(self):
if self.is_capturing:
return
self.is_capturing = True
self._previous_text = self.text()
self.setText(self.CAPTURE_PROMPT)
self.selectAll()
self.setStyleSheet("color: #666;")
self.start_keyboard_capture()
def finish_capture(self, sequence):
self.stop_keyboard_capture()
self.is_capturing = False
self.current_sequence = sequence or None
self.setStyleSheet("")
self.setText(sequence)
self.clearFocus()
def cancel_capture(self):
self.stop_keyboard_capture()
self.is_capturing = False
self.setStyleSheet("")
self.setText(self._previous_text)
self.clearFocus()
def mousePressEvent(self, event):
self.setFocus()
self.begin_capture()
super().mousePressEvent(event)
def focusInEvent(self, event):
super().focusInEvent(event)
self.begin_capture()
def focusOutEvent(self, event):
if self.is_capturing:
self.is_capturing = False
self.stop_keyboard_capture()
self.setStyleSheet("")
self.setText(self._previous_text)
super().focusOutEvent(event)
def start_keyboard_capture(self):
if self._keyboard_hook is not None:
return
for scan_codes in self._modifier_scan_codes.values():
scan_codes.clear()
try:
self._keyboard_hook = keyboard.hook(self.handle_keyboard_hook)
except Exception as e:
print(f"Failed to start hotkey capture hook: {e}")
def stop_keyboard_capture(self):
if self._keyboard_hook is None:
return
try:
keyboard.unhook(self._keyboard_hook)
except Exception as e:
print(f"Failed to stop hotkey capture hook: {e}")
finally:
self._keyboard_hook = None
for scan_codes in self._modifier_scan_codes.values():
scan_codes.clear()
def handle_keyboard_hook(self, event):
if not self.is_capturing:
return
key_name = self.normalize_hook_key_name(event.name)
modifier = self.modifier_name_for_hook_event(key_name, event.scan_code)
scan_code = event.scan_code
if modifier:
if event.event_type == "down":
self._modifier_scan_codes[modifier].add(scan_code)
elif event.event_type == "up":
self._modifier_scan_codes[modifier].discard(scan_code)
return
if event.event_type != "down":
return
if key_name in ("esc", "escape"):
self.capture_cancelled.emit()
return
if key_name in ("backspace", "delete"):
self.sequence_captured.emit("")
return
sequence = self.format_hook_hotkey(key_name)
if sequence:
self.sequence_captured.emit(sequence)
def normalize_hook_key_name(self, key_name):
key_name = (key_name or "").lower()
aliases = {
"left windows": "windows",
"right windows": "windows",
"win": "windows",
"cmd": "windows",
"+": "plus",
",": "comma",
" ": "space",
"return": "enter",
}
return aliases.get(key_name, key_name)
def modifier_name_for_hook_key(self, key_name):
aliases = {
"ctrl": "ctrl",
"control": "ctrl",
"left ctrl": "ctrl",
"right ctrl": "ctrl",
"alt": "alt",
"left alt": "alt",
"right alt": "alt",
"shift": "shift",
"left shift": "shift",
"right shift": "shift",
"windows": "windows",
"left windows": "windows",
"right windows": "windows",
}
return aliases.get(key_name)
def modifier_name_for_hook_event(self, key_name, scan_code):
if scan_code in self._modifier_names_by_scan_code:
return self._modifier_names_by_scan_code[scan_code]
return self.modifier_name_for_hook_key(key_name)
def build_modifier_scan_code_lookup(self):
lookup = {}
modifier_names = {
"ctrl": ("ctrl", "control", "left ctrl", "right ctrl"),
"alt": ("alt", "left alt", "right alt"),
"shift": ("shift", "left shift", "right shift"),
"windows": ("windows", "left windows", "right windows"),
}
for modifier, names in modifier_names.items():
for name in names:
try:
scan_codes = keyboard.key_to_scan_codes(name, False)
except Exception:
scan_codes = ()
for scan_code in scan_codes:
lookup[scan_code] = modifier
return lookup
def format_hook_hotkey(self, key_name):
parts = []
for modifier in ("ctrl", "alt", "shift", "windows"):
if self._modifier_scan_codes[modifier]:
parts.append(modifier)
key_text = self.normalize_hook_key_name(key_name)
if not key_text or self.modifier_name_for_hook_key(key_text):
return ""
parts.append(key_text)
return "+".join(parts)
def event(self, event):
if event.type() == QEvent.Type.ShortcutOverride and self.is_capturing:
self.handle_hotkey_event(event)
event.accept()
return True
return super().event(event)
def keyPressEvent(self, event):
self.handle_hotkey_event(event)
def handle_hotkey_event(self, event):
key = self.key_from_event(event)
modifiers = event.modifiers()
if key in (Qt.Key.Key_Backspace.value, Qt.Key.Key_Delete.value):
self.finish_capture("")
return
if key == Qt.Key.Key_Escape.value:
self.cancel_capture()
return
if key in (
Qt.Key.Key_Control.value,
Qt.Key.Key_Shift.value,
Qt.Key.Key_Alt.value,
Qt.Key.Key_Meta.value,
):
return
final_hotkey = self.format_hotkey(key, modifiers)
if final_hotkey:
self.finish_capture(final_hotkey)
def key_from_event(self, event):
key = event.key()
if key == Qt.Key.Key_unknown.value and event.nativeVirtualKey():
return event.nativeVirtualKey()
return key
def format_hotkey(self, key, modifiers):
parts = []
if modifiers & Qt.KeyboardModifier.ControlModifier:
parts.append("ctrl")
if modifiers & Qt.KeyboardModifier.AltModifier:
parts.append("alt")
if modifiers & Qt.KeyboardModifier.ShiftModifier:
parts.append("shift")
if modifiers & Qt.KeyboardModifier.MetaModifier:
parts.append("windows")
key_text = self.key_to_text(key)
if not key_text:
return ""
parts.append(key_text)
return "+".join(parts)
def key_to_text(self, key):
if Qt.Key.Key_A.value <= key <= Qt.Key.Key_Z.value:
return chr(key).lower()
if Qt.Key.Key_0.value <= key <= Qt.Key.Key_9.value:
return chr(key)
key_map = {
Qt.Key.Key_F1.value: "f1",
Qt.Key.Key_F2.value: "f2",
Qt.Key.Key_F3.value: "f3",
Qt.Key.Key_F4.value: "f4",
Qt.Key.Key_F5.value: "f5",
Qt.Key.Key_F6.value: "f6",
Qt.Key.Key_F7.value: "f7",
Qt.Key.Key_F8.value: "f8",
Qt.Key.Key_F9.value: "f9",
Qt.Key.Key_F10.value: "f10",
Qt.Key.Key_F11.value: "f11",
Qt.Key.Key_F12.value: "f12",
Qt.Key.Key_Left.value: "left",
Qt.Key.Key_Right.value: "right",
Qt.Key.Key_Up.value: "up",
Qt.Key.Key_Down.value: "down",
Qt.Key.Key_Space.value: "space",
Qt.Key.Key_Plus.value: "plus",
Qt.Key.Key_Comma.value: "comma",
Qt.Key.Key_Tab.value: "tab",
Qt.Key.Key_Return.value: "enter",
Qt.Key.Key_Enter.value: "enter",
Qt.Key.Key_Insert.value: "insert",
Qt.Key.Key_Home.value: "home",
Qt.Key.Key_End.value: "end",
Qt.Key.Key_PageUp.value: "pageup",
Qt.Key.Key_PageDown.value: "pagedown",
Qt.Key.Key_CapsLock.value: "capslock",
Qt.Key.Key_NumLock.value: "numlock",
Qt.Key.Key_ScrollLock.value: "scrolllock",
Qt.Key.Key_Print.value: "print_screen",
Qt.Key.Key_Pause.value: "pause",
}
if key in key_map:
return key_map[key]
if 0x20 <= key <= 0x7E:
return chr(key).lower()
return ""
class TrackEditor(QWidget):
changed = pyqtSignal()
KIND_INPUT = "input"
KIND_OUTPUT = "output"
KIND_APP = "app"
def __init__(self, parent=None):
super().__init__(parent)
self._loading = False
layout = QHBoxLayout(self)
layout.setContentsMargins(0, 0, 0, 0)
self.kind_combo = QComboBox()
self.kind_combo.addItems(
["Input Device", "Output (System Audio)", "Application"]
)
self.kind_combo.currentIndexChanged.connect(self.on_kind_changed)
self.input_combo = QComboBox()
self.output_combo = QComboBox()
self.app_label = QLabel("No application selected")
self.app_btn = QPushButton("Choose App...")
for widget in (self.input_combo, self.output_combo, self.app_label):
widget.setMinimumWidth(80)
self.app_btn.clicked.connect(self.open_app_picker)
self.remove_btn = QPushButton("Remove")
layout.addWidget(self.kind_combo)
layout.addWidget(self.input_combo, 1)
layout.addWidget(self.output_combo, 1)
layout.addWidget(self.app_label, 1)
layout.addWidget(self.app_btn)
layout.addWidget(self.remove_btn)
self.app_pid = None
self.app_hwnd = None
self.app_title = ""
self.app_name = ""
self.refresh_devices()
self.refresh_hw()
self.on_kind_changed(0)
def refresh_devices(self):
previous = self.input_combo.currentData()
self.input_combo.clear()
try:
cache = device_cache()
inputs = (
cache["inputs"]
if cache is not None
else get_devices(include_output=False)
)
default_index = 0
for i, m in enumerate(inputs):
self.input_combo.addItem(f"{m['name']}", m["id"])
if m.get("is_default"):
default_index = i
if self.input_combo.count() == 0:
self.input_combo.addItem("(no input devices)", None)
return
if previous is not None:
idx = self.input_combo.findData(previous)
if idx >= 0:
self.input_combo.setCurrentIndex(idx)
return
self.input_combo.setCurrentIndex(default_index)
except Exception as e:
print(f"Error refreshing devices: {e}")
def refresh_hw(self):
previous = self.output_combo.currentData()
self.output_combo.clear()
try:
cache = device_cache()
speakers = (
cache["speakers"]
if cache is not None
else get_devices(include_output=True)
)
default_index = 0
for i, s in enumerate(speakers):
self.output_combo.addItem(f"{s['name']}", s["id"])
if s.get("is_default"):
default_index = i
if self.output_combo.count() == 0:
self.output_combo.addItem("(no output devices)", None)
return
if previous is not None:
idx = self.output_combo.findData(previous)
if idx >= 0:
self.output_combo.setCurrentIndex(idx)
return
self.output_combo.setCurrentIndex(default_index)
except Exception as e:
print(f"Error refreshing hardware devices: {e}")
def on_kind_changed(self, index):
kind = self.current_kind()
self.input_combo.setVisible(kind == self.KIND_INPUT)
self.output_combo.setVisible(kind == self.KIND_OUTPUT)
self.app_label.setVisible(kind == self.KIND_APP)
self.app_btn.setVisible(kind == self.KIND_APP)
if not self._loading:
self.changed.emit()
def current_kind(self):
text = self.kind_combo.currentText()
if text.startswith("Input"):
return self.KIND_INPUT
if text.startswith("Output"):
return self.KIND_OUTPUT
return self.KIND_APP
def open_app_picker(self):
parent = self.parent()
recency = getattr(parent, "_app_recency", {}) or {}
dialog = AppPickerDialog(self, recency=recency)
if (