buttonbar.py 50.4 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 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314
"""
A ribbon button bar is similar to a traditional toolbar.


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

It contains one or more buttons (button bar buttons, not :class:`Button`), each of which
has a label and an icon. It differs from a :class:`toolbar` in several ways:

- Individual buttons can grow and contract.
- Buttons have labels as well as bitmaps.
- Bitmaps are typically larger (at least 32x32 pixels) on a button bar compared to
  a tool bar (which typically has 16x15).
- There is no grouping of buttons on a button bar
- A button bar typically has a border around each individual button, whereas a tool
  bar typically has a border around each group of buttons.


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

This class processes the following events:

======================================== ========================================
Event Name                               Description
======================================== ========================================
``EVT_RIBBONBUTTONBAR_CLICKED``          Triggered when the normal (non-dropdown) region of a button on the button bar is clicked.
``EVT_RIBBONBUTTONBAR_DROPDOWN_CLICKED`` Triggered when the dropdown region of a button on the button bar is clicked. :meth:`RibbonButtonBarEvent.PopupMenu() <RibbonButtonBarEvent.PopupMenu>` should be called by the event handler if it wants to display a popup menu (which is what most dropdown buttons should be doing).
======================================== ========================================

"""

import wx

from control import RibbonControl
from art import *

wxEVT_COMMAND_RIBBONBUTTON_CLICKED = wx.NewEventType()
wxEVT_COMMAND_RIBBONBUTTON_DROPDOWN_CLICKED = wx.NewEventType()

EVT_RIBBONBUTTONBAR_CLICKED = wx.PyEventBinder(wxEVT_COMMAND_RIBBONBUTTON_CLICKED, 1)
EVT_RIBBONBUTTONBAR_DROPDOWN_CLICKED = wx.PyEventBinder(wxEVT_COMMAND_RIBBONBUTTON_DROPDOWN_CLICKED, 1)


class RibbonButtonBarButtonSizeInfo(object):

    def __init__(self):
        
        self.is_supported = True
        self.size = wx.Size()
        self.normal_region = wx.Rect()
        self.dropdown_region = wx.Rect()


class RibbonButtonBarButtonInstance(object):

    def __init__(self):
        
        self.position = wx.Point()
        self.base = None
        self.size = wx.Size()


class RibbonButtonBarButtonBase(object):

    def __init__(self):

        self.label = ""
        self.help_string = ""
        self.bitmap_large = wx.NullBitmap
        self.bitmap_large_disabled = wx.NullBitmap
        self.bitmap_small = wx.NullBitmap
        self.bitmap_small_disabled = wx.NullBitmap
        self.sizes = [RibbonButtonBarButtonSizeInfo() for i in xrange(3)]
        self.client_data = None
        self.id = -1
        self.kind = None
        self.state = None

        
    def NewInstance(self):
    
        i = RibbonButtonBarButtonInstance()
        i.base = self
        return i
    

    def GetLargestSize(self):
    
        if self.sizes[RIBBON_BUTTONBAR_BUTTON_LARGE].is_supported:
            return RIBBON_BUTTONBAR_BUTTON_LARGE
        if self.sizes[RIBBON_BUTTONBAR_BUTTON_MEDIUM].is_supported:
            return RIBBON_BUTTONBAR_BUTTON_MEDIUM

        return RIBBON_BUTTONBAR_BUTTON_SMALL
    

    def GetSmallerSize(self, size, n=1):
    
        for i in xrange(n, 0, -1):
        
            if size == RIBBON_BUTTONBAR_BUTTON_LARGE:
                if self.sizes[RIBBON_BUTTONBAR_BUTTON_MEDIUM].is_supported:
                    return True, RIBBON_BUTTONBAR_BUTTON_MEDIUM
                
            elif size == RIBBON_BUTTONBAR_BUTTON_MEDIUM:
                if self.sizes[RIBBON_BUTTONBAR_BUTTON_SMALL].is_supported:
                    return True, RIBBON_BUTTONBAR_BUTTON_SMALL
                
            else:
                return False, None
    

class RibbonButtonBarLayout(object):

    def __init__(self):

        self.overall_size = wx.Size()
        self.buttons = []
    

    def CalculateOverallSize(self):
    
        self.overall_size = wx.Size(0, 0)

        for instance in self.buttons:
            size = instance.base.sizes[instance.size].size
            right = instance.position.x + size.GetWidth()
            bottom = instance.position.y + size.GetHeight()
            
            if right > self.overall_size.GetWidth():
                self.overall_size.SetWidth(right)
            if bottom > self.overall_size.GetHeight():            
                self.overall_size.SetHeight(bottom)


    def FindSimilarInstance(self, inst):
    
        if inst is None:
            return None
            
        for instance in self.buttons:
            if instance.base == inst.base:
                return instance
            
        return None
    

class RibbonButtonBarEvent(wx.PyCommandEvent):
    """
    Event used to indicate various actions relating to a button on a :class:`RibbonButtonBar`.

    .. seealso:: :class:`RibbonButtonBar` for available event types.
    """
    
    def __init__(self, command_type=None, win_id=0, bar=None):
        """
        Default class constructor.

        :param integer `command_type`: the event type;
        :param integer `win_id`: the event identifier;
        :param `bar`: an instance of :class:`RibbonButtonBar`.
        """

        wx.PyCommandEvent.__init__(self, command_type, win_id)
        self._bar = bar


    def GetBar(self):
        """
        Returns the bar which contains the button which the event relates to.

        :returns: An instance of :class:`RibbonButtonBar`.
        """

        return self._bar

    
    def SetBar(self, bar):
        """
        Sets the button bar relating to this event.

        :param `bar`: an instance of :class:`RibbonButtonBar`.

        """

        self._bar = bar


    def PopupMenu(self, menu):
        """
        Display a popup menu as a result of this (dropdown clicked) event.

        :param `menu`: an instance of :class:`Menu`.
        """

        pos = wx.Point()
        
        if self._bar._active_button:        
            size = self._bar._active_button.base.sizes[self._bar._active_button.size]
            btn_rect = wx.Rect()
            btn_rect.SetTopLeft(self._bar._layout_offset + self._bar._active_button.position)
            btn_rect.SetSize(wx.Size(*size.size))
            pos = btn_rect.GetBottomLeft()
            pos.y += 1
        
        return self._bar.PopupMenu(menu, pos)
        

