-
Notifications
You must be signed in to change notification settings - Fork 65
/
engine.py
3421 lines (3234 loc) · 169 KB
/
engine.py
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
from __future__ import annotations
import asyncio
import os
import sys
import tempfile
import time
import warnings
from typing import Any
from typing import Awaitable
from typing import Callable
from typing import Coroutine
from typing import List
from typing import Literal
from typing import NoReturn
from typing import Optional
from typing import overload
from typing import Tuple
from typing import Type
from typing import Union
from .._hotkey import Hotkey
from .._hotkey import Hotstring
from .._utils import type_escape
from ..directives import Directive
if sys.version_info < (3, 10):
from typing_extensions import TypeAlias
else:
from typing import TypeAlias
from ..keys import Key
from .transport import DaemonProcessTransport
from .transport import FutureResult
from .transport import Transport
from .window import Control
from .window import Window
from ahk.message import Position
sleep = time.sleep
SyncFilterFunc: TypeAlias = Callable[[Window], bool]
CoordModeTargets: TypeAlias = Union[
Literal['ToolTip'], Literal['Pixel'], Literal['Mouse'], Literal['Caret'], Literal['Menu']
]
CoordModeRelativeTo: TypeAlias = Union[Literal['Screen', 'Relative', 'Window', 'Client', '']]
CoordMode: TypeAlias = Union[CoordModeTargets, Tuple[CoordModeTargets, CoordModeRelativeTo]]
MatchModes: TypeAlias = Literal[1, 2, 3, 'RegEx', '']
MatchSpeeds: TypeAlias = Literal['Fast', 'Slow', '']
TitleMatchMode: TypeAlias = Optional[
Union[MatchModes, MatchSpeeds, Tuple[Union[MatchModes, MatchSpeeds], Union[MatchSpeeds, MatchModes]]]
]
_BUTTONS: dict[Union[str, int], str] = {
1: 'L',
2: 'R',
3: 'M',
'left': 'L',
'right': 'R',
'middle': 'M',
'wheelup': 'WU',
'wheeldown': 'WD',
'wheelleft': 'WL',
'wheelright': 'WR',
}
MouseButton: TypeAlias = Union[
int,
Literal[
'L',
'R',
'M',
'left',
'right',
'middle',
'wheelup',
'WU',
'wheeldown',
'WD',
'wheelleft',
'WL',
'wheelright',
'WR',
],
]
SyncPropertyReturnTupleIntInt: TypeAlias = Tuple[int, int]
SyncPropertyReturnOptionalAsyncWindow: TypeAlias = Optional[Window]
_PROPERTY_DEPRECATION_WARNING_MESSAGE = 'Use of the {0} property is not recommended (in the async API only) and may be removed in a future version. Use the get_{0} method instead'
def _resolve_button(button: Union[str, int]) -> str:
"""
Resolve a string of a button name to a canonical name used for AHK script
:param button:
:type button: str
:return:
"""
if isinstance(button, str):
button = button.lower()
if button in _BUTTONS:
resolved_button = _BUTTONS[button]
elif isinstance(button, int) and button > 3:
# for addtional mouse buttons
resolved_button = f'X{button-3}'
else:
assert isinstance(button, str)
resolved_button = button
return resolved_button
class AHK:
def __init__(
self,
*,
TransportClass: Optional[Type[Transport]] = None,
directives: Optional[list[Directive | Type[Directive]]] = None,
executable_path: str = '',
):
if TransportClass is None:
TransportClass = DaemonProcessTransport
assert TransportClass is not None
transport = TransportClass(executable_path=executable_path, directives=directives)
self._transport: Transport = transport
def add_hotkey(
self, keyname: str, callback: Callable[[], Any], ex_handler: Optional[Callable[[str, Exception], Any]] = None
) -> None:
"""
Register a function to be called when a hotkey is pressed.
Key notes:
- You must call the `start_hotkeys` method for the hotkeys to be active
- All hotkeys run in a single AHK process instance (but Python callbacks also get their own thread and can run simultaneously)
- If you add a hotkey after the hotkey thread/instance is active, it will be restarted automatically
- `async` functions are not directly supported as callbacks, however you may write a synchronous function that calls `asyncio.run`/`loop.create_task` etc.
:param keyname: the key trigger for the hotkey, such as ``#n`` (win+n)
:param callback: callback function to call when the hotkey is triggered
:param ex_handler: a function which accepts two parameters: the keyname for the hotkey and the exception raised by the callback function.
:return:
"""
hotkey = Hotkey(keyname, callback, ex_handler=ex_handler)
with warnings.catch_warnings(record=True) as caught_warnings:
self._transport.add_hotkey(hotkey=hotkey)
if caught_warnings:
for warning in caught_warnings:
warnings.warn(warning.message, warning.category, stacklevel=2)
return None
def add_hotstring(
self,
trigger: str,
replacement_or_callback: Union[str, Callable[[], Any]],
ex_handler: Optional[Callable[[str, Exception], Any]] = None,
options: str = '',
) -> None:
"""
Register a hotstring, e.g., `::btw::by the way`
Key notes:
- You must call the `start_hotkeys` method for registered hotstrings to be active
- All hotstrings (and hotkeys) run in a single AHK process instance separate from other AHK processes.
:param trigger: the trigger phrase for the hotstring, e.g., ``btw``
:param replacement_or_callback: the replacement phrase (e.g., ``by the way``) or a Python callable to execute in response to the hotstring trigger
:param ex_handler: a function which accepts two parameters: the hotstring and the exception raised by the callback function.
:param options: the hotstring options -- same meanings as in AutoHotkey.
:return:
"""
hotstring = Hotstring(trigger, replacement_or_callback, ex_handler=ex_handler, options=options)
with warnings.catch_warnings(record=True) as caught_warnings:
self._transport.add_hotstring(hotstring=hotstring)
if caught_warnings:
for warning in caught_warnings:
warnings.warn(warning.message, warning.category, stacklevel=2)
return None
def set_title_match_mode(self, title_match_mode: TitleMatchMode, /) -> None:
"""
Sets the default title match mode
Does not affect methods called with ``blocking=True`` (because these run in a separate AHK process)
Reference: https://www.autohotkey.com/docs/commands/SetTitleMatchMode.htm
:param title_match_mode: the match mode (and/or match speed) to set as the default title match mode. Can be 1, 2, 3, 'Regex', 'Fast', 'Slow' or a tuple of these.
:return: None
"""
args = []
if isinstance(title_match_mode, tuple):
(match_mode, match_speed) = title_match_mode
elif title_match_mode in (1, 2, 3, 'RegEx'):
match_mode = title_match_mode
match_speed = ''
elif title_match_mode in ('Fast', 'Slow'):
match_mode = ''
match_speed = title_match_mode
else:
raise ValueError(
f"Invalid value for title_match_mode argument. Expected 1, 2, 3, 'RegEx', 'Fast', 'Slow' or a tuple of these. Got {title_match_mode!r}"
)
args.append(str(match_mode))
args.append(str(match_speed))
self._transport.function_call('AHKSetTitleMatchMode', args)
return None
def get_title_match_mode(self) -> str:
"""
Get the title match mode.
I.E. the current value of ``A_TitleMatchMode``
"""
resp = self._transport.function_call('AHKGetTitleMatchMode')
return resp
def get_title_match_speed(self) -> str:
"""
Get the title match mode speed.
I.E. the current value of ``A_TitleMatchModeSpeed``
"""
resp = self._transport.function_call('AHKGetTitleMatchSpeed')
return resp
def set_coord_mode(self, target: CoordModeTargets, relative_to: CoordModeRelativeTo = 'Screen') -> None:
"""
Analog of `CoordMode <https://www.autohotkey.com/docs/commands/CoordMode.htm>`_
"""
args = [str(target), str(relative_to)]
self._transport.function_call('AHKSetCoordMode', args)
return None
def get_coord_mode(self, target: CoordModeTargets) -> str:
"""
Analog for ``A_CoordMode<target>``
"""
args = [str(target)]
resp = self._transport.function_call('AHKGetCoordMode', args)
return resp
# fmt: off
@overload
def control_click(self, button: Literal['L', 'R', 'M', 'LEFT', 'RIGHT', 'MIDDLE'] = 'L', click_count: int = 1, options: str = '', control: str = '', title: str = '', text: str = '', exclude_title: str = '', exclude_text: str = '', *, title_match_mode: Optional[TitleMatchMode] = None, detect_hidden_windows: Optional[bool] = None) -> None: ...
@overload
def control_click(self, button: Literal['L', 'R', 'M', 'LEFT', 'RIGHT', 'MIDDLE'] = 'L', click_count: int = 1, options: str = '', control: str = '', title: str = '', text: str = '', exclude_title: str = '', exclude_text: str = '', *, title_match_mode: Optional[TitleMatchMode] = None, detect_hidden_windows: Optional[bool] = None, blocking: Literal[False]) -> FutureResult[None]: ...
@overload
def control_click(self, button: Literal['L', 'R', 'M', 'LEFT', 'RIGHT', 'MIDDLE'] = 'L', click_count: int = 1, options: str = '', control: str = '', title: str = '', text: str = '', exclude_title: str = '', exclude_text: str = '', *, title_match_mode: Optional[TitleMatchMode] = None, detect_hidden_windows: Optional[bool] = None, blocking: Literal[True]) -> None: ...
@overload
def control_click(self, button: Literal['L', 'R', 'M', 'LEFT', 'RIGHT', 'MIDDLE'] = 'L', click_count: int = 1, options: str = '', control: str = '', title: str = '', text: str = '', exclude_title: str = '', exclude_text: str = '', *, title_match_mode: Optional[TitleMatchMode] = None, detect_hidden_windows: Optional[bool] = None, blocking: bool = True) -> Union[None, FutureResult[None]]: ...
# fmt: on
def control_click(
self,
button: Literal['L', 'R', 'M', 'LEFT', 'RIGHT', 'MIDDLE'] = 'L',
click_count: int = 1,
options: str = '',
control: str = '',
title: str = '',
text: str = '',
exclude_title: str = '',
exclude_text: str = '',
*,
title_match_mode: Optional[TitleMatchMode] = None,
detect_hidden_windows: Optional[bool] = None,
blocking: bool = True,
) -> Union[None, FutureResult[None]]:
"""
Analog for `ControlClick <https://www.autohotkey.com/docs/commands/ControlClick.htm>`_
"""
args = [control, title, text, str(button), str(click_count), options, exclude_title, exclude_text]
if detect_hidden_windows is not None:
if detect_hidden_windows is True:
args.append('On')
elif detect_hidden_windows is False:
args.append('Off')
else:
raise TypeError(
f'Invalid value for parameter detect_hidden_windows. Expected boolean or None, got {detect_hidden_windows!r}'
)
else:
args.append('')
if title_match_mode is not None:
if isinstance(title_match_mode, tuple):
match_mode, match_speed = title_match_mode
elif title_match_mode in (1, 2, 3, 'RegEx'):
match_mode = title_match_mode
match_speed = ''
elif title_match_mode in ('Fast', 'Slow'):
match_mode = ''
match_speed = title_match_mode
else:
raise ValueError(
f"Invalid value for title_match_mode argument. Expected 1, 2, 3, 'RegEx', 'Fast', 'Slow' or a tuple of these. Got {title_match_mode!r}"
)
args.append(str(match_mode))
args.append(str(match_speed))
else:
args.append('')
args.append('')
resp = self._transport.function_call('AHKControlClick', args=args, blocking=blocking)
return resp
# fmt: off
@overload
def control_get_text(self, *, control: str = '', title: str = '', text: str = '', exclude_title: str = '', exclude_text: str = '', title_match_mode: Optional[TitleMatchMode] = None, detect_hidden_windows: Optional[bool] = None) -> str: ...
@overload
def control_get_text(self, *, control: str = '', title: str = '', text: str = '', exclude_title: str = '', exclude_text: str = '', title_match_mode: Optional[TitleMatchMode] = None, detect_hidden_windows: Optional[bool] = None, blocking: Literal[False]) -> FutureResult[str]: ...
@overload
def control_get_text(self, *, control: str = '', title: str = '', text: str = '', exclude_title: str = '', exclude_text: str = '', title_match_mode: Optional[TitleMatchMode] = None, detect_hidden_windows: Optional[bool] = None, blocking: Literal[True]) -> str: ...
@overload
def control_get_text(self, *, control: str = '', title: str = '', text: str = '', exclude_title: str = '', exclude_text: str = '', title_match_mode: Optional[TitleMatchMode] = None, detect_hidden_windows: Optional[bool] = None, blocking: bool = True) -> Union[str, FutureResult[str]]: ...
# fmt: on
def control_get_text(
self,
*,
control: str = '',
title: str = '',
text: str = '',
exclude_title: str = '',
exclude_text: str = '',
title_match_mode: Optional[TitleMatchMode] = None,
detect_hidden_windows: Optional[bool] = None,
blocking: bool = True,
) -> Union[str, FutureResult[str]]:
"""
Analog for `ControlGetText <https://www.autohotkey.com/docs/commands/ControlGetText.htm>`_
"""
args = [control, title, text, exclude_title, exclude_text]
if detect_hidden_windows is not None:
if detect_hidden_windows is True:
args.append('On')
elif detect_hidden_windows is False:
args.append('Off')
else:
raise TypeError(
f'Invalid value for parameter detect_hidden_windows. Expected boolean or None, got {detect_hidden_windows!r}'
)
else:
args.append('')
if title_match_mode is not None:
if isinstance(title_match_mode, tuple):
match_mode, match_speed = title_match_mode
elif title_match_mode in (1, 2, 3, 'RegEx'):
match_mode = title_match_mode
match_speed = ''
elif title_match_mode in ('Fast', 'Slow'):
match_mode = ''
match_speed = title_match_mode
else:
raise ValueError(
f"Invalid value for title_match_mode argument. Expected 1, 2, 3, 'RegEx', 'Fast', 'Slow' or a tuple of these. Got {title_match_mode!r}"
)
args.append(str(match_mode))
args.append(str(match_speed))
else:
args.append('')
args.append('')
resp = self._transport.function_call('AHKControlGetText', args, blocking=blocking)
return resp
# fmt: off
@overload
def control_get_position(self, control: str = '', title: str = '', text: str = '', exclude_title: str = '', exclude_text: str = '', *, title_match_mode: Optional[TitleMatchMode] = None, detect_hidden_windows: Optional[bool] = None) -> Position: ...
@overload
def control_get_position(self, control: str = '', title: str = '', text: str = '', exclude_title: str = '', exclude_text: str = '', *, title_match_mode: Optional[TitleMatchMode] = None, detect_hidden_windows: Optional[bool] = None, blocking: Literal[False]) -> FutureResult[Position]: ...
@overload
def control_get_position(self, control: str = '', title: str = '', text: str = '', exclude_title: str = '', exclude_text: str = '', *, title_match_mode: Optional[TitleMatchMode] = None, detect_hidden_windows: Optional[bool] = None, blocking: Literal[True]) -> Position: ...
@overload
def control_get_position(self, control: str = '', title: str = '', text: str = '', exclude_title: str = '', exclude_text: str = '', *, title_match_mode: Optional[TitleMatchMode] = None, detect_hidden_windows: Optional[bool] = None, blocking: bool = True) -> Union[Position, FutureResult[Position]]: ...
# fmt: on
def control_get_position(
self,
control: str = '',
title: str = '',
text: str = '',
exclude_title: str = '',
exclude_text: str = '',
*,
title_match_mode: Optional[TitleMatchMode] = None,
detect_hidden_windows: Optional[bool] = None,
blocking: bool = True,
) -> Union[Position, FutureResult[Position]]:
"""
Analog to `ControlGetPos <https://www.autohotkey.com/docs/commands/ControlGetPos.htm>`_
"""
args = [control, title, text, exclude_title, exclude_text]
if detect_hidden_windows is not None:
if detect_hidden_windows is True:
args.append('On')
elif detect_hidden_windows is False:
args.append('Off')
else:
raise TypeError(
f'Invalid value for parameter detect_hidden_windows. Expected boolean or None, got {detect_hidden_windows!r}'
)
else:
args.append('')
if title_match_mode is not None:
if isinstance(title_match_mode, tuple):
match_mode, match_speed = title_match_mode
elif title_match_mode in (1, 2, 3, 'RegEx'):
match_mode = title_match_mode
match_speed = ''
elif title_match_mode in ('Fast', 'Slow'):
match_mode = ''
match_speed = title_match_mode
else:
raise ValueError(
f"Invalid value for title_match_mode argument. Expected 1, 2, 3, 'RegEx', 'Fast', 'Slow' or a tuple of these. Got {title_match_mode!r}"
)
args.append(str(match_mode))
args.append(str(match_speed))
else:
args.append('')
args.append('')
resp = self._transport.function_call('AHKControlGetPos', args, blocking=blocking)
return resp
# fmt: off
@overload
def control_send(self, keys: str, control: str = '', title: str = '', text: str = '', exclude_title: str = '', exclude_text: str = '', *, title_match_mode: Optional[TitleMatchMode] = None, detect_hidden_windows: Optional[bool] = None) -> None: ...
@overload
def control_send(self, keys: str, control: str = '', title: str = '', text: str = '', exclude_title: str = '', exclude_text: str = '', *, title_match_mode: Optional[TitleMatchMode] = None, detect_hidden_windows: Optional[bool] = None, blocking: Literal[False]) -> FutureResult[None]: ...
@overload
def control_send(self, keys: str, control: str = '', title: str = '', text: str = '', exclude_title: str = '', exclude_text: str = '', *, title_match_mode: Optional[TitleMatchMode] = None, detect_hidden_windows: Optional[bool] = None, blocking: Literal[True]) -> None: ...
@overload
def control_send(self, keys: str, control: str = '', title: str = '', text: str = '', exclude_title: str = '', exclude_text: str = '', *, title_match_mode: Optional[TitleMatchMode] = None, detect_hidden_windows: Optional[bool] = None, blocking: bool = True) -> Union[None, FutureResult[None]]: ...
# fmt: on
def control_send(
self,
keys: str,
control: str = '',
title: str = '',
text: str = '',
exclude_title: str = '',
exclude_text: str = '',
*,
title_match_mode: Optional[TitleMatchMode] = None,
detect_hidden_windows: Optional[bool] = None,
blocking: bool = True,
) -> Union[None, FutureResult[None]]:
"""
Analog for `ControlSend <https://www.autohotkey.com/docs/commands/ControlSend.htm>`_
"""
args = [control, keys, title, text, exclude_title, exclude_text]
if detect_hidden_windows is not None:
if detect_hidden_windows is True:
args.append('On')
elif detect_hidden_windows is False:
args.append('Off')
else:
raise TypeError(
f'Invalid value for parameter detect_hidden_windows. Expected boolean or None, got {detect_hidden_windows!r}'
)
else:
args.append('')
if title_match_mode is not None:
if isinstance(title_match_mode, tuple):
match_mode, match_speed = title_match_mode
elif title_match_mode in (1, 2, 3, 'RegEx'):
match_mode = title_match_mode
match_speed = ''
elif title_match_mode in ('Fast', 'Slow'):
match_mode = ''
match_speed = title_match_mode
else:
raise ValueError(
f"Invalid value for title_match_mode argument. Expected 1, 2, 3, 'RegEx', 'Fast', 'Slow' or a tuple of these. Got {title_match_mode!r}"
)
args.append(str(match_mode))
args.append(str(match_speed))
else:
args.append('')
args.append('')
resp = self._transport.function_call('AHKControlSend', args, blocking=blocking)
return resp
# TODO: raw option for control_send
def start_hotkeys(self) -> None:
"""
Start the Autohotkey process for triggering hotkeys
"""
return self._transport.start_hotkeys()
def stop_hotkeys(self) -> None:
"""
Stop the Autohotkey process for triggering hotkeys/hotstrings
"""
return self._transport.stop_hotkeys()
def set_detect_hidden_windows(self, value: bool) -> None:
"""
Analog for `DetectHiddenWindows <https://www.autohotkey.com/docs/commands/DetectHiddenWindows.htm>`_
:param value: The setting value. ``True`` to turn on hidden window detection, ``False`` to turn it off.
"""
if value not in (True, False):
raise TypeError(f'detect hidden windows must be a boolean, got object of type {type(value)}')
args = []
if value is True:
args.append('On')
else:
args.append('Off')
self._transport.function_call('AHKSetDetectHiddenWindows', args=args)
return None
@staticmethod
def _format_win_args(
title: str,
text: str,
exclude_title: str,
exclude_text: str,
title_match_mode: Optional[TitleMatchMode] = None,
detect_hidden_windows: Optional[bool] = None,
) -> List[str]:
args = [title, text, exclude_title, exclude_text]
if detect_hidden_windows is not None:
if detect_hidden_windows is True:
args.append('On')
elif detect_hidden_windows is False:
args.append('Off')
else:
raise TypeError(
f'Invalid value for parameter detect_hidden_windows. Expected boolean or None, got {detect_hidden_windows!r}'
)
else:
args.append('')
if title_match_mode is not None:
if isinstance(title_match_mode, tuple):
match_mode, match_speed = title_match_mode
elif title_match_mode in (1, 2, 3, 'RegEx'):
match_mode = title_match_mode
match_speed = ''
elif title_match_mode in ('Fast', 'Slow'):
match_mode = ''
match_speed = title_match_mode
else:
raise ValueError(
f"Invalid value for title_match_mode argument. Expected 1, 2, 3, 'RegEx', 'Fast', 'Slow' or a tuple of these. Got {title_match_mode!r}"
)
args.append(str(match_mode))
args.append(str(match_speed))
else:
args.append('')
args.append('')
return args
# fmt: off
@overload
def list_windows(self, title: str = '', text: str = '', exclude_title: str = '', exclude_text: str = '', *, title_match_mode: Optional[TitleMatchMode] = None, detect_hidden_windows: Optional[bool] = None) -> List[Window]: ...
@overload
def list_windows(self, title: str = '', text: str = '', exclude_title: str = '', exclude_text: str = '', *, title_match_mode: Optional[TitleMatchMode] = None, detect_hidden_windows: Optional[bool] = None, blocking: Literal[False]) -> Union[List[Window], FutureResult[List[Window]]]: ...
@overload
def list_windows(self, title: str = '', text: str = '', exclude_title: str = '', exclude_text: str = '', *, title_match_mode: Optional[TitleMatchMode] = None, detect_hidden_windows: Optional[bool] = None, blocking: Literal[True]) -> List[Window]: ...
@overload
def list_windows(self, title: str = '', text: str = '', exclude_title: str = '', exclude_text: str = '', *, title_match_mode: Optional[TitleMatchMode] = None, detect_hidden_windows: Optional[bool] = None, blocking: bool = True,) -> Union[List[Window], FutureResult[List[Window]]]: ...
# fmt: on
def list_windows(
self,
title: str = '',
text: str = '',
exclude_title: str = '',
exclude_text: str = '',
*,
title_match_mode: Optional[TitleMatchMode] = None,
detect_hidden_windows: Optional[bool] = None,
blocking: bool = True,
) -> Union[List[Window], FutureResult[List[Window]]]:
"""
Enumerate all windows matching the criteria.
Analog for `WinGet List subcommand <https://www.autohotkey.com/docs/v1/lib/WinGet.htm#List>_`
"""
args = self._format_win_args(
title=title,
text=text,
exclude_title=exclude_title,
exclude_text=exclude_text,
title_match_mode=title_match_mode,
detect_hidden_windows=detect_hidden_windows,
)
resp = self._transport.function_call('AHKWindowList', args, engine=self, blocking=blocking)
return resp
# fmt: off
@overload
def get_mouse_position(self, coord_mode: Optional[CoordModeRelativeTo] = None, *, blocking: Literal[True]) -> Tuple[int, int]: ...
@overload
def get_mouse_position(self, coord_mode: Optional[CoordModeRelativeTo] = None, *, blocking: Literal[False]) -> FutureResult[Tuple[int, int]]: ...
@overload
def get_mouse_position(self, coord_mode: Optional[CoordModeRelativeTo] = None) -> Tuple[int, int]: ...
@overload
def get_mouse_position(self, coord_mode: Optional[CoordModeRelativeTo] = None, *, blocking: bool = True) -> Union[Tuple[int, int], FutureResult[Tuple[int, int]]]: ...
# fmt: on
def get_mouse_position(
self, coord_mode: Optional[CoordModeRelativeTo] = None, *, blocking: bool = True
) -> Union[Tuple[int, int], FutureResult[Tuple[int, int]]]:
"""
Analog for `MouseGetPos <https://www.autohotkey.com/docs/commands/MouseGetPos.htm>`_
"""
if coord_mode:
args = [str(coord_mode)]
else:
args = []
resp = self._transport.function_call('AHKMouseGetPos', args, blocking=blocking)
return resp
@property
def mouse_position(self) -> SyncPropertyReturnTupleIntInt:
"""
Convenience property for :py:meth:`get_mouse_position`
Setter accepts a tuple of x,y coordinates passed to :py:meth:`mouse_mouse`
"""
return self.get_mouse_position()
@mouse_position.setter
def mouse_position(self, new_position: Tuple[int, int]) -> None:
"""
Convenience setter for ``mouse_move``
:param new_position: a tuple of x,y coordinates to move to
"""
x, y = new_position
return self.mouse_move(x=x, y=y, speed=0, relative=False)
# fmt: off
@overload
def mouse_move(self, x: Optional[Union[str, int]] = None, y: Optional[Union[str, int]] = None, *, speed: Optional[int] = None, relative: bool = False) -> None: ...
@overload
def mouse_move(self, x: Optional[Union[str, int]] = None, y: Optional[Union[str, int]] = None, *, blocking: Literal[True], speed: Optional[int] = None, relative: bool = False) -> None: ...
@overload
def mouse_move(self, x: Optional[Union[str, int]] = None, y: Optional[Union[str, int]] = None, *, blocking: Literal[False], speed: Optional[int] = None, relative: bool = False, ) -> FutureResult[None]: ...
@overload
def mouse_move(self, x: Optional[Union[str, int]] = None, y: Optional[Union[str, int]] = None, *, speed: Optional[int] = None, relative: bool = False, blocking: bool = True) -> Union[None, FutureResult[None]]: ...
# fmt: on
def mouse_move(
self,
x: Optional[Union[str, int]] = None,
y: Optional[Union[str, int]] = None,
*,
speed: Optional[int] = None,
relative: bool = False,
blocking: bool = True,
) -> Union[None, FutureResult[None]]:
"""
Analog for `MouseMove <https://www.autohotkey.com/docs/commands/MouseMove.htm>`_
"""
if relative and (x is None or y is None):
x = x or 0
y = y or 0
elif not relative and (x is None or y is None):
posx, posy = self.get_mouse_position()
x = x or posx
y = y or posy
if speed is None:
speed = 2
args = [str(x), str(y), str(speed)]
if relative:
args.append('R')
resp = self._transport.function_call('AHKMouseMove', args, blocking=blocking)
return resp
def a_run_script(self, *args: Any, **kwargs: Any) -> Union[str, FutureResult[str]]:
"""
Deprecated. Use :py:meth:`run_script` instead.
"""
warnings.warn('a_run_script is deprecated. Use run_script instead.', DeprecationWarning, stacklevel=2)
return self.run_script(*args, **kwargs)
# fmt: off
@overload
def get_active_window(self) -> Optional[Window]: ...
@overload
def get_active_window(self, blocking: Literal[True]) -> Optional[Window]: ...
@overload
def get_active_window(self, blocking: Literal[False]) -> FutureResult[Optional[Window]]: ...
@overload
def get_active_window(self, blocking: bool = True) -> Union[Optional[Window], FutureResult[Optional[Window]]]: ...
# fmt: on
def get_active_window(
self, blocking: bool = True
) -> Union[Optional[Window], FutureResult[Optional[Window]]]:
"""
Gets the currently active window.
"""
return self.win_get(
title='A', detect_hidden_windows=False, title_match_mode=(1, 'Fast'), blocking=blocking
)
@property
def active_window(self) -> SyncPropertyReturnOptionalAsyncWindow:
"""
Gets the currently active window. Convenience property for :py:meth:`get_active_window`
"""
return self.get_active_window()
def find_windows(
self,
func: Optional[SyncFilterFunc] = None,
*,
title_match_mode: Optional[TitleMatchMode] = None,
title: str = '',
text: str = '',
exclude_title: str = '',
exclude_text: str = '',
exact: Optional[bool] = None,
) -> List[Window]:
if exact is not None and title_match_mode is not None:
raise TypeError('exact and match_mode parameters are mutually exclusive')
if exact is not None:
warnings.warn('exact parameter is deprecated. Use match_mode=3 instead', stacklevel=2)
if exact:
title_match_mode = (3, 'Fast')
else:
title_match_mode = (1, 'Fast')
elif title_match_mode is None:
title_match_mode = (1, 'Fast')
windows = self.list_windows(
title=title,
text=text,
exclude_title=exclude_title,
exclude_text=exclude_text,
title_match_mode=title_match_mode,
)
if func is None:
return windows
else:
ret: List[Window] = []
for win in windows:
match = func(win)
if match:
ret.append(win)
return ret
def find_windows_by_class(
self, class_name: str, *, exact: Optional[bool] = None, title_match_mode: Optional[TitleMatchMode] = None
) -> List[Window]:
with warnings.catch_warnings(record=True) as caught_warnings:
ret = self.find_windows(
title=f'ahk_class {class_name}', title_match_mode=title_match_mode, exact=exact
)
if caught_warnings:
for warning in caught_warnings:
warnings.warn(warning.message, warning.category, stacklevel=2)
return ret
def find_windows_by_text(
self, text: str, exact: Optional[bool] = None, title_match_mode: Optional[TitleMatchMode] = None
) -> List[Window]:
with warnings.catch_warnings(record=True) as caught_warnings:
ret = self.find_windows(text=text, exact=exact, title_match_mode=title_match_mode)
if caught_warnings:
for warning in caught_warnings:
warnings.warn(warning.message, warning.category, stacklevel=2)
return ret
def find_windows_by_title(
self, title: str, exact: Optional[bool] = None, title_match_mode: Optional[TitleMatchMode] = None
) -> List[Window]:
with warnings.catch_warnings(record=True) as caught_warnings:
ret = self.find_windows(title=title, exact=exact, title_match_mode=title_match_mode)
if caught_warnings:
for warning in caught_warnings:
warnings.warn(warning.message, warning.category, stacklevel=2)
return ret
def find_window(
self,
func: Optional[SyncFilterFunc] = None,
*,
title_match_mode: Optional[TitleMatchMode] = None,
title: str = '',
text: str = '',
exclude_title: str = '',
exclude_text: str = '',
exact: Optional[bool] = None,
) -> Optional[Window]:
with warnings.catch_warnings(record=True) as caught_warnings:
windows = self.find_windows(
func,
title=title,
text=text,
exclude_title=exclude_title,
exclude_text=exclude_text,
exact=exact,
title_match_mode=title_match_mode,
)
if caught_warnings:
for warning in caught_warnings:
warnings.warn(warning.message, warning.category, stacklevel=2)
return windows[0] if windows else None
def find_window_by_class(
self, class_name: str, exact: Optional[bool] = None, title_match_mode: Optional[TitleMatchMode] = None
) -> Optional[Window]:
with warnings.catch_warnings(record=True) as caught_warnings:
windows = self.find_windows_by_class(
class_name=class_name, exact=exact, title_match_mode=title_match_mode
)
if caught_warnings:
for warning in caught_warnings:
warnings.warn(warning.message, warning.category, stacklevel=2)
return windows[0] if windows else None
def find_window_by_text(
self, text: str, exact: Optional[bool] = None, title_match_mode: Optional[TitleMatchMode] = None
) -> Optional[Window]:
with warnings.catch_warnings(record=True) as caught_warnings:
windows = self.find_windows_by_text(text=text, exact=exact, title_match_mode=title_match_mode)
if caught_warnings:
for warning in caught_warnings:
warnings.warn(warning.message, warning.category, stacklevel=2)
return windows[0] if windows else None
def find_window_by_title(
self, title: str, exact: Optional[bool] = None, title_match_mode: Optional[TitleMatchMode] = None
) -> Optional[Window]:
with warnings.catch_warnings(record=True) as caught_warnings:
windows = self.find_windows_by_title(title=title, exact=exact, title_match_mode=title_match_mode)
if caught_warnings:
for warning in caught_warnings:
warnings.warn(warning.message, warning.category, stacklevel=2)
return windows[0] if windows else None
def get_volume(self, device_number: int = 1) -> float:
"""
Analog for `SoundGetWaveVolume <https://www.autohotkey.com/docs/commands/SoundGetWaveVolume.htm>`_
"""
args = [str(device_number)]
response = self._transport.function_call('AHKGetVolume', args)
return response
# fmt: off
@overload
def key_down(self, key: Union[str, Key]) -> None: ...
@overload
def key_down(self, key: Union[str, Key], *, blocking: Literal[True]) -> None: ...
@overload
def key_down(self, key: Union[str, Key], *, blocking: Literal[False]) -> FutureResult[None]: ...
@overload
def key_down(self, key: Union[str, Key], *, blocking: bool = True) -> Union[None, FutureResult[None]]: ...
# fmt: on
def key_down(self, key: Union[str, Key], *, blocking: bool = True) -> Union[None, FutureResult[None]]:
"""
Shortcut for :py:meth:`send_input` but transforms specified key to perform a key "DOWN" only (no release)
"""
if isinstance(key, str):
key = Key(key_name=key)
if blocking:
self.send_input(key.DOWN, blocking=True)
return None
else:
return self.send_input(key.DOWN, blocking=False)
# fmt: off
@overload
def key_press(self, key: Union[str, Key], *, release: bool = True) -> None: ...
@overload
def key_press(self, key: Union[str, Key], *, blocking: Literal[True], release: bool = True) -> None: ...
@overload
def key_press(self, key: Union[str, Key], *, blocking: Literal[False], release: bool = True) -> FutureResult[None]: ...
@overload
def key_press(self, key: Union[str, Key], *, release: bool = True, blocking: bool = True) -> Union[None, FutureResult[None]]: ...
# fmt: on
def key_press(
self, key: Union[str, Key], *, release: bool = True, blocking: bool = True
) -> Union[None, FutureResult[None]]:
"""
Press (and release) a key. Sends `:py:meth:`key_down` then, if ``release`` is ``True`` (the default), sends
:py:meth:`key_up` subsequently.
"""
if blocking:
self.key_down(key, blocking=True)
if release:
self.key_up(key, blocking=True)
return None
else:
d = self.key_down(key, blocking=False)
if release:
return self.key_up(key, blocking=False)
return d
# fmt: off
@overload
def key_release(self, key: Union[str, Key]) -> None: ...
@overload
def key_release(self, key: Union[str, Key], *, blocking: Literal[True]) -> None: ...
@overload
def key_release(self, key: Union[str, Key], *, blocking: Literal[False]) -> FutureResult[None]: ...
@overload
def key_release(self, key: Union[str, Key], *, blocking: bool = True) -> Union[None, FutureResult[None]]: ...
# fmt: on
def key_release(self, key: Union[str, Key], *, blocking: bool = True) -> Union[None, FutureResult[None]]:
"""
Alias for :py:meth:`key_up`
"""
if blocking:
self.key_up(key=key, blocking=True)
return None
else:
return self.key_up(key=key, blocking=False)
# fmt: off
@overload
def key_state(self, key_name: str, *, mode: Optional[Literal['T', 'P']] = None) -> Union[float, int, str, None]: ...
@overload
def key_state(self, key_name: str, *, mode: Optional[Literal['T', 'P']] = None, blocking: Literal[True]) -> Union[float, int, str, None]: ...
@overload
def key_state(self, key_name: str, *, mode: Optional[Literal['T', 'P']] = None, blocking: Literal[False]) -> Union[FutureResult[str], FutureResult[int], FutureResult[float], FutureResult[None]]: ...
@overload
def key_state(self, key_name: str, *, mode: Optional[Literal['T', 'P']] = None, blocking: bool = True) -> Union[None, FutureResult[None], Union[str, FutureResult[str]], Union[int, FutureResult[int]], Union[float, FutureResult[float]]]: ...
# fmt: on
def key_state(
self, key_name: str, *, mode: Optional[Literal['T', 'P']] = None, blocking: bool = True
) -> Union[
int,
float,
str,
None,
FutureResult[str],
FutureResult[int],
FutureResult[float],
FutureResult[None],
]:
"""
Analog for `GetKeyState <https://www.autohotkey.com/docs/commands/GetKeyState.htm#command>`_
"""
args: List[str] = [key_name]
if mode is not None:
if mode not in ('T', 'P'):
raise ValueError(f'Invalid value for mode parameter. Mode must be `T` or `P`. Got {mode!r}')
args.append(mode)
resp = self._transport.function_call('AHKKeyState', args, blocking=blocking)
return resp
# fmt: off
@overload
def key_up(self, key: Union[str, Key]) -> None: ...
@overload
def key_up(self, key: Union[str, Key], *, blocking: Literal[True]) -> None: ...
@overload
def key_up(self, key: Union[str, Key], *, blocking: Literal[False]) -> FutureResult[None]: ...
@overload
def key_up(self, key: Union[str, Key], blocking: bool = True) -> Union[None, FutureResult[None]]: ...
# fmt: on
def key_up(self, key: Union[str, Key], blocking: bool = True) -> Union[None, FutureResult[None]]:
"""
Shortcut for :py:meth:`send_input` but transforms specified key to perform a key "UP" only. Useful if the key
was previously pressed down but not released.
"""
if isinstance(key, str):
key = Key(key_name=key)
if blocking:
self.send_input(key.UP, blocking=True)
return None
else:
return self.send_input(key.UP, blocking=False)
# fmt: off
@overload
def key_wait(self, key_name: str, *, timeout: Optional[int] = None, logical_state: bool = False, released: bool = False) -> int: ...
@overload
def key_wait(self, key_name: str, *, blocking: Literal[True], timeout: Optional[int] = None, logical_state: bool = False, released: bool = False) -> int: ...
@overload
def key_wait(self, key_name: str, *, blocking: Literal[False], timeout: Optional[int] = None, logical_state: bool = False, released: bool = False) -> FutureResult[int]: ...
@overload
def key_wait(self, key_name: str, *, timeout: Optional[int] = None, logical_state: bool = False, released: bool = False, blocking: bool = True) -> Union[int, FutureResult[int]]: ...
# fmt: on
def key_wait(
self,
key_name: str,
*,
timeout: Optional[int] = None,
logical_state: bool = False,
released: bool = False,
blocking: bool = True,
) -> Union[int, FutureResult[int]]:
"""
Analog for `KeyWait <https://www.autohotkey.com/docs/commands/KeyWait.htm>`_