fourwaysplitter.py 34.2 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101
# --------------------------------------------------------------------------------- #
# FOURWAYSPLITTER wxPython IMPLEMENTATION
#
# Andrea Gavana, @ 03 Nov 2006
# Latest Revision: 14 Mar 2012, 21.00 GMT
#
#
# TODO List
#
# 1. Any idea?
#
# For All Kind Of Problems, Requests Of Enhancements And Bug Reports, Please
# Write To Me At:
#
# andrea.gavana@maerskoil.com
# andrea.gavana@gmail.com
#
# Or, Obviously, To The wxPython Mailing List!!!
#
#
# End Of Comments
# --------------------------------------------------------------------------------- #

"""
:class:`FourWaySplitter` is a layout manager which manages 4 children like 4 panes in a
window.


Description
===========

The :class:`FourWaySplitter` is a layout manager which manages four children like four
panes in a window. You can use a four-way splitter for example in a CAD program
where you may want to maintain three orthographic views, and one oblique view of
a model.

The :class:`FourWaySplitter` allows interactive repartitioning of the panes by
means of moving the central splitter bars. When the :class:`FourWaySplitter` is itself
resized, each child is proportionally resized, maintaining the same split-percentage.

The main characteristics of :class:`FourWaySplitter` are:

- Handles horizontal, vertical or four way sizing via the sashes;
- Delayed or live update when resizing;
- Possibility to swap windows;
- Setting the vertical and horizontal split fractions;
- Possibility to expand a window by hiding the onther 3.

And a lot more. See the demo for a complete review of the functionalities.


Usage
=====

Usage example::

    import wx
    import wx.lib.agw.fourwaysplitter as fws

    class MyFrame(wx.Frame):

        def __init__(self, parent):
        
            wx.Frame.__init__(self, parent, -1, "FourWaySplitter Demo")

            splitter = fws.FourWaySplitter(self, -1, agwStyle=wx.SP_LIVE_UPDATE)

            # Put in some coloured panels...
            for colour in [wx.RED, wx.WHITE, wx.BLUE, wx.GREEN]:

                panel = wx.Panel(splitter)
                panel.SetBackgroundColour(colour)

                splitter.AppendWindow(panel)

        
    # our normal wxApp-derived class, as usual

    app = wx.App(0)

    frame = MyFrame(None)
    app.SetTopWindow(frame)
    frame.Show()

    app.MainLoop()



Supported Platforms
===================

:class:`FourWaySplitter` has been tested on the following platforms:
  * Windows (Windows XP);
  * Linux Ubuntu (Dapper 6.06)


Window Styles
=============

This class supports the following window styles:

================== =========== ==================================================
Window Styles      Hex Value   Description
================== =========== ==================================================
``SP_NOSASH``             0x10 No sash will be drawn on :class:`FourWaySplitter`.
``SP_LIVE_UPDATE``        0x80 Don't draw XOR line but resize the child windows immediately.
``SP_3DBORDER``          0x200 Draws a 3D effect border.
================== =========== ==================================================


Events Processing
=================

This class processes the following events:

================================== ==================================================
Event Name                         Description
================================== ==================================================
``EVT_SPLITTER_SASH_POS_CHANGED``  The sash position was changed. This event is generated after the user releases the mouse after dragging the splitter. Processes a ``wx.wxEVT_COMMAND_SPLITTER_SASH_POS_CHANGED`` event.
``EVT_SPLITTER_SASH_POS_CHANGING`` The sash position is in the process of being changed. You may prevent this change from happening by calling `Veto` or you may also modify the position of the tracking bar to properly reflect the position that would be set if the drag were to be completed at this point. Processes a ``wx.wxEVT_COMMAND_SPLITTER_SASH_POS_CHANGING`` event.
================================== ==================================================


License And Version
===================

:class:`FourWaySplitter` is distributed under the wxPython license. 

Latest Revision: Andrea Gavana @ 14 Mar 2012, 21.00 GMT

Version 0.4

"""

__docformat__ = "epytext"


import wx

_RENDER_VER = (2,6,1,1)

# Tolerance for mouse shape and sizing
_TOLERANCE = 5

