Debian Codegraph @

DisplayCAL/lib/agw/fourwaysplitter.py

raw
1 # ------------------------------------------------------------------------------------ #
2 # FOURWAYSPLITTER wxPython IMPLEMENTATION
3 #
4 # Andrea Gavana, @ 03 Nov 2006
5 # Latest Revision: 16 Jul 2012, 15.00 GMT
6 #
7 #
8 # TODO List
9 #
10 # 1. Any idea?
11 #
12 # For All Kind Of Problems, Requests Of Enhancements And Bug Reports,
13 # Please Write To Me At:
14 #
15 # [email protected]
16 # [email protected]
17 #
18 # Or, Obviously, To The wxPython Mailing List!!!
19 #
20 # Tags: phoenix-port, unittest, documented, py3-port
21 #
22 # End Of Comments
23 # ------------------------------------------------------------------------------------ #
24
25 """FourWaySplitter is a layout manager that arranges 4 child panes in a window.
26
27 Description
28 ===========
29
30 The :class:`FourWaySplitter` is a layout manager which manages four children like four
31 panes in a window. You can use a four-way splitter for example in a CAD program where
32 you may want to maintain three orthographic views, and one oblique view of a model.
33
34 The :class:`FourWaySplitter` allows interactive repartitioning of the panes by means of
35 moving the central splitter bars. When the :class:`FourWaySplitter` is itself resized,
36 each child is proportionally resized, maintaining the same split-percentage.
37
38 The main characteristics of :class:`FourWaySplitter` are:
39
40 - Handles horizontal, vertical or four way sizing via the sashes;
41 - Delayed or live update when resizing;
42 - Possibility to swap windows;
43 - Setting the vertical and horizontal split fractions;
44 - Possibility to expand a window by hiding the other 3.
45
46 And a lot more. See the demo for a complete review of the functionalities.
47
48
49 Usage
50 =====
51
52 Usage example::
53
54 import wx
55 import wx.lib.agw.fourwaysplitter as fws
56
57 class MyFrame(wx.Frame):
58
59 def __init__(self, parent: None | wx.Window) -> None:
60
61 wx.Frame.__init__(self, parent, -1, "FourWaySplitter Demo")
62
63 splitter = fws.FourWaySplitter(self, -1, agw_style=wx.SP_LIVE_UPDATE)
64
65 # Put in some coloured panels...
66 for colour in [wx.RED, wx.WHITE, wx.BLUE, wx.GREEN]:
67
68 panel = wx.Panel(splitter)
69 panel.SetBackgroundColour(colour)
70
71 splitter.AppendWindow(panel)
72
73
74 # our normal wxApp-derived class, as usual
75
76 app = wx.App(0)
77
78 frame = MyFrame(None)
79 app.SetTopWindow(frame)
80 frame.Show()
81
82 app.MainLoop()
83
84
85
86 Supported Platforms
87 ===================
88
89 :class:`FourWaySplitter` has been tested on the following platforms:
90 * Windows (Windows XP);
91 * Linux Ubuntu (Dapper 6.06)
92
93
94 Window Styles
95 =============
96
97 This class supports the following window styles:
98
99 ================== =========== =========================================================
100 Window Styles Hex Value Description
101 ================== =========== =========================================================
102 ``SP_NOSASH`` 0x10 No sash will be drawn on :class:`FourWaySplitter`.
103 ``SP_LIVE_UPDATE`` 0x80 Don't draw XOR line but resize the child windows
104 immediately.
105 ``SP_3DBORDER`` 0x200 Draws a 3D effect border.
106 ================== =========== =========================================================
107
108
109 Events Processing
110 =================
111
112 This class processes the following events:
113
114 ================================== =====================================================
115 Event Name Description
116 ================================== =====================================================
117 ``EVT_SPLITTER_SASH_POS_CHANGED`` The sash position was changed.
118 This event is generated after the user releases the
119 mouse after dragging the splitter. Processes a
120 ``wx.wxEVT_COMMAND_SPLITTER_SASH_POS_CHANGED``
121 event.
122 ``EVT_SPLITTER_SASH_POS_CHANGING`` The sash position is in the process of being changed.
123 You may prevent this change from happening by
124 calling `Veto` or you may also modify the position
125 of the tracking bar to properly reflect the position
126 that would be set if the drag were to be completed
127 at this point. Processes a
128 ``wx.wxEVT_COMMAND_SPLITTER_SASH_POS_CHANGING``
129 event.
130 ================================== =====================================================
131
132
133 License And Version
134 ===================
135
136 :class:`FourWaySplitter` is distributed under the wxPython license.
137
138 Latest Revision: Andrea Gavana @ 16 Jul 2012, 15.00 GMT
139
140 Version 0.5
141 """
142
143 from __future__ import annotations
144
145 import wx
146
147 _RENDER_VER = (2, 6, 1, 1)
148
149 # Tolerance for mouse shape and sizing
150 _TOLERANCE = 5
151
152 # Modes
153 NOWHERE = 0
154 """No sashes are changing position."""
155 FLAG_CHANGED = 1
156 """Sashes are changing position."""
157 FLAG_PRESSED = 2
158 """Sashes are in a pressed state."""
159
160 # FourWaySplitter styles
161 SP_NOSASH = wx.SP_NOSASH
162 """No sash will be drawn on :class:`FourWaySplitter`."""
163 SP_LIVE_UPDATE = wx.SP_LIVE_UPDATE
164 """Don't draw XOR line but resize the child windows immediately."""
165 SP_3DBORDER = wx.SP_3DBORDER
166 """Draw a 3D effect border."""
167
168 # FourWaySplitter events
169 EVT_SPLITTER_SASH_POS_CHANGING: wx.PyEventBinder = wx.EVT_SPLITTER_SASH_POS_CHANGING
170 """The sash position is in the process of being changed.
171
172 You may prevent this change from happening by calling `Veto` or you may also modify the
173 position of the tracking bar to properly reflect the position that would be set if the
174 drag were to be completed at this point.
175 Processes a ``wx.wxEVT_COMMAND_SPLITTER_SASH_POS_CHANGING`` event.
176 """
177 EVT_SPLITTER_SASH_POS_CHANGED: wx.PyEventBinder = wx.EVT_SPLITTER_SASH_POS_CHANGED
178 """The sash position was changed.
179
180 This event is generated after the user releases the mouse after dragging the splitter.
181 Processes a ``wx.wxEVT_COMMAND_SPLITTER_SASH_POS_CHANGED`` event.
182 """
183
184 # ------------------------------------------------------------------------------------ #
185 # Class FourWaySplitterEvent
186 # ------------------------------------------------------------------------------------ #
187
188
189 class FourWaySplitterEvent(wx.CommandEvent):
190 """This event class adds a sash index accessor to :class:`SplitterEvent`.
191
192 The same event type IDs and event binders are used as with :class:`SplitterEvent`.
193
194 Args:
195 evt_type (int): the event type;
196 splitter (None | FourWaySplitter): The associated :class:`FourWaySplitter`
197 window.
198 """
199
200 def __init__(
201 self,
202 evt_type: int = wx.wxEVT_NULL,
203 splitter: None | FourWaySplitter = None,
204 ) -> None:
205 wx.CommandEvent.__init__(self, evt_type)
206
207 if splitter:
208 self.SetEventObject(splitter)
209 self.SetId(splitter.GetId())
210
211 self.sashIdx = -1
212 self.sashPos: int | wx.Point = -1
213 self.isAllowed = True
214
215 def SetSashIdx(self, idx: int) -> None: # noqa: N802
216 """Set the index of the sash currently involved in the event.
217
218 Args:
219 idx (int): an integer between 0 and 3,
220 representing the index of the sash involved in the event.
221 """
222 self.sashIdx = idx
223
224 def SetSashPosition(self, pos: int | wx.Point) -> None: # noqa: N802
225 """For EVT_SPLITTER_SASH_POS_CHANGED events, set the new sash position.
226
227 In the case of ``EVT_SPLITTER_SASH_POS_CHANGING`` events, sets the new
228 tracking bar position so visual feedback during dragging will represent
229 that change that will actually take place. Set to -1 from the event
230 handler code to prevent repositioning.
231
232 Args:
233 pos (int | wx.Point): the new sash position.
234
235 Note:
236 May only be called while processing ``EVT_SPLITTER_SASH_POS_CHANGING``
237 and ``EVT_SPLITTER_SASH_POS_CHANGED`` events.
238 """
239 self.sashPos: int | wx.Point = pos
240
241 def GetSashIdx(self) -> int: # noqa: N802
242 """Return the index of the sash currently involved in the event.
243
244 Returns:
245 int: the index of the sash currently involved in the event.
246 """
247 return self.sashIdx
248
249 def GetSashPosition(self) -> int | wx.Point: # noqa: N802
250 """Return the new sash position.
251
252 Returns:
253 int | wx.Point: the new sash position.
254
255 Note:
256 May only be called while processing ``EVT_SPLITTER_SASH_POS_CHANGING`` and
257 ``EVT_SPLITTER_SASH_POS_CHANGED`` events.
258 """
259 return self.sashPos
260
261 # methods from wx.NotifyEvent
262 def Veto(self) -> None: # noqa: N802
263 """Prevent the change announced by this event from happening.
264
265 Note:
266 It is in general a good idea to notify the user about the reasons
267 for vetoing the change because otherwise the applications behaviour
268 (which just refuses to do what the user wants) might be quite
269 surprising.
270 """
271 self.isAllowed = False
272
273 def Allow(self) -> None: # noqa: N802
274 """Do the opposite of :meth:`~FourWaySplitterEvent.Veto`.
275
276 It explicitly allows the event to be processed.
277 For most events it is not necessary to call this method as the events
278 are allowed anyhow but some are forbidden by default (this will be
279 mentioned in the corresponding event description).
280 """
281 self.isAllowed = True
282
283 def IsAllowed(self) -> bool: # noqa: N802
284 """Return ``True`` if change is allowed, ``False`` if vetoed.
285
286 Returns:
287 bool: ``True`` if change is allowed, ``False`` if vetoed.
288 """
289 return self.isAllowed
290
291
292 # ---------------------------------------------------------------------------- #
293 # Class FourWaySplitter
294 # ---------------------------------------------------------------------------- #
295
296
297 class FourWaySplitter(wx.Panel):
298 """Similar to :class:`SplitterWindow`, but with four windows and two sashes.
299
300 Many of the same styles, constants,
301 and methods behave the same as in :class:`SplitterWindow`.
302 However, in addition to the ability to drag the vertical and the horizontal
303 sash, by dragging at the intersection between the two sashes, it is possible
304 to resize the four windows at the same time.
305
306 Note:
307 These things are not yet supported:
308 * Minimum pane size (minimum of what? Width? Height?).
309 * Using negative sash positions to indicate a position offset from
310 the end.
311 * User controlled unsplitting with double clicks on the sash
312 (but supported via the :meth:`FourWaySplitter.SetExpanded()
313 <FourWaySplitter.SetExpanded>` method).
314 * Sash gravity.
315 """
316
317 def __init__(
318 self,
319 parent: wx.Window,
320 id: int = wx.ID_ANY, # noqa: A002
321 pos: wx.Point = wx.DefaultPosition,
322 size: wx.Size = wx.DefaultSize,
323 style: int = 0,
324 agw_style: int = 0,
325 name: str = "FourWaySplitter",
326 ) -> None:
327 """Construct the default class.
328
329 Args:
330 parent (wx.Window): parent window. Must not be ``None``;
331 id (int): window identifier. A value of -1 indicates a default value;
332 pos (wx.Point): the control position.
333 A value of (-1, -1) indicates a default position, chosen by
334 either the windowing system or wxPython, depending on platform;
335 size (wx.Size): the control size. A value of (-1, -1) indicates a
336 default size, chosen by either the windowing system or wxPython,
337 depending on platform;
338 style (int): the underlying :class:`Panel` window style;
339 agw_style (int): the AGW-specific window style.
340 It can be a combination of the following bits:
341 ================== =========== =========================================
342 Window Styles Hex Value Description
343 ================== =========== =========================================
344 ``SP_NOSASH`` 0x10 No sash will be drawn on
345 :class:`FourWaySplitter`.
346 ``SP_LIVE_UPDATE`` 0x80 Don't draw XOR line but resize the child
347 windows immediately.
348 ``SP_3DBORDER`` 0x200 Draws a 3D effect border.
349 ================== =========== =========================================
350 name (str): the window name.
351 """
352 # always turn on tab traversal
353 style |= wx.TAB_TRAVERSAL
354
355 # and turn off any border styles
356 style &= ~wx.BORDER_MASK
357 style |= wx.BORDER_NONE
358
359 self._agw_style = agw_style
360
361 # initialize the base class
362 wx.Panel.__init__(self, parent, id, pos, size, style, name)
363 self.SetBackgroundStyle(wx.BG_STYLE_CUSTOM)
364
365 self._windows: list[wx.Window] = []
366
367 self._splitx = 0
368 self._splity = 0
369 self._expanded = -1
370 self._fhor = 5000
371 self._fver = 5000
372 self._offx = 0
373 self._offy = 0
374 self._mode = NOWHERE
375 self._flags = 0
376 self._isHot = False
377
378 self._sashTrackerPen = wx.Pen(wx.BLACK, 2, wx.PENSTYLE_SOLID)
379
380 self._sashCursorWE = wx.Cursor(wx.CURSOR_SIZEWE)
381 self._sashCursorNS = wx.Cursor(wx.CURSOR_SIZENS)
382 self._sashCursorSIZING = wx.Cursor(wx.CURSOR_SIZING)
383
384 self.Bind(wx.EVT_PAINT, self.OnPaint)
385 self.Bind(wx.EVT_MOTION, self.OnMotion)
386 self.Bind(wx.EVT_SIZE, self.OnSize)
387 self.Bind(wx.EVT_LEFT_DOWN, self.OnLeftDown)
388 self.Bind(wx.EVT_LEFT_UP, self.OnLeftUp)
389 self.Bind(wx.EVT_LEAVE_WINDOW, self.OnLeaveWindow)
390 self.Bind(wx.EVT_ENTER_WINDOW, self.OnEnterWindow)
391
392 def _IsVersionGreaterOrEqual(self, version: tuple[int, int, int, int]) -> bool: # noqa: N802
393 """Compare the current wxPython version with the given version.
394
395 Args:
396 version (tuple[int, int, int, int]): a tuple of version numbers.
397
398 Returns:
399 bool: ``True`` if the current wxPython version is greater or equal to the
400 given version.
401 """
402 wx_version = wx.VERSION[:3]
403 return (
404 wx_version[0] > version[0]
405 or (wx_version[0] == version[0] and wx_version[1] > version[1])
406 or (
407 wx_version[0] == version[0]
408 and wx_version[1] == version[1]
409 and wx_version[2] >= version[2]
410 )
411 )
412
413 def SetAGWWindowStyleFlag(self, agw_style: int) -> None: # noqa: N802
414 """Set the :class:`FourWaySplitter` window style flags.
415
416 Args:
417 agw_style (int): the AGW-specific window style.
418 This can be a combination of the following bits:
419 ================== =========== =========================================
420 Window Styles Hex Value Description
421 ================== =========== =========================================
422 ``SP_NOSASH`` 0x10 No sash will be drawn on
423 :class:`FourWaySplitter`.
424 ``SP_LIVE_UPDATE`` 0x80 Don't draw XOR line but resize the child
425 windows immediately.
426 ``SP_3DBORDER`` 0x200 Draws a 3D effect border.
427 ================== =========== =========================================
428 """
429 self._agw_style = agw_style
430 self.Refresh()
431
432 def GetAGWWindowStyleFlag(self) -> int: # noqa: N802
433 """Return the :class:`FourWaySplitter` window style.
434
435 See:
436 :meth:`~FourWaySplitter.SetAGWWindowStyleFlag` for a list of possible window
437 styles.
438
439 Returns:
440 int: The AGW-specific window style.
441 """
442 return self._agw_style
443
444 def AppendWindow(self, window: wx.Window) -> None: # noqa: N802
445 """Add a new window to the splitter at the right or bottom.
446
447 Args:
448 window (wx.Window): an instance of :class:`wx.Window`.
449 """
450 self.InsertWindow(len(self._windows), window)
451
452 def InsertWindow(self, idx: int, window: wx.Window) -> None: # noqa: N802
453 """Insert a new window into the splitter at the position given in `idx`.
454
455 Args:
456 idx (int): the index at which the window will be inserted;
457 window (wx.Window): an instance of :class:`wx.Window`.
458 """
459 if window in self._windows:
460 raise RuntimeError("A window can only be in the splitter once!")
461
462 self._windows.insert(idx, window)
463
464 self._SizeWindows()
465
466 def DetachWindow(self, window: wx.Window) -> None: # noqa: N802
467 """Remove the window from the stack of windows managed by the splitter.
468
469 The window will still exist so you should `Hide` or `Destroy` it as needed.
470
471 Args:
472 window (wx.Window): an instance of :class:`wx.Window`.
473 """
474 if window not in self._windows:
475 raise RuntimeError("Unknown window!")
476
477 idx = self._windows.index(window)
478 del self._windows[idx]
479
480 self._SizeWindows()
481
482 def ReplaceWindow(self, old_window: wx.Window, new_window: wx.Window) -> None: # noqa: N802
483 """Replace `oldWindow` with `newWindow` in the splitter.
484
485 The `oldWindow` window will still exist so you should `Hide` or `Destroy` it as
486 needed.
487
488 Args:
489 old_window (wx.Window): an instance of :class:`wx.Window`;
490 new_window (wx.Window): another instance of :class:`wx.Window`.
491 """
492 if old_window not in self._windows:
493 raise RuntimeError("Unknown window!")
494
495 idx = self._windows.index(old_window)
496 self._windows[idx] = new_window
497
498 self._SizeWindows()
499
500 def ExchangeWindows(self, window1: wx.Window, window2: wx.Window) -> None: # noqa: N802
501 """Trade the positions in the splitter of the two windows.
502
503 Args:
504 window1 (wx.Window): an instance of :class:`wx.Window`;
505 window2 (wx.Window): another instance of :class:`wx.Window`.
506 """
507 if window1 not in self._windows or window2 not in self._windows:
508 raise RuntimeError("Unknown window!")
509
510 idx1 = self._windows.index(window1)
511 idx2 = self._windows.index(window2)
512 self._windows[idx1] = window2
513 self._windows[idx2] = window1
514
515 if "__WXMSW__" in wx.Platform:
516 self.Freeze()
517
518 self._SizeWindows()
519
520 if "__WXMSW__" in wx.Platform:
521 self.Thaw()
522
523 def GetWindow(self, idx: int) -> None | wx.Window: # noqa: N802
524 """Return the window at the index `idx`.
525
526 Args:
527 idx (int): the index at which the window is located.
528
529 Returns:
530 None | wx.Window: The window at the specified index or `None`
531 if the index is out of range.
532 """
533 if len(self._windows) > idx:
534 return self._windows[idx]
535
536 return None
537
538 # Get top left child
539 def GetTopLeft(self) -> None | wx.Window: # noqa: N802
540 """Return the top left window (window index: 0).
541
542 Returns:
543 None | wx.Window: The top left window or ``None`` if the index is
544 out of range.
545 """
546 return self.GetWindow(0)
547
548 # Get top right child
549 def GetTopRight(self) -> None | wx.Window: # noqa: N802
550 """Return the top right window (window index: 1).
551
552 Returns:
553 None | wx.Window: The top right window or ``None`` if the
554 index is out of range.
555 """
556 return self.GetWindow(1)
557
558 # Get bottom left child
559 def GetBottomLeft(self) -> None | wx.Window: # noqa: N802
560 """Return the bottom left window (window index: 2).
561
562 Returns:
563 None | wx.Window: The bottom left window or ``None`` if the
564 index is out of range.
565 """
566 return self.GetWindow(2)
567
568 # Get bottom right child
569 def GetBottomRight(self) -> None | wx.Window: # noqa: N802
570 """Return the bottom right window (window index: 3).
571
572 Returns:
573 None | wx.Window: The bottom right window or ``None`` if the
574 index is out of range.
575 """
576 return self.GetWindow(3)
577
578 def DoGetBestSize(self) -> wx.Size: # noqa: N802
579 """Get the size which best suits the window.
580
581 For a control, it would be the minimal size which doesn't truncate the control,
582 for a panel - the same size as it would have after a call to `Fit()`.
583
584 Note:
585 Overridden from :class:`Panel`.
586
587 Returns:
588 wx.Size: The best size for the window.
589 """
590 if not self._windows:
591 # something is better than nothing...
592 return wx.Size(10, 10)
593
594 width = 0
595 height = 0
596 border = self._GetBorderSize()
597
598 tl = self.GetTopLeft()
599 tr = self.GetTopRight()
600 bl = self.GetBottomLeft()
601 br = self.GetBottomRight()
602
603 for win in self._windows:
604 w, h = win.GetEffectiveMinSize()
605 width += w
606 height += h
607
608 if tl and tr:
609 width += self._GetSashSize()
610
611 if bl and br:
612 height += self._GetSashSize()
613
614 return wx.Size(width + 2 * border, height + 2 * border)
615
616 # Recompute layout
617 def _SizeWindows(self) -> None: # noqa: N802
618 """Recalculate the layout based on split positions and split fractions.
619
620 See:
621 :meth:`~FourWaySplitter.SetHSplit` and :meth:`~FourWaySplitter.SetVSplit`
622 for more information about split fractions.
623 """
624 win0 = self.GetTopLeft()
625 win1 = self.GetTopRight()
626 win2 = self.GetBottomLeft()
627 win3 = self.GetBottomRight()
628
629 width, height = self.GetSize()
630 bar_size = self._GetSashSize()
631 border = self._GetBorderSize()
632
633 if self._expanded < 0:
634 total_width = width - bar_size - 2 * border
635 total_height = height - bar_size - 2 * border
636 self._splitx = (self._fhor * total_width) // 10000
637 self._splity = (self._fver * total_height) // 10000
638 rightw = total_width - self._splitx
639 bottomh = total_height - self._splity
640 if win0:
641 win0.SetSize(0, 0, self._splitx, self._splity)
642 win0.Show()
643 if win1:
644 win1.SetSize(self._splitx + bar_size, 0, rightw, self._splity)
645 win1.Show()
646 if win2:
647 win2.SetSize(0, self._splity + bar_size, self._splitx, bottomh)
648 win2.Show()
649 if win3:
650 win3.SetSize(
651 self._splitx + bar_size, self._splity + bar_size, rightw, bottomh
652 )
653 win3.Show()
654
655 elif self._expanded < len(self._windows):
656 for ii, win in enumerate(self._windows):
657 if ii == self._expanded:
658 win.SetSize(0, 0, width - 2 * border, height - 2 * border)
659 win.Show()
660 else:
661 win.Hide()
662
663 # Determine split mode
664 def GetMode(self, pt: wx.Point) -> int: # noqa: N802
665 """Determine the split mode for :class:`FourWaySplitter`.
666
667 Args:
668 pt (wx.Point): the point at which the mouse has been clicked,
669 an instance of :class:`wx.Point`.
670
671 Returns:
672 int: One of the following 3 split modes:
673 ================= ======================================================
674 Split Mode Description
675 ================= ======================================================
676 ``wx.HORIZONTAL`` the user has clicked on the horizontal sash
677 ``wx.VERTICAL`` the user has clicked on the vertical sash
678 ``wx.BOTH`` the user has clicked at the intersection between the 2
679 sashes
680 ================= ======================================================
681 """
682 bar_size = self._GetSashSize()
683 flag = wx.BOTH
684
685 if pt.x < self._splitx - _TOLERANCE:
686 flag &= ~wx.VERTICAL
687
688 if pt.y < self._splity - _TOLERANCE:
689 flag &= ~wx.HORIZONTAL
690
691 if pt.x >= self._splitx + bar_size + _TOLERANCE:
692 flag &= ~wx.VERTICAL
693
694 if pt.y >= self._splity + bar_size + _TOLERANCE:
695 flag &= ~wx.HORIZONTAL
696
697 return flag
698
699 # Move the split intelligently
700 def MoveSplit(self, x: int, y: int) -> None: # noqa: N802
701 """Move the split accordingly to user action.
702
703 Args:
704 x (int): the new splitter `x` coordinate;
705 y (int): the new splitter `y` coordinate.
706 """
707 width, height = self.GetSize()
708 bar_size = self._GetSashSize()
709
710 x = max(x, 0)
711 y = max(y, 0)
712 x = min(x, width - bar_size)
713 y = min(y, height - bar_size)
714
715 self._splitx = x
716 self._splity = y
717
718 # Adjust layout
719 def AdjustLayout(self) -> None: # noqa: N802
720 """Adjust layout of :class:`FourWaySplitter`.
721
722 Mainly used to recalculate the correct values for split fractions.
723 """
724 width, height = self.GetSize()
725 bar_size = self._GetSashSize()
726
727 self._fhor = (
728 (
729 width > bar_size
730 and [
731 (10000 * self._splitx + (width - bar_size - 1))
732 // (width - bar_size)
733 ]
734 )
735 or [0]
736 )[0]
737
738 self._fver = (
739 (
740 height > bar_size
741 and [
742 (10000 * self._splity + (height - bar_size - 1))
743 // (height - bar_size)
744 ]
745 )
746 or [0]
747 )[0]
748
749 self._SizeWindows()
750
751 # Button being pressed
752 def OnLeftDown(self, event: wx.MouseEvent) -> None: # noqa: N802
753 """Handle the ``wx.EVT_LEFT_DOWN`` event for :class:`FourWaySplitter`.
754
755 Args:
756 event (wx.MouseEvent): a :class:`MouseEvent` event to be processed.
757
758 Returns:
759 None
760 """
761 if not self.IsEnabled():
762 return
763
764 pt = event.GetPosition()
765 self.CaptureMouse()
766 self._mode = self.GetMode(pt)
767
768 if self._mode:
769 self._offx = pt.x - self._splitx
770 self._offy = pt.y - self._splity
771 if not self.GetAGWWindowStyleFlag() & wx.SP_LIVE_UPDATE:
772 self.DrawSplitter(wx.ClientDC(self))
773 self.DrawTrackSplitter(self._splitx, self._splity)
774
775 self._flags |= FLAG_PRESSED
776
777 # Button being released
778 def OnLeftUp(self, event: wx.MouseEvent) -> None: # noqa: N802
779 """Handle the ``wx.EVT_LEFT_UP`` event for :class:`FourWaySplitter`.
780
781 Args:
782 event (wx.MouseEvent): a :class:`MouseEvent` event to be processed.
783
784 Returns:
785 None
786 """
787 if not self.IsEnabled():
788 return
789
790 if self.HasCapture():
791 self.ReleaseMouse()
792
793 flgs = self._flags
794
795 self._flags &= ~FLAG_CHANGED
796 self._flags &= ~FLAG_PRESSED
797
798 if flgs & FLAG_PRESSED:
799 if not self.GetAGWWindowStyleFlag() & wx.SP_LIVE_UPDATE:
800 self.DrawTrackSplitter(self._splitx, self._splity)
801 self.DrawSplitter(wx.ClientDC(self))
802 self.AdjustLayout()
803
804 if flgs & FLAG_CHANGED:
805 splitter_event = FourWaySplitterEvent(
806 wx.wxEVT_COMMAND_SPLITTER_SASH_POS_CHANGED, self
807 )
808 splitter_event.SetSashIdx(self._mode)
809 splitter_event.SetSashPosition(wx.Point(self._splitx, self._splity))
810 self.GetEventHandler().ProcessEvent(splitter_event)
811
812 self._mode = NOWHERE
813
814 def OnLeaveWindow(self, event: wx.MouseEvent) -> None: # noqa: N802
815 """Handle the ``wx.EVT_LEAVE_WINDOW`` event for :class:`FourWaySplitter`.
816
817 Args:
818 event (wx.MouseEvent): a :class:`MouseEvent` event to be processed.
819 """
820 self.SetCursor(wx.STANDARD_CURSOR)
821 self._RedrawIfHotSensitive(False)
822
823 def OnEnterWindow(self, event: wx.MouseEvent) -> None: # noqa: N802
824 """Handle the ``wx.EVT_ENTER_WINDOW`` event for :class:`FourWaySplitter`.
825
826 Args:
827 event (wx.MouseEvent): a :class:`MouseEvent` event to be processed.
828 """
829 self._RedrawIfHotSensitive(True)
830
831 def _RedrawIfHotSensitive(self, is_hot: bool) -> None: # noqa: N802
832 """Use internally.
833
834 Redraw the splitter if we are using a hot-sensitive splitter.
835
836 Args:
837 is_hot (bool): ``True`` if the splitter is in a hot state,
838 ``False`` otherwise.
839 """
840 if not self._IsVersionGreaterOrEqual(_RENDER_VER):
841 return
842
843 if wx.RendererNative.Get().GetSplitterParams(self).isHotSensitive:
844 self._isHot = is_hot
845 dc = wx.ClientDC(self)
846 self.DrawSplitter(dc)
847
848 def OnMotion(self, event: wx.MouseEvent) -> None: # noqa: N802
849 """Handle the ``wx.EVT_MOTION`` event for :class:`FourWaySplitter`.
850
851 Args:
852 event (wx.MouseEvent): a :class:`MouseEvent` event to be processed.
853
854 Returns:
855 None
856 """
857 if self.HasFlag(wx.SP_NOSASH):
858 return
859
860 pt = event.GetPosition()
861
862 # Moving split
863 if self._flags & FLAG_PRESSED:
864 oldsplitx = self._splitx
865 oldsplity = self._splity
866
867 if self._mode == wx.BOTH:
868 self.MoveSplit(pt.x - self._offx, pt.y - self._offy)
869
870 elif self._mode == wx.VERTICAL:
871 self.MoveSplit(pt.x - self._offx, self._splity)
872
873 elif self._mode == wx.HORIZONTAL:
874 self.MoveSplit(self._splitx, pt.y - self._offy)
875
876 # Send a changing event
877 if not self.DoSendChangingEvent(wx.Point(self._splitx, self._splity)):
878 self._splitx = oldsplitx
879 self._splity = oldsplity
880 return
881
882 if oldsplitx != self._splitx or oldsplity != self._splity:
883 if not self.GetAGWWindowStyleFlag() & wx.SP_LIVE_UPDATE:
884 self.DrawTrackSplitter(oldsplitx, oldsplity)
885 self.DrawTrackSplitter(self._splitx, self._splity)
886 else:
887 self.AdjustLayout()
888
889 self._flags |= FLAG_CHANGED
890
891 # Change cursor based on position
892 ff = self.GetMode(pt)
893
894 if ff == wx.BOTH:
895 self.SetCursor(self._sashCursorSIZING)
896
897 elif ff == wx.VERTICAL:
898 self.SetCursor(self._sashCursorWE)
899
900 elif ff == wx.HORIZONTAL:
901 self.SetCursor(self._sashCursorNS)
902
903 else:
904 self.SetCursor(wx.STANDARD_CURSOR)
905
906 event.Skip()
907
908 def OnPaint(self, event: wx.PaintEvent) -> None: # noqa: N802
909 """Handle the ``wx.EVT_PAINT`` event for :class:`FourWaySplitter`.
910
911 Args:
912 event (wx.PaintEvent): a :class:`PaintEvent` event to be processed.
913 """
914 dc = wx.PaintDC(self)
915 self.DrawSplitter(dc)
916
917 def OnSize(self, event: wx.SizeEvent) -> None: # noqa: N802
918 """Handle the ``wx.EVT_SIZE`` event for :class:`FourWaySplitter`.
919
920 Args:
921 event (wx.SizeEvent): a :class:`SizeEvent` event to be processed.
922 """
923 parent = wx.GetTopLevelParent(self)
924 if isinstance(parent, wx.TopLevelWindow) and parent.IsIconized():
925 event.Skip()
926 return
927
928 self._SizeWindows()
929
930 def DoSendChangingEvent(self, pt: wx.Point) -> bool: # noqa: N802
931 """Send a ``EVT_SPLITTER_SASH_POS_CHANGING`` event.
932
933 Args:
934 pt (wx.Point): the point at which the splitter is being positioned.
935
936 Returns:
937 bool: ``True`` if the event is allowed, ``False`` otherwise.
938 """
939 # send the event
940 event = FourWaySplitterEvent(wx.wxEVT_COMMAND_SPLITTER_SASH_POS_CHANGING, self)
941 event.SetSashIdx(self._mode)
942 event.SetSashPosition(pt)
943
944 # the event handler vetoed the change or missing event.Skip()
945 # or it might have changed the value
946 return not self.GetEventHandler().ProcessEvent(event) or event.IsAllowed()
947
948 def _GetSashSize(self) -> int: # noqa: N802
949 """Use internally.
950
951 Returns:
952 int: The size of the sash.
953 """
954 if self.HasFlag(wx.SP_NOSASH):
955 return 0
956
957 if self._IsVersionGreaterOrEqual(_RENDER_VER):
958 return wx.RendererNative.Get().GetSplitterParams(self).widthSash
959 return 5
960
961 def _GetBorderSize(self) -> int: # noqa: N802
962 """Use internally.
963
964 Returns:
965 int: The size of the border.
966 """
967 if self._IsVersionGreaterOrEqual(_RENDER_VER):
968 return wx.RendererNative.Get().GetSplitterParams(self).border
969 return 0
970
971 # Draw the horizontal split
972 def DrawSplitter(self, dc: wx.DC) -> None: # noqa: N802
973 """Actually draw the sashes.
974
975 Args:
976 dc (wx.DC): an instance of :class:`wx.DC`.
977
978 Returns:
979 None
980 """
981 back_colour = self.GetBackgroundColour()
982 dc.SetBrush(wx.Brush(back_colour))
983 dc.SetPen(wx.Pen(back_colour))
984 dc.Clear()
985
986 bar_size = None
987 if self._IsVersionGreaterOrEqual(_RENDER_VER):
988 if self.HasFlag(wx.SP_3DBORDER):
989 wx.RendererNative.Get().DrawSplitterBorder(
990 self, dc, self.GetClientRect()
991 )
992 else:
993 bar_size = self._GetSashSize()
994
995 # if we are not supposed to use a sash then we're done.
996 if self.HasFlag(wx.SP_NOSASH):
997 return
998
999 flag = 0
1000 if self._isHot:
1001 flag = wx.CONTROL_CURRENT
1002
1003 width, height = self.GetSize()
1004
1005 if self._mode & wx.VERTICAL:
1006 if self._IsVersionGreaterOrEqual(_RENDER_VER):
1007 wx.RendererNative.Get().DrawSplitterSash(
1008 self, dc, self.GetClientSize(), self._splitx, wx.VERTICAL, flag
1009 )
1010 else:
1011 dc.DrawRectangle(self._splitx, 0, bar_size, height)
1012
1013 if self._mode & wx.HORIZONTAL:
1014 if self._IsVersionGreaterOrEqual(_RENDER_VER):
1015 wx.RendererNative.Get().DrawSplitterSash(
1016 self, dc, self.GetClientSize(), self._splity, wx.HORIZONTAL, flag
1017 )
1018 else:
1019 dc.DrawRectangle(0, self._splity, width, bar_size)
1020
1021 def DrawTrackSplitter(self, x: int, y: int) -> None: # noqa: N802
1022 """Draw a fake sash in case we don't have ``wx.SP_LIVE_UPDATE`` style.
1023
1024 Args:
1025 x (int): the `x` position of the sash;
1026 y (int): the `y` position of the sash.
1027
1028 Note:
1029 This method relies on :class:`ScreenDC` which is currently unavailable on
1030 wxMac.
1031 """
1032 # Draw a line to represent the dragging sash, for when not doing live updates
1033 w, h = self.GetClientSize()
1034 dc = wx.ScreenDC()
1035
1036 dc.SetLogicalFunction(wx.INVERT)
1037 dc.SetPen(self._sashTrackerPen)
1038 dc.SetBrush(wx.TRANSPARENT_BRUSH)
1039
1040 if self._mode == wx.VERTICAL:
1041 x1 = x
1042 y1 = 2
1043 x2 = x
1044 y2 = h - 2
1045 if x1 > w:
1046 x1 = w
1047 x2 = w
1048 elif x1 < 0:
1049 x1 = 0
1050 x2 = 0
1051
1052 x1, y1 = self.ClientToScreen((x1, y1))
1053 x2, y2 = self.ClientToScreen((x2, y2))
1054
1055 dc.DrawLine(x1, y1, x2, y2)
1056 dc.SetLogicalFunction(wx.COPY)
1057
1058 elif self._mode == wx.HORIZONTAL:
1059 x1 = 2
1060 y1 = y
1061 x2 = w - 2
1062 y2 = y
1063 if y1 > h:
1064 y1 = h
1065 y2 = h
1066 elif y1 < 0:
1067 y1 = 0
1068 y2 = 0
1069
1070 x1, y1 = self.ClientToScreen((x1, y1))
1071 x2, y2 = self.ClientToScreen((x2, y2))
1072
1073 dc.DrawLine(x1, y1, x2, y2)
1074 dc.SetLogicalFunction(wx.COPY)
1075
1076 elif self._mode == wx.BOTH:
1077 x1 = 2
1078 x2 = w - 2
1079 y1 = y
1080 y2 = y
1081
1082 x1, y1 = self.ClientToScreen((x1, y1))
1083 x2, y2 = self.ClientToScreen((x2, y2))
1084
1085 dc.DrawLine(x1, y1, x2, y2)
1086
1087 x1 = x
1088 x2 = x
1089 y1 = 2
1090 y2 = h - 2
1091
1092 x1, y1 = self.ClientToScreen((x1, y1))
1093 x2, y2 = self.ClientToScreen((x2, y2))
1094
1095 dc.DrawLine(x1, y1, x2, y2)
1096 dc.SetLogicalFunction(wx.COPY)
1097
1098 # Change horizontal split [fraction*10000]
1099 def SetHSplit(self, s: int) -> None: # noqa: N802
1100 """Change horizontal split fraction.
1101
1102 Args:
1103 s (int): the split fraction,
1104 which is an integer value between 0 and 10000 (inclusive),
1105 indicating how much space to allocate to the leftmost panes.
1106 For example, to split the panes at 35 percent, use::
1107 fourSplitter.SetHSplit(3500)
1108 """
1109 s = max(s, 0)
1110 s = min(s, 10000)
1111 if s != self._fhor:
1112 self._fhor = s
1113 self._SizeWindows()
1114
1115 # Change vertical split [fraction*10000]
1116 def SetVSplit(self, s: int) -> None: # noqa: N802
1117 """Change vertical split fraction.
1118
1119 Args:
1120 s (int): the split fraction,
1121 which is an integer value between 0 and 10000 (inclusive),
1122 indicating how much space to allocate to the topmost panes.
1123 For example, to split the panes at 35 percent,
1124 use::fourSplitter.SetVSplit(3500)
1125 """
1126 s = max(s, 0)
1127 s = min(s, 10000)
1128 if s != self._fver:
1129 self._fver = s
1130 self._SizeWindows()
1131
1132 # Expand one or all of the four panes
1133 def SetExpanded(self, expanded: int) -> None: # noqa: N802
1134 """Expand a window or revert to four.
1135
1136 Args:
1137 expanded (int): an integer >= 0 to expand a window to fill the whole client
1138 size, or an integer < 0 to return to the four-window view.
1139
1140 Raises:
1141 Exception: If the `expanded` index is out of range (>= 4).
1142 """
1143 if expanded >= 4:
1144 raise Exception(f"ERROR: SetExpanded: index out of range: {expanded}")
1145
1146 if self._expanded != expanded:
1147 self._expanded = expanded
1148 self._SizeWindows()
1149
1150
1151 if __name__ == "__main__":
1152 import wx
1153
1154 class MyFrame(wx.Frame):
1155 """A custom wx.Frame that demonstrates the usage of the FourWaySplitter.
1156
1157 It initializes a frame with a FourWaySplitter containing four colored panels.
1158
1159 Args:
1160 parent (None | wx.Window): The parent window for this frame.
1161 """
1162
1163 def __init__(self, parent: None | wx.Window) -> None:
1164 wx.Frame.__init__(self, parent, -1, "FourWaySplitter Demo")
1165
1166 splitter = FourWaySplitter(self, -1, agw_style=wx.SP_LIVE_UPDATE)
1167
1168 # Put in some coloured panels...
1169 for colour in [wx.RED, wx.WHITE, wx.BLUE, wx.GREEN]:
1170 panel = wx.Panel(splitter)
1171 panel.SetBackgroundColour(colour)
1172 splitter.AppendWindow(panel)
1173
1174 # our normal wxApp-derived class, as usual
1175
1176 app = wx.App(False)
1177
1178 frame = MyFrame(None)
1179 app.SetTopWindow(frame)
1180 frame.Show()
1181
1182 app.MainLoop()