aquabutton.py 30.8 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
# --------------------------------------------------------------------------------- #
# AQUABUTTON wxPython IMPLEMENTATION
#
# Andrea Gavana, @ 07 October 2008
# Latest Revision: 03 Dec 2012, 21.00 GMT
#
#
# TODO List
#
# 1) Anything to do?
#
#
# For all kind of problems, requests of enhancements and bug reports, please
# write to me at:
#
# andrea.gavana@gmail.com
# andrea.gavana@maerskoil.com
#
# Or, obviously, to the wxPython mailing list!!!
#
#
# End Of Comments
# --------------------------------------------------------------------------------- #

"""
:class:`AquaButton` is another custom-drawn button class which *approximatively* mimics
the behaviour of Aqua buttons on the Mac.


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

:class:`AquaButton` is another custom-drawn button class which *approximatively* mimics
the behaviour of Aqua buttons on the Mac. At the moment this class supports:

* Bubble and shadow effects;
* Customizable background, foreground and hover colours;
* Rounded-corners buttons;
* Text-only or image+text buttons;
* Pulse effect on gaining focus.

And a lot more. Check the demo for an almost complete review of the functionalities.


Usage
=====

Sample usage::

    import wx
    import wx.lib.agw.aquabutton as AB

    app = wx.App(0)

    frame = wx.Frame(None, -1, "AquaButton Test")
    
    mainPanel = wx.Panel(frame)
    mainPanel.SetBackgroundColour(wx.WHITE)
    
    # Initialize AquaButton 1 (with image)
    bitmap = wx.Bitmap("my_button_bitmap.png", wx.BITMAP_TYPE_PNG)
    btn1 = AB.AquaButton(mainPanel, -1, bitmap, "AquaButton")
    
    # Initialize AquaButton 2 (no image)
    btn2 = AB.AquaButton(mainPanel, -1, None, "Hello World!")

    frame.Show()
    
    app.MainLoop()


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

AquaButton has been tested on the following platforms:
  * Windows (Windows XP);
  * Linux Ubuntu (10.10).


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

`No particular window styles are available for this class.`


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

This class processes the following events:

================= ==================================================
Event Name        Description
================= ==================================================
``wx.EVT_BUTTON`` Process a `wxEVT_COMMAND_BUTTON_CLICKED` event, when the button is clicked.
================= ==================================================


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

:class:`AquaButton` control is distributed under the wxPython license.

Latest Revision: Andrea Gavana @ 03 Dec 2012, 21.00 GMT

Version 0.4

"""

import wx

# Constants for the hovering and clicking effects
HOVER = 1
""" Indicates that the mouse is hovering over :class:`AquaButton` """
CLICK = 2
""" Indicates that :class:`AquaButton` has been clicked """


class AquaButtonEvent(wx.PyCommandEvent):
    """ Event sent from the :class:`AquaButton` buttons when the button is activated. """

    def __init__(self, eventType, eventId):
        """
        Default class constructor.

        :param integer `eventType`: the event type;
        :param integer `eventId`: the event identifier.
        """

        wx.PyCommandEvent.__init__(self, eventType, eventId)
        self.isDown = False
        self.theButton = None


    def SetButtonObj(self, btn):
        """
        Sets the event object for the event.

        :param `btn`: the button object, an instance of :class:`AquaButton`.
        """

        self.theButton = btn


    def GetButtonObj(self):
        """
        Returns the object associated with this event.

        :return: An instance of :class:`AquaButton`.
        """

        return self.theButton


