Debian Codegraph @

DisplayCAL/wx_windows.py

raw
1 """wxPython-based GUI components and utilities.
2
3 It includes custom widgets, dialogs, frames, and enhancements to standard
4 wxPython controls, offering extended functionality and improved aesthetics. The
5 module also supports advanced features like custom rendering, event handling,
6 and platform-specific adjustments.
7 """
8
9 from __future__ import annotations
10
11 import contextlib
12 import errno
13 import html
14 import math
15 import os
16 import re
17 import signal
18 import socket
19 import subprocess as sp
20 import sys
21 import tarfile
22 import textwrap
23 import threading
24 import warnings
25 import xml.parsers.expat
26 import zipfile
27 from datetime import datetime
28 from time import gmtime, sleep, strftime, time
29 from typing import ClassVar
30
31 from DisplayCAL import audio, config, floatspin, util_str
32 from DisplayCAL import demjson_compat as demjson
33 from DisplayCAL import localization as lang
34 from DisplayCAL.config import (
35 APPBASENAME,
36 CONFIG_HOME,
37 DEFAULTS,
38 LOGDIR,
39 PYNAME,
40 get_bitmap,
41 get_data_path,
42 get_default_dpi,
43 get_icon,
44 get_verified_path,
45 getcfg,
46 hascfg,
47 set_default_app_dpi,
48 setcfg,
49 )
50 from DisplayCAL.debughelpers import (
51 DownloadError,
52 Info,
53 UnloggedError,
54 UnloggedInfo,
55 UnloggedWarning,
56 getevtobjname,
57 getevttype,
58 )
59 from DisplayCAL.icc_profile import (
60 ICCProfile,
61 ICCProfileInvalidError,
62 )
63 from DisplayCAL.lib.agw import labelbook, pygauge
64 from DisplayCAL.lib.agw.fourwaysplitter import (
65 _TOLERANCE,
66 FLAG_CHANGED,
67 FLAG_PRESSED,
68 NOWHERE,
69 FourWaySplitter,
70 FourWaySplitterEvent,
71 )
72 from DisplayCAL.lib.agw.gradientbutton import CLICK, HOVER, GradientButton
73 from DisplayCAL.meta import NAME as APPNAME
74 from DisplayCAL.network import ScriptingClientSocket, get_network_addr
75 from DisplayCAL.options import DEBUG
76 from DisplayCAL.util_os import launch_file, waccess
77 from DisplayCAL.util_str import box, safe_str
78 from DisplayCAL.util_xml import dict2xml
79 from DisplayCAL.wexpect import split_command_line
80 from DisplayCAL.wx_addons import (
81 EVT_BETTER_TIMER,
82 BetterTimer,
83 BetterWindowDisabler,
84 CustomEvent,
85 gamma_encode,
86 get_parent_frame,
87 get_platform_window_decoration_size,
88 wx,
89 )
90 from DisplayCAL.wx_addons import FileDrop as _FileDrop
91
92 # from wexpect import split_command_line
93 from DisplayCAL.wx_fixes import (
94 GenBitmapButton,
95 GenButton,
96 GTKMenuItemGetFixedLabel,
97 PlateButton,
98 ThemedGenButton,
99 adjust_font_size_for_gcdc,
100 get_bitmap_disabled,
101 get_dc_font_size,
102 get_dialogs,
103 platebtn,
104 set_bitmap_labels,
105 set_maxsize,
106 wx_Panel,
107 )
108
109 try:
110 from wx.lib.agw import aui
111 from wx.lib.agw.aui import AuiDefaultTabArt
112 except ImportError:
113 from wx import aui
114 from wx.aui import PyAuiTabArt as AuiDefaultTabArt
115 import wx.html
116 import wx.lib.filebrowsebutton as filebrowse
117 from wx._core import wxAssertionError
118 from wx.lib import fancytext
119 from wx.lib.agw import hyperlink
120 from wx.lib.statbmp import GenStaticBitmap
121
122 TASKBAR = None
123 SAFE_WX_UI = os.getenv("DISPLAYCAL_UNSAFE_WX_UI", "").strip() != "1"
124 if sys.platform == "win32" and sys.getwindowsversion() >= (6, 1):
125 try:
126 pass
127 except Exception as exception:
128 print(exception)
129
130 NUMPAD_KEYCODES = [
131 wx.WXK_NUMPAD0,
132 wx.WXK_NUMPAD1,
133 wx.WXK_NUMPAD2,
134 wx.WXK_NUMPAD3,
135 wx.WXK_NUMPAD4,
136 wx.WXK_NUMPAD5,
137 wx.WXK_NUMPAD6,
138 wx.WXK_NUMPAD7,
139 wx.WXK_NUMPAD8,
140 wx.WXK_NUMPAD9,
141 wx.WXK_NUMPAD_ADD,
142 wx.WXK_NUMPAD_DECIMAL,
143 wx.WXK_NUMPAD_ENTER,
144 wx.WXK_NUMPAD_EQUAL,
145 wx.WXK_NUMPAD_DIVIDE,
146 wx.WXK_NUMPAD_MULTIPLY,
147 wx.WXK_NUMPAD_SEPARATOR,
148 wx.WXK_NUMPAD_SUBTRACT,
149 ]
150
151 NAV_KEYCODES = [
152 wx.WXK_DOWN,
153 wx.WXK_END,
154 wx.WXK_HOME,
155 wx.WXK_LEFT,
156 wx.WXK_PAGEDOWN,
157 wx.WXK_PAGEUP,
158 wx.WXK_RIGHT,
159 wx.WXK_TAB,
160 wx.WXK_UP,
161 wx.WXK_NUMPAD_DOWN,
162 wx.WXK_NUMPAD_END,
163 wx.WXK_NUMPAD_HOME,
164 wx.WXK_NUMPAD_LEFT,
165 wx.WXK_NUMPAD_PAGEDOWN,
166 wx.WXK_NUMPAD_PAGEUP,
167 wx.WXK_NUMPAD_RIGHT,
168 wx.WXK_NUMPAD_UP,
169 ]
170
171 PROCESSING_KEYCODES = [
172 wx.WXK_ESCAPE,
173 wx.WXK_RETURN,
174 wx.WXK_INSERT,
175 wx.WXK_DELETE,
176 wx.WXK_BACK,
177 ]
178
179 MODIFIER_KEYCODES = [wx.WXK_SHIFT, wx.WXK_CONTROL, wx.WXK_ALT, wx.WXK_COMMAND]
180
181 REMAINING_TIME_LABEL = "--:--:--"
182
183
184 class AboutDialog(wx.Dialog):
185 """About dialog for the application."""
186
187 def __init__(self, *args, **kwargs):
188 kwargs["style"] = wx.DEFAULT_DIALOG_STYLE & ~(
189 wx.RESIZE_BORDER | wx.MAXIMIZE_BOX
190 )
191 kwargs["name"] = "aboutdialog"
192 wx.Dialog.__init__(self, *args, **kwargs)
193
194 # Set an icon so text isn't crammed to the left of the titlebar under
195 # Windows (other platforms?)
196 self.SetIcons(config.get_icon_bundle([256, 48, 32, 16], APPNAME))
197
198 self.Sizer = wx.BoxSizer(wx.VERTICAL)
199 self.panel = wx.ScrolledWindow(self, style=wx.VSCROLL)
200 self.Sizer.Add(self.panel, 1, flag=wx.EXPAND)
201
202 self.panel.Sizer = wx.BoxSizer(wx.VERTICAL)
203
204 if "gtk3" in wx.PlatformInfo:
205 # Fix background color not working for panels under GTK3
206 self.Bind(wx.EVT_ERASE_BACKGROUND, self.OnEraseBackground)
207
208 if "gtk3" in wx.PlatformInfo:
209 OnEraseBackground = wx_Panel.__dict__["OnEraseBackground"]
210
211 def OnClose(self, event):
212 """Handle the close button event to hide the dialog.
213
214 Args:
215 event (wx.CommandEvent): The event triggered by the close button.
216 """
217 self.Hide()
218
219 def Layout(self):
220 """Layout the dialog and its components."""
221 self.Sizer.SetMinSize(480, 560)
222 self.Sizer.SetSizeHints(self)
223 self.panel.SetScrollRate(2, 2)
224 self.Sizer.Layout()
225 if wx.Platform == "__WXGTK__":
226 for child in self.panel.Children:
227 # Fix height of children
228 child.MinSize = child.MinSize[0], child.Size[1]
229
230 def add_items(self, items):
231 """Add items to the dialog.
232
233 Args:
234 items (list): A list of items to add to the dialog.
235 """
236 self.line = wx.Panel(self, size=(-1, 1))
237 self.line.SetBackgroundColour(
238 wx.SystemSettings.GetColour(wx.SYS_COLOUR_3DLIGHT)
239 )
240 self.Sizer.Add(self.line, flag=wx.EXPAND)
241 self.btnpanel = wx.Panel(self)
242 self.btnpanel.Sizer = wx.GridSizer(1, 1, 0, 0)
243 self.Sizer.Add(self.btnpanel, flag=wx.EXPAND)
244 self.ok = wx.Button(self.btnpanel, -1, lang.getstr("close"))
245 self.btnpanel.Sizer.Add(self.ok, flag=wx.ALL | wx.ALIGN_CENTER, border=12)
246 self.Bind(wx.EVT_BUTTON, self.OnClose, id=self.ok.GetId())
247 for item in items:
248 if (
249 not isinstance(item, wx.Window)
250 and hasattr(item, "__iter__")
251 and [
252 subitem for subitem in item if not isinstance(subitem, (int, float))
253 ]
254 ):
255 sizer = wx.BoxSizer(wx.HORIZONTAL)
256 self.add_item(sizer, self.panel.Sizer)
257 for subitem in item:
258 self.add_item(subitem, sizer)
259 else:
260 self.add_item(item, self.panel.Sizer)
261 self.ok.SetDefault()
262 self.ok.SetFocus()
263
264 def add_item(self, item, sizer):
265 """Add an item to the dialog's sizer.
266
267 Args:
268 item (wx.Window | tuple | str): The item to add, which can be a
269 wx.Window, a tuple of items, or a string.
270 sizer (wx.Sizer): The sizer to add the item to.
271 """
272 if isinstance(item, (HyperLinkCtrl, ThemedGenButton)):
273 item.BackgroundColour = self.panel.BackgroundColour
274 if isinstance(item, wx.Window):
275 pointsize = 10
276 font = item.GetFont()
277 if item.GetLabel() and font.GetPointSize() > pointsize:
278 font.SetPointSize(pointsize)
279 item.SetFont(font)
280 flag = wx.ALIGN_NOT
281 if isinstance(item, (wx.Panel, wx.PyPanel)):
282 flag |= wx.EXPAND
283 elif sizer is self.panel.Sizer:
284 flag |= wx.LEFT | wx.RIGHT
285 sizer.Add(item, 0, flag, 12)
286
287
288 class AnimatedBitmap(wx.PyControl):
289 """Animated bitmap."""
290
291 def __init__(
292 self,
293 parent,
294 id=wx.ID_ANY, # noqa: A002
295 bitmaps=None,
296 range_=(0, -1),
297 loop=True,
298 pos=wx.DefaultPosition,
299 size=wx.DefaultSize,
300 style=wx.NO_BORDER,
301 ):
302 """Create animated bitmap.
303
304 bitmaps should be an array of bitmaps.
305 range should be the indexes of the range of frames that should be looped.
306 -1 means last frame.
307
308 """
309 self.dpiscale = getcfg("app.dpi") / get_default_dpi()
310 if self.dpiscale > 1:
311 size = tuple(round(v * self.dpiscale) if v != -1 else v for v in size)
312 wx.PyControl.__init__(self, parent, id, pos, size, style)
313 self._minsize = size
314 self.SetBitmaps(bitmaps or [], range_, loop)
315 # Avoid flickering under Windows
316 self.Bind(wx.EVT_ERASE_BACKGROUND, lambda event: None)
317 self.Bind(wx.EVT_PAINT, self.OnPaint)
318 self._timer = BetterTimer(self)
319 self.Bind(EVT_BETTER_TIMER, self.OnTimer, self._timer)
320 self.Bind(wx.EVT_WINDOW_DESTROY, self.OnDestroy)
321
322 def OnDestroy(self, event):
323 """Handle the destruction of the control to stop the timer.
324
325 Args:
326 event (wx.WindowDestroyEvent): The event triggered when the control
327 """
328 self._timer.Stop()
329 del self._timer
330 return 0
331
332 def DoGetBestSize(self):
333 """Get the best size for the control based on the bitmaps.
334
335 Returns:
336 wx.Size: The best size for the control.
337 """
338 return self._minsize
339
340 def OnPaint(self, event):
341 """Handle the paint event to draw the current frame of the animation.
342
343 Args:
344 event (wx.PaintEvent): The paint event triggered by the animation.
345 """
346 dc = wx.BufferedPaintDC(self)
347 dc.SetBackground(wx.Brush(self.Parent.BackgroundColour))
348 dc.Clear()
349 if self._bitmaps:
350 self.frame = min(self.frame, len(self._bitmaps) - 1)
351 if self.dpiscale > 1:
352 dc.SetUserScale(self.dpiscale, self.dpiscale)
353 dc.DrawBitmap(self._bitmaps[self.frame], 0, 0, True)
354
355 def OnTimer(self, event):
356 """Handle the timer event to update the frame of the animation.
357
358 Args:
359 event (wx.TimerEvent): The timer event triggered by the animation.
360 """
361 first_frame, last_frame = self.range
362 if first_frame < 0:
363 first_frame += len(self._bitmaps)
364 if last_frame < 0:
365 last_frame += len(self._bitmaps)
366 frame = self.frame
367 if frame < last_frame:
368 frame += 1
369 elif self.loop:
370 frame = first_frame
371 if frame != self.frame:
372 self.frame = frame
373 self.Refresh()
374
375 def Play(self, fps=24):
376 """Start the animation.
377
378 Args:
379 fps (int): Frames per second.
380 """
381 self._timer.Start(int(1000.0 / fps))
382
383 def Stop(self):
384 """Stop the animation."""
385 self._timer.Stop()
386
387 def SetBitmaps(self, bitmaps, range_=(0, -1), loop=True):
388 """Set the bitmaps to be used for the animation.
389
390 Args:
391 bitmaps (list): A list of wx.Bitmap objects to be used in the
392 animation.
393 range_ (tuple): A tuple specifying the range of frames to be
394 looped. The first element is the starting index, and the second
395 is the ending index.
396 loop (bool): Whether the animation should loop when it reaches the
397 end. Default is True.
398 """
399 w, h = self._minsize
400 for bitmap in bitmaps:
401 w = max(bitmap.Size[0], w)
402 h = max(bitmap.Size[0], h)
403 self._minsize = w, h
404 self._bitmaps = bitmaps
405 self.loop = loop
406 self.range = range_
407 self.frame = 0
408
409
410 class AuiBetterTabArt(AuiDefaultTabArt):
411 """A custom tab art class for AUI tab controls, providing enhanced drawing."""
412
413 def DrawTab(self, dc, wnd, page, in_rect, close_button_state, paint_control=False):
414 """Draw a single tab.
415
416 Args:
417 dc: a :class:`DC` device context.
418 wnd: a :class:`Window` instance object.
419 page: the tab control page associated with the tab.
420 in_rect (Rect): rectangle the tab should be confined to.
421 close_button_state (int): the state of the close button on the tab.
422 paint_control (bool): whether to draw the control inside a tab (if
423 any) on a :class:`MemoryDC`.
424 """
425 # if the caption is empty, measure some temporary text
426 caption = page.caption
427 if not caption:
428 caption = "Xj"
429
430 dc.SetFont(self._selected_font)
431 if hasattr(dc, "GetFullMultiLineTextExtent"):
432 # Phoenix
433 selected_textx, selected_texty = dc.GetMultiLineTextExtent(caption)
434 else:
435 # Classic
436 selected_textx, selected_texty, dummy = dc.GetMultiLineTextExtent(caption)
437
438 dc.SetFont(self._normal_font)
439 if hasattr(dc, "GetFullMultiLineTextExtent"):
440 # Phoenix
441 normal_textx, normal_texty = dc.GetMultiLineTextExtent(caption)
442 else:
443 # Classic
444 normal_textx, normal_texty, dummy = dc.GetMultiLineTextExtent(caption)
445
446 control = page.control
447
448 # figure out the size of the tab
449 tab_size, x_extent = self.GetTabSize(
450 dc, wnd, page.caption, page.bitmap, page.active, close_button_state, control
451 )
452
453 tab_height = self._tab_ctrl_height - 3
454 tab_width = tab_size[0]
455 tab_x = in_rect.x
456 tab_y = in_rect.y + in_rect.height - tab_height
457
458 caption = page.caption
459
460 # select pen, brush and font for the tab to be drawn
461
462 if page.active:
463 dc.SetFont(self._selected_font)
464 textx, texty = selected_textx, selected_texty
465
466 else:
467 dc.SetFont(self._normal_font)
468 textx, texty = normal_textx, normal_texty
469
470 if not page.enabled:
471 dc.SetTextForeground(self._tab_disabled_text_colour)
472 pagebitmap = page.dis_bitmap
473 else:
474 dc.SetTextForeground(self._tab_text_colour(page))
475 pagebitmap = page.bitmap
476
477 # create points that will make the tab outline
478
479 clip_width = tab_width
480 if tab_x + clip_width > in_rect.x + in_rect.width:
481 clip_width = in_rect.x + in_rect.width - tab_x
482
483 # since the above code above doesn't play well with WXDFB or WXCOCOA,
484 # we'll just use a rectangle for the clipping region for now --
485 dc.SetClippingRegion(tab_x, tab_y, clip_width + 1, tab_height - 3)
486
487 border_points = [wx.Point() for i in range(6)]
488 agwFlags = self.GetAGWFlags()
489
490 if agwFlags & aui.AUI_NB_BOTTOM:
491 border_points[0] = wx.Point(tab_x, tab_y)
492 border_points[1] = wx.Point(tab_x, tab_y + tab_height - 6)
493 border_points[2] = wx.Point(tab_x + 2, tab_y + tab_height - 4)
494 border_points[3] = wx.Point(tab_x + tab_width - 2, tab_y + tab_height - 4)
495 border_points[4] = wx.Point(tab_x + tab_width, tab_y + tab_height - 6)
496 border_points[5] = wx.Point(tab_x + tab_width, tab_y)
497
498 else: # if (agwFlags & aui.AUI_NB_TOP)
499 border_points[0] = wx.Point(tab_x, tab_y + tab_height - 4)
500 border_points[1] = wx.Point(tab_x, tab_y + 2)
501 border_points[2] = wx.Point(tab_x + 2, tab_y)
502 border_points[3] = wx.Point(tab_x + tab_width - 2, tab_y)
503 border_points[4] = wx.Point(tab_x + tab_width, tab_y + 2)
504 border_points[5] = wx.Point(tab_x + tab_width, tab_y + tab_height - 4)
505
506 # TODO: else if (agwFlags & aui.AUI_NB_LEFT)
507 # TODO: else if (agwFlags & aui.AUI_NB_RIGHT)
508
509 drawn_tab_yoff = border_points[1].y
510 drawn_tab_height = border_points[0].y - border_points[1].y
511
512 if page.active:
513 # draw active tab
514
515 # draw base background colour
516 r = wx.Rect(tab_x, tab_y, tab_width, tab_height)
517 dc.SetPen(self._base_colour_pen)
518 dc.SetBrush(self._base_colour_brush)
519 dc.DrawRectangle(r.x + 1, r.y + 1, r.width - 1, r.height - 4)
520
521 # this white helps fill out the gradient at the top of the tab
522 dc.SetPen(wx.Pen(self._tab_gradient_highlight_colour))
523 dc.SetBrush(wx.Brush(self._tab_gradient_highlight_colour))
524 dc.DrawRectangle(r.x + 2, r.y + 1, r.width - 3, r.height - 4)
525
526 # these two points help the rounded corners appear more antialiased
527 dc.SetPen(self._base_colour_pen)
528 dc.DrawPoint(r.x + 2, r.y + 1)
529 dc.DrawPoint(r.x + r.width - 2, r.y + 1)
530
531 # set rectangle down a bit for gradient drawing
532 r.SetHeight(int(r.GetHeight() / 2))
533 r.x += 2
534 r.width -= 3
535 r.y += r.height
536 r.y -= 2
537
538 # draw gradient background
539 top_colour = self._tab_bottom_colour
540 bottom_colour = self._tab_top_colour
541 dc.GradientFillLinear(r, bottom_colour, top_colour, wx.NORTH)
542
543 else:
544 # draw inactive tab
545
546 r = wx.Rect(tab_x, tab_y + 1, tab_width, tab_height - 3)
547
548 # start the gradent up a bit and leave the inside border inset
549 # by a pixel for a 3D look. Only the top half of the inactive
550 # tab will have a slight gradient
551 r.x += 2
552 r.y += 1
553 r.width -= 3
554 r.height = int(r.height / 2)
555
556 # -- draw top gradient fill for glossy look
557 top_colour = self._tab_inactive_top_colour
558 bottom_colour = self._tab_inactive_bottom_colour
559 dc.GradientFillLinear(r, bottom_colour, top_colour, wx.NORTH)
560
561 r.y += r.height
562 r.y -= 1
563
564 # -- draw bottom fill for glossy look
565 top_colour = self._tab_inactive_bottom_colour
566 bottom_colour = self._tab_inactive_bottom_colour
567 dc.GradientFillLinear(r, top_colour, bottom_colour, wx.SOUTH)
568
569 # draw tab outline
570 dc.SetPen(self._border_pen)
571 dc.SetBrush(wx.TRANSPARENT_BRUSH)
572 dc.DrawPolygon(border_points)
573
574 # there are two horizontal grey lines at the bottom of the tab control,
575 # this gets rid of the top one of those lines in the tab control
576 if page.active:
577 if agwFlags & aui.AUI_NB_BOTTOM:
578 dc.SetPen(wx.Pen(self._background_bottom_colour))
579
580 # TODO: else if (agwFlags & aui.AUI_NB_LEFT)
581 # TODO: else if (agwFlags & aui.AUI_NB_RIGHT)
582 else: # for aui.AUI_NB_TOP
583 dc.SetPen(self._base_colour_pen)
584
585 dc.DrawLine(
586 border_points[0].x + 1,
587 border_points[0].y,
588 border_points[5].x,
589 border_points[5].y,
590 )
591
592 text_offset = tab_x + 8
593 close_button_width = 0
594
595 if close_button_state != aui.AUI_BUTTON_STATE_HIDDEN:
596 close_button_width = self._active_close_bmp.GetWidth()
597
598 if agwFlags & aui.AUI_NB_CLOSE_ON_TAB_LEFT:
599 text_offset += close_button_width - 5
600
601 bitmap_offset = 0
602
603 if pagebitmap.IsOk():
604 bitmap_offset = tab_x + 8
605 if agwFlags & aui.AUI_NB_CLOSE_ON_TAB_LEFT and close_button_width:
606 bitmap_offset += close_button_width - 5
607
608 # draw bitmap
609 dc.DrawBitmap(
610 pagebitmap,
611 bitmap_offset,
612 drawn_tab_yoff
613 + int(drawn_tab_height / 2)
614 - int(pagebitmap.GetHeight() / 2),
615 True,
616 )
617
618 text_offset = bitmap_offset + pagebitmap.GetWidth()
619 text_offset += 3 # bitmap padding
620
621 elif agwFlags & aui.AUI_NB_CLOSE_ON_TAB_LEFT == 0 or not close_button_width:
622 text_offset = tab_x + 8
623
624 draw_text = aui.ChopText(
625 dc, caption, tab_width - (text_offset - tab_x) - close_button_width
626 )
627
628 ypos = drawn_tab_yoff + int(drawn_tab_height / 2) - int(texty / 2) - 1
629
630 offset_focus = text_offset
631
632 if control is not None:
633 try:
634 if control.GetPosition() != wx.Point(text_offset + 1, ypos):
635 control.SetPosition(wx.Point(text_offset + 1, ypos))
636
637 if not control.IsShown():
638 control.Show()
639
640 if paint_control:
641 bmp = aui.TakeScreenShot(control.GetScreenRect())
642 dc.DrawBitmap(bmp, text_offset + 1, ypos, True)
643
644 controlW, controlH = control.GetSize()
645 text_offset += controlW + 4
646 textx += controlW + 4
647 except wx.PyDeadObjectError:
648 pass
649
650 # draw tab text
651 if hasattr(dc, "GetFullMultiLineTextExtent"):
652 # Phoenix
653 rectx, recty = dc.GetMultiLineTextExtent(draw_text)
654 else:
655 # Classic
656 rectx, recty, dummy = dc.GetMultiLineTextExtent(draw_text)
657 textfg = dc.GetTextForeground()
658 shadow = wx.SystemSettings.GetColour(wx.SYS_COLOUR_3DLIGHT)
659 dc.SetTextForeground(shadow)
660 dc.DrawLabel(draw_text, wx.Rect(text_offset + 1, ypos + 1, rectx, recty))
661 dc.SetTextForeground(textfg)
662 dc.DrawLabel(draw_text, wx.Rect(text_offset, ypos, rectx, recty))
663
664 # draw focus rectangle
665 if (agwFlags & aui.AUI_NB_NO_TAB_FOCUS) == 0:
666 self.DrawFocusRectangle(
667 dc,
668 page,
669 wnd,
670 draw_text,
671 offset_focus,
672 bitmap_offset,
673 drawn_tab_yoff,
674 drawn_tab_height,
675 rectx,
676 recty,
677 )
678
679 out_button_rect = wx.Rect()
680
681 # draw close button if necessary
682 if close_button_state != aui.AUI_BUTTON_STATE_HIDDEN:
683 bmp = self._disabled_close_bmp
684
685 if close_button_state == aui.AUI_BUTTON_STATE_HOVER:
686 bmp = self._hover_close_bmp
687 elif close_button_state == aui.AUI_BUTTON_STATE_PRESSED:
688 bmp = self._pressed_close_bmp
689
690 shift = ((agwFlags & aui.AUI_NB_BOTTOM and [1]) or [0])[0]
691
692 if agwFlags & aui.AUI_NB_CLOSE_ON_TAB_LEFT:
693 rect = wx.Rect(
694 tab_x + 4,
695 tab_y + int((tab_height - bmp.GetHeight()) / 2 - shift),
696 close_button_width,
697 tab_height,
698 )
699 else:
700 rect = wx.Rect(
701 tab_x + tab_width - close_button_width - 1,
702 tab_y + int((tab_height - bmp.GetHeight()) / 2 - shift),
703 close_button_width,
704 tab_height,
705 )
706
707 rect = aui.IndentPressedBitmap(rect, close_button_state)
708 dc.DrawBitmap(bmp, rect.x, rect.y, True)
709
710 out_button_rect = rect
711
712 out_tab_rect = wx.Rect(tab_x, tab_y, tab_width, tab_height)
713
714 dc.DestroyClippingRegion()
715
716 return out_tab_rect, out_button_rect, x_extent
717
718 def SetDefaultColours(self, base_colour=None):
719 """Set the default colours, which are calculated from the given base colour.
720
721 Args:
722 base_colour: an instance of :class:`Colour`. If defaulted to ``None``,
723 a colour is generated accordingly to the platform and theme.
724 """
725 if base_colour is None:
726 base_colour = aui.GetBaseColour()
727
728 self.SetBaseColour(base_colour)
729 self._border_colour = aui.StepColour(base_colour, 75)
730 self._border_pen = wx.Pen(self._border_colour)
731
732 self._background_top_colour = aui.StepColour(self._base_colour, 90)
733 self._background_bottom_colour = aui.StepColour(self._base_colour, 120)
734
735 self._tab_top_colour = self._base_colour
736 self._tab_bottom_colour = aui.StepColour(self._base_colour, 130)
737 self._tab_gradient_highlight_colour = aui.StepColour(self._base_colour, 130)
738
739 self._tab_inactive_top_colour = self._background_top_colour
740 self._tab_inactive_bottom_colour = aui.StepColour(self._base_colour, 110)
741
742 self._tab_text_colour = lambda page: page.text_colour
743 self._tab_disabled_text_colour = wx.SystemSettings.GetColour(
744 wx.SYS_COLOUR_GRAYTEXT
745 )
746
747
748 class AutocompleteComboBox(wx.ComboBox):
749 """A wx.ComboBox with autocomplete functionality."""
750
751 def __init__(self, *args, **kwargs):
752 wx.ComboBox.__init__(self, *args, **kwargs)
753 self.Bind(wx.EVT_TEXT, self.OnText)
754 self.Bind(wx.EVT_CHAR, self.OnChar)
755 self.Bind(wx.EVT_COMBOBOX, self.OnComboBox)
756 self._ignore_text_evt = False
757 self._popup_shown = None
758 if hasattr(wx, "EVT_COMBOBOX_DROPDOWN"):
759 self.Bind(wx.EVT_COMBOBOX_DROPDOWN, self.OnComboBoxDropDown)
760 if hasattr(wx, "EVT_COMBOBOX_CLOSEUP"):
761 self.Bind(wx.EVT_COMBOBOX_CLOSEUP, self.OnComboBoxCloseUp)
762
763 def OnComboBox(self, event):
764 """Handle the combo box selection event.
765
766 Args:
767 event (wx.CommandEvent): The command event triggered by the combo box.
768 """
769 self._ignore_text_evt = True
770 event.Skip()
771
772 def OnComboBoxDropDown(self, event):
773 """Handle the dropdown event of the combo box.
774
775 Args:
776 event (wx.CommandEvent): The dropdown event triggered by the combo box.
777 """
778 self._popup_shown = True
779 event.Skip()
780
781 def OnComboBoxCloseUp(self, event):
782 """Handle the close-up event of the combo box.
783
784 Args:
785 event (wx.CommandEvent): The close-up event triggered by the combo box.
786 """
787 self._popup_shown = False
788 event.Skip()
789
790 def OnChar(self, event):
791 """Handle character input in the combo box.
792
793 Args:
794 event (wx.KeyEvent): The key event triggered by character input.
795 """
796 if event.GetKeyCode() == 8 or event.ControlDown(): # Backspace or modifier
797 self._ignore_text_evt = True
798 event.Skip()
799
800 def OnText(self, event):
801 """Handle text input in the combo box.
802
803 Args:
804 event (wx.CommandEvent): The text change event.
805 """
806 if self._ignore_text_evt:
807 self._ignore_text_evt = False
808 return
809 current_text = event.GetString().lower()
810 found = False
811 for i, choice in enumerate(self.Items):
812 if choice.lower().startswith(current_text):
813 self._ignore_text_evt = True
814 if self._popup_shown is not None:
815 self.SetSelection(i)
816 self.SetValue(choice)
817 self.SetInsertionPoint(len(current_text))
818 self.SetMark(len(current_text), len(choice))
819 found = True
820 break
821 if not found:
822 event.Skip()
823
824
825 class BaseApp(wx.App):
826 """Application base class implementing common functionality."""
827
828 _exithandlers: ClassVar[list] = []
829 _query_end_session = None
830
831 def __init__(self, *args, **kwargs):
832 # Fix sys.prefix for SetInstallPrefix used inside wx.App which does not
833 # decode to Unicode when calling SetInstallPrefix. DisplayCAL when
834 # bundled by Py2App can't be run from a path containing Unicode
835 # characters under Mac OS X otherwise.
836 prefix = sys.prefix
837 sys.prefix = str(sys.prefix)
838
839 wx.App.__init__(self, *args, **kwargs)
840
841 # Restore prefix
842 sys.prefix = prefix
843
844 if not kwargs.get("clearSigInt", True) or (len(args) == 4 and not args[3]):
845 # Install our own SIGINT handler, so we can do cleanup on receiving
846 # SIGINT
847 print("Installing SIGINT handler")
848 signal.signal(signal.SIGINT, self.signal_handler)
849 # This timer allows processing of SIGINT / CTRL+C, because normally
850 # with clearSigInt=False, SIGINT / CTRL+C are only processed during
851 # UI events
852 self._signal_timer = wx.Timer(self)
853 self.Bind(wx.EVT_TIMER, lambda e: None, self._signal_timer)
854 self._signal_timer.Start(100)
855
856 def signal_handler(self, signum, frame):
857 """Handle signals like SIGINT (Ctrl+C).
858
859 Args:
860 signum (int): The signal number.
861 frame (frame): The current stack frame.
862 """
863 if signum == signal.SIGINT:
864 print("Received SIGINT")
865 print("Sending query to end session...")
866 self.ProcessEvent(wx.CloseEvent(wx.EVT_QUERY_END_SESSION.evtType[0]))
867
868 def OnInit(self):
869 """Initialize the application.
870
871 Returns:
872 bool: True if initialization was successful, False otherwise.
873 """
874 self.AppName = PYNAME
875 set_default_app_dpi()
876 # We use a lock so we can make sure the exit handlers are executed
877 # properly before we actually exit when receiving OS
878 # logout/reboot/shutdown events. This is needed because it is not
879 # guaranteed that when we receive EVT_QUERY_END_SESSION and close
880 # the main application window (which will normally exit the main event
881 # loop unless BaseApp.ExitOnFrameDelete is False) that OnExit (which'll
882 # execute the exit handlers) will run right away because normally it'll
883 # run after the main event loop exits (i.e. in the next iteration of the
884 # main loop after an implicit or explicit call of ExitMainLoop).
885 # Also, we need to call OnExit explicitly when receiving EVT_END_SESSION
886 # because there will be no next iteration of the event loop (the OS
887 # simply kills the application after the handler is executed). If OnExit
888 # was already called before as a result of receiving
889 # EVT_QUERY_END_SESSION and exiting the main event loop (remember this
890 # is not guaranteed because of the way the event loop works!) and did
891 # already finish, this'll do nothing and we can just exit. If OnExit is
892 # still executing the exit handlers and thus holds the lock, the lock
893 # makes sure that we wait for OnExit to finish before we explicitly call
894 # sys.exit(0) (which'll make sure exit handlers registered by atexit
895 # will run) to finally exit for good before the OS tries to kill the
896 # application.
897 self._lock = threading.Lock()
898 self.Bind(wx.EVT_QUERY_END_SESSION, self.query_end_session)
899 self.Bind(wx.EVT_END_SESSION, self.end_session)
900 if os.getenv("XDG_SESSION_TYPE") == "wayland":
901 # Fix erroneous extra spacing around window contents under
902 # Wayland. First frame will get size right, but not min size,
903 # so create a 'dummy' frame, call Show() which is needed so
904 # we can fix subsequently created windows, then instantly get
905 # rid of it. Ugly.
906 dummy = wx.Frame(None)
907 # May not be needed, but we don't want to risk actually
908 # showing our dummy frame
909 dummy.SetTransparent(0)
910 # Need to call Show() to 'fix' subsequently created windows
911 dummy.Show()
912 # Now we can get rid of it
913 dummy.Close()
914 return True
915
916 def MacOpenFiles(self, paths):
917 """Handle opening files on macOS.
918
919 This method is called when files are opened via the application icon
920 or by dragging files onto the application icon in the dock or taskbar.
921
922 Args:
923 paths (list): List of file paths to open.
924 """
925 if self.TopWindow and isinstance(
926 getattr(self.TopWindow, "droptarget", None), FileDrop
927 ):
928 self.TopWindow.droptarget.OnDropFiles(0, 0, paths)
929
930 def MacReopenApp(self):
931 """Reopen the application on macOS.
932
933 This method is called when the application is reopened after being
934 closed, typically by the user clicking on the application icon in the
935 dock or taskbar.
936 """
937 if self.TopWindow and self.TopWindow.IsShownOnScreen():
938 self.TopWindow.Raise()
939
940 def process_argv(self, count=0):
941 """Process command line arguments to open files.
942
943 Args:
944 count (int): Number of files to open. If 0, all files are opened.
945
946 Returns:
947 list: List of file paths opened by the application.
948 """
949 paths = []
950 for arg in sys.argv[1:]:
951 if os.path.isfile(arg):
952 paths.append(str(arg))
953 if len(paths) == count:
954 break
955 if paths:
956 self.MacOpenFiles(paths)
957 return paths
958 return None
959
960 def OnExit(self):
961 """Handle application exit.
962
963 Returns:
964 int: Return code for the application exit. Defaults to 0.
965 """
966 print("Executing BaseApp.OnExit()")
967 with self._lock:
968 if BaseApp._exithandlers:
969 print("Running application exit handlers")
970 BaseApp._run_exitfuncs()
971 if hasattr(wx.App, "OnExit"):
972 result = wx.App.OnExit(self)
973 return result if result is not None else 0
974 return 0
975
976 @staticmethod
977 def _run_exitfuncs() -> int:
978 """Run any registered exit functions.
979
980 _exithandlers is traversed in reverse order so functions are executed
981 last in, first out.
982 """
983 # Inspired by python's 'atexit' module.
984 # It's important that the exit handlers run *before* the actual main
985 # loop exits, otherwise they might not run at all if the app is closed
986 # externally (e.g. if the OS asks the app to close on logout).
987 # Using the 'atexit' module will NOT work!
988
989 exc_info = None
990 while BaseApp._exithandlers:
991 func, args, kwargs = BaseApp._exithandlers.pop()
992 try:
993 func(*args, **kwargs)
994 except SystemExit:
995 exc_info = sys.exc_info()
996 except Exception:
997 import traceback
998
999 print("Error in BaseApp._run_exitfuncs:")
1000 print(traceback.format_exc())
1001
1002 if exc_info is not None:
1003 raise exc_info[0](exc_info[1]).with_traceback(exc_info[2])
1004
1005 return 0
1006
1007 @staticmethod
1008 def register_exitfunc(func, *args, **kwargs) -> None:
1009 """Register a function to be called on application exit.
1010
1011 Args:
1012 func (callable): The function to register.
1013 *args: Positional arguments to pass to the function.
1014 **kwargs: Keyword arguments to pass to the function.
1015 """
1016 BaseApp._exithandlers.append((func, args, kwargs))
1017
1018 def query_end_session(self, event):
1019 """Handle the query end session event.
1020
1021 Args:
1022 event (wx.Event): The query end session event.
1023 """
1024 print("Received query to end session")
1025 if event.CanVeto():
1026 print("Can veto")
1027 else:
1028 print("Cannot veto")
1029 if self.TopWindow and self.TopWindow is not self._query_end_session:
1030 if not isinstance(self.TopWindow, wx.Dialog):
1031 print("Trying to close main top-level application window...")
1032 if self.TopWindow.Close(force=not event.CanVeto()):
1033 if self.TopWindow is not None:
1034 self.TopWindow.listening = False
1035 self._query_end_session = self.TopWindow
1036 print("Main top-level application window processed close event")
1037 return
1038 print("Failed to close main top-level application window")
1039 if event.CanVeto():
1040 event.Veto()
1041 print("Vetoed query to end session")
1042
1043 def end_session(self, event):
1044 """Handle the end session event.
1045
1046 Args:
1047 event (wx.Event): The end session event.
1048 """
1049 print("Ending session")
1050 self.ExitMainLoop()
1051 # We may need to call OnExit() explicitly because there is not
1052 # guaranteed to be a next iteration of the main event loop
1053 with contextlib.suppress(Exception):
1054 # Yes, this can fail with a TypeError, amazingly enough :-(
1055 # Apparently sometimes, wx already shuts down the application
1056 # and OnExit will be None. We assume in this case that OnExit
1057 # already ran.
1058 self.OnExit()
1059 # Calling sys.exit makes sure that exit handlers registered by atexit
1060 # will run
1061 print("Calling sys.exit(0)")
1062 sys.exit(0)
1063
1064
1065 active_window = None
1066 responseformats = {}
1067
1068
1069 class BaseFrame(wx.Frame):
1070 """Main frame base class."""
1071
1072 def __init__(self, *args, **kwargs):
1073 wx.Frame.__init__(self, *args, **kwargs)
1074 self.init()
1075
1076 def FindWindowByName(self, name):
1077 """Find a child window by its name.
1078
1079 WxPython Phoenix FindWindowByName descends into the parent windows,
1080 we don't want that.
1081
1082 Args:
1083 name (str): The name of the child window to find.
1084
1085 Returns:
1086 wx.Window: The child window with the specified name, or None if not
1087 found.
1088 """
1089 for child in list(self.GetAllChildren()):
1090 if hasattr(child, "Name") and child.Name == name:
1091 return child
1092 return None
1093
1094 def __OnDestroy(self, event):
1095 """Handle the destruction of the main frame.
1096
1097 Args:
1098 event (wx.Event): The window destroy event.
1099 """
1100 if event.GetEventObject() is self:
1101 self.listening = False
1102 event.Skip()
1103 return 0
1104
1105 def close_all(self):
1106 """Close all dialogs and frames."""
1107 windows = list(wx.GetTopLevelWindows())
1108 while windows:
1109 win = windows.pop()
1110 if (
1111 isinstance(win, (AboutDialog, BaseInteractiveDialog, ProgressDialog))
1112 or win.__class__ is wx.Dialog
1113 ) and win.IsShown():
1114 if win.IsModal():
1115 wx.CallAfter(win.EndModal, wx.ID_CANCEL)
1116 print("Closed modal dialog", win)
1117 else:
1118 wx.CallAfter(win.Close)
1119 print("Closed dialog", win)
1120 elif isinstance(win, wx.Frame):
1121 wx.CallAfter(win.Close)
1122 print("Closed", win)
1123
1124 def init(self):
1125 """Initialize the main frame."""
1126 self.Bind(wx.EVT_ACTIVATE, self.activate_handler)
1127 self.Bind(wx.EVT_WINDOW_DESTROY, self.__OnDestroy)
1128
1129 def init_menubar(self):
1130 """Initialize the menu bar for the main frame."""
1131 self.MenuBar = wx.MenuBar()
1132 filemenu = wx.Menu()
1133 quit_action = filemenu.Append(
1134 -1 if wx.VERSION < (2, 9) else wx.ID_EXIT,
1135 "&{}\tCtrl+Q".format(lang.getstr("menuitem.quit")),
1136 )
1137 self.Bind(wx.EVT_MENU, lambda event: self.Close(), quit_action)
1138 if sys.platform != "darwin":
1139 self.MenuBar.Append(filemenu, "&{}".format(lang.getstr("menu.file")))
1140
1141 def activate_handler(self, event):
1142 """Handle activation events for the main frame.
1143
1144 Args:
1145 event (wx.Event): The activation event.
1146 """
1147 global active_window
1148 active_window = self
1149
1150 def listen(self):
1151 """Listen for incoming connections on the scripting socket."""
1152 if not isinstance(getattr(sys, "_appsocket", None), socket.socket):
1153 return
1154
1155 addr, port = sys._appsocket.getsockname()
1156 if addr == "0.0.0.0": # noqa: S104
1157 with contextlib.suppress(OSError):
1158 addr = get_network_addr()
1159 print(lang.getstr("app.listening", (addr, port)))
1160 self.listening = True
1161 self.listener = threading.Thread(
1162 target=self.connection_handler, name="ScriptingHost.ConnectionHandler"
1163 )
1164 self.listener.start()
1165
1166 def connect(self, ip, port):
1167 """Connect to a scripting client socket.
1168
1169 Args:
1170 ip (str): The IP address to connect to.
1171 port (int): The port to connect to.
1172
1173 Returns:
1174 socket.socket: The connected socket object.
1175 OSError: If the connection fails, an OSError is returned.
1176 """
1177 if getattr(self, "conn", None):
1178 self.conn.disconnect()
1179 conn = ScriptingClientSocket()
1180 conn.settimeout(3)
1181 try:
1182 conn.connect((ip, port))
1183 except OSError as exception:
1184 del conn
1185 return exception
1186 return conn # noqa: F821
1187
1188 def connection_handler(self):
1189 """Handle socket connections."""
1190 self._msghandlercount = 0
1191 while self and getattr(self, "listening", False):
1192 try:
1193 # Wait for connection
1194 conn, addrport = sys._appsocket.accept()
1195 except socket.timeout:
1196 continue
1197 except OSError as exception:
1198 if exception.errno == errno.EWOULDBLOCK:
1199 sleep(0.05)
1200 continue
1201 break
1202 if addrport[0] != "127.0.0.1" and not getcfg("app.allow_network_clients"):
1203 # Network client disallowed
1204 conn.close()
1205 print(lang.getstr("app.client.network.disallowed", addrport))
1206 sleep(0.2)
1207 continue
1208 try:
1209 conn.settimeout(0.2)
1210 except OSError as exception:
1211 conn.close()
1212 print(lang.getstr("app.client.ignored", exception))
1213 sleep(0.2)
1214 continue
1215 print(lang.getstr("app.client.connect", addrport))
1216 self._msghandlercount += 1
1217 threading.Thread(
1218 target=self.message_handler,
1219 name=f"ScriptingHost.MessageHandler-{self._msghandlercount}",
1220 args=(conn, addrport),
1221 ).start()
1222 sys._appsocket.close()
1223
1224 def message_handler(self, conn, addrport):
1225 """Handle messages sent via socket.
1226
1227 Args:
1228 conn (socket.socket): The socket connection to handle.
1229 addrport (tuple): A tuple containing the address and port of the
1230 connected client, e.g. ('127.0.0.1', 1234).
1231 """
1232 responseformats[conn] = "plain"
1233 buffer = ""
1234 while self and getattr(self, "listening", False):
1235 # Wait for incoming message
1236 try:
1237 incoming = conn.recv(4096)
1238 if isinstance(incoming, bytes):
1239 incoming = incoming.decode("utf-8")
1240 except socket.timeout:
1241 continue
1242 except OSError as exception:
1243 if exception.errno == errno.EWOULDBLOCK:
1244 sleep(0.05)
1245 continue
1246 break
1247 else:
1248 if not incoming:
1249 break
1250 buffer += incoming
1251 while "\n" in buffer and self and getattr(self, "listening", False):
1252 end = buffer.find("\n")
1253 line = buffer[:end].strip()
1254 buffer = buffer[end + 1 :]
1255 if line:
1256 command_timestamp = datetime.now().strftime(
1257 "%Y-%m-%dTH:%M:%S.%f"
1258 )
1259 line = str(line)
1260 print(lang.getstr("app.incoming_message", (*addrport, line)))
1261 data = split_command_line(line)
1262 response = None
1263 # Non-UI commands
1264 if data[0] == "getappname" and len(data) == 1:
1265 response = PYNAME
1266 elif data[0] == "getcfg" and len(data) < 3:
1267 if len(data) == 2:
1268 # Return cfg value
1269 if data[1] in DEFAULTS:
1270 if responseformats[conn].startswith("xml"):
1271 response = {
1272 "name": data[1],
1273 "value": getcfg(data[1]),
1274 }
1275 else:
1276 response = {data[1]: getcfg(data[1])}
1277 else:
1278 response = "invalid"
1279 else:
1280 # Return whole cfg
1281 if responseformats[conn] != "plain":
1282 response = []
1283 else:
1284 response = {}
1285 for name in sorted(DEFAULTS):
1286 value = getcfg(name, False)
1287 if value is not None:
1288 if responseformats[conn] != "plain":
1289 response.append(
1290 {"name": name, "value": value}
1291 )
1292 else:
1293 response[name] = value
1294 elif data[0] == "getcommands" and len(data) == 1:
1295 response = sorted(self.get_commands())
1296 elif data[0] == "getdefault" and len(data) == 2:
1297 if data[1] in DEFAULTS:
1298 if responseformats[conn] != "plain":
1299 response = {
1300 "name": data[1],
1301 "value": DEFAULTS[data[1]],
1302 }
1303 else:
1304 response = {data[1]: DEFAULTS[data[1]]}
1305 else:
1306 response = "invalid"
1307 elif data[0] == "getdefaults" and len(data) == 1:
1308 response = [] if responseformats[conn] != "plain" else {}
1309 for name in sorted(DEFAULTS):
1310 if responseformats[conn] != "plain":
1311 response.append(
1312 {"name": name, "value": DEFAULTS[name]}
1313 )
1314 else:
1315 response[name] = DEFAULTS[name]
1316 elif data[0] == "getvalid" and len(data) == 1:
1317 if responseformats[conn] != "plain":
1318 response = {}
1319 for section, options in (
1320 ("ranges", config.VALID_RANGES),
1321 ("values", config.VALID_VALUES),
1322 ):
1323 valid = response[section] = []
1324 for name in options:
1325 values = options[name]
1326 valid.append({"name": name, "values": values})
1327 else:
1328 response = {
1329 "ranges": config.VALID_RANGES,
1330 "values": config.VALID_VALUES,
1331 }
1332 if responseformats[conn] == "plain":
1333 valid = []
1334 for section in response:
1335 options = response[section]
1336 valid.append(f"[{section}]")
1337 for name in options:
1338 values = options[name]
1339 valid.append(
1340 "{} = {}".format(
1341 name,
1342 " ".join(
1343 demjson.encode(value)
1344 for value in values
1345 ),
1346 )
1347 )
1348 response = valid
1349 elif (
1350 data[0] == "setresponseformat"
1351 and len(data) == 2
1352 and data[1]
1353 in ("json", "json.pretty", "plain", "xml", "xml.pretty")
1354 ):
1355 responseformats[conn] = data[1]
1356 response = "ok"
1357 if response is not None:
1358 self.send_response(response, data, conn, command_timestamp)
1359 continue
1360 # UI commands
1361 wx.CallAfter(
1362 self.finish_processing, data, conn, command_timestamp
1363 )
1364 try:
1365 conn.shutdown(socket.SHUT_RDWR)
1366 except OSError as exception:
1367 if exception.errno != errno.ENOTCONN:
1368 print("Warning - could not shutdown connection:", exception)
1369 print(lang.getstr("app.client.disconnect", addrport))
1370 conn.close()
1371 responseformats.pop(conn)
1372
1373 def get_app_state(self, file_format):
1374 """Get the current application state.
1375
1376 Args:
1377 file_format (str): The format in which to return the state. Can be
1378 "plain", "json", "json.pretty", "xml", or "xml.pretty".
1379
1380 Returns:
1381 dict or str: The application state in the specified format.
1382 """
1383 win = self.get_top_window()
1384 if isinstance(win, wx.Dialog) and win.IsShown():
1385 if isinstance(win, (DirDialog, FileDialog)):
1386 response = format_ui_element(win, file_format)
1387 if file_format != "plain":
1388 response.update({"message": win.Message, "path": win.Path})
1389 else:
1390 response = [
1391 response,
1392 demjson.encode(win.Message),
1393 "path",
1394 demjson.encode(win.Path),
1395 ]
1396 elif isinstance(win, (AboutDialog, BaseInteractiveDialog, ProgressDialog)):
1397 response = format_ui_element(win, file_format)
1398 if file_format == "plain":
1399 response = [response]
1400 if hasattr(win, "message") and win.message:
1401 if file_format != "plain":
1402 response["message"] = win.message.Label
1403 else:
1404 response.append(demjson.encode(win.message.Label))
1405 # Ordering in tab order
1406 for child in list(win.GetAllChildren()):
1407 if (
1408 child
1409 and isinstance(child, (FlatShadedButton, GenButton, wx.Button))
1410 and child.TopLevelParent is win
1411 and child.IsShownOnScreen()
1412 and child.IsEnabled()
1413 ):
1414 if file_format != "plain":
1415 if "buttons" not in response:
1416 response["buttons"] = []
1417 response["buttons"].append(child.Label)
1418 else:
1419 if "buttons" not in response:
1420 response.append("buttons")
1421 response.append(demjson.encode(child.Label))
1422 elif win.__class__ is wx.Dialog:
1423 response = format_ui_element(win, file_format)
1424 if file_format == "plain":
1425 response = [response]
1426 else:
1427 return "blocked"
1428 if file_format == "plain":
1429 response = " ".join(response)
1430 return response
1431 if hasattr(self, "worker") and self.worker.is_working():
1432 return "busy"
1433 return "idle"
1434
1435 def get_commands(self):
1436 """Get a list of commands that can be used in the scripting interface.
1437
1438 Returns:
1439 list: A list of strings containing the commands.
1440 """
1441 return self.get_common_commands()
1442
1443 def get_common_commands(self):
1444 """Get a list of common commands that can be used in the scripting interface.
1445
1446 Returns:
1447 list: A list of strings containing the common commands.
1448 """
1449 cmds = [
1450 "abort",
1451 "activate [window]",
1452 "alt",
1453 "cancel",
1454 "ok [filename]",
1455 "close [window]",
1456 "echo <string>",
1457 "exit [force]",
1458 "getactivewindow",
1459 "getappname",
1460 "getcellvalues [window] <grid>",
1461 "getcommands",
1462 "getcfg [option]",
1463 "getdefault <option>",
1464 "getdefaults",
1465 "getmenus",
1466 "getmenuitems [menu]",
1467 "getstate",
1468 "getuielement [window] <element>",
1469 "getuielements [window]",
1470 "getvalid",
1471 "getwindows",
1472 "interact [window] <element> [setvalue value]",
1473 "invokemenu <menu> <menuitem>",
1474 "restore-defaults [category...]",
1475 "setcfg <option> <value>",
1476 "setresponseformat <format>",
1477 ]
1478 if hasattr(self, "update_controls"):
1479 cmds.append("refresh")
1480 if hasattr(self, "panel"):
1481 cmds.append("setlanguage <languagecode>")
1482 return cmds
1483
1484 def get_scripting_hosts(self):
1485 """Get a list of currently running scripting hosts.
1486
1487 Returns:
1488 list: A list of strings containing the IP address and port of each
1489 scripting host, along with the lock file basename.
1490 """
1491 scripting_hosts = []
1492 modules = [
1493 "3DLUT-maker",
1494 "curve-viewer",
1495 "profile-info",
1496 "scripting-client",
1497 "synthprofile",
1498 "testchart-editor",
1499 "VRML-to-X3D-converter",
1500 "apply-profiles",
1501 ]
1502 lock_file_basenames = [APPBASENAME]
1503 lock_file_basenames.extend(f"{APPBASENAME}-{module}" for module in modules)
1504 for lock_file_basename in lock_file_basenames:
1505 lockfilename = os.path.join(CONFIG_HOME, f"{lock_file_basename}.lock")
1506 if not os.path.isfile(lockfilename):
1507 continue
1508 ports = []
1509 try:
1510 with open(lockfilename) as lockfile:
1511 for line in lockfile.read().splitlines():
1512 if line:
1513 if ":" in line:
1514 pid, port = line.split(":", 1)
1515 else:
1516 port = line
1517 if port:
1518 ports.append(port)
1519 except OSError as exception:
1520 # This shouldn't happen
1521 print(
1522 f"Warning - could not read lockfile {lockfilename}:",
1523 exception,
1524 )
1525 else:
1526 scripting_hosts.extend(
1527 f"127.0.0.1:{port} {lock_file_basename}" for port in ports
1528 )
1529 scripting_hosts.sort()
1530 return scripting_hosts
1531
1532 def get_top_window(self):
1533 """Get the topmost window that is currently shown.
1534
1535 Returns:
1536 wx.Window: The topmost window that is currently shown, or self if no
1537 such window exists.
1538 """
1539 windows = [active_window or self, *list(wx.GetTopLevelWindows())]
1540 while windows:
1541 win = windows.pop()
1542 if win and isinstance(win, wx.Dialog) and win.IsShown():
1543 break
1544 return (win and win.IsShown() and win) or self
1545
1546 def global_navigate(self):
1547 """Navigate to the next focusable control in the application."""
1548 # We have wx.Window.Navigate, but it only works for siblings in the
1549 # same parent frame. Re-implement our own version.
1550 focus = self.FindFocus()
1551 if not focus:
1552 return False
1553 children = list(self.GetAllChildren())
1554 if focus not in children:
1555 return False
1556 start = i = children.index(focus)
1557 while True:
1558 if wx.GetKeyState(wx.WXK_SHIFT):
1559 i -= 1
1560 else:
1561 i += 1
1562 if i < 0:
1563 i = len(children) - 1
1564 elif i > len(children) - 1:
1565 i = 0
1566 if i == start:
1567 return False
1568 focus = children[i]
1569 if (
1570 focus
1571 and isinstance(focus, (wx.Control, wx.grid.Grid))
1572 and focus.AcceptsFocus()
1573 and not focus.HasFocus()
1574 ):
1575 focus.SetFocus()
1576 return True
1577 return False
1578
1579 def process_data(self, data):
1580 """Override this method in derived classes.
1581
1582 Args:
1583 data (list): The command data to process.
1584
1585 Returns:
1586 str: The response to the command.
1587 """
1588 return "invalid"
1589
1590 def finish_processing(self, data, conn, command_timestamp):
1591 """Finish processing a command.
1592
1593 Send a response back to the client connection.
1594
1595 Args:
1596 data (list): The command data to process.
1597 conn (socket.socket): The connection to send the response to.
1598 command_timestamp (str): The timestamp of the command.
1599 """
1600 if not responseformats.get(conn):
1601 # Client connection has broken down in the meantime
1602 return
1603 state = self.get_app_state("plain")
1604 dialog = isinstance(self.get_top_window(), wx.Dialog)
1605 if data[0] == "setcfg" and len(data) == 4 and data[-1] == "force":
1606 force_setcfg = data.pop()
1607 else:
1608 force_setcfg = False
1609 if (
1610 (state in ("blocked", "busy") or dialog)
1611 and data[0]
1612 not in (
1613 "abort",
1614 "activate",
1615 "alt",
1616 "cancel",
1617 "close",
1618 "exit",
1619 "getactivewindow",
1620 "getcellvalues",
1621 "getmenus",
1622 "getmenuitems",
1623 "getstate",
1624 "getuielement",
1625 "getuielements",
1626 "getwindows",
1627 "interact",
1628 "ok",
1629 )
1630 and not force_setcfg
1631 ):
1632 if dialog:
1633 state = "blocked"
1634 self.send_response(state, data, conn, command_timestamp)
1635 return
1636 win = None
1637 child = None
1638 response = "ok"
1639 if data[0] in ("abort", "close", "exit"):
1640 if (
1641 hasattr(self, "worker")
1642 and not self.worker.abort_all()
1643 and self.worker.is_working()
1644 ):
1645 response = "failed"
1646 elif data[0] in ("close", "exit"):
1647 if len(data) == 2:
1648 win = None if data[0] == "exit" else get_toplevel_window(data[1])
1649 else:
1650 win = self.get_top_window()
1651 if win:
1652 state = self.get_app_state("plain")
1653 if state == "blocked" or (state != "idle" and data[0] == "exit"):
1654 response = state
1655 elif (
1656 state not in ("busy", "idle")
1657 and win is not self.get_top_window()
1658 ):
1659 response = "blocked"
1660 elif (
1661 isinstance(
1662 win, (AboutDialog, BaseInteractiveDialog, ProgressDialog)
1663 )
1664 or win.__class__ is wx.Dialog
1665 ):
1666 if win.IsModal():
1667 wx.CallAfter(win.EndModal, wx.ID_CANCEL)
1668 else:
1669 wx.CallAfter(win.Close)
1670 elif isinstance(win, wx.Frame):
1671 wx.CallAfter(win.Close)
1672 else:
1673 response = "failed"
1674 elif data[0] == "exit" and len(data) == 2:
1675 wx.CallAfter(self.close_all)
1676 else:
1677 response = "invalid"
1678 else:
1679 response = "invalid"
1680 elif data[0] == "activate" and len(data) < 3:
1681 response = "ok"
1682 if len(data) < 2:
1683 win = self.get_top_window()
1684 else:
1685 try:
1686 id_name_label = int(data[1])
1687 except ValueError:
1688 id_name_label = data[1]
1689 for win in reversed(list(wx.GetTopLevelWindows())):
1690 if id_name_label in (win.Id, win.Name, win.Label) and win.IsShown():
1691 break
1692 else:
1693 win = None
1694 if win and win.IsShown():
1695 if win.IsIconized():
1696 win.Restore()
1697 win.Raise()
1698 else:
1699 response = "invalid"
1700 elif data[0] in ("alt", "cancel", "ok") and (
1701 len(data) == 1 or (data[0] == "ok" and len(data) == 2)
1702 ):
1703 response = "invalid"
1704 win = self.get_top_window()
1705 if isinstance(win, (DirDialog, FileDialog)):
1706 if data[0] in ("ok", "cancel"):
1707 if len(data) > 1:
1708 # Path
1709 win.SetPath(data[1])
1710 if win.IsModal():
1711 wx.CallAfter(
1712 win.EndModal,
1713 {"ok": wx.ID_OK, "cancel": wx.ID_CANCEL}[data[0]],
1714 )
1715 elif data[0] == "cancel":
1716 wx.CallAfter(win.Close)
1717 response = "ok"
1718 elif isinstance(
1719 win, (AboutDialog, BaseInteractiveDialog, ProgressDialog)
1720 ) and hasattr(win, data[0]):
1721 ctrl = getattr(win, data[0])
1722 if ctrl.IsEnabled():
1723 if win.IsModal():
1724 wx.CallAfter(win.EndModal, ctrl.Id)
1725 elif isinstance(ctrl, (FlatShadedButton, GenButton, wx.Button)):
1726 event = wx.CommandEvent(wx.EVT_BUTTON.typeId, ctrl.Id)
1727 event.SetEventObject(ctrl)
1728 wx.CallAfter(ctrl.ProcessEvent, event)
1729 response = "ok"
1730 else:
1731 response = "forbidden"
1732 elif (
1733 data[0] == "echo"
1734 and "echo <string>" in self.get_common_commands()
1735 and len(data) > 1
1736 ):
1737 txt = " ".join(data[1:])
1738 print(txt)
1739 elif data[0] == "invokemenu" and len(data) == 3:
1740 if self.get_app_state("plain") == "idle":
1741 menubar = self.GetMenuBar()
1742 response = "invalid"
1743 else:
1744 menubar = None
1745 response = "forbidden"
1746 if menubar:
1747 try:
1748 menu_pos = int(data[1])
1749 except ValueError:
1750 menu_pos = menubar.FindMenu(data[1])
1751 if (
1752 menu_pos not in (wx.NOT_FOUND, None)
1753 and -1 < menu_pos < menubar.GetMenuCount()
1754 and menubar.IsEnabledTop(menu_pos)
1755 ):
1756 menu = menubar.GetMenu(menu_pos)
1757 try:
1758 menuitem_id = int(data[2])
1759 except ValueError:
1760 menuitem_id = menu.FindItem(data[2])
1761 if menuitem_id not in (wx.NOT_FOUND, None):
1762 menuitem = menu.FindItemById(menuitem_id)
1763 if menuitem.IsEnabled():
1764 event = wx.CommandEvent(wx.EVT_MENU.typeId, menuitem_id)
1765 event.SetEventObject(menu)
1766 wx.CallAfter(self.ProcessEvent, event)
1767 response = "ok"
1768 else:
1769 response = "forbidden"
1770 elif data[0] == "getactivewindow" and len(data) == 1:
1771 win = self.get_top_window()
1772 response = format_ui_element(win, responseformats[conn])
1773 win = None
1774 elif data[0] == "getcellvalues" and len(data) in (2, 3):
1775 response = "invalid"
1776 if len(data) == 3:
1777 win = get_toplevel_window(data[1])
1778 else:
1779 win = self.get_top_window()
1780 if win:
1781 name = data[-1]
1782 child = get_widget(win, name)
1783 if (
1784 child
1785 and isinstance(child, wx.grid.Grid)
1786 and child.IsShownOnScreen()
1787 ):
1788 response = []
1789 for row in range(child.GetNumberRows()):
1790 values = [
1791 child.GetCellValue(row, col)
1792 for col in range(child.GetNumberCols())
1793 ]
1794 if responseformats[conn] == "plain":
1795 values = (
1796 demjson.encode(values).strip("[]").replace('","', '" "')
1797 )
1798 response.append(values)
1799 elif child is False:
1800 response = "forbidden"
1801 child = None
1802 elif data[0] == "getmenus" and len(data) == 1:
1803 menus = []
1804 menubar = self.GetMenuBar()
1805 if menubar:
1806 for i, (_menu, label) in enumerate(menubar.GetMenus()):
1807 label = label.lstrip("&_")
1808 if responseformats[conn] != "plain":
1809 menus.append(
1810 {
1811 "label": label,
1812 "position": i,
1813 "enabled": menubar.IsEnabledTop(i),
1814 }
1815 )
1816 else:
1817 menus.append(
1818 "{} {} {}".format(
1819 i,
1820 demjson.encode(label),
1821 "enabled" if menubar.IsEnabledTop(i) else "disabled",
1822 )
1823 )
1824 response = menus
1825 elif data[0] == "getmenuitems" and len(data) < 3:
1826 menuitems = []
1827 menulabels = []
1828 menus = []
1829 menubar = self.GetMenuBar()
1830 if menubar:
1831 if len(data) == 2:
1832 try:
1833 menu_pos_label = int(data[1])
1834 except ValueError:
1835 menu_pos_label = data[1]
1836 for i, (menu, label) in enumerate(menubar.GetMenus()):
1837 label = label.lstrip("&_")
1838 if len(data) == 2 and menu_pos_label not in (label, i):
1839 continue
1840 if responseformats[conn] != "plain" and label not in menulabels:
1841 menuitems = []
1842 menulabels.append(label)
1843 menus.append(
1844 {
1845 "label": label,
1846 "position": i,
1847 "enabled": menubar.IsEnabledTop(i),
1848 "menuitems": menuitems,
1849 }
1850 )
1851 for menuitem in menu.GetMenuItems():
1852 if menuitem.IsSeparator():
1853 continue
1854 if responseformats[conn] != "plain":
1855 menuitems.append(
1856 {
1857 "label": menuitem.Label,
1858 "id": menuitem.Id,
1859 "enabled": menubar.IsEnabledTop(i)
1860 and menuitem.IsEnabled(),
1861 "checkable": menuitem.IsCheckable(),
1862 "checked": menuitem.IsChecked(),
1863 }
1864 )
1865 else:
1866 menuitems.append(
1867 "{} {} {} {} {}{}{}".format(
1868 i,
1869 demjson.encode(label),
1870 menuitem.Id,
1871 demjson.encode(menuitem.Label),
1872 (
1873 "enabled"
1874 if menubar.IsEnabledTop(i)
1875 and menuitem.IsEnabled()
1876 else "disabled"
1877 ),
1878 " checkable" if menuitem.IsCheckable() else "",
1879 " checked" if menuitem.IsChecked() else "",
1880 )
1881 )
1882 response = menus if responseformats[conn] != "plain" else menuitems
1883 elif data[0] == "getstate" and len(data) == 1:
1884 response = self.get_app_state(responseformats[conn])
1885 elif data[0] == "getuielement" and len(data) in (2, 3):
1886 response = "invalid"
1887 if len(data) == 3:
1888 win = get_toplevel_window(data[1])
1889 else:
1890 win = self.get_top_window()
1891 if win:
1892 name = data[-1]
1893 child = get_widget(win, name)
1894 if child and child.IsShownOnScreen():
1895 response = format_ui_element(child, responseformats[conn])
1896 elif child is False:
1897 response = "forbidden"
1898 child = None
1899 elif data[0] == "getuielements" and len(data) < 3:
1900 uielements = []
1901 if len(data) == 2:
1902 win = get_toplevel_window(data[1])
1903 else:
1904 win = self.get_top_window()
1905 if win:
1906 # Ordering in tab order
1907 uielements.extend(
1908 format_ui_element(child, responseformats[conn])
1909 for child in list(win.GetAllChildren())
1910 if is_scripting_allowed(win, child)
1911 )
1912 child = None
1913 response = uielements
1914 else:
1915 response = "invalid"
1916 elif data[0] == "getwindows" and len(data) == 1:
1917 windows = [win for win in list(wx.GetTopLevelWindows()) if win.IsShown()]
1918 response = [
1919 format_ui_element(win, responseformats[conn]) for win in windows
1920 ]
1921 win = None
1922 elif data[0] == "interact" and 1 < len(data) < 6:
1923 response = "invalid"
1924 value = None
1925 args = data[1:]
1926 if len(args) > 2 and args[-2] == "setvalue":
1927 value = args.pop()
1928 args.pop()
1929 name = args.pop()
1930 state = self.get_app_state("plain")
1931 if state == "blocked":
1932 win = None
1933 response = state
1934 elif args:
1935 # Window name specified
1936 win = get_toplevel_window(args[0])
1937 if state not in ("busy", "idle") and win is not self.get_top_window():
1938 win = None
1939 response = "blocked"
1940 else:
1941 win = self.get_top_window()
1942 if win:
1943 child = get_widget(win, name)
1944 if child is False or (
1945 child and (not child.IsShownOnScreen() or not child.IsEnabled())
1946 ):
1947 response = "forbidden"
1948 elif child:
1949 event = None
1950 if value is not None:
1951 # Set value
1952 values = value.split(",", 2)
1953 if isinstance(child, floatspin.FloatSpin):
1954 try:
1955 child.SetValue(float(value))
1956 except Exception:
1957 response = "failed"
1958 else:
1959 event = floatspin.EVT_FLOATSPIN
1960 elif isinstance(
1961 child, (CustomCheckBox, wx.CheckBox)
1962 ) and value in ("0", "1", "false", "true"):
1963 child.SetValue(bool(demjson.decode(value)))
1964 event = wx.EVT_CHECKBOX
1965 elif isinstance(child, wx.ComboBox):
1966 child.SetValue(value)
1967 event = wx.EVT_TEXT
1968 elif isinstance(child, wx.Choice):
1969 # NOTE: Check for wx.ComboBox first because it is a
1970 # subclass of wx.Choice!
1971 if value in child.Items:
1972 child.SetStringSelection(value)
1973 event = wx.EVT_CHOICE
1974 elif isinstance(
1975 child,
1976 (aui.AuiNotebook, labelbook.FlatBookBase, wx.Notebook),
1977 ):
1978 for page_idx in range(child.GetPageCount()):
1979 if child.GetPageText(page_idx) == value:
1980 child.SetSelection(page_idx)
1981 event = wx.EVT_NOTEBOOK_PAGE_CHANGED
1982 break
1983 elif isinstance(child, wx.grid.Grid) and len(values) == 3:
1984 try:
1985 row, col = (int(v) for v in values[:2])
1986 except ValueError:
1987 row, col = -1, -1
1988 if (
1989 -1 < row < child.GetNumberRows()
1990 and -1 < col < child.GetNumberCols()
1991 ):
1992 if child.IsEditable() and not child.IsReadOnly(
1993 row, col
1994 ):
1995 child.SetCellValue(row, col, values[2])
1996 event = wx.grid.GridEvent(
1997 -1,
1998 wx.grid.EVT_GRID_CELL_CHANGE.evtType[0],
1999 child,
2000 row,
2001 col,
2002 )
2003 else:
2004 response = "forbidden"
2005 elif isinstance(child, wx.ListCtrl):
2006 for row in range(child.GetItemCount()):
2007 item = [
2008 child.GetItem(row, col).GetText()
2009 for col in range(child.GetColumnCount())
2010 ]
2011 if " ".join(item) == value:
2012 state = child.GetItemState(
2013 row, wx.LIST_STATE_SELECTED
2014 )
2015 child.Select(
2016 row, not state & wx.LIST_STATE_SELECTED
2017 )
2018 if state & wx.LIST_STATE_SELECTED:
2019 event = wx.EVT_LIST_ITEM_DESELECTED
2020 else:
2021 event = wx.EVT_LIST_ITEM_SELECTED
2022 break
2023 elif isinstance(child, wx.RadioButton) and value in (
2024 "0",
2025 "1",
2026 "false",
2027 "true",
2028 ):
2029 child.SetValue(bool(demjson.decode(value)))
2030 event = wx.EVT_RADIOBUTTON
2031 elif isinstance(child, wx.Slider):
2032 try:
2033 child.SetValue(int(value))
2034 except Exception:
2035 response = "failed"
2036 else:
2037 event = wx.EVT_SLIDER
2038 elif isinstance(child, wx.SpinCtrl):
2039 try:
2040 child.SetValue(int(value))
2041 except Exception:
2042 response = "failed"
2043 else:
2044 event = wx.EVT_SPINCTRL
2045 elif isinstance(child, wx.TextCtrl):
2046 child.ChangeValue(value)
2047 event = wx.EVT_TEXT
2048 elif isinstance(child, (FlatShadedButton, GenButton, wx.Button)):
2049 event = wx.EVT_BUTTON
2050 if event:
2051 ctrl = child._cb if isinstance(child, CustomCheckBox) else child
2052 events = [event]
2053 if event is wx.EVT_SPINCTRL:
2054 events.append(wx.EVT_TEXT)
2055 elif event is wx.EVT_TEXT and win.FindFocus() != ctrl:
2056 events.append(wx.EVT_KILL_FOCUS)
2057 for event in events:
2058 if not isinstance(event, wx.Event):
2059 event = wx.CommandEvent(event.typeId, ctrl.Id)
2060 if isinstance(
2061 child, (CustomCheckBox, wx.CheckBox, wx.RadioButton)
2062 ):
2063 event.SetInt(int(ctrl.Value))
2064 event.SetEventObject(ctrl)
2065 if not isinstance(ctrl, wx.Notebook):
2066 # Bus error under Mac OS X
2067 wx.CallAfter(ctrl.ProcessEvent, event)
2068 wx.CallLater(1, child.Refresh)
2069 response = "ok"
2070 elif data[0] == "setcfg" and len(data) == 3:
2071 # Set configuration option
2072 value = None
2073 if data[1] in DEFAULTS:
2074 value = data[2]
2075 if value == "null":
2076 value = None
2077 elif value == "false":
2078 value = 0
2079 elif value == "true":
2080 value = 1
2081 elif DEFAULTS[data[1]] is not None:
2082 with contextlib.suppress(ValueError):
2083 value = type(DEFAULTS[data[1]])(value)
2084 setcfg(data[1], value)
2085 if getcfg(data[1], False) != value:
2086 response = "failed"
2087 else:
2088 response = "invalid"
2089 else:
2090 try:
2091 response = self.process_data(data)
2092 except Exception as exception:
2093 print(exception)
2094 if responseformats[conn] != "plain":
2095 response = {
2096 "class": exception.__class__.__name__,
2097 "error": str(exception),
2098 }
2099 else:
2100 response = "error " + demjson.encode(str(exception))
2101 else:
2102 # Some commands can be overriden, check response
2103 if response == "invalid":
2104 if (
2105 data[0] == "refresh"
2106 and len(data) == 1
2107 and hasattr(self, "update_controls")
2108 ):
2109 self.update_controls()
2110 self.update_layout()
2111 response = "ok"
2112 elif data[0] == "restore-defaults":
2113 for name in DEFAULTS:
2114 if len(data) > 1:
2115 include = False
2116 for _ in data[1:]:
2117 if name.startswith(data[1]):
2118 include = True
2119 break
2120 if not include:
2121 continue
2122 setcfg(name, None)
2123 response = "ok"
2124 elif (
2125 data[0] == "setlanguage"
2126 and len(data) == 2
2127 and hasattr(self, "panel")
2128 and hasattr(self, "update_controls")
2129 ):
2130 setcfg("lang", data[1])
2131 self.panel.Freeze()
2132 self.setup_language()
2133 self.update_controls()
2134 self.update_layout()
2135 self.panel.Thaw()
2136 response = "ok"
2137 if (
2138 data[0].startswith("get")
2139 or data[0] in ("refresh", "restore-defaults", "setcfg")
2140 or response != "ok"
2141 ):
2142 # No interaction with UI
2143 def relayfunc(func, *args):
2144 func(*args)
2145 else:
2146 # Interaction with UI
2147 # Prevent actual file dialogs blocking the UI - need to restore
2148 # original values after processing
2149 wx.DirDialog = DirDialog
2150 wx.FileDialog = FileDialog
2151
2152 # Use CallLater so GUI methods have a chance to run before we send
2153 # our response
2154 def relayfunc(func, *args):
2155 wx.CallLater(55, func, *args)
2156
2157 relayfunc(restore_path_dialog_classes)
2158 relayfunc(
2159 self.send_response, response, data, conn, command_timestamp, child or win
2160 )
2161
2162 def send_response(self, response, data, conn, command_timestamp, win=None):
2163 """Send a response back to the client.
2164
2165 Args:
2166 response (str or dict): The response to send.
2167 data (list): The command data that was processed.
2168 conn (Connection): The client connection.
2169 command_timestamp (str): The timestamp of the command.
2170 win (wx.Window, optional): The window that was interacted with.
2171 """
2172 if not responseformats.get(conn):
2173 # Client connection has broken down in the meantime
2174 return
2175 if response == "invalid":
2176 print(lang.getstr("app.incoming_message.invalid"))
2177 if responseformats[conn] != "plain":
2178 if not isinstance(response, (str, list)):
2179 response = [response]
2180 command = {"name": data[0], "timestamp": command_timestamp}
2181 if data[1:]:
2182 command["arguments"] = data[1:]
2183 response = {
2184 "command": command,
2185 "result": response,
2186 "timestamp": datetime.now().strftime("%Y-%m-%dTH:%M:%S.%f"),
2187 }
2188 if win:
2189 response["object"] = format_ui_element(win, responseformats[conn])
2190 if responseformats[conn].startswith("json"):
2191 response = demjson.encode(
2192 response, compactly=responseformats[conn] == "json"
2193 )
2194 elif responseformats[conn].startswith("xml"):
2195 response = (
2196 '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>'
2197 + ((responseformats[conn] == "xml.pretty" and "\n") or "")
2198 + dict2xml(
2199 response, "response", pretty=responseformats[conn] == "xml.pretty"
2200 )
2201 )
2202 else:
2203 if isinstance(response, dict):
2204 response = [f"{name} = {value}" for name, value in response.items()]
2205 if isinstance(response, list):
2206 response = "\n".join(response)
2207 try:
2208 conn.sendall(("{}\4".format(safe_str(response, "utf-8"))).encode("utf-8"))
2209 except OSError as exception:
2210 print(exception)
2211
2212 def send_command(self, scripting_host_name_suffix, command):
2213 """Send a command to a scripting host.
2214
2215 Args:
2216 scripting_host_name_suffix (str): Suffix to identify the scripting
2217 host.
2218 command (str): The command to send.
2219
2220 Returns:
2221 str: The response from the scripting host.
2222 """
2223 lock_name = APPBASENAME
2224 scripting_host = APPNAME
2225 if scripting_host_name_suffix:
2226 lock_name += "-" + scripting_host_name_suffix
2227 scripting_host += "-" + scripting_host_name_suffix
2228 try:
2229 for host in self.get_scripting_hosts():
2230 ip_port, name = host.split(None, 1)
2231 if name == lock_name:
2232 ip, port = ip_port.split(":", 1)
2233 port = int(port)
2234 conn = self.connect(ip, port)
2235 if isinstance(conn, Exception):
2236 raise conn
2237 # Check if we're actually connected to the right
2238 # application (if it terminated unexpectedly, something
2239 # else may have grabbed the port)
2240 conn.send_command("getappname")
2241 response = conn.get_single_response()
2242 if response == scripting_host:
2243 conn.send_command(command)
2244 response = conn.get_single_response()
2245 print(f"{scripting_host} {command} returned", response)
2246 else:
2247 print(
2248 f"Warning - {scripting_host} not running under "
2249 "expected port",
2250 port,
2251 )
2252 del conn
2253 return response
2254 else:
2255 print(f"Warning - {scripting_host} not running?")
2256 except Exception as exception:
2257 print(f"Warning - couldn't talk to {scripting_host}:", exception)
2258 return exception
2259
2260 def focus_handler(self, event=None):
2261 """Handle focus events to keep track of the last focused control.
2262
2263 Args:
2264 event (wx.Event, optional): The focus event. If None, a default
2265 focus event is created.
2266 """
2267 # IMPORTANT: event can either be EVT_TEXT, EVT_SET_FOCUS, EVT_CLOSE,
2268 # EVT_MENU or EVT_BUTTON.
2269 # This means the available event methods will be different, e.g.
2270 # only EVT_SET_FOCUS will have a GetWindow method, and EVT_MENU's
2271 # GetEventObject method returns the menu item which doesn't have
2272 # most methods that controls would have.
2273 if not event:
2274 event = CustomEvent(wx.EVT_SET_FOCUS.evtType[0], self)
2275 if DEBUG:
2276 if hasattr(event.GetEventObject(), "GetId"):
2277 print(
2278 f"[D] focus_handler called for ID {event.GetEventObject().GetId()} "
2279 f"{getevtobjname(event, self)} "
2280 f"{event.GetEventObject().__class__}, event type "
2281 f"{event.GetEventType()} {getevttype(event)}"
2282 )
2283 else:
2284 print(
2285 f"[D] focus_handler called for {getevtobjname(event, self)} "
2286 f"{event.GetEventObject().__class__}, event type "
2287 f"{event.GetEventType()} {getevttype(event)}"
2288 )
2289 if (
2290 hasattr(event, "GetWindow")
2291 and event.GetWindow()
2292 and event.GetEventObject() != event.GetWindow()
2293 ):
2294 print(
2295 f"[D] Focus moving from control ID {event.GetWindow().GetId()} "
2296 f"{event.GetWindow().GetName()} {event.GetWindow().__class__}"
2297 )
2298 if getattr(self, "last_focused_ctrl", None):
2299 print(
2300 f"[D] Last focused control: ID {self.last_focused_ctrl.GetId()} "
2301 f"{self.last_focused_ctrl.GetName()} "
2302 f"{self.last_focused_ctrl.__class__}"
2303 )
2304 if (
2305 getattr(self, "last_focused_ctrl", None)
2306 and isinstance(self.last_focused_ctrl, wx.ComboBox)
2307 and self.last_focused_ctrl != event.GetEventObject()
2308 and self.last_focused_ctrl.IsShownOnScreen()
2309 and event.GetEventObject()
2310 and (
2311 not hasattr(event.GetEventObject(), "IsShownOnScreen")
2312 or event.GetEventObject().IsShownOnScreen()
2313 )
2314 ):
2315 catchup_event = wx.FocusEvent(
2316 wx.EVT_KILL_FOCUS.evtType[0], self.last_focused_ctrl.GetId()
2317 )
2318 if DEBUG:
2319 print(
2320 "[D] Last focused control ID "
2321 f"{self.last_focused_ctrl.GetId()} "
2322 f"{self.last_focused_ctrl.GetName()} "
2323 f"{self.last_focused_ctrl.__class__} processing "
2324 "catchup event type "
2325 f"{catchup_event.GetEventType()} {getevttype(catchup_event)}"
2326 )
2327 if self.last_focused_ctrl.ProcessEvent(catchup_event):
2328 if DEBUG:
2329 print("[D] Last focused control processed catchup event")
2330 self.last_focused_ctrl = None
2331 if (
2332 hasattr(event.GetEventObject(), "GetId")
2333 and callable(event.GetEventObject().GetId)
2334 and isinstance(event.GetEventObject(), wx.Control)
2335 and event.GetEventObject() != getattr(self, "last_focused_ctrl", None)
2336 and hasattr(event.GetEventObject(), "IsShownOnScreen")
2337 and event.GetEventObject().IsShownOnScreen()
2338 ):
2339 if DEBUG:
2340 print(
2341 "[D] Setting last focused control to ID "
2342 f"{event.GetEventObject().GetId()} "
2343 f"{getevtobjname(event, self)} {event.GetEventObject().__class__}"
2344 )
2345 self.last_focused_ctrl = event.GetEventObject()
2346 if isinstance(event, wx.FocusEvent) or isinstance(
2347 event.GetEventObject(), wx.ComboBox
2348 ):
2349 event.Skip()
2350
2351 def setup_language(self):
2352 """Substitute translated strings for menus, controls, labels and tooltips."""
2353 if not hasattr(self, "_menulabels"):
2354 # Needed for Phoenix because custom attributes attached to menus
2355 # are not retained
2356 self._menulabels = {}
2357 if not hasattr(self, "_ctrllabels"):
2358 # Needed for Phoenix because custom attributes attached to controls
2359 # may not be retained
2360 self._ctrllabels = {}
2361 if not hasattr(self, "_tooltipstrings"):
2362 # Needed for Phoenix because custom attributes attached to controls
2363 # may not be retained
2364 self._tooltipstrings = {}
2365
2366 # Title
2367 if not hasattr(self, "_Title"):
2368 # Backup un-translated label
2369 title = self._Title = self.Title
2370 else:
2371 # Restore un-translated label
2372 title = self._Title
2373 translated = lang.getstr(title)
2374 if translated != title:
2375 self.Title = translated
2376
2377 # Menus
2378 menubar = self.menubar if hasattr(self, "menubar") else self.GetMenuBar()
2379 if menubar:
2380 for menu, label in menubar.GetMenus():
2381 menu_pos = menubar.FindMenu(label)
2382 if menu not in self._menulabels:
2383 # Backup un-translated label
2384 self._menulabels[menu] = label
2385 menubar.SetMenuLabel(
2386 menu_pos,
2387 "&" + lang.getstr(GTKMenuItemGetFixedLabel(self._menulabels[menu])),
2388 )
2389 self.setup_menu_language(menu)
2390 if sys.platform == "darwin":
2391 wx.GetApp().SetMacHelpMenuTitleName(lang.getstr("menu.help"))
2392 if isinstance(menubar, wx.MenuBar):
2393 self.SetMenuBar(menubar)
2394
2395 # Controls and labels
2396 for child in list(self.GetAllChildren()):
2397 if isinstance(
2398 child,
2399 (
2400 wx.StaticText,
2401 wx.Control,
2402 BetterStaticFancyText,
2403 BitmapBackgroundPanelText,
2404 ),
2405 ):
2406 if child not in self._ctrllabels:
2407 # Backup un-translated label
2408 label = self._ctrllabels[child] = child.Label
2409 else:
2410 # Restore un-translated label
2411 label = self._ctrllabels[child]
2412 translated = lang.getstr(label)
2413 if translated != label:
2414 if isinstance(child, wx.Button):
2415 translated = translated.replace("&", "&&")
2416 elif isinstance(
2417 child, BetterStaticFancyText
2418 ) and child.Name.endswith("_info_text"):
2419 if lang.getcode() == "ko":
2420 # Korean text runs too wide on info panels with
2421 # default wrap of 119
2422 child.maxlen = 70
2423 else:
2424 child.maxlen = 119
2425 if child.Name == "display_instrument_warmup_info_text":
2426 # Fix spacing - exactly one blank line between
2427 # warmup info and instrument/disptech info text
2428 translated += "\n&#160;"
2429 child.Label = translated
2430 if child.ToolTip:
2431 if child not in self._tooltipstrings:
2432 # Backup un-translated tooltip
2433 tooltipstr = self._tooltipstrings[child] = child.ToolTip.Tip
2434 else:
2435 # Restore un-translated tooltip
2436 tooltipstr = self._tooltipstrings[child]
2437 translated = lang.getstr(tooltipstr)
2438 if translated != tooltipstr:
2439 child.SetToolTipString(translated)
2440 elif isinstance(child, FileBrowseBitmapButtonWithChoiceHistory):
2441 if child.history:
2442 selection = child.textControl.GetSelection()
2443 child.textControl.Clear()
2444 for path in child.history:
2445 child.textControl.Append(child.GetName(path))
2446 child.textControl.SetSelection(selection)
2447
2448 def setup_menu_language(self, menu):
2449 """Substitute translated strings for menu items.
2450
2451 Args:
2452 menu (wx.Menu): The menu to set up language for.
2453 """
2454 if not hasattr(self, "_menuitems"):
2455 self._menuitems = {}
2456
2457 if menu not in self._menuitems:
2458 # Backup un-translated labels
2459 self._menuitems[menu] = []
2460 for item in menu.GetMenuItems():
2461 item_label = item.GetItemLabelText()
2462 self._menuitems[menu].append((item, item_label))
2463
2464 for item, label in self._menuitems[menu]:
2465 item_label = item.GetItemLabelText()
2466 if item_label and item_label != "":
2467 label = GTKMenuItemGetFixedLabel(label)
2468 localized_label = lang.getstr(label)
2469 if item.Accel:
2470 localized_label_text_with_accel = (
2471 f"{localized_label}\t{item.Accel.ToString()}"
2472 )
2473 # item.Text = localized_label_text_with_accel
2474 item.SetItemLabel(localized_label_text_with_accel)
2475 else:
2476 # item.Text = localized_label
2477 item.SetItemLabel(localized_label)
2478 if item.SubMenu:
2479 self.setup_menu_language(item.SubMenu)
2480
2481 def update_layout(self):
2482 """Update main window layout."""
2483 border_lr = self.Size[0] - self.ClientSize[0]
2484 border_tb = self.Size[1] - self.ClientSize[1]
2485 clientarea = self.GetDisplay().ClientArea
2486 sw = wx.SystemSettings_GetMetric(wx.SYS_VSCROLL_X)
2487 if sys.platform not in ("darwin", "win32"): # Linux
2488 # Client-side decorations on wayland,
2489 # otherwise assume server-side decorations
2490 safety_margin = 0 if os.getenv("XDG_SESSION_TYPE") == "wayland" else 40
2491 else:
2492 safety_margin = 20
2493 w, h = 0, 0
2494 for child in self.Children:
2495 if child.IsShown():
2496 size = child.Sizer.CalcMin() if child.Sizer else child.BestSize
2497 w = max(size[0], w)
2498 h += max(size[1], 0)
2499 minsize = (
2500 min(clientarea[2] - border_lr, w + sw),
2501 min(clientarea[3] - border_tb - safety_margin, h),
2502 )
2503 clientsize = (
2504 min(clientarea[2] - border_lr, self.ClientSize[0]),
2505 min(clientarea[3] - border_tb - safety_margin, self.ClientSize[1]),
2506 )
2507 if not self.IsIconized() and not self.IsMaximized():
2508 if os.getenv("XDG_SESSION_TYPE") == "wayland":
2509 self.MaxSize = (-1, -1)
2510 if (
2511 minsize[0] > clientsize[0]
2512 or minsize[1] != clientsize[1]
2513 or not getattr(self, "_layout", False)
2514 ):
2515 if not getattr(self, "_layout", False):
2516 clientsize = minsize
2517 elif os.getenv("XDG_SESSION_TYPE") != "wayland":
2518 # XXX this causes brief flickering to previous height on
2519 # manual resize under Wayland
2520 clientsize = clientsize[0], minsize[1]
2521 self.Sizer.SetMinSize(
2522 (max(minsize[0], clientsize[0]), max(minsize[1], clientsize[1]))
2523 )
2524 self.GetSizer().SetSizeHints(self)
2525 self.GetSizer().Layout()
2526 self._layout = True
2527 else:
2528 self.Layout()
2529 if os.getenv("XDG_SESSION_TYPE") == "wayland":
2530 self.MaxSize = self.Size
2531 wx.CallAfter(set_maxsize, self, (-1, -1))
2532 self.Sizer.SetMinSize((minsize[0], minsize[1]))
2533 if hasattr(self, "MinClientSize"):
2534 # wxPython >= 2.9
2535 self.MinClientSize = minsize
2536 else:
2537 # wxPython < 2.9
2538 self.SetMinSize(self.ClientToWindowSize(minsize))
2539
2540 def set_child_ctrls_as_attrs(self, parent=None):
2541 """Set child controls and labels as attributes of the frame.
2542
2543 Will also set a maximum font size of 11 pt.
2544 parent is the window over which children will be iterated and
2545 defaults to self.
2546
2547 Args:
2548 parent (wx.Window, optional): The parent window to iterate over.
2549 """
2550 if not parent:
2551 parent = self
2552 scale = getcfg("app.dpi") / get_default_dpi()
2553 for child in list(parent.GetAllChildren()):
2554 if DEBUG:
2555 print(child.__class__, child.Name)
2556 if isinstance(
2557 child,
2558 (
2559 wx.StaticText,
2560 wx.Control,
2561 filebrowse.FileBrowseButton,
2562 floatspin.FloatSpin,
2563 ),
2564 ):
2565 if (
2566 isinstance(child, wx.Choice)
2567 and sys.platform not in ("darwin", "win32")
2568 and child.MinSize[1] == -1
2569 ):
2570 # wx.Choice can have varying height based on GTK theme if
2571 # no initial items. Simply always set min height to that
2572 # of a wx.Choice with items.
2573 if not hasattr(BaseFrame, "_choiceheight"):
2574 choice = wx.Choice(self, choices=["|"])
2575 BaseFrame._choiceheight = choice.Size[1]
2576 choice.Destroy()
2577 child.MinSize = child.MinSize[0], BaseFrame._choiceheight
2578 elif isinstance(child, wx.BitmapButton):
2579 if "gtk3" in wx.PlatformInfo:
2580 # GTK3 doesn't respect NO_BORDER in hovered state when
2581 # using wx.BitmapButton and looks ugly
2582 orig_child = child
2583 child = GenBitmapButton(
2584 child.Parent,
2585 -1,
2586 child.BitmapLabel,
2587 child.Position,
2588 child.MinSize,
2589 child.WindowStyle,
2590 child.Validator or wx.DefaultValidator,
2591 child.Name,
2592 )
2593 child.BackgroundColour = orig_child.Parent.BackgroundColour
2594 child.Enabled = orig_child.Enabled
2595 # wxPython Classic / Phoenix
2596 for tt_attr in ("ToolTipString", "ToolTip"):
2597 if hasattr(orig_child, tt_attr):
2598 break
2599 orig_tt = getattr(orig_child, tt_attr, None)
2600 if orig_tt:
2601 if isinstance(orig_tt, wx.ToolTip):
2602 orig_tt = orig_tt.Tip
2603 setattr(child, tt_attr, orig_tt)
2604 orig_child.ContainingSizer.Replace(orig_child, child)
2605 orig_child.Destroy()
2606 else:
2607 set_bitmap_labels(child)
2608 elif (
2609 isinstance(child, wx._SpinCtrl)
2610 and not hasattr(child, "_spinwidth")
2611 and "gtk3" in wx.PlatformInfo
2612 ):
2613 if not getattr(wx.SpinCtrl, "_spinwidth", 0):
2614 spin = wx.SpinCtrl(self, -1)
2615 text = wx.TextCtrl(self, -1)
2616 wx.SpinCtrl._spinwidth = spin.Size[0] - text.Size[0] + 11
2617 spin.Destroy()
2618 text.Destroy()
2619 child.MinSize = (
2620 child.MinSize[0] + wx.SpinCtrl._spinwidth,
2621 child.MinSize[1],
2622 )
2623 elif isinstance(child, wx._StaticText) and "gtk3" in wx.PlatformInfo:
2624 if (
2625 child.__class__.SetLabel
2626 is not wx.StaticText.__dict__["SetLabel"]
2627 ):
2628 child.__class__.SetLabel = wx.StaticText.__dict__["SetLabel"]
2629 if child.__class__.Label is not wx.StaticText.__dict__["Label"]:
2630 child.__class__.Label = property(
2631 child.__class__.GetLabel, child.__class__.SetLabel
2632 )
2633 elif isinstance(child, wx.ComboBox) and "gtk3" in wx.PlatformInfo:
2634 # ComboBox is not wide enough to accomodate its text
2635 # box under GTK3
2636 child.MinSize = (
2637 max(child.MinSize[0], int(170 * scale)),
2638 child.MinSize[1],
2639 )
2640 child.SetMaxFontSize(11)
2641 if sys.platform == "darwin":
2642 # Work around ComboBox issues on Mac OS X
2643 # (doesn't receive EVT_KILL_FOCUS)
2644 if isinstance(child, wx.ComboBox):
2645 if child.IsEditable():
2646 if DEBUG:
2647 print(
2648 "[D]", child.Name, "binds EVT_TEXT to focus_handler"
2649 )
2650 child.Bind(wx.EVT_TEXT, self.focus_handler)
2651 else:
2652 child.Bind(wx.EVT_SET_FOCUS, self.focus_handler)
2653 if not hasattr(self, child.Name):
2654 setattr(self, child.Name, child)
2655 if (
2656 sys.platform == "win32"
2657 and sys.getwindowsversion() >= (6,)
2658 and isinstance(child, wx.Panel)
2659 ):
2660 # No need to enable double buffering under Linux and Mac OS X.
2661 # Under Windows, enabling double buffering on the panel seems
2662 # to work best to reduce flicker.
2663 child.SetDoubleBuffered(True)
2664 if (
2665 sys.platform != "darwin"
2666 and isinstance(child, wx.Panel)
2667 and child.AcceptsFocus()
2668 ):
2669 # Has no children that can accept focus, so there is no reason
2670 # why this should be able to receive focus, ever.
2671 # Move focus to the next control.
2672 child.Bind(
2673 wx.EVT_SET_FOCUS,
2674 lambda event: (
2675 (
2676 event.EventObject.AcceptsFocus()
2677 and event.EventObject.Navigate(
2678 int(not wx.GetKeyState(wx.WXK_SHIFT))
2679 )
2680 )
2681 or event.Skip()
2682 ),
2683 )
2684
2685 def getcfg(self, name, fallback=True, raw=False, cfg=config.CFG):
2686 """Get a configuration option.
2687
2688 Args:
2689 name (str): The name of the configuration option.
2690 fallback (bool, optional): Whether to return the fallback value if
2691 the configuration option does not exist. Defaults to True.
2692 raw (bool, optional): Whether to return the raw value without
2693 processing. Defaults to False.
2694 cfg (dict, optional): The configuration dictionary to get the
2695 configuration option from. Defaults to config.CFG.
2696
2697 Returns:
2698 object: The value of the configuration option, or the fallback
2699 value if it does not exist.
2700 """
2701 return getcfg(name, fallback, raw, cfg)
2702
2703 def hascfg(self, name, fallback=True, cfg=config.CFG):
2704 """Check if a configuration option exists.
2705
2706 Args:
2707 name (str): The name of the configuration option.
2708 fallback (bool, optional): Whether to return the fallback value if
2709 the configuration option does not exist. Defaults to True.
2710 cfg (dict, optional): The configuration dictionary to check the
2711 configuration option in. Defaults to config.CFG.
2712
2713 Returns:
2714 bool: True if the configuration option exists, False otherwise.
2715 """
2716 return hascfg(name, fallback, cfg)
2717
2718 def setcfg(self, name, value, cfg=config.CFG):
2719 """Set a configuration option.
2720
2721 Args:
2722 name (str): The name of the configuration option.
2723 value: The value to set the configuration option to.
2724 cfg (dict, optional): The configuration dictionary to set the
2725 configuration option in. Defaults to config.CFG.
2726 """
2727 setcfg(name, value, cfg)
2728
2729
2730 class BaseInteractiveDialog(wx.Dialog):
2731 """Base class for informational and confirmation dialogs."""
2732
2733 def __init__(
2734 self,
2735 parent=None,
2736 id=-1, # noqa: A002
2737 title=APPNAME,
2738 msg="",
2739 ok=None,
2740 bitmap=None,
2741 pos=(-1, -1),
2742 size=(400, -1),
2743 show=True,
2744 log=True,
2745 style=wx.DEFAULT_DIALOG_STYLE,
2746 nowrap=False,
2747 wrap=70,
2748 name=wx.DialogNameStr,
2749 bitmap_margin=None,
2750 ):
2751 if not ok:
2752 ok = lang.getstr("ok")
2753 self._log = log
2754 self._msg = msg
2755 if parent:
2756 pos = list(pos)
2757 for i, coord in enumerate(pos):
2758 if coord > -1:
2759 pos[i] += parent.GetScreenPosition()[i]
2760 pos = tuple(pos)
2761 if title == APPNAME:
2762 appid = get_appid_from_window_hierarchy(parent)
2763 base_appid = APPNAME.lower()
2764 appid2title = {
2765 base_appid + "-3dlut-maker": "3dlut.frame.title",
2766 base_appid + "-curve-viewer": "calibration.lut_viewer.title",
2767 base_appid + "-profile-info": "profile.info",
2768 base_appid + "-scripting-client": "scripting-client",
2769 base_appid + "-synthprofile": "synthicc.create",
2770 base_appid + "-testchart-editor": "testchart.edit",
2771 base_appid + "-vrml-to-x3d-converter": "vrml_to_x3d_converter",
2772 }
2773 title = lang.getstr(appid2title.get(appid, "window.title"))
2774 scale = int(getcfg("app.dpi") / get_default_dpi())
2775 if scale > 1 and size == (400, -1):
2776 size = size[0] * scale, size[1]
2777 wx.Dialog.__init__(self, parent, id, title, pos, size, style, name)
2778 self.taskbar = None
2779 if sys.platform == "win32":
2780 bgcolor = self.BackgroundColour
2781 self.SetBackgroundColour(wx.SystemSettings.GetColour(wx.SYS_COLOUR_WINDOW))
2782 if TASKBAR:
2783 taskbarframe = parent if parent and parent.IsShownOnScreen() else self
2784 if hasattr(taskbarframe, "taskbar"):
2785 self.taskbar = taskbarframe.taskbar
2786 else:
2787 self.taskbar = TASKBAR.Taskbar(taskbarframe)
2788 self.SetPosition(pos) # yes, this is needed
2789
2790 self.Bind(wx.EVT_SHOW, self.OnShow, self)
2791
2792 margin = 12
2793
2794 if bitmap_margin is None:
2795 bitmap_margin = margin
2796
2797 self.sizer0 = wx.BoxSizer(wx.VERTICAL)
2798 self.SetSizer(self.sizer0)
2799 if bitmap:
2800 self.sizer1 = wx.FlexGridSizer(1, 2, 0, 0)
2801 else:
2802 self.sizer1 = wx.BoxSizer(wx.HORIZONTAL)
2803 self.sizer2 = wx.BoxSizer(wx.HORIZONTAL)
2804 self.sizer3 = wx.FlexGridSizer(0, 1, 0, 0)
2805 self.sizer0.Add(self.sizer1, flag=wx.ALIGN_LEFT | wx.RIGHT, border=margin)
2806 self.buttonpanel = wx.Panel(self)
2807 self.buttonpanel.SetSizer(wx.BoxSizer(wx.VERTICAL))
2808 self.buttonpanel.Sizer.Add(
2809 self.sizer2, 1, flag=wx.ALL | wx.EXPAND, border=margin
2810 )
2811 if sys.platform == "win32":
2812 self.buttonpanel_line = wx.Panel(self, size=(-1, 1))
2813 self.buttonpanel_line.SetBackgroundColour(
2814 wx.SystemSettings.GetColour(wx.SYS_COLOUR_3DLIGHT)
2815 )
2816 self.sizer0.Add(
2817 self.buttonpanel_line, flag=wx.TOP | wx.EXPAND, border=margin
2818 )
2819 self.buttonpanel.SetBackgroundColour(bgcolor)
2820 self.sizer0.Add(self.buttonpanel, flag=wx.EXPAND)
2821
2822 flags = wx.LEFT | wx.TOP if bitmap_margin else 0
2823 if bitmap:
2824 self.bitmap = wx.StaticBitmap(self, -1, bitmap)
2825 self.sizer1.Add(self.bitmap, flag=flags, border=margin)
2826 if self.taskbar:
2827 state = None
2828 if bitmap is get_icon(32, "dialog-error"):
2829 state = TASKBAR.TBPF_ERROR
2830 elif bitmap is get_icon(32, "dialog-warning"):
2831 state = TASKBAR.TBPF_PAUSED
2832 if state is not None:
2833 if (
2834 state == TASKBAR.TBPF_ERROR
2835 or not isinstance(self.Parent, ProgressDialog)
2836 or self.Parent.paused
2837 ):
2838 self.taskbar.set_progress_state(state)
2839 if not isinstance(self.Parent, ProgressDialog):
2840 self.taskbar.set_progress_value(self.taskbar.maxv)
2841
2842 self.sizer1.Add(self.sizer3, flag=wx.ALIGN_LEFT | flags | wx.TOP, border=margin)
2843 msg = msg.replace("&", "&&")
2844 self.message = wx.StaticText(
2845 self, -1, msg if nowrap else util_str.wrap(msg, wrap)
2846 )
2847 if sys.platform == "win32":
2848 # Prevent text cutoff (wxWidgets bug)
2849 self.message.MinSize = (
2850 self.message.Size[0] + math.ceil(1 * scale),
2851 self.message.MinSize[1],
2852 )
2853 self.sizer3.Add(self.message)
2854
2855 # btnwidth = 80
2856
2857 self.ok = wx.Button(self.buttonpanel, wx.ID_OK, ok)
2858 self.sizer2.Add((-1, 1), 1)
2859 self.sizer2.Add(self.ok)
2860 self.Bind(wx.EVT_BUTTON, self.OnClose, id=wx.ID_OK)
2861
2862 self.buttonpanel.Layout()
2863 self.sizer0.SetSizeHints(self)
2864 self.sizer0.Layout()
2865 self.pos = pos
2866 if show:
2867 self.ok.SetDefault()
2868 self.ShowModalThenDestroy()
2869
2870 def ShowModalThenDestroy(self):
2871 """Show the dialog as a modal dialog and destroy it after closing.
2872
2873 Returns:
2874 int: The return code of the dialog, typically wx.ID_OK or
2875 wx.ID_CANCEL.
2876 """
2877 result = self.ShowModal()
2878 self.Destroy()
2879 return result
2880
2881 def OnShow(self, event):
2882 """Handle the show event of the dialog.
2883
2884 Args:
2885 event (wx.ShowEvent): The event object containing information
2886 """
2887 event.Skip()
2888 if not getattr(event, "IsShown", getattr(event, "GetShow", bool))():
2889 return
2890 if self._log:
2891 print(box(self._msg))
2892 app = wx.GetApp()
2893 # Make sure taskbar button flashes under Windows
2894 topwindow = app.GetTopWindow()
2895 topwindow_shown = topwindow and topwindow.IsShown()
2896 window = topwindow if topwindow_shown else self.Parent or self
2897 # Only request user attention if toplevel window has a non-empty title
2898 if (
2899 not app.IsActive()
2900 or (self.Parent and not topwindow_shown and getattr(topwindow, "Title", ""))
2901 ) and hasattr(window, "RequestUserAttention"):
2902 window.RequestUserAttention()
2903 if window != self:
2904 self.RequestUserAttention()
2905
2906 def OnClose(self, event):
2907 """Handle the close event of the dialog.
2908
2909 Args:
2910 event (wx.CommandEvent): The event object containing information
2911 """
2912 id_ = wx.ID_CANCEL if event.GetEventObject() == self else event.GetId()
2913 if self._log and isinstance(self, ConfirmDialog):
2914 if hasattr(self, "FindWindow"):
2915 # wxPython 4
2916 ctrl = self.FindWindow(id_)
2917 else:
2918 # wxPython 3
2919 ctrl = self.FindWindowById(id_)
2920 if ctrl:
2921 print("->", ctrl.Label)
2922 self.EndModal(id_)
2923
2924 def EndModal(self, id): # noqa: A002
2925 """End the modal dialog and return the given id.
2926
2927 Args:
2928 id (int): The return code of the dialog, typically wx.ID_OK or
2929 wx.ID_CANCEL.
2930 """
2931 # Re-enable other windows
2932 if hasattr(self, "_disabler"):
2933 del self._disabler
2934 if self.IsModal():
2935 wx.Dialog.EndModal(self, id)
2936 else:
2937 # Process wx.WindowModalDialogEvent
2938 event = wx.WindowModalDialogEvent(
2939 wx.wxEVT_WINDOW_MODAL_DIALOG_CLOSED, self.Id
2940 )
2941 event.SetInt(id)
2942 self.ProcessEvent(event)
2943 self.Hide()
2944
2945 def Show(self, show=True):
2946 """Show the dialog.
2947
2948 Args:
2949 show (bool): Whether to show or hide the dialog.
2950
2951 Returns:
2952 bool: True if the dialog was shown, False if it was hidden.
2953 """
2954 if show:
2955 self.set_position()
2956 return wx.Dialog.Show(self, show)
2957
2958 def ShowModal(self):
2959 """Show the dialog as a modal dialog."""
2960 self.set_position()
2961 result = wx.Dialog.ShowModal(self)
2962 if self:
2963 self.update_taskbar()
2964 return result
2965
2966 def update_taskbar(self):
2967 """Update the taskbar progress state."""
2968 if self and self.taskbar:
2969 state = None
2970 if (
2971 isinstance(self.Parent, ProgressDialog)
2972 and self.Parent.timer.IsRunning()
2973 ):
2974 if self.Parent.indeterminate:
2975 state = TASKBAR.TBPF_INDETERMINATE
2976 elif not self.Parent.paused:
2977 state = TASKBAR.TBPF_NORMAL
2978 else:
2979 state = TASKBAR.TBPF_NOPROGRESS
2980 if state is not None:
2981 self.taskbar.set_progress_state(state)
2982
2983 def ShowWindowModal(self):
2984 """Show the dialog as a modal window."""
2985 self.set_position()
2986 self._disabler = BetterWindowDisabler(self, self.Parent)
2987 if hasattr(wx.Dialog, "ShowWindowModal") and sys.platform == "darwin":
2988 # wx 2.9+
2989 # Use CallAfter so the native macOS sheet animation starts from a
2990 # clean event-loop iteration instead of from within a suspended
2991 # Python frame. Without this, the sheet's opening animation runs
2992 # a nested Cocoa RunLoop which can dispatch paint events back into
2993 # Python; if any paint handler raises an unhandled exception,
2994 # CPython 3.11's re-entrant _PyErr_PrintEx / _PyFrame_Clear
2995 # crashes with SIGSEGV (issue #709).
2996 wx.CallAfter(wx.Dialog.ShowWindowModal, self)
2997 else:
2998 self.Show()
2999
3000 def ShowWindowModalBlocking(self):
3001 """Blocking ShoWindowModal implementation.
3002
3003 Normally, ShowWindowModal is only implemented under macOS and doesn't
3004 block. This version blocks, while still allowing interaction with
3005 windows other than the parent (i.e. like ShowModal under platforms
3006 other than macOS).
3007
3008 Returns:
3009 int: The return code of the dialog, typically wx.ID_OK or
3010 wx.ID_CANCEL.
3011 """
3012 result = {"dlg": None, "retcode": wx.ID_CANCEL}
3013
3014 def OnCloseWindowModalDialog(event):
3015 result["dlg"] = event.GetDialog()
3016 result["retcode"] = event.GetReturnCode()
3017
3018 self.Unbind(wx.EVT_WINDOW_MODAL_DIALOG_CLOSED)
3019 self.Bind(wx.EVT_WINDOW_MODAL_DIALOG_CLOSED, OnCloseWindowModalDialog)
3020 self.ShowWindowModal()
3021 while self and result["dlg"] is not self:
3022 wx.Yield()
3023 sleep(1.0 / 60)
3024 return result["retcode"]
3025
3026 def set_position(self):
3027 """Set the position of the dialog."""
3028 if self.Parent and self.Parent.IsIconized():
3029 self.Parent.Restore()
3030 if not getattr(self, "pos", None) or self.pos == (-1, -1):
3031 self.Center(wx.BOTH)
3032 elif self.pos[0] == -1:
3033 self.Center(wx.HORIZONTAL)
3034 elif self.pos[1] == -1:
3035 self.Center(wx.VERTICAL)
3036
3037
3038 if not hasattr(wx, "WindowModalDialogEvent") or sys.platform != "darwin":
3039 # Fake it or overwrite it, as we can't use GetDialog/GetReturnCode otherwise
3040
3041 wx.wxEVT_WINDOW_MODAL_DIALOG_CLOSED = wx.NewEventType()
3042 wx.EVT_WINDOW_MODAL_DIALOG_CLOSED = wx.PyEventBinder(
3043 wx.wxEVT_WINDOW_MODAL_DIALOG_CLOSED, 1
3044 )
3045
3046 class WindowModalDialogEvent(wx.PyCommandEvent):
3047 """A wx.CommandEvent that contains the dialog and return code."""
3048
3049 def __init__(self, commandType=wx.wxEVT_NULL, id=0): # noqa: A002
3050 wx.PyCommandEvent.__init__(self, commandType, id)
3051
3052 def GetDialog(self):
3053 """Get the dialog associated with this event.
3054
3055 Returns:
3056 wx.Dialog: The dialog associated with this event.
3057 """
3058 return wx.FindWindowById(self.Id)
3059
3060 def GetReturnCode(self):
3061 """Get the return code of the dialog.
3062
3063 Returns:
3064 int: The return code of the dialog, typically wx.ID_OK or
3065 wx.ID_CANCEL.
3066 """
3067 return self.GetInt()
3068
3069 wx.WindowModalDialogEvent = WindowModalDialogEvent
3070
3071
3072 class HtmlInfoDialog(BaseInteractiveDialog):
3073 """A dialog with an HTML window and a bitmap."""
3074
3075 def __init__(
3076 self,
3077 parent=None,
3078 id=-1, # noqa: A002
3079 title=APPNAME,
3080 msg="",
3081 html="",
3082 ok="OK",
3083 bitmap=None,
3084 pos=(-1, -1),
3085 size=(400, -1),
3086 show=True,
3087 log=True,
3088 bitmap_margin=None,
3089 ):
3090 BaseInteractiveDialog.__init__(
3091 self,
3092 parent,
3093 id,
3094 title,
3095 msg,
3096 ok,
3097 bitmap,
3098 pos,
3099 size,
3100 False,
3101 log,
3102 bitmap_margin=bitmap_margin,
3103 )
3104
3105 scale = getcfg("app.dpi") / config.get_default_dpi()
3106 scale = max(scale, 1)
3107 htmlwnd = HtmlWindow(
3108 self, -1, size=(332 * scale, 200 * scale), style=wx.BORDER_THEME
3109 )
3110 htmlwnd.SetPage(html)
3111 self.sizer3.Add(htmlwnd, 1, flag=wx.TOP | wx.ALIGN_LEFT | wx.EXPAND, border=12)
3112 self.sizer0.SetSizeHints(self)
3113 self.sizer0.Layout()
3114 if show:
3115 self.ok.SetDefault()
3116 self.ShowModalThenDestroy()
3117
3118
3119 class HtmlWindow(wx.html.HtmlWindow):
3120 """A wx.html.HtmlWindow that uses system default colors."""
3121
3122 def __init__(self, *args, **kwargs):
3123 wx.html.HtmlWindow.__init__(self, *args, **kwargs)
3124 scale = max(getcfg("app.dpi") / config.get_default_dpi(), 1)
3125 if "gtk3" in wx.PlatformInfo:
3126 size = round(
3127 wx.SystemSettings.GetFont(wx.SYS_DEFAULT_GUI_FONT).PointSize * scale
3128 )
3129 else:
3130 size = -1
3131 self.SetStandardFonts(size)
3132 self.Bind(
3133 wx.html.EVT_HTML_LINK_CLICKED,
3134 lambda event: launch_file(event.GetLinkInfo().Href),
3135 )
3136
3137 def SetPage(self, source):
3138 """Set displayed page with system default colors."""
3139 html = str(source)
3140 bgcolor, text, linkcolor, vlinkcolor = get_html_colors()
3141 try:
3142 bgcolor_html = f"#{int(bgcolor.Red()):02x}{int(bgcolor.Green()):02x}{int(bgcolor.Blue()):02x}"
3143 text_html = (
3144 f"#{int(text.Red()):02x}{int(text.Green()):02x}{int(text.Blue()):02x}"
3145 )
3146 link_html = f"#{int(linkcolor.Red()):02x}{int(linkcolor.Green()):02x}{int(linkcolor.Blue()):02x}"
3147 vlink_html = f"#{int(vlinkcolor.Red()):02x}{int(vlinkcolor.Green()):02x}{int(vlinkcolor.Blue()):02x}"
3148 except Exception:
3149 bgcolor_html = "#ffffff"
3150 text_html = "#000000"
3151 link_html = "#2c5dcd"
3152 vlink_html = "#6f6f6f"
3153 if "<body" not in html:
3154 html = f"<body>{html}</body>"
3155 html = re.sub(
3156 r"<body[^>]*",
3157 f'<body bgcolor="{bgcolor_html}" '
3158 f'text="{text_html}" '
3159 f'link="{link_html}" '
3160 f'alink="{link_html}" '
3161 f'vlink="{vlink_html}"',
3162 html,
3163 )
3164 wx.html.HtmlWindow.SetPage(self, html)
3165
3166
3167 class BitmapBackgroundBitmapButton(wx.BitmapButton):
3168 """A BitmapButton that will use its parent bitmap background.
3169
3170 The parent needs to have a GetBitmap() method.
3171
3172 """
3173
3174 def __init__(self, *args, **kwargs):
3175 wx.BitmapButton.__init__(self, *args, **kwargs)
3176 self.Bind(wx.EVT_PAINT, self.OnPaint)
3177
3178 def OnPaint(self, dc):
3179 """Handle paint events to draw the parent bitmap background.
3180
3181 Args:
3182 dc (wx.PaintDC): The device context to draw on.
3183 """
3184 dc = wx.PaintDC(self)
3185 with contextlib.suppress(Exception):
3186 dc = wx.GCDC(dc)
3187 parent = self.GetParent()
3188 if not parent:
3189 return
3190 with contextlib.suppress(Exception):
3191 dc.DrawBitmap(parent.GetBitmap(), 0, -self.GetPosition()[1])
3192 dc.DrawBitmap(self.GetBitmapLabel(), 0, 0)
3193
3194
3195 bitmaps = {}
3196
3197
3198 class BitmapBackgroundPanel(wx.PyPanel):
3199 """A panel with a background bitmap."""
3200
3201 def __init__(self, *args, **kwargs):
3202 wx.PyPanel.__init__(self, *args, **kwargs)
3203 self._bitmap = None
3204 self.alpha = 1.0
3205 self.blend = False
3206 self.borderbtmcolor = wx.SystemSettings.GetColour(wx.SYS_COLOUR_3DSHADOW)
3207 self.bordertopcolor = wx.SystemSettings.GetColour(wx.SYS_COLOUR_3DLIGHT)
3208 self.drawborderbtm = False
3209 self.drawbordertop = False
3210 self.repeat_sub_bitmap_h = None
3211 self.scalebitmap = (True, False)
3212 self.scalequality = wx.IMAGE_QUALITY_NORMAL
3213 if "gtk3" in wx.PlatformInfo:
3214 # Fix background color not working for panels under GTK3
3215 self.Bind(wx.EVT_ERASE_BACKGROUND, self.OnEraseBackground)
3216 else:
3217 self.SetBackgroundStyle(wx.BG_STYLE_CUSTOM)
3218 self.Bind(wx.EVT_PAINT, self.OnPaint)
3219 self.Bind(wx.EVT_SIZE, self.OnSize)
3220
3221 if "gtk3" in wx.PlatformInfo:
3222 OnEraseBackground = wx_Panel.__dict__["OnEraseBackground"]
3223
3224 def AcceptsFocus(self):
3225 """Override to prevent focus from being set on this panel.
3226
3227 Returns:
3228 bool: Always returns False, indicating that this panel does not
3229 accept focus.
3230 """
3231 return False
3232
3233 def AcceptsFocusFromKeyboard(self):
3234 """Override to prevent focus from being set on this panel.
3235
3236 Returns:
3237 bool: Always returns False, indicating that this panel does not
3238 accept focus from the keyboard.
3239 """
3240 return False
3241
3242 def GetBitmap(self):
3243 """Get the bitmap currently set as the background.
3244
3245 Returns:
3246 wx.Bitmap: The bitmap currently set as the background, or None if
3247 no bitmap is set.
3248 """
3249 return self._bitmap
3250
3251 def SetBitmap(self, bitmap):
3252 """Set the bitmap to be used as the background.
3253
3254 Args:
3255 bitmap (wx.Bitmap): The bitmap to set as the background. If the
3256 bitmap is None, the background will not be drawn.
3257 """
3258 self._bitmap = bitmap
3259
3260 def OnPaint(self, event):
3261 """Handle paint events to draw the bitmap background.
3262
3263 Args:
3264 event (wx.PaintEvent): The paint event that triggered the redraw.
3265 """
3266 if sys.platform != "win32":
3267 # AutoBufferedPaintDCFactory is the magic needed for crisp text
3268 # rendering in HiDPI mode under OS X and Linux
3269 cls = wx.AutoBufferedPaintDCFactory
3270 else:
3271 cls = wx.BufferedPaintDC
3272 dc = cls(self)
3273 self._draw(dc)
3274
3275 def OnSize(self, event):
3276 """Handle size events to redraw the bitmap background.
3277
3278 Args:
3279 event (wx.SizeEvent): The size event that triggered the redraw.
3280 """
3281 self.Refresh()
3282 event.Skip()
3283
3284 def _draw(self, dc):
3285 bgcolor = self.BackgroundColour
3286 bbr = wx.Brush(bgcolor, wx.BRUSHSTYLE_SOLID)
3287 dc.SetBackground(bbr)
3288 dc.SetBackgroundMode(wx.BRUSHSTYLE_SOLID)
3289 dc.Clear()
3290 dc.SetTextForeground(self.GetForegroundColour())
3291 bmp = self._bitmap
3292 if bmp:
3293 if self.alpha < 1.0 or self.blend:
3294 key = (
3295 id(bmp),
3296 (bgcolor.Red(), bgcolor.Green(), bgcolor.Blue()),
3297 self.alpha,
3298 )
3299 bmp = bitmaps.get(key)
3300 if not bmp:
3301 bmp = self._bitmap
3302 image = bmp.ConvertToImage()
3303 if self.alpha < 1.0:
3304 if not image.HasAlpha():
3305 image.InitAlpha()
3306 alphabuffer = image.GetAlphaBuffer()
3307 for i, byte in enumerate(alphabuffer):
3308 if byte > 0:
3309 alphabuffer[i] = round(byte * self.alpha)
3310 if self.blend:
3311 databuffer = image.GetDataBuffer()
3312 for i, byte in enumerate(databuffer):
3313 if byte > 0:
3314 databuffer[i] = round(byte * (bgcolor[i % 3] / 255.0))
3315 bmp = image.ConvertToBitmap()
3316 bitmaps[key] = bmp
3317 if True in self.scalebitmap:
3318 img = bmp.ConvertToImage()
3319 img.Rescale(
3320 self.GetSize()[0] if self.scalebitmap[0] else img.GetSize()[0],
3321 self.GetSize()[1] if self.scalebitmap[1] else img.GetSize()[1],
3322 quality=self.scalequality,
3323 )
3324 bmp = img.ConvertToBitmap()
3325 dc.DrawBitmap(bmp, 0, 0)
3326 if (
3327 self.repeat_sub_bitmap_h
3328 and self.Size[0] > bmp.Size[0] >= self.repeat_sub_bitmap_h[0]
3329 and bmp.Size[1] >= self.repeat_sub_bitmap_h[1]
3330 ):
3331 sub_bmp = bmp.GetSubBitmap(self.repeat_sub_bitmap_h)
3332 sub_img = sub_bmp.ConvertToImage()
3333 sub_img.Rescale(
3334 self.GetSize()[0] - bmp.GetSize()[0],
3335 bmp.GetSize()[1] if self.scalebitmap[1] else sub_bmp.GetSize()[1],
3336 quality=self.scalequality,
3337 )
3338 dc.DrawBitmap(sub_img.ConvertToBitmap(), bmp.GetSize()[0], 0)
3339 if self.drawbordertop:
3340 pen = wx.Pen(self.bordertopcolor, 1, wx.PENSTYLE_SOLID)
3341 pen.SetCap(wx.CAP_BUTT)
3342 dc.SetPen(pen)
3343 dc.DrawLine(0, 0, self.GetSize()[0], 0)
3344 if self.drawborderbtm:
3345 pen = wx.Pen(self.borderbtmcolor, 1, wx.PENSTYLE_SOLID)
3346 pen.SetCap(wx.CAP_BUTT)
3347 dc.SetPen(pen)
3348 dc.DrawLine(
3349 0, self.GetSize()[1] - 1, self.GetSize()[0], self.GetSize()[1] - 1
3350 )
3351
3352
3353 class BitmapBackgroundPanelText(BitmapBackgroundPanel):
3354 """A panel with a background bitmap and text label."""
3355
3356 def __init__(self, *args, **kwargs):
3357 BitmapBackgroundPanel.__init__(self, *args, **kwargs)
3358 self.label_x = None
3359 self.label_y = None
3360 self.textalpha = 1.0
3361 self.textshadow = True
3362 self.textshadowcolor = wx.SystemSettings.GetColour(wx.SYS_COLOUR_3DLIGHT)
3363 self.use_gcdc = False
3364 self._label = ""
3365
3366 def _set_font(self, dc):
3367 """Set the font for the device context.
3368
3369 Args:
3370 dc (wx.DC): The device context to set the font for.
3371
3372 Returns:
3373 wx.DC: The device context with the font set.
3374 """
3375 font = self.GetFont()
3376 if self.use_gcdc:
3377 # NOTE: Drawing text to wx.GCDC has problems with unicode chars
3378 # being replaced with boxes under wxGTK
3379 with contextlib.suppress(Exception):
3380 dc = wx.GCDC(dc)
3381 font.SetPointSize(get_dc_font_size(font.GetPointSize(), dc))
3382 dc.SetFont(font)
3383 return dc
3384
3385 def GetLabel(self):
3386 """Get the label text to be displayed on the panel.
3387
3388 Returns:
3389 str: The text to display as the label.
3390 """
3391 return self._label
3392
3393 @property
3394 def Label(self):
3395 """Get the label text to be displayed on the panel.
3396
3397 Returns:
3398 str: The text to display as the label.
3399 """
3400 return self.GetLabel()
3401
3402 @Label.setter
3403 def Label(self, label):
3404 """Set the label text to be displayed on the panel.
3405
3406 Args:
3407 label (str): The text to display as the label.
3408 """
3409 self.SetLabel(label)
3410
3411 def SetLabel(self, label):
3412 """Set the label text to be displayed on the panel.
3413
3414 Args:
3415 label (str): The text to display as the label.
3416 """
3417 self._label = label
3418
3419 def _draw(self, dc):
3420 BitmapBackgroundPanel._draw(self, dc)
3421 dc.SetBackgroundMode(wx.BRUSHSTYLE_TRANSPARENT)
3422 dc = self._set_font(dc)
3423 label = self.Label.splitlines()
3424 for i, line in enumerate(label):
3425 w1, h1 = self.GetTextExtent(line)
3426 w2, h2 = dc.GetTextExtent(line)
3427 if self.label_x is None:
3428 w = (max(w1, w2) - min(w1, w2)) / 2.0 + min(w1, w2)
3429 x = self.GetSize()[0] / 2.0 - w / 2.0
3430 else:
3431 x = self.label_x
3432 h = (max(h1, h2) - min(h1, h2)) / 2.0 + min(h1, h2)
3433 if self.label_y is None:
3434 y = self.GetSize()[1] / 2.0 - h / 2.0
3435 else:
3436 y = self.label_y + h * i
3437 if self.textshadow:
3438 dc.SetTextForeground(self.textshadowcolor)
3439 dc.DrawText(line, x + 1, y + 1)
3440 color = self.GetForegroundColour()
3441 if self.textalpha < 1:
3442 bgcolor = self.BackgroundColour
3443 bgblend = 1.0 - self.textalpha
3444 blend = self.textalpha
3445 color = wx.Colour(
3446 round(bgblend * bgcolor.Red() + blend * color.Red()),
3447 round(bgblend * bgcolor.Green() + blend * color.Green()),
3448 round(bgblend * bgcolor.Blue() + blend * color.Blue()),
3449 )
3450 dc.SetTextForeground(color)
3451 dc.DrawText(line, int(x), int(y))
3452
3453
3454 class BitmapBackgroundPanelTextGamut(BitmapBackgroundPanelText):
3455 """A panel with a background bitmap and text label to display gamut."""
3456
3457 def __init__(self, *args, **kwargs):
3458 BitmapBackgroundPanel.__init__(self, *args, **kwargs)
3459 self.title = lang.getstr("gamut.coverage")
3460 self.caption = lang.getstr("gamut.coverage")
3461 self.label_x = None
3462 self.label_y = None
3463 self.textalpha = 1.0
3464 self.textshadow = True
3465 self.textshadowcolor = wx.SystemSettings.GetColour(wx.SYS_COLOUR_3DLIGHT)
3466 self.use_gcdc = False
3467 self._label = ""
3468
3469
3470 class ConfirmDialog(BaseInteractiveDialog):
3471 """Confirmation dialog with OK and Cancel buttons."""
3472
3473 def __init__(
3474 self,
3475 parent=None,
3476 id=-1, # noqa: A002
3477 title=APPNAME,
3478 msg="",
3479 ok=None,
3480 cancel=None,
3481 bitmap=None,
3482 pos=(-1, -1),
3483 size=(400, -1),
3484 alt=None,
3485 log=False,
3486 style=wx.DEFAULT_DIALOG_STYLE,
3487 nowrap=False,
3488 wrap=70,
3489 name=wx.DialogNameStr,
3490 bitmap_margin=None,
3491 ):
3492 if not ok:
3493 ok = lang.getstr("ok")
3494 if not cancel:
3495 cancel = lang.getstr("cancel")
3496 BaseInteractiveDialog.__init__(
3497 self,
3498 parent,
3499 id,
3500 title,
3501 msg,
3502 ok,
3503 bitmap,
3504 pos,
3505 size,
3506 show=False,
3507 log=log,
3508 style=style,
3509 nowrap=nowrap,
3510 wrap=wrap,
3511 name=name,
3512 bitmap_margin=bitmap_margin,
3513 )
3514
3515 self.Bind(wx.EVT_CLOSE, self.OnClose, self)
3516
3517 margin = 12
3518
3519 if alt:
3520 self.alt = wx.Button(self.buttonpanel, -1, alt)
3521 self.sizer2.Insert(1, (margin, margin))
3522 self.sizer2.Insert(1, self.alt)
3523 self.Bind(wx.EVT_BUTTON, self.OnClose, id=self.alt.GetId())
3524
3525 if ok != cancel:
3526 self.cancel = wx.Button(self.buttonpanel, wx.ID_CANCEL, cancel)
3527 self.sizer2.Insert(1, (margin, margin))
3528 self.sizer2.Insert(1, self.cancel)
3529 self.Bind(wx.EVT_BUTTON, self.OnClose, id=wx.ID_CANCEL)
3530
3531 self.buttonpanel.Layout()
3532 self.sizer0.SetSizeHints(self)
3533 self.sizer0.Layout()
3534
3535
3536 class FileBrowseBitmapButtonWithChoiceHistory(filebrowse.FileBrowseButtonWithHistory):
3537 """A FileBrowseButton with a history of previously selected files."""
3538
3539 def __init__(self, *args, **kwargs):
3540 self.history = kwargs.pop("history", [])
3541 self.historyCallBack = None
3542 if callable(self.history):
3543 self.historyCallBack = self.history
3544 self.history = []
3545 name = kwargs.pop("name", "fileBrowseButtonWithHistory")
3546 filebrowse.FileBrowseButton.__init__(self, *args, **kwargs)
3547 self.SetName(name)
3548 self.Bind(wx.EVT_SET_FOCUS, self.OnSetFocus)
3549 if "__WXGTK__" in wx.PlatformInfo and wx.VERSION < (2, 9):
3550 self.textControl.Bind(wx.EVT_KEY_DOWN, self.OnKeyDown)
3551 self.browseButton.Bind(wx.EVT_KEY_DOWN, self.OnKeyDown)
3552
3553 def OnSetFocus(self, event):
3554 """Handle focus events for the text control and browse button.
3555
3556 Args:
3557 event (wx.FocusEvent): The focus event triggered by a control
3558 gaining focus.
3559 """
3560 if event.EventObject is self:
3561 floatspin.focus_next_keyboard_focusable_control(self)
3562 event.Skip()
3563
3564 def OnKeyDown(self, event):
3565 """Handle key down events for the text control and browse button.
3566
3567 Args:
3568 event (wx.KeyEvent): The key event triggered by a key press.
3569 """
3570 if event.KeyCode == wx.WXK_TAB:
3571 floatspin.focus_next_keyboard_focusable_control(event.EventObject)
3572 else:
3573 event.Skip()
3574
3575 def Disable(self):
3576 """Disable the text control and browse button."""
3577 self.Enable(False)
3578
3579 def Enable(self, enable=True):
3580 """Enable or disable the text control and browse button.
3581
3582 Args:
3583 enable (bool): Whether to enable the controls. Defaults to True.
3584 """
3585 self.textControl.Enable(enable and self.history != [""])
3586 self.browseButton.Enable(enable)
3587
3588 def GetName(self, path):
3589 """Return a name for a path. Return value may be a translated string.
3590
3591 Args:
3592 path (str): The file path to get the name for.
3593
3594 Returns:
3595 str: The name of the file or ICC profile, possibly translated.
3596 """
3597 name = None
3598 if os.path.splitext(path)[1].lower() in (".icc", ".icm"):
3599 try:
3600 profile = ICCProfile(path)
3601 except (OSError, ICCProfileInvalidError):
3602 pass
3603 else:
3604 name = profile.getDescription()
3605 if not name:
3606 name = os.path.basename(path)
3607 return lang.getstr(name)
3608
3609 def GetValue(self):
3610 """Retrieve current value of text control."""
3611 if self.textControl.GetSelection() > -1:
3612 return self.history[self.textControl.GetSelection()]
3613 return ""
3614
3615 GetPath = GetValue
3616
3617 def OnChanged(self, evt):
3618 """Handle changes in the text control.
3619
3620 Args:
3621 evt (wx.Event): The event triggered by a change in the text control.
3622 """
3623 self.textControl.SetToolTipString(self.history[self.textControl.GetSelection()])
3624 if self.callCallback and self.changeCallback:
3625 self.changeCallback(evt)
3626
3627 def SetBackgroundColour(self, color):
3628 """Set the background color of the panel.
3629
3630 Args:
3631 color (wx.Colour): The color to set as background.
3632 """
3633 wx.Panel.SetBackgroundColour(self, color)
3634
3635 def SetHistory(self, value=None, selectionIndex=None, control=None):
3636 """Set the current history list.
3637
3638 Args:
3639 value (tuple | list, optional): A list of paths to set as history.
3640 selectionIndex (int, optional): The index to select in the history.
3641 control (wx.Choice, optional): The control to set the history on.
3642 Defaults to None, which uses the textControl.
3643 """
3644 if value is None:
3645 value = ()
3646
3647 if control is None:
3648 control = self.textControl
3649 if self.history == value:
3650 return
3651 value = list(value)
3652
3653 if os.getenv("XDG_SESSION_TYPE") == "wayland":
3654 # When the number of items in a dropdown popup menu exceeds
3655 # the available display client area height, the popup menu
3656 # gets shown at weird positions or not at all under Wayland.
3657 # Work-around this wx bug by truncating the choices. Yuck.
3658
3659 # Text height multiplier of 1.6 matches default popup menu item
3660 # height under GNOME
3661 line_height = math.ceil(control.GetTextExtent("69Gg")[1] * 1.6)
3662
3663 # Find smallest display client area height
3664 max_height = sys.maxsize
3665 for i in range(wx.Display.GetCount()):
3666 max_height = min(wx.Display(i).ClientArea[3], max_height)
3667
3668 # Check if combined height of items exceeds available client area.
3669 # Account for possible current value which is not in list and
3670 # for GNOME top bar (assume item height for the latter).
3671 if line_height * len(value) + 2 > max_height:
3672 max_entries = int(max_height / line_height) - 2
3673 print(
3674 "Discarding entries to work around wxGTK Wayland "
3675 "dropdown popup menu bug:",
3676 ", ".join(value[max_entries:]),
3677 )
3678 value = value[:max_entries]
3679
3680 index = control.GetSelection()
3681 tempValue = self.history[index] if self.history and index > -1 else ""
3682 self.history = []
3683 control.Clear()
3684 for path in [*value, tempValue]:
3685 if path:
3686 self.history.append(path)
3687 control.Append(self.GetName(path))
3688 self.setupControl(selectionIndex, control)
3689
3690 def SetMaxFontSize(self, pointsize=11):
3691 """Set the maximum font size for the text control.
3692
3693 Args:
3694 pointsize (int): The maximum point size for the font. Defaults to 11.
3695 """
3696 self.textControl.SetMaxFontSize(pointsize)
3697
3698 def SetValue(self, value, callBack=1, clear_on_empty_value=False):
3699 """Set the current value of the text control.
3700
3701 Args:
3702 value (str): The value to set in the text control.
3703 callBack (bool): Whether to call the change callback. Defaults to 1.
3704 clear_on_empty_value (bool): Whether to clear the history if the value
3705 is empty. Defaults to False.
3706 """
3707 if not value and clear_on_empty_value and self.history:
3708 index = self.textControl.GetSelection()
3709 if index > -1:
3710 self.history.pop(index)
3711 self.textControl.Delete(index)
3712 if value not in self.history:
3713 self.history.append(value)
3714 self.textControl.Append(self.GetName(value))
3715 self.setupControl(self.history.index(value))
3716 if callBack:
3717 self.changeCallback(CustomEvent(wx.EVT_CHOICE.typeId, self.textControl))
3718
3719 def SetPath(self, path):
3720 """Set the current path in the text control.
3721
3722 Args:
3723 path (str): The path to set in the text control.
3724 """
3725 self.SetValue(path, 0, clear_on_empty_value=True)
3726
3727 def createBrowseButton(self):
3728 """Create the browse-button control."""
3729 button = GenBitmapButton(
3730 self, -1, get_icon(16, "document-open"), style=wx.NO_BORDER
3731 )
3732 if sys.platform == "win32":
3733 button.BackgroundColour = self.BackgroundColour
3734 button.SetToolTipString(self.toolTip)
3735 button.Bind(wx.EVT_BUTTON, self.OnBrowse)
3736 return button
3737
3738 def createDialog(self, parent, id, pos, size, style, name=None): # noqa: A002
3739 """Setup the graphic representation of the dialog.
3740
3741 Args:
3742 parent (wx.Window): The parent window.
3743 id (int): The identifier for the dialog.
3744 pos (tuple): The position of the dialog.
3745 size (tuple): The size of the dialog.
3746 style (int): The style of the dialog.
3747 name (str, optional): The name of the dialog. Defaults to None.
3748 """
3749 wx.Panel.__init__(self, parent, id, pos, size, style)
3750 self.SetMinSize(size) # play nice with sizers
3751 if sys.platform == "win32":
3752 self.BackgroundColour = parent.BackgroundColour
3753
3754 box = wx.BoxSizer(wx.HORIZONTAL)
3755
3756 self.textControl = self.createTextControl()
3757 if sys.platform == "darwin" and wx.VERSION > (2, 9):
3758 # Prevent 1px cut-off at left-hand side
3759 box.Add((1, 1))
3760 box.Add(self.textControl, 1, wx.ALIGN_CENTER_VERTICAL | wx.TOP | wx.BOTTOM, 4)
3761
3762 self.browseButton = self.createBrowseButton()
3763 box.Add(self.browseButton, 0, wx.ALIGN_CENTER_VERTICAL | wx.LEFT, 8)
3764 if self.history:
3765 history = self.history
3766 self.history = []
3767 self.SetHistory(history)
3768
3769 self.SetAutoLayout(True)
3770 self.SetSizer(box)
3771 self.Layout()
3772
3773 def createLabel(self):
3774 """Create the label control."""
3775 return (0, 0)
3776
3777 def createTextControl(self):
3778 """Create the text control."""
3779 textControl = wx.Choice(self, -1)
3780 textControl.Bind(wx.EVT_SET_FOCUS, self.OnSetFocus)
3781 if self.changeCallback:
3782 textControl.Bind(wx.EVT_CHOICE, self.OnChanged)
3783 return textControl
3784
3785 def setupControl(self, selectionIndex=None, control=None):
3786 """Setup the text control with the current history.
3787
3788 Args:
3789 selectionIndex (int, optional): The index of the item to select. If
3790 selectionIndex is None, the last item in the history will be
3791 selected.
3792 control (wx.Choice, optional): The control to set up. If control is
3793 None, self.textControl will be used. Defaults to
3794 self.textControl.
3795 """
3796 if control is None:
3797 control = self.textControl
3798 if selectionIndex is None:
3799 selectionIndex = len(self.history) - 1
3800 control.SetSelection(selectionIndex)
3801 toolTip = self.history[selectionIndex] if selectionIndex > -1 else self.toolTip
3802 control.SetToolTipString(toolTip)
3803 control.Enable(self.browseButton.Enabled and self.history != [""])
3804
3805
3806 class PathDialog(ConfirmDialog):
3807 """A dialog that allows the user to select a file or directory.
3808
3809 Args:
3810 parent (wx.Window): The parent window.
3811 msg (str): The message to display in the dialog.
3812 name (str): The name of the dialog.
3813 """
3814
3815 def __init__(self, parent: wx.Window, msg: str = "", name: str = "pathdialog"):
3816 ConfirmDialog.__init__(
3817 self,
3818 parent,
3819 msg=msg,
3820 ok=lang.getstr("browse"),
3821 cancel=lang.getstr("cancel"),
3822 name=name,
3823 )
3824 self.Bind(wx.EVT_WINDOW_DESTROY, self.OnDestroy)
3825 self.ok.Bind(wx.EVT_BUTTON, self.filedialog_handler)
3826
3827 def OnDestroy(self, event):
3828 """Handle the destruction of the dialog.
3829
3830 Args:
3831 event (wx.Event): The event object.
3832 """
3833 self.filedialog.Destroy()
3834 event.Skip()
3835
3836 return 0
3837
3838 def __getattr__(self, name):
3839 """Redirect all calls to the file dialog."""
3840 return getattr(self.filedialog, name)
3841
3842 def filedialog_handler(self, event):
3843 """Handle the file dialog event."""
3844 self.EndModal(self.filedialog.ShowModal())
3845
3846
3847 _DirDialog = wx.DirDialog
3848
3849
3850 class DirDialog(PathDialog):
3851 """wx.DirDialog alternative that allows programmatic interaction.
3852
3853 wx.DirDialog cannot be interacted with programmatically after
3854 ShowModal(), a functionality we need for scripting.
3855 """
3856
3857 def __init__(self, *args, **kwargs):
3858 PathDialog.__init__(self, *args[0:2], name="dirdialog")
3859 self.filedialog = _DirDialog(self, *args[1:], **kwargs)
3860
3861
3862 _FileDialog = wx.FileDialog
3863
3864
3865 class FileDialog(PathDialog):
3866 """wx.FileDialog alternative that allows programmatic interaction.
3867
3868 wx.FileDialog cannot be interacted with programmatically after
3869 ShowModal(), a functionality we need for scripting.
3870 """
3871
3872 def __init__(self, *args, **kwargs):
3873 PathDialog.__init__(self, *args[0:2], name="filedialog")
3874 self.filedialog = _FileDialog(self, *args[1:], **kwargs)
3875
3876
3877 class FileDrop(_FileDrop):
3878 """Drag'n'drop handler for unsupported files."""
3879
3880 def __init__(self, parent, drophandlers=None):
3881 self.parent = parent
3882 _FileDrop.__init__(self, drophandlers)
3883 self.unsupported_handler = self.drop_unsupported_handler
3884
3885 def drop_unsupported_handler(self):
3886 """Drag'n'drop handler for unsupported files.
3887
3888 Shows an error message.
3889
3890 """
3891 if not hasattr(self.parent, "worker") or not self.parent.worker.is_working():
3892 InfoDialog(
3893 self.parent,
3894 msg=lang.getstr("error.file_type_unsupported")
3895 + "\n\n"
3896 + "\n".join(self._filenames),
3897 ok=lang.getstr("ok"),
3898 bitmap=get_icon(32, "dialog-error"),
3899 )
3900
3901
3902 class FlatShadedButton(GradientButton):
3903 """A button with a flat shaded background.
3904
3905 This is a subclass of wx.BitmapButton that uses a flat shaded background
3906 instead of a gradient.
3907 """
3908
3909 __bitmap = None
3910 _enabled = True
3911
3912 def __init__(
3913 self,
3914 parent,
3915 id=wx.ID_ANY, # noqa: A002
3916 bitmap=None,
3917 label="",
3918 pos=wx.DefaultPosition,
3919 size=wx.DefaultSize,
3920 style=wx.NO_BORDER,
3921 validator=wx.DefaultValidator,
3922 name="gradientbutton",
3923 bgcolour=None,
3924 fgcolour=None,
3925 ):
3926 self.dpiscale = getcfg("app.dpi") / get_default_dpi()
3927 GradientButton.__init__(
3928 self,
3929 parent=parent,
3930 id=id,
3931 bitmap=bitmap,
3932 label=label,
3933 pos=pos,
3934 size=size,
3935 style=style,
3936 validator=validator,
3937 name=name,
3938 )
3939 self._bgcolour = bgcolour # Original bgcolour
3940 self._fgcolour = fgcolour # Original fgcolour
3941 self._setcolours(bgcolour, fgcolour)
3942 self._set_bitmap_labels(self.__bitmap)
3943 self.SetFont(adjust_font_size_for_gcdc(self.GetFont()))
3944 self._update_best_size()
3945
3946 def _set_bitmap_labels(self, bitmap):
3947 if bitmap:
3948 self._bitmapdisabled = get_bitmap_disabled(bitmap)
3949 img = bitmap.ConvertToImage()
3950 img = img.AdjustChannels(1.1, 1.1, 1.1)
3951 bitmap = img.ConvertToBitmap()
3952 else:
3953 self._bitmapdisabled = bitmap
3954 self._bitmaphover = bitmap
3955 self._bitmapselected = bitmap
3956 self._bitmapfocus = bitmap
3957
3958 def _setcolours(self, bgcolour=None, fgcolour=None):
3959 self.BackgroundColour = bgcolour or wx.Colour(0x22, 0x22, 0x22)
3960 self.ForegroundColour = fgcolour or wx.Colour(0x99, 0x99, 0x99)
3961
3962 def Disable(self):
3963 """Disable the button."""
3964 self.Enable(False)
3965
3966 def DoGetBestSize(self):
3967 """Overridden base class virtual.
3968
3969 Determines the best size of the button based on the label and bezel size.
3970 """
3971 if not getattr(self, "_lastBestSize", None):
3972 dummy = "FfGgJjPpYy"
3973 label = self.GetLabel() or dummy
3974
3975 dc = wx.MemoryDC(wx.EmptyBitmap(1, 1))
3976 with contextlib.suppress(Exception):
3977 dc = wx.GCDC(dc)
3978 dc.SetFont(self.GetFont())
3979 retWidth, retHeight = dc.GetTextExtent(label)
3980 if label == dummy:
3981 retWidth = 0
3982 elif wx.VERSION < (2, 9):
3983 retWidth += 5
3984
3985 bmpWidth = bmpHeight = 0
3986 if self._bitmap:
3987 if label != dummy:
3988 constant = 10
3989 if wx.VERSION < (2, 9):
3990 retWidth += 5
3991 else:
3992 constant = 0
3993 # Pin the bitmap height to 10
3994 bmpWidth, bmpHeight = (
3995 self._bitmap.GetWidth() + constant * self.dpiscale,
3996 10 * self.dpiscale,
3997 )
3998 retWidth += bmpWidth
3999 retHeight = max(bmpHeight, retHeight)
4000
4001 self._lastBestSize = wx.Size(
4002 int(retWidth + 25 * self.dpiscale), int(retHeight + 15 * self.dpiscale)
4003 )
4004 return self._lastBestSize
4005
4006 def OnGainFocus(self, event):
4007 """Handle the ``wx.EVT_SET_FOCUS`` event.
4008
4009 Args:
4010 event (wx.FocusEvent): A `wx.FocusEvent` event to be processed.
4011 """
4012 self._hasFocus = True
4013 self._mouseAction = HOVER
4014 self.Refresh()
4015 self.Update()
4016
4017 def OnLoseFocus(self, event):
4018 """Handle the ``wx.EVT_LEAVE_WINDOW`` event.
4019
4020 Args:
4021 event (wx.MouseEvent): A `wx.MouseEvent` event to be processed.
4022 """
4023 self._hasFocus = False
4024 pos = wx.GetMousePosition()
4025 if self.IsShownOnScreen() and not self.ClientRect.Contains(
4026 self.ScreenToClient(pos)
4027 ):
4028 # Note: ScreenToClient will only work if top level parent is shown
4029 self._mouseAction = None
4030 self.Refresh()
4031 event.Skip()
4032
4033 def OnPaint(self, event):
4034 """Handle the ``wx.EVT_PAINT`` event.
4035
4036 Args:
4037 event (wx.PaintEvent): A `wx.PaintEvent` event to be processed.
4038 """
4039 if sys.platform != "win32":
4040 # AutoBufferedPaintDCFactory is the magic needed for crisp text
4041 # rendering in HiDPI mode under OS X and Linux
4042 cls = wx.AutoBufferedPaintDCFactory
4043 else:
4044 cls = wx.BufferedPaintDC
4045 dc = cls(self)
4046 gc = wx.GraphicsContext.Create(dc)
4047 parent = self.GetParent()
4048 if not parent:
4049 return
4050 dc.SetBackground(wx.Brush(parent.BackgroundColour))
4051 dc.Clear()
4052
4053 clientRect = self.GetClientRect()
4054 capture = wx.Window.GetCapture()
4055
4056 x, y, width, height = clientRect
4057
4058 fgcolour = self.ForegroundColour
4059
4060 if capture != self:
4061 if self._mouseAction == HOVER or self._hasFocus:
4062 fill = self.LightColour(self.BackgroundColour, 3)
4063 fgcolour = self.LightColour(fgcolour, 15)
4064 else:
4065 fill = self.BackgroundColour
4066
4067 shadowOffset = 0
4068 else:
4069 fill = self.LightColour(self.BackgroundColour, 3)
4070
4071 shadowOffset = 1
4072
4073 gc.SetPen(wx.TRANSPARENT_PEN)
4074 gc.SetBrush(wx.Brush(fill))
4075 gc.DrawRoundedRectangle(x, y, width, height, 8 * self.dpiscale)
4076
4077 if self._enabled:
4078 if capture != self:
4079 if self._mouseAction == HOVER:
4080 bitmap = self._bitmaphover
4081 else:
4082 bitmap = self._bitmap
4083 else:
4084 bitmap = self._bitmapselected
4085 else:
4086 bitmap = self._bitmapdisabled
4087
4088 font = gc.CreateFont(self.GetFont(), fgcolour)
4089 gc.SetFont(font)
4090 label = self.GetLabel()
4091 if label and bitmap:
4092 label = " " + label
4093 # Note: Using self.GetTextExtent instead of gc.GetTextExtent seems
4094 # to fix sporadic segfaults with wxPython Phoenix up to 4.0.0a2
4095 # under Windows (fixed in 4.0.0a3), but self.GetTextExtent is NOT
4096 # an equivalent replacement for gc.GetTextExtent.
4097 tw, th = gc.GetTextExtent(label)
4098
4099 if bitmap:
4100 bw, bh = bitmap.GetWidth(), bitmap.GetHeight()
4101 if tw:
4102 tw += 5
4103 if wx.VERSION < (2, 9):
4104 tw += 5
4105 else:
4106 bw = bh = 0
4107
4108 pos_x = (
4109 width - bw - tw
4110 ) / 2 + shadowOffset # adjust for bitmap and text to centre
4111 if bitmap:
4112 pos_y = (height - bh) / 2 + shadowOffset
4113 gc.DrawBitmap(bitmap, pos_x, pos_y, bw, bh) # draw bitmap if available
4114 pos_x = pos_x + 5 # extra spacing from bitmap
4115
4116 gc.DrawText(
4117 label, pos_x + bw + shadowOffset, (height - th) / 2 - 0.5 + shadowOffset
4118 )
4119
4120 @property
4121 def BitmapLabel(self):
4122 """Get the bitmap label for the button.
4123
4124 Returns:
4125 wx.Bitmap: The bitmap currently set as the label.
4126 """
4127 return self._bitmap
4128
4129 @BitmapLabel.setter
4130 def BitmapLabel(self, bitmap):
4131 """Set the bitmap label for the button.
4132
4133 Args:
4134 bitmap (wx.Bitmap): The bitmap to set as the label.
4135 """
4136 self.SetBitmap(bitmap)
4137
4138 def Enable(self, enable=True):
4139 """Enable or disable the button.
4140
4141 Args:
4142 enable (bool): If True, the button is enabled; otherwise, it is disabled.
4143 """
4144 if enable:
4145 # Restore original colors
4146 self._setcolours(self._bgcolour, self._fgcolour)
4147 else:
4148 # Dim
4149 self._setcolours(wx.Colour(0x40, 0x40, 0x40), wx.Colour(0x66, 0x66, 0x66))
4150 GradientButton.Enable(self, enable)
4151 self._enabled = enable
4152
4153 @property
4154 def _bitmap(self):
4155 return self.__bitmap
4156
4157 @_bitmap.setter
4158 def _bitmap(self, bitmap):
4159 if bitmap is not self.__bitmap:
4160 self.__bitmap = bitmap
4161 self._set_bitmap_labels(bitmap)
4162
4163 def SetBitmap(self, bitmap):
4164 """Set the bitmap to be used for the button.
4165
4166 Args:
4167 bitmap (wx.Bitmap): The bitmap to set for the button.
4168 """
4169 self._bitmap = bitmap
4170 self._update_best_size()
4171 self.Refresh()
4172
4173 def SetBitmapDisabled(self, bitmap):
4174 """Set the bitmap to be used when the button is disabled.
4175
4176 Args:
4177 bitmap (wx.Bitmap): The bitmap to set for the disabled state.
4178 """
4179 self._bitmapdisabled = bitmap
4180 self._update_best_size()
4181 self.Refresh()
4182
4183 def SetBitmapFocus(self, bitmap):
4184 """Set the bitmap to be used when the button has focus.
4185
4186 Args:
4187 bitmap (wx.Bitmap): The bitmap to set for the focus state.
4188 """
4189 self._bitmapfocus = bitmap
4190 self._update_best_size()
4191 self.Refresh()
4192
4193 def SetBitmapHover(self, bitmap):
4194 """Set the bitmap to be used when the button is hovered.
4195
4196 Args:
4197 bitmap (wx.Bitmap): The bitmap to set for the hover state.
4198 """
4199 self._bitmaphover = bitmap
4200 self._update_best_size()
4201 self.Refresh()
4202
4203 def SetBitmapSelected(self, bitmap):
4204 """Set the bitmap to be used when the button is selected.
4205
4206 Args:
4207 bitmap (wx.Bitmap): The bitmap to set for the selected state.
4208 """
4209 self._bitmapselected = bitmap
4210 self._update_best_size()
4211 self.Refresh()
4212
4213 def SetLabel(self, label):
4214 """Set the label of the button.
4215
4216 Args:
4217 label (str): The label to set for the button.
4218 """
4219 wx.PyControl.SetLabel(self, label)
4220 self._update_best_size()
4221
4222 def _update_best_size(self):
4223 if hasattr(self, "_lastBestSize"):
4224 del self._lastBestSize
4225 self.MinSize = self.DoGetBestSize()
4226
4227 Label = property(wx.PyControl.GetLabel, SetLabel)
4228
4229
4230 class BorderGradientButton(GradientButton):
4231 """A button with a gradient background and border."""
4232
4233 def __init__(
4234 self,
4235 parent,
4236 id=wx.ID_ANY, # noqa: A002
4237 bitmap=None,
4238 label="",
4239 pos=wx.DefaultPosition,
4240 size=wx.DefaultSize,
4241 style=wx.NO_BORDER,
4242 validator=wx.DefaultValidator,
4243 name="gradientbutton",
4244 ):
4245 self.dpiscale = getcfg("app.dpi") / get_default_dpi()
4246 self.use_sierra_style = sys.platform == "darwin"
4247 self._enabled = True
4248 GradientButton.__init__(
4249 self,
4250 parent=parent,
4251 id=id,
4252 bitmap=bitmap,
4253 label=label,
4254 pos=pos,
4255 size=size,
4256 style=style,
4257 validator=validator,
4258 name=name,
4259 )
4260 self.SetFont(adjust_font_size_for_gcdc(self.GetFont()))
4261 self._bitmapdisabled = self._bitmap
4262 self._bitmapfocus = self._bitmap
4263 self._bitmaphover = self._bitmap
4264 self._bitmapselected = self._bitmap
4265 set_bitmap_labels(self, focus=False)
4266 if self.use_sierra_style:
4267 # Use Sierra-like color scheme
4268 sel = self._bitmap.ConvertToImage()
4269 sel.Invert()
4270 self.SetBitmapFocus(sel.ConvertToBitmap())
4271 sel = sel.AdjustChannels(1, 1, 1, 0.8)
4272 sel = sel.ConvertToBitmap()
4273 self.SetBitmapSelected(sel)
4274
4275 BitmapLabel = property(
4276 lambda self: self._bitmap, lambda self, bitmap: self.SetBitmap(bitmap)
4277 )
4278
4279 def DarkColour(self, colour, percent):
4280 """Return dark contrast of `colour`.
4281
4282 The colour returned is from the scale of `colour` ==> white.
4283
4284 Args:
4285 colour (wx.Colour): The input colour to be brightened;
4286 percent (float): Determines how dark the colour will be.
4287 `percent` = 100 returns black, `percent` = 0 returns `colour`.
4288
4289 Returns:
4290 wx.Colour: A darkened version of `colour`.
4291 """
4292 rd = colour.Red()
4293 gd = colour.Green()
4294 bd = colour.Blue()
4295 high = 100
4296
4297 # We take the percent way of the colour from colour -. black
4298 i = percent
4299 r = ((i * rd * 100) / high) / 100
4300 g = ((i * gd * 100) / high) / 100
4301 b = ((i * bd * 100) / high) / 100
4302
4303 return wx.Colour(int(r), int(g), int(b))
4304
4305 def Disable(self):
4306 """Disable the button."""
4307 self.Enable(False)
4308
4309 def DoGetBestSize(self):
4310 """Determine the best size of the button based on the label and bezel size.
4311
4312 Returns:
4313 wx.Size: The best size for the button, taking into account the label
4314 and bitmap size. If no label is set, returns a default size.
4315 """
4316 label = self.GetLabel()
4317 if not label:
4318 return wx.Size(112, 48)
4319
4320 dc = wx.MemoryDC(wx.EmptyBitmap(1, 1))
4321 with contextlib.suppress(Exception):
4322 dc = wx.GCDC(dc)
4323 dc.SetFont(self.GetFont())
4324 retWidth, retHeight = dc.GetTextExtent(label)
4325
4326 bmpWidth = bmpHeight = 0
4327 constant = 15 * self.dpiscale
4328 if self._bitmap:
4329 bmpWidth, bmpHeight = (
4330 self._bitmap.GetWidth() + 20 * self.dpiscale,
4331 self._bitmap.GetHeight(),
4332 )
4333 retWidth += bmpWidth
4334 retHeight = max(bmpHeight, retHeight)
4335
4336 return wx.Size(int(retWidth + constant), int(retHeight + constant))
4337
4338 def Enable(self, enable=True):
4339 """Enable or disable the button.
4340
4341 Args:
4342 enable (bool): If True, the button is enabled; if False, it is
4343 disabled.
4344 """
4345 self._enabled = enable
4346 GradientButton.Enable(self, enable)
4347 self.Update()
4348
4349 def IsEnabled(self):
4350 """Check if the button is enabled.
4351
4352 Returns:
4353 bool: True if the button is enabled, False otherwise.
4354 """
4355 return self._enabled
4356
4357 Enabled = property(IsEnabled, Enable)
4358
4359 def OnPaint(self, event):
4360 """Handle the ``wx.EVT_PAINT`` event.
4361
4362 Args:
4363 event (wx.PaintEvent): a `wx.PaintEvent` event to be processed.
4364 """
4365 if sys.platform != "win32":
4366 # AutoBufferedPaintDCFactory is the magic needed for crisp text
4367 # rendering in HiDPI mode under OS X and Linux
4368 cls = wx.AutoBufferedPaintDCFactory
4369 else:
4370 cls = wx.BufferedPaintDC
4371 dc = cls(self)
4372 gc = wx.GraphicsContext.Create(dc)
4373 parent = self.GetParent()
4374 if not parent:
4375 return
4376 dc.SetBackground(wx.Brush(parent.GetBackgroundColour()))
4377 dc.Clear()
4378
4379 clientRect = self.GetClientRect()
4380 gradientRect = wx.Rect(*clientRect)
4381 capture = wx.Window.GetCapture()
4382
4383 x, y, width, height = clientRect
4384
4385 gradientRect.SetHeight(
4386 int(gradientRect.GetHeight() / 2 + (((capture == self and [1]) or [0])[0]))
4387 )
4388
4389 fgcolor = self.ForegroundColour
4390
4391 # Determine fill color based on state and platform
4392 if self.use_sierra_style:
4393 # Use Sierra-like color scheme
4394 if capture == self and self._mouseAction in (CLICK, HOVER):
4395 # Pressed/selected state
4396 topStart = wx.Colour(*gamma_encode(74, 150, 253))
4397 topEnd = wx.Colour(*gamma_encode(8, 103, 221))
4398 fgcolor = wx.Colour(255, 255, 255, 204)
4399 elif capture != self and self._hasFocus:
4400 # Focus state
4401 topStart = wx.Colour(*gamma_encode(105, 177, 250))
4402 topEnd = wx.Colour(*gamma_encode(12, 128, 255))
4403 # fgcolor = wx.WHITE
4404 fgcolor = wx.BLACK
4405 else:
4406 # Normal state
4407 topStart = wx.WHITE
4408 topEnd = wx.WHITE
4409 fgcolor = wx.BLACK
4410 elif capture != self:
4411 # Normal, hover or focus state
4412 if self._mouseAction == HOVER:
4413 # Hover state
4414 topStart = self._pressedTopColour
4415 topEnd = self._pressedBottomColour
4416 topStart = wx.Colour(topStart.red, topStart.green, topStart.blue, 25)
4417 topEnd = wx.Colour(topEnd.red, topEnd.green, topEnd.blue, 25)
4418 else:
4419 # Normal or focus state
4420 topStart, topEnd = self._topStartColour, self._bottomEndColour
4421 else:
4422 # Pressed/selected state
4423 topStart = self._pressedTopColour
4424 topEnd = self._pressedBottomColour
4425 topStart = wx.Colour(topStart.red, topStart.green, topStart.blue, 51)
4426 topEnd = wx.Colour(topEnd.red, topEnd.green, topEnd.blue, 51)
4427
4428 # Determine border color and width based on state and platform
4429 borderwidth = 1
4430 if self.use_sierra_style:
4431 # Use Sierra-like color scheme
4432 if capture == self and self._mouseAction in (CLICK, HOVER):
4433 # Pressed/selected state
4434 bordercolor_top = wx.Colour(*gamma_encode(35, 125, 254))
4435 bordercolor = wx.Colour(*gamma_encode(2, 63, 221))
4436 elif capture != self and self._hasFocus:
4437 # Focus state
4438 bordercolor_top = wx.Colour(*gamma_encode(74, 160, 249))
4439 bordercolor = wx.Colour(*gamma_encode(4, 95, 255))
4440 else:
4441 # Normal state
4442 # bordercolor_top = wx.Colour(*gamma_encode(200, 200, 200))
4443 # bordercolor = wx.Colour(*gamma_encode(172, 172, 172))
4444 if sys.platform == "darwin":
4445 bordercolor_top = wx.Colour(*gamma_encode(0, 0, 0, 55))
4446 else:
4447 bordercolor_top = wx.Colour(*gamma_encode(0, 0, 0, 11))
4448 bordercolor = wx.Colour(*gamma_encode(0, 0, 0, 83))
4449 else:
4450 # Normal, hover, focus or pressed/selected state
4451 if self._mouseAction == HOVER or self._hasFocus:
4452 # Hover, focus or pressed/selected state
4453 bordercolor = wx.SystemSettings.GetColour(wx.SYS_COLOUR_HIGHLIGHT)
4454 if (
4455 sys.platform == "win32"
4456 and capture != self
4457 and self._mouseAction != HOVER
4458 ):
4459 # Focus state
4460 borderwidth = 2
4461 else:
4462 # Normal state
4463 bordercolor = wx.SystemSettings.GetColour(wx.SYS_COLOUR_3DSHADOW)
4464 if capture == self:
4465 # Pressed/selected state
4466 bordercolor = self.DarkColour(bordercolor, 71)
4467
4468 if not self.IsEnabled():
4469 fgcolor = wx.Colour(fgcolor.red, fgcolor.green, fgcolor.blue, 102)
4470 bordercolor.Set(
4471 bordercolor.red,
4472 bordercolor.green,
4473 bordercolor.blue,
4474 round(bordercolor.alpha * 153 / 255.0),
4475 )
4476
4477 brush = gc.CreateLinearGradientBrush(0, 1, 0, height - 1, topStart, topEnd)
4478 gc.SetBrush(brush)
4479
4480 if self.use_sierra_style:
4481 # Use Sierra-like color scheme
4482 # shadowcolor = wx.Colour(*gamma_encode(228, 228, 228))
4483 if sys.platform == "darwin":
4484 shadowcolor = wx.Colour(*gamma_encode(0, 0, 0, 8))
4485 else:
4486 shadowcolor = wx.Colour(*gamma_encode(0, 0, 0, 19))
4487
4488 # Draw Sierra-like shadow
4489 gc.SetPen(wx.Pen(shadowcolor))
4490 gc.DrawRoundedRectangle(
4491 borderwidth,
4492 borderwidth,
4493 width - 2 - borderwidth,
4494 height - 1 - borderwidth,
4495 (height - 1 - borderwidth) / 2.0,
4496 )
4497
4498 # Draw borders
4499 gc.SetPen(wx.Pen(bordercolor))
4500 gc.DrawRoundedRectangle(
4501 borderwidth,
4502 borderwidth,
4503 width - 2 - borderwidth,
4504 height - 2 - borderwidth,
4505 (height - 2 - borderwidth) / 2.0,
4506 )
4507 gc.SetPen(wx.Pen(bordercolor_top))
4508 gc.DrawRoundedRectangle(
4509 borderwidth,
4510 borderwidth,
4511 width - 2 - borderwidth,
4512 height - 2 - borderwidth * 2,
4513 (height - 2 - borderwidth * 2) / 2.0,
4514 )
4515
4516 # Draw fill
4517 gc.SetPen(wx.TRANSPARENT_PEN)
4518 gc.DrawRoundedRectangle(
4519 borderwidth * 2,
4520 borderwidth * 2,
4521 width - 2 - borderwidth * 2,
4522 height - 2 - borderwidth * 2,
4523 (height - 2 - borderwidth * 2) / 2.0,
4524 )
4525 else:
4526 # Draw border and fill
4527 gc.SetPen(wx.Pen(bordercolor, borderwidth))
4528 gc.DrawRoundedRectangle(
4529 borderwidth,
4530 borderwidth,
4531 width - 2 - borderwidth,
4532 height - 2 - borderwidth,
4533 (height - 2 - borderwidth) / 2.0,
4534 )
4535
4536 shadowOffset = 0
4537
4538 font = gc.CreateFont(self.GetFont(), fgcolor)
4539 gc.SetFont(font)
4540 label = self.GetLabel()
4541 if label and self._bitmap:
4542 label = " " + label
4543 # Note: Using self.GetTextExtent instead of gc.GetTextExtent seems
4544 # to fix sporadic segfaults with wxPython Phoenix up to 4.0.0a2
4545 # under Windows (fixed in 4.0.0a3), but self.GetTextExtent is NOT
4546 # an equivalent replacement for gc.GetTextExtent.
4547 tw, th = gc.GetTextExtent(label)
4548
4549 if self._bitmap:
4550 bw, bh = self._bitmap.GetWidth(), self._bitmap.GetHeight()
4551 if tw:
4552 tw += 5
4553 if wx.VERSION < (2, 9):
4554 tw += 5
4555 else:
4556 bw = bh = 0
4557
4558 # adjust for bitmap and text to centre
4559 pos_x = (width - bw - tw) / 2 + shadowOffset
4560 if self.IsEnabled():
4561 if capture == self and self._mouseAction in (CLICK, HOVER):
4562 bitmap = self._bitmapselected
4563 elif capture != self and self._hasFocus:
4564 bitmap = self._bitmapfocus
4565 elif self._mouseAction == HOVER and not get_dialogs(True):
4566 bitmap = self._bitmapfocus # self._bitmaphover
4567 else:
4568 bitmap = self._bitmapfocus # self._bitmap
4569 else:
4570 bitmap = self._bitmapfocus # self._bitmapdisabled
4571 if bitmap:
4572 pos_y = (height - bh) / 2 + shadowOffset
4573 gc.DrawBitmap(bitmap, pos_x, pos_y, bw, bh) # draw bitmap if available
4574 pos_x = pos_x + 4 # extra spacing from bitmap
4575
4576 gc.DrawText(
4577 label, pos_x + bw + shadowOffset, (height - th) / 2.0 - 1 + shadowOffset
4578 )
4579
4580 def SetBitmap(self, bitmap):
4581 """Set the bitmap to be used for the button.
4582
4583 Args:
4584 bitmap (wx.Bitmap): The bitmap to be used for the button.
4585 """
4586 self._bitmap = bitmap
4587
4588 def SetBitmapDisabled(self, bitmap):
4589 """Set the bitmap to be used when the button is disabled.
4590
4591 Args:
4592 bitmap (wx.Bitmap): The bitmap to be used when the button is disabled.
4593 """
4594 self._bitmapdisabled = bitmap
4595
4596 def SetBitmapFocus(self, bitmap):
4597 """Set the bitmap to be used when the button has focus.
4598
4599 Args:
4600 bitmap (wx.Bitmap): The bitmap to be used when the button has focus.
4601 """
4602 self._bitmapfocus = bitmap
4603
4604 def SetBitmapHover(self, bitmap):
4605 """Set the bitmap to be used when the button is hovered.
4606
4607 Args:
4608 bitmap (wx.Bitmap): The bitmap to be used when the button is hovered.
4609 """
4610 self._bitmaphover = bitmap
4611
4612 def SetBitmapSelected(self, bitmap):
4613 """Set the bitmap to be used when the button is selected.
4614
4615 Args:
4616 bitmap (wx.Bitmap): The bitmap to be used when the button is selected.
4617 """
4618 self._bitmapselected = bitmap
4619
4620 def Update(self):
4621 """Update the button's appearance."""
4622
4623
4624 class CustomGrid(wx.grid.Grid):
4625 """Handle some wxPython bugs and provide some additional functionality."""
4626
4627 def __init__(self, *args, **kwargs):
4628 wx.grid.Grid.__init__(self, *args, **kwargs)
4629 self.Bind(wx.EVT_KILL_FOCUS, self.OnKillFocus)
4630 self.Bind(wx.EVT_SIZE, self.OnResize)
4631 self.Bind(wx.grid.EVT_GRID_ROW_SIZE, self.OnResize)
4632 self.Bind(wx.grid.EVT_GRID_COL_SIZE, self.OnResize)
4633 self.Bind(wx.grid.EVT_GRID_CELL_LEFT_CLICK, self.OnCellLeftClick)
4634 self.Bind(wx.grid.EVT_GRID_CELL_LEFT_DCLICK, self.OnCellLeftClick)
4635 self.Bind(wx.EVT_KEY_DOWN, self.OnKeyDown)
4636 self.Bind(wx.grid.EVT_GRID_SELECT_CELL, self.OnCellSelect)
4637 self.Bind(wx.grid.EVT_GRID_LABEL_LEFT_CLICK, self.OnLabelLeftClick)
4638 self.GetGridCornerLabelWindow().Bind(wx.EVT_PAINT, self.OnPaintCornerLabel)
4639 self.GetGridColLabelWindow().Bind(wx.EVT_PAINT, self.OnPaintColLabels)
4640 self.GetGridRowLabelWindow().Bind(wx.EVT_PAINT, self.OnPaintRowLabels)
4641 self.SetDefaultCellAlignment(wx.ALIGN_LEFT, wx.ALIGN_CENTER)
4642 self.SetDefaultCellBackgroundColour(
4643 wx.SystemSettings.GetColour(wx.SYS_COLOUR_WINDOW)
4644 )
4645 self.SetDefaultEditor(CustomCellEditor(self))
4646 self._default_cell_renderer = CustomCellRenderer()
4647 self.SetDefaultRenderer(self._default_cell_renderer)
4648 self.SetRowLabelAlignment(wx.ALIGN_CENTER, wx.ALIGN_CENTER)
4649
4650 self.headerbitmap = None
4651 if sys.platform == "darwin" or "gtk3" in wx.PlatformInfo:
4652 # wxMac draws a too short native header
4653 self.rendernative = False
4654 self.style = "Mavericks"
4655 else:
4656 self.rendernative = True
4657 self.style = ""
4658 self._default_col_label_renderer = CustomColLabelRenderer()
4659 self._default_row_label_renderer = CustomRowLabelRenderer()
4660 self._col_label_renderers = {}
4661 self._overwrite_cell_values = True
4662 self._row_label_renderers = {}
4663 self.alternate_cell_background_color = True
4664 self.alternate_col_label_background_color = False
4665 self.alternate_row_label_background_color = True
4666 self.draw_col_labels = True
4667 self.draw_row_labels = True
4668 self.draw_horizontal_grid_lines = True
4669 self.draw_vertical_grid_lines = True
4670 self.selection_alpha = 1.0
4671 self.show_cursor_outline = True
4672
4673 if not hasattr(wx.grid.Grid, "CalcCellsExposed"):
4674 # wxPython < 2.8.10
4675 def CalcCellsExposed(self, region):
4676 """Calculate the cells that are exposed in the given region.
4677
4678 Args:
4679 region (wx.Region): The region to calculate the exposed cells
4680 for.
4681
4682 Returns:
4683 list: A list of tuples containing the row and column indices of
4684 the exposed cells.
4685 """
4686 rows = self.CalcRowLabelsExposed(region)
4687 cols = self.CalcColLabelsExposed(region)
4688 return [(row, col) for row in rows for col in cols if row > -1 and col > -1]
4689
4690 if not hasattr(wx.grid.Grid, "CalcColLabelsExposed"):
4691 # wxPython < 2.8.10
4692 def CalcColLabelsExposed(self, region):
4693 """Calculate the column labels that are exposed in the given region.
4694
4695 Args:
4696 region (wx.Region): The region to calculate the exposed column
4697 labels for.
4698
4699 Returns:
4700 list: A list of column indices that are exposed in the given
4701 region.
4702 """
4703 x, y = self.CalcUnscrolledPosition((0, 0))
4704 ri = wx.RegionIterator(region)
4705 cols = []
4706 while ri:
4707 rect = ri.GetRect()
4708 rect.Offset((x, 0))
4709 colPos = self.GetColPos(self.XToCol(rect.left))
4710 while self.GetNumberCols() > colPos >= 0:
4711 col = self.GetColAt(colPos)
4712 cl, cr = self.GetColLeftRight(col)
4713 if cr < rect.left:
4714 continue
4715 if cl > rect.right:
4716 break
4717 cols.append(col)
4718 colPos += 1
4719 ri.Next()
4720 return cols
4721
4722 if not hasattr(wx.grid.Grid, "CalcRowLabelsExposed"):
4723 # wxPython < 2.8.10
4724 def CalcRowLabelsExposed(self, region):
4725 """Calculate the row labels that are exposed in the given region.
4726
4727 Args:
4728 region (wx.Region): The region to calculate the exposed row
4729 labels for.
4730
4731 Returns:
4732 list: A list of row indices that are exposed in the given region.
4733 """
4734 x, y = self.CalcUnscrolledPosition((0, 0))
4735 ri = wx.RegionIterator(region)
4736 rows = []
4737 while ri:
4738 rect = ri.GetRect()
4739 rect.Offset((0, y))
4740 row = self.YToRow(rect.top)
4741 while self.GetNumberRows() > row >= 0:
4742 rt, rb = self.GetRowTopBottom(row)
4743 if rb < rect.top:
4744 continue
4745 if rt > rect.bottom:
4746 break
4747 rows.append(row)
4748 row += 1
4749 ri.Next()
4750 return rows
4751
4752 # def AppendCols(self, numCols=1):
4753 # """Override the AppendCols method.
4754 #
4755 # Args:
4756 # numCols (int): The number of columns to append.
4757 # """
4758 # raise NotImplementedError("testing")
4759
4760 def GetColLeftRight(self, col, c=0):
4761 """Get the left and right pixel positions of a column.
4762
4763 Args:
4764 col (int): The column index.
4765 c (int): The column index to start from, defaults to 0.
4766
4767 Returns:
4768 tuple: A tuple containing the left and right pixel positions of the
4769 column.
4770 """
4771 left = 0
4772 while c < col:
4773 left += self.GetColSize(c)
4774 c += 1
4775 right = left + self.GetColSize(col) - 1
4776 return left, right
4777
4778 def GetRowTopBottom(self, row, r=0):
4779 """Get the top and bottom pixel positions of a row.
4780
4781 Args:
4782 row (int): The row index.
4783 r (int): The row index to start from, defaults to 0.
4784
4785 Returns:
4786 tuple: A tuple containing the top and bottom pixel positions of the
4787 row.
4788 """
4789 top = 0
4790 while r < row:
4791 top += self.GetRowSize(r)
4792 r += 1
4793 bottom = top + self.GetRowSize(row) - 1
4794 return top, bottom
4795
4796 def OnCellLeftClick(self, event):
4797 """Handle the ``wx.grid.EVT_GRID_CELL_LEFT_CLICK`` event.
4798
4799 Args:
4800 event (wx.grid.GridEvent): A `wx.grid.GridEvent` event to be
4801 processed.
4802 """
4803 if (
4804 event.CmdDown()
4805 or event.ControlDown()
4806 or event.ShiftDown()
4807 or not isinstance(
4808 self.GetCellEditor(self.GetGridCursorRow(), self.GetGridCursorCol()),
4809 CustomCellEditor,
4810 )
4811 ):
4812 event.Skip()
4813 else:
4814 self.SetGridCursor(event.Row, event.Col)
4815
4816 def OnCellSelect(self, event):
4817 """Handle the ``wx.grid.EVT_GRID_SELECT_CELL`` event.
4818
4819 Args:
4820 event (wx.grid.GridEvent): A `wx.grid.GridEvent` event to be
4821 processed.
4822 """
4823 row, _ = event.GetRow(), event.GetCol()
4824 self._anchor_row = row
4825 self._overwrite_cell_values = True
4826 self.SelectBlock(event.Row, event.Col, event.Row, event.Col)
4827 self.Refresh()
4828 event.Skip()
4829
4830 def OnKeyDown(self, event):
4831 """Handle the ``wx.EVT_KEY_DOWN`` event.
4832
4833 Args:
4834 event (wx.KeyEvent): A `wx.KeyEvent` event to be processed.
4835 """
4836 keycode = event.KeyCode
4837 if event.CmdDown() or event.ControlDown():
4838 # CTRL (Linux/Mac/Windows) / CMD (Mac)
4839 if keycode == 65:
4840 # A
4841 self.SelectAll()
4842 return
4843 if keycode in (67, 88):
4844 # C / X
4845 clip = []
4846 cells = self.GetSelection()
4847 i = -1
4848 start_col = self.GetNumberCols()
4849 for cell in cells:
4850 row = cell[0]
4851 col = cell[1]
4852 if i < row:
4853 clip.append([])
4854 i = row
4855 offset = 0
4856 # Skip cols without label
4857 if self.GetColLabelSize() and not self.GetColLabelValue(col):
4858 offset += 1
4859 continue
4860 start_col = min(start_col, col - offset)
4861 while len(clip[-1]) - 1 < col - offset:
4862 clip[-1].append("")
4863 clip[-1][col - offset] = self.GetCellValue(row, col)
4864 for i, row in enumerate(clip):
4865 clip[i] = "\t".join(row[start_col:])
4866 clipdata = wx.TextDataObject()
4867 clipdata.SetText("\n".join(clip))
4868 wx.TheClipboard.Open()
4869 wx.TheClipboard.SetData(clipdata)
4870 wx.TheClipboard.Close()
4871 return
4872 if keycode == 86 and self.IsEditable():
4873 # V
4874 do = wx.TextDataObject()
4875 wx.TheClipboard.Open()
4876 success = wx.TheClipboard.GetData(do)
4877 wx.TheClipboard.Close()
4878 if success:
4879 lines = do.GetText().splitlines()
4880 for i, line in enumerate(lines):
4881 lines[i] = re.sub(r" +", "\t", line).split("\t")
4882 # Translate from selected cells into a grid with None values
4883 # for not selected cells
4884 grid = []
4885 cells = self.GetSelection()
4886 i = -1
4887 start_col = self.GetNumberCols()
4888 for cell in cells:
4889 row = cell[0]
4890 col = cell[1]
4891 if i < row:
4892 grid.append([])
4893 i = row
4894 offset = 0
4895 # Skip read-only cells and cols without label
4896 if self.IsReadOnly(row, col) or (
4897 self.GetColLabelSize() and not self.GetColLabelValue(col)
4898 ):
4899 offset += 1
4900 continue
4901 start_col = min(start_col, col - offset)
4902 while len(grid[-1]) - 1 < col - offset:
4903 grid[-1].append(None)
4904 grid[-1][col - offset] = cell
4905 for i, row in enumerate(grid):
4906 grid[i] = row[start_col:]
4907 # 'Paste' values from clipboard
4908 self.BeginBatch()
4909 for i, row in enumerate(grid):
4910 for j, cell in enumerate(row):
4911 if (
4912 cell is not None
4913 and len(lines) > i
4914 and len(lines[i]) > j
4915 ):
4916 self.SetCellValue(cell[0], cell[1], lines[i][j])
4917 self.ProcessEvent(
4918 wx.grid.GridEvent(
4919 -1,
4920 wx.grid.EVT_GRID_CELL_CHANGE.evtType[0],
4921 self,
4922 cell[0],
4923 cell[1],
4924 )
4925 )
4926 self.EndBatch()
4927 return
4928 elif self.IsEditable() and not self.IsCurrentCellReadOnly():
4929 if isinstance(
4930 self.GetCellEditor(self.GetGridCursorRow(), self.GetGridCursorCol()),
4931 CustomCellEditor,
4932 ):
4933 ch = None
4934 if keycode in [
4935 wx.WXK_NUMPAD0,
4936 wx.WXK_NUMPAD1,
4937 wx.WXK_NUMPAD2,
4938 wx.WXK_NUMPAD3,
4939 wx.WXK_NUMPAD4,
4940 wx.WXK_NUMPAD5,
4941 wx.WXK_NUMPAD6,
4942 wx.WXK_NUMPAD7,
4943 wx.WXK_NUMPAD8,
4944 wx.WXK_NUMPAD9,
4945 ]:
4946 ch = chr(ord("0") + keycode - wx.WXK_NUMPAD0)
4947 elif keycode in (wx.WXK_NUMPAD_DECIMAL, wx.WXK_NUMPAD_SEPARATOR):
4948 ch = "."
4949 elif 256 > keycode >= 32:
4950 ch = str(chr(keycode))
4951 if ch is not None or keycode in (wx.WXK_BACK, wx.WXK_DELETE):
4952 changed = 0
4953 batch = False
4954 for row, col in self.GetSelection():
4955 if row <= -1 or col <= -1 or self.IsReadOnly(row, col):
4956 continue
4957 if changed and not batch:
4958 self.BeginBatch()
4959 batch = True
4960 if self._overwrite_cell_values or keycode == wx.WXK_DELETE:
4961 value = ""
4962 else:
4963 value = self.GetCellValue(row, col)
4964 if keycode == wx.WXK_BACK:
4965 value = value[:-1]
4966 elif keycode != wx.WXK_DELETE:
4967 value += ch
4968 self.SetCellValue(row, col, value)
4969 self.ProcessEvent(
4970 wx.grid.GridEvent(
4971 -1,
4972 wx.grid.EVT_GRID_CELL_CHANGE.evtType[0],
4973 self,
4974 row,
4975 col,
4976 )
4977 )
4978 changed += 1
4979 if batch:
4980 self.EndBatch()
4981 self._overwrite_cell_values = False
4982 if not changed:
4983 wx.Bell()
4984 return
4985 elif event.KeyCode in (wx.WXK_RETURN, wx.WXK_NUMPAD_ENTER):
4986 self.EnableCellEditControl()
4987 return
4988 event.Skip()
4989
4990 def OnKillFocus(self, event):
4991 """Handle the ``wx.EVT_KILL_FOCUS`` event.
4992
4993 Args:
4994 event (wx.FocusEvent): a `wx.FocusEvent` event to be processed.
4995 """
4996 self.Refresh()
4997 event.Skip()
4998
4999 def OnLabelLeftClick(self, event):
5000 """Handle the ``wx.EVT_GRID_LABEL_LEFT_CLICK`` event.
5001
5002 Args:
5003 event (wx.grid.GridEvent): a `wx.grid.GridEvent` event to be
5004 processed.
5005 """
5006 row, col = event.GetRow(), event.GetCol()
5007 if row == -1 and col > -1:
5008 # Col label clicked
5009 self.SetFocus()
5010 self.SetGridCursor(max(self.GetGridCursorRow(), 0), col)
5011 self.MakeCellVisible(max(self.GetGridCursorRow(), 0), col)
5012 elif col == -1 and row > -1:
5013 # Row label clicked
5014 if self.select_row(
5015 row, event.ShiftDown(), event.ControlDown() or event.CmdDown()
5016 ):
5017 return
5018 event.Skip()
5019
5020 def OnPaintColLabels(self, evt):
5021 """Handle the ``wx.EVT_PAINT`` event for column labels.
5022
5023 Args:
5024 evt (wx.PaintEvent): a `wx.PaintEvent` event to be processed.
5025 """
5026 window = evt.GetEventObject()
5027 dc = wx.PaintDC(window)
5028
5029 try:
5030 cols = self.CalcColLabelsExposed(window.GetUpdateRegion())
5031 except wxAssertionError:
5032 return
5033
5034 if -1 in cols:
5035 return
5036
5037 x, y = self.CalcUnscrolledPosition((0, 0))
5038 pt = dc.GetDeviceOrigin()
5039 dc.SetDeviceOrigin(pt.x - x, pt.y)
5040 leftoffset = 0
5041 for i, col in enumerate(cols):
5042 left, right = self.GetColLeftRight(col, cols[0] if i > 0 else 0)
5043 if i > 0:
5044 left += leftoffset
5045 right += leftoffset
5046 else:
5047 leftoffset = left
5048 rect = wx.Rect()
5049 rect.left = left
5050 rect.right = right
5051 rect.y = 0
5052 rect.height = self.GetColLabelSize()
5053
5054 renderer = self._col_label_renderers.get(
5055 col, self._default_col_label_renderer
5056 )
5057
5058 renderer.Draw(self, dc, rect, col)
5059
5060 def OnPaintCornerLabel(self, evt):
5061 """Handle the ``wx.EVT_PAINT`` event for the corner label.
5062
5063 Args:
5064 evt (wx.PaintEvent): a `wx.PaintEvent` event to be processed.
5065 """
5066 window = evt.GetEventObject()
5067 dc = wx.PaintDC(window)
5068
5069 rect = wx.Rect()
5070 rect.width = self.GetRowLabelSize()
5071 rect.height = self.GetColLabelSize()
5072 rect.x = 0
5073 rect.y = 0
5074 self._default_col_label_renderer.Draw(self, dc, rect)
5075
5076 def OnPaintRowLabels(self, evt):
5077 """Handle the ``wx.EVT_PAINT`` event for row labels.
5078
5079 Args:
5080 evt (wx.PaintEvent): a `wx.PaintEvent` event to be processed.
5081 """
5082 window = evt.GetEventObject()
5083 dc = wx.PaintDC(window)
5084
5085 rows = self.CalcRowLabelsExposed(window.GetUpdateRegion())
5086 if -1 in rows:
5087 return
5088
5089 x, y = self.CalcUnscrolledPosition((0, 0))
5090 pt = dc.GetDeviceOrigin()
5091 dc.SetDeviceOrigin(pt.x, pt.y - y)
5092 topoffset = 0
5093 for i, row in enumerate(rows):
5094 top, bottom = self.GetRowTopBottom(row, rows[0] if i > 0 else 0)
5095 if i > 0:
5096 top += topoffset
5097 bottom += topoffset
5098 else:
5099 topoffset = top
5100 rect = wx.Rect()
5101 rect.top = top
5102 rect.bottom = bottom
5103 rect.x = 0
5104 rect.width = self.GetRowLabelSize()
5105
5106 renderer = self._row_label_renderers.get(
5107 row, self._default_row_label_renderer
5108 )
5109
5110 renderer.Draw(self, dc, rect, row)
5111
5112 def OnResize(self, event):
5113 """Handle the ``wx.EVT_SIZE`` event.
5114
5115 Args:
5116 event (wx.SizeEvent): a `wx.SizeEvent` event to be processed.
5117 """
5118 region = wx.Region(*self.ClientRect.Get())
5119 for row, col in self.CalcCellsExposed(region):
5120 cell_renderer = self.GetCellRenderer(row, col)
5121 if (
5122 isinstance(cell_renderer, CustomCellRenderer)
5123 and cell_renderer._selectionbitmaps
5124 ):
5125 # On resize, we need to tell any CustomCellRenderer that its
5126 # bitmaps are no longer valid and are garbage collected
5127 cell_renderer._selectionbitmaps = {}
5128 event.Skip()
5129
5130 def SetColLabelRenderer(self, col, renderer):
5131 """Register a renderer to be used for drawing the label for the given column.
5132
5133 Args:
5134 col (int): The column index for which to set the renderer.
5135 renderer (CustomColLabelRenderer or None): The renderer to use for
5136 the column label, or None to remove any existing renderer.
5137 """
5138 if renderer is None:
5139 if col in self._col_label_renderers:
5140 del self._col_label_renderers[col]
5141 else:
5142 self._col_label_renderers[col] = renderer
5143
5144 def SetDefaultCellBackgroundColour(self, color):
5145 """Set the default cell background color for the grid.
5146
5147 Args:
5148 color (wx.Colour or str): The color to set as the default cell
5149 background color. If a string is provided, it should be a
5150 valid color name or hex code.
5151 """
5152 # Set alpha to 0 so we can detect the default color
5153 if not isinstance(color, wx.Colour):
5154 color = wx.Colour(color)
5155 color.Set(color.Red(), color.Green(), color.Blue(), 0)
5156 wx.grid.Grid.SetDefaultCellBackgroundColour(self, color)
5157
5158 def SetRowLabelRenderer(self, row, renderer):
5159 """Register a renderer to be used for drawing the label for the given row.
5160
5161 Args:
5162 row (int): The row index for which to set the renderer.
5163 renderer (CustomRowLabelRenderer or None): The renderer to use for
5164 the row label, or None to remove any existing renderer.
5165 """
5166 if renderer is None:
5167 if row in self._row_label_renderers:
5168 del self._row_label_renderers[row]
5169 else:
5170 self._row_label_renderers[row] = renderer
5171
5172 def select_row(self, row, shift=False, ctrl=False):
5173 """Select a row in the grid.
5174
5175 Args:
5176 row (int): The row to select.
5177 shift (bool): If True, extend the selection to the anchor row.
5178 ctrl (bool): If True, toggle the selection of the row.
5179
5180 Returns:
5181 bool: True if the row was deselected, False otherwise.
5182 """
5183 self.SetFocus()
5184 if not shift and not ctrl:
5185 self.SetGridCursor(row, max(self.GetGridCursorCol(), 0))
5186 self.SelectRow(row)
5187 self._anchor_row = row
5188 self.MakeCellVisible(row, max(self.GetGridCursorCol(), 0))
5189 if self.IsSelection():
5190 if shift:
5191 self.BeginBatch()
5192 rows = self.GetSelectionRows()
5193 sel = list(
5194 range(min(self._anchor_row, row), max(self._anchor_row, row) + 1)
5195 )
5196 desel = [i for i in rows if i not in sel]
5197 add = [i for i in sel if i not in rows]
5198 if len(desel) >= len(add):
5199 # in this case deselecting rows will take as long or longer
5200 # than selecting, so use SelectRow to speed up the operation
5201 self.SelectRow(row)
5202 else:
5203 for i in desel:
5204 self.DeselectRow(i)
5205 for i in add:
5206 self.SelectRow(i, True)
5207 self.EndBatch()
5208 return False
5209 if ctrl:
5210 if self.IsInSelection(row, 0):
5211 self.DeselectRow(row)
5212 return True
5213 self.SelectRow(row, True)
5214 return False
5215
5216
5217 class CustomCheckBox(wx.Panel):
5218 """A custom checkbox where the label is independent from the checkbox itself.
5219
5220 Works around wxMac not taking into account text (foreground) color on
5221 a default checkbox label.
5222
5223 """
5224
5225 def __init__(
5226 self,
5227 parent,
5228 id=wx.ID_ANY, # noqa: A002
5229 label="",
5230 pos=wx.DefaultPosition,
5231 size=wx.DefaultSize,
5232 style=wx.NO_BORDER,
5233 validator=wx.DefaultValidator,
5234 name="CustomCheckBox",
5235 ):
5236 wx.Panel.__init__(self, parent, id, pos, size, style, name)
5237 self.BackgroundColour = parent.BackgroundColour
5238 self.SetSizer(wx.BoxSizer(wx.HORIZONTAL))
5239 self._cb = wx.CheckBox(self, -1)
5240 self._enabled = True
5241 self.Sizer.Add(self._cb, flag=wx.ALIGN_CENTER_VERTICAL)
5242 if sys.platform == "darwin":
5243 self._label = wx.StaticText(self, -1, "")
5244 self.Sizer.Add(self._label, 1, wx.ALIGN_CENTER_VERTICAL)
5245 self._label.Bind(wx.EVT_LEFT_DOWN, self.OnLeftDown)
5246 self._label.Bind(wx.EVT_LEFT_UP, self.OnLeftUp)
5247 self._up = True
5248 else:
5249 self._label = self._cb
5250 self._label.Label = label
5251
5252 def Bind(self, event_id, handler):
5253 """Bind an event handler to the CustomCheckBox.
5254
5255 Args:
5256 event_id (int): The event ID to bind to.
5257 handler (callable): The event handler to bind.
5258 """
5259 self._cb.Bind(event_id, handler)
5260
5261 def Disable(self):
5262 """Disable the CustomCheckBox."""
5263 self.Enable(False)
5264
5265 def Enable(self, enable=True):
5266 """Enable or disable the CustomCheckBox.
5267
5268 Args:
5269 enable (bool): True to enable the CustomCheckBox, False to disable
5270 it.
5271 """
5272 enable = bool(enable)
5273 if self.Enabled is enable:
5274 return
5275 self._enabled = enable
5276 self._cb.Enable(enable)
5277 if self._label is not self._cb:
5278 if not hasattr(self, "_fgcolor"):
5279 self._fgcolor = self.ForegroundColour
5280 color = self._fgcolor
5281 if not enable:
5282 bgcolor = self.Parent.BackgroundColour
5283 bgblend = 0.5
5284 blend = 0.5
5285 color = wx.Colour(
5286 round(bgblend * bgcolor.Red() + blend * color.Red()),
5287 round(bgblend * bgcolor.Green() + blend * color.Green()),
5288 round(bgblend * bgcolor.Blue() + blend * color.Blue()),
5289 )
5290 self._label.ForegroundColour = color
5291
5292 @property
5293 def Enabled(self):
5294 """Get whether the CustomCheckBox is enabled or not.
5295
5296 Returns:
5297 bool: True if the CustomCheckBox is enabled, False otherwise.
5298 """
5299 return self.IsEnabled()
5300
5301 @Enabled.setter
5302 def Enabled(self, enable=True):
5303 """Enable or disable the CustomCheckBox.
5304
5305 Args:
5306 enable (bool): True to enable the CustomCheckBox, False to disable
5307 it.
5308 """
5309 self.Enable(enable)
5310
5311 def IsEnabled(self):
5312 """Return whether the CustomCheckBox is enabled or not.
5313
5314 Returns:
5315 bool: True if the CustomCheckBox is enabled, False otherwise.
5316 """
5317 return self._enabled
5318
5319 def OnLeftDown(self, event):
5320 """Handle the ``wx.EVT_LEFT_DOWN`` event.
5321
5322 Args:
5323 event (wx.MouseEvent): a `wx.MouseEvent` event to be processed.
5324 """
5325 if not self.Enabled:
5326 return
5327 self._up = False
5328 self._cb.SetFocus()
5329 event.Skip()
5330
5331 def OnLeftUp(self, event):
5332 """Handle the ``wx.EVT_LEFT_UP`` event.
5333
5334 Args:
5335 event (wx.MouseEvent): a `wx.MouseEvent` event to be processed.
5336 """
5337 if not self.Enabled:
5338 return
5339 if not self._up and self.ClientRect.Contains(event.GetPosition()):
5340 # if the checkbox was down when the mouse was released...
5341 self.SendCheckBoxEvent()
5342 self._up = True
5343
5344 def SendCheckBoxEvent(self):
5345 """Actually sends the event to the checkbox."""
5346 self.Value = not self.Value
5347 checkEvent = wx.CommandEvent(
5348 wx.wxEVT_COMMAND_CHECKBOX_CLICKED, self._cb.GetId()
5349 )
5350 checkEvent.SetInt(int(self.Value))
5351
5352 # Set the originating object for the event (the checkbox)
5353 checkEvent.SetEventObject(self._cb)
5354
5355 # Watch for a possible listener of this event that will catch it and
5356 # eventually process it
5357 self._cb.GetEventHandler().ProcessEvent(checkEvent)
5358
5359 def SetMaxFontSize(self, pointsize=11):
5360 """Set the maximum font size for the label.
5361
5362 This is useful to ensure that the label does not grow too large
5363 when the CustomCheckBox is resized.
5364
5365 Args:
5366 pointsize (int): The maximum font size to set for the label.
5367 """
5368 self._label.SetMaxFontSize(pointsize)
5369
5370 def GetValue(self):
5371 """Return the state of CustomCheckBox.
5372
5373 Returns:
5374 bool: True if checked, False otherwise.
5375 """
5376 return self._cb.Value
5377
5378 def IsChecked(self):
5379 """This is just a maybe more readable synonym for GetValue.
5380
5381 Returns:
5382 bool: True if the CustomCheckBox is checked and False otherwise.
5383 """
5384 return self._cb.Value
5385
5386 def SetValue(self, state):
5387 """Set the CustomCheckBox to the given state.
5388
5389 This does not cause a wx.wxEVT_COMMAND_CHECKBOX_CLICKED event to get
5390 emitted.
5391
5392 Args:
5393 state (bool): True to check the CustomCheckBox, False to uncheck it.
5394 """
5395 self._cb.Value = state
5396
5397 def GetLabel(self):
5398 """Get the label of the CustomCheckBox.
5399
5400 Returns:
5401 str: The label of the CustomCheckBox.
5402 """
5403 return self._label.Label
5404
5405 def SetLabel(self, label):
5406 """Set the label of the CustomCheckBox.
5407
5408 Args:
5409 label (str): The label to set for the CustomCheckBox.
5410 """
5411 self._label.Label = label
5412
5413 def SetForegroundColour(self, color):
5414 """Set the foreground colour of the CustomCheckBox label.
5415
5416 Args:
5417 color (wx.Colour or str): The colour to set for the label.
5418 """
5419 wx.Panel.SetForegroundColour(self, color)
5420 self._label.ForegroundColour = color
5421
5422 @property
5423 def Label(self):
5424 """Get the label of the CustomCheckBox.
5425
5426 Returns:
5427 str: The label of the CustomCheckBox.
5428 """
5429 return self.GetLabel()
5430
5431 @Label.setter
5432 def Label(self, label):
5433 """Set the label of the CustomCheckBox.
5434
5435 Args:
5436 label (str): The label to set for the CustomCheckBox.
5437 """
5438 self.SetLabel(label)
5439
5440 @property
5441 def Value(self):
5442 """Get the state of CustomCheckBox.
5443
5444 Returns:
5445 bool: True if checked, False otherwise.
5446 """
5447 return self.GetValue()
5448
5449 @Value.setter
5450 def Value(self, state):
5451 """Set the CustomCheckBox to the given state.
5452
5453 Args:
5454 state (bool): True to check the CustomCheckBox, False to uncheck it.
5455 """
5456 self.SetValue(state)
5457
5458 @property
5459 def ForegroundColour(self):
5460 """Get the foreground colour of the CustomCheckBox label."""
5461 return self.GetForegroundColour()
5462
5463 @ForegroundColour.setter
5464 def ForegroundColour(self, color):
5465 """Set the foreground colour of the CustomCheckBox label."""
5466 self.SetForegroundColour(color)
5467
5468
5469 class CustomCellEditor(wx.grid.PyGridCellEditor):
5470 """Custom cell editor for wxPython grid.
5471
5472 This class is used to edit the cell value. It is used by the CustomGrid class.
5473 """
5474
5475 def __init__(self, grid):
5476 wx.grid.PyGridCellEditor.__init__(self)
5477 self._grid = grid
5478 self._cell_renderer = CustomCellRenderer()
5479
5480 def Create(self, parent, id, evtHandler): # noqa: A002
5481 """Called to create the control, which must derive from wx.Control."""
5482 print(
5483 f"CustomCellEditor.Create({parent!r}, {id!r}, {evtHandler!r}) was called. "
5484 "This should not happen, but is unlikely an issue."
5485 )
5486 self.SetControl(wx.StaticText(parent, -1, ""))
5487
5488 def SetSize(self, rect):
5489 """Called to position/size the edit control within the cell rectangle.
5490
5491 If you don't fill the cell (the rect) then be sure to override
5492 PaintBackground and do something meaningful there.
5493 """
5494 print(
5495 f"CustomCellEditor.SetSize({rect!r}) was called. This should not "
5496 "happen, but is unlikely an issue."
5497 )
5498 self.Control.SetDimensions(
5499 rect.x, rect.y, rect.width, rect.height, wx.SIZE_ALLOW_MINUS_ONE
5500 )
5501
5502 def Show(self, show, attr):
5503 """Show or hide the edit control.
5504
5505 You can use the attr (if not None) to set colours or fonts for the
5506 control.
5507 """
5508 print(
5509 f"CustomCellEditor.Show({show!r}, {attr!r}) was called. This should "
5510 "not happen, but is unlikely an issue."
5511 )
5512 super(self.__class__, self).Show(show, attr)
5513
5514 def PaintBackground(self, dc, rect, attr=None):
5515 """Draw the part of the cell not occupied by the edit control.
5516
5517 The base class version just fills it with background colour from the
5518 attribute. In this class the edit control fills the whole cell so
5519 don't do anything at all in order to reduce flicker.
5520 """
5521 self._cell_renderer.Draw(
5522 self._grid,
5523 attr,
5524 dc,
5525 rect,
5526 self._grid.GetGridCursorRow(),
5527 self._grid.GetGridCursorCol(),
5528 True,
5529 )
5530
5531 def BeginEdit(self, row, col, grid):
5532 """Fetch the value from the table and prepare the edit control to begin editing.
5533
5534 Set the focus to the edit control.
5535 """
5536 print(
5537 f"CustomCellEditor.BeginEdit({row!r}, {col!r}, {grid!r}) was called. "
5538 "This should not happen, but is unlikely an issue."
5539 )
5540
5541 def EndEdit(self, row, col, grid, value=None):
5542 """Complete the editing of the current cell.
5543
5544 If necessary, the control may be destroyed.
5545
5546 Returns:
5547 bool: True if the value has changed.
5548 """
5549 print(
5550 f"CustomCellEditor.EndEdit({row!r}, {col!r}, {grid!r}, {value!r}) "
5551 "was called. This should not happen, but is unlikely an issue."
5552 )
5553 return None if wx.VERSION >= (2, 9) else False
5554
5555 def Reset(self):
5556 """Reset the value in the control back to its starting value."""
5557 print(
5558 "CustomCellEditor.Reset() was called. This should "
5559 "not happen, but is unlikely an issue."
5560 )
5561
5562 def IsAcceptedKey(self, evt):
5563 """Return True if the key should start editing (F2 always allowed)."""
5564 return False
5565
5566 def StartingKey(self, evt):
5567 """Handle the first key when editing starts via keyboard."""
5568 print(
5569 f"CustomCellEditor.StartingKey({evt!r}) was called. This should "
5570 "not happen, but is unlikely an issue."
5571 )
5572 evt.Skip()
5573
5574 def StartingClick(self):
5575 """Called when editing starts via mouse click.
5576
5577 No-op for this editor."""
5578
5579 def Destroy(self):
5580 """Do final cleanup."""
5581 super(self.__class__, self).Destroy()
5582
5583 def Clone(self):
5584 """Create a new object which is the copy of this one *Must Override*."""
5585 return self.__class__()
5586
5587
5588 class CustomCellRenderer(wx.grid.PyGridCellRenderer):
5589 """Custom cell renderer for wxPython grid.
5590
5591 This class is used to draw the cell background and text.
5592 It is used by the CustomGrid class.
5593 """
5594
5595 def __init__(self, *args, **kwargs):
5596 wx.grid.PyGridCellRenderer.__init__(self)
5597 self.specialbitmap = get_bitmap("theme/checkerboard-10x10x2-333-444")
5598 self._selectionbitmaps = {}
5599
5600 def Clone(self):
5601 """Create a new object which is the copy of this one."""
5602 return self.__class__()
5603
5604 def Draw(self, grid, attr, dc, rect, row, col, isSelected):
5605 """Draw the cell background and text.
5606
5607 Args:
5608 grid (CustomGrid): The grid object.
5609 attr (wx.grid.GridCellAttr): The cell attribute.
5610 dc (wx.DC): The device context to draw on.
5611 rect (wx.Rect): The rectangle to draw the cell in.
5612 row (int): The row index of the cell.
5613 col (int): The column index of the cell.
5614 isSelected (bool): Whether the cell is selected.
5615 """
5616 orect = rect
5617 # if col == grid.GetNumberCols() - 1:
5618 # Last column
5619 # w = max(grid.ClientSize[0] - rect[0], rect[2])
5620 # rect = wx.Rect(rect[0], rect[1], w, rect[3])
5621 bgcolor = grid.GetCellBackgroundColour(row, col)
5622 col_label = grid.GetColLabelValue(col)
5623 is_default_bgcolor = bgcolor == grid.GetDefaultCellBackgroundColour()
5624 is_read_only = grid.IsReadOnly(row, col)
5625 if is_default_bgcolor:
5626 if (is_read_only or not grid.IsEditable()) and col_label:
5627 bgcolor = grid.GetLabelBackgroundColour()
5628 if row % 2 == 0 and grid.alternate_cell_background_color:
5629 bgcolor = wx.Colour(*[int(v * 0.98) for v in bgcolor])
5630 elif bgcolor.Alpha() < 255:
5631 # Make sure it's opaque
5632 bgcolor = wx.Colour(bgcolor.Red(), bgcolor.Green(), bgcolor.Blue())
5633 special = bgcolor.Get(True) == (0, 0, 0, 0)
5634 mavericks = getattr(grid, "style", None) == "Mavericks"
5635 if not special and mavericks and bgcolor.Red() < 255:
5636 # Use Mavericks-like color scheme
5637 newcolor = [
5638 round(min(bgcolor.Get()[i] * (v / 102.0), 255))
5639 for i, v in enumerate((98, 100, 102))
5640 ]
5641 bgcolor.Set(*newcolor)
5642 rowselect = grid.GetSelectionMode() == wx.grid.Grid.wxGridSelectRows
5643 isCursor = grid.show_cursor_outline and (
5644 (row, col) == (grid.GetGridCursorRow(), grid.GetGridCursorCol())
5645 or (rowselect and row == grid.GetGridCursorRow())
5646 )
5647 if (isSelected or isCursor) and is_default_bgcolor and col_label:
5648 color = grid.GetSelectionBackground()
5649 if isSelected:
5650 textcolor = grid.GetSelectionForeground()
5651 else:
5652 textcolor = grid.GetCellTextColour(row, col)
5653 focus = grid.Parent.FindFocus()
5654 if not focus or grid not in (
5655 focus,
5656 focus.GetParent(),
5657 focus.GetGrandParent(),
5658 ):
5659 if mavericks or sys.platform == "darwin" or "gtk3" in wx.PlatformInfo:
5660 # Use Mavericks-like color scheme
5661 color = wx.Colour(202, 202, 202)
5662 if isSelected:
5663 textcolor = wx.Colour(51, 51, 51)
5664 else:
5665 rgb = int((color.Red() + color.Green() + color.Blue()) / 3.0)
5666 color = wx.Colour(rgb, rgb, rgb)
5667 elif mavericks or sys.platform == "darwin" or "gtk3" in wx.PlatformInfo:
5668 # Use Mavericks-like color scheme
5669 color = wx.Colour(44, 93, 205)
5670 if isSelected:
5671 textcolor = wx.WHITE
5672 else:
5673 alpha = (
5674 grid.selection_alpha * 255 or grid.GetSelectionBackground().Alpha()
5675 )
5676 # Blend with bg color
5677 if alpha < 255:
5678 # Alpha blending
5679 bgblend = (255 - alpha) / 255.0
5680 blend = alpha / 255.0
5681 color = wx.Colour(
5682 round(bgblend * bgcolor.Red() + blend * color.Red()),
5683 round(bgblend * bgcolor.Green() + blend * color.Green()),
5684 round(bgblend * bgcolor.Blue() + blend * color.Blue()),
5685 )
5686 else:
5687 color = bgcolor
5688 textcolor = grid.GetCellTextColour(row, col)
5689 if special:
5690 # Special
5691 image = self.specialbitmap.ConvertToImage()
5692 image.Rescale(rect[2], rect[3])
5693 dc.DrawBitmap(image.ConvertToBitmap(), rect[0], rect[1])
5694 elif (isSelected or isCursor) and col_label:
5695 dc.SetBrush(wx.Brush(bgcolor))
5696 dc.SetPen(wx.TRANSPARENT_PEN)
5697 dc.DrawRectangle(rect)
5698 rect = orect
5699 if not rowselect:
5700 w = 60 + rect[3] * 2
5701 if rect.Width > w:
5702 rect.Left += int((rect.Width - w) / 2.0)
5703 rect.Width = int(w)
5704 offset = 1 # Selection offset from cell boundary
5705 cb = 2 # Cursor border
5706 left = not rowselect or col == 0 or not grid.GetColLabelValue(col - 1)
5707 right = (
5708 not rowselect
5709 or col == grid.GetNumberCols() - 1
5710 or not grid.GetColLabelValue(col + 1)
5711 )
5712 # We could use wx.GCDC, but it is buggy under wxGTK
5713 # (grid doesn't refresh properly when scrolling).
5714 # Implement our own supersampling antialiasing method
5715 # using wx.MemoryDC and cached bitmaps.
5716 # This has the drawback that it may use a lot of memory if
5717 # a grid has many cells with different dimensions or color
5718 # properties, but we make sure that old bitmaps are garbage
5719 # collected if the grid or rows/cols are resized by binding
5720 # resize events in CustomGrid initialization.
5721 key = (
5722 rect[2:]
5723 + bgcolor.Get()
5724 + color.Get()
5725 + (left, right, not isSelected and isCursor)
5726 )
5727 if not self._selectionbitmaps.get(key):
5728 scale = 4.0 # Supersampling factor
5729 offset *= scale
5730 cb *= scale
5731 x, y, w, h = 0, 0, rect[2] * scale, rect[3] * scale
5732 self._selectionbitmaps[key] = wx.EmptyBitmap(int(w), int(h))
5733 paintdc = dc
5734 dc = mdc = wx.MemoryDC(self._selectionbitmaps[key])
5735 dc.SetBrush(wx.Brush(bgcolor))
5736 dc.SetPen(wx.TRANSPARENT_PEN)
5737 dc.DrawRectangle(int(x), int(y), int(w), int(h))
5738 dc.SetBrush(wx.Brush(color))
5739 dc.SetPen(wx.TRANSPARENT_PEN)
5740 draw = dc.DrawRoundedRectangle
5741 draw(
5742 int(x + offset),
5743 int(y + offset),
5744 int(w - offset * 2),
5745 int(h - offset * 2),
5746 int(h / 2.0 - offset),
5747 )
5748 if not left:
5749 dc.DrawRectangle(
5750 int(x), int(y + offset), int(h / 2.0), int(h - offset * 2)
5751 )
5752 if not right:
5753 dc.DrawRectangle(
5754 int(x + w - h / 2.0),
5755 int(y + offset),
5756 int(h / 2.0),
5757 int(h - offset * 2),
5758 )
5759 if not isSelected and isCursor:
5760 dc.SetBrush(wx.Brush(bgcolor))
5761 draw(
5762 int(x + offset + cb),
5763 int(y + offset + cb),
5764 int(w - (offset + cb) * 2),
5765 int(h - (offset + cb) * 2),
5766 int(h / 2.0 - (offset + cb)),
5767 )
5768 if not left:
5769 dc.DrawRectangle(
5770 int(x),
5771 int(y + offset + cb),
5772 int(h / 2.0),
5773 int(h - (offset + cb) * 2),
5774 )
5775 if not right:
5776 dc.DrawRectangle(
5777 int(x + w - h / 2.0),
5778 int(y + offset + cb),
5779 int(h / 2.0),
5780 int(h - (offset + cb) * 2),
5781 )
5782 mdc.SelectObject(wx.NullBitmap)
5783 dc = paintdc
5784 img = self._selectionbitmaps[key].ConvertToImage()
5785 # Scale down to original size ("antialiasing")
5786 img.Rescale(rect[2], rect[3])
5787 self._selectionbitmaps[key] = img.ConvertToBitmap()
5788 bmp = self._selectionbitmaps.get(key)
5789 if bmp:
5790 dc.DrawBitmap(bmp, rect[0], rect[1])
5791 else:
5792 dc.SetBrush(wx.Brush(color))
5793 dc.SetPen(wx.TRANSPARENT_PEN)
5794 dc.DrawRectangle(rect)
5795 dc.SetFont(grid.GetCellFont(row, col))
5796 dc.SetTextForeground(textcolor)
5797 self.DrawLabel(grid, dc, orect, row, col)
5798
5799 def DrawLabel(self, grid, dc, rect, row, col):
5800 """Draw the label in the cell.
5801
5802 Args:
5803 grid (wx.grid.Grid): The grid containing the cell.
5804 dc (wx.DC): The device context to use for drawing.
5805 rect (wx.Rect): The rectangle in which to draw the label.
5806 row (int): The row index of the cell.
5807 col (int): The column index of the cell.
5808 """
5809 align = grid.GetCellAlignment(row, col)
5810 if align[1] == wx.ALIGN_CENTER:
5811 align = align[0], wx.ALIGN_CENTER_VERTICAL
5812 dc.DrawLabel(grid.GetCellValue(row, col), rect, align[0] | align[1])
5813
5814 def GetBestSize(self, grid, attr, dc, row, col):
5815 """Return the best size for the cell renderer.
5816
5817 Args:
5818 grid (wx.grid.Grid): The grid containing the cell.
5819 attr (wx.grid.GridCellAttr): The cell attributes.
5820 dc (wx.DC): The device context to use for drawing.
5821 row (int): The row index of the cell.
5822 col (int): The column index of the cell.
5823
5824 Returns:
5825 wx.Size: The best size for the cell renderer.
5826 """
5827 dc.SetFont(grid.GetCellFont(row, col))
5828 return dc.GetTextExtent(grid.GetCellValue(row, col))
5829
5830
5831 class CustomCellBoolRenderer(CustomCellRenderer):
5832 """Custom cell renderer for boolean values."""
5833
5834 def __init__(self, *args, **kwargs):
5835 CustomCellRenderer.__init__(self)
5836 self._bitmap = get_icon(16, "checkmark")
5837 self._bitmap_unchecked = get_icon(16, "x")
5838
5839 def DrawLabel(self, grid, dc, rect, row, col):
5840 """Draw the checkbox in the cell.
5841
5842 Args:
5843 grid (wx.grid.Grid): The grid containing the cell.
5844 dc (wx.DC): The device context to use for drawing.
5845 rect (wx.Rect): The rectangle in which to draw the checkbox.
5846 row (int): The row index of the cell.
5847 col (int): The column index of the cell.
5848 """
5849 if grid.GetCellValue(row, col) == "1":
5850 bitmap = self._bitmap
5851 else:
5852 bitmap = self._bitmap_unchecked
5853 x = rect[0] + int((rect[2] - self._bitmap.Size[0]) / 2.0)
5854 y = rect[1] + int((rect[3] - self._bitmap.Size[1]) / 2.0)
5855 dc.DrawBitmap(bitmap, x, y)
5856
5857 def GetBestSize(self, grid, attr, dc, row, col):
5858 """Return the best size for the cell renderer.
5859
5860 Args:
5861 grid (wx.grid.Grid): The grid containing the cell.
5862 attr (wx.grid.GridCellAttr): The cell attributes.
5863 dc (wx.DC): The device context to use for drawing.
5864 row (int): The row index of the cell.
5865 col (int): The column index of the cell.
5866
5867 Returns:
5868 wx.Size: The best size for the cell renderer.
5869 """
5870 return self._bitmap.Size
5871
5872
5873 class CustomColLabelRenderer:
5874 """Custom column label renderer."""
5875
5876 def __init__(self, bgcolor=None):
5877 self.bgcolor = bgcolor
5878
5879 def Draw(self, grid, dc, rect, col=-1):
5880 """Draw the column label in the given rectangle.
5881
5882 Args:
5883 grid (wx.grid.Grid): The grid to draw the label for.
5884 dc (wx.DC): The device context to draw on.
5885 rect (wx.Rect): The rectangle to draw the label in.
5886 col (int): The column index for which to draw the label.
5887 """
5888 if not grid.GetNumberCols():
5889 return
5890 orect = rect
5891 if col == grid.GetNumberCols() - 1:
5892 # Last column
5893 w = max(grid.ClientSize[0] - rect[0], rect[2])
5894 rect = wx.Rect(rect[0], rect[1], w, rect[3])
5895 mavericks = (
5896 getattr(grid, "style", None) == "Mavericks" or sys.platform == "darwin"
5897 )
5898 if grid.headerbitmap:
5899 img = grid.headerbitmap.ConvertToImage()
5900 img.Rescale(rect[2], rect[3], quality=wx.IMAGE_QUALITY_NORMAL)
5901 dc.DrawBitmap(img.ConvertToBitmap(), rect[0], 0)
5902 pen = wx.Pen(
5903 wx.SystemSettings.GetColour(wx.SYS_COLOUR_3DSHADOW),
5904 1,
5905 wx.PENSTYLE_SOLID,
5906 )
5907 pen.SetCap(wx.CAP_BUTT)
5908 dc.SetPen(pen)
5909 dc.DrawLine(
5910 rect[0], rect[1] + rect[3] - 1, rect[0] + rect[2], rect[1] + rect[3] - 1
5911 )
5912 elif grid.rendernative:
5913 render = wx.RendererNative.Get()
5914 render.DrawHeaderButton(grid, dc, rect)
5915 else:
5916 if self.bgcolor:
5917 color = self.bgcolor
5918 else:
5919 if mavericks:
5920 # Use Mavericks-like color scheme
5921 color = wx.SystemSettings.GetColour(wx.SYS_COLOUR_LISTBOX)
5922 else:
5923 color = grid.GetLabelBackgroundColour()
5924 if col % 2 == 0 and grid.alternate_col_label_background_color:
5925 color = wx.Colour(*[int(v * 0.98) for v in color])
5926 elif color.Alpha() < 255:
5927 # Make sure it's opaque
5928 color = wx.Colour(color.Red(), color.Green(), color.Blue())
5929 dc.SetBrush(wx.Brush(color))
5930 dc.SetPen(wx.TRANSPARENT_PEN)
5931 dc.DrawRectangle(rect)
5932 pen = wx.Pen(wx.SystemSettings.GetColour(wx.SYS_COLOUR_3DSHADOW))
5933 dc.SetPen(pen)
5934 if getattr(grid, "draw_horizontal_grid_lines", True) or (
5935 mavericks and not self.bgcolor
5936 ):
5937 dc.DrawLine(
5938 rect[0],
5939 rect[1] + rect[3] - 1,
5940 rect[0] + rect[2] - 1,
5941 rect[1] + rect[3] - 1,
5942 )
5943 if getattr(grid, "draw_vertical_grid_lines", True):
5944 dc.DrawLine(
5945 rect[0] + rect[2] - 1, rect[1], rect[0] + rect[2] - 1, rect[3]
5946 )
5947 if getattr(grid, "draw_col_labels", True) and col > -1:
5948 dc.SetFont(grid.GetLabelFont())
5949 if (
5950 mavericks
5951 and not self.bgcolor
5952 and (
5953 color.Red() == 255 and color.Green() == 255 and color.Blue() == 255
5954 )
5955 ):
5956 # Use Mavericks-like color scheme
5957 color = wx.Colour(80, 100, 120)
5958 else:
5959 color = grid.GetLabelTextColour()
5960 dc.SetTextForeground(color)
5961 # align = grid.GetColLabelAlignment()
5962 # if align[1] == wx.ALIGN_CENTER:
5963 # align = align[0], wx.ALIGN_CENTER_VERTICAL
5964 # dc.DrawLabel(f" grid.GetColLabelValue(col) ", orect, align[0] | align[1])
5965 dc.DrawLabel(f" {grid.GetColLabelValue(col)} ", orect)
5966
5967
5968 class CustomRowLabelRenderer:
5969 """Custom row label renderer."""
5970
5971 def __init__(self, bgcolor=None):
5972 self.bgcolor = bgcolor
5973
5974 def Draw(self, grid, dc, rect, row):
5975 """Draw the row label in the given rectangle.
5976
5977 Args:
5978 grid (wx.grid.Grid): The grid to draw the label for.
5979 dc (wx.DC): The device context to draw on.
5980 rect (wx.Rect): The rectangle to draw the label in.
5981 row (int): The row index for which to draw the label.
5982 """
5983 if self.bgcolor:
5984 color = self.bgcolor
5985 else:
5986 color = grid.GetLabelBackgroundColour()
5987 if row % 2 == 0 and grid.alternate_row_label_background_color:
5988 color = wx.Colour(*[int(v * 0.98) for v in color])
5989 elif color.Alpha() < 255:
5990 # Make sure it's opaque
5991 color = wx.Colour(color.Red(), color.Green(), color.Blue())
5992 if getattr(grid, "style", None) == "Mavericks" and color.Red() < 255:
5993 # Use Mavericks-like color scheme
5994 newcolor = [
5995 round(color.Get()[i] * (v / 102.0))
5996 for i, v in enumerate((98, 100, 102))
5997 ]
5998 color.Set(*newcolor)
5999 dc.SetBrush(wx.Brush(color))
6000 dc.SetPen(wx.TRANSPARENT_PEN)
6001 dc.DrawRectangle(rect)
6002 pen = wx.Pen(grid.GetGridLineColour())
6003 dc.SetPen(pen)
6004 if getattr(grid, "draw_horizontal_grid_lines", True):
6005 dc.DrawLine(
6006 rect[0],
6007 rect[1] + rect[3] - 1,
6008 rect[0] + rect[2] - 1,
6009 rect[1] + rect[3] - 1,
6010 )
6011 if getattr(grid, "draw_vertical_grid_lines", True):
6012 dc.DrawLine(rect[0] + rect[2] - 1, rect[1], rect[0] + rect[2] - 1, rect[3])
6013 if getattr(grid, "draw_row_labels", True):
6014 dc.SetFont(grid.GetLabelFont())
6015 dc.SetTextForeground(grid.GetLabelTextColour())
6016 align = grid.GetRowLabelAlignment()
6017 if align[1] == wx.ALIGN_CENTER:
6018 align = align[0], wx.ALIGN_CENTER_VERTICAL
6019 dc.DrawLabel(f" {grid.GetRowLabelValue(row)} ", rect, align[0] | align[1])
6020
6021
6022 class HStretchStaticBitmap(wx.StaticBitmap):
6023 """A StaticBitmap that will automatically stretch horizontally.
6024
6025 To be used with sizers.
6026 """
6027
6028 def __init__(self, *args, **kwargs):
6029 wx.StaticBitmap.__init__(self, *args, **kwargs)
6030 if sys.platform in ("darwin", "win32"):
6031 # Works (only) under Mac OS X / Windows.
6032 # Works better (no jump to correct width) under Mac OS X than
6033 # EVT_SIZE method.
6034 self.Bind(wx.EVT_PAINT, self.OnPaint)
6035 else:
6036 # Works under Mac OS X, Windows and Linux.
6037 # Under Mac OS X, this visibly jumps to the correct width when
6038 # first shown on screen.
6039 self.Bind(wx.EVT_SIZE, self.OnPaint)
6040 self._init = False
6041
6042 def OnPaint(self, event):
6043 """Resize the bitmap to the current width of the control.
6044
6045 Args:
6046 event (wx.Event): The paint or size event that triggered this
6047 method.
6048 """
6049 if self and self.GetBitmap() and self.GetBitmap().IsOk():
6050 if hasattr(self, "_bmp"):
6051 bmp = self._bmp
6052 else:
6053 bmp = self.GetBitmap()
6054 self._bmp = bmp
6055 w = self.Size[0]
6056 if getattr(self, "_width", -1) != w:
6057 img = bmp.ConvertToImage()
6058 img.Rescale(w, img.GetSize()[1])
6059 bmp = img.ConvertToBitmap()
6060 self._width = w
6061 # Avoid flicker under Windows
6062 if self._init:
6063 self.Freeze()
6064 self.SetBitmap(bmp)
6065 self.MinSize = self._bmp.GetSize()
6066 if self._init:
6067 self.IsFrozen() and self.Thaw()
6068 elif self.IsShownOnScreen():
6069 self._init = True
6070 if event:
6071 event.Skip()
6072
6073
6074 class HyperLinkCtrl(hyperlink.HyperLinkCtrl):
6075 """A wxPython hyperlink control that supports right-click context menu."""
6076
6077 def __init__(self, *args, **kwargs):
6078 hyperlink.HyperLinkCtrl.__init__(self, *args, **kwargs)
6079 bgcolor, text, linkcolor, vlinkcolor = get_html_colors()
6080 self.SetColours(linkcolor, vlinkcolor, linkcolor)
6081 self.DoPopup(False)
6082 self.UpdateLink()
6083 self.Bind(hyperlink.EVT_HYPERLINK_RIGHT, self.OnPopup)
6084
6085 def OnPopup(self, event):
6086 """Pop up a menu with 'Copy link address'."""
6087 menuPopUp = wx.Menu("", wx.MENU_TEAROFF)
6088 menuPopUp.Append(
6089 hyperlink.wxHYPERLINKS_POPUP_COPY, lang.getstr("link.address.copy")
6090 )
6091 self.Bind(wx.EVT_MENU, self.OnPopUpCopy, id=hyperlink.wxHYPERLINKS_POPUP_COPY)
6092 self.PopupMenu(menuPopUp, event.GetPosition())
6093 menuPopUp.Destroy()
6094 self.Unbind(wx.EVT_MENU, id=hyperlink.wxHYPERLINKS_POPUP_COPY)
6095
6096 if sys.platform not in ("darwin", "win32") and "gtk3" in wx.PlatformInfo:
6097
6098 def SetFont(self, font):
6099 """Set the font for the hyperlink control.
6100
6101 Args:
6102 font (wx.Font): The font to set.
6103 """
6104 scale = (getcfg("app.dpi") / get_default_dpi()) or 1
6105 font.PointSize = int(font.PointSize * scale)
6106 hyperlink.HyperLinkCtrl.SetFont(self, font)
6107
6108
6109 def fancytext_renderer_getCurrentFont(self) -> wx.Font:
6110 """Get the current font of the text.
6111
6112 Returns:
6113 wx.Font: The current font.
6114 """
6115 # Use system font instead of fancytext default font
6116 font = self.fonts[-1]
6117 # copy to avoid mutating the shared class-level _font on each render call
6118 _font = wx.Font(self._font or wx.SystemSettings_GetFont(wx.SYS_DEFAULT_GUI_FONT))
6119 if "encoding" in font:
6120 _font.SetEncoding(font["encoding"])
6121 if "family" in font:
6122 _font.SetFamily(font["family"])
6123 if "size" in font:
6124 _font.SetPointSize(font["size"])
6125 if sys.platform == "win32" or "gtk3" in wx.PlatformInfo:
6126 scale = (getcfg("app.dpi") / get_default_dpi()) or 1
6127 _font.SetPointSize(max(round(_font.GetPointSize() * scale), 1))
6128 if "style" in font:
6129 _font.SetStyle(font["style"])
6130 if "weight" in font:
6131 _font.SetWeight(font["weight"])
6132 return _font
6133
6134
6135 def fancytext_Renderer_getCurrentColor(self) -> wx.Colour:
6136 """Get the current color of the text.
6137
6138 Returns:
6139 wx.Colour: The current text color.
6140 """
6141 # Use system text color instead of fancytext default color
6142 font = self.fonts[-1]
6143 if "color" in font:
6144 return wx.TheColourDatabase.FindColour(font["color"])
6145 return wx.SystemSettings.GetColour(wx.SYS_COLOUR_WINDOWTEXT)
6146
6147
6148 fancytext.Renderer._font = None
6149 fancytext.Renderer.getCurrentColor = fancytext_Renderer_getCurrentColor
6150 fancytext.Renderer.getCurrentFont = fancytext_renderer_getCurrentFont
6151
6152
6153 def fancytext_RenderToRenderer(text: str, renderer, enclose: bool = True) -> None:
6154 """Render the given text using the given renderer.
6155
6156 Args:
6157 text (str): The text to render.
6158 renderer (FancyTextRenderer): The renderer to use.
6159 enclose (bool): Whether to enclose the text in XML tags.
6160
6161 Raises:
6162 ValueError: If there is an error parsing the text.
6163 """
6164 text = safe_str(text, "UTF-8")
6165 try:
6166 if enclose:
6167 text = f'<?xml version="1.0"?><FancyText>{text}</FancyText>'
6168 p = xml.parsers.expat.ParserCreate()
6169 p.StartElementHandler = renderer.startElement
6170 p.EndElementHandler = renderer.endElement
6171 p.CharacterDataHandler = renderer.characterData
6172 p.Parse(text, True)
6173 except xml.parsers.expat.error as err:
6174 raise ValueError(f'error parsing text text "{text}": {err}') from err
6175
6176
6177 fancytext.RenderToRenderer = fancytext_RenderToRenderer
6178
6179
6180 class BetterPyGauge(pygauge.PyGauge):
6181 """A wxPython gauge that supports gradients and indeterminate mode.
6182
6183 Args:
6184 parent (wx.Window): The parent window.
6185 id (int): The ID of the gauge.
6186 range_ (int): The range of the gauge.
6187 pos (tuple[int, int]): The position of the gauge.
6188 size (tuple[int, int]): The size of the gauge.
6189 style (int): The style of the gauge.
6190 pd (wx.Dialog): The parent dialog (optional).
6191 """
6192
6193 def __init__(
6194 self,
6195 parent,
6196 id=wx.ID_ANY, # noqa: A002
6197 range_=100,
6198 pos=wx.DefaultPosition,
6199 size=(-1, 30),
6200 style=0,
6201 pd=None,
6202 ):
6203 self.pd = pd
6204 self.dpiscale = getcfg("app.dpi") / get_default_dpi()
6205 if self.dpiscale > 1:
6206 size = tuple(round(v * self.dpiscale) if v != -1 else v for v in size)
6207 pygauge.PyGauge.__init__(self, parent, id, range_, pos, size, style)
6208 self._indeterminate = False
6209 self.gradientindex = 0
6210 self._gradients = []
6211 self._indeterminate_gradients = []
6212 self._timer = BetterTimer(self)
6213 self.Unbind(wx.EVT_TIMER)
6214 self.Bind(EVT_BETTER_TIMER, self.OnTimer, self._timer)
6215 self.Bind(wx.EVT_WINDOW_DESTROY, self.OnDestroy)
6216 self.Start()
6217
6218 def OnDestroy(self, event):
6219 """Handle the ``wx.EVT_WINDOW_DESTROY`` event.
6220
6221 Args:
6222 event (wx.WindowDestroyEvent): a `wx.WindowDestroyEvent` event to
6223 be processed.
6224 """
6225 self._timer.Stop()
6226 del self._timer
6227
6228 return 0
6229
6230 def OnPaint(self, event):
6231 """Handle the ``wx.EVT_PAINT`` event.
6232
6233 Args:
6234 event (wx.PaintEvent): a `wx.PaintEvent` event to be processed.
6235 """
6236 dc = wx.BufferedPaintDC(self)
6237 gc = wx.GraphicsContext.Create(dc)
6238 dc.SetBackground(wx.Brush(self.Parent.BackgroundColour))
6239 dc.Clear()
6240
6241 rect = self.GetClientRect()
6242
6243 if self._border_colour:
6244 gc.SetPen(wx.Pen(self._border_colour))
6245 else:
6246 gc.SetPen(wx.Pen(self.BackgroundColour))
6247 gc.SetBrush(wx.Brush(self.BackgroundColour))
6248 gc.DrawRoundedRectangle(
6249 rect.X,
6250 rect.Y,
6251 rect.Width - 1 * self.dpiscale,
6252 rect.Height - 1 * self.dpiscale,
6253 (rect.Height - 1 * self.dpiscale) / 2,
6254 )
6255
6256 pad = self.GetBorderPadding()
6257 if self._border_colour:
6258 pad += 1
6259 pad *= self.dpiscale
6260 if pad:
6261 rect.Deflate(pad, pad)
6262
6263 if self._barGradientSorted:
6264 for i, gradient in enumerate(self._barGradientSorted):
6265 c1, c2 = gradient
6266 w = max(
6267 rect.Width * (float(self._valueSorted[i]) / self._range),
6268 rect.Height,
6269 )
6270 gc.SetBrush(
6271 gc.CreateLinearGradientBrush(
6272 rect.X, rect.Y, rect.Y + w, rect.Y, c1, c2
6273 )
6274 )
6275 gc.SetPen(wx.TRANSPARENT_PEN)
6276 gc.DrawRoundedRectangle(
6277 rect.X, rect.Y, w, rect.Height, (rect.Height) / 2
6278 )
6279
6280 def OnTimer(self, event):
6281 """Handle the timer event to update the gauge.
6282
6283 Args:
6284 event (wx.TimerEvent): The timer event to be processed.
6285 """
6286 gradient = self._barGradient
6287 if self._indeterminate:
6288 if self.gradientindex < len(self._indeterminate_gradients) - 1:
6289 self.gradientindex += 1
6290 else:
6291 self.gradientindex = 0
6292 self._barGradient = [self._indeterminate_gradients[self.gradientindex]]
6293 else:
6294 if self.gradientindex < len(self._gradients) - 1:
6295 self.gradientindex += 1
6296 else:
6297 self.gradientindex = 0
6298 self._barGradient = [self._gradients[self.gradientindex]]
6299 if hasattr(self, "_update_step") and not self._indeterminate:
6300 stop = True
6301 for i in range(len(self._value)):
6302 self._value[i] += self._update_step[i]
6303
6304 if self._update_step[i] > 0:
6305 if self._value[i] > self._update_value[i]:
6306 self._value[i] = self._update_value[i]
6307 else:
6308 stop = False
6309 elif self._value[i] < self._update_value[i]:
6310 self._value[i] = self._update_value[i]
6311 else:
6312 stop = False
6313 if self.pd and self.pd.taskbar:
6314 self.pd.taskbar.set_progress_value(round(self.GetValue()))
6315 if stop:
6316 del self._update_step
6317 updated = True
6318 else:
6319 updated = False
6320 if gradient != self._barGradient or updated:
6321 self.SortForDisplay()
6322 if self._indeterminate:
6323 self._valueSorted = [self.GetRange()]
6324 self.Refresh()
6325
6326 def IsRunning(self):
6327 """Check if the gauge timer is running.
6328
6329 Returns:
6330 bool: True if the timer is running, False otherwise.
6331 """
6332 return self._timer.IsRunning()
6333
6334 def Pulse(self):
6335 """Set the gauge to indeterminate mode."""
6336 self._indeterminate = True
6337
6338 def SetBarGradients(self, gradients):
6339 """Set the gradients for the gauge.
6340
6341 Args:
6342 gradients (list): A list of tuples, where each tuple contains two
6343 wx.Colour objects representing the start and end colors of the
6344 gradient.
6345 """
6346 self._gradients = gradients
6347
6348 def SetIndeterminateBarGradients(self, gradients):
6349 """Set the gradients for the indeterminate mode of the gauge.
6350
6351 Args:
6352 gradients (list): A list of tuples, where each tuple contains two
6353 wx.Colour objects representing the start and end colors of the
6354 gradient.
6355 """
6356 self._indeterminate_gradients = gradients
6357
6358 def SetValue(self, value):
6359 """Set the value of the gauge.
6360
6361 Args:
6362 value (int | list): The value to set. If a list, it must match the
6363 length of the gauge's value list.
6364 """
6365 self._indeterminate = False
6366 pygauge.PyGauge.SetValue(self, value)
6367 self.Refresh()
6368
6369 def Start(self, milliseconds=67):
6370 """Start the gauge timer.
6371
6372 Args:
6373 milliseconds (int): The interval in milliseconds for the timer.
6374 """
6375 self._timer.Start(milliseconds)
6376
6377 def Stop(self):
6378 """Stop the gauge timer."""
6379 self._timer.Stop()
6380
6381 def Update(self, value, time=0):
6382 """Update the gauge by adding `value` to it over `time` milliseconds.
6383
6384 The `time` parameter **must** be a multiple of 50 milliseconds.
6385
6386 Args:
6387 value: The value to be added to the gauge.
6388 time: The length of time in milliseconds that it will take to move
6389 the gauge.
6390 """
6391 self._indeterminate = False
6392
6393 if not isinstance(value, list):
6394 value = [value]
6395
6396 if len(value) != len(self._value):
6397 raise Exception("ERROR:\n len(value) != len(self.GetValue())")
6398
6399 self._update_value = []
6400 self._update_step = []
6401 for i, v in enumerate(self._value):
6402 if value[i] < 0 or value[i] > self._range:
6403 warnings.warn(
6404 f"Gauge value {value[i]!r} is invalid - must be between 0 "
6405 f"and {self._range}",
6406 Warning,
6407 stacklevel=2,
6408 )
6409 if value[i] < 0:
6410 value[i] = 0
6411 else:
6412 value[i] = self._range
6413
6414 self._update_value.append(value[i])
6415 self._update_step.append((float(value[i]) - v) / (time / 50))
6416
6417
6418 class BetterStaticFancyTextBase:
6419 """Base class for BetterStaticFancyText and BetterStaticFancyTextSetLabelMarkup."""
6420
6421 def GetLabel(self):
6422 """Get the label with HTML-like markup.
6423
6424 Returns:
6425 str: The label text with HTML-like markup.
6426 """
6427 return self._rawlabel
6428
6429 @property
6430 def Label(self):
6431 """Get the label with HTML-like markup.
6432
6433 Returns:
6434 str: The label text with HTML-like markup.
6435 """
6436 return self._rawlabel
6437
6438 @Label.setter
6439 def Label(self, label):
6440 """Set the label with HTML-like markup.
6441
6442 Args:
6443 label (str): The label text with HTML-like markup.
6444 """
6445 self.SetLabel(label)
6446
6447 def SetLabel(self, label):
6448 """Set the label with HTML-like markup.
6449
6450 Args:
6451 label (str): The label text with HTML-like markup.
6452 """
6453 self._rawlabel = label
6454 # Wrap ignoring tags, only break in whitespace
6455 wrapped = ""
6456 llen = 0
6457 intag = False
6458 hyphens = "-\u2012\u2013\u2014\u2015"
6459 whitespace = "\n\t "
6460 for c in label:
6461 if c == "<":
6462 intag = True
6463 hyphen = c in hyphens
6464 if intag and c == ">":
6465 intag = False
6466 elif not intag:
6467 llen += 1
6468 if llen > self.maxlen and (c in whitespace or hyphen):
6469 if hyphen:
6470 wrapped += c
6471 elif llen > self.maxlen + 1:
6472 for i, rc in enumerate(reversed(wrapped)):
6473 if rc == ">":
6474 intag = True
6475 elif not intag and rc in whitespace + hyphens:
6476 line = wrapped[-i:]
6477 llen = 1
6478 for rc in reversed(line):
6479 if rc == ">":
6480 intag = True
6481 if not intag:
6482 llen += 1
6483 elif rc == "<":
6484 intag = False
6485 wrapped = wrapped[:-i] + "\n" + line
6486 break
6487 elif intag and rc == "<":
6488 intag = False
6489 if llen > self.maxlen:
6490 c = "\n"
6491 if c == "\n":
6492 llen = 0
6493 wrapped += c
6494 self._label = wrapped
6495
6496
6497 class BetterStaticFancyText(BetterStaticFancyTextBase, GenStaticBitmap):
6498 """Based on wx.lib.fancytext functionality.
6499
6500 Renders crisp on 'Retina' displays under OS X and in high DPI mode
6501 under Linux/Windows.
6502
6503 """
6504
6505 _enabled = True
6506 _rawlabel = ""
6507 maxlen = 119
6508
6509 def __init__(self, window, id, text, *args, **kargs): # noqa: A002
6510 args = list(args)
6511 kargs.setdefault("name", "staticFancyText")
6512 # Ignore background, always use parent background
6513 if "background" in kargs:
6514 kargs.pop("background")
6515 elif args:
6516 args.pop(0)
6517
6518 bmp = wx.EmptyBitmap(1, 1)
6519 GenStaticBitmap.__init__(self, window, id, bmp, *args, **kargs)
6520 self.Label = text
6521
6522 def Disable(self):
6523 """Disable the text."""
6524 self.Enable(False)
6525
6526 def Enable(self, enable=True):
6527 """Enable or disable the text.
6528
6529 Args:
6530 enable (bool): True to enable the text, False to disable it.
6531 """
6532 self._enabled = enable
6533 if sys.platform != "win32":
6534 return
6535 if enable:
6536 bmp = self._enabledbitmap
6537 else:
6538 bmp = (
6539 self._enabledbitmap.ConvertToImage()
6540 .AdjustChannels(1, 1, 1, 0.5)
6541 .ConvertToBitmap()
6542 )
6543 self.SetBitmap(bmp)
6544
6545 def IsEnabled(self):
6546 """Check if the text is enabled.
6547
6548 Returns:
6549 bool: True if the text is enabled, False otherwise.
6550 """
6551 return self._enabled
6552
6553 Enabled = property(IsEnabled, Enable)
6554
6555 def GetFont(self):
6556 """Get the current font of the text.
6557
6558 Returns:
6559 wx.Font: The current font.
6560 """
6561 return fancytext.Renderer._font or wx.SystemSettings_GetFont(
6562 wx.SYS_DEFAULT_GUI_FONT
6563 )
6564
6565 def OnPaint(self, event):
6566 """Handle the ``wx.EVT_PAINT`` event.
6567
6568 Args:
6569 event (wx.PaintEvent): a `wx.PaintEvent` event to be processed.
6570 """
6571 if sys.platform != "win32":
6572 # AutoBufferedPaintDCFactory is the magic needed for crisp text
6573 # rendering in HiDPI mode under OS X and Linux
6574 cls = wx.AutoBufferedPaintDCFactory
6575 else:
6576 cls = wx.BufferedPaintDC
6577 dc = cls(self)
6578 dc.SetBackground(wx.Brush(self.Parent.BackgroundColour, wx.BRUSHSTYLE_SOLID))
6579 dc.SetBackgroundMode(wx.BRUSHSTYLE_TRANSPARENT)
6580 dc.Clear()
6581 if sys.platform != "win32":
6582 fancytext.RenderToDC(self._label, dc, 0, 0)
6583 elif self._bitmap:
6584 dc.DrawBitmap(self._bitmap, 0, 0, True)
6585
6586 def SetFont(self, font):
6587 """Set the font for the text.
6588
6589 Args:
6590 font (wx.Font): The font to set.
6591 """
6592 fancytext.Renderer._font = font
6593
6594 def SetLabel(self, label):
6595 """Set the label with HTML-like markup.
6596
6597 This method replaces <font> tags with <span> tags and decodes HTML
6598 entities.
6599
6600 Args:
6601 label (str): The label text with HTML-like markup.
6602 """
6603 BetterStaticFancyTextBase.SetLabel(self, label)
6604 background = wx.Brush(self.Parent.BackgroundColour, wx.BRUSHSTYLE_SOLID)
6605 try:
6606 bmp = fancytext.RenderToBitmap(self._label, background)
6607 except ValueError:
6608 # XML parsing error, strip all tags
6609 self._label = re.sub(r"<[^>]*?>", "", self._label)
6610 self._label = self._label.replace("<", "").replace(">", "")
6611 bmp = fancytext.RenderToBitmap(self._label, background)
6612 if sys.platform == "win32":
6613 self._enabledbitmap = bmp
6614 self.SetBitmap(bmp)
6615 else:
6616 self.Size = self.MinSize = bmp.Size
6617 self.Refresh()
6618
6619
6620 class BetterStaticFancyTextSetLabelMarkup(BetterStaticFancyTextBase, wx.Panel):
6621 """Based on wx.lib.fancytext functionality.
6622
6623 Renders crisp on 'Retina' displays under OS X and in high DPI mode
6624 under Linux/Windows.
6625
6626 Better under GTK (no text cutoff).
6627 """
6628
6629 def __init__(self, parent, id, text, *args, **kwargs): # noqa: A002
6630 wx.Panel.__init__(self, parent, id, *args, **kwargs)
6631 self.maxlen = 119
6632 self._st = wx.StaticText(self, -1, "")
6633 self.Label = text
6634
6635 def SetLabel(self, label):
6636 """Set the label with HTML-like markup.
6637
6638 This method replaces <font> tags with <span> tags and decodes HTML
6639 entities.
6640
6641 Args:
6642 label (str): The label text with HTML-like markup.
6643 """
6644 BetterStaticFancyTextBase.SetLabel(self, label)
6645 markup = label.replace("<font", "<span")
6646 markup = markup.replace("</font>", "</span>")
6647 # Decode entities
6648 markup = html.unescape(markup)
6649 self._st.SetLabelMarkup(markup)
6650 # Figure out min size
6651 minw = 0
6652 minh = 0
6653 normal_font = self.Font
6654 bold_font = self.Font
6655 bold_font.Weight = wx.FONTWEIGHT_BOLD
6656 xh = self.GetTextExtent("X")[1]
6657 for line in self._label.splitlines():
6658 if line:
6659 # Account for bold text which is approximately 14% wider
6660 parts = re.findall(r"(<font weight='bold'>([^<]+)</font>|[^<]+)", line)
6661 w, h = 0, 0
6662 for markup, bold in parts:
6663 if bold:
6664 text = bold
6665 font = bold_font
6666 else:
6667 text = markup
6668 font = normal_font
6669 # Strip all remaining tags
6670 text = re.sub(r"<[^>]*?>", "", text)
6671 text = text.replace("<", "").replace(">", "")
6672 # Decode entities
6673 text = html.unescape(text)
6674 te = self.GetFullTextExtent(text, font)[:2]
6675 w += te[0]
6676 h = max(te[1], h)
6677 minw = max(w, minw)
6678 else:
6679 # Deal with empty lines having text extent of (0, 0)
6680 h = xh
6681 minh += h
6682 self._st.MaxSize = (-1, -1)
6683 self._st.Size = self._st.MinSize = minw, minh
6684 self._st.MaxSize = minw, -1
6685 self.Layout()
6686
6687
6688 if wx.Platform == "__WXGTK__" and hasattr(wx.StaticText, "SetLabelMarkup"):
6689 BetterStaticFancyText = BetterStaticFancyTextSetLabelMarkup
6690
6691
6692 class InfoDialog(BaseInteractiveDialog):
6693 """Informational dialog with OK button."""
6694
6695 def __init__(
6696 self,
6697 parent=None,
6698 id=-1, # noqa: A002
6699 title=APPNAME,
6700 msg="",
6701 ok="OK",
6702 bitmap=None,
6703 pos=(-1, -1),
6704 size=(400, -1),
6705 show=True,
6706 log=True,
6707 bitmap_margin=None,
6708 nowrap=False,
6709 wrap=70,
6710 ):
6711 BaseInteractiveDialog.__init__(
6712 self,
6713 parent,
6714 id,
6715 title,
6716 msg,
6717 ok,
6718 bitmap,
6719 pos,
6720 size,
6721 show,
6722 log,
6723 nowrap=nowrap,
6724 wrap=wrap,
6725 bitmap_margin=bitmap_margin,
6726 )
6727
6728
6729 class InvincibleFrame(BaseFrame):
6730 """A frame that won't be destroyed when closed."""
6731
6732 def __init__(
6733 self,
6734 parent=None,
6735 id=-1, # noqa: A002
6736 title="",
6737 pos=wx.DefaultPosition,
6738 size=wx.DefaultSize,
6739 style=wx.DEFAULT_FRAME_STYLE,
6740 name=wx.FrameNameStr,
6741 ):
6742 BaseFrame.__init__(self, parent, id, title, pos, size, style, name)
6743 self.Bind(wx.EVT_CLOSE, self.OnClose, self)
6744
6745 def OnClose(self, event):
6746 """Override the close event to hide the frame instead of destroying it.
6747
6748 Args:
6749 event (wx.Event): The close event.
6750 """
6751 self.Hide()
6752
6753
6754 class LogWindow(InvincibleFrame):
6755 """A log-type window with Clear and Save As buttons."""
6756
6757 def __init__(
6758 self,
6759 parent=None,
6760 id=-1, # noqa: A002
6761 title=None,
6762 pos=wx.DefaultPosition,
6763 size=wx.DefaultSize,
6764 logctrlstyle=wx.TE_MULTILINE | wx.TE_RICH | wx.NO_BORDER | wx.TE_READONLY,
6765 ):
6766 if not title:
6767 title = lang.getstr("infoframe.title")
6768 if pos == wx.DefaultPosition:
6769 pos = getcfg("position.info.x"), getcfg("position.info.y")
6770 if size == wx.DefaultSize:
6771 size = getcfg("size.info.w"), getcfg("size.info.h")
6772 InvincibleFrame.__init__(
6773 self, parent, id, title, pos=pos, style=wx.DEFAULT_FRAME_STYLE, name="info"
6774 )
6775 self.last_visible = False
6776 self.panel = wx.Panel(self, -1)
6777 # Fix wrong background color when disabled
6778 self.panel.Enable = lambda enable=True: None
6779 self.panel.Disable = lambda: None
6780 self.sizer = wx.BoxSizer(wx.VERTICAL)
6781 self.panel.SetSizer(self.sizer)
6782 self.log_txt = wx.TextCtrl(self.panel, -1, "", style=logctrlstyle)
6783 # Fix wrong background color under Linux when losing focus
6784 self.log_txt.BackgroundColour = self.log_txt.BackgroundColour
6785 # Fix wrong background color when disabled
6786 self.log_txt.Enable = lambda enable=True: None
6787 self.log_txt.Disable = lambda: None
6788 kwarg = "faceName" if "phoenix" in wx.PlatformInfo else "face"
6789 if sys.platform == "win32":
6790 font = wx.Font(
6791 9,
6792 wx.FONTFAMILY_TELETYPE,
6793 wx.FONTSTYLE_NORMAL,
6794 wx.FONTWEIGHT_NORMAL,
6795 **{kwarg: "Consolas"},
6796 )
6797 elif sys.platform == "darwin":
6798 font = wx.Font(
6799 11,
6800 wx.FONTFAMILY_TELETYPE,
6801 wx.FONTSTYLE_NORMAL,
6802 wx.FONTWEIGHT_NORMAL,
6803 **{kwarg: "Monaco"},
6804 )
6805 else:
6806 font = wx.Font(
6807 10, wx.FONTFAMILY_TELETYPE, wx.FONTSTYLE_NORMAL, wx.FONTWEIGHT_NORMAL
6808 )
6809 self.log_txt.SetFont(font)
6810 self.log_txt.SetDefaultStyle(
6811 wx.TextAttr(
6812 self.log_txt.ForegroundColour, self.log_txt.BackgroundColour, font=font
6813 )
6814 )
6815 bgcol = wx.Colour(
6816 int(self.log_txt.BackgroundColour.Red() * 0.5),
6817 int(self.log_txt.BackgroundColour.Green() * 0.5),
6818 int(self.log_txt.BackgroundColour.Blue() * 0.5),
6819 )
6820 fgcol = wx.Colour(
6821 int(bgcol.Red() + self.log_txt.ForegroundColour.Red() * 0.5),
6822 int(bgcol.Green() + self.log_txt.ForegroundColour.Green() * 0.5),
6823 int(bgcol.Blue() + self.log_txt.ForegroundColour.Blue() * 0.5),
6824 )
6825 self._1stcolstyle = wx.TextAttr(fgcol, self.log_txt.BackgroundColour, font=font)
6826 self.sizer.Add(self.log_txt, 1, flag=wx.EXPAND)
6827 self.log_txt.MinSize = (
6828 self.log_txt.GetTextExtent("=" * 95)[0]
6829 + wx.SystemSettings_GetMetric(wx.SYS_VSCROLL_X),
6830 DEFAULTS["size.info.h"] - 24 - max(0, self.Size[1] - self.ClientSize[1]),
6831 )
6832 separator = BitmapBackgroundPanel(self.panel, size=(-1, 1))
6833 separator.SetBackgroundColour(
6834 wx.SystemSettings.GetColour(wx.SYS_COLOUR_3DSHADOW)
6835 )
6836 self.sizer.Add(separator, flag=wx.EXPAND)
6837 self.btnsizer = wx.BoxSizer(wx.HORIZONTAL)
6838 self.sizer.Add(self.btnsizer, flag=wx.EXPAND)
6839 self.save_as_btn = GenBitmapButton(
6840 self.panel, -1, get_icon(16, "document-save-as"), style=wx.NO_BORDER
6841 )
6842 self.save_as_btn.Bind(wx.EVT_BUTTON, self.OnSaveAs)
6843 self.save_as_btn.SetToolTipString(lang.getstr("save_as"))
6844 self.btnsizer.Add(self.save_as_btn, flag=wx.ALL, border=4)
6845 self.archive_btn = GenBitmapButton(
6846 self.panel, -1, get_icon(16, "package-x-generic"), style=wx.NO_BORDER
6847 )
6848 self.archive_btn.Bind(wx.EVT_BUTTON, self.create_logs_archive)
6849 self.archive_btn.SetToolTipString(lang.getstr("archive.create"))
6850 self.btnsizer.Add(self.archive_btn, flag=wx.ALL, border=4)
6851 self.clear_btn = GenBitmapButton(
6852 self.panel, -1, get_icon(16, "edit-delete"), style=wx.NO_BORDER
6853 )
6854 self.clear_btn.Bind(wx.EVT_BUTTON, self.OnClear)
6855 self.clear_btn.SetToolTipString(lang.getstr("clear"))
6856 self.btnsizer.Add(self.clear_btn, flag=wx.ALL, border=4)
6857 self.sizer.SetSizeHints(self)
6858 self.sizer.Layout()
6859 self.SetSaneGeometry(*pos + size)
6860 self.Bind(wx.EVT_MOVE, self.OnMove)
6861 self.Bind(wx.EVT_SIZE, self.OnSize)
6862 self.Children[0].Bind(wx.EVT_WINDOW_DESTROY, self.OnDestroy)
6863 self._tspattern = re.compile(
6864 r"(?:\d{4}-\d{2}-\d{2} )?(\d{2}:\d{2}:\d{2},\d{3} )"
6865 )
6866 self._textwrapper = textwrap.TextWrapper(76)
6867 self._linecontinuation = " " * 13 + "\u21b3 "
6868 self._warning_lstr = lang.getstr("warning").lower()
6869 self._error_lstr = lang.getstr("error").lower()
6870
6871 def Log(self, txt):
6872 """Log the given text to the log text control.
6873
6874 Args:
6875 txt (str): The text to log.
6876 """
6877 # TextCtrl.AppendText is an EXPENSIVE operation under OS X.
6878 # For that reason, assemble the text to be added before calling it.
6879 lines = []
6880 start = self.log_txt.GetLastPosition()
6881 ts = None
6882 for line in str(txt).split("\n"):
6883 if sys.platform == "win32":
6884 # Formatting of boxes
6885 line = line.replace("\u2500", "-")
6886 tsmatch = re.match(self._tspattern, line)
6887 if tsmatch:
6888 line = line[len(tsmatch.group()) :]
6889 ts = tsmatch.group(1)
6890 elif line[:15] == self._linecontinuation:
6891 ts = line[:13]
6892 line = line[13:]
6893 else:
6894 s = time()
6895 ms = s - int(s)
6896 ts = strftime("%H:%M:%S,") + (f"{ms:.3f} ")[2:]
6897 if len(line) > 80:
6898 wrapped = self._textwrapper.wrap(line)
6899 i_last = len(wrapped) - 1
6900 for i, line in enumerate(wrapped):
6901 line = self._linecontinuation + line if i else ts + line
6902 if i < i_last:
6903 line = line.ljust(78 + 13) + " \u21b2"
6904 lines.append(line)
6905 else:
6906 lines.append(ts + line)
6907 self.log_txt.AppendText("\n".join(lines) + "\n")
6908 # TextCtrl.SetStyle is an EXPENSIVE operation, especially under OS X.
6909 # Only set styles for (up to) the last 1000 lines.
6910 for line in lines[:-1000]:
6911 start += len(line + "\n")
6912 textattr = None
6913 warning_lstr = self._warning_lstr
6914 error_lstr = self._error_lstr
6915 for line in lines[-1000:]:
6916 line_lower = line.lower()
6917 if (
6918 "brightness error" in line_lower
6919 or "white point error" in line_lower
6920 or "maximum neutral error" in line_lower
6921 or "average neutral error" in line_lower
6922 or "profile check complete" in line_lower
6923 ):
6924 # These are not actual errors
6925 pass
6926 elif warning_lstr in line_lower or "warning" in line_lower:
6927 textattr = wx.TextAttr("#F07F00", font=self.log_txt.Font)
6928 elif error_lstr in line_lower or "error" in line_lower:
6929 textattr = wx.TextAttr("#FF3300", font=self.log_txt.Font)
6930 self.log_txt.SetStyle(start, start + 12, self._1stcolstyle)
6931 if textattr:
6932 self.log_txt.SetStyle(start + 12, start + len(line), textattr)
6933 if not line.endswith(" \u21b2"):
6934 textattr = None
6935 start += len(line + "\n")
6936
6937 def ScrollToBottom(self):
6938 """Scroll the log text control to the bottom."""
6939 self.log_txt.ScrollLines(self.log_txt.GetNumberOfLines())
6940
6941 def OnClear(self, event):
6942 """Handle the ``wx.EVT_BUTTON`` event.
6943
6944 Args:
6945 event (wx.CommandEvent): a `wx.CommandEvent` event to be processed.
6946 """
6947 self.log_txt.SetValue("")
6948
6949 def OnClose(self, event):
6950 """Handle the ``wx.EVT_CLOSE`` event.
6951
6952 Args:
6953 event (wx.CloseEvent): a `wx.CloseEvent` event to be processed.
6954 """
6955 setcfg("log.show", 0)
6956 self.Hide()
6957
6958 def OnDestroy(self, event):
6959 """Handle the ``wx.EVT_WINDOW_DESTROY`` event.
6960
6961 Args:
6962 event (wx.WindowDestroyEvent): a `wx.WindowDestroyEvent` event to
6963 be processed.
6964 """
6965 with contextlib.suppress(RuntimeError):
6966 # jug ignore:
6967 # RuntimeError: wrapped C/C++ object of type LogWindow has been deleted
6968 self.Destroy()
6969 event.Skip()
6970
6971 return 0
6972
6973 def OnMove(self, event=None):
6974 """Handle the ``wx.EVT_MOVE`` event.
6975
6976 Args:
6977 event (wx.MoveEvent): a `wx.MoveEvent` event to be processed.
6978 """
6979 if self.IsShownOnScreen() and not self.IsMaximized() and not self.IsIconized():
6980 x, y = self.GetScreenPosition()
6981 setcfg("position.info.x", x)
6982 setcfg("position.info.y", y)
6983 if event:
6984 event.Skip()
6985
6986 def OnSaveAs(self, event):
6987 """Handle the ``wx.EVT_BUTTON`` event.
6988
6989 Args:
6990 event (wx.CommandEvent): a `wx.CommandEvent` event to be processed.
6991 """
6992 defaultDir, defaultFile = (
6993 get_verified_path("last_filedialog_path")[0],
6994 APPNAME,
6995 )
6996 dlg = _FileDialog(
6997 self,
6998 lang.getstr("save_as"),
6999 defaultDir=defaultDir,
7000 defaultFile=defaultFile,
7001 wildcard=lang.getstr("filetype.log") + "|*.log",
7002 style=wx.FD_SAVE | wx.FD_OVERWRITE_PROMPT,
7003 )
7004 dlg.Center(wx.BOTH)
7005 result = dlg.ShowModal()
7006 path = dlg.GetPath()
7007 dlg.Destroy()
7008 if result != wx.ID_OK:
7009 return
7010 if not waccess(path, os.W_OK):
7011 InfoDialog(
7012 self,
7013 msg=lang.getstr("error.access_denied.write", path),
7014 ok=lang.getstr("ok"),
7015 bitmap=get_icon(32, "dialog-error"),
7016 )
7017 return
7018 filename, ext = os.path.splitext(path)
7019 if ext.lower() != ".log":
7020 path += ".log"
7021 if os.path.exists(path):
7022 dlg = ConfirmDialog(
7023 self,
7024 msg=lang.getstr("dialog.confirm_overwrite", (path)),
7025 ok=lang.getstr("overwrite"),
7026 cancel=lang.getstr("cancel"),
7027 bitmap=get_icon(32, "dialog-warning"),
7028 )
7029 result = dlg.ShowModal()
7030 dlg.Destroy()
7031 if result != wx.ID_OK:
7032 return
7033 setcfg("last_filedialog_path", path)
7034 try:
7035 with open(path, "w", encoding="UTF-8", errors="replace") as file_:
7036 file_.write(self.log_txt.GetValue())
7037 except Exception as exception:
7038 InfoDialog(
7039 self,
7040 msg=str(exception),
7041 ok=lang.getstr("ok"),
7042 bitmap=get_icon(32, "dialog-error"),
7043 )
7044
7045 def OnSize(self, event=None):
7046 """Handle the ``wx.EVT_SIZE`` event.
7047
7048 Args:
7049 event (wx.SizeEvent): a `wx.SizeEvent` event to be processed.
7050 """
7051 if self.IsShownOnScreen() and not self.IsMaximized() and not self.IsIconized():
7052 w, h = self.ClientSize
7053 setcfg("size.info.w", w)
7054 setcfg("size.info.h", h)
7055 if event:
7056 event.Skip()
7057
7058 def create_logs_archive(self, event):
7059 """Create a compressed archive of the log directory.
7060
7061 Args:
7062 event (wx.Event): The event that triggered the method.
7063 """
7064 wildcard = lang.getstr("filetype.tgz") + "|*.tgz"
7065 wildcard += "|" + lang.getstr("filetype.zip") + "|*.zip"
7066 defaultDir, defaultFile = (
7067 get_verified_path("last_filedialog_path")[0],
7068 APPNAME + "-logs",
7069 )
7070 dlg = _FileDialog(
7071 self,
7072 lang.getstr("save_as"),
7073 defaultDir=defaultDir,
7074 defaultFile=defaultFile,
7075 wildcard=wildcard,
7076 style=wx.FD_SAVE | wx.FD_OVERWRITE_PROMPT,
7077 )
7078 dlg.Center(wx.BOTH)
7079 result = dlg.ShowModal()
7080 path = dlg.GetPath()
7081 dlg.Destroy()
7082 if result == wx.ID_OK:
7083 if not waccess(path, os.W_OK):
7084 InfoDialog(
7085 self,
7086 msg=lang.getstr("error.access_denied.write", path),
7087 ok=lang.getstr("ok"),
7088 bitmap=get_icon(32, "dialog-error"),
7089 )
7090 return
7091 filename, ext = os.path.splitext(path)
7092 file_format = "tgz" if path.lower().endswith(".tar.gz") else ext[1:]
7093 if ext.lower() != "." + file_format and (
7094 file_format != "tgz" or not path.lower().endswith(".tar.gz")
7095 ):
7096 path += "." + file_format
7097 if os.path.exists(path):
7098 dlg = ConfirmDialog(
7099 self,
7100 msg=lang.getstr("dialog.confirm_overwrite", (path)),
7101 ok=lang.getstr("overwrite"),
7102 cancel=lang.getstr("cancel"),
7103 bitmap=get_icon(32, "dialog-warning"),
7104 )
7105 result = dlg.ShowModal()
7106 dlg.Destroy()
7107 if result != wx.ID_OK:
7108 return
7109 setcfg("last_filedialog_path", path)
7110 if file_format == "tgz":
7111 # Create gzipped tar archive
7112 with tarfile.open(path, "w:gz", encoding="UTF-8") as tar:
7113 tar.add(LOGDIR, arcname=os.path.basename(path))
7114 else:
7115 # Create ZIP archive
7116 try:
7117 with zipfile.ZipFile(path, "w", zipfile.ZIP_DEFLATED) as zip_file:
7118 for filename in os.listdir(LOGDIR):
7119 zip_file.write(os.path.join(LOGDIR, filename), filename)
7120 except Exception as exception:
7121 InfoDialog(
7122 self,
7123 msg=str(exception),
7124 ok=lang.getstr("ok"),
7125 bitmap=get_icon(32, "dialog-error"),
7126 )
7127
7128
7129 class ProgressDialog(wx.Dialog):
7130 """A progress dialog."""
7131
7132 bitmaps: ClassVar[dict] = {}
7133
7134 def __init__(
7135 self,
7136 title=APPNAME,
7137 msg="",
7138 maximum=100,
7139 parent=None,
7140 style=None,
7141 handler=None,
7142 keyhandler=None,
7143 start_timer=True,
7144 pos=None,
7145 pauseable=False,
7146 fancy=True,
7147 allow_close=False,
7148 ):
7149 if style is None:
7150 style = (
7151 wx.PD_APP_MODAL
7152 | wx.PD_ELAPSED_TIME
7153 | wx.PD_REMAINING_TIME
7154 | wx.PD_CAN_ABORT
7155 | wx.PD_SMOOTH
7156 )
7157 self._style = style
7158 wx.Dialog.__init__(self, parent, wx.ID_ANY, title, name="progressdialog")
7159 if fancy:
7160 self.BackgroundColour = "#141414"
7161 self.ForegroundColour = "#FFFFFF"
7162 self.taskbar = None
7163 if sys.platform == "win32":
7164 if not fancy:
7165 bgcolor = self.BackgroundColour
7166 self.SetBackgroundColour(
7167 wx.SystemSettings.GetColour(wx.SYS_COLOUR_WINDOW)
7168 )
7169 if sys.getwindowsversion() >= (6,):
7170 # No need to enable double buffering under Linux and Mac OS X.
7171 # Under Windows, enabling double buffering on the panel seems
7172 # to work best to reduce flicker.
7173 self.SetDoubleBuffered(True)
7174 set_icons(self)
7175 self.Bind(wx.EVT_CLOSE, self.OnClose, self)
7176 if not pos:
7177 self.Bind(wx.EVT_MOVE, self.OnMove, self)
7178 self.timer = BetterTimer(self)
7179 self.Bind(EVT_BETTER_TIMER, handler or self.OnTimer, self.timer)
7180
7181 self.indeterminate = True
7182 self.keepGoing = True
7183 self.skip = False
7184 self.paused = False
7185 self.progress_type = 0 # 0 = processing, 1 = measurement
7186 self.allow_close = allow_close
7187
7188 margin = 12
7189
7190 self.sizer0 = wx.BoxSizer(wx.VERTICAL)
7191 if fancy:
7192 self.sizerH = wx.BoxSizer(wx.HORIZONTAL)
7193 self.SetSizer(self.sizerH)
7194 self.animbmp = AnimatedBitmap(self, -1, size=(200, 200))
7195 self.sizerH.Add(self.animbmp, 0, flag=wx.ALIGN_CENTER_VERTICAL)
7196 self.sizerH.Add(self.sizer0, 1, flag=wx.EXPAND)
7197 try:
7198 audio.init()
7199 except Exception as exception:
7200 print(exception)
7201 self.processor_sound = audio.Sound(
7202 get_data_path("theme/engine_hum_loop.wav"), True
7203 )
7204 self.generator_sound = audio.Sound(
7205 get_data_path("theme/pulsing_loop.wav"), True
7206 )
7207 self.sound = self.processor_sound
7208 self.indicator_sound = audio.Sound(get_data_path("theme/beep_boop.wav"))
7209 ProgressDialog.get_bitmaps(self.progress_type)
7210 sizer0flag = 0
7211 else:
7212 self.SetSizer(self.sizer0)
7213 sizer0flag = wx.LEFT
7214 self.sizer1 = wx.BoxSizer(wx.VERTICAL)
7215 self.sizer2 = wx.BoxSizer(wx.HORIZONTAL)
7216 self.sizer0.Add(
7217 self.sizer1,
7218 flag=wx.ALIGN_LEFT | wx.TOP | wx.RIGHT | sizer0flag,
7219 border=margin,
7220 )
7221 self.buttonpanel = wx.Panel(self)
7222 self.buttonpanel.SetSizer(wx.BoxSizer(wx.VERTICAL))
7223 self.buttonpanel.Sizer.Add(
7224 self.sizer2, 1, flag=wx.ALIGN_RIGHT | wx.ALL, border=margin
7225 )
7226 if sys.platform == "win32" and not fancy:
7227 self.buttonpanel_line = wx.Panel(self, size=(-1, 1))
7228 self.buttonpanel_line.SetBackgroundColour(
7229 wx.SystemSettings.GetColour(wx.SYS_COLOUR_3DLIGHT)
7230 )
7231 self.sizer0.Add(
7232 self.buttonpanel_line, flag=wx.TOP | wx.EXPAND, border=margin
7233 )
7234 self.buttonpanel.SetBackgroundColour(bgcolor)
7235 elif fancy:
7236 self.buttonpanel.BackgroundColour = "#141414"
7237 self.sizer0.Add(self.buttonpanel, flag=wx.EXPAND)
7238
7239 self.msg = wx.StaticText(self, -1, "", size=(-1, 74))
7240 self.sizer1.Add(self.msg, flag=wx.EXPAND | wx.BOTTOM, border=margin)
7241
7242 self._fpprogress = 0.0
7243 if fancy:
7244 self.gauge = BetterPyGauge(
7245 self, wx.ID_ANY, range_=maximum, size=(-1, 4), pd=self
7246 )
7247 self.gauge.BackgroundColour = "#003366"
7248 self.gauge.SetBarGradients(
7249 [
7250 ("#0099CC", "#00CCFF"),
7251 ("#0088BB", "#00BBEE"),
7252 ("#0077AA", "#00AADD"),
7253 ("#006699", "#0099CC"),
7254 ("#0077AA", "#00AADD"),
7255 ("#0088BB", "#00BBEE"),
7256 ]
7257 )
7258 self.gauge.SetIndeterminateBarGradients(
7259 [
7260 ("#00CCFF", "#001144"),
7261 ("#00BBEE", "#002255"),
7262 ("#00AADD", "#003366"),
7263 ("#0099CC", "#004477"),
7264 ("#0088BB", "#005588"),
7265 ("#0077AA", "#006699"),
7266 ("#006699", "#0077AA"),
7267 ("#005588", "#0088BB"),
7268 ("#004477", "#0099CC"),
7269 ("#003366", "#00AADD"),
7270 ("#002255", "#00BBEE"),
7271 ("#001144", "#00CCFF"),
7272 ("#002255", "#00BBEE"),
7273 ("#003366", "#00AADD"),
7274 ("#004477", "#0099CC"),
7275 ("#005588", "#0088BB"),
7276 ("#006699", "#0077AA"),
7277 ("#0077AA", "#006699"),
7278 ("#0088BB", "#005588"),
7279 ("#0099CC", "#004477"),
7280 ("#00AADD", "#003366"),
7281 ("#00BBEE", "#002255"),
7282 ]
7283 )
7284 self.gauge.SetValue(0)
7285 else:
7286 gauge_style = wx.GA_HORIZONTAL
7287 if style & wx.PD_SMOOTH:
7288 gauge_style |= wx.GA_SMOOTH
7289 self.gauge = wx.Gauge(self, wx.ID_ANY, range=maximum, style=gauge_style)
7290 self.sizer1.Add(self.gauge, flag=wx.EXPAND | wx.BOTTOM, border=margin)
7291
7292 if style & wx.PD_ELAPSED_TIME or style & wx.PD_REMAINING_TIME:
7293 self.sizer3 = wx.FlexGridSizer(0, 2, 0, margin)
7294 self.sizer1.Add(self.sizer3, flag=wx.ALIGN_LEFT)
7295
7296 if style & wx.PD_ELAPSED_TIME:
7297 self.elapsed_time_label = wx.StaticText(
7298 self, -1, lang.getstr("elapsed_time")
7299 )
7300 self.elapsed_time_label.SetMaxFontSize(11)
7301 self.sizer3.Add(self.elapsed_time_label)
7302 self.elapsed_time = wx.StaticText(self, -1, "")
7303 self.elapsed_time.SetMaxFontSize(11)
7304 self.sizer3.Add(self.elapsed_time)
7305 self.elapsed_timer = BetterTimer(self)
7306 self.Bind(EVT_BETTER_TIMER, self.elapsed_time_handler, self.elapsed_timer)
7307
7308 if style & wx.PD_REMAINING_TIME:
7309 self.remaining_time_label = wx.StaticText(
7310 self, -1, lang.getstr("remaining_time")
7311 )
7312 self.remaining_time_label.SetMaxFontSize(11)
7313 self.sizer3.Add(self.remaining_time_label)
7314 self.remaining_time = wx.StaticText(self, -1, "")
7315 self.remaining_time.SetMaxFontSize(11)
7316 self.sizer3.Add(self.remaining_time)
7317
7318 self.reset()
7319
7320 if fancy:
7321
7322 def buttoncls(parent, id, label): # noqa: A002
7323 return FlatShadedButton(parent, id, None, label, fgcolour="#FFFFFF")
7324
7325 else:
7326 buttoncls = wx.Button
7327
7328 if style & wx.PD_CAN_ABORT:
7329 self.cancel = buttoncls(self.buttonpanel, wx.ID_ANY, lang.getstr("cancel"))
7330 self.sizer2.Add(self.cancel)
7331 self.Bind(wx.EVT_BUTTON, self.OnClose, id=self.cancel.GetId())
7332
7333 self.pause_continue = buttoncls(
7334 self.buttonpanel, wx.ID_ANY, lang.getstr("continue")
7335 )
7336 self.sizer2.Prepend((margin, margin))
7337 self.sizer2.Prepend(self.pause_continue, flag=wx.LEFT, border=margin)
7338 self.Bind(
7339 wx.EVT_BUTTON, self.pause_continue_handler, id=self.pause_continue.GetId()
7340 )
7341 self.pause_continue.Show(pauseable)
7342
7343 if fancy:
7344 bitmap = self.get_sound_on_off_btn_bitmap()
7345 self.sound_on_off_btn = FlatShadedButton(
7346 self.buttonpanel, bitmap=bitmap, fgcolour="#FFFFFF"
7347 )
7348 self.sizer2.Prepend(self.sound_on_off_btn)
7349 self.sound_on_off_btn.Bind(wx.EVT_BUTTON, self.play_sound_handler)
7350
7351 self.buttonpanel.Layout()
7352
7353 # Use an accelerator table for 0-9, a-z, numpad
7354 keycodes = list(range(48, 58)) + list(range(97, 123)) + NUMPAD_KEYCODES
7355 self.id_to_keycode = {}
7356 for keycode in keycodes:
7357 self.id_to_keycode[wx.Window.NewControlId()] = keycode
7358 accels = []
7359 for id_ in self.id_to_keycode:
7360 keycode = self.id_to_keycode[id_]
7361 self.Bind(wx.EVT_MENU, keyhandler or self.key_handler, id=id_)
7362 accels.append((wx.ACCEL_NORMAL, keycode, id_))
7363 self.SetAcceleratorTable(wx.AcceleratorTable(accels))
7364
7365 self.msg.SetMaxFontSize(11)
7366 self.msg.Label = "\n".join(["E" * 80] * 4)
7367 w, h = self.msg.Size
7368 self.msg.WindowStyle |= wx.ST_NO_AUTORESIZE
7369 self.msg.SetMinSize((w, h))
7370 self.msg.SetSize((w, h))
7371 self.Sizer.SetSizeHints(self)
7372 self.Sizer.Layout()
7373 self.msg.SetLabel(msg.replace("&", "&&"))
7374
7375 self.pause_continue.Label = lang.getstr("pause")
7376
7377 self.Bind(wx.EVT_WINDOW_DESTROY, self.OnDestroy, self)
7378
7379 if "gtk3" in wx.PlatformInfo:
7380 # Fix background color not working for panels under GTK3
7381 self.Bind(wx.EVT_ERASE_BACKGROUND, self.OnEraseBackground)
7382
7383 # set position
7384 self.place(pos)
7385
7386 if start_timer:
7387 self.start_timer()
7388
7389 self.Show()
7390 if style & wx.PD_APP_MODAL:
7391 self.MakeModal()
7392
7393 if "gtk3" in wx.PlatformInfo:
7394 OnEraseBackground = wx_Panel.__dict__["OnEraseBackground"]
7395
7396 def MakeModal(self, modal=True):
7397 """Make the dialog modal or non-modal.
7398
7399 Args:
7400 modal (bool): If True, make the dialog modal; if False, make it
7401 non-modal.
7402 """
7403 # wxPython 3.0 deprecates MakeModal, use a replacement implementation
7404 # based on http://wxpython.org/Phoenix/docs/html/MigrationGuide.html
7405 if modal and not hasattr(self, "_disabler"):
7406 self._disabler = BetterWindowDisabler(self)
7407 if not modal and hasattr(self, "_disabler"):
7408 del self._disabler
7409
7410 def OnClose(self, event):
7411 """Handle the close event of the progress dialog.
7412
7413 Args:
7414 event (wx.CloseEvent): The close event.
7415 """
7416 self.keepGoing = False
7417 if hasattr(self, "cancel"):
7418 self.cancel.Disable()
7419 self.pause_continue.Disable()
7420 if not self.timer.IsRunning() and self.allow_close:
7421 self.Destroy()
7422 elif self.gauge.GetValue() == self.gauge.GetRange():
7423 event.Skip()
7424
7425 def OnDestroy(self, event):
7426 """Handle the destruction of the progress dialog.
7427
7428 Args:
7429 event (wx.WindowDestroyEvent): The window destroy event.
7430 """
7431 self.stop_timer()
7432 del self.timer
7433 if not hasattr(wx.Window, "UnreserveControlId"):
7434 return 0
7435 for id_ in self.id_to_keycode:
7436 if id_ >= 0:
7437 continue
7438 try:
7439 wx.Window.UnreserveControlId(id_)
7440 except wx.wxAssertionError as exception:
7441 print(exception)
7442
7443 return 0
7444
7445 def OnMove(self, event):
7446 """Handle the move event to update the dialog's position.
7447
7448 Args:
7449 event (wx.MoveEvent): The move event.
7450 """
7451 if (
7452 self.IsShownOnScreen()
7453 and not self.IsIconized()
7454 and (not self.GetParent() or not self.GetParent().IsShownOnScreen())
7455 ):
7456 prev_x = getcfg("position.progress.x")
7457 prev_y = getcfg("position.progress.y")
7458 x, y = self.GetScreenPosition()
7459 if x != prev_x or y != prev_y:
7460 setcfg("position.progress.x", x)
7461 setcfg("position.progress.y", y)
7462
7463 def OnTimer(self, event):
7464 """Handle the timer event to update the progress dialog.
7465
7466 Args:
7467 event (wx.TimerEvent): The timer event.
7468 """
7469 if self.keepGoing:
7470 if not self.pause_continue.IsEnabled():
7471 self.set_progress_type(int(not self.progress_type))
7472 self.pause_continue.Enable()
7473 if self.paused:
7474 return
7475 if self._fpprogress < self.gauge.GetRange():
7476 self.UpdateProgress(self._fpprogress + self.gauge.GetRange() / 1000.0)
7477 else:
7478 self.stop_timer(False)
7479 self.UpdateProgress(
7480 self.gauge.GetRange(), "Finished. You may now close this window."
7481 )
7482 self.pause_continue.Disable()
7483 if hasattr(self, "cancel"):
7484 self.cancel.Disable()
7485 else:
7486 self.Pulse("Aborting...")
7487 if not hasattr(self, "delayed_stop"):
7488 self.delayed_stop = wx.CallLater(3000, self.stop_timer, False)
7489 wx.CallLater(
7490 3000, self.Pulse, "Aborted. You may now close this window."
7491 )
7492
7493 def GetValue(self):
7494 """Get the current value of the progress dialog.
7495
7496 Returns:
7497 float: The current progress value, between 0 and the maximum.
7498 """
7499 return self._fpprogress
7500
7501 def SetValue(self, value):
7502 """Set the progress dialog's value.
7503
7504 Args:
7505 value (float): The new progress value, between 0 and the maximum.
7506 """
7507 self.UpdateProgress(value)
7508
7509 Value = property(GetValue, SetValue)
7510
7511 def Pulse(self, msg=None):
7512 """Pulse the progress dialog, indicating that it is still active.
7513
7514 Args:
7515 msg (None | str): The message to display. Defaults to None.
7516
7517 Returns:
7518 tuple[bool, bool]: A tuple containing two boolean values:
7519 - keepGoing: Whether the dialog should continue running.
7520 - skip: Whether to skip the current operation.
7521 """
7522 if msg and msg != self.msg.Label:
7523 self.msg.SetLabel(msg)
7524 self.msg.Wrap(self.msg.ContainingSizer.Size[0])
7525 self.msg.Refresh()
7526 if getattr(self, "time2", 0):
7527 self.time2 = 0
7528 if not self.time3:
7529 self.time3 = time()
7530 if not self.indeterminate:
7531 self.indeterminate = True
7532 if hasattr(self, "remaining_time"):
7533 self.remaining_time.Label = REMAINING_TIME_LABEL
7534 if self.taskbar and not self.paused:
7535 self.taskbar.set_progress_state(TASKBAR.TBPF_INDETERMINATE)
7536 self.gauge.Pulse()
7537 return self.keepGoing, self.skip
7538
7539 def Resume(self):
7540 """Resume the progress dialog after a pause."""
7541 self.keepGoing = True
7542 if hasattr(self, "sound_on_off_btn"):
7543 self.set_sound_on_off_btn_bitmap()
7544 if hasattr(self, "cancel"):
7545 self.cancel.Enable()
7546 if self.paused:
7547 self.pause_continue_handler()
7548 else:
7549 self.pause_continue.Enable()
7550
7551 def UpdateProgress(self, value, msg=None):
7552 """Update the progress dialog with a new value and message.
7553
7554 Args:
7555 value (float): The new progress value, between 0 and the maximum.
7556 msg (None | str): The message to display. Defaults to None.
7557 """
7558 self.indeterminate = False
7559 if msg and msg != self.msg.Label:
7560 self.msg.SetLabel(msg)
7561 self.msg.Wrap(self.msg.ContainingSizer.Size[0])
7562 self.msg.Refresh()
7563 prev_value = self._fpprogress
7564 if value == prev_value:
7565 return self.keepGoing, self.skip
7566 self._fpprogress = value
7567 value = round(value)
7568 if hasattr(self, "time2"):
7569 t = time()
7570 if not self.time2:
7571 if value < self.gauge.GetValue():
7572 # Reset
7573 self.time2 = t
7574 else:
7575 # Continue
7576 self.time4 += time() - self.time3
7577 self.time2 = self.time + self.time4
7578 self.time3 = 0
7579 if (
7580 getcfg("measurement.play_sound")
7581 and self._fpprogress < prev_value
7582 and hasattr(self, "indicator_sound")
7583 and not self.indicator_sound.is_playing
7584 ):
7585 self.indicator_sound.safe_play()
7586 if isinstance(self.gauge, BetterPyGauge) and self._style & wx.PD_SMOOTH:
7587 if self._fpprogress >= prev_value:
7588 update_value = abs(self._fpprogress - prev_value)
7589 if update_value:
7590 # Higher ms = smoother animation, but potentially
7591 # increased "lag"
7592 ms = 450 + 50 * update_value
7593 self.gauge.Update(self._fpprogress, ms)
7594 else:
7595 self.gauge.Update(self._fpprogress, 50)
7596 else:
7597 self.gauge.SetValue(value)
7598 if self.taskbar:
7599 self.taskbar.set_progress_value(value)
7600 return self.keepGoing, self.skip
7601
7602 UpdatePulse = Pulse
7603
7604 def anim_fadein(self):
7605 """Fade in the animation."""
7606 bitmaps = ProgressDialog.get_bitmaps(self.progress_type)
7607 if self.progress_type == 0:
7608 # Processing
7609 frame_range = (60, 68)
7610 loop = True
7611 elif self.progress_type == 1:
7612 # Measuring
7613 frame_range = (0, 9)
7614 loop = False
7615 else:
7616 # Generating test patches
7617 frame_range = (27, 36)
7618 loop = True
7619 self.animbmp.SetBitmaps(bitmaps, range_=frame_range, loop=loop)
7620 if self.progress_type == 1:
7621 self.animbmp.frame = 4
7622 wx.CallLater(50, lambda: self and self.IsShown() and self.animbmp.Play(24))
7623
7624 def sound_fadein(self):
7625 """Fade in the sound if it is not playing."""
7626 if getcfg("measurement.play_sound"):
7627 wx.CallLater(
7628 50,
7629 lambda: (
7630 self
7631 and self.IsShown()
7632 and self.sound.safe_fade(self.sound_get_delay(), True)
7633 ),
7634 )
7635
7636 def anim_fadeout(self):
7637 """Fade out the animation."""
7638 self.animbmp.loop = False
7639 self.animbmp.range = self.animbmp.range[0], -1
7640
7641 def sound_fadeout(self):
7642 """Fade out the sound if it is playing."""
7643 if self.sound.is_playing:
7644 self.sound.safe_stop(self.sound_get_delay())
7645
7646 def sound_get_delay(self):
7647 """Get the delay for the sound fade in/out.
7648
7649 Returns:
7650 int: The delay in milliseconds.
7651 """
7652 if self.sound is self.processor_sound:
7653 return 3000
7654 return 1500
7655
7656 def elapsed_time_handler(self, event):
7657 """Update the elapsed time and remaining time labels.
7658
7659 Args:
7660 event: The timer event that triggered this handler.
7661 """
7662 self.elapsed_time.Label = strftime("%H:%M:%S", gmtime(time() - self.time))
7663 value = self._fpprogress
7664 if getattr(self, "time2", 0) and value:
7665 t = time()
7666 if self.time2 < t:
7667 remaining = (t - self.time2) / value * (self.gauge.GetRange() - value)
7668 if remaining >= 0:
7669 self.remaining_time.Label = strftime("%H:%M:%S", gmtime(remaining))
7670
7671 @staticmethod
7672 def get_bitmaps(progress_type=0) -> list:
7673 """Get the bitmaps for the progress dialog animations.
7674
7675 Args:
7676 progress_type (int): The type of progress animation to retrieve.
7677 0 for processing, 1 for measurement, 2 for generating test patches.
7678
7679 Returns:
7680 list: A list of wx.Image objects representing the animation frames.
7681 """
7682 if progress_type in ProgressDialog.bitmaps:
7683 return ProgressDialog.bitmaps[progress_type]
7684
7685 bitmaps = ProgressDialog.bitmaps[progress_type] = []
7686 if progress_type == 0:
7687 # Animation for processing
7688 for pth in get_data_path("theme/shutter_anim", r"\.png$") or []:
7689 im = wx.Image(pth)
7690 if im.IsOk():
7691 bitmaps.append(im)
7692 for pth in get_data_path("theme/jet_anim", r"\.png$") or []:
7693 im = wx.Image(pth)
7694 if not im.IsOk():
7695 continue
7696 # Blend red
7697 im = im.AdjustChannels(1, 0.25, 0)
7698 # Adjust for background
7699 im.AdjustMinMax(1.0 / 255 * 0x14)
7700 bitmaps.append(im)
7701 # Needs to be exactly 17 images
7702 if bitmaps and len(bitmaps) == 17:
7703 for _ in range(7):
7704 bitmaps.extend(bitmaps[9:17])
7705 bitmaps.extend(bitmaps[9:13])
7706 # Fade in
7707 for i, im in enumerate(bitmaps[9:19]):
7708 bg = bitmaps[8].ConvertToBitmap()
7709 im = im.AdjustChannels(1, 1, 1, i / 10.0)
7710 bg.Blend(im.ConvertToBitmap(), 0, 0)
7711 bitmaps[i + 9] = bg
7712 for i, im in enumerate(bitmaps[:9]):
7713 bitmaps[i] = im.ConvertToBitmap()
7714 # Normal
7715 for i in range(41):
7716 im = bitmaps[i + 19].Copy()
7717 im.RotateHue(0.05 * (i / 50.0))
7718 bitmaps[i + 19] = im.ConvertToBitmap()
7719 for i, im in enumerate(bitmaps[60:]):
7720 im = im.Copy()
7721 im.RotateHue(0.05)
7722 bitmaps[i + 60] = im.ConvertToBitmap()
7723 # Fade out
7724 bitmaps.extend(reversed(bitmaps[:60]))
7725 else:
7726 bitmaps = ProgressDialog.bitmaps[progress_type] = []
7727 elif progress_type == 1:
7728 # Animation for measurements
7729 for i, pth in enumerate(
7730 get_data_path("theme/shutter_anim", r"\.png$") or []
7731 ):
7732 if i < 5:
7733 bmp = get_bitmap(os.path.splitext(pth)[0])
7734 bitmaps.insert(0, bmp)
7735 if bitmaps and len(bitmaps) == 5:
7736 bitmaps.extend(reversed(bitmaps[:5]))
7737 bitmaps.extend(bitmaps[:5])
7738 else:
7739 # Animation for generating test patches
7740 for pth in get_data_path("theme/patch_anim", r"\.png$") or []:
7741 im = wx.Image(pth)
7742 if im.IsOk():
7743 bitmaps.append(im)
7744 # Needs to be exactly 9 images
7745 if bitmaps and len(bitmaps) == 9:
7746 for _ in range(3):
7747 bitmaps.extend(bitmaps[:9])
7748 # Fade in
7749 for i, im in enumerate(bitmaps[:27]):
7750 im = im.AdjustChannels(1, 1, 1, i / 27.0)
7751 bitmaps[i] = im.ConvertToBitmap()
7752 # Normal
7753 for i, im in enumerate(bitmaps[27:]):
7754 bitmaps[i + 27] = im.ConvertToBitmap()
7755 # Fade out
7756 for _ in range(3):
7757 bitmaps.extend(bitmaps[27:36])
7758 for i, bmp in enumerate(bitmaps[36:]):
7759 im = bmp.ConvertToImage().AdjustChannels(1, 1, 1, 1 - i / 26.0)
7760 bitmaps[i + 36] = im.ConvertToBitmap()
7761 else:
7762 bitmaps = ProgressDialog.bitmaps[progress_type] = []
7763 return bitmaps
7764
7765 def key_handler(self, event):
7766 """Handle key events for the progress dialog.
7767
7768 Args:
7769 event: The key event that triggered this handler.
7770 """
7771
7772 def pause_continue_handler(self, event=None):
7773 """Toggle pause/continue state.
7774
7775 Args:
7776 event: The event that triggered this handler, if any.
7777 """
7778 if not self.pause_continue.IsShown():
7779 return
7780 self.paused = not self.paused
7781 if self.paused:
7782 self.pause_continue.Label = lang.getstr("continue")
7783 if self.taskbar:
7784 self.taskbar.set_progress_state(TASKBAR.TBPF_PAUSED)
7785 else:
7786 self.pause_continue.Label = lang.getstr("pause")
7787 if self.taskbar:
7788 if self.indeterminate:
7789 state = TASKBAR.TBPF_INDETERMINATE
7790 else:
7791 state = TASKBAR.TBPF_NORMAL
7792 self.taskbar.set_progress_state(state)
7793 self.pause_continue.Enable(not event)
7794 self.Layout()
7795 if getattr(self, "time2", 0):
7796 self.time2 = 0
7797 if not self.time3:
7798 self.time3 = time()
7799
7800 def place(self, pos=None):
7801 """Set position.
7802
7803 Args:
7804 pos (None | tuple): A tuple containing the x and y coordinates
7805 for the dialog's position. If None, the dialog will be centered
7806 on the parent or use the last saved position.
7807 """
7808 placed = False
7809 if pos:
7810 x, y = pos
7811 elif self.Parent and self.Parent.IsShownOnScreen():
7812 self.Center()
7813 placed = True
7814 else:
7815 x = getcfg("position.progress.x")
7816 y = getcfg("position.progress.y")
7817 if not placed:
7818 self.SetSaneGeometry(x, y)
7819
7820 def play_sound_handler(self, event):
7821 """Toggle the sound on/off.
7822
7823 Args:
7824 event: The event that triggered this handler.
7825 """
7826 setcfg(
7827 "measurement.play_sound", int(not (bool(getcfg("measurement.play_sound"))))
7828 )
7829 if getcfg("measurement.play_sound"):
7830 if (
7831 self.progress_type in (0, 2)
7832 and self.keepGoing
7833 and self._fpprogress < self.gauge.GetRange()
7834 ):
7835 self.sound.safe_play()
7836 elif self.sound.is_playing:
7837 self.sound.safe_stop()
7838 self.set_sound_on_off_btn_bitmap()
7839
7840 def get_sound_on_off_btn_bitmap(self):
7841 """Get the bitmap for the sound on/off button."""
7842 if getcfg("measurement.play_sound"):
7843 bitmap = get_icon(16, "sound_volume_full")
7844 else:
7845 bitmap = get_icon(16, "sound_off")
7846 im = bitmap.ConvertToImage()
7847 im.AdjustMinMax(maxvalue=1.5)
7848 return im.ConvertToBitmap()
7849
7850 def set_sound_on_off_btn_bitmap(self):
7851 """Set the bitmap for the sound on/off button."""
7852 bitmap = self.get_sound_on_off_btn_bitmap()
7853 self.sound_on_off_btn._bitmap = bitmap
7854
7855 def reset(self):
7856 """Reset the progress dialog to its initial state."""
7857 self._fpprogress = 0
7858 self.gauge.SetValue(0)
7859 self.time = time()
7860 if hasattr(self, "elapsed_time"):
7861 self.elapsed_time_handler(None)
7862 if hasattr(self, "remaining_time"):
7863 self.time2 = 0
7864 self.time3 = self.time
7865 self.time4 = 0
7866 self.remaining_time.Label = REMAINING_TIME_LABEL
7867
7868 def set_progress_type(self, progress_type):
7869 """Set the progress type and update animations and sounds accordingly.
7870
7871 Args:
7872 progress_type (int): The type of progress (0 for processing, 1 for
7873 measuring, 2 for generating test patches).
7874 """
7875 if progress_type != self.progress_type:
7876 if self.progress_type == 0:
7877 # Processing
7878 delay = 4000
7879 elif self.progress_type == 1:
7880 # Measuring
7881 delay = 500
7882 else:
7883 # Generating test patches
7884 delay = 2000
7885 if hasattr(self, "animbmp"):
7886 self.anim_fadeout()
7887 wx.CallLater(
7888 delay,
7889 lambda: (
7890 self
7891 and self.progress_type == progress_type
7892 and self.anim_fadein()
7893 ),
7894 )
7895 if hasattr(self, "sound"):
7896 self.sound_fadeout()
7897 if progress_type in (0, 2):
7898 self.set_sound(progress_type)
7899 wx.CallLater(
7900 delay,
7901 lambda: (
7902 self
7903 and self.progress_type == progress_type
7904 and self.sound_fadein()
7905 ),
7906 )
7907 self.progress_type = progress_type
7908
7909 def set_sound(self, progress_type=0):
7910 """Set the sound based on the progress type.
7911
7912 Args:
7913 progress_type (int): The type of progress (0 for processing, 1 for
7914 measuring, 2 for generating test patches).
7915 """
7916 if progress_type == 0 and hasattr(self, "processor_sound"):
7917 self.sound = self.processor_sound
7918 elif hasattr(self, "generator_sound"):
7919 self.sound = self.generator_sound
7920
7921 def start_timer(self, ms=75):
7922 """Start the timer and animations.
7923
7924 Args:
7925 ms (int): The interval in milliseconds for the timer.
7926 """
7927 self.timer.Start(ms)
7928 if isinstance(self.gauge, BetterPyGauge) and not self.gauge.IsRunning():
7929 self.gauge.Start()
7930 if hasattr(self, "elapsed_timer"):
7931 self.elapsed_timer.Start(1000)
7932 if hasattr(self, "animbmp"):
7933 self.anim_fadein()
7934 if hasattr(self, "sound") and self.progress_type in (0, 2):
7935 self.set_sound(self.progress_type)
7936 self.sound_fadein()
7937 if TASKBAR:
7938 if self.Parent and self.Parent.IsShownOnScreen():
7939 taskbarframe = self.Parent
7940 else:
7941 taskbarframe = self
7942 self.taskbar = TASKBAR.Taskbar(taskbarframe, self.gauge.GetRange())
7943 self.taskbar.set_progress_state(TASKBAR.TBPF_INDETERMINATE)
7944
7945 def stop_timer(self, immediate=True):
7946 """Stop the timer and animations.
7947
7948 Args:
7949 immediate (bool): If True, stop animations immediately, otherwise
7950 fade out.
7951 """
7952 if self.taskbar:
7953 self.taskbar.set_progress_state(TASKBAR.TBPF_NOPROGRESS)
7954 if not self.timer.IsRunning():
7955 return
7956 self.timer.Stop()
7957 if isinstance(self.gauge, BetterPyGauge) and immediate:
7958 self.gauge.Stop()
7959 if hasattr(self, "elapsed_timer"):
7960 self.elapsed_timer.Stop()
7961 if hasattr(self, "animbmp"):
7962 if immediate:
7963 self.animbmp.Stop()
7964 elif self.animbmp.loop or self.animbmp.range[1] != -1:
7965 self.anim_fadeout()
7966 if hasattr(self, "sound"):
7967 self.sound_fadeout()
7968
7969
7970 class FancyProgressDialog(ProgressDialog):
7971 """A fancy progress dialog."""
7972
7973 def __init__(self, *args, **kwargs):
7974 kwargs["fancy"] = True
7975 ProgressDialog.__init__(self, *args, **kwargs)
7976
7977
7978 class SimpleBook(labelbook.FlatBookBase):
7979 """A simple book-like control."""
7980
7981 def __init__(
7982 self,
7983 parent,
7984 id=wx.ID_ANY, # noqa: A002
7985 pos=wx.DefaultPosition,
7986 size=wx.DefaultSize,
7987 style=0,
7988 agw_style=0,
7989 name="SimpleBook",
7990 ):
7991 labelbook.FlatBookBase.__init__(
7992 self, parent, id, pos, size, style, agw_style, name
7993 )
7994
7995 self._pages = self.CreateImageContainer()
7996
7997 # Label book specific initialization
7998 self._mainSizer = wx.BoxSizer(wx.HORIZONTAL)
7999 self.SetSizer(self._mainSizer)
8000
8001 if "gtk3" in wx.PlatformInfo:
8002 # Fix background color not working for panels under GTK3
8003 self.Bind(wx.EVT_ERASE_BACKGROUND, self.OnEraseBackground)
8004
8005 if "gtk3" in wx.PlatformInfo:
8006 OnEraseBackground = wx_Panel.__dict__["OnEraseBackground"]
8007
8008 def CreateImageContainer(self):
8009 """Create the image container (LabelContainer) class for FlatImageBook."""
8010 return labelbook.ImageContainerBase(
8011 self, wx.ID_ANY, agw_style=self.GetAGWWindowStyleFlag()
8012 )
8013
8014
8015 class SimpleTerminal(InvincibleFrame):
8016 """A simple terminal-like window."""
8017
8018 def __init__(
8019 self,
8020 parent=None,
8021 id=-1, # noqa: A002
8022 title=APPNAME,
8023 handler=None,
8024 keyhandler=None,
8025 start_timer=True,
8026 pos=wx.DefaultPosition,
8027 size=wx.DefaultSize,
8028 consolestyle=wx.TE_CHARWRAP
8029 | wx.TE_MULTILINE
8030 | wx.TE_READONLY
8031 | wx.VSCROLL
8032 | wx.NO_BORDER,
8033 show=True,
8034 name="simpleterminal",
8035 ):
8036 if pos == wx.DefaultPosition:
8037 pos = getcfg("position.progress.x"), getcfg("position.progress.y")
8038 if size == wx.DefaultSize:
8039 size = getcfg("size.progress.w"), getcfg("size.progress.h")
8040 InvincibleFrame.__init__(
8041 self, parent, id, title, pos=pos, style=wx.DEFAULT_FRAME_STYLE, name=name
8042 )
8043
8044 self.Bind(wx.EVT_CLOSE, self.OnClose, self)
8045 self.Bind(wx.EVT_MOVE, self.OnMove, self)
8046 self.timer = BetterTimer(self)
8047 if handler:
8048 self.Bind(EVT_BETTER_TIMER, handler, self.timer)
8049
8050 self.panel = wx.Panel(self, -1)
8051 self.sizer = wx.BoxSizer(wx.VERTICAL)
8052 self.panel.SetSizer(self.sizer)
8053 self.console = wx.TextCtrl(self.panel, -1, "", style=consolestyle)
8054 self.console.SetBackgroundColour("#272727")
8055 self.console.SetForegroundColour("#808080")
8056 kwarg = "faceName" if "phoenix" in wx.PlatformInfo else "face"
8057 if sys.platform == "win32":
8058 font = wx.Font(
8059 9,
8060 wx.FONTFAMILY_TELETYPE,
8061 wx.FONTSTYLE_NORMAL,
8062 wx.FONTWEIGHT_NORMAL,
8063 **{kwarg: "Consolas"},
8064 )
8065 elif sys.platform == "darwin":
8066 font = wx.Font(
8067 11,
8068 wx.FONTFAMILY_TELETYPE,
8069 wx.FONTSTYLE_NORMAL,
8070 wx.FONTWEIGHT_NORMAL,
8071 **{kwarg: "Monaco"},
8072 )
8073 else:
8074 font = wx.Font(
8075 11, wx.FONTFAMILY_TELETYPE, wx.FONTSTYLE_NORMAL, wx.FONTWEIGHT_NORMAL
8076 )
8077 self.console.SetFont(font)
8078 self.sizer.Add(self.console, 1, flag=wx.ALL | wx.EXPAND, border=0)
8079
8080 if sys.platform == "win32":
8081 # Mac: TextCtrls don't receive EVT_KEY_DOWN
8082 self.console.Bind(
8083 wx.EVT_KEY_DOWN, keyhandler or self.key_handler, self.console
8084 )
8085 else:
8086 # Windows: EVT_CHAR_HOOK only receives "special" keys e.g. ESC, Tab
8087 self.Bind(wx.EVT_CHAR_HOOK, keyhandler or self.key_handler)
8088
8089 # set size
8090 text_extent = self.console.GetTextExtent(" ")
8091 vscroll_w = wx.SystemSettings_GetMetric(wx.SYS_VSCROLL_X)
8092 w, h = (text_extent[0] * 80 + vscroll_w + 4, text_extent[1] * 24)
8093 self.console.SetMinSize((w, h))
8094 w, h = max(size[0], w), max(size[1], h)
8095 self.console.SetSize((w, h))
8096 self.sizer.SetSizeHints(self)
8097 self.sizer.Layout()
8098
8099 # set position
8100 placed = False
8101 if parent:
8102 if parent.IsShownOnScreen():
8103 self.Center()
8104 placed = True
8105 else:
8106 x = pos[0] or parent.GetScreenPosition()[0]
8107 y = pos[1] or parent.GetScreenPosition()[1]
8108 else:
8109 x, y = pos
8110 if not placed:
8111 self.SetSaneGeometry(x, y, w, h)
8112
8113 self.lastmsg = ""
8114 self.keepGoing = True
8115
8116 self.Bind(wx.EVT_WINDOW_DESTROY, self.OnDestroy, self)
8117
8118 if start_timer:
8119 self.start_timer()
8120
8121 if show:
8122 self.Show()
8123 self.console.SetFocus()
8124
8125 def EndModal(self, returncode=wx.ID_OK):
8126 """End the modal terminal window.
8127
8128 Args:
8129 returncode (int): The return code to return when the modal ends.
8130 """
8131 return returncode
8132
8133 def MakeModal(self, modal=False):
8134 """Make the terminal modal.
8135
8136 Args:
8137 modal (bool): Whether to make the terminal modal or not.
8138 """
8139
8140 def OnClose(self, event):
8141 """Handle the close event of the terminal window.
8142
8143 Args:
8144 event (wx.CloseEvent): The event that triggered this method.
8145 """
8146 if not self.timer.IsRunning():
8147 self.Destroy()
8148 else:
8149 self.keepGoing = False
8150
8151 def OnDestroy(self, event):
8152 """Handle the destruction of the terminal window.
8153
8154 Args:
8155 event (wx.WindowDestroyEvent): The event that triggered this method.
8156 """
8157 self.stop_timer()
8158 del self.timer
8159 return 0
8160
8161 def OnMove(self, event):
8162 """Handle the move event to save the position of the console.
8163
8164 Args:
8165 event (wx.MoveEvent): The move event that triggered this method.
8166 """
8167 if (
8168 self.IsShownOnScreen()
8169 and not self.IsIconized()
8170 and (not self.GetParent() or not self.GetParent().IsShownOnScreen())
8171 ):
8172 prev_x = getcfg("position.progress.x")
8173 prev_y = getcfg("position.progress.y")
8174 x, y = self.GetScreenPosition()
8175 if x != prev_x or y != prev_y:
8176 setcfg("position.progress.x", x)
8177 setcfg("position.progress.y", y)
8178
8179 def Pulse(self, msg=None):
8180 """Pulse the console output with a message.
8181
8182 Args:
8183 msg (str): Message to display in the console.
8184
8185 Returns:
8186 tuple[bool, bool]: A tuple containing a boolean indicating whether
8187 to keep going and a boolean indicating whether to skip the next
8188 update.
8189 """
8190 if msg is None:
8191 msg = ""
8192 self.lastmsg = msg
8193 return self.keepGoing, False
8194
8195 def Resume(self):
8196 """Resume the console output."""
8197 self.keepGoing = True
8198
8199 def UpdateProgress(self, value, msg=""):
8200 """Update the console with a progress value and message.
8201
8202 Args:
8203 value (float): Progress value to set.
8204 msg (str): Message to display in the console.
8205 """
8206 return self.Pulse(msg)
8207
8208 def UpdatePulse(self, msg=""):
8209 """Update the console with a pulse message.
8210
8211 Args:
8212 msg (str): Message to display in the console.
8213 """
8214 return self.Pulse(msg)
8215
8216 def add_text(self, txt):
8217 """Add text to the console.
8218
8219 Args:
8220 txt (str): Text to add to the console.
8221 """
8222 pos = self.console.GetLastPosition()
8223 if txt.startswith("\r"):
8224 txt = txt.lstrip("\r")
8225 numlines = self.console.GetNumberOfLines()
8226 start = pos - self.console.GetLineLength(numlines - 1)
8227 self.console.Replace(start, pos, txt)
8228 else:
8229 self.console.AppendText(txt)
8230
8231 def flush(self):
8232 """Flush the console output.
8233
8234 This method is a no-op in this simulated console.
8235 """
8236
8237 def isatty(self):
8238 """Check if the console is a TTY.
8239
8240 Returns:
8241 bool: Always returns True, as this is a simulated console.
8242 """
8243 return True
8244
8245 def key_handler(self, event):
8246 """Handle key events.
8247
8248 Args:
8249 event (wx.KeyEvent): Key event that triggered this method.
8250 """
8251
8252 def start_timer(self, ms=50):
8253 """Start the timer with a specified interval.
8254
8255 Args:
8256 ms (int): Interval in milliseconds to trigger the timer.
8257 """
8258 self.timer.Start(ms)
8259
8260 def stop_timer(self):
8261 """Stop the timer."""
8262 self.timer.Stop()
8263
8264 def write(self, txt):
8265 """Write text to the console.
8266
8267 Args:
8268 txt (str): Text to write to the console.
8269 """
8270 wx.CallAfter(self.add_text, txt)
8271
8272
8273 class TabButton(PlateButton):
8274 """A button that looks like a tab."""
8275
8276 def __init__(self, *args, **kwargs):
8277 from DisplayCAL.config import get_default_dpi, getcfg
8278
8279 self.dpiscale = max(getcfg("app.dpi") / get_default_dpi(), 1.0)
8280 PlateButton.__init__(self, *args, **kwargs)
8281 self.Unbind(wx.EVT_PAINT)
8282 self.Bind(wx.EVT_PAINT, self.OnPaint)
8283
8284 def DoGetBestSize(self):
8285 """Calculate the best size of the button.
8286
8287 Returns:
8288 :class:`Size`: Best size of the button, which is based on the label
8289 and the bitmap if one has been set.
8290 """
8291 width = 0
8292 height = 6 * self.dpiscale
8293 if self.Label:
8294 # NOTE: Should measure with a GraphicsContext to get right
8295 # size, but due to random segfaults on linux special
8296 # handling is done in the drawing instead...
8297 lsize = self.GetFullTextExtent(self.Label)
8298 width += lsize[0]
8299 height += lsize[1]
8300
8301 if self._bmp["enable"] is not None:
8302 bsize = self._bmp["enable"].Size
8303 width += bsize[0] + 10 * self.dpiscale
8304 if height <= bsize[1]:
8305 height = bsize[1] + 6 * self.dpiscale
8306 else:
8307 height += 3 * self.dpiscale
8308 else:
8309 width += 10 * self.dpiscale
8310
8311 if self._menu is not None or self._style & platebtn.PB_STYLE_DROPARROW:
8312 width += 12 * self.dpiscale
8313
8314 height += 16 * self.dpiscale # Tab hilite
8315
8316 best = wx.Size(int(width), int(height))
8317 self.CacheBestSize(best)
8318 return best
8319
8320 def OnFocus(self, evt):
8321 """Set the visual focus state if need be."""
8322 if self._pressed:
8323 # Skip focus over to next control if it came from another control
8324 if isinstance(evt, wx.FocusEvent) and isinstance(
8325 evt.GetWindow(), wx.Control
8326 ):
8327 self.Navigate(int(not wx.GetKeyState(wx.WXK_SHIFT))) or evt.Skip()
8328 elif self._state["cur"] == platebtn.PLATE_NORMAL:
8329 self._SetState(platebtn.PLATE_HIGHLIGHT)
8330
8331 def OnKillFocus(self, evt):
8332 """Restore normal state on focus loss unless pressed."""
8333 if self._pressed:
8334 self._SetState(platebtn.PLATE_PRESSED)
8335 else:
8336 self._SetState(platebtn.PLATE_NORMAL)
8337
8338 def OnLeftDown(self, evt):
8339 """Show popup menu if click is on menu area."""
8340 pos = evt.GetPosition()
8341 size = self.GetSize()
8342 if pos[0] >= size[0] - 16:
8343 if self._menu is not None:
8344 self.ShowMenu()
8345 elif self._style & platebtn.PB_STYLE_DROPARROW:
8346 event = platebtn.PlateBtnDropArrowPressed()
8347 event.SetEventObject(self)
8348 self.EventHandler.ProcessEvent(event)
8349
8350 if not self._pressed:
8351 self.SetFocus()
8352
8353 def OnLeftUp(self, evt):
8354 """Post a button event.
8355
8356 Args:
8357 evt (wx.MouseEvent): Mouse event that triggered this method.
8358 """
8359 self._SetState(platebtn.PLATE_PRESSED)
8360 PlateButton.OnLeftUp(self, evt)
8361
8362 def OnKeyUp(self, evt):
8363 """Handle Return key press when focused.
8364
8365 Args:
8366 evt (wx.KeyEvent): wx.EVT_KEY_UP.
8367 """
8368 if evt.GetKeyCode() == wx.WXK_SPACE:
8369 self._SetState(platebtn.PLATE_PRESSED)
8370 self._PostEvent()
8371 else:
8372 evt.Skip()
8373
8374 def OnPaint(self, evt):
8375 """Draw the button.
8376
8377 Args:
8378 evt (wx.PaintEvent): wx.EVT_PAINT.
8379 """
8380 self.__DrawButton()
8381
8382 def __DrawBitmap(self, gc):
8383 """Draw the bitmap if one has been set.
8384
8385 Args:
8386 gc (GCDC): :class:`GCDC` to draw with
8387
8388 Returns:
8389 int: x cordinate to draw text at
8390 """
8391 bmp = self._bmp["enable"] if self.IsEnabled() else self._bmp["disable"]
8392 xpos = 0
8393 if bmp is not None and bmp.IsOk():
8394 bw, bh = bmp.GetSize()
8395 ypos = (self.GetSize()[1] - bh) // 2
8396 ypos -= 8 # Tab hilite
8397 gc.DrawBitmap(bmp, xpos, ypos, bmp.GetMask() is not None)
8398 return bw + xpos
8399 return xpos
8400
8401 def __DrawHighlight(self, gc, width, height):
8402 """Draw the main highlight/pressed state.
8403
8404 Args:
8405 gc (GCDC): :class:`GCDC` to draw with.
8406 width (int): Width of highlight.
8407 height (int): Height of highlight.
8408
8409 Returns:
8410 bool: True if highlight was drawn, False otherwise.
8411 """
8412 if (
8413 (self._state["cur"] == platebtn.PLATE_HIGHLIGHT or self.HasFocus())
8414 and not self._pressed
8415 and not get_dialogs(True)
8416 ):
8417 if sys.platform == "darwin":
8418 # Use Sierra-like color scheme
8419 color = wx.Colour(*gamma_encode(0, 105, 217))
8420 else:
8421 color = wx.SystemSettings.GetColour(wx.SYS_COLOUR_HIGHLIGHT)
8422 elif self._pressed:
8423 color = wx.SystemSettings.GetColour(wx.SYS_COLOUR_3DFACE)
8424 else:
8425 return False
8426
8427 gc.SetPen(wx.TRANSPARENT_PEN)
8428
8429 if self._style & platebtn.PB_STYLE_GRADIENT:
8430 gc.SetBrush(wx.TRANSPARENT_BRUSH)
8431 rgc = gc.GetGraphicsContext()
8432 brush = rgc.CreateLinearGradientBrush(
8433 0, 1, 0, height, color, platebtn.AdjustAlpha(color, 55)
8434 )
8435 rgc.SetBrush(brush)
8436 else:
8437 gc.SetBrush(wx.Brush(color))
8438
8439 # rad = 0 if self._style & platebtn.PB_STYLE_SQUARE else (height - 3) / 2
8440 # gc.DrawRoundedRectangle(1, 1, width - 2, height - 2, rad)
8441 gc.DrawRectangle(
8442 0, int(height + 10 * self.dpiscale), int(width), int(8 * self.dpiscale)
8443 )
8444 return True
8445
8446 def __DrawButton(self):
8447 """Draw the button."""
8448 # TODO using a buffered paintdc on windows with the nobg style
8449 # causes lots of weird drawing. So currently the use of a
8450 # buffered dc is dissabled for this style.
8451 if platebtn.PB_STYLE_NOBG & self._style:
8452 dc = wx.PaintDC(self)
8453 else:
8454 dc = wx.AutoBufferedPaintDCFactory(self)
8455 dc.SetBackground(wx.Brush(self.Parent.BackgroundColour))
8456 dc.Clear()
8457
8458 gc = wx.GCDC(dc)
8459
8460 # Setup
8461 gc.SetFont(adjust_font_size_for_gcdc(self.GetFont()))
8462 gc.SetBackgroundMode(wx.BRUSHSTYLE_TRANSPARENT)
8463
8464 # Calc Object Positions
8465 width, height = self.GetSize()
8466 height -= 16 # Tab hilite
8467 # Note: Using self.GetTextExtent instead of gc.GetTextExtent seems
8468 # to fix sporadic segfaults with wxPython Phoenix up to 4.0.0a2
8469 # under Windows (fixed in 4.0.0a3), but self.GetTextExtent is NOT
8470 # an equivalent replacement for gc.GetTextExtent.
8471 tw, th = gc.GetTextExtent(self.Label)
8472 txt_y = max((height - th) // 2, 1)
8473 height += 16
8474 height -= 16 * self.dpiscale # Tab hilite
8475
8476 # The background needs some help to look transparent on
8477 # on Gtk and Windows
8478 if wx.Platform in ["__WXGTK__", "__WXMSW__"]:
8479 gc.SetBrush(self.GetBackgroundBrush(gc))
8480 gc.SetPen(wx.TRANSPARENT_PEN)
8481 gc.DrawRectangle(0, 0, int(width), int(height))
8482
8483 gc.SetBrush(wx.TRANSPARENT_BRUSH)
8484
8485 if (
8486 self._state["cur"] == platebtn.PLATE_HIGHLIGHT
8487 or self._pressed
8488 or self.HasFocus()
8489 ) and self.IsEnabled():
8490 hl = self.__DrawHighlight(gc, int(width), int(height))
8491 else:
8492 hl = False
8493
8494 if hl:
8495 txt_c = self._color["htxt"]
8496 elif self.IsEnabled():
8497 txt_c = self.GetForegroundColour()
8498 else:
8499 txt_c = wx.SystemSettings.GetColour(wx.SYS_COLOUR_GRAYTEXT)
8500
8501 gc.SetTextForeground(txt_c)
8502
8503 # Draw bitmap and text
8504 txt_x = self.__DrawBitmap(gc)
8505 t_x = max(
8506 (width - tw - (txt_x + 8 * self.dpiscale)) // 2, txt_x + 8 * self.dpiscale
8507 )
8508 gc.DrawText(self.Label, int(t_x), int(txt_y))
8509 # self.__DrawDropArrow(gc, width - 10, (height // 2) - 2)
8510
8511
8512 class TaskBarNotification(wx.Frame):
8513 """A popup window in a visual style similar to Win10 'toast' notifications.
8514
8515 It will be shown next to the task bar tray, which makes it a possible
8516 replacement for 'balloon'-style notifications.
8517 The viewing/hiding animation is implemented as a fade effect.
8518
8519 """
8520
8521 def __init__(
8522 self,
8523 icon=None,
8524 title="Notification",
8525 text="",
8526 parent=None,
8527 pos=wx.DefaultPosition,
8528 timeout=-1,
8529 ):
8530 wx.Frame.__init__(
8531 self,
8532 parent,
8533 -1,
8534 style=wx.FRAME_NO_TASKBAR | wx.NO_BORDER | wx.STAY_ON_TOP,
8535 name="TaskBarNotification",
8536 )
8537 self.SetTransparent(0)
8538 border = wx.Panel(self)
8539 if sys.platform == "win32" and sys.getwindowsversion() >= (6,):
8540 border.SetDoubleBuffered(True)
8541 border.BackgroundColour = "#484848"
8542 border.Sizer = wx.BoxSizer(wx.HORIZONTAL)
8543 panel = wx.Panel(border)
8544 if sys.platform == "win32" and sys.getwindowsversion() >= (6,):
8545 panel.SetDoubleBuffered(True)
8546 border.Sizer.Add(panel, flag=wx.ALL, border=1)
8547 panel.Bind(wx.EVT_LEFT_DOWN, lambda event: self.fade("out"))
8548 panel.BackgroundColour = "#1F1F1F"
8549 panel.ForegroundColour = "#A5A5A5"
8550 panel.Sizer = wx.BoxSizer(wx.HORIZONTAL)
8551 if icon:
8552 icon = wx.StaticBitmap(panel, -1, icon)
8553 icon.Bind(wx.EVT_LEFT_DOWN, lambda event: self.fade("out"))
8554 panel.Sizer.Add(icon, flag=wx.TOP | wx.BOTTOM | wx.LEFT, border=12)
8555 sizer = wx.BoxSizer(wx.VERTICAL)
8556 panel.Sizer.Add(sizer, flag=wx.ALL, border=12)
8557 title = wx.StaticText(panel, -1, title)
8558 title.SetMaxFontSize(11)
8559 title.Bind(wx.EVT_LEFT_DOWN, lambda event: self.fade("out"))
8560 title.ForegroundColour = wx.WHITE
8561 font = title.Font
8562 font.Weight = wx.FONTWEIGHT_BOLD
8563 title.Font = font
8564 sizer.Add(title)
8565 msg = wx.StaticText(panel, -1, text)
8566 msg.SetMaxFontSize(11)
8567 msg.Bind(wx.EVT_LEFT_DOWN, lambda event: self.fade("out"))
8568 sizer.Add(msg)
8569 close = wx.BitmapButton(
8570 panel, -1, config.get_bitmap("theme/x-2px-12x12-999"), style=wx.NO_BORDER
8571 )
8572 close.BackgroundColour = panel.BackgroundColour
8573 close.Bind(wx.EVT_BUTTON, lambda event: self.fade("out"))
8574 set_bitmap_labels(close, focus=True)
8575 panel.Sizer.Add(close, flag=wx.TOP | wx.RIGHT | wx.BOTTOM, border=12)
8576 border.Sizer.SetSizeHints(self)
8577 border.Sizer.Layout()
8578 opos = pos
8579 display = self.GetDisplay()
8580 client_area = parent.ClientRect if parent else display.ClientArea
8581 geometry = display.Geometry
8582 # Determine tray position so we can show our popup
8583 # next to it
8584 if client_area[0] != geometry[0]:
8585 # Task bar is on the left, tray is in bottom left
8586 pos = [geometry[0], geometry[1] + geometry[3]]
8587 elif client_area[0] == geometry[0] and client_area[2] < geometry[2]:
8588 # Task bar is on the right, tray is in bottom right
8589 pos = [geometry[0] + geometry[2], geometry[1] + geometry[3]]
8590 elif client_area[1] != geometry[1]:
8591 # Task bar is at the top, tray is in top right
8592 pos = [geometry[0] + geometry[2], geometry[1]]
8593 elif client_area[1] == geometry[1] and client_area[3] < geometry[3]:
8594 # Task bar is at the bottom, tray is in bottom right
8595 pos = [geometry[0] + geometry[2], geometry[1] + geometry[3]]
8596 else:
8597 # Task bar is probably set to auto-hide, so we cannot use client
8598 # area to determine its position. Use mouse position instead.
8599 mousepos = wx.GetMousePosition()
8600 if mousepos[0] < (geometry[0] + geometry[2]) / 2.0:
8601 # Assume task bar is on the left, tray is in bottom left
8602 pos = [geometry[0], geometry[1] + geometry[3]]
8603 elif (
8604 mousepos[0] > (geometry[0] + geometry[2]) / 2.0
8605 and mousepos[1] < (geometry[1] + geometry[3]) / 2.0
8606 ):
8607 # Assume task bar is at the top, tray is in top right
8608 pos = [geometry[0] + geometry[2], geometry[1]]
8609 else:
8610 # Assume task tray is in bottom right
8611 pos = [geometry[0] + geometry[2], geometry[1] + geometry[3]]
8612 if pos[0] <= client_area[0]:
8613 pos[0] = client_area[0] + 12
8614 if pos[1] <= client_area[1]:
8615 pos[1] = client_area[1] + 12
8616 if pos[0] + self.Size[0] >= client_area[0] + client_area[2]:
8617 pos[0] = client_area[0] + client_area[2] - self.Size[0] - 12
8618 if pos[1] + self.Size[1] >= client_area[1] + client_area[3]:
8619 pos[1] = client_area[1] + client_area[3] - self.Size[1] - 12
8620 for i in (0, 1):
8621 if opos[i] != -1:
8622 pos[i] = opos[i]
8623 self.SetPosition(pos)
8624 if timeout == -1:
8625 timeout = 6250
8626 if timeout:
8627 self._fadeout_timer = wx.CallLater(
8628 timeout, lambda: self and self.fade("out")
8629 )
8630 if hasattr(panel, "SetFocusIgnoringChildren"):
8631 panel.SetFocusIgnoringChildren()
8632 self.Show()
8633 self.fade()
8634
8635 def fade(self, direction=None, i=1):
8636 """Fade in or out the window.
8637
8638 Args:
8639 direction (str): "in" to fade in, "out" to fade out.
8640 i (int): Current fade step, defaults to 1.
8641 """
8642 if direction is None:
8643 direction = "in"
8644
8645 if getattr(self, "_fade_timer", None) and self._fade_timer.IsRunning():
8646 self._fade_timer.Stop()
8647 i = self._fade_timer_i
8648 if direction != "in":
8649 if hasattr(self, "_fadeout_timer") and self._fadeout_timer.IsRunning():
8650 self._fadeout_timer.Stop()
8651 t = 10 - i
8652 else:
8653 t = i
8654 if not self:
8655 return
8656 self.SetTransparent(int(t * 25.5))
8657 if i < 10:
8658 self._fade_timer_i = i
8659 self._fade_timer = wx.CallLater(1, self.fade, direction, i + 1)
8660 elif direction != "in" and self:
8661 self.Destroy()
8662
8663
8664 class TooltipWindow(InvincibleFrame):
8665 """A tooltip-style window."""
8666
8667 def __init__(
8668 self,
8669 parent=None,
8670 id=-1, # noqa: A002
8671 title=APPNAME,
8672 msg="",
8673 cols=1,
8674 bitmap=None,
8675 pos=(-1, -1),
8676 size=(400, -1),
8677 style=(wx.DEFAULT_FRAME_STYLE | wx.FRAME_TOOL_WINDOW | wx.FRAME_FLOAT_ON_PARENT)
8678 & ~(wx.RESIZE_BORDER | wx.MAXIMIZE_BOX),
8679 wrap=70,
8680 use_header=True,
8681 show=True,
8682 scrolled=False,
8683 ):
8684 scale = getcfg("app.dpi") / get_default_dpi()
8685 if scale > 1 and size == (400, -1):
8686 size = int(size[0] * scale), size[1]
8687 InvincibleFrame.__init__(self, parent, id, title, pos, size, style)
8688 self.SetPosition(pos) # yes, this is needed
8689 set_icons(self)
8690
8691 margin = 12
8692
8693 if scrolled:
8694 self.panel = wx.ScrolledWindow(self, style=wx.VSCROLL)
8695 self.panel.SetScrollRate(2, 2)
8696 else:
8697 self.panel = wx.Panel(self)
8698 self.panel.BackgroundColour = wx.SystemSettings.GetColour(wx.SYS_COLOUR_WINDOW)
8699 self.sizer0 = wx.BoxSizer(wx.VERTICAL)
8700 self.panel.SetSizer(self.sizer0)
8701 self.sizer1 = wx.BoxSizer(wx.HORIZONTAL)
8702 self.sizer0.Add(self.sizer1, flag=wx.LEFT | wx.ALL, border=margin)
8703
8704 if bitmap:
8705 self.bitmap = wx.StaticBitmap(self.panel, -1, bitmap)
8706 self.sizer1.Add(self.bitmap)
8707
8708 self.sizer2 = wx.BoxSizer(wx.VERTICAL)
8709 self.sizer1.Add(self.sizer2)
8710
8711 if "<" not in msg and wrap:
8712 msg = util_str.wrap(msg, wrap)
8713 msg = msg.splitlines()
8714 for i, line in enumerate(msg):
8715 if not line and use_header:
8716 # Use as header
8717 header = wx.StaticText(self.panel, -1, "\n".join(msg[: i + 1]))
8718 self.sizer2.Add(header, flag=wx.LEFT, border=margin)
8719 msg = msg[i + 1 :]
8720 break
8721 self.sizer3 = wx.BoxSizer(wx.HORIZONTAL)
8722 self.sizer2.Add(self.sizer3, flag=wx.EXPAND)
8723 rowspercol = math.ceil(len(msg) / float(cols))
8724 msgs = []
8725 while msg:
8726 msgs.append(msg[:rowspercol])
8727 msg = msg[rowspercol:]
8728 for msg in msgs:
8729 label = "\n".join(msg)
8730 cls = BetterStaticFancyText if "<" in label else wx.StaticText
8731 # We need to initialize the label with something,
8732 # so initialize it with with "dummy text",
8733 # and it will be replaced later on...
8734 col = cls(self.panel, -1, "dummy text")
8735 if isinstance(col, wx.Panel):
8736 col.BackgroundColour = self.panel.BackgroundColour
8737 if "<" in label and wrap:
8738 col.maxlen = wrap
8739 col.SetMaxFontSize()
8740 maxlinewidth = 0
8741 tabcount = 0
8742 for line in msg:
8743 maxlinewidth = max(col.GetTextExtent(line)[0], maxlinewidth)
8744 tabcount = max(tabcount, line.count("\t"))
8745 # GetTextExtent doesn't always figure out correct width for
8746 # tab char, extra spacing needed
8747 tabwidth = tabcount * col.GetTextExtent("\t")[0]
8748 col.Label = label
8749 if "<" not in label:
8750 col.MinSize = maxlinewidth + tabwidth + margin * 2, -1
8751 self.sizer3.Add(col, flag=wx.LEFT, border=margin)
8752
8753 self.sizer0.SetSizeHints(self)
8754 self.sizer0.Layout()
8755 if not pos or pos == (-1, -1):
8756 self.Center(wx.BOTH)
8757 elif pos[0] == -1:
8758 self.Center(wx.HORIZONTAL)
8759 elif pos[1] == -1:
8760 self.Center(wx.VERTICAL)
8761 if show:
8762 self.Show()
8763 self.Raise()
8764
8765
8766 class TwoWaySplitter(FourWaySplitter):
8767 """A splitter that can be used to split a window into two panes."""
8768
8769 def __init__(self, *args, **kwargs):
8770 FourWaySplitter.__init__(self, *args, **kwargs)
8771 self._minimum_pane_size = 0
8772 self._sashbitmap = get_bitmap("theme/sash")
8773 self._splitsize = (800, 400)
8774 self._expandedsize = (400, 400)
8775 self._handcursor = wx.StockCursor(wx.CURSOR_HAND)
8776 self.Bind(wx.EVT_LEFT_DCLICK, self.OnLeftDClick)
8777 # Redrawing the splitter in FourWaySplitter._RedrawIfHotSensitive
8778 # which happens if the mouse enters or leaves the splitter causes blank
8779 # windows managed by the splitter under wxGTK if using GTK3.
8780 # We are using a custom splitter graphic without 'hot' state, so we can
8781 # circumvent this.
8782 self.Unbind(wx.EVT_ENTER_WINDOW)
8783
8784 def _GetSashSize(self):
8785 """Used internally."""
8786 if self.HasFlag(wx.SP_NOSASH):
8787 return 0
8788
8789 return self._sashbitmap.GetSize()[0]
8790
8791 # Recompute layout
8792 def _SizeWindows(self):
8793 """Recalculate the layout based on split positions and split fractions.
8794
8795 :see: SetHSplit and SetVSplit for more information about split fractions.
8796 """
8797 win0 = self.GetTopLeft()
8798 win1 = self.GetTopRight()
8799
8800 width, height = self.GetSize()
8801 bar_size = self._GetSashSize()
8802 border = self._GetBorderSize()
8803
8804 if self._expanded < 0:
8805 totw = int(width - bar_size - 2 * border)
8806 self._splitx = int(
8807 max((self._fhor * totw) / 10000, self._minimum_pane_size)
8808 )
8809 self._splity = int(height)
8810 rightw = max(totw - self._splitx, 0)
8811 if win0:
8812 win0.SetPosition((0, 0))
8813 win0.SetSize((self._splitx, self._splity))
8814 win0.Show()
8815 if win1:
8816 win1.SetPosition((self._splitx + bar_size, 0))
8817 win1.SetSize((rightw, self._splity))
8818 win1.Show()
8819
8820 elif self._expanded < len(self._windows):
8821 for ii, win in enumerate(self._windows):
8822 if ii == self._expanded:
8823 win.SetSize(
8824 (
8825 int(width - bar_size - 2 * border),
8826 int(height - 2 * border),
8827 )
8828 )
8829 win.Show()
8830 else:
8831 win.Hide()
8832
8833 # Draw the horizontal split
8834 def DrawSplitter(self, dc):
8835 """Actually draws the sashes.
8836
8837 Args:
8838 dc (wx.DC): A `wx.DC` instance.
8839 """
8840 backColour = wx.Colour(*[int(v * 0.85) for v in self.BackgroundColour[:3]])
8841 dc.SetBrush(wx.Brush(backColour, wx.BRUSHSTYLE_SOLID))
8842 dc.SetPen(wx.Pen(backColour))
8843 dc.Clear()
8844
8845 width, height = self.GetSize()
8846
8847 if self._expanded > -1:
8848 splitx = width - self._GetSashSize() - 2 * self._GetBorderSize()
8849 else:
8850 splitx = self._splitx
8851
8852 if self._expanded < 0:
8853 if splitx <= self._minimum_pane_size:
8854 self._sashbitmap = get_bitmap("theme/sash-right")
8855 else:
8856 self._sashbitmap = get_bitmap("theme/sash")
8857 else:
8858 self._sashbitmap = get_bitmap("theme/sash-left")
8859 sashwidth, sashheight = self._sashbitmap.GetSize()
8860
8861 dc.DrawRectangle(int(splitx), 0, int(sashwidth), int(height))
8862 dc.DrawBitmap(
8863 self._sashbitmap, int(splitx), int(height / 2 - sashheight / 2), True
8864 )
8865
8866 def GetExpandedSize(self):
8867 """Get the size of the expanded pane.
8868
8869 Returns:
8870 tuple: A tuple containing the width and height of the expanded pane.
8871 """
8872 return self._expandedsize
8873
8874 # Determine split mode
8875 def GetMode(self, pt):
8876 """Determine the split mode for FourWaySplitter.
8877
8878 Args:
8879 pt (wx.Point): The point at which the mouse has been clicked, an
8880 instance of `wx.Point`.
8881
8882 Returns:
8883 int: One of the following 3 split modes:
8884
8885 ================= ==============================
8886 Split Mode Description
8887 ================= ==============================
8888 ``wx.HORIZONTAL`` the user has clicked on the horizontal sash
8889 ``wx.VERTICAL`` The user has clicked on the vertical sash
8890 ``wx.BOTH`` The user has clicked at the intersection between the 2 sashes
8891 ================= ==============================
8892
8893 """
8894 barSize = self._GetSashSize()
8895 flag = wx.BOTH
8896
8897 width, height = self.GetSize()
8898 if self._expanded > -1:
8899 splitx = width - self._GetSashSize() - 2 * self._GetBorderSize()
8900 else:
8901 splitx = self._splitx
8902
8903 if pt.x < splitx - _TOLERANCE:
8904 flag &= ~wx.VERTICAL
8905
8906 if pt.y < self._splity - _TOLERANCE:
8907 flag &= ~wx.HORIZONTAL
8908
8909 if pt.x >= splitx + barSize + _TOLERANCE:
8910 flag &= ~wx.VERTICAL
8911
8912 if pt.y >= self._splity + barSize + _TOLERANCE:
8913 flag &= ~wx.HORIZONTAL
8914
8915 return flag
8916
8917 def GetSplitSize(self):
8918 """Get the size of the split area.
8919
8920 Returns:
8921 tuple: A tuple containing the width and height of the split area."""
8922 return self._splitsize
8923
8924 def OnLeaveWindow(self, event):
8925 """Handle the ``wx.EVT_LEAVE_WINDOW`` event.
8926
8927 Args:
8928 event: A `wx.MouseEvent` event to be processed.
8929 """
8930 self.SetCursor(wx.STANDARD_CURSOR)
8931
8932 def OnLeftDClick(self, event):
8933 """Handle the ``wx.EVT_LEFT_DCLICK`` event.
8934
8935 Args:
8936 event: A `wx.MouseEvent` event to be processed.
8937 """
8938 if not self.IsEnabled():
8939 return
8940
8941 pt = event.GetPosition()
8942
8943 if not self.GetMode(pt):
8944 return
8945
8946 barSize = self._GetSashSize()
8947
8948 winborder, titlebar = get_platform_window_decoration_size()
8949
8950 self.Freeze()
8951 self.SetExpanded(-1 if self._expanded > -1 else 0)
8952 if self._expanded < 0:
8953 if self.GetExpandedSize()[0] < self.GetSplitSize()[0]:
8954 self._fhor = math.ceil(
8955 (self.GetExpandedSize()[0] - barSize - winborder * 2)
8956 / float(self.GetSplitSize()[0] - barSize - winborder * 2)
8957 * 10000
8958 )
8959 else:
8960 self._fhor = math.ceil(
8961 self._minimum_pane_size
8962 / float(self.GetSplitSize()[0] - barSize - winborder * 2)
8963 * 10000
8964 )
8965 self.Thaw()
8966
8967 # Button being released
8968 def OnLeftUp(self, event):
8969 """Handle the ``wx.EVT_LEFT_UP`` event.
8970
8971 Args:
8972 event (wx.MouseEvent): A `wx.MouseEvent` event to be processed.
8973 """
8974 if not self.IsEnabled():
8975 return
8976
8977 if self.HasCapture():
8978 self.ReleaseMouse()
8979
8980 flgs = self._flags
8981
8982 self._flags &= ~FLAG_CHANGED
8983 self._flags &= ~FLAG_PRESSED
8984
8985 if flgs & FLAG_PRESSED:
8986 if not self.GetAGWWindowStyleFlag() & wx.SP_LIVE_UPDATE:
8987 self.DrawTrackSplitter(int(self._splitx), int(self._splity))
8988 self.DrawSplitter(wx.ClientDC(self))
8989 self.AdjustLayout()
8990
8991 if flgs & FLAG_CHANGED:
8992 event = FourWaySplitterEvent(
8993 wx.wxEVT_COMMAND_SPLITTER_SASH_POS_CHANGED, self
8994 )
8995 event.SetSashIdx(self._mode)
8996 event.SetSashPosition(wx.Point(int(self._splitx), int(self._splity)))
8997 self.GetEventHandler().ProcessEvent(event)
8998 else:
8999 self.OnLeftDClick(event)
9000
9001 self._mode = NOWHERE
9002
9003 def OnMotion(self, event):
9004 """Handle the ``wx.EVT_MOTION`` event.
9005
9006 Args:
9007 event (wx.MouseEvent): A `wx.MouseEvent` event to be processed.
9008 """
9009 if self.HasFlag(wx.SP_NOSASH):
9010 return
9011
9012 pt = event.GetPosition()
9013
9014 # Moving split
9015 if self._flags & FLAG_PRESSED:
9016 width, height = self.GetSize()
9017 barSize = self._GetSashSize()
9018 border = self._GetBorderSize()
9019
9020 totw = width - barSize - 2 * border
9021
9022 if pt.x > totw - _TOLERANCE:
9023 self._expanded = 0
9024 self._offx += 1
9025 elif self._expanded > -1 and pt.x > self._minimum_pane_size:
9026 self._fhor = int((pt.x - barSize - 2 * border) / float(totw) * 10000)
9027 self._splitx = (self._fhor * totw) / 10000
9028 self._offx = pt.x - self._splitx + 1
9029 self._expanded = -1
9030
9031 oldsplitx = self._splitx
9032 oldsplity = self._splity
9033
9034 if self._mode == wx.BOTH:
9035 self.MoveSplit(pt.x - self._offx, pt.y - self._offy)
9036
9037 elif self._mode == wx.VERTICAL:
9038 self.MoveSplit(pt.x - self._offx, self._splity)
9039
9040 elif self._mode == wx.HORIZONTAL:
9041 self.MoveSplit(self._splitx, pt.y - self._offy)
9042
9043 # Send a changing event
9044 if not self.DoSendChangingEvent(
9045 wx.Point(int(self._splitx), int(self._splity))
9046 ):
9047 self._splitx = oldsplitx
9048 self._splity = oldsplity
9049 return
9050
9051 if int(oldsplitx) != int(self._splitx) or int(oldsplity) != int(
9052 self._splity
9053 ):
9054 if not self.GetAGWWindowStyleFlag() & wx.SP_LIVE_UPDATE:
9055 self.DrawTrackSplitter(int(oldsplitx), int(oldsplity))
9056 self.DrawTrackSplitter(int(self._splitx), int(self._splity))
9057 else:
9058 self.AdjustLayout()
9059
9060 self._flags |= FLAG_CHANGED
9061
9062 self.Refresh()
9063
9064 # Change cursor based on position
9065 ff = self.GetMode(pt)
9066
9067 if self._expanded > -1 and self._splitx <= self._minimum_pane_size:
9068 self.SetCursor(self._handcursor)
9069
9070 elif ff == wx.BOTH:
9071 self.SetCursor(self._sashCursorSIZING)
9072
9073 elif ff == wx.VERTICAL:
9074 self.SetCursor(self._sashCursorWE)
9075
9076 elif ff == wx.HORIZONTAL:
9077 self.SetCursor(self._sashCursorNS)
9078
9079 else:
9080 self.SetCursor(self._handcursor)
9081
9082 event.Skip()
9083
9084 def SetExpandedSize(self, size):
9085 """Set the size of the expanded pane.
9086
9087 Args:
9088 size (tuple): A tuple containing the width and height of the
9089 expanded pane.
9090 """
9091 self._expandedsize = size
9092
9093 def SetMinimumPaneSize(self, size=0):
9094 """Set the minimum size of the panes.
9095
9096 Args:
9097 size (int): The minimum size of the panes in pixels.
9098 """
9099 self._minimum_pane_size = size
9100
9101 def SetSplitSize(self, size):
9102 """Set the size of the split panes.
9103
9104 Args:
9105 size (tuple): A tuple containing the width and height of the split
9106 panes.
9107 """
9108 self._splitsize = size
9109
9110
9111 def get_gradient_panel(parent, label, x=16):
9112 """Create a gradient panel with a label.
9113
9114 Args:
9115 parent (wx.Window): The parent window.
9116 label (str): The label to display on the panel.
9117 x (int): The x-coordinate for the label position.
9118
9119 Returns:
9120 wx.Panel: The created gradient panel.
9121 """
9122 gradientpanel = BitmapBackgroundPanelText(parent, size=(-1, 31))
9123 gradientpanel.alpha = 0.75
9124 gradientpanel.blend = True
9125 gradientpanel.bordertopcolor = wx.SystemSettings.GetColour(wx.SYS_COLOUR_3DSHADOW)
9126 gradientpanel.drawbordertop = True
9127 gradientpanel.label_x = x
9128 gradientpanel.textalpha = 0.8
9129 bitmap = bitmaps.get("gradient_panel")
9130 if not bitmap:
9131 bitmap = (
9132 get_bitmap("theme/gradient")
9133 .GetSubBitmap((0, 1, 8, 15))
9134 .ConvertToImage()
9135 .Mirror(False)
9136 .ConvertToBitmap()
9137 )
9138 image = bitmap.ConvertToImage()
9139 databuffer = image.GetDataBuffer()
9140 for i, byte in enumerate(databuffer):
9141 if byte > 0:
9142 databuffer[i] = round(ord(byte) * (255.0 / 223.0))
9143 bitmap = image.ConvertToBitmap()
9144 bitmaps["gradient_panel"] = bitmap
9145 gradientpanel.SetBitmap(bitmap)
9146 gradientpanel.SetMaxFontSize(11)
9147 font = gradientpanel.Font
9148 font.SetWeight(wx.FONTWEIGHT_BOLD)
9149 gradientpanel.Font = font
9150 gradientpanel.SetLabel(label)
9151 return gradientpanel
9152
9153
9154 def get_html_colors(allow_alpha=False):
9155 """Get background, text, link and visited link colors based on system colors."""
9156 if SAFE_WX_UI:
9157 return (
9158 wx.Colour(255, 255, 255),
9159 wx.Colour(0, 0, 0),
9160 wx.Colour(44, 93, 205),
9161 wx.Colour(111, 111, 111),
9162 )
9163
9164 bgcolor = wx.SystemSettings.GetColour(wx.SYS_COLOUR_WINDOW)
9165 text = wx.SystemSettings.GetColour(wx.SYS_COLOUR_WINDOWTEXT)
9166 linkcolor = wx.SystemSettings.GetColour(wx.SYS_COLOUR_HOTLIGHT)
9167 if max((linkcolor.Red(), linkcolor.Green(), linkcolor.Blue())) == 0:
9168 if sys.platform == "darwin":
9169 # Use Mavericks-like color scheme
9170 linkcolor = wx.Colour(44, 93, 205)
9171 else:
9172 linkcolor = wx.SystemSettings.GetColour(wx.SYS_COLOUR_HIGHLIGHT)
9173 vlinkcolor = wx.SystemSettings.GetColour(wx.SYS_COLOUR_GRAYTEXT)
9174 if not allow_alpha:
9175 bgcolor = wx.Colour(bgcolor.Red(), bgcolor.Green(), bgcolor.Blue())
9176 text = wx.Colour(text.Red(), text.Green(), text.Blue())
9177 linkcolor = wx.Colour(linkcolor.Red(), linkcolor.Green(), linkcolor.Blue())
9178 vlinkcolor = wx.Colour(vlinkcolor.Red(), vlinkcolor.Green(), vlinkcolor.Blue())
9179 return bgcolor, text, linkcolor, vlinkcolor
9180
9181
9182 def get_widget(win: wx.Window, id_name_label: str) -> None | wx.Window:
9183 """Get a widget based on ID, name, or label.
9184
9185 Args:
9186 win (wx.Window): The parent window.
9187 id_name_label (str): The ID, name, or label of the widget.
9188
9189 Returns:
9190 wx.Window: The widget if found, None otherwise.
9191 """
9192 # hasattr, getattr, setattr silently convert attribute names to byte strings,
9193 # we have to make sure there's no UnicodeEncodeError
9194 if id_name_label == safe_str(str(id_name_label), "ascii") and hasattr(
9195 win, id_name_label
9196 ):
9197 # Attribute name
9198 try:
9199 # Trying to access some attributes of wx widgets may
9200 # raise an exception
9201 child = getattr(win, id_name_label)
9202 except Exception:
9203 return False
9204 if is_scripting_allowed(win, child):
9205 return child
9206 else:
9207 # ID or label
9208 with contextlib.suppress(ValueError):
9209 id_name_label = int(id_name_label)
9210 for child in list(win.GetAllChildren()):
9211 if is_scripting_allowed(win, child) and (
9212 id_name_label in (child.Id, child.Name, child.Label)
9213 ):
9214 return child
9215 return None
9216
9217
9218 def get_toplevel_window(id_name_label):
9219 """Get the top-level window based on ID, name, or label.
9220
9221 Args:
9222 id_name_label (str): The ID, name, or label of the window.
9223
9224 Returns:
9225 wx.Window: The top-level window if found, None otherwise.
9226 """
9227 with contextlib.suppress(ValueError):
9228 id_name_label = int(id_name_label)
9229 for win in reversed(list(wx.GetTopLevelWindows())):
9230 if win and (id_name_label in (win.Id, win.Name, win.Label)) and win.IsShown():
9231 return win
9232 return None
9233
9234
9235 def is_scripting_allowed(win: wx.Window, child: wx.Window) -> bool:
9236 """Check if a child window is allowed for scripting.
9237
9238 Args:
9239 win (wx.Window): The parent window.
9240 child (wx.Window): The child window to check.
9241
9242 Returns:
9243 bool: True if the child window is allowed for scripting, False otherwise.
9244 """
9245 return (
9246 child
9247 and child.TopLevelParent is win
9248 and child.IsShownOnScreen()
9249 and isinstance(
9250 child,
9251 (
9252 CustomCheckBox,
9253 aui.AuiNotebook,
9254 labelbook.FlatBookBase,
9255 wx.Control,
9256 wx.Notebook,
9257 wx.grid.Grid,
9258 ),
9259 )
9260 and not isinstance(child, (SimpleBook, aui.AuiTabCtrl, wx.StaticBitmap))
9261 )
9262
9263
9264 _elementtable = {}
9265
9266
9267 def format_ui_element(child, file_format="plain"):
9268 """Format a UI element for output."""
9269 if child.TopLevelParent:
9270 if not hasattr(child.TopLevelParent, "_win2name"):
9271 child.TopLevelParent._win2name = {}
9272 for name in child.TopLevelParent.__dict__:
9273 attr = child.TopLevelParent.__dict__[name]
9274 if isinstance(attr, wx.Window):
9275 child.TopLevelParent._win2name[attr] = name
9276 name = child.TopLevelParent._win2name.get(child, child.Name)
9277 else:
9278 name = child.Name
9279 items = getattr(child, "Items", [])
9280 value = None
9281 if not items and isinstance(child, wx.ListCtrl):
9282 for row in range(child.GetItemCount()):
9283 item = [
9284 child.GetItem(row, col).GetText()
9285 for col in range(child.GetColumnCount())
9286 ]
9287 items.append(" ".join(item))
9288 row = child.GetFirstSelected()
9289 if row != wx.NOT_FOUND:
9290 value = items[row]
9291 elif isinstance(child, (aui.AuiNotebook, labelbook.FlatBookBase, wx.Notebook)):
9292 for page_idx in range(child.GetPageCount()):
9293 items.append(child.GetPageText(page_idx))
9294 page_idx = child.GetSelection()
9295 if page_idx != wx.NOT_FOUND:
9296 value = child.GetPageText(page_idx)
9297 cols = []
9298 if isinstance(child, wx.grid.Grid):
9299 cols.extend(child.GetColLabelValue(col) for col in range(child.GetNumberCols()))
9300 if file_format != "plain":
9301 uielement = {
9302 "class": child.__class__.__name__,
9303 "name": name,
9304 "enabled": child.IsEnabled(),
9305 "id": child.Id,
9306 }
9307 if child.Label:
9308 uielement["label"] = child.Label
9309 if isinstance(child, (CustomCheckBox, wx.CheckBox, wx.RadioButton)):
9310 uielement["checked"] = child.GetValue()
9311 elif hasattr(child, "GetValue") and not isinstance(child, wx.ListCtrl):
9312 uielement["value"] = child.GetValue()
9313 elif hasattr(child, "GetStringSelection"):
9314 uielement["value"] = child.GetStringSelection()
9315 elif value is not None:
9316 uielement["value"] = value
9317 if items:
9318 uielement["items"] = items
9319 if cols:
9320 uielement["cols"] = cols
9321 uielement["rows"] = child.GetNumberRows()
9322 return uielement
9323 return "{} {} {}{} {}{}{}{}".format(
9324 child.__class__.__name__,
9325 child.Id,
9326 sp.list2cmdline([name]),
9327 (child.Label and " " + demjson.encode(child.Label)),
9328 "enabled" if child.IsEnabled() else "disabled",
9329 (
9330 isinstance(child, (CustomCheckBox, wx.CheckBox, wx.RadioButton))
9331 and child.GetValue()
9332 and " checked"
9333 )
9334 or (
9335 getattr(child, "GetValue", "")
9336 and not isinstance(
9337 child, (CustomCheckBox, wx.CheckBox, wx.RadioButton, wx.ListCtrl)
9338 )
9339 and " value " + demjson.encode(child.GetValue())
9340 )
9341 or (
9342 getattr(child, "GetStringSelection", "")
9343 and " value " + demjson.encode(child.GetStringSelection())
9344 )
9345 or ((value is not None and " value " + demjson.encode(value)) or ""),
9346 (
9347 (
9348 items
9349 and " items " + demjson.encode(items).strip("[]").replace('","', '" "')
9350 )
9351 or ""
9352 ),
9353 (
9354 (
9355 cols
9356 and " rows {} cols {}".format(
9357 child.GetNumberRows(),
9358 demjson.encode(cols).strip("[]").replace('","', '" "'),
9359 )
9360 )
9361 or ""
9362 ),
9363 )
9364
9365
9366 def restore_path_dialog_classes():
9367 """Restore the original wx.DirDialog and wx.FileDialog classes."""
9368 wx.DirDialog = _DirDialog
9369 wx.FileDialog = _FileDialog
9370
9371
9372 def get_appid_from_window_hierarchy(toplevelwindow: wx.Window | wx.Frame) -> str:
9373 """Get the AppID from the window hierarchy.
9374
9375 Args:
9376 toplevelwindow (wx.Window): The top-level window.
9377
9378 Returns:
9379 str: The AppID.
9380 """
9381 if isinstance(toplevelwindow, wx.Frame):
9382 frame = toplevelwindow
9383 else:
9384 frame = get_parent_frame(toplevelwindow)
9385 base_appid = APPNAME.lower()
9386 return {
9387 "lut3dframe": f"{base_appid}-3dlut-maker",
9388 "lut_viewer": f"{base_appid}-curve-viewer",
9389 "profile_info": f"{base_appid}-profile-info",
9390 "scriptingframe": f"{base_appid}-scripting-client",
9391 "synthiccframe": f"{base_appid}-synthprofile",
9392 "tcgen": f"{base_appid}-testchart-editor",
9393 "vrml2x3dframe": f"{base_appid}-vrml-to-x3d-converter",
9394 }.get(frame and frame.Name, base_appid)
9395
9396
9397 def set_icons(toplevelwindow):
9398 """Set icon to that of parent frame."""
9399 appid = get_appid_from_window_hierarchy(toplevelwindow)
9400 toplevelwindow.SetIcons(config.get_icon_bundle([256, 48, 32, 16], appid))
9401
9402
9403 def show_result_dialog(result, parent=None, pos=None, confirm=False, wrap=70):
9404 """Show dialog depending on type of result.
9405
9406 Result should be an exception type. An appropriate visual representation
9407 will be chosen whether result is of exception type 'Info', 'Warning'
9408 or other error.
9409 """
9410 if result.__class__ is Exception and result.args and result.args[0] == "aborted":
9411 # Special case - aborted
9412 msg = lang.getstr("aborted")
9413 else:
9414 msg = str(result)
9415 if not pos:
9416 pos = (-1, -1)
9417 if isinstance(result, Info):
9418 bitmap = get_icon(32, "dialog-information")
9419 elif isinstance(result, (Warning, DownloadError)):
9420 bitmap = get_icon(32, "dialog-warning")
9421 else:
9422 bitmap = get_icon(32, "dialog-error")
9423 if isinstance(result, DownloadError):
9424 confirm = lang.getstr("go_to", result.url)
9425 if confirm:
9426 cls = ConfirmDialog
9427 ok = confirm
9428 else:
9429 cls = InfoDialog
9430 ok = lang.getstr("ok")
9431 nowrap = wrap is None
9432 dlg = cls(
9433 parent,
9434 pos=pos,
9435 msg=msg,
9436 ok=ok,
9437 bitmap=bitmap,
9438 log=not isinstance(result, (UnloggedError, UnloggedInfo, UnloggedWarning)),
9439 nowrap=nowrap,
9440 wrap=wrap,
9441 )
9442 if confirm:
9443 dlg_ok = dlg.ShowModal() == wx.ID_OK
9444 dlg.Destroy()
9445 if dlg_ok and isinstance(result, DownloadError):
9446 launch_file(result.url)
9447 return dlg_ok
9448
9449 return None