# Modes
NOWHERE = 0
""" No sashes are changing position. """
FLAG_CHANGED = 1
""" Sashes are changing position. """
FLAG_PRESSED = 2
""" Sashes are in a pressed state. """

# FourWaySplitter styles
SP_NOSASH = wx.SP_NOSASH
""" No sash will be drawn on :class:`FourWaySplitter`. """
SP_LIVE_UPDATE = wx.SP_LIVE_UPDATE
""" Don't draw XOR line but resize the child windows immediately. """
SP_3DBORDER = wx.SP_3DBORDER
""" Draws a 3D effect border. """

# FourWaySplitter events
EVT_SPLITTER_SASH_POS_CHANGING = wx.EVT_SPLITTER_SASH_POS_CHANGING
""" The sash position is in the process of being changed. You may prevent this change""" \
""" from happening by calling `Veto` or you may also modify the position of the tracking""" \
""" bar to properly reflect the position that would be set if the drag were to be""" \
""" completed at this point. Processes a ``wx.wxEVT_COMMAND_SPLITTER_SASH_POS_CHANGING`` event."""
EVT_SPLITTER_SASH_POS_CHANGED = wx.EVT_SPLITTER_SASH_POS_CHANGED
""" The sash position was changed. This event is generated after the user releases the""" \
""" mouse after dragging the splitter. Processes a ``wx.wxEVT_COMMAND_SPLITTER_SASH_POS_CHANGED`` event. """

# ---------------------------------------------------------------------------- #
# Class FourWaySplitterEvent
# ---------------------------------------------------------------------------- #

class FourWaySplitterEvent(wx.PyCommandEvent):
    """
    This event class is almost the same as :class:`SplitterEvent` except
    it adds an accessor for the sash index that is being changed.  The
    same event type IDs and event binders are used as with
    :class:`SplitterEvent`.
    """
    
    def __init__(self, evtType=wx.wxEVT_NULL, splitter=None):
        """
        Default class constructor.

        :param `evtType`: the event type;
        :param `splitter`: the associated :class:`FourWaySplitter` window.
        """
        
        wx.PyCommandEvent.__init__(self, evtType)

        if splitter:
            self.SetEventObject(splitter)
            self.SetId(splitter.GetId())

        self.sashIdx = -1
        self.sashPos = -1
        self.isAllowed = True


    def SetSashIdx(self, idx):
        """
        Sets the index of the sash currently involved in the event.

        :param `idx`: an integer between 0 and 3, representing the index of the
         sash involved in the event.
        """
        
        self.sashIdx = idx


    def SetSashPosition(self, pos):
        """
        In the case of ``EVT_SPLITTER_SASH_POS_CHANGED`` events, sets the new sash
        position. In the case of ``EVT_SPLITTER_SASH_POS_CHANGING`` events, sets
        the new tracking bar position so visual feedback during dragging will represent
        that change that will actually take place. Set to -1 from the event handler
        code to prevent repositioning.

        :param `pos`: the new sash position.        

        :note: May only be called while processing ``EVT_SPLITTER_SASH_POS_CHANGING``
         and ``EVT_SPLITTER_SASH_POS_CHANGED`` events.
        """
        
        self.sashPos = pos


    def GetSashIdx(self):
        """ Returns the index of the sash currently involved in the event. """

        return self.sashIdx


    def GetSashPosition(self):
        """
        Returns the new sash position.

        :note: May only be called while processing ``EVT_SPLITTER_SASH_POS_CHANGING``
         and ``EVT_SPLITTER_SASH_POS_CHANGED`` events.
        """
        
        return self.sashPos


    # methods from wx.NotifyEvent
    def Veto(self):
        """
        Prevents the change announced by this event from happening.

        :note: It is in general a good idea to notify the user about the reasons
         for vetoing the change because otherwise the applications behaviour (which
         just refuses to do what the user wants) might be quite surprising.
        """

        self.isAllowed = False


    def Allow(self):
        """
        This is the opposite of :meth:`~FourWaySplitterEvent.Veto`: it explicitly allows the event to be processed.
        For most events it is not necessary to call this method as the events are
        allowed anyhow but some are forbidden by default (this will be mentioned
        in the corresponding event description).
        """

        self.isAllowed = True


    def IsAllowed(self):
        """
        Returns ``True`` if the change is allowed (:meth:`~FourWaySplitterEvent.Veto` hasn't been called) or
        ``False`` otherwise (if it was).
        """

        return self.isAllowed
        

