Repository navigation
Expand file tree
/
Copy pathTypeHack.py
More file actions
1696 lines (1476 loc) · 59.9 KB
/
Copy pathTypeHack.py
File metadata and controls
1696 lines (1476 loc) · 59.9 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
#!/usr/bin/env python3
"""Legacy TypeHack 2.x (Python/Tk). TypeHack 3.0.0 is the Rust binary (`cargo run --release --bin TypeHack`)."""
from __future__ import annotations
import ctypes
import json
import os
import random
import sys
import threading
import time
from html.parser import HTMLParser
from pathlib import Path
import updater
from colorama import Fore, Style, init as colorama_init
from selenium import webdriver
from selenium.common.exceptions import TimeoutException, WebDriverException
from selenium.webdriver.chrome.options import Options as ChromeOptions
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.edge.options import Options as EdgeOptions
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.ui import WebDriverWait
colorama_init(autoreset=True)
def app_dir() -> Path:
"""Writable folder next to the exe (installer) or the source file (dev)."""
if getattr(sys, "frozen", False):
return Path(sys.executable).resolve().parent
return Path(__file__).resolve().parent
BASE_DIR = app_dir()
CREDENTIALS_FILE = BASE_DIR / "credentials.json"
CONFIG_FILE = BASE_DIR / "config.json"
VERSION = "2.5.0"
PRESET_URLS = {
"Österreich (at4)": "https://at4.typewriter.at",
"Deutschland (de4)": "https://de4.typewriter.at",
"Schweiz (ch4)": "https://ch4.typewriter.at",
"Benutzerdefiniert": "",
}
DEFAULT_CONFIG = {
"base_url": "https://at4.typewriter.at",
"url_preset": "Österreich (at4)",
"browser": "Auto",
"remember_login": True,
"always_on_top": True,
"open_level_page": True,
"auto_start": False,
"type_mode": "char",
"delay_ms": 50,
"char_delay_ms": 18,
"strokes_per_10min": 2000,
"jitter_pct": 0,
"burst_chars": 0,
"login_timeout_s": 180,
"prompt_timeout_s": 8,
"theme_accent": "#6ee7b7",
"auto_update_check": True,
"auto_install_updates": True,
}
LOGIN_PATH = "/index.php?r=site/login"
LEVEL_PATH = "/index.php?r=typewriter/runLevel"
LOGIN_USER = [
(By.ID, "LoginForm_username"),
(By.NAME, "LoginForm[username]"),
(By.CSS_SELECTOR, "input[name*='username' i]"),
(By.CSS_SELECTOR, "input[type='email']"),
(By.CSS_SELECTOR, "input[name*='email' i]"),
(By.ID, "username"),
]
LOGIN_PASS = [
(By.ID, "LoginForm_pw"),
(By.ID, "LoginForm_password"),
(By.NAME, "LoginForm[password]"),
(By.NAME, "LoginForm[pw]"),
(By.CSS_SELECTOR, "input[type='password']"),
]
LOGIN_SUBMIT = [
(By.ID, "login-submit-btn"),
(By.CSS_SELECTOR, "#login-form input[type='submit']"),
(By.CSS_SELECTOR, "input[type='submit'][value='Login']"),
(By.CSS_SELECTOR, "button[type='submit']"),
]
OVERLAY_CLICK = [
(By.CSS_SELECTOR, "button.fc-cta-consent"),
(By.CSS_SELECTOR, "button[aria-label='Consent']"),
(By.CSS_SELECTOR, "button.fc-data-preferences-accept-all"),
(By.CSS_SELECTOR, "button[aria-label='Accept all']"),
(By.XPATH, "//button[normalize-space()='Consent' or normalize-space()='Zustimmen' or contains(., 'Alle akzeptieren') or contains(., 'Accept all')]"),
]
CAPTCHA_CLICK = [
(By.CSS_SELECTOR, "#chal-form button"),
(By.CSS_SELECTOR, "form#chal-form button"),
(By.CSS_SELECTOR, ".altcha, .altcha-checkbox, button.altcha"),
(By.CSS_SELECTOR, "#altcha"),
(By.CSS_SELECTOR, "input[name='altcha']"),
(By.XPATH, "//button[contains(., 'Roboter') or contains(., 'Captcha') or contains(., 'Verify') or contains(., 'Mensch')]"),
(By.CSS_SELECTOR, "label:has(input[type='checkbox'])"),
]
PROMPT_SELECTORS = [
(By.ID, "text_todo_1"),
(By.CSS_SELECTOR, "[id^='text_todo']"),
(By.ID, "text_todo"),
(By.CSS_SELECTOR, "#typewriter-text"),
(By.CSS_SELECTOR, ".typewriter-text"),
(By.CSS_SELECTOR, "#textToType"),
(By.CSS_SELECTOR, "#tw-text"),
(By.CSS_SELECTOR, "#twText"),
(By.CSS_SELECTOR, ".tw-text"),
(By.CSS_SELECTOR, ".typewriter-line"),
(By.CSS_SELECTOR, ".current-line"),
(By.CSS_SELECTOR, "[data-prompt]"),
(By.CSS_SELECTOR, ".letter, .char, span.letter, span.char"),
]
START_CLICK = [
(By.CSS_SELECTOR, ".ui-dialog-buttonset button"),
(By.CSS_SELECTOR, ".ui-dialog-buttonset .ui-button"),
(By.CSS_SELECTOR, "div.ui-dialog button"),
(By.CLASS_NAME, "cockpitStartButton"),
(By.CSS_SELECTOR, "a.cockpitStartButton, button.cockpitStartButton"),
(By.XPATH, "//button[contains(., 'OK') or contains(., 'Start') or contains(., 'Weiter') or contains(., 'Begin') or contains(., 'Los') or contains(., 'Übung')]"),
(By.XPATH, "//span[contains(@class,'ui-button-text') and (contains(.,'OK') or contains(.,'Start') or contains(.,'Weiter') or contains(.,'Los'))]"),
]
WRITE_CLICK = [
(By.CLASS_NAME, "cockpitStartButton"),
(By.CSS_SELECTOR, "a.cockpitStartButton, button.cockpitStartButton"),
(By.CSS_SELECTOR, "a[href*='generateLevel'], a[href*='runLevel']"),
(By.XPATH, "//a[contains(., 'Schreiben') and not(contains(., 'Abmelden'))]"),
(By.XPATH, "//a[contains(@href,'typewriter/generateLevel') or contains(@href,'typewriter/runLevel')]"),
]
PALETTE = {
"bg": "#0b0d12",
"panel": "#12151c",
"card": "#1a1f29",
"line": "#2a3140",
"text": "#f4f4f5",
"muted": "#9aa3b2",
"accent": "#6ee7b7",
"accent2": "#7dd3fc",
"danger": "#fb7185",
"warn": "#fbbf24",
}
def merge_config(raw: dict | None) -> dict:
cfg = dict(DEFAULT_CONFIG)
if isinstance(raw, dict):
for key, value in raw.items():
if key in cfg:
cfg[key] = value
return cfg
def load_config(path: Path = CONFIG_FILE) -> dict:
try:
return merge_config(json.loads(path.read_text(encoding="utf-8")))
except (FileNotFoundError, json.JSONDecodeError, OSError):
return merge_config(None)
def save_config(cfg: dict, path: Path = CONFIG_FILE) -> None:
path.write_text(json.dumps(merge_config(cfg), indent=2), encoding="utf-8")
def load_credentials(path: Path = CREDENTIALS_FILE) -> tuple[str | None, str | None]:
try:
data = json.loads(path.read_text(encoding="utf-8"))
except (FileNotFoundError, json.JSONDecodeError, OSError):
return None, None
email = str(data.get("email") or "").strip() or None
password = str(data.get("password") or "") or None
return email, password
def save_credentials(email: str, password: str, path: Path = CREDENTIALS_FILE) -> None:
path.write_text(json.dumps({"email": email, "password": password}, indent=2), encoding="utf-8")
def clamp_strokes(n) -> int:
try:
value = int(float(n))
except Exception:
value = 2000
return max(200, min(8000, value))
def interval_seconds(cfg: dict) -> float:
"""Seconds between keystrokes from Anschläge / 10 minutes."""
n = clamp_strokes(cfg.get("strokes_per_10min") or 0)
base = 600.0 / n
jitter = max(0.0, min(100.0, float(cfg.get("jitter_pct") or 0))) / 100.0
factor = 1.0 + random.uniform(-jitter, jitter) if jitter else 1.0
return max(0.02, base * factor)
def delay_seconds(cfg: dict, *, char: bool = False) -> float:
if cfg.get("strokes_per_10min"):
return interval_seconds(cfg)
base_ms = float(cfg.get("char_delay_ms") if char else cfg.get("delay_ms") or 0)
jitter = max(0.0, min(100.0, float(cfg.get("jitter_pct") or 0))) / 100.0
factor = 1.0 + random.uniform(-jitter, jitter) if jitter else 1.0
return max(0.0, (base_ms / 1000.0) * factor)
def first_present(driver, locators, timeout: float = 2.0):
end = time.time() + timeout
while time.time() < end:
el = first_visible(driver, locators)
if el is not None:
return el
time.sleep(0.12)
raise TimeoutException("Kein passendes Element gefunden")
def first_visible(driver, locators, *, enabled: bool = False):
for by, value in locators:
try:
for el in driver.find_elements(by, value):
try:
if not el.is_displayed():
continue
if enabled and not el.is_enabled():
continue
return el
except Exception:
continue
except Exception:
continue
return None
def dismiss_overlays(driver) -> bool:
clicked = False
for by, value in OVERLAY_CLICK:
try:
els = driver.find_elements(by, value)
except Exception:
continue
for el in els:
try:
if el.is_displayed():
driver.execute_script("arguments[0].click();", el)
clicked = True
except Exception:
continue
return clicked
def nudge_captcha(driver) -> bool:
"""One cheap click if a captcha control is already there. Never blocks."""
for by, value in CAPTCHA_CLICK:
try:
els = driver.find_elements(by, value)
except Exception:
continue
for el in els:
try:
if el.is_displayed():
driver.execute_script("arguments[0].click();", el)
return True
except Exception:
continue
return False
def fill_input(driver, el, text: str) -> None:
try:
el.click()
except Exception:
try:
driver.execute_script("arguments[0].focus();", el)
except Exception:
pass
try:
el.clear()
el.send_keys(text)
if (el.get_attribute("value") or "") == text:
return
except Exception:
pass
driver.execute_script(
"var e=arguments[0],v=arguments[1];"
"e.focus(); e.value=v;"
"e.dispatchEvent(new Event('input',{bubbles:true}));"
"e.dispatchEvent(new Event('change',{bubbles:true}));",
el,
text,
)
def logged_in_markers(driver) -> bool:
if first_visible(driver, LOGIN_PASS):
return False
url = driver.current_url or ""
if "site/login" in url:
return False
if any(bit in url for bit in ("runLevel", "practise")):
return True
try:
if driver.find_elements(By.CLASS_NAME, "ui-dialog-buttonset"):
return True
if driver.find_elements(By.CSS_SELECTOR, "a[href*='site/logout']"):
return True
except Exception:
pass
return False
# Spans already accepted/rejected by typewriter.at — never replay these.
_DONE_HINTS = (
"done",
"typed",
"correct",
"ok",
"past",
"completed",
"right",
"hit",
"success",
"written",
"already",
"error",
"wrong",
"false",
"miss",
)
_SPACE_HINTS = ("space", "blank", "gap", "nbsp", "whitespace", "word-sep", "wordsep", "word_sep")
_SKIP_TAGS = {"script", "style", "noscript", "svg"}
# typewriter.at remaining chars are bare <span>s; empty ones are Abstände.
_LEAF_SPACE_TAGS = {"span", "i", "b", "em", "strong", "font"}
def normalize_prompt_text(raw: str) -> str:
text = raw or ""
for src in ("\xa0", "\u202f", "\u2002", "\u2003", "\u2009", "\t"):
text = text.replace(src, " ")
return text.replace("\n", "").replace("\r", "")
def keys_for_char(ch: str):
"""Glyph identity (layout-independent). Space is the character ' ', not a scan code."""
if ch in (" ", "\xa0", "\u202f", "\u2009"):
return " "
if ch in ("\n", "\r"):
return "\n"
return ch
def _attr_blob(attrs) -> str:
data = {str(k).lower(): str(v or "") for k, v in attrs}
return f"{data.get('class', '')} {data.get('id', '')} {data.get('data-type', '')} {data.get('data-kind', '')}".lower()
def _token_match(blob: str, hints: tuple[str, ...]) -> bool:
parts = set(blob.replace("_", "-").replace(",", " ").split())
for hint in hints:
for part in parts:
if part == hint or part.startswith(hint + "-") or part.endswith("-" + hint):
return True
return False
class _PromptParser(HTMLParser):
"""Walk typewriter markup → remaining glyphs, including Abstände, skipping completed spans."""
def __init__(self) -> None:
super().__init__(convert_charrefs=True)
self.parts: list[str] = []
self.skip = 0
self.tag_stack: list[str] = []
self.spacey_stack: list[bool] = []
self.had_data_stack: list[bool] = []
def handle_starttag(self, tag: str, attrs) -> None:
tag = (tag or "").lower()
self.tag_stack.append(tag)
if tag in _SKIP_TAGS:
self.skip += 1
self.spacey_stack.append(False)
self.had_data_stack.append(True)
return
blob = _attr_blob(attrs)
if self.skip or _token_match(blob, _DONE_HINTS):
self.skip += 1
self.spacey_stack.append(False)
self.had_data_stack.append(True)
return
spacey = _token_match(blob, _SPACE_HINTS)
self.spacey_stack.append(spacey)
self.had_data_stack.append(False)
def handle_endtag(self, tag: str) -> None:
if not self.tag_stack:
return
opened = self.tag_stack.pop()
spacey = self.spacey_stack.pop() if self.spacey_stack else False
had = self.had_data_stack.pop() if self.had_data_stack else False
if self.skip:
self.skip = max(0, self.skip - 1)
return
leaf_space = (not had) and (spacey or opened in _LEAF_SPACE_TAGS)
if leaf_space:
self.parts.append(" ")
had = True
if had and self.had_data_stack:
self.had_data_stack[-1] = True
def handle_startendtag(self, tag: str, attrs) -> None:
self.handle_starttag(tag, attrs)
self.handle_endtag(tag)
def handle_data(self, data: str) -> None:
if self.skip or not data:
return
if not data.strip(" \t\n\r\xa0\u202f"):
# Pretty-printed markup inserts "\n " between spans — not a typed Abstand.
if "\n" in data or "\r" in data:
return
data = " "
if self.had_data_stack:
self.had_data_stack[-1] = True
self.parts.append(data)
def extract_prompt_from_html(html: str) -> str:
"""Remaining typeable text from a typewriter fragment. Spaces count; done spans do not."""
parser = _PromptParser()
parser.feed(html or "")
parser.close()
return normalize_prompt_text("".join(parser.parts))
def _root_id(html: str) -> str:
blob = (html or "").lstrip()[:200].lower()
for key in ('id="', "id='"):
start = blob.find(key)
if start < 0:
continue
start += len(key)
quote = '"' if key.endswith('"') else "'"
end = blob.find(quote, start)
if end > start:
return blob[start:end]
return ""
def pick_remaining_prompt(htmls: list[str]) -> str:
"""Choose the real remaining line. Prefer #text_todo_*; empty wrappers lose; space-only is valid."""
todo: list[str] = []
other: list[str] = []
for html in htmls:
text = extract_prompt_from_html(html)
if text == "":
continue
if _root_id(html).startswith("text_todo"):
todo.append(text)
else:
other.append(text)
pool = todo or other
if not pool:
raise TimeoutException("Tipptext ist leer")
return max(pool, key=len)
def glyphs_to_type(text: str) -> list[str]:
"""One list entry per keystroke, layout-independent glyph identity."""
return [keys_for_char(ch) for ch in normalize_prompt_text(text)]
def glyph_payload(ch: str) -> dict:
"""CDP/key event for this glyph. Identity is `text`, never a physical KeyY/KeyZ code."""
glyph = keys_for_char(ch)
if glyph == " ":
return {"glyph": " ", "key": " ", "code": "Space", "vk": 32, "text": " ", "insert_text": " "}
if glyph == "\n":
return {"glyph": "\n", "key": "Enter", "code": "Enter", "vk": 13, "text": "\r", "insert_text": "\n"}
return {
"glyph": glyph,
"key": glyph,
"code": "",
"vk": 0,
"text": glyph,
"insert_text": glyph,
}
def collect_prompt_html(driver) -> list[str]:
htmls: list[str] = []
seen: set[str] = set()
def add(html: str | None) -> None:
raw = (html or "").strip()
if not raw or raw in seen:
return
seen.add(raw)
htmls.append(raw)
for by, value in PROMPT_SELECTORS:
try:
els = driver.find_elements(by, value)
except Exception:
continue
for el in els[:30]:
try:
add(el.get_attribute("outerHTML"))
except Exception:
continue
el_id = ""
try:
el_id = el.get_attribute("id") or ""
except Exception:
el_id = ""
# Parent of #text_todo_1 often also wraps #text_done_* — that would replay typed letters.
if str(el_id).startswith("text_todo"):
continue
try:
parent = driver.execute_script(
"var e=arguments[0]; return e && e.parentElement ? e.parentElement.outerHTML : '';",
el,
)
add(parent)
except Exception:
continue
return htmls
def prompt_text(driver, timeout: float = 8.0) -> str:
"""Remaining prompt including Abstände. Whitespace-only is typeable, not empty."""
end = time.time() + timeout
last: Exception | None = None
while time.time() < end:
try:
return pick_remaining_prompt(collect_prompt_html(driver))
except TimeoutException as exc:
last = exc
time.sleep(0.12)
raise last or TimeoutException("Tipptext ist leer")
def pass_altcha_then_reload(driver) -> bool:
"""Kept for compatibility: never wait, never refresh — that caused the 20s login delay."""
return nudge_captcha(driver)
def focus_typer(driver) -> None:
"""Focus the hidden typewriter input. Do not click #text_todo_1 — that steals focus."""
try:
driver.execute_script(
"window.focus();"
"if (typeof setFocusMobileText === 'function') { try { setFocusMobileText(); } catch (x) {} }"
"var nodes=document.querySelectorAll('input,textarea');"
"for (var i=0;i<nodes.length;i++){"
" var e=nodes[i];"
" var id=(e.id||''), name=(e.name||''), tp=(e.type||'').toLowerCase();"
" if (tp==='password' || tp==='hidden' || tp==='submit' || tp==='button') continue;"
" if (/login|user|email|pass/i.test(id+' '+name)) continue;"
" try { e.focus({preventScroll:true}); return id||name||tp; } catch (x) {}"
"}"
)
except Exception:
pass
# Sticky name of the send method that last moved the remaining prompt.
_PREFERRED_SEND: list[str] = []
SEND_METHODS = ("os", "js", "cdp", "chains")
# Win32 keyboard / window helpers (OS-level keys land even when CDP does not).
ULONG_PTR = ctypes.c_size_t
VK_SPACE = 0x20
VK_RETURN = 0x0D
VK_MENU = 0x12
KEYEVENTF_KEYUP = 0x0002
KEYEVENTF_UNICODE = 0x0004
INPUT_KEYBOARD = 1
SW_RESTORE = 9
SW_SHOW = 5
_JS_SEND_GLYPH = r"""
var ch = arguments[0];
var which = (ch === ' ' || ch === '\xa0') ? 32 : ch.charCodeAt(0);
var key = (ch === ' ' || ch === '\xa0') ? ' ' : ch;
var code = (key === ' ') ? 'Space' : '';
function fire(target, type) {
if (!target || !target.dispatchEvent) return;
var init = {
key: key, code: code, bubbles: true, cancelable: true, composed: true,
keyCode: which, which: which, charCode: type === 'keypress' ? which : 0,
view: window
};
var ev;
try { ev = new KeyboardEvent(type, init); } catch (e) { return; }
try {
Object.defineProperty(ev, 'keyCode', {get: function(){return which;}});
Object.defineProperty(ev, 'which', {get: function(){return which;}});
Object.defineProperty(ev, 'charCode', {get: function(){return type === 'keypress' ? which : 0;}});
Object.defineProperty(ev, 'key', {get: function(){return key;}});
} catch (e) {}
target.dispatchEvent(ev);
}
var nodes = [document.activeElement, document.getElementById('text_todo_1'), document.body, document];
var seen = [];
nodes.forEach(function(n) {
if (!n || seen.indexOf(n) >= 0) return;
seen.push(n);
fire(n, 'keydown'); fire(n, 'keypress'); fire(n, 'keyup');
});
if (window.jQuery) {
['keydown','keypress','keyup'].forEach(function(type) {
var je = jQuery.Event(type);
je.which = which; je.keyCode = which; je.charCode = which; je.key = key;
jQuery(document).trigger(je);
jQuery('body').trigger(je);
jQuery('#text_todo_1').trigger(je);
});
}
return true;
"""
class _KEYBDINPUT(ctypes.Structure):
_fields_ = (
("wVk", ctypes.c_ushort),
("wScan", ctypes.c_ushort),
("dwFlags", ctypes.c_ulong),
("time", ctypes.c_ulong),
("dwExtraInfo", ULONG_PTR),
)
class _MOUSEINPUT(ctypes.Structure):
_fields_ = (
("dx", ctypes.c_long),
("dy", ctypes.c_long),
("mouseData", ctypes.c_ulong),
("dwFlags", ctypes.c_ulong),
("time", ctypes.c_ulong),
("dwExtraInfo", ULONG_PTR),
)
class _HARDWAREINPUT(ctypes.Structure):
_fields_ = (
("uMsg", ctypes.c_ulong),
("wParamL", ctypes.c_ushort),
("wParamH", ctypes.c_ushort),
)
class _INPUT(ctypes.Structure):
class _U(ctypes.Union):
_fields_ = (("ki", _KEYBDINPUT), ("mi", _MOUSEINPUT), ("hi", _HARDWAREINPUT))
_anonymous_ = ("u",)
_fields_ = (("type", ctypes.c_ulong), ("u", _U))
def preferred_send() -> str | None:
return _PREFERRED_SEND[0] if _PREFERRED_SEND else None
def remember_send(name: str | None) -> None:
_PREFERRED_SEND.clear()
if name:
_PREFERRED_SEND.append(name)
def remaining_prompt_now(driver) -> str | None:
"""Current remaining prompt, or None if it cannot be read yet."""
try:
return pick_remaining_prompt(collect_prompt_html(driver))
except Exception:
return None
def first_remaining_glyph(text: str) -> str:
glyphs = glyphs_to_type(text)
if not glyphs:
raise TimeoutException("Tipptext ist leer")
return glyphs[0]
def _send_input(inputs: list[_INPUT]) -> None:
if not inputs or os.name != "nt":
raise OSError("SendInput nur unter Windows")
arr = (_INPUT * len(inputs))(*inputs)
sent = ctypes.windll.user32.SendInput(len(inputs), ctypes.byref(arr), ctypes.sizeof(_INPUT))
if sent != len(inputs):
raise OSError(f"SendInput {sent}/{len(inputs)}")
def _vk_down(vk: int) -> None:
# keybd_event reaches Chromium; SendInput often does not (UIPI / focus).
ctypes.windll.user32.keybd_event(vk, 0, 0, 0)
def _vk_up(vk: int) -> None:
ctypes.windll.user32.keybd_event(vk, 0, KEYEVENTF_KEYUP, 0)
def _vk_tap(vk: int) -> None:
_vk_down(vk)
_vk_up(vk)
def _unicode_tap(ch: str) -> None:
code = ord(ch)
down = _INPUT(type=INPUT_KEYBOARD, ki=_KEYBDINPUT(0, code, KEYEVENTF_UNICODE, 0, 0))
up = _INPUT(type=INPUT_KEYBOARD, ki=_KEYBDINPUT(0, code, KEYEVENTF_UNICODE | KEYEVENTF_KEYUP, 0, 0))
_send_input([down, up])
def os_send_glyph(ch: str) -> None:
"""Real OS keystroke into the foreground window (the Edge/Chrome lesson)."""
ch = keys_for_char(ch)
if os.name != "nt":
raise OSError("OS-Tasten nur unter Windows")
if ch == " ":
_vk_tap(VK_SPACE)
return
if ch == "\n":
_vk_tap(VK_RETURN)
return
scan = ctypes.windll.user32.VkKeyScanW(ord(ch))
if scan == -1 or scan == 0xFFFF:
_unicode_tap(ch)
return
vk = scan & 0xFF
shift = bool(scan & 0x100)
ctrl = bool(scan & 0x200)
alt = bool(scan & 0x400)
if shift:
_vk_down(0x10)
if ctrl:
_vk_down(0x11)
if alt:
_vk_down(0x12)
_vk_tap(vk)
if alt:
_vk_up(0x12)
if ctrl:
_vk_up(0x11)
if shift:
_vk_up(0x10)
def _window_title(hwnd: int) -> str:
n = ctypes.windll.user32.GetWindowTextLengthW(hwnd) + 1
buf = ctypes.create_unicode_buffer(n)
ctypes.windll.user32.GetWindowTextW(hwnd, buf, n)
return buf.value
def _window_class(hwnd: int) -> str:
buf = ctypes.create_unicode_buffer(256)
ctypes.windll.user32.GetClassNameW(hwnd, buf, 256)
return buf.value
def chrome_hwnds() -> list[int]:
found: list[int] = []
if os.name != "nt":
return found
@ctypes.WINFUNCTYPE(ctypes.c_int, ctypes.c_void_p, ctypes.c_ssize_t)
def cb(hwnd, _lparam):
if not ctypes.windll.user32.IsWindowVisible(hwnd):
return 1
cls = _window_class(hwnd)
if cls != "Chrome_WidgetWin_1":
return 1
title = _window_title(hwnd)
if not title or title.lower() == "typehack":
return 1
found.append(int(hwnd))
return 1
ctypes.windll.user32.EnumWindows(cb, 0)
return found
def pick_browser_hwnd(driver=None) -> int | None:
hwnds = chrome_hwnds()
if not hwnds:
return None
needle = ""
try:
needle = ((driver.title if driver is not None else "") or "").strip().lower()
except Exception:
needle = ""
scored: list[tuple[int, int]] = []
skip = ("discord", "nzxt", "kennwort", "password", "spotify", "slack", "teams", "vscode", "cursor")
for hwnd in hwnds:
title = _window_title(hwnd).lower()
if any(bit in title for bit in skip):
continue
score = 0
if "typewriter" in title:
score += 12
if needle and needle[:24] in title:
score += 8
if "microsoft edge" in title or "google chrome" in title:
score += 3
if "data:;," in title or title.startswith("data:"):
score -= 5
scored.append((score, hwnd))
if not scored:
return None
scored.sort(reverse=True)
return scored[0][1]
def force_foreground(hwnd: int) -> bool:
"""Bring hwnd to the front without injecting Alt into the page."""
if not hwnd or os.name != "nt":
return False
user32 = ctypes.windll.user32
kernel32 = ctypes.windll.kernel32
user32.ShowWindow(hwnd, SW_RESTORE)
user32.ShowWindow(hwnd, SW_SHOW)
if user32.GetForegroundWindow() == hwnd:
return True
fg = user32.GetForegroundWindow()
fg_thread = user32.GetWindowThreadProcessId(fg, None)
cur_thread = kernel32.GetCurrentThreadId()
attached = False
if fg_thread and cur_thread and fg_thread != cur_thread:
attached = bool(user32.AttachThreadInput(cur_thread, fg_thread, True))
user32.BringWindowToTop(hwnd)
ok = bool(user32.SetForegroundWindow(hwnd))
if attached:
user32.AttachThreadInput(cur_thread, fg_thread, False)
return ok or user32.GetForegroundWindow() == hwnd
def foreground_browser(driver) -> bool:
"""Put the Selenium Edge/Chrome window in front so OS keystrokes hit the lesson."""
try:
driver.switch_to.window(driver.current_window_handle)
except Exception:
pass
try:
driver.execute_script("window.focus();")
except Exception:
pass
hwnd = pick_browser_hwnd(driver)
if hwnd:
return force_foreground(hwnd)
return False
def js_send_glyph(driver, glyph: str) -> None:
driver.execute_script(_JS_SEND_GLYPH, keys_for_char(glyph))
def cdp_send_glyph(driver, glyph: str) -> None:
info = glyph_payload(glyph)
vk = int(info.get("vk") or 0)
if info["glyph"] == " ":
vk = VK_SPACE
common = {
"key": info["key"],
"code": info["code"] or ("Space" if info["glyph"] == " " else ""),
"windowsVirtualKeyCode": vk,
"nativeVirtualKeyCode": vk,
"text": info["text"],
"unmodifiedText": info["text"],
}
driver.execute_cdp_cmd("Input.dispatchKeyEvent", {**common, "type": "keyDown"})
if info["text"]:
driver.execute_cdp_cmd(
"Input.dispatchKeyEvent",
{"type": "char", "key": info["key"], "text": info["text"], "unmodifiedText": info["text"]},
)
driver.execute_cdp_cmd("Input.dispatchKeyEvent", {**common, "type": "keyUp"})
def chains_send_glyph(driver, glyph: str) -> None:
from selenium.webdriver.common.action_chains import ActionChains
ActionChains(driver).send_keys(keys_for_char(glyph)).perform()
def _dispatch_glyph(driver, glyph: str, method: str) -> None:
if method == "os":
os_send_glyph(glyph)
elif method == "js":
js_send_glyph(driver, glyph)
elif method == "cdp":
cdp_send_glyph(driver, glyph)
elif method == "chains":
chains_send_glyph(driver, glyph)
else:
raise ValueError(method)
def _click_first(driver, locators) -> bool:
for by, value in locators:
try:
els = driver.find_elements(by, value)
except Exception:
continue
for el in els:
try:
if not el.is_displayed():
continue
href = (el.get_attribute("href") or "").lower()
text = (el.text or "").lower()
if "logout" in href or "abmelden" in text or "site/logout" in href:
continue
try:
el.click()
except Exception:
driver.execute_script("arguments[0].click();", el)
return True
except Exception:
continue
return False
def open_write_mode(driver, base: str | None = None) -> bool:
"""From the overview, open Schreiben / generateLevel so #text_todo_1 exists."""
if remaining_prompt_now(driver):
return True
if _click_first(driver, WRITE_CLICK):
time.sleep(0.6)
if remaining_prompt_now(driver):
return True
if base:
for path in ("/index.php?r=typewriter/generateLevel", LEVEL_PATH):
try:
driver.get(base.rstrip("/") + path)
time.sleep(0.5)
except Exception:
continue
if remaining_prompt_now(driver):
return True
return remaining_prompt_now(driver) is not None
def arm_lesson(driver, base: str | None = None) -> bool:
"""Open Schreibmodus, click start/OK dialogs, send Enter so the lesson hears keys."""
opened = open_write_mode(driver, base)
clicked = _click_first(driver, START_CLICK)
focus_typer(driver)
try:
os_send_glyph("\n")
except Exception:
try:
chains_send_glyph(driver, "\n")
except Exception:
pass
return opened or clicked
def send_glyph(driver, glyph: str, *, method: str | None = None) -> str:
"""Deliver one remaining glyph. Default: OS key into the focused browser, then JS/CDP/chains."""
glyph = keys_for_char(glyph)
focus_typer(driver)
order: list[str] = []
if method:
order = [method]
else:
pref = preferred_send()
order = list(SEND_METHODS)
if pref in order:
order.remove(pref)
order.insert(0, pref)
last_error: Exception | None = None
for name in order:
try:
_dispatch_glyph(driver, glyph, name)
remember_send(name)
return name
except Exception as exc:
last_error = exc
continue
if last_error:
raise last_error
raise RuntimeError("kein Tipp-Verfahren")
def send_glyph_verified(driver, glyph: str, before: str, *, settle_s: float = 0.12) -> str | None:
"""Try send methods until the remaining prompt actually changes."""
glyph = keys_for_char(glyph)
methods: list[str] = []
pref = preferred_send()
if pref:
methods.append(pref)
for name in SEND_METHODS:
if name not in methods: