-
Notifications
You must be signed in to change notification settings - Fork 65
/
transport.py
936 lines (841 loc) · 48.2 KB
/
transport.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
from __future__ import annotations
import asyncio.subprocess
import atexit
import os
import re
import subprocess
import sys
import tempfile
import threading
import warnings
from abc import ABC
from abc import abstractmethod
from io import BytesIO
from typing import Any
from typing import Callable
from typing import Generic
from typing import List
from typing import Literal
from typing import Optional
from typing import overload
from typing import Protocol
from typing import runtime_checkable
from typing import Tuple
from typing import Type
from typing import TYPE_CHECKING
from typing import TypeVar
from typing import Union
if TYPE_CHECKING:
from ahk import AsyncControl
from ahk import AsyncWindow
if sys.version_info < (3, 10):
from typing_extensions import TypeAlias, TypeGuard
else:
from typing import TypeAlias, TypeGuard
import jinja2
from ahk.extensions import Extension, _resolve_includes
from ahk._hotkey import ThreadedHotkeyTransport, Hotkey, Hotstring
from ahk.message import RequestMessage
from ahk.message import ResponseMessage
from ahk.message import Position
from ahk.message import _message_registry
from ahk._constants import (
DAEMON_SCRIPT_TEMPLATE as _DAEMON_SCRIPT_TEMPLATE,
DAEMON_SCRIPT_V2_TEMPLATE as _DAEMON_SCRIPT_V2_TEMPLATE,
)
from ahk._utils import _version_detection_script
from ahk.directives import Directive
from concurrent.futures import Future, ThreadPoolExecutor
T_AsyncFuture = TypeVar('T_AsyncFuture') # unasync: remove
T_SyncFuture = TypeVar('T_SyncFuture')
class AHKProtocolError(Exception): ...
class AsyncFutureResult(Generic[T_AsyncFuture]): # unasync: remove
def __init__(self, task: asyncio.Task[T_AsyncFuture]):
self._task: asyncio.Task[T_AsyncFuture] = task
async def result(self) -> T_AsyncFuture:
return await self._task
class FutureResult(Generic[T_SyncFuture]):
def __init__(self, future: Future[T_SyncFuture]):
self._fut: Future[T_SyncFuture] = future
def result(self, timeout: Optional[float] = None) -> T_SyncFuture:
return self._fut.result(timeout=timeout)
AsyncIOProcess: TypeAlias = asyncio.subprocess.Process # unasync: remove
SyncIOProcess: TypeAlias = 'subprocess.Popen[bytes]'
FunctionName = Literal[
'AHKBlockInput',
'AHKClipWait',
'AHKControlClick',
'AHKControlGetPos',
'AHKControlGetText',
'AHKControlSend',
'AHKFileSelectFile',
'AHKFileSelectFolder',
'AHKGetClipboard',
'AHKGetClipboardAll',
'AHKGetCoordMode',
'AHKGetSendLevel',
'AHKGetTitleMatchMode',
'AHKGetTitleMatchSpeed',
'AHKGetVolume',
'AHKGuiNew',
'AHKImageSearch',
'AHKInputBox',
'AHKKeyState',
'AHKKeyWait',
'AHKMenuTrayIcon',
'AHKMenuTrayShow',
'AHKMenuTrayTip',
'AHKMsgBox',
'AHKMouseClickDrag',
'AHKMouseGetPos',
'AHKMouseMove',
'AHKPixelGetColor',
'AHKPixelSearch',
'AHKRegRead',
'AHKRegWrite',
'AHKRegDelete',
'AHKSend',
'AHKSendEvent',
'AHKSendInput',
'AHKSendPlay',
'AHKSendRaw',
'AHKSetClipboard',
'AHKSetClipboardAll',
'AHKSetCoordMode',
'AHKSetDetectHiddenWindows',
'AHKSetSendLevel',
'AHKSetTitleMatchMode',
'AHKSetVolume',
'AHKShowToolTip',
'AHKSoundBeep',
'AHKSoundGet',
'AHKSoundPlay',
'AHKSoundSet',
'AHKTrayTip',
'AHKWinActivate',
'AHKWinClose',
'AHKWinExist',
'AHKWinFromMouse',
'AHKWinGetControlList',
'AHKWinGetControlListHwnd',
'AHKWinGetCount',
'AHKWinGetExStyle',
'AHKWinGetID',
'AHKWinGetIDLast',
'AHKWinGetList',
'AHKWinGetMinMax',
'AHKWinGetPID',
'AHKWinGetPos',
'AHKWinGetProcessName',
'AHKWinGetProcessPath',
'AHKWinGetStyle',
'AHKWinGetText',
'AHKWinGetTitle',
'AHKWinGetTransColor',
'AHKWinGetTransparent',
'AHKWinHide',
'AHKWinIsActive',
'AHKWinIsAlwaysOnTop',
'AHKWinMove',
'AHKWinSetAlwaysOnTop',
'AHKWinSetBottom',
'AHKWinSetDisable',
'AHKWinSetEnable',
'AHKWinSetExStyle',
'AHKWinSetRedraw',
'AHKWinSetRegion',
'AHKWinSetStyle',
'AHKWinSetTitle',
'AHKWinSetTop',
'AHKWinSetTransColor',
'AHKWinSetTransparent',
'AHKWinShow',
'AHKWindowList',
'AHKWinWait',
'AHKWinWaitActive',
'AHKWinWaitClose',
'AHKWinWaitNotActive',
'AHKClick',
'AHKSetCapsLockState',
'SetKeyDelay',
'WinActivateBottom',
'AHKWinGetClass',
'AHKWinKill',
'AHKWinMaximize',
'AHKWinMinimize',
'AHKWinRestore',
]
@runtime_checkable
class Killable(Protocol):
def kill(self) -> None: ...
def kill(proc: Killable) -> None:
try:
proc.kill()
except: # noqa
pass
def async_assert_send_nonblocking_type_correct(
obj: Any,
) -> TypeGuard[
Future[Union[None, Tuple[int, int], int, str, bool, AsyncWindow, List[AsyncWindow], List[AsyncControl]]]
]:
return True
class Communicable(Protocol):
runargs: List[str]
def communicate(self, input_bytes: Optional[bytes], timeout: Optional[int] = None) -> Tuple[bytes, bytes]: ...
async def acommunicate( # unasync: remove
self, input_bytes: Optional[bytes], timeout: Optional[int] = None
) -> Tuple[bytes, bytes]: ...
@property
def returncode(self) -> Optional[int]: ...
class AsyncAHKProcess:
def __init__(self, runargs: List[str]):
self.runargs = runargs
self._proc: Optional[AsyncIOProcess] = None
@property
def returncode(self) -> Optional[int]:
assert self._proc is not None
return self._proc.returncode
async def start(self) -> None:
self._proc = await async_create_process(self.runargs)
atexit.register(kill, self._proc)
return None
async def adrain_stdin(self) -> None: # unasync: remove
assert self._proc is not None
assert self._proc.stdin is not None
await self._proc.stdin.drain()
return None
def drain_stdin(self) -> None:
assert isinstance(self._proc, subprocess.Popen)
assert self._proc.stdin is not None
self._proc.stdin.flush()
return None
def write(self, content: bytes) -> None:
assert self._proc is not None
assert self._proc.stdin is not None
self._proc.stdin.write(content)
async def readline(self) -> bytes:
assert self._proc is not None
assert self._proc.stdout is not None
line = await self._proc.stdout.readline()
assert isinstance(line, bytes)
return line
async def read(self) -> bytes:
assert self._proc is not None
assert self._proc.stdout is not None
b = await self._proc.stdout.read()
assert isinstance(b, bytes)
return b
def kill(self) -> None:
assert self._proc is not None, 'no process to kill'
self._proc.kill()
async def acommunicate( # unasync: remove
self, input_bytes: Optional[bytes] = None, timeout: Optional[int] = None
) -> Tuple[bytes, bytes]:
assert self._proc is not None
if timeout is not None: # unasync: remove
raise RuntimeError('timeout not supported in async api')
return await self._proc.communicate(input=input_bytes)
def communicate(self, input_bytes: Optional[bytes] = None, timeout: Optional[int] = None) -> Tuple[bytes, bytes]:
assert self._proc is not None
assert isinstance(self._proc, subprocess.Popen)
return self._proc.communicate(input=input_bytes, timeout=timeout)
async def async_create_process(runargs: List[str]) -> asyncio.subprocess.Process: # unasync: remove
return await asyncio.subprocess.create_subprocess_exec(
*runargs, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.STDOUT
)
def sync_create_process(runargs: List[str]) -> subprocess.Popen[bytes]:
return subprocess.Popen(runargs, stdin=subprocess.PIPE, stderr=subprocess.STDOUT, stdout=subprocess.PIPE)
class AsyncTransport(ABC):
_started: bool = False
def __init__(
self,
/,
directives: Optional[list[Union[Directive, Type[Directive]]]] = None,
version: Optional[Literal['v1', 'v2']] = 'v1',
hotkey_transport: Optional[ThreadedHotkeyTransport] = None,
**kwargs: Any,
):
self._hotkey_transport = hotkey_transport
self._directives: list[Union[Directive, Type[Directive]]] = directives or []
self._version: Optional[Literal['v1', 'v2']] = version
async def _get_full_version(self) -> str:
res = await self.run_script(_version_detection_script)
version = res.strip()
assert re.match(r'^\d+\.', version)
return version
async def _get_major_version(self) -> Literal['v1', 'v2']:
version = await self._get_full_version()
match = re.match(r'^(\d+)\.', version)
if not match:
raise ValueError(f'Unexpected version {version!r}')
major_version = match.group(1)
if major_version == '1':
return 'v1'
elif major_version == '2':
return 'v2'
else:
raise ValueError(f'Unexpected version {version!r}')
def on_clipboard_change(
self, callback: Callable[[int], Any], ex_handler: Optional[Callable[[int, Exception], Any]] = None
) -> None:
assert self._hotkey_transport is not None, 'current transport does not support hotkey functionality'
self._hotkey_transport.on_clipboard_change(callback, ex_handler)
return None
def add_hotkey(self, hotkey: Hotkey) -> None:
assert self._hotkey_transport is not None, 'current transport does not support hotkey functionality'
with warnings.catch_warnings(record=True) as caught_warnings:
self._hotkey_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, hotstring: Hotstring) -> None:
assert self._hotkey_transport is not None, 'current transport does not support hotkey functionality'
with warnings.catch_warnings(record=True) as caught_warnings:
self._hotkey_transport.add_hotstring(hotstring=hotstring)
if caught_warnings:
for warning in caught_warnings:
warnings.warn(warning.message, warning.category, stacklevel=2)
return None
def remove_hotkey(self, hotkey: Hotkey) -> None:
assert self._hotkey_transport is not None, 'current transport does not support hotkey functionality'
self._hotkey_transport.remove_hotkey(hotkey)
return None
def clear_hotkeys(self) -> None:
assert self._hotkey_transport is not None, 'current transport does not support hotkey functionality'
self._hotkey_transport.clear_hotkeys()
return None
def remove_hotstring(self, hotstring: Hotstring) -> None:
assert self._hotkey_transport is not None, 'current transport does not support hotkey functionality'
self._hotkey_transport.remove_hotstring(hotstring)
return None
def clear_hotstrings(self) -> None:
assert self._hotkey_transport is not None, 'current transport does not support hotkey functionality'
self._hotkey_transport.clear_hotstrings()
return None
def start_hotkeys(self) -> None:
assert self._hotkey_transport is not None, 'current transport does not support hotkey functionality'
return self._hotkey_transport.start()
def stop_hotkeys(self) -> None:
assert self._hotkey_transport is not None, 'current transport does not support hotkey functionality'
return self._hotkey_transport.stop()
async def init(self) -> None:
self._started = True
return None
# fmt: off
@overload
async def run_script(self, script_text_or_path: str, /, *, timeout: Optional[int] = None) -> str: ...
@overload
async def run_script(self, script_text_or_path: str, /, *, blocking: Literal[False], timeout: Optional[int] = None) -> AsyncFutureResult[str]: ...
@overload
async def run_script(self, script_text_or_path: str, /, *, blocking: Literal[True], timeout: Optional[int] = None) -> str: ...
@overload
async def run_script(self, script_text_or_path: str, /, *, blocking: bool = True, timeout: Optional[int] = None) -> Union[str, AsyncFutureResult[str]]: ...
# fmt: on
@abstractmethod
async def run_script(
self, script_text_or_path: str, /, *, blocking: bool = True, timeout: Optional[int] = None
) -> Union[str, AsyncFutureResult[str]]:
return NotImplemented
# fmt: off
@overload
async def function_call(self, function_name: Literal['AHKWinExist'], args: Optional[List[str]] = None, *, blocking: bool = True, engine: Optional[AsyncAHK[Any]] = None) -> Union[bool, AsyncFutureResult[bool]]: ...
@overload
async def function_call(self, function_name: Literal['AHKImageSearch'], args: Optional[List[str]] = None, *, blocking: bool = True, engine: Optional[AsyncAHK[Any]] = None) -> Union[Tuple[int, int], None, AsyncFutureResult[Union[Tuple[int, int], None]]]: ...
@overload
async def function_call(self, function_name: Literal['AHKPixelGetColor'], args: Optional[List[str]] = None, *, blocking: bool = True, engine: Optional[AsyncAHK[Any]] = None) -> Union[str, AsyncFutureResult[str]]: ...
@overload
async def function_call(self, function_name: Literal['AHKPixelSearch'], args: Optional[List[str]] = None, *, blocking: bool = True, engine: Optional[AsyncAHK[Any]] = None) -> Union[Optional[Tuple[int, int]], AsyncFutureResult[Optional[Tuple[int, int]]]]: ...
@overload
async def function_call(self, function_name: Literal['AHKMouseGetPos'], args: Optional[List[str]] = None, *, blocking: bool = True, engine: Optional[AsyncAHK[Any]] = None) -> Union[Tuple[int, int], AsyncFutureResult[Tuple[int, int]]]: ...
@overload
async def function_call(self, function_name: Literal['AHKKeyState'], args: Optional[List[str]] = None, *, blocking: bool = True, engine: Optional[AsyncAHK[Any]] = None) -> Union[int, float, str, None, AsyncFutureResult[None], AsyncFutureResult[str], AsyncFutureResult[int], AsyncFutureResult[float]]: ...
@overload
async def function_call(self, function_name: Literal['AHKMouseMove'], args: Optional[List[str]] = None, *, blocking: bool = True, engine: Optional[AsyncAHK[Any]] = None) -> Union[None, AsyncFutureResult[None]]: ...
@overload
async def function_call(self, function_name: Literal['AHKClick'], args: Optional[List[str]] = None, *, blocking: bool = True, engine: Optional[AsyncAHK[Any]] = None) -> Union[None, AsyncFutureResult[None]]: ...
@overload
async def function_call(self, function_name: Literal['AHKMouseClickDrag'], args: Optional[List[str]] = None, *, blocking: bool = True, engine: Optional[AsyncAHK[Any]] = None) -> Union[None, AsyncFutureResult[None]]: ...
@overload
async def function_call(self, function_name: Literal['AHKKeyWait'], args: Optional[List[str]] = None, *, blocking: bool = True, engine: Optional[AsyncAHK[Any]] = None) -> Union[int, AsyncFutureResult[int]]: ...
@overload
async def function_call(self, function_name: Literal['SetKeyDelay'], args: Optional[List[str]] = None, *, blocking: bool = True, engine: Optional[AsyncAHK[Any]] = None) -> Union[None, AsyncFutureResult[None]]: ...
@overload
async def function_call(self, function_name: Literal['AHKSend'], args: Optional[List[str]] = None, *, blocking: bool = True, engine: Optional[AsyncAHK[Any]] = None) -> Union[None, AsyncFutureResult[None]]: ...
@overload
async def function_call(self, function_name: Literal['AHKSendRaw'], args: Optional[List[str]] = None, *, blocking: bool = True, engine: Optional[AsyncAHK[Any]] = None) -> Union[None, AsyncFutureResult[None]]: ...
@overload
async def function_call(self, function_name: Literal['AHKSendInput'], args: Optional[List[str]] = None, *, blocking: bool = True, engine: Optional[AsyncAHK[Any]] = None) -> Union[None, AsyncFutureResult[None]]: ...
@overload
async def function_call(self, function_name: Literal['AHKSendEvent'], args: Optional[List[str]] = None, *, blocking: bool = True, engine: Optional[AsyncAHK[Any]] = None) -> Union[None, AsyncFutureResult[None]]: ...
@overload
async def function_call(self, function_name: Literal['AHKSendPlay'], args: Optional[List[str]] = None, *, blocking: bool = True, engine: Optional[AsyncAHK[Any]] = None) -> Union[None, AsyncFutureResult[None]]: ...
@overload
async def function_call(self, function_name: Literal['AHKSetCapsLockState'], args: Optional[List[str]] = None, *, blocking: bool = True, engine: Optional[AsyncAHK[Any]] = None) -> Union[None, AsyncFutureResult[None]]: ...
@overload
async def function_call(self, function_name: Literal['AHKWinGetTitle'], args: Optional[List[str]] = None, *, blocking: bool = True, engine: Optional[AsyncAHK[Any]] = None) -> Union[str, AsyncFutureResult[str]]: ...
@overload
async def function_call(self, function_name: Literal['AHKWinGetClass'], args: Optional[List[str]] = None, *, blocking: bool = True, engine: Optional[AsyncAHK[Any]] = None) -> Union[str, AsyncFutureResult[str]]: ...
@overload
async def function_call(self, function_name: Literal['AHKWinGetText'], args: Optional[List[str]] = None, *, blocking: bool = True, engine: Optional[AsyncAHK[Any]] = None) -> Union[str, AsyncFutureResult[str]]: ...
@overload
async def function_call(self, function_name: Literal['AHKWinActivate'], args: Optional[List[str]] = None, *, blocking: bool = True, engine: Optional[AsyncAHK[Any]] = None) -> Union[None, AsyncFutureResult[None]]: ...
@overload
async def function_call(self, function_name: Literal['WinActivateBottom'], args: Optional[List[str]] = None, *, blocking: bool = True, engine: Optional[AsyncAHK[Any]] = None) -> Union[None, AsyncFutureResult[None]]: ...
@overload
async def function_call(self, function_name: Literal['AHKWinClose'], args: Optional[List[str]] = None, *, blocking: bool = True, engine: Optional[AsyncAHK[Any]] = None) -> Union[None, AsyncFutureResult[None]]: ...
@overload
async def function_call(self, function_name: Literal['AHKWinKill'], args: Optional[List[str]] = None, *, blocking: bool = True, engine: Optional[AsyncAHK[Any]] = None) -> Union[None, AsyncFutureResult[None]]: ...
@overload
async def function_call(self, function_name: Literal['AHKWinMaximize'], args: Optional[List[str]] = None, *, blocking: bool = True, engine: Optional[AsyncAHK[Any]] = None) -> Union[None, AsyncFutureResult[None]]: ...
@overload
async def function_call(self, function_name: Literal['AHKWinMinimize'], args: Optional[List[str]] = None, *, blocking: bool = True, engine: Optional[AsyncAHK[Any]] = None) -> Union[None, AsyncFutureResult[None]]: ...
@overload
async def function_call(self, function_name: Literal['AHKWinRestore'], args: Optional[List[str]] = None, *, blocking: bool = True, engine: Optional[AsyncAHK[Any]] = None) -> Union[None, AsyncFutureResult[None]]: ...
@overload
async def function_call(self, function_name: Literal['AHKWindowList'], args: Optional[List[str]] = None, *, blocking: bool = True, engine: Optional[AsyncAHK[Any]] = None) -> Union[List[AsyncWindow], AsyncFutureResult[List[AsyncWindow]]]: ...
@overload
async def function_call(self, function_name: Literal['AHKControlSend'], args: Optional[List[str]] = None, *, blocking: bool = True, engine: Optional[AsyncAHK[Any]] = None) -> Union[None, AsyncFutureResult[None]]: ...
@overload
async def function_call(self, function_name: Literal['AHKWinFromMouse'], args: Optional[List[str]] = None, *, blocking: bool = True, engine: Optional[AsyncAHK[Any]] = None) -> Union[Optional[AsyncWindow], AsyncFutureResult[Optional[AsyncWindow]]]: ...
@overload
async def function_call(self, function_name: Literal['AHKWinIsAlwaysOnTop'], args: Optional[List[str]] = None, *, blocking: bool = True, engine: Optional[AsyncAHK[Any]] = None) -> Union[Optional[bool], AsyncFutureResult[Optional[bool]]]: ...
@overload
async def function_call(self, function_name: Literal['AHKWinMove'], args: Optional[List[str]] = None, *, blocking: bool = True, engine: Optional[AsyncAHK[Any]] = None) -> Union[None, AsyncFutureResult[None]]: ...
@overload
async def function_call(self, function_name: Literal['AHKWinGetPos'], args: Optional[List[str]] = None, *, blocking: bool = True, engine: Optional[AsyncAHK[Any]] = None) -> Union[Union[Position, None], AsyncFutureResult[Union[None, Position]]]: ...
@overload
async def function_call(self, function_name: Literal['AHKWinGetID'], args: Optional[List[str]] = None, *, blocking: bool = True, engine: Optional[AsyncAHK[Any]] = None) -> Union[Union[None, AsyncWindow], AsyncFutureResult[Union[None, AsyncWindow]]]: ...
@overload
async def function_call(self, function_name: Literal['AHKWinGetIDLast'], args: Optional[List[str]] = None, *, blocking: bool = True, engine: Optional[AsyncAHK[Any]] = None) -> Union[Union[None, AsyncWindow], AsyncFutureResult[Union[None, AsyncWindow]]]: ...
@overload
async def function_call(self, function_name: Literal['AHKWinGetPID'], args: Optional[List[str]] = None, *, blocking: bool = True, engine: Optional[AsyncAHK[Any]] = None) -> Union[Union[int, None], AsyncFutureResult[Union[int, None]]]: ...
@overload
async def function_call(self, function_name: Literal['AHKWinGetProcessName'], args: Optional[List[str]] = None, *, blocking: bool = True, engine: Optional[AsyncAHK[Any]] = None) -> Union[Union[None, str], AsyncFutureResult[Union[None, str]]]: ...
@overload
async def function_call(self, function_name: Literal['AHKWinGetProcessPath'], args: Optional[List[str]] = None, *, blocking: bool = True, engine: Optional[AsyncAHK[Any]] = None) -> Union[Union[None, str], AsyncFutureResult[Union[None, str]]]: ...
@overload
async def function_call(self, function_name: Literal['AHKWinGetCount'], args: Optional[List[str]] = None, *, blocking: bool = True, engine: Optional[AsyncAHK[Any]] = None) -> Union[int, AsyncFutureResult[int]]: ...
@overload
async def function_call(self, function_name: Literal['AHKWinGetList'], args: Optional[List[str]] = None, *, blocking: bool = True, engine: Optional[AsyncAHK[Any]] = None) -> Union[List[AsyncWindow], AsyncFutureResult[List[AsyncWindow]]]: ...
@overload
async def function_call(self, function_name: Literal['AHKWinGetMinMax'], args: Optional[List[str]] = None, *, blocking: bool = True, engine: Optional[AsyncAHK[Any]] = None) -> Union[Union[None, int], AsyncFutureResult[Union[None, int]]]: ...
@overload
async def function_call(self, function_name: Literal['AHKWinGetControlList'], args: Optional[List[str]] = None, *, blocking: bool = True, engine: Optional[AsyncAHK[Any]] = None) -> Union[List[AsyncControl], None, AsyncFutureResult[Union[List[AsyncControl], None]]]: ...
@overload
async def function_call(self, function_name: Literal['AHKWinGetTransparent'], args: Optional[List[str]] = None, *, blocking: bool = True, engine: Optional[AsyncAHK[Any]] = None) -> Union[Union[None, int], AsyncFutureResult[Union[None, int]]]: ...
@overload
async def function_call(self, function_name: Literal['AHKWinGetTransColor'], args: Optional[List[str]] = None, *, blocking: bool = True, engine: Optional[AsyncAHK[Any]] = None) -> Union[Union[None, str], AsyncFutureResult[Union[None, str]]]: ...
@overload
async def function_call(self, function_name: Literal['AHKWinGetStyle'], args: Optional[List[str]] = None, *, blocking: bool = True, engine: Optional[AsyncAHK[Any]] = None) -> Union[Union[None, str], AsyncFutureResult[Union[None, str]]]: ...
@overload
async def function_call(self, function_name: Literal['AHKWinGetExStyle'], args: Optional[List[str]] = None, *, blocking: bool = True, engine: Optional[AsyncAHK[Any]] = None) -> Union[Union[None, str], AsyncFutureResult[Union[None, str]]]: ...
@overload
async def function_call(self, function_name: Literal['AHKWinSetAlwaysOnTop'], args: Optional[List[str]] = None, *, blocking: bool = True, engine: Optional[AsyncAHK[Any]] = None) -> Union[None, AsyncFutureResult[None]]: ...
@overload
async def function_call(self, function_name: Literal['AHKWinSetBottom'], args: Optional[List[str]] = None, *, blocking: bool = True, engine: Optional[AsyncAHK[Any]] = None) -> Union[None, AsyncFutureResult[None]]: ...
@overload
async def function_call(self, function_name: Literal['AHKWinSetTop'], args: Optional[List[str]] = None, *, blocking: bool = True, engine: Optional[AsyncAHK[Any]] = None) -> Union[None, AsyncFutureResult[None]]: ...
@overload
async def function_call(self, function_name: Literal['AHKWinSetDisable'], args: Optional[List[str]] = None, *, blocking: bool = True, engine: Optional[AsyncAHK[Any]] = None) -> Union[None, AsyncFutureResult[None]]: ...
@overload
async def function_call(self, function_name: Literal['AHKWinSetEnable'], args: Optional[List[str]] = None, *, blocking: bool = True, engine: Optional[AsyncAHK[Any]] = None) -> Union[None, AsyncFutureResult[None]]: ...
@overload
async def function_call(self, function_name: Literal['AHKWinSetRedraw'], args: Optional[List[str]] = None, *, blocking: bool = True, engine: Optional[AsyncAHK[Any]] = None) -> Union[None, AsyncFutureResult[None]]: ...
@overload
async def function_call(self, function_name: Literal['AHKWinSetStyle'], args: Optional[List[str]] = None, *, blocking: bool = True, engine: Optional[AsyncAHK[Any]] = None) -> Union[bool, AsyncFutureResult[bool]]: ...
@overload
async def function_call(self, function_name: Literal['AHKWinSetExStyle'], args: Optional[List[str]] = None, *, blocking: bool = True, engine: Optional[AsyncAHK[Any]] = None) -> Union[bool, AsyncFutureResult[bool]]: ...
@overload
async def function_call(self, function_name: Literal['AHKWinSetRegion'], args: Optional[List[str]] = None, *, blocking: bool = True, engine: Optional[AsyncAHK[Any]] = None) -> Union[bool, AsyncFutureResult[bool]]: ...
@overload
async def function_call(self, function_name: Literal['AHKWinSetTransparent'], args: Optional[List[str]] = None, *, blocking: bool = True, engine: Optional[AsyncAHK[Any]] = None) -> Union[None, AsyncFutureResult[None]]: ...
@overload
async def function_call(self, function_name: Literal['AHKWinSetTransColor'], args: Optional[List[str]] = None, *, blocking: bool = True, engine: Optional[AsyncAHK[Any]] = None) -> Union[None, AsyncFutureResult[None]]: ...
@overload
async def function_call(self, function_name: Literal['AHKSetDetectHiddenWindows'], args: Optional[List[str]] = None) -> None: ...
@overload
async def function_call(self, function_name: Literal['AHKWinSetTitle'], args: Optional[List[str]] = None, *, blocking: bool = True) -> Union[None, AsyncFutureResult[None]]: ...
@overload
async def function_call(self, function_name: Literal['AHKSetTitleMatchMode'], args: Optional[List[str]] = None) -> None: ...
@overload
async def function_call(self, function_name: Literal['AHKGetTitleMatchMode']) -> str: ...
@overload
async def function_call(self, function_name: Literal['AHKGetTitleMatchSpeed']) -> str: ...
@overload
async def function_call(self, function_name: Literal['AHKControlGetText'], args: Optional[List[str]] = None, *, engine: Optional[AsyncAHK[Any]] = None, blocking: bool = True) -> Union[str, AsyncFutureResult[str]]: ...
@overload
async def function_call(self, function_name: Literal['AHKControlClick'], args: Optional[List[str]] = None, *, blocking: bool = True) -> Union[None, AsyncFutureResult[None]]: ...
@overload
async def function_call(self, function_name: Literal['AHKControlGetPos'], args: Optional[List[str]] = None, *, blocking: bool = True) -> Union[Position, AsyncFutureResult[Position]]: ...
@overload
async def function_call(self, function_name: Literal['AHKGetCoordMode'], args: List[str]) -> str: ...
@overload
async def function_call(self, function_name: Literal['AHKSetCoordMode'], args: List[str]) -> None: ...
@overload
async def function_call(self, function_name: Literal['AHKGetSendLevel']) -> int: ...
@overload
async def function_call(self, function_name: Literal['AHKSetSendLevel'], args: List[str]) -> None: ...
@overload
async def function_call(self, function_name: Literal['AHKWinWait'], args: Optional[List[str]] = None, *, blocking: bool = True, engine: Optional[AsyncAHK[Any]] = None) -> Union[AsyncWindow, AsyncFutureResult[AsyncWindow]]: ...
@overload
async def function_call(self, function_name: Literal['AHKWinWaitActive'], args: Optional[List[str]] = None, *, blocking: bool = True, engine: Optional[AsyncAHK[Any]] = None) -> Union[AsyncWindow, AsyncFutureResult[AsyncWindow]]: ...
@overload
async def function_call(self, function_name: Literal['AHKWinWaitNotActive'], args: Optional[List[str]] = None, *, blocking: bool = True, engine: Optional[AsyncAHK[Any]] = None) -> Union[AsyncWindow, AsyncFutureResult[AsyncWindow]]: ...
@overload
async def function_call(self, function_name: Literal['AHKWinShow'], args: Optional[List[str]] = None, *, blocking: bool = True, engine: Optional[AsyncAHK[Any]] = None) -> Union[None, AsyncFutureResult[None]]: ...
@overload
async def function_call(self, function_name: Literal['AHKWinHide'], args: Optional[List[str]] = None, *, blocking: bool = True, engine: Optional[AsyncAHK[Any]] = None) -> Union[None, AsyncFutureResult[None]]: ...
@overload
async def function_call(self, function_name: Literal['AHKWinIsActive'], args: Optional[List[str]] = None, *, blocking: bool = True, engine: Optional[AsyncAHK[Any]] = None) -> Union[bool, AsyncFutureResult[bool]]: ...
@overload
async def function_call(self, function_name: Literal['AHKGetVolume'], args: Optional[List[str]] = None) -> float: ...
@overload
async def function_call(self, function_name: Literal['AHKSoundBeep'], args: Optional[List[str]] = None, *, blocking: bool = True) -> None: ...
@overload
async def function_call(self, function_name: Literal['AHKSoundGet'], args: Optional[List[str]] = None, *, blocking: bool = True) -> Union[str, AsyncFutureResult[str]]: ...
@overload
async def function_call(self, function_name: Literal['AHKSoundPlay'], args: Optional[List[str]], *, blocking: bool = True) -> Union[None, AsyncFutureResult[None]]: ...
@overload
async def function_call(self, function_name: Literal['AHKSoundSet'], args: Optional[List[str]], *, blocking: bool = True) -> Union[None, AsyncFutureResult[None]]: ...
@overload
async def function_call(self, function_name: Literal['AHKSetVolume'], args: Optional[List[str]], *, blocking: bool = True) -> Union[None, AsyncFutureResult[None]]: ...
@overload
async def function_call(self, function_name: Literal['AHKTrayTip'], args: Optional[List[str]], *, blocking: bool = True) -> Union[None, AsyncFutureResult[None]]: ...
@overload
async def function_call(self, function_name: Literal['AHKGetClipboard'], args: Optional[List[str]] = None, *, blocking: bool = True) -> Union[str, AsyncFutureResult[str]]: ...
@overload
async def function_call(self, function_name: Literal['AHKGetClipboardAll'], args: Optional[List[str]] = None, *, blocking: bool = True) -> Union[bytes, AsyncFutureResult[bytes]]: ...
@overload
async def function_call(self, function_name: Literal['AHKSetClipboard'], args: Optional[List[str]], *, blocking: bool = True) -> Union[None, AsyncFutureResult[None]]: ...
@overload
async def function_call(self, function_name: Literal['AHKSetClipboardAll'], args: Optional[List[str]], *, blocking: bool = True) -> Union[None, AsyncFutureResult[None]]: ...
@overload
async def function_call(self, function_name: Literal['AHKBlockInput'], args: Optional[List[str]], *, blocking: bool = True) -> None: ...
@overload
async def function_call(self, function_name: Literal['AHKShowToolTip'], args: Optional[List[str]]) -> None: ...
@overload
async def function_call(self, function_name: Literal['AHKClipWait'], args: Optional[List[str]], *, blocking: bool = True) -> Union[None, AsyncFutureResult[None]]: ...
# @overload
# async def function_call(self, function_name: Literal['HideTrayTip'], args: Optional[List[str]] = None) -> None: ...
@overload
async def function_call(self, function_name: Literal['AHKWinWaitClose'], args: Optional[List[str]] = None, *, blocking: bool = True, engine: Optional[AsyncAHK[Any]] = None) -> Union[None, AsyncFutureResult[None]]: ...
@overload
async def function_call(self, function_name: Literal['AHKRegRead'], args: Optional[List[str]] = None, *, blocking: bool = True) -> Union[str, AsyncFutureResult[str]]: ...
@overload
async def function_call(self, function_name: Literal['AHKRegWrite'], args: Optional[List[str]] = None, *, blocking: bool = True) -> Union[None, AsyncFutureResult[None]]: ...
@overload
async def function_call(self, function_name: Literal['AHKRegDelete'], args: Optional[List[str]] = None, *, blocking: bool = True) -> Union[None, AsyncFutureResult[None]]: ...
@overload
async def function_call(self, function_name: Literal['AHKMenuTrayTip'], args: Optional[List[str]] = None, *, blocking: bool = True) -> Union[None, AsyncFutureResult[None]]: ...
@overload
async def function_call(self, function_name: Literal['AHKMenuTrayIcon'], args: Optional[List[str]] = None, *, blocking: bool = True) -> Union[None, AsyncFutureResult[None]]: ...
@overload
async def function_call(self, function_name: Literal['AHKMenuTrayShow'], args: Optional[List[str]] = None, *, blocking: bool = True) -> Union[None, AsyncFutureResult[None]]: ...
@overload
async def function_call(self, function_name: Literal['AHKGuiNew'], args: List[str], *, engine: AsyncAHK[Any]) -> str: ...
@overload
async def function_call(self, function_name: Literal['AHKMsgBox'], args: Optional[List[str]] = None, *, blocking: bool = True) -> Union[str, AsyncFutureResult[str]]: ...
@overload
async def function_call(self, function_name: Literal['AHKInputBox'], args: Optional[List[str]] = None, *, blocking: bool = True) -> Union[str, None, AsyncFutureResult[str], AsyncFutureResult[None]]: ...
@overload
async def function_call(self, function_name: Literal['AHKFileSelectFile'], args: Optional[List[str]] = None, *, blocking: bool = True) -> Union[str, None, AsyncFutureResult[str], AsyncFutureResult[None]]: ...
@overload
async def function_call(self, function_name: Literal['AHKFileSelectFolder'], args: Optional[List[str]] = None, *, blocking: bool = True) -> Union[str, None, AsyncFutureResult[str], AsyncFutureResult[None]]: ...
# fmt: on
async def function_call(
self,
function_name: FunctionName,
args: Optional[List[str]] = None,
blocking: bool = True,
engine: Optional[AsyncAHK[Any]] = None,
) -> Any:
if not self._started:
with warnings.catch_warnings(record=True) as caught_warnings:
await self.init()
if caught_warnings:
for warning in caught_warnings:
warnings.warn(warning.message, warning.category, stacklevel=3)
request = RequestMessage(function_name=function_name, args=args)
if blocking:
return await self.send(request, engine=engine)
else:
return await self.a_send_nonblocking(request, engine=engine)
@abstractmethod
async def send(
self, request: RequestMessage, engine: Optional[AsyncAHK[Any]] = None
) -> Union[None, Tuple[int, int], int, str, bool, AsyncWindow, List[AsyncWindow], List[AsyncControl]]:
return NotImplemented
@abstractmethod # unasync: remove
async def a_send_nonblocking( # unasync: remove
self, request: RequestMessage, engine: Optional[AsyncAHK[Any]] = None
) -> AsyncFutureResult[
Union[None, Tuple[int, int], int, str, bool, AsyncWindow, List[AsyncWindow], List[AsyncControl]]
]:
return NotImplemented
@abstractmethod
def send_nonblocking(
self, request: RequestMessage, engine: Optional[AsyncAHK[Any]] = None
) -> FutureResult[Union[None, Tuple[int, int], int, str, bool, AsyncWindow, List[AsyncWindow], List[AsyncControl]]]:
return NotImplemented
class AsyncDaemonProcessTransport(AsyncTransport):
def __init__(
self,
*,
executable_path: str = '',
directives: Optional[list[Directive | Type[Directive]]] = None,
jinja_loader: Optional[jinja2.BaseLoader] = None,
template: Optional[jinja2.Template] = None,
extensions: list[Extension] | None = None,
version: Optional[Literal['v1', 'v2']] = None,
skip_version_check: bool = False,
):
self._extensions = extensions or []
self._proc: Optional[AsyncAHKProcess]
self._proc = None
self._temp_script: Optional[str] = None
self.__template: jinja2.Template
self._jinja_env: jinja2.Environment
self._execution_lock = threading.Lock()
self._a_execution_lock = asyncio.Lock() # unasync: remove
self._executable_path = executable_path
if version is None or version == 'v1':
template_name = 'daemon.ahk'
const_script = _DAEMON_SCRIPT_TEMPLATE
elif version == 'v2':
template_name = 'daemon-v2.ahk'
const_script = _DAEMON_SCRIPT_V2_TEMPLATE
else:
raise ValueError(f'Invalid version {version!r} - must be one of "v1" or "v2"')
if jinja_loader is None:
try:
loader: jinja2.BaseLoader
loader = jinja2.PackageLoader('ahk', 'templates')
except ValueError:
# see: https://github.com/spyoungtech/ahk/issues/201
warnings.warn(
'Jinja could not find templates with PackageLoader. Falling back to BaseLoader',
category=UserWarning,
)
loader = jinja2.BaseLoader()
self._jinja_env = jinja2.Environment(loader=loader, trim_blocks=True, autoescape=False)
else:
self._jinja_env = jinja2.Environment(loader=jinja_loader, trim_blocks=True, autoescape=False)
try:
self.__template = self._jinja_env.get_template(template_name)
except jinja2.TemplateNotFound:
warnings.warn('daemon template missing. Falling back to constant', category=UserWarning)
self.__template = self._jinja_env.from_string(const_script)
if template is None:
template = self.__template
self._template: jinja2.Template = template
directives = directives or []
if extensions:
includes = _resolve_includes(extensions)
directives = includes + directives
hotkey_transport = ThreadedHotkeyTransport(
executable_path=self._executable_path, directives=directives, version=version
)
super().__init__(directives=directives, version=version, hotkey_transport=hotkey_transport)
@property
def template(self) -> jinja2.Template:
return self._template
async def init(self) -> None:
await self.start()
await super().init()
return None
async def start(self) -> None:
assert self._proc is None, 'cannot start a process twice'
with warnings.catch_warnings(record=True) as caught_warnings:
async with self.lock:
self._proc = await self._create_process()
if caught_warnings:
for warning in caught_warnings:
warnings.warn(warning.message, warning.category, stacklevel=2)
def _render_script(self, template: Optional[jinja2.Template] = None, **kwargs: Any) -> str:
if template is None:
template = self._template
kwargs['daemon'] = self.__template
message_types = {str(tom, 'utf-8'): c.__name__.upper() for tom, c in _message_registry.items()}
return template.render(
directives=self._directives,
message_types=message_types,
message_registry=_message_registry,
extensions=self._extensions,
ahk_version=self._version,
**kwargs,
)
@property
def lock(self) -> Any:
return self._a_execution_lock # unasync: remove
return self._execution_lock
async def _create_process(
self, template: Optional[jinja2.Template] = None, **template_kwargs: Any
) -> AsyncAHKProcess:
if template is None:
if template_kwargs:
raise ValueError('template kwargs were specified, but no template was provided')
if self._temp_script is None or not os.path.exists(self._temp_script):
script_text = self._render_script()
with tempfile.NamedTemporaryFile(
mode='w', prefix='python-ahk-', suffix='.ahk', delete=False
) as tempscriptfile:
tempscriptfile.write(script_text) # XXX: can we make this async?
self._temp_script = tempscriptfile.name
daemon_script = self._temp_script
atexit.register(os.remove, tempscriptfile.name)
else:
daemon_script = self._temp_script
else:
script_text = self._render_script(template=template, **template_kwargs)
with tempfile.NamedTemporaryFile(mode='w', prefix='python-ahk-', suffix='.ahk', delete=False) as tempscript:
tempscript.write(script_text)
daemon_script = tempscript.name
atexit.register(os.remove, tempscript.name)
runargs = [self._executable_path, '/CP65001', '/ErrorStdOut', daemon_script]
proc = AsyncAHKProcess(runargs=runargs)
await proc.start()
return proc
async def _send_nonblocking(
self, request: RequestMessage, engine: Optional[AsyncAHK[Any]] = None
) -> Union[None, Tuple[int, int], int, str, bool, AsyncWindow, List[AsyncWindow], List[AsyncControl]]:
msg = request.format()
proc = await self._create_process()
try:
proc.write(msg)
await proc.adrain_stdin()
tom = await proc.readline()
num_lines = await proc.readline()
content_buffer = BytesIO()
content_buffer.write(tom)
content_buffer.write(num_lines)
try:
lines_to_read = int(num_lines) + 1
except ValueError as e:
try:
stdout = tom + num_lines + await proc.read()
except Exception:
stdout = b''
raise AHKProtocolError(
'Unexpected data received. This is usually the result of an unhandled error in the AHK process'
+ (f': {stdout!r}' if stdout else '')
) from e
for _ in range(lines_to_read):
part = await proc.readline()
content_buffer.write(part)
content = content_buffer.getvalue()[:-1]
finally:
try:
proc.kill()
except: # noqa
pass
response = ResponseMessage.from_bytes(content, engine=engine)
return response.unpack() # type: ignore
async def a_send_nonblocking( # unasync: remove
self, request: RequestMessage, engine: Optional[AsyncAHK[Any]] = None
) -> AsyncFutureResult[
Union[None, Tuple[int, int], int, str, bool, AsyncWindow, List[AsyncWindow], List[AsyncControl]]
]:
loop = asyncio.get_running_loop()
task = loop.create_task(self._send_nonblocking(request=request, engine=engine))
return AsyncFutureResult(task)
def send_nonblocking(
self, request: RequestMessage, engine: Optional[AsyncAHK[Any]] = None
) -> FutureResult[Union[None, Tuple[int, int], int, str, bool, AsyncWindow, List[AsyncWindow], List[AsyncControl]]]:
# this is only used by the sync implementation
pool = ThreadPoolExecutor(max_workers=1)
fut = pool.submit(self._send_nonblocking, request=request, engine=engine)
pool.shutdown(wait=False)
assert async_assert_send_nonblocking_type_correct(
fut
) # workaround to get mypy correctness in sync and async implementation
return FutureResult(fut)
async def send(
self, request: RequestMessage, engine: Optional[AsyncAHK[Any]] = None
) -> Union[None, Tuple[int, int], int, str, bool, AsyncWindow, List[AsyncWindow], List[AsyncControl]]:
msg = request.format()
assert self._proc is not None
async with self.lock:
self._proc.write(msg)
await self._proc.adrain_stdin()
tom = await self._proc.readline()
num_lines = await self._proc.readline()
content_buffer = BytesIO()
content_buffer.write(tom)
content_buffer.write(num_lines)
try:
lines_to_read = int(num_lines) + 1
except ValueError as e:
try:
stdout = tom + num_lines + await self._proc.read()
except Exception:
stdout = b''
raise AHKProtocolError(
'Unexpected data received. This is usually the result of an unhandled error in the AHK process'
+ (f': {stdout!r}' if stdout else '')
) from e
for _ in range(lines_to_read):
part = await self._proc.readline()
content_buffer.write(part)
content = content_buffer.getvalue()[:-1]
response = ResponseMessage.from_bytes(content, engine=engine)
return response.unpack() # type: ignore
async def _async_run_nonblocking( # unasync: remove
self, proc: Communicable, script_bytes: Optional[bytes], timeout: Optional[int] = None
) -> AsyncFutureResult[str]:
loop = asyncio.get_running_loop()
async def f() -> str:
stdout, stderr = await proc.acommunicate(script_bytes, timeout)
if proc.returncode != 0:
assert proc.returncode is not None
raise subprocess.CalledProcessError(proc.returncode, proc.runargs, stdout, stderr)
return stdout.decode('utf-8')
task = loop.create_task(f())
return AsyncFutureResult(task)
def _sync_run_nonblocking(
self,
proc: Communicable,
script_bytes: Optional[bytes],
timeout: Optional[int] = None,
) -> FutureResult[str]:
pool = ThreadPoolExecutor(max_workers=1)
def f() -> str:
stdout, stderr = proc.communicate(script_bytes, timeout)
if proc.returncode != 0:
assert proc.returncode is not None
raise subprocess.CalledProcessError(proc.returncode, proc.runargs, stdout, stderr)
return stdout.decode('utf-8')
fut = pool.submit(f)
pool.shutdown(wait=False)
return FutureResult(fut)
# fmt: off
@overload
async def run_script(self, script_text_or_path: str, /, *, timeout: Optional[int] = None) -> str: ...
@overload
async def run_script(self, script_text_or_path: str, /, *, blocking: Literal[False], timeout: Optional[int] = None) -> AsyncFutureResult[str]: ...
@overload
async def run_script(self, script_text_or_path: str, /, *, blocking: Literal[True], timeout: Optional[int] = None) -> str: ...
@overload
async def run_script(self, script_text_or_path: str, /, *, blocking: bool = True, timeout: Optional[int] = None) -> Union[str, AsyncFutureResult[str]]: ...
# fmt: on
async def run_script(
self, script_text_or_path: str, /, *, blocking: bool = True, timeout: Optional[int] = None
) -> Union[str, AsyncFutureResult[str]]:
if os.path.exists(script_text_or_path):
script_bytes = None
runargs = [self._executable_path, '/CP65001', '/ErrorStdOut', script_text_or_path]
else:
script_bytes = bytes(script_text_or_path, 'utf-8')
runargs = [self._executable_path, '/CP65001', '/ErrorStdOut', '*']
proc = AsyncAHKProcess(runargs)
await proc.start()
if blocking:
stdout, stderr = await proc.acommunicate(script_bytes, timeout=timeout)
if proc.returncode != 0:
assert proc.returncode is not None
raise subprocess.CalledProcessError(proc.returncode, proc.runargs, stdout, stderr)
return stdout.decode('utf-8')
else:
return await self._async_run_nonblocking(proc, script_bytes, timeout=timeout)
if TYPE_CHECKING:
from .engine import AsyncAHK