-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbot_gui.py
More file actions
8671 lines (7864 loc) · 389 KB
/
bot_gui.py
File metadata and controls
8671 lines (7864 loc) · 389 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 os
import sys
import json
import logging
import tempfile
import cv2
import numpy as np
import pyautogui
import shutil
from datetime import datetime
from typing import Dict, List, Optional, Any, Tuple
from pathlib import Path
from PyQt6.QtWidgets import (QApplication, QMainWindow, QWidget, QVBoxLayout, QHBoxLayout, QLabel,
QPushButton, QListWidget, QStackedWidget, QLineEdit, QSpinBox,
QDoubleSpinBox, QComboBox, QFileDialog, QMessageBox, QCheckBox,
QGroupBox, QScrollArea, QSplitter, QFrame, QSizePolicy, QToolBar, QToolBox,
QStatusBar, QProgressBar, QDialog, QFormLayout, QListWidgetItem, QInputDialog, QMenu,
QDialogButtonBox, QMenuBar, QTableWidget, QTableWidgetItem, QGridLayout,
QHeaderView, QAbstractItemView, QTabWidget, QTimeEdit)
from PyQt6.QtCore import Qt, QSize, QTimer, pyqtSignal, QThread, QObject, QPoint, QRect, QEvent
from PyQt6.QtGui import (QAction, QIcon, QPixmap, QImage, QPainter, QPen, QColor,
QScreen, QGuiApplication, QKeySequence, QShortcut, QKeyEvent)
import pyautogui
import numpy as np
from PIL import ImageGrab, Image
import darkdetect
# Import the bot functionality
from image_detection_bot import ImageDetectionBot, ActionType, Action, parse_action
# Configure logging
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
logger = logging.getLogger(__name__)
class WorkerSignals(QObject):
"""Defines the signals available from a running worker thread."""
finished = pyqtSignal()
error = pyqtSignal(str)
result = pyqtSignal(object)
update = pyqtSignal(dict)
import os
import signal
class BotWorker(QThread):
"""Worker thread for running bot operations."""
def __init__(self, bot, sequence, loop=False, loop_count=1, non_required_wait=False, failsafe_config=None, failsafe_only=False, max_runtime_seconds=None, groups=None):
super().__init__()
self.bot = bot
self.sequence = sequence
self.loop = loop
self.loop_count = loop_count if loop else 1
self.non_required_wait = non_required_wait # Whether to wait for non-required steps
self.failsafe_config = failsafe_config # New failsafe configuration
self.failsafe_only = failsafe_only # If True, run only the failsafe sequence and exit
self.max_runtime_seconds = max_runtime_seconds # Max runtime cutoff
self.groups = groups or {}
self.signals = WorkerSignals()
self._is_running = True
self._should_stop = False # Flag to indicate if we should stop
self.current_step = 0
self.total_steps = 0
self.current_iteration = 0
self._process_pid = None # Store the process ID for forceful termination
self._executing_failsafe = False # Flag to track if we're in failsafe execution
logger.info("BotWorker initialized with loop=%s, loop_count=%s, non_required_wait=%s, failsafe_config=%s",
loop, loop_count, non_required_wait, bool(failsafe_config))
def run(self):
"""Run the sequence of steps with optional looping."""
# Store the process ID for forceful termination if needed
self._process_pid = os.getpid()
logger.info(f"BotWorker started with PID: {self._process_pid}")
# Track start time for max runtime cutoff
import time
self._start_time = time.time()
# Failsafe configuration is now handled by self.failsafe_config
# If we're in failsafe-only mode (e.g., Test Failsafe button), execute and exit
if getattr(self, 'failsafe_only', False):
try:
self.signals.update.emit({
"status": "Starting failsafe test...",
"progress": 0
})
self.execute_failsafe_sequence()
self.signals.update.emit({
"status": "Failsafe sequence completed.",
"progress": 100
})
except Exception as e:
self.signals.error.emit(f"Error executing failsafe sequence: {str(e)}")
finally:
self._is_running = False
self.signals.finished.emit()
return
try:
while self._is_running and not self._should_stop and (not self.loop or self.current_iteration < self.loop_count):
# Check max runtime before starting iteration
if self.max_runtime_seconds is not None:
elapsed = time.time() - getattr(self, '_start_time', time.time())
if elapsed >= self.max_runtime_seconds:
logger.info("Max runtime reached (%.2fs >= %.2fs)", elapsed, self.max_runtime_seconds)
self.signals.update.emit({
"status": "Max runtime reached. Stopping...",
"progress": int(100)
})
self._should_stop = True
break
self.current_iteration += 1
logger.info("Starting iteration %d/%d", self.current_iteration, self.loop_count if self.loop else 1)
# Check for stop request before starting iteration
if self._should_stop:
logger.info("Stop requested before starting iteration")
break
# Expand groups inline for this iteration
base_steps = self.sequence.get('steps', [])
expanded_steps = []
for st in base_steps:
try:
if isinstance(st, dict) and 'call_group' in st:
grp_name = st.get('call_group')
grp_steps = []
if grp_name and grp_name in self.groups:
grp_steps = self.groups.get(grp_name) or []
else:
logger.warning(f"Group '{grp_name}' not found; skipping call.")
for gs in grp_steps:
expanded_steps.append(gs)
else:
expanded_steps.append(st)
except Exception as e:
logger.error(f"Error expanding group step: {e}")
expanded_steps.append(st)
self.total_steps = len(expanded_steps)
if self.total_steps == 0:
self.signals.error.emit("No steps in sequence")
return
iteration_text = f" ({self.current_iteration}/{self.loop_count})" if self.loop and self.loop_count > 1 else ""
self.signals.update.emit({
"status": f"Starting sequence '{self.sequence.get('name', 'Unnamed')}'" +
(f" (Iteration: {self.current_iteration}{iteration_text})" if self.loop or self.current_iteration > 1 else "") +
f" with {self.total_steps} steps...",
"progress": 0
})
# Track the last position set by a MOVE action
last_move_position = None
should_continue = True
try:
for i, step in enumerate(expanded_steps):
if not self._is_running:
should_continue = False
break
# Check max runtime inside steps loop
if self.max_runtime_seconds is not None:
elapsed = time.time() - getattr(self, '_start_time', time.time())
if elapsed >= self.max_runtime_seconds:
logger.info("Max runtime reached during steps (%.2fs >= %.2fs)", elapsed, self.max_runtime_seconds)
self.signals.update.emit({
"status": "Max runtime reached during steps. Stopping...",
"progress": int(100)
})
self._should_stop = True
should_continue = False
break
self.current_step = i
template_name = step.get('find', '')
required = step.get('required', True)
timeout = step.get('timeout', 10.0)
confidence = step.get('confidence', 0.9)
search_region = step.get('search_region')
# If no explicit region, use per-step monitor override if provided
mon = step.get('monitor')
if not search_region and mon and ((isinstance(mon, tuple) and len(mon) == 4) or (isinstance(mon, list) and len(mon) == 4)):
search_region = tuple(mon)
step_loop_count = step.get('loop_count', 1)
# Check for stop request before each step
if self._should_stop:
logger.info("Stop requested, breaking step loop")
should_continue = False
break
# Update status
self.signals.update.emit({
"status": f"Step {i+1}/{self.total_steps}: Looking for '{template_name}'...",
"current_step": template_name,
"progress": int((i / self.total_steps) * 100)
})
for step_loop in range(step_loop_count):
if self._should_stop:
logger.info("Stop requested, breaking step loop")
should_continue = False
break
# Handle actions without template
if not template_name or str(template_name).lower() == 'none':
actions = step.get('actions', [])
for action_data in actions:
try:
action = parse_action(action_data)
success = self.bot.execute_action(action)
if action.type == ActionType.MOVE and action.x is not None and action.y is not None:
last_move_position = (action.x, action.y)
if not success:
self.signals.error.emit(f"Failed to execute {action.type.value}")
should_continue = False
break
# --- FAILSAFE CHECK ---
if self.check_failsafe_trigger():
# Failsafe sequence was executed, continue with next step
break
except Exception as e:
self.signals.error.emit(f"Error executing action: {str(e)}")
should_continue = False
break
if not should_continue:
break
# If failsafe triggered, continue at new step
if failsafe_template is not None and failsafe_goto_step is not None and i == failsafe_goto_step:
continue
else:
# Find the template in the image for each loop iteration
position = None
try:
if self._should_stop:
logger.info("Stop requested, breaking before find operation")
should_continue = False
break
if search_region:
# For non-required steps, use 0.5s timeout if waiting is disabled
current_timeout = timeout if (required or self.non_required_wait) else 0.5
logger.info(f"Looking for template '{template_name}' with timeout={current_timeout}s (required={required}, non_required_wait={self.non_required_wait})")
strategy = step.get('strategy') # e.g., 'feature' or None
min_inliers = step.get('min_inliers', 12)
ratio_thresh = step.get('ratio_thresh', 0.75)
ransac_thresh = step.get('ransac_thresh', 4.0)
position = self.bot.find_image(
template_name=template_name,
region=search_region,
timeout=current_timeout,
confidence=confidence,
strategy=strategy,
min_inliers=min_inliers,
ratio_thresh=ratio_thresh,
ransac_thresh=ransac_thresh
)
else:
start_time = datetime.now()
check_interval = 0.1
# For non-required steps, use 0.5s timeout if waiting is disabled
current_timeout = timeout if (required or self.non_required_wait) else 0.5
logger.info(f"Looking for template '{template_name}' with timeout={current_timeout}s (required={required}, non_required_wait={self.non_required_wait})")
strategy = step.get('strategy')
min_inliers = step.get('min_inliers', 12)
ratio_thresh = step.get('ratio_thresh', 0.75)
ransac_thresh = step.get('ransac_thresh', 4.0)
while not self._should_stop and (datetime.now() - start_time).total_seconds() < current_timeout:
position = self.bot.find_image(
template_name=template_name,
confidence=confidence,
strategy=strategy,
min_inliers=min_inliers,
ratio_thresh=ratio_thresh,
ransac_thresh=ransac_thresh
)
if position is not None:
break
self.msleep(int(check_interval * 1000))
if self._should_stop:
logger.info("Stop requested during wait_for_image")
should_continue = False
break
if position is None:
if required:
self.signals.error.emit(f"Required template '{template_name}' not found")
should_continue = False
break
else:
self.signals.update.emit({
"status": f"Optional template '{template_name}' not found, skipping...",
"progress": int(((i + 0.5) / self.total_steps) * 100)
})
break
# Execute actions for this step (only once per template detection)
actions = step.get('actions', [])
for action_data in actions:
if not self._is_running:
should_continue = False
break
try:
action = parse_action(action_data)
self.signals.update.emit({
"status": f"Executing {action.type.value}...",
"progress": int(((i + 0.5) / self.total_steps) * 100)
})
if action.type == ActionType.MOVE and action.x is not None and action.y is not None:
last_move_position = (action.x, action.y)
if action.type == ActionType.MOVE:
if action.x is not None and action.y is not None:
success = self.bot.execute_action(action)
elif position is not None:
# Treat MOVE as MOVE_TO when a detected position is available
success = self.bot.execute_action_at_position(action, position)
else:
self.signals.error.emit("MOVE action requires x and y coordinates")
should_continue = False
break
elif action.type == ActionType.MOVE_TO and position is not None:
success = self.bot.execute_action_at_position(action, position)
elif action.type == ActionType.CLICK and last_move_position is not None:
success = self.bot.execute_action_at_position(action, last_move_position)
elif position is not None:
success = self.bot.execute_action_at_position(action, position)
else:
success = self.bot.execute_action(action)
# Log the result of each action
logger.info(f"Action {action.type.value} executed with result: {success}")
if not success:
if action.type == ActionType.WAIT:
logger.warning(f"Wait action failed, but continuing to next action/loop.")
continue
self.signals.error.emit(f"Failed to execute {action.type.value}")
should_continue = False
break
# --- FAILSAFE CHECK ---
if self.check_failsafe_trigger():
# Failsafe sequence was executed, continue with next step
break
except Exception as e:
logger.error(f"Exception during action {action_data.get('type')}: {str(e)}")
if action_data.get('type') == 'wait':
logger.warning(f"Wait action exception, but continuing to next action/loop.")
continue
self.signals.error.emit(f"Error executing action: {str(e)}")
should_continue = False
break
if not should_continue:
break
except Exception as e:
self.signals.error.emit(f"Error finding template '{template_name}': {str(e)}")
should_continue = False
break
if not should_continue:
break
# End of steps loop
if not should_continue or not self.loop:
break
# Small delay between iterations
import time
time.sleep(0.1)
except Exception as e:
self.signals.error.emit(f"Error in sequence execution: {str(e)}")
should_continue = False
# Update completion status
if self._is_running and should_continue and self.loop:
self.signals.update.emit({
"status": f"Completed iteration {self.current_iteration}, starting next...",
"progress": 0
})
# End of main loop
if self._is_running:
self.signals.update.emit({
"status": f"Sequence '{self.sequence.get('name', 'Unnamed')}' completed " +
(f"after {self.current_iteration} iterations" if self.loop and self.current_iteration > 1 else "successfully") + "!",
"progress": 100
})
self.signals.finished.emit()
except Exception as e:
import traceback
error_msg = f"Error in sequence execution: {str(e)}\n\n{traceback.format_exc()}"
self.signals.error.emit(error_msg)
finally:
self._is_running = False
self.signals.finished.emit()
self.wait()
def execute_failsafe_sequence(self):
"""Execute the failsafe sequence when the failsafe template is detected."""
if not isinstance(self.failsafe_config, dict) or not self.failsafe_config.get('enabled'):
return False
failsafe_sequence = self.failsafe_config.get('sequence', [])
# Normalize sequence format if provided as {"steps": [...]} from editor
if isinstance(failsafe_sequence, dict):
failsafe_sequence = failsafe_sequence.get('steps', [])
if not isinstance(failsafe_sequence, list):
logger.warning("Invalid failsafe sequence format; expected a list of steps")
return False
if not failsafe_sequence:
return False
logger.info("Executing failsafe sequence")
self._executing_failsafe = True
try:
self.signals.update.emit({
"status": "Failsafe triggered! Executing failsafe sequence...",
"progress": 0
})
# Expand group call steps inline
expanded = []
try:
grp_map = getattr(self, 'groups', {}) or {}
for st in failsafe_sequence:
if isinstance(st, dict) and 'call_group' in st:
gname = st.get('call_group')
gsteps = []
if gname and gname in grp_map:
grp = grp_map.get(gname)
gsteps = grp if isinstance(grp, list) else (grp.get('steps', []) if isinstance(grp, dict) else [])
try:
logger.info(f"Failsafe: expanding group '{gname}' into {len(gsteps)} steps")
except Exception:
pass
else:
logger.warning(f"Group '{gname}' not found for failsafe call; skipping.")
expanded.extend(gsteps)
else:
expanded.append(st)
except Exception as e:
logger.debug(f"Failsafe group expansion error: {e}")
expanded = failsafe_sequence
try:
logger.info(f"Failsafe: expanded sequence size {len(expanded)} (original {len(failsafe_sequence)})")
except Exception:
pass
for i, step in enumerate(expanded):
if not self._is_running or self._should_stop:
break
self.signals.update.emit({
"status": f"Failsafe step {i+1}/{len(failsafe_sequence)}: {step.get('name', 'Unnamed step')}",
"progress": int((i / len(failsafe_sequence)) * 100)
})
# Execute the failsafe step
template_name = step.get('find', '')
actions = step.get('actions', [])
if template_name and str(template_name).lower() != 'none':
# Find template first
# Accept both desktop and web editor keys
strategy = step.get('strategy') or step.get('detection_strategy')
region = step.get('search_region') or step.get('region')
mon = step.get('monitor')
if not region and mon and ((isinstance(mon, tuple) and len(mon) == 4) or (isinstance(mon, list) and len(mon) == 4)):
region = tuple(mon)
position = self.bot.find_image(
template_name=template_name,
region=region,
timeout=step.get('timeout', 5.0),
confidence=step.get('confidence', 0.9),
strategy=strategy,
min_inliers=step.get('min_inliers', 12),
ratio_thresh=step.get('ratio_thresh', step.get('ratio', 0.75)),
ransac_thresh=step.get('ransac_thresh', step.get('ransac', 4.0))
)
if position is None and step.get('required', True):
logger.warning(f"Required template '{template_name}' not found in failsafe sequence")
continue
# Execute actions at found position
for action_data in actions:
if not self._is_running or self._should_stop:
break
try:
action = parse_action(action_data)
if position is not None and action.type in [ActionType.CLICK, ActionType.MOVE_TO]:
success = self.bot.execute_action_at_position(action, position)
else:
success = self.bot.execute_action(action)
if not success:
logger.warning(f"Failed to execute {action.type.value} in failsafe sequence")
except Exception as e:
logger.error(f"Error executing failsafe action: {str(e)}")
else:
# Execute actions without template
for action_data in actions:
if not self._is_running or self._should_stop:
break
try:
action = parse_action(action_data)
success = self.bot.execute_action(action)
if not success:
logger.warning(f"Failed to execute {action.type.value} in failsafe sequence")
except Exception as e:
logger.error(f"Error executing failsafe action: {str(e)}")
self.signals.update.emit({
"status": "Failsafe sequence completed",
"progress": 100
})
return True
except Exception as e:
logger.error(f"Error executing failsafe sequence: {str(e)}")
self.signals.error.emit(f"Error in failsafe sequence: {str(e)}")
return False
finally:
self._executing_failsafe = False
def check_failsafe_trigger(self):
"""Check if the failsafe template is detected and trigger failsafe sequence if found."""
if not self.failsafe_config or not self.failsafe_config.get('enabled'):
return False
if self._executing_failsafe: # Don't trigger failsafe while already executing it
return False
failsafe_template = self.failsafe_config.get('template')
failsafe_confidence = self.failsafe_config.get('confidence', 0.8)
failsafe_region = self.failsafe_config.get('region')
if not failsafe_template:
return False
# Quick check for failsafe template
pos = self.bot.find_image(
template_name=failsafe_template,
region=failsafe_region,
timeout=0.1, # Very short timeout for quick checks
confidence=failsafe_confidence
)
if pos is not None:
logger.info(f"Failsafe template '{failsafe_template}' detected at {pos}")
return self.execute_failsafe_sequence()
return False
def stop(self):
"""Request the worker to stop."""
logger.info("Stop requested for BotWorker")
self._is_running = False
self._should_stop = True
# Try graceful stop first
if hasattr(self.bot, 'stop'):
self.bot.stop() # If the bot has a stop method, call it
# Force stop after a short delay if needed
if not self.wait(1000): # Wait up to 1 second for graceful stop
logger.warning("Graceful stop failed, forcing termination")
self.terminate()
if not self.wait(500): # Wait up to 0.5 seconds for terminate to complete
logger.error("Failed to terminate thread, trying process kill")
if self._process_pid:
try:
os.kill(self._process_pid, signal.SIGTERM)
except ProcessLookupError:
pass # Process already dead
except Exception as e:
logger.error(f"Error killing process: {e}")
logger.info("Worker stop completed")
class ScreenCaptureDialog(QDialog):
"""Dialog for capturing a region of the screen.
Optionally restricts to a specific monitor geometry if provided.
"""
def __init__(self, parent=None, target_geometry: QRect | None = None):
super().__init__(parent)
self.setWindowTitle("Capture Screen Region")
self.setWindowFlags(
Qt.WindowType.FramelessWindowHint |
Qt.WindowType.WindowStaysOnTopHint |
Qt.WindowType.Tool
)
self.setCursor(Qt.CursorShape.CrossCursor)
# Make window semi-transparent
self.setWindowOpacity(0.3)
self.setAttribute(Qt.WidgetAttribute.WA_TranslucentBackground)
# Store screen information
self.screens = QGuiApplication.screens()
self.current_screen = QGuiApplication.primaryScreen()
self.screen_geometry = self.current_screen.availableGeometry()
self.target_geometry = target_geometry
# Calculate combined geometry of all screens
self.combined_geometry = QRect()
for screen in self.screens:
self.combined_geometry = self.combined_geometry.united(screen.geometry())
# Set dialog to cover target monitor or all screens
if isinstance(self.target_geometry, QRect) and self.target_geometry.isValid():
self.setGeometry(self.target_geometry)
self.move(self.target_geometry.topLeft())
else:
self.setGeometry(self.combined_geometry)
self.move(self.combined_geometry.topLeft())
# Selection rectangle in screen coordinates
self.start_pos = None
self.end_pos = None
self.selection_rect = None
def paintEvent(self, event):
"""Draw the semi-transparent overlay and selection rectangle."""
try:
painter = QPainter(self)
# Draw semi-transparent overlay for all screens
painter.setBrush(QColor(0, 0, 0, 100)) # Semi-transparent black
painter.setPen(Qt.PenStyle.NoPen)
# Fill overlay over the entire dialog window region
painter.drawRect(self.rect())
# Draw the selection rectangle if we have valid points
if (self.start_pos and self.end_pos and
not self.start_pos.isNull() and not self.end_pos.isNull() and
self.selection_rect and self.selection_rect.isValid()):
# Draw the selection border
painter.setPen(QPen(Qt.GlobalColor.red, 2, Qt.PenStyle.SolidLine))
painter.setBrush(Qt.BrushStyle.NoBrush)
# Convert to local coordinates relative to this dialog window
local_origin = self.geometry().topLeft()
local_rect = QRect(self.selection_rect.topLeft() - local_origin, self.selection_rect.size())
painter.drawRect(local_rect)
# Draw size info
size_text = f"{self.selection_rect.width()} x {self.selection_rect.height()}"
text_rect = painter.fontMetrics().boundingRect(size_text)
text_rect.moveBottomLeft(local_rect.bottomLeft() + QPoint(0, 5))
text_rect.adjust(-5, -2, 5, 2) # Add some padding
# Ensure text is visible
painter.fillRect(text_rect, QColor(0, 0, 0, 180))
painter.setPen(Qt.GlobalColor.white)
painter.drawText(text_rect, Qt.AlignmentFlag.AlignCenter, size_text)
painter.end()
except Exception as e:
print(f"Error in paintEvent: {e}")
if painter.isActive():
painter.end()
def mousePressEvent(self, event):
"""Start selection on mouse press."""
if event.button() == Qt.MouseButton.LeftButton:
self.start_pos = event.globalPosition().toPoint()
self.end_pos = self.start_pos
self.selection_rect = QRect(self.start_pos, QSize(1, 1))
self.update()
def mouseMoveEvent(self, event):
"""Update selection rectangle on mouse move."""
if self.start_pos:
self.end_pos = event.globalPosition().toPoint()
# Ensure we have valid coordinates
if not self.end_pos.isNull():
# Create a normalized rectangle from start to current position
x1 = min(self.start_pos.x(), self.end_pos.x())
y1 = min(self.start_pos.y(), self.end_pos.y())
x2 = max(self.start_pos.x(), self.end_pos.x())
y2 = max(self.start_pos.y(), self.end_pos.y())
# Ensure minimum size
if x2 - x1 < 5: x2 = x1 + 5
if y2 - y1 < 5: y2 = y1 + 5
self.selection_rect = QRect(
QPoint(x1, y1),
QPoint(x2, y2)
)
self.update()
def mouseReleaseEvent(self, event):
"""Finish selection on mouse release."""
if event.button() == Qt.MouseButton.LeftButton and self.start_pos:
self.end_pos = event.globalPosition().toPoint()
# Only accept if the selection is big enough
if (abs(self.end_pos.x() - self.start_pos.x()) > 5 and
abs(self.end_pos.y() - self.start_pos.y()) > 5):
self.accept()
else:
self.reject()
def keyPressEvent(self, event):
"""Handle Escape key to cancel."""
if event.key() == Qt.Key.Key_Escape:
self.reject()
def get_capture_rect(self) -> QRect:
"""Get the captured rectangle in screen coordinates."""
if self.selection_rect and self.selection_rect.isValid():
# Ensure the rectangle is within all screens' combined bounds
bounds = self.target_geometry if (isinstance(self.target_geometry, QRect) and self.target_geometry.isValid()) else self.combined_geometry
rect = self.selection_rect.intersected(bounds)
# Convert to screen coordinates if needed
if rect.isValid() and rect.width() > 5 and rect.height() > 5: # Minimum size
return rect
return None
class OverlayPreviewWindow(QDialog):
"""Non-interactive transparent overlay to preview a region or a click point.
Covers either a target monitor geometry or the combined desktop, draws a red
rectangle or crosshair marker, and auto-closes after a short duration.
"""
def __init__(self, parent=None, rect: QRect | None = None, point: QPoint | None = None, target_geometry: QRect | None = None, duration_ms: int = 1200, message: str | None = None):
super().__init__(parent)
self.setWindowFlags(
Qt.WindowType.FramelessWindowHint |
Qt.WindowType.WindowStaysOnTopHint |
Qt.WindowType.Tool
)
self.setAttribute(Qt.WidgetAttribute.WA_TranslucentBackground)
self.setWindowOpacity(0.3)
self._rect = rect if (isinstance(rect, QRect) and rect.isValid()) else None
self._point = point
self._message = message
# Determine coverage geometry
screens = QGuiApplication.screens()
combined = QRect()
for sc in screens:
combined = combined.united(sc.geometry())
if isinstance(target_geometry, QRect) and target_geometry.isValid():
self._coverage = target_geometry
else:
self._coverage = combined
self.setGeometry(self._coverage)
self.move(self._coverage.topLeft())
# Auto-close shortly
try:
self.setAttribute(Qt.WidgetAttribute.WA_DeleteOnClose)
except Exception:
pass
QTimer.singleShot(max(300, int(duration_ms)), self.close)
def paintEvent(self, event):
try:
painter = QPainter(self)
# Dim background
painter.setBrush(QColor(0, 0, 0, 100))
painter.setPen(Qt.PenStyle.NoPen)
painter.drawRect(self.rect())
origin = self.geometry().topLeft()
# Draw rectangle preview
if self._rect and self._rect.isValid():
local_rect = QRect(self._rect.topLeft() - origin, self._rect.size())
painter.setPen(QPen(Qt.GlobalColor.red, 2, Qt.PenStyle.SolidLine))
painter.setBrush(Qt.BrushStyle.NoBrush)
painter.drawRect(local_rect)
# Size text box
size_text = f"{self._rect.width()} x {self._rect.height()}"
text_rect = painter.fontMetrics().boundingRect(size_text)
text_rect.moveBottomLeft(local_rect.bottomLeft() + QPoint(0, 5))
text_rect.adjust(-5, -2, 5, 2)
painter.fillRect(text_rect, QColor(0, 0, 0, 180))
painter.setPen(Qt.GlobalColor.white)
painter.drawText(text_rect, Qt.AlignmentFlag.AlignCenter, size_text)
# Draw click point preview
if isinstance(self._point, QPoint):
local_pt = self._point - origin
painter.setPen(QPen(Qt.GlobalColor.green, 2, Qt.PenStyle.SolidLine))
# Crosshair
painter.drawLine(local_pt + QPoint(-10, 0), local_pt + QPoint(10, 0))
painter.drawLine(local_pt + QPoint(0, -10), local_pt + QPoint(0, 10))
painter.setBrush(QColor(0, 255, 0, 120))
painter.drawEllipse(local_pt, 6, 6)
# Optional message centered
if isinstance(self._message, str) and self._message:
painter.setPen(Qt.GlobalColor.white)
painter.setBrush(Qt.BrushStyle.NoBrush)
painter.drawText(self.rect(), Qt.AlignmentFlag.AlignCenter, self._message)
painter.end()
except Exception:
try:
if painter.isActive():
painter.end()
except Exception:
pass
class MonitorInfoDialog(QDialog):
"""Dialog to display monitor geometries and DPI, with quick capture preview per monitor."""
def __init__(self, parent=None):
super().__init__(parent)
self.setWindowTitle("Monitor Info")
self.setMinimumSize(500, 300)
layout = QVBoxLayout(self)
class RecorderWidget(QWidget):
def __init__(self, parent=None):
super().__init__(parent)
self.events = []
self._recording = False
self._start_time = None
self._mouse_listener = None
self._key_listener = None
self._lock = None
self._paused = False
self._paused_at = None
try:
import threading
self._lock = threading.Lock()
except Exception:
self._lock = None
self._build_ui()
def _build_ui(self):
lay = QVBoxLayout(self)
try:
import os
self.recordings_dir = os.path.join(os.path.dirname(os.path.abspath(__file__)), "recordings")
os.makedirs(self.recordings_dir, exist_ok=True)
except Exception:
self.recordings_dir = None
controls = QHBoxLayout()
self.start_btn = QPushButton("Start Recording")
self.stop_btn = QPushButton("Stop")
self.pause_btn = QPushButton("Pause")
self.clear_btn = QPushButton("Clear")
self.marker_btn = QPushButton("Add Marker")
self.delete_btn = QPushButton("Delete Selected")
self.save_btn = QPushButton("Save…")
self.load_btn = QPushButton("Load…")
self.play_btn = QPushButton("Playback")
self.preview_btn = QPushButton("Preview Overlay")
self.stop_btn.setEnabled(False)
self.pause_btn.setEnabled(False)
controls.addWidget(self.start_btn)
controls.addWidget(self.stop_btn)
controls.addWidget(self.pause_btn)
controls.addWidget(self.clear_btn)
controls.addWidget(self.marker_btn)
controls.addWidget(self.delete_btn)
controls.addWidget(self.save_btn)
controls.addWidget(self.load_btn)
controls.addWidget(self.play_btn)
controls.addWidget(self.preview_btn)
controls.addStretch()
lib = QHBoxLayout()
lib.addWidget(QLabel("Library:"))
self.library_combo = QComboBox()
lib.addWidget(self.library_combo, 1)
self.library_refresh_btn = QPushButton("Refresh")
self.library_open_btn = QPushButton("Open")
self.library_play_btn = QPushButton("Play")
self.library_rename_btn = QPushButton("Rename")
self.library_delete_btn = QPushButton("Delete")
lib.addWidget(self.library_refresh_btn)
lib.addWidget(self.library_open_btn)
lib.addWidget(self.library_play_btn)
lib.addWidget(self.library_rename_btn)
lib.addWidget(self.library_delete_btn)
seg = QHBoxLayout()
seg.addWidget(QLabel("Segments:"))
self.trim_btn = QPushButton("Trim to Selection")
self.split_btn = QPushButton("Split at Selection")
self.merge_btn = QPushButton("Merge Recordings…")
seg.addWidget(self.trim_btn)
seg.addWidget(self.split_btn)
seg.addWidget(self.merge_btn)
opts = QHBoxLayout()
self.record_moves_chk = QCheckBox("Record mouse moves")
self.record_moves_chk.setChecked(True)
opts.addWidget(self.record_moves_chk)
opts.addWidget(QLabel("Move sampling (ms):"))
self.move_sample_spin = QSpinBox(); self.move_sample_spin.setRange(5, 200); self.move_sample_spin.setValue(25)
opts.addWidget(self.move_sample_spin)
opts.addWidget(QLabel("Jitter (px):"))
self.jitter_spin = QSpinBox(); self.jitter_spin.setRange(0, 50); self.jitter_spin.setValue(0)
opts.addWidget(self.jitter_spin)
opts.addWidget(QLabel("Delay jitter (ms):"))
self.delay_jitter_spin = QSpinBox(); self.delay_jitter_spin.setRange(0, 1000); self.delay_jitter_spin.setValue(0)
opts.addWidget(self.delay_jitter_spin)
opts.addStretch()
# Collapsible tool sections to declutter the Recorder UI
tool = QToolBox()
session_page = QWidget(); sp = QVBoxLayout(session_page); sp.setContentsMargins(0,0,0,0); sp.setSpacing(6)
sp.addLayout(controls)
sp.addLayout(opts)
library_page = QWidget(); lp = QVBoxLayout(library_page); lp.setContentsMargins(0,0,0,0); lp.setSpacing(6)
lp.addLayout(lib)
segments_page = QWidget(); sg = QVBoxLayout(segments_page); sg.setContentsMargins(0,0,0,0); sg.setSpacing(6)
sg.addLayout(seg)
tool.addItem(session_page, "Session")
tool.addItem(library_page, "Library")
tool.addItem(segments_page, "Segments")
lay.addWidget(tool)
self.events_table = QTableWidget(0, 5)
self.events_table.setHorizontalHeaderLabels(["time(s)", "type", "x", "y", "info"])
try:
self.events_table.setSelectionBehavior(QAbstractItemView.SelectionBehavior.SelectRows)
self.events_table.setSelectionMode(QAbstractItemView.SelectionMode.ExtendedSelection)
except Exception:
pass
try:
self.events_table.horizontalHeader().setSectionResizeMode(QHeaderView.ResizeMode.Stretch)
except Exception:
pass
lay.addWidget(self.events_table)
self.start_btn.clicked.connect(self.start_recording)
self.stop_btn.clicked.connect(self.stop_recording)
self.pause_btn.clicked.connect(self.toggle_pause)
self.clear_btn.clicked.connect(self.clear_events)
self.delete_btn.clicked.connect(self.remove_selected_events)
self.save_btn.clicked.connect(self.save_events)
self.load_btn.clicked.connect(self.load_events)
self.play_btn.clicked.connect(self.playback_events)
self.preview_btn.clicked.connect(self.preview_overlay)
self.marker_btn.clicked.connect(self.add_marker)
self.library_refresh_btn.clicked.connect(self.refresh_library)
self.library_open_btn.clicked.connect(self.open_selected_recording)
self.library_play_btn.clicked.connect(self.play_selected_recording)
self.library_rename_btn.clicked.connect(self.rename_selected_recording)
self.library_delete_btn.clicked.connect(self.delete_selected_recording)
self.trim_btn.clicked.connect(self.trim_to_selection)
self.split_btn.clicked.connect(self.split_at_selection)
self.merge_btn.clicked.connect(self.merge_recordings)
try:
del_shortcut = QShortcut(QKeySequence("Delete"), self.events_table)
del_shortcut.activated.connect(self.remove_selected_events)
except Exception:
pass
try:
self.refresh_library()
except Exception:
pass
def _now(self):
try:
import time
return time.perf_counter()
except Exception:
import time
return time.time()
def _dt(self):
if self._start_time is None:
return 0.0
return max(0.0, float(self._now() - self._start_time))
def _append_event(self, ev: dict):
try:
if self._lock:
self._lock.acquire()
self.events.append(ev)
finally:
try:
if self._lock:
self._lock.release()
except Exception:
pass
self._append_row(ev)
def _append_row(self, ev: dict):
try:
row = self.events_table.rowCount()
self.events_table.insertRow(row)
def _set(c, val):
item = QTableWidgetItem(str(val))
self.events_table.setItem(row, c, item)
_set(0, f"{float(ev.get('t',0.0)):.3f}")
_set(1, ev.get('type',''))
_set(2, ev.get('x',''))