Debian Codegraph @

DisplayCAL/wx_addons.py

raw
1 """Extensions and utilities for wxPython GUI functionality.
2
3 It includes image
4 manipulation methods, custom event handling, improved timer implementations,
5 and additional window and display utilities.
6 """
7
8 import contextlib
9 import os
10 import sys
11 import threading
12 import types
13 from time import sleep
14 from typing import ClassVar
15
16 from DisplayCAL import floatspin
17 from DisplayCAL.colormath import special_pow
18 from DisplayCAL.lib.agw.gradientbutton import GradientButton
19 from DisplayCAL.wx_fixes import GenButton, PlateButton, get_dialogs, wx
20
21
22 def AdjustMinMax(self, minvalue=0.0, maxvalue=1.0): # noqa: D417
23 """Adjust min/max.
24
25 Args:
26 minvalue (float, optional): The minimum value to adjust to. Defaults to 0.0.
27 maxvalue (float, optional): The maximum value to adjust to. Defaults to 1.0.
28 """
29 buffer = self.GetDataBuffer()
30 for i, byte in enumerate(buffer):
31 buffer[i] = min(round(minvalue * 255 + byte * (maxvalue - minvalue)), 255)
32
33
34 wx.Image.AdjustMinMax = AdjustMinMax
35
36
37 def Blend(self, bitmap, x, y): # noqa: D417
38 """Blend the given bitmap over the specified position in this bitmap.
39
40 Args:
41 bitmap (wx.Bitmap): The bitmap to blend over this bitmap.
42 x (int): The x-coordinate where the bitmap will be blended.
43 y (int): The y-coordinate where the bitmap will be blended.
44 """
45 dc = wx.MemoryDC(self)
46 dc.DrawBitmap(bitmap, x, y)
47
48
49 wx.Bitmap.Blend = Blend
50
51
52 def Invert(self):
53 """Invert image colors."""
54 databuffer = self.GetDataBuffer()
55 for i, byte in enumerate(databuffer):
56 databuffer[i] = 255 - byte
57
58
59 wx.Image.Invert = Invert
60
61
62 def GammaCorrect(self, from_gamma=-2.4, to_gamma=1.8): # noqa: D417
63 """Gamma correct.
64
65 Args:
66 from_gamma (float, optional): The gamma value to convert from.
67 Defaults to -2.4.
68 to_gamma (float, optional): The gamma value to convert to.
69 Defaults to 1.8.
70 """
71 buffer = self.GetDataBuffer()
72 for i, byte in enumerate(buffer):
73 buffer[i] = round(
74 special_pow(byte / 255.0, from_gamma) ** (1.0 / to_gamma) * 255
75 )
76
77
78 wx.Image.GammaCorrect = GammaCorrect
79
80
81 def IsBW(self):
82 """Check if image is grayscale in the most effective way possible.
83
84 Note that this is a costly operation even though it returns as quickly as
85 possible for non-grayscale images (i.e. when it encounters the first
86 non-equal RGB triplet).
87
88 Returns:
89 bool: True if the image is grayscale (all RGB triplets are equal),
90 False otherwise.
91 """
92 triplet = set()
93 for i, byte in enumerate(self.GetDataBuffer()):
94 triplet.add(byte)
95 if i % 3 == 2:
96 if len(triplet) != 1:
97 return False
98 triplet = set()
99 return True
100
101
102 wx.Image.IsBW = IsBW
103
104
105 def GetRealClientArea(self):
106 """Return the real (non-overlapping) client area of a display.
107
108 Returns:
109 wx.Rect: The real client area of the display, adjusted to ensure it
110 does not overlap with the window's geometry.
111 """
112 # need to fix overlapping ClientArea on some Linux multi-display setups
113 # the client area must be always smaller than the geometry
114 clientarea = list(self.ClientArea)
115 clientarea[0] = max(clientarea[0], self.Geometry[0])
116 clientarea[1] = max(clientarea[1], self.Geometry[1])
117 clientarea[2] = min(clientarea[2], self.Geometry[2])
118 clientarea[3] = min(clientarea[3], self.Geometry[3])
119 return wx.Rect(*clientarea)
120
121
122 wx.Display.GetRealClientArea = GetRealClientArea
123
124
125 def GetAllChildren(self, skip=None): # noqa: D417
126 """Get children of window and its subwindows.
127
128 Args:
129 skip (list | tuple, optional): A list or tuple of windows to skip.
130 Defaults to None, which means no windows are skipped.
131
132 Returns:
133 list[wx.Window]: A list of all child windows, including subwindows,
134 excluding any specified in the skip parameter.
135 """
136 if not isinstance(skip, (list, tuple)):
137 skip = [skip]
138 children = [child for child in list(self.GetChildren()) if child not in skip]
139 allchildren = []
140 for child in children:
141 allchildren.append(child)
142 if hasattr(child, "GetAllChildren") and callable(child.GetAllChildren):
143 allchildren += child.GetAllChildren(skip)
144 return allchildren
145
146
147 wx.Window.GetAllChildren = GetAllChildren
148
149
150 def GetDisplay(self):
151 """Return the display the window is shown on.
152
153 Returns:
154 wx.Display: The display object representing the display the window is
155 shown on. If the window is outside the visible area, it returns
156 the first display.
157 """
158 display_no = wx.Display.GetFromWindow(self)
159 display_no = max(display_no, 0) # window outside visible area
160 return wx.Display(display_no)
161
162
163 wx.Window.GetDisplay = GetDisplay
164
165
166 def SetMaxFontSize(self, pointsize=11): # noqa: D417
167 """Set the maximum font size for this window.
168
169 Args:
170 pointsize (int, optional): The maximum point size for the font.
171 Defaults to 11.
172 """
173 font = self.GetFont()
174 if font.GetPointSize() > pointsize:
175 font.SetPointSize(pointsize)
176 self.SetFont(font)
177
178
179 wx.Window.SetMaxFontSize = SetMaxFontSize
180
181
182 def RealCenterOnScreen(self, dir=wx.BOTH): # noqa: A002, D417
183 """Center the window on the screen that it is on.
184
185 Unlike CenterOnScreen which always centers on 1st screen.
186
187 Args:
188 dir (int, optional): The direction to center the window. Can be
189 wx.HORIZONTAL, wx.VERTICAL, or wx.BOTH. Defaults to wx.BOTH.
190 """
191 x, y = self.Position
192 left, top, w, h = self.GetDisplay().ClientArea
193 if dir & wx.HORIZONTAL:
194 x = left + w / 2 - self.Size[0] / 2
195 if dir & wx.VERTICAL:
196 y = top + h / 2 - self.Size[1] / 2
197 self.Position = x, y
198
199
200 wx.TopLevelWindow.RealCenterOnScreen = RealCenterOnScreen
201
202
203 def SetSaneGeometry(self, x=None, y=None, w=None, h=None): # noqa: D417
204 """Set a 'sane' window position and/or size (within visible screen area).
205
206 Args:
207 x (int, optional): The x-coordinate to set. If None, the current x
208 position is used.
209 y (int, optional): The y-coordinate to set. If None, the current y
210 position is used.
211 w (int, optional): The width to set. If None, the current width is
212 used.
213 h (int, optional): The height to set. If None, the current height is
214 used.
215 """
216 if None not in (x, y):
217 # First, move to coordinates given
218 self.SetPosition((x, y))
219 # Returns the first display's client area if the window
220 # is completely outside the client area of all displays
221 display_client_rect = self.GetDisplay().ClientArea
222 if sys.platform not in ("darwin", "win32"): # Linux
223 # Client-side decorations on wayland, otherwise assume server-side decorations
224 safety_margin = 0 if os.getenv("XDG_SESSION_TYPE") == "wayland" else 40
225 else:
226 safety_margin = 20
227 if None not in (w, h):
228 # Set given size, but resize if needed to fit inside client area
229 if hasattr(self, "MinClientSize"):
230 min_w, min_h = self.MinClientSize
231 else:
232 min_w, min_h = self.WindowToClientSize(self.MinSize)
233 border_lr = self.Size[0] - self.ClientSize[0]
234 border_tb = self.Size[1] - self.ClientSize[1]
235 self.ClientSize = (
236 min(display_client_rect[2] - border_lr, max(w, min_w)),
237 min(display_client_rect[3] - border_tb - safety_margin, max(h, min_h)),
238 )
239 if None not in (x, y) and (
240 not display_client_rect.ContainsXY(x, y)
241 or not display_client_rect.ContainsRect((x, y, self.Size[0], self.Size[1]))
242 ):
243 # If outside client area, move into client area
244 xy = [x, y]
245 for i, pos in enumerate([xy, (x + self.Size[0], y + self.Size[1])]):
246 for j in range(2):
247 if (
248 pos[j] > display_client_rect[j] + display_client_rect[2 + j]
249 or pos[j] < display_client_rect[j]
250 ):
251 if i:
252 xy[j] = (
253 display_client_rect[j]
254 + display_client_rect[2 + j]
255 - self.Size[j]
256 )
257 else:
258 xy[j] = display_client_rect[j]
259 self.SetPosition(tuple(xy))
260
261
262 wx.Window.SetSaneGeometry = SetSaneGeometry
263
264
265 def GridGetSelectedRowsFromSelection(self):
266 """Return the number of fully selected rows.
267
268 Unlike GetSelectedRows, include rows that have been selected
269 by choosing individual cells.
270
271 Returns:
272 list[int]: A list of row indices that are fully selected.
273 """
274 numcols = self.GetNumberCols()
275 rows = []
276 i = -1
277 for cell in self.GetSelection():
278 row, col = cell
279 if row > i:
280 i = row
281 rownumcols = 0
282 rownumcols += 1
283 if rownumcols == numcols:
284 rows.append(row)
285 return rows
286
287
288 wx.grid.Grid.GetSelectedRowsFromSelection = GridGetSelectedRowsFromSelection
289
290
291 def GridGetSelectionRows(self):
292 """Return the selected rows, even if not all cells in a row are selected.
293
294 Returns:
295 list[int]: A list of row indices that are selected.
296 """
297 rows = []
298 i = -1
299 for row, _col in self.GetSelection():
300 if row > i:
301 i = row
302 rows.append(row)
303 return rows
304
305
306 wx.grid.Grid.GetSelectionRows = GridGetSelectionRows
307
308
309 def IsSizer(self):
310 """Check if the window is a sizer.
311
312 Returns:
313 bool: True if the window is a sizer, False otherwise.
314 """
315 return isinstance(self, wx.Sizer)
316
317
318 wx.Window.IsSizer = IsSizer
319
320
321 def gamma_encode(R, G, B, alpha=wx.ALPHA_OPAQUE):
322 """(Re-)Encode R'G'B' colors with specific platform gamma.
323
324 R, G, B = color components in range 0..255
325
326 Note this only has effect under wxMac which assumes a decoding gamma of 1.8
327
328 Args:
329 R (int): Red component (0-255).
330 G (int): Green component (0-255).
331 B (int): Blue component (0-255).
332 alpha (int, optional): Alpha component (0-255). Defaults to wx.ALPHA_OPAQUE.
333
334 Returns:
335 list[int]: A list containing the gamma-encoded R, G, B, and alpha values.
336 """
337 if sys.platform == "darwin":
338 # Adjust for wxMac assuming gamma 1.8 instead of sRGB
339 # Decode R'G'B' -> linear light using sRGB transfer function, then
340 # re-encode to gamma = 1.0 / 1.8 so that when decoded with gamma = 1.8
341 # we get the correct sRGB color
342 RGBa = [
343 round(special_pow(v / 255.0, -2.4) ** (1.0 / 1.8) * 255) for v in (R, G, B)
344 ]
345 RGBa.append(alpha)
346 return RGBa
347 return [R, G, B, alpha]
348
349
350 def get_platform_window_decoration_size():
351 """Get the size of the window decoration.
352
353 Returns:
354 tuple[int, int]: A tuple containing the border and titlebar size.
355 """
356 if sys.platform in ("darwin", "win32"):
357 # Size includes windows decoration
358 if sys.platform == "win32":
359 border = 8 # Windows 7
360 titlebar = 30 # Windows 7
361 else:
362 border = 0 # Mac OS X 10.7 Lion
363 titlebar = 22 # Mac OS X 10.7 Lion
364 else:
365 # Linux. Size does not include window decoration
366 border = 0
367 titlebar = 0
368 return border, titlebar
369
370
371 def draw_granger_rainbow(dc, x=0, y=0, width=1920, height=1080):
372 """Draw a granger rainbow to a DC.
373
374 Args:
375 dc (wx.DC): The device context to draw on.
376 x (int, optional): The x-coordinate of the top-left corner. Defaults to 0.
377 y (int, optional): The y-coordinate of the top-left corner. Defaults to 0.
378 width (int, optional): The width of the rainbow. Defaults to 1920.
379 height (int, optional): The height of the rainbow. Defaults to 1080.
380
381 Raises:
382 NotImplementedError: If the device context does not support alpha
383 transparency.
384
385 """
386 if not isinstance(dc, wx.GCDC):
387 raise NotImplementedError(f"{dc.__class__} lacks alpha transparency support")
388
389 # Widths
390 column_width = int(162.0 / 1920.0 * width)
391 rainbow_width = width - column_width * 2
392 strip_width = int(rainbow_width / 7.0)
393 rainbow_width = strip_width * 7
394 column_width = (width - rainbow_width) / 2
395
396 # Gray columns left/right
397 dc.GradientFillLinear(
398 wx.Rect(x, y, width, height),
399 wx.Colour(0, 0, 0),
400 wx.Colour(255, 255, 255),
401 wx.UP,
402 )
403
404 # Granger rainbow
405 rainbow = [
406 (255, 0, 255),
407 (0, 0, 255),
408 (0, 255, 255),
409 (0, 255, 0),
410 (255, 255, 0),
411 (255, 0, 0),
412 (255, 0, 255),
413 ]
414 start = rainbow[-2]
415 for i, end in enumerate(rainbow):
416 dc.GradientFillLinear(
417 wx.Rect(x + column_width + strip_width * i, y, strip_width, height),
418 wx.Colour(*start),
419 wx.Colour(*end),
420 wx.RIGHT,
421 )
422 start = end
423
424 # White-to-black gradient with transparency for shading
425 # Top half - white to transparent
426 dc.GradientFillLinear(
427 wx.Rect(x + column_width, y, rainbow_width, height / 2),
428 wx.Colour(0, 0, 0, 0),
429 wx.Colour(255, 255, 255, 255),
430 wx.UP,
431 )
432 # Bottom half - transparent to black
433 dc.GradientFillLinear(
434 wx.Rect(x + column_width, y + height / 2, rainbow_width, height / 2),
435 wx.Colour(0, 0, 0, 255),
436 wx.Colour(255, 255, 255, 0),
437 wx.UP,
438 )
439
440
441 def create_granger_rainbow_bitmap(width=1920, height=1080, filename=None):
442 """Create a granger rainbow bitmap.
443
444 Args:
445 width (int): The width of the bitmap. Defaults to 1920.
446 height (int): The height of the bitmap. Defaults to 1080.
447 filename (str, optional): If provided, save the bitmap to this file.
448 Defaults to None.
449
450 Returns:
451 wx.Bitmap: The created bitmap containing the granger rainbow.
452 """
453 # Main bitmap
454 bmp = wx.EmptyBitmap(width, height)
455 mdc = wx.MemoryDC(bmp)
456 dc = wx.GCDC(mdc)
457
458 draw_granger_rainbow(dc, 0, 0, width, height)
459
460 mdc.SelectObject(wx.NullBitmap)
461
462 if filename:
463 name, ext = os.path.splitext(filename)
464 ext = ext.lower()
465 bmp_type = {
466 ".bmp": wx.BITMAP_TYPE_BMP,
467 ".jpe": wx.BITMAP_TYPE_JPEG,
468 ".jpg": wx.BITMAP_TYPE_JPEG,
469 ".jpeg": wx.BITMAP_TYPE_JPEG,
470 ".jfif": wx.BITMAP_TYPE_JPEG,
471 ".pcx": wx.BITMAP_TYPE_PCX,
472 ".png": wx.BITMAP_TYPE_PNG,
473 ".tga": wx.BITMAP_TYPE_TGA,
474 ".tif": wx.BITMAP_TYPE_TIFF,
475 ".tiff": wx.BITMAP_TYPE_TIFF,
476 ".xpm": wx.BITMAP_TYPE_XPM,
477 }.get(ext, wx.BITMAP_TYPE_PNG)
478 bmp.SaveFile(filename, bmp_type)
479 return bmp
480
481
482 def get_parent_frame(window):
483 """Get parent frame (if any).
484
485 Args:
486 window (wx.Window): The wx.Window object to start searching from.
487
488 Returns:
489 None | wx.Frame: The parent frame of the window, or None if no parent
490 frame is found.
491 """
492 parent = window.Parent
493 while parent:
494 if isinstance(parent, wx.Frame):
495 return parent
496 parent = parent.Parent
497 return None
498
499
500 class CustomEvent(wx.PyEvent):
501 """A wx.Event replacement.
502
503 Args:
504 typeId (int): The event type ID.
505 object (wx.Window): The wx.Window object associated with the event.
506 window (wx.Window, optional): The window associated with the event.
507 Defaults to None.
508 """
509
510 def __init__(self, typeId, object, window=None): # noqa: A002
511 wx.PyEvent.__init__(self, object.GetId(), typeId)
512 self.EventObject = object
513 self.Window = window
514
515 def GetWindow(self):
516 """Return the window associated with this event.
517
518 Returns:
519 wx.Window: The window associated with this event, or None if not set.
520 """
521 return self.Window
522
523
524 _GLOBAL_TIMER_LOCK = threading.Lock()
525
526
527 wxEVT_BETTER_TIMER = wx.NewEventType() # noqa: N816
528 EVT_BETTER_TIMER = wx.PyEventBinder(wxEVT_BETTER_TIMER, 1)
529
530
531 class BetterTimerEvent(wx.PyCommandEvent):
532 """A wx.Timer event replacement.
533
534 Args:
535 id (int): The ID of the timer event.
536 ms (int): The interval of the timer in milliseconds.
537 """
538
539 def __init__(self, id=wx.ID_ANY, ms=0): # noqa: A002
540 wx.PyCommandEvent.__init__(self, wxEVT_BETTER_TIMER, id)
541 self._ms = ms
542
543 def GetInterval(self):
544 """Return the interval of the timer in milliseconds.
545
546 Returns:
547 int: The interval of the timer in milliseconds.
548 """
549 return self._ms
550
551 Interval = property(GetInterval)
552
553
554 class BetterTimer(wx.Timer):
555 """A wx.Timer replacement.
556
557 Doing GUI updates using regular timers can be incredibly SEGFAULTy under
558 wxPython Phoenix when several timers run concurrently.
559
560 This approach uses a global lock to work around the issue.
561
562 Args:
563 owner (wx.Window, optional): The owner window that will receive the
564 timer events. Defaults to None.
565 timerid (int): The ID of the timer. If -1, a new ID will be generated.
566 Defaults to wx.ID_ANY.
567 """
568
569 def __init__(self, owner=None, timerid=wx.ID_ANY):
570 wx.Timer.__init__(self, None, timerid)
571 self._owner = owner
572
573 def Notify(self):
574 """Notify the owner that the timer has expired."""
575 if self._owner and _GLOBAL_TIMER_LOCK.acquire(False):
576 try:
577 wx.PostEvent(self._owner, BetterTimerEvent(self.Id, self.Interval))
578 finally:
579 _GLOBAL_TIMER_LOCK.release()
580
581
582 class BetterCallLater(wx.CallLater):
583 """A wx.CallLater replacement.
584
585 Args:
586 millis (int): The number of milliseconds to wait before calling the
587 callable.
588 callableObj (callable): The callable object to call when the timer
589 expires.
590 *args: Positional arguments to pass to the callable.
591 **kwargs: Keyword arguments to pass to the callable.
592 """
593
594 def __init__(self, millis, callableObj, *args, **kwargs):
595 wx.CallLater.__init__(self, millis, callableObj, *args, **kwargs)
596
597 def Notify(self):
598 """Notify the owner that the timer has expired."""
599 if _GLOBAL_TIMER_LOCK.acquire(True):
600 try:
601 wx.CallLater.Notify(self)
602 finally:
603 _GLOBAL_TIMER_LOCK.release()
604
605
606 class ThreadedTimer:
607 """Threaded wx.Timer replacement.
608
609 This uses threads instead of actual timers which are a limited resource.
610
611 Args:
612 owner (wx.Window, optional): The owner window that will receive the
613 timer events. Defaults to None.
614 timerid (int): The ID of the timer. If -1, a new ID will be generated.
615 Defaults to wx.ID_ANY.
616 """
617
618 def __init__(self, owner=None, timerid=wx.ID_ANY):
619 self._owner = owner
620 if timerid < 0:
621 timerid = wx.Window.NewControlId()
622 self._id = timerid
623 self._ms = 0
624 self._oneshot = False
625 self._keep_running = False
626 self._thread = None
627
628 def _notify(self):
629 """Notify the owner that the timer has expired."""
630 if _GLOBAL_TIMER_LOCK.acquire(self._oneshot):
631 try:
632 self.Notify()
633 finally:
634 _GLOBAL_TIMER_LOCK.release()
635
636 def _timer(self):
637 """The timer thread that runs the timer logic."""
638 self._keep_running = True
639 while self._keep_running:
640 sleep(self._ms / 1000.0)
641 if self._keep_running:
642 wx.CallAfter(self._notify)
643 if self._oneshot:
644 self._keep_running = False
645
646 def Destroy(self):
647 """Destroy the timer and release its resources."""
648 if hasattr(wx.Window, "UnreserveControlId") and self.Id < 0:
649 with contextlib.suppress(wx.wxAssertionError):
650 wx.Window.UnreserveControlId(self.Id)
651
652 def GetId(self):
653 """Return the ID of the timer.
654
655 Returns:
656 int: The ID of the timer.
657 """
658 return self._id
659
660 def GetInterval(self):
661 """Return the interval of the timer in milliseconds.
662
663 Returns:
664 int: The interval of the timer in milliseconds.
665 """
666 return self._ms
667
668 def GetOwner(self):
669 """Return the owner of the timer.
670
671 Returns:
672 wx.Window: The owner window that will receive the timer events.
673 """
674 return self._owner
675
676 def SetOwner(self, owner):
677 """Set the owner of the timer.
678
679 Args:
680 owner (wx.Window): The owner window that will receive the timer
681 events.
682 """
683 self._owner = owner
684
685 Id = property(GetId)
686 Interval = property(GetInterval)
687 Owner = property(GetOwner, SetOwner)
688
689 def IsOneShot(self):
690 """Check if the timer is a one-shot timer.
691
692 Returns:
693 bool: True if the timer is a one-shot timer, False otherwise.
694 """
695 return self._oneshot
696
697 def IsRunning(self):
698 """Check if the timer is currently running.
699
700 Returns:
701 bool: True if the timer is running, False otherwise.
702 """
703 return self._keep_running
704
705 def Notify(self):
706 """Notify the owner that the timer has expired."""
707 if self._owner:
708 self._owner.ProcessEvent(BetterTimerEvent(self._id, self._ms))
709
710 def Start(self, milliseconds=-1, oneShot=False):
711 """Start the timer with the given milliseconds and one-shot flag.
712
713 Args:
714 milliseconds (int): The number of milliseconds to wait before
715 calling the Notify method. If -1, the timer will not be
716 restarted.
717 oneShot (bool): If True, the timer will only run once and then
718 stop. If False, the timer will keep running at the specified
719 interval.
720 """
721 if self._thread and self._thread.is_alive():
722 self._keep_running = False
723 self._thread.join()
724 if milliseconds > -1:
725 self._ms = milliseconds
726 self._oneshot = oneShot
727 self._thread = threading.Thread(target=self._timer, name="ThreadedTimer")
728 self._thread.start()
729
730 def Stop(self):
731 """Stop the timer."""
732 self._keep_running = False
733
734
735 class ThreadedCallLater(ThreadedTimer):
736 """Threaded wx.CallLater replacement.
737
738 This uses threads instead of actual timers which are a limited resource.
739
740 Args:
741 millis (int): The number of milliseconds to wait before calling the
742 callable.
743 callableObj (callable): The callable object to call when the timer
744 expires.
745 *args: Positional arguments to pass to the callable.
746 **kwargs: Keyword arguments to pass to the callable.
747 """
748
749 def __init__(self, millis, callableObj, *args, **kwargs):
750 ThreadedTimer.__init__(self)
751 self._oneshot = True
752 self._callable = callableObj
753 self._has_run = False
754 self._result = None
755 self.SetArgs(*args, **kwargs)
756 self.Start(millis)
757
758 def GetResult(self):
759 """Get the result of the callable after the timer has run.
760
761 Returns:
762 Any: The result of the callable, or None if the timer has not run.
763 """
764 return self._result
765
766 Result = property(GetResult)
767
768 def HasRun(self):
769 """Check if the timer has run.
770
771 Returns:
772 bool: True if the timer has run, False otherwise.
773 """
774 return self._has_run
775
776 def Notify(self):
777 """Notify the owner that the timer has expired and call the callable."""
778 self._result = self._callable(*self._args, **self._kwargs)
779 self._has_run = True
780
781 def SetArgs(self, *args, **kwargs):
782 """Set the arguments to be passed to the callable when the timer expires."""
783 self._args = args
784 self._kwargs = kwargs
785
786 def Start(self, millis=None, *args, **kwargs):
787 """Start the timer with the given milliseconds and optional args/kwargs.
788
789 Args:
790 millis (int, optional): The number of milliseconds to wait before
791 calling the callable. Defaults to None.
792 *args: Positional arguments to pass to the callable.
793 **kwargs: Keyword arguments to pass to the callable.
794 """
795 if args:
796 self._args = args
797 if kwargs:
798 self._kwargs = kwargs
799 ThreadedTimer.Start(self, millis, True)
800
801 Restart = Start
802
803
804 class BetterWindowDisabler:
805 """Class to disable all top-level windows and their child windows.
806
807 This is actually needed under Mac OS X where disabling a top level window
808 will not prevent interaction with its children.
809
810 If toplevelparent is given, disable only this window and its child windows.
811
812 Args:
813 skip (list, optional): A list of windows to skip when disabling.
814 Defaults to None.
815 toplevelparent (wx.Window, optional): The top-level parent window to
816 disable. If None, all top-level windows will be disabled.
817 Defaults to None.
818 include_menus (bool, optional): If True, include menus in the
819 disabling process. Defaults to False.
820 """
821
822 windows: ClassVar[set] = set()
823
824 def __init__(self, skip=None, toplevelparent=None, include_menus=False):
825 self._windows = []
826 self.skip = skip
827 self.toplevelparent = toplevelparent
828 self.include_menus = include_menus
829 self.disable()
830
831 def __del__(self) -> None:
832 """Destruct the instance."""
833 self.enable()
834
835 def disable(self):
836 """Disable the windows."""
837 self.enable(False)
838
839 def enable(self, enable=True):
840 """Enable or disable the windows.
841
842 Args:
843 enable (bool): If True, enable the windows; if False, disable them.
844 """
845 if enable:
846 self.restore_window_state()
847 return
848
849 skip = self.skip or []
850 if skip and not isinstance(skip, (list, tuple)):
851 skip = [skip]
852 if self.toplevelparent:
853 toplevel = [self.toplevelparent]
854 else:
855 toplevel = list(wx.GetTopLevelWindows())
856 for w in toplevel:
857 if (
858 w
859 and w not in skip
860 and "Inspection" not in f"{w}"
861 and w not in BetterWindowDisabler.windows
862 ):
863 self._windows.append(w)
864 # Selectively add children to our list of handled
865 # windows. This prevents a segfault with wxPython 4
866 # under macOS where GetAllChildren includes sub-controls
867 # of controls, like scrollbars etc.
868 for child in w.GetAllChildren(skip + toplevel):
869 if (
870 child
871 and isinstance(
872 child,
873 (
874 wx.BitmapButton,
875 wx.Button,
876 wx.CheckBox,
877 wx.Choice,
878 wx.ComboBox,
879 wx.ListBox,
880 wx.ListCtrl,
881 wx.RadioButton,
882 wx.SpinCtrl,
883 wx.Slider,
884 wx.StaticText,
885 wx.TextCtrl,
886 wx.grid.Grid,
887 floatspin.FloatSpin,
888 GenButton,
889 GradientButton,
890 PlateButton,
891 ),
892 )
893 and child not in BetterWindowDisabler.windows
894 ):
895 # Don't disable panels, this can have weird side
896 # effects for contained controls
897 self._windows.append(child)
898 if self.include_menus and (menubar := w.GetMenuBar()):
899 for menu, _label in menubar.GetMenus():
900 for item in menu.GetMenuItems():
901 self._windows.append(item)
902
903 def Enable(w_, enable=True):
904 """Enable or disable the window.
905
906 Args:
907 w_ (wx.Window): The window to enable or disable.
908 enable (bool): If True, enable the window; if False,
909 disable it.
910 """
911 w_._BetterWindowDisabler_enabled = enable
912
913 def Disable(w_):
914 """Disable the window.
915
916 Args:
917 w_ (wx.Window): The window to disable.
918 """
919 w_._BetterWindowDisabler_enabled = False
920
921 for w in reversed(self._windows):
922 BetterWindowDisabler.windows.add(w)
923 enabled = w.IsEnabled()
924 w.Enable(False)
925 if hasattr(w, "Disable"):
926 w._BetterWindowDisabler_Disable = w.Disable
927 w.Disable = types.MethodType(Disable, w)
928 w._BetterWindowDisabler_Enable = w.Enable
929 w.Enable = types.MethodType(Enable, w)
930 w.Enable(enabled)
931 return
932
933 self.restore_window_state()
934
935 def restore_window_state(self):
936 """Restore the state of all windows that were disabled."""
937 for w in self._windows:
938 BetterWindowDisabler.windows.remove(w)
939 if not w:
940 continue # window has been destroyed
941 if hasattr(w, "_BetterWindowDisabler_Disable"):
942 w.Disable = w._BetterWindowDisabler_Disable
943 if hasattr(w, "_BetterWindowDisabler_Enable"):
944 w.Enable = w._BetterWindowDisabler_Enable
945 if hasattr(w, "_BetterWindowDisabler_enabled"):
946 w.Enable(w._BetterWindowDisabler_enabled)
947
948
949 class CustomGridCellEvent(CustomEvent):
950 """Custom event for wx.grid.GridCell.
951
952 Args:
953 typeId (int): The event type ID.
954 object (wx.grid.GridCell): The grid cell object associated with the
955 event.
956 row (int, optional): The row index of the grid cell event. Defaults to
957 -1.
958 col (int, optional): The column index of the grid cell event. Defaults
959 to -1.
960 window (wx.Window, optional): The window associated with the event.
961 Defaults to None.
962 """
963
964 def __init__(self, typeId, object, row=-1, col=-1, window=None): # noqa: A002
965 CustomEvent.__init__(self, typeId, object, window)
966 self.Row = row
967 self.Col = col
968
969 def GetRow(self):
970 """Get the row index of the grid cell event.
971
972 Returns:
973 int: The row index of the grid cell event.
974 """
975 return self.Row
976
977 def GetCol(self):
978 """Get the column index of the grid cell event.
979
980 Returns:
981 int: The column index of the grid cell event.
982 """
983 return self.Col
984
985
986 class PopupMenu:
987 """A collection of menus that has a wx.MenuBar-like interface.
988
989 Args:
990 parent (wx.Window): The parent window that will display the popup menu.
991 """
992
993 def __init__(self, parent):
994 self.Parent = parent
995 self.TopLevelParent = parent.TopLevelParent
996 self._menus = []
997 self._enabledtop = {}
998
999 def Append(self, menu, title):
1000 """Append a menu to the popup menu."""
1001 self._menus.append((menu, title))
1002
1003 def EnableTop(self, pos, enable=True):
1004 """Enable or disable the top-level menu at the given position.
1005
1006 Args:
1007 pos (int): The position of the top-level menu to enable or disable.
1008 enable (bool): If True, enable the menu; if False, disable it.
1009 """
1010 self._enabledtop[pos] = enable
1011
1012 def FindItemById(self, id): # noqa: A002
1013 """Find a menu item by its ID.
1014
1015 Args:
1016 id (int): The ID of the menu item to find.
1017
1018 Returns:
1019 None | wx.MenuItem: The menu item with the given ID, or None if not
1020 found.
1021 """
1022 for menu, _label in self._menus:
1023 item = menu.FindItemById(id)
1024 if item:
1025 return item
1026 return None
1027
1028 def FindMenu(self, title):
1029 """Find the index of a menu by its title.
1030
1031 Args:
1032 title (str): The title of the menu to find.
1033
1034 Returns:
1035 int: The index of the menu with the given title, or wx.NOT_FOUND if
1036 the menu is not found.
1037 """
1038 for i, (_menu, label) in enumerate(self._menus):
1039 if title == label:
1040 return i
1041 return wx.NOT_FOUND
1042
1043 def GetMenu(self, index):
1044 """Get the menu at the given index.
1045
1046 Args:
1047 index (int): The index of the menu to retrieve.
1048
1049 Returns:
1050 wx.Menu: The menu at the specified index.
1051 """
1052 return self._menus[index][0]
1053
1054 def GetMenuCount(self):
1055 """Return the number of menus in this menubar.
1056
1057 Returns:
1058 int: The number of menus in this menubar.
1059 """
1060 return len(self._menus)
1061
1062 def GetMenus(self):
1063 """Return menus.
1064
1065 Returns:
1066 list[wx.Menu]: List of child menus.
1067 """
1068 return list(self._menus)
1069
1070 def SetMenus(self, menus):
1071 """Set menus.
1072
1073 Args:
1074 menus (list[wx.Menu]): A list of wx.Menu instances to set as a
1075 child of this menubar.
1076 """
1077 self._menus = []
1078 for menu, label in menus:
1079 self.Append((menu, label))
1080
1081 Menus = property(GetMenus, SetMenus)
1082
1083 def IsEnabledTop(self, pos):
1084 """Check if the top-level menu at the given position is enabled.
1085
1086 Args:
1087 pos (int): The position of the top-level menu to check.
1088
1089 Returns:
1090 bool: True if the top-level menu is enabled, False otherwise.
1091 """
1092 return self._enabledtop.get(pos, True)
1093
1094 def SetMenuLabel(self, pos, label):
1095 """Set the label of a menu at the given position.
1096
1097 Args:
1098 pos (int): The position of the menu to set the label for.
1099 label (str): The new label for the menu.
1100 """
1101 self._menus[pos] = (self._menus[pos][0], label)
1102
1103 def bind_keys(self):
1104 """Bind accelerator keys to the top level parent."""
1105 if sys.platform == "darwin":
1106 accels = self.get_accelerator_entries()
1107 self.TopLevelParent.SetAcceleratorTable(wx.AcceleratorTable(accels()))
1108 else:
1109 self.TopLevelParent.Bind(wx.EVT_CHAR_HOOK, self.key_handler)
1110
1111 def get_accelerator_entries(self):
1112 """Get accelerator entries for all menus.
1113
1114 Returns:
1115 list[wx.AcceleratorEntry]: List of accelerator entries for all
1116 menu items.
1117 """
1118 accels = []
1119 for menu, _label in self._menus:
1120 for item in menu.MenuItems:
1121 accel = item.Accel
1122 if accel:
1123 accel = wx.AcceleratorEntry(
1124 accel.Flags, accel.KeyCode, accel.Command, item
1125 )
1126 accels.append(accel)
1127 return accels
1128
1129 def key_handler(self, event):
1130 """Handle accelerator keys.
1131
1132 Args:
1133 event (wx.KeyEvent): The key event to handle.s
1134 """
1135 keycode = event.KeyCode
1136 flags = wx.ACCEL_NORMAL
1137 for key in ("ALT", "CMD", "CTRL", "SHIFT"):
1138 if wx.GetKeyState(getattr(wx, "WXK_" + key.replace("CTRL", "CONTROL"), -1)):
1139 flags |= getattr(wx, "ACCEL_" + key.upper())
1140 for menu, _label in self._menus:
1141 for item in menu.MenuItems:
1142 accel = item.Accel
1143 if accel and accel.KeyCode == keycode and accel.Flags == flags:
1144 event = wx.CommandEvent(wx.wxEVT_COMMAND_MENU_SELECTED)
1145 event.Id = item.Id
1146 if item.Kind == wx.ITEM_RADIO:
1147 event.SetInt(1)
1148 elif item.Kind == wx.ITEM_CHECK:
1149 event.SetInt(int(not item.Checked))
1150 self.TopLevelParent.ProcessEvent(event)
1151
1152 def popup(self):
1153 """Popup the list of menus (with actual menus as submenus)."""
1154 top_menu = wx.Menu()
1155
1156 for menu, label in self._menus:
1157 top_menu.AppendSubMenu(menu, label)
1158
1159 self.Parent.PopupMenu(top_menu)
1160
1161 # Delete menuitems (not submenus)
1162 for item in top_menu.MenuItems:
1163 top_menu.Delete(item)
1164
1165 # Now we can safely destroy the menu without affecting submenus
1166 top_menu.Destroy()
1167
1168
1169 class FileDrop(wx.FileDropTarget):
1170 """A wx.FileDropTarget derivative that can handle multiple file types.
1171
1172 Args:
1173 drophandlers (dict): A dictionary mapping file extensions to
1174 handler functions that will be called when files with those
1175 extensions are dropped. The handler function should accept a
1176 single argument, the filename.s.
1177 """
1178
1179 def __init__(self, drophandlers=None):
1180 wx.FileDropTarget.__init__(self)
1181 if drophandlers is None:
1182 drophandlers = {}
1183 self.drophandlers = drophandlers
1184 self.unsupported_handler = None
1185
1186 def OnDropFiles(self, x, y, filenames):
1187 """Handle dropped files.
1188
1189 Args:
1190 x (int): The x-coordinate of the drop position.
1191 y (int): The y-coordinate of the drop position.
1192 filenames (list[str]): List of file paths that were dropped.
1193 """
1194 dialogs = get_dialogs()
1195 interactable = not hasattr(self, "parent") or (
1196 self.parent.Enabled and (not dialogs or self.parent in dialogs)
1197 )
1198 if not interactable:
1199 wx.Bell()
1200 return False
1201 self._files = []
1202 self._filenames = filenames
1203
1204 for filename in filenames:
1205 name, ext = os.path.splitext(filename)
1206 if ext.lower() in self.drophandlers:
1207 self._files.append((ext.lower(), filename))
1208
1209 if self._files:
1210 self._files.reverse()
1211 wx.CallLater(1, wx.CallAfter, self.process)
1212 elif self.unsupported_handler:
1213 wx.CallLater(1, wx.CallAfter, self.unsupported_handler)
1214 return False
1215
1216 def process(self):
1217 """Process the files that were dropped."""
1218 ms = 1.0 / 60
1219 while self._files:
1220 if hasattr(self, "parent") and hasattr(self.parent, "worker"):
1221 while self.parent.worker.is_working():
1222 wx.Yield()
1223 sleep(ms)
1224 if self.parent.worker.thread_abort:
1225 return
1226 ext, filename = self._files.pop()
1227 self.drophandlers[ext](filename)
1228
1229
1230 class IdFactory:
1231 """Inspired by wxPython 4 (Phoenix) wx.IdManager."""
1232
1233 CurrentId = 100
1234 ReservedIds: ClassVar[set] = set()
1235
1236 @classmethod
1237 def NewId(cls) -> int:
1238 """Replacement for wx.NewId().
1239
1240 Returns:
1241 int: A new unique ID that is not reserved.
1242 """
1243 start_id = cls.CurrentId
1244
1245 while True:
1246 # Skip the part of IDs space that contains hard-coded values
1247 if cls.CurrentId == wx.ID_LOWEST:
1248 cls.CurrentId = wx.ID_HIGHEST + 1
1249 id_ = cls.CurrentId
1250 if id_ < 30095:
1251 cls.CurrentId += 1
1252 else:
1253 cls.CurrentId = 100
1254 if id_ not in cls.ReservedIds:
1255 break
1256 if cls.CurrentId == start_id:
1257 raise RuntimeError(
1258 "Error: Out of IDs. Recommend shutting down application."
1259 )
1260
1261 cls.ReserveId(id_)
1262
1263 return id_
1264
1265 @classmethod
1266 def ReserveId(cls, id_) -> None:
1267 """Reserve an ID.
1268
1269 Args:
1270 id_ (int): The ID to reserve.
1271 """
1272 cls.ReservedIds.add(id_)
1273
1274 @classmethod
1275 def UnreserveId(cls, id_) -> None:
1276 """Unreserve an ID.
1277
1278 Args:
1279 id_ (int): The ID to unreserve.
1280 """
1281 cls.ReservedIds.remove(id_)