-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdialogs.py
More file actions
444 lines (374 loc) · 17 KB
/
dialogs.py
File metadata and controls
444 lines (374 loc) · 17 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
"""
Themed dialogs, replaces tkinter.messagebox throughout the app.
Usage:
from dialogs import alert, confirm
alert(parent, 'Title', 'Message text')
if confirm(parent, 'Delete?', 'This cannot be undone.',
action_label='Delete', action_color='#b03030'):
...
"""
import ctypes
import ctypes.wintypes
import tkinter as tk
import customtkinter as ctk
from theme import (
BG, SURFACE, SURF2, SURF3,
ACCENT, ACCENTL, TEXT_P, TEXT_S,
FONT_FAMILY, PAD, PAD_SM, RADIUS_SM,
)
class ThemedDialog(ctk.CTkToplevel):
"""
Minimal dark-themed dialog.
mode='alert' , single OK button; result is always False
mode='confirm', Cancel + coloured action button; result True on confirm
"""
def __init__(self, parent, title: str, message: str,
mode: str = 'alert',
action_label: str = 'OK',
action_color: str = ACCENT,
action_hover: str = ACCENTL) -> None:
super().__init__(parent)
self.withdraw() # hide until positioned, avoids top-left flash
self.title(title)
self.configure(fg_color=BG)
self.resizable(False, False)
self.result = False
# ── Header ────────────────────────────────────────────────────────────
hdr = ctk.CTkFrame(self, fg_color=SURFACE, corner_radius=0)
hdr.pack(fill='x')
ctk.CTkLabel(hdr, text=title,
font=(FONT_FAMILY, 14, 'bold'),
text_color=TEXT_P).pack(anchor='w', padx=PAD, pady=PAD_SM)
# ── Body ──────────────────────────────────────────────────────────────
ctk.CTkLabel(self, text=message,
font=(FONT_FAMILY, 13), text_color=TEXT_S,
wraplength=320, justify='left').pack(
padx=PAD, pady=PAD)
# ── Footer ────────────────────────────────────────────────────────────
foot = ctk.CTkFrame(self, fg_color=SURFACE, corner_radius=0)
foot.pack(fill='x')
def _btn(text, cmd, fg, hover):
return ctk.CTkButton(
foot, text=text, command=cmd, width=80,
fg_color=fg, hover_color=hover,
text_color=TEXT_P, corner_radius=RADIUS_SM,
font=(FONT_FAMILY, 13),
)
if mode == 'confirm':
_btn(action_label, self._confirm,
action_color, action_hover).pack(
side='right', padx=PAD, pady=PAD_SM)
_btn('Cancel', self.destroy,
SURF2, SURF3).pack(side='right', pady=PAD_SM)
else:
_btn('OK', self.destroy,
ACCENT, ACCENTL).pack(side='right', padx=PAD, pady=PAD_SM)
# ── Keyboard shortcuts ────────────────────────────────────────────────
self.bind('<Escape>', lambda e: self.destroy())
self.bind('<Return>',
lambda e: (self._confirm() if mode == 'confirm' else self.destroy()))
self.after(50, lambda: self._show(parent))
def _confirm(self) -> None:
self.result = True
self.destroy()
def _show(self, parent) -> None:
center_over_parent(self, parent)
self.deiconify()
self.grab_set()
# ── Shared geometry helper ────────────────────────────────────────────────────
def _work_area() -> tuple[int, int, int, int]:
"""Return (left, top, right, bottom) of the primary monitor's work area.
The work area is the screen rectangle excluding the taskbar and any
always-on-top toolbars. Falls back to full screen dimensions on error.
"""
try:
rect = ctypes.wintypes.RECT()
# SPI_GETWORKAREA = 0x0030
ctypes.windll.user32.SystemParametersInfoW(0x0030, 0, ctypes.byref(rect), 0)
return rect.left, rect.top, rect.right, rect.bottom
except Exception:
return 0, 0, 0, 0
def center_over_parent(dialog, parent) -> None:
"""Position *dialog* centered over *parent* widget, clamped to the work area
(screen minus taskbar) so no part of the dialog is hidden behind the taskbar."""
dialog.update_idletasks()
try:
# winfo_width/height gives actual rendered size after update_idletasks;
# fall back to reqwidth/reqheight if the window hasn't been mapped yet.
w = dialog.winfo_width()
h = dialog.winfo_height()
if w <= 1:
w = dialog.winfo_reqwidth()
h = dialog.winfo_reqheight()
# Use the Windows work area so we never overlap the taskbar.
wa_left, wa_top, wa_right, wa_bottom = _work_area()
if wa_right <= wa_left or wa_bottom <= wa_top:
# Fallback: use tkinter screen size
wa_left, wa_top = 0, 0
wa_right = dialog.winfo_screenwidth()
wa_bottom = dialog.winfo_screenheight()
wa_w = wa_right - wa_left
wa_h = wa_bottom - wa_top
# If parent is visible, centre over it; otherwise centre on work area.
pw, ph = parent.winfo_width(), parent.winfo_height()
if pw <= 1 or ph <= 1 or not parent.winfo_ismapped():
x = wa_left + (wa_w - w) // 2
y = wa_top + (wa_h - h) // 2
else:
px, py = parent.winfo_rootx(), parent.winfo_rooty()
x = px + (pw - w) // 2
y = py + (ph - h) // 2
# Clamp fully inside the work area.
x = max(wa_left, min(x, wa_right - w))
y = max(wa_top, min(y, wa_bottom - h))
dialog.geometry(f'+{x}+{y}')
except Exception:
pass
# ── Convenience wrappers ──────────────────────────────────────────────────────
def alert(parent, title: str, message: str) -> None:
"""Show a themed alert and block until dismissed."""
dlg = ThemedDialog(parent, title, message, mode='alert')
parent.wait_window(dlg)
def confirm(parent, title: str, message: str,
action_label: str = 'OK',
action_color: str = ACCENT,
action_hover: str = ACCENTL) -> bool:
"""Show a themed confirm dialog; return True if the action button was clicked."""
dlg = ThemedDialog(parent, title, message, mode='confirm',
action_label=action_label,
action_color=action_color,
action_hover=action_hover)
parent.wait_window(dlg)
return dlg.result
def confirm3(parent, title: str, message: str,
primary_label: str, alt_label: str,
primary_color: str = ACCENT,
primary_hover: str = ACCENTL) -> str:
"""Three-button themed dialog used when the user needs to make a
choice between two real actions plus Cancel.
Returns one of:
'primary' if they clicked primary_label
'alt' if they clicked alt_label
'cancel' if they cancelled (Esc or Cancel button)
"""
dlg = ctk.CTkToplevel(parent)
dlg.withdraw()
dlg.title(title)
dlg.configure(fg_color=BG)
dlg.resizable(False, False)
choice = {'val': 'cancel'}
hdr = ctk.CTkFrame(dlg, fg_color=SURFACE, corner_radius=0)
hdr.pack(fill='x')
ctk.CTkLabel(hdr, text=title, font=(FONT_FAMILY, 14, 'bold'),
text_color=TEXT_P).pack(anchor='w', padx=PAD, pady=PAD_SM)
ctk.CTkLabel(dlg, text=message, font=(FONT_FAMILY, 13), text_color=TEXT_S,
wraplength=380, justify='left').pack(padx=PAD, pady=PAD)
foot = ctk.CTkFrame(dlg, fg_color=SURFACE, corner_radius=0)
foot.pack(fill='x')
def _mk(text, cmd, fg, hover, width=170):
return ctk.CTkButton(foot, text=text, command=cmd, width=width,
fg_color=fg, hover_color=hover, text_color=TEXT_P,
corner_radius=RADIUS_SM, font=(FONT_FAMILY, 13))
def _pick(v):
choice['val'] = v
dlg.destroy()
_mk(primary_label, lambda: _pick('primary'), primary_color, primary_hover,
width=200).pack(side='right', padx=PAD, pady=PAD_SM)
_mk(alt_label, lambda: _pick('alt'), SURF2, SURF3, width=180
).pack(side='right', pady=PAD_SM)
_mk('Cancel', lambda: _pick('cancel'), SURF2, SURF3, width=80
).pack(side='right', padx=(0, PAD_SM), pady=PAD_SM)
dlg.bind('<Escape>', lambda e: _pick('cancel'))
dlg.bind('<Return>', lambda e: _pick('primary'))
dlg.after(50, lambda: (center_over_parent(dlg, parent),
dlg.deiconify(), dlg.grab_set()))
parent.wait_window(dlg)
return choice['val']
# ── PopupMenu ────────────────────────────────────────────────────────────────
class PopupMenu:
"""Lightweight custom popup menu with optional theme color overrides.
Usage:
m = PopupMenu(parent_window)
m.add('Cut', cmd_cut, enabled=has_sel)
m.add('Copy', cmd_copy, enabled=has_sel)
m.add('Paste', cmd_paste)
m.separator()
m.add('Paste Image', cmd_ocr)
m.show(event.x_root, event.y_root)
Pass colors=dict(bg=..., border=..., text=..., dim=..., sep=...) to
override the default dark-theme palette.
"""
# Default dark-theme palette
_BG_D = '#1c1c1c'
_BORDER_D = '#333333'
_TEXT_D = '#e8e8e8'
_DIM_D = '#484848'
_SEP_D = '#2a2a2a'
_HOVER_BG = ACCENT # purple, same in both themes
_HOVER_FG = '#ffffff'
_FONT = (FONT_FAMILY, 11)
_PAD_X = 14
_ITEM_PY = 5
_MIN_W = 140
def __init__(self, parent, colors: dict | None = None) -> None:
self._parent = parent
self._items: list = []
self._win: tk.Toplevel | None = None
self._alive = [False]
c = colors or {}
self._BG = c.get('bg', self._BG_D)
self._BORDER = c.get('border', self._BORDER_D)
self._TEXT = c.get('text', self._TEXT_D)
self._DIM = c.get('dim', self._DIM_D)
self._SEP = c.get('sep', self._SEP_D)
def add(self, label: str, command, enabled: bool = True) -> 'PopupMenu':
self._items.append(('item', label, command, enabled))
return self
def separator(self) -> 'PopupMenu':
self._items.append(('sep',))
return self
def show(self, x: int, y: int) -> None:
win = tk.Toplevel(self._parent)
win.overrideredirect(True)
win.attributes('-topmost', True)
win.configure(bg=self._BORDER) # 1 px border via outer bg colour
inner = tk.Frame(win, bg=self._BG, bd=0)
inner.pack(padx=1, pady=1)
self._win = win
self._alive = [True]
for item in self._items:
if item[0] == 'sep':
tk.Frame(inner, bg=self._SEP, height=1).pack(
fill='x', padx=6, pady=3)
else:
_, label, cmd, enabled = item
fg = self._TEXT if enabled else self._DIM
lbl = tk.Label(
inner,
text=f' {label}',
bg=self._BG, fg=fg,
font=self._FONT,
anchor='w',
padx=self._PAD_X,
pady=self._ITEM_PY,
cursor='arrow',
)
lbl.pack(fill='x')
if enabled:
lbl.bind('<Enter>',
lambda e, w=lbl: w.configure(
bg=self._HOVER_BG, fg=self._HOVER_FG))
lbl.bind('<Leave>',
lambda e, w=lbl: w.configure(
bg=self._BG, fg=self._TEXT))
# return 'break' stops the event propagating to win's
# <ButtonRelease-1> handler so only the item fires
def _on_item_click(e, c=cmd):
self._dismiss()
c()
return 'break'
lbl.bind('<ButtonRelease-1>', _on_item_click)
# Keep menu within screen bounds
win.update_idletasks()
mw = win.winfo_reqwidth()
mh = win.winfo_reqheight()
sw = win.winfo_screenwidth()
sh = win.winfo_screenheight()
win.geometry(f'+{min(x, sw - mw - 4)}+{min(y, sh - mh - 4)}')
# grab_set() routes all in-app mouse events to this window.
# We skip focus_force(): on Windows it never gets OS focus on an
# overrideredirect window, which causes immediate <FocusOut> and
# self-destruction before the user can see the menu.
try:
win.grab_set()
except Exception:
pass
# Dismiss on left-click outside items, or Escape.
# We intentionally do NOT bind <ButtonRelease-3>: the normal right-click
# release happens 80–200 ms after the press, so any timed delay is
# unreliable and causes the menu to vanish the moment the user lets go.
# Standard Windows UX: left-click selects/dismisses, Escape cancels.
win.bind('<ButtonRelease-1>', lambda e: self._dismiss())
win.bind('<Escape>', lambda e: self._dismiss())
def _dismiss(self) -> None:
if not self._alive[0]:
return
self._alive[0] = False
try:
self._win.grab_release()
except Exception:
pass
try:
self._win.destroy()
except Exception:
pass
# ── Tooltip ───────────────────────────────────────────────────────────────────
class Tooltip:
"""Hover tooltip for any tkinter or CustomTkinter widget.
Usage:
Tooltip(widget, 'Explain what the widget does')
"""
def __init__(self, widget, text: str, delay: int = 450) -> None:
self._widget = widget
self._text = text
self._delay = delay
self._job = None
self._win = None
widget.bind('<Enter>', self._on_enter, add='+')
widget.bind('<Leave>', self._on_leave, add='+')
widget.bind('<Button>', self._on_leave, add='+')
def _on_enter(self, event=None) -> None:
self._cancel()
self._job = self._widget.after(self._delay, self._show)
def _on_leave(self, event=None) -> None:
self._cancel()
self._hide()
def _cancel(self) -> None:
if self._job:
try:
self._widget.after_cancel(self._job)
except Exception:
pass
self._job = None
def _show(self) -> None:
if self._win:
return
try:
wx = self._widget.winfo_rootx()
wy = self._widget.winfo_rooty()
wh = self._widget.winfo_height()
except Exception:
return
self._win = tk.Toplevel(self._widget)
self._win.overrideredirect(True)
self._win.attributes('-topmost', True)
lbl = tk.Label(
self._win,
text=self._text,
bg=SURF2, fg=TEXT_P,
font=(FONT_FAMILY, 11),
padx=10, pady=6,
justify='left',
relief='flat',
)
lbl.pack()
# Position above the widget (avoids overlapping window content below tabs)
# Falls back to below if not enough screen space above.
self._win.update_idletasks()
tw = self._win.winfo_reqwidth()
th = self._win.winfo_reqheight()
ww = self._widget.winfo_width()
sw = self._win.winfo_screenwidth()
x = wx + max(0, (ww - tw) // 2)
x = min(x, sw - tw - 4) # clamp to screen right edge
y = wy - th - 6 # above the widget
if y < 0:
y = wy + wh + 4 # not enough room above → fall back to below
self._win.geometry(f'+{x}+{y}')
def _hide(self) -> None:
if self._win:
try:
self._win.destroy()
except Exception:
pass
self._win = None