Debian Codegraph @

DisplayCAL/lib/agw/artmanager.py

raw
1 """Drawing routines and customizations for AGW widgets."""
2
3 from __future__ import annotations
4
5 import random
6 from io import BytesIO
7 from typing import Callable, ClassVar
8
9 import wx
10
11 from DisplayCAL.lib.agw.fmresources import (
12 ARROW_DOWN,
13 ARROW_UP,
14 BOTTOM_SHADOW,
15 BOTTOM_SHADOW_FULL,
16 BU_EXT_LEFT_ALIGN_STYLE,
17 BU_EXT_RIGHT_ALIGN_STYLE,
18 BU_EXT_RIGHT_TO_LEFT_STYLE,
19 CONTROL_DISABLED,
20 CONTROL_FOCUS,
21 CONTROL_PRESSED,
22 CS_DROPSHADOW,
23 RIGHT_SHADOW,
24 SHADOW_BOTTOM_ALPHA,
25 SHADOW_BOTTOM_LEFT_ALPHA,
26 SHADOW_BOTTOM_LEFT_XPM,
27 SHADOW_BOTTOM_XPM,
28 SHADOW_CENTER_ALPHA,
29 SHADOW_CENTER_XPM,
30 SHADOW_RIGHT_ALPHA,
31 SHADOW_RIGHT_TOP_ALPHA,
32 SHADOW_RIGHT_TOP_XPM,
33 SHADOW_RIGHT_XPM,
34 STYLE_2007,
35 STYLE_XP,
36 )
37
38 # ------------------------------------------------------------------------------------ #
39 # Class DCSaver
40 # ------------------------------------------------------------------------------------ #
41
42 _: Callable[[str], str] = wx.GetTranslation
43
44 _libimported = None
45
46 if wx.Platform == "__WXMSW__":
47 OS_VERSION = wx.GetOsVersion()
48 # Shadows behind menus are supported only in XP
49 if OS_VERSION[1] == 5 and OS_VERSION[2] == 1:
50 try:
51 import win32api
52 import win32con
53 import winxpgui
54
55 _libimported = "MH"
56 except ImportError:
57 try:
58 import ctypes
59
60 _libimported = "ctypes"
61 except ImportError:
62 pass
63 else:
64 _libimported = None
65
66
67 class DCSaver:
68 """Construct a DC saver.
69
70 The dc is copied as-is.
71
72 Args:
73 pdc (wx.DC): An instance of :class:`wx.DC`.
74 """
75
76 def __init__(self, pdc: wx.DC) -> None:
77 self._pdc = pdc
78 self._pen = pdc.GetPen()
79 self._brush = pdc.GetBrush()
80
81 def __del__(self) -> None:
82 """While destructing, restore the dc pen and brush."""
83 if self._pdc:
84 self._pdc.SetPen(self._pen)
85 self._pdc.SetBrush(self._brush)
86
87
88 # ------------------------------------------------------------------------------------ #
89 # Class RendererBase
90 # ------------------------------------------------------------------------------------ #
91
92
93 class RendererBase:
94 """Base class for all theme renderers."""
95
96 def DrawButtonBorders( # noqa: N802
97 self, dc: wx.DC, rect: wx.Rect, pen_colour: wx.Colour, brush_colour: wx.Colour
98 ) -> None:
99 """Draw borders for buttons.
100
101 Args:
102 dc (wx.DC): an instance of :class:`wx.DC`.
103 rect (wx.Rect): the button's client rectangle.
104 pen_colour (wx.Colour): a valid :class:`wx.Colour` for the pen
105 border.
106 brush_colour (wx.Colour): a valid :class:`wx.Colour` for the brush.
107 """
108 # Keep old pen and brush
109 _ = DCSaver(dc)
110
111 # Set new pen and brush
112 dc.SetPen(wx.Pen(pen_colour))
113 dc.SetBrush(wx.Brush(brush_colour))
114
115 # Draw the rectangle
116 dc.DrawRectangle(rect)
117
118 def DrawBitmapArea( # noqa: N802
119 self,
120 dc: wx.DC,
121 xpm_name: str,
122 rect: wx.Rect,
123 base_colour: wx.Colour,
124 flip_side: bool,
125 ) -> None:
126 """Draw the area below a bitmap and the bitmap itself using a gradient shading.
127
128 Args:
129 dc (wx.DC): :class:`wx.DC` instance.
130 xpm_name (str): The name of the XPM bitmap.
131 rect (wx.Rect): The bitmap client rectangle.
132 base_colour (wx.Colour): A valid :class:`wx.Colour` for the bitmap
133 background.
134 flip_side (bool): `True` to flip the gradient direction, `False`
135 otherwise.
136 """
137 # draw the gradient area
138 if not flip_side:
139 ArtManager.Get().PaintDiagonalGradientBox(
140 dc,
141 rect,
142 wx.WHITE,
143 ArtManager.Get().LightColour(base_colour, 20),
144 True,
145 False,
146 )
147 else:
148 ArtManager.Get().PaintDiagonalGradientBox(
149 dc,
150 rect,
151 ArtManager.Get().LightColour(base_colour, 20),
152 wx.WHITE,
153 True,
154 False,
155 )
156
157 # draw arrow
158 arrow_down = wx.Bitmap(xpm_name)
159 arrow_down.SetMask(wx.Mask(arrow_down, wx.WHITE))
160 dc.DrawBitmap(arrow_down, rect.x + 1, rect.y + 1, True)
161
162 def DrawBitmapBorders( # noqa: N802
163 self,
164 dc: wx.DC,
165 rect: wx.Rect,
166 pen_colour: wx.Colour,
167 bitmap_border_upper_left_pen: wx.Colour,
168 ) -> None:
169 """Draw borders for a bitmap.
170
171 Args:
172 dc (wx.DC): A :class:`wx.DC` instance.
173 rect (wx.Rect): The button's client rectangle.
174 pen_colour (wx.Colour): A valid :class:`wx.Colour` for the pen
175 border.
176 bitmap_border_upper_left_pen (wx.Colour): A valid
177 :class:`wx.Colour` for the pen upper left border.
178 """
179 # Keep old pen and brush
180 _ = DCSaver(dc)
181
182 # lower right side
183 dc.SetPen(wx.Pen(pen_colour))
184 dc.DrawLine(
185 rect.x,
186 rect.y + rect.height - 1,
187 rect.x + rect.width,
188 rect.y + rect.height - 1,
189 )
190 dc.DrawLine(
191 rect.x + rect.width - 1,
192 rect.y,
193 rect.x + rect.width - 1,
194 rect.y + rect.height,
195 )
196
197 # upper left side
198 dc.SetPen(wx.Pen(bitmap_border_upper_left_pen))
199 dc.DrawLine(rect.x, rect.y, rect.x + rect.width, rect.y)
200 dc.DrawLine(rect.x, rect.y, rect.x, rect.y + rect.height)
201
202 def GetMenuFaceColour(self) -> wx.Colour: # noqa: N802
203 """Return the foreground colour for the menu.
204
205 Returns:
206 wx.Colour: A :class:`wx.Colour` instance.
207 """
208 return ArtManager.Get().LightColour(
209 wx.SystemSettings.GetColour(wx.SYS_COLOUR_3DFACE), 80
210 )
211
212 def GetTextColourEnable(self) -> wx.Colour: # noqa: N802
213 """Return the colour used for text colour when enabled.
214
215 Returns:
216 wx.Colour: A :class:`wx.Colour` instance.
217 """
218 return wx.BLACK
219
220 def GetTextColourDisable(self) -> wx.Colour: # noqa: N802
221 """Return the colour used for text colour when disabled.
222
223 Returns:
224 wx.Colour: A :class:`wx.Colour` instance.
225 """
226 return ArtManager.Get().LightColour(
227 wx.SystemSettings.GetColour(wx.SYS_COLOUR_GRAYTEXT), 30
228 )
229
230 def GetFont(self) -> wx.Font: # noqa: N802
231 """Return the font used for text.
232
233 Returns:
234 wx.Font: A :class:`wx.Font` instance.
235 """
236 return wx.SystemSettings.GetFont(wx.SYS_DEFAULT_GUI_FONT)
237
238 def DrawButton( # noqa: N802
239 self,
240 dc: wx.DC,
241 rect: wx.Rect,
242 state: int,
243 input_: None | bool | wx.Colour = None,
244 ) -> None:
245 """Draw a button using the appropriate theme.
246
247 Args:
248 dc (wx.DC): an instance of :class:`wx.DC`.
249 rect (wx.Rect): the button's client rectangle.
250 state (int): the button state.
251 input_ (None | bool | wx.Colour): a flag used to call the
252 right method.
253
254 Raises:
255 NotImplementedError: This method must be implemented in derived
256 classes.
257 """
258 raise NotImplementedError(
259 "DrawButton method must be implemented in derived classes"
260 )
261
262 def DrawToolBarBg(self, dc: wx.DC, rect: wx.Rect) -> None: # noqa: N802
263 """Draw the toolbar background according to the active theme.
264
265 Args:
266 dc (wx.DC): an instance of :class:`wx.DC`.
267 rect (wx.Rect): the toolbar's client rectangle.
268
269 Raises:
270 NotImplementedError: This method must be implemented in derived classes.
271 """
272 raise NotImplementedError(
273 "DrawToolBarBg method must be implemented in derived classes"
274 )
275
276 def DrawMenuBarBg(self, dc: wx.DC, rect: wx.Rect) -> None: # noqa: N802
277 """Draw the menu bar background according to the active theme.
278
279 Args:
280 dc (wx.DC): an instance of :class:`wx.DC`.
281 rect (wx.Rect): the menu bar's client rectangle.
282
283 Raises:
284 NotImplementedError: This method must be implemented in derived classes.
285 """
286 raise NotImplementedError(
287 "DrawMenuBarBg method must be implemented in derived classes"
288 )
289
290
291 # ------------------------------------------------------------------------------------ #
292 # Class RendererXP
293 # ------------------------------------------------------------------------------------ #
294
295
296 class RendererXP(RendererBase):
297 """Xp-Style renderer."""
298
299 def __init__(self) -> None:
300 RendererBase.__init__(self)
301
302 def DrawButton( # noqa: N802
303 self,
304 dc: wx.DC,
305 rect: wx.Rect,
306 state: int,
307 input_: None | bool | wx.Colour = None,
308 ) -> None:
309 """Draw a button using the XP theme.
310
311 Args:
312 dc (wx.DC): An instance of :class:`wx.DC`.
313 rect (wx.Rect): The button's client rectangle.
314 state (int): The button state.
315 input_ (None | bool | wx.Colour): a flag used to call the
316 right method.
317 """
318 if input_ is None or isinstance(input_, bool):
319 self.DrawButtonTheme(dc, rect, state, input_)
320 else:
321 self.DrawButtonColour(dc, rect, state, input_)
322
323 def DrawButtonTheme( # noqa: N802
324 self,
325 dc: wx.DC,
326 rect: wx.Rect,
327 state: int,
328 use_light_colours: None | bool = None,
329 ) -> None:
330 """Draw a button using the XP theme.
331
332 Args:
333 dc (wx.DC): A :class:`wx.DC` instance.
334 rect (wx.Rect): The button's client rectangle.
335 state (int): The button state.
336 use_light_colours (None | bool): `True` to use light colours,
337 `False` otherwise.
338 """
339 # switch according to the status
340 if state == CONTROL_FOCUS:
341 pen_colour = ArtManager.Get().FrameColour()
342 brush_colour = ArtManager.Get().BackgroundColour()
343 elif state == CONTROL_PRESSED:
344 pen_colour = ArtManager.Get().FrameColour()
345 brush_colour = ArtManager.Get().HighlightBackgroundColour()
346 else:
347 pen_colour = ArtManager.Get().FrameColour()
348 brush_colour = ArtManager.Get().BackgroundColour()
349
350 # Draw the button borders
351 self.DrawButtonBorders(dc, rect, pen_colour, brush_colour)
352
353 def DrawButtonColour( # noqa: N802
354 self, dc: wx.DC, rect: wx.Rect, state: int, colour: wx.Colour
355 ) -> None:
356 """Draw a button using the XP theme.
357
358 Args:
359 dc (wx.DC): A :class:`wx.DC` instance.
360 rect (wx.Rect): The button's client rectangle.
361 state (int): The button state.
362 colour (wx.Colour): a valid :class:`wx.Colour` instance.
363 """
364 # switch according to the status
365 if state == CONTROL_FOCUS:
366 pen_colour = colour
367 brush_colour = ArtManager.Get().LightColour(colour, 75)
368 elif state == CONTROL_PRESSED:
369 pen_colour = colour
370 brush_colour = ArtManager.Get().LightColour(colour, 60)
371 else:
372 pen_colour = colour
373 brush_colour = ArtManager.Get().LightColour(colour, 75)
374
375 # Draw the button borders
376 self.DrawButtonBorders(dc, rect, pen_colour, brush_colour)
377
378 def DrawMenuBarBg(self, dc: wx.DC, rect: wx.Rect) -> None: # noqa: N802
379 """Draw the menu bar background according to the active theme.
380
381 Args:
382 dc (wx.DC): A :class:`wx.DC` instance.
383 rect (wx.Rect): The menu bar's client rectangle.
384 """
385 # For office style, we simple draw a rectangle with a gradient colouring
386 art_mgr = ArtManager.Get()
387 vertical = art_mgr.GetMBVerticalGradient()
388
389 _ = DCSaver(dc)
390
391 # fill with gradient
392 start_colour = art_mgr.GetMenuBarFaceColour()
393 if art_mgr.IsDark(start_colour):
394 start_colour = art_mgr.LightColour(start_colour, 50)
395
396 end_colour = art_mgr.LightColour(start_colour, 90)
397 art_mgr.PaintStraightGradientBox(dc, rect, start_colour, end_colour, vertical)
398
399 # Draw the border
400 if art_mgr.GetMenuBarBorder():
401 dc.SetPen(wx.Pen(start_colour))
402 dc.SetBrush(wx.TRANSPARENT_BRUSH)
403 dc.DrawRectangle(rect)
404
405 def DrawToolBarBg(self, dc: wx.DC, rect: wx.Rect) -> None: # noqa: N802
406 """Draw the toolbar background according to the active theme.
407
408 Args:
409 dc (wx.DC): A :class:`wx.DC` instance.
410 rect (wx.Rect): The toolbar's client rectangle.
411 """
412 art_mgr = ArtManager.Get()
413
414 if not art_mgr.GetRaiseToolbar():
415 return
416
417 # For office style, we simple draw a rectangle with a gradient colouring
418 vertical = art_mgr.GetMBVerticalGradient()
419
420 _ = DCSaver(dc)
421
422 # fill with gradient
423 start_colour = art_mgr.GetMenuBarFaceColour()
424 if art_mgr.IsDark(start_colour):
425 start_colour = art_mgr.LightColour(start_colour, 50)
426
427 start_colour = art_mgr.LightColour(start_colour, 20)
428
429 end_colour = art_mgr.LightColour(start_colour, 90)
430 art_mgr.PaintStraightGradientBox(dc, rect, start_colour, end_colour, vertical)
431 art_mgr.DrawBitmapShadow(dc, rect)
432
433 def GetTextColourEnable(self) -> wx.Colour: # noqa: N802
434 """Return the colour used for text colour when enabled.
435
436 Returns:
437 wx.Colour: A :class:`wx.Colour` instance.
438 """
439 return wx.BLACK
440
441
442 # ------------------------------------------------------------------------------------ #
443 # Class RendererMSOffice2007
444 # ------------------------------------------------------------------------------------ #
445
446
447 class RendererMSOffice2007(RendererBase):
448 """Windows MS Office 2007 style."""
449
450 def __init__(self) -> None:
451 RendererBase.__init__(self)
452
453 def GetColoursAccordingToState(self, state: int) -> tuple[int, int, int, int]: # noqa: N802
454 """Return a tuple according to the menu item state.
455
456 Args:
457 state (int): One of the following bits:
458
459 ==================== ======= ==========================
460 Item State Value Description
461 ==================== ======= ==========================
462 ``ControlPressed`` 0 The item is pressed
463 ``ControlFocus`` 1 The item is focused
464 ``ControlDisabled`` 2 The item is disabled
465 ``ControlNormal`` 3 Normal state
466 ==================== ======= ==========================
467
468 Returns:
469 tuple[int, int, int, int, bool, bool]: A tuple containing the
470 gradient percentages.
471 """
472 # switch according to the status
473 if state == CONTROL_FOCUS:
474 upper_box_top_percent = 95
475 upper_box_bottom_percent = 50
476 lower_box_top_percent = 40
477 lower_box_bottom_percent = 90
478 concave_upper_box = True
479 concave_lower_box = True
480
481 elif state == CONTROL_PRESSED:
482 upper_box_top_percent = 75
483 upper_box_bottom_percent = 90
484 lower_box_top_percent = 90
485 lower_box_bottom_percent = 40
486 concave_upper_box = True
487 concave_lower_box = True
488
489 elif state == CONTROL_DISABLED:
490 upper_box_top_percent = 100
491 upper_box_bottom_percent = 100
492 lower_box_top_percent = 70
493 lower_box_bottom_percent = 70
494 concave_upper_box = True
495 concave_lower_box = True
496
497 else:
498 upper_box_top_percent = 90
499 upper_box_bottom_percent = 50
500 lower_box_top_percent = 30
501 lower_box_bottom_percent = 75
502 concave_upper_box = True
503 concave_lower_box = True
504
505 return (
506 upper_box_top_percent,
507 upper_box_bottom_percent,
508 lower_box_top_percent,
509 lower_box_bottom_percent,
510 concave_upper_box,
511 concave_lower_box,
512 )
513
514 def DrawButton( # noqa: N802
515 self,
516 dc: wx.DC,
517 rect: wx.Rect,
518 state: int,
519 input_: None | bool | wx.Colour = None,
520 ) -> None:
521 """Draw a button using the MS Office 2007 theme.
522
523 Args:
524 dc (wx.DC): A :class:`wx.DC` instance.
525 rect (wx.Rect): The button's client rectangle.
526 state (int): The button state.
527 input_ (None | bool | wx.Colour): A flag used to call the
528 right method.
529 """
530 if input_ is None or isinstance(input_, bool):
531 self.DrawButtonTheme(dc, rect, state, input_)
532 else:
533 self.DrawButtonColour(dc, rect, state, input_)
534
535 def DrawButtonTheme( # noqa: N802
536 self, dc: wx.DC, rect: wx.Rect, state: int, use_light_colours: None | bool
537 ) -> None:
538 """Draw a button using the MS Office 2007 theme.
539
540 Args:
541 dc (wx.DC): an instance of :class:`wx.DC`.
542 rect (wx.Rect): the button's client rectangle.
543 state (int): the button state.
544 use_light_colours (None | bool): `True` to use light colours,
545 ``False`` otherwise.
546 """
547 self.DrawButtonColour(
548 dc, rect, state, ArtManager.Get().GetThemeBaseColour(use_light_colours)
549 )
550
551 def DrawButtonColour( # noqa: N802
552 self, dc: wx.DC, rect: wx.Rect, state: int, colour: wx.Colour
553 ) -> None:
554 """Draw a button using the MS Office 2007 theme.
555
556 Args:
557 dc (wx.DC): A :class:`wx.DC` instance.
558 rect (wx.Rect): The button's client rectangle.
559 state (int): The button state.
560 colour (wx.Colour): a valid :class:`wx.Colour` instance.
561 """
562 art_mgr = ArtManager.Get()
563
564 # Keep old pen and brush
565 _ = DCSaver(dc)
566
567 # Define the rounded rectangle base on the given rect
568 # we need an array of 9 points for it
569 base_colour = colour
570
571 # Define the middle points
572 left_pt = wx.Point(rect.x, rect.y + (rect.height / 2))
573 right_pt = wx.Point(rect.x + rect.width - 1, rect.y + (rect.height / 2))
574
575 # Define the top region
576 top = wx.Rect((rect.GetLeft(), rect.GetTop()), right_pt)
577 bottom = wx.Rect(left_pt, (rect.GetRight(), rect.GetBottom()))
578
579 (
580 upper_box_top_percent,
581 upper_box_bottom_percent,
582 lower_box_top_percent,
583 lower_box_bottom_percent,
584 concave_upper_box,
585 concave_lower_box,
586 ) = self.GetColoursAccordingToState(state)
587
588 top_start_colour = art_mgr.LightColour(base_colour, upper_box_top_percent)
589 top_end_colour = art_mgr.LightColour(base_colour, upper_box_bottom_percent)
590 bottom_start_colour = art_mgr.LightColour(base_colour, lower_box_top_percent)
591 bottom_end_colour = art_mgr.LightColour(base_colour, lower_box_bottom_percent)
592
593 art_mgr.PaintStraightGradientBox(dc, top, top_start_colour, top_end_colour)
594 art_mgr.PaintStraightGradientBox(
595 dc, bottom, bottom_start_colour, bottom_end_colour
596 )
597
598 rr = wx.Rect(rect.x, rect.y, rect.width, rect.height)
599 dc.SetBrush(wx.TRANSPARENT_BRUSH)
600
601 frame_colour = art_mgr.LightColour(base_colour, 60)
602 dc.SetPen(wx.Pen(frame_colour))
603 dc.DrawRectangle(rr)
604
605 wc = art_mgr.LightColour(base_colour, 80)
606 dc.SetPen(wx.Pen(wc))
607 rr.Deflate(1, 1)
608 dc.DrawRectangle(rr)
609
610 def DrawMenuBarBg(self, dc: wx.DC, rect: wx.Rect) -> None: # noqa: N802
611 """Draw the menu bar background according to the active theme.
612
613 Args:
614 dc (wx.DC): an instance of :class:`wx.DC`.
615 rect (wx.Rect): the menu bar's client rectangle.
616 """
617 # Keep old pen and brush
618 _ = DCSaver(dc)
619 art_mgr = ArtManager.Get()
620 base_colour = art_mgr.GetMenuBarFaceColour()
621
622 dc.SetBrush(wx.Brush(wx.SystemSettings.GetColour(wx.SYS_COLOUR_3DFACE)))
623 dc.SetPen(wx.Pen(wx.SystemSettings.GetColour(wx.SYS_COLOUR_3DFACE)))
624 dc.DrawRectangle(rect)
625
626 # Define the rounded rectangle base on the given rect
627 # we need an array of 9 points for it
628 reg_pts = [wx.Point() for _ in range(9)]
629 radius = 2
630
631 reg_pts[0] = wx.Point(rect.x, rect.y + radius)
632 reg_pts[1] = wx.Point(rect.x + radius, rect.y)
633 reg_pts[2] = wx.Point(rect.x + rect.width - radius - 1, rect.y)
634 reg_pts[3] = wx.Point(rect.x + rect.width - 1, rect.y + radius)
635 reg_pts[4] = wx.Point(
636 rect.x + rect.width - 1, rect.y + rect.height - radius - 1
637 )
638 reg_pts[5] = wx.Point(
639 rect.x + rect.width - radius - 1, rect.y + rect.height - 1
640 )
641 reg_pts[6] = wx.Point(rect.x + radius, rect.y + rect.height - 1)
642 reg_pts[7] = wx.Point(rect.x, rect.y + rect.height - radius - 1)
643 reg_pts[8] = reg_pts[0]
644
645 # Define the middle points
646 factor = art_mgr.GetMenuBgFactor()
647
648 left_pt1 = wx.Point(rect.x, rect.y + (rect.height / factor))
649 left_pt2 = wx.Point(rect.x, rect.y + (rect.height / factor) * (factor - 1))
650
651 right_pt1 = wx.Point(rect.x + rect.width, rect.y + (rect.height / factor))
652 right_pt2 = wx.Point(
653 rect.x + rect.width, rect.y + (rect.height / factor) * (factor - 1)
654 )
655
656 # Define the top region
657 top_reg = [wx.Point() for _ in range(7)]
658 top_reg[0] = reg_pts[0]
659 top_reg[1] = reg_pts[1]
660 top_reg[2] = wx.Point(reg_pts[2].x + 1, reg_pts[2].y)
661 top_reg[3] = wx.Point(reg_pts[3].x + 1, reg_pts[3].y)
662 top_reg[4] = wx.Point(right_pt1.x, right_pt1.y + 1)
663 top_reg[5] = wx.Point(left_pt1.x, left_pt1.y + 1)
664 top_reg[6] = top_reg[0]
665
666 # Define the middle region
667 middle = wx.Rect(left_pt1, wx.Point(right_pt2.x - 2, right_pt2.y))
668
669 # Define the bottom region
670 bottom = wx.Rect(left_pt2, wx.Point(rect.GetRight() - 1, rect.GetBottom()))
671
672 top_start_colour = art_mgr.LightColour(base_colour, 90)
673 top_end_colour = art_mgr.LightColour(base_colour, 60)
674 bottom_start_colour = art_mgr.LightColour(base_colour, 40)
675 bottom_end_colour = art_mgr.LightColour(base_colour, 20)
676
677 top_region = wx.Region(top_reg)
678
679 art_mgr.PaintGradientRegion(dc, top_region, top_start_colour, top_end_colour)
680 art_mgr.PaintStraightGradientBox(
681 dc, bottom, bottom_start_colour, bottom_end_colour
682 )
683 art_mgr.PaintStraightGradientBox(
684 dc, middle, top_end_colour, bottom_start_colour
685 )
686
687 def DrawToolBarBg(self, dc: wx.DC, rect: wx.Rect) -> None: # noqa: N802
688 """Draw the toolbar background according to the active theme.
689
690 Args:
691 dc (wx.DC): A :class:`wx.DC` instance.
692 rect (wx.Rect): The toolbar's client rectangle.
693 """
694 art_mgr = ArtManager.Get()
695
696 if not art_mgr.GetRaiseToolbar():
697 return
698
699 # Keep old pen and brush
700 _ = DCSaver(dc)
701
702 base_colour = art_mgr.GetMenuBarFaceColour()
703 base_colour = art_mgr.LightColour(base_colour, 20)
704
705 dc.SetBrush(wx.Brush(wx.SystemSettings.GetColour(wx.SYS_COLOUR_3DFACE)))
706 dc.SetPen(wx.Pen(wx.SystemSettings.GetColour(wx.SYS_COLOUR_3DFACE)))
707 dc.DrawRectangle(rect)
708
709 radius = 2
710
711 # Define the rounded rectangle base on the given rect
712 # we need an array of 9 points for it
713 reg_pts = [None] * 9
714
715 reg_pts[0] = wx.Point(rect.x, rect.y + radius)
716 reg_pts[1] = wx.Point(rect.x + radius, rect.y)
717 reg_pts[2] = wx.Point(rect.x + rect.width - radius - 1, rect.y)
718 reg_pts[3] = wx.Point(rect.x + rect.width - 1, rect.y + radius)
719 reg_pts[4] = wx.Point(
720 rect.x + rect.width - 1, rect.y + rect.height - radius - 1
721 )
722 reg_pts[5] = wx.Point(
723 rect.x + rect.width - radius - 1, rect.y + rect.height - 1
724 )
725 reg_pts[6] = wx.Point(rect.x + radius, rect.y + rect.height - 1)
726 reg_pts[7] = wx.Point(rect.x, rect.y + rect.height - radius - 1)
727 reg_pts[8] = reg_pts[0]
728
729 # Define the middle points
730 factor = art_mgr.GetMenuBgFactor()
731
732 left_pt1 = wx.Point(rect.x, rect.y + (rect.height / factor))
733 right_pt1 = wx.Point(rect.x + rect.width, rect.y + (rect.height / factor))
734
735 left_pt2 = wx.Point(rect.x, rect.y + (rect.height / factor) * (factor - 1))
736 right_pt2 = wx.Point(
737 rect.x + rect.width, rect.y + (rect.height / factor) * (factor - 1)
738 )
739
740 # Define the top region
741 top_reg = [None] * 7
742 top_reg[0] = reg_pts[0]
743 top_reg[1] = reg_pts[1]
744 top_reg[2] = wx.Point(reg_pts[2].x + 1, reg_pts[2].y)
745 top_reg[3] = wx.Point(reg_pts[3].x + 1, reg_pts[3].y)
746 top_reg[4] = wx.Point(right_pt1.x, right_pt1.y + 1)
747 top_reg[5] = wx.Point(left_pt1.x, left_pt1.y + 1)
748 top_reg[6] = top_reg[0]
749
750 # Define the middle region
751 middle = wx.Rect(left_pt1, wx.Point(right_pt2.x - 2, right_pt2.y))
752
753 # Define the bottom region
754 bottom = wx.Rect(left_pt2, wx.Point(rect.GetRight() - 1, rect.GetBottom()))
755
756 top_start_colour = art_mgr.LightColour(base_colour, 90)
757 top_end_colour = art_mgr.LightColour(base_colour, 60)
758 bottom_start_colour = art_mgr.LightColour(base_colour, 40)
759 bottom_end_colour = art_mgr.LightColour(base_colour, 20)
760
761 top_region = wx.Region(top_reg)
762
763 art_mgr.PaintGradientRegion(dc, top_region, top_start_colour, top_end_colour)
764 art_mgr.PaintStraightGradientBox(
765 dc, bottom, bottom_start_colour, bottom_end_colour
766 )
767 art_mgr.PaintStraightGradientBox(
768 dc, middle, top_end_colour, bottom_start_colour
769 )
770
771 art_mgr.DrawBitmapShadow(dc, rect)
772
773 def GetTextColourEnable(self) -> wx.Colour: # noqa: N802
774 """Return the colour used for text colour when enabled.
775
776 Returns:
777 An instance of :class:`wx.Colour`.
778 """
779 return wx.Colour("MIDNIGHT BLUE")
780
781
782 # ------------------------------------------------------------------------------------ #
783 # Class ArtManager
784 # ------------------------------------------------------------------------------------ #
785
786
787 class ArtManager(wx.EvtHandler):
788 """This class provides utilities for creating shadows and adjusting colors."""
789
790 _alignment_buffer = 7
791 _menu_theme: int = STYLE_XP
792 _vertical_gradient = False
793 _renderers: ClassVar[dict[int, RendererBase]] = {STYLE_XP: None, STYLE_2007: None}
794 _bmp_shadow_enabled = False
795 _ms2007sunken = False
796 _draw_mb_border = True
797 _menu_bg_factor = 5
798 _menu_bar_colour_scheme: str = _("Default")
799 _raise_trace_back = True
800 _bitmaps: ClassVar[dict[str, wx.Bitmap]] = {}
801 _transparency = 255
802
803 def __init__(self) -> None:
804 wx.EvtHandler.__init__(self)
805 self._menuBarBgColour = wx.SystemSettings.GetColour(wx.SYS_COLOUR_3DFACE)
806
807 # connect an event handler to the system colour change event
808 self.Bind(wx.EVT_SYS_COLOUR_CHANGED, self.OnSysColourChange)
809
810 # Initialize the menu bar selection colour
811 self._menuBarSelColour = wx.Colour(0, 0, 0) # Default to black
812
813 def SetTransparency(self, amount: int) -> None: # noqa: N802
814 """Set the alpha channel value for transparent windows.
815
816 Args:
817 amount (int): The actual transparency value (between 0 and 255).
818
819 Raises:
820 Exception: If the `amount` parameter is lower than ``0`` or greater than
821 ``255``.
822 """
823 if self._transparency == amount:
824 return
825
826 if amount < 0 or amount > 255:
827 raise Exception("Invalid transparency value")
828
829 self._transparency = amount
830
831 def GetTransparency(self) -> int: # noqa: N802
832 """Return the alpha channel value for transparent windows.
833
834 Returns:
835 int: An integer representing the alpha channel value.
836 """
837 return self._transparency
838
839 @classmethod
840 def ConvertToBitmap( # noqa: N802
841 cls, xpm: list[str] | bytes, alpha: None | list[int] = None
842 ) -> wx.Bitmap:
843 """Convert the given image to a bitmap, optionally overlaying an alpha channel.
844
845 Args:
846 xpm (list[str] | bytes): A list of strings formatted as XPM.
847 alpha (None | list[int]): A list of alpha values, the same size
848 as the xpm bitmap.
849
850 Raises:
851 TypeError: If `xpm` is not a list of strings or a bytes object.
852
853 Returns:
854 wx.Bitmap: An instance of :class:`wx.Bitmap`.
855 """
856 if isinstance(xpm, bytes):
857 img = wx.ImageFromStream(BytesIO(xpm))
858 elif isinstance(xpm, list) and all(isinstance(data, str) for data in xpm):
859 img = wx.Bitmap(xpm).ConvertToImage()
860 else:
861 raise TypeError("xpm must be a list of strings or a bytes object")
862
863 if alpha is not None:
864 x = img.GetWidth()
865 y = img.GetHeight()
866 img.InitAlpha()
867 for jj in range(y):
868 for ii in range(x):
869 img.SetAlpha(ii, jj, alpha[jj * x + ii])
870
871 return wx.Bitmap(img)
872
873 def Initialize(self) -> None: # noqa: N802
874 """Initialize the bitmaps and colours."""
875 # create wxBitmaps from the xpm's
876 self._rightBottomCorner = self.ConvertToBitmap(
877 SHADOW_CENTER_XPM, SHADOW_CENTER_ALPHA
878 )
879 self._bottom = self.ConvertToBitmap(SHADOW_BOTTOM_XPM, SHADOW_BOTTOM_ALPHA)
880 self._bottomLeft = self.ConvertToBitmap(
881 SHADOW_BOTTOM_LEFT_XPM, SHADOW_BOTTOM_LEFT_ALPHA
882 )
883 self._rightTop = self.ConvertToBitmap(
884 SHADOW_RIGHT_TOP_XPM, SHADOW_RIGHT_TOP_ALPHA
885 )
886 self._right = self.ConvertToBitmap(SHADOW_RIGHT_XPM, SHADOW_RIGHT_ALPHA)
887
888 # initialise the colour map
889 self.InitColours()
890 self.SetMenuBarColour(self._menu_bar_colour_scheme)
891
892 # Create common bitmaps
893 self.FillStockBitmaps()
894
895 def FillStockBitmaps(self) -> None: # noqa: N802
896 """Initialize few standard bitmaps."""
897 bmp = self.ConvertToBitmap(ARROW_DOWN, alpha=None)
898 bmp.SetMask(wx.Mask(bmp, wx.Colour(0, 128, 128)))
899 self._bitmaps.update({"arrow_down": bmp})
900
901 bmp = self.ConvertToBitmap(ARROW_UP, alpha=None)
902 bmp.SetMask(wx.Mask(bmp, wx.Colour(0, 128, 128)))
903 self._bitmaps.update({"arrow_up": bmp})
904
905 def GetStockBitmap(self, name: str) -> wx.Bitmap: # noqa: N802
906 """Return a bitmap from a stock.
907
908 Args:
909 name (str): The bitmap name.
910
911 Returns:
912 wx.Bitmap: The stock bitmap, if `name` was found in the stock bitmap
913 dictionary. Otherwise, :class:`NullBitmap` is returned.
914 """
915 return self._bitmaps.get(name, wx.NullBitmap)
916
917 @classmethod
918 def Get(cls: type[ArtManager]) -> ArtManager: # noqa: N802
919 """Accessor to the unique art manager object.
920
921 Returns:
922 A unique instance of :class:`ArtManager`.
923 """
924 if not hasattr(cls, "_instance"):
925 cls._instance = ArtManager()
926 cls._instance.Initialize()
927
928 # Initialize the renderers map
929 cls._renderers[STYLE_XP] = RendererXP()
930 cls._renderers[STYLE_2007] = RendererMSOffice2007()
931
932 return cls._instance
933
934 @classmethod
935 def Free(cls) -> None: # noqa: N802
936 """Destructor for the unique art manager object."""
937 if hasattr(cls, "_instance"):
938 del cls._instance
939
940 def OnSysColourChange(self, event: wx.SysColourChangedEvent) -> None: # noqa: N802
941 """Handle the ``wx.EVT_SYS_COLOUR_CHANGED`` event for :class:`ArtManager`.
942
943 Args:
944 event (wx.SysColourChangedEvent): A :class:`SysColourChangedEvent` event to
945 be processed.
946 """
947 # reinitialise the colour map
948 self.InitColours()
949
950 def LightColour(self, colour: wx.Colour, percent: int) -> wx.Colour: # noqa: N802
951 """Return light contrast of `colour`.
952
953 The colour returned is from the scale of `colour` ==> white.
954
955 Args:
956 colour (wx.Colour): The input colour to be brightened, an instance of
957 :class:`wx.Colour`.
958 percent (int): Determines how light the colour will be.
959 `percent` = ``100`` returns white, `percent` = ``0`` returns `colour`.
960
961 Returns:
962 wx.Colour: A light contrast of the input `colour`.
963 """
964 end_colour = wx.WHITE
965 rd = end_colour.Red() - colour.Red()
966 gd = end_colour.Green() - colour.Green()
967 bd = end_colour.Blue() - colour.Blue()
968 high = 100
969
970 # We take the percent way of the colour from colour -. white
971 i = percent
972 r = colour.Red() + ((i * rd * 100) / high) / 100
973 g = colour.Green() + ((i * gd * 100) / high) / 100
974 b = colour.Blue() + ((i * bd * 100) / high) / 100
975 a = colour.Alpha()
976
977 return wx.Colour(int(r), int(g), int(b), int(a))
978
979 def DarkColour(self, colour: wx.Colour, percent: int) -> wx.Colour: # noqa: N802
980 """Like :meth:`.LightColour`, but create a darker colour by `percent`.
981
982 Args:
983 colour (wx.Colour): The input colour to be darkened.
984 percent (int): Determines how dark the colour will be.
985 `percent` = ``100`` returns black, `percent` = ``0`` returns `colour`.
986
987 Returns:
988 wx.Colour: A dark contrast of the input `colour`.
989 """
990 end_colour = wx.BLACK
991 rd = end_colour.Red() - colour.Red()
992 gd = end_colour.Green() - colour.Green()
993 bd = end_colour.Blue() - colour.Blue()
994 high = 100
995
996 # We take the percent way of the colour from colour -. white
997 i = percent
998 r = colour.Red() + ((i * rd * 100) / high) / 100
999 g = colour.Green() + ((i * gd * 100) / high) / 100
1000 b = colour.Blue() + ((i * bd * 100) / high) / 100
1001
1002 return wx.Colour(int(r), int(g), int(b))
1003
1004 def PaintStraightGradientBox( # noqa: N802
1005 self,
1006 dc: wx.DC,
1007 rect: wx.Rect,
1008 start_colour: wx.Colour,
1009 end_colour: wx.Colour,
1010 vertical: bool = True,
1011 ) -> None:
1012 """Paint the rectangle with gradient coloring.
1013
1014 The gradient lines are either horizontal or vertical.
1015
1016 Args:
1017 dc (wx.DC): A :class:`wx.DC` instance.
1018 rect (wx.Rect): The rectangle to be filled with gradient shading.
1019 start_colour (wx.Colour): The first colour of the gradient
1020 shading.
1021 end_colour (wx.EndColour): The second colour of the gradient
1022 shading.
1023 vertical (bool): ``True`` for gradient coloring in the vertical
1024 direction, ``False`` for horizontal shading.
1025 """
1026 _ = DCSaver(dc)
1027
1028 if vertical:
1029 high = rect.GetHeight() - 1
1030 direction = wx.SOUTH
1031 else:
1032 high = rect.GetWidth() - 1
1033 direction = wx.EAST
1034
1035 if high < 1:
1036 return
1037
1038 dc.GradientFillLinear(rect, start_colour, end_colour, direction)
1039
1040 def PaintGradientRegion( # noqa: N802
1041 self,
1042 dc: wx.DC,
1043 region: wx.Region,
1044 start_colour: wx.Colour,
1045 end_colour: wx.Colour,
1046 vertical: bool = True,
1047 ) -> None:
1048 """Paint a region with gradient coloring.
1049
1050 Args:
1051 dc (wx.DC): A :class:`wx.DC` instance.
1052 region (wx.Region): A region to be filled with gradient shading.
1053 start_colour (wx.Colour): The first colour of the gradient shading.
1054 end_colour (wx.Colour): The second colour of the gradient shading.
1055 vertical (bool): ``True`` for gradient coloring in the vertical
1056 direction, ``False`` for horizontal shading.
1057 """
1058 # The way to achieve non-rectangle
1059 mem_dc = wx.MemoryDC()
1060 rect = region.GetBox()
1061 bitmap = wx.Bitmap(rect.width, rect.height)
1062 mem_dc.SelectObject(bitmap)
1063
1064 # Colour the whole rectangle with gradient
1065 rr = wx.Rect(0, 0, rect.width, rect.height)
1066 self.PaintStraightGradientBox(mem_dc, rr, start_colour, end_colour, vertical)
1067
1068 # Convert the region to a black and white bitmap with the white pixels
1069 # being inside the region we draw the bitmap over the gradient coloured
1070 # rectangle, with mask set to white, this will cause our region to be
1071 # coloured with the gradient, while area outside the region will be
1072 # painted with black. Then we simply draw the bitmap to the dc with
1073 # mask set to black.
1074 tmp_region = wx.Region(rect.x, rect.y, rect.width, rect.height)
1075 tmp_region.Offset(-rect.x, -rect.y)
1076 region_bmp = tmp_region.ConvertToBitmap()
1077 region_bmp.SetMask(wx.Mask(region_bmp, wx.WHITE))
1078
1079 # The function ConvertToBitmap() return a rectangle bitmap which is
1080 # shorter by 1 pixel on the height and width (this is correct behavior,
1081 # since DrawLine does not include the second point as part of the line)
1082 # we fix this issue by drawing our own line at the bottom and left side
1083 # of the rectangle
1084 mem_dc.SetPen(wx.BLACK_PEN)
1085 mem_dc.DrawBitmap(region_bmp, 0, 0, True)
1086 mem_dc.DrawLine(0, rr.height - 1, rr.width, rr.height - 1)
1087 mem_dc.DrawLine(rr.width - 1, 0, rr.width - 1, rr.height)
1088
1089 mem_dc.SelectObject(wx.NullBitmap)
1090 bitmap.SetMask(wx.Mask(bitmap, wx.BLACK))
1091 dc.DrawBitmap(bitmap, rect.x, rect.y, True)
1092
1093 def PaintDiagonalGradientBox( # noqa: N802
1094 self,
1095 dc: wx.DC,
1096 rect: wx.Rect,
1097 start_colour: wx.Colour,
1098 end_colour: wx.Colour,
1099 start_at_upper_left: bool = True,
1100 trim_to_square: bool = True,
1101 ) -> None:
1102 """Paint rectangle with gradient coloring.
1103
1104 The gradient lines are diagonal and may start from the upper left
1105 corner or from the upper right corner.
1106
1107 Args:
1108 dc (wx.DC): A :class:`wx.DC` instance.
1109 rect (wx.Rect): The rectangle to be filled with gradient shading.
1110 start_colour (wx.Colour): The first colour of the gradient shading.
1111 end_colour (wx.Colour): The second colour of the gradient shading.
1112 start_at_upper_left (bool): ``True`` to start the gradient lines at
1113 the upper left corner of the rectangle, ``False`` to start at
1114 the upper right corner.
1115 trim_to_square (bool): ``True`` to trim the gradient lines in a
1116 square.
1117 """
1118 # gradient fill from colour 1 to colour 2 with top to bottom
1119 if rect.height < 1 or rect.width < 1:
1120 return
1121
1122 # Save the current pen and brush
1123 saved_pen = dc.GetPen()
1124 saved_brush = dc.GetBrush()
1125
1126 # calculate some basic numbers
1127 size, size_x, size_y, proportion = self._calculate_sizes(rect, trim_to_square)
1128 rstep, gstep, bstep = self._calculate_steps(start_colour, end_colour, size)
1129
1130 self._draw_upper_triangle(
1131 dc,
1132 rect,
1133 start_colour,
1134 rstep,
1135 gstep,
1136 bstep,
1137 size,
1138 size_x,
1139 size_y,
1140 proportion,
1141 start_at_upper_left,
1142 )
1143 self._draw_lower_triangle(
1144 dc,
1145 rect,
1146 start_colour,
1147 rstep,
1148 gstep,
1149 bstep,
1150 size,
1151 size_x,
1152 size_y,
1153 proportion,
1154 start_at_upper_left,
1155 )
1156
1157 # Restore the pen and brush
1158 dc.SetPen(saved_pen)
1159 dc.SetBrush(saved_brush)
1160
1161 def _calculate_sizes(
1162 self, rect: wx.Rect, trim_to_square: bool
1163 ) -> tuple[int, int, int, float]:
1164 """Calculate the sizes for the gradient drawing.
1165
1166 Args:
1167 rect (wx.Rect): The rectangle to be filled with gradient shading.
1168 trim_to_square (bool): ``True`` to trim the gradient lines in a
1169 square.
1170
1171 Returns:
1172 tuple[int, int, int, float]: A tuple containing the size, sizeX,
1173 sizeY and proportion.
1174 """
1175 if rect.width > rect.height:
1176 if trim_to_square:
1177 size = rect.height
1178 size_x = size_y = rect.height - 1
1179 proportion = 1.0 # Square proportion is 1.0
1180 else:
1181 proportion = float(rect.heigh) / float(rect.width)
1182 size = rect.width
1183 size_x = rect.width - 1
1184 size_y = rect.height - 1
1185 elif trim_to_square:
1186 size = rect.width
1187 size_x = size_y = rect.width - 1
1188 proportion = 1.0 # Square proportion is 1.0
1189 else:
1190 size_x = rect.width - 1
1191 size = rect.height
1192 size_y = rect.height - 1
1193 proportion = float(rect.width) / float(rect.height)
1194 return size, size_x, size_y, proportion
1195
1196 def _calculate_steps(
1197 self, start_colour: wx.Colour, end_colour: wx.Colour, size: int
1198 ) -> tuple[float, float, float]:
1199 """Calculate the gradient steps for the diagonal gradient drawing.
1200
1201 Args:
1202 start_colour (wx.Colour): The first colour of the gradient shading.
1203 end_colour (wx.Colour): The second colour of the gradient shading.
1204 size (int): The size of the gradient.
1205
1206 Returns:
1207 A tuple containing the rstep, gstep, and bstep.
1208 """
1209 # calculate gradient coefficients
1210 col2 = end_colour
1211 col1 = start_colour
1212 rstep = float(col2.Red() - col1.Red()) / float(size)
1213 gstep = float(col2.Green() - col1.Green()) / float(size)
1214 bstep = float(col2.Blue() - col1.Blue()) / float(size)
1215 return rstep, gstep, bstep
1216
1217 def _draw_upper_triangle(
1218 self,
1219 dc: wx.DC,
1220 rect: wx.Rect,
1221 start_colour: wx.Colour,
1222 rstep: float,
1223 gstep: float,
1224 bstep: float,
1225 size: int,
1226 size_x: int,
1227 size_y: int,
1228 proportion: float,
1229 start_at_upper_left: bool,
1230 ) -> None:
1231 """Draw the upper triangle of the diagonal gradient.
1232
1233 Args:
1234 dc (wx.DC): A :class:`wx.DC` instance.
1235 rect (wx.Rect): The rectangle to be filled with gradient shading.
1236 start_colour (wx.Colour): The first colour of the gradient shading.
1237 rstep (float): The red step of the gradient.
1238 gstep (float): The green step of the gradient.
1239 bstep (float): The blue step of the gradient.
1240 size (int): The size of the gradient.
1241 size_x (int): The width of the gradient.
1242 size_y (int): The height of the gradient.
1243 proportion (float): The proportion of the gradient.
1244 start_at_upper_left (bool): ``True`` to start the gradient lines at
1245 the upper left corner of the rectangle, ``False`` to start at
1246 the upper right corner.
1247 """
1248 rf, gf, bf = 0.0, 0.0, 0.0
1249 # draw the upper triangle
1250 for i in range(size):
1251 curr_col = wx.Colour(
1252 start_colour.Red() + rf,
1253 start_colour.Green() + gf,
1254 start_colour.Blue() + bf,
1255 )
1256 dc.SetBrush(wx.Brush(curr_col, wx.BRUSHSTYLE_SOLID))
1257 dc.SetPen(wx.Pen(curr_col))
1258 self._draw_line_and_point(
1259 dc, rect, i, size_x, size_y, proportion, start_at_upper_left
1260 )
1261 rf += rstep / 2
1262 gf += gstep / 2
1263 bf += bstep / 2
1264
1265 def _draw_lower_tiangle(
1266 self,
1267 dc: wx.DC,
1268 rect: wx.Rect,
1269 start_colour: wx.Colour,
1270 rstep: float,
1271 gstep: float,
1272 bstep: float,
1273 size: int,
1274 size_x: int,
1275 size_y: int,
1276 proportion: float,
1277 start_at_upper_left: bool,
1278 ) -> None:
1279 """Draw the lower triangle of the diagonal gradient.
1280
1281 Args:
1282 dc (wx.DC): A :class:`wx.DC` instance.
1283 rect (wx.Rect): The rectangle to be filled with gradient shading.
1284 start_colour (wx.Colour): The first colour of the gradient shading.
1285 rstep (float): The red step of the gradient.
1286 gstep (float): The green step of the gradient.
1287 bstep (float): The blue step of the gradient.
1288 size (int): The size of the gradient.
1289 size_x (int): The width of the gradient.
1290 size_y (int): The height of the gradient.
1291 proportion (float): The proportion of the gradient.
1292 start_at_upper_left (bool): ``True`` to start the gradient lines at
1293 the upper left corner of the rectangle, ``False`` to start at
1294 the upper right corner.
1295 """
1296 rf = rstep * size / 2
1297 gf = gstep * size / 2
1298 bf = bstep * size / 2
1299 # draw the lower triangle
1300 for i in range(size):
1301 curr_col = wx.Colour(
1302 start_colour.Red() + rf,
1303 start_colour.Green() + gf,
1304 start_colour.Blue() + bf,
1305 )
1306 dc.SetBrush(wx.Brush(curr_col, wx.BRUSHSTYLE_SOLID))
1307 dc.SetPen(wx.Pen(curr_col))
1308 self._draw_line_and_point(
1309 dc, rect, i, size_x, size_y, proportion, start_at_upper_left, lower=True
1310 )
1311 rf += rstep / 2
1312 gf += gstep / 2
1313 bf += bstep / 2
1314
1315 def _draw_line_and_point(
1316 self,
1317 dc: wx.DC,
1318 rect: wx.Rect,
1319 i: int,
1320 size_x: int,
1321 size_y: int,
1322 proportion: float,
1323 start_at_upper_left: bool,
1324 lower: bool = False,
1325 ) -> None:
1326 """Draw a line and a point for the diagonal gradient.
1327
1328 Args:
1329 dc (wx.DC): A :class:`wx.DC` instance.
1330 rect (wx.Rect): The rectangle to be filled with gradient shading.
1331 i (int): The current step in the gradient.
1332 size_x (int): The width of the gradient.
1333 size_y (int): The height of the gradient.
1334 proportion (float): The proportion of the gradient.
1335 start_at_upper_left (bool): ``True`` to start the gradient lines at
1336 the upper left corner of the rectangle, ``False`` to start at
1337 the upper right corner.
1338 lower (bool): ``True`` to draw the lower triangle, ``False`` to
1339 draw the upper triangle.
1340 """
1341 if start_at_upper_left:
1342 if rect.width > rect.height:
1343 if lower:
1344 dc.DrawLine(
1345 rect.x + i,
1346 rect.y + size_y,
1347 rect.x + size_x,
1348 int(rect.y + proportion * i),
1349 )
1350 dc.DrawPoint(rect.x + size_x, int(rect.y + proportion * i))
1351 else:
1352 dc.DrawLine(
1353 rect.x + i, rect.y, rect.x, int(rect.y + proportion * i)
1354 )
1355 dc.DrawPoint(rect.x, int(rect.y + proportion * i))
1356 elif lower:
1357 dc.DrawLine(
1358 int(rect.x + proportion * i),
1359 rect.y + size_y,
1360 rect.x + size_x,
1361 rect.y + i,
1362 )
1363 dc.DrawPoint(rect.x + size_x, rect.y + i)
1364 else:
1365 dc.DrawLine(int(rect.x + proportion * i), rect.y, rect.x, rect.y + i)
1366 dc.DrawPoint(rect.x, rect.y + i)
1367 elif rect.width > rect.height:
1368 if lower:
1369 dc.DrawLine(
1370 rect.x + i, rect.y + size_y, rect.x + size_x - i, rect.y + size_y
1371 )
1372 dc.DrawPoint(rect.x + size_x - i, rect.y + size_y)
1373 else:
1374 dc.DrawLine(
1375 rect.x + size_x - i,
1376 rect.y,
1377 rect.x + size_x,
1378 int(rect.y + proportion * i),
1379 )
1380 dc.DrawPoint(rect.x + size_x, int(rect.y + proportion * i))
1381 else:
1382 x_to = max(int(rect.x + size_x - proportion * i), rect.x)
1383 if lower:
1384 dc.DrawLine(rect.x, rect.y + i, x_to, rect.y + size_y)
1385 dc.DrawPoint(x_to, rect.y + size_y)
1386 else:
1387 dc.DrawLine(x_to, rect.y, rect.x + size_x, rect.y + i)
1388 dc.DrawPoint(rect.x + size_x, rect.y + i)
1389
1390 def PaintCrescentGradientBox( # noqa: N802
1391 self,
1392 dc: wx.DC,
1393 rect: wx.Rect,
1394 start_colour: wx.Colour,
1395 end_colour: wx.Colour,
1396 concave: bool = True,
1397 ) -> None:
1398 """Paint a region with gradient colouring.
1399
1400 The gradient is in crescent shape which fits the 2007 style.
1401
1402 Args:
1403 dc (wx.DC): A :class:`wx.DC` instance.
1404 rect (wx.Rect): The rectangle to be filled with gradient shading.
1405 start_colour (wx.Colour): The first colour of the gradient shading.
1406 end_colour (wx.Colour): The second colour of the gradient shading.
1407 concave (bool): ``True`` for a concave effect, ``False`` for a
1408 convex one.
1409 """
1410 diagonal_rect_width = rect.GetWidth() / 4
1411 spare = rect.width - 4 * diagonal_rect_width
1412 left_rect = wx.Rect(rect.x, rect.y, diagonal_rect_width, rect.GetHeight())
1413 right_rect = wx.Rect(
1414 rect.x + 3 * diagonal_rect_width + spare,
1415 rect.y,
1416 diagonal_rect_width,
1417 rect.GetHeight(),
1418 )
1419
1420 if concave:
1421 self.PaintStraightGradientBox(
1422 dc, rect, self.MixColours(start_colour, end_colour, 50), end_colour
1423 )
1424 self.PaintDiagonalGradientBox(
1425 dc, left_rect, start_colour, end_colour, True, False
1426 )
1427 self.PaintDiagonalGradientBox(
1428 dc, right_rect, start_colour, end_colour, False, False
1429 )
1430
1431 else:
1432 self.PaintStraightGradientBox(
1433 dc, rect, end_colour, self.MixColours(end_colour, start_colour, 50)
1434 )
1435 self.PaintDiagonalGradientBox(
1436 dc, left_rect, end_colour, start_colour, False, False
1437 )
1438 self.PaintDiagonalGradientBox(
1439 dc, right_rect, end_colour, start_colour, True, False
1440 )
1441
1442 def FrameColour(self) -> wx.Colour: # noqa: N802
1443 """Return the surrounding colour for a control.
1444
1445 Returns:
1446 wx.Colour: An instance of :class:`wx.Colour`.
1447 """
1448 return wx.SystemSettings.GetColour(wx.SYS_COLOUR_ACTIVECAPTION)
1449
1450 def BackgroundColour(self) -> wx.Colour: # noqa: N802
1451 """Return the background colour of a control when not in focus.
1452
1453 Returns:
1454 wx.Colour: An instance of :class:`wx.Colour`.
1455 """
1456 return self.LightColour(self.FrameColour(), 75)
1457
1458 def HighlightBackgroundColour(self) -> wx.Colour: # noqa: N802
1459 """Return the background colour of a control when it is in focus.
1460
1461 Returns:
1462 wx.Colour: An instance of :class:`wx.Colour`.
1463 """
1464 return self.LightColour(self.FrameColour(), 60)
1465
1466 def MixColours( # noqa: N802
1467 self, first_colour: wx.Colour, second_colour: wx.Colour, percent: int
1468 ) -> wx.Colour:
1469 """Return mix of input colours.
1470
1471 Args:
1472 first_colour (wx.Colour): The first colour to be mixed.
1473 second_colour (wx.Colour): The second colour to be mixed.
1474 percent (int): The relative percentage of `first_colour` with
1475 respect to `second_colour`.
1476
1477 Returns:
1478 wx.Colour: An instance of :class:`wx.Colour`.
1479 """
1480 # calculate gradient coefficients
1481 red_offset = float(
1482 (second_colour.Red() * (100 - percent) / 100)
1483 - (first_colour.Red() * percent / 100)
1484 )
1485 green_offset = float(
1486 (second_colour.Green() * (100 - percent) / 100)
1487 - (first_colour.Green() * percent / 100)
1488 )
1489 blue_offset = float(
1490 (second_colour.Blue() * (100 - percent) / 100)
1491 - (first_colour.Blue() * percent / 100)
1492 )
1493
1494 return wx.Colour(
1495 first_colour.Red() + red_offset,
1496 first_colour.Green() + green_offset,
1497 first_colour.Blue() + blue_offset,
1498 )
1499
1500 @classmethod
1501 def RandomColour(cls) -> wx.Colour: # noqa: N802
1502 """Create a random colour.
1503
1504 Returns:
1505 wx.Colour: An instance of :class:`wx.Colour`.
1506 """
1507 r = random.randint(0, 255) # Random value between 0-255 # noqa: S311
1508 g = random.randint(0, 255) # Random value between 0-255 # noqa: S311
1509 b = random.randint(0, 255) # Random value between 0-255 # noqa: S311
1510 return wx.Colour(r, g, b)
1511
1512 def IsDark(self, colour: wx.Colour) -> bool: # noqa: N802
1513 """Return whether a colour is dark or light.
1514
1515 Args:
1516 colour (wx.Colour): A :class:`wx.Colour`.
1517
1518 Returns:
1519 bool: ``True`` if the average RGB values are dark, ``False``
1520 otherwise.
1521 """
1522 evg = (colour.Red() + colour.Green() + colour.Blue()) / 3
1523 return evg < 127
1524
1525 @classmethod
1526 def TruncateText(cls, dc: wx.DC, text: str, max_width: int) -> None | str: # noqa: N802
1527 """Truncate a given string to fit given width size.
1528
1529 If the text does not fit into the given width it is truncated to fit.
1530 The format of the fixed text is ``truncate text ...``.
1531
1532 Args:
1533 dc (wx.DC): A :class:`wx.DC` instance.
1534 text (str): The text to be (eventually) truncated.
1535 max_width (int): The maximum width allowed for the text.
1536
1537 Returns:
1538 None | str: A string containing the (possibly) truncated
1539 text.
1540 """
1541 text_len = len(text)
1542 temp_text = text
1543 rect_size = max_width
1544
1545 fixed_text = ""
1546
1547 text_w, _ = dc.GetTextExtent(text)
1548
1549 if rect_size >= text_w:
1550 return text
1551
1552 # The text does not fit in the designated area, so we need to truncate
1553 # it a bit
1554 suffix = ".."
1555 w, _ = dc.GetTextExtent(suffix)
1556 rect_size -= w
1557
1558 for _ in range(text_len, -1, -1):
1559 text_w, _ = dc.GetTextExtent(temp_text)
1560 if rect_size >= text_w:
1561 fixed_text = temp_text
1562 fixed_text += ".."
1563 return fixed_text
1564
1565 temp_text = temp_text[:-1]
1566
1567 return None
1568
1569 def DrawButton( # noqa: N802
1570 self,
1571 dc: wx.DC,
1572 rect: wx.Rect,
1573 theme: int,
1574 state: int,
1575 input_: None | bool | wx.Colour = None,
1576 ) -> None:
1577 """Colour rectangle according to the theme.
1578
1579 Args:
1580 dc (wx.DC): A :class:`wx.DC` instance.
1581 rect (wx.Rect): The rectangle to be filled with gradient shading.
1582 theme (int): The theme to use to draw the button.
1583 state (int): The button state.
1584 input_ (None | bool | wx.Colour): A flag used to call the
1585 right method.
1586 """
1587 if input_ is None or isinstance(input_, bool):
1588 self.DrawButtonTheme(dc, rect, theme, state, bool(input_))
1589 else:
1590 self.DrawButtonColour(dc, rect, theme, state, input_)
1591
1592 def DrawButtonTheme( # noqa: N802
1593 self,
1594 dc: wx.DC,
1595 rect: wx.Rect,
1596 theme: int,
1597 state: int,
1598 use_light_colours: bool = True,
1599 ) -> None:
1600 """Draw a button using the appropriate theme.
1601
1602 Args:
1603 dc (wx.DC): A :class:`wx.DC` instance.
1604 rect (wx.Rect): The button's client rectangle.
1605 theme (int): The theme to use to draw the button.
1606 state (int): The button state.
1607 use_light_colours (bool): ``True`` to use light colours, ``False``
1608 otherwise.
1609 """
1610 renderer = self._renderers[int(theme)]
1611
1612 # Set background colour if non given by caller
1613 renderer.DrawButton(dc, rect, state, use_light_colours)
1614
1615 def DrawButtonColour( # noqa: N802
1616 self, dc: wx.DC, rect: wx.Rect, theme: int, state: int, colour: wx.Colour
1617 ) -> None:
1618 """Draw a button using the appropriate theme.
1619
1620 Args:
1621 dc (wx.DC): A :class:`wx.DC` instance.
1622 rect (wx.Rect): The button's client rectangle.
1623 theme (int): The theme to use to draw the button.
1624 state (int): The button state.
1625 colour (wx.Colour): A valid :class:`wx.Colour` instance.
1626 """
1627 renderer = self._renderers[theme]
1628 renderer.DrawButton(dc, rect, state, colour)
1629
1630 def CanMakeWindowsTransparent(self) -> bool: # noqa: N802
1631 """Check if the current OS supports transparency.
1632
1633 Returns:
1634 bool: ``True`` if the system supports transparency of toplevel
1635 windows, otherwise returns ``False``.
1636 """
1637 if wx.Platform == "__WXMSW__":
1638 version = wx.GetOsDescription()
1639 return (
1640 version.find("XP") >= 0
1641 or version.find("2000") >= 0
1642 or version.find("NT") >= 0
1643 )
1644 if wx.Platform == "__WXMAC__": # noqa: SIM103
1645 return True
1646 # Linux
1647 return False
1648
1649 def MakeWindowTransparent(self, wnd: wx.TopLevelWindow, amount: int) -> None: # noqa: N802
1650 """Make a toplevel window transparent if the system supports it.
1651
1652 On supported windows systems (Win2000 and greater), this function will
1653 make a frame window transparent by a certain amount.
1654
1655 Args:
1656 wnd (wx.TopLevelWindow): The toplevel window to make transparent.
1657 amount (int): The window transparency to apply.
1658 """
1659 if wnd.GetSize() == (0, 0):
1660 return
1661
1662 # This API call is not in all SDKs, only the newer ones,
1663 # so we will runtime bind this
1664 if wx.Platform == "__WXMSW__":
1665 hwnd = wnd.GetHandle()
1666
1667 if not hasattr(self, "_winlib"):
1668 if _libimported == "MH":
1669 self._winlib = win32api.LoadLibrary("user32")
1670 elif _libimported == "ctypes":
1671 self._winlib = ctypes.windll.user32
1672
1673 if _libimported == "MH":
1674 p_set_layered_window_attributes = win32api.GetProcAddress(
1675 self._winlib, "SetLayeredWindowAttributes"
1676 )
1677
1678 if p_set_layered_window_attributes is None:
1679 return
1680
1681 exstyle = win32api.GetWindowLong(hwnd, win32con.GWL_EXSTYLE)
1682 if (exstyle & 0x80000) == 0:
1683 win32api.SetWindowLong(
1684 hwnd, win32con.GWL_EXSTYLE, exstyle | 0x80000
1685 )
1686
1687 winxpgui.SetLayeredWindowAttributes(hwnd, 0, amount, 2)
1688
1689 elif _libimported == "ctypes":
1690 style = self._winlib.GetWindowLongA(hwnd, 0xFFFFFFEC)
1691 style |= 0x00080000
1692 self._winlib.SetWindowLongA(hwnd, 0xFFFFFFEC, style)
1693 self._winlib.SetLayeredWindowAttributes(hwnd, 0, amount, 2)
1694 else:
1695 if not wnd.CanSetTransparent():
1696 return
1697 wnd.SetTransparent(amount)
1698
1699 def DrawBitmapShadow( # noqa: N802
1700 self, dc: wx.DC, rect: wx.Rect, where: int = BOTTOM_SHADOW | RIGHT_SHADOW
1701 ) -> None:
1702 """Draw a shadow using background bitmap.
1703
1704 Assumption: the background was already drawn on the dc
1705
1706 Args:
1707 dc (wx.DC): A :class:`wx.DC` instance.
1708 rect (wx.Rect): The bitmap's client rectangle.
1709 where (int): Where to draw the shadow. This can be any combination
1710 of the following bits:
1711
1712 ===================== ======= =======================
1713 Shadow Settings Value Description
1714 ===================== ======= =======================
1715 ``RightShadow`` 1 Right side shadow
1716 ``BottomShadow`` 2 Not full bottom shadow
1717 ``BottomShadowFull`` 4 Full bottom shadow
1718 ===================== ======= =======================
1719 """
1720 shadow_size = 5
1721
1722 # the rect must be at least 5x5 pixels
1723 if rect.height < 2 * shadow_size or rect.width < 2 * shadow_size:
1724 return
1725
1726 # Start by drawing the right bottom corner
1727 if where & BOTTOM_SHADOW or where & BOTTOM_SHADOW_FULL:
1728 dc.DrawBitmap(
1729 self._rightBottomCorner, rect.x + rect.width, rect.y + rect.height, True
1730 )
1731
1732 # Draw right side shadow
1733 xx = rect.x + rect.width
1734 yy = rect.y + rect.height - shadow_size
1735
1736 if where & RIGHT_SHADOW:
1737 while yy - rect.y > 2 * shadow_size:
1738 dc.DrawBitmap(self._right, xx, yy, True)
1739 yy -= shadow_size
1740
1741 dc.DrawBitmap(self._rightTop, xx, yy - shadow_size, True)
1742
1743 if where & BOTTOM_SHADOW:
1744 xx = rect.x + rect.width - shadow_size
1745 yy = rect.height + rect.y
1746 while xx - rect.x > 2 * shadow_size:
1747 dc.DrawBitmap(self._bottom, xx, yy, True)
1748 xx -= shadow_size
1749
1750 dc.DrawBitmap(self._bottomLeft, xx - shadow_size, yy, True)
1751
1752 if where & BOTTOM_SHADOW_FULL:
1753 xx = rect.x + rect.width - shadow_size
1754 yy = rect.height + rect.y
1755 while xx - rect.x >= 0:
1756 dc.DrawBitmap(self._bottom, xx, yy, True)
1757 xx -= shadow_size
1758
1759 dc.DrawBitmap(self._bottom, xx, yy, True)
1760
1761 def DropShadow(self, wnd: wx.TopLevelWindow, drop: bool = True) -> None: # noqa: N802
1762 """Add a shadow under the window (Windows only).
1763
1764 Args:
1765 wnd (wx.TopLevelWindow): The window for which we are dropping a
1766 shadow.
1767 drop (bool): ``True`` to drop a shadow, ``False`` to remove it.
1768 """
1769 if not self.CanMakeWindowsTransparent() or not _libimported:
1770 return
1771
1772 if "__WXMSW__" in wx.Platform:
1773 hwnd = wnd.GetHandle()
1774
1775 if not hasattr(self, "_winlib"):
1776 if _libimported == "MH":
1777 self._winlib = win32api.LoadLibrary("user32")
1778 elif _libimported == "ctypes":
1779 self._winlib = ctypes.windll.user32
1780
1781 if _libimported == "MH":
1782 csstyle = win32api.GetWindowLong(hwnd, win32con.GCL_STYLE)
1783 else:
1784 csstyle = self._winlib.GetWindowLongA(hwnd, win32con.GCL_STYLE)
1785
1786 if drop:
1787 if csstyle & CS_DROPSHADOW:
1788 return
1789 csstyle |= CS_DROPSHADOW # Nothing to be done
1790 elif csstyle & CS_DROPSHADOW:
1791 csstyle &= ~(CS_DROPSHADOW)
1792 else:
1793 return # Nothing to be done
1794
1795 win32api.SetWindowLong(hwnd, win32con.GCL_STYLE, csstyle)
1796
1797 def GetBitmapStartLocation( # noqa: N802
1798 self,
1799 dc: wx.DC,
1800 rect: wx.Rect,
1801 bitmap: wx.Bitmap,
1802 text: str = "",
1803 style: int = 0,
1804 ) -> tuple[float, float]:
1805 """Return the top left `x` and `y` coordinates of the bitmap drawing.
1806
1807 Args:
1808 dc (wx.DC): A :class:`wx.DC` instance.
1809 rect (wx.Rect): The bitmap's client rectangle.
1810 bitmap (wx.Bitmap): The bitmap associated with the button.
1811 text (str): The button label.
1812 style (int): The button style. This can be one of the following bits:
1813
1814 ============================== ======= ================================
1815 Button style Value Description
1816 ============================== ======= ================================
1817 ``BU_EXT_XP_STYLE`` 1 A button with a XP style
1818 ``BU_EXT_2007_STYLE`` 2 A button with a MS Office 2007
1819 style
1820 ``BU_EXT_LEFT_ALIGN_STYLE`` 4 A left-aligned button
1821 ``BU_EXT_CENTER_ALIGN_STYLE`` 8 A center-aligned button
1822 ``BU_EXT_RIGHT_ALIGN_STYLE`` 16 A right-aligned button
1823 ``BU_EXT_RIGHT_TO_LEFT_STYLE`` 32 A button suitable for
1824 right-to-left languages
1825 ============================== ======= ================================
1826
1827
1828 Returns:
1829 tuple[float, float]: A tuple containing the top left `x` and `y`
1830 coordinates of the bitmap drawing.
1831 """
1832 alignment_buffer = self.GetAlignBuffer()
1833
1834 # get the startLocationY
1835 fixed_text_width = fixed_text_height = 0
1836
1837 if not text:
1838 fixed_text_height = bitmap.GetHeight()
1839 else:
1840 fixed_text_width, fixed_text_height = dc.GetTextExtent(text)
1841
1842 start_location_y = rect.y + (rect.height - fixed_text_height) / 2
1843
1844 # get the startLocationX
1845 if style & BU_EXT_RIGHT_TO_LEFT_STYLE:
1846 start_location_x = (
1847 rect.x + rect.width - alignment_buffer - bitmap.GetWidth()
1848 )
1849 elif style & BU_EXT_RIGHT_ALIGN_STYLE:
1850 max_width = (
1851 rect.x + rect.width - (2 * alignment_buffer) - bitmap.GetWidth()
1852 ) # the alignment is for both sides
1853
1854 # get the truncated text. The text may stay as is, it is not a
1855 # must that is will be truncated
1856 fixed_text = self.TruncateText(dc, text, max_width)
1857
1858 # get the fixed text dimensions
1859 fixed_text_width, _ = dc.GetTextExtent(fixed_text)
1860
1861 # calculate the start location
1862 start_location_x = max_width - fixed_text_width
1863
1864 elif style & BU_EXT_LEFT_ALIGN_STYLE:
1865 # calculate the start location
1866 start_location_x = alignment_buffer
1867
1868 else: # meaning BU_EXT_CENTER_ALIGN_STYLE
1869 max_width = (
1870 rect.x + rect.width - (2 * alignment_buffer) - bitmap.GetWidth()
1871 ) # the alignment is for both sides
1872
1873 # get the truncated text. The text may stay as is, it is not a
1874 # must that is will be truncated
1875 fixed_text = self.TruncateText(dc, text, max_width)
1876
1877 # get the fixed text dimensions
1878 fixed_text_width, _ = dc.GetTextExtent(fixed_text)
1879
1880 if max_width > fixed_text_width:
1881 # calculate the start location
1882 start_location_x = (max_width - fixed_text_width) / 2
1883
1884 else:
1885 # calculate the start location
1886 start_location_x = max_width - fixed_text_width
1887
1888 # it is very important to validate that the start location is not less
1889 # than the alignment buffer
1890 start_location_x = max(start_location_x, alignment_buffer)
1891
1892 return start_location_x, start_location_y
1893
1894 def GetTextStartLocation( # noqa: N802
1895 self, dc: wx.DC, rect: wx.Rect, bitmap: wx.Bitmap, text: str, style: int = 0
1896 ) -> tuple[float, float, None | str]:
1897 """Return the top left `x` and `y` coordinates of the text drawing.
1898
1899 In case the text is too long, the text is being fixed (the text is cut
1900 and a '...' mark is added in the end).
1901
1902 Args:
1903 dc (wx.DC): A :class:`wx.DC` instance.
1904 rect (wx.Rect): The text's client rectangle.
1905 bitmap (wx.Bitmap): The bitmap associated with the button.
1906 text (str): The button label.
1907 style (int): The button style.
1908
1909 Returns:
1910 tuple[float, float, None | str]: A tuple containing the top
1911 left `x` and `y` coordinates of the text drawing, plus the
1912 truncated version of the input `text`.
1913
1914 See :meth:`~ArtManager.GetBitmapStartLocation`for a list of valid button
1915 styles.
1916 """
1917 alignment_buffer = self.GetAlignBuffer()
1918
1919 # get the bitmap offset
1920 bitmap_offset = 0
1921 if bitmap != wx.NullBitmap:
1922 bitmap_offset = bitmap.GetWidth()
1923
1924 # get the truncated text.
1925 # The text may stay as is, it is not a must that it will be truncated
1926 max_width = (
1927 rect.x + rect.width - (2 * alignment_buffer) - bitmap_offset
1928 ) # the alignment is for both sides
1929 fixed_text = self.TruncateText(dc, text, max_width)
1930
1931 # get the fixed text dimensions
1932 fixed_text_width, fixed_text_height = dc.GetTextExtent(fixed_text)
1933 start_location_y = (rect.height - fixed_text_height) / 2 + rect.y
1934
1935 # get the startLocationX
1936 if style & BU_EXT_RIGHT_TO_LEFT_STYLE:
1937 start_location_x = max_width - fixed_text_width + alignment_buffer
1938 elif style & BU_EXT_LEFT_ALIGN_STYLE:
1939 # calculate the start location
1940 start_location_x = bitmap_offset + alignment_buffer
1941 elif style & BU_EXT_RIGHT_ALIGN_STYLE:
1942 # calculate the start location
1943 start_location_x = (
1944 max_width - fixed_text_width + bitmap_offset + alignment_buffer
1945 )
1946 else: # meaning wxBU_EXT_CENTER_ALIGN_STYLE
1947 # calculate the start location
1948 start_location_x = (
1949 (max_width - fixed_text_width) / 2 + bitmap_offset + alignment_buffer
1950 )
1951
1952 # it is very important to validate that the start location is not less
1953 # than the alignment buffer
1954 start_location_x = max(start_location_x, alignment_buffer)
1955
1956 return start_location_x, start_location_y, fixed_text
1957
1958 def DrawTextAndBitmap( # noqa: N802
1959 self,
1960 dc: wx.DC,
1961 rect: wx.Rect,
1962 text: str,
1963 enable: bool = True,
1964 font: wx.Font = wx.NullFont,
1965 font_colour: wx.Colour = wx.BLACK,
1966 bitmap: wx.Bitmap = wx.NullBitmap,
1967 gray_bitmap: wx.Bitmap = wx.NullBitmap,
1968 style: int = 0,
1969 ) -> None:
1970 """Draw the text & bitmap on the input dc.
1971
1972 Args:
1973 dc (wx.DC): A :class:`wx.DC` instance.
1974 rect (wx.Rect): The text and bitmap client rectangle.
1975 text (str): the button label.
1976 enable (bool): ``True`` if the button is enabled, ``False`` otherwise.
1977 font (wx.Font): The font to use to draw the text.
1978 font_colour (wx.Colour): The colour to use to draw the text.
1979 bitmap (wx.Bitmap): The bitmap associated with the button.
1980 gray_bitmap (wx.Bitmap): A greyed-out version of the input `bitmap`
1981 representing a disabled bitmap.
1982 style (int): The button style.
1983
1984 See: :meth:`~ArtManager.GetBitmapStartLocation` for a list of valid button
1985 styles.
1986 """
1987 # enable colours
1988 if enable:
1989 dc.SetTextForeground(font_colour)
1990 else:
1991 dc.SetTextForeground(wx.SystemSettings.GetColour(wx.SYS_COLOUR_GRAYTEXT))
1992
1993 # set the font
1994 if font.IsSameAs(wx.NullFont):
1995 font = wx.SystemSettings.GetFont(wx.SYS_DEFAULT_GUI_FONT)
1996
1997 dc.SetFont(font)
1998
1999 start_location_x = start_location_y = 0.0
2000
2001 if not bitmap.IsSameAs(wx.NullBitmap):
2002 # calculate the bitmap start location
2003 start_location_x, start_location_y = self.GetBitmapStartLocation(
2004 dc, rect, bitmap, text, style
2005 )
2006
2007 # draw the bitmap
2008 if enable:
2009 dc.DrawBitmap(bitmap, start_location_x, start_location_y, True)
2010 else:
2011 dc.DrawBitmap(gray_bitmap, start_location_x, start_location_y, True)
2012
2013 # calculate the text start location
2014 location, label_only = self.GetAccelIndex(text)
2015 start_location_x, start_location_y, fixed_text = self.GetTextStartLocation(
2016 dc, rect, bitmap, label_only, style
2017 )
2018
2019 if fixed_text is None:
2020 fixed_text = ""
2021
2022 # after all the calculations are finished, it is time to draw the text underline
2023 # the first letter that is marked with a '&'
2024 if location == -1 or font.GetUnderlined() or location >= len(fixed_text):
2025 # draw the text
2026 dc.DrawText(fixed_text, start_location_x, start_location_y)
2027 else:
2028 # underline the first '&'
2029 before = fixed_text[0:location]
2030 underline_letter = fixed_text[location]
2031 after = fixed_text[location + 1 :]
2032
2033 # before
2034 dc.DrawText(before, start_location_x, start_location_y)
2035
2036 # underlineLetter
2037 if "__WXGTK__" not in wx.Platform:
2038 w1, _ = dc.GetTextExtent(before)
2039 font.SetUnderlined(True)
2040 dc.SetFont(font)
2041 dc.DrawText(underline_letter, start_location_x + w1, start_location_y)
2042 else:
2043 w1, _ = dc.GetTextExtent(before)
2044 dc.DrawText(underline_letter, start_location_x + w1, start_location_y)
2045
2046 # Draw the underline ourselves since using the Underline in GTK,
2047 # causes the line to be too close to the letter
2048 uderline_letter_w, uderline_letter_h = dc.GetTextExtent(
2049 underline_letter
2050 )
2051
2052 cur_pen = dc.GetPen()
2053 dc.SetPen(wx.BLACK_PEN)
2054
2055 dc.DrawLine(
2056 start_location_x + w1,
2057 start_location_y + uderline_letter_h - 2,
2058 start_location_x + w1 + uderline_letter_w,
2059 start_location_y + uderline_letter_h - 2,
2060 )
2061 dc.SetPen(cur_pen)
2062
2063 # after
2064 w2, _ = dc.GetTextExtent(underline_letter)
2065 font.SetUnderlined(False)
2066 dc.SetFont(font)
2067 dc.DrawText(after, start_location_x + w1 + w2, start_location_y)
2068
2069 def CalcButtonBestSize(self, label: str, bmp: wx.Bitmap) -> wx.Size: # noqa: N802
2070 """Return the best fit size for the supplied label & bitmap.
2071
2072 Args:
2073 label (str): The button label.
2074 bmp (wx.Bitmap): The bitmap associated with the button.
2075
2076 Returns:
2077 wx.Size: Representing the best fit size for the supplied label & bitmap.
2078 """
2079 default_height = 22 if "__WXMSW__" in wx.Platform else 26
2080
2081 dc = wx.MemoryDC()
2082 dc.SelectBitmap(wx.Bitmap(1, 1))
2083
2084 dc.SetFont(wx.SystemSettings.GetFont(wx.SYS_DEFAULT_GUI_FONT))
2085 width, height, _ = dc.GetFullMultiLineTextExtent(label)
2086
2087 width += 2 * self.GetAlignBuffer()
2088
2089 if bmp.IsOk():
2090 # allocate extra space for the bitmap
2091 height_bmp = bmp.GetHeight() + 2
2092 height = max(height, height_bmp)
2093
2094 width += bmp.GetWidth() + 2
2095
2096 height = max(height, default_height)
2097
2098 dc.SelectBitmap(wx.NullBitmap)
2099
2100 return wx.Size(width, height)
2101
2102 def GetMenuFaceColour(self) -> wx.Colour: # noqa: N802
2103 """Return the colour used for the menu foreground.
2104
2105 Returns:
2106 wx.Colour: The colour used for the menu foreground.
2107 """
2108 renderer = self._renderers[self.GetMenuTheme()]
2109 return renderer.GetMenuFaceColour()
2110
2111 def GetTextColourEnable(self) -> wx.Colour: # noqa: N802
2112 """Return the colour used for enabled menu items.
2113
2114 Returns:
2115 wx.Colour: The colour used for enabled menu items.
2116 """
2117 renderer = self._renderers[self.GetMenuTheme()]
2118 return renderer.GetTextColourEnable()
2119
2120 def GetTextColourDisable(self) -> wx.Font: # noqa: N802
2121 """Return the colour used for disabled menu items.
2122
2123 Returns:
2124 wx.Colour: The colour used for disabled menu items.
2125 """
2126 renderer = self._renderers[self.GetMenuTheme()]
2127 return renderer.GetTextColourDisable()
2128
2129 def GetFont(self) -> wx.Font: # noqa: N802
2130 """Return the font used by this theme.
2131
2132 Returns:
2133 wx.Font: The font used by this theme.
2134 """
2135 renderer = self._renderers[self.GetMenuTheme()]
2136 return renderer.GetFont()
2137
2138 def GetAccelIndex(self, label: str) -> tuple[int, str]: # noqa: N802
2139 """Return the mnemonic index and the label without the ampersand mnemonic.
2140
2141 (e.g. 'lab&el' ==> will result in 3 and labelOnly = label).
2142
2143 Args:
2144 label (str): A string containing an ampersand.
2145
2146 Returns:
2147 tuple[int, str]: A tuple containing the mnemonic index of the label
2148 and the label stripped of the ampersand mnemonic.
2149 """
2150 index_accel = 0
2151 while True:
2152 index_accel = label.find("&", index_accel)
2153 if index_accel == -1:
2154 return index_accel, label
2155 if label[index_accel : index_accel + 2] == "&&":
2156 label = label[0:index_accel] + label[index_accel + 1 :]
2157 index_accel += 1
2158 else:
2159 break
2160
2161 label_only = label[0:index_accel] + label[index_accel + 1 :]
2162
2163 return index_accel, label_only
2164
2165 def GetThemeBaseColour(self, use_light_colours: None | bool = True) -> wx.Colour: # noqa: N802
2166 """Return the theme base colour.
2167
2168 If no theme is active, return the active caption colour lightened by 30%.
2169
2170 Args:
2171 use_light_colours (None | bool): ``True`` to use light colours,
2172 ``False`` otherwise.
2173
2174 Returns:
2175 wx.Colour: The theme base colour or the 30% lightened active caption
2176 colour.
2177 """
2178 if not use_light_colours and not self.IsDark(self.FrameColour()):
2179 return wx.Colour("GOLD")
2180 return self.LightColour(self.FrameColour(), 30)
2181
2182 def GetAlignBuffer(self) -> int: # noqa: N802
2183 """Return the padding buffer for a text or bitmap.
2184
2185 Returns:
2186 int: An integer representing the padding buffer.
2187 """
2188 return self._alignment_buffer
2189
2190 def SetMenuTheme(self, theme: int) -> None: # noqa: N802
2191 """Set the menu theme, possible values (Style2007, StyleXP, StyleVista).
2192
2193 Args:
2194 theme (int): A rendering theme class, either `StyleXP`, `Style2007` or
2195 `StyleVista`.
2196 """
2197 self._menu_theme = theme
2198
2199 def GetMenuTheme(self) -> int: # noqa: N802
2200 """Return the currently used menu theme.
2201
2202 Returns:
2203 int: An int containing the currently used theme for the menu.
2204 """
2205 return self._menu_theme
2206
2207 def AddMenuTheme(self, render: RendererBase) -> int: # noqa: N802
2208 """Add a new theme to the stock.
2209
2210 Args:
2211 render (RendererBase): A rendering theme class, which must be
2212 derived from :class:`RendererBase`.
2213
2214 Returns:
2215 int: An integer representing the size of the renderers dictionary.
2216 """
2217 # Add new theme
2218 last_renderer = len(self._renderers)
2219 self._renderers[last_renderer] = render
2220
2221 return last_renderer
2222
2223 def SetMS2007ButtonSunken(self, sunken: bool) -> None: # noqa: N802
2224 """Set MS 2007 button style sunken or not.
2225
2226 Args:
2227 sunken (bool): ``True`` to have a sunken border effect, ``False``
2228 otherwise.
2229 """
2230 self._ms2007sunken = sunken
2231
2232 def GetMS2007ButtonSunken(self) -> bool: # noqa: N802
2233 """Return the sunken flag for MS 2007 buttons.
2234
2235 Returns:
2236 bool: ``True`` if the MS 2007 buttons are sunken, ``False`` otherwise.
2237 """
2238 return self._ms2007sunken
2239
2240 def GetMBVerticalGradient(self) -> bool: # noqa: N802
2241 """Return ``True`` if the menu bar should be painted with vertical gradient.
2242
2243 Returns:
2244 bool: A boolean indicating whether the menu bar should be painted with
2245 vertical gradient.
2246 """
2247 return self._vertical_gradient
2248
2249 def SetMBVerticalGradient(self, v: bool) -> None: # noqa: N802
2250 """Set the menu bar gradient style.
2251
2252 Args:
2253 v (bool): ``True`` for a vertical shaded gradient, ``False`` otherwise.
2254 """
2255 self._vertical_gradient = v
2256
2257 def DrawMenuBarBorder(self, border: bool) -> None: # noqa: N802
2258 """Enable menu border drawing (XP style only).
2259
2260 Args:
2261 border (bool): ``True`` to draw the menubar border, ``False`` otherwise.
2262 """
2263 self._draw_mb_border = border
2264
2265 def GetMenuBarBorder(self) -> bool: # noqa: N802
2266 """Return menu bar border drawing flag.
2267
2268 Returns:
2269 bool: ``True`` if the menu bar border is to be drawn, ``False`` otherwise.
2270 """
2271 return self._draw_mb_border
2272
2273 def GetMenuBgFactor(self) -> int: # noqa: N802
2274 """Return the visibility depth of the menu in Metallic style.
2275
2276 The higher the value, the menu bar will look more raised.
2277
2278 Returns:
2279 int: An integer representing the visibility depth of the menu.
2280 """
2281 return self._menu_bg_factor
2282
2283 def DrawDragSash(self, rect: wx.Rect) -> None: # noqa: N802
2284 """Draw resize sash.
2285
2286 Args:
2287 rect (wx.Rect): The sash client rectangle.
2288 """
2289 dc = wx.ScreenDC()
2290 mem_dc = wx.MemoryDC()
2291
2292 bmp = wx.Bitmap(rect.width, rect.height)
2293 mem_dc.SelectObject(bmp)
2294 mem_dc.SetBrush(wx.WHITE_BRUSH)
2295 mem_dc.SetPen(wx.Pen(wx.WHITE, 1))
2296 mem_dc.DrawRectangle(0, 0, rect.width, rect.height)
2297
2298 dc.Blit(rect.x, rect.y, rect.width, rect.height, mem_dc, 0, 0, wx.XOR)
2299
2300 def TakeScreenShot(self, rect: wx.Rect, bmp: wx.Bitmap) -> None: # noqa: N802
2301 """Take a screenshot of the screen at given position & size (rect).
2302
2303 Args:
2304 rect (wx.Rect): The screen rectangle we wish to capture.
2305 bmp (wx.Bitmap): Currently unused.
2306 """
2307 # Create a DC for the whole screen area
2308 dc_screen = wx.ScreenDC()
2309
2310 # Create a Bitmap that will later on hold the screenshot image
2311 # Note that the Bitmap must have a size big enough to hold the screenshot
2312 # -1 means using the current default colour depth
2313 bmp = wx.Bitmap(rect.width, rect.height)
2314
2315 # Create a memory DC that will be used for actually taking the screenshot
2316 mem_dc = wx.MemoryDC()
2317
2318 # Tell the memory DC to use our Bitmap
2319 # all drawing action on the memory DC will go to the Bitmap now
2320 mem_dc.SelectObject(bmp)
2321
2322 # Blit (in this case copy)
2323 # the actual screen on the memory DC and thus the Bitmap
2324 mem_dc.Blit(
2325 0, # Copy to this X coordinate
2326 0, # Copy to this Y coordinate
2327 rect.width, # Copy this width
2328 rect.height, # Copy this height
2329 dc_screen, # From where do we copy?
2330 rect.x, # What's the X offset in the original DC?
2331 rect.y, # What's the Y offset in the original DC?
2332 )
2333
2334 # Select the Bitmap out of the memory DC by selecting a new uninitialized Bitmap
2335 mem_dc.SelectObject(wx.NullBitmap)
2336
2337 def DrawToolBarBg(self, dc: wx.DC, rect: wx.Rect) -> None: # noqa: N802
2338 """Draw the toolbar background according to the active theme.
2339
2340 Args:
2341 dc (wx.DC): A :class:`wx.DC` instance.
2342 rect (wx.Rect): The toolbar's client rectangle.
2343 """
2344 renderer = self._renderers[self.GetMenuTheme()]
2345
2346 # Set background colour if non given by caller
2347 renderer.DrawToolBarBg(dc, rect)
2348
2349 def DrawMenuBarBg(self, dc: wx.DC, rect: wx.Rect) -> None: # noqa: N802
2350 """Draw the menu bar background according to the active theme.
2351
2352 Args:
2353 dc (wx.DC): A :class:`wx.DC` instance.
2354 rect (wx.Rect): The menubar's client rectangle.
2355 """
2356 renderer = self._renderers[self.GetMenuTheme()]
2357 # Set background colour if non given by caller
2358 renderer.DrawMenuBarBg(dc, rect)
2359
2360 def SetMenuBarColour(self, scheme: str) -> None: # noqa: N802
2361 """Set the menu bar colour scheme to use.
2362
2363 Args:
2364 scheme (str): A string representing a colour scheme (i.e., 'Default',
2365 'Dark', 'Dark Olive Green', 'Generic').
2366 """
2367 self._menu_bar_colour_scheme = scheme
2368 # set default colour
2369 if scheme in self._colourSchemeMap:
2370 self._menuBarBgColour = self._colourSchemeMap[scheme]
2371
2372 def GetMenuBarColourScheme(self) -> str: # noqa: N802
2373 """Return the current colour scheme.
2374
2375 Returns:
2376 str: A string representing the current colour scheme.
2377 """
2378 return self._menu_bar_colour_scheme
2379
2380 def GetMenuBarFaceColour(self) -> wx.Colour: # noqa: N802
2381 """Return the menu bar face colour.
2382
2383 Returns:
2384 wx.Colour: The menu bar face colour.
2385 """
2386 return self._menuBarBgColour
2387
2388 def GetMenuBarSelectionColour(self) -> wx.Colour: # noqa: N802
2389 """Return the menu bar selection colour.
2390
2391 Returns:
2392 wx.Colour: The menu bar selection colour.
2393 """
2394 return self._menuBarSelColour
2395
2396 def InitColours(self) -> None: # noqa: N802
2397 """Initialise the colour map."""
2398 self._colourSchemeMap = {
2399 _("Default"): wx.SystemSettings.GetColour(wx.SYS_COLOUR_3DFACE),
2400 _("Dark"): wx.BLACK,
2401 _("Dark Olive Green"): wx.Colour("DARK OLIVE GREEN"),
2402 _("Generic"): wx.SystemSettings.GetColour(wx.SYS_COLOUR_ACTIVECAPTION),
2403 }
2404
2405 def GetColourSchemes(self) -> list[str]: # noqa: N802
2406 """Return the available colour schemes.
2407
2408 Returns:
2409 list[str]: A list of strings representing the available colour
2410 schemes.
2411 """
2412 return list(self._colourSchemeMap)
2413
2414 def CreateGreyBitmap(self, bmp: wx.Bitmap) -> wx.Bitmap: # noqa: N802
2415 """Create a grey bitmap image from the input bitmap.
2416
2417 Args:
2418 bmp (wx.Bitmap): A valid :class:`wx.Bitmap` object to be greyed out.
2419
2420 Returns:
2421 wx.Bitmap: A greyed-out representation of the input bitmap.
2422 """
2423 img = bmp.ConvertToImage()
2424 return wx.Bitmap(img.ConvertToGreyscale())
2425
2426 def GetRaiseToolbar(self) -> bool: # noqa: N802
2427 """Return ``True`` if we are dropping a shadow under a toolbar.
2428
2429 Returns:
2430 bool: A boolean indicating whether a shadow is dropped under a
2431 toolbar.
2432 """
2433 return self._raise_trace_back
2434
2435 def SetRaiseToolbar(self, raise_: bool) -> None: # noqa: N802
2436 """Enable/disable toobar shadow drop.
2437
2438 Args:
2439 raise_ (bool): ``True`` to drop a shadow below a toolbar, ``False``
2440 otherwise.
2441 """
2442 self._raise_trace_back = raise_