-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhotkey_handler.py
More file actions
254 lines (214 loc) · 8.96 KB
/
hotkey_handler.py
File metadata and controls
254 lines (214 loc) · 8.96 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
"""
Hotkey Handler - Global hotkey registration and handling
"""
import keyboard
import pyperclip
import threading
import time
from typing import Callable, Optional
from clipboard_manager import ClipboardManager
from config import HOTKEYS
from settings_manager import get_settings
import notification
class HotkeyHandler:
"""Manages global hotkeys for sequential paste functionality"""
def __init__(self, clipboard_manager: ClipboardManager):
self.clipboard_manager = clipboard_manager
self.running = False
self._clipboard_monitor_thread: Optional[threading.Thread] = None
self._on_delimiter_change: Optional[Callable] = None
self._on_position_change: Optional[Callable] = None
self._last_clipboard_content: str = ""
self._is_pasting: bool = False # Guard to prevent monitor interference
def set_callbacks(self,
on_delimiter_change: Optional[Callable] = None,
on_position_change: Optional[Callable] = None):
"""Set callback functions for UI updates"""
self._on_delimiter_change = on_delimiter_change
self._on_position_change = on_position_change
def _update_position(self):
"""Trigger position change callback"""
if self._on_position_change:
try:
self._on_position_change()
except Exception:
pass
def _clipboard_monitor_loop(self):
"""
Background thread that monitors clipboard for ANY changes.
This detects copies from mouse, buttons, right-click menu, etc.
"""
while self.running:
try:
# Skip monitoring while we're pasting (to avoid false detections)
if self._is_pasting:
time.sleep(0.5)
continue
current_clipboard = pyperclip.paste()
# Check if clipboard content changed
if current_clipboard and current_clipboard != self._last_clipboard_content:
self._last_clipboard_content = current_clipboard
# Update clipboard manager (force reload to handle re-copying same text)
self.clipboard_manager.load_text(current_clipboard)
count = self.clipboard_manager.total_segments
if count > 0:
print(f"[DEBUG] Clipboard changed! Loaded {count} segments. First: {self.clipboard_manager.segments[0][:30] if self.clipboard_manager.segments else 'N/A'}")
notification.notify_sequence_loaded(count)
self._update_position()
except Exception:
pass
# Poll every 500ms
time.sleep(0.5)
def _on_sequential_paste(self):
"""Handle Ctrl+Shift+V - Paste next segment"""
# Check if we have content - if not, try loading from clipboard directly
if not self.clipboard_manager.has_content:
try:
current = pyperclip.paste()
if current and current.strip():
self.clipboard_manager.load_text(current)
self._last_clipboard_content = current
count = self.clipboard_manager.total_segments
if count > 0:
print(f"[DEBUG] Fallback load: {count} segments")
notification.notify_sequence_loaded(count)
self._update_position()
except Exception:
pass
if not self.clipboard_manager.has_content:
notification.notify_no_content()
return
# Check if sequence is exhausted
if self.clipboard_manager.is_exhausted():
notification.notify_sequence_complete(self.clipboard_manager.total_segments)
return
# Get next segment
segment = self.clipboard_manager.get_next_segment()
if segment:
# Set pasting flag to prevent monitor from interfering
self._is_pasting = True
try:
# Check paste mode from settings
settings = get_settings()
paste_mode = settings.get('paste_mode', 'paste')
if paste_mode == 'type':
# Type mode: simulate keystrokes (works on paste-blocked fields)
keyboard.write(segment, delay=0.02)
else:
# Paste mode: use clipboard (faster)
pyperclip.copy(segment)
keyboard.send('ctrl+v')
# Small delay to let action complete
time.sleep(0.1)
# Track segment as last clipboard content
self._last_clipboard_content = segment
finally:
self._is_pasting = False
# Show position notification
current, total = self.clipboard_manager.get_position()
if current == total:
# Just pasted the last item
notification.show_toast(
notification.APP_NAME,
f"Pasted {current}/{total} (last item)",
timeout=2
)
else:
notification.notify_paste_position(current, total)
self._update_position()
def _on_reset(self):
"""Handle Ctrl+Shift+R - Reset sequence"""
self.clipboard_manager.reset()
notification.notify_sequence_reset()
self._update_position()
def _on_skip(self):
"""Handle Ctrl+Shift+N - Skip current segment"""
if not self.clipboard_manager.has_content:
notification.notify_no_content()
return
if self.clipboard_manager.skip_segment():
current, total = self.clipboard_manager.get_position()
if self.clipboard_manager.is_exhausted():
notification.show_toast(
notification.APP_NAME,
f"Skipped to end. Sequence complete.",
timeout=2
)
else:
notification.show_toast(
notification.APP_NAME,
f"Skipped. Now at {current + 1}/{total}",
timeout=1
)
self._update_position()
else:
notification.notify_sequence_complete(self.clipboard_manager.total_segments)
def _on_go_back(self):
"""Handle Ctrl+Shift+B - Go back to previous segment"""
if not self.clipboard_manager.has_content:
notification.notify_no_content()
return
if self.clipboard_manager.go_back():
current, total = self.clipboard_manager.get_position()
notification.show_toast(
notification.APP_NAME,
f"Back to {current + 1}/{total}",
timeout=1
)
self._update_position()
else:
notification.show_toast(
notification.APP_NAME,
"Already at start",
timeout=1
)
def start(self):
"""Start listening for hotkeys and clipboard changes"""
if self.running:
return
self.running = True
# Initialize clipboard content tracking
try:
self._last_clipboard_content = pyperclip.paste() or ""
except Exception:
self._last_clipboard_content = ""
# Start clipboard monitor thread (detects ALL copy methods)
self._clipboard_monitor_thread = threading.Thread(
target=self._clipboard_monitor_loop,
daemon=True
)
self._clipboard_monitor_thread.start()
# Register hotkeys
keyboard.add_hotkey(
HOTKEYS['sequential_paste'],
self._on_sequential_paste,
suppress=True
)
keyboard.add_hotkey(
HOTKEYS['reset_sequence'],
self._on_reset,
suppress=True
)
keyboard.add_hotkey(
HOTKEYS['skip_segment'],
self._on_skip,
suppress=True
)
keyboard.add_hotkey(
HOTKEYS['go_back'],
self._on_go_back,
suppress=True
)
def stop(self):
"""Stop listening for hotkeys and clipboard monitor"""
self.running = False
keyboard.unhook_all_hotkeys()
# Global instance for easy access
_handler_instance: Optional[HotkeyHandler] = None
def get_handler() -> Optional[HotkeyHandler]:
"""Get the global hotkey handler instance"""
return _handler_instance
def set_handler(handler: HotkeyHandler):
"""Set the global hotkey handler instance"""
global _handler_instance
_handler_instance = handler