class AquaButton(wx.PyControl):
    """ This is the main class implementation of :class:`AquaButton`. """

    def __init__(self, parent, id=wx.ID_ANY, bitmap=None, label="", pos=wx.DefaultPosition,
                 size=wx.DefaultSize, style=wx.NO_BORDER, validator=wx.DefaultValidator,
                 name="aquabutton"):
        """
        Default class constructor.

        :param Window `parent`: parent window. Must not be ``None``;
        :param integer `id`: window identifier. A value of -1 indicates a default value;
        :param Bitmap `bitmap`: the button bitmap (if any);
        :param string `label`: the button text label;
        :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;
        :type `pos`: tuple or :class:`Point`
        :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;
        :type `size`: tuple or :class:`Size`
        :param integer `style`: the button style (unused);
        :param Validator `validator`: the validator associated to the button;
        :param string `name`: the button name.
        """

        wx.PyControl.__init__(self, parent, id, pos, size, style, validator, name)

        self.SetBackgroundStyle(wx.BG_STYLE_CUSTOM)

        self.Bind(wx.EVT_PAINT, self.OnPaint)
        self.Bind(wx.EVT_ERASE_BACKGROUND, lambda event: None)
        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.OnMouseLeave)
        self.Bind(wx.EVT_ENTER_WINDOW, self.OnMouseEnter)
        self.Bind(wx.EVT_SET_FOCUS, self.OnGainFocus)
        self.Bind(wx.EVT_KILL_FOCUS, self.OnLoseFocus)
        self.Bind(wx.EVT_KEY_DOWN, self.OnKeyDown)
        self.Bind(wx.EVT_KEY_UP, self.OnKeyUp)
        self.Bind(wx.EVT_TIMER, self.OnPulseTimer)

        if "__WXMSW__" in wx.PlatformInfo:
            self.Bind(wx.EVT_LEFT_DCLICK, self.OnLeftDown)

        self._mouseAction = None
        self.SetBitmapLabel(bitmap)
        self._hasFocus = False
        self._saveBitmap = True
        self._storedBitmap = wx.NullBitmap
        self._pulseOnFocus = False
        self._gammaFactor = 1.0
        self._gammaIncrement = 0.1

        self._timer = wx.Timer(self, wx.ID_ANY)

        self.SetLabel(label)
        self.InheritAttributes()
        self.SetInitialSize(size)

        # The following defaults are better suited to draw the text outline
        if "__WXMAC__" in wx.PlatformInfo:
            self._backColour = wx.Colour(147, 202, 255)
            self._hoverColour = self.LightColour(self._backColour, 30)
            self._disableColour = self.LightColour(self._backColour, 70)
            self._textColour = wx.BLACK
            self._shadowColour = wx.NamedColour("grey")
            self._rectColour = self.GetParent().GetBackgroundColour()
        else:
            self._backColour = wx.SystemSettings.GetColour(wx.SYS_COLOUR_ACTIVECAPTION)
            self._hoverColour = self.LightColour(self._backColour, 30)
            self._disableColour = self.LightColour(self._backColour, 70)
            self._textColour = wx.WHITE
            self._shadowColour = wx.NamedColour("grey")
            self._rectColour = self.GetParent().GetBackgroundColour()


    def SetBitmapLabel(self, bitmap):
        """
        Sets the bitmap label for the button.

        :param `bitmap`: the bitmap label to set, an instance of :class:`Bitmap`.
        """
        
        self._bitmap = bitmap
        self.Refresh()


    def LightColour(self, colour, percent):
        """
        Return light contrast of `colour`. The colour returned is from the scale of
        `colour` ==> white.

        :param `colour`: the input colour to be brightened, a valid instance of :class:`Colour`;
        :param integer `percent`: determines how light the colour will be. `percent` = ``100``
         returns white, `percent` = ``0`` returns `colour`.

        :return: A light contrast of the input `colour`, an instance of :class:`Colour`.         
        """

        end_colour = wx.WHITE
        rd = end_colour.Red() - colour.Red()
        gd = end_colour.Green() - colour.Green()
        bd = end_colour.Blue() - colour.Blue()
        high = 100

        # We take the percent way of the colour from colour ==> white
        i = percent
        r = colour.Red() + ((i*rd*100)/high)/100
        g = colour.Green() + ((i*gd*100)/high)/100
        b = colour.Blue() + ((i*bd*100)/high)/100

        return wx.Colour(r, g, b)


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

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

        dc = wx.BufferedPaintDC(self)
        gc = wx.GraphicsContext.Create(dc)

        xpos, ypos, width, height = self.GetClientRect()

        dc.SetBackground(wx.Brush(self._rectColour))
        dc.Clear()
        gc.SetBrush(wx.WHITE_BRUSH)

        shadowOffset = 5
        btnOffset = 0
        clr = self._backColour

        if self._mouseAction == CLICK:
            shadowOffset = 3
            clr = self._hoverColour
            btnOffset = 2

        elif self._mouseAction == HOVER:
            clr = self._hoverColour
            
        elif not self.IsEnabled():
            clr = self._disableColour

        rc1 = wx.Rect(btnOffset, btnOffset, width-8-btnOffset, height-8-btnOffset)
        path1 = self.GetPath(gc, rc1, 10)
        br1 = gc.CreateLinearGradientBrush(0, 0, 0, rc1.height+6, clr, wx.WHITE)

        # Create shadow
        rc2 = wx.Rect(*rc1)
        rc2.Offset((shadowOffset, shadowOffset))
        path2 = self.GetPath(gc, rc2, 10)
        br2 = gc.CreateRadialGradientBrush(rc2.x, rc2.y,
                                           rc2.x+rc2.width, rc2.y+rc2.height,
                                           rc2.width, self._shadowColour, wx.WHITE)

        # Create top water colour to give "aqua" effect
        rc3 = wx.Rect(*rc1)
        rc3.Inflate(-5, -5)
        rc3.height = 15
        path3 = self.GetPath(gc, rc3, 10)

        br3 = gc.CreateLinearGradientBrush(rc3.x, rc3.y, rc3.x, rc3.y+rc3.height,
                                           wx.Colour(255, 255, 255, 255), wx.Colour(255, 255, 255, 0))

        # draw shapes
        gc.SetBrush(br2)
        gc.FillPath(path2)  #draw shadow
        gc.SetBrush(br1)
        gc.FillPath(path1) #draw main
        gc.SetBrush(br3)
        gc.FillPath(path3) #draw top bubble

        font = gc.CreateFont(self.GetFont(), self._textColour)

        gc.SetFont(font)
        label = self.GetLabel()
        tw, th = gc.GetTextExtent(label)

        if self._bitmap:
            bw, bh = self._bitmap.GetWidth(), self._bitmap.GetHeight()
        else:
            bw = bh = 0

        pos_x = (width-bw-tw)/2+btnOffset-shadowOffset      # adjust for bitmap and text to centre
        if self._bitmap:
            pos_y =  (height-bh-shadowOffset)/2+btnOffset
            gc.DrawBitmap(self._bitmap, pos_x, pos_y, bw, bh) # draw bitmap if available
            pos_x = pos_x + 2   # extra spacing from bitmap

        # Create a Path to draw the text
        gc.DrawText(label, pos_x + bw + btnOffset, (height-th-shadowOffset)/2+btnOffset)      # draw the text

        if self._saveBitmap:
            # Save the bitmap using wx.MemoryDC for later use
            self._saveBitmap = False
            memory = wx.MemoryDC()
            self._storedBitmap = wx.EmptyBitmapRGBA(max(width, 1), max(height, 1))
            memory.SelectObject(self._storedBitmap)

            gcMemory = wx.GraphicsContext.Create(memory)

            gcMemory.SetBrush(br1)
            gcMemory.FillPath(path1) #draw main
            gcMemory.SetBrush(br3)
            gcMemory.FillPath(path3) #draw top bubble

            if self._bitmap:
                gcMemory.DrawBitmap(self._bitmap, pos_x - 2, pos_y, bw, bh)

            gcMemory.SetFont(font)
            gcMemory.DrawText(label, pos_x + bw + btnOffset, (height-th-shadowOffset)/2+btnOffset)

            memory.SelectObject(wx.NullBitmap)
            self._storedBitmap = self._storedBitmap.ConvertToImage()


    def GetPath(self, gc, rc, r):
        """
        Returns a rounded :class:`GraphicsPath` rectangle.

        :param `gc`: an instance of :class:`GraphicsContext`;
        :param Rect `rc`: a client rectangle;
        :param float `r`: the radius of the rounded part of the rectangle.

        :return: A rounded rectangle, an instance of :class:`GraphicsPath`.        
        """

        x, y, w, h = rc
        path = gc.CreatePath()
        path.AddRoundedRectangle(x, y, w, h, r)
        path.CloseSubpath()
        return path


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

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

        self.Invalidate()


    def OnLeftDown(self, event):
        """
        Handles the ``wx.EVT_LEFT_DOWN`` event for :class:`AquaButton`.

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

        if not self.IsEnabled():
            return

        self._mouseAction = CLICK
        self.CaptureMouse()
        self.Refresh()
        event.Skip()


    def OnLeftUp(self, event):
        """
        Handles the ``wx.EVT_LEFT_UP`` event for :class:`AquaButton`.

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

        if not self.IsEnabled() or not self.HasCapture():
            return

        pos = event.GetPosition()
        rect = self.GetClientRect()

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

        if rect.Contains(pos):
            self._mouseAction = HOVER
            self.Notify()
        else:
            self._mouseAction = None

        self.Refresh()
        event.Skip()


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

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

        if not self.IsEnabled():
            return

        self._mouseAction = HOVER
        self.Refresh()
        event.Skip()


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

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

        self._mouseAction = None
        self.Refresh()
        event.Skip()


    def OnGainFocus(self, event):
        """
        Handles the ``wx.EVT_SET_FOCUS`` event for :class:`AquaButton`.

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

        self._hasFocus = True
        self.Refresh()
        self.Update()

        if self._pulseOnFocus:
            self._gammaFactor = 1.0
            self._timer.Start(100)


    def OnLoseFocus(self, event):
        """
        Handles the ``wx.EVT_KILL_FOCUS`` event for :class:`AquaButton`.

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

        if self._pulseOnFocus:
            self._gammaFactor = 1.0
            self._timer.Stop()

        self._hasFocus = False
        self.Refresh()
        self.Update()


    def OnKeyDown(self, event):
        """
        Handles the ``wx.EVT_KEY_DOWN`` event for :class:`AquaButton`.

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

        if self._hasFocus and event.GetKeyCode() == ord(" "):
            self._mouseAction = HOVER
            self.Refresh()
        event.Skip()


    def OnKeyUp(self, event):
        """
        Handles the ``wx.EVT_KEY_UP`` event for :class:`AquaButton`.

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

        if self._hasFocus and event.GetKeyCode() == ord(" "):
            self._mouseAction = HOVER
            self.Notify()
            self.Refresh()
        event.Skip()


    def OnPulseTimer(self, event):
        """
        Handles the ``wx.EVT_TIMER`` event for :class:`AquaButton`.

        :param `event`: a :class:`TimerEvent` event to be processed.

        :note: This method is only invoked when `pulseOnFocus` is ``True``.
        """

        if not self._storedBitmap.IsOk():
            self._timer.Stop()
            return

        xpos, ypos, width, height = self.GetClientRect()
        gamma = self._gammaFactor

        if gamma >= 1.3:
            self._gammaIncrement = -self._gammaIncrement
        elif gamma < 0.7:
            self._gammaIncrement = abs(self._gammaIncrement)

        self._gammaFactor += self._gammaIncrement

        image = self._storedBitmap.AdjustChannels(gamma, gamma, gamma, 1.0)
        dc = wx.ClientDC(self)
        dc.SetClippingRect(wx.Rect(xpos, ypos, width-8, height-8))
        dc.DrawBitmap(image.ConvertToBitmap(), xpos, ypos, True)


    def SetInitialSize(self, size=None):
        """
        Given the current font and bezel width settings, calculate
        and set a good size.

        :param `size`: an instance of :class:`Size` or ``None``, in which case the wxWidgets
         :class:`DefaultSize` is used instead.
        """

        if size is None:
            size = wx.DefaultSize
        wx.PyControl.SetInitialSize(self, size)

    SetBestSize = SetInitialSize


    def AcceptsFocus(self):
        """
        Can this window be given focus by mouse click?

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

        return self.IsShown() and self.IsEnabled()


    def GetDefaultAttributes(self):
        """
        Overridden base class virtual. By default we should use
        the same font/colour attributes as the native :class:`Button`.

        :return: an instance of :class:`VisualAttributes`.
        
        :note: Overridden from :class:`PyControl`.        
        """

        return wx.Button.GetClassDefaultAttributes()


    def ShouldInheritColours(self):
        """
        Overridden base class virtual. Buttons usually don't inherit
        the parent's colours.

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

        return False


    def Enable(self, enable=True):
        """
        Enables/disables the button.

        :param bool `enable`: ``True`` to enable the button, ``False`` to disable it.

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

        wx.PyControl.Enable(self, enable)
        self.Refresh()


    def SetPulseOnFocus(self, pulse):
        """
        Sets whether to enable the pulsing effect on gaining focus or not.

        :param bool `pulse`: ``True`` to enable pulsing when the :class:`AquaButton` gains focus,
         ``False`` to disable this effect.
        """

        if pulse == self._pulseOnFocus:
            return

        self._pulseOnFocus = pulse
        self.Invalidate()


    def GetPulseOnFocus(self):
        """
        Returns whether the pulsing effect is active.

        :return: ``True`` if the pulsing effect is active, ``False`` otherwise.
        """

        return self._pulseOnFocus


    def DoGetBestSize(self):
        """
        Overridden base class virtual. Determines the best size of the
        button based on the label and bezel size.

        :return: An instance of :class:`Size`.
        
        :note: Overridden from :class:`PyControl`.
        """

        label = self.GetLabel()
        if not label:
            return wx.Size(112, 48)

        dc = wx.ClientDC(self)
        dc.SetFont(self.GetFont())
        retWidth, retHeight = dc.GetTextExtent(label)

        bmpWidth = bmpHeight = 0
        constant = 24
        if self._bitmap:
            bmpWidth, bmpHeight = self._bitmap.GetWidth()+10, self._bitmap.GetHeight()
            retWidth += bmpWidth
            retHeight = max(bmpHeight, retHeight)
            constant = 24

        return wx.Size(retWidth+constant, retHeight+constant)


    def SetBackgroundColour(self, colour):
        """
        Sets the :class:`AquaButton` background colour.

        :param `colour`: a valid :class:`Colour` object.

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

        wx.PyControl.SetBackgroundColour(self, colour)
        self._backColour = colour
        self.Invalidate()


    def GetBackgroundColour(self):
        """
        Returns the button colour when the mouse is not hovering on the button.

        :return: An instance of :class:`Colour`.
        
        :note: Overridden from :class:`PyControl`.
        """

        return self._backColour


    def SetHoverColour(self, colour):
        """
        Sets the button colour when the mouse is hovering on the button.

        :param `colour`: a valid :class:`Colour` object.
        """

        self._hoverColour = colour
        self.Invalidate()


    def GetHoverColour(self):
        """
        Returns the button colour when the mouse is hovering on the button.

        :return: An instance of :class:`Colour`.
        """

        return self._hoverColour


    def SetDisabledColour(self, colour):
        """
        Sets the button colour when it is disabled.

        :param `colour`: a valid :class:`Colour` object.
        """

        self._disableColour = colour
        self.Invalidate()


    def GetDisabledColour(self):
        """
        Returns the button colour when it is disabled.

        :return: An instance of :class:`Colour`.
        """

        return self._disableColour


    def SetShadowColour(self, colour):
        """
        Sets the button shadow colour.

        :param `colour`: a valid :class:`Colour` object.

        .. versionadded:: 0.9.7
        """

        self._shadowColour = colour
        self.Invalidate()


    def GetShadowColour(self):
        """
        Returns the button shadow colour.

        :return: An instance of :class:`Colour`.

        .. versionadded:: 0.9.7
        """

        return self._shadowColour


    def SetRectColour(self, colour):
        """
        Sets the button rectangular background colour.

        :param `colour`: a valid :class:`Colour` object.

        .. versionadded:: 0.9.7
        """

        self._rectColour = colour
        self.Invalidate()


    def GetRectColour(self):
        """
        Returns the button rectangular background colour.

        :return: An instance of :class:`Colour`.

        .. versionadded:: 0.9.7
        """

        return self._rectColour

    SetBackgroundColor = SetBackgroundColour
    SetHoverColor = SetHoverColour
    GetHoverColor = GetHoverColour
    SetDisabledColor = SetDisabledColour
    GetDisabledColor = GetDisabledColour
    SetShadowColor = SetShadowColour
    GetShadowColor = SetShadowColour
    SetRectColor = SetRectColour
    GetRectColor = SetRectColour


    def SetForegroundColour(self, colour):
        """
        Sets the :class:`AquaButton` foreground (text) colour.

        :param `colour`: a valid :class:`Colour` object.

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

        wx.PyControl.SetForegroundColour(self, colour)
        self._textColour = colour
        self.Invalidate()


    def GetForegroundColour(self):
        """
        Returns the text colour for :class:`AquaButton`.

        :return: An instance of :class:`Colour`.
        
        :note: Overridden from :class:`PyControl`.
        """

        return self._textColour


    def Invalidate(self):
        """ Invalidate the saved bitmap and refresh the button. """

        self._saveBitmap = True
        self._storedBitmap = wx.NullBitmap

        self.Refresh()


    def SetDefault(self):
        """
        This sets the :class:`AquaButton` to be the default item for the panel or dialog box.

        :note: Under Windows, only dialog box buttons respond to this function. As normal
         under Windows and Motif, pressing return causes the default button to be depressed
         when the return key is pressed. See also :meth:`Window.SetFocus` which sets the
         keyboard focus for windows and text panel items, and :meth:`TopLevelWindow.SetDefaultItem`.

        :note: Note that under Motif, calling this function immediately after creation of a button
         and before the creation of other buttons will cause misalignment of the row of buttons,
         since default buttons are larger. To get around this, call :meth:`~aquabutton.AquaButton.SetDefault` after you
         have created a row of buttons: wxPython will then set the size of all buttons currently
         on the panel to the same size.
        """

        tlw = wx.GetTopLevelParent(self)
        if hasattr(tlw, 'SetDefaultItem'):
            tlw.SetDefaultItem(self)


    def Notify(self):
        """ Actually sends a ``wx.EVT_BUTTON`` event to the listener (if any). """

        evt = AquaButtonEvent(wx.wxEVT_COMMAND_BUTTON_CLICKED, self.GetId())
        evt.SetButtonObj(self)
        evt.SetEventObject(self)
        self.GetEventHandler().ProcessEvent(evt)


class __ToggleMixin(object):
    """
    A mixin that allows to transform :class:`AquaButton` in the corresponding toggle button.
    """

    def SetToggle(self, flag):
        """
        Sets the button as toggled/not toggled.

        :param bool `flag`: ``True`` to set the button as toggled, ``False`` otherwise.
        """

        self.up = not flag
        self.Refresh()

    SetValue = SetToggle


    def GetToggle(self):
        """
        Returns the toggled state of a button.

        :return: ``True`` is the button is toggled, ``False`` if it is not toggled.
        """

        return not self.up

    GetValue = GetToggle


    def OnLeftDown(self, event):
        """
        Handles the ``wx.EVT_LEFT_DOWN`` event for :class:`AquaButton` when used as toggle button.

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

        if not self.IsEnabled():
            return

        self.saveUp = self.up
        self.up = not self.up
        self.CaptureMouse()
        self.SetFocus()
        self.Refresh()


    def OnLeftUp(self, event):
        """
        Handles the ``wx.EVT_LEFT_UP`` event for :class:`AquaButton` when used as toggle button.

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

        if not self.IsEnabled() or not self.HasCapture():
            return
        if self.HasCapture():
            self.ReleaseMouse()
            self.Refresh()
            if self.up != self.saveUp:
                self.Notify()


    def OnKeyDown(self, event):
        """
        Handles the ``wx.EVT_KEY_DOWN`` event for :class:`AquaButton` when used as toggle button.

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

        event.Skip()


    def OnMotion(self, event):
        """
        Handles the ``wx.EVT_MOTION`` event for :class:`AquaButton` when used as toggle button.

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

        if not self.IsEnabled():
            return
        
        if event.LeftIsDown() and self.HasCapture():
            x, y = event.GetPositionTuple()
            w, h = self.GetClientSizeTuple()
            
            if x < w and x >= 0 and y < h and y >= 0:
                self.up = not self.saveUp
                self.Refresh()
                return
            
            if x < 0 or y < 0 or x >= w or y >= h:
                self.up = self.saveUp
                self.Refresh()
                return
            
        event.Skip()


    def OnKeyUp(self, event):
        """
        Handles the ``wx.EVT_KEY_UP`` event for :class:`AquaButton` when used as toggle button.

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

        if self.hasFocus and event.GetKeyCode() == ord(" "):
            self.up = not self.up
            self.Notify()
            self.Refresh()

        event.Skip()


    def OnPaint(self, event):
        """
        Handles the ``wx.EVT_PAINT`` event for :class:`AquaButton` when used as toggle button.

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

        dc = wx.BufferedPaintDC(self)
        gc = wx.GraphicsContext.Create(dc)

        xpos, ypos, width, height = self.GetClientRect()

        dc.SetBackground(wx.Brush(self.GetParent().GetBackgroundColour()))
        dc.Clear()
        gc.SetBrush(wx.WHITE_BRUSH)

        shadowOffset = 5
        btnOffset = 0
        clr = self._backColour

        if not self.up:
            shadowOffset = 3
            clr = self._hoverColour
            btnOffset = 2

        if self._mouseAction == HOVER:
            clr = self._hoverColour

        rc1 = wx.Rect(btnOffset, btnOffset, width-8-btnOffset, height-8-btnOffset)
        path1 = self.GetPath(gc, rc1, 10)
        br1 = gc.CreateLinearGradientBrush(0, 0, 0, rc1.height+6, clr, wx.WHITE)

        # Create shadow
        rc2 = wx.Rect(*rc1)
        rc2.Offset((shadowOffset, shadowOffset))
        path2 = self.GetPath(gc, rc2, 10)
        br2 = gc.CreateRadialGradientBrush(rc2.x, rc2.y,
                                           rc2.x+rc2.width, rc2.y+rc2.height,
                                           rc2.width, wx.NamedColour("grey"), wx.WHITE)

        # Create top water colour to give "aqua" effect
        rc3 = wx.Rect(*rc1)
        rc3.Inflate(-5, -5)
        rc3.height = 15
        path3 = self.GetPath(gc, rc3, 10)

        br3 = gc.CreateLinearGradientBrush(rc3.x, rc3.y, rc3.x, rc3.y+rc3.height,
                                           wx.Colour(255, 255, 255, 255), wx.Colour(255, 255, 255, 0))

        # draw shapes
        gc.SetBrush(br2)
        gc.FillPath(path2)  #draw shadow
        gc.SetBrush(br1)
        gc.FillPath(path1) #draw main
        gc.SetBrush(br3)
        gc.FillPath(path3) #draw top bubble

        font = gc.CreateFont(self.GetFont(), self._textColour)

        gc.SetFont(font)
        label = self.GetLabel()
        tw, th = gc.GetTextExtent(label)

        if self._bitmap:
            bw, bh = self._bitmap.GetWidth(), self._bitmap.GetHeight()
        else:
            bw = bh = 0

        pos_x = (width-bw-tw)/2+btnOffset-shadowOffset      # adjust for bitmap and text to centre
        if self._bitmap:
            pos_y =  (height-bh-shadowOffset)/2+btnOffset
            gc.DrawBitmap(self._bitmap, pos_x, pos_y, bw, bh) # draw bitmap if available
            pos_x = pos_x + 2   # extra spacing from bitmap

        # Create a Path to draw the text
        gc.DrawText(label, pos_x + bw + btnOffset, (height-th-shadowOffset)/2+btnOffset)      # draw the text

        if self._saveBitmap:
            # Save the bitmap using wx.MemoryDC for later use
            self._saveBitmap = False
            memory = wx.MemoryDC()
            self._storedBitmap = wx.EmptyBitmapRGBA(max(width, 1), max(height, 1))
            memory.SelectObject(self._storedBitmap)

            gcMemory = wx.GraphicsContext.Create(memory)

            gcMemory.SetBrush(br1)
            gcMemory.FillPath(path1) #draw main
            gcMemory.SetBrush(br3)
            gcMemory.FillPath(path3) #draw top bubble

            if self._bitmap:
                gcMemory.DrawBitmap(self._bitmap, pos_x - 2, pos_y, bw, bh)

            gcMemory.SetFont(font)
            gcMemory.DrawText(label, pos_x + bw + btnOffset, (height-th-shadowOffset)/2+btnOffset)

            memory.SelectObject(wx.NullBitmap)
            self._storedBitmap = self._storedBitmap.ConvertToImage()


class AquaToggleButton(__ToggleMixin, AquaButton):
    """ An :class:`AquaButton` toggle button. """
    pass