-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtest_batch_selection.py
More file actions
512 lines (439 loc) · 15 KB
/
test_batch_selection.py
File metadata and controls
512 lines (439 loc) · 15 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
"""
Batch Selection Test Program
Tests different methods for selecting text to the left:
- VK: Virtual key codes
- ScanCode: Hardware scan codes (more reliable)
- UIA: TextPattern if available
Usage:
1. Run this script
2. Focus a text field with some text
3. Press 'G' to start the test
4. Click anywhere to stop the current test (program keeps running)
5. Press 'S' to stop the program
Results are saved to test_batch_selection_results.json
"""
import ctypes
import ctypes.wintypes as wintypes
import json
import string
import time
from dataclasses import dataclass, asdict
from pathlib import Path
from typing import Optional
# Windows API constants
INPUT_KEYBOARD = 1
KEYEVENTF_KEYUP = 0x0002
KEYEVENTF_SCANCODE = 0x0008
KEYEVENTF_EXTENDEDKEY = 0x0001
VK_SHIFT = 0x10
VK_LEFT = 0x25
VK_CONTROL = 0x11
VK_C = 0x43
user32 = ctypes.windll.user32
kernel32 = ctypes.windll.kernel32
# Set proper types for 64-bit handles
kernel32.GlobalAlloc.restype = ctypes.c_void_p
kernel32.GlobalLock.restype = ctypes.c_void_p
kernel32.GlobalLock.argtypes = [ctypes.c_void_p]
kernel32.GlobalUnlock.argtypes = [ctypes.c_void_p]
kernel32.GlobalFree.argtypes = [ctypes.c_void_p]
user32.SetClipboardData.argtypes = [wintypes.UINT, ctypes.c_void_p]
user32.GetClipboardData.restype = ctypes.c_void_p
# Input structures for SendInput
PUL = ctypes.POINTER(ctypes.c_ulong)
class KeyBdInput(ctypes.Structure):
_fields_ = [
("wVk", wintypes.WORD),
("wScan", wintypes.WORD),
("dwFlags", wintypes.DWORD),
("time", wintypes.DWORD),
("dwExtraInfo", PUL),
]
class HardwareInput(ctypes.Structure):
_fields_ = [
("uMsg", wintypes.DWORD),
("wParamL", wintypes.WORD),
("wParamH", wintypes.WORD),
]
class MouseInput(ctypes.Structure):
_fields_ = [
("dx", wintypes.LONG),
("dy", wintypes.LONG),
("mouseData", wintypes.DWORD),
("dwFlags", wintypes.DWORD),
("time", wintypes.DWORD),
("dwExtraInfo", ctypes.POINTER(ctypes.c_ulong)),
]
class InputUnion(ctypes.Union):
_fields_ = [("ki", KeyBdInput), ("mi", MouseInput), ("hi", HardwareInput)]
class Input(ctypes.Structure):
_fields_ = [("type", wintypes.DWORD), ("ii", InputUnion)]
@dataclass
class TestResult:
method: str
char_count: int
success: bool
expected: str
actual: str
time_ms: float
error: Optional[str] = None
def generate_test_pattern(length: int) -> str:
"""Generate test pattern like AaBbCcDd..."""
pattern = ""
letters = string.ascii_uppercase
for i in range(length):
letter_idx = (i // 2) % 26
if i % 2 == 0:
pattern += letters[letter_idx]
else:
pattern += letters[letter_idx].lower()
return pattern
def get_clipboard_text() -> str:
"""Get text from clipboard."""
user32.OpenClipboard(0)
try:
if user32.IsClipboardFormatAvailable(13): # CF_UNICODETEXT
h = user32.GetClipboardData(13) # CF_UNICODETEXT
if h:
ptr = kernel32.GlobalLock(h)
if ptr:
try:
return ctypes.wstring_at(ptr)
finally:
kernel32.GlobalUnlock(h)
return ""
finally:
user32.CloseClipboard()
def set_clipboard_text(text: str):
"""Set text to clipboard."""
if not user32.OpenClipboard(0):
print(f"[!] OpenClipboard failed")
return
try:
user32.EmptyClipboard()
# Allocate and set unicode text
data = ctypes.create_unicode_buffer(text)
size = (len(text) + 1) * 2
h = kernel32.GlobalAlloc(0x0002, size) # GMEM_MOVEABLE
if not h:
print(f"[!] GlobalAlloc failed")
return
ptr = kernel32.GlobalLock(h)
if not ptr:
print(f"[!] GlobalLock failed")
kernel32.GlobalFree(h)
return
ctypes.memmove(ptr, data, size)
kernel32.GlobalUnlock(h)
user32.SetClipboardData(13, h) # CF_UNICODETEXT
finally:
user32.CloseClipboard()
def send_ctrl_c():
"""Send Ctrl+C to copy selection."""
events = []
# Ctrl down
events.append(
Input(
type=INPUT_KEYBOARD,
ii=InputUnion(ki=KeyBdInput(wVk=VK_CONTROL, wScan=0, dwFlags=0)),
)
)
# C down
events.append(
Input(
type=INPUT_KEYBOARD,
ii=InputUnion(ki=KeyBdInput(wVk=VK_C, wScan=0, dwFlags=0)),
)
)
# C up
events.append(
Input(
type=INPUT_KEYBOARD,
ii=InputUnion(ki=KeyBdInput(wVk=VK_C, wScan=0, dwFlags=KEYEVENTF_KEYUP)),
)
)
# Ctrl up
events.append(
Input(
type=INPUT_KEYBOARD,
ii=InputUnion(ki=KeyBdInput(wVk=VK_CONTROL, wScan=0, dwFlags=KEYEVENTF_KEYUP)),
)
)
input_array = (Input * len(events))(*events)
user32.SendInput(len(events), ctypes.byref(input_array), ctypes.sizeof(Input))
def select_chars_left_vk(count: int):
"""Select N characters to the left using virtual key codes."""
events = []
# Shift down
events.append(
Input(
type=INPUT_KEYBOARD,
ii=InputUnion(ki=KeyBdInput(wVk=VK_SHIFT, wScan=0, dwFlags=0)),
)
)
# Left press+release N times
for _ in range(count):
events.append(
Input(
type=INPUT_KEYBOARD,
ii=InputUnion(ki=KeyBdInput(wVk=VK_LEFT, wScan=0, dwFlags=0)),
)
)
events.append(
Input(
type=INPUT_KEYBOARD,
ii=InputUnion(ki=KeyBdInput(wVk=VK_LEFT, wScan=0, dwFlags=KEYEVENTF_KEYUP)),
)
)
# Shift up
events.append(
Input(
type=INPUT_KEYBOARD,
ii=InputUnion(ki=KeyBdInput(wVk=VK_SHIFT, wScan=0, dwFlags=KEYEVENTF_KEYUP)),
)
)
input_array = (Input * len(events))(*events)
user32.SendInput(len(events), ctypes.byref(input_array), ctypes.sizeof(Input))
def select_chars_left_scancode(count: int):
"""Select N characters to the left using scan codes (more reliable)."""
events = []
scan_shift = user32.MapVirtualKeyW(VK_SHIFT, 0)
scan_left = user32.MapVirtualKeyW(VK_LEFT, 0)
# Shift down
events.append(
Input(
type=INPUT_KEYBOARD,
ii=InputUnion(ki=KeyBdInput(wVk=0, wScan=scan_shift, dwFlags=KEYEVENTF_SCANCODE)),
)
)
# Left press+release N times (extended key flag for arrow keys)
for _ in range(count):
events.append(
Input(
type=INPUT_KEYBOARD,
ii=InputUnion(
ki=KeyBdInput(
wVk=0,
wScan=scan_left,
dwFlags=KEYEVENTF_SCANCODE | KEYEVENTF_EXTENDEDKEY,
)
),
)
)
events.append(
Input(
type=INPUT_KEYBOARD,
ii=InputUnion(
ki=KeyBdInput(
wVk=0,
wScan=scan_left,
dwFlags=KEYEVENTF_SCANCODE | KEYEVENTF_EXTENDEDKEY | KEYEVENTF_KEYUP,
)
),
)
)
# Shift up
events.append(
Input(
type=INPUT_KEYBOARD,
ii=InputUnion(
ki=KeyBdInput(wVk=0, wScan=scan_shift, dwFlags=KEYEVENTF_SCANCODE | KEYEVENTF_KEYUP)
),
)
)
input_array = (Input * len(events))(*events)
user32.SendInput(len(events), ctypes.byref(input_array), ctypes.sizeof(Input))
def test_selection_method(method: str, count: int, expected_text: str) -> TestResult:
"""Test a selection method and return the result."""
# Clear clipboard
set_clipboard_text("")
time.sleep(0.02)
# Select text
start = time.perf_counter()
if method == "VK":
select_chars_left_vk(count)
elif method == "ScanCode":
select_chars_left_scancode(count)
else:
return TestResult(
method=method,
char_count=count,
success=False,
expected=expected_text,
actual="",
time_ms=0,
error="Unknown method",
)
time.sleep(0.05) # Let selection complete
# Copy selection
send_ctrl_c()
time.sleep(0.05)
elapsed_ms = (time.perf_counter() - start) * 1000
# Check result
actual = get_clipboard_text()
success = actual == expected_text
return TestResult(
method=method, char_count=count, success=success, expected=expected_text, actual=actual, time_ms=round(elapsed_ms, 2)
)
def paste_text(text: str):
"""Paste text using Ctrl+V."""
print("(clipboard", end="", flush=True)
set_clipboard_text(text)
print("->keys", end="", flush=True)
time.sleep(0.02)
# Ctrl+V
events = []
events.append(
Input(
type=INPUT_KEYBOARD,
ii=InputUnion(ki=KeyBdInput(wVk=VK_CONTROL, wScan=0, dwFlags=0)),
)
)
events.append(
Input(
type=INPUT_KEYBOARD,
ii=InputUnion(ki=KeyBdInput(wVk=0x56, wScan=0, dwFlags=0)),
)
) # V
events.append(
Input(
type=INPUT_KEYBOARD,
ii=InputUnion(ki=KeyBdInput(wVk=0x56, wScan=0, dwFlags=KEYEVENTF_KEYUP)),
)
)
events.append(
Input(
type=INPUT_KEYBOARD,
ii=InputUnion(ki=KeyBdInput(wVk=VK_CONTROL, wScan=0, dwFlags=KEYEVENTF_KEYUP)),
)
)
input_array = (Input * len(events))(*events)
user32.SendInput(len(events), ctypes.byref(input_array), ctypes.sizeof(Input))
print("->sent)", end="", flush=True)
def run_tests(stop_flag: dict):
"""Run the full test suite.
Args:
stop_flag: Dict with 'clicked' key that gets set True on mouse click.
"""
print("\n" + "=" * 60)
print("BATCH SELECTION TEST SUITE")
print("=" * 60)
print("\nTesting in 3 seconds... ensure text field is focused!")
print("(Click anywhere to stop the test)")
time.sleep(3)
results = []
methods = ["VK", "ScanCode"]
output_file = Path("test_batch_selection_results.json")
# Clear results file at start of each run
with open(output_file, "w") as f:
json.dump([], f)
# Test from 4 to 200 chars in steps of 4
for char_count in range(4, 201, 4):
# Check for mouse click stop
if stop_flag.get('clicked'):
print("\n\n[!] Test stopped by mouse click")
break
pattern = generate_test_pattern(char_count)
print(f"\n--- Testing {char_count} characters ---")
for method in methods:
# Insert test pattern
print(f" Pasting {len(pattern)} chars...", end=" ", flush=True)
paste_text(pattern)
print("done", flush=True)
time.sleep(0.1)
# Test selection
result = test_selection_method(method, char_count, pattern)
results.append(result)
status = "[OK]" if result.success else "[FAIL]"
print(f" {method:10} {status} {result.time_ms:6.1f}ms", end="")
if not result.success:
print(f" (got {len(result.actual)} chars: '{result.actual[:20]}...')", end="")
print()
# Save results after each test
with open(output_file, "w") as f:
json.dump([asdict(r) for r in results], f, indent=2)
# Delete the selected text to reset for next test
if result.success:
# Selection exists, delete it
events = [
Input(
type=INPUT_KEYBOARD,
ii=InputUnion(ki=KeyBdInput(wVk=0x2E, wScan=0, dwFlags=0)),
), # Delete
Input(
type=INPUT_KEYBOARD,
ii=InputUnion(ki=KeyBdInput(wVk=0x2E, wScan=0, dwFlags=KEYEVENTF_KEYUP)),
),
]
input_array = (Input * len(events))(*events)
user32.SendInput(len(events), ctypes.byref(input_array), ctypes.sizeof(Input))
else:
# Selection failed, need to manually delete the pattern
# Select all and delete (Ctrl+A, Delete)
select_chars_left_scancode(char_count + 50) # Select more than we inserted
time.sleep(0.05)
events = [
Input(
type=INPUT_KEYBOARD,
ii=InputUnion(ki=KeyBdInput(wVk=0x2E, wScan=0, dwFlags=0)),
),
Input(
type=INPUT_KEYBOARD,
ii=InputUnion(ki=KeyBdInput(wVk=0x2E, wScan=0, dwFlags=KEYEVENTF_KEYUP)),
),
]
input_array = (Input * len(events))(*events)
user32.SendInput(len(events), ctypes.byref(input_array), ctypes.sizeof(Input))
time.sleep(0.1)
print(f"\n\nResults saved to {output_file}")
# Print summary
print("\n" + "=" * 60)
print("SUMMARY")
print("=" * 60)
for method in methods:
method_results = [r for r in results if r.method == method]
successes = sum(1 for r in method_results if r.success)
max_success = max((r.char_count for r in method_results if r.success), default=0)
avg_time = sum(r.time_ms for r in method_results if r.success) / max(successes, 1)
print(f"{method:10} Success: {successes}/{len(method_results)} Max: {max_success} chars Avg: {avg_time:.1f}ms")
def main():
from pynput import keyboard, mouse
# Initialize COM for UIA in listener thread
ctypes.windll.ole32.CoInitialize(None)
running = True
testing = False
stop_flag = {'clicked': False}
def on_press(key):
nonlocal running, testing
try:
if hasattr(key, "char"):
if key.char == "g" and not testing:
testing = True
stop_flag['clicked'] = False
print("\nStarting tests...")
run_tests(stop_flag)
testing = False
print("\nPress 'G' to run again, 'S' to stop")
elif key.char == "s":
print("\nStopping...")
running = False
return False
except Exception as e:
print(f"Error: {e}")
def on_click(x, y, button, pressed):
if pressed and testing:
stop_flag['clicked'] = True
print("Batch Selection Test Program")
print("-" * 40)
print("Press 'G' to start tests on focused element")
print("Click anywhere to stop current test")
print("Press 'S' to stop the program")
print("-" * 40)
mouse_listener = mouse.Listener(on_click=on_click)
mouse_listener.start()
with keyboard.Listener(on_press=on_press) as listener:
while running:
time.sleep(0.1)
mouse_listener.stop()
if __name__ == "__main__":
main()