class RibbonButtonBar(RibbonControl):
    """ A ribbon button bar is similar to a traditional toolbar. """

    def __init__(self, parent, id=wx.ID_ANY, pos=wx.DefaultPosition, size=wx.DefaultSize, agwStyle=0):
        """
        Default class constructor.

        :param `parent`: pointer to a parent window, typically a :class:`~lib.agw.ribbon.panel.RibbonPanel`;
        :type `parent`: :class:`Window`
        :param integer `id`: window identifier. If ``wx.ID_ANY``, will automatically create
         an identifier;
        :param `pos`: window position. ``wx.DefaultPosition`` indicates that wxPython
         should generate a default position for the window;
        :type `pos`: tuple or :class:`Point`
        :param `size`: window size. ``wx.DefaultSize`` indicates that wxPython should
         generate a default size for the window. If no suitable size can be found, the
         window will be sized to 20x20 pixels so that the window is visible but obviously
         not correctly sized;
        :type `size`: tuple or :class:`Size`
        :param integer `agwStyle`: the AGW-specific window style, currently unused.
        """

        RibbonControl.__init__(self, parent, id, pos, size, style=wx.BORDER_NONE)        

        self._layouts_valid = False
        self.CommonInit(agwStyle)

        self.Bind(wx.EVT_ERASE_BACKGROUND, self.OnEraseBackground)
        self.Bind(wx.EVT_ENTER_WINDOW, self.OnMouseEnter)
        self.Bind(wx.EVT_LEAVE_WINDOW, self.OnMouseLeave)
        self.Bind(wx.EVT_MOTION, self.OnMouseMove)
        self.Bind(wx.EVT_PAINT, self.OnPaint)
        self.Bind(wx.EVT_SIZE, self.OnSize)
        self.Bind(wx.EVT_LEFT_DOWN, self.OnMouseDown)
        self.Bind(wx.EVT_LEFT_UP, self.OnMouseUp)
    
    
    def AddButton(self, button_id, label, bitmap, bitmap_small=wx.NullBitmap, bitmap_disabled=wx.NullBitmap,
                  bitmap_small_disabled=wx.NullBitmap, kind=RIBBON_BUTTON_NORMAL, help_string="", client_data=None):
        """
        Add a button to the button bar.

        :param integer `button_id`: id of the new button (used for event callbacks);
        :param string `label`: label of the new button;
        :param `bitmap`: large bitmap of the new button, an instance of :class:`Bitmap`. Must be the same size as
         all other large bitmaps used on the button bar;
        :param `bitmap_small`: small bitmap of the new button, an instance of :class:`Bitmap`. If left as :class:`NullBitmap`,
         then a small bitmap will be automatically generated. Must be the same size
         as all other small bitmaps used on the button bar;
        :param `bitmap_disabled`: large bitmap of the new button when it is disabled, an instance of :class:`Bitmap`.
         If left as :class:`NullBitmap`, then a bitmap will be automatically generated from `bitmap`;
        :param `bitmap_small_disabled`: small bitmap of the new button when it is disabled, an instance of :class:`Bitmap`.
         If left as :class:`NullBitmap`, then a bitmap will be automatically generated from `bitmap_small`;
        :param integer `kind`: the kind of button to add, one of the following values:

         ========================================== =========== ==========================================
         Button Kind                                Hex Value   Description
         ========================================== =========== ==========================================
         ``RIBBON_BUTTON_NORMAL``                           0x1 Normal button or tool with a clickable area which causes some generic action.
         ``RIBBON_BUTTON_DROPDOWN``                         0x2 Dropdown button or tool with a clickable area which typically causes a dropdown menu.
         ``RIBBON_BUTTON_HYBRID``                           0x3 Button or tool with two clickable areas - one which causes a dropdown menu, and one which causes a generic action.
         ``RIBBON_BUTTON_TOGGLE``                           0x4 Normal button or tool with a clickable area which toggles the button between a pressed and unpressed state.
         ========================================== =========== ==========================================
        
        :param string `help_string`: the UI help string to associate with the new button;
        :param object `client_data`: client data to associate with the new button (any Python object).

        :returns: An opaque pointer which can be used only with other button bar methods.
        
        :see: :meth:`~RibbonButtonBar.InsertButton`, :meth:`~RibbonButtonBar.AddDropdownButton`, :meth:`~RibbonButtonBar.AddHybridButton`
        """

        return self.InsertButton(self.GetButtonCount(), button_id, label, bitmap,
                                 bitmap_small, bitmap_disabled, bitmap_small_disabled, kind, help_string,
                                 client_data)


    def AddSimpleButton(self, button_id, label, bitmap, help_string, kind=RIBBON_BUTTON_NORMAL):
        """
        Add a button to the button bar (simple version).

        :param integer `button_id`: id of the new button (used for event callbacks);
        :param string `label`: label of the new button;
        :param `bitmap`: large bitmap of the new button, an instance of :class:`Bitmap`. Must be the same size as
         all other large bitmaps used on the button bar;
        :param string `help_string`: the UI help string to associate with the new button;
        :param integer `kind`: the kind of button to add.

        :returns: An opaque pointer which can be used only with other button bar methods.

        :see: :meth:`~RibbonButtonBar.AddButton` for a list of valid button `kind` values.        
        """

        return self.AddButton(button_id, label, bitmap, wx.NullBitmap, wx.NullBitmap,
                              wx.NullBitmap, kind, help_string)


    def InsertButton(self, pos, button_id, label, bitmap, bitmap_small=wx.NullBitmap, bitmap_disabled=wx.NullBitmap,
                     bitmap_small_disabled=wx.NullBitmap, kind=RIBBON_BUTTON_NORMAL, help_string="", client_data=None):

        """
        Inserts a button in the button bar at the position specified by `pos`.

        :param integer `pos`: the position at which the new button must be inserted (zero-based);
        :param integer `button_id`: id of the new button (used for event callbacks);
        :param string `label`: label of the new button;
        :param `bitmap`: large bitmap of the new button, an instance of :class:`Bitmap`. Must be the same size as
         all other large bitmaps used on the button bar;
        :param `bitmap_small`: small bitmap of the new button, an instance of :class:`Bitmap`. If left as :class:`NullBitmap`,
         then a small bitmap will be automatically generated. Must be the same size
         as all other small bitmaps used on the button bar;
        :param `bitmap_disabled`: large bitmap of the new button when it is disabled, an instance of :class:`Bitmap`.
         If left as :class:`NullBitmap`, then a bitmap will be automatically generated from `bitmap`;
        :param `bitmap_small_disabled`: small bitmap of the new button when it is disabled, an instance of :class:`Bitmap`.
         If left as :class:`NullBitmap`, then a bitmap will be automatically generated from `bitmap_small`;
        :param integer `kind`: the kind of button to add;
        :param string `help_string`: the UI help string to associate with the new button;
        :param object `client_data`: client data to associate with the new button.

        :returns: An opaque pointer which can be used only with other button bar methods.

        :raise: `Exception` if both `bitmap` and `bitmap_small` are invalid or if the input `help_string` is not
         a valid Python `basestring`.
         
        :see: :meth:`~RibbonButtonBar.AddDropdownButton`, :meth:`~RibbonButtonBar.AddHybridButton` and :meth:`~RibbonButtonBar.AddButton` for a list of valid button `kind` values.

        .. versionadded:: 0.9.5
        """

        if not bitmap.IsOk() and not bitmap_small.IsOk():
            raise Exception("Invalid main bitmap")

        if not isinstance(help_string, basestring):
            raise Exception("Invalid help string parameter")
            
        if not self._buttons:
            if bitmap.IsOk():
            
                self._bitmap_size_large = bitmap.GetSize()
                if not bitmap_small.IsOk():
                    w, h = self._bitmap_size_large
                    self._bitmap_size_small = wx.Size(0.5*w, 0.5*h)
                
            if bitmap_small.IsOk():
            
                self._bitmap_size_small = bitmap_small.GetSize()
                if not bitmap.IsOk():
                    w, h = self._bitmap_size_small
                    self._bitmap_size_large = wx.Size(2*w, 2*h)
                
        base = RibbonButtonBarButtonBase()
        base.id = button_id
        base.label = label
        base.bitmap_large = bitmap
        
        if not base.bitmap_large.IsOk():        
            base.bitmap_large = self.MakeResizedBitmap(base.bitmap_small, self._bitmap_size_large)
        
        elif base.bitmap_large.GetSize() != self._bitmap_size_large:        
            base.bitmap_large = self.MakeResizedBitmap(base.bitmap_large, self._bitmap_size_large)
        
        base.bitmap_small = bitmap_small
        
        if not base.bitmap_small.IsOk():
            base.bitmap_small = self.MakeResizedBitmap(base.bitmap_large, self._bitmap_size_small)
        
        elif base.bitmap_small.GetSize() != self._bitmap_size_small:
            base.bitmap_small = self.MakeResizedBitmap(base.bitmap_small, self._bitmap_size_small)
        
        base.bitmap_large_disabled = bitmap_disabled
        
        if not base.bitmap_large_disabled.IsOk():
            base.bitmap_large_disabled = self.MakeDisabledBitmap(base.bitmap_large)
        
        base.bitmap_small_disabled = bitmap_small_disabled
        
        if not base.bitmap_small_disabled.IsOk():        
            base.bitmap_small_disabled = self.MakeDisabledBitmap(base.bitmap_small)
        
        base.kind = kind
        base.help_string = help_string
        base.client_data = client_data
        base.state = 0

        temp_dc = wx.ClientDC(self)
        self.FetchButtonSizeInfo(base, RIBBON_BUTTONBAR_BUTTON_SMALL, temp_dc)
        self.FetchButtonSizeInfo(base, RIBBON_BUTTONBAR_BUTTON_MEDIUM, temp_dc)
        self.FetchButtonSizeInfo(base, RIBBON_BUTTONBAR_BUTTON_LARGE, temp_dc)

        self._buttons.insert(pos, base)
        self._layouts_valid = False
        
        return base


    def AddDropdownButton(self, button_id, label, bitmap, help_string=""):
        """
        Add a dropdown button to the button bar (simple version).

        :param integer `button_id`: id of the new button (used for event callbacks);
        :param string `label`: label of the new button;
        :param `bitmap`: large bitmap of the new button, an instance of :class:`Bitmap`. Must be the same size as
         all other large bitmaps used on the button bar;
        :param string `help_string`: the UI help string to associate with the new button.

        :returns: An opaque pointer which can be used only with other button bar methods.

        :see: :meth:`~RibbonButtonBar.AddButton`, :meth:`~RibbonButtonBar.InsertDropdownButton`, :meth:`~RibbonButtonBar.InsertButton`
        """

        return self.AddSimpleButton(button_id, label, bitmap, kind=RIBBON_BUTTON_DROPDOWN, help_string=help_string)


    def InsertDropdownButton(self, pos, button_id, label, bitmap, help_string=""):
        """
        Inserts a dropdown button in the button bar at the position specified by `pos`.

        :param integer `pos`: the position at which the new button must be inserted (zero-based);
        :param integer `button_id`: id of the new button (used for event callbacks);
        :param string `label`: label of the new button;
        :param `bitmap`: large bitmap of the new button, an instance of :class:`Bitmap`. Must be the same size as
         all other large bitmaps used on the button bar;
        :param string `help_string`: the UI help string to associate with the new button.

        :returns: An opaque pointer which can be used only with other button bar methods.

        :see: :meth:`~RibbonButtonBar.AddButton`, :meth:`~RibbonButtonBar.InsertButton`, :meth:`~RibbonButtonBar.AddDropdownButton`

        .. versionadded:: 0.9.5
        """

        return self.InsertButton(pos, button_id, label, bitmap, kind=RIBBON_BUTTON_DROPDOWN, help_string=help_string)
    

    def AddToggleButton(self, button_id, label, bitmap, help_string=""):
        """
        Add a toggle button to the button bar.

        :param integer `button_id`: id of the new button (used for event callbacks);
        :param string `label`: label of the new button;
        :param `bitmap`: large bitmap of the new button, an instance of :class:`Bitmap`. Must be the same size as
         all other large bitmaps used on the button bar;
        :param string `help_string`: the UI help string to associate with the new button.

        :returns: An opaque pointer which can be used only with other button bar methods.

        :see: :meth:`~RibbonButtonBar.AddButton`, :meth:`~RibbonButtonBar.InsertButton`, :meth:`~RibbonButtonBar.InsertToggleButton`
        """

        return self.AddButton(button_id, label, bitmap, kind=RIBBON_BUTTON_TOGGLE, help_string=help_string)


    def InsertToggleButton(self, pos, button_id, label, bitmap, help_string=""):
        """
        Inserts a toggle button in the button bar at the position specified by `pos`.

        :param integer `pos`: the position at which the new button must be inserted (zero-based);
        :param integer `button_id`: id of the new button (used for event callbacks);
        :param string `label`: label of the new button;
        :param `bitmap`: large bitmap of the new button, an instance of :class:`Bitmap`. Must be the same size as
         all other large bitmaps used on the button bar;
        :param string `help_string`: the UI help string to associate with the new button.

        :returns: An opaque pointer which can be used only with other button bar methods.

        :see: :meth:`~RibbonButtonBar.AddButton`, :meth:`~RibbonButtonBar.InsertButton`, :meth:`~RibbonButtonBar.AddToggleButton`

        .. versionadded:: 0.9.5
        """

        return self.InsertButton(pos, button_id, label, bitmap, kind=RIBBON_BUTTON_TOGGLE, help_string=help_string)


    def AddHybridButton(self, button_id, label, bitmap, help_string=""):
        """
        Add a hybrid button to the button bar (simple version).

        :param integer `button_id`: id of the new button (used for event callbacks);
        :param string `label`: label of the new button;
        :param `bitmap`: large bitmap of the new button, an instance of :class:`Bitmap`. Must be the same size as
         all other large bitmaps used on the button bar;
        :param string `help_string`: the UI help string to associate with the new button.

        :returns: An opaque pointer which can be used only with other button bar methods.

        :see: :meth:`~RibbonButtonBar.AddButton`, :meth:`~RibbonButtonBar.InsertButton`, :meth:`~RibbonButtonBar.InsertHybridButton`
        """

        return self.AddSimpleButton(button_id, label, bitmap, kind=RIBBON_BUTTON_HYBRID, help_string=help_string)


    def InsertHybridButton(self, pos, button_id, label, bitmap, help_string=""):
        """
        Inserts a hybrid button in the button bar at the position specified by `pos`.

        :param integer `pos`: the position at which the new button must be inserted (zero-based);
        :param integer `button_id`: id of the new button (used for event callbacks);
        :param string `label`: label of the new button;
        :param `bitmap`: large bitmap of the new button, an instance of :class:`Bitmap`. Must be the same size as
         all other large bitmaps used on the button bar;
        :param string `help_string`: the UI help string to associate with the new button.

        :returns: An opaque pointer which can be used only with other button bar methods.

        :see: :meth:`~RibbonButtonBar.AddButton`, :meth:`~RibbonButtonBar.InsertButton`, :meth:`~RibbonButtonBar.AddHybridButton`

        .. versionadded:: 0.9.5
        """

        return self.InsertButton(pos, button_id, label, bitmap, kind=RIBBON_BUTTON_HYBRID, help_string=help_string)

        
    def FetchButtonSizeInfo(self, button, size, dc):

        info = button.sizes[size]
        
        if self._art:
        
            info.is_supported, info.size, info.normal_region, info.dropdown_region = \
                               self._art.GetButtonBarButtonSize(dc, self, button.kind, size, button.label,
                                                                self._bitmap_size_large, self._bitmap_size_small)
        
        else:
            info.is_supported = False


    def MakeResizedBitmap(self, original, size):
        """
        Resize and scale the `original` bitmap to the dimensions specified in `size`.

        :param `original`: the original bitmap, an instance of :class:`Bitmap`;
        :param `size`: the size to which the input bitmap must be rescaled, an instance of :class:`Size`.

        :return: A scaled representation of the input bitmap.
        """

        img = original.ConvertToImage()
        img.Rescale(size.GetWidth(), size.GetHeight(), wx.IMAGE_QUALITY_HIGH)
        return wx.BitmapFromImage(img)


    def MakeDisabledBitmap(self, original):
        """
        Converts the `original` bitmap into a visually-looking disabled one.

        :param `original`: the original bitmap, an instance of :class:`Bitmap`.

        :return: A visually-looking disabled representation of the input bitmap.
        """

        img = original.ConvertToImage()
        return wx.BitmapFromImage(img.ConvertToGreyscale())


    def Realize(self):
        """
        Calculate button layouts and positions.

        Must be called after buttons are added to the button bar, as otherwise the newly
        added buttons will not be displayed. In normal situations, it will be called
        automatically when :meth:`RibbonBar.Realize() <lib.agw.ribbon.bar.RibbonBar.Realize>` is called.

        :note: Reimplemented from :class:`~lib.agw.ribbon.control.RibbonControl`.
        """

        if not self._layouts_valid:
            self.MakeLayouts()
            self._layouts_valid = True
        
        return True


    def ClearButtons(self):
        """
        Delete all buttons from the button bar.

        :see: :meth:`~RibbonButtonBar.DeleteButton`
        """

        self._layouts_valid = False
        self._buttons = []
        self.Realize()


    def DeleteButton(self, button_id):
        """
        Delete a single button from the button bar.

        :param integer `button_id`: id of the button to delete.

        :return: ``True`` if the button has been found and successfully deleted, ``False`` otherwise.
        
        :see: :meth:`~RibbonButtonBar.ClearButtons`
        """

        for button in self._buttons:
            if button.id == button_id:            
                self._layouts_valid = False
                self._buttons.pop(button)
                self.Realize()
                self.Refresh()
                return True
            
        return False


    def EnableButton(self, button_id, enable=True):
        """
        Enable or disable a single button on the bar.

        :param integer `button_id`: id of the button to enable or disable;
        :param bool `enable`: ``True`` to enable the button, ``False`` to disable it.

        :raise: `Exception` when the input `button_id` could not be associated
         with a :class:`RibbonButtonBar` button.
        """

        for button in self._buttons:
            if button.id == button_id:            
                if enable:                
                    if button.state & RIBBON_BUTTONBAR_BUTTON_DISABLED:                    
                        button.state &= ~RIBBON_BUTTONBAR_BUTTON_DISABLED
                        self.Refresh()
                else:
                    if button.state & RIBBON_BUTTONBAR_BUTTON_DISABLED == 0:                    
                        button.state |= RIBBON_BUTTONBAR_BUTTON_DISABLED
                        self.Refresh()
                    
                return

        raise Exception('Invalid button id specified.')


    def ToggleButton(self, button_id, checked=True):
        """
        Toggles/untoggles a :class:`RibbonButtonBar` toggle button.

        :param integer `button_id`: id of the button to be toggles/untoggled;
        :param bool `checked`: ``True`` to toggle the button, ``False`` to untoggle it.

        :raise: `Exception` when the input `button_id` could not be associated
         with a :class:`RibbonButtonBar` button.
        """

        for button in self._buttons:
            if button.id == button_id:
                if checked:
                    if button.state & RIBBON_BUTTONBAR_BUTTON_TOGGLED == 0:
                        button.state |= RIBBON_BUTTONBAR_BUTTON_TOGGLED
                        self.Refresh()
                else:
                    if button.state & RIBBON_BUTTONBAR_BUTTON_TOGGLED:
                        button.state &= ~RIBBON_BUTTONBAR_BUTTON_TOGGLED
                        self.Refresh()

                return

        raise Exception('Invalid button id specified.')
            

    def IsButtonEnabled(self, button_id):
        """
        Returns whether a button in the bar is enabled or not.

        :param integer `button_id`: id of the button to check.

        :return: ``True`` if the button is enabled, ``False`` otherwise.

        :raise: `Exception` when the input `button_id` could not be associated
         with a :class:`RibbonButtonBar` button.
        """

        for button in self._buttons:
            if button.id == button_id:
                if button.state & RIBBON_BUTTONBAR_BUTTON_DISABLED:
                    return False
                return True

        raise Exception('Invalid button id specified.')
    

    def GetButtonCount(self):
        """
        Returns the number of buttons in this :class:`RibbonButtonBar`.

        .. versionadded:: 0.9.5
        """

        return len(self._buttons)
    
            
    def SetArtProvider(self, art):
        """
        Set the art provider to be used.

        In many cases, setting the art provider will also set the art provider on all
        child windows which extend :class:`~lib.agw.ribbon.control.RibbonControl`. In most cases, controls will not
        take ownership of the given pointer, with the notable exception being
        :meth:`RibbonBar.SetArtProvider() <lib.agw.ribbon.bar.RibbonBar.SetArtProvider>`.

        :param `art`: an art provider.
        """

        if art == self._art:        
            return
        
        RibbonControl.SetArtProvider(self, art)

        temp_dc = wx.ClientDC(self)
        for base in self._buttons:
            self.FetchButtonSizeInfo(base, RIBBON_BUTTONBAR_BUTTON_SMALL, temp_dc)
            self.FetchButtonSizeInfo(base, RIBBON_BUTTONBAR_BUTTON_MEDIUM, temp_dc)
            self.FetchButtonSizeInfo(base, RIBBON_BUTTONBAR_BUTTON_LARGE, temp_dc)
        
        self._layouts_valid = False
        self.Realize()


    def IsSizingContinuous(self):
        """
        Returns ``True`` if this window can take any size (greater than its minimum size),
        ``False`` if it can only take certain sizes.
        
        :see: :meth:`RibbonControl.GetNextSmallerSize() <lib.agw.ribbon.control.RibbonControl.GetNextSmallerSize>`,
         :meth:`RibbonControl.GetNextLargerSize() <lib.agw.ribbon.control.RibbonControl.GetNextLargerSize>`
        """

        return False


    def DoGetNextSmallerSize(self, direction, _result):
        """
        Implementation of :meth:`RibbonControl.GetNextSmallerSize() <lib.agw.ribbon.control.RibbonControl.GetNextSmallerSize>`.

        Controls which have non-continuous sizing must override this virtual function
        rather than :meth:`RibbonControl.GetNextSmallerSize() <RibbonControl.GetNextSmallerSize>`.

        :return: An instance of :class:`Size`.
        """
        
        result = wx.Size(*_result)
        
        for i, layout in enumerate(self._layouts):
            size = wx.Size(*layout.overall_size)
            
            if direction == wx.HORIZONTAL:
                if size.x < result.x and size.y <= result.y:                
                    result.x = size.x
                    break
                
            elif direction == wx.VERTICAL:
                if size.x <= result.x and size.y < result.y:                
                    result.y = size.y
                    break
                
            elif direction == wx.BOTH:
                if size.x < result.x and size.y < result.y:                
                    result = size
                    break

        return result


    def DoGetNextLargerSize(self, direction, _result):
        """
        Implementation of :meth:`RibbonControl.GetNextLargerSize() <lib.agw.ribbon.control.RibbonControl.GetNextLargerSize>`.

        Controls which have non-continuous sizing must override this virtual function
        rather than :meth:`RibbonControl.GetNextLargerSize() <RibbonControl.GetNextLargerSize>`.

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

        nlayouts = i = len(self._layouts)
        result = wx.Size(*_result)
        
        while 1:
            i -= 1
            layout = self._layouts[i]
            size = wx.Size(*layout.overall_size)
            
            if direction == wx.HORIZONTAL:
                if size.x > result.x and size.y <= result.y:        
                    result.x = size.x
                    break
                
            elif direction == wx.VERTICAL:
                if size.x <= result.x and size.y > result.y:                
                    result.y = size.y
                    break
                
            elif direction == wx.BOTH:
                if size.x > result.x and size.y > result.y:
                    result = size
                    break

            if i <= 0:
                break

        return result


    def OnEraseBackground(self, event):
        """
        Handles the ``wx.EVT_ERASE_BACKGROUND`` event for :class:`RibbonButtonBar`.

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

        # All painting done in main paint handler to minimise flicker
        pass


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

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

        dc = wx.AutoBufferedPaintDC(self)
        self._art.DrawButtonBarBackground(dc, self, wx.Rect(0, 0, *self.GetSize()))

        layout = self._layouts[self._current_layout]

        for button in layout.buttons:
            base = button.base

            bitmap = base.bitmap_large
            bitmap_small = base.bitmap_small
            
            if base.state & RIBBON_BUTTONBAR_BUTTON_DISABLED:            
                bitmap = base.bitmap_large_disabled
                bitmap_small = base.bitmap_small_disabled

            rect = wx.RectPS(button.position + self._layout_offset, base.sizes[button.size].size)
            self._art.DrawButtonBarButton(dc, self, rect, base.kind, base.state | button.size, base.label, bitmap, bitmap_small)
        

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

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

        new_size = event.GetSize()
        layout_count = len(self._layouts)
        self._current_layout = layout_count - 1
        
        for layout_i in xrange(layout_count):

            layout_size = self._layouts[layout_i].overall_size
            if layout_size.x <= new_size.x and layout_size.y <= new_size.y:            
                self._layout_offset.x = (new_size.x - layout_size.x)/2
                self._layout_offset.y = (new_size.y - layout_size.y)/2
                self._current_layout = layout_i
                break
            
        self._hovered_button = self._layouts[self._current_layout].FindSimilarInstance(self._hovered_button)
        self.Refresh()


    def UpdateWindowUI(self, flags):
        """
        This function sends one or more :class:`UpdateUIEvent` to the window.

        The particular implementation depends on the window; for example a :class:`ToolBar` will
        send an update UI event for each toolbar button, and a :class:`Frame` will send an
        update UI event for each menubar menu item.

        You can call this function from your application to ensure that your UI is up-to-date
        at this point (as far as your :class:`UpdateUIEvent` handlers are concerned). This may be
        necessary if you have called :meth:`UpdateUIEvent.SetMode` or :meth:`UpdateUIEvent.SetUpdateInterval`
        to limit the overhead that wxWidgets incurs by sending update UI events in idle time.

        :param integer `flags`: should be a bitlist of one or more of ``wx.UPDATE_UI_NONE``,
         ``wx.UPDATE_UI_RECURSE`` or ``wx.UPDATE_UI_FROMIDLE``.

        If you are calling this function from an `OnInternalIdle` or `OnIdle` function, make sure
        you pass the ``wx.UPDATE_UI_FROMIDLE`` flag, since this tells the window to only update
        the UI elements that need to be updated in idle time. Some windows update their elements
        only when necessary, for example when a menu is about to be shown. The following is an
        example of how to call :meth:`~RibbonButtonBar.UpdateWindowUI` from an idle function::

            def OnInternalIdle(self):

                if wx.UpdateUIEvent.CanUpdate(self):
                    self.UpdateWindowUI(wx.UPDATE_UI_FROMIDLE)


        
        .. versionadded:: 0.9.5
        """        

        wx.PyControl.UpdateWindowUI(self, flags)

        # don't waste time updating state of tools in a hidden toolbar
        if not self.IsShown():
            return

        rerealize = False

        for button in self._buttons:

            id = button.id
            event = wx.UpdateUIEvent(id)
            event.SetEventObject(self)

            if self.ProcessWindowEvent(event):
                if event.GetSetEnabled():
                    self.EnableButton(id, event.GetEnabled())
                if event.GetSetChecked():
                    self.ToggleButton(id, event.GetChecked())
                if event.GetSetText():
                    button.label = event.GetText()
                    rerealize = True

        if rerealize:
            self.Realize()

        
    def CommonInit(self, agwStyle):
        """
        Common initialization procedures.

        :param integer `agwStyle`: the AGW-specific window style, currently unused.
        """

        self._bitmap_size_large = wx.Size(32, 32)
        self._bitmap_size_small = wx.Size(16, 16)

        self._layouts = []
        self._buttons = []
        
        placeholder_layout = RibbonButtonBarLayout()
        placeholder_layout.overall_size = wx.Size(20, 20)
        self._layouts.append(placeholder_layout)
        self._current_layout = 0
        self._layout_offset = wx.Point(0, 0)
        self._hovered_button = None
        self._active_button = None
        self._lock_active_state = False

        self.SetBackgroundStyle(wx.BG_STYLE_CUSTOM)


    def GetMinSize(self):
        """
        Returns the minimum size of the window, an indication to the sizer layout mechanism
        that this is the minimum required size.

        This method normally just returns the value set by `SetMinSize`, but it can be
        overridden to do the calculation on demand.

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

        return wx.Size(*self._layouts[-1].overall_size)


    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()`.

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

        return wx.Size(*self._layouts[0].overall_size)


    def MakeLayouts(self):

        if self._layouts_valid or self._art == None:
            return
        
        # Clear existing layouts
        if self._hovered_button:            
            self._hovered_button.base.state &= ~RIBBON_BUTTONBAR_BUTTON_HOVER_MASK
            self._hovered_button = None
        
        if self._active_button:
            self._active_button.base.state &= ~RIBBON_BUTTONBAR_BUTTON_ACTIVE_MASK
            self._active_button = None
        
        self._layouts = []
    
        # Best layout : all buttons large, stacking horizontally
        layout = RibbonButtonBarLayout()
        cursor = wx.Point(0, 0)
        layout.overall_size.SetHeight(0)

        for button in self._buttons:
            instance = button.NewInstance()
            instance.position = wx.Point(*cursor)
            instance.size = button.GetLargestSize()
            size = wx.Size(*button.sizes[instance.size].size)
            cursor.x += size.GetWidth()
            layout.overall_size.SetHeight(max(layout.overall_size.GetHeight(), size.GetHeight()))
            layout.buttons.append(instance)

        layout.overall_size.SetWidth(cursor.x)
        self._layouts.append(layout)
        
        if len(self._buttons) >= 2:        
            # Collapse the rightmost buttons and stack them vertically
            iLast = len(self._buttons) - 1
            result = True
            
            while result and iLast > 0:
                result, iLast = self.TryCollapseLayout(self._layouts[-1], iLast)
                iLast -= 1
        
       
    def TryCollapseLayout(self, original, first_btn, last_button=None):

        btn_count = len(self._buttons)
        used_height = 0
        used_width = 0
        available_width = 0
        available_height = 0

        count = first_btn + 1
        
        while 1:
            count -= 1

            button = self._buttons[count]
            large_size_class = button.GetLargestSize()
            large_size = button.sizes[large_size_class].size
            t_available_height = max(available_height, large_size.GetHeight())
            t_available_width = available_width + large_size.GetWidth()
            small_size_class = large_size_class

            result, small_size_class = button.GetSmallerSize(small_size_class)
            if not result:
                return False, count
            
            small_size = button.sizes[small_size_class].size
            t_used_height = used_height + small_size.GetHeight()
            t_used_width = max(used_width, small_size.GetWidth())

            if t_used_height > t_available_height:
                count += 1
                break
            
            else:
                used_height = t_used_height
                used_width = t_used_width
                available_width = t_available_width
                available_height = t_available_height

            if count <= 0:
                break
        
        if count >= first_btn or used_width >= available_width:
            return False, count

        if last_button != None:
            last_button = count

        layout = RibbonButtonBarLayout()
        for indx, button in enumerate(original.buttons):
            instance = RibbonButtonBarButtonInstance()
            instance.position = wx.Point(*button.position)
            instance.size = button.size
            instance.base = self._buttons[indx]
            layout.buttons.append(instance)
            
        cursor = wx.Point(*layout.buttons[count].position)
        preserve_height = False
        
        if count == 0:        
            # If height isn't preserved (i.e. it is reduced), then the minimum
            # size for the button bar will decrease, preventing the original
            # layout from being used (in some cases).
            # It may be a good idea to always preverse the height, but for now
            # it is only done when the first button is involved in a collapse.
            preserve_height = True

        for btn_i in xrange(count, first_btn+1):
            instance = layout.buttons[btn_i]
            result, instance.size = instance.base.GetSmallerSize(instance.size)
            instance.position = wx.Point(*cursor)
            cursor.y += instance.base.sizes[instance.size].size.GetHeight()
        
        x_adjust = available_width - used_width

        for btn_i in xrange(first_btn+1, btn_count):
            instance = layout.buttons[btn_i]
            instance.position.x -= x_adjust
        
        layout.CalculateOverallSize()
        
##        # Sanity check
##        if layout.overall_size.GetWidth() >= original.overall_size.GetWidth() or \
##           layout.overall_size.GetHeight() > original.overall_size.GetHeight():
##        
##            del layout
##            return False, count
        
        if preserve_height:
            layout.overall_size.SetHeight(original.overall_size.GetHeight())
        
        self._layouts.append(layout)
        return True, count


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

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

        cursor = event.GetPosition()
        new_hovered = None
        new_hovered_state = 0

        layout = self._layouts[self._current_layout]

        for instance in layout.buttons:
            size = instance.base.sizes[instance.size]
            btn_rect = wx.Rect()
            btn_rect.SetTopLeft(self._layout_offset + instance.position)
            btn_rect.SetSize(size.size)

            if btn_rect.Contains(cursor) and self.IsButtonEnabled(instance.base.id):
                new_hovered = instance
                new_hovered_state = instance.base.state
                new_hovered_state &= ~RIBBON_BUTTONBAR_BUTTON_HOVER_MASK
                offset = wx.Point(*cursor)
                offset -= btn_rect.GetTopLeft()
                if size.normal_region.Contains(offset):
                    new_hovered_state |= RIBBON_BUTTONBAR_BUTTON_NORMAL_HOVERED
                
                if size.dropdown_region.Contains(offset):
                    new_hovered_state |= RIBBON_BUTTONBAR_BUTTON_DROPDOWN_HOVERED
                
                break

        if new_hovered == None and self.GetToolTip():
            self.SetToolTipString("")

        if new_hovered != self._hovered_button or (self._hovered_button != None and \
                                                   new_hovered_state != self._hovered_button.base.state):
        
            if self._hovered_button != None:            
                self._hovered_button.base.state &= ~RIBBON_BUTTONBAR_BUTTON_HOVER_MASK
            
            self._hovered_button = new_hovered
            if self._hovered_button != None:
                self._hovered_button.base.state = new_hovered_state
                self.SetToolTipString(self._hovered_button.base.help_string) 
            
            self.Refresh(False)
        
        if self._active_button and not self._lock_active_state:
        
            new_active_state = self._active_button.base.state
            new_active_state &= ~RIBBON_BUTTONBAR_BUTTON_ACTIVE_MASK
            size = self._active_button.base.sizes[self._active_button.size]
            btn_rect = wx.Rect()
            btn_rect.SetTopLeft(self._layout_offset + self._active_button.position)
            btn_rect.SetSize(size.size)
            
            if btn_rect.Contains(cursor):
            
                offset = wx.Point(*cursor)
                offset -= btn_rect.GetTopLeft()
                
                if size.normal_region.Contains(offset):                
                    new_active_state |= RIBBON_BUTTONBAR_BUTTON_NORMAL_ACTIVE
                
                if size.dropdown_region.Contains(offset):                
                    new_active_state |= RIBBON_BUTTONBAR_BUTTON_DROPDOWN_ACTIVE
                
            if new_active_state != self._active_button.base.state:            
                self._active_button.base.state = new_active_state
                self.Refresh(False)
        

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

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

        cursor = event.GetPosition()
        self._active_button = None

        layout = self._layouts[self._current_layout]
        
        for instance in layout.buttons:
        
            size = instance.base.sizes[instance.size]
            btn_rect = wx.Rect()
            btn_rect.SetTopLeft(self._layout_offset + instance.position)
            btn_rect.SetSize(size.size)
            
            if btn_rect.Contains(cursor) and self.IsButtonEnabled(instance.base.id):
                self._active_button = instance
                cursor -= btn_rect.GetTopLeft()
                state = 0
                if size.normal_region.Contains(cursor):
                    state = RIBBON_BUTTONBAR_BUTTON_NORMAL_ACTIVE
                elif size.dropdown_region.Contains(cursor):
                    state = RIBBON_BUTTONBAR_BUTTON_DROPDOWN_ACTIVE
                instance.base.state |= state
                self.Refresh(False)
                break
            

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

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

        cursor = event.GetPosition()

        if self._active_button:
        
            size = self._active_button.base.sizes[self._active_button.size]
            btn_rect = wx.Rect()
            btn_rect.SetTopLeft(self._layout_offset + self._active_button.position)
            btn_rect.SetSize(size.size)
            
            if btn_rect.Contains(cursor):
                id = self._active_button.base.id
                cursor -= btn_rect.GetTopLeft()
                
                while 1:                
                    if size.normal_region.Contains(cursor):
                        event_type = wxEVT_COMMAND_RIBBONBUTTON_CLICKED
                    elif size.dropdown_region.Contains(cursor):
                        event_type = wxEVT_COMMAND_RIBBONBUTTON_DROPDOWN_CLICKED
                    else:
                        break
                    
                    notification = RibbonButtonBarEvent(event_type, id)

                    if self._active_button.base.kind == RIBBON_BUTTON_TOGGLE:
                        self._active_button.base.state ^= RIBBON_BUTTONBAR_BUTTON_TOGGLED
                        notification.SetInt(self._active_button.base.state & RIBBON_BUTTONBAR_BUTTON_TOGGLED)
                
                    notification.SetEventObject(self)
                    notification.SetBar(self)
                    self._lock_active_state = True
                    self.GetEventHandler().ProcessEvent(notification)
                    self._lock_active_state = False
                    break

                if self._active_button: # may have been Noneed by event handler
                    self._active_button.base.state &= ~RIBBON_BUTTONBAR_BUTTON_ACTIVE_MASK
                    self._active_button = None
                
                self.Refresh()
        

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

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

        if self._active_button and not event.LeftIsDown():
            self._active_button = None
    

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

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

        repaint = False
        if self._hovered_button != None:
            self._hovered_button.base.state &= ~RIBBON_BUTTONBAR_BUTTON_HOVER_MASK
            self._hovered_button = None
            repaint = True
        
        if self._active_button != None and not self._lock_active_state:
            self._active_button.base.state &= ~RIBBON_BUTTONBAR_BUTTON_ACTIVE_MASK
            repaint = True
        
        if repaint:
            self.Refresh(False)


    def GetDefaultBorder(self):
        """ Returns the default border style for :class:`RibbonButtonBar`. """

        return wx.BORDER_NONE