# ---------------------------------------------------------------------------- #
# Class FourWaySplitter
# ---------------------------------------------------------------------------- #

class FourWaySplitter(wx.PyPanel):
    """
    This class is very similar to :class:`SplitterWindow` except that it
    allows for four windows and two sashes.  Many of the same styles,
    constants, and methods behave the same as in :class:`SplitterWindow`.
    However, in addition of the ability to drag the vertical and the
    horizontal sash, by dragging at the intersection between the two
    sashes, it is possible to resize the four windows at the same time.

    :note: These things are not yet supported:
    
     * Minimum pane size (minimum of what? Width? Height?);
     * Using negative sash positions to indicate a position offset from the end;
     * User controlled unsplitting with double clicks on the sash (but supported via the
       :meth:`FourWaySplitter.SetExpanded() <FourWaySplitter.SetExpanded>` method);
     * Sash gravity.

     
    """

    def __init__(self, parent, id=wx.ID_ANY, pos=wx.DefaultPosition,
                 size=wx.DefaultSize, style=0, agwStyle=0, name="FourWaySplitter"):
        """
        Default class constructor.
        
        :param `parent`: parent window. Must not be ``None``;
        :param `id`: window identifier. A value of -1 indicates a default value;
        :param `pos`: the control position. A value of (-1, -1) indicates a default position,
         chosen by either the windowing system or wxPython, depending on platform;
        :param `size`: the control size. A value of (-1, -1) indicates a default size,
         chosen by either the windowing system or wxPython, depending on platform;
        :param `style`: the underlying :class:`PyPanel` window style;
        :param `agwStyle`: the AGW-specific window style. It can be a combination of the
         following bits:

         ================== =========== ==================================================
         Window Styles      Hex Value   Description
         ================== =========== ==================================================
         ``SP_NOSASH``             0x10 No sash will be drawn on :class:`FourWaySplitter`.
         ``SP_LIVE_UPDATE``        0x80 Don't draw XOR line but resize the child windows immediately.
         ``SP_3DBORDER``          0x200 Draws a 3D effect border.
         ================== =========== ==================================================

        :param `name`: the window name.
        """
        
        # always turn on tab traversal
        style |= wx.TAB_TRAVERSAL

        # and turn off any border styles
        style &= ~wx.BORDER_MASK
        style |= wx.BORDER_NONE

        self._agwStyle = agwStyle        

        # initialize the base class
        wx.PyPanel.__init__(self, parent, id, pos, size, style, name)
        self.SetBackgroundStyle(wx.BG_STYLE_CUSTOM)

        self._windows = []
        
        self._splitx = 0
        self._splity = 0
        self._expanded = -1
        self._fhor = 5000
        self._fver = 5000
        self._offx = 0
        self._offy = 0
        self._mode = NOWHERE
        self._flags = 0
        self._isHot = False

        self._sashTrackerPen = wx.Pen(wx.BLACK, 2, wx.SOLID)
        
        self._sashCursorWE = wx.StockCursor(wx.CURSOR_SIZEWE)
        self._sashCursorNS = wx.StockCursor(wx.CURSOR_SIZENS)
        self._sashCursorSIZING = wx.StockCursor(wx.CURSOR_SIZING)
        
        self.Bind(wx.EVT_PAINT, self.OnPaint)
        self.Bind(wx.EVT_MOTION, self.OnMotion)
        self.Bind(wx.EVT_SIZE, self.OnSize)
        self.Bind(wx.EVT_LEFT_DOWN, self.OnLeftDown)
        self.Bind(wx.EVT_LEFT_UP, self.OnLeftUp)
        self.Bind(wx.EVT_LEAVE_WINDOW, self.OnLeaveWindow)
        self.Bind(wx.EVT_ENTER_WINDOW, self.OnEnterWindow)


    def SetAGWWindowStyleFlag(self, agwStyle):
        """
        Sets the :class:`FourWaySplitter` window style flags.

        :param `agwStyle`: the AGW-specific window style. This can be a combination of the
         following bits:

         ================== =========== ==================================================
         Window Styles      Hex Value   Description
         ================== =========== ==================================================
         ``SP_NOSASH``             0x10 No sash will be drawn on :class:`FourWaySplitter`.
         ``SP_LIVE_UPDATE``        0x80 Don't draw XOR line but resize the child windows immediately.
         ``SP_3DBORDER``          0x200 Draws a 3D effect border.
         ================== =========== ==================================================         
        """

        self._agwStyle = agwStyle
        self.Refresh()
        

    def GetAGWWindowStyleFlag(self):
        """
        Returns the :class:`FourWaySplitter` window style.

        :see: :meth:`~FourWaySplitter.SetAGWWindowStyleFlag` for a list of possible window styles.        
        """

        return self._agwStyle


    def AppendWindow(self, window):
        """
        Add a new window to the splitter at the right side or bottom
        of the window stack.

        :param `window`: an instance of :class:`Window`.
        """
        
        self.InsertWindow(len(self._windows), window)


    def InsertWindow(self, idx, window, sashPos=-1):
        """
        Insert a new window into the splitter at the position given in `idx`.

        :param `idx`: the index at which the window will be inserted;
        :param `window`: an instance of :class:`Window`;
        :param `sashPos`: the sash position after the window insertion.
        """
        
        assert window not in self._windows, "A window can only be in the splitter once!"
        
        self._windows.insert(idx, window)
        
        self._SizeWindows()


    def DetachWindow(self, window):
        """
        Removes the window from the stack of windows managed by the splitter. The
        window will still exist so you should `Hide` or `Destroy` it as needed.

        :param `window`: an instance of :class:`Window`.        
        """
        
        assert window in self._windows, "Unknown window!"
        
        idx = self._windows.index(window)
        del self._windows[idx]

        self._SizeWindows()


    def ReplaceWindow(self, oldWindow, newWindow):
        """
        Replaces `oldWindow` (which is currently being managed by the
        splitter) with `newWindow`.  The `oldWindow` window will still
        exist so you should `Hide` or `Destroy` it as needed.

        :param `oldWindow`: an instance of :class:`Window`;
        :param `newWindow`: another instance of :class:`Window`.
        """

        assert oldWindow in self._windows, "Unknown window!"
        
        idx = self._windows.index(oldWindow)
        self._windows[idx] = newWindow
        
        self._SizeWindows()


    def ExchangeWindows(self, window1, window2):
        """
        Trade the positions in the splitter of the two windows.

        :param `window1`: an instance of :class:`Window`;
        :param `window2`: another instance of :class:`Window`.        
        """
        
        assert window1 in self._windows, "Unknown window!"
        assert window2 in self._windows, "Unknown window!"
        
        idx1 = self._windows.index(window1)
        idx2 = self._windows.index(window2)
        self._windows[idx1] = window2
        self._windows[idx2] = window1

        if "__WXMSW__" in wx.Platform:
            self.Freeze()

        self._SizeWindows()

        if "__WXMSW__" in wx.Platform:
            self.Thaw()


    def GetWindow(self, idx):
        """
        Returns the window at the index `idx`.

        :param `idx`: the index at which the window is located.
        """

        if len(self._windows) > idx:
            return self._windows[idx]
        
        return None

    # Get top left child
    def GetTopLeft(self):
        """ Returns the top left window (window index: 0). """

        return self.GetWindow(0)
    

    # Get top right child
    def GetTopRight(self):
        """ Returns the top right window (window index: 1). """

        return self.GetWindow(1)
  

    # Get bottom left child
    def GetBottomLeft(self):
        """ Returns the bottom left window (window index: 2). """

        return self.GetWindow(2)


    # Get bottom right child
    def GetBottomRight(self):
        """ Returns the bottom right window (window index: 3). """

        return self.GetWindow(3)


    def DoGetBestSize(self):
        """
        Gets the size which best suits the window: for a control, it would be the
        minimal size which doesn't truncate the control, for a panel - the same size
        as it would have after a call to `Fit()`.

        :note: Overridden from :class:`PyPanel`.        
        """

        if not self._windows:
            # something is better than nothing...
            return wx.Size(10, 10)
        
        width = height = 0
        border = self._GetBorderSize()
        
        tl = self.GetTopLeft()
        tr = self.GetTopRight()
        bl = self.GetBottomLeft()
        br = self.GetBottomRight()
    
        for win in self._windows:
            w, h = win.GetEffectiveMinSize()
            width += w
            height += h
            
        if tl and tr:
          width += self._GetSashSize()

        if bl and br:
          height += self._GetSashSize()
          
        return wx.Size(width+2*border, height+2*border)
  

    # Recompute layout
    def _SizeWindows(self):
        """
        Recalculate the layout based on split positions and split fractions.

        :see: :meth:`~FourWaySplitter.SetHSplit` and :meth:`~FourWaySplitter.SetVSplit` for more information about split fractions.
        """
            
        win0 = self.GetTopLeft()
        win1 = self.GetTopRight()
        win2 = self.GetBottomLeft()
        win3 = self.GetBottomRight()

        width, height = self.GetSize()
        barSize = self._GetSashSize()
        border = self._GetBorderSize()
        
        if self._expanded < 0:
            totw = width - barSize - 2*border
            toth = height - barSize - 2*border
            self._splitx = (self._fhor*totw)/10000
            self._splity = (self._fver*toth)/10000
            rightw = totw - self._splitx
            bottomh = toth - self._splity
            if win0:
                win0.SetDimensions(0, 0, self._splitx, self._splity)
                win0.Show() 
            if win1:
                win1.SetDimensions(self._splitx + barSize, 0, rightw, self._splity)
                win1.Show() 
            if win2:
                win2.SetDimensions(0, self._splity + barSize, self._splitx, bottomh)
                win2.Show() 
            if win3:
                win3.SetDimensions(self._splitx + barSize, self._splity + barSize, rightw, bottomh)
                win3.Show() 

        else:

            if self._expanded < len(self._windows):
                for ii, win in enumerate(self._windows):
                    if ii == self._expanded:
                        win.SetDimensions(0, 0, width-2*border, height-2*border)
                        win.Show()
                    else:
                        win.Hide()

        
    # Determine split mode
    def GetMode(self, pt):
        """
        Determines the split mode for :class:`FourWaySplitter`.

        :param `pt`: the point at which the mouse has been clicked, an instance of
         :class:`Point`.

        :return: One of the following 3 split modes:

         ================= ==============================
         Split Mode        Description
         ================= ==============================
         ``wx.HORIZONTAL`` the user has clicked on the horizontal sash
         ``wx.VERTICAL``   The user has clicked on the vertical sash
         ``wx.BOTH``       The user has clicked at the intersection between the 2 sashes
         ================= ==============================

        """

        barSize = self._GetSashSize()        
        flag = wx.BOTH
        
        if pt.x < self._splitx - _TOLERANCE:
            flag &= ~wx.VERTICAL

        if pt.y < self._splity - _TOLERANCE:
            flag &= ~wx.HORIZONTAL

        if pt.x >= self._splitx + barSize + _TOLERANCE:
            flag &= ~wx.VERTICAL
            
        if pt.y >= self._splity + barSize + _TOLERANCE:
            flag &= ~wx.HORIZONTAL
            
        return flag
  

    # Move the split intelligently
    def MoveSplit(self, x, y):
        """
        Moves the split accordingly to user action.

        :param `x`: the new splitter `x` coordinate;
        :param `y`: the new splitter `y` coordinate.
        """

        width, height = self.GetSize()
        barSize = self._GetSashSize()
        
        if x < 0: x = 0
        if y < 0: y = 0
        if x > width - barSize: x = width - barSize
        if y > height - barSize: y = height - barSize
        
        self._splitx = x
        self._splity = y


    # Adjust layout
    def AdjustLayout(self):
        """
        Adjust layout of :class:`FourWaySplitter`. Mainly used to recalculate the
        correct values for split fractions.
        """

        width, height = self.GetSize()
        barSize = self._GetSashSize()
        border = self._GetBorderSize()
        
        self._fhor = (width > barSize and \
                      [(10000*self._splitx+(width-barSize-1))/(width-barSize)] \
                      or [0])[0]
        
        self._fver = (height > barSize and \
                      [(10000*self._splity+(height-barSize-1))/(height-barSize)] \
                      or [0])[0]

        self._SizeWindows()
            

    # Button being pressed
    def OnLeftDown(self, event):
        """
        Handles the ``wx.EVT_LEFT_DOWN`` event for :class:`FourWaySplitter`.

        :param `event`: a :class:`MouseEvent` event to be processed.
        """

        if not self.IsEnabled():
            return
        
        pt = event.GetPosition()
        self.CaptureMouse()
        self._mode = self.GetMode(pt)

        if self._mode:
            self._offx = pt.x - self._splitx
            self._offy = pt.y - self._splity
            if not self.GetAGWWindowStyleFlag() & wx.SP_LIVE_UPDATE:
                self.DrawSplitter(wx.ClientDC(self))
                self.DrawTrackSplitter(self._splitx, self._splity)

            self._flags |= FLAG_PRESSED
            

    # Button being released
    def OnLeftUp(self, event):
        """
        Handles the ``wx.EVT_LEFT_UP`` event for :class:`FourWaySplitter`.

        :param `event`: a :class:`MouseEvent` event to be processed.
        """
        
        if not self.IsEnabled():
            return

        if self.HasCapture():
            self.ReleaseMouse()

        flgs = self._flags
        
        self._flags &= ~FLAG_CHANGED
        self._flags &= ~FLAG_PRESSED
        
        if flgs & FLAG_PRESSED:
            
            if not self.GetAGWWindowStyleFlag() & wx.SP_LIVE_UPDATE:
                self.DrawTrackSplitter(self._splitx, self._splity)
                self.DrawSplitter(wx.ClientDC(self))
                self.AdjustLayout()
                
            if flgs & FLAG_CHANGED:
                event = FourWaySplitterEvent(wx.wxEVT_COMMAND_SPLITTER_SASH_POS_CHANGED, self)
                event.SetSashIdx(self._mode)
                event.SetSashPosition(wx.Point(self._splitx, self._splity))
                self.GetEventHandler().ProcessEvent(event)                

        self._mode = NOWHERE
        

    def OnLeaveWindow(self, event):
        """
        Handles the ``wx.EVT_LEAVE_WINDOW`` event for :class:`FourWaySplitter`.

        :param `event`: a :class:`MouseEvent` event to be processed.
        """

        self.SetCursor(wx.STANDARD_CURSOR)
        self._RedrawIfHotSensitive(False)


    def OnEnterWindow(self, event):
        """
        Handles the ``wx.EVT_ENTER_WINDOW`` event for :class:`FourWaySplitter`.

        :param `event`: a :class:`MouseEvent` event to be processed.
        """
        
        self._RedrawIfHotSensitive(True)


    def _RedrawIfHotSensitive(self, isHot):
        """
        Used internally. Redraw the splitter if we are using a hot-sensitive splitter.

        :param `isHot`: ``True`` if the splitter is in a hot state, ``False`` otherwise.
        """

        if not wx.VERSION >= _RENDER_VER:
            return

        if wx.RendererNative.Get().GetSplitterParams(self).isHotSensitive:
            self._isHot = isHot
            dc = wx.ClientDC(self)
            self.DrawSplitter(dc)

        
    def OnMotion(self, event):
        """
        Handles the ``wx.EVT_MOTION`` event for :class:`FourWaySplitter`.

        :param `event`: a :class:`MouseEvent` event to be processed.
        """

        if self.HasFlag(wx.SP_NOSASH):
            return 

        pt = event.GetPosition()

        # Moving split
        if self._flags & FLAG_PRESSED:
                    
            oldsplitx = self._splitx
            oldsplity = self._splity
            
            if self._mode == wx.BOTH:
                self.MoveSplit(pt.x - self._offx, pt.y - self._offy)
              
            elif self._mode == wx.VERTICAL:
                self.MoveSplit(pt.x - self._offx, self._splity)
              
            elif self._mode == wx.HORIZONTAL:
                self.MoveSplit(self._splitx, pt.y - self._offy)

            # Send a changing event
            if not self.DoSendChangingEvent(wx.Point(self._splitx, self._splity)):
                self._splitx = oldsplitx
                self._splity = oldsplity
                return              

            if oldsplitx != self._splitx or oldsplity != self._splity:
                if not self.GetAGWWindowStyleFlag() & wx.SP_LIVE_UPDATE:
                    self.DrawTrackSplitter(oldsplitx, oldsplity)
                    self.DrawTrackSplitter(self._splitx, self._splity)
                else:
                    self.AdjustLayout()

                self._flags |= FLAG_CHANGED
        
        # Change cursor based on position
        ff = self.GetMode(pt)
        
        if ff == wx.BOTH:
            self.SetCursor(self._sashCursorSIZING)

        elif ff == wx.VERTICAL:
            self.SetCursor(self._sashCursorWE)

        elif ff == wx.HORIZONTAL:
            self.SetCursor(self._sashCursorNS)

        else:
            self.SetCursor(wx.STANDARD_CURSOR)

        event.Skip()


    def OnPaint(self, event):
        """
        Handles the ``wx.EVT_PAINT`` event for :class:`FourWaySplitter`.

        :param `event`: a :class:`PaintEvent` event to be processed.
        """

        dc = wx.PaintDC(self)
        self.DrawSplitter(dc)


    def OnSize(self, event):
        """
        Handles the ``wx.EVT_SIZE`` event for :class:`FourWaySplitter`.

        :param `event`: a :class:`SizeEvent` event to be processed.
        """

        parent = wx.GetTopLevelParent(self)
        if parent.IsIconized():
            event.Skip()
            return
    
        self._SizeWindows()


    def DoSendChangingEvent(self, pt):
        """
        Sends a ``EVT_SPLITTER_SASH_POS_CHANGING`` event.

        :param `pt`: the point at which the splitter is being positioned.
        """

        # send the event
        event = FourWaySplitterEvent(wx.wxEVT_COMMAND_SPLITTER_SASH_POS_CHANGING, self)
        event.SetSashIdx(self._mode)
        event.SetSashPosition(pt)
        
        if self.GetEventHandler().ProcessEvent(event) and not event.IsAllowed():
            # the event handler vetoed the change or missing event.Skip()
            return False
        else:
            # or it might have changed the value
            return True


    def _GetSashSize(self):
        """ Used internally. """

        if self.HasFlag(wx.SP_NOSASH):
            return 0

        if wx.VERSION >= _RENDER_VER:
            return wx.RendererNative.Get().GetSplitterParams(self).widthSash
        else:
            return 5


    def _GetBorderSize(self):
        """ Used internally. """

        if wx.VERSION >= _RENDER_VER:
            return wx.RendererNative.Get().GetSplitterParams(self).border
        else:
            return 0

        
    # Draw the horizontal split
    def DrawSplitter(self, dc):
        """
        Actually draws the sashes.

        :param `dc`: an instance of :class:`DC`.
        """

        backColour = self.GetBackgroundColour()        
        dc.SetBrush(wx.Brush(backColour, wx.SOLID))
        dc.SetPen(wx.Pen(backColour))
        dc.Clear()

        if wx.VERSION >= _RENDER_VER:
            if self.HasFlag(wx.SP_3DBORDER):
                wx.RendererNative.Get().DrawSplitterBorder(
                    self, dc, self.GetClientRect())
        else:
            barSize = self._GetSashSize()

        # if we are not supposed to use a sash then we're done.
        if self.HasFlag(wx.SP_NOSASH):
            return

        flag = 0
        if self._isHot:
            flag = wx.CONTROL_CURRENT
        
        width, height = self.GetSize()

        if self._mode & wx.VERTICAL:
            if wx.VERSION >= _RENDER_VER:
                wx.RendererNative.Get().DrawSplitterSash(self, dc,
                                                         self.GetClientSize(),
                                                         self._splitx, wx.VERTICAL, flag)
            else:
                dc.DrawRectangle(self._splitx, 0, barSize, height)

        if self._mode & wx.HORIZONTAL:
            if wx.VERSION >= _RENDER_VER:
                wx.RendererNative.Get().DrawSplitterSash(self, dc,
                                                         self.GetClientSize(),
                                                         self._splity, wx.VERTICAL, flag)
            else:
                dc.DrawRectangle(0, self._splity, width, barSize)


    def DrawTrackSplitter(self, x, y):
        """
        Draws a fake sash in case we don't have ``wx.SP_LIVE_UPDATE`` style.

        :param `x`: the `x` position of the sash;
        :param `y`: the `y` position of the sash.

        :note: This method relies on :class:`ScreenDC` which is currently unavailable on wxMac.        
        """

        # Draw a line to represent the dragging sash, for when not
        # doing live updates            
        w, h = self.GetClientSize()
        dc = wx.ScreenDC()
        
        dc.SetLogicalFunction(wx.INVERT)
        dc.SetPen(self._sashTrackerPen)
        dc.SetBrush(wx.TRANSPARENT_BRUSH)
        
        if self._mode == wx.VERTICAL:
            x1 = x
            y1 = 2
            x2 = x
            y2 = h-2
            if x1 > w:
                x1 = w
                x2 = w
            elif x1 < 0:
                x1 = 0
                x2 = 0

            x1, y1 = self.ClientToScreenXY(x1, y1)
            x2, y2 = self.ClientToScreenXY(x2, y2)
         
            dc.DrawLine(x1, y1, x2, y2)
            dc.SetLogicalFunction(wx.COPY)
                                
        elif self._mode == wx.HORIZONTAL:

            x1 = 2
            y1 = y
            x2 = w-2
            y2 = y
            if y1 > h:
                y1 = h
                y2 = h
            elif y1 < 0:
                y1 = 0
                y2 = 0

            x1, y1 = self.ClientToScreenXY(x1, y1)
            x2, y2 = self.ClientToScreenXY(x2, y2)

            dc.DrawLine(x1, y1, x2, y2)
            dc.SetLogicalFunction(wx.COPY)
            
        elif self._mode == wx.BOTH:

            x1 = 2
            x2 = w-2
            y1 = y
            y2 = y

            x1, y1 = self.ClientToScreenXY(x1, y1)
            x2, y2 = self.ClientToScreenXY(x2, y2)

            dc.DrawLine(x1, y1, x2, y2)
                        
            x1 = x
            x2 = x
            y1 = 2
            y2 = h-2

            x1, y1 = self.ClientToScreenXY(x1, y1)
            x2, y2 = self.ClientToScreenXY(x2, y2)

            dc.DrawLine(x1, y1, x2, y2)
            dc.SetLogicalFunction(wx.COPY)            

        
    # Change horizontal split [fraction*10000]
    def SetHSplit(self, s):
        """
        Change horizontal split fraction.

        :param `s`: the split fraction, which is an integer value between 0 and
         10000 (inclusive), indicating how much space to allocate to the leftmost
         panes. For example, to split the panes at 35 percent, use::

            fourSplitter.SetHSplit(3500)
          
        """

        if s < 0: s = 0
        if s > 10000: s  =10000
        if s != self._fhor:
            self._fhor = s
            self._SizeWindows()

    
    # Change vertical split [fraction*10000]
    def SetVSplit(self, s):
        """
        Change vertical split fraction.

        :param `s`: the split fraction, which is an integer value between 0 and
         10000 (inclusive), indicating how much space to allocate to the topmost
         panes. For example, to split the panes at 35 percent, use::

            fourSplitter.SetVSplit(3500)
          
        """

        if s < 0: s = 0
        if s > 10000: s  =10000
        if s != self._fver:
            self._fver = s
            self._SizeWindows()


    # Expand one or all of the four panes
    def SetExpanded(self, expanded):
        """
        This method is used to expand one of the four window to fill the
        whole client size (when `expanded` >= 0) or to return to the four-window
        view (when `expanded` < 0).

        :param `expanded`: an integer >= 0 to expand a window to fill the whole
         client size, or an integer < 0 to return to the four-window view.
        """
        
        if expanded >= 4:
            raise Exception("ERROR: SetExpanded: index out of range: %d"%expanded)

        if self._expanded != expanded:
            self._expanded = expanded
            self._SizeWindows()