"""wxPython-based GUI components and utilities. It includes custom widgets, dialogs, frames, and enhancements to standard wxPython controls, offering extended functionality and improved aesthetics. The module also supports advanced features like custom rendering, event handling, and platform-specific adjustments. """ from __future__ import annotations import contextlib import errno import html import math import os import re import signal import socket import subprocess as sp import sys import tarfile import textwrap import threading import warnings import xml.parsers.expat import zipfile from datetime import datetime from time import gmtime, sleep, strftime, time from typing import ClassVar from DisplayCAL import audio, config, floatspin, util_str from DisplayCAL import demjson_compat as demjson from DisplayCAL import localization as lang from DisplayCAL.config import ( APPBASENAME, CONFIG_HOME, DEFAULTS, LOGDIR, PYNAME, get_bitmap, get_data_path, get_default_dpi, get_icon, get_verified_path, getcfg, hascfg, set_default_app_dpi, setcfg, ) from DisplayCAL.debughelpers import ( DownloadError, Info, UnloggedError, UnloggedInfo, UnloggedWarning, getevtobjname, getevttype, ) from DisplayCAL.icc_profile import ( ICCProfile, ICCProfileInvalidError, ) from DisplayCAL.lib.agw import labelbook, pygauge from DisplayCAL.lib.agw.fourwaysplitter import ( _TOLERANCE, FLAG_CHANGED, FLAG_PRESSED, NOWHERE, FourWaySplitter, FourWaySplitterEvent, ) from DisplayCAL.lib.agw.gradientbutton import CLICK, HOVER, GradientButton from DisplayCAL.meta import NAME as APPNAME from DisplayCAL.network import ScriptingClientSocket, get_network_addr from DisplayCAL.options import DEBUG from DisplayCAL.util_os import launch_file, waccess from DisplayCAL.util_str import box, safe_str from DisplayCAL.util_xml import dict2xml from DisplayCAL.wexpect import split_command_line from DisplayCAL.wx_addons import ( EVT_BETTER_TIMER, BetterTimer, BetterWindowDisabler, CustomEvent, gamma_encode, get_parent_frame, get_platform_window_decoration_size, wx, ) from DisplayCAL.wx_addons import FileDrop as _FileDrop # from wexpect import split_command_line from DisplayCAL.wx_fixes import ( GenBitmapButton, GenButton, GTKMenuItemGetFixedLabel, PlateButton, ThemedGenButton, adjust_font_size_for_gcdc, get_bitmap_disabled, get_dc_font_size, get_dialogs, platebtn, set_bitmap_labels, set_maxsize, wx_Panel, ) try: from wx.lib.agw import aui from wx.lib.agw.aui import AuiDefaultTabArt except ImportError: from wx import aui from wx.aui import PyAuiTabArt as AuiDefaultTabArt import wx.html import wx.lib.filebrowsebutton as filebrowse from wx._core import wxAssertionError from wx.lib import fancytext from wx.lib.agw import hyperlink from wx.lib.statbmp import GenStaticBitmap TASKBAR = None SAFE_WX_UI = os.getenv("DISPLAYCAL_UNSAFE_WX_UI", "").strip() != "1" if sys.platform == "win32" and sys.getwindowsversion() >= (6, 1): try: pass except Exception as exception: print(exception) NUMPAD_KEYCODES = [ wx.WXK_NUMPAD0, wx.WXK_NUMPAD1, wx.WXK_NUMPAD2, wx.WXK_NUMPAD3, wx.WXK_NUMPAD4, wx.WXK_NUMPAD5, wx.WXK_NUMPAD6, wx.WXK_NUMPAD7, wx.WXK_NUMPAD8, wx.WXK_NUMPAD9, wx.WXK_NUMPAD_ADD, wx.WXK_NUMPAD_DECIMAL, wx.WXK_NUMPAD_ENTER, wx.WXK_NUMPAD_EQUAL, wx.WXK_NUMPAD_DIVIDE, wx.WXK_NUMPAD_MULTIPLY, wx.WXK_NUMPAD_SEPARATOR, wx.WXK_NUMPAD_SUBTRACT, ] NAV_KEYCODES = [ wx.WXK_DOWN, wx.WXK_END, wx.WXK_HOME, wx.WXK_LEFT, wx.WXK_PAGEDOWN, wx.WXK_PAGEUP, wx.WXK_RIGHT, wx.WXK_TAB, wx.WXK_UP, wx.WXK_NUMPAD_DOWN, wx.WXK_NUMPAD_END, wx.WXK_NUMPAD_HOME, wx.WXK_NUMPAD_LEFT, wx.WXK_NUMPAD_PAGEDOWN, wx.WXK_NUMPAD_PAGEUP, wx.WXK_NUMPAD_RIGHT, wx.WXK_NUMPAD_UP, ] PROCESSING_KEYCODES = [ wx.WXK_ESCAPE, wx.WXK_RETURN, wx.WXK_INSERT, wx.WXK_DELETE, wx.WXK_BACK, ] MODIFIER_KEYCODES = [wx.WXK_SHIFT, wx.WXK_CONTROL, wx.WXK_ALT, wx.WXK_COMMAND] REMAINING_TIME_LABEL = "--:--:--" class AboutDialog(wx.Dialog): """About dialog for the application.""" def __init__(self, *args, **kwargs): kwargs["style"] = wx.DEFAULT_DIALOG_STYLE & ~( wx.RESIZE_BORDER | wx.MAXIMIZE_BOX ) kwargs["name"] = "aboutdialog" wx.Dialog.__init__(self, *args, **kwargs) # Set an icon so text isn't crammed to the left of the titlebar under # Windows (other platforms?) self.SetIcons(config.get_icon_bundle([256, 48, 32, 16], APPNAME)) self.Sizer = wx.BoxSizer(wx.VERTICAL) self.panel = wx.ScrolledWindow(self, style=wx.VSCROLL) self.Sizer.Add(self.panel, 1, flag=wx.EXPAND) self.panel.Sizer = wx.BoxSizer(wx.VERTICAL) if "gtk3" in wx.PlatformInfo: # Fix background color not working for panels under GTK3 self.Bind(wx.EVT_ERASE_BACKGROUND, self.OnEraseBackground) if "gtk3" in wx.PlatformInfo: OnEraseBackground = wx_Panel.__dict__["OnEraseBackground"] def OnClose(self, event): """Handle the close button event to hide the dialog. Args: event (wx.CommandEvent): The event triggered by the close button. """ self.Hide() def Layout(self): """Layout the dialog and its components.""" self.Sizer.SetMinSize(480, 560) self.Sizer.SetSizeHints(self) self.panel.SetScrollRate(2, 2) self.Sizer.Layout() if wx.Platform == "__WXGTK__": for child in self.panel.Children: # Fix height of children child.MinSize = child.MinSize[0], child.Size[1] def add_items(self, items): """Add items to the dialog. Args: items (list): A list of items to add to the dialog. """ self.line = wx.Panel(self, size=(-1, 1)) self.line.SetBackgroundColour( wx.SystemSettings.GetColour(wx.SYS_COLOUR_3DLIGHT) ) self.Sizer.Add(self.line, flag=wx.EXPAND) self.btnpanel = wx.Panel(self) self.btnpanel.Sizer = wx.GridSizer(1, 1, 0, 0) self.Sizer.Add(self.btnpanel, flag=wx.EXPAND) self.ok = wx.Button(self.btnpanel, -1, lang.getstr("close")) self.btnpanel.Sizer.Add(self.ok, flag=wx.ALL | wx.ALIGN_CENTER, border=12) self.Bind(wx.EVT_BUTTON, self.OnClose, id=self.ok.GetId()) for item in items: if ( not isinstance(item, wx.Window) and hasattr(item, "__iter__") and [ subitem for subitem in item if not isinstance(subitem, (int, float)) ] ): sizer = wx.BoxSizer(wx.HORIZONTAL) self.add_item(sizer, self.panel.Sizer) for subitem in item: self.add_item(subitem, sizer) else: self.add_item(item, self.panel.Sizer) self.ok.SetDefault() self.ok.SetFocus() def add_item(self, item, sizer): """Add an item to the dialog's sizer. Args: item (wx.Window | tuple | str): The item to add, which can be a wx.Window, a tuple of items, or a string. sizer (wx.Sizer): The sizer to add the item to. """ if isinstance(item, (HyperLinkCtrl, ThemedGenButton)): item.BackgroundColour = self.panel.BackgroundColour if isinstance(item, wx.Window): pointsize = 10 font = item.GetFont() if item.GetLabel() and font.GetPointSize() > pointsize: font.SetPointSize(pointsize) item.SetFont(font) flag = wx.ALIGN_NOT if isinstance(item, (wx.Panel, wx.PyPanel)): flag |= wx.EXPAND elif sizer is self.panel.Sizer: flag |= wx.LEFT | wx.RIGHT sizer.Add(item, 0, flag, 12) class AnimatedBitmap(wx.PyControl): """Animated bitmap.""" def __init__( self, parent, id=wx.ID_ANY, # noqa: A002 bitmaps=None, range_=(0, -1), loop=True, pos=wx.DefaultPosition, size=wx.DefaultSize, style=wx.NO_BORDER, ): """Create animated bitmap. bitmaps should be an array of bitmaps. range should be the indexes of the range of frames that should be looped. -1 means last frame. """ self.dpiscale = getcfg("app.dpi") / get_default_dpi() if self.dpiscale > 1: size = tuple(round(v * self.dpiscale) if v != -1 else v for v in size) wx.PyControl.__init__(self, parent, id, pos, size, style) self._minsize = size self.SetBitmaps(bitmaps or [], range_, loop) # Avoid flickering under Windows self.Bind(wx.EVT_ERASE_BACKGROUND, lambda event: None) self.Bind(wx.EVT_PAINT, self.OnPaint) self._timer = BetterTimer(self) self.Bind(EVT_BETTER_TIMER, self.OnTimer, self._timer) self.Bind(wx.EVT_WINDOW_DESTROY, self.OnDestroy) def OnDestroy(self, event): """Handle the destruction of the control to stop the timer. Args: event (wx.WindowDestroyEvent): The event triggered when the control """ self._timer.Stop() del self._timer return 0 def DoGetBestSize(self): """Get the best size for the control based on the bitmaps. Returns: wx.Size: The best size for the control. """ return self._minsize def OnPaint(self, event): """Handle the paint event to draw the current frame of the animation. Args: event (wx.PaintEvent): The paint event triggered by the animation. """ dc = wx.BufferedPaintDC(self) dc.SetBackground(wx.Brush(self.Parent.BackgroundColour)) dc.Clear() if self._bitmaps: self.frame = min(self.frame, len(self._bitmaps) - 1) if self.dpiscale > 1: dc.SetUserScale(self.dpiscale, self.dpiscale) dc.DrawBitmap(self._bitmaps[self.frame], 0, 0, True) def OnTimer(self, event): """Handle the timer event to update the frame of the animation. Args: event (wx.TimerEvent): The timer event triggered by the animation. """ first_frame, last_frame = self.range if first_frame < 0: first_frame += len(self._bitmaps) if last_frame < 0: last_frame += len(self._bitmaps) frame = self.frame if frame < last_frame: frame += 1 elif self.loop: frame = first_frame if frame != self.frame: self.frame = frame self.Refresh() def Play(self, fps=24): """Start the animation. Args: fps (int): Frames per second. """ self._timer.Start(int(1000.0 / fps)) def Stop(self): """Stop the animation.""" self._timer.Stop() def SetBitmaps(self, bitmaps, range_=(0, -1), loop=True): """Set the bitmaps to be used for the animation. Args: bitmaps (list): A list of wx.Bitmap objects to be used in the animation. range_ (tuple): A tuple specifying the range of frames to be looped. The first element is the starting index, and the second is the ending index. loop (bool): Whether the animation should loop when it reaches the end. Default is True. """ w, h = self._minsize for bitmap in bitmaps: w = max(bitmap.Size[0], w) h = max(bitmap.Size[0], h) self._minsize = w, h self._bitmaps = bitmaps self.loop = loop self.range = range_ self.frame = 0 class AuiBetterTabArt(AuiDefaultTabArt): """A custom tab art class for AUI tab controls, providing enhanced drawing.""" def DrawTab(self, dc, wnd, page, in_rect, close_button_state, paint_control=False): """Draw a single tab. Args: dc: a :class:`DC` device context. wnd: a :class:`Window` instance object. page: the tab control page associated with the tab. in_rect (Rect): rectangle the tab should be confined to. close_button_state (int): the state of the close button on the tab. paint_control (bool): whether to draw the control inside a tab (if any) on a :class:`MemoryDC`. """ # if the caption is empty, measure some temporary text caption = page.caption if not caption: caption = "Xj" dc.SetFont(self._selected_font) if hasattr(dc, "GetFullMultiLineTextExtent"): # Phoenix selected_textx, selected_texty = dc.GetMultiLineTextExtent(caption) else: # Classic selected_textx, selected_texty, dummy = dc.GetMultiLineTextExtent(caption) dc.SetFont(self._normal_font) if hasattr(dc, "GetFullMultiLineTextExtent"): # Phoenix normal_textx, normal_texty = dc.GetMultiLineTextExtent(caption) else: # Classic normal_textx, normal_texty, dummy = dc.GetMultiLineTextExtent(caption) control = page.control # figure out the size of the tab tab_size, x_extent = self.GetTabSize( dc, wnd, page.caption, page.bitmap, page.active, close_button_state, control ) tab_height = self._tab_ctrl_height - 3 tab_width = tab_size[0] tab_x = in_rect.x tab_y = in_rect.y + in_rect.height - tab_height caption = page.caption # select pen, brush and font for the tab to be drawn if page.active: dc.SetFont(self._selected_font) textx, texty = selected_textx, selected_texty else: dc.SetFont(self._normal_font) textx, texty = normal_textx, normal_texty if not page.enabled: dc.SetTextForeground(self._tab_disabled_text_colour) pagebitmap = page.dis_bitmap else: dc.SetTextForeground(self._tab_text_colour(page)) pagebitmap = page.bitmap # create points that will make the tab outline clip_width = tab_width if tab_x + clip_width > in_rect.x + in_rect.width: clip_width = in_rect.x + in_rect.width - tab_x # since the above code above doesn't play well with WXDFB or WXCOCOA, # we'll just use a rectangle for the clipping region for now -- dc.SetClippingRegion(tab_x, tab_y, clip_width + 1, tab_height - 3) border_points = [wx.Point() for i in range(6)] agwFlags = self.GetAGWFlags() if agwFlags & aui.AUI_NB_BOTTOM: border_points[0] = wx.Point(tab_x, tab_y) border_points[1] = wx.Point(tab_x, tab_y + tab_height - 6) border_points[2] = wx.Point(tab_x + 2, tab_y + tab_height - 4) border_points[3] = wx.Point(tab_x + tab_width - 2, tab_y + tab_height - 4) border_points[4] = wx.Point(tab_x + tab_width, tab_y + tab_height - 6) border_points[5] = wx.Point(tab_x + tab_width, tab_y) else: # if (agwFlags & aui.AUI_NB_TOP) border_points[0] = wx.Point(tab_x, tab_y + tab_height - 4) border_points[1] = wx.Point(tab_x, tab_y + 2) border_points[2] = wx.Point(tab_x + 2, tab_y) border_points[3] = wx.Point(tab_x + tab_width - 2, tab_y) border_points[4] = wx.Point(tab_x + tab_width, tab_y + 2) border_points[5] = wx.Point(tab_x + tab_width, tab_y + tab_height - 4) # TODO: else if (agwFlags & aui.AUI_NB_LEFT) # TODO: else if (agwFlags & aui.AUI_NB_RIGHT) drawn_tab_yoff = border_points[1].y drawn_tab_height = border_points[0].y - border_points[1].y if page.active: # draw active tab # draw base background colour r = wx.Rect(tab_x, tab_y, tab_width, tab_height) dc.SetPen(self._base_colour_pen) dc.SetBrush(self._base_colour_brush) dc.DrawRectangle(r.x + 1, r.y + 1, r.width - 1, r.height - 4) # this white helps fill out the gradient at the top of the tab dc.SetPen(wx.Pen(self._tab_gradient_highlight_colour)) dc.SetBrush(wx.Brush(self._tab_gradient_highlight_colour)) dc.DrawRectangle(r.x + 2, r.y + 1, r.width - 3, r.height - 4) # these two points help the rounded corners appear more antialiased dc.SetPen(self._base_colour_pen) dc.DrawPoint(r.x + 2, r.y + 1) dc.DrawPoint(r.x + r.width - 2, r.y + 1) # set rectangle down a bit for gradient drawing r.SetHeight(int(r.GetHeight() / 2)) r.x += 2 r.width -= 3 r.y += r.height r.y -= 2 # draw gradient background top_colour = self._tab_bottom_colour bottom_colour = self._tab_top_colour dc.GradientFillLinear(r, bottom_colour, top_colour, wx.NORTH) else: # draw inactive tab r = wx.Rect(tab_x, tab_y + 1, tab_width, tab_height - 3) # start the gradent up a bit and leave the inside border inset # by a pixel for a 3D look. Only the top half of the inactive # tab will have a slight gradient r.x += 2 r.y += 1 r.width -= 3 r.height = int(r.height / 2) # -- draw top gradient fill for glossy look top_colour = self._tab_inactive_top_colour bottom_colour = self._tab_inactive_bottom_colour dc.GradientFillLinear(r, bottom_colour, top_colour, wx.NORTH) r.y += r.height r.y -= 1 # -- draw bottom fill for glossy look top_colour = self._tab_inactive_bottom_colour bottom_colour = self._tab_inactive_bottom_colour dc.GradientFillLinear(r, top_colour, bottom_colour, wx.SOUTH) # draw tab outline dc.SetPen(self._border_pen) dc.SetBrush(wx.TRANSPARENT_BRUSH) dc.DrawPolygon(border_points) # there are two horizontal grey lines at the bottom of the tab control, # this gets rid of the top one of those lines in the tab control if page.active: if agwFlags & aui.AUI_NB_BOTTOM: dc.SetPen(wx.Pen(self._background_bottom_colour)) # TODO: else if (agwFlags & aui.AUI_NB_LEFT) # TODO: else if (agwFlags & aui.AUI_NB_RIGHT) else: # for aui.AUI_NB_TOP dc.SetPen(self._base_colour_pen) dc.DrawLine( border_points[0].x + 1, border_points[0].y, border_points[5].x, border_points[5].y, ) text_offset = tab_x + 8 close_button_width = 0 if close_button_state != aui.AUI_BUTTON_STATE_HIDDEN: close_button_width = self._active_close_bmp.GetWidth() if agwFlags & aui.AUI_NB_CLOSE_ON_TAB_LEFT: text_offset += close_button_width - 5 bitmap_offset = 0 if pagebitmap.IsOk(): bitmap_offset = tab_x + 8 if agwFlags & aui.AUI_NB_CLOSE_ON_TAB_LEFT and close_button_width: bitmap_offset += close_button_width - 5 # draw bitmap dc.DrawBitmap( pagebitmap, bitmap_offset, drawn_tab_yoff + int(drawn_tab_height / 2) - int(pagebitmap.GetHeight() / 2), True, ) text_offset = bitmap_offset + pagebitmap.GetWidth() text_offset += 3 # bitmap padding elif agwFlags & aui.AUI_NB_CLOSE_ON_TAB_LEFT == 0 or not close_button_width: text_offset = tab_x + 8 draw_text = aui.ChopText( dc, caption, tab_width - (text_offset - tab_x) - close_button_width ) ypos = drawn_tab_yoff + int(drawn_tab_height / 2) - int(texty / 2) - 1 offset_focus = text_offset if control is not None: try: if control.GetPosition() != wx.Point(text_offset + 1, ypos): control.SetPosition(wx.Point(text_offset + 1, ypos)) if not control.IsShown(): control.Show() if paint_control: bmp = aui.TakeScreenShot(control.GetScreenRect()) dc.DrawBitmap(bmp, text_offset + 1, ypos, True) controlW, controlH = control.GetSize() text_offset += controlW + 4 textx += controlW + 4 except wx.PyDeadObjectError: pass # draw tab text if hasattr(dc, "GetFullMultiLineTextExtent"): # Phoenix rectx, recty = dc.GetMultiLineTextExtent(draw_text) else: # Classic rectx, recty, dummy = dc.GetMultiLineTextExtent(draw_text) textfg = dc.GetTextForeground() shadow = wx.SystemSettings.GetColour(wx.SYS_COLOUR_3DLIGHT) dc.SetTextForeground(shadow) dc.DrawLabel(draw_text, wx.Rect(text_offset + 1, ypos + 1, rectx, recty)) dc.SetTextForeground(textfg) dc.DrawLabel(draw_text, wx.Rect(text_offset, ypos, rectx, recty)) # draw focus rectangle if (agwFlags & aui.AUI_NB_NO_TAB_FOCUS) == 0: self.DrawFocusRectangle( dc, page, wnd, draw_text, offset_focus, bitmap_offset, drawn_tab_yoff, drawn_tab_height, rectx, recty, ) out_button_rect = wx.Rect() # draw close button if necessary if close_button_state != aui.AUI_BUTTON_STATE_HIDDEN: bmp = self._disabled_close_bmp if close_button_state == aui.AUI_BUTTON_STATE_HOVER: bmp = self._hover_close_bmp elif close_button_state == aui.AUI_BUTTON_STATE_PRESSED: bmp = self._pressed_close_bmp shift = ((agwFlags & aui.AUI_NB_BOTTOM and [1]) or [0])[0] if agwFlags & aui.AUI_NB_CLOSE_ON_TAB_LEFT: rect = wx.Rect( tab_x + 4, tab_y + int((tab_height - bmp.GetHeight()) / 2 - shift), close_button_width, tab_height, ) else: rect = wx.Rect( tab_x + tab_width - close_button_width - 1, tab_y + int((tab_height - bmp.GetHeight()) / 2 - shift), close_button_width, tab_height, ) rect = aui.IndentPressedBitmap(rect, close_button_state) dc.DrawBitmap(bmp, rect.x, rect.y, True) out_button_rect = rect out_tab_rect = wx.Rect(tab_x, tab_y, tab_width, tab_height) dc.DestroyClippingRegion() return out_tab_rect, out_button_rect, x_extent def SetDefaultColours(self, base_colour=None): """Set the default colours, which are calculated from the given base colour. Args: base_colour: an instance of :class:`Colour`. If defaulted to ``None``, a colour is generated accordingly to the platform and theme. """ if base_colour is None: base_colour = aui.GetBaseColour() self.SetBaseColour(base_colour) self._border_colour = aui.StepColour(base_colour, 75) self._border_pen = wx.Pen(self._border_colour) self._background_top_colour = aui.StepColour(self._base_colour, 90) self._background_bottom_colour = aui.StepColour(self._base_colour, 120) self._tab_top_colour = self._base_colour self._tab_bottom_colour = aui.StepColour(self._base_colour, 130) self._tab_gradient_highlight_colour = aui.StepColour(self._base_colour, 130) self._tab_inactive_top_colour = self._background_top_colour self._tab_inactive_bottom_colour = aui.StepColour(self._base_colour, 110) self._tab_text_colour = lambda page: page.text_colour self._tab_disabled_text_colour = wx.SystemSettings.GetColour( wx.SYS_COLOUR_GRAYTEXT ) class AutocompleteComboBox(wx.ComboBox): """A wx.ComboBox with autocomplete functionality.""" def __init__(self, *args, **kwargs): wx.ComboBox.__init__(self, *args, **kwargs) self.Bind(wx.EVT_TEXT, self.OnText) self.Bind(wx.EVT_CHAR, self.OnChar) self.Bind(wx.EVT_COMBOBOX, self.OnComboBox) self._ignore_text_evt = False self._popup_shown = None if hasattr(wx, "EVT_COMBOBOX_DROPDOWN"): self.Bind(wx.EVT_COMBOBOX_DROPDOWN, self.OnComboBoxDropDown) if hasattr(wx, "EVT_COMBOBOX_CLOSEUP"): self.Bind(wx.EVT_COMBOBOX_CLOSEUP, self.OnComboBoxCloseUp) def OnComboBox(self, event): """Handle the combo box selection event. Args: event (wx.CommandEvent): The command event triggered by the combo box. """ self._ignore_text_evt = True event.Skip() def OnComboBoxDropDown(self, event): """Handle the dropdown event of the combo box. Args: event (wx.CommandEvent): The dropdown event triggered by the combo box. """ self._popup_shown = True event.Skip() def OnComboBoxCloseUp(self, event): """Handle the close-up event of the combo box. Args: event (wx.CommandEvent): The close-up event triggered by the combo box. """ self._popup_shown = False event.Skip() def OnChar(self, event): """Handle character input in the combo box. Args: event (wx.KeyEvent): The key event triggered by character input. """ if event.GetKeyCode() == 8 or event.ControlDown(): # Backspace or modifier self._ignore_text_evt = True event.Skip() def OnText(self, event): """Handle text input in the combo box. Args: event (wx.CommandEvent): The text change event. """ if self._ignore_text_evt: self._ignore_text_evt = False return current_text = event.GetString().lower() found = False for i, choice in enumerate(self.Items): if choice.lower().startswith(current_text): self._ignore_text_evt = True if self._popup_shown is not None: self.SetSelection(i) self.SetValue(choice) self.SetInsertionPoint(len(current_text)) self.SetMark(len(current_text), len(choice)) found = True break if not found: event.Skip() class BaseApp(wx.App): """Application base class implementing common functionality.""" _exithandlers: ClassVar[list] = [] _query_end_session = None def __init__(self, *args, **kwargs): # Fix sys.prefix for SetInstallPrefix used inside wx.App which does not # decode to Unicode when calling SetInstallPrefix. DisplayCAL when # bundled by Py2App can't be run from a path containing Unicode # characters under Mac OS X otherwise. prefix = sys.prefix sys.prefix = str(sys.prefix) wx.App.__init__(self, *args, **kwargs) # Restore prefix sys.prefix = prefix if not kwargs.get("clearSigInt", True) or (len(args) == 4 and not args[3]): # Install our own SIGINT handler, so we can do cleanup on receiving # SIGINT print("Installing SIGINT handler") signal.signal(signal.SIGINT, self.signal_handler) # This timer allows processing of SIGINT / CTRL+C, because normally # with clearSigInt=False, SIGINT / CTRL+C are only processed during # UI events self._signal_timer = wx.Timer(self) self.Bind(wx.EVT_TIMER, lambda e: None, self._signal_timer) self._signal_timer.Start(100) def signal_handler(self, signum, frame): """Handle signals like SIGINT (Ctrl+C). Args: signum (int): The signal number. frame (frame): The current stack frame. """ if signum == signal.SIGINT: print("Received SIGINT") print("Sending query to end session...") self.ProcessEvent(wx.CloseEvent(wx.EVT_QUERY_END_SESSION.evtType[0])) def OnInit(self): """Initialize the application. Returns: bool: True if initialization was successful, False otherwise. """ self.AppName = PYNAME set_default_app_dpi() # We use a lock so we can make sure the exit handlers are executed # properly before we actually exit when receiving OS # logout/reboot/shutdown events. This is needed because it is not # guaranteed that when we receive EVT_QUERY_END_SESSION and close # the main application window (which will normally exit the main event # loop unless BaseApp.ExitOnFrameDelete is False) that OnExit (which'll # execute the exit handlers) will run right away because normally it'll # run after the main event loop exits (i.e. in the next iteration of the # main loop after an implicit or explicit call of ExitMainLoop). # Also, we need to call OnExit explicitly when receiving EVT_END_SESSION # because there will be no next iteration of the event loop (the OS # simply kills the application after the handler is executed). If OnExit # was already called before as a result of receiving # EVT_QUERY_END_SESSION and exiting the main event loop (remember this # is not guaranteed because of the way the event loop works!) and did # already finish, this'll do nothing and we can just exit. If OnExit is # still executing the exit handlers and thus holds the lock, the lock # makes sure that we wait for OnExit to finish before we explicitly call # sys.exit(0) (which'll make sure exit handlers registered by atexit # will run) to finally exit for good before the OS tries to kill the # application. self._lock = threading.Lock() self.Bind(wx.EVT_QUERY_END_SESSION, self.query_end_session) self.Bind(wx.EVT_END_SESSION, self.end_session) if os.getenv("XDG_SESSION_TYPE") == "wayland": # Fix erroneous extra spacing around window contents under # Wayland. First frame will get size right, but not min size, # so create a 'dummy' frame, call Show() which is needed so # we can fix subsequently created windows, then instantly get # rid of it. Ugly. dummy = wx.Frame(None) # May not be needed, but we don't want to risk actually # showing our dummy frame dummy.SetTransparent(0) # Need to call Show() to 'fix' subsequently created windows dummy.Show() # Now we can get rid of it dummy.Close() return True def MacOpenFiles(self, paths): """Handle opening files on macOS. This method is called when files are opened via the application icon or by dragging files onto the application icon in the dock or taskbar. Args: paths (list): List of file paths to open. """ if self.TopWindow and isinstance( getattr(self.TopWindow, "droptarget", None), FileDrop ): self.TopWindow.droptarget.OnDropFiles(0, 0, paths) def MacReopenApp(self): """Reopen the application on macOS. This method is called when the application is reopened after being closed, typically by the user clicking on the application icon in the dock or taskbar. """ if self.TopWindow and self.TopWindow.IsShownOnScreen(): self.TopWindow.Raise() def process_argv(self, count=0): """Process command line arguments to open files. Args: count (int): Number of files to open. If 0, all files are opened. Returns: list: List of file paths opened by the application. """ paths = [] for arg in sys.argv[1:]: if os.path.isfile(arg): paths.append(str(arg)) if len(paths) == count: break if paths: self.MacOpenFiles(paths) return paths return None def OnExit(self): """Handle application exit. Returns: int: Return code for the application exit. Defaults to 0. """ print("Executing BaseApp.OnExit()") with self._lock: if BaseApp._exithandlers: print("Running application exit handlers") BaseApp._run_exitfuncs() if hasattr(wx.App, "OnExit"): result = wx.App.OnExit(self) return result if result is not None else 0 return 0 @staticmethod def _run_exitfuncs() -> int: """Run any registered exit functions. _exithandlers is traversed in reverse order so functions are executed last in, first out. """ # Inspired by python's 'atexit' module. # It's important that the exit handlers run *before* the actual main # loop exits, otherwise they might not run at all if the app is closed # externally (e.g. if the OS asks the app to close on logout). # Using the 'atexit' module will NOT work! exc_info = None while BaseApp._exithandlers: func, args, kwargs = BaseApp._exithandlers.pop() try: func(*args, **kwargs) except SystemExit: exc_info = sys.exc_info() except Exception: import traceback print("Error in BaseApp._run_exitfuncs:") print(traceback.format_exc()) if exc_info is not None: raise exc_info[0](exc_info[1]).with_traceback(exc_info[2]) return 0 @staticmethod def register_exitfunc(func, *args, **kwargs) -> None: """Register a function to be called on application exit. Args: func (callable): The function to register. *args: Positional arguments to pass to the function. **kwargs: Keyword arguments to pass to the function. """ BaseApp._exithandlers.append((func, args, kwargs)) def query_end_session(self, event): """Handle the query end session event. Args: event (wx.Event): The query end session event. """ print("Received query to end session") if event.CanVeto(): print("Can veto") else: print("Cannot veto") if self.TopWindow and self.TopWindow is not self._query_end_session: if not isinstance(self.TopWindow, wx.Dialog): print("Trying to close main top-level application window...") if self.TopWindow.Close(force=not event.CanVeto()): if self.TopWindow is not None: self.TopWindow.listening = False self._query_end_session = self.TopWindow print("Main top-level application window processed close event") return print("Failed to close main top-level application window") if event.CanVeto(): event.Veto() print("Vetoed query to end session") def end_session(self, event): """Handle the end session event. Args: event (wx.Event): The end session event. """ print("Ending session") self.ExitMainLoop() # We may need to call OnExit() explicitly because there is not # guaranteed to be a next iteration of the main event loop with contextlib.suppress(Exception): # Yes, this can fail with a TypeError, amazingly enough :-( # Apparently sometimes, wx already shuts down the application # and OnExit will be None. We assume in this case that OnExit # already ran. self.OnExit() # Calling sys.exit makes sure that exit handlers registered by atexit # will run print("Calling sys.exit(0)") sys.exit(0) active_window = None responseformats = {} class BaseFrame(wx.Frame): """Main frame base class.""" def __init__(self, *args, **kwargs): wx.Frame.__init__(self, *args, **kwargs) self.init() def FindWindowByName(self, name): """Find a child window by its name. WxPython Phoenix FindWindowByName descends into the parent windows, we don't want that. Args: name (str): The name of the child window to find. Returns: wx.Window: The child window with the specified name, or None if not found. """ for child in list(self.GetAllChildren()): if hasattr(child, "Name") and child.Name == name: return child return None def __OnDestroy(self, event): """Handle the destruction of the main frame. Args: event (wx.Event): The window destroy event. """ if event.GetEventObject() is self: self.listening = False event.Skip() return 0 def close_all(self): """Close all dialogs and frames.""" windows = list(wx.GetTopLevelWindows()) while windows: win = windows.pop() if ( isinstance(win, (AboutDialog, BaseInteractiveDialog, ProgressDialog)) or win.__class__ is wx.Dialog ) and win.IsShown(): if win.IsModal(): wx.CallAfter(win.EndModal, wx.ID_CANCEL) print("Closed modal dialog", win) else: wx.CallAfter(win.Close) print("Closed dialog", win) elif isinstance(win, wx.Frame): wx.CallAfter(win.Close) print("Closed", win) def init(self): """Initialize the main frame.""" self.Bind(wx.EVT_ACTIVATE, self.activate_handler) self.Bind(wx.EVT_WINDOW_DESTROY, self.__OnDestroy) def init_menubar(self): """Initialize the menu bar for the main frame.""" self.MenuBar = wx.MenuBar() filemenu = wx.Menu() quit_action = filemenu.Append( -1 if wx.VERSION < (2, 9) else wx.ID_EXIT, "&{}\tCtrl+Q".format(lang.getstr("menuitem.quit")), ) self.Bind(wx.EVT_MENU, lambda event: self.Close(), quit_action) if sys.platform != "darwin": self.MenuBar.Append(filemenu, "&{}".format(lang.getstr("menu.file"))) def activate_handler(self, event): """Handle activation events for the main frame. Args: event (wx.Event): The activation event. """ global active_window active_window = self def listen(self): """Listen for incoming connections on the scripting socket.""" if not isinstance(getattr(sys, "_appsocket", None), socket.socket): return addr, port = sys._appsocket.getsockname() if addr == "0.0.0.0": # noqa: S104 with contextlib.suppress(OSError): addr = get_network_addr() print(lang.getstr("app.listening", (addr, port))) self.listening = True self.listener = threading.Thread( target=self.connection_handler, name="ScriptingHost.ConnectionHandler" ) self.listener.start() def connect(self, ip, port): """Connect to a scripting client socket. Args: ip (str): The IP address to connect to. port (int): The port to connect to. Returns: socket.socket: The connected socket object. OSError: If the connection fails, an OSError is returned. """ if getattr(self, "conn", None): self.conn.disconnect() conn = ScriptingClientSocket() conn.settimeout(3) try: conn.connect((ip, port)) except OSError as exception: del conn return exception return conn # noqa: F821 def connection_handler(self): """Handle socket connections.""" self._msghandlercount = 0 while self and getattr(self, "listening", False): try: # Wait for connection conn, addrport = sys._appsocket.accept() except socket.timeout: continue except OSError as exception: if exception.errno == errno.EWOULDBLOCK: sleep(0.05) continue break if addrport[0] != "127.0.0.1" and not getcfg("app.allow_network_clients"): # Network client disallowed conn.close() print(lang.getstr("app.client.network.disallowed", addrport)) sleep(0.2) continue try: conn.settimeout(0.2) except OSError as exception: conn.close() print(lang.getstr("app.client.ignored", exception)) sleep(0.2) continue print(lang.getstr("app.client.connect", addrport)) self._msghandlercount += 1 threading.Thread( target=self.message_handler, name=f"ScriptingHost.MessageHandler-{self._msghandlercount}", args=(conn, addrport), ).start() sys._appsocket.close() def message_handler(self, conn, addrport): """Handle messages sent via socket. Args: conn (socket.socket): The socket connection to handle. addrport (tuple): A tuple containing the address and port of the connected client, e.g. ('127.0.0.1', 1234). """ responseformats[conn] = "plain" buffer = "" while self and getattr(self, "listening", False): # Wait for incoming message try: incoming = conn.recv(4096) if isinstance(incoming, bytes): incoming = incoming.decode("utf-8") except socket.timeout: continue except OSError as exception: if exception.errno == errno.EWOULDBLOCK: sleep(0.05) continue break else: if not incoming: break buffer += incoming while "\n" in buffer and self and getattr(self, "listening", False): end = buffer.find("\n") line = buffer[:end].strip() buffer = buffer[end + 1 :] if line: command_timestamp = datetime.now().strftime( "%Y-%m-%dTH:%M:%S.%f" ) line = str(line) print(lang.getstr("app.incoming_message", (*addrport, line))) data = split_command_line(line) response = None # Non-UI commands if data[0] == "getappname" and len(data) == 1: response = PYNAME elif data[0] == "getcfg" and len(data) < 3: if len(data) == 2: # Return cfg value if data[1] in DEFAULTS: if responseformats[conn].startswith("xml"): response = { "name": data[1], "value": getcfg(data[1]), } else: response = {data[1]: getcfg(data[1])} else: response = "invalid" else: # Return whole cfg if responseformats[conn] != "plain": response = [] else: response = {} for name in sorted(DEFAULTS): value = getcfg(name, False) if value is not None: if responseformats[conn] != "plain": response.append( {"name": name, "value": value} ) else: response[name] = value elif data[0] == "getcommands" and len(data) == 1: response = sorted(self.get_commands()) elif data[0] == "getdefault" and len(data) == 2: if data[1] in DEFAULTS: if responseformats[conn] != "plain": response = { "name": data[1], "value": DEFAULTS[data[1]], } else: response = {data[1]: DEFAULTS[data[1]]} else: response = "invalid" elif data[0] == "getdefaults" and len(data) == 1: response = [] if responseformats[conn] != "plain" else {} for name in sorted(DEFAULTS): if responseformats[conn] != "plain": response.append( {"name": name, "value": DEFAULTS[name]} ) else: response[name] = DEFAULTS[name] elif data[0] == "getvalid" and len(data) == 1: if responseformats[conn] != "plain": response = {} for section, options in ( ("ranges", config.VALID_RANGES), ("values", config.VALID_VALUES), ): valid = response[section] = [] for name in options: values = options[name] valid.append({"name": name, "values": values}) else: response = { "ranges": config.VALID_RANGES, "values": config.VALID_VALUES, } if responseformats[conn] == "plain": valid = [] for section in response: options = response[section] valid.append(f"[{section}]") for name in options: values = options[name] valid.append( "{} = {}".format( name, " ".join( demjson.encode(value) for value in values ), ) ) response = valid elif ( data[0] == "setresponseformat" and len(data) == 2 and data[1] in ("json", "json.pretty", "plain", "xml", "xml.pretty") ): responseformats[conn] = data[1] response = "ok" if response is not None: self.send_response(response, data, conn, command_timestamp) continue # UI commands wx.CallAfter( self.finish_processing, data, conn, command_timestamp ) try: conn.shutdown(socket.SHUT_RDWR) except OSError as exception: if exception.errno != errno.ENOTCONN: print("Warning - could not shutdown connection:", exception) print(lang.getstr("app.client.disconnect", addrport)) conn.close() responseformats.pop(conn) def get_app_state(self, file_format): """Get the current application state. Args: file_format (str): The format in which to return the state. Can be "plain", "json", "json.pretty", "xml", or "xml.pretty". Returns: dict or str: The application state in the specified format. """ win = self.get_top_window() if isinstance(win, wx.Dialog) and win.IsShown(): if isinstance(win, (DirDialog, FileDialog)): response = format_ui_element(win, file_format) if file_format != "plain": response.update({"message": win.Message, "path": win.Path}) else: response = [ response, demjson.encode(win.Message), "path", demjson.encode(win.Path), ] elif isinstance(win, (AboutDialog, BaseInteractiveDialog, ProgressDialog)): response = format_ui_element(win, file_format) if file_format == "plain": response = [response] if hasattr(win, "message") and win.message: if file_format != "plain": response["message"] = win.message.Label else: response.append(demjson.encode(win.message.Label)) # Ordering in tab order for child in list(win.GetAllChildren()): if ( child and isinstance(child, (FlatShadedButton, GenButton, wx.Button)) and child.TopLevelParent is win and child.IsShownOnScreen() and child.IsEnabled() ): if file_format != "plain": if "buttons" not in response: response["buttons"] = [] response["buttons"].append(child.Label) else: if "buttons" not in response: response.append("buttons") response.append(demjson.encode(child.Label)) elif win.__class__ is wx.Dialog: response = format_ui_element(win, file_format) if file_format == "plain": response = [response] else: return "blocked" if file_format == "plain": response = " ".join(response) return response if hasattr(self, "worker") and self.worker.is_working(): return "busy" return "idle" def get_commands(self): """Get a list of commands that can be used in the scripting interface. Returns: list: A list of strings containing the commands. """ return self.get_common_commands() def get_common_commands(self): """Get a list of common commands that can be used in the scripting interface. Returns: list: A list of strings containing the common commands. """ cmds = [ "abort", "activate [window]", "alt", "cancel", "ok [filename]", "close [window]", "echo ", "exit [force]", "getactivewindow", "getappname", "getcellvalues [window] ", "getcommands", "getcfg [option]", "getdefault