-
-
Notifications
You must be signed in to change notification settings - Fork 12
Expand file tree
/
Copy pathAutoClicker.py
More file actions
8026 lines (7097 loc) · 392 KB
/
Copy pathAutoClicker.py
File metadata and controls
8026 lines (7097 loc) · 392 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import time
import tkinter as tk
import webbrowser
from tkinter import *
from tkinter import messagebox
from tkinter import ttk
from tkinter import filedialog
import os
import sys
import datetime
import threading
import queue
import json
import random
import math
import platform
import warnings
import shutil
import re
IMPORT_ERRORS = {}
APP_VERSION = "V11.0"
APP_STATE_DIR_NAME = "AutoClicker"
PROFILE_FILE_NAME = "autoclicker_profiles.json"
WORKSPACE_FILE_NAME = "autoclicker_workspace.json"
RUN_LOG_FILE_NAME = "autoclicker_runs.log"
STATE_SCHEMA_VERSION = 2
DEFAULT_CLICK_TYPES = {
"Left Click": ("left", 1),
"Right Click": ("right", 1),
"Middle Click": ("middle", 1),
"Double Left Click": ("left", 2),
"Double Right Click": ("right", 2),
"Double Middle Click": ("middle", 2),
}
# Every action the run engine can emit. "click" entries reproduce DEFAULT_CLICK_TYPES exactly,
# so existing profiles, sequences and workspaces keep loading unchanged.
ACTION_REGISTRY = {
"Left Click": {"kind": "click", "button": "left", "clicks": 1},
"Right Click": {"kind": "click", "button": "right", "clicks": 1},
"Middle Click": {"kind": "click", "button": "middle", "clicks": 1},
"Double Left Click": {"kind": "click", "button": "left", "clicks": 2},
"Double Right Click": {"kind": "click", "button": "right", "clicks": 2},
"Double Middle Click": {"kind": "click", "button": "middle", "clicks": 2},
"Triple Left Click": {"kind": "click", "button": "left", "clicks": 3},
"Key Press": {"kind": "key", "uses": ("action_key",)},
"Key Hold": {"kind": "key_hold", "uses": ("action_key", "hold_duration")},
"Type Text": {"kind": "text", "uses": ("action_text",)},
"Scroll Up": {"kind": "scroll", "direction": 1, "uses": ("scroll_amount",)},
"Scroll Down": {"kind": "scroll", "direction": -1, "uses": ("scroll_amount",)},
"Click And Hold": {"kind": "hold", "button": "left", "uses": ("hold_duration",)},
"Drag To": {"kind": "drag", "button": "left", "uses": ("drag_to_x", "drag_to_y", "hold_duration")},
"Move Only": {"kind": "move"},
}
ACTION_DEFAULTS = {
"action_key": "space",
"action_text": "",
"scroll_amount": 3,
"hold_duration": 0.25,
"drag_to_x": 0,
"drag_to_y": 0,
}
PROFILE_FIELDS = {
"target_x",
"target_y",
"click_mode",
"delay",
"delay_variance",
"jitter_x",
"jitter_y",
"countdown",
"runtime_limit",
"max_actions",
"stop_hotkey",
"repeat_mode",
"repeat_count",
"behaviour_preset",
"micro_pause_every",
"micro_pause_duration",
"topmost",
"minimize_on_start",
"restore_after_run",
"close_to_tray",
"fullscreen",
"remember_window_geometry",
"window_opacity",
"ui_scale",
"human_like",
"play_sound",
"dry_run",
"pyautogui_failsafe",
"theme",
"action_key",
"action_text",
"scroll_amount",
"hold_duration",
"drag_to_x",
"drag_to_y",
"pacing_mode",
"scheduled_start",
"target_cps",
}
PROFILE_INT_FIELDS = {
"target_x",
"target_y",
"jitter_x",
"jitter_y",
"max_actions",
"micro_pause_every",
"repeat_count",
"scroll_amount",
"drag_to_x",
"drag_to_y",
}
PROFILE_FLOAT_FIELDS = {
"delay",
"delay_variance",
"countdown",
"runtime_limit",
"micro_pause_duration",
"window_opacity",
"ui_scale",
"hold_duration",
"target_cps",
}
PROFILE_BOOL_FIELDS = {
"topmost",
"minimize_on_start",
"restore_after_run",
"close_to_tray",
"fullscreen",
"remember_window_geometry",
"human_like",
"play_sound",
"dry_run",
"pyautogui_failsafe",
}
PROFILE_ENUM_FIELDS = {
"click_mode": set(ACTION_REGISTRY),
"repeat_mode": {"Infinite", "Burst Count"},
"behaviour_preset": {"Balanced", "Precision", "Burst Sprint", "Human Mimic", "Feather Touch"},
"theme": {"Light", "Dark", "Ocean", "Midnight", "System"},
"pacing_mode": {"Precise", "Legacy V10.1"},
}
# The validator used to warn outside 0.2-1.0 / 0.5-2.0 while the runtime clamped to these
# tighter bounds, so a "valid" profile could still be silently changed on load.
WINDOW_OPACITY_RANGE = (0.70, 1.00)
UI_SCALE_RANGE = (0.90, 1.35)
SAFETY_PRESETS = {
"Simulation": {
"dry_run": True,
"pyautogui_failsafe": True,
"max_actions": "25",
},
"Guarded Live": {
"dry_run": False,
"pyautogui_failsafe": True,
"max_actions": "250",
},
"Manual Stop Live": {
"dry_run": False,
"pyautogui_failsafe": True,
"max_actions": "0",
},
}
def _resource_path(file_name):
"""Resolve bundled resources from source checkouts and PyInstaller builds."""
bundle_root = getattr(sys, "_MEIPASS", None)
search_roots = [
bundle_root,
os.path.dirname(os.path.abspath(__file__)),
os.getcwd(),
]
for root in search_roots:
if not root:
continue
candidate = os.path.join(root, file_name)
if os.path.exists(candidate):
return candidate
return os.path.join(os.getcwd(), file_name)
def _state_dir():
state_root = os.environ.get("APPDATA") or os.environ.get("LOCALAPPDATA")
if state_root:
return os.path.join(state_root, APP_STATE_DIR_NAME)
return os.getcwd()
def _state_file_location(file_name):
return os.path.join(_state_dir(), file_name)
def _copy_legacy_state_file(file_name, destination):
legacy_path = os.path.join(os.getcwd(), file_name)
if os.path.abspath(legacy_path) == os.path.abspath(destination):
return
if not os.path.exists(legacy_path) or os.path.exists(destination):
return
try:
with open(legacy_path, "r", encoding="utf-8") as source_handle:
legacy_contents = source_handle.read()
with open(destination, "w", encoding="utf-8") as destination_handle:
destination_handle.write(legacy_contents)
except Exception:
pass
def _state_file_path(file_name):
directory = _state_dir()
try:
os.makedirs(directory, exist_ok=True)
except Exception:
directory = os.getcwd()
destination = os.path.join(directory, file_name)
_copy_legacy_state_file(file_name, destination)
return destination
def _atomic_write_json(path, payload, sort_keys=False):
directory = os.path.dirname(path) or os.getcwd()
os.makedirs(directory, exist_ok=True)
temp_path = f"{path}.tmp"
try:
with open(temp_path, "w", encoding="utf-8") as file_handle:
json.dump(payload, file_handle, indent=2, sort_keys=sort_keys)
file_handle.flush()
try:
os.fsync(file_handle.fileno())
except Exception:
pass
os.replace(temp_path, path)
except Exception:
try:
if os.path.exists(temp_path):
os.remove(temp_path)
except Exception:
pass
raise
def _interruptible_sleep(duration, should_stop=None, slice_seconds=0.02, clock=None, sleeper=None):
"""Sleep up to `duration`, checking `should_stop` between short slices.
Returns True when the full duration elapsed and False when `should_stop` cut it short.
Sleep arguments are clamped to >= 0 so a descheduled thread can never hit
ValueError: sleep length must be non-negative.
"""
clock = clock or time.perf_counter
sleeper = sleeper or time.sleep
try:
duration = float(duration)
except Exception:
return True
if duration <= 0:
return not (should_stop is not None and should_stop())
slice_seconds = max(0.001, float(slice_seconds))
wake_at = clock() + duration
while True:
if should_stop is not None and should_stop():
return False
remaining = wake_at - clock()
if remaining <= 0:
return True
sleeper(max(0.0, min(slice_seconds, remaining)))
def _resolve_action(action_name, config=None, registry=None):
"""Describe an action as {kind, callable name, kwargs} without touching pyautogui.
Keeping dispatch declarative means every action the engine can emit is verifiable
headlessly, on machines with no display and no pyautogui installed.
"""
registry = registry if registry is not None else ACTION_REGISTRY
if action_name not in registry:
raise ValueError(f"Unknown action type: {action_name!r}")
spec = registry[action_name]
config = config or {}
def setting(name):
value = config.get(name, ACTION_DEFAULTS.get(name))
return ACTION_DEFAULTS.get(name) if value is None else value
kind = spec["kind"]
x_pos, y_pos = config.get("x", 0), config.get("y", 0)
if kind == "click":
return {"kind": kind, "call": "click",
"kwargs": {"x": x_pos, "y": y_pos, "button": spec["button"], "clicks": spec["clicks"]}}
if kind == "move":
return {"kind": kind, "call": "moveTo", "kwargs": {"x": x_pos, "y": y_pos}}
if kind == "key":
key_name = str(setting("action_key")).strip()
if not key_name:
raise ValueError("Key Press needs a key name (for example: space, enter, f5, a).")
return {"kind": kind, "call": "press", "kwargs": {"keys": key_name}}
if kind == "key_hold":
key_name = str(setting("action_key")).strip()
if not key_name:
raise ValueError("Key Hold needs a key name (for example: shift, w, ctrl).")
return {"kind": kind, "call": "keyDown/keyUp",
"kwargs": {"key": key_name, "hold_duration": max(0.0, float(setting("hold_duration")))}}
if kind == "text":
text_value = str(setting("action_text"))
if not text_value:
raise ValueError("Type Text needs some text to type.")
return {"kind": kind, "call": "write", "kwargs": {"message": text_value}}
if kind == "scroll":
magnitude = abs(int(setting("scroll_amount")))
if magnitude == 0:
raise ValueError("Scroll amount must not be zero.")
return {"kind": kind, "call": "scroll",
"kwargs": {"clicks": magnitude * spec["direction"], "x": x_pos, "y": y_pos}}
if kind == "hold":
return {"kind": kind, "call": "mouseDown/mouseUp",
"kwargs": {"x": x_pos, "y": y_pos, "button": spec["button"],
"hold_duration": max(0.0, float(setting("hold_duration")))}}
if kind == "drag":
return {"kind": kind, "call": "mouseDown/moveTo/mouseUp",
"kwargs": {"x": x_pos, "y": y_pos,
"to_x": int(setting("drag_to_x")), "to_y": int(setting("drag_to_y")),
"button": spec["button"],
"hold_duration": max(0.0, float(setting("hold_duration")))}}
raise ValueError(f"Unsupported action kind: {kind!r}")
def _action_moves_pointer(action_name, registry=None):
"""True when the action is anchored to the target coordinate."""
registry = registry if registry is not None else ACTION_REGISTRY
spec = registry.get(action_name) or {}
return spec.get("kind") not in ("key", "key_hold", "text")
def _cps_to_delay(cps):
"""Convert a clicks-per-second target into a per-action delay in seconds."""
try:
cps = float(cps)
except Exception:
return None
if cps <= 0:
return None
return 1.0 / cps
def _delay_to_cps(delay):
"""Convert a per-action delay into clicks per second. Zero delay means unbounded."""
try:
delay = float(delay)
except Exception:
return None
if delay <= 0:
return None
return 1.0 / delay
def _rate_stats(samples, window_seconds=3.0):
"""Summarise (timestamp, cumulative_actions) samples into instant/average/peak rates."""
points = [(float(t), int(n)) for t, n in (samples or [])]
if len(points) < 2:
return {"instant_cps": 0.0, "average_cps": 0.0, "peak_cps": 0.0, "samples": len(points)}
first_time, first_count = points[0]
last_time, last_count = points[-1]
span = last_time - first_time
average = (last_count - first_count) / span if span > 0 else 0.0
window_start = last_time - max(0.001, float(window_seconds))
windowed = [p for p in points if p[0] >= window_start] or points[-2:]
window_span = windowed[-1][0] - windowed[0][0]
instant = (windowed[-1][1] - windowed[0][1]) / window_span if window_span > 0 else average
peak = 0.0
for (t0, n0), (t1, n1) in zip(points, points[1:]):
step = t1 - t0
if step > 0:
peak = max(peak, (n1 - n0) / step)
return {
"instant_cps": round(instant, 3),
"average_cps": round(average, 3),
"peak_cps": round(peak, 3),
"samples": len(points),
}
def _effective_action_period(delay, pacing_mode="Precise", human_like=False, library_pause=0.1):
"""Predict the real seconds-per-action, including PyAutoGUI's own inter-call pause.
In Legacy V10.1 mode pyautogui.PAUSE is left at its default, so each emitted call
silently adds `library_pause`; the UI used to promise the raw delay and be wrong by 2-3x.
"""
try:
delay = max(0.0, float(delay))
except Exception:
delay = 0.0
if pacing_mode == "Precise":
overhead = 0.0
else:
overhead = float(library_pause) * (2 if human_like else 1)
if human_like:
overhead += 0.03 # average of the 0.01-0.05s humanised moveTo duration
return delay + overhead
def _validate_hotkey(hotkey, parser=None):
"""Check a hotkey string is one `keyboard` can actually poll.
`keyboard.is_pressed` raises for multi-step hotkeys ("a, b") and unmapped key names,
and the engine used to swallow that, leaving a run with a silently inert stop key.
"""
hotkey = str(hotkey or "").strip()
if not hotkey:
return {"valid": False, "hotkey": "", "reason": "No hotkey set."}
if "," in hotkey:
return {
"valid": False,
"hotkey": hotkey,
"reason": "Multi-step hotkeys (\"a, b\") cannot be polled; use a combination like ctrl+k.",
}
if parser is None:
parser = globals().get("keyboard")
parser = getattr(parser, "parse_hotkey", None) if parser else None
if parser is None:
return {"valid": True, "hotkey": hotkey, "reason": "Not verified: keyboard support is unavailable."}
try:
parser(hotkey)
except Exception as exc:
return {"valid": False, "hotkey": hotkey, "reason": f"'{hotkey}' is not a key this system recognises ({exc})."}
return {"valid": True, "hotkey": hotkey, "reason": f"Stop hotkey is {hotkey}."}
def _clamp_geometry_to_screen(geometry, screen_width, screen_height, margin=80):
"""Keep a restored "WxH+X+Y" geometry on-screen.
A layout saved on a second monitor used to be restored verbatim, putting the
window somewhere the user could not reach it.
"""
text = str(geometry or "").strip()
match = re.match(r"^(\d+)x(\d+)([+-]-?\d+)([+-]-?\d+)$", text)
if not match:
return text
width, height = int(match.group(1)), int(match.group(2))
x_pos, y_pos = int(match.group(3)), int(match.group(4))
width = max(200, min(width, int(screen_width)))
height = max(200, min(height, int(screen_height)))
x_pos = max(0, min(x_pos, max(0, int(screen_width) - margin)))
y_pos = max(0, min(y_pos, max(0, int(screen_height) - margin)))
return f"{width}x{height}+{x_pos}+{y_pos}"
def _detect_system_theme(reader=None):
"""Resolve the OS appearance preference to "Light" or "Dark".
`reader` lets tests inject a value; on Windows the real source is the
AppsUseLightTheme registry value under Personalize.
"""
if reader is not None:
try:
return "Dark" if not reader() else "Light"
except Exception:
return "Light"
try:
import winreg
key_path = r"Software\Microsoft\Windows\CurrentVersion\Themes\Personalize"
with winreg.OpenKey(winreg.HKEY_CURRENT_USER, key_path) as key:
apps_use_light, _ = winreg.QueryValueEx(key, "AppsUseLightTheme")
return "Light" if apps_use_light else "Dark"
except Exception:
return "Light"
def _rotate_run_log(log_path, keep=1):
"""Roll `x.log` to `x.log.1` so the live log never grows without bound."""
try:
oldest = f"{log_path}.{keep}"
if os.path.exists(oldest):
os.remove(oldest)
for index in range(keep - 1, 0, -1):
source = f"{log_path}.{index}"
if os.path.exists(source):
os.replace(source, f"{log_path}.{index + 1}")
if os.path.exists(log_path):
os.replace(log_path, f"{log_path}.1")
return True
except Exception:
return False
def _read_run_log(log_path, limit=200):
"""Read the newest `limit` run records back out of the JSON-lines run log."""
records = []
if not log_path or not os.path.exists(log_path):
return records
try:
with open(log_path, "r", encoding="utf-8") as handle:
for line in handle:
line = line.strip()
if not line:
continue
try:
records.append(json.loads(line))
except Exception:
continue
except Exception:
return records
return records[-limit:] if limit else records
def _summarize_run_history(records):
"""Aggregate run records into lifetime totals the dashboard can show."""
records = [r for r in (records or []) if isinstance(r, dict)]
total_actions = sum(int(r.get("actions", 0) or 0) for r in records)
total_seconds = sum(float(r.get("elapsed_seconds", 0) or 0) for r in records)
live = [r for r in records if not r.get("dry_run")]
reasons = {}
for record in records:
reason = str(record.get("stop_reason", "unknown"))
reasons[reason] = reasons.get(reason, 0) + 1
return {
"runs": len(records),
"live_runs": len(live),
"dry_runs": len(records) - len(live),
"actions": total_actions,
"seconds": round(total_seconds, 3),
"average_cps": round(total_actions / total_seconds, 3) if total_seconds > 0 else 0.0,
"stop_reasons": reasons,
"last_run": records[-1] if records else None,
}
def _parse_scheduled_start(value, now=None):
"""Resolve a HH:MM / HH:MM:SS wall-clock start into seconds from `now`.
A time earlier than `now` means tomorrow, so "start at 09:00" set in the evening waits.
"""
text = str(value or "").strip()
if not text:
return {"scheduled": False, "delay_seconds": 0.0, "detail": "No scheduled start."}
for fmt in ("%H:%M:%S", "%H:%M"):
try:
parsed = datetime.datetime.strptime(text, fmt)
break
except ValueError:
parsed = None
if parsed is None:
return {"scheduled": False, "delay_seconds": 0.0, "error": f"'{text}' is not a HH:MM or HH:MM:SS time."}
now = now or datetime.datetime.now()
target = now.replace(hour=parsed.hour, minute=parsed.minute, second=parsed.second, microsecond=0)
if target <= now:
target += datetime.timedelta(days=1)
delay_seconds = (target - now).total_seconds()
return {
"scheduled": True,
"delay_seconds": round(delay_seconds, 3),
"start_at": target.isoformat(timespec="seconds"),
"detail": f"Waiting {_format_seconds(delay_seconds)} until {target.strftime('%H:%M:%S')}.",
}
def _format_seconds(seconds):
try:
seconds = float(seconds)
except Exception:
return "unknown"
if seconds < 60:
return f"{seconds:.2f}s"
minutes, remainder = divmod(int(round(seconds)), 60)
if minutes < 60:
return f"{minutes}m {remainder:02d}s"
hours, minutes = divmod(minutes, 60)
return f"{hours}h {minutes:02d}m {remainder:02d}s"
def _build_readiness_checklist(config, screen_size=None):
items = []
def add(label, state, detail):
items.append({"label": label, "state": state, "detail": detail})
x_pos = int(config.get("x", 0))
y_pos = int(config.get("y", 0))
if screen_size:
screen_width, screen_height = screen_size
if 0 <= x_pos < screen_width and 0 <= y_pos < screen_height:
add("Target", "ok", f"{x_pos}, {y_pos} is inside the screen.")
else:
clamped_x = max(0, min(screen_width - 1, x_pos))
clamped_y = max(0, min(screen_height - 1, y_pos))
add("Target", "review", f"{x_pos}, {y_pos} is outside the screen; run clamps to {clamped_x}, {clamped_y}.")
else:
add("Target", "ok", f"{x_pos}, {y_pos} configured.")
if config.get("dry_run"):
add("Output", "ok", "Dry run is on; no clicks will be sent.")
else:
add("Output", "ok", "Live click output is enabled.")
if config.get("pyautogui_failsafe"):
add("Fail-safe", "ok", "PyAutoGUI corner fail-safe is enabled.")
else:
add("Fail-safe", "review", "Corner fail-safe is off.")
repeat_limit = config.get("repeat_limit")
runtime_limit = float(config.get("runtime_limit", 0))
max_actions = int(config.get("max_actions", 0))
if repeat_limit is not None:
add("Stop boundary", "ok", f"Burst count stops after {repeat_limit} action(s).")
elif runtime_limit > 0:
add("Stop boundary", "ok", f"Runtime cap stops after {_format_seconds(runtime_limit)}.")
elif max_actions > 0:
add("Stop boundary", "ok", f"Max action cap stops after {max_actions} action(s).")
else:
add("Stop boundary", "review", "No runtime or action cap is set.")
delay = float(config.get("delay", 0))
pacing_mode = config.get("pacing_mode", "Precise")
effective_period = _effective_action_period(delay, pacing_mode, config.get("human_like"))
if delay == 0:
add("Pace", "review", "Zero delay uses maximum available pace.")
elif abs(effective_period - delay) > 0.005:
add(
"Pace",
"review",
f"Base delay is {_format_seconds(delay)} but {pacing_mode} pacing makes each action take "
f"about {effective_period:.3f}s ({_delay_to_cps(effective_period) or 0:.1f}/sec).",
)
else:
add("Pace", "ok", f"Base delay is {_format_seconds(delay)} (about {_delay_to_cps(delay) or 0:.1f} action(s)/sec).")
# A hotkey that `keyboard` cannot poll used to be reported green while being inert.
hotkey_check = _validate_hotkey(config.get("stop_hotkey"))
if config.get("stop_hotkey"):
if hotkey_check["valid"]:
add("Stop hotkey", "ok", hotkey_check["reason"])
else:
add("Stop hotkey", "review", hotkey_check["reason"])
elif repeat_limit is None and runtime_limit == 0 and max_actions == 0:
add("Stop hotkey", "review", "Continuous run has no stop hotkey.")
action_name = config.get("click_mode")
if action_name:
try:
_resolve_action(action_name, config)
add("Action", "ok", f"{action_name} is configured correctly.")
except Exception as exc:
add("Action", "review", str(exc))
schedule = config.get("schedule") or {}
if schedule.get("error"):
add("Scheduled start", "review", schedule["error"])
elif schedule.get("scheduled"):
add("Scheduled start", "ok", schedule.get("detail", "Scheduled."))
targets = config.get("targets") or []
if len(targets) > 1:
add("Targets", "ok", f"Round-robin cycles {len(targets)} recorded point(s).")
review_count = sum(1 for item in items if item["state"] == "review")
status = "Ready" if review_count == 0 else f"Review {review_count} item(s)"
return {
"ready": review_count == 0,
"status": status,
"review_count": review_count,
"items": items,
}
def _format_readiness_text(readiness, limit=6):
lines = [f"Readiness: {readiness['status']}"]
for item in readiness["items"][:limit]:
prefix = "OK" if item["state"] == "ok" else "Review"
lines.append(f"- {prefix} {item['label']}: {item['detail']}")
remaining = len(readiness["items"]) - limit
if remaining > 0:
lines.append(f"- +{remaining} more check(s)")
return "\n".join(lines)
def _profile_payload_key(profile_data):
try:
return json.dumps(profile_data or {}, sort_keys=True, default=str)
except Exception:
return repr(profile_data)
def _build_profile_state(profile_name, profile_choice, current_profile, saved_profiles):
profile_name = str(profile_name or "").strip()
profile_choice = str(profile_choice or "").strip()
saved_profiles = saved_profiles if isinstance(saved_profiles, dict) else {}
if not profile_name and not profile_choice:
return {
"state": "review",
"profile_name": "",
"profile_choice": "",
"detail": "Enter a profile name before saving this setup.",
}
active_name = profile_name or profile_choice
saved_profile = saved_profiles.get(active_name)
selection_note = ""
if profile_name and profile_choice and profile_name != profile_choice:
selection_note = f" Selected profile is '{profile_choice}'."
if saved_profile is None:
return {
"state": "new",
"profile_name": active_name,
"profile_choice": profile_choice,
"detail": f"'{active_name}' is not saved yet.{selection_note}",
}
if _profile_payload_key(current_profile) == _profile_payload_key(saved_profile):
return {
"state": "saved",
"profile_name": active_name,
"profile_choice": profile_choice,
"detail": f"'{active_name}' matches the saved profile.{selection_note}",
}
return {
"state": "modified",
"profile_name": active_name,
"profile_choice": profile_choice,
"detail": f"'{active_name}' has unsaved changes.{selection_note}",
}
def _format_profile_state_text(profile_state):
labels = {
"saved": "Saved",
"modified": "Modified",
"new": "New",
"review": "Review",
}
label = labels.get(profile_state.get("state"), "Profile")
return f"Profile: {label} - {profile_state.get('detail', '')}"
try:
import pystray
from pystray import MenuItem as item
except Exception as exc:
pystray = None
item = None
IMPORT_ERRORS["pystray"] = str(exc)
try:
import pyautogui
except Exception as exc:
pyautogui = None
IMPORT_ERRORS["pyautogui"] = str(exc)
try:
import keyboard
except Exception as exc:
keyboard = None
IMPORT_ERRORS["keyboard"] = str(exc)
try:
from PIL import Image, ImageTk, ImageGrab
except Exception as exc:
Image = None
ImageTk = None
ImageGrab = None
IMPORT_ERRORS["Pillow"] = str(exc)
try:
import winsound
except ImportError:
winsound = None
DEPENDENCY_CATALOGUE = {
"pyautogui": {"module": "pyautogui", "required": True, "unlocks": "click, scroll, key and drag output"},
"keyboard": {"module": "keyboard", "required": True, "unlocks": "stop hotkey, global hotkeys, point recording"},
"pystray": {"module": "pystray", "required": False, "unlocks": "close-to-tray and the tray menu"},
"Pillow": {"module": "PIL", "required": False, "unlocks": "Photo Clicker previews and screen sampling"},
"numpy": {"module": "numpy", "required": False, "unlocks": "fast Colour Clicker region scanning"},
"opencv-python": {"module": "cv2", "required": False, "unlocks": "Photo Clicker confidence matching"},
"win10toast": {"module": "win10toast", "required": False, "unlocks": "Windows toast notifications"},
}
def _collect_dependency_health(catalogue=None):
"""Resolve every catalogued dependency to an availability record. Pure and headless."""
import importlib.util
catalogue = catalogue if catalogue is not None else DEPENDENCY_CATALOGUE
dependencies = {}
for dependency_name, spec in catalogue.items():
module_name = spec["module"]
if dependency_name in IMPORT_ERRORS:
available, detail = False, IMPORT_ERRORS[dependency_name]
else:
try:
found = importlib.util.find_spec(module_name) is not None
except Exception as exc:
found, detail = False, f"probe failed: {exc}"
else:
detail = "available" if found else "module not found"
available = found
dependencies[dependency_name] = {
"available": available,
"detail": detail,
"required": bool(spec.get("required")),
"unlocks": spec.get("unlocks", ""),
}
return dependencies
def _missing_required_dependencies(dependencies):
"""Names of required dependencies that are unavailable, sorted for stable output."""
return sorted(
name
for name, data in (dependencies or {}).items()
if data.get("required") and not data.get("available")
)
def _collect_headless_health_data():
dependencies = _collect_dependency_health()
profile_file = _state_file_location(PROFILE_FILE_NAME)
workspace_file = _state_file_location(WORKSPACE_FILE_NAME)
return {
"app_version": APP_VERSION,
"os": f"{platform.system()} {platform.release()}",
"python": sys.version.split()[0],
"resource_root": os.path.dirname(_resource_path("favicon.ico")),
"dependencies": dependencies,
"missing_required": _missing_required_dependencies(dependencies),
"state_files": {
"profiles": {
"path": profile_file,
"present": os.path.exists(profile_file),
},
"workspace": {
"path": workspace_file,
"present": os.path.exists(workspace_file),
},
},
}
def _build_headless_health_report():
health_data = _collect_headless_health_data()
dependency_lines = []
for dependency_name, dependency_data in health_data["dependencies"].items():
tier = "required" if dependency_data.get("required") else "optional"
if dependency_data["available"]:
dependency_lines.append(f"- {dependency_name} ({tier}): available")
else:
unlocks = dependency_data.get("unlocks") or "extra features"
dependency_lines.append(
f"- {dependency_name} ({tier}): missing ({dependency_data['detail']}) - unlocks {unlocks}"
)
missing_required = health_data.get("missing_required") or []
if missing_required:
dependency_lines.append(f"- ACTION: pip install {' '.join(missing_required)}")
profile_file = health_data["state_files"]["profiles"]
workspace_file = health_data["state_files"]["workspace"]
sections = [
"AutoClicker Health Check",
f"- App version: {health_data['app_version']}",
f"- OS: {health_data['os']}",
f"- Python: {health_data['python']}",
f"- Resource root: {health_data['resource_root']}",
"",
"Dependencies",
*dependency_lines,
"",
"State Files",
f"- Profiles file: {'present' if profile_file['present'] else 'not created yet'}",
f" {profile_file['path']}",
f"- Workspace file: {'present' if workspace_file['present'] else 'not created yet'}",
f" {workspace_file['path']}",
]
return "\n".join(sections)
def _build_session_report_payload(profile_data, activity_history, run_reports, state_files=None):
return {
"app_version": APP_VERSION,
"generated_at": datetime.datetime.now().isoformat(timespec="seconds"),
"platform": {
"os": f"{platform.system()} {platform.release()}",
"python": sys.version.split()[0],
},
"profile_data": dict(profile_data),
"activity_history": [str(entry) for entry in activity_history[-80:]],
"run_reports": list(run_reports[-40:]),
"state_files": dict(state_files or {}),
}
def _file_info(path):
present = os.path.exists(path)
info = {
"path": path,
"present": present,
"size_bytes": 0,
"modified_at": None,
}
if present:
try:
stat_result = os.stat(path)
info["size_bytes"] = stat_result.st_size
info["modified_at"] = datetime.datetime.fromtimestamp(stat_result.st_mtime).isoformat(timespec="seconds")
except Exception as exc:
info["error"] = str(exc)
return info
def _load_json_file(path):
with open(path, "r", encoding="utf-8-sig") as file_handle:
return json.load(file_handle)
def _normalize_recording_points(raw_points, limit=200, strict=True):
if not isinstance(raw_points, list):
raise ValueError("Recording files must contain a list of coordinate pairs.")
cleaned_points = []
for index, point in enumerate(raw_points, start=1):
try:
if not isinstance(point, (list, tuple)) or len(point) != 2:
raise ValueError("expected [x, y]")
cleaned_points.append((int(point[0]), int(point[1])))
except Exception as exc:
if strict:
raise ValueError(f"Point {index} is invalid: {exc}") from exc
return cleaned_points[-limit:]
def _normalize_sequence_steps(raw_steps, click_types=None):
# Defaults to the full action registry so sequences can use keys, scrolls and drags,
# not just the six original click types.
click_types = click_types or ACTION_REGISTRY
if not isinstance(raw_steps, list):
raise ValueError("Sequence files must contain a list of steps.")
normalized_steps = []
for index, step in enumerate(raw_steps, start=1):
if not isinstance(step, (list, tuple)) or len(step) != 4:
raise ValueError(f"Step {index} must contain X, Y, action, and delay.")
try:
x_pos = int(step[0])
y_pos = int(step[1])
action_name = str(step[2])
delay_seconds = float(step[3])
except Exception as exc:
raise ValueError(f"Step {index} contains values that cannot be parsed: {exc}") from exc
if action_name not in click_types:
raise ValueError(f"Step {index} uses an unknown action: {action_name}.")
if delay_seconds < 0:
raise ValueError(f"Step {index} uses a negative delay.")
normalized_steps.append((x_pos, y_pos, action_name, delay_seconds))
return normalized_steps
def _collect_state_summary_data():
profile_file = _state_file_location(PROFILE_FILE_NAME)
workspace_file = _state_file_location(WORKSPACE_FILE_NAME)
summary = {
"app_version": APP_VERSION,
"state_dir": os.path.dirname(profile_file),
"profiles": {
"file": _file_info(profile_file),
"count": 0,
"error": None,
},
"workspace": {
"file": _file_info(workspace_file),
"recording_points": 0,
"activity_entries": 0,
"run_reports": 0,
"has_profile_data": False,
"error": None,
},
}
if summary["profiles"]["file"]["present"]:
try:
profile_data = _load_json_file(profile_file)
if isinstance(profile_data, dict):
summary["profiles"]["count"] = len(profile_data)
else:
summary["profiles"]["error"] = "profiles file is not a JSON object"
except Exception as exc: