| 1 |
"""Compatibility fixes and enhancements for wxPython across platforms and versions. |
| 2 |
|
| 3 |
It includes custom widget implementations, DPI scaling adjustments, and |
| 4 |
additional utility functions for improved UI behavior and appearance. |
| 5 |
""" |
| 6 |
|
| 7 |
import contextlib |
| 8 |
import os |
| 9 |
import re |
| 10 |
import shutil |
| 11 |
import sys |
| 12 |
import tempfile |
| 13 |
from typing import Any |
| 14 |
|
| 15 |
from DisplayCAL.meta import NAME as APPNAME |
| 16 |
from DisplayCAL.meta import WX_MINVERSION |
| 17 |
|
| 18 |
if os.getenv("GTK_CSD", "0") != "0": |
| 19 |
# Work-around double window decorations, see |
| 20 |
# https://hub.displaycal.net/issue/17331/ |
| 21 |
os.environ["GTK_CSD"] = "0" |
| 22 |
|
| 23 |
# wx_version will be removed in Phoenix |
| 24 |
try: |
| 25 |
from DisplayCAL import wx_version |
| 26 |
except ImportError: |
| 27 |
pass |
| 28 |
else: |
| 29 |
if not getattr(sys, "frozen", False) and "wx" not in sys.modules: |
| 30 |
with contextlib.suppress(wx_version.VersionError): |
| 31 |
wx_version.select(["4.0", "3.0", "{}.{}.{}".format(*WX_MINVERSION[:3])]) |
| 32 |
|
| 33 |
import wx |
| 34 |
|
| 35 |
if wx.VERSION < WX_MINVERSION: # noqa: SIM300 |
| 36 |
app = wx.GetApp() or wx.App(0) |
| 37 |
result = wx.MessageBox( |
| 38 |
"This application requires a version of wxPython " |
| 39 |
"greater than or equal to {}, but your most recent " |
| 40 |
"version is {}.\n\n" |
| 41 |
"Would you like to download a new version of wxPython?\n".format( |
| 42 |
".".join(str(n) for n in WX_MINVERSION), wx.__version__ |
| 43 |
), |
| 44 |
"wxPython Upgrade Needed", |
| 45 |
style=wx.YES_NO, |
| 46 |
) |
| 47 |
if result == wx.YES: |
| 48 |
import webbrowser |
| 49 |
|
| 50 |
webbrowser.open("http://wxpython.org/") |
| 51 |
app.MainLoop() |
| 52 |
sys.exit() |
| 53 |
import wx.grid |
| 54 |
from wx import xrc |
| 55 |
from wx.lib import platebtn |
| 56 |
from wx.lib.buttons import GenBitmapButton as _GenBitmapButton |
| 57 |
from wx.lib.buttons import GenBitmapTextButton as _GenBitmapTextButton |
| 58 |
from wx.lib.buttons import ThemedGenButton as _ThemedGenButton |
| 59 |
from wx.lib.scrolledpanel import ScrolledPanel |
| 60 |
|
| 61 |
from DisplayCAL.colormath import convert_range |
| 62 |
|
| 63 |
if not hasattr(wx.Window, "HasFocus"): |
| 64 |
# wxPython < 3.0 |
| 65 |
wx.Window.HasFocus = lambda self: self.FindFocus() is self |
| 66 |
|
| 67 |
|
| 68 |
if not hasattr(wx, "wxAssertionError"): |
| 69 |
# wxPython < 4.0 |
| 70 |
wx.wxAssertionError = wx.PyAssertionError |
| 71 |
|
| 72 |
|
| 73 |
if not hasattr(platebtn, "PB_STYLE_TOGGLE"): |
| 74 |
platebtn.PB_STYLE_TOGGLE = 32 |
| 75 |
|
| 76 |
|
| 77 |
if not hasattr(platebtn, "PB_STYLE_DROPARROW"): |
| 78 |
platebtn.PB_STYLE_DROPARROW = 16 |
| 79 |
|
| 80 |
|
| 81 |
if "phoenix" in wx.PlatformInfo: |
| 82 |
# Phoenix compatibility |
| 83 |
import wx.adv |
| 84 |
from wx.lib.agw import aui |
| 85 |
|
| 86 |
def BitmapFromIcon(icon): |
| 87 |
"""Convert an icon to a bitmap.""" |
| 88 |
bmp = wx.Bitmap() |
| 89 |
bmp.CopyFromIcon(icon) |
| 90 |
return bmp |
| 91 |
|
| 92 |
def IconFromBitmap(bmp): |
| 93 |
"""Convert a bitmap to an icon.""" |
| 94 |
icon = wx.Icon() |
| 95 |
icon.CopyFromBitmap(bmp) |
| 96 |
return bmp |
| 97 |
|
| 98 |
wx.BitmapFromIcon = BitmapFromIcon |
| 99 |
wx.CursorFromImage = wx.Cursor |
| 100 |
wx.EmptyBitmap = wx.Bitmap |
| 101 |
wx.EmptyBitmapRGBA = lambda width, height, red=0, green=0, blue=0, alpha=0: ( |
| 102 |
wx.Bitmap.FromRGBA(width, height, red, green, blue, alpha) |
| 103 |
) |
| 104 |
wx.EmptyIcon = wx.Icon |
| 105 |
wx.IconFromBitmap = wx.Icon |
| 106 |
wx.ImageFromStream = wx.Image |
| 107 |
wx.ListCtrl.InsertStringItem = lambda self, index, label: self.InsertItem( |
| 108 |
int(index), str(label) |
| 109 |
) |
| 110 |
wx.ListCtrl.SetStringItem = lambda self, index, col, label: self.SetItem( |
| 111 |
int(index), int(col), str(label) |
| 112 |
) |
| 113 |
wx.Menu.RemoveItem = lambda self, item: self.Remove(item) |
| 114 |
wx.NamedColour = wx.Colour |
| 115 |
wx.PyControl = wx.Control |
| 116 |
wx.PyWindow = wx.Window |
| 117 |
wx.PyPanel = wx.Panel |
| 118 |
wx.StockCursor = wx.Cursor |
| 119 |
wx.Window.SetToolTipString = wx.Window.SetToolTip |
| 120 |
|
| 121 |
# Moved items |
| 122 |
|
| 123 |
wx.HL_DEFAULT_STYLE = wx.adv.HL_DEFAULT_STYLE |
| 124 |
wx.HyperlinkCtrl = wx.adv.HyperlinkCtrl |
| 125 |
wx.HyperlinkCtrlNameStr = wx.adv.HyperlinkCtrlNameStr |
| 126 |
|
| 127 |
wx.SOUND_ASYNC = wx.adv.SOUND_ASYNC |
| 128 |
wx.Sound = wx.adv.Sound |
| 129 |
|
| 130 |
wx.wxEVT_TASKBAR_BALLOON_CLICK = wx.adv.wxEVT_TASKBAR_BALLOON_CLICK |
| 131 |
wx.wxEVT_TASKBAR_BALLOON_TIMEOUT = wx.adv.wxEVT_TASKBAR_BALLOON_TIMEOUT |
| 132 |
wx.wxEVT_TASKBAR_CLICK = wx.adv.wxEVT_TASKBAR_CLICK |
| 133 |
wx.wxEVT_TASKBAR_LEFT_DCLICK = wx.adv.wxEVT_TASKBAR_LEFT_DCLICK |
| 134 |
wx.wxEVT_TASKBAR_LEFT_DOWN = wx.adv.wxEVT_TASKBAR_LEFT_DOWN |
| 135 |
wx.wxEVT_TASKBAR_LEFT_UP = wx.adv.wxEVT_TASKBAR_LEFT_UP |
| 136 |
wx.wxEVT_TASKBAR_MOVE = wx.adv.wxEVT_TASKBAR_MOVE |
| 137 |
wx.wxEVT_TASKBAR_RIGHT_DOWN = wx.adv.wxEVT_TASKBAR_RIGHT_DOWN |
| 138 |
wx.wxEVT_TASKBAR_RIGHT_UP = wx.adv.wxEVT_TASKBAR_RIGHT_UP |
| 139 |
wx.wxEVT_TASKBAR_RIGHT_DCLICK = wx.adv.wxEVT_TASKBAR_RIGHT_DCLICK |
| 140 |
|
| 141 |
wx.EVT_TASKBAR_BALLOON_CLICK = wx.adv.EVT_TASKBAR_BALLOON_CLICK |
| 142 |
wx.EVT_TASKBAR_BALLOON_TIMEOUT = wx.adv.EVT_TASKBAR_BALLOON_TIMEOUT |
| 143 |
wx.EVT_TASKBAR_CLICK = wx.adv.EVT_TASKBAR_CLICK |
| 144 |
wx.EVT_TASKBAR_LEFT_DCLICK = wx.adv.EVT_TASKBAR_LEFT_DCLICK |
| 145 |
wx.EVT_TASKBAR_LEFT_DOWN = wx.adv.EVT_TASKBAR_LEFT_DOWN |
| 146 |
wx.EVT_TASKBAR_LEFT_UP = wx.adv.EVT_TASKBAR_LEFT_UP |
| 147 |
wx.EVT_TASKBAR_MOVE = wx.adv.EVT_TASKBAR_MOVE |
| 148 |
wx.EVT_TASKBAR_RIGHT_DOWN = wx.adv.EVT_TASKBAR_RIGHT_DOWN |
| 149 |
wx.EVT_TASKBAR_RIGHT_UP = wx.adv.EVT_TASKBAR_RIGHT_UP |
| 150 |
wx.EVT_TASKBAR_RIGHT_DCLICK = wx.adv.EVT_TASKBAR_RIGHT_DCLICK |
| 151 |
|
| 152 |
# Removed items |
| 153 |
wx.IconBundle.AddIconFromFile = lambda file, type_=wx.BITMAP_TYPE_ANY: ( |
| 154 |
wx.IconBundle.AddIcon(file, type_) |
| 155 |
) |
| 156 |
|
| 157 |
def ContainsRect(self, *args): |
| 158 |
"""Check if the rectangle is contained in this rectangle.""" |
| 159 |
rect = wx.Rect(*args) if len(args) > 1 else args[0] |
| 160 |
return self.Contains(rect) |
| 161 |
|
| 162 |
wx.Rect.ContainsRect = ContainsRect |
| 163 |
wx.Rect.ContainsXY = lambda self, x, y: self.Contains((x, y)) |
| 164 |
wx.RectPS = wx.Rect |
| 165 |
wx.RegionFromBitmap = wx.Region |
| 166 |
|
| 167 |
def GetItemIndex(self, window): |
| 168 |
"""Return the index of the item in the sizer.""" |
| 169 |
for index, sizeritem in enumerate(self.Children): |
| 170 |
if sizeritem.Window == window: |
| 171 |
return index |
| 172 |
return None |
| 173 |
|
| 174 |
wx.Sizer.GetItemIndex = GetItemIndex |
| 175 |
wx.TopLevelWindow.Restore = lambda self: self.Iconize(False) |
| 176 |
|
| 177 |
# Renamed items |
| 178 |
|
| 179 |
wx.OPEN = wx.FD_OPEN |
| 180 |
wx.OVERWRITE_PROMPT = wx.FD_OVERWRITE_PROMPT |
| 181 |
wx.SAVE = wx.FD_SAVE |
| 182 |
|
| 183 |
wx.SystemSettings_GetColour = wx.SystemSettings.GetColour |
| 184 |
wx.SystemSettings_GetFont = wx.SystemSettings.GetFont |
| 185 |
wx.SystemSettings_GetMetric = wx.SystemSettings.GetMetric |
| 186 |
wx.grid.EVT_GRID_CELL_CHANGE = wx.grid.EVT_GRID_CELL_CHANGED |
| 187 |
if hasattr(wx.grid.Grid, "GridSelectRows"): |
| 188 |
# wxPython Phoenix 4.0.0a |
| 189 |
wx.grid.Grid.wxGridSelectRows = wx.grid.Grid.GridSelectRows |
| 190 |
else: |
| 191 |
# wxPython Phoenix 4.0.0b |
| 192 |
wx.grid.Grid.wxGridSelectRows = wx.grid.Grid.SelectRows |
| 193 |
wx.grid.PyGridCellEditor = wx.grid.GridCellEditor |
| 194 |
wx.grid.PyGridCellRenderer = wx.grid.GridCellRenderer |
| 195 |
wx.RegionFromBitmapColour = wx.Region |
| 196 |
|
| 197 |
# Bugfixes |
| 198 |
|
| 199 |
if not hasattr(wx.grid.GridEvent, "CmdDown"): |
| 200 |
# This may be a bug in the current development version of Phoenix |
| 201 |
wx.grid.GridEvent.CmdDown = lambda self: False |
| 202 |
|
| 203 |
# Not sure if this is a bug, but the PositionToXY signature differs from |
| 204 |
# current Phoenix docs. Actual return value is a 3-tuple, not a 2-tuple: |
| 205 |
# (bool inrange, int col, int line) |
| 206 |
PositionToXY = wx.TextCtrl.PositionToXY |
| 207 |
wx.TextCtrl.PositionToXY = lambda self, pos: PositionToXY(self, pos)[1:] |
| 208 |
|
| 209 |
def TabFrame__init__(self, parent): # noqa: D417 |
| 210 |
"""Fix TabFrame.__init__ to not set the size to 0, 0. |
| 211 |
|
| 212 |
Args: |
| 213 |
parent (wx.Window): The parent window for the TabFrame. |
| 214 |
""" |
| 215 |
wx.Window.__init__(self) |
| 216 |
|
| 217 |
self._tabs = None |
| 218 |
self._rect = wx.Rect(0, 0, 200, 200) |
| 219 |
self._tab_ctrl_height = 20 |
| 220 |
self._tab_rect = wx.Rect() |
| 221 |
self._parent = parent |
| 222 |
|
| 223 |
# With Phoenix, the TabFrame is unintentionally visible in the top left |
| 224 |
# corner (horizontal and vertical lines with a length of 20px each that |
| 225 |
# are lighter than the border color if tabs are at the top, or a |
| 226 |
# 20x20px square if tabs are at the bottom). Setting its size to 0, 0 |
| 227 |
# prevents this. Also see https://github.com/RobinD42/Phoenix/pull/91 |
| 228 |
self.Create(parent, size=(0, 0)) |
| 229 |
|
| 230 |
aui.TabFrame.__init__ = TabFrame__init__ |
| 231 |
|
| 232 |
|
| 233 |
wx._ListCtrl = wx.ListCtrl |
| 234 |
wx._SpinCtrl = wx.SpinCtrl |
| 235 |
wx._StaticText = wx.StaticText |
| 236 |
if "gtk3" in wx.PlatformInfo: |
| 237 |
# GTK3 fixes |
| 238 |
|
| 239 |
class wx_Panel(wx.Panel): # noqa: N801 |
| 240 |
"""Fix panel background color not working under wxGTK3.""" |
| 241 |
|
| 242 |
def __init__(self, *args, **kwargs): |
| 243 |
if not args and hasattr(wx, "PreFrame"): |
| 244 |
pre = wx.PrePanel() |
| 245 |
self.PostCreate(pre) |
| 246 |
self.Bind(wx.EVT_WINDOW_CREATE, self.OnCreate) |
| 247 |
else: |
| 248 |
wx.Panel.__init__(self, *args, **kwargs) |
| 249 |
self.OnCreate(None) |
| 250 |
|
| 251 |
def OnCreate(self, event): |
| 252 |
"""Handle the window creation event to bind the erase background event. |
| 253 |
|
| 254 |
Args: |
| 255 |
event (wx.Event): The window creation event. |
| 256 |
""" |
| 257 |
self.Unbind(wx.EVT_WINDOW_CREATE) |
| 258 |
self.Bind(wx.EVT_ERASE_BACKGROUND, self.OnEraseBackground) |
| 259 |
|
| 260 |
def OnEraseBackground(self, event): |
| 261 |
"""Handle the erase background event to prevent flickering. |
| 262 |
|
| 263 |
Args: |
| 264 |
event (wx.Event): The erase background event. |
| 265 |
""" |
| 266 |
dc = event.GetDC() |
| 267 |
rect = self.GetClientRect() |
| 268 |
dc.SetClippingRegion(rect.x, rect.y, rect.width, rect.height) |
| 269 |
bgcolor = self.BackgroundColour |
| 270 |
dc.SetBrush(wx.Brush(bgcolor, wx.BRUSHSTYLE_SOLID)) |
| 271 |
dc.SetPen(wx.Pen(bgcolor, wx.PENSTYLE_SOLID)) |
| 272 |
dc.DrawRectangle(*rect) |
| 273 |
|
| 274 |
from wx import dataview |
| 275 |
|
| 276 |
DataViewListCtrl = dataview.DataViewListCtrl |
| 277 |
|
| 278 |
class ListCtrl(DataViewListCtrl): |
| 279 |
"""Compatibility class for wx.ListCtrl. |
| 280 |
|
| 281 |
Implements ListCtrl as DataViewListCtrl. Works around header rendering |
| 282 |
ugliness with GTK3. |
| 283 |
|
| 284 |
Args: |
| 285 |
parent (wx.Window): The parent window. |
| 286 |
id (int): The identifier for the control. |
| 287 |
pos (wx.Point): The position of the control. |
| 288 |
size (wx.Size): The size of the control. |
| 289 |
style (int): The style of the control. |
| 290 |
validator (wx.Validator): The validator for the control. |
| 291 |
name (str): The name of the control. |
| 292 |
""" |
| 293 |
|
| 294 |
def __init__( |
| 295 |
self, |
| 296 |
parent, |
| 297 |
id=wx.ID_ANY, # noqa: A002 |
| 298 |
pos=wx.DefaultPosition, |
| 299 |
size=wx.DefaultSize, |
| 300 |
style=wx.LC_ICON, |
| 301 |
validator=wx.DefaultValidator, |
| 302 |
name=wx.ListCtrlNameStr, |
| 303 |
): |
| 304 |
dv_style = 0 |
| 305 |
if style & wx.LC_SINGLE_SEL: |
| 306 |
dv_style |= dataview.DV_SINGLE |
| 307 |
DataViewListCtrl.__init__(self, parent, id, pos, size, dv_style, validator) |
| 308 |
self.Name = name |
| 309 |
self._columns = {} |
| 310 |
self._items = {} |
| 311 |
self.Bind(dataview.EVT_DATAVIEW_SELECTION_CHANGED, self.OnEvent) |
| 312 |
self.Bind(dataview.EVT_DATAVIEW_ITEM_ACTIVATED, self.OnEvent) |
| 313 |
|
| 314 |
def OnEvent(self, event): |
| 315 |
"""Handle DataViewListCtrl events and convert them to ListCtrl events. |
| 316 |
|
| 317 |
Args: |
| 318 |
event (wx.Event): The event to handle. |
| 319 |
""" |
| 320 |
typeId = event.GetEventType() |
| 321 |
if typeId == dataview.EVT_DATAVIEW_SELECTION_CHANGED.typeId: |
| 322 |
if self.GetSelectedRow() != wx.NOT_FOUND: |
| 323 |
typeId = wx.EVT_LIST_ITEM_SELECTED.typeId |
| 324 |
else: |
| 325 |
typeId = wx.EVT_LIST_ITEM_DESELECTED.typeId |
| 326 |
event = wx.ListEvent(typeId, self.Id) |
| 327 |
elif typeId == dataview.EVT_DATAVIEW_ITEM_ACTIVATED.typeId: |
| 328 |
event = wx.ListEvent(wx.EVT_LIST_ITEM_ACTIVATED.typeId, self.Id) |
| 329 |
event.SetEventObject(self) |
| 330 |
self.GetEventHandler().ProcessEvent(event) |
| 331 |
|
| 332 |
def InsertColumn(self, pos, col): |
| 333 |
"""Insert a column at the specified position. |
| 334 |
|
| 335 |
Args: |
| 336 |
pos (int): The position to insert the column at. |
| 337 |
col (wx.DataViewColumn): The column to insert. |
| 338 |
""" |
| 339 |
self._columns[pos] = col |
| 340 |
|
| 341 |
def SetColumnWidth(self, pos, width): |
| 342 |
"""Set the width of the column at the specified position. |
| 343 |
|
| 344 |
Args: |
| 345 |
pos (int): The position of the column. |
| 346 |
width (int): The width to set for the column. |
| 347 |
""" |
| 348 |
self.AppendTextColumn(self._columns[pos], width=int(width)) |
| 349 |
|
| 350 |
def InsertStringItem(self, row, label): |
| 351 |
"""Insert a string item at the specified row. |
| 352 |
|
| 353 |
Args: |
| 354 |
row (int): The row to insert the item at. |
| 355 |
label (str): The label of the item. |
| 356 |
|
| 357 |
Returns: |
| 358 |
int: The row index where the item was inserted. |
| 359 |
""" |
| 360 |
self._items[row] = [] |
| 361 |
return row |
| 362 |
|
| 363 |
def SetStringItem(self, row, col, label): |
| 364 |
"""Set the string item at the specified row and column. |
| 365 |
|
| 366 |
Args: |
| 367 |
row (int): The row of the item. |
| 368 |
col (int): The column of the item. |
| 369 |
label (str): The label to set for the item. |
| 370 |
""" |
| 371 |
self._items[row].append(label) |
| 372 |
if len(self._items[row]) == len(self._columns): |
| 373 |
# Row complete |
| 374 |
DataViewListCtrl.InsertItem(self, row, self._items[row]) |
| 375 |
|
| 376 |
def GetItem(self, row, col=0): |
| 377 |
"""Return the item at the specified row and column. |
| 378 |
|
| 379 |
Args: |
| 380 |
row (int): The row of the item. |
| 381 |
col (int): The column of the item (default is 0). |
| 382 |
|
| 383 |
Returns: |
| 384 |
wx.DataViewItem: The item at the specified row and column. |
| 385 |
""" |
| 386 |
item = self.RowToItem(row) |
| 387 |
item.GetId = lambda: row |
| 388 |
item.GetText = lambda: self.GetTextValue(row, col) |
| 389 |
return item |
| 390 |
|
| 391 |
def SetItemState(self, row, state, stateMask): |
| 392 |
"""Set the state of the item. |
| 393 |
|
| 394 |
Args: |
| 395 |
row (int): The row to set the state for. |
| 396 |
state (int): The state to set. |
| 397 |
stateMask (int): The state mask to apply. |
| 398 |
|
| 399 |
Raises: |
| 400 |
NotImplementedError: If the state is not wx.LIST_STATE_SELECTED. |
| 401 |
""" |
| 402 |
if state == stateMask == wx.LIST_STATE_SELECTED: |
| 403 |
self.SelectRow(row) |
| 404 |
else: |
| 405 |
raise NotImplementedError( |
| 406 |
"SetItemState is only implemented for selecting a single row" |
| 407 |
) |
| 408 |
|
| 409 |
def GetNextItem( |
| 410 |
self, row, geometry=wx.LIST_NEXT_ALL, state=wx.LIST_STATE_DONTCARE |
| 411 |
): |
| 412 |
"""Return the next item in the list. |
| 413 |
|
| 414 |
Args: |
| 415 |
row (int): The row to start from. |
| 416 |
geometry (int): The geometry of the item to return. |
| 417 |
state (int): The state of the item to return. |
| 418 |
|
| 419 |
Returns: |
| 420 |
int: The next item in the list, or -1 if no item is found. |
| 421 |
""" |
| 422 |
if ( |
| 423 |
row == -1 |
| 424 |
and geometry == wx.LIST_NEXT_ALL |
| 425 |
and state == wx.LIST_STATE_SELECTED |
| 426 |
): |
| 427 |
return self.GetSelectedRow() |
| 428 |
raise NotImplementedError( |
| 429 |
"GetNextItem is only implemented for returning the selected row" |
| 430 |
) |
| 431 |
|
| 432 |
def GetItemCount(self): |
| 433 |
"""Return the number of items in the list. |
| 434 |
|
| 435 |
Returns: |
| 436 |
int: The number of items in the list. |
| 437 |
""" |
| 438 |
return len(self._items) |
| 439 |
|
| 440 |
GetFirstSelected = DataViewListCtrl.__dict__["GetSelectedRow"] |
| 441 |
|
| 442 |
def GetItemState(self, row, stateMask): |
| 443 |
"""Return the state of the item. |
| 444 |
|
| 445 |
Args: |
| 446 |
row (int): The row to check. |
| 447 |
stateMask (int): The state mask to check against. |
| 448 |
""" |
| 449 |
if stateMask == wx.LIST_STATE_SELECTED: |
| 450 |
if self.GetSelectedRow() == row: |
| 451 |
return wx.LIST_STATE_SELECTED |
| 452 |
return 0 |
| 453 |
raise NotImplementedError( |
| 454 |
"GetItemState is only implemented to check if a row is selected" |
| 455 |
) |
| 456 |
|
| 457 |
def Select(self, row, on=1): |
| 458 |
"""Select or unselect a row. |
| 459 |
|
| 460 |
Args: |
| 461 |
row (int): The row to select or unselect. |
| 462 |
on (bool): Whether to select (True) or unselect (False) the row. |
| 463 |
""" |
| 464 |
if on: |
| 465 |
self.SelectRow(row) |
| 466 |
else: |
| 467 |
self.UnselectRow(row) |
| 468 |
|
| 469 |
wx.ListCtrl = ListCtrl |
| 470 |
|
| 471 |
class SpinCtrl(wx._SpinCtrl): |
| 472 |
"""Compatibility class for wx.SpinCtrl. |
| 473 |
|
| 474 |
Args: |
| 475 |
parent (wx.Window): The parent window. |
| 476 |
id (int): The identifier for the control. |
| 477 |
value (str): The initial value of the spin control. |
| 478 |
pos (wx.Point): The position of the control. |
| 479 |
size (wx.Size): The size of the control. |
| 480 |
style (int): The style of the control. |
| 481 |
min (int): The minimum value of the spin control. |
| 482 |
max (int): The maximum value of the spin control. |
| 483 |
initial (int): The initial value to set. |
| 484 |
name (str): The name of the control. |
| 485 |
""" |
| 486 |
|
| 487 |
_spinwidth = 0 |
| 488 |
|
| 489 |
def __init__( |
| 490 |
self, |
| 491 |
parent, |
| 492 |
id=wx.ID_ANY, # noqa: A002 |
| 493 |
value="", |
| 494 |
pos=wx.DefaultPosition, |
| 495 |
size=wx.DefaultSize, |
| 496 |
style=wx.SP_ARROW_KEYS, |
| 497 |
min=0, # noqa: A002 |
| 498 |
max=100, # noqa: A002 |
| 499 |
initial=0, |
| 500 |
name="wxSpinCtrl", |
| 501 |
): |
| 502 |
if size[0] != -1: |
| 503 |
# Adjust initial size for GTK3 to accommodate spin buttons |
| 504 |
if not SpinCtrl._spinwidth: |
| 505 |
spin = wx.SpinCtrl(parent, -1) |
| 506 |
text = wx.TextCtrl(parent, -1) |
| 507 |
SpinCtrl._spinwidth = spin.Size[0] - text.Size[0] + 11 |
| 508 |
spin.Destroy() |
| 509 |
text.Destroy() |
| 510 |
size = size[0] + SpinCtrl._spinwidth, size[1] |
| 511 |
wx._SpinCtrl.__init__( |
| 512 |
self, parent, id, value, pos, size, style, min, max, initial, name |
| 513 |
) |
| 514 |
|
| 515 |
wx.SpinCtrl = SpinCtrl |
| 516 |
|
| 517 |
_StaticText_SetLabel = wx._StaticText.SetLabel |
| 518 |
|
| 519 |
class StaticText(wx._StaticText): |
| 520 |
"""Compatibility class for wx.StaticText.""" |
| 521 |
|
| 522 |
def __init__(self, *args, **kwargs): |
| 523 |
wx._StaticText.__init__(self, *args, **kwargs) |
| 524 |
|
| 525 |
def SetFont(self, font): |
| 526 |
"""Set the font of the static text. |
| 527 |
|
| 528 |
Args: |
| 529 |
font (wx.Font): The font to set. |
| 530 |
""" |
| 531 |
wx.Control.SetFont(self, font) |
| 532 |
self.SetLabel(self.Label) |
| 533 |
|
| 534 |
def SetLabel(self, label): |
| 535 |
"""Set the label of the static text. |
| 536 |
|
| 537 |
Args: |
| 538 |
label (str): The label to set. |
| 539 |
""" |
| 540 |
# Fix GTK3 label auto-resize on label change not working |
| 541 |
if not self.WindowStyle & wx.ST_NO_AUTORESIZE: |
| 542 |
self.MaxSize = -1, -1 |
| 543 |
self.MinSize = -1, -1 |
| 544 |
_StaticText_SetLabel(self, label) |
| 545 |
if not self.WindowStyle & wx.ST_NO_AUTORESIZE: |
| 546 |
# Find widest line |
| 547 |
max_width = 0 |
| 548 |
for line in label.splitlines(): |
| 549 |
width = self.GetTextExtent(line)[0] |
| 550 |
max_width = max(max_width, width) |
| 551 |
self.Size = max_width, -1 |
| 552 |
self.MaxSize = self.Size[0], -1 |
| 553 |
|
| 554 |
def Wrap(self, width): |
| 555 |
"""Wrap the text to the specified width. |
| 556 |
|
| 557 |
Args: |
| 558 |
width (int): The width to wrap the text to. |
| 559 |
""" |
| 560 |
wx._StaticText.Wrap(self, int(width)) |
| 561 |
self.SetLabel(self.Label) |
| 562 |
|
| 563 |
Label = property(lambda self: self.GetLabel(), SetLabel) |
| 564 |
|
| 565 |
wx.StaticText = StaticText |
| 566 |
else: |
| 567 |
|
| 568 |
class wx_Panel(wx.Panel): # noqa: N801 |
| 569 |
"""Compatibility class.""" |
| 570 |
|
| 571 |
def __init__(self, *args, **kwargs): |
| 572 |
wx.Panel.__init__(self, *args, **kwargs) |
| 573 |
|
| 574 |
|
| 575 |
wx.AnyButton._SetBitmapLabel = wx.AnyButton.SetBitmapLabel |
| 576 |
|
| 577 |
|
| 578 |
def SetBitmapLabel(self, bitmap): |
| 579 |
"""Override the SetBitmapLabel to avoid flickering.""" |
| 580 |
if self.GetBitmapLabel() != bitmap: |
| 581 |
self._SetBitmapLabel(bitmap) |
| 582 |
|
| 583 |
|
| 584 |
wx.AnyButton.SetBitmapLabel = SetBitmapLabel |
| 585 |
|
| 586 |
|
| 587 |
def BitmapButtonEnable(self, enable=True): |
| 588 |
"""Replacement for BitmapButton.Enable which circumvents repainting issues. |
| 589 |
|
| 590 |
(bitmap does not change on button state change) |
| 591 |
|
| 592 |
""" |
| 593 |
wx.Button.Enable(self, enable) |
| 594 |
if not hasattr(self, "_bitmaplabel"): |
| 595 |
self._bitmaplabel = self.GetBitmapLabel() |
| 596 |
if not hasattr(self, "_bitmapdisabled"): |
| 597 |
self._bitmapdisabled = self.GetBitmapDisabled() |
| 598 |
if enable: |
| 599 |
if self._bitmaplabel.IsOk(): |
| 600 |
self.SetBitmapLabel(self._bitmaplabel) |
| 601 |
elif self._bitmapdisabled.IsOk(): |
| 602 |
self.SetBitmapLabel(self._bitmapdisabled) |
| 603 |
|
| 604 |
|
| 605 |
def BitmapButtonDisable(self): |
| 606 |
"""Replacement for BitmapButton.Disable which circumvents repainting issues. |
| 607 |
|
| 608 |
(bitmap does not change on button state change) |
| 609 |
""" |
| 610 |
self.Enable(False) |
| 611 |
|
| 612 |
|
| 613 |
if "phoenix" not in wx.PlatformInfo: |
| 614 |
wx.BitmapButton.Enable = BitmapButtonEnable |
| 615 |
wx.BitmapButton.Disable = BitmapButtonDisable |
| 616 |
|
| 617 |
|
| 618 |
def FindMenuItem(self, label): |
| 619 |
"""Replacement for wx.Menu.FindItem.""" |
| 620 |
label = GTKMenuItemGetFixedLabel(label) |
| 621 |
for menuitem in self.GetMenuItems(): |
| 622 |
try: |
| 623 |
fixed_label = GTKMenuItemGetFixedLabel(menuitem.Label) |
| 624 |
except AttributeError: |
| 625 |
# wxPython 4.1.0+ |
| 626 |
fixed_label = GTKMenuItemGetFixedLabel(menuitem.GetItemLabelText()) |
| 627 |
if fixed_label == label: |
| 628 |
return menuitem.GetId() |
| 629 |
return None |
| 630 |
|
| 631 |
|
| 632 |
wx.Menu.FindItem = FindMenuItem |
| 633 |
|
| 634 |
|
| 635 |
def GTKMenuItemGetFixedLabel(label): |
| 636 |
"""Return the fixed label for GTK menu items.""" |
| 637 |
if sys.platform not in ("darwin", "win32"): |
| 638 |
# The underscore is a special character under GTK, like the |
| 639 |
# ampersand on Mac OS X and Windows |
| 640 |
# Recent wxPython versions already do the right thing, but we need |
| 641 |
# this workaround for older releases |
| 642 |
if "__" in label: |
| 643 |
label = label.replace("__", "_") |
| 644 |
while label and label[0] == "_": |
| 645 |
label = label[1:] |
| 646 |
return label |
| 647 |
|
| 648 |
|
| 649 |
if not hasattr(wx.Sizer, "GetItemIndex"): |
| 650 |
|
| 651 |
def GetItemIndex(self, item): |
| 652 |
"""Return the index of the item in the sizer.""" |
| 653 |
for i, child in enumerate(list(self.GetChildren())): |
| 654 |
if child.GetWindow() is item: |
| 655 |
return i |
| 656 |
return -1 |
| 657 |
|
| 658 |
wx.Sizer.GetItemIndex = GetItemIndex |
| 659 |
|
| 660 |
|
| 661 |
def set_maxsize(window, maxsize): |
| 662 |
"""Set the maximum size of a window.""" |
| 663 |
window.MaxSize = maxsize |
| 664 |
|
| 665 |
|
| 666 |
if os.getenv("XDG_SESSION_TYPE") == "wayland": |
| 667 |
# Fix erroneous extra spacing around window contents under Wayland |
| 668 |
|
| 669 |
is_first_toplevel_window = True |
| 670 |
|
| 671 |
def fix_wayland_window_size(window): |
| 672 |
"""Fix erroneous extra spacing around window contents under Wayland.""" |
| 673 |
global is_first_toplevel_window |
| 674 |
if is_first_toplevel_window: |
| 675 |
# Not needed for first toplevel window |
| 676 |
is_first_toplevel_window = False |
| 677 |
else: |
| 678 |
window.MaxSize = window.Size |
| 679 |
wx.CallAfter(set_maxsize, window, (-1, -1)) |
| 680 |
|
| 681 |
def TopLevelWindow_Show(self, show=True): |
| 682 |
"""Replacement for TopLevelWindow.Show which circumvents repainting issues.""" |
| 683 |
if show and not self.IsShown(): |
| 684 |
fix_wayland_window_size(self) |
| 685 |
return _TopLevelWindow_Show(self, show) |
| 686 |
|
| 687 |
_TopLevelWindow_Show = wx.TopLevelWindow.Show |
| 688 |
wx.TopLevelWindow.Show = TopLevelWindow_Show |
| 689 |
|
| 690 |
# ~ def Dialog_ShowModal(self): |
| 691 |
# ~ fix_wayland_window_size(self) |
| 692 |
# ~ return _Dialog_ShowModal(self) |
| 693 |
|
| 694 |
# ~ _Dialog_ShowModal = wx.Dialog.ShowModal |
| 695 |
# ~ wx.Dialog.ShowModal = Dialog_ShowModal |
| 696 |
|
| 697 |
def Sizer_SetSizeHints(self, window): |
| 698 |
"""Replacement for Sizer.SetSizeHints which circumvents repainting issues.""" |
| 699 |
if isinstance(window, wx.Dialog): |
| 700 |
window.MaxSize = (-1, -1) |
| 701 |
_Sizer_SetSizeHints(self, window) |
| 702 |
|
| 703 |
_Sizer_SetSizeHints = wx.Sizer.SetSizeHints |
| 704 |
wx.Sizer.SetSizeHints = Sizer_SetSizeHints |
| 705 |
|
| 706 |
def Sizer_Layout(self): |
| 707 |
"""Replacement for Sizer.Layout which circumvents repainting issues.""" |
| 708 |
_Sizer_Layout(self) |
| 709 |
window = self.GetContainingWindow() |
| 710 |
if isinstance(window, wx.Dialog): |
| 711 |
window.MaxSize = window.Size |
| 712 |
|
| 713 |
_Sizer_Layout = wx.Sizer.Layout |
| 714 |
wx.Sizer.Layout = Sizer_Layout |
| 715 |
|
| 716 |
|
| 717 |
if sys.platform == "darwin": |
| 718 |
# wxMac seem to lose the foreground color of StaticText |
| 719 |
# when enabled again |
| 720 |
|
| 721 |
@property |
| 722 |
def StaticTextEnabled(self): |
| 723 |
"""Replacement for StaticText.Enabled which circumvents repainting issues.""" |
| 724 |
return self.IsEnabled() |
| 725 |
|
| 726 |
@StaticTextEnabled.setter |
| 727 |
def StaticTextEnabled(self, enable=True): |
| 728 |
"""Replacement for StaticText.Enabled which circumvents repainting issues.""" |
| 729 |
self.Enable(enable) |
| 730 |
|
| 731 |
wx.StaticText.Enabled = StaticTextEnabled |
| 732 |
|
| 733 |
def StaticTextDisable(self): |
| 734 |
"""Replacement for StaticText.Disable which circumvents repainting issues.""" |
| 735 |
self.Enable(False) |
| 736 |
|
| 737 |
wx.StaticText.Disable = StaticTextDisable |
| 738 |
|
| 739 |
def StaticTextEnable(self, enable=True): |
| 740 |
"""Replacement for StaticText.Enable which circumvents repainting issues.""" |
| 741 |
enable = bool(enable) |
| 742 |
if self.Enabled is enable: |
| 743 |
return |
| 744 |
self._enabled = enable |
| 745 |
if not hasattr(self, "_fgcolor"): |
| 746 |
self._fgcolor = self.ForegroundColour |
| 747 |
color = self._fgcolor |
| 748 |
if not enable: |
| 749 |
bgcolor = self.Parent.BackgroundColour |
| 750 |
bgblend = 0.5 |
| 751 |
blend = 0.5 |
| 752 |
color = wx.Colour( |
| 753 |
round(bgblend * bgcolor.Red() + blend * color.Red()), |
| 754 |
round(bgblend * bgcolor.Green() + blend * color.Green()), |
| 755 |
round(bgblend * bgcolor.Blue() + blend * color.Blue()), |
| 756 |
) |
| 757 |
self.ForegroundColour = color |
| 758 |
|
| 759 |
wx.StaticText.Enable = StaticTextEnable |
| 760 |
|
| 761 |
def StaticTextIsEnabled(self) -> bool: |
| 762 |
"""Return whether the StaticText is enabled.""" |
| 763 |
return getattr(self, "_enabled", True) |
| 764 |
|
| 765 |
wx.StaticText.IsEnabled = StaticTextIsEnabled |
| 766 |
|
| 767 |
|
| 768 |
wx.Window._SetToolTipString = wx.Window.SetToolTipString |
| 769 |
|
| 770 |
|
| 771 |
def SetToolTipString(self, string): |
| 772 |
"""Replacement for SetToolTipString which updates correctly.""" |
| 773 |
wx.Window.SetToolTip(self, None) |
| 774 |
wx.Window._SetToolTipString(self, string) |
| 775 |
|
| 776 |
|
| 777 |
wx.Window.SetToolTipString = SetToolTipString |
| 778 |
|
| 779 |
|
| 780 |
def _adjust_sizer_args_scaling_for_appdpi(*args, **kwargs): |
| 781 |
from DisplayCAL.config import get_default_dpi, getcfg |
| 782 |
|
| 783 |
scale = getcfg("app.dpi") / get_default_dpi() |
| 784 |
if "border" in kwargs: |
| 785 |
kwargs["border"] = int(kwargs["border"]) |
| 786 |
|
| 787 |
if scale > 1: |
| 788 |
args = list(args) |
| 789 |
if kwargs.get("border"): |
| 790 |
kwargs["border"] = round(kwargs["border"] * scale) |
| 791 |
elif "border" not in kwargs: |
| 792 |
if ( |
| 793 |
isinstance(args[0], (tuple, wx.Size, wx.Sizer, wx.Window)) |
| 794 |
and len(args) > 3 |
| 795 |
and args[3] |
| 796 |
): |
| 797 |
# item, proportion, flag, border, ... |
| 798 |
args[3] = round(args[3] * scale) |
| 799 |
elif isinstance(args[0], int) and len(args) > 4 and args[4]: |
| 800 |
# width, height, proportion, flag, border, ... |
| 801 |
args[4] = round(args[4] * scale) |
| 802 |
if args and isinstance(args[0], (tuple, wx.Size)): |
| 803 |
spacer = list(args[0]) |
| 804 |
# print(spacer, '->') |
| 805 |
for i, dimension in enumerate(spacer): |
| 806 |
if dimension > 0: |
| 807 |
spacer[i] = round(dimension * scale) |
| 808 |
# print(spacer) |
| 809 |
args = [tuple(spacer)] + args[1:] |
| 810 |
return args, kwargs |
| 811 |
|
| 812 |
|
| 813 |
wx._Sizer = wx.Sizer |
| 814 |
|
| 815 |
|
| 816 |
class Sizer(wx._Sizer): |
| 817 |
"""wx.Sizer replacement that scales spacing for current DPI.""" |
| 818 |
|
| 819 |
def Add(self, *args, **kwargs): |
| 820 |
"""Add an item to the sizer. |
| 821 |
|
| 822 |
Returns: |
| 823 |
wx.SizerItem: The item added to the sizer. |
| 824 |
""" |
| 825 |
args, kwargs = _adjust_sizer_args_scaling_for_appdpi(*args, **kwargs) |
| 826 |
return wx._Sizer.Add(self, *args, **kwargs) |
| 827 |
|
| 828 |
def Insert(self, index, *args, **kwargs): |
| 829 |
"""Insert an item at the specified index in the sizer. |
| 830 |
|
| 831 |
Args: |
| 832 |
index (int): The index at which to insert the item. |
| 833 |
*args: Positional arguments for the item to insert. |
| 834 |
**kwargs: Keyword arguments for the item to insert. |
| 835 |
""" |
| 836 |
args, kwargs = _adjust_sizer_args_scaling_for_appdpi(*args, **kwargs) |
| 837 |
return wx._Sizer.Insert(self, index, *args, **kwargs) |
| 838 |
|
| 839 |
|
| 840 |
wx.Sizer = Sizer |
| 841 |
|
| 842 |
|
| 843 |
wx._BoxSizer = wx.BoxSizer |
| 844 |
|
| 845 |
|
| 846 |
class BoxSizer(wx._BoxSizer): |
| 847 |
"""BoxSizer with DPI scaling.""" |
| 848 |
|
| 849 |
Add = Sizer.__dict__["Add"] |
| 850 |
Insert = Sizer.__dict__["Insert"] |
| 851 |
|
| 852 |
|
| 853 |
wx.BoxSizer = BoxSizer |
| 854 |
|
| 855 |
|
| 856 |
wx._GridSizer = wx.GridSizer |
| 857 |
|
| 858 |
|
| 859 |
class GridSizer(wx._GridSizer): |
| 860 |
"""GridSizer with DPI scaling.""" |
| 861 |
|
| 862 |
def __init__(self, rows=0, cols=0, vgap=0, hgap=0): |
| 863 |
if vgap or hgap: |
| 864 |
from DisplayCAL.config import get_default_dpi, getcfg |
| 865 |
|
| 866 |
scale = getcfg("app.dpi") / get_default_dpi() |
| 867 |
if scale > 1: |
| 868 |
# print(vgap, hgap, '->') |
| 869 |
vgap, hgap = [round(v * scale) for v in (vgap, hgap)] |
| 870 |
# print(vgap, hgap) |
| 871 |
super().__init__(rows, cols, vgap, hgap) |
| 872 |
|
| 873 |
Add = Sizer.__dict__["Add"] |
| 874 |
Insert = Sizer.__dict__["Insert"] |
| 875 |
|
| 876 |
|
| 877 |
wx.GridSizer = GridSizer |
| 878 |
|
| 879 |
|
| 880 |
wx._FlexGridSizer = wx.FlexGridSizer |
| 881 |
|
| 882 |
|
| 883 |
class FlexGridSizer(wx._FlexGridSizer): |
| 884 |
"""FlexGridSizer with DPI scaling.""" |
| 885 |
|
| 886 |
def __init__(self, rows=0, cols=0, vgap=0, hgap=0): |
| 887 |
if vgap or hgap: |
| 888 |
from DisplayCAL.config import get_default_dpi, getcfg |
| 889 |
|
| 890 |
scale = getcfg("app.dpi") / get_default_dpi() |
| 891 |
if scale > 1: |
| 892 |
# print vgap, hgap, '->', |
| 893 |
vgap, hgap = [round(v * scale) for v in (vgap, hgap)] |
| 894 |
# print vgap, hgap |
| 895 |
super().__init__(rows, cols, vgap, hgap) |
| 896 |
|
| 897 |
Add = Sizer.__dict__["Add"] |
| 898 |
Insert = Sizer.__dict__["Insert"] |
| 899 |
|
| 900 |
|
| 901 |
wx.FlexGridSizer = FlexGridSizer |
| 902 |
|
| 903 |
|
| 904 |
def GridGetSelection(self): |
| 905 |
"""Return selected rows, cols, block and cells.""" |
| 906 |
sel = [] |
| 907 |
numrows = self.GetNumberRows() |
| 908 |
numcols = self.GetNumberCols() |
| 909 |
# rows |
| 910 |
rows = self.GetSelectedRows() |
| 911 |
sel.extend((row, i) for row in rows for i in range(numcols)) |
| 912 |
# cols |
| 913 |
cols = self.GetSelectedCols() |
| 914 |
sel.extend((i, col) for col in cols for i in range(numrows)) |
| 915 |
# block |
| 916 |
tl = self.GetSelectionBlockTopLeft() |
| 917 |
br = self.GetSelectionBlockBottomRight() |
| 918 |
if tl and br: |
| 919 |
sel.extend( |
| 920 |
(i, j) |
| 921 |
for n in range(min(len(tl), len(br))) |
| 922 |
for i in range(tl[n][0], br[n][0] + 1) # rows |
| 923 |
for j in range(tl[n][1], br[n][1] + 1) # cols |
| 924 |
) |
| 925 |
# single selected cells |
| 926 |
sel.extend(self.GetSelectedCells()) |
| 927 |
# TODO: I don't remember why I disabled the next line and added the for loop instead |
| 928 |
# sel = list(set(sel)) |
| 929 |
new_sel = [] |
| 930 |
for item in sel: |
| 931 |
if item not in new_sel: |
| 932 |
new_sel.append(item) |
| 933 |
sel = new_sel |
| 934 |
|
| 935 |
sel.sort() |
| 936 |
return sel |
| 937 |
|
| 938 |
|
| 939 |
wx.grid.Grid.GetSelection = GridGetSelection |
| 940 |
|
| 941 |
|
| 942 |
def adjust_font_size_for_gcdc(font): |
| 943 |
"""Adjust font size for GCDC.""" |
| 944 |
size = get_gcdc_font_size(font.PointSize) |
| 945 |
font.SetPointSize(int(size)) |
| 946 |
return font |
| 947 |
|
| 948 |
|
| 949 |
def get_dc_font_scale(dc): |
| 950 |
"""Get correct font scaling factor for DC.""" |
| 951 |
pointsize = (1.0, 1.0) |
| 952 |
if isinstance(dc, wx.GCDC): |
| 953 |
pointsize = tuple(1.0 / scale for scale in dc.GetLogicalScale()) |
| 954 |
if sys.platform in ("darwin", "win32") or ( |
| 955 |
not isinstance(dc, wx.GCDC) and "gtk3" not in wx.PlatformInfo |
| 956 |
): |
| 957 |
return sum(pointsize) / 2.0 |
| 958 |
# On Linux, we need to correct the font size by a certain factor if |
| 959 |
# wx.GCDC is used, to make text the same size as if wx.GCDC weren't used |
| 960 |
from DisplayCAL.config import get_default_dpi, getcfg, set_default_app_dpi |
| 961 |
|
| 962 |
set_default_app_dpi() |
| 963 |
scale = getcfg("app.dpi") / get_default_dpi() |
| 964 |
if wx.VERSION < (2, 9): |
| 965 |
# On Linux, we need to correct the font size by a certain factor if |
| 966 |
# wx.GCDC is used, to make text the same size as if wx.GCDC weren't used |
| 967 |
screenppi = list(map(float, wx.ScreenDC().GetPPI())) |
| 968 |
ppi = dc.GetPPI() |
| 969 |
scale *= (screenppi[0] / ppi[0] + screenppi[1] / ppi[1]) / 2.0 |
| 970 |
return (scale * pointsize[0] + scale * pointsize[1]) / 2.0 |
| 971 |
|
| 972 |
|
| 973 |
def get_dc_font_size(size, dc): |
| 974 |
"""Get correct font size for DC.""" |
| 975 |
return int(size * get_dc_font_scale(dc)) |
| 976 |
|
| 977 |
|
| 978 |
def get_gcdc_font_size(size): |
| 979 |
"""Get correct font size for GCDC.""" |
| 980 |
dc = wx.MemoryDC(wx.EmptyBitmap(1, 1)) |
| 981 |
with contextlib.suppress(Exception): |
| 982 |
dc = wx.GCDC(dc) |
| 983 |
return get_dc_font_size(size, dc) |
| 984 |
|
| 985 |
|
| 986 |
def get_bitmap_disabled(bitmap): |
| 987 |
"""Get the disabled bitmap.""" |
| 988 |
# Use Rec. 709 luma coefficients to convert to grayscale |
| 989 |
image = bitmap.ConvertToImage().ConvertToGreyscale(0.2126, 0.7152, 0.0722) |
| 990 |
if image.HasMask() and not image.HasAlpha(): |
| 991 |
image.InitAlpha() |
| 992 |
if image.HasAlpha(): |
| 993 |
alphabuffer = image.GetAlphaBuffer() |
| 994 |
for i, byte in enumerate(alphabuffer): |
| 995 |
if byte > 0: |
| 996 |
alphabuffer[i] = round(byte * 0.3) |
| 997 |
return image.ConvertToBitmap() |
| 998 |
|
| 999 |
|
| 1000 |
def get_bitmap_hover(bitmap, ctrl=None): |
| 1001 |
"""Get the hover bitmap.""" |
| 1002 |
image = bitmap.ConvertToImage() |
| 1003 |
if image.HasMask() and not image.HasAlpha(): |
| 1004 |
image.InitAlpha() |
| 1005 |
if sys.platform == "darwin": |
| 1006 |
color = [44, 93, 205] # Use Mavericks-like color scheme |
| 1007 |
else: |
| 1008 |
color = list(wx.SystemSettings.GetColour(wx.SYS_COLOUR_HIGHLIGHT)[:3]) |
| 1009 |
R = color[0] / 255.0 |
| 1010 |
G = color[1] / 255.0 |
| 1011 |
B = color[2] / 255.0 |
| 1012 |
# Assume Rec. 709 gamma 2.2 to determine rel. luminance |
| 1013 |
lum = 0.2126 * R**2.2 + 0.7152 * G**2.2 + 0.0722 * B**2.2 |
| 1014 |
is_bw = image.IsBW() |
| 1015 |
if ctrl: |
| 1016 |
bgcolor = ctrl.Parent.BackgroundColour |
| 1017 |
if is_bw: |
| 1018 |
# Adjust hilight color by background color if luminance difference |
| 1019 |
# is below threshhold |
| 1020 |
R = bgcolor[0] / 255.0 |
| 1021 |
G = bgcolor[1] / 255.0 |
| 1022 |
B = bgcolor[2] / 255.0 |
| 1023 |
# Assume Rec. 709 gamma 2.2 to determine rel. luminance |
| 1024 |
bglum = 0.2126 * R**2.2 + 0.7152 * G**2.2 + 0.0722 * B**2.2 |
| 1025 |
lumdiff = (max(lum, bglum) - min(lum, bglum)) ** (1 / 2.2) |
| 1026 |
if lumdiff < 1.0 / 3.0: |
| 1027 |
if lum > bglum: |
| 1028 |
newmin = bglum ** (1 / 2.2) * 255 |
| 1029 |
newmax = 255 |
| 1030 |
else: |
| 1031 |
newmin = 0 |
| 1032 |
newmax = bglum ** (1 / 2.2) * 153 # 60% |
| 1033 |
for i, v in enumerate(color): |
| 1034 |
color[i] = round(convert_range(v, 0, 255, newmin, newmax)) |
| 1035 |
databuffer = image.GetDataBuffer() |
| 1036 |
alphabuffer = image.GetAlphaBuffer() |
| 1037 |
minv = 256 # Intentionally above max possible value |
| 1038 |
j = 0 |
| 1039 |
RGB = {} |
| 1040 |
for i, byte in enumerate(databuffer): |
| 1041 |
RGB[i % 3] = byte |
| 1042 |
if i % 3 == 2: |
| 1043 |
RGBv = list(RGB.values()) |
| 1044 |
if not is_bw: |
| 1045 |
RGBv_max = max(RGBv) |
| 1046 |
if minv == 256 and alphabuffer[j] > 32: |
| 1047 |
# If a pixel is at least 12.5% opaque, check if it's value |
| 1048 |
# is less than or equal the previously seen minimum pixel |
| 1049 |
# value as a crude means to determine if the graphic |
| 1050 |
# contains a black outline. |
| 1051 |
minv = min(RGBv_max, minv) |
| 1052 |
|
| 1053 |
for k in range(3): |
| 1054 |
if is_bw: |
| 1055 |
v = color[k] |
| 1056 |
else: |
| 1057 |
v = RGB[k] |
| 1058 |
if minv > 0 and min(RGBv) != RGBv_max: |
| 1059 |
# If the minimum seen at least 12.5% opaque pixel value |
| 1060 |
# is above zero, assume a graphic without black outline |
| 1061 |
# and adjust intensity by applying a power. The hilight |
| 1062 |
# color isn't used. |
| 1063 |
v = (v / 255.0) ** 0.8 * 255 |
| 1064 |
else: |
| 1065 |
# If the minimum seen at least 12.5% opaque pixel value |
| 1066 |
# is zero, adjust value by hilight color value, so that |
| 1067 |
# graphics with a black outline get the hilight color |
| 1068 |
# at black. |
| 1069 |
v = convert_range(v, 0, 255, color[k], 255) |
| 1070 |
v = round(v) |
| 1071 |
databuffer[i - 2 + k] = v |
| 1072 |
j += 1 |
| 1073 |
if isinstance(ctrl, wx.BitmapButton) and sys.platform == "win32": |
| 1074 |
# wx.BitmapButton draws the focus bitmap over the normal bitmap, |
| 1075 |
# leading to ugly aliased edges. Yuck. Prevent this by setting the |
| 1076 |
# background to the control's background color instead of transparent. |
| 1077 |
bmp = wx.EmptyBitmap(image.Width, image.Height) |
| 1078 |
dc = wx.MemoryDC() |
| 1079 |
dc.SelectObject(bmp) |
| 1080 |
dc.SetBrush(wx.Brush(bgcolor)) |
| 1081 |
dc.SetPen(wx.Pen(bgcolor, width=0)) |
| 1082 |
dc.DrawRectangle(0, 0, image.Width, image.Height) |
| 1083 |
dc.DrawBitmap(image.ConvertToBitmap(), 0, 0, True) |
| 1084 |
dc.SelectObject(wx.NullBitmap) |
| 1085 |
else: |
| 1086 |
bmp = image.ConvertToBitmap() |
| 1087 |
return bmp |
| 1088 |
|
| 1089 |
|
| 1090 |
def get_bitmap_pressed(bitmap): |
| 1091 |
"""Get the pressed bitmap.""" |
| 1092 |
image = bitmap.ConvertToImage() |
| 1093 |
if image.HasMask() and not image.HasAlpha(): |
| 1094 |
image.InitAlpha() |
| 1095 |
databuffer = image.GetDataBuffer() |
| 1096 |
for i, byte in enumerate(databuffer): |
| 1097 |
if byte > 0: |
| 1098 |
databuffer[i] = round(byte * 0.85) |
| 1099 |
return image.ConvertToBitmap() |
| 1100 |
|
| 1101 |
|
| 1102 |
def get_bitmap_focus(bitmap): |
| 1103 |
"""Get the focus bitmap.""" |
| 1104 |
image = bitmap.ConvertToImage() |
| 1105 |
if image.HasMask() and not image.HasAlpha(): |
| 1106 |
image.InitAlpha() |
| 1107 |
databuffer = image.GetDataBuffer() |
| 1108 |
for i, byte in enumerate(databuffer): |
| 1109 |
if byte > 0: |
| 1110 |
databuffer[i] = round((byte / 255.0) ** 0.8 * 255) |
| 1111 |
return image.ConvertToBitmap() |
| 1112 |
|
| 1113 |
|
| 1114 |
def set_bitmap_labels(btn, disabled=True, focus=None, pressed=True): |
| 1115 |
"""Set the bitmap labels for a button.""" |
| 1116 |
bitmap = btn.BitmapLabel |
| 1117 |
if not bitmap.IsOk(): |
| 1118 |
size = btn.MinSize |
| 1119 |
if -1 in size: |
| 1120 |
size = (16, 16) |
| 1121 |
bitmap = wx.ArtProvider.GetBitmap(wx.ART_MISSING_IMAGE, size=size) |
| 1122 |
# Ensure the normal bitmap is set first, fixes #507 |
| 1123 |
btn.SetBitmapLabel(bitmap) |
| 1124 |
|
| 1125 |
# Disabled |
| 1126 |
if disabled: |
| 1127 |
disabled_bitmap = get_bitmap_disabled(bitmap) |
| 1128 |
with contextlib.suppress(wx._core.wxAssertionError): |
| 1129 |
btn.SetBitmapDisabled(disabled_bitmap) |
| 1130 |
|
| 1131 |
# Focus/Hover |
| 1132 |
if sys.platform != "darwin" and focus is not False: |
| 1133 |
# wxMac applies hover state also to disabled buttons... |
| 1134 |
if focus is None: |
| 1135 |
# Use hover bitmap |
| 1136 |
bmp = get_bitmap_hover(bitmap, btn) |
| 1137 |
else: |
| 1138 |
# Use focus bitmap |
| 1139 |
bmp = get_bitmap_focus(bitmap) |
| 1140 |
with contextlib.suppress(wx._core.wxAssertionError): |
| 1141 |
btn.SetBitmapFocus(bmp) |
| 1142 |
if hasattr(btn, "SetBitmapCurrent"): |
| 1143 |
# Phoenix |
| 1144 |
with contextlib.suppress(wx._core.wxAssertionError): |
| 1145 |
btn.SetBitmapCurrent(bmp) |
| 1146 |
else: |
| 1147 |
# Classic |
| 1148 |
btn.SetBitmapHover(bmp) |
| 1149 |
|
| 1150 |
# Selected |
| 1151 |
if pressed: |
| 1152 |
if sys.platform == "darwin": |
| 1153 |
bmp = get_bitmap_hover(bitmap, btn) |
| 1154 |
elif focus is False: |
| 1155 |
bmp = get_bitmap_pressed(bitmap) |
| 1156 |
if hasattr(btn, "SetBitmapPressed"): |
| 1157 |
# Phoenix |
| 1158 |
with contextlib.suppress(wx._core.wxAssertionError): |
| 1159 |
btn.SetBitmapPressed(bmp) |
| 1160 |
else: |
| 1161 |
# Classic |
| 1162 |
btn.SetBitmapSelected(bmp) |
| 1163 |
|
| 1164 |
|
| 1165 |
def get_dialogs(modal=False): |
| 1166 |
"""If there are any dialogs open, return them.""" |
| 1167 |
return [ |
| 1168 |
window |
| 1169 |
for window in list(wx.GetTopLevelWindows()) |
| 1170 |
if window |
| 1171 |
and isinstance(window, wx.Dialog) |
| 1172 |
and window.IsShown() |
| 1173 |
and (not modal or window.IsModal()) |
| 1174 |
] |
| 1175 |
|
| 1176 |
|
| 1177 |
# wx.DirDialog and wx.FileDialog are normally not returned by |
| 1178 |
# wx.GetTopLevelWindows, do some trickery to work around |
| 1179 |
|
| 1180 |
_DirDialog = wx.DirDialog |
| 1181 |
_FileDialog = wx.FileDialog |
| 1182 |
|
| 1183 |
|
| 1184 |
class PathDialogBase(wx.Dialog): |
| 1185 |
"""Base class for wx.DirDialog and wx.FileDialog. |
| 1186 |
|
| 1187 |
Args: |
| 1188 |
parent (wx.Window): The parent window. |
| 1189 |
name (str): The name of the dialog. |
| 1190 |
""" |
| 1191 |
|
| 1192 |
def __init__(self, parent, name): |
| 1193 |
wx.Dialog.__init__(self, parent, -1, name=name) |
| 1194 |
self._ismodal = False |
| 1195 |
self._isshown = False |
| 1196 |
self.Bind(wx.EVT_WINDOW_DESTROY, self.OnDestroy) |
| 1197 |
|
| 1198 |
def __getattr__(self, name) -> Any: |
| 1199 |
"""Get the attribute from the file dialog. |
| 1200 |
|
| 1201 |
Args: |
| 1202 |
name (str): The name of the attribute to get. |
| 1203 |
|
| 1204 |
Returns: |
| 1205 |
Any: The value of the attribute.s |
| 1206 |
""" |
| 1207 |
return getattr(self.filedialog, name) |
| 1208 |
|
| 1209 |
def IsModal(self): |
| 1210 |
"""Check if the dialog is modal. |
| 1211 |
|
| 1212 |
Returns: |
| 1213 |
bool: True if the dialog is modal, False otherwise. |
| 1214 |
""" |
| 1215 |
return self._ismodal |
| 1216 |
|
| 1217 |
def IsShown(self): |
| 1218 |
"""Check if the dialog is shown. |
| 1219 |
|
| 1220 |
Returns: |
| 1221 |
bool: True if the dialog is shown, False otherwise. |
| 1222 |
""" |
| 1223 |
return self._isshown |
| 1224 |
|
| 1225 |
def OnDestroy(self, event): |
| 1226 |
"""Handle the dialog destruction event. |
| 1227 |
|
| 1228 |
Args: |
| 1229 |
event (wx.WindowDestroyEvent): The window destroy event. |
| 1230 |
""" |
| 1231 |
self.filedialog.Destroy() |
| 1232 |
event.Skip() |
| 1233 |
return 0 |
| 1234 |
|
| 1235 |
def Show(self, show=True): |
| 1236 |
"""Show or hide the dialog. |
| 1237 |
|
| 1238 |
Args: |
| 1239 |
show (bool): Whether to show or hide the dialog. |
| 1240 |
""" |
| 1241 |
self._isshown = show |
| 1242 |
self.filedialog.Show(show) |
| 1243 |
|
| 1244 |
def ShowModal(self): |
| 1245 |
"""Show the dialog modally. |
| 1246 |
|
| 1247 |
Returns: |
| 1248 |
int: The return code of the dialog. |
| 1249 |
""" |
| 1250 |
self._isshown = True |
| 1251 |
self._ismodal = True |
| 1252 |
returncode = self.filedialog.ShowModal() |
| 1253 |
self._ismodal = False |
| 1254 |
self._isshown = False |
| 1255 |
return returncode |
| 1256 |
|
| 1257 |
|
| 1258 |
class DirDialog(PathDialogBase): |
| 1259 |
"""Directory dialog that works around wxGTK3 issues with file dialogs.""" |
| 1260 |
|
| 1261 |
def __init__(self, *args, **kwargs): |
| 1262 |
PathDialogBase.__init__(self, args[0], name="dirdialog") |
| 1263 |
self.filedialog = _DirDialog(*args, **kwargs) |
| 1264 |
|
| 1265 |
|
| 1266 |
class FileDialog(PathDialogBase): |
| 1267 |
"""File dialog that works around wxGTK3 issues with file dialogs.""" |
| 1268 |
|
| 1269 |
def __init__(self, *args, **kwargs): |
| 1270 |
PathDialogBase.__init__(self, args[0], name="filedialog") |
| 1271 |
self.filedialog = _FileDialog(*args, **kwargs) |
| 1272 |
|
| 1273 |
|
| 1274 |
wx.DirDialog = DirDialog |
| 1275 |
wx.FileDialog = FileDialog |
| 1276 |
|
| 1277 |
|
| 1278 |
wx._ScrolledWindow = wx.ScrolledWindow |
| 1279 |
|
| 1280 |
|
| 1281 |
class ScrolledWindow(wx._ScrolledWindow): |
| 1282 |
"""ScrolledWindow that scrolls child controls into view on focus. |
| 1283 |
|
| 1284 |
OnChildFocus and ScrollChildIntoView borrowed from wx.lib.scrolledpanel. |
| 1285 |
""" |
| 1286 |
|
| 1287 |
def __init__(self, *args, **kwargs): |
| 1288 |
wx._ScrolledWindow.__init__(self, *args, **kwargs) |
| 1289 |
self.Bind(wx.EVT_CHILD_FOCUS, self.OnChildFocus) |
| 1290 |
|
| 1291 |
def OnChildFocus(self, evt): |
| 1292 |
"""Handle child focus events. |
| 1293 |
|
| 1294 |
Args: |
| 1295 |
evt (wx.ChildFocusEvent): The child focus event. |
| 1296 |
""" |
| 1297 |
# If the child window that gets the focus is not visible, |
| 1298 |
# this handler will try to scroll enough to see it. |
| 1299 |
evt.Skip() |
| 1300 |
child = evt.GetWindow() |
| 1301 |
self.ScrollChildIntoView(child) |
| 1302 |
|
| 1303 |
def ScrollChildIntoView(self, child): |
| 1304 |
"""Scroll the panel such that the specified child window is in view.""" |
| 1305 |
sppu_x, sppu_y = self.GetScrollPixelsPerUnit() |
| 1306 |
vs_x, vs_y = self.GetViewStart() |
| 1307 |
cr = child.GetRect() |
| 1308 |
clntsz = self.GetClientSize() |
| 1309 |
new_vs_x, new_vs_y = -1, -1 |
| 1310 |
|
| 1311 |
# is it before the left edge? |
| 1312 |
if cr.x < 0 < sppu_x: |
| 1313 |
new_vs_x = vs_x + (cr.x / sppu_x) |
| 1314 |
|
| 1315 |
# is it above the top? |
| 1316 |
if cr.y < 0 < sppu_y: |
| 1317 |
new_vs_y = vs_y + (cr.y / sppu_y) |
| 1318 |
|
| 1319 |
# For the right and bottom edges, scroll enough to show the |
| 1320 |
# whole control if possible, but if not just scroll such that |
| 1321 |
# the top/left edges are still visible |
| 1322 |
|
| 1323 |
# is it past the right edge ? |
| 1324 |
if cr.right > clntsz.width and sppu_x > 0: |
| 1325 |
diff = (cr.right - clntsz.width) / sppu_x |
| 1326 |
if cr.x - diff * sppu_x > 0: |
| 1327 |
new_vs_x = vs_x + diff + 1 |
| 1328 |
else: |
| 1329 |
new_vs_x = vs_x + (cr.x / sppu_x) |
| 1330 |
|
| 1331 |
# is it below the bottom ? |
| 1332 |
if cr.bottom > clntsz.height and sppu_y > 0: |
| 1333 |
diff = (cr.bottom - clntsz.height) / sppu_y |
| 1334 |
if cr.y - diff * sppu_y > 0: |
| 1335 |
new_vs_y = vs_y + diff + 1 |
| 1336 |
else: |
| 1337 |
new_vs_y = vs_y + (cr.y / sppu_y) |
| 1338 |
|
| 1339 |
# if we need to adjust |
| 1340 |
if new_vs_x != -1 or new_vs_y != -1: |
| 1341 |
# print "%s: (%s, %s)" % (self.GetName(), new_vs_x, new_vs_y) |
| 1342 |
self.Scroll(int(new_vs_x), int(new_vs_y)) |
| 1343 |
|
| 1344 |
|
| 1345 |
wx.ScrolledWindow = ScrolledWindow |
| 1346 |
ScrolledPanel.ScrollChildIntoView = ScrolledWindow.ScrollChildIntoView |
| 1347 |
|
| 1348 |
|
| 1349 |
class GenButton: |
| 1350 |
"""A generic button, based on wx.lib.buttons.GenButton. |
| 1351 |
|
| 1352 |
Fixes wx.lib.buttons.ThemedGenButton not taking into account backgroun |
| 1353 |
color when pressed. |
| 1354 |
""" |
| 1355 |
|
| 1356 |
def __init__(self): |
| 1357 |
self.bezelWidth = 2 |
| 1358 |
self.hasFocus = False |
| 1359 |
self.up = True |
| 1360 |
self.useFocusInd = True |
| 1361 |
|
| 1362 |
def OnPaint(self, event): |
| 1363 |
"""Handle the paint event for the button. |
| 1364 |
|
| 1365 |
Args: |
| 1366 |
event (wx.PaintEvent): The paint event. |
| 1367 |
""" |
| 1368 |
(width, height) = self.ClientSize |
| 1369 |
x1 = y1 = 0 |
| 1370 |
x2 = width |
| 1371 |
y2 = height |
| 1372 |
|
| 1373 |
dc = wx.PaintDC(self) |
| 1374 |
brush = self.GetBackgroundBrush(dc) |
| 1375 |
if brush is not None: |
| 1376 |
brush.SetColour(self.Parent.BackgroundColour) |
| 1377 |
dc.SetBackground(brush) |
| 1378 |
dc.Clear() |
| 1379 |
|
| 1380 |
self.DrawBezel(dc, x1, y1, x2, y2) |
| 1381 |
self.DrawLabel(dc, width, height) |
| 1382 |
if self.hasFocus and self.useFocusInd: |
| 1383 |
self.DrawFocusIndicator(dc, width, height) |
| 1384 |
|
| 1385 |
|
| 1386 |
if "gtk3" not in wx.PlatformInfo: |
| 1387 |
# GTK3 doesn't respect NO_BORDER in hovered state when using wx.BitmapButton |
| 1388 |
_GenBitmapButton = wx.BitmapButton |
| 1389 |
|
| 1390 |
|
| 1391 |
class GenBitmapButton(GenButton, _GenBitmapButton): |
| 1392 |
"""A generic bitmap button, based on wx.lib.buttons.GenBitmapButton.""" |
| 1393 |
|
| 1394 |
def __init__(self, *args, **kwargs): |
| 1395 |
GenButton.__init__(self) |
| 1396 |
_GenBitmapButton.__init__(self, *args, **kwargs) |
| 1397 |
self.hover = False |
| 1398 |
set_bitmap_labels(self) |
| 1399 |
if _GenBitmapButton is not wx.BitmapButton: |
| 1400 |
self.Bind(wx.EVT_ENTER_WINDOW, self.OnMouseEnter) |
| 1401 |
self.Bind(wx.EVT_LEAVE_WINDOW, self.OnMouseLeave) |
| 1402 |
|
| 1403 |
@property |
| 1404 |
def BitmapFocus(self): |
| 1405 |
"""Get the bitmap used when the button has focus. |
| 1406 |
|
| 1407 |
Returns: |
| 1408 |
wx.Bitmap: The bitmap used for the focus state. |
| 1409 |
""" |
| 1410 |
return self.GetBitmapFocus() |
| 1411 |
|
| 1412 |
@BitmapFocus.setter |
| 1413 |
def BitmapFocus(self, bitmap): |
| 1414 |
"""Set the bitmap to use when the button has focus. |
| 1415 |
|
| 1416 |
Args: |
| 1417 |
bitmap (wx.Bitmap): The bitmap to set for the focus state. |
| 1418 |
""" |
| 1419 |
self.SetBitmapFocus(bitmap) |
| 1420 |
|
| 1421 |
@property |
| 1422 |
def BitmapDisabled(self): |
| 1423 |
"""Get the bitmap used when the button is disabled. |
| 1424 |
|
| 1425 |
Returns: |
| 1426 |
wx.Bitmap: The bitmap used for the disabled state. |
| 1427 |
""" |
| 1428 |
return self.GetBitmapDisabled() |
| 1429 |
|
| 1430 |
@BitmapDisabled.setter |
| 1431 |
def BitmapDisabled(self, bitmap): |
| 1432 |
"""Set the bitmap to use when the button is disabled. |
| 1433 |
|
| 1434 |
Args: |
| 1435 |
bitmap (wx.Bitmap): The bitmap to set for the disabled state. |
| 1436 |
""" |
| 1437 |
self.SetBitmapDisabled(bitmap) |
| 1438 |
|
| 1439 |
@property |
| 1440 |
def BitmapHover(self): |
| 1441 |
"""Get the bitmap used when the button is hovered. |
| 1442 |
|
| 1443 |
Returns: |
| 1444 |
wx.Bitmap: The bitmap used for the hover state. |
| 1445 |
""" |
| 1446 |
return self.GetBitmapHover() |
| 1447 |
|
| 1448 |
@BitmapHover.setter |
| 1449 |
def BitmapHover(self, bitmap): |
| 1450 |
"""Set the bitmap to use when the button is hovered. |
| 1451 |
|
| 1452 |
Args: |
| 1453 |
bitmap (wx.Bitmap): The bitmap to set for the hover state. |
| 1454 |
""" |
| 1455 |
self.SetBitmapHover(bitmap) |
| 1456 |
|
| 1457 |
@property |
| 1458 |
def BitmapSelected(self): |
| 1459 |
"""Get the bitmap used when the button is selected. |
| 1460 |
|
| 1461 |
Returns: |
| 1462 |
wx.Bitmap: The bitmap used for the selected state. |
| 1463 |
""" |
| 1464 |
return self.GetBitmapSelected() |
| 1465 |
|
| 1466 |
@BitmapSelected.setter |
| 1467 |
def BitmapSelected(self, bitmap): |
| 1468 |
"""Set the bitmap to use when the button is selected. |
| 1469 |
|
| 1470 |
Args: |
| 1471 |
bitmap (wx.Bitmap): The bitmap to set for the selected state. |
| 1472 |
""" |
| 1473 |
self.SetBitmapSelected(bitmap) |
| 1474 |
|
| 1475 |
@property |
| 1476 |
def BitmapLabel(self): |
| 1477 |
"""Get the bitmap label for the button. |
| 1478 |
|
| 1479 |
Returns: |
| 1480 |
wx.Bitmap: The bitmap label of the button. |
| 1481 |
""" |
| 1482 |
return self.GetBitmapLabel() |
| 1483 |
|
| 1484 |
@BitmapLabel.setter |
| 1485 |
def BitmapLabel(self, bitmap): |
| 1486 |
"""Set the bitmap label for the button. |
| 1487 |
|
| 1488 |
Args: |
| 1489 |
bitmap (wx.Bitmap): The bitmap to set as the label. |
| 1490 |
""" |
| 1491 |
self.SetBitmapLabel(bitmap) |
| 1492 |
|
| 1493 |
def DrawLabel(self, dc, width, height, dx=0, dy=0): |
| 1494 |
"""Draw the bitmap label in the button. |
| 1495 |
|
| 1496 |
Args: |
| 1497 |
dc (wx.DC): The device context to draw on. |
| 1498 |
width (int): The width of the button. |
| 1499 |
height (int): The height of the button. |
| 1500 |
dx (int, optional): Horizontal offset for the bitmap. Defaults to 0. |
| 1501 |
dy (int, optional): Vertical offset for the bitmap. Defaults to 0. |
| 1502 |
""" |
| 1503 |
bmp = self.BitmapLabel |
| 1504 |
if self.BitmapDisabled and not self.IsEnabled(): |
| 1505 |
bmp = self.BitmapDisabled |
| 1506 |
elif self.BitmapSelected and not self.up: |
| 1507 |
bmp = self.BitmapSelected |
| 1508 |
elif self.BitmapHover and self.hover: |
| 1509 |
bmp = self.BitmapHover |
| 1510 |
elif self.BitmapFocus and self.hasFocus: |
| 1511 |
bmp = self.BitmapFocus |
| 1512 |
bw, bh = bmp.GetWidth(), bmp.GetHeight() |
| 1513 |
hasMask = bmp.GetMask() is not None |
| 1514 |
dc.DrawBitmap( |
| 1515 |
bmp, int((width - bw) / 2 + dx), int((height - bh) / 2 + dy), hasMask |
| 1516 |
) |
| 1517 |
|
| 1518 |
def GetBitmapHover(self): |
| 1519 |
"""Get the bitmap used when the button is hovered.""" |
| 1520 |
return self.bmpHover |
| 1521 |
|
| 1522 |
def OnMouseEnter(self, event): |
| 1523 |
"""Handle the mouse enter event. |
| 1524 |
|
| 1525 |
Args: |
| 1526 |
event (wx.MouseEvent): The mouse event. |
| 1527 |
""" |
| 1528 |
if not self.IsEnabled(): |
| 1529 |
return |
| 1530 |
if not self.hover: |
| 1531 |
self.hover = True |
| 1532 |
self.Refresh() |
| 1533 |
event.Skip() |
| 1534 |
|
| 1535 |
def OnMouseLeave(self, event): |
| 1536 |
"""Handle the mouse leave event. |
| 1537 |
|
| 1538 |
Args: |
| 1539 |
event (wx.MouseEvent): The mouse event. |
| 1540 |
""" |
| 1541 |
if not self.IsEnabled(): |
| 1542 |
return |
| 1543 |
if self.hover: |
| 1544 |
self.hover = False |
| 1545 |
self.Refresh() |
| 1546 |
event.Skip() |
| 1547 |
|
| 1548 |
def SetBitmapHover(self, bitmap): |
| 1549 |
"""Set the bitmap to use when the button is hovered. |
| 1550 |
|
| 1551 |
Args: |
| 1552 |
bitmap (wx.Bitmap): The bitmap to set for the hover state. |
| 1553 |
""" |
| 1554 |
self.bmpHover = bitmap |
| 1555 |
|
| 1556 |
|
| 1557 |
class ThemedGenButton(GenButton, _ThemedGenButton): |
| 1558 |
"""A themed generic button, based on wx.lib.buttons.ThemedGenButton. |
| 1559 |
|
| 1560 |
Fixes wx.lib.buttons.ThemedGenButton sometimes not reflecting enabled |
| 1561 |
state correctly as well as not taking into account background color when |
| 1562 |
pressed, and mimics a default button under Windows more closely by |
| 1563 |
not drawing a focus outline and not shifting the label when pressed. |
| 1564 |
|
| 1565 |
Also implements state for SetDefault. |
| 1566 |
""" |
| 1567 |
|
| 1568 |
_really_enabled = True |
| 1569 |
label_delta = 1 |
| 1570 |
|
| 1571 |
def __init__(self, *args, **kwargs): |
| 1572 |
GenButton.__init__(self) |
| 1573 |
_ThemedGenButton.__init__(self, *args, **kwargs) |
| 1574 |
self._default = False |
| 1575 |
|
| 1576 |
def Disable(self): |
| 1577 |
"""Disable the button.""" |
| 1578 |
self.Enable(False) |
| 1579 |
|
| 1580 |
def DoGetBestSize(self): |
| 1581 |
"""Determine the best size of the button based on the label and bezel size. |
| 1582 |
|
| 1583 |
Returns: |
| 1584 |
tuple: The width and height of the button. |
| 1585 |
""" |
| 1586 |
w, h, useMin = self._GetLabelSize() |
| 1587 |
if self.style & wx.BU_EXACTFIT: |
| 1588 |
width = w + 2 + 2 * self.bezelWidth + 4 * int(self.useFocusInd) |
| 1589 |
height = h + 2 + 2 * self.bezelWidth + 4 * int(self.useFocusInd) |
| 1590 |
else: |
| 1591 |
defSize = wx.Button.GetDefaultSize() |
| 1592 |
width = 12 + w |
| 1593 |
if useMin and width < defSize.width: |
| 1594 |
width = defSize.width |
| 1595 |
height = 11 + h |
| 1596 |
if useMin and height < defSize.height: |
| 1597 |
height = defSize.height |
| 1598 |
width = width + self.bezelWidth - 2 |
| 1599 |
height = height + self.bezelWidth - 2 |
| 1600 |
return (width, height) |
| 1601 |
|
| 1602 |
def DrawBezel(self, dc, x1, y1, x2, y2): |
| 1603 |
"""Draw the bezel around the button. |
| 1604 |
|
| 1605 |
Args: |
| 1606 |
dc (wx.DC): The device context to draw on. |
| 1607 |
x1 (int): The x-coordinate of the top-left corner. |
| 1608 |
y1 (int): The y-coordinate of the top-left corner. |
| 1609 |
x2 (int): The x-coordinate of the bottom-right corner. |
| 1610 |
y2 (int): The y-coordinate of the bottom-right corner. |
| 1611 |
""" |
| 1612 |
rect = wx.Rect(x1, y1, x2, y2) |
| 1613 |
state = 0 if self.up else (wx.CONTROL_PRESSED | wx.CONTROL_SELECTED) |
| 1614 |
if not self.IsEnabled(): |
| 1615 |
state = wx.CONTROL_DISABLED |
| 1616 |
elif self._default: |
| 1617 |
state |= wx.CONTROL_ISDEFAULT |
| 1618 |
pt = self.ScreenToClient(wx.GetMousePosition()) |
| 1619 |
if self.GetClientRect().Contains(pt): |
| 1620 |
state |= wx.CONTROL_CURRENT |
| 1621 |
wx.RendererNative.Get().DrawPushButton(self, dc, rect, state) |
| 1622 |
|
| 1623 |
def DrawLabel(self, dc, width, height, dx=0, dy=0): |
| 1624 |
"""Draw the label text in the button. |
| 1625 |
|
| 1626 |
Args: |
| 1627 |
dc (wx.DC): The device context to draw on. |
| 1628 |
width (int): The width of the button. |
| 1629 |
height (int): The height of the button. |
| 1630 |
dx (int, optional): Horizontal offset for the label. Defaults to 0. |
| 1631 |
dy (int, optional): Vertical offset for the label. Defaults to 0. |
| 1632 |
""" |
| 1633 |
dc.SetFont(self.GetFont()) |
| 1634 |
if self.Enabled: |
| 1635 |
dc.SetTextForeground(self.ForegroundColour) |
| 1636 |
else: |
| 1637 |
dc.SetTextForeground(wx.SystemSettings.GetColour(wx.SYS_COLOUR_GRAYTEXT)) |
| 1638 |
label = self.Label |
| 1639 |
tw, th = dc.GetTextExtent(label) |
| 1640 |
if sys.platform != "win32" and not self.up: |
| 1641 |
dx = dy = self.label_delta |
| 1642 |
dc.DrawText(label, int((width - tw) / 2) + dx, int((height - th) / 2) + dy) |
| 1643 |
|
| 1644 |
def Enable(self, enable=True): |
| 1645 |
"""Enable or disable the button. |
| 1646 |
|
| 1647 |
Args: |
| 1648 |
enable (bool): True to enable the button, False to disable it. |
| 1649 |
""" |
| 1650 |
if enable == self.Enabled: |
| 1651 |
return |
| 1652 |
self.Enabled = enable |
| 1653 |
wx.PyControl.Enable(self, enable) |
| 1654 |
self.Refresh() |
| 1655 |
|
| 1656 |
@property |
| 1657 |
def Enabled(self): |
| 1658 |
"""Get the enabled state of the button. |
| 1659 |
|
| 1660 |
Returns: |
| 1661 |
bool: True if the button is enabled, False otherwise. |
| 1662 |
""" |
| 1663 |
return self._really_enabled |
| 1664 |
|
| 1665 |
@Enabled.setter |
| 1666 |
def Enabled(self, enabled): |
| 1667 |
"""Set the enabled state of the button.""" |
| 1668 |
self._really_enabled = enabled |
| 1669 |
|
| 1670 |
def IsEnabled(self): |
| 1671 |
"""Check if the button is enabled. |
| 1672 |
|
| 1673 |
Returns: |
| 1674 |
bool: True if the button is enabled, False otherwise. |
| 1675 |
""" |
| 1676 |
return self.Enabled |
| 1677 |
|
| 1678 |
def OnLeftDown(self, event): |
| 1679 |
"""Handle the left mouse button down event. |
| 1680 |
|
| 1681 |
Args: |
| 1682 |
event (wx.MouseEvent): The mouse event. |
| 1683 |
""" |
| 1684 |
if not self.Enabled: |
| 1685 |
return |
| 1686 |
self.up = False |
| 1687 |
self.CaptureMouse() |
| 1688 |
self.SetFocus() |
| 1689 |
self.useFocusInd = False |
| 1690 |
self.Refresh() |
| 1691 |
event.Skip() |
| 1692 |
|
| 1693 |
def OnGainFocus(self, event): |
| 1694 |
"""Handle the focus gain event. |
| 1695 |
|
| 1696 |
Args: |
| 1697 |
event (wx.FocusEvent): The focus event. |
| 1698 |
""" |
| 1699 |
self.hasFocus = True |
| 1700 |
self.useFocusInd = bool(self.bezelWidth) |
| 1701 |
self.Refresh() |
| 1702 |
self.Update() |
| 1703 |
|
| 1704 |
def SetDefault(self): |
| 1705 |
"""Set the button as default button.""" |
| 1706 |
self._default = True |
| 1707 |
_ThemedGenButton.SetDefault(self) |
| 1708 |
|
| 1709 |
|
| 1710 |
class PlateButton(platebtn.PlateButton): |
| 1711 |
"""Fixes PlateButton enabled state and related issues.""" |
| 1712 |
|
| 1713 |
_really_enabled = True |
| 1714 |
|
| 1715 |
def __init__(self, *args, **kwargs): |
| 1716 |
from DisplayCAL.config import get_default_dpi, getcfg |
| 1717 |
|
| 1718 |
self.dpiscale = getcfg("app.dpi") / get_default_dpi() |
| 1719 |
platebtn.PlateButton.__init__(self, *args, **kwargs) |
| 1720 |
self._bmp["hilite"] = None |
| 1721 |
if sys.platform == "darwin": |
| 1722 |
# Use Sierra-like color scheme |
| 1723 |
from DisplayCAL.wx_addons import gamma_encode |
| 1724 |
|
| 1725 |
color = wx.Colour(*gamma_encode(0, 105, 217)) |
| 1726 |
else: |
| 1727 |
color = wx.SystemSettings.GetColour(wx.SYS_COLOUR_HIGHLIGHT) |
| 1728 |
self._color["hlight"] = color |
| 1729 |
self.Unbind(wx.EVT_LEAVE_WINDOW) |
| 1730 |
self.Bind(wx.EVT_LEAVE_WINDOW, lambda evt: wx.CallLater(80, self.__LeaveWindow)) |
| 1731 |
if "gtk2" in wx.PlatformInfo and not isinstance(self.TopLevelParent, wx.Dialog): |
| 1732 |
self.BackgroundColour = self.Parent.BackgroundColour |
| 1733 |
|
| 1734 |
def DoGetBestSize(self): |
| 1735 |
"""Calculate the best size of the button. |
| 1736 |
|
| 1737 |
Returns: |
| 1738 |
wx.Size: The best size of the button, taking into account. |
| 1739 |
""" |
| 1740 |
# A little more padding left + right |
| 1741 |
width = 6 * self.dpiscale |
| 1742 |
height = 6 * self.dpiscale |
| 1743 |
if self.Label: |
| 1744 |
# NOTE: Should measure with a GraphicsContext to get right |
| 1745 |
# size, but due to random segfaults on linux special |
| 1746 |
# handling is done in the drawing instead... |
| 1747 |
lsize = self.GetFullTextExtent(self.Label) |
| 1748 |
width += lsize[0] |
| 1749 |
height += lsize[1] |
| 1750 |
|
| 1751 |
if self._bmp["enable"] is not None: |
| 1752 |
bsize = self._bmp["enable"].Size |
| 1753 |
width += bsize[0] + 10 * self.dpiscale |
| 1754 |
if height <= bsize[1]: |
| 1755 |
height = bsize[1] + 6 * self.dpiscale |
| 1756 |
else: |
| 1757 |
# No DPI scaling needed here |
| 1758 |
height += 3 |
| 1759 |
else: |
| 1760 |
width += 10 * self.dpiscale |
| 1761 |
|
| 1762 |
if self._menu is not None or self._style & platebtn.PB_STYLE_DROPARROW: |
| 1763 |
width += 12 * self.dpiscale |
| 1764 |
|
| 1765 |
best = wx.Size(int(width), int(height)) |
| 1766 |
self.CacheBestSize(best) |
| 1767 |
return best |
| 1768 |
|
| 1769 |
def GetBitmapLabel(self): |
| 1770 |
"""Get the label bitmap. |
| 1771 |
|
| 1772 |
Returns: |
| 1773 |
None | wx.Bitmap: wx.Bitmap or None. |
| 1774 |
""" |
| 1775 |
return self._bmp["enable"] |
| 1776 |
|
| 1777 |
def SetBitmapHover(self, bmp): |
| 1778 |
"""Set the bitmap displayed in the button when hovered. |
| 1779 |
|
| 1780 |
Args: |
| 1781 |
bmp (wx.Bitmap): Bitmap to set as hover bitmap. |
| 1782 |
""" |
| 1783 |
self._bmp["hilite"] = bmp |
| 1784 |
|
| 1785 |
def __DrawBitmap(self, gc, interactable): |
| 1786 |
"""Draw the bitmap if one has been set. |
| 1787 |
|
| 1788 |
Args: |
| 1789 |
gc (GCDC): :class:`GCDC` to draw with. |
| 1790 |
interactable (bool): Whether the button is interactable. |
| 1791 |
|
| 1792 |
Return: |
| 1793 |
float: x cordinate to draw text at. |
| 1794 |
""" |
| 1795 |
if self.IsEnabled(): |
| 1796 |
if ( |
| 1797 |
self._state["cur"] in (platebtn.PLATE_HIGHLIGHT, platebtn.PLATE_PRESSED) |
| 1798 |
and interactable |
| 1799 |
): |
| 1800 |
bmp = self._bmp["hilite"] |
| 1801 |
else: |
| 1802 |
bmp = self._bmp["enable"] |
| 1803 |
else: |
| 1804 |
bmp = self._bmp["disable"] |
| 1805 |
|
| 1806 |
xpos = 4 * self.dpiscale |
| 1807 |
if bmp is not None and bmp.IsOk(): |
| 1808 |
bw, bh = bmp.GetSize() |
| 1809 |
ypos = (self.GetSize()[1] - bh) // 2 |
| 1810 |
gc.DrawBitmap(bmp, int(xpos), int(ypos), bmp.GetMask() is not None) |
| 1811 |
return bw + xpos |
| 1812 |
return xpos |
| 1813 |
|
| 1814 |
def __DrawButton(self): |
| 1815 |
"""Draw the button.""" |
| 1816 |
# TODO using a buffered paintdc on windows with the nobg style |
| 1817 |
# causes lots of weird drawing. So currently the use of a |
| 1818 |
# buffered dc is dissabled for this style. |
| 1819 |
if platebtn.PB_STYLE_NOBG & self._style: |
| 1820 |
dc = wx.PaintDC(self) |
| 1821 |
else: |
| 1822 |
dc = wx.AutoBufferedPaintDCFactory(self) |
| 1823 |
dc.SetBackground(wx.TRANSPARENT_BRUSH) |
| 1824 |
dc.Clear() |
| 1825 |
|
| 1826 |
gc = wx.GCDC(dc) |
| 1827 |
|
| 1828 |
# Setup |
| 1829 |
gc.SetFont(adjust_font_size_for_gcdc(self.GetFont())) |
| 1830 |
gc.SetBackgroundMode(wx.BRUSHSTYLE_TRANSPARENT) |
| 1831 |
|
| 1832 |
# Calc Object Positions |
| 1833 |
width, height = self.GetSize() |
| 1834 |
# Note: Using self.GetTextExtent instead of gc.GetTextExtent seems |
| 1835 |
# to fix sporadic segfaults with wxPython Phoenix up to 4.0.0a2 |
| 1836 |
# under Windows (fixed in 4.0.0a3), but self.GetTextExtent is NOT |
| 1837 |
# an equivalent replacement for gc.GetTextExtent. |
| 1838 |
tw, th = gc.GetTextExtent(self.Label) |
| 1839 |
txt_y = max((height - th) // 2 - 1, 1) |
| 1840 |
|
| 1841 |
# The background needs some help to look transparent on |
| 1842 |
# on Gtk and Windows |
| 1843 |
if wx.Platform in ["__WXGTK__", "__WXMSW__"]: |
| 1844 |
gc.SetBrush(self.GetBackgroundBrush(gc)) |
| 1845 |
gc.SetPen(wx.TRANSPARENT_PEN) |
| 1846 |
gc.DrawRectangle(0, 0, width, height) |
| 1847 |
|
| 1848 |
gc.SetBrush(wx.TRANSPARENT_BRUSH) |
| 1849 |
|
| 1850 |
space = 4 * self.dpiscale |
| 1851 |
|
| 1852 |
# Our IsEnabled() override only deals with explit enabled/disabled |
| 1853 |
# state, while we also need to deal with interaction state |
| 1854 |
# (button enabled and interactable, eg. no modal dialog shown that |
| 1855 |
# would prevent interaction) |
| 1856 |
dialogs = get_dialogs() |
| 1857 |
interactable = not dialogs or self.TopLevelParent in dialogs |
| 1858 |
if ( |
| 1859 |
self._state["cur"] == platebtn.PLATE_HIGHLIGHT |
| 1860 |
and self.IsEnabled() |
| 1861 |
and interactable |
| 1862 |
): |
| 1863 |
gc.SetTextForeground(self._color["htxt"]) |
| 1864 |
gc.SetPen(wx.TRANSPARENT_PEN) |
| 1865 |
self.__DrawHighlight(gc, int(width), int(height)) |
| 1866 |
|
| 1867 |
elif self._state["cur"] == platebtn.PLATE_PRESSED and self.IsEnabled(): |
| 1868 |
gc.SetTextForeground(self._color["htxt"]) |
| 1869 |
pen = wx.Pen(platebtn.AdjustColour(self._color["press"], -80, 220), 1) |
| 1870 |
gc.SetPen(pen) |
| 1871 |
|
| 1872 |
self.__DrawHighlight(gc, int(width), int(height)) |
| 1873 |
txt_x = self.__DrawBitmap(gc, interactable) |
| 1874 |
t_x = max((width - tw - (txt_x + space)) // 2, txt_x + space) |
| 1875 |
gc.DrawText(self.Label, int(t_x), int(txt_y)) |
| 1876 |
self.__DrawDropArrow(gc, int(width - 10), int((height // 2) - 2)) |
| 1877 |
|
| 1878 |
elif self.IsEnabled(): |
| 1879 |
gc.SetTextForeground(self.GetForegroundColour()) |
| 1880 |
else: |
| 1881 |
txt_c = wx.SystemSettings.GetColour(wx.SYS_COLOUR_GRAYTEXT) |
| 1882 |
gc.SetTextForeground(txt_c) |
| 1883 |
|
| 1884 |
# Draw bitmap and text |
| 1885 |
if self._state["cur"] != platebtn.PLATE_PRESSED or not self.IsEnabled(): |
| 1886 |
txt_x = self.__DrawBitmap(gc, interactable) |
| 1887 |
t_x = max((width - tw - (txt_x + space)) // 2, txt_x + space) |
| 1888 |
gc.DrawText(self.Label, int(t_x), int(txt_y)) |
| 1889 |
self.__DrawDropArrow(gc, int(width - 10), int((height // 2) - 2)) |
| 1890 |
|
| 1891 |
def __LeaveWindow(self): |
| 1892 |
"""Handle updating the buttons state when the mouse cursor leaves.""" |
| 1893 |
if (self._style & platebtn.PB_STYLE_TOGGLE) and self._pressed: |
| 1894 |
self._SetState(platebtn.PLATE_PRESSED) |
| 1895 |
else: |
| 1896 |
self._SetState(platebtn.PLATE_NORMAL) |
| 1897 |
self._pressed = False |
| 1898 |
|
| 1899 |
def __PostEvent(self): |
| 1900 |
"""Post a button event to parent of this control.""" |
| 1901 |
if self._style & platebtn.PB_STYLE_TOGGLE: |
| 1902 |
etype = wx.wxEVT_COMMAND_TOGGLEBUTTON_CLICKED |
| 1903 |
else: |
| 1904 |
etype = wx.wxEVT_COMMAND_BUTTON_CLICKED |
| 1905 |
bevt = wx.CommandEvent(etype, self.GetId()) |
| 1906 |
bevt.SetEventObject(self) |
| 1907 |
bevt.SetString(self.GetLabel()) |
| 1908 |
self.GetEventHandler().ProcessEvent(bevt) |
| 1909 |
|
| 1910 |
_PostEvent = __PostEvent |
| 1911 |
|
| 1912 |
def Update(self): |
| 1913 |
"""Update the button's appearance.""" |
| 1914 |
|
| 1915 |
Disable = ThemedGenButton.__dict__["Disable"] |
| 1916 |
Enable = ThemedGenButton.__dict__["Enable"] |
| 1917 |
Enabled = ThemedGenButton.__dict__["Enabled"] |
| 1918 |
IsEnabled = ThemedGenButton.__dict__["IsEnabled"] |
| 1919 |
Label = property( |
| 1920 |
lambda self: self.GetLabel(), lambda self, label: self.SetLabel(label) |
| 1921 |
) |
| 1922 |
|
| 1923 |
|
| 1924 |
if not hasattr(PlateButton, "_SetState"): |
| 1925 |
# wxPython < 3.0 |
| 1926 |
PlateButton._SetState = PlateButton.SetState |
| 1927 |
|
| 1928 |
|
| 1929 |
class TempXmlResource: |
| 1930 |
"""Temporary XML resource class to handle scaling and cleanup. |
| 1931 |
|
| 1932 |
Args: |
| 1933 |
xmlpath (str): Path to the XML resource file. |
| 1934 |
""" |
| 1935 |
|
| 1936 |
_temp = None |
| 1937 |
|
| 1938 |
def __init__(self, xmlpath): |
| 1939 |
from DisplayCAL.config import get_default_dpi, getcfg |
| 1940 |
|
| 1941 |
scale = max(getcfg("app.dpi") / get_default_dpi(), 1) |
| 1942 |
if scale > 1 or "gtk3" in wx.PlatformInfo: |
| 1943 |
if not TempXmlResource._temp: |
| 1944 |
with contextlib.suppress(Exception): |
| 1945 |
TempXmlResource._temp = tempfile.mkdtemp(prefix=f"{APPNAME}-XRC-") |
| 1946 |
if TempXmlResource._temp and os.path.isdir(TempXmlResource._temp): |
| 1947 |
# Read original XML |
| 1948 |
with open(xmlpath, "rb") as xmlfile: |
| 1949 |
xml = xmlfile.read().decode() |
| 1950 |
# Adjust spacing for scale |
| 1951 |
for tag in ("border", "hgap", "vgap"): |
| 1952 |
xml = re.sub( |
| 1953 |
rf"<{tag}>(\d+)</{tag}>", |
| 1954 |
lambda match, tag=tag: ( |
| 1955 |
f"<{tag}>{round(int(match.group(1)) * scale):d}</{tag}>" |
| 1956 |
), |
| 1957 |
xml, |
| 1958 |
) |
| 1959 |
for tag in ("size",): |
| 1960 |
xml = re.sub( |
| 1961 |
rf"<{tag}>(-?\d+)\s*,\s*(-?\d+)</{tag}>", |
| 1962 |
lambda match, tag=tag: f"<{tag}>{{:d}},{{:d}}</{tag}>".format( |
| 1963 |
*tuple( |
| 1964 |
round(int(v) * scale) if int(v) > 0 else int(v) |
| 1965 |
for v in match.groups() |
| 1966 |
) |
| 1967 |
), |
| 1968 |
xml, |
| 1969 |
) |
| 1970 |
# Set relative paths to absolute |
| 1971 |
basedir = os.path.dirname(os.path.dirname(xmlpath)) |
| 1972 |
basedir = basedir.replace("\\", "/") |
| 1973 |
xml = xml.replace(">../", f">{basedir}/") |
| 1974 |
# Fix background color not working for panels under wxGTK3 |
| 1975 |
if "gtk3" in wx.PlatformInfo: |
| 1976 |
xml = xml.replace( |
| 1977 |
'class="wxPanel"', |
| 1978 |
'class="wxPanel" subclass="DisplayCAL.wx_fixes.wx_Panel"', |
| 1979 |
) |
| 1980 |
# 'class="wxPanel" subclass="wx_fixes.wx_Panel"') |
| 1981 |
# Write modified XML |
| 1982 |
xmlpath = os.path.join(TempXmlResource._temp, os.path.basename(xmlpath)) |
| 1983 |
with open(xmlpath, "wb") as xmlfile: |
| 1984 |
xmlfile.write(xml.encode()) |
| 1985 |
from DisplayCAL.wx_windows import BaseApp |
| 1986 |
|
| 1987 |
BaseApp.register_exitfunc(self._cleanup) |
| 1988 |
self.xmlpath = xmlpath |
| 1989 |
self.res = xrc.XmlResource(xmlpath) |
| 1990 |
|
| 1991 |
def _cleanup(self): |
| 1992 |
"""Clean up the temporary XML resource.""" |
| 1993 |
if ( |
| 1994 |
TempXmlResource._temp |
| 1995 |
and self.xmlpath.startswith(TempXmlResource._temp + os.path.sep) |
| 1996 |
and os.path.isfile(self.xmlpath) |
| 1997 |
): |
| 1998 |
os.remove(self.xmlpath) |
| 1999 |
if not os.listdir(TempXmlResource._temp): |
| 2000 |
shutil.rmtree(TempXmlResource._temp) |
| 2001 |
|
| 2002 |
def __getattr__(self, name) -> Any: |
| 2003 |
"""Get attribute from the resource. |
| 2004 |
|
| 2005 |
Args: |
| 2006 |
name (str): Name of the attribute to get. |
| 2007 |
|
| 2008 |
Returns: |
| 2009 |
Any: The value of the attribute. |
| 2010 |
""" |
| 2011 |
return getattr(self.res, name) |
| 2012 |
|
| 2013 |
|
| 2014 |
class GenBitmapTextButton(GenButton, _GenBitmapTextButton): |
| 2015 |
"""A generic bitmapped button with text label. |
| 2016 |
|
| 2017 |
Args: |
| 2018 |
parent (wx.Window): The parent window. |
| 2019 |
id (int, optional): The identifier for the button. Defaults to -1. |
| 2020 |
bitmap (wx.Bitmap, optional): The bitmap to use. Defaults to |
| 2021 |
wx.NullBitmap. |
| 2022 |
label (str, optional): The label to use. Defaults to "". |
| 2023 |
pos (wx.Point, optional): The position of the button. Defaults to |
| 2024 |
wx.DefaultPosition. |
| 2025 |
size (wx.Size, optional): The size of the button. Defaults to |
| 2026 |
wx.DefaultSize. |
| 2027 |
style (int, optional): The style of the button. Defaults to 0. |
| 2028 |
validator (wx.Validator, optional): The validator for the button. |
| 2029 |
Defaults to wx.DefaultValidator. |
| 2030 |
name (str, optional): The name of the button. Defaults to "genbutton". |
| 2031 |
""" |
| 2032 |
|
| 2033 |
def __init__( |
| 2034 |
self, |
| 2035 |
parent, |
| 2036 |
id=-1, # noqa: A002 |
| 2037 |
bitmap=wx.NullBitmap, |
| 2038 |
label="", |
| 2039 |
pos=wx.DefaultPosition, |
| 2040 |
size=wx.DefaultSize, |
| 2041 |
style=0, |
| 2042 |
validator=wx.DefaultValidator, |
| 2043 |
name="genbutton", |
| 2044 |
): |
| 2045 |
GenButton.__init__(self) |
| 2046 |
_GenBitmapTextButton.__init__( |
| 2047 |
self, parent, id, bitmap, label, pos, size, style, validator, name |
| 2048 |
) |
| 2049 |
self._default = False |
| 2050 |
|
| 2051 |
def DrawLabel(self, dc, width, height, dx=0, dy=0): |
| 2052 |
"""Draw the label of the button. |
| 2053 |
|
| 2054 |
Args: |
| 2055 |
dc (wx.DC): The device context to draw on. |
| 2056 |
width (int): The width of the button. |
| 2057 |
height (int): The height of the button. |
| 2058 |
dx (int, optional): Horizontal offset for the label. Defaults to 0. |
| 2059 |
dy (int, optional): Vertical offset for the label. Defaults to 0. |
| 2060 |
""" |
| 2061 |
bmp = self.bmpLabel |
| 2062 |
if bmp is not None: # if the bitmap is used |
| 2063 |
if self.bmpDisabled and not self.IsEnabled(): |
| 2064 |
bmp = self.bmpDisabled |
| 2065 |
if self.bmpFocus and self.hasFocus: |
| 2066 |
bmp = self.bmpFocus |
| 2067 |
if self.bmpSelected and not self.up: |
| 2068 |
bmp = self.bmpSelected |
| 2069 |
bw, bh = bmp.GetWidth(), bmp.GetHeight() |
| 2070 |
if sys.platform != "win32" and not self.up: |
| 2071 |
dx = dy = self.labelDelta |
| 2072 |
hasMask = bmp.GetMask() is not None |
| 2073 |
else: |
| 2074 |
bw = bh = 0 # no bitmap -> size is zero |
| 2075 |
|
| 2076 |
dc.SetFont(self.GetFont()) |
| 2077 |
if self.IsEnabled(): |
| 2078 |
dc.SetTextForeground(self.GetForegroundColour()) |
| 2079 |
else: |
| 2080 |
dc.SetTextForeground(wx.SystemSettings.GetColour(wx.SYS_COLOUR_GRAYTEXT)) |
| 2081 |
|
| 2082 |
label = self.GetLabel() |
| 2083 |
tw, th = dc.GetTextExtent(label) # size of text |
| 2084 |
sw, sh = dc.GetTextExtent(" ") # extra spacing from bitmap |
| 2085 |
if sys.platform != "win32" and not self.up: |
| 2086 |
dx = dy = self.labelDelta |
| 2087 |
|
| 2088 |
# adjust for bitmap and text to centre |
| 2089 |
pos_x = int((width - bw - sw - tw) / 2) + dx |
| 2090 |
if bmp is not None: |
| 2091 |
dc.DrawBitmap( |
| 2092 |
bmp, pos_x, int((height - bh) / 2) + dy, hasMask |
| 2093 |
) # draw bitmap if available |
| 2094 |
pos_x = pos_x + sw # extra spacing from bitmap |
| 2095 |
|
| 2096 |
# draw the text |
| 2097 |
dc.DrawText(label, pos_x + dx + bw, int((height - th) / 2) + dy) |
| 2098 |
|
| 2099 |
|
| 2100 |
class ThemedGenBitmapTextButton(ThemedGenButton, GenBitmapTextButton): |
| 2101 |
"""A themed generic bitmapped button with text label.""" |
| 2102 |
|
| 2103 |
|
| 2104 |
class BitmapWithThemedButton(wx.BoxSizer): |
| 2105 |
"""A sizer that contains a bitmap and a themed button.""" |
| 2106 |
|
| 2107 |
def __init__( |
| 2108 |
self, |
| 2109 |
parent, |
| 2110 |
id=-1, # noqa: A002 |
| 2111 |
bitmap=wx.NullBitmap, |
| 2112 |
label="", |
| 2113 |
pos=wx.DefaultPosition, |
| 2114 |
size=wx.DefaultSize, |
| 2115 |
style=0, |
| 2116 |
validator=wx.DefaultValidator, |
| 2117 |
name="button", |
| 2118 |
): |
| 2119 |
wx.BoxSizer.__init__(self, wx.HORIZONTAL) |
| 2120 |
self._bmp = wx.StaticBitmap(parent, -1, bitmap) |
| 2121 |
# self.Add(self._bmp, flag=wx.ALIGN_CENTER_VERTICAL) |
| 2122 |
self.Add(self._bmp) |
| 2123 |
btncls = ThemedGenButton if wx.Platform == "__WXMSW__" else wx.Button |
| 2124 |
self._btn = btncls(parent, id, label, pos, size, style, validator, name) |
| 2125 |
# self.Add(self._btn, flag=wx.ALIGN_CENTER_VERTICAL | wx.LEFT, border=8) |
| 2126 |
self.Add(self._btn, flag=wx.LEFT, border=8) |
| 2127 |
|
| 2128 |
def __getattr__(self, name) -> Any: |
| 2129 |
"""Get attribute from button or bitmap. |
| 2130 |
|
| 2131 |
Args: |
| 2132 |
name (str): Name of the attribute to get. |
| 2133 |
|
| 2134 |
Returns: |
| 2135 |
Any: The value of the attribute. |
| 2136 |
""" |
| 2137 |
return getattr(self._btn, name) |
| 2138 |
|
| 2139 |
def Bind(self, event, handler): |
| 2140 |
"""Bind an event to the button. |
| 2141 |
|
| 2142 |
Args: |
| 2143 |
event (wx.EventType): The event type to bind. |
| 2144 |
handler (callable): The handler function to call when the event |
| 2145 |
occurs. |
| 2146 |
""" |
| 2147 |
self._btn.Bind(event, handler) |
| 2148 |
|
| 2149 |
def SetBitmapLabel(self, bitmap): |
| 2150 |
"""Set the bitmap label for the static bitmap. |
| 2151 |
|
| 2152 |
Args: |
| 2153 |
bitmap (wx.Bitmap): The bitmap to set as label. |
| 2154 |
""" |
| 2155 |
self._bmp.SetBitmap(bitmap) |
| 2156 |
self.Layout() |