Debian Codegraph @

DisplayCAL/lib/agw/labelbook.py

raw
1 # ------------------------------------------------------------------------------------ #
2 # LABELBOOK And FLATIMAGEBOOK Widgets wxPython IMPLEMENTATION
3 #
4 # Original C++ Code From Eran, embedded in the FlatMenu source code
5 #
6 #
7 # License: wxWidgets license
8 #
9 #
10 # Python Code By:
11 #
12 # Andrea Gavana, @ 03 Nov 2006
13 # Latest Revision: 22 Jan 2013, 21.00 GMT
14 #
15 #
16 # For All Kind Of Problems, Requests Of Enhancements And Bug Reports,
17 # Please Write To Me At:
18 #
19 # [email protected]
20 # [email protected]
21 #
22 # Or, Obviously, To The wxPython Mailing List!!!
23 #
24 # TODO:
25 # LabelBook - Support IMB_SHOW_ONLY_IMAGES
26 # LabelBook - An option to only draw the border between the controls and the pages so
27 # the background colour can flow into the window background
28 #
29 # Tags: phoenix-port, unittest, documented, py3-port
30 #
31 #
32 # End Of Comments
33 # ------------------------------------------------------------------------------------ #
34
35 """LabelBook and FlatImageBook are owner-drawn notebooks.
36
37 Description
38 ===========
39
40 :class:`LabelBook` and :class:`FlatImageBook` are quasi-full implementations of the
41 :class:`Notebook`, and designed to be a drop-in replacement for :class:`Notebook`.
42 The API functions are similar so one can expect the function to behave in the same way.
43 :class:`LabelBook` and :class:`FlatImageBook` share their appearance with
44 :class:`Toolbook` and :class:`Listbook`, while having more options for custom drawings,
45 label positioning, mouse pointing and so on.
46 Moreover, they retain also some visual characteristics of the Outlook address book.
47
48 Some features:
49
50 - They are generic controls;
51 - Supports for left, right, top (:class:`FlatImageBook` only),
52 bottom (:class:`FlatImageBook` only) book styles;
53 - Possibility to draw images only, text only or both (:class:`FlatImageBook` only);
54 - Support for a "pin-button", that allows the user to shrink/expand the book tab area;
55 - Shadows behind tabs (:class:`LabelBook` only);
56 - Gradient shading of the tab area (:class:`LabelBook` only);
57 - Web-like mouse pointing on tabs style (:class:`LabelBook` only);
58 - Many customizable colours
59 (tab area, active tab text, tab borders, active tab, highlight)
60 :class:`LabelBook` only.
61
62 And much more. See the demo for a quasi-complete review of all the functionalities of
63 :class:`LabelBook` and :class:`FlatImageBook`.
64
65
66 Usage
67 =====
68
69 Usage example::
70
71 import wx
72 import wx.lib.agw.labelbook as LB
73
74
75 class MyFrame(wx.Frame):
76
77 def __init__(self, parent: None | wx.Window) -> None:
78 wx.Frame.__init__(self, parent, -1, "LabelBook Demo")
79
80 # Possible values for Tab placement are INB_TOP, INB_BOTTOM, INB_RIGHT, INB_LEFT
81 notebook = LB.LabelBook(
82 self,
83 -1,
84 agw_style=LB.INB_FIT_LABELTEXT
85 | LB.INB_LEFT
86 | LB.INB_DRAW_SHADOW
87 | LB.INB_GRADIENT_BACKGROUND,
88 )
89
90 pane1 = wx.Panel(notebook)
91 pane2 = wx.Panel(notebook)
92
93 imagelist = wx.ImageList(32, 32)
94 imagelist.Add(wx.Bitmap("my_bitmap.png", wx.BITMAP_TYPE_PNG))
95 notebook.AssignImageList(imagelist)
96
97 notebook.AddPage(pane1, "Tab1", True, 0)
98 notebook.AddPage(pane2, "Tab2", False, 0)
99
100
101 # our normal wxApp-derived class, as usual
102 app = wx.App(False)
103
104 frame = MyFrame(None)
105 app.SetTopWindow(frame)
106 frame.Show()
107
108 app.MainLoop()
109
110 Supported Platforms
111 ===================
112
113 :class:`LabelBook` and :class:`FlatImageBook` have been tested on the following
114 platforms:
115 * Windows (Windows XP);
116 * Linux Ubuntu (Dapper 6.06)
117
118
119 Window Styles
120 =============
121
122 This class supports the following window styles:
123
124 =========================== =========== ================================================
125 Window Styles Hex Value Description
126 =========================== =========== ================================================
127 ``INB_BOTTOM`` 0x1 Place labels below the page area.
128 Available only for :class:`FlatImageBook`.
129 ``INB_LEFT`` 0x2 Place labels on the left side.
130 Available only for :class:`FlatImageBook`.
131 ``INB_RIGHT`` 0x4 Place labels on the right side.
132 ``INB_TOP`` 0x8 Place labels above the page area.
133 ``INB_BORDER`` 0x10 Draws a border around :class:`LabelBook` or
134 :class:`FlatImageBook`.
135 ``INB_SHOW_ONLY_TEXT`` 0x20 Shows only text labels and no images.
136 Available only for :class:`LabelBook`.
137 ``INB_SHOW_ONLY_IMAGES`` 0x40 Shows only tab images and no label texts.
138 Available only for :class:`LabelBook`.
139 ``INB_FIT_BUTTON`` 0x80 Displays a pin button to show/hide the book
140 control.
141 ``INB_DRAW_SHADOW`` 0x100 Draw shadows below the book tabs.
142 Available only for :class:`LabelBook`.
143 ``INB_USE_PIN_BUTTON`` 0x200 Displays a pin button to show/hide the book
144 control.
145 ``INB_GRADIENT_BACKGROUND`` 0x400 Draws a gradient shading on the tabs background.
146 Available only for :class:`LabelBook`.
147 ``INB_WEB_HILITE`` 0x800 On mouse hovering,
148 tabs behave like html hyperlinks.
149 Available only for :class:`LabelBook`.
150 ``INB_NO_RESIZE`` 0x1000 Don't allow resizing of the tab area.
151 ``INB_FIT_LABELTEXT`` 0x2000 Will fit the tab area to the longest text (or
152 text+image if you have images) in all the tabs.
153 ``INB_BOLD_TAB_SELECTION`` 0x4000 Show the selected tab text using a bold font.
154 =========================== =========== ================================================
155
156
157 Events Processing
158 =================
159
160 This class processes the following events:
161
162 =================================== ====================================================
163 Event Name Description
164 =================================== ====================================================
165 ``EVT_IMAGENOTEBOOK_PAGE_CHANGED`` Notify client objects when the active page in
166 :class:`FlatImageBook` or :class:`LabelBook` has
167 changed.
168 ``EVT_IMAGENOTEBOOK_PAGE_CHANGING`` Notify client objects when the active page in
169 :class:`FlatImageBook` or :class:`LabelBook` is
170 about to change.
171 ``EVT_IMAGENOTEBOOK_PAGE_CLOSED`` Notify client objects when a page in
172 :class:`FlatImageBook` or :class:`LabelBook` has
173 been closed.
174 ``EVT_IMAGENOTEBOOK_PAGE_CLOSING`` Notify client objects when a page in
175 :class:`FlatImageBook` or :class:`LabelBook` is
176 closing.
177 =================================== ====================================================
178
179
180 TODOs
181 =====
182
183 - :class:`LabelBook`: support ``IMB_SHOW_ONLY_IMAGES``;
184 - :class:`LabelBook`: an option to only draw the border between the controls and the
185 pages so the background colour can flow into the window background.
186
187
188 License And Version
189 ===================
190
191 :class:`LabelBook` and :class:`FlatImageBook` are distributed under the wxPython
192 license.
193
194 Latest Revision: Andrea Gavana @ 22 Jan 2013, 21.00 GMT
195
196 Version 0.6.
197 """
198
199 from __future__ import annotations
200
201 __version__ = "0.6"
202
203
204 # ------------------------------------------------------------------------------------ #
205 # Beginning Of IMAGENOTEBOOK wxPython Code
206 # ------------------------------------------------------------------------------------ #
207
208 from enum import IntFlag
209
210 import wx
211
212 from DisplayCAL.lib.agw.artmanager import ArtManager, DCSaver
213 from DisplayCAL.lib.agw.fmresources import (
214 BOTTOM_SHADOW,
215 BOTTOM_SHADOW_FULL,
216 IMG_NONE,
217 IMG_OVER_EW_BORDER,
218 IMG_OVER_IMG,
219 IMG_OVER_PIN,
220 INB_ACTIVE_TAB_COLOUR,
221 INB_ACTIVE_TEXT_COLOUR,
222 INB_HILITE_TAB_COLOUR,
223 INB_PIN_HOVER,
224 INB_PIN_NONE,
225 INB_PIN_PRESSED,
226 INB_TAB_AREA_BACKGROUND_COLOUR,
227 INB_TABS_BORDER_COLOUR,
228 INB_TEXT_COLOUR,
229 PIN_DOWN_XPM,
230 PIN_LEFT_XPM,
231 RIGHT_SHADOW,
232 )
233
234
235 class ImageBookStyle(IntFlag):
236 """This class that defines the styles for the LabelBook and FlatImageBook."""
237
238 INB_BOTTOM = 1
239 """Place labels below the page area.
240
241 Available only for :class:`FlatImageBook`.
242 """
243 INB_LEFT = 2
244 """Place labels on the left side.
245
246 Available only for :class:`FlatImageBook`.
247 """
248 INB_RIGHT = 4
249 """Place labels on the right side."""
250 INB_TOP = 8
251 """Place labels above the page area."""
252 INB_BORDER = 16
253 """Draw a border around :class:`LabelBook` or :class:`FlatImageBook`."""
254 INB_SHOW_ONLY_TEXT = 32
255 """Show only text labels and no images.
256
257 Available only for :class:`LabelBook`.
258 """
259 INB_SHOW_ONLY_IMAGES = 64
260 """Show only tab images and no label texts.
261
262 Available only for :class:`LabelBook`.
263 """
264 INB_FIT_BUTTON = 128
265 """Display a pin button to show/hide the book control."""
266 INB_DRAW_SHADOW = 256
267 """Draw shadows below the book tabs.
268
269 Available only for :class:`LabelBook`.
270 """
271 INB_USE_PIN_BUTTON = 512
272 """Display a pin button to show/hide the book control."""
273 INB_GRADIENT_BACKGROUND = 1024
274 """Draw a gradient shading on the tabs background.
275
276 Available only for :class:`LabelBook`.
277 """
278 INB_WEB_HILITE = 2048
279 """On mouse hovering, tabs behave like html hyperlinks.
280
281 Available only for :class:`LabelBook`.
282 """
283 INB_NO_RESIZE = 4096
284 """Don't allow resizing of the tab area."""
285 INB_FIT_LABELTEXT = 8192
286 """Fit the tab area to the longest text (or text+image)."""
287 INB_BOLD_TAB_SELECTION = 16384
288 """Show the selected tab text using a bold font."""
289
290
291 wxEVT_IMAGENOTEBOOK_PAGE_CHANGED: int = wx.wxEVT_COMMAND_NOTEBOOK_PAGE_CHANGED # noqa: N816
292 wxEVT_IMAGENOTEBOOK_PAGE_CHANGING: int = wx.wxEVT_COMMAND_NOTEBOOK_PAGE_CHANGING # noqa: N816
293 wxEVT_IMAGENOTEBOOK_PAGE_CLOSING: int = wx.NewEventType() # noqa: N816
294 wxEVT_IMAGENOTEBOOK_PAGE_CLOSED: int = wx.NewEventType() # noqa: N816
295
296 # ------------------------------------------------------------------------------------ #
297 # ImageNotebookEvent
298 # ------------------------------------------------------------------------------------ #
299
300 EVT_IMAGENOTEBOOK_PAGE_CHANGED: wx.PyEventBinder = wx.EVT_NOTEBOOK_PAGE_CHANGED
301 """Notify clients when the active page in FlatImageBook or LabelBook changes."""
302 EVT_IMAGENOTEBOOK_PAGE_CHANGING: wx.PyEventBinder = wx.EVT_NOTEBOOK_PAGE_CHANGING
303 """Notify clients when the active page changes."""
304 EVT_IMAGENOTEBOOK_PAGE_CLOSING = wx.PyEventBinder(wxEVT_IMAGENOTEBOOK_PAGE_CLOSING, 1)
305 """Notify clients when a page in :class:`FlatImageBook` or :class:`LabelBook` closes."""
306 EVT_IMAGENOTEBOOK_PAGE_CLOSED = wx.PyEventBinder(wxEVT_IMAGENOTEBOOK_PAGE_CLOSED, 1)
307 """Notify clients when a page in FlatImageBook or LabelBook is closed."""
308
309
310 # ------------------------------------------------------------------------------------ #
311 # Class ImageNotebookEvent
312 # ------------------------------------------------------------------------------------ #
313
314
315 class ImageNotebookEvent(wx.PyCommandEvent):
316 """These events are sent when page changes or closures are mapped in the parent."""
317
318 def __init__(
319 self, event_type: int, event_id: int = 1, sel: int = -1, old_sel: int = -1
320 ) -> None:
321 """Construct the default class.
322
323 Args:
324 event_type (int): the event type;
325 event_id (int): the event identifier;
326 sel (int): the current selection;
327 old_sel (int): the old selection.
328 """
329 wx.PyCommandEvent.__init__(self, event_type, event_id)
330 self._eventType: int = event_type
331 self._sel: int = sel
332 self._oldsel: int = old_sel
333 self._allowed = True
334
335 def SetSelection(self, s: int) -> None: # noqa: N802
336 """Set the event selection.
337
338 Args:
339 s (int): an integer specifying the new selection.
340 """
341 self._sel = s
342
343 def SetOldSelection(self, s: int) -> None: # noqa: N802
344 """Set the event old selection.
345
346 Args:
347 s (int): an integer specifying the old selection.
348 """
349 self._oldsel = s
350
351 def GetSelection(self) -> int: # noqa: N802
352 """Return the event selection."""
353 return self._sel
354
355 def GetOldSelection(self) -> int: # noqa: N802
356 """Return the old event selection."""
357 return self._oldsel
358
359 def Veto(self) -> None: # noqa: N802
360 """Prevent the change announced by this event from happening.
361
362 Note:
363 It is in general a good idea to notify the user about the reasons for
364 vetoing the change because otherwise the applications behaviour
365 (which just refuses to do what the user wants) might be quite surprising.
366 """
367 self._allowed = False
368
369 def Allow(self) -> None: # noqa: N802
370 """Explicitly allow the event to be processed.
371
372 This is the opposite of :meth:`~ImageNotebookEvent.Veto`.
373 For most events it is not necessary to call this method as the events are
374 allowed anyhow but some are forbidden by default
375 (this will be mentioned in the corresponding event description).
376 """
377 self._allowed = True
378
379 def IsAllowed(self) -> bool: # noqa: N802
380 """Return ``True`` if allowed, ``False`` if vetoed."""
381 return self._allowed
382
383
384 # ------------------------------------------------------------------------------------ #
385 # Class ImageInfo
386 # ------------------------------------------------------------------------------------ #
387
388
389 class ImageInfo:
390 """This class stores tab info (caption, image, etc.) for :class:`LabelBook`."""
391
392 def __init__(
393 self, str_caption: str = "", image_index: int = -1, enabled: bool = True
394 ) -> None:
395 """Construct the default class.
396
397 Args:
398 str_caption (str): The tab caption.
399 image_index (int): the tab image index based on the assigned (set)
400 :class:`wx.ImageList` (if any).
401 enabled (bool): sets the tab as enabled or disabled.
402 """
403 self._pos = wx.Point()
404 self._size = wx.Size()
405 self._strCaption: str = str_caption
406 self._ImageIndex: int = image_index
407 self._captionRect = wx.Rect()
408 self._bEnabled: bool = enabled
409
410 def SetCaption(self, value: str) -> None: # noqa: N802
411 """Set the tab caption.
412
413 Args:
414 value (str): the new tab caption.
415 """
416 self._strCaption = value
417
418 def GetCaption(self) -> str: # noqa: N802
419 """Return the tab caption."""
420 return self._strCaption
421
422 def SetPosition(self, value: wx.Point) -> None: # noqa: N802
423 """Set the tab position.
424
425 Args:
426 value (wx.Point): the new tab position, an instance of :class:`wx.Point`.
427 """
428 self._pos: wx.Point = value
429
430 def GetPosition(self) -> wx.Point: # noqa: N802
431 """Return the tab position."""
432 return self._pos
433
434 def SetSize(self, value: wx.Size) -> None: # noqa: N802
435 """Set the tab size.
436
437 Args:
438 value (wx.Size): the new tab size, an instance of :class:`wx.Size`.
439 """
440 self._size: wx.Size = value
441
442 def GetSize(self) -> wx.Size: # noqa: N802
443 """Return the tab size."""
444 return self._size
445
446 def SetImageIndex(self, value: int) -> None: # noqa: N802
447 """Set the tab image index.
448
449 Args:
450 value (int): an index into the image list..
451 """
452 self._ImageIndex = value
453
454 def GetImageIndex(self) -> int: # noqa: N802
455 """Return the tab image index."""
456 return self._ImageIndex
457
458 def SetTextRect(self, rect: wx.Rect) -> None: # noqa: N802
459 """Set the client rectangle available for the tab text.
460
461 Args:
462 rect (wx.Rect): the tab text client rectangle,
463 an instance of :class:`wx.Rect`.
464 """
465 self._captionRect: wx.Rect = rect
466
467 def GetTextRect(self) -> wx.Rect: # noqa: N802
468 """Return the client rectangle available for the tab text."""
469 return self._captionRect
470
471 def GetEnabled(self) -> bool: # noqa: N802
472 """Return whether the tab is enabled or not."""
473 return self._bEnabled
474
475 def EnableTab(self, enabled: bool) -> None: # noqa: N802
476 """Set the tab enabled or disabled.
477
478 Args:
479 enabled (bool): ``True`` to enable a tab, ``False`` to disable it.
480 """
481 self._bEnabled = enabled
482
483
484 # ------------------------------------------------------------------------------------ #
485 # Class ImageContainerBase
486 # ------------------------------------------------------------------------------------ #
487
488
489 class ImageContainerBase(wx.Panel):
490 """Base class for :class:`FlatImageBook` image container."""
491
492 def __init__(
493 self,
494 parent: wx.Window,
495 id: int = wx.ID_ANY, # noqa: A002
496 pos: wx.Point = wx.DefaultPosition,
497 size: wx.Size = wx.DefaultSize,
498 style: int = 0,
499 agw_style: int = 0,
500 name: str = "ImageContainerBase",
501 ) -> None:
502 """Construct the default class.
503
504 Args:
505 parent (wx.Window): parent window. Must not be ``None``;
506 id (int): window identifier. A value of -1 indicates a default value;
507 pos (wx.Point): the control position.
508 A value of (-1, -1) indicates a default position, chosen by either the
509 windowing system or wxPython, depending on platform;
510 size (wx.Size): the control size.
511 A value of (-1, -1) indicates a default size, chosen by either the
512 windowing system or wxPython, depending on platform;
513 style (int): the underlying :class:`Panel` window style;
514 agw_style (int): the AGW-specific window style.
515 This can be a combination of the following bits:
516 =========================== =========== ================================
517 Window Styles Hex Value Description
518 =========================== =========== ================================
519 ``INB_BOTTOM`` 0x1 Place labels below the page
520 area. Available only for
521 :class:`FlatImageBook`.
522 ``INB_LEFT`` 0x2 Place labels on the left side.
523 Available only for
524 :class:`FlatImageBook`.
525 ``INB_RIGHT`` 0x4 Place labels on the right side.
526 ``INB_TOP`` 0x8 Place labels above the page
527 area.
528 ``INB_BORDER`` 0x10 Draws a border around
529 :class:`LabelBook` or
530 :class:`FlatImageBook`.
531 ``INB_SHOW_ONLY_TEXT`` 0x20 Shows only text labels and no
532 images. Available only for
533 :class:`LabelBook`.
534 ``INB_SHOW_ONLY_IMAGES`` 0x40 Shows only tab images and no
535 label texts. Available only for
536 :class:`LabelBook`.
537 ``INB_FIT_BUTTON`` 0x80 Displays a pin button to
538 show/hide the book control.
539 ``INB_DRAW_SHADOW`` 0x100 Draw shadows below the book
540 tabs. Available only for
541 :class:`LabelBook`.
542 ``INB_USE_PIN_BUTTON`` 0x200 Displays a pin button to
543 show/hide the book control.
544 ``INB_GRADIENT_BACKGROUND`` 0x400 Draws a gradient shading on the
545 tabs background. Available only
546 for :class:`LabelBook`.
547 ``INB_WEB_HILITE`` 0x800 On mouse hovering, tabs behave
548 like html hyperlinks. Available
549 only for :class:`LabelBook`.
550 ``INB_NO_RESIZE`` 0x1000 Don't allow resizing of the tab
551 area.
552 ``INB_FIT_LABELTEXT`` 0x2000 Will fit the tab area to the
553 longest text (or text+image if
554 you have images) in all the
555 tabs.
556 ``INB_BOLD_TAB_SELECTION`` 0x4000 Show the selected tab text using
557 a bold font.
558 =========================== =========== ================================
559 name (str): the window name.
560 """
561 self._nIndex = -1
562 self._nImgSize = 16
563 self._ImageList = None
564 self._nHoveredImgIdx = -1
565 self._bCollapsed = False
566 self._tabAreaSize: wx.Size = wx.Size(-1, -1)
567 self._nPinButtonStatus: int = INB_PIN_NONE
568 self._pagesInfoVec: list[ImageInfo] = []
569 self._pinBtnRect: wx.Rect = wx.Rect()
570
571 wx.Panel.__init__(
572 self,
573 parent,
574 id,
575 pos,
576 size,
577 style | wx.NO_BORDER | wx.NO_FULL_REPAINT_ON_RESIZE,
578 name,
579 )
580
581 def HasAGWFlag(self, flag: int) -> bool: # noqa: N802
582 """Test for existence of flag in the style.
583
584 Args:
585 flag (int): a window style. This can be a combination of the following bits:
586 =========================== =========== ================================
587 Window Styles Hex Value Description
588 =========================== =========== ================================
589 ``INB_BOTTOM`` 0x1 Place labels below the page
590 area. Available only for
591 :class:`FlatImageBook`.
592 ``INB_LEFT`` 0x2 Place labels on the left side.
593 Available only for
594 :class:`FlatImageBook`.
595 ``INB_RIGHT`` 0x4 Place labels on the right side.
596 ``INB_TOP`` 0x8 Place labels above the page
597 area.
598 ``INB_BORDER`` 0x10 Draws a border around
599 :class:`LabelBook` or
600 :class:`FlatImageBook`.
601 ``INB_SHOW_ONLY_TEXT`` 0x20 Shows only text labels and no
602 images. Available only for
603 :class:`LabelBook`.
604 ``INB_SHOW_ONLY_IMAGES`` 0x40 Shows only tab images and no
605 label texts. Available only for
606 :class:`LabelBook`.
607 ``INB_FIT_BUTTON`` 0x80 Displays a pin button to
608 show/hide the book control.
609 ``INB_DRAW_SHADOW`` 0x100 Draw shadows below the book
610 tabs. Available only for
611 :class:`LabelBook`.
612 ``INB_USE_PIN_BUTTON`` 0x200 Displays a pin button to
613 show/hide the book control.
614 ``INB_GRADIENT_BACKGROUND`` 0x400 Draws a gradient shading on the
615 tabs background. Available only
616 for :class:`LabelBook`.
617 ``INB_WEB_HILITE`` 0x800 On mouse hovering, tabs behave
618 like html hyperlinks. Available
619 only for :class:`LabelBook`.
620 ``INB_NO_RESIZE`` 0x1000 Don't allow resizing of the tab
621 area.
622 ``INB_FIT_LABELTEXT`` 0x2000 Will fit the tab area to the
623 longest text (or text+image if
624 you have images) in all the
625 tabs.
626 ``INB_BOLD_TAB_SELECTION`` 0x4000 Show the selected tab text using
627 a bold font.
628 =========================== =========== ================================
629 """
630 style: int = self.GetParent().GetAGWWindowStyleFlag()
631 res: bool = ((style & flag and [True]) or [False])[0]
632 return res
633
634 def ClearFlag(self, flag: int) -> None: # noqa: N802
635 """Remove flag from the style.
636
637 Args:
638 flag (int): a window style flag.
639
640 See:
641 :meth:`~ImageContainerBase.HasAGWFlag` for a list of possible window style
642 flags.
643 """
644 parent: wx.Window = self.GetParent()
645 agw_style: int = parent.GetAGWWindowStyleFlag()
646 agw_style &= ~flag
647 parent.SetAGWWindowStyleFlag(agw_style)
648
649 def AssignImageList(self, imglist: wx.ImageList) -> None: # noqa: N802
650 """Assign an image list to the :class:`wx.ImageContainerBase`.
651
652 Args:
653 imglist (wx.ImageList): an instance of :class:`wx.ImageList`.
654 """
655 if imglist and imglist.GetImageCount() != 0:
656 self._nImgSize: int = imglist.GetBitmap(0).GetHeight()
657
658 self._ImageList: None | wx.ImageList = imglist
659 parent: wx.Window = self.GetParent()
660 agw_style: int = parent.GetAGWWindowStyleFlag()
661 parent.SetAGWWindowStyleFlag(agw_style)
662
663 def GetImageList(self) -> None | wx.ImageList: # noqa: N802
664 """Return the image list for :class:`wx.ImageContainerBase`."""
665 return self._ImageList
666
667 def GetImageSize(self) -> int: # noqa: N802
668 """Return the image size in the :class:`wx.ImageContainerBase` image list."""
669 return self._nImgSize
670
671 def FixTextSize(self, dc: wx.DC, text: str, max_width: int) -> None | str: # noqa: N802
672 """Fix the text, to fit `maxWidth` value.
673
674 If the text length exceeds `maxWidth` value this function truncates it and
675 appends two dots at the end.
676 ("Long Long Long Text" might become "Long Long...").
677
678 Args:
679 dc (wx.DC): an instance of :class:`wx.DC`;
680 text (str): the text to fix/truncate;
681 max_width (int): the maximum allowed width for the text, in pixels.
682 """
683 return ArtManager.Get().TruncateText(dc, text, max_width)
684
685 def CanDoBottomStyle(self) -> bool: # noqa: N802
686 """Allow the parent to examine the children type.
687
688 Some implementation (such as :class:`LabelBook`),
689 does not support top/bottom images, only left/right.
690 """
691 return False
692
693 def AddPage(self, caption: str, selected: bool = False, image_id: int = -1) -> None: # noqa: N802
694 """Add a page to the container.
695
696 Args:
697 caption (str): specifies the text for the new tab;
698 selected (bool): specifies whether the page should be selected;
699 image_id (int): specifies the optional image index for the new tab.
700 """
701 self._pagesInfoVec.append(ImageInfo(caption, image_id))
702 if selected or len(self._pagesInfoVec) == 1:
703 self._nIndex: int = len(self._pagesInfoVec) - 1
704
705 self.Refresh()
706
707 def InsertPage( # noqa: N802
708 self, page_id: int, caption: str, selected: bool = False, image_id: int = -1
709 ) -> None:
710 """Insert a page into the container at the specified position.
711
712 Args:
713 page_id (int): specifies the position for the new tab;
714 caption (str): specifies the text for the new tab;
715 selected (bool): specifies whether the page should be selected;
716 image_id (int): specifies the optional image index for the new tab.
717 """
718 self._pagesInfoVec.insert(page_id, ImageInfo(caption, image_id))
719 if selected or len(self._pagesInfoVec) == 1:
720 self._nIndex = len(self._pagesInfoVec) - 1
721
722 self.Refresh()
723
724 def SetPageImage(self, page: int, image_id: int) -> None: # noqa: N802
725 """Set the image for the given page.
726
727 Args:
728 page (int): The index of the tab;
729 image_id (int): Specifies the optional image index for the tab.
730 """
731 image_info: ImageInfo = self._pagesInfoVec[page]
732 image_info.SetImageIndex(image_id)
733
734 def SetPageText(self, page: int, text: str) -> None: # noqa: N802
735 """Set the tab caption for the given page.
736
737 Args:
738 page (int): the index of the tab;
739 text (str): the new tab caption.
740 """
741 image_info: ImageInfo = self._pagesInfoVec[page]
742 image_info.SetCaption(text)
743
744 def GetPageImage(self, page: int) -> int: # noqa: N802
745 """Return the image index for the given page.
746
747 Args:
748 page (int): the index of the tab.
749 """
750 image_info: ImageInfo = self._pagesInfoVec[page]
751 return image_info.GetImageIndex()
752
753 def GetPageText(self, page: int) -> str: # noqa: N802
754 """Return the tab caption for the given page.
755
756 Args:
757 page (int): the index of the tab.
758 """
759 image_info: ImageInfo = self._pagesInfoVec[page]
760 return image_info.GetCaption()
761
762 def GetEnabled(self, page: int) -> bool: # noqa: N802
763 """Return whether a tab is enabled or not.
764
765 Args:
766 page (int): an integer specifying the page index.
767 """
768 if page >= len(self._pagesInfoVec):
769 return True # Adding a page - enabled by default
770
771 image_info: ImageInfo = self._pagesInfoVec[page]
772 return image_info.GetEnabled()
773
774 def EnableTab(self, page: int, enabled: bool = True) -> None: # noqa: N802
775 """Enable or disable a tab.
776
777 Args:
778 page (int): an integer specifying the page index;
779 enabled (bool): ``True`` to enable a tab, ``False`` to disable it.
780 """
781 if page >= len(self._pagesInfoVec):
782 return
783
784 image_info: ImageInfo = self._pagesInfoVec[page]
785 image_info.EnableTab(enabled)
786
787 def ClearAll(self) -> None: # noqa: N802
788 """Delete all the pages in the container."""
789 self._pagesInfoVec = []
790 self._nIndex = wx.NOT_FOUND
791
792 def DoDeletePage(self, page: int) -> None: # noqa: N802
793 """Delete the page.
794
795 Args:
796 page (int): the index of the tab.
797 """
798 # Remove the page from the vector
799 book: wx.Window = self.GetParent()
800 self._pagesInfoVec.pop(page)
801
802 if self._nIndex >= page:
803 self._nIndex = self._nIndex - 1
804
805 # The delete page was the last first on the array,
806 # but the book still has more pages, so we set the
807 # active page to be the first one (0)
808 if self._nIndex < 0 and len(self._pagesInfoVec) > 0:
809 self._nIndex = 0
810
811 # Refresh the tabs
812 if self._nIndex >= 0 and isinstance(book, FlatBookBase):
813 book._bForceSelection = True
814 book.SetSelection(self._nIndex)
815 book._bForceSelection = False
816
817 if not self._pagesInfoVec:
818 # Erase the page container drawings
819 dc = wx.ClientDC(self)
820 dc.Clear()
821
822 def OnSize(self, event: wx.SizeEvent) -> None: # noqa: N802
823 """Handle the wx.EVT_SIZE event for wx.ImageContainerBase.
824
825 Args:
826 event (wx.SizeEvent): a :class:`wx.SizeEvent` event to be processed.
827 """
828 self.Refresh() # Call on paint
829 event.Skip()
830
831 def OnEraseBackground(self, event: wx.EraseEvent) -> None: # noqa: N802
832 """Handle the wx.EVT_ERASE_BACKGROUND event for wx.ImageContainerBase.
833
834 Args:
835 event (wx.EraseEvent): a :class:`EraseEvent` event to be processed.
836
837 Note:
838 This method is intentionally empty to reduce flicker.
839 """
840
841 def HitTest(self, pt: wx.Point) -> tuple[int, int]: # noqa: N802
842 """Return the index of the tab at the specified position or NOT_FOUND if None.
843
844 plus the flag style of :meth:`~ImageContainerBase.HitTest`.
845
846 Args:
847 pt (wx.Point): an instance of :class:`wx.Point`, to test for hits.
848
849 Returns:
850 The index of the tab at the specified position plus the hit test flag,
851 which can be one of the following bits:
852 ====================== ======= =========================================
853 HitTest Flags Value Description
854 ====================== ======= =========================================
855 ``IMG_OVER_IMG`` 0 The mouse is over the tab icon
856 ``IMG_OVER_PIN`` 1 The mouse is over the pin button
857 ``IMG_OVER_EW_BORDER`` 2 The mouse is over the east-west book
858 border
859 ``IMG_NONE`` 3 Nowhere
860 ====================== ======= =========================================
861 """
862 style: int = self.GetParent().GetAGWWindowStyleFlag()
863
864 if style & ImageBookStyle.INB_USE_PIN_BUTTON and self._pinBtnRect.Contains(pt):
865 return -1, IMG_OVER_PIN
866
867 for i in range(len(self._pagesInfoVec)):
868 if self._pagesInfoVec[i].GetPosition() == wx.Point(-1, -1):
869 break
870
871 # For Web Hover style, we test the TextRect
872 if not self.HasAGWFlag(ImageBookStyle.INB_WEB_HILITE):
873 button_rect = wx.Rect(
874 self._pagesInfoVec[i].GetPosition(), self._pagesInfoVec[i].GetSize()
875 )
876 else:
877 button_rect: wx.Rect = self._pagesInfoVec[i].GetTextRect()
878
879 if button_rect.Contains(pt):
880 return i, IMG_OVER_IMG
881
882 if self.PointOnSash(pt):
883 return -1, IMG_OVER_EW_BORDER
884 return -1, IMG_NONE
885
886 def PointOnSash(self, pt: wx.Point) -> bool: # noqa: N802
887 """Test whether pt is located on the sash.
888
889 Args:
890 pt (wx.Point): an instance of :class:`wx.Point`, to test for hits.
891 """
892 # Check if we are on a the sash border
893 clt_rect: wx.Rect = self.GetClientRect()
894
895 if self.HasAGWFlag(ImageBookStyle.INB_LEFT) or self.HasAGWFlag(
896 ImageBookStyle.INB_TOP
897 ):
898 if pt.x > clt_rect.x + clt_rect.width - 4:
899 return True
900
901 elif pt.x < 4:
902 return True
903
904 return False
905
906 def OnMouseLeftDown(self, event: wx.MouseEvent) -> None: # noqa: N802
907 """Handle the ``wx.EVT_LEFT_DOWN`` event for :class:`wx.ImageContainerBase`.
908
909 Args:
910 event (wx.MouseEvent): a :class:`MouseEvent` event to be processed.
911 """
912 event.Skip()
913
914 # Support for collapse/expand
915 style: int = self.GetParent().GetAGWWindowStyleFlag()
916 if style & ImageBookStyle.INB_USE_PIN_BUTTON and self._pinBtnRect.Contains(
917 event.GetPosition()
918 ):
919 self._nPinButtonStatus = INB_PIN_PRESSED
920 dc = wx.ClientDC(self)
921 self.DrawPin(dc, self._pinBtnRect, not self._bCollapsed)
922 return
923
924 # In case panel is collapsed, there is nothing to check
925 if self._bCollapsed:
926 return
927
928 tab_id, where = self.HitTest(event.GetPosition())
929
930 if where == IMG_OVER_IMG:
931 self._nHoveredImgIdx = -1
932
933 if tab_id == -1:
934 return
935
936 self.GetParent().SetSelection(tab_id)
937
938 def OnMouseLeaveWindow(self, event: wx.MouseEvent) -> None: # noqa: N802
939 """Handle the ``wx.EVT_LEAVE_WINDOW`` event for :class:`wx.ImageContainerBase`.
940
941 Args:
942 event (wx.MouseEvent): a :class:`MouseEvent` event to be processed.
943 """
944 b_repaint: bool = self._nHoveredImgIdx != -1
945 self._nHoveredImgIdx = -1
946
947 # Make sure the pin button status is NONE in case we were in pin button style
948 style: int = self.GetParent().GetAGWWindowStyleFlag()
949
950 if style & ImageBookStyle.INB_USE_PIN_BUTTON:
951 self._nPinButtonStatus = INB_PIN_NONE
952 dc = wx.ClientDC(self)
953 self.DrawPin(dc, self._pinBtnRect, not self._bCollapsed)
954
955 # Restore cursor
956 self.SetCursor(wx.Cursor(wx.CURSOR_ARROW))
957
958 if b_repaint:
959 self.Refresh()
960
961 def OnMouseLeftUp(self, event: wx.MouseEvent) -> None: # noqa: N802
962 """Handle the ``wx.EVT_LEFT_UP`` event for :class:`wx.ImageContainerBase`.
963
964 Args:
965 event (wx.MouseEvent): a :class:`MouseEvent` event to be processed.
966 """
967 style: int = self.GetParent().GetAGWWindowStyleFlag()
968
969 if not style & ImageBookStyle.INB_USE_PIN_BUTTON:
970 return
971
972 b_is_label_container: bool = not self.CanDoBottomStyle()
973
974 if not self._pinBtnRect.Contains(event.GetPosition()):
975 return
976
977 self._nPinButtonStatus = INB_PIN_NONE
978 self._bCollapsed: bool = not self._bCollapsed
979
980 if self._bCollapsed:
981 # Save the current tab area width
982 self._tabAreaSize = self.GetSize()
983
984 if b_is_label_container:
985 self.SetSizeHints(20, self._tabAreaSize[1])
986
987 elif style & ImageBookStyle.INB_BOTTOM or style & ImageBookStyle.INB_TOP:
988 self.SetSizeHints(self._tabAreaSize[0], 20)
989 else:
990 self.SetSizeHints(20, self._tabAreaSize[1])
991
992 elif b_is_label_container:
993 self.SetSizeHints(self._tabAreaSize[0], -1)
994
995 # Restore the tab area size
996 elif style & ImageBookStyle.INB_BOTTOM or style & ImageBookStyle.INB_TOP:
997 self.SetSizeHints(-1, self._tabAreaSize[1])
998 else:
999 self.SetSizeHints(self._tabAreaSize[0], -1)
1000
1001 self.GetParent().GetSizer().Layout()
1002 self.Refresh()
1003 return
1004
1005 def OnMouseMove(self, event: wx.MouseEvent) -> None: # noqa: N802
1006 """Handle the ``wx.EVT_MOTION`` event for :class:`wx.ImageContainerBase`.
1007
1008 Args:
1009 event (wx.MouseEvent): a :class:`MouseEvent` event to be processed.
1010 """
1011 style: int = self.GetParent().GetAGWWindowStyleFlag()
1012 if style & ImageBookStyle.INB_USE_PIN_BUTTON and (
1013 not self._pinBtnRect.Contains(event.GetPosition())
1014 and self._nPinButtonStatus == INB_PIN_PRESSED
1015 ):
1016 # Check to see if we are in the pin button rect
1017 self._nPinButtonStatus = INB_PIN_NONE
1018 dc = wx.ClientDC(self)
1019 self.DrawPin(dc, self._pinBtnRect, not self._bCollapsed)
1020
1021 image_id, _ = self.HitTest(event.GetPosition())
1022
1023 # Allow hovering unless over current tab or tab is disabled
1024 self._nHoveredImgIdx = -1
1025
1026 if (
1027 image_id < len(self._pagesInfoVec)
1028 and self.GetEnabled(image_id)
1029 and image_id != self._nIndex
1030 ):
1031 self._nHoveredImgIdx: int = image_id
1032
1033 if not self._bCollapsed:
1034 if self._nHoveredImgIdx >= 0 and self.HasAGWFlag(
1035 ImageBookStyle.INB_WEB_HILITE
1036 ):
1037 # Change the cursor to be Hand if we have the Web hover style set
1038 self.SetCursor(wx.Cursor(wx.CURSOR_HAND))
1039
1040 elif not self.PointOnSash(event.GetPosition()):
1041 # Restore the cursor if we are not currently hovering the sash
1042 self.SetCursor(wx.Cursor(wx.CURSOR_ARROW))
1043
1044 self.Refresh()
1045
1046 def DrawPin(self, dc: wx.DC, rect: wx.Rect, down_pin: bool) -> None: # noqa: N802
1047 """Draw a pin button, that allows collapsing of the image panel.
1048
1049 Args:
1050 dc (wx.DC): an instance of :class:`wx.DC`;
1051 rect (wx.Rect): the pin button client rectangle;
1052 down_pin (bool): ``True`` if the pin button is facing downwards,
1053 ``False`` if it is facing leftwards.
1054 """
1055 # Set the bitmap according to the button status
1056 pin_bmp = wx.Bitmap(PIN_DOWN_XPM) if down_pin else wx.Bitmap(PIN_LEFT_XPM)
1057 xx: int = rect.x + 2
1058 if self._nPinButtonStatus in [INB_PIN_HOVER, INB_PIN_NONE]:
1059 dc.SetBrush(wx.TRANSPARENT_BRUSH)
1060 dc.SetPen(wx.BLACK_PEN)
1061 dc.DrawRectangle(xx, rect.y, 16, 16)
1062
1063 # Draw upper and left border with grey colour
1064 dc.SetPen(wx.WHITE_PEN)
1065 dc.DrawLine(xx, rect.y, xx + 16, rect.y)
1066 dc.DrawLine(xx, rect.y, xx, rect.y + 16)
1067
1068 elif self._nPinButtonStatus == INB_PIN_PRESSED:
1069 dc.SetBrush(wx.TRANSPARENT_BRUSH)
1070 dc.SetPen(wx.LIGHT_GREY_PEN)
1071 dc.DrawRectangle(xx, rect.y, 16, 16)
1072
1073 # Draw upper and left border with grey colour
1074 dc.SetPen(wx.BLACK_PEN)
1075 dc.DrawLine(xx, rect.y, xx + 16, rect.y)
1076 dc.DrawLine(xx, rect.y, xx, rect.y + 16)
1077
1078 # Set the masking
1079 pin_bmp.SetMask(wx.Mask(pin_bmp, wx.WHITE))
1080
1081 # Draw the new bitmap
1082 dc.DrawBitmap(pin_bmp, xx, rect.y, True)
1083
1084 # Save the pin rect
1085 self._pinBtnRect = rect
1086
1087
1088 # ------------------------------------------------------------------------------------ #
1089 # Class ImageContainer
1090 # ------------------------------------------------------------------------------------ #
1091
1092
1093 class ImageContainer(ImageContainerBase):
1094 """Base class for :class:`FlatImageBook` image container."""
1095
1096 def __init__(
1097 self,
1098 parent: wx.Window,
1099 id: int = wx.ID_ANY, # noqa: A002
1100 pos: wx.Point = wx.DefaultPosition,
1101 size: wx.Size = wx.DefaultSize,
1102 style: int = 0,
1103 agw_style: int = 0,
1104 name: str = "ImageContainer",
1105 ) -> None:
1106 """Construct the default class.
1107
1108 Args:
1109 parent (wx.Window): parent window. Must not be ``None``;
1110 id (int): window identifier. A value of -1 indicates a default value;
1111 pos (wx.Point): the control position.
1112 A value of (-1, -1) indicates a default position, chosen by either the
1113 windowing system or wxPython, depending on platform;
1114 size (wx.Size): the control size.
1115 A value of (-1, -1) indicates a default size, chosen by either the
1116 windowing system or wxPython, depending on platform;
1117 style (int): the underlying :class:`Panel` window style;
1118 agw_style (int): the AGW-specific window style.
1119 This can be a combination of the following bits:
1120 =========================== =========== ================================
1121 Window Styles Hex Value Description
1122 =========================== =========== ================================
1123 ``INB_BOTTOM`` 0x1 Place labels below the page
1124 area. Available only for
1125 :class:`FlatImageBook`.
1126 ``INB_LEFT`` 0x2 Place labels on the left side.
1127 Available only for
1128 :class:`FlatImageBook`.
1129 ``INB_RIGHT`` 0x4 Place labels on the right side.
1130 ``INB_TOP`` 0x8 Place labels above the page
1131 area.
1132 ``INB_BORDER`` 0x10 Draws a border around
1133 :class:`LabelBook` or
1134 :class:`FlatImageBook`.
1135 ``INB_SHOW_ONLY_TEXT`` 0x20 Shows only text labels and no
1136 images. Available only for
1137 :class:`LabelBook`.
1138 ``INB_SHOW_ONLY_IMAGES`` 0x40 Shows only tab images and no
1139 label texts. Available only for
1140 :class:`LabelBook`.
1141 ``INB_FIT_BUTTON`` 0x80 Displays a pin button to
1142 show/hide the book control.
1143 ``INB_DRAW_SHADOW`` 0x100 Draw shadows below the book
1144 tabs. Available only for
1145 :class:`LabelBook`.
1146 ``INB_USE_PIN_BUTTON`` 0x200 Displays a pin button to
1147 show/hide the book control.
1148 ``INB_GRADIENT_BACKGROUND`` 0x400 Draws a gradient shading on the
1149 tabs background. Available only
1150 for :class:`LabelBook`.
1151 ``INB_WEB_HILITE`` 0x800 On mouse hovering, tabs behave
1152 like html hyperlinks. Available
1153 only for :class:`LabelBook`.
1154 ``INB_NO_RESIZE`` 0x1000 Don't allow resizing of the tab
1155 area.
1156 ``INB_FIT_LABELTEXT`` 0x2000 Will fit the tab area to the
1157 longest text (or text+image if
1158 you have images) in all the
1159 tabs.
1160 ``INB_BOLD_TAB_SELECTION`` 0x4000 Show the selected tab text using
1161 a bold font.
1162 =========================== =========== ================================
1163 name (str): the window name.
1164 """
1165 ImageContainerBase.__init__(self, parent, id, pos, size, style, agw_style, name)
1166
1167 self.Bind(wx.EVT_PAINT, self.OnPaint)
1168 self.Bind(wx.EVT_SIZE, self.OnSize)
1169 self.Bind(wx.EVT_LEFT_DOWN, self.OnMouseLeftDown)
1170 self.Bind(wx.EVT_LEFT_UP, self.OnMouseLeftUp)
1171 self.Bind(wx.EVT_ERASE_BACKGROUND, self.OnEraseBackground)
1172 self.Bind(wx.EVT_MOTION, self.OnMouseMove)
1173 self.Bind(wx.EVT_LEAVE_WINDOW, self.OnMouseLeaveWindow)
1174
1175 self.padding = 4 # Define padding as a class attribute
1176
1177 def OnSize(self, event: wx.SizeEvent) -> None: # noqa: N802
1178 """Handle the ``wx.EVT_SIZE`` event for :class:`wx.ImageContainer`.
1179
1180 Args:
1181 event (wx.SizeEvent): a :class:`wx.SizeEvent` event to be processed.
1182 """
1183 ImageContainerBase.OnSize(self, event)
1184 event.Skip()
1185
1186 def OnMouseLeftDown(self, event: wx.MouseEvent) -> None: # noqa: N802
1187 """Handle the ``wx.EVT_LEFT_DOWN`` event for :class:`wx.ImageContainer`.
1188
1189 Args:
1190 event (wx.MouseEvent): a :class:`MouseEvent` event to be processed.
1191 """
1192 ImageContainerBase.OnMouseLeftDown(self, event)
1193 event.Skip()
1194
1195 def OnMouseLeftUp(self, event: wx.MouseEvent) -> None: # noqa: N802
1196 """Handle the ``wx.EVT_LEFT_UP`` event for :class:`wx.ImageContainer`.
1197
1198 Args:
1199 event (wx.MouseEvent): a :class:`MouseEvent` event to be processed.
1200 """
1201 ImageContainerBase.OnMouseLeftUp(self, event)
1202 event.Skip()
1203
1204 def OnEraseBackground(self, event: wx.EraseEvent) -> None: # noqa: N802
1205 """Handle the ``wx.EVT_ERASE_BACKGROUND`` event for :class:`wx.ImageContainer`.
1206
1207 Args:
1208 event (wx.EraseEvent): a :class:`EraseEvent` event to be processed.
1209 """
1210 ImageContainerBase.OnEraseBackground(self, event)
1211
1212 def OnMouseMove(self, event: wx.MouseEvent) -> None: # noqa: N802
1213 """Handle the ``wx.EVT_MOTION`` event for :class:`wx.ImageContainer`.
1214
1215 Args:
1216 event (wx.MouseEvent): a :class:`MouseEvent` event to be processed.
1217 """
1218 ImageContainerBase.OnMouseMove(self, event)
1219 event.Skip()
1220
1221 def OnMouseLeaveWindow(self, event: wx.MouseEvent) -> None: # noqa: N802
1222 """Handle the ``wx.EVT_LEAVE_WINDOW`` event for :class:`wx.ImageContainer`.
1223
1224 Args:
1225 event (wx.MouseEvent): a :class:`MouseEvent` event to be processed.
1226 """
1227 ImageContainerBase.OnMouseLeaveWindow(self, event)
1228 event.Skip()
1229
1230 def CanDoBottomStyle(self) -> bool: # noqa: N802
1231 """Allow the parent to examine the children type.
1232
1233 Some implementation (such as :class:`LabelBook`),
1234 does not support top/bottom images, only left/right.
1235 """
1236 return True
1237
1238 def OnPaint(self, event: wx.PaintEvent) -> None: # noqa: N802
1239 """Handle the ``wx.EVT_PAINT`` event for :class:`wx.ImageContainer`.
1240
1241 Args:
1242 event (wx.PaintEvent): a :class:`PaintEvent` event to be processed.
1243 """
1244 dc = wx.BufferedPaintDC(self)
1245 style: int = ImageBookStyle(self.GetParent().GetAGWWindowStyleFlag())
1246
1247 self._draw_background(dc, style)
1248 self._draw_pin_button(dc, style)
1249 self._draw_buttons(dc, style)
1250
1251 def _draw_background(self, dc: wx.DC, style: ImageBookStyle) -> None:
1252 size: wx.Size = self.GetSize()
1253 back_brush: wx.Brush = wx.WHITE_BRUSH
1254 border_pen: wx.Pen = (
1255 wx.Pen(wx.SystemSettings.GetColour(wx.SYS_COLOUR_3DSHADOW))
1256 if style & ImageBookStyle.INB_BORDER
1257 else wx.TRANSPARENT_PEN
1258 )
1259
1260 dc.SetBrush(back_brush)
1261 dc.SetPen(border_pen)
1262 dc.DrawRectangle(0, 0, size.width, size.height)
1263
1264 def _draw_pin_button(self, dc: wx.DC, style: ImageBookStyle) -> None:
1265 if not (style & ImageBookStyle.INB_USE_PIN_BUTTON):
1266 return
1267
1268 client_rect: wx.Rect = self.GetClientRect()
1269 pin_rect = wx.Rect(client_rect.x + client_rect.width - 20, 2, 20, 20)
1270 self.DrawPin(dc, pin_rect, not self._bCollapsed)
1271
1272 if self._bCollapsed:
1273 return
1274
1275 def _draw_buttons(self, dc: wx.DC, style: ImageBookStyle) -> None:
1276 size: wx.Size = self.GetSize()
1277 b_use_pin: ImageBookStyle = style & ImageBookStyle.INB_USE_PIN_BUTTON
1278 b_use_y_coord: ImageBookStyle = style & (
1279 ImageBookStyle.INB_RIGHT | ImageBookStyle.INB_LEFT
1280 )
1281 client_size: int = size.height if b_use_y_coord else size.width
1282 pin_btn_size: int = 20 if b_use_pin else 0
1283
1284 normal_font: wx.Font = wx.SystemSettings.GetFont(wx.SYS_DEFAULT_GUI_FONT)
1285 bold_font: wx.Font = wx.SystemSettings.GetFont(wx.SYS_DEFAULT_GUI_FONT)
1286 bold_font.SetWeight(wx.FONTWEIGHT_BOLD)
1287
1288 padding = 4
1289 text_padding_left = 2
1290 img_top_padding = 10
1291
1292 pos: int = 0 if style & ImageBookStyle.INB_BORDER else 1
1293 if b_use_pin and (style & (ImageBookStyle.INB_TOP | ImageBookStyle.INB_BOTTOM)):
1294 pos += 20
1295
1296 for i, page_info in enumerate(self._pagesInfoVec):
1297 if (
1298 pos + self._get_button_width(dc, page_info, style, pin_btn_size)
1299 > client_size
1300 ):
1301 break
1302
1303 button_rect: wx.Rect = self._get_button_rect(pos, size, style)
1304 self._draw_button(
1305 dc,
1306 i,
1307 button_rect,
1308 style,
1309 normal_font,
1310 bold_font,
1311 padding,
1312 text_padding_left,
1313 img_top_padding,
1314 )
1315
1316 pos += self._get_button_width(dc, page_info, style, pin_btn_size)
1317
1318 self._update_non_visible_buttons(pos)
1319
1320 def _get_button_width(
1321 self,
1322 dc: wx.DC,
1323 page_info: ImageInfo,
1324 style: ImageBookStyle,
1325 pin_button_size: int,
1326 ) -> int:
1327 rect_width: int = self._nImgSize * 2
1328 if (
1329 style & ImageBookStyle.INB_FIT_BUTTON
1330 and not (style & (ImageBookStyle.INB_LEFT | ImageBookStyle.INB_RIGHT))
1331 and page_info.GetCaption()
1332 and not (style & ImageBookStyle.INB_SHOW_ONLY_IMAGES)
1333 ):
1334 text_width, _ = dc.GetTextExtent(page_info.GetCaption())
1335 rect_width = max(rect_width, text_width + self.padding * 2)
1336 if rect_width % 2 != 0:
1337 rect_width += 1
1338
1339 return rect_width + pin_button_size
1340
1341 def _get_button_rect(
1342 self, pos: int, size: wx.Size, style: ImageBookStyle
1343 ) -> wx.Rect:
1344 rect_width: int = self._nImgSize * 2
1345 rect_height: int = self._nImgSize * 2
1346
1347 if style & (ImageBookStyle.INB_RIGHT | ImageBookStyle.INB_LEFT):
1348 rect_width -= 2
1349 else:
1350 rect_height -= 2
1351
1352 if style & (ImageBookStyle.INB_RIGHT | ImageBookStyle.INB_LEFT):
1353 return wx.Rect(1, pos, rect_width, rect_height)
1354 return wx.Rect(pos, 1, rect_width, rect_height)
1355
1356 def _draw_button(
1357 self,
1358 dc: wx.DC,
1359 index: int,
1360 button_rect: wx.Rect,
1361 style: ImageBookStyle,
1362 normal_font: wx.Font,
1363 bold_font: wx.Font,
1364 padding: int,
1365 text_padding_left: int,
1366 image_top_padding: int,
1367 ) -> None:
1368 if self._nIndex == index:
1369 self._draw_selected_button(dc, button_rect, style)
1370
1371 if self._nHoveredImgIdx == index:
1372 self._draw_hovered_button(dc, button_rect, style)
1373
1374 self._draw_button_content(
1375 dc,
1376 index,
1377 button_rect,
1378 style,
1379 normal_font,
1380 bold_font,
1381 padding,
1382 text_padding_left,
1383 image_top_padding,
1384 )
1385
1386 def _draw_selected_button(
1387 self, dc: wx.DC, button_rect: wx.Rect, style: ImageBookStyle
1388 ) -> None:
1389 pen_colour: wx.Colour = wx.SystemSettings.GetColour(wx.SYS_COLOUR_ACTIVECAPTION)
1390 brush_colour: wx.Colour = ArtManager.Get().LightColour(
1391 wx.SystemSettings.GetColour(wx.SYS_COLOUR_ACTIVECAPTION), 75
1392 )
1393
1394 dc.SetPen(wx.Pen(pen_colour))
1395 dc.SetBrush(wx.Brush(brush_colour))
1396
1397 if style & ImageBookStyle.INB_BORDER:
1398 button_rect = self._adjust_button_rect(button_rect, style)
1399
1400 dc.DrawRectangle(button_rect)
1401
1402 def _draw_hovered_button(
1403 self, dc: wx.DC, button_rect: wx.Rect, style: ImageBookStyle
1404 ) -> None:
1405 pen_colour: wx.Colour = wx.SystemSettings.GetColour(wx.SYS_COLOUR_ACTIVECAPTION)
1406 brush_colour: wx.Colour = ArtManager.Get().LightColour(
1407 wx.SystemSettings.GetColour(wx.SYS_COLOUR_ACTIVECAPTION), 90
1408 )
1409
1410 dc.SetPen(wx.Pen(pen_colour))
1411 dc.SetBrush(wx.Brush(brush_colour))
1412
1413 if style & ImageBookStyle.INB_BORDER:
1414 button_rect = self._adjust_button_rect(button_rect, style)
1415
1416 dc.DrawRectangle(button_rect)
1417
1418 def _adjust_button_rect(
1419 self, button_rect: wx.Rect, style: ImageBookStyle
1420 ) -> wx.Rect:
1421 if style & (ImageBookStyle.INB_TOP | ImageBookStyle.INB_BOTTOM):
1422 return wx.Rect(
1423 button_rect.x + 1,
1424 button_rect.y,
1425 button_rect.width - 1,
1426 button_rect.height,
1427 )
1428 return wx.Rect(
1429 button_rect.x, button_rect.y + 1, button_rect.width, button_rect.height - 1
1430 )
1431
1432 def _draw_button_content(
1433 self,
1434 dc: wx.DC,
1435 index: int,
1436 button_rect: wx.Rect,
1437 style: ImageBookStyle,
1438 normal_font: wx.Font,
1439 bold_font: wx.Font,
1440 padding: int,
1441 text_padding_left: int,
1442 image_top_padding: int,
1443 ) -> None:
1444 page_info: ImageInfo = self._pagesInfoVec[index]
1445 dc.SetFont(
1446 normal_font
1447 if not (
1448 style & ImageBookStyle.INB_BOLD_TAB_SELECTION and self._nIndex == index
1449 )
1450 else bold_font
1451 )
1452
1453 if not (
1454 style & ImageBookStyle.INB_SHOW_ONLY_TEXT
1455 and style & ImageBookStyle.INB_SHOW_ONLY_IMAGES
1456 ):
1457 if (
1458 style & ImageBookStyle.INB_SHOW_ONLY_TEXT
1459 and style & ImageBookStyle.INB_SHOW_ONLY_IMAGES
1460 ):
1461 style ^= ImageBookStyle.INB_SHOW_ONLY_TEXT
1462 style ^= ImageBookStyle.INB_SHOW_ONLY_IMAGES
1463 self.GetParent().SetAGWWindowStyleFlag(style)
1464
1465 if (
1466 not style & ImageBookStyle.INB_SHOW_ONLY_TEXT
1467 and page_info.GetImageIndex() != -1
1468 and self._ImageList is not None
1469 ):
1470 img_x_coord, img_y_coord = self._get_image_coords(
1471 button_rect, style, padding, image_top_padding
1472 )
1473 self._ImageList.Draw(
1474 page_info.GetImageIndex(),
1475 dc,
1476 img_x_coord,
1477 img_y_coord,
1478 wx.IMAGELIST_DRAW_TRANSPARENT,
1479 True,
1480 )
1481
1482 if (
1483 not style & ImageBookStyle.INB_SHOW_ONLY_IMAGES
1484 and page_info.GetCaption()
1485 ):
1486 fixed_text = self._get_fixed_text(
1487 dc, page_info.GetCaption(), style, padding
1488 )
1489 text_offset_x, text_offset_y = self._get_text_coords(
1490 dc,
1491 button_rect,
1492 style,
1493 padding,
1494 text_padding_left,
1495 image_top_padding,
1496 index,
1497 )
1498 dc.SetTextForeground(
1499 wx.SystemSettings.GetColour(wx.SYS_COLOUR_WINDOWTEXT)
1500 )
1501 dc.DrawText(fixed_text, text_offset_x, text_offset_y)
1502
1503 page_info.SetPosition(button_rect.GetPosition())
1504 page_info.SetSize(button_rect.GetSize())
1505
1506 def _get_image_coords(
1507 self,
1508 button_rect: wx.Rect,
1509 style: ImageBookStyle,
1510 padding: int,
1511 image_top_padding: int,
1512 ) -> tuple[int, int]:
1513 if style & (ImageBookStyle.INB_RIGHT | ImageBookStyle.INB_LEFT):
1514 img_x_coord: int = self._nImgSize // 2
1515 img_y_coord: int = button_rect.y + (
1516 self._nImgSize // 2
1517 if style & ImageBookStyle.INB_SHOW_ONLY_IMAGES
1518 else image_top_padding
1519 )
1520 else:
1521 img_x_coord = (
1522 button_rect.x + (button_rect.width // 2) - (self._nImgSize // 2)
1523 )
1524 img_y_coord = (
1525 self._nImgSize // 2
1526 if style & ImageBookStyle.INB_SHOW_ONLY_IMAGES
1527 else image_top_padding
1528 )
1529
1530 return img_x_coord, img_y_coord
1531
1532 def _get_fixed_text(
1533 self, dc: wx.DC, caption: str, style: ImageBookStyle, padding: int
1534 ) -> None | str:
1535 if not (
1536 style & ImageBookStyle.INB_FIT_BUTTON
1537 or style & (ImageBookStyle.INB_LEFT | ImageBookStyle.INB_RIGHT)
1538 ):
1539 return self.FixTextSize(dc, caption, self._nImgSize * 2 - 4)
1540
1541 return caption
1542
1543 def _get_text_coords(
1544 self,
1545 dc: wx.DC,
1546 button_rect: wx.Rect,
1547 style: ImageBookStyle,
1548 padding: int,
1549 text_padding_left: int,
1550 image_top_padding: int,
1551 index: int,
1552 ) -> tuple[int, int]:
1553 text_width, text_height = dc.GetTextExtent(
1554 self._get_fixed_text(
1555 dc, self._pagesInfoVec[index].GetCaption(), style, padding
1556 )
1557 )
1558
1559 if style & (ImageBookStyle.INB_RIGHT | ImageBookStyle.INB_LEFT):
1560 text_offset_x: int = (button_rect.width - text_width) // 2
1561 text_offset_y: int = button_rect.y + (
1562 image_top_padding + 3
1563 if not style & ImageBookStyle.INB_SHOW_ONLY_TEXT
1564 else (self._nImgSize * 2 - text_height) // 2
1565 )
1566 else:
1567 text_offset_x = (
1568 (button_rect.width - text_width) // 2
1569 + button_rect.x
1570 + text_padding_left
1571 )
1572 text_offset_y = (
1573 image_top_padding + 3
1574 if not style & ImageBookStyle.INB_SHOW_ONLY_TEXT
1575 else (self._nImgSize * 2 - text_height) // 2
1576 )
1577
1578 return text_offset_x, text_offset_y
1579
1580 def _update_non_visible_buttons(self, pos: int) -> None:
1581 for ii in range(pos // (self._nImgSize * 2), len(self._pagesInfoVec)):
1582 self._pagesInfoVec[ii].SetPosition(wx.Point(-1, -1))
1583
1584
1585 # ------------------------------------------------------------------------------------ #
1586 # Class LabelContainer
1587 # ------------------------------------------------------------------------------------ #
1588
1589
1590 class LabelContainer(ImageContainerBase):
1591 """Base class for :class:`LabelBook`."""
1592
1593 num_padding = 6
1594
1595 def __init__(
1596 self,
1597 parent: wx.Window,
1598 id: int = wx.ID_ANY, # noqa: A002
1599 pos: wx.Point = wx.DefaultPosition,
1600 size: wx.Size = wx.DefaultSize,
1601 style: int = 0,
1602 agw_style: int = 0,
1603 name: str = "LabelContainer",
1604 ) -> None:
1605 """Construct the default class.
1606
1607 Args:
1608 parent (wx.Window): parent window. Must not be ``None``;
1609 id (int): window identifier. A value of -1 indicates a default value;
1610 pos (wx.Point): the control position.
1611 A value of (-1, -1) indicates a default position, chosen by either the
1612 windowing system or wxPython, depending on platform;
1613 size (wx.Size): the control size.
1614 A value of (-1, -1) indicates a default size, chosen by either the
1615 windowing system or wxPython, depending on platform;
1616 style (int): the underlying :class:`Panel` window style;
1617 agw_style (int): the AGW-specific window style.
1618 This can be a combination of the following bits:
1619 =========================== =========== ================================
1620 Window Styles Hex Value Description
1621 =========================== =========== ================================
1622 ``INB_BOTTOM`` 0x1 Place labels below the page
1623 area. Available only for
1624 :class:`FlatImageBook`.
1625 ``INB_LEFT`` 0x2 Place labels on the left side.
1626 Available only for
1627 :class:`FlatImageBook`.
1628 ``INB_RIGHT`` 0x4 Place labels on the right side.
1629 ``INB_TOP`` 0x8 Place labels above the page
1630 area.
1631 ``INB_BORDER`` 0x10 Draws a border around
1632 :class:`LabelBook` or
1633 :class:`FlatImageBook`.
1634 ``INB_SHOW_ONLY_TEXT`` 0x20 Shows only text labels and no
1635 images. Available only for
1636 :class:`LabelBook`.
1637 ``INB_SHOW_ONLY_IMAGES`` 0x40 Shows only tab images and no
1638 label texts. Available only for
1639 :class:`LabelBook`.
1640 ``INB_FIT_BUTTON`` 0x80 Displays a pin button to
1641 show/hide the book control.
1642 ``INB_DRAW_SHADOW`` 0x100 Draw shadows below the book
1643 tabs. Available only for
1644 :class:`LabelBook`.
1645 ``INB_USE_PIN_BUTTON`` 0x200 Displays a pin button to
1646 show/hide the book control.
1647 ``INB_GRADIENT_BACKGROUND`` 0x400 Draws a gradient shading on the
1648 tabs background. Available only
1649 for :class:`LabelBook`.
1650 ``INB_WEB_HILITE`` 0x800 On mouse hovering, tabs behave
1651 like html hyperlinks. Available
1652 only for :class:`LabelBook`.
1653 ``INB_NO_RESIZE`` 0x1000 Don't allow resizing of the tab
1654 area.
1655 ``INB_FIT_LABELTEXT`` 0x2000 Will fit the tab area to the
1656 longest text (or text+image if
1657 you have images) in all the
1658 tabs.
1659 ``INB_BOLD_TAB_SELECTION`` 0x4000 Show the selected tab text using
1660 a bold font.
1661 =========================== =========== ================================
1662 name (str): the window name.
1663 """
1664 ImageContainerBase.__init__(self, parent, id, pos, size, style, agw_style, name)
1665 self._nTabAreaWidth = 100
1666 self._oldCursor: wx.Cursor = wx.NullCursor
1667 self._coloursMap: dict[int, wx.Colour] = {}
1668 self._skin: wx.Bitmap = wx.NullBitmap
1669 self._sashRect = wx.Rect()
1670
1671 self.Bind(wx.EVT_PAINT, self.OnPaint)
1672 self.Bind(wx.EVT_SIZE, self.OnSize)
1673 self.Bind(wx.EVT_LEFT_DOWN, self.OnMouseLeftDown)
1674 self.Bind(wx.EVT_LEFT_UP, self.OnMouseLeftUp)
1675 self.Bind(wx.EVT_MOTION, self.OnMouseMove)
1676 self.Bind(wx.EVT_LEAVE_WINDOW, self.OnMouseLeaveWindow)
1677 self.Bind(wx.EVT_ERASE_BACKGROUND, self.OnEraseBackground)
1678
1679 self._ImageList: None | wx.ImageList = None
1680 self._initialize_image_list()
1681
1682 def _initialize_image_list(self) -> None:
1683 # Initialize the image list with default values or from a source
1684 self._ImageList = wx.ImageList(16, 16) # Example initialization
1685
1686 def OnSize(self, event: wx.SizeEvent) -> None: # noqa: N802
1687 """Handle the ``wx.EVT_SIZE`` event for :class:`LabelContainer`.
1688
1689 Args:
1690 event (wx.SizeEvent): a :class:`wx.SizeEvent` event to be processed.
1691 """
1692 ImageContainerBase.OnSize(self, event)
1693 event.Skip()
1694
1695 def OnEraseBackground(self, event: wx.EraseEvent) -> None: # noqa: N802
1696 """Handle the ``wx.EVT_ERASE_BACKGROUND`` event for :class:`LabelContainer`.
1697
1698 Args:
1699 event (wx.EraseEvent): a :class:`EraseEvent` event to be processed.
1700 """
1701 ImageContainerBase.OnEraseBackground(self, event)
1702
1703 def GetTabAreaWidth(self) -> int: # noqa: N802
1704 """Return the width of the tab area."""
1705 return self._nTabAreaWidth
1706
1707 def SetTabAreaWidth(self, width: int) -> None: # noqa: N802
1708 """Set the width of the tab area.
1709
1710 Args:
1711 width (int): the width of the tab area, in pixels.
1712 """
1713 self._nTabAreaWidth: int = width
1714 self.SetSizeHints(width, -1)
1715
1716 def CanDoBottomStyle(self) -> bool: # noqa: N802
1717 """Allow the parent to examine the children type.
1718
1719 Some implementation (such as :class:`LabelBook`),
1720 does not support top/bottom images, only left/right.
1721 """
1722 return False
1723
1724 def SetBackgroundBitmap(self, bmp: wx.Bitmap) -> None: # noqa: N802
1725 """Set the background bitmap for the control.
1726
1727 Args:
1728 bmp (wx.Bitmap): a valid :class:`wx.Bitmap` object.
1729 """
1730 self._skin = bmp
1731
1732 def OnPaint(self, event: wx.PaintEvent) -> None: # noqa: N802
1733 """Handle the ``wx.EVT_PAINT`` event for :class:`LabelContainer`.
1734
1735 Args:
1736 event (wx.PaintEvent): a :class:`PaintEvent` event to be processed.
1737 """
1738 style: int = self.GetParent().GetAGWWindowStyleFlag()
1739
1740 # In case user set both flags, we override them to display both
1741 # INB_SHOW_ONLY_TEXT and INB_SHOW_ONLY_IMAGES
1742 if (
1743 style & ImageBookStyle.INB_SHOW_ONLY_TEXT
1744 and style & ImageBookStyle.INB_SHOW_ONLY_IMAGES
1745 ):
1746 style ^= ImageBookStyle.INB_SHOW_ONLY_TEXT
1747 style ^= ImageBookStyle.INB_SHOW_ONLY_IMAGES
1748 self.GetParent().SetAGWWindowStyleFlag(style)
1749
1750 dc = wx.BufferedPaintDC(self)
1751 self._draw_background(dc)
1752 self._draw_tabs(dc)
1753 self._draw_pin_button(dc)
1754
1755 def _draw_background(self, dc: wx.DC) -> None:
1756 """Draw the background of the control.
1757
1758 Args:
1759 dc (wx.DC): an instance of :class:`wx.DC`.
1760 """
1761 size: wx.Size = self.GetSize()
1762 back_brush = wx.Brush(self._coloursMap[INB_TAB_AREA_BACKGROUND_COLOUR])
1763 border_pen: wx.Pen = (
1764 wx.Pen(self._coloursMap[INB_TABS_BORDER_COLOUR])
1765 if self.HasAGWFlag(ImageBookStyle.INB_BORDER)
1766 else wx.TRANSPARENT_PEN
1767 )
1768
1769 dc.SetBrush(back_brush)
1770 dc.SetPen(border_pen)
1771 dc.DrawRectangle(wx.Rect(0, 0, size.x, size.y))
1772
1773 if (
1774 self.HasAGWFlag(ImageBookStyle.INB_GRADIENT_BACKGROUND)
1775 and not self._skin.IsOk()
1776 ):
1777 self._draw_gradient_background(dc, size)
1778
1779 def _draw_gradient_background(self, dc: wx.DC, size: wx.Size) -> None:
1780 """Draw a gradient background.
1781
1782 Args:
1783 dc (wx.DC): an instance of :class:`wx.DC`.
1784 size (wx.Size): the size of the control.
1785 """
1786 start_colour: wx.Colour = self._coloursMap[INB_TAB_AREA_BACKGROUND_COLOUR]
1787 end_colour: wx.Colour = ArtManager.Get().LightColour(start_colour, 50)
1788
1789 ArtManager.Get().PaintStraightGradientBox(
1790 dc, wx.Rect(0, 0, size.x // 2, size.y), start_colour, end_colour, False
1791 )
1792 ArtManager.Get().PaintStraightGradientBox(
1793 dc,
1794 wx.Rect(size.x // 2, 0, size.x // 2, size.y),
1795 end_colour,
1796 start_colour,
1797 False,
1798 )
1799
1800 def _draw_tabs(self, dc: wx.DC) -> None:
1801 """Draw the tabs.
1802
1803 Args:
1804 dc (wx.DC): an instance of :class:`wx.DC`.
1805 """
1806 size: wx.Size = self.GetSize()
1807 posy = 20
1808 count = 0
1809
1810 for i in range(len(self._pagesInfoVec)):
1811 count += 1
1812 rect_width: int = self._nTabAreaWidth
1813 rect_height: int = self._calculate_tab_height(i)
1814
1815 if posy + rect_height > size.GetHeight():
1816 break
1817
1818 button_rect = wx.Rect(0, posy, rect_width, rect_height)
1819 self._draw_tab(
1820 dc,
1821 button_rect,
1822 i,
1823 selected=self._nIndex == i,
1824 hover=self._nHoveredImgIdx == i,
1825 )
1826 posy += rect_height
1827
1828 self._update_non_visible_tabs(count)
1829
1830 def _calculate_tab_height(self, index: int) -> int:
1831 """Calculate the height of a tab.
1832
1833 Args:
1834 index (int): the index of the tab.
1835
1836 Returns:
1837 int: the height of the tab.
1838 """
1839 if not self.HasAGWFlag(ImageBookStyle.INB_SHOW_ONLY_TEXT):
1840 return self._nImgSize * 2
1841
1842 font: wx.Font = wx.SystemSettings.GetFont(wx.SYS_DEFAULT_GUI_FONT)
1843 font.SetPointSize(
1844 int(font.GetPointSize() * self.GetParent().GetFontSizeMultiple())
1845 )
1846 if self.GetParent().GetFontBold() or (
1847 self.HasAGWFlag(ImageBookStyle.INB_BOLD_TAB_SELECTION)
1848 and self._nIndex == index
1849 ):
1850 font.SetWeight(wx.FONTWEIGHT_BOLD)
1851
1852 dc = wx.ClientDC(self)
1853 dc.SetFont(font)
1854 w, h = dc.GetTextExtent(self._pagesInfoVec[index].GetCaption())
1855 return h * 2
1856
1857 def _draw_tab(
1858 self,
1859 dc: wx.DC,
1860 rect: wx.Rect,
1861 index: int,
1862 selected: bool,
1863 hover: bool,
1864 ) -> None:
1865 """Draw a single tab.
1866
1867 Args:
1868 dc (wx.DC): an instance of :class:`wx.DC`.
1869 rect (wx.Rect): the tab client rectangle.
1870 index (int): the index of the tab.
1871 selected (bool): ``True`` if the tab is selected, ``False`` otherwise.
1872 hover (bool): ``True`` if the tab is being hovered with the mouse,
1873 ``False`` otherwise.
1874 """
1875 orientation_left: bool = self.HasAGWFlag(
1876 ImageBookStyle.INB_LEFT
1877 ) or self.HasAGWFlag(ImageBookStyle.INB_TOP)
1878 text: str = self._pagesInfoVec[index].GetCaption()
1879 bmp: wx.Bitmap = self._get_tab_bitmap(index)
1880 text_rect: wx.Rect = self._calculate_text_rect(dc, rect, text, bmp)
1881 image_rect: wx.Rect = self._calculate_image_rect(dc, rect, bmp)
1882 image_info: ImageInfo = self._pagesInfoVec[
1883 index
1884 ] # Assuming ImageInfo is a part of _pagesInfoVec
1885
1886 self._draw_tab_background(dc, rect, selected, orientation_left)
1887 self._draw_tab_text(dc, text_rect, text, selected, image_info)
1888 self._draw_tab_image(dc, image_rect, bmp)
1889 self._draw_tab_shadow(dc, rect, selected, index, hover)
1890 self._draw_tab_hover_effect(
1891 dc, rect, text_rect, text, selected, hover, image_info
1892 )
1893
1894 self._pagesInfoVec[index].SetPosition(rect.GetPosition())
1895 self._pagesInfoVec[index].SetSize(rect.GetSize())
1896
1897 def _get_tab_bitmap(self, index: int) -> wx.Bitmap:
1898 """Get the bitmap for a tab.
1899
1900 Args:
1901 index (int): the index of the tab.
1902
1903 Returns:
1904 wx.Bitmap: the bitmap for the tab.
1905 """
1906 if self._ImageList is None or self._pagesInfoVec[index].GetImageIndex() == -1:
1907 return wx.NullBitmap
1908 return self._ImageList.GetBitmap(self._pagesInfoVec[index].GetImageIndex())
1909
1910 def _update_non_visible_tabs(self, count: int) -> None:
1911 """Update the visibility of tabs that do not fit on the screen.
1912
1913 Args:
1914 count (int): the number of tabs that fit on the screen.
1915 """
1916 for ii in range(count, len(self._pagesInfoVec)):
1917 self._pagesInfoVec[ii].SetPosition(wx.Point(-1, -1))
1918
1919 def _draw_pin_button(self, dc: wx.DC) -> None:
1920 """Draw the pin button if it is enabled and the control is not collapsed.
1921
1922 Args:
1923 dc (wx.DC): an instance of :class:`wx.DC`.
1924 """
1925 if self.HasAGWFlag(ImageBookStyle.INB_USE_PIN_BUTTON) and not self._bCollapsed:
1926 client_rect: wx.Rect = self.GetClientRect()
1927 pin_rect = wx.Rect(
1928 client_rect.GetX() + client_rect.GetWidth() - 20, 2, 20, 20
1929 )
1930 self.DrawPin(dc, pin_rect, not self._bCollapsed)
1931
1932 def DrawBackgroundBitmap(self, dc: wx.DC) -> None: # noqa: N802
1933 """Draw a bitmap as the background of the control.
1934
1935 Args:
1936 dc (wx.DC): an instance of :class:`wx.DC`.
1937 """
1938 client_rect: wx.Rect = self.GetClientRect()
1939 width: int = client_rect.GetWidth()
1940 height: int = client_rect.GetHeight()
1941 xstep: int = self._skin.GetWidth()
1942 ystep: int = self._skin.GetHeight()
1943 bmp_rect = wx.Rect(0, 0, xstep, ystep)
1944
1945 if bmp_rect != client_rect:
1946 self._draw_tiled_background(dc, width, height, xstep, ystep)
1947 else:
1948 dc.DrawBitmap(self._skin, 0, 0)
1949
1950 def _draw_tiled_background(
1951 self, dc: wx.DC, width: int, height: int, xstep: int, ystep: int
1952 ) -> None:
1953 """Draw a tiled background.
1954
1955 Args:
1956 dc (wx.DC): an instance of :class:`wx.DC`.
1957 width (int): the width of the control.
1958 height (int): the height of the control.
1959 xstep (int): the width of the background bitmap.
1960 ystep (int): the height of the background bitmap.
1961 """
1962 mem_dc = wx.MemoryDC()
1963 bmp = wx.Bitmap(width, height)
1964 mem_dc.SelectObject(bmp)
1965
1966 covered_y = 0
1967 covered_x = 0
1968
1969 while covered_y < height:
1970 while covered_x < width:
1971 mem_dc.DrawBitmap(self._skin, covered_x, covered_y, True)
1972 covered_x += xstep
1973 covered_x = 0
1974 covered_y += ystep
1975
1976 mem_dc.SelectObject(wx.NullBitmap)
1977 dc.DrawBitmap(bmp, 0, 0)
1978
1979 def OnMouseLeftUp(self, event: wx.MouseEvent) -> None: # noqa: N802
1980 """Handle the ``wx.EVT_LEFT_UP`` event for :class:`LabelContainer`.
1981
1982 Args:
1983 event (wx.MouseEvent): a :class:`MouseEvent` event to be processed.
1984 """
1985 if self.HasAGWFlag(ImageBookStyle.INB_NO_RESIZE):
1986 ImageContainerBase.OnMouseLeftUp(self, event)
1987 return
1988
1989 if self.HasCapture():
1990 self.ReleaseMouse()
1991
1992 if not self._sashRect.IsEmpty():
1993 self._handle_sash_release(event)
1994 return
1995
1996 self._sashRect = wx.Rect()
1997
1998 if self._oldCursor.IsOk():
1999 self.SetCursor(self._oldCursor)
2000 self._oldCursor = wx.NullCursor
2001
2002 ImageContainerBase.OnMouseLeftUp(self, event)
2003
2004 def _handle_sash_release(self, event: wx.MouseEvent) -> None:
2005 """Handle the release of the sash.
2006
2007 Args:
2008 event (wx.MouseEvent): a :class:`MouseEvent` event to be processed.
2009 """
2010 ArtManager.Get().DrawDragSash(self._sashRect)
2011 size_event = wx.SizeEvent(self.GetSize())
2012 self.Resize(size_event)
2013 self._sashRect = wx.Rect()
2014
2015 def Resize(self, event: wx.SizeEvent) -> None: # noqa: N802
2016 """Actually resize the tab area.
2017
2018 Args:
2019 event (wx.SizeEvent): an instance of :class:`wx.SizeEvent`.
2020 """
2021 self._tabAreaSize = self.GetSize()
2022 new_width: int = self._tabAreaSize.width
2023 event_size: wx.Size = event.GetSize()
2024
2025 if self.HasAGWFlag(ImageBookStyle.INB_BOTTOM) or self.HasAGWFlag(
2026 ImageBookStyle.INB_RIGHT
2027 ):
2028 new_width -= event_size.width
2029 else:
2030 new_width = event_size.width
2031
2032 new_width = max(new_width, 100) # Don't allow width to be lower than that
2033
2034 self.SetSizeHints(new_width, self._tabAreaSize.height)
2035 self.GetParent().Freeze()
2036 self.GetParent().GetSizer().Layout()
2037 self.GetParent().Thaw()
2038
2039 def OnMouseMove(self, event: wx.MouseEvent) -> None: # noqa: N802
2040 """Handle the ``wx.EVT_MOTION`` event for :class:`LabelContainer`.
2041
2042 Args:
2043 event (wx.MouseEvent): a :class:`MouseEvent` event to be processed.
2044 """
2045 if self.HasAGWFlag(ImageBookStyle.INB_NO_RESIZE):
2046 ImageContainerBase.OnMouseMove(self, event)
2047 return
2048
2049 if not self._sashRect.IsEmpty():
2050 self._handle_sash_drag(event)
2051 elif event.LeftIsDown():
2052 self._handle_sash_start(event)
2053 else:
2054 self._handle_cursor_change(event)
2055
2056 def _handle_sash_drag(self, event: wx.MouseEvent) -> None:
2057 """Handle the dragging of the sash.
2058
2059 Args:
2060 event (wx.MouseEvent): a :class:`MouseEvent` event to be processed.
2061 """
2062 ArtManager.Get().DrawDragSash(self._sashRect)
2063 client_rect: wx.Rect = self.GetClientRect()
2064 pt: wx.Point = self.ClientToScreen(wx.Point(event.GetX(), 0))
2065 self._sashRect = wx.Rect(pt, wx.Size(4, client_rect.height))
2066 ArtManager.Get().DrawDragSash(self._sashRect)
2067
2068 def _handle_sash_start(self, event: wx.MouseEvent) -> None:
2069 """Handle the start of sash dragging.
2070
2071 Args:
2072 event (wx.MouseEvent): a :class:`MouseEvent` event to be processed.
2073 """
2074 image_id, where = self.HitTest(event.GetPosition())
2075 if where != IMG_OVER_EW_BORDER or self._bCollapsed:
2076 return
2077
2078 if not self._sashRect.IsEmpty():
2079 ArtManager.Get().DrawDragSash(self._sashRect)
2080 else:
2081 self.CaptureMouse()
2082 self._oldCursor = self.GetCursor()
2083 self.SetCursor(wx.Cursor(wx.CURSOR_SIZEWE))
2084 client_rect: wx.Rect = self.GetClientRect()
2085 pt: wx.Point = self.ClientToScreen(wx.Point(event.GetX(), 0))
2086 self._sashRect = wx.Rect(pt, wx.Size(4, client_rect.height))
2087 ArtManager.Get().DrawDragSash(self._sashRect)
2088
2089 def _handle_cursor_change(self, event: wx.MouseEvent) -> None:
2090 """Handle the change of cursor when not dragging the sash.
2091
2092 Args:
2093 event (wx.MouseEvent): a :class:`MouseEvent` event to be processed.
2094 """
2095 if self.PointOnSash(event.GetPosition()):
2096 self._oldCursor = self.GetCursor()
2097 self.SetCursor(wx.Cursor(wx.CURSOR_SIZEWE))
2098 elif self._oldCursor.IsOk():
2099 self.SetCursor(self._oldCursor)
2100 self._oldCursor = wx.NullCursor
2101
2102 self._sashRect = wx.Rect()
2103 ImageContainerBase.OnMouseMove(self, event)
2104
2105 def OnMouseLeftDown(self, event: wx.MouseEvent) -> None: # noqa: N802
2106 """Handle the ``wx.EVT_LEFT_DOWN`` event for :class:`LabelContainer`.
2107
2108 Args:
2109 event (wx.MouseEvent): a :class:`MouseEvent` event to be processed.
2110 """
2111 if self.HasAGWFlag(ImageBookStyle.INB_NO_RESIZE):
2112 ImageContainerBase.OnMouseLeftDown(self, event)
2113 return
2114
2115 _, where = self.HitTest(event.GetPosition())
2116
2117 if where == IMG_OVER_EW_BORDER and not self._bCollapsed:
2118 if not self._sashRect.IsEmpty():
2119 ArtManager.Get().DrawDragSash(self._sashRect)
2120 else:
2121 self.CaptureMouse()
2122 self._oldCursor = self.GetCursor()
2123 self.SetCursor(wx.Cursor(wx.CURSOR_SIZEWE))
2124 client_rect: wx.Rect = self.GetClientRect()
2125 pt: wx.Point = self.ClientToScreen(wx.Point(event.GetX(), 0))
2126 self._sashRect = wx.Rect(pt, wx.Size(4, client_rect.height))
2127 ArtManager.Get().DrawDragSash(self._sashRect)
2128 else:
2129 ImageContainerBase.OnMouseLeftDown(self, event)
2130
2131 def OnMouseLeaveWindow(self, event: wx.MouseEvent) -> None: # noqa: N802
2132 """Handle the ``wx.EVT_LEAVE_WINDOW`` event for :class:`LabelContainer`.
2133
2134 Args:
2135 event (wx.MouseEvent): a :class:`MouseEvent` event to be processed.
2136 """
2137 if self.HasAGWFlag(ImageBookStyle.INB_NO_RESIZE):
2138 ImageContainerBase.OnMouseLeaveWindow(self, event)
2139 return
2140
2141 if not self.HasCapture():
2142 ImageContainerBase.OnMouseLeaveWindow(self, event)
2143
2144 def DrawRegularHover(self, dc: wx.DC, rect: wx.Rect, image_info: ImageInfo) -> None: # noqa: N802
2145 """Draw a rounded rectangle around the current tab.
2146
2147 Args:
2148 dc (wx.DC): an instance of :class:`wx.DC`;
2149 rect (wx.Rect): the current tab client rectangle.
2150 image_info (ImageInfo): an instance of :class:`ImageInfo`.
2151 """
2152 dc.SetBrush(wx.TRANSPARENT_BRUSH)
2153 dc.SetPen(wx.Pen(wx.WHITE))
2154
2155 if self.HasAGWFlag(ImageBookStyle.INB_RIGHT) or self.HasAGWFlag(
2156 ImageBookStyle.INB_TOP
2157 ):
2158 dc.DrawLine(rect.x + 1, rect.y, rect.x + rect.width, rect.y)
2159 dc.DrawLine(
2160 rect.x + rect.width, rect.y, rect.x + rect.width, rect.y + rect.height
2161 )
2162 dc.SetPen(wx.Pen(self._coloursMap[INB_TABS_BORDER_COLOUR]))
2163 dc.DrawLine(
2164 rect.x + rect.width, rect.y + rect.height, rect.x, rect.y + rect.height
2165 )
2166 else:
2167 dc.DrawLine(rect.x, rect.y, rect.x + rect.width - 1, rect.y)
2168 dc.DrawLine(rect.x, rect.y, rect.x, rect.y + rect.height)
2169 dc.SetPen(wx.Pen(self._coloursMap[INB_TABS_BORDER_COLOUR]))
2170 dc.DrawLine(
2171 rect.x, rect.y + rect.height, rect.x + rect.width, rect.y + rect.height
2172 )
2173
2174 def DrawWebHover( # noqa: N802
2175 self,
2176 dc: wx.DC,
2177 caption: None | str,
2178 x_coord: int,
2179 y_coord: int,
2180 selected: bool,
2181 image_info: ImageInfo,
2182 ) -> None:
2183 """Draw a web style hover effect (set cursor to hand & underline text).
2184
2185 Args:
2186 dc (wx.DC): an instance of :class:`wx.DC`;
2187 caption (str): the tab caption text;
2188 x_coord (int): the x position of the tab caption;
2189 y_coord (int): the y position of the tab caption;
2190 selected (bool): ``True`` if the tab is selected, ``False`` otherwise.
2191 image_info (ImageInfo): an instance of :class:`ImageInfo`.
2192 """
2193 under_lined_font: wx.Font = wx.SystemSettings.GetFont(wx.SYS_DEFAULT_GUI_FONT)
2194 under_lined_font.SetPointSize(
2195 int(
2196 under_lined_font.GetPointSize() * self.GetParent().GetFontSizeMultiple()
2197 )
2198 )
2199 if self.GetParent().GetFontBold() or (
2200 self.HasAGWFlag(ImageBookStyle.INB_BOLD_TAB_SELECTION) and selected
2201 ):
2202 under_lined_font.SetWeight(wx.FONTWEIGHT_BOLD)
2203
2204 under_lined_font.SetUnderlined(True)
2205 dc.SetFont(under_lined_font)
2206 dc.DrawText(caption, x_coord, y_coord)
2207
2208 def SetColour(self, which: int, colour: wx.Colour) -> None: # noqa: N802
2209 """Set a colour for a parameter.
2210
2211 Args:
2212 which (int): can be one of the following parameters:
2213 ================================== ======= =============================
2214 Colour Key Value Description
2215 ================================== ======= =============================
2216 ``INB_TAB_AREA_BACKGROUND_COLOUR`` 100 The tab area background
2217 colour
2218 ``INB_ACTIVE_TAB_COLOUR`` 101 The active tab background
2219 colour
2220 ``INB_TABS_BORDER_COLOUR`` 102 The tabs border colour
2221 ``INB_TEXT_COLOUR`` 103 The tab caption text colour
2222 ``INB_ACTIVE_TEXT_COLOUR`` 104 The active tab caption text
2223 colour
2224 ``INB_HILITE_TAB_COLOUR`` 105 The tab caption highlight
2225 text colour
2226 ================================== ======= =============================
2227 colour (wx.Colour): a valid :class:`wx.Colour` object.
2228 """
2229 self._coloursMap[which] = colour
2230
2231 def GetColour(self, which: int) -> wx.Colour: # noqa: N802
2232 """Return a colour for a parameter.
2233
2234 Args:
2235 which (int): the colour key.
2236
2237 See:
2238 :meth:`~LabelContainer.SetColour` for a list of valid colour keys.
2239 """
2240 return self._coloursMap.get(which, wx.Colour())
2241
2242 def InitializeColours(self) -> None: # noqa: N802
2243 """Initialize the colours map to be used for this control."""
2244 self._coloursMap.update(
2245 {
2246 INB_TAB_AREA_BACKGROUND_COLOUR: ArtManager.Get().LightColour(
2247 ArtManager.Get().FrameColour(), 50
2248 )
2249 }
2250 )
2251 self._coloursMap.update(
2252 {INB_ACTIVE_TAB_COLOUR: ArtManager.Get().GetMenuFaceColour()}
2253 )
2254 self._coloursMap.update(
2255 {
2256 INB_TABS_BORDER_COLOUR: wx.SystemSettings.GetColour(
2257 wx.SYS_COLOUR_3DSHADOW
2258 )
2259 }
2260 )
2261 self._coloursMap.update({INB_HILITE_TAB_COLOUR: wx.Colour("LIGHT BLUE")})
2262 self._coloursMap.update({INB_TEXT_COLOUR: wx.WHITE})
2263 self._coloursMap.update({INB_ACTIVE_TEXT_COLOUR: wx.BLACK})
2264
2265 if not ArtManager.Get().IsDark(
2266 self._coloursMap[INB_TAB_AREA_BACKGROUND_COLOUR]
2267 ) and not ArtManager.Get().IsDark(self._coloursMap[INB_TEXT_COLOUR]):
2268 self._coloursMap[INB_TEXT_COLOUR] = ArtManager.Get().DarkColour(
2269 self._coloursMap[INB_TEXT_COLOUR], 100
2270 )
2271
2272 def DrawLabel( # noqa: N802
2273 self,
2274 dc: wx.DC,
2275 rect: wx.Rect,
2276 text: str,
2277 bmp: wx.Bitmap,
2278 image_info: ImageInfo,
2279 orientation_left: bool,
2280 image_id: int,
2281 selected: bool,
2282 hover: bool,
2283 ) -> None:
2284 """Draw a label using the specified dc.
2285
2286 Args:
2287 dc (wx.DC): an instance of :class:`wx.DC`;
2288 rect (wx.Rect): the text client rectangle;
2289 text (str): the actual text string;
2290 bmp (wx.Bitmap): a bitmap to be drawn next to the text;
2291 image_info (ImageInfo): an instance of :class:`ImageInfo`;
2292 orientation_left (bool): ``True`` if the book has the ``INB_RIGHT`` or
2293 ``INB_LEFT`` style set;
2294 image_id (int): the tab image index;
2295 selected (bool): ``True`` if the tab is selected, ``False`` otherwise;
2296 hover (bool): ``True`` if the tab is being hovered with the mouse,
2297 ``False`` otherwise.
2298 """
2299 dcsaver = DCSaver(dc)
2300 n_padding = 6
2301
2302 if orientation_left:
2303 rect.x += n_padding
2304 rect.width -= n_padding
2305 else:
2306 rect.width -= n_padding
2307
2308 text_rect: wx.Rect = self._calculate_text_rect(dc, rect, text, bmp)
2309 image_rect: wx.Rect = self._calculate_image_rect(dc, rect, bmp)
2310
2311 self._draw_tab_background(dc, rect, selected, orientation_left)
2312 self._draw_tab_text(dc, text_rect, text, selected, image_info)
2313 self._draw_tab_image(dc, image_rect, bmp)
2314 self._draw_tab_shadow(dc, rect, selected, image_id, hover)
2315 self._draw_tab_hover_effect(
2316 dc, rect, text_rect, text, selected, hover, image_info
2317 )
2318
2319 image_info.SetPosition(rect.GetPosition())
2320 image_info.SetSize(rect.GetSize())
2321
2322 del dcsaver
2323
2324 def _calculate_text_rect(
2325 self, dc: wx.DC, rect: wx.Rect, text: str, bmp: wx.Bitmap
2326 ) -> wx.Rect:
2327 """Calculate the text bounding rectangle.
2328
2329 Args:
2330 dc (wx.DC): an instance of :class:`wx.DC`.
2331 rect (wx.Rect): the tab client rectangle.
2332 text (str): the tab caption text.
2333 bmp (wx.Bitmap): the tab bitmap.
2334
2335 Returns:
2336 wx.Rect: the text bounding rectangle.
2337 """
2338 n_padding = 6
2339
2340 font: wx.Font = wx.SystemSettings.GetFont(wx.SYS_DEFAULT_GUI_FONT)
2341 font.SetPointSize(
2342 int(font.GetPointSize() * self.GetParent().GetFontSizeMultiple())
2343 )
2344 if self.GetParent().GetFontBold() or (
2345 self.HasAGWFlag(ImageBookStyle.INB_BOLD_TAB_SELECTION)
2346 and self._nIndex == self._nHoveredImgIdx
2347 ):
2348 font.SetWeight(wx.FONTWEIGHT_BOLD)
2349
2350 dc.SetFont(font)
2351 w, h = dc.GetTextExtent(text)
2352 text_rect = wx.Rect(
2353 rect.x + n_padding,
2354 rect.y + (rect.height - h) // 2,
2355 rect.width - 2 * n_padding,
2356 h,
2357 )
2358
2359 if bmp.IsOk() and not self.HasAGWFlag(ImageBookStyle.INB_SHOW_ONLY_TEXT):
2360 text_rect.x += bmp.GetWidth() + n_padding
2361 text_rect.width -= bmp.GetWidth() + n_padding
2362
2363 # Truncate text if needed
2364 caption = ArtManager.Get().TruncateText(dc, text, text_rect.width)
2365 if caption is not None:
2366 text_rect.width = dc.GetTextExtent(caption)[0]
2367
2368 return text_rect
2369
2370 def _calculate_image_rect(
2371 self, dc: wx.DC, rect: wx.Rect, bmp: wx.Bitmap
2372 ) -> wx.Rect:
2373 """Calculate the image bounding rectangle.
2374
2375 Args:
2376 dc (wx.DC): an instance of :class:`wx.DC`.
2377 rect (wx.Rect): the tab client rectangle.
2378 bmp (wx.Bitmap): the tab bitmap.
2379
2380 Returns:
2381 wx.Rect: the image bounding rectangle.
2382 """
2383 if bmp.IsOk() and not self.HasAGWFlag(ImageBookStyle.INB_SHOW_ONLY_TEXT):
2384 return wx.Rect(
2385 rect.x + self.num_padding,
2386 rect.y + (rect.height - bmp.GetHeight()) // 2,
2387 bmp.GetWidth(),
2388 bmp.GetHeight(),
2389 )
2390 return wx.Rect()
2391
2392 def _draw_tab_background(
2393 self, dc: wx.DC, rect: wx.Rect, selected: bool, orientation_left: bool
2394 ) -> None:
2395 """Draw the tab background.
2396
2397 Args:
2398 dc (wx.DC): an instance of :class:`wx.DC`.
2399 rect (wx.Rect): the tab client rectangle.
2400 selected (bool): ``True`` if the tab is selected, ``False`` otherwise.
2401 orientation_left (bool): ``True`` if the book has the ``INB_RIGHT`` or
2402 ``INB_LEFT`` style set.
2403 """
2404 if not selected:
2405 return
2406
2407 dc.SetBrush(wx.Brush(self._coloursMap[INB_ACTIVE_TAB_COLOUR]))
2408 dc.SetPen(
2409 wx.Pen(self._coloursMap[INB_TABS_BORDER_COLOUR])
2410 if self.HasAGWFlag(ImageBookStyle.INB_BORDER)
2411 else wx.Pen(self._coloursMap[INB_ACTIVE_TAB_COLOUR])
2412 )
2413 label_rect = wx.Rect(*rect)
2414
2415 if orientation_left:
2416 label_rect.width += 3
2417 else:
2418 label_rect.width += 3
2419 label_rect.x -= 3
2420
2421 dc.DrawRoundedRectangle(label_rect, 3)
2422
2423 if not orientation_left and self.HasAGWFlag(ImageBookStyle.INB_DRAW_SHADOW):
2424 dc.SetPen(wx.BLACK_PEN)
2425 dc.DrawPoint(
2426 label_rect.x + label_rect.width - 1,
2427 label_rect.y + label_rect.height - 1,
2428 )
2429
2430 def _draw_tab_text(
2431 self,
2432 dc: wx.DC,
2433 text_rect: wx.Rect,
2434 text: str,
2435 selected: bool,
2436 image_info: ImageInfo,
2437 ) -> None:
2438 """Draw the tab text.
2439
2440 Args:
2441 dc (wx.DC): an instance of :class:`wx.DC`.
2442 text_rect (wx.Rect): the text bounding rectangle.
2443 text (str): the tab caption text.
2444 selected (bool): ``True`` if the tab is selected, ``False`` otherwise.
2445 image_info (ImageInfo): an instance of :class:`ImageInfo`.
2446 """
2447 if not text:
2448 return
2449
2450 dc.SetTextForeground(
2451 self._coloursMap[INB_ACTIVE_TEXT_COLOUR]
2452 if selected
2453 else self._coloursMap[INB_TEXT_COLOUR]
2454 )
2455 dc.DrawText(text, text_rect.x, text_rect.y)
2456 image_info.SetTextRect(text_rect)
2457
2458 def _draw_tab_image(self, dc: wx.DC, image_rect: wx.Rect, bmp: wx.Bitmap) -> None:
2459 """Draw the tab image.
2460
2461 Args:
2462 dc (wx.DC): an instance of :class:`wx.DC`.
2463 image_rect (wx.Rect): the image bounding rectangle.
2464 bmp (wx.Bitmap): the tab bitmap.
2465 """
2466 if bmp.IsOk() and not self.HasAGWFlag(ImageBookStyle.INB_SHOW_ONLY_TEXT):
2467 dc.DrawBitmap(bmp, image_rect.x, image_rect.y, True)
2468
2469 def _draw_tab_shadow(
2470 self, dc: wx.DC, rect: wx.Rect, selected: bool, image_id: int, hover: bool
2471 ) -> None:
2472 """Draw the tab shadow.
2473
2474 Args:
2475 dc (wx.DC): an instance of :class:`wx.DC`.
2476 rect (wx.Rect): the tab client rectangle.
2477 selected (bool): ``True`` if the tab is selected, ``False`` otherwise.
2478 image_id (int): the tab image index.
2479 hover (bool): ``True`` if the tab is being hovered with the mouse,
2480 ``False`` otherwise.
2481 """
2482 if not self.HasAGWFlag(ImageBookStyle.INB_DRAW_SHADOW) or not selected:
2483 return
2484
2485 sstyle: int = (
2486 BOTTOM_SHADOW
2487 if self.HasAGWFlag(ImageBookStyle.INB_LEFT)
2488 else BOTTOM_SHADOW_FULL | RIGHT_SHADOW
2489 )
2490 if (
2491 self.HasAGWFlag(ImageBookStyle.INB_WEB_HILITE)
2492 or image_id + 1 != self._nHoveredImgIdx
2493 ):
2494 ArtManager.Get().DrawBitmapShadow(dc, rect, sstyle)
2495
2496 def _draw_tab_hover_effect(
2497 self,
2498 dc: wx.DC,
2499 rect: wx.Rect,
2500 text_rect: wx.Rect,
2501 text: str,
2502 selected: bool,
2503 hover: bool,
2504 image_info: ImageInfo,
2505 ) -> None:
2506 """Draw the tab hover effect.
2507
2508 Args:
2509 dc (wx.DC): an instance of :class:`wx.DC`.
2510 rect (wx.Rect): the tab client rectangle.
2511 text_rect (wx.Rect): the text bounding rectangle.
2512 text (str): the tab caption text.
2513 selected (bool): ``True`` if the tab is selected, ``False`` otherwise.
2514 hover (bool): ``True`` if the tab is being hovered with the mouse,
2515 ``False`` otherwise.
2516 image_info (ImageInfo): an instance of :class:`ImageInfo`.
2517 """
2518 if not hover:
2519 return
2520
2521 if self.HasAGWFlag(ImageBookStyle.INB_WEB_HILITE) and text:
2522 self.DrawWebHover(dc, text, text_rect.x, text_rect.y, selected, image_info)
2523 else:
2524 self.DrawRegularHover(dc, rect, image_info)
2525
2526
2527 # ------------------------------------------------------------------------------------ #
2528 # Class FlatBookBase
2529 # ------------------------------------------------------------------------------------ #
2530
2531
2532 class FlatBookBase(wx.Panel):
2533 """Base class for :class:`LabelBook` and :class:`FlatImageBook` containers."""
2534
2535 def __init__(
2536 self,
2537 parent: wx.Window,
2538 id: int = wx.ID_ANY, # noqa: A002
2539 pos: wx.Point = wx.DefaultPosition,
2540 size: wx.Size = wx.DefaultSize,
2541 style: int = 0,
2542 agw_style: int = 0,
2543 name: str = "FlatBookBase",
2544 ) -> None:
2545 """Construct the default class.
2546
2547 Args:
2548 parent (wx.Window): parent window. Must not be ``None``;
2549 id (int): window identifier. A value of -1 indicates a default value;
2550 pos (wx.Point): the control position.
2551 A value of (-1, -1) indicates a default position, chosen by either the
2552 windowing system or wxPython, depending on platform;
2553 size (wx.Size): the control size.
2554 A value of (-1, -1) indicates a default size, chosen by either the
2555 windowing system or wxPython, depending on platform;
2556 style (int): the underlying :class:`Panel` window style;
2557 agw_style (int): the AGW-specific window style.
2558 This can be a combination of the following bits:
2559 =========================== =========== ================================
2560 Window Styles Hex Value Description
2561 =========================== =========== ================================
2562 ``INB_BOTTOM`` 0x1 Place labels below the page
2563 area. Available only for
2564 :class:`FlatImageBook`.
2565 ``INB_LEFT`` 0x2 Place labels on the left side.
2566 Available only for
2567 :class:`FlatImageBook`.
2568 ``INB_RIGHT`` 0x4 Place labels on the right side.
2569 ``INB_TOP`` 0x8 Place labels above the page
2570 area.
2571 ``INB_BORDER`` 0x10 Draws a border around
2572 :class:`LabelBook` or
2573 :class:`FlatImageBook`.
2574 ``INB_SHOW_ONLY_TEXT`` 0x20 Shows only text labels and no
2575 images. Available only for
2576 :class:`LabelBook`.
2577 ``INB_SHOW_ONLY_IMAGES`` 0x40 Shows only tab images and no
2578 label texts. Available only for
2579 :class:`LabelBook`.
2580 ``INB_FIT_BUTTON`` 0x80 Displays a pin button to
2581 show/hide the book control.
2582 ``INB_DRAW_SHADOW`` 0x100 Draw shadows below the book
2583 tabs. Available only for
2584 :class:`LabelBook`.
2585 ``INB_USE_PIN_BUTTON`` 0x200 Displays a pin button to
2586 show/hide the book control.
2587 ``INB_GRADIENT_BACKGROUND`` 0x400 Draws a gradient shading on the
2588 tabs background. Available only
2589 for :class:`LabelBook`.
2590 ``INB_WEB_HILITE`` 0x800 On mouse hovering, tabs behave
2591 like html hyperlinks. Available
2592 only for :class:`LabelBook`.
2593 ``INB_NO_RESIZE`` 0x1000 Don't allow resizing of the tab
2594 area.
2595 ``INB_FIT_LABELTEXT`` 0x2000 Will fit the tab area to the
2596 longest text (or text+image if
2597 you have images) in all the
2598 tabs.
2599 ``INB_BOLD_TAB_SELECTION`` 0x4000 Show the selected tab text using
2600 a bold font.
2601 =========================== =========== ================================
2602 name (str): the window name.
2603 """
2604 self._pages = None
2605 self._bInitializing = True
2606 self._bForceSelection = False
2607 self._windows: list[wx.Window] = []
2608 self._fontSizeMultiple = 1.0
2609 self._fontBold = False
2610
2611 style |= wx.TAB_TRAVERSAL
2612 self._agw_style: int = agw_style
2613
2614 wx.Panel.__init__(self, parent, id, pos, size, style, name)
2615 self._bInitializing = False
2616
2617 self.Bind(wx.EVT_NAVIGATION_KEY, self.OnNavigationKey)
2618 self.Bind(wx.EVT_MOUSE_CAPTURE_LOST, lambda evt: True)
2619
2620 def CreateImageContainer(self) -> ImageContainerBase: # noqa: N802
2621 """Create the image container class for :class:`FlatBookBase`."""
2622 return ImageContainer(self, wx.ID_ANY, agw_style=self.GetAGWWindowStyleFlag())
2623
2624 def SetAGWWindowStyleFlag(self, agw_style: int) -> None: # noqa: N802
2625 """Set the window style.
2626
2627 Args:
2628 agw_style (int): can be a combination of the following bits:
2629 =========================== =========== ================================
2630 Window Styles Hex Value Description
2631 =========================== =========== ================================
2632 ``INB_BOTTOM`` 0x1 Place labels below the page
2633 area. Available only for
2634 :class:`FlatImageBook`.
2635 ``INB_LEFT`` 0x2 Place labels on the left side.
2636 Available only for
2637 :class:`FlatImageBook`.
2638 ``INB_RIGHT`` 0x4 Place labels on the right side.
2639 ``INB_TOP`` 0x8 Place labels above the page
2640 area.
2641 ``INB_BORDER`` 0x10 Draws a border around
2642 :class:`LabelBook` or
2643 :class:`FlatImageBook`.
2644 ``INB_SHOW_ONLY_TEXT`` 0x20 Shows only text labels and no
2645 images. Available only for
2646 :class:`LabelBook`.
2647 ``INB_SHOW_ONLY_IMAGES`` 0x40 Shows only tab images and no
2648 label texts. Available only for
2649 :class:`LabelBook`.
2650 ``INB_FIT_BUTTON`` 0x80 Displays a pin button to
2651 show/hide the book control.
2652 ``INB_DRAW_SHADOW`` 0x100 Draw shadows below the book
2653 tabs. Available only for
2654 :class:`LabelBook`.
2655 ``INB_USE_PIN_BUTTON`` 0x200 Displays a pin button to
2656 show/hide the book control.
2657 ``INB_GRADIENT_BACKGROUND`` 0x400 Draws a gradient shading on the
2658 tabs background. Available only
2659 for :class:`LabelBook`.
2660 ``INB_WEB_HILITE`` 0x800 On mouse hovering, tabs behave
2661 like html hyperlinks. Available
2662 only for :class:`LabelBook`.
2663 ``INB_NO_RESIZE`` 0x1000 Don't allow resizing of the tab
2664 area.
2665 ``INB_FIT_LABELTEXT`` 0x2000 Will fit the tab area to the
2666 longest text (or text+image if
2667 you have images) in all the
2668 tabs.
2669 ``INB_BOLD_TAB_SELECTION`` 0x4000 Show the selected tab text using
2670 a bold font.
2671 =========================== =========== ================================
2672 """
2673 self._agw_style = agw_style
2674
2675 # Check that we are not in initialization process
2676 if self._bInitializing:
2677 return
2678
2679 if not self._pages:
2680 return
2681
2682 # Detach the windows attached to the sizer
2683 if self.GetSelection() >= 0:
2684 self._mainSizer.Detach(self._windows[self.GetSelection()])
2685
2686 self._mainSizer.Detach(self._pages)
2687
2688 if (
2689 isinstance(self, LabelBook)
2690 or agw_style & ImageBookStyle.INB_LEFT
2691 or agw_style & ImageBookStyle.INB_RIGHT
2692 ):
2693 self._mainSizer = wx.BoxSizer(wx.HORIZONTAL)
2694 else:
2695 self._mainSizer = wx.BoxSizer(wx.VERTICAL)
2696
2697 self.SetSizer(self._mainSizer)
2698
2699 # Add the tab container and the separator
2700 self._mainSizer.Add(self._pages, 0, wx.EXPAND)
2701
2702 if isinstance(self, FlatImageBook):
2703 if (
2704 agw_style & ImageBookStyle.INB_LEFT
2705 or agw_style & ImageBookStyle.INB_RIGHT
2706 ):
2707 self._pages.SetSizeHints(self._pages._nImgSize * 2, -1)
2708 else:
2709 self._pages.SetSizeHints(-1, self._pages._nImgSize * 2)
2710
2711 # Attach the windows back to the sizer to the sizer
2712 if self.GetSelection() >= 0:
2713 self.DoSetSelection(self._windows[self.GetSelection()])
2714
2715 if agw_style & ImageBookStyle.INB_FIT_LABELTEXT:
2716 self.ResizeTabArea()
2717
2718 self._mainSizer.Layout()
2719 dummy = wx.SizeEvent(self.GetSize())
2720 wx.PostEvent(self, dummy)
2721 self._pages.Refresh()
2722
2723 def GetAGWWindowStyleFlag(self) -> int: # noqa: N802
2724 """Return the :class:`FlatBookBase` window style.
2725
2726 See:
2727 :meth:`~FlatBookBase.SetAGWWindowStyleFlag` for a list of possible window
2728 style flags.
2729 """
2730 return self._agw_style
2731
2732 def HasAGWFlag(self, flag: int) -> bool: # noqa: N802
2733 """Return whether a flag is present in the :class:`FlatBookBase` style.
2734
2735 Args:
2736 flag (int): one of the possible :class:`FlatBookBase` window styles.
2737
2738 See:
2739 :meth:`~FlatBookBase.SetAGWWindowStyleFlag` for a list of possible window
2740 style flags.
2741 """
2742 agw_style: int = self.GetAGWWindowStyleFlag()
2743 res: bool = ((agw_style & flag and [True]) or [False])[0]
2744 return res
2745
2746 def AddPage( # noqa: N802
2747 self, page: wx.Window, text: str, select: bool = False, image_id: int = -1
2748 ) -> None:
2749 """Add a page to the book.
2750
2751 Args:
2752 page (wx.Window): specifies the new page;
2753 text (str): specifies the text for the new page;
2754 select (bool): specifies whether the page should be selected;
2755 image_id (int): specifies the optional image index for the new page.
2756
2757 Note:
2758 The call to this function generates the page changing events.
2759 """
2760 if not page:
2761 return
2762
2763 if self._pages is None:
2764 raise ValueError("ImageContainer is not initialized")
2765
2766 page.Reparent(self)
2767
2768 self._windows.append(page)
2769
2770 if select or len(self._windows) == 1:
2771 self.SetSelection(len(self._windows) - 1)
2772 else:
2773 page.Hide()
2774
2775 self._pages.AddPage(text, select, image_id)
2776 self.ResizeTabArea()
2777 self.Refresh()
2778
2779 def InsertPage( # noqa: N802
2780 self,
2781 page_id: int,
2782 page: wx.Window,
2783 text: str,
2784 select: bool = False,
2785 image_id: int = -1,
2786 ) -> None:
2787 """Insert a page into the book at the specified position.
2788
2789 Args:
2790 page_id (int): specifies the position for the new page;
2791 page (wx.Window): specifies the new page;
2792 text (str): specifies the text for the new page;
2793 select (bool): specifies whether the page should be selected;
2794 image_id (int): specifies the optional image index for the new page.
2795
2796 Note:
2797 The call to this function generates the page changing events.
2798 """
2799 if not page:
2800 return
2801
2802 if self._pages is None:
2803 raise ValueError("LabelContainer is not initialized")
2804
2805 page.Reparent(self)
2806
2807 self._windows.insert(page_id, page)
2808
2809 if select or len(self._windows) == 1:
2810 self.SetSelection(page_id)
2811 else:
2812 page.Hide()
2813
2814 self._pages.InsertPage(page_id, text, select, image_id)
2815 self.ResizeTabArea()
2816 self.Refresh()
2817
2818 def DeletePage(self, page: int) -> None | bool: # noqa: N802
2819 """Delete the specified page, and the associated window.
2820
2821 Args:
2822 page (int): an integer specifying the page to be deleted.
2823
2824 Note:
2825 The call to this function generates the page changing events.
2826 """
2827 if page >= len(self._windows) or page < 0:
2828 return None
2829
2830 # Fire a closing event
2831 event = ImageNotebookEvent(wxEVT_IMAGENOTEBOOK_PAGE_CLOSING, self.GetId())
2832 event.SetSelection(page)
2833 event.SetEventObject(self)
2834 self.GetEventHandler().ProcessEvent(event)
2835
2836 # The event handler allows it?
2837 if not event.IsAllowed():
2838 return False
2839
2840 self.Freeze()
2841
2842 # Delete the requested page
2843 page_removed: wx.Window = self._windows[page]
2844
2845 # If the page is the current window, remove it from the sizer as well
2846 if page == self.GetSelection():
2847 self._mainSizer.Detach(page_removed)
2848
2849 # Remove it from the array as well
2850 self._windows.pop(page)
2851
2852 # Now we can destroy it in wxWidgets use Destroy instead of delete
2853 page_removed.Destroy()
2854 self._mainSizer.Layout()
2855
2856 if self._pages:
2857 self._pages.DoDeletePage(page)
2858 self.ResizeTabArea()
2859
2860 self.Thaw()
2861
2862 # Fire a closed event
2863 closed_event = ImageNotebookEvent(wxEVT_IMAGENOTEBOOK_PAGE_CLOSED, self.GetId())
2864 closed_event.SetSelection(page)
2865 closed_event.SetEventObject(self)
2866 self.GetEventHandler().ProcessEvent(closed_event)
2867 return True
2868
2869 def RemovePage(self, page: int) -> bool: # noqa: N802
2870 """Delete the specified page, without deleting the associated window.
2871
2872 Args:
2873 page (int): an integer specifying the page to be removed.
2874
2875 Note:
2876 The call to this function generates the page changing events.
2877 """
2878 if page >= len(self._windows):
2879 return False
2880
2881 # Fire a closing event
2882 event = ImageNotebookEvent(wxEVT_IMAGENOTEBOOK_PAGE_CLOSING, self.GetId())
2883 event.SetSelection(page)
2884 event.SetEventObject(self)
2885 self.GetEventHandler().ProcessEvent(event)
2886
2887 # The event handler allows it?
2888 if not event.IsAllowed():
2889 return False
2890
2891 self.Freeze()
2892
2893 # Remove the requested page
2894 page_removed: wx.Window = self._windows[page]
2895
2896 # If the page is the current window, remove it from the sizer as well
2897 if page == self.GetSelection():
2898 self._mainSizer.Detach(page_removed)
2899
2900 # Remove it from the array as well
2901 self._windows.pop(page)
2902 self._mainSizer.Layout()
2903 self.ResizeTabArea()
2904 self.Thaw()
2905
2906 if self._pages is not None:
2907 self._pages.DoDeletePage(page)
2908
2909 # Fire a closed event
2910 closed_event = ImageNotebookEvent(wxEVT_IMAGENOTEBOOK_PAGE_CLOSED, self.GetId())
2911 closed_event.SetSelection(page)
2912 closed_event.SetEventObject(self)
2913 self.GetEventHandler().ProcessEvent(closed_event)
2914
2915 return True
2916
2917 def ResizeTabArea(self) -> None: # noqa: N802
2918 """Resize the tab area if ``INB_FIT_LABELTEXT`` style is set."""
2919 if self._pages is None:
2920 return
2921
2922 agw_style: int = self.GetAGWWindowStyleFlag()
2923
2924 if agw_style & ImageBookStyle.INB_FIT_LABELTEXT == 0:
2925 return
2926
2927 if isinstance(self._pages, LabelContainer):
2928 self._pages.SetTabAreaWidth(self._calculate_max_tab_width())
2929 self._pages.Refresh()
2930
2931 def _calculate_max_tab_width(self) -> int:
2932 """Calculate the maximum width needed for the tab area."""
2933 if self._pages is None:
2934 return 100
2935
2936 dc = wx.MemoryDC()
2937 dc.SelectObject(wx.Bitmap(1, 1))
2938 font: wx.Font = wx.SystemSettings.GetFont(wx.SYS_DEFAULT_GUI_FONT)
2939 font.SetPointSize(int(font.GetPointSize() * self._fontSizeMultiple))
2940 if self.GetFontBold() or self.HasAGWFlag(ImageBookStyle.INB_BOLD_TAB_SELECTION):
2941 font.SetWeight(wx.FONTWEIGHT_BOLD)
2942 dc.SetFont(font)
2943 max_width = 0
2944
2945 for page in range(self.GetPageCount()):
2946 caption: str = self._pages.GetPageText(page)
2947 w, h = dc.GetTextExtent(caption)
2948 max_width: int = max(max_width, w)
2949
2950 max_width += 24 # TODO this is 6*4 6 is nPadding from drawlabel
2951
2952 if not self.HasAGWFlag(ImageBookStyle.INB_SHOW_ONLY_TEXT):
2953 max_width += self._pages._nImgSize * 2
2954
2955 return max(max_width, 100)
2956
2957 def DeleteAllPages(self) -> None: # noqa: N802
2958 """Delete all the pages in the book."""
2959 if not self._windows:
2960 return
2961
2962 self.Freeze()
2963
2964 for win in self._windows:
2965 win.Destroy()
2966
2967 self._windows = []
2968 self.Thaw()
2969
2970 if self._pages:
2971 self._pages.ClearAll()
2972 self._pages.Refresh()
2973
2974 def SetSelection(self, page: int) -> None: # noqa: N802
2975 """Change selection to the page given by page.
2976
2977 Args:
2978 page (int): an integer specifying the page to be selected.
2979
2980 Note:
2981 The call to this function generates the page changing events.
2982 """
2983 if self._pages is None:
2984 raise ValueError("Pages container is not initialized")
2985
2986 if page >= len(self._windows):
2987 return
2988
2989 if not self.GetEnabled(page):
2990 return
2991
2992 if page == self.GetSelection() and not self._bForceSelection:
2993 return
2994
2995 old_selection: int = self.GetSelection()
2996
2997 # Generate an event that indicates that an image is about to be selected
2998 event = ImageNotebookEvent(wxEVT_IMAGENOTEBOOK_PAGE_CHANGING, self.GetId())
2999 event.SetSelection(page)
3000 event.SetOldSelection(old_selection)
3001 event.SetEventObject(self)
3002 self.GetEventHandler().ProcessEvent(event)
3003
3004 # The event handler allows it?
3005 if not event.IsAllowed() and not self._bForceSelection:
3006 return
3007
3008 self.DoSetSelection(self._windows[page])
3009 # Now we can update the new selection
3010 self._pages._nIndex = page
3011
3012 # Refresh calls the OnPaint of this class
3013 self._pages.Refresh()
3014
3015 # Generate an event that indicates that an image was selected
3016 event_changed = ImageNotebookEvent(
3017 wxEVT_IMAGENOTEBOOK_PAGE_CHANGED, self.GetId()
3018 )
3019 event_changed.SetEventObject(self)
3020 event_changed.SetOldSelection(old_selection)
3021 event_changed.SetSelection(page)
3022 self.GetEventHandler().ProcessEvent(event_changed)
3023
3024 def AssignImageList(self, imglist: wx.ImageList) -> None: # noqa: N802
3025 """Assign an image list to the control.
3026
3027 Args:
3028 imglist (wx.ImageList): an instance of :class:`wx.ImageList`.
3029 """
3030 if self._pages is None:
3031 raise ValueError("ImageContainer is not initialized")
3032
3033 self._pages.AssignImageList(imglist)
3034
3035 # Force change
3036 self.SetAGWWindowStyleFlag(self.GetAGWWindowStyleFlag())
3037
3038 def GetSelection(self) -> int: # noqa: N802
3039 """Return the current selection.
3040
3041 Returns:
3042 int: The current selection.
3043 """
3044 if self._pages:
3045 return self._pages._nIndex
3046 return -1
3047
3048 def DoSetSelection(self, window: wx.Window) -> None: # noqa: N802
3049 """Select the window by the provided pointer.
3050
3051 Args:
3052 window (wx.Window): an instance of :class:`wx.Window`.
3053 """
3054 cur_sel: int = self.GetSelection()
3055 agw_style: int = self.GetAGWWindowStyleFlag()
3056 # Replace the window in the sizer
3057 self.Freeze()
3058
3059 # Check if a new selection was made
3060 b_insert_first: int = (
3061 agw_style & ImageBookStyle.INB_BOTTOM
3062 or agw_style & ImageBookStyle.INB_RIGHT
3063 )
3064
3065 if cur_sel >= 0:
3066 # Remove the window from the main sizer
3067 self._mainSizer.Detach(self._windows[cur_sel])
3068 self._windows[cur_sel].Hide()
3069
3070 if b_insert_first:
3071 self._mainSizer.Insert(0, window, 1, wx.EXPAND)
3072 else:
3073 self._mainSizer.Add(window, 1, wx.EXPAND)
3074
3075 window.Show()
3076 self._mainSizer.Layout()
3077 self.Thaw()
3078
3079 def GetImageList(self) -> None | wx.ImageList: # noqa: N802
3080 """Return the associated image list."""
3081 if self._pages is None:
3082 return None
3083 return self._pages.GetImageList()
3084
3085 def GetPageCount(self) -> int: # noqa: N802
3086 """Return the number of pages in the book.
3087
3088 Returns:
3089 int: The number of pages in the book.
3090 """
3091 return len(self._windows)
3092
3093 def GetFontBold(self) -> bool: # noqa: N802
3094 """Get the font bold status.
3095
3096 Returns:
3097 bool: ``True`` if the page captions are bold, ``False`` otherwise.
3098 """
3099 return self._fontBold
3100
3101 def SetFontBold(self, bold: bool) -> None: # noqa: N802
3102 """Set whether the page captions are bold or not.
3103
3104 Args:
3105 bold (bool): ``True`` or ``False``.
3106 """
3107 self._fontBold: bool = bold
3108
3109 def GetFontSizeMultiple(self) -> float: # noqa: N802
3110 """Get the font size multiple for the page captions."""
3111 return self._fontSizeMultiple
3112
3113 def SetFontSizeMultiple(self, multiple: float) -> None: # noqa: N802
3114 """Set the font size multiple for the page captions.
3115
3116 Args:
3117 multiple (float): The multiple to be applied to the system font to get the
3118 our font size.
3119 """
3120 self._fontSizeMultiple: float = multiple
3121
3122 def SetPageImage(self, page: int, image_id: int) -> None: # noqa: N802
3123 """Set the image index for the given page.
3124
3125 Args:
3126 page (int): an integer specifying the page index;
3127 image_id (int): an index into the image list.
3128 """
3129 if self._pages is None:
3130 raise ValueError("ImageContainer is not initialized")
3131
3132 self._pages.SetPageImage(page, image_id)
3133 self._pages.Refresh()
3134
3135 def SetPageText(self, page: int, text: str) -> None: # noqa: N802
3136 """Set the text for the given page.
3137
3138 Args:
3139 page (int): an integer specifying the page index;
3140 text (str): the new tab label.
3141 """
3142 if self._pages is None:
3143 raise ValueError("Pages container is not initialized")
3144 self._pages.SetPageText(page, text)
3145 self._pages.Refresh()
3146
3147 def GetPageText(self, page: int) -> str: # noqa: N802
3148 """Return the text for the given page.
3149
3150 Args:
3151 page (int): an integer specifying the page index.
3152 """
3153 if self._pages is None:
3154 raise ValueError("Pages container is not initialized")
3155 return self._pages.GetPageText(page)
3156
3157 def GetPageImage(self, page: int) -> int: # noqa: N802
3158 """Return the image index for the given page.
3159
3160 Args:
3161 page (int): an integer specifying the page index.
3162 """
3163 if self._pages is None:
3164 raise ValueError("ImageContainer is not initialized")
3165 return self._pages.GetPageImage(page)
3166
3167 def GetEnabled(self, page: int) -> bool: # noqa: N802
3168 """Return whether a tab is enabled or not.
3169
3170 Args:
3171 page (int): an integer specifying the page index.
3172 """
3173 if self._pages is None:
3174 raise ValueError("Pages container is not initialized")
3175 return self._pages.GetEnabled(page)
3176
3177 def EnableTab(self, page: int, enabled: bool = True) -> None: # noqa: N802
3178 """Enable or disable a tab.
3179
3180 Args:
3181 page (int): an integer specifying the page index;
3182 enabled (bool): ``True`` to enable a tab, ``False`` to disable it.
3183 """
3184 if page >= len(self._windows):
3185 return
3186
3187 if self._pages is None:
3188 raise ValueError("Pages container is not initialized")
3189
3190 self._windows[page].Enable(enabled)
3191 self._pages.EnableTab(page, enabled)
3192
3193 def GetPage(self, page: int) -> None | wx.Window: # noqa: N802
3194 """Return the window at the given page position.
3195
3196 Args:
3197 page (int): an integer specifying the page to be returned.
3198 """
3199 if page >= len(self._windows):
3200 return None
3201
3202 return self._windows[page]
3203
3204 def GetCurrentPage(self) -> None | wx.Window: # noqa: N802
3205 """Return the currently selected notebook page or ``None``."""
3206 selection: int = self.GetSelection()
3207 if selection < 0:
3208 return None
3209 return self.GetPage(selection)
3210
3211 def OnNavigationKey(self, event: wx.NavigationKeyEvent) -> None: # noqa: N802
3212 """Handle the ``wx.EVT_NAVIGATION_KEY`` event for :class:`FlatBookBase`.
3213
3214 Args:
3215 event (wx.NavigationKeyEvent): a :class:`NavigationKeyEvent` event to be
3216 processed.
3217 """
3218 if event.IsWindowChange():
3219 if self.GetPageCount() == 0:
3220 return
3221
3222 # change pages
3223 self.AdvanceSelection(event.GetDirection())
3224
3225 else:
3226 event.Skip()
3227
3228 def AdvanceSelection(self, forward: bool = True) -> None: # noqa: N802
3229 """Cycle through the tabs.
3230
3231 Args:
3232 forward (bool): if ``True``, the selection is advanced in ascending order
3233 (to the right), otherwise the selection is advanced in descending order.
3234
3235 Note:
3236 The call to this function generates the page changing events.
3237 """
3238 n_sel: int = self.GetSelection()
3239
3240 if n_sel < 0:
3241 return
3242
3243 n_max: int = self.GetPageCount() - 1
3244
3245 if forward:
3246 new_selection: int = ((n_sel == n_max and [0]) or [n_sel + 1])[0]
3247 else:
3248 new_selection = ((n_sel == 0 and [n_max]) or [n_sel - 1])[0]
3249
3250 self.SetSelection(new_selection)
3251
3252 def ChangeSelection(self, page: int) -> None | int: # noqa: N802
3253 """Change the selection for the given page, returning the previous selection.
3254
3255 Args:
3256 page (int): an integer specifying the page to be selected.
3257
3258 Note:
3259 The call to this function does not generate the page changing events.
3260 """
3261 if page < 0 or page >= self.GetPageCount():
3262 return None
3263
3264 old_page: int = self.GetSelection()
3265 if page >= 0 and page < len(self._windows):
3266 self.DoSetSelection(self._windows[page]) # Pass the window object
3267
3268 return old_page
3269
3270 @property
3271 def PageText(self) -> str: # noqa: N802
3272 """Return the text for the current page.
3273
3274 Returns:
3275 str: The text for the current page.
3276 """
3277 page: int = self.GetSelection()
3278 if page >= 0:
3279 return self.GetPageText(page)
3280 return ""
3281
3282 @PageText.setter
3283 def PageText(self, text: str) -> None: # noqa: N802
3284 """Set the text for the current page.
3285
3286 Args:
3287 text (str): The new tab label.
3288 """
3289 page: int = self.GetSelection()
3290 if page >= 0:
3291 self.SetPageText(page, text)
3292
3293 @property
3294 def PageImage(self) -> int: # noqa: N802
3295 """Return the image index for the current page.
3296
3297 Returns:
3298 int: The image index for the current page.
3299 """
3300 return self.GetPageImage(self.GetSelection())
3301
3302 @PageImage.setter
3303 def PageImage(self, value: int) -> None: # noqa: N802
3304 self.SetPageImage(self.GetSelection(), value)
3305
3306 @property
3307 def Page(self) -> None | wx.Window: # noqa: N802
3308 """Return the currently selected notebook page or ``None``."""
3309 return self.GetCurrentPage()
3310
3311 @property
3312 def CurrentPage(self) -> None | wx.Window: # noqa: N802
3313 """Return the currently selected notebook page or ``None``."""
3314 return self.GetCurrentPage()
3315
3316 @property
3317 def PageCount(self) -> int: # noqa: N802
3318 """Return the number of pages in the book.
3319
3320 Returns:
3321 int: The number of pages in the book.
3322 """
3323 return self.GetPageCount()
3324
3325 @property
3326 def Selection(self) -> int: # noqa: N802
3327 """Return the current selection.
3328
3329 Returns:
3330 int: The current selection.
3331 """
3332 return self.GetSelection()
3333
3334 @Selection.setter
3335 def Selection(self, page: int) -> None: # noqa: N802
3336 """Change selection to the page given by page.
3337
3338 Args:
3339 page (int): an integer specifying the page to be selected.
3340
3341 Note:
3342 Setting this property generates the page changing events.
3343 """
3344 self.SetSelection(page)
3345
3346
3347 # ---------------------------------------------------------------------------- #
3348 # Class FlatImageBook
3349 # ---------------------------------------------------------------------------- #
3350
3351
3352 class FlatImageBook(FlatBookBase):
3353 """Default implementation of the image book.
3354
3355 It is like a :class:`Notebook`,
3356 except that images are used to control the different pages.
3357
3358 This container is usually used for configuration dialogs etc.
3359
3360 Note:
3361 Currently, this control works properly for images of size 32x32 and bigger.
3362 """
3363
3364 def __init__(
3365 self,
3366 parent: wx.Window,
3367 id: int = wx.ID_ANY, # noqa: A002
3368 pos: wx.Point = wx.DefaultPosition,
3369 size: wx.Size = wx.DefaultSize,
3370 style: int = 0,
3371 agw_style: int = 0,
3372 name: str = "FlatImageBook",
3373 ) -> None:
3374 """Construct the default class.
3375
3376 Args:
3377 parent (wx.Window): parent window. Must not be ``None``;
3378 id (int): window identifier. A value of -1 indicates a default value;
3379 pos (wx.Point): the control position.
3380 A value of (-1, -1) indicates a default position, chosen by either the
3381 windowing system or wxPython, depending on platform;
3382 size (wx.Size): the control size.
3383 A value of (-1, -1) indicates a default size, chosen by either the
3384 windowing system or wxPython, depending on platform;
3385 style (int): the underlying :class:`Panel` window style;
3386 agw_style (int): the AGW-specific window style.
3387 This can be a combination of the following bits:
3388 =========================== =========== ================================
3389 Window Styles Hex Value Description
3390 =========================== =========== ================================
3391 ``INB_BOTTOM`` 0x1 Place labels below the page
3392 area. Available only for
3393 :class:`FlatImageBook`.
3394 ``INB_LEFT`` 0x2 Place labels on the left side.
3395 Available only for
3396 :class:`FlatImageBook`.
3397 ``INB_RIGHT`` 0x4 Place labels on the right side.
3398 ``INB_TOP`` 0x8 Place labels above the page
3399 area.
3400 ``INB_BORDER`` 0x10 Draws a border around
3401 :class:`LabelBook` or
3402 :class:`FlatImageBook`.
3403 ``INB_SHOW_ONLY_TEXT`` 0x20 Shows only text labels and no
3404 images. Available only for
3405 :class:`LabelBook`.
3406 ``INB_SHOW_ONLY_IMAGES`` 0x40 Shows only tab images and no
3407 label texts. Available only for
3408 :class:`LabelBook`.
3409 ``INB_FIT_BUTTON`` 0x80 Displays a pin button to
3410 show/hide the book control.
3411 ``INB_DRAW_SHADOW`` 0x100 Draw shadows below the book
3412 tabs. Available only for
3413 :class:`LabelBook`.
3414 ``INB_USE_PIN_BUTTON`` 0x200 Displays a pin button to
3415 show/hide the book control.
3416 ``INB_GRADIENT_BACKGROUND`` 0x400 Draws a gradient shading on the
3417 tabs background. Available only
3418 for :class:`LabelBook`.
3419 ``INB_WEB_HILITE`` 0x800 On mouse hovering, tabs behave
3420 like html hyperlinks. Available
3421 only for :class:`LabelBook`.
3422 ``INB_NO_RESIZE`` 0x1000 Don't allow resizing of the tab
3423 area.
3424 ``INB_FIT_LABELTEXT`` 0x2000 Will fit the tab area to the
3425 longest text (or text+image if
3426 you have images) in all the
3427 tabs.
3428 ``INB_BOLD_TAB_SELECTION`` 0x4000 Show the selected tab text using
3429 a bold font.
3430 =========================== =========== ================================
3431 name (str): the window name.
3432 """
3433 FlatBookBase.__init__(self, parent, id, pos, size, style, agw_style, name)
3434
3435 self._pages: ImageContainer = self.CreateImageContainer()
3436
3437 if self._pages is None:
3438 raise ValueError("Failed to create ImageContainer")
3439
3440 if agw_style & ImageBookStyle.INB_LEFT or agw_style & ImageBookStyle.INB_RIGHT:
3441 self._mainSizer = wx.BoxSizer(wx.HORIZONTAL)
3442 else:
3443 self._mainSizer = wx.BoxSizer(wx.VERTICAL)
3444
3445 self.SetSizer(self._mainSizer)
3446
3447 # Add the tab container to the sizer
3448 self._mainSizer.Add(self._pages, 0, wx.EXPAND)
3449
3450 if agw_style & ImageBookStyle.INB_LEFT or agw_style & ImageBookStyle.INB_RIGHT:
3451 self._pages.SetSizeHints(self._pages.GetImageSize() * 2, -1)
3452 else:
3453 self._pages.SetSizeHints(-1, self._pages.GetImageSize() * 2)
3454
3455 self._mainSizer.Layout()
3456
3457 def CreateImageContainer(self) -> ImageContainer: # noqa: N802
3458 """Create the image container class for :class:`FlatImageBook`."""
3459 return ImageContainer(self, wx.ID_ANY, agw_style=self.GetAGWWindowStyleFlag())
3460
3461
3462 # ---------------------------------------------------------------------------- #
3463 # Class LabelBook
3464 # ---------------------------------------------------------------------------- #
3465
3466
3467 class LabelBook(FlatBookBase):
3468 """An implementation of a notebook control.
3469
3470 Except that instead of having tabs to show labels,
3471 it labels to the right or left (arranged horizontally).
3472 """
3473
3474 def __init__(
3475 self,
3476 parent: wx.Window,
3477 id: int = wx.ID_ANY, # noqa: A002
3478 pos: wx.Point = wx.DefaultPosition,
3479 size: wx.Size = wx.DefaultSize,
3480 style: int = 0,
3481 agw_style: int = 0,
3482 name: str = "LabelBook",
3483 ) -> None:
3484 """Construct the default class.
3485
3486 Args:
3487 parent (wx.Window): parent window. Must not be ``None``;
3488 id (int): window identifier. A value of -1 indicates a default value;
3489 pos (wx.Point): the control position.
3490 A value of (-1, -1) indicates a default position, chosen by either the
3491 windowing system or wxPython, depending on platform;
3492 size (wx.Size): the control size.
3493 A value of (-1, -1) indicates a default size, chosen by either the
3494 windowing system or wxPython, depending on platform;
3495 style (int): the underlying :class:`Panel` window style;
3496 agw_style (int): the AGW-specific window style.
3497 This can be a combination of the following bits:
3498 =========================== =========== ================================
3499 Window Styles Hex Value Description
3500 =========================== =========== ================================
3501 ``INB_BOTTOM`` 0x1 Place labels below the page
3502 area. Available only for
3503 :class:`FlatImageBook`.
3504 ``INB_LEFT`` 0x2 Place labels on the left side.
3505 Available only for
3506 :class:`FlatImageBook`.
3507 ``INB_RIGHT`` 0x4 Place labels on the right side.
3508 ``INB_TOP`` 0x8 Place labels above the page
3509 area.
3510 ``INB_BORDER`` 0x10 Draws a border around
3511 :class:`LabelBook` or
3512 :class:`FlatImageBook`.
3513 ``INB_SHOW_ONLY_TEXT`` 0x20 Shows only text labels and no
3514 images. Available only for
3515 :class:`LabelBook`.
3516 ``INB_SHOW_ONLY_IMAGES`` 0x40 Shows only tab images and no
3517 label texts. Available only for
3518 :class:`LabelBook`.
3519 ``INB_FIT_BUTTON`` 0x80 Displays a pin button to
3520 show/hide the book control.
3521 ``INB_DRAW_SHADOW`` 0x100 Draw shadows below the book
3522 tabs. Available only for
3523 :class:`LabelBook`.
3524 ``INB_USE_PIN_BUTTON`` 0x200 Displays a pin button to
3525 show/hide the book control.
3526 ``INB_GRADIENT_BACKGROUND`` 0x400 Draws a gradient shading on the
3527 tabs background. Available only
3528 for :class:`LabelBook`.
3529 ``INB_WEB_HILITE`` 0x800 On mouse hovering, tabs behave
3530 like html hyperlinks. Available
3531 only for :class:`LabelBook`.
3532 ``INB_NO_RESIZE`` 0x1000 Don't allow resizing of the tab
3533 area.
3534 ``INB_FIT_LABELTEXT`` 0x2000 Will fit the tab area to the
3535 longest text (or text+image if
3536 you have images) in all the
3537 tabs.
3538 ``INB_BOLD_TAB_SELECTION`` 0x4000 Show the selected tab text using
3539 a bold font.
3540 =========================== =========== ================================
3541 name (str): the window name.
3542 """
3543 FlatBookBase.__init__(self, parent, id, pos, size, style, agw_style, name)
3544
3545 self._pages: LabelContainer = self.CreateImageContainer()
3546 print(f"self._pages initialized: {self._pages}")
3547
3548 if self._pages is None:
3549 raise ValueError("Failed to create LabelContainer")
3550
3551 # Label book specific initialization
3552 self._mainSizer = wx.BoxSizer(wx.HORIZONTAL)
3553 self.SetSizer(self._mainSizer)
3554
3555 # Add the tab container to the sizer
3556 self._mainSizer.Add(self._pages, 0, wx.EXPAND)
3557 self._pages.SetSizeHints(self._pages.GetTabAreaWidth(), -1)
3558
3559 # Initialize the colours maps
3560 self._pages.InitializeColours()
3561
3562 self.Bind(wx.EVT_SIZE, self.OnSize)
3563
3564 def CreateImageContainer(self) -> LabelContainer: # noqa: N802
3565 """Create the image container (LabelContainer) class for :class:`LabelBook`."""
3566 return LabelContainer(self, wx.ID_ANY, agw_style=self.GetAGWWindowStyleFlag())
3567
3568 def SetColour(self, which: int, colour: wx.Colour) -> None: # noqa: N802
3569 """Set the colour for the specified parameter.
3570
3571 Args:
3572 which (int): the colour key;
3573 colour (wx.Colour): a valid :class:`wx.Colour` instance.
3574
3575 See:
3576 :meth:`LabelContainer.SetColour() <LabelContainer.SetColour>` for a list of
3577 valid colour keys.
3578 """
3579 self._pages.SetColour(which, colour)
3580
3581 def GetColour(self, which: int) -> wx.Colour: # noqa: N802
3582 """Return the colour for the specified parameter.
3583
3584 Args:
3585 which (int): the colour key.
3586
3587 See:
3588 :meth:`LabelContainer.SetColour() <LabelContainer.SetColour>` for a list of
3589 valid colour keys.
3590 """
3591 return self._pages.GetColour(which)
3592
3593 def OnSize(self, event: wx.SizeEvent) -> None: # noqa: N802
3594 """Handle the ``wx.EVT_SIZE`` event for :class:`LabelBook`.
3595
3596 Args:
3597 event (wx.SizeEvent): a :class:`wx.SizeEvent` event to be processed.
3598 """
3599 self._pages.Refresh()
3600 event.Skip()