Advanced Generic Widgets

Navigation

  • index
  • modules |
  • next |
  • Home |
  • Gallery |
  • Contents»
  • Advanced Generic Widgets

Advanced Generic Widgets

This is the Advanced Generic Widgets package (AGW). It provides many custom-drawn wxPython controls: some of them can be used as a replacement of the platform native controls, others are simply an addition to the already rich wxPython widgets set.

AGW sample screenshots

Starting from version 2.8.9.2, AGW has been officially integrated in the wxPython framework, under the wx.lib.agw package.

In order to use one of the AGW widgets, you can simply write:

import wx.lib.agw.customtreectrl as CT

#------------------------
# CustomTreeCtrl subclass
#------------------------

class CustomTreeCtrl(CT.CustomTreeCtrl):

    def __init__(self, parent, id=wx.ID_ANY, pos=wx.DefaultPosition,
                 size=wx.DefaultSize,
                 style=wx.SUNKEN_BORDER,
                 agwStyle=CT.TR_HAS_BUTTONS|CT.TR_HAS_VARIABLE_ROW_HEIGHT):

        CT.CustomTreeCtrl.__init__(self, parent, id, pos, size, style, agwStyle)

        # Do something else in the initialization...

Some of the widgets contained in AGW are simply a translation/improvements of existing wxWidgets C++ controls (i.e., aui or ultimatelistctrl are a couple of examples).

Version: | 0.9.4
Date: | 12 March 2012

Note

There currently is a first draft of the documentation, created with HTML Help Workshop, in a downloadable format. You can get the CHM file here (10.3 MB).

Warning

As per AGW version 0.8.0, most widgets constructors have a modified signature, taking into account the introduction of the agwStyle keyword.

description Description

AGW contains many different modules, listed below. Items labelled with an asterisk were already present in wx.lib before:

  • advancedsplash: reproduces the behaviour of wx.SplashScreen, with more advanced features like custom shapes and text animations;
  • aquabutton: this is another custom-drawn button class which approximatively mimics the behaviour of Aqua buttons on the Mac;
  • aui: a pure-Python implementation of wx.aui, with many bug fixes and new features like HUD docking and AuiNotebook tab arts;
  • balloontip: allows you to display tooltips in a balloon style window (actually a frame), similarly to the Windows XP balloon help;
  • buttonpanel (*): a panel with gradient background shading with the possibility to add buttons and controls still respecting the gradient background;
  • cubecolourdialog: an alternative implementation of wx.ColourDialog, it offers different functionalities like colour wheel and RGB cube;
  • customtreectrl (*): mimics the behaviour of wx.TreeCtrl, with almost the same base functionalities plus a bunch of enhancements and goodies;
  • flatmenu: as the name implies, it is a generic menu implementation, offering the same wx.MenuBar/wx.Menu/wx.ToolBar capabilities and much more;
  • flatnotebook (*): a full implementation of the wx.Notebook, and designed to be a drop-in replacement for wx.Notebook with enhanced capabilities;
  • floatspin: this class implements a floating point spinctrl, cabable (in theory) of handling infinite-precision floating point numbers;
  • foldpanelbar (*): a control that contains multiple panels that can be expanded or collapsed a la Windows Explorer/Outlook command bars;
  • fourwaysplitter: this is a layout manager which manages four children like four panes in a window, similar to many CAD software interfaces;
  • genericmessagedialog: it is a possible replacement for the standard wx.MessageDialog, with a fancier look and extended functionalities;
  • gradientbutton: another custom-drawn button class which mimics Windows CE mobile gradient buttons, using a tri-vertex blended gradient background;
  • hyperlink (*): this widget acts line an hyper link in a typical browser;
  • hypertreelist: a class that mimics the behaviour of wx.gizmos.TreeListCtrl, with almost the same base functionalities plus some more enhancements;
  • infobar: a transient window shown at top or bottom of its parent window to display non-critical information to the user;
  • knobctrl: a widget which lets the user select a numerical value by rotating it, like a slider with a wheel shape;
  • labelbook and FlatImageBook: these are a quasi-full implementations of wx.ListBook, with additional features;
  • multidirdialog: it represents a possible replacement for wx.DirDialog, with the additional ability of selecting multiple folders at once and a fancier look;
  • peakmeter: this widget mimics the behaviour of LED equalizers that are usually found in stereos and MP3 players;
  • persist: widgets which automatically save their state when they are destroyed and restore it when they are recreated, even during another program invocation;
  • piectrl and ProgressPie: these are simple classes that reproduce the behavior of a pie chart, in a static or progress-gauge-like way;
  • pybusyinfo: constructs a busy info window and displays a message in it: it is similar to wx.BusyInfo;
  • pycollapsiblepane: a pure Python implementation of the original wxWidgets C++ code of wx.CollapsiblePane, with customizable buttons;
  • pygauge: a generic wx.Gauge implementation, it supports the determinate mode functions as wx.Gauge;
  • pyprogress: it is similar to wx.ProgressDialog in indeterminated mode, but with a different gauge appearance and a different spinning behavior;
  • ribbon: the RibbonBar is a set of classes for writing a ribbon user interface, similar to the user interface present in recent versions of Microsoft Office;
  • rulerctrl: it implements a ruler window that can be placed on top, bottom, left or right to any wxPython widget. It is somewhat similar to the rulers you can find in text editors software;
  • shapedbutton: this class tries to fill the lack of “custom shaped” controls in wxPython. It can be used to build round buttons or elliptic buttons;
  • shortcuteditor: a widget that allows the user to customize and change keyboard shortcuts via a dialog;
  • speedmeter: this widget tries to reproduce the behavior of some car controls (but not only), by creating an “angular” control;
  • supertooltip: a class that mimics the behaviour of wx.TipWindow and generic tooltips, with many features and highly customizable;
  • thumbnailctrl: a widget that can be used to display a series of images in a “thumbnail” format; it mimics, for example, the Windows Explorer behavior when you select the “view thumbnails” option;
  • toasterbox: a cross-platform widget to make the creation of MSN-style “toaster” popups easier;
  • ultimatelistctrl: mimics the behaviour of wx.ListCtrl, with almost the same base functionalities plus some more enhancements;
  • xlsgrid: a class based on wx.grid.Grid that can be used to faithfully reproduce the appearance of a Microsoft Excel spreadsheets;
  • zoombar: a class that appoximatively mimics the behaviour of the Mac Dock, inside a wx.Panel.

stats Code Statistics

Code statistics for AGW:

Code statistics for AGW (12-March-2012)
Stat Name | Value | Relative Percentage
Total Lines Of Code (Including Demos) | 166058 | —
Total Lines Of Code (Excluding Demos) | 134417 | —
Docstring Lines | 18777 | 14.06%
Python Code Lines | 115640 | 85.94%

Other Information

Bugs and Limitations: many, patches and fixes welcome :-D

See the demos for an example of what AGW can do, and on how to use it.

Copyright: Andrea Gavana

License: Same as the version of wxPython you are using it with.

SVN for latest code: http://svn.wxwidgets.org/viewvc/wx/wxPython/3rdParty/AGW/

Mailing List: wxpython-users@lists.wxwidgets.org

My personal web page: http://xoomer.alice.it/infinity77

Please let me know if you are using AGW!

You can contact me at:

andrea.gavana@gmail.com

andrea.gavana@maerskoil.com

AGW version: 0.9.4

Last updated: 12 March 2012, 22.00 GMT

Table of Contents

  • AGW Master Index
  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • infobar
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar

indices Indices and tables

  • AGW Master Index
  • Index
  • Module Index
  • Search Page

Navigation

  • index
  • modules |
  • next |
  • Home |
  • Gallery |
  • Contents»
  • Advanced Generic Widgets
© Copyright 2012, Andrea Gavana. Created using Sphinx 1.2pre.


  • modules |
  • Home |
  • Gallery |
  • Contents»
  • Python Module Index

Python Module Index

a | b | c | f | g | h | i | k | l | m | p | r | s | t | u | x | z
 | a
 | advancedsplash
 | aquabutton
 | artmanager
- | aui
 | aui.aui_switcherdialog
 | aui.aui_utilities
 | aui.auibar
 | aui.auibook
 | aui.dockart
 | aui.framemanager
 | aui.tabart
 | b
 | balloontip
 | buttonpanel
 | c
 | cubecolourdialog
 | customtreectrl
 | f
 | flatmenu
 | flatnotebook
 | floatspin
 | fmcustomizedlg
 | foldpanelbar
 | fourwaysplitter
 | g
 | genericmessagedialog
 | gradientbutton
 | h
 | hyperlink
 | hypertreelist
 | i
 | infobar
 | k
 | knobctrl
 | l
 | labelbook
 | m
 | multidirdialog
 | p
 | peakmeter
- | persist
 | persist.persist_handlers
 | persist.persistencemanager
 | piectrl
 | pybusyinfo
 | pycollapsiblepane
 | pygauge
 | pyprogress
 | r
- | ribbon
 | ribbon.art_aui
 | ribbon.art_internal
 | ribbon.art_msw
 | ribbon.bar
 | ribbon.buttonbar
 | ribbon.control
 | ribbon.gallery
 | ribbon.page
 | ribbon.panel
 | ribbon.toolbar
 | rulerctrl
 | s
 | shapedbutton
 | shortcuteditor
 | speedmeter
 | supertooltip
 | t
 | thumbnailctrl
 | toasterbox
 | u
 | ultimatelistctrl
 | x
 | xlsgrid
 | z
 | zoombar

Navigation

  • index
  • modules |
  • Home |
  • Gallery |
  • Contents»
  • Python Module Index


AGW Master Index

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • AGW Master Index

AGW Master Index

This is the master index for Advanced Generic Widgets package (AGW). AGW provides many custom-drawn wxPython controls: some of them can be used as a replacement of the platform native controls, others are simply an addition to the already rich wxPython widgets set.

  • Libraries

    • aui
      • aui.aui_switcherdialog
        • MultiColumnListCtrl
        • SwitcherDialog
        • SwitcherItem
        • SwitcherItems
      • aui.aui_utilities
        • TabDragImage
        • aui_utilities functions
      • aui.auibar
        • AuiDefaultToolBarArt
        • AuiToolBar
        • AuiToolBarEvent
        • AuiToolBarItem
        • CommandToolBarEvent
        • ToolbarCommandCapture
      • aui.auibook
        • AuiNotebook
        • AuiNotebookEvent
        • AuiNotebookPage
        • AuiTabContainer
        • AuiTabContainerButton
        • AuiTabCtrl
        • CommandNotebookEvent
        • TabFrame
        • TabNavigatorProps
        • TabNavigatorWindow
        • TabTextCtrl
      • aui.dockart
        • AuiDefaultDockArt
        • ModernDockArt
      • aui.framemanager
        • AuiCenterDockingGuide
        • AuiDockInfo
        • AuiDockUIPart
        • AuiDockingGuide
        • AuiDockingGuideInfo
        • AuiDockingGuideWindow
        • AuiDockingHintWindow
        • AuiFloatingFrame
        • AuiManager
        • AuiManagerEvent
        • AuiManager_DCP
        • AuiPaneButton
        • AuiPaneInfo
        • AuiSingleDockingGuide
        • framemanager functions
      • aui.tabart
        • AuiCommandCapture
        • AuiDefaultTabArt
        • AuiSimpleTabArt
        • ChromeTabArt
        • FF2TabArt
        • VC71TabArt
        • VC8TabArt
    • persist
      • persist.persist_handlers
        • AUIHandler
        • AbstractHandler
        • BookHandler
        • CalendarCtrlHandler
        • CheckBoxHandler
        • CheckListBoxHandler
        • ChoiceComboHandler
        • ChoiceDialogHandler
        • CollapsiblePaneHandler
        • ColourDialogHandler
        • ColourPickerHandler
        • DatePickerHandler
        • FileDirDialogHandler
        • FileDirPickerHandler
        • FileHistoryHandler
        • FindReplaceHandler
        • FoldPanelBarHandler
        • FontDialogHandler
        • FontPickerHandler
        • ListBoxHandler
        • ListCtrlHandler
        • MediaCtrlHandler
        • MenuBarHandler
        • RadioBoxHandler
        • RadioButtonHandler
        • ScrolledWindowHandler
        • SliderHandler
        • SpinHandler
        • SplitterHandler
        • TLWHandler
        • TextCtrlHandler
        • TextEntryHandler
        • ToggleButtonHandler
        • ToolBarHandler
        • TreeCtrlHandler
        • TreeListCtrlHandler
        • TreebookHandler
        • persist_handlers functions
      • persist.persistencemanager
        • PersistenceManager
        • PersistentObject
    • ribbon
      • ribbon.art_aui
        • RibbonAUIArtProvider
        • art_aui functions
      • ribbon.art_internal
        • RibbonHSLColour
        • RibbonPageTabInfo
        • art_internal functions
      • ribbon.art_msw
        • RibbonMSWArtProvider
        • art_msw functions
      • ribbon.bar
        • RibbonBar
        • RibbonBarEvent
        • bar functions
      • ribbon.buttonbar
        • RibbonButtonBar
        • RibbonButtonBarButtonBase
        • RibbonButtonBarButtonInstance
        • RibbonButtonBarButtonSizeInfo
        • RibbonButtonBarEvent
        • RibbonButtonBarLayout
      • ribbon.control
        • RibbonControl
      • ribbon.gallery
        • RibbonGallery
        • RibbonGalleryEvent
        • RibbonGalleryItem
      • ribbon.page
        • RibbonPage
        • RibbonPageScrollButton
        • page functions
      • ribbon.panel
        • RibbonPanel
        • panel functions
      • ribbon.toolbar
        • RibbonToolBar
        • RibbonToolBarEvent
        • RibbonToolBarToolBase
        • RibbonToolBarToolGroup
        • toolbar functions

  • Standalone Widgets

  • advancedsplash
    • AdvancedSplash
  • aquabutton
    • AquaButton
    • AquaButtonEvent
    • AquaToggleButton
    • __ToggleMixin
  • artmanager
    • ArtManager
    • DCSaver
    • RendererBase
    • RendererMSOffice2007
    • RendererXP
  • balloontip
    • BalloonFrame
    • BalloonTip
  • buttonpanel
    • BPArt
    • BoxSizer
    • ButtonInfo
    • ButtonPanel
    • ButtonPanelText
    • Control
    • Separator
    • Sizer
    • StatusBarTimer
    • buttonpanel functions
  • cubecolourdialog
    • AlphaCtrl
    • BaseLineCtrl
    • BasePyControl
    • BrightCtrl
    • Colour
    • ColourPanel
    • CubeColourDialog
    • CustomPanel
    • HSVWheel
    • LineDescription
    • RGBCube
    • cubecolourdialog functions
  • customtreectrl
    • CommandTreeEvent
    • CustomTreeCtrl
    • DragImage
    • GenericTreeItem
    • TreeEditTimer
    • TreeEvent
    • TreeFindTimer
    • TreeItemAttr
    • TreeTextCtrl
    • customtreectrl functions
  • flatmenu
    • FMRenderer
    • FMRendererMSOffice2007
    • FMRendererMgr
    • FMRendererVista
    • FMRendererXP
    • FileHistory
    • FlatMenu
    • FlatMenuBar
    • FlatMenuBase
    • FlatMenuButton
    • FlatMenuEvent
    • FlatMenuItem
    • FlatMenuItemGroup
    • FlatToolbarItem
    • FocusHandler
    • MenuEntryInfo
    • MenuKbdRedirector
    • ShadowPopupWindow
    • StatusBarTimer
    • ToolBarItem
    • flatmenu functions
    • mcPopupWindow
  • flatnotebook
    • FNBDragInfo
    • FNBDropSource
    • FNBDropTarget
    • FNBRenderer
    • FNBRendererDefault
    • FNBRendererFancy
    • FNBRendererFirefox2
    • FNBRendererMgr
    • FNBRendererRibbonTabs
    • FNBRendererVC71
    • FNBRendererVC8
    • FlatNotebook
    • FlatNotebookCompatible
    • FlatNotebookDragEvent
    • FlatNotebookEvent
    • PageContainer
    • PageInfo
    • TabNavigatorWindow
    • flatnotebook functions
  • floatspin
    • FixedPoint
    • FloatSpin
    • FloatSpinEvent
    • FloatTextCtrl
    • floatspin functions
  • fmcustomizedlg
    • FMCustomizeDlg
    • FMTitlePanel
  • foldpanelbar
    • CaptionBar
    • CaptionBarEvent
    • CaptionBarStyle
    • FoldPanelBar
    • FoldPanelItem
    • FoldWindowItem
  • fourwaysplitter
    • FourWaySplitter
    • FourWaySplitterEvent
  • genericmessagedialog
    • GenericMessageDialog
    • StdDialogButtonSizer
  • gradientbutton
    • GradientButton
    • GradientButtonEvent
  • hyperlink
    • HyperLinkCtrl
    • HyperLinkEvent
  • hypertreelist
    • EditCtrl
    • EditTextCtrl
    • HyperTreeList
    • TreeListColumnInfo
    • TreeListHeaderWindow
    • TreeListItem
    • TreeListMainWindow
    • hypertreelist functions
  • infobar
    • InfoBar
    • infobar functions
  • knobctrl
    • BufferedWindow
    • KnobCtrl
    • KnobCtrlEvent
  • labelbook
    • FlatBookBase
    • FlatImageBook
    • ImageContainer
    • ImageContainerBase
    • ImageInfo
    • ImageNotebookEvent
    • LabelBook
    • LabelContainer
  • multidirdialog
    • MultiDirDialog
  • peakmeter
    • PeakMeterCtrl
    • PeakMeterData
    • peakmeter functions
  • piectrl
    • PieCtrl
    • PieCtrlLegend
    • PiePart
    • ProgressPie
  • pybusyinfo
    • PyBusyInfo
    • PyInfoFrame
  • pycollapsiblepane
    • GTKExpander
    • PyCollapsiblePane
  • pygauge
    • PyGauge
  • pyprogress
    • ProgressGauge
    • PyProgress
  • rulerctrl
    • Indicator
    • Label
    • RulerCtrl
    • RulerCtrlEvent
    • rulerctrl functions
  • shapedbutton
    • SBitmapButton
    • SBitmapTextButton
    • SBitmapTextToggleButton
    • SBitmapToggleButton
    • SButton
    • SButtonEvent
    • SToggleButton
    • shapedbutton functions
    • __SToggleMixin
  • shortcuteditor
    • ConflictDialog
    • HTMLHelpWindow
    • ListShortcut
    • Shortcut
    • ShortcutEditor
    • ShortcutEvent
    • shortcuteditor functions
  • speedmeter
    • BufferedWindow
    • SpeedMeter
  • supertooltip
    • SuperToolTip
    • ToolTipWindow
    • ToolTipWindowBase
    • supertooltip functions
  • thumbnailctrl
    • NativeImageHandler
    • PILImageHandler
    • ScrolledThumbnail
    • Thumb
    • ThumbnailCtrl
    • ThumbnailEvent
    • thumbnailctrl functions
  • toasterbox
    • ToasterBox
    • ToasterBoxWindow
  • ultimatelistctrl
    • ColWidthInfo
    • CommandListEvent
    • GeometryInfo
    • PyImageList
    • SelectionStore
    • UltimateListCtrl
    • UltimateListEvent
    • UltimateListHeaderData
    • UltimateListHeaderWindow
    • UltimateListItem
    • UltimateListItemAttr
    • UltimateListItemData
    • UltimateListLineData
    • UltimateListMainWindow
    • UltimateListRenameTimer
    • UltimateListTextCtrl
    • ultimatelistctrl functions
  • xlsgrid
    • Excel
    • TransientPopup
    • XLSBackground
    • XLSBorder
    • XLSBorderFactory
    • XLSCell
    • XLSComment
    • XLSGrid
    • XLSRenderer
    • XLSRichText
    • XLSTable
    • XLSText
    • xlsgrid functions
  • zoombar
    • ImageBar
    • ZoomBar
    • ZoomBarEvent
    • ZoomBarImage
    • zoombar functions

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • AGW Master Index


advancedsplash

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • advancedsplash

advancedsplash

AdvancedSplash tries to reproduce the behavior of wx.SplashScreen, with some enhancements.

description Description

AdvancedSplash tries to reproduce the behavior of wx.SplashScreen, but with some enhancements (in my opinion).

AdvancedSplash starts its construction from a simple frame. Then, depending on the options passed to it, it sets the frame shape accordingly to the image passed as input. AdvancedSplash behaves somewhat like wx.SplashScreen, and almost all the methods available in wx.SplashScreen are available also in this module.

usage Usage

Sample usage:

import wx
import wx.lib.agw.advancedsplash as AS

app = wx.App(0)

frame = wx.Frame(None, -1, "AdvancedSplash Test")

imagePath = "my_splash_image.png"
bitmap = wx.Bitmap(imagePath, wx.BITMAP_TYPE_PNG)
shadow = wx.WHITE

splash = AS.AdvancedSplash(frame, bitmap=bitmap, timeout=5000,
                           agwStyle=AS.AS_TIMEOUT |
                           AS.AS_CENTER_ON_PARENT |
                           AS.AS_SHADOW_BITMAP,
                           shadowcolour=shadow)

app.MainLoop()

This code snippet can be downloaded, see this example script.

Note

Some of the AGW snippets of code in the documentation use images and external files (to create bitmaps or access external data). As these files are not provided in these snippets, you should make the approriate modifications to the code to actually run it.

None of the options are strictly required (a part of the bitmap parameter). If you use the defaults you get a very simple AdvancedSplash.

settings Methods and Settings

AdvancedSplash is customizable, and in particular you can set:

  • Whether you want to mask a colour or not in your input bitmap;
  • Where to center the splash screen (on screen, on parent or nowhere);
  • Whether it is a “timeout” splashscreen or not;
  • The time after which AdvancedSplash is destroyed (if it is a timeout splashscreen);
  • The (optional) text you wish to display;
  • The font, colour and position of the displayed text (optional).

styles Window Styles

This class supports the following window styles:

Window styles for advancedsplash
Window Styles | Hex Value | Description
AS_TIMEOUT | 0x1 | AdvancedSplash will be destroyed after timeout milliseconds.
AS_NOTIMEOUT | 0x2 | AdvancedSplash can be destroyed by clicking on it, pressing a key or by explicitly call the Close() method.
AS_CENTER_ON_SCREEN | 0x4 | AdvancedSplash will be centered on screen.
AS_CENTER_ON_PARENT | 0x8 | AdvancedSplash will be centered on parent.
AS_NO_CENTER | 0x10 | AdvancedSplash will not be centered.
AS_SHADOW_BITMAP | 0x20 | If the bitmap you pass as input has no transparency, you can choose one colour that will be masked in your bitmap. the final shape of AdvancedSplash will be defined only by non-transparent (non-masked) pixels.

events Events Processing

No custom events are available for this class.

license License And Version

AdvancedSplash control is distributed under the wxPython license.

Latest revision: Andrea Gavana @ 17 Aug 2011, 15.00 GMT

Version 0.4

Module author: Andrea Gavana <andrea.gavana@gmail.com>

hierarchy Inheritance Diagram

Inheritance diagram for module: advancedsplash

Inheritance diagram of advancedsplash.AdvancedSplash

SVN Revisions

A graphical representation of the SVN commits in the last year.

Click on any date in the picture to jump to that particular revision page, containing information about committers, log messages and SVN diffs.

Revision Graph For advancedsplash

2to3 Python 3 Issues (via 2to3)

No issues have been detected by 2to3.py.

Class Summary

  • AdvancedSplash

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • infobar
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • advancedsplash


aquabutton

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • aquabutton

aquabutton

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

description Description

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

This code snippet can be downloaded, see this example script.

Note

Some of the AGW snippets of code in the documentation use images and external files (to create bitmaps or access external data). As these files are not provided in these snippets, you should make the approriate modifications to the code to actually run it.

platforms Supported Platforms

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

styles Window Styles

No particular window styles are available for this class.

events Events Processing

This class processes the following events:

Events processing for aquabutton
Event Name | Description
wx.EVT_BUTTON | Process a wx.wxEVT_COMMAND_BUTTON_CLICKED event, when the button is clicked.

license License And Version

AquaButton control is distributed under the wxPython license.

Latest Revision: Andrea Gavana @ 22 Nov 2011, 22.00 GMT

Version 0.4

Module author: Andrea Gavana <andrea.gavana@gmail.com>

hierarchy Inheritance Diagram

Inheritance diagram for module: aquabutton

Inheritance diagram of aquabutton.AquaButton, aquabutton.AquaButtonEvent, aquabutton.AquaToggleButton, aquabutton.__ToggleMixin

SVN Revisions

A graphical representation of the SVN commits in the last year.

Click on any date in the picture to jump to that particular revision page, containing information about committers, log messages and SVN diffs.

Revision Graph For aquabutton

2to3 Python 3 Issues (via 2to3)

No issues have been detected by 2to3.py.

Class Summary

  • AquaButton
  • AquaButtonEvent
  • AquaToggleButton
  • __ToggleMixin

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • infobar
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • aquabutton


artmanager

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • artmanager

artmanager

This module contains drawing routines and customizations for the AGW widgets LabelBook and FlatMenu.

Module author: Andrea Gavana <andrea.gavana@gmail.com>

hierarchy Inheritance Diagram

Inheritance diagram for module: artmanager

Inheritance diagram of artmanager.ArtManager, artmanager.DCSaver, artmanager.RendererBase, artmanager.RendererMSOffice2007, artmanager.RendererXP

SVN Revisions

A graphical representation of the SVN commits in the last year.

Click on any date in the picture to jump to that particular revision page, containing information about committers, log messages and SVN diffs.

Revision Graph For artmanager

2to3 Python 3 Issues (via 2to3)

No issues have been detected by 2to3.py.

Class Summary

  • ArtManager
  • DCSaver
  • RendererBase
  • RendererMSOffice2007
  • RendererXP

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • infobar
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • artmanager


aui library

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • aui library

aui library

AUI is an Advanced User Interface library that aims to implement “cutting-edge” interface usability and design features so developers can quickly and easily create beautiful and usable application interfaces.

vision Vision and Design Principles

AUI attempts to encapsulate the following aspects of the user interface:

  • Frame Management: Frame management provides the means to open, move and hide common controls that are needed to interact with the document, and allow these configurations to be saved into different perspectives and loaded at a later time.
  • Toolbars: Toolbars are a specialized subset of the frame management system and should behave similarly to other docked components. However, they also require additional functionality, such as “spring-loaded” rebar support, “chevron” buttons and end-user customizability.
  • Modeless Controls: Modeless controls expose a tool palette or set of options that float above the application content while allowing it to be accessed. Usually accessed by the toolbar, these controls disappear when an option is selected, but may also be “torn off” the toolbar into a floating frame of their own.
  • Look and Feel: Look and feel encompasses the way controls are drawn, both when shown statically as well as when they are being moved. This aspect of user interface design incorporates “special effects” such as transparent window dragging as well as frame animation.

AUI adheres to the following principles:

  • Use native floating frames to obtain a native look and feel for all platforms;
  • Use existing wxPython code where possible, such as sizer implementation for frame management;
  • Use standard wxPython coding conventions.

usage Usage

The following example shows a simple implementation that uses AuiManager to manage three text controls in a frame window:

import wx
import wx.lib.agw.aui as aui

class MyFrame(wx.Frame):

    def __init__(self, parent, id=-1, title="AUI Test", pos=wx.DefaultPosition,
                 size=(800, 600), style=wx.DEFAULT_FRAME_STYLE):

        wx.Frame.__init__(self, parent, id, title, pos, size, style)

        self._mgr = aui.AuiManager()

        # notify AUI which frame to use
        self._mgr.SetManagedWindow(self)

        # create several text controls
        text1 = wx.TextCtrl(self, -1, "Pane 1 - sample text",
                            wx.DefaultPosition, wx.Size(200,150),
                            wx.NO_BORDER | wx.TE_MULTILINE)

        text2 = wx.TextCtrl(self, -1, "Pane 2 - sample text",
                            wx.DefaultPosition, wx.Size(200,150),
                            wx.NO_BORDER | wx.TE_MULTILINE)

        text3 = wx.TextCtrl(self, -1, "Main content window",
                            wx.DefaultPosition, wx.Size(200,150),
                            wx.NO_BORDER | wx.TE_MULTILINE)

        # add the panes to the manager
        self._mgr.AddPane(text1, AuiPaneInfo().Left().Caption("Pane Number One"))
        self._mgr.AddPane(text2, AuiPaneInfo().Bottom().Caption("Pane Number Two"))
        self._mgr.AddPane(text3, AuiPaneInfo().CenterPane())

        # tell the manager to "commit" all the changes just made
        self._mgr.Update()

        self.Bind(wx.EVT_CLOSE, self.OnClose)

    def OnClose(self, event):

        # deinitialize the frame manager
        self._mgr.UnInit()

        self.Destroy()
        event.Skip()

# our normal wxApp-derived class, as usual

app = wx.PySimpleApp()

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

app.MainLoop()

This code snippet can be downloaded, see this example script.

Note

Some of the AGW snippets of code in the documentation use images and external files (to create bitmaps or access external data). As these files are not provided in these snippets, you should make the approriate modifications to the code to actually run it.

whatsnew What’s New

Current wxAUI Version Tracked: wxWidgets 2.9.2 (SVN HEAD)

The wxPython AUI version fixes the following bugs or implement the following missing features (the list is not exhaustive):

  • Visual Studio 2005 style docking: http://www.kirix.com/forums/viewtopic.php?f=16&t=596
  • Dock and Pane Resizing: http://www.kirix.com/forums/viewtopic.php?f=16&t=582
  • Patch concerning dock resizing: http://www.kirix.com/forums/viewtopic.php?f=16&t=610
  • Patch to effect wxAuiToolBar orientation switch: http://www.kirix.com/forums/viewtopic.php?f=16&t=641
  • AUI: Core dump when loading a perspective in wxGTK (MSW OK): http://www.kirix.com/forums/viewtopic.php?f=15&t=627
  • wxAuiNotebook reordered AdvanceSelection(): http://www.kirix.com/forums/viewtopic.php?f=16&t=617
  • Vertical Toolbar Docking Issue: http://www.kirix.com/forums/viewtopic.php?f=16&t=181
  • Patch to show the resize hint on mouse-down in aui: http://trac.wxwidgets.org/ticket/9612
  • The Left/Right and Top/Bottom Docks over draw each other: http://trac.wxwidgets.org/ticket/3516
  • MinSize() not honoured: http://trac.wxwidgets.org/ticket/3562
  • Layout problem with wxAUI: http://trac.wxwidgets.org/ticket/3597
  • Resizing children ignores current window size: http://trac.wxwidgets.org/ticket/3908
  • Resizing panes under Vista does not repaint background: http://trac.wxwidgets.org/ticket/4325
  • Resize sash resizes in response to click: http://trac.wxwidgets.org/ticket/4547
  • “Illegal” resizing of the AuiPane? (wxPython): http://trac.wxwidgets.org/ticket/4599
  • Floating wxAUIPane Resize Event doesn’t update its position: http://trac.wxwidgets.org/ticket/9773
  • Don’t hide floating panels when we maximize some other panel: http://trac.wxwidgets.org/ticket/4066
  • wxAUINotebook incorrect ALLOW_ACTIVE_PANE handling: http://trac.wxwidgets.org/ticket/4361
  • Page changing veto doesn’t work, (patch supplied): http://trac.wxwidgets.org/ticket/4518
  • Show and DoShow are mixed around in wxAuiMDIChildFrame: http://trac.wxwidgets.org/ticket/4567
  • wxAuiManager & wxToolBar - ToolBar Of Size Zero: http://trac.wxwidgets.org/ticket/9724
  • wxAuiNotebook doesn’t behave properly like a container as far as...: http://trac.wxwidgets.org/ticket/9911
  • Serious layout bugs in wxAUI: http://trac.wxwidgets.org/ticket/10620
  • wAuiDefaultTabArt::Clone() should just use copy contructor: http://trac.wxwidgets.org/ticket/11388
  • Drop down button for check tool on wxAuiToolbar: http://trac.wxwidgets.org/ticket/11139

Plus the following features:

  • AuiManager:
    1. Implementation of a simple minimize pane system: Clicking on this minimize button causes a new AuiToolBar to be created and added to the frame manager, (currently the implementation is such that panes at West will have a toolbar at the right, panes at South will have toolbars at the bottom etc...) and the pane is hidden in the manager. Clicking on the restore button on the newly created toolbar will result in the toolbar being removed and the original pane being restored;
    2. Panes can be docked on top of each other to form AuiNotebooks; AuiNotebooks tabs can be torn off to create floating panes;
    3. On Windows XP, use the nice sash drawing provided by XP while dragging the sash;
    4. Possibility to set an icon on docked panes;
    5. Possibility to draw a sash visual grip, for enhanced visualization of sashes;
    6. Implementation of a native docking art (ModernDockArt). Windows XP only, requires Mark Hammond’s pywin32 package (winxptheme);
    7. Possibility to set a transparency for floating panes (a la Paint .NET);
    8. Snapping the main frame to the screen in any positin specified by horizontal and vertical alignments;
    9. Snapping floating panes on left/right/top/bottom or any combination of directions, a la Winamp;
    10. “Fly-out” floating panes, i.e. panes which show themselves only when the mouse hover them;
    11. Ability to set custom bitmaps for pane buttons (close, maximize, etc...);
    12. Implementation of the style AUI_MGR_ANIMATE_FRAMES, which fade-out floating panes when they are closed (all platforms which support frames transparency) and show a moving rectangle when they are docked and minimized (Windows < Vista and GTK only);
    13. A pane switcher dialog is available to cycle through existing AUI panes;
    14. Some flags which allow to choose the orientation and the position of the minimized panes;
    15. The functions [Get]MinimizeMode() in AuiPaneInfo which allow to set/get the flags described above;
    16. Events like EVT_AUI_PANE_DOCKING, EVT_AUI_PANE_DOCKED, EVT_AUI_PANE_FLOATING and EVT_AUI_PANE_FLOATED are available for all panes except toolbar panes;
    17. Implementation of the RequestUserAttention method for panes;
    18. Ability to show the caption bar of docked panes on the left instead of on the top (with caption text rotated by 90 degrees then). This is similar to what wxDockIt did. To enable this feature on any given pane, simply call CaptionVisible(True, left=True);
    19. New Aero-style docking guides: you can enable them by using the AuiManager style AUI_MGR_AERO_DOCKING_GUIDES;
    20. A slide-in/slide-out preview of minimized panes can be seen by enabling the AuiManager style AUI_MGR_PREVIEW_MINIMIZED_PANES and by hovering with the mouse on the minimized pane toolbar tool;
    21. New Whidbey-style docking guides: you can enable them by using the AuiManager style AUI_MGR_WHIDBEY_DOCKING_GUIDES;
    22. Native of custom-drawn mini frames can be used as floating panes, depending on the AUI_MGR_USE_NATIVE_MINIFRAMES style;
    23. A “smooth docking effect” can be obtained by using the AUI_MGR_SMOOTH_DOCKING style (similar to PyQT docking style).

  • AuiNotebook:
    1. Implementation of the style AUI_NB_HIDE_ON_SINGLE_TAB, a la wx.lib.agw.flatnotebook;
    2. Implementation of the style AUI_NB_SMART_TABS, a la wx.lib.agw.flatnotebook;
    3. Implementation of the style AUI_NB_USE_IMAGES_DROPDOWN, which allows to show tab images on the tab dropdown menu instead of bare check menu items (a la wx.lib.agw.flatnotebook);
    4. 6 different tab arts are available, namely:
      1. Default “glossy” theme (as in wx.aui.AuiNotebook)
      2. Simple theme (as in wx.aui.AuiNotebook)
      3. Firefox 2 theme
      4. Visual Studio 2003 theme (VC71)
      5. Visual Studio 2005 theme (VC81)
      6. Google Chrome theme
    5. Enabling/disabling tabs;
    6. Setting the colour of the tab’s text;
    7. Implementation of the style AUI_NB_CLOSE_ON_TAB_LEFT, which draws the tab close button on the left instead of on the right (a la Camino browser);
    8. Ability to save and load perspectives in AuiNotebook (experimental);
    9. Possibility to add custom buttons in the AuiNotebook tab area;
    10. Implementation of the style AUI_NB_TAB_FLOAT, which allows the floating of single tabs. Known limitation: when the notebook is more or less full screen, tabs cannot be dragged far enough outside of the notebook to become floating pages;
    11. Implementation of the style AUI_NB_DRAW_DND_TAB (on by default), which draws an image representation of a tab while dragging;
    12. Implementation of the AuiNotebook unsplit functionality, which unsplit a splitted AuiNotebook when double-clicking on a sash;
    13. Possibility to hide all the tabs by calling HideAllTAbs;
    14. wxPython controls can now be added inside page tabs by calling AddControlToPage, and they can be removed by calling RemoveControlFromPage;
    15. Possibility to preview all the pages in a AuiNotebook (as thumbnails) by using the NotebookPreview method of AuiNotebook;
    16. Tab labels can be edited by calling the SetRenamable method on a AuiNotebook page;
    17. Support for multi-lines tab labels in AuiNotebook;
    18. Support for setting minimum and maximum tab widths for fixed width tabs;
    19. Implementation of the style AUI_NB_ORDER_BY_ACCESS, which orders the tabs by last access time inside the Tab Navigator dialog;
    20. Implementation of the style AUI_NB_NO_TAB_FOCUS, allowing the developer not to draw the tab focus rectangle on tne AuiNotebook tabs.

  • AuiToolBar:
    1. AUI_TB_PLAIN_BACKGROUND style that allows to easy setup a plain background to the AUI toolbar, without the need to override drawing methods. This style contrasts with the default behaviour of the wx.aui.AuiToolBar that draws a background gradient and this break the window design when putting it within a control that has margin between the borders and the toolbar (example: put wx.aui.AuiToolBar within a wx.StaticBoxSizer that has a plain background);
    2. AuiToolBar allow item alignment: http://trac.wxwidgets.org/ticket/10174;
    3. AUIToolBar DrawButton() improvement: http://trac.wxwidgets.org/ticket/10303;
    4. AuiToolBar automatically assign new id for tools: http://trac.wxwidgets.org/ticket/10173;
    5. AuiToolBar Allow right-click on any kind of button: http://trac.wxwidgets.org/ticket/10079;
    6. AuiToolBar idle update only when visible: http://trac.wxwidgets.org/ticket/10075;
    7. Ability of creating AuiToolBar tools with [counter]clockwise rotation. This allows to propose a variant of the minimizing functionality with a rotated button which keeps the caption of the pane as label;
    8. Allow setting the alignment of all tools in a toolbar that is expanded;
    9. Implementation of the AUI_MINIMIZE_POS_TOOLBAR flag, which allows to minimize a pane inside an existing toolbar. Limitation: if the minimized icon in the toolbar ends up in the overflowing items (i.e., a menu is needed to show the icon), this style will not work.

todos TODOs

  • Documentation, documentation and documentation;
  • Fix tabmdi.AuiMDIParentFrame and friends, they do not work correctly at present;
  • Allow specification of CaptionLeft() to AuiPaneInfo to show the caption bar of docked panes on the left instead of on the top (with caption text rotated by 90 degrees then). This is similar to what wxDockIt did - DONE;
  • Make developer-created AuiNotebooks and automatic (framemanager-created) AuiNotebooks behave the same way (undocking of tabs) - DONE, to some extent;
  • Find a way to dock panes in already floating panes (AuiFloatingFrames), as they already have their own AuiManager;
  • Add more gripper styles (see, i.e., PlusDock 4.0);
  • Add an “AutoHide” feature to docked panes, similar to fly-out floating panes (see, i.e., PlusDock 4.0);
  • Add events for panes when they are about to float or to be docked (something like EVT_AUI_PANE_FLOATING/ED and EVT_AUI_PANE_DOCKING/ED) - DONE, to some extent;
  • Implement the 4-ways splitter behaviour for horizontal and vertical sashes if they intersect;
  • Extend tabart.py with more aui tab arts;
  • Implement AUI_NB_LEFT and AUI_NB_RIGHT tab locations in AuiNotebook;
  • Move AuiDefaultToolBarArt into a separate module (as with tabart.py and dockart.py) and provide more arts for toolbars (maybe from wx.lib.agw.flatmenu?)
  • Support multiple-rows/multiple columns toolbars;
  • Integrate as much as possible with wx.lib.agw.flatmenu, from dropdown menus in AuiNotebook to toolbars and menu positioning;
  • Possibly handle minimization of panes in a different way (or provide an option to switch to another way of minimizing panes);
  • Clean up/speed up the code, especially time-consuming for-loops;
  • Possibly integrate wxPyRibbon (still on development), at least on Windows.

license License And Version

AUI library is distributed under the wxPython license.

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

Version 1.3.

Module author: Andrea Gavana <andrea.gavana@gmail.com>

hierarchy Inheritance Diagram

Inheritance diagram for library: aui

Inheritance diagram of aui.aui_switcherdialog, aui.aui_utilities, aui.auibar, aui.auibook, aui.dockart, aui.framemanager, aui.tabart

Module Summary

  • aui_switcherdialog
  • aui_utilities
  • auibar
  • auibook
  • dockart
  • framemanager
  • tabart

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • infobar
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • aui library


balloontip

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • balloontip

balloontip

BalloonTip is a class that allows you to display tooltips in a balloon style window.

description Description

BalloonTip is a class that allows you to display tooltips in a balloon style window (actually a frame), similarly to the windows XP balloon help. There is also an arrow that points to the center of the control designed as a “target” for the BalloonTip.

What it can do:

  • Set the balloon shape as a rectangle or a rounded rectangle;
  • Set an icon to the top-left of the BalloonTip frame;
  • Set a title at the top of the BalloonTip frame;
  • Automatic “best” placement of BalloonTip frame depending on the target control/window position;
  • Runtime customization of title/tip fonts and foreground colours;
  • Runtime change of BalloonTip frame shape;
  • Set the balloon background colour;
  • Possibility to set the delay after which the BalloonTip is displayed;
  • Possibility to set the delay after which the BalloonTip is destroyed;
  • Three different behaviors for the BalloonTip window (regardless the delay destruction time set):
    1. Destroy by leave: the BalloonTip is destroyed when the mouse leaves the target control/window;
    2. Destroy by click: the BalloonTip is destroyed when you click on any area of the target control/window;
    3. Destroy by button: the BalloonTip is destroyed when you click on the top-right close button;
  • Possibility to enable/disable globally the BalloonTip on you application;
  • Set the BalloonTip also for the taskbar icon.

usage Usage

Usage example:

import wx
import wx.lib.agw.balloontip as BT

class MyFrame(wx.Frame):

    def __init__(self, parent):

        wx.Frame.__init(self, parent, -1, "BalloonTip Demo")

        panel = wx.Panel(self)

        # Let's suppose that in your application you have a wx.TextCtrl defined as:
        mytextctrl = wx.TextCtrl(panel, -1, "I am a textctrl", pos=(100, 100))

        # You can define your BalloonTip as follows:
        tipballoon = BT.BalloonTip(topicon=None, toptitle="textctrl",
                                   message="this is a textctrl",
                                   shape=BT.BT_ROUNDED,
                                   tipstyle=BT.BT_LEAVE)

        # Set the BalloonTip target
        tipballoon.SetTarget(mytextctrl)
        # Set the BalloonTip background colour
        tipballoon.SetBalloonColour(wx.WHITE)
        # Set the font for the balloon title
        tipballoon.SetTitleFont(wx.Font(9, wx.SWISS, wx.NORMAL, wx.BOLD, False))
        # Set the colour for the balloon title
        tipballoon.SetTitleColour(wx.BLACK)
        # Leave the message font as default
        tipballoon.SetMessageFont()
        # Set the message (tip) foreground colour
        tipballoon.SetMessageColour(wx.LIGHT_GREY)
        # Set the start delay for the BalloonTip
        tipballoon.SetStartDelay(1000)
        # Set the time after which the BalloonTip is destroyed
        tipballoon.SetEndDelay(3000)

# our normal wxApp-derived class, as usual

app = wx.PySimpleApp()

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

app.MainLoop()

This code snippet can be downloaded, see this example script.

Note

Some of the AGW snippets of code in the documentation use images and external files (to create bitmaps or access external data). As these files are not provided in these snippets, you should make the approriate modifications to the code to actually run it.

styles Window Styles

This class supports the following window styles:

Window styles for balloontip
Window Styles | Hex Value | Description
BT_ROUNDED | 0x1 | BalloonTip will have a rounded rectangular shape.
BT_RECTANGLE | 0x2 | BalloonTip will have a rectangular shape.
BT_LEAVE | 0x3 | BalloonTip will be destroyed when the user moves the mouse outside the target window.
BT_CLICK | 0x4 | BalloonTip will be destroyed when the user click on BalloonTip.
BT_BUTTON | 0x5 | BalloonTip will be destroyed when the user click on the close button.

events Events Processing

No custom events are available for this class.

license License And Version

BalloonTip is distributed under the wxPython license.

Latest revision: Andrea Gavana @ 17 Aug 2011, 15.00 GMT

Version 0.2

Module author: Andrea Gavana <andrea.gavana@gmail.com>

hierarchy Inheritance Diagram

Inheritance diagram for module: balloontip

Inheritance diagram of balloontip.BalloonFrame, balloontip.BalloonTip

SVN Revisions

A graphical representation of the SVN commits in the last year.

Click on any date in the picture to jump to that particular revision page, containing information about committers, log messages and SVN diffs.

Revision Graph For balloontip

2to3 Python 3 Issues (via 2to3)

No issues have been detected by 2to3.py.

Class Summary

  • BalloonFrame
  • BalloonTip

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • infobar
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • balloontip


buttonpanel

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • buttonpanel

buttonpanel

A custom panel class with gradient background shading with the possibility to add buttons and controls still respecting the gradient background.

description Description

With ButtonPanel class you have a panel with gradient colouring on it and with the possibility to place some buttons on it. Using a standard panel with normal wx.Buttons leads to an ugly result: the buttons are placed correctly on the panel - but with grey area around them. Gradient colouring is kept behind the images - this was achieved due to the PNG format and the transparency of the bitmaps.

The image are functioning like a buttons and can be caught in your code using the usual:

self.Bind(wx.EVT_BUTTON, self.OnButton)

method.

The control is generic, and support theming (well, I tested it under Windows with the three defauls themes: grey, blue, silver and the classic look).

usage Usage

ButtonPanel supports 4 alignments: left, right, top, bottom, which have a different meaning and behavior with respect to wx.Toolbar. The easiest thing is to try the demo to understand, but I’ll try to explain how it works.

CASE 1: ButtonPanel has a main caption text.

  • Left alignment means ButtonPanel is horizontal, with the text aligned to the left. When you shrink the demo frame, if there is not enough room for all the controls to be shown, the controls closest to the text are hidden;
  • Right alignment means ButtonPanel is horizontal, with the text aligned to the right. Item layout as above;
  • Top alignment means ButtonPanel is vertical, with the text aligned to the top. Item layout as above;
  • Bottom alignment means ButtonPanel is vertical, with the text aligned to the bottom. Item layout as above.

CASE 2: ButtonPanel has no main caption text.

  • In this case, left and right alignment are the same (as top and bottom are the same), but the layout strategy changes: now if there is not enough room for all the controls to be shown, the last added items are hidden (“last” means on the far right for an horizontal ButtonPanel and far bottom for a vertical ButtonPanel).

Usage example:

import wx
import wx.lib.agw.buttonpanel as BP

class MyFrame(wx.Frame):

    def __init__(self, parent, id=-1, title="ButtonPanel", pos=wx.DefaultPosition,
                 size=(800, 600), style=wx.DEFAULT_FRAME_STYLE):

        wx.Frame.__init__(self, parent, id, title, pos, size, style)

        mainPanel = wx.Panel(self, -1)
        self.logtext = wx.TextCtrl(mainPanel, -1, "", style=wx.TE_MULTILINE)

        vSizer = wx.BoxSizer(wx.VERTICAL)
        mainPanel.SetSizer(vSizer)

        titleBar = BP.ButtonPanel(mainPanel, -1, "A Simple Test & Demo")

        btn1 = BP.ButtonInfo(titleBar, wx.NewId(), wx.Bitmap("png4.png", wx.BITMAP_TYPE_PNG))
        titleBar.AddButton(btn1)
        self.Bind(wx.EVT_BUTTON, self.OnButton, btn1)

        btn2 = BP.ButtonInfo(titleBar, wx.NewId(), wx.Bitmap("png3.png", wx.BITMAP_TYPE_PNG))
        titleBar.AddButton(btn2)
        self.Bind(wx.EVT_BUTTON, self.OnButton, btn2)

        btn3 = BP.ButtonInfo(titleBar, wx.NewId(), wx.Bitmap("png2.png", wx.BITMAP_TYPE_PNG))
        titleBar.AddButton(btn3)
        self.Bind(wx.EVT_BUTTON, self.OnButton, btn3)

        btn4 = BP.ButtonInfo(titleBar, wx.NewId(), wx.Bitmap("png1.png", wx.BITMAP_TYPE_PNG))
        titleBar.AddButton(btn4)
        self.Bind(wx.EVT_BUTTON, self.OnButton, btn4)

        vSizer.Add(titleBar, 0, wx.EXPAND)
        vSizer.Add((20, 20))
        vSizer.Add(self.logtext, 1, wx.EXPAND|wx.ALL, 5)

        titleBar.DoLayout()
        vSizer.Layout()

    def OnButton(self, event):
        ''' Handler for the ``wx.EVT_BUTTON`` event. '''

        obj = event.GetEventObject()

        # This will print the button label
        print obj.GetText()

# our normal wxApp-derived class, as usual

app = wx.PySimpleApp()

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

app.MainLoop()

This code snippet can be downloaded, see this example script.

Note

Some of the AGW snippets of code in the documentation use images and external files (to create bitmaps or access external data). As these files are not provided in these snippets, you should make the approriate modifications to the code to actually run it.

styles Window Styles

This class supports the following window styles:

Window styles for buttonpanel
Window Styles | Hex Value | Description
BP_DEFAULT_STYLE | 0x1 | ButtonPanel has a plain solid background.
BP_USE_GRADIENT | 0x2 | ButtonPanel has a gradient shading background.

events Events Processing

This class processes the following events:

Events processing for buttonpanel
Event Name | Description
wx.EVT_BUTTON | Process a wx.wxEVT_COMMAND_BUTTON_CLICKED event, when a button is clicked.

license License And Version

ButtonPanel is distributed under the wxPython license.

Latest Revision: Andrea Gavana @ 17 Aug 2011, 15.00 GMT

Version 0.6.

Module author: Andrea Gavana <andrea.gavana@gmail.com>

hierarchy Inheritance Diagram

Inheritance diagram for module: buttonpanel

Inheritance diagram of buttonpanel.BPArt, buttonpanel.BoxSizer, buttonpanel.ButtonInfo, buttonpanel.ButtonPanel, buttonpanel.ButtonPanelText, buttonpanel.Control, buttonpanel.Separator, buttonpanel.Sizer, buttonpanel.StatusBarTimer

SVN Revisions

A graphical representation of the SVN commits in the last year.

Click on any date in the picture to jump to that particular revision page, containing information about committers, log messages and SVN diffs.

Revision Graph For buttonpanel

2to3 Python 3 Issues (via 2to3)

No issues have been detected by 2to3.py.

Function Summary

  • BrightenColour
  • MakeDisabledBitmap

Class Summary

  • BPArt
  • BoxSizer
  • ButtonInfo
  • ButtonPanel
  • ButtonPanelText
  • Control
  • Separator
  • Sizer
  • StatusBarTimer

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • infobar
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • buttonpanel


cubecolourdialog

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • cubecolourdialog

cubecolourdialog

CubeColourDialog is an alternative implementation of wx.ColourDialog.

description Description

The CubeColourDialog is an alternative implementation of wx.ColourDialog, and it offers different functionalities with respect to the default wxPython one. It can be used as a replacement of wx.ColourDialog with exactly the same syntax and methods.

Some features:

  • RGB components may be controlled using spin controls or with mouse gestures on a 3D RGB cube, with the 3 components laying on the X, Y, Z axes;
  • HSB components may be controlled using spin controls or with mouse gestures on a 2D colour wheel;
  • Brightness has its own vertical slider to play with;
  • The colour alpha channel can be controlled using another vertical slider, or via spin control;
  • The colour alpha channel controls can be completely hidden at startup or the choice to use the alpha channel can be left to the user while playing with the dialog, via a simple wx.CheckBox;
  • The “old colour” and “new colour” are displayed in two small custom panel, which support alpha transparency and texture;
  • CubeColourDialog displays also the HTML colour code in hexadecimal format;
  • When available, a corresponding “Web Safe” colour is generated using a 500 web colours “database” (a dictionary inside the widget source code). Web Safe colours are recognized by all the browsers;
  • When available, a corresponding “HTML name” for the selected colour is displayed, by using the same 500 web colours “database”;
  • When available, a corresponding “Microsoft Access Code” for the selected colour is displayed, by using the same 500 web colours “database”.

And much more.

usage Usage

Usage example:

import wx
import wx.lib.agw.cubecolourdialog as CCD

# Our normal wxApp-derived class, as usual
app = wx.App(0)

colourData = wx.ColourData()
dlg = CCD.CubeColourDialog(None, colourData)

if dlg.ShowModal() == wx.ID_OK:

    # If the user selected OK, then the dialog's wx.ColourData will
    # contain valid information. Fetch the data ...
    colourData = dlg.GetColourData()
    h, s, v, a = dlg.GetHSVAColour()

    # ... then do something with it. The actual colour data will be
    # returned as a three-tuple (r, g, b) in this particular case.
    colour = colourData.GetColour()
    r, g, b, alpha = colour.Red(), colour.Green(), colour.Blue(), colour.Alpha()
    print "You selected (RGBA): %d, %d, %d, %d"%(r, g, b, alpha)
    print "You selected (HSVA): %d, %d, %d, %d"%(h, s, v, a)

# Once the dialog is destroyed, Mr. wx.ColourData is no longer your
# friend. Don't use it again!
dlg.Destroy()

app.MainLoop()

This code snippet can be downloaded, see this example script.

Note

Some of the AGW snippets of code in the documentation use images and external files (to create bitmaps or access external data). As these files are not provided in these snippets, you should make the approriate modifications to the code to actually run it.

styles Window Styles

This class supports the following window styles:

Window styles for cubecolourdialog
Window Styles | Hex Value | Description
CCD_SHOW_ALPHA | 0x1 | Show the widget used to control colour alpha channels in CubeColourDialog.

events Events Processing

No custom events are available for this class.

license License And Version

CubeColourDialog is distributed under the wxPython license.

Latest Revision: Andrea Gavana @ 26 Feb 2012, 15.00 GMT

Version 0.4.

Module author: Andrea Gavana <andrea.gavana@gmail.com>

hierarchy Inheritance Diagram

Inheritance diagram for module: cubecolourdialog

SVN Revisions

A graphical representation of the SVN commits in the last year.

Click on any date in the picture to jump to that particular revision page, containing information about committers, log messages and SVN diffs.

Revision Graph For cubecolourdialog

2to3 Python 3 Issues (via 2to3)

No issues have been detected by 2to3.py.

Function Summary

  • AngleFromPoint
  • Distance
  • DrawCheckerBoard
  • FindC
  • Intersection
  • PointOnLine
  • PtFromAngle
  • RestoreOldDC
  • Slope
  • deg2rad
  • rad2deg
  • rgb2html
  • scaletomax
  • toscale

Class Summary

  • AlphaCtrl
  • BaseLineCtrl
  • BasePyControl
  • BrightCtrl
  • Colour
  • ColourPanel
  • CubeColourDialog
  • CustomPanel
  • HSVWheel
  • LineDescription
  • RGBCube

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • infobar
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • cubecolourdialog


customtreectrl

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • customtreectrl

customtreectrl

CustomTreeCtrl is a class that mimics the behaviour of wx.TreeCtrl, with some more enhancements.

description Description

CustomTreeCtrl is a class that mimics the behaviour of wx.TreeCtrl, with almost the same base functionalities plus some more enhancements. This class does not rely on the native control, as it is a full owner-drawn tree control. Apart of the base functionalities of CustomTreeCtrl (described below), in addition to the standard wx.TreeCtrl behaviour this class supports:

  • CheckBox-type items: checkboxes are easy to handle, just selected or unselected state with no particular issues in handling the item’s children;
  • Added support for 3-state value checkbox items;
  • RadioButton-type items: since I elected to put radiobuttons in CustomTreeCtrl, I needed some way to handle them, that made sense. So, I used the following approach:
    • All peer-nodes that are radiobuttons will be mutually exclusive. In other words, only one of a set of radiobuttons that share a common parent can be checked at once. If a radiobutton node becomes checked, then all of its peer radiobuttons must be unchecked.
    • If a radiobutton node becomes unchecked, then all of its child nodes will become inactive.
  • Hyperlink-type items: they look like an hyperlink, with the proper mouse cursor on hovering;
  • Multiline text items (note: to add a newline character in a multiline item, press Shift + Enter as the Enter key alone is consumed by CustomTreeCtrl to finish the editing and Ctrl + Enter is consumed by the platform for tab navigation);
  • Enabling/disabling items (together with their plain or grayed out icons);
  • Whatever non-toplevel widget can be attached next to an item;
  • Possibility to horizontally align the widgets attached to tree items on the same tree level.
  • Possibility to align the widgets attached to tree items to the rightmost edge of CustomTreeCtrl;
  • Default selection style, gradient (horizontal/vertical) selection style and Windows Vista selection style;
  • Customized drag and drop images built on the fly;
  • Setting the CustomTreeCtrl item buttons to a personalized imagelist;
  • Setting the CustomTreeCtrl check/radio item icons to a personalized imagelist;
  • Changing the style of the lines that connect the items (in terms of wx.Pen styles);
  • Using an image as a CustomTreeCtrl background (currently only in “tile” mode);
  • Adding images to any item in the leftmost area of the CustomTreeCtrl client window.
  • Separator-type items which are simply visual indicators that are meant to set apart or divide tree items, with the following caveats:
    • Separator items should not have children, labels, data or an associated window;
    • You can change the color of individual separators by using SetItemTextColour, or you can use SetSeparatorColour to change the color of all separators. The default separator colour is that returned by wx.SystemSettings.GetColour(wx.SYS_COLOUR_GRAYTEXT);
    • Separators can be selected just like any other tree item;
    • Separators cannot have text;
    • Separators cannot have children;
    • Separators cannot be edited via the EVT_TREE_BEGIN_LABEL_EDIT event.
  • Ellipsization of long items when the horizontal space is low, via the TR_ELLIPSIZE_LONG_ITEMS style (New in version 0.9.3);
  • Tooltips on long items when the horizontal space is low, via the TR_TOOLTIP_ON_LONG_ITEMS style (New in version 0.9.3).

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

base Base Functionalities

CustomTreeCtrl supports all the wx.TreeCtrl styles, except:

  • TR_EXTENDED: supports for this style is on the todo list (am I sure of this?).

Plus it has 3 more styles to handle checkbox-type items:

  • TR_AUTO_CHECK_CHILD: automatically checks/unchecks the item children;
  • TR_AUTO_CHECK_PARENT: automatically checks/unchecks the item parent;
  • TR_AUTO_TOGGLE_CHILD: automatically toggles the item children.

And two styles you can use to force the horizontal alignment of all the widgets attached to the tree items:

  • TR_ALIGN_WINDOWS: aligns horizontally the windows belonging to the item on the same tree level.
  • TR_ALIGN_WINDOWS_RIGHT: aligns to the rightmost position the windows belonging to the item on the same tree level.

And two styles related to long items (with a lot of text in them), which can be ellipsized and/or highlighted with a tooltip:

  • TR_ELLIPSIZE_LONG_ITEMS: ellipsizes long items when the horizontal space for CustomTreeCtrl is low (New in version 0.9.3);
  • TR_TOOLTIP_ON_LONG_ITEMS: shows tooltips on long items when the horizontal space for CustomTreeCtrl is low (New in version 0.9.3);.

All the methods available in wx.TreeCtrl are also available in CustomTreeCtrl.

usage Usage

Usage example:

import wx
import wx.lib.agw.customtreectrl as CT

class MyFrame(wx.Frame):

    def __init__(self, parent):

        wx.Frame.__init(self, parent, -1, "CustomTreeCtrl Demo")

        # Create a CustomTreeCtrl instance
        custom_tree = CT.CustomTreeCtrl(self, agwStyle=wx.TR_DEFAULT_STYLE)

        # Add a root node to it
        root = custom_tree.AddRoot("The Root Item")

        # Create an image list to add icons next to an item
        il = wx.ImageList(16, 16)
        fldridx     = il.Add(wx.ArtProvider_GetBitmap(wx.ART_FOLDER,      wx.ART_OTHER, 16))
        fldropenidx = il.Add(wx.ArtProvider_GetBitmap(wx.ART_FILE_OPEN,   wx.ART_OTHER, 16))
        fileidx     = il.Add(wx.ArtProvider_GetBitmap(wx.ART_NORMAL_FILE, wx.ART_OTHER, 16))

        custom_tree.SetImageList(il)

        custom_tree.SetItemImage(root, fldridx, wx.TreeItemIcon_Normal)
        custom_tree.SetItemImage(root, fldropenidx, wx.TreeItemIcon_Expanded)

        for x in range(15):
            child = custom_tree.AppendItem(root, "Item %d" % x)
            custom_tree.SetItemImage(child, fldridx, wx.TreeItemIcon_Normal)
            custom_tree.SetItemImage(child, fldropenidx, wx.TreeItemIcon_Expanded)

            for y in range(5):
                last = custom_tree.AppendItem(child, "item %d-%s" % (x, chr(ord("a")+y)))
                custom_tree.SetItemImage(last, fldridx, wx.TreeItemIcon_Normal)
                custom_tree.SetItemImage(last, fldropenidx, wx.TreeItemIcon_Expanded)

                for z in range(5):
                    item = custom_tree.AppendItem(last,  "item %d-%s-%d" % (x, chr(ord("a")+y), z))
                    custom_tree.SetItemImage(item, fileidx, wx.TreeItemIcon_Normal)
                    custom_tree.SetItemImage(item, smileidx, wx.TreeItemIcon_Selected)

        custom_tree.Expand(self.root)

# our normal wxApp-derived class, as usual

app = wx.PySimpleApp()

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

app.MainLoop()

This code snippet can be downloaded, see this example script.

Note

Some of the AGW snippets of code in the documentation use images and external files (to create bitmaps or access external data). As these files are not provided in these snippets, you should make the approriate modifications to the code to actually run it.

events Events

All the events supported by wx.TreeCtrl are also available in CustomTreeCtrl, with a few exceptions:

  • EVT_TREE_GET_INFO (don’t know what this means);
  • EVT_TREE_SET_INFO (don’t know what this means);
  • EVT_TREE_ITEM_MIDDLE_CLICK (not implemented, but easy to add);
  • EVT_TREE_STATE_IMAGE_CLICK (no need for that, look at the checking events below).

Plus, CustomTreeCtrl supports the events related to the checkbutton-type items:

  • EVT_TREE_ITEM_CHECKING: an item is being checked;
  • EVT_TREE_ITEM_CHECKED: an item has been checked.

And to hyperlink-type items:

  • EVT_TREE_ITEM_HYPERLINK: an hyperlink item has been clicked (this event is sent after the EVT_TREE_SEL_CHANGED event).

platforms Supported Platforms

CustomTreeCtrl has been tested on the following platforms:
  • Windows (Windows XP);
  • GTK (Thanks to Michele Petrazzo);
  • Mac OS (Thanks to John Jackson).

styles Window Styles

This class supports the following window styles:

Window styles for customtreectrl
Window Styles | Hex Value | Description
TR_NO_BUTTONS | 0x0 | For convenience to document that no buttons are to be drawn.
TR_SINGLE | 0x0 | For convenience to document that only one item may be selected at a time. Selecting another item causes the current selection, if any, to be deselected. This is the default.
TR_HAS_BUTTONS | 0x1 | Use this style to show + and - buttons to the left of parent items.
TR_NO_LINES | 0x4 | Use this style to hide vertical level connectors.
TR_LINES_AT_ROOT | 0x8 | Use this style to show lines between root nodes. Only applicable if TR_HIDE_ROOT is set and TR_NO_LINES is not set.
TR_DEFAULT_STYLE | 0x9 | The set of flags that are closest to the defaults for the native control for a particular toolkit.
TR_TWIST_BUTTONS | 0x10 | Use old Mac-twist style buttons.
TR_MULTIPLE | 0x20 | Use this style to allow a range of items to be selected. If a second range is selected, the current range, if any, is deselected.
TR_EXTENDED | 0x40 | Use this style to allow disjoint items to be selected. (Only partially implemented; may not work in all cases).
TR_HAS_VARIABLE_ROW_HEIGHT | 0x80 | Use this style to cause row heights to be just big enough to fit the content. If not set, all rows use the largest row height. The default is that this flag is unset.
TR_EDIT_LABELS | 0x200 | Use this style if you wish the user to be able to edit labels in the tree control.
TR_ROW_LINES | 0x400 | Use this style to draw a contrasting border between displayed rows.
TR_HIDE_ROOT | 0x800 | Use this style to suppress the display of the root node, effectively causing the first-level nodes to appear as a series of root nodes.
TR_FULL_ROW_HIGHLIGHT | 0x2000 | Use this style to have the background colour and the selection highlight extend over the entire horizontal row of the tree control window.
TR_AUTO_CHECK_CHILD | 0x4000 | Only meaningful foe checkbox-type items: when a parent item is checked/unchecked its children are checked/unchecked as well.
TR_AUTO_TOGGLE_CHILD | 0x8000 | Only meaningful foe checkbox-type items: when a parent item is checked/unchecked its children are toggled accordingly.
TR_AUTO_CHECK_PARENT | 0x10000 | Only meaningful foe checkbox-type items: when a child item is checked/unchecked its parent item is checked/unchecked as well.
TR_ALIGN_WINDOWS | 0x20000 | Flag used to align windows (in items with windows) at the same horizontal position.
TR_ALIGN_WINDOWS_RIGHT | 0x40000 | Flag used to align windows (in items with windows) to the rightmost edge of CustomTreeCtrl.
TR_ELLIPSIZE_LONG_ITEMS | 0x80000 | Flag used to ellipsize long items when the horizontal space for CustomTreeCtrl is low.
TR_TOOLTIP_ON_LONG_ITEMS | 0x100000 | Flag used to show tooltips on long items when the horizontal space for CustomTreeCtrl is low.

events Events Processing

This class processes the following events:

Events processing for customtreectrl
Event Name | Description
EVT_TREE_BEGIN_DRAG | Begin dragging with the left mouse button.
EVT_TREE_BEGIN_LABEL_EDIT | Begin editing a label. This can be prevented by calling Veto.
EVT_TREE_BEGIN_RDRAG | Begin dragging with the right mouse button.
EVT_TREE_DELETE_ITEM | Delete an item.
EVT_TREE_END_DRAG | End dragging with the left or right mouse button.
EVT_TREE_END_LABEL_EDIT | End editing a label. This can be prevented by calling Veto.
EVT_TREE_GET_INFO | Request information from the application (not implemented in CustomTreeCtrl).
EVT_TREE_ITEM_ACTIVATED | The item has been activated, i.e. chosen by double clicking it with mouse or from keyboard.
EVT_TREE_ITEM_CHECKED | A checkbox or radiobox type item has been checked.
EVT_TREE_ITEM_CHECKING | A checkbox or radiobox type item is being checked.
EVT_TREE_ITEM_COLLAPSED | The item has been collapsed.
EVT_TREE_ITEM_COLLAPSING | The item is being collapsed. This can be prevented by calling Veto.
EVT_TREE_ITEM_EXPANDED | The item has been expanded.
EVT_TREE_ITEM_EXPANDING | The item is being expanded. This can be prevented by calling Veto.
EVT_TREE_ITEM_GETTOOLTIP | The opportunity to set the item tooltip is being given to the application (call TreeEvent.SetToolTip).
EVT_TREE_ITEM_HYPERLINK | An hyperlink type item has been clicked.
EVT_TREE_ITEM_MENU | The context menu for the selected item has been requested, either by a right click or by using the menu key.
EVT_TREE_ITEM_MIDDLE_CLICK | The user has clicked the item with the middle mouse button (not implemented in CustomTreeCtrl).
EVT_TREE_ITEM_RIGHT_CLICK | The user has clicked the item with the right mouse button.
EVT_TREE_KEY_DOWN | A key has been pressed.
EVT_TREE_SEL_CHANGED | Selection has changed.
EVT_TREE_SEL_CHANGING | Selection is changing. This can be prevented by calling Veto.
EVT_TREE_SET_INFO | Information is being supplied to the application (not implemented in CustomTreeCtrl).
EVT_TREE_STATE_IMAGE_CLICK | The state image has been clicked (not implemented in CustomTreeCtrl).

license License And Version

CustomTreeCtrl is distributed under the wxPython license.

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

Version 2.6

Module author: Andrea Gavana <andrea.gavana@gmail.com>

hierarchy Inheritance Diagram

Inheritance diagram for module: customtreectrl

Inheritance diagram of customtreectrl.CommandTreeEvent, customtreectrl.CustomTreeCtrl, customtreectrl.DragImage, customtreectrl.GenericTreeItem, customtreectrl.TreeEditTimer, customtreectrl.TreeEvent, customtreectrl.TreeFindTimer, customtreectrl.TreeItemAttr, customtreectrl.TreeTextCtrl

SVN Revisions

A graphical representation of the SVN commits in the last year.

Click on any date in the picture to jump to that particular revision page, containing information about committers, log messages and SVN diffs.

Revision Graph For customtreectrl

2to3 Python 3 Issues (via 2to3)

No issues have been detected by 2to3.py.

Function Summary

  • ChopText
  • DrawTreeItemButton
  • EventFlagsToSelType
  • MakeDisabledBitmap

Class Summary

  • CommandTreeEvent
  • CustomTreeCtrl
  • DragImage
  • GenericTreeItem
  • TreeEditTimer
  • TreeEvent
  • TreeFindTimer
  • TreeItemAttr
  • TreeTextCtrl

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • infobar
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • customtreectrl


flatmenu

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • flatmenu

flatmenu

FlatMenu is a generic menu implementation.

description Description

FlatMenu, like the name implies, it is a generic menu implementation. I tried to provide a full functionality for menus, menubar and toolbar.

FlatMenu supports the following features:

  • Fires all the events (UI & Cmd);
  • Check items;
  • Separators;
  • Enabled / Disabled menu items;
  • Images on items;
  • Toolbar support, with images and separators;
  • Controls in toolbar (work in progress);
  • Toolbar tools tooltips (done: thanks to Peter Kort);
  • Accelerators for menus;
  • Accelerators for menubar;
  • Radio items in menus;
  • Integration with AUI;
  • Scrolling when menu is too big to fit the screen;
  • Menu navigation with keyboard;
  • Drop down arrow button to the right of the menu, it always contains the “Customize” option, which will popup an options dialog. The dialog has the following abilities:
    1. Ability to add/remove menus;
    2. Select different colour schemes for the menu bar / toolbar;
    3. Control various options, such as: colour for highlight menu item, draw border around menus (classic look only);
    4. Toolbar floating appearance.
  • Allows user to specify grey bitmap for disabled menus/toolbar tools;
  • If no grey bitmap is provided, it generates one from the existing bitmap;
  • Hidden toolbar items / menu bar items - will appear in a small popmenu to the right if they are hidden;
  • 4 different colour schemes for the menu bar (more can easily added);
  • Scrolling is available if the menu height is greater than the screen height;
  • Context menus for menu items;
  • Show/hide the drop down arrow which allows the customization of FlatMenu;
  • Multiple columns menu window;
  • Tooltips for menus and toolbar items on a wx.StatusBar (if present);
  • Transparency (alpha channel) for menu windows (for platforms supporting it);
  • FileHistory support through a pure-Python wx.FileHistory implementation;
  • Possibility to set a background bitmap for a FlatMenu;
  • First attempt in adding controls to FlatToolbar;
  • Added a MiniBar (thanks to Vladiuz);
  • Added wx.ToolBar methods AddCheckTool/AddRadioTool (thanks to Vladiuz).

usage Usage

Usage example:

import wx
import wx.lib.agw.flatmenu as FM

class MyFrame(wx.Frame):

    def __init__(self, parent):

        wx.Frame.__init__(self, parent, -1, "FlatMenu Demo")

        self.CreateMenu()

        panel = wx.Panel(self, -1)
        btn = wx.Button(panel, -1, "Hello", (15, 12), (100, 120))

        main_sizer = wx.BoxSizer(wx.VERTICAL)
        main_sizer.Add(self.menubar, 0, wx.EXPAND)
        main_sizer.Add(panel, 1, wx.EXPAND)

        self.SetSizer(main_sizer)
        main_sizer.Layout()

    def CreateMenu(self):

        self.menubar = FM.FlatMenuBar(self, -1)

        f_menu = FM.FlatMenu()
        e_menu = FM.FlatMenu()
        v_menu = FM.FlatMenu()
        t_menu = FM.FlatMenu()
        w_menu = FM.FlatMenu()

        # Append the menu items to the menus
        f_menu.Append(-1, "Simple   Ctrl+N", "Text", None)
        e_menu.Append(-1, "FlatMenu", "Text", None)
        v_menu.Append(-1, "Example", "Text", None)
        t_menu.Append(-1, "Hello", "Text", None)
        w_menu.Append(-1, "World", "Text", None)

        # Append menus to the menubar
        self.menubar.Append(f_menu, "&File")
        self.menubar.Append(e_menu, "&Edit")
        self.menubar.Append(v_menu, "&View")
        self.menubar.Append(t_menu, "&Options")
        self.menubar.Append(w_menu, "&Help")

# our normal wxApp-derived class, as usual

app = wx.PySimpleApp()

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

app.MainLoop()

This code snippet can be downloaded, see this example script.

Note

Some of the AGW snippets of code in the documentation use images and external files (to create bitmaps or access external data). As these files are not provided in these snippets, you should make the approriate modifications to the code to actually run it.

platforms Supported Platforms

FlatMenu has been tested on the following platforms:
  • Windows (Windows XP, Vista);
  • Linux Ubuntu (Dapper 6.06)

styles Window Styles

This class supports the following window styles:

Window styles for flatmenu
Window Styles | Hex Value | Description
FM_OPT_IS_LCD | 0x1 | Use this style if your computer uses a LCD screen.
FM_OPT_MINIBAR | 0x2 | Use this if you plan to use the toolbar only.
FM_OPT_SHOW_CUSTOMIZE | 0x4 | Show “customize link” in the More menu, you will need to write your own handler. See demo.
FM_OPT_SHOW_TOOLBAR | 0x8 | Set this option is you are planning to use the toolbar.

events Events Processing

This class processes the following events:

Events processing for flatmenu
Event Name | Description
EVT_FLAT_MENU_DISMISSED | Used internally.
EVT_FLAT_MENU_ITEM_MOUSE_OUT | Fires an event when the mouse leaves a FlatMenuItem.
EVT_FLAT_MENU_ITEM_MOUSE_OVER | Fires an event when the mouse enters a FlatMenuItem.
EVT_FLAT_MENU_SELECTED | Fires the wx.EVT_MENU event for FlatMenu.

license License And Version

FlatMenu is distributed under the wxPython license.

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

Version 1.0

Module author: Andrea Gavana <andrea.gavana@gmail.com>

hierarchy Inheritance Diagram

Inheritance diagram for module: flatmenu

SVN Revisions

A graphical representation of the SVN commits in the last year.

Click on any date in the picture to jump to that particular revision page, containing information about committers, log messages and SVN diffs.

Revision Graph For flatmenu

2to3 Python 3 Issues (via 2to3)

No issues have been detected by 2to3.py.

Function Summary

  • ConvertToMonochrome
  • GetAccelIndex
  • GetMRUEntryLabel

Class Summary

  • FMRenderer
  • FMRendererMSOffice2007
  • FMRendererMgr
  • FMRendererVista
  • FMRendererXP
  • FileHistory
  • FlatMenu
  • FlatMenuBar
  • FlatMenuBase
  • FlatMenuButton
  • FlatMenuEvent
  • FlatMenuItem
  • FlatMenuItemGroup
  • FlatToolbarItem
  • FocusHandler
  • MenuEntryInfo
  • MenuKbdRedirector
  • ShadowPopupWindow
  • StatusBarTimer
  • ToolBarItem
  • mcPopupWindow

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • infobar
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • flatmenu


flatnotebook

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • flatnotebook

flatnotebook

FlatNotebook is a full, generic and owner-drawn implementation of wx.Notebook.

description Description

FlatNotebook is a full implementation of the wx.Notebook, and designed to be a drop-in replacement for wx.Notebook. The API functions are similar so one can expect the function to behave in the same way.

Some features:

  • The buttons are highlighted a la Firefox style;
  • The scrolling is done for bulks of tabs (so, the scrolling is faster and better);
  • The buttons area is never overdrawn by tabs (unlike many other implementations I saw);
  • It is a generic control;
  • Currently there are 6 different styles - VC8, VC 71, Standard, Fancy, Firefox 2 and Ribbon;
  • Mouse middle click can be used to close tabs;
  • A function to add right click menu for tabs (simple as SetRightClickMenu);
  • All styles has bottom style as well (they can be drawn in the bottom of screen);
  • An option to hide ‘X’ button or navigation buttons (separately);
  • Gradient colouring of the selected tabs and border;
  • Support for drag ‘n’ drop of tabs, both in the same notebook or to another notebook;
  • Possibility to have closing button on the active tab directly;
  • Support for disabled tabs;
  • Colours for active/inactive tabs, and captions;
  • Background of tab area can be painted in gradient (VC8 style only);
  • Colourful tabs - a random gentle colour is generated for each new tab (very cool, VC8 style only);
  • Support for showing pages in “column/row mode”, which means that all the pages will be shown in “tile” mode while the tabs are hidden;
  • Possibility to add a custom panel to show a logo or HTML documentation or whatever you like when there are no pages left in FlatNotebook;
  • Try setting the tab area colour for the Ribbon Style.

And much more.

usage Usage

Usage example:

import wx
import wx.lib.agw.flatnotebook as fnb

class MyFrame(wx.Frame):

    def __init__(self, parent):

        wx.Frame.__init(self, parent, -1, "FlatNotebook Demo")

        panel = wx.Panel(self)

        notebook = fnb.FlatNotebook(panel, -1)

        for i in xrange(3):
            caption = "Page %d"%(i+1)
            notebook.AddPage(self.CreatePage(notebook, caption), caption)

        sizer = wx.BoxSizer(wx.VERTICAL)
        sizer.Add(notebook, 1, wx.ALL|wx.EXPAND, 5)
        panel.SetSizer(sizer)

    def CreatePage(self, notebook, caption):
        '''
        Creates a simple `wx.Panel` containing a `wx.TextCtrl`.

        :param `notebook`: an instance of `FlatNotebook`;
        :param `caption`: a simple label.
        '''

        p = wx.Panel(notebook)
        wx.StaticText(p, -1, caption, (20,20))
        wx.TextCtrl(p, -1, "", (20,40), (150,-1))
        return p

# our normal wxApp-derived class, as usual

app = wx.PySimpleApp()

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

app.MainLoop()

This code snippet can be downloaded, see this example script.

Note

Some of the AGW snippets of code in the documentation use images and external files (to create bitmaps or access external data). As these files are not provided in these snippets, you should make the approriate modifications to the code to actually run it.

styles Window Styles

This class supports the following window styles:

Window styles for flatnotebook
Window Styles | Hex Value | Description
FNB_VC71 | 0x1 | Use Visual Studio 2003 (VC7.1) style for tabs.
FNB_FANCY_TABS | 0x2 | Use fancy style - square tabs filled with gradient colouring.
FNB_TABS_BORDER_SIMPLE | 0x4 | Draw thin border around the page.
FNB_NO_X_BUTTON | 0x8 | Do not display the ‘X’ button.
FNB_NO_NAV_BUTTONS | 0x10 | Do not display the right/left arrows.
FNB_MOUSE_MIDDLE_CLOSES_TABS | 0x20 | Use the mouse middle button for cloing tabs.
FNB_BOTTOM | 0x40 | Place tabs at bottom - the default is to place them at top.
FNB_NODRAG | 0x80 | Disable dragging of tabs.
FNB_VC8 | 0x100 | Use Visual Studio 2005 (VC8) style for tabs.
FNB_X_ON_TAB | 0x200 | Place ‘X’ close button on the active tab.
FNB_BACKGROUND_GRADIENT | 0x400 | Use gradients to paint the tabs background.
FNB_COLOURFUL_TABS | 0x800 | Use colourful tabs (VC8 style only).
FNB_DCLICK_CLOSES_TABS | 0x1000 | Style to close tab using double click.
FNB_SMART_TABS | 0x2000 | Use Smart Tabbing, like Alt + Tab on Windows.
FNB_DROPDOWN_TABS_LIST | 0x4000 | Use a dropdown menu on the left in place of the arrows.
FNB_ALLOW_FOREIGN_DND | 0x8000 | Allows drag ‘n’ drop operations between different FlatNotebook.
FNB_HIDE_ON_SINGLE_TAB | 0x10000 | Hides the Page Container when there is one or fewer tabs.
FNB_DEFAULT_STYLE | 0x10020 | FlatNotebook default style.
FNB_FF2 | 0x20000 | Use Firefox 2 style for tabs.
FNB_NO_TAB_FOCUS | 0x40000 | Does not allow tabs to have focus.
FNB_RIBBON_TABS | 0x80000 | Use the Ribbon Tabs style
FNB_HIDE_TABS | 0x100000 | Hides the Page Container allowing only keyboard navigation
FNB_NAV_BUTTONS_WHEN_NEEDED | 0x200000 | Hides the navigation left/right arrows if all tabs fit

events Events Processing

This class processes the following events:

Events processing for flatnotebook
Event Name | Description
EVT_FLATNOTEBOOK_PAGE_CHANGED | Notify client objects when the active page in FlatNotebook has changed.
EVT_FLATNOTEBOOK_PAGE_CHANGING | Notify client objects when the active page in FlatNotebook is about to change.
EVT_FLATNOTEBOOK_PAGE_CLOSED | Notify client objects when a page in FlatNotebook has been closed.
EVT_FLATNOTEBOOK_PAGE_CLOSING | Notify client objects when a page in FlatNotebook is closing.
EVT_FLATNOTEBOOK_PAGE_CONTEXT_MENU | Notify client objects when a pop-up menu should appear next to a tab.
EVT_FLATNOTEBOOK_PAGE_DROPPED | Notify client objects when a tab has been dropped and re-arranged (on the same notebook)
EVT_FLATNOTEBOOK_PAGE_DROPPED_FOREIGN | Notify client objects when a tab has been dropped and re-arranged (from a foreign notebook)

license License And Version

FlatNotebook is distributed under the wxPython license.

Latest Revision: Andrea Gavana @ 26 Oct 2011, 21.00 GMT

Version 3.2

Module author: Andrea Gavana <andrea.gavana@gmail.com>

hierarchy Inheritance Diagram

Inheritance diagram for module: flatnotebook

SVN Revisions

A graphical representation of the SVN commits in the last year.

Click on any date in the picture to jump to that particular revision page, containing information about committers, log messages and SVN diffs.

Revision Graph For flatnotebook

2to3 Python 3 Issues (via 2to3)

No issues have been detected by 2to3.py.

Function Summary

  • AdjustColour
  • DrawButton
  • FormatColour
  • LightColour
  • PaintStraightGradientBox
  • RandomColour

Class Summary

  • FNBDragInfo
  • FNBDropSource
  • FNBDropTarget
  • FNBRenderer
  • FNBRendererDefault
  • FNBRendererFancy
  • FNBRendererFirefox2
  • FNBRendererMgr
  • FNBRendererRibbonTabs
  • FNBRendererVC71
  • FNBRendererVC8
  • FlatNotebook
  • FlatNotebookCompatible
  • FlatNotebookDragEvent
  • FlatNotebookEvent
  • PageContainer
  • PageInfo
  • TabNavigatorWindow

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • infobar
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • flatnotebook


floatspin

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • floatspin

floatspin

FloatSpin implements a floating point wx.SpinCtrl.

description Description

FloatSpin implements a floating point wx.SpinCtrl. It is built using a custom wx.PyControl, composed by a wx.TextCtrl and a wx.SpinButton. In order to correctly handle floating points numbers without rounding errors or non-exact floating point representations, FloatSpin uses the great FixedPoint class from Tim Peters.

What you can do:

  • Set the number of representative digits for your floating point numbers;
  • Set the floating point format (%f, %F, %e, %E, %g, %G);
  • Set the increment of every EVT_FLOATSPIN event;
  • Set minimum, maximum values for FloatSpin as well as its range;
  • Change font and colour for the underline wx.TextCtrl.

usage Usage

Usage example:

import wx
import wx.lib.agw.floatspin as FS

class MyFrame(wx.Frame):

    def __init__(self, parent):

        wx.Frame.__init__(self, parent, -1, "FloatSpin Demo")

        panel = wx.Panel(self)

        floatspin = FS.FloatSpin(panel, -1, pos=(50, 50), min_val=0, max_val=1,
                                 increment=0.01, value=0.1, agwStyle=FS.FS_LEFT)
        floatspin.SetFormat("%f")
        floatspin.SetDigits(2)

# our normal wxApp-derived class, as usual

app = wx.PySimpleApp()

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

app.MainLoop()

This code snippet can be downloaded, see this example script.

Note

Some of the AGW snippets of code in the documentation use images and external files (to create bitmaps or access external data). As these files are not provided in these snippets, you should make the approriate modifications to the code to actually run it.

events Events

FloatSpin catches 3 different types of events:

  1. Spin events: events generated by spinning up/down the spinbutton;
  2. Char events: playing with up/down arrows of the keyboard increase/decrease the value of FloatSpin;
  3. Mouse wheel event: using the wheel will change the value of FloatSpin.

In addition, there are some other functionalities:

  • It remembers the initial value as a default value, call SetToDefaultValue, or press Esc to return to it;
  • Shift + arrow = 2 * increment (or Shift + mouse wheel);
  • Ctrl + arrow = 10 * increment (or Ctrl + mouse wheel);
  • Alt + arrow = 100 * increment (or Alt + mouse wheel);
  • Combinations of Shift, Ctrl, Alt increment the FloatSpin value by the product of the factors;
  • PgUp & PgDn = 10 * increment * the product of the Shift, Ctrl, Alt factors;
  • Space sets the control’s value to it’s last valid state.

styles Window Styles

This class supports the following window styles:

Window styles for floatspin
Window Styles | Hex Value | Description
FS_READONLY | 0x1 | Sets FloatSpin as read-only control.
FS_LEFT | 0x2 | Horizontally align the underlying wx.TextCtrl on the left.
FS_CENTRE | 0x4 | Horizontally align the underlying wx.TextCtrl on center.
FS_RIGHT | 0x8 | Horizontally align the underlying wx.TextCtrl on the right.

events Events Processing

This class processes the following events:

Events processing for floatspin
Event Name | Description
EVT_FLOATSPIN | Emitted when the user changes the value of FloatSpin, either with the mouse or with the keyboard.

license License And Version

FloatSpin control is distributed under the wxPython license.

Latest revision: Andrea Gavana @ 17 Aug 2011, 15.00 GMT

Version 0.9

backward Backward Incompatibilities

Modifications to allow min_val or max_val to be None done by:

James Bigler, SCI Institute, University of Utah, March 14, 2007

Note

Note that the changes I made will break backward compatibility, because I changed the contructor’s parameters from min / max to min_val / max_val to be consistent with the other functions and to eliminate any potential confusion with the built in min and max functions.

You specify open ranges like this (you can equally do this in the constructor):

SetRange(min_val=1, max_val=None)     # [1,  ]
SetRange(min_val=None, max_val=0)     # [ , 0]

or no range:

SetRange(min_val=None, max_val=None)  # [ , ]

Module author: Andrea Gavana <andrea.gavana@gmail.com>

hierarchy Inheritance Diagram

Inheritance diagram for module: floatspin

Inheritance diagram of floatspin.FixedPoint, floatspin.FloatSpin, floatspin.FloatSpinEvent, floatspin.FloatTextCtrl

SVN Revisions

A graphical representation of the SVN commits in the last year.

Click on any date in the picture to jump to that particular revision page, containing information about committers, log messages and SVN diffs.

Revision Graph For floatspin

2to3 Python 3 Issues (via 2to3)

No issues have been detected by 2to3.py.

Function Summary

  • _mkFP
  • _norm
  • _roundquotient
  • _string2exact
  • _tento

Class Summary

  • FixedPoint
  • FloatSpin
  • FloatSpinEvent
  • FloatTextCtrl

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • infobar
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • floatspin


fmcustomizedlg

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • fmcustomizedlg

fmcustomizedlg

This module contains a custom dialog class used to personalize the appearance of a FlatMenu on the fly, allowing also the user of your application to do the same.

Module author: Andrea Gavana <andrea.gavana@gmail.com>

hierarchy Inheritance Diagram

Inheritance diagram for module: fmcustomizedlg

Inheritance diagram of fmcustomizedlg.FMCustomizeDlg, fmcustomizedlg.FMTitlePanel

SVN Revisions

A graphical representation of the SVN commits in the last year.

Click on any date in the picture to jump to that particular revision page, containing information about committers, log messages and SVN diffs.

Revision Graph For fmcustomizedlg

2to3 Python 3 Issues (via 2to3)

No issues have been detected by 2to3.py.

Class Summary

  • FMCustomizeDlg
  • FMTitlePanel

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • infobar
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • fmcustomizedlg


foldpanelbar

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • foldpanelbar

foldpanelbar

FoldPanelBar is a control that contains multiple panels, which can be expanded or collapsed.

description Description

The FoldPanelBar is a control that contains multiple panels (of type FoldPanelItem) that can be expanded or collapsed. The captionbar of the FoldPanelBar can be customized by setting it to a horizontal gradient style, vertical gradient style, a single colour, a rectangle or filled rectangle. The FoldPanel items can be collapsed in place or to the bottom of the control. wx.Window derived controls can be added dynamically, and separated by separator lines.

How does it work

The internals of the FoldPanelBar is a list of FoldPanelItem objects. Through the reference of FoldPanel these panels can be controlled by adding new controls to a FoldPanel or adding new FoldPanels to the FoldPanelBar.

The CaptionBar fires events to the parent (container of all panel items) when a sub-panel needs resizing (either folding or expanding). The fold or expand process is simply a resize of the panel so it looks like all controls on it are gone. All controls are still child of the FoldPanel they are located on. If they don’t handle the event (and they won’t) then the owner of the FoldPanelBar gets the events.

This is what you need to handle the controls. There isn’t much to it just a lot of calculations to see what panel belongs where. There are no sizers involved in the panels, everything is purely x-y positioning.

What can it do and what not?

  1. What it can do:
    • Run-time addition of panels (no deletion just yet);
    • Run time addition of controls to the panel (it will be resized accordingly);
    • Creating panels in collapsed mode or expanded mode;
    • Various modes of caption behaviour and filling to make it more appealing;
    • Panels can be folded and collapsed (or all of them) to allow more space.
  2. What it cannot do:
    • Selection of a panel like in a listctrl;
    • Dragging and dropping the panels;
    • Re-ordering the panels (not yet).

usage Usage

Usage example:

import wx
import wx.lib.agw.foldpanelbar as fpb

class MyFrame(wx.Frame):

    def __init__(self, parent):

        wx.Frame.__init__(self, parent, -1, "FoldPanelBar Demo")

        text_ctrl = wx.TextCtrl(self, -1, size=(400, 100), style=wx.TE_MULTILINE)

        panel_bar = fpb.FoldPanelBar(self, -1, agwStyle=fpb.FPB_HORIZONTAL|fpb.FPB_DEFAULT_STYLE)

        fold_panel = panel_bar.AddFoldPanel("Thing")
        thing = wx.TextCtrl(fold_panel, -1, size=(400, -1), style=wx.TE_MULTILINE)

        panel_bar.AddFoldPanelWindow(fold_panel, thing)

        main_sizer = wx.BoxSizer(wx.HORIZONTAL)
        main_sizer.Add(text_ctrl, 1, wx.EXPAND)
        main_sizer.Add(panel_bar, 0, wx.EXPAND)
        self.SetSizer(main_sizer)

# our normal wxApp-derived class, as usual

app = wx.PySimpleApp()

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

app.MainLoop()

This code snippet can be downloaded, see this example script.

Note

Some of the AGW snippets of code in the documentation use images and external files (to create bitmaps or access external data). As these files are not provided in these snippets, you should make the approriate modifications to the code to actually run it.

platforms Supported Platforms

FoldPanelBar is supported on the following platforms:
  • Windows (Verified on Windows XP, 2000)
  • Linux/Unix (GTK2) (Thanks to Toni Brkic and Robin Dunn)
  • Mac OSX (Thanks to Robin Dunn for the CaptionBar size patch)

styles Window Styles

This class supports the following window styles:

Window styles for foldpanelbar
Window Styles | Hex Value | Description
FPB_SINGLE_FOLD | 0x1 | Single fold forces other panels to close when they are open, and only opens the current panel. This will allow the open panel to gain the full size left in the client area.
FPB_COLLAPSE_TO_BOTTOM | 0x2 | All panels are stacked to the bottom. When they are expanded again they show up at the top.
FPB_EXCLUSIVE_FOLD | 0x4 | FPB_SINGLE_FOLD style plus the panels will be stacked at the bottom.
FPB_HORIZONTAL | 0x8 | FoldPanelBar will be horizontal.
FPB_VERTICAL | 0x10 | FoldPanelBar will be vertical.

events Events Processing

This class processes the following events:

Events processing for foldpanelbar
Event Name | Description
EVT_CAPTIONBAR | The user has pressed the caption bar: FoldPanelBar will either expand or collapse the underlying panel.

license License And Version

FoldPanelBar is distributed under the wxPython license.

Latest Revision: Andrea Gavana @ 17 Sep 2011, 23.00 GMT

Version 0.5

Module author: Andrea Gavana <andrea.gavana@gmail.com>

hierarchy Inheritance Diagram

Inheritance diagram for module: foldpanelbar

Inheritance diagram of foldpanelbar.CaptionBar, foldpanelbar.CaptionBarEvent, foldpanelbar.CaptionBarStyle, foldpanelbar.FoldPanelBar, foldpanelbar.FoldPanelItem, foldpanelbar.FoldWindowItem

SVN Revisions

A graphical representation of the SVN commits in the last year.

Click on any date in the picture to jump to that particular revision page, containing information about committers, log messages and SVN diffs.

Revision Graph For foldpanelbar

2to3 Python 3 Issues (via 2to3)

No issues have been detected by 2to3.py.

Class Summary

  • CaptionBar
  • CaptionBarEvent
  • CaptionBarStyle
  • FoldPanelBar
  • FoldPanelItem
  • FoldWindowItem

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • infobar
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • foldpanelbar


fourwaysplitter

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • fourwaysplitter

fourwaysplitter

FourWaySplitter is a layout manager which manages 4 children like 4 panes in a window.

description Description

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

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

The main characteristics of FourWaySplitter are:

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

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

usage Usage

Usage example:

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

class MyFrame(wx.Frame):

    def __init__(self, parent):

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

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

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

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

            splitter.AppendWindow(panel)

# our normal wxApp-derived class, as usual

app = wx.PySimpleApp()

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

app.MainLoop()

This code snippet can be downloaded, see this example script.

Note

Some of the AGW snippets of code in the documentation use images and external files (to create bitmaps or access external data). As these files are not provided in these snippets, you should make the approriate modifications to the code to actually run it.

platforms Supported Platforms

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

styles Window Styles

This class supports the following window styles:

Window styles for fourwaysplitter
Window Styles | Hex Value | Description
SP_NOSASH | 0x10 | No sash will be drawn on FourWaySplitter.
SP_LIVE_UPDATE | 0x80 | Don’t draw XOR line but resize the child windows immediately.
SP_3DBORDER | 0x200 | Draws a 3D effect border.

events Events Processing

This class processes the following events:

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

license License And Version

FourWaySplitter is distributed under the wxPython license.

Latest Revision: Andrea Gavana @ 17 Aug 2011, 15.00 GMT

Version 0.4

Module author: Andrea Gavana <andrea.gavana@gmail.com>

hierarchy Inheritance Diagram

Inheritance diagram for module: fourwaysplitter

Inheritance diagram of fourwaysplitter.FourWaySplitter, fourwaysplitter.FourWaySplitterEvent

SVN Revisions

A graphical representation of the SVN commits in the last year.

Click on any date in the picture to jump to that particular revision page, containing information about committers, log messages and SVN diffs.

Revision Graph For fourwaysplitter

2to3 Python 3 Issues (via 2to3)

No issues have been detected by 2to3.py.

Class Summary

  • FourWaySplitter
  • FourWaySplitterEvent

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • infobar
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • fourwaysplitter


genericmessagedialog

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • genericmessagedialog

genericmessagedialog

This class is a possible, fancy replacement for wx.MessageDialog.

description Description

This class represents a dialog that shows a single or multi-line message, with a choice of OK, Yes, No, Cancel and Help buttons. It is a possible replacement for the standard wx.MessageDialog, with these extra functionalities:

  • Possibility to modify the dialog position;
  • Custom themed generic bitmap & text buttons;
  • Support for normal and extended message (in different fonts);
  • Custom labels for the OK, Yes, No, Cancel and Help buttons;
  • Custom icons for the OK, Yes, No, Cancel and Help buttons;
  • Possibility to set an icon to the dialog;
  • More visibility to the button getting the focus;
  • Support for Aqua buttons or Gradient buttons instead of themed ones (see AquaButton and GradientButton);
  • Possibility to automatically wrap long lines of text;
  • Good old Python code :-D .

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

usage Usage

Usage example:

import wx
import wx.lib.agw.genericmessagedialog as GMD

# Our normal wxApp-derived class, as usual
app = wx.App(0)

main_message = "Hello world! I am the main message."

dlg = GMD.GenericMessageDialog(None, main_message, "A Nice Message Box",
                               agwStyle=wx.ICON_INFORMATION|wx.OK)

dlg.ShowModal()
dlg.Destroy()

app.MainLoop()

This code snippet can be downloaded, see this example script.

Note

Some of the AGW snippets of code in the documentation use images and external files (to create bitmaps or access external data). As these files are not provided in these snippets, you should make the approriate modifications to the code to actually run it.

platforms Supported Platforms

GenericMessageDialog has been tested on the following platforms:
  • Windows (Windows XP).

styles Window Styles

This class supports the following window styles:

Window styles for genericmessagedialog
Window Styles | Hex Value | Description
GMD_USE_AQUABUTTONS | 0x20 | Uses wx.lib.agw.aquabutton buttons instead of generic buttons.
GMD_USE_GRADIENTBUTTONS | 0x40 | Uses wx.lib.agw.gradientbutton buttons instead of generic buttons.

The styles above are mutually exclusive. The style chosen above can be combined with a bitlist containing flags chosen from the following:

Window styles for genericmessagedialog
Window Styles | Hex Value | Description
wx.OK | 0x4 | Shows an OK button.
wx.CANCEL | 0x10 | Shows a Cancel button.
wx.YES_NO | 0xA | Show Yes and No buttons.
wx.YES_DEFAULT | 0x0 | Used with wx.YES_NO, makes Yes button the default - which is the default behaviour.
wx.NO_DEFAULT | 0x80 | Used with wx.YES_NO, makes No button the default.
wx.ICON_EXCLAMATION | 0x100 | Shows an exclamation mark icon.
wx.ICON_HAND | 0x200 | Shows an error icon.
wx.ICON_ERROR | 0x200 | Shows an error icon - the same as wx.ICON_HAND.
wx.ICON_QUESTION | 0x400 | Shows a question mark icon.
wx.ICON_INFORMATION | 0x800 | Shows an information icon.

events Events Processing

No custom events are available for this class.

license License And Version

GenericMessageDialog is distributed under the wxPython license.

Latest Revision: Andrea Gavana @ 29 Feb 2012, 21.00 GMT

Version 0.7

Module author: Andrea Gavana <andrea.gavana@gmail.com>

hierarchy Inheritance Diagram

Inheritance diagram for module: genericmessagedialog

Inheritance diagram of genericmessagedialog.GenericMessageDialog, genericmessagedialog.StdDialogButtonSizer

SVN Revisions

A graphical representation of the SVN commits in the last year.

Click on any date in the picture to jump to that particular revision page, containing information about committers, log messages and SVN diffs.

Revision Graph For genericmessagedialog

2to3 Python 3 Issues (via 2to3)

No issues have been detected by 2to3.py.

Class Summary

  • GenericMessageDialog
  • StdDialogButtonSizer

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • infobar
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • genericmessagedialog


gradientbutton

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • gradientbutton

gradientbutton

GradientButton is another custom-drawn button class which mimics Windows CE mobile gradient buttons.

description Description

GradientButton is another custom-drawn button class which mimics Windows CE mobile gradient buttons, using a tri-vertex blended gradient plus some ClearType bold font (best effect with Tahoma Bold). GradientButton supports:

  • Triple blended gradient background, with customizable colours;
  • Custom colours for the “pressed” state;
  • Rounded-corners buttons;
  • Text-only or image+text buttons.

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

usage Usage

Usage example:

import wx
import wx.lib.agw.gradientbutton as GB

class MyFrame(wx.Frame):

    def __init__(self, parent):

        wx.Frame.__init__(self, parent, -1, "GradientButton Demo")

        panel = wx.Panel(self, -1)

        # One button without bitmap
        button_1 = GB.GradientButton(panel, -1, None, "Hello World", (100, 50))

        # One button with bitmap
        my_bitmap = wx.Bitmap("my_bitmap.png", wx.BITMAP_TYPE_PNG)
        button_2 = GB.GradientButton(panel, -1, my_bitmap, "GradientButton", (100, 150))

# our normal wxApp-derived class, as usual

app = wx.PySimpleApp()

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

app.MainLoop()

This code snippet can be downloaded, see this example script.

Note

Some of the AGW snippets of code in the documentation use images and external files (to create bitmaps or access external data). As these files are not provided in these snippets, you should make the approriate modifications to the code to actually run it.

platforms Supported Platforms

GradientButton has been tested on the following platforms:
  • Windows (Windows XP).

styles Window Styles

No particular window styles are available for this class.

events Events Processing

This class processes the following events:

Events processing for gradientbutton
Event Name | Description
wx.EVT_BUTTON | Process a wx.wxEVT_COMMAND_BUTTON_CLICKED event, when the button is clicked.

license License And Version

GradientButton is distributed under the wxPython license.

Latest Revision: Andrea Gavana @ 09 Feb 2012, 21.00 GMT

Version 0.3

Module author: Andrea Gavana <andrea.gavana@gmail.com>

hierarchy Inheritance Diagram

Inheritance diagram for module: gradientbutton

Inheritance diagram of gradientbutton.GradientButton, gradientbutton.GradientButtonEvent

SVN Revisions

A graphical representation of the SVN commits in the last year.

Click on any date in the picture to jump to that particular revision page, containing information about committers, log messages and SVN diffs.

Revision Graph For gradientbutton

2to3 Python 3 Issues (via 2to3)

No issues have been detected by 2to3.py.

Class Summary

  • GradientButton
  • GradientButtonEvent

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • infobar
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • gradientbutton


hyperlink

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • hyperlink

hyperlink

HyperLinkCtrl is a control for wxPython that acts like a hyper link in a typical browser.

description Description

HyperLinkCtrl is a control for wxPython that acts like a hyper link in a typical browser. Latest features include the ability to capture your own left, middle, and right click events to perform your own custom event handling and ability to open link in a new or current browser window.

Special thanks to Robin Dunn for the event binder for the 3 mouse buttons.

usage Usage

Usage example:

import wx
import wx.lib.agw.hyperlink as hl

class MyFrame(wx.Frame):

    def __init__(self, parent):

        wx.Frame.__init__(self, parent, -1, "HyperLink Demo")

        panel = wx.Panel(self, -1)

        # Default Web links:
        hyper1 = hl.HyperLinkCtrl(panel, -1, "wxPython Main Page", pos=(100, 100),
                                  URL="http://www.wxpython.org/")

        # Web link with underline rollovers, opens in same window
        hyper2 = hl.HyperLinkCtrl(panel, -1, "My Home Page", pos=(100, 150),
                                  URL="http://xoomer.virgilio.it/infinity77/")

        hyper2.AutoBrowse(False)
        hyper2.SetColours("BLUE", "BLUE", "BLUE")
        hyper2.EnableRollover(True)
        hyper2.SetUnderlines(False, False, True)
        hyper2.SetBold(True)
        hyper2.OpenInSameWindow(True)
        hyper2.SetToolTip(wx.ToolTip("Hello World!"))
        hyper2.UpdateLink()

# our normal wxApp-derived class, as usual

app = wx.PySimpleApp()

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

app.MainLoop()

This code snippet can be downloaded, see this example script.

Note

Some of the AGW snippets of code in the documentation use images and external files (to create bitmaps or access external data). As these files are not provided in these snippets, you should make the approriate modifications to the code to actually run it.

styles Window Styles

No particular window styles are available for this class.

events Events Processing

This class processes the following events:

Events processing for hyperlink
Event Name | Description
EVT_HYPERLINK_LEFT | Responds to a left mouse button event. Sent when the left mouse button is clicked, but only if AutoBrowse is set to False.
EVT_HYPERLINK_MIDDLE | Responds to a middle mouse button event. Sent when the middle mouse button is clicked.
EVT_HYPERLINK_RIGHT | Handles a right mouse button event. Sent when the right mouse button is clicked, but only if DoPopup is set to False.

license License And Version

HyperLinkCtrl is distributed under the wxPython license.

Latest Revision: Andrea Gavana @ 17 Aug 2011, 15.00 GMT

Version 0.6

Module author: Andrea Gavana <andrea.gavana@gmail.com>

hierarchy Inheritance Diagram

Inheritance diagram for module: hyperlink

Inheritance diagram of hyperlink.HyperLinkCtrl, hyperlink.HyperLinkEvent

SVN Revisions

A graphical representation of the SVN commits in the last year.

Click on any date in the picture to jump to that particular revision page, containing information about committers, log messages and SVN diffs.

Revision Graph For hyperlink

2to3 Python 3 Issues (via 2to3)

No issues have been detected by 2to3.py.

Class Summary

  • HyperLinkCtrl
  • HyperLinkEvent

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • infobar
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • hyperlink


hypertreelist

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • hypertreelist

hypertreelist

HyperTreeList is a class that mimics the behaviour of wx.gizmos.TreeListCtrl, with some more functionalities.

description Description

HyperTreeList is a class that mimics the behaviour of wx.gizmos.TreeListCtrl, with almost the same base functionalities plus some more enhancements. This class does not rely on the native control, as it is a full owner-drawn tree-list control.

HyperTreeList is somewhat an hybrid between CustomTreeCtrl and wx.gizmos.TreeListCtrl.

In addition to the standard wx.gizmos.TreeListCtrl behaviour this class supports:

  • CheckBox-type items: checkboxes are easy to handle, just selected or unselected state with no particular issues in handling the item’s children;
  • Added support for 3-state value checkbox items;
  • RadioButton-type items: since I elected to put radiobuttons in CustomTreeCtrl, I needed some way to handle them, that made sense. So, I used the following approach:
    • All peer-nodes that are radiobuttons will be mutually exclusive. In other words, only one of a set of radiobuttons that share a common parent can be checked at once. If a radiobutton node becomes checked, then all of its peer radiobuttons must be unchecked.
    • If a radiobutton node becomes unchecked, then all of its child nodes will become inactive.
  • Hyperlink-type items: they look like an hyperlink, with the proper mouse cursor on hovering;
  • Multiline text items;
  • Enabling/disabling items (together with their plain or grayed out icons);
  • Whatever non-toplevel widget can be attached next to a tree item;
  • Whatever non-toplevel widget can be attached next to a list item;
  • Column headers are fully customizable in terms of icons, colour, font, alignment etc...;
  • Default selection style, gradient (horizontal/vertical) selection style and Windows Vista selection style;
  • Customized drag and drop images built on the fly;
  • Setting the HyperTreeList item buttons to a personalized imagelist;
  • Setting the HyperTreeList check/radio item icons to a personalized imagelist;
  • Changing the style of the lines that connect the items (in terms of wx.Pen styles);
  • Using an image as a HyperTreeList background (currently only in “tile” mode);
  • Ellipsization of long items when the horizontal space is low, via the TR_ELLIPSIZE_LONG_ITEMS style (New in version 0.9.3).

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

base Base Functionalities

HyperTreeList supports all the wx.gizmos.TreeListCtrl styles, except:

  • TR_EXTENDED: supports for this style is on the todo list (Am I sure of this?).

Plus it has 3 more styles to handle checkbox-type items:

  • TR_AUTO_CHECK_CHILD: automatically checks/unchecks the item children;
  • TR_AUTO_CHECK_PARENT: automatically checks/unchecks the item parent;
  • TR_AUTO_TOGGLE_CHILD: automatically toggles the item children.

And a style useful to hide the TreeListCtrl header:

  • TR_NO_HEADER: hides the HyperTreeList header.

And a style related to long items (with a lot of text in them), which can be ellipsized:

  • TR_ELLIPSIZE_LONG_ITEMS: ellipsizes long items when the horizontal space for HyperTreeList is low (New in version 0.9.3).

All the methods available in wx.gizmos.TreeListCtrl are also available in HyperTreeList.

usage Usage

Usage example:

import wx
import wx.lib.agw.hypertreelist as HTL

class MyFrame(wx.Frame):

    def __init__(self, parent):

        wx.Frame.__init__(self, parent, -1, "HyperTreeList Demo")

        tree_list = HTL.HyperTreeList(self)

        tree_list.AddColumn("First column")

        root = tree_list.AddRoot("Root", ct_type=1)

        parent = tree_list.AppendItem(root, "First child", ct_type=1)
        child = tree_list.AppendItem(parent, "First Grandchild", ct_type=1)

        tree_list.AppendItem(root, "Second child", ct_type=1)

# our normal wxApp-derived class, as usual

app = wx.PySimpleApp()

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

app.MainLoop()

This code snippet can be downloaded, see this example script.

Note

Some of the AGW snippets of code in the documentation use images and external files (to create bitmaps or access external data). As these files are not provided in these snippets, you should make the approriate modifications to the code to actually run it.

events Events

All the events supported by wx.gizmos.TreeListCtrl are also available in HyperTreeList, with a few exceptions:

  • EVT_TREE_GET_INFO (don’t know what this means);
  • EVT_TREE_SET_INFO (don’t know what this means);
  • EVT_TREE_ITEM_MIDDLE_CLICK (not implemented, but easy to add);
  • EVT_TREE_STATE_IMAGE_CLICK (no need for that, look at the checking events below).

Plus, HyperTreeList supports the events related to the checkbutton-type items:

  • EVT_TREE_ITEM_CHECKING: an item is being checked;
  • EVT_TREE_ITEM_CHECKED: an item has been checked.

And to hyperlink-type items:

  • EVT_TREE_ITEM_HYPERLINK: an hyperlink item has been clicked (this event is sent after the EVT_TREE_SEL_CHANGED event).

platforms Supported Platforms

HyperTreeList has been tested on the following platforms:
  • Windows (Windows XP);

styles Window Styles

This class supports the following window styles:

Window styles for hypertreelist
Window Styles | Hex Value | Description
TR_NO_BUTTONS | 0x0 | For convenience to document that no buttons are to be drawn.
TR_SINGLE | 0x0 | For convenience to document that only one item may be selected at a time. Selecting another item causes the current selection, if any, to be deselected. This is the default.
TR_HAS_BUTTONS | 0x1 | Use this style to show + and - buttons to the left of parent items.
TR_NO_LINES | 0x4 | Use this style to hide vertical level connectors.
TR_LINES_AT_ROOT | 0x8 | Use this style to show lines between root nodes. Only applicable if TR_HIDE_ROOT is set and TR_NO_LINES is not set.
TR_DEFAULT_STYLE | 0x9 | The set of flags that are closest to the defaults for the native control for a particular toolkit.
TR_TWIST_BUTTONS | 0x10 | Use old Mac-twist style buttons.
TR_MULTIPLE | 0x20 | Use this style to allow a range of items to be selected. If a second range is selected, the current range, if any, is deselected.
TR_EXTENDED | 0x40 | Use this style to allow disjoint items to be selected. (Only partially implemented; may not work in all cases).
TR_HAS_VARIABLE_ROW_HEIGHT | 0x80 | Use this style to cause row heights to be just big enough to fit the content. If not set, all rows use the largest row height. The default is that this flag is unset.
TR_EDIT_LABELS | 0x200 | Use this style if you wish the user to be able to edit labels in the tree control.
TR_ROW_LINES | 0x400 | Use this style to draw a contrasting border between displayed rows.
TR_HIDE_ROOT | 0x800 | Use this style to suppress the display of the root node, effectively causing the first-level nodes to appear as a series of root nodes.
TR_COLUMN_LINES | 0x1000 | Use this style to draw a contrasting border between displayed columns.
TR_FULL_ROW_HIGHLIGHT | 0x2000 | Use this style to have the background colour and the selection highlight extend over the entire horizontal row of the tree control window.
TR_AUTO_CHECK_CHILD | 0x4000 | Only meaningful foe checkbox-type items: when a parent item is checked/unchecked its children are checked/unchecked as well.
TR_AUTO_TOGGLE_CHILD | 0x8000 | Only meaningful foe checkbox-type items: when a parent item is checked/unchecked its children are toggled accordingly.
TR_AUTO_CHECK_PARENT | 0x10000 | Only meaningful foe checkbox-type items: when a child item is checked/unchecked its parent item is checked/unchecked as well.
TR_ALIGN_WINDOWS | 0x20000 | Flag used to align windows (in items with windows) at the same horizontal position.
TR_NO_HEADER | 0x40000 | Use this style to hide the columns header.
TR_ELLIPSIZE_LONG_ITEMS | 0x80000 | Flag used to ellipsize long items when the horizontal space for HyperTreeList columns is low.
TR_VIRTUAL | 0x100000 | HyperTreeList will have virtual behaviour.

events Events Processing

This class processes the following events:

Events processing for hypertreelist
Event Name | Description
EVT_LIST_COL_BEGIN_DRAG | The user started resizing a column - can be vetoed.
EVT_LIST_COL_CLICK | A column has been left-clicked.
EVT_LIST_COL_DRAGGING | The divider between columns is being dragged.
EVT_LIST_COL_END_DRAG | A column has been resized by the user.
EVT_LIST_COL_RIGHT_CLICK | A column has been right-clicked.
EVT_TREE_BEGIN_DRAG | Begin dragging with the left mouse button.
EVT_TREE_BEGIN_LABEL_EDIT | Begin editing a label. This can be prevented by calling Veto.
EVT_TREE_BEGIN_RDRAG | Begin dragging with the right mouse button.
EVT_TREE_DELETE_ITEM | Delete an item.
EVT_TREE_END_DRAG | End dragging with the left or right mouse button.
EVT_TREE_END_LABEL_EDIT | End editing a label. This can be prevented by calling Veto.
EVT_TREE_GET_INFO | Request information from the application (not implemented in HyperTreeList).
EVT_TREE_ITEM_ACTIVATED | The item has been activated, i.e. chosen by double clicking it with mouse or from keyboard.
EVT_TREE_ITEM_CHECKED | A checkbox or radiobox type item has been checked.
EVT_TREE_ITEM_CHECKING | A checkbox or radiobox type item is being checked.
EVT_TREE_ITEM_COLLAPSED | The item has been collapsed.
EVT_TREE_ITEM_COLLAPSING | The item is being collapsed. This can be prevented by calling Veto.
EVT_TREE_ITEM_EXPANDED | The item has been expanded.s
EVT_TREE_ITEM_EXPANDING | The item is being expanded. This can be prevented by calling Veto.
EVT_TREE_ITEM_GETTOOLTIP | The opportunity to set the item tooltip is being given to the application (call SetToolTip).
EVT_TREE_ITEM_HYPERLINK | An hyperlink type item has been clicked.
EVT_TREE_ITEM_MENU | The context menu for the selected item has been requested, either by a right click or by using the menu key.
EVT_TREE_ITEM_MIDDLE_CLICK | The user has clicked the item with the middle mouse button (not implemented in HyperTreeList).
EVT_TREE_ITEM_RIGHT_CLICK | The user has clicked the item with the right mouse button.
EVT_TREE_KEY_DOWN | A key has been pressed.
EVT_TREE_SEL_CHANGED | Selection has changed.
EVT_TREE_SEL_CHANGING | Selection is changing. This can be prevented by calling Veto.
EVT_TREE_SET_INFO | Information is being supplied to the application (not implemented in HyperTreeList).
EVT_TREE_STATE_IMAGE_CLICK | The state image has been clicked (not implemented in HyperTreeList).

license License And Version

HyperTreeList is distributed under the wxPython license.

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

Version 1.3

Module author: Andrea Gavana <andrea.gavana@gmail.com>

hierarchy Inheritance Diagram

Inheritance diagram for module: hypertreelist

Inheritance diagram of hypertreelist.EditCtrl, hypertreelist.EditTextCtrl, hypertreelist.HyperTreeList, hypertreelist.TreeListColumnInfo, hypertreelist.TreeListHeaderWindow, hypertreelist.TreeListItem, hypertreelist.TreeListMainWindow

SVN Revisions

A graphical representation of the SVN commits in the last year.

Click on any date in the picture to jump to that particular revision page, containing information about committers, log messages and SVN diffs.

Revision Graph For hypertreelist

2to3 Python 3 Issues (via 2to3)

No issues have been detected by 2to3.py.

Function Summary

  • IsBufferingSupported
  • create_delegator_for

Class Summary

  • EditCtrl
  • EditTextCtrl
  • HyperTreeList
  • TreeListColumnInfo
  • TreeListHeaderWindow
  • TreeListItem
  • TreeListMainWindow

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • infobar
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • hypertreelist


infobar

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • infobar

infobar

An info bar is a transient window shown at top or bottom of its parent window to display non-critical information to the user.

description Description

An info bar is a transient window shown at top or bottom of its parent window to display non-critical information to the user.

Note

The Python implementation of InfoBar is a direct translation of the generic C++ implementation of wx.InfoBar.

This class provides another way to show messages to the user, intermediate between message boxes and status bar messages. The message boxes are modal and thus interrupt the users work flow and should be used sparingly for this reason. However status bar messages are often too easy not to notice at all. An info bar provides a way to present the messages which has a much higher chance to be noticed by the user but without being annoying.

Info bar may show an icon (on the left), text message and, optionally, buttons allowing the user to react to the information presented. It always has a close button at the right allowing the user to dismiss it so it isn’t necessary to provide a button just to close it.

InfoBar calls its parent Layout() method (if its parent is not managed by AuiManager or wx.aui.AuiManager) and assumes that it will change the parent layout appropriately depending on whether the info bar itself is shown or hidden. Usually this is achieved by simply using a sizer for the parent window layout and adding wxInfoBar to this sizer as one of the items. Considering the usual placement of the info bars, normally this sizer should be a vertical wx.BoxSizer and the bar its first or last element.

base Base Functionalities

InfoBar supports all the wx.InfoBar generic implementation functionalities, and in addition it using AddButton it is possible to add a button with a bitmap (and not only a plain wx.Button).

For example:

info = InfoBar(parent)
bitmap = wx.Bitmap('nice_bitmap.png', wx.BITMAP_TYPE_PNG)

info.AddButton(wx.NewId(), 'New Button', bitmap)

usage Usage

The simplest possible example of using this class would be:

import wx
import wx.lib.agw.infobar as IB

class MyFrame(wx.Frame):

    def __init__(self, parent):

        wx.Frame.__init__(self, parent, -1, 'InfoBar Demo')

        self._infoBar = IB.InfoBar(self)

        sizer = wx.BoxSizer(wx.VERTICAL)
        sizer.AddF(self._infoBar, wx.SizerFlags().Expand())

        panel = wx.Panel(self)
        sizer.Add(panel, 1, wx.EXPAND)

        # ... Add other frame controls to the sizer ...
        self.SetSizer(sizer)

        wx.CallLater(2000, self.SomeMethod)

    def SomeMethod(self):

        self._infoBar.ShowMessage("Something happened", wx.ICON_INFORMATION)

# our normal wxApp-derived class, as usual

app = wx.PySimpleApp()

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

app.MainLoop()

This code snippet can be downloaded, see this example script.

Note

Some of the AGW snippets of code in the documentation use images and external files (to create bitmaps or access external data). As these files are not provided in these snippets, you should make the approriate modifications to the code to actually run it.

platforms Supported Platforms

InfoBar has been tested on the following platforms:
  • Windows (Vista/7).

styles Window Styles

No particular window styles are available for this class.

events Events Processing

This class processes the following events:

Events processing for infobar
Event Name | Description
wx.EVT_BUTTON | Process a wx.wxEVT_COMMAND_BUTTON_CLICKED event, when the button is clicked.

license License And Version

InfoBar control is distributed under the wxPython license.

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

Version 0.1

Module author: Andrea Gavana <andrea.gavana@gmail.com>

hierarchy Inheritance Diagram

Inheritance diagram for module: infobar

Inheritance diagram of infobar.InfoBar

SVN Revisions

A graphical representation of the SVN commits in the last year.

Click on any date in the picture to jump to that particular revision page, containing information about committers, log messages and SVN diffs.

Revision Graph For infobar

2to3 Python 3 Issues (via 2to3)

No issues have been detected by 2to3.py.

Function Summary

  • GetCloseButtonBitmap

Class Summary

  • InfoBar

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • infobar
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • infobar


knobctrl

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • knobctrl

knobctrl

KnobCtrl lets the user select a numerical value by rotating it.

description Description

KnobCtrl lets the user select a numerical value by rotating it. It works like a scrollbar: just set the ticks range property and read the value property in the associated EVT_KC_ANGLE_CHANGING/EVT_KC_ANGLE_CHANGED events. Simple but effective.

It can be easily used if you want to simulate the volume knob of a music player or similar functionalities.

usage Usage

Usage example:

import wx
import wx.lib.agw.knobctrl as KC

class MyFrame(wx.Frame):

    def __init__(self, parent):

        wx.Frame.__init__(self, parent, -1, "KnobCtrl Demo")

        panel = wx.Panel(self)

        knob1 = KC.KnobCtrl(panel, -1, size=(100, 100))
        knob2 = KC.KnobCtrl(panel, -1, size=(100, 100))

        knob1.SetTags(range(0, 151, 10))
        knob1.SetAngularRange(-45, 225)
        knob1.SetValue(45)

        knob2.SetTags(range(0, 151, 10))
        knob2.SetAngularRange(0, 270)
        knob2.SetValue(100)

        main_sizer = wx.BoxSizer(wx.VERTICAL)
        main_sizer.Add(knob1, 0, wx.EXPAND|wx.ALL, 20)
        main_sizer.Add(knob2, 0, wx.EXPAND|wx.ALL, 20)

        panel.SetSizer(main_sizer)
        main_sizer.Layout()

# our normal wxApp-derived class, as usual

app = wx.PySimpleApp()

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

app.MainLoop()

This code snippet can be downloaded, see this example script.

Note

Some of the AGW snippets of code in the documentation use images and external files (to create bitmaps or access external data). As these files are not provided in these snippets, you should make the approriate modifications to the code to actually run it.

events Events

KnobCtrl implements two events that can be intercepted by the user:

  • EVT_KC_ANGLE_CHANGING;
  • EVT_KC_ANGLE_CHANGED.

The first one can be “vetoed” by eliminating the event.Skip() at the end of the event handler.

platforms Supported Platforms

KnobCtrl has been tested on the following platforms:
  • Windows (Windows XP);
  • Linux Ubuntu (Dapper 6.06)

styles Window Styles

This class supports the following window styles:

Window styles for knobctrl
Window Styles | Hex Value | Description
KC_BUFFERED_DC | 0x1 | Flag to use double buffering (recommendeded = 1).

events Events Processing

This class processes the following events:

Events processing for knobctrl
Event Name | Description
EVT_KC_ANGLE_CHANGED | Notify the client that the knob has changed its value.
EVT_KC_ANGLE_CHANGING | Notify the client that the knob is changing its value.

license License And Version

KnobCtrl is distributed under the wxPython license.

Latest Revision: Andrea Gavana @ 17 Aug 2011, 15.00 GMT

Version 0.3

Module author: Andrea Gavana <andrea.gavana@gmail.com>

hierarchy Inheritance Diagram

Inheritance diagram for module: knobctrl

Inheritance diagram of knobctrl.BufferedWindow, knobctrl.KnobCtrl, knobctrl.KnobCtrlEvent

SVN Revisions

A graphical representation of the SVN commits in the last year.

Click on any date in the picture to jump to that particular revision page, containing information about committers, log messages and SVN diffs.

Revision Graph For knobctrl

2to3 Python 3 Issues (via 2to3)

No issues have been detected by 2to3.py.

Class Summary

  • BufferedWindow
  • KnobCtrl
  • KnobCtrlEvent

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • infobar
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • knobctrl


labelbook

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • labelbook

labelbook

LabelBook and FlatImageBook are a quasi-full generic and owner-drawn implementations of wx.Notebook.

description Description

LabelBook and FlatImageBook are quasi-full implementations of the wx.Notebook, and designed to be a drop-in replacement for wx.Notebook. The API functions are similar so one can expect the function to behave in the same way. LabelBook anf FlatImageBook share their appearance with wx.Toolbook and wx.Listbook, while having more options for custom drawings, label positioning, mouse pointing and so on. Moreover, they retain also some visual characteristics of the Outlook address book.

Some features:

  • They are generic controls;
  • Supports for left, right, top (FlatImageBook only), bottom (FlatImageBook only) book styles;
  • Possibility to draw images only, text only or both (FlatImageBook only);
  • Support for a “pin-button”, that allows the user to shrink/expand the book tab area;
  • Shadows behind tabs (LabelBook only);
  • Gradient shading of the tab area (LabelBook only);
  • Web-like mouse pointing on tabs style (LabelBook only);
  • Many customizable colours (tab area, active tab text, tab borders, active tab, highlight) - LabelBook only.

And much more. See the demo for a quasi-complete review of all the functionalities of LabelBook and FlatImageBook.

usage Usage

Usage example:

import wx
import wx.lib.agw.labelbook as LB

class MyFrame(wx.Frame):

    def __init__(self, parent):

        wx.Frame.__init__(self, parent, -1, "LabelBook Demo")

        # Possible values for Tab placement are INB_TOP, INB_BOTTOM, INB_RIGHT, INB_LEFT

        notebook = LB.LabelBook(self, -1, agwStyle=LB.INB_FIT_LABELTEXT|LB.INB_LEFT|LB.INB_DRAW_SHADOW|LB.INB_GRADIENT_BACKGROUND)

        pane1 = wx.Panel(notebook)
        pane2 = wx.Panel(notebook)

        imagelist = wx.ImageList(32, 32)
        imagelist.Add(wx.Bitmap("my_bitmap.png", wx.BITMAP_TYPE_PNG))
        notebook.AssignImageList(imagelist)

        notebook.AddPage(pane_1, "Tab1", 1, 0)
        notebook.AddPage(pane_2, "Tab2", 0, 0)

# our normal wxApp-derived class, as usual

app = wx.PySimpleApp()

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

app.MainLoop()

This code snippet can be downloaded, see this example script.

Note

Some of the AGW snippets of code in the documentation use images and external files (to create bitmaps or access external data). As these files are not provided in these snippets, you should make the approriate modifications to the code to actually run it.

platforms Supported Platforms

LabelBook and FlatImageBook have been tested on the following platforms:
  • Windows (Windows XP);
  • Linux Ubuntu (Dapper 6.06)

styles Window Styles

This class supports the following window styles:

Window styles for labelbook
Window Styles | Hex Value | Description
INB_BOTTOM | 0x1 | Place labels below the page area. Available only for FlatImageBook.
INB_LEFT | 0x2 | Place labels on the left side. Available only for FlatImageBook.
INB_RIGHT | 0x4 | Place labels on the right side.
INB_TOP | 0x8 | Place labels above the page area.
INB_BORDER | 0x10 | Draws a border around LabelBook or FlatImageBook.
INB_SHOW_ONLY_TEXT | 0x20 | Shows only text labels and no images. Available only for LabelBook.
INB_SHOW_ONLY_IMAGES | 0x40 | Shows only tab images and no label texts. Available only for LabelBook.
INB_FIT_BUTTON | 0x80 | Displays a pin button to show/hide the book control.
INB_DRAW_SHADOW | 0x100 | Draw shadows below the book tabs. Available only for LabelBook.
INB_USE_PIN_BUTTON | 0x200 | Displays a pin button to show/hide the book control.
INB_GRADIENT_BACKGROUND | 0x400 | Draws a gradient shading on the tabs background. Available only for LabelBook.
INB_WEB_HILITE | 0x800 | On mouse hovering, tabs behave like html hyperlinks. Available only for LabelBook.
INB_NO_RESIZE | 0x1000 | Don’t allow resizing of the tab area.
INB_FIT_LABELTEXT | 0x2000 | Will fit the tab area to the longest text (or text+image if you have images) in all the tabs.
INB_BOLD_TAB_SELECTION | 0x4000 | Show the selected tab text using a bold font.

events Events Processing

This class processes the following events:

Events processing for labelbook
Event Name | Description
EVT_IMAGENOTEBOOK_PAGE_CHANGED | Notify client objects when the active page in FlatImageBook or LabelBook has changed.
EVT_IMAGENOTEBOOK_PAGE_CHANGING | Notify client objects when the active page in FlatImageBook or LabelBook is about to change.
EVT_IMAGENOTEBOOK_PAGE_CLOSED | Notify client objects when a page in FlatImageBook or LabelBook has been closed.
EVT_IMAGENOTEBOOK_PAGE_CLOSING | Notify client objects when a page in FlatImageBook or LabelBook is closing.

todos TODOs

  • LabelBook: support IMB_SHOW_ONLY_IMAGES;
  • LabelBook: an option to only draw the border between the controls and the pages so the background colour can flow into the window background.

license License And Version

LabelBook and FlatImageBook are distributed under the wxPython license.

Latest Revision: Andrea Gavana @ 07 Dec 2011, 21.00 GMT

Version 0.6.

Module author: Andrea Gavana <andrea.gavana@gmail.com>

hierarchy Inheritance Diagram

Inheritance diagram for module: labelbook

Inheritance diagram of labelbook.FlatBookBase, labelbook.FlatImageBook, labelbook.ImageContainer, labelbook.ImageContainerBase, labelbook.ImageInfo, labelbook.ImageNotebookEvent, labelbook.LabelBook, labelbook.LabelContainer

SVN Revisions

A graphical representation of the SVN commits in the last year.

Click on any date in the picture to jump to that particular revision page, containing information about committers, log messages and SVN diffs.

Revision Graph For labelbook

2to3 Python 3 Issues (via 2to3)

No issues have been detected by 2to3.py.

Class Summary

  • FlatBookBase
  • FlatImageBook
  • ImageContainer
  • ImageContainerBase
  • ImageInfo
  • ImageNotebookEvent
  • LabelBook
  • LabelContainer

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • infobar
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • labelbook


multidirdialog

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • multidirdialog

multidirdialog

This class represents a possible replacement for wx.DirDialog, with the additional ability of selecting multiple folders at once.

description Description

This class represents a possible replacement for wx.DirDialog, with the additional ability of selecting multiple folders at once. It may be useful when you wish to present to the user a directory browser which allows multiple folder selections. MultiDirDialog sports the following features:

  • Ability to select a single or mutliple folders, depending on the style passed;
  • More colourful and eye-catching buttons;
  • Good old Python code :-D .

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

usage Usage

Usage example:

import os
import wx

import wx.lib.agw.multidirdialog as MDD

# Our normal wxApp-derived class, as usual
app = wx.App(0)

dlg = MDD.MultiDirDialog(None, title="Custom MultiDirDialog", defaultPath=os.getcwd(),
                         agwStyle=MDD.DD_MULTIPLE|MDD.DD_DIR_MUST_EXIST)

if dlg.ShowModal() != wx.ID_OK:
    print "You Cancelled The Dialog!"
    dlg.Destroy()
    return

paths = dlg.GetPaths()
for indx, path in enumerate(paths):
    print "Path %d: %s"%(indx+1, path)

dlg.Destroy()

app.MainLoop()

This code snippet can be downloaded, see this example script.

Note

Some of the AGW snippets of code in the documentation use images and external files (to create bitmaps or access external data). As these files are not provided in these snippets, you should make the approriate modifications to the code to actually run it.

platforms Supported Platforms

MultiDirDialog has been tested on the following platforms:
  • Windows (Windows XP).

styles Window Styles

This class supports the following window styles:

Window styles for multidirdialog
Window Styles | Hex Value | Description
DD_NEW_DIR_BUTTON | 0x000 | Enable/disable the “Make new folder” button
DD_DIR_MUST_EXIST | 0x200 | The dialog will allow the user to choose only an existing folder. When this style is not given, a “Create new directory” button is added to the dialog (on Windows) or some other way is provided to the user to type the name of a new folder.
DD_MULTIPLE | 0x400 | Allows the selection of multiple folders.

events Events Processing

No custom events are available for this class.

license License And Version

MultiDirDialog is distributed under the wxPython license.

Latest Revision: Andrea Gavana @ 17 Aug 2011, 15.00 GMT

Version 0.3

Module author: Andrea Gavana <andrea.gavana@gmail.com>

hierarchy Inheritance Diagram

Inheritance diagram for module: multidirdialog

Inheritance diagram of multidirdialog.MultiDirDialog

SVN Revisions

A graphical representation of the SVN commits in the last year.

Click on any date in the picture to jump to that particular revision page, containing information about committers, log messages and SVN diffs.

Revision Graph For multidirdialog

2to3 Python 3 Issues (via 2to3)

No issues have been detected by 2to3.py.

Class Summary

  • MultiDirDialog

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • infobar
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • multidirdialog


peakmeter

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • peakmeter

peakmeter

PeakMeterCtrl mimics the behaviour of equalizers that are usually found in stereos and MP3 players.

description Description

PeakMeterCtrl mimics the behaviour of equalizers that are usually found in stereos and MP3 players. This widgets supports:

  • Vertical and horizontal led bands;
  • Settings number of bands and leds per band;
  • Possibility to change the colour for low/medium/high band frequencies;
  • Falloff effects;
  • Showing a background grid for the bands.

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

usage Usage

Usage example:

import wx
import random

import wx.lib.agw.peakmeter as PM

class MyFrame(wx.Frame):

    def __init__(self, parent):

        wx.Frame.__init__(self, parent, -1, "PeakMeterCtrl Demo")

        panel = wx.Panel(self)

        # Initialize Peak Meter control 1
        self.vertPeak = PM.PeakMeterCtrl(panel, -1, style=wx.SIMPLE_BORDER, agwStyle=PM.PM_VERTICAL)
        # Initialize Peak Meter control 2
        self.horzPeak = PM.PeakMeterCtrl(panel, -1, style=wx.SUNKEN_BORDER, agwStyle=PM.PM_HORIZONTAL)

        self.vertPeak.SetMeterBands(10, 15)
        self.horzPeak.SetMeterBands(10, 15)

        # Layout the two PeakMeterCtrl
        mainSizer = wx.BoxSizer(wx.HORIZONTAL)
        mainSizer.Add(self.vertPeak, 0, wx.EXPAND|wx.ALL, 15)
        mainSizer.Add(self.horzPeak, 0, wx.EXPAND|wx.ALL, 15)

        panel.SetSizer(mainSizer)
        mainSizer.Layout()

        self.timer = wx.Timer(self)
        self.Bind(wx.EVT_TIMER, self.OnTimer)

        wx.CallLater(500, self.Start)

    def Start(self):
        ''' Starts the PeakMeterCtrl. '''

        self.timer.Start(1000/2)            # 2 fps

        self.vertPeak.Start(1000/18)        # 18 fps
        self.horzPeak.Start(1000/20)        # 20 fps

    def OnTimer(self, event):
        '''
        Handles the ``wx.EVT_TIMER`` event for :class:`~peakmeter.PeakMeterCtrl`.

        :param `event`: a `wx.TimerEvent` event to be processed.
        '''

        # Generate 15 random number and set them as data for the meter
        nElements = 15
        arrayData = []

        for i in xrange(nElements):
            nRandom = random.randint(0, 100)
            arrayData.append(nRandom)

        self.vertPeak.SetData(arrayData, 0, nElements)
        self.horzPeak.SetData(arrayData, 0, nElements)

# our normal wxApp-derived class, as usual

app = wx.PySimpleApp()

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

app.MainLoop()

This code snippet can be downloaded, see this example script.

Note

Some of the AGW snippets of code in the documentation use images and external files (to create bitmaps or access external data). As these files are not provided in these snippets, you should make the approriate modifications to the code to actually run it.

platforms Supported Platforms

PeakMeterCtrl has been tested on the following platforms:
  • Windows (Windows XP).

styles Window Styles

This class supports the following window styles:

Window styles for peakmeter
Window Styles | Hex Value | Description
PM_HORIZONTAL | 0x0 | Shows horizontal bands in PeakMeterCtrl.
PM_VERTICAL | 0x1 | Shows vertical bands in PeakMeterCtrl.

events Events Processing

No custom events are available for this class.

license License And Version

PeakMeterCtrl is distributed under the wxPython license.

Latest Revision: Andrea Gavana @ 17 Aug 2011, 15.00 GMT

Version 0.3

Module author: Andrea Gavana <andrea.gavana@gmail.com>

hierarchy Inheritance Diagram

Inheritance diagram for module: peakmeter

Inheritance diagram of peakmeter.PeakMeterCtrl, peakmeter.PeakMeterData

SVN Revisions

A graphical representation of the SVN commits in the last year.

Click on any date in the picture to jump to that particular revision page, containing information about committers, log messages and SVN diffs.

Revision Graph For peakmeter

2to3 Python 3 Issues (via 2to3)

No issues have been detected by 2to3.py.

Function Summary

  • DarkenColour
  • InRange
  • LightenColour

Class Summary

  • PeakMeterCtrl
  • PeakMeterData

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • infobar
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • peakmeter


persist library

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • persist library

persist library

description Introduction

Persistent objects are simply the objects which automatically save their state when they are destroyed and restore it when they are recreated, even during another program invocation.

viewmag Persistent Object Overview

Most often, persistent objects are, in fact, persistent windows as it is especially convenient to automatically restore the UI state when the program is restarted but an object of any class can be made persistent. Moreover, persistence is implemented in a non-intrusive way so that the original object class doesn’t need to be modified at all in order to add support for saving and restoring its properties.

The persistence framework involves:

  • PersistenceManager which all persistent objects register themselves with. This class handles actual saving and restoring of persistent data as well as various global aspects of persistence, e.g. it can be used to disable restoring the saved data;
  • PersistentObject is the base class for all persistent objects or, rather, adaptors for the persistent objects as this class main purpose is to provide the bridge between the original class – which has no special persistence support – and PersistenceManager;
  • PersistentHandlers which handle different kind of saving/restoring actions depending on the widget kind.

usage Using Persistent Windows

wxPython has built-in support for a (constantly growing) number of controls. Currently the following classes are supported:

  • wx.TopLevelWindow (and hence wx.Frame and wx.Dialog, together with their own AUI perspectives);
  • wx.MenuBar, FlatMenuBar;
  • AuiToolBar;
  • wx.Notebook, wx.Toolbook, wx.Treebook, wx.Choicebook, wx.aui.AuiNotebook, AuiNotebook (together with its own AUI perspective), FlatNotebook, LabelBook, FlatImageBook;
  • wx.CheckBox;
  • wx.ListBox, wx.VListBox, wx.HtmlListBox, wx.SimpleHtmlListBox, wx.gizmos.EditableListBox;
  • wx.ListCtrl, wx.ListView, UltimateListCtrl;
  • wx.CheckListBox;
  • wx.Choice, wx.ComboBox, wx.combo.OwnerDrawnComboBox;
  • wx.RadioBox;
  • wx.RadioButton;
  • wx.ScrolledWindow, wx.lib.scrolledpanel.ScrolledPanel;
  • wx.Slider, KnobCtrl;
  • wx.SpinButton, wx.SpinCtrl, FloatSpin;
  • wx.SplitterWindow;
  • wx.TextCtrl, wx.SearchCtrl, wx.lib.expando.ExpandoTextCtrl, wx.lib.masked.Ctrl;
  • wx.ToggleButton, wx.lib.buttons.GenToggleButton, wx.lib.buttons.GenBitmapToggleButton, wx.lib.buttons.GenBitmapTextToggleButton, SToggleButton, SBitmapToggleButton, SBitmapTextToggleButton;
  • wx.TreeCtrl, wx.GenericDirCtrl, CustomTreeCtrl;
  • wx.gizmos.TreeListCtrl, HyperTreeList;
  • wx.lib.calendar.CalendarCtrl;
  • wx.CollapsiblePane;
  • wx.DatePickerCtrl, wx.GenericDatePickerCtrl;
  • wx.media.MediaCtrl;
  • wx.ColourPickerCtrl, wx.lib.colourselect.ColourSelect;
  • wx.FilePickerCtrl, wx.DirPickerCtrl;
  • wx.FontPickerCtrl;
  • wx.FileHistory;
  • wx.DirDialog, wx.FileDialog;
  • wx.FindReplaceDialog;
  • wx.FontDialog;
  • wx.ColourDialog, CubeColourDialog;
  • FoldPanelBar;
  • wx.SingleChoiceDialog, wx.MultiChoiceDialog;
  • wx.TextEntryDialog, wx.PasswordEntryDialog.

To automatically save and restore the properties of the windows of classes listed above you need to:

  • Set a unique name for the window using SetName(): this step is important as the name is used in the configuration file and so must be unique among all windows of the same class;
  • Call PersistenceManager.Register(window) at any moment after creating the window and then PersistenceManager.Restore(window) when the settings may be restored (which can’t be always done immediately, e.g. often the window needs to be populated first). If settings can be restored immediately after the window creation, as is often the case for wx.TopLevelWindow, for example, then PersistenceManager.RegisterAndRestore(window) can be used to do both at once.
  • If you want the settings for the window to be saved when your main frame is destroyed (or your app closes), simply call PersistenceManager.SaveAndUnregister(window) with no arguments.

usage Usage

Example of using a notebook control which automatically remembers the last open page:

import wx
import wx.lib.agw.persist as PM

class MyFrame(wx.Frame):

    def __init__(self, parent):

        wx.Frame.__init(self, parent, -1, "Persistent Controls Demo")

        book = wx.Notebook(self, wx.ID_ANY)

        # Very important step!!
        book.SetName("MyBook") # Do not use the default name!!

        book.AddPage(wx.Panel(book), "Hello")
        book.AddPage(wx.Panel(book), "World")

        if not PM.PersistenceManager.RegisterAndRestore(book):
            # Nothing was restored, so choose the default page ourselves
            book.SetSelection(0)

# our normal wxApp-derived class, as usual

app = wx.PySimpleApp()

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

app.MainLoop()

This code snippet can be downloaded, see this example script.

Note

Some of the AGW snippets of code in the documentation use images and external files (to create bitmaps or access external data). As these files are not provided in these snippets, you should make the approriate modifications to the code to actually run it.

viewmag Defining Custom Persistent Windows

User-defined classes can be easily integrated with PersistenceManager. To add support for your custom class MyWidget you just need to:

  • Define a MyWidgetHandler class inheriting from AbstractHandler;
  • Implement its GetKind() method returning a unique string identifying all MyWidget objects, typically something like “widget”;
  • Implement its Save() and Restore() methods to actually save and restore the widget settings using PersistentObject.SaveValue() and PersistentObject.RestoreValue() methods.

If you want to add persistence support for a class not deriving from wx.Window, you need to derive MyPersistentWidget directly from PersistentObject and so implement its PersistentObject.GetName() method too. Additionally, you must ensure that PersistenceManager.SaveAndUnregister() is called when your object is destroyed as this can be only done automatically for windows.

todos TODOs

  • Find a way to handle wx.ToolBar UI settings as it has been done for AuiToolBar: current wx.ToolBar doesn’t seem to have easy access to the underlying toolbar tools;
  • Implement handler(s) for wx.grid.Grid for row/columns sizes (possibly adding another style to PersistenceManager as wx.grid.Grid sets up arrays to store individual row and column sizes when non-default sizes are used. The memory requirements for this could become prohibitive if the grid is very large);
  • Find a way to properly save and restore dialog data (wx.ColourDialog, wx.FontDialog etc...);
  • Add handlers for the remaining widgets not yet wrapped (mostly in wx.lib).

license License And Version

PersistentObjects library is distributed under the wxPython license.

Latest revision: Andrea Gavana @ 24 Oct 2011, 21.00 GMT Version 0.4.

Module author: Andrea Gavana <andrea.gavana@gmail.com>

hierarchy Inheritance Diagram

Inheritance diagram for library: persist

Inheritance diagram of persist.persist_handlers, persist.persistencemanager

Module Summary

  • persist_handlers
  • persistencemanager

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • infobar
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • persist library


piectrl

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • piectrl

piectrl

PieCtrl and ProgressPie are simple classes that reproduce the behavior of a pie chart.

description Description

PieCtrl and ProgressPie are simple classes that reproduce the behavior of a pie chart. They use only pure wxPython classes/methods, without external dependencies. PieCtrl is somewhat a “static” control, that you may create in order to display a simple pie chart on a wx.Panel or similar. ProgressPie tries to emulate the behavior of wx.ProgressDialog, but using a pie chart instead of a gauge.

usage Usage

Usage example:

import wx
import wx.lib.agw.piectrl as PC

class MyFrame(wx.Frame):

    def __init__(self, parent):

        wx.Frame.__init__(self, parent, -1, "PieCtrl Demo")

        panel = wx.Panel(self)

        # create a simple PieCtrl with 3 sectors
        mypie = PC.PieCtrl(panel, -1, wx.DefaultPosition, wx.Size(180,270))

        part = PC.PiePart()

        part.SetLabel("Label 1")
        part.SetValue(300)
        part.SetColour(wx.Colour(200, 50, 50))
        mypie._series.append(part)

        part = PC.PiePart()

        part.SetLabel("Label 2")
        part.SetValue(200)
        part.SetColour(wx.Colour(50, 200, 50))
        mypie._series.append(part)

        part = PC.PiePart()

        part.SetLabel("helloworld label 3")
        part.SetValue(50)
        part.SetColour(wx.Colour(50, 50, 200))
        mypie._series.append(part)

        # create a ProgressPie
        progress_pie = PC.ProgressPie(panel, 100, 50, -1, wx.DefaultPosition,
                                      wx.Size(180, 200), wx.SIMPLE_BORDER)

        progress_pie.SetBackColour(wx.Colour(150, 200, 255))
        progress_pie.SetFilledcolour(wx.Colour(255, 0, 0))
        progress_pie.SetUnfilledColour(wx.WHITE)
        progress_pie.SetHeight(20)

        main_sizer = wx.BoxSizer(wx.HORIZONTAL)

        main_sizer.Add(mypie, 1, wx.EXPAND | wx.ALL, 5)
        main_sizer.Add(progress_pie, 1, wx.EXPAND | wx.ALL, 5)

        panel.SetSizer(main_sizer)
        main_sizer.Layout()

# our normal wxApp-derived class, as usual

app = wx.PySimpleApp()

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

app.MainLoop()

This code snippet can be downloaded, see this example script.

Note

Some of the AGW snippets of code in the documentation use images and external files (to create bitmaps or access external data). As these files are not provided in these snippets, you should make the approriate modifications to the code to actually run it.

settings Methods and Settings

With PieCtrl you can:

  • Create a PieCtrl with different sectors;
  • Set the sector values, colours and labels;
  • Assign a legend to the PieCtrl;
  • Use an image as the PieCtrl background;
  • Change the vertical rotation (perspective) of the PieCtrl;
  • Show/hide the segment edges.

styles Window Styles

No particular window styles are available for this class.

events Events Processing

No custom events are available for this class.

license License And Version

PieCtrl is distributed under the wxPython license.

Latest revision: Andrea Gavana @ 17 Aug 2011, 15.00 GMT

Version 0.2

Module author: Andrea Gavana <andrea.gavana@gmail.com>

hierarchy Inheritance Diagram

Inheritance diagram for module: piectrl

Inheritance diagram of piectrl.PieCtrl, piectrl.PieCtrlLegend, piectrl.PiePart, piectrl.ProgressPie

SVN Revisions

A graphical representation of the SVN commits in the last year.

Click on any date in the picture to jump to that particular revision page, containing information about committers, log messages and SVN diffs.

Revision Graph For piectrl

2to3 Python 3 Issues (via 2to3)

No issues have been detected by 2to3.py.

Class Summary

  • PieCtrl
  • PieCtrlLegend
  • PiePart
  • ProgressPie

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • infobar
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • piectrl


pybusyinfo

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • pybusyinfo

pybusyinfo

PyBusyInfo constructs a busy info window and displays a message in it.

description Description

PyBusyInfo constructs a busy info window and displays a message in it.

This class makes it easy to tell your user that the program is temporarily busy. Just create a PyBusyInfo object, and within the current scope, a message window will be shown.

For example:

busy = PyBusyInfo("Please wait, working...")

for i in xrange(10000):
    DoACalculation()

del busy

It works by creating a window in the constructor, and deleting it in the destructor. You may also want to call wx.Yield() to refresh the window periodically (in case it had been obscured by other windows, for example).

usage Usage

Usage example:

import wx
import wx.lib.agw.pybusyinfo as PBI

class MyFrame(wx.Frame):

    def __init__(self, parent):

        wx.Frame.__init__(self, parent, -1, "PyBusyInfo Demo")

        panel = wx.Panel(self)

        b = wx.Button(panel, -1, "Test PyBusyInfo ", (50,50))
        self.Bind(wx.EVT_BUTTON, self.OnButton, b)

    def OnButton(self, event):

        message = "Please wait 5 seconds, working..."
        busy = PBI.PyBusyInfo(message, parent=self, title="Really Busy")

        wx.Yield()

        for indx in xrange(5):
            wx.MilliSleep(1000)

        del busy

# our normal wxApp-derived class, as usual

app = wx.PySimpleApp()

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

app.MainLoop()

This code snippet can be downloaded, see this example script.

Note

Some of the AGW snippets of code in the documentation use images and external files (to create bitmaps or access external data). As these files are not provided in these snippets, you should make the approriate modifications to the code to actually run it.

platforms Supported Platforms

PyBusyInfo has been tested on the following platforms:
  • Windows (Windows XP).

styles Window Styles

No particular window styles are available for this class.

events Events Processing

No custom events are available for this class.

license License And Version

PyBusyInfo is distributed under the wxPython license.

Latest Revision: Andrea Gavana @ 17 Aug 2011, 15.00 GMT

Version 0.1

Module author: Andrea Gavana <andrea.gavana@gmail.com>

hierarchy Inheritance Diagram

Inheritance diagram for module: pybusyinfo

Inheritance diagram of pybusyinfo.PyBusyInfo, pybusyinfo.PyInfoFrame

SVN Revisions

A graphical representation of the SVN commits in the last year.

Click on any date in the picture to jump to that particular revision page, containing information about committers, log messages and SVN diffs.

Revision Graph For pybusyinfo

2to3 Python 3 Issues (via 2to3)

No issues have been detected by 2to3.py.

Class Summary

  • PyBusyInfo
  • PyInfoFrame

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • infobar
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • pybusyinfo


pycollapsiblepane

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • pycollapsiblepane

pycollapsiblepane

PyCollapsiblePane is a container with an embedded button-like control which can be used by the user to collapse or expand the pane’s contents.

description Description

A collapsible pane is a container with an embedded button-like control which can be used by the user to collapse or expand the pane’s contents. Once constructed you should use the GetPane function to access the pane and add your controls inside it (i.e. use the window returned from GetPane as the parent for the controls which must go in the pane, not the PyCollapsiblePane itself!).

Note

Note that because of its nature of control which can dynamically (and drastically) change its size at run-time under user-input, when putting PyCollapsiblePane inside a wx.Sizer you should be careful to add it with a proportion value of zero; this is because otherwise all other windows with non-null proportion values would automatically get resized each time the user expands or collapse the pane window resulting usually in a weird, flickering effect.

usage Usage

Usage example:

import wx
import wx.lib.agw.pycollapsiblepane as PCP

class MyFrame(wx.Frame):

    def __init__(self, parent):

        wx.Frame.__init__(self, parent, -1, "PyCollapsiblePane Demo")

        panel = wx.Panel(self)

        title = wx.StaticText(panel, label="PyCollapsiblePane")
        title.SetFont(wx.Font(18, wx.SWISS, wx.NORMAL, wx.BOLD))
        title.SetForegroundColour("blue")

        self.cp = cp = PCP.PyCollapsiblePane(panel, label=label1,
                                             style=wx.CP_DEFAULT_STYLE|wx.CP_NO_TLW_RESIZE)

        self.MakePaneContent(cp.GetPane())

        sizer = wx.BoxSizer(wx.VERTICAL)
        sizer.Add(title, 0, wx.ALL, 25)
        sizer.Add(cp, 0, wx.RIGHT|wx.LEFT|wx.EXPAND, 25)

        panel.SetSizer(sizer)
        sizer.Layout()

    def MakePaneContent(self, pane):
        ''' Just makes a few controls to put on `PyCollapsiblePane`. '''

        nameLbl = wx.StaticText(pane, -1, "Name:")
        name = wx.TextCtrl(pane, -1, "");

        addrLbl = wx.StaticText(pane, -1, "Address:")
        addr1 = wx.TextCtrl(pane, -1, "");
        addr2 = wx.TextCtrl(pane, -1, "");

        cstLbl = wx.StaticText(pane, -1, "City, State, Zip:")
        city  = wx.TextCtrl(pane, -1, "", size=(150,-1));
        state = wx.TextCtrl(pane, -1, "", size=(50,-1));
        zip   = wx.TextCtrl(pane, -1, "", size=(70,-1));

        addrSizer = wx.FlexGridSizer(cols=2, hgap=5, vgap=5)
        addrSizer.AddGrowableCol(1)
        addrSizer.Add(nameLbl, 0,
                      wx.ALIGN_RIGHT|wx.ALIGN_CENTER_VERTICAL)
        addrSizer.Add(name, 0, wx.EXPAND)
        addrSizer.Add(addrLbl, 0,
                      wx.ALIGN_RIGHT|wx.ALIGN_CENTER_VERTICAL)
        addrSizer.Add(addr1, 0, wx.EXPAND)
        addrSizer.Add((5,5))
        addrSizer.Add(addr2, 0, wx.EXPAND)

        addrSizer.Add(cstLbl, 0,
                      wx.ALIGN_RIGHT|wx.ALIGN_CENTER_VERTICAL)

        cstSizer = wx.BoxSizer(wx.HORIZONTAL)
        cstSizer.Add(city, 1)
        cstSizer.Add(state, 0, wx.LEFT|wx.RIGHT, 5)
        cstSizer.Add(zip)
        addrSizer.Add(cstSizer, 0, wx.EXPAND)

        border = wx.BoxSizer()
        border.Add(addrSizer, 1, wx.EXPAND|wx.ALL, 5)
        pane.SetSizer(border)

# our normal wxApp-derived class, as usual

app = wx.PySimpleApp()

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

app.MainLoop()

This code snippet can be downloaded, see this example script.

Note

Some of the AGW snippets of code in the documentation use images and external files (to create bitmaps or access external data). As these files are not provided in these snippets, you should make the approriate modifications to the code to actually run it.

styles Window Styles

This class supports the following window styles:

Window styles for pycollapsiblepane
Window Styles | Hex Value | Description
CP_NO_TLW_RESIZE | 0x2 | By default PyCollapsiblePane resizes the top level window containing it when its own size changes. This allows to easily implement dialogs containing an optionally shown part, for example, and so is the default behaviour but can be inconvenient in some specific cases – use this flag to disable this automatic parent resizing then.
CP_GTK_EXPANDER | 0x4 | Uses a GTK expander instead of a button.
CP_USE_STATICBOX | 0x8 | Uses a wx.StaticBox around PyCollapsiblePane.
CP_LINE_ABOVE | 0x10 | Draws a line above PyCollapsiblePane.

events Events Processing

This class processes the following events:

Events processing for pycollapsiblepane
Event Name | Description
EVT_COLLAPSIBLEPANE_CHANGED | The user showed or hid the collapsible pane.

license License And Version

PyCollapsiblePane is distributed under the wxPython license.

Latest Revision: Andrea Gavana @ 17 Aug 2011, 15.00 GMT

Version 0.4

Module author: Andrea Gavana <andrea.gavana@gmail.com>

hierarchy Inheritance Diagram

Inheritance diagram for module: pycollapsiblepane

Inheritance diagram of pycollapsiblepane.GTKExpander, pycollapsiblepane.PyCollapsiblePane

SVN Revisions

A graphical representation of the SVN commits in the last year.

Click on any date in the picture to jump to that particular revision page, containing information about committers, log messages and SVN diffs.

Revision Graph For pycollapsiblepane

2to3 Python 3 Issues (via 2to3)

No issues have been detected by 2to3.py.

Class Summary

  • GTKExpander
  • PyCollapsiblePane

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • infobar
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • pycollapsiblepane


pygauge

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • pygauge

pygauge

PyGauge is a generic wx.Gauge implementation.

description Description

PyGauge supports the determinate mode functions as wx.Gauge and adds an Update function which takes a value and a time parameter. The value is added to the current value over a period of time milliseconds.

usage Usage

Usage example:

import wx
import wx.lib.agw.pygauge as PG

class MyFrame(wx.Frame):

    def __init__(self, parent):

        wx.Frame.__init__(self, parent, -1, "PyGauge Demo")

        panel = wx.Panel(self)

        gauge1 = PG.PyGauge(panel, -1, size=(100, 25), style=wx.GA_HORIZONTAL)
        gauge1.SetValue(80)
        gauge1.SetBackgroundColour(wx.WHITE)
        gauge1.SetBorderColor(wx.BLACK)

        gauge2 = PG.PyGauge(panel, -1, size=(100, 25), style=wx.GA_HORIZONTAL)
        gauge2.SetValue([20, 80])
        gauge2.SetBarColor([wx.Colour(162, 255, 178), wx.Colour(159, 176, 255)])
        gauge2.SetBackgroundColour(wx.WHITE)
        gauge2.SetBorderColor(wx.BLACK)
        gauge2.SetBorderPadding(2)
        gauge2.Update([30, 0], 2000)

        gauge3 = PG.PyGauge(panel, -1, size=(100, 25), style=wx.GA_HORIZONTAL)
        gauge3.SetValue(50)
        gauge3.SetBarColor(wx.GREEN)
        gauge3.SetBackgroundColour(wx.WHITE)
        gauge3.SetBorderColor(wx.BLACK)

        sizer = wx.BoxSizer(wx.VERTICAL)
        sizer.Add(gauge1, 0, wx.ALIGN_CENTER_VERTICAL|wx.ALL, 20)
        sizer.Add(gauge2, 0, wx.ALIGN_CENTER_VERTICAL|wx.ALL, 20)
        sizer.Add(gauge3, 0, wx.ALIGN_CENTER_VERTICAL|wx.ALL, 20)

        panel.SetSizer(sizer)
        sizer.Layout()

# our normal wxApp-derived class, as usual

app = wx.PySimpleApp()

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

app.MainLoop()

This code snippet can be downloaded, see this example script.

Note

Some of the AGW snippets of code in the documentation use images and external files (to create bitmaps or access external data). As these files are not provided in these snippets, you should make the approriate modifications to the code to actually run it.

platforms Supported Platforms

PyGauge has been tested on the following platforms:
  • Windows (Windows XP);

license License And Version

PyGauge is distributed under the wxPython license.

PyGauge has been kindly contributed to the AGW library by Mark Reed.

Latest Revision: Andrea Gavana @ 17 Aug 2011, 15.00 GMT

Version 0.1

Module author: Andrea Gavana <andrea.gavana@gmail.com>

hierarchy Inheritance Diagram

Inheritance diagram for module: pygauge

Inheritance diagram of pygauge.PyGauge

SVN Revisions

A graphical representation of the SVN commits in the last year.

Click on any date in the picture to jump to that particular revision page, containing information about committers, log messages and SVN diffs.

Revision Graph For pygauge

2to3 Python 3 Issues (via 2to3)

No issues have been detected by 2to3.py.

Class Summary

  • PyGauge

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • infobar
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • pygauge


pyprogress

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • pyprogress

pyprogress

PyProgress is similar to wx.ProgressDialog in indeterminated mode, but with a different gauge appearance and a different spinning behavior.

description Description

PyProgress is similar to wx.ProgressDialog in indeterminated mode, but with a different gauge appearance and a different spinning behavior. The moving gauge can be drawn with a single solid colour or with a shading gradient foreground. The gauge background colour is user customizable.

The bar does not move always from the beginning to the end as in wx.ProgressDialog in indeterminated mode, but spins cyclically forward and backward.

Other options include:

  • Possibility to change the proportion between the spinning bar and the entire gauge, so that the bar can be longer or shorter (the default is 20%);
  • Modifying the number of steps the spinning bar performs before a forward (or backward) loop reverses.

PyProgress can optionally display a Cancel button, and a wx.StaticText which outputs the elapsed time from the starting of the process.

usage Usage

Usage example:

import wx
import wx.lib.agw.pyprogress as PP

# Our normal wxApp-derived class, as usual
app = wx.App(0)

dlg = PP.PyProgress(None, -1, "PyProgress Example",
                    "An Informative Message",
                    agwStyle=wx.PD_APP_MODAL|wx.PD_ELAPSED_TIME)

dlg.SetGaugeProportion(0.2)
dlg.SetGaugeSteps(50)
dlg.SetGaugeBackground(wx.WHITE)
dlg.SetFirstGradientColour(wx.WHITE)
dlg.SetSecondGradientColour(wx.BLUE)

max = 400
keepGoing = True
count = 0

while keepGoing and count < max:
    count += 1
    wx.MilliSleep(30)

    if count >= max / 2:
        keepGoing = dlg.UpdatePulse("Half-time!")
    else:
        keepGoing = dlg.UpdatePulse()

dlg.Destroy()

app.MainLoop()

This code snippet can be downloaded, see this example script.

Note

Some of the AGW snippets of code in the documentation use images and external files (to create bitmaps or access external data). As these files are not provided in these snippets, you should make the approriate modifications to the code to actually run it.

platforms Supported Platforms

PyProgress has been tested on the following platforms:
  • Windows (Windows XP);
  • Linux Ubuntu (Dapper 6.06)

styles Window Styles

This class supports the following window styles:

Window styles for pyprogress
Window Styles | Hex Value | Description
PD_CAN_ABORT | 0x1 | This flag tells the dialog that it should have a Cancel button which the user may press. If this happens, the next call to Update will return False.
PD_APP_MODAL | 0x2 | Make the progress dialog modal. If this flag is not given, it is only ‘locally’ modal - that is the input to the parent window is disabled, but not to the other ones.
PD_AUTO_HIDE | 0x4 | Causes the progress dialog to disappear from screen as soon as the maximum value of the progress meter has been reached.
PD_ELAPSED_TIME | 0x8 | This flag tells the dialog that it should show elapsed time (since creating the dialog).

events Events Processing

No custom events are available for this class.

license License And Version

PyProgress is distributed under the wxPython license.

Latest Revision: Andrea Gavana @ 17 Aug 2011, 15.00 GMT

Version 0.4

Module author: Andrea Gavana <andrea.gavana@gmail.com>

hierarchy Inheritance Diagram

Inheritance diagram for module: pyprogress

Inheritance diagram of pyprogress.ProgressGauge, pyprogress.PyProgress

SVN Revisions

A graphical representation of the SVN commits in the last year.

Click on any date in the picture to jump to that particular revision page, containing information about committers, log messages and SVN diffs.

Revision Graph For pyprogress

2to3 Python 3 Issues (via 2to3)

No issues have been detected by 2to3.py.

Class Summary

  • ProgressGauge
  • PyProgress

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • infobar
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • pyprogress


ribbon library

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • ribbon library

ribbon library

The RibbonBar library is a set of classes for writing a ribbon user interface.

description Description

At the most generic level, this is a combination of a tab control with a toolbar. At a more functional level, it is similar to the user interface present in recent versions of Microsoft Office.

A ribbon user interface typically has a RibbonBar, which contains one or more RibbonPage, which in turn each contains one or more RibbonPanel, which in turn contain controls.

usage Usage

Usage example:

import wx
import wx.lib.agw.ribbon as RB

class MyFrame(wx.Frame):

    def __init__(self, parent, id=-1, title="Ribbon Demo", pos=wx.DefaultPosition,
                 size=(800, 600), style=wx.DEFAULT_FRAME_STYLE):

        wx.Frame.__init__(self, parent, id, title, pos, size, style)

        self._ribbon = RB.RibbonBar(self, wx.ID_ANY)

        home = RB.RibbonPage(self._ribbon, wx.ID_ANY, "Examples", CreateBitmap("ribbon"))
        toolbar_panel = RB.RibbonPanel(home, wx.ID_ANY, "Toolbar", wx.NullBitmap, wx.DefaultPosition,
                                       wx.DefaultSize, agwStyle=RB.RIBBON_PANEL_NO_AUTO_MINIMISE)

        toolbar = RB.RibbonToolBar(toolbar_panel, ID_MAIN_TOOLBAR)
        toolbar.AddTool(wx.ID_ANY, CreateBitmap("align_left"))
        toolbar.AddTool(wx.ID_ANY, CreateBitmap("align_center"))
        toolbar.AddTool(wx.ID_ANY, CreateBitmap("align_right"))
        toolbar.AddSeparator()
        toolbar.AddHybridTool(wx.ID_NEW, wx.ArtProvider.GetBitmap(wx.ART_NEW, wx.ART_OTHER, wx.Size(16, 15)))
        toolbar.AddTool(wx.ID_ANY, wx.ArtProvider.GetBitmap(wx.ART_FILE_OPEN, wx.ART_OTHER, wx.Size(16, 15)))
        toolbar.AddTool(wx.ID_ANY, wx.ArtProvider.GetBitmap(wx.ART_FILE_SAVE, wx.ART_OTHER, wx.Size(16, 15)))
        toolbar.AddTool(wx.ID_ANY, wx.ArtProvider.GetBitmap(wx.ART_FILE_SAVE_AS, wx.ART_OTHER, wx.Size(16, 15)))
        toolbar.AddSeparator()
        toolbar.AddDropdownTool(wx.ID_UNDO, wx.ArtProvider.GetBitmap(wx.ART_UNDO, wx.ART_OTHER, wx.Size(16, 15)))
        toolbar.AddDropdownTool(wx.ID_REDO, wx.ArtProvider.GetBitmap(wx.ART_REDO, wx.ART_OTHER, wx.Size(16, 15)))
        toolbar.AddSeparator()
        toolbar.AddTool(wx.ID_ANY, wx.ArtProvider.GetBitmap(wx.ART_REPORT_VIEW, wx.ART_OTHER, wx.Size(16, 15)))
        toolbar.AddTool(wx.ID_ANY, wx.ArtProvider.GetBitmap(wx.ART_LIST_VIEW, wx.ART_OTHER, wx.Size(16, 15)))
        toolbar.AddSeparator()
        toolbar.AddHybridTool(ID_POSITION_LEFT, CreateBitmap("position_left"),
                              "Align ribbonbar vertically on the left for demonstration purposes")
        toolbar.AddHybridTool(ID_POSITION_TOP, CreateBitmap("position_top"),
                              "Align the ribbonbar horizontally at the top for demonstration purposes")
        toolbar.AddSeparator()
        toolbar.AddHybridTool(wx.ID_PRINT, wx.ArtProvider.GetBitmap(wx.ART_PRINT, wx.ART_OTHER, wx.Size(16, 15)),
                              "This is the Print button tooltip demonstrating a tooltip")
        toolbar.SetRows(2, 3)

        selection_panel = RB.RibbonPanel(home, wx.ID_ANY, "Selection", CreateBitmap("selection_panel"))
        selection = RB.RibbonButtonBar(selection_panel)
        selection.AddSimpleButton(ID_SELECTION_EXPAND_V, "Expand Vertically", CreateBitmap("expand_selection_v"),
                                  "This is a tooltip for Expand Vertically demonstrating a tooltip")
        selection.AddSimpleButton(ID_SELECTION_EXPAND_H, "Expand Horizontally", CreateBitmap("expand_selection_h"), "")
        selection.AddSimpleButton(ID_SELECTION_CONTRACT, "Contract", CreateBitmap("auto_crop_selection"),
                                  CreateBitmap("auto_crop_selection_small"))

        shapes_panel = RB.RibbonPanel(home, wx.ID_ANY, "Shapes", CreateBitmap("circle_small"))
        shapes = RB.RibbonButtonBar(shapes_panel)

        # Show toggle buttons behaviour
        shapes.AddButton(ID_CIRCLE, "Circle", CreateBitmap("circle"), CreateBitmap("circle_small"),
                         help_string="This is a tooltip for the circle button demonstrating another tooltip",
                         kind=RB.RIBBON_BUTTON_TOGGLE)

        shapes.AddSimpleButton(ID_CROSS, "Cross", CreateBitmap("cross"), "")
        shapes.AddHybridButton(ID_TRIANGLE, "Triangle", CreateBitmap("triangle"))
        shapes.AddSimpleButton(ID_SQUARE, "Square", CreateBitmap("square"), "")
        shapes.AddDropdownButton(ID_POLYGON, "Other Polygon", CreateBitmap("hexagon"), "")

        sizer_panel = RB.RibbonPanel(home, wx.ID_ANY, "Panel with Sizer",
                                     wx.NullBitmap, wx.DefaultPosition, wx.DefaultSize,
                                     agwStyle=RB.RIBBON_PANEL_DEFAULT_STYLE)

        scheme = RB.RibbonPage(self._ribbon, wx.ID_ANY, "Appearance", CreateBitmap("eye"))
        self._default_primary, self._default_secondary, self._default_tertiary = self._ribbon.GetArtProvider().GetColourScheme(1, 1, 1)

        provider_panel = RB.RibbonPanel(scheme, wx.ID_ANY, "Art", wx.NullBitmap, wx.DefaultPosition, wx.DefaultSize,
                                        agwStyle=RB.RIBBON_PANEL_NO_AUTO_MINIMISE)
        provider_bar = RB.RibbonButtonBar(provider_panel, wx.ID_ANY)
        provider_bar.AddSimpleButton(ID_DEFAULT_PROVIDER, "Default Provider",
                                     wx.ArtProvider.GetBitmap(wx.ART_QUESTION, wx.ART_OTHER, wx.Size(32, 32)), "")
        provider_bar.AddSimpleButton(ID_AUI_PROVIDER, "AUI Provider", CreateBitmap("aui_style"), "")
        provider_bar.AddSimpleButton(ID_MSW_PROVIDER, "MSW Provider", CreateBitmap("msw_style"), "")

        primary_panel = RB.RibbonPanel(scheme, wx.ID_ANY, "Primary Colour", CreateBitmap("colours"))
        self._primary_gallery = self.PopulateColoursPanel(primary_panel, self._default_primary, ID_PRIMARY_COLOUR)

        secondary_panel = RB.RibbonPanel(scheme, wx.ID_ANY, "Secondary Colour", CreateBitmap("colours"))
        self._secondary_gallery = self.PopulateColoursPanel(secondary_panel, self._default_secondary, ID_SECONDARY_COLOUR)

        dummy_2 = RB.RibbonPage(self._ribbon, wx.ID_ANY, "Empty Page", CreateBitmap("empty"))
        dummy_3 = RB.RibbonPage(self._ribbon, wx.ID_ANY, "Another Page", CreateBitmap("empty"))

        self._ribbon.Realize()

        self._logwindow = wx.TextCtrl(self, wx.ID_ANY, "", wx.DefaultPosition, wx.DefaultSize,
                                      wx.TE_MULTILINE | wx.TE_READONLY | wx.TE_LEFT | wx.TE_BESTWRAP | wx.BORDER_NONE)

        s = wx.BoxSizer(wx.VERTICAL)

        s.Add(self._ribbon, 0, wx.EXPAND)
        s.Add(self._logwindow, 1, wx.EXPAND)

        self.SetSizer(s)

# our normal wxApp-derived class, as usual

app = wx.PySimpleApp()

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

app.MainLoop()

This code snippet can be downloaded, see this example script.

Note

Some of the AGW snippets of code in the documentation use images and external files (to create bitmaps or access external data). As these files are not provided in these snippets, you should make the approriate modifications to the code to actually run it.

whatsnew What’s New

Current wxRibbon Version Tracked: wxWidgets 2.9.2 (SVN HEAD)

New features recently implemented:

  • Possibility to hide panels in the RibbonBar;
  • Added the EVT_RIBBONBAR_TAB_LEFT_DCLICK event, which generates a special event when a ribbon bar tab is double-clicked;
  • Added support for toggle buttons in the RibbonBar;
  • Improved support for ribbon panel sizers: panels with sizers should now automatically minimise at small sizes, and behave properly when popping up from a minimised state;
  • Added tooltips via SetToolTip for those buttons which have the help_string attribute set.

license License And Version

RIBBON library is distributed under the wxPython license.

Latest revision: Andrea Gavana @ 17 Aug 2011, 15.00 GMT

Version 0.2.

Module author: Andrea Gavana <andrea.gavana@gmail.com>

hierarchy Inheritance Diagram

Inheritance diagram for library: ribbon

Inheritance diagram of ribbon.art_aui, ribbon.art_internal, ribbon.art_msw, ribbon.bar, ribbon.buttonbar, ribbon.control, ribbon.gallery, ribbon.page, ribbon.panel, ribbon.toolbar

Module Summary

  • art_aui
  • art_internal
  • art_msw
  • bar
  • buttonbar
  • control
  • gallery
  • page
  • panel
  • toolbar

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • infobar
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • ribbon library


rulerctrl

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • rulerctrl

rulerctrl

RulerCtrl implements a ruler window that can be placed on top, bottom, left or right to any wxPython widget.

description Description

RulerCtrl implements a ruler window that can be placed on top, bottom, left or right to any wxPython widget. It is somewhat similar to the rulers you can find in text editors software, though not so powerful.

RulerCtrl has the following characteristics:

  • Can be horizontal or vertical;
  • 4 built-in formats: integer, real, time and linearDB formats;
  • Units (as cm, dB, inches) can be displayed together with the label values;
  • Possibility to add a number of “paragraph indicators”, small arrows that point at the current indicator position;
  • Customizable background colour, tick colour, label colour;
  • Possibility to flip the ruler (i.e. changing the tick alignment);
  • Changing individually the indicator colour (requires PIL at the moment);
  • Different window borders are supported (wx.STATIC_BORDER, wx.SUNKEN_BORDER, wx.DOUBLE_BORDER, wx.NO_BORDER, wx.RAISED_BORDER, wx.SIMPLE_BORDER);
  • Logarithmic scale available;
  • Possibility to draw a thin line over a selected window when moving an indicator, which emulates the text editors software.

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

usage Usage

Usage example:

import wx
import wx.lib.agw.rulerctrl as RC

class MyFrame(wx.Frame):

    def __init__(self, parent):

        wx.Frame.__init__(self, parent, -1, "RulerCtrl Demo")

        panel = wx.Panel(self)

        text = wx.TextCtrl(panel, -1, "Hello World! wxPython rules", style=wx.TE_MULTILINE)

        ruler1 = RC.RulerCtrl(panel, -1, orient=wx.HORIZONTAL, style=wx.SUNKEN_BORDER)
        ruler2 = RC.RulerCtrl(panel, -1, orient=wx.VERTICAL, style=wx.SUNKEN_BORDER)

        mainsizer = wx.BoxSizer(wx.HORIZONTAL)
        leftsizer = wx.BoxSizer(wx.VERTICAL)
        bottomleftsizer = wx.BoxSizer(wx.HORIZONTAL)
        topsizer = wx.BoxSizer(wx.HORIZONTAL)

        leftsizer.Add((20, 20), 0, wx.ADJUST_MINSIZE, 0)
        topsizer.Add((39, 0), 0, wx.ADJUST_MINSIZE, 0)
        topsizer.Add(ruler1, 1, wx.EXPAND, 0)
        leftsizer.Add(topsizer, 0, wx.EXPAND, 0)

        bottomleftsizer.Add((10, 0))
        bottomleftsizer.Add(ruler2, 0, wx.EXPAND, 0)
        bottomleftsizer.Add(text, 1, wx.EXPAND, 0)
        leftsizer.Add(bottomleftsizer, 1, wx.EXPAND, 0)
        mainsizer.Add(leftsizer, 3, wx.EXPAND, 0)

        panel.SetSizer(mainsizer)

# our normal wxApp-derived class, as usual

app = wx.PySimpleApp()

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

app.MainLoop()

This code snippet can be downloaded, see this example script.

Note

Some of the AGW snippets of code in the documentation use images and external files (to create bitmaps or access external data). As these files are not provided in these snippets, you should make the approriate modifications to the code to actually run it.

events Events

RulerCtrl implements the following events related to indicators:

  • EVT_INDICATOR_CHANGING: the user is about to change the position of one indicator;
  • EVT_INDICATOR_CHANGED: the user has changed the position of one indicator.

platforms Supported Platforms

RulerCtrl has been tested on the following platforms:
  • Windows (Windows XP);
  • Linux Ubuntu (Dapper 6.06)

styles Window Styles

No particular window styles are available for this class.

events Events Processing

This class processes the following events:

Events processing for rulerctrl
Event Name | Description
EVT_INDICATOR_CHANGED | The user has changed the indicator value.
EVT_INDICATOR_CHANGING | The user is about to change the indicator value.

license License And Version

RulerCtrl is distributed under the wxPython license.

Latest Revision: Andrea Gavana @ 17 Aug 2011, 15.00 GMT

Version 0.3

Module author: Andrea Gavana <andrea.gavana@gmail.com>

hierarchy Inheritance Diagram

Inheritance diagram for module: rulerctrl

Inheritance diagram of rulerctrl.Indicator, rulerctrl.Label, rulerctrl.RulerCtrl, rulerctrl.RulerCtrlEvent

SVN Revisions

A graphical representation of the SVN commits in the last year.

Click on any date in the picture to jump to that particular revision page, containing information about committers, log messages and SVN diffs.

Revision Graph For rulerctrl

2to3 Python 3 Issues (via 2to3)

No issues have been detected by 2to3.py.

Function Summary

  • ConvertPILToWX
  • ConvertWXToPIL
  • GetIndicatorBitmap
  • GetIndicatorData
  • GetIndicatorImage
  • MakePalette

Class Summary

  • Indicator
  • Label
  • RulerCtrl
  • RulerCtrlEvent

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • infobar
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • rulerctrl


shapedbutton

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • shapedbutton

shapedbutton

ShapedButton tries to fill the lack of “custom shaped” controls in wxPython and it can be used to build round or elliptic-shaped buttons.

description Description

ShapedButton tries to fill the lack of “custom shaped” controls in wxPython (that depends on the same lack in wxWidgets). It can be used to build round buttons or elliptic buttons.

I have stolen some code from wx.lib.buttons in order to recreate the same classes (GenButton, GenBitmapButton, GenBitmapTextButton, GenToggleButton, GenBitmapToggleButton, GenBitmapTextToggleButton). Here you have the same classes (with “Gen” replaced by “S”), with the same event handling, but they are rounded/elliptical buttons.

ShapedButton is based on a wx.Window, in which 2 images are drawn depending on the button state (pressed or not pressed). The 2 images have been stolen from Audacity (written with wxWidgets) and rearranged/reshaped/restyled using adobe PhotoShop. Changing the button colour in runtime was more difficult, but using some intelligent instruction from the PIL library it can be done.

ShapedButton reacts on mouse events only if the mouse event occurred inside the circle/ellipse, even if ShapedButton is built on a rectangular window. This behavior is a lot different with respect to Audacity round buttons.

usage Usage

Usage example:

import wx
import wx.lib.agw.shapedbutton as SB

class MyFrame(wx.Frame):

    def __init__(self, parent):

        wx.Frame.__init__(self, parent, -1, "ShapedButton Demo")

        panel = wx.Panel(self)

        # Create 2 bitmaps for the button
        upbmp = wx.Bitmap("play.png", wx.BITMAP_TYPE_PNG)
        disbmp = wx.Bitmap("playdisabled.png", wx.BITMAP_TYPE_PNG)

        play = SB.SBitmapToggleButton(panel, -1, upbmp, (100, 50))
        play.SetUseFocusIndicator(False)
        play.SetBitmapDisabled(disbmp)

# our normal wxApp-derived class, as usual

app = wx.PySimpleApp()

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

app.MainLoop()

This code snippet can be downloaded, see this example script.

Note

Some of the AGW snippets of code in the documentation use images and external files (to create bitmaps or access external data). As these files are not provided in these snippets, you should make the approriate modifications to the code to actually run it.

The ShapedButton construction and usage is quite similar to the wx.lib.buttons implementation.

settings Methods and Settings

With ShapedButton you can:

  • Create rounded/elliptical buttons/togglebuttons;
  • Set images for the enabled/disabled/focused/selected state of the button;
  • Draw the focus indicator (or disable it);
  • Set label colour and font;
  • Apply a rotation to the ShapedButton label;
  • Change ShapedButton shape and text orientation in runtime.

Note

ShapedButton requires PIL (Python Imaging Library) library to be installed, which can be downloaded from http://www.pythonware.com/products/pil/ .

styles Window Styles

No particular window styles are available for this class.

events Events Processing

This class processes the following events:

Events processing for shapedbutton
Event Name | Description
wx.EVT_BUTTON | Process a wx.wxEVT_COMMAND_BUTTON_CLICKED event, when the button is clicked.

license License And Version

ShapedButton is distributed under the wxPython license.

Latest revision: Andrea Gavana @ 16 Jan 2012, 20.00 GMT

Version 0.4

Module author: Andrea Gavana <andrea.gavana@gmail.com>

hierarchy Inheritance Diagram

Inheritance diagram for module: shapedbutton

Inheritance diagram of shapedbutton.SBitmapButton, shapedbutton.SBitmapTextButton, shapedbutton.SBitmapTextToggleButton, shapedbutton.SBitmapToggleButton, shapedbutton.SButton, shapedbutton.SButtonEvent, shapedbutton.SToggleButton, shapedbutton.__SToggleMixin

SVN Revisions

A graphical representation of the SVN commits in the last year.

Click on any date in the picture to jump to that particular revision page, containing information about committers, log messages and SVN diffs.

Revision Graph For shapedbutton

2to3 Python 3 Issues (via 2to3)

No issues have been detected by 2to3.py.

Function Summary

  • opj

Class Summary

  • SBitmapButton
  • SBitmapTextButton
  • SBitmapTextToggleButton
  • SBitmapToggleButton
  • SButton
  • SButtonEvent
  • SToggleButton
  • __SToggleMixin

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • infobar
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • shapedbutton


shortcuteditor

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • shortcuteditor

shortcuteditor

ShortcutEditor is a widget that allows the user to customize and change keyboard shortcuts via a dialog. It can be used to edit wx.MenuItem shortcuts or accelerators defined in a wx.AcceleratorTable.

Note

ShortcutEditor requires the minimum AGW version 0.9.3 or the current SVN, for the various enhancements made to the HyperTreeList and GenericMessageDialog widgets.

description Description

ShortcutEditor is a widget that allows the user to customize and change keyboard shortcuts via a dialog. It can be used to edit wx.MenuItem shortcuts or accelerators defined in a wx.AcceleratorTable.

The interface itself is very much inpired by the GIMP shortcut editor:

http://graphicssoft.about.com/od/gimptutorials/tp/keyboard-shortcut-editor.htm

There are very few minor UI differences between ShortcutEditor and the GIMP one, although the behaviour should be pretty much equivalent.

Various features:

  • Shortcuts are listed in a tree-like structure, pretty much reflecting a menu hierarchy (as most of the time ShortcutEditor is used to edit wx.MenuItem shortcuts);
  • Accelerators defined via wx.AcceleratorTable are handled in a similar way;
  • Support for I18N;
  • Ability to restore default shortcuts/accelerators via a UI button;
  • Possibility to send back the new/updated shortcuts to the original wx.MenuBar or the original wx.AcceleratorTable;
  • Filters on the shortcuts label (case-insensitive);
  • Basic help window with instructions (customizable via SetHTMLHelpFile), via the Help button.

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

interface UI Interactions

  1. In the ShortcutEditor dialog you can open sub-sections by clicking the small box with a + sign in it next to each section name. In the screen grab, you can see I’ve opened the Options sub-section as I’m going to add a keyboard shortcut to the OptionsItem 1 item.

    Figure 1

  2. Now you need to scroll to the tool or command that you want to edit and click on it to select it. When selected, the text for that tool in the Shortcut column changes to read ‘New accelerator...’ and you can press the key or combination of keys you want to assign as a shortcut.

    Figure 2

  3. I’ve changed the OptionsItem 1‘s keyboard shortcut to Shift+Ctrl+F by pressing the Shift, Ctrl and F keys simultaneously. If you want to remove a keyboard shortcut from any tool or command, just click on it to select it and then when the ‘New accelerator...’ text displays, press the backspace key and the text will change to ‘Disabled’.

    Once you’re happy that your keyboard shortcuts are set up as you wish, simply click the OK button.

    Figure 3

  4. If you thought my choice of Shift+Ctrl+F was an odd selection, I chose it because it was a keyboard combination that hadn’t already been assigned to any tool or command. If you try to assign a keyboard shortcut that is already in use, an alert will open telling you what the shortcut is currently being used for. If you want to keep the original shortcut, just click the Cancel button, otherwise click Reassign shortcut to make the shortcut apply to your new selection.

    Figure 4

base Base Functionalities

There are basically three ways to populate the ShortcutEditor dialog, depending on your needs. These approaches can be combined if needed.

  1. Use the FromMenuBar method: if you need to give your user the ability to edit the various wx.MenuItem shortcuts in your application, you can create ShortcutEditor in this way:

    # Build your wx.MenuBar first!!!
# "self" is an instance of wx.TopLevelWindow

dlg = ShortcutEditor(self)
dlg.FromMenuBar(self)

# Here the user will make all the various modifications
# to the shortcuts

if dlg.ShowModal() == wx.ID_OK:
    # Changes accepted, send back the new shortcuts to
    # the TLW wx.MenuBar
    dlg.ToMenuBar(self)

dlg.Destroy()

  2. Use the FromAcceleratorTable method: if you need to give your user the ability to edit the various accelerators you set via wx.AcceleratorTable in your application, you can create ShortcutEditor in this way:

    # Build your wx.AcceleratorTable first!!!
# "accelTable" is a list of tuples (4 elements per tuple)

accelTable = []

# Every tuple is defined in this way:

for label, flags, keyCode, cmdID in my_accelerators:
    # label:   the string used to show the accelerator into the ShortcutEditor dialog
    # flags:   a bitmask of wx.ACCEL_ALT, wx.ACCEL_SHIFT, wx.ACCEL_CTRL, wx.ACCEL_CMD,
    #          or wx.ACCEL_NORMAL used to specify which modifier keys are held down
    # keyCode: the keycode to be detected (i.e., ord('b'), wx.WXK_F10, etc...)
    # cmdID:   the menu or control command ID to use for the accelerator event.

    accel_tuple = (label, flags, keyCode, cmdID)
    accelTable.append(accel_tuple)

dlg = ShortcutEditor(self)
dlg.FromAcceleratorTable(accelTable)

# Here the user will make all the various modifications
# to the shortcuts

if dlg.ShowModal() == wx.ID_OK:
    # Changes accepted, send back the new shortcuts to
    # the window with the wx.AcceleratorTable:
    dlg.ToAcceleratorTable(self)

dlg.Destroy()

  3. Build your own hierarchy of shortcuts using GetShortcutManager:

    dlg = ShortcutEditor(self)
manager = dlg.GetShortcutManager()

for label, accelerator, bitmap, help, cmdID in my_list:
    shortcut = Shortcut(label, accelerator, bitmap, help, accelId=cmdID)
    manager.AppendItem(shortcut)

dlg.ShowModal()
dlg.Destroy()

usage Usage

Usage example:

import wx
import wx.lib.agw.shortcuteditor as SE

class MyFrame(wx.Frame):

    def __init__(self, parent):

        wx.Frame.__init(self, parent, -1, "ShortcutEditor Demo")

        bar = wx.MenuBar()
        menu = wx.Menu()

        menu.Append(101, "&Mercury", "This the text in the Statusbar")
        menu.Append(102, "&Venus", "")
        menu.Append(103, "&Earth", "You may select Earth too")
        menu.AppendSeparator()
        menu.Append(104, "&Close", "Close this frame")

        bar.Append(menu, 'File')
        self.SetMenuBar(bar)

        dlg = SE.ShortcutEditor(self)
        dlg.FromMenuBar(self)

        if dlg.ShowModal() == wx.ID_OK:
            # Changes accepted, send back the new shortcuts to the TLW wx.MenuBar
            dlg.ToMenuBar(self)

        dlg.Destroy()

# our normal wxApp-derived class, as usual

app = wx.PySimpleApp()

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

app.MainLoop()

This code snippet can be downloaded, see this example script.

Note

Some of the AGW snippets of code in the documentation use images and external files (to create bitmaps or access external data). As these files are not provided in these snippets, you should make the approriate modifications to the code to actually run it.

styles Window Styles

No particular window styles are available for this class.

events Events Processing

This class processes the following events:

Events processing for shortcuteditor
Event Name | Description
EVT_SHORTCUT_CHANGING | Event emitted when the user is about to change a shortcut.
EVT_SHORTCUT_CHANGED | Event emitted when the user has changed a shortcut.

platforms Supported Platforms

ShortcutEditor has been tested on the following platforms:
  • Windows (Windows Vista/7);

license License And Version

ShortcutEditor is distributed under the wxPython license.

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

Version 0.1

New in version 0.9.3.

Module author: Andrea Gavana <andrea.gavana@gmail.com>

hierarchy Inheritance Diagram

Inheritance diagram for module: shortcuteditor

Inheritance diagram of shortcuteditor.ConflictDialog, shortcuteditor.HTMLHelpWindow, shortcuteditor.ListShortcut, shortcuteditor.Shortcut, shortcuteditor.ShortcutEditor, shortcuteditor.ShortcutEvent

SVN Revisions

A graphical representation of the SVN commits in the last year.

Click on any date in the picture to jump to that particular revision page, containing information about committers, log messages and SVN diffs.

Revision Graph For shortcuteditor

2to3 Python 3 Issues (via 2to3)

No issues have been detected by 2to3.py.

Function Summary

  • FontFromFont

Class Summary

  • ConflictDialog
  • HTMLHelpWindow
  • ListShortcut
  • Shortcut
  • ShortcutEditor
  • ShortcutEvent

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • infobar
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • shortcuteditor


speedmeter

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • speedmeter

speedmeter

SpeedMeter tries to reproduce the behavior of some car controls (but not only), by creating an “angular” control (actually, circular).

description Description

SpeedMeter tries to reproduce the behavior of some car controls (but not only), by creating an “angular” control (actually, circular). I remember to have seen it somewhere, and i decided to implement it in wxPython.

SpeedMeter starts its construction from an empty bitmap, and it uses some functions of the wx.DC class to create the rounded effects. everything is processed in the Draw() method of SpeedMeter class.

This implementation allows you to use either directly the wx.PaintDC, or the better (for me) double buffered style with wx.BufferedPaintDC. the double buffered implementation has been adapted from the wxPython wiki example:

http://wiki.wxpython.org/index.cgi/doublebuffereddrawing

usage Usage

Usage example:

import wx
import wx.lib.agw.speedmeter as SM

class MyFrame(wx.Frame):

    def __init__(self, parent):

        wx.Frame.__init__(self, parent, -1, "SpeedMeter Demo")

        speed = SM.SpeedMeter(self, agwStyle=SM.SM_DRAW_HAND|SM.SM_DRAW_SECTORS|SM.SM_DRAW_MIDDLE_TEXT|SM.SM_DRAW_SECONDARY_TICKS)

        # Set The Region Of Existence Of SpeedMeter (Always In Radians!!!!)
        speed.SetAngleRange(-pi/6, 7*pi/6)

        # Create The Intervals That Will Divide Our SpeedMeter In Sectors
        intervals = range(0, 201, 20)
        speed.SetIntervals(intervals)

        # Assign The Same Colours To All Sectors (We Simulate A Car Control For Speed)
        # Usually This Is Black
        colours = [wx.BLACK]*10
        speed.SetIntervalColours(colours)

        # Assign The Ticks: Here They Are Simply The String Equivalent Of The Intervals
        ticks = [str(interval) for interval in intervals]
        speed.SetTicks(ticks)
        # Set The Ticks/Tick Markers Colour
        speed.SetTicksColour(wx.WHITE)
        # We Want To Draw 5 Secondary Ticks Between The Principal Ticks
        speed.SetNumberOfSecondaryTicks(5)

        # Set The Font For The Ticks Markers
        speed.SetTicksFont(wx.Font(7, wx.SWISS, wx.NORMAL, wx.NORMAL))

        # Set The Text In The Center Of SpeedMeter
        speed.SetMiddleText("Km/h")
        # Assign The Colour To The Center Text
        speed.SetMiddleTextColour(wx.WHITE)
        # Assign A Font To The Center Text
        speed.SetMiddleTextFont(wx.Font(8, wx.SWISS, wx.NORMAL, wx.BOLD))

        # Set The Colour For The Hand Indicator
        speed.SetHandColour(wx.Colour(255, 50, 0))

        # Do Not Draw The External (Container) Arc. Drawing The External Arc May
        # Sometimes Create Uglier Controls. Try To Comment This Line And See It
        # For Yourself!
        speed.DrawExternalArc(False)

        # Set The Current Value For The SpeedMeter
        speed.SetSpeedValue(44)

# our normal wxApp-derived class, as usual

app = wx.PySimpleApp()

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

app.MainLoop()

This code snippet can be downloaded, see this example script.

Note

Some of the AGW snippets of code in the documentation use images and external files (to create bitmaps or access external data). As these files are not provided in these snippets, you should make the approriate modifications to the code to actually run it.

settings Methods and Settings

SpeedMeter is highly customizable, and in particular you can set:

  • The start and end angle of existence for SpeedMeter;
  • The intervals in which you divide the SpeedMeter (numerical values);
  • The corresponding thicks for the intervals;
  • The interval colours (different intervals may have different filling colours);
  • The ticks font and colour;
  • The background colour (outsize the SpeedMeter region);
  • The external arc colour;
  • The hand (arrow) colour;
  • The hand’s shadow colour;
  • The hand’s style (“arrow” or “hand”);
  • The partial filler colour;
  • The number of secondary (intermediate) ticks;
  • The direction of increasing speed (“advance” or “reverse”);
  • The text to be drawn in the middle and its font;
  • The icon to be drawn in the middle;
  • The first and second gradient colours (that fills the SpeedMeter control);
  • The current value.

styles Window Styles

This class supports the following window styles:

Window styles for speedmeter
Window Styles | Hex Value | Description
SM_ROTATE_TEXT | 0x1 | Draws the ticks rotated: the ticks are rotated accordingly to the tick marks positions.
SM_DRAW_SECTORS | 0x2 | Different intervals are painted in differend colours (every sector of the circle has its own colour).
SM_DRAW_PARTIAL_SECTORS | 0x4 | Every interval has its own colour, but only a circle corona is painted near the ticks.
SM_DRAW_HAND | 0x8 | The hand (arrow indicator) is drawn.
SM_DRAW_SHADOW | 0x10 | A shadow for the hand is drawn.
SM_DRAW_PARTIAL_FILLER | 0x20 | A circle corona that follows the hand position is drawn near the ticks.
SM_DRAW_SECONDARY_TICKS | 0x40 | Intermediate (smaller) ticks are drawn between principal ticks.
SM_DRAW_MIDDLE_TEXT | 0x80 | Some text is printed in the middle of the control near the center.
SM_DRAW_MIDDLE_ICON | 0x100 | An icon is drawn in the middle of the control near the center.
SM_DRAW_GRADIENT | 0x200 | A gradient of colours will fill the control.
SM_DRAW_FANCY_TICKS | 0x400 | With this style you can use xml tags to create some custom text and draw it at the ticks position. See wx.lib.fancytext for the tags.

events Events Processing

No custom events are available for this class.

license License And Version

SpeedMeter is distributed under the wxPython license.

Latest revision: Andrea Gavana @ 17 Aug 2011, 15.00 GMT

Version 0.3

Module author: Andrea Gavana <andrea.gavana@gmail.com>

hierarchy Inheritance Diagram

Inheritance diagram for module: speedmeter

Inheritance diagram of speedmeter.BufferedWindow, speedmeter.SpeedMeter

SVN Revisions

A graphical representation of the SVN commits in the last year.

Click on any date in the picture to jump to that particular revision page, containing information about committers, log messages and SVN diffs.

Revision Graph For speedmeter

2to3 Python 3 Issues (via 2to3)

No issues have been detected by 2to3.py.

Class Summary

  • BufferedWindow
  • SpeedMeter

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • infobar
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • speedmeter


supertooltip

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • supertooltip

supertooltip

SuperToolTip is a class that mimics the behaviour of wx.TipWindow and generic tooltip windows, although it is a custom-drawn widget.

description Description

SuperToolTip is a class that mimics the behaviour of wx.TipWindow and generic tooltip windows, although it is a custom-drawn widget.

This class supports:

  • Blended triple-gradient for the tooltip background;
  • Header text and header image, with possibility to set the header font indipendently;
  • Footer text and footer image, with possibility to set the footer font indipendently;
  • Multiline text message in the tooltip body, plus an optional image as “body image”;
  • Bold lines and hyperlink lines in the tooltip body;
  • A wide set of predefined drawing styles for the tooltip background;
  • Drawing of separator lines after the header and/or before the footer;
  • Rounded corners and shadows below the tooltip window (Windows XP only);
  • Fade in/fade out effects (Windows XP only);
  • User-settable delays for the delay after which the tooltip appears and the delay after which the tooltip is destroyed.

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

usage Usage

Usage example:

import wx
import wx.lib.agw.supertooltip as STT

class MyFrame(wx.Frame):

    def __init__(self, parent):

        wx.Frame.__init__(self, parent, -1, "SuperToolTip Demo")

        panel = wx.Panel(self)
        button = wx.Button(panel, -1, "I am the SuperToolTip target", pos=(100, 50))

        tip = STT.SuperToolTip("A nice tooltip message")

        tip.SetHeader("Hello World")
        tip.SetTarget(button)
        tip.SetDrawHeaderLine(True)

        tip.ApplyStyle("Office 2007 Blue")

        tip.SetDropShadow(True)

# our normal wxApp-derived class, as usual

app = wx.PySimpleApp()

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

app.MainLoop()

This code snippet can be downloaded, see this example script.

Note

Some of the AGW snippets of code in the documentation use images and external files (to create bitmaps or access external data). As these files are not provided in these snippets, you should make the approriate modifications to the code to actually run it.

platforms Supported Platforms

SuperToolTip has been tested on the following platforms:
  • Windows (Windows XP).

styles Window Styles

No particular window styles are available for this class.

events Events Processing

No custom events are available for this class.

license License And Version

SuperToolTip is distributed under the wxPython license.

Latest Revision: Andrea Gavana @ 14 Sep 2011, 21.00 GMT

Version 0.4

Module author: Andrea Gavana <andrea.gavana@gmail.com>

hierarchy Inheritance Diagram

Inheritance diagram for module: supertooltip

Inheritance diagram of supertooltip.SuperToolTip, supertooltip.ToolTipWindow, supertooltip.ToolTipWindowBase

SVN Revisions

A graphical representation of the SVN commits in the last year.

Click on any date in the picture to jump to that particular revision page, containing information about committers, log messages and SVN diffs.

Revision Graph For supertooltip

2to3 Python 3 Issues (via 2to3)

No issues have been detected by 2to3.py.

Function Summary

  • ExtractLink
  • GetStyleKeys
  • MakeBold

Class Summary

  • SuperToolTip
  • ToolTipWindow
  • ToolTipWindowBase

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • infobar
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • supertooltip


thumbnailctrl

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • thumbnailctrl

thumbnailctrl

ThumbnailCtrl is a widget that can be used to display a series of images in a “thumbnail” format.

description Description

ThumbnailCtrl is a widget that can be used to display a series of images in a “thumbnail” format; it mimics, for example, the windows explorer behavior when you select the “view thumbnails” option. Basically, by specifying a folder that contains some image files, the files in the folder are displayed as miniature versions of the actual images in a wx.ScrolledWindow.

The code is partly based on wxVillaLib, a wxWidgets implementation of this control. However, ThumbnailCtrl wouldn’t have been so fast and complete without the suggestions and hints from Peter Damoc. So, if he accepts the mention, this control is his as much as mine.

usage Usage

Usage example:

import os

import wx
import wx.lib.agw.thumbnailctrl as TC

class MyFrame(wx.Frame):

    def __init__(self, parent):

        wx.Frame.__init__(self, parent, -1, "ThumbnailCtrl Demo")

        panel = wx.Panel(self)

        sizer = wx.BoxSizer(wx.VERTICAL)

        thumbnail = TC.ThumbnailCtrl(panel, imagehandler=TC.NativeImageHandler)
        sizer.Add(thumbnail, 1, wx.EXPAND | wx.ALL, 10)

        thumbnail.ShowDir(os.getcwd())
        panel.SetSizer(sizer)

# our normal wxApp-derived class, as usual

app = wx.PySimpleApp()

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

app.MainLoop()

This code snippet can be downloaded, see this example script.

Note

Some of the AGW snippets of code in the documentation use images and external files (to create bitmaps or access external data). As these files are not provided in these snippets, you should make the approriate modifications to the code to actually run it.

settings Methods and Settings

With ThumbnailCtrl you can:

  • Create different thumbnail outlines (none, images only, full, etc...);
  • Highlight thumbnails on mouse hovering;
  • Show/hide file names below thumbnails;
  • Change thumbnail caption font;
  • Zoom in/out thumbnails (done via Ctrl key + mouse wheel or with + and - chars, with zoom factor value customizable);
  • Rotate thumbnails with these specifications:
    1. d key rotates 90 degrees clockwise;
    2. s key rotates 90 degrees counter-clockwise;
    3. a key rotates 180 degrees.
  • Delete files/thumbnails (via the del key);
  • Drag and drop thumbnails from ThumbnailCtrl to whatever application you want;
  • Use local (when at least one thumbnail is selected) or global (no need for thumbnail selection) popup menus;
  • Show/hide a wx.ComboBox at the top of ThumbnailCtrl: this combobox contains working directory information and it has history entries;
  • possibility to show tooltips on thumbnails, which display file information (like file name, size, last modification date and thumbnail size).

Note

Using highlight thumbnails on mouse hovering may be slow on slower computers.

styles Window Styles

No particular window styles are available for this class.

events Events Processing

This class processes the following events:

Events processing for thumbnailctrl
Event Name | Description
EVT_THUMBNAILS_CAPTION_CHANGED | The thumbnail caption has been changed. Not used at present.
EVT_THUMBNAILS_DCLICK | The user has double-clicked on a thumbnail.
EVT_THUMBNAILS_POINTED | The mouse cursor is hovering over a thumbnail.
EVT_THUMBNAILS_SEL_CHANGED | The user has changed the selected thumbnail.
EVT_THUMBNAILS_THUMB_CHANGED | The thumbnail of an image has changed. Used internally.

license License And Version

ThumbnailCtrl is distributed under the wxPython license.

Latest revision: Andrea Gavana @ 17 Aug 2011, 15.00 GMT

Version 0.9

Module author: Andrea Gavana <andrea.gavana@gmail.com>

hierarchy Inheritance Diagram

Inheritance diagram for module: thumbnailctrl

Inheritance diagram of thumbnailctrl.NativeImageHandler, thumbnailctrl.PILImageHandler, thumbnailctrl.ScrolledThumbnail, thumbnailctrl.Thumb, thumbnailctrl.ThumbnailCtrl, thumbnailctrl.ThumbnailEvent

SVN Revisions

A graphical representation of the SVN commits in the last year.

Click on any date in the picture to jump to that particular revision page, containing information about committers, log messages and SVN diffs.

Revision Graph For thumbnailctrl

2to3 Python 3 Issues (via 2to3)

No issues have been detected by 2to3.py.

Function Summary

  • CmpThumb
  • GetMondrianBitmap
  • GetMondrianData
  • GetMondrianImage
  • SortFiles
  • getDataBL
  • getDataSH
  • getDataTR
  • getShadow
  • opj

Class Summary

  • NativeImageHandler
  • PILImageHandler
  • ScrolledThumbnail
  • Thumb
  • ThumbnailCtrl
  • ThumbnailEvent

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • infobar
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • thumbnailctrl


toasterbox

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • toasterbox

toasterbox

ToasterBox is a cross-platform widget to make the creation of MSN style “toaster” popups easier.

description Description

ToasterBox is a cross-platform widget to make the creation of MSN style “toaster” popups easier. The syntax is really easy especially if you are familiar with the syntax of wxPython.

It has 2 main styles:

  • TB_SIMPLE: using this style, you will be able to specify a background image for ToasterBox, text properties as text colour, font and label;
  • TB_COMPLEX: this style will allow you to put almost any control inside a ToasterBox. You can add a panel in which you can put all the controls you like.

Both styles support the setting of ToasterBox position (on screen coordinates), size, the time after which the ToasterBox is destroyed (linger), and the scroll speed of ToasterBox.

usage Usage

Usage example:

import wx
import wx.lib.agw.toasterbox as TB

class MyFrame(wx.Frame):

    def __init__(self, parent):

        wx.Frame.__init__(self, parent, -1, "ToasterBox Demo")

        toaster = TB.ToasterBox(self, tbstyle=TB.TB_COMPLEX)
        toaster.SetPopupPauseTime(3000)

        tbpanel = toaster.GetToasterBoxWindow()
        panel = wx.Panel(tbpanel, -1)
        sizer = wx.BoxSizer(wx.VERTICAL)

        button = wx.Button(panel, wx.ID_ANY, "Simple button")
        sizer.Add(button, 0, wx.EXPAND)

        panel.SetSizer(sizer)
        toaster.AddPanel(panel)

        wx.CallLater(1000, toaster.Play)

# our normal wxApp-derived class, as usual

app = wx.PySimpleApp()

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

app.MainLoop()

This code snippet can be downloaded, see this example script.

Note

Some of the AGW snippets of code in the documentation use images and external files (to create bitmaps or access external data). As these files are not provided in these snippets, you should make the approriate modifications to the code to actually run it.

platforms Supported Platforms

ToasterBox has been tested on the following platforms:

  • Windows (verified on Windows XP, 2000)
  • Linux
  • Mac

styles Window Styles

This class supports the following window styles:

Window styles for toasterbox
Window Styles | Hex Value | Description
TB_SIMPLE | 0x1 | A simple ToasterBox, with background image and text customization can be created.
TB_ONTIME | 0x1 | ToasterBox will close after a specified amount of time.
TB_COMPLEX | 0x2 | ToasterBoxes with different degree of complexity can be created. You can add as many controls as you want, provided that you call the AddPanel method and pass to it a dummy frame and a wx.Panel. See the demo for details.
TB_ONCLICK | 0x2 | ToasterBox can be closed by clicking anywhere on the ToasterBox frame.
TB_DEFAULT_STYLE | 0x2008002 | Default window style for ToasterBox, with no caption nor close box.
TB_CAPTION | 0x22009806 | ToasterBox will have a caption, with the possibility to set a title for the ToasterBox frame, and a close box.

events Events Processing

No custom events are available for this class.

license License And Version

ToasterBox is distributed under the wxPython license.

Latest revision: Andrea Gavana @ 17 Aug 2011, 15.00 GMT

Version 0.3

Module author: Andrea Gavana <andrea.gavana@gmail.com>

hierarchy Inheritance Diagram

Inheritance diagram for module: toasterbox

Inheritance diagram of toasterbox.ToasterBox, toasterbox.ToasterBoxWindow

SVN Revisions

A graphical representation of the SVN commits in the last year.

Click on any date in the picture to jump to that particular revision page, containing information about committers, log messages and SVN diffs.

Revision Graph For toasterbox

2to3 Python 3 Issues (via 2to3)

No issues have been detected by 2to3.py.

Class Summary

  • ToasterBox
  • ToasterBoxWindow

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • infobar
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • toasterbox


ultimatelistctrl

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • ultimatelistctrl

ultimatelistctrl

description Description

UltimateListCtrl is a class that mimics the behaviour of wx.ListCtrl, with almost the same base functionalities plus some more enhancements. This class does not rely on the native control, as it is a full owner-drawn list control.

In addition to the standard wx.ListCtrl behaviour this class supports:

appearance Appearance

  • Multiple images for items/subitems;
  • Images can be of any size and not limited to a single specific pair of width, height as it is the case of wx.ImageList. Simply use PyImageList instead of wx.ImageList to add your images.
  • Font, colour, background, custom renderers and formatting for items and subitems;
  • Ability to add persistent data to an item using SetItemPyData and GetItemPyData: the data can be any Python object and not necessarily an integer as in wx.ListCtrl;
  • CheckBox-type items and subitems;
  • RadioButton-type items and subitems;
  • Overflowing items/subitems, a la wx.grid.Grid, i.e. an item/subitem may overwrite neighboring items/subitems if its text would not normally fit in the space allotted to it;
  • Hyperlink-type items and subitems: they look like an hyperlink, with the proper mouse cursor on hovering;
  • Multiline text items and subitems;
  • Variable row heights depending on the item/subitem kind/text/window;
  • User defined item/subitem renderers: these renderer classes must implement the methods DrawSubItem, GetLineHeight and GetSubItemWidth (see the demo);
  • Enabling/disabling items (together with their plain or grayed out icons);
  • Whatever non-toplevel widget can be attached next to an item/subitem;
  • Column headers are fully customizable in terms of icons, colour, font, alignment etc...;
  • Column headers can have their own checkbox/radiobutton;
  • Column footers are fully customizable in terms of icons, colour, font, alignment etc...;
  • Column footers can have their own checkbox/radiobutton;
  • Ability to hide/show columns;
  • Default selection style, gradient (horizontal/vertical) selection style and Windows Vista selection style.

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

usage Usage

Usage example:

import sys

import wx
import wx.lib.agw.ultimatelistctrl as ULC

class MyFrame(wx.Frame):

    def __init__(self):

        wx.Frame.__init__(self, parent, -1, "UltimateListCtrl Demo")

        list = ULC.UltimateListCtrl(self, wx.ID_ANY, agwStyle=wx.LC_REPORT|wx.LC_VRULES|wx.LC_HRULES|wx.LC_SINGLE_SEL)

        list.InsertColumn(0, "Column 1")
        list.InsertColumn(1, "Column 2")

        index = list.InsertStringItem(sys.maxint, "Item 1")
        list.SetStringItem(index, 1, "Sub-item 1")

        index = list.InsertStringItem(sys.maxint, "Item 2")
        list.SetStringItem(index, 1, "Sub-item 2")

        choice = wx.Choice(list, -1, choices=["one", "two"])
        index = list.InsertStringItem(sys.maxint, "A widget")

        list.SetItemWindow(index, 1, choice, expand=True)

        sizer = wx.BoxSizer(wx.VERTICAL)
        sizer.Add(list, 1, wx.EXPAND)
        self.SetSizer(sizer)

# our normal wxApp-derived class, as usual

app = wx.PySimpleApp()

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

app.MainLoop()

This code snippet can be downloaded, see this example script.

Note

Some of the AGW snippets of code in the documentation use images and external files (to create bitmaps or access external data). As these files are not provided in these snippets, you should make the approriate modifications to the code to actually run it.

styles Window Styles

This class supports the following window styles:

Window styles for ultimatelistctrl
Window Styles | Hex Value | Description
ULC_VRULES | 0x1 | Draws light vertical rules between rows in report mode.
ULC_HRULES | 0x2 | Draws light horizontal rules between rows in report mode.
ULC_ICON | 0x4 | Large icon view, with optional labels.
ULC_SMALL_ICON | 0x8 | Small icon view, with optional labels.
ULC_LIST | 0x10 | Multicolumn list view, with optional small icons. Columns are computed automatically, i.e. you don’t set columns as in ULC_REPORT. In other words, the list wraps, unlike a wx.ListBox.
ULC_REPORT | 0x20 | Single or multicolumn report view, with optional header.
ULC_ALIGN_TOP | 0x40 | Icons align to the top. Win32 default, Win32 only.
ULC_ALIGN_LEFT | 0x80 | Icons align to the left.
ULC_AUTOARRANGE | 0x100 | Icons arrange themselves. Win32 only.
ULC_VIRTUAL | 0x200 | The application provides items text on demand. May only be used with ULC_REPORT.
ULC_EDIT_LABELS | 0x400 | Labels are editable: the application will be notified when editing starts.
ULC_NO_HEADER | 0x800 | No header in report mode.
ULC_NO_SORT_HEADER | 0x1000 | No Docs.
ULC_SINGLE_SEL | 0x2000 | Single selection (default is multiple).
ULC_SORT_ASCENDING | 0x4000 | Sort in ascending order. (You must still supply a comparison callback in wx.ListCtrl.SortItems.)
ULC_SORT_DESCENDING | 0x8000 | Sort in descending order. (You must still supply a comparison callback in wx.ListCtrl.SortItems.)
ULC_TILE | 0x10000 | Each item appears as a full-sized icon with a label of one or more lines beside it (partially implemented).
ULC_NO_HIGHLIGHT | 0x20000 | No highlight when an item is selected.
ULC_STICKY_HIGHLIGHT | 0x40000 | Items are selected by simply hovering on them, with no need to click on them.
ULC_STICKY_NOSELEVENT | 0x80000 | Don’t send a selection event when using ULC_STICKY_HIGHLIGHT style.
ULC_SEND_LEFTCLICK | 0x100000 | Send a left click event when an item is selected.
ULC_HAS_VARIABLE_ROW_HEIGHT | 0x200000 | The list has variable row heights.
ULC_AUTO_CHECK_CHILD | 0x400000 | When a column header has a checkbox associated, auto-check all the subitems in that column.
ULC_AUTO_TOGGLE_CHILD | 0x800000 | When a column header has a checkbox associated, toggle all the subitems in that column.
ULC_AUTO_CHECK_PARENT | 0x1000000 | Only meaningful foe checkbox-type items: when an item is checked/unchecked its column header item is checked/unchecked as well.
ULC_SHOW_TOOLTIPS | 0x2000000 | Show tooltips for ellipsized items/subitems (text too long to be shown in the available space) containing the full item/subitem text.
ULC_HOT_TRACKING | 0x4000000 | Enable hot tracking of items on mouse motion.
ULC_BORDER_SELECT | 0x8000000 | Changes border colour whan an item is selected, instead of highlighting the item.
ULC_TRACK_SELECT | 0x10000000 | Enables hot-track selection in a list control. Hot track selection means that an item is automatically selected when the cursor remains over the item for a certain period of time. The delay is retrieved on Windows using the win32api call win32gui.SystemParametersInfo(win32con.SPI_GETMOUSEHOVERTIME), and is defaulted to 400ms on other platforms. This style applies to all views of UltimateListCtrl.
ULC_HEADER_IN_ALL_VIEWS | 0x20000000 | Show column headers in all view modes.
ULC_NO_FULL_ROW_SELECT | 0x40000000 | When an item is selected, the only the item in the first column is highlighted.
ULC_FOOTER | 0x80000000 | Show a footer too (only when header is present).
ULC_USER_ROW_HEIGHT | 0x100000000 | Allows to set a custom row height (one value for all the items, only in report mode).

events Events Processing

This class processes the following events:

Events processing for ultimatelistctrl
Event Name | Description
EVT_LIST_BEGIN_DRAG | Begin dragging with the left mouse button.
EVT_LIST_BEGIN_RDRAG | Begin dragging with the right mouse button.
EVT_LIST_BEGIN_LABEL_EDIT | Begin editing a label. This can be prevented by calling Veto().
EVT_LIST_END_LABEL_EDIT | Finish editing a label. This can be prevented by calling Veto().
EVT_LIST_DELETE_ITEM | An item was deleted.
EVT_LIST_DELETE_ALL_ITEMS | All items were deleted.
EVT_LIST_KEY_DOWN | A key has been pressed.
EVT_LIST_INSERT_ITEM | An item has been inserted.
EVT_LIST_COL_CLICK | A column (m_col) has been left-clicked.
EVT_LIST_COL_RIGHT_CLICK | A column (m_col) has been right-clicked.
EVT_LIST_COL_BEGIN_DRAG | The user started resizing a column - can be vetoed.
EVT_LIST_COL_END_DRAG | The user finished resizing a column.
EVT_LIST_COL_DRAGGING | The divider between columns is being dragged.
EVT_LIST_ITEM_SELECTED | The item has been selected.
EVT_LIST_ITEM_DESELECTED | The item has been deselected.
EVT_LIST_ITEM_RIGHT_CLICK | The right mouse button has been clicked on an item.
EVT_LIST_ITEM_MIDDLE_CLICK | The middle mouse button has been clicked on an item.
EVT_LIST_ITEM_ACTIVATED | The item has been activated (ENTER or double click).
EVT_LIST_ITEM_FOCUSED | The currently focused item has changed.
EVT_LIST_CACHE_HINT | Prepare cache for a virtual list control.
EVT_LIST_ITEM_CHECKING | An item/subitem is being checked.
EVT_LIST_ITEM_CHECKED | An item/subitem has been checked.
EVT_LIST_COL_CHECKING | A column header is being checked.
EVT_LIST_COL_CHECKED | A column header has being checked.
EVT_LIST_FOOTER_CHECKING | A column footer is being checked.
EVT_LIST_FOOTER_CHECKED | A column footer has being checked.
EVT_LIST_ITEM_HYPERLINK | An hyperlink item has been clicked.
EVT_LIST_FOOTER_CLICK | The user left-clicked on a column footer.
EVT_LIST_FOOTER_RIGHT_CLICK | The user right-clicked on a column footer.
EVT_LIST_ITEM_LEFT_CLICK | Send a left-click event after an item is selected.
EVT_LIST_END_DRAG | Notify an end-drag operation.

platforms Supported Platforms

UltimateListCtrl has been tested on the following platforms:
  • Windows (Windows XP);

license License And Version

UltimateListCtrl is distributed under the wxPython license.

Latest Revision: Andrea Gavana @ 09 Feb 2012, 21.00 GMT

Version 0.8

Module author: Andrea Gavana <andrea.gavana@gmail.com>

hierarchy Inheritance Diagram

Inheritance diagram for module: ultimatelistctrl

SVN Revisions

A graphical representation of the SVN commits in the last year.

Click on any date in the picture to jump to that particular revision page, containing information about committers, log messages and SVN diffs.

Revision Graph For ultimatelistctrl

2to3 Python 3 Issues (via 2to3)

No issues have been detected by 2to3.py.

Function Summary

  • CheckVariableRowHeight
  • CreateListItem
  • GetdragcursorBitmap
  • GetdragcursorData
  • GetdragcursorImage
  • MakeDisabledBitmap
  • to_list

Class Summary

  • ColWidthInfo
  • CommandListEvent
  • GeometryInfo
  • PyImageList
  • SelectionStore
  • UltimateListCtrl
  • UltimateListEvent
  • UltimateListHeaderData
  • UltimateListHeaderWindow
  • UltimateListItem
  • UltimateListItemAttr
  • UltimateListItemData
  • UltimateListLineData
  • UltimateListMainWindow
  • UltimateListRenameTimer
  • UltimateListTextCtrl

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • infobar
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • ultimatelistctrl


xlsgrid

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • xlsgrid

xlsgrid

XLSGrid is a class based on wx.grid.Grid that can be used to faithfully reproduce the appearance of a Microsoft Excel spreadsheet (one worksheet per every instance of XLSGrid).

description Description

XLSGrid is a class based on wx.grid.Grid that can be used to faithfully reproduce the appearance of a Microsoft Excel spreadsheet (one worksheet per every instance of XLSGrid).

XLSGrid is a completely owner-drawn control, and it relies on the power of wx.grid.PyGridTableBase and wx.grid.PyGridCellRenderer to draw the cell content. For this reasons (and for some others, see the TODOs section), it will work efficiently only for relatively small Excel files.

Note

XLSGrid requires the xlrd package from:

http://pypi.python.org/pypi/xlrd

Minimum version requirement for xlrd is 0.7.1. If you wish to have support for hyperlinks inside cells and rich text content, you need the SVN version of xlrd.

Note

On Windows, it is strongly recommended to install Mark Hammonds’ pywin32 package:

http://sourceforge.net/projects/pywin32/

This will allow you to perfectly reproduce the appearance of the Excel worksheet in your instance of XLSGrid.

Warning

If Mark Hammonds’ pywin32 package is not available, the formatting capabilities of XLSGrid are severely limited; for instance, you won’t probably get the exact WYSIWYG between the Excel spreadsheet and XLSGrid.

Warning

XLSGrid can only read Excel xls files, not the newer versions xlsx generated by Office 2007/2010. If you have a xlsx file, you will need to save it in 1997-2003 Office compatibility mode.

Currently this class provides a read-only subclass of wx.grid.Grid, with the following formatting features already implemented:

  • Cell background: support for any cell background colour and fill pattern (hatching) in the Excel default set. There currently is no support for gradient shading inside a cell as xlrd doesn’t report this information.
  • Cell borders: support for all the border types and colours exposed by Excel (left, top, bottom, right and diagonal borders, thin, double, thick, ect... line styles).
  • Cell text: support for all kind of fonts (except strikethrough, but this is a bug in wxWidgets), and font colours. As a subset of text/font capabilities, XLSGrid supports the following features found in Excel:
    • Horizontal alignment: left, right, centered, left-indented;
    • Vertical alignment: left, right, centered;
    • Text direction: left-to-right or right-to-left;
    • Text-wrapping: wrapping long texts inside a grid cell;
    • Shrink-to-fit: text font is reduced until the text can fit in a one-line inside the grid cell;
    • Text rotation: text can be rotated from +90 to -90 degrees.
  • Cell rich text (new in version 0.2): support for strings containing partial bold, italic and underlined text, change of font inside a string etc... Cells with rich text content can not be multi-line and they will not honour the shrink-to-fit and wrapping settings.
  • Cell text appearance: if you are using Mark Hammonds’ pywin32 package, the text displayed in the XLSGrid cells has exactly the same appearance as in the Excel spreadsheet.
  • Cell comments (notes): if you are using Mark Hammonds’ pywin32 package, cell comments (notes) are extracted and you will see a small red triangle at the top-right corner of any cell containing a comment. Hovering with the mouse on that cell will pop-up a “comment-window” displaying the comment text (the comment window is based on wx.lib.agw.supertooltip).
  • Cell hyperlinks: starting from version 0.7.2 (SVN), xlrd is capable of extracting hyperlinks from Excel cells. This will be appropriately displayed in XLSGrid with a cursor changing and a tooltip on that cell.
  • Cell merging: merged cells in the Excel spreadsheet will be correctly handled by XLSGrid.
  • Columns and rows sizes: XLSGrid calculates the correct rows and columns sizes based on the Excel reported values in characters. The calculations are based on the default width of the text in 1/256 of the width of the zero character, using default Excel font (first FONT record in the Excel file).

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

usage Usage

Sample usage:

import wx
import xlrd
import os

import xlsgrid as XG

class MyFrame(wx.Frame):

    def __init__(self):

        wx.Frame.__init__(self, parent, -1, "XLSGrid Demo", size=(1000, 800))

        filename = os.path.join(os.getcwd(), "Excel", "Example_1.xls")
        sheetname = "Example_1"

        book = xlrd.open_workbook(filename, formatting_info=1)

        sheet = book.sheet_by_name(sheetname)
        rows, cols = sheet.nrows, sheet.ncols

        comments, texts = XG.ReadExcelCOM(filename, sheetname, rows, cols)

        xls_grid = XG.XLSGrid(self)
        xls_grid.PopulateGrid(book, sheet, texts, comments)

# our normal wxApp-derived class, as usual

app = wx.PySimpleApp()

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

app.MainLoop()

This code snippet can be downloaded, see this example script.

Note

Some of the AGW snippets of code in the documentation use images and external files (to create bitmaps or access external data). As these files are not provided in these snippets, you should make the approriate modifications to the code to actually run it.

Note

Please note that you have to pass the keyword formatting_info to the method xlrd.open_workbook to obtain the cell formatting.

todos TODOs

  1. XLSGrid is sufficiently efficient and fast for reasonably small Excel files. There might be some improvement to be made in the code to make it work with bigger files and in a faster way;
  2. wx.grid.Grid seems to completely redraw itself at every resize event, even if the cell content has not changed and it has not been damaged (this seems to be fixed in wxPython 2.9.2.1);
  3. There is currently no support for strikethrough fonts, although xlrd correctly reports this format. The issue is a bug in wxWidgets itself which doesn’t allow the creation of strikethrough fonts (http://trac.wxwidgets.org/ticket/9907).

platforms Supported Platforms

XLSGrid has been tested on the following platforms:
  • Windows (Windows Vista and 7);

styles Window Styles

No particular window styles are available for this class.

events Events Processing

No custom events are available for this class.

license License And Version

XLSGrid is distributed under the wxPython license.

Latest Revision: Andrea Gavana @ 17 Aug 2011, 15.00 GMT

Version 0.3

Module author: Andrea Gavana <andrea.gavana@gmail.com>

hierarchy Inheritance Diagram

Inheritance diagram for module: xlsgrid

Inheritance diagram of xlsgrid.Excel, xlsgrid.TransientPopup, xlsgrid.XLSBackground, xlsgrid.XLSBorder, xlsgrid.XLSBorderFactory, xlsgrid.XLSCell, xlsgrid.XLSComment, xlsgrid.XLSGrid, xlsgrid.XLSRenderer, xlsgrid.XLSRichText, xlsgrid.XLSTable, xlsgrid.XLSText

SVN Revisions

A graphical representation of the SVN commits in the last year.

Click on any date in the picture to jump to that particular revision page, containing information about committers, log messages and SVN diffs.

Revision Graph For xlsgrid

2to3 Python 3 Issues (via 2to3)

No issues have been detected by 2to3.py.

Function Summary

  • FontFromFont
  • ReadExcelCOM
  • SplitThousands

Class Summary

  • Excel
  • TransientPopup
  • XLSBackground
  • XLSBorder
  • XLSBorderFactory
  • XLSCell
  • XLSComment
  • XLSGrid
  • XLSRenderer
  • XLSRichText
  • XLSTable
  • XLSText

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • infobar
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • xlsgrid


zoombar

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • zoombar

zoombar

ZoomBar is a class that appoximatively mimics the behaviour of the Mac Dock, inside a wx.Panel.

description Description

ZoomBar is a class that appoximatively mimics the behaviour of the Mac Dock, inside a wx.Panel.

Once you hover mouse over the ZoomBar correct button will bubble up, grow to predefined size, so you can easily see the button you are about to click and have larger area to click. Difference this makes is amazing.

The buttons are able to be zoomed from the bottom up (bottom fixed) as well as to zoom from a central point. Also the container is able to move the remaining buttons around the zoomed button.

usage Usage

Usage example:

import os
import random
import glob

import wx
import wx.lib.agw.zoombar as ZB

class MyFrame(wx.Frame):

    def __init__(self, parent):

        wx.Frame.__init__(self, parent, -1, "ZoomBar Demo")

        panel = wx.Panel(self)

        bar = ZB.ZoomBar(panel, -1)

        standard = glob.glob(bitmapDir + "/*96.png")
        reflections = glob.glob(bitmapDir + "/*96Flip40.png")

        separatorImage = bitmapDir + "/separator.gif"
        separatorReflection = bitmapDir + "/separatorFlip.png"
        count = 0

        for std, ref in zip(standard, reflections):
            if random.randint(0, 1) == 1 and count > 0:
                sep1 = wx.Bitmap(separatorImage, wx.BITMAP_TYPE_GIF)
                sep2 = wx.Bitmap(separatorReflection, wx.BITMAP_TYPE_PNG)
                bar.AddSeparator(sep1, sep2)

            bname = os.path.split(std)[1][0:-6]
            bar.AddButton(wx.Bitmap(std, wx.BITMAP_TYPE_PNG), wx.Bitmap(ref, wx.BITMAP_TYPE_PNG), bname)
            count += 1

        bar.ResetSize()

        sizer = wx.BoxSizer(wx.HORIZONTAL)
        sizer.Add(bar, 0, wx.ALIGN_CENTER_HORIZONTAL|wx.ALIGN_CENTER_VERTICAL|wx.ALL, 15)
        panel.SetSizer(sizer)

# our normal wxApp-derived class, as usual

app = wx.PySimpleApp()

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

app.MainLoop()

This code snippet can be downloaded, see this example script.

Note

Some of the AGW snippets of code in the documentation use images and external files (to create bitmaps or access external data). As these files are not provided in these snippets, you should make the approriate modifications to the code to actually run it.

platforms Supported Platforms

ZoomBar has been tested on the following platforms:
  • Windows (Windows XP).

styles Window Styles

No particular window styles are available for this class.

events Events Processing

This class processes the following events:

Events processing for zoombar
Event Name | Description
EVT_ZOOMBAR | Process a wxEVT_ZOOMBAR event, when a ZoomBar button is clicked.

license License And Version

ZoomBar is distributed under the wxPython license.

Latest Revision: Andrea Gavana @ 17 Aug 2011, 15.00 GMT

Version 0.1

Module author: Andrea Gavana <andrea.gavana@gmail.com>

hierarchy Inheritance Diagram

Inheritance diagram for module: zoombar

Inheritance diagram of zoombar.ImageBar, zoombar.ZoomBar, zoombar.ZoomBarEvent, zoombar.ZoomBarImage

SVN Revisions

A graphical representation of the SVN commits in the last year.

Click on any date in the picture to jump to that particular revision page, containing information about committers, log messages and SVN diffs.

Revision Graph For zoombar

2to3 Python 3 Issues (via 2to3)

No issues have been detected by 2to3.py.

Function Summary

  • MakeDisabledBitmap

Class Summary

  • ImageBar
  • ZoomBar
  • ZoomBarEvent
  • ZoomBarImage

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • infobar
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • zoombar


AdvancedSplash

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • advancedsplash »
  • AdvancedSplash

AdvancedSplash

AdvancedSplash tries to reproduce the behavior of wx.SplashScreen, with some enhancements.

This is the main class implementation.

hierarchy Inheritance Diagram

Inheritance diagram for: AdvancedSplash

Inheritance diagram of AdvancedSplash

appearance Control Appearance

AdvancedSplash

Methods Summary

__init__ | Default class constructor.
GetSplashStyle | Returns a list of strings and a list of integers containing the styles.
GetText | Returns the text displayed on AdvancedSplash.
GetTextColour | Gets the colour for the text in AdvancedSplash.
GetTextFont | Gets the font for the text in AdvancedSplash.
GetTextPosition | Returns the text position inside AdvancedSplash frame.
OnCharEvents | Handles the wx.EVT_CHAR event for AdvancedSplash.
OnCloseWindow | Handles the wx.EVT_CLOSE event for AdvancedSplash.
OnMouseEvents | Handles the wx.EVT_MOUSE_EVENTS events for AdvancedSplash.
OnNotify | Handles the timer expiration, and calls the Close() method.
OnPaint | Handles the wx.EVT_PAINT event for AdvancedSplash.
SetSplashShape | Sets AdvancedSplash shape using the region created from the bitmap.
SetText | Sets the text to be displayed on AdvancedSplash.
SetTextColour | Sets the colour for the text in AdvancedSplash.
SetTextFont | Sets the font for the text in AdvancedSplash.
SetTextPosition | Sets the text position inside AdvancedSplash frame.
ShadowBitmap | Applies a mask on the bitmap accordingly to user input.

API Class API

class AdvancedSplash(wx.Frame) [source]

AdvancedSplash tries to reproduce the behavior of wx.SplashScreen, with some enhancements.

This is the main class implementation.

__init__(parent, id=-1, pos=wx.DefaultPosition, size=wx.DefaultSize, style=wx.FRAME_NO_TASKBAR | wx.FRAME_SHAPED | wx.STAY_ON_TOP, bitmap=None, timeout=5000, agwStyle=AS_TIMEOUT | AS_CENTER_ON_SCREEN, shadowcolour=wx.NullColour) [source]

Default class constructor.

Parameters:
  • parent (wx.Window) – parent window;
  • id (integer) – window identifier. A value of -1 indicates a default value;
  • pos (tuple or wx.Point) – the control position. A value of (-1, -1) indicates a default position, chosen by either the windowing system or wxPython, depending on platform;
  • size (tuple or wx.Size) – the control size. A value of (-1, -1) indicates a default size, chosen by either the windowing system or wxPython, depending on platform;
  • style (integer) – the underlying wx.Frame style;
  • bitmap – this must be a valid bitmap, that you may construct using whatever image file format supported by wxPython. If the file you load already supports mask/transparency (like png), the transparent areas will not be drawn on screen, and the AdvancedSplash frame will have the shape defined only by non-transparent pixels. If you use other file formats that does not supports transparency, you can obtain the same effect as above by masking a specific colour in your wx.Bitmap.
  • timeout (integer) – if you construct AdvancedSplash using the style AS_TIMEOUT, AdvancedSplash will be destroyed after timeout milliseconds;
  • agwStyle (integer) – this value specifies the AdvancedSplash styles:

    integer parameter settings
    Window Styles | Hex Value | Description
    AS_TIMEOUT | 0x1 | AdvancedSplash will be destroyed after timeout milliseconds.
    AS_NOTIMEOUT | 0x2 | AdvancedSplash can be destroyed by clicking on it, pressing a key or by explicitly call the Close() method.
    AS_CENTER_ON_SCREEN | 0x4 | AdvancedSplash will be centered on screen.
    AS_CENTER_ON_PARENT | 0x8 | AdvancedSplash will be centered on parent.
    AS_NO_CENTER | 0x10 | AdvancedSplash will not be centered.
    AS_SHADOW_BITMAP | 0x20 | If the bitmap you pass as input has no transparency, you can choose one colour that will be masked in your bitmap. the final shape of AdvancedSplash will be defined only by non-transparent (non-masked) pixels.
  • shadowcolour (wx.Colour) – if you construct AdvancedSplash using the style AS_SHADOW_BITMAP, here you can specify the colour that will be masked on your input bitmap. This has to be a valid wxPython colour.
Raise :

Exception in the following cases:

  • The AS_TIMEOUT style is set but timeout is not a positive integer;
  • The AS_SHADOW_BITMAP style is set but shadowcolour is not a valid wxPython colour;
  • The AdvancedSplash bitmap is an invalid wx.Bitmap.

GetSplashStyle() [source]

Returns a list of strings and a list of integers containing the styles.

Returns: Two Python lists containing the style name and style values for AdvancedSplash.

GetText() [source]

Returns the text displayed on AdvancedSplash.

Returns: A string representing the text drawn on top of the AdvancedSplash bitmap.

GetTextColour() [source]

Gets the colour for the text in AdvancedSplash.

Returns: An instance of wx.Colour.

GetTextFont() [source]

Gets the font for the text in AdvancedSplash.

Returns: An instance of wx.Font to draw the text and a wx.Size object containing the text width an height, in pixels.

GetTextPosition() [source]

Returns the text position inside AdvancedSplash frame.

Returns: A tuple containing the text x and y position inside the AdvancedSplash frame.

OnCharEvents(event) [source]

Handles the wx.EVT_CHAR event for AdvancedSplash.

Parameters: event – a wx.KeyEvent to be processed.

Note

This reproduces the behavior of wx.SplashScreen.

OnCloseWindow(event) [source]

Handles the wx.EVT_CLOSE event for AdvancedSplash.

Parameters: event – a wx.CloseEvent to be processed.

Note

This reproduces the behavior of wx.SplashScreen.

OnMouseEvents(event) [source]

Handles the wx.EVT_MOUSE_EVENTS events for AdvancedSplash.

Parameters: event – a wx.MouseEvent to be processed.

Note

This reproduces the behavior of wx.SplashScreen.

OnNotify() [source]

Handles the timer expiration, and calls the Close() method.

OnPaint(event) [source]

Handles the wx.EVT_PAINT event for AdvancedSplash.

Parameters: event – a wx.PaintEvent to be processed.

SetSplashShape(event=None) [source]

Sets AdvancedSplash shape using the region created from the bitmap.

Parameters: event – a wx.WindowCreateEvent event (GTK only, as GTK supports setting the window shape only during window creation).

SetText(text=None) [source]

Sets the text to be displayed on AdvancedSplash.

Parameters: text (string or None) – the text we want to display on top of the bitmap. If text is set to None, nothing will be drawn on top of the bitmap.

SetTextColour(colour=None) [source]

Sets the colour for the text in AdvancedSplash.

Parameters: colour – the text colour to use while drawing the text on top of our bitmap. If colour is None, then wx.BLACK is used.

SetTextFont(font=None) [source]

Sets the font for the text in AdvancedSplash.

Parameters: font (wx.Font or None) – the font to use while drawing the text on top of our bitmap. If font is None, a simple generic font is generated.

SetTextPosition(position=None) [source]

Sets the text position inside AdvancedSplash frame.

Parameters: position (tuple or None) – the text position inside our bitmap. If position is None, the text will be placed at the top-left corner.

ShadowBitmap(bmp, shadowcolour) [source]

Applies a mask on the bitmap accordingly to user input.

Parameters:
  • bmp – the bitmap to which we want to apply the mask colour shadowcolour;
  • shadowcolour – the mask colour for our bitmap.
Returns:

A masked version of the input bitmap, an instance of wx.Bitmap.

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • infobar
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • advancedsplash »
  • AdvancedSplash


SVN Revision 68362 For advancedsplash

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • advancedsplash »
  • SVN Revision 68362 For advancedsplash

svn SVN Revision 68362 For advancedsplash

This file contains the SVN revision history for advancedsplash, at revision 68362.

Available information include commit date, the name of the committer, the file size, the SVN log messages and a diff from the previous version (if available).

File Information

  • Commit Date: 19-May-2009 21:07:56 UTC
  • Committer: AG
  • File Size: 16356 byte(s)

Log Messages

The following log message was entered by the committer:

  • All of AGW: change my work e-mail from KPO to Maersk Oil (silly commit)

Diff To Previous Version (66805)

Version SVN diff:

--- wxPython/3rdParty/AGW/agw/advancedsplash.py     2011/01/28 15:22:45     66805
+++ wxPython/3rdParty/AGW/agw/advancedsplash.py     2011/07/24 21:36:47     68362
@@ -25,7 +25,7 @@
# Write To Me At:
#
# andrea.gavana@gmail.com
-# gavana@kpo.kz
+# andrea.gavana@maerskoil.com
#
# Or, Obviously, To The wxPython Mailing List!!!
#

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • advancedsplash »
  • SVN Revision 68362 For advancedsplash


SVN Revision 68475 For advancedsplash

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • advancedsplash »
  • SVN Revision 68475 For advancedsplash

svn SVN Revision 68475 For advancedsplash

This file contains the SVN revision history for advancedsplash, at revision 68475.

Available information include commit date, the name of the committer, the file size, the SVN log messages and a diff from the previous version (if available).

File Information

  • Commit Date: 12-May-2009 14:58:36 UTC
  • Committer: AG
  • File Size: 16821 byte(s)

Log Messages

The following log message was entered by the committer:

framemanager.py: Implementation of the AUI_MINIMIZE_POS_TOOLBAR flag, which allows to minimize a pane inside an existing toolbar. Limitation: if the minimized icon in the toolbar ends up in the overflowing items (i.e., a menu is needed to show the icon), this style will not work.

Diff To Previous Version (68362)

Version SVN diff:

--- wxPython/3rdParty/AGW/agw/advancedsplash.py     2011/07/24 21:36:47     68362
+++ wxPython/3rdParty/AGW/agw/advancedsplash.py     2011/07/31 20:22:23     68475
@@ -3,7 +3,7 @@
# Python Code By:
#
# Andrea Gavana, @ 10 Oct 2005
-# Latest Revision: 27 Jan 2011, 15.00 GMT
+# Latest Revision: 26 Jul 2011, 22.00 GMT
#
#
# TODO List/Caveats
@@ -35,21 +35,21 @@

"""
-AdvancedSplash tries to reproduce the behavior of `wx.SplashScreen`, with
+L{AdvancedSplash} tries to reproduce the behavior of `wx.SplashScreen`, with
some enhancements.

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

-AdvancedSplash tries to reproduce the behavior of `wx.SplashScreen`, but with
+L{AdvancedSplash} tries to reproduce the behavior of `wx.SplashScreen`, but with
some enhancements (in my opinion).

-AdvancedSplash starts its construction from a simple frame. Then, depending on
-the options passed to AdvancedSplash, it sets the frame shape accordingly to
-the image passed as input. AdvancedSplash behaves somewhat like `wx.SplashScreen`,
-and almost all the methods available in `wx.SplashScreen` are available also In
-AdvancedSplash.
+L{AdvancedSplash} starts its construction from a simple frame. Then, depending on
+the options passed to it, it sets the frame shape accordingly to the image passed
+as input. L{AdvancedSplash} behaves somewhat like `wx.SplashScreen`, and almost
+all the methods available in `wx.SplashScreen` are available also in
+this module.

Usage
@@ -57,23 +57,39 @@

Sample usage::

-    SplashScreen = AS.AdvancedSplash(parent, bitmap, timeout, agwStyle,
-                                     shadowcolour)
+    import wx
+    import wx.lib.agw.advancedsplash as AS

+    app = wx.App(0)
+
+    frame = wx.Frame(None, -1, "AdvancedSplash Test")
+
+    imagePath = "my_splash_image.png"
+    bitmap = wx.Bitmap(imagePath, wx.BITMAP_TYPE_PNG)
+    shadow = wx.WHITE
+
+    splash = AS.AdvancedSplash(frame, bitmap=bitmap, timeout=5000,
+                               agwStyle=AS.AS_TIMEOUT |
+                               AS.AS_CENTER_ON_PARENT |
+                               AS.AS_SHADOW_BITMAP,
+                               shadowcolour=shadow)
+
+    app.MainLoop()
+

None of the options are strictly required (a part of the `bitmap` parameter).
-If you use the defaults you get a very simple AdvancedSplash.
+If you use the defaults you get a very simple L{AdvancedSplash}.

Methods and Settings
====================

-AdvancedSplash is customizable, and in particular you can set:
+L{AdvancedSplash} is customizable, and in particular you can set:

- Whether you want to mask a colour or not in your input bitmap;
- Where to center the splash screen (on screen, on parent or nowhere);
- Whether it is a "timeout" splashscreen or not;
-- The time after which AdvancedSplash is destroyed (if it is a timeout splashscreen);
+- The time after which L{AdvancedSplash} is destroyed (if it is a timeout splashscreen);
- The (optional) text you wish to display;
- The font, colour and position of the displayed text (optional).

@@ -86,12 +102,12 @@
======================= =========== ==================================================
Window Styles           Hex Value   Description
======================= =========== ==================================================
-``AS_TIMEOUT``                  0x1 `AdvancedSplash` will be destroyed after `timeout` milliseconds.
-``AS_NOTIMEOUT``                0x2 `AdvancedSplash` can be destroyed by clicking on it, pressing a key or by explicitly call the `Close()` method.
-``AS_CENTER_ON_SCREEN``         0x4 `AdvancedSplash` will be centered on screen.
-``AS_CENTER_ON_PARENT``         0x8 `AdvancedSplash` will be centered on parent.
-``AS_NO_CENTER``               0x10 `AdvancedSplash` will not be centered.
-``AS_SHADOW_BITMAP``           0x20 If the bitmap you pass as input has no transparency, you can choose one colour that will be masked in your bitmap. the final shape of `AdvancedSplash` will be defined only by non-transparent (non-masked) pixels.
+``AS_TIMEOUT``                  0x1 L{AdvancedSplash} will be destroyed after `timeout` milliseconds.
+``AS_NOTIMEOUT``                0x2 L{AdvancedSplash} can be destroyed by clicking on it, pressing a key or by explicitly call the `Close()` method.
+``AS_CENTER_ON_SCREEN``         0x4 L{AdvancedSplash` will be centered on screen.
+``AS_CENTER_ON_PARENT``         0x8 L{AdvancedSplash} will be centered on parent.
+``AS_NO_CENTER``               0x10 L{AdvancedSplash} will not be centered.
+``AS_SHADOW_BITMAP``           0x20 If the bitmap you pass as input has no transparency, you can choose one colour that will be masked in your bitmap. the final shape of L{AdvancedSplash} will be defined only by non-transparent (non-masked) pixels.
======================= =========== ==================================================

@@ -104,9 +120,9 @@
License And Version
===================

-AdvancedSplash control is distributed under the wxPython license.
+L{AdvancedSplash} control is distributed under the wxPython license.

-Latest revision: Andrea Gavana @ 27 Jan 2011, 15.00 GMT
+Latest revision: Andrea Gavana @ 26 Jul 2011, 22.00 GMT

Version 0.4

@@ -123,23 +139,23 @@
# Timeout Or Not

AS_TIMEOUT = 1
-""" `AdvancedSplash` will be destroyed after `timeout` milliseconds. """
+""" L{AdvancedSplash} will be destroyed after `timeout` milliseconds. """
AS_NOTIMEOUT = 2
-""" `AdvancedSplash` can be destroyed by clicking on it, pressing a key or by""" \
+""" L{AdvancedSplash} can be destroyed by clicking on it, pressing a key or by""" \
""" explicitly call the Close() method. """

# These Flags Are Used To Position AdvancedSplash Correctly On Screen
AS_CENTER_ON_SCREEN = 4
-""" `AdvancedSplash` will be centered on screen. """
+""" L{AdvancedSplash} will be centered on screen. """
AS_CENTER_ON_PARENT = 8
-""" `AdvancedSplash` will be centered on parent. """
+""" L{AdvancedSplash} will be centered on parent. """
AS_NO_CENTER = 16
-""" `AdvancedSplash` will not be centered. """
+""" L{AdvancedSplash} will not be centered. """

# This Option Allow To Mask A Colour In The Input Bitmap
AS_SHADOW_BITMAP = 32
""" If the bitmap you pass as input has no transparency, you can choose one colour""" \
-""" that will be masked in your bitmap. the final shape of `AdvancedSplash` will be""" \
+""" that will be masked in your bitmap. the final shape of L{AdvancedSplash} will be""" \
""" defined only by non-transparent (non-masked) pixels. """

#----------------------------------------------------------------------
@@ -150,7 +166,7 @@

class AdvancedSplash(wx.Frame):
"""
-    AdvancedSplash tries to reproduce the behavior of `wx.SplashScreen`, with
+    L{AdvancedSplash} tries to reproduce the behavior of `wx.SplashScreen`, with
some enhancements.

This is the main class implementation.

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • advancedsplash »
  • SVN Revision 68475 For advancedsplash


SVN Revision 68881 For advancedsplash

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • advancedsplash »
  • SVN Revision 68881 For advancedsplash

svn SVN Revision 68881 For advancedsplash

This file contains the SVN revision history for advancedsplash, at revision 68881.

Available information include commit date, the name of the committer, the file size, the SVN log messages and a diff from the previous version (if available).

File Information

  • Commit Date: 09-Apr-2009 07:24:37 UTC
  • Committer: AG
  • File Size: 16796 byte(s)

Log Messages

The following log message was entered by the committer:

  • AGW: General overhaul of the documentation, much improved. All the widgets have their own sample usage in the docs as well;

  • FlatNotebook: Added the FNB_NAV_BUTTONS_WHEN_NEEDED style, which hides the navigation left/right arrows if all tabs fit;

  • RibbonBar: - Added the EVT_RIBBONBAR_TAB_LEFT_DCLICK event, which generates a special event

    when a ribbon bar tab is double-clicked;

    • Added support for toggle buttons;
    • Improved support for ribbon panel sizers: panels with sizers should now automatically minimise at small sizes, and behave properly when popping up from a minimised state;
    • Added tooltips via SetToolTip for those buttons which have the help_string attribute set.

  • XLSGrid: a new widget was added to AGW, termed XLSGrid. It’s based on wx.grid.Grid and can be used to faithfully reproduce the appearance of a Microsoft Excel spreadsheets.

Diff To Previous Version (68475)

Version SVN diff:

--- wxPython/3rdParty/AGW/agw/advancedsplash.py     2011/07/31 20:22:23     68475
+++ wxPython/3rdParty/AGW/agw/advancedsplash.py     2011/08/25 16:40:17     68881
@@ -3,7 +3,7 @@
# Python Code By:
#
# Andrea Gavana, @ 10 Oct 2005
-# Latest Revision: 26 Jul 2011, 22.00 GMT
+# Latest Revision: 17 Aug 2011, 15.00 GMT
#
#
# TODO List/Caveats
@@ -122,7 +122,7 @@

L{AdvancedSplash} control is distributed under the wxPython license.

-Latest revision: Andrea Gavana @ 26 Jul 2011, 22.00 GMT
+Latest revision: Andrea Gavana @ 17 Aug 2011, 15.00 GMT

Version 0.4

@@ -141,8 +141,7 @@
AS_TIMEOUT = 1
""" L{AdvancedSplash} will be destroyed after `timeout` milliseconds. """
AS_NOTIMEOUT = 2
-""" L{AdvancedSplash} can be destroyed by clicking on it, pressing a key or by""" \
-""" explicitly call the Close() method. """
+""" L{AdvancedSplash} can be destroyed by clicking on it, pressing a key or by explicitly call the `Close()` method. """

# These Flags Are Used To Position AdvancedSplash Correctly On Screen
AS_CENTER_ON_SCREEN = 4
@@ -154,9 +153,7 @@

# This Option Allow To Mask A Colour In The Input Bitmap
AS_SHADOW_BITMAP = 32
-""" If the bitmap you pass as input has no transparency, you can choose one colour""" \
-""" that will be masked in your bitmap. the final shape of L{AdvancedSplash} will be""" \
-""" defined only by non-transparent (non-masked) pixels. """
+""" If the bitmap you pass as input has no transparency, you can choose one colour that will be masked in your bitmap. the final shape of L{AdvancedSplash} will be defined only by non-transparent (non-masked) pixels. """

#----------------------------------------------------------------------
# ADVANCEDSPLASH Class

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • advancedsplash »
  • SVN Revision 68881 For advancedsplash


SVN Revision 69086 For advancedsplash

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • advancedsplash »
  • SVN Revision 69086 For advancedsplash

svn SVN Revision 69086 For advancedsplash

This file contains the SVN revision history for advancedsplash, at revision 69086.

Available information include commit date, the name of the committer, the file size, the SVN log messages and a diff from the previous version (if available).

File Information

  • Commit Date: 17-Oct-2008 20:51:43 UTC
  • Committer: AG
  • File Size: 18757 byte(s)

Log Messages

The following log message was entered by the committer:

  • Fixed bug #13437 for SuperToolTip;
  • Fixed bug #13477 for UltimateListCtrl.

Diff To Previous Version (68881)

Version SVN diff:

--- wxPython/3rdParty/AGW/agw/advancedsplash.py     2011/08/25 16:40:17     68881
+++ wxPython/3rdParty/AGW/agw/advancedsplash.py     2011/09/14 19:39:08     69086
@@ -176,7 +176,14 @@
"""
Default class constructor.

-        :param `bitmap`: this must be a valid `wx.Bitmap`, that you may construct using
+        :param `parent`: parent window;
+        :param integer `id`: window identifier. A value of -1 indicates a default value;
+        :param `pos`: the control position. A value of (-1, -1) indicates a default position,
+         chosen by either the windowing system or wxPython, depending on platform;
+        :param `size`: the control size. A value of (-1, -1) indicates a default size,
+         chosen by either the windowing system or wxPython, depending on platform;
+        :param integer `style`: the underlying `wx.Frame` style;
+        :param `bitmap`: this must be a valid bitmap, that you may construct using
whatever image file format supported by wxPython. If the file you load
already supports mask/transparency (like png), the transparent areas
will not be drawn on screen, and the L{AdvancedSplash} frame will have
@@ -184,11 +191,9 @@
If you use other file formats that does not supports transparency, you
can obtain the same effect as above by masking a specific colour in
your `wx.Bitmap`.
-
-        :param `timeout`: if you construct L{AdvancedSplash} using the style ``AS_TIMEOUT``,
+        :param integer `timeout`: if you construct L{AdvancedSplash} using the style ``AS_TIMEOUT``,
L{AdvancedSplash} will be destroyed after `timeout` milliseconds;
-
-        :param `agwStyle`: this value specifies the L{AdvancedSplash} styles:
+        :param integer `agwStyle`: this value specifies the L{AdvancedSplash} styles:

======================= =========== ==================================================
Window Styles           Hex Value   Description
@@ -205,6 +210,18 @@
``AS_SHADOW_BITMAP``, here you can specify the colour that will be masked on
your input bitmap. This has to be a valid wxPython colour.

+        :type parent: `wx.Window`
+        :type pos: tuple or `wx.Point`
+        :type size: tuple or `wx.Size`
+        :type bitmap: `wx.Bitmap`
+        :type shadowcolour: `wx.Colour`
+
+        :raise: `Exception` in the following cases:
+
+         - The ``AS_TIMEOUT`` style is set but `timeout` is not a positive integer;
+         - The ``AS_SHADOW_BITMAP`` style is set but `shadowcolour` is not a valid wxPython colour;
+         - The L{AdvancedSplash} bitmap is an invalid `wx.Bitmap`.
+
"""

wx.Frame.__init__(self, parent, id, "", pos, size, style)
@@ -290,6 +307,10 @@

:param `bmp`: the bitmap to which we want to apply the mask colour `shadowcolour`;
:param `shadowcolour`: the mask colour for our bitmap.
+        :type bmp: `wx.Bitmap`
+        :type shadowcolour: `wx.Colour`
+
+        :return: A masked version of the input bitmap, an instance of `wx.Bitmap`.
"""

mask = wx.Mask(bmp, shadowcolour)
@@ -380,6 +401,7 @@

:param `text`: the text we want to display on top of the bitmap. If `text` is
set to ``None``, nothing will be drawn on top of the bitmap.
+        :type text: string or ``None``
"""

if text is None:
@@ -392,7 +414,11 @@

def GetText(self):
-        """ Returns the text displayed on L{AdvancedSplash}."""
+        """
+        Returns the text displayed on L{AdvancedSplash}.
+
+        :return: A string representing the text drawn on top of the L{AdvancedSplash} bitmap.
+        """

return self._text

@@ -403,6 +429,7 @@

:param `font`: the font to use while drawing the text on top of our bitmap. If `font`
is ``None``, a simple generic font is generated.
+        :type font: `wx.Font` or ``None``
"""

if font is None:
@@ -419,7 +446,12 @@

def GetTextFont(self):
-        """ Gets the font for the text in L{AdvancedSplash}."""
+        """
+        Gets the font for the text in L{AdvancedSplash}.
+
+        :return: An instance of `wx.Font` to draw the text and a `wx.Size` object containing
+         the text width an height, in pixels.
+        """

return self._textfont, self._textsize

@@ -430,6 +462,7 @@

:param `colour`: the text colour to use while drawing the text on top of our
bitmap. If `colour` is ``None``, then ``wx.BLACK`` is used.
+        :type colour: `wx.Colour` or ``None``
"""

if colour is None:
@@ -441,7 +474,11 @@

def GetTextColour(self):
-        """ Gets the colour for the text in L{AdvancedSplash}."""
+        """
+        Gets the colour for the text in L{AdvancedSplash}.
+
+        :return: An instance of `wx.Colour`.
+        """

return self._textcolour

@@ -452,10 +489,11 @@

:param `position`: the text position inside our bitmap. If `position` is ``None``,
the text will be placed at the top-left corner.
+        :type position: tuple or ``None``
"""

if position is None:
-            position = (0,0)
+            position = (0, 0)

self._textpos = position
self.Refresh()
@@ -463,13 +501,21 @@

def GetTextPosition(self):
-        """ Returns the text position inside L{AdvancedSplash} frame."""
+        """
+        Returns the text position inside L{AdvancedSplash} frame.
+
+        :return: A tuple containing the text `x` and `y` position inside the L{AdvancedSplash} frame.
+        """

return self._textpos

def GetSplashStyle(self):
-        """ Returns a list of strings and a list of integers containing the styles. """
+        """
+        Returns a list of strings and a list of integers containing the styles.
+
+        :return: Two Python lists containing the style name and style values for L{AdvancedSplash}.
+        """

stringstyle = []
integerstyle = []
@@ -500,4 +546,3 @@

return stringstyle, integerstyle

-

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • advancedsplash »
  • SVN Revision 69086 For advancedsplash


SVN Revision 69294 For advancedsplash

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • advancedsplash »
  • SVN Revision 69294 For advancedsplash

svn SVN Revision 69294 For advancedsplash

This file contains the SVN revision history for advancedsplash, at revision 69294.

Available information include commit date, the name of the committer, the file size, the SVN log messages and a diff from the previous version (if available).

File Information

  • Commit Date: 17-Oct-2008 19:15:31 UTC
  • Committer: AG
  • File Size: 18757 byte(s)

Log Messages

The following log message was entered by the committer:

ModernDockArt for AUI: fixed an unreferenced link to winxptheme.

Diff To Previous Version (69086)

Version SVN diff:

--- wxPython/3rdParty/AGW/agw/advancedsplash.py     2011/09/14 19:39:08     69086
+++ wxPython/3rdParty/AGW/agw/advancedsplash.py     2011/10/02 19:32:45     69294
@@ -104,7 +104,7 @@
======================= =========== ==================================================
``AS_TIMEOUT``                  0x1 L{AdvancedSplash} will be destroyed after `timeout` milliseconds.
``AS_NOTIMEOUT``                0x2 L{AdvancedSplash} can be destroyed by clicking on it, pressing a key or by explicitly call the `Close()` method.
-``AS_CENTER_ON_SCREEN``         0x4 L{AdvancedSplash` will be centered on screen.
+``AS_CENTER_ON_SCREEN``         0x4 L{AdvancedSplash} will be centered on screen.
``AS_CENTER_ON_PARENT``         0x8 L{AdvancedSplash} will be centered on parent.
``AS_NO_CENTER``               0x10 L{AdvancedSplash} will not be centered.
``AS_SHADOW_BITMAP``           0x20 If the bitmap you pass as input has no transparency, you can choose one colour that will be masked in your bitmap. the final shape of L{AdvancedSplash} will be defined only by non-transparent (non-masked) pixels.

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • advancedsplash »
  • SVN Revision 69294 For advancedsplash


__ToggleMixin

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • aquabutton »
  • __ToggleMixin

__ToggleMixin

A mixin that allows to transform AquaButton in the corresponding toggle button.

hierarchy Inheritance Diagram

Inheritance diagram for: __ToggleMixin

subclasses Known Subclasses

  • aquabutton.AquaToggleButton

Methods Summary

GetToggle | Returns the toggled state of a button.
GetValue | Returns the toggled state of a button.
OnKeyDown | Handles the wx.EVT_KEY_DOWN event for AquaButton when used as toggle button.
OnKeyUp | Handles the wx.EVT_KEY_UP event for AquaButton when used as toggle button.
OnLeftDown | Handles the wx.EVT_LEFT_DOWN event for AquaButton when used as toggle button.
OnLeftUp | Handles the wx.EVT_LEFT_UP event for AquaButton when used as toggle button.
OnMotion | Handles the wx.EVT_MOTION event for AquaButton when used as toggle button.
OnPaint | Handles the wx.EVT_PAINT event for AquaButton when used as toggle button.
SetToggle | Sets the button as toggled/not toggled.
SetValue | Sets the button as toggled/not toggled.

API Class API

class __ToggleMixin(object) [source]

A mixin that allows to transform AquaButton in the corresponding toggle button.

GetToggle() [source]

Returns the toggled state of a button.

Returns: True is the button is toggled, False if it is not toggled.

GetValue()

Returns the toggled state of a button.

Returns: True is the button is toggled, False if it is not toggled.

OnKeyDown(event) [source]

Handles the wx.EVT_KEY_DOWN event for AquaButton when used as toggle button.

Parameters: event – a wx.KeyEvent event to be processed.

OnKeyUp(event) [source]

Handles the wx.EVT_KEY_UP event for AquaButton when used as toggle button.

Parameters: event – a wx.KeyEvent event to be processed.

OnLeftDown(event) [source]

Handles the wx.EVT_LEFT_DOWN event for AquaButton when used as toggle button.

Parameters: event – a wx.MouseEvent event to be processed.

OnLeftUp(event) [source]

Handles the wx.EVT_LEFT_UP event for AquaButton when used as toggle button.

Parameters: event – a wx.MouseEvent event to be processed.

OnMotion(event) [source]

Handles the wx.EVT_MOTION event for AquaButton when used as toggle button.

Parameters: event – a wx.MouseEvent event to be processed.

OnPaint(event) [source]

Handles the wx.EVT_PAINT event for AquaButton when used as toggle button.

Parameters: event – a wx.PaintEvent event to be processed.

SetToggle(flag) [source]

Sets the button as toggled/not toggled.

Parameters: flag (bool) – True to set the button as toggled, False otherwise.

SetValue(flag)

Sets the button as toggled/not toggled.

Parameters: flag (bool) – True to set the button as toggled, False otherwise.

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • infobar
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • aquabutton »
  • __ToggleMixin


AquaButton

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • aquabutton »
  • AquaButton

AquaButton

This is the main class implementation of AquaButton.

hierarchy Inheritance Diagram

Inheritance diagram for: AquaButton

Inheritance diagram of AquaButton

subclasses Known Subclasses

  • aquabutton.AquaToggleButton

appearance Control Appearance

AquaButton

Methods Summary

__init__ | Default class constructor.
AcceptsFocus | Can this window be given focus by mouse click? ..
DoGetBestSize | Overridden base class virtual.
Enable | Enables/disables the button.
GetBackgroundColour | Returns the button colour when the mouse is not hovering on the button.
GetDefaultAttributes | Overridden base class virtual.
GetDisabledColor | Returns the button colour when it is disabled.
GetDisabledColour | Returns the button colour when it is disabled.
GetForegroundColour | Returns the text colour for AquaButton.
GetHoverColor | Returns the button colour when the mouse is hovering on the button.
GetHoverColour | Returns the button colour when the mouse is hovering on the button.
GetPath | Returns a rounded wx.GraphicsPath rectangle.
GetPulseOnFocus | Returns whether the pulsing effect is active.
Invalidate | Invalidate the saved bitmap and refresh the button.
LightColour | Return light contrast of colour.
Notify | Actually sends a wx.EVT_BUTTON event to the listener (if any).
OnGainFocus | Handles the wx.EVT_SET_FOCUS event for AquaButton.
OnKeyDown | Handles the wx.EVT_KEY_DOWN event for AquaButton.
OnKeyUp | Handles the wx.EVT_KEY_UP event for AquaButton.
OnLeftDown | Handles the wx.EVT_LEFT_DOWN event for AquaButton.
OnLeftUp | Handles the wx.EVT_LEFT_UP event for AquaButton.
OnLoseFocus | Handles the wx.EVT_KILL_FOCUS event for AquaButton.
OnMouseEnter | Handles the wx.EVT_ENTER_WINDOW event for AquaButton.
OnMouseLeave | Handles the wx.EVT_LEAVE_WINDOW event for AquaButton.
OnPaint | Handles the wx.EVT_PAINT event for AquaButton.
OnPulseTimer | Handles the wx.EVT_TIMER event for AquaButton.
OnSize | Handles the wx.EVT_SIZE event for AquaButton.
SetBackgroundColor | Sets the AquaButton background colour.
SetBackgroundColour | Sets the AquaButton background colour.
SetBestSize | Given the current font and bezel width settings, calculate and set a good size.
SetBitmapLabel | Sets the bitmap label for the button.
SetDefault | This sets the AquaButton to be the default item for the panel or dialog box.
SetDisabledColor | Sets the button colour when it is disabled.
SetDisabledColour | Sets the button colour when it is disabled.
SetForegroundColour | Sets the AquaButton foreground (text) colour.
SetHoverColor | Sets the button colour when the mouse is hovering on the button.
SetHoverColour | Sets the button colour when the mouse is hovering on the button.
SetInitialSize | Given the current font and bezel width settings, calculate and set a good size.
SetPulseOnFocus | Sets whether to enable the pulsing effect on gaining focus or not.
ShouldInheritColours | Overridden base class virtual.

API Class API

class AquaButton(wx.PyControl) [source]

This is the main class implementation of AquaButton.

__init__(parent, id=wx.ID_ANY, bitmap=None, label="", pos=wx.DefaultPosition, size=wx.DefaultSize, style=wx.NO_BORDER, validator=wx.DefaultValidator, name="aquabutton") [source]

Default class constructor.

Parameters:
  • parent (wx.Window) – parent window. Must not be None;
  • id (integer) – window identifier. A value of -1 indicates a default value;
  • bitmap (wx.Bitmap) – the button bitmap (if any);
  • label (string) – the button text label;
  • pos (tuple or wx.Point) – the control position. A value of (-1, -1) indicates a default position, chosen by either the windowing system or wxPython, depending on platform;
  • size (tuple or wx.Size) – the control size. A value of (-1, -1) indicates a default size, chosen by either the windowing system or wxPython, depending on platform;
  • style (integer) – the button style (unused);
  • validator (wx.Validator) – the validator associated to the button;
  • name (string) – the button name.

AcceptsFocus() [source]

Can this window be given focus by mouse click?

Note

Overridden from wx.PyControl.

DoGetBestSize() [source]

Overridden base class virtual. Determines the best size of the button based on the label and bezel size.

Returns: An instance of wx.Size.

Note

Overridden from wx.PyControl.

Enable(enable=True) [source]

Enables/disables the button.

Parameters: enable (bool) – True to enable the button, False to disable it.

Note

Overridden from wx.PyControl.

GetBackgroundColour() [source]

Returns the button colour when the mouse is not hovering on the button.

Returns: An instance of wx.Colour.

Note

Overridden from wx.PyControl.

GetDefaultAttributes() [source]

Overridden base class virtual. By default we should use the same font/colour attributes as the native wx.Button.

Returns: an instance of wx.VisualAttributes.

Note

Overridden from wx.PyControl.

GetDisabledColor()

Returns the button colour when it is disabled.

Returns: An instance of wx.Colour.

GetDisabledColour() [source]

Returns the button colour when it is disabled.

Returns: An instance of wx.Colour.

GetForegroundColour() [source]

Returns the text colour for AquaButton.

Returns: An instance of wx.Colour.

Note

Overridden from wx.PyControl.

GetHoverColor()

Returns the button colour when the mouse is hovering on the button.

Returns: An instance of wx.Colour.

GetHoverColour() [source]

Returns the button colour when the mouse is hovering on the button.

Returns: An instance of wx.Colour.

GetPath(gc, rc, r) [source]

Returns a rounded wx.GraphicsPath rectangle.

Parameters:
  • gc – an instance of wx.GraphicsContext;
  • rc (wx.Rect) – a client rectangle;
  • r (float) – the radius of the rounded part of the rectangle.
Returns:

A rounded rectangle, an instance of wx.GraphicsPath.

GetPulseOnFocus() [source]

Returns whether the pulsing effect is active.

Returns: True if the pulsing effect is active, False otherwise.

Invalidate() [source]

Invalidate the saved bitmap and refresh the button.

LightColour(colour, percent) [source]

Return light contrast of colour. The colour returned is from the scale of colour ==> white.

Parameters:
  • colour – the input colour to be brightened, a valid instance of wx.Colour;

  • percent (integer) – determines how light the colour will be. percent = 100 returns white, percent = 0 returns colour.
Returns:

A light contrast of the input colour, an instance of wx.Colour.

Notify() [source]

Actually sends a wx.EVT_BUTTON event to the listener (if any).

OnGainFocus(event) [source]

Handles the wx.EVT_SET_FOCUS event for AquaButton.

Parameters: event – a wx.FocusEvent event to be processed.

OnKeyDown(event) [source]

Handles the wx.EVT_KEY_DOWN event for AquaButton.

Parameters: event – a wx.KeyEvent event to be processed.

OnKeyUp(event) [source]

Handles the wx.EVT_KEY_UP event for AquaButton.

Parameters: event – a wx.KeyEvent event to be processed.

OnLeftDown(event) [source]

Handles the wx.EVT_LEFT_DOWN event for AquaButton.

Parameters: event – a wx.MouseEvent event to be processed.

OnLeftUp(event) [source]

Handles the wx.EVT_LEFT_UP event for AquaButton.

Parameters: event – a wx.MouseEvent event to be processed.

OnLoseFocus(event) [source]

Handles the wx.EVT_KILL_FOCUS event for AquaButton.

Parameters: event – a wx.FocusEvent event to be processed.

OnMouseEnter(event) [source]

Handles the wx.EVT_ENTER_WINDOW event for AquaButton.

Parameters: event – a wx.MouseEvent event to be processed.

OnMouseLeave(event) [source]

Handles the wx.EVT_LEAVE_WINDOW event for AquaButton.

Parameters: event – a wx.MouseEvent event to be processed.

OnPaint(event) [source]

Handles the wx.EVT_PAINT event for AquaButton.

Parameters: event – a wx.PaintEvent event to be processed.

OnPulseTimer(event) [source]

Handles the wx.EVT_TIMER event for AquaButton.

Parameters: event – a wx.TimerEvent event to be processed.

Note

This method is only invoked when pulseOnFocus is True.

OnSize(event) [source]

Handles the wx.EVT_SIZE event for AquaButton.

Parameters: event – a wx.SizeEvent event to be processed.

SetBackgroundColor(colour)

Sets the AquaButton background colour.

Parameters: colour – a valid wx.Colour object.

Note

Overridden from wx.PyControl.

SetBackgroundColour(colour) [source]

Sets the AquaButton background colour.

Parameters: colour – a valid wx.Colour object.

Note

Overridden from wx.PyControl.

SetBestSize(size=None)

Given the current font and bezel width settings, calculate and set a good size.

Parameters: size – an instance of wx.Size or None, in which case the wxWidgets wx.DefaultSize is used instead.

SetBitmapLabel(bitmap) [source]

Sets the bitmap label for the button.

Parameters: bitmap – the bitmap label to set, an instance of wx.Bitmap.

SetDefault() [source]

This sets the 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 wx.Window.SetFocus which sets the keyboard focus for windows and text panel items, and wx.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 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.

SetDisabledColor(colour)

Sets the button colour when it is disabled.

Parameters: colour – a valid wx.Colour object.

SetDisabledColour(colour) [source]

Sets the button colour when it is disabled.

Parameters: colour – a valid wx.Colour object.

SetForegroundColour(colour) [source]

Sets the AquaButton foreground (text) colour.

Parameters: colour – a valid wx.Colour object.

Note

Overridden from wx.PyControl.

SetHoverColor(colour)

Sets the button colour when the mouse is hovering on the button.

Parameters: colour – a valid wx.Colour object.

SetHoverColour(colour) [source]

Sets the button colour when the mouse is hovering on the button.

Parameters: colour – a valid wx.Colour object.

SetInitialSize(size=None) [source]

Given the current font and bezel width settings, calculate and set a good size.

Parameters: size – an instance of wx.Size or None, in which case the wxWidgets wx.DefaultSize is used instead.

SetPulseOnFocus(pulse) [source]

Sets whether to enable the pulsing effect on gaining focus or not.

Parameters: pulse (bool) – True to enable pulsing when the AquaButton gains focus, False to disable this effect.

ShouldInheritColours() [source]

Overridden base class virtual. Buttons usually don’t inherit the parent’s colours.

Note

Overridden from wx.PyControl.

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • infobar
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • aquabutton »
  • AquaButton


AquaButtonEvent

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • aquabutton »
  • AquaButtonEvent

AquaButtonEvent

Event sent from the AquaButton buttons when the button is activated.

hierarchy Inheritance Diagram

Inheritance diagram for: AquaButtonEvent

Inheritance diagram of AquaButtonEvent

Methods Summary

__init__ | Default class constructor.
GetButtonObj | Returns the object associated with this event.
SetButtonObj | Sets the event object for the event.

API Class API

class AquaButtonEvent(wx.PyCommandEvent) [source]

Event sent from the AquaButton buttons when the button is activated.

__init__(eventType, eventId) [source]

Default class constructor.

Parameters:
  • eventType (integer) – the event type;
  • eventId (integer) – the event identifier.

GetButtonObj() [source]

Returns the object associated with this event.

Returns: An instance of AquaButton.

SetButtonObj(btn) [source]

Sets the event object for the event.

Parameters: btn – the button object, an instance of AquaButton.

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • infobar
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • aquabutton »
  • AquaButtonEvent


AquaToggleButton

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • aquabutton »
  • AquaToggleButton

AquaToggleButton

An AquaButton toggle button.

hierarchy Inheritance Diagram

Inheritance diagram for: AquaToggleButton

Inheritance diagram of AquaToggleButton

supclasses Known Superclasses

  • aquabutton.AquaButton
  • aquabutton.__ToggleMixin

API Class API

class AquaToggleButton(__ToggleMixin, AquaButton) [source]

An AquaButton toggle button.

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • infobar
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • aquabutton »
  • AquaToggleButton


SVN Revision 68343 For aquabutton

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • aquabutton »
  • SVN Revision 68343 For aquabutton

svn SVN Revision 68343 For aquabutton

This file contains the SVN revision history for aquabutton, at revision 68343.

Available information include commit date, the name of the committer, the file size, the SVN log messages and a diff from the previous version (if available).

File Information

  • Commit Date: 11-Dec-2009 11:51:15 UTC
  • Committer: AG
  • File Size: 25965 byte(s)

Log Messages

The following log message was entered by the committer:

  • AquaButton: added the possibility to use it as a toggle button;
  • SuperToolTip: Simple check to avoid starting many SuperToolTips at once.

Diff To Previous Version (66805)

Version SVN diff:

--- wxPython/3rdParty/AGW/agw/aquabutton.py 2011/01/28 15:22:45     66805
+++ wxPython/3rdParty/AGW/agw/aquabutton.py 2011/07/23 19:24:24     68343
@@ -2,7 +2,7 @@
# AQUABUTTON wxPython IMPLEMENTATION
#
# Andrea Gavana, @ 07 October 2008
-# Latest Revision: 27 Jan 2011, 15.00 GMT
+# Latest Revision: 22 Jul 2011, 21.00 GMT
#
#
# TODO List
@@ -63,7 +63,7 @@
================= ==================================================
Event Name        Description
================= ==================================================
-``wx.EVT_BUTTON`` Process a `wx.wxEVT_COMMAND_BUTTON_CLICKED` event, when the button is clicked.
+``wx.EVT_BUTTON`` Process a `wx.wxEVT_COMMAND_BUTTON_CLICKED` event, when the button is clicked.
================= ==================================================

@@ -72,9 +72,9 @@

AquaButton control is distributed under the wxPython license.

-Latest Revision: Andrea Gavana @ 27 Jan 2011, 15.00 GMT
+Latest Revision: Andrea Gavana @ 22 Jul 2011, 21.00 GMT

-Version 0.3
+Version 0.4

"""

@@ -87,7 +87,7 @@

class AquaButtonEvent(wx.PyCommandEvent):
""" Event sent from the Aqua buttons when the button is activated. """
-
+
def __init__(self, eventType, eventId):
"""
Default class constructor.
@@ -95,7 +95,7 @@
:param `eventType`: the event type;
:param `eventId`: the event identifier.
"""
-
+
wx.PyCommandEvent.__init__(self, eventType, eventId)
self.isDown = False
self.theButton = None
@@ -107,16 +107,16 @@

:param `btn`: the button object.
"""
-
+
self.theButton = btn

def GetButtonObj(self):
""" Returns the object associated with this event. """
-
+
return self.theButton

-
+
class AquaButton(wx.PyControl):
""" This is the main class implementation of L{AquaButton}. """

@@ -142,7 +142,7 @@
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)
@@ -160,30 +160,33 @@
self.Bind(wx.EVT_LEFT_DCLICK, self.OnLeftDown)

self._mouseAction = None
-        self._bitmap = bitmap
+        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._backColour = wx.Colour(147, 202, 255)
self._hoverColour = self.LightColour(self._backColour, 30)
self._textColour = wx.BLACK
else:
self._backColour = wx.SystemSettings.GetColour(wx.SYS_COLOUR_ACTIVECAPTION)
self._hoverColour = self.LightColour(self._backColour, 30)
self._textColour = wx.WHITE
-
+
+    def SetBitmapLabel(self, bitmap):
+        self._bitmap=bitmap
+        self.Refresh()

def LightColour(self, colour, percent):
"""
@@ -209,7 +212,7 @@

return wx.Colour(r, g, b)

-
+
def OnPaint(self, event):
"""
Handles the ``wx.EVT_PAINT`` event for L{AquaButton}.
@@ -221,15 +224,15 @@
gc = wx.GraphicsContext.Create(dc)

xpos, ypos, width, height = self.GetClientRect()
-
-        dc.SetBackground(wx.Brush(self.GetParent().GetBackgroundColour()))
+
+        dc.SetBackground(wx.Brush(self.GetParent().GetBackgroundColour()))
dc.Clear()
gc.SetBrush(wx.WHITE_BRUSH)

shadowOffset = 5
btnOffset = 0
clr = self._backColour
-
+
if self._mouseAction == CLICK:
shadowOffset = 3
clr = self._hoverColour
@@ -237,15 +240,15 @@

elif 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)
+        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)
@@ -255,7 +258,7 @@
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))

@@ -268,7 +271,7 @@
gc.FillPath(path3) #draw top bubble

font = gc.CreateFont(self.GetFont(), self._textColour)
-
+
gc.SetFont(font)
label = self.GetLabel()
tw, th = gc.GetTextExtent(label)
@@ -277,8 +280,8 @@
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
+
+        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
@@ -293,7 +296,7 @@
memory = wx.MemoryDC()
self._storedBitmap = wx.EmptyBitmapRGBA(width, height)
memory.SelectObject(self._storedBitmap)
-
+
gcMemory = wx.GraphicsContext.Create(memory)

gcMemory.SetBrush(br1)
@@ -310,7 +313,7 @@
memory.SelectObject(wx.NullBitmap)
self._storedBitmap = self._storedBitmap.ConvertToImage()

-
+
def GetPath(self, gc, rc, r):
"""
Returns a rounded `wx.GraphicsPath` rectangle.
@@ -319,13 +322,13 @@
:param `rc`: a client rectangle;
:param `r`: the radius of the rounded part of the rectangle.
"""
-
+
x, y, w, h = rc
path = gc.CreatePath()
path.AddRoundedRectangle(x, y, w, h, r)
path.CloseSubpath()
return path
-
+

def OnSize(self, event):
"""
@@ -346,7 +349,7 @@

if not self.IsEnabled():
return
-
+
self._mouseAction = CLICK
self.CaptureMouse()
self.Refresh()
@@ -362,13 +365,13 @@

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()
@@ -388,7 +391,7 @@

if not self.IsEnabled():
return
-
+
self._mouseAction = HOVER
self.Refresh()
event.Skip()
@@ -412,7 +415,7 @@

:param `event`: a `wx.FocusEvent` event to be processed.
"""
-
+
self._hasFocus = True
self.Refresh()
self.Update()
@@ -432,7 +435,7 @@
if self._pulseOnFocus:
self._gammaFactor = 1.0
self._timer.Stop()
-
+
self._hasFocus = False
self.Refresh()
self.Update()
@@ -444,7 +447,7 @@

:param `event`: a `wx.KeyEvent` event to be processed.
"""
-
+
if self._hasFocus and event.GetKeyCode() == ord(" "):
self._mouseAction = HOVER
self.Refresh()
@@ -477,8 +480,8 @@
if not self._storedBitmap.IsOk():
self._timer.Stop()
return
-
-        xpos, ypos, width, height = self.GetClientRect()
+
+        xpos, ypos, width, height = self.GetClientRect()
gamma = self._gammaFactor

if gamma >= 1.3:
@@ -487,27 +490,27 @@
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 `wx.Size`.
+        :param `size`: an instance of `wx.Size`.
"""
-
+
if size is None:
-            size = wx.DefaultSize
+            size = wx.DefaultSize
wx.PyControl.SetInitialSize(self, size)

SetBestSize = SetInitialSize
-
+

def AcceptsFocus(self):
"""
@@ -515,7 +518,7 @@

:note: Overridden from `wx.PyControl`.
"""
-
+
return self.IsShown() and self.IsEnabled()

@@ -524,7 +527,7 @@
Overridden base class virtual. By default we should use
the same font/colour attributes as the native `wx.Button`.
"""
-
+
return wx.Button.GetClassDefaultAttributes()

@@ -535,19 +538,19 @@

:note: Overridden from `wx.PyControl`.
"""
-
+
return False
-
+

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

:param `enable`: ``True`` to enable the button, ``False`` to disable it.
-
+
:note: Overridden from `wx.PyControl`.
"""
-
+
wx.PyControl.Enable(self, enable)
self.Refresh()

@@ -562,7 +565,7 @@

if pulse == self._pulseOnFocus:
return
-
+
self._pulseOnFocus = pulse
self.Invalidate()

@@ -571,8 +574,8 @@
""" Returns whether the pulsing effect is active. """

return self._pulseOnFocus
-
-
+
+
def DoGetBestSize(self):
"""
Overridden base class virtual. Determines the best size of the
@@ -582,11 +585,11 @@
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 = 30
if self._bitmap:
@@ -595,7 +598,7 @@
retHeight = max(bmpHeight, retHeight)
constant = 24

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

def SetBackgroundColour(self, colour):
@@ -620,7 +623,7 @@
"""

return self._backColour
-
+

def SetHoverColour(self, colour):
"""
@@ -637,12 +640,12 @@
""" Returns the button colour when the mouse is hovering on the button. """

return self._hoverColour
-
+

SetBackgroundColor = SetBackgroundColour
SetHoverColor = SetHoverColour
GetHoverColor = GetHoverColour
-
+

def SetForegroundColour(self, colour):
"""
@@ -666,31 +669,243 @@
"""

return self._textColour
-
+

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

self._saveBitmap = True
self._storedBitmap = wx.NullBitmap
-
-        self.Refresh()
+
+        self.Refresh()

def SetDefault(self):
""" Sets the default button. """
-
+
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 L{AquaButton} in the corresponding toggle button.
+    """
+
+    def SetToggle(self, flag):
+        """
+        Sets the button as toggled/not toggled.
+
+        :param `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 not self.up
+
+    GetValue = GetToggle
+
+
+    def OnLeftDown(self, event):
+        """
+        Handles the ``wx.EVT_LEFT_DOWN`` event for L{AquaButton} when used as toggle button.
+
+        :param `event`: a `wx.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 L{AquaButton} when used as toggle button.
+
+        :param `event`: a `wx.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 L{AquaButton} when used as toggle button.
+
+        :param `event`: a `wx.KeyEvent` event to be processed.
+        """
+
+        event.Skip()
+
+
+    def OnMotion(self, event):
+        """
+        Handles the ``wx.EVT_MOTION`` event for L{AquaButton} when used as toggle button.
+
+        :param `event`: a `wx.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 L{AquaButton} when used as toggle button.
+
+        :param `event`: a `wx.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 L{AquaButton} when used as toggle button.
+
+        :param `event`: a `wx.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(width, height)
+            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 L{AquaButton} toggle button"""
+    pass
+

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • aquabutton »
  • SVN Revision 68343 For aquabutton


SVN Revision 68475 For aquabutton

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • aquabutton »
  • SVN Revision 68475 For aquabutton

svn SVN Revision 68475 For aquabutton

This file contains the SVN revision history for aquabutton, at revision 68475.

Available information include commit date, the name of the committer, the file size, the SVN log messages and a diff from the previous version (if available).

File Information

  • Commit Date: 22-Jun-2009 15:50:25 UTC
  • Committer: AG
  • File Size: 27774 byte(s)

Log Messages

The following log message was entered by the committer:

framemanager.py: Implementation of the AUI_MINIMIZE_POS_TOOLBAR flag, which allows to minimize a pane inside an existing toolbar. Limitation: if the minimized icon in the toolbar ends up in the overflowing items (i.e., a menu is needed to show the icon), this style will not work.

Diff To Previous Version (68362)

Version SVN diff:

--- wxPython/3rdParty/AGW/agw/aquabutton.py 2011/07/24 21:36:47     68362
+++ wxPython/3rdParty/AGW/agw/aquabutton.py 2011/07/31 20:22:23     68475
@@ -2,7 +2,7 @@
# AQUABUTTON wxPython IMPLEMENTATION
#
# Andrea Gavana, @ 07 October 2008
-# Latest Revision: 22 Jul 2011, 21.00 GMT
+# Latest Revision: 26 Jul 2011, 22.00 GMT
#
#
# TODO List
@@ -23,14 +23,14 @@
# --------------------------------------------------------------------------------- #

"""
-AquaButton is another custom-drawn button class which *approximatively* mimics
+L{AquaButton} is another custom-drawn button class which *approximatively* mimics
the behaviour of Aqua buttons on the Mac.

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

-AquaButton is another custom-drawn button class which *approximatively* mimics
+L{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;
@@ -42,11 +42,39 @@
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).
+  * Windows (Windows XP);
+  * Linux Ubuntu (10.10).

Window Styles
@@ -70,9 +98,9 @@
License And Version
===================

-AquaButton control is distributed under the wxPython license.
+L{AquaButton} control is distributed under the wxPython license.

-Latest Revision: Andrea Gavana @ 22 Jul 2011, 21.00 GMT
+Latest Revision: Andrea Gavana @ 26 Jul 2011, 22.00 GMT

Version 0.4

@@ -86,7 +114,7 @@

class AquaButtonEvent(wx.PyCommandEvent):
-    """ Event sent from the Aqua buttons when the button is activated. """
+    """ Event sent from the L{AquaButton} buttons when the button is activated. """

def __init__(self, eventType, eventId):
"""
@@ -184,10 +212,18 @@
self._hoverColour = self.LightColour(self._backColour, 30)
self._textColour = wx.WHITE

+
def SetBitmapLabel(self, bitmap):
-        self._bitmap=bitmap
+        """
+        Sets the bitmap label for the button.
+
+        :param `bitmap`: the bitmap label to set, an instance of `wx.Bitmap`.
+        """
+
+        self._bitmap = bitmap
self.Refresh()

+
def LightColour(self, colour, percent):
"""
Return light contrast of `colour`. The colour returned is from the scale of
@@ -204,7 +240,7 @@
bd = end_colour.Blue() - colour.Blue()
high = 100

-        # We take the percent way of the colour from colour -. white
+        # 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
@@ -526,6 +562,8 @@
"""
Overridden base class virtual. By default we should use
the same font/colour attributes as the native `wx.Button`.
+
+        :note: Overridden from `wx.PyControl`.
"""

return wx.Button.GetClassDefaultAttributes()
@@ -580,6 +618,8 @@
"""
Overridden base class virtual. Determines the best size of the
button based on the label and bezel size.
+
+        :note: Overridden from `wx.PyControl`.
"""

label = self.GetLabel()
@@ -681,7 +721,20 @@

def SetDefault(self):
-        """ Sets the default button. """
+        """
+        This sets the L{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 `wx.Window.SetFocus` which sets the
+         keyboard focus for windows and text panel items, and `wx.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 L{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'):
@@ -775,17 +828,21 @@

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:
+            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):
+
+            if x < 0 or y < 0 or x >= w or y >= h:
self.up = self.saveUp
self.Refresh()
return
+
event.Skip()

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • aquabutton »
  • SVN Revision 68475 For aquabutton


SVN Revision 68881 For aquabutton

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • aquabutton »
  • SVN Revision 68881 For aquabutton

svn SVN Revision 68881 For aquabutton

This file contains the SVN revision history for aquabutton, at revision 68881.

Available information include commit date, the name of the committer, the file size, the SVN log messages and a diff from the previous version (if available).

File Information

  • Commit Date: 29-May-2009 08:06:58 UTC
  • Committer: AG
  • File Size: 27892 byte(s)

Log Messages

The following log message was entered by the committer:

  • AGW: General overhaul of the documentation, much improved. All the widgets have their own sample usage in the docs as well;

  • FlatNotebook: Added the FNB_NAV_BUTTONS_WHEN_NEEDED style, which hides the navigation left/right arrows if all tabs fit;

  • RibbonBar: - Added the EVT_RIBBONBAR_TAB_LEFT_DCLICK event, which generates a special event

    when a ribbon bar tab is double-clicked;

    • Added support for toggle buttons;
    • Improved support for ribbon panel sizers: panels with sizers should now automatically minimise at small sizes, and behave properly when popping up from a minimised state;
    • Added tooltips via SetToolTip for those buttons which have the help_string attribute set.

  • XLSGrid: a new widget was added to AGW, termed XLSGrid. It’s based on wx.grid.Grid and can be used to faithfully reproduce the appearance of a Microsoft Excel spreadsheets.

Diff To Previous Version (68475)

Version SVN diff:

--- wxPython/3rdParty/AGW/agw/aquabutton.py 2011/07/31 20:22:23     68475
+++ wxPython/3rdParty/AGW/agw/aquabutton.py 2011/08/25 16:40:17     68881
@@ -2,7 +2,7 @@
# AQUABUTTON wxPython IMPLEMENTATION
#
# Andrea Gavana, @ 07 October 2008
-# Latest Revision: 26 Jul 2011, 22.00 GMT
+# Latest Revision: 17 Aug 2011, 15.00 GMT
#
#
# TODO List
@@ -100,7 +100,7 @@

L{AquaButton} control is distributed under the wxPython license.

-Latest Revision: Andrea Gavana @ 26 Jul 2011, 22.00 GMT
+Latest Revision: Andrea Gavana @ 17 Aug 2011, 15.00 GMT

Version 0.4

@@ -110,7 +110,9 @@

# Constants for the hovering and clicking effects
HOVER = 1
+""" Indicates that the mouse is hovering over L{AquaButton} """
CLICK = 2
+""" Indicates that L{AquaButton} has been clicked """

class AquaButtonEvent(wx.PyCommandEvent):

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • aquabutton »
  • SVN Revision 68881 For aquabutton


SVN Revision 69086 For aquabutton

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • aquabutton »
  • SVN Revision 69086 For aquabutton

svn SVN Revision 69086 For aquabutton

This file contains the SVN revision history for aquabutton, at revision 69086.

Available information include commit date, the name of the committer, the file size, the SVN log messages and a diff from the previous version (if available).

File Information

  • Commit Date: 02-Jan-2009 03:09:18 UTC
  • Committer: AG
  • File Size: 28997 byte(s)

Log Messages

The following log message was entered by the committer:

  • Fixed bug #13437 for SuperToolTip;
  • Fixed bug #13477 for UltimateListCtrl.

Diff To Previous Version (68881)

Version SVN diff:

--- wxPython/3rdParty/AGW/agw/aquabutton.py 2011/08/25 16:40:17     68881
+++ wxPython/3rdParty/AGW/agw/aquabutton.py 2011/09/14 19:39:08     69086
@@ -122,8 +122,8 @@
"""
Default class constructor.

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

wx.PyCommandEvent.__init__(self, eventType, eventId)
@@ -135,14 +135,18 @@
"""
Sets the event object for the event.

-        :param `btn`: the button object.
+        :param `btn`: the button object, an instance of L{AquaButton}.
"""

self.theButton = btn

def GetButtonObj(self):
-        """ Returns the object associated with this event. """
+        """
+        Returns the object associated with this event.
+
+        :return: An instance of L{AquaButton}.
+        """

return self.theButton

@@ -156,17 +160,19 @@
"""
Default class constructor.

-        :param `parent`: the L{AquaButton} parent;
-        :param `id`: window identifier. A value of -1 indicates a default value;
-        :param `bitmap`: the button bitmap (if any);
-        :param `label`: the button text label;
+        :param `wx.Window` `parent`: parent window. Must not be ``None``;
+        :param integer `id`: window identifier. A value of -1 indicates a default value;
+        :param `wx.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 `wx.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;
-        :param `style`: the button style (unused);
-        :param `validator`: the validator associated to the button;
-        :param `name`: the button name.
+        :type `size`: tuple or `wx.Size`
+        :param integer `style`: the button style (unused);
+        :param `wx.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)
@@ -231,9 +237,11 @@
Return light contrast of `colour`. The colour returned is from the scale of
`colour` ==> white.

-        :param `colour`: the input colour to be brightened;
-        :param `percent`: determines how light the colour will be. `percent` = 100
-         returns white, `percent` = 0 returns `colour`.
+        :param `colour`: the input colour to be brightened, a valid instance of `wx.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 `wx.Colour`.
"""

end_colour = wx.WHITE
@@ -357,8 +365,10 @@
Returns a rounded `wx.GraphicsPath` rectangle.

:param `gc`: an instance of `wx.GraphicsContext`;
-        :param `rc`: a client rectangle;
-        :param `r`: the radius of the rounded part of the rectangle.
+        :param `wx.Rect` `rc`: a client rectangle;
+        :param float `r`: the radius of the rounded part of the rectangle.
+
+        :return: A rounded rectangle, an instance of `wx.GraphicsPath`.
"""

x, y, w, h = rc
@@ -540,7 +550,8 @@
Given the current font and bezel width settings, calculate
and set a good size.

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

if size is None:
@@ -565,7 +576,9 @@
Overridden base class virtual. By default we should use
the same font/colour attributes as the native `wx.Button`.

-        :note: Overridden from `wx.PyControl`.
+        :return: an instance of `wx.VisualAttributes`.
+
+        :note: Overridden from `wx.PyControl`.
"""

return wx.Button.GetClassDefaultAttributes()
@@ -586,7 +599,7 @@
"""
Enables/disables the button.

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

:note: Overridden from `wx.PyControl`.
"""
@@ -599,7 +612,7 @@
"""
Sets whether to enable the pulsing effect on gaining focus or not.

-        :param `pulse`: ``True`` to enable pulsing when the L{AquaButton} gains focus,
+        :param bool `pulse`: ``True`` to enable pulsing when the L{AquaButton} gains focus,
``False`` to disable this effect.
"""

@@ -611,7 +624,11 @@

def GetPulseOnFocus(self):
-        """ Returns whether the pulsing effect is active. """
+        """
+        Returns whether the pulsing effect is active.
+
+        :return: ``True`` if the pulsing effect is active, ``False`` otherwise.
+        """

return self._pulseOnFocus

@@ -621,6 +638,8 @@
Overridden base class virtual. Determines the best size of the
button based on the label and bezel size.

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

@@ -661,6 +680,8 @@
"""
Returns the button colour when the mouse is not hovering on the button.

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

@@ -679,7 +700,11 @@

def GetHoverColour(self):
-        """ Returns the button colour when the mouse is hovering on the button. """
+        """
+        Returns the button colour when the mouse is hovering on the button.
+
+        :return: An instance of `wx.Colour`.
+        """

return self._hoverColour

@@ -707,6 +732,8 @@
"""
Returns the text colour for L{AquaButton}.

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

@@ -761,7 +788,7 @@
"""
Sets the button as toggled/not toggled.

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

self.up = not flag
@@ -771,7 +798,11 @@

def GetToggle(self):
-        """ Returns the toggled state of a button. """
+        """
+        Returns the toggled state of a button.
+
+        :return: ``True`` is the button is toggled, ``False`` if it is not toggled.
+        """

return not self.up

@@ -965,6 +996,6 @@

class AquaToggleButton(__ToggleMixin, AquaButton):
-    """ An L{AquaButton} toggle button"""
+    """ An L{AquaButton} toggle button. """
pass

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • aquabutton »
  • SVN Revision 69086 For aquabutton


SVN Revision 69134 For aquabutton

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • aquabutton »
  • SVN Revision 69134 For aquabutton

svn SVN Revision 69134 For aquabutton

This file contains the SVN revision history for aquabutton, at revision 69134.

Available information include commit date, the name of the committer, the file size, the SVN log messages and a diff from the previous version (if available).

File Information

  • Commit Date: 20-Oct-2008 20:05:15 UTC
  • Committer: AG
  • File Size: 29743 byte(s)

Log Messages

The following log message was entered by the committer:

  • AquaButton: applied patch from Werner with the option of selecting the disabled colour;
  • FoldPanelBar: Fixed ticket #13485.

Diff To Previous Version (69086)

Version SVN diff:

--- wxPython/3rdParty/AGW/agw/aquabutton.py 2011/09/14 19:39:08     69086
+++ wxPython/3rdParty/AGW/agw/aquabutton.py 2011/09/17 22:02:20     69134
@@ -2,7 +2,7 @@
# AQUABUTTON wxPython IMPLEMENTATION
#
# Andrea Gavana, @ 07 October 2008
-# Latest Revision: 17 Aug 2011, 15.00 GMT
+# Latest Revision: 17 Sep 2011, 23.00 GMT
#
#
# TODO List
@@ -100,7 +100,7 @@

L{AquaButton} control is distributed under the wxPython license.

-Latest Revision: Andrea Gavana @ 17 Aug 2011, 15.00 GMT
+Latest Revision: Andrea Gavana @ 17 Sep 2011, 17.00 GMT

Version 0.4

@@ -214,10 +214,12 @@
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
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

@@ -286,6 +288,9 @@

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)
@@ -709,9 +714,31 @@
return self._hoverColour

+    def SetDisabledColour(self, colour):
+        """
+        Sets the button colour when it is disabled.
+
+        :param `colour`: a valid `wx.Colour` object.
+        """
+
+        self._disableColour = colour
+        self.Invalidate()
+
+
+    def GetDisabledColour(self):
+        """
+        Returns the button colour when it is disabled.
+
+        :return: An instance of `wx.Colour`.
+        """
+
+        return self._disableColour
+
SetBackgroundColor = SetBackgroundColour
SetHoverColor = SetHoverColour
GetHoverColor = GetHoverColour
+    SetDisabledColor = SetDisabledColour
+    GetDisabledColor = GetDisabledColour

def SetForegroundColour(self, colour):

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • aquabutton »
  • SVN Revision 69134 For aquabutton


SVN Revision 69719 For aquabutton

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • aquabutton »
  • SVN Revision 69719 For aquabutton

svn SVN Revision 69719 For aquabutton

This file contains the SVN revision history for aquabutton, at revision 69719.

Available information include commit date, the name of the committer, the file size, the SVN log messages and a diff from the previous version (if available).

File Information

  • Commit Date: 17-Oct-2008 20:51:43 UTC
  • Committer: AG
  • File Size: 29743 byte(s)

Log Messages

The following log message was entered by the committer:

AquaButton: changed the default height for the button to 24 pixels when the button itself does not have a bitmap.

Diff To Previous Version (69134)

Version SVN diff:

--- wxPython/3rdParty/AGW/agw/aquabutton.py 2011/09/17 22:02:20     69134
+++ wxPython/3rdParty/AGW/agw/aquabutton.py 2011/11/09 21:31:32     69719
@@ -2,7 +2,7 @@
# AQUABUTTON wxPython IMPLEMENTATION
#
# Andrea Gavana, @ 07 October 2008
-# Latest Revision: 17 Sep 2011, 23.00 GMT
+# Latest Revision: 09 Nov 2011, 21.00 GMT
#
#
# TODO List
@@ -100,7 +100,7 @@

L{AquaButton} control is distributed under the wxPython license.

-Latest Revision: Andrea Gavana @ 17 Sep 2011, 17.00 GMT
+Latest Revision: Andrea Gavana @ 09 Nov 2011, 21.00 GMT

Version 0.4

@@ -657,7 +657,7 @@
retWidth, retHeight = dc.GetTextExtent(label)

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

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • aquabutton »
  • SVN Revision 69719 For aquabutton


SVN Revision 69813 For aquabutton

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • aquabutton »
  • SVN Revision 69813 For aquabutton

svn SVN Revision 69813 For aquabutton

This file contains the SVN revision history for aquabutton, at revision 69813.

Available information include commit date, the name of the committer, the file size, the SVN log messages and a diff from the previous version (if available).

File Information

  • Commit Date: 17-Oct-2008 19:15:31 UTC
  • Committer: AG
  • File Size: 29775 byte(s)

Log Messages

The following log message was entered by the committer:

AquaButton: fix zero-sized bitmaps errors.

Diff To Previous Version (69719)

Version SVN diff:

--- wxPython/3rdParty/AGW/agw/aquabutton.py 2011/11/09 21:31:32     69719
+++ wxPython/3rdParty/AGW/agw/aquabutton.py 2011/11/24 22:38:24     69813
@@ -2,7 +2,7 @@
# AQUABUTTON wxPython IMPLEMENTATION
#
# Andrea Gavana, @ 07 October 2008
-# Latest Revision: 09 Nov 2011, 21.00 GMT
+# Latest Revision: 24 Nov 2011, 22.00 GMT
#
#
# TODO List
@@ -100,7 +100,7 @@

L{AquaButton} control is distributed under the wxPython license.

-Latest Revision: Andrea Gavana @ 09 Nov 2011, 21.00 GMT
+Latest Revision: Andrea Gavana @ 22 Nov 2011, 22.00 GMT

Version 0.4

@@ -345,7 +345,7 @@
# Save the bitmap using wx.MemoryDC for later use
self._saveBitmap = False
memory = wx.MemoryDC()
-            self._storedBitmap = wx.EmptyBitmapRGBA(width, height)
+            self._storedBitmap = wx.EmptyBitmapRGBA(max(width, 1), max(height, 1))
memory.SelectObject(self._storedBitmap)

gcMemory = wx.GraphicsContext.Create(memory)
@@ -1002,7 +1002,7 @@
# Save the bitmap using wx.MemoryDC for later use
self._saveBitmap = False
memory = wx.MemoryDC()
-            self._storedBitmap = wx.EmptyBitmapRGBA(width, height)
+            self._storedBitmap = wx.EmptyBitmapRGBA(max(width, 1), max(height, 1))
memory.SelectObject(self._storedBitmap)

gcMemory = wx.GraphicsContext.Create(memory)

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • aquabutton »
  • SVN Revision 69813 For aquabutton


SVN Revision 68881 For art_aui

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • ribbon library »
  • ribbon.art_aui »
  • SVN Revision 68881 For art_aui

svn SVN Revision 68881 For art_aui

This file contains the SVN revision history for art_aui, at revision 68881.

Available information include commit date, the name of the committer, the file size, the SVN log messages and a diff from the previous version (if available).

File Information

  • Commit Date: 10-Dec-2009 18:09:38 UTC
  • Committer: AG
  • File Size: 55981 byte(s)

Log Messages

The following log message was entered by the committer:

  • AGW: General overhaul of the documentation, much improved. All the widgets have their own sample usage in the docs as well;

  • FlatNotebook: Added the FNB_NAV_BUTTONS_WHEN_NEEDED style, which hides the navigation left/right arrows if all tabs fit;

  • RibbonBar: - Added the EVT_RIBBONBAR_TAB_LEFT_DCLICK event, which generates a special event

    when a ribbon bar tab is double-clicked;

    • Added support for toggle buttons;
    • Improved support for ribbon panel sizers: panels with sizers should now automatically minimise at small sizes, and behave properly when popping up from a minimised state;
    • Added tooltips via SetToolTip for those buttons which have the help_string attribute set.

  • XLSGrid: a new widget was added to AGW, termed XLSGrid. It’s based on wx.grid.Grid and can be used to faithfully reproduce the appearance of a Microsoft Excel spreadsheets.

Diff To Previous Version (63108)

Version SVN diff:

--- wxPython/3rdParty/AGW/agw/ribbon/art_aui.py     2010/01/09 21:41:13     63108
+++ wxPython/3rdParty/AGW/agw/ribbon/art_aui.py     2011/08/25 16:40:17     68881
@@ -411,9 +411,10 @@

if self._flags & RIBBON_BAR_SHOW_PAGE_ICONS:
icon = tab.page.GetIcon()
-            if self._flags & RIBBON_BAR_SHOW_PAGE_LABELS == 0:
-                x = tab.rect.x + (tab.rect.width - icon.GetWidth()) / 2
-                dc.DrawBitmap(icon, x, tab.rect.y + 1 + (tab.rect.height - 1 - icon.GetHeight()) / 2, True)
+            if self._flags & RIBBON_BAR_SHOW_PAGE_LABELS == 0:
+                if icon.IsOk():
+                    x = tab.rect.x + (tab.rect.width - icon.GetWidth()) / 2
+                    dc.DrawBitmap(icon, x, tab.rect.y + 1 + (tab.rect.height - 1 - icon.GetHeight()) / 2, True)

if self._flags & RIBBON_BAR_SHOW_PAGE_LABELS:
label = tab.page.GetLabel()
@@ -688,7 +689,12 @@
size.DecBy(6, label_height + 4)
if client_offset is not None:
client_offset = wx.Point(3, label_height + 2)
-
+
+        if size.x < 0:
+            size.x = 0
+        if size.y < 0:
+            size.y = 0
+
return size, client_offset

@@ -1034,6 +1040,11 @@

"""

+        if kind == RIBBON_BUTTON_TOGGLE:
+            kind = RIBBON_BUTTON_NORMAL
+            if state & RIBBON_BUTTONBAR_BUTTON_TOGGLED:
+                state ^= RIBBON_BUTTONBAR_BUTTON_ACTIVE_MASK
+
if state & (RIBBON_BUTTONBAR_BUTTON_HOVER_MASK | RIBBON_BUTTONBAR_BUTTON_ACTIVE_MASK):
dc.SetPen(self._button_bar_hover_border_pen)
bg_rect = wx.Rect(*rect)

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • ribbon library »
  • ribbon.art_aui »
  • SVN Revision 68881 For art_aui


SVN Revision 69086 For art_aui

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • ribbon library »
  • ribbon.art_aui »
  • SVN Revision 69086 For art_aui

svn SVN Revision 69086 For art_aui

This file contains the SVN revision history for art_aui, at revision 69086.

Available information include commit date, the name of the committer, the file size, the SVN log messages and a diff from the previous version (if available).

File Information

  • Commit Date: 18-Nov-2009 22:19:25 UTC
  • Committer: AG
  • File Size: 55983 byte(s)

Log Messages

The following log message was entered by the committer:

  • Fixed bug #13437 for SuperToolTip;
  • Fixed bug #13477 for UltimateListCtrl.

Diff To Previous Version (68881)

Version SVN diff:

--- wxPython/3rdParty/AGW/agw/ribbon/art_aui.py     2011/08/25 16:40:17     68881
+++ wxPython/3rdParty/AGW/agw/ribbon/art_aui.py     2011/09/14 19:39:08     69086
@@ -462,8 +462,8 @@

:param `dc`: A device context to use when one is required for size calculations;
:param `wnd`: The window onto which the tab will eventually be drawn;
-        :param `label`: The tab's label (or wx.EmptyString if it has none);
-        :param `bitmap`: The tab's icon (or wx.NullBitmap if it has none);
+        :param `label`: The tab's label (or an empty string if it has none);
+        :param `bitmap`: The tab's icon (or `wx.NullBitmap` if it has none);
:param `ideal`: The ideal width (in pixels) of the tab;
:param `small_begin_need_separator`: A size less than the size, at which a tab
separator should begin to be drawn (i.e. drawn, but still fairly transparent);
@@ -1152,7 +1152,7 @@
hybrid or dropdown tool, then the foreground should also contain a standard
dropdown button;
:param `kind`: The kind of tool to draw (normal, dropdown, or hybrid);
-        :param `state`: A combination of wx.RibbonToolBarToolState flags giving the
+        :param `state`: A combination of `RibbonToolBarToolState` flags giving the
state of the tool and it's relative position within a tool group.

"""

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • ribbon library »
  • ribbon.art_aui »
  • SVN Revision 69086 For art_aui


SVN Revision 68881 For art_msw

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • ribbon library »
  • ribbon.art_msw »
  • SVN Revision 68881 For art_msw

svn SVN Revision 68881 For art_msw

This file contains the SVN revision history for art_msw, at revision 68881.

Available information include commit date, the name of the committer, the file size, the SVN log messages and a diff from the previous version (if available).

File Information

  • Commit Date: 10-Dec-2009 18:09:38 UTC
  • Committer: AG
  • File Size: 130151 byte(s)

Log Messages

The following log message was entered by the committer:

  • AGW: General overhaul of the documentation, much improved. All the widgets have their own sample usage in the docs as well;

  • FlatNotebook: Added the FNB_NAV_BUTTONS_WHEN_NEEDED style, which hides the navigation left/right arrows if all tabs fit;

  • RibbonBar: - Added the EVT_RIBBONBAR_TAB_LEFT_DCLICK event, which generates a special event

    when a ribbon bar tab is double-clicked;

    • Added support for toggle buttons;
    • Improved support for ribbon panel sizers: panels with sizers should now automatically minimise at small sizes, and behave properly when popping up from a minimised state;
    • Added tooltips via SetToolTip for those buttons which have the help_string attribute set.

  • XLSGrid: a new widget was added to AGW, termed XLSGrid. It’s based on wx.grid.Grid and can be used to faithfully reproduce the appearance of a Microsoft Excel spreadsheets.

Diff To Previous Version (63108)

Version SVN diff:

--- wxPython/3rdParty/AGW/agw/ribbon/art_msw.py     2010/01/09 21:41:13     63108
+++ wxPython/3rdParty/AGW/agw/ribbon/art_msw.py     2011/08/25 16:40:17     68881
@@ -48,14 +48,14 @@
gallery_extension_xpm = ["5 5 2 1", "  c None", "x c #FF00FF", "xxxxx", "     ", "xxxxx", " xxx ", "  x  "]

-def LikePrimary(primary_hsl, h, s, l):
+def LikePrimary(primary_hsl, is_gray, h, s, l):

-    return primary_hsl.ShiftHue(h).Saturated(s).Lighter(l).ToRGB()
+    return primary_hsl.ShiftHue(h).Saturated((is_gray and [0] or [s])[0]).Lighter(l).ToRGB()

-def LikeSecondary(secondary_hsl, h, s, l):
+def LikeSecondary(secondary_hsl, is_gray, h, s, l):

-    return secondary_hsl.ShiftHue(h).Saturated(s).Lighter(l).ToRGB()
+    return secondary_hsl.ShiftHue(h).Saturated((is_gray and [0] or [s])[0]).Lighter(l).ToRGB()

def SingleLine(dc, rect, start, finish):
@@ -68,9 +68,9 @@
def __init__(self, set_colour_scheme=True):

self._flags = 0
-        self._tab_label_font = wx.Font(8, wx.SWISS, wx.NORMAL, wx.NORMAL, False)
-        self._button_bar_label_font = wx.Font(8, wx.SWISS, wx.NORMAL, wx.NORMAL, False)
-        self._panel_label_font = wx.Font(8, wx.SWISS, wx.NORMAL, wx.NORMAL, False)
+        self._tab_label_font = wx.NORMAL_FONT
+        self._button_bar_label_font = wx.NORMAL_FONT
+        self._panel_label_font = wx.NORMAL_FONT

self._gallery_up_bitmap = [wx.NullBitmap for i in xrange(4)]
self._gallery_down_bitmap = [wx.NullBitmap for i in xrange(4)]
@@ -155,102 +155,113 @@
# tertiary not used for anything

# Map primary saturation from [0, 1] to [.25, .75]
-        primary_hsl.saturation = cos(primary_hsl.saturation * M_PI) * -0.25 + 0.5
+        primary_is_gray = False
+        gray_saturation_threshold = 0.01
+
+        if primary_hsl.saturation <= gray_saturation_threshold:
+            primary_is_gray = True
+        else:
+            primary_hsl.saturation = cos(primary_hsl.saturation * M_PI) * -0.25 + 0.5

# Map primary luminance from [0, 1] to [.23, .83]
primary_hsl.luminance = cos(primary_hsl.luminance * M_PI) * -0.3 + 0.53

# Map secondary saturation from [0, 1] to [0.16, 0.84]
-        secondary_hsl.saturation = cos(secondary_hsl.saturation * M_PI) * -0.34 + 0.5
+        secondary_is_gray = False
+
+        if secondary_hsl.saturation <= gray_saturation_threshold:
+            secondary_is_gray = True
+        else:
+            secondary_hsl.saturation = cos(secondary_hsl.saturation * M_PI) * -0.34 + 0.5

# Map secondary luminance from [0, 1] to [0.1, 0.9]
secondary_hsl.luminance = cos(secondary_hsl.luminance * M_PI) * -0.4 + 0.5

-        self._page_border_pen = wx.Pen(LikePrimary(primary_hsl, 1.4, 0.00, -0.08))
-
-        self._page_background_top_colour = LikePrimary(primary_hsl, -0.1, -0.03, 0.12)
-        self._page_hover_background_top_colour = LikePrimary(primary_hsl, -2.8, 0.27, 0.17)
-        self._page_background_top_gradient_colour = LikePrimary(primary_hsl, 0.1, -0.10, 0.08)
-        self._page_hover_background_top_gradient_colour = LikePrimary(primary_hsl, 3.2, 0.16, 0.13)
-        self._page_background_colour = LikePrimary(primary_hsl, 0.4, -0.09, 0.05)
-        self._page_hover_background_colour = LikePrimary(primary_hsl, 0.1, 0.19, 0.10)
-        self._page_background_gradient_colour = LikePrimary(primary_hsl, -3.2, 0.27, 0.10)
-        self._page_hover_background_gradient_colour = LikePrimary(primary_hsl, 1.8, 0.01, 0.15)
-
-        self._tab_active_background_colour = LikePrimary(primary_hsl, -0.1, -0.31, 0.16)
-        self._tab_active_background_gradient_colour = LikePrimary(primary_hsl, -0.1, -0.03, 0.12)
-        self._tab_separator_colour = LikePrimary(primary_hsl, 0.9, 0.24, 0.05)
-        self._tab_ctrl_background_brush = wx.Brush(LikePrimary(primary_hsl, 1.0, 0.39, 0.07))
-        self._tab_hover_background_colour = LikePrimary(primary_hsl, 1.3, 0.15, 0.10)
-        self._tab_hover_background_top_colour = LikePrimary(primary_hsl, 1.4, 0.36, 0.08)
-        self._tab_border_pen = wx.Pen(LikePrimary(primary_hsl, 1.4, 0.03, -0.05)  )
-        self._tab_separator_gradient_colour = LikePrimary(primary_hsl, 1.7, -0.15, -0.18)
-        self._tab_hover_background_top_gradient_colour = LikePrimary(primary_hsl, 1.8, 0.34, 0.13)
-        self._tab_label_colour = LikePrimary(primary_hsl, 4.3, 0.13, -0.49)
-        self._tab_hover_background_gradient_colour = LikeSecondary(primary_hsl, -1.5, -0.34, 0.01)
-
-        self._panel_minimised_border_gradient_pen = wx.Pen(LikePrimary(primary_hsl, -6.9, -0.17, -0.09))
-        self._panel_minimised_border_pen = wx.Pen(LikePrimary(primary_hsl, -5.3, -0.24, -0.06))
-        self._panel_border_gradient_pen = wx.Pen(LikePrimary(primary_hsl, -5.2, -0.15, -0.06))
-        self._panel_border_pen = wx.Pen(LikePrimary(primary_hsl, -2.8, -0.32, 0.02))
-        self._panel_label_background_brush = wx.Brush(LikePrimary(primary_hsl, -1.5, 0.03, 0.05))
-        self._panel_active_background_gradient_colour = LikePrimary(primary_hsl, 0.5, 0.34, 0.05)
-        self._panel_hover_label_background_brush = wx.Brush(LikePrimary(primary_hsl, 1.0, 0.30, 0.09))
-        self._panel_active_background_top_gradient_colour = LikePrimary(primary_hsl, 1.4, -0.17, -0.13)
-        self._panel_active_background_colour = LikePrimary(primary_hsl, 1.6, -0.18, -0.18)
-        self._panel_active_background_top_colour = LikePrimary(primary_hsl, 1.7, -0.20, -0.03)
-        self._panel_label_colour = LikePrimary(primary_hsl, 2.8, -0.14, -0.35)
+        self._page_border_pen = wx.Pen(LikePrimary(primary_hsl, primary_is_gray, 1.4, 0.00, -0.08))
+        self._page_background_top_colour = LikePrimary(primary_hsl, primary_is_gray, -0.1, -0.03, 0.12)
+        self._page_hover_background_top_colour = LikePrimary(primary_hsl, primary_is_gray, -2.8, 0.27, 0.17)
+        self._page_background_top_gradient_colour = LikePrimary(primary_hsl, primary_is_gray, 0.1, -0.10, 0.08)
+        self._page_hover_background_top_gradient_colour = LikePrimary(primary_hsl, primary_is_gray, 3.2, 0.16, 0.13)
+        self._page_background_colour = LikePrimary(primary_hsl, primary_is_gray, 0.4, -0.09, 0.05)
+        self._page_hover_background_colour = LikePrimary(primary_hsl, primary_is_gray, 0.1, 0.19, 0.10)
+        self._page_background_gradient_colour = LikePrimary(primary_hsl, primary_is_gray, -3.2, 0.27, 0.10)
+        self._page_hover_background_gradient_colour = LikePrimary(primary_hsl, primary_is_gray, 1.8, 0.01, 0.15)
+
+        self._tab_active_background_colour = LikePrimary(primary_hsl, primary_is_gray, -0.1, -0.31, 0.16)
+        self._tab_active_background_gradient_colour = LikePrimary(primary_hsl, primary_is_gray, -0.1, -0.03, 0.12)
+        self._tab_separator_colour = LikePrimary(primary_hsl, primary_is_gray, 0.9, 0.24, 0.05)
+        self._tab_ctrl_background_brush = wx.Brush(LikePrimary(primary_hsl, primary_is_gray, 1.0, 0.39, 0.07))
+        self._tab_hover_background_colour = LikePrimary(primary_hsl, primary_is_gray, 1.3, 0.15, 0.10)
+        self._tab_hover_background_top_colour = LikePrimary(primary_hsl, primary_is_gray, 1.4, 0.36, 0.08)
+        self._tab_border_pen = wx.Pen(LikePrimary(primary_hsl, primary_is_gray, 1.4, 0.03, -0.05)  )
+        self._tab_separator_gradient_colour = LikePrimary(primary_hsl, primary_is_gray, 1.7, -0.15, -0.18)
+        self._tab_hover_background_top_gradient_colour = LikePrimary(primary_hsl, primary_is_gray, 1.8, 0.34, 0.13)
+        self._tab_label_colour = LikePrimary(primary_hsl, primary_is_gray, 4.3, 0.13, -0.49)
+        self._tab_hover_background_gradient_colour = LikeSecondary(primary_hsl, secondary_is_gray, -1.5, -0.34, 0.01)
+
+        self._panel_minimised_border_gradient_pen = wx.Pen(LikePrimary(primary_hsl, primary_is_gray, -6.9, -0.17, -0.09))
+        self._panel_minimised_border_pen = wx.Pen(LikePrimary(primary_hsl, primary_is_gray, -5.3, -0.24, -0.06))
+        self._panel_border_gradient_pen = wx.Pen(LikePrimary(primary_hsl, primary_is_gray, -5.2, -0.15, -0.06))
+        self._panel_border_pen = wx.Pen(LikePrimary(primary_hsl, primary_is_gray, -2.8, -0.32, 0.02))
+        self._panel_label_background_brush = wx.Brush(LikePrimary(primary_hsl, primary_is_gray, -1.5, 0.03, 0.05))
+        self._panel_active_background_gradient_colour = LikePrimary(primary_hsl, primary_is_gray, 0.5, 0.34, 0.05)
+        self._panel_hover_label_background_brush = wx.Brush(LikePrimary(primary_hsl, primary_is_gray, 1.0, 0.30, 0.09))
+        self._panel_active_background_top_gradient_colour = LikePrimary(primary_hsl, primary_is_gray, 1.4, -0.17, -0.13)
+        self._panel_active_background_colour = LikePrimary(primary_hsl, primary_is_gray, 1.6, -0.18, -0.18)
+        self._panel_active_background_top_colour = LikePrimary(primary_hsl, primary_is_gray, 1.7, -0.20, -0.03)
+        self._panel_label_colour = LikePrimary(primary_hsl, primary_is_gray, 2.8, -0.14, -0.35)
self._panel_hover_label_colour = self._panel_label_colour
self._panel_minimised_label_colour = self._tab_label_colour

-        self._gallery_button_disabled_background_colour = LikePrimary(primary_hsl, -2.8, -0.46, 0.09)
-        self._gallery_button_disabled_background_top_brush = wx.Brush(LikePrimary(primary_hsl, -2.8, -0.36, 0.15))
-        self._gallery_hover_background_brush = wx.Brush(LikePrimary(primary_hsl, -0.8, 0.05, 0.15))
-        self._gallery_border_pen = wx.Pen(LikePrimary(primary_hsl, 0.7, -0.02, 0.03))
-        self._gallery_button_background_top_brush = wx.Brush(LikePrimary(primary_hsl, 0.8, 0.34, 0.13))
-        self._gallery_button_background_colour = LikePrimary(primary_hsl, 1.3, 0.10, 0.08)
+        self._gallery_button_disabled_background_colour = LikePrimary(primary_hsl, primary_is_gray, -2.8, -0.46, 0.09)
+        self._gallery_button_disabled_background_top_brush = wx.Brush(LikePrimary(primary_hsl, primary_is_gray, -2.8, -0.36, 0.15))
+        self._gallery_hover_background_brush = wx.Brush(LikePrimary(primary_hsl, primary_is_gray, -0.8, 0.05, 0.15))
+        self._gallery_border_pen = wx.Pen(LikePrimary(primary_hsl, primary_is_gray, 0.7, -0.02, 0.03))
+        self._gallery_button_background_top_brush = wx.Brush(LikePrimary(primary_hsl, primary_is_gray, 0.8, 0.34, 0.13))
+        self._gallery_button_background_colour = LikePrimary(primary_hsl, primary_is_gray, 1.3, 0.10, 0.08)
+
# SetColour used so that the relevant bitmaps are generated
-        self.SetColour(RIBBON_ART_GALLERY_BUTTON_FACE_COLOUR, LikePrimary(primary_hsl, 1.4, -0.21, -0.23))
-        self.SetColour(RIBBON_ART_GALLERY_BUTTON_HOVER_FACE_COLOUR, LikePrimary(primary_hsl, 1.5, -0.24, -0.29))
-        self.SetColour(RIBBON_ART_GALLERY_BUTTON_ACTIVE_FACE_COLOUR, LikePrimary(primary_hsl, 1.5, -0.24, -0.29))
-        self.SetColour(RIBBON_ART_GALLERY_BUTTON_DISABLED_FACE_COLOUR, LikePrimary(primary_hsl, 0.0, -1.0, 0.0))
-        self._gallery_button_disabled_background_gradient_colour = LikePrimary(primary_hsl, 1.5, -0.43, 0.12)
-        self._gallery_button_background_gradient_colour = LikePrimary(primary_hsl, 1.7, 0.11, 0.09)
-        self._gallery_item_border_pen = wx.Pen(LikeSecondary(secondary_hsl, -3.9, -0.16, -0.14))
-        self._gallery_button_hover_background_colour = LikeSecondary(secondary_hsl, -0.9, 0.16, -0.07)
-        self._gallery_button_hover_background_gradient_colour = LikeSecondary(secondary_hsl, 0.1, 0.12, 0.03)
-        self._gallery_button_hover_background_top_brush = wx.Brush(LikeSecondary(secondary_hsl, 4.3, 0.16, 0.17))
-
-        self._gallery_button_active_background_colour = LikeSecondary(secondary_hsl, -9.9, 0.03, -0.22)
-        self._gallery_button_active_background_gradient_colour = LikeSecondary(secondary_hsl, -9.5, 0.14, -0.11)
-        self._gallery_button_active_background_top_brush = wx.Brush(LikeSecondary(secondary_hsl, -9.0, 0.15, -0.08))
+        self.SetColour(RIBBON_ART_GALLERY_BUTTON_FACE_COLOUR, LikePrimary(primary_hsl, primary_is_gray, 1.4, -0.21, -0.23))
+        self.SetColour(RIBBON_ART_GALLERY_BUTTON_HOVER_FACE_COLOUR, LikePrimary(primary_hsl, primary_is_gray, 1.5, -0.24, -0.29))
+        self.SetColour(RIBBON_ART_GALLERY_BUTTON_ACTIVE_FACE_COLOUR, LikePrimary(primary_hsl, primary_is_gray, 1.5, -0.24, -0.29))
+        self.SetColour(RIBBON_ART_GALLERY_BUTTON_DISABLED_FACE_COLOUR, LikePrimary(primary_hsl, primary_is_gray, 0.0, -1.0, 0.0))
+        self._gallery_button_disabled_background_gradient_colour = LikePrimary(primary_hsl, primary_is_gray, 1.5, -0.43, 0.12)
+        self._gallery_button_background_gradient_colour = LikePrimary(primary_hsl, primary_is_gray, 1.7, 0.11, 0.09)
+        self._gallery_item_border_pen = wx.Pen(LikeSecondary(secondary_hsl, secondary_is_gray, -3.9, -0.16, -0.14))
+        self._gallery_button_hover_background_colour = LikeSecondary(secondary_hsl, secondary_is_gray, -0.9, 0.16, -0.07)
+        self._gallery_button_hover_background_gradient_colour = LikeSecondary(secondary_hsl, secondary_is_gray, 0.1, 0.12, 0.03)
+        self._gallery_button_hover_background_top_brush = wx.Brush(LikeSecondary(secondary_hsl, secondary_is_gray, 4.3, 0.16, 0.17))
+
+        self._gallery_button_active_background_colour = LikeSecondary(secondary_hsl, secondary_is_gray, -9.9, 0.03, -0.22)
+        self._gallery_button_active_background_gradient_colour = LikeSecondary(secondary_hsl, secondary_is_gray, -9.5, 0.14, -0.11)
+        self._gallery_button_active_background_top_brush = wx.Brush(LikeSecondary(secondary_hsl, secondary_is_gray, -9.0, 0.15, -0.08))

self._button_bar_label_colour = self._tab_label_colour
-        self._button_bar_hover_border_pen = wx.Pen(LikeSecondary(secondary_hsl, -6.2, -0.47, -0.14))
-        self._button_bar_hover_background_gradient_colour = LikeSecondary(secondary_hsl, -0.6, 0.16, 0.04)
-        self._button_bar_hover_background_colour = LikeSecondary(secondary_hsl, -0.2, 0.16, -0.10)
-        self._button_bar_hover_background_top_gradient_colour = LikeSecondary(secondary_hsl, 0.2, 0.16, 0.03)
-        self._button_bar_hover_background_top_colour = LikeSecondary(secondary_hsl, 8.8, 0.16, 0.17)
-        self._button_bar_active_border_pen = wx.Pen(LikeSecondary(secondary_hsl, -6.2, -0.47, -0.25))
-        self._button_bar_active_background_top_colour = LikeSecondary(secondary_hsl, -8.4, 0.08, 0.06)
-        self._button_bar_active_background_top_gradient_colour = LikeSecondary(secondary_hsl, -9.7, 0.13, -0.07)
-        self._button_bar_active_background_colour = LikeSecondary(secondary_hsl, -9.9, 0.14, -0.14)
-        self._button_bar_active_background_gradient_colour = LikeSecondary(secondary_hsl, -8.7, 0.17, -0.03)
-
-        self._toolbar_border_pen = wx.Pen(LikePrimary(primary_hsl, 1.4, -0.21, -0.16))
-        self.SetColour(RIBBON_ART_TOOLBAR_FACE_COLOUR, LikePrimary(primary_hsl, 1.4, -0.17, -0.22))
-        self._tool_background_top_colour = LikePrimary(primary_hsl, -1.9, -0.07, 0.06)
-        self._tool_background_top_gradient_colour = LikePrimary(primary_hsl, 1.4, 0.12, 0.08)
-        self._tool_background_colour = LikePrimary(primary_hsl, 1.4, -0.09, 0.03)
-        self._tool_background_gradient_colour = LikePrimary(primary_hsl, 1.9, 0.11, 0.09)
-        self._tool_hover_background_top_colour = LikeSecondary(secondary_hsl, 3.4, 0.11, 0.16)
-        self._tool_hover_background_top_gradient_colour = LikeSecondary(secondary_hsl, -1.4, 0.04, 0.08)
-        self._tool_hover_background_colour = LikeSecondary(secondary_hsl, -1.8, 0.16, -0.12)
-        self._tool_hover_background_gradient_colour = LikeSecondary(secondary_hsl, -2.6, 0.16, 0.05)
-        self._tool_active_background_top_colour = LikeSecondary(secondary_hsl, -9.9, -0.12, -0.09)
-        self._tool_active_background_top_gradient_colour = LikeSecondary(secondary_hsl, -8.5, 0.16, -0.12)
-        self._tool_active_background_colour = LikeSecondary(secondary_hsl, -7.9, 0.16, -0.20)
-        self._tool_active_background_gradient_colour = LikeSecondary(secondary_hsl, -6.6, 0.16, -0.10)
+        self._button_bar_hover_border_pen = wx.Pen(LikeSecondary(secondary_hsl, secondary_is_gray, -6.2, -0.47, -0.14))
+        self._button_bar_hover_background_gradient_colour = LikeSecondary(secondary_hsl, secondary_is_gray, -0.6, 0.16, 0.04)
+        self._button_bar_hover_background_colour = LikeSecondary(secondary_hsl, secondary_is_gray, -0.2, 0.16, -0.10)
+        self._button_bar_hover_background_top_gradient_colour = LikeSecondary(secondary_hsl, secondary_is_gray, 0.2, 0.16, 0.03)
+        self._button_bar_hover_background_top_colour = LikeSecondary(secondary_hsl, secondary_is_gray, 8.8, 0.16, 0.17)
+        self._button_bar_active_border_pen = wx.Pen(LikeSecondary(secondary_hsl, secondary_is_gray, -6.2, -0.47, -0.25))
+        self._button_bar_active_background_top_colour = LikeSecondary(secondary_hsl, secondary_is_gray, -8.4, 0.08, 0.06)
+        self._button_bar_active_background_top_gradient_colour = LikeSecondary(secondary_hsl, secondary_is_gray, -9.7, 0.13, -0.07)
+        self._button_bar_active_background_colour = LikeSecondary(secondary_hsl, secondary_is_gray, -9.9, 0.14, -0.14)
+        self._button_bar_active_background_gradient_colour = LikeSecondary(secondary_hsl, secondary_is_gray, -8.7, 0.17, -0.03)
+
+        self._toolbar_border_pen = wx.Pen(LikePrimary(primary_hsl, primary_is_gray, 1.4, -0.21, -0.16))
+        self.SetColour(RIBBON_ART_TOOLBAR_FACE_COLOUR, LikePrimary(primary_hsl, primary_is_gray, 1.4, -0.17, -0.22))
+        self._tool_background_top_colour = LikePrimary(primary_hsl, primary_is_gray, -1.9, -0.07, 0.06)
+        self._tool_background_top_gradient_colour = LikePrimary(primary_hsl, primary_is_gray, 1.4, 0.12, 0.08)
+        self._tool_background_colour = LikePrimary(primary_hsl, primary_is_gray, 1.4, -0.09, 0.03)
+        self._tool_background_gradient_colour = LikePrimary(primary_hsl, primary_is_gray, 1.9, 0.11, 0.09)
+        self._tool_hover_background_top_colour = LikeSecondary(secondary_hsl, secondary_is_gray, 3.4, 0.11, 0.16)
+        self._tool_hover_background_top_gradient_colour = LikeSecondary(secondary_hsl, secondary_is_gray, -1.4, 0.04, 0.08)
+        self._tool_hover_background_colour = LikeSecondary(secondary_hsl, secondary_is_gray, -1.8, 0.16, -0.12)
+        self._tool_hover_background_gradient_colour = LikeSecondary(secondary_hsl, secondary_is_gray, -2.6, 0.16, 0.05)
+        self._tool_active_background_top_colour = LikeSecondary(secondary_hsl, secondary_is_gray, -9.9, -0.12, -0.09)
+        self._tool_active_background_top_gradient_colour = LikeSecondary(secondary_hsl, secondary_is_gray, -8.5, 0.16, -0.12)
+        self._tool_active_background_colour = LikeSecondary(secondary_hsl, secondary_is_gray, -7.9, 0.16, -0.20)
+        self._tool_active_background_gradient_colour = LikeSecondary(secondary_hsl, secondary_is_gray, -6.6, 0.16, -0.10)

# Invalidate cached tab separator
self._cached_tab_separator_visibility = -1.0
@@ -967,11 +978,13 @@

if self._flags & RIBBON_BAR_SHOW_PAGE_ICONS:
icon = tab.page.GetIcon()
-            x = tab.rect.x + 4
-            if self._flags & RIBBON_BAR_SHOW_PAGE_LABELS == 0:
-                x = tab.rect.x + (tab.rect.width - icon.GetWidth()) / 2
-
-            dc.DrawBitmap(icon, x, tab.rect.y + 1 + (tab.rect.height - 1 - icon.GetHeight()) / 2, True)
+
+            if icon.IsOk():
+                x = tab.rect.x + 4
+                if self._flags & RIBBON_BAR_SHOW_PAGE_LABELS == 0:
+                    x = tab.rect.x + (tab.rect.width - icon.GetWidth()) / 2
+
+                dc.DrawBitmap(icon, x, tab.rect.y + 1 + (tab.rect.height - 1 - icon.GetHeight()) / 2, True)

if self._flags & RIBBON_BAR_SHOW_PAGE_LABELS:
label = tab.page.GetLabel()
@@ -1862,6 +1875,11 @@

"""

+        if kind == RIBBON_BUTTON_TOGGLE:
+            kind = RIBBON_BUTTON_NORMAL
+            if state & RIBBON_BUTTONBAR_BUTTON_TOGGLED:
+                state ^= RIBBON_BUTTONBAR_BUTTON_ACTIVE_MASK
+
if state & (RIBBON_BUTTONBAR_BUTTON_HOVER_MASK | RIBBON_BUTTONBAR_BUTTON_ACTIVE_MASK):
if state & RIBBON_BUTTONBAR_BUTTON_ACTIVE_MASK:
dc.SetPen(self._button_bar_active_border_pen)
@@ -2313,7 +2331,12 @@
client_offset = wx.Point(2, 3)
else:
client_offset = wx.Point(3, 2)
-
+
+        if size.x < 0:
+            size.x = 0
+        if size.y < 0:
+            size.y = 0
+
return size, client_offset

@@ -2487,7 +2510,7 @@
# Small bitmap, no label
button_size = bitmap_size_small + wx.Size(6, 4)

-            if kind == RIBBON_BUTTON_NORMAL:
+            if kind in [RIBBON_BUTTON_NORMAL, RIBBON_BUTTON_TOGGLE]:
normal_region = wx.Rect(0, 0, *button_size)
dropdown_region = wx.Rect(0, 0, 0, 0)

@@ -2517,7 +2540,7 @@
dropdown_region.SetX(dropdown_region.GetX() + text_size)
normal_region.SetWidth(normal_region.GetWidth() + text_size)
# no break
-            elif kind == RIBBON_BUTTON_NORMAL:
+            elif kind in [RIBBON_BUTTON_NORMAL, RIBBON_BUTTON_TOGGLE]:
normal_region.SetWidth(normal_region.GetWidth() + text_size)

elif result == RIBBON_BUTTONBAR_BUTTON_LARGE:
@@ -2526,13 +2549,10 @@
icon_size = wx.Size(*bitmap_size_large)
icon_size += wx.Size(4, 4)
best_width, label_height = dc.GetTextExtent(label)
-#            label_height += 1
-            best_num_lines = 1
last_line_extra_width = 0

-            if kind != RIBBON_BUTTON_NORMAL:
+            if kind not in [RIBBON_BUTTON_NORMAL, RIBBON_BUTTON_TOGGLE]:
last_line_extra_width += 8
-                best_num_lines = 2 # label on top line, button below

for i in xrange(0, len(label)):
if RibbonCanLabelBreakAtPosition(label, i):
@@ -2541,7 +2561,6 @@
dc.GetTextExtent(label[i+1:])[0] + last_line_extra_width)
if width < best_width:
best_width = width
-                        best_num_lines = 2

label_height *= 2 # Assume two lines even when only one is used
# (to give all buttons a consistent height)
@@ -2558,7 +2577,7 @@
dropdown_region.y = normal_region.height
dropdown_region.width = icon_size.GetWidth()
dropdown_region.height = icon_size.GetHeight() - normal_region.height
-            elif kind == RIBBON_BUTTON_NORMAL:
+            elif kind in [RIBBON_BUTTON_NORMAL, RIBBON_BUTTON_TOGGLE]:
normal_region = wx.Rect(0, 0, *icon_size)

return True, button_size, normal_region, dropdown_region

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • ribbon library »
  • ribbon.art_msw »
  • SVN Revision 68881 For art_msw


SVN Revision 69086 For art_msw

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • ribbon library »
  • ribbon.art_msw »
  • SVN Revision 69086 For art_msw

svn SVN Revision 69086 For art_msw

This file contains the SVN revision history for art_msw, at revision 69086.

Available information include commit date, the name of the committer, the file size, the SVN log messages and a diff from the previous version (if available).

File Information

  • Commit Date: 18-Nov-2009 22:19:25 UTC
  • Committer: AG
  • File Size: 130152 byte(s)

Log Messages

The following log message was entered by the committer:

  • Fixed bug #13437 for SuperToolTip;
  • Fixed bug #13477 for UltimateListCtrl.

Diff To Previous Version (68881)

Version SVN diff:

--- wxPython/3rdParty/AGW/agw/ribbon/art_msw.py     2011/08/25 16:40:17     68881
+++ wxPython/3rdParty/AGW/agw/ribbon/art_msw.py     2011/09/14 19:39:08     69086
@@ -2091,7 +2091,7 @@
hybrid or dropdown tool, then the foreground should also contain a standard
dropdown button;
:param `kind`: The kind of tool to draw (normal, dropdown, or hybrid);
-        :param `state`: A combination of wx.RibbonToolBarToolState flags giving the
+        :param `state`: A combination of `RibbonToolBarToolState` flags giving the
state of the tool and it's relative position within a tool group.

"""
@@ -2181,7 +2181,7 @@
:param `dc`: A device context to use when one is required for size calculations;
:param `wnd`: The window onto which the tab will eventually be drawn;
:param `label`: The tab's label (or "" if it has none);
-        :param `bitmap`: The tab's icon (or wx.NullBitmap if it has none);
+        :param `bitmap`: The tab's icon (or `wx.NullBitmap` if it has none);
:param `ideal`: The ideal width (in pixels) of the tab;
:param `small_begin_need_separator`: A size less than the size, at which a
tab separator should begin to be drawn (i.e. drawn, but still fairly transparent);

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • ribbon library »
  • ribbon.art_msw »
  • SVN Revision 69086 For art_msw


ArtManager

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • artmanager »
  • ArtManager

ArtManager

This class provides various art utilities, such as creating shadow, providing lighter / darker colours for a given colour, etc...

hierarchy Inheritance Diagram

Inheritance diagram for: ArtManager

Inheritance diagram of ArtManager

Methods Summary

__init__ | Default class constructor.
AddMenuTheme | Adds a new theme to the stock.
BackgroundColour | Returns the background colour of a control when not in focus.
CalcButtonBestSize | Returns the best fit size for the supplied label & bitmap.
CanMakeWindowsTransparent | Used internally.
ConvertToBitmap | Convert the given image to a bitmap, optionally overlaying an alpha channel to it.
CreateGreyBitmap | Creates a grey bitmap image from the input bitmap.
DarkColour | Like the LightColour function, but create the colour darker by percent.
DrawBitmapShadow | Draws a shadow using background bitmap.
DrawButton | Colour rectangle according to the theme.
DrawButtonColour | Draws a button using the appropriate theme.
DrawButtonTheme | Draws a button using the appropriate theme.
DrawDragSash | Draws resize sash.
DrawMenuBarBg | Draws the menu bar background according to the active theme.
DrawMenuBarBorder | Enables menu border drawing (XP style only).
DrawTextAndBitmap | Draws the text & bitmap on the input dc.
DrawToolBarBg | Draws the toolbar background according to the active theme.
DropShadow | Adds a shadow under the window (Windows only).
FillStockBitmaps | Initializes few standard bitmaps.
FrameColour | Return the surrounding colour for a control.
Free | Destructor for the unique art manager object.
Get | Accessor to the unique art manager object.
GetAccelIndex | Returns the mnemonic index of the label and the label stripped of the ampersand mnemonic (e.g.
GetAlignBuffer | Return the padding buffer for a text or bitmap.
GetBitmapStartLocation | Returns the top left x and y cordinates of the bitmap drawing.
GetColourSchemes | Returns the available colour schemes.
GetFont | Returns the font used by this theme.
GetMBVerticalGradient | Returns True if the menu bar should be painted with vertical gradient.
GetMS2007ButtonSunken | Returns the sunken flag for MS 2007 buttons.
GetMenuBarBorder | Returns menu bar border drawing flag.
GetMenuBarColourScheme | Returns the current colour scheme.
GetMenuBarFaceColour | Returns the menu bar face colour.
GetMenuBarSelectionColour | Returns the menu bar selection colour.
GetMenuBgFactor | Gets the visibility depth of the menu in Metallic style.
GetMenuFaceColour | Returns the colour used for the menu foreground.
GetMenuTheme | Returns the currently used menu theme.
GetRaiseToolbar | Returns True if we are dropping a shadow under a toolbar.
GetStockBitmap | Returns a bitmap from a stock.
GetTextColourDisable | Returns the colour used for disabled menu items.
GetTextColourEnable | Returns the colour used for enabled menu items.
GetTextStartLocation | Returns the top left x and y cordinates of the text drawing.
GetThemeBaseColour | Returns the theme (Blue, Silver, Green etc.) base colour, if no theme is active
GetTransparency | Returns the alpha channel value for transparent windows.
HighlightBackgroundColour | Returns the background colour of a control when it is in focus.
InitColours | Initialise the colour map.
Initialize | Initializes the bitmaps and colours.
IsDark | Returns whether a colour is dark or light.
LightColour | Return light contrast of colour.
MakeWindowTransparent | Used internally.
MixColours | Return mix of input colours.
OnSysColourChange | Handles the wx.EVT_SYS_COLOUR_CHANGED event for ArtManager.
PaintCrescentGradientBox | Paint a region with gradient colouring.
PaintDiagonalGradientBox | Paint rectangle with gradient colouring; the gradient lines are diagonal and may start from the upper left corner or from the upper right corner.
PaintGradientRegion | Paint a region with gradient colouring.
PaintStraightGradientBox | Paint the rectangle with gradient colouring; the gradient lines are either horizontal or vertical.
RandomColour | Creates a random colour.
SetMBVerticalGradient | Sets the menu bar gradient style.
SetMS2007ButtonSunken | Sets MS 2007 button style sunken or not.
SetMenuBarColour | Sets the menu bar colour scheme to use.
SetMenuTheme | Set the menu theme, possible values (Style2007, StyleXP, StyleVista).
SetRaiseToolbar | Enables/disables toobar shadow drop.
SetTransparency | Sets the alpha channel value for transparent windows.
TakeScreenShot | Takes a screenshot of the screen at given position & size (rect).
TruncateText | Truncates a given string to fit given width size.

API Class API

class ArtManager(wx.EvtHandler) [source]

This class provides various art utilities, such as creating shadow, providing lighter / darker colours for a given colour, etc...

__init__() [source]

Default class constructor.

AddMenuTheme(render) [source]

Adds a new theme to the stock.

Parameters: render – a rendering theme class, which must be derived from RendererBase.
Returns: An integer representing the size of the renderers dictionary.

BackgroundColour() [source]

Returns the background colour of a control when not in focus.

Returns: An instance of wx.Colour.

CalcButtonBestSize(label, bmp) [source]

Returns the best fit size for the supplied label & bitmap.

Parameters:
  • label (string) – the button label;
  • bmp – the bitmap associated with the button, an instance of wx.Bitmap.
Returns:

An instance of wx.Size, representing the best fit size for the supplied label & bitmap.

CanMakeWindowsTransparent() [source]

Used internally.

Returns: True if the system supports transparency of toplevel windows, otherwise returns False.

ConvertToBitmap(xpm, alpha=None) [source]

Convert the given image to a bitmap, optionally overlaying an alpha channel to it.

Parameters:
  • xpm (list of strings) – a list of strings formatted as XPM;
  • alpha (list of integers) – a list of alpha values, the same size as the xpm bitmap.
Returns:

An instance of wx.Bitmap.

CreateGreyBitmap(bmp) [source]

Creates a grey bitmap image from the input bitmap.

Parameters: bmp – a valid wx.Bitmap object to be greyed out.
Returns: A greyed-out representation of the input bitmap, an instance of wx.Bitmap.

DarkColour(colour, percent) [source]

Like the LightColour function, but create the colour darker by percent.

Parameters:
  • colour – the input colour to be darkened, an instance of wx.Colour;

  • percent (integer) – determines how dark the colour will be. percent = 100 returns black, percent = 0 returns colour.
Returns:

A dark contrast of the input colour, an instance of wx.Colour.

DrawBitmapShadow(dc, rect, where=3) [source]

Draws a shadow using background bitmap.

Parameters:
  • dc – an instance of wx.DC;
  • rect (wx.Rect) – the bitmap’s client rectangle;
  • where (integer) – where to draw the shadow. This can be any combination of the following bits:

    integer parameter settings
    Shadow Settings | Value | Description
    RightShadow | 1 | Right side shadow
    BottomShadow | 2 | Not full bottom shadow
    BottomShadowFull | 4 | Full bottom shadow

DrawButton(dc, rect, theme, state, input=None) [source]

Colour rectangle according to the theme.

Parameters:
  • dc – an instance of wx.DC;

  • rect (wx.Rect) – the rectangle to be filled with gradient shading;
  • theme (string) – the theme to use to draw the button;
  • state (integer) – the button state;
  • input – a flag used to call the right method.

DrawButtonColour(dc, rect, theme, state, colour) [source]

Draws a button using the appropriate theme.

Parameters:
  • dc – an instance of wx.DC;

  • rect (wx.Rect) – the button’s client rectangle;
  • theme (string) – the theme to use to draw the button;
  • state (integer) – the button state;
  • colour – a valid wx.Colour instance.

DrawButtonTheme(dc, rect, theme, state, useLightColours=True) [source]

Draws a button using the appropriate theme.

Parameters:
  • dc – an instance of wx.DC;

  • rect (wx.Rect) – the button’s client rectangle;
  • theme (string) – the theme to use to draw the button;
  • state (integer) – the button state;
  • useLightColours (bool) – True to use light colours, False otherwise.

DrawDragSash(rect) [source]

Draws resize sash.

Parameters: rect (wx.Rect) – the sash client rectangle.

DrawMenuBarBg(dc, rect) [source]

Draws the menu bar background according to the active theme.

Parameters:
  • dc – an instance of wx.DC;

  • rect (wx.Rect) – the menubar’s client rectangle.

DrawMenuBarBorder(border) [source]

Enables menu border drawing (XP style only).

Parameters: border (bool) – True to draw the menubar border, False otherwise.

DrawTextAndBitmap(dc, rect, text, enable=True, font=wx.NullFont, fontColour=wx.BLACK, bitmap=wx.NullBitmap, grayBitmap=wx.NullBitmap, style=0) [source]

Draws the text & bitmap on the input dc.

Parameters:
  • dc – an instance of wx.DC;

  • rect (wx.Rect) – the text and bitmap client rectangle;
  • text (string) – the button label;
  • enable (bool) – True if the button is enabled, False otherwise;
  • font – the font to use to draw the text, an instance of wx.Font;
  • fontColour – the colour to use to draw the text, an instance of wx.Colour;
  • bitmap – the bitmap associated with the button, an instance of wx.Bitmap;

  • grayBitmap – a greyed-out version of the input bitmap representing a disabled bitmap, an instance of wx.Bitmap;

  • style (integer) – the button style.

See also

GetBitmapStartLocation for a list of valid button styles.

DrawToolBarBg(dc, rect) [source]

Draws the toolbar background according to the active theme.

Parameters:
  • dc – an instance of wx.DC;

  • rect (wx.Rect) – the toolbar’s client rectangle.

DropShadow(wnd, drop=True) [source]

Adds a shadow under the window (Windows only).

Parameters:
  • wnd – the window for which we are dropping a shadow, an instance of wx.TopLevelWindow;
  • drop (bool) – True to drop a shadow, False to remove it.

FillStockBitmaps() [source]

Initializes few standard bitmaps.

FrameColour() [source]

Return the surrounding colour for a control.

Returns: An instance of wx.Colour.

classmethod Free() [source]

Destructor for the unique art manager object.

classmethod Get() [source]

Accessor to the unique art manager object.

Returns: A unique instance of ArtManager.

GetAccelIndex(label) [source]

Returns the mnemonic index of the label and the label stripped of the ampersand mnemonic (e.g. ‘lab&el’ ==> will result in 3 and labelOnly = label).

Parameters: label (string) – a string containining an ampersand.
Returns: A tuple containining the mnemonic index of the label and the label stripped of the ampersand mnemonic.

GetAlignBuffer() [source]

Return the padding buffer for a text or bitmap.

Returns: An integer representing the padding buffer.

GetBitmapStartLocation(dc, rect, bitmap, text='', style=0) [source]

Returns the top left x and y cordinates of the bitmap drawing.

Parameters:
  • dc – an instance of wx.DC;

  • rect (wx.Rect) – the bitmap’s client rectangle;
  • bitmap (wx.Bitmap) – the bitmap associated with the button;
  • text (string) – the button label;
  • style (integer) – the button style. This can be one of the following bits:

    integer parameter settings
    Button style | Value | Description
    BU_EXT_XP_STYLE | 1 | A button with a XP style
    BU_EXT_2007_STYLE | 2 | A button with a MS Office 2007 style
    BU_EXT_LEFT_ALIGN_STYLE | 4 | A left-aligned button
    BU_EXT_CENTER_ALIGN_STYLE | 8 | A center-aligned button
    BU_EXT_RIGHT_ALIGN_STYLE | 16 | A right-aligned button
    BU_EXT_RIGHT_TO_LEFT_STYLE | 32 | A button suitable for right-to-left languages
Returns:

A tuple containining the top left x and y cordinates of the bitmap drawing.

GetColourSchemes() [source]

Returns the available colour schemes.

Returns: A list of strings representing the available colour schemes.

GetFont() [source]

Returns the font used by this theme.

Returns: An instance of wx.Font.

GetMBVerticalGradient() [source]

Returns True if the menu bar should be painted with vertical gradient.

GetMS2007ButtonSunken() [source]

Returns the sunken flag for MS 2007 buttons.

Returns: True if the MS 2007 buttons are sunken, False otherwise.

GetMenuBarBorder() [source]

Returns menu bar border drawing flag.

Returns: True if the menu bar border is to be drawn, False otherwise.

GetMenuBarColourScheme() [source]

Returns the current colour scheme.

Returns: A string representing the current colour scheme.

GetMenuBarFaceColour() [source]

Returns the menu bar face colour.

Returns: An instance of wx.Colour.

GetMenuBarSelectionColour() [source]

Returns the menu bar selection colour.

Returns: An instance of wx.Colour.

GetMenuBgFactor() [source]

Gets the visibility depth of the menu in Metallic style. The higher the value, the menu bar will look more raised

GetMenuFaceColour() [source]

Returns the colour used for the menu foreground.

Returns: An instance of wx.Colour.

GetMenuTheme() [source]

Returns the currently used menu theme.

Returns: A string containining the currently used theme for the menu.

GetRaiseToolbar() [source]

Returns True if we are dropping a shadow under a toolbar.

GetStockBitmap(name) [source]

Returns a bitmap from a stock.

Parameters: name (string) – the bitmap name.
Returns: The stock bitmap, if name was found in the stock bitmap dictionary. Othewise, wx.NullBitmap is returned.

GetTextColourDisable() [source]

Returns the colour used for disabled menu items.

Returns: An instance of wx.Colour.

GetTextColourEnable() [source]

Returns the colour used for enabled menu items.

Returns: An instance of wx.Colour.

GetTextStartLocation(dc, rect, bitmap, text, style=0) [source]

Returns the top left x and y cordinates of the text drawing. In case the text is too long, the text is being fixed (the text is cut and a ‘...’ mark is added in the end).

Parameters:
  • dc – an instance of wx.DC;

  • rect (wx.Rect) – the text’s client rectangle;
  • bitmap (wx.Bitmap) – the bitmap associated with the button;
  • text (string) – the button label;
  • style (integer) – the button style.
Returns:

A tuple containining the top left x and y cordinates of the text drawing, plus the truncated version of the input text.

See also

GetBitmapStartLocation for a list of valid button styles.

GetThemeBaseColour(useLightColours=True) [source]

Returns the theme (Blue, Silver, Green etc.) base colour, if no theme is active it return the active caption colour, lighter in 30%.

Parameters: useLightColours (bool) – True to use light colours, False otherwise.
Returns: An instance of wx.Colour.

GetTransparency() [source]

Returns the alpha channel value for transparent windows.

Returns: An integer representing the alpha channel value.

HighlightBackgroundColour() [source]

Returns the background colour of a control when it is in focus.

Returns: An instance of wx.Colour.

InitColours() [source]

Initialise the colour map.

Initialize() [source]

Initializes the bitmaps and colours.

IsDark(colour) [source]

Returns whether a colour is dark or light.

Parameters: colour – an instance of wx.Colour.
Returns: True if the average RGB values are dark, False otherwise.

LightColour(colour, percent) [source]

Return light contrast of colour. The colour returned is from the scale of colour ==> white.

Parameters:
  • colour – the input colour to be brightened, an instance of wx.Colour;

  • percent (integer) – determines how light the colour will be. percent = 100 returns white, percent = 0 returns colour.
Returns:

A light contrast of the input colour, an instance of wx.Colour.

MakeWindowTransparent(wnd, amount) [source]

Used internally. Makes a toplevel window transparent if the system supports it.

Parameters:
  • wnd – the toplevel window to make transparent, an instance of wx.TopLevelWindow;

  • amount (integer) – the window transparency to apply.

MixColours(firstColour, secondColour, percent) [source]

Return mix of input colours.

Parameters:
  • firstColour – the first colour to be mixed, an instance of wx.Colour;

  • secondColour – the second colour to be mixed, an instance of wx.Colour;

  • percent (integer) – the relative percentage of firstColour with respect to secondColour.
Returns:

An instance of wx.Colour.

OnSysColourChange(event) [source]

Handles the wx.EVT_SYS_COLOUR_CHANGED event for ArtManager.

Parameters: event – a wx.SysColourChangedEvent event to be processed.

PaintCrescentGradientBox(dc, rect, startColour, endColour, concave=True) [source]

Paint a region with gradient colouring. The gradient is in crescent shape which fits the 2007 style.

Parameters:
  • dc – an instance of wx.DC;

  • rect (wx.Rect) – the rectangle to be filled with gradient shading;
  • startColour (wx.Colour) – the first colour of the gradient shading;
  • endColour (wx.Colour) – the second colour of the gradient shading;
  • concave (bool) – True for a concave effect, False for a convex one.

PaintDiagonalGradientBox(dc, rect, startColour, endColour, startAtUpperLeft=True, trimToSquare=True) [source]

Paint rectangle with gradient colouring; the gradient lines are diagonal and may start from the upper left corner or from the upper right corner.

Parameters:
  • dc – an instance of wx.DC;

  • rect (wx.Rect) – the rectangle to be filled with gradient shading;
  • startColour (wx.Colour) – the first colour of the gradient shading;
  • endColour (wx.Colour) – the second colour of the gradient shading;
  • startAtUpperLeft (bool) – True to start the gradient lines at the upper left corner of the rectangle, False to start at the upper right corner;
  • trimToSquare (bool) – True to trim the gradient lines in a square.

PaintGradientRegion(dc, region, startColour, endColour, vertical=True) [source]

Paint a region with gradient colouring.

Parameters:
  • dc – an instance of wx.DC;

  • region – a region to be filled with gradient shading (an instance of wx.Region);
  • startColour (wx.Colour) – the first colour of the gradient shading;
  • endColour (wx.Colour) – the second colour of the gradient shading;
  • vertical (bool) – True for gradient colouring in the vertical direction, False for horizontal shading.

PaintStraightGradientBox(dc, rect, startColour, endColour, vertical=True) [source]

Paint the rectangle with gradient colouring; the gradient lines are either horizontal or vertical.

Parameters:
  • dc – an instance of wx.DC;

  • rect (wx.Rect) – the rectangle to be filled with gradient shading;
  • startColour (wx.Colour) – the first colour of the gradient shading;
  • endColour (wx.Colour) – the second colour of the gradient shading;
  • vertical (bool) – True for gradient colouring in the vertical direction, False for horizontal shading.

RandomColour() [source]

Creates a random colour.

Returns: An instance of wx.Colour.

SetMBVerticalGradient(v) [source]

Sets the menu bar gradient style.

Parameters: v (bool) – True for a vertical shaded gradient, False otherwise.

SetMS2007ButtonSunken(sunken) [source]

Sets MS 2007 button style sunken or not.

Parameters: sunken (bool) – True to have a sunken border effect, False otherwise.

SetMenuBarColour(scheme) [source]

Sets the menu bar colour scheme to use.

Parameters: scheme (string) – a string representing a colour scheme (i.e., ‘Default’, ‘Dark’, ‘Dark Olive Green’, ‘Generic’).

SetMenuTheme(theme) [source]

Set the menu theme, possible values (Style2007, StyleXP, StyleVista).

Parameters: theme (string) – a rendering theme class, either StyleXP, Style2007 or StyleVista.

SetRaiseToolbar(rais) [source]

Enables/disables toobar shadow drop.

Parameters: rais (bool) – True to drop a shadow below a toolbar, False otherwise.

SetTransparency(amount) [source]

Sets the alpha channel value for transparent windows.

Parameters: amount (integer) – the actual transparency value (between 0 and 255).
Raise : Exception if the amount parameter is lower than 0 or greater than 255.

TakeScreenShot(rect, bmp) [source]

Takes a screenshot of the screen at given position & size (rect).

Parameters:
  • rect (wx.Rect) – the screen rectangle we wish to capture;
  • bmp (wx.Bitmap) – currently unused.

TruncateText(dc, text, maxWidth) [source]

Truncates a given string to fit given width size. if the text does not fit into the given width it is truncated to fit. the format of the fixed text is <truncate text ...>.

Parameters:
  • dc – an instance of wx.DC;

  • text (string) – the text to be (eventually) truncated;
  • maxWidth (integer) – the maximum width allowed for the text.
Returns:

A new string containining the (possibly) truncated text.

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • infobar
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • artmanager »
  • ArtManager


DCSaver

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • artmanager »
  • DCSaver

DCSaver

Construct a DC saver. The dc is copied as-is.

hierarchy Inheritance Diagram

Inheritance diagram for: DCSaver

Inheritance diagram of DCSaver

Methods Summary

__init__ | Default class constructor.
__del__ | While destructing, restores the dc pen and brush.

API Class API

class DCSaver(object) [source]

Construct a DC saver. The dc is copied as-is.

__init__(pdc) [source]

Default class constructor.

Parameters: pdc – an instance of wx.DC.

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • infobar
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • artmanager »
  • DCSaver


RendererBase

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • artmanager »
  • RendererBase

RendererBase

Base class for all theme renderers.

hierarchy Inheritance Diagram

Inheritance diagram for: RendererBase

Inheritance diagram of RendererBase

subclasses Known Subclasses

  • artmanager.RendererMSOffice2007
  • artmanager.RendererXP

Methods Summary

__init__ | Default class constructor.
DrawBitmapArea | Draws the area below a bitmap and the bitmap itself using a gradient shading.
DrawBitmapBorders | Draws borders for a bitmap.
DrawButtonBorders | Draws borders for buttons.
GetFont | Returns the font used for text.
GetMenuFaceColour | Returns the foreground colour for the menu.
GetTextColourDisable | Returns the colour used for text colour when disabled.
GetTextColourEnable | Returns the colour used for text colour when enabled.

API Class API

class RendererBase(object) [source]

Base class for all theme renderers.

__init__() [source]

Default class constructor. Intentionally empty.

DrawBitmapArea(dc, xpm_name, rect, baseColour, flipSide) [source]

Draws the area below a bitmap and the bitmap itself using a gradient shading.

Parameters:
  • dc – an instance of wx.DC;
  • xpm_name (string) – a name of a XPM bitmap;
  • rect (wx.Rect) – the bitmap client rectangle;
  • baseColour – a valid wx.Colour for the bitmap background;
  • flipSide (bool) – True to flip the gradient direction, False otherwise.

DrawBitmapBorders(dc, rect, penColour, bitmapBorderUpperLeftPen) [source]

Draws borders for a bitmap.

Parameters:
  • dc – an instance of wx.DC;

  • rect (wx.Rect) – the button’s client rectangle;
  • penColour – a valid wx.Colour for the pen border;

  • bitmapBorderUpperLeftPen – a valid wx.Colour for the pen upper left border.

DrawButtonBorders(dc, rect, penColour, brushColour) [source]

Draws borders for buttons.

Parameters:
  • dc – an instance of wx.DC;

  • rect (wx.Rect) – the button’s client rectangle;
  • penColour – a valid wx.Colour for the pen border;

  • brushColour – a valid wx.Colour for the brush.

GetFont() [source]

Returns the font used for text.

Returns: An instance of wx.Font.

GetMenuFaceColour() [source]

Returns the foreground colour for the menu.

Returns: An instance of wx.Colour.

GetTextColourDisable() [source]

Returns the colour used for text colour when disabled.

Returns: An instance of wx.Colour.

GetTextColourEnable() [source]

Returns the colour used for text colour when enabled.

Returns: An instance of wx.Colour.

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • infobar
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • artmanager »
  • RendererBase


RendererMSOffice2007

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • artmanager »
  • RendererMSOffice2007

RendererMSOffice2007

Windows MS Office 2007 style.

hierarchy Inheritance Diagram

Inheritance diagram for: RendererMSOffice2007

Inheritance diagram of RendererMSOffice2007

supclasses Known Superclasses

  • artmanager.RendererBase

Methods Summary

__init__ | Default class constructor.
DrawButton | Draws a button using the MS Office 2007 theme.
DrawButtonColour | Draws a button using the MS Office 2007 theme.
DrawMenuBarBg | Draws the menu bar background according to the active theme.
DrawToolBarBg | Draws the toolbar background according to the active theme.
GetColoursAccordingToState | Returns a wx.Colour according to the menu item state.
GetTextColourEnable | Returns the colour used for text colour when enabled.

API Class API

class RendererMSOffice2007(RendererBase) [source]

Windows MS Office 2007 style.

__init__() [source]

Default class constructor.

DrawButton(dc, rect, state, useLightColours) [source]

Draws a button using the MS Office 2007 theme.

Parameters:
  • dc – an instance of wx.DC;
  • rect (wx.Rect) – the button’s client rectangle;
  • state (integer) – the button state;
  • useLightColours (bool) – True to use light colours, False otherwise.

DrawButtonColour(dc, rect, state, colour) [source]

Draws a button using the MS Office 2007 theme.

Parameters:
  • dc – an instance of wx.DC;

  • rect (wx.Rect) – the button’s client rectangle;
  • state (integer) – the button state;
  • colour – a valid wx.Colour instance.

DrawMenuBarBg(dc, rect) [source]

Draws the menu bar background according to the active theme.

Parameters:
  • dc – an instance of wx.DC;

  • rect (wx.Rect) – the menu bar’s client rectangle.

DrawToolBarBg(dc, rect) [source]

Draws the toolbar background according to the active theme.

Parameters:
  • dc – an instance of wx.DC;

  • rect (wx.Rect) – the toolbar’s client rectangle.

GetColoursAccordingToState(state) [source]

Returns a wx.Colour according to the menu item state.

Parameters: state (integer) – one of the following bits:

integer parameter settings
Item State | Value | Description
ControlPressed | 0 | The item is pressed
ControlFocus | 1 | The item is focused
ControlDisabled | 2 | The item is disabled
ControlNormal | 3 | Normal state
Returns: An instance of wx.Colour.

GetTextColourEnable() [source]

Returns the colour used for text colour when enabled.

Returns: An instance of wx.Colour.

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • infobar
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • artmanager »
  • RendererMSOffice2007


RendererXP

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • artmanager »
  • RendererXP

RendererXP

Xp-Style renderer.

hierarchy Inheritance Diagram

Inheritance diagram for: RendererXP

Inheritance diagram of RendererXP

supclasses Known Superclasses

  • artmanager.RendererBase

Methods Summary

__init__ | Default class constructor.
DrawButton | Draws a button using the XP theme.
DrawButtonColour | Draws a button using the XP theme.
DrawButtonTheme | Draws a button using the XP theme.
DrawMenuBarBg | Draws the menu bar background according to the active theme.
DrawToolBarBg | Draws the toolbar background according to the active theme.
GetTextColourEnable | Returns the colour used for text colour when enabled.

API Class API

class RendererXP(RendererBase) [source]

Xp-Style renderer.

__init__() [source]

Default class constructor.

DrawButton(dc, rect, state, input=None) [source]

Draws a button using the XP theme.

Parameters:
  • dc – an instance of wx.DC;
  • rect (wx.Rect) – the button’s client rectangle;
  • state (integer) – the button state;
  • input – a flag used to call the right method.

DrawButtonColour(dc, rect, state, colour) [source]

Draws a button using the XP theme.

Parameters:
  • dc – an instance of wx.DC;

  • rect (wx.Rect) – the button’s client rectangle;
  • state (integer) – the button state;
  • colour – a valid wx.Colour instance.

DrawButtonTheme(dc, rect, state, useLightColours=None) [source]

Draws a button using the XP theme.

Parameters:
  • dc – an instance of wx.DC;

  • rect (wx.Rect) – the button’s client rectangle;
  • state (integer) – the button state;
  • useLightColours (bool) – True to use light colours, False otherwise.

DrawMenuBarBg(dc, rect) [source]

Draws the menu bar background according to the active theme.

Parameters:
  • dc – an instance of wx.DC;

  • rect (wx.Rect) – the menu bar’s client rectangle.

DrawToolBarBg(dc, rect) [source]

Draws the toolbar background according to the active theme.

Parameters:
  • dc – an instance of wx.DC;

  • rect (wx.Rect) – the toolbar’s client rectangle.

GetTextColourEnable() [source]

Returns the colour used for text colour when enabled.

Returns: An instance of wx.Colour.

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • infobar
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • artmanager »
  • RendererXP


SVN Revision 69086 For artmanager

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • artmanager »
  • SVN Revision 69086 For artmanager

svn SVN Revision 69086 For artmanager

This file contains the SVN revision history for artmanager, at revision 69086.

Available information include commit date, the name of the committer, the file size, the SVN log messages and a diff from the previous version (if available).

File Information

  • Commit Date: 17-Oct-2008 19:15:31 UTC
  • Committer: AG
  • File Size: 73042 byte(s)

Log Messages

The following log message was entered by the committer:

  • Fixed bug #13437 for SuperToolTip;
  • Fixed bug #13477 for UltimateListCtrl.

Diff To Previous Version (65585)

Version SVN diff:

--- wxPython/3rdParty/AGW/agw/artmanager.py 2010/09/21 21:09:52     65585
+++ wxPython/3rdParty/AGW/agw/artmanager.py 2011/09/14 19:39:08     69086
@@ -79,7 +79,7 @@
Draws borders for buttons.

:param `dc`: an instance of `wx.DC`;
-        :param `rect`: the button's client rectangle;
+        :param `wx.Rect` `rect`: the button's client rectangle;
:param `penColour`: a valid `wx.Colour` for the pen border;
:param `brushColour`: a valid `wx.Colour` for the brush.
"""
@@ -96,10 +96,10 @@
Draws the area below a bitmap and the bitmap itself using a gradient shading.

:param `dc`: an instance of `wx.DC`;
-        :param `xpm_name`: a name of a XPM bitmap;
-        :param `rect`: the bitmap client rectangle;
+        :param string `xpm_name`: a name of a XPM bitmap;
+        :param `wx.Rect` `rect`: the bitmap client rectangle;
:param `baseColour`: a valid `wx.Colour` for the bitmap background;
-        :param `flipSide`: ``True`` to flip the gradient direction, ``False`` otherwise.
+        :param bool `flipSide`: ``True`` to flip the gradient direction, ``False`` otherwise.
"""

# draw the gradient area
@@ -122,7 +122,7 @@
Draws borders for a bitmap.

:param `dc`: an instance of `wx.DC`;
-        :param `rect`: the button's client rectangle;
+        :param `wx.Rect` `rect`: the button's client rectangle;
:param `penColour`: a valid `wx.Colour` for the pen border;
:param `bitmapBorderUpperLeftPen`: a valid `wx.Colour` for the pen upper
left border.
@@ -143,25 +143,41 @@

def GetMenuFaceColour(self):
-        """ Returns the foreground colour for the menu. """
+        """
+        Returns the foreground colour for the menu.
+
+        :return: An instance of `wx.Colour`.
+        """

return ArtManager.Get().LightColour(wx.SystemSettings_GetColour(wx.SYS_COLOUR_3DFACE), 80)

def GetTextColourEnable(self):
-        """ Returns the colour used for text colour when enabled. """
+        """
+        Returns the colour used for text colour when enabled.
+
+        :return: An instance of `wx.Colour`.
+        """

return wx.BLACK

def GetTextColourDisable(self):
-        """ Returns the colour used for text colour when disabled. """
+        """
+        Returns the colour used for text colour when disabled.
+
+        :return: An instance of `wx.Colour`.
+        """

return ArtManager.Get().LightColour(wx.SystemSettings_GetColour(wx.SYS_COLOUR_GRAYTEXT), 30)

def GetFont(self):
-        """ Returns the font used for text. """
+        """
+        Returns the font used for text.
+
+        :return: An instance of `wx.Font`.
+        """

return wx.SystemSettings_GetFont(wx.SYS_DEFAULT_GUI_FONT)

@@ -184,8 +200,8 @@
Draws a button using the XP theme.

:param `dc`: an instance of `wx.DC`;
-        :param `rect`: the button's client rectangle;
-        :param `state`: the button state;
+        :param `wx.Rect` `rect`: the button's client rectangle;
+        :param integer `state`: the button state;
:param `input`: a flag used to call the right method.
"""

@@ -200,9 +216,9 @@
Draws a button using the XP theme.

:param `dc`: an instance of `wx.DC`;
-        :param `rect`: the button's client rectangle;
-        :param `state`: the button state;
-        :param `useLightColours`: ``True`` to use light colours, ``False`` otherwise.
+        :param `wx.Rect` `rect`: the button's client rectangle;
+        :param integer `state`: the button state;
+        :param bool `useLightColours`: ``True`` to use light colours, ``False`` otherwise.
"""

# switch according to the status
@@ -225,8 +241,8 @@
Draws a button using the XP theme.

:param `dc`: an instance of `wx.DC`;
-        :param `rect`: the button's client rectangle;
-        :param `state`: the button state;
+        :param `wx.Rect` `rect`: the button's client rectangle;
+        :param integer `state`: the button state;
:param `colour`: a valid `wx.Colour` instance.
"""

@@ -250,7 +266,7 @@
Draws the menu bar background according to the active theme.

:param `dc`: an instance of `wx.DC`;
-        :param `rect`: the menu bar's client rectangle.
+        :param `wx.Rect` `rect`: the menu bar's client rectangle.
"""

# For office style, we simple draw a rectangle with a gradient colouring
@@ -280,7 +296,7 @@
Draws the toolbar background according to the active theme.

:param `dc`: an instance of `wx.DC`;
-        :param `rect`: the toolbar's client rectangle.
+        :param `wx.Rect` `rect`: the toolbar's client rectangle.
"""

artMgr = ArtManager.Get()
@@ -306,7 +322,11 @@

def GetTextColourEnable(self):
-        """ Returns the colour used for text colour when enabled. """
+        """
+        Returns the colour used for text colour when enabled.
+
+        :return: An instance of `wx.Colour`.
+        """

return wx.BLACK

@@ -328,7 +348,7 @@
"""
Returns a `wx.Colour` according to the menu item state.

-        :param `state`: one of the following bits:
+        :param integer `state`: one of the following bits:

==================== ======= ==========================
Item State            Value  Description
@@ -338,7 +358,8 @@
``ControlDisabled``        2 The item is disabled
``ControlNormal``          3 Normal state
==================== ======= ==========================
-
+
+        :return: An instance of `wx.Colour`.
"""

# switch according to the status
@@ -383,9 +404,9 @@
Draws a button using the MS Office 2007 theme.

:param `dc`: an instance of `wx.DC`;
-        :param `rect`: the button's client rectangle;
-        :param `state`: the button state;
-        :param `useLightColours`: ``True`` to use light colours, ``False`` otherwise.
+        :param `wx.Rect` `rect`: the button's client rectangle;
+        :param integer `state`: the button state;
+        :param bool `useLightColours`: ``True`` to use light colours, ``False`` otherwise.
"""

self.DrawButtonColour(dc, rect, state, ArtManager.Get().GetThemeBaseColour(useLightColours))
@@ -396,8 +417,8 @@
Draws a button using the MS Office 2007 theme.

:param `dc`: an instance of `wx.DC`;
-        :param `rect`: the button's client rectangle;
-        :param `state`: the button state;
+        :param `wx.Rect` `rect`: the button's client rectangle;
+        :param integer `state`: the button state;
:param `colour`: a valid `wx.Colour` instance.
"""

@@ -447,7 +468,7 @@
Draws the menu bar background according to the active theme.

:param `dc`: an instance of `wx.DC`;
-        :param `rect`: the menu bar's client rectangle.
+        :param `wx.Rect` `rect`: the menu bar's client rectangle.
"""

# Keep old pen and brush
@@ -517,7 +538,7 @@
Draws the toolbar background according to the active theme.

:param `dc`: an instance of `wx.DC`;
-        :param `rect`: the toolbar's client rectangle.
+        :param `wx.Rect` `rect`: the toolbar's client rectangle.
"""

artMgr = ArtManager.Get()
@@ -591,7 +612,11 @@

def GetTextColourEnable(self):
-        """ Returns the colour used for text colour when enabled. """
+        """
+        Returns the colour used for text colour when enabled.
+
+        :return: An instance of `wx.Colour`.
+        """

return wx.NamedColour("MIDNIGHT BLUE")

@@ -634,7 +659,9 @@
"""
Sets the alpha channel value for transparent windows.

-        :param `amount`: the actual transparency value (between 0 and 255).
+        :param integer `amount`: the actual transparency value (between 0 and 255).
+
+        :raise: `Exception` if the `amount` parameter is lower than ``0`` or greater than ``255``.
"""

if self._transparency == amount:
@@ -647,7 +674,11 @@

def GetTransparency(self):
-        """ Returns the alpha channel value for transparent windows. """
+        """
+        Returns the alpha channel value for transparent windows.
+
+        :return: An integer representing the alpha channel value.
+        """

return self._transparency

@@ -658,7 +689,11 @@
channel to it.

:param `xpm`: a list of strings formatted as XPM;
+        :type `xpm`: list of strings
:param `alpha`: a list of alpha values, the same size as the xpm bitmap.
+        :type `alpha`: list of integers
+
+        :return: An instance of `wx.Bitmap`.
"""

if alpha is not None:
@@ -713,7 +748,7 @@
"""
Returns a bitmap from a stock.

-        :param `name`: the bitmap name.
+        :param string `name`: the bitmap name.

:return: The stock bitmap, if `name` was found in the stock bitmap dictionary.
Othewise, `wx.NullBitmap` is returned.
@@ -726,7 +761,11 @@

def Get(self):
-        """ Accessor to the unique art manager object. """
+        """
+        Accessor to the unique art manager object.
+
+        :return: A unique instance of L{ArtManager}.
+        """

if not hasattr(self, "_instance"):

@@ -767,9 +806,11 @@
Return light contrast of `colour`. The colour returned is from the scale of
`colour` ==> white.

-        :param `colour`: the input colour to be brightened;
-        :param `percent`: determines how light the colour will be. `percent` = 100
-         returns white, `percent` = 0 returns `colour`.
+        :param `colour`: the input colour to be brightened, an instance of `wx.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 `wx.Colour`.
"""

end_colour = wx.WHITE
@@ -791,9 +832,11 @@
"""
Like the L{LightColour} function, but create the colour darker by `percent`.

-        :param `colour`: the input colour to be darkened;
-        :param `percent`: determines how dark the colour will be. `percent` = 100
-         returns black, `percent` = 0 returns `colour`.
+        :param `colour`: the input colour to be darkened, an instance of `wx.Colour`;
+        :param integer `percent`: determines how dark the colour will be. `percent` = ``100``
+         returns black, `percent` = ``0`` returns `colour`.
+
+        :return: A dark contrast of the input `colour`, an instance of `wx.Colour`.
"""

end_colour = wx.BLACK
@@ -817,10 +860,10 @@
horizontal or vertical.

:param `dc`: an instance of `wx.DC`;
-        :param `rect`: the rectangle to be filled with gradient shading;
-        :param `startColour`: the first colour of the gradient shading;
-        :param `endColour`: the second colour of the gradient shading;
-        :param `vertical`: ``True`` for gradient colouring in the vertical direction,
+        :param `wx.Rect` `rect`: the rectangle to be filled with gradient shading;
+        :param `wx.Colour` `startColour`: the first colour of the gradient shading;
+        :param `wx.Colour` `endColour`: the second colour of the gradient shading;
+        :param bool `vertical`: ``True`` for gradient colouring in the vertical direction,
``False`` for horizontal shading.
"""

@@ -846,9 +889,9 @@
:param `dc`: an instance of `wx.DC`;
:param `region`: a region to be filled with gradient shading (an instance of
`wx.Region`);
-        :param `startColour`: the first colour of the gradient shading;
-        :param `endColour`: the second colour of the gradient shading;
-        :param `vertical`: ``True`` for gradient colouring in the vertical direction,
+        :param `wx.Colour` `startColour`: the first colour of the gradient shading;
+        :param `wx.Colour` `endColour`: the second colour of the gradient shading;
+        :param bool `vertical`: ``True`` for gradient colouring in the vertical direction,
``False`` for horizontal shading.

"""
@@ -894,12 +937,12 @@
and may start from the upper left corner or from the upper right corner.

:param `dc`: an instance of `wx.DC`;
-        :param `rect`: the rectangle to be filled with gradient shading;
-        :param `startColour`: the first colour of the gradient shading;
-        :param `endColour`: the second colour of the gradient shading;
-        :param `startAtUpperLeft`: ``True`` to start the gradient lines at the upper
+        :param `wx.Rect` `rect`: the rectangle to be filled with gradient shading;
+        :param `wx.Colour` `startColour`: the first colour of the gradient shading;
+        :param `wx.Colour` `endColour`: the second colour of the gradient shading;
+        :param bool `startAtUpperLeft`: ``True`` to start the gradient lines at the upper
left corner of the rectangle, ``False`` to start at the upper right corner;
-        :param `trimToSquare`: ``True`` to trim the gradient lines in a square.
+        :param bool `trimToSquare`: ``True`` to trim the gradient lines in a square.
"""

# Save the current pen and brush
@@ -1036,10 +1079,10 @@
which fits the 2007 style.

:param `dc`: an instance of `wx.DC`;
-        :param `rect`: the rectangle to be filled with gradient shading;
-        :param `startColour`: the first colour of the gradient shading;
-        :param `endColour`: the second colour of the gradient shading;
-        :param `concave`: ``True`` for a concave effect, ``False`` for a convex one.
+        :param `wx.Rect` `rect`: the rectangle to be filled with gradient shading;
+        :param `wx.Colour` `startColour`: the first colour of the gradient shading;
+        :param `wx.Colour` `endColour`: the second colour of the gradient shading;
+        :param bool `concave`: ``True`` for a concave effect, ``False`` for a convex one.
"""

diagonalRectWidth = rect.GetWidth()/4
@@ -1061,19 +1104,31 @@

def FrameColour(self):
-        """ Return the surrounding colour for a control. """
+        """
+        Return the surrounding colour for a control.
+
+        :return: An instance of `wx.Colour`.
+        """

return wx.SystemSettings_GetColour(wx.SYS_COLOUR_ACTIVECAPTION)

def BackgroundColour(self):
-        """ Returns the background colour of a control when not in focus. """
+        """
+        Returns the background colour of a control when not in focus.
+
+        :return: An instance of `wx.Colour`.
+        """

return self.LightColour(self.FrameColour(), 75)

def HighlightBackgroundColour(self):
-        """ Returns the background colour of a control when it is in focus. """
+        """
+        Returns the background colour of a control when it is in focus.
+
+        :return: An instance of `wx.Colour`.
+        """

return self.LightColour(self.FrameColour(), 60)

@@ -1084,8 +1139,10 @@

:param `firstColour`: the first colour to be mixed, an instance of `wx.Colour`;
:param `secondColour`: the second colour to be mixed, an instance of `wx.Colour`;
-        :param `percent`: the relative percentage of `firstColour` with respect to
+        :param integer `percent`: the relative percentage of `firstColour` with respect to
`secondColour`.
+
+        :return: An instance of `wx.Colour`.
"""

# calculate gradient coefficients
@@ -1098,7 +1155,11 @@

def RandomColour():
-        """ Creates a random colour. """
+        """
+        Creates a random colour.
+
+        :return: An instance of `wx.Colour`.
+        """

r = random.randint(0, 255) # Random value betweem 0-255
g = random.randint(0, 255) # Random value betweem 0-255
@@ -1112,6 +1173,8 @@
Returns whether a colour is dark or light.

:param `colour`: an instance of `wx.Colour`.
+
+        :return: ``True`` if the average RGB values are dark, ``False`` otherwise.
"""

evg = (colour.Red() + colour.Green() + colour.Blue())/3
@@ -1129,8 +1192,10 @@
is <truncate text ...>.

:param `dc`: an instance of `wx.DC`;
-        :param `text`: the text to be (eventually) truncated;
-        :param `maxWidth`: the maximum width allowed for the text.
+        :param string `text`: the text to be (eventually) truncated;
+        :param integer `maxWidth`: the maximum width allowed for the text.
+
+        :return: A new string containining the (possibly) truncated text.
"""

textLen = len(text)
@@ -1166,9 +1231,9 @@
Colour rectangle according to the theme.

:param `dc`: an instance of `wx.DC`;
-        :param `rect`: the rectangle to be filled with gradient shading;
-        :param `theme`: the theme to use to draw the button;
-        :param `state`: the button state;
+        :param `wx.Rect` `rect`: the rectangle to be filled with gradient shading;
+        :param string `theme`: the theme to use to draw the button;
+        :param integer `state`: the button state;
:param `input`: a flag used to call the right method.
"""

@@ -1183,10 +1248,10 @@
Draws a button using the appropriate theme.

:param `dc`: an instance of `wx.DC`;
-        :param `rect`: the button's client rectangle;
-        :param `theme`: the theme to use to draw the button;
-        :param `state`: the button state;
-        :param `useLightColours`: ``True`` to use light colours, ``False`` otherwise.
+        :param `wx.Rect` `rect`: the button's client rectangle;
+        :param string `theme`: the theme to use to draw the button;
+        :param integer `state`: the button state;
+        :param bool  `useLightColours`: ``True`` to use light colours, ``False`` otherwise.
"""

renderer = self._renderers[theme]
@@ -1200,9 +1265,9 @@
Draws a button using the appropriate theme.

:param `dc`: an instance of `wx.DC`;
-        :param `rect`: the button's client rectangle;
-        :param `theme`: the theme to use to draw the button;
-        :param `state`: the button state;
+        :param `wx.Rect` `rect`: the button's client rectangle;
+        :param string `theme`: the theme to use to draw the button;
+        :param integer `state`: the button state;
:param `colour`: a valid `wx.Colour` instance.
"""

@@ -1236,8 +1301,8 @@
"""
Used internally. Makes a toplevel window transparent if the system supports it.

-        :param `wnd`: the toplevel window to make transparent;
-        :param `amount`: the window transparency to apply.
+        :param `wnd`: the toplevel window to make transparent, an instance of `wx.TopLevelWindow`;
+        :param integer `amount`: the window transparency to apply.
"""

if wnd.GetSize() == (0, 0):
@@ -1285,8 +1350,8 @@
Draws a shadow using background bitmap.

:param `dc`: an instance of `wx.DC`;
-        :param `rect`: the bitmap's client rectangle;
-        :param `where`: where to draw the shadow. This can be any combination of the
+        :param `wx.Rect` `rect`: the bitmap's client rectangle;
+        :param integer `where`: where to draw the shadow. This can be any combination of the
following bits:

========================== ======= ================================
@@ -1341,10 +1406,10 @@

def DropShadow(self, wnd, drop=True):
"""
-        Adds a shadow under the window (Windows Only).
+        Adds a shadow under the window (Windows only).

-        :param `wnd`: the window for which we are dropping a shadow;
-        :param `drop`: ``True`` to drop a shadow, ``False`` to remove it.
+        :param `wnd`: the window for which we are dropping a shadow, an instance of `wx.TopLevelWindow`;
+        :param bool `drop`: ``True`` to drop a shadow, ``False`` to remove it.
"""

if not self.CanMakeWindowsTransparent() or not _libimported:
@@ -1386,10 +1451,10 @@
Returns the top left `x` and `y` cordinates of the bitmap drawing.

:param `dc`: an instance of `wx.DC`;
-        :param `rect`: the bitmap's client rectangle;
-        :param `bitmap`: the bitmap associated with the button;
-        :param `text`: the button label;
-        :param `style`: the button style. This can be one of the following bits:
+        :param `wx.Rect` `rect`: the bitmap's client rectangle;
+        :param `wx.Bitmap` `bitmap`: the bitmap associated with the button;
+        :param string `text`: the button label;
+        :param integer `style`: the button style. This can be one of the following bits:

============================== ======= ================================
Button style                    Value  Description
@@ -1401,7 +1466,8 @@
``BU_EXT_RIGHT_ALIGN_STYLE``      16   A right-aligned button
``BU_EXT_RIGHT_TO_LEFT_STYLE``    32   A button suitable for right-to-left languages
============================== ======= ================================
-
+
+        :return: A tuple containining the top left `x` and `y` cordinates of the bitmap drawing.
"""

alignmentBuffer = self.GetAlignBuffer()
@@ -1427,7 +1493,7 @@

maxWidth = rect.x + rect.width - (2 * alignmentBuffer) - bitmap.GetWidth() # the alignment is for both sides

-                # get the truncaed text. The text may stay as is, it is not a must that is will be trancated
+                # get the truncated text. The text may stay as is, it is not a must that is will be trancated
fixedText = self.TruncateText(dc, text, maxWidth)

# get the fixed text dimentions
@@ -1445,7 +1511,7 @@

maxWidth = rect.x + rect.width - (2 * alignmentBuffer) - bitmap.GetWidth() # the alignment is for both sides

-                # get the truncaed text. The text may stay as is, it is not a must that is will be trancated
+                # get the truncated text. The text may stay as is, it is not a must that is will be trancated
fixedText = self.TruncateText(dc, text, maxWidth)

# get the fixed text dimentions
@@ -1475,10 +1541,13 @@
a '...' mark is added in the end).

:param `dc`: an instance of `wx.DC`;
-        :param `rect`: the text's client rectangle;
-        :param `bitmap`: the bitmap associated with the button;
-        :param `text`: the button label;
-        :param `style`: the button style.
+        :param `wx.Rect` `rect`: the text's client rectangle;
+        :param `wx.Bitmap` `bitmap`: the bitmap associated with the button;
+        :param string `text`: the button label;
+        :param integer `style`: the button style.
+
+        :return: A tuple containining the top left `x` and `y` cordinates of the text drawing, plus
+         the truncated version of the input `text`.

:see: L{GetBitmapStartLocation} for a list of valid button styles.
"""
@@ -1536,16 +1605,16 @@
Draws the text & bitmap on the input dc.

:param `dc`: an instance of `wx.DC`;
-        :param `rect`: the text and bitmap client rectangle;
-        :param `text`: the button label;
-        :param `enable`: ``True`` if the button is enabled, ``False`` otherwise;
+        :param `wx.Rect` `rect`: the text and bitmap client rectangle;
+        :param string `text`: the button label;
+        :param bool `enable`: ``True`` if the button is enabled, ``False`` otherwise;
:param `font`: the font to use to draw the text, an instance of `wx.Font`;
:param `fontColour`: the colour to use to draw the text, an instance of
`wx.Colour`;
-        :param `bitmap`: the bitmap associated with the button;
+        :param `bitmap`: the bitmap associated with the button, an instance of `wx.Bitmap`;
:param `grayBitmap`: a greyed-out version of the input `bitmap` representing
-         a disabled bitmap;
-        :param `style`: the button style.
+         a disabled bitmap, an instance of `wx.Bitmap`;
+        :param integer `style`: the button style.

:see: L{GetBitmapStartLocation} for a list of valid button styles.
"""
@@ -1628,8 +1697,10 @@
"""
Returns the best fit size for the supplied label & bitmap.

-        :param `label`: the button label;
-        :param `bmp`: the bitmap associated with the button.
+        :param string `label`: the button label;
+        :param `bmp`: the bitmap associated with the button, an instance of `wx.Bitmap`.
+
+        :return: An instance of `wx.Size`, representing the best fit size for the supplied label & bitmap.
"""

if "__WXMSW__" in wx.Platform:
@@ -1663,28 +1734,44 @@

def GetMenuFaceColour(self):
-        """ Returns the colour used for the menu foreground. """
+        """
+        Returns the colour used for the menu foreground.
+
+        :return: An instance of `wx.Colour`.
+        """

renderer = self._renderers[self.GetMenuTheme()]
return renderer.GetMenuFaceColour()

def GetTextColourEnable(self):
-        """ Returns the colour used for enabled menu items. """
+        """
+        Returns the colour used for enabled menu items.
+
+        :return: An instance of `wx.Colour`.
+        """

renderer = self._renderers[self.GetMenuTheme()]
return renderer.GetTextColourEnable()

def GetTextColourDisable(self):
-        """ Returns the colour used for disabled menu items. """
+        """
+        Returns the colour used for disabled menu items.
+
+        :return: An instance of `wx.Colour`.
+        """

renderer = self._renderers[self.GetMenuTheme()]
return renderer.GetTextColourDisable()

def GetFont(self):
-        """ Returns the font used by this theme. """
+        """
+        Returns the font used by this theme.
+
+        :return: An instance of `wx.Font`.
+        """

renderer = self._renderers[self.GetMenuTheme()]
return renderer.GetFont()
@@ -1695,7 +1782,10 @@
Returns the mnemonic index of the label and the label stripped of the ampersand mnemonic
(e.g. 'lab&el' ==> will result in 3 and labelOnly = label).

-        :param `label`: a string containining an ampersand.
+        :param string `label`: a string containining an ampersand.
+
+        :return: A tuple containining the mnemonic index of the label and the label
+         stripped of the ampersand mnemonic.
"""

indexAccel = 0
@@ -1719,7 +1809,9 @@
Returns the theme (Blue, Silver, Green etc.) base colour, if no theme is active
it return the active caption colour, lighter in 30%.

-        :param `useLightColours`: ``True`` to use light colours, ``False`` otherwise.
+        :param bool `useLightColours`: ``True`` to use light colours, ``False`` otherwise.
+
+        :return: An instance of `wx.Colour`.
"""

if not useLightColours and not self.IsDark(self.FrameColour()):
@@ -1729,7 +1821,11 @@

def GetAlignBuffer(self):
-        """ Return the padding buffer for a text or bitmap. """
+        """
+        Return the padding buffer for a text or bitmap.
+
+        :return: An integer representing the padding buffer.
+        """

return self._alignmentBuffer

@@ -1738,14 +1834,18 @@
"""
Set the menu theme, possible values (Style2007, StyleXP, StyleVista).

-        :param `theme`: a rendering theme class, either `StyleXP`, `Style2007` or `StyleVista`.
+        :param string `theme`: a rendering theme class, either `StyleXP`, `Style2007` or `StyleVista`.
"""

self._menuTheme = theme

def GetMenuTheme(self):
-        """ Returns the currently used menu theme. """
+        """
+        Returns the currently used menu theme.
+
+        :return: A string containining the currently used theme for the menu.
+        """

return self._menuTheme

@@ -1756,6 +1856,8 @@

:param `render`: a rendering theme class, which must be derived from
L{RendererBase}.
+
+        :return: An integer representing the size of the renderers dictionary.
"""

# Add new theme
@@ -1769,14 +1871,18 @@
"""
Sets MS 2007 button style sunken or not.

-        :param `sunken`: ``True`` to have a sunken border effect, ``False`` otherwise.
+        :param bool `sunken`: ``True`` to have a sunken border effect, ``False`` otherwise.
"""

self._ms2007sunken = sunken

def GetMS2007ButtonSunken(self):
-        """ Returns the sunken flag for MS 2007 buttons. """
+        """
+        Returns the sunken flag for MS 2007 buttons.
+
+        :return: ``True`` if the MS 2007 buttons are sunken, ``False`` otherwise.
+        """

return self._ms2007sunken

@@ -1791,7 +1897,7 @@
"""
Sets the menu bar gradient style.

-        :param `v`: ``True`` for a vertical shaded gradient, ``False`` otherwise.
+        :param bool `v`: ``True`` for a vertical shaded gradient, ``False`` otherwise.
"""

self._verticalGradient = v
@@ -1801,14 +1907,18 @@
"""
Enables menu border drawing (XP style only).

-        :param `border`: ``True`` to draw the menubar border, ``False`` otherwise.
+        :param bool `border`: ``True`` to draw the menubar border, ``False`` otherwise.
"""

self._drowMBBorder = border

def GetMenuBarBorder(self):
-        """ Returns menu bar border drawing flag. """
+        """
+        Returns menu bar border drawing flag.
+
+        :return: ``True`` if the menu bar border is to be drawn, ``False`` otherwise.
+        """

return self._drowMBBorder

@@ -1819,14 +1929,14 @@
The higher the value, the menu bar will look more raised
"""

-        return self._menuBgFactor
+        return self._menuBgFactor

def DrawDragSash(self, rect):
"""
Draws resize sash.

-        :param `rect`: the sash client rectangle.
+        :param `wx.Rect` `rect`: the sash client rectangle.
"""

dc = wx.ScreenDC()
@@ -1845,8 +1955,8 @@
"""
Takes a screenshot of the screen at given position & size (rect).

-        :param `rect`: the screen rectangle we wish to capture;
-        :param `bmp`: currently unused.
+        :param `wx.Rect` `rect`: the screen rectangle we wish to capture;
+        :param `wx.Bitmap` `bmp`: currently unused.
"""

# Create a DC for the whole screen area
@@ -1885,7 +1995,7 @@
Draws the toolbar background according to the active theme.

:param `dc`: an instance of `wx.DC`;
-        :param `rect`: the toolbar's client rectangle.
+        :param `wx.Rect` `rect`: the toolbar's client rectangle.
"""

renderer = self._renderers[self.GetMenuTheme()]
@@ -1899,7 +2009,7 @@
Draws the menu bar background according to the active theme.

:param `dc`: an instance of `wx.DC`;
-        :param `rect`: the menubar's client rectangle.
+        :param `wx.Rect` `rect`: the menubar's client rectangle.
"""

renderer = self._renderers[self.GetMenuTheme()]
@@ -1911,7 +2021,7 @@
"""
Sets the menu bar colour scheme to use.

-        :param `scheme`: a string representing a colour scheme (i.e., 'Default',
+        :param string `scheme`: a string representing a colour scheme (i.e., 'Default',
'Dark', 'Dark Olive Green', 'Generic').
"""

@@ -1922,19 +2032,31 @@

def GetMenuBarColourScheme(self):
-        """ Returns the current colour scheme. """
+        """
+        Returns the current colour scheme.
+
+        :return: A string representing the current colour scheme.
+        """

return self._menuBarColourScheme

def GetMenuBarFaceColour(self):
-        """ Returns the menu bar face colour. """
+        """
+        Returns the menu bar face colour.
+
+        :return: An instance of `wx.Colour`.
+        """

return self._menuBarBgColour

def GetMenuBarSelectionColour(self):
-        """ Returns the menu bar selection colour. """
+        """
+        Returns the menu bar selection colour.
+
+        :return: An instance of `wx.Colour`.
+        """

return self._menuBarSelColour

@@ -1949,7 +2071,11 @@

def GetColourSchemes(self):
-        """ Returns the available colour schemes. """
+        """
+        Returns the available colour schemes.
+
+        :return: A list of strings representing the available colour schemes.
+        """

return self._colourSchemeMap.keys()

@@ -1959,6 +2085,8 @@
Creates a grey bitmap image from the input bitmap.

:param `bmp`: a valid `wx.Bitmap` object to be greyed out.
+
+        :return: A greyed-out representation of the input bitmap, an instance of `wx.Bitmap`.
"""

img = bmp.ConvertToImage()
@@ -1975,7 +2103,7 @@
"""
Enables/disables toobar shadow drop.

-        :param `rais`: ``True`` to drop a shadow below a toolbar, ``False`` otherwise.
+        :param bool `rais`: ``True`` to drop a shadow below a toolbar, ``False`` otherwise.
"""

self._raiseTB = rais

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • artmanager »
  • SVN Revision 69086 For artmanager


MultiColumnListCtrl

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • aui library »
  • aui.aui_switcherdialog »
  • MultiColumnListCtrl

MultiColumnListCtrl

A control for displaying several columns (not scrollable).

hierarchy Inheritance Diagram

Inheritance diagram for: MultiColumnListCtrl

Inheritance diagram of MultiColumnListCtrl

Methods Summary

__init__ |
AdvanceToNextSelectableItem |
CalculateLayout |
DoGetBestSize |
GenerateSelectionEvent |
GetExtraNavigationKey |
GetItems |
GetModifierKey |
OnChar |
OnEraseBackground |
OnKey |
OnMouseEvent |
OnPaint |
SetExtraNavigationKey | Set an extra key that can be used to cycle through items,
SetItems |
SetModifierKey | Set the modifier used to invoke the dialog, and therefore to test for
SetTransparency |
__del__ |

API Class API

class MultiColumnListCtrl(wx.PyControl) [source]

A control for displaying several columns (not scrollable).

__init__(parent, aui_manager, id=wx.ID_ANY, pos=wx.DefaultPosition, size=wx.DefaultSize, style=0, validator=wx.DefaultValidator, name="MultiColumnListCtrl") [source]

AdvanceToNextSelectableItem(direction) [source]

CalculateLayout(dc=None) [source]

DoGetBestSize() [source]

GenerateSelectionEvent() [source]

GetExtraNavigationKey() [source]

GetItems() [source]

GetModifierKey() [source]

OnChar(event) [source]

OnEraseBackground(event) [source]

OnKey(event) [source]

OnMouseEvent(event) [source]

OnPaint(event) [source]

SetExtraNavigationKey(keyCode) [source]

Set an extra key that can be used to cycle through items, in case not using the Ctrl + Tab combination.

SetItems(items) [source]

SetModifierKey(modifierKey) [source]

Set the modifier used to invoke the dialog, and therefore to test for release.

SetTransparency(selection=None) [source]

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • infobar
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • aui library »
  • aui.aui_switcherdialog »
  • MultiColumnListCtrl


SwitcherDialog

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • aui library »
  • aui.aui_switcherdialog »
  • SwitcherDialog

SwitcherDialog

SwitcherDialog shows a MultiColumnListCtrl with a list of panes and tabs for the user to choose. Ctrl + Tab cycles through them.

hierarchy Inheritance Diagram

Inheritance diagram for: SwitcherDialog

Inheritance diagram of SwitcherDialog

Methods Summary

__init__ | Default class constructor.
ColourToHexString |
GetExtraNavigationKey |
GetModifierKey |
GetSelection |
OnActivate |
OnCloseWindow |
OnPaint |
OnSelectItem |
SetBorderColour |
SetExtraNavigationKey |
SetModifierKey |
ShowDescription |

API Class API

class SwitcherDialog(wx.Dialog) [source]

SwitcherDialog shows a MultiColumnListCtrl with a list of panes and tabs for the user to choose. Ctrl + Tab cycles through them.

__init__(items, parent, aui_manager, id=wx.ID_ANY, title=_("Pane Switcher"), pos=wx.DefaultPosition, size=wx.DefaultSize, style=wx.STAY_ON_TOP|wx.DIALOG_NO_PARENT|wx.BORDER_SIMPLE) [source]

Default class constructor.

ColourToHexString(col) [source]

GetExtraNavigationKey() [source]

GetModifierKey() [source]

GetSelection() [source]

OnActivate(event) [source]

OnCloseWindow(event) [source]

OnPaint(event) [source]

OnSelectItem(event) [source]

SetBorderColour(colour) [source]

SetExtraNavigationKey(keyCode) [source]

SetModifierKey(modifierKey) [source]

ShowDescription(i) [source]

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • infobar
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • aui library »
  • aui.aui_switcherdialog »
  • SwitcherDialog


SwitcherItem

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • aui library »
  • aui.aui_switcherdialog »
  • SwitcherItem

SwitcherItem

An object containing information about one item.

hierarchy Inheritance Diagram

Inheritance diagram for: SwitcherItem

Inheritance diagram of SwitcherItem

Methods Summary

__init__ | Default class constructor.
BreakColumn |
Copy | Copy operator between 2 SwitcherItem instances.
GetBitmap |
GetBreakColumn |
GetColPos |
GetDescription |
GetFont |
GetId |
GetIsGroup |
GetName |
GetRect |
GetRowPos |
GetTextColour |
GetTitle |
GetWindow |
SetBitmap |
SetColPos |
SetDescription |
SetFont |
SetId |
SetIsGroup |
SetName |
SetRect |
SetRowPos |
SetTextColour |
SetTitle |
SetWindow |

API Class API

class SwitcherItem(object) [source]

An object containing information about one item.

__init__(item=None) [source]

Default class constructor.

BreakColumn(breakCol=True) [source]

Copy(item) [source]

Copy operator between 2 SwitcherItem instances.

Parameters: item – another instance of SwitcherItem.

GetBitmap() [source]

GetBreakColumn() [source]

GetColPos() [source]

GetDescription() [source]

GetFont() [source]

GetId() [source]

GetIsGroup() [source]

GetName() [source]

GetRect() [source]

GetRowPos() [source]

GetTextColour() [source]

GetTitle() [source]

GetWindow() [source]

SetBitmap(bitmap) [source]

SetColPos(pos) [source]

SetDescription(descr) [source]

SetFont(font) [source]

SetId(id) [source]

SetIsGroup(isGroup) [source]

SetName(name) [source]

SetRect(rect) [source]

SetRowPos(pos) [source]

SetTextColour(colour) [source]

SetTitle(title) [source]

SetWindow(win) [source]

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • infobar
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • aui library »
  • aui.aui_switcherdialog »
  • SwitcherItem


SwitcherItems

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • aui library »
  • aui.aui_switcherdialog »
  • SwitcherItems

SwitcherItems

An object containing switcher items.

hierarchy Inheritance Diagram

Inheritance diagram for: SwitcherItems

Inheritance diagram of SwitcherItems

Methods Summary

__init__ | Default class constructor.
AddGroup |
AddItem |
CalculateItemSize |
Clear |
Copy | Copy operator between 2 SwitcherItems.
FindItemById |
FindItemByName |
GetBackgroundColour |
GetColumnCount |
GetIndexForFocus |
GetItem |
GetItemCount |
GetItemFont |
GetRowCount |
GetSelection |
GetSelectionColour |
GetSelectionOutlineColour |
GetTextColour |
PaintItems |
SetBackgroundColour |
SetColumnCount |
SetItemFont |
SetRowCount |
SetSelection |
SetSelectionByName |
SetSelectionColour |
SetSelectionOutlineColour |
SetTextColour |

API Class API

class SwitcherItems(object) [source]

An object containing switcher items.

__init__(items=None) [source]

Default class constructor.

AddGroup(title, name, id=0, bitmap=wx.NullBitmap) [source]

AddItem(titleOrItem, name=None, id=0, bitmap=wx.NullBitmap) [source]

CalculateItemSize(dc) [source]

Clear() [source]

Copy(items) [source]

Copy operator between 2 SwitcherItems.

Parameters: items – another instance of SwitcherItems.

FindItemById(id) [source]

FindItemByName(name) [source]

GetBackgroundColour() [source]

GetColumnCount() [source]

GetIndexForFocus() [source]

GetItem(i) [source]

GetItemCount() [source]

GetItemFont() [source]

GetRowCount() [source]

GetSelection() [source]

GetSelectionColour() [source]

GetSelectionOutlineColour() [source]

GetTextColour() [source]

PaintItems(dc, win) [source]

SetBackgroundColour(colour) [source]

SetColumnCount(cols) [source]

SetItemFont(font) [source]

SetRowCount(rows) [source]

SetSelection(sel) [source]

SetSelectionByName(name) [source]

SetSelectionColour(colour) [source]

SetSelectionOutlineColour(colour) [source]

SetTextColour(colour) [source]

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • infobar
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • aui library »
  • aui.aui_switcherdialog »
  • SwitcherItems


aui.aui_switcherdialog

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • aui library »
  • aui.aui_switcherdialog

aui.aui_switcherdialog

description Description

The idea of SwitcherDialog is to make it easier to implement keyboard navigation in AUI and other applications that have multiple panes and tabs.

A key combination with a modifier (such as Ctrl + Tab) shows the dialog, and the user holds down the modifier whilst navigating with Tab and arrow keys before releasing the modifier to dismiss the dialog and activate the selected pane.

The switcher dialog is a multi-column menu with no scrolling, implemented by the MultiColumnListCtrl class. You can have headings for your items for logical grouping, and you can force a column break if you need to.

The modifier used for invoking and dismissing the dialog can be customised, as can the colours, number of rows, and the key used for cycling through the items. So you can use different keys on different platforms if required (especially since Ctrl + Tab is reserved on some platforms).

Items are shown as names and optional 16x16 images.

base Base Functionalities

To use the dialog, you set up the items in a SwitcherItems object, before passing this to the SwitcherDialog instance.

Call AddItem and optionally AddGroup to add items and headings. These functions take a label (to be displayed to the user), an identifying name, an integer id, and a bitmap. The name and id are purely for application-defined identification. You may also set a description to be displayed when each item is selected; and you can set a window pointer for convenience when activating the desired window after the dialog returns.

Have created the dialog, you call ShowModal(), and if the return value is wx.ID_OK, retrieve the selection from the dialog and activate the pane.

The sample code below shows a generic method of finding panes and notebook tabs within the current AuiManager, and using the pane name or notebook tab position to display the pane.

The only other code to add is a menu item with the desired accelerator, whose modifier matches the one you pass to SetModifierKey (the default being wx.WXK_CONTROL).

usage Usage

Menu item:

if wx.Platform == "__WXMAC__":
    switcherAccel = "Alt+Tab"
elif wx.Platform == "__WXGTK__":
    switcherAccel = "Ctrl+/"
else:
    switcherAccel = "Ctrl+Tab"

view_menu.Append(ID_SwitchPane, _("S&witch Window...") + "  " + switcherAccel)

Event handler:

def OnSwitchPane(self, event):

    items = SwitcherItems()
    items.SetRowCount(12)

    # Add the main windows and toolbars, in two separate columns
    # We'll use the item 'id' to store the notebook selection, or -1 if not a page

    for k in xrange(2):
        if k == 0:
            items.AddGroup(_("Main Windows"), "mainwindows")
        else:
            items.AddGroup(_("Toolbars"), "toolbars").BreakColumn()

        for pane in self._mgr.GetAllPanes():
            name = pane.name
            caption = pane.caption

            toolbar = isinstance(info.window, wx.ToolBar) or isinstance(info.window, aui.AuiToolBar)
            if caption and (toolBar  and k == 1) or (not toolBar and k == 0):
                items.AddItem(caption, name, -1).SetWindow(pane.window)

    # Now add the wxAuiNotebook pages

    items.AddGroup(_("Notebook Pages"), "pages").BreakColumn()

    for pane in self._mgr.GetAllPanes():
        nb = pane.window
        if isinstance(nb, aui.AuiNotebook):
            for j in xrange(nb.GetPageCount()):

                name = nb.GetPageText(j)
                win = nb.GetPage(j)

                items.AddItem(name, name, j, nb.GetPageBitmap(j)).SetWindow(win)

    # Select the focused window

    idx = items.GetIndexForFocus()
    if idx != wx.NOT_FOUND:
        items.SetSelection(idx)

    if wx.Platform == "__WXMAC__":
        items.SetBackgroundColour(wx.WHITE)

    # Show the switcher dialog

    dlg = SwitcherDialog(items, wx.GetApp().GetTopWindow())

    # In GTK+ we can't use Ctrl+Tab; we use Ctrl+/ instead and tell the switcher
    # to treat / in the same was as tab (i.e. cycle through the names)

    if wx.Platform == "__WXGTK__":
        dlg.SetExtraNavigationKey(wxT('/'))

    if wx.Platform == "__WXMAC__":
        dlg.SetBackgroundColour(wx.WHITE)
        dlg.SetModifierKey(wx.WXK_ALT)

    ans = dlg.ShowModal()

    if ans == wx.ID_OK and dlg.GetSelection() != -1:
        item = items.GetItem(dlg.GetSelection())

        if item.GetId() == -1:
            info = self._mgr.GetPane(item.GetName())
            info.Show()
            self._mgr.Update()
            info.window.SetFocus()

        else:
            nb = item.GetWindow().GetParent()
            win = item.GetWindow();
            if isinstance(nb, aui.AuiNotebook):
                nb.SetSelection(item.GetId())
                win.SetFocus()

Module author: Andrea Gavana <andrea.gavana@gmail.com>

hierarchy Inheritance Diagram

Inheritance diagram for module: aui.aui_switcherdialog

Inheritance diagram of aui.aui_switcherdialog.MultiColumnListCtrl, aui.aui_switcherdialog.SwitcherDialog, aui.aui_switcherdialog.SwitcherItem, aui.aui_switcherdialog.SwitcherItems

SVN Revisions

A graphical representation of the SVN commits in the last year.

Click on any date in the picture to jump to that particular revision page, containing information about committers, log messages and SVN diffs.

Revision Graph For aui_switcherdialog

2to3 Python 3 Issues (via 2to3)

No issues have been detected by 2to3.py.

Class Summary

  • MultiColumnListCtrl
  • SwitcherDialog
  • SwitcherItem
  • SwitcherItems

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • infobar
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • aui library »
  • aui.aui_switcherdialog


aui.aui_utilities functions

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • aui library »
  • aui.aui_utilities »
  • aui.aui_utilities functions

aui.aui_utilities functions

This is the description of standalone Python functions in the aui.aui_utilities module.

Functions Summary

BitmapFromBits | BitmapFromBits() is a utility function that creates a
BlendColour | Blends the two colour component fg and bg into one colour component, adding an optional alpha channel.
ChopText | Chops the input text if its size does not fit in max_size, by cutting the text and adding ellipsis at the end.
Clip | Clips the value in a based on the extremes b and c.
CopyAttributes | Copies pens, brushes, colours and fonts from the old tab art to the new one.
DarkenBitmap | Darkens the input bitmap on wxMAC using the input colour.
DrawGradientRectangle | Draws a gradient-shaded rectangle.
DrawMACCloseButton | Draws the wxMAC tab close button using wx.GraphicsContext.
FindFocusDescendant | Find a window with the focus, that is also a descendant of the given window.
GetBaseColour | Returns the face shading colour on push buttons/backgrounds, mimicking as closely
GetDockingImage | Returns the correct name of the docking bitmap depending on the input parameters.
GetLabelSize | Returns the AuiToolBar item label size.
GetSlidingPoints | Returns the point at which the sliding in and out of a minimized pane begins.
IndentPressedBitmap | Indents the input rectangle rect based on the value of button_state.
LightColour | Brighten input colour by percent.
LightContrastColour | Creates a new, lighter colour based on the input colour c.
MakeDisabledBitmap | Convert the given image (in place) to a grayed-out version, appropriate for a ‘disabled’ appearance.
MakeGray | Make a pixel grayed-out.
PaneCreateStippleBitmap | Creates a stipple bitmap to be used in a wx.Brush.
RescaleScreenShot | Rescales a bitmap to be 300 pixels wide (or tall) at maximum.
StepColour | Darken/lighten the input colour c.
TakeScreenShot | Takes a screenshot of the screen at given position and size (rect).

API Functions API

BitmapFromBits(bits, w, h, colour) [source]

BitmapFromBits() is a utility function that creates a masked bitmap from raw bits (XBM format).

Parameters:
  • bits – a string containing the raw bits of the bitmap;
  • w – the bitmap width;
  • h – the bitmap height;
  • colour – the colour which will replace all white pixels in the raw bitmap.

BlendColour(fg, bg, alpha) [source]

Blends the two colour component fg and bg into one colour component, adding an optional alpha channel.

Parameters:
  • fg – the first colour component;
  • bg – the second colour component;
  • alpha – an optional transparency value.

ChopText(dc, text, max_size) [source]

Chops the input text if its size does not fit in max_size, by cutting the text and adding ellipsis at the end.

Parameters:
  • dc – a wx.DC device context;
  • text – the text to chop;
  • max_size – the maximum size in which the text should fit.

Clip(a, b, c) [source]

Clips the value in a based on the extremes b and c.

Parameters:
  • a – the value to analyze;
  • b – a minimum value;
  • c – a maximum value.

CopyAttributes(newArt, oldArt) [source]

Copies pens, brushes, colours and fonts from the old tab art to the new one.

Parameters:
  • newArt – the new instance of AuiDefaultTabArt;
  • oldArt – the old instance of AuiDefaultTabArt.

DarkenBitmap(bmp, caption_colour, new_colour) [source]

Darkens the input bitmap on wxMAC using the input colour.

Parameters:
  • bmp – the bitmap to be manipulated;
  • caption_colour – the colour of the pane caption;
  • new_colour – the colour used to darken the bitmap.

DrawGradientRectangle(dc, rect, start_colour, end_colour, direction, offset=0, length=0) [source]

Draws a gradient-shaded rectangle.

Parameters:
  • dc – a wx.DC device context;

  • rect – the rectangle in which to draw the gradient;
  • start_colour – the first colour of the gradient;
  • end_colour – the second colour of the gradient;
  • direction – the gradient direction (horizontal or vertical).

DrawMACCloseButton(colour, backColour=None) [source]

Draws the wxMAC tab close button using wx.GraphicsContext.

Parameters:
  • colour – the colour to use to draw the circle;
  • backColour – the optional background colour for the circle.

FindFocusDescendant(ancestor) [source]

Find a window with the focus, that is also a descendant of the given window. This is used to determine the window to initially send commands to.

Parameters: ancestor – the window to check for ancestry.

GetBaseColour() [source]

Returns the face shading colour on push buttons/backgrounds, mimicking as closely as possible the platform UI colours.

GetDockingImage(direction, useAero, center) [source]

Returns the correct name of the docking bitmap depending on the input parameters.

Parameters:
  • useAero – whether AuiManager is using Aero-style or Whidbey-style docking images or not;
  • center – whether we are looking for the center diamond-shaped bitmap or not.

GetLabelSize(dc, label, vertical) [source]

Returns the AuiToolBar item label size.

Parameters:
  • label – the toolbar tool label;
  • vertical – whether the toolbar tool orientation is vertical or not.

GetSlidingPoints(rect, size, direction) [source]

Returns the point at which the sliding in and out of a minimized pane begins.

Parameters:
  • rect – the AuiToolBar tool screen rectangle;
  • size – the pane window size;
  • direction – the pane docking direction.

IndentPressedBitmap(rect, button_state) [source]

Indents the input rectangle rect based on the value of button_state.

Parameters:
  • rect – an instance of wx.Rect;
  • button_state – an AuiNotebook button state.

LightColour(colour, percent) [source]

Brighten input colour by percent.

Parameters:
  • colour – the colour to be brightened;
  • percent – brightening percentage.

LightContrastColour(c) [source]

Creates a new, lighter colour based on the input colour c.

Parameters: c – the input colour to analyze.

MakeDisabledBitmap(bitmap) [source]

Convert the given image (in place) to a grayed-out version, appropriate for a ‘disabled’ appearance.

Parameters: bitmap – the bitmap to gray-out.

MakeGray(rgbTuple, factor, maskColour) [source]

Make a pixel grayed-out. If the pixel matches the maskColour, it won’t be changed.

Parameters:
  • rgbTuple – a tuple representing a pixel colour;
  • factor – a graying-out factor;
  • maskColour – a colour mask.

PaneCreateStippleBitmap() [source]

Creates a stipple bitmap to be used in a wx.Brush. This is used to draw sash resize hints.

RescaleScreenShot(bmp, thumbnail_size=200) [source]

Rescales a bitmap to be 300 pixels wide (or tall) at maximum.

Parameters:
  • bmp – the bitmap to rescale;
  • thumbnail_size – the maximum size of every page thumbnail.

StepColour(c, ialpha) [source]

Darken/lighten the input colour c.

Parameters:
  • c – a colour to darken/lighten;
  • ialpha – a transparency value.

TakeScreenShot(rect) [source]

Takes a screenshot of the screen at given position and size (rect).

Parameters: rect – the screen rectangle for which we want to take a screenshot.

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • infobar
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • aui library »
  • aui.aui_utilities »
  • aui.aui_utilities functions


TabDragImage

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • aui library »
  • aui.aui_utilities »
  • TabDragImage

TabDragImage

This class handles the creation of a custom image in case of drag and drop of a notebook tab.

hierarchy Inheritance Diagram

Inheritance diagram for: TabDragImage

Inheritance diagram of TabDragImage

Methods Summary

__init__ | Default class constructor.
CreateBitmap | Actually creates the drag and drop bitmap.

API Class API

class TabDragImage(wx.DragImage) [source]

This class handles the creation of a custom image in case of drag and drop of a notebook tab.

__init__(notebook, page, button_state, tabArt) [source]

Default class constructor.

For internal use: do not call it in your code!

Parameters:
  • notebook – an instance of AuiNotebook;
  • page – the dragged AuiNotebook page;
  • button_state – the state of the close button on the tab;
  • tabArt – an instance of AuiDefaultTabArt or one of its derivations.

CreateBitmap(notebook, page, button_state, tabArt) [source]

Actually creates the drag and drop bitmap.

Parameters:
  • notebook – an instance of AuiNotebook;
  • page – the dragged AuiNotebook page;
  • button_state – the state of the close button on the tab;
  • tabArt – an instance of AuiDefaultTabArt or one of its derivations.

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • infobar
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • aui library »
  • aui.aui_utilities »
  • TabDragImage


aui.aui_utilities

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • aui library »
  • aui.aui_utilities

aui.aui_utilities

This module contains some common functions used by wxPython-AUI to manipulate colours, bitmaps, text, gradient shadings and custom dragging images for AuiNotebook tabs.

Module author: Andrea Gavana <andrea.gavana@gmail.com>

hierarchy Inheritance Diagram

Inheritance diagram for module: aui.aui_utilities

Inheritance diagram of aui.aui_utilities.TabDragImage

SVN Revisions

A graphical representation of the SVN commits in the last year.

Click on any date in the picture to jump to that particular revision page, containing information about committers, log messages and SVN diffs.

Revision Graph For aui_utilities

2to3 Python 3 Issues (via 2to3)

No issues have been detected by 2to3.py.

Function Summary

  • BitmapFromBits
  • BlendColour
  • ChopText
  • Clip
  • CopyAttributes
  • DarkenBitmap
  • DrawGradientRectangle
  • DrawMACCloseButton
  • FindFocusDescendant
  • GetBaseColour
  • GetDockingImage
  • GetLabelSize
  • GetSlidingPoints
  • IndentPressedBitmap
  • LightColour
  • LightContrastColour
  • MakeDisabledBitmap
  • MakeGray
  • PaneCreateStippleBitmap
  • RescaleScreenShot
  • StepColour
  • TakeScreenShot

Class Summary

  • TabDragImage

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • infobar
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • aui library »
  • aui.aui_utilities


AuiDefaultToolBarArt

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • aui library »
  • aui.auibar »
  • AuiDefaultToolBarArt

AuiDefaultToolBarArt

Toolbar art provider code - a tab provider provides all drawing functionality to the AuiToolBar. This allows the AuiToolBar to have a plugable look-and-feel.

By default, a AuiToolBar uses an instance of this class called AuiDefaultToolBarArt which provides bitmap art and a colour scheme that is adapted to the major platforms’ look. You can either derive from that class to alter its behaviour or write a completely new tab art class. Call SetArtProvider to make use this new tab art.

hierarchy Inheritance Diagram

Inheritance diagram for: AuiDefaultToolBarArt

Inheritance diagram of AuiDefaultToolBarArt

Methods Summary

__init__ | Default class constructor.
Clone | Clones the AuiToolBar art.
DrawBackground | Draws a toolbar background with a gradient shading.
DrawButton | Draws a toolbar item button.
DrawControlLabel | Draws a label for a toolbar control.
DrawDropDownButton | Draws a toolbar dropdown button.
DrawGripper | Draws the toolbar gripper.
DrawLabel | Draws a toolbar item label.
DrawOverflowButton | Draws the overflow button for the AuiToolBar.
DrawPlainBackground | Draws a toolbar background with a plain colour.
DrawSeparator | Draws a toolbar separator.
GetAGWFlags | Returns the AuiDefaultToolBarArt flags. See SetAGWFlags for more
GetElementSize | Returns the size of a UI element in the AuiToolBar.
GetFont | Returns the AuiDefaultToolBarArt font.
GetLabelSize | Returns the label size for a toolbar item.
GetOrientation | Returns the toolbar orientation.
GetTextOrientation | Returns the AuiDefaultToolBarArt text orientation. See
GetToolSize | Returns the toolbar item size.
GetToolsPosition | Returns the bitmap and text rectangles for a toolbar item.
SetAGWFlags | Sets the toolbar art flags.
SetDefaultColours | Sets the default colours, which are calculated from the given base colour.
SetElementSize | Sets the size of a UI element in the AuiToolBar.
SetFont | Sets the AuiDefaultToolBarArt font.
SetOrientation | Sets the toolbar tool orientation.
SetTextOrientation | Sets the text orientation.
ShowDropDown | Shows the drop down window menu for overflow items.

API Class API

class AuiDefaultToolBarArt(object) [source]

Toolbar art provider code - a tab provider provides all drawing functionality to the AuiToolBar. This allows the AuiToolBar to have a plugable look-and-feel.

By default, a AuiToolBar uses an instance of this class called AuiDefaultToolBarArt which provides bitmap art and a colour scheme that is adapted to the major platforms’ look. You can either derive from that class to alter its behaviour or write a completely new tab art class. Call AuiToolBar.SetArtProvider() to make use this new tab art.

__init__() [source]

Default class constructor.

Clone() [source]

Clones the AuiToolBar art.

DrawBackground(dc, wnd, _rect, horizontal=True) [source]

Draws a toolbar background with a gradient shading.

Parameters:
  • dc – a wx.DC device context;
  • wnd – a wx.Window derived window;
  • _rect – the AuiToolBar rectangle;
  • horizontal – True if the toolbar is horizontal, False if it is vertical.

DrawButton(dc, wnd, item, rect) [source]

Draws a toolbar item button.

Parameters:
  • dc – a wx.DC device context;

  • wnd – a wx.Window derived window;

  • item – an instance of AuiToolBarItem;
  • rect – the AuiToolBarItem rectangle.

DrawControlLabel(dc, wnd, item, rect) [source]

Draws a label for a toolbar control.

Parameters:
  • dc – a wx.DC device context;

  • wnd – a wx.Window derived window;

  • item – an instance of AuiToolBarItem;
  • rect – the AuiToolBarItem rectangle.

DrawDropDownButton(dc, wnd, item, rect) [source]

Draws a toolbar dropdown button.

Parameters:
  • dc – a wx.DC device context;

  • wnd – a wx.Window derived window;

  • item – an instance of AuiToolBarItem;
  • rect – the AuiToolBarItem rectangle.

DrawGripper(dc, wnd, rect) [source]

Draws the toolbar gripper.

Parameters:
  • dc – a wx.DC device context;

  • wnd – a wx.Window derived window;

  • rect – the AuiToolBar rectangle.

DrawLabel(dc, wnd, item, rect) [source]

Draws a toolbar item label.

Parameters:
  • dc – a wx.DC device context;

  • wnd – a wx.Window derived window;

  • item – an instance of AuiToolBarItem;
  • rect – the AuiToolBarItem rectangle.

DrawOverflowButton(dc, wnd, rect, state) [source]

Draws the overflow button for the AuiToolBar.

Parameters:
  • dc – a wx.DC device context;

  • wnd – a wx.Window derived window;

  • rect – the AuiToolBar rectangle;
  • state – the overflow button state.

DrawPlainBackground(dc, wnd, _rect) [source]

Draws a toolbar background with a plain colour.

This method contrasts with the default behaviour of the AuiToolBar that draws a background gradient and this break the window design when putting it within a control that has margin between the borders and the toolbar (example: put AuiToolBar within a wx.StaticBoxSizer that has a plain background).

Parameters:
  • dc – a wx.DC device context;

  • wnd – a wx.Window derived window;

  • _rect – the AuiToolBar rectangle.

DrawSeparator(dc, wnd, _rect) [source]

Draws a toolbar separator.

Parameters:
  • dc – a wx.DC device context;

  • wnd – a wx.Window derived window;

  • _rect – the AuiToolBarItem rectangle.

GetAGWFlags() [source]

Returns the AuiDefaultToolBarArt flags. See SetAGWFlags for more details.

See also

SetAGWFlags

GetElementSize(element_id) [source]

Returns the size of a UI element in the AuiToolBar.

Parameters: element_id – can be one of the following:

Element Identifier | Description
AUI_TBART_SEPARATOR_SIZE | Separator size in AuiToolBar
AUI_TBART_GRIPPER_SIZE | Gripper size in AuiToolBar
AUI_TBART_OVERFLOW_SIZE | Overflow button size in AuiToolBar

GetFont() [source]

Returns the AuiDefaultToolBarArt font.

GetLabelSize(dc, wnd, item) [source]

Returns the label size for a toolbar item.

Parameters:
  • dc – a wx.DC device context;

  • wnd – a wx.Window derived window;

  • item – an instance of AuiToolBarItem.

GetOrientation() [source]

Returns the toolbar orientation.

GetTextOrientation() [source]

Returns the AuiDefaultToolBarArt text orientation. See SetTextOrientation for more details.

See also

SetTextOrientation

GetToolSize(dc, wnd, item) [source]

Returns the toolbar item size.

Parameters:
  • dc – a wx.DC device context;

  • wnd – a wx.Window derived window;

  • item – an instance of AuiToolBarItem.

GetToolsPosition(dc, item, rect) [source]

Returns the bitmap and text rectangles for a toolbar item.

Parameters:
  • dc – a wx.DC device context;

  • item – an instance of AuiToolBarItem;
  • rect – the tool rect.

SetAGWFlags(agwFlags) [source]

Sets the toolbar art flags.

Parameters: agwFlags – a combination of the following values:

Flag name | Description
AUI_TB_TEXT | Shows the text in the toolbar buttons; by default only icons are shown
AUI_TB_NO_TOOLTIPS | Don’t show tooltips on AuiToolBar items
AUI_TB_NO_AUTORESIZE | Do not auto-resize the AuiToolBar
AUI_TB_GRIPPER | Shows a gripper on the AuiToolBar
AUI_TB_OVERFLOW | The AuiToolBar can contain overflow items
AUI_TB_VERTICAL | The AuiToolBar is vertical
AUI_TB_HORZ_LAYOUT | Shows the text and the icons alongside, not vertically stacked. This style must be used with AUI_TB_TEXT
AUI_TB_PLAIN_BACKGROUND | Don’t draw a gradient background on the toolbar
AUI_TB_HORZ_TEXT | Combination of AUI_TB_HORZ_LAYOUT and AUI_TB_TEXT

SetDefaultColours(base_colour=None) [source]

Sets the default colours, which are calculated from the given base colour.

Parameters: base_colour – an instance of wx.Colour. If defaulted to None, a colour is generated accordingly to the platform and theme.

SetElementSize(element_id, size) [source]

Sets the size of a UI element in the AuiToolBar.

Parameters:
  • element_id – can be one of the following:

    Element Identifier | Description
    AUI_TBART_SEPARATOR_SIZE | Separator size in AuiToolBar
    AUI_TBART_GRIPPER_SIZE | Gripper size in AuiToolBar
    AUI_TBART_OVERFLOW_SIZE | Overflow button size in AuiToolBar
  • size – the new size of the UI element.

SetFont(font) [source]

Sets the AuiDefaultToolBarArt font.

Parameters: font – a wx.Font object.

SetOrientation(orientation) [source]

Sets the toolbar tool orientation.

Parameters: orientation – one of AUI_TBTOOL_HORIZONTAL, AUI_TBTOOL_VERT_CLOCKWISE or AUI_TBTOOL_VERT_COUNTERCLOCKWISE.

SetTextOrientation(orientation) [source]

Sets the text orientation.

Parameters: orientation – can be one of the following constants:

Orientation Switches | Description
AUI_TBTOOL_TEXT_LEFT | Text in AuiToolBar items is aligned left
AUI_TBTOOL_TEXT_RIGHT | Text in AuiToolBar items is aligned right
AUI_TBTOOL_TEXT_TOP | Text in AuiToolBar items is aligned top
AUI_TBTOOL_TEXT_BOTTOM | Text in AuiToolBar items is aligned bottom

ShowDropDown(wnd, items) [source]

Shows the drop down window menu for overflow items.

Parameters:
  • wnd – an instance of wx.Window;

  • items – the overflow toolbar items (a Python list).

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • infobar
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • aui library »
  • aui.auibar »
  • AuiDefaultToolBarArt


AuiToolBar

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • aui library »
  • aui.auibar »
  • AuiToolBar

AuiToolBar

AuiToolBar is a completely owner-drawn toolbar perfectly integrated with the AUI layout system. This allows drag and drop of toolbars, docking/floating behaviour and the possibility to define “overflow” items in the toolbar itself.

The default theme that is used is AuiDefaultToolBarArt, which provides a modern, glossy look and feel. The theme can be changed by calling SetArtProvider.

hierarchy Inheritance Diagram

Inheritance diagram for: AuiToolBar

Inheritance diagram of AuiToolBar

appearance Control Appearance

AuiToolBar

Methods Summary

__init__ | Default class constructor.
AddCheckTool | Adds a new check (or toggle) tool to the AuiToolBar.
AddControl | Adds any control to the toolbar, typically e.g.
AddLabel | Adds a label tool to the AuiToolBar.
AddRadioTool | Adds a new radio tool to the toolbar.
AddSeparator | Adds a separator for spacing groups of tools.
AddSimpleTool | Adds a tool to the toolbar.
AddSpacer | Adds a spacer for spacing groups of tools.
AddStretchSpacer | Adds a stretchable spacer for spacing groups of tools.
AddToggleTool | Adds a toggle tool to the toolbar.
AddTool | Adds a tool to the toolbar.
Clear | Deletes all the tools in the AuiToolBar.
ClearTools | Deletes all the tools in the AuiToolBar.
DeleteTool | Removes the specified tool from the toolbar and deletes it.
DeleteToolByPos | This function behaves like DeleteTool but it deletes the tool at the
DoGetBestSize | Gets the size which best suits the window: for a control, it would be the
DoIdleUpdate | Updates the toolbar during idle times.
DoSetSize | Sets the position and size of the window in pixels.
EnableTool | Enables or disables the tool.
FindControl | Returns a pointer to the control identified by id or None if no corresponding
FindTool | Finds a tool for the given tool id.
FindToolByIndex | Finds a tool for the given tool position in the AuiToolBar.
FindToolByLabel | Finds a tool for the given label.
FindToolForPosition | Finds a tool for the given mouse position.
FindToolForPositionWithPacking | Finds a tool for the given mouse position, taking into account also the tool packing.
GetAGWWindowStyleFlag | Returns the AGW-specific window style flag.
GetArtProvider | Returns the current art provider being used.
GetAuiManager | Returns the AuiManager which manages the toolbar.
GetGripperVisible | Returns whether the toolbar gripper is visible or not.
GetLabelSize | Returns the standard size of a toolbar item.
GetOverflowRect | Returns the rectangle of the overflow button.
GetOverflowState | Returns the state of the overflow button.
GetOverflowVisible | Returns whether the overflow button is visible or not.
GetToolBarFits | Returns whether the AuiToolBar size fits in a specified size.
GetToolBitmap | Returns the tool bitmap for the tool identified by tool_id.
GetToolBitmapSize | Returns the size of bitmap that the toolbar expects to have.
GetToolBorderPadding | Returns the padding between the tool border and the label, in pixels.
GetToolCount | Returns the number of tools in the AuiToolBar.
GetToolDropDown | Returns whether the toolbar item identified by tool_id has an associated drop down window menu or not.
GetToolEnabled | Returns whether the tool identified by tool_id is enabled or not.
GetToolFits | Returns whether the tool identified by tool_id fits into the toolbar or not.
GetToolFitsByIndex | Returns whether the tool identified by tool_id fits into the toolbar or not.
GetToolIndex | Returns the position of the tool in the toolbar given its identifier.
GetToolLabel | Returns the tool label for the tool identified by tool_id.
GetToolLongHelp | Returns the long help for the given tool.
GetToolOrientation | Returns the orientation for the toolbar items.
GetToolPacking | Returns the value used for spacing tools.
GetToolPos | Returns the position of the tool in the toolbar given its identifier.
GetToolProportion | Returns the tool proportion in the toolbar.
GetToolRect | Returns the toolbar item rectangle
GetToolSeparation | Returns the separator size for the toolbar, in pixels.
GetToolShortHelp | Returns the short help for the given tool.
GetToolSticky | Returns whether the toolbar item identified by tool_id has a sticky behaviour or not.
GetToolTextOrientation | Returns the label orientation for the toolbar items.
GetToolToggled | Returns whether a tool is toggled or not.
HitTest | Finds a tool for the given mouse position.
IsPaneMinimized | Returns whether this AuiToolBar contains a minimized pane tool.
OnCustomRender | Handles custom render for single AuiToolBar items.
OnEraseBackground | Handles the wx.EVT_ERASE_BACKGROUND event for AuiToolBar.
OnIdle | Handles the wx.EVT_IDLE event for AuiToolBar.
OnLeaveWindow | Handles the wx.EVT_LEAVE_WINDOW event for AuiToolBar.
OnLeftDown | Handles the wx.EVT_LEFT_DOWN event for AuiToolBar.
OnLeftUp | Handles the wx.EVT_LEFT_UP event for AuiToolBar.
OnMiddleDown | Handles the wx.EVT_MIDDLE_DOWN event for AuiToolBar.
OnMiddleUp | Handles the wx.EVT_MIDDLE_UP event for AuiToolBar.
OnMotion | Handles the wx.EVT_MOTION event for AuiToolBar.
OnPaint | Handles the wx.EVT_PAINT event for AuiToolBar.
OnRightDown | Handles the wx.EVT_RIGHT_DOWN event for AuiToolBar.
OnRightUp | Handles the wx.EVT_RIGHT_UP event for AuiToolBar.
OnSetCursor | Handles the wx.EVT_SET_CURSOR event for AuiToolBar.
OnSize | Handles the wx.EVT_SIZE event for AuiToolBar.
Realize | Realizes the toolbar.
RefreshOverflowState | Refreshes the overflow button.
SetAGWWindowStyleFlag | Sets the AGW-specific style of the window.
SetArtProvider | Instructs AuiToolBar to use art provider specified by parameter art
SetAuiManager | Sets the AuiManager which manages the toolbar.
SetCustomOverflowItems | Sets the two lists prepend and append as custom overflow items.
SetFont | Sets the AuiToolBar font.
SetGripperVisible | Sets whether the toolbar gripper is visible or not.
SetHoverItem | Sets a toolbar item to be currently hovered by the mouse.
SetMargins | Set the values to be used as margins for the toolbar.
SetMarginsSize | Set the values to be used as margins for the toolbar.
SetMarginsXY | Set the values to be used as margins for the toolbar.
SetOrientation | Sets the toolbar orientation.
SetOverflowVisible | Sets whether the overflow button is visible or not.
SetPressedItem | Sets a toolbar item to be currently in a “pressed” state.
SetToolAlignment | This sets the alignment for all of the tools within the toolbar (only has an effect when the toolbar is expanded).
SetToolBitmap | Sets the tool bitmap for the tool identified by tool_id.
SetToolBitmapSize | Sets the default size of each tool bitmap.
SetToolBorderPadding | Sets the padding between the tool border and the label.
SetToolDisabledBitmap | Sets the tool disabled bitmap for the tool identified by tool_id.
SetToolDropDown | Assigns a drop down window menu to the toolbar item.
SetToolLabel | Sets the tool label for the tool identified by tool_id.
SetToolLongHelp | Sets the long help for the given tool.
SetToolNormalBitmap | Sets the tool bitmap for the tool identified by tool_id.
SetToolOrientation | Sets the tool orientation for the toolbar items.
SetToolPacking | Sets the value used for spacing tools.
SetToolProportion | Sets the tool proportion in the toolbar.
SetToolSeparation | Sets the separator size for the toolbar.
SetToolShortHelp | Sets the short help for the given tool.
SetToolSticky | Sets the toolbar item as sticky or non-sticky.
SetToolTextOrientation | Sets the label orientation for the toolbar items.
SetWindowStyleFlag | Sets the style of the window.
StartPreviewTimer | Starts a timer in AuiManager to slide-in/slide-out the minimized pane.
StopPreviewTimer | Stops a timer in AuiManager to slide-in/slide-out the minimized pane.
ToggleTool | Toggles a tool on or off.

API Class API

class AuiToolBar(wx.PyControl) [source]

AuiToolBar is a completely owner-drawn toolbar perfectly integrated with the AUI layout system. This allows drag and drop of toolbars, docking/floating behaviour and the possibility to define “overflow” items in the toolbar itself.

The default theme that is used is AuiDefaultToolBarArt, which provides a modern, glossy look and feel. The theme can be changed by calling AuiToolBar.SetArtProvider().

__init__(parent, id=wx.ID_ANY, pos=wx.DefaultPosition, size=wx.DefaultSize, style=0, agwStyle=AUI_TB_DEFAULT_STYLE) [source]

Default class constructor.

Parameters:
  • parent – the AuiToolBar parent;
  • id – an identifier for the control: a value of -1 is taken to mean a default;
  • pos – the control position. A value of (-1, -1) indicates a default position, chosen by either the windowing system or wxPython, depending on platform;
  • size – the control size. A value of (-1, -1) indicates a default size, chosen by either the windowing system or wxPython, depending on platform;
  • style – the control window style;
  • agwStyle – the AGW-specific window style. This can be a combination of the following bits:

    Flag name | Description
    AUI_TB_TEXT | Shows the text in the toolbar buttons; by default only icons are shown
    AUI_TB_NO_TOOLTIPS | Don’t show tooltips on AuiToolBar items
    AUI_TB_NO_AUTORESIZE | Do not auto-resize the AuiToolBar
    AUI_TB_GRIPPER | Shows a gripper on the AuiToolBar
    AUI_TB_OVERFLOW | The AuiToolBar can contain overflow items
    AUI_TB_VERTICAL | The AuiToolBar is vertical
    AUI_TB_HORZ_LAYOUT | Shows the text and the icons alongside, not vertically stacked. This style must be used with AUI_TB_TEXT
    AUI_TB_PLAIN_BACKGROUND | Don’t draw a gradient background on the toolbar
    AUI_TB_HORZ_TEXT | Combination of AUI_TB_HORZ_LAYOUT and AUI_TB_TEXT

    The default value for agwStyle is: AUI_TB_DEFAULT_STYLE = 0

AddCheckTool(tool_id, label, bitmap, disabled_bitmap, short_help_string='', long_help_string='', client_data=None) [source]

Adds a new check (or toggle) tool to the AuiToolBar.

See also

AddTool.

AddControl(control, label='') [source]

Adds any control to the toolbar, typically e.g. a combobox.

Parameters:
  • control – the control to be added;
  • label – the label which appears if the control goes into the overflow items in the toolbar.

AddLabel(tool_id, label='', width=0) [source]

Adds a label tool to the AuiToolBar.

Parameters:
  • tool_id – an integer by which the tool may be identified in subsequent operations;
  • label – the toolbar tool label;
  • width – the tool width.

AddRadioTool(tool_id, label, bitmap, disabled_bitmap, short_help_string='', long_help_string='', client_data=None) [source]

Adds a new radio tool to the toolbar.

Consecutive radio tools form a radio group such that exactly one button in the group is pressed at any moment, in other words whenever a button in the group is pressed the previously pressed button is automatically released. You should avoid having the radio groups of only one element as it would be impossible for the user to use such button.

Note

By default, the first button in the radio group is initially pressed, the others are not.

See also

AddTool.

AddSeparator() [source]

Adds a separator for spacing groups of tools.

AddSimpleTool(tool_id, label, bitmap, short_help_string="", kind=ITEM_NORMAL, target=None) [source]

Adds a tool to the toolbar. This is the simplest method you can use to ass an item to the AuiToolBar.

Parameters:
  • tool_id – an integer by which the tool may be identified in subsequent operations;
  • label – the toolbar tool label;
  • bitmap – the primary tool bitmap;
  • short_help_string – this string is used for the tools tooltip;
  • kind – the item kind. Can be one of the following:

    Item Kind | Description
    ITEM_CONTROL | The item in the AuiToolBar is a control
    ITEM_LABEL | The item in the AuiToolBar is a text label
    ITEM_SPACER | The item in the AuiToolBar is a spacer
    ITEM_SEPARATOR | The item in the AuiToolBar is a separator
    ITEM_CHECK | The item in the AuiToolBar is a toolbar check item
    ITEM_NORMAL | The item in the AuiToolBar is a standard toolbar item
    ITEM_RADIO | The item in the AuiToolBar is a toolbar radio item
  • target – a custom string indicating that an instance of AuiPaneInfo has been minimized into this toolbar.

AddSpacer(pixels) [source]

Adds a spacer for spacing groups of tools.

Parameters: pixels – the width of the spacer.

AddStretchSpacer(proportion=1) [source]

Adds a stretchable spacer for spacing groups of tools.

Parameters: proportion – the stretchable spacer proportion.

AddToggleTool(tool_id, bitmap, disabled_bitmap, toggle=False, client_data=None, short_help_string='', long_help_string='') [source]

Adds a toggle tool to the toolbar.

Parameters:
  • tool_id – an integer by which the tool may be identified in subsequent operations;
  • bitmap – the primary tool bitmap;
  • disabled_bitmap – the bitmap to use when the tool is disabled. If it is equal to wx.NullBitmap, the disabled bitmap is automatically generated by greing the normal one;
  • client_data – whatever Python object to associate with the toolbar item;
  • short_help_string – this string is used for the tools tooltip;
  • long_help_string – this string is shown in the statusbar (if any) of the parent frame when the mouse pointer is inside the tool.

AddTool(tool_id, label, bitmap, disabled_bitmap, kind, short_help_string='', long_help_string='', client_data=None, target=None) [source]

Adds a tool to the toolbar. This is the full feature version of AddTool.

Parameters:
  • tool_id – an integer by which the tool may be identified in subsequent operations;
  • label – the toolbar tool label;
  • bitmap – the primary tool bitmap;
  • disabled_bitmap – the bitmap to use when the tool is disabled. If it is equal to wx.NullBitmap, the disabled bitmap is automatically generated by greing the normal one;
  • kind – the item kind. Can be one of the following:

    Item Kind | Description
    ITEM_CONTROL | The item in the AuiToolBar is a control
    ITEM_LABEL | The item in the AuiToolBar is a text label
    ITEM_SPACER | The item in the AuiToolBar is a spacer
    ITEM_SEPARATOR | The item in the AuiToolBar is a separator
    ITEM_CHECK | The item in the AuiToolBar is a toolbar check item
    ITEM_NORMAL | The item in the AuiToolBar is a standard toolbar item
    ITEM_RADIO | The item in the AuiToolBar is a toolbar radio item
  • short_help_string – this string is used for the tools tooltip;
  • long_help_string – this string is shown in the statusbar (if any) of the parent frame when the mouse pointer is inside the tool.
  • client_data – whatever Python object to associate with the toolbar item.
  • target – a custom string indicating that an instance of AuiPaneInfo has been minimized into this toolbar.

Clear() [source]

Deletes all the tools in the AuiToolBar.

ClearTools() [source]

Deletes all the tools in the AuiToolBar.

DeleteTool(tool_id) [source]

Removes the specified tool from the toolbar and deletes it.

Parameters: tool_id – the AuiToolBarItem identifier.
Returns: True if the tool was deleted, False otherwise.

Note

Note that it is unnecessary to call Realize for the change to take place, it will happen immediately.

DeleteToolByPos(pos) [source]

This function behaves like DeleteTool but it deletes the tool at the specified position and not the one with the given id.

Parameters: pos – the tool position.

See also

DeleteTool

DoGetBestSize() [source]

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

Note

Overridden from wx.PyControl.

DoIdleUpdate() [source]

Updates the toolbar during idle times.

DoSetSize(x, y, width, height, sizeFlags=wx.SIZE_AUTO) [source]

Sets the position and size of the window in pixels. The sizeFlags parameter indicates the interpretation of the other params if they are equal to -1.

Parameters:
  • x – the window x position;
  • y – the window y position;
  • width – the window width;
  • height – the window height;
  • sizeFlags – may have one of this bit set:

    Size Flags | Description
    wx.SIZE_AUTO | A -1 indicates that a class-specific default should be used.
    wx.SIZE_AUTO_WIDTH | A -1 indicates that a class-specific default should be used for the width.
    wx.SIZE_AUTO_HEIGHT | A -1 indicates that a class-specific default should be used for the height.
    wx.SIZE_USE_EXISTING | Existing dimensions should be used if -1 values are supplied.
    wx.SIZE_ALLOW_MINUS_ONE | Allow dimensions of -1 and less to be interpreted as real dimensions, not default values.
    wx.SIZE_FORCE | Normally, if the position and the size of the window are already the same as the parameters of this function, nothing is done. but with this flag a window resize may be forced even in this case (supported in wx 2.6.2 and later and only implemented for MSW and ignored elsewhere currently)

Note

Overridden from wx.PyControl.

EnableTool(tool_id, state) [source]

Enables or disables the tool.

Parameters:
  • tool_id – identifier for the tool to enable or disable.
  • state – if True, enables the tool, otherwise disables it.

FindControl(id) [source]

Returns a pointer to the control identified by id or None if no corresponding control is found.

Parameters: id – the control identifier.

FindTool(tool_id) [source]

Finds a tool for the given tool id.

Parameters: tool_id – the AuiToolBarItem identifier.

FindToolByIndex(pos) [source]

Finds a tool for the given tool position in the AuiToolBar.

Parameters: pos – the tool position in the toolbar.
Returns: a pointer to a AuiToolBarItem if a tool is found, or None otherwise.

FindToolByLabel(label) [source]

Finds a tool for the given label.

Parameters: tool_id – the AuiToolBarItem label.

FindToolForPosition(x, y) [source]

Finds a tool for the given mouse position.

Parameters:
  • x – mouse x position;
  • y – mouse y position.
Returns:

a pointer to a AuiToolBarItem if a tool is found, or None otherwise.

FindToolForPositionWithPacking(x, y) [source]

Finds a tool for the given mouse position, taking into account also the tool packing.

Parameters:
  • x – mouse x position;
  • y – mouse y position.
Returns:

a pointer to a AuiToolBarItem if a tool is found, or None otherwise.

GetAGWWindowStyleFlag() [source]

Returns the AGW-specific window style flag.

See also

SetAGWWindowStyleFlag for an explanation of various AGW-specific style.

GetArtProvider() [source]

Returns the current art provider being used.

GetAuiManager() [source]

Returns the AuiManager which manages the toolbar.

GetGripperVisible() [source]

Returns whether the toolbar gripper is visible or not.

GetLabelSize(label) [source]

Returns the standard size of a toolbar item.

Parameters: label – a test label.

GetOverflowRect() [source]

Returns the rectangle of the overflow button.

GetOverflowState() [source]

Returns the state of the overflow button.

GetOverflowVisible() [source]

Returns whether the overflow button is visible or not.

GetToolBarFits() [source]

Returns whether the AuiToolBar size fits in a specified size.

GetToolBitmap(tool_id) [source]

Returns the tool bitmap for the tool identified by tool_id.

Parameters: tool_id – the tool identifier.

GetToolBitmapSize() [source]

Returns the size of bitmap that the toolbar expects to have. The default bitmap size is 16 by 15 pixels.

Note

Note that this is the size of the bitmap you pass to AddTool, and not the eventual size of the tool button.

Todo

Add wx.ToolBar compatibility, actually implementing this method.

GetToolBorderPadding() [source]

Returns the padding between the tool border and the label, in pixels.

GetToolCount() [source]

Returns the number of tools in the AuiToolBar.

GetToolDropDown(tool_id) [source]

Returns whether the toolbar item identified by tool_id has an associated drop down window menu or not.

Parameters: tool_id – the AuiToolBarItem identifier.

GetToolEnabled(tool_id) [source]

Returns whether the tool identified by tool_id is enabled or not.

Parameters: tool_id – the tool identifier.

GetToolFits(tool_id) [source]

Returns whether the tool identified by tool_id fits into the toolbar or not.

Parameters: tool_id – the toolbar item identifier.

GetToolFitsByIndex(tool_id) [source]

Returns whether the tool identified by tool_id fits into the toolbar or not.

Parameters: tool_id – the toolbar item identifier.

GetToolIndex(tool_id) [source]

Returns the position of the tool in the toolbar given its identifier.

Parameters: tool_id – the toolbar item identifier.

GetToolLabel(tool_id) [source]

Returns the tool label for the tool identified by tool_id.

Parameters: tool_id – the tool identifier.

GetToolLongHelp(tool_id) [source]

Returns the long help for the given tool.

Parameters: tool_id – the tool identifier.

GetToolOrientation() [source]

Returns the orientation for the toolbar items.

GetToolPacking() [source]

Returns the value used for spacing tools. The default value is 1 pixel.

GetToolPos(tool_id) [source]

Returns the position of the tool in the toolbar given its identifier.

Parameters: tool_id – the toolbar item identifier.

GetToolProportion(tool_id) [source]

Returns the tool proportion in the toolbar.

Parameters: tool_id – the AuiToolBarItem identifier.

GetToolRect(tool_id) [source]

Returns the toolbar item rectangle

Parameters: tool_id – the toolbar item identifier.

GetToolSeparation() [source]

Returns the separator size for the toolbar, in pixels.

GetToolShortHelp(tool_id) [source]

Returns the short help for the given tool.

Parameters: tool_id – the tool identifier.

GetToolSticky(tool_id) [source]

Returns whether the toolbar item identified by tool_id has a sticky behaviour or not.

Parameters: tool_id – the AuiToolBarItem identifier.

GetToolTextOrientation() [source]

Returns the label orientation for the toolbar items.

GetToolToggled(tool_id) [source]

Returns whether a tool is toggled or not.

Parameters: tool_id – the toolbar item identifier.

Note

This only applies to a tool that has been specified as a toggle tool.

HitTest(x, y) [source]

Finds a tool for the given mouse position.

Parameters:
  • x – mouse x position;
  • y – mouse y position.
Returns:

a pointer to a AuiToolBarItem if a tool is found, or None otherwise.

Note

This method is similar to FindToolForPosition but it works with absolute coordinates.

IsPaneMinimized() [source]

Returns whether this AuiToolBar contains a minimized pane tool.

OnCustomRender(dc, item, rect) [source]

Handles custom render for single AuiToolBar items.

Parameters:
  • dc – a wx.DC device context;
  • item – an instance of AuiToolBarItem;
  • rect – the toolbar item rect.

Note

This method must be overridden to provide custom rendering of items.

OnEraseBackground(event) [source]

Handles the wx.EVT_ERASE_BACKGROUND event for AuiToolBar.

Parameters: event – a wx.EraseEvent event to be processed.

Note

This is intentionally empty, to reduce flicker.

OnIdle(event) [source]

Handles the wx.EVT_IDLE event for AuiToolBar.

Parameters: event – a wx.IdleEvent event to be processed.

OnLeaveWindow(event) [source]

Handles the wx.EVT_LEAVE_WINDOW event for AuiToolBar.

Parameters: event – a wx.MouseEvent event to be processed.

OnLeftDown(event) [source]

Handles the wx.EVT_LEFT_DOWN event for AuiToolBar.

Parameters: event – a wx.MouseEvent event to be processed.

OnLeftUp(event) [source]

Handles the wx.EVT_LEFT_UP event for AuiToolBar.

Parameters: event – a wx.MouseEvent event to be processed.

OnMiddleDown(event) [source]

Handles the wx.EVT_MIDDLE_DOWN event for AuiToolBar.

Parameters: event – a wx.MouseEvent event to be processed.

OnMiddleUp(event) [source]

Handles the wx.EVT_MIDDLE_UP event for AuiToolBar.

Parameters: event – a wx.MouseEvent event to be processed.

OnMotion(event) [source]

Handles the wx.EVT_MOTION event for AuiToolBar.

Parameters: event – a wx.MouseEvent event to be processed.

OnPaint(event) [source]

Handles the wx.EVT_PAINT event for AuiToolBar.

Parameters: event – a wx.PaintEvent event to be processed.

OnRightDown(event) [source]

Handles the wx.EVT_RIGHT_DOWN event for AuiToolBar.

Parameters: event – a wx.MouseEvent event to be processed.

OnRightUp(event) [source]

Handles the wx.EVT_RIGHT_UP event for AuiToolBar.

Parameters: event – a wx.MouseEvent event to be processed.

OnSetCursor(event) [source]

Handles the wx.EVT_SET_CURSOR event for AuiToolBar.

Parameters: event – a wx.SetCursorEvent event to be processed.

OnSize(event) [source]

Handles the wx.EVT_SIZE event for AuiToolBar.

Parameters: event – a wx.SizeEvent event to be processed.

Realize() [source]

Realizes the toolbar. This function should be called after you have added tools.

RefreshOverflowState() [source]

Refreshes the overflow button.

SetAGWWindowStyleFlag(agwStyle) [source]

Sets the AGW-specific style of the window.

Parameters: agwStyle – the new window style. This can be a combination of the following bits:

Flag name | Description
AUI_TB_TEXT | Shows the text in the toolbar buttons; by default only icons are shown
AUI_TB_NO_TOOLTIPS | Don’t show tooltips on AuiToolBar items
AUI_TB_NO_AUTORESIZE | Do not auto-resize the AuiToolBar
AUI_TB_GRIPPER | Shows a gripper on the AuiToolBar
AUI_TB_OVERFLOW | The AuiToolBar can contain overflow items
AUI_TB_VERTICAL | The AuiToolBar is vertical
AUI_TB_HORZ_LAYOUT | Shows the text and the icons alongside, not vertically stacked. This style must be used with AUI_TB_TEXT
AUI_TB_PLAIN_BACKGROUND | Don’t draw a gradient background on the toolbar
AUI_TB_HORZ_TEXT | Combination of AUI_TB_HORZ_LAYOUT and AUI_TB_TEXT

Note

Please note that some styles cannot be changed after the window creation and that Refresh might need to be be called after changing the others for the change to take place immediately.

SetArtProvider(art) [source]

Instructs AuiToolBar to use art provider specified by parameter art for all drawing calls. This allows plugable look-and-feel features.

Parameters: art – an art provider.

Note

The previous art provider object, if any, will be deleted by AuiToolBar.

SetAuiManager(auiManager) [source]

Sets the AuiManager which manages the toolbar.

SetCustomOverflowItems(prepend, append) [source]

Sets the two lists prepend and append as custom overflow items.

Parameters:
  • prepend – a list of AuiToolBarItem to be prepended;
  • append – a list of AuiToolBarItem to be appended.

SetFont(font) [source]

Sets the AuiToolBar font.

Parameters: font – a wx.Font object.

Note

Overridden from wx.PyControl.

SetGripperVisible(visible) [source]

Sets whether the toolbar gripper is visible or not.

Parameters: visible – True for a visible gripper, False otherwise.

SetHoverItem(pitem) [source]

Sets a toolbar item to be currently hovered by the mouse.

Parameters: pitem – an instance of AuiToolBarItem.

SetMargins(left=-1, right=-1, top=-1, bottom=-1) [source]

Set the values to be used as margins for the toolbar.

Parameters:
  • left – the left toolbar margin;
  • right – the right toolbar margin;
  • top – the top toolbar margin;
  • bottom – the bottom toolbar margin.

SetMarginsSize(size) [source]

Set the values to be used as margins for the toolbar.

Parameters: size – the margin size (an instance of wx.Size).

SetMarginsXY(x, y) [source]

Set the values to be used as margins for the toolbar.

Parameters:
  • x – left margin, right margin and inter-tool separation value;
  • y – top margin, bottom margin and inter-tool separation value.

SetOrientation(orientation) [source]

Sets the toolbar orientation.

Parameters: orientation – either wx.VERTICAL or wx.HORIZONTAL.

Note

This can be temporarily overridden by AuiManager when floating and docking a AuiToolBar.

SetOverflowVisible(visible) [source]

Sets whether the overflow button is visible or not.

Parameters: visible – True for a visible overflow button, False otherwise.

SetPressedItem(pitem) [source]

Sets a toolbar item to be currently in a “pressed” state.

Parameters: pitem – an instance of AuiToolBarItem.

SetToolAlignment(alignment=wx.EXPAND) [source]

This sets the alignment for all of the tools within the toolbar (only has an effect when the toolbar is expanded).

Parameters: alignment – wx.Sizer alignment value (wx.ALIGN_CENTER_HORIZONTAL or wx.ALIGN_CENTER_VERTICAL).

SetToolBitmap(tool_id, bitmap) [source]

Sets the tool bitmap for the tool identified by tool_id.

Parameters:
  • tool_id – the tool identifier;
  • bitmap – the new bitmap for the toolbar item (an instance of wx.Bitmap).

SetToolBitmapSize(size) [source]

Sets the default size of each tool bitmap. The default bitmap size is 16 by 15 pixels.

Parameters: size – the size of the bitmaps in the toolbar.

Note

This should be called to tell the toolbar what the tool bitmap size is. Call it before you add tools.

Note

Note that this is the size of the bitmap you pass to AddTool, and not the eventual size of the tool button.

Todo

Add wx.ToolBar compatibility, actually implementing this method.

SetToolBorderPadding(padding) [source]

Sets the padding between the tool border and the label.

Parameters: padding – the padding in pixels.

SetToolDisabledBitmap(tool_id, bitmap) [source]

Sets the tool disabled bitmap for the tool identified by tool_id.

Parameters:
  • tool_id – the tool identifier;
  • bitmap – the new disabled bitmap for the toolbar item (an instance of wx.Bitmap).

SetToolDropDown(tool_id, dropdown) [source]

Assigns a drop down window menu to the toolbar item.

Parameters:
  • tool_id – the AuiToolBarItem identifier;
  • dropdown – whether to assign a drop down menu or not.

SetToolLabel(tool_id, label) [source]

Sets the tool label for the tool identified by tool_id.

Parameters:
  • tool_id – the tool identifier;
  • label – the new toolbar item label.

SetToolLongHelp(tool_id, help_string) [source]

Sets the long help for the given tool.

Parameters:
  • tool_id – the tool identifier;
  • help_string – the string for the long help.

SetToolNormalBitmap(tool_id, bitmap) [source]

Sets the tool bitmap for the tool identified by tool_id.

Parameters:
  • tool_id – the tool identifier;
  • bitmap – the new bitmap for the toolbar item (an instance of wx.Bitmap).

SetToolOrientation(orientation) [source]

Sets the tool orientation for the toolbar items.

Parameters: orientation – the AuiToolBarItem orientation.

SetToolPacking(packing) [source]

Sets the value used for spacing tools. The default value is 1 pixel.

Parameters: packing – the value for packing.

SetToolProportion(tool_id, proportion) [source]

Sets the tool proportion in the toolbar.

Parameters:
  • tool_id – the AuiToolBarItem identifier;
  • proportion – the tool proportion in the toolbar.

SetToolSeparation(separation) [source]

Sets the separator size for the toolbar.

Parameters: separation – the separator size in pixels.

SetToolShortHelp(tool_id, help_string) [source]

Sets the short help for the given tool.

Parameters:
  • tool_id – the tool identifier;
  • help_string – the string for the short help.

SetToolSticky(tool_id, sticky) [source]

Sets the toolbar item as sticky or non-sticky.

Parameters:
  • tool_id – the AuiToolBarItem identifier;
  • sticky – whether the tool should be sticky or not.

SetToolTextOrientation(orientation) [source]

Sets the label orientation for the toolbar items.

Parameters: orientation – the AuiToolBarItem label orientation.

SetWindowStyleFlag(style) [source]

Sets the style of the window.

Parameters: style – the new window style.

Note

Please note that some styles cannot be changed after the window creation and that Refresh might need to be be called after changing the others for the change to take place immediately.

Note

Overridden from wx.PyControl.

StartPreviewTimer() [source]

Starts a timer in AuiManager to slide-in/slide-out the minimized pane.

StopPreviewTimer() [source]

Stops a timer in AuiManager to slide-in/slide-out the minimized pane.

ToggleTool(tool_id, state) [source]

Toggles a tool on or off. This does not cause any event to get emitted.

Parameters:
  • tool_id – tool in question.
  • state – if True, toggles the tool on, otherwise toggles it off.

Note

This only applies to a tool that has been specified as a toggle tool.

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • infobar
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • aui library »
  • aui.auibar »
  • AuiToolBar


AuiToolBarEvent

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • aui library »
  • aui.auibar »
  • AuiToolBarEvent

AuiToolBarEvent

A specialized command event class for events sent by AuiToolBar.

hierarchy Inheritance Diagram

Inheritance diagram for: AuiToolBarEvent

Inheritance diagram of AuiToolBarEvent

supclasses Known Superclasses

  • aui.auibar.CommandToolBarEvent

Methods Summary

__init__ | Default class constructor.
Allow | This is the opposite of Veto: it explicitly allows the event to be
GetNotifyEvent | Returns the actual wx.NotifyEvent.
IsAllowed | Returns whether the event is allowed or not.
Veto | Prevents the change announced by this event from happening.

API Class API

class AuiToolBarEvent(CommandToolBarEvent) [source]

A specialized command event class for events sent by AuiToolBar.

__init__(command_type=None, win_id=0) [source]

Default class constructor.

Parameters:
  • command_type – the event kind or an instance of wx.PyCommandEvent.
  • win_id – the window identification number.

Allow() [source]

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

GetNotifyEvent() [source]

Returns the actual wx.NotifyEvent.

IsAllowed() [source]

Returns whether the event is allowed or not.

Veto() [source]

Prevents the change announced by this event from happening.

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

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • infobar
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • aui library »
  • aui.auibar »
  • AuiToolBarEvent


AuiToolBarItem

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • aui library »
  • aui.auibar »
  • AuiToolBarItem

AuiToolBarItem

AuiToolBarItem is a toolbar element.

It has a unique id (except for the separators which always have id = -1), the style (telling whether it is a normal button, separator or a control), the state (toggled or not, enabled or not) and short and long help strings. The default implementations use the short help string for the tooltip text which is popped up when the mouse pointer enters the tool and the long help string for the applications status bar.

hierarchy Inheritance Diagram

Inheritance diagram for: AuiToolBarItem

Inheritance diagram of AuiToolBarItem

Methods Summary

__init__ | Default class constructor.
Assign | Assigns the properties of the AuiToolBarItem c to self.
GetAlignment | Returns the toolbar item alignment.
GetBitmap | Returns the toolbar item bitmap.
GetDisabledBitmap | Returns the toolbar item disabled bitmap.
GetHoverBitmap | Returns the toolbar item hover bitmap.
GetId | Returns the toolbar item identifier.
GetKind | Returns the toolbar item kind.
GetLabel | Returns the toolbar item label.
GetLongHelp | Returns the long help string for the AuiToolBarItem.
GetMinSize | Returns the toolbar item minimum size.
GetOrientation | Returns the toolbar tool orientation.
GetProportion | Returns the AuiToolBarItem proportion in the toolbar.
GetRotatedBitmap | Returns the correct bitmap depending on the tool orientation.
GetShortHelp | Returns the short help string for the AuiToolBarItem.
GetSizerItem | Returns the associated sizer item.
GetSpacerPixels | Returns the number of pixels for a toolbar item with kind = ITEM_SEPARATOR.
GetState | Returns the toolbar item state.
GetUserData | Returns the associated user data.
GetWindow | Returns window associated to the toolbar item.
HasDropDown | Returns whether the toolbar item has an associated dropdown menu or not.
IsActive | Returns whether the toolbar item is active or not.
IsSticky | Returns whether the toolbar item has a sticky behaviour or not.
SetActive | Activates/deactivates the toolbar item.
SetAlignment | Sets the toolbar item alignment.
SetBitmap | Sets the toolbar item bitmap.
SetDisabledBitmap | Sets the toolbar item disabled bitmap.
SetHasDropDown | Sets whether the toolbar item has an associated dropdown menu.
SetHoverBitmap | Sets the toolbar item hover bitmap.
SetId | Sets the toolbar item identifier.
SetKind | Sets the AuiToolBarItem kind.
SetLabel | Sets the toolbar item label.
SetLongHelp | Sets the long help string for the toolbar item.
SetMinSize | Sets the toolbar item minimum size.
SetOrientation | Sets the toolbar tool orientation.
SetProportion | Sets the AuiToolBarItem proportion in the toolbar.
SetShortHelp | Sets the short help string for the AuiToolBarItem, to be displayed in a
SetSizerItem | Associates a sizer item to this toolbar item.
SetSpacerPixels | Sets the number of pixels for a toolbar item with kind = ITEM_SEPARATOR.
SetState | Sets the toolbar item state.
SetSticky | Sets whether the toolbar item is sticky (permanent highlight after mouse enter) or not.
SetUserData | Associates some kind of user data to the toolbar item.
SetWindow | Assigns a window to the toolbar item.

API Class API

class AuiToolBarItem(object) [source]

AuiToolBarItem is a toolbar element.

It has a unique id (except for the separators which always have id = -1), the style (telling whether it is a normal button, separator or a control), the state (toggled or not, enabled or not) and short and long help strings. The default implementations use the short help string for the tooltip text which is popped up when the mouse pointer enters the tool and the long help string for the applications status bar.

__init__(item=None) [source]

Default class constructor.

Parameters: item – another instance of AuiToolBarItem.

Assign(c) [source]

Assigns the properties of the AuiToolBarItem c to self.

Parameters: c – another instance of AuiToolBarItem.

GetAlignment() [source]

Returns the toolbar item alignment.

GetBitmap() [source]

Returns the toolbar item bitmap.

GetDisabledBitmap() [source]

Returns the toolbar item disabled bitmap.

GetHoverBitmap() [source]

Returns the toolbar item hover bitmap.

GetId() [source]

Returns the toolbar item identifier.

GetKind() [source]

Returns the toolbar item kind. See SetKind for more details.

GetLabel() [source]

Returns the toolbar item label.

GetLongHelp() [source]

Returns the long help string for the AuiToolBarItem.

GetMinSize() [source]

Returns the toolbar item minimum size.

GetOrientation() [source]

Returns the toolbar tool orientation.

GetProportion() [source]

Returns the AuiToolBarItem proportion in the toolbar.

GetRotatedBitmap(disabled) [source]

Returns the correct bitmap depending on the tool orientation.

Parameters: disabled – whether to return the disabled bitmap or not.

GetShortHelp() [source]

Returns the short help string for the AuiToolBarItem.

GetSizerItem() [source]

Returns the associated sizer item.

GetSpacerPixels() [source]

Returns the number of pixels for a toolbar item with kind = ITEM_SEPARATOR.

GetState() [source]

Returns the toolbar item state. See SetState for more details.

See also

SetState

GetUserData() [source]

Returns the associated user data.

GetWindow() [source]

Returns window associated to the toolbar item.

HasDropDown() [source]

Returns whether the toolbar item has an associated dropdown menu or not.

IsActive() [source]

Returns whether the toolbar item is active or not.

IsSticky() [source]

Returns whether the toolbar item has a sticky behaviour or not.

SetActive(b) [source]

Activates/deactivates the toolbar item.

Parameters: b – True to activate the item, False to deactivate it.

SetAlignment(l) [source]

Sets the toolbar item alignment.

Parameters: l – the item alignment, which can be one of the available wx.Sizer alignments.

SetBitmap(bmp) [source]

Sets the toolbar item bitmap.

Parameters: bmp – an instance of wx.Bitmap.

SetDisabledBitmap(bmp) [source]

Sets the toolbar item disabled bitmap.

Parameters: bmp – an instance of wx.Bitmap.

SetHasDropDown(b) [source]

Sets whether the toolbar item has an associated dropdown menu.

Parameters: b – True to set a dropdown menu, False otherwise.

SetHoverBitmap(bmp) [source]

Sets the toolbar item hover bitmap.

Parameters: bmp – an instance of wx.Bitmap.

SetId(new_id) [source]

Sets the toolbar item identifier.

Parameters: new_id – the new tool id.

SetKind(new_kind) [source]

Sets the AuiToolBarItem kind.

Parameters: new_kind – can be one of the following items:

Item Kind | Description
ITEM_CONTROL | The item in the AuiToolBar is a control
ITEM_LABEL | The item in the AuiToolBar is a text label
ITEM_SPACER | The item in the AuiToolBar is a spacer
ITEM_SEPARATOR | The item in the AuiToolBar is a separator
ITEM_CHECK | The item in the AuiToolBar is a toolbar check item
ITEM_NORMAL | The item in the AuiToolBar is a standard toolbar item
ITEM_RADIO | The item in the AuiToolBar is a toolbar radio item

SetLabel(s) [source]

Sets the toolbar item label.

Parameters: s – a string specifying the toolbar item label.

SetLongHelp(s) [source]

Sets the long help string for the toolbar item. This string is shown in the statusbar (if any) of the parent frame when the mouse pointer is inside the tool.

Parameters: s – the tool long help string.

SetMinSize(s) [source]

Sets the toolbar item minimum size.

Parameters: s – an instance of wx.Size.

SetOrientation(a) [source]

Sets the toolbar tool orientation.

Parameters: a – one of AUI_TBTOOL_HORIZONTAL, AUI_TBTOOL_VERT_CLOCKWISE or AUI_TBTOOL_VERT_COUNTERCLOCKWISE.

SetProportion(p) [source]

Sets the AuiToolBarItem proportion in the toolbar.

Parameters: p – the item proportion.

SetShortHelp(s) [source]

Sets the short help string for the AuiToolBarItem, to be displayed in a wx.ToolTip when the mouse hover over the toolbar item.

Parameters: s – the tool short help string.

SetSizerItem(s) [source]

Associates a sizer item to this toolbar item.

Parameters: s – an instance of wx.SizerItem.

SetSpacerPixels(s) [source]

Sets the number of pixels for a toolbar item with kind = ITEM_SEPARATOR.

Parameters: s – number of pixels.

SetState(new_state) [source]

Sets the toolbar item state.

Parameters: new_state – can be one of the following states:

Button State Constant | Description
AUI_BUTTON_STATE_NORMAL | Normal button state
AUI_BUTTON_STATE_HOVER | Hovered button state
AUI_BUTTON_STATE_PRESSED | Pressed button state
AUI_BUTTON_STATE_DISABLED | Disabled button state
AUI_BUTTON_STATE_HIDDEN | Hidden button state
AUI_BUTTON_STATE_CHECKED | Checked button state

SetSticky(b) [source]

Sets whether the toolbar item is sticky (permanent highlight after mouse enter) or not.

Parameters: b – True to set the item as sticky, False otherwise.

SetUserData(l) [source]

Associates some kind of user data to the toolbar item.

Parameters: l – a Python object.

Note

The user data can be any Python object.

SetWindow(w) [source]

Assigns a window to the toolbar item.

Parameters: w – an instance of wx.Window.

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • infobar
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • aui library »
  • aui.auibar »
  • AuiToolBarItem


CommandToolBarEvent

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • aui library »
  • aui.auibar »
  • CommandToolBarEvent

CommandToolBarEvent

A specialized command event class for events sent by AuiToolBar.

hierarchy Inheritance Diagram

Inheritance diagram for: CommandToolBarEvent

Inheritance diagram of CommandToolBarEvent

subclasses Known Subclasses

  • aui.auibar.AuiToolBarEvent

Methods Summary

__init__ | Default class constructor.
GetClickPoint | Returns the point where the user clicked with the mouse.
GetItemRect | Returns the AuiToolBarItem rectangle.
GetToolId | Returns the AuiToolBarItem identifier.
IsDropDownClicked | Returns whether the drop down menu has been clicked.
SetClickPoint | Sets the clicking point.
SetDropDownClicked | Sets whether the drop down menu has been clicked.
SetItemRect | Sets the AuiToolBarItem rectangle.
SetToolId | Sets the AuiToolBarItem identifier.

API Class API

class CommandToolBarEvent(wx.PyCommandEvent) [source]

A specialized command event class for events sent by AuiToolBar.

__init__(command_type, win_id) [source]

Default class constructor.

Parameters:
  • command_type – the event kind or an instance of wx.PyCommandEvent.
  • win_id – the window identification number.

GetClickPoint() [source]

Returns the point where the user clicked with the mouse.

GetItemRect() [source]

Returns the AuiToolBarItem rectangle.

GetToolId() [source]

Returns the AuiToolBarItem identifier.

IsDropDownClicked() [source]

Returns whether the drop down menu has been clicked.

SetClickPoint(p) [source]

Sets the clicking point.

Parameters: p – a wx.Point object.

SetDropDownClicked(c) [source]

Sets whether the drop down menu has been clicked.

Parameters: c – True to set the drop down as clicked, False otherwise.

SetItemRect(r) [source]

Sets the AuiToolBarItem rectangle.

Parameters: r – an instance of wx.Rect.

SetToolId(id) [source]

Sets the AuiToolBarItem identifier.

Parameters: id – the toolbar item identifier.

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • infobar
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • aui library »
  • aui.auibar »
  • CommandToolBarEvent


ToolbarCommandCapture

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • aui library »
  • aui.auibar »
  • ToolbarCommandCapture

ToolbarCommandCapture

A class to handle the dropdown window menu.

hierarchy Inheritance Diagram

Inheritance diagram for: ToolbarCommandCapture

Inheritance diagram of ToolbarCommandCapture

Methods Summary

__init__ | Default class constructor.
GetCommandId | Returns the event command identifier.
ProcessEvent | Processes an event, searching event tables and calling zero or more suitable event handler function(s).

API Class API

class ToolbarCommandCapture(wx.PyEvtHandler) [source]

A class to handle the dropdown window menu.

__init__() [source]

Default class constructor.

GetCommandId() [source]

Returns the event command identifier.

ProcessEvent(event) [source]

Processes an event, searching event tables and calling zero or more suitable event handler function(s).

Parameters: event – the event to process.

Note

Normally, your application would not call this function: it is called in the wxPython implementation to dispatch incoming user interface events to the framework (and application). However, you might need to call it if implementing new functionality (such as a new control) where you define new event types, as opposed to allowing the user to override functions.

An instance where you might actually override the ProcessEvent function is where you want to direct event processing to event handlers not normally noticed by wxPython. For example, in the document/view architecture, documents and views are potential event handlers. When an event reaches a frame, ProcessEvent will need to be called on the associated document and view in case event handler functions are associated with these objects.

The normal order of event table searching is as follows:

  1. If the object is disabled (via a call to SetEvtHandlerEnabled) the function skips to step (6).
  2. If the object is a wx.Window, ProcessEvent is recursively called on the window’s wx.Validator. If this returns True, the function exits.
  3. wxWidgets SearchEventTable is called for this event handler. If this fails, the base class table is tried, and so on until no more tables exist or an appropriate function was found, in which case the function exits.
  4. The search is applied down the entire chain of event handlers (usually the chain has a length of one). If this succeeds, the function exits.
  5. If the object is a wx.Window and the event is a wx.CommandEvent, ProcessEvent is recursively applied to the parent window’s event handler. If this returns True, the function exits.
  6. Finally, ProcessEvent is called on the wx.App object.

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • infobar
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • aui library »
  • aui.auibar »
  • ToolbarCommandCapture


aui.auibar

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • aui library »
  • aui.auibar

aui.auibar

auibar contains an implementation of AuiToolBar, which is a completely owner-drawn toolbar perfectly integrated with the AUI layout system. This allows drag and drop of toolbars, docking/floating behaviour and the possibility to define “overflow” items in the toolbar itself.

The default theme that is used is AuiDefaultToolBarArt, which provides a modern, glossy look and feel. The theme can be changed by calling SetArtProvider.

Module author: Andrea Gavana <andrea.gavana@gmail.com>

hierarchy Inheritance Diagram

Inheritance diagram for module: aui.auibar

Inheritance diagram of aui.auibar.AuiDefaultToolBarArt, aui.auibar.AuiToolBar, aui.auibar.AuiToolBarEvent, aui.auibar.AuiToolBarItem, aui.auibar.CommandToolBarEvent, aui.auibar.ToolbarCommandCapture

SVN Revisions

A graphical representation of the SVN commits in the last year.

Click on any date in the picture to jump to that particular revision page, containing information about committers, log messages and SVN diffs.

Revision Graph For auibar

2to3 Python 3 Issues (via 2to3)

No issues have been detected by 2to3.py.

Class Summary

  • AuiDefaultToolBarArt
  • AuiToolBar
  • AuiToolBarEvent
  • AuiToolBarItem
  • CommandToolBarEvent
  • ToolbarCommandCapture

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • infobar
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • aui library »
  • aui.auibar


AuiNotebook

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • aui library »
  • aui.auibook »
  • AuiNotebook

AuiNotebook

AuiNotebook is a notebook control which implements many features common in applications with dockable panes. Specifically, AuiNotebook implements functionality which allows the user to rearrange tab order via drag-and-drop, split the tab window into many different splitter configurations, and toggle through different themes to customize the control’s look and feel.

An effort has been made to try to maintain an API as similar to that of wx.Notebook.

The default theme that is used is AuiDefaultTabArt, which provides a modern, glossy look and feel. The theme can be changed by calling SetArtProvider.

hierarchy Inheritance Diagram

Inheritance diagram for: AuiNotebook

Inheritance diagram of AuiNotebook

subclasses Known Subclasses

  • aui.tabmdi.AuiMDIClientWindow

appearance Control Appearance

AuiNotebook

Methods Summary

__init__ | Default class constructor.
AddControlToPage | Adds a control inside a tab (not in the tab area).
AddPage | Adds a page.
AddTabAreaButton | Adds a button in the tab area.
AdvanceSelection | Cycles through the tabs.
AssignImageList | Sets the image list for the AuiNotebook control.
CalculateNewSplitSize | Calculates the size of the new split.
CalculateTabCtrlHeight | Calculates the tab control area height.
CloneTabAreaButtons | Clones the tab area buttons when the AuiNotebook is being split.
DeletePage | Deletes a page at the given index.
Destroy | Destroys the window safely.
DoSizing | Performs all sizing operations in each tab control.
EditTab | Starts the editing of an item label, sending a EVT_AUINOTEBOOK_BEGIN_LABEL_EDIT event.
EnableTab | Enables/disables a page in the notebook.
EnsureVisible | Ensures the input page index indx is visible.
FindNextActiveTab | Finds the next active tab (used mainly when AuiNotebook has inactive/disabled
FindTab | Finds the tab control that currently contains the window as well as the index of the window in the tab control.
FloatPage | Float the page in page_index by reparenting it to a floating frame.
GetAGWWindowStyleFlag | Returns the AGW-specific style of the window.
GetActiveTabCtrl | Returns the active tab control.
GetArtProvider | Returns the associated art provider.
GetAuiManager | Returns the associated AuiManager.
GetCurrentPage | Returns the currently active page (not the index), or None if none was selected.
GetDefaultBorder | Returns the default border style for AuiNotebook.
GetEnabled | Returns whether the page specified by the index page_idx is enabled.
GetHeightForPageHeight | Gets the height of the notebook for a given page height.
GetImageList | Returns the associated image list (if any).
GetMinMaxTabWidth | Returns the minimum and the maximum tab widths for AuiNotebook when the
GetPage | Returns the page specified by the given index.
GetPageBitmap | Returns the tab bitmap for the page.
GetPageCount | Returns the number of pages in the notebook.
GetPageImage | Returns the image index for the given page.
GetPageIndex | Returns the page index for the specified window.
GetPageInfo | Returns the AuiNotebookPage info structure specified by the given index.
GetPageText | Returns the tab label for the page.
GetPageTextColour | Returns the tab text colour for the page.
GetSashDClickUnsplit | Returns whether a splitted AuiNotebook can be unsplitted by double-clicking
GetSelection | Returns the index of the currently active page, or -1 if none was selected.
GetTabContainer | Returns the instance of AuiTabContainer.
GetTabCtrlFromPoint | Returns the tab control at the specified point.
GetTabCtrlHeight | Returns the tab control height.
GetTabFrameFromTabCtrl | Returns the tab frame associated with a tab control.
GetTabFrameFromWindow | Returns the tab frame associated with a window.
HasCloseButton | Returns whether a tab displays a close button or not.
HasMultiplePages | This method should be overridden to return True if this window has multiple pages. All
HideAllTabs | Hides all tabs on the AuiNotebook control.
InitNotebook | Contains common initialization code called by all constructors.
InsertPage | This is similar to AddPage, but allows the ability to specify the insert location.
IsMouseWellOutsideWindow | Returns whether the mouse is well outside the AuiNotebook screen rectangle.
IsRenamable | Returns whether a tab can be renamed or not.
LoadPerspective | Loads a layout which was saved with SavePerspective.
NotebookPreview | Generates a preview of all the pages in the notebook (MSW and GTK only).
OnChildFocusNotebook | Handles the wx.EVT_CHILD_FOCUS event for AuiNotebook.
OnCloseFloatingPage | Handles the wx.EVT_CLOSE event for a floating page in AuiNotebook.
OnNavigationKeyNotebook | Handles the wx.EVT_NAVIGATION_KEY event for AuiNotebook.
OnRenameAccept | Called by TabTextCtrl, to accept the changes and to send the
OnRenameCancelled | Called by TabTextCtrl, to cancel the changes and to send the
OnSize | Handles the wx.EVT_SIZE event for AuiNotebook.
OnTabBeginDrag | Handles the EVT_AUINOTEBOOK_BEGIN_DRAG event for AuiNotebook.
OnTabBgDClick | Handles the EVT_AUINOTEBOOK_BG_DCLICK event for AuiNotebook.
OnTabButton | Handles the EVT_AUINOTEBOOK_BUTTON event for AuiNotebook.
OnTabCancelDrag | Handles the EVT_AUINOTEBOOK_CANCEL_DRAG event for AuiNotebook.
OnTabClicked | Handles the EVT_AUINOTEBOOK_PAGE_CHANGING event for AuiNotebook.
OnTabDClick | Handles the EVT_AUINOTEBOOK_TAB_DCLICK event for AuiNotebook.
OnTabDragMotion | Handles the EVT_AUINOTEBOOK_DRAG_MOTION event for AuiNotebook.
OnTabEndDrag | Handles the EVT_AUINOTEBOOK_END_DRAG event for AuiNotebook.
OnTabMiddleDown | Handles the EVT_AUINOTEBOOK_TAB_MIDDLE_DOWN event for AuiNotebook.
OnTabMiddleUp | Handles the EVT_AUINOTEBOOK_TAB_MIDDLE_UP event for AuiNotebook.
OnTabRightDown | Handles the EVT_AUINOTEBOOK_TAB_RIGHT_DOWN event for AuiNotebook.
OnTabRightUp | Handles the EVT_AUINOTEBOOK_TAB_RIGHT_UP event for AuiNotebook.
ReDockPage | Re-docks a floating AuiNotebook tab in the original position, when possible.
RemoveControlFromPage | Removes a control from a tab (not from the tab area).
RemoveEmptyTabFrames | Removes all the empty tab frames.
RemovePage | Removes a page, without deleting the window pointer.
RemoveTabAreaButton | Removes a button from the tab area.
ReparentControl | Reparents a control added inside a tab.
ResetTextControl | Called by TabTextCtrl when it marks itself for deletion.
SavePerspective | Saves the entire user interface layout into an encoded string, which can then
SetAGWWindowStyleFlag | Sets the AGW-specific style of the window.
SetArtProvider | Sets the art provider to be used by the notebook.
SetCloseButton | Sets whether a tab should display a close button or not.
SetFont | Sets the tab font.
SetImageList | Sets the image list for the AuiNotebook control.
SetMeasuringFont | Sets the font for calculating text measurements.
SetMinMaxTabWidth | Sets the minimum and/or the maximum tab widths for AuiNotebook when the
SetNavigatorIcon | Sets the icon used by the TabNavigatorWindow.
SetNormalFont | Sets the normal font for drawing tab labels.
SetPageBitmap | Sets the tab bitmap for the page.
SetPageImage | Sets the image index for the given page.
SetPageText | Sets the tab label for the page.
SetPageTextColour | Sets the tab text colour for the page.
SetRenamable | Sets whether a tab can be renamed via a left double-click or not.
SetSashDClickUnsplit | Sets whether to unsplit a splitted AuiNotebook when double-clicking on a sash.
SetSelectedFont | Sets the selected tab font for drawing tab labels.
SetSelection | Sets the page selection.
SetSelectionToPage | Sets the selection based on the input page.
SetSelectionToWindow | Sets the selection based on the input window win.
SetTabCtrlHeight | Sets the tab height.
SetUniformBitmapSize | Ensures that all tabs will have the same height, even if some tabs don’t have bitmaps.
ShowWindowMenu | Shows the window menu for the active tab control associated with this
Split | Performs a split operation programmatically.
UnSplit | Restores original view after a tab split.
UnsplitDClick | Unsplit the AuiNotebook on sash double-click.
UpdateHintWindowSize | Updates the AuiManager hint window size.
UpdateTabCtrlHeight | UpdateTabCtrlHeight() does the actual tab resizing. It’s meant

API Class API

class AuiNotebook(wx.PyPanel) [source]

AuiNotebook is a notebook control which implements many features common in applications with dockable panes. Specifically, AuiNotebook implements functionality which allows the user to rearrange tab order via drag-and-drop, split the tab window into many different splitter configurations, and toggle through different themes to customize the control’s look and feel.

An effort has been made to try to maintain an API as similar to that of wx.Notebook.

The default theme that is used is AuiDefaultTabArt, which provides a modern, glossy look and feel. The theme can be changed by calling AuiNotebook.SetArtProvider().

__init__(parent, id=wx.ID_ANY, pos=wx.DefaultPosition, size=wx.DefaultSize, style=0, agwStyle=AUI_NB_DEFAULT_STYLE, name="AuiNotebook") [source]

Default class constructor.

Parameters:
  • parent – the AuiNotebook parent;
  • id – an identifier for the control: a value of -1 is taken to mean a default;
  • pos – the control position. A value of (-1, -1) indicates a default position, chosen by either the windowing system or wxPython, depending on platform;
  • size – the control size. A value of (-1, -1) indicates a default size, chosen by either the windowing system or wxPython, depending on platform;
  • style – the underlying wx.PyPanel window style;
  • agwStyle – the AGW-specific window style. This can be a combination of the following bits:

    Flag name | Description
    AUI_NB_TOP | With this style, tabs are drawn along the top of the notebook
    AUI_NB_LEFT | With this style, tabs are drawn along the left of the notebook. Not implemented yet.
    AUI_NB_RIGHT | With this style, tabs are drawn along the right of the notebook. Not implemented yet.
    AUI_NB_BOTTOM | With this style, tabs are drawn along the bottom of the notebook
    AUI_NB_TAB_SPLIT | Allows the tab control to be split by dragging a tab
    AUI_NB_TAB_MOVE | Allows a tab to be moved horizontally by dragging
    AUI_NB_TAB_EXTERNAL_MOVE | Allows a tab to be moved to another tab control
    AUI_NB_TAB_FIXED_WIDTH | With this style, all tabs have the same width
    AUI_NB_SCROLL_BUTTONS | With this style, left and right scroll buttons are displayed
    AUI_NB_WINDOWLIST_BUTTON | With this style, a drop-down list of windows is available
    AUI_NB_CLOSE_BUTTON | With this style, a close button is available on the tab bar
    AUI_NB_CLOSE_ON_ACTIVE_TAB | With this style, a close button is available on the active tab
    AUI_NB_CLOSE_ON_ALL_TABS | With this style, a close button is available on all tabs
    AUI_NB_MIDDLE_CLICK_CLOSE | Allows to close AuiNotebook tabs by mouse middle button click
    AUI_NB_SUB_NOTEBOOK | This style is used by AuiManager to create automatic AuiNotebooks
    AUI_NB_HIDE_ON_SINGLE_TAB | Hides the tab window if only one tab is present
    AUI_NB_SMART_TABS | Use Smart Tabbing, like Alt + Tab on Windows
    AUI_NB_USE_IMAGES_DROPDOWN | Uses images on dropdown window list menu instead of check items
    AUI_NB_CLOSE_ON_TAB_LEFT | Draws the tab close button on the left instead of on the right (a la Camino browser)
    AUI_NB_TAB_FLOAT | Allows the floating of single tabs. Known limitation: when the notebook is more or less full screen, tabs cannot be dragged far enough outside of the notebook to become floating pages
    AUI_NB_DRAW_DND_TAB | Draws an image representation of a tab while dragging (on by default)
    AUI_NB_ORDER_BY_ACCESS | Tab navigation order by last access time for the tabs
    AUI_NB_NO_TAB_FOCUS | Don’t draw tab focus rectangle

    Default value for agwStyle is: AUI_NB_DEFAULT_STYLE = AUI_NB_TOP | AUI_NB_TAB_SPLIT | AUI_NB_TAB_MOVE | AUI_NB_SCROLL_BUTTONS | AUI_NB_CLOSE_ON_ACTIVE_TAB | AUI_NB_MIDDLE_CLICK_CLOSE | AUI_NB_DRAW_DND_TAB

  • name – the window name.

AddControlToPage(page_idx, control) [source]

Adds a control inside a tab (not in the tab area).

Parameters:
  • page_idx – the page index;
  • control – an instance of wx.Window.

AddPage(page, caption, select=False, bitmap=wx.NullBitmap, disabled_bitmap=wx.NullBitmap, control=None) [source]

Adds a page. If the select parameter is True, calling this will generate a page change event.

Parameters:
  • page – the page to be added;
  • caption – specifies the text for the new page;
  • select – specifies whether the page should be selected;
  • bitmap – the wx.Bitmap to display in the enabled tab;
  • disabled_bitmap – the wx.Bitmap to display in the disabled tab;

  • control – a wx.Window instance inside a tab (or None).

AddTabAreaButton(id, location, normal_bitmap=wx.NullBitmap, disabled_bitmap=wx.NullBitmap) [source]

Adds a button in the tab area.

Parameters:
  • id – the button identifier. This can be one of the following:

    Button Identifier | Description
    AUI_BUTTON_CLOSE | Shows a close button on the tab area
    AUI_BUTTON_WINDOWLIST | Shows a window list button on the tab area
    AUI_BUTTON_LEFT | Shows a left button on the tab area
    AUI_BUTTON_RIGHT | Shows a right button on the tab area
  • location – the button location. Can be wx.LEFT or wx.RIGHT;
  • normal_bitmap – the bitmap for an enabled tab;
  • disabled_bitmap – the bitmap for a disabled tab.

AdvanceSelection(forward=True, wrap=True) [source]

Cycles through the tabs.

Parameters:
  • forward – whether to advance forward or backward;
  • wrap – True to return to the first tab if we reach the last tab.

Note

The call to this function generates the page changing events.

AssignImageList(imageList) [source]

Sets the image list for the AuiNotebook control.

Parameters: imageList – an instance of wx.ImageList.

CalculateNewSplitSize() [source]

Calculates the size of the new split.

CalculateTabCtrlHeight() [source]

Calculates the tab control area height.

CloneTabAreaButtons() [source]

Clones the tab area buttons when the AuiNotebook is being split.

See also

AddTabAreaButton

Note

Standard buttons for AuiNotebook are not cloned, only custom ones.

DeletePage(page_idx) [source]

Deletes a page at the given index. Calling this method will generate a page change event.

Parameters: page_idx – the page index to be deleted.

Note

DeletePage removes a tab from the multi-notebook, and destroys the window as well.

See also

RemovePage

Destroy() [source]

Destroys the window safely.

Use this function instead of the del operator, since different window classes can be destroyed differently. Frames and dialogs are not destroyed immediately when this function is called – they are added to a list of windows to be deleted on idle time, when all the window’s events have been processed. This prevents problems with events being sent to non-existent windows.

Returns: True if the window has either been successfully deleted, or it has been added to the list of windows pending real deletion.

DoSizing() [source]

Performs all sizing operations in each tab control.

EditTab(page_index) [source]

Starts the editing of an item label, sending a EVT_AUINOTEBOOK_BEGIN_LABEL_EDIT event.

Parameters: page_index – the page index we want to edit.

EnableTab(page_idx, enable=True) [source]

Enables/disables a page in the notebook.

Parameters:
  • page_idx – the page index;
  • enable – True to enable the page, False to disable it.

EnsureVisible(indx) [source]

Ensures the input page index indx is visible.

Parameters: indx – the page index.

FindNextActiveTab(ctrl_idx, ctrl) [source]

Finds the next active tab (used mainly when AuiNotebook has inactive/disabled tabs in it).

Parameters:
  • ctrl_idx – the index of the first (most obvious) tab to check for active status;
  • ctrl – an instance of AuiTabCtrl.

FindTab(page) [source]

Finds the tab control that currently contains the window as well as the index of the window in the tab control. It returns True if the window was found, otherwise False.

Parameters: page – an instance of AuiNotebookPage.

FloatPage(page_index) [source]

Float the page in page_index by reparenting it to a floating frame.

Parameters: page_index – the index of the page to be floated.

Warning

When the notebook is more or less full screen, tabs cannot be dragged far enough outside of the notebook to become floating pages.

GetAGWWindowStyleFlag() [source]

Returns the AGW-specific style of the window.

See also

SetAGWWindowStyleFlag for a list of possible AGW-specific window styles.

GetActiveTabCtrl() [source]

Returns the active tab control. It is called to determine which control gets new windows being added.

GetArtProvider() [source]

Returns the associated art provider.

GetAuiManager() [source]

Returns the associated AuiManager.

GetCurrentPage() [source]

Returns the currently active page (not the index), or None if none was selected.

GetDefaultBorder() [source]

Returns the default border style for AuiNotebook.

GetEnabled(page_idx) [source]

Returns whether the page specified by the index page_idx is enabled.

Parameters: page_idx – the page index.

GetHeightForPageHeight(pageHeight) [source]

Gets the height of the notebook for a given page height.

Parameters: pageHeight – the given page height.

GetImageList() [source]

Returns the associated image list (if any).

GetMinMaxTabWidth() [source]

Returns the minimum and the maximum tab widths for AuiNotebook when the AUI_NB_TAB_FIXED_WIDTH style is defined.

Note

Minimum and maximum tabs widths are used only when the AUI_NB_TAB_FIXED_WIDTH style is present.

See also

SetMinMaxTabWidth for more information.

GetPage(page_idx) [source]

Returns the page specified by the given index.

Parameters: page_idx – the page index.

GetPageBitmap(page_idx) [source]

Returns the tab bitmap for the page.

Parameters: page_idx – the page index.

GetPageCount() [source]

Returns the number of pages in the notebook.

GetPageImage(page) [source]

Returns the image index for the given page.

Parameters: page – the given page for which to retrieve the image index.

GetPageIndex(page_wnd) [source]

Returns the page index for the specified window. If the window is not found in the notebook, wx.NOT_FOUND is returned.

GetPageInfo(page_idx) [source]

Returns the AuiNotebookPage info structure specified by the given index.

Parameters: page_idx – the page index.

GetPageText(page_idx) [source]

Returns the tab label for the page.

Parameters: page_idx – the page index.

GetPageTextColour(page_idx) [source]

Returns the tab text colour for the page.

Parameters: page_idx – the page index.

GetSashDClickUnsplit() [source]

Returns whether a splitted AuiNotebook can be unsplitted by double-clicking on the splitter sash.

GetSelection() [source]

Returns the index of the currently active page, or -1 if none was selected.

GetTabContainer() [source]

Returns the instance of AuiTabContainer.

GetTabCtrlFromPoint(pt) [source]

Returns the tab control at the specified point.

Parameters: pt – a wx.Point object.

GetTabCtrlHeight() [source]

Returns the tab control height.

GetTabFrameFromTabCtrl(tab_ctrl) [source]

Returns the tab frame associated with a tab control.

Parameters: tab_ctrl – an instance of AuiTabCtrl.

GetTabFrameFromWindow(wnd) [source]

Returns the tab frame associated with a window.

Parameters: wnd – an instance of wx.Window.

HasCloseButton(page_idx) [source]

Returns whether a tab displays a close button or not.

Parameters: page_idx – the page index.

Note

This can only be called if AUI_NB_CLOSE_ON_ALL_TABS is specified.

HasMultiplePages() [source]

This method should be overridden to return True if this window has multiple pages. All standard class with multiple pages such as wx.Notebook, wx.Listbook and wx.Treebook already override it to return True and user-defined classes with similar behaviour should do it as well to allow the library to handle such windows appropriately.

Note

Overridden from wx.PyPanel.

HideAllTabs(hidden=True) [source]

Hides all tabs on the AuiNotebook control.

Parameters: hidden – if True hides all tabs.

InitNotebook(agwStyle) [source]

Contains common initialization code called by all constructors.

Parameters: agwStyle – the notebook style.

See also

__init__

InsertPage(page_idx, page, caption, select=False, bitmap=wx.NullBitmap, disabled_bitmap=wx.NullBitmap, control=None) [source]

This is similar to AddPage, but allows the ability to specify the insert location.

Parameters:
  • page_idx – specifies the position for the new page;
  • page – the page to be added;
  • caption – specifies the text for the new page;
  • select – specifies whether the page should be selected;
  • bitmap – the wx.Bitmap to display in the enabled tab;

  • disabled_bitmap – the wx.Bitmap to display in the disabled tab;

  • control – a wx.Window instance inside a tab (or None).

IsMouseWellOutsideWindow() [source]

Returns whether the mouse is well outside the AuiNotebook screen rectangle.

IsRenamable(page_idx) [source]

Returns whether a tab can be renamed or not.

Parameters: page_idx – the page index.
Returns: True is a page can be renamed, False otherwise.

LoadPerspective(layout) [source]

Loads a layout which was saved with SavePerspective.

Parameters: layout – a string which contains a saved AuiNotebook layout.

NavigatorProps

NotebookPreview(thumbnail_size=200) [source]

Generates a preview of all the pages in the notebook (MSW and GTK only).

Parameters: thumbnail_size – the maximum size of every page thumbnail.

Note

this functionality is currently unavailable on wxMac.

OnChildFocusNotebook(event) [source]

Handles the wx.EVT_CHILD_FOCUS event for AuiNotebook.

Parameters: event – a wx.ChildFocusEvent event to be processed.

OnCloseFloatingPage(event) [source]

Handles the wx.EVT_CLOSE event for a floating page in AuiNotebook.

Parameters: event – a wx.CloseEvent event to be processed.

OnNavigationKeyNotebook(event) [source]

Handles the wx.EVT_NAVIGATION_KEY event for AuiNotebook.

Parameters: event – a wx.NavigationKeyEvent event to be processed.

OnRenameAccept(page_index, value) [source]

Called by TabTextCtrl, to accept the changes and to send the EVT_AUINOTEBOOK_END_LABEL_EDIT event.

Parameters:
  • page_index – the page index in the notebook;
  • value – the new label for the tab.

OnRenameCancelled(page_index) [source]

Called by TabTextCtrl, to cancel the changes and to send the EVT_AUINOTEBOOK_END_LABEL_EDIT event.

Parameters: page_index – the page index in the notebook.

OnSize(event) [source]

Handles the wx.EVT_SIZE event for AuiNotebook.

Parameters: event – a wx.SizeEvent event to be processed.

OnTabBeginDrag(event) [source]

Handles the EVT_AUINOTEBOOK_BEGIN_DRAG event for AuiNotebook.

Parameters: event – a AuiNotebookEvent event to be processed.

OnTabBgDClick(event) [source]

Handles the EVT_AUINOTEBOOK_BG_DCLICK event for AuiNotebook.

Parameters: event – a AuiNotebookEvent event to be processed.

OnTabButton(event) [source]

Handles the EVT_AUINOTEBOOK_BUTTON event for AuiNotebook.

Parameters: event – a AuiNotebookEvent event to be processed.

OnTabCancelDrag(event) [source]

Handles the EVT_AUINOTEBOOK_CANCEL_DRAG event for AuiNotebook.

Parameters: event – a AuiNotebookEvent event to be processed.

OnTabClicked(event) [source]

Handles the EVT_AUINOTEBOOK_PAGE_CHANGING event for AuiNotebook.

Parameters: event – a AuiNotebookEvent event to be processed.

OnTabDClick(event) [source]

Handles the EVT_AUINOTEBOOK_TAB_DCLICK event for AuiNotebook.

Parameters: event – a AuiNotebookEvent event to be processed.

OnTabDragMotion(event) [source]

Handles the EVT_AUINOTEBOOK_DRAG_MOTION event for AuiNotebook.

Parameters: event – a AuiNotebookEvent event to be processed.

OnTabEndDrag(event) [source]

Handles the EVT_AUINOTEBOOK_END_DRAG event for AuiNotebook.

Parameters: event – a AuiNotebookEvent event to be processed.

OnTabMiddleDown(event) [source]

Handles the EVT_AUINOTEBOOK_TAB_MIDDLE_DOWN event for AuiNotebook.

Parameters: event – a AuiNotebookEvent event to be processed.

OnTabMiddleUp(event) [source]

Handles the EVT_AUINOTEBOOK_TAB_MIDDLE_UP event for AuiNotebook.

Parameters: event – a AuiNotebookEvent event to be processed.

OnTabRightDown(event) [source]

Handles the EVT_AUINOTEBOOK_TAB_RIGHT_DOWN event for AuiNotebook.

Parameters: event – a AuiNotebookEvent event to be processed.

OnTabRightUp(event) [source]

Handles the EVT_AUINOTEBOOK_TAB_RIGHT_UP event for AuiNotebook.

Parameters: event – a AuiNotebookEvent event to be processed.

ReDockPage(pane) [source]

Re-docks a floating AuiNotebook tab in the original position, when possible.

Parameters: pane – an instance of AuiPaneInfo.

RemoveControlFromPage(page_idx) [source]

Removes a control from a tab (not from the tab area).

Parameters: page_idx – the page index.

RemoveEmptyTabFrames() [source]

Removes all the empty tab frames.

RemovePage(page_idx) [source]

Removes a page, without deleting the window pointer.

Parameters: page_idx – the page index to be removed.

Note

RemovePage removes a tab from the multi-notebook, but does not destroy the window.

See also

DeletePage

RemoveTabAreaButton(id) [source]

Removes a button from the tab area.

Parameters: id – the button identifier. See AddTabAreaButton for a list of button identifiers.

See also

AddTabAreaButton

ReparentControl(control, dest_tabs) [source]

Reparents a control added inside a tab.

Parameters:
  • control – an instance of wx.Window;

  • dest_tabs – the destination AuiTabCtrl.

ResetTextControl() [source]

Called by TabTextCtrl when it marks itself for deletion.

SavePerspective() [source]

Saves the entire user interface layout into an encoded string, which can then be stored by the application (probably using wx.Config). When a perspective is restored using LoadPerspective, the entire user interface will return to the state it was when the perspective was saved.

SetAGWWindowStyleFlag(agwStyle) [source]

Sets the AGW-specific style of the window.

Parameters: agwStyle – the new window style. This can be a combination of the following bits:

Flag name | Description
AUI_NB_TOP | With this style, tabs are drawn along the top of the notebook
AUI_NB_LEFT | With this style, tabs are drawn along the left of the notebook. Not implemented yet.
AUI_NB_RIGHT | With this style, tabs are drawn along the right of the notebook. Not implemented yet.
AUI_NB_BOTTOM | With this style, tabs are drawn along the bottom of the notebook
AUI_NB_TAB_SPLIT | Allows the tab control to be split by dragging a tab
AUI_NB_TAB_MOVE | Allows a tab to be moved horizontally by dragging
AUI_NB_TAB_EXTERNAL_MOVE | Allows a tab to be moved to another tab control
AUI_NB_TAB_FIXED_WIDTH | With this style, all tabs have the same width
AUI_NB_SCROLL_BUTTONS | With this style, left and right scroll buttons are displayed
AUI_NB_WINDOWLIST_BUTTON | With this style, a drop-down list of windows is available
AUI_NB_CLOSE_BUTTON | With this style, a close button is available on the tab bar
AUI_NB_CLOSE_ON_ACTIVE_TAB | With this style, a close button is available on the active tab
AUI_NB_CLOSE_ON_ALL_TABS | With this style, a close button is available on all tabs
AUI_NB_MIDDLE_CLICK_CLOSE | Allows to close AuiNotebook tabs by mouse middle button click
AUI_NB_SUB_NOTEBOOK | This style is used by AuiManager to create automatic AuiNotebooks
AUI_NB_HIDE_ON_SINGLE_TAB | Hides the tab window if only one tab is present
AUI_NB_SMART_TABS | Use Smart Tabbing, like Alt + Tab on Windows
AUI_NB_USE_IMAGES_DROPDOWN | Uses images on dropdown window list menu instead of check items
AUI_NB_CLOSE_ON_TAB_LEFT | Draws the tab close button on the left instead of on the right (a la Camino browser)
AUI_NB_TAB_FLOAT | Allows the floating of single tabs. Known limitation: when the notebook is more or less full screen, tabs cannot be dragged far enough outside of the notebook to become floating pages
AUI_NB_DRAW_DND_TAB | Draws an image representation of a tab while dragging (on by default)
AUI_NB_ORDER_BY_ACCESS | Tab navigation order by last access time for the tabs
AUI_NB_NO_TAB_FOCUS | Don’t draw tab focus rectangle

Note

Please note that some styles cannot be changed after the window creation and that Refresh might need to be be called after changing the others for the change to take place immediately.

Todo

Implementation of flags AUI_NB_RIGHT and AUI_NB_LEFT.

SetArtProvider(art) [source]

Sets the art provider to be used by the notebook.

Parameters: art – an art provider.

SetCloseButton(page_idx, hasCloseButton) [source]

Sets whether a tab should display a close button or not.

Parameters:
  • page_idx – the page index;
  • hasCloseButton – True if the page displays a close button.

Note

This can only be called if AUI_NB_CLOSE_ON_ALL_TABS is specified.

SetFont(font) [source]

Sets the tab font.

Parameters: font – a wx.Font object.

Note

Overridden from wx.PyPanel.

SetImageList(imageList) [source]

Sets the image list for the AuiNotebook control.

Parameters: imageList – an instance of wx.ImageList.

SetMeasuringFont(font) [source]

Sets the font for calculating text measurements.

Parameters: font – a wx.Font object.

SetMinMaxTabWidth(minTabWidth, maxTabWidth) [source]

Sets the minimum and/or the maximum tab widths for AuiNotebook when the AUI_NB_TAB_FIXED_WIDTH style is defined.

Pass -1 to either minTabWidth or maxTabWidth to reset to the default tab width behaviour for AuiNotebook.

Parameters:
  • minTabWidth – the minimum allowed tab width, in pixels;
  • maxTabWidth – the maximum allowed tab width, in pixels.

Note

Minimum and maximum tabs widths are used only when the AUI_NB_TAB_FIXED_WIDTH style is present.

SetNavigatorIcon(bmp) [source]

Sets the icon used by the TabNavigatorWindow.

Parameters: bmp – an instance of wx.Bitmap.

SetNormalFont(font) [source]

Sets the normal font for drawing tab labels.

Parameters: font – a wx.Font object.

SetPageBitmap(page_idx, bitmap) [source]

Sets the tab bitmap for the page.

Parameters:
  • page_idx – the page index;
  • bitmap – an instance of wx.Bitmap.

SetPageImage(page, image) [source]

Sets the image index for the given page.

Parameters:
  • page – the page index;
  • image – an index into the image list which was set with SetImageList.

SetPageText(page_idx, text) [source]

Sets the tab label for the page.

Parameters:
  • page_idx – the page index;
  • text – the new tab label.

SetPageTextColour(page_idx, colour) [source]

Sets the tab text colour for the page.

Parameters:
  • page_idx – the page index;
  • colour – an instance of wx.Colour.

SetRenamable(page_idx, renamable) [source]

Sets whether a tab can be renamed via a left double-click or not.

Parameters:
  • page_idx – the page index;
  • renamable – True if the page can be renamed.

SetSashDClickUnsplit(unsplit=True) [source]

Sets whether to unsplit a splitted AuiNotebook when double-clicking on a sash.

Parameters: unsplit – True to unsplit on sash double-clicking, False otherwise.

SetSelectedFont(font) [source]

Sets the selected tab font for drawing tab labels.

Parameters: font – a wx.Font object.

SetSelection(new_page, force=False) [source]

Sets the page selection. Calling this method will generate a page change event.

Parameters:
  • new_page – the index of the new selection;
  • force – whether to force the selection or not.

SetSelectionToPage(page) [source]

Sets the selection based on the input page.

Parameters: page – an instance of AuiNotebookPage.

SetSelectionToWindow(win) [source]

Sets the selection based on the input window win.

Parameters: win – a wx.Window derived window.

SetTabCtrlHeight(height) [source]

Sets the tab height.

By default, the tab control height is calculated by measuring the text height and bitmap sizes on the tab captions.

Calling this method will override that calculation and set the tab control to the specified height parameter. A call to this method will override any call to SetUniformBitmapSize. Specifying -1 as the height will return the control to its default auto-sizing behaviour.

Parameters: height – the tab control area height.

SetUniformBitmapSize(size) [source]

Ensures that all tabs will have the same height, even if some tabs don’t have bitmaps. Passing wx.DefaultSize to this function will instruct the control to use dynamic tab height, which is the default behaviour. Under the default behaviour, when a tab with a large bitmap is added, the tab control’s height will automatically increase to accommodate the larger bitmap.

Parameters: size – an instance of wx.Size specifying the tab bitmap size.

ShowWindowMenu() [source]

Shows the window menu for the active tab control associated with this notebook, and returns True if a selection was made.

Split(page, direction) [source]

Performs a split operation programmatically.

Parameters:
  • page – indicates the page that will be split off. This page will also become the active page after the split.
  • direction – specifies where the pane should go, it should be one of the following: wx.TOP, wx.BOTTOM, wx.LEFT, or wx.RIGHT.

UnSplit() [source]

Restores original view after a tab split.

UnsplitDClick(part, sash_size, pos) [source]

Unsplit the AuiNotebook on sash double-click.

Parameters:
  • part – an UI part representing the sash;
  • sash_size – the sash size;
  • pos – the double-click mouse position.

Warning

Due to a bug on MSW, for disabled pages wx.FindWindowAtPoint returns the wrong window. See http://trac.wxwidgets.org/ticket/2942

UpdateHintWindowSize() [source]

Updates the AuiManager hint window size.

UpdateTabCtrlHeight(force=False) [source]

UpdateTabCtrlHeight() does the actual tab resizing. It’s meant to be used interally.

Parameters: force – True to force the tab art to repaint.

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • infobar
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • aui library »
  • aui.auibook »
  • AuiNotebook


AuiNotebookEvent

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • aui library »
  • aui.auibook »
  • AuiNotebookEvent

AuiNotebookEvent

A specialized command event class for events sent by AuiNotebook.

hierarchy Inheritance Diagram

Inheritance diagram for: AuiNotebookEvent

Inheritance diagram of AuiNotebookEvent

supclasses Known Superclasses

  • aui.auibook.CommandNotebookEvent

Methods Summary

__init__ | Default class constructor.
Allow | This is the opposite of Veto: it explicitly allows the event to be
GetNotifyEvent | Returns the actual wx.NotifyEvent.
IsAllowed | Returns whether the event is allowed or not.
Veto | Prevents the change announced by this event from happening.

API Class API

class AuiNotebookEvent(CommandNotebookEvent) [source]

A specialized command event class for events sent by AuiNotebook.

__init__(command_type=None, win_id=0) [source]

Default class constructor.

Parameters:
  • command_type – the event kind or an instance of wx.PyCommandEvent.
  • win_id – the window identification number.

Allow() [source]

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

GetNotifyEvent() [source]

Returns the actual wx.NotifyEvent.

IsAllowed() [source]

Returns whether the event is allowed or not.

Veto() [source]

Prevents the change announced by this event from happening.

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

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • infobar
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • aui library »
  • aui.auibook »
  • AuiNotebookEvent


AuiNotebookPage

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • aui library »
  • aui.auibook »
  • AuiNotebookPage

AuiNotebookPage

A simple class which holds information about tab captions, bitmaps and colours.

hierarchy Inheritance Diagram

Inheritance diagram for: AuiNotebookPage

Inheritance diagram of AuiNotebookPage

Methods Summary

__init__ | Default class constructor.
IsMultiline | Returns whether the tab contains multiline text.

API Class API

class AuiNotebookPage(object) [source]

A simple class which holds information about tab captions, bitmaps and colours.

__init__() [source]

Default class constructor. Used internally, do not call it in your code!

IsMultiline() [source]

Returns whether the tab contains multiline text.

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • infobar
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • aui library »
  • aui.auibook »
  • AuiNotebookPage


AuiTabContainer

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • aui library »
  • aui.auibook »
  • AuiTabContainer

AuiTabContainer

AuiTabContainer is a class which contains information about each tab. It also can render an entire tab control to a specified DC. It’s not a window class itself, because this code will be used by the AuiManager, where it is disadvantageous to have separate windows for each tab control in the case of “docked tabs”.

A derived class, AuiTabCtrl, is an actual wx.Window - derived window which can be used as a tab control in the normal sense.

hierarchy Inheritance Diagram

Inheritance diagram for: AuiTabContainer

Inheritance diagram of AuiTabContainer

subclasses Known Subclasses

  • aui.auibook.AuiTabCtrl

Methods Summary

__init__ | Default class constructor.
AddButton | Adds a button in the tab area.
AddPage | Adds a page to the tab control.
ButtonHitTest | Tests if a button was hit.
CloneButtons | Clones the tab area buttons when the AuiNotebook is being split.
DoShowHide | This function shows the active window, then hides all of the other windows
EnableTab | Enables/disables a tab in the AuiTabContainer.
GetAGWFlags | Returns the tab art flags.
GetActivePage | Returns the current selected tab or wx.NOT_FOUND if none is selected.
GetArtProvider | Returns the current art provider being used.
GetEnabled | Returns whether a tab is enabled or not.
GetIdxFromWindow | Returns the tab index based on the window wnd associated with it.
GetPage | Returns the page specified by the given index.
GetPageCount | Returns the number of pages in the AuiTabContainer.
GetPages | Returns a list of all the pages in this AuiTabContainer.
GetTabOffset | Returns the tab offset.
GetWindowFromIdx | Returns the window associated with the tab with index idx.
InsertPage | Inserts a page in the tab control in the position specified by idx.
IsTabVisible | Returns whether a tab is visible or not.
MakeTabVisible | Make the tab visible if it wasn’t already.
MinimizeTabOffset | Minimize self._tab_offset to fit as many tabs as possible in the available space.
MovePage | Moves a page in a new position specified by new_idx.
RemoveButton | Removes a button from the tab area.
RemovePage | Removes a page from the tab control.
Render | Renders the tab catalog to the specified wx.DC.
SetAGWFlags | Sets the tab art flags.
SetActivePage | Sets the AuiTabContainer active page.
SetArtProvider | Instructs AuiTabContainer to use art provider specified by parameter art
SetMeasuringFont | Sets the font for calculating text measurements.
SetNoneActive | Sets all the tabs as inactive (non-selected).
SetNormalFont | Sets the normal font for drawing tab labels.
SetSelectedFont | Sets the selected tab font for drawing tab labels.
SetTabOffset | Sets the tab offset.
SetTabRect | Sets the tab area rectangle.
TabHitTest | TabHitTest() tests if a tab was hit, passing the window pointer

API Class API

class AuiTabContainer(object) [source]

AuiTabContainer is a class which contains information about each tab. It also can render an entire tab control to a specified DC. It’s not a window class itself, because this code will be used by the AuiManager, where it is disadvantageous to have separate windows for each tab control in the case of “docked tabs”.

A derived class, AuiTabCtrl, is an actual wx.Window - derived window which can be used as a tab control in the normal sense.

__init__(auiNotebook) [source]

Default class constructor. Used internally, do not call it in your code!

Parameters: auiNotebook – the parent AuiNotebook window.

AddButton(id, location, normal_bitmap=wx.NullBitmap, disabled_bitmap=wx.NullBitmap) [source]

Adds a button in the tab area.

Parameters:
  • id – the button identifier. This can be one of the following:

    Button Identifier | Description
    AUI_BUTTON_CLOSE | Shows a close button on the tab area
    AUI_BUTTON_WINDOWLIST | Shows a window list button on the tab area
    AUI_BUTTON_LEFT | Shows a left button on the tab area
    AUI_BUTTON_RIGHT | Shows a right button on the tab area
  • location – the button location. Can be wx.LEFT or wx.RIGHT;
  • normal_bitmap – the bitmap for an enabled tab;
  • disabled_bitmap – the bitmap for a disabled tab.

AddPage(page, info) [source]

Adds a page to the tab control.

Parameters:
  • page – the window associated with this tab;
  • info – an instance of AuiNotebookPage.

ButtonHitTest(x, y) [source]

Tests if a button was hit.

Parameters:
  • x – the mouse x position;
  • y – the mouse y position.
Returns:

and instance of AuiTabContainerButton if a button was hit, None otherwise.

CloneButtons() [source]

Clones the tab area buttons when the AuiNotebook is being split.

See also

AddButton

Note

Standard buttons for AuiNotebook are not cloned, only custom ones.

DoShowHide() [source]

This function shows the active window, then hides all of the other windows (in that order).

EnableTab(idx, enable=True) [source]

Enables/disables a tab in the AuiTabContainer.

Parameters:
  • idx – the tab index;
  • enable – True to enable a tab, False to disable it.

GetAGWFlags() [source]

Returns the tab art flags.

See SetAGWFlags for a list of possible return values.

See also

SetAGWFlags

GetActivePage() [source]

Returns the current selected tab or wx.NOT_FOUND if none is selected.

GetArtProvider() [source]

Returns the current art provider being used.

GetEnabled(idx) [source]

Returns whether a tab is enabled or not.

Parameters: idx – the tab index.

GetIdxFromWindow(wnd) [source]

Returns the tab index based on the window wnd associated with it.

Parameters: wnd – an instance of wx.Window.

GetPage(idx) [source]

Returns the page specified by the given index.

Parameters: idx – the tab index.

GetPageCount() [source]

Returns the number of pages in the AuiTabContainer.

GetPages() [source]

Returns a list of all the pages in this AuiTabContainer.

GetTabOffset() [source]

Returns the tab offset.

GetWindowFromIdx(idx) [source]

Returns the window associated with the tab with index idx.

Parameters: idx – the tab index.

InsertPage(page, info, idx) [source]

Inserts a page in the tab control in the position specified by idx.

Parameters:
  • page – the window associated with this tab;
  • info – an instance of AuiNotebookPage;
  • idx – the page insertion index.

IsTabVisible(tabPage, tabOffset, dc, wnd) [source]

Returns whether a tab is visible or not.

Parameters:
  • tabPage – the tab index;
  • tabOffset – the tab offset;
  • dc – a wx.DC device context;

  • wnd – an instance of wx.Window derived window.

MakeTabVisible(tabPage, win) [source]

Make the tab visible if it wasn’t already.

Parameters:
  • tabPage – the tab index;
  • win – an instance of wx.Window derived window.

MinimizeTabOffset(dc, wnd, max_width) [source]

Minimize self._tab_offset to fit as many tabs as possible in the available space.

Parameters:
  • dc – a wx.DC device context;

  • wnd – an instance of wx.Window;

  • max_width – the maximum available width for the tabs.

MovePage(page, new_idx) [source]

Moves a page in a new position specified by new_idx.

Parameters:
  • page – the window associated with this tab;
  • new_idx – the new page position.

RemoveButton(id) [source]

Removes a button from the tab area.

Parameters: id – the button identifier. See AddButton for a list of button identifiers.

See also

AddButton

RemovePage(wnd) [source]

Removes a page from the tab control.

Parameters: wnd – an instance of wx.Window, a window associated with this tab.

Render(raw_dc, wnd) [source]

Renders the tab catalog to the specified wx.DC.

It is a virtual function and can be overridden to provide custom drawing capabilities.

Parameters:
  • raw_dc – a wx.DC device context;

  • wnd – an instance of wx.Window.

SetAGWFlags(agwFlags) [source]

Sets the tab art flags.

Parameters: agwFlags – a combination of the following values:

Flag name | Description
AUI_NB_TOP | With this style, tabs are drawn along the top of the notebook
AUI_NB_LEFT | With this style, tabs are drawn along the left of the notebook. Not implemented yet
AUI_NB_RIGHT | With this style, tabs are drawn along the right of the notebook. Not implemented yet
AUI_NB_BOTTOM | With this style, tabs are drawn along the bottom of the notebook
AUI_NB_TAB_SPLIT | Allows the tab control to be split by dragging a tab
AUI_NB_TAB_MOVE | Allows a tab to be moved horizontally by dragging
AUI_NB_TAB_EXTERNAL_MOVE | Allows a tab to be moved to another tab control
AUI_NB_TAB_FIXED_WIDTH | With this style, all tabs have the same width
AUI_NB_SCROLL_BUTTONS | With this style, left and right scroll buttons are displayed
AUI_NB_WINDOWLIST_BUTTON | With this style, a drop-down list of windows is available
AUI_NB_CLOSE_BUTTON | With this style, a close button is available on the tab bar
AUI_NB_CLOSE_ON_ACTIVE_TAB | With this style, a close button is available on the active tab
AUI_NB_CLOSE_ON_ALL_TABS | With this style, a close button is available on all tabs
AUI_NB_MIDDLE_CLICK_CLOSE | Allows to close AuiNotebook tabs by mouse middle button click
AUI_NB_SUB_NOTEBOOK | This style is used by AuiManager to create automatic AuiNotebooks
AUI_NB_HIDE_ON_SINGLE_TAB | Hides the tab window if only one tab is present
AUI_NB_SMART_TABS | Use Smart Tabbing, like Alt + Tab on Windows
AUI_NB_USE_IMAGES_DROPDOWN | Uses images on dropdown window list menu instead of check items
AUI_NB_CLOSE_ON_TAB_LEFT | Draws the tab close button on the left instead of on the right (a la Camino browser)
AUI_NB_TAB_FLOAT | Allows the floating of single tabs. Known limitation: when the notebook is more or less full screen, tabs cannot be dragged far enough outside of the notebook to become floating pages
AUI_NB_DRAW_DND_TAB | Draws an image representation of a tab while dragging (on by default)
AUI_NB_ORDER_BY_ACCESS | Tab navigation order by last access time for the tabs
AUI_NB_NO_TAB_FOCUS | Don’t draw tab focus rectangle

Todo

Implementation of flags AUI_NB_RIGHT and AUI_NB_LEFT.

SetActivePage(wndOrInt) [source]

Sets the AuiTabContainer active page.

Parameters: wndOrInt – an instance of wx.Window or an integer specifying a tab index.

SetArtProvider(art) [source]

Instructs AuiTabContainer to use art provider specified by parameter art for all drawing calls. This allows plugable look-and-feel features.

Parameters: art – an art provider.

Note

The previous art provider object, if any, will be deleted by AuiTabContainer.

SetMeasuringFont(font) [source]

Sets the font for calculating text measurements.

Parameters: font – a wx.Font object.

SetNoneActive() [source]

Sets all the tabs as inactive (non-selected).

SetNormalFont(font) [source]

Sets the normal font for drawing tab labels.

Parameters: font – a wx.Font object.

SetSelectedFont(font) [source]

Sets the selected tab font for drawing tab labels.

Parameters: font – a wx.Font object.

SetTabOffset(offset) [source]

Sets the tab offset.

Parameters: offset – the tab offset.

SetTabRect(rect) [source]

Sets the tab area rectangle.

Parameters: rect – an instance of wx.Rect, specifying the available area for AuiTabContainer.

TabHitTest(x, y) [source]

TabHitTest() tests if a tab was hit, passing the window pointer back if that condition was fulfilled.

Parameters:
  • x – the mouse x position;
  • y – the mouse y position.

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • infobar
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • aui library »
  • aui.auibook »
  • AuiTabContainer


AuiTabContainerButton

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • aui library »
  • aui.auibook »
  • AuiTabContainerButton

AuiTabContainerButton

A simple class which holds information about tab buttons and their state.

hierarchy Inheritance Diagram

Inheritance diagram for: AuiTabContainerButton

Inheritance diagram of AuiTabContainerButton

Methods Summary

__init__ Default class constructor.

API Class API

class AuiTabContainerButton(object) [source]

A simple class which holds information about tab buttons and their state.

__init__() [source]

Default class constructor. Used internally, do not call it in your code!

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • infobar
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • aui library »
  • aui.auibook »
  • AuiTabContainerButton


AuiTabCtrl

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • aui library »
  • aui.auibook »
  • AuiTabCtrl

AuiTabCtrl

This is an actual wx.Window - derived window which can be used as a tab control in the normal sense.

hierarchy Inheritance Diagram

Inheritance diagram for: AuiTabCtrl

Inheritance diagram of AuiTabCtrl

supclasses Known Superclasses

  • aui.auibook.AuiTabContainer

Methods Summary

__init__ | Default class constructor.
DoGetBestSize | Gets the size which best suits the window: for a control, it would be the
GetDefaultBorder | Returns the default border style for AuiTabCtrl.
IsDragging | Returns whether the user is dragging a tab with the mouse or not.
OnButton | Handles the EVT_AUINOTEBOOK_BUTTON event for AuiTabCtrl.
OnCaptureLost | Handles the wx.EVT_MOUSE_CAPTURE_LOST event for AuiTabCtrl.
OnEraseBackground | Handles the wx.EVT_ERASE_BACKGROUND event for AuiTabCtrl.
OnKeyDown | Handles the wx.EVT_KEY_DOWN event for AuiTabCtrl.
OnKeyDown2 | Deprecated.
OnKillFocus | Handles the wx.EVT_KILL_FOCUS event for AuiTabCtrl.
OnLeaveWindow | Handles the wx.EVT_LEAVE_WINDOW event for AuiTabCtrl.
OnLeftDClick | Handles the wx.EVT_LEFT_DCLICK event for AuiTabCtrl.
OnLeftDown | Handles the wx.EVT_LEFT_DOWN event for AuiTabCtrl.
OnLeftUp | Handles the wx.EVT_LEFT_UP event for AuiTabCtrl.
OnMiddleDown | Handles the wx.EVT_MIDDLE_DOWN event for AuiTabCtrl.
OnMiddleUp | Handles the wx.EVT_MIDDLE_UP event for AuiTabCtrl.
OnMotion | Handles the wx.EVT_MOTION event for AuiTabCtrl.
OnPaint | Handles the wx.EVT_PAINT event for AuiTabCtrl.
OnRightDown | Handles the wx.EVT_RIGHT_DOWN event for AuiTabCtrl.
OnRightUp | Handles the wx.EVT_RIGHT_UP event for AuiTabCtrl.
OnSetFocus | Handles the wx.EVT_SET_FOCUS event for AuiTabCtrl.
OnSize | Handles the wx.EVT_SIZE event for AuiTabCtrl.

API Class API

class AuiTabCtrl(wx.PyControl, AuiTabContainer) [source]

This is an actual wx.Window - derived window which can be used as a tab control in the normal sense.

__init__(parent, id=wx.ID_ANY, pos=wx.DefaultPosition, size=wx.DefaultSize, style=wx.NO_BORDER|wx.WANTS_CHARS|wx.TAB_TRAVERSAL) [source]

Default class constructor. Used internally, do not call it in your code!

Parameters:
  • parent – the AuiTabCtrl parent;
  • id – an identifier for the control: a value of -1 is taken to mean a default;
  • pos – the control position. A value of (-1, -1) indicates a default position, chosen by either the windowing system or wxPython, depending on platform;
  • size – the control size. A value of (-1, -1) indicates a default size, chosen by either the windowing system or wxPython, depending on platform;
  • style – the window style.

DoGetBestSize() [source]

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

Note

Overridden from wx.PyControl.

GetDefaultBorder() [source]

Returns the default border style for AuiTabCtrl.

IsDragging() [source]

Returns whether the user is dragging a tab with the mouse or not.

OnButton(event) [source]

Handles the EVT_AUINOTEBOOK_BUTTON event for AuiTabCtrl.

Parameters: event – a AuiNotebookEvent event to be processed.

OnCaptureLost(event) [source]

Handles the wx.EVT_MOUSE_CAPTURE_LOST event for AuiTabCtrl.

Parameters: event – a wx.MouseCaptureLostEvent event to be processed.

OnEraseBackground(event) [source]

Handles the wx.EVT_ERASE_BACKGROUND event for AuiTabCtrl.

Parameters: event – a wx.EraseEvent event to be processed.

Note

This is intentionally empty, to reduce flicker.

OnKeyDown(event) [source]

Handles the wx.EVT_KEY_DOWN event for AuiTabCtrl.

Parameters: event – a wx.KeyEvent event to be processed.

OnKeyDown2(event) [source]

Deprecated.

Handles the wx.EVT_KEY_DOWN event for AuiTabCtrl.

Parameters: event – a wx.KeyEvent event to be processed.

Warning

This method implementation is now deprecated. Refer to OnKeyDown for the correct one.

OnKillFocus(event) [source]

Handles the wx.EVT_KILL_FOCUS event for AuiTabCtrl.

Parameters: event – a wx.FocusEvent event to be processed.

OnLeaveWindow(event) [source]

Handles the wx.EVT_LEAVE_WINDOW event for AuiTabCtrl.

Parameters: event – a wx.MouseEvent event to be processed.

OnLeftDClick(event) [source]

Handles the wx.EVT_LEFT_DCLICK event for AuiTabCtrl.

Parameters: event – a wx.MouseEvent event to be processed.

OnLeftDown(event) [source]

Handles the wx.EVT_LEFT_DOWN event for AuiTabCtrl.

Parameters: event – a wx.MouseEvent event to be processed.

OnLeftUp(event) [source]

Handles the wx.EVT_LEFT_UP event for AuiTabCtrl.

Parameters: event – a wx.MouseEvent event to be processed.

OnMiddleDown(event) [source]

Handles the wx.EVT_MIDDLE_DOWN event for AuiTabCtrl.

Parameters: event – a wx.MouseEvent event to be processed.

OnMiddleUp(event) [source]

Handles the wx.EVT_MIDDLE_UP event for AuiTabCtrl.

Parameters: event – a wx.MouseEvent event to be processed.

OnMotion(event) [source]

Handles the wx.EVT_MOTION event for AuiTabCtrl.

Parameters: event – a wx.MouseEvent event to be processed.

OnPaint(event) [source]

Handles the wx.EVT_PAINT event for AuiTabCtrl.

Parameters: event – a wx.PaintEvent event to be processed.

OnRightDown(event) [source]

Handles the wx.EVT_RIGHT_DOWN event for AuiTabCtrl.

Parameters: event – a wx.MouseEvent event to be processed.

OnRightUp(event) [source]

Handles the wx.EVT_RIGHT_UP event for AuiTabCtrl.

Parameters: event – a wx.MouseEvent event to be processed.

OnSetFocus(event) [source]

Handles the wx.EVT_SET_FOCUS event for AuiTabCtrl.

Parameters: event – a wx.FocusEvent event to be processed.

OnSize(event) [source]

Handles the wx.EVT_SIZE event for AuiTabCtrl.

Parameters: event – a wx.SizeEvent event to be processed.

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • infobar
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • aui library »
  • aui.auibook »
  • AuiTabCtrl


CommandNotebookEvent

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • aui library »
  • aui.auibook »
  • CommandNotebookEvent

CommandNotebookEvent

A specialized command event class for events sent by AuiNotebook .

hierarchy Inheritance Diagram

Inheritance diagram for: CommandNotebookEvent

Inheritance diagram of CommandNotebookEvent

subclasses Known Subclasses

  • aui.auibook.AuiNotebookEvent

Methods Summary

__init__ | Default class constructor.
GetDispatched | Returns whether the event was dispatched (used for automatic AuiNotebook ).
GetDragSource | Returns the drag and drop source.
GetLabel | Returns the label-itemtext (for EVT_AUINOTEBOOK_BEGIN | END_LABEL_EDIT only).
GetOldSelection | Returns the page that was selected before the change, or -1 if none was
GetSelection | Returns the currently selected page, or -1 if none was selected.
IsEditCancelled | Returns the edit cancel flag (for EVT_AUINOTEBOOK_BEGIN | END_LABEL_EDIT only).
SetDispatched | Sets the event as dispatched (used for automatic AuiNotebook ).
SetDragSource | Sets the drag and drop source.
SetEditCanceled | Sets the edit cancel flag (for EVT_AUINOTEBOOK_BEGIN | END_LABEL_EDIT only).
SetLabel | Sets the label.
SetOldSelection | Sets the id of the page selected before the change.
SetSelection | Sets the selection member variable.

API Class API

class CommandNotebookEvent(wx.PyCommandEvent) [source]

A specialized command event class for events sent by AuiNotebook .

__init__(command_type=None, win_id=0) [source]

Default class constructor.

Parameters:
  • command_type – the event kind or an instance of wx.PyCommandEvent.
  • win_id – the window identification number.

GetDispatched() [source]

Returns whether the event was dispatched (used for automatic AuiNotebook ).

GetDragSource() [source]

Returns the drag and drop source.

GetLabel() [source]

Returns the label-itemtext (for EVT_AUINOTEBOOK_BEGIN | END_LABEL_EDIT only).

GetOldSelection() [source]

Returns the page that was selected before the change, or -1 if none was selected.

GetSelection() [source]

Returns the currently selected page, or -1 if none was selected.

IsEditCancelled() [source]

Returns the edit cancel flag (for EVT_AUINOTEBOOK_BEGIN | END_LABEL_EDIT only).

Page

Selection

SetDispatched(b) [source]

Sets the event as dispatched (used for automatic AuiNotebook ).

Parameters: b – whether the event was dispatched or not.

SetDragSource(s) [source]

Sets the drag and drop source.

Parameters: s – the drag source.

SetEditCanceled(editCancelled) [source]

Sets the edit cancel flag (for EVT_AUINOTEBOOK_BEGIN | END_LABEL_EDIT only).

Parameters: editCancelled – whether the editing action has been cancelled or not.

SetLabel(label) [source]

Sets the label. Useful only for EVT_AUINOTEBOOK_END_LABEL_EDIT.

Parameters: label – the new label.

SetOldSelection(s) [source]

Sets the id of the page selected before the change.

Parameters: s – the old selection.

SetSelection(s) [source]

Sets the selection member variable.

Parameters: s – the new selection.

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • infobar
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • aui library »
  • aui.auibook »
  • CommandNotebookEvent


TabFrame

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • aui library »
  • aui.auibook »
  • TabFrame

TabFrame

TabFrame is an interesting case. It’s important that all child pages of the multi-notebook control are all actually children of that control (and not grandchildren). TabFrame facilitates this. There is one instance of TabFrame for each tab control inside the multi-notebook.

It’s important to know that TabFrame is not a real window, but it merely used to capture the dimensions/positioning of the internal tab control and it’s managed page windows.

hierarchy Inheritance Diagram

Inheritance diagram for: TabFrame

Inheritance diagram of TabFrame

Methods Summary

__init__ | Default class constructor.
DoGetClientSize | Returns the window client size.
DoGetSize | Returns the window size.
DoSetSize | Sets the position and size of the window in pixels.
DoSizing | Does the actual sizing of the tab control.
SetTabCtrlHeight | Sets the tab control height.
Show | Shows/hides the window.
Update | Calling this method immediately repaints the invalidated area of the window and all of its children recursively while this would usually only happen when the flow of control returns to the event loop.

API Class API

class TabFrame(wx.PyWindow) [source]

TabFrame is an interesting case. It’s important that all child pages of the multi-notebook control are all actually children of that control (and not grandchildren). TabFrame facilitates this. There is one instance of TabFrame for each tab control inside the multi-notebook.

It’s important to know that TabFrame is not a real window, but it merely used to capture the dimensions/positioning of the internal tab control and it’s managed page windows.

__init__(parent) [source]

Default class constructor. Used internally, do not call it in your code!

DoGetClientSize() [source]

Returns the window client size.

Note

Overridden from wx.PyControl.

DoGetSize() [source]

Returns the window size.

Note

Overridden from wx.PyControl.

DoSetSize(x, y, width, height, flags=wx.SIZE_AUTO) [source]

Sets the position and size of the window in pixels. The flags parameter indicates the interpretation of the other params if they are equal to -1.

Parameters:
  • x – the window x position;
  • y – the window y position;
  • width – the window width;
  • height – the window height;
  • flags – may have one of this bit set:

    Size Flags | Description
    wx.SIZE_AUTO | A -1 indicates that a class-specific default should be used.
    wx.SIZE_AUTO_WIDTH | A -1 indicates that a class-specific default should be used for the width.
    wx.SIZE_AUTO_HEIGHT | A -1 indicates that a class-specific default should be used for the height.
    wx.SIZE_USE_EXISTING | Existing dimensions should be used if -1 values are supplied.
    wx.SIZE_ALLOW_MINUS_ONE | Allow dimensions of -1 and less to be interpreted as real dimensions, not default values.
    wx.SIZE_FORCE | Normally, if the position and the size of the window are already the same as the parameters of this function, nothing is done. but with this flag a window resize may be forced even in this case (supported in wx 2.6.2 and later and only implemented for MSW and ignored elsewhere currently)

Note

Overridden from wx.PyControl.

DoSizing() [source]

Does the actual sizing of the tab control.

SetTabCtrlHeight(h) [source]

Sets the tab control height.

Parameters: h – the tab area height.

Show(show=True) [source]

Shows/hides the window.

Parameters: show – True to show the window, False otherwise.

Note

Overridden from wx.PyControl, this method always returns False as TabFrame should never be phisically shown on screen.

Update() [source]

Calling this method immediately repaints the invalidated area of the window and all of its children recursively while this would usually only happen when the flow of control returns to the event loop.

Note

Notice that this function doesn’t invalidate any area of the window so nothing happens if nothing has been invalidated (i.e. marked as requiring a redraw). Use Refresh first if you want to immediately redraw the window unconditionally.

Note

Overridden from wx.PyControl.

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • infobar
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • aui library »
  • aui.auibook »
  • TabFrame


TabNavigatorProps

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • aui library »
  • aui.auibook »
  • TabNavigatorProps

TabNavigatorProps

Data storage class for managing and providing access to TabNavigatorWindow. properties.

hierarchy Inheritance Diagram

Inheritance diagram for: TabNavigatorProps

Inheritance diagram of TabNavigatorProps

Methods Summary

__init__ Default class constructor.

API Class API

class TabNavigatorProps(object) [source]

Data storage class for managing and providing access to TabNavigatorWindow. properties.

__init__() [source]

Default class constructor.

Font

Sets/Gets the font for the TabNavigatorWindow, an instance of wx.Font.

Icon

Sets/Gets the icon for the TabNavigatorWindow, an instance of wx.Bitmap.

MinSize

Sets/Gets the minimum size for the TabNavigatorWindow, an instance of wx.Size.

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • infobar
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • aui library »
  • aui.auibook »
  • TabNavigatorProps


TabNavigatorWindow

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • aui library »
  • aui.auibook »
  • TabNavigatorWindow

TabNavigatorWindow

This class is used to create a modal dialog that enables “Smart Tabbing”, similar to what you would get by hitting Alt + Tab on Windows.

hierarchy Inheritance Diagram

Inheritance diagram for: TabNavigatorWindow

Inheritance diagram of TabNavigatorWindow

Methods Summary

__init__ | Default class constructor.
CloseDialog | Closes the TabNavigatorWindow dialog, setting selection in AuiNotebook.
GetSelectedPage | Gets the page index that was selected when the dialog was closed.
OnItemSelected | Handles the wx.EVT_LISTBOX_DCLICK event for the wx.ListBox inside TabNavigatorWindow.
OnKeyUp | Handles the wx.EVT_KEY_UP for the TabNavigatorWindow.
OnNavigationKey | Handles the wx.EVT_NAVIGATION_KEY for the TabNavigatorWindow.
OnPanelEraseBg | Handles the wx.EVT_ERASE_BACKGROUND event for TabNavigatorWindow top panel.
OnPanelPaint | Handles the wx.EVT_PAINT event for TabNavigatorWindow top panel.
PopulateListControl | Populates the TabNavigatorWindow listbox with a list of tabs.

API Class API

class TabNavigatorWindow(wx.Dialog) [source]

This class is used to create a modal dialog that enables “Smart Tabbing”, similar to what you would get by hitting Alt + Tab on Windows.

__init__(parent, props) [source]

Default class constructor. Used internally.

Parameters:
  • parent – the TabNavigatorWindow parent;
  • props – the TabNavigatorProps object.

CloseDialog() [source]

Closes the TabNavigatorWindow dialog, setting selection in AuiNotebook.

GetSelectedPage() [source]

Gets the page index that was selected when the dialog was closed.

OnItemSelected(event) [source]

Handles the wx.EVT_LISTBOX_DCLICK event for the wx.ListBox inside TabNavigatorWindow.

Parameters: event – a wx.ListEvent event to be processed.

OnKeyUp(event) [source]

Handles the wx.EVT_KEY_UP for the TabNavigatorWindow.

Parameters: event – a wx.KeyEvent event to be processed.

OnNavigationKey(event) [source]

Handles the wx.EVT_NAVIGATION_KEY for the TabNavigatorWindow.

Parameters: event – a wx.NavigationKeyEvent event to be processed.

OnPanelEraseBg(event) [source]

Handles the wx.EVT_ERASE_BACKGROUND event for TabNavigatorWindow top panel.

Parameters: event – a wx.EraseEvent event to be processed.

Note

This is intentionally empty, to reduce flicker.

OnPanelPaint(event) [source]

Handles the wx.EVT_PAINT event for TabNavigatorWindow top panel.

Parameters: event – a wx.PaintEvent event to be processed.

PopulateListControl(book) [source]

Populates the TabNavigatorWindow listbox with a list of tabs.

Parameters: book – the actual AuiNotebook.

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • infobar
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • aui library »
  • aui.auibook »
  • TabNavigatorWindow


TabTextCtrl

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • aui library »
  • aui.auibook »
  • TabTextCtrl

TabTextCtrl

Control used for in-place edit.

hierarchy Inheritance Diagram

Inheritance diagram for: TabTextCtrl

Inheritance diagram of TabTextCtrl

Methods Summary

__init__ | Default class constructor.
AcceptChanges | Accepts/refuses the changes made by the user.
Finish | Finish editing.
OnChar | Handles the wx.EVT_CHAR event for TabTextCtrl.
OnKeyUp | Handles the wx.EVT_KEY_UP event for TabTextCtrl.
OnKillFocus | Handles the wx.EVT_KILL_FOCUS event for TabTextCtrl.
StopEditing | Suddenly stops the editing.
item | Returns the item currently edited.

API Class API

class TabTextCtrl(ExpandoTextCtrl) [source]

Control used for in-place edit.

__init__(owner, tab, page_index) [source]

Default class constructor. For internal use: do not call it in your code!

Parameters:
  • owner – the AuiTabCtrl owning the tab;
  • tab – the actual AuiNotebookPage tab;
  • page_index – the AuiNotebook page index for the tab.

AcceptChanges() [source]

Accepts/refuses the changes made by the user.

Finish() [source]

Finish editing.

OnChar(event) [source]

Handles the wx.EVT_CHAR event for TabTextCtrl.

Parameters: event – a wx.KeyEvent event to be processed.

OnKeyUp(event) [source]

Handles the wx.EVT_KEY_UP event for TabTextCtrl.

Parameters: event – a wx.KeyEvent event to be processed.

OnKillFocus(event) [source]

Handles the wx.EVT_KILL_FOCUS event for TabTextCtrl.

Parameters: event – a wx.FocusEvent event to be processed.

StopEditing() [source]

Suddenly stops the editing.

item() [source]

Returns the item currently edited.

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • infobar
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • aui library »
  • aui.auibook »
  • TabTextCtrl


aui.auibook

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • aui library »
  • aui.auibook

aui.auibook

auibook contains a notebook control which implements many features common in applications with dockable panes. Specifically, AuiNotebook implements functionality which allows the user to rearrange tab order via drag-and-drop, split the tab window into many different splitter configurations, and toggle through different themes to customize the control’s look and feel.

An effort has been made to try to maintain an API as similar to that of wx.Notebook.

The default theme that is used is AuiDefaultTabArt, which provides a modern, glossy look and feel. The theme can be changed by calling SetArtProvider.

Module author: Andrea Gavana <andrea.gavana@gmail.com>

hierarchy Inheritance Diagram

Inheritance diagram for module: aui.auibook

SVN Revisions

A graphical representation of the SVN commits in the last year.

Click on any date in the picture to jump to that particular revision page, containing information about committers, log messages and SVN diffs.

Revision Graph For auibook

2to3 Python 3 Issues (via 2to3)

No issues have been detected by 2to3.py.

Class Summary

  • AuiNotebook
  • AuiNotebookEvent
  • AuiNotebookPage
  • AuiTabContainer
  • AuiTabContainerButton
  • AuiTabCtrl
  • CommandNotebookEvent
  • TabFrame
  • TabNavigatorProps
  • TabNavigatorWindow
  • TabTextCtrl

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • infobar
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • aui library »
  • aui.auibook


AuiDefaultDockArt

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • aui library »
  • aui.dockart »
  • AuiDefaultDockArt

AuiDefaultDockArt

Dock art provider code - a dock provider provides all drawing functionality to the AUI dock manager. This allows the dock manager to have a plugable look-and-feel.

By default, a AuiManager uses an instance of this class called AuiDefaultDockArt which provides bitmap art and a colour scheme that is adapted to the major platforms’ look. You can either derive from that class to alter its behaviour or write a completely new dock art class.

Call SetArtProvider to make use this new dock art.

Metric Ordinals

These are the possible pane dock art settings for AuiManager:

Metric Ordinal Constant | Description
AUI_DOCKART_SASH_SIZE | Customizes the sash size
AUI_DOCKART_CAPTION_SIZE | Customizes the caption size
AUI_DOCKART_GRIPPER_SIZE | Customizes the gripper size
AUI_DOCKART_PANE_BORDER_SIZE | Customizes the pane border size
AUI_DOCKART_PANE_BUTTON_SIZE | Customizes the pane button size
AUI_DOCKART_BACKGROUND_COLOUR | Customizes the background colour
AUI_DOCKART_BACKGROUND_GRADIENT_COLOUR | Customizes the background gradient colour
AUI_DOCKART_SASH_COLOUR | Customizes the sash colour
AUI_DOCKART_ACTIVE_CAPTION_COLOUR | Customizes the active caption colour
AUI_DOCKART_ACTIVE_CAPTION_GRADIENT_COLOUR | Customizes the active caption gradient colour
AUI_DOCKART_INACTIVE_CAPTION_COLOUR | Customizes the inactive caption colour
AUI_DOCKART_INACTIVE_CAPTION_GRADIENT_COLOUR | Customizes the inactive gradient caption colour
AUI_DOCKART_ACTIVE_CAPTION_TEXT_COLOUR | Customizes the active caption text colour
AUI_DOCKART_INACTIVE_CAPTION_TEXT_COLOUR | Customizes the inactive caption text colour
AUI_DOCKART_BORDER_COLOUR | Customizes the border colour
AUI_DOCKART_GRIPPER_COLOUR | Customizes the gripper colour
AUI_DOCKART_CAPTION_FONT | Customizes the caption font
AUI_DOCKART_GRADIENT_TYPE | Customizes the gradient type (no gradient, vertical or horizontal)
AUI_DOCKART_DRAW_SASH_GRIP | Draw a sash grip on the sash

Gradient Types

These are the possible gradient dock art settings for AuiManager:

Gradient Constant | Description
AUI_GRADIENT_NONE | No gradient on the captions
AUI_GRADIENT_VERTICAL | Vertical gradient on the captions
AUI_GRADIENT_HORIZONTAL | Horizontal gradient on the captions

Button States

These are the possible pane button / AuiNotebook button / AuiToolBar button states:

Button State Constant | Description
AUI_BUTTON_STATE_NORMAL | Normal button state
AUI_BUTTON_STATE_HOVER | Hovered button state
AUI_BUTTON_STATE_PRESSED | Pressed button state
AUI_BUTTON_STATE_DISABLED | Disabled button state
AUI_BUTTON_STATE_HIDDEN | Hidden button state
AUI_BUTTON_STATE_CHECKED | Checked button state

Button Identifiers

These are the possible pane button / AuiNotebook button / AuiToolBar button identifiers:

Button Identifier | Description
AUI_BUTTON_CLOSE | Shows a close button on the pane
AUI_BUTTON_MAXIMIZE_RESTORE | Shows a maximize/restore button on the pane
AUI_BUTTON_MINIMIZE | Shows a minimize button on the pane
AUI_BUTTON_PIN | Shows a pin button on the pane
AUI_BUTTON_OPTIONS | Shows an option button on the pane (not implemented)
AUI_BUTTON_WINDOWLIST | Shows a window list button on the pane (for AuiNotebook)
AUI_BUTTON_LEFT | Shows a left button on the pane (for AuiNotebook)
AUI_BUTTON_RIGHT | Shows a right button on the pane (for AuiNotebook)
AUI_BUTTON_UP | Shows an up button on the pane (not implemented)
AUI_BUTTON_DOWN | Shows a down button on the pane (not implemented)
AUI_BUTTON_CUSTOM1 | Shows a custom button on the pane (not implemented)
AUI_BUTTON_CUSTOM2 | Shows a custom button on the pane (not implemented)
AUI_BUTTON_CUSTOM3 | Shows a custom button on the pane (not implemented)

hierarchy Inheritance Diagram

Inheritance diagram for: AuiDefaultDockArt

Inheritance diagram of AuiDefaultDockArt

subclasses Known Subclasses

  • aui.dockart.ModernDockArt

Methods Summary

__init__ | Default class constructor.
DrawBackground | Draws a background.
DrawBorder | Draws the pane border.
DrawCaption | Draws the text in the pane caption.
DrawCaptionBackground | Draws the text caption background in the pane.
DrawGripper | Draws a gripper on the pane.
DrawIcon | Draws the icon in the pane caption area.
DrawPaneButton | Draws a pane button in the pane caption area.
DrawSash | Draws a sash between two windows.
DrawSashGripper | Draws a sash gripper on a sash between two windows.
GetColor | Gets the colour of a certain setting.
GetColour | Gets the colour of a certain setting.
GetFont | Gets a font setting.
GetMetric | Gets the value of a certain setting.
Init | Initializes the dock art.
RequestUserAttention | Requests the user attention by intermittently highlighting the pane caption.
SetColor | Sets the colour of a certain setting.
SetColour | Sets the colour of a certain setting.
SetCustomPaneBitmap | Sets a custom button bitmap for the pane button.
SetDefaultColours | Sets the default colours, which are calculated from the given base colour.
SetDefaultPaneBitmaps | Assigns the default pane bitmaps.
SetFont | Sets a font setting.
SetMetric | Sets the value of a certain setting using new_val

API Class API

class AuiDefaultDockArt(object) [source]

Dock art provider code - a dock provider provides all drawing functionality to the AUI dock manager. This allows the dock manager to have a plugable look-and-feel.

By default, a AuiManager uses an instance of this class called AuiDefaultDockArt which provides bitmap art and a colour scheme that is adapted to the major platforms’ look. You can either derive from that class to alter its behaviour or write a completely new dock art class.

Call AuiManager.SetArtProvider() to make use this new dock art.

Metric Ordinals

These are the possible pane dock art settings for AuiManager:

Metric Ordinal Constant | Description
AUI_DOCKART_SASH_SIZE | Customizes the sash size
AUI_DOCKART_CAPTION_SIZE | Customizes the caption size
AUI_DOCKART_GRIPPER_SIZE | Customizes the gripper size
AUI_DOCKART_PANE_BORDER_SIZE | Customizes the pane border size
AUI_DOCKART_PANE_BUTTON_SIZE | Customizes the pane button size
AUI_DOCKART_BACKGROUND_COLOUR | Customizes the background colour
AUI_DOCKART_BACKGROUND_GRADIENT_COLOUR | Customizes the background gradient colour
AUI_DOCKART_SASH_COLOUR | Customizes the sash colour
AUI_DOCKART_ACTIVE_CAPTION_COLOUR | Customizes the active caption colour
AUI_DOCKART_ACTIVE_CAPTION_GRADIENT_COLOUR | Customizes the active caption gradient colour
AUI_DOCKART_INACTIVE_CAPTION_COLOUR | Customizes the inactive caption colour
AUI_DOCKART_INACTIVE_CAPTION_GRADIENT_COLOUR | Customizes the inactive gradient caption colour
AUI_DOCKART_ACTIVE_CAPTION_TEXT_COLOUR | Customizes the active caption text colour
AUI_DOCKART_INACTIVE_CAPTION_TEXT_COLOUR | Customizes the inactive caption text colour
AUI_DOCKART_BORDER_COLOUR | Customizes the border colour
AUI_DOCKART_GRIPPER_COLOUR | Customizes the gripper colour
AUI_DOCKART_CAPTION_FONT | Customizes the caption font
AUI_DOCKART_GRADIENT_TYPE | Customizes the gradient type (no gradient, vertical or horizontal)
AUI_DOCKART_DRAW_SASH_GRIP | Draw a sash grip on the sash

Gradient Types

These are the possible gradient dock art settings for AuiManager:

Gradient Constant | Description
AUI_GRADIENT_NONE | No gradient on the captions
AUI_GRADIENT_VERTICAL | Vertical gradient on the captions
AUI_GRADIENT_HORIZONTAL | Horizontal gradient on the captions

Button States

These are the possible pane button / AuiNotebook button / AuiToolBar button states:

Button State Constant | Description
AUI_BUTTON_STATE_NORMAL | Normal button state
AUI_BUTTON_STATE_HOVER | Hovered button state
AUI_BUTTON_STATE_PRESSED | Pressed button state
AUI_BUTTON_STATE_DISABLED | Disabled button state
AUI_BUTTON_STATE_HIDDEN | Hidden button state
AUI_BUTTON_STATE_CHECKED | Checked button state

Button Identifiers

These are the possible pane button / AuiNotebook button / AuiToolBar button identifiers:

Button Identifier | Description
AUI_BUTTON_CLOSE | Shows a close button on the pane
AUI_BUTTON_MAXIMIZE_RESTORE | Shows a maximize/restore button on the pane
AUI_BUTTON_MINIMIZE | Shows a minimize button on the pane
AUI_BUTTON_PIN | Shows a pin button on the pane
AUI_BUTTON_OPTIONS | Shows an option button on the pane (not implemented)
AUI_BUTTON_WINDOWLIST | Shows a window list button on the pane (for AuiNotebook)
AUI_BUTTON_LEFT | Shows a left button on the pane (for AuiNotebook)
AUI_BUTTON_RIGHT | Shows a right button on the pane (for AuiNotebook)
AUI_BUTTON_UP | Shows an up button on the pane (not implemented)
AUI_BUTTON_DOWN | Shows a down button on the pane (not implemented)
AUI_BUTTON_CUSTOM1 | Shows a custom button on the pane (not implemented)
AUI_BUTTON_CUSTOM2 | Shows a custom button on the pane (not implemented)
AUI_BUTTON_CUSTOM3 | Shows a custom button on the pane (not implemented)

__init__() [source]

Default class constructor.

DrawBackground(dc, window, orient, rect) [source]

Draws a background.

Parameters:
  • dc – a wx.DC device context;
  • window – an instance of wx.Window;
  • orient – the gradient (if any) orientation;
  • rect – the background rectangle.

DrawBorder(dc, window, rect, pane) [source]

Draws the pane border.

Parameters:
  • dc – a wx.DC device context;

  • window – an instance of wx.Window;

  • rect – the border rectangle;
  • pane – the pane for which the border is drawn.

DrawCaption(dc, window, text, rect, pane) [source]

Draws the text in the pane caption.

Parameters:
  • dc – a wx.DC device context;

  • window – an instance of wx.Window;

  • text – the text to be displayed;
  • rect – the pane caption rectangle;
  • pane – the pane for which the text is drawn.

DrawCaptionBackground(dc, rect, pane) [source]

Draws the text caption background in the pane.

Parameters:
  • dc – a wx.DC device context;

  • rect – the text caption rectangle;
  • pane – the pane for which the text background is drawn.

DrawGripper(dc, window, rect, pane) [source]

Draws a gripper on the pane.

Parameters:
  • dc – a wx.DC device context;

  • window – an instance of wx.Window;

  • rect – the pane caption rectangle;
  • pane – the pane for which the gripper is drawn.

DrawIcon(dc, rect, pane) [source]

Draws the icon in the pane caption area.

Parameters:
  • dc – a wx.DC device context;

  • rect – the pane caption rectangle;
  • pane – the pane for which the icon is drawn.

DrawPaneButton(dc, window, button, button_state, _rect, pane) [source]

Draws a pane button in the pane caption area.

Parameters:
  • dc – a wx.DC device context;

  • window – an instance of wx.Window;

  • button – the button to be drawn;
  • button_state – the pane button state;
  • _rect – the pane caption rectangle;
  • pane – the pane for which the button is drawn.

DrawSash(dc, window, orient, rect) [source]

Draws a sash between two windows.

Parameters:
  • dc – a wx.DC device context;

  • window – an instance of wx.Window;

  • orient – the sash orientation;
  • rect – the sash rectangle.

DrawSashGripper(dc, orient, rect) [source]

Draws a sash gripper on a sash between two windows.

Parameters:
  • dc – a wx.DC device context;

  • orient – the sash orientation;
  • rect – the sash rectangle.

GetColor(id) [source]

Gets the colour of a certain setting.

Parameters: id – can be one of the colour values in Metric Ordinals.

GetColour(id)

Gets the colour of a certain setting.

Parameters: id – can be one of the colour values in Metric Ordinals.

GetFont(id) [source]

Gets a font setting.

Parameters: id – must be AUI_DOCKART_CAPTION_FONT, otherwise wx.NullFont is returned.

GetMetric(id) [source]

Gets the value of a certain setting.

Parameters: id – can be one of the size values in Metric Ordinals.

Init() [source]

Initializes the dock art.

RequestUserAttention(dc, window, text, rect, pane) [source]

Requests the user attention by intermittently highlighting the pane caption.

Parameters:
  • dc – a wx.DC device context;

  • window – an instance of wx.Window;

  • text – the text to be displayed;
  • rect – the pane caption rectangle;
  • pane – the pane for which the text is drawn.

SetColor(id, colour) [source]

Sets the colour of a certain setting.

Parameters:
  • id – can be one of the colour values in Metric Ordinals;
  • colour – the new value of the setting.

SetColour(id, colour)

Sets the colour of a certain setting.

Parameters:
  • id – can be one of the colour values in Metric Ordinals;
  • colour – the new value of the setting.

SetCustomPaneBitmap(bmp, button, active, maximize=False) [source]

Sets a custom button bitmap for the pane button.

Parameters:
  • bmp – the actual bitmap to set;
  • button – the button identifier;
  • active – whether it is the bitmap for the active button or not;
  • maximize – used to distinguish between the maximize and restore bitmaps.

SetDefaultColours(base_colour=None) [source]

Sets the default colours, which are calculated from the given base colour.

Parameters: base_colour – an instance of wx.Colour. If defaulted to None, a colour is generated accordingly to the platform and theme.

SetDefaultPaneBitmaps(isMac) [source]

Assigns the default pane bitmaps.

Parameters: isMac – whether we are on wxMAC or not.

SetFont(id, font) [source]

Sets a font setting.

Parameters:
  • id – must be AUI_DOCKART_CAPTION_FONT;
  • font – an instance of wx.Font.

SetMetric(id, new_val) [source]

Sets the value of a certain setting using new_val

Parameters:
  • id – can be one of the size values in Metric Ordinals;
  • new_val – the new value of the setting.

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • infobar
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • aui library »
  • aui.dockart »
  • AuiDefaultDockArt


ModernDockArt

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • aui library »
  • aui.dockart »
  • ModernDockArt

ModernDockArt

ModernDockArt is a custom AuiDockArt class, that implements a look similar to Firefox and other recents applications.

Is uses the winxptheme module and XP themes whenever possible, so it should look good even if the user has a custom theme.

Note

This dock art is Windows only and will only work if you have installed Mark Hammond’s pywin32 module (http://sourceforge.net/projects/pywin32/).

hierarchy Inheritance Diagram

Inheritance diagram for: ModernDockArt

Inheritance diagram of ModernDockArt

supclasses Known Superclasses

  • aui.dockart.AuiDefaultDockArt

Methods Summary

__init__ | Default class constructor.
DrawCaption | Draws the text in the pane caption.
DrawCaptionBackground | Draws the text caption background in the pane.
DrawPaneButton | Draws a pane button in the pane caption area.
Init | Initializes the dock art.
RequestUserAttention | Requests the user attention by intermittently highlighting the pane caption.

API Class API

class ModernDockArt(AuiDefaultDockArt) [source]

ModernDockArt is a custom AuiDockArt class, that implements a look similar to Firefox and other recents applications.

Is uses the winxptheme module and XP themes whenever possible, so it should look good even if the user has a custom theme.

Note

This dock art is Windows only and will only work if you have installed Mark Hammond’s pywin32 module (http://sourceforge.net/projects/pywin32/).

__init__(win) [source]

Default class constructor.

Parameters: win – the window managed by AuiManager.

DrawCaption(dc, window, text, rect, pane) [source]

Draws the text in the pane caption.

Parameters:
  • dc – a wx.DC device context;
  • window – an instance of wx.Window;
  • text – the text to be displayed;
  • rect – the pane caption rectangle;
  • pane – the pane for which the text is drawn.

DrawCaptionBackground(dc, rect, pane) [source]

Draws the text caption background in the pane.

Parameters:
  • dc – a wx.DC device context;

  • rect – the text caption rectangle;
  • pane – the pane for which we are drawing the caption background.

DrawPaneButton(dc, window, button, button_state, rect, pane) [source]

Draws a pane button in the pane caption area.

Parameters:
  • dc – a wx.DC device context;

  • window – an instance of wx.Window;

  • button – the button to be drawn;
  • button_state – the pane button state;
  • rect – the pane caption rectangle;
  • pane – the pane for which the button is drawn.

Init() [source]

Initializes the dock art.

RequestUserAttention(dc, window, text, rect, pane) [source]

Requests the user attention by intermittently highlighting the pane caption.

Parameters:
  • dc – a wx.DC device context;

  • window – an instance of wx.Window;

  • text – the text to be displayed;
  • rect – the pane caption rectangle;
  • pane – the pane for which the text is drawn.

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • infobar
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • aui library »
  • aui.dockart »
  • ModernDockArt


aui.dockart

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • aui library »
  • aui.dockart

aui.dockart

Dock art provider code - a dock provider provides all drawing functionality to the AUI dock manager. This allows the dock manager to have a plugable look-and-feel.

By default, a AuiManager uses an instance of this class called AuiDefaultDockArt which provides bitmap art and a colour scheme that is adapted to the major platforms’ look. You can either derive from that class to alter its behaviour or write a completely new dock art class. Call SetArtProvider to make use this new dock art.

Module author: Andrea Gavana <andrea.gavana@gmail.com>

hierarchy Inheritance Diagram

Inheritance diagram for module: aui.dockart

Inheritance diagram of aui.dockart.AuiDefaultDockArt, aui.dockart.ModernDockArt

SVN Revisions

A graphical representation of the SVN commits in the last year.

Click on any date in the picture to jump to that particular revision page, containing information about committers, log messages and SVN diffs.

Revision Graph For dockart

2to3 Python 3 Issues (via 2to3)

No issues have been detected by 2to3.py.

Class Summary

  • AuiDefaultDockArt
  • ModernDockArt

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • infobar
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • aui library »
  • aui.dockart


aui.framemanager functions

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • aui library »
  • aui.framemanager »
  • aui.framemanager functions

aui.framemanager functions

This is the description of standalone Python functions in the aui.framemanager module.

Functions Summary

AuiManager_HasLiveResize | Static function which returns if the input manager should have “live resize” behaviour.
AuiManager_UseNativeMiniframes | Static function which returns if the input manager should use native wx.MiniFrame as
CheckEdgeDrop | Checks on which edge of a window the drop action has taken place.
CheckOutOfWindow | Checks if a point is outside the window rectangle.
CopyDocksAndPanes | This utility function creates shallow copies of the dock and pane info.
CopyDocksAndPanes2 | This utility function creates full copies of the dock and pane info.
DoInsertDockLayer | This is an internal function that inserts a new dock layer by incrementing all existing dock layer values by one.
DoInsertDockRow | This is an internal function that inserts a new dock row by incrementing all existing dock row values by one.
DoInsertPane | This is an internal function that inserts a new pane by incrementing all existing dock position values by one.
DrawResizeHint | Draws a resize hint while a sash is dragged.
EscapeDelimiters | Changes ; into \ and | into \| in the input string.
FindDocks | This is an internal function that returns a list of docks which meet the specified conditions in the parameters and returns a sorted array (sorted by layer and then row).
FindOppositeDocks | This is an internal function that returns a list of docks which is related to the opposite direction.
FindPaneInDock | This method looks up a specified window pointer inside a dock.
GetInternalFrameRect | Returns the window rectangle excluding toolbars.
GetManager | This function will return the aui manager for a given window.
GetMaxLayer | This is an internal function which returns the highest layer inside the specified dock.
GetMaxRow | This is an internal function which returns the highest layer inside the specified dock.
GetNotebookRoot | Returns the AuiPaneInfo which has the specified notebook_id.
GetToolBarDockOffsets | Returns the toolbar dock offsets (top-left and bottom-right).
IsDifferentDockingPosition | Returns whether pane1 and pane2 are in a different docking position based on pane status, docking direction, docking layer and docking row.
PaneSortFunc | This function is used to sort panes by dock position.
RefreshDockingGuides | Refreshes the docking guide windows.
RemovePaneFromDocks | Removes a pane window from all docks with a possible exception specified by parameter exc.
RenumberDockRows | Takes a dock and assigns sequential numbers to existing rows.
SetActivePane | Sets the active pane, as well as cycles through every other pane and makes sure that all others’ active flags are turned off.
ShowDockingGuides | Shows or hide the docking guide windows.

API Functions API

AuiManager_HasLiveResize(manager) [source]

Static function which returns if the input manager should have “live resize” behaviour.

Parameters: manager – an instance of AuiManager.

Note

This method always returns True on wxMac as this platform doesn’t have the ability to use wx.ScreenDC to draw sashes.

AuiManager_UseNativeMiniframes(manager) [source]

Static function which returns if the input manager should use native wx.MiniFrame as floating panes.

Parameters: manager – an instance of AuiManager.

Note

This method always returns True on wxMac as this platform doesn’t have the ability to use custom drawn miniframes.

CheckEdgeDrop(window, docks, pt) [source]

Checks on which edge of a window the drop action has taken place.

Parameters:
  • window – a wx.Window derived window;
  • docks – a list of AuiDockInfo structures;
  • pt – a wx.Point object.

CheckOutOfWindow(window, pt) [source]

Checks if a point is outside the window rectangle.

Parameters:
  • window – a wx.Window derived window;

  • pt – a wx.Point object.

CopyDocksAndPanes(src_docks, src_panes) [source]

This utility function creates shallow copies of the dock and pane info. AuiDockInfo usually contain pointers to AuiPaneInfo classes, thus this function is necessary to reliably reconstruct that relationship in the new dock info and pane info arrays.

Parameters:
  • src_docks – a list of AuiDockInfo classes;
  • src_panes – a list of AuiPaneInfo classes.

CopyDocksAndPanes2(src_docks, src_panes) [source]

This utility function creates full copies of the dock and pane info. AuiDockInfo usually contain pointers to AuiPaneInfo classes, thus this function is necessary to reliably reconstruct that relationship in the new dock info and pane info arrays.

Parameters:
  • src_docks – a list of AuiDockInfo classes;
  • src_panes – a list of AuiPaneInfo classes.

DoInsertDockLayer(panes, dock_direction, dock_layer) [source]

This is an internal function that inserts a new dock layer by incrementing all existing dock layer values by one.

Parameters:
  • panes – a list of AuiPaneInfo;
  • dock_direction – the AuiPaneInfo docking direction to analyze;
  • dock_layer – the AuiPaneInfo layer to analyze.

DoInsertDockRow(panes, dock_direction, dock_layer, dock_row) [source]

This is an internal function that inserts a new dock row by incrementing all existing dock row values by one.

Parameters:
  • panes – a list of AuiPaneInfo;
  • dock_direction – the AuiPaneInfo docking direction to analyze;
  • dock_layer – the AuiPaneInfo layer to analyze;
  • dock_row – the AuiPaneInfo row to analyze.

DoInsertPane(panes, dock_direction, dock_layer, dock_row, dock_pos) [source]

This is an internal function that inserts a new pane by incrementing all existing dock position values by one.

Parameters:
  • panes – a list of AuiPaneInfo;
  • dock_direction – the AuiPaneInfo docking direction to analyze;
  • dock_layer – the AuiPaneInfo layer to analyze;
  • dock_row – the AuiPaneInfo row to analyze;
  • dock_pos – the AuiPaneInfo row to analyze.

DrawResizeHint(dc, rect) [source]

Draws a resize hint while a sash is dragged.

Parameters: rect – a wx.Rect rectangle which specifies the sash dimensions.

EscapeDelimiters(s) [source]

Changes ; into \ and | into \| in the input string.

Parameters: s – the string to be analyzed.

Note

This is an internal functions which is used for saving perspectives.

FindDocks(docks, dock_direction, dock_layer=-1, dock_row=-1, reverse=False) [source]

This is an internal function that returns a list of docks which meet the specified conditions in the parameters and returns a sorted array (sorted by layer and then row).

Parameters:
  • docks – a list of AuiDockInfo;
  • dock_direction – the AuiDockInfo docking direction to analyze;
  • dock_layer – the AuiDockInfo layer to analyze;
  • dock_row – the AuiDockInfo row to analyze;

FindOppositeDocks(docks, dock_direction) [source]

This is an internal function that returns a list of docks which is related to the opposite direction.

Parameters:
  • docks – a list of AuiDockInfo;
  • dock_direction – the AuiDockInfo docking direction to analyze;

FindPaneInDock(dock, window) [source]

This method looks up a specified window pointer inside a dock. If found, the corresponding AuiPaneInfo pointer is returned, otherwise None.

Parameters:
  • dock – a AuiDockInfo structure;
  • window – a wx.Window derived window (associated to a pane).

GetInternalFrameRect(window, docks) [source]

Returns the window rectangle excluding toolbars.

Parameters:
  • window – a wx.Window derived window;

  • docks – a list of AuiDockInfo structures.

GetManager(window) [source]

This function will return the aui manager for a given window.

Parameters: window – this parameter should be any child window or grand-child window (and so on) of the frame/window managed by AuiManager. The window does not need to be managed by the manager itself, nor does it even need to be a child or sub-child of a managed window. It must however be inside the window hierarchy underneath the managed window.

GetMaxLayer(docks, dock_direction) [source]

This is an internal function which returns the highest layer inside the specified dock.

Parameters:
  • docks – a list of AuiDockInfo;
  • dock_direction – the AuiDockInfo docking direction to analyze.

GetMaxRow(panes, dock_direction, dock_layer) [source]

This is an internal function which returns the highest layer inside the specified dock.

Parameters:
  • panes – a list of AuiPaneInfo;
  • dock_direction – the AuiPaneInfo docking direction to analyze;
  • dock_layer – the AuiPaneInfo layer to analyze.

GetNotebookRoot(panes, notebook_id) [source]

Returns the AuiPaneInfo which has the specified notebook_id.

Parameters:
  • panes – a list of AuiPaneInfo instances;
  • notebook_id – the target notebook id.

GetToolBarDockOffsets(docks) [source]

Returns the toolbar dock offsets (top-left and bottom-right).

Parameters: docks – a list of AuiDockInfo to analyze.

IsDifferentDockingPosition(pane1, pane2) [source]

Returns whether pane1 and pane2 are in a different docking position based on pane status, docking direction, docking layer and docking row.

Parameters:
  • pane1 – a AuiPaneInfo instance;
  • pane2 – another AuiPaneInfo instance.

PaneSortFunc(p1, p2) [source]

This function is used to sort panes by dock position.

Parameters:
  • p1 – a AuiPaneInfo instance;
  • p2 – another AuiPaneInfo instance.

RefreshDockingGuides(guides) [source]

Refreshes the docking guide windows.

Parameters: guides – a list of AuiDockingGuideInfo classes;

RemovePaneFromDocks(docks, pane, exc=None) [source]

Removes a pane window from all docks with a possible exception specified by parameter exc.

Parameters:
  • docks – a list of AuiDockInfo structures;
  • pane – the AuiPaneInfo pane to be removed;
  • exc – the possible pane exception.

RenumberDockRows(docks) [source]

Takes a dock and assigns sequential numbers to existing rows. Basically it takes out the gaps so if a dock has rows with numbers 0, 2, 5, they will become 0, 1, 2.

Parameters: docks – a list of AuiDockInfo structures.

SetActivePane(panes, active_pane) [source]

Sets the active pane, as well as cycles through every other pane and makes sure that all others’ active flags are turned off.

Parameters:
  • panes – a list of AuiPaneInfo structures;
  • active_pane – the pane to be made active (if found).

ShowDockingGuides(guides, show) [source]

Shows or hide the docking guide windows.

Parameters:
  • guides – a list of AuiDockingGuideInfo classes;
  • show – whether to show or hide the docking guide windows.

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • infobar
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • aui library »
  • aui.framemanager »
  • aui.framemanager functions


AuiCenterDockingGuide

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • aui library »
  • aui.framemanager »
  • AuiCenterDockingGuide

AuiCenterDockingGuide

A docking guide window for multiple docking hint (diamond-shaped HUD).

hierarchy Inheritance Diagram

Inheritance diagram for: AuiCenterDockingGuide

Inheritance diagram of AuiCenterDockingGuide

supclasses Known Superclasses

  • aui.framemanager.AuiDockingGuide

Methods Summary

__init__ | Default class constructor.
AeroMove | Moves the docking guide window to the new position.
CreateShapesWithStyle | Creates the docking guide window shape based on which docking bitmaps are used.
HitTest | Checks if the mouse position is inside the target windows rect.
OnEraseBackground | Handles the wx.EVT_ERASE_BACKGROUND event for AuiCenterDockingGuide.
OnPaint | Handles the wx.EVT_PAINT event for AuiCenterDockingGuide.
SetGuideShape | Sets the correct shape for the docking guide window.
UpdateDockGuide | Updates the docking guides images depending on the mouse position, using focused images if the mouse is inside the docking guide or unfocused images if it is outside.
ValidateNotebookDocking | Sets whether a pane can be docked on top of another to create an automatic

API Class API

class AuiCenterDockingGuide(AuiDockingGuide) [source]

A docking guide window for multiple docking hint (diamond-shaped HUD).

__init__(parent) [source]

Default class constructor. Used internally, do not call it in your code!

Parameters: parent – the AuiCenterDockingGuide parent.

AeroMove(pos) [source]

Moves the docking guide window to the new position.

Parameters: pos – the new docking guide position.

CreateShapesWithStyle() [source]

Creates the docking guide window shape based on which docking bitmaps are used.

HitTest(x, y) [source]

Checks if the mouse position is inside the target windows rect.

Parameters:
  • x – the x mouse position;
  • y – the y mouse position.

OnEraseBackground(event) [source]

Handles the wx.EVT_ERASE_BACKGROUND event for AuiCenterDockingGuide.

Parameters: event – wx.EraseEvent to be processed.

Note

This is intentionally empty to reduce flickering while drawing.

OnPaint(event) [source]

Handles the wx.EVT_PAINT event for AuiCenterDockingGuide.

Parameters: event – a wx.PaintEvent to be processed.

SetGuideShape(event=None) [source]

Sets the correct shape for the docking guide window.

Parameters: event – on wxGTK, a wx.WindowCreateEvent event to process.

UpdateDockGuide(pos) [source]

Updates the docking guides images depending on the mouse position, using focused images if the mouse is inside the docking guide or unfocused images if it is outside.

Parameters: pos – a wx.Point mouse position.

ValidateNotebookDocking(valid) [source]

Sets whether a pane can be docked on top of another to create an automatic AuiNotebook.

Parameters: valid – whether a pane can be docked on top to another to form an automatic AuiNotebook.

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • infobar
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • aui library »
  • aui.framemanager »
  • AuiCenterDockingGuide


AuiDockInfo

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • aui library »
  • aui.framemanager »
  • AuiDockInfo

AuiDockInfo

A class to store all properties of a dock.

hierarchy Inheritance Diagram

Inheritance diagram for: AuiDockInfo

Inheritance diagram of AuiDockInfo

Methods Summary

__init__ | Default class constructor.
IsHorizontal | Returns whether the dock is horizontal or not.
IsOk | Returns whether a dock is valid or not.
IsVertical | Returns whether the dock is vertical or not.

API Class API

class AuiDockInfo(object) [source]

A class to store all properties of a dock.

__init__() [source]

Default class constructor. Used internally, do not call it in your code!

IsHorizontal() [source]

Returns whether the dock is horizontal or not.

IsOk() [source]

Returns whether a dock is valid or not.

In order to be valid, a dock needs to have a non-zero dock_direction.

IsVertical() [source]

Returns whether the dock is vertical or not.

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • infobar
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • aui library »
  • aui.framemanager »
  • AuiDockInfo


AuiDockingGuide

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • aui library »
  • aui.framemanager »
  • AuiDockingGuide

AuiDockingGuide

Base class for AuiCenterDockingGuide and AuiSingleDockingGuide.

hierarchy Inheritance Diagram

Inheritance diagram for: AuiDockingGuide

Inheritance diagram of AuiDockingGuide

subclasses Known Subclasses

  • aui.framemanager.AuiCenterDockingGuide
  • aui.framemanager.AuiSingleDockingGuide

Methods Summary

__init__ | Default class constructor.
HitTest | To be overridden by parent classes.
ValidateNotebookDocking | To be overridden by parent classes.

API Class API

class AuiDockingGuide(wx.Frame) [source]

Base class for AuiCenterDockingGuide and AuiSingleDockingGuide.

__init__(parent, id=wx.ID_ANY, title="", pos=wx.DefaultPosition, size=wx.DefaultSize, style=wx.FRAME_TOOL_WINDOW | wx.STAY_ON_TOP | wx.FRAME_NO_TASKBAR | wx.NO_BORDER, name="AuiDockingGuide") [source]

Default class constructor. Used internally, do not call it in your code!

Parameters:
  • parent – the AuiDockingGuide parent;
  • id – the window identifier. It may take a value of -1 to indicate a default value.
  • title – the caption to be displayed on the frame’s title bar.
  • pos – the window position. A value of (-1, -1) indicates a default position, chosen by either the windowing system or wxPython, depending on platform.
  • size – the window size. A value of (-1, -1) indicates a default size, chosen by either the windowing system or wxPython, depending on platform.
  • style – the window style.
  • name – the name of the window. This parameter is used to associate a name with the item, allowing the application user to set Motif resource values for individual windows.

HitTest(x, y) [source]

To be overridden by parent classes.

Parameters:
  • x – the x mouse position;
  • y – the y mouse position.

ValidateNotebookDocking(valid) [source]

To be overridden by parent classes.

Parameters: valid – whether a pane can be docked on top to another to form an automatic AuiNotebook.

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • infobar
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • aui library »
  • aui.framemanager »
  • AuiDockingGuide


AuiDockingGuideInfo

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • aui library »
  • aui.framemanager »
  • AuiDockingGuideInfo

AuiDockingGuideInfo

A class which holds information about VS2005 docking guide windows.

hierarchy Inheritance Diagram

Inheritance diagram for: AuiDockingGuideInfo

Inheritance diagram of AuiDockingGuideInfo

Methods Summary

__init__ | Default class constructor.
Assign | Assigns the properties of the other AuiDockingGuideInfo to self.
Bottom | Sets the guide window to bottom docking.
Center | Sets the guide window to center docking.
Centre | Sets the guide window to centre docking.
Host | Hosts a docking guide window.
Left | Sets the guide window to left docking.
Right | Sets the guide window to right docking.
Top | Sets the guide window to top docking.

API Class API

class AuiDockingGuideInfo(object) [source]

A class which holds information about VS2005 docking guide windows.

__init__(other=None) [source]

Default class constructor. Used internally, do not call it in your code!

Parameters: other – another instance of AuiDockingGuideInfo.

Assign(other) [source]

Assigns the properties of the other AuiDockingGuideInfo to self.

Parameters: other – another instance of AuiDockingGuideInfo.

Bottom() [source]

Sets the guide window to bottom docking.

Center() [source]

Sets the guide window to center docking.

Centre() [source]

Sets the guide window to centre docking.

Host(h) [source]

Hosts a docking guide window.

Parameters: h – an instance of AuiSingleDockingGuide or AuiCenterDockingGuide.

Left() [source]

Sets the guide window to left docking.

Right() [source]

Sets the guide window to right docking.

Top() [source]

Sets the guide window to top docking.

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • infobar
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • aui library »
  • aui.framemanager »
  • AuiDockingGuideInfo


AuiDockingGuideWindow

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • aui library »
  • aui.framemanager »
  • AuiDockingGuideWindow

AuiDockingGuideWindow

Target class for AuiSingleDockingGuide and AuiCenterDockingGuide.

hierarchy Inheritance Diagram

Inheritance diagram for: AuiDockingGuideWindow

Inheritance diagram of AuiDockingGuideWindow

Methods Summary

__init__ | Default class constructor.
Draw | Draws the whole docking guide window (not used if the docking guide images are ok).
DrawArrow | Draws the docking guide arrow icon (not used if the docking guide images are ok).
DrawBackground | Draws the docking guide background.
DrawDottedLine | Draws a dotted line (not used if the docking guide images are ok).
DrawIcon | Draws the docking guide icon (not used if the docking guide images are ok).
IsValid | Returns whether the docking direction is valid.
OnEraseBackground | Handles the wx.EVT_ERASE_BACKGROUND event for AuiDockingGuideWindow.
OnPaint | Handles the wx.EVT_PAINT event for AuiDockingGuideWindow.
SetValid | Sets the docking direction as valid or invalid.
UpdateDockGuide | Updates the docking guide images depending on the mouse position, using focused images if the mouse is inside the docking guide or unfocused images if it is outside.

API Class API

class AuiDockingGuideWindow(wx.Window) [source]

Target class for AuiSingleDockingGuide and AuiCenterDockingGuide.

__init__(parent, rect, direction=0, center=False, useAero=False) [source]

Default class constructor. Used internally, do not call it in your code!

Parameters:
  • parent – the AuiDockingGuideWindow parent;
  • rect – the window rect;
  • direction – one of wx.TOP, wx.BOTTOM, wx.LEFT, wx.RIGHT, wx.CENTER;
  • center – whether the calling class is a AuiCenterDockingGuide;
  • useAero – whether to use the new Aero-style bitmaps or Whidbey-style bitmaps for the docking guide.

Draw(dc) [source]

Draws the whole docking guide window (not used if the docking guide images are ok).

Parameters: dc – a wx.DC device context object.

DrawArrow(dc) [source]

Draws the docking guide arrow icon (not used if the docking guide images are ok).

Parameters: dc – a wx.DC device context object.

DrawBackground(dc) [source]

Draws the docking guide background.

Parameters: dc – a wx.DC device context object.

DrawDottedLine(dc, point, length, vertical) [source]

Draws a dotted line (not used if the docking guide images are ok).

Parameters:
  • dc – a wx.DC device context object;

  • point – a wx.Point where to start drawing the dotted line;
  • length – the length of the dotted line;
  • vertical – whether it is a vertical docking guide window or not.

DrawIcon(dc) [source]

Draws the docking guide icon (not used if the docking guide images are ok).

Parameters: dc – a wx.DC device context object.

IsValid() [source]

Returns whether the docking direction is valid.

OnEraseBackground(event) [source]

Handles the wx.EVT_ERASE_BACKGROUND event for AuiDockingGuideWindow.

Parameters: event – a wx.EraseEvent to be processed.

Note

This is intentionally empty to reduce flickering while drawing.

OnPaint(event) [source]

Handles the wx.EVT_PAINT event for AuiDockingGuideWindow.

Parameters: event – a wx.PaintEvent to be processed.

SetValid(valid) [source]

Sets the docking direction as valid or invalid.

Parameters: valid – whether the docking direction is allowed or not.

UpdateDockGuide(pos) [source]

Updates the docking guide images depending on the mouse position, using focused images if the mouse is inside the docking guide or unfocused images if it is outside.

Parameters: pos – a wx.Point mouse position.

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • infobar
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • aui library »
  • aui.framemanager »
  • AuiDockingGuideWindow


AuiDockingHintWindow

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • aui library »
  • aui.framemanager »
  • AuiDockingHintWindow

AuiDockingHintWindow

The original wxAUI docking window hint.

hierarchy Inheritance Diagram

Inheritance diagram for: AuiDockingHintWindow

Inheritance diagram of AuiDockingHintWindow

Methods Summary

__init__ | Default class constructor.
MakeVenetianBlinds | Creates the “venetian blind” effect if AuiManager has the AUI_MGR_VENETIAN_BLINDS_HINT
OnSize | Handles the wx.EVT_SIZE event for AuiDockingHintWindow.
SetBlindMode | Sets whether venetian blinds or transparent hints will be shown as docking hint.
SetShape | If the platform supports it, sets the shape of the window to that depicted by region.
Show | Show the hint window.

API Class API

class AuiDockingHintWindow(wx.Frame) [source]

The original wxAUI docking window hint.

__init__(parent, id=wx.ID_ANY, title="", pos=wx.DefaultPosition, size=wx.Size(1, 1), style=wx.FRAME_TOOL_WINDOW | wx.FRAME_FLOAT_ON_PARENT | wx.FRAME_NO_TASKBAR | wx.NO_BORDER | wx.FRAME_SHAPED, name="auiHintWindow") [source]

Default class constructor. Used internally, do not call it in your code!

Parameters:
  • parent – the AuiDockingGuide parent;
  • id – the window identifier. It may take a value of -1 to indicate a default value.
  • title – the caption to be displayed on the frame’s title bar;
  • pos – the window position. A value of (-1, -1) indicates a default position, chosen by either the windowing system or wxPython, depending on platform;
  • size – the window size. A value of (-1, -1) indicates a default size, chosen by either the windowing system or wxPython, depending on platform;
  • style – the window style;
  • name – the name of the window. This parameter is used to associate a name with the item, allowing the application user to set Motif resource values for individual windows.

MakeVenetianBlinds() [source]

Creates the “venetian blind” effect if AuiManager has the AUI_MGR_VENETIAN_BLINDS_HINT flag set.

OnSize(event) [source]

Handles the wx.EVT_SIZE event for AuiDockingHintWindow.

Parameters: event – a wx.SizeEvent to be processed.

SetBlindMode(agwFlags) [source]

Sets whether venetian blinds or transparent hints will be shown as docking hint. This depends on the AuiManager flags.

Parameters: agwFlags – the AuiManager flags.

SetShape(region) [source]

If the platform supports it, sets the shape of the window to that depicted by region. The system will not display or respond to any mouse event for the pixels that lie outside of the region. To reset the window to the normal rectangular shape simply call SetShape again with an empty region.

Parameters: region – the shape of the frame (an instance of wx.Region).

Note

Overridden for wxMac.

Show(show=True) [source]

Show the hint window.

Parameters: show – whether to show or hide the hint docking window.

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • infobar
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • aui library »
  • aui.framemanager »
  • AuiDockingHintWindow


AuiDockUIPart

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • aui library »
  • aui.framemanager »
  • AuiDockUIPart

AuiDockUIPart

A class which holds attributes for a UI part in the interface.

hierarchy Inheritance Diagram

Inheritance diagram for: AuiDockUIPart

Inheritance diagram of AuiDockUIPart

Methods Summary

__init__ Default class constructor.

API Class API

class AuiDockUIPart(object) [source]

A class which holds attributes for a UI part in the interface.

__init__() [source]

Default class constructor. Used internally, do not call it in your code!

typeBackground = 6

typeCaption = 0

typeDock = 2

typeDockSizer = 3

typeGripper = 1

typePane = 4

typePaneBorder = 7

typePaneButton = 8

typePaneSizer = 5

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • infobar
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • aui library »
  • aui.framemanager »
  • AuiDockUIPart


AuiFloatingFrame

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • aui library »
  • aui.framemanager »
  • AuiFloatingFrame

AuiFloatingFrame

AuiFloatingFrame is the frame class that holds floating panes.

hierarchy Inheritance Diagram

Inheritance diagram for: AuiFloatingFrame

Inheritance diagram of AuiFloatingFrame

Methods Summary

__init__ | Default class constructor.
CopyAttributes | Copies all the attributes of the input pane into another AuiPaneInfo.
FadeOut | Actually starts the fading out of the floating pane.
FlyOut | Starts the flying in and out of a floating pane.
GetOwnerManager | Returns the AuiManager that manages the pane.
OnActivate | Handles the wx.EVT_ACTIVATE event for AuiFloatingFrame.
OnCheckFlyTimer | Handles the wx.EVT_TIMER event for AuiFloatingFrame.
OnClose | Handles the wx.EVT_CLOSE event for AuiFloatingFrame.
OnFindManager | Handles the EVT_AUI_FIND_MANAGER event for AuiFloatingFrame.
OnFlyTimer | Handles the wx.EVT_TIMER event for AuiFloatingFrame.
OnIdle | Handles the wx.EVT_IDLE event for AuiFloatingFrame.
OnMove | Handles the wx.EVT_MOVE event for AuiFloatingFrame.
OnMoveEvent | Handles the wx.EVT_MOVE and wx.EVT_MOVING events for AuiFloatingFrame.
OnMoveFinished | The user has just finished moving the floating pane.
OnMoveStart | The user has just started moving the floating pane.
OnMoving | The user is moving the floating pane.
OnSize | Handles the wx.EVT_SIZE event for AuiFloatingFrame.
SetPaneWindow | Sets all the properties of a pane.

API Class API

class AuiFloatingFrame(wx.MiniFrame) [source]

AuiFloatingFrame is the frame class that holds floating panes.

__init__(parent, owner_mgr, pane=None, id=wx.ID_ANY, title="", style=wx.FRAME_TOOL_WINDOW | wx.FRAME_FLOAT_ON_PARENT | wx.FRAME_NO_TASKBAR | wx.CLIP_CHILDREN) [source]

Default class constructor. Used internally, do not call it in your code!

Parameters:
  • parent – the AuiFloatingFrame parent;
  • owner_mgr – the AuiManager that manages the floating pane;
  • pane – the AuiPaneInfo pane that is about to float;
  • id – the window identifier. It may take a value of -1 to indicate a default value.
  • title – the caption to be displayed on the frame’s title bar.
  • style – the window style.

CopyAttributes(pane) [source]

Copies all the attributes of the input pane into another AuiPaneInfo.

Parameters: pane – the source AuiPaneInfo from where to copy attributes.

FadeOut() [source]

Actually starts the fading out of the floating pane.

FlyOut() [source]

Starts the flying in and out of a floating pane.

GetOwnerManager() [source]

Returns the AuiManager that manages the pane.

OnActivate(event) [source]

Handles the wx.EVT_ACTIVATE event for AuiFloatingFrame.

Parameters: event – a wx.ActivateEvent to be processed.

OnCheckFlyTimer(event) [source]

Handles the wx.EVT_TIMER event for AuiFloatingFrame.

Parameters: event – a wx.TimerEvent to be processed.

Note

This is used solely for “fly-out” panes.

OnClose(event) [source]

Handles the wx.EVT_CLOSE event for AuiFloatingFrame.

Parameters: event – a wx.CloseEvent to be processed.

OnFindManager(event) [source]

Handles the EVT_AUI_FIND_MANAGER event for AuiFloatingFrame.

Parameters: event – a AuiManagerEvent event to be processed.

OnFlyTimer(event) [source]

Handles the wx.EVT_TIMER event for AuiFloatingFrame.

Parameters: event – a wx.TimerEvent to be processed.

OnIdle(event) [source]

Handles the wx.EVT_IDLE event for AuiFloatingFrame.

Parameters: event – a wx.IdleEvent event to be processed.

Note

This event is only processed on wxMAC or if AuiManager is using the AUI_MGR_USE_NATIVE_MINIFRAMES style.

OnMove(event) [source]

Handles the wx.EVT_MOVE event for AuiFloatingFrame.

Parameters: event – a wx.MoveEvent to be processed.

Note

This event is not processed on wxMAC or if AuiManager is not using the AUI_MGR_USE_NATIVE_MINIFRAMES style.

OnMoveEvent(event) [source]

Handles the wx.EVT_MOVE and wx.EVT_MOVING events for AuiFloatingFrame.

Parameters: event – a wx.MoveEvent to be processed.

Note

This event is only processed on wxMAC or if AuiManager is using the AUI_MGR_USE_NATIVE_MINIFRAMES style.

OnMoveFinished() [source]

The user has just finished moving the floating pane.

Note

This method is used only on wxMAC or if AuiManager is using the AUI_MGR_USE_NATIVE_MINIFRAMES style.

OnMoveStart(event) [source]

The user has just started moving the floating pane.

Parameters: event – an instance of wx.MouseEvent.

Note

This method is used only on wxMAC or if AuiManager is using the AUI_MGR_USE_NATIVE_MINIFRAMES style.

OnMoving(event) [source]

The user is moving the floating pane.

Parameters: event – an instance of wx.MouseEvent.

Note

This method is used only on wxMAC or if AuiManager is using the AUI_MGR_USE_NATIVE_MINIFRAMES style.

OnSize(event) [source]

Handles the wx.EVT_SIZE event for AuiFloatingFrame.

Parameters: event – a wx.SizeEvent to be processed.

SetPaneWindow(pane) [source]

Sets all the properties of a pane.

Parameters: pane – the AuiPaneInfo to analyze.

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • infobar
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • aui library »
  • aui.framemanager »
  • AuiFloatingFrame


AuiManager

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • aui library »
  • aui.framemanager »
  • AuiManager

AuiManager

AuiManager manages the panes associated with it for a particular wx.Frame, using a pane’s AuiPaneInfo information to determine each pane’s docking and floating behavior. AuiManager uses wxPython’s sizer mechanism to plan the layout of each frame. It uses a replaceable dock art class to do all drawing, so all drawing is localized in one area, and may be customized depending on an applications’ specific needs.

AuiManager works as follows: the programmer adds panes to the class, or makes changes to existing pane properties (dock position, floating state, show state, etc...). To apply these changes, the Update function is called. This batch processing can be used to avoid flicker, by modifying more than one pane at a time, and then “committing” all of the changes at once by calling Update().

Panes can be added quite easily:

text1 = wx.TextCtrl(self, -1)
text2 = wx.TextCtrl(self, -1)
self._mgr.AddPane(text1, AuiPaneInfo().Left().Caption("Pane Number One"))
self._mgr.AddPane(text2, AuiPaneInfo().Bottom().Caption("Pane Number Two"))

self._mgr.Update()

Later on, the positions can be modified easily. The following will float an existing pane in a tool window:

self._mgr.GetPane(text1).Float()

Layers, Rows and Directions, Positions:

Inside AUI, the docking layout is figured out by checking several pane parameters. Four of these are important for determining where a pane will end up.

Direction - Each docked pane has a direction, Top, Bottom, Left, Right, or Center. This is fairly self-explanatory. The pane will be placed in the location specified by this variable.

Position - More than one pane can be placed inside of a “dock”. Imagine two panes being docked on the left side of a window. One pane can be placed over another. In proportionally managed docks, the pane position indicates it’s sequential position, starting with zero. So, in our scenario with two panes docked on the left side, the top pane in the dock would have position 0, and the second one would occupy position 1.

Row - A row can allow for two docks to be placed next to each other. One of the most common places for this to happen is in the toolbar. Multiple toolbar rows are allowed, the first row being in row 0, and the second in row 1. Rows can also be used on vertically docked panes.

Layer - A layer is akin to an onion. Layer 0 is the very center of the managed pane. Thus, if a pane is in layer 0, it will be closest to the center window (also sometimes known as the “content window”). Increasing layers “swallow up” all layers of a lower value. This can look very similar to multiple rows, but is different because all panes in a lower level yield to panes in higher levels. The best way to understand layers is by running the AUI sample (AUI.py).

hierarchy Inheritance Diagram

Inheritance diagram for: AuiManager

Inheritance diagram of AuiManager

subclasses Known Subclasses

  • aui.framemanager.AuiManager_DCP

appearance Control Appearance

AuiManager

Methods Summary

__init__ | Default class constructor.
ActivatePane | Activates the pane to which window is associated.
AddPane | Tells the frame manager to start managing a child window.
AddPane1 | See comments on AddPane.
AddPane2 | See comments on AddPane.
AddPane3 | See comments on AddPane.
AddPane4 | See comments on AddPane.
AnimateDocking | Animates the minimization/docking of a pane a la Eclipse, using a wx.ScreenDC
CalculateDockSizerLimits | Calculates the minimum and maximum sizes allowed for the input dock.
CalculateHintRect | Calculates the drop hint rectangle.
CalculatePaneSizerLimits | Calculates the minimum and maximum sizes allowed for the input pane.
CanDockPanel | Returns whether a pane can be docked or not.
CanUseModernDockArt | Returns whether ModernDockArt can be used (Windows XP / Vista / 7 only,
CheckMovableSizer | Checks if a UI part can be actually resized.
CheckPaneMove | Checks if a pane has moved by a visible amount.
ClosePane | Destroys or hides the pane depending on its flags.
CopyTarget | Copies all the attributes of the input target into another AuiPaneInfo.
CreateFloatingFrame | Creates a floating frame for the windows.
CreateGuideWindows | Creates the VS2005 HUD guide windows.
CreateHintWindow | Creates the standard wxAUI hint window.
CreateNotebook | Creates an automatic AuiNotebook when a pane is docked on
CreateNotebookBase | Creates an auto-notebook base from a pane, and then add that pane as a page.
DestroyGuideWindows | Destroys the VS2005 HUD guide windows.
DestroyHintWindow | Destroys the standard wxAUI hint window.
DetachPane | Tells the AuiManager to stop managing the pane specified
DoDrop | This is an important function.
DoDropFloatingPane | Handles the situation in which the dropped pane contains a normal window.
DoDropLayer | Handles the situation in which target is a single dock guide.
DoDropNonFloatingPane | Handles the situation in which the dropped pane is not floating.
DoDropPane | Drop a pane in the interface.
DoDropRow | Insert a row in the interface before dropping.
DoDropToolbar | Handles the situation in which the dropped pane contains a toolbar.
DoEndResizeAction | Ends a resize action, or for live update, resizes the sash.
DoFrameLayout | This is an internal function which invokes wx.Sizer.Layout
DrawHintRect | Calculates the hint rectangle by calling
DrawPaneButton | Draws a pane button in the caption (convenience function).
FireEvent | Fires one of the EVT_AUI_PANE_FLOATED/FLOATING/DOCKING/DOCKED/ACTIVATED event.
GetAGWFlags | Returns the current manager’s flags.
GetAllPanes | Returns a reference to all the pane info structures.
GetAnimationStep | Returns the animation step speed (a float) to use in AnimateDocking.
GetArtProvider | Returns the current art provider being used.
GetAttributes | Returns all the attributes of a AuiPaneInfo.
GetAutoNotebookStyle | Returns the default AGW-specific window style for automatic notebooks.
GetAutoNotebookTabArt | Returns the default tab art provider for automatic notebooks.
GetDockPixelOffset | This is an internal function which returns a dock’s offset in pixels from the left side of the window (for horizontal docks) or from the top of the window (for vertical docks).
GetDockSizeConstraint | Returns the current dock constraint values.
GetFrame | Returns the window being managed by AuiManager.
GetManagedWindow | Returns the window being managed by AuiManager.
GetNotebooks | Returns all the automatic AuiNotebook in the AuiManager.
GetOppositeDockTotalSize | Returns the dimensions of the dock which lives opposite of the input dock.
GetPane | Looks up a AuiPaneInfo structure based
GetPaneByName | This version of GetPane looks up a pane based on a
GetPaneByWidget | This version of GetPane looks up a pane based on a
GetPanePart | Looks up the pane border UI part of the
GetPanePositionsAndSizes | Returns all the panes positions and sizes in a dock.
GetPartSizerRect | Returns the rectangle surrounding the specified UI parts.
GetPartnerDock | Returns the partner dock for the input dock.
GetPartnerPane | Returns the partner pane for the input pane.
GetSnapPosition | Returns the main frame snapping position.
GetTotalPixSizeAndProportion | Returns the dimensions and proportion of the input dock.
HideHint | Hides a transparent window hint if there is one.
HitTest | This is an internal function which determines
InsertPane | This method is used to insert either a previously unmanaged pane window into the frame manager, or to insert a currently managed pane somewhere else.
IsPaneButtonVisible | Returns whether a pane button in the pane caption is visible.
LayoutAddDock | Adds a dock into the existing layout.
LayoutAddPane | Adds a pane into the existing layout (in an existing dock).
LayoutAll | Layouts all the UI structures in the interface.
LoadPaneInfo | This method is similar to to LoadPerspective, with the exception that
LoadPerspective | Loads a layout which was saved with SavePerspective.
MaximizePane | Maximizes the input pane.
MinimizePane | Minimizes a pane in a newly and automatically created AuiToolBar.
OnCaptionDoubleClicked | Handles the mouse double click on the pane caption.
OnCaptureLost | Handles the wx.EVT_MOUSE_CAPTURE_LOST event for AuiManager.
OnChildFocus | Handles the wx.EVT_CHILD_FOCUS event for AuiManager.
OnEraseBackground | Handles the wx.EVT_ERASE_BACKGROUND event for AuiManager.
OnFindManager | Handles the EVT_AUI_FIND_MANAGER event for AuiManager.
OnFloatingPaneActivated | Handles the activation event of a floating pane.
OnFloatingPaneClosed | Handles the close event of a floating pane.
OnFloatingPaneMoved | Handles the move event of a floating pane.
OnFloatingPaneResized | Handles the resizing of a floating pane.
OnGripperClicked | Handles the mouse click on the pane gripper.
OnHintFadeTimer | Handles the wx.EVT_TIMER event for AuiManager.
OnLeaveWindow | Handles the wx.EVT_LEAVE_WINDOW event for AuiManager.
OnLeftDClick | Handles the wx.EVT_LEFT_DCLICK event for AuiManager.
OnLeftDown | Handles the wx.EVT_LEFT_DOWN event for AuiManager.
OnLeftUp | Handles the wx.EVT_LEFT_UP event for AuiManager.
OnLeftUp_ClickButton | Sub-handler for the OnLeftUp event.
OnLeftUp_DragFloatingPane | Sub-handler for the OnLeftUp event.
OnLeftUp_DragToolbarPane | Sub-handler for the OnLeftUp event.
OnLeftUp_Resize | Sub-handler for the OnLeftUp event.
OnMotion | Handles the wx.EVT_MOTION event for AuiManager.
OnMotion_ClickCaption | Sub-handler for the OnMotion event.
OnMotion_DragFloatingPane | Sub-handler for the OnMotion event.
OnMotion_DragToolbarPane | Sub-handler for the OnMotion event.
OnMotion_Other | Sub-handler for the OnMotion event.
OnMotion_Resize | Sub-handler for the OnMotion event.
OnMove | Handles the wx.EVT_MOVE event for AuiManager.
OnPaint | Handles the wx.EVT_PAINT event for AuiManager.
OnPaneButton | Handles the EVT_AUI_PANE_BUTTON event for AuiManager.
OnPaneDocked | Handles the EVT_AUI_PANE_DOCKED event for AuiManager.
OnRender | Draws all of the pane captions, sashes, backgrounds, captions, grippers, pane borders and buttons.
OnRestoreMinimizedPane | Handles the EVT_AUI_PANE_MIN_RESTORE event for AuiManager.
OnSetCursor | Handles the wx.EVT_SET_CURSOR event for AuiManager.
OnSize | Handles the wx.EVT_SIZE event for AuiManager.
OnSysColourChanged | Handles the wx.EVT_SYS_COLOUR_CHANGED event for AuiManager.
OnTabBeginDrag | Handles the EVT_AUINOTEBOOK_BEGIN_DRAG event.
OnTabPageClose | Handles the EVT_AUINOTEBOOK_PAGE_CLOSE event.
OnTabSelected | Handles the EVT_AUINOTEBOOK_PAGE_CHANGED event.
PaneFromTabEvent | Returns a AuiPaneInfo from a AuiNotebookEvent event.
PaneHitTest | Similar to HitTest, but it checks in which AuiPaneInfo rectangle the
ProcessDockResult | This is a utility function used by DoDrop - it checks
ProcessMgrEvent | Process the AUI events sent to the manager.
RefreshButton | Refreshes a pane button in the caption.
RefreshCaptions | Refreshes all pane captions.
RemoveAutoNBCaption | Removes the caption on newly created automatic notebooks.
Render | Fires a render event, which is normally handled by
Repaint | Repaints the entire frame decorations (sashes, borders, buttons and so on).
RepositionPane | Repositions a pane after the main frame has been moved/resized.
RequestUserAttention | Requests the user attention by intermittently highlighting the pane caption.
RestoreMaximizedPane | Restores the current maximized pane (if any).
RestoreMinimizedPane | Restores a previously minimized pane.
RestorePane | Restores the input pane from a previous maximized or minimized state.
RestrictResize | Common method between DoEndResizeAction and OnLeftUp_Resize.
SavePaneInfo | This method is similar to SavePerspective, with the exception
SavePerspective | Saves the entire user interface layout into an encoded string, which can then
SavePreviousDockSizes | Stores the previous dock sizes, to be used in a “restore” action later.
SetAGWFlags | This method is used to specify AuiManager‘s settings flags.
SetAnimationStep | Sets the animation step speed (a float) to use in AnimateDocking.
SetArtProvider | Instructs AuiManager to use art provider specified by the parameter
SetAttributes | Sets all the attributes contained in attrs to a AuiPaneInfo.
SetAutoNotebookStyle | Sets the default AGW-specific window style for automatic notebooks.
SetAutoNotebookTabArt | Sets the default tab art provider for automatic notebooks.
SetDockSizeConstraint | When a user creates a new dock by dragging a window into a docked position, often times the large size of the window will create a dock that is unwieldly large.
SetFrame | Called to specify the frame or window which is to be managed by AuiManager.
SetManagedWindow | Called to specify the frame or window which is to be managed by AuiManager.
SetMasterManager | Sets the master manager for an automatic AuiNotebook.
SetSnapLimits | Modifies the snap limits used when snapping the managed_window to the screen
ShowHint | Shows the AUI hint window.
ShowPane | Shows or hides a pane based on the window passed as input.
SlideIn | Handles the wx.EVT_TIMER event for AuiManager.
SlideOut | Slides out a preview of a minimized pane.
SmartShrink | Used to intelligently shrink the docks’ size (if needed).
SmoothDock | This method implements a smooth docking effect for floating panes, similar to
Snap | Snaps the main frame to specified position on the screen.
SnapPane | Snaps a floating pane to one of the main frame sides.
SnapToScreen | Snaps the main frame to specified position on the screen.
StartPreviewTimer | Starts a timer for sliding in and out a minimized pane.
StopPreviewTimer | Stops a timer for sliding in and out a minimized pane.
SwitchToolBarOrientation | Switches the toolbar orientation from vertical to horizontal and vice-versa.
UnInit | Uninitializes the framework and should be called before a managed frame or window is destroyed.
Update | This method is called after any number of changes are made to any of the managed panes.
UpdateButtonOnScreen | Updates/redraws the UI part containing a pane button.
UpdateDockingGuides | Updates the docking guide windows positions and appearance.
UpdateNotebook | Updates the automatic AuiNotebook in the layout (if any exists).

API Class API

class AuiManager(wx.EvtHandler) [source]

AuiManager manages the panes associated with it for a particular wx.Frame, using a pane’s AuiPaneInfo information to determine each pane’s docking and floating behavior. AuiManager uses wxPython’s sizer mechanism to plan the layout of each frame. It uses a replaceable dock art class to do all drawing, so all drawing is localized in one area, and may be customized depending on an applications’ specific needs.

AuiManager works as follows: the programmer adds panes to the class, or makes changes to existing pane properties (dock position, floating state, show state, etc...). To apply these changes, the AuiManager.Update() function is called. This batch processing can be used to avoid flicker, by modifying more than one pane at a time, and then “committing” all of the changes at once by calling Update().

Panes can be added quite easily:

text1 = wx.TextCtrl(self, -1)
text2 = wx.TextCtrl(self, -1)
self._mgr.AddPane(text1, AuiPaneInfo().Left().Caption("Pane Number One"))
self._mgr.AddPane(text2, AuiPaneInfo().Bottom().Caption("Pane Number Two"))

self._mgr.Update()

Later on, the positions can be modified easily. The following will float an existing pane in a tool window:

self._mgr.GetPane(text1).Float()

Layers, Rows and Directions, Positions:

Inside AUI, the docking layout is figured out by checking several pane parameters. Four of these are important for determining where a pane will end up.

Direction - Each docked pane has a direction, Top, Bottom, Left, Right, or Center. This is fairly self-explanatory. The pane will be placed in the location specified by this variable.

Position - More than one pane can be placed inside of a “dock”. Imagine two panes being docked on the left side of a window. One pane can be placed over another. In proportionally managed docks, the pane position indicates it’s sequential position, starting with zero. So, in our scenario with two panes docked on the left side, the top pane in the dock would have position 0, and the second one would occupy position 1.

Row - A row can allow for two docks to be placed next to each other. One of the most common places for this to happen is in the toolbar. Multiple toolbar rows are allowed, the first row being in row 0, and the second in row 1. Rows can also be used on vertically docked panes.

Layer - A layer is akin to an onion. Layer 0 is the very center of the managed pane. Thus, if a pane is in layer 0, it will be closest to the center window (also sometimes known as the “content window”). Increasing layers “swallow up” all layers of a lower value. This can look very similar to multiple rows, but is different because all panes in a lower level yield to panes in higher levels. The best way to understand layers is by running the AUI sample (AUI.py).

__init__(managed_window=None, agwFlags=None) [source]

Default class constructor.

Parameters:
  • managed_window – specifies the window which should be managed;
  • agwFlags – specifies options which allow the frame management behavior to be modified. agwFlags can be a combination of the following style bits:

    Flag name | Description
    AUI_MGR_ALLOW_FLOATING | Allow floating of panes
    AUI_MGR_ALLOW_ACTIVE_PANE | If a pane becomes active, “highlight” it in the interface
    AUI_MGR_TRANSPARENT_DRAG | If the platform supports it, set transparency on a floating pane while it is dragged by the user
    AUI_MGR_TRANSPARENT_HINT | If the platform supports it, show a transparent hint window when the user is about to dock a floating pane
    AUI_MGR_VENETIAN_BLINDS_HINT | Show a “venetian blind” effect when the user is about to dock a floating pane
    AUI_MGR_RECTANGLE_HINT | Show a rectangle hint effect when the user is about to dock a floating pane
    AUI_MGR_HINT_FADE | If the platform supports it, the hint window will fade in and out
    AUI_MGR_NO_VENETIAN_BLINDS_FADE | Disables the “venetian blind” fade in and out
    AUI_MGR_LIVE_RESIZE | Live resize when the user drag a sash
    AUI_MGR_ANIMATE_FRAMES | Fade-out floating panes when they are closed (all platforms which support frames transparency) and show a moving rectangle when they are docked (Windows < Vista and GTK only)
    AUI_MGR_AERO_DOCKING_GUIDES | Use the new Aero-style bitmaps as docking guides
    AUI_MGR_PREVIEW_MINIMIZED_PANES | Slide in and out minimized panes to preview them
    AUI_MGR_WHIDBEY_DOCKING_GUIDES | Use the new Whidbey-style bitmaps as docking guides
    AUI_MGR_SMOOTH_DOCKING | Performs a “smooth” docking of panes (a la PyQT)
    AUI_MGR_USE_NATIVE_MINIFRAMES | Use miniframes with native caption bar as floating panes instead or custom drawn caption bars (forced on wxMac)
    AUI_MGR_AUTONB_NO_CAPTION | Panes that merge into an automatic notebook will not have the pane caption visible

    Default value for agwFlags is: AUI_MGR_DEFAULT = AUI_MGR_ALLOW_FLOATING | AUI_MGR_TRANSPARENT_HINT | AUI_MGR_HINT_FADE | AUI_MGR_NO_VENETIAN_BLINDS_FADE

    Note

    If using the AUI_MGR_USE_NATIVE_MINIFRAMES, double-clicking on a floating pane caption will not re-dock the pane, but simply maximize it (if AuiPaneInfo.MaximizeButton() has been set to True) or do nothing.

ActivatePane(window) [source]

Activates the pane to which window is associated.

Parameters: window – a wx.Window derived window.

AddPane(window, arg1=None, arg2=None, target=None) [source]

Tells the frame manager to start managing a child window. There are four versions of this function. The first verison allows the full spectrum of pane parameter possibilities (AddPane1). The second version is used for simpler user interfaces which do not require as much configuration (AddPane2). The AddPane3 version allows a drop position to be specified, which will determine where the pane will be added. The AddPane4 version allows to turn the target AuiPaneInfo pane into a notebook and the added pane into a page.

In wxPython, simply call AddPane.

Parameters:
  • window – the child window to manage;
  • arg1 – a AuiPaneInfo or an integer value (direction);
  • arg2 – a AuiPaneInfo or a wx.Point (drop position);
  • target – a AuiPaneInfo to be turned into a notebook and new pane added to it as a page. (additionally, target can be any pane in an existing notebook)

AddPane1(window, pane_info) [source]

See comments on AddPane.

AddPane2(window, direction, caption) [source]

See comments on AddPane.

AddPane3(window, pane_info, drop_pos) [source]

See comments on AddPane.

AddPane4(window, pane_info, target) [source]

See comments on AddPane.

AnimateDocking(win_rect, pane_rect) [source]

Animates the minimization/docking of a pane a la Eclipse, using a wx.ScreenDC to draw a “moving docking rectangle” on the screen.

Parameters:
  • win_rect – the original pane screen rectangle;
  • pane_rect – the newly created toolbar/pane screen rectangle.

Note

This functionality is not available on wxMAC as this platform doesn’t have the ability to use wx.ScreenDC to draw on-screen and on Windows > Vista.

CalculateDockSizerLimits(dock) [source]

Calculates the minimum and maximum sizes allowed for the input dock.

Parameters: dock – the AuiDockInfo structure to analyze.

CalculateHintRect(pane_window, pt, offset) [source]

Calculates the drop hint rectangle.

The method first calls DoDrop to determine the exact position the pane would be at were if dropped. If the pane would indeed become docked at the specified drop point, the the rectangle hint will be returned in screen coordinates. Otherwise, an empty rectangle is returned.

Parameters:
  • pane_window – it is the window pointer of the pane being dragged;
  • pt – is the mouse position, in client coordinates;
  • offset – describes the offset that the mouse is from the upper-left corner of the item being dragged.

CalculatePaneSizerLimits(dock, pane) [source]

Calculates the minimum and maximum sizes allowed for the input pane.

Parameters:
  • dock – the AuiDockInfo structure to which pane belongs to;
  • pane – a AuiPaneInfo class for which calculation are requested.

CanDockPanel(p) [source]

Returns whether a pane can be docked or not.

Parameters: p – the AuiPaneInfo class with all the pane’s information.

CanUseModernDockArt() [source]

Returns whether ModernDockArt can be used (Windows XP / Vista / 7 only, requires Mark Hammonds’s pywin32 package).

CheckMovableSizer(part) [source]

Checks if a UI part can be actually resized.

Parameters: part – a UI part.

CheckPaneMove(pane) [source]

Checks if a pane has moved by a visible amount.

Parameters: pane – an instance of AuiPaneInfo.

ClosePane(pane_info) [source]

Destroys or hides the pane depending on its flags.

Parameters: pane_info – a AuiPaneInfo instance.

CopyTarget(target) [source]

Copies all the attributes of the input target into another AuiPaneInfo.

Parameters: target – the source AuiPaneInfo from where to copy attributes.

CreateFloatingFrame(parent, pane_info) [source]

Creates a floating frame for the windows.

Parameters:
  • parent – the floating frame parent;
  • pane_info – the AuiPaneInfo class with all the pane’s information.

CreateGuideWindows() [source]

Creates the VS2005 HUD guide windows.

CreateHintWindow() [source]

Creates the standard wxAUI hint window.

CreateNotebook() [source]

Creates an automatic AuiNotebook when a pane is docked on top of another pane.

CreateNotebookBase(panes, paneInfo) [source]

Creates an auto-notebook base from a pane, and then add that pane as a page.

Parameters:
  • panes – Set of panes to append new notebook base pane to
  • paneInfo – AuiPaneInfo instance to convert to new notebook.

DestroyGuideWindows() [source]

Destroys the VS2005 HUD guide windows.

DestroyHintWindow() [source]

Destroys the standard wxAUI hint window.

DetachPane(window) [source]

Tells the AuiManager to stop managing the pane specified by window. The window, if in a floated frame, is reparented to the frame managed by AuiManager.

Parameters: window – the window to be un-managed.

DoDrop(docks, panes, target, pt, offset=wx.Point(0, 0)) [source]

This is an important function. It basically takes a mouse position, and determines where the panes new position would be. If the pane is to be dropped, it performs the drop operation using the specified dock and pane arrays. By specifying copy dock and pane arrays when calling, a “what-if” scenario can be performed, giving precise coordinates for drop hints.

Parameters:
  • docks – a list of AuiDockInfo classes;
  • panes – a list of AuiPaneInfo instances;
  • pt – a mouse position to check for a drop operation;
  • offset – a possible offset from the input point pt.

DoDropFloatingPane(docks, panes, target, pt) [source]

Handles the situation in which the dropped pane contains a normal window.

Parameters:
  • docks – a list of AuiDockInfo classes;
  • panes – a list of AuiPaneInfo instances;
  • target – the target pane containing the window;
  • pt – a mouse position to check for a drop operation.

DoDropLayer(docks, target, dock_direction) [source]

Handles the situation in which target is a single dock guide.

Parameters:
  • docks – a list of AuiDockInfo classes;
  • target – the target pane;
  • dock_direction – the docking direction.

DoDropNonFloatingPane(docks, panes, target, pt) [source]

Handles the situation in which the dropped pane is not floating.

Parameters:
  • docks – a list of AuiDockInfo classes;
  • panes – a list of AuiPaneInfo instances;
  • target – the target pane containing the toolbar;
  • pt – a mouse position to check for a drop operation.

DoDropPane(panes, target, dock_direction, dock_layer, dock_row, dock_pos) [source]

Drop a pane in the interface.

Parameters:
  • panes – a list of AuiPaneInfo classes;
  • target – the target pane;
  • dock_direction – the docking direction;
  • dock_layer – the docking layer;
  • dock_row – the docking row;
  • dock_pos – the docking position.

DoDropRow(panes, target, dock_direction, dock_layer, dock_row) [source]

Insert a row in the interface before dropping.

Parameters:
  • panes – a list of AuiPaneInfo classes;
  • target – the target pane;
  • dock_direction – the docking direction;
  • dock_layer – the docking layer;
  • dock_row – the docking row.

DoDropToolbar(docks, panes, target, pt, offset) [source]

Handles the situation in which the dropped pane contains a toolbar.

Parameters:
  • docks – a list of AuiDockInfo classes;
  • panes – a list of AuiPaneInfo instances;
  • target – the target pane containing the toolbar;
  • pt – a mouse position to check for a drop operation;
  • offset – a possible offset from the input point pt.

DoEndResizeAction(event) [source]

Ends a resize action, or for live update, resizes the sash.

Parameters: event – a wx.MouseEvent to be processed.

DoFrameLayout() [source]

This is an internal function which invokes wx.Sizer.Layout on the frame’s main sizer, then measures all the various UI items and updates their internal rectangles.

Note

This should always be called instead of calling self._managed_window.Layout() directly.

DrawHintRect(pane_window, pt, offset) [source]

Calculates the hint rectangle by calling CalculateHintRect. If there is a rectangle, it shows it by calling ShowHint, otherwise it hides any hint rectangle currently shown.

Parameters:
  • pane_window – it is the window pointer of the pane being dragged;
  • pt – is the mouse position, in client coordinates;
  • offset – describes the offset that the mouse is from the upper-left corner of the item being dragged.

DrawPaneButton(dc, part, pt) [source]

Draws a pane button in the caption (convenience function).

Parameters:
  • dc – a wx.DC device context object;
  • part – the UI part to analyze;
  • pt – a wx.Point object, specifying the mouse location.

FireEvent(evtType, pane, canVeto=False) [source]

Fires one of the EVT_AUI_PANE_FLOATED/FLOATING/DOCKING/DOCKED/ACTIVATED event.

Parameters:
  • evtType – one of the aforementioned events;
  • pane – the AuiPaneInfo instance associated to this event;
  • canVeto – whether the event can be vetoed or not.

GetAGWFlags() [source]

Returns the current manager’s flags.

See also

SetAGWFlags for a list of possible AuiManager flags.

GetAllPanes() [source]

Returns a reference to all the pane info structures.

GetAnimationStep() [source]

Returns the animation step speed (a float) to use in AnimateDocking.

GetArtProvider() [source]

Returns the current art provider being used.

GetAttributes(pane) [source]

Returns all the attributes of a AuiPaneInfo.

Parameters: pane – a AuiPaneInfo instance.

GetAutoNotebookStyle() [source]

Returns the default AGW-specific window style for automatic notebooks.

See also

SetAutoNotebookStyle method for a list of possible styles.

GetAutoNotebookTabArt() [source]

Returns the default tab art provider for automatic notebooks.

GetDockPixelOffset(test) [source]

This is an internal function which returns a dock’s offset in pixels from the left side of the window (for horizontal docks) or from the top of the window (for vertical docks).

This value is necessary for calculating fixed-pane/toolbar offsets when they are dragged.

Parameters: test – a fake AuiPaneInfo for testing purposes.

GetDockSizeConstraint() [source]

Returns the current dock constraint values.

See also

SetDockSizeConstraint

GetFrame() [source]

Returns the window being managed by AuiManager.

Warning

This method is now deprecated, use GetManagedWindow instead.

GetManagedWindow() [source]

Returns the window being managed by AuiManager.

GetNotebooks() [source]

Returns all the automatic AuiNotebook in the AuiManager.

GetOppositeDockTotalSize(docks, direction) [source]

Returns the dimensions of the dock which lives opposite of the input dock.

Parameters:
  • docks – a list of AuiDockInfo structures to analyze;
  • direction – the direction in which to look for the opposite dock.

GetPane(item) [source]

Looks up a AuiPaneInfo structure based on the supplied window pointer. Upon failure, GetPane returns an empty AuiPaneInfo, a condition which can be checked by calling AuiPaneInfo.IsOk().

The pane info’s structure may then be modified. Once a pane’s info is modified, Update must be called to realize the changes in the UI.

Parameters: item – either a pane name or a wx.Window.

GetPaneByName(name) [source]

This version of GetPane looks up a pane based on a ‘pane name’.

Parameters: name – the pane name.

See also

GetPane

GetPaneByWidget(window) [source]

This version of GetPane looks up a pane based on a ‘pane window’.

Parameters: window – a wx.Window derived window.

See also

GetPane

GetPanePart(wnd) [source]

Looks up the pane border UI part of the pane specified. This allows the caller to get the exact rectangle of the pane in question, including decorations like caption and border.

Parameters: wnd – the window to which the pane border belongs to.

GetPanePositionsAndSizes(dock) [source]

Returns all the panes positions and sizes in a dock.

Parameters: dock – a AuiDockInfo instance.

GetPartSizerRect(uiparts) [source]

Returns the rectangle surrounding the specified UI parts.

Parameters: uiparts – UI parts.

GetPartnerDock(dock) [source]

Returns the partner dock for the input dock.

Parameters: dock – a AuiDockInfo instance.

GetPartnerPane(dock, pane) [source]

Returns the partner pane for the input pane. They both need to live in the same AuiDockInfo.

Parameters:
  • dock – a AuiDockInfo instance;
  • pane – a AuiPaneInfo class.

GetSnapPosition() [source]

Returns the main frame snapping position.

GetTotalPixSizeAndProportion(dock) [source]

Returns the dimensions and proportion of the input dock.

Parameters: dock – the AuiDockInfo structure to analyze.

HideHint() [source]

Hides a transparent window hint if there is one.

HitTest(x, y) [source]

This is an internal function which determines which UI item the specified coordinates are over.

Parameters:
  • x – specifies a x position in client coordinates;
  • y – specifies a y position in client coordinates.

InsertPane(window, pane_info, insert_level=AUI_INSERT_PANE) [source]

This method is used to insert either a previously unmanaged pane window into the frame manager, or to insert a currently managed pane somewhere else. InsertPane will push all panes, rows, or docks aside and insert the window into the position specified by pane_info.

Because pane_info can specify either a pane, dock row, or dock layer, the insert_level parameter is used to disambiguate this. The parameter insert_level can take a value of AUI_INSERT_PANE, AUI_INSERT_ROW or AUI_INSERT_DOCK.

Parameters:
  • window – the window to be inserted and managed;
  • pane_info – the insert location for the new window;
  • insert_level – the insertion level of the new pane.

IsPaneButtonVisible(part) [source]

Returns whether a pane button in the pane caption is visible.

Parameters: part – the UI part to analyze.

LayoutAddDock(cont, dock, uiparts, spacer_only) [source]

Adds a dock into the existing layout.

Parameters:
  • cont – a wx.Sizer object;
  • dock – the AuiDockInfo structure to add to the layout;
  • uiparts – a list of UI parts in the interface;
  • spacer_only – whether to add a simple spacer or a real window.

LayoutAddPane(cont, dock, pane, uiparts, spacer_only) [source]

Adds a pane into the existing layout (in an existing dock).

Parameters:
  • cont – a wx.Sizer object;

  • dock – the AuiDockInfo structure in which to add the pane;
  • pane – the AuiPaneInfo instance to add to the dock;
  • uiparts – a list of UI parts in the interface;
  • spacer_only – whether to add a simple spacer or a real window.

LayoutAll(panes, docks, uiparts, spacer_only=False, oncheck=True) [source]

Layouts all the UI structures in the interface.

Parameters:
  • panes – a list of AuiPaneInfo instances;
  • docks – a list of AuiDockInfo classes;
  • uiparts – a list of UI parts in the interface;
  • spacer_only – whether to add a simple spacer or a real window;
  • oncheck – whether to store the results in a class member or not.

LoadPaneInfo(pane_part, pane) [source]

This method is similar to to LoadPerspective, with the exception that it only loads information about a single pane. It is used in combination with SavePaneInfo.

Parameters:
  • pane_part – the string to analyze;
  • pane – the AuiPaneInfo structure in which to load pane_part.

LoadPerspective(layout, update=True) [source]

Loads a layout which was saved with SavePerspective.

If the update flag parameter is True, Update will be automatically invoked, thus realizing the saved perspective on screen.

Parameters:
  • layout – a string which contains a saved AUI layout;
  • update – whether to update immediately the window or not.

MaximizePane(pane_info, savesizes=True) [source]

Maximizes the input pane.

Parameters:
  • pane_info – a AuiPaneInfo instance.
  • savesizes – whether to save previous dock sizes.

MinimizePane(paneInfo) [source]

Minimizes a pane in a newly and automatically created AuiToolBar.

Clicking on the minimize button causes a new AuiToolBar to be created and added to the frame manager (currently the implementation is such that panes at West will have a toolbar at the right, panes at South will have toolbars at the bottom etc...) and the pane is hidden in the manager.

Clicking on the restore button on the newly created toolbar will result in the toolbar being removed and the original pane being restored.

Parameters: paneInfo – a AuiPaneInfo instance for the pane to be minimized.

OnCaptionDoubleClicked(pane_window) [source]

Handles the mouse double click on the pane caption.

Parameters: pane_window – a wx.Window derived window, managed by the pane.

OnCaptureLost(event) [source]

Handles the wx.EVT_MOUSE_CAPTURE_LOST event for AuiManager.

Parameters: event – a wx.MouseCaptureLostEvent to be processed.

OnChildFocus(event) [source]

Handles the wx.EVT_CHILD_FOCUS event for AuiManager.

Parameters: event – a wx.ChildFocusEvent to be processed.

OnEraseBackground(event) [source]

Handles the wx.EVT_ERASE_BACKGROUND event for AuiManager.

Parameters: event – wx.EraseEvent to be processed.

Note

This is intentionally empty (excluding wxMAC) to reduce flickering while drawing.

OnFindManager(event) [source]

Handles the EVT_AUI_FIND_MANAGER event for AuiManager.

Parameters: event – a AuiManagerEvent event to be processed.

OnFloatingPaneActivated(wnd) [source]

Handles the activation event of a floating pane.

Parameters: wnd – a wx.Window derived window, managed by the pane.

OnFloatingPaneClosed(wnd, event) [source]

Handles the close event of a floating pane.

Parameters:
  • wnd – a wx.Window derived window, managed by the pane;

  • event – a wx.CloseEvent to be processed.

OnFloatingPaneMoved(wnd, eventOrPt) [source]

Handles the move event of a floating pane.

Parameters:
  • wnd – a wx.Window derived window, managed by the pane;

  • eventOrPt – a wx.MoveEvent to be processed or an instance of wx.Point.

OnFloatingPaneResized(wnd, size) [source]

Handles the resizing of a floating pane.

Parameters:
  • wnd – a wx.Window derived window, managed by the pane;

  • size – a wx.Size object, specifying the new pane floating size.

OnGripperClicked(pane_window, start, offset) [source]

Handles the mouse click on the pane gripper.

Parameters:
  • pane_window – a wx.Window derived window, managed by the pane;

  • start – a wx.Point object, specifying the clicking position;

  • offset – an offset point from the start position.

OnHintFadeTimer(event) [source]

Handles the wx.EVT_TIMER event for AuiManager.

Parameters: event – a wx.TimerEvent to be processed.

OnLeaveWindow(event) [source]

Handles the wx.EVT_LEAVE_WINDOW event for AuiManager.

Parameters: event – a wx.MouseEvent to be processed.

OnLeftDClick(event) [source]

Handles the wx.EVT_LEFT_DCLICK event for AuiManager.

Parameters: event – a wx.MouseEvent to be processed.

OnLeftDown(event) [source]

Handles the wx.EVT_LEFT_DOWN event for AuiManager.

Parameters: event – a wx.MouseEvent to be processed.

OnLeftUp(event) [source]

Handles the wx.EVT_LEFT_UP event for AuiManager.

Parameters: event – a wx.MouseEvent to be processed.

OnLeftUp_ClickButton(event) [source]

Sub-handler for the OnLeftUp event.

Parameters: event – a wx.MouseEvent to be processed.

OnLeftUp_DragFloatingPane(eventOrPt) [source]

Sub-handler for the OnLeftUp event.

Parameters: event – a wx.MouseEvent to be processed.

OnLeftUp_DragToolbarPane(eventOrPt) [source]

Sub-handler for the OnLeftUp event.

Parameters: event – a wx.MouseEvent to be processed.

OnLeftUp_Resize(event) [source]

Sub-handler for the OnLeftUp event.

Parameters: event – a wx.MouseEvent to be processed.

OnMotion(event) [source]

Handles the wx.EVT_MOTION event for AuiManager.

Parameters: event – a wx.MouseEvent to be processed.

OnMotion_ClickCaption(event) [source]

Sub-handler for the OnMotion event.

Parameters: event – a wx.MouseEvent to be processed.

OnMotion_DragFloatingPane(eventOrPt) [source]

Sub-handler for the OnMotion event.

Parameters: event – a wx.MouseEvent to be processed.

OnMotion_DragToolbarPane(eventOrPt) [source]

Sub-handler for the OnMotion event.

Parameters: event – a wx.MouseEvent to be processed.

OnMotion_Other(event) [source]

Sub-handler for the OnMotion event.

Parameters: event – a wx.MouseEvent to be processed.

OnMotion_Resize(event) [source]

Sub-handler for the OnMotion event.

Parameters: event – a wx.MouseEvent to be processed.

OnMove(event) [source]

Handles the wx.EVT_MOVE event for AuiManager.

Parameters: event – a wx.MoveEvent to be processed.

OnPaint(event) [source]

Handles the wx.EVT_PAINT event for AuiManager.

Parameters: event – an instance of wx.PaintEvent to be processed.

OnPaneButton(event) [source]

Handles the EVT_AUI_PANE_BUTTON event for AuiManager.

Parameters: event – a AuiManagerEvent event to be processed.

OnPaneDocked(event) [source]

Handles the EVT_AUI_PANE_DOCKED event for AuiManager.

Parameters: event – an instance of AuiManagerEvent to be processed.

OnRender(event) [source]

Draws all of the pane captions, sashes, backgrounds, captions, grippers, pane borders and buttons. It renders the entire user interface. It binds the EVT_AUI_RENDER event.

Parameters: event – an instance of AuiManagerEvent.

OnRestoreMinimizedPane(event) [source]

Handles the EVT_AUI_PANE_MIN_RESTORE event for AuiManager.

Parameters: event – an instance of AuiManagerEvent to be processed.

OnSetCursor(event) [source]

Handles the wx.EVT_SET_CURSOR event for AuiManager.

Parameters: event – a wx.SetCursorEvent to be processed.

OnSize(event) [source]

Handles the wx.EVT_SIZE event for AuiManager.

Parameters: event – a wx.SizeEvent to be processed.

OnSysColourChanged(event) [source]

Handles the wx.EVT_SYS_COLOUR_CHANGED event for AuiManager.

Parameters: event – a wx.SysColourChangedEvent to be processed.

OnTabBeginDrag(event) [source]

Handles the EVT_AUINOTEBOOK_BEGIN_DRAG event.

Parameters: event – a AuiNotebookEvent event to be processed.

OnTabPageClose(event) [source]

Handles the EVT_AUINOTEBOOK_PAGE_CLOSE event.

Parameters: event – a AuiNotebookEvent event to be processed.

OnTabSelected(event) [source]

Handles the EVT_AUINOTEBOOK_PAGE_CHANGED event.

Parameters: event – a AuiNotebookEvent event to be processed.

PaneFromTabEvent(event) [source]

Returns a AuiPaneInfo from a AuiNotebookEvent event.

Parameters: event – a AuiNotebookEvent event.

PaneHitTest(panes, pt) [source]

Similar to HitTest, but it checks in which AuiPaneInfo rectangle the input point belongs to.

Parameters:
  • panes – a list of AuiPaneInfo instances;
  • pt – a wx.Point object.

ProcessDockResult(target, new_pos) [source]

This is a utility function used by DoDrop - it checks if a dock operation is allowed, the new dock position is copied into the target info. If the operation was allowed, the function returns True.

Parameters:
  • target – the AuiPaneInfo instance to be docked;
  • new_pos – the new docking position if the docking operation is allowed.

ProcessMgrEvent(event) [source]

Process the AUI events sent to the manager.

Parameters: event – the event to process, an instance of AuiManagerEvent.

RefreshButton(part) [source]

Refreshes a pane button in the caption.

Parameters: part – the UI part to analyze.

RefreshCaptions() [source]

Refreshes all pane captions.

RemoveAutoNBCaption(pane) [source]

Removes the caption on newly created automatic notebooks.

Parameters: pane – an instance of AuiPaneInfo (the target notebook).

Render(dc) [source]

Fires a render event, which is normally handled by OnRender. This allows the render function to be overridden via the render event.

This can be useful for painting custom graphics in the main window. Default behavior can be invoked in the overridden function by calling OnRender.

Parameters: dc – a wx.DC device context object.

Repaint(dc=None) [source]

Repaints the entire frame decorations (sashes, borders, buttons and so on). It renders the entire user interface.

Parameters: dc – if not None, an instance of wx.PaintDC.

RepositionPane(pane, wnd_pos, wnd_size) [source]

Repositions a pane after the main frame has been moved/resized.

Parameters:
  • pane – a AuiPaneInfo instance;
  • wnd_pos – the main frame position;
  • wnd_size – the main frame size.

RequestUserAttention(pane_window) [source]

Requests the user attention by intermittently highlighting the pane caption.

Parameters: pane_window – a wx.Window derived window, managed by the pane.

RestoreMaximizedPane() [source]

Restores the current maximized pane (if any).

RestoreMinimizedPane(paneInfo) [source]

Restores a previously minimized pane.

Parameters: paneInfo – a AuiPaneInfo instance for the pane to be restored.

RestorePane(pane_info) [source]

Restores the input pane from a previous maximized or minimized state.

Parameters: pane_info – a AuiPaneInfo instance.

RestrictResize(clientPt, screenPt, createDC) [source]

Common method between DoEndResizeAction and OnLeftUp_Resize.

SavePaneInfo(pane) [source]

This method is similar to SavePerspective, with the exception that it only saves information about a single pane. It is used in combination with LoadPaneInfo.

Parameters: pane – a AuiPaneInfo instance to save.

SavePerspective() [source]

Saves the entire user interface layout into an encoded string, which can then be stored by the application (probably using wx.Config).

When a perspective is restored using LoadPerspective, the entire user interface will return to the state it was when the perspective was saved.

SavePreviousDockSizes(pane_info) [source]

Stores the previous dock sizes, to be used in a “restore” action later.

Parameters: pane_info – a AuiPaneInfo instance.

SetAGWFlags(agwFlags) [source]

This method is used to specify AuiManager‘s settings flags.

Parameters: agwFlags – specifies options which allow the frame management behavior to be modified. agwFlags can be one of the following style bits:

Flag name | Description
AUI_MGR_ALLOW_FLOATING | Allow floating of panes
AUI_MGR_ALLOW_ACTIVE_PANE | If a pane becomes active, “highlight” it in the interface
AUI_MGR_TRANSPARENT_DRAG | If the platform supports it, set transparency on a floating pane while it is dragged by the user
AUI_MGR_TRANSPARENT_HINT | If the platform supports it, show a transparent hint window when the user is about to dock a floating pane
AUI_MGR_VENETIAN_BLINDS_HINT | Show a “venetian blind” effect when the user is about to dock a floating pane
AUI_MGR_RECTANGLE_HINT | Show a rectangle hint effect when the user is about to dock a floating pane
AUI_MGR_HINT_FADE | If the platform supports it, the hint window will fade in and out
AUI_MGR_NO_VENETIAN_BLINDS_FADE | Disables the “venetian blind” fade in and out
AUI_MGR_LIVE_RESIZE | Live resize when the user drag a sash
AUI_MGR_ANIMATE_FRAMES | Fade-out floating panes when they are closed (all platforms which support frames transparency) and show a moving rectangle when they are docked (Windows < Vista and GTK only)
AUI_MGR_AERO_DOCKING_GUIDES | Use the new Aero-style bitmaps as docking guides
AUI_MGR_PREVIEW_MINIMIZED_PANES | Slide in and out minimized panes to preview them
AUI_MGR_WHIDBEY_DOCKING_GUIDES | Use the new Whidbey-style bitmaps as docking guides
AUI_MGR_SMOOTH_DOCKING | Performs a “smooth” docking of panes (a la PyQT)
AUI_MGR_USE_NATIVE_MINIFRAMES | Use miniframes with native caption bar as floating panes instead or custom drawn caption bars (forced on wxMac)
AUI_MGR_AUTONB_NO_CAPTION | Panes that merge into an automatic notebook will not have the pane caption visible

Note

If using the AUI_MGR_USE_NATIVE_MINIFRAMES, double-clicking on a floating pane caption will not re-dock the pane, but simply maximize it (if AuiPaneInfo.MaximizeButton() has been set to True) or do nothing.

SetAnimationStep(step) [source]

Sets the animation step speed (a float) to use in AnimateDocking.

Parameters: step – a floating point value for the animation speed.

SetArtProvider(art_provider) [source]

Instructs AuiManager to use art provider specified by the parameter art_provider for all drawing calls. This allows plugable look-and-feel features.

Parameters: art_provider – a AUI dock art provider.

Note

The previous art provider object, if any, will be deleted by AuiManager.

SetAttributes(pane, attrs) [source]

Sets all the attributes contained in attrs to a AuiPaneInfo.

Parameters:
  • pane – a AuiPaneInfo instance;
  • attrs – a list of attributes.

SetAutoNotebookStyle(agwStyle) [source]

Sets the default AGW-specific window style for automatic notebooks.

Parameters: agwStyle – the underlying AuiNotebook window style. This can be a combination of the following bits:

Flag name | Description
AUI_NB_TOP | With this style, tabs are drawn along the top of the notebook
AUI_NB_LEFT | With this style, tabs are drawn along the left of the notebook. Not implemented yet.
AUI_NB_RIGHT | With this style, tabs are drawn along the right of the notebook. Not implemented yet.
AUI_NB_BOTTOM | With this style, tabs are drawn along the bottom of the notebook
AUI_NB_TAB_SPLIT | Allows the tab control to be split by dragging a tab
AUI_NB_TAB_MOVE | Allows a tab to be moved horizontally by dragging
AUI_NB_TAB_EXTERNAL_MOVE | Allows a tab to be moved to another tab control
AUI_NB_TAB_FIXED_WIDTH | With this style, all tabs have the same width
AUI_NB_SCROLL_BUTTONS | With this style, left and right scroll buttons are displayed
AUI_NB_WINDOWLIST_BUTTON | With this style, a drop-down list of windows is available
AUI_NB_CLOSE_BUTTON | With this style, a close button is available on the tab bar
AUI_NB_CLOSE_ON_ACTIVE_TAB | With this style, a close button is available on the active tab
AUI_NB_CLOSE_ON_ALL_TABS | With this style, a close button is available on all tabs
AUI_NB_MIDDLE_CLICK_CLOSE | Allows to close AuiNotebook tabs by mouse middle button click
AUI_NB_SUB_NOTEBOOK | This style is used by {AuiManager} to create automatic AuiNotebooks
AUI_NB_HIDE_ON_SINGLE_TAB | Hides the tab window if only one tab is present
AUI_NB_SMART_TABS | Use Smart Tabbing, like Alt + Tab on Windows
AUI_NB_USE_IMAGES_DROPDOWN | Uses images on dropdown window list menu instead of check items
AUI_NB_CLOSE_ON_TAB_LEFT | Draws the tab close button on the left instead of on the right (a la Camino browser)
AUI_NB_TAB_FLOAT | Allows the floating of single tabs. Known limitation: when the notebook is more or less full screen, tabs cannot be dragged far enough outside of the notebook to become floating pages
AUI_NB_DRAW_DND_TAB | Draws an image representation of a tab while dragging (on by default)

SetAutoNotebookTabArt(art) [source]

Sets the default tab art provider for automatic notebooks.

Parameters: art – a tab art provider.

SetDockSizeConstraint(width_pct, height_pct) [source]

When a user creates a new dock by dragging a window into a docked position, often times the large size of the window will create a dock that is unwieldly large.

AuiManager by default limits the size of any new dock to 1/3 of the window size. For horizontal docks, this would be 1/3 of the window height. For vertical docks, 1/3 of the width. Calling this function will adjust this constraint value.

The numbers must be between 0.0 and 1.0. For instance, calling SetDockSizeConstraint with (0.5, 0.5) will cause new docks to be limited to half of the size of the entire managed window.

Parameters:
  • width_pct – a float number representing the x dock size constraint;
  • width_pct – a float number representing the y dock size constraint.

SetFrame(managed_window) [source]

Called to specify the frame or window which is to be managed by AuiManager. Frame management is not restricted to just frames. Child windows or custom controls are also allowed.

Parameters: managed_window – specifies the window which should be managed by the AUI manager.

Warning

This method is now deprecated, use SetManagedWindow instead.

SetManagedWindow(managed_window) [source]

Called to specify the frame or window which is to be managed by AuiManager. Frame management is not restricted to just frames. Child windows or custom controls are also allowed.

Parameters: managed_window – specifies the window which should be managed by the AUI manager.

SetMasterManager(manager) [source]

Sets the master manager for an automatic AuiNotebook.

Parameters: manager – an instance of AuiManager.

SetSnapLimits(x, y) [source]

Modifies the snap limits used when snapping the managed_window to the screen (using SnapToScreen) or when snapping the floating panes to one side of the managed_window (using SnapPane).

To change the limit after which the managed_window or the floating panes are automatically stickled to the screen border (or to the managed_window side), set these two variables. Default values are 15 pixels.

Parameters:
  • x – the minimum horizontal distance below which the snap occurs;
  • y – the minimum vertical distance below which the snap occurs.

ShowHint(rect) [source]

Shows the AUI hint window.

Parameters: rect – the hint rect calculated in advance.

ShowPane(window, show) [source]

Shows or hides a pane based on the window passed as input.

Parameters:
  • window – a wx.Window derived window;

  • show – True to show the pane, False otherwise.

SlideIn(event) [source]

Handles the wx.EVT_TIMER event for AuiManager.

Parameters: event – a wx.TimerEvent to be processed.

Note

This is used solely for sliding in and out minimized panes.

SlideOut() [source]

Slides out a preview of a minimized pane.

Note

This is used solely for sliding in and out minimized panes.

SmartShrink(docks, direction) [source]

Used to intelligently shrink the docks’ size (if needed).

Parameters:
  • docks – a list of AuiDockInfo instances;
  • direction – the direction in which to shrink.

SmoothDock(paneInfo) [source]

This method implements a smooth docking effect for floating panes, similar to what the PyQT library does with its floating windows.

Parameters: paneInfo – an instance of AuiPaneInfo.

Note

The smooth docking effect can only be used if you set the AUI_MGR_SMOOTH_DOCKING style to AuiManager.

Snap() [source]

Snaps the main frame to specified position on the screen.

See also

SnapToScreen

SnapPane(pane, pane_pos, pane_size, toSnap=False) [source]

Snaps a floating pane to one of the main frame sides.

Parameters:
  • pane – a AuiPaneInfo instance;
  • pane_pos – the new pane floating position;
  • pane_size – the new pane floating size;
  • toSnap – a bool variable to check if SnapPane was called from a move event.

SnapToScreen(snap=True, monitor=0, hAlign=wx.RIGHT, vAlign=wx.TOP) [source]

Snaps the main frame to specified position on the screen.

Parameters:
  • snap – whether to snap the main frame or not;
  • monitor – the monitor display in which snapping the window;
  • hAlign – the horizontal alignment of the snapping position;
  • vAlign – the vertical alignment of the snapping position.

StartPreviewTimer(toolbar) [source]

Starts a timer for sliding in and out a minimized pane.

Parameters: toolbar – the AuiToolBar containing the minimized pane tool.

StopPreviewTimer() [source]

Stops a timer for sliding in and out a minimized pane.

SwitchToolBarOrientation(pane) [source]

Switches the toolbar orientation from vertical to horizontal and vice-versa. This is especially useful for vertical docked toolbars once they float.

Parameters: pane – an instance of AuiPaneInfo, which may have a AuiToolBar window associated with it.

UnInit() [source]

Uninitializes the framework and should be called before a managed frame or window is destroyed. UnInit is usually called in the managed wx.Frame / wx.Window destructor.

It is necessary to call this function before the managed frame or window is destroyed, otherwise the manager cannot remove its custom event handlers from a window.

Update() [source]

This method is called after any number of changes are made to any of the managed panes. Update must be invoked after AddPane or InsertPane are called in order to “realize” or “commit” the changes.

In addition, any number of changes may be made to AuiPaneInfo structures (retrieved with GetPane), but to realize the changes, Update must be called. This construction allows pane flicker to be avoided by updating the whole layout at one time.

UpdateButtonOnScreen(button_ui_part, event) [source]

Updates/redraws the UI part containing a pane button.

Parameters:
  • button_ui_part – the UI part the button belongs to;
  • event – a wx.MouseEvent to be processed.

UpdateDockingGuides(paneInfo) [source]

Updates the docking guide windows positions and appearance.

Parameters: paneInfo – a AuiPaneInfo instance.

UpdateNotebook() [source]

Updates the automatic AuiNotebook in the layout (if any exists).

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • infobar
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • aui library »
  • aui.framemanager »
  • AuiManager


AuiManager_DCP

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • aui library »
  • aui.framemanager »
  • AuiManager_DCP

AuiManager_DCP

A class similar to AuiManager but with a Dummy Center Pane (DCP). The code for this class is still flickery due to the call to wx.CallAfter and the double-update call.

hierarchy Inheritance Diagram

Inheritance diagram for: AuiManager_DCP

Inheritance diagram of AuiManager_DCP

supclasses Known Superclasses

  • aui.framemanager.AuiManager

Methods Summary

__init__ |
Update | This method is called after any number of changes are made to any of the managed panes.
_createDummyPane | Creates a Dummy Center Pane (DCP).
_destroyDummyPane | Destroys the Dummy Center Pane (DCP).

API Class API

class AuiManager_DCP(AuiManager) [source]

A class similar to AuiManager but with a Dummy Center Pane (DCP). The code for this class is still flickery due to the call to wx.CallAfter and the double-update call.

__init__() [source]

Update() [source]

This method is called after any number of changes are made to any of the managed panes. Update must be invoked after AuiManager.AddPane() or AuiManager.InsertPane() are called in order to “realize” or “commit” the changes.

In addition, any number of changes may be made to AuiPaneInfo structures (retrieved with AuiManager.GetPane()), but to realize the changes, Update must be called. This construction allows pane flicker to be avoided by updating the whole layout at one time.

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • infobar
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • aui library »
  • aui.framemanager »
  • AuiManager_DCP


AuiManagerEvent

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • aui library »
  • aui.framemanager »
  • AuiManagerEvent

AuiManagerEvent

A specialized command event class for events sent by AuiManager.

hierarchy Inheritance Diagram

Inheritance diagram for: AuiManagerEvent

Inheritance diagram of AuiManagerEvent

Methods Summary

__init__ | Default class constructor.
CanVeto | Returns whether the event can be vetoed and has been vetoed.
GetButton | Returns the associated AuiPaneButton instance (if any).
GetDC | Returns the associated wx.DC device context (if any).
GetManager | Returns the associated AuiManager (if any).
GetPane | Returns the associated AuiPaneInfo structure (if any).
GetVeto | Returns whether the event has been vetoed or not.
SetButton | Associates a AuiPaneButton instance to this event.
SetCanVeto | Sets whether the event can be vetoed or not.
SetDC | Associates a wx.DC device context to this event.
SetManager | Associates a AuiManager to the current event.
SetPane | Associates a AuiPaneInfo instance to this event.
Veto | Prevents the change announced by this event from happening.

API Class API

class AuiManagerEvent(wx.PyCommandEvent) [source]

A specialized command event class for events sent by AuiManager.

__init__(eventType, id=1) [source]

Default class constructor.

Parameters:
  • eventType – the event kind;
  • id – the event identification number.

CanVeto() [source]

Returns whether the event can be vetoed and has been vetoed.

GetButton() [source]

Returns the associated AuiPaneButton instance (if any).

GetDC() [source]

Returns the associated wx.DC device context (if any).

GetManager() [source]

Returns the associated AuiManager (if any).

GetPane() [source]

Returns the associated AuiPaneInfo structure (if any).

GetVeto() [source]

Returns whether the event has been vetoed or not.

SetButton(b) [source]

Associates a AuiPaneButton instance to this event.

Parameters: b – a AuiPaneButton instance.

SetCanVeto(can_veto) [source]

Sets whether the event can be vetoed or not.

Parameters: can_veto – a bool flag. True if the event can be vetoed, False otherwise.

SetDC(pdc) [source]

Associates a wx.DC device context to this event.

Parameters: pdc – a wx.DC device context object.

SetManager(mgr) [source]

Associates a AuiManager to the current event.

Parameters: mgr – an instance of AuiManager.

SetPane(p) [source]

Associates a AuiPaneInfo instance to this event.

Parameters: p – a AuiPaneInfo instance.

Veto(veto=True) [source]

Prevents the change announced by this event from happening.

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

Parameters: veto – True to veto the event, False otherwise.

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • infobar
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • aui library »
  • aui.framemanager »
  • AuiManagerEvent


AuiPaneButton

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • aui library »
  • aui.framemanager »
  • AuiPaneButton

AuiPaneButton

A simple class which describes the caption pane button attributes.

hierarchy Inheritance Diagram

Inheritance diagram for: AuiPaneButton

Inheritance diagram of AuiPaneButton

Methods Summary

__init__ Default class constructor.

API Class API

class AuiPaneButton(object) [source]

A simple class which describes the caption pane button attributes.

__init__(button_id) [source]

Default class constructor. Used internally, do not call it in your code!

Parameters: button_id – the pane button identifier.

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • infobar
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • aui library »
  • aui.framemanager »
  • AuiPaneButton


AuiPaneInfo

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • aui library »
  • aui.framemanager »
  • AuiPaneInfo

AuiPaneInfo

AuiPaneInfo specifies all the parameters for a pane. These parameters specify where the pane is on the screen, whether it is docked or floating, or hidden. In addition, these parameters specify the pane’s docked position, floating position, preferred size, minimum size, caption text among many other parameters.

hierarchy Inheritance Diagram

Inheritance diagram for: AuiPaneInfo

Inheritance diagram of AuiPaneInfo

Methods Summary

__init__ | Default class constructor.
BestSize | Sets the ideal size for the pane.
BestSize1 | Sets the best size of the pane.
BestSize2 | Sets the best size of the pane.
Bottom | Sets the pane dock position to the bottom of the frame.
BottomDockable | Indicates whether a pane can be docked at the bottom of the frame.
BottomSnappable | Indicates whether a pane can be snapped at the bottom of the main frame.
Caption | Sets the caption of the pane.
CaptionVisible | Indicates that a pane caption should be visible.
Center | Sets the pane to the center position of the frame.
CenterPane | Specifies that the pane should adopt the default center pane settings.
Centre | Sets the pane to the center position of the frame.
CentrePane | Specifies that the pane should adopt the default center pane settings.
CloseButton | Indicates that a close button should be drawn for the pane.
CountButtons | Returns the number of visible buttons in the docked pane.
DefaultPane | Specifies that the pane should adopt the default pane settings.
DestroyOnClose | Indicates whether a pane should be destroyed when it is closed.
Direction | Determines the direction of the docked pane.
Dock | Indicates that a pane should be docked.
DockFixed | Causes the containing dock to have no resize sash.
Dockable | Specifies whether a frame can be docked or not.
Fixed | Forces a pane to be fixed size so that it cannot be resized.
Float | Indicates that a pane should be floated.
Floatable | Sets whether the user will be able to undock a pane and turn it into a floating window.
FloatingPosition | Sets the position of the floating pane.
FloatingSize | Sets the size of the floating pane.
FlyOut | Indicates whether a pane, when floating, has a “fly-out” effect (i.e., floating panes which only show themselves when moused over).
GetMinimizeMode | Returns the minimization style for this pane.
Gripper | Indicates that a gripper should be drawn for the pane.
GripperTop | Indicates that a gripper should be drawn at the top of the pane.
HasBorder | Returns True if the pane displays a border.
HasCaption | Returns True if the pane displays a caption.
HasCaptionLeft | Returns True if the pane displays a caption on the left (rotated by 90 degrees).
HasCloseButton | Returns True if the pane displays a button to close the pane.
HasFlag | Returns True if the the property specified by flag is active for the pane.
HasGripper | Returns True if the pane displays a gripper.
HasGripperTop | Returns True if the pane displays a gripper at the top.
HasMaximizeButton | Returns True if the pane displays a button to maximize the pane.
HasMinimizeButton | Returns True if the pane displays a button to minimize the pane.
HasNotebook | Returns whether a pane has a AuiNotebook or not.
HasPinButton | Returns True if the pane displays a button to float the pane.
Hide | Indicates that a pane should be hidden.
Icon | Specifies whether an icon is drawn on the left of the caption text when the pane is docked.
IsBottomDockable | Returns True if the pane can be docked at the bottom
IsBottomSnappable | Returns True if the pane can be snapped at the bottom of the managed frame.
IsDestroyOnClose | Returns True if the pane should be destroyed when it is closed.
IsDockable | Returns True if the pane can be docked.
IsDocked | Returns True if the pane is docked.
IsFixed | Returns True if the pane cannot be resized.
IsFloatable | Returns True if the pane can be undocked and displayed as a
IsFloating | Returns True if the pane is floating.
IsFlyOut | Returns True if the floating pane has a “fly-out” effect.
IsHorizontal | Returns True if the pane dock_direction is horizontal.
IsLeftDockable | Returns True if the pane can be docked at the left
IsLeftSnappable | Returns True if the pane can be snapped on the left of the managed frame.
IsMaximized | Returns True if the pane is maximized.
IsMinimized | Returns True if the pane is minimized.
IsMovable | Returns True if the docked frame can be undocked or moved to
IsNotebookControl | Returns whether the pane is a notebook control (AuiNotebook).
IsNotebookDockable | Returns True if a pane can be docked on top to another to create a
IsNotebookPage | Returns whether the pane is a notebook page in a AuiNotebook.
IsOk | Returns True if the AuiPaneInfo structure is valid.
IsResizeable | Returns True if the pane can be resized.
IsRightDockable | Returns True if the pane can be docked at the right
IsRightSnappable | Returns True if the pane can be snapped on the right of the managed frame.
IsShown | Returns True if the pane is currently shown.
IsSnappable | Returns True if the pane can be snapped.
IsToolbar | Returns True if the pane contains a toolbar.
IsTopDockable | Returns True if the pane can be docked at the top
IsTopSnappable | Returns True if the pane can be snapped at the top of the managed frame.
IsVertical | Returns True if the pane dock_direction is vertical.
Layer | Determines the layer of the docked pane.
Left | Sets the pane dock position to the left side of the frame.
LeftDockable | Indicates whether a pane can be docked on the left of the frame.
LeftSnappable | Indicates whether a pane can be snapped on the left of the main frame.
MaxSize | Sets the maximum size of the pane.
MaxSize1 | Sets the maximum size of the pane.
MaxSize2 | Sets the maximum size of the pane.
Maximize | Makes the pane take up the full area.
MaximizeButton | Indicates that a maximize button should be drawn for the pane.
MinSize | Sets the minimum size of the pane.
MinSize1 | Sets the minimum size of the pane.
MinSize2 | Sets the minimum size of the pane.
Minimize | Makes the pane minimized in a AuiToolBar.
MinimizeButton | Indicates that a minimize button should be drawn for the pane.
MinimizeMode | Sets the expected minimized mode if the MinimizeButton() is visible.
MinimizeTarget | Minimizes the panes using a AuiPaneInfo as a target. As AuiPaneInfo properties
Movable | Indicates whether a pane can be moved.
Name | Sets the name of the pane so it can be referenced in lookup functions.
NotebookControl | Forces a pane to be a notebook control (AuiNotebook).
NotebookDockable | Indicates whether a pane can be docked in an automatic AuiNotebook.
NotebookPage | Forces a pane to be a notebook page, so that the pane can be
PaneBorder | Indicates that a border should be drawn for the pane.
PinButton | Indicates that a pin button should be drawn for the pane.
Position | Determines the position of the docked pane.
ResetButtons | Resets all the buttons and recreates them from scratch depending on the
Resizable | Allows a pane to be resizable if resizable is True, and forces
Restore | Is the reverse of Maximize and Minimize.
Right | Sets the pane dock position to the right side of the frame.
RightDockable | Indicates whether a pane can be docked on the right of the frame.
RightSnappable | Indicates whether a pane can be snapped on the right of the main frame.
Row | Determines the row of the docked pane.
SetDockPos | Copies the source pane members that pertain to docking position to self.
SetFlag | Turns the property given by flag on or off with the option_state parameter.
SetNameFromNotebookId | Sets the pane name once docked in a AuiNotebook using the notebook id.
Show | Indicates that a pane should be shown.
Snappable | Indicates whether a pane can be snapped on the main frame.
ToolbarPane | Specifies that the pane should adopt the default toolbar pane settings.
Top | Sets the pane dock position to the top of the frame.
TopDockable | Indicates whether a pane can be docked at the top of the frame.
TopSnappable | Indicates whether a pane can be snapped at the top of the main frame.
Transparent | Makes the pane transparent when floating.
Window | Associate a wx.Window derived window to this pane.
dock_direction_get | Getter for the dock_direction.
dock_direction_set | Setter for the dock_direction.

API Class API

class AuiPaneInfo(object) [source]

AuiPaneInfo specifies all the parameters for a pane. These parameters specify where the pane is on the screen, whether it is docked or floating, or hidden. In addition, these parameters specify the pane’s docked position, floating position, preferred size, minimum size, caption text among many other parameters.

__init__() [source]

Default class constructor.

BestSize(arg1=None, arg2=None) [source]

Sets the ideal size for the pane. The docking manager will attempt to use this size as much as possible when docking or floating the pane.

This method is split in 2 versions depending on the input type. If arg1 is a wx.Size object, then BestSize1 is called. Otherwise, BestSize2 is called.

Parameters:
  • arg1 – a wx.Size object, a (x, y) tuple or a x coordinate.

  • arg2 – a y coordinate (only if arg1 is a x coordinate, otherwise unused).

BestSize1(size) [source]

Sets the best size of the pane.

See also

BestSize for an explanation of input parameters.

BestSize2(x, y) [source]

Sets the best size of the pane.

See also

BestSize for an explanation of input parameters.

Bottom() [source]

Sets the pane dock position to the bottom of the frame.

Note

This is the same thing as calling Direction with AUI_DOCK_BOTTOM as parameter.

BottomDockable(b=True) [source]

Indicates whether a pane can be docked at the bottom of the frame.

Parameters: b – whether the pane can be docked at the bottom or not.

BottomSnappable(b=True) [source]

Indicates whether a pane can be snapped at the bottom of the main frame.

Parameters: b – whether the pane can be snapped at the bottom of the main frame or not.

Caption(caption) [source]

Sets the caption of the pane.

Parameters: caption – a string specifying the pane caption.

CaptionVisible(visible=True, left=False) [source]

Indicates that a pane caption should be visible. If visible is False, no pane caption is drawn.

Parameters:
  • visible – whether the caption should be visible or not;
  • left – whether the caption should be drawn on the left (rotated by 90 degrees) or not.

Center() [source]

Sets the pane to the center position of the frame.

The centre pane is the space in the middle after all border panes (left, top, right, bottom) are subtracted from the layout.

Note

This is the same thing as calling Direction with AUI_DOCK_CENTER as parameter.

CenterPane() [source]

Specifies that the pane should adopt the default center pane settings.

Centre panes usually do not have caption bars. This function provides an easy way of preparing a pane to be displayed in the center dock position.

Centre() [source]

Sets the pane to the center position of the frame.

The centre pane is the space in the middle after all border panes (left, top, right, bottom) are subtracted from the layout.

Note

This is the same thing as calling Direction with AUI_DOCK_CENTRE as parameter.

CentrePane() [source]

Specifies that the pane should adopt the default center pane settings.

Centre panes usually do not have caption bars. This function provides an easy way of preparing a pane to be displayed in the center dock position.

CloseButton(visible=True) [source]

Indicates that a close button should be drawn for the pane.

Parameters: visible – whether the close button should be visible or not.

CountButtons() [source]

Returns the number of visible buttons in the docked pane.

DefaultPane() [source]

Specifies that the pane should adopt the default pane settings.

DestroyOnClose(b=True) [source]

Indicates whether a pane should be destroyed when it is closed.

Normally a pane is simply hidden when the close button is clicked. Setting b to True will cause the window to be destroyed when the user clicks the pane’s close button.

Parameters: b – whether the pane should be destroyed when it is closed or not.

Direction(direction) [source]

Determines the direction of the docked pane. It is functionally the same as calling Left, Right, Top or Bottom, except that docking direction may be specified programmatically via the parameter direction.

Parameters: direction – the direction of the docked pane.

See also

dock_direction_set for a list of valid docking directions.

Dock() [source]

Indicates that a pane should be docked. It is the opposite of Float.

DockFixed(b=True) [source]

Causes the containing dock to have no resize sash. This is useful for creating panes that span the entire width or height of a dock, but should not be resizable in the other direction.

Parameters: b – whether the pane will have a resize sash or not.

Dockable(b=True) [source]

Specifies whether a frame can be docked or not. It is the same as specifying TopDockable . BottomDockable . LeftDockable . RightDockable .

Parameters: b – whether the frame can be docked or not.

Fixed() [source]

Forces a pane to be fixed size so that it cannot be resized. After calling Fixed, IsFixed will return True.

Float() [source]

Indicates that a pane should be floated. It is the opposite of Dock.

Floatable(b=True) [source]

Sets whether the user will be able to undock a pane and turn it into a floating window.

Parameters: b – whether the pane can be floated or not.

FloatingPosition(pos) [source]

Sets the position of the floating pane.

Parameters: pos – a wx.Point or a tuple indicating the pane floating position.

FloatingSize(size) [source]

Sets the size of the floating pane.

Parameters: size – a wx.Size or a tuple indicating the pane floating size.

FlyOut(b=True) [source]

Indicates whether a pane, when floating, has a “fly-out” effect (i.e., floating panes which only show themselves when moused over).

Parameters: b – whether the pane can be snapped on the main frame or not.

GetMinimizeMode() [source]

Returns the minimization style for this pane.

Possible return values are:

Minimize Mode Flag | Hex Value | Description
AUI_MINIMIZE_POS_SMART | 0x01 | Minimizes the pane on the closest tool bar
AUI_MINIMIZE_POS_TOP | 0x02 | Minimizes the pane on the top tool bar
AUI_MINIMIZE_POS_LEFT | 0x03 | Minimizes the pane on its left tool bar
AUI_MINIMIZE_POS_RIGHT | 0x04 | Minimizes the pane on its right tool bar
AUI_MINIMIZE_POS_BOTTOM | 0x05 | Minimizes the pane on its bottom tool bar
AUI_MINIMIZE_POS_TOOLBAR | 0x06 | Minimizes the pane on a target AuiToolBar
AUI_MINIMIZE_POS_MASK | 0x17 | Mask to filter the position flags
AUI_MINIMIZE_CAPT_HIDE | 0x0 | Hides the caption of the minimized pane
AUI_MINIMIZE_CAPT_SMART | 0x08 | Displays the caption in the best rotation (horizontal or clockwise)
AUI_MINIMIZE_CAPT_HORZ | 0x10 | Displays the caption horizontally
AUI_MINIMIZE_CAPT_MASK | 0x18 | Mask to filter the caption flags

The flags can be filtered with the following masks:

Minimize Mask Flag | Hex Value | Description
AUI_MINIMIZE_POS_MASK | 0x17 | Filters the position flags
AUI_MINIMIZE_CAPT_MASK | 0x18 | Filters the caption flags

Gripper(visible=True) [source]

Indicates that a gripper should be drawn for the pane.

Parameters: visible – whether the gripper should be visible or not.

GripperTop(attop=True) [source]

Indicates that a gripper should be drawn at the top of the pane.

Parameters: attop – whether the gripper should be drawn at the top or not.

HasBorder() [source]

Returns True if the pane displays a border.

HasCaption() [source]

Returns True if the pane displays a caption.

HasCaptionLeft() [source]

Returns True if the pane displays a caption on the left (rotated by 90 degrees).

HasCloseButton() [source]

Returns True if the pane displays a button to close the pane.

HasFlag(flag) [source]

Returns True if the the property specified by flag is active for the pane.

Parameters: flag – the property to check for activity.

HasGripper() [source]

Returns True if the pane displays a gripper.

HasGripperTop() [source]

Returns True if the pane displays a gripper at the top.

HasMaximizeButton() [source]

Returns True if the pane displays a button to maximize the pane.

HasMinimizeButton() [source]

Returns True if the pane displays a button to minimize the pane.

HasNotebook() [source]

Returns whether a pane has a AuiNotebook or not.

HasPinButton() [source]

Returns True if the pane displays a button to float the pane.

Hide() [source]

Indicates that a pane should be hidden.

Calling Show (False) achieve the same effect.

Icon(icon) [source]

Specifies whether an icon is drawn on the left of the caption text when the pane is docked. If icon is None or wx.NullIcon, no icon is drawn on the caption space.

Parameters: icon – an icon to draw on the caption space, or None.

IsBottomDockable() [source]

Returns True if the pane can be docked at the bottom of the managed frame.

IsBottomSnappable() [source]

Returns True if the pane can be snapped at the bottom of the managed frame.

IsDestroyOnClose() [source]

Returns True if the pane should be destroyed when it is closed.

Normally a pane is simply hidden when the close button is clicked. Calling DestroyOnClose with a True input parameter will cause the window to be destroyed when the user clicks the pane’s close button.

IsDockable() [source]

Returns True if the pane can be docked.

IsDocked() [source]

Returns True if the pane is docked.

IsFixed() [source]

Returns True if the pane cannot be resized.

IsFloatable() [source]

Returns True if the pane can be undocked and displayed as a floating window.

IsFloating() [source]

Returns True if the pane is floating.

IsFlyOut() [source]

Returns True if the floating pane has a “fly-out” effect.

IsHorizontal() [source]

Returns True if the pane dock_direction is horizontal.

IsLeftDockable() [source]

Returns True if the pane can be docked at the left of the managed frame.

IsLeftSnappable() [source]

Returns True if the pane can be snapped on the left of the managed frame.

IsMaximized() [source]

Returns True if the pane is maximized.

IsMinimized() [source]

Returns True if the pane is minimized.

IsMovable() [source]

Returns True if the docked frame can be undocked or moved to another dock position.

IsNotebookControl() [source]

Returns whether the pane is a notebook control (AuiNotebook).

IsNotebookDockable() [source]

Returns True if a pane can be docked on top to another to create a AuiNotebook.

IsNotebookPage() [source]

Returns whether the pane is a notebook page in a AuiNotebook.

IsOk() [source]

Returns True if the AuiPaneInfo structure is valid.

Note

A pane structure is valid if it has an associated window.

IsResizeable() [source]

Returns True if the pane can be resized.

IsRightDockable() [source]

Returns True if the pane can be docked at the right of the managed frame.

IsRightSnappable() [source]

Returns True if the pane can be snapped on the right of the managed frame.

IsShown() [source]

Returns True if the pane is currently shown.

IsSnappable() [source]

Returns True if the pane can be snapped.

IsToolbar() [source]

Returns True if the pane contains a toolbar.

IsTopDockable() [source]

Returns True if the pane can be docked at the top of the managed frame.

IsTopSnappable() [source]

Returns True if the pane can be snapped at the top of the managed frame.

IsVertical() [source]

Returns True if the pane dock_direction is vertical.

Layer(layer) [source]

Determines the layer of the docked pane.

The dock layer is similar to an onion, the inner-most layer being layer 0. Each shell moving in the outward direction has a higher layer number. This allows for more complex docking layout formation.

Parameters: layer – the layer of the docked pane.

Left() [source]

Sets the pane dock position to the left side of the frame.

Note

This is the same thing as calling Direction with AUI_DOCK_LEFT as parameter.

LeftDockable(b=True) [source]

Indicates whether a pane can be docked on the left of the frame.

Parameters: b – whether the pane can be docked at the left or not.

LeftSnappable(b=True) [source]

Indicates whether a pane can be snapped on the left of the main frame.

Parameters: b – whether the pane can be snapped at the left of the main frame or not.

MaxSize(arg1=None, arg2=None) [source]

Sets the maximum size of the pane.

This method is split in 2 versions depending on the input type. If arg1 is a wx.Size object, then MaxSize1 is called. Otherwise, MaxSize2 is called.

Parameters:
  • arg1 – a wx.Size object, a (x, y) tuple or a x coordinate.

  • arg2 – a y coordinate (only if arg1 is a x coordinate, otherwise unused).

MaxSize1(size) [source]

Sets the maximum size of the pane.

See also

MaxSize for an explanation of input parameters.

MaxSize2(x, y) [source]

Sets the maximum size of the pane.

See also

MaxSize for an explanation of input parameters.

Maximize() [source]

Makes the pane take up the full area.

MaximizeButton(visible=True) [source]

Indicates that a maximize button should be drawn for the pane.

Parameters: visible – whether the maximize button should be visible or not.

MinSize(arg1=None, arg2=None) [source]

Sets the minimum size of the pane.

This method is split in 2 versions depending on the input type. If arg1 is a wx.Size object, then MinSize1 is called. Otherwise, MinSize2 is called.

Parameters:
  • arg1 – a wx.Size object, a (x, y) tuple or or a x coordinate.

  • arg2 – a y coordinate (only if arg1 is a x coordinate, otherwise unused).

MinSize1(size) [source]

Sets the minimum size of the pane.

See also

MinSize for an explanation of input parameters.

MinSize2(x, y) [source]

Sets the minimum size of the pane.

See also

MinSize for an explanation of input parameters.

Minimize() [source]

Makes the pane minimized in a AuiToolBar.

Clicking on the minimize button causes a new AuiToolBar to be created and added to the frame manager, (currently the implementation is such that panes at West will have a toolbar at the right, panes at South will have toolbars at the bottom etc...) and the pane is hidden in the manager.

Clicking on the restore button on the newly created toolbar will result in the toolbar being removed and the original pane being restored.

MinimizeButton(visible=True) [source]

Indicates that a minimize button should be drawn for the pane.

Parameters: visible – whether the minimize button should be visible or not.

MinimizeMode(mode) [source]

Sets the expected minimized mode if the MinimizeButton() is visible.

The minimized pane can have a specific position in the work space:

Minimize Mode Flag | Hex Value | Description
AUI_MINIMIZE_POS_SMART | 0x01 | Minimizes the pane on the closest tool bar
AUI_MINIMIZE_POS_TOP | 0x02 | Minimizes the pane on the top tool bar
AUI_MINIMIZE_POS_LEFT | 0x03 | Minimizes the pane on its left tool bar
AUI_MINIMIZE_POS_RIGHT | 0x04 | Minimizes the pane on its right tool bar
AUI_MINIMIZE_POS_BOTTOM | 0x05 | Minimizes the pane on its bottom tool bar
AUI_MINIMIZE_POS_TOOLBAR | 0x06 | Minimizes the pane on a target AuiToolBar

The caption of the minimized pane can be displayed in different modes:

Caption Mode Flag | Hex Value | Description
AUI_MINIMIZE_CAPT_HIDE | 0x0 | Hides the caption of the minimized pane
AUI_MINIMIZE_CAPT_SMART | 0x08 | Displays the caption in the best rotation (horizontal in the top and in the bottom tool bar or clockwise in the right and in the left tool bar)
AUI_MINIMIZE_CAPT_HORZ | 0x10 | Displays the caption horizontally

Note

In order to use the AUI_MINIMIZE_POS_TOOLBAR flag, the instance of AuiPaneInfo you pass as an input for MinimizeTarget must have a real name and not the randomly generated one. Remember to set the Name property of the toolbar pane before calling this method.

MinimizeTarget(toolbarPane) [source]

Minimizes the panes using a AuiPaneInfo as a target. As AuiPaneInfo properties need to be copied back and forth every time the perspective has changed, we only store the toobar name.

Parameters: toolbarPane – an instance of AuiPaneInfo, containing a AuiToolBar.

Note

In order to use this functionality (and with the AUI_MINIMIZE_POS_TOOLBAR flag set), the instance of AuiPaneInfo you pass as an input must have a real name and not the randomly generated one. Remember to set the Name property of the toolbar pane before calling this method.

Movable(b=True) [source]

Indicates whether a pane can be moved.

Parameters: b – whether the pane can be moved or not.

Name(name) [source]

Sets the name of the pane so it can be referenced in lookup functions.

If a name is not specified by the user, a random name is assigned to the pane when it is added to the manager.

Parameters: name – a string specifying the pane name.

Warning

If you are using AuiManager.SavePerspective() and AuiManager.LoadPerspective(), you will have to specify a name for your pane using Name, as randomly generated names can not be properly restored.

NotebookControl(id) [source]

Forces a pane to be a notebook control (AuiNotebook).

Parameters: id – the notebook id.

NotebookDockable(b=True) [source]

Indicates whether a pane can be docked in an automatic AuiNotebook.

Parameters: b – whether the pane can be docked in a notebook or not.

NotebookPage(id, tab_position=1000) [source]

Forces a pane to be a notebook page, so that the pane can be docked on top to another to create a AuiNotebook.

Parameters:
  • id – the notebook id;
  • tab_position – the tab number of the pane once docked in a notebook.

PaneBorder(visible=True) [source]

Indicates that a border should be drawn for the pane.

Parameters: visible – whether the pane border should be visible or not.

PinButton(visible=True) [source]

Indicates that a pin button should be drawn for the pane.

Parameters: visible – whether the pin button should be visible or not.

Position(pos) [source]

Determines the position of the docked pane.

Parameters: pos – the position of the docked pane.

ResetButtons() [source]

Resets all the buttons and recreates them from scratch depending on the AuiPaneInfo flags.

Resizable(resizable=True) [source]

Allows a pane to be resizable if resizable is True, and forces it to be a fixed size if resizeable is False.

If resizable is False, this is simply an antonym for Fixed.

Parameters: resizable – whether the pane will be resizeable or not.

Restore() [source]

Is the reverse of Maximize and Minimize.

Right() [source]

Sets the pane dock position to the right side of the frame.

Note

This is the same thing as calling Direction with AUI_DOCK_RIGHT as parameter.

RightDockable(b=True) [source]

Indicates whether a pane can be docked on the right of the frame.

Parameters: b – whether the pane can be docked at the right or not.

RightSnappable(b=True) [source]

Indicates whether a pane can be snapped on the right of the main frame.

Parameters: b – whether the pane can be snapped at the right of the main frame or not.

Row(row) [source]

Determines the row of the docked pane.

Parameters: row – the row of the docked pane.

SetDockPos(source) [source]

Copies the source pane members that pertain to docking position to self.

Parameters: source – the source pane from where to copy the attributes.

SetFlag(flag, option_state) [source]

Turns the property given by flag on or off with the option_state parameter.

Parameters:
  • flag – the property to set;
  • option_state – either True or False.

SetNameFromNotebookId() [source]

Sets the pane name once docked in a AuiNotebook using the notebook id.

Show(show=True) [source]

Indicates that a pane should be shown.

Parameters: show – whether the pane should be shown or not.

Snappable(b=True) [source]

Indicates whether a pane can be snapped on the main frame. This is equivalent as calling TopSnappable . BottomSnappable . LeftSnappable . RightSnappable .

Parameters: b – whether the pane can be snapped on the main frame or not.

ToolbarPane() [source]

Specifies that the pane should adopt the default toolbar pane settings.

Top() [source]

Sets the pane dock position to the top of the frame.

Note

This is the same thing as calling Direction with AUI_DOCK_TOP as parameter.

TopDockable(b=True) [source]

Indicates whether a pane can be docked at the top of the frame.

Parameters: b – whether the pane can be docked at the top or not.

TopSnappable(b=True) [source]

Indicates whether a pane can be snapped at the top of the main frame.

Parameters: b – whether the pane can be snapped at the top of the main frame or not.

Transparent(alpha) [source]

Makes the pane transparent when floating.

Parameters: alpha – an integer value between 0 and 255 for pane transparency.

Window(w) [source]

Associate a wx.Window derived window to this pane.

This normally does not need to be specified, as the window pointer is automatically assigned to the AuiPaneInfo structure as soon as it is added to the manager.

Parameters: w – a wx.Window derived window.

actionPane = 17179869184L

buttonClose = 67108864

buttonCustom1 = 1073741824

buttonCustom2 = 2147483648L

buttonCustom3 = 4294967296L

buttonMaximize = 134217728

buttonMinimize = 268435456

buttonPin = 536870912

dock_direction

Getter for the dock_direction.

See also

dock_direction_set for a set of valid docking directions.

dock_direction_get() [source]

Getter for the dock_direction.

See also

dock_direction_set for a set of valid docking directions.

dock_direction_set(value) [source]

Setter for the dock_direction.

Parameters: value – the docking direction. This cab ne one of the following bits:

Dock Flag | Value | Description
AUI_DOCK_NONE | 0 | No docking direction.
AUI_DOCK_TOP | 1 | Top docking direction.
AUI_DOCK_RIGHT | 2 | Right docking direction.
AUI_DOCK_BOTTOM | 3 | Bottom docking direction.
AUI_DOCK_LEFT | 4 | Left docking direction.
AUI_DOCK_CENTER | 5 | Center docking direction.
AUI_DOCK_CENTRE | 5 | Centre docking direction.
AUI_DOCK_NOTEBOOK_PAGE | 6 | Automatic AuiNotebooks docking style.

needsRestore = 68719476736L

optionActive = 16384

optionBottomDockable = 32

optionBottomSnapped = 8388608

optionCaption = 1024

optionCaptionLeft = 33554432

optionDestroyOnClose = 4096

optionDockFixed = 131072

optionFloatable = 64

optionFloating = 1

optionFlyOut = 16777216

optionGripper = 2048

optionGripperTop = 32768

optionHidden = 2

optionLeftDockable = 4

optionLeftSnapped = 1048576

optionMaximized = 65536

optionMinimized = 524288

optionMovable = 128

optionNotebookDockable = 262144

optionPaneBorder = 512

optionResizable = 256

optionRightDockable = 8

optionRightSnapped = 2097152

optionToolbar = 8192

optionTopDockable = 16

optionTopSnapped = 4194304

savedHiddenState = 8589934592L

wasMaximized = 34359738368L

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • infobar
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • aui library »
  • aui.framemanager »
  • AuiPaneInfo


AuiSingleDockingGuide

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • aui library »
  • aui.framemanager »
  • AuiSingleDockingGuide

AuiSingleDockingGuide

A docking guide window for single docking hint (not diamond-shaped HUD).

hierarchy Inheritance Diagram

Inheritance diagram for: AuiSingleDockingGuide

Inheritance diagram of AuiSingleDockingGuide

supclasses Known Superclasses

  • aui.framemanager.AuiDockingGuide

Methods Summary

__init__ | Default class constructor.
AeroMove | Moves the docking window to the new position.
CreateShapesWithStyle | Creates the docking guide window shape based on which docking bitmaps are used.
HitTest | Checks if the mouse position is inside the target window rect.
IsValid | Returns whether the docking direction is valid.
SetGuideShape | Sets the correct shape for the docking guide window.
SetShape | If the platform supports it, sets the shape of the window to that depicted by region.
SetValid | Sets the docking direction as valid or invalid.
UpdateDockGuide | Updates the docking guide images depending on the mouse position, using focused images if the mouse is inside the docking guide or unfocused images if it is outside.

API Class API

class AuiSingleDockingGuide(AuiDockingGuide) [source]

A docking guide window for single docking hint (not diamond-shaped HUD).

__init__(parent, direction=0) [source]

Default class constructor. Used internally, do not call it in your code!

Parameters:
  • parent – the AuiSingleDockingGuide parent;
  • direction – one of wx.TOP, wx.BOTTOM, wx.LEFT, wx.RIGHT.

AeroMove(pos) [source]

Moves the docking window to the new position. Overridden in children classes.

Parameters: pos – the new docking guide position.

CreateShapesWithStyle(useWhidbey) [source]

Creates the docking guide window shape based on which docking bitmaps are used.

Parameters: useWhidbey – if True, use Whidbey-style bitmaps; if False, use the Aero-style bitmaps.

HitTest(x, y) [source]

Checks if the mouse position is inside the target window rect.

Parameters:
  • x – the x mouse position;
  • y – the y mouse position.

IsValid() [source]

Returns whether the docking direction is valid.

SetGuideShape(event=None) [source]

Sets the correct shape for the docking guide window.

Parameters: event – on wxGTK, a wx.WindowCreateEvent event to process.

SetShape(region) [source]

If the platform supports it, sets the shape of the window to that depicted by region. The system will not display or respond to any mouse event for the pixels that lie outside of the region. To reset the window to the normal rectangular shape simply call SetShape again with an empty region.

Parameters: region – the shape of the frame.

Note

Overridden for wxMac.

SetValid(valid) [source]

Sets the docking direction as valid or invalid.

Parameters: valid – whether the docking direction is allowed or not.

UpdateDockGuide(pos) [source]

Updates the docking guide images depending on the mouse position, using focused images if the mouse is inside the docking guide or unfocused images if it is outside.

Parameters: pos – a wx.Point mouse position.

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • infobar
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • aui library »
  • aui.framemanager »
  • AuiSingleDockingGuide


aui.framemanager

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • aui library »
  • aui.framemanager

aui.framemanager

description Description

framemanager.py is the central module of the AUI class framework.

AuiManager manages the panes associated with it for a particular wx.Frame, using a pane’s AuiPaneInfo information to determine each pane’s docking and floating behavior. AuiManager uses wxPython’ sizer mechanism to plan the layout of each frame. It uses a replaceable dock art class to do all drawing, so all drawing is localized in one area, and may be customized depending on an application’s specific needs.

AuiManager works as follows: the programmer adds panes to the class, or makes changes to existing pane properties (dock position, floating state, show state, etc...). To apply these changes, AuiManager’s Update function is called. This batch processing can be used to avoid flicker, by modifying more than one pane at a time, and then “committing” all of the changes at once by calling Update().

Panes can be added quite easily:

text1 = wx.TextCtrl(self, -1)
text2 = wx.TextCtrl(self, -1)
self._mgr.AddPane(text1, AuiPaneInfo().Left().Caption("Pane Number One"))
self._mgr.AddPane(text2, AuiPaneInfo().Bottom().Caption("Pane Number Two"))

self._mgr.Update()

Later on, the positions can be modified easily. The following will float an existing pane in a tool window:

self._mgr.GetPane(text1).Float()

layers Layers, Rows and Directions, Positions

Inside AUI, the docking layout is figured out by checking several pane parameters. Four of these are important for determining where a pane will end up.

Direction - Each docked pane has a direction, Top, Bottom, Left, Right, or Center. This is fairly self-explanatory. The pane will be placed in the location specified by this variable.

Position - More than one pane can be placed inside of a “dock”. Imagine two panes being docked on the left side of a window. One pane can be placed over another. In proportionally managed docks, the pane position indicates it’s sequential position, starting with zero. So, in our scenario with two panes docked on the left side, the top pane in the dock would have position 0, and the second one would occupy position 1.

Row - A row can allow for two docks to be placed next to each other. One of the most common places for this to happen is in the toolbar. Multiple toolbar rows are allowed, the first row being in row 0, and the second in row 1. Rows can also be used on vertically docked panes.

Layer - A layer is akin to an onion. Layer 0 is the very center of the managed pane. Thus, if a pane is in layer 0, it will be closest to the center window (also sometimes known as the “content window”). Increasing layers “swallow up” all layers of a lower value. This can look very similar to multiple rows, but is different because all panes in a lower level yield to panes in higher levels. The best way to understand layers is by running the AUI sample (AUI.py).

Module author: Andrea Gavana <andrea.gavana@gmail.com>

hierarchy Inheritance Diagram

Inheritance diagram for module: aui.framemanager

SVN Revisions

A graphical representation of the SVN commits in the last year.

Click on any date in the picture to jump to that particular revision page, containing information about committers, log messages and SVN diffs.

Revision Graph For framemanager

2to3 Python 3 Issues (via 2to3)

No issues have been detected by 2to3.py.

Function Summary

  • AuiManager_HasLiveResize
  • AuiManager_UseNativeMiniframes
  • CheckEdgeDrop
  • CheckOutOfWindow
  • CopyDocksAndPanes
  • CopyDocksAndPanes2
  • DoInsertDockLayer
  • DoInsertDockRow
  • DoInsertPane
  • DrawResizeHint
  • EscapeDelimiters
  • FindDocks
  • FindOppositeDocks
  • FindPaneInDock
  • GetInternalFrameRect
  • GetManager
  • GetMaxLayer
  • GetMaxRow
  • GetNotebookRoot
  • GetToolBarDockOffsets
  • IsDifferentDockingPosition
  • PaneSortFunc
  • RefreshDockingGuides
  • RemovePaneFromDocks
  • RenumberDockRows
  • SetActivePane
  • ShowDockingGuides

Class Summary

  • AuiCenterDockingGuide
  • AuiDockInfo
  • AuiDockUIPart
  • AuiDockingGuide
  • AuiDockingGuideInfo
  • AuiDockingGuideWindow
  • AuiDockingHintWindow
  • AuiFloatingFrame
  • AuiManager
  • AuiManagerEvent
  • AuiManager_DCP
  • AuiPaneButton
  • AuiPaneInfo
  • AuiSingleDockingGuide

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • infobar
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • aui library »
  • aui.framemanager


AuiCommandCapture

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • aui library »
  • aui.tabart »
  • AuiCommandCapture

AuiCommandCapture

A class to handle the dropdown window menu.

hierarchy Inheritance Diagram

Inheritance diagram for: AuiCommandCapture

Inheritance diagram of AuiCommandCapture

Methods Summary

__init__ | Default class constructor.
GetCommandId | Returns the event command identifier.
ProcessEvent | Processes an event, searching event tables and calling zero or more suitable event handler function(s).

API Class API

class AuiCommandCapture(wx.PyEvtHandler) [source]

A class to handle the dropdown window menu.

__init__() [source]

Default class constructor.

GetCommandId() [source]

Returns the event command identifier.

ProcessEvent(event) [source]

Processes an event, searching event tables and calling zero or more suitable event handler function(s).

Parameters: event – the event to process.

Note

Normally, your application would not call this function: it is called in the wxPython implementation to dispatch incoming user interface events to the framework (and application). However, you might need to call it if implementing new functionality (such as a new control) where you define new event types, as opposed to allowing the user to override functions.

An instance where you might actually override the ProcessEvent function is where you want to direct event processing to event handlers not normally noticed by wxPython. For example, in the document/view architecture, documents and views are potential event handlers. When an event reaches a frame, ProcessEvent will need to be called on the associated document and view in case event handler functions are associated with these objects.

The normal order of event table searching is as follows:

  1. If the object is disabled (via a call to SetEvtHandlerEnabled) the function skips to step (6).
  2. If the object is a wx.Window, ProcessEvent is recursively called on the window’s wx.Validator. If this returns True, the function exits.
  3. wxWidgets SearchEventTable is called for this event handler. If this fails, the base class table is tried, and so on until no more tables exist or an appropriate function was found, in which case the function exits.
  4. The search is applied down the entire chain of event handlers (usually the chain has a length of one). If this succeeds, the function exits.
  5. If the object is a wx.Window and the event is a wx.CommandEvent, ProcessEvent is recursively applied to the parent window’s event handler. If this returns True, the function exits.
  6. Finally, ProcessEvent is called on the wx.App object.

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • infobar
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • aui library »
  • aui.tabart »
  • AuiCommandCapture


AuiDefaultTabArt

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • aui library »
  • aui.tabart »
  • AuiDefaultTabArt

AuiDefaultTabArt

Tab art provider code - a tab provider provides all drawing functionality to the AuiNotebook. This allows the AuiNotebook to have a plugable look-and-feel.

By default, a AuiNotebook uses an instance of this class called AuiDefaultTabArt which provides bitmap art and a colour scheme that is adapted to the major platforms’ look. You can either derive from that class to alter its behaviour or write a completely new tab art class. Call SetArtProvider to make use this new tab art.

hierarchy Inheritance Diagram

Inheritance diagram for: AuiDefaultTabArt

Inheritance diagram of AuiDefaultTabArt

subclasses Known Subclasses

  • aui.tabart.ChromeTabArt
  • aui.tabart.FF2TabArt
  • aui.tabart.VC71TabArt
  • aui.tabart.VC8TabArt

Methods Summary

__init__ | Default class constructor.
Clone | Clones the art object.
DrawBackground | Draws the tab area background.
DrawButton | Draws a button on the tab or on the tab area, depending on the button identifier.
DrawFocusRectangle | Draws the focus rectangle on a tab.
DrawTab | Draws a single tab.
GetAGWFlags | Returns the tab art flags.
GetBestTabCtrlSize | Returns the best tab control size.
GetIndentSize | Returns the tabs indent size.
GetMeasuringFont | Returns the font for calculating text measurements.
GetNormalFont | Returns the normal font for drawing tab labels.
GetSelectedFont | Returns the selected tab font for drawing tab labels.
GetTabSize | Returns the tab size for the given caption, bitmap and button state.
SetAGWFlags | Sets the tab art flags.
SetBaseColour | Sets a new base colour.
SetCustomButton | Sets a custom bitmap for the close, left, right and window list buttons.
SetDefaultColours | Sets the default colours, which are calculated from the given base colour.
SetMeasuringFont | Sets the font for calculating text measurements.
SetNormalFont | Sets the normal font for drawing tab labels.
SetSelectedFont | Sets the selected tab font for drawing tab labels.
SetSizingInfo | Sets the tab sizing information.
ShowDropDown | Shows the drop-down window menu on the tab area.

API Class API

class AuiDefaultTabArt(object) [source]

Tab art provider code - a tab provider provides all drawing functionality to the AuiNotebook. This allows the AuiNotebook to have a plugable look-and-feel.

By default, a AuiNotebook uses an instance of this class called AuiDefaultTabArt which provides bitmap art and a colour scheme that is adapted to the major platforms’ look. You can either derive from that class to alter its behaviour or write a completely new tab art class. Call AuiNotebook.SetArtProvider() to make use this new tab art.

__init__() [source]

Default class constructor.

Clone() [source]

Clones the art object.

DrawBackground(dc, wnd, rect) [source]

Draws the tab area background.

Parameters:
  • dc – a wx.DC device context;
  • wnd – a wx.Window instance object;
  • rect – the tab control rectangle.

DrawButton(dc, wnd, in_rect, button, orientation) [source]

Draws a button on the tab or on the tab area, depending on the button identifier.

Parameters:
  • dc – a wx.DC device context;

  • wnd – a wx.Window instance object;

  • in_rect – rectangle the tab should be confined to;
  • button – an instance of the button class;
  • orientation – the tab orientation.

DrawFocusRectangle(dc, page, wnd, draw_text, text_offset, bitmap_offset, drawn_tab_yoff, drawn_tab_height, textx, texty) [source]

Draws the focus rectangle on a tab.

Parameters:
  • dc – a wx.DC device context;

  • page – the page associated with the tab;
  • wnd – a wx.Window instance object;

  • draw_text – the text that has been drawn on the tab;
  • text_offset – the text offset on the tab;
  • bitmap_offset – the bitmap offset on the tab;
  • drawn_tab_yoff – the y offset of the tab text;
  • drawn_tab_height – the height of the tab;
  • textx – the x text extent;
  • texty – the y text extent.

DrawTab(dc, wnd, page, in_rect, close_button_state, paint_control=False) [source]

Draws a single tab.

Parameters:
  • dc – a wx.DC device context;

  • wnd – a wx.Window instance object;

  • page – the tab control page associated with the tab;
  • in_rect – rectangle the tab should be confined to;
  • close_button_state – the state of the close button on the tab;
  • paint_control – whether to draw the control inside a tab (if any) on a wx.MemoryDC.

GetAGWFlags() [source]

Returns the tab art flags.

See also

SetAGWFlags for a list of possible return values.

GetBestTabCtrlSize(wnd, pages, required_bmp_size) [source]

Returns the best tab control size.

Parameters:
  • wnd – a wx.Window instance object;

  • pages – the pages associated with the tabs;
  • required_bmp_size – the size of the bitmap on the tabs.

GetIndentSize() [source]

Returns the tabs indent size.

GetMeasuringFont() [source]

Returns the font for calculating text measurements.

GetNormalFont() [source]

Returns the normal font for drawing tab labels.

GetSelectedFont() [source]

Returns the selected tab font for drawing tab labels.

GetTabSize(dc, wnd, caption, bitmap, active, close_button_state, control=None) [source]

Returns the tab size for the given caption, bitmap and button state.

Parameters:
  • dc – a wx.DC device context;

  • wnd – a wx.Window instance object;

  • caption – the tab text caption;
  • bitmap – the bitmap displayed on the tab;
  • active – whether the tab is selected or not;
  • close_button_state – the state of the close button on the tab;
  • control – a wx.Window instance inside a tab (or None).

SetAGWFlags(agwFlags) [source]

Sets the tab art flags.

Parameters: agwFlags – a combination of the following values:

Flag name | Description
AUI_NB_TOP | With this style, tabs are drawn along the top of the notebook
AUI_NB_LEFT | With this style, tabs are drawn along the left of the notebook. Not implemented yet.
AUI_NB_RIGHT | With this style, tabs are drawn along the right of the notebook. Not implemented yet.
AUI_NB_BOTTOM | With this style, tabs are drawn along the bottom of the notebook
AUI_NB_TAB_SPLIT | Allows the tab control to be split by dragging a tab
AUI_NB_TAB_MOVE | Allows a tab to be moved horizontally by dragging
AUI_NB_TAB_EXTERNAL_MOVE | Allows a tab to be moved to another tab control
AUI_NB_TAB_FIXED_WIDTH | With this style, all tabs have the same width
AUI_NB_SCROLL_BUTTONS | With this style, left and right scroll buttons are displayed
AUI_NB_WINDOWLIST_BUTTON | With this style, a drop-down list of windows is available
AUI_NB_CLOSE_BUTTON | With this style, a close button is available on the tab bar
AUI_NB_CLOSE_ON_ACTIVE_TAB | With this style, a close button is available on the active tab
AUI_NB_CLOSE_ON_ALL_TABS | With this style, a close button is available on all tabs
AUI_NB_MIDDLE_CLICK_CLOSE | Allows to close AuiNotebook tabs by mouse middle button click
AUI_NB_SUB_NOTEBOOK | This style is used by AuiManager to create automatic AuiNotebooks
AUI_NB_HIDE_ON_SINGLE_TAB | Hides the tab window if only one tab is present
AUI_NB_SMART_TABS | Use Smart Tabbing, like Alt + Tab on Windows
AUI_NB_USE_IMAGES_DROPDOWN | Uses images on dropdown window list menu instead of check items
AUI_NB_CLOSE_ON_TAB_LEFT | Draws the tab close button on the left instead of on the right (a la Camino browser)
AUI_NB_TAB_FLOAT | Allows the floating of single tabs. Known limitation: when the notebook is more or less full screen, tabs cannot be dragged far enough outside of the notebook to become floating pages
AUI_NB_DRAW_DND_TAB | Draws an image representation of a tab while dragging (on by default)
AUI_NB_ORDER_BY_ACCESS | Tab navigation order by last access time for the tabs
AUI_NB_NO_TAB_FOCUS | Don’t draw tab focus rectangle

SetBaseColour(base_colour) [source]

Sets a new base colour.

Parameters: base_colour – an instance of wx.Colour.

SetCustomButton(bitmap_id, button_state, bmp) [source]

Sets a custom bitmap for the close, left, right and window list buttons.

Parameters:
  • bitmap_id – the button identifier;
  • button_state – the button state;
  • bmp – the custom bitmap to use for the button.

SetDefaultColours(base_colour=None) [source]

Sets the default colours, which are calculated from the given base colour.

Parameters: base_colour – an instance of wx.Colour. If defaulted to None, a colour is generated accordingly to the platform and theme.

SetMeasuringFont(font) [source]

Sets the font for calculating text measurements.

Parameters: font – a wx.Font object.

SetNormalFont(font) [source]

Sets the normal font for drawing tab labels.

Parameters: font – a wx.Font object.

SetSelectedFont(font) [source]

Sets the selected tab font for drawing tab labels.

Parameters: font – a wx.Font object.

SetSizingInfo(tab_ctrl_size, tab_count, minMaxTabWidth) [source]

Sets the tab sizing information.

Parameters:
  • tab_ctrl_size – the size of the tab control area;
  • tab_count – the number of tabs;
  • minMaxTabWidth – a tuple containing the minimum and maximum tab widths to be used when the AUI_NB_TAB_FIXED_WIDTH style is active.

ShowDropDown(wnd, pages, active_idx) [source]

Shows the drop-down window menu on the tab area.

Parameters:
  • wnd – a wx.Window derived window instance;

  • pages – the pages associated with the tabs;
  • active_idx – the active tab index.

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • infobar
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • aui library »
  • aui.tabart »
  • AuiDefaultTabArt


AuiSimpleTabArt

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • aui library »
  • aui.tabart »
  • AuiSimpleTabArt

AuiSimpleTabArt

A simple-looking implementation of a tab art.

hierarchy Inheritance Diagram

Inheritance diagram for: AuiSimpleTabArt

Inheritance diagram of AuiSimpleTabArt

Methods Summary

__init__ | Default class constructor.
Clone | Clones the art object.
DrawBackground | Draws the tab area background.
DrawButton | Draws a button on the tab or on the tab area, depending on the button identifier.
DrawButtons | Convenience method to draw tab buttons.
DrawTab | Draws a single tab.
GetAGWFlags | Returns the tab art flags.
GetBestTabCtrlSize | Returns the best tab control size.
GetIndentSize | Returns the tabs indent size.
GetMeasuringFont | Returns the font for calculating text measurements.
GetNormalFont | Returns the normal font for drawing tab labels.
GetSelectedFont | Returns the selected tab font for drawing tab labels.
GetTabSize | Returns the tab size for the given caption, bitmap and button state.
SetAGWFlags | Sets the tab art flags.
SetCustomButton | Sets a custom bitmap for the close, left, right and window list buttons.
SetMeasuringFont | Sets the font for calculating text measurements.
SetNormalFont | Sets the normal font for drawing tab labels.
SetSelectedFont | Sets the selected tab font for drawing tab labels.
SetSizingInfo | Sets the tab sizing information.
ShowDropDown | Shows the drop-down window menu on the tab area.

API Class API

class AuiSimpleTabArt(object) [source]

A simple-looking implementation of a tab art.

__init__() [source]

Default class constructor.

Clone() [source]

Clones the art object.

DrawBackground(dc, wnd, rect) [source]

Draws the tab area background.

Parameters:
  • dc – a wx.DC device context;
  • wnd – a wx.Window instance object;
  • rect – the tab control rectangle.

DrawButton(dc, wnd, in_rect, button, orientation) [source]

Draws a button on the tab or on the tab area, depending on the button identifier.

Parameters:
  • dc – a wx.DC device context;

  • wnd – a wx.Window instance object;

  • in_rect – rectangle the tab should be confined to;
  • button – an instance of the button class;
  • orientation – the tab orientation.

DrawButtons(dc, _rect, bmp, bkcolour, button_state) [source]

Convenience method to draw tab buttons.

Parameters:
  • dc – a wx.DC device context;

  • _rect – the tab rectangle;
  • bmp – the tab bitmap;
  • bkcolour – the tab background colour;
  • button_state – the state of the tab button.

DrawTab(dc, wnd, page, in_rect, close_button_state, paint_control=False) [source]

Draws a single tab.

Parameters:
  • dc – a wx.DC device context;

  • wnd – a wx.Window instance object;

  • page – the tab control page associated with the tab;
  • in_rect – rectangle the tab should be confined to;
  • close_button_state – the state of the close button on the tab;
  • paint_control – whether to draw the control inside a tab (if any) on a wx.MemoryDC.

GetAGWFlags() [source]

Returns the tab art flags.

See also

SetAGWFlags for a list of possible return values.

GetBestTabCtrlSize(wnd, pages, required_bmp_size) [source]

Returns the best tab control size.

Parameters:
  • wnd – a wx.Window instance object;

  • pages – the pages associated with the tabs;
  • required_bmp_size – the size of the bitmap on the tabs.

GetIndentSize() [source]

Returns the tabs indent size.

GetMeasuringFont() [source]

Returns the font for calculating text measurements.

GetNormalFont() [source]

Returns the normal font for drawing tab labels.

GetSelectedFont() [source]

Returns the selected tab font for drawing tab labels.

GetTabSize(dc, wnd, caption, bitmap, active, close_button_state, control=None) [source]

Returns the tab size for the given caption, bitmap and button state.

Parameters:
  • dc – a wx.DC device context;

  • wnd – a wx.Window instance object;

  • caption – the tab text caption;
  • bitmap – the bitmap displayed on the tab;
  • active – whether the tab is selected or not;
  • close_button_state – the state of the close button on the tab;
  • control – a wx.Window instance inside a tab (or None).

SetAGWFlags(agwFlags) [source]

Sets the tab art flags.

Parameters: agwFlags – a combination of the following values:

Flag name | Description
AUI_NB_TOP | With this style, tabs are drawn along the top of the notebook
AUI_NB_LEFT | With this style, tabs are drawn along the left of the notebook. Not implemented yet.
AUI_NB_RIGHT | With this style, tabs are drawn along the right of the notebook. Not implemented yet.
AUI_NB_BOTTOM | With this style, tabs are drawn along the bottom of the notebook
AUI_NB_TAB_SPLIT | Allows the tab control to be split by dragging a tab
AUI_NB_TAB_MOVE | Allows a tab to be moved horizontally by dragging
AUI_NB_TAB_EXTERNAL_MOVE | Allows a tab to be moved to another tab control
AUI_NB_TAB_FIXED_WIDTH | With this style, all tabs have the same width
AUI_NB_SCROLL_BUTTONS | With this style, left and right scroll buttons are displayed
AUI_NB_WINDOWLIST_BUTTON | With this style, a drop-down list of windows is available
AUI_NB_CLOSE_BUTTON | With this style, a close button is available on the tab bar
AUI_NB_CLOSE_ON_ACTIVE_TAB | With this style, a close button is available on the active tab
AUI_NB_CLOSE_ON_ALL_TABS | With this style, a close button is available on all tabs
AUI_NB_MIDDLE_CLICK_CLOSE | Allows to close AuiNotebook tabs by mouse middle button click
AUI_NB_SUB_NOTEBOOK | This style is used by AuiManager to create automatic AuiNotebooks
AUI_NB_HIDE_ON_SINGLE_TAB | Hides the tab window if only one tab is present
AUI_NB_SMART_TABS | Use Smart Tabbing, like Alt + Tab on Windows
AUI_NB_USE_IMAGES_DROPDOWN | Uses images on dropdown window list menu instead of check items
AUI_NB_CLOSE_ON_TAB_LEFT | Draws the tab close button on the left instead of on the right (a la Camino browser)
AUI_NB_TAB_FLOAT | Allows the floating of single tabs. Known limitation: when the notebook is more or less full screen, tabs cannot be dragged far enough outside of the notebook to become floating pages
AUI_NB_DRAW_DND_TAB | Draws an image representation of a tab while dragging (on by default)
AUI_NB_ORDER_BY_ACCESS | Tab navigation order by last access time for the tabs
AUI_NB_NO_TAB_FOCUS | Don’t draw tab focus rectangle

SetCustomButton(bitmap_id, button_state, bmp) [source]

Sets a custom bitmap for the close, left, right and window list buttons.

Parameters:
  • bitmap_id – the button identifier;
  • button_state – the button state;
  • bmp – the custom bitmap to use for the button.

SetMeasuringFont(font) [source]

Sets the font for calculating text measurements.

Parameters: font – a wx.Font object.

SetNormalFont(font) [source]

Sets the normal font for drawing tab labels.

Parameters: font – a wx.Font object.

SetSelectedFont(font) [source]

Sets the selected tab font for drawing tab labels.

Parameters: font – a wx.Font object.

SetSizingInfo(tab_ctrl_size, tab_count, minMaxTabWidth) [source]

Sets the tab sizing information.

Parameters:
  • tab_ctrl_size – the size of the tab control area;
  • tab_count – the number of tabs;
  • minMaxTabWidth – a tuple containing the minimum and maximum tab widths to be used when the AUI_NB_TAB_FIXED_WIDTH style is active.

ShowDropDown(wnd, pages, active_idx) [source]

Shows the drop-down window menu on the tab area.

Parameters:
  • wnd – a wx.Window derived window instance;

  • pages – the pages associated with the tabs;
  • active_idx – the active tab index.

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • infobar
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • aui library »
  • aui.tabart »
  • AuiSimpleTabArt


ChromeTabArt

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • aui library »
  • aui.tabart »
  • ChromeTabArt

ChromeTabArt

A class to draw tabs using the Google Chrome browser style. It uses custom bitmap to render the tabs, so that the look and feel is as close as possible to the Chrome style.

hierarchy Inheritance Diagram

Inheritance diagram for: ChromeTabArt

Inheritance diagram of ChromeTabArt

supclasses Known Superclasses

  • aui.tabart.AuiDefaultTabArt

Methods Summary

__init__ | Default class constructor.
Clone | Clones the art object.
DrawTab | Draws a single tab.
GetTabSize | Returns the tab size for the given caption, bitmap and button state.
SetAGWFlags | Sets the tab art flags.
SetBitmaps | Assigns the tab custom bitmaps
SetSizingInfo | Sets the tab sizing information.

API Class API

class ChromeTabArt(AuiDefaultTabArt) [source]

A class to draw tabs using the Google Chrome browser style. It uses custom bitmap to render the tabs, so that the look and feel is as close as possible to the Chrome style.

__init__() [source]

Default class constructor.

Clone() [source]

Clones the art object.

DrawTab(dc, wnd, page, in_rect, close_button_state, paint_control=False) [source]

Draws a single tab.

Parameters:
  • dc – a wx.DC device context;
  • wnd – a wx.Window instance object;
  • page – the tab control page associated with the tab;
  • in_rect – rectangle the tab should be confined to;
  • close_button_state – the state of the close button on the tab;
  • paint_control – whether to draw the control inside a tab (if any) on a wx.MemoryDC.

GetTabSize(dc, wnd, caption, bitmap, active, close_button_state, control=None) [source]

Returns the tab size for the given caption, bitmap and button state.

Parameters:
  • dc – a wx.DC device context;

  • wnd – a wx.Window instance object;

  • caption – the tab text caption;
  • bitmap – the bitmap displayed on the tab;
  • active – whether the tab is selected or not;
  • close_button_state – the state of the close button on the tab;
  • control – a wx.Window instance inside a tab (or None).

SetAGWFlags(agwFlags) [source]

Sets the tab art flags.

Parameters: agwFlags – a combination of the following values:

Flag name | Description
AUI_NB_TOP | With this style, tabs are drawn along the top of the notebook
AUI_NB_LEFT | With this style, tabs are drawn along the left of the notebook. Not implemented yet.
AUI_NB_RIGHT | With this style, tabs are drawn along the right of the notebook. Not implemented yet.
AUI_NB_BOTTOM | With this style, tabs are drawn along the bottom of the notebook
AUI_NB_TAB_SPLIT | Allows the tab control to be split by dragging a tab
AUI_NB_TAB_MOVE | Allows a tab to be moved horizontally by dragging
AUI_NB_TAB_EXTERNAL_MOVE | Allows a tab to be moved to another tab control
AUI_NB_TAB_FIXED_WIDTH | With this style, all tabs have the same width
AUI_NB_SCROLL_BUTTONS | With this style, left and right scroll buttons are displayed
AUI_NB_WINDOWLIST_BUTTON | With this style, a drop-down list of windows is available
AUI_NB_CLOSE_BUTTON | With this style, a close button is available on the tab bar
AUI_NB_CLOSE_ON_ACTIVE_TAB | With this style, a close button is available on the active tab
AUI_NB_CLOSE_ON_ALL_TABS | With this style, a close button is available on all tabs
AUI_NB_MIDDLE_CLICK_CLOSE | Allows to close AuiNotebook tabs by mouse middle button click
AUI_NB_SUB_NOTEBOOK | This style is used by AuiManager to create automatic AuiNotebooks
AUI_NB_HIDE_ON_SINGLE_TAB | Hides the tab window if only one tab is present
AUI_NB_SMART_TABS | Use Smart Tabbing, like Alt + Tab on Windows
AUI_NB_USE_IMAGES_DROPDOWN | Uses images on dropdown window list menu instead of check items
AUI_NB_CLOSE_ON_TAB_LEFT | Draws the tab close button on the left instead of on the right (a la Camino browser)
AUI_NB_TAB_FLOAT | Allows the floating of single tabs. Known limitation: when the notebook is more or less full screen, tabs cannot be dragged far enough outside of the notebook to become floating pages
AUI_NB_DRAW_DND_TAB | Draws an image representation of a tab while dragging (on by default)
AUI_NB_ORDER_BY_ACCESS | Tab navigation order by last access time for the tabs
AUI_NB_NO_TAB_FOCUS | Don’t draw tab focus rectangle

Note

Overridden from AuiDefaultTabArt.

SetBitmaps(mirror) [source]

Assigns the tab custom bitmaps

Parameters: mirror – whether to vertically mirror the bitmap or not.

SetSizingInfo(tab_ctrl_size, tab_count, minMaxTabWidth) [source]

Sets the tab sizing information.

Parameters:
  • tab_ctrl_size – the size of the tab control area;
  • tab_count – the number of tabs;
  • minMaxTabWidth – a tuple containing the minimum and maximum tab widths to be used when the AUI_NB_TAB_FIXED_WIDTH style is active.

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • infobar
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • aui library »
  • aui.tabart »
  • ChromeTabArt


FF2TabArt

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • aui library »
  • aui.tabart »
  • FF2TabArt

FF2TabArt

A class to draw tabs using the Firefox 2 (FF2) style.

hierarchy Inheritance Diagram

Inheritance diagram for: FF2TabArt

Inheritance diagram of FF2TabArt

supclasses Known Superclasses

  • aui.tabart.AuiDefaultTabArt

Methods Summary

__init__ | Default class constructor.
Clone | Clones the art object.
DrawTab | Draws a single tab.
DrawTabBackground | Draws the tab background for the Firefox 2 style.
GetTabSize | Returns the tab size for the given caption, bitmap and button state.

API Class API

class FF2TabArt(AuiDefaultTabArt) [source]

A class to draw tabs using the Firefox 2 (FF2) style.

__init__() [source]

Default class constructor.

Clone() [source]

Clones the art object.

DrawTab(dc, wnd, page, in_rect, close_button_state, paint_control=False) [source]

Draws a single tab.

Parameters:
  • dc – a wx.DC device context;
  • wnd – a wx.Window instance object;
  • page – the tab control page associated with the tab;
  • in_rect – rectangle the tab should be confined to;
  • close_button_state – the state of the close button on the tab;
  • paint_control – whether to draw the control inside a tab (if any) on a wx.MemoryDC.

DrawTabBackground(dc, rect, focus, upperTabs) [source]

Draws the tab background for the Firefox 2 style. This is more consistent with FlatNotebook than before.

Parameters:
  • dc – a wx.DC device context;

  • rect – rectangle the tab should be confined to;
  • focus – whether the tab has focus or not;
  • upperTabs – whether the style is AUI_NB_TOP or AUI_NB_BOTTOM.

GetTabSize(dc, wnd, caption, bitmap, active, close_button_state, control) [source]

Returns the tab size for the given caption, bitmap and button state.

Parameters:
  • dc – a wx.DC device context;

  • wnd – a wx.Window instance object;

  • caption – the tab text caption;
  • bitmap – the bitmap displayed on the tab;
  • active – whether the tab is selected or not;
  • close_button_state – the state of the close button on the tab;
  • control – a wx.Window instance inside a tab (or None).

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • infobar
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • aui library »
  • aui.tabart »
  • FF2TabArt


VC8TabArt

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • aui library »
  • aui.tabart »
  • VC8TabArt

VC8TabArt

A class to draw tabs using the Visual Studio 2005 (VC8) style.

hierarchy Inheritance Diagram

Inheritance diagram for: VC8TabArt

Inheritance diagram of VC8TabArt

supclasses Known Superclasses

  • aui.tabart.AuiDefaultTabArt

Methods Summary

__init__ | Default class constructor.
Clone | Clones the art object.
DrawTab | Draws a single tab.
FillVC8GradientColour | Fills the tab with the Visual Studio 2005 gradient background.
GetTabSize | Returns the tab size for the given caption, bitmap and button state.
SetSizingInfo | Sets the tab sizing information.

API Class API

class VC8TabArt(AuiDefaultTabArt) [source]

A class to draw tabs using the Visual Studio 2005 (VC8) style.

__init__() [source]

Default class constructor.

Clone() [source]

Clones the art object.

DrawTab(dc, wnd, page, in_rect, close_button_state, paint_control=False) [source]

Draws a single tab.

Parameters:
  • dc – a wx.DC device context;
  • wnd – a wx.Window instance object;
  • page – the tab control page associated with the tab;
  • in_rect – rectangle the tab should be confined to;
  • close_button_state – the state of the close button on the tab;
  • paint_control – whether to draw the control inside a tab (if any) on a wx.MemoryDC.

FillVC8GradientColour(dc, tabPoints, active) [source]

Fills the tab with the Visual Studio 2005 gradient background.

Parameters:
  • dc – a wx.DC device context;

  • tabPoints – a list of wx.Point objects describing the tab shape;
  • active – whether the tab is selected or not.

GetTabSize(dc, wnd, caption, bitmap, active, close_button_state, control=None) [source]

Returns the tab size for the given caption, bitmap and button state.

Parameters:
  • dc – a wx.DC device context;

  • wnd – a wx.Window instance object;

  • caption – the tab text caption;
  • bitmap – the bitmap displayed on the tab;
  • active – whether the tab is selected or not;
  • close_button_state – the state of the close button on the tab;
  • control – a wx.Window instance inside a tab (or None).

SetSizingInfo(tab_ctrl_size, tab_count, minMaxTabWidth) [source]

Sets the tab sizing information.

Parameters:
  • tab_ctrl_size – the size of the tab control area;
  • tab_count – the number of tabs;
  • minMaxTabWidth – a tuple containing the minimum and maximum tab widths to be used when the AUI_NB_TAB_FIXED_WIDTH style is active.

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • infobar
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • aui library »
  • aui.tabart »
  • VC8TabArt


VC71TabArt

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • aui library »
  • aui.tabart »
  • VC71TabArt

VC71TabArt

A class to draw tabs using the Visual Studio 2003 (VC71) style.

hierarchy Inheritance Diagram

Inheritance diagram for: VC71TabArt

Inheritance diagram of VC71TabArt

supclasses Known Superclasses

  • aui.tabart.AuiDefaultTabArt

Methods Summary

__init__ | Default class constructor.
Clone | Clones the art object.
DrawTab | Draws a single tab.

API Class API

class VC71TabArt(AuiDefaultTabArt) [source]

A class to draw tabs using the Visual Studio 2003 (VC71) style.

__init__() [source]

Default class constructor.

Clone() [source]

Clones the art object.

DrawTab(dc, wnd, page, in_rect, close_button_state, paint_control=False) [source]

Draws a single tab.

Parameters:
  • dc – a wx.DC device context;
  • wnd – a wx.Window instance object;
  • page – the tab control page associated with the tab;
  • in_rect – rectangle the tab should be confined to;
  • close_button_state – the state of the close button on the tab;
  • paint_control – whether to draw the control inside a tab (if any) on a wx.MemoryDC.

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • infobar
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • aui library »
  • aui.tabart »
  • VC71TabArt


aui.tabart

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • aui library »
  • aui.tabart

aui.tabart

Tab art provider code - a tab provider provides all drawing functionality to the AuiNotebook. This allows the AuiNotebook to have a plugable look-and-feel.

By default, a AuiNotebook uses an instance of this class called AuiDefaultTabArt which provides bitmap art and a colour scheme that is adapted to the major platforms’ look. You can either derive from that class to alter its behaviour or write a completely new tab art class. Call SetArtProvider to make use this new tab art.

Module author: Andrea Gavana <andrea.gavana@gmail.com>

hierarchy Inheritance Diagram

Inheritance diagram for module: aui.tabart

Inheritance diagram of aui.tabart.AuiCommandCapture, aui.tabart.AuiDefaultTabArt, aui.tabart.AuiSimpleTabArt, aui.tabart.ChromeTabArt, aui.tabart.FF2TabArt, aui.tabart.VC71TabArt, aui.tabart.VC8TabArt

SVN Revisions

A graphical representation of the SVN commits in the last year.

Click on any date in the picture to jump to that particular revision page, containing information about committers, log messages and SVN diffs.

Revision Graph For tabart

2to3 Python 3 Issues (via 2to3)

No issues have been detected by 2to3.py.

Class Summary

  • AuiCommandCapture
  • AuiDefaultTabArt
  • AuiSimpleTabArt
  • ChromeTabArt
  • FF2TabArt
  • VC71TabArt
  • VC8TabArt

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • infobar
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • aui library »
  • aui.tabart


SVN Revision 69086 For aui_utilities

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • aui library »
  • aui.aui_utilities »
  • SVN Revision 69086 For aui_utilities

svn SVN Revision 69086 For aui_utilities

This file contains the SVN revision history for aui_utilities, at revision 69086.

Available information include commit date, the name of the committer, the file size, the SVN log messages and a diff from the previous version (if available).

File Information

  • Commit Date: 31-Mar-2009 15:36:51 UTC
  • Committer: AG
  • File Size: 20341 byte(s)

Log Messages

The following log message was entered by the committer:

  • Fixed bug #13437 for SuperToolTip;
  • Fixed bug #13477 for UltimateListCtrl.

Diff To Previous Version (62851)

Version SVN diff:

--- wxPython/3rdParty/AGW/agw/aui/aui_utilities.py  2009/12/10 18:09:38     62851
+++ wxPython/3rdParty/AGW/agw/aui/aui_utilities.py  2011/09/14 19:39:08     69086
@@ -149,7 +149,7 @@
"""
Indents the input rectangle `rect` based on the value of `button_state`.

-    :param `rect`: an instance of wx.Rect;
+    :param `rect`: an instance of `wx.Rect`;
:param `button_state`: an L{AuiNotebook} button state.
"""

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • aui library »
  • aui.aui_utilities »
  • SVN Revision 69086 For aui_utilities


SVN Revision 68021 For auibar

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • aui library »
  • aui.auibar »
  • SVN Revision 68021 For auibar

svn SVN Revision 68021 For auibar

This file contains the SVN revision history for auibar, at revision 68021.

Available information include commit date, the name of the committer, the file size, the SVN log messages and a diff from the previous version (if available).

File Information

  • Commit Date: 07-Apr-2009 17:33:16 UTC
  • Committer: AG
  • File Size: 130636 byte(s)

Log Messages

The following log message was entered by the committer:

  • Fixed bug #13269 for CustomTreeCtrl and HyperTreeList (thanks to Frank Niessink);
  • Fixed bug #13268 for AuiToolBar;
  • Fixed bug #13107 on AuiNotebook.

Diff To Previous Version (65721)

Version SVN diff:

--- wxPython/3rdParty/AGW/agw/aui/auibar.py 2010/10/01 21:03:22     65721
+++ wxPython/3rdParty/AGW/agw/aui/auibar.py 2011/06/22 19:56:23     68021
@@ -3664,8 +3664,8 @@
if self._overflow_sizer_item:

dropdown_size = self._art.GetElementSize(AUI_TBART_OVERFLOW_SIZE)
-            if dropdown_size > 0 and event.m_x > cli_rect.width - dropdown_size and \
-               event.m_y >= 0 and event.m_y < cli_rect.height and self._art:
+            if dropdown_size > 0 and event.GetX() > cli_rect.width - dropdown_size and \
+               event.GetY() >= 0 and event.GetY() < cli_rect.height and self._art:
return

self._action_pos = wx.Point(*event.GetPosition())
@@ -3730,8 +3730,8 @@
if self._overflow_sizer_item:

dropdown_size = self._art.GetElementSize(AUI_TBART_OVERFLOW_SIZE)
-            if dropdown_size > 0 and event.m_x > cli_rect.width - dropdown_size and \
-               event.m_y >= 0 and event.m_y < cli_rect.height and self._art:
+            if dropdown_size > 0 and event.GetX() > cli_rect.width - dropdown_size and \
+               event.GetY() >= 0 and event.GetY() < cli_rect.height and self._art:
return

self._action_pos = wx.Point(*event.GetPosition())
@@ -3778,7 +3778,7 @@

# start a drag event
if not self._dragging and self._action_item != None and self._action_pos != wx.Point(-1, -1) and \
-           abs(event.m_x - self._action_pos.x) + abs(event.m_y - self._action_pos.y) > 5:
+           abs(event.GetX() - self._action_pos.x) + abs(event.GetY() - self._action_pos.y) > 5:

self.SetToolTipString("")
self._dragging = True

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • aui library »
  • aui.auibar »
  • SVN Revision 68021 For auibar


SVN Revision 68475 For auibar

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • aui library »
  • aui.auibar »
  • SVN Revision 68475 For auibar

svn SVN Revision 68475 For auibar

This file contains the SVN revision history for auibar, at revision 68475.

Available information include commit date, the name of the committer, the file size, the SVN log messages and a diff from the previous version (if available).

File Information

  • Commit Date: 07-Apr-2009 11:10:38 UTC
  • Committer: AG
  • File Size: 131533 byte(s)

Log Messages

The following log message was entered by the committer:

framemanager.py: Implementation of the AUI_MINIMIZE_POS_TOOLBAR flag, which allows to minimize a pane inside an existing toolbar. Limitation: if the minimized icon in the toolbar ends up in the overflowing items (i.e., a menu is needed to show the icon), this style will not work.

Diff To Previous Version (68021)

Version SVN diff:

--- wxPython/3rdParty/AGW/agw/aui/auibar.py 2011/06/22 19:56:23     68021
+++ wxPython/3rdParty/AGW/agw/aui/auibar.py 2011/07/31 20:22:23     68475
@@ -299,6 +299,7 @@
self.hover_bitmap = wx.NullBitmap
self.short_help = ""
self.long_help = ""
+        self.target = None
self.min_size = wx.Size(-1, -1)
self.alignment = wx.ALIGN_CENTER
self.orientation = AUI_TBTOOL_HORIZONTAL
@@ -331,6 +332,7 @@
self.user_data = c.user_data
self.alignment = c.alignment
self.orientation = c.orientation
+        self.target = c.target

def SetWindow(self, w):
@@ -1694,7 +1696,7 @@
return self._art

-    def AddSimpleTool(self, tool_id, label, bitmap, short_help_string="", kind=ITEM_NORMAL):
+    def AddSimpleTool(self, tool_id, label, bitmap, short_help_string="", kind=ITEM_NORMAL, target=None):
"""
Adds a tool to the toolbar. This is the simplest method you can use to
ass an item to the L{AuiToolBar}.
@@ -1716,9 +1718,12 @@
``ITEM_NORMAL``           The item in the `AuiToolBar` is a standard toolbar item
``ITEM_RADIO``            The item in the `AuiToolBar` is a toolbar radio item
========================  =============================
+
+        :param `target`: a custom string indicating that an instance of L{framemanager.AuiPaneInfo}
+         has been minimized into this toolbar.
"""

-        return self.AddTool(tool_id, label, bitmap, wx.NullBitmap, kind, short_help_string, "", None)
+        return self.AddTool(tool_id, label, bitmap, wx.NullBitmap, kind, short_help_string, "", None, target)

def AddToggleTool(self, tool_id, bitmap, disabled_bitmap, toggle=False, client_data=None, short_help_string="", long_help_string=""):
@@ -1739,7 +1744,7 @@
return self.AddTool(tool_id, "", bitmap, disabled_bitmap, kind, short_help_string, long_help_string, client_data)

-    def AddTool(self, tool_id, label, bitmap, disabled_bitmap, kind, short_help_string, long_help_string, client_data):
+    def AddTool(self, tool_id, label, bitmap, disabled_bitmap, kind, short_help_string, long_help_string, client_data, target):
"""
Adds a tool to the toolbar. This is the full feature version of L{AddTool}.

@@ -1766,6 +1771,8 @@
:param `long_help_string`: this string is shown in the statusbar (if any) of the parent
frame when the mouse pointer is inside the tool.
:param `client_data`: whatever Python object to associate with the toolbar item.
+        :param `target`: a custom string indicating that an instance of L{framemanager.AuiPaneInfo}
+         has been minimized into this toolbar.
"""

item = AuiToolBarItem()
@@ -1775,6 +1782,7 @@
item.disabled_bitmap = disabled_bitmap
item.short_help = short_help_string
item.long_help = long_help_string
+        item.target = target
item.active = True
item.dropdown = False
item.spacer_pixels = 0
@@ -2063,6 +2071,20 @@
return None

+    def FindToolByLabel(self, label):
+        """
+        Finds a tool for the given label.
+
+        :param `tool_id`: the L{AuiToolBarItem} label.
+        """
+
+        for item in self._items:
+            if item.label == label:
+                return item
+
+        return None
+
+
def FindToolForPosition(self, x, y):
"""
Finds a tool for the given mouse position.
@@ -3625,7 +3647,11 @@
if not manager:
return

-                        pane = manager.GetPane(self)
+                        if self._action_item.target:
+                            pane = manager.GetPane(self._action_item.target)
+                        else:
+                            pane = manager.GetPane(self)
+
e = framemanager.AuiManagerEvent(framemanager.wxEVT_AUI_PANE_MIN_RESTORE)

e.SetManager(manager)

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • aui library »
  • aui.auibar »
  • SVN Revision 68475 For auibar


SVN Revision 69097 For auibar

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • aui library »
  • aui.auibar »
  • SVN Revision 69097 For auibar

svn SVN Revision 69097 For auibar

This file contains the SVN revision history for auibar, at revision 69097.

Available information include commit date, the name of the committer, the file size, the SVN log messages and a diff from the previous version (if available).

File Information

  • Commit Date: 06-Apr-2009 10:55:48 UTC
  • Committer: AG
  • File Size: 131744 byte(s)

Log Messages

The following log message was entered by the committer:

Fix AuiToolBar disabled items text colour

Diff To Previous Version (68475)

Version SVN diff:

--- wxPython/3rdParty/AGW/agw/aui/auibar.py 2011/07/31 20:22:23     68475
+++ wxPython/3rdParty/AGW/agw/aui/auibar.py 2011/09/15 20:14:29     69097
@@ -936,7 +936,12 @@
"""

dc.SetFont(self._font)
-        dc.SetTextForeground(wx.BLACK)
+
+        if item.state & AUI_BUTTON_STATE_DISABLED:
+            dc.SetTextForeground(wx.SystemSettings.GetColour(wx.SYS_COLOUR_GRAYTEXT))
+        else:
+            dc.SetTextForeground(wx.SystemSettings.GetColour(wx.SYS_COLOUR_BTNTEXT))
+
orient = item.GetOrientation()

horizontal = orient == AUI_TBTOOL_HORIZONTAL

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • aui library »
  • aui.auibar »
  • SVN Revision 69097 For auibar


SVN Revision 69147 For auibar

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • aui library »
  • aui.auibar »
  • SVN Revision 69147 For auibar

svn SVN Revision 69147 For auibar

This file contains the SVN revision history for auibar, at revision 69147.

Available information include commit date, the name of the committer, the file size, the SVN log messages and a diff from the previous version (if available).

File Information

  • Commit Date: 02-Apr-2009 10:53:15 UTC
  • Committer: AG
  • File Size: 132209 byte(s)

Log Messages

The following log message was entered by the committer:

AuiToolBar: applied patch from nagylzs, fixing bug #13489.

Diff To Previous Version (69097)

Version SVN diff:

--- wxPython/3rdParty/AGW/agw/aui/auibar.py 2011/09/15 20:14:29     69097
+++ wxPython/3rdParty/AGW/agw/aui/auibar.py 2011/09/18 19:50:28     69147
@@ -2116,6 +2116,21 @@
return None

+    def HitTest(self, x, y):
+        """
+        Finds a tool for the given mouse position.
+
+        :param `x`: mouse `x` position;
+        :param `y`: mouse `y` position.
+
+        :returns: a pointer to a L{AuiToolBarItem} if a tool is found, or ``None`` otherwise.
+
+        :note: This method is similar to L{FindToolForPosition} but it works with absolute coordinates.
+        """
+
+        return self.FindToolForPosition(*self.ScreenToClient((x,y)))
+
+
def FindToolForPositionWithPacking(self, x, y):
"""
Finds a tool for the given mouse position, taking into account also the

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • aui library »
  • aui.auibar »
  • SVN Revision 69147 For auibar


SVN Revision 69315 For auibar

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • aui library »
  • aui.auibar »
  • SVN Revision 69315 For auibar

svn SVN Revision 69315 For auibar

This file contains the SVN revision history for auibar, at revision 69315.

Available information include commit date, the name of the committer, the file size, the SVN log messages and a diff from the previous version (if available).

File Information

  • Commit Date: 01-Apr-2009 02:45:51 UTC
  • Committer: AG
  • File Size: 132245 byte(s)

Log Messages

The following log message was entered by the committer:

  • HyperTreeList: fixed missing GetPrev method and associated TypeError;
  • AuiToolBar: don’t draw the gripper if the AuiToolBar style doesn’t contain the AUI_TB_GRIPPER bit.

Diff To Previous Version (69147)

Version SVN diff:

--- wxPython/3rdParty/AGW/agw/aui/auibar.py 2011/09/18 19:50:28     69147
+++ wxPython/3rdParty/AGW/agw/aui/auibar.py 2011/10/05 19:01:34     69315
@@ -3416,7 +3416,7 @@
dropdown_size = self._art.GetElementSize(AUI_TBART_OVERFLOW_SIZE)

# paint the gripper
-        if gripper_size > 0 and self._gripper_sizer_item:
+        if self._agwStyle & AUI_TB_GRIPPER and gripper_size > 0 and self._gripper_sizer_item:
gripper_rect = wx.Rect(*self._gripper_sizer_item.GetRect())
if horizontal:
gripper_rect.width = gripper_size

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • aui library »
  • aui.auibar »
  • SVN Revision 69315 For auibar


SVN Revision 69982 For auibar

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • aui library »
  • aui.auibar »
  • SVN Revision 69982 For auibar

svn SVN Revision 69982 For auibar

This file contains the SVN revision history for auibar, at revision 69982.

Available information include commit date, the name of the committer, the file size, the SVN log messages and a diff from the previous version (if available).

File Information

  • Commit Date: 31-Mar-2009 16:34:20 UTC
  • Committer: AG
  • File Size: 132261 byte(s)

Log Messages

The following log message was entered by the committer:

  • AuiToolBar: fixed mixed keyword-non keyword signature of AddTool.

Diff To Previous Version (69315)

Version SVN diff:

--- wxPython/3rdParty/AGW/agw/aui/auibar.py 2011/10/05 19:01:34     69315
+++ wxPython/3rdParty/AGW/agw/aui/auibar.py 2011/12/11 09:15:20     69982
@@ -1749,7 +1749,7 @@
return self.AddTool(tool_id, "", bitmap, disabled_bitmap, kind, short_help_string, long_help_string, client_data)

-    def AddTool(self, tool_id, label, bitmap, disabled_bitmap, kind, short_help_string, long_help_string, client_data, target):
+    def AddTool(self, tool_id, label, bitmap, disabled_bitmap, kind, short_help_string='', long_help_string='', client_data=None, target=None):
"""
Adds a tool to the toolbar. This is the full feature version of L{AddTool}.

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • aui library »
  • aui.auibar »
  • SVN Revision 69982 For auibar


SVN Revision 70555 For auibar

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • aui library »
  • aui.auibar »
  • SVN Revision 70555 For auibar

svn SVN Revision 70555 For auibar

This file contains the SVN revision history for auibar, at revision 70555.

Available information include commit date, the name of the committer, the file size, the SVN log messages and a diff from the previous version (if available).

File Information

  • Commit Date: 31-Mar-2009 15:36:51 UTC
  • Committer: AG
  • File Size: 132527 byte(s)

Log Messages

The following log message was entered by the committer:

  • GradientButton: applied patch from Werner and cleaned up a bit the useless parts of the code;
  • AuiToolBar/AuiDefaultDockArt: applied patch from Werner for default colour settings for AUI toolbars;
  • UltimateListCtrl: Fixed bug #13938. Also, don’t throw an error on key down if the list is empty.

Diff To Previous Version (69982)

Version SVN diff:

--- wxPython/3rdParty/AGW/agw/aui/auibar.py 2011/12/11 09:15:20     69982
+++ wxPython/3rdParty/AGW/agw/aui/auibar.py 2012/02/09 20:52:26     70555
@@ -733,8 +733,8 @@

def __init__(self):
""" Default class constructor. """
-
-        self._base_colour = GetBaseColour()
+
+        self.SetDefaultColours()

self._agwFlags = 0
self._text_orientation = AUI_TBTOOL_TEXT_BOTTOM
@@ -745,16 +745,6 @@
self._gripper_size = 7
self._overflow_size = 16

-        darker1_colour = StepColour(self._base_colour, 85)
-        darker2_colour = StepColour(self._base_colour, 75)
-        darker3_colour = StepColour(self._base_colour, 60)
-        darker4_colour = StepColour(self._base_colour, 50)
-        darker5_colour = StepColour(self._base_colour, 40)
-
-        self._gripper_pen1 = wx.Pen(darker5_colour)
-        self._gripper_pen2 = wx.Pen(darker3_colour)
-        self._gripper_pen3 = wx.WHITE_PEN
-
button_dropdown_bits = "\xe0\xf1\xfb"
overflow_bits = "\x80\xff\x80\xc1\xe3\xf7"

@@ -767,6 +757,27 @@
self._font = wx.SystemSettings.GetFont(wx.SYS_DEFAULT_GUI_FONT)

+    def SetDefaultColours(self, base_colour=None):
+        """
+        Sets the default colours, which are calculated from the given base colour.
+
+        :param `base_colour`: an instance of `wx.Colour`. If defaulted to ``None``, a colour
+         is generated accordingly to the platform and theme.
+        """
+
+        if base_colour is None:
+            self._base_colour = GetBaseColour()
+        else:
+            self._base_colour = base_colour
+
+        darker3_colour = StepColour(self._base_colour, 60)
+        darker5_colour = StepColour(self._base_colour, 40)
+
+        self._gripper_pen1 = wx.Pen(darker5_colour)
+        self._gripper_pen2 = wx.Pen(darker3_colour)
+        self._gripper_pen3 = wx.WHITE_PEN
+
+
def Clone(self):
""" Clones the L{AuiToolBar} art. """

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • aui library »
  • aui.auibar »
  • SVN Revision 70555 For auibar


SVN Revision 68021 For auibook

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • aui library »
  • aui.auibook »
  • SVN Revision 68021 For auibook

svn SVN Revision 68021 For auibook

This file contains the SVN revision history for auibook, at revision 68021.

Available information include commit date, the name of the committer, the file size, the SVN log messages and a diff from the previous version (if available).

File Information

  • Commit Date: 21-Apr-2009 13:41:28 UTC
  • Committer: AG
  • File Size: 191735 byte(s)

Log Messages

The following log message was entered by the committer:

  • Fixed bug #13269 for CustomTreeCtrl and HyperTreeList (thanks to Frank Niessink);
  • Fixed bug #13268 for AuiToolBar;
  • Fixed bug #13107 on AuiNotebook.

Diff To Previous Version (67166)

Version SVN diff:

--- wxPython/3rdParty/AGW/agw/aui/auibook.py        2011/03/10 13:52:18     67166
+++ wxPython/3rdParty/AGW/agw/aui/auibook.py        2011/06/22 19:56:23     68021
@@ -2682,6 +2682,7 @@
self._requested_tabctrl_height = -1
self._textCtrl = None
self._tabBounds = (-1, -1)
+        self._click_tab = None

wx.PyPanel.__init__(self, parent, id, pos, size, style|wx.BORDER_NONE|wx.TAB_TRAVERSAL)
self._mgr = framemanager.AuiManager()

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • aui library »
  • aui.auibook »
  • SVN Revision 68021 For auibook


SVN Revision 68342 For auibook

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • aui library »
  • aui.auibook »
  • SVN Revision 68342 For auibook

svn SVN Revision 68342 For auibook

This file contains the SVN revision history for auibook, at revision 68342.

Available information include commit date, the name of the committer, the file size, the SVN log messages and a diff from the previous version (if available).

File Information

  • Commit Date: 17-Apr-2009 14:49:01 UTC
  • Committer: AG
  • File Size: 191865 byte(s)

Log Messages

The following log message was entered by the committer:

  • ToasterBox: fixed ticket #13258. It appears wx.FRAME_TOOL_WINDOW doesn’t work as expected on Windows 7
  • AuiNotebook: fixed tickets #12800 and #12919

Diff To Previous Version (68021)

Version SVN diff:

--- wxPython/3rdParty/AGW/agw/aui/auibook.py        2011/06/22 19:56:23     68021
+++ wxPython/3rdParty/AGW/agw/aui/auibook.py        2011/07/23 19:06:24     68342
@@ -3618,12 +3618,15 @@
"""

if page >= self._tabs.GetPageCount():
-            return False
+            return wx.NOT_FOUND

bitmap = self.GetPageBitmap(page)
+        bmpData1 = bitmap.ConvertToImage().GetData()
+
for indx in xrange(self._imageList.GetImageCount()):
imgListBmp = self._imageList.GetBitmap(indx)
-            if imgListBmp == bitmap:
+            bmpData2 = imgListBmp.ConvertToImage().GetData()
+            if bmpData1 == bmpData2:
return indx

return wx.NOT_FOUND

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • aui library »
  • aui.auibook »
  • SVN Revision 68342 For auibook


SVN Revision 68742 For auibook

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • aui library »
  • aui.auibook »
  • SVN Revision 68742 For auibook

svn SVN Revision 68742 For auibook

This file contains the SVN revision history for auibook, at revision 68742.

Available information include commit date, the name of the committer, the file size, the SVN log messages and a diff from the previous version (if available).

File Information

  • Commit Date: 09-Apr-2009 16:25:54 UTC
  • Committer: AG
  • File Size: 193376 byte(s)

Log Messages

The following log message was entered by the committer:

  • FlatNotebook: fix issues with custom page and vertical/horizontal tiling of pages;
  • AuiBook: every time the AuiBook is split, copy over the custom buttons in the tab area of the newly created AuiBook;
  • Others: minor modifications to the docstrings.

Diff To Previous Version (68342)

Version SVN diff:

--- wxPython/3rdParty/AGW/agw/aui/auibook.py        2011/07/23 19:06:24     68342
+++ wxPython/3rdParty/AGW/agw/aui/auibook.py        2011/08/16 16:37:37     68742
@@ -795,7 +795,7 @@
Default class constructor.
Used internally, do not call it in your code!

-        :param `auiNotebook`: the parent L{AuiNotebook} window.
+        :param `auiNotebook`: the parent L{AuiNotebook} window.
"""

self._tab_offset = 0
@@ -1204,6 +1204,30 @@
self._buttons.append(button)

+    def CloneButtons(self):
+        """
+        Clones the tab area buttons when the L{AuiNotebook} is being split.
+
+        :see: L{AddButton}
+
+        :note: Standard buttons for L{AuiNotebook} are not cloned, only custom ones.
+        """
+
+        singleton_list = [AUI_BUTTON_CLOSE, AUI_BUTTON_WINDOWLIST, AUI_BUTTON_LEFT, AUI_BUTTON_RIGHT]
+        clones = []
+
+        for button in self._buttons:
+            if button.id not in singleton_list:
+                new_button = AuiTabContainerButton()
+                new_button.id = button.id
+                new_button.bitmap = button.bitmap
+                new_button.dis_bitmap = button.dis_bitmap
+                new_button.location = button.location
+                clones.append(new_button)
+
+        return clones
+
+
def RemoveButton(self, id):
"""
Removes a button from the tab area.
@@ -1991,7 +2015,7 @@
if not isinstance(eventHandler, AuiTabCtrl):
event.Skip()
return
-
+
x, y = event.GetX(), event.GetY()
wnd = self.TabHitTest(x, y)

@@ -3622,7 +3646,7 @@

bitmap = self.GetPageBitmap(page)
bmpData1 = bitmap.ConvertToImage().GetData()
-
+
for indx in xrange(self._imageList.GetImageCount()):
imgListBmp = self._imageList.GetBitmap(indx)
bmpData2 = imgListBmp.ConvertToImage().GetData()
@@ -4123,6 +4147,9 @@
if page_info.control:
self.ReparentControl(page_info.control, dest_tabs)

+        cloned_buttons = self.CloneTabAreaButtons()
+        for clone in cloned_buttons:
+            dest_tabs.AddButton(clone.id, clone.location, clone.bitmap, clone.dis_bitmap)
# create a pane info structure with the information
# about where the pane should be added
pane_info = framemanager.AuiPaneInfo().Bottom().CaptionVisible(False)
@@ -4720,6 +4747,9 @@
self._mgr.Update()
dest_tabs = new_tabs._tabs

+                cloned_buttons = self.CloneTabAreaButtons()
+                for clone in cloned_buttons:
+                    dest_tabs.AddButton(clone.id, clone.location, clone.bitmap, clone.dis_bitmap)
# remove the page from the source tabs
page_info = src_tabs.GetPage(event.GetSelection())

@@ -5543,6 +5573,21 @@
active_tabctrl.RemoveButton(id)

+    def CloneTabAreaButtons(self):
+        """
+        Clones the tab area buttons when the L{AuiNotebook} is being split.
+
+        :see: L{AddTabAreaButton}
+
+        :note: Standard buttons for L{AuiNotebook} are not cloned, only custom ones.
+        """
+
+        active_tabctrl = self.GetActiveTabCtrl()
+        clones = active_tabctrl.CloneButtons()
+
+        return clones
+
+
def HasMultiplePages(self):
"""
This method should be overridden to return ``True`` if this window has multiple pages. All

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • aui library »
  • aui.auibook »
  • SVN Revision 68742 For auibook


SVN Revision 69086 For auibook

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • aui library »
  • aui.auibook »
  • SVN Revision 69086 For auibook

svn SVN Revision 69086 For auibook

This file contains the SVN revision history for auibook, at revision 69086.

Available information include commit date, the name of the committer, the file size, the SVN log messages and a diff from the previous version (if available).

File Information

  • Commit Date: 08-Apr-2009 15:24:09 UTC
  • Committer: AG
  • File Size: 193382 byte(s)

Log Messages

The following log message was entered by the committer:

  • Fixed bug #13437 for SuperToolTip;
  • Fixed bug #13477 for UltimateListCtrl.

Diff To Previous Version (68742)

Version SVN diff:

--- wxPython/3rdParty/AGW/agw/aui/auibook.py        2011/08/16 16:37:37     68742
+++ wxPython/3rdParty/AGW/agw/aui/auibook.py        2011/09/14 19:39:08     69086
@@ -700,7 +700,7 @@

def OnItemSelected(self, event):
"""
-        Handles the ``wx.EVT_LISTBOX_DCLICK`` event for the wx.ListBox inside L{TabNavigatorWindow}.
+        Handles the ``wx.EVT_LISTBOX_DCLICK`` event for the `wx.ListBox` inside L{TabNavigatorWindow}.

:param `event`: a `wx.ListEvent` event to be processed.
"""
@@ -786,7 +786,7 @@
the L{AuiManager}, where it is disadvantageous to have separate
windows for each tab control in the case of "docked tabs".

-    A derived class, L{AuiTabCtrl}, is an actual `wx.Window`-derived window
+    A derived class, L{AuiTabCtrl}, is an actual `wx.Window` - derived window
which can be used as a tab control in the normal sense.
"""

@@ -1730,7 +1730,7 @@

class AuiTabCtrl(wx.PyControl, AuiTabContainer):
"""
-    This is an actual `wx.Window`-derived window which can be used as a tab
+    This is an actual `wx.Window` - derived window which can be used as a tab
control in the normal sense.
"""

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • aui library »
  • aui.auibook »
  • SVN Revision 69086 For auibook


SVN Revision 69163 For auibook

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • aui library »
  • aui.auibook »
  • SVN Revision 69163 For auibook

svn SVN Revision 69163 For auibook

This file contains the SVN revision history for auibook, at revision 69163.

Available information include commit date, the name of the committer, the file size, the SVN log messages and a diff from the previous version (if available).

File Information

  • Commit Date: 07-Apr-2009 16:09:59 UTC
  • Committer: AG
  • File Size: 193484 byte(s)

Log Messages

The following log message was entered by the committer:

AuiNotebook: implement the Selection property in CommandNotebookEvent. Closes #13491.

Diff To Previous Version (69086)

Version SVN diff:

--- wxPython/3rdParty/AGW/agw/aui/auibook.py        2011/09/14 19:39:08     69086
+++ wxPython/3rdParty/AGW/agw/aui/auibook.py        2011/09/20 17:26:19     69163
@@ -484,6 +484,8 @@
self.label = label

+    Selection = property(lambda self: self.GetSelection(), lambda self, sel: self.SetSelection(sel))
+
# ----------------------------------------------------------------------

class AuiNotebookEvent(CommandNotebookEvent):

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • aui library »
  • aui.auibook »
  • SVN Revision 69163 For auibook


SVN Revision 69232 For auibook

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • aui library »
  • aui.auibook »
  • SVN Revision 69232 For auibook

svn SVN Revision 69232 For auibook

This file contains the SVN revision history for auibook, at revision 69232.

Available information include commit date, the name of the committer, the file size, the SVN log messages and a diff from the previous version (if available).

File Information

  • Commit Date: 07-Apr-2009 11:03:26 UTC
  • Committer: AG
  • File Size: 194522 byte(s)

Log Messages

The following log message was entered by the committer:

Applied patch from Cody Precord adding a new data container class and some properties to AuiNotebook used to customize some attributes of the TabNavigator window (Ctrl+Tab).

Diff To Previous Version (69163)

Version SVN diff:

--- wxPython/3rdParty/AGW/agw/aui/auibook.py        2011/09/20 17:26:19     69163
+++ wxPython/3rdParty/AGW/agw/aui/auibook.py        2011/09/29 19:16:48     69232
@@ -543,6 +543,34 @@

# ---------------------------------------------------------------------------- #
+# Class TabNavigatorProps
+# ---------------------------------------------------------------------------- #
+
+class TabNavigatorProps(object):
+    """
+    Data storage class for managing and providing access to L{TabNavigatorWindow}
+    properties.
+    """
+
+    def __init__(self):
+        """ Default class constructor. """
+
+        super(TabNavigatorProps, self).__init__()
+
+        # Attributes
+        self._icon = wx.NullBitmap
+        self._font = wx.NullFont
+        self._minsize = wx.DefaultSize
+
+    # Accessors
+    Icon = property(lambda self: self._icon,
+                    lambda self, icon: setattr(self, '_icon', icon))
+    Font = property(lambda self: self._font,
+                    lambda self, font: setattr(self, '_font', font))
+    MinSize = property(lambda self: self._minsize,
+                       lambda self, size: setattr(self, '_minsize', size))
+
+# ---------------------------------------------------------------------------- #
# Class TabNavigatorWindow
# ---------------------------------------------------------------------------- #

@@ -552,32 +580,37 @@
similar to what you would get by hitting ``Alt`` + ``Tab`` on Windows.
"""

-    def __init__(self, parent=None, icon=None):
+    def __init__(self, parent, props):
"""
Default class constructor. Used internally.

:param `parent`: the L{TabNavigatorWindow} parent;
-        :param `icon`: the L{TabNavigatorWindow} icon.
+        :param `props`: the L{TabNavigatorProps} object.
"""

-        wx.Dialog.__init__(self, parent, wx.ID_ANY, "", style=0)
+        wx.Dialog.__init__(self, parent, wx.ID_ANY, "", size=props.MinSize, style=0)

self._selectedItem = -1
self._indexMap = []
+        self._props = props

-        if icon is None:
-            self._bmp = Mondrian.GetBitmap()
-        else:
-            self._bmp = icon
+        if not self._props.Icon.IsOk():
+            self._props.Icon = Mondrian.GetBitmap()

-        if self._bmp.GetSize() != (16, 16):
-            img = self._bmp.ConvertToImage()
+        if props.Icon.GetSize() != (16, 16):
+            img = self._props.Icon.ConvertToImage()
img.Rescale(16, 16, wx.IMAGE_QUALITY_HIGH)
-            self._bmp = wx.BitmapFromImage(img)
+            self._props.Icon = wx.BitmapFromImage(img)
+
+        if self._props.Font.IsOk():
+            self.Font = self._props.Font

sz = wx.BoxSizer(wx.VERTICAL)

-        self._listBox = wx.ListBox(self, wx.ID_ANY, wx.DefaultPosition, wx.Size(200, 150), [], wx.LB_SINGLE | wx.NO_BORDER)
+        self._listBox = wx.ListBox(self, wx.ID_ANY,
+                                   wx.DefaultPosition,
+                                   wx.Size(200, 150), [],
+                                   wx.LB_SINGLE | wx.NO_BORDER)

mem_dc = wx.MemoryDC()
mem_dc.SelectObject(wx.EmptyBitmap(1,1))
@@ -592,9 +625,10 @@
if panelHeight < 24:
panelHeight = 24

-        self._panel = wx.Panel(self, wx.ID_ANY, wx.DefaultPosition, wx.Size(200, panelHeight))
+        self._panel = wx.Panel(self, wx.ID_ANY, wx.DefaultPosition,
+                               wx.Size(-1, panelHeight))

-        sz.Add(self._panel)
+        sz.Add(self._panel, 0, wx.EXPAND)
sz.Add(self._listBox, 1, wx.EXPAND)

self.SetSizer(sz)
@@ -612,9 +646,7 @@
self._listBox.SetBackgroundColour(wx.SystemSettings_GetColour(wx.SYS_COLOUR_3DFACE))
self.PopulateListControl(parent)

-        self.GetSizer().Fit(self)
-        self.GetSizer().SetSizeHints(self)
-        self.GetSizer().Layout()
+        self.SetInitialSize(props.MinSize)
self.Centre()

# Set focus on the list box to avoid having to click on it to change
@@ -746,9 +778,9 @@
# Draw the caption title and place the bitmap
# get the bitmap optimal position, and draw it
bmpPt, txtPt = wx.Point(), wx.Point()
-        bmpPt.y = (rect.height - self._bmp.GetHeight())/2
+        bmpPt.y = (rect.height - self._props.Icon.GetHeight())/2
bmpPt.x = 3
-        mem_dc.DrawBitmap(self._bmp, bmpPt.x, bmpPt.y, True)
+        mem_dc.DrawBitmap(self._props.Icon, bmpPt.x, bmpPt.y, True)

# get the text position, and draw it
font = wx.SystemSettings_GetFont(wx.SYS_DEFAULT_GUI_FONT)
@@ -756,7 +788,7 @@
mem_dc.SetFont(font)
fontHeight = mem_dc.GetCharHeight()

-        txtPt.x = bmpPt.x + self._bmp.GetWidth() + 4
+        txtPt.x = bmpPt.x + self._props.Icon.GetWidth() + 4
txtPt.y = (rect.height - fontHeight)/2
mem_dc.SetTextForeground(wx.WHITE)
mem_dc.DrawText("Opened tabs:", txtPt.x, txtPt.y)
@@ -2716,6 +2748,7 @@

self.InitNotebook(agwStyle)

+    NavigatorProps = property(lambda self: self._navProps)

def GetTabContainer(self):
""" Returns the instance of L{AuiTabContainer}. """
@@ -2736,8 +2769,8 @@
self._agwFlags = agwStyle

self._popupWin = None
-        self._naviIcon = None
self._imageList = None
+        self._navProps = TabNavigatorProps()
self._last_drag_x = 0

self._normal_font = wx.SystemSettings.GetFont(wx.SYS_DEFAULT_GUI_FONT)
@@ -5095,12 +5128,7 @@
"""

if isinstance(bmp, wx.Bitmap) and bmp.IsOk():
-            # Make sure image is proper size
-            if bmp.GetSize() != (16, 16):
-                img = bmp.ConvertToImage()
-                img.Rescale(16, 16, wx.IMAGE_QUALITY_HIGH)
-                bmp = wx.BitmapFromImage(img)
-            self._naviIcon = bmp
+            self.NavigatorProps.Icon = bmp
else:
raise TypeError, "SetNavigatorIcon requires a valid bitmap"

@@ -5115,7 +5143,7 @@
if event.IsWindowChange():
if self._agwFlags & AUI_NB_SMART_TABS:
if not self._popupWin:
-                    self._popupWin = TabNavigatorWindow(self, self._naviIcon)
+                    self._popupWin = TabNavigatorWindow(self, self.NavigatorProps)
self._popupWin.SetReturnCode(wx.ID_OK)
self._popupWin.ShowModal()
idx = self._popupWin.GetSelectedPage()

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • aui library »
  • aui.auibook »
  • SVN Revision 69232 For auibook


SVN Revision 69295 For auibook

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • aui library »
  • aui.auibook »
  • SVN Revision 69295 For auibook

svn SVN Revision 69295 For auibook

This file contains the SVN revision history for auibook, at revision 69295.

Available information include commit date, the name of the committer, the file size, the SVN log messages and a diff from the previous version (if available).

File Information

  • Commit Date: 06-Apr-2009 15:34:45 UTC
  • Committer: AG
  • File Size: 194741 byte(s)

Log Messages

The following log message was entered by the committer:

AuiNotebook: applied workaround from Cody Precord to fix a wrong tab index when the book has been split.

Diff To Previous Version (69232)

Version SVN diff:

--- wxPython/3rdParty/AGW/agw/aui/auibook.py        2011/09/29 19:16:48     69232
+++ wxPython/3rdParty/AGW/agw/aui/auibook.py        2011/10/02 20:22:37     69295
@@ -382,7 +382,7 @@
self.dispatched = 0
self.label = ""
self.editCancelled = False
-
+        self.page = None

def SetSelection(self, s):
"""
@@ -484,6 +484,8 @@
self.label = label

+    Page      = property(lambda self: self.page,
+                         lambda self, page: setattr(self, 'page', page))
Selection = property(lambda self: self.GetSelection(), lambda self, sel: self.SetSelection(sel))

# ----------------------------------------------------------------------
@@ -2077,7 +2079,8 @@
if wnd:
e = AuiNotebookEvent(wxEVT_COMMAND_AUINOTEBOOK_TAB_RIGHT_UP, self.GetId())
e.SetEventObject(self)
-            e.SetSelection(self.GetIdxFromWindow(wnd))
+            e.Selection = self.GetIdxFromWindow(wnd)
+            e.Page = wnd
self.GetEventHandler().ProcessEvent(e)
elif not self.ButtonHitTest(x, y):
e = AuiNotebookEvent(wxEVT_COMMAND_AUINOTEBOOK_BG_RIGHT_UP, self.GetId())
@@ -2099,6 +2102,7 @@
e = AuiNotebookEvent(wxEVT_COMMAND_AUINOTEBOOK_TAB_RIGHT_DOWN, self.GetId())
e.SetEventObject(self)
e.SetSelection(self.GetIdxFromWindow(wnd))
+            e.Page = wnd
self.GetEventHandler().ProcessEvent(e)
elif not self.ButtonHitTest(x, y):
e = AuiNotebookEvent(wxEVT_COMMAND_AUINOTEBOOK_BG_RIGHT_DOWN, self.GetId())
@@ -2120,6 +2124,7 @@
e = AuiNotebookEvent(wxEVT_COMMAND_AUINOTEBOOK_TAB_DCLICK, self.GetId())
e.SetEventObject(self)
e.SetSelection(self.GetIdxFromWindow(wnd))
+            e.Page = wnd
self.GetEventHandler().ProcessEvent(e)
elif not self.ButtonHitTest(x, y):
e = AuiNotebookEvent(wxEVT_COMMAND_AUINOTEBOOK_BG_DCLICK, self.GetId())

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • aui library »
  • aui.auibook »
  • SVN Revision 69295 For auibook


SVN Revision 69382 For auibook

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • aui library »
  • aui.auibook »
  • SVN Revision 69382 For auibook

svn SVN Revision 69382 For auibook

This file contains the SVN revision history for auibook, at revision 69382.

Available information include commit date, the name of the committer, the file size, the SVN log messages and a diff from the previous version (if available).

File Information

  • Commit Date: 05-Apr-2009 10:55:25 UTC
  • Committer: AG
  • File Size: 194788 byte(s)

Log Messages

The following log message was entered by the committer:

AuiNotebook: possibly fix (?) un-reproduceable bug on tab size/text clipped.

Diff To Previous Version (69299)

Version SVN diff:

--- wxPython/3rdParty/AGW/agw/aui/auibook.py        2011/10/03 19:57:45     69299
+++ wxPython/3rdParty/AGW/agw/aui/auibook.py        2011/10/11 19:17:58     69382
@@ -3260,7 +3260,8 @@

if bitmap.IsOk() and not disabled_bitmap.IsOk():
disabled_bitmap = MakeDisabledBitmap(bitmap)
-            info.dis_bitmap = disabled_bitmap
+
+        info.dis_bitmap = disabled_bitmap

# if there are currently no tabs, the first added
# tab must be active

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • aui library »
  • aui.auibook »
  • SVN Revision 69382 For auibook


SVN Revision 69432 For auibook

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • aui library »
  • aui.auibook »
  • SVN Revision 69432 For auibook

svn SVN Revision 69432 For auibook

This file contains the SVN revision history for auibook, at revision 69432.

Available information include commit date, the name of the committer, the file size, the SVN log messages and a diff from the previous version (if available).

File Information

  • Commit Date: 04-Apr-2009 15:04:18 UTC
  • Committer: AG
  • File Size: 194823 byte(s)

Log Messages

The following log message was entered by the committer:

AuiNotebook: allow to set the window name to the underlying wx.PyPanel.

Diff To Previous Version (69382)

Version SVN diff:

--- wxPython/3rdParty/AGW/agw/aui/auibook.py        2011/10/11 19:17:58     69382
+++ wxPython/3rdParty/AGW/agw/aui/auibook.py        2011/10/14 18:29:37     69432
@@ -2691,7 +2691,7 @@
"""

def __init__(self, parent, id=wx.ID_ANY, pos=wx.DefaultPosition, size=wx.DefaultSize,
-                 style=0, agwStyle=AUI_NB_DEFAULT_STYLE):
+                 style=0, agwStyle=AUI_NB_DEFAULT_STYLE, name="AuiNotebook"):
"""
Default class constructor.

@@ -2735,6 +2735,7 @@
Default value for `agwStyle` is:
``AUI_NB_DEFAULT_STYLE`` = ``AUI_NB_TOP`` | ``AUI_NB_TAB_SPLIT`` | ``AUI_NB_TAB_MOVE`` | ``AUI_NB_SCROLL_BUTTONS`` | ``AUI_NB_CLOSE_ON_ACTIVE_TAB`` | ``AUI_NB_MIDDLE_CLICK_CLOSE`` | ``AUI_NB_DRAW_DND_TAB``

+        :param `name`: the window name.
"""

self._curpage = -1
@@ -2749,7 +2750,7 @@
self._tabBounds = (-1, -1)
self._click_tab = None

-        wx.PyPanel.__init__(self, parent, id, pos, size, style|wx.BORDER_NONE|wx.TAB_TRAVERSAL)
+        wx.PyPanel.__init__(self, parent, id, pos, size, style|wx.BORDER_NONE|wx.TAB_TRAVERSAL, name=name)
self._mgr = framemanager.AuiManager()
self._tabs = AuiTabContainer(self)

@@ -2772,7 +2773,6 @@
:see: L{__init__}
"""

-        self.SetName("AuiNotebook")
self._agwFlags = agwStyle

self._popupWin = None

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • aui library »
  • aui.auibook »
  • SVN Revision 69432 For auibook


SVN Revision 69627 For auibook

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • aui library »
  • aui.auibook »
  • SVN Revision 69627 For auibook

svn SVN Revision 69627 For auibook

This file contains the SVN revision history for auibook, at revision 69627.

Available information include commit date, the name of the committer, the file size, the SVN log messages and a diff from the previous version (if available).

File Information

  • Commit Date: 03-Apr-2009 10:31:34 UTC
  • Committer: AG
  • File Size: 194853 byte(s)

Log Messages

The following log message was entered by the committer:

  • AuiManager: fix the assertion error in the demo;
  • Others: minor fixes to the docstrings.

Diff To Previous Version (69432)

Version SVN diff:

--- wxPython/3rdParty/AGW/agw/aui/auibook.py        2011/10/14 18:29:37     69432
+++ wxPython/3rdParty/AGW/agw/aui/auibook.py        2011/11/01 19:42:21     69627
@@ -2585,7 +2585,9 @@

:param `show`: ``True`` to show the window, ``False`` otherwise.

-        :note: Overridden from `wx.PyControl`, this method always returns ``False`` as
+        :note:
+
+         Overridden from `wx.PyControl`, this method always returns ``False`` as
L{TabFrame} should never be phisically shown on screen.
"""

@@ -3309,7 +3311,9 @@

:param `page_idx`: the page index to be deleted.

-        :note: L{DeletePage} removes a tab from the multi-notebook, and destroys the window as well.
+        :note:
+
+         L{DeletePage} removes a tab from the multi-notebook, and destroys the window as well.

:see: L{RemovePage}
"""
@@ -3338,7 +3342,9 @@

:param `page_idx`: the page index to be removed.

-        :note: L{RemovePage} removes a tab from the multi-notebook, but does not destroy the window.
+        :note:
+
+         L{RemovePage} removes a tab from the multi-notebook, but does not destroy the window.

:see: L{DeletePage}
"""

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • aui library »
  • aui.auibook »
  • SVN Revision 69627 For auibook


SVN Revision 70742 For auibook

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • aui library »
  • aui.auibook »
  • SVN Revision 70742 For auibook

svn SVN Revision 70742 For auibook

This file contains the SVN revision history for auibook, at revision 70742.

Available information include commit date, the name of the committer, the file size, the SVN log messages and a diff from the previous version (if available).

File Information

  • Commit Date: 02-Apr-2009 14:32:39 UTC
  • Committer: AG
  • File Size: 196041 byte(s)

Log Messages

The following log message was entered by the committer:

AuiNotebook: apply patches from Luke McCarthy to fix the following:

  • Button widths not calculated correctly if some buttons are hidden;
  • Notebook control buttons (e.g. close button) can’t be clicked quickly;
  • Tab can’t be selected after dragging (_curpage not updated).

Diff To Previous Version (69627)

Version SVN diff:

--- wxPython/3rdParty/AGW/agw/aui/auibook.py        2011/11/01 19:42:21     69627
+++ wxPython/3rdParty/AGW/agw/aui/auibook.py        2012/02/28 22:11:31     70742
@@ -556,7 +556,7 @@

def __init__(self):
""" Default class constructor. """
-
+
super(TabNavigatorProps, self).__init__()

# Attributes
@@ -609,9 +609,9 @@

sz = wx.BoxSizer(wx.VERTICAL)

-        self._listBox = wx.ListBox(self, wx.ID_ANY,
-                                   wx.DefaultPosition,
-                                   wx.Size(200, 150), [],
+        self._listBox = wx.ListBox(self, wx.ID_ANY,
+                                   wx.DefaultPosition,
+                                   wx.Size(200, 150), [],
wx.LB_SINGLE | wx.NO_BORDER)

mem_dc = wx.MemoryDC()
@@ -627,7 +627,7 @@
if panelHeight < 24:
panelHeight = 24

-        self._panel = wx.Panel(self, wx.ID_ANY, wx.DefaultPosition,
+        self._panel = wx.Panel(self, wx.ID_ANY, wx.DefaultPosition,
wx.Size(-1, panelHeight))

sz.Add(self._panel, 0, wx.EXPAND)
@@ -1391,7 +1391,15 @@
else:
visible_width += size[0]

-        if total_width > self._rect.GetWidth() or self._tab_offset != 0:
+        buttons_width = 0
+
+        for button in self._buttons:
+            if not (button.cur_state & AUI_BUTTON_STATE_HIDDEN):
+                buttons_width += button.rect.GetWidth()
+
+        total_width += buttons_width
+
+        if (total_width > self._rect.GetWidth() and page_count > 1) or self._tab_offset != 0:

# show left/right buttons
for button in self._buttons:
@@ -1418,7 +1426,7 @@
button.cur_state &= ~AUI_BUTTON_STATE_DISABLED

if button.id == AUI_BUTTON_RIGHT:
-                if visible_width < self._rect.GetWidth() - 16*button_count:
+                if visible_width < self._rect.GetWidth() - buttons_width:
button.cur_state |= AUI_BUTTON_STATE_DISABLED
else:
button.cur_state &= ~AUI_BUTTON_STATE_DISABLED
@@ -1495,6 +1503,20 @@

self.MinimizeTabOffset(dc, wnd, self._rect.GetWidth() - right_buttons_width - offset - 2)

+        # draw tab before tab offset
+        if self._tab_offset > 0:
+            page = self._pages[self._tab_offset - 1]
+            tab_button = self._tab_close_buttons[self._tab_offset - 1]
+            size, x_extent = self._art.GetTabSize(dc, wnd, page.caption, page.bitmap, page.active, tab_button.cur_state, page.control)
+
+            rect = wx.Rect(offset - x_extent, 0, self._rect.width - right_buttons_width - offset - x_extent - 2, self._rect.height)
+            clip_rect = wx.Rect(*self._rect)
+            clip_rect.x = offset
+
+            dc.SetClippingRect(clip_rect)
+            self._art.DrawTab(dc, wnd, page, rect, tab_button.cur_state)
+            dc.DestroyClippingRegion()
+
# draw the tabs
active = 999
active_offset = 0
@@ -1883,7 +1905,9 @@
:param `event`: a `wx.MouseEvent` event to be processed.
"""

-        self.CaptureMouse()
+        if not self.HasCapture():
+            self.CaptureMouse()
+
self._click_pt = wx.Point(-1, -1)
self._is_dragging = False
self._click_tab = None
@@ -1908,15 +1932,19 @@
self._click_pt.x = event.GetX()
self._click_pt.y = event.GetY()
self._click_tab = wnd
+
+            wnd.SetFocus()
else:
page_index = self.GetActivePage()
if page_index != wx.NOT_FOUND:
self.GetWindowFromIdx(page_index).SetFocus()

+            self._hover_button = self.ButtonHitTest(event.GetX(), event.GetY())
if self._hover_button:
self._pressed_button = self._hover_button
self._pressed_button.cur_state = AUI_BUTTON_STATE_PRESSED
self._on_button = True
+
self.Refresh()
self.Update()

@@ -1980,6 +2008,7 @@

if self._hover_button:
self._pressed_button = self._hover_button
+            self._hover_button.cur_state = AUI_BUTTON_STATE_NORMAL

if self._pressed_button:

@@ -4485,6 +4514,8 @@
:param `event`: a L{AuiNotebookEvent} event to be processed.
"""

+        self._curpage = event.GetSelection()
+
tabs = event.GetEventObject()
if not tabs.GetEnabled(event.GetSelection()):
return

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • aui library »
  • aui.auibook »
  • SVN Revision 70742 For auibook


SVN Revision 70836 For auibook

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • aui library »
  • aui.auibook »
  • SVN Revision 70836 For auibook

svn SVN Revision 70836 For auibook

This file contains the SVN revision history for auibook, at revision 70836.

Available information include commit date, the name of the committer, the file size, the SVN log messages and a diff from the previous version (if available).

File Information

  • Commit Date: 31-Mar-2009 16:34:20 UTC
  • Committer: AG
  • File Size: 197106 byte(s)

Log Messages

The following log message was entered by the committer:

  • AuiManager: fix a resource leak by calling Destroy on the AuiManager’s wx.EvtHandler;
  • AuiNotebook: override Destroy to call UnInit on the AuiNotebook‘s manager during window destruction.

Diff To Previous Version (70742)

Version SVN diff:

--- wxPython/3rdParty/AGW/agw/aui/auibook.py        2012/02/28 22:11:31     70742
+++ wxPython/3rdParty/AGW/agw/aui/auibook.py        2012/03/07 19:49:50     70836
@@ -550,7 +550,7 @@

class TabNavigatorProps(object):
"""
-    Data storage class for managing and providing access to L{TabNavigatorWindow}
+    Data storage class for managing and providing access to L{TabNavigatorWindow}.
properties.
"""

@@ -566,11 +566,14 @@

# Accessors
Icon = property(lambda self: self._icon,
-                    lambda self, icon: setattr(self, '_icon', icon))
+                    lambda self, icon: setattr(self, '_icon', icon),
+                    doc='Sets/Gets the icon for the L{TabNavigatorWindow}, an instance of `wx.Bitmap`.')
Font = property(lambda self: self._font,
-                    lambda self, font: setattr(self, '_font', font))
+                    lambda self, font: setattr(self, '_font', font),
+                    doc='Sets/Gets the font for the L{TabNavigatorWindow}, an instance of `wx.Font`.')
MinSize = property(lambda self: self._minsize,
-                       lambda self, size: setattr(self, '_minsize', size))
+                       lambda self, size: setattr(self, '_minsize', size),
+                       doc='Sets/Gets the minimum size for the L{TabNavigatorWindow}, an instance of `wx.Size`.')

# ---------------------------------------------------------------------------- #
# Class TabNavigatorWindow
@@ -2789,6 +2792,25 @@

NavigatorProps = property(lambda self: self._navProps)

+
+    def Destroy(self):
+        """
+        Destroys the window safely.
+
+        Use this function instead of the `del` operator, since different window
+        classes can be destroyed differently. Frames and dialogs are not destroyed
+        immediately when this function is called -- they are added to a list of
+        windows to be deleted on idle time, when all the window's events have been
+        processed. This prevents problems with events being sent to non-existent windows.
+
+        :return: ``True`` if the window has either been successfully deleted, or
+         it has been added to the list of windows pending real deletion.
+        """
+
+        self._mgr.UnInit()
+        return wx.PyPanel.Destroy(self)
+
+
def GetTabContainer(self):
""" Returns the instance of L{AuiTabContainer}. """

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • aui library »
  • aui.auibook »
  • SVN Revision 70836 For auibook


SVN Revision 70883 For auibook

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • aui library »
  • aui.auibook »
  • SVN Revision 70883 For auibook

svn SVN Revision 70883 For auibook

This file contains the SVN revision history for auibook, at revision 70883.

Available information include commit date, the name of the committer, the file size, the SVN log messages and a diff from the previous version (if available).

File Information

  • Commit Date: 31-Mar-2009 15:36:51 UTC
  • Committer: AG
  • File Size: 197131 byte(s)

Log Messages

The following log message was entered by the committer:

AuiNotebook: correct wrong indentation in OnLeftDown which cause bad flicker on the AuiNotebook buttons.

Diff To Previous Version (70836)

Version SVN diff:

--- wxPython/3rdParty/AGW/agw/aui/auibook.py        2012/03/07 19:49:50     70836
+++ wxPython/3rdParty/AGW/agw/aui/auibook.py        2012/03/12 17:13:59     70883
@@ -1943,13 +1943,14 @@
self.GetWindowFromIdx(page_index).SetFocus()

self._hover_button = self.ButtonHitTest(event.GetX(), event.GetY())
-        if self._hover_button:
-            self._pressed_button = self._hover_button
-            self._pressed_button.cur_state = AUI_BUTTON_STATE_PRESSED
-            self._on_button = True

-            self.Refresh()
-            self.Update()
+            if self._hover_button:
+                self._pressed_button = self._hover_button
+                self._pressed_button.cur_state = AUI_BUTTON_STATE_PRESSED
+                self._on_button = True
+
+                self.Refresh()
+                self.Update()

def OnCaptureLost(self, event):

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • aui library »
  • aui.auibook »
  • SVN Revision 70883 For auibook


BalloonFrame

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • balloontip »
  • BalloonFrame

BalloonFrame

This class is called by the main BalloonTip class, and it is responsible for the frame creation/positioning on screen depending on target control/window, the frame can position itself to NW (default), NE, SW, SE. The switch on positioning is done by calculating the absolute position of the target control/window plus/minus the balloontip size. The pointing arrow is positioned accordingly.

hierarchy Inheritance Diagram

Inheritance diagram for: BalloonFrame

Inheritance diagram of BalloonFrame

Methods Summary

__init__ | Default class constructor.
OnClose | Handles the wx.EVT_CLOSE event for BalloonTip.
OnEnterButton | Handles the wx.EVT_ENTER_WINDOW for the BalloonTip button.
OnLeaveButton | Handles the wx.EVT_LEAVE_WINDOW for the BalloonTip button.
SetBalloonShape | Sets the balloon shape.

API Class API

class BalloonFrame(wx.Frame) [source]

This class is called by the main BalloonTip class, and it is responsible for the frame creation/positioning on screen depending on target control/window, the frame can position itself to NW (default), NE, SW, SE. The switch on positioning is done by calculating the absolute position of the target control/window plus/minus the balloontip size. The pointing arrow is positioned accordingly.

__init__(parent, id=wx.ID_ANY, pos=wx.DefaultPosition, size=wx.DefaultSize, classparent=None) [source]

Default class constructor.

Used internally. Do not call directly this class in your application!

OnClose(event) [source]

Handles the wx.EVT_CLOSE event for BalloonTip.

Parameters: event – a wx.CloseEvent event to be processed.

OnEnterButton(event) [source]

Handles the wx.EVT_ENTER_WINDOW for the BalloonTip button.

When the BalloonTip is created with the tipstyle = BT_BUTTON, this event provide some kind of 3D effect when the mouse enters the button area.

Parameters: event – a wx.MouseEvent event to be processed.

OnLeaveButton(event) [source]

Handles the wx.EVT_LEAVE_WINDOW for the BalloonTip button.

When the BalloonTip is created with the tipstyle = BT_BUTTON, this event provide some kind of 3D effect when the mouse enters the button area.

Parameters: event – a wx.MouseEvent event to be processed.

SetBalloonShape(event=None) [source]

Sets the balloon shape.

Parameters: event – on wxGTK, a wx.WindowCreateEvent event to process.

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • infobar
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • balloontip »
  • BalloonFrame


BalloonTip

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • balloontip »
  • BalloonTip

BalloonTip

BalloonTip is a class that allows you to display tooltips in a balloon style window.

This is the main class implementation.

hierarchy Inheritance Diagram

Inheritance diagram for: BalloonTip

Inheritance diagram of BalloonTip

appearance Control Appearance

BalloonTip

Methods Summary

__init__ | Default class constructor.
DestroyTimer | The destruction timer has expired.
EnableTip | Enable/disable globally the BalloonTip.
GetBalloonColour | Returns the BalloonTip background colour.
GetBalloonIcon | Returns the BalloonTip top-left icon.
GetBalloonMessage | Returns the BalloonTip tip message.
GetBalloonShape | Returns the BalloonTip frame shape.
GetBalloonTipStyle | Returns the BalloonTip tipstyle parameter.
GetBalloonTitle | Returns the BalloonTip top title.
GetEndDelay | Returns the delay time after which the BalloonTip is destroyed.
GetMessageColour | Returns the colour for the tip message.
GetMessageFont | Returns the font for the tip message.
GetStartDelay | Returns the delay time after which the BalloonTip is created.
GetTarget | Returns the target window for the BalloonTip.
GetTitleColour | Returns the colour for the top title.
GetTitleFont | Returns the font for the top title.
NotifyTimer | The creation timer has expired.
OnDestroy | Handles the target destruction, specifically handling the wx.EVT_WINDOW_DESTROY
OnTaskBarMove | Handles the mouse motion inside the taskbar icon area.
OnWidgetEnter | Handles the wx.EVT_ENTER_WINDOW for the target control/window and
OnWidgetLeave | Handles the wx.EVT_LEAVE_WINDOW for the target control/window.
OnWidgetMotion | Handle the mouse motion inside the target.
SetBalloonColour | Sets the BalloonTip background colour.
SetBalloonIcon | Sets the BalloonTip top-left icon.
SetBalloonMessage | Sets the BalloonTip tip message.
SetBalloonShape | Sets the BalloonTip frame shape.
SetBalloonTipStyle | Sets the BalloonTip tipstyle parameter.
SetBalloonTitle | Sets the BalloonTip top title.
SetEndDelay | Sets the delay time after which the BalloonTip is destroyed.
SetMessageColour | Sets the colour for the tip message.
SetMessageFont | Sets the font for the tip message.
SetStartDelay | Sets the delay time after which the BalloonTip is created.
SetTarget | Sets the target control/window for the BalloonTip.
SetTitleColour | Sets the colour for the top title.
SetTitleFont | Sets the font for the top title.
TaskBarTimer | This timer check periodically the mouse position.

API Class API

class BalloonTip(object) [source]

BalloonTip is a class that allows you to display tooltips in a balloon style window.

This is the main class implementation.

__init__(topicon=None, toptitle="", message="", shape=BT_ROUNDED, tipstyle=BT_LEAVE) [source]

Default class constructor.

Parameters:
  • topicon (wx.Bitmap or None) – an icon that will be displayed on the top-left part of the BalloonTip frame. If set to None, no icon will be displayed;
  • toptitle (string) – a title that will be displayed on the top part of the BalloonTip frame. If set to an empty string, no title will be displayed;
  • message (string) – the tip message that will be displayed. It can not be set to an empty string;
  • shape (integer) – the BalloonTip shape. It can be one of the following:

    integer parameter settings
    Shape Flag | Hex Value | Description
    BT_ROUNDED | 0x1 | BalloonTip will have a rounded rectangular shape.
    BT_RECTANGLE | 0x2 | BalloonTip will have a rectangular shape.
  • tipstyle (integer) – the BalloonTip destruction behavior. It can be one of:

    integer parameter settings
    Tip Flag | Hex Value | Description
    BT_LEAVE | 0x3 | BalloonTip will be destroyed when the user moves the mouse outside the target window.
    BT_CLICK | 0x4 | BalloonTip will be destroyed when the user click on BalloonTip.
    BT_BUTTON | 0x5 | BalloonTip will be destroyed when the user click on the close button.
Raise :

Exception in the following cases:

  • The message parameter is an empty string;
  • The shape parameter has an invalid value (i.e., it’s not one of BT_ROUNDED, BT_RECTANGLE);
  • The tipstyle parameter has an invalid value (i.e., it’s not one of BT_LEAVE, BT_CLICK, BT_BUTTON).

DestroyTimer() [source]

The destruction timer has expired. Destroys the BalloonTip frame.

EnableTip(enable=True) [source]

Enable/disable globally the BalloonTip.

Parameters: enable (bool) – True to enable BalloonTip, False otherwise.

GetBalloonColour() [source]

Returns the BalloonTip background colour.

Returns: An instance of wx.Colour.

GetBalloonIcon() [source]

Returns the BalloonTip top-left icon.

Returns: An instance of wx.Bitmap.

GetBalloonMessage() [source]

Returns the BalloonTip tip message.

Returns: A string containing the main message.

GetBalloonShape() [source]

Returns the BalloonTip frame shape.

Returns: An integer, one of BT_ROUNDED, BT_RECTANGLE.

GetBalloonTipStyle() [source]

Returns the BalloonTip tipstyle parameter.

Returns: An integer representing the style.

See also

SetBalloonTipStyle

GetBalloonTitle() [source]

Returns the BalloonTip top title.

Returns: A string containing the top title.

GetEndDelay() [source]

Returns the delay time after which the BalloonTip is destroyed.

Returns: the delay time, in milliseconds.

GetMessageColour() [source]

Returns the colour for the tip message.

Returns: An instance of wx.Colour.

GetMessageFont() [source]

Returns the font for the tip message.

Returns: An instance of wx.Font.

GetStartDelay() [source]

Returns the delay time after which the BalloonTip is created.

Returns: the delay time, in milliseconds.

GetTarget() [source]

Returns the target window for the BalloonTip.

Returns: An instance of wx.Window.
Raise : Exception if the SetTarget method has not previously called.

GetTitleColour() [source]

Returns the colour for the top title.

Returns: An instance of wx.Colour.

GetTitleFont() [source]

Returns the font for the top title.

Returns: An instance of wx.Font.

NotifyTimer() [source]

The creation timer has expired. Creates the BalloonTip frame.

OnDestroy(event) [source]

Handles the target destruction, specifically handling the wx.EVT_WINDOW_DESTROY event.

Parameters: event – a wx.WindowDestroyEvent event to be processed.

OnTaskBarMove(event) [source]

Handles the mouse motion inside the taskbar icon area.

Parameters: event – a wx.MouseEvent event to be processed.

OnWidgetEnter(event) [source]

Handles the wx.EVT_ENTER_WINDOW for the target control/window and starts the BalloonTip timer for creation.

Parameters: event – a wx.MouseEvent event to be processed.

OnWidgetLeave(event) [source]

Handles the wx.EVT_LEAVE_WINDOW for the target control/window.

Parameters: event – a wx.MouseEvent event to be processed.

Note

If the BalloonTip tipstyle is set to BT_LEAVE, the BalloonTip is destroyed.

OnWidgetMotion(event) [source]

Handle the mouse motion inside the target.

This prevents the annoying behavior of BalloonTip to display when the user does something else inside the window. The BalloonTip window is displayed only when the mouse does not move for the start delay time.

Parameters: event – a wx.MouseEvent event to be processed.

SetBalloonColour(colour=None) [source]

Sets the BalloonTip background colour.

Parameters: colour – a valid wx.Colour instance.

SetBalloonIcon(icon) [source]

Sets the BalloonTip top-left icon.

Parameters: icon – an instance of wx.Bitmap.
Raise : Exception if the icon bitmap is not a valid wx.Bitmap.

SetBalloonMessage(message) [source]

Sets the BalloonTip tip message.

Parameters: message (string) – a string identifying the main message body of BalloonTip.
Raise : Exception if the message is an empty string.

Note

The BalloonTip message should never be empty.

SetBalloonShape(shape=BT_ROUNDED) [source]

Sets the BalloonTip frame shape.

Parameters: shape (integer) – should be one of BT_ROUNDED or BT_RECTANGLE.
Raise : Exception if the shape parameter is not a valid value (i.e., it’s not one of BT_ROUNDED, BT_RECTANGLE);

SetBalloonTipStyle(tipstyle=BT_LEAVE) [source]

Sets the BalloonTip tipstyle parameter.

Parameters: tipstyle (integer) – one of the following bit set:

integer parameter settings
Tip Style | Hex Value | Description
BT_LEAVE | 0x3 | BalloonTip will be destroyed when the user moves the mouse outside the target window.
BT_CLICK | 0x4 | BalloonTip will be destroyed when the user click on BalloonTip.
BT_BUTTON | 0x5 | BalloonTip will be destroyed when the user click on the close button.
Raise : Exception if the tipstyle parameter has an invalid value (i.e., it’s not one of BT_LEAVE, BT_CLICK, BT_BUTTON).

SetBalloonTitle(title='') [source]

Sets the BalloonTip top title.

Parameters: title (string) – a string to use as a BalloonTip title.

SetEndDelay(delay=1000000.0) [source]

Sets the delay time after which the BalloonTip is destroyed.

Parameters: delay (integer) – the number of milliseconds after which BalloonTip is destroyed.
Raise : Exception if delay is less than 1 milliseconds.

SetMessageColour(colour=None) [source]

Sets the colour for the tip message.

Parameters: colour – a valid wx.Colour instance.

SetMessageFont(font=None) [source]

Sets the font for the tip message.

Parameters: font – a valid wx.Font instance.

SetStartDelay(delay=1) [source]

Sets the delay time after which the BalloonTip is created.

Parameters: delay (integer) – the number of milliseconds after which BalloonTip is created.
Raise : Exception if delay is less than 1 milliseconds.

SetTarget(widget) [source]

Sets the target control/window for the BalloonTip.

Parameters: widget – any subclass of wx.Window.

SetTitleColour(colour=None) [source]

Sets the colour for the top title.

Parameters: colour – a valid wx.Colour instance.

SetTitleFont(font=None) [source]

Sets the font for the top title.

Parameters: font – a valid wx.Font instance.

TaskBarTimer() [source]

This timer check periodically the mouse position.

If the current mouse position is sufficiently far from the coordinates it had when entered the taskbar icon and the BalloonTip style is BT_LEAVE, the BalloonTip frame is destroyed.

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • infobar
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • balloontip »
  • BalloonTip


SVN Revision 68362 For balloontip

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • balloontip »
  • SVN Revision 68362 For balloontip

svn SVN Revision 68362 For balloontip

This file contains the SVN revision history for balloontip, at revision 68362.

Available information include commit date, the name of the committer, the file size, the SVN log messages and a diff from the previous version (if available).

File Information

  • Commit Date: 02-Jan-2009 03:09:18 UTC
  • Committer: AG
  • File Size: 32266 byte(s)

Log Messages

The following log message was entered by the committer:

  • All of AGW: change my work e-mail from KPO to Maersk Oil (silly commit)

Diff To Previous Version (65377)

Version SVN diff:

--- wxPython/3rdParty/AGW/agw/balloontip.py 2010/08/21 20:27:02     65377
+++ wxPython/3rdParty/AGW/agw/balloontip.py 2011/07/24 21:36:47     68362
@@ -31,7 +31,7 @@
# Write To Me At:
#
# andrea.gavana@gmail.com
-# gavana@kpo.kz
+# andrea.gavana@maerskoil.com
#
# Or, Obviously, To The wxPython Mailing List!!!
#

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • balloontip »
  • SVN Revision 68362 For balloontip


SVN Revision 68742 For balloontip

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • balloontip »
  • SVN Revision 68742 For balloontip

svn SVN Revision 68742 For balloontip

This file contains the SVN revision history for balloontip, at revision 68742.

Available information include commit date, the name of the committer, the file size, the SVN log messages and a diff from the previous version (if available).

File Information

  • Commit Date: 20-Oct-2008 20:05:15 UTC
  • Committer: AG
  • File Size: 32881 byte(s)

Log Messages

The following log message was entered by the committer:

  • FlatNotebook: fix issues with custom page and vertical/horizontal tiling of pages;
  • AuiBook: every time the AuiBook is split, copy over the custom buttons in the tab area of the newly created AuiBook;
  • Others: minor modifications to the docstrings.

Diff To Previous Version (68362)

Version SVN diff:

--- wxPython/3rdParty/AGW/agw/balloontip.py 2011/07/24 21:36:47     68362
+++ wxPython/3rdParty/AGW/agw/balloontip.py 2011/08/16 16:37:37     68742
@@ -3,7 +3,7 @@
# Python Code By:
#
# Andrea Gavana, @ 29 May 2005
-# Latest Revision: 23 Nov 2009, 09.00 GMT
+# Latest Revision: 11 Aug 2011, 23.00 GMT
#
#
# TODO List/Caveats
@@ -82,33 +82,52 @@

Usage example::

-    # let's suppose that in your application you have a wx.TextCtrl defined as:
+    import wx
+    import wx.lib.agw.balloontip as BT

-    mytextctrl = wx.TextCtrl(panel, -1, "i am a textctrl")
+    class MyFrame(wx.Frame):

-    # you can define your BalloonTip as follows:
+        def __init__(self, parent):

-    tipballoon = BalloonTip(topicon=None, toptitle="textctrl",
-                            message="this is a textctrl",
-                            shape=BT_ROUNDED,
-                            tipstyle=BT_LEAVE)
-
-    # set the BalloonTip target
-    tipballoon.SetTarget(mytextctrl)
-    # set the BalloonTip background colour
-    tipballoon.SetBalloonColour(wx.white)
-    # set the font for the balloon title
-    tipballoon.SetTitleFont(wx.Font(9, wx.SWISS, wx.NORMAL, wx.BOLD, False))
-    # set the colour for the balloon title
-    tipballoon.SetTitleColour(wx.BLACK)
-    # leave the message font as default
-    tipballoon.SetMessageFont()
-    # set the message (tip) foreground colour
-    tipballoon.SetMessageColour(wx.LIGHT_GREY)
-    # set the start delay for the BalloonTip
-    tipballoon.SetStartDelay(1000)
-    # set the time after which the BalloonTip is destroyed
-    tipballoon.SetEndDelay(3000)
+            wx.Frame.__init(self, parent, -1, "BalloonTip Demo")
+
+            panel = wx.Panel(self)
+
+            # Let's suppose that in your application you have a wx.TextCtrl defined as:
+            mytextctrl = wx.TextCtrl(panel, -1, "I am a textctrl", pos=(100, 100))
+
+            # You can define your BalloonTip as follows:
+            tipballoon = BalloonTip(topicon=None, toptitle="textctrl",
+                                    message="this is a textctrl",
+                                    shape=BT.BT_ROUNDED,
+                                    tipstyle=BT.BT_LEAVE)
+
+            # Set the BalloonTip target
+            tipballoon.SetTarget(mytextctrl)
+            # Set the BalloonTip background colour
+            tipballoon.SetBalloonColour(wx.WHITE)
+            # Set the font for the balloon title
+            tipballoon.SetTitleFont(wx.Font(9, wx.SWISS, wx.NORMAL, wx.BOLD, False))
+            # Set the colour for the balloon title
+            tipballoon.SetTitleColour(wx.BLACK)
+            # Leave the message font as default
+            tipballoon.SetMessageFont()
+            # Set the message (tip) foreground colour
+            tipballoon.SetMessageColour(wx.LIGHT_GREY)
+            # Set the start delay for the BalloonTip
+            tipballoon.SetStartDelay(1000)
+            # Set the time after which the BalloonTip is destroyed
+            tipballoon.SetEndDelay(3000)
+
+    # our normal wxApp-derived class, as usual
+
+    app = wx.PySimpleApp()
+
+    frame = MyFrame(None)
+    app.SetTopWindow(frame)
+    frame.Show()
+
+    app.MainLoop()

Window Styles
@@ -138,7 +157,7 @@

BalloonTip is distributed under the wxPython license.

-Latest revision: Andrea Gavana @ 23 Nov 2009, 09.00 GMT
+Latest revision: Andrea Gavana @ 11 Aug 2011, 23.00 GMT

Version 0.2

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • balloontip »
  • SVN Revision 68742 For balloontip


SVN Revision 68881 For balloontip

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • balloontip »
  • SVN Revision 68881 For balloontip

svn SVN Revision 68881 For balloontip

This file contains the SVN revision history for balloontip, at revision 68881.

Available information include commit date, the name of the committer, the file size, the SVN log messages and a diff from the previous version (if available).

File Information

  • Commit Date: 17-Oct-2008 20:51:43 UTC
  • Committer: AG
  • File Size: 32960 byte(s)

Log Messages

The following log message was entered by the committer:

  • AGW: General overhaul of the documentation, much improved. All the widgets have their own sample usage in the docs as well;

  • FlatNotebook: Added the FNB_NAV_BUTTONS_WHEN_NEEDED style, which hides the navigation left/right arrows if all tabs fit;

  • RibbonBar: - Added the EVT_RIBBONBAR_TAB_LEFT_DCLICK event, which generates a special event

    when a ribbon bar tab is double-clicked;

    • Added support for toggle buttons;
    • Improved support for ribbon panel sizers: panels with sizers should now automatically minimise at small sizes, and behave properly when popping up from a minimised state;
    • Added tooltips via SetToolTip for those buttons which have the help_string attribute set.

  • XLSGrid: a new widget was added to AGW, termed XLSGrid. It’s based on wx.grid.Grid and can be used to faithfully reproduce the appearance of a Microsoft Excel spreadsheets.

Diff To Previous Version (68742)

Version SVN diff:

--- wxPython/3rdParty/AGW/agw/balloontip.py 2011/08/16 16:37:37     68742
+++ wxPython/3rdParty/AGW/agw/balloontip.py 2011/08/25 16:40:17     68881
@@ -3,7 +3,7 @@
# Python Code By:
#
# Andrea Gavana, @ 29 May 2005
-# Latest Revision: 11 Aug 2011, 23.00 GMT
+# Latest Revision: 17 Aug 2011, 15.00 GMT
#
#
# TODO List/Caveats
@@ -40,41 +40,41 @@
# --------------------------------------------------------------------------- #

"""
-BalloonTip is a class that allows you to display tooltips in a balloon style
+L{BalloonTip} is a class that allows you to display tooltips in a balloon style
window.

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

-BalloonTip is a class that allows you to display tooltips in a balloon style
+L{BalloonTip} is a class that allows you to display tooltips in a balloon style
window (actually a frame), similarly to the windows XP balloon help. There is
also an arrow that points to the center of the control designed as a "target"
-for the BalloonTip.
+for the L{BalloonTip}.

What it can do:

- Set the balloon shape as a rectangle or a rounded rectangle;
-- Set an icon to the top-left of the BalloonTip frame;
-- Set a title at the top of the BalloonTip frame;
-- Automatic "best" placement of BalloonTip frame depending on the target
+- Set an icon to the top-left of the L{BalloonTip} frame;
+- Set a title at the top of the L{BalloonTip} frame;
+- Automatic "best" placement of L{BalloonTip} frame depending on the target
control/window position;
- Runtime customization of title/tip fonts and foreground colours;
-- Runtime change of BalloonTip frame shape;
+- Runtime change of L{BalloonTip} frame shape;
- Set the balloon background colour;
-- Possibility to set the delay after which the BalloonTip is displayed;
-- Possibility to set the delay after which the BalloonTip is destroyed;
-- Three different behaviors for the BalloonTip window (regardless the delay
+- Possibility to set the delay after which the L{BalloonTip} is displayed;
+- Possibility to set the delay after which the L{BalloonTip} is destroyed;
+- Three different behaviors for the L{BalloonTip} window (regardless the delay
destruction time set):

-  a) Destroy by leave: the BalloonTip is destroyed when the mouse leaves the
+  a) Destroy by leave: the L{BalloonTip} is destroyed when the mouse leaves the
target control/window;
-  b) Destroy by click: the BalloonTip is destroyed when you click on any area
+  b) Destroy by click: the L{BalloonTip} is destroyed when you click on any area
of the target control/window;
-  c) Destroy by button: the BalloonTip is destroyed when you click on the
+  c) Destroy by button: the L{BalloonTip} is destroyed when you click on the
top-right close button;
-- Possibility to enable/disable globally the BalloonTip on you application;
-- Set the BalloonTip also for the taskbar icon.
+- Possibility to enable/disable globally the L{BalloonTip} on you application;
+- Set the L{BalloonTip} also for the taskbar icon.

Usage
@@ -97,10 +97,10 @@
mytextctrl = wx.TextCtrl(panel, -1, "I am a textctrl", pos=(100, 100))

# You can define your BalloonTip as follows:
-            tipballoon = BalloonTip(topicon=None, toptitle="textctrl",
-                                    message="this is a textctrl",
-                                    shape=BT.BT_ROUNDED,
-                                    tipstyle=BT.BT_LEAVE)
+            tipballoon = BT.BalloonTip(topicon=None, toptitle="textctrl",
+                                       message="this is a textctrl",
+                                       shape=BT.BT_ROUNDED,
+                                       tipstyle=BT.BT_LEAVE)

# Set the BalloonTip target
tipballoon.SetTarget(mytextctrl)
@@ -138,11 +138,11 @@
================ =========== ==================================================
Window Styles    Hex Value   Description
================ =========== ==================================================
-``BT_ROUNDED``           0x1 `BalloonTip` will have a rounded rectangular shape.
-``BT_RECTANGLE``         0x2 `BalloonTip` will have a rectangular shape.
-``BT_LEAVE``             0x3 `BalloonTip` will be destroyed when the user moves the mouse outside the target window.
-``BT_CLICK``             0x4 `BalloonTip` will be destroyed when the user click on `BalloonTip`.
-``BT_BUTTON``            0x5 `BalloonTip` will be destroyed when the user click on the close button.
+``BT_ROUNDED``           0x1 L{BalloonTip} will have a rounded rectangular shape.
+``BT_RECTANGLE``         0x2 L{BalloonTip} will have a rectangular shape.
+``BT_LEAVE``             0x3 L{BalloonTip} will be destroyed when the user moves the mouse outside the target window.
+``BT_CLICK``             0x4 L{BalloonTip} will be destroyed when the user click on L{BalloonTip}.
+``BT_BUTTON``            0x5 L{BalloonTip} will be destroyed when the user click on the close button.
================ =========== ==================================================

@@ -157,7 +157,7 @@

BalloonTip is distributed under the wxPython license.

-Latest revision: Andrea Gavana @ 11 Aug 2011, 23.00 GMT
+Latest revision: Andrea Gavana @ 17 Aug 2011, 15.00 GMT

Version 0.2

@@ -170,17 +170,17 @@

# Define The Values For The BalloonTip Frame Shape
BT_ROUNDED = 1
-""" `BalloonTip` will have a rounded rectangular shape. """
+""" L{BalloonTip} will have a rounded rectangular shape. """
BT_RECTANGLE = 2
-""" `BalloonTip` will have a rectangular shape. """
+""" L{BalloonTip} will have a rectangular shape. """

# Define The Value For The BalloonTip Destruction Behavior
BT_LEAVE = 3
-""" `BalloonTip` will be destroyed when the user moves the mouse outside the target window. """
+""" L{BalloonTip} will be destroyed when the user moves the mouse outside the target window. """
BT_CLICK = 4
-""" `BalloonTip` will be destroyed when the user click on `BalloonTip`. """
+""" L{BalloonTip} will be destroyed when the user click on L{BalloonTip}. """
BT_BUTTON = 5
-""" `BalloonTip` will be destroyed when the user click on the close button. """
+""" L{BalloonTip} will be destroyed when the user click on the close button. """

# ---------------------------------------------------------------
@@ -510,8 +510,8 @@
======================= ========= ====================================
Shape Flag              Hex Value  Description
======================= ========= ====================================
-         ``BT_ROUNDED``           0x1      `BalloonTip` will have a rounded rectangular shape.
-         ``BT_RECTANGLE``         0x2      `BalloonTip` will have a rectangular shape.
+         ``BT_ROUNDED``           0x1      L{BalloonTip} will have a rounded rectangular shape.
+         ``BT_RECTANGLE``         0x2      L{BalloonTip} will have a rectangular shape.
======================= ========= ====================================

:param `tipstyle`: the L{BalloonTip} destruction behavior. It can be one of:
@@ -519,9 +519,9 @@
======================= ========= ====================================
Tip Flag                Hex Value  Description
======================= ========= ====================================
-         ``BT_LEAVE``                  0x3 `BalloonTip` will be destroyed when the user moves the mouse outside the target window.
-         ``BT_CLICK``                  0x4 `BalloonTip` will be destroyed when the user click on `BalloonTip`.
-         ``BT_BUTTON``                 0x5 `BalloonTip` will be destroyed when the user click on the close button.
+         ``BT_LEAVE``                  0x3 L{BalloonTip} will be destroyed when the user moves the mouse outside the target window.
+         ``BT_CLICK``                  0x4 L{BalloonTip} will be destroyed when the user click on L{BalloonTip}.
+         ``BT_BUTTON``                 0x5 L{BalloonTip} will be destroyed when the user click on the close button.
======================= ========= ====================================

"""
@@ -860,9 +860,9 @@
============== ========== =====================================
Tip Style      Hex Value  Description
============== ========== =====================================
-         ``BT_LEAVE``          0x3 `BalloonTip` will be destroyed when the user moves the mouse outside the target window.
-         ``BT_CLICK``          0x4 `BalloonTip` will be destroyed when the user click on `BalloonTip`.
-         ``BT_BUTTON``         0x5 `BalloonTip` will be destroyed when the user click on the close button.
+         ``BT_LEAVE``          0x3 L{BalloonTip} will be destroyed when the user moves the mouse outside the target window.
+         ``BT_CLICK``          0x4 L{BalloonTip} will be destroyed when the user click on L{BalloonTip}.
+         ``BT_BUTTON``         0x5 L{BalloonTip} will be destroyed when the user click on the close button.
============== ========== =====================================
"""

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • balloontip »
  • SVN Revision 68881 For balloontip


SVN Revision 69086 For balloontip

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • balloontip »
  • SVN Revision 69086 For balloontip

svn SVN Revision 69086 For balloontip

This file contains the SVN revision history for balloontip, at revision 69086.

Available information include commit date, the name of the committer, the file size, the SVN log messages and a diff from the previous version (if available).

File Information

  • Commit Date: 17-Oct-2008 19:15:31 UTC
  • Committer: AG
  • File Size: 35053 byte(s)

Log Messages

The following log message was entered by the committer:

  • Fixed bug #13437 for SuperToolTip;
  • Fixed bug #13477 for UltimateListCtrl.

Diff To Previous Version (68881)

Version SVN diff:

--- wxPython/3rdParty/AGW/agw/balloontip.py 2011/08/25 16:40:17     68881
+++ wxPython/3rdParty/AGW/agw/balloontip.py 2011/09/14 19:39:08     69086
@@ -489,7 +489,7 @@

class BalloonTip(object):
"""
-    BalloonTip is a class that allows you to display tooltips in a balloon style
+    L{BalloonTip} is a class that allows you to display tooltips in a balloon style
window.

This is the main class implementation.
@@ -501,11 +501,12 @@

:param `topicon`: an icon that will be displayed on the top-left part of the
L{BalloonTip} frame. If set to ``None``, no icon will be displayed;
-        :param `toptitle`: a title that will be displayed on the top part of the
+        :type `topicon`: `wx.Bitmap` or ``None``
+        :param string `toptitle`: a title that will be displayed on the top part of the
L{BalloonTip} frame. If set to an empty string, no title will be displayed;
-        :param `message`: the tip message that will be displayed. It can not be set to
+        :param string `message`: the tip message that will be displayed. It can not be set to
an empty string;
-        :param `shape`: the L{BalloonTip} shape. It can be one of the following:
+        :param integer `shape`: the L{BalloonTip} shape. It can be one of the following:

======================= ========= ====================================
Shape Flag              Hex Value  Description
@@ -514,7 +515,7 @@
``BT_RECTANGLE``         0x2      L{BalloonTip} will have a rectangular shape.
======================= ========= ====================================

-        :param `tipstyle`: the L{BalloonTip} destruction behavior. It can be one of:
+        :param integer `tipstyle`: the L{BalloonTip} destruction behavior. It can be one of:

======================= ========= ====================================
Tip Flag                Hex Value  Description
@@ -524,6 +525,12 @@
``BT_BUTTON``                 0x5 L{BalloonTip} will be destroyed when the user click on the close button.
======================= ========= ====================================

+        :raise: `Exception` in the following cases:
+
+         - The `message` parameter is an empty string;
+         - The `shape` parameter has an invalid value (i.e., it's not one of ``BT_ROUNDED``, ``BT_RECTANGLE``);
+         - The `tipstyle` parameter has an invalid value (i.e., it's not one of ``BT_LEAVE``, ``BT_CLICK``, ``BT_BUTTON``).
+
"""

self._shape = shape
@@ -565,7 +572,7 @@
"""
Sets the target control/window for the L{BalloonTip}.

-        :param `widget`: an instance of `wx.Window`.
+        :param `widget`: any subclass of `wx.Window`.
"""

self._widget = widget
@@ -582,7 +589,13 @@

def GetTarget(self):
-        """ Returns the target window for the L{BalloonTip}."""
+        """
+        Returns the target window for the L{BalloonTip}.
+
+        :return: An instance of `wx.Window`.
+
+        :raise: `Exception` if the L{SetTarget} method has not previously called.
+        """

if not hasattr(self, "_widget"):
raise Exception("\nERROR: BalloonTip Target Has Not Been Set")
@@ -594,7 +607,9 @@
"""
Sets the delay time after which the L{BalloonTip} is created.

-        :param `delay`: the number of milliseconds after which L{BalloonTip} is created.
+        :param integer `delay`: the number of milliseconds after which L{BalloonTip} is created.
+
+        :raise: `Exception` if `delay` is less than ``1`` milliseconds.
"""

if delay < 1:
@@ -604,7 +619,11 @@

def GetStartDelay(self):
-        """ Returns the delay time after which the L{BalloonTip} is created."""
+        """
+        Returns the delay time after which the L{BalloonTip} is created.
+
+        :return: the delay time, in milliseconds.
+        """

return self._startdelaytime

@@ -613,7 +632,9 @@
"""
Sets the delay time after which the BalloonTip is destroyed.

-        :param `delay`: the number of milliseconds after which L{BalloonTip} is destroyed.
+        :param integer `delay`: the number of milliseconds after which L{BalloonTip} is destroyed.
+
+        :raise: `Exception` if `delay` is less than ``1`` milliseconds.
"""

if delay < 1:
@@ -623,7 +644,11 @@

def GetEndDelay(self):
-        """ Returns the delay time after which the L{BalloonTip} is destroyed."""
+        """
+        Returns the delay time after which the L{BalloonTip} is destroyed.
+
+        :return: the delay time, in milliseconds.
+        """

return self._enddelaytime

@@ -711,6 +736,8 @@
This prevents the annoying behavior of L{BalloonTip} to display when the
user does something else inside the window. The L{BalloonTip} window is
displayed only when the mouse does *not* move for the start delay time.
+
+        :param `event`: a `wx.MouseEvent` event to be processed.
"""

if hasattr(self, "BalloonFrame"):
@@ -780,7 +807,10 @@
"""
Sets the L{BalloonTip} frame shape.

-        :param `shape`: should be one of ``BT_ROUNDED`` or ``BT_RECTANGLE``.
+        :param integer `shape`: should be one of ``BT_ROUNDED`` or ``BT_RECTANGLE``.
+
+        :raise: `Exception` if the `shape` parameter is not a valid value
+         (i.e., it's not one of ``BT_ROUNDED``, ``BT_RECTANGLE``);
"""

if shape not in [BT_ROUNDED, BT_RECTANGLE]:
@@ -790,7 +820,11 @@

def GetBalloonShape(self):
-        """ Returns the L{BalloonTip} frame shape."""
+        """
+        Returns the L{BalloonTip} frame shape.
+
+        :return: An integer, one of ``BT_ROUNDED``, ``BT_RECTANGLE``.
+        """

return self._shape

@@ -800,6 +834,8 @@
Sets the L{BalloonTip} top-left icon.

:param `icon`: an instance of `wx.Bitmap`.
+
+        :raise: `Exception` if the `icon` bitmap is not a valid `wx.Bitmap`.
"""

if icon.Ok():
@@ -809,7 +845,11 @@

def GetBalloonIcon(self):
-        """ Returns the L{BalloonTip} top-left icon."""
+        """
+        Returns the L{BalloonTip} top-left icon.
+
+        :return: An instance of `wx.Bitmap`.
+        """

return self._topicon

@@ -818,14 +858,18 @@
"""
Sets the L{BalloonTip} top title.

-        :param `title`: a string to use as a L{BalloonTip} title.
+        :param string `title`: a string to use as a L{BalloonTip} title.
"""

self._toptitle = title

def GetBalloonTitle(self):
-        """ Returns the L{BalloonTip} top title."""
+        """
+        Returns the L{BalloonTip} top title.
+
+        :return: A string containing the top title.
+        """

return self._toptitle

@@ -834,7 +878,9 @@
"""
Sets the L{BalloonTip} tip message.

-        :param `message`: a string identifying the main message body of L{BalloonTip}.
+        :param string `message`: a string identifying the main message body of L{BalloonTip}.
+
+        :raise: `Exception` if the message is an empty string.

:note: The L{BalloonTip} message should never be empty.
"""
@@ -846,7 +892,11 @@

def GetBalloonMessage(self):
-        """ Returns the L{BalloonTip} tip message."""
+        """
+        Returns the L{BalloonTip} tip message.
+
+        :return: A string containing the main message.
+        """

return self._message

@@ -855,7 +905,7 @@
"""
Sets the L{BalloonTip} `tipstyle` parameter.

-        :param `tipstyle`: one of the following bit set:
+        :param integer `tipstyle`: one of the following bit set:

============== ========== =====================================
Tip Style      Hex Value  Description
@@ -864,6 +914,9 @@
``BT_CLICK``          0x4 L{BalloonTip} will be destroyed when the user click on L{BalloonTip}.
``BT_BUTTON``         0x5 L{BalloonTip} will be destroyed when the user click on the close button.
============== ========== =====================================
+
+        :raise: `Exception` if the `tipstyle` parameter has an invalid value
+         (i.e., it's not one of ``BT_LEAVE``, ``BT_CLICK``, ``BT_BUTTON``).
"""

if tipstyle not in [BT_LEAVE, BT_CLICK, BT_BUTTON]:
@@ -877,6 +930,8 @@
"""
Returns the L{BalloonTip} `tipstyle` parameter.

+        :return: An integer representing the style.
+
:see: L{SetBalloonTipStyle}
"""

@@ -897,7 +952,11 @@

def GetBalloonColour(self):
-        """ Returns the L{BalloonTip} background colour."""
+        """
+        Returns the L{BalloonTip} background colour.
+
+        :return: An instance of `wx.Colour`.
+        """

return self._ballooncolour

@@ -916,7 +975,11 @@

def GetTitleFont(self):
-        """ Returns the font for the top title."""
+        """
+        Returns the font for the top title.
+
+        :return: An instance of `wx.Font`.
+        """

return self._balloontitlefont

@@ -935,7 +998,11 @@

def GetMessageFont(self):
-        """ Returns the font for the tip message."""
+        """
+        Returns the font for the tip message.
+
+        :return: An instance of `wx.Font`.
+        """

return self._balloonmsgfont

@@ -954,7 +1021,11 @@

def GetTitleColour(self):
-        """ Returns the colour for the top title."""
+        """
+        Returns the colour for the top title.
+
+        :return: An instance of `wx.Colour`.
+        """

return self._balloontitlecolour

@@ -973,7 +1044,11 @@

def GetMessageColour(self):
-        """ Returns the colour for the tip message."""
+        """
+        Returns the colour for the tip message.
+
+        :return: An instance of `wx.Colour`.
+        """

return self._balloonmsgcolour

@@ -1010,7 +1085,7 @@
"""
Enable/disable globally the L{BalloonTip}.

-        :param `enable`: ``True`` to enable L{BalloonTip}, ``False`` otherwise.
+        :param bool `enable`: ``True`` to enable L{BalloonTip}, ``False`` otherwise.
"""

self._runningapp.__tooltipenabled__ = enable

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • balloontip »
  • SVN Revision 69086 For balloontip


SVN Revision 68362 For bar

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • ribbon library »
  • ribbon.bar »
  • SVN Revision 68362 For bar

svn SVN Revision 68362 For bar

This file contains the SVN revision history for bar, at revision 68362.

Available information include commit date, the name of the committer, the file size, the SVN log messages and a diff from the previous version (if available).

File Information

  • Commit Date: 09-Jan-2010 21:41:13 UTC
  • Committer: AG
  • File Size: 44252 byte(s)

Log Messages

The following log message was entered by the committer:

  • All of AGW: change my work e-mail from KPO to Maersk Oil (silly commit)

Diff To Previous Version (65529)

Version SVN diff:

--- wxPython/3rdParty/AGW/agw/ribbon/bar.py 2010/09/12 11:58:40     65529
+++ wxPython/3rdParty/AGW/agw/ribbon/bar.py 2011/07/24 21:36:47     68362
@@ -15,7 +15,7 @@
# Write To Me At:
#
# andrea.gavana@gmail.com
-# gavana@kpo.kz
+# andrea.gavana@maerskoil.com
#
# Or, Obviously, To The wxPython Mailing List!!!
#

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • ribbon library »
  • ribbon.bar »
  • SVN Revision 68362 For bar


SVN Revision 68881 For bar

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • ribbon library »
  • ribbon.bar »
  • SVN Revision 68881 For bar

svn SVN Revision 68881 For bar

This file contains the SVN revision history for bar, at revision 68881.

Available information include commit date, the name of the committer, the file size, the SVN log messages and a diff from the previous version (if available).

File Information

  • Commit Date: 18-Nov-2009 22:19:25 UTC
  • Committer: AG
  • File Size: 45263 byte(s)

Log Messages

The following log message was entered by the committer:

  • AGW: General overhaul of the documentation, much improved. All the widgets have their own sample usage in the docs as well;

  • FlatNotebook: Added the FNB_NAV_BUTTONS_WHEN_NEEDED style, which hides the navigation left/right arrows if all tabs fit;

  • RibbonBar: - Added the EVT_RIBBONBAR_TAB_LEFT_DCLICK event, which generates a special event

    when a ribbon bar tab is double-clicked;

    • Added support for toggle buttons;
    • Improved support for ribbon panel sizers: panels with sizers should now automatically minimise at small sizes, and behave properly when popping up from a minimised state;
    • Added tooltips via SetToolTip for those buttons which have the help_string attribute set.

  • XLSGrid: a new widget was added to AGW, termed XLSGrid. It’s based on wx.grid.Grid and can be used to faithfully reproduce the appearance of a Microsoft Excel spreadsheets.

Diff To Previous Version (68362)

Version SVN diff:

--- wxPython/3rdParty/AGW/agw/ribbon/bar.py 2011/07/24 21:36:47     68362
+++ wxPython/3rdParty/AGW/agw/ribbon/bar.py 2011/08/25 16:40:17     68881
@@ -9,7 +9,7 @@
# Python Code By:
#
# Andrea Gavana, @ 15 Oct 2009
-# Latest Revision: 12 Sep 2010, 10.00 GMT
+# Latest Revision: 17 Aug 2011, 15.00 GMT
#
# For All Kind Of Problems, Requests Of Enhancements And Bug Reports, Please
# Write To Me At:
@@ -77,6 +77,7 @@
``EVT_RIBBONBAR_TAB_MIDDLE_UP``   Triggered when the middle mouse button is released on a tab.
``EVT_RIBBONBAR_TAB_RIGHT_DOWN``  Triggered when the right mouse button is pressed on a tab.
``EVT_RIBBONBAR_TAB_RIGHT_UP``    Triggered when the right mouse button is released on a tab.
+``EVT_RIBBONBAR_TAB_LEFT_DCLICK`` Triggered when the user double-clicks on a tab.
================================= =================================

@@ -102,6 +103,7 @@
wxEVT_COMMAND_RIBBONBAR_TAB_MIDDLE_UP = wx.NewEventType()
wxEVT_COMMAND_RIBBONBAR_TAB_RIGHT_DOWN = wx.NewEventType()
wxEVT_COMMAND_RIBBONBAR_TAB_RIGHT_UP = wx.NewEventType()
+wxEVT_COMMAND_RIBBONBAR_TAB_LEFT_DCLICK = wx.NewEventType()

EVT_RIBBONBAR_PAGE_CHANGED = wx.PyEventBinder(wxEVT_COMMAND_RIBBONBAR_PAGE_CHANGED, 1)
EVT_RIBBONBAR_PAGE_CHANGING = wx.PyEventBinder(wxEVT_COMMAND_RIBBONBAR_PAGE_CHANGING, 1)
@@ -109,6 +111,7 @@
EVT_RIBBONBAR_TAB_MIDDLE_UP = wx.PyEventBinder(wxEVT_COMMAND_RIBBONBAR_TAB_MIDDLE_UP, 1)
EVT_RIBBONBAR_TAB_RIGHT_DOWN = wx.PyEventBinder(wxEVT_COMMAND_RIBBONBAR_TAB_RIGHT_DOWN, 1)
EVT_RIBBONBAR_TAB_RIGHT_UP = wx.PyEventBinder(wxEVT_COMMAND_RIBBONBAR_TAB_RIGHT_UP, 1)
+EVT_RIBBONBAR_TAB_LEFT_DCLICK = wx.PyEventBinder(wxEVT_COMMAND_RIBBONBAR_TAB_LEFT_DCLICK, 1)

def SET_FLAG(variable, flag):
@@ -231,11 +234,13 @@
self._tab_scroll_left_button_state = RIBBON_SCROLL_BTN_NORMAL
self._tab_scroll_right_button_state = RIBBON_SCROLL_BTN_NORMAL
self._tab_scroll_buttons_shown = False
+        self._arePanelsShown = True
self._pages = []

self.Bind(wx.EVT_ERASE_BACKGROUND, self.OnEraseBackground)
self.Bind(wx.EVT_LEAVE_WINDOW, self.OnMouseLeave)
self.Bind(wx.EVT_LEFT_DOWN, self.OnMouseLeftDown)
+        self.Bind(wx.EVT_LEFT_DCLICK, self.OnMouseDoubleClick)
self.Bind(wx.EVT_LEFT_UP, self.OnMouseLeftUp)
self.Bind(wx.EVT_MIDDLE_DOWN, self.OnMouseMiddleDown)
self.Bind(wx.EVT_MIDDLE_UP, self.OnMouseMiddleUp)
@@ -302,6 +307,19 @@
return self._pages[self._current_page].page.DismissExpandedPanel()

+    def ShowPanels(self, show=True):
+        """
+        Shows or hides the panels inside L{RibbonBar}.
+
+        :param `show`: ``True`` to show the panels, ``False`` to hide them.
+        """
+
+        self._arePanelsShown = show
+        self.SetMinSize(wx.Size(self.GetSize().GetWidth(), self.DoGetBestSize().GetHeight()))
+        self.Realise()
+        self.GetParent().Layout()
+
+
def SetAGWWindowStyleFlag(self, agwStyle):
"""
Sets the window style for L{RibbonBar}.
@@ -749,6 +767,7 @@
self._tab_scroll_left_button_state = RIBBON_SCROLL_BTN_NORMAL
self._tab_scroll_right_button_state = RIBBON_SCROLL_BTN_NORMAL
self._tab_scroll_buttons_shown = False
+        self._arePanelsShown = True
self._tab_scroll_left_button_rect = wx.Rect()
self._tab_scroll_right_button_rect = wx.Rect()

@@ -922,7 +941,12 @@
elif self._tab_scroll_right_button_rect.Contains(event.GetPosition()):
self._tab_scroll_right_button_state |= RIBBON_SCROLL_BTN_ACTIVE | RIBBON_SCROLL_BTN_HOVERED
self.RefreshTabBar()
-
+
+
+    def OnMouseDoubleClick(self, event):
+
+        self.DoMouseButtonCommon(event, wxEVT_COMMAND_RIBBONBAR_TAB_LEFT_DCLICK)
+

def OnMouseLeftUp(self, event):

@@ -1049,7 +1073,7 @@
min_size.IncBy(0, self._tab_height)

self._minWidth = min_size.GetWidth()
-        self._minHeight = min_size.GetHeight()
+        self._minHeight = (self._arePanelsShown and [min_size.GetHeight()] or [self._tab_height])[0]

def DoGetBestSize(self):
@@ -1064,6 +1088,9 @@
else:
best.IncBy(0, self._tab_height)

+        if not self._arePanelsShown:
+            best.SetHeight(self._tab_height)
+
return best

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • ribbon library »
  • ribbon.bar »
  • SVN Revision 68881 For bar


SVN Revision 68881 For buttonbar

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • ribbon library »
  • ribbon.buttonbar »
  • SVN Revision 68881 For buttonbar

svn SVN Revision 68881 For buttonbar

This file contains the SVN revision history for buttonbar, at revision 68881.

Available information include commit date, the name of the committer, the file size, the SVN log messages and a diff from the previous version (if available).

File Information

  • Commit Date: 10-Dec-2009 18:09:38 UTC
  • Committer: AG
  • File Size: 34686 byte(s)

Log Messages

The following log message was entered by the committer:

  • AGW: General overhaul of the documentation, much improved. All the widgets have their own sample usage in the docs as well;

  • FlatNotebook: Added the FNB_NAV_BUTTONS_WHEN_NEEDED style, which hides the navigation left/right arrows if all tabs fit;

  • RibbonBar: - Added the EVT_RIBBONBAR_TAB_LEFT_DCLICK event, which generates a special event

    when a ribbon bar tab is double-clicked;

    • Added support for toggle buttons;
    • Improved support for ribbon panel sizers: panels with sizers should now automatically minimise at small sizes, and behave properly when popping up from a minimised state;
    • Added tooltips via SetToolTip for those buttons which have the help_string attribute set.

  • XLSGrid: a new widget was added to AGW, termed XLSGrid. It’s based on wx.grid.Grid and can be used to faithfully reproduce the appearance of a Microsoft Excel spreadsheets.

Diff To Previous Version (65529)

Version SVN diff:

--- wxPython/3rdParty/AGW/agw/ribbon/buttonbar.py   2010/09/12 11:58:40     65529
+++ wxPython/3rdParty/AGW/agw/ribbon/buttonbar.py   2011/08/25 16:40:17     68881
@@ -206,12 +206,12 @@
"""
Default class constructor.

-        :param `parent`: Pointer to a parent window;
-        :param `id`: Window identifier. If ``wx.ID_ANY``, will automatically create
+        :param `parent`: pointer to a parent window;
+        :param `id`: window identifier. If ``wx.ID_ANY``, will automatically create
an identifier;
-        :param `pos`: Window position. ``wx.DefaultPosition`` indicates that wxPython
+        :param `pos`: window position. ``wx.DefaultPosition`` indicates that wxPython
should generate a default position for the window;
-        :param `size`: Window size. ``wx.DefaultSize`` indicates that wxPython should
+        :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;
@@ -238,11 +238,11 @@
"""
Add a button to the button bar (simple version).

-        :param `button_id`: ID of the button to enable or disable;
-        :param `label`: Label of the new button;
-        :param `bitmap`: Large bitmap of the new button. Must be the same size as
+        :param `button_id`: ID of the button;
+        :param `label`: label of the new button;
+        :param `bitmap`: large bitmap of the new button. Must be the same size as
all other large bitmaps used on the button bar;
-        :param `help_string`: The UI help string to associate with the new button;
+        :param `help_string`: the UI help string to associate with the new button;
:param `kind`: The kind of button to add.

"""
@@ -255,11 +255,11 @@
"""
Add a dropdown button to the button bar (simple version).

-        :param `button_id`: ID of the button to enable or disable;
-        :param `label`: Label of the new button;
-        :param `bitmap`: Large bitmap of the new button. Must be the same size as
+        :param `button_id`: ID of the button;
+        :param `label`: label of the new button;
+        :param `bitmap`: large bitmap of the new button. Must be the same size as
all other large bitmaps used on the button bar;
-        :param `help_string`: The UI help string to associate with the new button.
+        :param `help_string`: the UI help string to associate with the new button.

:see: L{AddButton}
"""
@@ -271,11 +271,11 @@
"""
Add a hybrid button to the button bar (simple version).

-        :param `button_id`: ID of the button to enable or disable;
-        :param `label`: Label of the new button;
-        :param `bitmap`: Large bitmap of the new button. Must be the same size as
+        :param `button_id`: ID of the button;
+        :param `label`: label of the new button;
+        :param `bitmap`: large bitmap of the new button. Must be the same size as
all other large bitmaps used on the button bar;
-        :param `help_string`: The UI help string to associate with the new button.
+        :param `help_string`: the UI help string to associate with the new button.

:see: L{AddButton}
"""
@@ -289,19 +289,19 @@
Add a button to the button bar.

:param `button_id`: ID of the new button (used for event callbacks);
-        :param `label`: Label of the new button;
-        :param `bitmap`: Large bitmap of the new button. Must be the same size as
+        :param `label`: label of the new button;
+        :param `bitmap`: large bitmap of the new button. Must be the same size as
all other large bitmaps used on the button bar;
-        :param `bitmap_small`: Small bitmap of the new button. If left as ``None``,
+        :param `bitmap_small`: small bitmap of the new button. If left as ``None``,
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.
+        :param `bitmap_disabled`: large bitmap of the new button when it is disabled.
If left as ``None``, then a bitmap will be automatically generated from `bitmap`;
-        :param `bitmap_small_disabled`: Small bitmap of the new button when it is disabled.
+        :param `bitmap_small_disabled`: small bitmap of the new button when it is disabled.
If left as ``None``, then a bitmap will be automatically generated from `bitmap_small`;
-        :param `kind`: The kind of button to add;
-        :param `help_string`: The UI help string to associate with the new button;
-        :param `client_data`: Client data to associate with the new button.
+        :param `kind`: the kind of button to add;
+        :param `help_string`: the UI help string to associate with the new button;
+        :param `client_data`: client data to associate with the new button.

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

@@ -309,8 +309,11 @@
"""

if not bitmap.IsOk() and not bitmap_small.IsOk():
-            raise Exception("exception")
-
+            raise Exception("Invalid main bitmap")
+
+        if not isinstance(help_string, basestring):
+            raise Exception("Invalid help string parameter")
+
if not self._buttons:
if bitmap.IsOk():

@@ -372,6 +375,22 @@
return base

+    def AddToggleButton(self, button_id, label, bitmap, help_string=""):
+        """
+        Add a toggle button to the button bar.
+
+        :param `button_id`: ID of the button;
+        :param `label`: label of the new button;
+        :param `bitmap`: large bitmap of the new button. Must be the same size as
+         all other large bitmaps used on the button bar;
+        :param `help_string`: the UI help string to associate with the new button.
+
+        :see: L{AddButton}
+        """
+
+        return self.AddButton(button_id, label, bitmap, help_string, RIBBON_BUTTON_TOGGLE)
+
+
def FetchButtonSizeInfo(self, button, size, dc):

info = button.sizes[size]
@@ -407,8 +426,7 @@
added buttons will not be displayed. In normal situations, it will be called
automatically when L{RibbonBar.Realize} is called.

-        Reimplemented from L{RibbonControl}.
-
+        :note: Reimplemented from L{RibbonControl}.
"""

if not self._layouts_valid:
@@ -434,7 +452,7 @@
"""
Delete a single button from the button bar.

-        :param `button_id`: ID of the button to enable or disable.
+        :param `button_id`: ID of the button to delete.

:see: L{ClearButtons}
"""
@@ -456,7 +474,6 @@

:param `button_id`: ID of the button to enable or disable;
:param `enable`: ``True`` to enable the button, ``False`` to disable it.
-
"""

for button in self._buttons:
@@ -473,6 +490,28 @@
return

+    def ToggleButton(self, button_id, checked=True):
+        """
+        Toggles/untoggles a L{RibbonButtonBar} toggle button.
+
+        :param `button_id`: ID of the button to be toggles/untoggled;
+        :param `checked`: ``True`` to toggle the button, ``False`` to untoggle it.
+        """
+
+        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
+
+
def IsButtonEnabled(self, button_id):
"""
Returns whether a button in the bar is enabled or not.
@@ -805,7 +844,10 @@
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):

@@ -815,6 +857,7 @@
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)

@@ -892,7 +935,13 @@
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

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • ribbon library »
  • ribbon.buttonbar »
  • SVN Revision 68881 For buttonbar


SVN Revision 69086 For buttonbar

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • ribbon library »
  • ribbon.buttonbar »
  • SVN Revision 69086 For buttonbar

svn SVN Revision 69086 For buttonbar

This file contains the SVN revision history for buttonbar, at revision 69086.

Available information include commit date, the name of the committer, the file size, the SVN log messages and a diff from the previous version (if available).

File Information

  • Commit Date: 18-Nov-2009 22:19:25 UTC
  • Committer: AG
  • File Size: 34687 byte(s)

Log Messages

The following log message was entered by the committer:

  • Fixed bug #13437 for SuperToolTip;
  • Fixed bug #13477 for UltimateListCtrl.

Diff To Previous Version (68881)

Version SVN diff:

--- wxPython/3rdParty/AGW/agw/ribbon/buttonbar.py   2011/08/25 16:40:17     68881
+++ wxPython/3rdParty/AGW/agw/ribbon/buttonbar.py   2011/09/14 19:39:08     69086
@@ -5,7 +5,7 @@
Description
===========

-It contains one or more buttons (button bar buttons, not wx.Buttons), each of which
+It contains one or more buttons (button bar buttons, not `wx.Button`), each of which
has a label and an icon. It differs from a L{RibbonToolBar} in several ways:

- Individual buttons can grow and contract.

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • ribbon library »
  • ribbon.buttonbar »
  • SVN Revision 69086 For buttonbar


buttonpanel functions

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • buttonpanel »
  • buttonpanel functions

buttonpanel functions

This is the description of standalone Python functions in the buttonpanel module.

Functions Summary

BrightenColour | Brighten the input colour by a factor.
MakeDisabledBitmap | Creates a disabled-looking bitmap starting from the input one.

API Functions API

BrightenColour(colour, factor) [source]

Brighten the input colour by a factor.

Parameters:
  • colour – a valid wx.Colour instance;
  • factor (integer) – the factor by which the input colour should be brightened.
Returns:

An instance of wx.Colour, a brightened version of the input colour.

MakeDisabledBitmap(original) [source]

Creates a disabled-looking bitmap starting from the input one.

Parameters: original – an instance of wx.Bitmap to be greyed-out.
Returns: A greyed-out representation of the input bitmap, an instance of wx.Bitmap.

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • infobar
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • buttonpanel »
  • buttonpanel functions


BoxSizer

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • buttonpanel »
  • BoxSizer

BoxSizer

Pseudo-class that imitates wx.BoxSizer.

hierarchy Inheritance Diagram

Inheritance diagram for: BoxSizer

Inheritance diagram of BoxSizer

supclasses Known Superclasses

  • buttonpanel.Sizer

Methods Summary

__init__ | Constructor for BoxSizer.
Add | Appends a child item to the sizer.
Insert | Inserts a child item into the sizer.
Layout | Call this to force layout of the children anew, e.g.
Prepend | Prepends a child item to the sizer.
Remove | Removes an item from the sizer and destroys it.
Show | Shows or hides the sizer item.

API Class API

class BoxSizer(Sizer, wx.BoxSizer) [source]

Pseudo-class that imitates wx.BoxSizer.

__init__(orient=wx.HORIZONTAL) [source]

Constructor for BoxSizer.

Parameters: orient (integer) – may be one of wx.VERTICAL or wx.HORIZONTAL for creating either a column sizer or a row sizer.

Add(item, proportion=0, flag=0, border=0, userData=None) [source]

Appends a child item to the sizer.

Parameters:
  • item – the item to be added to BoxSizer. Can be an instance of wx.Window, wx.Sizer or a spacer;
  • proportion (integer) – this parameter is used in BoxSizer to indicate if a child of a sizer can change its size in the main orientation of the BoxSizer - where 0 stands for not changeable and a value of more than zero is interpreted relative to the value of other children of the same BoxSizer. For example, you might have a horizontal BoxSizer with three children, two of which are supposed to change their size with the sizer. Then the two stretchable windows would get a value of 1 each to make them grow and shrink equally with the sizer’s horizontal dimension.
  • flag (integer) – this parameter can be used to set a number of flags which can be combined using the binary OR operator |. Two main behaviours are defined using these flags. One is the border around a window: the border parameter determines the border width whereas the flags given here determine which side(s) of the item that the border will be added. The other flags determine how the sizer item behaves when the space allotted to the sizer changes, and is somewhat dependent on the specific kind of sizer used:

    integer parameter settings
    Sizer Flag | Description
    wx.TOP | These flags are used to specify which side(s) of the sizer item the border width will apply to.
    wx.BOTTOM
    wx.LEFT
    wx.RIGHT
    wx.ALL
    wx.EXPAND | The item will be expanded to fill the space assigned to the item.
    wx.SHAPED | The item will be expanded as much as possible while also maintaining its aspect ratio
    wx.FIXED_MINSIZE | Normally wx.Sizers will use wx.Window.GetAdjustedBestSize to determine what the minimal size of window items should be, and will use that size to calculate the layout. This allows layouts to adjust when an item changes and its best size becomes different. If you would rather have a window item stay the size it started with then use wx.FIXED_MINSIZE.
    wx.RESERVE_SPACE_EVEN_IF_HIDDEN | Normally wx.Sizers don’t allocate space for hidden windows or other items. This flag overrides this behavior so that sufficient space is allocated for the window even if it isn’t visible. This makes it possible to dynamically show and hide controls without resizing parent dialog, for example. This function is new since wxWidgets version 2.8.8
    wx.ALIGN_CENTER or wx.ALIGN_CENTRE | The wx.ALIGN* flags allow you to specify the alignment of the item within the space allotted to it by the sizer, adjusted for the border if any.
    wx.ALIGN_LEFT
    wx.ALIGN_RIGHT
    wx.ALIGN_TOP
    wx.ALIGN_BOTTOM
    wx.ALIGN_CENTER_VERTICAL or wx.ALIGN_CENTRE_VERTICAL
    wx.ALIGN_CENTER_HORIZONTAL or wx.ALIGN_CENTRE_HORIZONTAL
  • border (integer) – determines the border width, if the flag parameter is set to include any border flag.
  • userData (object) – Allows an extra object to be attached to the sizer item, for use in derived classes when sizing information is more complex than the proportion and flag will allow for.

Note

there is no support for userData parameter if item is a pseudocontrol, since that is already used.

Insert(before, item, proportion=0, flag=0, border=0, userData=None, realIndex=None) [source]

Inserts a child item into the sizer.

See also

Add method for an explanation of the input parameters.

Layout() [source]

Call this to force layout of the children anew, e.g. after having added a child to or removed a child (window, other sizer or space) from the sizer while keeping the current dimension.

Prepend(item, proportion=0, flag=0, border=0, userData=None) [source]

Prepends a child item to the sizer.

See also

Add method for an explanation of the input parameters.

Remove(indx, pop=-1) [source]

Removes an item from the sizer and destroys it.

This method does not cause any layout or resizing to take place, call BoxSizer.Layout() to update the layout on screen after removing a child from the sizer.

Parameters:
  • indx (integer) – the zero-based index of an item to remove;
  • pop (bool) – whether to remove the sizer item from the list of children.

Show(item, show=True) [source]

Shows or hides the sizer item.

Parameters:
  • item – the sizer item we want to show/hide;
  • show (bool) – True to show the item, False to hide it.

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • infobar
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • buttonpanel »
  • BoxSizer


BPArt

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • buttonpanel »
  • BPArt

BPArt

BPArt is an art provider class which does all of the drawing for ButtonPanel. This allows the library caller to customize the BPArt or to completely replace all drawing with custom BPArts.

hierarchy Inheritance Diagram

Inheritance diagram for: BPArt

Inheritance diagram of BPArt

Methods Summary

__init__ | Default class constructor.
DrawButton | Draws a button in ButtonPanel, together with its text (if any).
DrawButtonPanel | Paint the ButtonPanel‘s background.
DrawCaption | Draws the main caption text in ButtonPanel.
DrawLabel | Draws the label for a button.
DrawSeparator | Draws a separator in ButtonPanel.
FillGradientColour | Gradient fill from colour 1 to colour 2 with top to bottom or left to right.
GetColor | Returns the option value for the specified colour id.
GetColour | Returns the option value for the specified colour id.
GetFont | Returns the option value for the specified font id.
GetGradientType | Returns the gradient type for BPArt drawings.
GetMetric | Returns the option value for the specified size id.
SetColor | Sets the option value for the specified colour id.
SetColour | Sets the option value for the specified colour id.
SetFont | Sets the option value for the specified font id.
SetGradientType | Sets the gradient type for BPArt drawings.
SetMetric | Sets the option value for the specified size id.

API Class API

class BPArt(object) [source]

BPArt is an art provider class which does all of the drawing for ButtonPanel. This allows the library caller to customize the BPArt or to completely replace all drawing with custom BPArts.

__init__(parentStyle) [source]

Default class constructor.

Parameters: parentStyle (integer) – the window style for ButtonPanel.

DrawButton(dc, rect, buttonBitmap, isVertical, buttonStatus, isToggled, textAlignment, text='') [source]

Draws a button in ButtonPanel, together with its text (if any).

Parameters:
  • dc – an instance of wx.DC;
  • rect (wx.Rect) – the button client rectangle;
  • buttonBitmap (wx.Bitmap) – the bitmap associated with the button;
  • isVertical (bool) – True if ButtonPanel is in vertical orientation, False otherwise;
  • buttonStatus (string) – one of “Normal”, “Toggled”, “Pressed”, “Disabled” or “Hover”;
  • isToggled (bool) – whether the button is toggled or not;
  • textAlignment (integer) – the text alignment inside the button;
  • text (string) – the button label.

DrawButtonPanel(dc, rect, style) [source]

Paint the ButtonPanel‘s background.

Parameters:
  • dc – an instance of wx.DC;

  • rect (wx.Rect) – the ButtonPanel client rectangle;
  • style (integer) – the ButtonPanel window style.

DrawCaption(dc, rect, captionText) [source]

Draws the main caption text in ButtonPanel.

Parameters:
  • dc – an instance of wx.DC;

  • rect (wx.Rect) – the main caption text rectangle;
  • captionText (string) – the caption text string.

DrawLabel(dc, text, isEnabled, xpos, ypos) [source]

Draws the label for a button.

Parameters:
  • dc – an instance of wx.DC;

  • text (string) – the button label;
  • isEnabled (bool) – True if the button is enabled, False otherwise;
  • xpos (integer) – the text x position inside the button;
  • ypos (integer) – the text y position inside the button.

DrawSeparator(dc, rect, isVertical) [source]

Draws a separator in ButtonPanel.

Parameters:
  • dc – an instance of wx.DC;

  • rect (wx.Rect) – the separator client rectangle;
  • isVertical (bool) – True if ButtonPanel is in vertical orientation, False otherwise.

FillGradientColour(dc, rect) [source]

Gradient fill from colour 1 to colour 2 with top to bottom or left to right.

Parameters:
  • dc – an instance of wx.DC;

  • rect (wx.Rect) – the ButtonPanel client rectangle.

GetColor(id)

Returns the option value for the specified colour id.

Parameters: internal`id` – the identification bit for the colour value. This can be one of the following bits:

wx.Rect parameter settings
Colour Id | Value | Description
BP_BACKGROUND_COLOUR | 0 | Background brush colour when no gradient shading exists
BP_GRADIENT_COLOUR_FROM | 1 | Starting gradient colour, used only when BP_USE_GRADIENT style is applied
BP_GRADIENT_COLOUR_TO | 2 | Ending gradient colour, used only when BP_USE_GRADIENT style is applied
BP_BORDER_COLOUR | 3 | Pen colour to paint the border of ButtonPanel
BP_TEXT_COLOUR | 4 | Main ButtonPanel caption colour
BP_BUTTONTEXT_COLOUR | 5 | Text colour for buttons with text
BP_BUTTONTEXT_INACTIVE_COLOUR | 6 | Text colour for inactive buttons with text
BP_SELECTION_BRUSH_COLOUR | 7 | Brush colour to be used when hovering or selecting a button
BP_SELECTION_PEN_COLOUR | 8 | Pen colour to be used when hovering or selecting a button
BP_SEPARATOR_COLOUR | 9 | Pen colour used to paint the separators
Returns: An instance of wx.Colour for the input id.
Raise : Exception if the id is not recognized.

GetColour(id) [source]

Returns the option value for the specified colour id.

Parameters: internal`id` – the identification bit for the colour value. This can be one of the following bits:

Colour Id | Value | Description
BP_BACKGROUND_COLOUR | 0 | Background brush colour when no gradient shading exists
BP_GRADIENT_COLOUR_FROM | 1 | Starting gradient colour, used only when BP_USE_GRADIENT style is applied
BP_GRADIENT_COLOUR_TO | 2 | Ending gradient colour, used only when BP_USE_GRADIENT style is applied
BP_BORDER_COLOUR | 3 | Pen colour to paint the border of ButtonPanel
BP_TEXT_COLOUR | 4 | Main ButtonPanel caption colour
BP_BUTTONTEXT_COLOUR | 5 | Text colour for buttons with text
BP_BUTTONTEXT_INACTIVE_COLOUR | 6 | Text colour for inactive buttons with text
BP_SELECTION_BRUSH_COLOUR | 7 | Brush colour to be used when hovering or selecting a button
BP_SELECTION_PEN_COLOUR | 8 | Pen colour to be used when hovering or selecting a button
BP_SEPARATOR_COLOUR | 9 | Pen colour used to paint the separators
Returns: An instance of wx.Colour for the input id.
Raise : Exception if the id is not recognized.

GetFont(id) [source]

Returns the option value for the specified font id.

Parameters: id (integer) – the identification bit for the font value. This can be one of the following bits:

integer parameter settings
Size Id | Value | Description
BP_TEXT_FONT | 10 | Font of the ButtonPanel main caption
BP_BUTTONTEXT_FONT | 11 | Text font for the buttons with text
Returns: An instance of wx.Font for the input id.
Raise : Exception if the id is not recognized.

GetGradientType() [source]

Returns the gradient type for BPArt drawings.

Returns: An integer representing the gradient type.

See also

SetGradientType for a list of possible gradient types.

GetMetric(id) [source]

Returns the option value for the specified size id.

Parameters: id (integer) – the identification bit for the size value. This can be one of the following bits:

integer parameter settings
Size Id | Value | Description
BP_SEPARATOR_SIZE | 14 | Separator size. Note: This is not the line width, but the sum of the space before and after the separator line plus the width of the line
BP_MARGINS_SIZE | 15 | Size of the left/right margins in ButtonPanel (top/bottom for vertically aligned ButtonPanel)
BP_BORDER_SIZE | 16 | Size of the border
BP_PADDING_SIZE | 17 | Inter-tool separator size
Returns: An integer representing the option value for the input id.
Raise : Exception if the id is not recognized.

SetColor(id, colour)

Sets the option value for the specified colour id.

Parameters:
  • id (integer) – the identification bit for the colour value;
  • colour – the new value for the colour (a valid wx.Colour instance).
Raise :

Exception if the id is not recognized.

See also

GetColour for a list of meaningful colour ids.

SetColour(id, colour) [source]

Sets the option value for the specified colour id.

Parameters:
  • id (integer) – the identification bit for the colour value;
  • colour – the new value for the colour (a valid wx.Colour instance).
Raise :

Exception if the id is not recognized.

See also

GetColour for a list of meaningful colour ids.

SetFont(id, font) [source]

Sets the option value for the specified font id.

Parameters:
  • id (integer) – the identification bit for the font value;
  • colour – the new value for the font (a valid wx.Font instance).
Raise :

Exception if the id is not recognized.

See also

GetFont for a list of meaningful font ids.

SetGradientType(gradient) [source]

Sets the gradient type for BPArt drawings.

Parameters: gradient (integer) – can be one of the following bits:

integer parameter settings
Gradient Type | Value | Description
BP_GRADIENT_NONE | 0 | No gradient shading should be used to paint the background
BP_GRADIENT_VERTICAL | 1 | Vertical gradient shading should be used to paint the background
BP_GRADIENT_HORIZONTAL | 2 | Horizontal gradient shading should be used to paint the background

SetMetric(id, new_val) [source]

Sets the option value for the specified size id.

Parameters:
  • id (integer) – the identification bit for the size value;
  • input`new_val` – the new value for the size.
Raise :

Exception if the id is not recognized.

See also

GetMetric for a list of meaningful size ids.

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • infobar
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • buttonpanel »
  • BPArt


ButtonInfo

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • buttonpanel »
  • ButtonInfo

ButtonInfo

This class holds information about every button that is added to ButtonPanel. It is an auxiliary class that you should use every time you add a button.

hierarchy Inheritance Diagram

Inheritance diagram for: ButtonInfo

Inheritance diagram of ButtonInfo

supclasses Known Superclasses

  • buttonpanel.Control

Methods Summary

__init__ | Default class constructor.
AddStatus | Add a programmer-defined status in addition to the 5 default status:
CheckRefresh | Checks whether a ButtonPanel repaint is needed or not. This is a convenience function.
Draw | Draws the button on ButtonPanel. Actually the drawing is done in BPArt.
Enable | Enables/disables this instance of ButtonInfo.
GetBestSize | Returns the best size for the button.
GetBitmap | Returns the bitmap associated with this instance of ButtonInfo.
GetId | Returns the ButtonInfo id.
GetKind | Returns the button type (standard or toggle).
GetLongHelp | Returns the help string shown in the statusbar.
GetRect | Returns the ButtonInfo client rectangle.
GetShortHelp | Returns the help string shown in a tooltip.
GetStatus | Returns the ButtonInfo status.
GetText | Returns the text associated to the button.
GetTextAlignment | Returns the text alignment in the button (bottom or right).
GetToggled | Returns whether a wx.ITEM_CHECK button is toggled or not.
HasText | Returns whether the button has text or not.
IsEnabled | Returns True if this instance of ButtonInfo is enabled for input,
SetBitmap | Sets the bitmap associated with this instance of ButtonInfo.
SetId | Sets the ButtonInfo identifier.
SetKind | Sets the button type (standard or toggle).
SetLongHelp | Sets the help string to be shown in the statusbar.
SetRect | Sets the ButtonInfo client rectangle.
SetShortHelp | Sets the help string to be shown in a tooltip.
SetStatus | Sets the ButtonInfo status.
SetText | Sets the button label text.
SetTextAlignment | Sets the text alignment in the button (bottom or right).
SetToggled | Sets a wx.ITEM_CHECK button toggled/not toggled.

API Class API

class ButtonInfo(Control) [source]

This class holds information about every button that is added to ButtonPanel. It is an auxiliary class that you should use every time you add a button.

__init__(parent, id=wx.ID_ANY, bmp=wx.NullBitmap, status="Normal", text="", kind=wx.ITEM_NORMAL, shortHelp="", longHelp="") [source]

Default class constructor.

Parameters:
  • parent – the parent window (ButtonPanel);
  • id (integer) – the button id;
  • bmp (wx.Bitmap) – the associated bitmap;
  • status (string) – button status (“Pressed”, “Hover”, “Normal”, “Toggled”, “Disabled”);
  • text (string) – text to be displayed either below of to the right of the button;
  • kind (integer) – button kind, may be wx.ITEM_NORMAL for standard buttons or wx.ITEM_CHECK for toggle buttons;
  • shortHelp (string) – a short help to be shown in the button tooltip;
  • longHelp (string) – this string is shown in the statusbar (if any) of the parent frame when the mouse pointer is inside the button.

AddStatus(name="Custom", bmp=wx.NullBitmap) [source]

Add a programmer-defined status in addition to the 5 default status:

  • Normal;
  • Disabled;
  • Hover;
  • Pressed;
  • Toggled.
Parameters:
  • name (string) – the new status name;
  • bmp (wx.Bitmap) – the bitmap associated with the new status.

Bitmap

Returns the bitmap associated with this instance of ButtonInfo.

Parameters: status (string) – the ButtonInfo status (“Pressed”, “Hover”, “Normal”, “Toggled”, “Disabled”).
Returns: An instance of wx.Bitmap.

CheckRefresh(status) [source]

Checks whether a ButtonPanel repaint is needed or not. This is a convenience function.

Parameters: status (bool) – the status of a newly added ButtonInfo or a change in the ButtonInfo status.

Draw(dc, rect) [source]

Draws the button on ButtonPanel. Actually the drawing is done in BPArt.

Parameters:
  • dc – an instance of wx.DC;
  • rect (wx.Rect) – the main caption text client rectangle.

Enable(enable=True) [source]

Enables/disables this instance of ButtonInfo.

Parameters: enable (bool) – True to enable the button, False otherwise.

GetBestSize() [source]

Returns the best size for the button.

Returns: An instance of wx.Size.

GetBitmap(status=None) [source]

Returns the bitmap associated with this instance of ButtonInfo.

Parameters: status (string) – the ButtonInfo status (“Pressed”, “Hover”, “Normal”, “Toggled”, “Disabled”).
Returns: An instance of wx.Bitmap.

GetId() [source]

Returns the ButtonInfo id.

Returns: An integer representing the button id.

GetKind() [source]

Returns the button type (standard or toggle).

Returns: An integer representing the button type, one of wx.ITEM_NORMAL, wx.ITEM_CHECK.

GetLongHelp() [source]

Returns the help string shown in the statusbar.

Returns: A string containing the ButtonInfo long help string.

GetRect() [source]

Returns the ButtonInfo client rectangle.

Returns: An instance of wx.Rect.

GetShortHelp() [source]

Returns the help string shown in a tooltip.

Returns: A string containing the ButtonInfo short help string.

GetStatus() [source]

Returns the ButtonInfo status.

Returns: A string containing the ButtonInfo status (one of “Pressed”, “Hover”, “Normal”, “Toggled”, “Disabled”).

GetText() [source]

Returns the text associated to the button.

Returns: A string containing the ButtonInfo text.

GetTextAlignment() [source]

Returns the text alignment in the button (bottom or right).

Returns: An integer representing the ButtonInfo text alignment.

GetToggled() [source]

Returns whether a wx.ITEM_CHECK button is toggled or not.

Returns: True if the button is toggled, False otherwise.

HasText() [source]

Returns whether the button has text or not.

Returns: True if this ButtonInfo instance has a label, False otherwise.

Id

Returns the ButtonInfo id.

Returns: An integer representing the button id.

IsEnabled() [source]

Returns True if this instance of ButtonInfo is enabled for input, False otherwise.

Rect

Returns the ButtonInfo client rectangle.

Returns: An instance of wx.Rect.

SetBitmap(bmp, status='Normal') [source]

Sets the bitmap associated with this instance of ButtonInfo.

Parameters:
  • bmp – a valid wx.Bitmap object;

  • status (string) – the ButtonInfo status (“Pressed”, “Hover”, “Normal”, “Toggled”, “Disabled”).

SetId(id) [source]

Sets the ButtonInfo identifier.

Parameters: id (integer) – the identifier of the window.

SetKind(kind=wx.ITEM_NORMAL) [source]

Sets the button type (standard or toggle).

Parameters: kind (integer) – one of wx.ITEM_NORMAL, wx.ITEM_CHECK.

SetLongHelp(help='') [source]

Sets the help string to be shown in the statusbar.

Parameters: help (string) – the string for the long help.

SetRect(rect) [source]

Sets the ButtonInfo client rectangle.

Parameters: rect – an instance of wx.Rect.

SetShortHelp(help='') [source]

Sets the help string to be shown in a tooltip.

Parameters: help (string) – the string for the short help.

SetStatus(status) [source]

Sets the ButtonInfo status.

Parameters: status (string) – one of “Pressed”, “Hover”, “Normal”, “Toggled”, “Disabled”.

SetText(text='') [source]

Sets the button label text.

Parameters: text (string) – the button label string.

SetTextAlignment(alignment) [source]

Sets the text alignment in the button (bottom or right).

Parameters: alignment (integer) – the text alignment in this ButtonInfo instance.

SetToggled(toggle=True) [source]

Sets a wx.ITEM_CHECK button toggled/not toggled.

Parameters: toggle (bool) – True to toggle the button, False otherwise.

Status

Returns the ButtonInfo status.

Returns: A string containing the ButtonInfo status (one of “Pressed”, “Hover”, “Normal”, “Toggled”, “Disabled”).

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • infobar
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • buttonpanel »
  • ButtonInfo


ButtonPanel

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • buttonpanel »
  • ButtonPanel

ButtonPanel

A custom panel class with gradient background shading with the possibility to add buttons and controls still respecting the gradient background.

hierarchy Inheritance Diagram

Inheritance diagram for: ButtonPanel

Inheritance diagram of ButtonPanel

appearance Control Appearance

ButtonPanel

Methods Summary

__init__ | Default class constructor.
AddButton | Adds a button to ButtonPanel.
AddControl | Adds a wxPython control to ButtonPanel.
AddSeparator | Adds a separator line to ButtonPanel.
AddSpacer | Adds a spacer (stretchable or fixed-size) to ButtonPanel.
Clear | Clears the ButtonPanel.
DoGetBestSize | Gets the size which best suits ButtonPanel: for a control, it would be
DoGiveHelp | Shows tooltips and long help strings in wx.StatusBar.
DoLayout | Do the Layout for ButtonPanel.
FlexibleLayout | Layout the items when the main caption exists.
GetAlignment | Returns the buttons alignment.
GetBPArt | Returns the associated BPArt art provider.
GetBarText | Returns the main caption text.
GetControls | Returns the wxPython controls that belongs to ButtonPanel.
GetItemSize | Returns the size of an item in the main ButtonPanel sizer.
GetNonFlexibleChildren | Returns all the ButtonPanel main sizer’s children that are not
GetStyle | Returns the ButtonPanel window style.
GetUseHelp | Returns whether or not short and long help strings should be displayed as tooltips
HasBarText | Returns whether ButtonPanel has a main caption text or not.
HitTest | HitTest method for ButtonPanel.
IsStandard | Returns whether ButtonPanel is aligned “Standard” (left/top) or not.
IsVertical | Returns whether ButtonPanel is vertically aligned or not.
LayoutItems | Layout the items using a different algorithms depending on the existance
OnEraseBackground | Handles the wx.EVT_ERASE_BACKGROUND event for ButtonPanel.
OnLeftDown | Handles the wx.EVT_LEFT_DOWN event for ButtonPanel.
OnLeftUp | Handles the wx.EVT_LEFT_UP event for ButtonPanel.
OnMouseEnterWindow | Handles the wx.EVT_ENTER_WINDOW event for ButtonPanel.
OnMouseLeave | Handles the wx.EVT_LEAVE_WINDOW event for ButtonPanel.
OnMouseMove | Handles the wx.EVT_MOTION event for ButtonPanel.
OnPaint | Handles the wx.EVT_PAINT event for ButtonPanel.
OnSize | Handles the wx.EVT_SIZE event for ButtonPanel.
OnStatusBarTimer | Handles the timer expiring to delete the long help string in wx.StatusBar.
ReCreateSizer | Recreates the ButtonPanel sizer accordingly to the alignment specified.
RemoveAllButtons | Remove all the buttons from ButtonPanel.
RemoveAllSeparators | Remove all the separators from ButtonPanel.
RemoveHelp | Removes the tooltips and statusbar help (if any) for a button.
RemoveText | Removes the main caption text.
RepaintOldSelection | Repaints the old selected/hovered button.
SetAlignment | Sets the buttons alignment.
SetBPArt | Sets a new BPArt art provider to ButtonPanel.
SetBarText | Sets the main caption text.
SetStyle | Sets the ButtonPanel window style.
SetUseHelp | Sets whether or not short and long help strings should be displayed as tooltips
SizeLayout | Layout the items when no main caption exists.

API Class API

class ButtonPanel(wx.PyPanel) [source]

A custom panel class with gradient background shading with the possibility to add buttons and controls still respecting the gradient background.

__init__(parent, id=wx.ID_ANY, text="", agwStyle=BP_DEFAULT_STYLE, alignment=BP_ALIGN_LEFT, name="buttonPanel") [source]

Default class constructor.

Parameters:
  • parent (wx.Window) – the parent window. Must not be None;
  • id (integer) – window identifier. If wx.ID_ANY, will automatically create an identifier;
  • text (string) – the main caption text for ButtonPanel;
  • agwStyle (integer) – the AGW-specific window style (one of BP_DEFAULT_STYLE, BP_USE_GRADIENT);
  • alignment (integer) – alignment of buttons (left or right);
  • name (string) – window class name.

AddButton(btnInfo) [source]

Adds a button to ButtonPanel.

Parameters: btnInfo – an instance of ButtonInfo.

Note

Remember to pass a ButtonInfo instance to this method, and not a standard wx.Button or a wx.ToolBar tool.

AddControl(control, proportion=0, flag=wx.ALIGN_CENTER|wx.ALL, border=None) [source]

Adds a wxPython control to ButtonPanel.

Parameters:
  • control – an instance of wx.Window;
  • proportion (integer) – the control proportion (0 for fixed-size, 1 or more for a stretchable one);
  • flag (integer) – one of the wx.BoxSizer flags;
  • border (integer) – the control border width (in pixels), if the flag parameter is set to include any border flag.

AddSeparator() [source]

Adds a separator line to ButtonPanel.

AddSpacer(size=(0, 0), proportion=1, flag=wx.EXPAND) [source]

Adds a spacer (stretchable or fixed-size) to ButtonPanel.

Parameters:
  • size (tuple) – the spacer size as a tuple;
  • proportion (integer) – the spacer proportion (0 for fixed-size, 1 or more for a stretchable one);
  • flag (integer) – one of the wx.BoxSizer flags.

Clear() [source]

Clears the ButtonPanel.

Can be used to reset the ButtonPanel if you’d like have a new set of buttons on the panel.

DoGetBestSize() [source]

Gets the size which best suits ButtonPanel: 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().

Returns: An instance of wx.Size.

Note

Overridden from wx.PyPanel.

DoGiveHelp(hit) [source]

Shows tooltips and long help strings in wx.StatusBar.

Parameters: hit – an instance of ButtonInfo where the mouse is hovering.

DoLayout() [source]

Do the Layout for ButtonPanel.

Note

Call this method every time you make a modification to the layout or to the customizable sizes of the pseudo controls.

FlexibleLayout(nonspacers, allchildren) [source]

Layout the items when the main caption exists.

Parameters:
  • nonspacers (list) – a list of items which are not spacers;
  • allchildren (list) – a list of all the children of ButtonPanel.

GetAlignment() [source]

Returns the buttons alignment.

Returns: An integer specifying the buttons alignment.

See also

SetAlignment for a set of valid alignment bits.

GetBPArt() [source]

Returns the associated BPArt art provider.

GetBarText() [source]

Returns the main caption text.

Returns: A string representing the caption text.

GetControls() [source]

Returns the wxPython controls that belongs to ButtonPanel.

Returns: A list of items inside ButtonPanel that are wxPython controls.

GetItemSize(item, isVertical) [source]

Returns the size of an item in the main ButtonPanel sizer.

Parameters:
  • item – an instance of ButtonInfo;
  • isVertical (bool) – True if ButtonPanel is in vertical orientation, False otherwise.
Returns:

An instance of wx.Size.

GetNonFlexibleChildren() [source]

Returns all the ButtonPanel main sizer’s children that are not flexible spacers.

Returns: A list of items inside ButtonPanel that are not flexible spacers.

GetStyle() [source]

Returns the ButtonPanel window style.

See also

SetStyle for a list of valid window styles.

GetUseHelp() [source]

Returns whether or not short and long help strings should be displayed as tooltips and wx.StatusBar items respectively.

Returns: True if the short and long help strings should be displayed as tooltips and wx.StatusBar items respectively, False otherwise.

HasBarText() [source]

Returns whether ButtonPanel has a main caption text or not.

Returns: True if ButtonPanel has a main caption text, False otherwise.

HitTest(pt) [source]

HitTest method for ButtonPanel.

Parameters: pt – the mouse position, an instance of wx.Point.
Returns: an instance of ButtonInfo and the hit flag BP_HT_BUTTON if a button client rectangle contains the input point pt, or wx.NOT_FOUND and BP_HT_NONE.

IsStandard() [source]

Returns whether ButtonPanel is aligned “Standard” (left/top) or not.

Returns: True if ButtonPanel is aligned “standard”, False otherwise.

IsVertical() [source]

Returns whether ButtonPanel is vertically aligned or not.

Returns: True if ButtonPanel is vertically aligned, False otherwise.

LayoutItems() [source]

Layout the items using a different algorithms depending on the existance of the main caption.

OnEraseBackground(event) [source]

Handles the wx.EVT_ERASE_BACKGROUND event for ButtonPanel.

Parameters: event – a wx.EraseEvent event to be processed.

Note

This is intentionally empty to reduce flicker.

OnLeftDown(event) [source]

Handles the wx.EVT_LEFT_DOWN event for ButtonPanel.

Parameters: event – a wx.MouseEvent event to be processed.

OnLeftUp(event) [source]

Handles the wx.EVT_LEFT_UP event for ButtonPanel.

Parameters: event – a wx.MouseEvent event to be processed.

OnMouseEnterWindow(event) [source]

Handles the wx.EVT_ENTER_WINDOW event for ButtonPanel.

Parameters: event – a wx.MouseEvent event to be processed.

OnMouseLeave(event) [source]

Handles the wx.EVT_LEAVE_WINDOW event for ButtonPanel.

Parameters: event – a wx.MouseEvent event to be processed.

OnMouseMove(event) [source]

Handles the wx.EVT_MOTION event for ButtonPanel.

Parameters: event – a wx.MouseEvent event to be processed.

OnPaint(event) [source]

Handles the wx.EVT_PAINT event for ButtonPanel.

Parameters: event – a wx.PaintEvent event to be processed.

OnSize(event) [source]

Handles the wx.EVT_SIZE event for ButtonPanel.

Parameters: event – a wx.SizeEvent event to be processed.

Todo

Improve the chain of methods OnSize ==> DoLayout ==> LayoutItems to avoid multiple calls to LayoutItems.

OnStatusBarTimer() [source]

Handles the timer expiring to delete the long help string in wx.StatusBar.

ReCreateSizer(text=None) [source]

Recreates the ButtonPanel sizer accordingly to the alignment specified.

Parameters: text (string) – the text to display as main caption. If text is set to None, the main caption will not be displayed.

RemoveAllButtons() [source]

Remove all the buttons from ButtonPanel.

Note

This function is for internal use only. If you are interested in manipulating a ButtonPanel in real time (ie. removing things on it) have a look at the Clear method.

RemoveAllSeparators() [source]

Remove all the separators from ButtonPanel.

Note

This function is for internal use only. If you are interested in manipulating a ButtonPanel in real time (ie. removing things on it) have a look at the Clear method.

RemoveHelp() [source]

Removes the tooltips and statusbar help (if any) for a button.

RemoveText() [source]

Removes the main caption text.

RepaintOldSelection() [source]

Repaints the old selected/hovered button.

SetAlignment(alignment) [source]

Sets the buttons alignment.

Parameters: alignment (integer) – can be one of the following bits:

integer parameter settings
Alignment Flag | Value | Description
BP_ALIGN_RIGHT | 1 | Buttons are aligned on the right
BP_ALIGN_LEFT | 2 | Buttons are aligned on the left
BP_ALIGN_TOP | 4 | Buttons are aligned at the top
BP_ALIGN_BOTTOM | 8 | Buttons are aligned at the bottom

SetBPArt(art) [source]

Sets a new BPArt art provider to ButtonPanel.

Parameters: art – an instance of BPArt.

SetBarText(text) [source]

Sets the main caption text.

Parameters: text (string) – the main caption text label. An empty string erases the main caption text.

SetStyle(agwStyle) [source]

Sets the ButtonPanel window style.

Parameters: agwStyle (integer) – one of the following bits:

integer parameter settings
Window Styles | Hex Value | Description
BP_DEFAULT_STYLE | 0x1 | ButtonPanel has a plain solid background.
BP_USE_GRADIENT | 0x2 | ButtonPanel has a gradient shading background.

SetUseHelp(useHelp=True) [source]

Sets whether or not short and long help strings should be displayed as tooltips and wx.StatusBar items respectively.

Parameters: useHelp (bool) – True to display short and long help strings as tooltips and wx.StatusBar items respectively, False otherwise.

SizeLayout(nonspacers, children) [source]

Layout the items when no main caption exists.

Parameters:
  • nonspacers (list) – a list of items which are not spacers;
  • children (list) – a list of all the children of ButtonPanel.

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • infobar
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • buttonpanel »
  • ButtonPanel


ButtonPanelText

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • buttonpanel »
  • ButtonPanelText

ButtonPanelText

This class is used to hold data about the main caption in ButtonPanel.

hierarchy Inheritance Diagram

Inheritance diagram for: ButtonPanelText

Inheritance diagram of ButtonPanelText

supclasses Known Superclasses

  • buttonpanel.Control

Methods Summary

__init__ | Default class constructor.
CreateDC | Convenience function to create a wx.DC.
Draw | Draws the main caption.
GetBestSize | Returns the best size for the main caption in ButtonPanel.
GetText | Returns the caption text.
SetText | Sets the caption text.

API Class API

class ButtonPanelText(Control) [source]

This class is used to hold data about the main caption in ButtonPanel.

__init__(parent, text='') [source]

Default class constructor.

Parameters:
  • parent – the text parent object, an instance of ButtonPanel;
  • text (string) – the actual main caption string.

CreateDC() [source]

Convenience function to create a wx.DC.

Draw(dc, rect) [source]

Draws the main caption. Actually the drawing is done in BPArt.

Parameters:
  • dc – an instance of wx.DC;

  • rect (wx.Rect) – the main caption text client rectangle.

GetBestSize() [source]

Returns the best size for the main caption in ButtonPanel.

Returns: An instance of wx.Size.

GetText() [source]

Returns the caption text.

Returns: A string representing the caption text.

SetText(text='') [source]

Sets the caption text.

Parameters: text (string) – the main caption string.

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • infobar
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • buttonpanel »
  • ButtonPanelText


Control

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • buttonpanel »
  • Control

Control

This class represents a base class for all pseudo controls used in ButtonPanel.

hierarchy Inheritance Diagram

Inheritance diagram for: Control

Inheritance diagram of Control

subclasses Known Subclasses

  • buttonpanel.ButtonInfo
  • buttonpanel.ButtonPanelText
  • buttonpanel.Separator

Methods Summary

__init__ | Default class constructor.
Disable | Disables the control.
Draw | Handles the drawing of the control.
Enable | Enable or disable the window for user input.
GetBestSize | This functions returns the best acceptable minimal size for the window.
GetId | Returns the identifier of the window.
HasFocus | Returns whether the control has the focus or not.
Hide | Hides the control.
IsShown | Returns True if the window is shown, False if it has been hidden.
OnMouseEvent | Handles the wx.EVT_MOUSE_EVENTS events for the control.
SetFocus | Sets or kills the focus on the control.
Show | Shows or hide the control.

API Class API

class Control(wx.EvtHandler) [source]

This class represents a base class for all pseudo controls used in ButtonPanel.

__init__(parent, size=wx.Size(-1, -1), id=wx.ID_ANY) [source]

Default class constructor.

Parameters:
  • parent (wx.Window) – the control parent object. Must not be None;
  • size (tuple or wx.Size) – the control size. A value of (-1, -1) indicates a default size, chosen by either the windowing system or wxPython, depending on platform;
  • id (integer) – window identifier. A value of -1 indicates a default value.

Disable() [source]

Disables the control.

Returns: True if the window has been disabled, False if it had been already disabled before the call to this function.

Note

This is functionally equivalent of calling Enable with a False flag.

Draw(rect) [source]

Handles the drawing of the control.

Parameters: rect (wx.Rect) – the control client rectangle.

Enable(value=True) [source]

Enable or disable the window for user input.

Parameters: enable (bool) – If True, enables the window for input. If False, disables the window.
Returns: True if the window has been enabled or disabled, False if nothing was done, i.e. if the window had already been in the specified state.

Note

Note that when a parent window is disabled, all of its children are disabled as well and they are reenabled again when the parent is.

GetBestSize() [source]

This functions returns the best acceptable minimal size for the window. For example, for a static control, it will be the minimal size such that the control label is not truncated. For windows containing subwindows (typically wx.Panel), the size returned by this function will be the same as the size the window would have had after calling Fit().

Returns: An instance of wx.Size.

GetId() [source]

Returns the identifier of the window.

Returns: An integer representing the identifier of the window.

Note

Each window has an integer identifier. If the application has not provided one (or the default wx.ID_ANY) an unique identifier with a negative value will be generated.

HasFocus() [source]

Returns whether the control has the focus or not.

Returns: True if the control has the focus, False otherwise.

Hide() [source]

Hides the control.

Note

This is functionally equivalent of calling Show with a False input.

IsShown() [source]

Returns True if the window is shown, False if it has been hidden.

OnMouseEvent(x, y, event) [source]

Handles the wx.EVT_MOUSE_EVENTS events for the control.

Parameters:
  • x (integer) – the mouse x position;
  • y (integer) – the mouse y position;
  • event – the wx.MouseEvent event to be processed.

SetFocus(focus=True) [source]

Sets or kills the focus on the control.

Parameters: focus (bool) – whether the control can receive keyboard inputs or not.

Show(show=True) [source]

Shows or hide the control.

Parameters: show (bool) – If True displays the window. Otherwise, it hides it.

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • infobar
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • buttonpanel »
  • Control


Separator

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • buttonpanel »
  • Separator

Separator

This class holds all the information to size and draw a separator inside ButtonPanel.

hierarchy Inheritance Diagram

Inheritance diagram for: Separator

Inheritance diagram of Separator

supclasses Known Superclasses

  • buttonpanel.Control

Methods Summary

__init__ | Default class constructor.
Draw | Draws the separator.
GetBestSize | Returns the separator best size.

API Class API

class Separator(Control) [source]

This class holds all the information to size and draw a separator inside ButtonPanel.

__init__(parent) [source]

Default class constructor.

Parameters: parent – the separator parent object, an instance of ButtonPanel.

Draw(dc, rect) [source]

Draws the separator. Actually the drawing is done in BPArt.

Parameters:
  • dc – an instance of wx.DC;
  • rect (wx.Rect) – the separator client rectangle.

GetBestSize() [source]

Returns the separator best size.

Returns: An instance of wx.Size.

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • infobar
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • buttonpanel »
  • Separator


Sizer

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • buttonpanel »
  • Sizer

Sizer

This is a mix-in class to add pseudo support to wx.Sizer. Just create a new class that derives from this class and wx.Sizer and intercepts any methods that add to the wx sizer.

hierarchy Inheritance Diagram

Inheritance diagram for: Sizer

Inheritance diagram of Sizer

subclasses Known Subclasses

  • buttonpanel.BoxSizer

Methods Summary

__init__ | Default class constructor.
Draw | Draws all the children of the sizer.
GetBestSize | This functions returns the best acceptable minimal size for the sizer object.

API Class API

class Sizer(object) [source]

This is a mix-in class to add pseudo support to wx.Sizer. Just create a new class that derives from this class and wx.Sizer and intercepts any methods that add to the wx sizer.

__init__() [source]

Default class constructor. For internal use: do not call it in your code!

Draw(dc, x1=0, y1=0, x2=0, y2=0) [source]

Draws all the children of the sizer.

GetBestSize() [source]

This functions returns the best acceptable minimal size for the sizer object.

Returns: An instance of wx.Size.

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • infobar
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • buttonpanel »
  • Sizer


StatusBarTimer

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • buttonpanel »
  • StatusBarTimer

StatusBarTimer

Timer used for deleting wx.StatusBar long help after _DELAY seconds.

hierarchy Inheritance Diagram

Inheritance diagram for: StatusBarTimer

Inheritance diagram of StatusBarTimer

Methods Summary

__init__ | Default class constructor.
Notify | The timer has expired.

API Class API

class StatusBarTimer(wx.Timer) [source]

Timer used for deleting wx.StatusBar long help after _DELAY seconds.

__init__(owner) [source]

Default class constructor. For internal use: do not call it in your code!

Parameters: owner – an instance of ButtonPanel.

Notify() [source]

The timer has expired.

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • infobar
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • buttonpanel »
  • StatusBarTimer


SVN Revision 68362 For buttonpanel

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • buttonpanel »
  • SVN Revision 68362 For buttonpanel

svn SVN Revision 68362 For buttonpanel

This file contains the SVN revision history for buttonpanel, at revision 68362.

Available information include commit date, the name of the committer, the file size, the SVN log messages and a diff from the previous version (if available).

File Information

  • Commit Date: 03-Jan-2009 02:26:57 UTC
  • Committer: AG
  • File Size: 91498 byte(s)

Log Messages

The following log message was entered by the committer:

  • All of AGW: change my work e-mail from KPO to Maersk Oil (silly commit)

Diff To Previous Version (66288)

Version SVN diff:

--- wxPython/3rdParty/AGW/agw/buttonpanel.py        2010/11/28 15:20:26     66288
+++ wxPython/3rdParty/AGW/agw/buttonpanel.py        2011/07/24 21:36:47     68362
@@ -18,7 +18,7 @@
# Write To Me At:
#
# andrea.gavana@gmail.com
-# gavana@kpo.kz
+# andrea.gavana@maerskoil.com
#
# Or, Obviously, To The wxPython Mailing List!!!
#

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • buttonpanel »
  • SVN Revision 68362 For buttonpanel


SVN Revision 68742 For buttonpanel

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • buttonpanel »
  • SVN Revision 68742 For buttonpanel

svn SVN Revision 68742 For buttonpanel

This file contains the SVN revision history for buttonpanel, at revision 68742.

Available information include commit date, the name of the committer, the file size, the SVN log messages and a diff from the previous version (if available).

File Information

  • Commit Date: 31-Dec-2008 05:45:16 UTC
  • Committer: AG
  • File Size: 91578 byte(s)

Log Messages

The following log message was entered by the committer:

  • FlatNotebook: fix issues with custom page and vertical/horizontal tiling of pages;
  • AuiBook: every time the AuiBook is split, copy over the custom buttons in the tab area of the newly created AuiBook;
  • Others: minor modifications to the docstrings.

Diff To Previous Version (68362)

Version SVN diff:

--- wxPython/3rdParty/AGW/agw/buttonpanel.py        2011/07/24 21:36:47     68362
+++ wxPython/3rdParty/AGW/agw/buttonpanel.py        2011/08/16 16:37:37     68742
@@ -11,7 +11,7 @@
# Python Code By:
#
# Andrea Gavana, @ 02 Oct 2006
-# Latest Revision: 28 Nov 2010, 16.00 GMT
+# Latest Revision: 11 Aug 2011, 23.00 GMT
#
#
# For All Kind Of Problems, Requests Of Enhancements And Bug Reports, Please
@@ -34,7 +34,7 @@
Description
===========

-With `ButtonPanel` class you have a panel with gradient colouring
+With L{ButtonPanel} class you have a panel with gradient colouring
on it and with the possibility to place some buttons on it. Using a
standard panel with normal `wx.Buttons` leads to an ugly result: the
buttons are placed correctly on the panel - but with grey area around
@@ -60,23 +60,23 @@
different meaning and behavior with respect to `wx.Toolbar`. The easiest
thing is to try the demo to understand, but I'll try to explain how it works.

-**CASE 1**: `ButtonPanel` has a main caption text.
+**CASE 1**: L{ButtonPanel} has a main caption text.

-- Left alignment means `ButtonPanel` is horizontal, with the text aligned to the
+- Left alignment means L{ButtonPanel} is horizontal, with the text aligned to the
left. When you shrink the demo frame, if there is not enough room for all
the controls to be shown, the controls closest to the text are hidden;

-- Right alignment means `ButtonPanel` is horizontal, with the text aligned to the
+- Right alignment means L{ButtonPanel} is horizontal, with the text aligned to the
right. Item layout as above;

-- Top alignment means `ButtonPanel` is vertical, with the text aligned to the top.
+- Top alignment means L{ButtonPanel} is vertical, with the text aligned to the top.
Item layout as above;

-- Bottom alignment means `ButtonPanel` is vertical, with the text aligned to the
+- Bottom alignment means L{ButtonPanel} is vertical, with the text aligned to the
bottom. Item layout as above.

-**CASE 2**: `ButtonPanel` has **no** main caption text.
+**CASE 2**: L{ButtonPanel} has **no** main caption text.

- In this case, left and right alignment are the same (as top and bottom are the same),
but the layout strategy changes: now if there is not enough room for all the controls
@@ -84,9 +84,12 @@
horizontal ButtonPanels and far bottom for vertical ButtonPanels).

-The following example shows a simple implementation that uses `ButtonPanel`
+The following example shows a simple implementation that uses L{ButtonPanel}
inside a very simple frame::

+  import wx
+  import wx.lib.agw.buttonpanel as BP
+
class MyFrame(wx.Frame):

def __init__(self, parent, id=-1, title="ButtonPanel", pos=wx.DefaultPosition,
@@ -102,21 +105,21 @@

alignment = BP_ALIGN_RIGHT

-          titleBar = ButtonPanel(mainPanel, -1, "A Simple Test & Demo")
+          titleBar = BP.ButtonPanel(mainPanel, -1, "A Simple Test & Demo")

-          btn1 = ButtonInfo(titleBar, wx.NewId(), wx.Bitmap("png4.png", wx.BITMAP_TYPE_PNG))
+          btn1 = BP.ButtonInfo(titleBar, wx.NewId(), wx.Bitmap("png4.png", wx.BITMAP_TYPE_PNG))
titleBar.AddButton(btn1)
self.Bind(wx.EVT_BUTTON, self.OnButton, btn1)

-          btn2 = ButtonInfo(titleBar, wx.NewId(), wx.Bitmap("png3.png", wx.BITMAP_TYPE_PNG))
+          btn2 = BP.ButtonInfo(titleBar, wx.NewId(), wx.Bitmap("png3.png", wx.BITMAP_TYPE_PNG))
titleBar.AddButton(btn2)
self.Bind(wx.EVT_BUTTON, self.OnButton, btn2)

-          btn3 = ButtonInfo(titleBar, wx.NewId(), wx.Bitmap("png2.png", wx.BITMAP_TYPE_PNG))
+          btn3 = BP.ButtonInfo(titleBar, wx.NewId(), wx.Bitmap("png2.png", wx.BITMAP_TYPE_PNG))
titleBar.AddButton(btn3)
self.Bind(wx.EVT_BUTTON, self.OnButton, btn3)

-          btn4 = ButtonInfo(titleBar, wx.NewId(), wx.Bitmap("png1.png", wx.BITMAP_TYPE_PNG))
+          btn4 = BP.ButtonInfo(titleBar, wx.NewId(), wx.Bitmap("png1.png", wx.BITMAP_TYPE_PNG))
titleBar.AddButton(btn4)
self.Bind(wx.EVT_BUTTON, self.OnButton, btn4)

@@ -146,8 +149,8 @@
==================== =========== ==================================================
Window Styles        Hex Value   Description
==================== =========== ==================================================
-``BP_DEFAULT_STYLE``         0x1 `ButtonPanel` has a plain solid background.
-``BP_USE_GRADIENT``          0x2 `ButtonPanel` has a gradient shading background.
+``BP_DEFAULT_STYLE``         0x1 L{ButtonPanel} has a plain solid background.
+``BP_USE_GRADIENT``          0x2 L{ButtonPanel} has a gradient shading background.
==================== =========== ==================================================

@@ -168,7 +171,7 @@

ButtonPanel is distributed under the wxPython license.

-Latest Revision: Andrea Gavana @ 28 Nov 2010, 16.00 GMT
+Latest Revision: Andrea Gavana @ 11 Aug 2011, 23.00 GMT

Version 0.6.

@@ -243,9 +246,9 @@

# ButtonPanel styles
BP_DEFAULT_STYLE = 1
-""" `ButtonPanel` has a plain solid background. """
+""" L{ButtonPanel} has a plain solid background. """
BP_USE_GRADIENT = 2
-""" `ButtonPanel` has a gradient shading background. """
+""" L{ButtonPanel} has a gradient shading background. """

# Delay used to cancel the longHelp in the statusbar field
_DELAY = 3000

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • buttonpanel »
  • SVN Revision 68742 For buttonpanel


SVN Revision 68881 For buttonpanel

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • buttonpanel »
  • SVN Revision 68881 For buttonpanel

svn SVN Revision 68881 For buttonpanel

This file contains the SVN revision history for buttonpanel, at revision 68881.

Available information include commit date, the name of the committer, the file size, the SVN log messages and a diff from the previous version (if available).

File Information

  • Commit Date: 20-Oct-2008 20:05:15 UTC
  • Committer: AG
  • File Size: 92150 byte(s)

Log Messages

The following log message was entered by the committer:

  • AGW: General overhaul of the documentation, much improved. All the widgets have their own sample usage in the docs as well;

  • FlatNotebook: Added the FNB_NAV_BUTTONS_WHEN_NEEDED style, which hides the navigation left/right arrows if all tabs fit;

  • RibbonBar: - Added the EVT_RIBBONBAR_TAB_LEFT_DCLICK event, which generates a special event

    when a ribbon bar tab is double-clicked;

    • Added support for toggle buttons;
    • Improved support for ribbon panel sizers: panels with sizers should now automatically minimise at small sizes, and behave properly when popping up from a minimised state;
    • Added tooltips via SetToolTip for those buttons which have the help_string attribute set.

  • XLSGrid: a new widget was added to AGW, termed XLSGrid. It’s based on wx.grid.Grid and can be used to faithfully reproduce the appearance of a Microsoft Excel spreadsheets.

Diff To Previous Version (68742)

Version SVN diff:

--- wxPython/3rdParty/AGW/agw/buttonpanel.py        2011/08/16 16:37:37     68742
+++ wxPython/3rdParty/AGW/agw/buttonpanel.py        2011/08/25 16:40:17     68881
@@ -1,5 +1,5 @@
# --------------------------------------------------------------------------- #
-# FANCYBUTTONPANEL Widget wxPython IMPLEMENTATION
+# BUTTONPANEL Widget wxPython IMPLEMENTATION
#
# Original C++ Code From Eran. You Can Find It At:
#
@@ -11,7 +11,7 @@
# Python Code By:
#
# Andrea Gavana, @ 02 Oct 2006
-# Latest Revision: 11 Aug 2011, 23.00 GMT
+# Latest Revision: 17 Aug 2011, 15.00 GMT
#
#
# For All Kind Of Problems, Requests Of Enhancements And Bug Reports, Please
@@ -56,7 +56,7 @@
Usage
=====

-ButtonPanel supports 4 alignments: left, right, top, bottom, which have a
+L{ButtonPanel} supports 4 alignments: left, right, top, bottom, which have a
different meaning and behavior with respect to `wx.Toolbar`. The easiest
thing is to try the demo to understand, but I'll try to explain how it works.

@@ -80,12 +80,11 @@

- In this case, left and right alignment are the same (as top and bottom are the same),
but the layout strategy changes: now if there is not enough room for all the controls
-  to be shown, the last added items are hidden ("last" means on the far right for
-  horizontal ButtonPanels and far bottom for vertical ButtonPanels).
+  to be shown, the last added items are hidden ("last" means on the far right for an
+  horizontal L{ButtonPanel} and far bottom for a vertical L{ButtonPanel}).

-The following example shows a simple implementation that uses L{ButtonPanel}
-inside a very simple frame::
+Usage example::

import wx
import wx.lib.agw.buttonpanel as BP
@@ -103,8 +102,6 @@
vSizer = wx.BoxSizer(wx.VERTICAL)
mainPanel.SetSizer(vSizer)

-          alignment = BP_ALIGN_RIGHT
-
titleBar = BP.ButtonPanel(mainPanel, -1, "A Simple Test & Demo")

btn1 = BP.ButtonInfo(titleBar, wx.NewId(), wx.Bitmap("png4.png", wx.BITMAP_TYPE_PNG))
@@ -129,6 +126,16 @@

titleBar.DoLayout()
vSizer.Layout()
+
+
+      def OnButton(self, event):
+          ''' Handler for the ``wx.EVT_BUTTON`` event. '''
+
+          obj = event.GetEventObject()
+
+          # This will print the button label
+          print obj.GetText()
+

# our normal wxApp-derived class, as usual

@@ -169,9 +176,9 @@
License And Version
===================

-ButtonPanel is distributed under the wxPython license.
+L{ButtonPanel} is distributed under the wxPython license.

-Latest Revision: Andrea Gavana @ 11 Aug 2011, 23.00 GMT
+Latest Revision: Andrea Gavana @ 17 Aug 2011, 15.00 GMT

Version 0.6.

@@ -184,13 +191,13 @@
BP_BACKGROUND_COLOUR = 0
""" Background brush colour when no gradient shading exists. """
BP_GRADIENT_COLOUR_FROM = 1
-""" Starting gradient colour, used only when BP_USE_GRADIENT style is applied. """
+""" Starting gradient colour, used only when ``BP_USE_GRADIENT`` style is applied. """
BP_GRADIENT_COLOUR_TO = 2
-""" Ending gradient colour, used only when BP_USE_GRADIENT style is applied. """
+""" Ending gradient colour, used only when ``BP_USE_GRADIENT`` style is applied. """
BP_BORDER_COLOUR = 3
-""" Pen colour to paint the border of ButtonPanel. """
+""" Pen colour to paint the border of L{ButtonPanel}. """
BP_TEXT_COLOUR = 4
-""" Main ButtonPanel caption colour. """
+""" Main L{ButtonPanel} caption colour. """
BP_BUTTONTEXT_COLOUR = 5
""" Text colour for buttons with text. """
BP_BUTTONTEXT_INACTIVE_COLOUR = 6
@@ -202,7 +209,7 @@
BP_SEPARATOR_COLOUR = 9
""" Pen colour used to paint the separators. """
BP_TEXT_FONT = 10
-""" Font of the ButtonPanel main caption. """
+""" Font of the L{ButtonPanel} main caption. """
BP_BUTTONTEXT_FONT = 11
""" Text font for the buttons with text. """

@@ -212,15 +219,9 @@
""" Flag that indicates the text is shown alongside the image in buttons with text. """

BP_SEPARATOR_SIZE = 14
-"""
-Separator size. NB: This is not the line width, but the sum of the space before
-and after the separator line plus the width of the line.
-"""
+""" Separator size. NB: This is not the line width, but the sum of the space before and after the separator line plus the width of the line. """
BP_MARGINS_SIZE = 15
-"""
-Size of the left/right margins in ButtonPanel (top/bottom for vertically
-aligned ButtonPanels).
-"""
+""" Size of the left/right margins in L{ButtonPanel} (top/bottom for vertically aligned L{ButtonPanel})."""
BP_BORDER_SIZE = 16
""" Size of the border. """
BP_PADDING_SIZE = 17
@@ -236,13 +237,19 @@

# Flags for HitTest() method
BP_HT_BUTTON = 200
+""" This flag indicates that the user has hit a button inside L{ButtonPanel}. """
BP_HT_NONE = 201
+""" This flag indicates that no buttons were hit inside L{ButtonPanel}. """

# Alignment of buttons in the panel
BP_ALIGN_RIGHT = 1
+""" Aligns the buttons to the right (for an horizontal L{ButtonPanel}). """
BP_ALIGN_LEFT = 2
+""" Aligns the buttons to the left (for an horizontal L{ButtonPanel}). """
BP_ALIGN_TOP = 4
+""" Aligns the buttons at the top (for a vertical L{ButtonPanel}). """
BP_ALIGN_BOTTOM = 8
+""" Aligns the buttons at the bottom (for a vertical L{ButtonPanel}). """

# ButtonPanel styles
BP_DEFAULT_STYLE = 1
@@ -367,7 +374,7 @@
Size Id                         Value  Description
============================== ======= =====================================
``BP_SEPARATOR_SIZE``               14 Separator size. Note: This is not the line width, but the sum of the space before and after the separator line plus the width of the line
-         ``BP_MARGINS_SIZE``                 15 Size of the left/right margins in L{ButtonPanel} (top/bottom for vertically aligned ButtonPanels)
+         ``BP_MARGINS_SIZE``                 15 Size of the left/right margins in L{ButtonPanel} (top/bottom for vertically aligned L{ButtonPanel})
``BP_BORDER_SIZE``                  16 Size of the border
``BP_PADDING_SIZE``                 17 Inter-tool separator size
============================== ======= =====================================
@@ -423,7 +430,7 @@
``BP_GRADIENT_COLOUR_FROM``              1 Starting gradient colour, used only when ``BP_USE_GRADIENT`` style is applied
``BP_GRADIENT_COLOUR_TO``                2 Ending gradient colour, used only when ``BP_USE_GRADIENT`` style is applied
``BP_BORDER_COLOUR``                     3 Pen colour to paint the border of L{ButtonPanel}
-         ``BP_TEXT_COLOUR``                       4 Main ButtonPanel caption colour
+         ``BP_TEXT_COLOUR``                       4 Main L{ButtonPanel} caption colour
``BP_BUTTONTEXT_COLOUR``                 5 Text colour for buttons with text
``BP_BUTTONTEXT_INACTIVE_COLOUR``        6 Text colour for inactive buttons with text
``BP_SELECTION_BRUSH_COLOUR``            7 Brush colour to be used when hovering or selecting a button

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • buttonpanel »
  • SVN Revision 68881 For buttonpanel


SVN Revision 68933 For buttonpanel

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • buttonpanel »
  • SVN Revision 68933 For buttonpanel

svn SVN Revision 68933 For buttonpanel

This file contains the SVN revision history for buttonpanel, at revision 68933.

Available information include commit date, the name of the committer, the file size, the SVN log messages and a diff from the previous version (if available).

File Information

  • Commit Date: 17-Oct-2008 20:51:43 UTC
  • Committer: AG
  • File Size: 92221 byte(s)

Log Messages

The following log message was entered by the committer:

AGW: Some further refactoring of the docs: - Added downloadable snippets of code in the Sphinx documentation itself; - Re-run 2to3 afresh so that the patches are up-to-date for Python 3.

Diff To Previous Version (68881)

Version SVN diff:

--- wxPython/3rdParty/AGW/agw/buttonpanel.py        2011/08/25 16:40:17     68881
+++ wxPython/3rdParty/AGW/agw/buttonpanel.py        2011/08/27 17:11:41     68933
@@ -86,66 +86,67 @@

Usage example::

-  import wx
-  import wx.lib.agw.buttonpanel as BP
-
-  class MyFrame(wx.Frame):
+    import wx
+    import wx.lib.agw.buttonpanel as BP

-      def __init__(self, parent, id=-1, title="ButtonPanel", pos=wx.DefaultPosition,
-                   size=(800, 600), style=wx.DEFAULT_FRAME_STYLE):
+    class MyFrame(wx.Frame):
+
+        def __init__(self, parent, id=-1, title="ButtonPanel", pos=wx.DefaultPosition,
+                     size=(800, 600), style=wx.DEFAULT_FRAME_STYLE):

-          wx.Frame.__init__(self, parent, id, title, pos, size, style)
+            wx.Frame.__init__(self, parent, id, title, pos, size, style)
+
+            mainPanel = wx.Panel(self, -1)
+            self.logtext = wx.TextCtrl(mainPanel, -1, "", style=wx.TE_MULTILINE)
+
+            vSizer = wx.BoxSizer(wx.VERTICAL)
+            mainPanel.SetSizer(vSizer)
+
+            titleBar = BP.ButtonPanel(mainPanel, -1, "A Simple Test & Demo")
+
+            btn1 = BP.ButtonInfo(titleBar, wx.NewId(), wx.Bitmap("png4.png", wx.BITMAP_TYPE_PNG))
+            titleBar.AddButton(btn1)
+            self.Bind(wx.EVT_BUTTON, self.OnButton, btn1)

-          mainPanel = wx.Panel(self, -1)
-          self.logtext = wx.TextCtrl(mainPanel, -1, "", style=wx.TE_MULTILINE)
+            btn2 = BP.ButtonInfo(titleBar, wx.NewId(), wx.Bitmap("png3.png", wx.BITMAP_TYPE_PNG))
+            titleBar.AddButton(btn2)
+            self.Bind(wx.EVT_BUTTON, self.OnButton, btn2)

-          vSizer = wx.BoxSizer(wx.VERTICAL)
-          mainPanel.SetSizer(vSizer)
+            btn3 = BP.ButtonInfo(titleBar, wx.NewId(), wx.Bitmap("png2.png", wx.BITMAP_TYPE_PNG))
+            titleBar.AddButton(btn3)
+            self.Bind(wx.EVT_BUTTON, self.OnButton, btn3)

-          titleBar = BP.ButtonPanel(mainPanel, -1, "A Simple Test & Demo")
+            btn4 = BP.ButtonInfo(titleBar, wx.NewId(), wx.Bitmap("png1.png", wx.BITMAP_TYPE_PNG))
+            titleBar.AddButton(btn4)
+            self.Bind(wx.EVT_BUTTON, self.OnButton, btn4)

-          btn1 = BP.ButtonInfo(titleBar, wx.NewId(), wx.Bitmap("png4.png", wx.BITMAP_TYPE_PNG))
-          titleBar.AddButton(btn1)
-          self.Bind(wx.EVT_BUTTON, self.OnButton, btn1)
+            vSizer.Add(titleBar, 0, wx.EXPAND)
+            vSizer.Add((20, 20))
+            vSizer.Add(self.logtext, 1, wx.EXPAND|wx.ALL, 5)

-          btn2 = BP.ButtonInfo(titleBar, wx.NewId(), wx.Bitmap("png3.png", wx.BITMAP_TYPE_PNG))
-          titleBar.AddButton(btn2)
-          self.Bind(wx.EVT_BUTTON, self.OnButton, btn2)
+            titleBar.DoLayout()
+            vSizer.Layout()

-          btn3 = BP.ButtonInfo(titleBar, wx.NewId(), wx.Bitmap("png2.png", wx.BITMAP_TYPE_PNG))
-          titleBar.AddButton(btn3)
-          self.Bind(wx.EVT_BUTTON, self.OnButton, btn3)

-          btn4 = BP.ButtonInfo(titleBar, wx.NewId(), wx.Bitmap("png1.png", wx.BITMAP_TYPE_PNG))
-          titleBar.AddButton(btn4)
-          self.Bind(wx.EVT_BUTTON, self.OnButton, btn4)
+        def OnButton(self, event):
+            ''' Handler for the ``wx.EVT_BUTTON`` event. '''

-          vSizer.Add(titleBar, 0, wx.EXPAND)
-          vSizer.Add((20, 20))
-          vSizer.Add(self.logtext, 1, wx.EXPAND|wx.ALL, 5)
+            obj = event.GetEventObject()

-          titleBar.DoLayout()
-          vSizer.Layout()
+            # This will print the button label
+            print obj.GetText()

-      def OnButton(self, event):
-          ''' Handler for the ``wx.EVT_BUTTON`` event. '''
+    # our normal wxApp-derived class, as usual

-          obj = event.GetEventObject()
+    app = wx.PySimpleApp()

-          # This will print the button label
-          print obj.GetText()
+    frame = MyFrame(None)
+    app.SetTopWindow(frame)
+    frame.Show()

-
-  # our normal wxApp-derived class, as usual
+    app.MainLoop()

-  app = wx.PySimpleApp()
-
-  frame = MyFrame(None)
-  app.SetTopWindow(frame)
-  frame.Show()
-
-  app.MainLoop()

Window Styles

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • buttonpanel »
  • SVN Revision 68933 For buttonpanel


SVN Revision 69086 For buttonpanel

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • buttonpanel »
  • SVN Revision 69086 For buttonpanel

svn SVN Revision 69086 For buttonpanel

This file contains the SVN revision history for buttonpanel, at revision 69086.

Available information include commit date, the name of the committer, the file size, the SVN log messages and a diff from the previous version (if available).

File Information

  • Commit Date: 17-Oct-2008 19:15:31 UTC
  • Committer: AG
  • File Size: 96342 byte(s)

Log Messages

The following log message was entered by the committer:

  • Fixed bug #13437 for SuperToolTip;
  • Fixed bug #13477 for UltimateListCtrl.

Diff To Previous Version (68933)

Version SVN diff:

--- wxPython/3rdParty/AGW/agw/buttonpanel.py        2011/08/27 17:11:41     68933
+++ wxPython/3rdParty/AGW/agw/buttonpanel.py        2011/09/14 19:39:08     69086
@@ -272,7 +272,9 @@
Brighten the input colour by a factor.

:param `colour`: a valid `wx.Colour` instance;
-    :param `factor`: the factor by which the input colour should be brightened.
+    :param integer `factor`: the factor by which the input colour should be brightened.
+
+    :return: An instance of `wx.Colour`, a brightened version of the input `colour`.
"""

val = colour.Red()*factor
@@ -303,6 +305,8 @@
Creates a disabled-looking bitmap starting from the input one.

:param `original`: an instance of `wx.Bitmap` to be greyed-out.
+
+    :return: A greyed-out representation of the input bitmap, an instance of `wx.Bitmap`.
"""

img = original.ConvertToImage()
@@ -326,7 +330,7 @@
"""
Default class constructor.

-        :param `parentStyle`: the window style for L{ButtonPanel}.
+        :param integer `parentStyle`: the window style for L{ButtonPanel}.
"""

base_colour = wx.SystemSettings_GetColour(wx.SYS_COLOUR_3DFACE)
@@ -368,7 +372,7 @@
"""
Returns the option value for the specified size `id`.

-        :param `id`: the identification bit for the size value. This can be one of the
+        :param integer `id`: the identification bit for the size value. This can be one of the
following bits:

============================== ======= =====================================
@@ -380,6 +384,9 @@
``BP_PADDING_SIZE``                 17 Inter-tool separator size
============================== ======= =====================================

+        :return: An integer representing the option value for the input `id`.
+
+        :raise: `Exception` if the `id` is not recognized.
"""

if id == BP_SEPARATOR_SIZE:
@@ -398,8 +405,10 @@
"""
Sets the option value for the specified size `id`.

-        :param `id`: the identification bit for the size value;
-        :param `new_val`: the new value for the size.
+        :param integer `id`: the identification bit for the size value;
+        :param input`new_val`: the new value for the size.
+
+        :raise: `Exception` if the `id` is not recognized.

:see: L{GetMetric} for a list of meaningful size ids.
"""
@@ -421,7 +430,7 @@
"""
Returns the option value for the specified colour `id`.

-        :param `id`: the identification bit for the colour value. This can be one of the
+        :param internal`id`: the identification bit for the colour value. This can be one of the
following bits:

================================== ======= =====================================
@@ -439,6 +448,9 @@
``BP_SEPARATOR_COLOUR``                  9 Pen colour used to paint the separators
================================== ======= =====================================

+        :return: An instance of `wx.Colour` for the input `id`.
+
+        :raise: `Exception` if the `id` is not recognized.
"""

if id == BP_BACKGROUND_COLOUR:
@@ -469,9 +481,11 @@
"""
Sets the option value for the specified colour `id`.

-        :param `id`: the identification bit for the colour value;
+        :param integer `id`: the identification bit for the colour value;
:param `colour`: the new value for the colour (a valid `wx.Colour` instance).

+        :raise: `Exception` if the `id` is not recognized.
+
:see: L{GetColour} for a list of meaningful colour ids.
"""

@@ -507,7 +521,7 @@
"""
Returns the option value for the specified font `id`.

-        :param `id`: the identification bit for the font value. This can be one of the
+        :param integer `id`: the identification bit for the font value. This can be one of the
following bits:

============================== ======= =====================================
@@ -516,7 +530,10 @@
``BP_TEXT_FONT``                    10 Font of the L{ButtonPanel} main caption
``BP_BUTTONTEXT_FONT``              11 Text font for the buttons with text
============================== ======= =====================================
-
+
+        :return: An instance of `wx.Font` for the input `id`.
+
+        :raise: `Exception` if the `id` is not recognized.
"""

if id == BP_TEXT_FONT:
@@ -531,9 +548,11 @@
"""
Sets the option value for the specified font `id`.

-        :param `id`: the identification bit for the font value;
+        :param integer `id`: the identification bit for the font value;
:param `colour`: the new value for the font (a valid `wx.Font` instance).

+        :raise: `Exception` if the `id` is not recognized.
+
:see: L{GetFont} for a list of meaningful font ids.
"""

@@ -547,7 +566,7 @@
"""
Sets the gradient type for L{BPArt} drawings.

-        :param `gradient`: can be one of the following bits:
+        :param integer `gradient`: can be one of the following bits:

============================ ======= ============================
Gradient Type                 Value  Description
@@ -566,6 +585,8 @@
"""
Returns the gradient type for L{BPArt} drawings.

+        :return: An integer representing the gradient type.
+
:see: L{SetGradientType} for a list of possible gradient types.
"""

@@ -577,8 +598,8 @@
Draws a separator in L{ButtonPanel}.

:param `dc`: an instance of `wx.DC`;
-        :param `rect`: the separator client rectangle;
-        :param `isVertical`: ``True`` if L{ButtonPanel} is in vertical orientation,
+        :param `wx.Rect` `rect`: the separator client rectangle;
+        :param bool `isVertical`: ``True`` if L{ButtonPanel} is in vertical orientation,
``False`` otherwise.
"""

@@ -601,8 +622,8 @@
Draws the main caption text in L{ButtonPanel}.

:param `dc`: an instance of `wx.DC`;
-        :param `rect`: the main caption text rectangle;
-        :param `captionText`: the caption text string.
+        :param `wx.Rect` `rect`: the main caption text rectangle;
+        :param string `captionText`: the caption text string.
"""

textColour = self._caption_text_colour
@@ -621,14 +642,14 @@
Draws a button in L{ButtonPanel}, together with its text (if any).

:param `dc`: an instance of `wx.DC`;
-        :param `rect`: the button client rectangle;
-        :param `buttonBitmap`: the bitmap associated with the button;
-        :param `isVertical`: ``True`` if L{ButtonPanel} is in vertical orientation,
+        :param `wx.Rect` `rect`: the button client rectangle;
+        :param `wx.Bitmap` `buttonBitmap`: the bitmap associated with the button;
+        :param bool `isVertical`: ``True`` if L{ButtonPanel} is in vertical orientation,
``False`` otherwise;
-        :param `buttonStatus`: one of "Normal", "Toggled", "Pressed", "Disabled" or "Hover";
-        :param `isToggled`: whether the button is toggled or not;
-        :param `textAlignment`: the text alignment inside the button;
-        :param `text`: the button label.
+        :param string `buttonStatus`: one of "Normal", "Toggled", "Pressed", "Disabled" or "Hover";
+        :param bool `isToggled`: whether the button is toggled or not;
+        :param integer `textAlignment`: the text alignment inside the button;
+        :param string `text`: the button label.
"""

bmpxsize, bmpysize = buttonBitmap.GetWidth(), buttonBitmap.GetHeight()
@@ -712,10 +733,10 @@
Draws the label for a button.

:param `dc`: an instance of `wx.DC`;
-        :param `text`: the button label;
-        :param `isEnabled`: ``True`` if the button is enabled, ``False`` otherwise;
-        :param `xpos`: the text x position inside the button;
-        :param `ypos`: the text y position inside the button.
+        :param string `text`: the button label;
+        :param bool `isEnabled`: ``True`` if the button is enabled, ``False`` otherwise;
+        :param integer `xpos`: the text `x` position inside the button;
+        :param integer `ypos`: the text `y` position inside the button.
"""

if not isEnabled:
@@ -731,8 +752,8 @@
Paint the L{ButtonPanel}'s background.

:param `dc`: an instance of `wx.DC`;
-        :param `rect`: the L{ButtonPanel} client rectangle;
-        :param `style`: the L{ButtonPanel} window style.
+        :param `wx.Rect` `rect`: the L{ButtonPanel} client rectangle;
+        :param integer `style`: the L{ButtonPanel} window style.
"""

if style & BP_USE_GRADIENT:
@@ -753,7 +774,7 @@
Gradient fill from colour 1 to colour 2 with top to bottom or left to right.

:param `dc`: an instance of `wx.DC`;
-        :param `rect`: the L{ButtonPanel} client rectangle.
+        :param `wx.Rect` `rect`: the L{ButtonPanel} client rectangle.
"""

if rect.height < 1 or rect.width < 1:
@@ -795,6 +816,8 @@
"""
Default class constructor.
For internal use: do not call it in your code!
+
+        :param `owner`: an instance of L{ButtonPanel}.
"""

wx.Timer.__init__(self)
@@ -817,11 +840,11 @@
"""
Default class constructor.

-        :param `parent`: the control parent object;
-        :param `size`: the control 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.
+        :param `wx.Window` `parent`: the control parent object. Must not be ``None``;
+        :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 `wx.Size`
+        :param integer `id`: window identifier. A value of -1 indicates a default value.
"""

wx.EvtHandler.__init__(self)
@@ -842,7 +865,7 @@
"""
Shows or hide the control.

-        :param `show`: If ``True`` displays the window. Otherwise, it hides it.
+        :param bool `show`: If ``True`` displays the window. Otherwise, it hides it.
"""

self._isshown = show
@@ -868,6 +891,8 @@
"""
Returns the identifier of the window.

+        :return: An integer representing the identifier of the window.
+
:note: Each window has an integer identifier. If the application has not provided
one (or the default ``wx.ID_ANY``) an unique identifier with a negative value will
be generated.
@@ -883,6 +908,8 @@
label is not truncated. For windows containing subwindows (typically `wx.Panel`),
the size returned by this function will be the same as the size the window would
have had after calling `Fit()`.
+
+        :return: An instance of `wx.Size`.
"""

return self._size
@@ -905,7 +932,7 @@
"""
Enable or disable the window for user input.

-        :param `enable`: If ``True``, enables the window for input. If ``False``, disables the window.
+        :param bool `enable`: If ``True``, enables the window for input. If ``False``, disables the window.

:returns: ``True`` if the window has been enabled or disabled, ``False`` if nothing was
done, i.e. if the window had already been in the specified state.
@@ -922,14 +949,18 @@
"""
Sets or kills the focus on the control.

-        :param `focus`: whether the control can receive keyboard inputs or not.
+        :param bool `focus`: whether the control can receive keyboard inputs or not.
"""

self._focus = focus

def HasFocus(self):
-        """ Returns whether the control has the focus or not. """
+        """
+        Returns whether the control has the focus or not.
+
+        :return: ``True`` if the control has the focus, ``False`` otherwise.
+        """

return self._focus

@@ -938,8 +969,8 @@
"""
Handles the ``wx.EVT_MOUSE_EVENTS`` events for the control.

-        :param `x`: the mouse x position;
-        :param `y`: the mouse y position;
+        :param integer `x`: the mouse `x` position;
+        :param integer `y`: the mouse `y` position;
:param `event`: the `wx.MouseEvent` event to be processed.
"""

@@ -950,7 +981,7 @@
"""
Handles the drawing of the control.

-        :param `rect`: the control client rectangle.
+        :param `wx.Rect` `rect`: the control client rectangle.
"""

pass
@@ -986,6 +1017,8 @@
def GetBestSize(self):
"""
This functions returns the best acceptable minimal size for the sizer object.
+
+        :return: An instance of `wx.Size`.
"""

# this should be handled by the wx.Sizer based class
@@ -1000,7 +1033,7 @@
"""
Constructor for L{BoxSizer}.

-        :param `orient`: may be one of ``wx.VERTICAL`` or ``wx.HORIZONTAL`` for creating
+        :param integer `orient`: may be one of ``wx.VERTICAL`` or ``wx.HORIZONTAL`` for creating
either a column sizer or a row sizer.
"""

@@ -1018,14 +1051,14 @@

:param `item`: the item to be added to L{BoxSizer}. Can be an instance of `wx.Window`,
`wx.Sizer` or a spacer;
-        :param `proportion`: this parameter is used in L{BoxSizer} to indicate if a child of
+        :param integer `proportion`: this parameter is used in L{BoxSizer} to indicate if a child of
a sizer can change its size in the main orientation of the L{BoxSizer} - where 0
stands for not changeable and a value of more than zero is interpreted relative
to the value of other children of the same L{BoxSizer}. For example, you might have
a horizontal L{BoxSizer} with three children, two of which are supposed to change their
size with the sizer. Then the two stretchable windows would get a value of 1 each to
make them grow and shrink equally with the sizer's horizontal dimension.
-        :param `flag`: this parameter can be used to set a number of flags which can be combined using the binary OR operator ``|``.
+        :param integer `flag`: this parameter can be used to set a number of flags which can be combined using the binary OR operator ``|``.
Two main behaviours are defined using these flags. One is the border around a window: the border parameter determines the border
width whereas the flags given here determine which side(s) of the item that the border will be added. The other flags determine
how the sizer item behaves when the space allotted to the sizer changes, and is somewhat dependent on the specific kind of sizer used:
@@ -1050,7 +1083,7 @@
|                                                                     | maintaining its aspect ratio                                                |
+---------------------------------------------------------------------+-----------------------------------------------------------------------------+
| ``wx.FIXED_MINSIZE``                                                | Normally `wx.Sizers` will use                                               |
-         |                                                                     | `wx.Window.GetAdjustedBestSize` to                                          |
+         |                                                                     | ``wx.Window.GetAdjustedBestSize`` to                                        |
|                                                                     | determine what the minimal size of window items should be, and will use that|
|                                                                     | size to calculate the layout. This allows layouts to adjust when an item    |
|                                                                     | changes and its best size becomes different. If you would rather have a     |
@@ -1077,9 +1110,9 @@
| ``wx.ALIGN_CENTER_HORIZONTAL`` **or** ``wx.ALIGN_CENTRE_HORIZONTAL``|                                                                             |
+---------------------------------------------------------------------+-----------------------------------------------------------------------------+

-        :param `border`: determines the border width, if the flag parameter is set
+        :param integer `border`: determines the border width, if the flag parameter is set
to include any border flag.
-        :param `userData`: Allows an extra object to be attached to the sizer item,
+        :param object `userData`: Allows an extra object to be attached to the sizer item,
for use in derived classes when sizing information is more complex than the
proportion and flag will allow for.

@@ -1152,8 +1185,8 @@
L{BoxSizer.Layout} to update the layout on screen after removing a child from
the sizer.

-        :param `indx`: the zero-based index of an item to remove;
-        :param `pop`: whether to remove the sizer item from the list of children.
+        :param integer `indx`: the zero-based index of an item to remove;
+        :param bool `pop`: whether to remove the sizer item from the list of children.
"""

if pop >= 0:
@@ -1182,7 +1215,7 @@
Shows or hides the sizer item.

:param `item`: the sizer item we want to show/hide;
-        :param `show`: ``True`` to show the item, ``False`` to hide it.
+        :param bool `show`: ``True`` to show the item, ``False`` to hide it.
"""

child = self.GetChildren()[item]
@@ -1208,7 +1241,7 @@
"""
Default class constructor.

-        :param `parent`: the separator parent object.
+        :param `parent`: the separator parent object, an instance of L{ButtonPanel}.
"""

self._isshown = True
@@ -1217,7 +1250,11 @@

def GetBestSize(self):
-        """ Returns the separator best size. """
+        """
+        Returns the separator best size.
+
+        :return: An instance of `wx.Size`.
+        """

# 10 is completely arbitrary, but it works anyhow
if self._parent.IsVertical():
@@ -1231,7 +1268,7 @@
Draws the separator. Actually the drawing is done in L{BPArt}.

:param `dc`: an instance of `wx.DC`;
-        :param `rect`: the separator client rectangle.
+        :param `wx.Rect` `rect`: the separator client rectangle.
"""

if not self.IsShown():
@@ -1253,8 +1290,8 @@
"""
Default class constructor.

-        :param `parent`: the text parent object;
-        :param `text`: the actual main caption string.
+        :param `parent`: the text parent object, an instance of L{ButtonPanel};
+        :param string `text`: the actual main caption string.
"""

self._text = text
@@ -1265,7 +1302,11 @@

def GetText(self):
-        """ Returns the caption text. """
+        """
+        Returns the caption text.
+
+        :return: A string representing the caption text.
+        """

return self._text

@@ -1274,7 +1315,7 @@
"""
Sets the caption text.

-        :param `text`: the main caption string.
+        :param string `text`: the main caption string.
"""

self._text = text
@@ -1291,7 +1332,11 @@

def GetBestSize(self):
-        """ Returns the best size for the main caption in L{ButtonPanel}. """
+        """
+        Returns the best size for the main caption in L{ButtonPanel}.
+
+        :return: An instance of `wx.Size`.
+        """

if self._text == "":
return wx.Size(0, 0)
@@ -1311,7 +1356,7 @@
Draws the main caption. Actually the drawing is done in L{BPArt}.

:param `dc`: an instance of `wx.DC`;
-        :param `rect`: the main caption text client rectangle.
+        :param `wx.Rect` `rect`: the main caption text client rectangle.
"""

if not self.IsShown():
@@ -1339,14 +1384,14 @@
Default class constructor.

:param `parent`: the parent window (L{ButtonPanel});
-        :param `id`: the button id;
-        :param `bmp`: the associated bitmap;
-        :param `status`: button status ("Pressed", "Hover", "Normal", "Toggled", "Disabled");
-        :param `text`: text to be displayed either below of to the right of the button;
-        :param `kind`: button kind, may be ``wx.ITEM_NORMAL`` for standard buttons or
+        :param integer `id`: the button id;
+        :param `wx.Bitmap` `bmp`: the associated bitmap;
+        :param string `status`: button status ("Pressed", "Hover", "Normal", "Toggled", "Disabled");
+        :param string `text`: text to be displayed either below of to the right of the button;
+        :param integer `kind`: button kind, may be ``wx.ITEM_NORMAL`` for standard buttons or
``wx.ITEM_CHECK`` for toggle buttons;
-        :param `shortHelp`: a short help to be shown in the button tooltip;
-        :param `longHelp`: this string is shown in the statusbar (if any) of the parent
+        :param string `shortHelp`: a short help to be shown in the button tooltip;
+        :param string `longHelp`: this string is shown in the statusbar (if any) of the parent
frame when the mouse pointer is inside the button.
"""

@@ -1374,7 +1419,11 @@

def GetBestSize(self):
-        """ Returns the best size for the button. """
+        """
+        Returns the best size for the button.
+
+        :return: An instance of `wx.Size`.
+        """

xsize = self.GetBitmap().GetWidth()
ysize = self.GetBitmap().GetHeight()
@@ -1411,7 +1460,7 @@
Draws the button on L{ButtonPanel}. Actually the drawing is done in L{BPArt}.

:param `dc`: an instance of `wx.DC`;
-        :param `rect`: the main caption text client rectangle.
+        :param `wx.Rect` `rect`: the main caption text client rectangle.
"""

if not self.IsShown():
@@ -1434,7 +1483,7 @@
"""
Checks whether a L{ButtonPanel} repaint is needed or not. This is a convenience function.

-        :param `status`: the status of a newly added L{ButtonInfo} or a change in the
+        :param bool `status`: the status of a newly added L{ButtonInfo} or a change in the
L{ButtonInfo} status.
"""

@@ -1447,7 +1496,7 @@
Sets the bitmap associated with this instance of L{ButtonInfo}.

:param `bmp`: a valid `wx.Bitmap` object;
-        :param `status`: the L{ButtonInfo} status ("Pressed", "Hover", "Normal",
+        :param string `status`: the L{ButtonInfo} status ("Pressed", "Hover", "Normal",
"Toggled", "Disabled").
"""

@@ -1459,8 +1508,10 @@
"""
Returns the bitmap associated with this instance of L{ButtonInfo}.

-        :param `status`: the L{ButtonInfo} status ("Pressed", "Hover", "Normal",
+        :param string `status`: the L{ButtonInfo} status ("Pressed", "Hover", "Normal",
"Toggled", "Disabled").
+
+        :return: An instance of `wx.Bitmap`.
"""

if status is None:
@@ -1479,19 +1530,32 @@

def GetRect(self):
-        """ Returns the L{ButtonInfo} client rectangle. """
+        """
+        Returns the L{ButtonInfo} client rectangle.
+
+        :return: An instance of `wx.Rect`.
+        """

return self._rect

def GetStatus(self):
-        """ Returns the L{ButtonInfo} status. """
+        """
+        Returns the L{ButtonInfo} status.
+
+        :return: A string containing the L{ButtonInfo} status (one of "Pressed", "Hover", "Normal",
+         "Toggled", "Disabled").
+        """

return self._status

def GetId(self):
-        """ Returns the L{ButtonInfo} id. """
+        """
+        Returns the L{ButtonInfo} id.
+
+        :return: An integer representing the button id.
+        """

return self._id

@@ -1510,7 +1574,7 @@
"""
Sets the L{ButtonInfo} status.

-        :param `status`: one of "Pressed", "Hover", "Normal", "Toggled", "Disabled".
+        :param string `status`: one of "Pressed", "Hover", "Normal", "Toggled", "Disabled".
"""

if status == self._status:
@@ -1524,7 +1588,11 @@

def GetTextAlignment(self):
-        """ Returns the text alignment in the button (bottom or right). """
+        """
+        Returns the text alignment in the button (bottom or right).
+
+        :return: An integer representing the L{ButtonInfo} text alignment.
+        """

return self._textAlignment

@@ -1533,7 +1601,7 @@
"""
Sets the text alignment in the button (bottom or right).

-        :param `alignment`: the text alignment in this L{ButtonInfo} instance.
+        :param integer `alignment`: the text alignment in this L{ButtonInfo} instance.
"""

if alignment == self._textAlignment:
@@ -1543,7 +1611,11 @@

def GetToggled(self):
-        """ Returns whether a ``wx.ITEM_CHECK`` button is toggled or not. """
+        """
+        Returns whether a ``wx.ITEM_CHECK`` button is toggled or not.
+
+        :return: ``True`` if the button is toggled, ``False`` otherwise.
+        """

if self._kind == wx.ITEM_NORMAL:
return False
@@ -1555,7 +1627,7 @@
"""
Sets a ``wx.ITEM_CHECK`` button toggled/not toggled.

-        :param `toggle`: ``True`` to toggle the button, ``False`` otherwise.
+        :param bool `toggle`: ``True`` to toggle the button, ``False`` otherwise.
"""

if self._kind == wx.ITEM_NORMAL:
@@ -1568,7 +1640,7 @@
"""
Sets the L{ButtonInfo} identifier.

-        :param `id`: the identifier of the window.
+        :param integer `id`: the identifier of the window.
"""

self._id = id
@@ -1584,8 +1656,8 @@
- Pressed;
- Toggled.

-        :param `name`: the new status name;
-        :param `bmp`: the bitmap associated with the new status.
+        :param string `name`: the new status name;
+        :param `wx.Bitmap` `bmp`: the bitmap associated with the new status.
"""

self._bitmaps.update({name: bmp})
@@ -1595,7 +1667,7 @@
"""
Enables/disables this instance of L{ButtonInfo}.

-        :param `enable`: ``True`` to enable the button, ``False`` otherwise.
+        :param bool `enable`: ``True`` to enable the button, ``False`` otherwise.
"""

if enable:
@@ -1617,20 +1689,28 @@
"""
Sets the button label text.

-        :param `text`: the button label string.
+        :param string `text`: the button label string.
"""

self._text = text

def GetText(self):
-        """ Returns the text associated to the button. """
+        """
+        Returns the text associated to the button.
+
+        :return: A string containing the L{ButtonInfo} text.
+        """

return self._text

def HasText(self):
-        """ Returns whether the button has text or not. """
+        """
+        Returns whether the button has text or not.
+
+        :return: ``True`` if this L{ButtonInfo} instance has a label, ``False`` otherwise.
+        """

return self._text != ""

@@ -1639,14 +1719,18 @@
"""
Sets the button type (standard or toggle).

-        :param `kind`: one of ``wx.ITEM_NORMAL``, ``wx.ITEM_CHECK``.
+        :param integer `kind`: one of ``wx.ITEM_NORMAL``, ``wx.ITEM_CHECK``.
"""

self._kind = kind

def GetKind(self):
-        """ Returns the button type (standard or toggle). """
+        """
+        Returns the button type (standard or toggle).
+
+        :return: An integer representing the button type, one of ``wx.ITEM_NORMAL``, ``wx.ITEM_CHECK``.
+        """

return self._kind

@@ -1655,14 +1739,18 @@
"""
Sets the help string to be shown in a tooltip.

-        :param `help`: the string for the short help.
+        :param string `help`: the string for the short help.
"""

self._shortHelp = help

def GetShortHelp(self):
-        """ Returns the help string shown in a tooltip. """
+        """
+        Returns the help string shown in a tooltip.
+
+        :return: A string containing the L{ButtonInfo} short help string.
+        """

return self._shortHelp

@@ -1671,14 +1759,18 @@
"""
Sets the help string to be shown in the statusbar.

-        :param `help`: the string for the long help.
+        :param string `help`: the string for the long help.
"""

self._longHelp = help

def GetLongHelp(self):
-        """ Returns the help string shown in the statusbar. """
+        """
+        Returns the help string shown in the statusbar.
+
+        :return: A string containing the L{ButtonInfo} long help string.
+        """

return self._longHelp

@@ -1703,12 +1795,12 @@
"""
Default class constructor.

-        :param `parent`: the parent window;
-        :param `id`: window identifier. If ``wx.ID_ANY``, will automatically create an identifier;
-        :param `text`: the main caption text for L{ButtonPanel};
-        :param `agwStyle`: the AGW-specific window style (one of ``BP_DEFAULT_STYLE``, ``BP_USE_GRADIENT``);
-        :param `alignment`: alignment of buttons (left or right);
-        :param `name`: window class name.
+        :param `wx.Window` `parent`: the parent window. Must not be ``None``;
+        :param integer `id`: window identifier. If ``wx.ID_ANY``, will automatically create an identifier;
+        :param string `text`: the main caption text for L{ButtonPanel};
+        :param integer `agwStyle`: the AGW-specific window style (one of ``BP_DEFAULT_STYLE``, ``BP_USE_GRADIENT``);
+        :param integer `alignment`: alignment of buttons (left or right);
+        :param string `name`: window class name.
"""

wx.PyPanel.__init__(self, parent, id, wx.DefaultPosition, wx.DefaultSize,
@@ -1758,7 +1850,7 @@
"""
Sets the main caption text.

-        :param `text`: the main caption text label. An empty string erases the
+        :param string `text`: the main caption text label. An empty string erases the
main caption text.
"""

@@ -1818,13 +1910,21 @@

def GetBarText(self):
-        """ Returns the main caption text. """
+        """
+        Returns the main caption text.
+
+        :return: A string representing the caption text.
+        """

return self._text.GetText()

def HasBarText(self):
-        """ Returns whether L{ButtonPanel} has a main caption text or not. """
+        """
+        Returns whether L{ButtonPanel} has a main caption text or not.
+
+        :return: ``True`` if L{ButtonPanel} has a main caption text, ``False`` otherwise.
+        """

return hasattr(self, "_text") and self._text.GetText() != ""

@@ -1849,10 +1949,10 @@
"""
Adds a spacer (stretchable or fixed-size) to L{ButtonPanel}.

-        :param `size`: the spacer size as a tuple;
-        :param `proportion`: the spacer proportion (0 for fixed-size, 1 or more for a
+        :param tuple `size`: the spacer size as a tuple;
+        :param integer `proportion`: the spacer proportion (0 for fixed-size, 1 or more for a
stretchable one);
-        :param `flag`: one of the `wx.BoxSizer` flags.
+        :param integer `flag`: one of the `wx.BoxSizer` flags.
"""

lenChildren = len(self._mainsizer.GetChildren())
@@ -1864,10 +1964,10 @@
Adds a wxPython control to L{ButtonPanel}.

:param `control`: an instance of `wx.Window`;
-        :param `proportion`: the control proportion (0 for fixed-size, 1 or more for a
+        :param integer `proportion`: the control proportion (0 for fixed-size, 1 or more for a
stretchable one);
-        :param `flag`: one of the `wx.BoxSizer` flags;
-        :param `border`: the control border width (in pixels), if the `flag` parameter
+        :param integer `flag`: one of the `wx.BoxSizer` flags;
+        :param integer `border`: the control border width (in pixels), if the `flag` parameter
is set to include any border flag.
"""

@@ -1894,7 +1994,7 @@
"""
Remove all the buttons from L{ButtonPanel}.

-        :note: This function is only for internal use only. If you are interested in
+        :note: This function is for internal use only. If you are interested in
manipulating a L{ButtonPanel} in real time (ie. removing things on it)
have a look at the L{Clear} method.
"""
@@ -1906,7 +2006,7 @@
"""
Remove all the separators from L{ButtonPanel}.

-        :note: This function is only for internal use only. If you are interested in
+        :note: This function is for internal use only. If you are interested in
manipulating a L{ButtonPanel} in real time (ie. removing things on it)
have a look at the L{Clear} method.
"""
@@ -1938,6 +2038,8 @@
"""
Returns the buttons alignment.

+        :return: An integer specifying the buttons alignment.
+
:see: L{SetAlignment} for a set of valid alignment bits.
"""

@@ -1948,7 +2050,7 @@
"""
Sets the buttons alignment.

-        :param `alignment`: can be one of the following bits:
+        :param integer `alignment`: can be one of the following bits:

====================== ======= ==========================
Alignment Flag          Value  Description
@@ -1981,13 +2083,21 @@

def IsVertical(self):
-        """ Returns whether L{ButtonPanel} is vertically aligned or not. """
+        """
+        Returns whether L{ButtonPanel} is vertically aligned or not.
+
+        :return: ``True`` if L{ButtonPanel} is vertically aligned, ``False`` otherwise.
+        """

return self._alignment not in [BP_ALIGN_RIGHT, BP_ALIGN_LEFT]

def IsStandard(self):
-        """ Returns whether L{ButtonPanel} is aligned "Standard" (left/top) or not. """
+        """
+        Returns whether L{ButtonPanel} is aligned "Standard" (left/top) or not.
+
+        :return: ``True`` if L{ButtonPanel} is aligned "standard", ``False`` otherwise.
+        """

return self._alignment in [BP_ALIGN_LEFT, BP_ALIGN_TOP]

@@ -2023,7 +2133,7 @@
"""
Recreates the L{ButtonPanel} sizer accordingly to the alignment specified.

-        :param `text`: the text to display as main caption. If `text` is set to ``None``,
+        :param string `text`: the text to display as main caption. If `text` is set to ``None``,
the main caption will not be displayed.
"""

@@ -2080,6 +2190,8 @@
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 `wx.Size`.
+
:note: Overridden from `wx.PyPanel`.
"""

@@ -2200,8 +2312,8 @@
"""
Layout the items when no main caption exists.

-        :param `nonspacers`: a list of items which are not spacers;
-        :param `children`: a list of all the children of L{ButtonPanel}.
+        :param list `nonspacers`: a list of items which are not spacers;
+        :param list `children`: a list of all the children of L{ButtonPanel}.
"""

size = self.GetSize()
@@ -2227,8 +2339,10 @@
Returns the size of an item in the main L{ButtonPanel} sizer.

:param `item`: an instance of L{ButtonInfo};
-        :param `isVertical`: ``True`` if L{ButtonPanel} is in vertical orientation,
+        :param bool `isVertical`: ``True`` if L{ButtonPanel} is in vertical orientation,
``False`` otherwise.
+
+        :return: An instance of `wx.Size`.
"""

if item.GetUserData():
@@ -2241,8 +2355,8 @@
"""
Layout the items when the main caption exists.

-        :param `nonspacers`: a list of items which are not spacers;
-        :param `allchildren`: a list of all the children of L{ButtonPanel}.
+        :param list `nonspacers`: a list of items which are not spacers;
+        :param list `allchildren`: a list of all the children of L{ButtonPanel}.
"""

if len(nonspacers) < 2:
@@ -2288,6 +2402,8 @@
"""
Returns all the L{ButtonPanel} main sizer's children that are not
flexible spacers.
+
+        :return: A list of items inside L{ButtonPanel} that are not flexible spacers.
"""

children1 = []
@@ -2304,7 +2420,11 @@

def GetControls(self):
-        """ Returns the wxPython controls that belongs to L{ButtonPanel}. """
+        """
+        Returns the wxPython controls that belongs to L{ButtonPanel}.
+
+        :return: A list of items inside L{ButtonPanel} that are wxPython controls.
+        """

children2 = self._mainsizer.GetChildren()
children1 = [child for child in children2 if not child.IsSpacer()]
@@ -2316,7 +2436,7 @@
"""
Sets the L{ButtonPanel} window style.

-        :param `agwStyle`: one of the following bits:
+        :param integer `agwStyle`: one of the following bits:

==================== =========== ==================================================
Window Styles        Hex Value   Description
@@ -2556,7 +2676,7 @@
Sets whether or not short and long help strings should be displayed as tooltips
and `wx.StatusBar` items respectively.

-        :param `useHelp`: ``True`` to display short and long help strings as tooltips
+        :param bool `useHelp`: ``True`` to display short and long help strings as tooltips
and `wx.StatusBar` items respectively, ``False`` otherwise.
"""

@@ -2567,6 +2687,9 @@
"""
Returns whether or not short and long help strings should be displayed as tooltips
and `wx.StatusBar` items respectively.
+
+        :return: ``True`` if the short and long help strings should be displayed as tooltips
+         and `wx.StatusBar` items respectively, ``False`` otherwise.
"""

return self._useHelp

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • buttonpanel »
  • SVN Revision 69086 For buttonpanel


cubecolourdialog functions

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • cubecolourdialog »
  • cubecolourdialog functions

cubecolourdialog functions

This is the description of standalone Python functions in the cubecolourdialog module.

Functions Summary

AngleFromPoint | Returns the angle between the x-axis and the line connecting the center and the point pt.
Distance | Returns the distance between 2 points.
DrawCheckerBoard | Draws a checkerboard on a wx.DC.
FindC | Internal function.
Intersection | Calculates the intersection point between 2 lines.
PointOnLine | Internal function.
PtFromAngle | Given the angle with respect to the x-axis, returns the point based on the saturation value.
RestoreOldDC | Restores the old settings for a wx.DC.
Slope | Calculates the slope of the line connecting 2 points.
deg2rad | Transforms degrees into radians.
rad2deg | Transforms radians into degrees.
rgb2html | Transforms a RGB triplet into an html hex string.
scaletomax | Normalize a value as a function of the radius.
toscale | Normalize a value as a function of the radius.

API Functions API

AngleFromPoint(pt, center) [source]

Returns the angle between the x-axis and the line connecting the center and the point pt.

Parameters:
  • pt – an instance of wx.Point;
  • center – a float value representing the center.

Distance(pt1, pt2) [source]

Returns the distance between 2 points.

Parameters:
  • pt1 – an instance of wx.Point;

  • pt2 – another instance of wx.Point.

DrawCheckerBoard(dc, rect, checkColour, box=5) [source]

Draws a checkerboard on a wx.DC.

Parameters:
  • dc – an instance of wx.DC;

  • rect – the client rectangle on which to draw the checkerboard;
  • checkColour – the colour used for the dark checkerboards;
  • box – the checkerboards box sizes.

Note

Used for the Alpha channel control and the colour panels.

FindC(line) [source]

Internal function.

Intersection(line1, line2) [source]

Calculates the intersection point between 2 lines.

Parameters:
  • line1 – an instance of LineDescription;
  • line2 – another instance of LineDescription.

PointOnLine(pt1, pt2, length, maxLen) [source]

Internal function.

PtFromAngle(angle, sat, center) [source]

Given the angle with respect to the x-axis, returns the point based on the saturation value.

Parameters:
  • angle – a float representing an angle;
  • sat – a float representing the colour saturation value;
  • center – a float value representing the center.

RestoreOldDC(dc, oldPen, oldBrush, oldMode) [source]

Restores the old settings for a wx.DC.

Parameters:
  • dc – an instance of wx.DC;

  • oldPen – an instance of wx.Pen;
  • oldBrush – an instance of wx.Brush;
  • oldMode – the wx.DC drawing mode bit.

Slope(pt1, pt2) [source]

Calculates the slope of the line connecting 2 points.

Parameters:
  • pt1 – an instance of wx.Point;

  • pt2 – another instance of wx.Point.

deg2rad(x) [source]

Transforms degrees into radians.

Parameters: x – a float representing an angle in degrees.

rad2deg(x) [source]

Transforms radians into degrees.

Parameters: x – a float representing an angle in radians.

rgb2html(colour) [source]

Transforms a RGB triplet into an html hex string.

Parameters: colour – a tuple of red, green, blue integers.

scaletomax(x) [source]

Normalize a value as a function of the radius.

Parameters: x – a float value to normalize

toscale(x) [source]

Normalize a value as a function of the radius.

Parameters: x – a float value to normalize

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • infobar
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • cubecolourdialog »
  • cubecolourdialog functions


AlphaCtrl

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • cubecolourdialog »
  • AlphaCtrl

AlphaCtrl

Implements the drawing, mouse handling and sizing routines for the alpha channel control.

hierarchy Inheritance Diagram

Inheritance diagram for: AlphaCtrl

Inheritance diagram of AlphaCtrl

supclasses Known Superclasses

  • cubecolourdialog.BaseLineCtrl

Methods Summary

__init__ | Default class constructor.
DrawAlphaShading | Draws the alpha shading on top of the checkerboard.
DrawMarkers | Draws square markers used with mouse gestures.
OnPaint | Handles the wx.EVT_PAINT for AlphaCtrl.
TrackPoint | Tracks a mouse action inside the Alpha channel control.

API Class API

class AlphaCtrl(BaseLineCtrl) [source]

Implements the drawing, mouse handling and sizing routines for the alpha channel control.

__init__(parent) [source]

Default class constructor. Used internally. Do not call it in your code!

Parameters: parent – the control parent window.

DrawAlphaShading(dc, rect) [source]

Draws the alpha shading on top of the checkerboard.

Parameters:
  • dc – an instance of wx.DC;
  • rect – the AlphaCtrl client rectangle.

DrawMarkers(dc=None) [source]

Draws square markers used with mouse gestures.

Parameters: dc – an instance of wx.DC.

OnPaint(event) [source]

Handles the wx.EVT_PAINT for AlphaCtrl.

Parameters: event – a wx.PaintEvent event to be processed.

TrackPoint(pt) [source]

Tracks a mouse action inside the Alpha channel control.

Parameters: pt – an instance of wx.Point.

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • infobar
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • cubecolourdialog »
  • AlphaCtrl


BaseLineCtrl

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • cubecolourdialog »
  • BaseLineCtrl

BaseLineCtrl

Base class used to hold common code for the Alpha channel control and the brightness palette control.

hierarchy Inheritance Diagram

Inheritance diagram for: BaseLineCtrl

Inheritance diagram of BaseLineCtrl

subclasses Known Subclasses

  • cubecolourdialog.AlphaCtrl
  • cubecolourdialog.BrightCtrl

Methods Summary

__init__ | Default class constructor.
AcceptsFocus | Can this window be given focus by mouse click? ..
AcceptsFocusFromKeyboard | Can this window be given focus by keyboard navigation? If not, the
BuildRect | Internal method.
DoGetBestSize | Overridden base class virtual.
OnEraseBackground | Handles the wx.EVT_ERASE_BACKGROUND for BaseLineCtrl.
OnLeftDown | Handles the wx.EVT_LEFT_DOWN for BaseLineCtrl.
OnLeftUp | Handles the wx.EVT_LEFT_UP for BaseLineCtrl.
OnMotion | Handles the wx.EVT_MOTION for BaseLineCtrl.
OnSize | Handles the wx.EVT_SIZE for BaseLineCtrl.

API Class API

class BaseLineCtrl(wx.PyControl) [source]

Base class used to hold common code for the Alpha channel control and the brightness palette control.

__init__(parent) [source]

Default class constructor. Used internally. Do not call it in your code!

Parameters: parent – the control parent window.

AcceptsFocus() [source]

Can this window be given focus by mouse click?

Note

This method always returns False as we do not accept focus from mouse click.

Note

Overridden from wx.PyControl.

AcceptsFocusFromKeyboard() [source]

Can this window be given focus by keyboard navigation? If not, the only way to give it focus (provided it accepts it at all) is to click it.

Note

This method always returns False as we do not accept focus from the keyboard.

Note

Overridden from wx.PyControl.

BuildRect() [source]

Internal method.

DoGetBestSize() [source]

Overridden base class virtual. Determines the best size of the control.

Note

Overridden from wx.PyControl.

OnEraseBackground(event) [source]

Handles the wx.EVT_ERASE_BACKGROUND for BaseLineCtrl.

Parameters: event – a wx.EraseEvent event to be processed.

Note

This is intentionally empty to reduce flicker.

OnLeftDown(event) [source]

Handles the wx.EVT_LEFT_DOWN for BaseLineCtrl.

Parameters: event – a wx.MouseEvent event to be processed.

OnLeftUp(event) [source]

Handles the wx.EVT_LEFT_UP for BaseLineCtrl.

Parameters: event – a wx.MouseEvent event to be processed.

OnMotion(event) [source]

Handles the wx.EVT_MOTION for BaseLineCtrl.

Parameters: event – a wx.MouseEvent event to be processed.

OnSize(event) [source]

Handles the wx.EVT_SIZE for BaseLineCtrl.

Parameters: event – a wx.SizeEvent event to be processed.

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • infobar
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • cubecolourdialog »
  • BaseLineCtrl


BasePyControl

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • cubecolourdialog »
  • BasePyControl

BasePyControl

Base class used to hold common code for the HSB colour wheel and the RGB colour cube.

hierarchy Inheritance Diagram

Inheritance diagram for: BasePyControl

Inheritance diagram of BasePyControl

subclasses Known Subclasses

  • cubecolourdialog.HSVWheel
  • cubecolourdialog.RGBCube

Methods Summary

__init__ | Default class constructor.
AcceptsFocus | Can this window be given focus by mouse click? ..
AcceptsFocusFromKeyboard | Can this window be given focus by keyboard navigation? If not, the
DoGetBestSize | Overridden base class virtual.
DrawLines | Draws the lines connecting the markers on top of the background bitmap.
DrawMarkers | Draws the markers on top of the background bitmap.
OnEraseBackground | Handles the wx.EVT_ERASE_BACKGROUND for BasePyControl.
OnLeftDown | Handles the wx.EVT_LEFT_DOWN for BasePyControl.
OnLeftUp | Handles the wx.EVT_LEFT_UP for BasePyControl.
OnMotion | Handles the wx.EVT_MOTION for BasePyControl.
OnPaint | Handles the wx.EVT_PAINT for BasePyControl.
OnSize | Handles the wx.EVT_SIZE for BasePyControl.

API Class API

class BasePyControl(wx.PyControl) [source]

Base class used to hold common code for the HSB colour wheel and the RGB colour cube.

__init__(parent, bitmap=None) [source]

Default class constructor. Used internally. Do not call it in your code!

Parameters:
  • parent – the control parent;
  • bitmap – the background bitmap for this custom control.

AcceptsFocus() [source]

Can this window be given focus by mouse click?

Note

This method always returns False as we do not accept focus from mouse click.

Note

Overridden from wx.PyControl.

AcceptsFocusFromKeyboard() [source]

Can this window be given focus by keyboard navigation? If not, the only way to give it focus (provided it accepts it at all) is to click it.

Note

This method always returns False as we do not accept focus from the keyboard.

Note

Overridden from wx.PyControl.

DoGetBestSize() [source]

Overridden base class virtual. Determines the best size of the control based on the bitmap size.

Note

Overridden from wx.PyControl.

DrawLines(dc) [source]

Draws the lines connecting the markers on top of the background bitmap.

Parameters: dc – an instance of wx.DC.

Note

This method must be overridden in derived classes.

DrawMarkers(dc=None) [source]

Draws the markers on top of the background bitmap.

Parameters: dc – an instance of wx.DC.

Note

This method must be overridden in derived classes.

OnEraseBackground(event) [source]

Handles the wx.EVT_ERASE_BACKGROUND for BasePyControl.

Parameters: event – a wx.EraseEvent event to be processed.

Note

This is intentionally empty to reduce flicker.

OnLeftDown(event) [source]

Handles the wx.EVT_LEFT_DOWN for BasePyControl.

Parameters: event – a wx.MouseEvent event to be processed.

Note

This method must be overridden in derived classes.

OnLeftUp(event) [source]

Handles the wx.EVT_LEFT_UP for BasePyControl.

Parameters: event – a wx.MouseEvent event to be processed.

Note

This method must be overridden in derived classes.

OnMotion(event) [source]

Handles the wx.EVT_MOTION for BasePyControl.

Parameters: event – a wx.MouseEvent event to be processed.

Note

This method must be overridden in derived classes.

OnPaint(event) [source]

Handles the wx.EVT_PAINT for BasePyControl.

Parameters: event – a wx.PaintEvent event to be processed.

OnSize(event) [source]

Handles the wx.EVT_SIZE for BasePyControl.

Parameters: event – a wx.SizeEvent event to be processed.

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • infobar
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • cubecolourdialog »
  • BasePyControl


BrightCtrl

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • cubecolourdialog »
  • BrightCtrl

BrightCtrl

Implements the drawing, mouse handling and sizing routines for the brightness palette control.

hierarchy Inheritance Diagram

Inheritance diagram for: BrightCtrl

Inheritance diagram of BrightCtrl

supclasses Known Superclasses

  • cubecolourdialog.BaseLineCtrl

Methods Summary

__init__ | Default class constructor.
DrawMarkers | Draws square markers used with mouse gestures.
OnPaint | Handles the wx.EVT_PAINT for BrightCtrl.
TrackPoint | Tracks a mouse action inside the palette control.

API Class API

class BrightCtrl(BaseLineCtrl) [source]

Implements the drawing, mouse handling and sizing routines for the brightness palette control.

__init__(parent) [source]

Default class constructor. Used internally. Do not call it in your code!

Parameters: parent – the control parent window.

DrawMarkers(dc=None) [source]

Draws square markers used with mouse gestures.

Parameters: dc – an instance of wx.DC.

OnPaint(event) [source]

Handles the wx.EVT_PAINT for BrightCtrl.

Parameters: event – a wx.PaintEvent event to be processed.

TrackPoint(pt) [source]

Tracks a mouse action inside the palette control.

Parameters: pt – an instance of wx.Point.

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • infobar
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • cubecolourdialog »
  • BrightCtrl


Colour

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • cubecolourdialog »
  • Colour

Colour

This is a subclass of wx.Colour, which adds Hue, Saturation and Brightness capability to the base class. It contains also methods to convert RGB triplets into HSB triplets and vice-versa.

hierarchy Inheritance Diagram

Inheritance diagram for: Colour

Inheritance diagram of Colour

Methods Summary

__init__ | Default class constructor.
GetPyColour | Returns the wxPython wx.Colour associated with this instance.
ToHSV | Converts a RGB triplet into a HSV triplet.
ToRGB | Converts a HSV triplet into a RGB triplet.

API Class API

class Colour(wx.Colour) [source]

This is a subclass of wx.Colour, which adds Hue, Saturation and Brightness capability to the base class. It contains also methods to convert RGB triplets into HSB triplets and vice-versa.

__init__(colour) [source]

Default class constructor.

Parameters: colour – a standard wx.Colour.

GetPyColour() [source]

Returns the wxPython wx.Colour associated with this instance.

ToHSV() [source]

Converts a RGB triplet into a HSV triplet.

ToRGB() [source]

Converts a HSV triplet into a RGB triplet.

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • infobar
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • cubecolourdialog »
  • Colour


ColourPanel

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • cubecolourdialog »
  • ColourPanel

ColourPanel

Simple custom class used to display “old” and “new” colour panels, with alpha blending capabilities.

hierarchy Inheritance Diagram

Inheritance diagram for: ColourPanel

Inheritance diagram of ColourPanel

Methods Summary

__init__ | Default class constructor.
AcceptsFocus | Can this window be given focus by mouse click? ..
AcceptsFocusFromKeyboard | Can this window be given focus by keyboard navigation? If not, the
OnEraseBackground | Handles the wx.EVT_ERASE_BACKGROUND for ColourPanel.
OnPaint | Handles the wx.EVT_PAINT for ColourPanel.
OnSize | Handles the wx.EVT_SIZE for ColourPanel.
RefreshColour | Refresh the panel after a colour/alpha change.

API Class API

class ColourPanel(wx.PyPanel) [source]

Simple custom class used to display “old” and “new” colour panels, with alpha blending capabilities.

__init__(parent, style=wx.SIMPLE_BORDER) [source]

Default class constructor. Used internally. Do not call it in your code!

Parameters:
  • parent – the control parent window;
  • style – the ColourPanel window style.

AcceptsFocus() [source]

Can this window be given focus by mouse click?

Note

This method always returns False as we do not accept focus from mouse click.

Note

Overridden from wx.PyPanel.

AcceptsFocusFromKeyboard() [source]

Can this window be given focus by keyboard navigation? If not, the only way to give it focus (provided it accepts it at all) is to click it.

Note

This method always returns False as we do not accept focus from the keyboard.

Note

Overridden from wx.PyPanel.

OnEraseBackground(event) [source]

Handles the wx.EVT_ERASE_BACKGROUND for ColourPanel.

Parameters: event – a wx.EraseEvent event to be processed.

Note

This is intentionally empty to reduce flicker.

OnPaint(event) [source]

Handles the wx.EVT_PAINT for ColourPanel.

Parameters: event – a wx.PaintEvent event to be processed.

OnSize(event) [source]

Handles the wx.EVT_SIZE for ColourPanel.

Parameters: event – a wx.SizeEvent event to be processed.

RefreshColour(colour) [source]

Refresh the panel after a colour/alpha change.

Parameters: colour – the new background colour of ColourPanel.

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • infobar
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • cubecolourdialog »
  • ColourPanel


CubeColourDialog

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • cubecolourdialog »
  • CubeColourDialog

CubeColourDialog

This is the CubeColourDialog main class implementation.

hierarchy Inheritance Diagram

Inheritance diagram for: CubeColourDialog

Inheritance diagram of CubeColourDialog

appearance Control Appearance

CubeColourDialog

Methods Summary

__init__ | Default class constructor.
AssignColourValue | Common code to handle spin control changes.
CalcCuboid | Calculates the RGB colour cube vertices.
CalcRects | Calculates the brightness control user-selected rect.
CalcSlopes | Calculates the line slopes in the RGB colour cube.
DoLayout | Layouts all the controls in the CubeColourDialog.
DrawAll | Draws all the custom controls after a colour change.
DrawAlpha | Refreshes the alpha channel control.
DrawBright | Refreshes the brightness control.
DrawHSB | Refreshes the HSB colour wheel.
DrawMarkers | Draws the markers for all the controls.
DrawRGB | Refreshes the RGB colour cube.
GetAGWWindowStyleFlag | Returns the CubeColourDialog window style flags.
GetColourData | Returns a wxPython compatible wx.ColourData.
GetHSVAColour | Returns a 4-elements tuple of hue, saturation, brightness, alpha components.
GetRGBAColour | Returns a 4-elements tuple of red, green, blue, alpha components.
InitDialog | Initialize the CubeColourDialog.
OnAddCustom | Handles the Add Custom wx.EVT_BUTTON event for CubeColourDialog.
OnAlphaSpin | Handles the wx.EVT_SPINCTRL event for the alpha channel.
OnCancel | Handles the Cancel wx.EVT_BUTTON event for CubeColourDialog.
OnCloseWindow | Handles the wx.EVT_CLOSE event for CubeColourDialog.
OnKeyUp | Handles the wx.EVT_CHAR_HOOK event for CubeColourDialog.
OnOk | Handles the Ok wx.EVT_BUTTON event for CubeColourDialog.
OnShowAlpha | Shows/hides the alpha channel control in CubeColourDialog.
OnSpinCtrl | Handles the wx.EVT_SPINCTRL event for RGB and HSB colours.
SetAGWWindowStyleFlag | Sets the CubeColourDialog window style flags.
SetCodes | Sets the HTML/MS Access codes (if any) in the text controls.
SetPanelColours | Assigns colours to the colour panels.
SetProperties | Sets some initial properties for CubeColourDialog (sizes, values).
SetSpinVals | Sets the values for all the spin controls.
ShowModal | Shows CubeColourDialog as a modal dialog. Program flow does

API Class API

class CubeColourDialog(wx.Dialog) [source]

This is the CubeColourDialog main class implementation.

__init__(parent, colourData=None, agwStyle=CCD_SHOW_ALPHA) [source]

Default class constructor.

Parameters:
  • colourData – a standard wx.ColourData (as used in wx.ColourDialog);
  • agwStyle – can be either None or CCD_SHOW_ALPHA, depending if you want to hide the alpha channel control or not.

AssignColourValue(attribute, colourVal, maxVal, position) [source]

Common code to handle spin control changes.

CalcCuboid() [source]

Calculates the RGB colour cube vertices.

CalcRects() [source]

Calculates the brightness control user-selected rect.

CalcSlopes() [source]

Calculates the line slopes in the RGB colour cube.

DoLayout() [source]

Layouts all the controls in the CubeColourDialog.

DrawAll() [source]

Draws all the custom controls after a colour change.

DrawAlpha() [source]

Refreshes the alpha channel control.

DrawBright() [source]

Refreshes the brightness control.

DrawHSB() [source]

Refreshes the HSB colour wheel.

DrawMarkers(dc=None) [source]

Draws the markers for all the controls.

Parameters: dc – an instance of wx.DC. If dc is None, a wx.ClientDC is created on the fly.

DrawRGB() [source]

Refreshes the RGB colour cube.

GetAGWWindowStyleFlag() [source]

Returns the CubeColourDialog window style flags.

See also

SetAGWWindowStyleFlag for a list of possible flags.

GetColourData() [source]

Returns a wxPython compatible wx.ColourData.

GetHSVAColour() [source]

Returns a 4-elements tuple of hue, saturation, brightness, alpha components.

GetRGBAColour() [source]

Returns a 4-elements tuple of red, green, blue, alpha components.

InitDialog() [source]

Initialize the CubeColourDialog.

OnAddCustom(event) [source]

Handles the Add Custom wx.EVT_BUTTON event for CubeColourDialog.

Parameters: event – a wx.CommandEvent event to be processed.

OnAlphaSpin(event) [source]

Handles the wx.EVT_SPINCTRL event for the alpha channel.

Parameters: event – a wx.SpinEvent event to be processed.

OnCancel(event) [source]

Handles the Cancel wx.EVT_BUTTON event for CubeColourDialog.

Parameters: event – a wx.CommandEvent event to be processed.

OnCloseWindow(event) [source]

Handles the wx.EVT_CLOSE event for CubeColourDialog.

Parameters: event – a wx.CloseEvent event to be processed.

OnKeyUp(event) [source]

Handles the wx.EVT_CHAR_HOOK event for CubeColourDialog.

Parameters: event – a wx.KeyEvent event to be processed.

OnOk(event) [source]

Handles the Ok wx.EVT_BUTTON event for CubeColourDialog.

Parameters: event – a wx.CommandEvent event to be processed.

OnShowAlpha(event) [source]

Shows/hides the alpha channel control in CubeColourDialog.

Parameters: event – a wx.CommandEvent event to be processed.

OnSpinCtrl(event) [source]

Handles the wx.EVT_SPINCTRL event for RGB and HSB colours.

Parameters: event – a wx.SpinEvent event to be processed.

SetAGWWindowStyleFlag(agwStyle) [source]

Sets the CubeColourDialog window style flags.

Parameters: agwStyle – can only be CCD_SHOW_ALPHA or None.

SetCodes() [source]

Sets the HTML/MS Access codes (if any) in the text controls.

SetPanelColours() [source]

Assigns colours to the colour panels.

SetProperties() [source]

Sets some initial properties for CubeColourDialog (sizes, values).

SetSpinVals() [source]

Sets the values for all the spin controls.

ShowModal() [source]

Shows CubeColourDialog as a modal dialog. Program flow does not return until the dialog has been dismissed with EndModal.

Note

Overridden from wx.Dialog.

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • infobar
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • cubecolourdialog »
  • CubeColourDialog


CustomPanel

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • cubecolourdialog »
  • CustomPanel

CustomPanel

This panel displays a series of custom colours (chosen by the user) just like the standard wx.ColourDialog.

hierarchy Inheritance Diagram

Inheritance diagram for: CustomPanel

Inheritance diagram of CustomPanel

Methods Summary

__init__ | Default class constructor.
AddCustom | Adds a user-chosen colour to the list of custom colours.
DoGetBestSize | Overridden base class virtual.
InitializeColours | Initializes the 16 custom colours in CustomPanel.
OnEraseBackground | Handles the wx.EVT_ERASE_BACKGROUND for CustomPanel.
OnLeftDown | Handles the wx.EVT_LEFT_DOWN for CustomPanel.
OnPaint | Handles the wx.EVT_PAINT for CustomPanel.
OnSize | Handles the wx.EVT_SIZE for CustomPanel.
PaintCustomColour | Paints a newly added custom colour subpanel.
PaintCustomColours | Draws all the 16 subpanels with their custom colours.
PaintHighlight | Highlight the current custom colour selection (if any).

API Class API

class CustomPanel(wx.PyControl) [source]

This panel displays a series of custom colours (chosen by the user) just like the standard wx.ColourDialog.

__init__(parent, colourData) [source]

Default class constructor. Used internally. Do not call it in your code!

Parameters:
  • parent – the control parent window;
  • colourData – an instance of wx.ColourData.

AddCustom(colour) [source]

Adds a user-chosen colour to the list of custom colours.

Parameters: colour – an instance of wx.Colour.

DoGetBestSize() [source]

Overridden base class virtual. Determines the best size of the control.

Note

Overridden from wx.PyControl.

InitializeColours() [source]

Initializes the 16 custom colours in CustomPanel.

OnEraseBackground(event) [source]

Handles the wx.EVT_ERASE_BACKGROUND for CustomPanel.

Parameters: event – a wx.EraseEvent event to be processed.

Note

This is intentionally empty to reduce flicker.

OnLeftDown(event) [source]

Handles the wx.EVT_LEFT_DOWN for CustomPanel.

Parameters: event – a wx.MouseEvent event to be processed.

OnPaint(event) [source]

Handles the wx.EVT_PAINT for CustomPanel.

Parameters: event – a wx.PaintEvent event to be processed.

OnSize(event) [source]

Handles the wx.EVT_SIZE for CustomPanel.

Parameters: event – a wx.SizeEvent event to be processed.

PaintCustomColour(dc, selX, selY) [source]

Paints a newly added custom colour subpanel.

Parameters:
  • dc – an instance of wx.DC;
  • selX – the x coordinate of the custom colour subpanel;
  • selY – the y coordinate of the custom colour subpanel.

PaintCustomColours(dc) [source]

Draws all the 16 subpanels with their custom colours.

Parameters: dc – an instance of wx.DC.

PaintHighlight(dc, draw=True) [source]

Highlight the current custom colour selection (if any).

Parameters:
  • dc – an instance of wx.DC;

  • draw – whether to draw a thin black border around the selected custom colour or not.

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • infobar
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • cubecolourdialog »
  • CustomPanel


HSVWheel

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • cubecolourdialog »
  • HSVWheel

HSVWheel

Implements the drawing, mouse handling and sizing routines for the HSV colour wheel.

hierarchy Inheritance Diagram

Inheritance diagram for: HSVWheel

Inheritance diagram of HSVWheel

supclasses Known Superclasses

  • cubecolourdialog.BasePyControl

Methods Summary

__init__ | Default class constructor.
DrawMarkers | Draws the markers on top of the background bitmap.
InCircle | Returns whether a point is inside the HSV wheel or not.
OnLeftDown | Handles the wx.EVT_LEFT_DOWN for HSVWheel.
OnLeftUp | Handles the wx.EVT_LEFT_UP for HSVWheel.
OnMotion | Handles the wx.EVT_MOTION for HSVWheel.
TrackPoint | Track a mouse event inside the HSV colour wheel.

API Class API

class HSVWheel(BasePyControl) [source]

Implements the drawing, mouse handling and sizing routines for the HSV colour wheel.

__init__(parent) [source]

Default class constructor. Used internally. Do not call it in your code!

Parameters: parent – the control parent window.

DrawMarkers(dc=None) [source]

Draws the markers on top of the background bitmap.

Parameters: dc – an instance of wx.DC.

InCircle(pt) [source]

Returns whether a point is inside the HSV wheel or not.

Parameters: pt – an instance of wx.Point.

OnLeftDown(event) [source]

Handles the wx.EVT_LEFT_DOWN for HSVWheel.

Parameters: event – a wx.MouseEvent event to be processed.

OnLeftUp(event) [source]

Handles the wx.EVT_LEFT_UP for HSVWheel.

Parameters: event – a wx.MouseEvent event to be processed.

OnMotion(event) [source]

Handles the wx.EVT_MOTION for HSVWheel.

Parameters: event – a wx.MouseEvent event to be processed.

TrackPoint(pt) [source]

Track a mouse event inside the HSV colour wheel.

Parameters: pt – an instance of wx.Point.

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • infobar
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • cubecolourdialog »
  • HSVWheel


LineDescription

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • cubecolourdialog »
  • LineDescription

LineDescription

Simple class to store description and constants for a line in 2D space.

hierarchy Inheritance Diagram

Inheritance diagram for: LineDescription

Inheritance diagram of LineDescription

Methods Summary

__init__ Default class constructor.

API Class API

class LineDescription(object) [source]

Simple class to store description and constants for a line in 2D space.

__init__(x=0, y=0, slope=None, c=None) [source]

Default class constructor.

Used internally. Do not call it in your code!

Parameters:
  • x – the x coordinate of the first point;
  • y – the y coordinate of the first point;
  • slope – the line’s slope;
  • c – a floating point constant.

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • infobar
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • cubecolourdialog »
  • LineDescription


RGBCube

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • cubecolourdialog »
  • RGBCube

RGBCube

Implements the drawing, mouse handling and sizing routines for the RGB cube colour.

hierarchy Inheritance Diagram

Inheritance diagram for: RGBCube

Inheritance diagram of RGBCube

supclasses Known Superclasses

  • cubecolourdialog.BasePyControl

Methods Summary

__init__ | Default class constructor.
DrawLines | Draws the lines connecting the markers on top of the background bitmap.
DrawMarkers | Draws the markers on top of the background bitmap.
OnLeftDown | Handles the wx.EVT_LEFT_DOWN for RGBCube.
OnLeftUp | Handles the wx.EVT_LEFT_UP for RGBCube.
OnMotion | Handles the wx.EVT_MOTION for RGBCube.

API Class API

class RGBCube(BasePyControl) [source]

Implements the drawing, mouse handling and sizing routines for the RGB cube colour.

__init__(parent) [source]

Default class constructor. Used internally. Do not call it in your code!

Parameters: parent – the control parent window.

DrawLines(dc) [source]

Draws the lines connecting the markers on top of the background bitmap.

Parameters: dc – an instance of wx.DC.

DrawMarkers(dc=None) [source]

Draws the markers on top of the background bitmap.

Parameters: dc – an instance of wx.DC.

OnLeftDown(event) [source]

Handles the wx.EVT_LEFT_DOWN for RGBCube.

Parameters: event – a wx.MouseEvent event to be processed.

OnLeftUp(event) [source]

Handles the wx.EVT_LEFT_UP for RGBCube.

Parameters: event – a wx.MouseEvent event to be processed.

OnMotion(event) [source]

Handles the wx.EVT_MOTION for RGBCube.

Parameters: event – a wx.MouseEvent event to be processed.

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • infobar
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • cubecolourdialog »
  • RGBCube


SVN Revision 68362 For cubecolourdialog

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • cubecolourdialog »
  • SVN Revision 68362 For cubecolourdialog

svn SVN Revision 68362 For cubecolourdialog

This file contains the SVN revision history for cubecolourdialog, at revision 68362.

Available information include commit date, the name of the committer, the file size, the SVN log messages and a diff from the previous version (if available).

File Information

  • Commit Date: 02-Jan-2009 03:09:18 UTC
  • Committer: AG
  • File Size: 139728 byte(s)

Log Messages

The following log message was entered by the committer:

  • All of AGW: change my work e-mail from KPO to Maersk Oil (silly commit)

Diff To Previous Version (65377)

Version SVN diff:

--- wxPython/3rdParty/AGW/agw/cubecolourdialog.py   2010/08/21 20:27:02     65377
+++ wxPython/3rdParty/AGW/agw/cubecolourdialog.py   2011/07/24 21:36:47     68362
@@ -19,7 +19,7 @@
# Write To Me At:
#
# andrea.gavana@gmail.com
-# gavana@kpo.kz
+# andrea.gavana@maerskoil.com
#
# Or, Obviously, To The wxPython Mailing List!!!
#

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • cubecolourdialog »
  • SVN Revision 68362 For cubecolourdialog


SVN Revision 68742 For cubecolourdialog

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • cubecolourdialog »
  • SVN Revision 68742 For cubecolourdialog

svn SVN Revision 68742 For cubecolourdialog

This file contains the SVN revision history for cubecolourdialog, at revision 68742.

Available information include commit date, the name of the committer, the file size, the SVN log messages and a diff from the previous version (if available).

File Information

  • Commit Date: 20-Oct-2008 20:05:15 UTC
  • Committer: AG
  • File Size: 139732 byte(s)

Log Messages

The following log message was entered by the committer:

  • FlatNotebook: fix issues with custom page and vertical/horizontal tiling of pages;
  • AuiBook: every time the AuiBook is split, copy over the custom buttons in the tab area of the newly created AuiBook;
  • Others: minor modifications to the docstrings.

Diff To Previous Version (68362)

Version SVN diff:

--- wxPython/3rdParty/AGW/agw/cubecolourdialog.py   2011/07/24 21:36:47     68362
+++ wxPython/3rdParty/AGW/agw/cubecolourdialog.py   2011/08/16 16:37:37     68742
@@ -4,7 +4,7 @@
# Python Code By:
#
# Andrea Gavana, @ 16 Aug 2007
-# Latest Revision: 14 Apr 2010, 12.00 GMT
+# Latest Revision: 15 Aug 2011, 20.00 GMT
#
#
# TODO List
@@ -88,7 +88,7 @@

CubeColourDialog is distributed under the wxPython license.

-Latest Revision: Andrea Gavana @ 14 Apr 2010, 12.00 GMT
+Latest Revision: Andrea Gavana @ 15 Aug 2011, 20.00 GMT

Version 0.3.

@@ -1175,6 +1175,7 @@

return 180.0*x/pi

+
def deg2rad(x):
"""
Transforms degrees into radians.
@@ -1184,6 +1185,7 @@

return x*pi/180.0

+
def toscale(x):
"""
Normalize a value as a function of the radius.
@@ -1193,6 +1195,7 @@

return x*RADIUS/255.0

+
def scaletomax(x):
"""
Normalize a value as a function of the radius.
@@ -1202,6 +1205,7 @@

return x*255.0/RADIUS

+
def rgb2html(colour):
"""
Transforms a RGB triplet into an html hex string.

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • cubecolourdialog »
  • SVN Revision 68742 For cubecolourdialog


SVN Revision 68881 For cubecolourdialog

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • cubecolourdialog »
  • SVN Revision 68881 For cubecolourdialog

svn SVN Revision 68881 For cubecolourdialog

This file contains the SVN revision history for cubecolourdialog, at revision 68881.

Available information include commit date, the name of the committer, the file size, the SVN log messages and a diff from the previous version (if available).

File Information

  • Commit Date: 17-Oct-2008 21:01:24 UTC
  • Committer: AG
  • File Size: 141071 byte(s)

Log Messages

The following log message was entered by the committer:

  • AGW: General overhaul of the documentation, much improved. All the widgets have their own sample usage in the docs as well;

  • FlatNotebook: Added the FNB_NAV_BUTTONS_WHEN_NEEDED style, which hides the navigation left/right arrows if all tabs fit;

  • RibbonBar: - Added the EVT_RIBBONBAR_TAB_LEFT_DCLICK event, which generates a special event

    when a ribbon bar tab is double-clicked;

    • Added support for toggle buttons;
    • Improved support for ribbon panel sizers: panels with sizers should now automatically minimise at small sizes, and behave properly when popping up from a minimised state;
    • Added tooltips via SetToolTip for those buttons which have the help_string attribute set.

  • XLSGrid: a new widget was added to AGW, termed XLSGrid. It’s based on wx.grid.Grid and can be used to faithfully reproduce the appearance of a Microsoft Excel spreadsheets.

Diff To Previous Version (68742)

Version SVN diff:

--- wxPython/3rdParty/AGW/agw/cubecolourdialog.py   2011/08/16 16:37:37     68742
+++ wxPython/3rdParty/AGW/agw/cubecolourdialog.py   2011/08/25 16:40:17     68881
@@ -4,7 +4,7 @@
# Python Code By:
#
# Andrea Gavana, @ 16 Aug 2007
-# Latest Revision: 15 Aug 2011, 20.00 GMT
+# Latest Revision: 17 Aug 2011, 15.00 GMT
#
#
# TODO List
@@ -28,13 +28,13 @@
# --------------------------------------------------------------------------- #

"""
-CubeColourDialog is an alternative implementation of `wx.ColourDialog`.
+L{CubeColourDialog} is an alternative implementation of `wx.ColourDialog`.

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

-The CubeColourDialog is an alternative implementation of `wx.ColourDialog`, and it
+The L{CubeColourDialog} is an alternative implementation of `wx.ColourDialog`, and it
offers different functionalities with respect to the default wxPython one. It
can be used as a replacement of `wx.ColourDialog` with exactly the same syntax and
methods.
@@ -53,7 +53,7 @@
dialog, via a simple `wx.CheckBox`;
- The "old colour" and "new colour" are displayed in two small custom panel,
which support alpha transparency and texture;
-- CubeColourDialog displays also the HTML colour code in hexadecimal format;
+- L{CubeColourDialog} displays also the HTML colour code in hexadecimal format;
- When available, a corresponding "Web Safe" colour is generated using a 500
web colours "database" (a dictionary inside the widget source code). Web Safe
colours are recognized by all the browsers;
@@ -65,6 +65,42 @@
And much more.

+Usage
+=====
+
+Usage example::
+
+    import wx
+    import wx.lib.agw.cubecolourdialog as CCD
+
+    # Our normal wxApp-derived class, as usual
+    app = wx.App(0)
+
+    colourData = wx.ColourData()
+    dlg = CCD.CubeColourDialog(None, colourData)
+
+    if dlg.ShowModal() == wx.ID_OK:
+
+        # If the user selected OK, then the dialog's wx.ColourData will
+        # contain valid information. Fetch the data ...
+        colourData = dlg.GetColourData()
+        h, s, v, a = dlg.GetHSVAColour()
+
+        # ... then do something with it. The actual colour data will be
+        # returned as a three-tuple (r, g, b) in this particular case.
+        colour = colourData.GetColour()
+        r, g, b, alpha = colour.Red(), colour.Green(), colour.Blue(), colour.Alpha()
+        print "You selected (RGBA): %d, %d, %d, %d"%(r, g, b, alpha)
+        print "You selected (HSVA): %d, %d, %d, %d"%(h, s, v, a)
+
+    # Once the dialog is destroyed, Mr. wx.ColourData is no longer your
+    # friend. Don't use it again!
+    dlg.Destroy()
+
+    app.MainLoop()
+
+
+
Window Styles
=============

@@ -73,7 +109,7 @@
================== =========== ==================================================
Window Styles      Hex Value   Description
================== =========== ==================================================
-``CCD_SHOW_ALPHA``         0x1 Show the widget used to control colour alpha channels in `CubeColourDialog`.
+``CCD_SHOW_ALPHA``         0x1 Show the widget used to control colour alpha channels in L{CubeColourDialog}.
================== =========== ==================================================

@@ -86,9 +122,9 @@
License And Version
===================

-CubeColourDialog is distributed under the wxPython license.
+L{CubeColourDialog} is distributed under the wxPython license.

-Latest Revision: Andrea Gavana @ 15 Aug 2011, 20.00 GMT
+Latest Revision: Andrea Gavana @ 17 Aug 2011, 15.00 GMT

Version 0.3.

@@ -113,7 +149,7 @@

# Show the alpha control in the dialog
CCD_SHOW_ALPHA = 1
-""" Show the widget used to control colour alpha channels in `CubeColourDialog`. """
+""" Show the widget used to control colour alpha channels in L{CubeColourDialog}. """

# Radius of the HSB colour wheel
RADIUS = 100
@@ -1744,7 +1780,12 @@

def DoGetBestSize(self):
-        """ Returns the custom control best size (used by sizers). """
+        """
+        Overridden base class virtual. Determines the best size of the
+        control based on the bitmap size.
+
+        :note: Overridden from `wx.PyControl`.
+        """

return wx.Size(self._bitmap.GetWidth(), self._bitmap.GetHeight())

@@ -2172,7 +2213,11 @@

def DoGetBestSize(self):
-        """ Returns the custom control best size (used by sizers). """
+        """
+        Overridden base class virtual. Determines the best size of the control.
+
+        :note: Overridden from `wx.PyControl`.
+        """

return wx.Size(24, 208)

@@ -2580,7 +2625,7 @@

class CustomPanel(wx.PyControl):
"""
-    This panel displays a series of cutom colours (chosen by the user) just like
+    This panel displays a series of custom colours (chosen by the user) just like
the standard `wx.ColourDialog`.
"""

@@ -2631,7 +2676,11 @@

def DoGetBestSize(self):
-        """ Returns the custom control best size (used by sizers). """
+        """
+        Overridden base class virtual. Determines the best size of the control.
+
+        :note: Overridden from `wx.PyControl`.
+        """

return self._customColourRect.width+4, self._customColourRect.height+4

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • cubecolourdialog »
  • SVN Revision 68881 For cubecolourdialog


SVN Revision 70696 For cubecolourdialog

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • cubecolourdialog »
  • SVN Revision 70696 For cubecolourdialog

svn SVN Revision 70696 For cubecolourdialog

This file contains the SVN revision history for cubecolourdialog, at revision 70696.

Available information include commit date, the name of the committer, the file size, the SVN log messages and a diff from the previous version (if available).

File Information

  • Commit Date: 17-Oct-2008 19:15:31 UTC
  • Committer: AG
  • File Size: 141143 byte(s)

Log Messages

The following log message was entered by the committer:

CubeColourDialog: internationalize the various hard-coded strings.

Diff To Previous Version (68881)

Version SVN diff:

--- wxPython/3rdParty/AGW/agw/cubecolourdialog.py   2011/08/25 16:40:17     68881
+++ wxPython/3rdParty/AGW/agw/cubecolourdialog.py   2012/02/26 14:29:57     70696
@@ -4,7 +4,7 @@
# Python Code By:
#
# Andrea Gavana, @ 16 Aug 2007
-# Latest Revision: 17 Aug 2011, 15.00 GMT
+# Latest Revision: 26 Feb 2012, 15.00 GMT
#
#
# TODO List
@@ -124,9 +124,9 @@

L{CubeColourDialog} is distributed under the wxPython license.

-Latest Revision: Andrea Gavana @ 17 Aug 2011, 15.00 GMT
+Latest Revision: Andrea Gavana @ 26 Feb 2012, 15.00 GMT

-Version 0.3.
+Version 0.4.

"""

@@ -2873,24 +2873,24 @@

self.mainPanel = wx.Panel(self, -1)

-        self.hsvSizer_staticbox = wx.StaticBox(self.mainPanel, -1, "HSB")
-        self.rgbValueSizer_staticbox = wx.StaticBox(self.mainPanel, -1, "RGB Values")
-        self.hsvValueSizer_staticbox = wx.StaticBox(self.mainPanel, -1, "HSB Values")
-        self.rgbSizer_staticbox = wx.StaticBox(self.mainPanel, -1, "RGB")
-        self.alphaSizer_staticbox = wx.StaticBox(self.mainPanel, -1, "Alpha")
-        self.alphaValueSizer_staticbox = wx.StaticBox(self.mainPanel, -1, "Alpha")
+        self.hsvSizer_staticbox = wx.StaticBox(self.mainPanel, -1, _("HSB"))
+        self.rgbValueSizer_staticbox = wx.StaticBox(self.mainPanel, -1, _("RGB Values"))
+        self.hsvValueSizer_staticbox = wx.StaticBox(self.mainPanel, -1, _("HSB Values"))
+        self.rgbSizer_staticbox = wx.StaticBox(self.mainPanel, -1, _("RGB"))
+        self.alphaSizer_staticbox = wx.StaticBox(self.mainPanel, -1, _("Alpha"))
+        self.alphaValueSizer_staticbox = wx.StaticBox(self.mainPanel, -1, _("Alpha"))

self.rgbBitmap = RGBCube(self.mainPanel)
self.hsvBitmap = HSVWheel(self.mainPanel)
self.brightCtrl = BrightCtrl(self.mainPanel)
self.alphaCtrl = AlphaCtrl(self.mainPanel)

-        self.showAlpha = wx.CheckBox(self.mainPanel, -1, "Show Alpha Control")
+        self.showAlpha = wx.CheckBox(self.mainPanel, -1, _("Show Alpha Control"))
self.customColours = CustomPanel(self.mainPanel, self._colourData)
-        self.addCustom = wx.Button(self.mainPanel, -1, "Add to custom colours")
+        self.addCustom = wx.Button(self.mainPanel, -1, _("Add to custom colours"))

-        self.okButton = wx.Button(self.mainPanel, -1, "Ok")
-        self.cancelButton = wx.Button(self.mainPanel, -1, "Cancel")
+        self.okButton = wx.Button(self.mainPanel, -1, _("OK"))
+        self.cancelButton = wx.Button(self.mainPanel, -1, _("Cancel"))

self.oldColourPanel = ColourPanel(self.mainPanel, style=wx.SIMPLE_BORDER)
self.newColourPanel = ColourPanel(self.mainPanel, style=wx.SIMPLE_BORDER)
@@ -2983,8 +2983,8 @@

mainSizer.Add(self.showAlpha, (0, 0), (1, 1), wx.LEFT|wx.TOP, 10)

-        htmlLabel1 = wx.StaticText(self.mainPanel, -1, "HTML Code")
-        htmlLabel2 = wx.StaticText(self.mainPanel, -1, "Web Safe")
+        htmlLabel1 = wx.StaticText(self.mainPanel, -1, _("HTML Code"))
+        htmlLabel2 = wx.StaticText(self.mainPanel, -1, _("Web Safe"))
htmlSizer_a.Add(htmlLabel1, 0, wx.TOP, 3)
htmlSizer_b.Add(htmlLabel2, 0, wx.TOP, 3)
htmlSizer_a.Add(self.htmlCode, 0, wx.TOP, 3)
@@ -2994,13 +2994,13 @@
htmlSizer1.Add(htmlSizer_b, 0, wx.LEFT, 10)
mainSizer.Add(htmlSizer1, (1, 0), (1, 1), wx.LEFT|wx.RIGHT, 10)

-        htmlLabel3 = wx.StaticText(self.mainPanel, -1, "HTML Name")
+        htmlLabel3 = wx.StaticText(self.mainPanel, -1, _("HTML Name"))
htmlSizer2.Add(htmlLabel3, 0, wx.TOP|wx.BOTTOM, 3)
htmlSizer2.Add(self.htmlName, 0)

mainSizer.Add(htmlSizer2, (1, 1), (1, 1), wx.LEFT|wx.RIGHT, 10)

-        customLabel = wx.StaticText(self.mainPanel, -1, "Custom Colours")
+        customLabel = wx.StaticText(self.mainPanel, -1, _("Custom Colours"))
customSizer.Add(customLabel, 0, wx.BOTTOM, 3)
customSizer.Add(self.customColours, 0)
customSizer.Add(self.addCustom, 0, wx.TOP|wx.ALIGN_LEFT|wx.ALIGN_CENTER_VERTICAL, 5)
@@ -3014,11 +3014,11 @@
alphaSizer.Add(self.alphaCtrl, 0, wx.TOP|wx.ALIGN_CENTER, 15)
mainSizer.Add(alphaSizer, (2, 2), (1, 1), wx.ALL|wx.EXPAND, 10)

-        oldLabel = wx.StaticText(self.mainPanel, -1, "Old Colour")
+        oldLabel = wx.StaticText(self.mainPanel, -1, _("Old Colour"))
panelSizer.Add(oldLabel, 0, wx.BOTTOM, 3)
panelSizer.Add(self.oldColourPanel, 0, wx.BOTTOM|wx.EXPAND, 20)
-        newLabel = wx.StaticText(self.mainPanel, -1, "New Colour")
-        accessLabel = wx.StaticText(self.mainPanel, -1, "MS Access Code")
+        newLabel = wx.StaticText(self.mainPanel, -1, _("New Colour"))
+        accessLabel = wx.StaticText(self.mainPanel, -1, _("MS Access Code"))
accessSizer.Add(accessLabel, 0, wx.BOTTOM, 3)
accessSizer.Add(self.accessCode, 0)
panelSizer.Add(newLabel, 0, wx.BOTTOM, 3)
@@ -3026,29 +3026,29 @@
panelSizer.Add((0, 0), 1, wx.EXPAND)
panelSizer.Add(accessSizer, 0, wx.TOP, 5)
mainSizer.Add(panelSizer, (2, 3), (1, 1), wx.ALL|wx.EXPAND, 10)
-        redLabel = wx.StaticText(self.mainPanel, -1, "Red")
+        redLabel = wx.StaticText(self.mainPanel, -1, _("Red"))
rgbGridSizer.Add(redLabel, 0)
-        greenLabel = wx.StaticText(self.mainPanel, -1, "Green")
+        greenLabel = wx.StaticText(self.mainPanel, -1, _("Green"))
rgbGridSizer.Add(greenLabel, 0)
-        blueLabel = wx.StaticText(self.mainPanel, -1, "Blue")
+        blueLabel = wx.StaticText(self.mainPanel, -1, _("Blue"))
rgbGridSizer.Add(blueLabel, 0)
rgbGridSizer.Add(self.redSpin, 0, wx.EXPAND)
rgbGridSizer.Add(self.greenSpin, 0, wx.EXPAND)
rgbGridSizer.Add(self.blueSpin, 0, wx.EXPAND)
rgbValueSizer.Add(rgbGridSizer, 1, 0, 0)
mainSizer.Add(rgbValueSizer, (3, 0), (1, 1), wx.LEFT|wx.RIGHT|wx.BOTTOM|wx.EXPAND, 10)
-        hueLabel = wx.StaticText(self.mainPanel, -1, "Hue")
+        hueLabel = wx.StaticText(self.mainPanel, -1, _("Hue"))
hsvGridSizer.Add(hueLabel, 0)
-        saturationLabel = wx.StaticText(self.mainPanel, -1, "Saturation")
+        saturationLabel = wx.StaticText(self.mainPanel, -1, _("Saturation"))
hsvGridSizer.Add(saturationLabel, 0)
-        brightnessLabel = wx.StaticText(self.mainPanel, -1, "Brightness")
+        brightnessLabel = wx.StaticText(self.mainPanel, -1, _("Brightness"))
hsvGridSizer.Add(brightnessLabel, 0)
hsvGridSizer.Add(self.hueSpin, 0, wx.EXPAND)
hsvGridSizer.Add(self.saturationSpin, 0, wx.EXPAND)
hsvGridSizer.Add(self.brightnessSpin, 0, wx.EXPAND)
hsvValueSizer.Add(hsvGridSizer, 1, wx.EXPAND)
mainSizer.Add(hsvValueSizer, (3, 1), (1, 1), wx.LEFT|wx.RIGHT|wx.BOTTOM|wx.EXPAND, 10)
-        alphaLabel = wx.StaticText(self.mainPanel, -1, "Alpha")
+        alphaLabel = wx.StaticText(self.mainPanel, -1, _("Alpha"))
alphaGridSizer.Add(alphaLabel, 0)
alphaGridSizer.Add(self.alphaSpin, 0, wx.EXPAND|wx.TOP, 10)
alphaValueSizer.Add(alphaGridSizer, 1, wx.EXPAND)

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • cubecolourdialog »
  • SVN Revision 70696 For cubecolourdialog


customtreectrl functions

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • customtreectrl »
  • customtreectrl functions

customtreectrl functions

This is the description of standalone Python functions in the customtreectrl module.

Functions Summary

ChopText | Chops the input text if its size does not fit in max_size, by cutting the text and adding ellipsis at the end.
DrawTreeItemButton | Draw the expanded/collapsed icon for a tree control item.
EventFlagsToSelType | Translate the key or mouse event flag to the type of selection we are dealing with.
MakeDisabledBitmap | Creates a disabled-looking bitmap starting from the input one.

API Functions API

ChopText(dc, text, max_size) [source]

Chops the input text if its size does not fit in max_size, by cutting the text and adding ellipsis at the end.

Parameters:
  • dc – a wx.DC device context;
  • text – the text to chop;
  • max_size – the maximum size in which the text should fit.

Note

This method is used exclusively when CustomTreeCtrl has the TR_ELLIPSIZE_LONG_ITEMS style set.

New in version 0.9.3.

DrawTreeItemButton(win, dc, rect, flags) [source]

Draw the expanded/collapsed icon for a tree control item.

Parameters:
  • win – an instance of wx.Window;
  • dc – an instance of wx.DC;

  • rect (wx.Rect) – the client rectangle where to draw the tree item button;
  • flags (integer) – contains wx.CONTROL_EXPANDED bit for expanded tree items.

Note

This is a simple replacement of wx.RendererNative.DrawTreeItemButton.

Note

This method is never used in wxPython versions newer than 2.6.2.1.

EventFlagsToSelType(style, shiftDown=False, ctrlDown=False) [source]

Translate the key or mouse event flag to the type of selection we are dealing with.

Parameters:
  • style (integer) – the main CustomTreeCtrl window style flag;
  • shiftDown (bool) – True if the Shift key is pressed, False otherwise;
  • ctrlDown (bool) – True if the Ctrl key is pressed, False otherwise;
Returns:

A 3-elements tuple, with the following elements:

  • is_multiple: True if CustomTreeCtrl has the TR_MULTIPLE flag set, False otherwise;
  • extended_select: True if the Shift key is pressend and if CustomTreeCtrl has the TR_MULTIPLE flag set, False otherwise;
  • unselect_others: True if the Ctrl key is pressend and if CustomTreeCtrl has the TR_MULTIPLE flag set, False otherwise.

MakeDisabledBitmap(original) [source]

Creates a disabled-looking bitmap starting from the input one.

Parameters: original – an instance of wx.Bitmap to be greyed-out.
Returns: An instance of wx.Bitmap, containing a disabled-looking representation of the original item image.

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • infobar
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • customtreectrl »
  • customtreectrl functions


CommandTreeEvent

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • customtreectrl »
  • CommandTreeEvent

CommandTreeEvent

CommandTreeEvent is a special subclassing of wx.PyCommandEvent.

Note

Not all the accessors make sense for all the events, see the event description for every method in this class.

hierarchy Inheritance Diagram

Inheritance diagram for: CommandTreeEvent

Inheritance diagram of CommandTreeEvent

subclasses Known Subclasses

  • customtreectrl.TreeEvent

Methods Summary

__init__ | Default class constructor.
GetItem | Gets the item on which the operation was performed or the newly selected
GetKeyCode | Returns the virtual key code.
GetKeyEvent | Returns the keyboard data (for EVT_TREE_KEY_DOWN event only).
GetLabel | Returns the item text (for EVT_TREE_BEGIN_LABEL_EDIT and
GetOldItem | Returns the previously selected item for EVT_TREE_SEL_CHANGED and
GetPoint | Returns the point where the mouse was when the drag operation started
GetToolTip | Returns the tooltip for the item (for EVT_TREE_ITEM_GETTOOLTIP events).
IsEditCancelled | Returns the edit cancel flag (for EVT_TREE_BEGIN_LABEL_EDIT and
SetEditCanceled | Sets the edit cancel flag (for EVT_TREE_BEGIN_LABEL_EDIT and
SetItem | Sets the item on which the operation was performed or the newly selected
SetKeyEvent | Sets the keyboard data (for EVT_TREE_KEY_DOWN event only).
SetLabel | Sets the item text (for EVT_TREE_BEGIN_LABEL_EDIT and
SetOldItem | Returns the previously selected item for EVT_TREE_SEL_CHANGED and
SetPoint | Sets the point where the mouse was when the drag operation started
SetToolTip | Sets the tooltip for the item (for EVT_TREE_ITEM_GETTOOLTIP events).

API Class API

class CommandTreeEvent(wx.PyCommandEvent) [source]

CommandTreeEvent is a special subclassing of wx.PyCommandEvent.

Note

Not all the accessors make sense for all the events, see the event description for every method in this class.

__init__(evtType, evtId, item=None, evtKey=None, point=None, label=None) [source]

Default class constructor. For internal use: do not call it in your code!

Parameters:
  • evtType (integer) – the event type;
  • evtId (integer) – the event identifier;
  • item – an instance of GenericTreeItem;
  • evtKey (integer) – a character ordinal;
  • point – an instance of wx.Point;
  • label (string) – a GenericTreeItem text label.

GetItem() [source]

Gets the item on which the operation was performed or the newly selected item for EVT_TREE_SEL_CHANGED and EVT_TREE_SEL_CHANGING events.

Returns: An instance of GenericTreeItem.

GetKeyCode() [source]

Returns the virtual key code. ASCII events return normal ASCII values, while non-ASCII events return values such as wx.WXK_LEFT for the left cursor key.

This method is for EVT_TREE_KEY_DOWN events only.

Returns: An integer representing the virtual key code.

Note

In Unicode build, the returned value is meaningful only if the user entered a character that can be represented in current locale’s default charset. You can obtain the corresponding Unicode character using GetUnicodeKey.

GetKeyEvent() [source]

Returns the keyboard data (for EVT_TREE_KEY_DOWN event only).

Returns: An instance of wx.KeyEvent.

GetLabel() [source]

Returns the item text (for EVT_TREE_BEGIN_LABEL_EDIT and EVT_TREE_END_LABEL_EDIT events only).

Returns: A string containing the item text.

GetOldItem() [source]

Returns the previously selected item for EVT_TREE_SEL_CHANGED and EVT_TREE_SEL_CHANGING events.

Returns: An instance of GenericTreeItem.

GetPoint() [source]

Returns the point where the mouse was when the drag operation started (for EVT_TREE_BEGIN_DRAG and EVT_TREE_BEGIN_RDRAG events only) or the click position.

Returns: An instance of wx.Point.

GetToolTip() [source]

Returns the tooltip for the item (for EVT_TREE_ITEM_GETTOOLTIP events).

Returns: A string containing the item tooltip.

IsEditCancelled() [source]

Returns the edit cancel flag (for EVT_TREE_BEGIN_LABEL_EDIT and EVT_TREE_END_LABEL_EDIT events only).

Returns: True is the item editing has been cancelled, False otherwise.

SetEditCanceled(editCancelled) [source]

Sets the edit cancel flag (for EVT_TREE_BEGIN_LABEL_EDIT and EVT_TREE_END_LABEL_EDIT events only).

Parameters: editCancelled (bool) – True to cancel the editing, False otherwise.

SetItem(item) [source]

Sets the item on which the operation was performed or the newly selected item for EVT_TREE_SEL_CHANGED and EVT_TREE_SEL_CHANGING events.

Parameters: item – an instance of GenericTreeItem.

SetKeyEvent(event) [source]

Sets the keyboard data (for EVT_TREE_KEY_DOWN event only).

Parameters: event – a CommandTreeEvent event to be processed.

SetLabel(label) [source]

Sets the item text (for EVT_TREE_BEGIN_LABEL_EDIT and EVT_TREE_END_LABEL_EDIT events only).

Parameters: label (string) – a string containing the new item text.

SetOldItem(item) [source]

Returns the previously selected item for EVT_TREE_SEL_CHANGED and EVT_TREE_SEL_CHANGING events.

Parameters: item – an instance of GenericTreeItem.

SetPoint(pt) [source]

Sets the point where the mouse was when the drag operation started (for EVT_TREE_BEGIN_DRAG and EVT_TREE_BEGIN_RDRAG events only) or the click position.

Parameters: pt – an instance of wx.Point.

SetToolTip(toolTip) [source]

Sets the tooltip for the item (for EVT_TREE_ITEM_GETTOOLTIP events).

Parameters: tooltip (string) – a string representing the item tooltip.

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • infobar
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • customtreectrl »
  • CommandTreeEvent


CustomTreeCtrl

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • customtreectrl »
  • CustomTreeCtrl

CustomTreeCtrl

CustomTreeCtrl is a class that mimics the behaviour of wx.TreeCtrl, with almost the same base functionalities plus some more enhancements. This class does not rely on the native control, as it is a full owner-drawn tree control.

hierarchy Inheritance Diagram

Inheritance diagram for: CustomTreeCtrl

Inheritance diagram of CustomTreeCtrl

subclasses Known Subclasses

  • hypertreelist.TreeListMainWindow

appearance Control Appearance

CustomTreeCtrl

Methods Summary

__init__ | Default class constructor.
AcceptsFocus | Can this window be given focus by mouse click? ..
AddRoot | Adds a root item to the CustomTreeCtrl.
AdjustMyScrollbars | Internal method used to adjust the wx.PyScrolledWindow scrollbars.
AppendItem | Appends an item as a last child of its parent.
AppendSeparator | Appends an horizontal line separator as a last child of its parent.
AssignButtonsImageList | Assigns the button image list.
AssignImageList | Assigns the normal image list.
AssignLeftImageList | Assigns the image list for CustomTreeCtrl filled with images to be used on
AssignStateImageList | Assigns the state image list.
AutoCheckChild | Transverses the tree and checks/unchecks the items.
AutoCheckParent | Traverses up the tree and checks/unchecks parent items.
AutoToggleChild | Transverses the tree and toggles the items.
CalculateLevel | Calculates the level of an item inside the tree hierarchy.
CalculateLineHeight | Calculates the height of a line.
CalculatePositions | Calculates all the positions of the visible items.
CalculateSize | Calculates overall position and size of an item.
CheckChilds | Programatically check/uncheck item children.
CheckItem | Actually checks/uncheks an item, sending (eventually) the two
CheckItem2 | Used internally to avoid EVT_TREE_ITEM_CHECKED events.
CheckSameLevel | Uncheck radio items which are on the same level of the checked one.
ChildrenClosing | We are about to destroy the item children.
Collapse | Collapse an item, sending a EVT_TREE_ITEM_COLLAPSING and
CollapseAndReset | Collapse the given item and deletes its children.
Delete | Deletes an item.
DeleteAllItems | Deletes all items in the CustomTreeCtrl.
DeleteChildren | Delete all the item’s children.
DeleteItemWindow | Deletes the window associated to an item (if any).
DoGetBestSize | Gets the size which best suits the window: for a control, it would be the
DoInsertItem | Actually inserts an item in the tree.
DoSelectItem | Actually selects/unselects an item, sending EVT_TREE_SEL_CHANGING and
DrawHorizontalGradient | Gradient fill from colour 1 to colour 2 from left to right.
DrawVerticalGradient | Gradient fill from colour 1 to colour 2 from top to bottom.
DrawVistaRectangle | Draws the selected item(s) with the Windows Vista style.
Edit | Internal function.
EditLabel | Starts editing an item label.
EnableChildren | Enables/disables the item children.
EnableItem | Enables/disables an item.
EnableSelectionGradient | Globally enables/disables drawing of gradient selections.
EnableSelectionVista | Globally enables/disables drawing of Windows Vista selections.
EnsureVisible | Scrolls and/or expands items to ensure that the given item is visible.
Expand | Expands an item, sending a EVT_TREE_ITEM_EXPANDING and
ExpandAll | Expands all CustomTreeCtrl items.
ExpandAllChildren | Expands all the items children of the input item.
FillArray | Internal function.
FindItem | Finds the first item starting with the given prefix after the given parent.
Freeze | Freeze CustomTreeCtrl.
GetAGWWindowStyleFlag | Returns the CustomTreeCtrl style.
GetBackgroundImage | Returns the CustomTreeCtrl background image (if any).
GetBorderPen | Returns the pen used to draw the selected item border.
GetBoundingRect | Retrieves the rectangle bounding the item.
GetButtonsImageList | Returns the buttons image list associated with CustomTreeCtrl (from
GetChildrenCount | Returns the item children count.
GetClassDefaultAttributes | Returns the default font and colours which are used by the control.
GetConnectionPen | Returns the pen used to draw the connecting lines between items.
GetControlBmp | Returns a native looking checkbox or radio button bitmap.
GetCount | Returns the global number of items in the tree.
GetDisabledColour | Returns the colour for items in a disabled state.
GetEditControl | Returns a pointer to the edit TreeTextCtrl if the item is being edited or
GetFirstChild | Returns the item’s first child and an integer value ‘cookie’.
GetFirstGradientColour | Returns the first gradient colour for gradient-style selections.
GetFirstVisibleItem | Returns the first visible item.
GetGradientStyle | Returns the gradient style for gradient-style selections.
GetHilightFocusColour | Returns the colour used to highlight focused selected items.
GetHilightNonFocusColour | Returns the colour used to highlight unfocused selected items.
GetHyperTextFont | Returns the font used to render hypertext items.
GetHyperTextNewColour | Returns the colour used to render a non-visited hypertext item.
GetHyperTextVisitedColour | Returns the colour used to render a visited hypertext item.
GetImageList | Returns the normal image list associated with CustomTreeCtrl.
GetImageListCheck | Returns the image list used to build the check/radio buttons in CustomTreeCtrl.
GetIndent | Returns the item indentation, in pixels.
GetItem3StateValue | Gets the state of a 3-state checkbox item.
GetItemBackgroundColour | Returns the item background colour.
GetItemFont | Returns the item font.
GetItemImage | Returns the item image.
GetItemLeftImage | Returns the item leftmost image, i.e.
GetItemParent | Returns the item parent (can be None for root items).
GetItemPyData | Returns the data associated to an item.
GetItemSize | Returns the horizontal space available in CustomTreeCtrl, in pixels, to draw this item.
GetItemText | Returns the item text.
GetItemTextColour | Returns the item text colour or separator horizontal line colour.
GetItemType | Returns the item type.
GetItemVisited | Returns whether an hypertext item was visited.
GetItemWindow | Returns the window associated to the item (if any).
GetItemWindowEnabled | Returns whether the window associated to the item is enabled.
GetLastChild | Returns the item last child.
GetLeftImageList | Returns the image list for CustomTreeCtrl filled with images to be used on
GetLineHeight | Returns the line height for the given item.
GetMaxWidth | Returns the maximum width of the CustomTreeCtrl.
GetNext | Returns the next item.
GetNextActiveItem | Returns the next active item.
GetNextChild | Returns the item’s next child.
GetNextExpanded | Returns the next expanded item after the input one.
GetNextSibling | Returns the next sibling of an item.
GetNextVisible | Returns the next visible item.
GetPrev | Returns the previous item.
GetPrevExpanded | Returns the previous expanded item before the input one.
GetPrevSibling | Returns the previous sibling of an item.
GetPrevVisible | Returns the previous visible item.
GetPyData | Returns the data associated to an item.
GetRootItem | Returns the root item, an instance of GenericTreeItem.
GetSecondGradientColour | Returns the second gradient colour for gradient-style selections.
GetSelection | Returns the current selection.
GetSelections | Returns a list of selected items.
GetSeparatorColour | Returns the pen colour for separator-type items.
GetSpacing | Returns the spacing between the start and the text, in pixels.
GetStateImageList | Returns the state image list associated with CustomTreeCtrl (from which
HandleHyperLink | Handles the hyperlink items, sending the EVT_TREE_ITEM_HYPERLINK event.
HasAGWFlag | Returns True if CustomTreeCtrl has the flag bit set.
HasButtons | Returns whether CustomTreeCtrl has the TR_HAS_BUTTONS flag set.
HasChildren | Returns whether an item has children or not.
HideWindows | Hides the windows associated to the items.
HitTest | Calculates which (if any) item is under the given point, returning the tree item at this point plus extra information flags.
InsertItem | Inserts an item after the given previous.
InsertItemByIndex | Inserts an item after the given previous.
InsertItemByItem | Inserts an item after the given previous.
InsertSeparator | Inserts a separator item after the given previous.
IsBold | Returns whether the item font is bold or not.
IsDescendantOf | Checks if the given item is under another one in the tree hierarchy.
IsExpanded | Returns whether the item is expanded or not.
IsItalic | Returns whether the item font is italic or not.
IsItem3State | Returns whether or not the checkbox item is a 3-state checkbox.
IsItemChecked | Returns whether an item is checked or not.
IsItemEnabled | Returns whether an item is enabled or disabled.
IsItemHyperText | Returns whether an item is hypertext or not.
IsItemSeparator | Returns whether an item is of separator type or not.
IsSelected | Returns whether the item is selected or not.
IsVisible | Returns whether the item is visible or not (i.e., its hierarchy is expanded enough to show the item).
ItemHasChildren | Returns whether the item has children or not.
OnAcceptEdit | Called by TreeTextCtrl, to accept the changes and to send the
OnCancelEdit | Called by TreeTextCtrl, to cancel the changes and to send the
OnCompareItems | Returns whether 2 items have the same text.
OnDestroy | Handles the wx.EVT_WINDOW_DESTROY event for CustomTreeCtrl.
OnEditTimer | The timer for editing has expired.
OnEraseBackground | Handles the wx.EVT_ERASE_BACKGROUND event for CustomTreeCtrl.
OnGetToolTip | Process the tooltip event, to speed up event processing.
OnInternalIdle | This method is normally only used internally, but sometimes an application
OnKeyDown | Handles the wx.EVT_KEY_DOWN event for CustomTreeCtrl, sending a
OnKillFocus | Handles the wx.EVT_KILL_FOCUS event for CustomTreeCtrl.
OnMouse | Handles a bunch of wx.EVT_MOUSE_EVENTS events for CustomTreeCtrl.
OnPaint | Handles the wx.EVT_PAINT event for CustomTreeCtrl.
OnSetFocus | Handles the wx.EVT_SET_FOCUS event for CustomTreeCtrl.
OnSize | Handles the wx.EVT_SIZE event for CustomTreeCtrl.
PaintItem | Actually draws an item.
PaintLevel | Paint a level in the hierarchy of CustomTreeCtrl.
PrependItem | Prepends an item as a first child of parent.
PrependSeparator | Prepends a separator item as a first child of parent.
RecurseOnChildren | Recurses over all the children of the spcified items, calculating their maximum width.
RefreshItemWithWindows | Refreshes the items with which a window is associated.
RefreshLine | Refreshes a damaged item line.
RefreshSelected | Refreshes a damaged selected item line.
RefreshSelectedUnder | Refreshes the selected items under the given item.
RefreshSubtree | Refreshes a damaged subtree of an item.
ResetEditControl | Called by TreeTextCtrl when it marks itself for deletion.
ScrollTo | Scrolls the specified item into view.
SelectAll | Selects all the item in the tree.
SelectAllChildren | Selects all the children of the given item.
SelectItem | Selects/deselects an item.
SelectItemRange | Selects all the items between item1 and item2.
SendDeleteEvent | Actually sends the EVT_TREE_DELETE_ITEM event.
SetAGWWindowStyleFlag | Sets the CustomTreeCtrl window style.
SetBackgroundColour | Changes the background colour of CustomTreeCtrl.
SetBackgroundImage | Sets the CustomTreeCtrl background image.
SetBorderPen | Sets the pen used to draw the selected item border.
SetButtonsImageList | Sets the buttons image list for CustomTreeCtrl (from which application-defined
SetConnectionPen | Sets the pen used to draw the connecting lines between items.
SetDisabledColour | Sets the colour for items in a disabled state.
SetFirstGradientColour | Sets the first gradient colour for gradient-style selections.
SetFont | Sets the CustomTreeCtrl font.
SetForegroundColour | Changes the foreground colour of CustomTreeCtrl.
SetGradientStyle | Sets the gradient style for gradient-style selections.
SetHilightFocusColour | Sets the colour used to highlight focused selected items.
SetHilightNonFocusColour | Sets the colour used to highlight unfocused selected items.
SetHyperTextFont | Sets the font used to render hypertext items.
SetHyperTextNewColour | Sets the colour used to render a non-visited hypertext item.
SetHyperTextVisitedColour | Sets the colour used to render a visited hypertext item.
SetImageList | Sets the normal image list for CustomTreeCtrl.
SetImageListCheck | Sets the checkbox/radiobutton image list.
SetIndent | Sets the indentation for CustomTreeCtrl.
SetItem3State | Sets whether the item has a 3-state value checkbox assigned to it or not.
SetItem3StateValue | Sets the checkbox item to the given state.
SetItemBackgroundColour | Sets the item background colour.
SetItemBold | Sets the item font as bold/unbold.
SetItemDropHighlight | Gives the item the visual feedback for drag and drop operations.
SetItemFont | Sets the item font.
SetItemHasChildren | Forces the appearance/disappearance of the button next to the item.
SetItemHyperText | Sets whether the item is hypertext or not.
SetItemImage | Sets the item image, depending on the item state.
SetItemItalic | Sets the item font as italic/non-italic.
SetItemLeftImage | Sets the item leftmost image, i.e.
SetItemPyData | Sets the data associated to an item.
SetItemText | Sets the item text.
SetItemTextColour | Sets the item text colour or separator horizontal line colour.
SetItemType | Sets the item type.
SetItemVisited | Sets whether an hypertext item was visited.
SetItemWindow | Sets the window for the given item.
SetItemWindowEnabled | Enables/disables the window associated to the item.
SetLeftImageList | Sets the image list for CustomTreeCtrl filled with images to be used on
SetPyData | Sets the data associated to an item.
SetSecondGradientColour | Sets the second gradient colour for gradient-style selections.
SetSeparatorColour | Sets the pen colour for separator-type items.
SetSpacing | Sets the spacing between items in CustomTreeCtrl.
SetStateImageList | Sets the state image list for CustomTreeCtrl (from which application-defined
ShouldInheritColours | Return True from here to allow the colours of this window to be
SortChildren | Sorts the children of the given item using the OnCompareItems method of
TagAllChildrenUntilLast | Used internally.
TagNextChildren | Used internally.
Thaw | Thaw CustomTreeCtrl.
TileBackground | Tiles the background image to fill all the available area.
Toggle | Toggles the item state (collapsed/expanded).
ToggleItemSelection | Toggles the item selection.
UnCheckRadioParent | Used internally to handle radio node parent correctly.
Unselect | Unselects the current selection.
UnselectAll | Unselect all the items.
UnselectAllChildren | Unselects all the children of the given item.

API Class API

class CustomTreeCtrl(wx.PyScrolledWindow) [source]

CustomTreeCtrl is a class that mimics the behaviour of wx.TreeCtrl, with almost the same base functionalities plus some more enhancements. This class does not rely on the native control, as it is a full owner-drawn tree control.

__init__(parent, id=wx.ID_ANY, pos=wx.DefaultPosition, size=wx.DefaultSize, style=0, agwStyle=TR_DEFAULT_STYLE, validator=wx.DefaultValidator, name="CustomTreeCtrl") [source]

Default class constructor.

Parameters:
  • parent (wx.Window) – parent window. Must not be None;
  • id (integer) – window identifier. A value of -1 indicates a default value;
  • pos (tuple or wx.Point) – the control position. A value of (-1, -1) indicates a default position, chosen by either the windowing system or wxPython, depending on platform;
  • size (tuple or wx.Size) – the control size. A value of (-1, -1) indicates a default size, chosen by either the windowing system or wxPython, depending on platform;
  • style (integer) – the underlying wx.PyScrolledWindow style;
  • agwStyle (integer) – the AGW-specific window style for CustomTreeCtrl. It can be a combination of the following bits:

    integer parameter settings
    Window Styles | Hex Value | Description
    TR_NO_BUTTONS | 0x0 | For convenience to document that no buttons are to be drawn.
    TR_SINGLE | 0x0 | For convenience to document that only one item may be selected at a time. Selecting another item causes the current selection, if any, to be deselected. This is the default.
    TR_HAS_BUTTONS | 0x1 | Use this style to show + and - buttons to the left of parent items.
    TR_NO_LINES | 0x4 | Use this style to hide vertical level connectors.
    TR_LINES_AT_ROOT | 0x8 | Use this style to show lines between root nodes. Only applicable if TR_HIDE_ROOT is set and TR_NO_LINES is not set.
    TR_DEFAULT_STYLE | 0x9 | The set of flags that are closest to the defaults for the native control for a particular toolkit.
    TR_TWIST_BUTTONS | 0x10 | Use old Mac-twist style buttons.
    TR_MULTIPLE | 0x20 | Use this style to allow a range of items to be selected. If a second range is selected, the current range, if any, is deselected.
    TR_EXTENDED | 0x40 | Use this style to allow disjoint items to be selected. (Only partially implemented; may not work in all cases).
    TR_HAS_VARIABLE_ROW_HEIGHT | 0x80 | Use this style to cause row heights to be just big enough to fit the content. If not set, all rows use the largest row height. The default is that this flag is unset.
    TR_EDIT_LABELS | 0x200 | Use this style if you wish the user to be able to edit labels in the tree control.
    TR_ROW_LINES | 0x400 | Use this style to draw a contrasting border between displayed rows.
    TR_HIDE_ROOT | 0x800 | Use this style to suppress the display of the root node, effectively causing the first-level nodes to appear as a series of root nodes.
    TR_FULL_ROW_HIGHLIGHT | 0x2000 | Use this style to have the background colour and the selection highlight extend over the entire horizontal row of the tree control window.
    TR_AUTO_CHECK_CHILD | 0x4000 | Only meaningful foe checkbox-type items: when a parent item is checked/unchecked its children are checked/unchecked as well.
    TR_AUTO_TOGGLE_CHILD | 0x8000 | Only meaningful foe checkbox-type items: when a parent item is checked/unchecked its children are toggled accordingly.
    TR_AUTO_CHECK_PARENT | 0x10000 | Only meaningful foe checkbox-type items: when a child item is checked/unchecked its parent item is checked/unchecked as well.
    TR_ALIGN_WINDOWS | 0x20000 | Flag used to align windows (in items with windows) at the same horizontal position.
    TR_ALIGN_WINDOWS_RIGHT | 0x40000 | Flag used to align windows (in items with windows) to the rightmost edge of CustomTreeCtrl.
    TR_ELLIPSIZE_LONG_ITEMS | 0x80000 | Flag used to ellipsize long items when the horizontal space for CustomTreeCtrl is low.
    TR_TOOLTIP_ON_LONG_ITEMS | 0x100000 | Flag used to show tooltips on long items when the horizontal space for CustomTreeCtrl is low.
  • validator (wx.Validator) – window validator;
  • name (string) – window name.

AcceptsFocus() [source]

Can this window be given focus by mouse click?

Note

This method always returns True as we always accept focus from mouse click.

Note

Overridden from wx.PyScrolledWindow.

AddRoot(text, ct_type=0, wnd=None, image=-1, selImage=-1, data=None) [source]

Adds a root item to the CustomTreeCtrl.

Parameters:
  • text (string) – the item text label;
  • ct_type (integer) – the item type (see SetItemType for a list of valid item types);
  • wnd – if not None, a non-toplevel window to show next to the item, any subclass of wx.Window except top-level windows;
  • image (integer) – an index within the normal image list specifying the image to use for the item in unselected state;
  • selImage (integer) – an index within the normal image list specifying the image to use for the item in selected state; if image > -1 and selImage is -1, the same image is used for both selected and unselected items;
  • data (object) – associate the given Python object data with the item.
Returns:

An instance of GenericTreeItem upon successful insertion.
Raise :

Exception in the following cases:

  • There already is a root item in the tree;
  • The item window is not None but the TR_HAS_VARIABLE_ROW_HEIGHT flag has not been set for CustomTreeCtrl;
  • The item has multiline text (with line-breaks in it) but the TR_HAS_VARIABLE_ROW_HEIGHT flag has not been set for CustomTreeCtrl;
  • The ct_type attribute is less than 0 or greater than 2.

Warning

only one root is allowed to exist in any given instance of CustomTreeCtrl.

AdjustMyScrollbars() [source]

Internal method used to adjust the wx.PyScrolledWindow scrollbars.

AppendItem(parentId, text, ct_type=0, wnd=None, image=-1, selImage=-1, data=None) [source]

Appends an item as a last child of its parent.

Parameters:
  • parentId – an instance of GenericTreeItem representing the item’s parent;
  • text (string) – the item text label;
  • ct_type (integer) – the item type (see SetItemType for a list of valid item types);
  • wnd – if not None, a non-toplevel window to show next to the item, any subclass of wx.Window;

  • image (integer) – an index within the normal image list specifying the image to use for the item in unselected state;
  • selImage (integer) – an index within the normal image list specifying the image to use for the item in selected state; if image > -1 and selImage is -1, the same image is used for both selected and unselected items;
  • data (object) – associate the given Python object data with the item.
Returns:

An instance of GenericTreeItem upon successful insertion.

See also

DoInsertItem for possible exceptions generated by this method.

AppendSeparator(parentId) [source]

Appends an horizontal line separator as a last child of its parent.

Parameters: parentId – an instance of GenericTreeItem representing the separator’s parent.
Returns: An instance of GenericTreeItem upon successful insertion.

See also

DoInsertItem for possible exceptions generated by this method.

AssignButtonsImageList(imageList) [source]

Assigns the button image list.

Parameters: imageList – an instance of wx.ImageList.

AssignImageList(imageList) [source]

Assigns the normal image list.

Parameters: imageList – an instance of wx.ImageList.

AssignLeftImageList(imageList) [source]

Assigns the image list for CustomTreeCtrl filled with images to be used on the leftmost part of the client area. Any item can have a leftmost image associated with it.

Parameters: imageList – an instance of wx.ImageList.

AssignStateImageList(imageList) [source]

Assigns the state image list.

Parameters: imageList – an instance of wx.ImageList.

AutoCheckChild(item, checked) [source]

Transverses the tree and checks/unchecks the items.

Parameters:
  • item – an instance of GenericTreeItem;
  • checked (bool) – True to check an item, False to uncheck it.

Note

This method is meaningful only for checkbox-like and radiobutton-like items.

AutoCheckParent(item, checked) [source]

Traverses up the tree and checks/unchecks parent items.

Parameters:
  • item – an instance of GenericTreeItem;
  • checked (bool) – True to check an item, False to uncheck it.

Note

This method is meaningful only for checkbox-like and radiobutton-like items.

AutoToggleChild(item) [source]

Transverses the tree and toggles the items.

Parameters: item – an instance of GenericTreeItem.

Note

This method is meaningful only for checkbox-like and radiobutton-like items.

CalculateLevel(item, dc, level, y, align=0) [source]

Calculates the level of an item inside the tree hierarchy.

Parameters:
  • item – an instance of GenericTreeItem;
  • dc – an instance of wx.DC;
  • level (integer) – the item level in the tree hierarchy;
  • y (integer) – the current vertical position inside the wx.PyScrolledWindow;
  • align (integer) – an integer specifying the alignment type:

    integer parameter settings
    align Value | Description
    0 | No horizontal alignment of windows (in items with windows).
    1 | Windows (in items with windows) are aligned at the same horizontal position.
    2 | Windows (in items with windows) are aligned at the rightmost edge of CustomTreeCtrl.
Returns:

The new y vertical position inside the wx.PyScrolledWindow.

CalculateLineHeight() [source]

Calculates the height of a line.

CalculatePositions() [source]

Calculates all the positions of the visible items.

CalculateSize(item, dc, level=-1, align=0) [source]

Calculates overall position and size of an item.

Parameters:
  • item – an instance of GenericTreeItem;
  • dc – an instance of wx.DC;

  • level (integer) – the item level in the tree hierarchy;
  • align (integer) – an integer specifying the alignment type:

    integer parameter settings
    align Value | Description
    0 | No horizontal alignment of windows (in items with windows).
    1 | Windows (in items with windows) are aligned at the same horizontal position.
    2 | Windows (in items with windows) are aligned at the rightmost edge of CustomTreeCtrl.

CheckChilds(item, checked=True) [source]

Programatically check/uncheck item children.

Parameters:
  • item – an instance of GenericTreeItem;
  • checked (bool) – True to check an item, False to uncheck it.

Note

This method is meaningful only for checkbox-like and radiobutton-like items.

Note

This method does not generate EVT_TREE_ITEM_CHECKING and EVT_TREE_ITEM_CHECKED events.

CheckItem(item, checked=True) [source]

Actually checks/uncheks an item, sending (eventually) the two events EVT_TREE_ITEM_CHECKING and EVT_TREE_ITEM_CHECKED.

Parameters:
  • item – an instance of GenericTreeItem;
  • checked (bool) – for a radiobutton-type item, True to check it, False to uncheck it. For a checkbox-type item, it can be one of wx.CHK_UNCHECKED when the checkbox is unchecked, wx.CHK_CHECKED when it is checked and wx.CHK_UNDETERMINED when it’s in the undetermined state.

CheckItem2(item, checked=True, torefresh=False) [source]

Used internally to avoid EVT_TREE_ITEM_CHECKED events.

Parameters:
  • item – an instance of GenericTreeItem;
  • checked (bool) – True to check an item, False to uncheck it;
  • torefresh (bool) – whether to redraw the item or not.

CheckSameLevel(item, checked=False) [source]

Uncheck radio items which are on the same level of the checked one. Used internally.

Parameters:
  • item – an instance of GenericTreeItem;
  • checked (bool) – True to check an item, False to uncheck it.

Note

This method is meaningful only for radiobutton-like items.

ChildrenClosing(item) [source]

We are about to destroy the item children.

Parameters: item – an instance of GenericTreeItem.

Collapse(item) [source]

Collapse an item, sending a EVT_TREE_ITEM_COLLAPSING and EVT_TREE_ITEM_COLLAPSED events.

Parameters: item – an instance of GenericTreeItem.
Raise : Exception if you try to collapse a hidden root (i.e., when the TR_HIDE_ROOT style is set for CustomTreeCtrl).

CollapseAndReset(item) [source]

Collapse the given item and deletes its children.

Parameters: item – an instance of GenericTreeItem.

Delete(item) [source]

Deletes an item.

Parameters: item – an instance of GenericTreeItem.

Note

This method sends the EVT_TREE_DELETE_ITEM event.

DeleteAllItems() [source]

Deletes all items in the CustomTreeCtrl.

DeleteChildren(item) [source]

Delete all the item’s children.

Parameters: item – an instance of GenericTreeItem.

DeleteItemWindow(item) [source]

Deletes the window associated to an item (if any).

Parameters: item – an instance of GenericTreeItem.

DoGetBestSize() [source]

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

Returns: An instance of wx.Size.

Note

Overridden from wx.PyScrolledWindow.

DoInsertItem(parentId, previous, text, ct_type=0, wnd=None, image=-1, selImage=-1, data=None, separator=False) [source]

Actually inserts an item in the tree.

Parameters:
  • parentId – an instance of GenericTreeItem representing the item’s parent;
  • previous (integer) – the index at which we should insert the item;
  • text (string) – the item text label;
  • ct_type (integer) – the item type (see SetItemType for a list of valid item types);
  • wnd – if not None, a non-toplevel window to show next to the item, any subclass of wx.Window except top-level windows;

  • image (integer) – an index within the normal image list specifying the image to use for the item in unselected state;
  • selImage (integer) – an index within the normal image list specifying the image to use for the item in selected state; if image > -1 and selImage is -1, the same image is used for both selected and unselected items;
  • data (object) – associate the given Python object data with the item;
  • separator (bool) – True if the item is a separator, False otherwise.
Returns:

An instance of GenericTreeItem upon successful insertion.
Raise :

Exception in the following cases:

  • The item window is not None but the TR_HAS_VARIABLE_ROW_HEIGHT flag has not been set for CustomTreeCtrl;
  • The item has multiline text (with line-breaks in it) but the TR_HAS_VARIABLE_ROW_HEIGHT flag has not been set for CustomTreeCtrl;
  • The ct_type attribute is less than 0 or greater than 2;
  • The parent item is a separator;
  • The item is a separator but it has text or an associated window.

Note

Separator items should not have children, text labels or an associated window.

DoSelectItem(item, unselect_others=True, extended_select=False) [source]

Actually selects/unselects an item, sending EVT_TREE_SEL_CHANGING and EVT_TREE_SEL_CHANGED events.

Parameters:
  • item – an instance of GenericTreeItem;
  • unselect_others (bool) – if True, all the other selected items are unselected.
  • extended_select (bool) – True if the CustomTreeCtrl is using the TR_EXTENDED style.

DrawHorizontalGradient(dc, rect, hasfocus) [source]

Gradient fill from colour 1 to colour 2 from left to right.

Parameters:
  • dc – an instance of wx.DC;

  • rect (wx.Rect) – the rectangle to be filled with the gradient shading;
  • hasfocus (bool) – True if the main CustomTreeCtrl has focus, False otherwise.

DrawVerticalGradient(dc, rect, hasfocus) [source]

Gradient fill from colour 1 to colour 2 from top to bottom.

Parameters:
  • dc – an instance of wx.DC;

  • rect (wx.Rect) – the rectangle to be filled with the gradient shading;
  • hasfocus (bool) – True if the main CustomTreeCtrl has focus, False otherwise.

DrawVistaRectangle(dc, rect, hasfocus) [source]

Draws the selected item(s) with the Windows Vista style.

Parameters:
  • dc – an instance of wx.DC;

  • rect (wx.Rect) – the rectangle to be filled with the gradient shading;
  • hasfocus (bool) – True if the main CustomTreeCtrl has focus, False otherwise.

Edit(item) [source]

Internal function. Starts the editing of an item label, sending a EVT_TREE_BEGIN_LABEL_EDIT event.

Parameters: item – an instance of GenericTreeItem.

Warning

Separator-type items can not be edited.

EditLabel(item) [source]

Starts editing an item label.

Parameters: item – an instance of GenericTreeItem.

EnableChildren(item, enable=True) [source]

Enables/disables the item children.

Parameters:
  • item – an instance of GenericTreeItem;
  • enable (bool) – True to enable the children, False to disable them.

Note

This method is used internally.

EnableItem(item, enable=True, torefresh=True) [source]

Enables/disables an item.

Parameters:
  • item – an instance of GenericTreeItem;
  • enable (bool) – True to enable the item, False to disable it;
  • torefresh (bool) – whether to redraw the item or not.

EnableSelectionGradient(enable=True) [source]

Globally enables/disables drawing of gradient selections.

Parameters: enable (bool) – True to enable gradient-style selections, False to disable it.

Note

Calling this method disables any Vista-style selection previously enabled.

EnableSelectionVista(enable=True) [source]

Globally enables/disables drawing of Windows Vista selections.

Parameters: enable (bool) – True to enable Vista-style selections, False to disable it.

Note

Calling this method disables any gradient-style selection previously enabled.

EnsureVisible(item) [source]

Scrolls and/or expands items to ensure that the given item is visible.

Parameters: item – an instance of GenericTreeItem.

Expand(item) [source]

Expands an item, sending a EVT_TREE_ITEM_EXPANDING and EVT_TREE_ITEM_EXPANDED events.

Parameters: item – an instance of GenericTreeItem.
Raise : Exception if you try to expand a hidden root (i.e., when the TR_HIDE_ROOT style is set for CustomTreeCtrl).

ExpandAll() [source]

Expands all CustomTreeCtrl items.

Note

This method suppresses the EVT_TREE_ITEM_EXPANDING and EVT_TREE_ITEM_EXPANDED events because expanding many items int the control would be too slow then.

ExpandAllChildren(item) [source]

Expands all the items children of the input item.

Parameters: item – an instance of GenericTreeItem.

Note

This method suppresses the EVT_TREE_ITEM_EXPANDING and EVT_TREE_ITEM_EXPANDED events because expanding many items int the control would be too slow then.

FillArray(item, array=[]) [source]

Internal function. Used to populate an array of selected items when the style TR_MULTIPLE is used.

Parameters:
  • item – an instance of GenericTreeItem;
  • array (list) – a Python list containing the selected items.
Returns:

A Python list containing the selected items.

FindItem(idParent, prefixOrig) [source]

Finds the first item starting with the given prefix after the given parent.

Parameters:
  • idParent (integer) – an instance of GenericTreeItem;
  • prefixOrig (string) – a string containing the item text prefix.
Returns:

An instance of GenericTreeItem or None if no item has been found.

Freeze() [source]

Freeze CustomTreeCtrl.

Freezes the window or, in other words, prevents any updates from taking place on screen, the window is not redrawn at all. Thaw must be called to reenable window redrawing. Calls to these two functions may be nested.

Note

This method is useful for visual appearance optimization (for example, it is a good idea to use it before doing many large text insertions in a row into a wx.TextCtrl under wxGTK) but is not implemented on all platforms nor for all controls so it is mostly just a hint to wxWidgets and not a mandatory directive.

GetAGWWindowStyleFlag() [source]

Returns the CustomTreeCtrl style.

See also

The __init__ method for a list of possible style flags.

GetBackgroundImage() [source]

Returns the CustomTreeCtrl background image (if any).

Returns: An instance of wx.Bitmap if a background image is present, None otherwise.

Note

At present, the background image can only be used in “tile” mode.

Todo

Support background images also in stretch and centered modes.

GetBorderPen() [source]

Returns the pen used to draw the selected item border.

Returns: An instance of wx.Pen.

Note

The border pen is not used if the Windows Vista selection style is applied.

GetBoundingRect(item, textOnly=False) [source]

Retrieves the rectangle bounding the item.

Parameters:
  • item – an instance of GenericTreeItem;
  • textOnly (bool) – if True, only the rectangle around the item’s label will be returned, otherwise the item’s image is also taken into account.
Returns:

An instance of wx.Rect.

Note

The rectangle coordinates are logical, not physical ones. So, for example, the x coordinate may be negative if the tree has a horizontal scrollbar and its position is not 0.

GetButtonsImageList() [source]

Returns the buttons image list associated with CustomTreeCtrl (from which application-defined button images are taken).

Returns: An instance of wx.ImageList.

GetChildrenCount(item, recursively=True) [source]

Returns the item children count.

Parameters:
  • item – an instance of GenericTreeItem;
  • recursively (bool) – if True, returns the total number of descendants, otherwise only one level of children is counted.

classmethod GetClassDefaultAttributes() [source]

Returns the default font and colours which are used by the control. This is useful if you want to use the same font or colour in your own control as in a standard control – which is a much better idea than hard coding specific colours or fonts which might look completely out of place on the users system, especially if it uses themes.

This static method is “overridden’’ in many derived classes and so calling, for example, wx.Button.GetClassDefaultAttributes() will typically return the values appropriate for a button which will be normally different from those returned by, say, wx.ListCtrl.GetClassDefaultAttributes().

Returns: An instance of wx.VisualAttributes.

Note

The wx.VisualAttributes structure has at least the fields font, colFg and colBg. All of them may be invalid if it was not possible to determine the default control appearance or, especially for the background colour, if the field doesn’t make sense as is the case for colBg for the controls with themed background.

Note

Overridden from wx.PyControl.

GetConnectionPen() [source]

Returns the pen used to draw the connecting lines between items.

Returns: An instance of wx.Pen.

GetControlBmp(checkbox=True, checked=False, enabled=True, x=16, y=16) [source]

Returns a native looking checkbox or radio button bitmap.

Parameters:
  • checkbox (bool) – True to get a checkbox image, False for a radiobutton one;
  • checked (bool) – True if the control is marked, False if it is not;
  • enabled (bool) – True if the control is enabled, False if it is not;
  • x (integer) – the width of the bitmap;
  • y (integer) – the height of the bitmap.
Returns:

An instance of wx.Bitmap, representing a native looking checkbox or radiobutton.

GetCount() [source]

Returns the global number of items in the tree.

GetDisabledColour() [source]

Returns the colour for items in a disabled state.

Returns: An instance of wx.Colour.

GetEditControl() [source]

Returns a pointer to the edit TreeTextCtrl if the item is being edited or None otherwise (it is assumed that no more than one item may be edited simultaneously).

GetFirstChild(item) [source]

Returns the item’s first child and an integer value ‘cookie’. Call GetNextChild for the next child using this very ‘cookie’ return value as an input.

Parameters: item – an instance of GenericTreeItem.
Returns: A tuple with the first value being an instance of GenericTreeItem or None if there are no further children, and as second value an integer parameter ‘cookie’.

Note

This method returns None if there are no further children.

GetFirstGradientColour() [source]

Returns the first gradient colour for gradient-style selections.

Returns: An instance of wx.Colour.

GetFirstVisibleItem() [source]

Returns the first visible item.

Returns: An instance of GenericTreeItem or None if there are no visible items.

GetGradientStyle() [source]

Returns the gradient style for gradient-style selections.

Returns: 0 for horizontal gradient-style selections, 1 for vertical gradient-style selections.

GetHilightFocusColour() [source]

Returns the colour used to highlight focused selected items.

Returns: An instance of wx.Colour.

Note

This is used only if gradient and Windows Vista selection styles are disabled.

GetHilightNonFocusColour() [source]

Returns the colour used to highlight unfocused selected items.

Returns: An instance of wx.Colour.

Note

This is used only if gradient and Windows Vista selection styles are disabled.

GetHyperTextFont() [source]

Returns the font used to render hypertext items.

Returns: An instance of wx.Font.

Note

This method is meaningful only for hypertext-like items.

GetHyperTextNewColour() [source]

Returns the colour used to render a non-visited hypertext item.

Returns: An instance of wx.Colour.

Note

This method is meaningful only for hypertext-like items.

GetHyperTextVisitedColour() [source]

Returns the colour used to render a visited hypertext item.

Returns: An instance of wx.Colour.

Note

This method is meaningful only for hypertext-like items.

GetImageList() [source]

Returns the normal image list associated with CustomTreeCtrl.

Returns: An instance of wx.ImageList.

GetImageListCheck() [source]

Returns the image list used to build the check/radio buttons in CustomTreeCtrl.

Returns: An instance of wx.ImageList.

GetIndent() [source]

Returns the item indentation, in pixels.

GetItem3StateValue(item) [source]

Gets the state of a 3-state checkbox item.

Parameters: item – an instance of GenericTreeItem.
Returns: wx.CHK_UNCHECKED when the checkbox is unchecked, wx.CHK_CHECKED when it is checked and wx.CHK_UNDETERMINED when it’s in the undetermined state.

Note

This method raises an exception when the function is used with a 2-state checkbox item.

Note

This method is meaningful only for checkbox-like items.

GetItemBackgroundColour(item) [source]

Returns the item background colour.

Parameters: item – an instance of GenericTreeItem.
Returns: An instance of wx.Colour.

GetItemFont(item) [source]

Returns the item font.

Parameters: item – an instance of GenericTreeItem.
Returns: An instance of wx.Font.

GetItemImage(item, which=TreeItemIcon_Normal) [source]

Returns the item image.

Parameters:
  • item – an instance of GenericTreeItem;
  • which (integer) – can be one of the following bits:

    integer parameter settings
    Item State | Description
    TreeItemIcon_Normal | To get the normal item image
    TreeItemIcon_Selected | To get the selected item image (i.e. the image which is shown when the item is currently selected)
    TreeItemIcon_Expanded | To get the expanded image (this only makes sense for items which have children - then this image is shown when the item is expanded and the normal image is shown when it is collapsed)
    TreeItemIcon_SelectedExpanded | To get the selected expanded image (which is shown when an expanded item is currently selected)
Returns:

An integer index that can be used to retrieve the item image inside a wx.ImageList.

GetItemLeftImage(item) [source]

Returns the item leftmost image, i.e. the image associated to the item on the leftmost part of the CustomTreeCtrl client area.

Parameters: item – an instance of GenericTreeItem.
Returns: An integer index that can be used to retrieve the item leftmost image inside a wx.ImageList.

GetItemParent(item) [source]

Returns the item parent (can be None for root items).

Parameters: item – an instance of GenericTreeItem.
Returns: An instance of GenericTreeItem or None for root items.

GetItemPyData(item)

Returns the data associated to an item.

Parameters: item – an instance of GenericTreeItem.
Returns: A Python object representing the item data, or None if no data has been assigned to this item.

GetItemSize(item) [source]

Returns the horizontal space available in CustomTreeCtrl, in pixels, to draw this item.

Parameters: item – an instance of GenericTreeItem.

New in version 0.9.3.

GetItemText(item) [source]

Returns the item text.

Parameters: item – an instance of GenericTreeItem.

GetItemTextColour(item) [source]

Returns the item text colour or separator horizontal line colour.

Parameters: item – an instance of GenericTreeItem.
Returns: An instance of wx.Colour.

GetItemType(item) [source]

Returns the item type.

Parameters: item – an instance of GenericTreeItem.
Returns: An integer representing the item type.

See also

SetItemType for a description of valid item types.

GetItemVisited(item) [source]

Returns whether an hypertext item was visited.

Parameters: item – an instance of GenericTreeItem.
Returns: True if the hypertext item has been visited, False otherwise.

Note

This method is meaningful only for hypertext-like items.

GetItemWindow(item) [source]

Returns the window associated to the item (if any).

Parameters: item – an instance of GenericTreeItem.
Returns: An instance of wx.Window if the item has an associated window, None otherwise.

GetItemWindowEnabled(item) [source]

Returns whether the window associated to the item is enabled.

Parameters: item – an instance of GenericTreeItem.
Returns: True if the item has an associated window and this window is enabled, False in all other cases.

GetLastChild(item) [source]

Returns the item last child.

Parameters: item – an instance of GenericTreeItem.
Returns: An instance of GenericTreeItem or None if there are no further children.

GetLeftImageList() [source]

Returns the image list for CustomTreeCtrl filled with images to be used on the leftmost part of the client area. Any item can have a leftmost image associated with it.

Returns: An instance of wx.ImageList.

GetLineHeight(item) [source]

Returns the line height for the given item.

Parameters: item – an instance of GenericTreeItem.
Returns: the item height, in pixels.

GetMaxWidth(respect_expansion_state=True) [source]

Returns the maximum width of the CustomTreeCtrl.

Parameters: respect_expansion_state (bool) – if True, only the expanded items (and their children) will be measured. Otherwise all the items are expanded and their width measured.
Returns: the maximum width of CustomTreeCtrl, in pixels.

GetNext(item) [source]

Returns the next item. Only for internal use right now.

Returns: An instance of GenericTreeItem or None if there are no further items.
Parameters: item – an instance of GenericTreeItem.

GetNextActiveItem(item, down=True) [source]

Returns the next active item. Used Internally at present.

Parameters:
  • item – an instance of GenericTreeItem;
  • down (bool) – True to search downwards in the hierarchy for an active item, False to search upwards.
Returns:

An instance of GenericTreeItem if an active item has been found or None if none has been found.

GetNextChild(item, cookie) [source]

Returns the item’s next child.

Parameters:
  • item – an instance of GenericTreeItem;
  • cookie – a parameter which is opaque for the application but is necessary for the library to make these functions reentrant (i.e. allow more than one enumeration on one and the same object simultaneously).
Returns:

A tuple with the first value being an instance of GenericTreeItem or None if there are no further children, and as second value an integer parameter ‘cookie’.

Note

This method returns None if there are no further children.

GetNextExpanded(item) [source]

Returns the next expanded item after the input one.

Parameters: item – an instance of TreeListItem.

GetNextSibling(item) [source]

Returns the next sibling of an item.

Parameters: item – an instance of GenericTreeItem.
Returns: An instance of GenericTreeItem or None if there are no further siblings.

Note

This method returns None if there are no further siblings.

GetNextVisible(item) [source]

Returns the next visible item.

Parameters: item – an instance of GenericTreeItem.
Returns: An instance of GenericTreeItem or None if there are no next visible items.

GetPrev(item) [source]

Returns the previous item. Only for internal use right now.

Parameters: item – an instance of GenericTreeItem.
Returns: An instance of GenericTreeItem

GetPrevExpanded(item) [source]

Returns the previous expanded item before the input one.

Parameters: item – an instance of TreeListItem.

GetPrevSibling(item) [source]

Returns the previous sibling of an item.

Parameters: item – an instance of GenericTreeItem.
Returns: An instance of GenericTreeItem or None if there are no further siblings.

Note

This method returns None if there are no further siblings.

GetPrevVisible(item) [source]

Returns the previous visible item.

Parameters: item – an instance of GenericTreeItem.
Returns: An instance of GenericTreeItem or None if there are no previous visible items.

GetPyData(item) [source]

Returns the data associated to an item.

Parameters: item – an instance of GenericTreeItem.
Returns: A Python object representing the item data, or None if no data has been assigned to this item.

GetRootItem() [source]

Returns the root item, an instance of GenericTreeItem.

GetSecondGradientColour() [source]

Returns the second gradient colour for gradient-style selections.

Returns: An instance of wx.Colour.

GetSelection() [source]

Returns the current selection.

Returns: An instance of GenericTreeItem.

Note

This method is valid only with the style TR_SINGLE set. Use GetSelections for multiple-selections trees.

GetSelections() [source]

Returns a list of selected items.

Note

This method can be used only if CustomTreeCtrl has the TR_MULTIPLE or TR_EXTENDED style set.

Returns: A Python list containing the selected items, all instances of GenericTreeItem.

GetSeparatorColour(colour) [source]

Returns the pen colour for separator-type items.

Returns: An instance of wx.Colour representing the separator pen colour.

GetSpacing() [source]

Returns the spacing between the start and the text, in pixels.

GetStateImageList() [source]

Returns the state image list associated with CustomTreeCtrl (from which application-defined state images are taken).

Returns: An instance of wx.ImageList.

HandleHyperLink(item) [source]

Handles the hyperlink items, sending the EVT_TREE_ITEM_HYPERLINK event.

Parameters: item – an instance of GenericTreeItem.

HasAGWFlag(flag) [source]

Returns True if CustomTreeCtrl has the flag bit set.

Parameters: flag (integer) – any possible window style for CustomTreeCtrl.

See also

The __init__ method for the flag parameter description.

HasButtons() [source]

Returns whether CustomTreeCtrl has the TR_HAS_BUTTONS flag set.

Returns: True if CustomTreeCtrl has the TR_HAS_BUTTONS flag set, False otherwise.

HasChildren(item) [source]

Returns whether an item has children or not.

Parameters: item – an instance of GenericTreeItem.

HideWindows() [source]

Hides the windows associated to the items. Used internally.

HitTest(point, flags=0) [source]

Calculates which (if any) item is under the given point, returning the tree item at this point plus extra information flags.

Parameters:
  • point – an instance of wx.Point, a point to test for hits;

  • flags (integer) – a bitlist of the following values:

    integer parameter settings
    HitTest Flags | Hex Value | Description
    TREE_HITTEST_ABOVE | 0x1 | Above the client area
    TREE_HITTEST_BELOW | 0x2 | Below the client area
    TREE_HITTEST_NOWHERE | 0x4 | No item has been hit
    TREE_HITTEST_ONITEMBUTTON | 0x8 | On the button associated to an item
    TREE_HITTEST_ONITEMICON | 0x10 | On the icon associated to an item
    TREE_HITTEST_ONITEMINDENT | 0x20 | On the indent associated to an item
    TREE_HITTEST_ONITEMLABEL | 0x40 | On the label (string) associated to an item
    TREE_HITTEST_ONITEM | 0x50 | Anywhere on the item
    TREE_HITTEST_ONITEMRIGHT | 0x80 | On the right of the label associated to an item
    TREE_HITTEST_TOLEFT | 0x200 | On the left of the client area
    TREE_HITTEST_TORIGHT | 0x400 | On the right of the client area
    TREE_HITTEST_ONITEMUPPERPART | 0x800 | On the upper part (first half) of the item
    TREE_HITTEST_ONITEMLOWERPART | 0x1000 | On the lower part (second half) of the item
    TREE_HITTEST_ONITEMCHECKICON | 0x2000 | On the check/radio icon, if present
Returns:

A tuple with the first value being an instance of GenericTreeItem or None if no item has been hit-tested, and as second value an integer parameter flag.

Note

both the item (if any, None otherwise) and the flags are always returned as a tuple.

InsertItem(parentId, input, text, ct_type=0, wnd=None, image=-1, selImage=-1, data=None, separator=False) [source]

Inserts an item after the given previous.

Returns: An instance of GenericTreeItem upon successful insertion.

See also

InsertItemByIndex and InsertItemByItem for an explanation of the input parameters.

See also

DoInsertItem for possible exceptions generated by this method.

InsertItemByIndex(parentId, idPrevious, text, ct_type=0, wnd=None, image=-1, selImage=-1, data=None, separator=False) [source]

Inserts an item after the given previous.

Parameters:
  • parentId – an instance of GenericTreeItem representing the item’s parent;
  • idPrevious – the index at which we should insert the new item;
  • text (string) – the item text label;
  • ct_type (integer) – the item type (see SetItemType for a list of valid item types);
  • wnd – if not None, a non-toplevel window to show next to the item, any subclass of wx.Window;

  • image (integer) – an index within the normal image list specifying the image to use for the item in unselected state;
  • selImage (integer) – an index within the normal image list specifying the image to use for the item in selected state; if image > -1 and selImage is -1, the same image is used for both selected and unselected items;
  • data (object) – associate the given Python object data with the item;
  • separator (bool) – True if the item is a separator, False otherwise.
Returns:

An instance of GenericTreeItem upon successful insertion.

See also

DoInsertItem for possible exceptions generated by this method.

InsertItemByItem(parentId, idPrevious, text, ct_type=0, wnd=None, image=-1, selImage=-1, data=None, separator=False) [source]

Inserts an item after the given previous.

Parameters:
  • parentId – an instance of GenericTreeItem representing the item’s parent;
  • idPrevious – an instance of GenericTreeItem representing the previous item;
  • text (string) – the item text label;
  • ct_type (integer) – the item type (see SetItemType for a list of valid item types);
  • wnd – if not None, a non-toplevel window to show next to the item, any subclass of wx.Window;

  • image (integer) – an index within the normal image list specifying the image to use for the item in unselected state;
  • selImage (integer) – an index within the normal image list specifying the image to use for the item in selected state; if image > -1 and selImage is -1, the same image is used for both selected and unselected items;
  • data (object) – associate the given Python object data with the item;
  • separator (bool) – True if the item is a separator, False otherwise.
Returns:

An instance of GenericTreeItem upon successful insertion.
Raise :

Exception if the previous item is not a sibling.

See also

DoInsertItem for other possible exceptions generated by this method.

InsertSeparator(parentId, input) [source]

Inserts a separator item after the given previous.

Returns: An instance of GenericTreeItem upon successful insertion.

See also

InsertItemByIndex and InsertItemByItem for an explanation of the input parameters.

See also

DoInsertItem for possible exceptions generated by this method.

IsBold(item) [source]

Returns whether the item font is bold or not.

Parameters: item – an instance of GenericTreeItem.
Returns: True if the item has bold text, False otherwise.

IsDescendantOf(parent, item) [source]

Checks if the given item is under another one in the tree hierarchy.

Parameters:
  • parent – an instance of GenericTreeItem, representing the possible parent of item;
  • item – another instance of GenericTreeItem.
Returns:

True if item is a descendant of parent, False otherwise.

IsExpanded(item) [source]

Returns whether the item is expanded or not.

Parameters: item – an instance of GenericTreeItem.
Returns: True if the item is expanded, False if it is collapsed.

IsItalic(item) [source]

Returns whether the item font is italic or not.

Parameters: item – an instance of GenericTreeItem.
Returns: True if the item has italic text, False otherwise.

IsItem3State(item) [source]

Returns whether or not the checkbox item is a 3-state checkbox.

Parameters: item – an instance of GenericTreeItem.
Returns: True if this checkbox is a 3-state checkbox, False if it’s a 2-state checkbox item.

Note

This method is meaningful only for checkbox-like items.

IsItemChecked(item) [source]

Returns whether an item is checked or not.

Parameters: item – an instance of GenericTreeItem.
Returns: True if the item is in a ‘checked’ state, False otherwise.

Note

This method is meaningful only for checkbox-like and radiobutton-like items.

IsItemEnabled(item) [source]

Returns whether an item is enabled or disabled.

Parameters: item – an instance of GenericTreeItem.

IsItemHyperText(item) [source]

Returns whether an item is hypertext or not.

Parameters: item – an instance of GenericTreeItem.
Returns: True if the item is hypertext-like, False otherwise.

IsItemSeparator(item) [source]

Returns whether an item is of separator type or not.

Parameters: item – an instance of GenericTreeItem.

IsSelected(item) [source]

Returns whether the item is selected or not.

Parameters: item – an instance of GenericTreeItem.
Returns: True if the item is selected, False otherwise.

IsVisible(item) [source]

Returns whether the item is visible or not (i.e., its hierarchy is expanded enough to show the item).

Parameters: item – an instance of GenericTreeItem.
Returns: True if the item is visible, False if it is hidden.

ItemHasChildren(item) [source]

Returns whether the item has children or not.

Parameters: item – an instance of GenericTreeItem.
Returns: True if the item has children, False otherwise.

OnAcceptEdit(item, value) [source]

Called by TreeTextCtrl, to accept the changes and to send the EVT_TREE_END_LABEL_EDIT event.

Parameters:
  • item – an instance of GenericTreeItem;
  • value (string) – the new value of the item label.
Returns:

True if the editing has not been vetoed, False otherwise.

OnCancelEdit(item) [source]

Called by TreeTextCtrl, to cancel the changes and to send the EVT_TREE_END_LABEL_EDIT event.

Parameters: item – an instance of GenericTreeItem.

OnCompareItems(item1, item2) [source]

Returns whether 2 items have the same text.

Override this function in the derived class to change the sort order of the items in the CustomTreeCtrl. The function should return a negative, zero or positive value if the first item is less than, equal to or greater than the second one.

Parameters:
  • item1 – an instance of GenericTreeItem;
  • item2 – another instance of GenericTreeItem.
Returns:

The return value is negative if item1 < item2, zero if item1 == item2 and strictly positive if item1 < item2.

Note

The base class version compares items alphabetically.

OnDestroy(event) [source]

Handles the wx.EVT_WINDOW_DESTROY event for CustomTreeCtrl.

Parameters: event – a wx.WindowDestroyEvent event to be processed.

OnEditTimer() [source]

The timer for editing has expired. Start editing.

OnEraseBackground(event) [source]

Handles the wx.EVT_ERASE_BACKGROUND event for CustomTreeCtrl.

Parameters: event – a wx.EraseEvent event to be processed.

OnGetToolTip(event) [source]

Process the tooltip event, to speed up event processing. Does not actually get a tooltip.

Parameters: event – a CommandTreeEvent event to be processed.

OnInternalIdle() [source]

This method is normally only used internally, but sometimes an application may need it to implement functionality that should not be disabled by an application defining an OnIdle handler in a derived class.

This method may be used to do delayed painting, for example, and most implementations call wx.Window.UpdateWindowUI in order to send update events to the window in idle time.

OnKeyDown(event) [source]

Handles the wx.EVT_KEY_DOWN event for CustomTreeCtrl, sending a EVT_TREE_KEY_DOWN event.

Parameters: event – a wx.KeyEvent event to be processed.

OnKillFocus(event) [source]

Handles the wx.EVT_KILL_FOCUS event for CustomTreeCtrl.

Parameters: event – a wx.FocusEvent event to be processed.

OnMouse(event) [source]

Handles a bunch of wx.EVT_MOUSE_EVENTS events for CustomTreeCtrl.

Parameters: event – a wx.MouseEvent event to be processed.

OnPaint(event) [source]

Handles the wx.EVT_PAINT event for CustomTreeCtrl.

Parameters: event – a wx.PaintEvent event to be processed.

OnSetFocus(event) [source]

Handles the wx.EVT_SET_FOCUS event for CustomTreeCtrl.

Parameters: event – a wx.FocusEvent event to be processed.

OnSize(event) [source]

Handles the wx.EVT_SIZE event for CustomTreeCtrl.

Parameters: event – a wx.SizeEvent event to be processed.

PaintItem(item, dc, level, align) [source]

Actually draws an item.

Parameters:
  • item – an instance of GenericTreeItem;
  • dc – an instance of wx.DC;

  • level (integer) – the item level in the tree hierarchy;
  • align (integer) – an integer specifying the alignment type:

    integer parameter settings
    align Value | Description
    0 | No horizontal alignment of windows (in items with windows).
    1 | Windows (in items with windows) are aligned at the same horizontal position.
    2 | Windows (in items with windows) are aligned at the rightmost edge of CustomTreeCtrl.

PaintLevel(item, dc, level, y, align) [source]

Paint a level in the hierarchy of CustomTreeCtrl.

Parameters:
  • item – an instance of GenericTreeItem;
  • dc – an instance of wx.DC;

  • level (integer) – the item level in the tree hierarchy;
  • y (integer) – the current vertical position in the wx.PyScrolledWindow;
  • align (integer) – an integer specifying the alignment type:

    integer parameter settings
    align Value | Description
    0 | No horizontal alignment of windows (in items with windows).
    1 | Windows (in items with windows) are aligned at the same horizontal position.
    2 | Windows (in items with windows) are aligned at the rightmost edge of CustomTreeCtrl.

PrependItem(parent, text, ct_type=0, wnd=None, image=-1, selImage=-1, data=None, separator=False) [source]

Prepends an item as a first child of parent.

Parameters:
  • parent – an instance of GenericTreeItem representing the item’s parent;
  • text (string) – the item text label;
  • ct_type (integer) – the item type (see SetItemType for a list of valid item types);
  • wnd – if not None, a non-toplevel window to show next to the item, any subclass of wx.Window except top-level windows;

  • image (integer) – an index within the normal image list specifying the image to use for the item in unselected state;
  • selImage (integer) – an index within the normal image list specifying the image to use for the item in selected state; if image > -1 and selImage is -1, the same image is used for both selected and unselected items;
  • data (object) – associate the given Python object data with the item;
  • separator (bool) – True if the item is a separator, False otherwise.
Returns:

An instance of GenericTreeItem upon successful insertion.

See also

DoInsertItem for possible exceptions generated by this method.

PrependSeparator(parent) [source]

Prepends a separator item as a first child of parent.

Parameters: parent – an instance of GenericTreeItem representing the item’s parent.
Returns: An instance of GenericTreeItem upon successful insertion.

See also

DoInsertItem for possible exceptions generated by this method.

RecurseOnChildren(item, maxwidth, respect_expansion_state) [source]

Recurses over all the children of the spcified items, calculating their maximum width.

Parameters:
  • item – an instance of GenericTreeItem;
  • maxwidth (integer) – the current maximum width for CustomTreeCtrl, in pixels;
  • respect_expansion_state (bool) – if True, only the expanded items (and their children) will be measured. Otherwise all the items are expanded and their width measured.
Returns:

A tuple containing the maximum width and item height, in pixels.

RefreshItemWithWindows(item=None) [source]

Refreshes the items with which a window is associated.

Parameters: item – an instance of GenericTreeItem. If item is None, then the recursive refresh starts from the root node.

Note

This method is called only if the style TR_ALIGN_WINDOWS_RIGHT is used.

RefreshLine(item) [source]

Refreshes a damaged item line.

Parameters: item – an instance of GenericTreeItem.

RefreshSelected() [source]

Refreshes a damaged selected item line.

RefreshSelectedUnder(item) [source]

Refreshes the selected items under the given item.

Parameters: item – an instance of GenericTreeItem.

RefreshSubtree(item) [source]

Refreshes a damaged subtree of an item.

Parameters: item – an instance of GenericTreeItem.

ResetEditControl() [source]

Called by TreeTextCtrl when it marks itself for deletion.

ScrollTo(item) [source]

Scrolls the specified item into view.

Parameters: item – an instance of GenericTreeItem.

SelectAll() [source]

Selects all the item in the tree.

Raise : Exception if used without the TR_EXTENDED or TR_MULTIPLE style set.

Note

This method can be used only if CustomTreeCtrl has the TR_MULTIPLE or TR_EXTENDED style set.

SelectAllChildren(item) [source]

Selects all the children of the given item.

Parameters: item – an instance of GenericTreeItem.
Raise : Exception if used without the TR_EXTENDED or TR_MULTIPLE style set.

Note

This method can be used only if CustomTreeCtrl has the TR_MULTIPLE or TR_EXTENDED style set.

SelectItem(item, select=True) [source]

Selects/deselects an item.

Parameters:
  • item – an instance of GenericTreeItem;
  • select (bool) – True to select an item, False to deselect it.

SelectItemRange(item1, item2) [source]

Selects all the items between item1 and item2.

Parameters:
  • item1 – an instance of GenericTreeItem, representing the first item in the range to select;
  • item2 – an instance of GenericTreeItem, representing the last item in the range to select.
Raise :

Exception if used without the TR_EXTENDED or TR_MULTIPLE style set.

Note

This method can be used only if CustomTreeCtrl has the TR_MULTIPLE or TR_EXTENDED style set.

SendDeleteEvent(item) [source]

Actually sends the EVT_TREE_DELETE_ITEM event.

Parameters: item – an instance of GenericTreeItem.

SetAGWWindowStyleFlag(agwStyle) [source]

Sets the CustomTreeCtrl window style.

Parameters: agwStyle (integer) – the new CustomTreeCtrl window style.

See also

The __init__ method for the agwStyle parameter description.

SetBackgroundColour(colour) [source]

Changes the background colour of CustomTreeCtrl.

Parameters: colour – the colour to be used as the background colour, pass wx.NullColour to reset to the default colour.
Returns: False if the underlying wx.PyScrolledWindow does not accept the new colour, True otherwise.

Note

The background colour is usually painted by the default wx.EraseEvent event handler function under Windows and automatically under GTK.

Note

Setting the background colour does not cause an immediate refresh, so you may wish to call wx.Window.ClearBackground or wx.Window.Refresh after calling this function.

Note

Overridden from wx.PyScrolledWindow.

SetBackgroundImage(image) [source]

Sets the CustomTreeCtrl background image.

Parameters: image – if not None, an instance of wx.Bitmap.

Note

At present, the background image can only be used in “tile” mode.

Todo

Support background images also in stretch and centered modes.

SetBorderPen(pen) [source]

Sets the pen used to draw the selected item border.

Parameters: pen – an instance of wx.Pen.

Note

The border pen is not used if the Windows Vista selection style is applied.

SetButtonsImageList(imageList) [source]

Sets the buttons image list for CustomTreeCtrl (from which application-defined button images are taken).

Parameters: imageList – an instance of wx.ImageList.

SetConnectionPen(pen) [source]

Sets the pen used to draw the connecting lines between items.

Parameters: pen – an instance of wx.Pen.

SetDisabledColour(colour) [source]

Sets the colour for items in a disabled state.

Parameters: colour – a valid wx.Colour instance.

SetFirstGradientColour(colour=None) [source]

Sets the first gradient colour for gradient-style selections.

Parameters: colour – if not None, a valid wx.Colour instance. Otherwise, the colour is taken from the system value wx.SYS_COLOUR_HIGHLIGHT.

SetFont(font) [source]

Sets the CustomTreeCtrl font.

Parameters: font – a valid wx.Font instance.

Note

Overridden from wx.PyScrolledWindow.

SetForegroundColour(colour) [source]

Changes the foreground colour of CustomTreeCtrl.

Parameters: colour – the colour to be used as the foreground colour, pass wx.NullColour to reset to the default colour.
Returns: False if the underlying wx.PyScrolledWindow does not accept the new colour, True otherwise.

Note

Overridden from wx.PyScrolledWindow.

SetGradientStyle(vertical=0) [source]

Sets the gradient style for gradient-style selections.

Parameters: vertical (integer) – 0 for horizontal gradient-style selections, 1 for vertical gradient-style selections.

SetHilightFocusColour(colour) [source]

Sets the colour used to highlight focused selected items.

Parameters: colour – a valid wx.Colour instance.

Note

This is applied only if gradient and Windows Vista selection styles are disabled.

SetHilightNonFocusColour(colour) [source]

Sets the colour used to highlight unfocused selected items.

Parameters: colour – a valid wx.Colour instance.

Note

This is applied only if gradient and Windows Vista selection styles are disabled.

SetHyperTextFont(font) [source]

Sets the font used to render hypertext items.

Parameters: font – a valid wx.Font instance.

Note

This method is meaningful only for hypertext-like items.

SetHyperTextNewColour(colour) [source]

Sets the colour used to render a non-visited hypertext item.

Parameters: colour – a valid wx.Colour instance.

Note

This method is meaningful only for hypertext-like items.

SetHyperTextVisitedColour(colour) [source]

Sets the colour used to render a visited hypertext item.

Parameters: colour – a valid wx.Colour instance.

Note

This method is meaningful only for hypertext-like items.

SetImageList(imageList) [source]

Sets the normal image list for CustomTreeCtrl.

Parameters: imageList – an instance of wx.ImageList.

SetImageListCheck(sizex, sizey, imglist=None) [source]

Sets the checkbox/radiobutton image list.

Parameters:
  • sizex (integer) – the width of the bitmaps in the imglist, in pixels;
  • sizey (integer) – the height of the bitmaps in the imglist, in pixels;
  • imglist – an instance of wx.ImageList.

SetIndent(indent) [source]

Sets the indentation for CustomTreeCtrl.

Parameters: indent (integer) – an integer representing the indentation for the items in the tree.

SetItem3State(item, allow) [source]

Sets whether the item has a 3-state value checkbox assigned to it or not.

Parameters:
  • item – an instance of GenericTreeItem;
  • allow (bool) – True to set an item as a 3-state checkbox, False to set it to a 2-state checkbox.
Returns:

True if the change was successful, False otherwise.

Note

This method is meaningful only for checkbox-like items.

SetItem3StateValue(item, state) [source]

Sets the checkbox item to the given state.

Parameters:
  • item – an instance of GenericTreeItem;
  • state (integer) – can be one of: wx.CHK_UNCHECKED (check is off), wx.CHK_CHECKED (check is on) or wx.CHK_UNDETERMINED (check is mixed).

Note

This method raises an exception when the checkbox item is a 2-state checkbox and setting the state to wx.CHK_UNDETERMINED.

Note

This method is meaningful only for checkbox-like items.

SetItemBackgroundColour(item, colour) [source]

Sets the item background colour.

Parameters:
  • item – an instance of GenericTreeItem;
  • colour – a valid wx.Colour instance.

SetItemBold(item, bold=True) [source]

Sets the item font as bold/unbold.

Parameters:
  • item – an instance of GenericTreeItem;
  • bold (bool) – True to set the item font as bold, False otherwise.

SetItemDropHighlight(item, highlight=True) [source]

Gives the item the visual feedback for drag and drop operations. This is useful when something is dragged from outside the CustomTreeCtrl.

Parameters:
  • item – an instance of GenericTreeItem;
  • highlight (bool) – True to highlight the dragged items, False otherwise.

SetItemFont(item, font) [source]

Sets the item font.

Parameters:
  • item – an instance of GenericTreeItem;
  • font – a valid wx.Font instance.

SetItemHasChildren(item, has=True) [source]

Forces the appearance/disappearance of the button next to the item.

Parameters:
  • item – an instance of GenericTreeItem;
  • has (bool) – True to have a button next to an item, False otherwise.

SetItemHyperText(item, hyper=True) [source]

Sets whether the item is hypertext or not.

Parameters:
  • item – an instance of GenericTreeItem;
  • hyper (bool) – True to have an item with hypertext behaviour, False otherwise.

SetItemImage(item, image, which=TreeItemIcon_Normal) [source]

Sets the item image, depending on the item state.

Parameters:
  • item – an instance of GenericTreeItem;
  • image (integer) – an index within the normal image list specifying the image to use for the item in the state specified by the which parameter;
  • which (integer) – the item state.

See also

GetItemImage for an explanation of the which parameter.

SetItemItalic(item, italic=True) [source]

Sets the item font as italic/non-italic.

Parameters:
  • item – an instance of GenericTreeItem;
  • italic (bool) – True to set the item font as italic, False otherwise.

SetItemLeftImage(item, image) [source]

Sets the item leftmost image, i.e. the image associated to the item on the leftmost part of the CustomTreeCtrl client area.

Parameters:
  • item – an instance of GenericTreeItem;
  • image (integer) – an index within the left image list specifying the image to use for the item in the leftmost part of the client area.

SetItemPyData(item, data)

Sets the data associated to an item.

Parameters:
  • item – an instance of GenericTreeItem;
  • data (object) – can be any Python object.

SetItemText(item, text) [source]

Sets the item text.

Parameters:
  • item – an instance of GenericTreeItem;
  • text (string) – the new item label.
Raise :

Exception if the input item is a separator.

SetItemTextColour(item, colour) [source]

Sets the item text colour or separator horizontal line colour.

Parameters:
  • item – an instance of GenericTreeItem;
  • colour – a valid wx.Colour instance.

SetItemType(item, ct_type) [source]

Sets the item type.

Parameters:
  • item – an instance of GenericTreeItem;
  • ct_type (integer) – may be one of the following integers:

    integer parameter settings
    ct_type Value | Description
    0 | A normal item
    1 | A checkbox-like item
    2 | A radiobutton-type item

Note

Regarding radiobutton-type items (with ct_type = 2), the following approach is used:

  • All peer-nodes that are radiobuttons will be mutually exclusive. In other words, only one of a set of radiobuttons that share a common parent can be checked at once. If a radiobutton node becomes checked, then all of its peer radiobuttons must be unchecked.
  • If a radiobutton node becomes unchecked, then all of its child nodes will become inactive.

SetItemVisited(item, visited=True) [source]

Sets whether an hypertext item was visited.

Parameters:
  • item – an instance of GenericTreeItem;
  • visited (bool) – True to mark an hypertext item as visited, False otherwise.

Note

This method is meaningful only for hypertext-like items.

SetItemWindow(item, wnd) [source]

Sets the window for the given item.

Parameters:
  • item – an instance of GenericTreeItem;
  • wnd – if not None, a non-toplevel window to be displayed next to the item.
Raise :

Exception if the input item is a separator and wnd is not None.

SetItemWindowEnabled(item, enable=True) [source]

Enables/disables the window associated to the item.

Parameters:
  • item – an instance of GenericTreeItem;
  • enable (bool) – True to enable the associated window, False to disable it.

SetLeftImageList(imageList) [source]

Sets the image list for CustomTreeCtrl filled with images to be used on the leftmost part of the client area. Any item can have a leftmost image associated with it.

Parameters: imageList – an instance of wx.ImageList.

SetPyData(item, data) [source]

Sets the data associated to an item.

Parameters:
  • item – an instance of GenericTreeItem;
  • data (object) – can be any Python object.

SetSecondGradientColour(colour=None) [source]

Sets the second gradient colour for gradient-style selections.

Parameters: colour – if not None, a valid wx.Colour instance. Otherwise, the colour generated is a slightly darker version of the CustomTreeCtrl background colour.

SetSeparatorColour(colour) [source]

Sets the pen colour for separator-type items.

Parameters: colour – a valid instance of wx.Colour.

SetSpacing(spacing) [source]

Sets the spacing between items in CustomTreeCtrl.

Parameters: spacing (integer) – an integer representing the spacing between items in the tree.

SetStateImageList(imageList) [source]

Sets the state image list for CustomTreeCtrl (from which application-defined state images are taken).

Parameters: imageList – an instance of wx.ImageList.

ShouldInheritColours() [source]

Return True from here to allow the colours of this window to be changed by InheritAttributes, returning False forbids inheriting them from the parent window.

The base class version returns False, but this method is overridden in wx.Control where it returns True.

CustomTreeCtrl does not inherit colours from anyone.

SortChildren(item) [source]

Sorts the children of the given item using the OnCompareItems method of CustomTreeCtrl.

Parameters: item – an instance of GenericTreeItem.

Note

You should override the OnCompareItems method in your derived class to change the sort order (the default is ascending case-sensitive alphabetical order).

TagAllChildrenUntilLast(crt_item, last_item, select) [source]

Used internally.

TagNextChildren(crt_item, last_item, select) [source]

Used internally.

Thaw() [source]

Thaw CustomTreeCtrl.

Reenables window updating after a previous call to Freeze. To really thaw the control, it must be called exactly the same number of times as Freeze.

Raise : Exception if Thaw has been called without an un-matching Freeze.

TileBackground(dc) [source]

Tiles the background image to fill all the available area.

Parameters: dc – an instance of wx.DC.

Todo

Support background images also in stretch and centered modes.

Toggle(item) [source]

Toggles the item state (collapsed/expanded).

Parameters: item – an instance of GenericTreeItem.

ToggleItemSelection(item) [source]

Toggles the item selection.

Parameters: item – an instance of GenericTreeItem.

UnCheckRadioParent(item, checked=False) [source]

Used internally to handle radio node parent correctly.

Parameters:
  • item – an instance of GenericTreeItem;
  • checked (bool) – True to check an item, False to uncheck it.

Unselect() [source]

Unselects the current selection.

UnselectAll() [source]

Unselect all the items.

UnselectAllChildren(item) [source]

Unselects all the children of the given item.

Parameters: item – an instance of GenericTreeItem.

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • infobar
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • customtreectrl »
  • CustomTreeCtrl


DragImage

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • customtreectrl »
  • DragImage

DragImage

This class handles the creation of a custom image in case of item drag and drop.

hierarchy Inheritance Diagram

Inheritance diagram for: DragImage

Inheritance diagram of DragImage

Methods Summary

__init__ | Default class constructor.
CreateBitmap | Actually creates the drag and drop bitmap for DragImage.

API Class API

class DragImage(wx.DragImage) [source]

This class handles the creation of a custom image in case of item drag and drop.

__init__(treeCtrl, item) [source]

Default class constructor. For internal use: do not call it in your code!

Parameters:
  • treeCtrl – the parent CustomTreeCtrl;
  • item – one of the tree control item (an instance of GenericTreeItem).

CreateBitmap() [source]

Actually creates the drag and drop bitmap for DragImage.

Returns: An instance of DragImage, a close representation of the item’s appearance (i.e., a screenshot of the item).

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • infobar
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • customtreectrl »
  • DragImage


GenericTreeItem

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • customtreectrl »
  • GenericTreeItem

GenericTreeItem

This class holds all the information and methods for every single item in CustomTreeCtrl. This is a generic implementation of wx.TreeItem.

hierarchy Inheritance Diagram

Inheritance diagram for: GenericTreeItem

Inheritance diagram of GenericTreeItem

subclasses Known Subclasses

  • hypertreelist.TreeListItem

Methods Summary

__init__ | Default class constructor.
AssignAttributes | Assigns the item attributes (font, colours, etc...) for this item.
Attr | Creates a new attribute (font, colours, etc...) for this item.
Check | Checks/unchecks an item.
Collapse | Collapses the item.
DeleteChildren | Deletes the item children.
DeleteWindow | Deletes the window associated to the item (if any).
Enable | Enables/disables the item.
Expand | Expands the item.
Get3StateValue | Gets the state of a 3-state checkbox item.
GetAttributes | Returns the item attributes (font, colours, etc...).
GetCheckedImage | Returns the item check image.
GetChildren | Returns the item’s children.
GetChildrenCount | Gets the number of children of this item.
GetCurrentCheckedImage | Returns the current item check image.
GetCurrentImage | Returns the current item image.
GetData | Returns the data associated to this item.
GetHeight | Returns the height of the item, in pixels.
GetImage | Returns the item image for a particular item state.
GetLeftImage | Returns the leftmost image associated to this item, i.e.
GetParent | Gets the item parent (another instance of GenericTreeItem or None for
GetSize | Returns the item size.
GetText | Returns the item text.
GetType | Returns the item type.
GetValue | Returns whether the item is checked or not.
GetVisited | Returns whether an hypertext item was visited or not.
GetWidth | Returns the width of the item, in pixels.
GetWindow | Returns the window associated to the item (if any).
GetWindowEnabled | Returns whether the associated window is enabled or not.
GetWindowSize | Returns the associated window size.
GetX | Returns the x position on an item, in logical coordinates.
GetY | Returns the y position on an item, in logical coordinates.
HasChildren | Returns whether the item has children or not.
HasPlus | Returns whether the item has the plus button or not.
HitTest | HitTest method for an item. Called from the main window CustomTreeCtrl.HitTest().
Insert | Inserts an item in the item children list for this item.
Is3State | Returns whether or not the checkbox item is a 3-state checkbox.
IsBold | Returns whether the item font is bold or not.
IsChecked | This is just a maybe more readable synonym for GetValue.
IsEnabled | Returns whether the item is enabled or not.
IsExpanded | Returns whether the item is expanded or not.
IsHyperText | Returns whether the item is hypetext or not.
IsItalic | Returns whether the item font is italic or not.
IsOk | Returns whether the item is ok or not.
IsSelected | Returns whether the item is selected or not.
IsSeparator | Returns whether the item is meant to be an horizontal line separator or not.
OnSetFocus | Handles the wx.EVT_SET_FOCUS event for the window associated with the item.
Set3State | Sets whether the item has a 3-state value checkbox assigned to it or not.
Set3StateValue | Sets the checkbox item to the given state.
SetAttributes | Sets the item attributes (font, colours, etc...).
SetBold | Sets the item font bold.
SetData | Sets the data associated to this item.
SetHasPlus | Sets whether an item has the ‘plus’ button.
SetHeight | Sets the item’s height.
SetHilight | Sets the item focus/unfocus.
SetHyperText | Sets whether the item is hypertext or not.
SetImage | Sets the item image.
SetItalic | Sets the item font italic.
SetLeftImage | Sets the item leftmost image, i.e.
SetText | Sets the item text.
SetType | Sets the item type.
SetVisited | Sets whether an hypertext item was visited or not.
SetWidth | Sets the item’s width.
SetWindow | Sets the window associated to the item.
SetWindowEnabled | Sets whether the associated window is enabled or not.
SetX | Sets the x position on an item, in logical coordinates.
SetY | Sets the y position on an item, in logical coordinates.

API Class API

class GenericTreeItem(object) [source]

This class holds all the information and methods for every single item in CustomTreeCtrl. This is a generic implementation of wx.TreeItem.

__init__(parent, text='', ct_type=0, wnd=None, image=-1, selImage=-1, data=None, separator=False) [source]

Default class constructor. For internal use: do not call it in your code!

Parameters:
  • parent – the tree item parent, an instance of GenericTreeItem (may be None for root items);
  • text (string) – the tree item text;
  • ct_type (integer) – the tree item kind. May be one of the following integers:

    integer parameter settings
    ct_type Value | Description
    0 | A normal item
    1 | A checkbox-like item
    2 | A radiobutton-type item
  • wnd – if not None, a non-toplevel window to be displayed next to the item, an instance of wx.Window;
  • image (integer) – an index within the normal image list specifying the image to use for the item in unselected state;
  • selImage (integer) – an index within the normal image list specifying the image to use for the item in selected state; if image > -1 and selImage is -1, the same image is used for both selected and unselected items;
  • data (object) – associate the given Python object data with the item;
  • separator (bool) – True if the item is a separator, False otherwise.

Note

Regarding radiobutton-type items (with ct_type = 2), the following approach is used:

  • All peer-nodes that are radiobuttons will be mutually exclusive. In other words, only one of a set of radiobuttons that share a common parent can be checked at once. If a radiobutton node becomes checked, then all of its peer radiobuttons must be unchecked.
  • If a radiobutton node becomes unchecked, then all of its child nodes will become inactive.

Note

Separator items should not have children, labels, data or an associated window. Other issues/features associated to separator items:

  • You can change the color of individual separators by using CustomTreeCtrl.SetItemTextColour(), or you can use CustomTreeCtrl.SetSeparatorColour() to change the color of all separators. The default separator colour is that returned by wx.SystemSettings.GetColour(wx.SYS_COLOUR_GRAYTEXT);
  • Separators can be selected just like any other tree item;
  • Separators cannot have text;
  • Separators cannot have children;
  • Separators cannot be edited via the EVT_TREE_BEGIN_LABEL_EDIT event.

AssignAttributes(attr) [source]

Assigns the item attributes (font, colours, etc...) for this item.

Parameters: attr – an instance of TreeItemAttr.

Attr() [source]

Creates a new attribute (font, colours, etc...) for this item.

Returns: An instance of TreeItemAttr.

Check(checked=True) [source]

Checks/unchecks an item.

Parameters: checked (bool) – True to check an item, False to uncheck it.

Note

This is meaningful only for checkbox-like and radiobutton-like items.

Collapse() [source]

Collapses the item.

DeleteChildren(tree) [source]

Deletes the item children.

Parameters: tree – the main CustomTreeCtrl instance.

DeleteWindow() [source]

Deletes the window associated to the item (if any).

Enable(enable=True) [source]

Enables/disables the item.

Parameters: enable (bool) – True to enable the item, False to disable it.

Expand() [source]

Expands the item.

Get3StateValue() [source]

Gets the state of a 3-state checkbox item.

Returns: wx.CHK_UNCHECKED when the checkbox is unchecked, wx.CHK_CHECKED when it is checked and wx.CHK_UNDETERMINED when it’s in the undetermined state.
Raise : Exception when the item is not a 3-state checkbox item.

Note

This method raises an exception when the function is used with a 2-state checkbox item.

Note

This method is meaningful only for checkbox-like items.

GetAttributes() [source]

Returns the item attributes (font, colours, etc...).

Returns: An instance of TreeItemAttr.

GetCheckedImage(which=TreeItemIcon_Checked) [source]

Returns the item check image.

Parameters: which (integer) – can be one of the following bits:

integer parameter settings
Item State | Description
TreeItemIcon_Checked | To get the checkbox checked item image
TreeItemIcon_NotChecked | To get the checkbox unchecked item image
TreeItemIcon_Undetermined | To get the checkbox undetermined state item image
TreeItemIcon_Flagged | To get the radiobutton checked image
TreeItemIcon_NotFlagged | To get the radiobutton unchecked image
Returns: An integer index that can be used to retrieve the item check image inside a wx.ImageList.

Note

This method is meaningful only for radio & check items.

GetChildren() [source]

Returns the item’s children.

Returns: A Python list containing instances of GenericTreeItem, representing this item’s children.

GetChildrenCount(recursively=True) [source]

Gets the number of children of this item.

Parameters: recursively (bool) – if True, returns the total number of descendants, otherwise only one level of children is counted.

GetCurrentCheckedImage() [source]

Returns the current item check image.

Returns: An integer index that can be used to retrieve the item check image inside a wx.ImageList.

GetCurrentImage() [source]

Returns the current item image.

Returns: An integer index that can be used to retrieve the item image inside a wx.ImageList.

GetData() [source]

Returns the data associated to this item.

Returns: A Python object representing the item data, or None if no data has been assigned to this item.

GetHeight() [source]

Returns the height of the item, in pixels.

GetImage(which=TreeItemIcon_Normal) [source]

Returns the item image for a particular item state.

Parameters: which (integer) – can be one of the following bits:

integer parameter settings
Item State | Description
TreeItemIcon_Normal | To get the normal item image
TreeItemIcon_Selected | To get the selected item image (i.e. the image which is shown when the item is currently selected)
TreeItemIcon_Expanded | To get the expanded image (this only makes sense for items which have children - then this image is shown when the item is expanded and the normal image is shown when it is collapsed)
TreeItemIcon_SelectedExpanded | To get the selected expanded image (which is shown when an expanded item is currently selected)
Returns: An integer index that can be used to retrieve the item image inside a wx.ImageList.

GetLeftImage() [source]

Returns the leftmost image associated to this item, i.e. the image on the leftmost part of the client area of CustomTreeCtrl.

Returns: An integer index that can be used to retrieve the item leftmost image inside a wx.ImageList.

GetParent() [source]

Gets the item parent (another instance of GenericTreeItem or None for root items.

Returns: An instance of GenericTreeItem or None for root items.

GetSize(x, y, theButton) [source]

Returns the item size.

Parameters:
  • x (integer) – the current item’s x position;
  • y (integer) – the current item’s y position;
  • theButton – an instance of the main CustomTreeCtrl.
Returns:

A tuple of (x, y) dimensions, in pixels, representing the item’s width and height.

GetText() [source]

Returns the item text.

Returns: A string containing the item text.

GetType() [source]

Returns the item type.

See also

SetType and __init__ for a description of valid item types.

GetValue() [source]

Returns whether the item is checked or not.

Note

This is meaningful only for checkbox-like and radiobutton-like items.

GetVisited() [source]

Returns whether an hypertext item was visited or not.

GetWidth() [source]

Returns the width of the item, in pixels.

GetWindow() [source]

Returns the window associated to the item (if any).

Returns: An instance of any wx.Window derived class, excluding top-level windows.

GetWindowEnabled() [source]

Returns whether the associated window is enabled or not.

Returns: True if the associated window is enabled, False if it is disabled.
Raise : Exception when the item has no associated window.

GetWindowSize() [source]

Returns the associated window size.

GetX() [source]

Returns the x position on an item, in logical coordinates.

GetY() [source]

Returns the y position on an item, in logical coordinates.

HasChildren() [source]

Returns whether the item has children or not.

Returns: True if the item has children, False otherwise.

HasPlus() [source]

Returns whether the item has the plus button or not.

Returns: True if the item has a ‘plus’ mark, False otherwise.

HitTest(point, theCtrl, flags=0, level=0) [source]

HitTest method for an item. Called from the main window CustomTreeCtrl.HitTest().

Parameters:
  • point – the point to test for the hit (an instance of wx.Point);
  • theCtrl – the main CustomTreeCtrl tree;
  • flags (integer) – a bitlist of hit locations;
  • level (integer) – the item’s level inside the tree hierarchy.

See also

CustomTreeCtrl.HitTest() method for the flags explanation.

Insert(child, index) [source]

Inserts an item in the item children list for this item.

Parameters:
  • child – an instance of GenericTreeItem;
  • index (integer) – the index at which we should insert the new child.

Is3State() [source]

Returns whether or not the checkbox item is a 3-state checkbox.

Returns: True if this checkbox is a 3-state checkbox, False if it’s a 2-state checkbox item.

Note

This method is meaningful only for checkbox-like items.

IsBold() [source]

Returns whether the item font is bold or not.

Returns: True if the item has bold text, False otherwise.

IsChecked() [source]

This is just a maybe more readable synonym for GetValue. Returns whether the item is checked or not.

Note

This is meaningful only for checkbox-like and radiobutton-like items.

IsEnabled() [source]

Returns whether the item is enabled or not.

Returns: True if the item is enabled, False if it is disabled.

IsExpanded() [source]

Returns whether the item is expanded or not.

Returns: True if the item is expanded, False if it is collapsed.

IsHyperText() [source]

Returns whether the item is hypetext or not.

IsItalic() [source]

Returns whether the item font is italic or not.

Returns: True if the item has italic text, False otherwise.

IsOk() [source]

Returns whether the item is ok or not.

Note

This method always returns True, it has been added for backward compatibility with the wxWidgets C++ implementation.

IsSelected() [source]

Returns whether the item is selected or not.

Returns: True if the item is selected, False otherwise.

IsSeparator() [source]

Returns whether the item is meant to be an horizontal line separator or not.

Returns: True if this item is a separator, False otherwise.

OnSetFocus(event) [source]

Handles the wx.EVT_SET_FOCUS event for the window associated with the item.

Parameters: event – a wx.FocusEvent event to be processed.

Set3State(allow) [source]

Sets whether the item has a 3-state value checkbox assigned to it or not.

Parameters: allow (bool) – True to set an item as a 3-state checkbox, False to set it to a 2-state checkbox.
Returns: True if the change was successful, False otherwise.

Note

This method is meaningful only for checkbox-like items.

Set3StateValue(state) [source]

Sets the checkbox item to the given state.

Parameters: state (integer) – can be one of: wx.CHK_UNCHECKED (check is off), wx.CHK_CHECKED (check is on) or wx.CHK_UNDETERMINED (check is mixed).
Raise : Exception when the item is not a 3-state checkbox item.

Note

This method raises an exception when the checkbox item is a 2-state checkbox and setting the state to wx.CHK_UNDETERMINED.

Note

This method is meaningful only for checkbox-like items.

SetAttributes(attr) [source]

Sets the item attributes (font, colours, etc...).

Parameters: attr – an instance of TreeItemAttr.

SetBold(bold) [source]

Sets the item font bold.

Parameters: bold (bool) – True to have a bold font item, False otherwise.

SetData(data) [source]

Sets the data associated to this item.

Parameters: data (object) – can be any Python object.

SetHasPlus(has=True) [source]

Sets whether an item has the ‘plus’ button.

Parameters: has (bool) – True to set the ‘plus’ button on the item, False otherwise.

SetHeight(h) [source]

Sets the item’s height.

Parameters: h (integer) – an integer specifying the item’s height, in pixels.

SetHilight(set=True) [source]

Sets the item focus/unfocus.

Parameters: set (bool) – True to set the focus to the item, False otherwise.

SetHyperText(hyper=True) [source]

Sets whether the item is hypertext or not.

Parameters: hyper (bool) – True to set hypertext behaviour, False otherwise.

SetImage(image, which) [source]

Sets the item image.

Parameters:
  • image (integer) – an index within the normal image list specifying the image to use;
  • which (integer) – the image kind.

See also

GetImage for a description of the which parameter.

SetItalic(italic) [source]

Sets the item font italic.

Parameters: italic (bool) – True to have an italic font item, False otherwise.

SetLeftImage(image) [source]

Sets the item leftmost image, i.e. the image associated to the item on the leftmost part of the CustomTreeCtrl client area.

Parameters: image (integer) – an index within the left image list specifying the image to use for the item in the leftmost part of the client area.

SetText(text) [source]

Sets the item text.

Parameters: text (string) – the new item label.
Raise : Exception if the item is a separator.

SetType(ct_type) [source]

Sets the item type.

Parameters: ct_type (integer) – may be one of the following integers:

integer parameter settings
ct_type Value | Description
0 | A normal item
1 | A checkbox-like item
2 | A radiobutton-type item

Note

Regarding radiobutton-type items (with ct_type = 2), the following approach is used:

  • All peer-nodes that are radiobuttons will be mutually exclusive. In other words, only one of a set of radiobuttons that share a common parent can be checked at once. If a radiobutton node becomes checked, then all of its peer radiobuttons must be unchecked.
  • If a radiobutton node becomes unchecked, then all of its child nodes will become inactive.

SetVisited(visited=True) [source]

Sets whether an hypertext item was visited or not.

Parameters: visited (bool) – True to set a hypertext item as visited, False otherwise.

SetWidth(w) [source]

Sets the item’s width.

Parameters: w (integer) – an integer specifying the item’s width, in pixels.

SetWindow(wnd) [source]

Sets the window associated to the item.

Parameters: wnd – a non-toplevel window to be displayed next to the item, any subclass of wx.Window.
Raise : Exception if the input item is a separator and wnd is not None.

SetWindowEnabled(enable=True) [source]

Sets whether the associated window is enabled or not.

Parameters: enable (bool) – True to enable the associated window, False to disable it.
Raise : Exception when the item has no associated window.

SetX(x) [source]

Sets the x position on an item, in logical coordinates.

Parameters: x (integer) – an integer specifying the x position of the item.

SetY(y) [source]

Sets the y position on an item, in logical coordinates.

Parameters: y (integer) – an integer specifying the y position of the item.

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • infobar
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • customtreectrl »
  • GenericTreeItem


TreeEditTimer

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • customtreectrl »
  • TreeEditTimer

TreeEditTimer

Timer used for enabling in-place edit.

hierarchy Inheritance Diagram

Inheritance diagram for: TreeEditTimer

Inheritance diagram of TreeEditTimer

Methods Summary

__init__ | Default class constructor.
Notify | The timer has expired, starts the item editing.

API Class API

class TreeEditTimer(wx.Timer) [source]

Timer used for enabling in-place edit.

__init__(owner) [source]

Default class constructor. For internal use: do not call it in your code!

Parameters: owner – the wx.Timer owner (an instance of CustomTreeCtrl).

Notify() [source]

The timer has expired, starts the item editing.

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • infobar
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • customtreectrl »
  • TreeEditTimer


TreeEvent

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • customtreectrl »
  • TreeEvent

TreeEvent

CommandTreeEvent is a special class for all events associated with tree controls.

Note

Not all accessors make sense for all events, see the event descriptions below.

hierarchy Inheritance Diagram

Inheritance diagram for: TreeEvent

Inheritance diagram of TreeEvent

supclasses Known Superclasses

  • customtreectrl.CommandTreeEvent

Methods Summary

__init__ | Default class constructor.
Allow | This is the opposite of Veto: it explicitly allows the event to be processed.
GetNotifyEvent | Returns the actual wx.NotifyEvent.
IsAllowed | Returns True if the change is allowed (Veto hasn’t been called) or
Veto | Prevents the change announced by this event from happening.

API Class API

class TreeEvent(CommandTreeEvent) [source]

CommandTreeEvent is a special class for all events associated with tree controls.

Note

Not all accessors make sense for all events, see the event descriptions below.

__init__(evtType, evtId, item=None, evtKey=None, point=None, label=None) [source]

Default class constructor. For internal use: do not call it in your code!

Parameters:
  • evtType (integer) – the event type;
  • evtId (integer) – the event identifier;
  • item – an instance of GenericTreeItem;
  • evtKey (integer) – a character ordinal;
  • point – an instance of wx.Point;
  • label (string) – a GenericTreeItem text label.

Allow() [source]

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

GetNotifyEvent() [source]

Returns the actual wx.NotifyEvent.

Returns: An instance of wx.NotifyEvent.

IsAllowed() [source]

Returns True if the change is allowed (Veto hasn’t been called) or False otherwise (if it was).

Veto() [source]

Prevents the change announced by this event from happening.

Note

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

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • infobar
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • customtreectrl »
  • TreeEvent


TreeFindTimer

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • customtreectrl »
  • TreeFindTimer

TreeFindTimer

Timer used to clear the CustomTreeCtrl _findPrefix attribute if no key was pressed for a sufficiently long time.

hierarchy Inheritance Diagram

Inheritance diagram for: TreeFindTimer

Inheritance diagram of TreeFindTimer

Methods Summary

__init__ | Default class constructor.
Notify | The timer has expired, clear the _findPrefix attribute in CustomTreeCtrl.

API Class API

class TreeFindTimer(wx.Timer) [source]

Timer used to clear the CustomTreeCtrl _findPrefix attribute if no key was pressed for a sufficiently long time.

__init__(owner) [source]

Default class constructor. For internal use: do not call it in your code!

Parameters: owner – the wx.Timer owner (an instance of CustomTreeCtrl).

Notify() [source]

The timer has expired, clear the _findPrefix attribute in CustomTreeCtrl.

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • infobar
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • customtreectrl »
  • TreeFindTimer


TreeItemAttr

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • customtreectrl »
  • TreeItemAttr

TreeItemAttr

Creates the item attributes (text colour, background colour and font).

Note

This class is inspired by the wxWidgets generic implementation of wx.TreeItemAttr.

hierarchy Inheritance Diagram

Inheritance diagram for: TreeItemAttr

Inheritance diagram of TreeItemAttr

Methods Summary

__init__ | Default class constructor.
GetBackgroundColour | Returns the attribute background colour.
GetFont | Returns the attribute font.
GetTextColour | Returns the attribute text colour.
HasBackgroundColour | Returns whether the attribute has background colour.
HasFont | Returns whether the attribute has font.
HasTextColour | Returns whether the attribute has text colour.
SetBackgroundColour | Sets the item background colour attribute.
SetFont | Sets the item font attribute.
SetTextColour | Sets the text colour attribute.

API Class API

class TreeItemAttr(object) [source]

Creates the item attributes (text colour, background colour and font).

Note

This class is inspired by the wxWidgets generic implementation of wx.TreeItemAttr.

__init__(colText=wx.NullColour, colBack=wx.NullColour, font=wx.NullFont) [source]

Default class constructor. For internal use: do not call it in your code!

Parameters:
  • colText – the text colour, an instance of wx.Colour;
  • colBack – the tree item background colour, an instance of wx.Colour;

  • font – the tree item font, an instance of wx.Font.

GetBackgroundColour() [source]

Returns the attribute background colour.

Returns: An instance of wx.Colour.

GetFont() [source]

Returns the attribute font.

Returns: An instance of wx.Font.

GetTextColour() [source]

Returns the attribute text colour.

Returns: An instance of wx.Colour.

HasBackgroundColour() [source]

Returns whether the attribute has background colour.

Returns: True if the background colour attribute has been set, False otherwise.

HasFont() [source]

Returns whether the attribute has font.

Returns: True if the font attribute has been set, False otherwise.

HasTextColour() [source]

Returns whether the attribute has text colour.

Returns: True if the text colour attribute has been set, False otherwise.

SetBackgroundColour(colBack) [source]

Sets the item background colour attribute.

Parameters: colBack – an instance of wx.Colour.

SetFont(font) [source]

Sets the item font attribute.

Parameters: font – an instance of wx.Font.

SetTextColour(colText) [source]

Sets the text colour attribute.

Parameters: colText – an instance of wx.Colour.

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • infobar
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • customtreectrl »
  • TreeItemAttr


TreeTextCtrl

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • customtreectrl »
  • TreeTextCtrl

TreeTextCtrl

Control used for in-place edit.

This is a subclass of wx.lib.expando.ExpandoTextCtrl as CustomTreeCtrl supports multiline text items.

Note

To add a newline character in a multiline item, press Shift + Enter as the Enter key alone is consumed by CustomTreeCtrl to finish the editing and Ctrl + Enter is consumed by the platform for tab navigation.

hierarchy Inheritance Diagram

Inheritance diagram for: TreeTextCtrl

Inheritance diagram of TreeTextCtrl

Methods Summary

__init__ | Default class constructor.
AcceptChanges | Accepts/rejects the changes made by the user.
Finish | Finish editing.
OnChar | Handles the wx.EVT_CHAR event for TreeTextCtrl.
OnKeyUp | Handles the wx.EVT_KEY_UP event for TreeTextCtrl.
OnKillFocus | Handles the wx.EVT_KILL_FOCUS event for TreeTextCtrl.
StopEditing | Suddenly stops the editing.
item | Returns the item currently edited.

API Class API

class TreeTextCtrl(ExpandoTextCtrl) [source]

Control used for in-place edit.

This is a subclass of wx.lib.expando.ExpandoTextCtrl as CustomTreeCtrl supports multiline text items.

Note

To add a newline character in a multiline item, press Shift + Enter as the Enter key alone is consumed by CustomTreeCtrl to finish the editing and Ctrl + Enter is consumed by the platform for tab navigation.

__init__(owner, item=None) [source]

Default class constructor. For internal use: do not call it in your code!

Parameters:
  • owner – the control parent (an instance of CustomTreeCtrl);
  • item – an instance of GenericTreeItem.
Raise :

Exception when the item has an associated image but the parent CustomTreeCtrl does not have a wx.ImageList assigned.

AcceptChanges() [source]

Accepts/rejects the changes made by the user.

Returns: True if the changes to the item text have been accepted, False if they have been rejected (i.e., vetoed by the user).

Finish() [source]

Finish editing.

OnChar(event) [source]

Handles the wx.EVT_CHAR event for TreeTextCtrl.

Parameters: event – a wx.KeyEvent event to be processed.

OnKeyUp(event) [source]

Handles the wx.EVT_KEY_UP event for TreeTextCtrl.

Parameters: event – a wx.KeyEvent event to be processed.

OnKillFocus(event) [source]

Handles the wx.EVT_KILL_FOCUS event for TreeTextCtrl.

Parameters: event – a wx.FocusEvent event to be processed.

StopEditing() [source]

Suddenly stops the editing.

item() [source]

Returns the item currently edited.

Returns: An instance of GenericTreeItem.

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • infobar
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • customtreectrl »
  • TreeTextCtrl


SVN Revision 67457 For customtreectrl

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • customtreectrl »
  • SVN Revision 67457 For customtreectrl

svn SVN Revision 67457 For customtreectrl

This file contains the SVN revision history for customtreectrl, at revision 67457.

Available information include commit date, the name of the committer, the file size, the SVN log messages and a diff from the previous version (if available).

File Information

  • Commit Date: 07-Apr-2010 16:35:19 UTC
  • Committer: RD
  • File Size: 260043 byte(s)

Log Messages

The following log message was entered by the committer:

typo

Diff To Previous Version (66732)

Version SVN diff:

--- wxPython/3rdParty/AGW/agw/customtreectrl.py     2011/01/23 09:12:31     66732
+++ wxPython/3rdParty/AGW/agw/customtreectrl.py     2011/04/13 18:03:05     67457
@@ -102,7 +102,7 @@
And a style you can use to force the horizontal alignment of all the widgets
attached to the tree items:

-- ``TR_ALIGN_WINDOWS``: aligns horizontally the windows belongiing to the item on the
+- ``TR_ALIGN_WINDOWS``: aligns horizontally the windows belonging to the item on the
same tree level.

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • customtreectrl »
  • SVN Revision 67457 For customtreectrl


SVN Revision 68021 For customtreectrl

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • customtreectrl »
  • SVN Revision 68021 For customtreectrl

svn SVN Revision 68021 For customtreectrl

This file contains the SVN revision history for customtreectrl, at revision 68021.

Available information include commit date, the name of the committer, the file size, the SVN log messages and a diff from the previous version (if available).

File Information

  • Commit Date: 30-Mar-2010 04:15:46 UTC
  • Committer: AG
  • File Size: 263572 byte(s)

Log Messages

The following log message was entered by the committer:

  • Fixed bug #13269 for CustomTreeCtrl and HyperTreeList (thanks to Frank Niessink);
  • Fixed bug #13268 for AuiToolBar;
  • Fixed bug #13107 on AuiNotebook.

Diff To Previous Version (67457)

Version SVN diff:

--- wxPython/3rdParty/AGW/agw/customtreectrl.py     2011/04/13 18:03:05     67457
+++ wxPython/3rdParty/AGW/agw/customtreectrl.py     2011/06/22 19:56:23     68021
@@ -3,7 +3,7 @@
# Inspired By And Heavily Based On wxGenericTreeCtrl.
#
# Andrea Gavana, @ 17 May 2006
-# Latest Revision: 23 Jan 2011, 10.00 GMT
+# Latest Revision: 21 Jun 2011, 22.00 GMT
#
#
# TODO List
@@ -74,6 +74,7 @@
* Whatever non-toplevel widget can be attached next to an item;
* Possibility to horizontally align the widgets attached to tree items on the
same tree level.
+* Possibility to align the widgets attached to tree items to the rightmost edge of CustomTreeCtrl;
* Default selection style, gradient (horizontal/vertical) selection style and Windows
Vista selection style;
* Customized drag and drop images built on the fly;
@@ -99,12 +100,13 @@
- ``TR_AUTO_CHECK_PARENT``: automatically checks/unchecks the item parent;
- ``TR_AUTO_TOGGLE_CHILD``: automatically toggles the item children.

-And a style you can use to force the horizontal alignment of all the widgets
+And two styles you can use to force the horizontal alignment of all the widgets
attached to the tree items:

- ``TR_ALIGN_WINDOWS``: aligns horizontally the windows belonging to the item on the
same tree level.
-
+- ``TR_ALIGN_WINDOWS_RIGHT``: aligns to the rightmost position the windows belonging
+  to the item on the same tree level.

All the methods available in `wx.TreeCtrl` are also available in CustomTreeCtrl.

@@ -166,6 +168,7 @@
``TR_AUTO_TOGGLE_CHILD``            0x8000 Only meaningful foe checkbox-type items: when a parent item is checked/unchecked its children are toggled accordingly.
``TR_AUTO_CHECK_PARENT``           0x10000 Only meaningful foe checkbox-type items: when a child item is checked/unchecked its parent item is checked/unchecked as well.
``TR_ALIGN_WINDOWS``               0x20000 Flag used to align windows (in items with windows) at the same horizontal position.
+``TR_ALIGN_WINDOWS_RIGHT``         0x40000 Flag used to align windows (in items with windows) to the rightmost edge of `CustomTreeCtrl`.
============================== =========== ==================================================

@@ -209,14 +212,14 @@

CustomTreeCtrl is distributed under the wxPython license.

-Latest Revision: Andrea Gavana @ 23 Jan 2011, 10.00 GMT
+Latest Revision: Andrea Gavana @ 21 Jun 2011, 22.00 GMT

-Version 2.3
+Version 2.4

"""

# Version Info
-__version__ = "2.3"
+__version__ = "2.4"

import wx
from wx.lib.expando import ExpandoTextCtrl
@@ -300,6 +303,8 @@
""" its parent item is checked/unchecked as well. """
TR_ALIGN_WINDOWS = 0x20000                                     # to align windows horizontally for items at the same level
""" Flag used to align windows (in items with windows) at the same horizontal position. """
+TR_ALIGN_WINDOWS_RIGHT = 0x40000                               # to align windows to the rightmost edge of CustomTreeCtrl
+""" Flag used to align windows (in items with windows) to the rightmost edge of `CustomTreeCtrl`."""

TR_DEFAULT_STYLE = wx.TR_DEFAULT_STYLE                         # default style for the tree control
""" The set of flags that are closest to the defaults for the native control for a""" \
@@ -999,10 +1004,10 @@

# -----------------------------------------------------------------------------
-# Auxiliary Classes: TreeRenameTimer
+# Auxiliary Classes: TreeEditTimer
# -----------------------------------------------------------------------------

-class TreeRenameTimer(wx.Timer):
+class TreeEditTimer(wx.Timer):
""" Timer used for enabling in-place edit."""

def __init__(self, owner):
@@ -1020,7 +1025,7 @@
def Notify(self):
""" The timer has expired. """

-        self._owner.OnRenameTimer()
+        self._owner.OnEditTimer()

# -----------------------------------------------------------------------------
@@ -1130,10 +1135,10 @@
# needs to be notified that the user decided
# not to change the tree item label, and that
# the edit has been cancelled
-            self._owner.OnRenameCancelled(self._itemEdited)
+            self._owner.OnCancelEdit(self._itemEdited)
return True

-        if not self._owner.OnRenameAccept(self._itemEdited, value):
+        if not self._owner.OnAcceptEdit(self._itemEdited, value):
# vetoed by the user
return False

@@ -1149,7 +1154,7 @@
if not self._finished:
self._finished = True
self._owner.SetFocusIgnoringChildren()
-            self._owner.ResetTextControl()
+            self._owner.ResetEditControl()

def OnChar(self, event):
@@ -1221,7 +1226,7 @@
# focus problems:

if not self.AcceptChanges():
-                self._owner.OnRenameCancelled(self._itemEdited)
+                self._owner.OnCancelEdit(self._itemEdited)

# We must let the native text control handle focus, too, otherwise
# it could have problems with the cursor (e.g., in wxGTK).
@@ -1231,7 +1236,7 @@
def StopEditing(self):
"""Suddenly stops the editing."""

-        self._owner.OnRenameCancelled(self._itemEdited)
+        self._owner.OnCancelEdit(self._itemEdited)
self.Finish()

@@ -2282,6 +2287,7 @@
``TR_AUTO_TOGGLE_CHILD``            0x8000 Only meaningful foe checkbox-type items: when a parent item is checked/unchecked its children are toggled accordingly.
``TR_AUTO_CHECK_PARENT``           0x10000 Only meaningful foe checkbox-type items: when a child item is checked/unchecked its parent item is checked/unchecked as well.
``TR_ALIGN_WINDOWS``               0x20000 Flag used to align windows (in items with windows) at the same horizontal position.
+         ``TR_ALIGN_WINDOWS_RIGHT``         0x40000 Flag used to align windows (in items with windows) to the rightmost edge of `CustomTreeCtrl`.
============================== =========== ==================================================

:param `validator`: window validator;
@@ -2322,9 +2328,9 @@
self._dragImage = None
self._underMouse = None

-        # TextCtrl initial settings for editable items
-        self._textCtrl = None
-        self._renameTimer = None
+        # EditCtrl initial settings for editable items
+        self._editCtrl = None
+        self._editTimer = None

# This one allows us to handle Freeze() and Thaw() calls
self._freezeCount = 0
@@ -2477,10 +2483,10 @@

# Here there may be something I miss... do I have to destroy
# something else?
-        if self._renameTimer and self._renameTimer.IsRunning():
-            self._renameTimer.Stop()
-            del self._renameTimer
-            self._renameTimer = None
+        if self._editTimer and self._editTimer.IsRunning():
+            self._editTimer.Stop()
+            del self._editTimer
+            self._editTimer = None

if self._findTimer and self._findTimer.IsRunning():
self._findTimer.Stop()
@@ -3063,7 +3069,7 @@

:see: The L{__init__} method for the `agwStyle` parameter description.
"""
-
+
# Do not try to expand the root node if it hasn't been created yet
if self._anchor and not self.HasAGWFlag(TR_HIDE_ROOT) and agwStyle & TR_HIDE_ROOT:

@@ -4110,12 +4116,12 @@
return lastGoodItem

-    def ResetTextControl(self):
-        """ Called by L{TreeTextCtrl} when it marks itself for deletion. """
+    def ResetEditControl(self):
+        """ Called by L{EditCtrl} when it marks itself for deletion. """

-        if self._textCtrl is not None:
-            self._textCtrl.Destroy()
-            self._textCtrl = None
+        if self._editCtrl is not None:
+            self._editCtrl.Destroy()
+            self._editCtrl = None

self.CalculatePositions()
self.Refresh()
@@ -4442,8 +4448,8 @@
:param `item`: an instance of L{GenericTreeItem}.
"""

-        if self._textCtrl != None and item != self._textCtrl.item() and self.IsDescendantOf(item, self._textCtrl.item()):
-            self._textCtrl.StopEditing()
+        if self._editCtrl != None and item != self._editCtrl.item() and self.IsDescendantOf(item, self._editCtrl.item()):
+            self._editCtrl.StopEditing()

if item != self._key_current and self.IsDescendantOf(item, self._key_current):
self._key_current = None
@@ -4479,9 +4485,9 @@

self._dirty = True     # do this first so stuff below doesn't cause flicker

-        if self._textCtrl != None and self.IsDescendantOf(item, self._textCtrl.item()):
+        if self._editCtrl != None and self.IsDescendantOf(item, self._editCtrl.item()):
# can't delete the item being edited, cancel editing it first
-            self._textCtrl.StopEditing()
+            self._editCtrl.StopEditing()

parent = item.GetParent()

@@ -5859,8 +5865,14 @@
if item.GetHeight() > item.GetWindowSize()[1]:
ya += (item.GetHeight() - item.GetWindowSize()[1])/2

-            if align and level in self.absoluteWindows:
-                wndx = self.absoluteWindows[level] + item.GetX() + 2
+            if align == 1:
+                # Horizontal alignment of windows
+                if level in self.absoluteWindows:
+                    wndx = self.absoluteWindows[level] + item.GetX() + 2
+
+            elif align == 2:
+                # Rightmost alignment of windows
+                wndx = self.GetClientSize().x - item.GetWindowSize().x - 2

if not wnd.IsShown():
wnd.Show()
@@ -5880,8 +5892,16 @@
:param `dc`: an instance of `wx.DC`;
:param `level`: the item level in the tree hierarchy;
:param `y`: the current vertical position in the `wx.PyScrolledWindow`;
-        :param `align`: ``True`` if we want to align windows (in items with windows)
-         at the same horizontal position.
+        :param `align`: an integer specifying the alignment type:
+
+         =============== =========================================
+         `align` Value   Description
+         =============== =========================================
+                0        No horizontal alignment of windows (in items with windows).
+                1        Windows (in items with windows) are aligned at the same horizontal position.
+                2        Windows (in items with windows) are aligned at the rightmost edge of L{CustomTreeCtrl}.
+         =============== =========================================
+
"""

x = level*self._indent
@@ -6113,7 +6133,13 @@
dc.SetFont(self._normalFont)
dc.SetPen(self._dottedPen)

-        align = self.HasAGWFlag(TR_ALIGN_WINDOWS)
+        align = 0
+
+        if self.HasAGWFlag(TR_ALIGN_WINDOWS):
+            align = 1
+        elif self.HasAGWFlag(TR_ALIGN_WINDOWS_RIGHT):
+            align = 2
+
y = 2
self.PaintLevel(self._anchor, dc, 0, y, align)

@@ -6125,7 +6151,11 @@
:param `event`: a `wx.SizeEvent` event to be processed.
"""

-        self.RefreshSelected()
+        if self.HasAGWFlag(TR_ALIGN_WINDOWS_RIGHT) and self._itemWithWindow:
+            self.RefreshItemWithWindows()
+        else:
+            self.RefreshSelected()
+
event.Skip()

@@ -6608,11 +6638,11 @@
else:
wx.YieldIfNeeded()

-        if self._textCtrl != None and item != self._textCtrl.item():
-            self._textCtrl.StopEditing()
+        if self._editCtrl != None and item != self._editCtrl.item():
+            self._editCtrl.StopEditing()

-        self._textCtrl = TreeTextCtrl(self, item=item)
-        self._textCtrl.SetFocus()
+        self._editCtrl = TreeTextCtrl(self, item=item)
+        self._editCtrl.SetFocus()

def GetEditControl(self):
@@ -6622,12 +6652,12 @@
simultaneously).
"""

-        return self._textCtrl
+        return self._editCtrl

-    def OnRenameAccept(self, item, value):
+    def OnAcceptEdit(self, item, value):
"""
-        Called by L{TreeTextCtrl}, to accept the changes and to send the
+        Called by L{EditCtrl}, to accept the changes and to send the
``EVT_TREE_END_LABEL_EDIT`` event.

:param `item`: an instance of L{GenericTreeItem};
@@ -6643,9 +6673,9 @@
return not self.GetEventHandler().ProcessEvent(le) or le.IsAllowed()

-    def OnRenameCancelled(self, item):
+    def OnCancelEdit(self, item):
"""
-        Called by L{TreeTextCtrl}, to cancel the changes and to send the
+        Called by L{EditCtrl}, to cancel the changes and to send the
``EVT_TREE_END_LABEL_EDIT`` event.

:param `item`: an instance of L{GenericTreeItem}.
@@ -6661,8 +6691,8 @@
self.GetEventHandler().ProcessEvent(le)

-    def OnRenameTimer(self):
-        """ The timer for renaming has expired. Start editing. """
+    def OnEditTimer(self):
+        """ The timer for editing has expired. Start editing. """

self.Edit(self._current)

@@ -6686,7 +6716,7 @@
underMouseChanged = underMouse != self._underMouse

if underMouse and (flags & TREE_HITTEST_ONITEM) and not event.LeftIsDown() and \
-           not self._isDragging and (not self._renameTimer or not self._renameTimer.IsRunning()):
+           not self._isDragging and (not self._editTimer or not self._editTimer.IsRunning()):
underMouse = underMouse
else:
underMouse = None
@@ -6701,8 +6731,8 @@
# Determines what item we are hovering over and need a tooltip for
hoverItem = thisItem

-        # We do not want a tooltip if we are dragging, or if the rename timer is running
-        if underMouseChanged and not self._isDragging and (not self._renameTimer or not self._renameTimer.IsRunning()):
+        # We do not want a tooltip if we are dragging, or if the edit timer is running
+        if underMouseChanged and not self._isDragging and (not self._editTimer or not self._editTimer.IsRunning()):

if hoverItem is not None:
# Ask the tree control what tooltip (if any) should be shown
@@ -6867,14 +6897,14 @@
self._dragCount = 0

if item == None:
-                if self._textCtrl != None and item != self._textCtrl.item():
-                    self._textCtrl.StopEditing()
+                if self._editCtrl != None and item != self._editCtrl.item():
+                    self._editCtrl.StopEditing()
return  # we hit the blank area

if event.RightDown():

-                if self._textCtrl != None and item != self._textCtrl.item():
-                    self._textCtrl.StopEditing()
+                if self._editCtrl != None and item != self._editCtrl.item():
+                    self._editCtrl.StopEditing()

self._hasFocus = True
self.SetFocusIgnoringChildren()
@@ -6915,17 +6945,17 @@

if item == self._current and (flags & TREE_HITTEST_ONITEMLABEL) and self.HasAGWFlag(TR_EDIT_LABELS):

-                        if self._renameTimer:
+                        if self._editTimer:

-                            if self._renameTimer.IsRunning():
+                            if self._editTimer.IsRunning():

-                                self._renameTimer.Stop()
+                                self._editTimer.Stop()

else:

-                            self._renameTimer = TreeRenameTimer(self)
+                            self._editTimer = TreeEditTimer(self)

-                        self._renameTimer.Start(_DELAY, True)
+                        self._editTimer.Start(_DELAY, True)

self._lastOnSame = False

@@ -6933,12 +6963,12 @@
else: # !RightDown() && !LeftUp() ==> LeftDown() || LeftDClick()

if not item or not item.IsEnabled():
-                    if self._textCtrl != None and item != self._textCtrl.item():
-                        self._textCtrl.StopEditing()
+                    if self._editCtrl != None and item != self._editCtrl.item():
+                        self._editCtrl.StopEditing()
return

-                if self._textCtrl != None and item != self._textCtrl.item():
-                    self._textCtrl.StopEditing()
+                if self._editCtrl != None and item != self._editCtrl.item():
+                    self._editCtrl.StopEditing()

self._hasFocus = True
self.SetFocusIgnoringChildren()
@@ -7001,8 +7031,8 @@
if event.LeftDClick():

# double clicking should not start editing the item label
-                    if self._renameTimer:
-                        self._renameTimer.Stop()
+                    if self._editTimer:
+                        self._editTimer.Stop()

self._lastOnSame = False

@@ -7059,15 +7089,23 @@
#        event.Skip()

-    def CalculateSize(self, item, dc, level=-1, align=False):
+    def CalculateSize(self, item, dc, level=-1, align=0):
"""
Calculates overall position and size of an item.

:param `item`: an instance of L{GenericTreeItem};
:param `dc`: an instance of `wx.DC`;
:param `level`: the item level in the tree hierarchy;
-        :param `align`: ``True`` if we want to align windows (in items with windows)
-         at the same horizontal position.
+        :param `align`: an integer specifying the alignment type:
+
+         =============== =========================================
+         `align` Value   Description
+         =============== =========================================
+                0        No horizontal alignment of windows (in items with windows).
+                1        Windows (in items with windows) are aligned at the same horizontal position.
+                2        Windows (in items with windows) are aligned at the rightmost edge of L{CustomTreeCtrl}.
+         =============== =========================================
+
"""

attr = item.GetAttributes()
@@ -7124,19 +7162,19 @@
totalHeight = max(total_h, item.GetWindowSize()[1])

if level >= 0 and wnd:
-            if not align:
+            if align == 0:
if level in self.absoluteWindows:
self.absoluteWindows[level] = max(self.absoluteWindows[level], image_w+text_w+wcheck+2)
else:
self.absoluteWindows[level] = image_w+text_w+wcheck+2
-            else:
+            elif align == 1:
self.absoluteWindows[level] = max(self.absoluteWindows[level], image_w+text_w+wcheck+2)

item.SetWidth(totalWidth)
item.SetHeight(totalHeight)

-    def CalculateLevel(self, item, dc, level, y, align=False):
+    def CalculateLevel(self, item, dc, level, y, align=0):
"""
Calculates the level of an item inside the tree hierarchy.

@@ -7144,8 +7182,16 @@
:param `dc`: an instance of `wx.DC`;
:param `level`: the item level in the tree hierarchy;
:param `y`: the current vertical position inside the `wx.PyScrolledWindow`;
-        :param `align`: ``True`` if we want to align windows (in items with windows)
-         at the same horizontal position.
+        :param `align`: an integer specifying the alignment type:
+
+         =============== =========================================
+         `align` Value   Description
+         =============== =========================================
+                0        No horizontal alignment of windows (in items with windows).
+                1        Windows (in items with windows) are aligned at the same horizontal position.
+                2        Windows (in items with windows) are aligned at the rightmost edge of L{CustomTreeCtrl}.
+         =============== =========================================
+
"""

x = level*self._indent
@@ -7202,9 +7248,10 @@
y = 2
y = self.CalculateLevel(self._anchor, dc, 0, y) # start recursion

-        if self.HasAGWFlag(TR_ALIGN_WINDOWS):
+        if self.HasAGWFlag(TR_ALIGN_WINDOWS) or self.HasAGWFlag(TR_ALIGN_WINDOWS_RIGHT):
+            align = (self.HasAGWFlag(TR_ALIGN_WINDOWS) and [1] or [2])[0]
y = 2
-            y = self.CalculateLevel(self._anchor, dc, 0, y, align=True) # start recursion
+            y = self.CalculateLevel(self._anchor, dc, 0, y, align) # start recursion

def RefreshSubtree(self, item):
@@ -7280,6 +7327,33 @@
self.RefreshSelectedUnder(child)

+    def RefreshItemWithWindows(self, item=None):
+        """
+        Refreshes the items with which a window is associated.
+
+        :param `item`: an instance of L{GenericTreeItem}. If `item` is ``None``, then the
+         recursive refresh starts from the root node.
+
+        :note: This method is called only if the style ``TR_ALIGN_WINDOWS_RIGHT`` is used.
+        """
+
+        if self._freezeCount:
+            return
+
+        if item is None:
+            if self._anchor:
+                self.RefreshItemWithWindows(self._anchor)
+                return
+
+        wnd = item.GetWindow()
+        if wnd and wnd.IsShown():
+            self.RefreshLine(item)
+
+        children = item.GetChildren()
+        for child in children:
+            self.RefreshItemWithWindows(child)
+
+
def Freeze(self):
"""
Freeze L{CustomTreeCtrl}.

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • customtreectrl »
  • SVN Revision 68021 For customtreectrl


SVN Revision 68362 For customtreectrl

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • customtreectrl »
  • SVN Revision 68362 For customtreectrl

svn SVN Revision 68362 For customtreectrl

This file contains the SVN revision history for customtreectrl, at revision 68362.

Available information include commit date, the name of the committer, the file size, the SVN log messages and a diff from the previous version (if available).

File Information

  • Commit Date: 16-Feb-2010 15:34:56 UTC
  • Committer: AG
  • File Size: 263586 byte(s)

Log Messages

The following log message was entered by the committer:

  • All of AGW: change my work e-mail from KPO to Maersk Oil (silly commit)

Diff To Previous Version (68021)

Version SVN diff:

--- wxPython/3rdParty/AGW/agw/customtreectrl.py     2011/06/22 19:56:23     68021
+++ wxPython/3rdParty/AGW/agw/customtreectrl.py     2011/07/24 21:36:47     68362
@@ -28,7 +28,7 @@
# For All Kind Of Problems, Requests Of Enhancements And Bug Reports, Please
# Write To Me At:
#
-# gavana@kpo.kz
+# andrea.gavana@maerskoil.com
# andrea.gavana@gmail.com
#
# Or, Obviously, To The wxPython Mailing List!!!

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • customtreectrl »
  • SVN Revision 68362 For customtreectrl


SVN Revision 68439 For customtreectrl

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • customtreectrl »
  • SVN Revision 68439 For customtreectrl

svn SVN Revision 68439 For customtreectrl

This file contains the SVN revision history for customtreectrl, at revision 68439.

Available information include commit date, the name of the committer, the file size, the SVN log messages and a diff from the previous version (if available).

File Information

  • Commit Date: 11-Dec-2009 11:51:15 UTC
  • Committer: AG
  • File Size: 263602 byte(s)

Log Messages

The following log message was entered by the committer:

CustomTreeCtrl: fix a silly mistake on RecurseOnChildren(): when there are no more children, GetNextChild() returns None, which does not have an IsOK() method so throws an AttributeError. Thanks to Jill Holliday for the bug report and the patch.

Diff To Previous Version (68362)

Version SVN diff:

--- wxPython/3rdParty/AGW/agw/customtreectrl.py     2011/07/24 21:36:47     68362
+++ wxPython/3rdParty/AGW/agw/customtreectrl.py     2011/07/27 17:17:15     68439
@@ -3,7 +3,7 @@
# Inspired By And Heavily Based On wxGenericTreeCtrl.
#
# Andrea Gavana, @ 17 May 2006
-# Latest Revision: 21 Jun 2011, 22.00 GMT
+# Latest Revision: 27 Jul 2011, 19.00 GMT
#
#
# TODO List
@@ -212,7 +212,7 @@

CustomTreeCtrl is distributed under the wxPython license.

-Latest Revision: Andrea Gavana @ 21 Jun 2011, 22.00 GMT
+Latest Revision: Andrea Gavana @ 27 Jul 2011, 19.00 GMT

Version 2.4

@@ -7513,8 +7513,9 @@
"""

child, cookie = self.GetFirstChild(item)
+        lastheight = 0

-        while child.IsOk():
+        while child:

rect = self.GetBoundingRect(child, True)

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • customtreectrl »
  • SVN Revision 68439 For customtreectrl


SVN Revision 68455 For customtreectrl

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • customtreectrl »
  • SVN Revision 68455 For customtreectrl

svn SVN Revision 68455 For customtreectrl

This file contains the SVN revision history for customtreectrl, at revision 68455.

Available information include commit date, the name of the committer, the file size, the SVN log messages and a diff from the previous version (if available).

File Information

  • Commit Date: 10-Dec-2009 21:22:23 UTC
  • Committer: AG
  • File Size: 263649 byte(s)

Log Messages

The following log message was entered by the committer:

CustomTreeCtrl: when expanding an item shows the vertical scrollbar, collapsing it leaves the scrollbar showing even if it’s no longer needed. Call AdjustMyScrollbars() inside the Collapse() method to prevent this behaviour. Thanks to Jill Holliday for the bug report and the patch.

Diff To Previous Version (68439)

Version SVN diff:

--- wxPython/3rdParty/AGW/agw/customtreectrl.py     2011/07/27 17:17:15     68439
+++ wxPython/3rdParty/AGW/agw/customtreectrl.py     2011/07/29 20:09:55     68455
@@ -3,7 +3,7 @@
# Inspired By And Heavily Based On wxGenericTreeCtrl.
#
# Andrea Gavana, @ 17 May 2006
-# Latest Revision: 27 Jul 2011, 19.00 GMT
+# Latest Revision: 29 Jul 2011, 21.00 GMT
#
#
# TODO List
@@ -212,7 +212,7 @@

CustomTreeCtrl is distributed under the wxPython license.

-Latest Revision: Andrea Gavana @ 27 Jul 2011, 19.00 GMT
+Latest Revision: Andrea Gavana @ 29 Jul 2011, 21.00 GMT

Version 2.4

@@ -4666,6 +4666,8 @@

if self._hasWindows:
self.HideWindows()
+
+        self.AdjustMyScrollbars()

event.SetEventType(wxEVT_TREE_ITEM_COLLAPSED)
self.GetEventHandler().ProcessEvent(event)

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • customtreectrl »
  • SVN Revision 68455 For customtreectrl


SVN Revision 68486 For customtreectrl

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • customtreectrl »
  • SVN Revision 68486 For customtreectrl

svn SVN Revision 68486 For customtreectrl

This file contains the SVN revision history for customtreectrl, at revision 68486.

Available information include commit date, the name of the committer, the file size, the SVN log messages and a diff from the previous version (if available).

File Information

  • Commit Date: 10-Dec-2009 18:09:38 UTC
  • Committer: AG
  • File Size: 263659 byte(s)

Log Messages

The following log message was entered by the committer:

CustomTreeCtrl: Correct GetLineHeight for the silly new “true division” behaviour of Python. Thanks to Nat Echols for the bug report.

Diff To Previous Version (68455)

Version SVN diff:

--- wxPython/3rdParty/AGW/agw/customtreectrl.py     2011/07/29 20:09:55     68455
+++ wxPython/3rdParty/AGW/agw/customtreectrl.py     2011/08/01 18:16:47     68486
@@ -3,7 +3,7 @@
# Inspired By And Heavily Based On wxGenericTreeCtrl.
#
# Andrea Gavana, @ 17 May 2006
-# Latest Revision: 29 Jul 2011, 21.00 GMT
+# Latest Revision: 01 Aug 2011, 20.00 GMT
#
#
# TODO List
@@ -212,7 +212,7 @@

CustomTreeCtrl is distributed under the wxPython license.

-Latest Revision: Andrea Gavana @ 29 Jul 2011, 21.00 GMT
+Latest Revision: Andrea Gavana @ 01 Aug 2011, 20.00 GMT

Version 2.4

@@ -5476,9 +5476,9 @@
"""

if self.GetAGWWindowStyleFlag() & TR_HAS_VARIABLE_ROW_HEIGHT:
-            return item.GetHeight()
+            return int(item.GetHeight())
else:
-            return self._lineHeight
+            return int(self._lineHeight)

def DrawVerticalGradient(self, dc, rect, hasfocus):

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • customtreectrl »
  • SVN Revision 68486 For customtreectrl


SVN Revision 68510 For customtreectrl

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • customtreectrl »
  • SVN Revision 68510 For customtreectrl

svn SVN Revision 68510 For customtreectrl

This file contains the SVN revision history for customtreectrl, at revision 68510.

Available information include commit date, the name of the committer, the file size, the SVN log messages and a diff from the previous version (if available).

File Information

  • Commit Date: 17-Sep-2009 15:44:57 UTC
  • Committer: AG
  • File Size: 263661 byte(s)

Log Messages

The following log message was entered by the committer:

FlatNotebook, CustomTreeCtrl: possibly fix bug 13377 by setting background/foreground colours compatible with the system settings.

Diff To Previous Version (68486)

Version SVN diff:

--- wxPython/3rdParty/AGW/agw/customtreectrl.py     2011/08/01 18:16:47     68486
+++ wxPython/3rdParty/AGW/agw/customtreectrl.py     2011/08/03 19:50:42     68510
@@ -3,7 +3,7 @@
# Inspired By And Heavily Based On wxGenericTreeCtrl.
#
# Andrea Gavana, @ 17 May 2006
-# Latest Revision: 01 Aug 2011, 20.00 GMT
+# Latest Revision: 03 Aug 2011, 22.00 GMT
#
#
# TODO List
@@ -212,7 +212,7 @@

CustomTreeCtrl is distributed under the wxPython license.

-Latest Revision: Andrea Gavana @ 01 Aug 2011, 20.00 GMT
+Latest Revision: Andrea Gavana @ 03 Aug 2011, 22.00 GMT

Version 2.4

@@ -2435,7 +2435,7 @@

attr = self.GetDefaultAttributes()
self.SetOwnForegroundColour(attr.colFg)
-        self.SetOwnBackgroundColour(wx.WHITE)
+        self.SetOwnBackgroundColour(attr.colBg)

if not self._hasFont:
self.SetOwnFont(attr.font)

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • customtreectrl »
  • SVN Revision 68510 For customtreectrl


SVN Revision 68881 For customtreectrl

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • customtreectrl »
  • SVN Revision 68881 For customtreectrl

svn SVN Revision 68881 For customtreectrl

This file contains the SVN revision history for customtreectrl, at revision 68881.

Available information include commit date, the name of the committer, the file size, the SVN log messages and a diff from the previous version (if available).

File Information

  • Commit Date: 14-Jul-2009 13:27:20 UTC
  • Committer: AG
  • File Size: 266473 byte(s)

Log Messages

The following log message was entered by the committer:

  • AGW: General overhaul of the documentation, much improved. All the widgets have their own sample usage in the docs as well;

  • FlatNotebook: Added the FNB_NAV_BUTTONS_WHEN_NEEDED style, which hides the navigation left/right arrows if all tabs fit;

  • RibbonBar: - Added the EVT_RIBBONBAR_TAB_LEFT_DCLICK event, which generates a special event

    when a ribbon bar tab is double-clicked;

    • Added support for toggle buttons;
    • Improved support for ribbon panel sizers: panels with sizers should now automatically minimise at small sizes, and behave properly when popping up from a minimised state;
    • Added tooltips via SetToolTip for those buttons which have the help_string attribute set.

  • XLSGrid: a new widget was added to AGW, termed XLSGrid. It’s based on wx.grid.Grid and can be used to faithfully reproduce the appearance of a Microsoft Excel spreadsheets.

Diff To Previous Version (68510)

Version SVN diff:

--- wxPython/3rdParty/AGW/agw/customtreectrl.py     2011/08/03 19:50:42     68510
+++ wxPython/3rdParty/AGW/agw/customtreectrl.py     2011/08/25 16:40:17     68881
@@ -3,7 +3,7 @@
# Inspired By And Heavily Based On wxGenericTreeCtrl.
#
# Andrea Gavana, @ 17 May 2006
-# Latest Revision: 03 Aug 2011, 22.00 GMT
+# Latest Revision: 17 Aug 2011, 15.00 GMT
#
#
# TODO List
@@ -39,23 +39,23 @@

"""
-CustomTreeCtrl is a class that mimics the behaviour of `wx.TreeCtrl`, with some more
+L{CustomTreeCtrl} is a class that mimics the behaviour of `wx.TreeCtrl`, with some more
enhancements.

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

-CustomTreeCtrl is a class that mimics the behaviour of `wx.TreeCtrl`, with almost the
+L{CustomTreeCtrl} is a class that mimics the behaviour of `wx.TreeCtrl`, with almost the
same base functionalities plus some more enhancements. This class does not rely on
the native control, as it is a full owner-drawn tree control.
-Apart of the base functionalities of CustomTreeCtrl (described below), in addition
+Apart of the base functionalities of L{CustomTreeCtrl} (described below), in addition
to the standard `wx.TreeCtrl` behaviour this class supports:

* CheckBox-type items: checkboxes are easy to handle, just selected or unselected
state with no particular issues in handling the item's children;
* Added support for 3-state value checkbox items;
-* RadioButton-type items: since I elected to put radiobuttons in CustomTreeCtrl, I
+* RadioButton-type items: since I elected to put radiobuttons in L{CustomTreeCtrl}, I
needed some way to handle them, that made sense. So, I used the following approach:

- All peer-nodes that are radiobuttons will be mutually exclusive. In other words,
@@ -68,21 +68,21 @@
* Hyperlink-type items: they look like an hyperlink, with the proper mouse cursor on
hovering;
* Multiline text items (**note**: to add a newline character in a multiline item, press
-  ``Shift`` + ``Enter`` as the ``Enter`` key alone is consumed by CustomTreeCtrl to finish
+  ``Shift`` + ``Enter`` as the ``Enter`` key alone is consumed by L{CustomTreeCtrl} to finish
the editing and ``Ctrl`` + ``Enter`` is consumed by the platform for tab navigation);
* Enabling/disabling items (together with their plain or grayed out icons);
* Whatever non-toplevel widget can be attached next to an item;
* Possibility to horizontally align the widgets attached to tree items on the
same tree level.
-* Possibility to align the widgets attached to tree items to the rightmost edge of CustomTreeCtrl;
+* Possibility to align the widgets attached to tree items to the rightmost edge of L{CustomTreeCtrl};
* Default selection style, gradient (horizontal/vertical) selection style and Windows
Vista selection style;
* Customized drag and drop images built on the fly;
-* Setting the CustomTreeCtrl item buttons to a personalized imagelist;
-* Setting the CustomTreeCtrl check/radio item icons to a personalized imagelist;
+* Setting the L{CustomTreeCtrl} item buttons to a personalized imagelist;
+* Setting the L{CustomTreeCtrl} check/radio item icons to a personalized imagelist;
* Changing the style of the lines that connect the items (in terms of `wx.Pen` styles);
-* Using an image as a CustomTreeCtrl background (currently only in "tile" mode);
-* Adding images to any item in the leftmost area of the CustomTreeCtrl client window.
+* Using an image as a L{CustomTreeCtrl} background (currently only in "tile" mode);
+* Adding images to any item in the leftmost area of the L{CustomTreeCtrl} client window.

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

@@ -90,7 +90,7 @@
Base Functionalities
====================

-CustomTreeCtrl supports all the wx.TreeCtrl styles, except:
+L{CustomTreeCtrl} supports all the `wx.TreeCtrl` styles, except:

- ``TR_EXTENDED``: supports for this style is on the todo list (am I sure of this?).

@@ -108,13 +108,74 @@
- ``TR_ALIGN_WINDOWS_RIGHT``: aligns to the rightmost position the windows belonging
to the item on the same tree level.

-All the methods available in `wx.TreeCtrl` are also available in CustomTreeCtrl.
+All the methods available in `wx.TreeCtrl` are also available in L{CustomTreeCtrl}.

+Usage
+=====
+
+Usage example::
+
+    import wx
+    import wx.lib.agw.customtreectrl as CT
+
+    class MyFrame(wx.Frame):
+
+        def __init__(self, parent):
+
+            wx.Frame.__init(self, parent, -1, "CustomTreeCtrl Demo")
+
+            # Create a CustomTreeCtrl instance
+            custom_tree = CT.CustomTreeCtrl(self, agwStyle=wx.TR_DEFAULT_STYLE)
+
+            # Add a root node to it
+            root = custom_tree.AddRoot("The Root Item")
+
+            # Create an image list to add icons next to an item
+            il = wx.ImageList(16, 16)
+            fldridx     = il.Add(wx.ArtProvider_GetBitmap(wx.ART_FOLDER,      wx.ART_OTHER, 16))
+            fldropenidx = il.Add(wx.ArtProvider_GetBitmap(wx.ART_FILE_OPEN,   wx.ART_OTHER, 16))
+            fileidx     = il.Add(wx.ArtProvider_GetBitmap(wx.ART_NORMAL_FILE, wx.ART_OTHER, 16))
+
+            custom_tree.SetImageList(il)
+
+            custom_tree.SetItemImage(root, fldridx, wx.TreeItemIcon_Normal)
+            custom_tree.SetItemImage(root, fldropenidx, wx.TreeItemIcon_Expanded)
+
+            for x in range(15):
+                child = custom_tree.AppendItem(root, "Item %d" % x)
+                custom_tree.SetItemImage(child, fldridx, wx.TreeItemIcon_Normal)
+                custom_tree.SetItemImage(child, fldropenidx, wx.TreeItemIcon_Expanded)
+
+                for y in range(5):
+                    last = custom_tree.AppendItem(child, "item %d-%s" % (x, chr(ord("a")+y)))
+                    custom_tree.SetItemImage(last, fldridx, wx.TreeItemIcon_Normal)
+                    custom_tree.SetItemImage(last, fldropenidx, wx.TreeItemIcon_Expanded)
+
+                    for z in range(5):
+                        item = custom_tree.AppendItem(last,  "item %d-%s-%d" % (x, chr(ord("a")+y), z))
+                        custom_tree.SetItemImage(item, fileidx, wx.TreeItemIcon_Normal)
+                        custom_tree.SetItemImage(item, smileidx, wx.TreeItemIcon_Selected)
+
+            custom_tree.Expand(self.root)
+
+
+    # our normal wxApp-derived class, as usual
+
+    app = wx.PySimpleApp()
+
+    frame = MyFrame(None)
+    app.SetTopWindow(frame)
+    frame.Show()
+
+    app.MainLoop()
+
+
+
Events
======

-All the events supported by `wx.TreeCtrl` are also available in CustomTreeCtrl, with
+All the events supported by `wx.TreeCtrl` are also available in L{CustomTreeCtrl}, with
a few exceptions:

- ``EVT_TREE_GET_INFO`` (don't know what this means);
@@ -122,7 +183,7 @@
- ``EVT_TREE_ITEM_MIDDLE_CLICK`` (not implemented, but easy to add);
- ``EVT_TREE_STATE_IMAGE_CLICK`` (no need for that, look at the checking events below).

-Plus, CustomTreeCtrl supports the events related to the checkbutton-type items:
+Plus, L{CustomTreeCtrl} supports the events related to the checkbutton-type items:

- ``EVT_TREE_ITEM_CHECKING``: an item is being checked;
- ``EVT_TREE_ITEM_CHECKED``: an item has been checked.
@@ -136,7 +197,7 @@
Supported Platforms
===================

-CustomTreeCtrl has been tested on the following platforms:
+L{CustomTreeCtrl} has been tested on the following platforms:
* Windows (Windows XP);
* GTK (Thanks to Michele Petrazzo);
* Mac OS (Thanks to John Jackson).
@@ -168,7 +229,7 @@
``TR_AUTO_TOGGLE_CHILD``            0x8000 Only meaningful foe checkbox-type items: when a parent item is checked/unchecked its children are toggled accordingly.
``TR_AUTO_CHECK_PARENT``           0x10000 Only meaningful foe checkbox-type items: when a child item is checked/unchecked its parent item is checked/unchecked as well.
``TR_ALIGN_WINDOWS``               0x20000 Flag used to align windows (in items with windows) at the same horizontal position.
-``TR_ALIGN_WINDOWS_RIGHT``         0x40000 Flag used to align windows (in items with windows) to the rightmost edge of `CustomTreeCtrl`.
+``TR_ALIGN_WINDOWS_RIGHT``         0x40000 Flag used to align windows (in items with windows) to the rightmost edge of L{CustomTreeCtrl}.
============================== =========== ==================================================

@@ -181,29 +242,29 @@
Event Name                     Description
============================== ==================================================
``EVT_TREE_BEGIN_DRAG``        Begin dragging with the left mouse button.
-``EVT_TREE_BEGIN_LABEL_EDIT``  Begin editing a label. This can be prevented by calling `Veto()`.
+``EVT_TREE_BEGIN_LABEL_EDIT``  Begin editing a label. This can be prevented by calling L{Veto}.
``EVT_TREE_BEGIN_RDRAG``       Begin dragging with the right mouse button.
``EVT_TREE_DELETE_ITEM``       Delete an item.
``EVT_TREE_END_DRAG``          End dragging with the left or right mouse button.
-``EVT_TREE_END_LABEL_EDIT``    End editing a label. This can be prevented by calling `Veto()`.
-``EVT_TREE_GET_INFO``          Request information from the application (not implemented in `CustomTreeCtrl`).
+``EVT_TREE_END_LABEL_EDIT``    End editing a label. This can be prevented by calling L{Veto}.
+``EVT_TREE_GET_INFO``          Request information from the application (not implemented in L{CustomTreeCtrl}).
``EVT_TREE_ITEM_ACTIVATED``    The item has been activated, i.e. chosen by double clicking it with mouse or from keyboard.
``EVT_TREE_ITEM_CHECKED``      A checkbox or radiobox type item has been checked.
``EVT_TREE_ITEM_CHECKING``     A checkbox or radiobox type item is being checked.
``EVT_TREE_ITEM_COLLAPSED``    The item has been collapsed.
-``EVT_TREE_ITEM_COLLAPSING``   The item is being collapsed. This can be prevented by calling `Veto()`.
+``EVT_TREE_ITEM_COLLAPSING``   The item is being collapsed. This can be prevented by calling L{Veto}.
``EVT_TREE_ITEM_EXPANDED``     The item has been expanded.
-``EVT_TREE_ITEM_EXPANDING``    The item is being expanded. This can be prevented by calling `Veto()`.
+``EVT_TREE_ITEM_EXPANDING``    The item is being expanded. This can be prevented by calling L{Veto}.
``EVT_TREE_ITEM_GETTOOLTIP``   The opportunity to set the item tooltip is being given to the application (call `TreeEvent.SetToolTip`).
``EVT_TREE_ITEM_HYPERLINK``    An hyperlink type item has been clicked.
``EVT_TREE_ITEM_MENU``         The context menu for the selected item has been requested, either by a right click or by using the menu key.
-``EVT_TREE_ITEM_MIDDLE_CLICK`` The user has clicked the item with the middle mouse button (not implemented in `CustomTreeCtrl`).
+``EVT_TREE_ITEM_MIDDLE_CLICK`` The user has clicked the item with the middle mouse button (not implemented in L{CustomTreeCtrl}).
``EVT_TREE_ITEM_RIGHT_CLICK``  The user has clicked the item with the right mouse button.
``EVT_TREE_KEY_DOWN``          A key has been pressed.
``EVT_TREE_SEL_CHANGED``       Selection has changed.
-``EVT_TREE_SEL_CHANGING``      Selection is changing. This can be prevented by calling `Veto()`.
-``EVT_TREE_SET_INFO``          Information is being supplied to the application (not implemented in `CustomTreeCtrl`).
-``EVT_TREE_STATE_IMAGE_CLICK`` The state image has been clicked (not implemented in `CustomTreeCtrl`).
+``EVT_TREE_SEL_CHANGING``      Selection is changing. This can be prevented by calling L{Veto}.
+``EVT_TREE_SET_INFO``          Information is being supplied to the application (not implemented in L{CustomTreeCtrl}).
+``EVT_TREE_STATE_IMAGE_CLICK`` The state image has been clicked (not implemented in L{CustomTreeCtrl}).
============================== ==================================================

@@ -212,7 +273,7 @@

CustomTreeCtrl is distributed under the wxPython license.

-Latest Revision: Andrea Gavana @ 03 Aug 2011, 22.00 GMT
+Latest Revision: Andrea Gavana @ 17 Aug 2011, 15.00 GMT

Version 2.4

@@ -244,15 +305,23 @@

# Enum for different images associated with a treectrl item
TreeItemIcon_Normal = 0              # not selected, not expanded
+""" The tree item is not selected and not expanded. """
TreeItemIcon_Selected = 1            #     selected, not expanded
+""" The tree item is selected and not expanded. """
TreeItemIcon_Expanded = 2            # not selected,     expanded
+""" The tree item is not selected but expanded. """
TreeItemIcon_SelectedExpanded = 3    #     selected,     expanded
-
+""" The tree item is selected and expanded. """
TreeItemIcon_Checked = 0             # check button,     checked
+""" The item's check button is checked. """
TreeItemIcon_NotChecked = 1          # check button, not checked
+""" The item's check button is not checked. """
TreeItemIcon_Undetermined = 2        # check button, undetermined
+""" The item's check button is in undetermined state (used only for a 3-state check button). """
TreeItemIcon_Flagged = 3             # radio button,     selected
+""" The item's radio button is checked. """
TreeItemIcon_NotFlagged = 4          # radio button, not selected
+""" The item's radio button is not checked. """

# ----------------------------------------------------------------------------
# CustomTreeCtrl flags
@@ -304,7 +373,7 @@
TR_ALIGN_WINDOWS = 0x20000                                     # to align windows horizontally for items at the same level
""" Flag used to align windows (in items with windows) at the same horizontal position. """
TR_ALIGN_WINDOWS_RIGHT = 0x40000                               # to align windows to the rightmost edge of CustomTreeCtrl
-""" Flag used to align windows (in items with windows) to the rightmost edge of `CustomTreeCtrl`."""
+""" Flag used to align windows (in items with windows) to the rightmost edge of L{CustomTreeCtrl}."""

TR_DEFAULT_STYLE = wx.TR_DEFAULT_STYLE                         # default style for the tree control
""" The set of flags that are closest to the defaults for the native control for a""" \
@@ -398,27 +467,27 @@
EVT_TREE_BEGIN_RDRAG = wx.EVT_TREE_BEGIN_RDRAG
""" Begin dragging with the right mouse button. """
EVT_TREE_BEGIN_LABEL_EDIT = wx.EVT_TREE_BEGIN_LABEL_EDIT
-""" Begin editing a label. This can be prevented by calling `Veto()`. """
+""" Begin editing a label. This can be prevented by calling L{Veto}. """
EVT_TREE_END_LABEL_EDIT = wx.EVT_TREE_END_LABEL_EDIT
-""" End editing a label. This can be prevented by calling `Veto()`. """
+""" End editing a label. This can be prevented by calling L{Veto}. """
EVT_TREE_DELETE_ITEM = wx.EVT_TREE_DELETE_ITEM
""" Delete an item. """
EVT_TREE_GET_INFO = wx.EVT_TREE_GET_INFO
-""" Request information from the application (not implemented in `CustomTreeCtrl`). """
+""" Request information from the application (not implemented in L{CustomTreeCtrl}). """
EVT_TREE_SET_INFO = wx.EVT_TREE_SET_INFO
-""" Information is being supplied to the application (not implemented in `CustomTreeCtrl`). """
+""" Information is being supplied to the application (not implemented in L{CustomTreeCtrl}). """
EVT_TREE_ITEM_EXPANDED = wx.EVT_TREE_ITEM_EXPANDED
""" The item has been expanded. """
EVT_TREE_ITEM_EXPANDING = wx.EVT_TREE_ITEM_EXPANDING
-""" The item is being expanded. This can be prevented by calling `Veto()`. """
+""" The item is being expanded. This can be prevented by calling L{Veto}. """
EVT_TREE_ITEM_COLLAPSED = wx.EVT_TREE_ITEM_COLLAPSED
""" The item has been collapsed. """
EVT_TREE_ITEM_COLLAPSING = wx.EVT_TREE_ITEM_COLLAPSING
-""" The item is being collapsed. This can be prevented by calling `Veto()`. """
+""" The item is being collapsed. This can be prevented by calling L{Veto}. """
EVT_TREE_SEL_CHANGED = wx.EVT_TREE_SEL_CHANGED
""" Selection has changed. """
EVT_TREE_SEL_CHANGING = wx.EVT_TREE_SEL_CHANGING
-""" Selection is changing. This can be prevented by calling `Veto()`. """
+""" Selection is changing. This can be prevented by calling L{Veto}. """
EVT_TREE_KEY_DOWN = wx.EVT_TREE_KEY_DOWN
""" A key has been pressed. """
EVT_TREE_ITEM_ACTIVATED = wx.EVT_TREE_ITEM_ACTIVATED
@@ -426,11 +495,11 @@
EVT_TREE_ITEM_RIGHT_CLICK = wx.EVT_TREE_ITEM_RIGHT_CLICK
""" The user has clicked the item with the right mouse button. """
EVT_TREE_ITEM_MIDDLE_CLICK = wx.EVT_TREE_ITEM_MIDDLE_CLICK
-""" The user has clicked the item with the middle mouse button (not implemented in `CustomTreeCtrl`). """
+""" The user has clicked the item with the middle mouse button (not implemented in L{CustomTreeCtrl}). """
EVT_TREE_END_DRAG = wx.EVT_TREE_END_DRAG
""" End dragging with the left or right mouse button. """
EVT_TREE_STATE_IMAGE_CLICK = wx.EVT_TREE_STATE_IMAGE_CLICK
-""" The state image has been clicked (not implemented in `CustomTreeCtrl`). """
+""" The state image has been clicked (not implemented in L{CustomTreeCtrl}). """
EVT_TREE_ITEM_GETTOOLTIP = wx.EVT_TREE_ITEM_GETTOOLTIP
""" The opportunity to set the item tooltip is being given to the application (call `TreeEvent.SetToolTip`). """
EVT_TREE_ITEM_MENU = wx.EVT_TREE_ITEM_MENU
@@ -1040,7 +1109,9 @@
This is a subclass of `ExpandoTextCtrl` as L{CustomTreeCtrl} supports multiline
text items.

-    :note: To add a newline character in a multiline item, press ``Shift`` + ``Enter`` as the ``Enter`` key alone is consumed by L{CustomTreeCtrl} to finish the editing and ``Ctrl`` + ``Enter`` is consumed by the platform for tab navigation.
+    :note: To add a newline character in a multiline item, press ``Shift`` + ``Enter`` as the ``Enter``
+     key alone is consumed by L{CustomTreeCtrl} to finish the editing and ``Ctrl`` + ``Enter`` is
+     consumed by the platform for tab navigation.
"""

def __init__(self, owner, item=None):
@@ -2287,7 +2358,7 @@
``TR_AUTO_TOGGLE_CHILD``            0x8000 Only meaningful foe checkbox-type items: when a parent item is checked/unchecked its children are toggled accordingly.
``TR_AUTO_CHECK_PARENT``           0x10000 Only meaningful foe checkbox-type items: when a child item is checked/unchecked its parent item is checked/unchecked as well.
``TR_ALIGN_WINDOWS``               0x20000 Flag used to align windows (in items with windows) at the same horizontal position.
-         ``TR_ALIGN_WINDOWS_RIGHT``         0x40000 Flag used to align windows (in items with windows) to the rightmost edge of `CustomTreeCtrl`.
+         ``TR_ALIGN_WINDOWS_RIGHT``         0x40000 Flag used to align windows (in items with windows) to the rightmost edge of L{CustomTreeCtrl}.
============================== =========== ==================================================

:param `validator`: window validator;
@@ -7460,8 +7531,10 @@
Gets the size which best suits the window: for a control, it would be the
minimal size which doesn't truncate the control, for a panel - the same size
as it would have after a call to `Fit()`.
+
+        :note: Overridden from `wx.PyScrolledWindow`.
"""
-
+
# something is better than nothing...
# 100x80 is what the MSW version will get from the default
# wxControl::DoGetBestSize

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • customtreectrl »
  • SVN Revision 68881 For customtreectrl


SVN Revision 68955 For customtreectrl

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • customtreectrl »
  • SVN Revision 68955 For customtreectrl

svn SVN Revision 68955 For customtreectrl

This file contains the SVN revision history for customtreectrl, at revision 68955.

Available information include commit date, the name of the committer, the file size, the SVN log messages and a diff from the previous version (if available).

File Information

  • Commit Date: 22-Jun-2009 15:50:25 UTC
  • Committer: AG
  • File Size: 284980 byte(s)

Log Messages

The following log message was entered by the committer:

  • Fix GetPrevExpanded/GetNextExpanded issues with CustomTreeCtrl and HyperTreeList. Thanks to struppimoppi for the partial patch.

Diff To Previous Version (68881)

Version SVN diff:

--- wxPython/3rdParty/AGW/agw/customtreectrl.py     2011/08/25 16:40:17     68881
+++ wxPython/3rdParty/AGW/agw/customtreectrl.py     2011/08/29 19:08:33     68955
@@ -271,7 +271,7 @@
License And Version
===================

-CustomTreeCtrl is distributed under the wxPython license.
+L{CustomTreeCtrl} is distributed under the wxPython license.

Latest Revision: Andrea Gavana @ 17 Aug 2011, 15.00 GMT

@@ -519,6 +519,9 @@
Creates a disabled-looking bitmap starting from the input one.

:param `original`: an instance of `wx.Bitmap` to be greyed-out.
+
+    :return: An instance of `wx.Bitmap`, containing a disabled-looking
+     representation of the original item image.
"""

img = original.ConvertToImage()
@@ -532,8 +535,8 @@

:param `win`: an instance of `wx.Window`;
:param `dc`: an instance of `wx.DC`;
-    :param `rect`: the client rectangle where to draw the tree item button;
-    :param `flags`: contains ``wx.CONTROL_EXPANDED`` bit for expanded tree items.
+    :param `wx.Rect` `rect`: the client rectangle where to draw the tree item button;
+    :param integer `flags`: contains ``wx.CONTROL_EXPANDED`` bit for expanded tree items.

:note: This is a simple replacement of `wx.RendererNative.DrawTreeItemButton`.

@@ -568,9 +571,17 @@
Translate the key or mouse event flag to the type of selection we
are dealing with.

-    :param `style`: the main L{CustomTreeCtrl} window style flag;
-    :param `shiftDown`: ``True`` if the ``Shift`` key is pressed, ``False`` otherwise;
-    :param `ctrlDown`: ``True`` if the ``Ctrl`` key is pressed, ``False`` otherwise;
+    :param integer `style`: the main L{CustomTreeCtrl} window style flag;
+    :param bool `shiftDown`: ``True`` if the ``Shift`` key is pressed, ``False`` otherwise;
+    :param bool `ctrlDown`: ``True`` if the ``Ctrl`` key is pressed, ``False`` otherwise;
+
+    :return: A 3-elements tuple, with the following elements:
+
+     - `is_multiple`: ``True`` if L{CustomTreeCtrl} has the ``TR_MULTIPLE`` flag set, ``False`` otherwise;
+     - `extended_select`: ``True`` if the ``Shift`` key is pressend and if L{CustomTreeCtrl} has the
+       ``TR_MULTIPLE`` flag set, ``False`` otherwise;
+     - `unselect_others`: ``True`` if the ``Ctrl`` key is pressend and if L{CustomTreeCtrl} has the
+       ``TR_MULTIPLE`` flag set, ``False`` otherwise.
"""

is_multiple = (style & TR_MULTIPLE) != 0
@@ -693,7 +704,12 @@

def CreateBitmap(self):
-        """ Actually creates the drag and drop bitmap for L{DragImage}. """
+        """
+        Actually creates the drag and drop bitmap for L{DragImage}.
+
+        :return: An instance of L{DragImage}, a close representation of the item's
+         appearance (i.e., a screenshot of the item).
+        """

memory = wx.MemoryDC()

@@ -743,16 +759,20 @@
# ----------------------------------------------------------------------------

class TreeItemAttr(object):
-    """ Creates the item attributes (text colour, background colour and font). """
+    """
+    Creates the item attributes (text colour, background colour and font).
+
+    :note: This class is inspired by the wxWidgets generic implementation of `wx.TreeItemAttr`.
+    """

def __init__(self, colText=wx.NullColour, colBack=wx.NullColour, font=wx.NullFont):
"""
Default class constructor.
For internal use: do not call it in your code!

-        :param `colText`: the text colour;
-        :param `colBack`: the tree item background colour;
-        :param `font`: the tree item font.
+        :param `colText`: the text colour, an instance of `wx.Colour`;
+        :param `colBack`: the tree item background colour, an instance of `wx.Colour`;
+        :param `font`: the tree item font, an instance of `wx.Font`.
"""

self._colText = colText
@@ -792,38 +812,62 @@

# accessors
def HasTextColour(self):
-        """Returns whether the attribute has text colour."""
+        """
+        Returns whether the attribute has text colour.
+
+        :return: ``True`` if the text colour attribute has been set, ``False`` otherwise.
+        """

return self._colText != wx.NullColour

def HasBackgroundColour(self):
-        """Returns whether the attribute has background colour."""
+        """
+        Returns whether the attribute has background colour.
+
+        :return: ``True`` if the background colour attribute has been set, ``False`` otherwise.
+        """

return self._colBack != wx.NullColour

def HasFont(self):
-        """Returns whether the attribute has font."""
+        """
+        Returns whether the attribute has font.
+
+        :return: ``True`` if the font attribute has been set, ``False`` otherwise.
+        """

return self._font != wx.NullFont

# getters
def GetTextColour(self):
-        """Returns the attribute text colour."""
+        """
+        Returns the attribute text colour.
+
+        :return: An instance of `wx.Colour`.
+        """

return self._colText

def GetBackgroundColour(self):
-        """Returns the attribute background colour."""
+        """
+        Returns the attribute background colour.
+
+        :return: An instance of `wx.Colour`.
+        """

return self._colBack

def GetFont(self):
-        """Returns the attribute font."""
+        """
+        Returns the attribute font.
+
+        :return: An instance of `wx.Font`.
+        """

return self._font

@@ -837,7 +881,7 @@

class CommandTreeEvent(wx.PyCommandEvent):
"""
-    CommandTreeEvent is a special subclassing of `wx.PyCommandEvent`.
+    L{CommandTreeEvent} is a special subclassing of `wx.PyCommandEvent`.

:note: Not all the accessors make sense for all the events, see the event description for every method in this class.
"""
@@ -848,12 +892,12 @@
Default class constructor.
For internal use: do not call it in your code!

-        :param `evtType`: the event type;
-        :param `evtId`: the event identifier;
+        :param integer `evtType`: the event type;
+        :param integer `evtId`: the event identifier;
:param `item`: an instance of L{GenericTreeItem};
-        :param `evtKey`: a character ordinal;
+        :param integer `evtKey`: a character ordinal;
:param `point`: an instance of `wx.Point`;
-        :param `label`: a L{GenericTreeItem} text label.
+        :param string `label`: a L{GenericTreeItem} text label.
"""

wx.PyCommandEvent.__init__(self, evtType, evtId, **kwargs)
@@ -867,6 +911,8 @@
"""
Gets the item on which the operation was performed or the newly selected
item for ``EVT_TREE_SEL_CHANGED`` and ``EVT_TREE_SEL_CHANGING`` events.
+
+        :return: An instance of L{GenericTreeItem}.
"""

return self._item
@@ -887,6 +933,8 @@
"""
Returns the previously selected item for ``EVT_TREE_SEL_CHANGED`` and
``EVT_TREE_SEL_CHANGING`` events.
+
+        :return: An instance of L{GenericTreeItem}.
"""

return self._itemOld
@@ -908,6 +956,8 @@
Returns the point where the mouse was when the drag operation started
(for ``EVT_TREE_BEGIN_DRAG`` and ``EVT_TREE_BEGIN_RDRAG`` events only)
or the click position.
+
+        :return: An instance of `wx.Point`.
"""

return self._pointDrag
@@ -926,13 +976,28 @@

def GetKeyEvent(self):
-        """ Returns the keyboard data (for ``EVT_TREE_KEY_DOWN`` event only)."""
+        """
+        Returns the keyboard data (for ``EVT_TREE_KEY_DOWN`` event only).
+
+        :return: An instance of `wx.KeyEvent`.
+        """

return self._evtKey

def GetKeyCode(self):
-        """ Returns the integer key code (for ``EVT_TREE_KEY_DOWN`` event only)."""
+        """
+        Returns the virtual key code. ASCII events return normal ASCII values, while
+        non-ASCII events return values such as ``wx.WXK_LEFT`` for the left cursor key.
+
+        This method is for ``EVT_TREE_KEY_DOWN`` events only.
+
+        :return: An integer representing the virtual key code.
+
+        :note: In Unicode build, the returned value is meaningful only if the user entered
+         a character that can be represented in current locale's default charset. You can
+         obtain the corresponding Unicode character using `GetUnicodeKey`.
+        """

return self._evtKey.GetKeyCode()

@@ -951,6 +1016,8 @@
"""
Returns the item text (for ``EVT_TREE_BEGIN_LABEL_EDIT`` and
``EVT_TREE_END_LABEL_EDIT`` events only).
+
+        :return: A string containing the item text.
"""

return self._label
@@ -961,7 +1028,7 @@
Sets the item text (for ``EVT_TREE_BEGIN_LABEL_EDIT`` and
``EVT_TREE_END_LABEL_EDIT`` events only).

-        :param `label`: a string containing the new item text.
+        :param string `label`: a string containing the new item text.
"""

self._label = label
@@ -971,6 +1038,8 @@
"""
Returns the edit cancel flag (for ``EVT_TREE_BEGIN_LABEL_EDIT`` and
``EVT_TREE_END_LABEL_EDIT`` events only).
+
+        :return: ``True`` is the item editing has been cancelled, ``False`` otherwise.
"""

return self._editCancelled
@@ -981,7 +1050,7 @@
Sets the edit cancel flag (for ``EVT_TREE_BEGIN_LABEL_EDIT`` and
``EVT_TREE_END_LABEL_EDIT`` events only).

-        :param `editCancelled`: ``True`` to cancel the editing, ``False`` otherwise.
+        :param bool `editCancelled`: ``True`` to cancel the editing, ``False`` otherwise.
"""

self._editCancelled = editCancelled
@@ -991,14 +1060,18 @@
"""
Sets the tooltip for the item (for ``EVT_TREE_ITEM_GETTOOLTIP`` events).

-        :param `tooltip`: a string representing the item tooltip.
+        :param string `tooltip`: a string representing the item tooltip.
"""

self._label = toolTip

def GetToolTip(self):
-        """Returns the tooltip for the item (for ``EVT_TREE_ITEM_GETTOOLTIP`` events)."""
+        """
+        Returns the tooltip for the item (for ``EVT_TREE_ITEM_GETTOOLTIP`` events).
+
+        :return: A string containing the item tooltip.
+        """

return self._label

@@ -1012,7 +1085,7 @@

class TreeEvent(CommandTreeEvent):
"""
-    `TreeEvent` is a special class for all events associated with tree controls.
+    L{TreeEvent} is a special class for all events associated with tree controls.

:note: Not all accessors make sense for all events, see the event descriptions below.
"""
@@ -1022,12 +1095,12 @@
Default class constructor.
For internal use: do not call it in your code!

-        :param `evtType`: the event type;
-        :param `evtId`: the event identifier;
+        :param integer `evtType`: the event type;
+        :param integer `evtId`: the event identifier;
:param `item`: an instance of L{GenericTreeItem};
-        :param `evtKey`: a character ordinal;
+        :param integer `evtKey`: a character ordinal;
:param `point`: an instance of `wx.Point`;
-        :param `label`: a L{GenericTreeItem} text label.
+        :param string `label`: a L{GenericTreeItem} text label.
"""

CommandTreeEvent.__init__(self, evtType, evtId, item, evtKey, point, label, **kwargs)
@@ -1035,7 +1108,11 @@

def GetNotifyEvent(self):
-        """Returns the actual `wx.NotifyEvent`."""
+        """
+        Returns the actual `wx.NotifyEvent`.
+
+        :return: An instance of `wx.NotifyEvent`.
+        """

return self.notify

@@ -1092,7 +1169,7 @@

def Notify(self):
-        """ The timer has expired. """
+        """ The timer has expired, starts the item editing. """

self._owner.OnEditTimer()

@@ -1106,7 +1183,7 @@
"""
Control used for in-place edit.

-    This is a subclass of `ExpandoTextCtrl` as L{CustomTreeCtrl} supports multiline
+    This is a subclass of `wx.lib.expando.ExpandoTextCtrl` as L{CustomTreeCtrl} supports multiline
text items.

:note: To add a newline character in a multiline item, press ``Shift`` + ``Enter`` as the ``Enter``
@@ -1121,6 +1198,9 @@

:param `owner`: the control parent (an instance of L{CustomTreeCtrl});
:param `item`: an instance of L{GenericTreeItem}.
+
+        :raise: `Exception` when the item has an associated image but the parent
+         L{CustomTreeCtrl} does not have a `wx.ImageList` assigned.
"""

self._owner = owner
@@ -1196,7 +1276,12 @@

def AcceptChanges(self):
-        """Accepts/refuses the changes made by the user."""
+        """
+        Accepts/rejects the changes made by the user.
+
+        :return: ``True`` if the changes to the item text have been accepted, ``False``
+         if they have been rejected (i.e., vetoed by the user).
+        """

value = self.GetValue()

@@ -1220,7 +1305,7 @@

def Finish(self):
-        """Finish editing."""
+        """ Finish editing. """

if not self._finished:
self._finished = True
@@ -1305,14 +1390,18 @@

def StopEditing(self):
-        """Suddenly stops the editing."""
+        """ Suddenly stops the editing. """

self._owner.OnCancelEdit(self._itemEdited)
self.Finish()

def item(self):
-        """Returns the item currently edited."""
+        """
+        Returns the item currently edited.
+
+        :return: An instance of L{GenericTreeItem}.
+        """

return self._itemEdited

@@ -1342,7 +1431,7 @@

def Notify(self):
-        """The timer has expired."""
+        """ The timer has expired, clear the `_findPrefix` attribute in L{CustomTreeCtrl}. """

self._owner._findPrefix = ""

@@ -1364,9 +1453,10 @@
Default class constructor.
For internal use: do not call it in your code!

-        :param `parent`: the tree item parent (may be ``None`` for root items);
-        :param `text`: the tree item text;
-        :param `ct_type`: the tree item kind. May be one of the following integers:
+        :param `parent`: the tree item parent, an instance of L{GenericTreeItem} (may
+         be ``None`` for root items);
+        :param string `text`: the tree item text;
+        :param integer `ct_type`: the tree item kind. May be one of the following integers:

=============== =========================================
`ct_type` Value Description
@@ -1377,13 +1467,13 @@
=============== =========================================

:param `wnd`: if not ``None``, a non-toplevel window to be displayed next to
-         the item;
-        :param `image`: an index within the normal image list specifying the image to
+         the item, an instance of `wx.Window`;
+        :param integer `image`: an index within the normal image list specifying the image to
use for the item in unselected state;
-        :param `selImage`: an index within the normal image list specifying the image to
+        :param integer `selImage`: an index within the normal image list specifying the image to
use for the item in selected state; if `image` > -1 and `selImage` is -1, the
same image is used for both selected and unselected items;
-        :param `data`: associate the given Python object `data` with the item.
+        :param object `data`: associate the given Python object `data` with the item.

:note: Regarding radiobutton-type items (with `ct_type` = 2), the following
approach is used:
@@ -1469,13 +1559,22 @@

def GetChildren(self):
-        """Returns the item's children."""
+        """
+        Returns the item's children.
+
+        :return: A Python list containing instances of L{GenericTreeItem}, representing
+         this item's children.
+        """

return self._children

def GetText(self):
-        """Returns the item text."""
+        """
+        Returns the item text.
+
+        :return: A string containing the item text.
+        """

return self._text

@@ -1484,7 +1583,7 @@
"""
Returns the item image for a particular item state.

-        :param `which`: can be one of the following bits:
+        :param integer `which`: can be one of the following bits:

================================= ========================
Item State                        Description
@@ -1495,6 +1594,8 @@
``TreeItemIcon_SelectedExpanded`` To get the selected expanded image (which is shown when an expanded item is currently selected)
================================= ========================

+        :return: An integer index that can be used to retrieve the item image inside
+         a `wx.ImageList`.
"""

return self._images[which]
@@ -1504,7 +1605,7 @@
"""
Returns the item check image.

-        :param `which`: can be one of the following bits:
+        :param integer `which`: can be one of the following bits:

================================= ========================
Item State                        Description
@@ -1516,6 +1617,9 @@
``TreeItemIcon_NotFlagged``       To get the radiobutton unchecked image
================================= ========================

+        :return: An integer index that can be used to retrieve the item check image inside
+         a `wx.ImageList`.
+
:note: This method is meaningful only for radio & check items.
"""

@@ -1526,13 +1630,21 @@
"""
Returns the leftmost image associated to this item, i.e. the image on the
leftmost part of the client area of L{CustomTreeCtrl}.
+
+        :return: An integer index that can be used to retrieve the item leftmost image inside
+         a `wx.ImageList`.
"""

return self._leftimage

def GetData(self):
-        """Returns the data associated to this item."""
+        """
+        Returns the data associated to this item.
+
+        :return: A Python object representing the item data, or ``None`` if no data
+         has been assigned to this item.
+        """

return self._data

@@ -1541,8 +1653,8 @@
"""
Sets the item image.

-        :param `image`: an index within the normal image list specifying the image to use;
-        :param `which`: the image kind.
+        :param integer `image`: an index within the normal image list specifying the image to use;
+        :param integer `which`: the image kind.

:see: L{GetImage} for a description of the `which` parameter.
"""
@@ -1555,7 +1667,7 @@
Sets the item leftmost image, i.e. the image associated to the item on the leftmost
part of the L{CustomTreeCtrl} client area.

-        :param `image`: an index within the left image list specifying the image to
+        :param integer `image`: an index within the left image list specifying the image to
use for the item in the leftmost part of the client area.
"""

@@ -1566,7 +1678,7 @@
"""
Sets the data associated to this item.

-        :param `data`: can be any Python object.
+        :param object `data`: can be any Python object.
"""

self._data = data
@@ -1576,7 +1688,7 @@
"""
Sets whether an item has the 'plus' button.

-        :param `has`: ``True`` to set the 'plus' button on the item, ``False`` otherwise.
+        :param bool `has`: ``True`` to set the 'plus' button on the item, ``False`` otherwise.
"""

self._hasPlus = has
@@ -1586,7 +1698,7 @@
"""
Sets the item font bold.

-        :parameter `bold`: ``True`` to have a bold font item, ``False`` otherwise.
+        :parameter bool `bold`: ``True`` to have a bold font item, ``False`` otherwise.
"""

self._isBold = bold
@@ -1596,20 +1708,20 @@
"""
Sets the item font italic.

-        :parameter `italic`: ``True`` to have an italic font item, ``False`` otherwise.
+        :parameter bool `italic`: ``True`` to have an italic font item, ``False`` otherwise.
"""

self._isItalic = italic

def GetX(self):
-        """Returns the `x` position on an item, in logical coordinates. """
+        """ Returns the `x` position on an item, in logical coordinates. """

return self._x

def GetY(self):
-        """Returns the `y` position on an item, in logical coordinates. """
+        """ Returns the `y` position on an item, in logical coordinates. """

return self._y

@@ -1618,7 +1730,7 @@
"""
Sets the `x` position on an item, in logical coordinates.

-        :param `x`: an integer specifying the x position of the item.
+        :param integer `x`: an integer specifying the x position of the item.
"""

self._x = x
@@ -1628,20 +1740,20 @@
"""
Sets the `y` position on an item, in logical coordinates.

-        :param `y`: an integer specifying the y position of the item.
+        :param integer `y`: an integer specifying the y position of the item.
"""

self._y = y

def GetHeight(self):
-        """Returns the height of the item."""
+        """ Returns the height of the item, in pixels. """

return self._height

def GetWidth(self):
-        """Returns the width of the item."""
+        """ Returns the width of the item, in pixels. """

return self._width

@@ -1650,7 +1762,7 @@
"""
Sets the item's height.

-        :param `h`: an integer specifying the item's height.
+        :param integer `h`: an integer specifying the item's height, in pixels.
"""

self._height = h
@@ -1660,7 +1772,7 @@
"""
Sets the item's width.

-        :param `w`: an integer specifying the item's width.
+        :param integer `w`: an integer specifying the item's width, in pixels.
"""

self._width = w
@@ -1670,7 +1782,8 @@
"""
Sets the window associated to the item.

-        :param `wnd`: a non-toplevel window to be displayed next to the item.
+        :param `wnd`: a non-toplevel window to be displayed next to the item, any
+         subclass of `wx.Window`.
"""

self._wnd = wnd
@@ -1700,13 +1813,17 @@

def GetWindow(self):
-        """Returns the window associated to the item (if any)."""
+        """
+        Returns the window associated to the item (if any).
+
+        :return: An instance of any `wx.Window` derived class, excluding top-level windows.
+        """

return self._wnd

def DeleteWindow(self):
-        """Deletes the window associated to the item (if any)."""
+        """ Deletes the window associated to the item (if any). """

if self._wnd:
self._wnd.Destroy()
@@ -1714,7 +1831,13 @@

def GetWindowEnabled(self):
-        """Returns whether the associated window is enabled or not."""
+        """
+        Returns whether the associated window is enabled or not.
+
+        :return: ``True`` if the associated window is enabled, ``False`` if it is disabled.
+
+        :raise: `Exception` when the item has no associated window.
+        """

if not self._wnd:
raise Exception("\nERROR: This Item Has No Window Associated")
@@ -1726,7 +1849,9 @@
"""
Sets whether the associated window is enabled or not.

-        :param `enable`: ``True`` to enable the associated window, ``False`` to disable it.
+        :param bool `enable`: ``True`` to enable the associated window, ``False`` to disable it.
+
+        :raise: `Exception` when the item has no associated window.
"""

if not self._wnd:
@@ -1737,7 +1862,7 @@

def GetWindowSize(self):
-        """Returns the associated window size."""
+        """ Returns the associated window size. """

return self._windowsize

@@ -1776,7 +1901,7 @@
"""
Sets the item type.

-        :param `ct_type`: May be one of the following integers:
+        :param integer `ct_type`: may be one of the following integers:

=============== =========================================
`ct_type` Value Description
@@ -1804,7 +1929,7 @@
"""
Sets whether the item is hypertext or not.

-        :param `hyper`: ``True`` to set hypertext behaviour, ``False`` otherwise.
+        :param bool `hyper`: ``True`` to set hypertext behaviour, ``False`` otherwise.
"""

self._hypertext = hyper
@@ -1814,20 +1939,20 @@
"""
Sets whether an hypertext item was visited or not.

-        :param `visited`: ``True`` to set a hypertext item as visited, ``False`` otherwise.
+        :param bool `visited`: ``True`` to set a hypertext item as visited, ``False`` otherwise.
"""

self._visited = visited

def GetVisited(self):
-        """Returns whether an hypertext item was visited or not."""
+        """ Returns whether an hypertext item was visited or not. """

return self._visited

def IsHyperText(self):
-        """Returns whether the item is hypetext or not."""
+        """ Returns whether the item is hypetext or not. """

return self._hypertext

@@ -1836,6 +1961,8 @@
"""
Gets the item parent (another instance of L{GenericTreeItem} or ``None`` for
root items.
+
+        :return: An instance of L{GenericTreeItem} or ``None`` for root items.
"""

return self._parent
@@ -1843,23 +1970,23 @@

def Insert(self, child, index):
"""
-        Inserts an item in the item children.
+        Inserts an item in the item children list for this item.

:param `child`: an instance of L{GenericTreeItem};
-        :param `index`: the index at which we should insert the new child.
+        :param integer `index`: the index at which we should insert the new child.
"""

self._children.insert(index, child)

def Expand(self):
-        """Expands the item."""
+        """ Expands the item. """

self._isCollapsed = False

def Collapse(self):
-        """Collapses the item."""
+        """ Collapses the item. """

self._isCollapsed = True

@@ -1868,26 +1995,38 @@
"""
Sets the item focus/unfocus.

-        :param `set`: ``True`` to set the focus to the item, ``False`` otherwise.
+        :param bool `set`: ``True`` to set the focus to the item, ``False`` otherwise.
"""

self._hasHilight = set

def HasChildren(self):
-        """Returns whether the item has children or not."""
+        """
+        Returns whether the item has children or not.
+
+        :return: ``True`` if the item has children, ``False`` otherwise.
+        """

return len(self._children) > 0

def IsSelected(self):
-        """Returns whether the item is selected or not."""
+        """
+        Returns whether the item is selected or not.
+
+        :return: ``True`` if the item is selected, ``False`` otherwise.
+        """

return self._hasHilight != 0

def IsExpanded(self):
-        """Returns whether the item is expanded or not."""
+        """
+        Returns whether the item is expanded or not.
+
+        :return: ``True`` if the item is expanded, ``False`` if it is collapsed.
+        """

return not self._isCollapsed

@@ -1913,6 +2052,8 @@
when it is checked and ``wx.CHK_UNDETERMINED`` when it's in the undetermined
state.

+        :raise: `Exception` when the item is not a 3-state checkbox item.
+
:note: This method raises an exception when the function is used with a 2-state
checkbox item.

@@ -1942,9 +2083,11 @@
"""
Sets the checkbox item to the given `state`.

-        :param `state`: can be one of: ``wx.CHK_UNCHECKED`` (check is off), ``wx.CHK_CHECKED``
+        :param integer `state`: can be one of: ``wx.CHK_UNCHECKED`` (check is off), ``wx.CHK_CHECKED``
(check is on) or ``wx.CHK_UNDETERMINED`` (check is mixed).

+        :raise: `Exception` when the item is not a 3-state checkbox item.
+
:note: This method raises an exception when the checkbox item is a 2-state checkbox
and setting the state to ``wx.CHK_UNDETERMINED``.

@@ -1961,7 +2104,7 @@
"""
Sets whether the item has a 3-state value checkbox assigned to it or not.

-        :param `allow`: ``True`` to set an item as a 3-state checkbox, ``False`` to set it
+        :param bool `allow`: ``True`` to set an item as a 3-state checkbox, ``False`` to set it
to a 2-state checkbox.

:return: ``True`` if the change was successful, ``False`` otherwise.
@@ -1991,7 +2134,7 @@
"""
Checks/unchecks an item.

-        :param `checked`: ``True`` to check an item, ``False`` to uncheck it.
+        :param bool `checked`: ``True`` to check an item, ``False`` to uncheck it.

:note: This is meaningful only for checkbox-like and radiobutton-like items.
"""
@@ -2000,19 +2143,31 @@

def HasPlus(self):
-        """Returns whether the item has the plus button or not."""
+        """
+        Returns whether the item has the plus button or not.
+
+        :return: ``True`` if the item has a 'plus' mark, ``False`` otherwise.
+        """

return self._hasPlus or self.HasChildren()

def IsBold(self):
-        """Returns whether the item font is bold or not."""
+        """
+        Returns whether the item font is bold or not.
+
+        :return: ``True`` if the item has bold text, ``False`` otherwise.
+        """

return self._isBold != 0

def IsItalic(self):
-        """Returns whether the item font is italic or not."""
+        """
+        Returns whether the item font is italic or not.
+
+        :return: ``True`` if the item has italic text, ``False`` otherwise.
+        """

return self._isItalic != 0

@@ -2021,26 +2176,38 @@
"""
Enables/disables the item.

-        :param `enable`: ``True`` to enable the item, ``False`` to disable it.
+        :param bool `enable`: ``True`` to enable the item, ``False`` to disable it.
"""

self._enabled = enable

def IsEnabled(self):
-        """Returns whether the item is enabled or not."""
+        """
+        Returns whether the item is enabled or not.
+
+        :return: ``True`` if the item is enabled, ``False`` if it is disabled.
+        """

return self._enabled

def GetAttributes(self):
-        """Returns the item attributes (font, colours)."""
+        """
+        Returns the item attributes (font, colours, etc...).
+
+        :return: An instance of L{TreeItemAttr}.
+        """

return self._attr

def Attr(self):
-        """Creates a new attribute (font, colours)."""
+        """
+        Creates a new attribute (font, colours, etc...) for this item.
+
+        :return: An instance of L{TreeItemAttr}.
+        """

if not self._attr:

@@ -2052,7 +2219,7 @@

def SetAttributes(self, attr):
"""
-        Sets the item attributes (font, colours).
+        Sets the item attributes (font, colours, etc...).

:param `attr`: an instance of L{TreeItemAttr}.
"""
@@ -2066,7 +2233,7 @@

def AssignAttributes(self, attr):
"""
-        Assigns the item attributes (font, colours).
+        Assigns the item attributes (font, colours, etc...) for this item.

:param `attr`: an instance of L{TreeItemAttr}.
"""
@@ -2109,7 +2276,7 @@
"""
Sets the item text.

-        :param `text`: the new item label.
+        :param string `text`: the new item label.
"""

self._text = text
@@ -2119,7 +2286,7 @@
"""
Gets the number of children of this item.

-        :param `recursively`: if ``True``, returns the total number of descendants,
+        :param bool `recursively`: if ``True``, returns the total number of descendants,
otherwise only one level of children is counted.
"""

@@ -2140,9 +2307,12 @@
"""
Returns the item size.

-        :param `x`: the current item's x position;
-        :param `y`: the current item's y position;
+        :param integer `x`: the current item's x position;
+        :param integer `y`: the current item's y position;
:param `theButton`: an instance of the main L{CustomTreeCtrl}.
+
+        :return: A tuple of (`x`, `y`) dimensions, in pixels, representing the
+         item's width and height.
"""

bottomY = self._y + theButton.GetLineHeight(self)
@@ -2164,12 +2334,12 @@

def HitTest(self, point, theCtrl, flags=0, level=0):
"""
-        HitTest method for an item. Called from the main window HitTest.
+        L{HitTest} method for an item. Called from the main window L{CustomTreeCtrl.HitTest}.

:param `point`: the point to test for the hit (an instance of `wx.Point`);
:param `theCtrl`: the main L{CustomTreeCtrl} tree;
-        :param `flags`: a bitlist of hit locations;
-        :param `level`: the item's level inside the tree hierarchy.
+        :param integer `flags`: a bitlist of hit locations;
+        :param integer `level`: the item's level inside the tree hierarchy.

:see: L{CustomTreeCtrl.HitTest} method for the flags explanation.
"""
@@ -2257,7 +2427,12 @@

def GetCurrentImage(self):
-        """Returns the current item image."""
+        """
+        Returns the current item image.
+
+        :return: An integer index that can be used to retrieve the item image inside
+         a `wx.ImageList`.
+        """

image = _NO_IMAGE

@@ -2287,7 +2462,12 @@

def GetCurrentCheckedImage(self):
-        """Returns the current item check image."""
+        """
+        Returns the current item check image.
+
+        :return: An integer index that can be used to retrieve the item check image inside
+         a `wx.ImageList`.
+        """

if self._type == 0:
return None
@@ -2316,7 +2496,7 @@

class CustomTreeCtrl(wx.PyScrolledWindow):
"""
-    CustomTreeCtrl is a class that mimics the behaviour of `wx.TreeCtrl`, with almost the
+    L{CustomTreeCtrl} is a class that mimics the behaviour of `wx.TreeCtrl`, with almost the
same base functionalities plus some more enhancements. This class does not rely on
the native control, as it is a full owner-drawn tree control.
"""
@@ -2327,14 +2507,16 @@
"""
Default class constructor.

-        :param `parent`: parent window. Must not be ``None``;
-        :param `id`: window identifier. A value of -1 indicates a default value;
+        :param `wx.Window` `parent`: parent window. Must not be ``None``;
+        :param integer `id`: window identifier. A value of -1 indicates a default value;
:param `pos`: the control position. A value of (-1, -1) indicates a default position,
chosen by either the windowing system or wxPython, depending on platform;
+        :type `pos`: tuple or `wx.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;
-        :param `style`: the underlying `wx.PyScrolledWindow` style;
-        :param `agwStyle`: the AGW-specific window style for L{CustomTreeCtrl}. It can be a
+        :type `size`: tuple or `wx.Size`
+        :param integer `style`: the underlying `wx.PyScrolledWindow` style;
+        :param integer `agwStyle`: the AGW-specific window style for L{CustomTreeCtrl}. It can be a
combination of the following bits:

============================== =========== ==================================================
@@ -2361,8 +2543,8 @@
``TR_ALIGN_WINDOWS_RIGHT``         0x40000 Flag used to align windows (in items with windows) to the rightmost edge of L{CustomTreeCtrl}.
============================== =========== ==================================================

-        :param `validator`: window validator;
-        :param `name`: window name.
+        :param `wx.Validator` `validator`: window validator;
+        :param string `name`: window name.
"""

self._current = self._key_current = self._anchor = self._select_me = None
@@ -2533,7 +2715,7 @@
"""
Can this window be given focus by mouse click?

-        :note: This method always returns ``True`` as we alsways accept focus from
+        :note: This method always returns ``True`` as we always accept focus from
mouse click.

:note: Overridden from `wx.PyScrolledWindow`.
@@ -2570,12 +2752,13 @@
"""
Returns a native looking checkbox or radio button bitmap.

-        :param `checkbox`: ``True`` to get a checkbox image, ``False`` for a radiobutton
-         one;
-        :param `checked`: ``True`` if the control is marked, ``False`` if it is not;
-        :param `enabled`: ``True`` if the control is enabled, ``False`` if it is not;
-        :param `x`: the width of the bitmap;
-        :param `y`: the height of the bitmap.
+        :param bool `checkbox`: ``True`` to get a checkbox image, ``False`` for a radiobutton one;
+        :param bool `checked`: ``True`` if the control is marked, ``False`` if it is not;
+        :param bool `enabled`: ``True`` if the control is enabled, ``False`` if it is not;
+        :param integer `x`: the width of the bitmap;
+        :param integer `y`: the height of the bitmap.
+
+        :return: An instance of `wx.Bitmap`, representing a native looking checkbox or radiobutton.
"""

bmp = wx.EmptyBitmap(x, y)
@@ -2626,19 +2809,19 @@

def GetIndent(self):
-        """ Returns the item indentation. """
+        """ Returns the item indentation, in pixels. """

return self._indent

def GetSpacing(self):
-        """ Returns the spacing between the start and the text. """
+        """ Returns the spacing between the start and the text, in pixels. """

return self._spacing

def GetRootItem(self):
-        """ Returns the root item. """
+        """ Returns the root item, an instance of L{GenericTreeItem}. """

return self._anchor

@@ -2647,6 +2830,8 @@
"""
Returns the current selection.

+        :return: An instance of L{GenericTreeItem}.
+
:note: This method is valid only with the style ``TR_SINGLE`` set. Use
L{GetSelections} for multiple-selections trees.
"""
@@ -2669,7 +2854,7 @@
Enables/disables the item children.

:param `item`: an instance of L{GenericTreeItem};
-        :param `enable`: ``True`` to enable the children, ``False`` otherwise.
+        :param bool `enable`: ``True`` to enable the children, ``False`` to disable them.

:note: This method is used internally.
"""
@@ -2697,8 +2882,8 @@
Enables/disables an item.

:param `item`: an instance of L{GenericTreeItem};
-        :param `enable`: ``True`` to enable the item, ``False`` otherwise;
-        :param `torefresh`: whether to redraw the item or not.
+        :param bool `enable`: ``True`` to enable the item, ``False`` to disable it;
+        :param bool `torefresh`: whether to redraw the item or not.
"""

if item.IsEnabled() == enable:
@@ -2744,7 +2929,11 @@

def GetDisabledColour(self):
-        """ Returns the colour for items in a disabled state. """
+        """
+        Returns the colour for items in a disabled state.
+
+        :return: An instance of `wx.Colour`.
+        """

return self._disabledColour

@@ -2755,6 +2944,8 @@

:param `item`: an instance of L{GenericTreeItem}.

+        :return: ``True`` if the item is in a 'checked' state, ``False`` otherwise.
+
:note: This method is meaningful only for checkbox-like and radiobutton-like items.
"""

@@ -2800,7 +2991,7 @@
Sets the checkbox item to the given `state`.

:param `item`: an instance of L{GenericTreeItem};
-        :param `state`: can be one of: ``wx.CHK_UNCHECKED`` (check is off), ``wx.CHK_CHECKED``
+        :param integer `state`: can be one of: ``wx.CHK_UNCHECKED`` (check is off), ``wx.CHK_CHECKED``
(check is on) or ``wx.CHK_UNDETERMINED`` (check is mixed).

:note: This method raises an exception when the checkbox item is a 2-state checkbox
@@ -2817,7 +3008,7 @@
Sets whether the item has a 3-state value checkbox assigned to it or not.

:param `item`: an instance of L{GenericTreeItem};
-        :param `allow`: ``True`` to set an item as a 3-state checkbox, ``False`` to set it
+        :param bool `allow`: ``True`` to set an item as a 3-state checkbox, ``False`` to set it
to a 2-state checkbox.

:return: ``True`` if the change was successful, ``False`` otherwise.
@@ -2833,8 +3024,8 @@
Used internally to avoid ``EVT_TREE_ITEM_CHECKED`` events.

:param `item`: an instance of L{GenericTreeItem};
-        :param `checked`: ``True`` to check an item, ``False`` to uncheck it;
-        :param `torefresh`: whether to redraw the item or not.
+        :param bool `checked`: ``True`` to check an item, ``False`` to uncheck it;
+        :param bool `torefresh`: whether to redraw the item or not.
"""

if item.GetType() == 0:
@@ -2853,7 +3044,7 @@
Used internally to handle radio node parent correctly.

:param `item`: an instance of L{GenericTreeItem};
-        :param `checked`: ``True`` to check an item, ``False`` to uncheck it.
+        :param bool `checked`: ``True`` to check an item, ``False`` to uncheck it.
"""

e = TreeEvent(wxEVT_TREE_ITEM_CHECKING, self.GetId())
@@ -2880,7 +3071,7 @@
events ``EVT_TREE_ITEM_CHECKING`` and ``EVT_TREE_ITEM_CHECKED``.

:param `item`: an instance of L{GenericTreeItem};
-        :param `checked`: for a radiobutton-type item, ``True`` to check it, ``False``
+        :param bool `checked`: for a radiobutton-type item, ``True`` to check it, ``False``
to uncheck it. For a checkbox-type item, it can be one of ``wx.CHK_UNCHECKED``
when the checkbox is unchecked, ``wx.CHK_CHECKED`` when it is checked and
``wx.CHK_UNDETERMINED`` when it's in the undetermined state.
@@ -2960,7 +3151,7 @@
Transverses the tree and checks/unchecks the items.

:param `item`: an instance of L{GenericTreeItem};
-        :param `checked`: ``True`` to check an item, ``False`` to uncheck it.
+        :param bool `checked`: ``True`` to check an item, ``False`` to uncheck it.

:note: This method is meaningful only for checkbox-like and radiobutton-like items.
"""
@@ -2983,7 +3174,7 @@
Traverses up the tree and checks/unchecks parent items.

:param `item`: an instance of L{GenericTreeItem};
-        :param `checked`: ``True`` to check an item, ``False`` to uncheck it.
+        :param bool `checked`: ``True`` to check an item, ``False`` to uncheck it.

:note: This method is meaningful only for checkbox-like and radiobutton-like items.
"""
@@ -3008,7 +3199,7 @@
Programatically check/uncheck item children.

:param `item`: an instance of L{GenericTreeItem};
-        :param `checked`: ``True`` to check an item, ``False`` to uncheck it.
+        :param bool `checked`: ``True`` to check an item, ``False`` to uncheck it.

:note: This method is meaningful only for checkbox-like and radiobutton-like items.

@@ -3028,7 +3219,7 @@
Used internally.

:param `item`: an instance of L{GenericTreeItem};
-        :param `checked`: ``True`` to check an item, ``False`` to uncheck it.
+        :param bool `checked`: ``True`` to check an item, ``False`` to uncheck it.

:note: This method is meaningful only for radiobutton-like items.
"""
@@ -3080,7 +3271,7 @@
"""
Sets the indentation for L{CustomTreeCtrl}.

-        :param `indent`: an integer representing the indentation for the items in the tree.
+        :param integer `indent`: an integer representing the indentation for the items in the tree.
"""

self._indent = indent
@@ -3091,7 +3282,7 @@
"""
Sets the spacing between items in L{CustomTreeCtrl}.

-        :param `spacing`: an integer representing the spacing between items in the tree.
+        :param integer `spacing`: an integer representing the spacing between items in the tree.
"""

self._spacing = spacing
@@ -3113,7 +3304,7 @@
Returns the item children count.

:param `item`: an instance of L{GenericTreeItem};
-        :param `recursively`: if ``True``, returns the total number of descendants,
+        :param bool `recursively`: if ``True``, returns the total number of descendants,
otherwise only one level of children is counted.
"""

@@ -3124,7 +3315,7 @@
"""
Returns ``True`` if L{CustomTreeCtrl} has the `flag` bit set.

-        :param `flag`: any possible window style for L{CustomTreeCtrl}.
+        :param integer `flag`: any possible window style for L{CustomTreeCtrl}.

:see: The L{__init__} method for the `flag` parameter description.
"""
@@ -3136,7 +3327,7 @@
"""
Sets the L{CustomTreeCtrl} window style.

-        :param `agwStyle`: the new L{CustomTreeCtrl} window style.
+        :param integer `agwStyle`: the new L{CustomTreeCtrl} window style.

:see: The L{__init__} method for the `agwStyle` parameter description.
"""
@@ -3173,7 +3364,12 @@

def HasButtons(self):
-        """Returns whether L{CustomTreeCtrl} has the ``TR_HAS_BUTTONS`` flag set."""
+        """
+        Returns whether L{CustomTreeCtrl} has the ``TR_HAS_BUTTONS`` flag set.
+
+        :return: ``True`` if L{CustomTreeCtrl} has the ``TR_HAS_BUTTONS`` flag set,
+         ``False`` otherwise.
+        """

return self.HasAGWFlag(TR_HAS_BUTTONS)

@@ -3197,7 +3393,7 @@
Returns the item image.

:param `item`: an instance of L{GenericTreeItem};
-        :param `which`: can be one of the following bits:
+        :param integer `which`: can be one of the following bits:

================================= ========================
Item State                        Description
@@ -3207,6 +3403,9 @@
``TreeItemIcon_Expanded``         To get the expanded image (this only makes sense for items which have children - then this image is shown when the item is expanded and the normal image is shown when it is collapsed)
``TreeItemIcon_SelectedExpanded`` To get the selected expanded image (which is shown when an expanded item is currently selected)
================================= ========================
+
+        :return: An integer index that can be used to retrieve the item image inside
+         a `wx.ImageList`.
"""

return item.GetImage(which)
@@ -3218,6 +3417,9 @@
part of the L{CustomTreeCtrl} client area.

:param `item`: an instance of L{GenericTreeItem}.
+
+        :return: An integer index that can be used to retrieve the item leftmost image inside
+         a `wx.ImageList`.
"""

return item.GetLeftImage()
@@ -3228,6 +3430,9 @@
Returns the data associated to an item.

:param `item`: an instance of L{GenericTreeItem}.
+
+        :return: A Python object representing the item data, or ``None`` if no data
+         has been assigned to this item.
"""

return item.GetData()
@@ -3240,6 +3445,8 @@
Returns the item text colour.

:param `item`: an instance of L{GenericTreeItem}.
+
+        :return: An instance of `wx.Colour`.
"""

return item.Attr().GetTextColour()
@@ -3250,6 +3457,8 @@
Returns the item background colour.

:param `item`: an instance of L{GenericTreeItem}.
+
+        :return: An instance of `wx.Colour`.
"""

return item.Attr().GetBackgroundColour()
@@ -3260,6 +3469,8 @@
Returns the item font.

:param `item`: an instance of L{GenericTreeItem}.
+
+        :return: An instance of `wx.Font`.
"""

font = item.Attr().GetFont()
@@ -3274,6 +3485,8 @@
Returns whether an item is hypertext or not.

:param `item`: an instance of L{GenericTreeItem}.
+
+        :return: ``True`` if the item is hypertext-like, ``False`` otherwise.
"""

return item.IsHyperText()
@@ -3284,7 +3497,7 @@
Sets the item text.

:param `item`: an instance of L{GenericTreeItem};
-        :param `text`: the new item label.
+        :param string `text`: the new item label.
"""

dc = wx.ClientDC(self)
@@ -3298,9 +3511,9 @@
Sets the item image, depending on the item state.

:param `item`: an instance of L{GenericTreeItem};
-        :param `image`: an index within the normal image list specifying the image to
+        :param integer `image`: an index within the normal image list specifying the image to
use for the item in the state specified by the `which` parameter;
-        :param `which`: the item state.
+        :param integer `which`: the item state.

:see: L{GetItemImage} for an explanation of the `which` parameter.
"""
@@ -3318,7 +3531,7 @@
part of the L{CustomTreeCtrl} client area.

:param `item`: an instance of L{GenericTreeItem};
-        :param `image`: an index within the left image list specifying the image to
+        :param integer `image`: an index within the left image list specifying the image to
use for the item in the leftmost part of the client area.
"""

@@ -3334,7 +3547,7 @@
Sets the data associated to an item.

:param `item`: an instance of L{GenericTreeItem};
-        :param `data`: can be any Python object.
+        :param object `data`: can be any Python object.
"""

item.SetData(data)
@@ -3347,7 +3560,7 @@
Forces the appearance/disappearance of the button next to the item.

:param `item`: an instance of L{GenericTreeItem};
-        :param `has`: ``True`` to have a button next to an item, ``False`` otherwise.
+        :param bool `has`: ``True`` to have a button next to an item, ``False`` otherwise.
"""

item.SetHasPlus(has)
@@ -3359,7 +3572,7 @@
Sets the item font as bold/unbold.

:param `item`: an instance of L{GenericTreeItem};
-        :param `bold`: ``True`` to set the item font as bold, ``False`` otherwise.
+        :param bool `bold`: ``True`` to set the item font as bold, ``False`` otherwise.
"""

# avoid redrawing the tree if no real change
@@ -3373,7 +3586,7 @@
Sets the item font as italic/non-italic.

:param `item`: an instance of L{GenericTreeItem};
-        :param `italic`: ``True`` to set the item font as italic, ``False`` otherwise.
+        :param bool `italic`: ``True`` to set the item font as italic, ``False`` otherwise.
"""

if item.IsItalic() != italic:
@@ -3387,7 +3600,7 @@
This is useful when something is dragged from outside the L{CustomTreeCtrl}.

:param `item`: an instance of L{GenericTreeItem};
-        :param `highlight`: ``True`` to highlight the dragged items, ``False`` otherwise.
+        :param bool `highlight`: ``True`` to highlight the dragged items, ``False`` otherwise.
"""

if highlight:
@@ -3428,7 +3641,7 @@
Sets whether the item is hypertext or not.

:param `item`: an instance of L{GenericTreeItem};
-        :param `hyper`: ``True`` to have an item with hypertext behaviour, ``False`` otherwise.
+        :param bool `hyper`: ``True`` to have an item with hypertext behaviour, ``False`` otherwise.
"""

item.SetHyperText(hyper)
@@ -3473,7 +3686,13 @@

def GetHyperTextFont(self):
-        """ Returns the font used to render hypertext items. """
+        """
+        Returns the font used to render hypertext items.
+
+        :return: An instance of `wx.Font`.
+
+        :note: This method is meaningful only for hypertext-like items.
+        """

return self._hypertextfont

@@ -3483,6 +3702,8 @@
Sets the font used to render hypertext items.

:param `font`: a valid `wx.Font` instance.
+
+        :note: This method is meaningful only for hypertext-like items.
"""

self._hypertextfont = font
@@ -3494,6 +3715,8 @@
Sets the colour used to render a non-visited hypertext item.

:param `colour`: a valid `wx.Colour` instance.
+
+        :note: This method is meaningful only for hypertext-like items.
"""

self._hypertextnewcolour = colour
@@ -3501,7 +3724,13 @@

def GetHyperTextNewColour(self):
-        """ Returns the colour used to render a non-visited hypertext item. """
+        """
+        Returns the colour used to render a non-visited hypertext item.
+
+        :return: An instance of `wx.Colour`.
+
+        :note: This method is meaningful only for hypertext-like items.
+        """

return self._hypertextnewcolour

@@ -3511,6 +3740,8 @@
Sets the colour used to render a visited hypertext item.

:param `colour`: a valid `wx.Colour` instance.
+
+        :note: This method is meaningful only for hypertext-like items.
"""

self._hypertextvisitedcolour = colour
@@ -3518,7 +3749,13 @@

def GetHyperTextVisitedColour(self):
-        """ Returns the colour used to render a visited hypertext item. """
+        """
+        Returns the colour used to render a visited hypertext item.
+
+        :return: An instance of `wx.Colour`.
+
+        :note: This method is meaningful only for hypertext-like items.
+        """

return self._hypertextvisitedcolour

@@ -3528,7 +3765,9 @@
Sets whether an hypertext item was visited.

:param `item`: an instance of L{GenericTreeItem};
-        :param `visited`: ``True`` to mark an hypertext item as visited, ``False`` otherwise.
+        :param bool `visited`: ``True`` to mark an hypertext item as visited, ``False`` otherwise.
+
+        :note: This method is meaningful only for hypertext-like items.
"""

item.SetVisited(visited)
@@ -3540,6 +3779,10 @@
Returns whether an hypertext item was visited.

:param `item`: an instance of L{GenericTreeItem}.
+
+        :return: ``True`` if the hypertext item has been visited, ``False`` otherwise.
+
+        :note: This method is meaningful only for hypertext-like items.
"""

return item.GetVisited()
@@ -3577,6 +3820,8 @@
"""
Returns the colour used to highlight focused selected items.

+        :return: An instance of `wx.Colour`.
+
:note: This is used only if gradient and Windows Vista selection
styles are disabled.
"""
@@ -3588,6 +3833,8 @@
"""
Returns the colour used to highlight unfocused selected items.

+        :return: An instance of `wx.Colour`.
+
:note: This is used only if gradient and Windows Vista selection
styles are disabled.
"""
@@ -3635,13 +3882,21 @@

def GetFirstGradientColour(self):
-        """ Returns the first gradient colour for gradient-style selections. """
+        """
+        Returns the first gradient colour for gradient-style selections.
+
+        :return: An instance of `wx.Colour`.
+        """

return self._firstcolour

def GetSecondGradientColour(self):
-        """ Returns the second gradient colour for gradient-style selections. """
+        """
+        Returns the second gradient colour for gradient-style selections.
+
+        :return: An instance of `wx.Colour`.
+        """

return self._secondcolour

@@ -3650,7 +3905,7 @@
"""
Globally enables/disables drawing of gradient selections.

-        :param `enable`: ``True`` to enable gradient-style selections, ``False``
+        :param bool `enable`: ``True`` to enable gradient-style selections, ``False``
to disable it.

:note: Calling this method disables any Vista-style selection previously
@@ -3666,7 +3921,7 @@
"""
Sets the gradient style for gradient-style selections.

-        :param `vertical`: 0 for horizontal gradient-style selections, 1 for vertical
+        :param integer `vertical`: ``0`` for horizontal gradient-style selections, ``1`` for vertical
gradient-style selections.
"""

@@ -3681,7 +3936,7 @@
"""
Returns the gradient style for gradient-style selections.

-        :returns: 0 for horizontal gradient-style selections, 1 for vertical
+        :return: ``0`` for horizontal gradient-style selections, ``1`` for vertical
gradient-style selections.
"""

@@ -3692,7 +3947,7 @@
"""
Globally enables/disables drawing of Windows Vista selections.

-        :param `enable`: ``True`` to enable Vista-style selections, ``False`` to
+        :param bool `enable`: ``True`` to enable Vista-style selections, ``False`` to
disable it.

:note: Calling this method disables any gradient-style selection previously
@@ -3721,6 +3976,8 @@
"""
Returns the pen used to draw the selected item border.

+        :return: An instance of `wx.Pen`.
+
:note: The border pen is not used if the Windows Vista selection style is applied.
"""

@@ -3739,7 +3996,11 @@

def GetConnectionPen(self):
-        """Returns the pen used to draw the connecting lines between items."""
+        """
+        Returns the pen used to draw the connecting lines between items.
+
+        :return: An instance of `wx.Pen`.
+        """

return self._dottedPen

@@ -3763,6 +4024,8 @@
"""
Returns the L{CustomTreeCtrl} background image (if any).

+        :return: An instance of `wx.Bitmap` if a background image is present, ``None`` otherwise.
+
:note: At present, the background image can only be used in "tile" mode.

:todo: Support background images also in stretch and centered modes.
@@ -3776,6 +4039,8 @@
Returns the window associated to the item (if any).

:param `item`: an instance of L{GenericTreeItem}.
+
+        :return: An instance of `wx.Window` if the item has an associated window, ``None`` otherwise.
"""

return item.GetWindow()
@@ -3825,6 +4090,9 @@
Returns whether the window associated to the item is enabled.

:param `item`: an instance of L{GenericTreeItem}.
+
+        :return: ``True`` if the item has an associated window and this window is
+         enabled, ``False`` in all other cases.
"""

return item.GetWindowEnabled()
@@ -3835,7 +4103,7 @@
Enables/disables the window associated to the item.

:param `item`: an instance of L{GenericTreeItem};
-        :param `enable`: ``True`` to enable the associated window, ``False`` to
+        :param bool `enable`: ``True`` to enable the associated window, ``False`` to
disable it.
"""

@@ -3847,6 +4115,8 @@
Returns the item type.

:param `item`: an instance of L{GenericTreeItem}.
+
+        :return: An integer representing the item type.

:see: L{SetItemType} for a description of valid item types.
"""
@@ -3859,7 +4129,7 @@
Sets the item type.

:param `item`: an instance of L{GenericTreeItem};
-        :param `ct_type`: May be one of the following integers:
+        :param integer `ct_type`: may be one of the following integers:

=============== =========================================
`ct_type` Value Description
@@ -3894,8 +4164,10 @@
"""
Returns whether the item is visible or not (i.e., its hierarchy is expanded
enough to show the item).
-
+
:param `item`: an instance of L{GenericTreeItem}.
+
+        :return: ``True`` if the item is visible, ``False`` if it is hidden.
"""

# An item is only visible if it's not a descendant of a collapsed item
@@ -3930,6 +4202,8 @@
Returns whether the item has children or not.

:param `item`: an instance of L{GenericTreeItem}.
+
+        :return: ``True`` if the item has children, ``False`` otherwise.
"""

# consider that the item does have children if it has the "+" button: it
@@ -3945,6 +4219,8 @@
Returns whether the item is expanded or not.

:param `item`: an instance of L{GenericTreeItem}.
+
+        :return: ``True`` if the item is expanded, ``False`` if it is collapsed.
"""

return item.IsExpanded()
@@ -3955,6 +4231,8 @@
Returns whether the item is selected or not.

:param `item`: an instance of L{GenericTreeItem}.
+
+        :return: ``True`` if the item is selected, ``False`` otherwise.
"""

return item.IsSelected()
@@ -3965,6 +4243,8 @@
Returns whether the item font is bold or not.

:param `item`: an instance of L{GenericTreeItem}.
+
+        :return: ``True`` if the item has bold text, ``False`` otherwise.
"""

return item.IsBold()
@@ -3975,6 +4255,8 @@
Returns whether the item font is italic or not.

:param `item`: an instance of L{GenericTreeItem}.
+
+        :return: ``True`` if the item has italic text, ``False`` otherwise.
"""

return item.IsItalic()
@@ -3989,6 +4271,8 @@
Returns the item parent (can be ``None`` for root items).

:param `item`: an instance of L{GenericTreeItem}.
+
+        :return: An instance of L{GenericTreeItem} or ``None`` for root items.
"""

return item.GetParent()
@@ -4002,6 +4286,9 @@

:param `item`: an instance of L{GenericTreeItem}.

+        :return: A tuple with the first value being an instance of L{GenericTreeItem} or ``None`` if there are no
+         further children, and as second value an integer parameter 'cookie'.
+
:note: This method returns ``None`` if there are no further children.
"""

@@ -4018,6 +4305,9 @@
for the library to make these functions reentrant (i.e. allow more than one
enumeration on one and the same object simultaneously).

+        :return: A tuple with the first value being an instance of L{GenericTreeItem} or ``None`` if there are no
+         further children, and as second value an integer parameter 'cookie'.
+
:note: This method returns ``None`` if there are no further children.
"""

@@ -4041,6 +4331,9 @@
Returns the item last child.

:param `item`: an instance of L{GenericTreeItem}.
+
+        :return: An instance of L{GenericTreeItem} or ``None`` if there are no
+         further children.
"""

children = item.GetChildren()
@@ -4053,6 +4346,9 @@

:param `item`: an instance of L{GenericTreeItem}.

+        :return: An instance of L{GenericTreeItem} or ``None`` if there are no
+         further siblings.
+
:note: This method returns ``None`` if there are no further siblings.
"""

@@ -4077,6 +4373,9 @@

:param `item`: an instance of L{GenericTreeItem}.

+        :return: An instance of L{GenericTreeItem} or ``None`` if there are no
+         further siblings.
+
:note: This method returns ``None`` if there are no further siblings.
"""

@@ -4098,6 +4397,9 @@
"""
Returns the next item. Only for internal use right now.

+        :return: An instance of L{GenericTreeItem} or ``None`` if there are no
+         further items.
+
:param `item`: an instance of L{GenericTreeItem}.
"""

@@ -4116,10 +4418,72 @@
p = self.GetItemParent(p)

return toFind
-
+
+
+    def GetPrev(self, item):
+        """
+        Returns the previous item. Only for internal use right now.
+
+        :param `item`: an instance of L{GenericTreeItem}.
+
+        :return: An instance of L{GenericTreeItem}
+        """
+
+        # Look for a previous sibling of this item
+        prevSibling = self.GetPrevSibling(item)
+        if prevSibling:
+
+            # return it's last child or itself if has not got any children
+            if len(prevSibling.GetChildren()) > 0:
+                return self.GetLastChild(prevSibling)
+
+            return prevSibling
+
+        # item has not got a previous sibling, return it's parent
+        return self.GetItemParent(item)
+
+
+    def GetNextExpanded(self, item):
+        """
+        Returns the next expanded item after the input one.
+
+        :param `item`: an instance of L{TreeListItem}.
+        """
+
+        nextSibling = self.GetNextSibling(item)
+        if nextSibling:
+            if nextSibling.IsExpanded():
+                return nextSibling
+
+            return self.GetNextExpanded(prevSibling)
+
+        return None
+
+
+    def GetPrevExpanded(self, item):
+        """
+        Returns the previous expanded item before the input one.
+
+        :param `item`: an instance of L{TreeListItem}.
+        """
+
+        prevSibling = self.GetPrevSibling(item)
+        if prevSibling:
+            if prevSibling.IsExpanded():
+                return prevSibling
+
+            return self.GetPrevExpanded(prevSibling)
+
+        return None
+

def GetFirstVisibleItem(self):
-        """ Returns the first visible item. """
+        """
+        Returns the first visible item.
+
+        :return: An instance of L{GenericTreeItem} or ``None`` if there are no
+         visible items.
+        """

id = self.GetRootItem()
if not id:
@@ -4138,6 +4502,9 @@
Returns the next visible item.

:param `item`: an instance of L{GenericTreeItem}.
+
+        :return: An instance of L{GenericTreeItem} or ``None`` if there are no
+         next visible items.
"""

id = item
@@ -4155,6 +4522,9 @@
Returns the previous visible item.

:param `item`: an instance of L{GenericTreeItem}.
+
+        :return: An instance of L{GenericTreeItem} or ``None`` if there are no
+         previous visible items.
"""

# find a previous sibling or parent which is visible
@@ -4188,7 +4558,7 @@

def ResetEditControl(self):
-        """ Called by L{EditCtrl} when it marks itself for deletion. """
+        """ Called by L{TreeTextCtrl} when it marks itself for deletion. """

if self._editCtrl is not None:
self._editCtrl.Destroy()
@@ -4203,8 +4573,10 @@
"""
Finds the first item starting with the given prefix after the given parent.

-        :param `idParent`: an instance of L{GenericTreeItem};
-        :param `prefixOrig`: a string containing the item text prefix.
+        :param integer `idParent`: an instance of L{GenericTreeItem};
+        :param string `prefixOrig`: a string containing the item text prefix.
+
+        :return: An instance of L{GenericTreeItem} or ``None`` if no item has been found.
"""

# match is case insensitive as this is more convenient to the user: having
@@ -4255,17 +4627,28 @@

:param `parentId`: an instance of L{GenericTreeItem} representing the
item's parent;
-        :param `previous`: the index at which we should insert the item;
-        :param `text`: the item text label;
-        :param `ct_type`: the item type (see L{SetItemType} for a list of valid
+        :param integer `previous`: the index at which we should insert the item;
+        :param string `text`: the item text label;
+        :param integer `ct_type`: the item type (see L{SetItemType} for a list of valid
item types);
-        :param `wnd`: if not ``None``, a non-toplevel window to show next to the item;
-        :param `image`: an index within the normal image list specifying the image to
+        :param `wnd`: if not ``None``, a non-toplevel window to show next to the item, any
+         subclass of `wx.Window` except top-level windows;
+        :param integer `image`: an index within the normal image list specifying the image to
use for the item in unselected state;
-        :param `selImage`: an index within the normal image list specifying the image to
+        :param integer `selImage`: an index within the normal image list specifying the image to
use for the item in selected state; if `image` > -1 and `selImage` is -1, the
same image is used for both selected and unselected items;
-        :param `data`: associate the given Python object `data` with the item.
+        :param object `data`: associate the given Python object `data` with the item.
+
+        :return: An instance of L{GenericTreeItem} upon successful insertion.
+
+        :raise: `Exception` in the following cases:
+
+         - The item window is not ``None`` but the ``TR_HAS_VARIABLE_ROW_HEIGHT`` flag has not been
+           set for L{CustomTreeCtrl};
+         - The item has multiline text (with line-breaks in it) but the ``TR_HAS_VARIABLE_ROW_HEIGHT``
+           flag has not been set for L{CustomTreeCtrl};
+         - The `ct_type` attribute is less than ``0`` or greater than ``2``.
"""

if wnd is not None and not self.HasAGWFlag(TR_HAS_VARIABLE_ROW_HEIGHT):
@@ -4300,16 +4683,28 @@
"""
Adds a root item to the L{CustomTreeCtrl}.

-        :param `text`: the item text label;
-        :param `ct_type`: the item type (see L{SetItemType} for a list of valid
+        :param string `text`: the item text label;
+        :param integer `ct_type`: the item type (see L{SetItemType} for a list of valid
item types);
-        :param `wnd`: if not ``None``, a non-toplevel window to show next to the item;
-        :param `image`: an index within the normal image list specifying the image to
+        :param `wnd`: if not ``None``, a non-toplevel window to show next to the item,
+         any subclass of `wx.Window` except top-level windows;
+        :param integer `image`: an index within the normal image list specifying the image to
use for the item in unselected state;
-        :param `selImage`: an index within the normal image list specifying the image to
+        :param  integer `selImage`: an index within the normal image list specifying the image to
use for the item in selected state; if `image` > -1 and `selImage` is -1, the
same image is used for both selected and unselected items;
-        :param `data`: associate the given Python object `data` with the item.
+        :param object `data`: associate the given Python object `data` with the item.
+
+        :return: An instance of L{GenericTreeItem} upon successful insertion.
+
+        :raise: `Exception` in the following cases:
+
+         - There already is a root item in the tree;
+         - The item window is not ``None`` but the ``TR_HAS_VARIABLE_ROW_HEIGHT`` flag has not been
+           set for L{CustomTreeCtrl};
+         - The item has multiline text (with line-breaks in it) but the ``TR_HAS_VARIABLE_ROW_HEIGHT``
+           flag has not been set for L{CustomTreeCtrl};
+         - The `ct_type` attribute is less than ``0`` or greater than ``2``.

:warning: only one root is allowed to exist in any given instance of L{CustomTreeCtrl}.
"""
@@ -4356,16 +4751,21 @@

:param `parent`: an instance of L{GenericTreeItem} representing the
item's parent;
-        :param `text`: the item text label;
-        :param `ct_type`: the item type (see L{SetItemType} for a list of valid
+        :param string `text`: the item text label;
+        :param integer `ct_type`: the item type (see L{SetItemType} for a list of valid
item types);
-        :param `wnd`: if not ``None``, a non-toplevel window to show next to the item;
-        :param `image`: an index within the normal image list specifying the image to
+        :param `wnd`: if not ``None``, a non-toplevel window to show next to the item, any
+         subclass of `wx.Window` except top-level windows;
+        :param integer `image`: an index within the normal image list specifying the image to
use for the item in unselected state;
-        :param `selImage`: an index within the normal image list specifying the image to
+        :param integer `selImage`: an index within the normal image list specifying the image to
use for the item in selected state; if `image` > -1 and `selImage` is -1, the
same image is used for both selected and unselected items;
-        :param `data`: associate the given Python object `data` with the item.
+        :param object `data`: associate the given Python object `data` with the item.
+
+        :return: An instance of L{GenericTreeItem} upon successful insertion.
+
+        :see: L{DoInsertItem} for possible exceptions generated by this method.
"""

return self.DoInsertItem(parent, 0, text, ct_type, wnd, image, selImage, data)
@@ -4379,16 +4779,23 @@
item's parent;
:param `idPrevious`: an instance of L{GenericTreeItem} representing the
previous item;
-        :param `text`: the item text label;
-        :param `ct_type`: the item type (see L{SetItemType} for a list of valid
+        :param string `text`: the item text label;
+        :param integer `ct_type`: the item type (see L{SetItemType} for a list of valid
item types);
-        :param `wnd`: if not ``None``, a non-toplevel window to show next to the item;
-        :param `image`: an index within the normal image list specifying the image to
+        :param `wnd`: if not ``None``, a non-toplevel window to show next to the item,
+         any subclass of `wx.Window`;
+        :param integer `image`: an index within the normal image list specifying the image to
use for the item in unselected state;
-        :param `selImage`: an index within the normal image list specifying the image to
+        :param integer `selImage`: an index within the normal image list specifying the image to
use for the item in selected state; if `image` > -1 and `selImage` is -1, the
same image is used for both selected and unselected items;
-        :param `data`: associate the given Python object `data` with the item.
+        :param object `data`: associate the given Python object `data` with the item.
+
+        :return: An instance of L{GenericTreeItem} upon successful insertion.
+
+        :raise: `Exception` if the previous item is not a sibling.
+
+        :see: L{DoInsertItem} for other possible exceptions generated by this method.
"""

parent = parentId
@@ -4415,16 +4822,21 @@
:param `parentId`: an instance of L{GenericTreeItem} representing the
item's parent;
:param `idPrevious`: the index at which we should insert the new item;
-        :param `text`: the item text label;
-        :param `ct_type`: the item type (see L{SetItemType} for a list of valid
+        :param string `text`: the item text label;
+        :param integer `ct_type`: the item type (see L{SetItemType} for a list of valid
item types);
-        :param `wnd`: if not ``None``, a non-toplevel window to show next to the item;
-        :param `image`: an index within the normal image list specifying the image to
+        :param `wnd`: if not ``None``, a non-toplevel window to show next to the item,
+         any subclass of `wx.Window`;
+        :param integer `image`: an index within the normal image list specifying the image to
use for the item in unselected state;
-        :param `selImage`: an index within the normal image list specifying the image to
+        :param integer `selImage`: an index within the normal image list specifying the image to
use for the item in selected state; if `image` > -1 and `selImage` is -1, the
same image is used for both selected and unselected items;
-        :param `data`: associate the given Python object `data` with the item.
+        :param object `data`: associate the given Python object `data` with the item.
+
+        :return: An instance of L{GenericTreeItem} upon successful insertion.
+
+        :see: L{DoInsertItem} for possible exceptions generated by this method.
"""

parent = parentId
@@ -4440,8 +4852,12 @@
"""
Inserts an item after the given previous.

+        :return: An instance of L{GenericTreeItem} upon successful insertion.
+
:see: L{InsertItemByIndex} and L{InsertItemByItem} for an explanation of
the input parameters.
+
+        :see: L{DoInsertItem} for possible exceptions generated by this method.
"""

if type(input) == type(1):
@@ -4456,16 +4872,21 @@

:param `parentId`: an instance of L{GenericTreeItem} representing the
item's parent;
-        :param `text`: the item text label;
-        :param `ct_type`: the item type (see L{SetItemType} for a list of valid
+        :param string `text`: the item text label;
+        :param integer `ct_type`: the item type (see L{SetItemType} for a list of valid
item types);
-        :param `wnd`: if not ``None``, a non-toplevel window to show next to the item;
-        :param `image`: an index within the normal image list specifying the image to
+        :param `wnd`: if not ``None``, a non-toplevel window to show next to the item,
+         any subclass of `wx.Window`;
+        :param integer `image`: an index within the normal image list specifying the image to
use for the item in unselected state;
-        :param `selImage`: an index within the normal image list specifying the image to
+        :param integer `selImage`: an index within the normal image list specifying the image to
use for the item in selected state; if `image` > -1 and `selImage` is -1, the
same image is used for both selected and unselected items;
-        :param `data`: associate the given Python object `data` with the item.
+        :param object `data`: associate the given Python object `data` with the item.
+
+        :return: An instance of L{GenericTreeItem} upon successful insertion.
+
+        :see: L{DoInsertItem} for possible exceptions generated by this method.
"""

parent = parentId
@@ -4497,6 +4918,8 @@
:param `parent`: an instance of L{GenericTreeItem}, representing the possible
parent of `item`;
:param `item`: another instance of L{GenericTreeItem}.
+
+        :return: ``True`` if `item` is a descendant of `parent`, ``False`` otherwise.
"""

while item:
@@ -4552,6 +4975,8 @@
Deletes an item.

:param `item`: an instance of L{GenericTreeItem}.
+
+        :note: This method sends the ``EVT_TREE_DELETE_ITEM`` event.
"""

self._dirty = True     # do this first so stuff below doesn't cause flicker
@@ -4628,6 +5053,9 @@
``EVT_TREE_ITEM_EXPANDED`` events.

:param `item`: an instance of L{GenericTreeItem}.
+
+        :raise: `Exception` if you try to expand a hidden root (i.e., when the ``TR_HIDE_ROOT``
+         style is set for L{CustomTreeCtrl}).
"""

if self.HasAGWFlag(TR_HIDE_ROOT) and item == self.GetRootItem():
@@ -4714,6 +5142,9 @@
``EVT_TREE_ITEM_COLLAPSED`` events.

:param `item`: an instance of L{GenericTreeItem}.
+
+        :raise: `Exception` if you try to collapse a hidden root (i.e., when the ``TR_HIDE_ROOT``
+         style is set for L{CustomTreeCtrl}).
"""

if self.HasAGWFlag(TR_HIDE_ROOT) and item == self.GetRootItem():
@@ -4811,6 +5242,8 @@

:param `item`: an instance of L{GenericTreeItem}.

+        :raise: `Exception` if used without the ``TR_EXTENDED`` or ``TR_MULTIPLE`` style set.
+
:note: This method can be used only if L{CustomTreeCtrl} has the ``TR_MULTIPLE`` or ``TR_EXTENDED``
style set.
"""
@@ -4843,6 +5276,8 @@
"""
Selects all the item in the tree.

+        :raise: `Exception` if used without the ``TR_EXTENDED`` or ``TR_MULTIPLE`` style set.
+
:note: This method can be used only if L{CustomTreeCtrl} has the ``TR_MULTIPLE`` or ``TR_EXTENDED``
style set.
"""
@@ -4910,6 +5345,8 @@
:param `item2`: an instance of L{GenericTreeItem}, representing the last
item in the range to select.

+        :raise: `Exception` if used without the ``TR_EXTENDED`` or ``TR_MULTIPLE`` style set.
+
:note: This method can be used only if L{CustomTreeCtrl} has the ``TR_MULTIPLE`` or ``TR_EXTENDED``
style set.
"""
@@ -4938,9 +5375,9 @@
``EVT_TREE_SEL_CHANGED`` events.

:param `item`: an instance of L{GenericTreeItem};
-        :param `unselect_others`: if ``True``, all the other selected items are
+        :param bool `unselect_others`: if ``True``, all the other selected items are
unselected.
-        :param `extended_select`: ``True`` if the L{CustomTreeCtrl} is using the
+        :param bool `extended_select`: ``True`` if the L{CustomTreeCtrl} is using the
``TR_EXTENDED`` style.
"""

@@ -5025,7 +5462,7 @@
Selects/deselects an item.

:param `item`: an instance of L{GenericTreeItem};
-        :param `select`: ``True`` to select an item, ``False`` to deselect it.
+        :param bool `select`: ``True`` to select an item, ``False`` to deselect it.
"""

if select:
@@ -5042,6 +5479,11 @@
"""
Internal function. Used to populate an array of selected items when
the style ``TR_MULTIPLE`` is used.
+
+        :param `item`: an instance of L{GenericTreeItem};
+        :param list `array`: a Python list containing the selected items.
+
+        :return: A Python list containing the selected items.
"""

if not array:
@@ -5063,6 +5505,8 @@

:note: This method can be used only if L{CustomTreeCtrl} has the ``TR_MULTIPLE`` or ``TR_EXTENDED``
style set.
+
+        :return: A Python list containing the selected items, all instances of L{GenericTreeItem}.
"""

array = []
@@ -5171,6 +5615,9 @@
:param `item1`: an instance of L{GenericTreeItem};
:param `item2`: another instance of L{GenericTreeItem}.

+        :return: The return value is negative if `item1` < `item2`, zero if `item1` == `item2`
+         and strictly positive if `item1` < `item2`.
+
:note: The base class version compares items alphabetically.
"""

@@ -5196,7 +5643,11 @@

def GetImageList(self):
-        """ Returns the normal image list associated with L{CustomTreeCtrl}. """
+        """
+        Returns the normal image list associated with L{CustomTreeCtrl}.
+
+        :return: An instance of `wx.ImageList`.
+        """

return self._imageListNormal

@@ -5205,6 +5656,8 @@
"""
Returns the buttons image list associated with L{CustomTreeCtrl} (from
which application-defined button images are taken).
+
+        :return: An instance of `wx.ImageList`.
"""

return self._imageListButtons
@@ -5214,13 +5667,19 @@
"""
Returns the state image list associated with L{CustomTreeCtrl} (from which
application-defined state images are taken).
+
+        :return: An instance of `wx.ImageList`.
"""

return self._imageListState

def GetImageListCheck(self):
-        """ Returns the image list used to build the check/radio buttons in L{CustomTreeCtrl}. """
+        """
+        Returns the image list used to build the check/radio buttons in L{CustomTreeCtrl}.
+
+        :return: An instance of `wx.ImageList`.
+        """

return self._imageListCheck

@@ -5230,6 +5689,8 @@
Returns the image list for L{CustomTreeCtrl} filled with images to be used on
the leftmost part of the client area. Any item can have a leftmost image associated
with it.
+
+        :return: An instance of `wx.ImageList`.
"""

return self._imageListLeft
@@ -5396,8 +5857,8 @@
"""
Sets the checkbox/radiobutton image list.

-        :param `sizex`: the width of the bitmaps in the `imglist`;
-        :param `sizey`: the height of the bitmaps in the `imglist`;
+        :param integer `sizex`: the width of the bitmaps in the `imglist`, in pixels;
+        :param integer `sizey`: the height of the bitmaps in the `imglist`, in pixels;
:param `imglist`: an instance of `wx.ImageList`.
"""

@@ -5544,6 +6005,8 @@
Returns the line height for the given item.

:param `item`: an instance of L{GenericTreeItem}.
+
+        :return: the item height, in pixels.
"""

if self.GetAGWWindowStyleFlag() & TR_HAS_VARIABLE_ROW_HEIGHT:
@@ -5557,8 +6020,8 @@
Gradient fill from colour 1 to colour 2 from top to bottom.

:param `dc`: an instance of `wx.DC`;
-        :param `rect`: the rectangle to be filled with the gradient shading;
-        :param `hasfocus`: ``True`` if the main L{CustomTreeCtrl} has focus, ``False``
+        :param `wx.Rect` `rect`: the rectangle to be filled with the gradient shading;
+        :param bool `hasfocus`: ``True`` if the main L{CustomTreeCtrl} has focus, ``False``
otherwise.
"""

@@ -5604,8 +6067,8 @@
Gradient fill from colour 1 to colour 2 from left to right.

:param `dc`: an instance of `wx.DC`;
-        :param `rect`: the rectangle to be filled with the gradient shading;
-        :param `hasfocus`: ``True`` if the main L{CustomTreeCtrl} has focus, ``False``
+        :param `wx.Rect` `rect`: the rectangle to be filled with the gradient shading;
+        :param bool `hasfocus`: ``True`` if the main L{CustomTreeCtrl} has focus, ``False``
otherwise.
"""

@@ -5652,8 +6115,8 @@
Draws the selected item(s) with the Windows Vista style.

:param `dc`: an instance of `wx.DC`;
-        :param `rect`: the rectangle to be filled with the gradient shading;
-        :param `hasfocus`: ``True`` if the main L{CustomTreeCtrl} has focus, ``False``
+        :param `wx.Rect` `rect`: the rectangle to be filled with the gradient shading;
+        :param bool `hasfocus`: ``True`` if the main L{CustomTreeCtrl} has focus, ``False``
otherwise.
"""

@@ -5717,9 +6180,16 @@

:param `item`: an instance of L{GenericTreeItem};
:param `dc`: an instance of `wx.DC`;
-        :param `level`: the item level in the tree hierarchy;
-        :param `align`: ``True`` if we want to align windows (in items with windows)
-         at the same horizontal position.
+        :param integer `level`: the item level in the tree hierarchy;
+        :param integer `align`: an integer specifying the alignment type:
+
+         =============== =========================================
+         `align` Value   Description
+         =============== =========================================
+                0        No horizontal alignment of windows (in items with windows).
+                1        Windows (in items with windows) are aligned at the same horizontal position.
+                2        Windows (in items with windows) are aligned at the rightmost edge of L{CustomTreeCtrl}.
+         =============== =========================================
"""

attr = item.GetAttributes()
@@ -5963,9 +6433,9 @@

:param `item`: an instance of L{GenericTreeItem};
:param `dc`: an instance of `wx.DC`;
-        :param `level`: the item level in the tree hierarchy;
-        :param `y`: the current vertical position in the `wx.PyScrolledWindow`;
-        :param `align`: an integer specifying the alignment type:
+        :param integer `level`: the item level in the tree hierarchy;
+        :param integer `y`: the current vertical position in the `wx.PyScrolledWindow`;
+        :param integer `align`: an integer specifying the alignment type:

=============== =========================================
`align` Value   Description
@@ -6567,8 +7037,11 @@
Returns the next active item. Used Internally at present.

:param `item`: an instance of L{GenericTreeItem};
-        :param `down`: ``True`` to search downwards in the hierarchy for an active item,
+        :param bool `down`: ``True`` to search downwards in the hierarchy for an active item,
``False`` to search upwards.
+
+        :return: An instance of L{GenericTreeItem} if an active item has been found or
+         ``None`` if none has been found.
"""

if down:
@@ -6606,7 +7079,7 @@
at this point plus extra information flags.

:param `point`: an instance of `wx.Point`, a point to test for hits;
-        :param `flags`: a bitlist of the following values:
+        :param integer `flags`: a bitlist of the following values:

================================== =============== =================================
HitTest Flags                      Hex Value       Description
@@ -6627,6 +7100,9 @@
``TREE_HITTEST_ONITEMCHECKICON``            0x2000 On the check/radio icon, if present
================================== =============== =================================

+        :return: A tuple with the first value being an instance of L{GenericTreeItem} or ``None`` if
+         no item has been hit-tested, and as second value an integer parameter `flag`.
+
:note: both the item (if any, ``None`` otherwise) and the `flags` are always returned as a tuple.
"""

@@ -6666,12 +7142,14 @@
Retrieves the rectangle bounding the item.

:param `item`: an instance of L{GenericTreeItem};
-        :param `textOnly`: if ``True``, only the rectangle around the item's label will
+        :param bool `textOnly`: if ``True``, only the rectangle around the item's label will
be returned, otherwise the item's image is also taken into account.

+        :return: An instance of `wx.Rect`.
+
:note: The rectangle coordinates are logical, not physical ones. So, for example,
-         the x coordinate may be negative if the tree has a horizontal scrollbar and its
-         position is not 0.
+         the `x` coordinate may be negative if the tree has a horizontal scrollbar and its
+         position is not ``0``.
"""

i = item
@@ -6722,7 +7200,7 @@
"""
Returns a pointer to the edit L{TreeTextCtrl} if the item is being edited or
``None`` otherwise (it is assumed that no more than one item may be edited
-        simultaneously).
+        simultaneously).
"""

return self._editCtrl
@@ -6730,11 +7208,13 @@

def OnAcceptEdit(self, item, value):
"""
-        Called by L{EditCtrl}, to accept the changes and to send the
+        Called by L{TreeTextCtrl}, to accept the changes and to send the
``EVT_TREE_END_LABEL_EDIT`` event.

:param `item`: an instance of L{GenericTreeItem};
-        :param `value`: the new value of the item label.
+        :param string `value`: the new value of the item label.
+
+        :return: ``True`` if the editing has not been vetoed, ``False`` otherwise.
"""

le = TreeEvent(wxEVT_TREE_END_LABEL_EDIT, self.GetId())
@@ -6748,7 +7228,7 @@

def OnCancelEdit(self, item):
"""
-        Called by L{EditCtrl}, to cancel the changes and to send the
+        Called by L{TreeTextCtrl}, to cancel the changes and to send the
``EVT_TREE_END_LABEL_EDIT`` event.

:param `item`: an instance of L{GenericTreeItem}.
@@ -7168,8 +7648,8 @@

:param `item`: an instance of L{GenericTreeItem};
:param `dc`: an instance of `wx.DC`;
-        :param `level`: the item level in the tree hierarchy;
-        :param `align`: an integer specifying the alignment type:
+        :param integer `level`: the item level in the tree hierarchy;
+        :param integer `align`: an integer specifying the alignment type:

=============== =========================================
`align` Value   Description
@@ -7253,9 +7733,9 @@

:param `item`: an instance of L{GenericTreeItem};
:param `dc`: an instance of `wx.DC`;
-        :param `level`: the item level in the tree hierarchy;
-        :param `y`: the current vertical position inside the `wx.PyScrolledWindow`;
-        :param `align`: an integer specifying the alignment type:
+        :param integer `level`: the item level in the tree hierarchy;
+        :param integer `y`: the current vertical position inside the `wx.PyScrolledWindow`;
+        :param integer `align`: an integer specifying the alignment type:

=============== =========================================
`align` Value   Description
@@ -7265,6 +7745,7 @@
2        Windows (in items with windows) are aligned at the rightmost edge of L{CustomTreeCtrl}.
=============== =========================================

+        :return: The new `y` vertical position inside the `wx.PyScrolledWindow`.
"""

x = level*self._indent
@@ -7451,6 +7932,8 @@

Reenables window updating after a previous call to L{Freeze}. To really thaw the
control, it must be called exactly the same number of times as L{Freeze}.
+
+        :raise: `Exception` if L{Thaw} has been called without an un-matching L{Freeze}.
"""

if self._freezeCount == 0:
@@ -7473,6 +7956,9 @@
:param `colour`: the colour to be used as the background colour, pass
`wx.NullColour` to reset to the default colour.

+        :return: ``False`` if the underlying `wx.PyScrolledWindow` does not accept
+         the new colour, ``True`` otherwise.
+
:note: The background colour is usually painted by the default `wx.EraseEvent`
event handler function under Windows and automatically under GTK.

@@ -7501,6 +7987,9 @@
:param `colour`: the colour to be used as the foreground colour, pass
`wx.NullColour` to reset to the default colour.

+        :return: ``False`` if the underlying `wx.PyScrolledWindow` does not accept
+         the new colour, ``True`` otherwise.
+
:note: Overridden from `wx.PyScrolledWindow`.
"""

@@ -7532,6 +8021,8 @@
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 `wx.Size`.
+
:note: Overridden from `wx.PyScrolledWindow`.
"""

@@ -7546,9 +8037,11 @@
"""
Returns the maximum width of the L{CustomTreeCtrl}.

-        :param `respect_expansion_state`: if ``True``, only the expanded items (and their
+        :param bool `respect_expansion_state`: if ``True``, only the expanded items (and their
children) will be measured. Otherwise all the items are expanded and
their width measured.
+
+        :return: the maximum width of L{CustomTreeCtrl}, in pixels.
"""

self.Freeze()
@@ -7581,10 +8074,12 @@
maximum width.

:param `item`: an instance of L{GenericTreeItem};
-        :param `maxwidth`: the current maximum width for L{CustomTreeCtrl};
-        :param `respect_expansion_state`: if ``True``, only the expanded items (and their
+        :param integer `maxwidth`: the current maximum width for L{CustomTreeCtrl}, in pixels;
+        :param bool `respect_expansion_state`: if ``True``, only the expanded items (and their
children) will be measured. Otherwise all the items are expanded and
their width measured.
+
+        :return: A tuple containing the maximum width and item height, in pixels.
"""

child, cookie = self.GetFirstChild(item)
@@ -7620,6 +8115,8 @@
values appropriate for a button which will be normally different from those
returned by, say, `wx.ListCtrl.GetClassDefaultAttributes()`.

+        :return: An instance of `wx.VisualAttributes`.
+
:note: The `wx.VisualAttributes` structure has at least the fields `font`,
`colFg` and `colBg`. All of them may be invalid if it was not possible to
determine the default control appearance or, especially for the background
@@ -7637,4 +8134,3 @@

GetClassDefaultAttributes = classmethod(GetClassDefaultAttributes)

-

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • customtreectrl »
  • SVN Revision 68955 For customtreectrl


SVN Revision 69627 For customtreectrl

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • customtreectrl »
  • SVN Revision 69627 For customtreectrl

svn SVN Revision 69627 For customtreectrl

This file contains the SVN revision history for customtreectrl, at revision 69627.

Available information include commit date, the name of the committer, the file size, the SVN log messages and a diff from the previous version (if available).

File Information

  • Commit Date: 29-May-2009 08:06:58 UTC
  • Committer: AG
  • File Size: 284990 byte(s)

Log Messages

The following log message was entered by the committer:

  • AuiManager: fix the assertion error in the demo;
  • Others: minor fixes to the docstrings.

Diff To Previous Version (68955)

Version SVN diff:

--- wxPython/3rdParty/AGW/agw/customtreectrl.py     2011/08/29 19:08:33     68955
+++ wxPython/3rdParty/AGW/agw/customtreectrl.py     2011/11/01 19:42:21     69627
@@ -2832,7 +2832,9 @@

:return: An instance of L{GenericTreeItem}.

-        :note: This method is valid only with the style ``TR_SINGLE`` set. Use
+        :note:
+
+         This method is valid only with the style ``TR_SINGLE`` set. Use
L{GetSelections} for multiple-selections trees.
"""

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • customtreectrl »
  • SVN Revision 69627 For customtreectrl


SVN Revision 69864 For customtreectrl

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • customtreectrl »
  • SVN Revision 69864 For customtreectrl

svn SVN Revision 69864 For customtreectrl

This file contains the SVN revision history for customtreectrl, at revision 69864.

Available information include commit date, the name of the committer, the file size, the SVN log messages and a diff from the previous version (if available).

File Information

  • Commit Date: 28-Apr-2009 03:16:54 UTC
  • Committer: AG
  • File Size: 292038 byte(s)

Log Messages

The following log message was entered by the committer:

CustomTreeCtrl: add the ability to use horizontal line separators between tree items. Show it in the demo by randomly adding separators in the tree.

Diff To Previous Version (69627)

Version SVN diff:

--- wxPython/3rdParty/AGW/agw/customtreectrl.py     2011/11/01 19:42:21     69627
+++ wxPython/3rdParty/AGW/agw/customtreectrl.py     2011/11/29 20:11:02     69864
@@ -3,7 +3,7 @@
# Inspired By And Heavily Based On wxGenericTreeCtrl.
#
# Andrea Gavana, @ 17 May 2006
-# Latest Revision: 17 Aug 2011, 15.00 GMT
+# Latest Revision: 29 Nov 2011, 15.00 GMT
#
#
# TODO List
@@ -83,6 +83,18 @@
* Changing the style of the lines that connect the items (in terms of `wx.Pen` styles);
* Using an image as a L{CustomTreeCtrl} background (currently only in "tile" mode);
* Adding images to any item in the leftmost area of the L{CustomTreeCtrl} client window.
+* Separator-type items which are simply visual indicators that are meant to set apart
+  or divide tree items, with the following caveats:
+
+  - Separator items should not have children, labels, data or an associated window;
+  - You can change the color of individual separators by using L{SetItemTextColour}, or you can use
+    L{SetSeparatorColour} to change the color of all separators. The default separator colour
+    is that returned by `wx.SystemSettings.GetColour(wx.SYS_COLOUR_GRAYTEXT)`;
+  - Separators can be selected just like any other tree item;
+  - Separators cannot have text;
+  - Separators cannot have children;
+  - Separators cannot be edited via the ``EVT_TREE_BEGIN_LABEL_EDIT`` event.
+

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

@@ -273,14 +285,14 @@

L{CustomTreeCtrl} is distributed under the wxPython license.

-Latest Revision: Andrea Gavana @ 17 Aug 2011, 15.00 GMT
+Latest Revision: Andrea Gavana @ 29 Nov 2011, 15.00 GMT

-Version 2.4
+Version 2.5

"""

# Version Info
-__version__ = "2.4"
+__version__ = "2.5"

import wx
from wx.lib.expando import ExpandoTextCtrl
@@ -1448,7 +1460,7 @@
L{CustomTreeCtrl}. This is a generic implementation of `wx.TreeItem`.
"""

-    def __init__(self, parent, text="", ct_type=0, wnd=None, image=-1, selImage=-1, data=None):
+    def __init__(self, parent, text="", ct_type=0, wnd=None, image=-1, selImage=-1, data=None, separator=False):
"""
Default class constructor.
For internal use: do not call it in your code!
@@ -1473,7 +1485,8 @@
:param integer `selImage`: an index within the normal image list specifying the image to
use for the item in selected state; if `image` > -1 and `selImage` is -1, the
same image is used for both selected and unselected items;
-        :param object `data`: associate the given Python object `data` with the item.
+        :param object `data`: associate the given Python object `data` with the item;
+        :param bool `separator`: ``True`` if the item is a separator, ``False`` otherwise.

:note: Regarding radiobutton-type items (with `ct_type` = 2), the following
approach is used:
@@ -1484,7 +1497,19 @@
must be unchecked.
- If a radiobutton node becomes unchecked, then all of its child nodes will become
inactive.
-
+
+
+        :note: Separator items should not have children, labels, data or an associated window.
+         Other issues/features associated to separator items:
+
+         - You can change the color of individual separators by using L{SetItemTextColour}, or you can use
+           L{SetSeparatorColour} to change the color of all separators. The default separator colour
+           is that returned by `wx.SystemSettings.GetColour(wx.SYS_COLOUR_GRAYTEXT)`;
+         - Separators can be selected just like any other tree item;
+         - Separators cannot have text;
+         - Separators cannot have children;
+         - Separators cannot be edited via the ``EVT_TREE_BEGIN_LABEL_EDIT`` event.
+
"""

# since there can be very many of these, we save size by chosing
@@ -1498,6 +1523,8 @@

self._attr = None       # attributes???

+        self._separator = separator
+
# tree ctrl images for the normal, selected, expanded and
# expanded+selected states
self._images = [-1, -1, -1, -1]
@@ -1558,6 +1585,16 @@
return True

+    def IsSeparator(self):
+        """
+        Returns whether the item is meant to be an horizontal line separator or not.
+
+        :return: ``True`` if this item is a separator, ``False`` otherwise.
+        """
+
+        return self._separator
+
+
def GetChildren(self):
"""
Returns the item's children.
@@ -1784,8 +1821,13 @@

:param `wnd`: a non-toplevel window to be displayed next to the item, any
subclass of `wx.Window`.
+
+        :raise: `Exception` if the input `item` is a separator and `wnd` is not ``None``.
"""

+        if self.IsSeparator() and wnd is not None:
+            raise Exception("Separator items can not have an associated window")
+
self._wnd = wnd

if wnd.GetSizer():      # the window is a complex one hold by a sizer
@@ -2277,8 +2319,13 @@
Sets the item text.

:param string `text`: the new item label.
+
+        :raise: `Exception` if the item is a separator.
"""

+        if self.IsSeparator():
+            raise Exception("Separator items can not have text")
+
self._text = text

@@ -2669,6 +2716,9 @@
else:
self._drawingfunction = wx.RendererNative.Get().DrawTreeItemButton

+        # Set the separator pen default colour
+        self._separatorPen = wx.Pen(wx.SystemSettings.GetColour(wx.SYS_COLOUR_GRAYTEXT))
+
# Create our container... at last!
wx.PyScrolledWindow.__init__(self, parent, id, pos, size, style|wx.HSCROLL|wx.VSCROLL, name)

@@ -3444,7 +3494,7 @@

def GetItemTextColour(self, item):
"""
-        Returns the item text colour.
+        Returns the item text colour or separator horizontal line colour.

:param `item`: an instance of L{GenericTreeItem}.

@@ -3500,8 +3550,13 @@

:param `item`: an instance of L{GenericTreeItem};
:param string `text`: the new item label.
+
+        :raise: `Exception` if the input `item` is a separator.
"""

+        if item.IsSeparator():
+            raise Exception("Separator items can not have text")
+
dc = wx.ClientDC(self)
item.SetText(text)
self.CalculateSize(item, dc)
@@ -3616,7 +3671,7 @@

def SetItemTextColour(self, item, colour):
"""
-        Sets the item text colour.
+        Sets the item text colour or separator horizontal line colour.

:param `item`: an instance of L{GenericTreeItem};
:param `colour`: a valid `wx.Colour` instance.
@@ -3624,7 +3679,7 @@

item.Attr().SetTextColour(colour)
self.RefreshLine(item)
-
+

def SetItemBackgroundColour(self, item, colour):
"""
@@ -4036,6 +4091,37 @@
return self._backgroundImage

+    def SetSeparatorColour(self, colour):
+        """
+        Sets the pen colour for separator-type items.
+
+        :param `colour` a valid instance of `wx.Colour`.
+        """
+
+        self._separatorPen = wx.Pen(colour, 1)
+        self.Refresh()
+
+
+    def GetSeparatorColour(self, colour):
+        """
+        Returns the pen colour for separator-type items.
+
+        :return An instance of `wx.Colour` representing the separator pen colour.
+        """
+
+        return self._separatorPen.GetColour()
+
+
+    def IsItemSeparator(self, item):
+        """
+        Returns whether an item is of separator type or not.
+
+        :param `item`: an instance of L{GenericTreeItem}.
+        """
+
+        return item.IsSeparator()
+
+
def GetItemWindow(self, item):
"""
Returns the window associated to the item (if any).
@@ -4055,8 +4141,13 @@
:param `item`: an instance of L{GenericTreeItem};
:param `wnd`: if not ``None``, a non-toplevel window to be displayed next to
the item.
+
+        :raise: `Exception` if the input `item` is a separator and `wnd` is not ``None``.
"""

+        if item.IsSeparator() and wnd is not None:
+            raise Exception("Separator items can not have an associated window")
+
if wnd is not None:
self._hasWindows = True
if item not in self._itemWithWindow:
@@ -4623,7 +4714,7 @@
# operations
# -----------------------------------------------------------------------------

-    def DoInsertItem(self, parentId, previous, text, ct_type=0, wnd=None, image=-1, selImage=-1, data=None):
+    def DoInsertItem(self, parentId, previous, text, ct_type=0, wnd=None, image=-1, selImage=-1, data=None, separator=False):
"""
Actually inserts an item in the tree.

@@ -4640,7 +4731,8 @@
:param integer `selImage`: an index within the normal image list specifying the image to
use for the item in selected state; if `image` > -1 and `selImage` is -1, the
same image is used for both selected and unselected items;
-        :param object `data`: associate the given Python object `data` with the item.
+        :param object `data`: associate the given Python object `data` with the item;
+        :param bool `separator`: ``True`` if the item is a separator, ``False`` otherwise.

:return: An instance of L{GenericTreeItem} upon successful insertion.

@@ -4650,7 +4742,12 @@
set for L{CustomTreeCtrl};
- The item has multiline text (with line-breaks in it) but the ``TR_HAS_VARIABLE_ROW_HEIGHT``
flag has not been set for L{CustomTreeCtrl};
-         - The `ct_type` attribute is less than ``0`` or greater than ``2``.
+         - The `ct_type` attribute is less than ``0`` or greater than ``2``;
+         - The parent item is a separator;
+         - The item is a separator but it has text or an associated window.
+
+
+        :note: Separator items should not have children, text labels or an associated window.
"""

if wnd is not None and not self.HasAGWFlag(TR_HAS_VARIABLE_ROW_HEIGHT):
@@ -4661,6 +4758,12 @@

if ct_type < 0 or ct_type > 2:
raise Exception("\nERROR: Item Type Should Be 0 (Normal), 1 (CheckBox) or 2 (RadioButton). ")
+
+        if separator:
+            if wnd:
+                raise Exception("Separator items can not have associated windows")
+            if text.strip():
+                raise Exception("Separator items can not text labels")

parent = parentId

@@ -4670,7 +4773,7 @@

self._dirty = True     # do this first so stuff below doesn't cause flicker

-        item = GenericTreeItem(parent, text, ct_type, wnd, image, selImage, data)
+        item = GenericTreeItem(parent, text, ct_type, wnd, image, selImage, data, separator)

if wnd is not None:
self._hasWindows = True
@@ -4747,7 +4850,7 @@
return self._anchor

-    def PrependItem(self, parent, text, ct_type=0, wnd=None, image=-1, selImage=-1, data=None):
+    def PrependItem(self, parent, text, ct_type=0, wnd=None, image=-1, selImage=-1, data=None, separator=False):
"""
Prepends an item as a first child of parent.

@@ -4763,17 +4866,18 @@
:param integer `selImage`: an index within the normal image list specifying the image to
use for the item in selected state; if `image` > -1 and `selImage` is -1, the
same image is used for both selected and unselected items;
-        :param object `data`: associate the given Python object `data` with the item.
+        :param object `data`: associate the given Python object `data` with the item;
+        :param bool `separator`: ``True`` if the item is a separator, ``False`` otherwise.

:return: An instance of L{GenericTreeItem} upon successful insertion.

:see: L{DoInsertItem} for possible exceptions generated by this method.
"""

-        return self.DoInsertItem(parent, 0, text, ct_type, wnd, image, selImage, data)
+        return self.DoInsertItem(parent, 0, text, ct_type, wnd, image, selImage, data, separator)

-    def InsertItemByItem(self, parentId, idPrevious, text, ct_type=0, wnd=None, image=-1, selImage=-1, data=None):
+    def InsertItemByItem(self, parentId, idPrevious, text, ct_type=0, wnd=None, image=-1, selImage=-1, data=None, separator=False):
"""
Inserts an item after the given previous.

@@ -4791,8 +4895,9 @@
:param integer `selImage`: an index within the normal image list specifying the image to
use for the item in selected state; if `image` > -1 and `selImage` is -1, the
same image is used for both selected and unselected items;
-        :param object `data`: associate the given Python object `data` with the item.
-
+        :param object `data`: associate the given Python object `data` with the item;
+        :param bool `separator`: ``True`` if the item is a separator, ``False`` otherwise.
+
:return: An instance of L{GenericTreeItem} upon successful insertion.

:raise: `Exception` if the previous item is not a sibling.
@@ -4814,10 +4919,10 @@
except:
raise Exception("ERROR: Previous Item In CustomTreeCtrl.InsertItem() Is Not A Sibling")

-        return self.DoInsertItem(parentId, index+1, text, ct_type, wnd, image, selImage, data)
+        return self.DoInsertItem(parentId, index+1, text, ct_type, wnd, image, selImage, data, separator)

-    def InsertItemByIndex(self, parentId, idPrevious, text, ct_type=0, wnd=None, image=-1, selImage=-1, data=None):
+    def InsertItemByIndex(self, parentId, idPrevious, text, ct_type=0, wnd=None, image=-1, selImage=-1, data=None, separator=False):
"""
Inserts an item after the given previous.

@@ -4834,8 +4939,9 @@
:param integer `selImage`: an index within the normal image list specifying the image to
use for the item in selected state; if `image` > -1 and `selImage` is -1, the
same image is used for both selected and unselected items;
-        :param object `data`: associate the given Python object `data` with the item.
-
+        :param object `data`: associate the given Python object `data` with the item;
+        :param bool `separator`: ``True`` if the item is a separator, ``False`` otherwise.
+
:return: An instance of L{GenericTreeItem} upon successful insertion.

:see: L{DoInsertItem} for possible exceptions generated by this method.
@@ -4847,10 +4953,10 @@
# should we give a warning here?
return self.AddRoot(text, ct_type, wnd, image, selImage, data)

-        return self.DoInsertItem(parentId, idPrevious, text, ct_type, wnd, image, selImage, data)
+        return self.DoInsertItem(parentId, idPrevious, text, ct_type, wnd, image, selImage, data, separator)

-    def InsertItem(self, parentId, input, text, ct_type=0, wnd=None, image=-1, selImage=-1, data=None):
+    def InsertItem(self, parentId, input, text, ct_type=0, wnd=None, image=-1, selImage=-1, data=None, separator=False):
"""
Inserts an item after the given previous.

@@ -4863,9 +4969,9 @@
"""

if type(input) == type(1):
-            return self.InsertItemByIndex(parentId, input, text, ct_type, wnd, image, selImage, data)
+            return self.InsertItemByIndex(parentId, input, text, ct_type, wnd, image, selImage, data, separator)
else:
-            return self.InsertItemByItem(parentId, input, text, ct_type, wnd, image, selImage, data)
+            return self.InsertItemByItem(parentId, input, text, ct_type, wnd, image, selImage, data, separator)

def AppendItem(self, parentId, text, ct_type=0, wnd=None, image=-1, selImage=-1, data=None):
@@ -4900,6 +5006,52 @@
return self.DoInsertItem(parent, len(parent.GetChildren()), text, ct_type, wnd, image, selImage, data)

+    def AppendSeparator(self, parentId):
+        """
+        Appends an horizontal line separator as a last child of its parent.
+
+        :param `parentId`: an instance of L{GenericTreeItem} representing the
+         separator's parent.
+
+        :return: An instance of L{GenericTreeItem} upon successful insertion.
+
+        :see: L{DoInsertItem} for possible exceptions generated by this method.
+        """
+
+        parent = parentId
+        return self.DoInsertItem(parent, len(parent.GetChildren()), "", separator=True)
+
+
+    def InsertSeparator(self, parentId, input):
+        """
+        Inserts a separator item after the given previous.
+
+        :return: An instance of L{GenericTreeItem} upon successful insertion.
+
+        :see: L{InsertItemByIndex} and L{InsertItemByItem} for an explanation of
+         the input parameters.
+
+        :see: L{DoInsertItem} for possible exceptions generated by this method.
+        """
+
+        return self.InsertItem(parentId, input, "", separator=True)
+
+
+    def PrependSeparator(self, parent):
+        """
+        Prepends a separator item as a first child of parent.
+
+        :param `parent`: an instance of L{GenericTreeItem} representing the
+         item's parent.
+
+        :return: An instance of L{GenericTreeItem} upon successful insertion.
+
+        :see: L{DoInsertItem} for possible exceptions generated by this method.
+        """
+
+        return self.PrependItem(parent, 0, separator=True)
+
+
def SendDeleteEvent(self, item):
"""
Actually sends the ``EVT_TREE_DELETE_ITEM`` event.
@@ -6211,10 +6363,12 @@
dc.SetTextForeground(self.GetHyperTextNewColour())

text_w, text_h, dummy = dc.GetMultiLineTextExtent(item.GetText())
-
+        w, h = self.GetClientSize()
+
image = item.GetCurrentImage()
checkimage = item.GetCurrentCheckedImage()
leftimage = _NO_IMAGE
+        separator = item.IsSeparator()

if self._imageListLeft:
leftimage = item.GetLeftImage()
@@ -6270,7 +6424,6 @@

if self.HasAGWFlag(TR_FULL_ROW_HIGHLIGHT):
x = 0
-            w, h = self.GetClientSize()

itemrect = wx.Rect(x, item.GetY()+offset, w, total_h-offset)

@@ -6311,9 +6464,14 @@
if wnd:
wndx, wndy = item.GetWindowSize()

+                if separator:
+                    item_width = w
+                else:
+                    item_width = item.GetWidth() - image_w - wcheck + 2 - wndx
+
itemrect = wx.Rect(item.GetX() + wcheck + image_w - 2,
item.GetY()+offset,
-                                   item.GetWidth() - image_w - wcheck + 2 - wndx,
+                                   item_width,
total_h-offset)

if self._usegradients:
@@ -6337,9 +6495,15 @@
elif drawItemBackground:

minusicon = wcheck + image_w - 2
+
+                if separator:
+                    item_width = w
+                else:
+                    item_width = item.GetWidth()-minusicon,
+
itemrect = wx.Rect(item.GetX()+minusicon,
item.GetY()+offset,
-                                   item.GetWidth()-minusicon,
+                                   item_width,
total_h-offset)

if self._usegradients and self._hasFocus:
@@ -6417,13 +6581,28 @@

elif align == 2:
# Rightmost alignment of windows
-                wndx = self.GetClientSize().x - item.GetWindowSize().x - 2
+                wndx = w - item.GetWindowSize().x - 2

if not wnd.IsShown():
wnd.Show()
if wnd.GetPosition() != (wndx, ya):
wnd.SetPosition((wndx, ya))

+        if separator:
+            oldPen = dc.GetPen()
+
+            if item.IsEnabled():
+                if attr and attr.HasTextColour():
+                    separatorPen = wx.Pen(attr.GetTextColour(), 1)
+                else:
+                    separatorPen = self._separatorPen
+            else:
+                separatorPen = wx.GREY_PEN
+
+            dc.SetPen(separatorPen)
+            dc.DrawLine(item.GetX()+2, item.GetY()+total_h/2, w, item.GetY()+total_h/2)
+            dc.SetPen(oldPen)
+
# restore normal font
dc.SetFont(self._normalFont)

@@ -7172,9 +7351,14 @@
Internal function. Starts the editing of an item label, sending a
``EVT_TREE_BEGIN_LABEL_EDIT`` event.

-        :param `item`: an instance of L{GenericTreeItem}.
+        :param `item`: an instance of L{GenericTreeItem}.
+
+        :warning: Separator-type items can not be edited.
"""

+        if item.IsSeparator():
+            return
+
te = TreeEvent(wxEVT_TREE_BEGIN_LABEL_EDIT, self.GetId())
te._item = item
te.SetEventObject(self)
@@ -7724,7 +7908,11 @@
self.absoluteWindows[level] = image_w+text_w+wcheck+2
elif align == 1:
self.absoluteWindows[level] = max(self.absoluteWindows[level], image_w+text_w+wcheck+2)
-
+
+        if item.IsSeparator():
+            totalWidth = self.GetClientSize()[0]
+            totalHeight = total_h
+
item.SetWidth(totalWidth)
item.SetHeight(totalHeight)

@@ -8136,3 +8324,4 @@

GetClassDefaultAttributes = classmethod(GetClassDefaultAttributes)

+

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • customtreectrl »
  • SVN Revision 69864 For customtreectrl


SVN Revision 70819 For customtreectrl

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • customtreectrl »
  • SVN Revision 70819 For customtreectrl

svn SVN Revision 70819 For customtreectrl

This file contains the SVN revision history for customtreectrl, at revision 70819.

Available information include commit date, the name of the committer, the file size, the SVN log messages and a diff from the previous version (if available).

File Information

  • Commit Date: 28-Oct-2008 22:08:44 UTC
  • Committer: AG
  • File Size: 296981 byte(s)

Log Messages

The following log message was entered by the committer:

  • Added the new widget ShortcutEditor.
  • GenericMessageDialog:
    • Added the possibility to have custom labels for the buttons;
    • Added the possibility to have custom icons for the buttons.
  • CustomTreeCtrl:
    • Added the style TR_ELLIPSIZE_LONG_ITEMS, which ellipsizes long items when the horizontal space for CustomTreeCtrl is low;
    • Added the style TR_TOOLTIP_ON_LONG_ITEMS which shows tooltips on long items when the horizontal space for CustomTreeCtrl is low.
  • HyperTreeList:
    • Added the style TR_ELLIPSIZE_LONG_ITEMS, which ellipsizes long items when the horizontal space for HyperTreeList is low.

Diff To Previous Version (69866)

Version SVN diff:

--- wxPython/3rdParty/AGW/agw/customtreectrl.py     2011/11/29 21:26:34     69866
+++ wxPython/3rdParty/AGW/agw/customtreectrl.py     2012/03/05 20:59:35     70819
@@ -3,7 +3,7 @@
# Inspired By And Heavily Based On wxGenericTreeCtrl.
#
# Andrea Gavana, @ 17 May 2006
-# Latest Revision: 29 Nov 2011, 15.00 GMT
+# Latest Revision: 03 Mar 2012, 21.00 GMT
#
#
# TODO List
@@ -95,6 +95,10 @@
- Separators cannot have children;
- Separators cannot be edited via the ``EVT_TREE_BEGIN_LABEL_EDIT`` event.

+* Ellipsization of long items when the horizontal space is low, via the ``TR_ELLIPSIZE_LONG_ITEMS``
+  style (`New in version 0.9.3`);
+* Tooltips on long items when the horizontal space is low, via the ``TR_TOOLTIP_ON_LONG_ITEMS``
+  style (`New in version 0.9.3`).

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

@@ -119,7 +123,15 @@
same tree level.
- ``TR_ALIGN_WINDOWS_RIGHT``: aligns to the rightmost position the windows belonging
to the item on the same tree level.
-
+
+And two styles related to long items (with a lot of text in them), which can be
+ellipsized and/or highlighted with a tooltip:
+
+- ``TR_ELLIPSIZE_LONG_ITEMS``: ellipsizes long items when the horizontal space for
+  L{CustomTreeCtrl} is low (`New in version 0.9.3`);
+- ``TR_TOOLTIP_ON_LONG_ITEMS``: shows tooltips on long items when the horizontal space
+  for L{CustomTreeCtrl} is low (`New in version 0.9.3`);.
+
All the methods available in `wx.TreeCtrl` are also available in L{CustomTreeCtrl}.

@@ -242,6 +254,8 @@
``TR_AUTO_CHECK_PARENT``           0x10000 Only meaningful foe checkbox-type items: when a child item is checked/unchecked its parent item is checked/unchecked as well.
``TR_ALIGN_WINDOWS``               0x20000 Flag used to align windows (in items with windows) at the same horizontal position.
``TR_ALIGN_WINDOWS_RIGHT``         0x40000 Flag used to align windows (in items with windows) to the rightmost edge of L{CustomTreeCtrl}.
+``TR_ELLIPSIZE_LONG_ITEMS``        0x80000 Flag used to ellipsize long items when the horizontal space for L{CustomTreeCtrl} is low.
+``TR_TOOLTIP_ON_LONG_ITEMS``      0x100000 Flag used to show tooltips on long items when the horizontal space for L{CustomTreeCtrl} is low.
============================== =========== ==================================================

@@ -285,14 +299,14 @@

L{CustomTreeCtrl} is distributed under the wxPython license.

-Latest Revision: Andrea Gavana @ 29 Nov 2011, 15.00 GMT
+Latest Revision: Andrea Gavana @ 03 Mar 2012, 21.00 GMT

-Version 2.5
+Version 2.6

"""

# Version Info
-__version__ = "2.5"
+__version__ = "2.6"

import wx
from wx.lib.expando import ExpandoTextCtrl
@@ -386,6 +400,10 @@
""" Flag used to align windows (in items with windows) at the same horizontal position. """
TR_ALIGN_WINDOWS_RIGHT = 0x40000                               # to align windows to the rightmost edge of CustomTreeCtrl
""" Flag used to align windows (in items with windows) to the rightmost edge of L{CustomTreeCtrl}."""
+TR_ELLIPSIZE_LONG_ITEMS = 0x80000                              # to ellipsize long items when horizontal space is low
+""" Flag used to ellipsize long items when the horizontal space for L{CustomTreeCtrl} is low."""
+TR_TOOLTIP_ON_LONG_ITEMS = 0x100000                            # to display tooltips on long items when horizontal space is low
+""" Flag used to show tooltips on long items when the horizontal space for L{CustomTreeCtrl} is low."""

TR_DEFAULT_STYLE = wx.TR_DEFAULT_STYLE                         # default style for the tree control
""" The set of flags that are closest to the defaults for the native control for a""" \
@@ -577,6 +595,7 @@
dc.DrawLine(xMiddle, yMiddle - halfHeight,
xMiddle, yMiddle + halfHeight + 1)

+# ----------------------------------------------------------------------------

def EventFlagsToSelType(style, shiftDown=False, ctrlDown=False):
"""
@@ -602,6 +621,45 @@

return is_multiple, extended_select, unselect_others

+# ----------------------------------------------------------------------------
+
+def ChopText(dc, text, max_size):
+    """
+    Chops the input `text` if its size does not fit in `max_size`, by cutting the
+    text and adding ellipsis at the end.
+
+    :param `dc`: a `wx.DC` device context;
+    :param `text`: the text to chop;
+    :param `max_size`: the maximum size in which the text should fit.
+
+    :note: This method is used exclusively when L{CustomTreeCtrl} has the ``TR_ELLIPSIZE_LONG_ITEMS``
+     style set.
+
+    .. versionadded:: 0.9.3
+    """
+
+    # first check if the text fits with no problems
+    x, y, dummy = dc.GetMultiLineTextExtent(text)
+
+    if x <= max_size:
+        return text
+
+    textLen = len(text)
+    last_good_length = 0
+
+    for i in xrange(textLen, -1, -1):
+        s = text[0:i]
+        s += "..."
+
+        x, y = dc.GetTextExtent(s)
+        last_good_length = i
+
+        if x < max_size:
+            break
+
+    ret = text[0:last_good_length] + "..."
+    return ret
+

#---------------------------------------------------------------------------
# DragImage Implementation
@@ -2588,6 +2646,8 @@
``TR_AUTO_CHECK_PARENT``           0x10000 Only meaningful foe checkbox-type items: when a child item is checked/unchecked its parent item is checked/unchecked as well.
``TR_ALIGN_WINDOWS``               0x20000 Flag used to align windows (in items with windows) at the same horizontal position.
``TR_ALIGN_WINDOWS_RIGHT``         0x40000 Flag used to align windows (in items with windows) to the rightmost edge of L{CustomTreeCtrl}.
+         ``TR_ELLIPSIZE_LONG_ITEMS``        0x80000 Flag used to ellipsize long items when the horizontal space for L{CustomTreeCtrl} is low.
+         ``TR_TOOLTIP_ON_LONG_ITEMS``      0x100000 Flag used to show tooltips on long items when the horizontal space for L{CustomTreeCtrl} is low.
============================== =========== ==================================================

:param `wx.Validator` `validator`: window validator;
@@ -3440,6 +3500,35 @@
return item.GetText()

+    def GetItemSize(self, item):
+        """
+        Returns the horizontal space available in L{CustomTreeCtrl}, in pixels, to draw this item.
+
+        :param `item`: an instance of L{GenericTreeItem}.
+
+        .. versionadded:: 0.9.3
+        """
+
+        w, h = self.GetClientSize()
+        xa, ya = self.CalcScrolledPosition((0, item.GetY()))
+
+        wcheck = image_w = 0
+
+        if item.GetType() != 0:
+            wcheck, dummy = self._imageListCheck.GetSize(item.GetType())
+            wcheck += 4
+
+        image = item.GetCurrentImage()
+
+        if image != _NO_IMAGE:
+            if self._imageListNormal:
+                image_w, dummy = self._imageListNormal.GetSize(image)
+                image_w += 4
+
+        maxsize = w - (wcheck + image_w + item.GetX()) + xa
+        return maxsize
+
+
def GetItemImage(self, item, which=TreeItemIcon_Normal):
"""
Returns the item image.
@@ -6555,16 +6644,22 @@
extraH = ((total_h > text_h) and [(total_h - text_h)/2] or [0])[0]

textrect = wx.Rect(wcheck + image_w + item.GetX(), item.GetY() + extraH, text_w, text_h)
+
+        itemText = item.GetText()
+        if self.HasAGWFlag(TR_ELLIPSIZE_LONG_ITEMS) and not separator:
+            xa, ya = self.CalcScrolledPosition((0, item.GetY()))
+            maxsize = w - (wcheck + image_w + item.GetX()) + xa
+            itemText = ChopText(dc, itemText, maxsize)

if not item.IsEnabled():
foreground = dc.GetTextForeground()
dc.SetTextForeground(self._disabledColour)
-            dc.DrawLabel(item.GetText(), textrect)
+            dc.DrawLabel(itemText, textrect)
dc.SetTextForeground(foreground)
else:
if wx.Platform == "__WXMAC__" and item.IsSelected() and self._hasFocus:
dc.SetTextForeground(wx.WHITE)
-            dc.DrawLabel(item.GetText(), textrect)
+            dc.DrawLabel(itemText, textrect)

wnd = item.GetWindow()
if wnd:
@@ -6875,6 +6970,11 @@
:param `event`: a `wx.SizeEvent` event to be processed.
"""

+        if self.HasAGWFlag(TR_ELLIPSIZE_LONG_ITEMS):
+            self.Refresh()
+            event.Skip()
+            return
+
if self.HasAGWFlag(TR_ALIGN_WINDOWS_RIGHT) and self._itemWithWindow:
self.RefreshItemWithWindows()
else:
@@ -7480,8 +7580,28 @@
hevent.SetEventObject(self)

if self.GetEventHandler().ProcessEvent(hevent) and hevent.IsAllowed():
-                    self.SetToolTip(hevent._label)
+                    self.SetToolTipString(hevent._label)

+                elif self.HasAGWFlag(TR_TOOLTIP_ON_LONG_ITEMS):
+
+                    tip = self.GetToolTipString()
+
+                    if hoverItem.IsSeparator():
+                        if tip:
+                            self.SetToolTipString('')
+                    else:
+                        maxsize = self.GetItemSize(hoverItem)
+                        itemText = hoverItem.GetText()
+
+                        dc = wx.ClientDC(self)
+
+                        if dc.GetMultiLineTextExtent(itemText)[0] > maxsize:
+                            if tip != itemText:
+                                self.SetToolTipString(itemText)
+                        else:
+                            if tip:
+                                self.SetToolTipString('')
+
if hoverItem.IsHyperText() and (flags & TREE_HITTEST_ONITEMLABEL) and hoverItem.IsEnabled():
self.SetCursor(wx.StockCursor(wx.CURSOR_HAND))
self._isonhyperlink = True

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • customtreectrl »
  • SVN Revision 70819 For customtreectrl


SVN Revision 70845 For customtreectrl

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • customtreectrl »
  • SVN Revision 70845 For customtreectrl

svn SVN Revision 70845 For customtreectrl

This file contains the SVN revision history for customtreectrl, at revision 70845.

Available information include commit date, the name of the committer, the file size, the SVN log messages and a diff from the previous version (if available).

File Information

  • Commit Date: 17-Oct-2008 20:51:43 UTC
  • Committer: AG
  • File Size: 297001 byte(s)

Log Messages

The following log message was entered by the committer:

CustomTreeCtrl: fix wrong scrolling behaviour of windows when using the style TR_ALIGN_WINDOWS.

Diff To Previous Version (70830)

Version SVN diff:

--- wxPython/3rdParty/AGW/agw/customtreectrl.py     2012/03/06 21:10:55     70830
+++ wxPython/3rdParty/AGW/agw/customtreectrl.py     2012/03/08 19:16:09     70845
@@ -3,7 +3,7 @@
# Inspired By And Heavily Based On wxGenericTreeCtrl.
#
# Andrea Gavana, @ 17 May 2006
-# Latest Revision: 06 Mar 2012, 21.00 GMT
+# Latest Revision: 08 Mar 2012, 21.00 GMT
#
#
# TODO List
@@ -299,7 +299,7 @@

L{CustomTreeCtrl} is distributed under the wxPython license.

-Latest Revision: Andrea Gavana @ 06 Mar 2012, 21.00 GMT
+Latest Revision: Andrea Gavana @ 08 Mar 2012, 21.00 GMT

Version 2.6

@@ -6672,11 +6672,11 @@
if align == 1:
# Horizontal alignment of windows
if level in self.absoluteWindows:
-                    wndx = self.absoluteWindows[level] + item.GetX() + 2
+                    wndx = self.absoluteWindows[level] + item.GetX() + 2 + xa

elif align == 2:
# Rightmost alignment of windows
-                wndx = w - item.GetWindowSize().x - 2
+                wndx = w - item.GetWindowSize().x - 2 + xa

if not wnd.IsShown():
wnd.Show()

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • customtreectrl »
  • SVN Revision 70845 For customtreectrl


SVN Revision 70873 For customtreectrl

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • customtreectrl »
  • SVN Revision 70873 For customtreectrl

svn SVN Revision 70873 For customtreectrl

This file contains the SVN revision history for customtreectrl, at revision 70873.

Available information include commit date, the name of the committer, the file size, the SVN log messages and a diff from the previous version (if available).

File Information

  • Commit Date: 17-Oct-2008 19:15:31 UTC
  • Committer: AG
  • File Size: 297004 byte(s)

Log Messages

The following log message was entered by the committer:

CustomTreeCtrl: draw more realistic (in terms of size) +/- tree buttons

Diff To Previous Version (70845)

Version SVN diff:

--- wxPython/3rdParty/AGW/agw/customtreectrl.py     2012/03/08 19:16:09     70845
+++ wxPython/3rdParty/AGW/agw/customtreectrl.py     2012/03/11 20:26:28     70873
@@ -3,7 +3,7 @@
# Inspired By And Heavily Based On wxGenericTreeCtrl.
#
# Andrea Gavana, @ 17 May 2006
-# Latest Revision: 08 Mar 2012, 21.00 GMT
+# Latest Revision: 10 Mar 2012, 21.00 GMT
#
#
# TODO List
@@ -299,7 +299,7 @@

L{CustomTreeCtrl} is distributed under the wxPython license.

-Latest Revision: Andrea Gavana @ 08 Mar 2012, 21.00 GMT
+Latest Revision: Andrea Gavana @ 10 Mar 2012, 21.00 GMT

Version 2.6

@@ -6878,8 +6878,8 @@
else:
# These are the standard wx.TreeCtrl buttons as wx.RendererNative knows

-                        wImage = 9
-                        hImage = 9
+                        wImage = 11
+                        hImage = 11

flag = 0

@@ -6888,7 +6888,7 @@
if item == self._underMouse:
flag |= _CONTROL_CURRENT

-                        self._drawingfunction(self, dc, wx.Rect(x - wImage/2, y_mid - hImage/2,wImage, hImage), flag)
+                        self._drawingfunction(self, dc, wx.Rect(x - wImage/2, y_mid - hImage/2, wImage, hImage), flag)

if item.IsExpanded():

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • customtreectrl »
  • SVN Revision 70873 For customtreectrl


SVN Revision 69294 For dockart

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • aui library »
  • aui.dockart »
  • SVN Revision 69294 For dockart

svn SVN Revision 69294 For dockart

This file contains the SVN revision history for dockart, at revision 69294.

Available information include commit date, the name of the committer, the file size, the SVN log messages and a diff from the previous version (if available).

File Information

  • Commit Date: 31-Mar-2009 16:34:20 UTC
  • Committer: AG
  • File Size: 45090 byte(s)

Log Messages

The following log message was entered by the committer:

ModernDockArt for AUI: fixed an unreferenced link to winxptheme.

Diff To Previous Version (66778)

Version SVN diff:

--- wxPython/3rdParty/AGW/agw/aui/dockart.py        2011/01/26 20:56:31     66778
+++ wxPython/3rdParty/AGW/agw/aui/dockart.py        2011/10/02 19:32:45     69294
@@ -915,10 +915,11 @@

# Get the size of a small close button (themed)
hwnd = self.win.GetHandle()
+        self.usingTheme = False

-        self.hTheme1 = winxptheme.OpenThemeData(hwnd, "Window")
-
-        self.usingTheme = True
+        if _ctypes:
+            self.hTheme1 = winxptheme.OpenThemeData(hwnd, "Window")
+            self.usingTheme = True

if not self.hTheme1:
self.usingTheme = False

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • aui library »
  • aui.dockart »
  • SVN Revision 69294 For dockart


SVN Revision 70555 For dockart

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • aui library »
  • aui.dockart »
  • SVN Revision 70555 For dockart

svn SVN Revision 70555 For dockart

This file contains the SVN revision history for dockart, at revision 70555.

Available information include commit date, the name of the committer, the file size, the SVN log messages and a diff from the previous version (if available).

File Information

  • Commit Date: 31-Mar-2009 15:36:51 UTC
  • Committer: AG
  • File Size: 45477 byte(s)

Log Messages

The following log message was entered by the committer:

  • GradientButton: applied patch from Werner and cleaned up a bit the useless parts of the code;
  • AuiToolBar/AuiDefaultDockArt: applied patch from Werner for default colour settings for AUI toolbars;
  • UltimateListCtrl: Fixed bug #13938. Also, don’t throw an error on key down if the list is empty.

Diff To Previous Version (69294)

Version SVN diff:

--- wxPython/3rdParty/AGW/agw/aui/dockart.py        2011/10/02 19:32:45     69294
+++ wxPython/3rdParty/AGW/agw/aui/dockart.py        2012/02/09 20:52:26     70555
@@ -180,14 +180,7 @@
def Init(self):
""" Initializes the dock art. """

-        base_colour = GetBaseColour()
-        darker1_colour = StepColour(base_colour, 85)
-        darker2_colour = StepColour(base_colour, 75)
-        darker3_colour = StepColour(base_colour, 60)
-        darker4_colour = StepColour(base_colour, 40)
-
-        self._background_colour = base_colour
-        self._background_gradient_colour = StepColour(base_colour, 180)
+        self.SetDefaultColours()

isMac = wx.Platform == "__WXMAC__"

@@ -198,10 +191,31 @@

self._active_caption_gradient_colour = LightContrastColour(wx.SystemSettings.GetColour(wx.SYS_COLOUR_HIGHLIGHT))
self._active_caption_text_colour = wx.SystemSettings.GetColour(wx.SYS_COLOUR_HIGHLIGHTTEXT)
-        self._inactive_caption_colour = darker1_colour
-        self._inactive_caption_gradient_colour = StepColour(base_colour, 97)
self._inactive_caption_text_colour = wx.BLACK

+
+    def SetDefaultColours(self, base_colour=None):
+        """
+        Sets the default colours, which are calculated from the given base colour.
+
+        :param `base_colour`: an instance of `wx.Colour`. If defaulted to ``None``, a colour
+         is generated accordingly to the platform and theme.
+        """
+
+        if base_colour is None:
+            base_colour = GetBaseColour()
+
+        darker1_colour = StepColour(base_colour, 85)
+        darker2_colour = StepColour(base_colour, 75)
+        darker3_colour = StepColour(base_colour, 60)
+        darker4_colour = StepColour(base_colour, 40)
+
+        self._background_colour = base_colour
+        self._background_gradient_colour = StepColour(base_colour, 180)
+
+        self._inactive_caption_colour = darker1_colour
+        self._inactive_caption_gradient_colour = StepColour(base_colour, 97)
+
self._sash_brush = wx.Brush(base_colour)
self._background_brush = wx.Brush(base_colour)
self._border_pen = wx.Pen(darker2_colour)

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • aui library »
  • aui.dockart »
  • SVN Revision 70555 For dockart


flatmenu functions

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • flatmenu »
  • flatmenu functions

flatmenu functions

This is the description of standalone Python functions in the flatmenu module.

Functions Summary

ConvertToMonochrome | Converts a bitmap to monochrome colour.
GetAccelIndex | Returns the mnemonic index of the label and the label stripped of the ampersand mnemonic (e.g.
GetMRUEntryLabel | Returns the string used for the MRU list items in the menu.

API Functions API

ConvertToMonochrome(bmp) [source]

Converts a bitmap to monochrome colour.

Parameters: bmp – a valid wx.Bitmap object.

GetAccelIndex(label) [source]

Returns the mnemonic index of the label and the label stripped of the ampersand mnemonic (e.g. ‘lab&el’ ==> will result in 3 and labelOnly = label).

Parameters: label (string) – a string possibly containining an ampersand.

GetMRUEntryLabel(n, path) [source]

Returns the string used for the MRU list items in the menu.

Parameters:
  • n (integer) – the index of the file name in the MRU list;
  • path (string) – the full path of the file name.

Note

The index n is 0-based, as usual, but the strings start from 1.

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • infobar
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • flatmenu »
  • flatmenu functions


FileHistory

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • flatmenu »
  • FileHistory

FileHistory

The FileHistory encapsulates a user interface convenience, the list of most recently visited files as shown on a menu (usually the File menu).

FileHistory can manage one or more file menus. More than one menu may be required in an MDI application, where the file history should appear on each MDI child menu as well as the MDI parent frame.

hierarchy Inheritance Diagram

Inheritance diagram for: FileHistory

Inheritance diagram of FileHistory

Methods Summary

__init__ | Default class constructor.
AddFileToHistory | Adds a file to the file history list, if the object has a pointer to an appropriate file menu.
AddFilesToMenu | Appends the files in the history list, to all menus managed by the file history object
AddFilesToMenu2 | Appends the files in the history list, to the given menu only.
GetBaseId | Returns the base identifier for the range used for appending items.
GetCount | Returns the number of files currently stored in the file history.
GetHistoryFile | Returns the file at this index (zero-based).
GetMaxFiles | Returns the maximum number of files that can be stored.
GetMenus | Returns the list of menus that are managed by this file history object.
GetNoHistoryFiles | Returns the number of files currently stored in the file history.
Load | Loads the file history from the given config object.
RemoveFileFromHistory | Removes the specified file from the history.
RemoveMenu | Removes this menu from the list of those managed by this object.
Save | Saves the file history to the given config object.
SetBaseId | Sets the base identifier for the range used for appending items.
UseMenu | Adds this menu to the list of those menus that are managed by this file history object.

API Class API

class FileHistory(object) [source]

The FileHistory encapsulates a user interface convenience, the list of most recently visited files as shown on a menu (usually the File menu).

FileHistory can manage one or more file menus. More than one menu may be required in an MDI application, where the file history should appear on each MDI child menu as well as the MDI parent frame.

__init__(maxFiles=9, idBase=wx.ID_FILE1) [source]

Default class constructor.

Parameters:
  • maxFiles (integer) – the maximum number of files that should be stored and displayed;
  • idBase (integer) – defaults to wx.ID_FILE1 and represents the id given to the first history menu item.

Note

Since menu items can’t share the same ID you should change idBase to one of your own defined IDs when using more than one FileHistory in your application.

AddFileToHistory(fnNew) [source]

Adds a file to the file history list, if the object has a pointer to an appropriate file menu.

Parameters: fnNew (string) – the file name to add to the history list.

AddFilesToMenu(menu=None) [source]

Appends the files in the history list, to all menus managed by the file history object if menu is None. Otherwise it calls the auxiliary method AddFilesToMenu2.

Parameters: menu – if not None, an instance of FlatMenu.

AddFilesToMenu2(menu) [source]

Appends the files in the history list, to the given menu only.

Parameters: menu – an instance of FlatMenu.

GetBaseId() [source]

Returns the base identifier for the range used for appending items.

GetCount() [source]

Returns the number of files currently stored in the file history.

GetHistoryFile(index) [source]

Returns the file at this index (zero-based).

Parameters: index (integer) – the index at which the file is stored in the file list (zero-based).

GetMaxFiles() [source]

Returns the maximum number of files that can be stored.

GetMenus() [source]

Returns the list of menus that are managed by this file history object.

See also

UseMenu.

GetNoHistoryFiles() [source]

Returns the number of files currently stored in the file history.

Load(config) [source]

Loads the file history from the given config object.

Parameters: config – an instance of wx.Config.

Note

This function should be called explicitly by the application.

See also

Save.

RemoveFileFromHistory(index) [source]

Removes the specified file from the history.

Parameters: index (integer) – the zero-based index indicating the file name position in the file list.

RemoveMenu(menu) [source]

Removes this menu from the list of those managed by this object.

Parameters: menu – an instance of FlatMenu.

Save(config) [source]

Saves the file history to the given config object.

Parameters: config – an instance of wx.Config.

Note

This function should be called explicitly by the application.

See also

Load.

SetBaseId(baseId) [source]

Sets the base identifier for the range used for appending items.

Parameters: baseId (integer) – the base identifier for the range used for appending items.

UseMenu(menu) [source]

Adds this menu to the list of those menus that are managed by this file history object.

Parameters: menu – an instance of FlatMenu.

See also

AddFilesToMenu for initializing the menu with filenames that are already in the history when this function is called, as this is not done automatically.

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • infobar
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • flatmenu »
  • FileHistory


FlatMenu

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • flatmenu »
  • FlatMenu

FlatMenu

A Flat popup menu generic implementation.

hierarchy Inheritance Diagram

Inheritance diagram for: FlatMenu

Inheritance diagram of FlatMenu

supclasses Known Superclasses

  • flatmenu.FlatMenuBase

appearance Control Appearance

FlatMenu

Methods Summary

__init__ | Default class constructor.
AddItem | Internal function to add the item to this menu.
AdvanceSelection | Advance forward or backward the current selection.
Append | Appends an item to this menu.
AppendCheckItem | Adds a checkable item to the end of the menu.
AppendItem | Appends an item to this menu.
AppendMenu | Adds a pull-right submenu to the end of the menu.
AppendRadioItem | Adds a radio item to the end of the menu.
AppendSeparator | Appends a separator item to the end of this menu.
AppendSubMenu | Adds a pull-right submenu to the end of the menu.
Clear | Clears the menu items.
CloseSubMenu | Closes a child sub-menu.
Delete | Removes the menu item from the menu but doesn’t delete the associated menu object.
Destroy | Deletes the menu item from the menu.
Dismiss | Dismisses the popup window.
DoAction | Performs an action based on user selection.
DrawSelection | Redraws the menu.
FindItem | Finds the menu item object associated with the given menu item identifier and, optionally, the (sub)menu it belongs to.
FindMenuItemPos | Finds an item and its position inside the menu based on its id.
FindMenuItemPosSimple | Finds an item and its position inside the menu based on its id.
GetAccelArray | Returns a list filled with the accelerator entries for the menu.
GetAccelTable | Returns the menu accelerator table, an instance of wx.AcceleratorTable.
GetAllItems | Internal function to help recurse through all the menu items.
GetBackgroundBitmap | Returns the background bitmap for this particular FlatMenu, if any.
GetBorderXWidth | Returns the menu border x-width, in pixels.
GetBorderYWidth | Returns the menu border y-width, in pixels.
GetItemFont | Returns this FlatMenuItem font.
GetItemHeight | Returns the height of a particular item, in pixels.
GetItemTextColour | Returns this FlatMenuItem foreground text colour.
GetLabel | Returns the label of a FlatMenuItem.
GetLeftMarginWidth | Returns the menu left margin width, in pixels.
GetMenuBar | Returns the menubar associated with this menu item.
GetMenuBarForSubMenu | Returns the menubar associated with this menu item.
GetMenuItemCount | Returns the number of items in the FlatMenu.
GetMenuItemWidth | Returns the width of a particular item.
GetMenuItems | Returns the list of menu items in the menu.
GetMenuRect | Returns the menu client rectangle.
GetMenuWidth | Returns the menu width in pixels.
GetNumberColumns | Returns the number of columns for a menu window.
GetRightMarginWidth | Returns the menu right margin width, in pixels.
GetSiblingGroupItem | Used internally.
HitTest | HitTest method for FlatMenu.
Insert | Inserts the given item before the position pos.
InsertItem | Inserts an item into the menu.
InsertSeparator | Inserts a separator at the given position.
OnChar | Handles key events for FlatMenu.
OnEraseBackground | Handles the wx.EVT_ERASE_BACKGROUND event for FlatMenu.
OnKeyDown | Handles the wx.EVT_KEY_DOWN event for FlatMenu.
OnKillFocus | Handles the wx.EVT_KILL_FOCUS event for FlatMenu.
OnMouseEnterWindow | Handles the wx.EVT_ENTER_WINDOW event for FlatMenu.
OnMouseLeaveWindow | Handles the wx.EVT_LEAVE_WINDOW event for FlatMenu.
OnMouseLeftDown | Handles the wx.EVT_LEFT_DOWN event for FlatMenu.
OnMouseLeftUp | Handles the wx.EVT_LEFT_UP event for FlatMenu.
OnMouseMove | Handles the wx.EVT_MOTION event for FlatMenu.
OnMouseRightDown | Handles the wx.EVT_RIGHT_DOWN event for FlatMenu.
OnPaint | Handles the wx.EVT_PAINT event for FlatMenu.
OnTimer | Handles the wx.EVT_TIMER event for FlatMenu.
OpenItemContextMenu | Open an item’s context menu (if any).
Popup | Pops up the menu.
Prepend | Prepends an item to this menu.
PrependItem | Prepends an item to this menu.
ProcessMouseLClick | Processes mouse left clicks.
ProcessMouseLClickEnd | Processes mouse left clicks.
ProcessMouseMove | Processes mouse movements.
ProcessMouseRClick | Processes mouse right clicks.
RefreshChilds | In some cases, we need to perform a recursive refresh for all opened submenu
Remove | Removes the menu item from the menu but doesn’t delete the associated menu object.
ResizeMenu | Resizes the menu to the correct size.
ScrollDown | Scrolls the menu down (for very tall menus).
ScrollUp | Scrolls the menu up (for very tall menus).
SendCmdEvent | Actually sends menu command events.
SendOverItem | Sends the EVT_FLAT_MENU_ITEM_MOUSE_OVER and EVT_FLAT_MENU_ITEM_MOUSE_OUT
SendUIEvent | Actually sends menu UI events.
SetBackgroundBitmap | Sets a background bitmap for this particular FlatMenu.
SetItemFont | Sets the FlatMenuItem font.
SetItemTextColour | Sets the FlatMenuItem foreground text colour.
SetLabel | Sets the label of a FlatMenuItem.
SetMenuBar | Attaches this menu to a menubar.
SetNumberColumns | Sets the number of columns for a menu window.
SetSubMenuBar | Attaches this menu to a menubar.
TryOpenSubMenu | If itemIdx is an item with submenu, open it.
TryScrollButtons | Used internally.
UpdateItem | Updates an item.
UpdateRadioGroup | Updates a group of radio items.
_DestroyById | Used internally.
_RemoveById | Used internally.

API Class API

class FlatMenu(FlatMenuBase) [source]

A Flat popup menu generic implementation.

__init__(parent=None) [source]

Default class constructor.

Parameters: parent – the FlatMenu parent window (used to initialize the underlying ShadowPopupWindow).

AddItem(menuItem) [source]

Internal function to add the item to this menu. The item must already be in the self._itemsArr attribute.

Parameters: menuItem – an instance of FlatMenuItem.

AdvanceSelection(down=True) [source]

Advance forward or backward the current selection.

Parameters: down (bool) – True to advance the selection forward, False otherwise.

Append(id, item, helpString="", kind=wx.ITEM_NORMAL) [source]

Appends an item to this menu.

Parameters:
  • id (integer) – the menu item identifier;
  • item (string) – the string to appear on the menu item;
  • helpString (string) – an optional help string associated with the item. By default, the handler for the EVT_FLAT_MENU_ITEM_MOUSE_OVER event displays this string in the status line;
  • kind (integer) – may be wx.ITEM_NORMAL for a normal button (default), wx.ITEM_CHECK for a checkable tool (such tool stays pressed after it had been toggled) or wx.ITEM_RADIO for a checkable tool which makes part of a radio group of tools each of which is automatically unchecked whenever another button in the group is checked;

AppendCheckItem(id, item, helpString='') [source]

Adds a checkable item to the end of the menu.

See also

Append for the explanation of the input parameters.

AppendItem(menuItem) [source]

Appends an item to this menu.

Parameters: menuItem – an instance of FlatMenuItem.

AppendMenu(id, item, subMenu, helpString='') [source]

Adds a pull-right submenu to the end of the menu.

Parameters:
  • id (integer) – the menu item identifier;
  • item (string) – the string to appear on the menu item;
  • subMenu – an instance of FlatMenu, the submenu to append;
  • helpString (string) – an optional help string associated with the item. By default, the handler for the EVT_FLAT_MENU_ITEM_MOUSE_OVER event displays this string in the status line.

AppendRadioItem(id, item, helpString='') [source]

Adds a radio item to the end of the menu.

All consequent radio items form a group and when an item in the group is checked, all the others are automatically unchecked.

See also

Append for the explanation of the input parameters.

AppendSeparator() [source]

Appends a separator item to the end of this menu.

AppendSubMenu(subMenu, item, helpString='') [source]

Adds a pull-right submenu to the end of the menu.

This function is added to duplicate the API of wx.Menu.

See also

AppendMenu for an explanation of the input parameters.

Clear() [source]

Clears the menu items.

CloseSubMenu(itemIdx, alwaysClose=False) [source]

Closes a child sub-menu.

Parameters:
  • itemIdx (integer) – the index of the item for which we want to close the submenu;
  • alwaysClose (bool) – if True, always close the submenu irrespectively of other conditions.

Delete(item)

Removes the menu item from the menu but doesn’t delete the associated menu object. This allows to reuse the same item later by adding it back to the menu (especially useful with submenus).

Parameters: item – can be either a menu item identifier or a plain FlatMenuItem.

Destroy(item) [source]

Deletes the menu item from the menu. If the item is a submenu, it will be deleted. Use Remove if you want to keep the submenu (for example, to reuse it later).

Parameters: item – can be either a menu item identifier or a plain FlatMenuItem.

Dismiss(dismissParent, resetOwner) [source]

Dismisses the popup window.

Parameters:
  • dismissParent (bool) – whether to dismiss the parent menu or not;
  • resetOwner (bool) – True to delete the link between this menu and the owner menu, False otherwise.

DoAction(itemIdx) [source]

Performs an action based on user selection.

Parameters: itemIdx (integer) – the index of the item for which we want to perform the action.

DrawSelection(dc, oldSelection=-1) [source]

Redraws the menu.

Parameters:
  • dc – an instance of wx.DC;
  • oldSelection (integer) – if non-negative, the index representing the previous selected menu item.

FindItem(itemId, menu=None) [source]

Finds the menu item object associated with the given menu item identifier and, optionally, the (sub)menu it belongs to.

Parameters:
  • itemId (integer) – menu item identifier;
  • menu – if not None, it will be filled with the item’s parent menu (if the item was found).
Returns:

The found menu item object, or None if one was not found.

FindMenuItemPos(itemId, menu=None) [source]

Finds an item and its position inside the menu based on its id.

Parameters:
  • itemId (integer) – menu item identifier;
  • menu – if not None, it will be filled with the item’s parent menu (if the item was found).
Returns:

The found menu item object, or None if one was not found.

FindMenuItemPosSimple(item) [source]

Finds an item and its position inside the menu based on its id.

Parameters: item – an instance of FlatMenuItem.
Returns: An integer specifying the index found menu item object, or wx.NOT_FOUND if one was not found.

GetAccelArray() [source]

Returns a list filled with the accelerator entries for the menu.

GetAccelTable() [source]

Returns the menu accelerator table, an instance of wx.AcceleratorTable.

GetAllItems(menu=None, items=[]) [source]

Internal function to help recurse through all the menu items.

Parameters:
  • menu – the menu from which we start accumulating items;
  • items (list) – the array which is recursively filled with menu items.
Returns:

a list of FlatMenuItem.

GetBackgroundBitmap() [source]

Returns the background bitmap for this particular FlatMenu, if any.

GetBorderXWidth() [source]

Returns the menu border x-width, in pixels.

GetBorderYWidth() [source]

Returns the menu border y-width, in pixels.

GetItemFont(itemId) [source]

Returns this FlatMenuItem font.

Parameters: itemId (integer) – the menu item identifier.

GetItemHeight() [source]

Returns the height of a particular item, in pixels.

GetItemTextColour(itemId) [source]

Returns this FlatMenuItem foreground text colour.

Parameters: itemId (integer) – the menu item identifier.

GetLabel(itemId) [source]

Returns the label of a FlatMenuItem.

Parameters: id (integer) – the menu item identifier;

See also

SetLabel.

GetLeftMarginWidth() [source]

Returns the menu left margin width, in pixels.

GetMenuBar() [source]

Returns the menubar associated with this menu item.

GetMenuBarForSubMenu() [source]

Returns the menubar associated with this menu item.

GetMenuItemCount() [source]

Returns the number of items in the FlatMenu.

GetMenuItemWidth(menuItem) [source]

Returns the width of a particular item.

Parameters: menuItem – an instance of FlatMenuItem.

GetMenuItems() [source]

Returns the list of menu items in the menu.

GetMenuRect() [source]

Returns the menu client rectangle.

GetMenuWidth() [source]

Returns the menu width in pixels.

GetNumberColumns() [source]

Returns the number of columns for a menu window.

GetRightMarginWidth() [source]

Returns the menu right margin width, in pixels.

GetSiblingGroupItem(item) [source]

Used internally.

Parameters: item – an instance of FlatMenuItem.

HitTest(pos) [source]

HitTest method for FlatMenu.

Parameters: pos – an instance of wx.Point, a point to test for hits.
Returns: A tuple representing one of the following combinations:
integer parameter settings
Return Tuple | Description
(0, -1) | The HitTest method didn’t find any item with the specified input point pt (MENU_HT_NONE = 0)
(1, integer) | A menu item has been hit (MENU_HT_ITEM = 1)
(2, -1) | The Scroll Up button has been hit (MENU_HT_SCROLL_UP = 2)
(3, -1) | The Scroll Down button has been hit (MENU_HT_SCROLL_DOWN = 3)

Insert(pos, id, item, helpString="", kind=wx.ITEM_NORMAL) [source]

Inserts the given item before the position pos.

Parameters:
  • pos (integer) – the position at which to insert the new menu item;
  • id (integer) – the menu item identifier;
  • item (string) – the string to appear on the menu item;
  • helpString (string) – an optional help string associated with the item. By default, the handler for the EVT_FLAT_MENU_ITEM_MOUSE_OVER event displays this string in the status line;
  • kind (integer) – may be wx.ITEM_NORMAL for a normal button (default), wx.ITEM_CHECK for a checkable tool (such tool stays pressed after it had been toggled) or wx.ITEM_RADIO for a checkable tool which makes part of a radio group of tools each of which is automatically unchecked whenever another button in the group is checked;

InsertItem(pos, item) [source]

Inserts an item into the menu.

Parameters:
  • pos (integer) – the position at which to insert the new menu item;
  • item – an instance of FlatMenuItem.

InsertSeparator(pos) [source]

Inserts a separator at the given position.

Parameters: pos (integer) – the index at which we want to insert the separator.

OnChar(key) [source]

Handles key events for FlatMenu.

Parameters: key – the keyboard key integer code.

OnEraseBackground(event) [source]

Handles the wx.EVT_ERASE_BACKGROUND event for FlatMenu.

Parameters: event – a wx.EraseEvent event to be processed.

Note

This method is intentionally empty to avoid flicker.

OnKeyDown(event) [source]

Handles the wx.EVT_KEY_DOWN event for FlatMenu.

Parameters: event – a wx.KeyEvent event to be processed.

OnKillFocus(event) [source]

Handles the wx.EVT_KILL_FOCUS event for FlatMenu.

Parameters: event – a wx.FocusEvent event to be processed.

OnMouseEnterWindow(event) [source]

Handles the wx.EVT_ENTER_WINDOW event for FlatMenu.

Parameters: event – a wx.MouseEvent event to be processed.

OnMouseLeaveWindow(event) [source]

Handles the wx.EVT_LEAVE_WINDOW event for FlatMenu.

Parameters: event – a wx.MouseEvent event to be processed.

OnMouseLeftDown(event) [source]

Handles the wx.EVT_LEFT_DOWN event for FlatMenu.

Parameters: event – a wx.MouseEvent event to be processed.

OnMouseLeftUp(event) [source]

Handles the wx.EVT_LEFT_UP event for FlatMenu.

Parameters: event – a wx.MouseEvent event to be processed.

OnMouseMove(event) [source]

Handles the wx.EVT_MOTION event for FlatMenu.

Parameters: event – a wx.MouseEvent event to be processed.

OnMouseRightDown(event) [source]

Handles the wx.EVT_RIGHT_DOWN event for FlatMenu.

Parameters: event – a wx.MouseEvent event to be processed.

OnPaint(event) [source]

Handles the wx.EVT_PAINT event for FlatMenu.

Parameters: event – a wx.PaintEvent event to be processed.

OnTimer(event) [source]

Handles the wx.EVT_TIMER event for FlatMenu.

Parameters: event – a wx.TimerEvent event to be processed.

OpenItemContextMenu(itemIdx) [source]

Open an item’s context menu (if any).

Parameters: itemIdx (integer) – the index of the item for which we want to open the context menu.

Popup(pt, owner=None, parent=None) [source]

Pops up the menu.

Parameters:
  • pt – the point at which the menu should be popped up (an instance of wx.Point);

  • owner – the owner of the menu. The owner does not necessarly mean the menu parent, it can also be the window that popped up it;
  • parent – the menu parent window.

Prepend(id, item, helpString="", kind=wx.ITEM_NORMAL) [source]

Prepends an item to this menu.

Parameters:
  • id (integer) – the menu item identifier;
  • item (string) – the string to appear on the menu item;
  • helpString (string) – an optional help string associated with the item. By default, the handler for the EVT_FLAT_MENU_ITEM_MOUSE_OVER event displays this string in the status line;
  • kind (integer) – may be wx.ITEM_NORMAL for a normal button (default), wx.ITEM_CHECK for a checkable tool (such tool stays pressed after it had been toggled) or wx.ITEM_RADIO for a checkable tool which makes part of a radio group of tools each of which is automatically unchecked whenever another button in the group is checked;

PrependItem(menuItem) [source]

Prepends an item to this menu.

Parameters: menuItem – an instance of FlatMenuItem.

ProcessMouseLClick(pos) [source]

Processes mouse left clicks.

Parameters: pos – the position at which the mouse left button was pressed, an instance of wx.Point.

ProcessMouseLClickEnd(pos) [source]

Processes mouse left clicks.

Parameters: pos – the position at which the mouse left button was pressed, an instance of wx.Point.

ProcessMouseMove(pos) [source]

Processes mouse movements.

Parameters: pos – the position at which the mouse was moved, an instance of wx.Point.

ProcessMouseRClick(pos) [source]

Processes mouse right clicks.

Parameters: pos – the position at which the mouse right button was pressed, an instance of wx.Point.

RefreshChilds() [source]

In some cases, we need to perform a recursive refresh for all opened submenu from this.

Remove(item) [source]

Removes the menu item from the menu but doesn’t delete the associated menu object. This allows to reuse the same item later by adding it back to the menu (especially useful with submenus).

Parameters: item – can be either a menu item identifier or a plain FlatMenuItem.

ResizeMenu() [source]

Resizes the menu to the correct size.

ScrollDown() [source]

Scrolls the menu down (for very tall menus).

ScrollUp() [source]

Scrolls the menu up (for very tall menus).

SendCmdEvent(itemIdx) [source]

Actually sends menu command events.

Parameters: itemIdx (integer) – the menu item index for which we want to send a command event.

SendOverItem(itemIdx, over) [source]

Sends the EVT_FLAT_MENU_ITEM_MOUSE_OVER and EVT_FLAT_MENU_ITEM_MOUSE_OUT events.

Parameters:
  • itemIdx (integer) – the menu item index for which we want to send an event;
  • over (bool) – True to send a EVT_FLAT_MENU_ITEM_MOUSE_OVER event, False to send a EVT_FLAT_MENU_ITEM_MOUSE_OUT event.

SendUIEvent(itemIdx) [source]

Actually sends menu UI events.

Parameters: itemIdx (integer) – the menu item index for which we want to send a UI event.

SetBackgroundBitmap(bitmap=None) [source]

Sets a background bitmap for this particular FlatMenu.

Parameters: bitmap – an instance of wx.Bitmap. Set bitmap to None if you wish to remove the background bitmap altogether.

Note

the bitmap is rescaled to fit the menu width and height.

SetItemFont(itemId, font=None) [source]

Sets the FlatMenuItem font.

Parameters:
  • itemId (integer) – the menu item identifier;
  • font – an instance of a valid wx.Font.

SetItemTextColour(itemId, colour=None) [source]

Sets the FlatMenuItem foreground text colour.

Parameters:
  • itemId (integer) – the menu item identifier;
  • colour – an instance of a valid wx.Colour.

SetLabel(itemId, label) [source]

Sets the label of a FlatMenuItem.

Parameters:
  • itemId (integer) – the menu item identifier;
  • label (string) – the menu item label to set.

See also

GetLabel.

SetMenuBar(mb) [source]

Attaches this menu to a menubar.

Parameters: mb – an instance of FlatMenuBar.

SetNumberColumns(numCols) [source]

Sets the number of columns for a menu window.

Parameters: numCols (integer) – the number of columns for this FlatMenu window.

SetSubMenuBar(mb) [source]

Attaches this menu to a menubar.

Parameters: mb – an instance of FlatMenuBar.

TryOpenSubMenu(itemIdx, selectFirst=False) [source]

If itemIdx is an item with submenu, open it.

Parameters:
  • itemIdx (integer) – the index of the item for which we want to open the submenu;
  • selectFirst (bool) – if True, the first item of the submenu will be shown as selected.

TryScrollButtons(event) [source]

Used internally.

UpdateItem(item) [source]

Updates an item.

Parameters: item – an instance of FlatMenuItem.

UpdateRadioGroup(item) [source]

Updates a group of radio items.

Parameters: item – an instance of FlatMenuItem.

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • infobar
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • flatmenu »
  • FlatMenu


FlatMenuBar

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • flatmenu »
  • FlatMenuBar

FlatMenuBar

Implements the generic owner-drawn menu bar for FlatMenu.

hierarchy Inheritance Diagram

Inheritance diagram for: FlatMenuBar

Inheritance diagram of FlatMenuBar

Methods Summary

__init__ | Default class constructor.
ActivateMenu | Activates a menu.
ActivateNextMenu | Activates next menu and make sure all others are non-active.
ActivatePreviousMenu | Activates previous menu and make sure all others are non-active.
AddCheckTool | Adds a new check (or toggle) tool to the toolbar.
AddControl | Adds any control to the toolbar, typically e.g.
AddRadioTool | Adds a new radio tool to the toolbar.
AddSeparator | Adds a separator for spacing groups of tools in toolbar.
AddTool | Adds a tool to the toolbar.
Append | Adds the item to the end of the menu bar.
AppendToolbarItem | Appends a tool to the FlatMenuBar.
ClearBitmaps | Restores a wx.NullBitmap for all the items in the menu.
CreateMoreMenu | Creates the drop down menu and populate it.
DoGiveHelp | Gives tooltips and help in wx.StatusBar.
DoMouseMove | Handles mouse move event.
DoToolbarAction | Performs a toolbar button pressed action.
DrawMoreButton | Draws ‘more’ button to the right side of the menu bar.
DrawToolbar | Draws the toolbar (if present).
DrawToolbarItem | Draws a toolbar item button.
FindMenu | Returns the index of the menu with the given title or wx.NOT_FOUND if
FindMenuItem | Finds the menu item object associated with the given menu item identifier.
GetActiveToolbarItem | Returns the active toolbar item.
GetBackgroundColour | Returns the menu bar background colour.
GetInvisibleMenuItemCount | Returns the number of invisible menu items.
GetInvisibleToolbarItemCount | Returns the number of invisible toolbar items.
GetLastVisibleMenu | Returns the index of the last visible menu on the menu bar.
GetMenu | Returns the menu at the specified index menuIdx (zero-based).
GetMenuCount | Returns the number of menus in the menubar.
GetMoreMenuButtonRect | Returns a rectangle region, as an instance of wx.Rect, surrounding the menu button.
GetOptions | Returns the FlatMenuBar options, whether to show a toolbar, to use LCD screen settings etc...
GetRenderer | Returns the renderer associated with this instance.
GetRendererManager | Returns the FlatMenuBar renderer manager.
HitTest | HitTest method for FlatMenuBar.
Insert | Inserts the menu at the given position into the menu bar.
OnAccelCmd | Single function to handle any accelerator key used inside the menubar.
OnCustomizeDlg | Handles the customize dialog here.
OnEraseBackground | Handles the wx.EVT_ERASE_BACKGROUND event for FlatMenuBar.
OnIdle | Handles the wx.EVT_IDLE event for FlatMenuBar.
OnLeaveMenuBar | Handles the wx.EVT_LEAVE_WINDOW event for FlatMenuBar.
OnLeaveWindow | Handles the wx.EVT_LEAVE_WINDOW event for FlatMenuBar.
OnLeftDown | Handles the wx.EVT_LEFT_DOWN event for FlatMenuBar.
OnLeftUp | Handles the wx.EVT_LEFT_UP event for FlatMenuBar.
OnMenuDismissed | Handles the EVT_FLAT_MENU_DISMISSED event for FlatMenuBar.
OnMouseMove | Handles the wx.EVT_MOTION event for FlatMenuBar.
OnPaint | Handles the wx.EVT_PAINT event for FlatMenuBar.
OnSize | Handles the wx.EVT_SIZE event for FlatMenuBar.
OnStatusBarTimer | Handles the timer expiring to delete the longHelp string in the wx.StatusBar.
PopupMoreMenu | Pops up the ‘more’ menu.
PositionAUI | Positions the control inside a wxAUI / PyAUI frame manager.
ProcessMouseMoveFromMenu | This function is called from child menus, this allow a child menu to pass the mouse movement event to the menu bar.
Remove | Removes the menu from the menu bar and returns the menu object - the caller is responsible for deleting it.
RemoveHelp | Removes the tooltips and statusbar help (if any) for a button.
ResetToolbarItems | Used internally.
SetBackgroundColour | Sets the menu bar background colour.
SetBarHeight | Recalculates the FlatMenuBar height when its settings change.
SetLCDMonitor | Sets whether the PC monitor is an LCD or not.
SetMargin | Sets the margin above and below the menu bar text.
SetOptions | Sets the FlatMenuBar options, whether to show a toolbar, to use LCD screen settings etc...
SetSpacing | Sets the spacing between the menubar items.
SetToolbarMargin | Sets the margin around the toolbar.
SetToolbarSpacing | Sets the spacing between the toolbar tools.
SetUpdateInterval | Sets the UpdateUI interval for toolbar items. All UpdateUI events are
ShowCustomize | Shows/hides the drop-down arrow which allows customization of FlatMenu.
UpdateAcceleratorTable | Updates the parent accelerator table.
UpdateItem | An item was modified.

API Class API

class FlatMenuBar(wx.Panel) [source]

Implements the generic owner-drawn menu bar for FlatMenu.

__init__(parent, id=wx.ID_ANY, iconSize=SmallIcons, spacer=SPACER, options=FM_OPT_SHOW_CUSTOMIZE|FM_OPT_IS_LCD) [source]

Default class constructor.

Parameters:
  • parent – the menu bar parent, must not be None;
  • id (integer) – the window identifier. If wx.ID_ANY, will automatically create an identifier;
  • iconSize (integer) – size of the icons in the toolbar. This can be one of the following values (in pixels):

    integer parameter settings
    iconSize Bit | Value | Description
    LargeIcons | 32 | Use large 32x32 icons
    SmallIcons | 16 | Use standard 16x16 icons
  • spacer (integer) – the space between the menu bar text and the menu bar border;
  • options (integer) – a combination of the following bits:

    integer parameter settings
    options Bit | Hex Value | Description
    FM_OPT_IS_LCD | 0x1 | Use this style if your computer uses a LCD screen
    FM_OPT_MINIBAR | 0x2 | Use this if you plan to use toolbar only
    FM_OPT_SHOW_CUSTOMIZE | 0x4 | Show “customize link” in more menus, you will need to write your own handler. See demo.
    FM_OPT_SHOW_TOOLBAR | 0x8 | Set this option is you are planing to use the toolbar

ActivateMenu(menuInfo) [source]

Activates a menu.

Parameters: menuInfo – an instance of MenuEntryInfo.

ActivateNextMenu() [source]

Activates next menu and make sure all others are non-active.

ActivatePreviousMenu() [source]

Activates previous menu and make sure all others are non-active.

AddCheckTool(toolId, label="", bitmap1=wx.NullBitmap, bitmap2=wx.NullBitmap, shortHelp="", longHelp="") [source]

Adds a new check (or toggle) tool to the toolbar.

See also

AddTool for parameter descriptions.

AddControl(control) [source]

Adds any control to the toolbar, typically e.g. a combobox.

Parameters: control – the control to be added, a subclass of wx.Window (but no wx.TopLevelWindow).

AddRadioTool(toolId, label= "", bitmap1=wx.NullBitmap, bitmap2=wx.NullBitmap, shortHelp="", longHelp="") [source]

Adds a new radio tool to the toolbar.

Consecutive radio tools form a radio group such that exactly one button in the group is pressed at any moment, in other words whenever a button in the group is pressed the previously pressed button is automatically released.

You should avoid having the radio groups of only one element as it would be impossible for the user to use such button.

By default, the first button in the radio group is initially pressed, the others are not.

See also

AddTool for parameter descriptions.

AddSeparator() [source]

Adds a separator for spacing groups of tools in toolbar.

AddTool(toolId, label="", bitmap1=wx.NullBitmap, bitmap2=wx.NullBitmap, kind=wx.ITEM_NORMAL, shortHelp="", longHelp="") [source]

Adds a tool to the toolbar.

Parameters:
  • toolId (integer) – an integer by which the tool may be identified in subsequent operations;
  • label (string) – the tool label string;
  • kind (integer) – may be wx.ITEM_NORMAL for a normal button (default), wx.ITEM_CHECK for a checkable tool (such tool stays pressed after it had been toggled) or wx.ITEM_RADIO for a checkable tool which makes part of a radio group of tools each of which is automatically unchecked whenever another button in the group is checked;
  • bitmap1 – the primary tool bitmap, an instance of wx.Bitmap;
  • bitmap2 – the bitmap used when the tool is disabled. If it is equal to wx.NullBitmap, the disabled bitmap is automatically generated by greing out the normal one;
  • shortHelp (string) – a string used for the tools tooltip;
  • longHelp (string) – this string is shown in the wx.StatusBar (if any) of the parent frame when the mouse pointer is inside the tool.

Append(menu, title) [source]

Adds the item to the end of the menu bar.

Parameters:
  • menu – the menu to which we are appending a new item, an instance of FlatMenu;
  • title (string) – the menu item label, must not be empty.

See also

Insert.

AppendToolbarItem(item) [source]

Appends a tool to the FlatMenuBar.

Warning

This method is now deprecated.

See also

AddTool

ClearBitmaps(start=0) [source]

Restores a wx.NullBitmap for all the items in the menu.

Parameters: start (integer) – the index at which to start resetting the bitmaps.

CreateMoreMenu() [source]

Creates the drop down menu and populate it.

DoGiveHelp(hit) [source]

Gives tooltips and help in wx.StatusBar.

Parameters: hit – the toolbar tool currently hovered by the mouse.

DoMouseMove(pt, leftIsDown) [source]

Handles mouse move event.

Parameters:
  • pt – an instance of wx.Point;
  • leftIsDown (bool) – True is the left mouse button is down, False otherwise.

DoToolbarAction(idx) [source]

Performs a toolbar button pressed action.

Parameters: idx (integer) – the tool index in the toolbar.

DrawMoreButton(dc, state) [source]

Draws ‘more’ button to the right side of the menu bar.

Parameters:
  • dc – an instance of wx.DC;
  • state (integer) – the ‘more’ button state.

See also

MenuEntryInfo.SetState() for a list of valid menu states.

DrawToolbar(dc, rect) [source]

Draws the toolbar (if present).

Parameters:
  • dc – an instance of wx.DC;

  • rect – the toolbar client rectangle, an instance of wx.Rect.

DrawToolbarItem(dc, idx, state) [source]

Draws a toolbar item button.

Parameters:
  • dc – an instance of wx.DC;

  • idx (integer) – the tool index in the toolbar;
  • state (integer) – the button state.

See also

MenuEntryInfo.SetState() for a list of valid menu states.

FindMenu(title) [source]

Returns the index of the menu with the given title or wx.NOT_FOUND if no such menu exists in this menubar.

Parameters: title (string) – may specify either the menu title (with accelerator characters, i.e. “&File”) or just the menu label (“File”) indifferently.

FindMenuItem(id) [source]

Finds the menu item object associated with the given menu item identifier.

Parameters: id (integer) – the identifier for the sought FlatMenuItem.
Returns: The found menu item object, or None if one was not found.

GetActiveToolbarItem() [source]

Returns the active toolbar item.

GetBackgroundColour() [source]

Returns the menu bar background colour.

GetInvisibleMenuItemCount() [source]

Returns the number of invisible menu items.

Note

Valid only after the wx.PaintEvent has been processed after a resize.

GetInvisibleToolbarItemCount() [source]

Returns the number of invisible toolbar items.

Note

Valid only after the wx.PaintEvent has been processed after a resize.

GetLastVisibleMenu() [source]

Returns the index of the last visible menu on the menu bar.

GetMenu(menuIdx) [source]

Returns the menu at the specified index menuIdx (zero-based).

Parameters: menuIdx (integer) – the index of the sought menu.
Returns: The found menu item object, or None if one was not found.

GetMenuCount() [source]

Returns the number of menus in the menubar.

GetMoreMenuButtonRect() [source]

Returns a rectangle region, as an instance of wx.Rect, surrounding the menu button.

GetOptions() [source]

Returns the FlatMenuBar options, whether to show a toolbar, to use LCD screen settings etc...

See also

SetOptions for a list of valid options.

GetRenderer() [source]

Returns the renderer associated with this instance.

GetRendererManager() [source]

Returns the FlatMenuBar renderer manager.

HitTest(pt) [source]

HitTest method for FlatMenuBar.

Parameters: pt – an instance of wx.Point, specifying the hit test position.
Returns: A tuple representing one of the following combinations:
integer parameter settings
Return Tuple | Description
(-1, 0) | The HitTest method didn’t find any item with the specified input point pt (NoWhere = 0)
(integer, 1) | A menu item has been hit, its position specified by the tuple item integer (MenuItem = 1)
(integer, 2) | A toolbar item has ben hit, its position specified by the tuple item integer (ToolbarItem = 2)
(-1, 3) | The drop-down area button has been hit (DropDownArrowButton = 3)

Insert(pos, menu, title) [source]

Inserts the menu at the given position into the menu bar.

Parameters:
  • pos (integer) – the position of the new menu in the menu bar;
  • menu – the menu to add, an instance of FlatMenu. FlatMenuBar owns the menu and will free it;
  • title (string) – the title of the menu.

Note

Inserting menu at position 0 will insert it in the very beginning of it, inserting at position GetMenuCount is the same as calling Append.

OnAccelCmd(event) [source]

Single function to handle any accelerator key used inside the menubar.

Parameters: event – a FlatMenuEvent event to be processed.

OnCustomizeDlg(event) [source]

Handles the customize dialog here.

Parameters: event – a FlatMenuEvent event to be processed.

OnEraseBackground(event) [source]

Handles the wx.EVT_ERASE_BACKGROUND event for FlatMenuBar.

Parameters: event – a wx.EraseEvent event to be processed.

Note

This method is intentionally empty to reduce flicker.

OnIdle(event) [source]

Handles the wx.EVT_IDLE event for FlatMenuBar.

Parameters: event – a wx.IdleEvent event to be processed.

OnLeaveMenuBar(event) [source]

Handles the wx.EVT_LEAVE_WINDOW event for FlatMenuBar.

Parameters: event – a wx.MouseEvent event to be processed.

Note

This method is for MSW only.

OnLeaveWindow(event) [source]

Handles the wx.EVT_LEAVE_WINDOW event for FlatMenuBar.

Parameters: event – a wx.MouseEvent event to be processed.

Note

This method is for GTK only.

OnLeftDown(event) [source]

Handles the wx.EVT_LEFT_DOWN event for FlatMenuBar.

Parameters: event – a wx.MouseEvent event to be processed.

OnLeftUp(event) [source]

Handles the wx.EVT_LEFT_UP event for FlatMenuBar.

Parameters: event – a wx.MouseEvent event to be processed.

OnMenuDismissed(event) [source]

Handles the EVT_FLAT_MENU_DISMISSED event for FlatMenuBar.

Parameters: event – a FlatMenuEvent event to be processed.

OnMouseMove(event) [source]

Handles the wx.EVT_MOTION event for FlatMenuBar.

Parameters: event – a wx.MouseEvent event to be processed.

OnPaint(event) [source]

Handles the wx.EVT_PAINT event for FlatMenuBar.

Parameters: event – a wx.PaintEvent event to be processed.

OnSize(event) [source]

Handles the wx.EVT_SIZE event for FlatMenuBar.

Parameters: event – a wx.SizeEvent event to be processed.

OnStatusBarTimer() [source]

Handles the timer expiring to delete the longHelp string in the wx.StatusBar.

PopupMoreMenu() [source]

Pops up the ‘more’ menu.

PositionAUI(mgr, fixToolbar=True) [source]

Positions the control inside a wxAUI / PyAUI frame manager.

Parameters:
  • mgr – an instance of wx.aui.AuiManager or AuiManager;
  • fixToolbar (bool) – True if FlatMenuBar can not be floated.

ProcessMouseMoveFromMenu(pt) [source]

This function is called from child menus, this allow a child menu to pass the mouse movement event to the menu bar.

Parameters: pt – an instance of wx.Point.

Remove(pos) [source]

Removes the menu from the menu bar and returns the menu object - the caller is responsible for deleting it.

Parameters: pos (integer) – the position of the menu in the menu bar.

Note

This function may be used together with Insert to change the menubar dynamically.

RemoveHelp() [source]

Removes the tooltips and statusbar help (if any) for a button.

ResetToolbarItems() [source]

Used internally.

SetBackgroundColour(colour) [source]

Sets the menu bar background colour.

Parameters: colour – a valid wx.Colour.

SetBarHeight() [source]

Recalculates the FlatMenuBar height when its settings change.

SetLCDMonitor(lcd=True) [source]

Sets whether the PC monitor is an LCD or not.

Parameters: lcd (bool) – True to use the settings appropriate for a LCD monitor, False otherwise.

SetMargin(margin) [source]

Sets the margin above and below the menu bar text.

Parameters: margin (integer) – height in pixels of the margin.

SetOptions(options) [source]

Sets the FlatMenuBar options, whether to show a toolbar, to use LCD screen settings etc...

Parameters: options (integer) – a combination of the following bits:

integer parameter settings
options Bit | Hex Value | Description
FM_OPT_IS_LCD | 0x1 | Use this style if your computer uses a LCD screen
FM_OPT_MINIBAR | 0x2 | Use this if you plan to use toolbar only
FM_OPT_SHOW_CUSTOMIZE | 0x4 | Show “customize link” in more menus, you will need to write your own handler. See demo.
FM_OPT_SHOW_TOOLBAR | 0x8 | Set this option is you are planing to use the toolbar

SetSpacing(spacer) [source]

Sets the spacing between the menubar items.

Parameters: spacer (integer) – number of pixels between each menu item.

SetToolbarMargin(margin) [source]

Sets the margin around the toolbar.

Parameters: margin (integer) – width in pixels of the margin around the tools in the toolbar.

SetToolbarSpacing(spacer) [source]

Sets the spacing between the toolbar tools.

Parameters: spacer (integer) – number of pixels between each tool in the toolbar.

SetUpdateInterval(interval) [source]

Sets the UpdateUI interval for toolbar items. All UpdateUI events are sent from within OnIdle handler, the default is 20 milliseconds.

Parameters: interval (integer) – the updateUI interval in milliseconds.

ShowCustomize(show=True) [source]

Shows/hides the drop-down arrow which allows customization of FlatMenu.

Parameters: show (bool) – True to show the customize menu, False to hide it.

UpdateAcceleratorTable() [source]

Updates the parent accelerator table.

UpdateItem(item) [source]

An item was modified. This function is called by FlatMenu in case an item was modified directly and not via a wx.UpdateUIEvent event.

Parameters: item – an instance of FlatMenu.

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • infobar
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • flatmenu »
  • FlatMenuBar


FlatMenuBase

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • flatmenu »
  • FlatMenuBase

FlatMenuBase

Base class for generic flat menu derived from wx.PopupWindow.

hierarchy Inheritance Diagram

Inheritance diagram for: FlatMenuBase

Inheritance diagram of FlatMenuBase

subclasses Known Subclasses

  • flatmenu.FlatMenu

supclasses Known Superclasses

  • flatmenu.ShadowPopupWindow

Methods Summary

__init__ | Default class constructor.
AdjustPosition | Adjusts position so the menu will be fully visible on screen.
Dismiss | Dismisses the popup window.
GetMenuOwner | Returns the menu logical owner, the owner does not necessarly mean the
GetRenderer | Returns the renderer for this class.
GetRootMenu | Returns the top level menu.
OnChildDismiss | Handles children dismiss.
OnDismiss | Fires an event EVT_FLAT_MENU_DISMISSED and handle menu dismiss.
Popup | Popups menu at the specified point.
ScrollDown | Scroll one unit down.
ScrollUp | Scroll one unit up.
SetOwnerHeight | Sets the menu owner height, this will be used to position the menu below or above the owner.

API Class API

class FlatMenuBase(ShadowPopupWindow) [source]

Base class for generic flat menu derived from wx.PopupWindow.

__init__(parent=None) [source]

Default class constructor.

Parameters: parent – the ShadowPopupWindow parent window.

AdjustPosition(pos) [source]

Adjusts position so the menu will be fully visible on screen.

Parameters: pos – an instance of wx.Point specifying the menu position.

Dismiss(dismissParent, resetOwner) [source]

Dismisses the popup window.

Parameters:
  • dismissParent (bool) – whether to dismiss the parent menu or not;
  • resetOwner (bool) – True to delete the link between this menu and the owner menu, False otherwise.

GetMenuOwner() [source]

Returns the menu logical owner, the owner does not necessarly mean the menu parent, it can also be the window that popped up it.

GetRenderer() [source]

Returns the renderer for this class.

GetRootMenu() [source]

Returns the top level menu.

OnChildDismiss() [source]

Handles children dismiss.

OnDismiss() [source]

Fires an event EVT_FLAT_MENU_DISMISSED and handle menu dismiss.

Popup(pt, parent) [source]

Popups menu at the specified point.

Parameters:
  • pt – an instance of wx.Point, assumed to be in screen coordinates. However, if parent is not None, pt is translated into the screen coordinates using parent.ClientToScreen();

  • parent – if not None, an instance of wx.Window.

ScrollDown() [source]

Scroll one unit down. By default this function is empty, let derived class do something.

ScrollUp() [source]

Scroll one unit up. By default this function is empty, let derived class do something.

SetOwnerHeight(height) [source]

Sets the menu owner height, this will be used to position the menu below or above the owner.

Parameters: height (integer) – an integer representing the menu owner height.

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • infobar
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • flatmenu »
  • FlatMenuBase


FlatMenuButton

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • flatmenu »
  • FlatMenuButton

FlatMenuButton

A nice small class that functions like wx.BitmapButton, the reason I did not used wx.BitmapButton is that on Linux, it has some extra margins that I can’t seem to be able to remove.

hierarchy Inheritance Diagram

Inheritance diagram for: FlatMenuButton

Inheritance diagram of FlatMenuButton

Methods Summary

__init__ | Default class constructor.
Contains | Used internally.
Draw | Draws self at rect using dc.
GetClientRect | Returns the client rectangle for FlatMenuButton.
GetTimer | Returns the timer object.
GetTimerId | Returns the timer object identifier.
Move | Moves FlatMenuButton to the specified position.
ProcessLeftDown | Handles left down mouse events.
ProcessLeftUp | Handles left up mouse events.
ProcessMouseMove | Handles mouse motion events.
SetSize | Sets the size for FlatMenuButton.
__del__ | Used internally.

API Class API

class FlatMenuButton(object) [source]

A nice small class that functions like wx.BitmapButton, the reason I did not used wx.BitmapButton is that on Linux, it has some extra margins that I can’t seem to be able to remove.

__init__(menu, up, normalBmp, disabledBmp=wx.NullBitmap, scrollOnHover=False) [source]

Default class constructor.

Parameters:
  • menu – the parent menu associated with this button, an instance of FlatMenu;
  • up (bool) – True for up arrow or False for down arrow;
  • normalBmp – normal state bitmap, an instance of wx.Bitmap;
  • disabledBmp – disabled state bitmap, an instance of wx.Bitmap.

Contains(pt) [source]

Used internally.

Draw(dc) [source]

Draws self at rect using dc.

Parameters: dc – an instance of wx.DC.

GetClientRect() [source]

Returns the client rectangle for FlatMenuButton.

GetTimer() [source]

Returns the timer object.

GetTimerId() [source]

Returns the timer object identifier.

Move(input1, input2=None) [source]

Moves FlatMenuButton to the specified position.

Parameters:
  • input1 – if it is an instance of wx.Point, it represents the FlatMenuButton position and the input2 parameter is not used. Otherwise it is an integer representing the button x position;
  • input2 – if not None, it is an integer representing the button y position.

ProcessLeftDown(pt) [source]

Handles left down mouse events.

Parameters: pt – an instance of wx.Point where the left mouse button was pressed.

ProcessLeftUp(pt) [source]

Handles left up mouse events.

Parameters: pt – an instance of wx.Point where the left mouse button was released.

ProcessMouseMove(pt) [source]

Handles mouse motion events. This is called any time the mouse moves in the parent menu, so we must check to see if the mouse is over the button.

Parameters: pt – an instance of wx.Point where the mouse pointer was moved.

SetSize(input1, input2=None) [source]

Sets the size for FlatMenuButton.

Parameters:
  • input1 – if it is an instance of wx.Size, it represents the FlatMenuButton size and the input2 parameter is not used. Otherwise it is an integer representing the button width;
  • input2 – if not None, it is an integer representing the button height.

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • infobar
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • flatmenu »
  • FlatMenuButton


FlatMenuEvent

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • flatmenu »
  • FlatMenuEvent

FlatMenuEvent

Event class that supports the FlatMenu-compatible event called EVT_FLAT_MENU_SELECTED.

hierarchy Inheritance Diagram

Inheritance diagram for: FlatMenuEvent

Inheritance diagram of FlatMenuEvent

Methods Summary

__init__ Default class constructor.

API Class API

class FlatMenuEvent(wx.PyCommandEvent) [source]

Event class that supports the FlatMenu-compatible event called EVT_FLAT_MENU_SELECTED.

__init__(eventType, eventId=1) [source]

Default class constructor.

Parameters:
  • eventType (integer) – the event type;
  • eventId (integer) – the event identifier.

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • infobar
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • flatmenu »
  • FlatMenuEvent


FlatMenuItem

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • flatmenu »
  • FlatMenuItem

FlatMenuItem

A class that represents an item in a menu.

hierarchy Inheritance Diagram

Inheritance diagram for: FlatMenuItem

Inheritance diagram of FlatMenuItem

Methods Summary

__init__ | Default class constructor.
Check | Checks or unchecks the menu item.
Enable | Enables or disables a menu item.
GetAccelString | Returns the accelerator string.
GetAcceleratorEntry | Returns the accelerator entry associated to this menu item.
GetBitmap | Returns the normal bitmap associated to the menu item or wx.NullBitmap if
GetContextMenu | Returns the context menu associated with this item (if any).
GetDisabledBitmap | Returns the disabled bitmap associated to the menu item or wx.NullBitmap
GetFont | Returns this FlatMenuItem font.
GetHeight | Returns the menu item height, in pixels.
GetHelp | Returns the item help string.
GetHotBitmap | Returns the hot bitmap associated to the menu item or wx.NullBitmap if
GetId | Returns the item id.
GetKind | Returns the menu item kind, can be one of wx.ITEM_SEPARATOR, wx.ITEM_NORMAL,
GetLabel | Returns the menu item label (without the accelerator if it is part of the string).
GetLongHelp | Returns the item long help string (displayed in the parent frame wx.StatusBar).
GetMenu | Returns the parent menu.
GetMnemonicChar | Returns the shortcut char for this menu item.
GetRect | Returns the menu item client rectangle.
GetShortHelp | Returns the item short help string (displayed in the tool’s tooltip).
GetSubMenu | Returns the sub-menu of this menu item (if any).
GetSuitableBitmap | Gets the bitmap that should be used based on the item state.
GetText | Returns the text associated with the menu item including the accelerator.
GetTextColour | Returns this FlatMenuItem foreground text colour.
IsCheckable | Returns True if this item is of type wx.ITEM_CHECK, False otherwise.
IsChecked | Returns whether an item is checked or not.
IsEnabled | Returns whether an item is enabled or not.
IsRadioItem | Returns True if this item is of type wx.ITEM_RADIO, False otherwise.
IsSeparator | Returns True if this item is of type wx.ITEM_SEPARATOR, False otherwise.
IsShown | Returns whether an item is shown or not.
IsSubMenu | Returns whether an item is a sub-menu or not.
SetContextMenu | Assigns a context menu to this item.
SetDisabledBitmap | Sets the menu item disabled bitmap.
SetFont | Sets the FlatMenuItem font.
SetHelp | Sets the menu item help string.
SetHotBitmap | Sets the menu item hot bitmap.
SetLabel | Sets the label text for this item from the text (excluding the accelerator).
SetLongHelp | Sets the item long help string (displayed in the parent frame wx.StatusBar).
SetMenu | Sets the menu item parent menu.
SetMenuBar | Links the current menu item with the main FlatMenuBar.
SetNormalBitmap | Sets the menu item normal bitmap.
SetRect | Sets the menu item client rectangle.
SetSubMenu | Sets the menu item sub-menu.
SetText | Sets the text for this menu item (including accelerators).
SetTextColour | Sets the FlatMenuItem foreground colour for the menu label.
Show | Actually shows/hides the menu item.

API Class API

class FlatMenuItem(object) [source]

A class that represents an item in a menu.

__init__(parent, id=wx.ID_SEPARATOR, label="", helpString="", kind=wx.ITEM_NORMAL, subMenu=None, normalBmp=wx.NullBitmap, disabledBmp=wx.NullBitmap, hotBmp=wx.NullBitmap) [source]

Default class constructor.

Parameters:
  • parent – menu that the menu item belongs to, an instance of FlatMenu;
  • id (integer) – the menu item identifier;
  • label (string) – text for the menu item, as shown on the menu. An accelerator key can be specified using the ampersand ‘&’ character. In order to embed an ampersand character in the menu item text, the ampersand must be doubled;
  • helpString (string) – optional help string that will be shown on the status bar;
  • kind (integer) – may be wx.ITEM_SEPARATOR, wx.ITEM_NORMAL, wx.ITEM_CHECK or wx.ITEM_RADIO;
  • subMenu – if not None, the sub menu this item belongs to (an instance of FlatMenu);
  • normalBmp – normal bitmap to draw to the side of the text, this bitmap is used when the menu is enabled (an instance of wx.Bitmap);
  • disabledBmp – ‘greyed’ bitmap to draw to the side of the text, this bitmap is used when the menu is disabled, if none supplied normal is used (an instance of wx.Bitmap);

  • hotBmp – hot bitmap to draw to the side of the text, this bitmap is used when the menu is hovered, if non supplied, normal is used (an instance of wx.Bitmap).

Check(check=True) [source]

Checks or unchecks the menu item.

Parameters: check (bool) – True to check the menu item, False to uncheck it.

Note

This method is meaningful only for menu items of wx.ITEM_CHECK or wx.ITEM_RADIO kind.

Enable(enable=True) [source]

Enables or disables a menu item.

Parameters: enable (bool) – True to enable the menu item, False to disable it.

GetAccelString() [source]

Returns the accelerator string.

GetAcceleratorEntry() [source]

Returns the accelerator entry associated to this menu item.

GetBitmap() [source]

Returns the normal bitmap associated to the menu item or wx.NullBitmap if none has been supplied.

GetContextMenu() [source]

Returns the context menu associated with this item (if any).

GetDisabledBitmap() [source]

Returns the disabled bitmap associated to the menu item or wx.NullBitmap if none has been supplied.

GetFont() [source]

Returns this FlatMenuItem font.

GetHeight() [source]

Returns the menu item height, in pixels.

GetHelp() [source]

Returns the item help string.

GetHotBitmap() [source]

Returns the hot bitmap associated to the menu item or wx.NullBitmap if none has been supplied.

GetId() [source]

Returns the item id.

GetKind() [source]

Returns the menu item kind, can be one of wx.ITEM_SEPARATOR, wx.ITEM_NORMAL, wx.ITEM_CHECK or wx.ITEM_RADIO.

GetLabel() [source]

Returns the menu item label (without the accelerator if it is part of the string).

GetLongHelp() [source]

Returns the item long help string (displayed in the parent frame wx.StatusBar).

GetMenu() [source]

Returns the parent menu.

GetMnemonicChar() [source]

Returns the shortcut char for this menu item.

GetRect() [source]

Returns the menu item client rectangle.

GetShortHelp() [source]

Returns the item short help string (displayed in the tool’s tooltip).

GetSubMenu() [source]

Returns the sub-menu of this menu item (if any).

GetSuitableBitmap(selected) [source]

Gets the bitmap that should be used based on the item state.

Parameters: selected (bool) – True if this menu item is currently hovered by the mouse, False otherwise.

GetText() [source]

Returns the text associated with the menu item including the accelerator.

GetTextColour() [source]

Returns this FlatMenuItem foreground text colour.

IsCheckable() [source]

Returns True if this item is of type wx.ITEM_CHECK, False otherwise.

IsChecked() [source]

Returns whether an item is checked or not.

Note

This method is meaningful only for items of kind wx.ITEM_CHECK or wx.ITEM_RADIO.

IsEnabled() [source]

Returns whether an item is enabled or not.

IsRadioItem() [source]

Returns True if this item is of type wx.ITEM_RADIO, False otherwise.

IsSeparator() [source]

Returns True if this item is of type wx.ITEM_SEPARATOR, False otherwise.

IsShown() [source]

Returns whether an item is shown or not.

IsSubMenu() [source]

Returns whether an item is a sub-menu or not.

SetContextMenu(context_menu) [source]

Assigns a context menu to this item.

Parameters: context_menu – an instance of FlatMenu.

SetDisabledBitmap(bmp) [source]

Sets the menu item disabled bitmap.

Parameters: bmp – an instance of wx.Bitmap.

SetFont(font=None) [source]

Sets the FlatMenuItem font.

Parameters: font – an instance of a valid wx.Font.

SetHelp(helpString) [source]

Sets the menu item help string.

Parameters: helpString (string) – the new menu item help string.

SetHotBitmap(bmp) [source]

Sets the menu item hot bitmap.

Parameters: bmp – an instance of wx.Bitmap.

SetLabel(text) [source]

Sets the label text for this item from the text (excluding the accelerator).

Parameters: text (string) – the new item label (excluding the accelerator).

SetLongHelp(help) [source]

Sets the item long help string (displayed in the parent frame wx.StatusBar).

Parameters: help (string) – the new item long help string.

SetMenu(menu) [source]

Sets the menu item parent menu.

Parameters: menu – an instance of FlatMenu.

SetMenuBar() [source]

Links the current menu item with the main FlatMenuBar.

SetNormalBitmap(bmp) [source]

Sets the menu item normal bitmap.

Parameters: bmp – an instance of wx.Bitmap.

SetRect(rect) [source]

Sets the menu item client rectangle.

Parameters: rect – the menu item client rectangle, an instance of wx.Rect.

SetSubMenu(menu) [source]

Sets the menu item sub-menu.

Parameters: menu – an instance of FlatMenu.

SetText(text) [source]

Sets the text for this menu item (including accelerators).

Parameters: text (string) – the new item label (including the accelerator).

SetTextColour(colour=None) [source]

Sets the FlatMenuItem foreground colour for the menu label.

Parameters: colour – an instance of a valid wx.Colour.

Show(show=True) [source]

Actually shows/hides the menu item.

Parameters: show (bool) – True to show the menu item, False to hide it.

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • infobar
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • flatmenu »
  • FlatMenuItem


FlatMenuItemGroup

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • flatmenu »
  • FlatMenuItemGroup

FlatMenuItemGroup

A class that manages a group of radio menu items.

hierarchy Inheritance Diagram

Inheritance diagram for: FlatMenuItemGroup

Inheritance diagram of FlatMenuItemGroup

Methods Summary

__init__ | Default class constructor.
Add | Adds a new item to the group.
Exist | Checks if an item is in the group.
GetSelectedItem | Returns the selected item.
Remove | Removes a particular item.
SetSelection | Selects a particular item.

API Class API

class FlatMenuItemGroup(object) [source]

A class that manages a group of radio menu items.

__init__() [source]

Default class constructor.

Add(item) [source]

Adds a new item to the group.

Parameters: item – an instance of FlatMenu.

Exist(item) [source]

Checks if an item is in the group.

Parameters: item – an instance of FlatMenu.

GetSelectedItem() [source]

Returns the selected item.

Remove(item) [source]

Removes a particular item.

Parameters: item – an instance of FlatMenu.

SetSelection(item) [source]

Selects a particular item.

Parameters: item – an instance of FlatMenu.

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • infobar
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • flatmenu »
  • FlatMenuItemGroup


FlatToolbarItem

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • flatmenu »
  • FlatToolbarItem

FlatToolbarItem

This class represents a toolbar item.

hierarchy Inheritance Diagram

Inheritance diagram for: FlatToolbarItem

Inheritance diagram of FlatToolbarItem

Methods Summary

__init__ | Default class constructor.
Enable | Enables or disables the tool.
GetBitmap | Returns the tool bitmap.
GetCustomControl | Returns the associated custom control.
GetDisabledBitmap | Returns the tool disabled bitmap.
GetGroup | Returns group id for radio item, or -1 for other item types.
GetId | Gets the tool id.
GetLabel | Returns the tool label.
GetLongHelp | Returns the tool long help string (displayed in the parent frame wx.StatusBar).
GetShortHelp | Returns the tool short help string (displayed in the tool’s tooltip).
IsCheckItem | Returns True if the item is a radio item.
IsChecked | Same as IsSelected. More intuitive for check items though.
IsCustomControl | Returns whether the tool is a custom control or not.
IsEnabled | Returns whether the tool is enabled or not.
IsRadioItem | Returns True if the item is a radio item.
IsRegularItem | Returns whether the tool is a standard tool or not.
IsSelected | Returns whether the tool is selected or checked.
IsSeparator | Returns whether the tool is a separator or not.
Select | Selects or checks a radio or check item.
SetBitmap | Sets the tool bitmap.
SetDisabledBitmap | Sets the tool disabled bitmap.
SetGroup | Sets group id for a radio item, for other items does nothing.
SetLabel | Sets the tool label.
SetLongHelp | Sets the tool long help string (displayed in the parent frame wx.StatusBar).
SetShortHelp | Sets the tool short help string (displayed in the tool’s tooltip).
Toggle | Toggles a check item.

API Class API

class FlatToolbarItem(object) [source]

This class represents a toolbar item.

__init__(controlType=None, id=wx.ID_ANY, label="", disabledBmp=wx.NullBitmap, kind=wx.ITEM_NORMAL, shortHelp="", longHelp="") [source]

Default class constructor.

Parameters:
  • controlType – can be None for a toolbar separator, an instance of wx.Window for a control or an instance of wx.Bitmap for a standard toolbar tool;
  • id (integer) – the toolbar tool id. If set to wx.ID_ANY, a new id is automatically assigned;
  • label (string) – the toolbar tool label;
  • disabledBmp – the bitmap used when the tool is disabled. If the tool is a standard one (i.e., not a control or a separator), and disabledBmp is equal to wx.NullBitmap, the disabled bitmap is automatically generated by greing the normal one;
  • kind (integer) – may be wx.ITEM_NORMAL for a normal button (default), wx.ITEM_CHECK for a checkable tool (such tool stays pressed after it had been toggled) or wx.ITEM_RADIO for a checkable tool which makes part of a radio group of tools each of which is automatically unchecked whenever another button in the group is checked;
  • shortHelp (string) – a string used for the tool’s tooltip;
  • longHelp (string) – this string is shown in the wx.StatusBar (if any) of the parent frame when the mouse pointer is inside the tool.

Enable(enable=True) [source]

Enables or disables the tool.

Parameters: enable (bool) – True to enable the tool, False to disable it.

GetBitmap() [source]

Returns the tool bitmap.

GetCustomControl() [source]

Returns the associated custom control.

GetDisabledBitmap() [source]

Returns the tool disabled bitmap.

GetGroup() [source]

Returns group id for radio item, or -1 for other item types.

GetId() [source]

Gets the tool id.

GetLabel() [source]

Returns the tool label.

GetLongHelp() [source]

Returns the tool long help string (displayed in the parent frame wx.StatusBar).

GetShortHelp() [source]

Returns the tool short help string (displayed in the tool’s tooltip).

IsCheckItem() [source]

Returns True if the item is a radio item.

IsChecked() [source]

Same as IsSelected. More intuitive for check items though.

IsCustomControl() [source]

Returns whether the tool is a custom control or not.

IsEnabled() [source]

Returns whether the tool is enabled or not.

IsRadioItem() [source]

Returns True if the item is a radio item.

IsRegularItem() [source]

Returns whether the tool is a standard tool or not.

IsSelected() [source]

Returns whether the tool is selected or checked.

IsSeparator() [source]

Returns whether the tool is a separator or not.

Select(select=True) [source]

Selects or checks a radio or check item.

Parameters: select (bool) – True to select or check a tool, False to unselect or uncheck it.

SetBitmap(bmp) [source]

Sets the tool bitmap.

Parameters: bmp – the new tool bitmap, a valid wx.Bitmap object.

SetDisabledBitmap(bmp) [source]

Sets the tool disabled bitmap.

Parameters: bmp – the new tool disabled bitmap, a valid wx.Bitmap object.

SetGroup(group) [source]

Sets group id for a radio item, for other items does nothing.

Parameters: group – an instance of FlatMenuItemGroup.

SetLabel(label) [source]

Sets the tool label.

Parameters: label (string) – the new tool string.

SetLongHelp(help) [source]

Sets the tool long help string (displayed in the parent frame wx.StatusBar).

Parameters: help (string) – the new tool long help string.

SetShortHelp(help) [source]

Sets the tool short help string (displayed in the tool’s tooltip).

Parameters: help (string) – the new tool short help string.

Toggle() [source]

Toggles a check item.

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • infobar
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • flatmenu »
  • FlatToolbarItem


FMRenderer

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • flatmenu »
  • FMRenderer

FMRenderer

Base class for the FlatMenu renderers. This class implements the common methods of all the renderers.

hierarchy Inheritance Diagram

Inheritance diagram for: FMRenderer

Inheritance diagram of FMRenderer

subclasses Known Subclasses

  • flatmenu.FMRendererMSOffice2007
  • flatmenu.FMRendererXP

Methods Summary

__init__ | Default class constructor.
ConvertToBitmap | Convert the given image to a bitmap, optionally overlaying an alpha channel to it.
DrawBitmapShadow | Draws a shadow using background bitmap.
DrawButton | Draws a button.
DrawLeftMargin | Draws the menu left margin.
DrawMenu | Draws the menu.
DrawMenuBar | Draws everything for FlatMenuBar.
DrawMenuBarBackground | Draws the menu bar background colour according to the menubar.GetBackgroundColour
DrawMenuBarButton | Draws the highlight on a FlatMenuBar.
DrawMenuButton | Draws the highlight on a FlatMenu
DrawMenuItem | Draws the menu item.
DrawScrollButton | Draws the scroll button
DrawSeparator | Draws a separator inside a FlatMenu.
DrawToolBarBg | Draws the toolbar background
DrawToolbarSeparator | Draws a separator inside the toolbar in FlatMenuBar.
GetColoursAccordingToState | Returns a wx.Colour according to the menu item state.
SetMenuBarHighlightColour | Set the colour to highlight focus on the menu bar.
SetMenuHighlightColour | Set the colour to highlight focus on the menu.

API Class API

class FMRenderer(object) [source]

Base class for the FlatMenu renderers. This class implements the common methods of all the renderers.

__init__() [source]

Default class constructor.

ConvertToBitmap(xpm, alpha=None) [source]

Convert the given image to a bitmap, optionally overlaying an alpha channel to it.

Parameters:
  • xpm – a list of strings formatted as XPM;
  • alpha – a list of alpha values, the same size as the xpm bitmap.

DrawBitmapShadow(dc, rect, where=3) [source]

Draws a shadow using background bitmap.

Parameters:
  • dc – an instance of wx.DC;
  • rect – an instance of wx.Rect, representing the bitmap client rectangle;
  • where (integer) – where to draw the shadow. This can be any combination of the following bits:

    integer parameter settings
    Shadow Settings | Value | Description
    RightShadow | 1 | Right side shadow
    BottomShadow | 2 | Not full bottom shadow
    BottomShadowFull | 4 | Full bottom shadow

DrawButton(dc, rect, state, colour=None) [source]

Draws a button.

Parameters:
  • dc – an instance of wx.DC;

  • rect – an instance of wx.Rect, representing the button client rectangle;

  • state (integer) – the button state;
  • colour – if not None, an instance of wx.Colour to be used to draw the FlatMenuItem background.

DrawLeftMargin(item, dc, menuRect) [source]

Draws the menu left margin.

Parameters:
  • item – an instance of FlatMenuItem;
  • dc – an instance of wx.DC;

  • menuRect – an instance of wx.Rect, representing the menu client rectangle.

DrawMenu(flatmenu, dc) [source]

Draws the menu.

Parameters:
  • flatmenu – the FlatMenu instance we need to paint;
  • dc – an instance of wx.DC.

DrawMenuBar(menubar, dc) [source]

Draws everything for FlatMenuBar.

Parameters:
  • menubar – an instance of FlatMenuBar.
  • dc – an instance of wx.DC.

DrawMenuBarBackground(dc, rect) [source]

Draws the menu bar background colour according to the menubar.GetBackgroundColour

Parameters:
  • dc – an instance of wx.DC;

  • rect – an instance of wx.Rect, representing the menubar client rectangle.

DrawMenuBarButton(dc, rect, state) [source]

Draws the highlight on a FlatMenuBar.

Parameters:
  • dc – an instance of wx.DC;

  • rect – an instance of wx.Rect, representing the button client rectangle;

  • state (integer) – the button state.

DrawMenuButton(dc, rect, state) [source]

Draws the highlight on a FlatMenu

Parameters:
  • dc – an instance of wx.DC;

  • rect – an instance of wx.Rect, representing the button client rectangle;

  • state (integer) – the button state.

DrawMenuItem(item, dc, xCoord, yCoord, imageMarginX, markerMarginX, textX, rightMarginX, selected=False, backgroundImage=None) [source]

Draws the menu item.

Parameters:
  • item – a FlatMenuItem instance;
  • dc – an instance of wx.DC;

  • xCoord (integer) – the current x position where to draw the menu;
  • yCoord (integer) – the current y position where to draw the menu;
  • imageMarginX (integer) – the spacing between the image and the menu border;
  • markerMarginX (integer) – the spacing between the checkbox/radio marker and the menu border;
  • textX (integer) – the menu item label x position;
  • rightMarginX (integer) – the right margin between the text and the menu border;
  • selected (bool) – True if this menu item is currentl hovered by the mouse, False otherwise.
  • backgroundImage – if not None, an instance of wx.Bitmap which will become the background image for this FlatMenu.

DrawScrollButton(dc, rect, state) [source]

Draws the scroll button

Parameters:
  • dc – an instance of wx.DC;

  • rect – an instance of wx.Rect, representing the button client rectangle;

  • state (integer) – the button state.

DrawSeparator(dc, xCoord, yCoord, textX, sepWidth) [source]

Draws a separator inside a FlatMenu.

Parameters:
  • dc – an instance of wx.DC;

  • xCoord (integer) – the current x position where to draw the separator;
  • yCoord (integer) – the current y position where to draw the separator;
  • textX (integer) – the menu item label x position;
  • sepWidth (integer) – the width of the separator, in pixels.

DrawToolBarBg(dc, rect) [source]

Draws the toolbar background

Parameters:
  • dc – an instance of wx.DC;

  • rect – an instance of wx.Rect, representing the toolbar client rectangle.

DrawToolbarSeparator(dc, rect) [source]

Draws a separator inside the toolbar in FlatMenuBar.

Parameters:
  • dc – an instance of wx.DC;

  • rect – an instance of wx.Rect, representing the bitmap client rectangle.

GetColoursAccordingToState(state) [source]

Returns a wx.Colour according to the menu item state.

Parameters: state (integer) – one of the following bits:

integer parameter settings
Item State | Value | Description
ControlPressed | 0 | The item is pressed
ControlFocus | 1 | The item is focused
ControlDisabled | 2 | The item is disabled
ControlNormal | 3 | Normal state

SetMenuBarHighlightColour(colour) [source]

Set the colour to highlight focus on the menu bar.

Parameters: colour – a valid instance of wx.Colour.

SetMenuHighlightColour(colour) [source]

Set the colour to highlight focus on the menu.

Parameters: colour – a valid instance of wx.Colour.

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • infobar
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • flatmenu »
  • FMRenderer


FMRendererMgr

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • flatmenu »
  • FMRendererMgr

FMRendererMgr

This class represents a manager that handles all the renderers defined. Every instance of this class will share the same state, so everyone can instantiate their own and a call to SetTheme anywhere will affect everyone.

hierarchy Inheritance Diagram

Inheritance diagram for: FMRendererMgr

Inheritance diagram of FMRendererMgr

Methods Summary

__init__ | Default class constructor.
AddRenderer | Adds a user defined custom renderer.
GetRenderer | Returns the current theme’s renderer.
SetTheme | Sets the current theme.

API Class API

class FMRendererMgr(object) [source]

This class represents a manager that handles all the renderers defined. Every instance of this class will share the same state, so everyone can instantiate their own and a call to FMRendererMgr.SetTheme() anywhere will affect everyone.

__init__() [source]

Default class constructor.

AddRenderer(renderer) [source]

Adds a user defined custom renderer.

Parameters: renderer – a class derived from FMRenderer.

GetRenderer() [source]

Returns the current theme’s renderer.

SetTheme(theme) [source]

Sets the current theme.

Parameters: theme – an integer specifying the theme to use.

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • infobar
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • flatmenu »
  • FMRendererMgr


FMRendererMSOffice2007

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • flatmenu »
  • FMRendererMSOffice2007

FMRendererMSOffice2007

Windows Office 2007 style.

hierarchy Inheritance Diagram

Inheritance diagram for: FMRendererMSOffice2007

Inheritance diagram of FMRendererMSOffice2007

subclasses Known Subclasses

  • flatmenu.FMRendererVista

supclasses Known Superclasses

  • flatmenu.FMRenderer

Methods Summary

__init__ | Default class constructor.
DrawButton | Draws a button using the Office 2007 theme.
DrawButtonColour | Draws a button using the Office 2007 theme.
DrawLeftMargin | Draws the menu left margin.
DrawMenuBarBackground | Draws the menu bar background according to the active theme.
DrawMenuBarButton | Draws the highlight on a FlatMenuBar.
DrawMenuButton | Draws the highlight on a FlatMenu.
DrawToolBarBg | Draws the toolbar background according to the active theme.
GetTextColourEnable | Returns the colour used for text colour when enabled.

API Class API

class FMRendererMSOffice2007(FMRenderer) [source]

Windows Office 2007 style.

__init__() [source]

Default class constructor.

DrawButton(dc, rect, state, colour=None) [source]

Draws a button using the Office 2007 theme.

Parameters:
  • dc – an instance of wx.DC;
  • rect – an instance of wx.Rect, representing the button client rectangle;
  • state (integer) – the button state;
  • colour – if not None, an instance of wx.Colour to be used to draw the FlatMenuItem background.

DrawButtonColour(dc, rect, state, colour) [source]

Draws a button using the Office 2007 theme.

Parameters:
  • dc – an instance of wx.DC;

  • rect – an instance of wx.Rect, representing the button client rectangle;

  • state (integer) – the button state;
  • colour – a valid wx.Colour instance.

DrawLeftMargin(item, dc, menuRect) [source]

Draws the menu left margin.

Parameters:
  • item – the FlatMenuItem to paint;
  • dc – an instance of wx.DC;

  • menuRect – an instance of wx.Rect, representing the menu client rectangle.

DrawMenuBarBackground(dc, rect) [source]

Draws the menu bar background according to the active theme.

Parameters:
  • dc – an instance of wx.DC;

  • rect – an instance of wx.Rect, representing the menubar client rectangle.

DrawMenuBarButton(dc, rect, state) [source]

Draws the highlight on a FlatMenuBar.

Parameters:
  • dc – an instance of wx.DC;

  • rect – an instance of wx.Rect, representing the button client rectangle;

  • state (integer) – the button state.

DrawMenuButton(dc, rect, state) [source]

Draws the highlight on a FlatMenu.

Parameters:
  • dc – an instance of wx.DC;

  • rect – an instance of wx.Rect, representing the button client rectangle;

  • state (integer) – the button state.

DrawToolBarBg(dc, rect) [source]

Draws the toolbar background according to the active theme.

Parameters:
  • dc – an instance of wx.DC;

  • rect – an instance of wx.Rect, representing the toolbar client rectangle.

GetTextColourEnable() [source]

Returns the colour used for text colour when enabled.

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • infobar
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • flatmenu »
  • FMRendererMSOffice2007


FMRendererVista

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • flatmenu »
  • FMRendererVista

FMRendererVista

Windows Vista-like style.

hierarchy Inheritance Diagram

Inheritance diagram for: FMRendererVista

Inheritance diagram of FMRendererVista

supclasses Known Superclasses

  • flatmenu.FMRendererMSOffice2007

Methods Summary

__init__ | Default class constructor.
DrawButtonColour | Draws a button using the Vista theme.

API Class API

class FMRendererVista(FMRendererMSOffice2007) [source]

Windows Vista-like style.

__init__() [source]

Default class constructor.

DrawButtonColour(dc, rect, state, colour) [source]

Draws a button using the Vista theme.

Parameters:
  • dc – an instance of wx.DC;
  • rect – the an instance of wx.Rect, representing the button client rectangle;
  • state (integer) – the button state;
  • colour – a valid wx.Colour instance.

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • infobar
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • flatmenu »
  • FMRendererVista


FMRendererXP

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • flatmenu »
  • FMRendererXP

FMRendererXP

Xp-Style renderer.

hierarchy Inheritance Diagram

Inheritance diagram for: FMRendererXP

Inheritance diagram of FMRendererXP

supclasses Known Superclasses

  • flatmenu.FMRenderer

Methods Summary

__init__ | Default class constructor.
DrawLeftMargin | Draws the menu left margin.
DrawMenuBarBackground | Draws the menu bar background according to the active theme.
DrawToolBarBg | Draws the toolbar background according to the active theme.
GetTextColourEnable | Returns the colour used for text colour when enabled.

API Class API

class FMRendererXP(FMRenderer) [source]

Xp-Style renderer.

__init__() [source]

Default class constructor.

DrawLeftMargin(item, dc, menuRect) [source]

Draws the menu left margin.

Parameters:
  • item – the FlatMenuItem to paint;
  • dc – an instance of wx.DC;
  • menuRect – an instance of wx.Rect, representing the menu client rectangle.

DrawMenuBarBackground(dc, rect) [source]

Draws the menu bar background according to the active theme.

Parameters:
  • dc – an instance of wx.DC;

  • rect – an instance of wx.Rect, representing the menubar client rectangle.

DrawToolBarBg(dc, rect) [source]

Draws the toolbar background according to the active theme.

Parameters:
  • dc – an instance of wx.DC;

  • rect – an instance of wx.Rect, representing the toolbar client rectangle.

GetTextColourEnable() [source]

Returns the colour used for text colour when enabled.

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • infobar
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • flatmenu »
  • FMRendererXP


FocusHandler

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • flatmenu »
  • FocusHandler

FocusHandler

A focus event handler.

hierarchy Inheritance Diagram

Inheritance diagram for: FocusHandler

Inheritance diagram of FocusHandler

Methods Summary

__init__ | Default class constructor.
OnKeyDown | Handles the wx.EVT_KEY_DOWN event for FocusHandler.
OnKillFocus | Handles the wx.EVT_KILL_FOCUS event for FocusHandler.
SetMenu | Sets the listener menu.

API Class API

class FocusHandler(wx.EvtHandler) [source]

A focus event handler.

__init__(menu) [source]

Default class constructor.

Parameters: menu – an instance of FlatMenu for which we want to redirect focus inputs.

OnKeyDown(event) [source]

Handles the wx.EVT_KEY_DOWN event for FocusHandler.

Parameters: event – a wx.KeyEvent event to be processed.

OnKillFocus(event) [source]

Handles the wx.EVT_KILL_FOCUS event for FocusHandler.

Parameters: event – a wx.FocusEvent event to be processed.

SetMenu(menu) [source]

Sets the listener menu.

Parameters: menu – an instance of FlatMenu.

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • infobar
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • flatmenu »
  • FocusHandler


mcPopupWindow

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • flatmenu »
  • mcPopupWindow

mcPopupWindow

Since Max OS does not support wx.PopupWindow, this is an alternative.

hierarchy Inheritance Diagram

Inheritance diagram for: mcPopupWindow

Inheritance diagram of mcPopupWindow

Methods Summary

__init__ | Default class constructor.
OnLeaveWindow | Handles the wx.EVT_LEAVE_WINDOW event for mcPopupWindow.

API Class API

class mcPopupWindow(wx.MiniFrame) [source]

Since Max OS does not support wx.PopupWindow, this is an alternative.

__init__(parent) [source]

Default class constructor.

Parameters: parent – the mcPopupWindow parent window.

OnLeaveWindow(event) [source]

Handles the wx.EVT_LEAVE_WINDOW event for mcPopupWindow.

Parameters: event – a wx.MouseEvent event to be processed.

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • infobar
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • flatmenu »
  • mcPopupWindow


MenuEntryInfo

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • flatmenu »
  • MenuEntryInfo

MenuEntryInfo

Internal class which holds information about a menu.

hierarchy Inheritance Diagram

Inheritance diagram for: MenuEntryInfo

Inheritance diagram of MenuEntryInfo

Methods Summary

__init__ | Default class constructor.
GetCmdId | Returns the associated menu accelerator identifier.
GetMenu | Returns the associated menu.
GetRect | Returns the associated menu client rectangle.
GetSelectedTextBitmap | Returns the associated selected menu bitmap.
GetState | Returns the associated menu state.
GetTextBitmap | Returns the associated menu bitmap.
GetTitle | Returns the associated menu title.
SetRect | Sets the associated menu client rectangle.
SetSelectedTextBitmap | Sets the associated selected menu bitmap.
SetState | Sets the associated menu state.
SetTextBitmap | Sets the associated menu bitmap.

API Class API

class MenuEntryInfo(object) [source]

Internal class which holds information about a menu.

__init__(titleOrMenu="", menu=None, state=ControlNormal, cmd=wx.ID_ANY) [source]

Default class constructor.

Used internally. Do not call it in your code!

Parameters:
  • titleOrMenu – if it is a string, it represents the new menu label, otherwise it is another instance of MenuEntryInfo from which the attributes are copied;
  • menu – the associated FlatMenu object;
  • state (integer) – the menu item state. This can be one of the following:

    integer parameter settings
    Item State | Value | Description
    ControlPressed | 0 | The item is pressed
    ControlFocus | 1 | The item is focused
    ControlDisabled | 2 | The item is disabled
    ControlNormal | 3 | Normal state
  • cmd (integer) – the menu accelerator identifier.

GetCmdId() [source]

Returns the associated menu accelerator identifier.

GetMenu() [source]

Returns the associated menu.

GetRect() [source]

Returns the associated menu client rectangle.

GetSelectedTextBitmap() [source]

Returns the associated selected menu bitmap.

GetState() [source]

Returns the associated menu state.

See also

SetState for a list of valid menu states.

GetTextBitmap() [source]

Returns the associated menu bitmap.

GetTitle() [source]

Returns the associated menu title.

SetRect(rect) [source]

Sets the associated menu client rectangle.

Parameters: rect – an instance of wx.Rect, representing the menu client rectangle.

SetSelectedTextBitmap(bmp) [source]

Sets the associated selected menu bitmap.

Parameters: bmp – a valid wx.Bitmap object.

SetState(state) [source]

Sets the associated menu state.

Parameters: state (integer) – the menu item state. This can be one of the following:

integer parameter settings
Item State | Value | Description
ControlPressed | 0 | The item is pressed
ControlFocus | 1 | The item is focused
ControlDisabled | 2 | The item is disabled
ControlNormal | 3 | Normal state

SetTextBitmap(bmp) [source]

Sets the associated menu bitmap.

Parameters: bmp – a valid wx.Bitmap object.

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • infobar
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • flatmenu »
  • MenuEntryInfo


MenuKbdRedirector

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • flatmenu »
  • MenuKbdRedirector

MenuKbdRedirector

A keyboard event handler.

hierarchy Inheritance Diagram

Inheritance diagram for: MenuKbdRedirector

Inheritance diagram of MenuKbdRedirector

Methods Summary

__init__ | Default class constructor.
ProcessEvent | Processes the inout event.
SetMenu | Sets the listener menu.

API Class API

class MenuKbdRedirector(wx.EvtHandler) [source]

A keyboard event handler.

__init__(menu, oldHandler) [source]

Default class constructor.

Parameters:
  • menu – an instance of FlatMenu for which we want to redirect keyboard inputs;
  • oldHandler – a previous (if any) wx.EvtHandler associated with the menu.

ProcessEvent(event) [source]

Processes the inout event.

Parameters: event – any kind of keyboard-generated events.

SetMenu(menu) [source]

Sets the listener menu.

Parameters: menu – an instance of FlatMenu.

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • infobar
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • flatmenu »
  • MenuKbdRedirector


ShadowPopupWindow

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • flatmenu »
  • ShadowPopupWindow

ShadowPopupWindow

Base class for generic FlatMenu derived from wx.PopupWindow.

hierarchy Inheritance Diagram

Inheritance diagram for: ShadowPopupWindow

Inheritance diagram of ShadowPopupWindow

subclasses Known Subclasses

  • flatmenu.FlatMenuBase

Methods Summary

__init__ Default class constructor.

API Class API

class ShadowPopupWindow(wx.PopupWindow) [source]

Base class for generic FlatMenu derived from wx.PopupWindow.

__init__(parent=None) [source]

Default class constructor.

Parameters: parent – the ShadowPopupWindow parent (tipically your main frame).

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • infobar
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • flatmenu »
  • ShadowPopupWindow


StatusBarTimer

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • flatmenu »
  • StatusBarTimer

StatusBarTimer

Timer used for deleting wx.StatusBar long help after _DELAY seconds.

hierarchy Inheritance Diagram

Inheritance diagram for: StatusBarTimer

Inheritance diagram of StatusBarTimer

Methods Summary

__init__ | Default class constructor.
Notify | The timer has expired.

API Class API

class StatusBarTimer(wx.Timer) [source]

Timer used for deleting wx.StatusBar long help after _DELAY seconds.

__init__(owner) [source]

Default class constructor. For internal use: do not call it in your code!

Parameters: owner – the wx.Timer owner (FlatMenuBar).

Notify() [source]

The timer has expired.

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • infobar
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • flatmenu »
  • StatusBarTimer


ToolBarItem

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • flatmenu »
  • ToolBarItem

ToolBarItem

A simple class that holds information about a toolbar item.

hierarchy Inheritance Diagram

Inheritance diagram for: ToolBarItem

Inheritance diagram of ToolBarItem

Methods Summary

__init__ Default class constructor.

API Class API

class ToolBarItem(object) [source]

A simple class that holds information about a toolbar item.

__init__(tbItem, rect, state) [source]

Default class constructor.

Parameters:
  • tbItem – an instance of FlatToolbarItem;
  • rect – the client rectangle for the toolbar item, an instance of wx.Rect;
  • state (integer) – the toolbar item state.

See also

MenuEntryInfo.SetState() for a list of valid item states.

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • infobar
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • flatmenu »
  • ToolBarItem


SVN Revision 68352 For flatmenu

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • flatmenu »
  • SVN Revision 68352 For flatmenu

svn SVN Revision 68352 For flatmenu

This file contains the SVN revision history for flatmenu, at revision 68352.

Available information include commit date, the name of the committer, the file size, the SVN log messages and a diff from the previous version (if available).

File Information

  • Commit Date: 10-Nov-2009 18:39:07 UTC
  • Committer: AG
  • File Size: 226141 byte(s)

Log Messages

The following log message was entered by the committer:

FlatMenu: added a pure-Python implementation of wx.FileHistory to handle MRU file list in FlatMenu. Added a menu in the demo to show how to use it (it’s the same as the wxPython demo for wx.FileHistory).

Diff To Previous Version (65585)

Version SVN diff:

--- wxPython/3rdParty/AGW/agw/flatmenu.py   2010/09/21 21:09:52     65585
+++ wxPython/3rdParty/AGW/agw/flatmenu.py   2011/07/24 11:45:28     68352
@@ -2,7 +2,7 @@
# FLATMENU wxPython IMPLEMENTATION
#
# Andrea Gavana, @ 03 Nov 2006
-# Latest Revision: 21 Sep 2010, 23.00 GMT
+# Latest Revision: 23 Jul 2011, 15.00 GMT
#
# TODO List
#
@@ -70,6 +70,7 @@
- Multiple columns menu window;
- Tooltips for menus and toolbar items on a `wx.StatusBar` (if present);
- Transparency (alpha channel) for menu windows (for platforms supporting it);
+- FileHistory support through a pure-Python `wx.FileHistory` implementation;
- First attempt in adding controls to FlatToolbar;
- Added a MiniBar (thanks to Vladiuz);
- Added `wx.ToolBar` methods AddCheckTool/AddRadioTool (thanks to Vladiuz).
@@ -120,16 +121,17 @@

FlatMenu is distributed under the wxPython license.

-Latest Revision: Andrea Gavana @ 21 Sep 2010, 23.00 GMT
+Latest Revision: Andrea Gavana @ 23 Jul 2011, 15.00 GMT

-Version 0.9.6
+Version 1.0

"""

__docformat__ = "epytext"
-__version__ = "0.9.6"
+__version__ = "1.0"

import wx
+import os
import math
import cStringIO

@@ -215,6 +217,8 @@
""" Used internally. """
EVT_FLAT_MENU_SELECTED = wx.PyEventBinder(wxEVT_FLAT_MENU_SELECTED, 2)
""" Fires the wx.EVT_MENU event for `FlatMenu`. """
+EVT_FLAT_MENU_RANGE = wx.PyEventBinder(wxEVT_FLAT_MENU_SELECTED, 2)
+""" Fires the wx.EVT_MENU event for a series of `FlatMenu`. """
EVT_FLAT_MENU_ITEM_MOUSE_OUT = wx.PyEventBinder(wxEVT_FLAT_MENU_ITEM_MOUSE_OUT, 1)
""" Fires an event when the mouse leaves a `FlatMenuItem`. """
EVT_FLAT_MENU_ITEM_MOUSE_OVER = wx.PyEventBinder(wxEVT_FLAT_MENU_ITEM_MOUSE_OVER, 1)
@@ -1764,6 +1768,316 @@
return wx.BLACK

+# ----------------------------------------------------------------------------
+# File history (a.k.a. MRU, most recently used, files list)
+# ----------------------------------------------------------------------------
+
+def GetMRUEntryLabel(n, path):
+    """
+    Returns the string used for the MRU list items in the menu.
+
+    :param `n`: the index of the file name in the MRU list;
+    :param `path`: the full path of the file name.
+
+    :note: The index `n` is 0-based, as usual, but the strings start from 1.
+    """
+
+    # we need to quote '&' characters which are used for mnemonics
+    pathInMenu = path.replace("&", "&&")
+    return "&%d %s"%(n + 1, pathInMenu)
+
+
+# ----------------------------------------------------------------------------
+# File history management
+# ----------------------------------------------------------------------------
+
+class FileHistory(object):
+    """
+    The L{FileHistory} encapsulates a user interface convenience, the list of most
+    recently visited files as shown on a menu (usually the File menu).
+
+    L{FileHistory} can manage one or more file menus. More than one menu may be
+    required in an MDI application, where the file history should appear on each MDI
+    child menu as well as the MDI parent frame.
+    """
+
+    def __init__(self, maxFiles=9, idBase=wx.ID_FILE1):
+        """
+        Default class constructor.
+
+        :param `maxFiles`: the maximum number of files that should be stored and displayed;
+        :param `idBase`: defaults to ``wx.ID_FILE1`` and represents the id given to the first
+         history menu item.
+
+        :note: Since menu items can't share the same ID you should change `idBase` to one of
+         your own defined IDs when using more than one L{FileHistory} in your application.
+         """
+
+        # The ID of the first history menu item (Doesn't have to be wxID_FILE1)
+        self._idBase = idBase
+
+        # Last n files
+        self._fileHistory = []
+
+        # Menus to maintain (may need several for an MDI app)
+        self._fileMenus = []
+
+        # Max files to maintain
+        self._fileMaxFiles = maxFiles
+
+
+    def GetMaxFiles(self):
+        """ Returns the maximum number of files that can be stored. """
+
+        return self._fileMaxFiles
+
+
+    # Accessors
+    def GetHistoryFile(self, index):
+        """
+        Returns the file at this index (zero-based).
+
+        :param `index`: the index at which the file is stored in the file list (zero-based).
+        """
+
+        return self._fileHistory[index]
+
+
+    def GetCount(self):
+        """ Returns the number of files currently stored in the file history. """
+
+        return len(self._fileHistory)
+
+
+    def GetMenus(self):
+        """
+        Returns the list of menus that are managed by this file history object.
+
+        :see: L{UseMenu}.
+        """
+
+        return self._fileMenus
+
+
+    # Set/get base id
+    def SetBaseId(self, baseId):
+        """
+        Sets the base identifier for the range used for appending items.
+
+        :param `baseId`: the base identifier for the range used for appending items.
+        """
+
+        self._idBase = baseId
+
+
+    def GetBaseId(self):
+        """ Returns the base identifier for the range used for appending items. """
+
+        return self._idBase
+
+
+    def GetNoHistoryFiles(self):
+        """ Returns the number of files currently stored in the file history. """
+
+        return self.GetCount()
+
+
+    def AddFileToHistory(self, fnNew):
+        """
+        Adds a file to the file history list, if the object has a pointer to an
+        appropriate file menu.
+
+        :param `fnNew`: the file name to add to the history list.
+        """
+
+        # check if we don't already have this file
+        numFiles = len(self._fileHistory)
+
+        for index, fileH in enumerate(self._fileHistory):
+            if fnNew == fileH:
+                # we do have it, move it to the top of the history
+                self.RemoveFileFromHistory(index)
+                numFiles -= 1
+                break
+
+        # if we already have a full history, delete the one at the end
+        if numFiles == self._fileMaxFiles:
+            self.RemoveFileFromHistory(numFiles-1)
+
+        # add a new menu item to all file menus (they will be updated below)
+        for menu in self._fileMenus:
+            if numFiles == 0 and menu.GetMenuItemCount() > 0:
+                menu.AppendSeparator()
+
+            # label doesn't matter, it will be set below anyhow, but it can't
+            # be empty (this is supposed to indicate a stock item)
+            menu.Append(self._idBase + numFiles, " ")
+
+        # insert the new file in the beginning of the file history
+        self._fileHistory.insert(0, fnNew)
+        numFiles += 1
+
+        # update the labels in all menus
+        for index in xrange(numFiles):
+
+            # if in same directory just show the filename otherwise the full path
+            fnOld = self._fileHistory[index]
+            oldPath, newPath = os.path.split(fnOld)[0], os.path.split(fnNew)[0]
+
+            if oldPath == newPath:
+                pathInMenu = os.path.split(fnOld)[1]
+
+            else:
+                # file in different directory
+                # absolute path could also set relative path
+                pathInMenu = self._fileHistory[index]
+
+            for menu in self._fileMenus:
+                menu.SetLabel(self._idBase + index, GetMRUEntryLabel(index, pathInMenu))
+
+
+    def RemoveFileFromHistory(self, index):
+        """
+        Removes the specified file from the history.
+
+        :param `index`: the zero-based index indicating the file name position in
+         the file list.
+        """
+
+        numFiles = len(self._fileHistory)
+        if index >= numFiles:
+            raise Exception("Invalid index in RemoveFileFromHistory: %d (only %d files)"%(index, numFiles))
+
+        # delete the element from the array
+        self._fileHistory.pop(index)
+        numFiles -= 1
+
+        for menu in self._fileMenus:
+            # shift filenames up
+            for j in xrange(numFiles):
+                menu.SetLabel(self._idBase + j, GetMRUEntryLabel(j, self._fileHistory[j]))
+
+            # delete the last menu item which is unused now
+            lastItemId = self._idBase + numFiles
+            if menu.FindItem(lastItemId):
+                menu.Delete(lastItemId)
+
+            if not self._fileHistory:
+                lastMenuItem = menu.GetMenuItems()[-1]
+                if lastMenuItem.IsSeparator():
+                    menu.Delete(lastMenuItem)
+
+                #else: menu is empty somehow
+
+
+    def UseMenu(self, menu):
+        """
+        Adds this menu to the list of those menus that are managed by this file history
+        object.
+
+        :param `menu`: an instance of L{FlatMenu}.
+
+        :see: L{AddFilesToMenu} for initializing the menu with filenames that are already
+         in the history when this function is called, as this is not done automatically.
+        """
+
+        if menu not in self._fileMenus:
+            self._fileMenus.append(menu)
+
+
+    def RemoveMenu(self, menu):
+        """
+        Removes this menu from the list of those managed by this object.
+
+        :param `menu`: an instance of L{FlatMenu}.
+        """
+
+        self._fileMenus.remove(menu)
+
+
+    def Load(self, config):
+        """
+        Loads the file history from the given `config` object.
+
+        :param `config`: an instance of `wx.Config`.
+
+        :note: This function should be called explicitly by the application.
+
+        :see: L{Save}.
+        """
+
+        self._fileHistory = []
+        buffer = "file%d"
+        count = 1
+
+        while 1:
+            historyFile = config.Read(buffer%count)
+            if not historyFile or len(self._fileHistory) >= self._fileMaxFiles:
+                break
+
+            self._fileHistory.append(historyFile)
+            count += 1
+
+        self.AddFilesToMenu()
+
+
+    def Save(self, config):
+        """
+        Saves the file history to the given `config` object.
+
+        :param `config`: an instance of `wx.Config`.
+
+        :note: This function should be called explicitly by the application.
+
+        :see: L{Load}.
+        """
+
+        buffer = "file%d"
+
+        for index in xrange(self._fileMaxFiles):
+
+            if index < len(self._fileHistory):
+                config.Write(buffer%(index+1), self._fileHistory[i])
+            else:
+                config.Write(buffer%(index+1), "")
+
+
+    def AddFilesToMenu(self, menu=None):
+        """
+        Appends the files in the history list, to all menus managed by the file history object
+        if `menu` is ``None``. Otherwise it calls the auxiliary method L{AddFilesToMenu2}.
+
+        :param `menu`: if not ``None``, an instance of L{FlatMenu}.
+        """
+
+        if not self._fileHistory:
+            return
+
+        if menu is not None:
+            self.AddFilesToMenu2(menu)
+            return
+
+        for menu in self._fileMenus:
+            self.AddFilesToMenu2(menu)
+
+
+    def AddFilesToMenu2(self, menu):
+        """
+        Appends the files in the history list, to the given menu only.
+
+        :param `menu`: an instance of L{FlatMenu}.
+        """
+
+        if not self._fileHistory:
+            return
+
+        if menu.GetMenuItemCount():
+            menu.AppendSeparator()
+
+        for index in xrange(len(self._fileHistory)):
+            menu.Append(self._idBase + index, GetMRUEntryLabel(index, self._fileHistory[i]))
+
+
# ---------------------------------------------------------------------------- #
# Class FlatMenuEvent
# ---------------------------------------------------------------------------- #
@@ -4172,6 +4486,7 @@
self._shortHelp = shortHelp
self._longHelp = longHelp

+
def GetLabel(self):
""" Returns the tool label. """

@@ -4728,7 +5043,7 @@

:param `text`: the new item label (excluding the accelerator).
"""
-
+
if text:

indx = text.find("\t")
@@ -6144,6 +6459,8 @@

return self._RemoveById(item)

+    Delete = Remove
+

def _DestroyById(self, id):
""" Used internally. """
@@ -6321,6 +6638,36 @@
return None

+    def SetLabel(self, itemId, label):
+        """
+        Sets the label of a L{FlatMenuItem}.
+
+        :param `id`: The menu item identifier;
+        :param `label`: The menu item label to set.
+
+        :see: L{GetLabel}.
+        """
+
+        item = self.FindItem(itemId)
+        item.SetLabel(label)
+        item.SetText(label)
+
+        self.ResizeMenu()
+
+
+    def GetLabel(self, itemId):
+        """
+        Returns the label of a L{FlatMenuItem}.
+
+        :param `id`: The menu item identifier;
+
+        :see: L{SetLabel}.
+        """
+
+        item = self.FindItem(itemId)
+        return item.GetText()
+
+
def FindMenuItemPos(self, itemId, menu=None):
"""
Finds an item and its position inside the menu based on its id.
@@ -6376,6 +6723,11 @@
return table

+    def GetMenuItemCount(self):
+
+        return len(self._itemsArr)
+
+
def GetAccelArray(self):
""" Returns an array filled with the accelerator entries for the menu. """

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • flatmenu »
  • SVN Revision 68352 For flatmenu


SVN Revision 68881 For flatmenu

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • flatmenu »
  • SVN Revision 68881 For flatmenu

svn SVN Revision 68881 For flatmenu

This file contains the SVN revision history for flatmenu, at revision 68881.

Available information include commit date, the name of the committer, the file size, the SVN log messages and a diff from the previous version (if available).

File Information

  • Commit Date: 20-Oct-2008 20:05:15 UTC
  • Committer: AG
  • File Size: 230420 byte(s)

Log Messages

The following log message was entered by the committer:

  • AGW: General overhaul of the documentation, much improved. All the widgets have their own sample usage in the docs as well;

  • FlatNotebook: Added the FNB_NAV_BUTTONS_WHEN_NEEDED style, which hides the navigation left/right arrows if all tabs fit;

  • RibbonBar: - Added the EVT_RIBBONBAR_TAB_LEFT_DCLICK event, which generates a special event

    when a ribbon bar tab is double-clicked;

    • Added support for toggle buttons;
    • Improved support for ribbon panel sizers: panels with sizers should now automatically minimise at small sizes, and behave properly when popping up from a minimised state;
    • Added tooltips via SetToolTip for those buttons which have the help_string attribute set.

  • XLSGrid: a new widget was added to AGW, termed XLSGrid. It’s based on wx.grid.Grid and can be used to faithfully reproduce the appearance of a Microsoft Excel spreadsheets.

Diff To Previous Version (68419)

Version SVN diff:

--- wxPython/3rdParty/AGW/agw/flatmenu.py   2011/07/25 20:31:17     68419
+++ wxPython/3rdParty/AGW/agw/flatmenu.py   2011/08/25 16:40:17     68881
@@ -2,7 +2,7 @@
# FLATMENU wxPython IMPLEMENTATION
#
# Andrea Gavana, @ 03 Nov 2006
-# Latest Revision: 23 Jul 2011, 15.00 GMT
+# Latest Revision: 17 Aug 2011, 15.00 GMT
#
# TODO List
#
@@ -23,17 +23,17 @@
# --------------------------------------------------------------------------------- #

"""
-FlatMenu is a generic menu implementation.
+L{FlatMenu} is a generic menu implementation.

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

-FlatMenu, like the name implies, it is a generic menu implementation.
+L{FlatMenu}, like the name implies, it is a generic menu implementation.
I tried to provide a full functionality for menus, menubar and toolbar.

-FlatMenu supports the following features:
+L{FlatMenu} supports the following features:

- Fires all the events (UI & Cmd);
- Check items;
@@ -66,26 +66,89 @@
- 4 different colour schemes for the menu bar (more can easily added);
- Scrolling is available if the menu height is greater than the screen height;
- Context menus for menu items;
-- Show/hide the drop down arrow which allows the customization of FlatMenu;
+- Show/hide the drop down arrow which allows the customization of L{FlatMenu};
- Multiple columns menu window;
- Tooltips for menus and toolbar items on a `wx.StatusBar` (if present);
- Transparency (alpha channel) for menu windows (for platforms supporting it);
- FileHistory support through a pure-Python `wx.FileHistory` implementation;
-- Possibility to set a background bitmap for a `FlatMenu`;
+- Possibility to set a background bitmap for a L{FlatMenu};
- First attempt in adding controls to FlatToolbar;
- Added a MiniBar (thanks to Vladiuz);
- Added `wx.ToolBar` methods AddCheckTool/AddRadioTool (thanks to Vladiuz).

+Usage
+=====
+
+Usage example::
+
+    import wx
+    import wx.lib.agw.flatmenu as FM
+
+    class MyFrame(wx.Frame):
+
+        def __init__(self, parent):
+
+            wx.Frame.__init__(self, parent, -1, "FlatMenu Demo")
+
+            self.CreateMenu()
+
+            panel = wx.Panel(self, -1)
+            btn = wx.Button(panel, -1, "Hello", (15, 12), (100, 120))
+
+            main_sizer = wx.BoxSizer(wx.VERTICAL)
+            main_sizer.Add(self.menubar, 0, wx.EXPAND)
+            main_sizer.Add(panel, 1, wx.EXPAND)
+
+            self.SetSizer(main_sizer)
+            main_sizer.Layout()
+
+
+        def CreateMenu(self):
+
+            self.menubar = FM.FlatMenuBar(self, -1)
+
+            f_menu = FM.FlatMenu()
+            e_menu = FM.FlatMenu()
+            v_menu = FM.FlatMenu()
+            t_menu = FM.FlatMenu()
+            w_menu = FM.FlatMenu()
+
+            # Append the menu items to the menus
+            f_menu.Append(-1, "Simple\tCtrl+N", "Text", None)
+            e_menu.Append(-1, "FlatMenu", "Text", None)
+            v_menu.Append(-1, "Example", "Text", None)
+            t_menu.Append(-1, "Hello", "Text", None)
+            w_menu.Append(-1, "World", "Text", None)
+
+            # Append menus to the menubar
+            self.menubar.Append(f_menu, "&File")
+            self.menubar.Append(e_menu, "&Edit")
+            self.menubar.Append(v_menu, "&View")
+            self.menubar.Append(t_menu, "&Options")
+            self.menubar.Append(w_menu, "&Help")
+
+
+    # our normal wxApp-derived class, as usual
+
+    app = wx.PySimpleApp()
+
+    frame = MyFrame(None)
+    app.SetTopWindow(frame)
+    frame.Show()
+
+    app.MainLoop()
+
+
+
Supported Platforms
===================

-FlatMenu v0.8 has been tested on the following platforms:
-  * Windows (Windows XP);
-  * Linux Ubuntu (Dapper 6.06)
-v0.9.* has been tested on
+L{FlatMenu} has been tested on the following platforms:
* Windows (Windows XP, Vista);
+  * Linux Ubuntu (Dapper 6.06)

+

Window Styles
=============
@@ -111,18 +174,18 @@
Event Name                        Description
================================= ==================================================
``EVT_FLAT_MENU_DISMISSED``       Used internally.
-``EVT_FLAT_MENU_ITEM_MOUSE_OUT``  Fires an event when the mouse leaves a `FlatMenuItem`.
-``EVT_FLAT_MENU_ITEM_MOUSE_OVER`` Fires an event when the mouse enters a `FlatMenuItem`.
-``EVT_FLAT_MENU_SELECTED``        Fires the `wx.EVT_MENU` event for `FlatMenu`.
+``EVT_FLAT_MENU_ITEM_MOUSE_OUT``  Fires an event when the mouse leaves a L{FlatMenuItem}.
+``EVT_FLAT_MENU_ITEM_MOUSE_OVER`` Fires an event when the mouse enters a L{FlatMenuItem}.
+``EVT_FLAT_MENU_SELECTED``        Fires the `wx.EVT_MENU` event for L{FlatMenu}.
================================= ==================================================

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

-FlatMenu is distributed under the wxPython license.
+L{FlatMenu} is distributed under the wxPython license.

-Latest Revision: Andrea Gavana @ 23 Jul 2011, 15.00 GMT
+Latest Revision: Andrea Gavana @ 17 Aug 2011, 15.00 GMT

Version 1.0

@@ -217,13 +280,13 @@
EVT_FLAT_MENU_DISMISSED = wx.PyEventBinder(wxEVT_FLAT_MENU_DISMISSED, 1)
""" Used internally. """
EVT_FLAT_MENU_SELECTED = wx.PyEventBinder(wxEVT_FLAT_MENU_SELECTED, 2)
-""" Fires the wx.EVT_MENU event for `FlatMenu`. """
+""" Fires the wx.EVT_MENU event for L{FlatMenu}. """
EVT_FLAT_MENU_RANGE = wx.PyEventBinder(wxEVT_FLAT_MENU_SELECTED, 2)
-""" Fires the wx.EVT_MENU event for a series of `FlatMenu`. """
+""" Fires the wx.EVT_MENU event for a series of L{FlatMenu}. """
EVT_FLAT_MENU_ITEM_MOUSE_OUT = wx.PyEventBinder(wxEVT_FLAT_MENU_ITEM_MOUSE_OUT, 1)
-""" Fires an event when the mouse leaves a `FlatMenuItem`. """
+""" Fires an event when the mouse leaves a L{FlatMenuItem}. """
EVT_FLAT_MENU_ITEM_MOUSE_OVER = wx.PyEventBinder(wxEVT_FLAT_MENU_ITEM_MOUSE_OVER, 1)
-""" Fires an event when the mouse enters a `FlatMenuItem`. """
+""" Fires an event when the mouse enters a L{FlatMenuItem}. """

def GetAccelIndex(label):
@@ -676,7 +739,7 @@
"""
Draws the menu item.

-        :param `item`: `FlatMenuItem` instance;
+        :param `item`: a L{FlatMenuItem} instance;
:param `dc`: an instance of `wx.DC`;
:param `xCoord`: the current x position where to draw the menu;
:param `yCoord`: the current y position where to draw the menu;
@@ -792,6 +855,7 @@
enabledTxtColour = colourutils.BestLabelColour(self.menuFocusFaceColour, bw=True)
else:
enabledTxtColour = colourutils.BestLabelColour(self.menuFaceColour, bw=True)
+
disabledTxtColour = self.itemTextColourDisabled
textColour = (item.IsEnabled() and [enabledTxtColour] or [disabledTxtColour])[0]

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • flatmenu »
  • SVN Revision 68881 For flatmenu


SVN Revision 70699 For flatmenu

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • flatmenu »
  • SVN Revision 70699 For flatmenu

svn SVN Revision 70699 For flatmenu

This file contains the SVN revision history for flatmenu, at revision 70699.

Available information include commit date, the name of the committer, the file size, the SVN log messages and a diff from the previous version (if available).

File Information

  • Commit Date: 17-Oct-2008 20:51:43 UTC
  • Committer: AG
  • File Size: 230476 byte(s)

Log Messages

The following log message was entered by the committer:

FlatMenu: internationalize the various hard-coded strings.

Diff To Previous Version (68881)

Version SVN diff:

--- wxPython/3rdParty/AGW/agw/flatmenu.py   2011/08/25 16:40:17     68881
+++ wxPython/3rdParty/AGW/agw/flatmenu.py   2012/02/26 16:10:53     70699
@@ -2,7 +2,7 @@
# FLATMENU wxPython IMPLEMENTATION
#
# Andrea Gavana, @ 03 Nov 2006
-# Latest Revision: 17 Aug 2011, 15.00 GMT
+# Latest Revision: 26 Feb 2012, 15.00 GMT
#
# TODO List
#
@@ -185,7 +185,7 @@

L{FlatMenu} is distributed under the wxPython license.

-Latest Revision: Andrea Gavana @ 17 Aug 2011, 15.00 GMT
+Latest Revision: Andrea Gavana @ 26 Feb 2012, 15.00 GMT

Version 1.0

@@ -224,6 +224,9 @@
_libimported = None
_DELAY = 5000

+# Define a translation string
+_ = wx.GetTranslation
+
if wx.Platform == "__WXMSW__":
osVersion = wx.GetOsVersion()
# Shadows behind menus are supported only in XP
@@ -3555,7 +3558,7 @@
if self._showCustomize:
if invT + invM > 0:
self._moreMenu.AppendSeparator()
-            item = FlatMenuItem(self._moreMenu, self._popupDlgCmdId, "Customize ...")
+            item = FlatMenuItem(self._moreMenu, self._popupDlgCmdId, _(u"Customize..."))
self._moreMenu.AppendItem(item)

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • flatmenu »
  • SVN Revision 70699 For flatmenu


SVN Revision 70837 For flatmenu

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • flatmenu »
  • SVN Revision 70837 For flatmenu

svn SVN Revision 70837 For flatmenu

This file contains the SVN revision history for flatmenu, at revision 70837.

Available information include commit date, the name of the committer, the file size, the SVN log messages and a diff from the previous version (if available).

File Information

  • Commit Date: 17-Oct-2008 19:15:31 UTC
  • Committer: AG
  • File Size: 236660 byte(s)

Log Messages

The following log message was entered by the committer:

FlatMenu: improve overall docstrings

Diff To Previous Version (70699)

Version SVN diff:

--- wxPython/3rdParty/AGW/agw/flatmenu.py   2012/02/26 16:10:53     70699
+++ wxPython/3rdParty/AGW/agw/flatmenu.py   2012/03/07 22:03:27     70837
@@ -2,7 +2,7 @@
# FLATMENU wxPython IMPLEMENTATION
#
# Andrea Gavana, @ 03 Nov 2006
-# Latest Revision: 26 Feb 2012, 15.00 GMT
+# Latest Revision: 07 Mar 2012, 21.00 GMT
#
# TODO List
#
@@ -185,7 +185,7 @@

L{FlatMenu} is distributed under the wxPython license.

-Latest Revision: Andrea Gavana @ 26 Feb 2012, 15.00 GMT
+Latest Revision: Andrea Gavana @ 07 Mar 2012, 21.00 GMT

Version 1.0

@@ -297,7 +297,7 @@
Returns the mnemonic index of the label and the label stripped of the ampersand mnemonic
(e.g. 'lab&el' ==> will result in 3 and labelOnly = label).

-    :param `label`: a string containining an ampersand.
+    :param string `label`: a string possibly containining an ampersand.
"""

indexAccel = 0
@@ -511,7 +511,7 @@
"""
Returns a `wx.Colour` according to the menu item state.

-        :param `state`: one of the following bits:
+        :param integer `state`: one of the following bits:

==================== ======= ==========================
Item State            Value  Description
@@ -592,8 +592,9 @@
"""
Draws the menu left margin.

+        :param `item`: an instance of L{FlatMenuItem};
:param `dc`: an instance of `wx.DC`;
-        :param `menuRect`: the menu client rectangle.
+        :param `menuRect`: an instance of `wx.Rect`, representing the menu client rectangle.
"""

raise Exception("This style doesn't support Drawing a Left Margin")
@@ -604,7 +605,7 @@
Draws a separator inside the toolbar in L{FlatMenuBar}.

:param `dc`: an instance of `wx.DC`;
-        :param `rect`: the bitmap's client rectangle.
+        :param `rect`: an instance of `wx.Rect`, representing the bitmap client rectangle.
"""

# Place a separator bitmap
@@ -638,8 +639,8 @@
Draws a shadow using background bitmap.

:param `dc`: an instance of `wx.DC`;
-        :param `rect`: the bitmap's client rectangle;
-        :param `where`: where to draw the shadow. This can be any combination of the
+        :param `rect`: an instance of `wx.Rect`, representing the bitmap client rectangle;
+        :param integer `where`: where to draw the shadow. This can be any combination of the
following bits:

========================== ======= ================================
@@ -697,7 +698,7 @@
Draws the toolbar background

:param `dc`: an instance of `wx.DC`;
-        :param `rect`: the toolbar's client rectangle.
+        :param `rect`: an instance of `wx.Rect`, representing the toolbar client rectangle.
"""

if not self.raiseToolbar:
@@ -720,10 +721,10 @@
Draws a separator inside a L{FlatMenu}.

:param `dc`: an instance of `wx.DC`;
-        :param `xCoord`: the current x position where to draw the separator;
-        :param `yCoord`: the current y position where to draw the separator;
-        :param `textX`: the menu item label x position;
-        :param `sepWidth`: the width of the separator, in pixels.
+        :param integer `xCoord`: the current x position where to draw the separator;
+        :param integer `yCoord`: the current y position where to draw the separator;
+        :param integer `textX`: the menu item label x position;
+        :param integer `sepWidth`: the width of the separator, in pixels.
"""

dcsaver = DCSaver(dc)
@@ -744,14 +745,14 @@

:param `item`: a L{FlatMenuItem} instance;
:param `dc`: an instance of `wx.DC`;
-        :param `xCoord`: the current x position where to draw the menu;
-        :param `yCoord`: the current y position where to draw the menu;
-        :param `imageMarginX`: the spacing between the image and the menu border;
-        :param `markerMarginX`: the spacing between the checkbox/radio marker and
+        :param integer `xCoord`: the current x position where to draw the menu;
+        :param integer `yCoord`: the current y position where to draw the menu;
+        :param integer `imageMarginX`: the spacing between the image and the menu border;
+        :param integer `markerMarginX`: the spacing between the checkbox/radio marker and
the menu border;
-        :param `textX`: the menu item label x position;
-        :param `rightMarginX`: the right margin between the text and the menu border;
-        :param `selected`: ``True`` if this menu item is currentl hovered by the mouse,
+        :param integer `textX`: the menu item label x position;
+        :param integer `rightMarginX`: the right margin between the text and the menu border;
+        :param bool `selected`: ``True`` if this menu item is currentl hovered by the mouse,
``False`` otherwise.
:param `backgroundImage`: if not ``None``, an instance of `wx.Bitmap` which will
become the background image for this L{FlatMenu}.
@@ -928,11 +929,11 @@

def DrawMenuBarButton(self, dc, rect, state):
"""
-        Draws the highlight on a FlatMenuBar
+        Draws the highlight on a L{FlatMenuBar}.

:param `dc`: an instance of `wx.DC`;
-        :param `rect`: the button's client rectangle;
-        :param `state`: the button state;
+        :param `rect`: an instance of `wx.Rect`, representing the button client rectangle;
+        :param integer `state`: the button state.
"""

# switch according to the status
@@ -954,8 +955,8 @@
Draws the highlight on a FlatMenu

:param `dc`: an instance of `wx.DC`;
-        :param `rect`: the button's client rectangle;
-        :param `state`: the button state;
+        :param `rect`: an instance of `wx.Rect`, representing the button client rectangle;
+        :param integer `state`: the button state.
"""

# switch according to the status
@@ -977,8 +978,8 @@
Draws the scroll button

:param `dc`: an instance of `wx.DC`;
-        :param `rect`: the button's client rectangle;
-        :param `state`: the button state;
+        :param `rect`: an instance of `wx.Rect`, representing the button client rectangle;
+        :param integer `state`: the button state.
"""

if not self.scrollBarButtons:
@@ -1030,11 +1031,13 @@

def DrawButton(self, dc, rect, state, colour=None):
"""
-        Draws a button
+        Draws a button.

:param `dc`: an instance of `wx.DC`;
-        :param `rect`: the button's client rectangle;
-        :param `state`: the button state;
+        :param `rect`: an instance of `wx.Rect`, representing the button client rectangle;
+        :param integer `state`: the button state;
+        :param `colour`: if not ``None``, an instance of `wx.Colour` to be used to draw
+         the L{FlatMenuItem} background.
"""

# switch according to the status
@@ -1072,7 +1075,7 @@
Draws the menu bar background colour according to the menubar.GetBackgroundColour

:param `dc`: an instance of `wx.DC`;
-        :param `rect`: the menu bar's client rectangle.
+        :param `rect`: an instance of `wx.Rect`, representing the menubar client rectangle.
"""

dcsaver = DCSaver(dc)
@@ -1089,6 +1092,7 @@
"""
Draws everything for L{FlatMenuBar}.

+        :param `menubar`: an instance of L{FlatMenuBar}.
:param `dc`: an instance of `wx.DC`.
"""

@@ -1275,7 +1279,7 @@
memDc.SelectObject(wx.NullBitmap)

# Draw the drop down arrow button
-            menubar.DrawMoreButton(dc, 0, menubar._dropDownButtonState)
+            menubar.DrawMoreButton(dc, menubar._dropDownButtonState)
# Set the button rect
menubar._dropDownButtonArea = moreMenubtnBgBmpRect

@@ -1407,8 +1411,9 @@
"""
Draws the menu left margin.

+        :param `item`: the L{FlatMenuItem} to paint;
:param `dc`: an instance of `wx.DC`;
-        :param `menuRect`: the menu client rectangle.
+        :param `menuRect`: an instance of `wx.Rect`, representing the menu client rectangle.
"""

# Construct the margin rectangle
@@ -1437,8 +1442,8 @@
Draws the highlight on a L{FlatMenu}.

:param `dc`: an instance of `wx.DC`;
-        :param `rect`: the button's client rectangle;
-        :param `state`: the button state.
+        :param `rect`: an instance of `wx.Rect`, representing the button client rectangle;
+        :param integer `state`: the button state.
"""

self.DrawButton(dc, rect, state)
@@ -1449,8 +1454,8 @@
Draws the highlight on a L{FlatMenuBar}.

:param `dc`: an instance of `wx.DC`;
-        :param `rect`: the button's client rectangle;
-        :param `state`: the button state.
+        :param `rect`: an instance of `wx.Rect`, representing the button client rectangle;
+        :param integer `state`: the button state.
"""

self.DrawButton(dc, rect, state)
@@ -1461,9 +1466,10 @@
Draws a button using the Office 2007 theme.

:param `dc`: an instance of `wx.DC`;
-        :param `rect`: the button's client rectangle;
-        :param `state`: the button state;
-        :param `colour`: a valid `wx.Colour` instance.
+        :param `rect`: an instance of `wx.Rect`, representing the button client rectangle;
+        :param integer `state`: the button state;
+        :param `colour`: if not ``None``, an instance of `wx.Colour` to be used to draw
+         the L{FlatMenuItem} background.
"""

colour = wx.SystemSettings_GetColour(wx.SYS_COLOUR_ACTIVECAPTION)
@@ -1476,8 +1482,8 @@
Draws a button using the Office 2007 theme.

:param `dc`: an instance of `wx.DC`;
-        :param `rect`: the button's client rectangle;
-        :param `state`: the button state;
+        :param `rect`: an instance of `wx.Rect`, representing the button client rectangle;
+        :param integer `state`: the button state;
:param `colour`: a valid `wx.Colour` instance.
"""

@@ -1527,7 +1533,7 @@
Draws the menu bar background according to the active theme.

:param `dc`: an instance of `wx.DC`;
-        :param `rect`: the menu bar's client rectangle.
+        :param `rect`: an instance of `wx.Rect`, representing the menubar client rectangle.
"""

# Keep old pen and brush
@@ -1597,7 +1603,7 @@
Draws the toolbar background according to the active theme.

:param `dc`: an instance of `wx.DC`;
-        :param `rect`: the toolbar's client rectangle.
+        :param `rect`: an instance of `wx.Rect`, representing the toolbar client rectangle.
"""

artMgr = ArtManager.Get()
@@ -1694,8 +1700,8 @@
Draws a button using the Vista theme.

:param `dc`: an instance of `wx.DC`;
-        :param `rect`: the button's client rectangle;
-        :param `state`: the button state;
+        :param `rect`: the an instance of `wx.Rect`, representing the button client rectangle;
+        :param integer `state`: the button state;
:param `colour`: a valid `wx.Colour` instance.
"""

@@ -1764,8 +1770,9 @@
"""
Draws the menu left margin.

+        :param `item`: the L{FlatMenuItem} to paint;
:param `dc`: an instance of `wx.DC`;
-        :param `menuRect`: the menu client rectangle.
+        :param `menuRect`: an instance of `wx.Rect`, representing the menu client rectangle.
"""

# Construct the margin rectangle
@@ -1785,7 +1792,7 @@
Draws the menu bar background according to the active theme.

:param `dc`: an instance of `wx.DC`;
-        :param `rect`: the menu bar's client rectangle.
+        :param `rect`: an instance of `wx.Rect`, representing the menubar client rectangle.
"""

# For office style, we simple draw a rectangle with a gradient colouring
@@ -1815,7 +1822,7 @@
Draws the toolbar background according to the active theme.

:param `dc`: an instance of `wx.DC`;
-        :param `rect`: the toolbar's client rectangle.
+        :param `rect`: an instance of `wx.Rect`, representing the toolbar client rectangle.
"""

artMgr = ArtManager.Get()
@@ -1854,8 +1861,8 @@
"""
Returns the string used for the MRU list items in the menu.

-    :param `n`: the index of the file name in the MRU list;
-    :param `path`: the full path of the file name.
+    :param integer `n`: the index of the file name in the MRU list;
+    :param string `path`: the full path of the file name.

:note: The index `n` is 0-based, as usual, but the strings start from 1.
"""
@@ -1883,13 +1890,13 @@
"""
Default class constructor.

-        :param `maxFiles`: the maximum number of files that should be stored and displayed;
-        :param `idBase`: defaults to ``wx.ID_FILE1`` and represents the id given to the first
+        :param integer `maxFiles`: the maximum number of files that should be stored and displayed;
+        :param integer `idBase`: defaults to ``wx.ID_FILE1`` and represents the id given to the first
history menu item.

:note: Since menu items can't share the same ID you should change `idBase` to one of
your own defined IDs when using more than one L{FileHistory} in your application.
-         """
+        """

# The ID of the first history menu item (Doesn't have to be wxID_FILE1)
self._idBase = idBase
@@ -1915,7 +1922,7 @@
"""
Returns the file at this index (zero-based).

-        :param `index`: the index at which the file is stored in the file list (zero-based).
+        :param integer `index`: the index at which the file is stored in the file list (zero-based).
"""

return self._fileHistory[index]
@@ -1942,7 +1949,7 @@
"""
Sets the base identifier for the range used for appending items.

-        :param `baseId`: the base identifier for the range used for appending items.
+        :param integer `baseId`: the base identifier for the range used for appending items.
"""

self._idBase = baseId
@@ -1965,7 +1972,7 @@
Adds a file to the file history list, if the object has a pointer to an
appropriate file menu.

-        :param `fnNew`: the file name to add to the history list.
+        :param string `fnNew`: the file name to add to the history list.
"""

# check if we don't already have this file
@@ -2018,7 +2025,7 @@
"""
Removes the specified file from the history.

-        :param `index`: the zero-based index indicating the file name position in
+        :param integer `index`: the zero-based index indicating the file name position in
the file list.
"""

@@ -2166,14 +2173,12 @@
``EVT_FLAT_MENU_SELECTED``.
"""

-    def __init__(self, eventType, eventId=1, nSel=-1, nOldSel=-1):
+    def __init__(self, eventType, eventId=1):
"""
Default class constructor.

-        :param `eventType`: the event type;
-        :param `eventId`: the event identifier;
-        :param `nSel`: the current selection;
-        :param `nOldSel`: the old selection.
+        :param integer `eventType`: the event type;
+        :param integer `eventId`: the event identifier.
"""

wx.PyCommandEvent.__init__(self, eventType, eventId)
@@ -2199,7 +2204,7 @@
otherwise it is another instance of L{MenuEntryInfo} from which the attributes
are copied;
:param `menu`: the associated L{FlatMenu} object;
-        :param `state`: the menu item state. This can be one of the following:
+        :param integer `state`: the menu item state. This can be one of the following:

==================== ======= ==========================
Item State            Value  Description
@@ -2210,7 +2215,7 @@
``ControlNormal``          3 Normal state
==================== ======= ==========================

-        :param `cmd`: the menu accelerator identifier.
+        :param integer `cmd`: the menu accelerator identifier.
"""

if isinstance(titleOrMenu, basestring):
@@ -2269,7 +2274,7 @@
"""
Sets the associated menu state.

-        :param `state`: the menu item state. This can be one of the following:
+        :param integer `state`: the menu item state. This can be one of the following:

==================== ======= ==========================
Item State            Value  Description
@@ -2303,6 +2308,7 @@

self._textBmp = bmp

+
def SetSelectedTextBitmap(self, bmp):
"""
Sets the associated selected menu bitmap.
@@ -2318,6 +2324,7 @@

return self._textBmp

+
def GetSelectedTextBitmap(self):
""" Returns the associated selected menu bitmap. """

@@ -2369,9 +2376,9 @@
"""
Default class constructor.

-        :param `parent`: the menu bar parent
-        :param `id`: the window identifier. If ``wx.ID_ANY``, will automatically create an identifier;
-        :param `iconSize`: size of the icons in the toolbar. This can be one of the
+        :param `parent`: the menu bar parent, must not be ``None``;
+        :param integer `id`: the window identifier. If ``wx.ID_ANY``, will automatically create an identifier;
+        :param integer `iconSize`: size of the icons in the toolbar. This can be one of the
following values (in pixels):

==================== ======= =============================
@@ -2381,8 +2388,8 @@
``SmallIcons``            16 Use standard 16x16 icons
==================== ======= =============================

-        :param `spacer`: the space between the menu bar text and the menu bar border;
-        :param `options`: a combination of the following bits:
+        :param integer `spacer`: the space between the menu bar text and the menu bar border;
+        :param integer `options`: a combination of the following bits:

========================= ========= =============================
`options` Bit             Hex Value  Description
@@ -2458,8 +2465,10 @@
"""
Adds the item to the end of the menu bar.

-        :param `menu`: the menu to which we are appending a new item;
-        :param `title`: the menu item label.
+        :param `menu`: the menu to which we are appending a new item, an instance of L{FlatMenu};
+        :param string `title`: the menu item label, must not be empty.
+
+        :see: L{Insert}.
"""

menu._menuBarFullTitle = title
@@ -2534,7 +2543,7 @@
"""
Sets the L{FlatMenuBar} options, whether to show a toolbar, to use LCD screen settings etc...

-        :param `options`: a combination of the following bits:
+        :param integer `options`: a combination of the following bits:

========================= ========= =============================
`options` Bit             Hex Value  Description
@@ -2634,7 +2643,7 @@
Draws the toolbar (if present).

:param `dc`: an instance of `wx.DC`;
-        :param `rect`: the toolbar client rectangle.
+        :param `rect`: the toolbar client rectangle, an instance of `wx.Rect`.
"""

highlight_width = self._tbIconSize + self._toolbarSpacer
@@ -2766,7 +2775,7 @@

def GetMoreMenuButtonRect(self):
-        """ Returns a rectangle surrounding the menu button. """
+        """ Returns a rectangle region, as an instance of `wx.Rect`, surrounding the menu button. """

clientRect = self.GetClientRect()
rect = wx.Rect(*clientRect)
@@ -2778,13 +2787,12 @@
return rect

-    def DrawMoreButton(self, dc, fr, state):
+    def DrawMoreButton(self, dc, state):
"""
Draws 'more' button to the right side of the menu bar.

:param `dc`: an instance of `wx.DC`;
-        :param `fr`: unused at present;
-        :param `state`: the 'more' button state.
+        :param integer `state`: the 'more' button state.

:see: L{MenuEntryInfo.SetState} for a list of valid menu states.
"""
@@ -2823,6 +2831,18 @@
HitTest method for L{FlatMenuBar}.

:param `pt`: an instance of `wx.Point`, specifying the hit test position.
+
+        :return: A tuple representing one of the following combinations:
+
+         ========================= ==================================================
+         Return Tuple              Description
+         ========================= ==================================================
+         (-1, 0)                   The L{HitTest} method didn't find any item with the specified input point `pt` (``NoWhere``=0)
+         (`integer`, 1)            A menu item has been hit, its position specified by the tuple item `integer` (``MenuItem``=1)
+         (`integer`, 2)            A toolbar item has ben hit, its position specified by the tuple item `integer` (``ToolbarItem``=2)
+         (-1, 3)                   The drop-down area button has been hit (``DropDownArrowButton``=3)
+         ========================= ==================================================
+
"""

if self._dropDownButtonArea.Contains(pt):
@@ -2850,9 +2870,11 @@

def FindMenuItem(self, id):
"""
-        Returns a L{FlatMenuItem} according to its `id`.
+        Finds the menu item object associated with the given menu item identifier.

-        :param `id`: the identifier for the sought L{FlatMenuItem}.
+        :param integer `id`: the identifier for the sought L{FlatMenuItem}.
+
+        :return: The found menu item object, or ``None`` if one was not found.
"""

for item in self._items:
@@ -2889,7 +2911,7 @@
"""
Shows/hides the drop-down arrow which allows customization of L{FlatMenu}.

-        :param `show`: ``True`` to show the customize menu, ``False`` to hide it.
+        :param bool `show`: ``True`` to show the customize menu, ``False`` to hide it.
"""

if self._showCustomize == show:
@@ -2901,37 +2923,41 @@

def SetMargin(self, margin):
"""
-        Sets the margin above and below the menu bar text
+        Sets the margin above and below the menu bar text.

-        :param `margin`: Height in pixels of the margin
+        :param integer `margin`: height in pixels of the margin.
"""
+
self._margin = margin

def SetSpacing(self, spacer):
"""
-        Sets the spacing between the menubar items
+        Sets the spacing between the menubar items.

-        :param `spacer`: number of pixels between each menu item
+        :param integer `spacer`: number of pixels between each menu item.
"""
+
self._spacer = spacer

def SetToolbarMargin(self, margin):
"""
-        Sets the margin around the toolbar
+        Sets the margin around the toolbar.

-        :param `margin`: width in pixels of the margin around the tools in the toolbar
+        :param integer `margin`: width in pixels of the margin around the tools in the toolbar.
"""
+
self._toolbarMargin = margin

def SetToolbarSpacing(self, spacer):
"""
-        Sets the spacing between the toolbar tools
+        Sets the spacing between the toolbar tools.

-        :param `spacer`: number of pixels between each tool in the toolbar
+        :param integer `spacer`: number of pixels between each tool in the toolbar.
"""
+
self._toolbarSpacer = spacer

@@ -2939,7 +2965,7 @@
"""
Sets whether the PC monitor is an LCD or not.

-        :param `lcd`: ``True`` to use the settings appropriate for a LCD monitor,
+        :param bool `lcd`: ``True`` to use the settings appropriate for a LCD monitor,
``False`` otherwise.
"""

@@ -2968,7 +2994,7 @@
Handles mouse move event.

:param `pt`: an instance of `wx.Point`;
-        :param `leftIsDown`: ``True`` is the left mouse button is down, ``False`` otherwise.
+        :param bool `leftIsDown`: ``True`` is the left mouse button is down, ``False`` otherwise.
"""

# Reset items state
@@ -2981,7 +3007,7 @@
self.RemoveHelp()
if self._dropDownButtonState != ControlFocus and not leftIsDown:
dc = wx.ClientDC(self)
-                self.DrawMoreButton(dc, -1, ControlFocus)
+                self.DrawMoreButton(dc, ControlFocus)

elif where == MenuItem:
self._dropDownButtonState = ControlNormal
@@ -3159,7 +3185,7 @@

if where == DropDownArrowButton:
dc = wx.ClientDC(self)
-            self.DrawMoreButton(dc, -1, ControlPressed)
+            self.DrawMoreButton(dc, ControlPressed)
self.PopupMoreMenu()

elif where == MenuItem:
@@ -3219,8 +3245,8 @@
Draws a toolbar item button.

:param `dc`: an instance of `wx.DC`;
-        :param `idx`: the tool index in the toolbar;
-        :param `state`: the button state.
+        :param integer `idx`: the tool index in the toolbar;
+        :param integer `state`: the button state.

:see: L{MenuEntryInfo.SetState} for a list of valid menu states.
"""
@@ -3294,7 +3320,7 @@
"""
Performs a toolbar button pressed action.

-        :param `idx`: the tool index in the toolbar.
+        :param integer `idx`: the tool index in the toolbar.
"""

# we handle only button clicks
@@ -3313,8 +3339,8 @@
Returns the index of the menu with the given title or ``wx.NOT_FOUND`` if
no such menu exists in this menubar.

-        :param `title`: may specify either the menu title (with accelerator characters
-         , i.e. "&File") or just the menu label ("File") indifferently.
+        :param string `title`: may specify either the menu title (with accelerator characters,
+         i.e. "&File") or just the menu label ("File") indifferently.
"""

for ii, item in enumerate(self._items):
@@ -3328,9 +3354,11 @@

def GetMenu(self, menuIdx):
"""
-        Returns the menu at the specified index (zero-based).
+        Returns the menu at the specified index `menuIdx` (zero-based).
+
+        :param integer `menuIdx`: the index of the sought menu.

-        :param `menuIdx`: the index of the sought menu.
+        :return: The found menu item object, or ``None`` if one was not found.
"""

if menuIdx >= len(self._items) or menuIdx < 0:
@@ -3349,9 +3377,9 @@
"""
Inserts the menu at the given position into the menu bar.

-        :param `pos`: the position of the new menu in the menu bar;
-        :param `menu`: the menu to add. L{FlatMenuBar} owns the menu and will free it;
-        :param `title`: the title of the menu.
+        :param integer `pos`: the position of the new menu in the menu bar;
+        :param `menu`: the menu to add, an instance of L{FlatMenu}. L{FlatMenuBar} owns the menu and will free it;
+        :param string `title`: the title of the menu.

:note: Inserting menu at position 0 will insert it in the very beginning of it,
inserting at position L{GetMenuCount} is the same as calling L{Append}.
@@ -3371,7 +3399,7 @@
Removes the menu from the menu bar and returns the menu object - the
caller is responsible for deleting it.

-        :param `pos`: the position of the menu in the menu bar.
+        :param integer `pos`: the position of the menu in the menu bar.

:note: This function may be used together with L{Insert} to change the menubar
dynamically.
@@ -3441,9 +3469,9 @@

def ClearBitmaps(self, start=0):
"""
-        Restores a `wx.NullBitmap` for the menu.
+        Restores a `wx.NullBitmap` for all the items in the menu.

-        :param `start`: the index at which to start resetting the bitmaps.
+        :param integer `start`: the index at which to start resetting the bitmaps.
"""

if self._isLCD:
@@ -3589,7 +3617,7 @@

def PopupMoreMenu(self):
-        """ Popups the 'more' menu. """
+        """ Pops up the 'more' menu. """

if (not self._showCustomize) and self.GetInvisibleMenuItemCount() + self.GetInvisibleToolbarItemCount() < 1:
return
@@ -3622,13 +3650,13 @@
if "__WXGTK__" in wx.Platform:
# Reset the more button
dc = wx.ClientDC(self)
-            self.DrawMoreButton(dc, -1, ControlNormal)
+            self.DrawMoreButton(dc, ControlNormal)

def AppendToolbarItem(self, item):
"""
Appends a tool to the L{FlatMenuBar}.
-
+
:warning: This method is now deprecated.

:see: L{AddTool}
@@ -3643,20 +3671,20 @@
"""
Adds a tool to the toolbar.

-        :param `toolId`: an integer by which the tool may be identified in subsequent
+        :param integer `toolId`: an integer by which the tool may be identified in subsequent
operations;
-        :param `label`: the tool label string;
-        :param `kind`: may be ``wx.ITEM_NORMAL`` for a normal button (default),
+        :param string `label`: the tool label string;
+        :param integer `kind`: may be ``wx.ITEM_NORMAL`` for a normal button (default),
``wx.ITEM_CHECK`` for a checkable tool (such tool stays pressed after it had been
toggled) or ``wx.ITEM_RADIO`` for a checkable tool which makes part of a radio
group of tools each of which is automatically unchecked whenever another button
in the group is checked;
-        :param `bitmap1`: the primary tool bitmap;
+        :param `bitmap1`: the primary tool bitmap, an instance of `wx.Bitmap`;
:param `bitmap2`: the bitmap used when the tool is disabled. If it is equal to
`wx.NullBitmap`, the disabled bitmap is automatically generated by greing out
the normal one;
-        :param `shortHelp`: a string used for the tools tooltip;
-        :param `longHelp`: this string is shown in the `wx.StatusBar` (if any) of the
+        :param string `shortHelp`: a string used for the tools tooltip;
+        :param string `longHelp`: this string is shown in the `wx.StatusBar` (if any) of the
parent frame when the mouse pointer is inside the tool.
"""

@@ -3674,7 +3702,7 @@
"""
Adds any control to the toolbar, typically e.g. a combobox.

-        :param `control`: the control to be added.
+        :param `control`: the control to be added, a subclass of `wx.Window` (but no `wx.TopLevelWindow`).
"""

self._tbButtons.append(ToolBarItem(FlatToolbarItem(control), wx.Rect(), ControlNormal))
@@ -3694,10 +3722,9 @@
"""
Adds a new radio tool to the toolbar.

-        Consecutive radio tools form a radio group
-        such that exactly one button in the group is pressed at any moment, in other
-        words whenever a button in the group is pressed the previously pressed button
-        is automatically released.
+        Consecutive radio tools form a radio group such that exactly one button in the
+        group is pressed at any moment, in other words whenever a button in the group is
+        pressed the previously pressed button is automatically released.

You should avoid having the radio groups of only one element as it would be
impossible for the user to use such button.
@@ -3718,10 +3745,10 @@

def SetUpdateInterval(self, interval):
"""
-        Sets the updateUI interval for toolbar items. All UpdateUI events are
+        Sets the UpdateUI interval for toolbar items. All UpdateUI events are
sent from within L{OnIdle} handler, the default is 20 milliseconds.

-        :param `interval`: the updateUI interval in milliseconds.
+        :param integer `interval`: the updateUI interval in milliseconds.
"""

self._interval = interval
@@ -3732,7 +3759,7 @@
Positions the control inside a wxAUI / PyAUI frame manager.

:param `mgr`: an instance of `wx.aui.AuiManager` or L{AuiManager};
-        :param `fixToolbar`: ``True`` if L{FlatMenuBar} can not be floated.
+        :param bool `fixToolbar`: ``True`` if L{FlatMenuBar} can not be floated.
"""

if isinstance(mgr, wx.aui.AuiManager):
@@ -3826,7 +3853,7 @@

class mcPopupWindow(wx.MiniFrame):
-    """ Since Max OS does not support `wx.PopupWindow`, this is an alternative."""
+    """ Since Max OS does not support `wx.PopupWindow`, this is an alternative. """

def __init__(self, parent):
"""
@@ -3907,10 +3934,10 @@
"""
Default class constructor.

-        :param `menu`: the parent menu associated with this button;
-        :param `up`: ``True`` for up arrow or ``False`` for down arrow;
-        :param `normalBmp`: normal state bitmap;
-        :param `disabledBmp`: disabled state bitmap.
+        :param `menu`: the parent menu associated with this button, an instance of L{FlatMenu};
+        :param bool `up`: ``True`` for up arrow or ``False`` for down arrow;
+        :param `normalBmp`: normal state bitmap, an instance of `wx.Bitmap`;
+        :param `disabledBmp`: disabled state bitmap, an instance of `wx.Bitmap`.
"""

self._normalBmp = normalBmp
@@ -4038,7 +4065,7 @@

def GetTimerId(self):
-        """ Returns the timer object Ientifier. """
+        """ Returns the timer object identifier. """

return self._timerID

@@ -4378,8 +4405,8 @@
"""
Dismisses the popup window.

-        :param `dismissParent`: whether to dismiss the parent menu or not;
-        :param `resetOwner`: ``True`` to delete the link between this menu and the
+        :param bool `dismissParent`: whether to dismiss the parent menu or not;
+        :param bool `resetOwner`: ``True`` to delete the link between this menu and the
owner menu, ``False`` otherwise.
"""

@@ -4408,14 +4435,15 @@

self._openedSubMenu = None

+
def GetRenderer(self):
-        """ Gets the renderer for this class. """
+        """ Returns the renderer for this class. """

return self._rendererMgr.GetRenderer()

def GetRootMenu(self):
-        """ Gets the top level menu. """
+        """ Returns the top level menu. """

root = self
while root._parentMenu:
@@ -4429,7 +4457,7 @@
Sets the menu owner height, this will be used to position the menu below
or above the owner.

-        :param `height`: an integer representing the menu owner height.
+        :param integer `height`: an integer representing the menu owner height.
"""

self._popupPtOffset = height
@@ -4478,8 +4506,8 @@
Default class constructor.

:param `tbItem`: an instance of L{FlatToolbarItem};
-        :param `rect`: the client rectangle for the toolbar item;
-        :param `state`: the toolbar item state.
+        :param `rect`: the client rectangle for the toolbar item, an instance of `wx.Rect`;
+        :param integer `state`: the toolbar item state.

:see: L{MenuEntryInfo.SetState} for a list of valid item states.
"""
@@ -4507,20 +4535,20 @@
:param `controlType`: can be ``None`` for a toolbar separator, an instance
of `wx.Window` for a control or an instance of `wx.Bitmap` for a standard
toolbar tool;
-        :param `id`: the toolbar tool id. If set to ``wx.ID_ANY``, a new id is
+        :param integer `id`: the toolbar tool id. If set to ``wx.ID_ANY``, a new id is
automatically assigned;
-        :param `label`: the toolbar tool label;
+        :param string `label`: the toolbar tool label;
:param `disabledBmp`: the bitmap used when the tool is disabled. If the tool
is a standard one (i.e., not a control or a separator), and `disabledBmp`
is equal to `wx.NullBitmap`, the disabled bitmap is automatically generated
by greing the normal one;
-        :param `kind`: may be ``wx.ITEM_NORMAL`` for a normal button (default),
+        :param integer `kind`: may be ``wx.ITEM_NORMAL`` for a normal button (default),
``wx.ITEM_CHECK`` for a checkable tool (such tool stays pressed after it had been
toggled) or ``wx.ITEM_RADIO`` for a checkable tool which makes part of a radio
group of tools each of which is automatically unchecked whenever another button
in the group is checked;
-        :param `shortHelp`: a string used for the tool's tooltip;
-        :param `longHelp`: this string is shown in the `wx.StatusBar` (if any) of the
+        :param string `shortHelp`: a string used for the tool's tooltip;
+        :param string `longHelp`: this string is shown in the `wx.StatusBar` (if any) of the
parent frame when the mouse pointer is inside the tool.
"""

@@ -4576,7 +4604,7 @@
"""
Sets the tool label.

-        :param `label`: the new tool string.
+        :param string `label`: the new tool string.
"""

self._label = label
@@ -4627,13 +4655,13 @@

def IsRadioItem(self):
-        """ Returns True if the item is a radio item. """
+        """ Returns ``True`` if the item is a radio item. """

return self._kind == wx.ITEM_RADIO

def IsCheckItem(self):
-        """ Returns True if the item is a radio item. """
+        """ Returns ``True`` if the item is a radio item. """

return self._kind == wx.ITEM_CHECK

@@ -4672,7 +4700,7 @@
"""
Selects or checks a radio or check item.

-        :param `select`: ``True`` to select or check a tool, ``False`` to unselect
+        :param bool `select`: ``True`` to select or check a tool, ``False`` to unselect
or uncheck it.
"""

@@ -4713,7 +4741,7 @@
"""
Enables or disables the tool.

-        :param `enable`: ``True`` to enable the tool, ``False`` to disable it.
+        :param bool `enable`: ``True`` to enable the tool, ``False`` to disable it.
"""

self._enabled = enable
@@ -4732,7 +4760,7 @@
"""
Sets the tool short help string (displayed in the tool's tooltip).

-        :param `help`: the new tool short help string.
+        :param string `help`: the new tool short help string.
"""

if self._kind == wx.ITEM_NORMAL:
@@ -4743,7 +4771,7 @@
"""
Sets the tool long help string (displayed in the parent frame `wx.StatusBar`).

-        :param `help`: the new tool long help string.
+        :param string `help`: the new tool long help string.
"""

if self._kind == wx.ITEM_NORMAL:
@@ -4775,21 +4803,21 @@
"""
Default class constructor.

-        :param `parent`: menu that the menu item belongs to;
-        :param `id`: the menu item identifier;
-        :param `label`: text for the menu item, as shown on the menu. An accelerator
+        :param `parent`: menu that the menu item belongs to, an instance of L{FlatMenu};
+        :param integer `id`: the menu item identifier;
+        :param string `label`: text for the menu item, as shown on the menu. An accelerator
key can be specified using the ampersand '&' character. In order to embed
an ampersand character in the menu item text, the ampersand must be doubled;
-        :param `helpString`: optional help string that will be shown on the status bar;
-        :param `kind`: may be ``wx.ITEM_SEPARATOR``, ``wx.ITEM_NORMAL``, ``wx.ITEM_CHECK``
+        :param string `helpString`: optional help string that will be shown on the status bar;
+        :param integer `kind`: may be ``wx.ITEM_SEPARATOR``, ``wx.ITEM_NORMAL``, ``wx.ITEM_CHECK``
or ``wx.ITEM_RADIO``;
-        :param `subMenu`: if not ``None``, the subMenu this item belongs to;
+        :param `subMenu`: if not ``None``, the sub menu this item belongs to (an instance of L{FlatMenu});
:param `normalBmp`: normal bitmap to draw to the side of the text, this bitmap
-         is used when the menu is enabled;
+         is used when the menu is enabled (an instance of `wx.Bitmap`);
:param `disabledBmp`: 'greyed' bitmap to draw to the side of the text, this
-         bitmap is used when the menu is disabled, if none supplied normal is used;
+         bitmap is used when the menu is disabled, if none supplied normal is used (an instance of `wx.Bitmap`);
:param `hotBmp`: hot bitmap to draw to the side of the text, this bitmap is
-         used when the menu is hovered, if non supplied, normal is used.
+         used when the menu is hovered, if non supplied, normal is used (an instance of `wx.Bitmap`).
"""

self._text = label
@@ -4830,7 +4858,7 @@
"""
Sets the item long help string (displayed in the parent frame `wx.StatusBar`).

-        :param `help`: the new item long help string.
+        :param string `help`: the new item long help string.
"""

self._helpString = help
@@ -4852,7 +4880,7 @@
"""
Enables or disables a menu item.

-        :param `enable`: ``True`` to enable the menu item, ``False`` to disable it.
+        :param bool `enable`: ``True`` to enable the menu item, ``False`` to disable it.
"""

self._bIsEnabled = enable
@@ -5023,7 +5051,7 @@
"""
Sets the menu item help string.

-        :param `helpString`: the new menu item help string.
+        :param string `helpString`: the new menu item help string.
"""

self._helpString = helpString
@@ -5062,7 +5090,7 @@
"""
Sets the menu item client rectangle.

-        :param `rect`: the menu item client rectangle.
+        :param `rect`: the menu item client rectangle, an instance of `wx.Rect`.
"""

self._rect = rect
@@ -5084,14 +5112,14 @@
"""
Actually shows/hides the menu item.

-        :param `show`: ``True`` to show the menu item, ``False`` to hide it.
+        :param bool `show`: ``True`` to show the menu item, ``False`` to hide it.
"""

self._visible = show

def GetHeight(self):
-        """ Returns the menu item height. """
+        """ Returns the menu item height, in pixels. """

if self.IsSeparator():
return self._parentMenu.GetRenderer().separatorHeight
@@ -5103,7 +5131,7 @@
"""
Gets the bitmap that should be used based on the item state.

-        :param `selected`: ``True`` if this menu item is currentl hovered by the mouse,
+        :param bool `selected`: ``True`` if this menu item is currently hovered by the mouse,
``False`` otherwise.
"""

@@ -5123,7 +5151,7 @@
"""
Sets the label text for this item from the text (excluding the accelerator).

-        :param `text`: the new item label (excluding the accelerator).
+        :param string `text`: the new item label (excluding the accelerator).
"""

if text:
@@ -5151,7 +5179,7 @@
"""
Sets the text for this menu item (including accelerators).

-        :param `text`: the new item label (including the accelerator).
+        :param string `text`: the new item label (including the accelerator).
"""

self._text = text
@@ -5186,7 +5214,7 @@
"""
Checks or unchecks the menu item.

-        :param `check`: ``True`` to check the menu item, ``False`` to uncheck it.
+        :param bool `check`: ``True`` to check the menu item, ``False`` to uncheck it.

:note: This method is meaningful only for menu items of ``wx.ITEM_CHECK``
or ``wx.ITEM_RADIO`` kind.
@@ -5209,6 +5237,11 @@

def SetFont(self, font=None):
+        """
+        Sets the L{FlatMenuItem} font.
+
+        :param `font`: an instance of a valid `wx.Font`.
+        """

self._font = font

@@ -5217,16 +5250,23 @@

def GetFont(self):
+        """ Returns this L{FlatMenuItem} font. """

return self._font

def SetTextColour(self, colour=None):
+        """
+        Sets the L{FlatMenuItem} foreground colour for the menu label.
+
+        :param `colour`: an instance of a valid `wx.Colour`.
+        """

self._textColour = colour

def GetTextColour(self):
+        """ Returns this L{FlatMenuItem} foreground text colour. """

return self._textColour

@@ -5392,12 +5432,12 @@
"""
Appends an item to this menu.

-        :param `id`: the menu item identifier;
-        :param `item`: the string to appear on the menu item;
-        :param `helpString`: an optional help string associated with the item. By default,
+        :param integer `id`: the menu item identifier;
+        :param string `item`: the string to appear on the menu item;
+        :param string `helpString`: an optional help string associated with the item. By default,
the handler for the ``EVT_FLAT_MENU_ITEM_MOUSE_OVER`` event displays this string
in the status line;
-        :param `kind`: may be ``wx.ITEM_NORMAL`` for a normal button (default),
+        :param integer `kind`: may be ``wx.ITEM_NORMAL`` for a normal button (default),
``wx.ITEM_CHECK`` for a checkable tool (such tool stays pressed after it had been
toggled) or ``wx.ITEM_RADIO`` for a checkable tool which makes part of a radio
group of tools each of which is automatically unchecked whenever another button
@@ -5412,12 +5452,12 @@
"""
Prepends an item to this menu.

-        :param `id`: the menu item identifier;
-        :param `item`: the string to appear on the menu item;
-        :param `helpString`: an optional help string associated with the item. By default,
+        :param integer `id`: the menu item identifier;
+        :param string `item`: the string to appear on the menu item;
+        :param string `helpString`: an optional help string associated with the item. By default,
the handler for the ``EVT_FLAT_MENU_ITEM_MOUSE_OVER`` event displays this string
in the status line;
-        :param `kind`: may be ``wx.ITEM_NORMAL`` for a normal button (default),
+        :param integer `kind`: may be ``wx.ITEM_NORMAL`` for a normal button (default),
``wx.ITEM_CHECK`` for a checkable tool (such tool stays pressed after it had been
toggled) or ``wx.ITEM_RADIO`` for a checkable tool which makes part of a radio
group of tools each of which is automatically unchecked whenever another button
@@ -5444,10 +5484,10 @@
"""
Adds a pull-right submenu to the end of the menu.

-        :param `id`: the menu item identifier;
-        :param `item`: the string to appear on the menu item;
+        :param integer `id`: the menu item identifier;
+        :param string `item`: the string to appear on the menu item;
:param `subMenu`: an instance of L{FlatMenu}, the submenu to append;
-        :param `helpString`: an optional help string associated with the item. By default,
+        :param string `helpString`: an optional help string associated with the item. By default,
the handler for the ``EVT_FLAT_MENU_ITEM_MOUSE_OVER`` event displays this string
in the status line.
"""
@@ -5481,7 +5521,7 @@
def AddItem(self, menuItem):
"""
Internal function to add the item to this menu. The item must
-        already be in self._itemsArr.
+        already be in the `self._itemsArr` attribute.

:param `menuItem`: an instance of L{FlatMenuItem}.
"""
@@ -5614,37 +5654,37 @@

def GetMenuWidth(self):
-        """ Returns the menu width. """
+        """ Returns the menu width in pixels. """

return self._menuWidth

def GetLeftMarginWidth(self):
-        """ Returns the menu left margin width. """
+        """ Returns the menu left margin width, in pixels. """

return self._leftMarginWidth

def GetRightMarginWidth(self):
-        """ Returns the menu right margin width. """
+        """ Returns the menu right margin width, in pixels. """

return self._rightMarginWidth

def GetBorderXWidth(self):
-        """ Returns the menu border x-width. """
+        """ Returns the menu border x-width, in pixels. """

return self._borderXWidth

def GetBorderYWidth(self):
-        """ Returns the menu border y-width. """
+        """ Returns the menu border y-width, in pixels. """

return self._borderYWidth

def GetItemHeight(self):
-        """ Returns the height of a particular item. """
+        """ Returns the height of a particular item, in pixels. """

return self._itemHeight

@@ -5663,6 +5703,7 @@
def AppendRadioItem(self, id, item, helpString=""):
"""
Adds a radio item to the end of the menu.
+
All consequent radio items form a group and when an item in the group is
checked, all the others are automatically unchecked.

@@ -5674,7 +5715,7 @@

def AppendSeparator(self):
-        """ Appends a separator item to teh end of this menu. """
+        """ Appends a separator item to the end of this menu. """

newItem = FlatMenuItem(self)
return self.AppendItem(newItem)
@@ -5684,7 +5725,7 @@
"""
Inserts a separator at the given position.

-        :param `pos`: the index at which we want to insert the separator.
+        :param integer `pos`: the index at which we want to insert the separator.
"""

newItem = FlatMenuItem(self)
@@ -5695,8 +5736,8 @@
"""
Dismisses the popup window.

-        :param `dismissParent`: whether to dismiss the parent menu or not;
-        :param `resetOwner`: ``True`` to delete the link between this menu and the
+        :param bool `dismissParent`: whether to dismiss the parent menu or not;
+        :param bool `resetOwner`: ``True`` to delete the link between this menu and the
owner menu, ``False`` otherwise.
"""

@@ -5717,6 +5758,7 @@

FlatMenuBase.Dismiss(self, dismissParent, resetOwner)

+
def OnPaint(self, event):
"""
Handles the ``wx.EVT_PAINT`` event for L{FlatMenu}.
@@ -5760,7 +5802,7 @@
Redraws the menu.

:param `dc`: an instance of `wx.DC`;
-        :param `oldSelection`: if >= 0, the index representing the previous selected
+        :param integer `oldSelection`: if non-negative, the index representing the previous selected
menu item.
"""

@@ -5938,7 +5980,7 @@
"""
Advance forward or backward the current selection.

-        :param `down`: ``True`` to advance the selection forward, ``False`` otherwise.
+        :param bool `down`: ``True`` to advance the selection forward, ``False`` otherwise.
"""

# make sure we have at least two items in the menu (which are not
@@ -5997,6 +6039,18 @@
HitTest method for L{FlatMenu}.

:param `pos`: an instance of `wx.Point`, a point to test for hits.
+
+        :return: A tuple representing one of the following combinations:
+
+         ========================= ==================================================
+         Return Tuple              Description
+         ========================= ==================================================
+         (0, -1)                   The L{HitTest} method didn't find any item with the specified input point `pt` (``MENU_HT_NONE``=0)
+         (1, `integer`)            A menu item has been hit (``MENU_HT_ITEM``=1)
+         (2, -1)                   The `Scroll Up` button has been hit (``MENU_HT_SCROLL_UP``=2)
+         (3, -1)                   The `Scroll Down` button has been hit (``MENU_HT_SCROLL_DOWN``=3)
+         ========================= ==================================================
+
"""

if self._showScrollButtons:
@@ -6129,7 +6183,8 @@
"""
Processes mouse right clicks.

-        :param `pos`: the position at which the mouse right button was pressed.
+        :param `pos`: the position at which the mouse right button was pressed,
+         an instance of `wx.Point`.
"""

rect = self.GetClientRect()
@@ -6170,7 +6225,7 @@
"""
Open an item's context menu (if any).

-        :param `itemIdx`: the index of the item for which we want to open the context menu.
+        :param integer `itemIdx`: the index of the item for which we want to open the context menu.
"""

item = self._itemsArr[itemIdx]
@@ -6197,7 +6252,8 @@
"""
Processes mouse left clicks.

-        :param `pos`: the position at which the mouse left button was pressed.
+        :param `pos`: the position at which the mouse left button was pressed,
+         an instance of `wx.Point`.
"""

rect = self.GetClientRect()
@@ -6233,7 +6289,8 @@
"""
Processes mouse left clicks.

-        :param `pos`: the position at which the mouse left button was pressed.
+        :param `pos`: the position at which the mouse left button was pressed,
+         an instance of `wx.Point`.
"""

self.ProcessMouseLClick(pos)
@@ -6260,7 +6317,7 @@
"""
Processes mouse movements.

-        :param `pos`: the position at which the mouse was moved.
+        :param `pos`: the position at which the mouse was moved, an instance of `wx.Point`.
"""

rect = self.GetClientRect()
@@ -6431,8 +6488,8 @@
"""
Closes a child sub-menu.

-        :param `itemIdx`: the index of the item for which we want to close the submenu;
-        :param `alwaysClose`: if ``True``, always close the submenu irrespectively of
+        :param integer `itemIdx`: the index of the item for which we want to close the submenu;
+        :param bool `alwaysClose`: if ``True``, always close the submenu irrespectively of
other conditions.
"""

@@ -6457,7 +6514,7 @@
"""
Performs an action based on user selection.

-        :param `itemIdx`: the index of the item for which we want to perform the action.
+        :param integer `itemIdx`: the index of the item for which we want to perform the action.
"""

if itemIdx < 0 or itemIdx >= len(self._itemsArr):
@@ -6503,8 +6560,8 @@
"""
If `itemIdx` is an item with submenu, open it.

-        :param `itemIdx`: the index of the item for which we want to open the submenu;
-        :param `selectFirst`: if ``True``, the first item of the submenu will be shown
+        :param integer `itemIdx`: the index of the item for which we want to open the submenu;
+        :param bool `selectFirst`: if ``True``, the first item of the submenu will be shown
as selected.
"""

@@ -6606,13 +6663,13 @@
"""
Inserts the given `item` before the position `pos`.

-        :param `pos`: the position at which to insert the new menu item;
-        :param `id`: the menu item identifier;
-        :param `item`: the string to appear on the menu item;
-        :param `helpString`: an optional help string associated with the item. By default,
+        :param integer `pos`: the position at which to insert the new menu item;
+        :param integer `id`: the menu item identifier;
+        :param string `item`: the string to appear on the menu item;
+        :param string `helpString`: an optional help string associated with the item. By default,
the handler for the ``EVT_FLAT_MENU_ITEM_MOUSE_OVER`` event displays this string
in the status line;
-        :param `kind`: may be ``wx.ITEM_NORMAL`` for a normal button (default),
+        :param integer `kind`: may be ``wx.ITEM_NORMAL`` for a normal button (default),
``wx.ITEM_CHECK`` for a checkable tool (such tool stays pressed after it had been
toggled) or ``wx.ITEM_RADIO`` for a checkable tool which makes part of a radio
group of tools each of which is automatically unchecked whenever another button
@@ -6627,7 +6684,7 @@
"""
Inserts an item into the menu.

-        :param `pos`: the position at which to insert the new menu item;
+        :param integer `pos`: the position at which to insert the new menu item;
:param `item`: an instance of L{FlatMenuItem}.
"""

@@ -6707,7 +6764,7 @@
"""
Sets the number of columns for a menu window.

-        :param `numCols`: the number of columns for this L{FlatMenu} window.
+        :param integer `numCols`: the number of columns for this L{FlatMenu} window.
"""

if self._numCols == numCols:
@@ -6729,9 +6786,11 @@
Finds the menu item object associated with the given menu item identifier and,
optionally, the (sub)menu it belongs to.

-        :param `itemId`: menu item identifier;
+        :param integer `itemId`: menu item identifier;
:param `menu`: if not ``None``, it will be filled with the item's parent menu
(if the item was found).
+
+        :return: The found menu item object, or ``None`` if one was not found.
"""

idx = wx.NOT_FOUND
@@ -6754,24 +6813,46 @@

def SetItemFont(self, itemId, font=None):
+        """
+        Sets the L{FlatMenuItem} font.
+
+        :param integer `itemId`: the menu item identifier;
+        :param `font`: an instance of a valid `wx.Font`.
+        """

item = self.FindItem(itemId)
item.SetFont(font)

def GetItemFont(self, itemId):
+        """
+        Returns this L{FlatMenuItem} font.
+
+        :param integer `itemId`: the menu item identifier.
+        """

item = self.FindItem(itemId)
return item.GetFont()

def SetItemTextColour(self, itemId, colour=None):
+        """
+        Sets the L{FlatMenuItem} foreground text colour.
+
+        :param integer `itemId`: the menu item identifier;
+        :param `colour`: an instance of a valid `wx.Colour`.
+        """

item = self.FindItem(itemId)
item.SetTextColour(colour)

def GetItemTextColour(self, itemId):
+        """
+        Returns this L{FlatMenuItem} foreground text colour.
+
+        :param integer `itemId`: the menu item identifier.
+        """

item = self.FindItem(itemId)
return item.GetTextColour()
@@ -6781,8 +6862,8 @@
"""
Sets the label of a L{FlatMenuItem}.

-        :param `id`: The menu item identifier;
-        :param `label`: The menu item label to set.
+        :param integer `itemId`: the menu item identifier;
+        :param string `label`: the menu item label to set.

:see: L{GetLabel}.
"""
@@ -6798,7 +6879,7 @@
"""
Returns the label of a L{FlatMenuItem}.

-        :param `id`: The menu item identifier;
+        :param integer `id`: the menu item identifier;

:see: L{SetLabel}.
"""
@@ -6811,9 +6892,11 @@
"""
Finds an item and its position inside the menu based on its id.

-        :param `itemId`: menu item identifier;
+        :param integer `itemId`: menu item identifier;
:param `menu`: if not ``None``, it will be filled with the item's parent menu
(if the item was found).
+
+        :return: The found menu item object, or ``None`` if one was not found.
"""

menu = None
@@ -6845,7 +6928,7 @@

def GetAccelTable(self):
-        """ Returns the menu accelerator table. """
+        """ Returns the menu accelerator table, an instance of `wx.AcceleratorTable`. """

n = len(self._accelArray)
if n == 0:
@@ -6869,7 +6952,7 @@

def GetAccelArray(self):
-        """ Returns an array filled with the accelerator entries for the menu. """
+        """ Returns a list filled with the accelerator entries for the menu. """

return self._accelArray

@@ -6879,7 +6962,7 @@
"""
Actually sends menu command events.

-        :param `itemIdx`: the menu item index for which we want to send a command event.
+        :param integer `itemIdx`: the menu item index for which we want to send a command event.
"""

if itemIdx < 0 or itemIdx >= len(self._itemsArr):
@@ -6908,8 +6991,8 @@
Sends the ``EVT_FLAT_MENU_ITEM_MOUSE_OVER`` and ``EVT_FLAT_MENU_ITEM_MOUSE_OUT``
events.

-        :param `itemIdx`: the menu item index for which we want to send an event;
-        :param `over`: ``True`` to send a ``EVT_FLAT_MENU_ITEM_MOUSE_OVER`` event, ``False`` to
+        :param integer `itemIdx`: the menu item index for which we want to send an event;
+        :param bool `over`: ``True`` to send a ``EVT_FLAT_MENU_ITEM_MOUSE_OVER`` event, ``False`` to
send a ``EVT_FLAT_MENU_ITEM_MOUSE_OUT`` event.
"""

@@ -6934,7 +7017,7 @@
"""
Actually sends menu UI events.

-        :param `itemIdx`: the menu item index for which we want to send a UI event.
+        :param integer `itemIdx`: the menu item index for which we want to send a UI event.
"""

if itemIdx < 0 or itemIdx >= len(self._itemsArr):
@@ -6980,6 +7063,9 @@
Finds an item and its position inside the menu based on its id.

:param `item`: an instance of L{FlatMenuItem}.
+
+        :return: An integer specifying the index found menu item object, or
+         ``wx.NOT_FOUND`` if one was not found.
"""

if item == None or len(self._itemsArr) == 0:
@@ -7009,9 +7095,7 @@

def GetBackgroundBitmap(self):
-        """
-        Returns the background bitmap for this particular L{FlatMenu}, if any.
-        """
+        """ Returns the background bitmap for this particular L{FlatMenu}, if any. """

return self._originalBackgroundImage

@@ -7021,7 +7105,9 @@
Internal function to help recurse through all the menu items.

:param `menu`: the menu from which we start accumulating items;
-        :param `items`: the array which is recursively filled with menu items.
+        :param list `items`: the array which is recursively filled with menu items.
+
+        :return: a list of L{FlatMenuItem}.
"""

# first copy the current menu items

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • flatmenu »
  • SVN Revision 70837 For flatmenu


flatnotebook functions

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • flatnotebook »
  • flatnotebook functions

flatnotebook functions

This is the description of standalone Python functions in the flatnotebook module.

Functions Summary

AdjustColour | Brighten/darken input colour by percent and adjust alpha channel if needed.
DrawButton | Draws a FlatNotebook tab.
FormatColour | Convert the input colour into a valid wx.Colour instance, using whatever typemap
LightColour | Brighten the input colour by a percentage.
PaintStraightGradientBox | Draws a gradient coloured box from startColour to endColour.
RandomColour | Creates a random colour.

API Functions API

AdjustColour(colour, percent, alpha=255) [source]

Brighten/darken input colour by percent and adjust alpha channel if needed.

Parameters:
  • colour – colour object to adjust, an instance of wx.Colour;

  • percent – percent to adjust + (brighten) or - (darken);
  • alpha – amount to adjust the alpha channel.
Returns:

The modified colour.

DrawButton(dc, rect, focus, upperTabs) [source]

Draws a FlatNotebook tab.

Parameters:
  • dc – an instance of wx.DC;
  • rect – the tab’s client rectangle;
  • focus – True if the tab has focus, False otherwise;
  • upperTabs – True if the tabs are at the top, False if they are at the bottom.

FormatColour(colour) [source]

Convert the input colour into a valid wx.Colour instance, using whatever typemap accepted by wxWidgets/wxPython.

Parameters: colour – can be an instance of wx.Colour, a 3 or 4 integer tuple, a hex string, a string representing the colour name or None.
Returns: a valid instance of wx.Colour or None if the input colour was None in the first place.

LightColour(colour, percent) [source]

Brighten the input colour by a percentage.

Parameters:
  • colour – a valid wx.Colour instance;

  • percent – the percentage by which the input colour should be brightened.

PaintStraightGradientBox(dc, rect, startColour, endColour, vertical=True) [source]

Draws a gradient coloured box from startColour to endColour.

Parameters:
  • dc – an instance of wx.DC;

  • rect – the rectangle to fill with the gradient shading;
  • startColour – the first colour in the gradient shading;
  • endColour – the last colour in the gradient shading;
  • vertical – True if the gradient shading is north to south, False if it is east to west.

RandomColour() [source]

Creates a random colour.

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • infobar
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • flatnotebook »
  • flatnotebook functions


FlatNotebook

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • flatnotebook »
  • FlatNotebook

FlatNotebook

The FlatNotebook is a full implementation of the wx.Notebook, and designed to be a drop-in replacement for wx.Notebook. The API functions are similar so one can expect the function to behave in the same way.

hierarchy Inheritance Diagram

Inheritance diagram for: FlatNotebook

Inheritance diagram of FlatNotebook

subclasses Known Subclasses

  • flatnotebook.FlatNotebookCompatible

appearance Control Appearance

FlatNotebook

Methods Summary

__init__ | Default class constructor.
AddPage | Adds a page to the FlatNotebook.
AdvanceSelection | Cycles through the tabs.
AssignImageList | Assigns the image list for the page control.
DeleteAllPages | Deletes all the pages in the FlatNotebook.
DeletePage | Deletes the specified page, and the associated window.
DoGetBestSize | Gets the size which best suits the window: for a control, it would be the
EnableTab | Enables or disables a tab.
EnsureVisible | Ensures that a tab is visible.
GetAGWWindowStyleFlag | Returns the FlatNotebook window style.
GetActiveTabColour | Returns the active tab colour.
GetActiveTabTextColour | Get the active tab text colour.
GetBorderColour | Returns the border colour.
GetCurrentPage | Returns the currently selected notebook page or None if none is selected.
GetCustomPage | Returns a custom panel to show when there are no pages left in FlatNotebook.
GetEnabled | Returns whether a tab is enabled or not.
GetGradientColourBorder | Gets the tab border colour.
GetGradientColourFrom | Gets first gradient colour.
GetGradientColourTo | Gets second gradient colour.
GetImageList | Returns the associated image list.
GetNonActiveTabTextColour | Returns the non active tabs text colour.
GetPadding | Returns the amount of space around each page’s icon and label, in pixels.
GetPage | Returns the window at the given page position, or None.
GetPageBestSize | Return the page best size.
GetPageCount | Returns the number of pages in the FlatNotebook control.
GetPageImage | Returns the image index for the given page.
GetPageIndex | Returns the index at which the window is found.
GetPageShapeAngle | Returns the angle associated to a tab.
GetPageText | Returns the string for the given page.
GetPageTextColour | Returns the tab text colour if it has been set previously, or None otherwise.
GetPreviousSelection | Returns the previous selection.
GetSelection | Returns the currently selected page, or -1 if none was selected.
GetTabArea | Returns the associated page.
GetTabAreaColour | Returns the area behind the tabs colour.
GetTileOrientation | Returns the orientation when on tiling mode.
HasAGWFlag | Returns whether a flag is present in the FlatNotebook style.
HideTabs | Hides the tabs.
Init | Initializes all the class attributes.
InsertPage | Inserts a new page at the specified position.
OnDropTarget | Handles the drop action from a drag and drop operation.
OnNavigationKey | Handles the wx.EVT_NAVIGATION_KEY event for FlatNotebook.
RemovePage | Deletes the specified page, without deleting the associated window.
SetAGWWindowStyleFlag | Sets the FlatNotebook window style flags.
SetActiveTabColour | Sets the active tab colour.
SetActiveTabTextColour | Sets the text colour for the active tab.
SetAllPagesShapeAngle | Sets the angle associated to all the tab.
SetCustomPage | Sets a custom panel to show when there are no pages left in FlatNotebook.
SetGradientColourBorder | Sets the tab border colour.
SetGradientColourFrom | Sets the starting colour for the gradient.
SetGradientColourTo | Sets the ending colour for the gradient.
SetGradientColours | Sets the gradient colours for the tab.
SetImageList | Sets the image list for the page control.
SetNavigatorIcon | Set the icon used by the TabNavigatorWindow.
SetNonActiveTabTextColour | Sets the non active tabs text colour.
SetPadding | Sets the amount of space around each page’s icon and label, in pixels.
SetPageImage | Sets the image index for the given page.
SetPageShapeAngle | Sets the angle associated to a tab.
SetPageText | Sets the text for the given page.
SetPageTextColour | Sets the tab text colour individually.
SetRightClickMenu | Sets the popup menu associated to a right click on a tab.
SetSelection | Sets the selection for the given page.
SetTabAreaColour | Sets the area behind the tabs colour.
ShowCustomPage | Hides the custom panel which is shown when there are no pages left in FlatNotebook.
ShowTabs | Shows the tabs if hidden previously.
Tile | Shows pages in column/row mode (one panel after the other in columns/rows).

API Class API

class FlatNotebook(wx.PyPanel) [source]

The FlatNotebook is a full implementation of the wx.Notebook, and designed to be a drop-in replacement for wx.Notebook. The API functions are similar so one can expect the function to behave in the same way.

__init__(parent, id=wx.ID_ANY, pos=wx.DefaultPosition, size=wx.DefaultSize, style=0, agwStyle=0, name="FlatNotebook") [source]

Default class constructor.

Parameters:
  • parent – the FlatNotebook parent;
  • id – an identifier for the control: a value of -1 is taken to mean a default;
  • pos – the control position. A value of (-1, -1) indicates a default position, chosen by either the windowing system or wxPython, depending on platform;
  • size – the control size. A value of (-1, -1) indicates a default size, chosen by either the windowing system or wxPython, depending on platform;
  • style – the underlying wx.PyPanel window style;
  • agwStyle – the AGW-specific window style. This can be a combination of the following bits:

    Window Styles | Hex Value | Description
    FNB_VC71 | 0x1 | Use Visual Studio 2003 (VC7.1) style for tabs.
    FNB_FANCY_TABS | 0x2 | Use fancy style - square tabs filled with gradient colouring.
    FNB_TABS_BORDER_SIMPLE | 0x4 | Draw thin border around the page.
    FNB_NO_X_BUTTON | 0x8 | Do not display the ‘X’ button.
    FNB_NO_NAV_BUTTONS | 0x10 | Do not display the right/left arrows.
    FNB_MOUSE_MIDDLE_CLOSES_TABS | 0x20 | Use the mouse middle button for cloing tabs.
    FNB_BOTTOM | 0x40 | Place tabs at bottom - the default is to place them at top.
    FNB_NODRAG | 0x80 | Disable dragging of tabs.
    FNB_VC8 | 0x100 | Use Visual Studio 2005 (VC8) style for tabs.
    FNB_X_ON_TAB | 0x200 | Place ‘X’ close button on the active tab.
    FNB_BACKGROUND_GRADIENT | 0x400 | Use gradients to paint the tabs background.
    FNB_COLOURFUL_TABS | 0x800 | Use colourful tabs (VC8 style only).
    FNB_DCLICK_CLOSES_TABS | 0x1000 | Style to close tab using double click.
    FNB_SMART_TABS | 0x2000 | Use Smart Tabbing, like Alt + Tab on Windows.
    FNB_DROPDOWN_TABS_LIST | 0x4000 | Use a dropdown menu on the left in place of the arrows.
    FNB_ALLOW_FOREIGN_DND | 0x8000 | Allows drag ‘n’ drop operations between different FlatNotebook.
    FNB_HIDE_ON_SINGLE_TAB | 0x10000 | Hides the Page Container when there is one or fewer tabs.
    FNB_DEFAULT_STYLE | 0x10020 | FlatNotebook default style.
    FNB_FF2 | 0x20000 | Use Firefox 2 style for tabs.
    FNB_NO_TAB_FOCUS | 0x40000 | Does not allow tabs to have focus.
    FNB_RIBBON_TABS | 0x80000 | Use the Ribbon Tabs style.
    FNB_HIDE_TABS | 0x100000 | Hides the Page Container allowing only keyboard navigation
    FNB_NAV_BUTTONS_WHEN_NEEDED | 0x200000 | Hides the navigation left/right arrows if all tabs fit
  • name – the window name.

AddPage(page, text, select=False, imageId=-1) [source]

Adds a page to the FlatNotebook.

Parameters:
  • page – specifies the new page;
  • text – specifies the text for the new page;
  • select – specifies whether the page should be selected;
  • imageId – specifies the optional image index for the new page.
Returns:

True if successful, False otherwise.

AdvanceSelection(forward=True) [source]

Cycles through the tabs.

Parameters: forward – if True, the selection is advanced in ascending order (to the right), otherwise the selection is advanced in descending order.

Note

The call to this function generates the page changing events.

AssignImageList(imageList) [source]

Assigns the image list for the page control.

Parameters: imageList – an instance of wx.ImageList.

DeleteAllPages() [source]

Deletes all the pages in the FlatNotebook.

DeletePage(page) [source]

Deletes the specified page, and the associated window.

Parameters: page – an integer specifying the new selected page.

Note

The call to this function generates the page changing events.

DoGetBestSize() [source]

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

Note

Overridden from wx.PyPanel.

EnableTab(page, enabled=True) [source]

Enables or disables a tab.

Parameters:
  • page – an integer specifying the page index;
  • enabled – True to enable a tab, False to disable it.

EnsureVisible(page) [source]

Ensures that a tab is visible.

Parameters: page – an integer specifying the page index.

GetAGWWindowStyleFlag() [source]

Returns the FlatNotebook window style.

See also

SetAGWWindowStyleFlag for a list of valid window styles.

GetActiveTabColour() [source]

Returns the active tab colour.

GetActiveTabTextColour() [source]

Get the active tab text colour.

GetBorderColour() [source]

Returns the border colour.

GetCurrentPage() [source]

Returns the currently selected notebook page or None if none is selected.

GetCustomPage() [source]

Returns a custom panel to show when there are no pages left in FlatNotebook.

GetEnabled(page) [source]

Returns whether a tab is enabled or not.

Parameters: page – an integer specifying the page index.

GetGradientColourBorder() [source]

Gets the tab border colour.

GetGradientColourFrom() [source]

Gets first gradient colour.

GetGradientColourTo() [source]

Gets second gradient colour.

GetImageList() [source]

Returns the associated image list.

GetNonActiveTabTextColour() [source]

Returns the non active tabs text colour.

GetPadding() [source]

Returns the amount of space around each page’s icon and label, in pixels.

GetPage(page) [source]

Returns the window at the given page position, or None.

GetPageBestSize() [source]

Return the page best size.

GetPageCount() [source]

Returns the number of pages in the FlatNotebook control.

GetPageImage(page) [source]

Returns the image index for the given page.

Parameters: page – an integer specifying the page index.

GetPageIndex(win) [source]

Returns the index at which the window is found.

Parameters: win – an instance of wx.Window.

GetPageShapeAngle(page_index) [source]

Returns the angle associated to a tab.

Parameters: page_index – the index of the tab for which we wish to get the shape angle.

GetPageText(page) [source]

Returns the string for the given page.

Parameters: page – an integer specifying the page index.

GetPageTextColour(page) [source]

Returns the tab text colour if it has been set previously, or None otherwise.

Parameters: page – an integer specifying the page index.

GetPreviousSelection() [source]

Returns the previous selection.

GetSelection() [source]

Returns the currently selected page, or -1 if none was selected.

GetTabArea() [source]

Returns the associated page.

GetTabAreaColour() [source]

Returns the area behind the tabs colour.

GetTileOrientation() [source]

Returns the orientation when on tiling mode. This method can return wx.VERTICAL when the panels are vertically stacked, wx.HORIZONTAL when they are horizontally stacked panels or None when there is no stacking and FlatNotebook behaves like a normal notebook.

HasAGWFlag(flag) [source]

Returns whether a flag is present in the FlatNotebook style.

Parameters: flag – one of the possible FlatNotebook window styles.

See also

SetAGWWindowStyleFlag for a list of possible window style flags.

HideTabs() [source]

Hides the tabs.

Init() [source]

Initializes all the class attributes.

InsertPage(indx, page, text, select=True, imageId=-1) [source]

Inserts a new page at the specified position.

Parameters:
  • indx – specifies the position of the new page;
  • page – specifies the new page;
  • text – specifies the text for the new page;
  • select – specifies whether the page should be selected;
  • imageId – specifies the optional image index for the new page.
Returns:

True if successful, False otherwise.

OnDropTarget(x, y, nTabPage, wnd_oldContainer) [source]

Handles the drop action from a drag and drop operation.

Parameters:
  • x – the x position of the drop action;
  • y – the y position of the drop action;
  • nTabPage – the index of the tab being dropped;
  • wnd_oldContainer – the FlatNotebook to which the dropped tab previously belonged to.

OnNavigationKey(event) [source]

Handles the wx.EVT_NAVIGATION_KEY event for FlatNotebook.

Parameters: event – a wx.NavigationKeyEvent event to be processed.

RemovePage(page) [source]

Deletes the specified page, without deleting the associated window.

Parameters: page – an integer specifying the page index.

SetAGWWindowStyleFlag(agwStyle) [source]

Sets the FlatNotebook window style flags.

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

Window Styles | Hex Value | Description
FNB_VC71 | 0x1 | Use Visual Studio 2003 (VC7.1) style for tabs.
FNB_FANCY_TABS | 0x2 | Use fancy style - square tabs filled with gradient colouring.
FNB_TABS_BORDER_SIMPLE | 0x4 | Draw thin border around the page.
FNB_NO_X_BUTTON | 0x8 | Do not display the ‘X’ button.
FNB_NO_NAV_BUTTONS | 0x10 | Do not display the right/left arrows.
FNB_MOUSE_MIDDLE_CLOSES_TABS | 0x20 | Use the mouse middle button for cloing tabs.
FNB_BOTTOM | 0x40 | Place tabs at bottom - the default is to place them at top.
FNB_NODRAG | 0x80 | Disable dragging of tabs.
FNB_VC8 | 0x100 | Use Visual Studio 2005 (VC8) style for tabs.
FNB_X_ON_TAB | 0x200 | Place ‘X’ close button on the active tab.
FNB_BACKGROUND_GRADIENT | 0x400 | Use gradients to paint the tabs background.
FNB_COLOURFUL_TABS | 0x800 | Use colourful tabs (VC8 style only).
FNB_DCLICK_CLOSES_TABS | 0x1000 | Style to close tab using double click.
FNB_SMART_TABS | 0x2000 | Use Smart Tabbing, like Alt + Tab on Windows.
FNB_DROPDOWN_TABS_LIST | 0x4000 | Use a dropdown menu on the left in place of the arrows.
FNB_ALLOW_FOREIGN_DND | 0x8000 | Allows drag ‘n’ drop operations between different FlatNotebook.
FNB_HIDE_ON_SINGLE_TAB | 0x10000 | Hides the Page Container when there is one or fewer tabs.
FNB_DEFAULT_STYLE | 0x10020 | FlatNotebook default style.
FNB_FF2 | 0x20000 | Use Firefox 2 style for tabs.
FNB_NO_TAB_FOCUS | 0x40000 | Does not allow tabs to have focus.
FNB_RIBBON_TABS | 0x80000 | Use the Ribbon Tabs style.
FNB_HIDE_TABS | 0x100000 | Hides the Page Container allowing only keyboard navigation
FNB_NAV_BUTTONS_WHEN_NEEDED | 0x200000 | Hides the navigation left/right arrows if all tabs fit

SetActiveTabColour(colour) [source]

Sets the active tab colour.

Parameters: colour – a valid wx.Colour object or any typemap supported by wxWidgets/wxPython to generate a colour (i.e., a hex string, a colour name, a 3 or 4 integer tuple).

SetActiveTabTextColour(textColour) [source]

Sets the text colour for the active tab.

Parameters: textColour – a valid wx.Colour object or any typemap supported by wxWidgets/wxPython to generate a colour (i.e., a hex string, a colour name, a 3 or 4 integer tuple).

SetAllPagesShapeAngle(angle) [source]

Sets the angle associated to all the tab.

Parameters: angle – the new shape angle for the tab (must be less than 15 degrees).

SetCustomPage(panel) [source]

Sets a custom panel to show when there are no pages left in FlatNotebook.

Parameters: panel – any subclass of wx.Window will do, as long as it is suitable to be used as a notebook page. Examples include wx.Panel, wx.ScrolledWindow, and so on.

SetGradientColourBorder(border) [source]

Sets the tab border colour.

Parameters: border – the border colour, an instance of wx.Colour.

SetGradientColourFrom(fr) [source]

Sets the starting colour for the gradient.

Parameters: fr – the first gradient colour, an instance of wx.Colour.

SetGradientColourTo(to) [source]

Sets the ending colour for the gradient.

Parameters: to – the second gradient colour, an instance of wx.Colour;

SetGradientColours(fr, to, border) [source]

Sets the gradient colours for the tab.

Parameters:
  • fr – the first gradient colour, an instance of wx.Colour;

  • to – the second gradient colour, an instance of wx.Colour;

  • border – the border colour, an instance of wx.Colour.

SetImageList(imageList) [source]

Sets the image list for the page control.

Parameters: imageList – an instance of wx.ImageList.

SetNavigatorIcon(bmp) [source]

Set the icon used by the TabNavigatorWindow.

Parameters: bmp – a valid wx.Bitmap object.

SetNonActiveTabTextColour(colour) [source]

Sets the non active tabs text colour.

Parameters: colour – a valid wx.Colour object or any typemap supported by wxWidgets/wxPython to generate a colour (i.e., a hex string, a colour name, a 3 or 4 integer tuple).

SetPadding(padding) [source]

Sets the amount of space around each page’s icon and label, in pixels.

Parameters: padding – the amount of space around each page’s icon and label, in pixels.

Note

Only the horizontal padding is considered.

SetPageImage(page, image) [source]

Sets the image index for the given page.

Parameters:
  • page – an integer specifying the page index;
  • image – an index into the image list which was set with SetImageList.

SetPageShapeAngle(page_index, angle) [source]

Sets the angle associated to a tab.

Parameters:
  • page_index – the index of the tab for which we wish to get the shape angle;
  • angle – the new shape angle for the tab (must be less than 15 degrees).

SetPageText(page, text) [source]

Sets the text for the given page.

Parameters:
  • page – an integer specifying the page index;
  • text – the new tab label.

SetPageTextColour(page, colour) [source]

Sets the tab text colour individually.

Parameters:
  • page – an integer specifying the page index;
  • colour – a valid wx.Colour object or any typemap supported by wxWidgets/wxPython to generate a colour (i.e., a hex string, a colour name, a 3 or 4 integer tuple). You can pass None or wx.NullColour to return to the default page text colour.

SetRightClickMenu(menu) [source]

Sets the popup menu associated to a right click on a tab.

Parameters: menu – an instance of wx.Menu.

SetSelection(page) [source]

Sets the selection for the given page.

Parameters: page – an integer specifying the new selected page.

Note

The call to this function does not generate the page changing events.

SetTabAreaColour(colour) [source]

Sets the area behind the tabs colour.

Parameters: colour – a valid wx.Colour object or any typemap supported by wxWidgets/wxPython to generate a colour (i.e., a hex string, a colour name, a 3 or 4 integer tuple).

ShowCustomPage(show=True) [source]

Hides the custom panel which is shown when there are no pages left in FlatNotebook.

ShowTabs() [source]

Shows the tabs if hidden previously.

Tile(orient=None) [source]

Shows pages in column/row mode (one panel after the other in columns/rows).

Parameters: orient – this parameter represents the orientation of the stacked panels. Pass wx.VERTICAL to get vertically stacked panels, wx.HORIZONTAL to get horizontally stacked panels or None to return to the default FlatNotebook behaviour with tabs.

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • infobar
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • flatnotebook »
  • FlatNotebook


FlatNotebookCompatible

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • flatnotebook »
  • FlatNotebookCompatible

FlatNotebookCompatible

This class is more compatible with the wx.Notebook API, especially regarding page changing events. Use the SetSelection method if you wish to send page changing events, or ChangeSelection otherwise.

hierarchy Inheritance Diagram

Inheritance diagram for: FlatNotebookCompatible

Inheritance diagram of FlatNotebookCompatible

supclasses Known Superclasses

  • flatnotebook.FlatNotebook

Methods Summary

__init__ | Default class constructor.
ChangeSelection | Sets the selection for the given page.
SetSelection | Sets the selection for the given page.

API Class API

class FlatNotebookCompatible(FlatNotebook) [source]

This class is more compatible with the wx.Notebook API, especially regarding page changing events. Use the FlatNotebookCompatible.SetSelection() method if you wish to send page changing events, or FlatNotebookCompatible.ChangeSelection() otherwise.

__init__(parent, id=wx.ID_ANY, pos=wx.DefaultPosition, size=wx.DefaultSize, style=0, agwStyle=0, name="FlatNotebook") [source]

Default class constructor.

Parameters:
  • parent – the FlatNotebook parent;
  • id – an identifier for the control: a value of -1 is taken to mean a default;
  • pos – the control position. A value of (-1, -1) indicates a default position, chosen by either the windowing system or wxPython, depending on platform;
  • size – the control size. A value of (-1, -1) indicates a default size, chosen by either the windowing system or wxPython, depending on platform;
  • style – the underlying wx.PyPanel window style;
  • agwStyle – the AGW-specific window style. This can be a combination of the following bits:

    Window Styles | Hex Value | Description
    FNB_VC71 | 0x1 | Use Visual Studio 2003 (VC7.1) style for tabs.
    FNB_FANCY_TABS | 0x2 | Use fancy style - square tabs filled with gradient colouring.
    FNB_TABS_BORDER_SIMPLE | 0x4 | Draw thin border around the page.
    FNB_NO_X_BUTTON | 0x8 | Do not display the ‘X’ button.
    FNB_NO_NAV_BUTTONS | 0x10 | Do not display the right/left arrows.
    FNB_MOUSE_MIDDLE_CLOSES_TABS | 0x20 | Use the mouse middle button for cloing tabs.
    FNB_BOTTOM | 0x40 | Place tabs at bottom - the default is to place them at top.
    FNB_NODRAG | 0x80 | Disable dragging of tabs.
    FNB_VC8 | 0x100 | Use Visual Studio 2005 (VC8) style for tabs.
    FNB_X_ON_TAB | 0x200 | Place ‘X’ close button on the active tab.
    FNB_BACKGROUND_GRADIENT | 0x400 | Use gradients to paint the tabs background.
    FNB_COLOURFUL_TABS | 0x800 | Use colourful tabs (VC8 style only).
    FNB_DCLICK_CLOSES_TABS | 0x1000 | Style to close tab using double click.
    FNB_SMART_TABS | 0x2000 | Use Smart Tabbing, like Alt + Tab on Windows.
    FNB_DROPDOWN_TABS_LIST | 0x4000 | Use a dropdown menu on the left in place of the arrows.
    FNB_ALLOW_FOREIGN_DND | 0x8000 | Allows drag ‘n’ drop operations between different FlatNotebook.
    FNB_HIDE_ON_SINGLE_TAB | 0x10000 | Hides the Page Container when there is one or fewer tabs.
    FNB_DEFAULT_STYLE | 0x10020 | FlatNotebook default style.
    FNB_FF2 | 0x20000 | Use Firefox 2 style for tabs.
    FNB_NO_TAB_FOCUS | 0x40000 | Does not allow tabs to have focus.
    FNB_RIBBON_TABS | 0x80000 | Use the Ribbon Tabs style.
    FNB_HIDE_TABS | 0x100000 | Hides the Page Container allowing only keyboard navigation
    FNB_NAV_BUTTONS_WHEN_NEEDED | 0x200000 | Hides the navigation left/right arrows if all tabs fit
  • name – the window name.

ChangeSelection(page) [source]

Sets the selection for the given page.

Parameters: page – an integer specifying the new selected page.

Note

The call to this function does not generate the page changing events.

SetSelection(page) [source]

Sets the selection for the given page.

Parameters: page – an integer specifying the new selected page.

Note

The call to this function generates the page changing events.

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • infobar
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • flatnotebook »
  • FlatNotebookCompatible


FlatNotebookDragEvent

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • flatnotebook »
  • FlatNotebookDragEvent

FlatNotebookDragEvent

This event will be sent when a EVT_FLATNOTEBOOK_PAGE_DRAGGED_FOREIGN is mapped in the parent.

hierarchy Inheritance Diagram

Inheritance diagram for: FlatNotebookDragEvent

Inheritance diagram of FlatNotebookDragEvent

supclasses Known Superclasses

  • flatnotebook.FlatNotebookEvent

Methods Summary

__init__ | Default class constructor.
GetNotebook | Returns the new notebook.
GetOldNotebook | Returns the old notebook.
SetNotebook | Sets the new notebook.
SetOldNotebook | Sets the old notebook.

API Class API

class FlatNotebookDragEvent(FlatNotebookEvent) [source]

This event will be sent when a EVT_FLATNOTEBOOK_PAGE_DRAGGED_FOREIGN is mapped in the parent.

__init__(eventType, eventId=1, nSel=-1, nOldSel=-1) [source]

Default class constructor.

Parameters:
  • eventType – the event type;
  • eventId – the event identifier;
  • nSel – the current selection;
  • nOldSel – the old selection.

GetNotebook() [source]

Returns the new notebook.

GetOldNotebook() [source]

Returns the old notebook.

SetNotebook(notebook) [source]

Sets the new notebook.

Parameters: notebook – an instance of FlatNotebook.

SetOldNotebook(old) [source]

Sets the old notebook.

Parameters: notebook – an instance of FlatNotebook.

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • infobar
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • flatnotebook »
  • FlatNotebookDragEvent


FlatNotebookEvent

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • flatnotebook »
  • FlatNotebookEvent

FlatNotebookEvent

This events will be sent when a EVT_FLATNOTEBOOK_PAGE_CHANGED, EVT_FLATNOTEBOOK_PAGE_CHANGING, EVT_FLATNOTEBOOK_PAGE_CLOSING, EVT_FLATNOTEBOOK_PAGE_CLOSED and EVT_FLATNOTEBOOK_PAGE_CONTEXT_MENU is mapped in the parent.

hierarchy Inheritance Diagram

Inheritance diagram for: FlatNotebookEvent

Inheritance diagram of FlatNotebookEvent

subclasses Known Subclasses

  • flatnotebook.FlatNotebookDragEvent

Methods Summary

__init__ | Default class constructor.
Allow | This is the opposite of Veto: it explicitly allows the event to be processed.
GetNotifyEvent | Returns the actual wx.NotifyEvent.
GetOldSelection | Returns the page that was selected before the change, -1 if none was selected.
GetSelection | Returns the currently selected page, or -1 if none was selected.
IsAllowed | Returns True if the change is allowed (Veto hasn’t been called) or
SetOldSelection | Sets the id of the page selected before the change.
SetSelection | Sets the event selection.
Veto | Prevents the change announced by this event from happening.

API Class API

class FlatNotebookEvent(wx.PyCommandEvent) [source]

This events will be sent when a EVT_FLATNOTEBOOK_PAGE_CHANGED, EVT_FLATNOTEBOOK_PAGE_CHANGING, EVT_FLATNOTEBOOK_PAGE_CLOSING, EVT_FLATNOTEBOOK_PAGE_CLOSED and EVT_FLATNOTEBOOK_PAGE_CONTEXT_MENU is mapped in the parent.

__init__(eventType, eventId=1, nSel=-1, nOldSel=-1) [source]

Default class constructor.

Parameters:
  • eventType – the event type;
  • eventId – the event identifier;
  • nSel – the current selection;
  • nOldSel – the old selection.

Allow() [source]

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

GetNotifyEvent() [source]

Returns the actual wx.NotifyEvent.

GetOldSelection() [source]

Returns the page that was selected before the change, -1 if none was selected.

GetSelection() [source]

Returns the currently selected page, or -1 if none was selected.

IsAllowed() [source]

Returns True if the change is allowed (Veto hasn’t been called) or False otherwise (if it was).

SetOldSelection(nOldSel) [source]

Sets the id of the page selected before the change.

Parameters: nOldSel – an integer specifying the old selection.

SetSelection(nSel) [source]

Sets the event selection.

Parameters: nSel – an integer specifying the new selection.

Veto() [source]

Prevents the change announced by this event from happening.

Note

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

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • infobar
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • flatnotebook »
  • FlatNotebookEvent


FNBDragInfo

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • flatnotebook »
  • FNBDragInfo

FNBDragInfo

Stores all the information to allow drag and drop between different FlatNotebook instances.

hierarchy Inheritance Diagram

Inheritance diagram for: FNBDragInfo

Inheritance diagram of FNBDragInfo

Methods Summary

__init__ | Default class constructor.
GetContainer | Returns the FlatNotebook page (usually a panel).
GetPageIndex | Returns the page index associated with a page.

API Class API

class FNBDragInfo(object) [source]

Stores all the information to allow drag and drop between different FlatNotebook instances.

__init__(container, pageindex) [source]

Default class constructor.

Parameters:
  • container – the drag and drop container, a page in FlatNotebook;
  • pageindex – the index of the tab that is actually being dragged.

GetContainer() [source]

Returns the FlatNotebook page (usually a panel).

GetPageIndex() [source]

Returns the page index associated with a page.

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • infobar
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • flatnotebook »
  • FNBDragInfo


FNBDropSource

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • flatnotebook »
  • FNBDropSource

FNBDropSource

Give some custom UI feedback during the drag and drop operation in this function. It is called on each mouse move, so your implementation must not be too slow.

hierarchy Inheritance Diagram

Inheritance diagram for: FNBDropSource

Inheritance diagram of FNBDropSource

Methods Summary

__init__ | Default class constructor.
GiveFeedback | You may give some custom UI feedback during the drag and drop operation

API Class API

class FNBDropSource(wx.DropSource) [source]

Give some custom UI feedback during the drag and drop operation in this function. It is called on each mouse move, so your implementation must not be too slow.

__init__(win) [source]

Default class constructor. Used internally.

Parameters: win – the source window for which we wish to provide UI feedback during drag and drop operations.

GiveFeedback(effect) [source]

You may give some custom UI feedback during the drag and drop operation in this function. It is called on each mouse move, so your implementation must not be too slow.

Parameters: effect – the effect to implement. One of wx.DragCopy, wx.DragMove, wx.DragLink and wx.DragNone.
Returns: Return False if you want default feedback, or True if you implement your own feedback. The return values is ignored under GTK.

Note

To show your own custom drag and drop UI feedback, you must override this method.

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • infobar
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • flatnotebook »
  • FNBDropSource


FNBDropTarget

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • flatnotebook »
  • FNBDropTarget

FNBDropTarget

Class used to handle the OnDropTarget method when dragging and dropping between different FlatNotebook instances.

hierarchy Inheritance Diagram

Inheritance diagram for: FNBDropTarget

Inheritance diagram of FNBDropTarget

Methods Summary

__init__ | Default class constructor.
OnData | Called after OnDrop returns True.

API Class API

class FNBDropTarget(wx.DropTarget) [source]

Class used to handle the FlatNotebook.OnDropTarget() method when dragging and dropping between different FlatNotebook instances.

__init__(parent) [source]

Default class constructor.

Parameters: parent – the window handling the drag and drop, an instance of FlatNotebook.

OnData(x, y, dragres) [source]

Called after OnDrop returns True.

By default this will usually call GetData and will return the suggested default value dragres.

Parameters:
  • x – the current x position of the mouse while dragging and dropping;
  • y – the current y position of the mouse while dragging and dropping;
  • dragres – an optional default return value.

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • infobar
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • flatnotebook »
  • FNBDropTarget


FNBRenderer

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • flatnotebook »
  • FNBRenderer

FNBRenderer

Parent class for the 6 renderers defined: Standard, VC71, Fancy, Firefox 2, VC8 and Ribbon. This class implements the common methods of all 6 renderers.

hierarchy Inheritance Diagram

Inheritance diagram for: FNBRenderer

Inheritance diagram of FNBRenderer

subclasses Known Subclasses

  • flatnotebook.FNBRendererDefault
  • flatnotebook.FNBRendererFancy
  • flatnotebook.FNBRendererFirefox2
  • flatnotebook.FNBRendererRibbonTabs
  • flatnotebook.FNBRendererVC71
  • flatnotebook.FNBRendererVC8

Methods Summary

__init__ | Default class constructor.
CalcTabHeight | Calculates the height of the input tab.
CalcTabWidth | Calculates the width of the input tab.
DrawArrowAccordingToState | Draws the left and right scrolling arrows.
DrawDragHint | Draws tab drag hint, the default implementation is to do nothing.
DrawDropDownArrow | Draws the drop-down arrow in the navigation area.
DrawFocusRectangle | Draws a focus rectangle like the native wx.Notebook.
DrawLeftArrow | Draws the left navigation arrow.
DrawRightArrow | Draws the right navigation arrow.
DrawTabX | Draws the ‘X’ in the selected tab.
DrawTabs | Actually draws the tabs in FlatNotebook.
DrawTabsLine | Draws a line over the tabs.
DrawX | Draw the ‘X’ navigation button in the navigation area.
GetButtonsAreaLength | Returns the navigation area width.
GetDropArrowButtonPos | Returns the drop down button position in the navigation area.
GetLeftButtonPos | Returns the left button position in the navigation area.
GetRightButtonPos | Returns the right button position in the navigation area.
GetXPos | Returns the ‘X’ button position in the navigation area.
NumberTabsCanFit | Calculates the number of tabs that can fit on the available space on screen.

API Class API

class FNBRenderer(object) [source]

Parent class for the 6 renderers defined: Standard, VC71, Fancy, Firefox 2, VC8 and Ribbon. This class implements the common methods of all 6 renderers.

__init__() [source]

Default class constructor.

CalcTabHeight(pageContainer) [source]

Calculates the height of the input tab.

Parameters: pageContainer – an instance of FlatNotebook.

CalcTabWidth(pageContainer, tabIdx, tabHeight) [source]

Calculates the width of the input tab.

Parameters:
  • pageContainer – an instance of FlatNotebook;
  • tabIdx – the index of the input tab;
  • tabHeight – the height of the tab.

DrawArrowAccordingToState(dc, pc, rect) [source]

Draws the left and right scrolling arrows.

Parameters:
  • dc – an instance of wx.DC;
  • pc – an instance of FlatNotebook;
  • rect – the client rectangle containing the scrolling arrows.

DrawDragHint(pc, tabIdx) [source]

Draws tab drag hint, the default implementation is to do nothing. You can override this function to provide a nice feedback to user.

Parameters:
  • pc – an instance of FlatNotebook;
  • tabIdx – the index of the tab we are dragging.

Note

To show your own custom drag and drop UI feedback, you must override this method in your derived class.

DrawDropDownArrow(pageContainer, dc) [source]

Draws the drop-down arrow in the navigation area.

Parameters:
  • pageContainer – an instance of FlatNotebook;
  • dc – an instance of wx.DC.

DrawFocusRectangle(dc, pageContainer, page) [source]

Draws a focus rectangle like the native wx.Notebook.

Parameters:
  • dc – an instance of wx.DC;

  • pageContainer – an instance of FlatNotebook;
  • page – an instance of PageInfo, representing a page in the notebook.

DrawLeftArrow(pageContainer, dc) [source]

Draws the left navigation arrow.

Parameters:
  • pageContainer – an instance of FlatNotebook;
  • dc – an instance of wx.DC.

DrawRightArrow(pageContainer, dc) [source]

Draws the right navigation arrow.

Parameters:
  • pageContainer – an instance of FlatNotebook;
  • dc – an instance of wx.DC.

DrawTabX(pageContainer, dc, rect, tabIdx, btnStatus) [source]

Draws the ‘X’ in the selected tab.

Parameters:
  • pageContainer – an instance of FlatNotebook;
  • dc – an instance of wx.DC;

  • rect – the current tab client rectangle;
  • tabIdx – the index of the current tab;
  • btnStatus – the status of the ‘X’ button in the current tab.

DrawTabs(pageContainer, dc) [source]

Actually draws the tabs in FlatNotebook.

Parameters:
  • pageContainer – an instance of FlatNotebook;
  • dc – an instance of wx.DC.

DrawTabsLine(pageContainer, dc, selTabX1=-1, selTabX2=-1) [source]

Draws a line over the tabs.

Parameters:
  • pageContainer – an instance of FlatNotebook;
  • dc – an instance of wx.DC;

  • selTabX1 – first x coordinate of the tab line;
  • selTabX2 – second x coordinate of the tab line.

DrawX(pageContainer, dc) [source]

Draw the ‘X’ navigation button in the navigation area.

Parameters:
  • pageContainer – an instance of FlatNotebook;
  • dc – an instance of wx.DC.

GetButtonsAreaLength(pageContainer) [source]

Returns the navigation area width.

Parameters: pageContainer – an instance of FlatNotebook.

GetDropArrowButtonPos(pageContainer) [source]

Returns the drop down button position in the navigation area.

Parameters: pageContainer – an instance of FlatNotebook.

GetLeftButtonPos(pageContainer) [source]

Returns the left button position in the navigation area.

Parameters: pageContainer – an instance of FlatNotebook.

GetRightButtonPos(pageContainer) [source]

Returns the right button position in the navigation area.

Parameters: pageContainer – an instance of FlatNotebook.

GetXPos(pageContainer) [source]

Returns the ‘X’ button position in the navigation area.

Parameters: pageContainer – an instance of FlatNotebook.

NumberTabsCanFit(pageContainer, fr=-1) [source]

Calculates the number of tabs that can fit on the available space on screen.

Parameters:
  • pageContainer – an instance of FlatNotebook;
  • fr – the current first visible tab.

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • infobar
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • flatnotebook »
  • FNBRenderer


FNBRendererDefault

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • flatnotebook »
  • FNBRendererDefault

FNBRendererDefault

This class handles the drawing of tabs using the standard renderer.

hierarchy Inheritance Diagram

Inheritance diagram for: FNBRendererDefault

Inheritance diagram of FNBRendererDefault

supclasses Known Superclasses

  • flatnotebook.FNBRenderer

Methods Summary

__init__ | Default class constructor.
DrawTab | Draws a tab using the Standard style.

API Class API

class FNBRendererDefault(FNBRenderer) [source]

This class handles the drawing of tabs using the standard renderer.

__init__() [source]

Default class constructor.

DrawTab(pageContainer, dc, posx, tabIdx, tabWidth, tabHeight, btnStatus) [source]

Draws a tab using the Standard style.

Parameters:
  • pageContainer – an instance of FlatNotebook;
  • dc – an instance of wx.DC;
  • posx – the x position of the tab;
  • tabIdx – the index of the tab;
  • tabWidth – the tab’s width;
  • tabHeight – the tab’s height;
  • btnStatus – the status of the ‘X’ button inside this tab.

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • infobar
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • flatnotebook »
  • FNBRendererDefault


FNBRendererFancy

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • flatnotebook »
  • FNBRendererFancy

FNBRendererFancy

This class handles the drawing of tabs using the Fancy renderer.

hierarchy Inheritance Diagram

Inheritance diagram for: FNBRendererFancy

Inheritance diagram of FNBRendererFancy

supclasses Known Superclasses

  • flatnotebook.FNBRenderer

Methods Summary

__init__ | Default class constructor.
DrawTab | Draws a tab using the Fancy style, similar to the VC71 one but with gradients.

API Class API

class FNBRendererFancy(FNBRenderer) [source]

This class handles the drawing of tabs using the Fancy renderer.

__init__() [source]

Default class constructor.

DrawTab(pageContainer, dc, posx, tabIdx, tabWidth, tabHeight, btnStatus) [source]

Draws a tab using the Fancy style, similar to the VC71 one but with gradients.

Parameters:
  • pageContainer – an instance of FlatNotebook;
  • dc – an instance of wx.DC;
  • posx – the x position of the tab;
  • tabIdx – the index of the tab;
  • tabWidth – the tab’s width;
  • tabHeight – the tab’s height;
  • btnStatus – the status of the ‘X’ button inside this tab.

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • infobar
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • flatnotebook »
  • FNBRendererFancy


FNBRendererFirefox2

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • flatnotebook »
  • FNBRendererFirefox2

FNBRendererFirefox2

This class handles the drawing of tabs using the Firefox 2 renderer.

hierarchy Inheritance Diagram

Inheritance diagram for: FNBRendererFirefox2

Inheritance diagram of FNBRendererFirefox2

supclasses Known Superclasses

  • flatnotebook.FNBRenderer

Methods Summary

__init__ | Default class constructor.
DrawTab | Draws a tab using the Firefox 2 style.

API Class API

class FNBRendererFirefox2(FNBRenderer) [source]

This class handles the drawing of tabs using the Firefox 2 renderer.

__init__() [source]

Default class constructor.

DrawTab(pageContainer, dc, posx, tabIdx, tabWidth, tabHeight, btnStatus) [source]

Draws a tab using the Firefox 2 style.

Parameters:
  • pageContainer – an instance of FlatNotebook;
  • dc – an instance of wx.DC;
  • posx – the x position of the tab;
  • tabIdx – the index of the tab;
  • tabWidth – the tab’s width;
  • tabHeight – the tab’s height;
  • btnStatus – the status of the ‘X’ button inside this tab.

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • infobar
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • flatnotebook »
  • FNBRendererFirefox2


FNBRendererMgr

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • flatnotebook »
  • FNBRendererMgr

FNBRendererMgr

This class represents a manager that handles all the 6 renderers defined and calls the appropriate one when drawing is needed.

hierarchy Inheritance Diagram

Inheritance diagram for: FNBRendererMgr

Inheritance diagram of FNBRendererMgr

Methods Summary

__init__ | Default class constructor.
GetRenderer | Returns the current renderer based on the style selected.

API Class API

class FNBRendererMgr(object) [source]

This class represents a manager that handles all the 6 renderers defined and calls the appropriate one when drawing is needed.

__init__() [source]

Default class constructor.

GetRenderer(style) [source]

Returns the current renderer based on the style selected.

Parameters: style – represents one of the 6 implemented styles for FlatNotebook, namely one of these bits:

Tabs style | Hex Value | Description
FNB_VC71 | 0x1 | Use Visual Studio 2003 (VC7.1) style for tabs
FNB_FANCY_TABS | 0x2 | Use fancy style - square tabs filled with gradient colouring
FNB_VC8 | 0x100 | Use Visual Studio 2005 (VC8) style for tabs
FNB_FF2 | 0x20000 | Use Firefox 2 style for tabs
FNB_RIBBON_TABS | 0x80000 | Use the Ribbon Tabs style to render the tabs

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • infobar
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • flatnotebook »
  • FNBRendererMgr


FNBRendererRibbonTabs

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • flatnotebook »
  • FNBRendererRibbonTabs

FNBRendererRibbonTabs

This class handles the drawing of tabs using the Ribbon Tabs renderer.

hierarchy Inheritance Diagram

Inheritance diagram for: FNBRendererRibbonTabs

Inheritance diagram of FNBRendererRibbonTabs

supclasses Known Superclasses

  • flatnotebook.FNBRenderer

Methods Summary

__init__ | Default class constructor.
CalcTabWidth | Calculates the width of the input tab.
DrawTab | Draws a tab using the Ribbon Tabs style.
DrawTabs | Actually draws the tabs in FlatNotebook.

API Class API

class FNBRendererRibbonTabs(FNBRenderer) [source]

This class handles the drawing of tabs using the Ribbon Tabs renderer.

__init__() [source]

Default class constructor.

CalcTabWidth(pageContainer, tabIdx, tabHeight) [source]

Calculates the width of the input tab.

Parameters:
  • pageContainer – an instance of FlatNotebook;
  • tabIdx – the index of the input tab;
  • tabHeight – the height of the tab.

DrawTab(pageContainer, dc, posx, tabIdx, tabWidth, tabHeight, btnStatus) [source]

Draws a tab using the Ribbon Tabs style.

Parameters:
  • pageContainer – an instance of FlatNotebook;
  • dc – an instance of wx.DC;
  • posx – the x position of the tab;
  • tabIdx – the index of the tab;
  • tabWidth – the tab’s width;
  • tabHeight – the tab’s height;
  • btnStatus – the status of the ‘X’ button inside this tab.

DrawTabs(pageContainer, dc) [source]

Actually draws the tabs in FlatNotebook.

Parameters:
  • pageContainer – an instance of FlatNotebook;
  • dc – an instance of wx.DC.

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • infobar
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • flatnotebook »
  • FNBRendererRibbonTabs


FNBRendererVC8

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • flatnotebook »
  • FNBRendererVC8

FNBRendererVC8

This class handles the drawing of tabs using the VC8 renderer.

hierarchy Inheritance Diagram

Inheritance diagram for: FNBRendererVC8

Inheritance diagram of FNBRendererVC8

supclasses Known Superclasses

  • flatnotebook.FNBRenderer

Methods Summary

__init__ | Default class constructor.
DrawTab | Draws a tab using the VC8 style.
DrawTabs | Draws all the tabs using VC8 style.
FillVC8GradientColour | Fills a tab with a gradient shading.
GetEndX | Returns the x end position of a tab.
GetStartX | Returns the x start position of a tab.
NumberTabsCanFit | Calculates the number of tabs that can fit on the available space on screen.

API Class API

class FNBRendererVC8(FNBRenderer) [source]

This class handles the drawing of tabs using the VC8 renderer.

__init__() [source]

Default class constructor.

DrawTab(pageContainer, dc, posx, tabIdx, tabWidth, tabHeight, btnStatus) [source]

Draws a tab using the VC8 style.

Parameters:
  • pageContainer – an instance of FlatNotebook;
  • dc – an instance of wx.DC;
  • posx – the x position of the tab;
  • tabIdx – the index of the tab;
  • tabWidth – the tab’s width;
  • tabHeight – the tab’s height;
  • btnStatus – the status of the ‘X’ button inside this tab.

DrawTabs(pageContainer, dc) [source]

Draws all the tabs using VC8 style.

Parameters:
  • pageContainer – an instance of FlatNotebook;
  • dc – an instance of wx.DC.

FillVC8GradientColour(pageContainer, dc, tabPoints, bSelectedTab, tabIdx) [source]

Fills a tab with a gradient shading.

Parameters:
  • pageContainer – an instance of FlatNotebook;
  • dc – an instance of wx.DC;

  • tabPoints – a Python list of wx.Point representing the tab outline;
  • bSelectedTab – True if the tab is selected, False otherwise;
  • tabIdx – the index of the tab;

GetEndX(tabPoints, y, style) [source]

Returns the x end position of a tab.

Parameters:
  • tabPoints – a Python list of wx.Point representing the tab outline;

  • y – the y end position of the tab;
  • style – can be FNB_BOTTOM or the default (tabs at top).

GetStartX(tabPoints, y, style) [source]

Returns the x start position of a tab.

Parameters:
  • tabPoints – a Python list of wx.Point representing the tab outline;

  • y – the y start position of the tab;
  • style – can be FNB_BOTTOM or the default (tabs at top).

NumberTabsCanFit(pageContainer, fr=-1) [source]

Calculates the number of tabs that can fit on the available space on screen.

Parameters:
  • pageContainer – an instance of FlatNotebook;
  • fr – the current first visible tab.

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • infobar
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • flatnotebook »
  • FNBRendererVC8


FNBRendererVC71

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • flatnotebook »
  • FNBRendererVC71

FNBRendererVC71

This class handles the drawing of tabs using the VC71 renderer.

hierarchy Inheritance Diagram

Inheritance diagram for: FNBRendererVC71

Inheritance diagram of FNBRendererVC71

supclasses Known Superclasses

  • flatnotebook.FNBRenderer

Methods Summary

__init__ | Default class constructor.
DrawTab | Draws a tab using the VC71 style.

API Class API

class FNBRendererVC71(FNBRenderer) [source]

This class handles the drawing of tabs using the VC71 renderer.

__init__() [source]

Default class constructor.

DrawTab(pageContainer, dc, posx, tabIdx, tabWidth, tabHeight, btnStatus) [source]

Draws a tab using the VC71 style.

Parameters:
  • pageContainer – an instance of FlatNotebook;
  • dc – an instance of wx.DC;
  • posx – the x position of the tab;
  • tabIdx – the index of the tab;
  • tabWidth – the tab’s width;
  • tabHeight – the tab’s height;
  • btnStatus – the status of the ‘X’ button inside this tab.

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • infobar
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • flatnotebook »
  • FNBRendererVC71


PageContainer

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • flatnotebook »
  • PageContainer

PageContainer

This class acts as a container for the pages you add to FlatNotebook.

hierarchy Inheritance Diagram

Inheritance diagram for: PageContainer

Inheritance diagram of PageContainer

Methods Summary

__init__ | Default class constructor.
AddPage | Adds a page to the PageContainer.
AdvanceSelection | Cycles through the tabs.
AssignImageList | Assigns the image list for the PageContainer.
CanFitToScreen | Returns wheter a tab can fit in the left space in the screen or not.
ClearAGWFlag | Deletes a flag from the FlatNotebook style.
DeleteAllPages | Deletes all the pages in the PageContainer.
DeletePage | Delete the specified page from PageContainer.
DoDeletePage | Does the actual page deletion.
DoSetSelection | Does the actual selection of a page.
DrawDragHint | Draws small arrow at the place that the tab will be placed.
EnableTab | Enables or disables a tab.
FireEvent | Fires the EVT_FLATNOTEBOOK_PAGE_CHANGING and EVT_FLATNOTEBOOK_PAGE_CHANGED
GetAGWWindowStyleFlag | Returns the FlatNotebook window style.
GetEnabled | Returns whether a tab is enabled or not.
GetImageList | Returns the image list for the page control.
GetLastVisibleTab | Returns the last visible tab in the tab area.
GetNumOfVisibleTabs | Returns the number of visible tabs.
GetNumTabsCanScrollLeft | Returns the number of tabs than can be scrolled left.
GetPageCount | Returns the number of tabs in the FlatNotebook control.
GetPageImage | Returns the image index associated to a page.
GetPageText | Returns the tab caption of the page.
GetPageTextColour | Returns the tab text colour if it has been set previously, or None otherwise.
GetSelection | Returns the current selected page.
GetSingleLineBorderColour | Returns the colour for the single line border.
HasAGWFlag | Returns whether a flag is present in the FlatNotebook style.
HitTest | HitTest method for PageContainer.
InsertPage | Inserts a new page at the specified position.
IsDefaultTabs | Returns whether a tab has a default style.
IsMouseHovering | Returns whether or not the mouse is hovering over this page’s tab
IsTabVisible | Returns whether a tab is visible or not.
MoveTabPage | Moves a tab inside the same FlatNotebook.
OnDropTarget | Handles the drop action from a drag and drop operation.
OnEraseBackground | Handles the wx.EVT_ERASE_BACKGROUND event for PageContainer.
OnKeyDown | Handles the wx.EVT_KEY_DOWN event for PageContainer.
OnKillFocus | Handles the wx.EVT_KILL_FOCUS event for PageContainer.
OnLeftDClick | Handles the wx.EVT_LEFT_DCLICK event for PageContainer.
OnLeftDown | Handles the wx.EVT_LEFT_DOWN event for PageContainer.
OnLeftUp | Handles the wx.EVT_LEFT_UP event for PageContainer.
OnMiddleDown | Handles the wx.EVT_MIDDLE_DOWN event for PageContainer.
OnMouseEnterWindow | Handles the wx.EVT_ENTER_WINDOW event for PageContainer.
OnMouseLeave | Handles the wx.EVT_LEAVE_WINDOW event for PageContainer.
OnMouseMove | Handles the wx.EVT_MOTION event for PageContainer.
OnMouseWheel | Handles the wx.EVT_MOUSEWHEEL event for PageContainer.
OnPaint | Handles the wx.EVT_PAINT event for PageContainer.
OnRightDown | Handles the wx.EVT_RIGHT_DOWN event for PageContainer.
OnSetFocus | Handles the wx.EVT_SET_FOCUS event for PageContainer.
OnSize | Handles the wx.EVT_SIZE event for PageContainer.
OnTabMenuSelection | Handles the wx.EVT_MENU event for PageContainer.
PopupTabsMenu | Pops up the menu activated with the drop down arrow in the navigation area.
RotateLeft | Scrolls tabs to the left by bulk of 5 tabs.
RotateRight | Scrolls tabs to the right by bulk of 5 tabs.
SetAGWWindowStyleFlag | Sets the FlatNotebook window style.
SetFocusedPage | Sets/Unsets the focus on the appropriate page.
SetImageList | Sets the image list for the PageContainer.
SetPageImage | Sets the image index for the given page.
SetPageText | Sets the tab caption of the page.
SetPageTextColour | Sets the tab text colour individually.
SetSelection | Sets the selected page.
ShowTabTooltip | Shows a tab tooltip.
TabHasImage | Returns whether a tab has an associated image index or not.
_ReShow | Handles the redraw of the tabs when the FNB_HIDE_ON_SINGLE_TAB has been removed.

API Class API

class PageContainer(wx.PyPanel) [source]

This class acts as a container for the pages you add to FlatNotebook.

__init__(parent, id=wx.ID_ANY, pos=wx.DefaultPosition, size=wx.DefaultSize, style=0) [source]

Default class constructor.

Used internally, do not call it in your code!

Parameters:
  • parent – the PageContainer parent;
  • id – an identifier for the control: a value of -1 is taken to mean a default;
  • pos – the control position. A value of (-1, -1) indicates a default position, chosen by either the windowing system or wxPython, depending on platform;
  • size – the control size. A value of (-1, -1) indicates a default size, chosen by either the windowing system or wxPython, depending on platform;
  • style – the window style.

AddPage(caption, selected=False, imgindex=-1) [source]

Adds a page to the PageContainer.

Parameters:
  • page – specifies the new page;
  • text – specifies the text for the new page;
  • select – specifies whether the page should be selected;
  • imageId – specifies the optional image index for the new page.

AdvanceSelection(forward=True) [source]

Cycles through the tabs.

Parameters: forward – if True, the selection is advanced in ascending order (to the right), otherwise the selection is advanced in descending order.

Note

The call to this function generates the page changing events.

AssignImageList(imglist) [source]

Assigns the image list for the PageContainer.

Parameters: imageList – an instance of wx.ImageList.

CanFitToScreen(page) [source]

Returns wheter a tab can fit in the left space in the screen or not.

Parameters: page – an integer specifying the page index.

ClearAGWFlag(flag) [source]

Deletes a flag from the FlatNotebook style.

Parameters: flag – one of the possible FlatNotebook window styles.

See also

FlatNotebook.SetAGWWindowStyleFlag() for a list of possible window style flags.

DeleteAllPages() [source]

Deletes all the pages in the PageContainer.

DeletePage(page) [source]

Delete the specified page from PageContainer.

Parameters: page – an integer specifying the page index.

DoDeletePage(page) [source]

Does the actual page deletion.

Parameters: page – an integer specifying the page index.

DoSetSelection(page) [source]

Does the actual selection of a page.

Parameters: page – an integer specifying the page index.

DrawDragHint() [source]

Draws small arrow at the place that the tab will be placed.

EnableTab(page, enabled=True) [source]

Enables or disables a tab.

Parameters:
  • page – an integer specifying the page index;
  • enabled – True to enable a tab, False to disable it.

FireEvent(selection) [source]

Fires the EVT_FLATNOTEBOOK_PAGE_CHANGING and EVT_FLATNOTEBOOK_PAGE_CHANGED events called from other methods (from menu selection or Smart Tabbing).

This is an utility function.

Parameters: selection – the new selection inside FlatNotebook.

GetAGWWindowStyleFlag() [source]

Returns the FlatNotebook window style.

See also

The FlatNotebook.__init__() method for the agwStyle parameter description.

GetEnabled(page) [source]

Returns whether a tab is enabled or not.

Parameters: page – an integer specifying the page index.

GetImageList() [source]

Returns the image list for the page control.

GetLastVisibleTab() [source]

Returns the last visible tab in the tab area.

GetNumOfVisibleTabs() [source]

Returns the number of visible tabs.

GetNumTabsCanScrollLeft() [source]

Returns the number of tabs than can be scrolled left.

GetPageCount() [source]

Returns the number of tabs in the FlatNotebook control.

GetPageImage(page) [source]

Returns the image index associated to a page.

Parameters: page – an integer specifying the page index.

GetPageText(page) [source]

Returns the tab caption of the page.

Parameters: page – an integer specifying the page index.

GetPageTextColour(page) [source]

Returns the tab text colour if it has been set previously, or None otherwise.

Parameters: page – an integer specifying the page index.

GetSelection() [source]

Returns the current selected page.

GetSingleLineBorderColour() [source]

Returns the colour for the single line border.

HasAGWFlag(flag) [source]

Returns whether a flag is present in the FlatNotebook style.

Parameters: flag – one of the possible FlatNotebook window styles.

See also

FlatNotebook.SetAGWWindowStyleFlag() for a list of possible window style flags.

HitTest(pt) [source]

HitTest method for PageContainer.

Parameters: pt – an instance of wx.Point, to test for hits.
Returns: The hit test flag (if any) and the hit page index (if any). The return value can be one of the following bits:
HitTest Flag | Value | Description
FNB_NOWHERE | 0 | Indicates mouse coordinates not on any tab of the notebook
FNB_TAB | 1 | Indicates mouse coordinates inside a tab
FNB_X | 2 | Indicates mouse coordinates inside the ‘X’ button region
FNB_TAB_X | 3 | Indicates mouse coordinates inside the ‘X’ region in a tab
FNB_LEFT_ARROW | 4 | Indicates mouse coordinates inside the left arrow region
FNB_RIGHT_ARROW | 5 | Indicates mouse coordinates inside the right arrow region
FNB_DROP_DOWN_ARROW | 6 | Indicates mouse coordinates inside the drop down arrow region

InsertPage(indx, text, selected=True, imgindex=-1) [source]

Inserts a new page at the specified position.

Parameters:
  • indx – specifies the position of the new page;
  • page – specifies the new page;
  • text – specifies the text for the new page;
  • select – specifies whether the page should be selected;
  • imageId – specifies the optional image index for the new page.

IsDefaultTabs() [source]

Returns whether a tab has a default style.

IsMouseHovering(page) [source]

Returns whether or not the mouse is hovering over this page’s tab

Parameters: page – an integer specifying the page index.

IsTabVisible(page) [source]

Returns whether a tab is visible or not.

Parameters: page – an integer specifying the page index.

MoveTabPage(nMove, nMoveTo) [source]

Moves a tab inside the same FlatNotebook.

Parameters:
  • nMove – the start index of the moved tab;
  • nMoveTo – the destination index of the moved tab.

OnDropTarget(x, y, nTabPage, wnd_oldContainer) [source]

Handles the drop action from a drag and drop operation.

Parameters:
  • x – the x position of the drop action;
  • y – the y position of the drop action;
  • nTabPage – the index of the tab being dropped;
  • wnd_oldContainer – the FlatNotebook to which the dropped tab previously belonged to.

OnEraseBackground(event) [source]

Handles the wx.EVT_ERASE_BACKGROUND event for PageContainer.

Parameters: event – a wx.EraseEvent event to be processed.

Note

This method is intentionally empty to reduce flicker.

OnKeyDown(event) [source]

Handles the wx.EVT_KEY_DOWN event for PageContainer.

Parameters: event – a wx.KeyEvent event to be processed.

Note

When the PageContainer has the focus tabs can be changed with the left/right arrow keys.

OnKillFocus(event) [source]

Handles the wx.EVT_KILL_FOCUS event for PageContainer.

Parameters: event – a wx.FocusEvent event to be processed.

OnLeftDClick(event) [source]

Handles the wx.EVT_LEFT_DCLICK event for PageContainer.

Parameters: event – a wx.MouseEvent event to be processed.

OnLeftDown(event) [source]

Handles the wx.EVT_LEFT_DOWN event for PageContainer.

Parameters: event – a wx.MouseEvent event to be processed.

OnLeftUp(event) [source]

Handles the wx.EVT_LEFT_UP event for PageContainer.

Parameters: event – a wx.MouseEvent event to be processed.

OnMiddleDown(event) [source]

Handles the wx.EVT_MIDDLE_DOWN event for PageContainer.

Parameters: event – a wx.MouseEvent event to be processed.

OnMouseEnterWindow(event) [source]

Handles the wx.EVT_ENTER_WINDOW event for PageContainer.

Parameters: event – a wx.MouseEvent event to be processed.

OnMouseLeave(event) [source]

Handles the wx.EVT_LEAVE_WINDOW event for PageContainer.

Parameters: event – a wx.MouseEvent event to be processed.

OnMouseMove(event) [source]

Handles the wx.EVT_MOTION event for PageContainer.

Parameters: event – a wx.MouseEvent event to be processed.

OnMouseWheel(event) [source]

Handles the wx.EVT_MOUSEWHEEL event for PageContainer.

Parameters: event – a wx.MouseEvent event to be processed.

OnPaint(event) [source]

Handles the wx.EVT_PAINT event for PageContainer.

Parameters: event – a wx.PaintEvent event to be processed.

OnRightDown(event) [source]

Handles the wx.EVT_RIGHT_DOWN event for PageContainer.

Parameters: event – a wx.MouseEvent event to be processed.

OnSetFocus(event) [source]

Handles the wx.EVT_SET_FOCUS event for PageContainer.

Parameters: event – a wx.FocusEvent event to be processed.

OnSize(event) [source]

Handles the wx.EVT_SIZE event for PageContainer.

Parameters: event – a wx.SizeEvent event to be processed.

OnTabMenuSelection(event) [source]

Handles the wx.EVT_MENU event for PageContainer.

Parameters: event – a wx.MenuEvent event to be processed.

PopupTabsMenu() [source]

Pops up the menu activated with the drop down arrow in the navigation area.

RotateLeft() [source]

Scrolls tabs to the left by bulk of 5 tabs.

RotateRight() [source]

Scrolls tabs to the right by bulk of 5 tabs.

SetAGWWindowStyleFlag(agwStyle) [source]

Sets the FlatNotebook window style.

Parameters: agwStyle – the new FlatNotebook window style.

See also

The FlatNotebook.__init__() method for the agwStyle parameter description.

SetFocusedPage(pageIndex=-1) [source]

Sets/Unsets the focus on the appropriate page.

Parameters: pageIndex – an integer specifying the page index. If pageIndex is defaulted to -1, we have lost focus and no focus indicator is drawn.

SetImageList(imglist) [source]

Sets the image list for the PageContainer.

Parameters: imageList – an instance of wx.ImageList.

SetPageImage(page, image) [source]

Sets the image index for the given page.

Parameters:
  • page – an integer specifying the page index;
  • image – an index into the image list which was set with SetImageList.

SetPageText(page, text) [source]

Sets the tab caption of the page.

Parameters:
  • page – an integer specifying the page index;
  • text – the new tab label.

SetPageTextColour(page, colour) [source]

Sets the tab text colour individually.

Parameters:
  • page – an integer specifying the page index;
  • colour – a valid wx.Colour object or any typemap supported by wxWidgets/wxPython to generate a colour (i.e., a hex string, a colour name, a 3 or 4 integer tuple). You can pass None or wx.NullColour to return to the default page text colour.

SetSelection(page) [source]

Sets the selected page.

Parameters: page – an integer specifying the page index.

ShowTabTooltip(tabIdx) [source]

Shows a tab tooltip.

Parameters: tabIdx – an integer specifying the page index.

TabHasImage(tabIdx) [source]

Returns whether a tab has an associated image index or not.

Parameters: tabIdx – an integer specifying the page index.

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • infobar
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • flatnotebook »
  • PageContainer


PageInfo

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • flatnotebook »
  • PageInfo

PageInfo

This class holds all the information (caption, image, etc...) belonging to a single tab in FlatNotebook.

hierarchy Inheritance Diagram

Inheritance diagram for: PageInfo

Inheritance diagram of PageInfo

Methods Summary

__init__ | Default Class Constructor.
EnableTab | Sets the tab enabled or disabled.
GetCaption | Returns the tab caption.
GetColour | Returns the tab colour.
GetEnabled | Returns whether the tab is enabled or not.
GetImageIndex | Returns the tab image index.
GetPageTextColour | Returns the tab text colour if it has been set previously, or None
GetPosition | Returns the tab position.
GetRegion | Returns the tab region.
GetSize | Returns the tab size.
GetTabAngle | Returns the tab angle.
GetXRect | Returns the button ‘X’ area rect.
SetCaption | Sets the tab caption.
SetColour | Sets the tab colour.
SetImageIndex | Sets the tab image index.
SetPageTextColour | Sets the tab text colour for this tab.
SetPosition | Sets the tab position.
SetRegion | Sets the tab region.
SetSize | Sets the tab size.
SetTabAngle | Sets the tab header angle.
SetXRect | Sets the button ‘X’ area rect.

API Class API

class PageInfo(object) [source]

This class holds all the information (caption, image, etc...) belonging to a single tab in FlatNotebook.

__init__(caption='', imageindex=-1, tabangle=0, enabled=True) [source]

Default Class Constructor.

Parameters:
  • caption – the tab caption;
  • imageindex – the tab image index based on the assigned (set) wx.ImageList (if any);
  • tabangle – the tab angle (only on standard tabs, from 0 to 15 degrees);
  • enabled – sets the tab as enabled or disabled.

EnableTab(enabled) [source]

Sets the tab enabled or disabled.

Parameters: enabled – True to enable a tab, False to disable it.

GetCaption() [source]

Returns the tab caption.

GetColour() [source]

Returns the tab colour.

GetEnabled() [source]

Returns whether the tab is enabled or not.

GetImageIndex() [source]

Returns the tab image index.

GetPageTextColour() [source]

Returns the tab text colour if it has been set previously, or None otherwise.

GetPosition() [source]

Returns the tab position.

GetRegion() [source]

Returns the tab region.

GetSize() [source]

Returns the tab size.

GetTabAngle() [source]

Returns the tab angle.

GetXRect() [source]

Returns the button ‘X’ area rect.

SetCaption(value) [source]

Sets the tab caption.

Parameters: value – the new tab caption string.

SetColour(colour) [source]

Sets the tab colour.

Parameters: colour – a valid wx.Colour object or any typemap supported by wxWidgets/wxPython to generate a colour (i.e., a hex string, a colour name, a 3 or 4 integer tuple).

SetImageIndex(value) [source]

Sets the tab image index.

Parameters: value – an index within the FlatNotebook image list specifying the image to use for this tab.

SetPageTextColour(colour) [source]

Sets the tab text colour for this tab.

Parameters: colour – an instance of wx.Colour. You can pass None or wx.NullColour to return to the default page text colour.

SetPosition(value) [source]

Sets the tab position.

Parameters: value – an instance of wx.Point.

SetRegion(points=[]) [source]

Sets the tab region.

Parameters: points – a Python list of wx.Point

SetSize(value) [source]

Sets the tab size.

Parameters: value – an instance of wx.Size.

SetTabAngle(value) [source]

Sets the tab header angle.

Parameters: value – the tab header angle (0 <= value <= 15 degrees).

SetXRect(xrect) [source]

Sets the button ‘X’ area rect.

Parameters: xrect – an instance of wx.Rect, specifying the client rectangle of the ‘X’ button.

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • infobar
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • flatnotebook »
  • PageInfo


TabNavigatorWindow

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • flatnotebook »
  • TabNavigatorWindow

TabNavigatorWindow

This class is used to create a modal dialog that enables Smart Tabbing, similar to what you would get by hitting Alt + Tab on Windows.

hierarchy Inheritance Diagram

Inheritance diagram for: TabNavigatorWindow

Inheritance diagram of TabNavigatorWindow

Methods Summary

__init__ | Default class constructor.
CloseDialog | Closes the TabNavigatorWindow dialog, setting the new selection in
OnItemSelected | Handles the wx.EVT_LISTBOX_DCLICK for the TabNavigatorWindow.
OnKeyUp | Handles the wx.EVT_KEY_UP for the TabNavigatorWindow.
OnNavigationKey | Handles the wx.EVT_NAVIGATION_KEY for the TabNavigatorWindow.
OnPanelEraseBg | Handles the wx.EVT_ERASE_BACKGROUND for the TabNavigatorWindow top panel.
OnPanelPaint | Handles the wx.EVT_PAINT for the TabNavigatorWindow top panel.
PopulateListControl | Populates the TabNavigatorWindow listbox with a list of tabs.

API Class API

class TabNavigatorWindow(wx.Dialog) [source]

This class is used to create a modal dialog that enables Smart Tabbing, similar to what you would get by hitting Alt + Tab on Windows.

__init__(parent=None, icon=None) [source]

Default class constructor. Used internally.

Parameters:
  • parent – the TabNavigatorWindow parent window;
  • icon – a valid wx.Bitmap object representing the icon to be displayed in the TabNavigatorWindow.

CloseDialog() [source]

Closes the TabNavigatorWindow dialog, setting the new selection in FlatNotebook.

OnItemSelected(event) [source]

Handles the wx.EVT_LISTBOX_DCLICK for the TabNavigatorWindow.

Parameters: event – a wx.ListEvent event to be processed.

OnKeyUp(event) [source]

Handles the wx.EVT_KEY_UP for the TabNavigatorWindow.

Parameters: event – a wx.KeyEvent event to be processed.

OnNavigationKey(event) [source]

Handles the wx.EVT_NAVIGATION_KEY for the TabNavigatorWindow.

Parameters: event – a wx.NavigationKeyEvent event to be processed.

OnPanelEraseBg(event) [source]

Handles the wx.EVT_ERASE_BACKGROUND for the TabNavigatorWindow top panel.

Parameters: event – a wx.EraseEvent event to be processed.

Note

This method is intentionally empty to reduce flicker.

OnPanelPaint(event) [source]

Handles the wx.EVT_PAINT for the TabNavigatorWindow top panel.

Parameters: event – a wx.PaintEvent event to be processed.

PopulateListControl(book) [source]

Populates the TabNavigatorWindow listbox with a list of tabs.

Parameters: book – an instance of FlatNotebook containing the tabs to be displayed in the listbox.

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • infobar
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • flatnotebook »
  • TabNavigatorWindow


SVN Revision 68362 For flatnotebook

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • flatnotebook »
  • SVN Revision 68362 For flatnotebook

svn SVN Revision 68362 For flatnotebook

This file contains the SVN revision history for flatnotebook, at revision 68362.

Available information include commit date, the name of the committer, the file size, the SVN log messages and a diff from the previous version (if available).

File Information

  • Commit Date: 14-Nov-2009 18:34:26 UTC
  • Committer: AG
  • File Size: 213730 byte(s)

Log Messages

The following log message was entered by the committer:

  • All of AGW: change my work e-mail from KPO to Maersk Oil (silly commit)

Diff To Previous Version (65529)

Version SVN diff:

--- wxPython/3rdParty/AGW/agw/flatnotebook.py       2010/09/12 11:58:40     65529
+++ wxPython/3rdParty/AGW/agw/flatnotebook.py       2011/07/24 21:36:47     68362
@@ -18,7 +18,7 @@
# Write To Me At:
#
# andrea.gavana@gmail.com
-# gavana@kpo.kz
+# andrea.gavana@maerskoil.com
#
# Or, Obviously, To The wxPython Mailing List!!!
#

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • flatnotebook »
  • SVN Revision 68362 For flatnotebook


SVN Revision 68508 For flatnotebook

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • flatnotebook »
  • SVN Revision 68508 For flatnotebook

svn SVN Revision 68508 For flatnotebook

This file contains the SVN revision history for flatnotebook, at revision 68508.

Available information include commit date, the name of the committer, the file size, the SVN log messages and a diff from the previous version (if available).

File Information

  • Commit Date: 05-Nov-2009 12:25:42 UTC
  • Committer: AG
  • File Size: 213735 byte(s)

Log Messages

The following log message was entered by the committer:

FlatNotebook: Correct OnMouseWheel for the silly new “true division” behaviour of Python. Thanks to Nat Echols for the bug report.

Diff To Previous Version (68362)

Version SVN diff:

--- wxPython/3rdParty/AGW/agw/flatnotebook.py       2011/07/24 21:36:47     68362
+++ wxPython/3rdParty/AGW/agw/flatnotebook.py       2011/08/03 18:32:28     68508
@@ -11,7 +11,7 @@
# Python Code By:
#
# Andrea Gavana, @ 02 Oct 2006
-# Latest Revision: 12 Sep 2010, 10.00 GMT
+# Latest Revision: 03 Aug 2011, 08.00 GMT
#
#
# For All Kind Of Problems, Requests Of Enhancements And Bug Reports, Please
@@ -117,7 +117,7 @@

FlatNotebook is distributed under the wxPython license.

-Latest Revision: Andrea Gavana @ 12 Sep 2010, 10.00 GMT
+Latest Revision: Andrea Gavana @ 03 Aug 2011, 08.00 GMT

Version 3.1
"""
@@ -5045,7 +5045,7 @@

rotation = event.GetWheelRotation()
delta = event.GetWheelDelta()
-        steps = rotation/delta
+        steps = int(rotation/delta)

for tab in xrange(abs(steps)):
if steps > 0:

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • flatnotebook »
  • SVN Revision 68508 For flatnotebook


SVN Revision 68645 For flatnotebook

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • flatnotebook »
  • SVN Revision 68645 For flatnotebook

svn SVN Revision 68645 For flatnotebook

This file contains the SVN revision history for flatnotebook, at revision 68645.

Available information include commit date, the name of the committer, the file size, the SVN log messages and a diff from the previous version (if available).

File Information

  • Commit Date: 29-May-2009 08:06:58 UTC
  • Committer: AG
  • File Size: 219142 byte(s)

Log Messages

The following log message was entered by the committer:

  • FlatNotebook: add support for tiling pages horizontally/vertically, plus add the possibility to show a custom page when there are no pages left (GetPageCount() returns 0)

Diff To Previous Version (68511)

Version SVN diff:

--- wxPython/3rdParty/AGW/agw/flatnotebook.py       2011/08/03 19:53:50     68511
+++ wxPython/3rdParty/AGW/agw/flatnotebook.py       2011/08/11 20:14:55     68645
@@ -11,7 +11,7 @@
# Python Code By:
#
# Andrea Gavana, @ 02 Oct 2006
-# Latest Revision: 03 Aug 2011, 22.00 GMT
+# Latest Revision: 11 Aug 2011, 15.00 GMT
#
#
# For All Kind Of Problems, Requests Of Enhancements And Bug Reports, Please
@@ -55,6 +55,10 @@
- Colours for active/inactive tabs, and captions;
- Background of tab area can be painted in gradient (VC8 style only);
- Colourful tabs - a random gentle colour is generated for each new tab (very cool, VC8 style only);
+- Support for showing pages in "column/row mode", which means that all the pages will be
+  shown in "tile" mode while the tabs are hidden;
+- Possibility to add a custom panel to show a logo or HTML documentation or
+  whatever you like when there are no pages left in L{FlatNotebook};
- Try setting the tab area colour for the Ribbon Style.

@@ -117,9 +121,9 @@

FlatNotebook is distributed under the wxPython license.

-Latest Revision: Andrea Gavana @ 03 Aug 2011, 22.00 GMT
+Latest Revision: Andrea Gavana @ 11 Aug 2011, 15.00 GMT

-Version 3.1
+Version 3.2
"""

__docformat__ = "epytext"
@@ -2245,7 +2249,7 @@
# | PADDING | IMG | IMG_PADDING | TEXT | PADDING | x |PADDING |
# +-----------------------------------------------------------+
tabWidth = self.CalcTabWidth(pageContainer, i, tabHeight)
-
+
# Check if we can draw more
if posx + tabWidth + self.GetButtonsAreaLength(pc) >= clientWidth:
break
@@ -3842,6 +3846,8 @@
self._popupWin = None
self._naviIcon = None
self._agwStyle = agwStyle
+        self._orientation = None
+        self._customPanel = None

wx.PyPanel.__init__(self, parent, id, pos, size, style)
attr = self.GetDefaultAttributes()
@@ -3916,8 +3922,137 @@
maxWidth, maxHeight = max(maxWidth, width), max(maxHeight, height)

return wx.Size(maxWidth, maxHeight+tabHeight)
-

+
+    def Tile(self, orient=None):
+        """
+        Shows pages in column/row mode (one panel after the other in columns/rows).
+
+        :param `orient`: this parameter represents the orientation of the stacked
+         panels. Pass ``wx.VERTICAL`` to get vertically stacked panels, ``wx.HORIZONTAL``
+         to get horizontally stacked panels or ``None`` to return to the default
+         L{FlatNotebook} behaviour with tabs.
+        """
+
+        self.Freeze()
+        self._orientation = orient
+
+        self._mainSizer.Detach(self._pages)
+        for win in self._windows:
+            self._mainSizer.Detach(win)
+
+        self._mainSizer.Destroy()
+
+        if orient is not None:
+            self._mainSizer = wx.BoxSizer(orient)
+            self._mainSizer.Add(self._pages)
+
+            for win in self._windows:
+                self._mainSizer.Add(win, 1, wx.EXPAND | wx.ALL, 2)
+                win.Show()
+
+        else:
+
+            self._mainSizer = wx.BoxSizer(wx.VERTICAL)
+            # Add the tab container to the sizer
+            self._mainSizer.Insert(0, self._pages, 0, wx.EXPAND)
+
+            curr = self._pages.GetSelection()
+            for indx, win in enumerate(self._windows):
+                if indx == curr:
+                    if self.GetAGWWindowStyleFlag() & FNB_BOTTOM:
+                        self._mainSizer.Insert(0, win, 1, wx.EXPAND)
+                    else:
+                        # We leave a space of 1 pixel around the window
+                        self._mainSizer.Add(win, 1, wx.EXPAND)
+                    win.Show()
+
+                else:
+                    win.Hide()
+
+        self.SetSizer(self._mainSizer)
+
+        self._mainSizer.Layout()
+        self.Layout()
+
+        if orient is None:
+            self.SetSelection(self._pages._iActivePage)
+            self._pages._ReShow()
+
+        self.Thaw()
+
+
+    def GetTileOrientation(self):
+        """
+        Returns the orientation when on tiling mode. This method can return
+        ``wx.VERTICAL`` when the panels are vertically stacked, ``wx.HORIZONTAL``
+        when they are horizontally stacked panels or ``None`` when there is no
+        stacking and L{FlatNotebook} behaves like a normal notebook.
+        """
+
+        return self._orientation
+
+
+    def SetCustomPage(self, panel):
+        """
+        Sets a custom panel to show when there are no pages left in L{FlatNotebook}.
+
+        :param `panel`: any subclass of `wx.Window` will do, as long as it is suitable
+         to be used as a notebook page. Examples include `wx.Panel`, wx.ScrolledWindow`,
+         and so on.
+        """
+
+        self.Freeze()
+
+        if panel is None:
+            if self._customPanel is not None:
+                self._mainSizer.Detach(self._customPanel)
+                self._customPanel.Show(False)
+
+        else:
+            if self.GetPageCount() == 0:
+                if self._customPanel is not None:
+                    self._mainSizer.Detach(self._customPanel)
+                    self._customPanel.Show(False)
+                    self._customPanel.Destroy()
+
+                self._mainSizer.Add(panel, 1, wx.EXPAND | wx.ALL, 2)
+                panel.Show(True)
+            else:
+                panel.Show(False)
+
+        self._customPanel = panel
+        self._pages._ReShow()
+        self._mainSizer.Layout()
+        self.Thaw()
+
+
+    def GetCustomPage(self):
+        """ Returns a custom panel to show when there are no pages left in L{FlatNotebook}. """
+
+        return self._customPanel
+
+
+    def ShowCustomPage(self, show=True):
+        """ Hides the custom panel which is shown when there are no pages left in L{FlatNotebook}. """
+
+        if self._customPanel is None:
+            return
+
+        if self.GetPageCount() == 0:
+
+            self.Freeze()
+
+            if show:
+                self._mainSizer.Add(self._customPanel, 1, wx.EXPAND | wx.ALL, 2)
+            else:
+                self._mainSizer.Detach(self._customPanel)
+
+            self._customPanel.Show(show)
+            self._mainSizer.Layout()
+            self.Thaw()
+
+
def SetActiveTabTextColour(self, textColour):
"""
Sets the text colour for the active tab.
@@ -3964,6 +4099,8 @@
if not page:
return False

+        self.ShowCustomPage(False)
+
# reparent the window to us
page.Reparent(self)

@@ -4024,7 +4161,8 @@
# Hide the page
page.Hide()

-        self.Thaw()
+        self.Tile(self._orientation)
+        self.Thaw()
self._mainSizer.Layout()
self.Refresh()

@@ -4074,6 +4212,8 @@
if not page:
return False

+        self.ShowCustomPage(False)
+
# reparent the window to us
page.Reparent(self)

@@ -4139,6 +4279,7 @@
# Hide the page
page.Hide()

+        self.Tile(self._orientation)
self.Thaw()
self._mainSizer.Layout()
self.Refresh()
@@ -4162,6 +4303,9 @@
if not self._pages.GetEnabled(page) and len(self._windows) > 1 and not self._bForceSelection:
return

+        if self._orientation is not None:
+            return
+
curSel = self._pages.GetSelection()

# program allows the page change
@@ -4235,6 +4379,10 @@
self.Thaw()

self._pages.DoDeletePage(page)
+
+        self.ShowCustomPage(True)
+        self.Tile(self._orientation)
+
self.Refresh()
self.Update()

@@ -4261,6 +4409,8 @@

# Clear the container of the tabs as well
self._pages.DeleteAllPages()
+        self.ShowCustomPage(True)
+
return True

@@ -4546,7 +4696,7 @@

agwStyle = self.GetAGWWindowStyleFlag()
agwStyle |= FNB_HIDE_TABS
-        self.SetAGWWindowStyleFlag( agwStyle )
+        self.SetAGWWindowStyleFlag(agwStyle)

def ShowTabs(self):
@@ -4554,7 +4704,7 @@

agwStyle = self.GetAGWWindowStyleFlag()
agwStyle &= ~FNB_HIDE_TABS
-        self.SetAGWWindowStyleFlag( agwStyle )
+        self.SetAGWWindowStyleFlag(agwStyle)

def RemovePage(self, page):
@@ -4943,11 +5093,14 @@
"""

dc = wx.BufferedPaintDC(self)
-        renderer = self._mgr.GetRenderer(self.GetParent().GetAGWWindowStyleFlag())
+        parent = self.GetParent()
+
+        renderer = self._mgr.GetRenderer(parent.GetAGWWindowStyleFlag())
renderer.DrawTabs(self, dc)
-
-        if self.HasAGWFlag(FNB_HIDE_ON_SINGLE_TAB) and len(self._pagesInfoVec) <= 1 or\
-           self.HasAGWFlag(FNB_HIDE_TABS):
+
+        if self.HasAGWFlag(FNB_HIDE_ON_SINGLE_TAB) and len(self._pagesInfoVec) <= 1 or \
+           self.HasAGWFlag(FNB_HIDE_TABS) or parent._orientation or \
+           (parent._customPanel and len(self._pagesInfoVec) == 0):
self.Hide()
self.GetParent()._mainSizer.Layout()
self.Refresh()
@@ -5413,6 +5566,7 @@
:param `page`: an integer specifying the page index.
"""
return page == self._nHoveringOverTabIndex
+

def IsTabVisible(self, page):
"""
@@ -5512,7 +5666,6 @@
bRedrawTabs = False
self._nHoveringOverTabIndex = -1

-
where, tabIdx = self.HitTest(event.GetPosition())

if where == FNB_X:

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • flatnotebook »
  • SVN Revision 68645 For flatnotebook


SVN Revision 68702 For flatnotebook

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • flatnotebook »
  • SVN Revision 68702 For flatnotebook

svn SVN Revision 68702 For flatnotebook

This file contains the SVN revision history for flatnotebook, at revision 68702.

Available information include commit date, the name of the committer, the file size, the SVN log messages and a diff from the previous version (if available).

File Information

  • Commit Date: 12-May-2009 14:58:36 UTC
  • Committer: AG
  • File Size: 219196 byte(s)

Log Messages

The following log message was entered by the committer:

FlatNotebook: fix issues with custom page and vertical/horizontal tiling of pages.

Diff To Previous Version (68645)

Version SVN diff:

--- wxPython/3rdParty/AGW/agw/flatnotebook.py       2011/08/11 20:14:55     68645
+++ wxPython/3rdParty/AGW/agw/flatnotebook.py       2011/08/15 18:37:09     68702
@@ -11,7 +11,7 @@
# Python Code By:
#
# Andrea Gavana, @ 02 Oct 2006
-# Latest Revision: 11 Aug 2011, 15.00 GMT
+# Latest Revision: 15 Aug 2011, 20.00 GMT
#
#
# For All Kind Of Problems, Requests Of Enhancements And Bug Reports, Please
@@ -121,7 +121,7 @@

FlatNotebook is distributed under the wxPython license.

-Latest Revision: Andrea Gavana @ 11 Aug 2011, 15.00 GMT
+Latest Revision: Andrea Gavana @ 15 Aug 2011, 20.00 GMT

Version 3.2
"""
@@ -4010,18 +4010,14 @@
self._customPanel.Show(False)

else:
-            if self.GetPageCount() == 0:
-                if self._customPanel is not None:
-                    self._mainSizer.Detach(self._customPanel)
-                    self._customPanel.Show(False)
-                    self._customPanel.Destroy()
+            if self._customPanel is not None:
+                self._mainSizer.Detach(self._customPanel)
+                self._customPanel.Show(False)
+                self._customPanel.Destroy()

-                self._mainSizer.Add(panel, 1, wx.EXPAND | wx.ALL, 2)
-                panel.Show(True)
-            else:
-                panel.Show(False)
-
self._customPanel = panel
+        self.ShowCustomPage(True)
+
self._pages._ReShow()
self._mainSizer.Layout()
self.Thaw()
@@ -4039,18 +4035,18 @@
if self._customPanel is None:
return

-        if self.GetPageCount() == 0:
-
-            self.Freeze()
-
-            if show:
+        self.Freeze()
+        self._customPanel.Show(False)
+
+        if show:
+            if self.GetPageCount() == 0:
self._mainSizer.Add(self._customPanel, 1, wx.EXPAND | wx.ALL, 2)
-            else:
-                self._mainSizer.Detach(self._customPanel)
-
-            self._customPanel.Show(show)
-            self._mainSizer.Layout()
-            self.Thaw()
+                self._customPanel.Show(True)
+        else:
+            self._mainSizer.Detach(self._customPanel)
+
+        self._mainSizer.Layout()
+        self.Thaw()

def SetActiveTabTextColour(self, textColour):
@@ -4099,6 +4095,10 @@
if not page:
return False

+        min_size = page.GetMinSize()
+        if not min_size.IsFullySpecified():
+            page.SetMinSize((1, 1))
+
self.ShowCustomPage(False)

# reparent the window to us
@@ -4380,8 +4380,8 @@

self._pages.DoDeletePage(page)

-        self.ShowCustomPage(True)
self.Tile(self._orientation)
+        self.ShowCustomPage(True)

self.Refresh()
self.Update()
@@ -4739,6 +4739,10 @@

# Remove it from the array as well
self._windows.pop(page)
+
+        self.Tile(self._orientation)
+        self.ShowCustomPage(True)
+
self.Thaw()

self._pages.DoDeletePage(page)
@@ -6548,7 +6552,7 @@
if not self._pages.GetEnabled(page) and len(self._windows) > 1 and not self._bForceSelection:
return

-        self.FireEvent(page)
+        self._pages.FireEvent(page)

def ChangeSelection(self, page):

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • flatnotebook »
  • SVN Revision 68702 For flatnotebook


SVN Revision 68881 For flatnotebook

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • flatnotebook »
  • SVN Revision 68881 For flatnotebook

svn SVN Revision 68881 For flatnotebook

This file contains the SVN revision history for flatnotebook, at revision 68881.

Available information include commit date, the name of the committer, the file size, the SVN log messages and a diff from the previous version (if available).

File Information

  • Commit Date: 29-Oct-2008 00:57:05 UTC
  • Committer: AG
  • File Size: 216698 byte(s)

Log Messages

The following log message was entered by the committer:

  • AGW: General overhaul of the documentation, much improved. All the widgets have their own sample usage in the docs as well;

  • FlatNotebook: Added the FNB_NAV_BUTTONS_WHEN_NEEDED style, which hides the navigation left/right arrows if all tabs fit;

  • RibbonBar: - Added the EVT_RIBBONBAR_TAB_LEFT_DCLICK event, which generates a special event

    when a ribbon bar tab is double-clicked;

    • Added support for toggle buttons;
    • Improved support for ribbon panel sizers: panels with sizers should now automatically minimise at small sizes, and behave properly when popping up from a minimised state;
    • Added tooltips via SetToolTip for those buttons which have the help_string attribute set.

  • XLSGrid: a new widget was added to AGW, termed XLSGrid. It’s based on wx.grid.Grid and can be used to faithfully reproduce the appearance of a Microsoft Excel spreadsheets.

Diff To Previous Version (68742)

Version SVN diff:

--- wxPython/3rdParty/AGW/agw/flatnotebook.py       2011/08/16 16:37:37     68742
+++ wxPython/3rdParty/AGW/agw/flatnotebook.py       2011/08/25 16:40:17     68881
@@ -11,7 +11,7 @@
# Python Code By:
#
# Andrea Gavana, @ 02 Oct 2006
-# Latest Revision: 16 Aug 2011, 18.00 GMT
+# Latest Revision: 17 Aug 2011, 15.00 GMT
#
#
# For All Kind Of Problems, Requests Of Enhancements And Bug Reports, Please
@@ -27,13 +27,13 @@
# --------------------------------------------------------------------------- #

"""
-FlatNotebook is a full, generic and owner-drawn implementation of `wx.Notebook`.
+L{FlatNotebook} is a full, generic and owner-drawn implementation of `wx.Notebook`.

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

-The FlatNotebook is a full implementation of the `wx.Notebook`, and designed to be
+L{FlatNotebook} is a full implementation of the `wx.Notebook`, and designed to be
a drop-in replacement for `wx.Notebook`. The API functions are similar so one can
expect the function to behave in the same way.

@@ -65,6 +65,59 @@
And much more.

+Usage
+=====
+
+Usage example::
+
+    import wx
+    import wx.lib.agw.flatnotebook as fnb
+
+    class MyFrame(wx.Frame):
+
+        def __init__(self, parent):
+
+            wx.Frame.__init(self, parent, -1, "FlatNotebook Demo")
+
+            panel = wx.Panel(self)
+
+            notebook = fnb.FlatNotebook(panel, -1)
+
+            for i in xrange(3):
+                caption = "Page %d"%(i+1)
+                notebook.AddPage(self.CreatePage(notebook, caption), caption)
+
+            sizer = wx.BoxSizer(wx.VERTICAL)
+            sizer.Add(notebook, 1, wx.ALL|wx.EXPAND, 5)
+            panel.SetSizer(sizer)
+
+
+        def CreatePage(self, notebook, caption):
+            '''
+            Creates a simple `wx.Panel` containing a `wx.TextCtrl`.
+
+            :param `notebook`: an instance of `FlatNotebook`;
+            :param `caption`: a simple label.
+            '''
+
+            p = wx.Panel(notebook)
+            wx.StaticText(p, -1, caption, (20,20))
+            wx.TextCtrl(p, -1, "", (20,40), (150,-1))
+            return p
+
+
+    # our normal wxApp-derived class, as usual
+
+    app = wx.PySimpleApp()
+
+    frame = MyFrame(None)
+    app.SetTopWindow(frame)
+    frame.Show()
+
+    app.MainLoop()
+
+
+
Window Styles
=============

@@ -88,13 +141,14 @@
``FNB_DCLICK_CLOSES_TABS``            0x1000 Style to close tab using double click.
``FNB_SMART_TABS``                    0x2000 Use `Smart Tabbing`, like ``Alt`` + ``Tab`` on Windows.
``FNB_DROPDOWN_TABS_LIST``            0x4000 Use a dropdown menu on the left in place of the arrows.
-``FNB_ALLOW_FOREIGN_DND``             0x8000 Allows drag 'n' drop operations between different FlatNotebooks.
+``FNB_ALLOW_FOREIGN_DND``             0x8000 Allows drag 'n' drop operations between different L{FlatNotebook}.
``FNB_HIDE_ON_SINGLE_TAB``           0x10000 Hides the Page Container when there is one or fewer tabs.
-``FNB_DEFAULT_STYLE``                0x10020 FlatNotebook default style.
+``FNB_DEFAULT_STYLE``                0x10020 L{FlatNotebook} default style.
``FNB_FF2``                          0x20000 Use Firefox 2 style for tabs.
``FNB_NO_TAB_FOCUS``                 0x40000 Does not allow tabs to have focus.
``FNB_RIBBON_TABS``                  0x80000 Use the Ribbon Tabs style
``FNB_HIDE_TABS``                   0x100000 Hides the Page Container allowing only keyboard navigation
+``FNB_NAV_BUTTONS_WHEN_NEEDED``     0x200000 Hides the navigation left/right arrows if all tabs fit
================================ =========== ==================================================

@@ -106,10 +160,10 @@
========================================= ==================================================
Event Name                                Description
========================================= ==================================================
-``EVT_FLATNOTEBOOK_PAGE_CHANGED``         Notify client objects when the active page in `FlatNotebook` has changed.
-``EVT_FLATNOTEBOOK_PAGE_CHANGING``        Notify client objects when the active page in `FlatNotebook` is about to change.
-``EVT_FLATNOTEBOOK_PAGE_CLOSED``          Notify client objects when a page in `FlatNotebook` has been closed.
-``EVT_FLATNOTEBOOK_PAGE_CLOSING``         Notify client objects when a page in `FlatNotebook` is closing.
+``EVT_FLATNOTEBOOK_PAGE_CHANGED``         Notify client objects when the active page in L{FlatNotebook} has changed.
+``EVT_FLATNOTEBOOK_PAGE_CHANGING``        Notify client objects when the active page in L{FlatNotebook} is about to change.
+``EVT_FLATNOTEBOOK_PAGE_CLOSED``          Notify client objects when a page in L{FlatNotebook} has been closed.
+``EVT_FLATNOTEBOOK_PAGE_CLOSING``         Notify client objects when a page in L{FlatNotebook} is closing.
``EVT_FLATNOTEBOOK_PAGE_CONTEXT_MENU``    Notify client objects when a pop-up menu should appear next to a tab.
``EVT_FLATNOTEBOOK_PAGE_DROPPED``         Notify client objects when a tab has been dropped and re-arranged (on the *same* notebook)
``EVT_FLATNOTEBOOK_PAGE_DROPPED_FOREIGN`` Notify client objects when a tab has been dropped and re-arranged (from a foreign notebook)
@@ -119,9 +173,9 @@
License And Version
===================

-FlatNotebook is distributed under the wxPython license.
+L{FlatNotebook} is distributed under the wxPython license.

-Latest Revision: Andrea Gavana @ 16 Aug 2011, 18.00 GMT
+Latest Revision: Andrea Gavana @ 17 Aug 2011, 15.00 GMT

Version 3.2
"""
@@ -211,7 +265,7 @@
"""Use a dropdown menu on the left in place of the arrows"""

FNB_ALLOW_FOREIGN_DND = 32768
-"""Allows drag 'n' drop operations between different L{FlatNotebook}s"""
+"""Allows drag and drop operations between different L{FlatNotebook}"""

FNB_HIDE_ON_SINGLE_TAB = 65536
"""Hides the Page Container when there is one or fewer tabs"""
@@ -225,6 +279,9 @@
FNB_HIDE_TABS = 0x100000
"""Hides the tabs allowing only keyboard navigation between pages"""

+FNB_NAV_BUTTONS_WHEN_NEEDED = 0x200000
+""" Hides the navigation left/right arrows if all tabs fit. """
+
VERTICAL_BORDER_PADDING = 4

# Button size is a 16x16 xpm bitmap
@@ -288,13 +345,13 @@
#-----------------------------------#

EVT_FLATNOTEBOOK_PAGE_CHANGED = wx.EVT_NOTEBOOK_PAGE_CHANGED
-""" Notify client objects when the active page in `FlatNotebook` has changed."""
+""" Notify client objects when the active page in L{FlatNotebook} has changed."""
EVT_FLATNOTEBOOK_PAGE_CHANGING = wx.EVT_NOTEBOOK_PAGE_CHANGING
-""" Notify client objects when the active page in `FlatNotebook` is about to change."""
+""" Notify client objects when the active page in L{FlatNotebook} is about to change."""
EVT_FLATNOTEBOOK_PAGE_CLOSING = wx.PyEventBinder(wxEVT_FLATNOTEBOOK_PAGE_CLOSING, 1)
-""" Notify client objects when a page in `FlatNotebook` is closing."""
+""" Notify client objects when a page in L{FlatNotebook} is closing."""
EVT_FLATNOTEBOOK_PAGE_CLOSED = wx.PyEventBinder(wxEVT_FLATNOTEBOOK_PAGE_CLOSED, 1)
-""" Notify client objects when a page in `FlatNotebook` has been closed."""
+""" Notify client objects when a page in L{FlatNotebook} has been closed."""
EVT_FLATNOTEBOOK_PAGE_CONTEXT_MENU = wx.PyEventBinder(wxEVT_FLATNOTEBOOK_PAGE_CONTEXT_MENU, 1)
""" Notify client objects when a pop-up menu should appear next to a tab."""
EVT_FLATNOTEBOOK_PAGE_DROPPED = wx.PyEventBinder(wxEVT_FLATNOTEBOOK_PAGE_DROPPED, 1)
@@ -1777,6 +1834,10 @@
if not pc._pagesInfoVec:
return

+        if agwStyle & FNB_NAV_BUTTONS_WHEN_NEEDED:
+            if pc._pagesInfoVec[-1].GetPosition() != wx.Point(-1, -1) and pc._nFrom == 0:
+                return
+
# Set the bitmap according to the button status
if pc._nLeftButtonStatus == FNB_BTN_HOVER:
arrowBmp = wx.BitmapFromXPMData(left_arrow_hilite_xpm)
@@ -1817,6 +1878,10 @@
if not pc._pagesInfoVec:
return

+        if agwStyle & FNB_NAV_BUTTONS_WHEN_NEEDED:
+            if pc._pagesInfoVec[-1].GetPosition() != wx.Point(-1, -1) and pc._nFrom == 0:
+                return
+
# Set the bitmap according to the button status
if pc._nRightButtonStatus == FNB_BTN_HOVER:
arrowBmp = wx.BitmapFromXPMData(right_arrow_hilite_xpm)
@@ -3826,12 +3891,14 @@
``FNB_DCLICK_CLOSES_TABS``            0x1000 Style to close tab using double click.
``FNB_SMART_TABS``                    0x2000 Use `Smart Tabbing`, like ``Alt`` + ``Tab`` on Windows.
``FNB_DROPDOWN_TABS_LIST``            0x4000 Use a dropdown menu on the left in place of the arrows.
-         ``FNB_ALLOW_FOREIGN_DND``             0x8000 Allows drag 'n' drop operations between different FlatNotebooks.
+         ``FNB_ALLOW_FOREIGN_DND``             0x8000 Allows drag 'n' drop operations between different L{FlatNotebook}.
``FNB_HIDE_ON_SINGLE_TAB``           0x10000 Hides the Page Container when there is one or fewer tabs.
-         ``FNB_DEFAULT_STYLE``                0x10020 FlatNotebook default style.
+         ``FNB_DEFAULT_STYLE``                0x10020 L{FlatNotebook} default style.
``FNB_FF2``                          0x20000 Use Firefox 2 style for tabs.
``FNB_NO_TAB_FOCUS``                 0x40000 Does not allow tabs to have focus.
``FNB_RIBBON_TABS``                  0x80000 Use the Ribbon Tabs style.
+         ``FNB_HIDE_TABS``                   0x100000 Hides the Page Container allowing only keyboard navigation
+         ``FNB_NAV_BUTTONS_WHEN_NEEDED``     0x200000 Hides the navigation left/right arrows if all tabs fit
================================ =========== ==================================================

:param `name`: the window name.
@@ -4637,12 +4704,14 @@
``FNB_DCLICK_CLOSES_TABS``            0x1000 Style to close tab using double click.
``FNB_SMART_TABS``                    0x2000 Use `Smart Tabbing`, like ``Alt`` + ``Tab`` on Windows.
``FNB_DROPDOWN_TABS_LIST``            0x4000 Use a dropdown menu on the left in place of the arrows.
-         ``FNB_ALLOW_FOREIGN_DND``             0x8000 Allows drag 'n' drop operations between different FlatNotebooks.
+         ``FNB_ALLOW_FOREIGN_DND``             0x8000 Allows drag 'n' drop operations between different L{FlatNotebook}.
``FNB_HIDE_ON_SINGLE_TAB``           0x10000 Hides the Page Container when there is one or fewer tabs.
-         ``FNB_DEFAULT_STYLE``                0x10020 FlatNotebook default style.
+         ``FNB_DEFAULT_STYLE``                0x10020 L{FlatNotebook} default style.
``FNB_FF2``                          0x20000 Use Firefox 2 style for tabs.
``FNB_NO_TAB_FOCUS``                 0x40000 Does not allow tabs to have focus.
``FNB_RIBBON_TABS``                  0x80000 Use the Ribbon Tabs style.
+         ``FNB_HIDE_TABS``                   0x100000 Hides the Page Container allowing only keyboard navigation
+         ``FNB_NAV_BUTTONS_WHEN_NEEDED``     0x200000 Hides the navigation left/right arrows if all tabs fit
================================ =========== ==================================================

"""
@@ -6524,12 +6593,14 @@
``FNB_DCLICK_CLOSES_TABS``            0x1000 Style to close tab using double click.
``FNB_SMART_TABS``                    0x2000 Use `Smart Tabbing`, like ``Alt`` + ``Tab`` on Windows.
``FNB_DROPDOWN_TABS_LIST``            0x4000 Use a dropdown menu on the left in place of the arrows.
-         ``FNB_ALLOW_FOREIGN_DND``             0x8000 Allows drag 'n' drop operations between different FlatNotebooks.
+         ``FNB_ALLOW_FOREIGN_DND``             0x8000 Allows drag 'n' drop operations between different L{FlatNotebook}.
``FNB_HIDE_ON_SINGLE_TAB``           0x10000 Hides the Page Container when there is one or fewer tabs.
-         ``FNB_DEFAULT_STYLE``                0x10020 FlatNotebook default style.
+         ``FNB_DEFAULT_STYLE``                0x10020 L{FlatNotebook} default style.
``FNB_FF2``                          0x20000 Use Firefox 2 style for tabs.
``FNB_NO_TAB_FOCUS``                 0x40000 Does not allow tabs to have focus.
``FNB_RIBBON_TABS``                  0x80000 Use the Ribbon Tabs style.
+         ``FNB_HIDE_TABS``                   0x100000 Hides the Page Container allowing only keyboard navigation
+         ``FNB_NAV_BUTTONS_WHEN_NEEDED``     0x200000 Hides the navigation left/right arrows if all tabs fit
================================ =========== ==================================================

:param `name`: the window name.

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • flatnotebook »
  • SVN Revision 68881 For flatnotebook


SVN Revision 69086 For flatnotebook

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • flatnotebook »
  • SVN Revision 69086 For flatnotebook

svn SVN Revision 69086 For flatnotebook

This file contains the SVN revision history for flatnotebook, at revision 69086.

Available information include commit date, the name of the committer, the file size, the SVN log messages and a diff from the previous version (if available).

File Information

  • Commit Date: 29-Oct-2008 00:55:34 UTC
  • Committer: AG
  • File Size: 216694 byte(s)

Log Messages

The following log message was entered by the committer:

  • Fixed bug #13437 for SuperToolTip;
  • Fixed bug #13477 for UltimateListCtrl.

Diff To Previous Version (68881)

Version SVN diff:

--- wxPython/3rdParty/AGW/agw/flatnotebook.py       2011/08/25 16:40:17     68881
+++ wxPython/3rdParty/AGW/agw/flatnotebook.py       2011/09/14 19:39:08     69086
@@ -1235,7 +1235,7 @@
"""
Sets the tab region.

-        :param `points`: a Python list of `wx.Points`
+        :param `points`: a Python list of `wx.Point`
"""

self._region = wx.RegionFromPoints(points)
@@ -2366,7 +2366,7 @@

def DrawFocusRectangle(self, dc, pageContainer, page):
"""
-        Draws a focus rectangle like the native `wx.Notebooks`.
+        Draws a focus rectangle like the native `wx.Notebook`.

:param `dc`: an instance of `wx.DC`;
:param `pageContainer`: an instance of L{FlatNotebook};
@@ -3323,7 +3323,7 @@

:param `pageContainer`: an instance of L{FlatNotebook};
:param `dc`: an instance of `wx.DC`;
-        :param `tabPoints`: a Python list of `wx.Points` representing the tab outline;
+        :param `tabPoints`: a Python list of `wx.Point` representing the tab outline;
:param `bSelectedTab`: ``True`` if the tab is selected, ``False`` otherwise;
:param `tabIdx`: the index of the tab;
"""
@@ -3414,7 +3414,7 @@
"""
Returns the `x` start position of a tab.

-        :param `tabPoints`: a Python list of `wx.Points` representing the tab outline;
+        :param `tabPoints`: a Python list of `wx.Point` representing the tab outline;
:param `y`: the y start position of the tab;
:param `style`: can be ``FNB_BOTTOM`` or the default (tabs at top).
"""
@@ -3479,7 +3479,7 @@
"""
Returns the `x` end position of a tab.

-        :param `tabPoints`: a Python list of `wx.Points` representing the tab outline;
+        :param `tabPoints`: a Python list of `wx.Point` representing the tab outline;
:param `y`: the y end position of the tab;
:param `style`: can be ``FNB_BOTTOM`` or the default (tabs at top).
"""
@@ -4065,7 +4065,7 @@
Sets a custom panel to show when there are no pages left in L{FlatNotebook}.

:param `panel`: any subclass of `wx.Window` will do, as long as it is suitable
-         to be used as a notebook page. Examples include `wx.Panel`, wx.ScrolledWindow`,
+         to be used as a notebook page. Examples include `wx.Panel`, `wx.ScrolledWindow`,
and so on.
"""

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • flatnotebook »
  • SVN Revision 69086 For flatnotebook


SVN Revision 69551 For flatnotebook

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • flatnotebook »
  • SVN Revision 69551 For flatnotebook

svn SVN Revision 69551 For flatnotebook

This file contains the SVN revision history for flatnotebook, at revision 69551.

Available information include commit date, the name of the committer, the file size, the SVN log messages and a diff from the previous version (if available).

File Information

  • Commit Date: 29-Oct-2008 00:49:41 UTC
  • Committer: AG
  • File Size: 218361 byte(s)

Log Messages

The following log message was entered by the committer:

FlatNotebook: add the ability to set colours using any typemap wxWidgets/wxPython support (i.e., hex string, tuples, name, wx.Colour instance)

Diff To Previous Version (69086)

Version SVN diff:

--- wxPython/3rdParty/AGW/agw/flatnotebook.py       2011/09/14 19:39:08     69086
+++ wxPython/3rdParty/AGW/agw/flatnotebook.py       2011/10/26 19:11:52     69551
@@ -11,7 +11,7 @@
# Python Code By:
#
# Andrea Gavana, @ 02 Oct 2006
-# Latest Revision: 17 Aug 2011, 15.00 GMT
+# Latest Revision: 26 Oct 2011, 21.00 GMT
#
#
# For All Kind Of Problems, Requests Of Enhancements And Bug Reports, Please
@@ -175,7 +175,7 @@

L{FlatNotebook} is distributed under the wxPython license.

-Latest Revision: Andrea Gavana @ 17 Aug 2011, 15.00 GMT
+Latest Revision: Andrea Gavana @ 26 Oct 2011, 21.00 GMT

Version 3.2
"""
@@ -793,6 +793,26 @@
return wx.Colour(r, g, b)

+def FormatColour(colour):
+    """
+    Convert the input `colour` into a valid `wx.Colour` instance, using whatever typemap
+    accepted by wxWidgets/wxPython.
+
+    :param `colour`: can be an instance of `wx.Colour`, a 3 or 4 integer tuple, a hex
+     string, a string representing the colour name or ``None``.
+
+    :returns: a valid instance of `wx.Colour` or ``None`` if the input `colour` was ``None``
+     in the first place.
+    """
+
+    if isinstance(colour, (list, tuple)):
+        colour = wx.Colour(*colour)
+    elif isinstance(clr, basestring):
+        colour = wx.Colour(colour)
+
+    return colour
+
+
def RandomColour():
""" Creates a random colour. """

@@ -1209,6 +1229,8 @@
`wx.NullColour` to return to the default page text colour.
"""

+        colour = FormatColour(colour)
+
if colour is None or not colour.IsOk():
self._pageTextColour = None
else:
@@ -1274,10 +1296,11 @@
"""
Sets the tab colour.

-        :param `colour`: a valid `wx.Colour` object.
+        :param `colour`: a valid `wx.Colour` object or any typemap supported by wxWidgets/wxPython
+         to generate a colour (i.e., a hex string, a colour name, a 3 or 4 integer tuple).
"""

-        self._colour = colour
+        self._colour = FormatColour(colour)

# ---------------------------------------------------------------------------- #
@@ -4121,10 +4144,11 @@
"""
Sets the text colour for the active tab.

-        :param `textColour`: a valid `wx.Colour` object.
+        :param `textColour`: a valid `wx.Colour` object or any typemap supported by wxWidgets/wxPython
+         to generate a colour (i.e., a hex string, a colour name, a 3 or 4 integer tuple).
"""

-        self._pages._activeTextColour = textColour
+        self._pages._activeTextColour = FormatColour(textColour)

def OnDropTarget(self, x, y, nTabPage, wnd_oldContainer):
@@ -4970,10 +4994,11 @@
"""
Sets the non active tabs text colour.

-        :param `colour`: a valid instance of `wx.Colour`.
+        :param `colour`: a valid `wx.Colour` object or any typemap supported by wxWidgets/wxPython
+         to generate a colour (i.e., a hex string, a colour name, a 3 or 4 integer tuple).
"""

-        self._pages._nonActiveTextColour = colour
+        self._pages._nonActiveTextColour = FormatColour(colour)

def GetPageTextColour(self, page):
@@ -4991,8 +5016,9 @@
Sets the tab text colour individually.

:param `page`: an integer specifying the page index;
-        :param `colour`: an instance of `wx.Colour`. You can pass ``None`` or
-         `wx.NullColour` to return to the default page text colour.
+        :param `colour`: a valid `wx.Colour` object or any typemap supported by wxWidgets/wxPython
+         to generate a colour (i.e., a hex string, a colour name, a 3 or 4 integer tuple). You can
+         pass ``None`` or `wx.NullColour` to return to the default page text colour.
"""

self._pages.SetPageTextColour(page, colour)
@@ -5002,10 +5028,11 @@
"""
Sets the area behind the tabs colour.

-        :param `colour`: a valid instance of `wx.Colour`.
+        :param `colour`: a valid `wx.Colour` object or any typemap supported by wxWidgets/wxPython
+         to generate a colour (i.e., a hex string, a colour name, a 3 or 4 integer tuple).
"""

-        self._pages._tabAreaColour = colour
+        self._pages._tabAreaColour = FormatColour(colour)

def GetTabAreaColour(self):
@@ -5018,10 +5045,11 @@
"""
Sets the active tab colour.

-        :param `colour`: a valid instance of `wx.Colour`.
+        :param `colour`: a valid `wx.Colour` object or any typemap supported by wxWidgets/wxPython
+         to generate a colour (i.e., a hex string, a colour name, a 3 or 4 integer tuple).
"""

-        self._pages._activeTabColour = colour
+        self._pages._activeTabColour = FormatColour(colour)

def GetActiveTabColour(self):
@@ -6031,8 +6059,9 @@
Sets the tab text colour individually.

:param `page`: an integer specifying the page index;
-        :param `colour`: an instance of `wx.Colour`. You can pass ``None`` or
-         `wx.NullColour` to return to the default page text colour.
+        :param `colour`: a valid `wx.Colour` object or any typemap supported by wxWidgets/wxPython
+         to generate a colour (i.e., a hex string, a colour name, a 3 or 4 integer tuple). You can
+         pass ``None`` or `wx.NullColour` to return to the default page text colour.
"""

if page < len(self._pagesInfoVec):

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • flatnotebook »
  • SVN Revision 69551 For flatnotebook


floatspin functions

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • floatspin »
  • floatspin functions

floatspin functions

This is the description of standalone Python functions in the floatspin module.

Functions Summary

_mkFP
_norm
_roundquotient
_string2exact
_tento

API Functions API

_mkFP(n, p, FixedPoint=<class 'floatspin.FixedPoint'>) [source]

_norm(x, y, isinstance=<built-in function isinstance>, FixedPoint=<class 'floatspin.FixedPoint'>, _tento=<function _tento at 0x000000000630CE48>) [source]

_roundquotient(x, y) [source]

_string2exact(s) [source]

_tento(n, cache={}) [source]

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • infobar
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • floatspin »
  • floatspin functions


FixedPoint

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • floatspin »
  • FixedPoint

FixedPoint

FixedPoint objects support decimal arithmetic with a fixed number of digits (called the object’s precision) after the decimal point. The number of digits before the decimal point is variable & unbounded.

The precision is user-settable on a per-object basis when a FixedPoint is constructed, and may vary across FixedPoint objects. The precision may also be changed after construction via FixedPoint.set_precision(p). Note that if the precision of a FixedPoint is reduced via set_precision, information may be lost to rounding.

Example:

>>> x = FixedPoint("5.55")  # precision defaults to 2
>>> print x
5.55
>>> x.set_precision(1)      # round to one fraction digit
>>> print x
5.6
>>> print FixedPoint("5.55", 1)  # same thing setting to 1 in constructor
5.6
>>> repr(x) #  returns constructor string that reproduces object exactly
"FixedPoint('5.6', 1)"
>>>

When FixedPoint objects of different precision are combined via + - * /, the result is computed to the larger of the inputs’ precisions, which also becomes the precision of the resulting FixedPoint object. Example:

>>> print FixedPoint("3.42") + FixedPoint("100.005", 3)
103.425
>>>

When a FixedPoint is combined with other numeric types (ints, floats, strings representing a number) via + - * /, then similarly the computation is carried out using – and the result inherits – the FixedPoint‘s precision. Example:

>>> print FixedPoint(1) / 7
0.14
>>> print FixedPoint(1, 30) / 7
0.142857142857142857142857142857
>>>

The string produced by str(x) (implictly invoked by print) always contains at least one digit before the decimal point, followed by a decimal point, followed by exactly x.get_precision() digits. If x is negative, str(x)[0] == “-“.

The FixedPoint constructor can be passed an int, long, string, float, FixedPoint, or any object convertible to a float via float() or to a long via long(). Passing a precision is optional; if specified, the precision must be a non-negative int. There is no inherent limit on the size of the precision, but if very very large you’ll probably run out of memory.

Note that conversion of floats to FixedPoint can be surprising, and should be avoided whenever possible. Conversion from string is exact (up to final rounding to the requested precision), so is greatly preferred. Example:

>>> print FixedPoint(1.1e30)
1099999999999999993725589651456.00
>>> print FixedPoint("1.1e30")
1100000000000000000000000000000.00
>>>

hierarchy Inheritance Diagram

Inheritance diagram for: FixedPoint

Inheritance diagram of FixedPoint

Methods Summary

__init__ | Default class constructor.
_FixedPoint__reduce |
__abs__ |
__add__ |
__cmp__ |
__copy__ | Create a copy of the current FixedPoint.
__deepcopy__ | Create a copy of the current FixedPoint.
__div__ |
__divmod__ |
__float__ |
__hash__ |
__int__ |
__long__ |
__mod__ |
__mul__ |
__neg__ |
__nonzero__ |
__radd__ |
__rdiv__ |
__rdivmod__ |
__repr__ |
__rmod__ |
__rmul__ |
__rsub__ |
__str__ |
__sub__ |
copy | Create a copy of the current FixedPoint.
frac | Returns fractional portion as a FixedPoint.
get_precision | Return the precision of this FixedPoint.
set_precision | Change the precision carried by this FixedPoint to precision.

API Class API

class FixedPoint(object) [source]

FixedPoint objects support decimal arithmetic with a fixed number of digits (called the object’s precision) after the decimal point. The number of digits before the decimal point is variable & unbounded.

The precision is user-settable on a per-object basis when a FixedPoint is constructed, and may vary across FixedPoint objects. The precision may also be changed after construction via FixedPoint.set_precision(p). Note that if the precision of a FixedPoint is reduced via FixedPoint.set_precision(), information may be lost to rounding.

Example:

>>> x = FixedPoint("5.55")  # precision defaults to 2
>>> print x
5.55
>>> x.set_precision(1)      # round to one fraction digit
>>> print x
5.6
>>> print FixedPoint("5.55", 1)  # same thing setting to 1 in constructor
5.6
>>> repr(x) #  returns constructor string that reproduces object exactly
"FixedPoint('5.6', 1)"
>>>

When FixedPoint objects of different precision are combined via + - * /, the result is computed to the larger of the inputs’ precisions, which also becomes the precision of the resulting FixedPoint object. Example:

>>> print FixedPoint("3.42") + FixedPoint("100.005", 3)
103.425
>>>

When a FixedPoint is combined with other numeric types (ints, floats, strings representing a number) via + - * /, then similarly the computation is carried out using – and the result inherits – the FixedPoint‘s precision. Example:

>>> print FixedPoint(1) / 7
0.14
>>> print FixedPoint(1, 30) / 7
0.142857142857142857142857142857
>>>

The string produced by str(x) (implictly invoked by print) always contains at least one digit before the decimal point, followed by a decimal point, followed by exactly x.get_precision() digits. If x is negative, str(x)[0] == “-“.

The FixedPoint constructor can be passed an int, long, string, float, FixedPoint, or any object convertible to a float via float() or to a long via long(). Passing a precision is optional; if specified, the precision must be a non-negative int. There is no inherent limit on the size of the precision, but if very very large you’ll probably run out of memory.

Note that conversion of floats to FixedPoint can be surprising, and should be avoided whenever possible. Conversion from string is exact (up to final rounding to the requested precision), so is greatly preferred. Example:

>>> print FixedPoint(1.1e30)
1099999999999999993725589651456.00
>>> print FixedPoint("1.1e30")
1100000000000000000000000000000.00
>>>
Inherited-members :

__init__(value=0, precision=DEFAULT_PRECISION) [source]

Default class constructor.

Parameters:
  • value – the initial value;
  • precision – must be an int >= 0, and defaults to DEFAULT_PRECISION.

copy() [source]

Create a copy of the current FixedPoint.

frac() [source]

Returns fractional portion as a FixedPoint.

Note

In FixedPoint,

this equality holds true:

x = x.frac() + long(x)

get_precision() [source]

Return the precision of this FixedPoint.

Note

The precision is the number of decimal digits carried after the decimal point, and is an int >= 0.

set_precision(precision=DEFAULT_PRECISION) [source]

Change the precision carried by this FixedPoint to precision.

Parameters: precision – must be an int >= 0, and defaults to DEFAULT_PRECISION.

Note

If precision is less than this FixedPoint’s current precision, information may be lost to rounding.

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • infobar
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • floatspin »
  • FixedPoint


FloatSpin

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • floatspin »
  • FloatSpin

FloatSpin

FloatSpin implements a floating point wx.SpinCtrl. It is built using a custom wx.PyControl, composed by a wx.TextCtrl and a wx.SpinButton. In order to correctly handle floating points numbers without rounding errors or non-exact floating point representations, FloatSpin uses the great FixedPoint class from Tim Peters.

hierarchy Inheritance Diagram

Inheritance diagram for: FloatSpin

Inheritance diagram of FloatSpin

appearance Control Appearance

FloatSpin

Methods Summary

__init__ | Default class constructor.
ClampValue | Clamps var between _min and _max depending if the range has been specified.
DoGetBestSize | Gets the size which best suits the window: for a control, it would be the
DoSendEvent | Send the event to the parent.
GetDefaultValue | Returns the FloatSpin default value.
GetDigits | Returns the number of digits shown.
GetFont | Returns the underlying wx.TextCtrl font.
GetFormat | Returns the string format in use.
GetIncrement | Returns the increment for every EVT_FLOATSPIN event.
GetMax | Returns the maximum value for FloatSpin. It can be a
GetMin | Returns the minimum value for FloatSpin. It can be a
GetSnapToTicks | Returns whether the snap to ticks option is active or not.
GetTextCtrl | Returns the underlying wx.TextCtrl.
GetValue | Returns the FloatSpin value.
HasRange | Returns whether FloatSpin range has been set or not.
InRange | Returns whether a value is inside FloatSpin range.
IsDefaultValue | Returns whether the current value is the default value or not.
IsFinite | Tries to determine if a value is finite or infinite/NaN.
OnChar | Handles the wx.EVT_CHAR event for FloatSpin.
OnDestroy | Handles the wx.EVT_WINDOW_DESTROY event for FloatSpin.
OnFocus | Handles the wx.EVT_SET_FOCUS event for FloatSpin.
OnKillFocus | Handles the wx.EVT_KILL_FOCUS event for FloatSpin.
OnMouseWheel | Handles the wx.EVT_MOUSEWHEEL event for FloatSpin.
OnSize | Handles the wx.EVT_SIZE event for FloatSpin.
OnSpinDown | Handles the wx.EVT_SPIN_DOWN event for FloatSpin.
OnSpinMouseDown | Handles the wx.EVT_LEFT_DOWN event for FloatSpin.
OnSpinUp | Handles the wx.EVT_SPIN_UP event for FloatSpin.
OnTextEnter | Handles the wx.EVT_TEXT_ENTER event for FloatSpin.
ReplaceDoubleZero | Replaces the (somewhat) python ugly +e000 with +e00.
SetDefaultValue | Sets the FloatSpin default value.
SetDigits | Sets the number of digits to show.
SetFont | Sets the underlying wx.TextCtrl font.
SetFormat | Set the string format to use.
SetIncrement | Sets the increment for every EVT_FLOATSPIN event.
SetRange | Sets the allowed range.
SetRangeDontClampValue | Sets the allowed range.
SetSnapToTicks | Force the value to always be divisible by the increment.
SetToDefaultValue | Sets FloatSpin value to its default value.
SetValue | Sets the FloatSpin value.
SyncSpinToText | Synchronize the underlying wx.TextCtrl with wx.SpinButton.

API Class API

class FloatSpin(wx.PyControl) [source]

FloatSpin implements a floating point wx.SpinCtrl. It is built using a custom wx.PyControl, composed by a wx.TextCtrl and a wx.SpinButton. In order to correctly handle floating points numbers without rounding errors or non-exact floating point representations, FloatSpin uses the great FixedPoint class from Tim Peters.

__init__(parent, id=wx.ID_ANY, pos=wx.DefaultPosition, size=(95, -1), style=0, value=0.0, min_val=None, max_val=None, increment=1.0, digits=-1, agwStyle=FS_LEFT, name="FloatSpin") [source]

Default class constructor.

Parameters:
  • parent – the FloatSpin parent;
  • id – an identifier for the control: a value of -1 is taken to mean a default;
  • pos – the control position. A value of (-1, -1) indicates a default position, chosen by either the windowing system or wxPython, depending on platform;
  • size – the control size. A value of (-1, -1) indicates a default size, chosen by either the windowing system or wxPython, depending on platform;
  • style – the window style;
  • value – is the current value for FloatSpin;
  • min_val – the minimum value, ignored if None;
  • max_val – the maximum value, ignored if None;
  • increment – the increment for every FloatSpinEvent event;
  • digits – number of representative digits for your floating point numbers;
  • agwStyle – one of the following bits:

    Window Styles | Hex Value | Description
    FS_READONLY | 0x1 | Sets FloatSpin as read-only control.
    FS_LEFT | 0x2 | Horizontally align the underlying wx.TextCtrl on the left.
    FS_CENTRE | 0x4 | Horizontally align the underlying wx.TextCtrl on center.
    FS_RIGHT | 0x8 | Horizontally align the underlying wx.TextCtrl on the right.
  • name – the window name.

ClampValue(var) [source]

Clamps var between _min and _max depending if the range has been specified.

Parameters: var – the value to be clamped.
Returns: A clamped copy of var.

DoGetBestSize() [source]

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

Note

Overridden from wx.PyControl.

DoSendEvent() [source]

Send the event to the parent.

GetDefaultValue() [source]

Returns the FloatSpin default value.

GetDigits() [source]

Returns the number of digits shown.

GetFont() [source]

Returns the underlying wx.TextCtrl font.

GetFormat() [source]

Returns the string format in use.

See also

SetFormat for a list of valid string formats.

GetIncrement() [source]

Returns the increment for every EVT_FLOATSPIN event.

GetMax() [source]

Returns the maximum value for FloatSpin. It can be a number or None if no minimum is present.

GetMin() [source]

Returns the minimum value for FloatSpin. It can be a number or None if no minimum is present.

GetSnapToTicks() [source]

Returns whether the snap to ticks option is active or not.

GetTextCtrl() [source]

Returns the underlying wx.TextCtrl.

GetValue() [source]

Returns the FloatSpin value.

HasRange() [source]

Returns whether FloatSpin range has been set or not.

InRange(value) [source]

Returns whether a value is inside FloatSpin range.

Parameters: value – the value to test.

IsDefaultValue() [source]

Returns whether the current value is the default value or not.

IsFinite(value) [source]

Tries to determine if a value is finite or infinite/NaN.

Parameters: value – the value to test.

OnChar(event) [source]

Handles the wx.EVT_CHAR event for FloatSpin.

Parameters: event – a wx.KeyEvent event to be processed.

Note

This method works on the underlying wx.TextCtrl.

OnDestroy(event) [source]

Handles the wx.EVT_WINDOW_DESTROY event for FloatSpin.

Parameters: event – a wx.WindowDestroyEvent event to be processed.

Note

This method tries to correctly handle the control destruction under MSW.

OnFocus(event) [source]

Handles the wx.EVT_SET_FOCUS event for FloatSpin.

Parameters: event – a wx.FocusEvent event to be processed.

OnKillFocus(event) [source]

Handles the wx.EVT_KILL_FOCUS event for FloatSpin.

Parameters: event – a wx.FocusEvent event to be processed.

OnMouseWheel(event) [source]

Handles the wx.EVT_MOUSEWHEEL event for FloatSpin.

Parameters: event – a wx.MouseEvent event to be processed.

OnSize(event) [source]

Handles the wx.EVT_SIZE event for FloatSpin.

Parameters: event – a wx.SizeEvent event to be processed.

Note

This method resizes the text control and reposition the spin button when resized.

OnSpinDown(event) [source]

Handles the wx.EVT_SPIN_DOWN event for FloatSpin.

Parameters: event – a wx.SpinEvent event to be processed.

OnSpinMouseDown(event) [source]

Handles the wx.EVT_LEFT_DOWN event for FloatSpin.

Parameters: event – a wx.MouseEvent event to be processed.

Note

This method works on the underlying wx.SpinButton.

OnSpinUp(event) [source]

Handles the wx.EVT_SPIN_UP event for FloatSpin.

Parameters: event – a wx.SpinEvent event to be processed.

OnTextEnter(event) [source]

Handles the wx.EVT_TEXT_ENTER event for FloatSpin.

Parameters: event – a wx.KeyEvent event to be processed.

Note

This method works on the underlying wx.TextCtrl.

ReplaceDoubleZero(strs) [source]

Replaces the (somewhat) python ugly +e000 with +e00.

Parameters: strs – a string (possibly) containing a +e00 substring.

SetDefaultValue(defaultvalue) [source]

Sets the FloatSpin default value.

Parameters: defaultvalue – a floating point value representing the new default value for FloatSpin.

SetDigits(digits=-1) [source]

Sets the number of digits to show.

Parameters: digits – the number of digits to show. If digits < 0, FloatSpin tries to calculate the best number of digits based on input values passed in the constructor.

SetFont(font=None) [source]

Sets the underlying wx.TextCtrl font.

Parameters: font – a valid instance of wx.Font.

SetFormat(fmt='%f') [source]

Set the string format to use.

Parameters: fmt – the new string format to use. One of the following strings:

Format | Description
‘e’ | Floating point exponential format (lowercase)
‘E’ | Floating point exponential format (uppercase)
‘f’ | Floating point decimal format
‘F’ | Floating point decimal format
‘g’ | Floating point format. Uses lowercase exponential format if exponent is less than -4 or not less than precision, decimal format otherwise
‘G’ | Floating point format. Uses uppercase exponential format if exponent is less than -4 or not less than precision, decimal format otherwise

SetIncrement(increment) [source]

Sets the increment for every EVT_FLOATSPIN event.

Parameters: increment – a floating point number specifying the FloatSpin increment.

SetRange(min_val, max_val) [source]

Sets the allowed range.

Parameters:
  • min_val – the minimum value for FloatSpin. If it is None it is ignored;
  • max_val – the maximum value for FloatSpin. If it is None it is ignored.

Note

This method doesn’t modify the current value.

Note

You specify open ranges like this (you can equally do this in the constructor):

SetRange(min_val=1, max_val=None)
SetRange(min_val=None, max_val=0)

or no range:

SetRange(min_val=None, max_val=None)

SetRangeDontClampValue(min_val, max_val) [source]

Sets the allowed range.

Parameters:
  • min_val – the minimum value for FloatSpin. If it is None it is ignored;
  • max_val – the maximum value for FloatSpin. If it is None it is ignored.

Note

This method doesn’t modify the current value.

SetSnapToTicks(forceticks=True) [source]

Force the value to always be divisible by the increment. Initially False.

Parameters: forceticks – True to force the snap to ticks option, False otherwise.

Note

This uses the default value as the basis, you will get strange results for very large differences between the current value and default value when the increment is very small.

SetToDefaultValue() [source]

Sets FloatSpin value to its default value.

SetValue(value) [source]

Sets the FloatSpin value.

Parameters: value – the new value.

SyncSpinToText(send_event=True, force_valid=True) [source]

Synchronize the underlying wx.TextCtrl with wx.SpinButton.

Parameters:
  • send_event – True to send a EVT_FLOATSPIN event, False otherwise;
  • force_valid – True to force a valid value (i.e. inside the provided range), False otherwise.

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • infobar
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • floatspin »
  • FloatSpin


FloatSpinEvent

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • floatspin »
  • FloatSpinEvent

FloatSpinEvent

This event will be sent when a EVT_FLOATSPIN event is mapped in the parent.

hierarchy Inheritance Diagram

Inheritance diagram for: FloatSpinEvent

Inheritance diagram of FloatSpinEvent

Methods Summary

__init__ | Default class constructor.
GetPosition | Returns event position.
SetPosition | Sets event position.

API Class API

class FloatSpinEvent(wx.PyCommandEvent) [source]

This event will be sent when a EVT_FLOATSPIN event is mapped in the parent.

__init__(eventType, eventId=1, nSel=-1, nOldSel=-1) [source]

Default class constructor.

Parameters:
  • eventType – the event type;
  • eventId – the event identifier;
  • nSel – the current selection;
  • nOldSel – the old selection.

GetPosition() [source]

Returns event position.

SetPosition(pos) [source]

Sets event position.

Parameters: pos – an integer specyfing the event position.

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • infobar
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • floatspin »
  • FloatSpinEvent


FloatTextCtrl

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • floatspin »
  • FloatTextCtrl

FloatTextCtrl

A class which holds a wx.TextCtrl, one of the two building blocks of FloatSpin.

hierarchy Inheritance Diagram

Inheritance diagram for: FloatTextCtrl

Inheritance diagram of FloatTextCtrl

Methods Summary

__init__ | Default class constructor.
OnChar | Handles the wx.EVT_CHAR event for FloatTextCtrl.
OnDestroy | Handles the wx.EVT_WINDOW_DESTROY event for FloatTextCtrl.
OnKillFocus | Handles the wx.EVT_KILL_FOCUS event for FloatTextCtrl.

API Class API

class FloatTextCtrl(wx.TextCtrl) [source]

A class which holds a wx.TextCtrl, one of the two building blocks of FloatSpin.

__init__(parent, id=wx.ID_ANY, value="", pos=wx.DefaultPosition, size=wx.DefaultSize, style=wx.TE_NOHIDESEL | wx.TE_PROCESS_ENTER, validator=wx.DefaultValidator, name=wx.TextCtrlNameStr) [source]

Default class constructor. Used internally. Do not call directly this class in your code!

Parameters:
  • parent – the FloatTextCtrl parent;
  • id – an identifier for the control: a value of -1 is taken to mean a default;
  • value – default text value;
  • pos – the control position. A value of (-1, -1) indicates a default position, chosen by either the windowing system or wxPython, depending on platform;
  • size – the control size. A value of (-1, -1) indicates a default size, chosen by either the windowing system or wxPython, depending on platform;
  • style – the window style;
  • validator – the window validator;
  • name – the window name.

OnChar(event) [source]

Handles the wx.EVT_CHAR event for FloatTextCtrl.

Parameters: event – a wx.KeyEvent event to be processed.

OnDestroy(event) [source]

Handles the wx.EVT_WINDOW_DESTROY event for FloatTextCtrl.

Parameters: event – a wx.WindowDestroyEvent event to be processed.

Note

This method tries to correctly handle the control destruction under MSW.

OnKillFocus(event) [source]

Handles the wx.EVT_KILL_FOCUS event for FloatTextCtrl.

Parameters: event – a wx.FocusEvent event to be processed.

Note

This method synchronizes the wx.SpinButton and the wx.TextCtrl when focus is lost.

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • infobar
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • floatspin »
  • FloatTextCtrl


SVN Revision 68350 For floatspin

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • floatspin »
  • SVN Revision 68350 For floatspin

svn SVN Revision 68350 For floatspin

This file contains the SVN revision history for floatspin, at revision 68350.

Available information include commit date, the name of the committer, the file size, the SVN log messages and a diff from the previous version (if available).

File Information

  • Commit Date: 25-Feb-2009 23:46:10 UTC
  • Committer: AG
  • File Size: 52162 byte(s)

Log Messages

The following log message was entered by the committer:

Bind the mouse wheel events to the spinbutton and textctrl instead of to FloatSpin

Diff To Previous Version (65774)

Version SVN diff:

--- wxPython/3rdParty/AGW/agw/floatspin.py  2010/10/05 23:38:27     65774
+++ wxPython/3rdParty/AGW/agw/floatspin.py  2011/07/23 23:26:40     68350
@@ -3,7 +3,7 @@
# Python Code By:
#
# Andrea Gavana, @ 16 Nov 2005
-# Latest Revision: 21 Sep 2010, 23.00 GMT
+# Latest Revision: 22 Jul 2011, 21.00 GMT
#
#
# TODO List/Caveats
@@ -101,7 +101,7 @@

FloatSpin control is distributed under the wxPython license.

-Latest revision: Andrea Gavana @ 21 Sep 2010, 23.00 GMT
+Latest revision: Andrea Gavana @ 22 Jul 2011, 21.00 GMT

Version 0.9

@@ -459,9 +459,11 @@
self._spinbutton.Bind(wx.EVT_LEFT_DOWN, self.OnSpinMouseDown)

self._textctrl.Bind(wx.EVT_TEXT_ENTER, self.OnTextEnter)
+        self._textctrl.Bind(wx.EVT_MOUSEWHEEL, self.OnMouseWheel)
+        self._spinbutton.Bind(wx.EVT_MOUSEWHEEL, self.OnMouseWheel)
+
self.Bind(wx.EVT_SET_FOCUS, self.OnFocus)
self.Bind(wx.EVT_KILL_FOCUS, self.OnKillFocus)
-        self.Bind(wx.EVT_MOUSEWHEEL, self.OnMouseWheel)
self.Bind(wx.EVT_SIZE, self.OnSize)

# start Philip Semanchuk move

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • floatspin »
  • SVN Revision 68350 For floatspin


SVN Revision 68881 For floatspin

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • floatspin »
  • SVN Revision 68881 For floatspin

svn SVN Revision 68881 For floatspin

This file contains the SVN revision history for floatspin, at revision 68881.

Available information include commit date, the name of the committer, the file size, the SVN log messages and a diff from the previous version (if available).

File Information

  • Commit Date: 17-Oct-2008 20:51:43 UTC
  • Committer: AG
  • File Size: 52908 byte(s)

Log Messages

The following log message was entered by the committer:

  • AGW: General overhaul of the documentation, much improved. All the widgets have their own sample usage in the docs as well;

  • FlatNotebook: Added the FNB_NAV_BUTTONS_WHEN_NEEDED style, which hides the navigation left/right arrows if all tabs fit;

  • RibbonBar: - Added the EVT_RIBBONBAR_TAB_LEFT_DCLICK event, which generates a special event

    when a ribbon bar tab is double-clicked;

    • Added support for toggle buttons;
    • Improved support for ribbon panel sizers: panels with sizers should now automatically minimise at small sizes, and behave properly when popping up from a minimised state;
    • Added tooltips via SetToolTip for those buttons which have the help_string attribute set.

  • XLSGrid: a new widget was added to AGW, termed XLSGrid. It’s based on wx.grid.Grid and can be used to faithfully reproduce the appearance of a Microsoft Excel spreadsheets.

Diff To Previous Version (68362)

Version SVN diff:

--- wxPython/3rdParty/AGW/agw/floatspin.py  2011/07/24 21:36:47     68362
+++ wxPython/3rdParty/AGW/agw/floatspin.py  2011/08/25 16:40:17     68881
@@ -3,7 +3,7 @@
# Python Code By:
#
# Andrea Gavana, @ 16 Nov 2005
-# Latest Revision: 22 Jul 2011, 21.00 GMT
+# Latest Revision: 17 Aug 2011, 15.00 GMT
#
#
# TODO List/Caveats
@@ -24,16 +24,16 @@

"""
-FloatSpin implements a floating point `wx.SpinCtrl`.
+L{FloatSpin} implements a floating point `wx.SpinCtrl`.

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

-FloatSpin implements a floating point `wx.Spinctrl`. It is built using a custom
+L{FloatSpin} implements a floating point `wx.Spinctrl`. It is built using a custom
`wx.PyControl`, composed by a `wx.TextCtrl` and a `wx.SpinButton`. In order to
correctly handle floating points numbers without rounding errors or non-exact
-floating point representations, FloatSpin uses the great L{FixedPoint} class
+floating point representations, L{FloatSpin} uses the great L{FixedPoint} class
from Tim Peters.

What you can do:
@@ -41,19 +41,53 @@
- Set the number of representative digits for your floating point numbers;
- Set the floating point format (``%f``, ``%F``, ``%e``, ``%E``, ``%g``, ``%G``);
- Set the increment of every ``EVT_FLOATSPIN`` event;
-- Set minimum, maximum values for FloatSpin as well as its range;
+- Set minimum, maximum values for L{FloatSpin} as well as its range;
- Change font and colour for the underline `wx.TextCtrl`.

+Usage
+=====
+
+Usage example::
+
+    import wx
+    import wx.lib.agw.floatspin as FS
+
+    class MyFrame(wx.Frame):
+
+        def __init__(self, parent):
+
+            wx.Frame.__init__(self, parent, -1, "FloatSpin Demo")
+
+            panel = wx.Panel(self)
+
+            floatspin = FS.FloatSpin(panel, -1, pos=(50, 50), min_val=0, max_val=1,
+                                     increment=0.01, value=0.1, agwStyle=FS.FS_LEFT)
+            floatspin.SetFormat("%f")
+            floatspin.SetDigits(2)
+
+
+    # our normal wxApp-derived class, as usual
+
+    app = wx.PySimpleApp()
+
+    frame = MyFrame(None)
+    app.SetTopWindow(frame)
+    frame.Show()
+
+    app.MainLoop()
+
+
+
Events
======

-FloatSpin catches 3 different types of events:
+L{FloatSpin} catches 3 different types of events:

1) Spin events: events generated by spinning up/down the spinbutton;
2) Char events: playing with up/down arrows of the keyboard increase/decrease
-   the value of FloatSpin;
-3) Mouse wheel event: using the wheel will change the value of FloatSpin.
+   the value of L{FloatSpin};
+3) Mouse wheel event: using the wheel will change the value of L{FloatSpin}.

In addition, there are some other functionalities:

@@ -62,7 +96,7 @@
- ``Shift`` + arrow = 2 * increment        (or ``Shift`` + mouse wheel);
- ``Ctrl``  + arrow = 10 * increment       (or ``Ctrl`` + mouse wheel);
- ``Alt``   + arrow = 100 * increment      (or ``Alt`` + mouse wheel);
-- Combinations of ``Shift``, ``Ctrl``, ``Alt`` increment the FloatSpin value by the
+- Combinations of ``Shift``, ``Ctrl``, ``Alt`` increment the L{FloatSpin} value by the
product of the factors;
- ``PgUp`` & ``PgDn`` = 10 * increment * the product of the ``Shift``, ``Ctrl``, ``Alt``
factors;
@@ -77,7 +111,7 @@
=============== =========== ==================================================
Window Styles   Hex Value   Description
=============== =========== ==================================================
-``FS_READONLY``         0x1 Sets `FloatSpin` as read-only control.
+``FS_READONLY``         0x1 Sets L{FloatSpin} as read-only control.
``FS_LEFT``             0x2 Horizontally align the underlying `wx.TextCtrl` on the left.
``FS_CENTRE``           0x4 Horizontally align the underlying `wx.TextCtrl` on center.
``FS_RIGHT``            0x8 Horizontally align the underlying `wx.TextCtrl` on the right.
@@ -92,16 +126,16 @@
================= ==================================================
Event Name        Description
================= ==================================================
-``EVT_FLOATSPIN`` Emitted when the user changes the value of `FloatSpin`, either with the mouse or with the keyboard.
+``EVT_FLOATSPIN`` Emitted when the user changes the value of L{FloatSpin}, either with the mouse or with the keyboard.
================= ==================================================

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

-FloatSpin control is distributed under the wxPython license.
+L{FloatSpin} control is distributed under the wxPython license.

-Latest revision: Andrea Gavana @ 22 Jul 2011, 21.00 GMT
+Latest revision: Andrea Gavana @ 17 Aug 2011, 15.00 GMT

Version 0.9

@@ -111,9 +145,9 @@

Modifications to allow `min_val` or `max_val` to be ``None`` done by:

-  James Bigler
-  sci institute, university of utah
-  march 14, 2007
+James Bigler,
+SCI Institute, University of Utah,
+March 14, 2007

:note: Note that the changes I made will break backward compatibility,
because I changed the contructor's parameters from `min` / `max` to
@@ -144,7 +178,7 @@

# Set The Styles For The Underline wx.TextCtrl
FS_READONLY = 1
-""" Sets `FloatSpin` as read-only control. """
+""" Sets L{FloatSpin} as read-only control. """
FS_LEFT = 2
""" Horizontally align the underlying `wx.TextCtrl` on the left. """
FS_CENTRE = 4
@@ -160,7 +194,7 @@
#-----------------------------------#

EVT_FLOATSPIN = wx.PyEventBinder(wxEVT_FLOATSPIN, 1)
-""" Emitted when the user changes the value of `FloatSpin`, either with the mouse or""" \
+""" Emitted when the user changes the value of L{FloatSpin}, either with the mouse or""" \
""" with the keyboard. """

# ---------------------------------------------------------------------------- #
@@ -288,10 +322,10 @@

class FloatSpin(wx.PyControl):
"""
-    FloatSpin implements a floating point `wx.Spinctrl`. It is built using a custom
+    L{FloatSpin} implements a floating point `wx.Spinctrl`. It is built using a custom
`wx.PyControl`, composed by a `wx.TextCtrl` and a `wx.SpinButton`. In order to
correctly handle floating points numbers without rounding errors or non-exact
-    floating point representations, FloatSpin uses the great L{FixedPoint} class
+    floating point representations, L{FloatSpin} uses the great L{FixedPoint} class
from Tim Peters.
"""

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • floatspin »
  • SVN Revision 68881 For floatspin


SVN Revision 69086 For floatspin

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • floatspin »
  • SVN Revision 69086 For floatspin

svn SVN Revision 69086 For floatspin

This file contains the SVN revision history for floatspin, at revision 69086.

Available information include commit date, the name of the committer, the file size, the SVN log messages and a diff from the previous version (if available).

File Information

  • Commit Date: 17-Oct-2008 19:15:31 UTC
  • Committer: AG
  • File Size: 52908 byte(s)

Log Messages

The following log message was entered by the committer:

  • Fixed bug #13437 for SuperToolTip;
  • Fixed bug #13477 for UltimateListCtrl.

Diff To Previous Version (68881)

Version SVN diff:

--- wxPython/3rdParty/AGW/agw/floatspin.py  2011/08/25 16:40:17     68881
+++ wxPython/3rdParty/AGW/agw/floatspin.py  2011/09/14 19:39:08     69086
@@ -30,7 +30,7 @@
Description
===========

-L{FloatSpin} implements a floating point `wx.Spinctrl`. It is built using a custom
+L{FloatSpin} implements a floating point `wx.SpinCtrl`. It is built using a custom
`wx.PyControl`, composed by a `wx.TextCtrl` and a `wx.SpinButton`. In order to
correctly handle floating points numbers without rounding errors or non-exact
floating point representations, L{FloatSpin} uses the great L{FixedPoint} class
@@ -322,7 +322,7 @@

class FloatSpin(wx.PyControl):
"""
-    L{FloatSpin} implements a floating point `wx.Spinctrl`. It is built using a custom
+    L{FloatSpin} implements a floating point `wx.SpinCtrl`. It is built using a custom
`wx.PyControl`, composed by a `wx.TextCtrl` and a `wx.SpinButton`. In order to
correctly handle floating points numbers without rounding errors or non-exact
floating point representations, L{FloatSpin} uses the great L{FixedPoint} class

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • floatspin »
  • SVN Revision 69086 For floatspin


FMCustomizeDlg

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • fmcustomizedlg »
  • FMCustomizeDlg

FMCustomizeDlg

Class used to customize the appearance of FlatMenu and FlatMenuBar.

hierarchy Inheritance Diagram

Inheritance diagram for: FMCustomizeDlg

Inheritance diagram of FMCustomizeDlg

appearance Control Appearance

FMCustomizeDlg

Methods Summary

__init__ | Default class constructor.
CloseDialog | Closes the dialog.
ConnectEvents | Does nothing at the moment.
CreateDialog | Actually creates the dialog.
CreateMenusPage | Creates the LabelBook pages with FlatMenu information.
CreateOptionsPage | Creates the LabelBook option page which holds the FlatMenu styles.
CreateShortcutsPage | Creates the LabelBook shorcuts page.
Initialise | Initialzes the LabelBook pages.
OnChangeStyle | Handles the wx.EVT_CHECKBOX event for FMCustomizeDlg.
OnMenuChecked | Handles the wx.EVT_CHECKBOX event for FMCustomizeDlg.

API Class API

class FMCustomizeDlg(wx.Dialog) [source]

Class used to customize the appearance of FlatMenu and FlatMenuBar.

__init__(parent=None) [source]

Default class constructor.

Parameters: parent – the FMCustomizeDlg parent window.

CloseDialog() [source]

Closes the dialog.

ConnectEvents() [source]

Does nothing at the moment.

CreateDialog() [source]

Actually creates the dialog.

CreateMenusPage() [source]

Creates the LabelBook pages with FlatMenu information.

CreateOptionsPage() [source]

Creates the LabelBook option page which holds the FlatMenu styles.

CreateShortcutsPage() [source]

Creates the LabelBook shorcuts page.

Initialise() [source]

Initialzes the LabelBook pages.

OnChangeStyle(event) [source]

Handles the wx.EVT_CHECKBOX event for FMCustomizeDlg.

Parameters: event – a wx.CommandEvent event to be processed.

Note

This method handles the FlatMenu styles.

OnMenuChecked(event) [source]

Handles the wx.EVT_CHECKBOX event for FMCustomizeDlg.

Parameters: event – a wx.CommandEvent event to be processed.

Note

This method handles the FlatMenu menus visibility.

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • infobar
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • fmcustomizedlg »
  • FMCustomizeDlg


FMTitlePanel

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • fmcustomizedlg »
  • FMTitlePanel

FMTitlePanel

Helper class to draw gradient shadings on the dialog.

hierarchy Inheritance Diagram

Inheritance diagram for: FMTitlePanel

Inheritance diagram of FMTitlePanel

Methods Summary

__init__ | Default class constructor.
OnEraseBackground | Handles the wx.EVT_ERASE_BACKGROUND event for FMTitlePanel.
OnPaint | Handles the wx.EVT_PAINT event for FMTitlePanel.

API Class API

class FMTitlePanel(wx.Panel) [source]

Helper class to draw gradient shadings on the dialog.

__init__(parent, title) [source]

Default class constructor.

Parameters:
  • parent – the FMTitlePanel parent;
  • title – the string to use as a dialog title.

OnEraseBackground(event) [source]

Handles the wx.EVT_ERASE_BACKGROUND event for FMTitlePanel.

Parameters: event – a wx.EraseEvent event to be processed.

Note

This method is intentionally empty to reduce flicker.

OnPaint(event) [source]

Handles the wx.EVT_PAINT event for FMTitlePanel.

Parameters: event – a wx.PaintEvent event to be processed.

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • infobar
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • fmcustomizedlg »
  • FMTitlePanel


CaptionBar

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • foldpanelbar »
  • CaptionBar

CaptionBar

This class is a graphical caption component that consists of a caption and a clickable arrow.

The CaptionBar fires an event EVT_CAPTIONBAR which is a CaptionBarEvent. This event can be caught and the parent window can act upon the collapsed or expanded state of the bar (which is actually just the icon which changed). The parent panel can reduce size or expand again.

hierarchy Inheritance Diagram

Inheritance diagram for: CaptionBar

Inheritance diagram of CaptionBar

Methods Summary

__init__ | Default class constructor.
ApplyCaptionStyle | Applies the style defined in cbstyle to the CaptionBar.
Collapse | This sets the internal state/representation to collapsed.
DoGetBestSize | Returns the best size for this panel, based upon the font assigned to this window, and the caption string.
DrawHorizontalGradient | Gradient fill from colour 1 to colour 2 from left to right.
DrawSingleColour | Single colour fill for CaptionBar.
DrawSingleRectangle | Single rectangle for CaptionBar.
DrawVerticalGradient | Gradient fill from colour 1 to colour 2 from top to bottom.
Expand | This sets the internal state/representation to expanded.
FillCaptionBackground | Fills the background of the caption with either a gradient or a solid colour.
GetCaptionStyle | Returns the current style of the captionbar in a CaptionBarStyle class.
IsCollapsed | Returns wether the status of the bar is expanded or collapsed.
IsVertical | Returns wether the CaptionBar has a default orientation or not.
OnChar | Handles the wx.EVT_CHAR event for CaptionBar.
OnMouseEvent | Handles the wx.EVT_MOUSE_EVENTS event for CaptionBar.
OnPaint | Handles the wx.EVT_PAINT event for CaptionBar.
OnSize | Handles the wx.EVT_SIZE event for CaptionBar.
RedrawIconBitmap | Redraws the icons (if they exists).
SetBoldFont | Sets the CaptionBar font weight to bold.
SetCaptionStyle | Sets CaptionBar styles with CaptionBarStyle class.
SetNormalFont | Sets the CaptionBar font weight to normal.
SetRightIndent | Sets the amount of pixels on the right from which the bitmap is trailing.

API Class API

class CaptionBar(wx.Window) [source]

This class is a graphical caption component that consists of a caption and a clickable arrow.

The CaptionBar fires an event EVT_CAPTIONBAR which is a CaptionBarEvent. This event can be caught and the parent window can act upon the collapsed or expanded state of the bar (which is actually just the icon which changed). The parent panel can reduce size or expand again.

__init__(parent, id, pos, size, caption="", foldIcons=None, cbstyle=None, rightIndent=FPB_BMP_RIGHTSPACE, iconWidth=16, iconHeight=16, collapsed=False) [source]

Default class constructor.

Parameters:
  • parent – the CaptionBar parent window;
  • id – an identifier for the control: a value of -1 is taken to mean a default;
  • pos – the control position. A value of (-1, -1) indicates a default position, chosen by either the windowing system or wxPython, depending on platform;
  • size – the control size. A value of (-1, -1) indicates a default size, chosen by either the windowing system or wxPython, depending on platform;
  • caption – the string to be displayed in CaptionBar;
  • foldIcons – an instance of wx.ImageList containing the icons to display next to the caption text;
  • cbstyle – the CaptionBar window style. Must be an instance of CaptionBarStyle;
  • rightIndent – number of pixels of the bmp to be aligned from the right filled with space;
  • iconWidth – the CaptionBar icon width;
  • iconHeight – the CaptionBar icon height;
  • collapsed – True if the CaptionBar should start in the collapsed state, False otherwise.

ApplyCaptionStyle(cbstyle=None, applyDefault=True) [source]

Applies the style defined in cbstyle to the CaptionBar.

Parameters:
  • cbstyle – an instance of CaptionBarStyle;
  • applyDefault – if True, the colours used in the CaptionBarStyle will be reset to their default values.

Collapse() [source]

This sets the internal state/representation to collapsed.

Note

This does not trigger a CaptionBarEvent to be sent to the parent.

DoGetBestSize() [source]

Returns the best size for this panel, based upon the font assigned to this window, and the caption string.

Note

Overridden from wx.Window.

DrawHorizontalGradient(dc, rect) [source]

Gradient fill from colour 1 to colour 2 from left to right.

Parameters:
  • dc – an instance of wx.DC;
  • rect – the CaptionBar client rectangle.

DrawSingleColour(dc, rect) [source]

Single colour fill for CaptionBar.

Parameters:
  • dc – an instance of wx.DC;

  • rect – the CaptionBar client rectangle.

DrawSingleRectangle(dc, rect) [source]

Single rectangle for CaptionBar.

Parameters:
  • dc – an instance of wx.DC;

  • rect – the CaptionBar client rectangle.

DrawVerticalGradient(dc, rect) [source]

Gradient fill from colour 1 to colour 2 from top to bottom.

Parameters:
  • dc – an instance of wx.DC;

  • rect – the CaptionBar client rectangle.

Expand() [source]

This sets the internal state/representation to expanded.

Note

This does not trigger a CaptionBarEvent to be sent to the parent.

FillCaptionBackground(dc) [source]

Fills the background of the caption with either a gradient or a solid colour.

Parameters: dc – an instance of wx.DC.

GetCaptionStyle() [source]

Returns the current style of the captionbar in a CaptionBarStyle class.

Note

This can be used to change and set back the changes.

IsCollapsed() [source]

Returns wether the status of the bar is expanded or collapsed.

IsVertical() [source]

Returns wether the CaptionBar has a default orientation or not. Default is vertical.

OnChar(event) [source]

Handles the wx.EVT_CHAR event for CaptionBar.

Parameters: event – a wx.KeyEvent event to be processed.

Note

This method currently does nothing.

OnMouseEvent(event) [source]

Handles the wx.EVT_MOUSE_EVENTS event for CaptionBar.

Parameters: event – a wx.MouseEvent event to be processed.

Note

This method catches the mouse click-double click. If clicked on the arrow (single) or double on the caption we change state and an event must be fired to let this panel collapse or expand.

OnPaint(event) [source]

Handles the wx.EVT_PAINT event for CaptionBar.

Parameters: event – a wx.PaintEvent event to be processed.

OnSize(event) [source]

Handles the wx.EVT_SIZE event for CaptionBar.

Parameters: event – a wx.SizeEvent event to be processed.

RedrawIconBitmap() [source]

Redraws the icons (if they exists).

SetBoldFont() [source]

Sets the CaptionBar font weight to bold.

SetCaptionStyle(cbstyle=None, applyDefault=True) [source]

Sets CaptionBar styles with CaptionBarStyle class.

Parameters:
  • cbstyle – an instance of CaptionBarStyle;
  • applyDefault – if True, the colours used in the CaptionBarStyle will be reset to their default values.

Note

All styles that are actually set, are applied. If you set applyDefault to True, all other (not defined) styles will be set to default. If it is False, the styles which are not set in the CaptionBarStyle will be ignored.

SetNormalFont() [source]

Sets the CaptionBar font weight to normal.

SetRightIndent(pixels) [source]

Sets the amount of pixels on the right from which the bitmap is trailing.

Parameters: pixels – the number of pixels on the right from which the bitmap is trailing. If this is 0, it will be drawn all the way to the right, default is equal to FPB_BMP_RIGHTSPACE. Assign this before assigning an image list to prevent a redraw.

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • infobar
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • foldpanelbar »
  • CaptionBar


CaptionBarEvent

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • foldpanelbar »
  • CaptionBarEvent

CaptionBarEvent

This event will be sent when a EVT_CAPTIONBAR is mapped in the parent. It is to notify the parent that the bar is now in collapsed or expanded state. The parent should re-arrange the associated windows accordingly

hierarchy Inheritance Diagram

Inheritance diagram for: CaptionBarEvent

Inheritance diagram of CaptionBarEvent

Methods Summary

__init__ | Default class constructor.
GetBar | Returns the selected CaptionBar.
GetFoldStatus | Returns whether the bar is expanded or collapsed.
GetTag | Returns the tag assigned to the selected CaptionBar.
SetBar | Sets the bar associated with this event.
SetTag | Assigns a tag to the selected CaptionBar.

API Class API

class CaptionBarEvent(wx.PyCommandEvent) [source]

This event will be sent when a EVT_CAPTIONBAR is mapped in the parent. It is to notify the parent that the bar is now in collapsed or expanded state. The parent should re-arrange the associated windows accordingly

__init__(evtType) [source]

Default class constructor.

Parameters: evtType – the event type.

GetBar() [source]

Returns the selected CaptionBar.

GetFoldStatus() [source]

Returns whether the bar is expanded or collapsed. True means expanded.

GetTag() [source]

Returns the tag assigned to the selected CaptionBar.

SetBar(bar) [source]

Sets the bar associated with this event.

Parameters: bar – an instance of CaptionBar.

Note

Should not be used by any other than the originator of the event.

SetTag(tag) [source]

Assigns a tag to the selected CaptionBar.

Parameters: tag – an instance of FoldPanelBar.

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • infobar
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • foldpanelbar »
  • CaptionBarEvent


CaptionBarStyle

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • foldpanelbar »
  • CaptionBarStyle

CaptionBarStyle

This class encapsulates the styles you wish to set for the CaptionBar (this is the part of the FoldPanel where the caption is displayed). It can either be applied at creation time be reapplied when styles need to be changed.

At construction time, all styles are set to their default transparency. This means none of the styles will be applied to the CaptionBar in question, meaning it will be created using the default internals. When setting i.e the colour, font or panel style, these styles become active to be used.

hierarchy Inheritance Diagram

Inheritance diagram for: CaptionBarStyle

Inheritance diagram of CaptionBarStyle

Methods Summary

__init__ | Default constructor for this class.
CaptionColourUsed | Checks if the caption colour of the caption bar is set.
CaptionFontUsed | Checks if the caption bar font is set.
CaptionStyleUsed | Checks if the caption style of the caption bar is set.
FirstColourUsed | Checks if the first colour of the caption bar is set.
GetCaptionColour | Returns the caption colour for the caption bar.
GetCaptionFont | Returns the font for the caption bar.
GetCaptionStyle | Returns the caption style for the caption bar.
GetFirstColour | Returns the first colour for the caption bar.
GetSecondColour | Returns the second colour for the caption bar.
ResetDefaults | Resets default CaptionBarStyle.
SecondColourUsed | Checks if the second colour of the caption bar is set.
SetCaptionColour | Sets caption colour for the caption bar.
SetCaptionFont | Sets font for the caption bar.
SetCaptionStyle | Sets caption style for the caption bar.
SetFirstColour | Sets first colour for the caption bar.
SetSecondColour | Sets second colour for the caption bar.

API Class API

class CaptionBarStyle(object) [source]

This class encapsulates the styles you wish to set for the CaptionBar (this is the part of the FoldPanel where the caption is displayed). It can either be applied at creation time be reapplied when styles need to be changed.

At construction time, all styles are set to their default transparency. This means none of the styles will be applied to the CaptionBar in question, meaning it will be created using the default internals. When setting i.e the colour, font or panel style, these styles become active to be used.

__init__() [source]

Default constructor for this class.

CaptionColourUsed() [source]

Checks if the caption colour of the caption bar is set.

CaptionFontUsed() [source]

Checks if the caption bar font is set.

CaptionStyleUsed() [source]

Checks if the caption style of the caption bar is set.

FirstColourUsed() [source]

Checks if the first colour of the caption bar is set.

GetCaptionColour() [source]

Returns the caption colour for the caption bar.

Note

Please be warned this will result in an assertion failure when this property is not previously set.

See also

SetCaptionColour, CaptionColourUsed

GetCaptionFont() [source]

Returns the font for the caption bar.

Note

Please be warned this will result in an assertion failure when this property is not previously set.

See also

SetCaptionFont, CaptionFontUsed

GetCaptionStyle() [source]

Returns the caption style for the caption bar.

Note

Please be warned this will result in an assertion failure when this property is not previously set.

See also

SetCaptionStyle, CaptionStyleUsed

GetFirstColour() [source]

Returns the first colour for the caption bar.

Note

Please be warned this will result in an assertion failure when this property is not previously set.

See also

SetFirstColour, FirstColourUsed

GetSecondColour() [source]

Returns the second colour for the caption bar.

Note

Please be warned this will result in an assertion failure when this property is not previously set.

See also

SetSecondColour, SecondColourUsed

ResetDefaults() [source]

Resets default CaptionBarStyle.

SecondColourUsed() [source]

Checks if the second colour of the caption bar is set.

SetCaptionColour(colour) [source]

Sets caption colour for the caption bar.

Parameters: colour – a valid wx.Colour object.

Note

If this is not set, the colour property is undefined and will not be used. Use CaptionColourUsed to check if this style is used.

SetCaptionFont(font) [source]

Sets font for the caption bar.

Parameters: font – a valid wx.Font object.

Note

If this is not set, the font property is undefined and will not be used. Use CaptionFontUsed to check if this style is used.

SetCaptionStyle(style) [source]

Sets caption style for the caption bar.

Parameters: style – can be one of the following bits:

Caption Style | Value | Description
CAPTIONBAR_GRADIENT_V | 1 | Draws a vertical gradient from top to bottom
CAPTIONBAR_GRADIENT_H | 2 | Draws a horizontal gradient from left to right
CAPTIONBAR_SINGLE | 3 | Draws a single filled rectangle to draw the caption
CAPTIONBAR_RECTANGLE | 4 | Draws a single colour with a rectangle around the caption
CAPTIONBAR_FILLED_RECTANGLE | 5 | Draws a filled rectangle and a border around it

Note

If this is not set, the property is undefined and will not be used. Use CaptionStyleUsed to check if this style is used.

SetFirstColour(colour) [source]

Sets first colour for the caption bar.

Parameters: colour – a valid wx.Colour object.

Note

If this is not set, the colour property is undefined and will not be used. Use FirstColourUsed to check if this style is used.

SetSecondColour(colour) [source]

Sets second colour for the caption bar.

Parameters: colour – a valid wx.Colour object.

Note

If this is not set, the colour property is undefined and will not be used. Use SecondColourUsed to check if this style is used.

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • infobar
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • foldpanelbar »
  • CaptionBarStyle


FoldPanelBar

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • foldpanelbar »
  • FoldPanelBar

FoldPanelBar

The FoldPanelBar is a class which can maintain a list of collapsible panels. Once a panel is collapsed, only it’s caption bar is visible to the user. This will provide more space for the other panels, or allow the user to close panels which are not used often to get the most out of the work area.

This control is easy to use. Simply create it as a child for a panel or sash window, and populate panels with AddFoldPanel. Then use the AddFoldPanelWindow to add wx.Window derived controls to the current fold panel. Use AddFoldPanelSeparator to put separators between the groups of controls that need a visual separator to group them together. After all is constructed, the user can fold the panels by double clicking on the bar or single click on the arrow, which will indicate the collapsed or expanded state.

hierarchy Inheritance Diagram

Inheritance diagram for: FoldPanelBar

Inheritance diagram of FoldPanelBar

appearance Control Appearance

FoldPanelBar

Methods Summary

__init__ | Default class constructor.
AddFoldPanel | Adds a fold panel to the list of panels.
AddFoldPanelSeparator | Adds a separator line to the current fold panel.
AddFoldPanelWindow | Adds a wx.Window derived instance to the referenced fold panel.
ApplyCaptionStyle | Sets the style of the caption bar (CaptionBar) of the fold panel.
ApplyCaptionStyleAll | Sets the style of all the caption bars of the fold panel.
Collapse | Collapses the given fold panel reference, and updates the foldpanel bar.
Expand | Expands the given fold panel reference, and updates the foldpanel bar.
GetCaptionStyle | Returns the currently used caption style for the fold panel.
GetCount | Returns the number of panels in the FoldPanelBar.
GetFoldPanel | Returns the panel associated with the index item.
GetPanelsLength | Returns the length of the panels that are expanded and collapsed.
IsVertical | Returns whether the CaptionBar has default orientation or not.
OnPressCaption | Handles the wx.EVT_CAPTIONBAR event for CaptionBar.
OnSizePanel | Handles the wx.EVT_SIZE event for FoldPanelBar.
RedisplayFoldPanelItems | Resizes the fold panels so they match the width.
RefreshPanelsFrom | Refreshes all the panels from given one down to last one.
RepositionCollapsedToBottom | Repositions all the collapsed panels to the bottom.

API Class API

class FoldPanelBar(wx.Panel) [source]

The FoldPanelBar is a class which can maintain a list of collapsible panels. Once a panel is collapsed, only it’s caption bar is visible to the user. This will provide more space for the other panels, or allow the user to close panels which are not used often to get the most out of the work area.

This control is easy to use. Simply create it as a child for a panel or sash window, and populate panels with FoldPanelBar.AddFoldPanel(). Then use the FoldPanelBar.AddFoldPanelWindow() to add wx.Window derived controls to the current fold panel. Use FoldPanelBar.AddFoldPanelSeparator() to put separators between the groups of controls that need a visual separator to group them together. After all is constructed, the user can fold the panels by double clicking on the bar or single click on the arrow, which will indicate the collapsed or expanded state.

__init__(parent, id=-1, pos=wx.DefaultPosition, size=wx.DefaultSize, style=wx.TAB_TRAVERSAL|wx.NO_BORDER, agwStyle=0) [source]

Default class constructor.

Parameters:
  • parent – the FoldPanelBar parent window;
  • id – an identifier for the control: a value of -1 is taken to mean a default;
  • pos – the control position. A value of (-1, -1) indicates a default position, chosen by either the windowing system or wxPython, depending on platform;
  • size – the control size. A value of (-1, -1) indicates a default size, chosen by either the windowing system or wxPython, depending on platform;
  • style – the underlying wx.Panel window style;
  • agwStyle – the AGW-specific FoldPanelBar window style. It can be one of the following bits:

    Window Styles | Hex Value | Description
    FPB_SINGLE_FOLD | 0x1 | Single fold forces other panels to close when they are open, and only opens the current panel. This will allow the open panel to gain the full size left in the client area.
    FPB_COLLAPSE_TO_BOTTOM | 0x2 | All panels are stacked to the bottom. When they are expanded again they show up at the top.
    FPB_EXCLUSIVE_FOLD | 0x4 | FPB_SINGLE_FOLD style plus the panels will be stacked at the bottom.
    FPB_HORIZONTAL | 0x4 | FoldPanelBar will be horizontal.
    FPB_VERTICAL | 0x8 | FoldPanelBar will be vertical.

AddFoldPanel(caption='', collapsed=False, foldIcons=None, cbstyle=None) [source]

Adds a fold panel to the list of panels.

Parameters:
  • caption – the caption to be displayed in the associated CaptionBar;
  • collapsed – if set to True, the panel is collapsed initially;
  • foldIcons – an instance of wx.ImageList containing the icons to display next to the caption text;
  • cbstyle – an instance of CaptionBarStyle.

Note

The FoldPanel item which is returned, can be used as a reference to perform actions upon the fold panel like collapsing it, expanding it, or deleting it from the list. Use this foldpanel to add windows to it.

See also

AddFoldPanelWindow and AddFoldPanelSeparator to see how to add items derived from wx.Window to the panels.

AddFoldPanelSeparator(panel, colour=wx.BLACK, spacing=FPB_DEFAULT_SPACING, leftSpacing=FPB_DEFAULT_LEFTLINESPACING, rightSpacing=FPB_DEFAULT_RIGHTLINESPACING) [source]

Adds a separator line to the current fold panel.

The separator is a simple line which is drawn and is no real component. It can be used to separate groups of controls which belong to each other.

Parameters:
  • colour – the separator colour, an instance of wx.Colour;
  • spacing – the separator to be added can be slightly indented from left and right so it is more visibly placed in the fold panel. Use spacing > 0 to give the control an y offset from the previous wx.Window added;

  • leftSpacing – give the added separator a slight indent from the left;
  • rightSpacing – give the added separator a slight indent from the right.

AddFoldPanelWindow(panel, window, flags=FPB_ALIGN_WIDTH, spacing=FPB_DEFAULT_SPACING, leftSpacing=FPB_DEFAULT_LEFTLINESPACING, rightSpacing=FPB_DEFAULT_RIGHTLINESPACING) [source]

Adds a wx.Window derived instance to the referenced fold panel.

Parameters:
  • panel – an instance of FoldPanelItem;
  • window – the window we wish to add to the fold panel, an instance of wx.Window;

  • flags – can be one of the following bits:

    Align Flag | Value | Description
    FPB_ALIGN_WIDTH | 1 | The wx.Window to be added will be aligned to fit the width of the FoldPanel when it is resized. Very handy for sizer items, buttons and text boxes.
    FPB_ALIGN_LEFT | 0 | Aligns left instead of fitting the width of the child window to be added. Use either this one or FPB_ALIGN_WIDTH.
  • spacing – the wx.Window to be added can be slightly indented from left and right so it is more visibly placed in the fold panel. Use spacing > 0 to give the control an y offset from the previous wx.Window added;

  • leftSpacing – give the wx.Window added a slight indent from the left;

  • rightSpacing – give the wx.Window added a slight indent from the right;

Note

Make the window be a child of the fold panel!

The following example adds a FoldPanel to the FoldPanelBar and adds two wx.Window derived controls to the FoldPanel:

# Create the FoldPanelBar
m_pnl = FoldPanelBar(self, wx.ID_ANY, wx.DefaultPosition, wx.DefaultSize, agwStyle=0x2)

# Add a foldpanel to the control. "Test me" is the caption and it is
# initially not collapsed.
item = m_pnl.AddFoldPanel("Test me", False)

# Now add a button to the fold panel. Mind that the button should be
# made child of the FoldPanel and not of the main form.
m_pnl.AddFoldPanelWindow(item, wx.Button(item, ID_COLLAPSEME, "Collapse Me"))

# Add a separator between the two controls. This is purely a visual
# line that can have a certain colour and also the indents and width
# aligning like a control.
m_pnl.AddFoldPanelSeparator(item)

# Now add a text ctrl. Also very easy. Align this on width so that
# when the control gets wider the text control also sizes along.
m_pnl.AddFoldPanelWindow(item, wx.TextCtrl(item, wx.ID_ANY, "Comment"), FPB_ALIGN_WIDTH, FPB_DEFAULT_SPACING, 20)

ApplyCaptionStyle(foldpanel, cbstyle) [source]

Sets the style of the caption bar (CaptionBar) of the fold panel.

Parameters:
  • foldpanel – an instance of FoldPanelItem;
  • cbstyle – an instance of CaptionBarStyle.

Note

The changes are applied immediately. All styles not set in the CaptionBarStyle class are not applied. Use the CaptionBar reference to indicate what captionbar you want to apply the style to. To apply one style to all CaptionBar items, use ApplyCaptionStyleAll.

ApplyCaptionStyleAll(cbstyle) [source]

Sets the style of all the caption bars of the fold panel. The changes are applied immediately.

Parameters: cbstyle – an instance of CaptionBarStyle.

Collapse(foldpanel) [source]

Collapses the given fold panel reference, and updates the foldpanel bar.

Parameters: foldpanel – an instance of FoldPanelItem.

Note

With the FPB_COLLAPSE_TO_BOTTOM style set, all collapsed captions are put at the bottom of the control. In the normal mode, they stay where they are.

Expand(foldpanel) [source]

Expands the given fold panel reference, and updates the foldpanel bar.

Parameters: foldpanel – an instance of FoldPanelItem.

Note

With the FPB_COLLAPSE_TO_BOTTOM style set, they will be removed from the bottom and the order where the panel originally was placed is restored.

GetCaptionStyle(foldpanel) [source]

Returns the currently used caption style for the fold panel.

It is returned as a CaptionBarStyle class. After modifying it, it can be set again.

Parameters: foldpanel – an instance of FoldPanelItem.

GetCount() [source]

Returns the number of panels in the FoldPanelBar.

GetFoldPanel(item) [source]

Returns the panel associated with the index item.

Parameters: item – an integer representing the FoldPanelItem in the list of panels in this FoldPanelBar.

GetPanelsLength(collapsed, expanded) [source]

Returns the length of the panels that are expanded and collapsed.

Parameters:
  • collapsed – the current value of the collapsed panels;
  • expanded – the current value of the expanded panels.

Note

This is useful to determine quickly what size is used to display, and what is left at the bottom (right) to align the collapsed panels.

IsVertical() [source]

Returns whether the CaptionBar has default orientation or not. Default is vertical.

OnPressCaption(event) [source]

Handles the wx.EVT_CAPTIONBAR event for CaptionBar.

Parameters: event – a CaptionBarEvent event to be processed.

OnSizePanel(event) [source]

Handles the wx.EVT_SIZE event for FoldPanelBar.

Parameters: event – a wx.SizeEvent event to be processed.

RedisplayFoldPanelItems() [source]

Resizes the fold panels so they match the width.

RefreshPanelsFrom(item) [source]

Refreshes all the panels from given one down to last one.

Parameters: item – the first FoldPanelItem to be refreshed.

RepositionCollapsedToBottom() [source]

Repositions all the collapsed panels to the bottom.

When it is not possible to align them to the bottom, stick them behind the visible panels.

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • infobar
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • foldpanelbar »
  • FoldPanelBar


FoldPanelItem

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • foldpanelbar »
  • FoldPanelItem

FoldPanelItem

This class is a child sibling of the FoldPanelBar class. It will contain a CaptionBar class for receiving of events, and a the rest of the area can be populated by a wx.Panel derived class.

hierarchy Inheritance Diagram

Inheritance diagram for: FoldPanelItem

Inheritance diagram of FoldPanelItem

Methods Summary

__init__ | Default class constructor.
AddSeparator | Adds a separator item to the list of items on this panel.
AddWindow | Adds a window item to the list of items on this panel.
ApplyCaptionStyle | Applies the style defined in cbstyle to the CaptionBar.
Collapse | Internal method.
Expand | Internal method.
GetCaptionLength | Returns height of caption only.
GetCaptionStyle | Returns the current style of the captionbar in a CaptionBarStyle class.
GetItemPos | Returns item’s position.
GetPanelLength | Returns size of panel.
IsExpanded | Returns expanded or collapsed status.
IsVertical | Returns whether the CaptionBar has default orientation or not.
OnPaint | Handles the wx.EVT_PAINT event for FoldPanelItem.
OnPressCaption | Handles the wx.EVT_CAPTIONBAR event for FoldPanelItem.
Reposition | Repositions this FoldPanelItem and reports the length occupied
ResizePanel | Resizes the panel.

API Class API

class FoldPanelItem(wx.Panel) [source]

This class is a child sibling of the FoldPanelBar class. It will contain a CaptionBar class for receiving of events, and a the rest of the area can be populated by a wx.Panel derived class.

__init__(parent, id=wx.ID_ANY, caption="", foldIcons=None, collapsed=False, cbstyle=None) [source]

Default class constructor.

Parameters:
  • parent – the FoldPanelItem parent window;
  • id – an identifier for the control: a value of -1 is taken to mean a default;
  • caption – the string to be displayed in CaptionBar;
  • foldIcons – an instance of wx.ImageList containing the icons to display next to the caption text;
  • collapsed – True if the CaptionBar should start in the collapsed state, False otherwise;
  • cbstyle – the CaptionBar window style. Must be an instance of CaptionBarStyle.

AddSeparator(colour=wx.BLACK, spacing=FPB_DEFAULT_SPACING, leftSpacing=FPB_DEFAULT_LEFTSPACING, rightSpacing=FPB_DEFAULT_RIGHTSPACING) [source]

Adds a separator item to the list of items on this panel.

Parameters:
  • colour – the separator colour, an instance of wx.Colour;
  • spacing – the separator to be added can be slightly indented from left and right so it is more visibly placed in the fold panel. Use spacing > 0 to give the control an y offset from the previous wx.Window added;
  • leftSpacing – give the added separator a slight indent from the left;
  • rightSpacing – give the added separator a slight indent from the right.

AddWindow(window, flags=FPB_ALIGN_WIDTH, spacing=FPB_DEFAULT_SPACING, leftSpacing=FPB_DEFAULT_LEFTLINESPACING, rightSpacing=FPB_DEFAULT_RIGHTLINESPACING) [source]

Adds a window item to the list of items on this panel.

Parameters:
  • window – an instance of wx.Window;

  • flags – can be one of the following bits:

    Align Flag | Value | Description
    FPB_ALIGN_WIDTH | 1 | The wx.Window to be added will be aligned to fit the width of the FoldPanel when it is resized. Very handy for sizer items, buttons and text boxes.
    FPB_ALIGN_LEFT | 0 | Aligns left instead of fitting the width of the child window to be added. Use either this one or FPB_ALIGN_WIDTH.
  • spacing – reserves a number of pixels before the window element;
  • leftSpacing – an indent, in pixels;
  • rightSpacing – a right spacing, only relevant when the style FPB_ALIGN_WIDTH is chosen.

ApplyCaptionStyle(cbstyle) [source]

Applies the style defined in cbstyle to the CaptionBar.

Collapse() [source]

Internal method.

This should not be called by the user, because it doesn’t trigger the parent to tell it that we are collapsed or expanded, it only changes visual state.

Expand() [source]

Internal method.

This should not be called by the user, because it doesn’t trigger the parent to tell it that we are collapsed or expanded, it only changes visual state.

GetCaptionLength() [source]

Returns height of caption only. This is for folding calculation purposes.

GetCaptionStyle() [source]

Returns the current style of the captionbar in a CaptionBarStyle class.

This can be used to change and set back the changes.

GetItemPos() [source]

Returns item’s position.

GetPanelLength() [source]

Returns size of panel.

IsExpanded() [source]

Returns expanded or collapsed status. If the panel is expanded, True is returned.

IsVertical() [source]

Returns whether the CaptionBar has default orientation or not. Default is vertical.

OnPaint(event) [source]

Handles the wx.EVT_PAINT event for FoldPanelItem.

Parameters: event – a wx.PaintEvent event to be processed.

OnPressCaption(event) [source]

Handles the wx.EVT_CAPTIONBAR event for FoldPanelItem.

Parameters: event – a CaptionBarEvent event to be processed.

Reposition(pos) [source]

Repositions this FoldPanelItem and reports the length occupied for the next FoldPanelItem in the list.

Parameters: pos – the new item position.

ResizePanel() [source]

Resizes the panel.

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • infobar
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • foldpanelbar »
  • FoldPanelItem


FoldWindowItem

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • foldpanelbar »
  • FoldWindowItem

FoldWindowItem

This class is a child sibling of the FoldPanelItem class. It will contain wx.Window that can be either a separator (a coloured line simulated by a wx.Window) or a wxPython controls (such as a wx.Button, a wx.ListCtrl etc...).

hierarchy Inheritance Diagram

Inheritance diagram for: FoldWindowItem

Inheritance diagram of FoldWindowItem

Methods Summary

__init__ | Default class constructor
GetLeftSpacing | Returns the left indent of FoldWindowItem.
GetLineColour | Returns the separator line colour.
GetLineLength | Returns the separator line length.
GetLineY | Returns the y position of the separator.
GetRightSpacing | Returns the right indent of FoldWindowItem.
GetSpacing | Returns the spacing of FoldWindowItem.
GetType | Returns the FoldWindowItem type.
GetWindowLength | Returns space needed by the window if type is FoldWindowItem
ResizeItem | Resizes the element, whatever it is.

API Class API

class FoldWindowItem(object) [source]

This class is a child sibling of the FoldPanelItem class. It will contain wx.Window that can be either a separator (a coloured line simulated by a wx.Window) or a wxPython controls (such as a wx.Button, a wx.ListCtrl etc...).

__init__(parent, window=None) [source]

Default class constructor

Parameters:
  • parent – the FoldWindowItem parent;
  • window – the window contained in this item.
  • Type – can be “WINDOW” or “SEPARATOR”;
  • lineColour – the separator colour (meaningful for separators only);
  • y – the separator y position (meaningful for separators only);
  • flags – the alignment flags;
  • spacing – reserves a number of pixels before the window/separator element;
  • leftSpacing – an indent, in pixels;
  • rightSpacing – a right spacing, only relevant when the style FPB_ALIGN_WIDTH is chosen.

See also

FoldPanelBar.AddFoldPanelWindow() for a list of valid alignment flags.

GetLeftSpacing() [source]

Returns the left indent of FoldWindowItem.

GetLineColour() [source]

Returns the separator line colour.

GetLineLength() [source]

Returns the separator line length.

GetLineY() [source]

Returns the y position of the separator.

GetRightSpacing() [source]

Returns the right indent of FoldWindowItem.

GetSpacing() [source]

Returns the spacing of FoldWindowItem.

GetType() [source]

Returns the FoldWindowItem type.

GetWindowLength(vertical=True) [source]

Returns space needed by the window if type is FoldWindowItem “WINDOW” and returns the total size plus the extra spacing.

Parameters: vertical – True if the parent FoldPanelBar is in vertical mode.

ResizeItem(size, vertical=True) [source]

Resizes the element, whatever it is.

A separator or line will be always aligned by width or height depending on orientation of the whole panel.

Parameters:
  • size – the maximum size available for the FoldWindowItem;
  • vertical – True if the parent FoldPanelBar is in vertical mode.

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • infobar
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • foldpanelbar »
  • FoldWindowItem


SVN Revision 68362 For foldpanelbar

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • foldpanelbar »
  • SVN Revision 68362 For foldpanelbar

svn SVN Revision 68362 For foldpanelbar

This file contains the SVN revision history for foldpanelbar, at revision 68362.

Available information include commit date, the name of the committer, the file size, the SVN log messages and a diff from the previous version (if available).

File Information

  • Commit Date: 12-May-2009 14:58:36 UTC
  • Committer: AG
  • File Size: 76046 byte(s)

Log Messages

The following log message was entered by the committer:

  • All of AGW: change my work e-mail from KPO to Maersk Oil (silly commit)

Diff To Previous Version (65377)

Version SVN diff:

--- wxPython/3rdParty/AGW/agw/foldpanelbar.py       2010/08/21 20:27:02     65377
+++ wxPython/3rdParty/AGW/agw/foldpanelbar.py       2011/07/24 21:36:47     68362
@@ -49,7 +49,7 @@
# Write To Me At:
#
# andrea.gavana@gmail.com
-# gavana@kpo.kz
+# andrea.gavana@maerskoil.com
#
# Or, Obviously, To The wxPython Mailing List!!!
#

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • foldpanelbar »
  • SVN Revision 68362 For foldpanelbar


SVN Revision 68881 For foldpanelbar

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • foldpanelbar »
  • SVN Revision 68881 For foldpanelbar

svn SVN Revision 68881 For foldpanelbar

This file contains the SVN revision history for foldpanelbar, at revision 68881.

Available information include commit date, the name of the committer, the file size, the SVN log messages and a diff from the previous version (if available).

File Information

  • Commit Date: 28-Apr-2009 03:17:40 UTC
  • Committer: AG
  • File Size: 77017 byte(s)

Log Messages

The following log message was entered by the committer:

  • AGW: General overhaul of the documentation, much improved. All the widgets have their own sample usage in the docs as well;

  • FlatNotebook: Added the FNB_NAV_BUTTONS_WHEN_NEEDED style, which hides the navigation left/right arrows if all tabs fit;

  • RibbonBar: - Added the EVT_RIBBONBAR_TAB_LEFT_DCLICK event, which generates a special event

    when a ribbon bar tab is double-clicked;

    • Added support for toggle buttons;
    • Improved support for ribbon panel sizers: panels with sizers should now automatically minimise at small sizes, and behave properly when popping up from a minimised state;
    • Added tooltips via SetToolTip for those buttons which have the help_string attribute set.

  • XLSGrid: a new widget was added to AGW, termed XLSGrid. It’s based on wx.grid.Grid and can be used to faithfully reproduce the appearance of a Microsoft Excel spreadsheets.

Diff To Previous Version (68362)

Version SVN diff:

--- wxPython/3rdParty/AGW/agw/foldpanelbar.py       2011/07/24 21:36:47     68362
+++ wxPython/3rdParty/AGW/agw/foldpanelbar.py       2011/08/25 16:40:17     68881
@@ -3,7 +3,7 @@
# Ported From Jorgen Bodde & Julian Smart (Extended Demo) C++ Code By:
#
# Andrea Gavana, @ 23 Mar 2005
-# Latest Revision: 14 Nov 2010, 12.00 GMT
+# Latest Revision: 17 Aug 2011, 15.00 GMT
#
#
# TODO List
@@ -59,18 +59,18 @@

"""
-FoldPanelBar is a control that contains multiple panels, which can be expanded
+L{FoldPanelBar} is a control that contains multiple panels, which can be expanded
or collapsed.

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

-The FoldPanelBar is a control that contains multiple panels (of type
+The L{FoldPanelBar} is a control that contains multiple panels (of type
L{FoldPanelItem}) that can be expanded or collapsed. The captionbar of
-the FoldPanelBar can be customized by setting it to a horizontal gradient
+the L{FoldPanelBar} can be customized by setting it to a horizontal gradient
style, vertical gradient style, a single colour, a rectangle or filled
-rectangle. The FoldPanel items can be collapsed in place or to the
+rectangle. The `FoldPanel` items can be collapsed in place or to the
bottom of the control. `wx.Window` derived controls can be added
dynamically, and separated by separator lines.

@@ -78,15 +78,15 @@
How does it work
----------------

-The internals of the FoldPanelBar is a list of L{FoldPanelItem} objects. Through
+The internals of the L{FoldPanelBar} is a list of L{FoldPanelItem} objects. Through
the reference of `FoldPanel` these panels can be controlled by adding new controls
-to a FoldPanel or adding new FoldPanels to the FoldPanelBar.
+to a FoldPanel or adding new FoldPanels to the L{FoldPanelBar}.

The L{CaptionBar} fires events to the parent (container of all panel items) when a
sub-panel needs resizing (either folding or expanding). The fold or expand process
is simply a resize of the panel so it looks like all controls on it are gone. All
controls are still child of the `FoldPanel` they are located on. If they don't
-handle the event (and they won't) then the owner of the FoldPanelBar gets the
+handle the event (and they won't) then the owner of the L{FoldPanelBar} gets the
events.

This is what you need to handle the controls. There isn't much to it just
@@ -111,14 +111,55 @@
* Dragging and dropping the panels;
* Re-ordering the panels (not yet).

+
+Usage
+=====
+
+Usage example::
+
+    import wx
+    import wx.lib.agw.foldpanelbar as fpb
+
+    class MyFrame(wx.Frame):
+
+        def __init__(self, parent):
+
+            wx.Frame.__init__(self, parent, -1, "FoldPanelBar Demo")
+
+            text_ctrl = wx.TextCtrl(self, -1, size=(400, 100), style=wx.TE_MULTILINE)
+
+            panel_bar = fpb.FoldPanelBar(self, -1, agwStyle=fpb.FPB_HORIZONTAL|fpb.FPB_DEFAULT_STYLE)
+
+            fold_panel = panel_bar.AddFoldPanel("Thing")
+            thing = wx.TextCtrl(fold_panel, -1, size=(400, -1), style=wx.TE_MULTILINE)
+
+            panel_bar.AddFoldPanelWindow(fold_panel, thing)
+
+            main_sizer = wx.BoxSizer(wx.HORIZONTAL)
+            main_sizer.Add(text_ctrl, 1, wx.EXPAND)
+            main_sizer.Add(panel_bar, 0, wx.EXPAND)
+            self.SetSizer(main_sizer)
+
+
+    # our normal wxApp-derived class, as usual
+
+    app = wx.PySimpleApp()
+
+    frame = MyFrame(None)
+    app.SetTopWindow(frame)
+    frame.Show()
+
+    app.MainLoop()
+
+

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

-FoldPanelBar is supported on the following platforms:
+L{FoldPanelBar} is supported on the following platforms:
* Windows (Verified on Windows XP, 2000)
* Linux/Unix (GTK2) (Thanks to Toni Brkic and Robin Dunn)
-  * Mac OSX (Thanks to Robin Dunn for the CaptionBar size patch)
+  * Mac OSX (Thanks to Robin Dunn for the L{CaptionBar} size patch)

Window Styles
@@ -129,11 +170,11 @@
========================== =========== ==================================================
Window Styles              Hex Value   Description
========================== =========== ==================================================
-``FPB_SINGLE_FOLD``                0x1 Single fold forces other panels to close when they are open, and only opens the current panel. This will allow the open panel to gain the full size left in the client area. This is an extra style.
-``FPB_COLLAPSE_TO_BOTTOM``         0x2 All panels are stacked to the bottom. When they are expanded again they show up at the top. This is an extra style.
-``FPB_EXCLUSIVE_FOLD``             0x4 ``FPB_SINGLE_FOLD`` style plus the panels will be stacked at the bottom.  This is an extra style.
-``FPB_HORIZONTAL``                 0x8 `FoldPanelBar` will be horizontal.
-``FPB_VERTICAL``                  0x10 `FoldPanelBar` will be vertical.
+``FPB_SINGLE_FOLD``                0x1 Single fold forces other panels to close when they are open, and only opens the current panel. This will allow the open panel to gain the full size left in the client area.
+``FPB_COLLAPSE_TO_BOTTOM``         0x2 All panels are stacked to the bottom. When they are expanded again they show up at the top.
+``FPB_EXCLUSIVE_FOLD``             0x4 ``FPB_SINGLE_FOLD`` style plus the panels will be stacked at the bottom.
+``FPB_HORIZONTAL``                 0x8 L{FoldPanelBar} will be horizontal.
+``FPB_VERTICAL``                  0x10 L{FoldPanelBar} will be vertical.
========================== =========== ==================================================

@@ -145,16 +186,16 @@
================== ==================================================
Event Name         Description
================== ==================================================
-``EVT_CAPTIONBAR`` The user has pressed the caption bar: `FoldPanelBar` will either expand or collapse the underlying panel.
+``EVT_CAPTIONBAR`` The user has pressed the caption bar: L{FoldPanelBar} will either expand or collapse the underlying panel.
================== ==================================================

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

-FoldPanelBar is distributed under the wxPython license.
+L{FoldPanelBar} is distributed under the wxPython license.

-Latest Revision: Andrea Gavana @ 27 Nov 2009, 15.00 GMT
+Latest Revision: Andrea Gavana @ 17 Aug 2011, 15.00 GMT

Version 0.5

@@ -209,25 +250,24 @@
FPB_SINGLE_FOLD = 0x0001
""" Single fold forces other panels to close when they are open, and only opens""" \
""" the current panel. This will allow the open panel to gain the full size left""" \
-""" in the client area. This is an extra style. """
+""" in the client area."""

# All panels are stacked to the bottom. When they are expanded again they
# show up at the top
FPB_COLLAPSE_TO_BOTTOM = 0x0002
""" All panels are stacked to the bottom. When they are expanded again they show""" \
-""" up at the top. This is an extra style. """
+""" up at the top. """

# Now supported! Single fold plus panels
# will be stacked at the bottom
FPB_EXCLUSIVE_FOLD = 0x0004
-""" ``FPB_SINGLE_FOLD`` style plus the panels will be stacked at the bottom. """ \
-""" This is an extra style. """
+""" ``FPB_SINGLE_FOLD`` style plus the panels will be stacked at the bottom. """

# Orientation Flag
FPB_HORIZONTAL = 0x0008
-""" `FoldPanelBar` will be horizontal. """
+""" L{FoldPanelBar} will be horizontal. """
FPB_VERTICAL = 0x0010
-""" `FoldPanelBar` will be vertical. """
+""" L{FoldPanelBar} will be vertical. """

# FoldPanelItem default settings
FPB_ALIGN_LEFT = 0
@@ -465,7 +505,7 @@
#-----------------------------------#
wxEVT_CAPTIONBAR = wx.NewEventType()
EVT_CAPTIONBAR = wx.PyEventBinder(wxEVT_CAPTIONBAR, 0)
-""" The user has pressed the caption bar: `FoldPanelBar` will either expand or""" \
+""" The user has pressed the caption bar: L{FoldPanelBar} will either expand or""" \
""" collapse the underlying panel. """

# Define Empty CaptionBar Style
@@ -544,7 +584,7 @@
This class is a graphical caption component that consists of a
caption and a clickable arrow.

-    The CaptionBar fires an event ``EVT_CAPTIONBAR`` which is a
+    The L{CaptionBar} fires an event ``EVT_CAPTIONBAR`` which is a
L{CaptionBarEvent}. This event can be caught and the parent window
can act upon the collapsed or expanded state of the bar (which is
actually just the icon which changed). The parent panel can
@@ -916,6 +956,8 @@
"""
Returns the best size for this panel, based upon the font
assigned to this window, and the caption string.
+
+        :note: Overridden from `wx.Window`.
"""

if self.IsVertical():
@@ -1130,7 +1172,7 @@

class FoldPanelBar(wx.Panel):
"""
-    The FoldPanelBar is a class which can maintain a list of
+    The L{FoldPanelBar} is a class which can maintain a list of
collapsible panels. Once a panel is collapsed, only it's caption
bar is visible to the user. This will provide more space for the
other panels, or allow the user to close panels which are not used
@@ -1277,7 +1319,7 @@

:note: Make the window be a child of the fold panel!

-         The following example adds a FoldPanel to the FoldPanelBar and
+         The following example adds a FoldPanel to the L{FoldPanelBar} and
adds two `wx.Window` derived controls to the FoldPanel::

# Create the FoldPanelBar

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • foldpanelbar »
  • SVN Revision 68881 For foldpanelbar


SVN Revision 69134 For foldpanelbar

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • foldpanelbar »
  • SVN Revision 69134 For foldpanelbar

svn SVN Revision 69134 For foldpanelbar

This file contains the SVN revision history for foldpanelbar, at revision 69134.

Available information include commit date, the name of the committer, the file size, the SVN log messages and a diff from the previous version (if available).

File Information

  • Commit Date: 17-Oct-2008 20:51:43 UTC
  • Committer: AG
  • File Size: 77015 byte(s)

Log Messages

The following log message was entered by the committer:

  • AquaButton: applied patch from Werner with the option of selecting the disabled colour;
  • FoldPanelBar: Fixed ticket #13485.

Diff To Previous Version (68881)

Version SVN diff:

--- wxPython/3rdParty/AGW/agw/foldpanelbar.py       2011/08/25 16:40:17     68881
+++ wxPython/3rdParty/AGW/agw/foldpanelbar.py       2011/09/17 22:02:20     69134
@@ -3,7 +3,7 @@
# Ported From Jorgen Bodde & Julian Smart (Extended Demo) C++ Code By:
#
# Andrea Gavana, @ 23 Mar 2005
-# Latest Revision: 17 Aug 2011, 15.00 GMT
+# Latest Revision: 17 Sep 2011, 23.00 GMT
#
#
# TODO List
@@ -195,7 +195,7 @@

L{FoldPanelBar} is distributed under the wxPython license.

-Latest Revision: Andrea Gavana @ 17 Aug 2011, 15.00 GMT
+Latest Revision: Andrea Gavana @ 17 Sep 2011, 23.00 GMT

Version 0.5

@@ -1218,10 +1218,10 @@
self._controlCreated = False

# make sure there is any orientation
-        if agwStyle & FPB_HORIZONTAL != FPB_HORIZONTAL:
+        if not agwStyle & (FPB_HORIZONTAL | FPB_VERTICAL):
agwStyle = agwStyle | FPB_VERTICAL

-        if agwStyle & FPB_HORIZONTAL == 4:
+        if agwStyle & FPB_HORIZONTAL:
self._isVertical = False
else:
self._isVertical = True

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • foldpanelbar »
  • SVN Revision 69134 For foldpanelbar


SVN Revision 69627 For foldpanelbar

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • foldpanelbar »
  • SVN Revision 69627 For foldpanelbar

svn SVN Revision 69627 For foldpanelbar

This file contains the SVN revision history for foldpanelbar, at revision 69627.

Available information include commit date, the name of the committer, the file size, the SVN log messages and a diff from the previous version (if available).

File Information

  • Commit Date: 17-Oct-2008 19:15:31 UTC
  • Committer: AG
  • File Size: 77025 byte(s)

Log Messages

The following log message was entered by the committer:

  • AuiManager: fix the assertion error in the demo;
  • Others: minor fixes to the docstrings.

Diff To Previous Version (69134)

Version SVN diff:

--- wxPython/3rdParty/AGW/agw/foldpanelbar.py       2011/09/17 22:02:20     69134
+++ wxPython/3rdParty/AGW/agw/foldpanelbar.py       2011/11/01 19:42:21     69627
@@ -1625,7 +1625,9 @@
:param `foldpanel`: an instance of L{FoldPanelItem};
:param `cbstyle`: an instance of L{CaptionBarStyle}.

-        :note: The changes are applied immediately. All styles not set in the
+        :note:
+
+         The changes are applied immediately. All styles not set in the
L{CaptionBarStyle} class are not applied. Use the L{CaptionBar} reference
to indicate what captionbar you want to apply the style to. To apply one
style to all L{CaptionBar} items, use L{ApplyCaptionStyleAll}.

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • foldpanelbar »
  • SVN Revision 69627 For foldpanelbar


FourWaySplitter

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • fourwaysplitter »
  • FourWaySplitter

FourWaySplitter

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

Note

These things are not yet supported:

  • Minimum pane size (minimum of what? Width? Height?);
  • Using negative sash positions to indicate a position offset from the end;
  • User controlled unsplitting with double clicks on the sash (but supported via the SetExpanded method);
  • Sash gravity.

hierarchy Inheritance Diagram

Inheritance diagram for: FourWaySplitter

Inheritance diagram of FourWaySplitter

appearance Control Appearance

FourWaySplitter

Methods Summary

__init__ | Default class constructor.
AdjustLayout | Adjust layout of FourWaySplitter. Mainly used to recalculate the
AppendWindow | Add a new window to the splitter at the right side or bottom of the window stack.
DetachWindow | Removes the window from the stack of windows managed by the splitter.
DoGetBestSize | Gets the size which best suits the window: for a control, it would be the
DoSendChangingEvent | Sends a EVT_SPLITTER_SASH_POS_CHANGING event.
DrawSplitter | Actually draws the sashes.
DrawTrackSplitter | Draws a fake sash in case we don’t have wx.SP_LIVE_UPDATE style.
ExchangeWindows | Trade the positions in the splitter of the two windows.
GetAGWWindowStyleFlag | Returns the FourWaySplitter window style.
GetBottomLeft | Returns the bottom left window (window index: 2).
GetBottomRight | Returns the bottom right window (window index: 3).
GetMode | Determines the split mode for FourWaySplitter.
GetTopLeft | Returns the top left window (window index: 0).
GetTopRight | Returns the top right window (window index: 1).
GetWindow | Returns the window at the index idx.
InsertWindow | Insert a new window into the splitter at the position given in idx.
MoveSplit | Moves the split accordingly to user action.
OnEnterWindow | Handles the wx.EVT_ENTER_WINDOW event for FourWaySplitter.
OnLeaveWindow | Handles the wx.EVT_LEAVE_WINDOW event for FourWaySplitter.
OnLeftDown | Handles the wx.EVT_LEFT_DOWN event for FourWaySplitter.
OnLeftUp | Handles the wx.EVT_LEFT_UP event for FourWaySplitter.
OnMotion | Handles the wx.EVT_MOTION event for FourWaySplitter.
OnPaint | Handles the wx.EVT_PAINT event for FourWaySplitter.
OnSize | Handles the wx.EVT_SIZE event for FourWaySplitter.
ReplaceWindow | Replaces oldWindow (which is currently being managed by the
SetAGWWindowStyleFlag | Sets the FourWaySplitter window style flags.
SetExpanded | This method is used to expand one of the four window to fill the whole client size (when expanded >= 0) or to return to the four-window view (when expanded < 0).
SetHSplit | Change horizontal split fraction.
SetVSplit | Change vertical split fraction.
_GetBorderSize | Used internally.
_GetSashSize | Used internally.
_RedrawIfHotSensitive | Used internally.
_SizeWindows | Recalculate the layout based on split positions and split fractions.

API Class API

class FourWaySplitter(wx.PyPanel) [source]

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

Note

These things are not yet supported:

  • Minimum pane size (minimum of what? Width? Height?);
  • Using negative sash positions to indicate a position offset from the end;
  • User controlled unsplitting with double clicks on the sash (but supported via the FourWaySplitter.SetExpanded() method);
  • Sash gravity.

__init__(parent, id=wx.ID_ANY, pos=wx.DefaultPosition, size=wx.DefaultSize, style=0, agwStyle=0, name="FourWaySplitter") [source]

Default class constructor.

Parameters:
  • parent – parent window. Must not be None;
  • id – window identifier. A value of -1 indicates a default value;
  • pos – the control position. A value of (-1, -1) indicates a default position, chosen by either the windowing system or wxPython, depending on platform;
  • size – the control size. A value of (-1, -1) indicates a default size, chosen by either the windowing system or wxPython, depending on platform;
  • style – the underlying wx.PyPanel window style;
  • agwStyle – the AGW-specific window style. It can be a combination of the following bits:

    Window Styles | Hex Value | Description
    SP_NOSASH | 0x10 | No sash will be drawn on FourWaySplitter.
    SP_LIVE_UPDATE | 0x80 | Don’t draw XOR line but resize the child windows immediately.
    SP_3DBORDER | 0x200 | Draws a 3D effect border.
  • name – the window name.

AdjustLayout() [source]

Adjust layout of FourWaySplitter. Mainly used to recalculate the correct values for split fractions.

AppendWindow(window) [source]

Add a new window to the splitter at the right side or bottom of the window stack.

Parameters: window – an instance of wx.Window.

DetachWindow(window) [source]

Removes the window from the stack of windows managed by the splitter. The window will still exist so you should Hide or Destroy it as needed.

Parameters: window – an instance of wx.Window.

DoGetBestSize() [source]

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

Note

Overridden from wx.PyPanel.

DoSendChangingEvent(pt) [source]

Sends a EVT_SPLITTER_SASH_POS_CHANGING event.

Parameters: pt – the point at which the splitter is being positioned.

DrawSplitter(dc) [source]

Actually draws the sashes.

Parameters: dc – an instance of wx.DC.

DrawTrackSplitter(x, y) [source]

Draws a fake sash in case we don’t have wx.SP_LIVE_UPDATE style.

Parameters:
  • x – the x position of the sash;
  • y – the y position of the sash.

Note

This method relies on wx.ScreenDC which is currently unavailable on wxMac.

ExchangeWindows(window1, window2) [source]

Trade the positions in the splitter of the two windows.

Parameters:
  • window1 – an instance of wx.Window;

  • window2 – another instance of wx.Window.

GetAGWWindowStyleFlag() [source]

Returns the FourWaySplitter window style.

See also

SetAGWWindowStyleFlag for a list of possible window styles.

GetBottomLeft() [source]

Returns the bottom left window (window index: 2).

GetBottomRight() [source]

Returns the bottom right window (window index: 3).

GetMode(pt) [source]

Determines the split mode for FourWaySplitter.

Parameters: pt – the point at which the mouse has been clicked, an instance of wx.Point.
Returns: One of the following 3 split modes:
Split Mode | Description
wx.HORIZONTAL | the user has clicked on the horizontal sash
wx.VERTICAL | The user has clicked on the vertical sash
wx.BOTH | The user has clicked at the intersection between the 2 sashes

GetTopLeft() [source]

Returns the top left window (window index: 0).

GetTopRight() [source]

Returns the top right window (window index: 1).

GetWindow(idx) [source]

Returns the window at the index idx.

Parameters: idx – the index at which the window is located.

InsertWindow(idx, window, sashPos=-1) [source]

Insert a new window into the splitter at the position given in idx.

Parameters:
  • idx – the index at which the window will be inserted;
  • window – an instance of wx.Window;

  • sashPos – the sash position after the window insertion.

MoveSplit(x, y) [source]

Moves the split accordingly to user action.

Parameters:
  • x – the new splitter x coordinate;
  • y – the new splitter y coordinate.

OnEnterWindow(event) [source]

Handles the wx.EVT_ENTER_WINDOW event for FourWaySplitter.

Parameters: event – a wx.MouseEvent event to be processed.

OnLeaveWindow(event) [source]

Handles the wx.EVT_LEAVE_WINDOW event for FourWaySplitter.

Parameters: event – a wx.MouseEvent event to be processed.

OnLeftDown(event) [source]

Handles the wx.EVT_LEFT_DOWN event for FourWaySplitter.

Parameters: event – a wx.MouseEvent event to be processed.

OnLeftUp(event) [source]

Handles the wx.EVT_LEFT_UP event for FourWaySplitter.

Parameters: event – a wx.MouseEvent event to be processed.

OnMotion(event) [source]

Handles the wx.EVT_MOTION event for FourWaySplitter.

Parameters: event – a wx.MouseEvent event to be processed.

OnPaint(event) [source]

Handles the wx.EVT_PAINT event for FourWaySplitter.

Parameters: event – a wx.PaintEvent event to be processed.

OnSize(event) [source]

Handles the wx.EVT_SIZE event for FourWaySplitter.

Parameters: event – a wx.SizeEvent event to be processed.

ReplaceWindow(oldWindow, newWindow) [source]

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

Parameters:
  • oldWindow – an instance of wx.Window;

  • newWindow – another instance of wx.Window.

SetAGWWindowStyleFlag(agwStyle) [source]

Sets the FourWaySplitter window style flags.

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

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

SetExpanded(expanded) [source]

This method is used to expand one of the four window to fill the whole client size (when expanded >= 0) or to return to the four-window view (when expanded < 0).

Parameters: expanded – an integer >= 0 to expand a window to fill the whole client size, or an integer < 0 to return to the four-window view.

SetHSplit(s) [source]

Change horizontal split fraction.

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

fourSplitter.SetHSplit(3500)

SetVSplit(s) [source]

Change vertical split fraction.

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

fourSplitter.SetVSplit(3500)

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • infobar
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • fourwaysplitter »
  • FourWaySplitter


FourWaySplitterEvent

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • fourwaysplitter »
  • FourWaySplitterEvent

FourWaySplitterEvent

This event class is almost the same as wx.SplitterEvent except it adds an accessor for the sash index that is being changed. The same event type IDs and event binders are used as with wx.SplitterEvent.

hierarchy Inheritance Diagram

Inheritance diagram for: FourWaySplitterEvent

Inheritance diagram of FourWaySplitterEvent

Methods Summary

__init__ | Default class constructor.
Allow | This is the opposite of Veto: it explicitly allows the event to be processed.
GetSashIdx | Returns the index of the sash currently involved in the event.
GetSashPosition | Returns the new sash position.
IsAllowed | Returns True if the change is allowed (Veto hasn’t been called) or
SetSashIdx | Sets the index of the sash currently involved in the event.
SetSashPosition | In the case of EVT_SPLITTER_SASH_POS_CHANGED events, sets the new sash
Veto | Prevents the change announced by this event from happening.

API Class API

class FourWaySplitterEvent(wx.PyCommandEvent) [source]

This event class is almost the same as wx.SplitterEvent except it adds an accessor for the sash index that is being changed. The same event type IDs and event binders are used as with wx.SplitterEvent.

__init__(evtType=wx.wxEVT_NULL, splitter=None) [source]

Default class constructor.

Parameters:
  • evtType – the event type;
  • splitter – the associated FourWaySplitter window.

Allow() [source]

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

GetSashIdx() [source]

Returns the index of the sash currently involved in the event.

GetSashPosition() [source]

Returns the new sash position.

Note

May only be called while processing EVT_SPLITTER_SASH_POS_CHANGING and EVT_SPLITTER_SASH_POS_CHANGED events.

IsAllowed() [source]

Returns True if the change is allowed (Veto hasn’t been called) or False otherwise (if it was).

SetSashIdx(idx) [source]

Sets the index of the sash currently involved in the event.

Parameters: idx – an integer between 0 and 3, representing the index of the sash involved in the event.

SetSashPosition(pos) [source]

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

Parameters: pos – the new sash position.

Note

May only be called while processing EVT_SPLITTER_SASH_POS_CHANGING and EVT_SPLITTER_SASH_POS_CHANGED events.

Veto() [source]

Prevents the change announced by this event from happening.

Note

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

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • infobar
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • fourwaysplitter »
  • FourWaySplitterEvent


SVN Revision 68362 For fourwaysplitter

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • fourwaysplitter »
  • SVN Revision 68362 For fourwaysplitter

svn SVN Revision 68362 For fourwaysplitter

This file contains the SVN revision history for fourwaysplitter, at revision 68362.

Available information include commit date, the name of the committer, the file size, the SVN log messages and a diff from the previous version (if available).

File Information

  • Commit Date: 17-Oct-2008 21:01:24 UTC
  • Committer: AG
  • File Size: 33701 byte(s)

Log Messages

The following log message was entered by the committer:

  • All of AGW: change my work e-mail from KPO to Maersk Oil (silly commit)

Diff To Previous Version (65377)

Version SVN diff:

--- wxPython/3rdParty/AGW/agw/fourwaysplitter.py    2010/08/21 20:27:02     65377
+++ wxPython/3rdParty/AGW/agw/fourwaysplitter.py    2011/07/24 21:36:47     68362
@@ -12,7 +12,7 @@
# For All Kind Of Problems, Requests Of Enhancements And Bug Reports, Please
# Write To Me At:
#
-# gavana@kpo.kz
+# andrea.gavana@maerskoil.com
# andrea.gavana@gmail.com
#
# Or, Obviously, To The wxPython Mailing List!!!

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • fourwaysplitter »
  • SVN Revision 68362 For fourwaysplitter


SVN Revision 68881 For fourwaysplitter

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • fourwaysplitter »
  • SVN Revision 68881 For fourwaysplitter

svn SVN Revision 68881 For fourwaysplitter

This file contains the SVN revision history for fourwaysplitter, at revision 68881.

Available information include commit date, the name of the committer, the file size, the SVN log messages and a diff from the previous version (if available).

File Information

  • Commit Date: 17-Oct-2008 19:15:31 UTC
  • Committer: AG
  • File Size: 34482 byte(s)

Log Messages

The following log message was entered by the committer:

  • AGW: General overhaul of the documentation, much improved. All the widgets have their own sample usage in the docs as well;

  • FlatNotebook: Added the FNB_NAV_BUTTONS_WHEN_NEEDED style, which hides the navigation left/right arrows if all tabs fit;

  • RibbonBar: - Added the EVT_RIBBONBAR_TAB_LEFT_DCLICK event, which generates a special event

    when a ribbon bar tab is double-clicked;

    • Added support for toggle buttons;
    • Improved support for ribbon panel sizers: panels with sizers should now automatically minimise at small sizes, and behave properly when popping up from a minimised state;
    • Added tooltips via SetToolTip for those buttons which have the help_string attribute set.

  • XLSGrid: a new widget was added to AGW, termed XLSGrid. It’s based on wx.grid.Grid and can be used to faithfully reproduce the appearance of a Microsoft Excel spreadsheets.

Diff To Previous Version (68362)

Version SVN diff:

--- wxPython/3rdParty/AGW/agw/fourwaysplitter.py    2011/07/24 21:36:47     68362
+++ wxPython/3rdParty/AGW/agw/fourwaysplitter.py    2011/08/25 16:40:17     68881
@@ -2,7 +2,7 @@
# FOURWAYSPLITTER wxPython IMPLEMENTATION
#
# Andrea Gavana, @ 03 Nov 2006
-# Latest Revision: 14 Apr 2010, 12.00 GMT
+# Latest Revision: 17 Aug 2011, 15.00 GMT
#
#
# TODO List
@@ -22,23 +22,23 @@
# --------------------------------------------------------------------------------- #

"""
-FourWaySplitter is a layout manager which manages 4 children like 4 panes in a
+L{FourWaySplitter} is a layout manager which manages 4 children like 4 panes in a
window.

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

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

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

-The main characteristics of FourWaySplitter are:
+The main characteristics of L{FourWaySplitter} are:

- Handles horizontal, vertical or four way sizing via the sashes;
- Delayed or live update when resizing;
@@ -49,10 +49,47 @@
And a lot more. See the demo for a complete review of the functionalities.

+Usage
+=====
+
+Usage example::
+
+    import wx
+    import wx.lib.agw.fourwaysplitter as fws
+
+    class MyFrame(wx.Frame):
+
+        def __init__(self, parent):
+
+            wx.Frame.__init__(self, parent, -1, "FourWaySplitter Demo")
+
+            splitter = fws.FourWaySplitter(self, -1, agwStyle=wx.SP_LIVE_UPDATE)
+
+            # Put in some coloured panels...
+            for colour in [wx.RED, wx.WHITE, wx.BLUE, wx.GREEN]:
+
+                panel = wx.Panel(splitter)
+                panel.SetBackgroundColour(colour)
+
+                splitter.AppendWindow(panel)
+
+
+    # our normal wxApp-derived class, as usual
+
+    app = wx.PySimpleApp()
+
+    frame = MyFrame(None)
+    app.SetTopWindow(frame)
+    frame.Show()
+
+    app.MainLoop()
+
+
+
Supported Platforms
===================

-FourWaySplitter has been tested on the following platforms:
+L{FourWaySplitter} has been tested on the following platforms:
* Windows (Windows XP);
* Linux Ubuntu (Dapper 6.06)

@@ -65,7 +102,7 @@
================== =========== ==================================================
Window Styles      Hex Value   Description
================== =========== ==================================================
-``SP_NOSASH``             0x10 No sash will be drawn on `FourWaySplitter`.
+``SP_NOSASH``             0x10 No sash will be drawn on L{FourWaySplitter}.
``SP_LIVE_UPDATE``        0x80 Don't draw XOR line but resize the child windows immediately.
``SP_3DBORDER``          0x200 Draws a 3D effect border.
================== =========== ==================================================
@@ -79,17 +116,17 @@
================================== ==================================================
Event Name                         Description
================================== ==================================================
-``EVT_SPLITTER_SASH_POS_CHANGED``  The sash position was changed. This event is generated after the user releases the mouse after dragging the splitter. Processes a `wx.wxEVT_COMMAND_SPLITTER_SASH_POS_CHANGED` event.
-``EVT_SPLITTER_SASH_POS_CHANGING`` The sash position is in the process of being changed. You may prevent this change from happening by calling `Veto` or you may also modify the position of the tracking bar to properly reflect the position that would be set if the drag were to be completed at this point. Processes a `wx.wxEVT_COMMAND_SPLITTER_SASH_POS_CHANGING` event.
+``EVT_SPLITTER_SASH_POS_CHANGED``  The sash position was changed. This event is generated after the user releases the mouse after dragging the splitter. Processes a ``wx.wxEVT_COMMAND_SPLITTER_SASH_POS_CHANGED`` event.
+``EVT_SPLITTER_SASH_POS_CHANGING`` The sash position is in the process of being changed. You may prevent this change from happening by calling `Veto` or you may also modify the position of the tracking bar to properly reflect the position that would be set if the drag were to be completed at this point. Processes a ``wx.wxEVT_COMMAND_SPLITTER_SASH_POS_CHANGING`` event.
================================== ==================================================

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

-FourWaySplitter is distributed under the wxPython license.
+L{FourWaySplitter} is distributed under the wxPython license.

-Latest Revision: Andrea Gavana @ 14 Apr 2010, 12.00 GMT
+Latest Revision: Andrea Gavana @ 17 Aug 2011, 15.00 GMT

Version 0.4

@@ -112,7 +149,7 @@

# FourWaySplitter styles
SP_NOSASH = wx.SP_NOSASH
-""" No sash will be drawn on `FourWaySplitter`. """
+""" No sash will be drawn on L{FourWaySplitter}. """
SP_LIVE_UPDATE = wx.SP_LIVE_UPDATE
""" Don't draw XOR line but resize the child windows immediately. """
SP_3DBORDER = wx.SP_3DBORDER
@@ -123,10 +160,10 @@
""" The sash position is in the process of being changed. You may prevent this change""" \
""" from happening by calling `Veto` or you may also modify the position of the tracking""" \
""" bar to properly reflect the position that would be set if the drag were to be""" \
-""" completed at this point. Processes a `wx.wxEVT_COMMAND_SPLITTER_SASH_POS_CHANGING` event."""
+""" completed at this point. Processes a ``wx.wxEVT_COMMAND_SPLITTER_SASH_POS_CHANGING`` event."""
EVT_SPLITTER_SASH_POS_CHANGED = wx.EVT_SPLITTER_SASH_POS_CHANGED
""" The sash position was changed. This event is generated after the user releases the""" \
-""" mouse after dragging the splitter. Processes a `wx.wxEVT_COMMAND_SPLITTER_SASH_POS_CHANGED` event. """
+""" mouse after dragging the splitter. Processes a ``wx.wxEVT_COMMAND_SPLITTER_SASH_POS_CHANGED`` event. """

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

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • fourwaysplitter »
  • SVN Revision 68881 For fourwaysplitter


SVN Revision 68342 For framemanager

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • aui library »
  • aui.framemanager »
  • SVN Revision 68342 For framemanager

svn SVN Revision 68342 For framemanager

This file contains the SVN revision history for framemanager, at revision 68342.

Available information include commit date, the name of the committer, the file size, the SVN log messages and a diff from the previous version (if available).

File Information

  • Commit Date: 03-Apr-2009 08:32:16 UTC
  • Committer: AG
  • File Size: 361572 byte(s)

Log Messages

The following log message was entered by the committer:

  • ToasterBox: fixed ticket #13258. It appears wx.FRAME_TOOL_WINDOW doesn’t work as expected on Windows 7
  • AuiNotebook: fixed tickets #12800 and #12919

Diff To Previous Version (67166)

Version SVN diff:

--- wxPython/3rdParty/AGW/agw/aui/framemanager.py   2011/03/10 13:52:18     67166
+++ wxPython/3rdParty/AGW/agw/aui/framemanager.py   2011/07/23 19:06:24     68342
@@ -13,7 +13,7 @@
# Python Code By:
#
# Andrea Gavana, @ 23 Dec 2005
-# Latest Revision: 10 Mar 2011, 15.00 GMT
+# Latest Revision: 22 Jul 2011, 21.00 GMT
#
# For All Kind Of Problems, Requests Of Enhancements And Bug Reports, Please
# Write To Me At:
@@ -1044,8 +1044,10 @@
ret = self.MinSize1(arg1)
elif isinstance(arg1, types.TupleType):
ret = self.MinSize1(wx.Size(*arg1))
-        else:
+        elif isinstance(arg1, types.IntType) and arg2 is not None:
ret = self.MinSize2(arg1, arg2)
+        else:
+            raise Exception("Invalid argument passed to `MinSize`: arg1=%s, arg2=%s"%(repr(arg1), repr(arg2)))

return ret

@@ -1086,8 +1088,10 @@
ret = self.MaxSize1(arg1)
elif isinstance(arg1, types.TupleType):
ret = self.MaxSize1(wx.Size(*arg1))
-        else:
+        elif isinstance(arg1, types.IntType) and arg2 is not None:
ret = self.MaxSize2(arg1, arg2)
+        else:
+            raise Exception("Invalid argument passed to `MaxSize`: arg1=%s, arg2=%s"%(repr(arg1), repr(arg2)))

return ret

@@ -1130,8 +1134,10 @@
ret = self.BestSize1(arg1)
elif isinstance(arg1, types.TupleType):
ret = self.BestSize1(wx.Size(*arg1))
-        else:
+        elif isinstance(arg1, types.IntType) and arg2 is not None:
ret = self.BestSize2(arg1, arg2)
+        else:
+            raise Exception("Invalid argument passed to `BestSize`: arg1=%s, arg2=%s"%(repr(arg1), repr(arg2)))

return ret

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • aui library »
  • aui.framemanager »
  • SVN Revision 68342 For framemanager


SVN Revision 68475 For framemanager

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • aui library »
  • aui.framemanager »
  • SVN Revision 68475 For framemanager

svn SVN Revision 68475 For framemanager

This file contains the SVN revision history for framemanager, at revision 68475.

Available information include commit date, the name of the committer, the file size, the SVN log messages and a diff from the previous version (if available).

File Information

  • Commit Date: 02-Apr-2009 14:32:39 UTC
  • Committer: AG
  • File Size: 364831 byte(s)

Log Messages

The following log message was entered by the committer:

framemanager.py: Implementation of the AUI_MINIMIZE_POS_TOOLBAR flag, which allows to minimize a pane inside an existing toolbar. Limitation: if the minimized icon in the toolbar ends up in the overflowing items (i.e., a menu is needed to show the icon), this style will not work.

Diff To Previous Version (68362)

Version SVN diff:

--- wxPython/3rdParty/AGW/agw/aui/framemanager.py   2011/07/24 21:36:47     68362
+++ wxPython/3rdParty/AGW/agw/aui/framemanager.py   2011/07/31 20:22:23     68475
@@ -13,7 +13,7 @@
# Python Code By:
#
# Andrea Gavana, @ 23 Dec 2005
-# Latest Revision: 22 Jul 2011, 21.00 GMT
+# Latest Revision: 31 Jul 2011, 22.00 GMT
#
# For All Kind Of Problems, Requests Of Enhancements And Bug Reports, Please
# Write To Me At:
@@ -30,7 +30,7 @@
Description
===========

-framemanager is the central module of the AUI class framework.
+`framemanager.py` is the central module of the AUI class framework.

L{AuiManager} manages the panes associated with it for a particular `wx.Frame`, using
a pane's L{AuiPaneInfo} information to determine each pane's docking and floating
@@ -547,6 +547,7 @@
self.previousDockPos = None
self.previousDockSize = 0
self.snapped = 0
+        self.minimize_target = None

self.DefaultPane()

@@ -822,7 +823,8 @@
``AUI_MINIMIZE_POS_LEFT``           0x03 Minimizes the pane on its left tool bar
``AUI_MINIMIZE_POS_RIGHT``          0x04 Minimizes the pane on its right tool bar
``AUI_MINIMIZE_POS_BOTTOM``         0x05 Minimizes the pane on its bottom tool bar
-        ``AUI_MINIMIZE_POS_MASK``           0x07 Mask to filter the position flags
+        ``AUI_MINIMIZE_POS_TOOLBAR``        0x06 Minimizes the pane on a target L{AuiToolBar}
+        ``AUI_MINIMIZE_POS_MASK``           0x17 Mask to filter the position flags
``AUI_MINIMIZE_CAPT_HIDE``           0x0 Hides the caption of the minimized pane
``AUI_MINIMIZE_CAPT_SMART``         0x08 Displays the caption in the best rotation (horizontal or clockwise)
``AUI_MINIMIZE_CAPT_HORZ``          0x10 Displays the caption horizontally
@@ -834,7 +836,7 @@
============================== ========= ==============================
Minimize Mask Flag             Hex Value Description
============================== ========= ==============================
-        ``AUI_MINIMIZE_POS_MASK``           0x07 Filters the position flags
+        ``AUI_MINIMIZE_POS_MASK``           0x17 Filters the position flags
``AUI_MINIMIZE_CAPT_MASK``          0x18 Filters the caption flags
============================== ========= ==============================

@@ -1222,6 +1224,7 @@
``AUI_MINIMIZE_POS_LEFT``           0x03 Minimizes the pane on its left tool bar
``AUI_MINIMIZE_POS_RIGHT``          0x04 Minimizes the pane on its right tool bar
``AUI_MINIMIZE_POS_BOTTOM``         0x05 Minimizes the pane on its bottom tool bar
+        ``AUI_MINIMIZE_POS_TOOLBAR``        0x06 Minimizes the pane on a target L{AuiToolBar}
============================== ========= ==============================

The caption of the minimized pane can be displayed in different modes:
@@ -1240,6 +1243,24 @@
return self

+    def MinimizeTarget(self, toolbarPane):
+        """
+        Minimizes the panes using a L{AuiPaneInfo} as a target. As L{AuiPaneInfo} properties
+        need to be copied back and forth every time the perspective has changed, we
+        only store the toobar **name**.
+
+        :param `toolbarPane`: an instance of L{AuiPaneInfo}, containing a L{AuiToolBar}.
+
+        :note: In order to use this functionality (and with the ``AUI_MINIMIZE_POS_TOOLBAR``
+         flag set), the instance of L{AuiPaneInfo} you pass as an input **must** have a real
+         name and not the randomly generated one. Remember to set the L{Name} property of
+         the toolbar pane before calling this method.
+        """
+
+        self.minimize_target = toolbarPane.name
+        return self
+
+
def Restore(self):
""" Is the reverse of L{Maximize} and L{Minimize}."""

@@ -1678,8 +1699,7 @@
self.optionFloatable | self.optionMovable | self.optionResizable | \
self.optionCaption | self.optionPaneBorder | self.buttonClose

-        self.state = state
-
+        self.state = state
return self

@@ -1708,7 +1728,7 @@

def ToolbarPane(self):
""" Specifies that the pane should adopt the default toolbar pane settings. """
-
+
self.DefaultPane()
state = self.state

@@ -2891,6 +2911,7 @@
contained_pane.transparent = pane.transparent
contained_pane.snapped = pane.snapped
contained_pane.minimize_mode = pane.minimize_mode
+        contained_pane.minimize_target = pane.minimize_target

return contained_pane

@@ -3425,6 +3446,7 @@
dest_panes[ii].transparent = src_panes[ii].transparent
dest_panes[ii].snapped = src_panes[ii].snapped
dest_panes[ii].minimize_mode = src_panes[ii].minimize_mode
+        dest_panes[ii].minimize_target = src_panes[ii].minimize_target

for ii in xrange(len(dest_docks)):
dock = dest_docks[ii]
@@ -7416,6 +7438,7 @@
drop.transparent = target.transparent
drop.snapped = target.snapped
drop.minimize_mode = target.minimize_mode
+        drop.minimize_target = target.minimize_target

return drop

@@ -8206,7 +8229,7 @@
pane.floating_pos, pane.floating_size, pane.best_size,
pane.min_size, pane.max_size, pane.caption, pane.name,
pane.buttons, pane.rect, pane.icon, pane.notebook_id,
-                      pane.transparent, pane.snapped, pane.minimize_mode])
+                      pane.transparent, pane.snapped, pane.minimize_mode, pane.minimize_target])

return attrs

@@ -8241,6 +8264,7 @@
pane.transparent = attrs[19]
pane.snapped = attrs[20]
pane.minimize_mode = attrs[21]
+        pane.minimize_target = attrs[22]

return pane

@@ -9793,15 +9817,30 @@
#
# 3) Hide the minimizing pane

-
# personalize the toolbar style
+
tbStyle = AUI_TB_DEFAULT_STYLE
posMask = paneInfo.minimize_mode & AUI_MINIMIZE_POS_MASK
captMask = paneInfo.minimize_mode & AUI_MINIMIZE_CAPT_MASK
dockDirection = paneInfo.dock_direction
if captMask != 0:
tbStyle |= AUI_TB_TEXT
-            if posMask == AUI_MINIMIZE_POS_SMART:
+
+            if posMask == AUI_MINIMIZE_POS_TOOLBAR:
+                minimize_toolbar = self.GetPane(paneInfo.minimize_target)
+                if not minimize_toolbar.IsOk():
+                    posMask = AUI_MINIMIZE_POS_SMART
+                    if paneInfo.dock_direction in [AUI_DOCK_TOP, AUI_DOCK_BOTTOM]:
+                        tbStyle |= AUI_TB_HORZ_LAYOUT
+
+                    elif paneInfo.dock_direction in [AUI_DOCK_LEFT, AUI_DOCK_RIGHT, AUI_DOCK_CENTER]:
+                        tbStyle |= AUI_TB_VERTICAL
+                        if captMask == AUI_MINIMIZE_CAPT_SMART:
+                            tbStyle |= AUI_TB_CLOCKWISE
+                else:
+                    minimize_toolbar = minimize_toolbar.window
+
+            elif posMask == AUI_MINIMIZE_POS_SMART:
if paneInfo.dock_direction in [AUI_DOCK_TOP, AUI_DOCK_BOTTOM]:
tbStyle |= AUI_TB_HORZ_LAYOUT

@@ -9832,17 +9871,29 @@
# give it the same name as the minimized pane with _min appended

win_rect = paneInfo.window.GetScreenRect()
-
-            minimize_toolbar = auibar.AuiToolBar(self.GetManagedWindow(), agwStyle=tbStyle)
-            minimize_toolbar.Hide()
-            minimize_toolbar.SetToolBitmapSize(wx.Size(16, 16))
+
+            if posMask != AUI_MINIMIZE_POS_TOOLBAR:
+                minimize_toolbar = auibar.AuiToolBar(self.GetManagedWindow(), agwStyle=tbStyle)
+                minimize_toolbar.Hide()
+                minimize_toolbar.SetToolBitmapSize(wx.Size(16, 16))

if paneInfo.icon and paneInfo.icon.IsOk():
restore_bitmap = paneInfo.icon
else:
restore_bitmap = self._art._restore_bitmap
+
+            if posMask == AUI_MINIMIZE_POS_TOOLBAR:
+                xsize, ysize = minimize_toolbar.GetToolBitmapSize()
+                if xsize != restore_bitmap.GetWidth():
+                    img = restore_bitmap.ConvertToImage()
+                    img.Rescale(xsize, ysize, wx.IMAGE_QUALITY_HIGH)
+                    restore_bitmap = img.ConvertToBitmap()
+
+            target = None
+            if posMask == AUI_MINIMIZE_POS_TOOLBAR:
+                target = paneInfo.name

-            minimize_toolbar.AddSimpleTool(ID_RESTORE_FRAME, paneInfo.caption, restore_bitmap, "Restore " + paneInfo.caption)
+            minimize_toolbar.AddSimpleTool(ID_RESTORE_FRAME, paneInfo.caption, restore_bitmap, "Restore " + paneInfo.caption, target=target)
minimize_toolbar.SetAuiManager(self)
minimize_toolbar.Realize()
toolpanelname = paneInfo.name + "_min"
@@ -9850,29 +9901,31 @@
if paneInfo.IsMaximized():
paneInfo.SetFlag(paneInfo.wasMaximized, True)

-            if dockDirection == AUI_DOCK_TOP:
-                self.AddPane(minimize_toolbar, AuiPaneInfo(). \
-                    Name(toolpanelname).Caption(paneInfo.caption). \
-                    ToolbarPane().Top().BottomDockable(False). \
-                    LeftDockable(False).RightDockable(False).DestroyOnClose())
-
-            elif dockDirection == AUI_DOCK_BOTTOM:
-                self.AddPane(minimize_toolbar, AuiPaneInfo(). \
-                    Name(toolpanelname).Caption(paneInfo.caption). \
-                    ToolbarPane().Bottom().TopDockable(False). \
-                    LeftDockable(False).RightDockable(False).DestroyOnClose())
-
-            elif dockDirection == AUI_DOCK_LEFT:
-                self.AddPane(minimize_toolbar, AuiPaneInfo(). \
-                    Name(toolpanelname).Caption(paneInfo.caption). \
-                    ToolbarPane().Left().TopDockable(False). \
-                    BottomDockable(False).RightDockable(False).DestroyOnClose())
-
-            elif dockDirection in [AUI_DOCK_RIGHT, AUI_DOCK_CENTER]:
-                self.AddPane(minimize_toolbar, AuiPaneInfo(). \
-                    Name(toolpanelname).Caption(paneInfo.caption). \
-                    ToolbarPane().Right().TopDockable(False). \
-                    LeftDockable(False).BottomDockable(False).DestroyOnClose())
+            if posMask != AUI_MINIMIZE_POS_TOOLBAR:
+
+                if dockDirection == AUI_DOCK_TOP:
+                    self.AddPane(minimize_toolbar, AuiPaneInfo(). \
+                        Name(toolpanelname).Caption(paneInfo.caption). \
+                        ToolbarPane().Top().BottomDockable(False). \
+                        LeftDockable(False).RightDockable(False).DestroyOnClose())
+
+                elif dockDirection == AUI_DOCK_BOTTOM:
+                    self.AddPane(minimize_toolbar, AuiPaneInfo(). \
+                        Name(toolpanelname).Caption(paneInfo.caption). \
+                        ToolbarPane().Bottom().TopDockable(False). \
+                        LeftDockable(False).RightDockable(False).DestroyOnClose())
+
+                elif dockDirection == AUI_DOCK_LEFT:
+                    self.AddPane(minimize_toolbar, AuiPaneInfo(). \
+                        Name(toolpanelname).Caption(paneInfo.caption). \
+                        ToolbarPane().Left().TopDockable(False). \
+                        BottomDockable(False).RightDockable(False).DestroyOnClose())
+
+                elif dockDirection in [AUI_DOCK_RIGHT, AUI_DOCK_CENTER]:
+                    self.AddPane(minimize_toolbar, AuiPaneInfo(). \
+                        Name(toolpanelname).Caption(paneInfo.caption). \
+                        ToolbarPane().Right().TopDockable(False). \
+                        LeftDockable(False).BottomDockable(False).DestroyOnClose())

arr = FindDocks(self._docks, paneInfo.dock_direction, paneInfo.dock_layer, paneInfo.dock_row)

@@ -9970,11 +10023,17 @@
"""

panename = paneInfo.name
-        panename = panename[0:-4]
-        pane = self.GetPane(panename)

+        if paneInfo.minimize_mode & AUI_MINIMIZE_POS_TOOLBAR:
+            pane = self.GetPane(panename)
+            hasTarget = True
+        else:
+            panename = panename[0:-4]
+            hasTarget = False
+
+        pane = self.GetPane(panename)
pane.SetFlag(pane.needsRestore, True)
-
+
if not pane.IsOk():
panename = paneInfo.name
pane = self.GetPane(panename)
@@ -9989,18 +10048,24 @@

if pane.HasFlag(pane.wasMaximized):
-
self.SavePreviousDockSizes(pane)

-
self.ShowPane(pane.window, True)
pane.Show(True)
self._has_minimized = False
pane.SetFlag(pane.optionMinimized, False)
-            paneInfo.window.Show(False)
-            self.DetachPane(paneInfo.window)
-            paneInfo.Show(False)
-            paneInfo.Hide()
+
+            if hasTarget:
+                targetName = pane.minimize_target
+                toolbarPane = self.GetPane(targetName)
+                toolbar = toolbarPane.window
+                item = toolbar.FindToolByLabel(pane.caption)
+                toolbar.DeleteTool(item.id)
+            else:
+                paneInfo.window.Show(False)
+                self.DetachPane(paneInfo.window)
+                paneInfo.Show(False)
+                paneInfo.Hide()

self.Update()

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • aui library »
  • aui.framemanager »
  • SVN Revision 68475 For framemanager


SVN Revision 68933 For framemanager

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • aui library »
  • aui.framemanager »
  • SVN Revision 68933 For framemanager

svn SVN Revision 68933 For framemanager

This file contains the SVN revision history for framemanager, at revision 68933.

Available information include commit date, the name of the committer, the file size, the SVN log messages and a diff from the previous version (if available).

File Information

  • Commit Date: 02-Apr-2009 13:19:54 UTC
  • Committer: AG
  • File Size: 365132 byte(s)

Log Messages

The following log message was entered by the committer:

AGW: Some further refactoring of the docs: - Added downloadable snippets of code in the Sphinx documentation itself; - Re-run 2to3 afresh so that the patches are up-to-date for Python 3.

Diff To Previous Version (68476)

Version SVN diff:

--- wxPython/3rdParty/AGW/agw/aui/framemanager.py   2011/07/31 22:50:55     68476
+++ wxPython/3rdParty/AGW/agw/aui/framemanager.py   2011/08/27 17:11:41     68933
@@ -13,7 +13,7 @@
# Python Code By:
#
# Andrea Gavana, @ 23 Dec 2005
-# Latest Revision: 31 Jul 2011, 22.00 GMT
+# Latest Revision: 17 Aug 2011, 15.00 GMT
#
# For All Kind Of Problems, Requests Of Enhancements And Bug Reports, Please
# Write To Me At:

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • aui library »
  • aui.framemanager »
  • SVN Revision 68933 For framemanager


SVN Revision 69086 For framemanager

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • aui library »
  • aui.framemanager »
  • SVN Revision 69086 For framemanager

svn SVN Revision 69086 For framemanager

This file contains the SVN revision history for framemanager, at revision 69086.

Available information include commit date, the name of the committer, the file size, the SVN log messages and a diff from the previous version (if available).

File Information

  • Commit Date: 02-Apr-2009 10:53:15 UTC
  • Committer: AG
  • File Size: 365134 byte(s)

Log Messages

The following log message was entered by the committer:

  • Fixed bug #13437 for SuperToolTip;
  • Fixed bug #13477 for UltimateListCtrl.

Diff To Previous Version (68933)

Version SVN diff:

--- wxPython/3rdParty/AGW/agw/aui/framemanager.py   2011/08/27 17:11:41     68933
+++ wxPython/3rdParty/AGW/agw/aui/framemanager.py   2011/09/14 19:39:08     69086
@@ -4469,7 +4469,7 @@
def UnInit(self):
"""
Uninitializes the framework and should be called before a managed frame or
-        window is destroyed. L{UnInit} is usually called in the managed `wx.Frame`/`wx.Window`
+        window is destroyed. L{UnInit} is usually called in the managed `wx.Frame` / `wx.Window`
destructor.

It is necessary to call this function before the managed frame or window is

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • aui library »
  • aui.framemanager »
  • SVN Revision 69086 For framemanager


SVN Revision 69627 For framemanager

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • aui library »
  • aui.framemanager »
  • SVN Revision 69627 For framemanager

svn SVN Revision 69627 For framemanager

This file contains the SVN revision history for framemanager, at revision 69627.

Available information include commit date, the name of the committer, the file size, the SVN log messages and a diff from the previous version (if available).

File Information

  • Commit Date: 01-Apr-2009 02:45:51 UTC
  • Committer: AG
  • File Size: 365384 byte(s)

Log Messages

The following log message was entered by the committer:

  • AuiManager: fix the assertion error in the demo;
  • Others: minor fixes to the docstrings.

Diff To Previous Version (69086)

Version SVN diff:

--- wxPython/3rdParty/AGW/agw/aui/framemanager.py   2011/09/14 19:39:08     69086
+++ wxPython/3rdParty/AGW/agw/aui/framemanager.py   2011/11/01 19:42:21     69627
@@ -13,7 +13,7 @@
# Python Code By:
#
# Andrea Gavana, @ 23 Dec 2005
-# Latest Revision: 17 Aug 2011, 15.00 GMT
+# Latest Revision: 01 Nov 2011, 21.00 GMT
#
# For All Kind Of Problems, Requests Of Enhancements And Bug Reports, Please
# Write To Me At:
@@ -4034,7 +4034,9 @@
Default value for `agwFlags` is:
``AUI_MGR_DEFAULT`` = ``AUI_MGR_ALLOW_FLOATING`` | ``AUI_MGR_TRANSPARENT_HINT`` | ``AUI_MGR_HINT_FADE`` | ``AUI_MGR_NO_VENETIAN_BLINDS_FADE``

-         :note: If using the ``AUI_MGR_USE_NATIVE_MINIFRAMES``, double-clicking on a
+         :note:
+
+          If using the ``AUI_MGR_USE_NATIVE_MINIFRAMES``, double-clicking on a
floating pane caption will not re-dock the pane, but simply maximize it (if
L{AuiPaneInfo.MaximizeButton} has been set to ``True``) or do nothing.
"""
@@ -4321,7 +4323,9 @@
``AUI_MGR_AUTONB_NO_CAPTION``        Panes that merge into an automatic notebook will not have the pane caption visible
==================================== ==================================

-         :note: If using the ``AUI_MGR_USE_NATIVE_MINIFRAMES``, double-clicking on a
+         :note:
+
+          If using the ``AUI_MGR_USE_NATIVE_MINIFRAMES``, double-clicking on a
floating pane caption will not re-dock the pane, but simply maximize it (if
L{AuiPaneInfo.MaximizeButton} has been set to ``True``) or do nothing.

@@ -4477,8 +4481,14 @@
from a window.
"""

-        if self._frame:
-            self._frame.RemoveEventHandler(self)
+        if not self._frame:
+            return
+
+        for klass in [self._frame] + list(self._frame.GetChildren()):
+            handler = klass.GetEventHandler()
+            if klass is not handler:
+                if isinstance(handler, AuiManager):
+                    klass.PopEventHandler(True)

def GetArtProvider(self):

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • aui library »
  • aui.framemanager »
  • SVN Revision 69627 For framemanager


SVN Revision 70697 For framemanager

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • aui library »
  • aui.framemanager »
  • SVN Revision 70697 For framemanager

svn SVN Revision 70697 For framemanager

This file contains the SVN revision history for framemanager, at revision 70697.

Available information include commit date, the name of the committer, the file size, the SVN log messages and a diff from the previous version (if available).

File Information

  • Commit Date: 31-Mar-2009 16:34:20 UTC
  • Committer: AG
  • File Size: 365431 byte(s)

Log Messages

The following log message was entered by the committer:

AuiManager: internationalize the various hard-coded strings.

Diff To Previous Version (69627)

Version SVN diff:

--- wxPython/3rdParty/AGW/agw/aui/framemanager.py   2011/11/01 19:42:21     69627
+++ wxPython/3rdParty/AGW/agw/aui/framemanager.py   2012/02/26 15:15:02     70697
@@ -13,7 +13,7 @@
# Python Code By:
#
# Andrea Gavana, @ 23 Dec 2005
-# Latest Revision: 01 Nov 2011, 21.00 GMT
+# Latest Revision: 26 Feb 2012, 15.00 GMT
#
# For All Kind Of Problems, Requests Of Enhancements And Bug Reports, Please
# Write To Me At:
@@ -9906,7 +9906,8 @@
if posMask == AUI_MINIMIZE_POS_TOOLBAR:
target = paneInfo.name

-            minimize_toolbar.AddSimpleTool(ID_RESTORE_FRAME, paneInfo.caption, restore_bitmap, "Restore " + paneInfo.caption, target=target)
+            minimize_toolbar.AddSimpleTool(ID_RESTORE_FRAME, paneInfo.caption, restore_bitmap,
+                                           _(u"Restore %s")%paneInfo.caption, target=target)
minimize_toolbar.SetAuiManager(self)
minimize_toolbar.Realize()
toolpanelname = paneInfo.name + "_min"

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • aui library »
  • aui.framemanager »
  • SVN Revision 70697 For framemanager


SVN Revision 70836 For framemanager

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • aui library »
  • aui.framemanager »
  • SVN Revision 70836 For framemanager

svn SVN Revision 70836 For framemanager

This file contains the SVN revision history for framemanager, at revision 70836.

Available information include commit date, the name of the committer, the file size, the SVN log messages and a diff from the previous version (if available).

File Information

  • Commit Date: 31-Mar-2009 15:36:51 UTC
  • Committer: AG
  • File Size: 365458 byte(s)

Log Messages

The following log message was entered by the committer:

  • AuiManager: fix a resource leak by calling Destroy on the AuiManager’s wx.EvtHandler;
  • AuiNotebook: override Destroy to call UnInit on the AuiNotebook‘s manager during window destruction.

Diff To Previous Version (70697)

Version SVN diff:

--- wxPython/3rdParty/AGW/agw/aui/framemanager.py   2012/02/26 15:15:02     70697
+++ wxPython/3rdParty/AGW/agw/aui/framemanager.py   2012/03/07 19:49:50     70836
@@ -13,7 +13,7 @@
# Python Code By:
#
# Andrea Gavana, @ 23 Dec 2005
-# Latest Revision: 26 Feb 2012, 15.00 GMT
+# Latest Revision: 07 Mar 2012, 21.00 GMT
#
# For All Kind Of Problems, Requests Of Enhancements And Bug Reports, Please
# Write To Me At:
@@ -4482,6 +4482,7 @@
"""

if not self._frame:
+            self.Destroy()
return

for klass in [self._frame] + list(self._frame.GetChildren()):

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • aui library »
  • aui.framemanager »
  • SVN Revision 70836 For framemanager


Thumbnail gallery

  • modules |
  • Home |
  • Gallery |
  • Contents»
  • Thumbnail gallery

Click on any image to see full size image

AquaButton
AquaButton
AuiManager
AuiManager
AuiNotebook
AuiNotebook
AuiToolBar
AuiToolBar
ButtonPanel
ButtonPanel
CubeColourDialog
CubeColourDialog
FMCustomizeDlg
FMCustomizeDlg
FlatImageBook
FlatImageBook
FlatMenu
FlatMenu
FlatNotebook
FlatNotebook
FourWaySplitter
FourWaySplitter
GenericMessageDialog
GenericMessageDialog
GradientButton
GradientButton
HyperTreeList
HyperTreeList
InfoBar
InfoBar
KnobCtrl
KnobCtrl
LabelBook
LabelBook
MultiDirDialog
MultiDirDialog
PeakMeterCtrl
PeakMeterCtrl
PyBusyInfo
PyBusyInfo
PyCollapsiblePane
PyCollapsiblePane
PyGauge
PyGauge
PyProgress
PyProgress
RibbonBar
RibbonBar
RibbonButtonBar
RibbonButtonBar
RibbonGallery
RibbonGallery
RibbonPage
RibbonPage
RibbonPanel
RibbonPanel
RibbonToolBar
RibbonToolBar
RulerCtrl
RulerCtrl
ShortcutEditor
ShortcutEditor
SuperToolTip
SuperToolTip
UltimateListCtrl
UltimateListCtrl
XLSGrid
XLSGrid
ZoomBar
ZoomBar

Navigation

  • index
  • modules |
  • Home |
  • Gallery |
  • Thumbnail gallery


SVN Revision 68881 For gallery

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • ribbon library »
  • ribbon.gallery »
  • SVN Revision 68881 For gallery

svn SVN Revision 68881 For gallery

This file contains the SVN revision history for gallery, at revision 68881.

Available information include commit date, the name of the committer, the file size, the SVN log messages and a diff from the previous version (if available).

File Information

  • Commit Date: 18-Nov-2009 22:19:25 UTC
  • Committer: AG
  • File Size: 28474 byte(s)

Log Messages

The following log message was entered by the committer:

  • AGW: General overhaul of the documentation, much improved. All the widgets have their own sample usage in the docs as well;

  • FlatNotebook: Added the FNB_NAV_BUTTONS_WHEN_NEEDED style, which hides the navigation left/right arrows if all tabs fit;

  • RibbonBar: - Added the EVT_RIBBONBAR_TAB_LEFT_DCLICK event, which generates a special event

    when a ribbon bar tab is double-clicked;

    • Added support for toggle buttons;
    • Improved support for ribbon panel sizers: panels with sizers should now automatically minimise at small sizes, and behave properly when popping up from a minimised state;
    • Added tooltips via SetToolTip for those buttons which have the help_string attribute set.

  • XLSGrid: a new widget was added to AGW, termed XLSGrid. It’s based on wx.grid.Grid and can be used to faithfully reproduce the appearance of a Microsoft Excel spreadsheets.

Diff To Previous Version (65529)

Version SVN diff:

--- wxPython/3rdParty/AGW/agw/ribbon/gallery.py     2010/09/12 11:58:40     65529
+++ wxPython/3rdParty/AGW/agw/ribbon/gallery.py     2011/08/25 16:40:17     68881
@@ -25,9 +25,9 @@
=================================== ===================================
``EVT_RIBBONGALLERY_SELECTED``      Triggered when the user selects an item from the gallery. Note that the ID is that of the gallery, not of the item.
``EVT_RIBBONGALLERY_HOVER_CHANGED`` Triggered when the item being hovered over by the user changes. The item in the event will be the new item being hovered, or ``None`` if there is no longer an item being hovered. Note that the ID is that of the gallery, not of the item.
+``EVT_RIBBONGALLERY_CLICKED``       Triggered when the user clicks on an item in the gallery.
``EVT_BUTTON``                      Triggered when the "extension" button of the gallery is pressed.
=================================== ===================================
-
"""

import wx
@@ -37,9 +37,11 @@

wxEVT_COMMAND_RIBBONGALLERY_HOVER_CHANGED = wx.NewEventType()
wxEVT_COMMAND_RIBBONGALLERY_SELECTED = wx.NewEventType()
+wxEVT_COMMAND_RIBBONGALLERY_CLICKED = wx.NewEventType()

EVT_RIBBONGALLERY_HOVER_CHANGED = wx.PyEventBinder(wxEVT_COMMAND_RIBBONGALLERY_HOVER_CHANGED, 1)
EVT_RIBBONGALLERY_SELECTED = wx.PyEventBinder(wxEVT_COMMAND_RIBBONGALLERY_SELECTED, 1)
+EVT_RIBBONGALLERY_CLICKED = wx.PyEventBinder(wxEVT_COMMAND_RIBBONGALLERY_CLICKED, 1)

class RibbonGalleryEvent(wx.PyCommandEvent):
@@ -157,6 +159,7 @@
self.Bind(wx.EVT_LEAVE_WINDOW, self.OnMouseLeave)
self.Bind(wx.EVT_LEFT_DOWN, self.OnMouseDown)
self.Bind(wx.EVT_LEFT_UP, self.OnMouseUp)
+        self.Bind(wx.EVT_LEFT_DCLICK, self.OnMouseDClick)
self.Bind(wx.EVT_MOTION, self.OnMouseMove)
self.Bind(wx.EVT_PAINT, self.OnPaint)
self.Bind(wx.EVT_SIZE, self.OnSize)
@@ -361,12 +364,27 @@
notification.SetGallery(self)
notification.SetGalleryItem(self._selected_item)
self.GetEventHandler().ProcessEvent(notification)
-
+
+                    notification = RibbonGalleryEvent(wxEVT_COMMAND_RIBBONGALLERY_CLICKED, self.GetId())
+                    notification.SetEventObject(self)
+                    notification.SetGallery(self)
+                    notification.SetGalleryItem(self._selected_item)
+                    self.GetEventHandler().ProcessEvent(notification)
+
self._mouse_active_rect = None
self._active_item = None
self.Refresh(False)

+    def OnMouseDClick(self, event):
+
+        # The 2nd click of a double-click should be handled as a click in the
+        # same way as the 1st click of the double-click. This is useful for
+        # scrolling through the gallery.
+        self.OnMouseDown(event)
+        self.OnMouseUp(event)
+
+
def SetItemClientData(self, item, data):
"""
Set the client data associated with a gallery item.
@@ -487,10 +505,7 @@
if self._art == None:
return

-        cur_size = self.GetSize()
-        min_size = self.GetMinSize()
-
-        self._art.DrawGalleryBackground(dc, self, wx.Rect(0, 0, *cur_size))
+        self._art.DrawGalleryBackground(dc, self, wx.Rect(0, 0, *self.GetSize()))

padding_top = self._art.GetMetric(RIBBON_ART_GALLERY_BITMAP_PADDING_TOP_SIZE)
padding_left = self._art.GetMetric(RIBBON_ART_GALLERY_BITMAP_PADDING_LEFT_SIZE)

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • ribbon library »
  • ribbon.gallery »
  • SVN Revision 68881 For gallery


GenericMessageDialog

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • genericmessagedialog »
  • GenericMessageDialog

GenericMessageDialog

Main class implementation, GenericMessageDialog is a possible replacement for the standard wx.MessageDialog.

hierarchy Inheritance Diagram

Inheritance diagram for: GenericMessageDialog

Inheritance diagram of GenericMessageDialog

subclasses Known Subclasses

  • shortcuteditor.ConflictDialog

appearance Control Appearance

GenericMessageDialog

Methods Summary

__init__ | Default class constructor.
CreateButtonSizer | Creates a sizer with standard buttons.
CreateMessageDialog | Actually creates the GenericMessageDialog, just before showing it on screen.
CreateSeparatedButtonSizer | Creates a sizer with standard buttons using CreateButtonSizer separated
CreateStdDialogButtonSizer | Creates a StdDialogButtonSizer with standard buttons.
EndDialog | Ends the GenericMessageDialog life. This will be done differently depending on
GetCaption | Returns the main caption (the title) for GenericMessageDialog.
GetCustomCancelBitmap | If a custom icon been used for the Cancel button, this method will return
GetCustomCancelLabel | If a custom label has been used for the Cancel button, this method will return
GetCustomHelpBitmap | If a custom icon has been used for the Help button, this method will return
GetCustomHelpLabel | If a custom label has been used for the Help button, this method will return
GetCustomNoBitmap | If a custom icon has been used for the No button, this method will return
GetCustomNoLabel | If a custom label has been used for the No button, this method will return
GetCustomOKBitmap | If a custom icon has been used for the OK button, this method will return
GetCustomOKLabel | If a custom label has been used for the OK button, this method will return
GetCustomYesBitmap | If a custom icon has been used for the Yes button, this method will return
GetCustomYesLabel | If a custom label has been used for the Yes button, this method will return
GetDefaultCancelBitmap | Returns the default icon for the Cancel button.
GetDefaultCancelLabel | Returns the default label for the Cancel button.
GetDefaultHelpBitmap | Returns the default icon for the Help button.
GetDefaultHelpLabel | Returns the default label for the Help button.
GetDefaultNoBitmap | Returns the default icon for the No button.
GetDefaultNoLabel | Returns the default label for the No button.
GetDefaultOKBitmap | Returns the default icon for the OK button.
GetDefaultOKLabel | Returns the default label for the OK button.
GetDefaultYesBitmap | Returns the default icon for the Yes button.
GetDefaultYesLabel | Returns the default label for the Yes button.
GetExtendedMessage | Returns a string representing the extended GenericMessageDialog message.
GetFullMessage | Returns a string representing the combination of the main GenericMessageDialog
GetMessage | Returns a string representing the main GenericMessageDialog message.
GetMessageDialogStyle | Returns the AGW-specific window style for GenericMessageDialog.
HasCustomBitmaps | Returns True if any of the buttons have a non-default icons.
HasCustomLabels | Returns True if any of the buttons have a non-default label.
OnCancel | GenericMessageDialog had received a wx.ID_CANCEL answer.
OnHelp | GenericMessageDialog had received a wx.ID_HELP answer.
OnKeyDown | Handles the wx.EVT_KEY_DOWN event for GenericMessageDialog.
OnNavigation | Handles the wx.EVT_NAVIGATION_KEY event for GenericMessageDialog.
OnNo | GenericMessageDialog had received a wx.ID_NO answer.
OnOk | GenericMessageDialog had received a wx.ID_OK answer.
OnYes | GenericMessageDialog had received a wx.ID_YES answer.
SetExtendedMessage | Sets the extended message for the dialog: this message is usually an extension of the
SetHelpBitmap | Overrides the default icon of the Help button.
SetHelpLabel | Overrides the default label of the Help button.
SetMessage | Sets the message shown by the dialog.
SetOKBitmap | Overrides the default icon of the OK button.
SetOKCancelBitmaps | Overrides the default icons of the OK and Cancel buttons.
SetOKCancelLabels | Overrides the default labels of the OK and Cancel buttons.
SetOKLabel | Overrides the default label of the OK button.
SetYesNoBitmaps | Overrides the default icons of the Yes and No buttons.
SetYesNoCancelBitmaps | Overrides the default icons of the Yes and No buttons.
SetYesNoCancelLabels | Overrides the default labels of the Yes and No buttons.
SetYesNoLabels | Overrides the default labels of the Yes and No buttons.
ShowModal | Shows the dialog, returning one of wx.ID_OK, wx.ID_CANCEL, wx.ID_YES,
SwitchFocus | Switch focus between buttons.
WrapMessage | Wraps the input message to multi lines so that the resulting new message is at most wrap pixels wide.

API Class API

class GenericMessageDialog(wx.Dialog) [source]

Main class implementation, GenericMessageDialog is a possible replacement for the standard wx.MessageDialog.

__init__(parent, message, caption, agwStyle, pos=wx.DefaultPosition, size=wx.DefaultSize, style=wx.DEFAULT_DIALOG_STYLE|wx.WANTS_CHARS, wrap=-1) [source]

Default class constructor. Use ShowModal to show the dialog.

Parameters:
  • parent – the GenericMessageDialog parent (if any);
  • message – the message in the main body of the dialog;
  • caption – the dialog title;
  • agwStyle – the AGW-specific dialog style; it can be one of the following bits:

    Window Styles | Hex Value | Description
    0 | 0 | Uses normal generic buttons
    GMD_USE_AQUABUTTONS | 0x20 | Uses AquaButton buttons instead of generic buttons.
    GMD_USE_GRADIENTBUTTONS | 0x40 | Uses GradientButton buttons instead of generic buttons.

    The styles above are mutually exclusive. The style chosen above can be combined with a bitlist containing flags chosen from the following:

    Window Styles | Hex Value | Description
    wx.OK | 0x4 | Shows an OK button.
    wx.CANCEL | 0x10 | Shows a Cancel button.
    wx.YES_NO | 0xA | Show Yes and No buttons.
    wx.YES_DEFAULT | 0x0 | Used with wx.YES_NO, makes Yes button the default - which is the default behaviour.
    wx.NO_DEFAULT | 0x80 | Used with wx.YES_NO, makes No button the default.
    wx.ICON_EXCLAMATION | 0x100 | Shows an exclamation mark icon.
    wx.ICON_HAND | 0x200 | Shows an error icon.
    wx.ICON_ERROR | 0x200 | Shows an error icon - the same as wx.ICON_HAND.
    wx.ICON_QUESTION | 0x400 | Shows a question mark icon.
    wx.ICON_INFORMATION | 0x800 | Shows an information icon.
  • pos – the dialog position on screen;
  • size – the dialog size;
  • style – the underlying wx.Dialog style;
  • wrap – if set greater than zero, wraps the string in message so that every line is at most wrap pixels long.

Note

Notice that not all styles are compatible: only one of wx.OK and wx.YES_NO may be specified (and one of them must be specified) and at most one default button style can be used and it is only valid if the corresponding button is shown in the message box.

CreateButtonSizer(flags) [source]

Creates a sizer with standard buttons.

Parameters: flags – a bit list of the following flags:

Flags | Hex Value | Description
wx.YES | 0x2 | Show a Yes button
wx.OK | 0x4 | Show an OK button
wx.NO | 0x8 | Show a No button
wx.CANCEL | 0x10 | Show a Cancel button
wx.NO_DEFAULT | 0x80 | Used with wx.YES and wx.NO, makes No button the default
wx.HELP | 0x8000 | Show a Help button

Note

The sizer lays out the buttons in a manner appropriate to the platform.

CreateMessageDialog() [source]

Actually creates the GenericMessageDialog, just before showing it on screen.

CreateSeparatedButtonSizer(flags) [source]

Creates a sizer with standard buttons using CreateButtonSizer separated from the rest of the dialog contents by a horizontal wx.StaticLine.

Parameters: flags – the button sizer flags.

See also

CreateButtonSizer for a list of valid flags.

CreateStdDialogButtonSizer(flags) [source]

Creates a StdDialogButtonSizer with standard buttons.

Parameters: flags – the button sizer flags.

See also

CreateButtonSizer for a list of valid flags.

Note

The sizer lays out the buttons in a manner appropriate to the platform.

EndDialog(rc) [source]

Ends the GenericMessageDialog life. This will be done differently depending on the dialog modal/non-modal behaviour.

Parameters: rc – one of the wx.ID_YES, wx.ID_NO, wx.ID_OK, wx.ID_CANCEL constants.

Note

the rc parameter is unused if the dialog is not modal.

GetCaption() [source]

Returns the main caption (the title) for GenericMessageDialog.

New in version 0.9.3.

GetCustomCancelBitmap() [source]

If a custom icon been used for the Cancel button, this method will return it as an instance of wx.Bitmap. Otherwise, the default one (as defined in GetDefaultCancelBitmap) is returned.

New in version 0.9.3.

GetCustomCancelLabel() [source]

If a custom label has been used for the Cancel button, this method will return it as a string. Otherwise, the default one (as defined in GetDefaultCancelLabel) is returned.

New in version 0.9.3.

GetCustomHelpBitmap() [source]

If a custom icon has been used for the Help button, this method will return it as an instance of wx.Bitmap. Otherwise, the default one (as defined in GetDefaultHelpBitmap) is returned.

New in version 0.9.3.

GetCustomHelpLabel() [source]

If a custom label has been used for the Help button, this method will return it as a string. Otherwise, the default one (as defined in GetDefaultHelpLabel) is returned.

New in version 0.9.3.

GetCustomNoBitmap() [source]

If a custom icon has been used for the No button, this method will return it as an instance of wx.Bitmap. Otherwise, the default one (as defined in GetDefaultNoBitmap) is returned.

New in version 0.9.3.

GetCustomNoLabel() [source]

If a custom label has been used for the No button, this method will return it as a string. Otherwise, the default one (as defined in GetDefaultNoLabel) is returned.

New in version 0.9.3.

GetCustomOKBitmap() [source]

If a custom icon has been used for the OK button, this method will return it as an instance of wx.Bitmap. Otherwise, the default one (as defined in GetDefaultOKBitmap) is returned.

New in version 0.9.3.

GetCustomOKLabel() [source]

If a custom label has been used for the OK button, this method will return it as a string. Otherwise, the default one (as defined in GetDefaultOKLabel) is returned.

New in version 0.9.3.

GetCustomYesBitmap() [source]

If a custom icon has been used for the Yes button, this method will return it as an instance of wx.Bitmap. Otherwise, the default one (as defined in GetDefaultYesBitmap) is returned.

New in version 0.9.3.

GetCustomYesLabel() [source]

If a custom label has been used for the Yes button, this method will return it as a string. Otherwise, the default one (as defined in GetDefaultYesLabel) is returned.

New in version 0.9.3.

GetDefaultCancelBitmap() [source]

Returns the default icon for the Cancel button.

Note

this method may be overridden to provide different defaults for the default button icons.

New in version 0.9.3.

GetDefaultCancelLabel() [source]

Returns the default label for the Cancel button.

Note

this method may be overridden to provide different defaults for the default button labels.

New in version 0.9.3.

GetDefaultHelpBitmap() [source]

Returns the default icon for the Help button.

Note

this method may be overridden to provide different defaults for the default button icons.

New in version 0.9.3.

GetDefaultHelpLabel() [source]

Returns the default label for the Help button.

Note

this method may be overridden to provide different defaults for the default button labels.

New in version 0.9.3.

GetDefaultNoBitmap() [source]

Returns the default icon for the No button.

Note

this method may be overridden to provide different defaults for the default button icons.

New in version 0.9.3.

GetDefaultNoLabel() [source]

Returns the default label for the No button.

Note

this method may be overridden to provide different defaults for the default button labels.

New in version 0.9.3.

GetDefaultOKBitmap() [source]

Returns the default icon for the OK button.

Note

this method may be overridden to provide different defaults for the default button icons.

New in version 0.9.3.

GetDefaultOKLabel() [source]

Returns the default label for the OK button.

Note

this method may be overridden to provide different defaults for the default button labels.

New in version 0.9.3.

GetDefaultYesBitmap() [source]

Returns the default icon for the Yes button.

Note

this method may be overridden to provide different defaults for the default button icons.

New in version 0.9.3.

GetDefaultYesLabel() [source]

Returns the default label for the Yes button.

Note

this method may be overridden to provide different defaults for the default button labels.

New in version 0.9.3.

GetExtendedMessage() [source]

Returns a string representing the extended GenericMessageDialog message.

New in version 0.9.3.

GetFullMessage() [source]

Returns a string representing the combination of the main GenericMessageDialog message and the extended message, separated by an empty line.

New in version 0.9.3.

GetMessage() [source]

Returns a string representing the main GenericMessageDialog message.

New in version 0.9.3.

GetMessageDialogStyle() [source]

Returns the AGW-specific window style for GenericMessageDialog.

New in version 0.9.3.

HasCustomBitmaps() [source]

Returns True if any of the buttons have a non-default icons.

New in version 0.9.3.

HasCustomLabels() [source]

Returns True if any of the buttons have a non-default label.

New in version 0.9.3.

OnCancel(event) [source]

GenericMessageDialog had received a wx.ID_CANCEL answer.

OnHelp(event) [source]

GenericMessageDialog had received a wx.ID_HELP answer.

OnKeyDown(event) [source]

Handles the wx.EVT_KEY_DOWN event for GenericMessageDialog.

Parameters: event – a wx.KeyEvent event to be processed.

OnNavigation(event) [source]

Handles the wx.EVT_NAVIGATION_KEY event for GenericMessageDialog.

Parameters: event – a wx.NavigationKeyEvent event to be processed.

OnNo(event) [source]

GenericMessageDialog had received a wx.ID_NO answer.

OnOk(event) [source]

GenericMessageDialog had received a wx.ID_OK answer.

OnYes(event) [source]

GenericMessageDialog had received a wx.ID_YES answer.

SetExtendedMessage(extendedMessage) [source]

Sets the extended message for the dialog: this message is usually an extension of the short message specified in the constructor or set with SetMessage.

If it is set, the main message appears highlighted and this message appears beneath it in normal font.

Parameters: extendedMessage – a string representing the extended GenericMessageDialog message.

New in version 0.9.3.

SetHelpBitmap(helpBitmap) [source]

Overrides the default icon of the Help button.

Parameters: helpBitmap – the new icon for the Help button, an instance of wx.Bitmap.

New in version 0.9.3.

SetHelpLabel(help) [source]

Overrides the default label of the Help button.

Parameters: help – the new label for the Help button.

See also

The remarks in the SetYesNoLabels documentation.

New in version 0.9.3.

SetMessage(message) [source]

Sets the message shown by the dialog.

Parameters: message – a string representing the main GenericMessageDialog message.

New in version 0.9.3.

SetOKBitmap(okBitmap) [source]

Overrides the default icon of the OK button.

Parameters: yesBitmap – the new icon for the OK button, an instance of wx.Bitmap;

New in version 0.9.3.

SetOKCancelBitmaps(okBitmap, cancelBitmap) [source]

Overrides the default icons of the OK and Cancel buttons.

Parameters:
  • okBitmap – the new icon for the OK button, an instance of wx.Bitmap;

  • cancelBitmap – the new icon for the Cancel button, an instance of wx.Bitmap.

New in version 0.9.3.

SetOKCancelLabels(ok, cancel) [source]

Overrides the default labels of the OK and Cancel buttons.

Parameters:
  • ok – the new label for the OK button;
  • cancel – the new label for the Cancel button.

See also

The remarks in the SetYesNoLabels documentation.

New in version 0.9.3.

SetOKLabel(ok) [source]

Overrides the default label of the OK button.

Parameters: ok – the new label for the OK button.

See also

The remarks in the SetYesNoLabels documentation.

New in version 0.9.3.

SetYesNoBitmaps(yesBitmap, noBitmap) [source]

Overrides the default icons of the Yes and No buttons.

Parameters:
  • yesBitmap – the new icon for the Yes button, an instance of wx.Bitmap;

  • noBitmap – the new icon for the No button, an instance of wx.Bitmap.

New in version 0.9.3.

SetYesNoCancelBitmaps(yesBitmap, noBitmap, cancelBitmap) [source]

Overrides the default icons of the Yes and No buttons.

Parameters:
  • yesBitmap – the new icon for the Yes button, an instance of wx.Bitmap;

  • noBitmap – the new icon for the No button, an instance of wx.Bitmap;

  • cancelBitmap – the new icon for the Cancel button, an instance of wx.Bitmap.

New in version 0.9.3.

SetYesNoCancelLabels(yes, no, cancel) [source]

Overrides the default labels of the Yes and No buttons.

Parameters:
  • yes – the new label for the Yes button;
  • no – the new label for the No button;
  • cancel – the new label for the Cancel button.

See also

The remarks in the SetYesNoLabels documentation.

New in version 0.9.3.

SetYesNoLabels(yes, no) [source]

Overrides the default labels of the Yes and No buttons.

Parameters:
  • yes – the new label for the Yes button;
  • no – the new label for the No button.

Typically, if the function was used successfully, the main dialog message may need to be changed, e.g.:

main_message = "Hello world! I am the main message."

dlg = GenericMessageDialog(None, main_message, "A Nice Message Box",
                           agwStyle=wx.ICON_INFORMATION|wx.OK)

if dlg.SetYesNoLabels(_("&Quit"), _("&Don't quit")):
    dlg.SetMessage(_("What do you want to do?"))

else: # buttons have standard "Yes"/"No" values, so rephrase the question
    dlg.SetMessage(_("Do you really want to quit?"))

New in version 0.9.3.

ShowModal() [source]

Shows the dialog, returning one of wx.ID_OK, wx.ID_CANCEL, wx.ID_YES, wx.ID_NO or wx.ID_HELP.

Note

Notice that this method returns the identifier of the button which was clicked unlike the wx.MessageBox() function.

Note

Reimplemented from wx.Dialog.

SwitchFocus() [source]

Switch focus between buttons.

WrapMessage(message, wrap, font=None) [source]

Wraps the input message to multi lines so that the resulting new message is at most wrap pixels wide.

Parameters:
  • message – the original input message;
  • wrap – wraps the string in message so that every line is at most wrap pixels long;
  • font – if not None, it should be an instance of wx.Font to be used to measure and then wrap the input message.
Returns:

a new message wrapped at maximum wrap pixels wide.

Todo

Estabilish if wrapping all messages by default is a better idea than provide a keyword parameter to GenericMessageDialog. A default maximum line width might be the wxMac one, at 360 pixels.

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • infobar
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • genericmessagedialog »
  • GenericMessageDialog


StdDialogButtonSizer

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • genericmessagedialog »
  • StdDialogButtonSizer

StdDialogButtonSizer

wxWidgets standard dialog button sizer.

hierarchy Inheritance Diagram

Inheritance diagram for: StdDialogButtonSizer

Inheritance diagram of StdDialogButtonSizer

Methods Summary

__init__ | Default class constructor.
AddButton | Add a button to the sizer.
Realize | Realizes the sizer depending on the platform.
SetAffirmativeButton | Sets the affirmative button.
SetCancelButton | Sets the cancel button.
SetNegativeButton | Sets the negative button.

API Class API

class StdDialogButtonSizer(wx.BoxSizer) [source]

wxWidgets standard dialog button sizer.

__init__() [source]

Default class constructor.

AddButton(mybutton) [source]

Add a button to the sizer.

Parameters: mybutton – the button to add.

Realize() [source]

Realizes the sizer depending on the platform.

SetAffirmativeButton(button) [source]

Sets the affirmative button.

Parameters: button – the button to set as affirmative one.

SetCancelButton(button) [source]

Sets the cancel button.

Parameters: button – the button to set as cancel one.

SetNegativeButton(button) [source]

Sets the negative button.

Parameters: button – the button to set as negative one.

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • infobar
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • genericmessagedialog »
  • StdDialogButtonSizer


SVN Revision 68346 For genericmessagedialog

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • genericmessagedialog »
  • SVN Revision 68346 For genericmessagedialog

svn SVN Revision 68346 For genericmessagedialog

This file contains the SVN revision history for genericmessagedialog, at revision 68346.

Available information include commit date, the name of the committer, the file size, the SVN log messages and a diff from the previous version (if available).

File Information

  • Commit Date: 29-May-2009 08:06:58 UTC
  • Committer: AG
  • File Size: 42199 byte(s)

Log Messages

The following log message was entered by the committer:

Adjusted GenericMessageDialog to handle modal and non-modal situations

Diff To Previous Version (65529)

Version SVN diff:

--- wxPython/3rdParty/AGW/agw/genericmessagedialog.py       2010/09/12 11:58:40     65529
+++ wxPython/3rdParty/AGW/agw/genericmessagedialog.py       2011/07/23 22:40:01     68346
@@ -2,7 +2,7 @@
# GENERICMESSAGEDIALOG wxPython IMPLEMENTATION
#
# Andrea Gavana, @ 07 October 2008
-# Latest Revision: 12 Sep 2010, 10.00 GMT
+# Latest Revision: 22 Jul 2011, 21.00 GMT
#
#
# TODO List
@@ -76,9 +76,9 @@

GenericMessageDialog is distributed under the wxPython license.

-Latest Revision: Andrea Gavana @ 12 Sep 2010, 10.00 GMT
+Latest Revision: Andrea Gavana @ 22 Jul 2011, 21.00 GMT

-Version 0.5
+Version 0.6

"""

@@ -652,23 +652,39 @@
self.Bind(wx.EVT_NAVIGATION_KEY, self.OnNavigation)
self.SwitchFocus()

+
+    def EndDialog(self, rc):
+        """
+        Ends the L{GenericMessageDialog} life. This will be done differently depending on
+        the dialog modal/non-modal behaviour.
+
+        :param `rc`: one of the ``wx.ID_YES``, ``wx.ID_NO``, ``wx.ID_OK``, ``wx.ID_CANCEL`` constants.
+
+        :note: the `rc` parameter is unused if the dialog is not modal.
+        """
+
+        if self.IsModal():
+            self.EndModal(rc)
+        else:
+            self.Hide()
+

def OnYes(self, event):
""" L{GenericMessageDialog} had received a ``wx.ID_YES`` answer. """

-        self.EndModal(wx.ID_YES)
+        self.EndDialog(wx.ID_YES)

def OnOk(self, event):
""" L{GenericMessageDialog} had received a ``wx.ID_OK`` answer. """

-        self.EndModal(wx.ID_OK)
+        self.EndDialog(wx.ID_OK)

def OnNo(self, event):
""" L{GenericMessageDialog} had received a ``wx.ID_NO`` answer. """

-        self.EndModal(wx.ID_NO)
+        self.EndDialog(wx.ID_NO)

def OnCancel(self, event):
@@ -678,7 +694,7 @@
# only YES and NO are specified.

if self._agwStyle & wx.YES_NO != wx.YES_NO or self._agwStyle & wx.CANCEL:
-            self.EndModal(wx.ID_CANCEL)
+            self.EndDialog(wx.ID_CANCEL)

def OnKeyDown(self, event):
@@ -729,7 +745,7 @@

button = wx.Window.FindFocus()
buttonId = button.GetId()
-        self.EndModal(buttonId)
+        self.EndDialog(buttonId)

def SwitchFocus(self):

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • genericmessagedialog »
  • SVN Revision 68346 For genericmessagedialog


SVN Revision 68881 For genericmessagedialog

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • genericmessagedialog »
  • SVN Revision 68881 For genericmessagedialog

svn SVN Revision 68881 For genericmessagedialog

This file contains the SVN revision history for genericmessagedialog, at revision 68881.

Available information include commit date, the name of the committer, the file size, the SVN log messages and a diff from the previous version (if available).

File Information

  • Commit Date: 17-Oct-2008 20:51:43 UTC
  • Committer: AG
  • File Size: 45393 byte(s)

Log Messages

The following log message was entered by the committer:

  • AGW: General overhaul of the documentation, much improved. All the widgets have their own sample usage in the docs as well;

  • FlatNotebook: Added the FNB_NAV_BUTTONS_WHEN_NEEDED style, which hides the navigation left/right arrows if all tabs fit;

  • RibbonBar: - Added the EVT_RIBBONBAR_TAB_LEFT_DCLICK event, which generates a special event

    when a ribbon bar tab is double-clicked;

    • Added support for toggle buttons;
    • Improved support for ribbon panel sizers: panels with sizers should now automatically minimise at small sizes, and behave properly when popping up from a minimised state;
    • Added tooltips via SetToolTip for those buttons which have the help_string attribute set.

  • XLSGrid: a new widget was added to AGW, termed XLSGrid. It’s based on wx.grid.Grid and can be used to faithfully reproduce the appearance of a Microsoft Excel spreadsheets.

Diff To Previous Version (68362)

Version SVN diff:

--- wxPython/3rdParty/AGW/agw/genericmessagedialog.py       2011/07/24 21:36:47     68362
+++ wxPython/3rdParty/AGW/agw/genericmessagedialog.py       2011/08/25 16:40:17     68881
@@ -2,7 +2,7 @@
# GENERICMESSAGEDIALOG wxPython IMPLEMENTATION
#
# Andrea Gavana, @ 07 October 2008
-# Latest Revision: 22 Jul 2011, 21.00 GMT
+# Latest Revision: 17 Aug 2011, 15.00 GMT
#
#
# TODO List
@@ -45,10 +45,33 @@
And a lot more. Check the demo for an almost complete review of the functionalities.

+Usage
+=====
+
+Usage example::
+
+    import wx
+    import wx.lib.agw.genericmessagedialog as GMD
+
+    # Our normal wxApp-derived class, as usual
+    app = wx.App(0)
+
+    main_message = "Hello world! I am the main message."
+
+    dlg = GMD.GenericMessageDialog(None, main_message, "A Nice Message Box",
+                                   agwStyle=wx.ICON_INFORMATION|wx.OK)
+
+    dlg.ShowModal()
+    dlg.Destroy()
+
+    app.MainLoop()
+
+
+
Supported Platforms
===================

-GenericMessageDialog has been tested on the following platforms:
+L{GenericMessageDialog} has been tested on the following platforms:
* Windows (Windows XP).

@@ -64,6 +87,24 @@
``GMD_USE_GRADIENTBUTTONS``        0x40 Uses `wx.lib.agw.gradientbutton` buttons instead of generic buttons.
=========================== =========== ==================================================

+The styles above are mutually exclusive. The style chosen above can be combined with a
+bitlist containing flags chosen from the following:
+
+=========================== =========== ==================================================
+Window Styles               Hex Value   Description
+=========================== =========== ==================================================
+``wx.OK``                           0x4 Shows an ``OK`` button.
+``wx.CANCEL``                      0x10 Shows a ``Cancel`` button.
+``wx.YES_NO``                       0xA Show ``Yes`` and ``No`` buttons.
+``wx.YES_DEFAULT``                  0x0 Used with ``wx.YES_NO``, makes ``Yes`` button the default - which is the default behaviour.
+``wx.NO_DEFAULT``                  0x80 Used with ``wx.YES_NO``, makes ``No`` button the default.
+``wx.ICON_EXCLAMATION``           0x100 Shows an exclamation mark icon.
+``wx.ICON_HAND``                  0x200 Shows an error icon.
+``wx.ICON_ERROR``                 0x200 Shows an error icon - the same as ``wx.ICON_HAND``.
+``wx.ICON_QUESTION``              0x400 Shows a question mark icon.
+``wx.ICON_INFORMATION``           0x800 Shows an information icon.
+=========================== =========== ==================================================
+

Events Processing
=================
@@ -74,9 +115,9 @@
License And Version
===================

-GenericMessageDialog is distributed under the wxPython license.
+L{GenericMessageDialog} is distributed under the wxPython license.

-Latest Revision: Andrea Gavana @ 22 Jul 2011, 21.00 GMT
+Latest Revision: Andrea Gavana @ 17 Aug 2011, 15.00 GMT

Version 0.6

@@ -576,6 +617,24 @@
``GMD_USE_GRADIENTBUTTONS``        0x40 Uses L{GradientButton} buttons instead of generic buttons.
=========================== =========== ==================================================

+         The styles above are mutually exclusive. The style chosen above can be combined with a
+         bitlist containing flags chosen from the following:
+
+         =========================== =========== ==================================================
+         Window Styles               Hex Value   Description
+         =========================== =========== ==================================================
+         ``wx.OK``                           0x4 Shows an ``OK`` button.
+         ``wx.CANCEL``                      0x10 Shows a ``Cancel`` button.
+         ``wx.YES_NO``                       0xA Show ``Yes`` and ``No`` buttons.
+         ``wx.YES_DEFAULT``                  0x0 Used with ``wx.YES_NO``, makes ``Yes`` button the default - which is the default behaviour.
+         ``wx.NO_DEFAULT``                  0x80 Used with ``wx.YES_NO``, makes ``No`` button the default.
+         ``wx.ICON_EXCLAMATION``           0x100 Shows an exclamation mark icon.
+         ``wx.ICON_HAND``                  0x200 Shows an error icon.
+         ``wx.ICON_ERROR``                 0x200 Shows an error icon - the same as ``wx.ICON_HAND``.
+         ``wx.ICON_QUESTION``              0x400 Shows a question mark icon.
+         ``wx.ICON_INFORMATION``           0x800 Shows an information icon.
+         =========================== =========== ==================================================
+
:param `pos`: the dialog position on screen;
:param `size`: the dialog size;
:param `style`: the underlying `wx.Dialog` style;

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • genericmessagedialog »
  • SVN Revision 68881 For genericmessagedialog


SVN Revision 70819 For genericmessagedialog

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • genericmessagedialog »
  • SVN Revision 70819 For genericmessagedialog

svn SVN Revision 70819 For genericmessagedialog

This file contains the SVN revision history for genericmessagedialog, at revision 70819.

Available information include commit date, the name of the committer, the file size, the SVN log messages and a diff from the previous version (if available).

File Information

  • Commit Date: 17-Oct-2008 19:15:31 UTC
  • Committer: AG
  • File Size: 63503 byte(s)

Log Messages

The following log message was entered by the committer:

  • Added the new widget ShortcutEditor.
  • GenericMessageDialog:
    • Added the possibility to have custom labels for the buttons;
    • Added the possibility to have custom icons for the buttons.
  • CustomTreeCtrl:
    • Added the style TR_ELLIPSIZE_LONG_ITEMS, which ellipsizes long items when the horizontal space for CustomTreeCtrl is low;
    • Added the style TR_TOOLTIP_ON_LONG_ITEMS which shows tooltips on long items when the horizontal space for CustomTreeCtrl is low.
  • HyperTreeList:
    • Added the style TR_ELLIPSIZE_LONG_ITEMS, which ellipsizes long items when the horizontal space for HyperTreeList is low.

Diff To Previous Version (68881)

Version SVN diff:

--- wxPython/3rdParty/AGW/agw/genericmessagedialog.py       2011/08/25 16:40:17     68881
+++ wxPython/3rdParty/AGW/agw/genericmessagedialog.py       2012/03/05 20:59:35     70819
@@ -2,7 +2,7 @@
# GENERICMESSAGEDIALOG wxPython IMPLEMENTATION
#
# Andrea Gavana, @ 07 October 2008
-# Latest Revision: 17 Aug 2011, 15.00 GMT
+# Latest Revision: 29 Feb 2012, 21.00 GMT
#
#
# TODO List
@@ -30,11 +30,14 @@
===========

This class represents a dialog that shows a single or multi-line message,
-with a choice of ``OK``, ``Yes``, ``No`` and ``Cancel`` buttons. It is a possible
+with a choice of ``OK``, ``Yes``, ``No``, ``Cancel`` and ``Help`` buttons. It is a possible
replacement for the standard `wx.MessageDialog`, with these extra functionalities:

* Possibility to modify the dialog position;
* Custom themed generic bitmap & text buttons;
+* Support for normal and extended message (in different fonts);
+* Custom labels for the ``OK``, ``Yes``, ``No``, ``Cancel`` and ``Help`` buttons;
+* Custom icons for the ``OK``, ``Yes``, ``No``, ``Cancel`` and ``Help`` buttons;
* Possibility to set an icon to the dialog;
* More visibility to the button getting the focus;
* Support for Aqua buttons or Gradient buttons instead of themed ones (see L{AquaButton}
@@ -117,9 +120,9 @@

L{GenericMessageDialog} is distributed under the wxPython license.

-Latest Revision: Andrea Gavana @ 17 Aug 2011, 15.00 GMT
+Latest Revision: Andrea Gavana @ 29 Feb 2012, 21.00 GMT

-Version 0.6
+Version 0.7

"""

@@ -601,7 +604,7 @@
style=wx.DEFAULT_DIALOG_STYLE|wx.WANTS_CHARS,
wrap=-1):
"""
-        Default class constructor.
+        Default class constructor. Use L{ShowModal} to show the dialog.

:param `parent`: the L{GenericMessageDialog} parent (if any);
:param `message`: the message in the main body of the dialog;
@@ -640,15 +643,37 @@
:param `style`: the underlying `wx.Dialog` style;
:param `wrap`: if set greater than zero, wraps the string in `message` so that
every line is at most `wrap` pixels long.
+
+        :note: Notice that not all styles are compatible: only one of ``wx.OK`` and ``wx.YES_NO`` may be
+         specified (and one of them must be specified) and at most one default button style can be used
+         and it is only valid if the corresponding button is shown in the message box.
"""

wx.Dialog.__init__(self, parent, wx.ID_ANY, caption, pos, size, style)

+        self._message = message
self._agwStyle = agwStyle
+        self._wrap = wrap
+
+        # The extended message placeholder
+        self._extendedMessage = ''
+
+        # Labels for the buttons, initially empty meaning that the defaults should
+        # be used, use GetYes/No/OK/CancelLabel() to access them
+        self._yes = self._no = self._ok = self._cancel = self._help = ''
+
+        # Icons for the buttons, initially empty meaning that the defaults should
+        # be used, use GetYes/No/OK/CancelBitmap() to access them
+        self._yesBitmap = self._noBitmap = self._okBitmap = self._cancelBitmap = self._helpBitmap = None
+
+        self._created = False
+

-        if wrap > 0:
-            message = self.WrapMessage(message, wrap)
+    def CreateMessageDialog(self):
+        """ Actually creates the L{GenericMessageDialog}, just before showing it on screen. """

+        message = self.GetMessage()
+
topsizer = wx.BoxSizer(wx.VERTICAL)
icon_text = wx.BoxSizer(wx.HORIZONTAL)

@@ -669,8 +694,36 @@
# Populate the sizers...
icon = wx.StaticBitmap(self, -1, bitmap.GetBitmap())
icon_text.Add(icon, 0, wx.ALIGN_CENTER_HORIZONTAL)
-        icon_text.Add(self.CreateTextSizer(message), 1, wx.ALIGN_CENTER | wx.LEFT, 10)
+
+        textsizer = wx.BoxSizer(wx.VERTICAL)
+
+        # We want to show the main message in a different font to make it stand
+        # out if the extended message is used as well. This looks better and is
+        # more consistent with the native dialogs under MSW and GTK.
+
+        if self._extendedMessage.strip():
+            boldFont = self.GetFont().Larger().MakeBold()
+            if self._wrap > 0:
+                message = self.WrapMessage(message, self._wrap, boldFont)

+            msgSizer = self.CreateTextSizer(message)
+
+            for index in xrange(len(msgSizer.GetChildren())):
+                msgSizer.GetItem(index).GetWindow().SetFont(boldFont)
+
+            textsizer.AddF(msgSizer, wx.SizerFlags().Border(wx.BOTTOM, 20))
+            lowerMessage = self.GetExtendedMessage()
+
+        else: # no extended message
+
+            lowerMessage = message
+
+        if self._wrap > 0:
+            lowerMessage = self.WrapMessage(lowerMessage, self._wrap)
+
+        textsizer.Add(self.CreateTextSizer(lowerMessage))
+
+        icon_text.Add(textsizer, 1, wx.ALIGN_CENTER | wx.LEFT, 10)
topsizer.Add(icon_text, 1, wx.EXPAND | wx.LEFT | wx.RIGHT | wx.TOP, 10)

center_flag = wx.EXPAND
@@ -699,6 +752,7 @@
self.Bind(wx.EVT_BUTTON, self.OnOk, id=wx.ID_OK)
self.Bind(wx.EVT_BUTTON, self.OnNo, id=wx.ID_NO)
self.Bind(wx.EVT_BUTTON, self.OnCancel, id=wx.ID_CANCEL)
+        self.Bind(wx.EVT_BUTTON, self.OnHelp, id=wx.ID_HELP)

for child in self.GetChildren():
if isinstance(child, wx.lib.buttons.ThemedGenBitmapTextButton) or \
@@ -709,7 +763,7 @@
child.SetUseFocusIndicator(False)

self.Bind(wx.EVT_NAVIGATION_KEY, self.OnNavigation)
-        self.SwitchFocus()
+        self.SwitchFocus()

def EndDialog(self, rc):
@@ -756,6 +810,12 @@
self.EndDialog(wx.ID_CANCEL)

+    def OnHelp(self, event):
+        """ L{GenericMessageDialog} had received a ``wx.ID_HELP`` answer. """
+
+        self.EndDialog(wx.ID_HELP)
+
+
def OnKeyDown(self, event):
"""
Handles the ``wx.EVT_KEY_DOWN`` event for L{GenericMessageDialog}.
@@ -781,6 +841,8 @@
self.OnCancel(None)
elif key in [ord("o"), ord("O")] and wx.ID_OK in ids:
self.OnOk(None)
+        elif key in [ord("h"), ord("H")] and wx.ID_HELP in ids:
+            self.OnHelp(None)

event.Skip()

@@ -892,33 +954,31 @@
# Remove unwanted flags...
flags &= ~(wx.YES | wx.NO | wx.NO_DEFAULT)

-        size=(-1, 28)
if self._agwStyle & GMD_USE_AQUABUTTONS:
klass = AB.AquaButton
-            size=(-1, -1)
elif self._agwStyle & GMD_USE_GRADIENTBUTTONS:
klass = GB.GradientButton
else:
klass = buttons.ThemedGenBitmapTextButton

if flags & wx.OK:
-            ok = klass(self, wx.ID_OK, _ok.GetBitmap(), _("OK"), size=size)
+            ok = klass(self, wx.ID_OK, self.GetCustomOKBitmap(), self.GetCustomOKLabel())
sizer.AddButton(ok)

if flags & wx.CANCEL:
-            cancel = klass(self, wx.ID_CANCEL, _cancel.GetBitmap(), _("Cancel"), size=size)
+            cancel = klass(self, wx.ID_CANCEL, self.GetCustomCancelBitmap(), self.GetCustomCancelLabel())
sizer.AddButton(cancel)

if flags & wx.YES:
-            yes = klass(self, wx.ID_YES, _yes.GetBitmap(), _("Yes"), size=size)
+            yes = klass(self, wx.ID_YES, self.GetCustomYesBitmap(), self.GetCustomYesLabel())
sizer.AddButton(yes)

if flags & wx.NO:
-            no = klass(self, wx.ID_NO, _no.GetBitmap(), _("No"), size=size)
+            no = klass(self, wx.ID_NO, self.GetCustomNoBitmap(), self.GetCustomNoLabel())
sizer.AddButton(no)

if flags & wx.HELP:
-            help = klass(self, wx.ID_HELP, _help.GetBitmap(), _("Help"), size=size)
+            help = klass(self, wx.ID_HELP, self.GetCustomHelpBitmap(), self.GetCustomHelpLabel())
sizer.AddButton(help)

if flags & wx.NO_DEFAULT:
@@ -943,14 +1003,459 @@
return sizer

-    def WrapMessage(self, message, wrap):
+    def GetDefaultYesLabel(self):
+        """
+        Returns the default label for the ``Yes`` button.
+
+        :note: this method may be overridden to provide different defaults for the
+         default button labels.
+
+        .. versionadded:: 0.9.3
+        """
+
+        return _("Yes")
+
+
+    def GetDefaultNoLabel(self):
+        """
+        Returns the default label for the ``No`` button.
+
+        :note: this method may be overridden to provide different defaults for the
+         default button labels.
+
+        .. versionadded:: 0.9.3
+        """
+
+        return _("No")
+
+
+    def GetDefaultOKLabel(self):
+        """
+        Returns the default label for the ``OK`` button.
+
+        :note: this method may be overridden to provide different defaults for the
+         default button labels.
+
+        .. versionadded:: 0.9.3
+        """
+
+        return _("OK")
+
+
+    def GetDefaultCancelLabel(self):
+        """
+        Returns the default label for the ``Cancel`` button.
+
+        :note: this method may be overridden to provide different defaults for the
+         default button labels.
+
+        .. versionadded:: 0.9.3
+        """
+
+        return _("Cancel")
+
+
+    def GetDefaultHelpLabel(self):
+        """
+        Returns the default label for the ``Help`` button.
+
+        :note: this method may be overridden to provide different defaults for the
+         default button labels.
+
+        .. versionadded:: 0.9.3
+        """
+
+        return _("Help")
+
+
+    def GetCustomOKLabel(self):
+        """
+        If a custom label has been used for the ``OK`` button, this method will return
+        it as a string. Otherwise, the default one (as defined in L{GetDefaultOKLabel})
+        is returned.
+
+        .. versionadded:: 0.9.3
+        """
+
+        return (self._ok and [self._ok] or [self.GetDefaultOKLabel()])[0]
+
+
+    def GetCustomYesLabel(self):
+        """
+        If a custom label has been used for the ``Yes`` button, this method will return
+        it as a string. Otherwise, the default one (as defined in L{GetDefaultYesLabel})
+        is returned.
+
+        .. versionadded:: 0.9.3
+        """
+
+        return (self._yes and [self._yes] or [self.GetDefaultYesLabel()])[0]
+
+
+    def GetCustomNoLabel(self):
+        """
+        If a custom label has been used for the ``No`` button, this method will return
+        it as a string. Otherwise, the default one (as defined in L{GetDefaultNoLabel})
+        is returned.
+
+        .. versionadded:: 0.9.3
+        """
+
+        return (self._no and [self._no] or [self.GetDefaultNoLabel()])[0]
+
+
+    def GetCustomCancelLabel(self):
+        """
+        If a custom label has been used for the ``Cancel`` button, this method will return
+        it as a string. Otherwise, the default one (as defined in L{GetDefaultCancelLabel})
+        is returned.
+
+        .. versionadded:: 0.9.3
+        """
+
+        return (self._cancel and [self._cancel] or [self.GetDefaultCancelLabel()])[0]
+
+
+    def GetCustomHelpLabel(self):
+        """
+        If a custom label has been used for the ``Help`` button, this method will return
+        it as a string. Otherwise, the default one (as defined in L{GetDefaultHelpLabel})
+        is returned.
+
+        .. versionadded:: 0.9.3
+        """
+
+        return (self._help and [self._help] or [self.GetDefaultHelpLabel()])[0]
+
+
+    # Customization of the message box buttons
+    def SetYesNoLabels(self, yes, no):
+        """
+        Overrides the default labels of the ``Yes`` and ``No`` buttons.
+
+        :param `yes`: the new label for the ``Yes`` button;
+        :param `no`: the new label for the ``No`` button.
+
+        Typically, if the function was used successfully, the main dialog message may need to be changed, e.g.::
+
+            main_message = "Hello world! I am the main message."
+
+            dlg = GenericMessageDialog(None, main_message, "A Nice Message Box",
+                                       agwStyle=wx.ICON_INFORMATION|wx.OK)
+
+            if dlg.SetYesNoLabels(_("&Quit"), _("&Don't quit")):
+                dlg.SetMessage(_("What do you want to do?"))
+
+            else: # buttons have standard "Yes"/"No" values, so rephrase the question
+                dlg.SetMessage(_("Do you really want to quit?"))
+
+
+        .. versionadded:: 0.9.3
+        """
+
+        self._yes, self._no = yes, no
+        return True
+
+
+    def SetYesNoCancelLabels(self, yes, no, cancel):
+        """
+        Overrides the default labels of the ``Yes`` and ``No`` buttons.
+
+        :param `yes`: the new label for the ``Yes`` button;
+        :param `no`: the new label for the ``No`` button;
+        :param `cancel`: the new label for the ``Cancel`` button.
+
+        :see: The remarks in the L{SetYesNoLabels} documentation.
+
+        .. versionadded:: 0.9.3
+        """
+
+        self._yes, self._no, self._cancel = yes, no, cancel
+        return True
+
+
+    def SetOKLabel(self, ok):
+        """
+        Overrides the default label of the ``OK`` button.
+
+        :param `ok`: the new label for the ``OK`` button.
+
+        :see: The remarks in the L{SetYesNoLabels} documentation.
+
+        .. versionadded:: 0.9.3
+        """
+
+        self._ok = ok
+        return True
+
+
+    def SetOKCancelLabels(self, ok, cancel):
+        """
+        Overrides the default labels of the ``OK`` and ``Cancel`` buttons.
+
+        :param `ok`: the new label for the ``OK`` button;
+        :param `cancel`: the new label for the ``Cancel`` button.
+
+        :see: The remarks in the L{SetYesNoLabels} documentation.
+
+        .. versionadded:: 0.9.3
+        """
+
+        self._ok, self._cancel = ok, cancel
+        return True
+
+
+    def SetHelpLabel(self, help):
+        """
+        Overrides the default label of the ``Help`` button.
+
+        :param `help`: the new label for the ``Help`` button.
+
+        :see: The remarks in the L{SetYesNoLabels} documentation.
+
+        .. versionadded:: 0.9.3
+        """
+
+        self._help = help
+        return True
+
+
+    # Test if any custom labels were set
+    def HasCustomLabels(self):
+        """
+        Returns ``True`` if any of the buttons have a non-default label.
+
+        .. versionadded:: 0.9.3
+        """
+
+        for label in [self._ok, self._no, self._yes, self._cancel, self._help]:
+            if label.strip():
+                return True
+
+        return False
+
+
+    def GetDefaultYesBitmap(self):
+        """
+        Returns the default icon for the ``Yes`` button.
+
+        :note: this method may be overridden to provide different defaults for the
+         default button icons.
+
+        .. versionadded:: 0.9.3
+        """
+
+        return _yes.GetBitmap()
+
+
+    def GetDefaultNoBitmap(self):
+        """
+        Returns the default icon for the ``No`` button.
+
+        :note: this method may be overridden to provide different defaults for the
+         default button icons.
+
+        .. versionadded:: 0.9.3
+        """
+
+        return _no.GetBitmap()
+
+
+    def GetDefaultOKBitmap(self):
+        """
+        Returns the default icon for the ``OK`` button.
+
+        :note: this method may be overridden to provide different defaults for the
+         default button icons.
+
+        .. versionadded:: 0.9.3
+        """
+
+        return _ok.GetBitmap()
+
+
+    def GetDefaultCancelBitmap(self):
+        """
+        Returns the default icon for the ``Cancel`` button.
+
+        :note: this method may be overridden to provide different defaults for the
+         default button icons.
+
+        .. versionadded:: 0.9.3
+        """
+
+        return _cancel.GetBitmap()
+
+
+    def GetDefaultHelpBitmap(self):
+        """
+        Returns the default icon for the ``Help`` button.
+
+        :note: this method may be overridden to provide different defaults for the
+         default button icons.
+
+        .. versionadded:: 0.9.3
+        """
+
+        return _help.GetBitmap()
+
+
+    def GetCustomOKBitmap(self):
+        """
+        If a custom icon has been used for the ``OK`` button, this method will return
+        it as an instance of `wx.Bitmap`. Otherwise, the default one (as defined in
+        L{GetDefaultOKBitmap}) is returned.
+
+        .. versionadded:: 0.9.3
+        """
+
+        return (self._okBitmap and [self._okBitmap] or [self.GetDefaultOKBitmap()])[0]
+
+
+    def GetCustomYesBitmap(self):
+        """
+        If a custom icon has been used for the ``Yes`` button, this method will return
+        it as an instance of `wx.Bitmap`. Otherwise, the default one (as defined in
+        L{GetDefaultYesBitmap}) is returned.
+
+        .. versionadded:: 0.9.3
+        """
+
+        return (self._yesBitmap and [self._yesBitmap] or [self.GetDefaultYesBitmap()])[0]
+
+
+    def GetCustomNoBitmap(self):
+        """
+        If a custom icon has been used for the ``No`` button, this method will return
+        it as an instance of `wx.Bitmap`. Otherwise, the default one (as defined in
+        L{GetDefaultNoBitmap}) is returned.
+
+        .. versionadded:: 0.9.3
+        """
+
+        return (self._noBitmap and [self._noBitmap] or [self.GetDefaultNoBitmap()])[0]
+
+
+    def GetCustomCancelBitmap(self):
+        """
+        If a custom icon been used for the ``Cancel`` button, this method will return
+        it as an instance of `wx.Bitmap`. Otherwise, the default one (as defined in
+        L{GetDefaultCancelBitmap}) is returned.
+
+        .. versionadded:: 0.9.3
+        """
+
+        return (self._cancelBitmap and [self._cancelBitmap] or [self.GetDefaultCancelBitmap()])[0]
+
+
+    def GetCustomHelpBitmap(self):
+        """
+        If a custom icon has been used for the ``Help`` button, this method will return
+        it as an instance of `wx.Bitmap`. Otherwise, the default one (as defined in
+        L{GetDefaultHelpBitmap}) is returned.
+
+        .. versionadded:: 0.9.3
+        """
+
+        return (self._helpBitmap and [self._helpBitmap] or [self.GetDefaultHelpBitmap()])[0]
+
+
+    # Customization of the message box buttons icons
+    def SetYesNoBitmaps(self, yesBitmap, noBitmap):
+        """
+        Overrides the default icons of the ``Yes`` and ``No`` buttons.
+
+        :param `yesBitmap`: the new icon for the ``Yes`` button, an instance of `wx.Bitmap`;
+        :param `noBitmap`: the new icon for the ``No`` button, an instance of `wx.Bitmap`.
+
+        .. versionadded:: 0.9.3
+        """
+
+        self._yesBitmap, self._noBitmap = yesBitmap, noBitmap
+        return True
+
+
+    def SetYesNoCancelBitmaps(self, yesBitmap, noBitmap, cancelBitmap):
+        """
+        Overrides the default icons of the ``Yes`` and ``No`` buttons.
+
+        :param `yesBitmap`: the new icon for the ``Yes`` button, an instance of `wx.Bitmap`;
+        :param `noBitmap`: the new icon for the ``No`` button, an instance of `wx.Bitmap`;
+        :param `cancelBitmap`: the new icon for the ``Cancel`` button, an instance of `wx.Bitmap`.
+
+        .. versionadded:: 0.9.3
+        """
+
+        self._yesBitmap, self._noBitmap, self._cancelBitmap = yesBitmap, noBitmap, cancelBitmap
+        return True
+
+
+    def SetOKBitmap(self, okBitmap):
+        """
+        Overrides the default icon of the ``OK`` button.
+
+        :param `yesBitmap`: the new icon for the ``OK`` button, an instance of `wx.Bitmap`;
+
+        .. versionadded:: 0.9.3
+        """
+
+        self._okBitmap = okBitmap
+        return True
+
+
+    def SetOKCancelBitmaps(self, okBitmap, cancelBitmap):
+        """
+        Overrides the default icons of the ``OK`` and ``Cancel`` buttons.
+
+        :param `okBitmap`: the new icon for the ``OK`` button, an instance of `wx.Bitmap`;
+        :param `cancelBitmap`: the new icon for the ``Cancel`` button, an instance of `wx.Bitmap`.
+
+        .. versionadded:: 0.9.3
+        """
+
+        self._okBitmap, self._cancelBitmap = okBitmap, cancelBitmap
+        return True
+
+
+    def SetHelpBitmap(self, helpBitmap):
+        """
+        Overrides the default icon of the ``Help`` button.
+
+        :param `helpBitmap`: the new icon for the ``Help`` button, an instance of `wx.Bitmap`.
+
+        .. versionadded:: 0.9.3
+        """
+
+        self._helpBitmap = helpBitmap
+        return True
+
+
+    # Test if any custom icons were set
+    def HasCustomBitmaps(self):
+        """
+        Returns ``True`` if any of the buttons have a non-default icons.
+
+        .. versionadded:: 0.9.3
+        """
+
+        for icon in [self._okBitmap, self._noBitmap, self._yesBitmap,
+                     self._cancelBitmap, self._helpBitmap]:
+            if icon is not None:
+                return True
+
+        return False
+
+
+    def WrapMessage(self, message, wrap, font=None):
"""
Wraps the input message to multi lines so that the resulting new message
is at most `wrap` pixels wide.

:param `message`: the original input message;
:param `wrap`: wraps the string in `message` so that every line is at most
-         `wrap` pixels long.
+         `wrap` pixels long;
+        :param `font`: if not ``None``, it should be an instance of `wx.Font` to be
+         used to measure and then wrap the input `message`.

:return: a new message wrapped at maximum `wrap` pixels wide.

@@ -960,8 +1465,115 @@
"""

dc = wx.ClientDC(self)
-        dc.SetFont(self.GetFont())
+
+        if font is None:
+            dc.SetFont(self.GetFont())
+        else:
+            dc.SetFont(font)

newMessage = wordwrap.wordwrap(message, wrap, dc, False)
return newMessage
+
+
+    def ShowModal(self):
+        """
+        Shows the dialog, returning one of ``wx.ID_OK``, ``wx.ID_CANCEL``, ``wx.ID_YES``,
+        ``wx.ID_NO`` or ``wx.ID_HELP``.
+
+        :note: Notice that this method returns the identifier of the button which was
+         clicked unlike the `wx.MessageBox()` function.
+
+        :note: Reimplemented from `wx.Dialog`.
+        """
+
+        if not self._created:
+
+            self._created = True
+            self.CreateMessageDialog()
+
+        return wx.Dialog.ShowModal(self)
+
+
+    def GetCaption(self):
+        """
+        Returns the main caption (the title) for L{GenericMessageDialog}.
+
+        .. versionadded:: 0.9.3
+        """
+
+        return self.GetTitle()
+
+
+    def SetMessage(self, message):
+        """
+        Sets the message shown by the dialog.
+
+        :param `message`: a string representing the main L{GenericMessageDialog} message.
+
+        .. versionadded:: 0.9.3
+        """
+
+        self._message = message
+
+
+    def GetMessage(self):
+        """
+        Returns a string representing the main L{GenericMessageDialog} message.
+
+        .. versionadded:: 0.9.3
+        """
+
+        return self._message
+
+
+    def SetExtendedMessage(self, extendedMessage):
+        """
+        Sets the extended message for the dialog: this message is usually an extension of the
+        short message specified in the constructor or set with L{SetMessage}.
+
+        If it is set, the main message appears highlighted and this message appears beneath
+        it in normal font.
+
+        :param `extendedMessage`: a string representing the extended L{GenericMessageDialog} message.
+
+        .. versionadded:: 0.9.3
+        """
+
+        self._extendedMessage = extendedMessage
+
+
+    def GetExtendedMessage(self):
+        """
+        Returns a string representing the extended L{GenericMessageDialog} message.
+
+        .. versionadded:: 0.9.3
+        """
+
+        return self._extendedMessage
+

+    def GetMessageDialogStyle(self):
+        """
+        Returns the AGW-specific window style for L{GenericMessageDialog}.
+
+        .. versionadded:: 0.9.3
+        """
+
+        return self._agwStyle
+
+
+    # To combine the separate main and extended messages in a single string
+    def GetFullMessage(self):
+        """
+        Returns a string representing the combination of the main L{GenericMessageDialog}
+        message and the extended message, separated by an empty line.
+
+        .. versionadded:: 0.9.3
+        """
+
+        msg = self._message
+        if self._extendedMessage.strip():
+            msg += '\n\n' + self._extendedMessage
+
+        return msg
+

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • genericmessagedialog »
  • SVN Revision 70819 For genericmessagedialog


  • modules |
  • Home |
  • Gallery |
  • Contents»
  • Index

Index

Index pages by letter:

_ | A | B | C | D | E | F | G | H | I | K | L | M | N | O | P | R | S | T | U | V | W | X | Z

Full index on one page (can be huge)

Navigation

  • index
  • modules |
  • Home |
  • Gallery |
  • Index


Index

  • modules |
  • Home |
  • Gallery |
  • Contents»
  • Index

Index – _

__init__() (AbstractHandler method)
(AUIHandler method)
(AdvancedSplash method)
(AlphaCtrl method)
(AquaButton method)
(AquaButtonEvent method)
(ArtManager method)
(AuiCenterDockingGuide method)
(AuiCommandCapture method)
(AuiDefaultDockArt method)
(AuiDefaultTabArt method)
(AuiDefaultToolBarArt method)
(AuiDockInfo method)
(AuiDockUIPart method)
(AuiDockingGuide method)
(AuiDockingGuideInfo method)
(AuiDockingGuideWindow method)
(AuiDockingHintWindow method)
(AuiFloatingFrame method)
(AuiManager method)
(AuiManagerEvent method)
(AuiManager_DCP method)
(AuiNotebook method)
(AuiNotebookEvent method)
(AuiNotebookPage method)
(AuiPaneButton method)
(AuiPaneInfo method)
(AuiSimpleTabArt method)
(AuiSingleDockingGuide method)
(AuiTabContainer method)
(AuiTabContainerButton method)
(AuiTabCtrl method)
(AuiToolBar method)
(AuiToolBarEvent method)
(AuiToolBarItem method)
(BPArt method)
(BalloonFrame method)
(BalloonTip method)
(BaseLineCtrl method)
(BasePyControl method)
(BookHandler method)
(BoxSizer method)
(BrightCtrl method)
(BufferedWindow method), [1]
(ButtonInfo method)
(ButtonPanel method)
(ButtonPanelText method)
(CalendarCtrlHandler method)
(CaptionBar method)
(CaptionBarEvent method)
(CaptionBarStyle method)
(CheckBoxHandler method)
(CheckListBoxHandler method)
(ChoiceComboHandler method)
(ChoiceDialogHandler method)
(ChromeTabArt method)
(ColWidthInfo method)
(CollapsiblePaneHandler method)
(Colour method)
(ColourDialogHandler method)
(ColourPanel method)
(ColourPickerHandler method)
(CommandListEvent method)
(CommandNotebookEvent method)
(CommandToolBarEvent method)
(CommandTreeEvent method)
(ConflictDialog method)
(Control method)
(CubeColourDialog method)
(CustomPanel method)
(CustomTreeCtrl method)
(DCSaver method)
(DatePickerHandler method)
(DragImage method)
(EditCtrl method)
(EditTextCtrl method)
(Excel method)
(FF2TabArt method)
(FMCustomizeDlg method)
(FMRenderer method)
(FMRendererMSOffice2007 method)
(FMRendererMgr method)
(FMRendererVista method)
(FMRendererXP method)
(FMTitlePanel method)
(FNBDragInfo method)
(FNBDropSource method)
(FNBDropTarget method)
(FNBRenderer method)
(FNBRendererDefault method)
(FNBRendererFancy method)
(FNBRendererFirefox2 method)
(FNBRendererMgr method)
(FNBRendererRibbonTabs method)
(FNBRendererVC71 method)
(FNBRendererVC8 method)
(FileDirDialogHandler method)
(FileDirPickerHandler method)
(FileHistory method)
(FileHistoryHandler method)
(FindReplaceHandler method)
(FixedPoint method)
(FlatBookBase method)
(FlatImageBook method)
(FlatMenu method)
(FlatMenuBar method)
(FlatMenuBase method)
(FlatMenuButton method)
(FlatMenuEvent method)
(FlatMenuItem method)
(FlatMenuItemGroup method)
(FlatNotebook method)
(FlatNotebookCompatible method)
(FlatNotebookDragEvent method)
(FlatNotebookEvent method)
(FlatToolbarItem method)
(FloatSpin method)
(FloatSpinEvent method)
(FloatTextCtrl method)
(FocusHandler method)
(FoldPanelBar method)
(FoldPanelBarHandler method)
(FoldPanelItem method)
(FoldWindowItem method)
(FontDialogHandler method)
(FontPickerHandler method)
(FourWaySplitter method)
(FourWaySplitterEvent method)
(GTKExpander method)
(GenericMessageDialog method)
(GenericTreeItem method)
(GeometryInfo method)
(GradientButton method)
(GradientButtonEvent method)
(HSVWheel method)
(HTMLHelpWindow method)
(HyperLinkCtrl method)
(HyperLinkEvent method)
(HyperTreeList method)
(ImageBar method)
(ImageContainer method)
(ImageContainerBase method)
(ImageInfo method)
(ImageNotebookEvent method)
(Indicator method)
(InfoBar method)
(KnobCtrl method)
(KnobCtrlEvent method)
(Label method)
(LabelBook method)
(LabelContainer method)
(LineDescription method)
(ListBoxHandler method)
(ListCtrlHandler method)
(ListShortcut method)
(MediaCtrlHandler method)
(MenuBarHandler method)
(MenuEntryInfo method)
(MenuKbdRedirector method)
(ModernDockArt method)
(MultiColumnListCtrl method)
(MultiDirDialog method)
(PILImageHandler method)
(PageContainer method)
(PageInfo method)
(PeakMeterCtrl method)
(PeakMeterData method)
(PersistenceManager method)
(PersistentObject method)
(PieCtrl method)
(PieCtrlLegend method)
(PiePart method)
(ProgressGauge method)
(ProgressPie method)
(PyBusyInfo method)
(PyCollapsiblePane method)
(PyGauge method)
(PyImageList method)
(PyInfoFrame method)
(PyProgress method)
(RGBCube method)
(RadioBoxHandler method)
(RadioButtonHandler method)
(RendererBase method)
(RendererMSOffice2007 method)
(RendererXP method)
(RibbonAUIArtProvider method)
(RibbonBar method)
(RibbonBarEvent method)
(RibbonButtonBar method)
(RibbonButtonBarButtonBase method)
(RibbonButtonBarButtonInstance method)
(RibbonButtonBarButtonSizeInfo method)
(RibbonButtonBarEvent method)
(RibbonButtonBarLayout method)
(RibbonControl method)
(RibbonGallery method)
(RibbonGalleryEvent method)
(RibbonGalleryItem method)
(RibbonHSLColour method)
(RibbonMSWArtProvider method)
(RibbonPage method)
(RibbonPageScrollButton method)
(RibbonPageTabInfo method)
(RibbonPanel method)
(RibbonToolBar method)
(RibbonToolBarEvent method)
(RibbonToolBarToolBase method)
(RibbonToolBarToolGroup method)
(RulerCtrl method)
(RulerCtrlEvent method)
(SBitmapButton method)
(SBitmapTextButton method)
(SButton method)
(SButtonEvent method)
(ScrolledThumbnail method)
(ScrolledWindowHandler method)
(SelectionStore method)
(Separator method)
(ShadowPopupWindow method)
(Shortcut method)
(ShortcutEditor method)
(ShortcutEvent method)
(Sizer method)
(SliderHandler method)
(SpeedMeter method)
(SpinHandler method)
(SplitterHandler method)
(StatusBarTimer method), [1]
(StdDialogButtonSizer method)
(SuperToolTip method)
(SwitcherDialog method)
(SwitcherItem method)
(SwitcherItems method)
(TLWHandler method)
(TabDragImage method)
(TabFrame method)
(TabNavigatorProps method)
(TabNavigatorWindow method), [1]
(TabTextCtrl method)
(TextCtrlHandler method)
(TextEntryHandler method)
(Thumb method)
(ThumbnailCtrl method)
(ThumbnailEvent method)
(ToasterBox method)
(ToasterBoxWindow method)
(ToggleButtonHandler method)
(ToolBarHandler method)
(ToolBarItem method)
(ToolTipWindow method)
(ToolTipWindowBase method)
(ToolbarCommandCapture method)
(TransientPopup method)
(TreeCtrlHandler method)
(TreeEditTimer method)
(TreeEvent method)
(TreeFindTimer method)
(TreeItemAttr method)
(TreeListColumnInfo method)
(TreeListCtrlHandler method)
(TreeListHeaderWindow method)
(TreeListItem method)
(TreeListMainWindow method)
(TreeTextCtrl method)
(TreebookHandler method)
(UltimateListCtrl method)
(UltimateListEvent method)
(UltimateListHeaderData method)
(UltimateListHeaderWindow method)
(UltimateListItem method)
(UltimateListItemAttr method)
(UltimateListItemData method)
(UltimateListLineData method)
(UltimateListMainWindow method)
(UltimateListRenameTimer method)
(UltimateListTextCtrl method)
(VC71TabArt method)
(VC8TabArt method)
(XLSBackground method)
(XLSBorder method)
(XLSBorderFactory method)
(XLSCell method)
(XLSComment method)
(XLSGrid method)
(XLSRenderer method)
(XLSRichText method)
(XLSTable method)
(XLSText method)
(ZoomBar method)
(ZoomBarEvent method)
(ZoomBarImage method)
(mcPopupWindow method)
__SToggleMixin (class in shapedbutton)
__ToggleMixin (class in aquabutton)
_mkFP() (in module floatspin)
_norm() (in module floatspin)
_roundquotient() (in module floatspin)
_string2exact() (in module floatspin)
_tento() (in module floatspin)

Navigation

  • index
  • modules |
  • Home |
  • Gallery |
  • Index


Index

  • modules |
  • Home |
  • Gallery |
  • Contents»
  • Index

Index – A

AbstractHandler (class in persist.persist_handlers)
AcceptChanges() (EditCtrl method)
(TabTextCtrl method)
(TreeTextCtrl method)
(UltimateListTextCtrl method)
AcceptsFocus() (AquaButton method)
(BaseLineCtrl method)
(BasePyControl method)
(ColourPanel method)
(CustomTreeCtrl method)
(GradientButton method)
(SButton method)
AcceptsFocusFromKeyboard() (BaseLineCtrl method)
(BasePyControl method)
(ColourPanel method)
AcceptShortcut() (ListShortcut method)
actionPane (AuiPaneInfo attribute)
ActivateMenu() (FlatMenuBar method)
ActivateNextMenu() (FlatMenuBar method)
ActivatePane() (AuiManager method)
ActivatePreviousMenu() (FlatMenuBar method)
Add() (BoxSizer method)
(FlatMenuItemGroup method)
(PyImageList method)
AddBadDefaultName() (PersistenceManager method)
AddButton() (AuiTabContainer method)
(ButtonPanel method)
(InfoBar method)
(RibbonButtonBar method)
(StdDialogButtonSizer method)
(ZoomBar method)
AddCheckTool() (AuiToolBar method)
(FlatMenuBar method)
AddChild() (RibbonPanel method)
AddColumn() (HyperTreeList method)
(TreeListHeaderWindow method)
AddColumnInfo() (HyperTreeList method)
(TreeListHeaderWindow method)
AddControl() (AuiToolBar method)
(ButtonPanel method)
(FlatMenuBar method)
AddControlToPage() (AuiNotebook method)
AddCustom() (CustomPanel method)
AddDropdownButton() (RibbonButtonBar method)
AddDropdownTool() (RibbonToolBar method)
AddFilesToMenu() (FileHistory method)
AddFilesToMenu2() (FileHistory method)
AddFileToHistory() (FileHistory method)
AddFoldPanel() (FoldPanelBar method)
AddFoldPanelSeparator() (FoldPanelBar method)
AddFoldPanelWindow() (FoldPanelBar method)
AddGroup() (SwitcherItems method)
AddHybridButton() (RibbonButtonBar method)
AddHybridTool() (RibbonToolBar method)
AddIcon() (PyImageList method)
AddIndicator() (RulerCtrl method)
AddItem() (FlatMenu method)
(SwitcherItems method)
AddLabel() (AuiToolBar method)
AddMenuTheme() (ArtManager method)
AddPage() (AuiNotebook method)
(AuiTabContainer method)
(FlatBookBase method)
(FlatNotebook method)
(ImageContainerBase method)
(PageContainer method)
(RibbonBar method)
AddPane() (AuiManager method)
AddPane1() (AuiManager method)
AddPane2() (AuiManager method)
AddPane3() (AuiManager method)
AddPane4() (AuiManager method)
AddPanel() (ToasterBox method)
(ToasterBoxWindow method)
AddRadioTool() (AuiToolBar method)
(FlatMenuBar method)
AddRenderer() (FMRendererMgr method)
AddRoot() (CustomTreeCtrl method)
(HyperTreeList method)
(TreeListMainWindow method)
AddSeparator() (AuiToolBar method)
(ButtonPanel method)
(FlatMenuBar method)
(FoldPanelItem method)
(RibbonToolBar method)
(ZoomBar method)
AddSimpleButton() (RibbonButtonBar method)
AddSimpleTool() (AuiToolBar method)
(RibbonToolBar method)
AddSpacer() (AuiToolBar method)
(ButtonPanel method)
AddStatus() (ButtonInfo method)
AddStretchSpacer() (AuiToolBar method)
AddTabAreaButton() (AuiNotebook method)
AddToggleButton() (RibbonButtonBar method)
AddToggleTool() (AuiToolBar method)
AddTool() (AuiToolBar method)
(FlatMenuBar method)
(RibbonToolBar method)
AddWindow() (FoldPanelItem method)
AddWithColourMask() (PyImageList method)
AdjustColour() (in module flatnotebook)
AdjustDC() (TreeListHeaderWindow method)
(UltimateListHeaderWindow method)
AdjustLayout() (FourWaySplitter method)
AdjustMyScrollbars() (CustomTreeCtrl method)
(TreeListMainWindow method)
AdjustPosition() (FlatMenuBase method)
AdjustRectToIncludeScrollButtons() (RibbonPage method)
AdvancedSplash (class in advancedsplash)
advancedsplash (module)
AdvanceSelection() (AuiNotebook method)
(FlatBookBase method)
(FlatMenu method)
(FlatNotebook method)
(PageContainer method)
AdvanceToNextSelectableItem() (MultiColumnListCtrl method)
AeroMove() (AuiCenterDockingGuide method)
(AuiSingleDockingGuide method)
Allow() (AuiNotebookEvent method)
(AuiToolBarEvent method)
(FlatNotebookEvent method)
(FourWaySplitterEvent method)
(ImageNotebookEvent method)
(RibbonBarEvent method)
(TreeEvent method)
(UltimateListEvent method)
AlphaCtrl (class in cubecolourdialog)
AlphaCycle() (ToasterBoxWindow method)
(ToolTipWindowBase method)
AngleFromPoint() (in module cubecolourdialog)
AnimateDocking() (AuiManager method)
Append() (FlatMenu method)
(FlatMenuBar method)
(RibbonGallery method)
(UltimateListCtrl method)
AppendCheckItem() (FlatMenu method)
AppendGroup() (RibbonToolBar method)
AppendItem() (CustomTreeCtrl method)
(FlatMenu method)
(HyperTreeList method)
(Shortcut method)
AppendMenu() (FlatMenu method)
AppendRadioItem() (FlatMenu method)
AppendSeparator() (CustomTreeCtrl method)
(FlatMenu method)
AppendSubMenu() (FlatMenu method)
AppendToolbarItem() (FlatMenuBar method)
AppendWindow() (FourWaySplitter method)
ApplyCaptionStyle() (CaptionBar method)
(FoldPanelBar method)
(FoldPanelItem method)
ApplyCaptionStyleAll() (FoldPanelBar method)
ApplyStyle() (SuperToolTip method)
AquaButton (class in aquabutton)
aquabutton (module)
AquaButtonEvent (class in aquabutton)
AquaToggleButton (class in aquabutton)
Arrange() (UltimateListCtrl method)
ArtManager (class in artmanager)
artmanager (module)
Assign() (AuiDockingGuideInfo method)
(AuiToolBarItem method)
AssignAttributes() (GenericTreeItem method)
AssignButtonsImageList() (CustomTreeCtrl method)
(HyperTreeList method)
AssignColourValue() (CubeColourDialog method)
AssignImageList() (AuiNotebook method)
(CustomTreeCtrl method)
(FlatBookBase method)
(FlatNotebook method)
(HyperTreeList method)
(ImageContainerBase method)
(PageContainer method)
(UltimateListCtrl method)
AssignLeftImageList() (CustomTreeCtrl method)
AssignStateImageList() (CustomTreeCtrl method)
(HyperTreeList method)
Attr() (GenericTreeItem method)
Attributes() (UltimateListItem method)
aui (module)
aui.aui_switcherdialog (module)
aui.aui_utilities (module)
aui.auibar (module)
aui.auibook (module)
aui.dockart (module)
aui.framemanager (module)
aui.tabart (module)
AuiCenterDockingGuide (class in aui.framemanager)
AuiCommandCapture (class in aui.tabart)
AuiDefaultDockArt (class in aui.dockart)
AuiDefaultTabArt (class in aui.tabart)
AuiDefaultToolBarArt (class in aui.auibar)
AuiDockInfo (class in aui.framemanager)
AuiDockingGuide (class in aui.framemanager)
AuiDockingGuideInfo (class in aui.framemanager)
AuiDockingGuideWindow (class in aui.framemanager)
AuiDockingHintWindow (class in aui.framemanager)
AuiDockUIPart (class in aui.framemanager)
AuiFloatingFrame (class in aui.framemanager)
AUIHandler (class in persist.persist_handlers)
AuiManager (class in aui.framemanager)
AuiManager_DCP (class in aui.framemanager)
AuiManager_HasLiveResize() (in module aui.framemanager)
AuiManager_UseNativeMiniframes() (in module aui.framemanager)
AuiManagerEvent (class in aui.framemanager)
AuiNotebook (class in aui.auibook)
AuiNotebookEvent (class in aui.auibook)
AuiNotebookPage (class in aui.auibook)
AuiPaneButton (class in aui.framemanager)
AuiPaneInfo (class in aui.framemanager)
AuiSimpleTabArt (class in aui.tabart)
AuiSingleDockingGuide (class in aui.framemanager)
AuiTabContainer (class in aui.auibook)
AuiTabContainerButton (class in aui.auibook)
AuiTabCtrl (class in aui.auibook)
AuiToolBar (class in aui.auibar)
AuiToolBarEvent (class in aui.auibar)
AuiToolBarItem (class in aui.auibar)
AutoBrowse() (HyperLinkCtrl method)
AutoCheckChild() (CustomTreeCtrl method)
(HyperTreeList method)
(UltimateListMainWindow method)
AutoCheckParent() (CustomTreeCtrl method)
(HyperTreeList method)
AutoToggleChild() (CustomTreeCtrl method)
(HyperTreeList method)
(UltimateListMainWindow method)

Navigation

  • index
  • modules |
  • Home |
  • Gallery |
  • Index


  • modules |
  • Home |
  • Gallery |
  • Contents»
  • Index

Index

_ | A | B | C | D | E | F | G | H | I | K | L | M | N | O | P | R | S | T | U | V | W | X | Z

_

__init__() (AbstractHandler method)
(AUIHandler method)
(AdvancedSplash method)
(AlphaCtrl method)
(AquaButton method)
(AquaButtonEvent method)
(ArtManager method)
(AuiCenterDockingGuide method)
(AuiCommandCapture method)
(AuiDefaultDockArt method)
(AuiDefaultTabArt method)
(AuiDefaultToolBarArt method)
(AuiDockInfo method)
(AuiDockUIPart method)
(AuiDockingGuide method)
(AuiDockingGuideInfo method)
(AuiDockingGuideWindow method)
(AuiDockingHintWindow method)
(AuiFloatingFrame method)
(AuiManager method)
(AuiManagerEvent method)
(AuiManager_DCP method)
(AuiNotebook method)
(AuiNotebookEvent method)
(AuiNotebookPage method)
(AuiPaneButton method)
(AuiPaneInfo method)
(AuiSimpleTabArt method)
(AuiSingleDockingGuide method)
(AuiTabContainer method)
(AuiTabContainerButton method)
(AuiTabCtrl method)
(AuiToolBar method)
(AuiToolBarEvent method)
(AuiToolBarItem method)
(BPArt method)
(BalloonFrame method)
(BalloonTip method)
(BaseLineCtrl method)
(BasePyControl method)
(BookHandler method)
(BoxSizer method)
(BrightCtrl method)
(BufferedWindow method), [1]
(ButtonInfo method)
(ButtonPanel method)
(ButtonPanelText method)
(CalendarCtrlHandler method)
(CaptionBar method)
(CaptionBarEvent method)
(CaptionBarStyle method)
(CheckBoxHandler method)
(CheckListBoxHandler method)
(ChoiceComboHandler method)
(ChoiceDialogHandler method)
(ChromeTabArt method)
(ColWidthInfo method)
(CollapsiblePaneHandler method)
(Colour method)
(ColourDialogHandler method)
(ColourPanel method)
(ColourPickerHandler method)
(CommandListEvent method)
(CommandNotebookEvent method)
(CommandToolBarEvent method)
(CommandTreeEvent method)
(ConflictDialog method)
(Control method)
(CubeColourDialog method)
(CustomPanel method)
(CustomTreeCtrl method)
(DCSaver method)
(DatePickerHandler method)
(DragImage method)
(EditCtrl method)
(EditTextCtrl method)
(Excel method)
(FF2TabArt method)
(FMCustomizeDlg method)
(FMRenderer method)
(FMRendererMSOffice2007 method)
(FMRendererMgr method)
(FMRendererVista method)
(FMRendererXP method)
(FMTitlePanel method)
(FNBDragInfo method)
(FNBDropSource method)
(FNBDropTarget method)
(FNBRenderer method)
(FNBRendererDefault method)
(FNBRendererFancy method)
(FNBRendererFirefox2 method)
(FNBRendererMgr method)
(FNBRendererRibbonTabs method)
(FNBRendererVC71 method)
(FNBRendererVC8 method)
(FileDirDialogHandler method)
(FileDirPickerHandler method)
(FileHistory method)
(FileHistoryHandler method)
(FindReplaceHandler method)
(FixedPoint method)
(FlatBookBase method)
(FlatImageBook method)
(FlatMenu method)
(FlatMenuBar method)
(FlatMenuBase method)
(FlatMenuButton method)
(FlatMenuEvent method)
(FlatMenuItem method)
(FlatMenuItemGroup method)
(FlatNotebook method)
(FlatNotebookCompatible method)
(FlatNotebookDragEvent method)
(FlatNotebookEvent method)
(FlatToolbarItem method)
(FloatSpin method)
(FloatSpinEvent method)
(FloatTextCtrl method)
(FocusHandler method)
(FoldPanelBar method)
(FoldPanelBarHandler method)
(FoldPanelItem method)
(FoldWindowItem method)
(FontDialogHandler method)
(FontPickerHandler method)
(FourWaySplitter method)
(FourWaySplitterEvent method)
(GTKExpander method)
(GenericMessageDialog method)
(GenericTreeItem method)
(GeometryInfo method)
(GradientButton method)
(GradientButtonEvent method)
(HSVWheel method)
(HTMLHelpWindow method)
(HyperLinkCtrl method)
(HyperLinkEvent method)
(HyperTreeList method)
(ImageBar method)
(ImageContainer method)
(ImageContainerBase method)
(ImageInfo method)
(ImageNotebookEvent method)
(Indicator method)
(InfoBar method)
(KnobCtrl method)
(KnobCtrlEvent method)
(Label method)
(LabelBook method)
(LabelContainer method)
(LineDescription method)
(ListBoxHandler method)
(ListCtrlHandler method)
(ListShortcut method)
(MediaCtrlHandler method)
(MenuBarHandler method)
(MenuEntryInfo method)
(MenuKbdRedirector method)
(ModernDockArt method)
(MultiColumnListCtrl method)
(MultiDirDialog method)
(PILImageHandler method)
(PageContainer method)
(PageInfo method)
(PeakMeterCtrl method)
(PeakMeterData method)
(PersistenceManager method)
(PersistentObject method)
(PieCtrl method)
(PieCtrlLegend method)
(PiePart method)
(ProgressGauge method)
(ProgressPie method)
(PyBusyInfo method)
(PyCollapsiblePane method)
(PyGauge method)
(PyImageList method)
(PyInfoFrame method)
(PyProgress method)
(RGBCube method)
(RadioBoxHandler method)
(RadioButtonHandler method)
(RendererBase method)
(RendererMSOffice2007 method)
(RendererXP method)
(RibbonAUIArtProvider method)
(RibbonBar method)
(RibbonBarEvent method)
(RibbonButtonBar method)
(RibbonButtonBarButtonBase method)
(RibbonButtonBarButtonInstance method)
(RibbonButtonBarButtonSizeInfo method)
(RibbonButtonBarEvent method)
(RibbonButtonBarLayout method)
(RibbonControl method)
(RibbonGallery method)
(RibbonGalleryEvent method)
(RibbonGalleryItem method)
(RibbonHSLColour method)
(RibbonMSWArtProvider method)
(RibbonPage method)
(RibbonPageScrollButton method)
(RibbonPageTabInfo method)
(RibbonPanel method)
(RibbonToolBar method)
(RibbonToolBarEvent method)
(RibbonToolBarToolBase method)
(RibbonToolBarToolGroup method)
(RulerCtrl method)
(RulerCtrlEvent method)
(SBitmapButton method)
(SBitmapTextButton method)
(SButton method)
(SButtonEvent method)
(ScrolledThumbnail method)
(ScrolledWindowHandler method)
(SelectionStore method)
(Separator method)
(ShadowPopupWindow method)
(Shortcut method)
(ShortcutEditor method)
(ShortcutEvent method)
(Sizer method)
(SliderHandler method)
(SpeedMeter method)
(SpinHandler method)
(SplitterHandler method)
(StatusBarTimer method), [1]
(StdDialogButtonSizer method)
(SuperToolTip method)
(SwitcherDialog method)
(SwitcherItem method)
(SwitcherItems method)
(TLWHandler method)
(TabDragImage method)
(TabFrame method)
(TabNavigatorProps method)
(TabNavigatorWindow method), [1]
(TabTextCtrl method)
(TextCtrlHandler method)
(TextEntryHandler method)
(Thumb method)
(ThumbnailCtrl method)
(ThumbnailEvent method)
(ToasterBox method)
(ToasterBoxWindow method)
(ToggleButtonHandler method)
(ToolBarHandler method)
(ToolBarItem method)
(ToolTipWindow method)
(ToolTipWindowBase method)
(ToolbarCommandCapture method)
(TransientPopup method)
(TreeCtrlHandler method)
(TreeEditTimer method)
(TreeEvent method)
(TreeFindTimer method)
(TreeItemAttr method)
(TreeListColumnInfo method)
(TreeListCtrlHandler method)
(TreeListHeaderWindow method)
(TreeListItem method)
(TreeListMainWindow method)
(TreeTextCtrl method)
(TreebookHandler method)
(UltimateListCtrl method)
(UltimateListEvent method)
(UltimateListHeaderData method)
(UltimateListHeaderWindow method)
(UltimateListItem method)
(UltimateListItemAttr method)
(UltimateListItemData method)
(UltimateListLineData method)
(UltimateListMainWindow method)
(UltimateListRenameTimer method)
(UltimateListTextCtrl method)
(VC71TabArt method)
(VC8TabArt method)
(XLSBackground method)
(XLSBorder method)
(XLSBorderFactory method)
(XLSCell method)
(XLSComment method)
(XLSGrid method)
(XLSRenderer method)
(XLSRichText method)
(XLSTable method)
(XLSText method)
(ZoomBar method)
(ZoomBarEvent method)
(ZoomBarImage method)
(mcPopupWindow method)
__SToggleMixin (class in shapedbutton)
__ToggleMixin (class in aquabutton)
_mkFP() (in module floatspin)
_norm() (in module floatspin)
_roundquotient() (in module floatspin)
_string2exact() (in module floatspin)
_tento() (in module floatspin)

A

AbstractHandler (class in persist.persist_handlers)
AcceptChanges() (EditCtrl method)
(TabTextCtrl method)
(TreeTextCtrl method)
(UltimateListTextCtrl method)
AcceptsFocus() (AquaButton method)
(BaseLineCtrl method)
(BasePyControl method)
(ColourPanel method)
(CustomTreeCtrl method)
(GradientButton method)
(SButton method)
AcceptsFocusFromKeyboard() (BaseLineCtrl method)
(BasePyControl method)
(ColourPanel method)
AcceptShortcut() (ListShortcut method)
actionPane (AuiPaneInfo attribute)
ActivateMenu() (FlatMenuBar method)
ActivateNextMenu() (FlatMenuBar method)
ActivatePane() (AuiManager method)
ActivatePreviousMenu() (FlatMenuBar method)
Add() (BoxSizer method)
(FlatMenuItemGroup method)
(PyImageList method)
AddBadDefaultName() (PersistenceManager method)
AddButton() (AuiTabContainer method)
(ButtonPanel method)
(InfoBar method)
(RibbonButtonBar method)
(StdDialogButtonSizer method)
(ZoomBar method)
AddCheckTool() (AuiToolBar method)
(FlatMenuBar method)
AddChild() (RibbonPanel method)
AddColumn() (HyperTreeList method)
(TreeListHeaderWindow method)
AddColumnInfo() (HyperTreeList method)
(TreeListHeaderWindow method)
AddControl() (AuiToolBar method)
(ButtonPanel method)
(FlatMenuBar method)
AddControlToPage() (AuiNotebook method)
AddCustom() (CustomPanel method)
AddDropdownButton() (RibbonButtonBar method)
AddDropdownTool() (RibbonToolBar method)
AddFilesToMenu() (FileHistory method)
AddFilesToMenu2() (FileHistory method)
AddFileToHistory() (FileHistory method)
AddFoldPanel() (FoldPanelBar method)
AddFoldPanelSeparator() (FoldPanelBar method)
AddFoldPanelWindow() (FoldPanelBar method)
AddGroup() (SwitcherItems method)
AddHybridButton() (RibbonButtonBar method)
AddHybridTool() (RibbonToolBar method)
AddIcon() (PyImageList method)
AddIndicator() (RulerCtrl method)
AddItem() (FlatMenu method)
(SwitcherItems method)
AddLabel() (AuiToolBar method)
AddMenuTheme() (ArtManager method)
AddPage() (AuiNotebook method)
(AuiTabContainer method)
(FlatBookBase method)
(FlatNotebook method)
(ImageContainerBase method)
(PageContainer method)
(RibbonBar method)
AddPane() (AuiManager method)
AddPane1() (AuiManager method)
AddPane2() (AuiManager method)
AddPane3() (AuiManager method)
AddPane4() (AuiManager method)
AddPanel() (ToasterBox method)
(ToasterBoxWindow method)
AddRadioTool() (AuiToolBar method)
(FlatMenuBar method)
AddRenderer() (FMRendererMgr method)
AddRoot() (CustomTreeCtrl method)
(HyperTreeList method)
(TreeListMainWindow method)
AddSeparator() (AuiToolBar method)
(ButtonPanel method)
(FlatMenuBar method)
(FoldPanelItem method)
(RibbonToolBar method)
(ZoomBar method)
AddSimpleButton() (RibbonButtonBar method)
AddSimpleTool() (AuiToolBar method)
(RibbonToolBar method)
AddSpacer() (AuiToolBar method)
(ButtonPanel method)
AddStatus() (ButtonInfo method)
AddStretchSpacer() (AuiToolBar method)
AddTabAreaButton() (AuiNotebook method)
AddToggleButton() (RibbonButtonBar method)
AddToggleTool() (AuiToolBar method)
AddTool() (AuiToolBar method)
(FlatMenuBar method)
(RibbonToolBar method)
AddWindow() (FoldPanelItem method)
AddWithColourMask() (PyImageList method)
AdjustColour() (in module flatnotebook)
AdjustDC() (TreeListHeaderWindow method)
(UltimateListHeaderWindow method)
AdjustLayout() (FourWaySplitter method)
AdjustMyScrollbars() (CustomTreeCtrl method)
(TreeListMainWindow method)
AdjustPosition() (FlatMenuBase method)
AdjustRectToIncludeScrollButtons() (RibbonPage method)
AdvancedSplash (class in advancedsplash)
advancedsplash (module)
AdvanceSelection() (AuiNotebook method)
(FlatBookBase method)
(FlatMenu method)
(FlatNotebook method)
(PageContainer method)
AdvanceToNextSelectableItem() (MultiColumnListCtrl method)
AeroMove() (AuiCenterDockingGuide method)
(AuiSingleDockingGuide method)
Allow() (AuiNotebookEvent method)
(AuiToolBarEvent method)
(FlatNotebookEvent method)
(FourWaySplitterEvent method)
(ImageNotebookEvent method)
(RibbonBarEvent method)
(TreeEvent method)
(UltimateListEvent method)
AlphaCtrl (class in cubecolourdialog)
AlphaCycle() (ToasterBoxWindow method)
(ToolTipWindowBase method)
AngleFromPoint() (in module cubecolourdialog)
AnimateDocking() (AuiManager method)
Append() (FlatMenu method)
(FlatMenuBar method)
(RibbonGallery method)
(UltimateListCtrl method)
AppendCheckItem() (FlatMenu method)
AppendGroup() (RibbonToolBar method)
AppendItem() (CustomTreeCtrl method)
(FlatMenu method)
(HyperTreeList method)
(Shortcut method)
AppendMenu() (FlatMenu method)
AppendRadioItem() (FlatMenu method)
AppendSeparator() (CustomTreeCtrl method)
(FlatMenu method)
AppendSubMenu() (FlatMenu method)
AppendToolbarItem() (FlatMenuBar method)
AppendWindow() (FourWaySplitter method)
ApplyCaptionStyle() (CaptionBar method)
(FoldPanelBar method)
(FoldPanelItem method)
ApplyCaptionStyleAll() (FoldPanelBar method)
ApplyStyle() (SuperToolTip method)
AquaButton (class in aquabutton)
aquabutton (module)
AquaButtonEvent (class in aquabutton)
AquaToggleButton (class in aquabutton)
Arrange() (UltimateListCtrl method)
ArtManager (class in artmanager)
artmanager (module)
Assign() (AuiDockingGuideInfo method)
(AuiToolBarItem method)
AssignAttributes() (GenericTreeItem method)
AssignButtonsImageList() (CustomTreeCtrl method)
(HyperTreeList method)
AssignColourValue() (CubeColourDialog method)
AssignImageList() (AuiNotebook method)
(CustomTreeCtrl method)
(FlatBookBase method)
(FlatNotebook method)
(HyperTreeList method)
(ImageContainerBase method)
(PageContainer method)
(UltimateListCtrl method)
AssignLeftImageList() (CustomTreeCtrl method)
AssignStateImageList() (CustomTreeCtrl method)
(HyperTreeList method)
Attr() (GenericTreeItem method)
Attributes() (UltimateListItem method)
aui (module)
aui.aui_switcherdialog (module)
aui.aui_utilities (module)
aui.auibar (module)
aui.auibook (module)
aui.dockart (module)
aui.framemanager (module)
aui.tabart (module)
AuiCenterDockingGuide (class in aui.framemanager)
AuiCommandCapture (class in aui.tabart)
AuiDefaultDockArt (class in aui.dockart)
AuiDefaultTabArt (class in aui.tabart)
AuiDefaultToolBarArt (class in aui.auibar)
AuiDockInfo (class in aui.framemanager)
AuiDockingGuide (class in aui.framemanager)
AuiDockingGuideInfo (class in aui.framemanager)
AuiDockingGuideWindow (class in aui.framemanager)
AuiDockingHintWindow (class in aui.framemanager)
AuiDockUIPart (class in aui.framemanager)
AuiFloatingFrame (class in aui.framemanager)
AUIHandler (class in persist.persist_handlers)
AuiManager (class in aui.framemanager)
AuiManager_DCP (class in aui.framemanager)
AuiManager_HasLiveResize() (in module aui.framemanager)
AuiManager_UseNativeMiniframes() (in module aui.framemanager)
AuiManagerEvent (class in aui.framemanager)
AuiNotebook (class in aui.auibook)
AuiNotebookEvent (class in aui.auibook)
AuiNotebookPage (class in aui.auibook)
AuiPaneButton (class in aui.framemanager)
AuiPaneInfo (class in aui.framemanager)
AuiSimpleTabArt (class in aui.tabart)
AuiSingleDockingGuide (class in aui.framemanager)
AuiTabContainer (class in aui.auibook)
AuiTabContainerButton (class in aui.auibook)
AuiTabCtrl (class in aui.auibook)
AuiToolBar (class in aui.auibar)
AuiToolBarEvent (class in aui.auibar)
AuiToolBarItem (class in aui.auibar)
AutoBrowse() (HyperLinkCtrl method)
AutoCheckChild() (CustomTreeCtrl method)
(HyperTreeList method)
(UltimateListMainWindow method)
AutoCheckParent() (CustomTreeCtrl method)
(HyperTreeList method)
AutoToggleChild() (CustomTreeCtrl method)
(HyperTreeList method)
(UltimateListMainWindow method)

B

BackgroundColour() (ArtManager method)
BalloonFrame (class in balloontip)
BalloonTip (class in balloontip)
balloontip (module)
BaseLineCtrl (class in cubecolourdialog)
BasePyControl (class in cubecolourdialog)
BestSize() (AuiPaneInfo method)
BestSize1() (AuiPaneInfo method)
BestSize2() (AuiPaneInfo method)
BindEvents() (MultiDirDialog method)
(ShortcutEditor method)
Bitmap (ButtonInfo attribute)
BitmapFromBits() (in module aui.aui_utilities)
BlendColour() (in module aui.aui_utilities)
BookHandler (class in persist.persist_handlers)
Bottom() (AuiDockingGuideInfo method)
(AuiPaneInfo method)
BottomDockable() (AuiPaneInfo method)
BottomSnappable() (AuiPaneInfo method)
BoxSizer (class in buttonpanel)
BPArt (class in buttonpanel)
BreakCaption() (Thumb method)
BreakColumn() (SwitcherItem method)
BrightCtrl (class in cubecolourdialog)
BrightenColour() (in module buttonpanel)
BufferedWindow (class in knobctrl)
(class in speedmeter)
BuildChunks() (XLSRichText method)
BuildImageList() (ListShortcut method)
BuildRect() (BaseLineCtrl method)
BuildToolBar() (HTMLHelpWindow method)
buttonClose (AuiPaneInfo attribute)
buttonCustom1 (AuiPaneInfo attribute)
buttonCustom2 (AuiPaneInfo attribute)
buttonCustom3 (AuiPaneInfo attribute)
ButtonHitTest() (AuiTabContainer method)
ButtonInfo (class in buttonpanel)
buttonMaximize (AuiPaneInfo attribute)
buttonMinimize (AuiPaneInfo attribute)
ButtonPanel (class in buttonpanel)
buttonpanel (module)
ButtonPanelText (class in buttonpanel)
buttonPin (AuiPaneInfo attribute)

C

CacheLineData() (UltimateListMainWindow method)
CalcButtonBestSize() (ArtManager method)
CalcCuboid() (CubeColourDialog method)
CalcRects() (CubeColourDialog method)
CalcSlopes() (CubeColourDialog method)
CalcTabHeight() (FNBRenderer method)
CalcTabWidth() (FNBRenderer method)
(FNBRendererRibbonTabs method)
CalculateAndSetHeaderHeight() (HyperTreeList method)
CalculateBestCaption() (ScrolledThumbnail method)
CalculateBestPosition() (ToolTipWindowBase method)
CalculateBestSize() (ToolTipWindowBase method)
CalculateDockSizerLimits() (AuiManager method)
CalculateHintRect() (AuiManager method)
CalculateItemSize() (SwitcherItems method)
CalculateLayout() (MultiColumnListCtrl method)
CalculateLevel() (CustomTreeCtrl method)
(TreeListMainWindow method)
CalculateLineHeight() (CustomTreeCtrl method)
CalculateMinSize() (RibbonGallery method)
CalculateNewSplitSize() (AuiNotebook method)
CalculateOffset() (ListShortcut method)
CalculateOverallSize() (RibbonButtonBarLayout method)
CalculatePaneSizerLimits() (AuiManager method)
CalculatePositions() (CustomTreeCtrl method)
(TreeListMainWindow method)
CalculateSize() (CustomTreeCtrl method)
(TreeListMainWindow method)
(UltimateListLineData method)
CalculateTabCtrlHeight() (AuiNotebook method)
CalendarCtrlHandler (class in persist.persist_handlers)
CanAutoMinimise() (RibbonPanel method)
CanDoBottomStyle() (ImageContainer method)
(ImageContainerBase method)
(LabelContainer method)
CanDockPanel() (AuiManager method)
CanFitToScreen() (PageContainer method)
CanMakeWindowsTransparent() (ArtManager method)
CanUseModernDockArt() (AuiManager method)
CanVeto() (AuiManagerEvent method)
Caption() (AuiPaneInfo method)
CaptionBar (class in foldpanelbar)
CaptionBarEvent (class in foldpanelbar)
CaptionBarStyle (class in foldpanelbar)
CaptionColourUsed() (CaptionBarStyle method)
CaptionFontUsed() (CaptionBarStyle method)
CaptionStyleUsed() (CaptionBarStyle method)
CaptionVisible() (AuiPaneInfo method)
Center() (AuiDockingGuideInfo method)
(AuiPaneInfo method)
CenterOnParent() (ToasterBox method)
CenterOnScreen() (ToasterBox method)
CenterPane() (AuiPaneInfo method)
Centre() (AuiDockingGuideInfo method)
(AuiPaneInfo method)
CentreOnParent() (ToasterBox method)
CentreOnScreen() (ToasterBox method)
CentrePane() (AuiPaneInfo method)
ChangeCurrent() (UltimateListMainWindow method)
ChangeSelection() (FlatBookBase method)
(FlatNotebookCompatible method)
Check() (FlatMenuItem method)
(GenericTreeItem method)
(UltimateListHeaderData method)
(UltimateListItem method)
(UltimateListItemData method)
(UltimateListLineData method)
CheckAccelerator() (Shortcut method)
CheckBoxHandler (class in persist.persist_handlers)
CheckChilds() (CustomTreeCtrl method)
(HyperTreeList method)
CheckEdgeDrop() (in module aui.framemanager)
CheckFooter() (UltimateListHeaderData method)
(UltimateListItem method)
CheckItem() (CustomTreeCtrl method)
(HyperTreeList method)
(UltimateListMainWindow method)
CheckItem2() (CustomTreeCtrl method)
(HyperTreeList method)
CheckListBoxHandler (class in persist.persist_handlers)
CheckMovableSizer() (AuiManager method)
CheckOutOfWindow() (in module aui.framemanager)
CheckPaneMove() (AuiManager method)
CheckRefresh() (ButtonInfo method)
CheckSameLevel() (CustomTreeCtrl method)
(HyperTreeList method)
CheckStyle() (RulerCtrl method)
CheckVariableRowHeight() (in module ultimatelistctrl)
ChildrenClosing() (CustomTreeCtrl method)
(TreeListMainWindow method)
ChoiceComboHandler (class in persist.persist_handlers)
ChoiceDialogHandler (class in persist.persist_handlers)
ChopText() (in module aui.aui_utilities)
(in module customtreectrl)
ChromeTabArt (class in aui.tabart)
CircleCoords() (KnobCtrl method)
(SpeedMeter method)
ClampValue() (FloatSpin method)
CleanList() (ToasterBox method)
Clear() (AuiToolBar method)
(ButtonPanel method)
(FlatMenu method)
(RibbonGallery method)
(ScrolledThumbnail method)
(SelectionStore method)
(SwitcherItems method)
(UltimateListItem method)
ClearAGWFlag() (PageContainer method)
ClearAll() (ImageContainerBase method)
(UltimateListCtrl method)
ClearAttributes() (UltimateListItem method)
ClearBitmaps() (FlatMenuBar method)
ClearButtons() (RibbonButtonBar method)
ClearColumnImage() (UltimateListCtrl method)
ClearFlag() (ImageContainerBase method)
ClearTools() (AuiToolBar method)
ClientToScreen() (UltimateListCtrl method)
ClientToScreenXY() (UltimateListCtrl method)
Clip() (in module aui.aui_utilities)
Clone() (AuiDefaultTabArt method)
(AuiDefaultToolBarArt method)
(AuiSimpleTabArt method)
(ChromeTabArt method)
(FF2TabArt method)
(RibbonAUIArtProvider method)
(RibbonMSWArtProvider method)
(VC71TabArt method)
(VC8TabArt method)
CloneButtons() (AuiTabContainer method)
CloneTabAreaButtons() (AuiNotebook method)
CloneTo() (RibbonMSWArtProvider method)
Close() (Excel method)
CloseButton() (AuiPaneInfo method)
CloseDialog() (FMCustomizeDlg method)
(TabNavigatorWindow method), [1]
ClosePane() (AuiManager method)
CloseSubMenu() (FlatMenu method)
CmpThumb() (in module thumbnailctrl)
Collapse() (CaptionBar method)
(CustomTreeCtrl method)
(FoldPanelBar method)
(FoldPanelItem method)
(GenericTreeItem method)
(HyperTreeList method)
(PyCollapsiblePane method)
CollapseAndReset() (CustomTreeCtrl method)
(HyperTreeList method)
CollapsePanels() (RibbonPage method)
CollapsiblePaneHandler (class in persist.persist_handlers)
Colour (class in cubecolourdialog)
ColourDialogHandler (class in persist.persist_handlers)
ColourPanel (class in cubecolourdialog)
ColourPickerHandler (class in persist.persist_handlers)
ColourToHexString() (SwitcherDialog method)
column() (EditCtrl method)
ColWidthInfo (class in ultimatelistctrl)
CombineAttr() (XLSBackground method)
(XLSText method)
CommandListEvent (class in ultimatelistctrl)
CommandNotebookEvent (class in aui.auibook)
CommandToolBarEvent (class in aui.auibar)
CommandTreeEvent (class in customtreectrl)
CommonInit() (RibbonBar method)
(RibbonButtonBar method)
(RibbonGallery method)
(RibbonPage method)
(RibbonPanel method)
(RibbonToolBar method)
ConflictDialog (class in shortcuteditor)
ConnectEvents() (FMCustomizeDlg method)
Contains() (FlatMenuButton method)
Control (class in buttonpanel)
ConvertPILToWX() (in module rulerctrl)
(SButton method)
ConvertToBitmap() (ArtManager method)
(FMRenderer method)
ConvertToMonochrome() (in module flatmenu)
ConvertWXToPIL() (in module rulerctrl)
(SButton method)
copy() (FixedPoint method)
Copy() (SwitcherItem method)
(SwitcherItems method)
CopyAttributes() (AuiFloatingFrame method)
(in module aui.aui_utilities)
CopyDocksAndPanes() (in module aui.framemanager)
CopyDocksAndPanes2() (in module aui.framemanager)
CopyTarget() (AuiManager method)
CountButtons() (AuiPaneInfo method)
create_delegator_for() (in module hypertreelist)
CreateAlignment() (XLSText method)
CreateBackgroundColour() (XLSBackground method)
CreateBitmap() (DragImage method)
(TabDragImage method)
CreateButtons() (MultiDirDialog method)
CreateButtonSizer() (GenericMessageDialog method)
CreateDC() (ButtonPanelText method)
CreateDialog() (FMCustomizeDlg method)
CreateEditCtrl() (HyperTreeList method)
CreateFloatingFrame() (AuiManager method)
CreateFont() (in module persist.persist_handlers)
(XLSText method)
CreateFormat() (XLSText method)
CreateGreyBitmap() (ArtManager method)
CreateGuideWindows() (AuiManager method)
CreateHintWindow() (AuiManager method)
CreateImageContainer() (FlatImageBook method)
(LabelBook method)
CreateLabel() (PyProgress method)
CreateListItem() (in module ultimatelistctrl)
CreateMenusPage() (FMCustomizeDlg method)
CreateMessageDialog() (GenericMessageDialog method)
CreateMoreMenu() (FlatMenuBar method)
CreateNotebook() (AuiManager method)
CreateNotebookBase() (AuiManager method)
CreateOptionsPage() (FMCustomizeDlg method)
CreateOrDestroyFooterWindowAsNeeded() (UltimateListCtrl method)
CreateOrDestroyHeaderWindowAsNeeded() (UltimateListCtrl method)
CreateSeparatedButtonSizer() (GenericMessageDialog method)
CreateShapesWithStyle() (AuiCenterDockingGuide method)
(AuiSingleDockingGuide method)
CreateShortcutsPage() (FMCustomizeDlg method)
CreateStdDialogButtonSizer() (GenericMessageDialog method)
CreateTextColour() (XLSText method)
CreateWidgets() (ShortcutEditor method)
CubeColourDialog (class in cubecolourdialog)
cubecolourdialog (module)
CurrentPage (FlatBookBase attribute)
CustomPanel (class in cubecolourdialog)
CustomTreeCtrl (class in customtreectrl)
customtreectrl (module)

D

DarkColour() (ArtManager method)
DarkenBitmap() (in module aui.aui_utilities)
DarkenColour() (in module peakmeter)
Darker() (RibbonHSLColour method)
DatePickerHandler (class in persist.persist_handlers)
DCSaver (class in artmanager)
DefaultPane() (AuiPaneInfo method)
deg2rad() (in module cubecolourdialog)
Delete() (CustomTreeCtrl method)
(FlatMenu method)
(HyperTreeList method)
(TreeListMainWindow method)
DeleteAllColumns() (UltimateListCtrl method)
DeleteAllItems() (CustomTreeCtrl method)
(HyperTreeList method)
(TreeListMainWindow method)
(UltimateListCtrl method)
(UltimateListMainWindow method)
DeleteAllPages() (FlatBookBase method)
(FlatNotebook method)
(PageContainer method)
DeleteButton() (RibbonButtonBar method)
DeleteChildren() (CustomTreeCtrl method)
(GenericTreeItem method)
(HyperTreeList method)
(TreeListItem method)
DeleteColumn() (UltimateListCtrl method)
(UltimateListMainWindow method)
DeleteEverything() (UltimateListMainWindow method)
DeleteFiles() (ScrolledThumbnail method)
DeleteItem() (UltimateListCtrl method)
(UltimateListMainWindow method)
DeleteItemWindow() (CustomTreeCtrl method)
(UltimateListCtrl method)
(UltimateListMainWindow method)
DeletePage() (AuiNotebook method)
(FlatBookBase method)
(FlatNotebook method)
(PageContainer method)
DeleteRoot() (HyperTreeList method)
(TreeListMainWindow method)
DeleteTool() (AuiToolBar method)
DeleteToolByPos() (AuiToolBar method)
DeleteWindow() (GenericTreeItem method)
(TreeListItem method)
(UltimateListItem method)
(UltimateListItemData method)
Desaturated() (RibbonHSLColour method)
Destroy() (AuiNotebook method)
(FlatMenu method)
DestroyGuideWindows() (AuiManager method)
DestroyHintWindow() (AuiManager method)
DestroyOnClose() (AuiPaneInfo method)
DestroyTimer() (BalloonTip method)
DestroyTip() (XLSGrid method)
DetachPane() (AuiManager method)
DetachWindow() (FourWaySplitter method)
Direction() (AuiPaneInfo method)
Disable() (Control method)
DisableAbort() (PyProgress method)
DisableRestoring() (PersistenceManager method)
DisableSaving() (PersistenceManager method)
DisableShortcut() (ListShortcut method)
Dismiss() (FlatMenu method)
(FlatMenuBase method)
(InfoBar method)
DismissExpandedPanel() (RibbonBar method)
(RibbonPage method)
DisplayError() (HyperLinkCtrl method)
Distance() (in module cubecolourdialog)
DoAction() (FlatMenu method)
Dock() (AuiPaneInfo method)
dock_direction (AuiPaneInfo attribute)
dock_direction_get() (AuiPaneInfo method)
dock_direction_set() (AuiPaneInfo method)
Dockable() (AuiPaneInfo method)
DockFixed() (AuiPaneInfo method)
DoDeleteAllItems() (UltimateListMainWindow method)
DoDeletePage() (ImageContainerBase method)
(PageContainer method)
DoDrop() (AuiManager method)
DoDropFloatingPane() (AuiManager method)
DoDropLayer() (AuiManager method)
DoDropNonFloatingPane() (AuiManager method)
DoDropPane() (AuiManager method)
DoDropRow() (AuiManager method)
DoDropToolbar() (AuiManager method)
DoEndResizeAction() (AuiManager method)
DoEraseBackground() (RibbonBar method)
DoFrameLayout() (AuiManager method)
DoGetBestSize() (AquaButton method)
(AuiTabCtrl method)
(AuiToolBar method)
(BaseLineCtrl method)
(BasePyControl method)
(ButtonPanel method)
(CaptionBar method)
(CustomPanel method)
(CustomTreeCtrl method)
(FlatNotebook method)
(FloatSpin method)
(FourWaySplitter method)
(GTKExpander method)
(GradientButton method)
(HyperTreeList method)
(MultiColumnListCtrl method)
(PeakMeterCtrl method)
(PyCollapsiblePane method)
(PyGauge method)
(RibbonBar method)
(RibbonButtonBar method)
(RibbonGallery method)
(RibbonPage method)
(RibbonPanel method)
(RibbonToolBar method)
(SButton method)
(UltimateListCtrl method)
(UltimateListHeaderWindow method)
(UltimateListMainWindow method)
(ZoomBar method)
DoGetClientSize() (TabFrame method)
DoGetNextLargerSize() (RibbonButtonBar method)
(RibbonControl method)
(RibbonGallery method)
(RibbonPanel method)
(RibbonToolBar method)
DoGetNextSmallerSize() (RibbonButtonBar method)
(RibbonControl method)
(RibbonGallery method)
(RibbonPanel method)
(RibbonToolBar method)
DoGetSize() (TabFrame method)
DoGiveHelp() (ButtonPanel method)
(FlatMenuBar method)
DoHeaderLayout() (HyperTreeList method)
DoHide() (InfoBar method)
DoIdleUpdate() (AuiToolBar method)
DoInsertDockLayer() (in module aui.framemanager)
DoInsertDockRow() (in module aui.framemanager)
DoInsertItem() (CustomTreeCtrl method)
(TreeListMainWindow method)
DoInsertPane() (in module aui.framemanager)
DoLayout() (ButtonPanel method)
(CubeColourDialog method)
(ShortcutEditor method)
(UltimateListCtrl method)
(ZoomBar method)
DoMouseButtonCommon() (RibbonBar method)
DoMouseMove() (FlatMenuBar method)
DoPopup() (HyperLinkCtrl method)
DoRestoreValue() (PersistenceManager method)
DoSaveValue() (PersistenceManager method)
DoSelectItem() (CustomTreeCtrl method)
DoSendChangingEvent() (FourWaySplitter method)
DoSendEvent() (FloatSpin method)
DoSetSelection() (FlatBookBase method)
(PageContainer method)
DoSetSize() (AuiToolBar method)
(RibbonPage method)
(RibbonPanel method)
(TabFrame method)
DoShow() (InfoBar method)
DoShowHide() (AuiTabContainer method)
DoShowNow() (SuperToolTip method)
DoSizing() (AuiNotebook method)
(TabFrame method)
DoTimerProcessing() (PeakMeterCtrl method)
DoToolbarAction() (FlatMenuBar method)
DragFinish() (UltimateListMainWindow method)
DragImage (class in customtreectrl)
Draw() (AuiDockingGuideWindow method)
(BufferedWindow method), [1]
(ButtonInfo method)
(ButtonPanelText method)
(Control method)
(FlatMenuButton method)
(Indicator method)
(KnobCtrl method)
(PieCtrl method)
(PyImageList method)
(RulerCtrl method)
(Separator method)
(Sizer method)
(SpeedMeter method)
(UltimateListLineData method)
(XLSBackground method)
(XLSBorder method)
(XLSBorderFactory method)
(XLSComment method)
(XLSRenderer method)
(XLSRichText method)
(XLSText method)
DrawAll() (CubeColourDialog method)
DrawAlpha() (CubeColourDialog method)
DrawAlphaShading() (AlphaCtrl method)
DrawArrow() (AuiDockingGuideWindow method)
DrawArrowAccordingToState() (FNBRenderer method)
DrawBackground() (AuiDefaultDockArt method)
(AuiDefaultTabArt method)
(AuiDefaultToolBarArt method)
(AuiDockingGuideWindow method)
(AuiSimpleTabArt method)
DrawBackgroundBitmap() (LabelContainer method)
DrawBitmapArea() (RendererBase method)
DrawBitmapBorders() (RendererBase method)
DrawBitmapShadow() (ArtManager method)
(FMRenderer method)
DrawBorder() (AuiDefaultDockArt method)
(XLSBorder method)
DrawBoundingCircle() (KnobCtrl method)
DrawBright() (CubeColourDialog method)
DrawButton() (ArtManager method)
(AuiDefaultTabArt method)
(AuiDefaultToolBarArt method)
(AuiSimpleTabArt method)
(BPArt method)
(FMRenderer method)
(FMRendererMSOffice2007 method)
(RendererMSOffice2007 method)
(RendererXP method)
(in module flatnotebook)
DrawButtonBarBackground() (RibbonAUIArtProvider method)
(RibbonMSWArtProvider method)
DrawButtonBarButton() (RibbonAUIArtProvider method)
(RibbonMSWArtProvider method)
DrawButtonBarButtonForeground() (RibbonMSWArtProvider method)
DrawButtonBorders() (RendererBase method)
DrawButtonColour() (ArtManager method)
(FMRendererMSOffice2007 method)
(FMRendererVista method)
(RendererMSOffice2007 method)
(RendererXP method)
DrawButtonPanel() (BPArt method)
DrawButtons() (AuiSimpleTabArt method)
(ZoomBar method)
DrawButtonTheme() (ArtManager method)
(RendererXP method)
DrawCaption() (AuiDefaultDockArt method)
(BPArt method)
(ModernDockArt method)
DrawCaptionBackground() (AuiDefaultDockArt method)
(ModernDockArt method)
DrawCheckbox() (UltimateListMainWindow method)
DrawCheckerBoard() (in module cubecolourdialog)
DrawControlLabel() (AuiDefaultToolBarArt method)
DrawCurrent() (TreeListHeaderWindow method)
(UltimateListHeaderWindow method)
DrawDiagonalGradient() (KnobCtrl method)
DrawDiagonals() (XLSBorder method)
DrawDnDArrow() (UltimateListMainWindow method)
DrawDottedLine() (AuiDockingGuideWindow method)
DrawDragHint() (FNBRenderer method)
(PageContainer method)
DrawDragSash() (ArtManager method)
DrawDropDownArrow() (FNBRenderer method)
DrawDropdownArrow() (RibbonMSWArtProvider method)
DrawDropDownButton() (AuiDefaultToolBarArt method)
DrawExternalArc() (SpeedMeter method)
DrawFocusIndicator() (SButton method)
DrawFocusRectangle() (AuiDefaultTabArt method)
(FNBRenderer method)
DrawGalleryBackground() (RibbonAUIArtProvider method)
(RibbonMSWArtProvider method)
DrawGalleryBackgroundCommon() (RibbonMSWArtProvider method)
DrawGalleryButton() (RibbonAUIArtProvider method)
(RibbonMSWArtProvider method)
DrawGalleryItemBackground() (RibbonAUIArtProvider method)
(RibbonMSWArtProvider method)
DrawGradientRectangle() (in module aui.aui_utilities)
DrawGripper() (AuiDefaultDockArt method)
(AuiDefaultToolBarArt method)
DrawHintRect() (AuiManager method)
DrawHorizontalGradient() (CaptionBar method)
(CustomTreeCtrl method)
(UltimateListLineData method)
DrawHorzBand() (PeakMeterCtrl method)
DrawHSB() (CubeColourDialog method)
DrawIcon() (AuiDefaultDockArt method)
(AuiDockingGuideWindow method)
DrawImage() (UltimateListMainWindow method)
DrawInReportMode() (UltimateListLineData method)
DrawInsetCircle() (KnobCtrl method)
DrawLabel() (AuiDefaultToolBarArt method)
(BPArt method)
(LabelContainer method)
(SBitmapButton method)
(SBitmapTextButton method)
(SButton method)
DrawLabels() (ZoomBar method)
DrawLeftArrow() (FNBRenderer method)
DrawLeftMargin() (FMRenderer method)
(FMRendererMSOffice2007 method)
(FMRendererXP method)
DrawLines() (BasePyControl method)
(RGBCube method)
DrawMACCloseButton() (in module aui.aui_utilities)
DrawMainButton() (SButton method)
DrawMarkers() (AlphaCtrl method)
(BasePyControl method)
(BrightCtrl method)
(CubeColourDialog method)
(HSVWheel method)
(RGBCube method)
DrawMenu() (FMRenderer method)
DrawMenuBar() (FMRenderer method)
DrawMenuBarBackground() (FMRenderer method)
(FMRendererMSOffice2007 method)
(FMRendererXP method)
DrawMenuBarBg() (ArtManager method)
(RendererMSOffice2007 method)
(RendererXP method)
DrawMenuBarBorder() (ArtManager method)
DrawMenuBarButton() (FMRenderer method)
(FMRendererMSOffice2007 method)
DrawMenuButton() (FMRenderer method)
(FMRendererMSOffice2007 method)
DrawMenuItem() (FMRenderer method)
DrawMinimisedPanel() (RibbonAUIArtProvider method)
(RibbonMSWArtProvider method)
DrawMinimisedPanelCommon() (RibbonMSWArtProvider method)
DrawMoreButton() (FlatMenuBar method)
DrawOnParent() (RulerCtrl method)
DrawOverflowButton() (AuiDefaultToolBarArt method)
DrawPageBackground() (RibbonAUIArtProvider method)
(RibbonMSWArtProvider method)
DrawPaneButton() (AuiDefaultDockArt method)
(AuiManager method)
(ModernDockArt method)
DrawPanelBackground() (RibbonAUIArtProvider method)
(RibbonMSWArtProvider method)
DrawPanelBorder() (RibbonMSWArtProvider method)
DrawPartialPageBackground() (RibbonMSWArtProvider method)
DrawPartialPageBackground1() (RibbonMSWArtProvider method)
DrawPartialPageBackground2() (RibbonMSWArtProvider method)
DrawPartialPanelBackground() (RibbonAUIArtProvider method)
DrawParts() (PieCtrl method)
DrawPin() (ImageContainerBase method)
DrawPlainBackground() (AuiDefaultToolBarArt method)
DrawProgress() (ProgressGauge method)
DrawReflections() (ZoomBar method)
DrawRegularHover() (LabelContainer method)
DrawResizeHint() (in module aui.framemanager)
DrawRGB() (CubeColourDialog method)
DrawRightArrow() (FNBRenderer method)
DrawSash() (AuiDefaultDockArt method)
DrawSashGripper() (AuiDefaultDockArt method)
DrawScrollButton() (FMRenderer method)
(RibbonAUIArtProvider method)
(RibbonMSWArtProvider method)
DrawSelection() (FlatMenu method)
DrawSeparator() (AuiDefaultToolBarArt method)
(BPArt method)
(FMRenderer method)
DrawSingleColour() (CaptionBar method)
DrawSingleRectangle() (CaptionBar method)
DrawSplitter() (FourWaySplitter method)
DrawTab() (AuiDefaultTabArt method)
(AuiSimpleTabArt method)
(ChromeTabArt method)
(FF2TabArt method)
(FNBRendererDefault method)
(FNBRendererFancy method)
(FNBRendererFirefox2 method)
(FNBRendererRibbonTabs method)
(FNBRendererVC71 method)
(FNBRendererVC8 method)
(RibbonAUIArtProvider method)
(RibbonMSWArtProvider method)
(VC71TabArt method)
(VC8TabArt method)
DrawTabBackground() (FF2TabArt method)
DrawTabCtrlBackground() (RibbonAUIArtProvider method)
(RibbonMSWArtProvider method)
DrawTabs() (FNBRenderer method)
(FNBRendererRibbonTabs method)
(FNBRendererVC8 method)
DrawTabSeparator() (RibbonAUIArtProvider method)
(RibbonMSWArtProvider method)
DrawTabsLine() (FNBRenderer method)
DrawTabX() (FNBRenderer method)
DrawTags() (KnobCtrl method)
DrawText() (ToasterBoxWindow method)
DrawTextAndBitmap() (ArtManager method)
DrawTextFormatted() (UltimateListHeaderWindow method)
(UltimateListLineData method)
DrawThumbnail() (ScrolledThumbnail method)
DrawTool() (RibbonAUIArtProvider method)
(RibbonMSWArtProvider method)
DrawToolbar() (FlatMenuBar method)
DrawToolBarBackground() (RibbonAUIArtProvider method)
(RibbonMSWArtProvider method)
DrawToolBarBg() (ArtManager method)
(FMRenderer method)
(FMRendererMSOffice2007 method)
(FMRendererXP method)
(RendererMSOffice2007 method)
(RendererXP method)
DrawToolbarItem() (FlatMenuBar method)
DrawToolbarSeparator() (FMRenderer method)
DrawToolGroupBackground() (RibbonAUIArtProvider method)
(RibbonMSWArtProvider method)
DrawTrackSplitter() (FourWaySplitter method)
DrawTreeItemButton() (in module customtreectrl)
DrawVertBand() (PeakMeterCtrl method)
DrawVerticalGradient() (CaptionBar method)
(CustomTreeCtrl method)
(UltimateListLineData method)
DrawVistaRectangle() (CustomTreeCtrl method)
(UltimateListLineData method)
DrawWebHover() (LabelContainer method)
DrawX() (FNBRenderer method)
DropShadow() (ArtManager method)
(ToolTipWindowBase method)

E

Edit() (CustomTreeCtrl method)
EditCtrl (class in hypertreelist)
EditLabel() (CustomTreeCtrl method)
(HyperTreeList method)
(TreeListMainWindow method)
(UltimateListCtrl method)
(UltimateListMainWindow method)
EditTab() (AuiNotebook method)
EditTextCtrl (class in hypertreelist)
Enable() (AquaButton method)
(ButtonInfo method)
(Control method)
(FlatMenuItem method)
(FlatToolbarItem method)
(GenericTreeItem method)
(GradientButton method)
(SButton method)
(UltimateListItem method)
(UltimateListItemAttr method)
(UltimateListItemData method)
(ZoomBarImage method)
EnableAbort() (PyProgress method)
EnableButton() (RibbonButtonBar method)
(ZoomBar method)
EnableChildren() (CustomTreeCtrl method)
(HyperTreeList method)
EnableClose() (PyProgress method)
EnableDragging() (ScrolledThumbnail method)
EnableItem() (CustomTreeCtrl method)
(HyperTreeList method)
(TreeListMainWindow method)
(UltimateListCtrl method)
(UltimateListMainWindow method)
EnableRestoring() (PersistenceManager method)
EnableRollover() (HyperLinkCtrl method)
EnableSaving() (PersistenceManager method)
EnableSelectionGradient() (CustomTreeCtrl method)
(HyperTreeList method)
(UltimateListCtrl method)
(UltimateListMainWindow method)
EnableSelectionVista() (CustomTreeCtrl method)
(HyperTreeList method)
(UltimateListCtrl method)
(UltimateListMainWindow method)
EnableTab() (AuiNotebook method)
(AuiTabContainer method)
(FlatBookBase method)
(FlatNotebook method)
(ImageContainerBase method)
(ImageInfo method)
(PageContainer method)
(PageInfo method)
EnableTip() (BalloonTip method)
(SuperToolTip method)
EnableTool() (AuiToolBar method)
EnableToolTips() (ScrolledThumbnail method)
EndDialog() (GenericMessageDialog method)
EnsureVisible() (AuiNotebook method)
(CustomTreeCtrl method)
(FlatNotebook method)
(HyperTreeList method)
(RibbonGallery method)
(UltimateListCtrl method)
(UltimateListMainWindow method)
EscapeDelimiters() (in module aui.framemanager)
EventFlagsToSelType() (in module customtreectrl)
Excel (class in xlsgrid)
ExchangeWindows() (FourWaySplitter method)
Exist() (FlatMenuItemGroup method)
Expand() (CaptionBar method)
(CustomTreeCtrl method)
(FoldPanelBar method)
(FoldPanelItem method)
(GenericTreeItem method)
(HyperTreeList method)
(PyCollapsiblePane method)
ExpandAll() (CustomTreeCtrl method)
(HyperTreeList method)
ExpandAllChildren() (CustomTreeCtrl method)
(HyperTreeList method)
ExpandPanels() (RibbonPage method)
ExtendWidth() (GeometryInfo method)
ExtractLink() (in module supertooltip)

F

FadeOut() (AuiFloatingFrame method)
FetchButtonSizeInfo() (RibbonButtonBar method)
FF2TabArt (class in aui.tabart)
FileDirDialogHandler (class in persist.persist_handlers)
FileDirPickerHandler (class in persist.persist_handlers)
FileHistory (class in flatmenu)
FileHistoryHandler (class in persist.persist_handlers)
FillArray() (CustomTreeCtrl method)
FillCaptionBackground() (CaptionBar method)
FillGradientColour() (BPArt method)
FillStockBitmaps() (ArtManager method)
FillVC8GradientColour() (FNBRendererVC8 method)
(VC8TabArt method)
Find() (PersistenceManager method)
FindC() (in module cubecolourdialog)
FindControl() (AuiToolBar method)
FindDocks() (in module aui.framemanager)
FindFocusDescendant() (in module aui.aui_utilities)
FindHandler() (in module persist.persist_handlers)
FindItem() (CustomTreeCtrl method)
(FlatMenu method)
(HyperTreeList method)
(UltimateListCtrl method)
(UltimateListMainWindow method)
FindItemAtPos() (UltimateListCtrl method)
(UltimateListMainWindow method)
FindItemById() (SwitcherItems method)
FindItemByName() (SwitcherItems method)
FindItemData() (UltimateListCtrl method)
(UltimateListMainWindow method)
FindLinearTickSizes() (RulerCtrl method)
FindMenu() (FlatMenuBar method)
FindMenuItem() (FlatMenuBar method)
FindMenuItemPos() (FlatMenu method)
FindMenuItemPosSimple() (FlatMenu method)
FindNextActiveTab() (AuiNotebook method)
FindOppositeDocks() (in module aui.framemanager)
FindPaneInDock() (in module aui.framemanager)
FindReplaceHandler (class in persist.persist_handlers)
FindSimilarInstance() (RibbonButtonBarLayout method)
FindTab() (AuiNotebook method)
FindTool() (AuiToolBar method)
FindToolByIndex() (AuiToolBar method)
FindToolByLabel() (AuiToolBar method)
FindToolForPosition() (AuiToolBar method)
FindToolForPositionWithPacking() (AuiToolBar method)
Finish() (EditCtrl method)
(TabTextCtrl method)
(TreeTextCtrl method)
(UltimateListTextCtrl method)
FireEvent() (AuiManager method)
(PageContainer method)
FireShortcutChanged() (ListShortcut method)
FireShortcutChanging() (ListShortcut method)
FirstColourUsed() (CaptionBarStyle method)
Fixed() (AuiPaneInfo method)
FixedPoint (class in floatspin)
FixTextSize() (ImageContainerBase method)
FlatBookBase (class in labelbook)
FlatImageBook (class in labelbook)
FlatMenu (class in flatmenu)
flatmenu (module)
FlatMenuBar (class in flatmenu)
FlatMenuBase (class in flatmenu)
FlatMenuButton (class in flatmenu)
FlatMenuEvent (class in flatmenu)
FlatMenuItem (class in flatmenu)
FlatMenuItemGroup (class in flatmenu)
FlatNotebook (class in flatnotebook)
flatnotebook (module)
FlatNotebookCompatible (class in flatnotebook)
FlatNotebookDragEvent (class in flatnotebook)
FlatNotebookEvent (class in flatnotebook)
FlatToolbarItem (class in flatmenu)
FlexibleLayout() (ButtonPanel method)
Float() (AuiPaneInfo method)
Floatable() (AuiPaneInfo method)
FloatingPosition() (AuiPaneInfo method)
FloatingSize() (AuiPaneInfo method)
FloatPage() (AuiNotebook method)
FloatSpin (class in floatspin)
floatspin (module)
FloatSpinEvent (class in floatspin)
FloatTextCtrl (class in floatspin)
FlyOut() (AuiFloatingFrame method)
(AuiPaneInfo method)
FMCustomizeDlg (class in fmcustomizedlg)
fmcustomizedlg (module)
FMRenderer (class in flatmenu)
FMRendererMgr (class in flatmenu)
FMRendererMSOffice2007 (class in flatmenu)
FMRendererVista (class in flatmenu)
FMRendererXP (class in flatmenu)
FMTitlePanel (class in fmcustomizedlg)
FNBDragInfo (class in flatnotebook)
FNBDropSource (class in flatnotebook)
FNBDropTarget (class in flatnotebook)
FNBRenderer (class in flatnotebook)
FNBRendererDefault (class in flatnotebook)
FNBRendererFancy (class in flatnotebook)
FNBRendererFirefox2 (class in flatnotebook)
FNBRendererMgr (class in flatnotebook)
FNBRendererRibbonTabs (class in flatnotebook)
FNBRendererVC71 (class in flatnotebook)
FNBRendererVC8 (class in flatnotebook)
Focus() (UltimateListCtrl method)
FocusHandler (class in flatmenu)
FoldPanelBar (class in foldpanelbar)
foldpanelbar (module)
FoldPanelBarHandler (class in persist.persist_handlers)
FoldPanelItem (class in foldpanelbar)
FoldWindowItem (class in foldpanelbar)
Font (TabNavigatorProps attribute)
FontDialogHandler (class in persist.persist_handlers)
FontFromFont() (in module ribbon.art_aui)
(in module shortcuteditor)
(in module xlsgrid)
FontPickerHandler (class in persist.persist_handlers)
FormatCell() (XLSGrid method)
FormatColour() (in module flatnotebook)
FormatString() (XLSText method)
FourWaySplitter (class in fourwaysplitter)
fourwaysplitter (module)
FourWaySplitterEvent (class in fourwaysplitter)
frac() (FixedPoint method)
FrameColour() (ArtManager method)
Free() (artmanager.ArtManager class method)
(persist.persistencemanager.PersistenceManager class method)
Freeze() (CustomTreeCtrl method)
FromAcceleratorTable() (ShortcutEditor method)
FromMenuBar() (ShortcutEditor method)
FromMenuItem() (Shortcut method)

G

GenerateSelectionEvent() (MultiColumnListCtrl method)
GenericMessageDialog (class in genericmessagedialog)
genericmessagedialog (module)
GenericTreeItem (class in customtreectrl)
GeometryInfo (class in ultimatelistctrl)
Get() (artmanager.ArtManager class method)
(Shortcut method)
(persist.persistencemanager.PersistenceManager class method)
Get3StateValue() (GenericTreeItem method)
get_precision() (FixedPoint method)
GetAccelArray() (FlatMenu method)
GetAccelerator() (Shortcut method)
(ShortcutEvent method)
GetAcceleratorEntry() (FlatMenuItem method)
GetAccelIndex() (ArtManager method)
(in module flatmenu)
GetAccelString() (FlatMenuItem method)
GetAccelTable() (FlatMenu method)
GetActiveItem() (RibbonGallery method)
GetActivePage() (AuiTabContainer method)
(RibbonBar method)
GetActiveTabColour() (FlatNotebook method)
GetActiveTabCtrl() (AuiNotebook method)
GetActiveTabTextColour() (FlatNotebook method)
GetActiveToolbarItem() (FlatMenuBar method)
GetAGWFlags() (AuiDefaultTabArt method)
(AuiDefaultToolBarArt method)
(AuiManager method)
(AuiSimpleTabArt method)
(AuiTabContainer method)
GetAGWWindowStyleFlag() (AuiNotebook method)
(AuiToolBar method)
(CubeColourDialog method)
(CustomTreeCtrl method)
(FlatBookBase method)
(FlatNotebook method)
(FourWaySplitter method)
(HyperTreeList method)
(PageContainer method)
(PeakMeterCtrl method)
(PyCollapsiblePane method)
(RibbonBar method)
(UltimateListCtrl method)
GetAlign() (UltimateListItem method)
GetAlignBuffer() (ArtManager method)
GetAlignment() (AuiToolBarItem method)
(ButtonPanel method)
(TreeListColumnInfo method)
GetAllItems() (FlatMenu method)
GetAllPanes() (AuiManager method)
GetAngle() (PieCtrl method)
GetAngleFromCoord() (KnobCtrl method)
GetAngleOfRotation() (SButton method)
GetAngleRange() (SpeedMeter method)
GetAngularRange() (KnobCtrl method)
GetAnimationStep() (AuiManager method)
GetArcColour() (SpeedMeter method)
GetArtProvider() (AuiManager method)
(AuiNotebook method)
(AuiTabContainer method)
(AuiToolBar method)
(RibbonControl method)
GetAttr() (UltimateListItemData method)
(UltimateListLineData method)
(XLSCell method)
(XLSTable method)
GetAttributes() (AuiManager method)
(GenericTreeItem method)
(UltimateListItem method)
GetAuiManager() (AuiNotebook method)
(AuiToolBar method)
GetAutoNotebookStyle() (AuiManager method)
GetAutoNotebookTabArt() (AuiManager method)
GetBackColour() (PieCtrl method)
(PieCtrlLegend method)
GetBackground() (PieCtrl method)
GetBackgroundBitmap() (FlatMenu method)
GetBackgroundColour() (AquaButton method)
(FlatMenuBar method)
(SwitcherItems method)
(TreeItemAttr method)
(UltimateListCtrl method)
(UltimateListItem method)
(UltimateListItemAttr method)
(UltimateListItemData method)
GetBackgroundImage() (CustomTreeCtrl method)
(HyperTreeList method)
(UltimateListCtrl method)
(UltimateListMainWindow method)
GetBalloonColour() (BalloonTip method)
GetBalloonIcon() (BalloonTip method)
GetBalloonMessage() (BalloonTip method)
GetBalloonShape() (BalloonTip method)
GetBalloonTipStyle() (BalloonTip method)
GetBalloonTitle() (BalloonTip method)
GetBar() (CaptionBarEvent method)
(RibbonButtonBarEvent method)
(RibbonToolBarEvent method)
GetBarColor() (PyGauge method)
GetBarColour() (ImageBar method)
(PyGauge method)
(ZoomBar method)
GetBarGradient() (PyGauge method)
GetBarPlacement() (InfoBar method)
GetBarTabWidth() (RibbonAUIArtProvider method)
(RibbonMSWArtProvider method)
GetBarText() (ButtonPanel method)
GetBaseColour() (in module aui.aui_utilities)
GetBaseId() (FileHistory method)
GetBestColumnWidth() (TreeListMainWindow method)
GetBestSize() (ButtonInfo method)
(ButtonPanelText method)
(Control method)
(Separator method)
(Sizer method)
GetBestTabCtrlSize() (AuiDefaultTabArt method)
(AuiSimpleTabArt method)
GetBitmap() (AuiToolBarItem method)
(ButtonInfo method)
(FlatMenuItem method)
(FlatToolbarItem method)
(ImageBar method)
(PyImageList method)
(RibbonGalleryItem method)
(Shortcut method)
(SwitcherItem method)
(Thumb method)
(ZoomBarImage method)
GetBitmapDisabled() (SBitmapButton method)
GetBitmapFocus() (SBitmapButton method)
GetBitmapLabel() (SBitmapButton method)
GetBitmapSelected() (SBitmapButton method)
GetBitmapStartLocation() (ArtManager method)
GetBodyImage() (SuperToolTip method)
GetBold() (HyperLinkCtrl method)
GetBorder() (PyCollapsiblePane method)
GetBorderColor() (PyGauge method)
GetBorderColour() (FlatNotebook method)
(PyGauge method)
GetBorderPadding() (PyGauge method)
GetBorderPen() (CustomTreeCtrl method)
(HyperTreeList method)
GetBorderXWidth() (FlatMenu method)
GetBorderYWidth() (FlatMenu method)
GetBottomEndColour() (GradientButton method)
GetBottomGradientColor() (SuperToolTip method)
GetBottomGradientColour() (SuperToolTip method)
GetBottomLeft() (FourWaySplitter method)
GetBottomRight() (FourWaySplitter method)
GetBottomStartColour() (GradientButton method)
GetBoundingColour() (KnobCtrl method)
GetBoundingRect() (CustomTreeCtrl method)
(HyperTreeList method)
GetBounds() (RulerCtrl method)
GetBPArt() (ButtonPanel method)
GetBreakColumn() (SwitcherItem method)
GetBtnLabel() (PyCollapsiblePane method)
GetButton() (AuiManagerEvent method)
(PyCollapsiblePane method)
GetButtonBarButtonSize() (RibbonMSWArtProvider method)
GetButtonColour() (SButton method)
GetButtonFont() (PyCollapsiblePane method)
GetButtonObj() (AquaButtonEvent method)
(GradientButtonEvent method)
(SButtonEvent method)
GetButtonsAreaLength() (FNBRenderer method)
GetButtonsImageList() (CustomTreeCtrl method)
(HyperTreeList method)
GetButtonSize() (ZoomBar method)
GetById() (Shortcut method)
GetCacheFrom() (CommandListEvent method)
GetCacheTo() (CommandListEvent method)
GetCaption() (GenericMessageDialog method)
(ImageInfo method)
(PageInfo method)
(ScrolledThumbnail method)
(Thumb method)
GetCaptionColour() (CaptionBarStyle method)
GetCaptionFont() (CaptionBarStyle method)
(ScrolledThumbnail method)
GetCaptionHeight() (ScrolledThumbnail method)
GetCaptionLength() (FoldPanelItem method)
GetCaptionLinesCount() (Thumb method)
GetCaptionStyle() (CaptionBar method)
(CaptionBarStyle method)
(FoldPanelBar method)
(FoldPanelItem method)
GetCenterZoom() (ZoomBar method)
GetCheckboxImageSize() (UltimateListMainWindow method)
GetCheckedImage() (GenericTreeItem method)
GetCheckedState() (TreeCtrlHandler method)
GetCheckedStateOfChildren() (TreeCtrlHandler method)
GetCheckedStateOfItem() (TreeCtrlHandler method)
GetChildren() (GenericTreeItem method)
GetChildrenCount() (CustomTreeCtrl method)
(GenericTreeItem method)
(HyperTreeList method)
GetClassDefaultAttributes() (customtreectrl.CustomTreeCtrl class method)
(UltimateListCtrl method)
(hypertreelist.HyperTreeList class method)
GetClickPoint() (CommandToolBarEvent method)
GetClientData() (RibbonGalleryItem method)
GetClientRect() (FlatMenuButton method)
GetCloseButtonBitmap() (in module infobar)
GetCmdId() (MenuEntryInfo method)
GetColor() (AuiDefaultDockArt method)
(BPArt method)
GetColour() (AuiDefaultDockArt method)
(BPArt method)
(LabelBook method)
(LabelContainer method)
(PageInfo method)
(PiePart method)
(RibbonAUIArtProvider method)
(RibbonMSWArtProvider method)
(TreeListColumnInfo method)
(UltimateListItemData method)
GetColourData() (CubeColourDialog method)
GetColours() (HyperLinkCtrl method)
GetColoursAccordingToState() (FMRenderer method)
(RendererMSOffice2007 method)
GetColourScheme() (RibbonMSWArtProvider method)
GetColourSchemes() (ArtManager method)
GetColPos() (SwitcherItem method)
GetColumn() (CommandListEvent method)
(HyperTreeList method)
(TreeListHeaderWindow method)
(UltimateListCtrl method)
(UltimateListItem method)
(UltimateListMainWindow method)
GetColumnAlignment() (HyperTreeList method)
(TreeListHeaderWindow method)
GetColumnColour() (HyperTreeList method)
(TreeListHeaderWindow method)
GetColumnCount() (HyperTreeList method)
(SwitcherItems method)
(TreeListHeaderWindow method)
(TreeListMainWindow method)
(UltimateListCtrl method)
(UltimateListMainWindow method)
GetColumnCustomRenderer() (UltimateListMainWindow method)
GetColumnFont() (HyperTreeList method)
GetColumnImage() (HyperTreeList method)
GetColumnText() (HyperTreeList method)
(TreeListHeaderWindow method)
GetColumnWidth() (HyperTreeList method)
(TreeListHeaderWindow method)
(UltimateListCtrl method)
(UltimateListMainWindow method)
GetCommandId() (AuiCommandCapture method)
(ToolbarCommandCapture method)
GetComment() (XLSCell method)
GetCommentsRange() (Excel method)
GetConfigurationHandler() (PersistenceManager method)
GetConnectionPen() (CustomTreeCtrl method)
(HyperTreeList method)
GetContainer() (FNBDragInfo method)
GetContextMenu() (FlatMenuItem method)
GetControlBmp() (CustomTreeCtrl method)
(UltimateListMainWindow method)
GetControls() (ButtonPanel method)
GetCount() (CustomTreeCtrl method)
(FileHistory method)
(FoldPanelBar method)
(RibbonGallery method)
GetCountPerPage() (UltimateListCtrl method)
(UltimateListMainWindow method)
GetCreationDate() (Thumb method)
GetCurrentCheckedImage() (GenericTreeItem method)
GetCurrentImage() (GenericTreeItem method)
(TreeListItem method)
GetCurrentItem() (HyperTreeList method)
(TreeListMainWindow method)
GetCurrentPage() (AuiNotebook method)
(FlatBookBase method)
(FlatNotebook method)
GetCustomCancelBitmap() (GenericMessageDialog method)
GetCustomCancelLabel() (GenericMessageDialog method)
GetCustomControl() (FlatToolbarItem method)
GetCustomHelpBitmap() (GenericMessageDialog method)
GetCustomHelpLabel() (GenericMessageDialog method)
GetCustomNoBitmap() (GenericMessageDialog method)
GetCustomNoLabel() (GenericMessageDialog method)
GetCustomOKBitmap() (GenericMessageDialog method)
GetCustomOKLabel() (GenericMessageDialog method)
GetCustomPage() (FlatNotebook method)
GetCustomRenderer() (UltimateListHeaderData method)
(UltimateListItem method)
(UltimateListItemData method)
GetCustomYesBitmap() (GenericMessageDialog method)
GetCustomYesLabel() (GenericMessageDialog method)
GetData() (CommandListEvent method)
(GenericTreeItem method)
(UltimateListItem method)
getDataBL() (in module thumbnailctrl)
getDataSH() (in module thumbnailctrl)
getDataTR() (in module thumbnailctrl)
GetDC() (AuiManagerEvent method)
GetDefaultAttributes() (AquaButton method)
(GradientButton method)
GetDefaultBorder() (AuiNotebook method)
(AuiTabCtrl method)
(InfoBar method)
(RibbonBar method)
(RibbonButtonBar method)
(RibbonGallery method)
(RibbonPage method)
(RibbonPanel method)
(RibbonToolBar method)
(UltimateListCtrl method)
GetDefaultCancelBitmap() (GenericMessageDialog method)
GetDefaultCancelLabel() (GenericMessageDialog method)
GetDefaultFontData() (XLSGrid method)
GetDefaultHelpBitmap() (GenericMessageDialog method)
GetDefaultHelpLabel() (GenericMessageDialog method)
GetDefaultNoBitmap() (GenericMessageDialog method)
GetDefaultNoLabel() (GenericMessageDialog method)
GetDefaultOKBitmap() (GenericMessageDialog method)
GetDefaultOKLabel() (GenericMessageDialog method)
GetDefaultValue() (FloatSpin method)
GetDefaultYesBitmap() (GenericMessageDialog method)
GetDefaultYesLabel() (GenericMessageDialog method)
GetDescription() (SwitcherItem method)
GetDigits() (FloatSpin method)
GetDirection() (SpeedMeter method)
GetDisabledBitmap() (AuiToolBarItem method)
(FlatMenuItem method)
(FlatToolbarItem method)
GetDisabledColor() (AquaButton method)
GetDisabledColour() (AquaButton method)
(CustomTreeCtrl method)
(HyperTreeList method)
GetDisabledTextColour() (UltimateListCtrl method)
(UltimateListMainWindow method)
GetDispatched() (CommandNotebookEvent method)
GetDockingImage() (in module aui.aui_utilities)
GetDockPixelOffset() (AuiManager method)
GetDockSizeConstraint() (AuiManager method)
GetDownButtonState() (RibbonGallery method)
GetdragcursorBitmap() (in module ultimatelistctrl)
GetdragcursorData() (in module ultimatelistctrl)
GetdragcursorImage() (in module ultimatelistctrl)
GetDragSource() (CommandNotebookEvent method)
GetDrawFooterLine() (SuperToolTip method)
GetDrawHeaderLine() (SuperToolTip method)
GetDrawingParent() (RulerCtrl method)
GetDropArrowButtonPos() (FNBRenderer method)
GetDropShadow() (ScrolledThumbnail method)
(SuperToolTip method)
GetDropTarget() (UltimateListCtrl method)
GetDummyLine() (UltimateListMainWindow method)
GetEditControl() (CustomTreeCtrl method)
(HyperTreeList method)
(UltimateListCtrl method)
GetEffectDuration() (InfoBar method)
GetElementSize() (AuiDefaultToolBarArt method)
GetEllipseAxis() (SButton method)
GetEnabled() (AuiNotebook method)
(AuiTabContainer method)
(FlatBookBase method)
(FlatNotebook method)
(ImageContainerBase method)
(ImageInfo method)
(PageContainer method)
(PageInfo method)
GetEndDelay() (BalloonTip method)
(SuperToolTip method)
GetEndX() (FNBRendererVC8 method)
GetExpandedDummy() (RibbonPanel method)
GetExpandedPanel() (RibbonPanel method)
GetExpandedPosition() (RibbonPanel method)
GetExpanderDimensions() (PyCollapsiblePane method)
GetExpansionState() (TreeCtrlHandler method)
GetExpansionStateOfChildren() (TreeCtrlHandler method)
GetExpansionStateOfItem() (TreeCtrlHandler method)
GetExtendedMessage() (GenericMessageDialog method)
GetExtensionButtonState() (RibbonGallery method)
GetExtraNavigationKey() (MultiColumnListCtrl method)
(SwitcherDialog method)
GetFalloffEffect() (PeakMeterCtrl method)
GetFileName() (Thumb method)
GetFileSize() (Thumb method)
GetFilledColour() (ProgressPie method)
GetFillerColour() (SpeedMeter method)
GetFirstChild() (CustomTreeCtrl method)
(HyperTreeList method)
(Shortcut method)
GetFirstColour() (CaptionBarStyle method)
GetFirstExpandedItem() (HyperTreeList method)
(TreeListMainWindow method)
GetFirstGradientColour() (CustomTreeCtrl method)
(HyperTreeList method)
(KnobCtrl method)
(ProgressGauge method)
(PyProgress method)
(SpeedMeter method)
(UltimateListCtrl method)
(UltimateListMainWindow method)
GetFirstSelected() (UltimateListCtrl method)
GetFirstVisibleItem() (CustomTreeCtrl method)
(HyperTreeList method)
(TreeListMainWindow method)
GetFlags() (RibbonMSWArtProvider method)
GetFocusedItem() (UltimateListCtrl method)
GetFoldPanel() (FoldPanelBar method)
GetFoldStatus() (CaptionBarEvent method)
GetFont() (ArtManager method)
(AuiDefaultDockArt method)
(AuiDefaultToolBarArt method)
(BPArt method)
(FlatMenuItem method)
(FloatSpin method)
(RendererBase method)
(RibbonMSWArtProvider method)
(SwitcherItem method)
(TreeItemAttr method)
(TreeListColumnInfo method)
(UltimateListHeaderData method)
(UltimateListItem method)
(UltimateListItemAttr method)
(UltimateListItemData method)
GetFontBold() (FlatBookBase method)
GetFontSizeMultiple() (FlatBookBase method)
GetFooter() (SuperToolTip method)
GetFooterAlign() (UltimateListItem method)
GetFooterBackgroundColour() (UltimateListItem method)
(UltimateListItemAttr method)
GetFooterBitmap() (SuperToolTip method)
GetFooterFont() (SuperToolTip method)
(UltimateListItem method)
(UltimateListItemAttr method)
GetFooterFormat() (UltimateListHeaderData method)
(UltimateListItem method)
GetFooterHeight() (UltimateListCtrl method)
GetFooterImage() (UltimateListHeaderData method)
(UltimateListItem method)
GetFooterKind() (UltimateListHeaderData method)
(UltimateListItem method)
GetFooterText() (UltimateListItem method)
GetFooterTextColour() (UltimateListItem method)
(UltimateListItemAttr method)
GetForegroundColour() (AquaButton method)
(UltimateListCtrl method)
GetFormat() (FloatSpin method)
(RulerCtrl method)
(UltimateListHeaderData method)
(UltimateListItem method)
GetFrame() (AuiManager method)
GetFullFileName() (Thumb method)
GetFullMessage() (GenericMessageDialog method)
GetGallery() (RibbonGalleryEvent method)
GetGalleryClientSize() (RibbonMSWArtProvider method)
GetGalleryItem() (RibbonGalleryEvent method)
GetGallerySize() (RibbonMSWArtProvider method)
GetGaugeBackground() (ProgressGauge method)
(PyProgress method)
GetGaugeProportion() (ProgressGauge method)
(PyProgress method)
GetGaugeSteps() (ProgressGauge method)
(PyProgress method)
GetGlobalPopupMenu() (ScrolledThumbnail method)
GetGradientColourBorder() (FlatNotebook method)
GetGradientColourFrom() (FlatNotebook method)
GetGradientColourTo() (FlatNotebook method)
GetGradientStyle() (CustomTreeCtrl method)
(HyperTreeList method)
(UltimateListCtrl method)
(UltimateListMainWindow method)
GetGradientType() (BPArt method)
GetGripperVisible() (AuiToolBar method)
GetGroup() (FlatToolbarItem method)
GetHandColour() (SpeedMeter method)
GetHandStyle() (SpeedMeter method)
GetHeader() (SuperToolTip method)
GetHeaderBitmap() (SuperToolTip method)
GetHeaderFont() (SuperToolTip method)
GetHeaderHeight() (UltimateListCtrl method)
GetHeaderWidth() (UltimateListMainWindow method)
GetHeaderWindow() (HyperTreeList method)
GetHeight() (FlatMenuItem method)
(GenericTreeItem method)
(PieCtrl method)
(UltimateListItemData method)
(UltimateListLineData method)
GetHeightForPageHeight() (AuiNotebook method)
GetHelp() (FlatMenuItem method)
GetHideEffect() (InfoBar method)
GetHighlightBrush() (UltimateListMainWindow method)
GetHighlightPointed() (ScrolledThumbnail method)
GetHilightFocusColour() (CustomTreeCtrl method)
(HyperTreeList method)
GetHilightNonFocusColour() (CustomTreeCtrl method)
(HyperTreeList method)
GetHistoryFile() (FileHistory method)
GetHorizontalBorder() (PieCtrlLegend method)
GetHotBitmap() (FlatMenuItem method)
GetHoverBitmap() (AuiToolBarItem method)
GetHoverColor() (AquaButton method)
GetHoverColour() (AquaButton method)
GetHoveredItem() (RibbonGallery method)
GetHSVAColour() (CubeColourDialog method)
GetHyperlinkFont() (SuperToolTip method)
GetHyperTextFont() (CustomTreeCtrl method)
(HyperTreeList method)
(UltimateListCtrl method)
(UltimateListMainWindow method)
GetHyperTextNewColour() (CustomTreeCtrl method)
(HyperTreeList method)
(UltimateListCtrl method)
(UltimateListMainWindow method)
GetHyperTextVisitedColour() (CustomTreeCtrl method)
(HyperTreeList method)
(UltimateListCtrl method)
(UltimateListMainWindow method)
GetIcon() (PyImageList method)
(RibbonPage method)
GetId() (AuiToolBarItem method)
(ButtonInfo method)
(Control method)
(FlatMenuItem method)
(FlatToolbarItem method)
(Indicator method)
(Shortcut method)
(SwitcherItem method)
(Thumb method)
(UltimateListItem method)
GetIdxFromWindow() (AuiTabContainer method)
GetImage() (CommandListEvent method)
(GenericTreeItem method)
(Thumb method)
(TreeListColumnInfo method)
(TreeListItem method)
(UltimateListHeaderData method)
(UltimateListItem method)
(UltimateListItemData method)
(UltimateListLineData method)
GetImageCount() (PyImageList method)
GetImageIndex() (ImageInfo method)
(PageInfo method)
(Shortcut method)
GetImageList() (AuiNotebook method)
(CustomTreeCtrl method)
(FlatBookBase method)
(FlatNotebook method)
(HyperTreeList method)
(ImageContainerBase method)
(PageContainer method)
(UltimateListCtrl method)
GetImageListCheck() (CustomTreeCtrl method)
(HyperTreeList method)
GetImageSize() (ImageContainerBase method)
(Indicator method)
(UltimateListMainWindow method)
GetIncrement() (FloatSpin method)
GetIndent() (CustomTreeCtrl method)
(HyperTreeList method)
GetIndentSize() (AuiDefaultTabArt method)
(AuiSimpleTabArt method)
GetIndex() (CommandListEvent method)
GetIndexForFocus() (SwitcherItems method)
GetIndexOfItem() (TreeCtrlHandler method)
GetIndicator() (RulerCtrl method)
GetIndicatorBitmap() (in module rulerctrl)
GetIndicatorData() (in module rulerctrl)
GetIndicatorImage() (in module rulerctrl)
GetInternalFrameRect() (in module aui.framemanager)
GetIntersection() (SpeedMeter method)
GetIntervalColours() (SpeedMeter method)
GetIntervals() (SpeedMeter method)
GetInvisibleMenuItemCount() (FlatMenuBar method)
GetInvisibleToolbarItemCount() (FlatMenuBar method)
GetIsDown() (SButtonEvent method)
GetIsGroup() (SwitcherItem method)
GetItem() (CommandListEvent method)
(CommandTreeEvent method)
(RibbonGallery method)
(ScrolledThumbnail method)
(SwitcherItems method)
(UltimateListCtrl method)
(UltimateListHeaderData method)
(UltimateListItemData method)
(UltimateListLineData method)
(UltimateListMainWindow method)
GetItem3StateValue() (CustomTreeCtrl method)
(HyperTreeList method)
GetItemBackgroundColour() (CustomTreeCtrl method)
(HyperTreeList method)
(UltimateListCtrl method)
GetItemChildren() (TreeCtrlHandler method)
GetItemClientData() (RibbonGallery method)
GetItemCount() (ScrolledThumbnail method)
(SwitcherItems method)
(UltimateListCtrl method)
(UltimateListMainWindow method)
GetItemCustomRenderer() (UltimateListCtrl method)
(UltimateListMainWindow method)
GetItemData() (UltimateListCtrl method)
GetItemFont() (CustomTreeCtrl method)
(FlatMenu method)
(HyperTreeList method)
(SwitcherItems method)
(UltimateListCtrl method)
GetItemHeight() (FlatMenu method)
GetItemIdentity() (ListShortcut method)
(TreeCtrlHandler method)
GetItemImage() (CustomTreeCtrl method)
(HyperTreeList method)
(TreeListMainWindow method)
GetItemIndex() (ScrolledThumbnail method)
GetItemKind() (UltimateListCtrl method)
(UltimateListMainWindow method)
GetItemLeftImage() (CustomTreeCtrl method)
GetItemOverFlow() (UltimateListCtrl method)
(UltimateListMainWindow method)
GetItemParent() (CustomTreeCtrl method)
(HyperTreeList method)
GetItemPos() (FoldPanelItem method)
GetItemPosition() (UltimateListCtrl method)
(UltimateListMainWindow method)
GetItemPyData() (CustomTreeCtrl method)
(HyperTreeList method)
(UltimateListCtrl method)
GetItemRect() (CommandToolBarEvent method)
(UltimateListCtrl method)
(UltimateListMainWindow method)
GetItems() (MultiColumnListCtrl method)
GetItemSize() (ButtonPanel method)
(CustomTreeCtrl method)
GetItemSpacing() (UltimateListCtrl method)
(UltimateListMainWindow method)
GetItemState() (UltimateListCtrl method)
(UltimateListMainWindow method)
GetItemText() (CustomTreeCtrl method)
(HyperTreeList method)
(TreeListMainWindow method)
(UltimateListCtrl method)
(UltimateListMainWindow method)
GetItemTextColour() (CustomTreeCtrl method)
(FlatMenu method)
(HyperTreeList method)
(UltimateListCtrl method)
GetItemTextSize() (UltimateListMainWindow method)
GetItemType() (CustomTreeCtrl method)
(HyperTreeList method)
GetItemVisited() (CustomTreeCtrl method)
(HyperTreeList method)
(UltimateListCtrl method)
(UltimateListMainWindow method)
GetItemWidth() (TreeListMainWindow method)
GetItemWidthWithImage() (UltimateListMainWindow method)
GetItemWindow() (CustomTreeCtrl method)
(HyperTreeList method)
(TreeListMainWindow method)
(UltimateListCtrl method)
(UltimateListMainWindow method)
GetItemWindowEnabled() (CustomTreeCtrl method)
(HyperTreeList method)
(TreeListMainWindow method)
(UltimateListCtrl method)
(UltimateListMainWindow method)
GetKey() (PersistenceManager method)
GetKeyCode() (CommandListEvent method)
(CommandTreeEvent method)
GetKeyEvent() (CommandTreeEvent method)
GetKind() (AbstractHandler method)
(AuiToolBarItem method)
(ButtonInfo method)
(FlatMenuItem method)
(PersistentObject method)
(UltimateListHeaderData method)
(UltimateListItem method)
(UltimateListItemData method)
(UltimateListLineData method)
GetKnobRadius() (KnobCtrl method)
GetLabel() (AuiToolBarItem method)
(CommandListEvent method)
(CommandNotebookEvent method)
(CommandTreeEvent method)
(FlatMenu method)
(FlatMenuItem method)
(FlatToolbarItem method)
(PiePart method)
(PyCollapsiblePane method)
(SButton method)
(Shortcut method)
(ZoomBarEvent method)
(ZoomBarImage method)
GetLabelColour() (PieCtrlLegend method)
(SButton method)
GetLabelFont() (PieCtrlLegend method)
GetLabelSize() (AuiDefaultToolBarArt method)
(AuiToolBar method)
(in module aui.aui_utilities)
GetLargestSize() (RibbonButtonBarButtonBase method)
GetLastChild() (CustomTreeCtrl method)
(HyperTreeList method)
GetLastVisibleMenu() (FlatMenuBar method)
GetLastVisibleTab() (PageContainer method)
GetLeftButtonPos() (FNBRenderer method)
GetLeftImage() (GenericTreeItem method)
GetLeftImageList() (CustomTreeCtrl method)
GetLeftMarginWidth() (FlatMenu method)
GetLeftSpacing() (FoldWindowItem method)
GetLegend() (PieCtrl method)
GetLine() (UltimateListMainWindow method)
GetLineCheckboxRect() (UltimateListMainWindow method)
GetLineColour() (FoldWindowItem method)
GetLineHeight() (CustomTreeCtrl method)
(UltimateListMainWindow method)
GetLineHighlightRect() (UltimateListMainWindow method)
GetLineIconRect() (UltimateListMainWindow method)
GetLineLabelRect() (UltimateListMainWindow method)
GetLineLength() (FoldWindowItem method)
GetLineRect() (UltimateListMainWindow method)
GetLineSize() (UltimateListMainWindow method)
GetLineY() (FoldWindowItem method)
(UltimateListMainWindow method)
GetLinkCursor() (HyperLinkCtrl method)
GetListCtrl() (UltimateListMainWindow method)
GetLongHelp() (AuiToolBarItem method)
(ButtonInfo method)
(FlatMenuItem method)
(FlatToolbarItem method)
GetMainColumn() (TreeListMainWindow method)
GetMainWindow() (HyperTreeList method)
GetMainWindowOfCompositeControl() (UltimateListMainWindow method)
GetMajorAxis() (RibbonPage method)
GetManagedWindow() (AuiManager method)
GetManager() (AuiManagerEvent method)
(in module aui.framemanager)
GetManagerStyle() (PersistenceManager method)
GetMask() (CommandListEvent method)
(UltimateListItem method)
GetMax() (FloatSpin method)
GetMaxFiles() (FileHistory method)
GetMaxLayer() (in module aui.framemanager)
GetMaxRow() (in module aui.framemanager)
GetMaxValue() (KnobCtrl method)
(ProgressPie method)
GetMaxWidth() (CustomTreeCtrl method)
GetMBVerticalGradient() (ArtManager method)
GetMeasuringFont() (AuiDefaultTabArt method)
(AuiSimpleTabArt method)
GetMenu() (FlatMenuBar method)
(FlatMenuItem method)
(MenuEntryInfo method)
GetMenuBar() (FlatMenu method)
GetMenuBarBorder() (ArtManager method)
GetMenuBarColourScheme() (ArtManager method)
GetMenuBarFaceColour() (ArtManager method)
GetMenuBarForSubMenu() (FlatMenu method)
GetMenuBarSelectionColour() (ArtManager method)
GetMenuBgFactor() (ArtManager method)
GetMenuCount() (FlatMenuBar method)
GetMenuFaceColour() (ArtManager method)
(RendererBase method)
GetMenuItemCount() (FlatMenu method)
GetMenuItems() (FlatMenu method)
GetMenuItemWidth() (FlatMenu method)
GetMenuOwner() (FlatMenuBase method)
GetMenuRect() (FlatMenu method)
GetMenus() (FileHistory method)
GetMenuTheme() (ArtManager method)
GetMenuWidth() (FlatMenu method)
GetMessage() (GenericMessageDialog method)
(SuperToolTip method)
GetMessageColour() (BalloonTip method)
GetMessageDialogStyle() (GenericMessageDialog method)
GetMessageFont() (BalloonTip method)
(SuperToolTip method)
GetMetric() (AuiDefaultDockArt method)
(BPArt method)
(RibbonMSWArtProvider method)
GetMiddleGradientColor() (SuperToolTip method)
GetMiddleGradientColour() (SuperToolTip method)
GetMiddleIcon() (SpeedMeter method)
GetMiddleIconDimens() (SpeedMeter method)
GetMiddleText() (SpeedMeter method)
GetMiddleTextColour() (SpeedMeter method)
GetMiddleTextFont() (SpeedMeter method)
GetMin() (FloatSpin method)
GetMinimisedIcon() (RibbonPanel method)
GetMinimisedPanelMinimumSize() (RibbonMSWArtProvider method)
GetMinimizeMode() (AuiPaneInfo method)
GetMinMaxTabWidth() (AuiNotebook method)
GetMinNotMinimisedSize() (RibbonPanel method)
GetMinSize() (AuiToolBarItem method)
(RibbonButtonBar method)
(RibbonPage method)
(RibbonPanel method)
GetMinValue() (KnobCtrl method)
GetMnemonicChar() (FlatMenuItem method)
GetMode() (FourWaySplitter method)
(UltimateListLineData method)
GetModifierKey() (MultiColumnListCtrl method)
(SwitcherDialog method)
GetMondrianBitmap() (in module thumbnailctrl)
GetMondrianData() (in module thumbnailctrl)
GetMondrianImage() (in module thumbnailctrl)
GetMoreMenuButtonRect() (FlatMenuBar method)
GetMRUEntryLabel() (in module flatmenu)
GetMS2007ButtonSunken() (ArtManager method)
GetName() (PersistentObject method)
(SwitcherItem method)
GetNext() (CustomTreeCtrl method)
(HyperTreeList method)
GetNextActiveItem() (CustomTreeCtrl method)
(UltimateListMainWindow method)
GetNextChild() (CustomTreeCtrl method)
(HyperTreeList method)
(Shortcut method)
GetNextExpanded() (CustomTreeCtrl method)
(HyperTreeList method)
(TreeListMainWindow method)
GetNextItem() (UltimateListCtrl method)
(UltimateListMainWindow method)
GetNextLargerSize() (RibbonControl method)
GetNextSelected() (UltimateListCtrl method)
GetNextSibling() (CustomTreeCtrl method)
(HyperTreeList method)
GetNextSmallerSize() (RibbonControl method)
GetNextVisible() (CustomTreeCtrl method)
(HyperTreeList method)
GetNoHistoryFiles() (FileHistory method)
GetNonActiveTabTextColour() (FlatNotebook method)
GetNonFlexibleChildren() (ButtonPanel method)
GetNormalFont() (AuiDefaultTabArt method)
(AuiSimpleTabArt method)
GetNotebook() (FlatNotebookDragEvent method)
GetNotebookRoot() (in module aui.framemanager)
GetNotebooks() (AuiManager method)
GetNotifyEvent() (AuiNotebookEvent method)
(AuiToolBarEvent method)
(FlatNotebookEvent method)
(TreeEvent method)
(UltimateListEvent method)
GetNumberCols() (XLSTable method)
GetNumberColumns() (FlatMenu method)
GetNumberOfSecondaryTicks() (SpeedMeter method)
GetNumberRows() (XLSTable method)
GetNumOfVisibleTabs() (PageContainer method)
GetNumTabsCanScrollLeft() (PageContainer method)
GetOldAccelerator() (ShortcutEvent method)
GetOldItem() (CommandTreeEvent method)
GetOldNotebook() (FlatNotebookDragEvent method)
GetOldSelection() (CommandNotebookEvent method)
(FlatNotebookEvent method)
(ImageNotebookEvent method)
GetOldValue() (KnobCtrlEvent method)
(RulerCtrlEvent method)
GetOppositeDockTotalSize() (AuiManager method)
GetOptions() (FlatMenuBar method)
GetOrientation() (AuiDefaultToolBarArt method)
(AuiToolBarItem method)
GetOriginalImage() (ScrolledThumbnail method)
(Thumb method)
GetOriginalSize() (Thumb method)
GetOverFlow() (UltimateListItem method)
(UltimateListItemData method)
GetOverflowRect() (AuiToolBar method)
GetOverflowState() (AuiToolBar method)
GetOverflowVisible() (AuiToolBar method)
GetOwner() (UltimateListHeaderWindow method)
GetOwnerManager() (AuiFloatingFrame method)
GetPadding() (FlatNotebook method)
GetPage() (AuiNotebook method)
(AuiTabContainer method)
(FlatBookBase method)
(FlatNotebook method)
(RibbonBar method)
(RibbonBarEvent method)
GetPageBackgroundRedrawArea() (RibbonMSWArtProvider method)
GetPageBestSize() (FlatNotebook method)
GetPageBitmap() (AuiNotebook method)
GetPageCount() (AuiNotebook method)
(AuiTabContainer method)
(FlatBookBase method)
(FlatNotebook method)
(PageContainer method)
GetPageImage() (AuiNotebook method)
(FlatBookBase method)
(FlatNotebook method)
(ImageContainerBase method)
(PageContainer method)
GetPageIndex() (AuiNotebook method)
(FNBDragInfo method)
(FlatNotebook method)
GetPageInfo() (AuiNotebook method)
GetPages() (AuiTabContainer method)
GetPageShapeAngle() (FlatNotebook method)
GetPageText() (AuiNotebook method)
(FlatBookBase method)
(FlatNotebook method)
(ImageContainerBase method)
(PageContainer method)
GetPageTextColour() (AuiNotebook method)
(FlatNotebook method)
(PageContainer method)
(PageInfo method)
GetPaintRect() (ScrolledThumbnail method)
GetPane() (AuiManager method)
(AuiManagerEvent method)
(PyCollapsiblePane method)
GetPaneByName() (AuiManager method)
GetPaneByWidget() (AuiManager method)
GetPanelClientSize() (RibbonAUIArtProvider method)
(RibbonMSWArtProvider method)
GetPanelLength() (FoldPanelItem method)
GetPanelSize() (RibbonAUIArtProvider method)
(RibbonMSWArtProvider method)
GetPanelSizerBestSize() (RibbonPanel method)
GetPanelSizerMinSize() (RibbonPanel method)
GetPanelsLength() (FoldPanelBar method)
GetPanePart() (AuiManager method)
GetPanePositionsAndSizes() (AuiManager method)
GetParent() (GenericTreeItem method)
GetPartAngles() (PieCtrl method)
GetPartnerDock() (AuiManager method)
GetPartnerPane() (AuiManager method)
GetPartSizerRect() (AuiManager method)
GetPath() (AquaButton method)
(GradientButton method)
GetPaths() (MultiDirDialog method)
GetPersistenceDirectory() (PersistenceManager method)
GetPersistenceFile() (PersistenceManager method)
GetPersistenceKey() (PersistenceManager method)
GetPoint() (CommandListEvent method)
(CommandTreeEvent method)
GetPointed() (ScrolledThumbnail method)
GetPointedItem() (ScrolledThumbnail method)
GetPopupMenu() (ScrolledThumbnail method)
GetPopupText() (ToasterBoxWindow method)
GetPosition() (FloatSpinEvent method)
(HyperLinkEvent method)
(ImageBar method)
(ImageInfo method)
(Indicator method)
(PageInfo method)
(RibbonGalleryItem method)
(ZoomBarImage method)
GetPressedBottomColour() (GradientButton method)
GetPressedTopColour() (GradientButton method)
GetPrev() (CustomTreeCtrl method)
(HyperTreeList method)
GetPrevChild() (HyperTreeList method)
(TreeListMainWindow method)
GetPrevExpanded() (CustomTreeCtrl method)
(HyperTreeList method)
(TreeListMainWindow method)
GetPreviousSelection() (FlatNotebook method)
GetPrevSibling() (CustomTreeCtrl method)
(HyperTreeList method)
GetPrevVisible() (CustomTreeCtrl method)
(HyperTreeList method)
(TreeListMainWindow method)
GetProportion() (AuiToolBarItem method)
GetPulseOnFocus() (AquaButton method)
GetPyColour() (Colour method)
GetPyData() (CustomTreeCtrl method)
(HyperTreeList method)
(UltimateListCtrl method)
(UltimateListItem method)
GetRaiseToolbar() (ArtManager method)
GetRange() (PyGauge method)
GetRangeValue() (PeakMeterCtrl method)
GetRawValue() (XLSTable method)
GetRect() (ButtonInfo method)
(FlatMenuItem method)
(Indicator method)
(MenuEntryInfo method)
(SwitcherItem method)
GetRegion() (PageInfo method)
GetRenderer() (FlatMenuBar method)
(FMRendererMgr method)
(FNBRendererMgr method)
(FlatMenuBase method)
GetRendererManager() (FlatMenuBar method)
GetRGBAColour() (CubeColourDialog method)
GetRightButtonPos() (FNBRenderer method)
GetRightMarginWidth() (FlatMenu method)
GetRightSpacing() (FoldWindowItem method)
GetRootItem() (CustomTreeCtrl method)
(HyperTreeList method)
GetRootMenu() (FlatMenuBase method)
GetRotatedBitmap() (AuiToolBarItem method)
GetRotatedImage() (Thumb method)
GetRotation() (Thumb method)
GetRotationAngle() (PieCtrl method)
GetRowCount() (SwitcherItems method)
GetRowPos() (SwitcherItem method)
GetRuleColour() (UltimateListMainWindow method)
GetSashDClickUnsplit() (AuiNotebook method)
GetSashIdx() (FourWaySplitterEvent method)
GetSashPosition() (FourWaySplitterEvent method)
GetScrollButtonMinimumSize() (RibbonAUIArtProvider method)
(RibbonMSWArtProvider method)
GetScrolledWin() (UltimateListCtrl method)
GetScrollPos() (UltimateListCtrl method)
GetScrollRange() (UltimateListCtrl method)
GetScrollThumb() (UltimateListCtrl method)
GetSecondColour() (CaptionBarStyle method)
GetSecondGradientColour() (CustomTreeCtrl method)
(HyperTreeList method)
(KnobCtrl method)
(ProgressGauge method)
(PyProgress method)
(SpeedMeter method)
(UltimateListCtrl method)
(UltimateListMainWindow method)
GetSelectedCount() (SelectionStore method)
GetSelectedFont() (AuiDefaultTabArt method)
(AuiSimpleTabArt method)
GetSelectedImage() (TreeListColumnInfo method)
GetSelectedItem() (FlatMenuItemGroup method)
(ScrolledThumbnail method)
GetSelectedItemCount() (UltimateListCtrl method)
(UltimateListMainWindow method)
GetSelectedPage() (TabNavigatorWindow method)
GetSelectedTextBitmap() (MenuEntryInfo method)
GetSelection() (AuiNotebook method)
(CommandNotebookEvent method)
(CustomTreeCtrl method)
(FlatBookBase method)
(FlatNotebook method)
(FlatNotebookEvent method)
(HyperTreeList method)
(ImageNotebookEvent method)
(PageContainer method)
(RibbonGallery method)
(ScrolledThumbnail method)
(SwitcherDialog method)
(SwitcherItems method)
(ZoomBarEvent method)
GetSelectionColour() (ScrolledThumbnail method)
(SwitcherItems method)
GetSelectionOutlineColour() (SwitcherItems method)
GetSelections() (CustomTreeCtrl method)
(HyperTreeList method)
(ListBoxHandler method)
GetSelectionState() (TreeCtrlHandler method)
GetSelectionStateOfChildren() (TreeCtrlHandler method)
GetSelectionStateOfItem() (TreeCtrlHandler method)
GetSeparatorColour() (CustomTreeCtrl method)
getShadow() (in module thumbnailctrl)
GetShadowColour() (SpeedMeter method)
GetShortcut() (ShortcutEvent method)
GetShortcutManager() (ShortcutEditor method)
GetShortHelp() (AuiToolBarItem method)
(ButtonInfo method)
(FlatMenuItem method)
(FlatToolbarItem method)
GetShowComboBox() (ThumbnailCtrl method)
GetShowDir() (ScrolledThumbnail method)
GetShowEdges() (PieCtrl method)
GetShowEffect() (InfoBar method)
GetShowLabels() (ZoomBar method)
GetShowReflections() (ZoomBar method)
GetSiblingGroupItem() (FlatMenu method)
GetSingleLineBorderColour() (PageContainer method)
GetSize() (GenericTreeItem method)
(ImageBar method)
(ImageInfo method)
(PageInfo method)
(PyImageList method)
(ZoomBarImage method)
GetSizeInOrientation() (in module ribbon.page)
(in module ribbon.toolbar)
GetSizerItem() (AuiToolBarItem method)
GetSlidingPoints() (in module aui.aui_utilities)
GetSmallerSize() (RibbonButtonBarButtonBase method)
GetSnapPosition() (AuiManager method)
GetSnapToTicks() (FloatSpin method)
GetSpacerPixels() (AuiToolBarItem method)
GetSpacing() (CustomTreeCtrl method)
(FoldWindowItem method)
(HyperTreeList method)
GetSpeedBackground() (SpeedMeter method)
GetSpeedStyle() (SpeedMeter method)
GetSpeedValue() (SpeedMeter method)
GetSplashStyle() (AdvancedSplash method)
GetStartDelay() (BalloonTip method)
(SuperToolTip method)
GetStartX() (FNBRendererVC8 method)
GetState() (AuiToolBarItem method)
(MenuEntryInfo method)
(UltimateListHeaderData method)
(UltimateListItem method)
GetStateImageList() (CustomTreeCtrl method)
(HyperTreeList method)
GetStatus() (ButtonInfo method)
GetStockBitmap() (ArtManager method)
GetStyle() (ButtonPanel method)
GetStyleKeys() (in module supertooltip)
GetSubItemRect() (UltimateListCtrl method)
(UltimateListMainWindow method)
GetSubMenu() (FlatMenuItem method)
GetSuitableBitmap() (FlatMenuItem method)
GetTabAngle() (PageInfo method)
GetTabArea() (FlatNotebook method)
GetTabAreaColour() (FlatNotebook method)
GetTabAreaWidth() (LabelContainer method)
GetTabContainer() (AuiNotebook method)
GetTabCtrlFromPoint() (AuiNotebook method)
GetTabCtrlHeight() (AuiNotebook method)
(RibbonAUIArtProvider method)
(RibbonMSWArtProvider method)
GetTabFrameFromTabCtrl() (AuiNotebook method)
GetTabFrameFromWindow() (AuiNotebook method)
GetTabOffset() (AuiTabContainer method)
GetTabSize() (AuiDefaultTabArt method)
(AuiSimpleTabArt method)
(ChromeTabArt method)
(FF2TabArt method)
(VC8TabArt method)
GetTag() (CaptionBarEvent method)
GetTags() (KnobCtrl method)
GetTagsColour() (KnobCtrl method)
GetTarget() (BalloonTip method)
(SuperToolTip method)
GetText() (AdvancedSplash method)
(ButtonInfo method)
(ButtonPanelText method)
(CommandListEvent method)
(Excel method)
(FlatMenuItem method)
(GenericTreeItem method)
(TreeListColumnInfo method)
(TreeListItem method)
(UltimateListHeaderData method)
(UltimateListItem method)
(UltimateListItemData method)
(UltimateListLineData method)
GetTextAlignment() (ButtonInfo method)
GetTextBitmap() (MenuEntryInfo method)
GetTextColor() (SuperToolTip method)
GetTextColour() (AdvancedSplash method)
(FlatMenuItem method)
(SuperToolTip method)
(SwitcherItem method)
(SwitcherItems method)
(TreeItemAttr method)
(UltimateListCtrl method)
(UltimateListItem method)
(UltimateListItemAttr method)
GetTextColourDisable() (ArtManager method)
(RendererBase method)
GetTextColourEnable() (ArtManager method)
(FMRendererMSOffice2007 method)
(FMRendererXP method)
(RendererBase method)
(RendererMSOffice2007 method)
(RendererXP method)
GetTextCtrl() (FloatSpin method)
GetTextCtrlAlignmentStyle() (HyperTreeList method)
GetTextCtrlStyle() (HyperTreeList method)
GetTextFont() (AdvancedSplash method)
GetTextForMeasuring() (UltimateListItemData method)
GetTextHeight() (UltimateListHeaderWindow method)
GetTextLength() (UltimateListMainWindow method)
GetTextOrientation() (AuiDefaultToolBarArt method)
GetTextPosition() (AdvancedSplash method)
GetTextRect() (ImageInfo method)
GetTextStartLocation() (ArtManager method)
GetTextX() (TreeListItem method)
GetThemeBaseColour() (ArtManager method)
GetThumbBorder() (ScrolledThumbnail method)
GetThumbHeight() (ScrolledThumbnail method)
GetThumbInfo() (ScrolledThumbnail method)
GetThumbOutline() (ScrolledThumbnail method)
GetThumbSize() (ScrolledThumbnail method)
GetThumbWidth() (ScrolledThumbnail method)
GetTicks() (SpeedMeter method)
GetTicksColour() (SpeedMeter method)
GetTicksFont() (SpeedMeter method)
GetTileOrientation() (FlatNotebook method)
GetTimeFormat() (RulerCtrl method)
GetTimer() (FlatMenuButton method)
GetTimerId() (FlatMenuButton method)
GetTipWindow() (SuperToolTip method)
GetTitle() (MenuEntryInfo method)
(SwitcherItem method)
GetTitleColour() (BalloonTip method)
GetTitleFont() (BalloonTip method)
GetToasterBoxWindow() (ToasterBox method)
GetToggle() (__SToggleMixin method)
(__ToggleMixin method)
GetToggled() (ButtonInfo method)
GetToolBarDockOffsets() (in module aui.framemanager)
GetToolBarFits() (AuiToolBar method)
GetToolBitmap() (AuiToolBar method)
GetToolBitmapSize() (AuiToolBar method)
GetToolBorderPadding() (AuiToolBar method)
GetToolCount() (AuiToolBar method)
GetToolDropDown() (AuiToolBar method)
GetToolEnabled() (AuiToolBar method)
GetToolFits() (AuiToolBar method)
GetToolFitsByIndex() (AuiToolBar method)
GetToolId() (CommandToolBarEvent method)
GetToolIndex() (AuiToolBar method)
GetToolLabel() (AuiToolBar method)
GetToolLongHelp() (AuiToolBar method)
GetToolOrientation() (AuiToolBar method)
GetToolPacking() (AuiToolBar method)
GetToolPos() (AuiToolBar method)
GetToolProportion() (AuiToolBar method)
GetToolRect() (AuiToolBar method)
GetToolSeparation() (AuiToolBar method)
GetToolShortHelp() (AuiToolBar method)
GetToolSize() (AuiDefaultToolBarArt method)
(RibbonMSWArtProvider method)
GetToolsPosition() (AuiDefaultToolBarArt method)
GetToolSticky() (AuiToolBar method)
GetToolTextOrientation() (AuiToolBar method)
GetToolTip() (CommandTreeEvent method)
(UltimateListHeaderData method)
(UltimateListItem method)
(UltimateListItemData method)
(UltimateListLineData method)
GetToolToggled() (AuiToolBar method)
GetTopEndColour() (GradientButton method)
GetTopGradientColor() (SuperToolTip method)
GetTopGradientColour() (SuperToolTip method)
GetTopItem() (UltimateListCtrl method)
GetTopLeft() (FourWaySplitter method)
GetTopRight() (FourWaySplitter method)
GetTopStartColour() (GradientButton method)
GetTotalPixSizeAndProportion() (AuiManager method)
GetTotalWidth() (UltimateListMainWindow method)
GetTrackPosition() (KnobCtrl method)
GetTransparency() (ArtManager method)
GetType() (FoldWindowItem method)
(GenericTreeItem method)
GetUnderlines() (HyperLinkCtrl method)
GetUnfilledColour() (ProgressPie method)
GetUpButtonState() (RibbonGallery method)
GetURL() (HyperLinkCtrl method)
GetUseFade() (SuperToolTip method)
GetUseFocus() (ToasterBox method)
GetUseFocusIndicator() (SButton method)
GetUseHelp() (ButtonPanel method)
GetUserData() (AuiToolBarItem method)
GetUserLineHeight() (UltimateListCtrl method)
(UltimateListMainWindow method)
GetValue() (__SToggleMixin method)
(FloatSpin method)
(GenericTreeItem method)
(Indicator method)
(KnobCtrl method)
(KnobCtrlEvent method)
(PiePart method)
(ProgressPie method)
(PyGauge method)
(RulerCtrlEvent method)
(XLSCell method)
(XLSTable method)
(XLSText method)
(__ToggleMixin method)
GetVerticalBorder() (PieCtrlLegend method)
GetVeto() (AuiManagerEvent method)
GetViewRect() (UltimateListCtrl method)
(UltimateListMainWindow method)
GetVisibleLinesRange() (UltimateListMainWindow method)
GetVisited() (GenericTreeItem method)
(HyperLinkCtrl method)
(UltimateListItem method)
(UltimateListItemData method)
GetWaterMark() (UltimateListCtrl method)
(UltimateListMainWindow method)
GetWidth() (GenericTreeItem method)
(TreeListColumnInfo method)
(TreeListHeaderWindow method)
(UltimateListHeaderData method)
(UltimateListItem method)
(UltimateListItemData method)
(UltimateListLineData method)
GetWindow() (AuiToolBarItem method)
(FourWaySplitter method)
(GenericTreeItem method)
(PersistentObject method)
(SwitcherItem method)
(TreeListItem method)
(UltimateListItem method)
(UltimateListItemData method)
GetWindowEnabled() (GenericTreeItem method)
(TreeListItem method)
(UltimateListItem method)
(UltimateListItemData method)
GetWindowFromIdx() (AuiTabContainer method)
GetWindowHeight() (UltimateListHeaderWindow method)
GetWindowLength() (FoldWindowItem method)
GetWindowSize() (GenericTreeItem method)
(TreeListItem method)
(UltimateListItem method)
(UltimateListItemData method)
GetX() (GenericTreeItem method)
(UltimateListItemData method)
(UltimateListLineData method)
GetXPos() (FNBRenderer method)
GetXRect() (PageInfo method)
GetY() (GenericTreeItem method)
(UltimateListItemData method)
(UltimateListLineData method)
GetZoomFactor() (ScrolledThumbnail method)
(ZoomBar method)
GiveFeedback() (FNBDropSource method)
GotoURL() (HyperLinkCtrl method)
GradientButton (class in gradientbutton)
gradientbutton (module)
GradientButtonEvent (class in gradientbutton)
Gripper() (AuiPaneInfo method)
GripperTop() (AuiPaneInfo method)
GTKExpander (class in pycollapsiblepane)

H

HandleColumnCheck() (UltimateListHeaderWindow method)
HandleHyperLink() (CustomTreeCtrl method)
(UltimateListMainWindow method)
HasAGWFlag() (CustomTreeCtrl method)
(FlatBookBase method)
(FlatNotebook method)
(HyperTreeList method)
(ImageContainerBase method)
(PageContainer method)
(PyCollapsiblePane method)
(UltimateListCtrl method)
(UltimateListMainWindow method)
HasAttributes() (UltimateListItem method)
HasBackgroundColour() (TreeItemAttr method)
(UltimateListItemAttr method)
(UltimateListItemData method)
HasBarText() (ButtonPanel method)
HasBorder() (AuiPaneInfo method)
HasButtons() (CustomTreeCtrl method)
HasCaption() (AuiPaneInfo method)
HasCaptionLeft() (AuiPaneInfo method)
HasChanged() (Shortcut method)
HasChildren() (CustomTreeCtrl method)
(GenericTreeItem method)
(HyperTreeList method)
HasCloseButton() (AuiNotebook method)
(AuiPaneInfo method)
HasColour() (UltimateListItemData method)
HasCtrlHandler() (in module persist.persist_handlers)
HasCurrent() (UltimateListMainWindow method)
HasCustomBitmaps() (GenericMessageDialog method)
HasCustomLabels() (GenericMessageDialog method)
HasDropDown() (AuiToolBarItem method)
HasFlag() (AuiPaneInfo method)
(ListShortcut method)
HasFocus() (Control method)
(UltimateListMainWindow method)
HasFont() (TreeItemAttr method)
(UltimateListItemAttr method)
(UltimateListItemData method)
HasFooter() (UltimateListCtrl method)
(UltimateListMainWindow method)
HasFooterBackgroundColour() (UltimateListItemAttr method)
HasFooterFont() (UltimateListItemAttr method)
HasFooterImage() (UltimateListHeaderData method)
HasFooterTextColour() (UltimateListItemAttr method)
HasGripper() (AuiPaneInfo method)
HasGripperTop() (AuiPaneInfo method)
HasHeader() (UltimateListCtrl method)
(UltimateListMainWindow method)
HasImage() (UltimateListHeaderData method)
(UltimateListItemData method)
(UltimateListLineData method)
HasMaximizeButton() (AuiPaneInfo method)
HasMinimizeButton() (AuiPaneInfo method)
HasMode() (UltimateListLineData method)
HasMultiplePages() (AuiNotebook method)
(RibbonBar method)
HasNotebook() (AuiPaneInfo method)
HasPinButton() (AuiPaneInfo method)
HasPlus() (GenericTreeItem method)
HasRange() (FloatSpin method)
HasText() (ButtonInfo method)
(UltimateListHeaderData method)
(UltimateListItemData method)
(UltimateListLineData method)
HasTextColour() (TreeItemAttr method)
(UltimateListItemAttr method)
Hide() (AuiPaneInfo method)
(Control method)
(TreeListItem method)
HideAllTabs() (AuiNotebook method)
HideExpanded() (RibbonPanel method)
HideHint() (AuiManager method)
HideItem() (HyperTreeList method)
(TreeListMainWindow method)
HideItemWindow() (UltimateListLineData method)
HideScrollButtons() (RibbonPage method)
HideTabs() (FlatNotebook method)
HideWindows() (CustomTreeCtrl method)
(TreeListMainWindow method)
(UltimateListMainWindow method)
Highlight() (UltimateListLineData method)
HighlightAll() (UltimateListMainWindow method)
HighlightBackgroundColour() (ArtManager method)
HighlightImage() (NativeImageHandler method)
(PILImageHandler method)
HighlightLine() (UltimateListMainWindow method)
HighlightLines() (UltimateListMainWindow method)
HitTest() (AuiCenterDockingGuide method)
(AuiDockingGuide method)
(AuiManager method)
(AuiSingleDockingGuide method)
(AuiToolBar method)
(ButtonPanel method)
(CustomTreeCtrl method)
(FlatMenu method)
(FlatMenuBar method)
(GenericTreeItem method)
(HyperTreeList method)
(ImageContainerBase method)
(PageContainer method)
(TreeListItem method)
(TreeListMainWindow method)
(UltimateListCtrl method)
(UltimateListMainWindow method)
(ZoomBar method)
HitTestColumn() (UltimateListHeaderWindow method)
HitTestLine() (UltimateListMainWindow method)
HitTestTabs() (RibbonBar method)
Host() (AuiDockingGuideInfo method)
HSVWheel (class in cubecolourdialog)
HTMLHelpWindow (class in shortcuteditor)
hyperlink (module)
HyperLinkCtrl (class in hyperlink)
HyperLinkEvent (class in hyperlink)
HyperTreeList (class in hypertreelist)
hypertreelist (module)

I

Icon (TabNavigatorProps attribute)
Icon() (AuiPaneInfo method)
Id (ButtonInfo attribute)
ImageBar (class in zoombar)
ImageContainer (class in labelbook)
ImageContainerBase (class in labelbook)
ImageInfo (class in labelbook)
ImageNotebookEvent (class in labelbook)
InCircle() (HSVWheel method)
IndentPressedBitmap() (in module aui.aui_utilities)
Indicator (class in rulerctrl)
InfoBar (class in infobar)
infobar (module)
Init() (AuiDefaultDockArt method)
(FlatNotebook method)
(InfoBar method)
(ModernDockArt method)
(ShortcutEditor method)
(UltimateListHeaderData method)
(UltimateListItem method)
(UltimateListItemData method)
(UltimateListMainWindow method)
InitColours() (ArtManager method)
(SButton method)
InitData() (PeakMeterCtrl method)
InitDialog() (CubeColourDialog method)
InitFont() (SuperToolTip method)
Initialise() (FMCustomizeDlg method)
Initialize() (ArtManager method)
InitializeColours() (CustomPanel method)
(LabelContainer method)
InitialReposition() (ZoomBar method)
InitItems() (UltimateListLineData method)
InitNotebook() (AuiNotebook method)
InRange() (FloatSpin method)
(in module peakmeter)
InReportView() (UltimateListLineData method)
(UltimateListMainWindow method)
Insert() (BoxSizer method)
(FlatMenu method)
(FlatMenuBar method)
(GenericTreeItem method)
InsertColumn() (HyperTreeList method)
(TreeListHeaderWindow method)
(UltimateListCtrl method)
(UltimateListMainWindow method)
InsertColumnInfo() (HyperTreeList method)
(TreeListHeaderWindow method)
(UltimateListCtrl method)
InsertImageItem() (UltimateListCtrl method)
InsertImageStringItem() (UltimateListCtrl method)
InsertItem() (CustomTreeCtrl method)
(FlatMenu method)
(HyperTreeList method)
(ScrolledThumbnail method)
(UltimateListCtrl method)
(UltimateListMainWindow method)
InsertItemByIndex() (CustomTreeCtrl method)
InsertItemByItem() (CustomTreeCtrl method)
InsertPage() (AuiNotebook method)
(AuiTabContainer method)
(FlatBookBase method)
(FlatNotebook method)
(ImageContainerBase method)
(PageContainer method)
InsertPane() (AuiManager method)
InsertSeparator() (CustomTreeCtrl method)
(FlatMenu method)
InsertStringItem() (UltimateListCtrl method)
InsertWindow() (FourWaySplitter method)
InstallGridHint() (XLSGrid method)
Intersection() (in module cubecolourdialog)
InTileView() (UltimateListMainWindow method)
Invalidate() (AquaButton method)
(RulerCtrl method)
(ToolTipWindowBase method)
Is3State() (GenericTreeItem method)
IsActive() (AuiToolBarItem method)
IsAllowed() (AuiNotebookEvent method)
(AuiToolBarEvent method)
(FlatNotebookEvent method)
(FourWaySplitterEvent method)
(ImageNotebookEvent method)
(RibbonBarEvent method)
(TreeEvent method)
(UltimateListEvent method)
IsAncestorOf() (in module ribbon.panel)
IsAudio() (ScrolledThumbnail method)
IsAudioVideo() (ScrolledThumbnail method)
IsBold() (CustomTreeCtrl method)
(GenericTreeItem method)
(HyperTreeList method)
IsBottomDockable() (AuiPaneInfo method)
IsBottomSnappable() (AuiPaneInfo method)
IsBufferingSupported() (in module hypertreelist)
IsButtonEnabled() (RibbonButtonBar method)
(ZoomBar method)
IsCheckable() (FlatMenuItem method)
IsChecked() (FlatMenuItem method)
(FlatToolbarItem method)
(GenericTreeItem method)
(UltimateListHeaderData method)
(UltimateListItem method)
(UltimateListItemData method)
(UltimateListLineData method)
IsCheckItem() (FlatToolbarItem method)
IsCollapsed() (CaptionBar method)
(PyCollapsiblePane method)
IsColumnEditable() (HyperTreeList method)
(TreeListHeaderWindow method)
IsColumnShown() (HyperTreeList method)
(TreeListHeaderWindow method)
(UltimateListCtrl method)
(UltimateListHeaderWindow method)
(UltimateListMainWindow method)
IsCustomControl() (FlatToolbarItem method)
IsDark() (ArtManager method)
IsDefaultTabs() (PageContainer method)
IsDefaultValue() (FloatSpin method)
IsDescendantOf() (CustomTreeCtrl method)
(HyperTreeList method)
IsDestroyOnClose() (AuiPaneInfo method)
IsDifferentDockingPosition() (in module aui.framemanager)
IsDockable() (AuiPaneInfo method)
IsDocked() (AuiPaneInfo method)
IsDragging() (AuiTabCtrl method)
IsDropDownClicked() (CommandToolBarEvent method)
IsEditable() (TreeListColumnInfo method)
IsEditCancelled() (CommandListEvent method)
(CommandNotebookEvent method)
(CommandTreeEvent method)
IsEmpty() (RibbonGallery method)
(UltimateListMainWindow method)
IsEnabled() (ButtonInfo method)
(FlatMenuItem method)
(FlatToolbarItem method)
(GenericTreeItem method)
(SButton method)
(UltimateListItem method)
(UltimateListItemAttr method)
(UltimateListItemData method)
(ZoomBarImage method)
IsEqual() (PeakMeterData method)
IsExpanded() (CustomTreeCtrl method)
(FoldPanelItem method)
(GenericTreeItem method)
(HyperTreeList method)
(PyCollapsiblePane method)
IsFinite() (FloatSpin method)
IsFixed() (AuiPaneInfo method)
IsFloatable() (AuiPaneInfo method)
IsFloating() (AuiPaneInfo method)
IsFlyOut() (AuiPaneInfo method)
IsFooterChecked() (UltimateListHeaderData method)
(UltimateListItem method)
IsGreater() (PeakMeterData method)
IsGridVisible() (PeakMeterCtrl method)
IsHidden() (TreeListItem method)
IsHighlighted() (UltimateListLineData method)
(UltimateListMainWindow method)
IsHit() (UltimateListHeaderData method)
(UltimateListItemData method)
IsHorizontal() (AuiDockInfo method)
(AuiPaneInfo method)
IsHovered() (RibbonGallery method)
(RibbonPanel method)
IsHyperLink() (XLSText method)
IsHyperText() (GenericTreeItem method)
(UltimateListItem method)
(UltimateListItemData method)
IsItalic() (CustomTreeCtrl method)
(GenericTreeItem method)
IsItem3State() (CustomTreeCtrl method)
(HyperTreeList method)
IsItemChecked() (CustomTreeCtrl method)
(HyperTreeList method)
(UltimateListCtrl method)
(UltimateListMainWindow method)
IsItemEnabled() (CustomTreeCtrl method)
(HyperTreeList method)
(TreeListMainWindow method)
(UltimateListCtrl method)
(UltimateListMainWindow method)
IsItemHyperText() (CustomTreeCtrl method)
(HyperTreeList method)
(UltimateListCtrl method)
(UltimateListMainWindow method)
IsItemSeparator() (CustomTreeCtrl method)
IsItemVisible() (HyperTreeList method)
(TreeListMainWindow method)
IsLeftDockable() (AuiPaneInfo method)
IsLeftSnappable() (AuiPaneInfo method)
IsLower() (PeakMeterData method)
IsMaximized() (AuiPaneInfo method)
IsMinimised() (RibbonPanel method)
IsMinimised1() (RibbonPanel method)
IsMinimised2() (RibbonPanel method)
IsMinimized() (AuiPaneInfo method)
IsMouseHovering() (PageContainer method)
IsMouseWellOutsideWindow() (AuiNotebook method)
IsMovable() (AuiPaneInfo method)
IsMultiline() (AuiNotebookPage method)
IsNotebookControl() (AuiPaneInfo method)
IsNotebookDockable() (AuiPaneInfo method)
IsNotebookPage() (AuiPaneInfo method)
IsOk() (AuiDockInfo method)
(AuiPaneInfo method)
(GenericTreeItem method)
IsOutside() (SButton method)
IsPaneButtonVisible() (AuiManager method)
IsPaneMinimized() (AuiToolBar method)
IsRadioItem() (FlatMenuItem method)
(FlatToolbarItem method)
IsRegularItem() (FlatToolbarItem method)
IsRenamable() (AuiNotebook method)
IsResizeable() (AuiPaneInfo method)
IsRightDockable() (AuiPaneInfo method)
IsRightSnappable() (AuiPaneInfo method)
IsSelected() (CustomTreeCtrl method)
(FlatToolbarItem method)
(GenericTreeItem method)
(HyperTreeList method)
(ScrolledThumbnail method)
(SelectionStore method)
(UltimateListCtrl method)
IsSeparator() (FlatMenuItem method)
(FlatToolbarItem method)
(GenericTreeItem method)
IsShown() (AuiPaneInfo method)
(Control method)
(FlatMenuItem method)
(TreeListColumnInfo method)
(UltimateListItem method)
IsSingleSel() (UltimateListMainWindow method)
IsSizingContinuous() (RibbonButtonBar method)
(RibbonControl method)
(RibbonGallery method)
(RibbonPanel method)
(RibbonToolBar method)
IsSnappable() (AuiPaneInfo method)
IsStandard() (ButtonPanel method)
IsStarted() (PeakMeterCtrl method)
IsSticky() (AuiToolBarItem method)
IsSubMenu() (FlatMenuItem method)
IsTabVisible() (AuiTabContainer method)
(PageContainer method)
IsToolbar() (AuiPaneInfo method)
IsTop() (Shortcut method)
IsTopDockable() (AuiPaneInfo method)
IsTopSnappable() (AuiPaneInfo method)
IsTransparent() (PieCtrlLegend method)
IsValid() (AuiDockingGuideWindow method)
(AuiSingleDockingGuide method)
IsVertical() (AuiDockInfo method)
(AuiPaneInfo method)
(ButtonPanel method)
(CaptionBar method)
(FoldPanelBar method)
(FoldPanelItem method)
IsVideo() (ScrolledThumbnail method)
IsVirtual() (TreeListMainWindow method)
(UltimateListCtrl method)
(UltimateListLineData method)
(UltimateListMainWindow method)
IsVisible() (CustomTreeCtrl method)
(RibbonGalleryItem method)
IsZoomed() (ZoomBarImage method)
item() (EditCtrl method)
(TabTextCtrl method)
(TreeTextCtrl method)
ItemHasChildren() (CustomTreeCtrl method)
(HyperTreeList method)

K

KnobCtrl (class in knobctrl)
knobctrl (module)
KnobCtrlEvent (class in knobctrl)

L

Label (class in rulerctrl)
LabelBook (class in labelbook)
labelbook (module)
LabelContainer (class in labelbook)
LabelMajor() (RulerCtrl method)
LabelMinor() (RulerCtrl method)
LabelString() (RulerCtrl method)
Layer() (AuiPaneInfo method)
Layout() (BoxSizer method)
(PyCollapsiblePane method)
(RibbonGallery method)
(RibbonPage method)
(RibbonPanel method)
LayoutAddDock() (AuiManager method)
LayoutAddPane() (AuiManager method)
LayoutAll() (AuiManager method)
LayoutItems() (ButtonPanel method)
(MultiDirDialog method)
Left() (AuiDockingGuideInfo method)
(AuiPaneInfo method)
LeftDockable() (AuiPaneInfo method)
LeftSnappable() (AuiPaneInfo method)
LightColour() (AquaButton method)
(ArtManager method)
(GradientButton method)
(in module aui.aui_utilities)
(in module flatnotebook)
LightContrastColour() (in module aui.aui_utilities)
LightenColour() (in module peakmeter)
Lighter() (RibbonHSLColour method)
LikePrimary() (in module ribbon.art_msw)
LikeSecondary() (in module ribbon.art_msw)
LineDescription (class in cubecolourdialog)
ListBoxHandler (class in persist.persist_handlers)
ListCtrlHandler (class in persist.persist_handlers)
ListDirectory() (ScrolledThumbnail method)
ListShortcut (class in shortcuteditor)
Load() (FileHistory method)
LoadImages() (ScrolledThumbnail method)
LoadPaneInfo() (AuiManager method)
LoadPerspective() (AuiManager method)
(AuiNotebook method)
LoadThumbnail() (NativeImageHandler method)
(PILImageHandler method)
LoopScales() (ZoomBarImage method)

M

MakeBold() (in module supertooltip)
MakeDarker() (RibbonHSLColour method)
MakeDisabledBitmap() (in module aui.aui_utilities)
(RibbonButtonBar method)
(RibbonToolBar method)
(in module buttonpanel)
(in module customtreectrl)
(in module ultimatelistctrl)
(in module zoombar)
MakeGray() (in module aui.aui_utilities)
MakeImageList() (ListShortcut method)
MakeLayouts() (RibbonButtonBar method)
MakePalette() (in module rulerctrl)
(SButton method)
MakeResizedBitmap() (RibbonButtonBar method)
MakeTabVisible() (AuiTabContainer method)
MakeVenetianBlinds() (AuiDockingHintWindow method)
MakeWindowTransparent() (ArtManager method)
(ToasterBoxWindow method)
(ToolTipWindowBase method)
Match() (Shortcut method)
Maximize() (AuiPaneInfo method)
MaximizeButton() (AuiPaneInfo method)
MaximizePane() (AuiManager method)
MaxSize() (AuiPaneInfo method)
MaxSize1() (AuiPaneInfo method)
MaxSize2() (AuiPaneInfo method)
mcPopupWindow (class in flatmenu)
Measure() (XLSRichText method)
MediaCtrlHandler (class in persist.persist_handlers)
MenuBarHandler (class in persist.persist_handlers)
MenuEntryInfo (class in flatmenu)
MenuKbdRedirector (class in flatmenu)
Minimize() (AuiPaneInfo method)
MinimizeButton() (AuiPaneInfo method)
MinimizeMode() (AuiPaneInfo method)
MinimizePane() (AuiManager method)
MinimizeTabOffset() (AuiTabContainer method)
MinimizeTarget() (AuiPaneInfo method)
MinSize (TabNavigatorProps attribute)
MinSize() (AuiPaneInfo method)
MinSize1() (AuiPaneInfo method)
MinSize2() (AuiPaneInfo method)
MixColours() (ArtManager method)
ModernDockArt (class in aui.dockart)
Movable() (AuiPaneInfo method)
Move() (FlatMenuButton method)
MoveAbove() (ToasterBox method)
MovePage() (AuiTabContainer method)
MoveSplit() (FourWaySplitter method)
MoveTabPage() (PageContainer method)
MoveToFocus() (UltimateListMainWindow method)
MoveToItem() (UltimateListMainWindow method)
MultiColumnListCtrl (class in aui.aui_switcherdialog)
MultiDirDialog (class in multidirdialog)
multidirdialog (module)

N

Name() (AuiPaneInfo method)
NativeImageHandler (class in thumbnailctrl)
NavigatorProps (AuiNotebook attribute)
needsRestore (AuiPaneInfo attribute)
NewInstance() (RibbonButtonBarButtonBase method)
NotebookControl() (AuiPaneInfo method)
NotebookDockable() (AuiPaneInfo method)
NotebookPage() (AuiPaneInfo method)
NotebookPreview() (AuiNotebook method)
Notify() (AquaButton method)
(GradientButton method)
(SButton method)
(StatusBarTimer method), [1]
(ToasterBox method)
(TreeEditTimer method)
(TreeFindTimer method)
(UltimateListRenameTimer method)
NotifyTimer() (BalloonTip method)
(ToasterBoxWindow method)
NumberTabsCanFit() (FNBRenderer method)
(FNBRendererVC8 method)

O

OfflimitsPixels() (RulerCtrl method)
OffsetColour() (KnobCtrl method)
OnAccelCmd() (FlatMenuBar method)
OnAcceptEdit() (CustomTreeCtrl method)
(TreeListMainWindow method)
OnActivate() (AuiFloatingFrame method)
(SwitcherDialog method)
OnAddCustom() (CubeColourDialog method)
OnAlphaSpin() (CubeColourDialog method)
OnArrowChar() (UltimateListMainWindow method)
OnButton() (AuiTabCtrl method)
(InfoBar method)
(PyCollapsiblePane method)
OnCancel() (CubeColourDialog method)
(GenericMessageDialog method)
(MultiDirDialog method)
(PyProgress method)
OnCancelEdit() (CustomTreeCtrl method)
(TreeListMainWindow method)
OnCaptionDoubleClicked() (AuiManager method)
OnCaptureLost() (AuiManager method)
(AuiTabCtrl method)
OnChangeStyle() (FMCustomizeDlg method)
OnChar() (CaptionBar method)
(EditTextCtrl method)
(FlatMenu method)
(FloatSpin method)
(FloatTextCtrl method)
(MultiColumnListCtrl method)
(ScrolledThumbnail method)
(TabTextCtrl method)
(TreeTextCtrl method)
(UltimateListMainWindow method)
(UltimateListTextCtrl method)
OnCharEvents() (AdvancedSplash method)
OnCheckFlyTimer() (AuiFloatingFrame method)
OnChildDismiss() (FlatMenuBase method)
OnChildFocus() (AuiManager method)
(UltimateListMainWindow method)
OnChildFocusNotebook() (AuiNotebook method)
OnChildKillFocus() (RibbonPanel method)
OnClearFilter() (ShortcutEditor method)
OnClose() (AuiFloatingFrame method)
(BalloonFrame method)
(HTMLHelpWindow method)
(MultiDirDialog method)
(PyProgress method)
(ToasterBoxWindow method)
OnCloseFloatingPage() (AuiNotebook method)
OnCloseWindow() (AdvancedSplash method)
(CubeColourDialog method)
(SwitcherDialog method)
OnComboBox() (ThumbnailCtrl method)
OnCompareItems() (CustomTreeCtrl method)
(HyperTreeList method)
(UltimateListMainWindow method)
OnCustomizeDlg() (FlatMenuBar method)
OnCustomRender() (AuiToolBar method)
OnData() (FNBDropTarget method)
OnDestroy() (BalloonTip method)
(CustomTreeCtrl method)
(FloatSpin method)
(FloatTextCtrl method)
(PyProgress method)
(SuperToolTip method)
(ToolTipWindowBase method)
OnDismiss() (FlatMenuBase method)
OnDrawGTKExpander() (GTKExpander method)
(PyCollapsiblePane method)
OnDrawGTKStyle() (PyCollapsiblePane method)
OnDrawGTKText() (GTKExpander method)
(PyCollapsiblePane method)
OnDropTarget() (FlatNotebook method)
(PageContainer method)
OnEditTimer() (CustomTreeCtrl method)
(TreeListMainWindow method)
OnEndTimer() (SuperToolTip method)
OnEnterButton() (BalloonFrame method)
OnEnterWindow() (FourWaySplitter method)
(UltimateListHeaderWindow method)
OnErase() (PyInfoFrame method)
OnEraseBackground() (AuiCenterDockingGuide method)
(AuiDockingGuideWindow method)
(AuiManager method)
(AuiTabCtrl method)
(AuiToolBar method)
(BaseLineCtrl method)
(BasePyControl method)
(ButtonPanel method)
(ColourPanel method)
(CustomPanel method)
(CustomTreeCtrl method)
(FMTitlePanel method)
(FlatMenu method)
(FlatMenuBar method)
(ImageContainer method)
(ImageContainerBase method)
(LabelContainer method)
(MultiColumnListCtrl method)
(PageContainer method)
(PeakMeterCtrl method)
(ProgressGauge method)
(PyGauge method)
(RibbonBar method)
(RibbonButtonBar method)
(RibbonGallery method)
(RibbonPage method)
(RibbonPageScrollButton method)
(RibbonPanel method)
(RibbonToolBar method)
(RulerCtrl method)
(ToolTipWindowBase method)
(TreeListMainWindow method)
(UltimateListMainWindow method)
(ZoomBar method)
OnExpandCollapse() (ListShortcut method)
OnFindManager() (AuiFloatingFrame method)
(AuiManager method)
OnFloatingPaneActivated() (AuiManager method)
OnFloatingPaneClosed() (AuiManager method)
OnFloatingPaneMoved() (AuiManager method)
OnFloatingPaneResized() (AuiManager method)
OnFlyTimer() (AuiFloatingFrame method)
OnFocus() (FloatSpin method)
OnGainFocus() (AquaButton method)
(GradientButton method)
(SButton method)
OnGetItemAttr() (UltimateListCtrl method)
OnGetItemCheck() (UltimateListCtrl method)
OnGetItemColumnCheck() (UltimateListCtrl method)
OnGetItemColumnImage() (UltimateListCtrl method)
OnGetItemColumnKind() (UltimateListCtrl method)
OnGetItemImage() (UltimateListCtrl method)
OnGetItemKind() (UltimateListCtrl method)
OnGetItemText() (HyperTreeList method)
(UltimateListCtrl method)
OnGetItemTextColour() (UltimateListCtrl method)
OnGetItemToolTip() (UltimateListCtrl method)
OnGetToolTip() (CustomTreeCtrl method)
OnGripperClicked() (AuiManager method)
OnHelp() (GenericMessageDialog method)
OnHintFadeTimer() (AuiManager method)
OnHoverTimer() (UltimateListMainWindow method)
OnHTMLHelp() (ShortcutEditor method)
OnHTMLToolbar() (HTMLHelpWindow method)
OnIdle() (AuiFloatingFrame method)
(AuiToolBar method)
(FlatMenuBar method)
OnInternalIdle() (CustomTreeCtrl method)
(UltimateListCtrl method)
(UltimateListHeaderWindow method)
OnItemDelete() (SelectionStore method)
OnItemSelected() (TabNavigatorWindow method), [1]
OnKey() (MultiColumnListCtrl method)
OnKeyDown() (__SToggleMixin method)
(AquaButton method)
(AuiTabCtrl method)
(CustomTreeCtrl method)
(FlatMenu method)
(FocusHandler method)
(GenericMessageDialog method)
(GradientButton method)
(PageContainer method)
(SButton method)
(UltimateListMainWindow method)
(__ToggleMixin method)
OnKeyDown2() (AuiTabCtrl method)
OnKeyUp() (__SToggleMixin method)
(AquaButton method)
(CubeColourDialog method)
(EditTextCtrl method)
(GradientButton method)
(MultiDirDialog method)
(SButton method)
(TabNavigatorWindow method), [1]
(TabTextCtrl method)
(TreeTextCtrl method)
(UltimateListMainWindow method)
(UltimateListTextCtrl method)
(__ToggleMixin method)
OnKillFocus() (AuiTabCtrl method)
(CustomTreeCtrl method)
(EditCtrl method)
(FlatMenu method)
(FloatSpin method)
(FloatTextCtrl method)
(FocusHandler method)
(ListShortcut method)
(PageContainer method)
(RibbonPanel method)
(TabTextCtrl method)
(TreeTextCtrl method)
(UltimateListMainWindow method)
(UltimateListTextCtrl method)
OnLeaveButton() (BalloonFrame method)
OnLeaveMenuBar() (FlatMenuBar method)
OnLeaveWindow() (AuiManager method)
(AuiTabCtrl method)
(AuiToolBar method)
(FlatMenuBar method)
(FourWaySplitter method)
(UltimateListHeaderWindow method)
(ZoomBar method)
(mcPopupWindow method)
OnLeftDClick() (AuiManager method)
(AuiTabCtrl method)
(PageContainer method)
OnLeftDown() (__SToggleMixin method)
(AquaButton method)
(AuiManager method)
(AuiTabCtrl method)
(AuiToolBar method)
(BaseLineCtrl method)
(BasePyControl method)
(ButtonPanel method)
(CustomPanel method)
(FlatMenuBar method)
(FourWaySplitter method)
(GradientButton method)
(HSVWheel method)
(ListShortcut method)
(PageContainer method)
(RGBCube method)
(SButton method)
(ZoomBar method)
(__ToggleMixin method)
OnLeftUp() (__SToggleMixin method)
(AquaButton method)
(AuiManager method)
(AuiTabCtrl method)
(AuiToolBar method)
(BaseLineCtrl method)
(BasePyControl method)
(ButtonPanel method)
(FlatMenuBar method)
(FourWaySplitter method)
(GradientButton method)
(HSVWheel method)
(PageContainer method)
(RGBCube method)
(SButton method)
(ZoomBar method)
(__ToggleMixin method)
OnLeftUp_ClickButton() (AuiManager method)
OnLeftUp_DragFloatingPane() (AuiManager method)
OnLeftUp_DragToolbarPane() (AuiManager method)
OnLeftUp_Resize() (AuiManager method)
OnLoseFocus() (AquaButton method)
(GradientButton method)
(SButton method)
OnMenuChecked() (FMCustomizeDlg method)
OnMenuDismissed() (FlatMenuBar method)
OnMiddleDown() (AuiTabCtrl method)
(AuiToolBar method)
(PageContainer method)
OnMiddleUp() (AuiTabCtrl method)
(AuiToolBar method)
OnMotion() (__SToggleMixin method)
(AuiManager method)
(AuiTabCtrl method)
(AuiToolBar method)
(BaseLineCtrl method)
(BasePyControl method)
(FourWaySplitter method)
(HSVWheel method)
(RGBCube method)
(SButton method)
(ZoomBar method)
(__ToggleMixin method)
OnMotion_ClickCaption() (AuiManager method)
OnMotion_DragFloatingPane() (AuiManager method)
OnMotion_DragToolbarPane() (AuiManager method)
OnMotion_Other() (AuiManager method)
OnMotion_Resize() (AuiManager method)
OnMouse() (CustomTreeCtrl method)
(TreeListHeaderWindow method)
(TreeListMainWindow method)
(UltimateListHeaderWindow method)
(UltimateListMainWindow method)
OnMouseClick() (RibbonPanel method)
OnMouseDClick() (RibbonGallery method)
(ScrolledThumbnail method)
OnMouseDoubleClick() (RibbonBar method)
OnMouseDown() (RibbonButtonBar method)
(RibbonGallery method)
(RibbonPageScrollButton method)
(RibbonToolBar method)
(ScrolledThumbnail method)
(ToasterBoxWindow method)
OnMouseEnter() (AquaButton method)
(GradientButton method)
(RibbonButtonBar method)
(RibbonGallery method)
(RibbonPageScrollButton method)
(RibbonPanel method)
(RibbonToolBar method)
OnMouseEnterChild() (RibbonPanel method)
OnMouseEnterWindow() (ButtonPanel method)
(FlatMenu method)
(PageContainer method)
OnMouseEvent() (CaptionBar method)
(Control method)
(HyperLinkCtrl method)
(MultiColumnListCtrl method)
OnMouseEvents() (AdvancedSplash method)
(KnobCtrl method)
(RulerCtrl method)
OnMouseLeave() (AquaButton method)
(ButtonPanel method)
(GradientButton method)
(PageContainer method)
(RibbonBar method)
(RibbonButtonBar method)
(RibbonGallery method)
(RibbonPageScrollButton method)
(RibbonPanel method)
(RibbonToolBar method)
(ScrolledThumbnail method)
OnMouseLeaveChild() (RibbonPanel method)
OnMouseLeaveWindow() (FlatMenu method)
(ImageContainer method)
(ImageContainerBase method)
(LabelContainer method)
OnMouseLeftDown() (FlatMenu method)
(ImageContainer method)
(ImageContainerBase method)
(LabelContainer method)
(RibbonBar method)
OnMouseLeftUp() (FlatMenu method)
(ImageContainer method)
(ImageContainerBase method)
(LabelContainer method)
(RibbonBar method)
OnMouseMiddleDown() (RibbonBar method)
OnMouseMiddleUp() (RibbonBar method)
OnMouseMotion() (SpeedMeter method)
(ToolTipWindowBase method)
OnMouseMove() (ButtonPanel method)
(FlatMenu method)
(FlatMenuBar method)
(ImageContainer method)
(ImageContainerBase method)
(LabelContainer method)
(PageContainer method)
(RibbonBar method)
(RibbonButtonBar method)
(RibbonGallery method)
(RibbonToolBar method)
(ScrolledThumbnail method)
OnMouseRightDown() (FlatMenu method)
(RibbonBar method)
OnMouseRightUp() (RibbonBar method)
OnMouseUp() (RibbonButtonBar method)
(RibbonGallery method)
(RibbonPageScrollButton method)
(RibbonToolBar method)
(ScrolledThumbnail method)
OnMouseWheel() (FloatSpin method)
(PageContainer method)
(ScrolledThumbnail method)
OnMove() (AuiFloatingFrame method)
(AuiManager method)
OnMoveEvent() (AuiFloatingFrame method)
OnMoveFinished() (AuiFloatingFrame method)
OnMoveStart() (AuiFloatingFrame method)
OnMoveTimer() (ToasterBox method)
OnMoving() (AuiFloatingFrame method)
OnNavigation() (GenericMessageDialog method)
OnNavigationKey() (FlatBookBase method)
(FlatNotebook method)
(TabNavigatorWindow method), [1]
OnNavigationKeyNotebook() (AuiNotebook method)
OnNo() (GenericMessageDialog method)
OnNotify() (AdvancedSplash method)
OnOk() (CubeColourDialog method)
(GenericMessageDialog method)
(MultiDirDialog method)
OnPaint() (__ToggleMixin method)
(AdvancedSplash method)
(AlphaCtrl method)
(AquaButton method)
(AuiCenterDockingGuide method)
(AuiDockingGuideWindow method)
(AuiManager method)
(AuiTabCtrl method)
(AuiToolBar method)
(BasePyControl method)
(BrightCtrl method)
(BufferedWindow method), [1]
(ButtonPanel method)
(CaptionBar method)
(ColourPanel method)
(CustomPanel method)
(CustomTreeCtrl method)
(FMTitlePanel method)
(FlatMenu method)
(FlatMenuBar method)
(FoldPanelItem method)
(FourWaySplitter method)
(GradientButton method)
(ImageContainer method)
(LabelContainer method)
(MultiColumnListCtrl method)
(PageContainer method)
(PeakMeterCtrl method)
(PieCtrl method)
(PieCtrlLegend method)
(ProgressGauge method)
(PyGauge method)
(PyInfoFrame method)
(RibbonBar method)
(RibbonButtonBar method)
(RibbonGallery method)
(RibbonPage method)
(RibbonPageScrollButton method)
(RibbonPanel method)
(RibbonToolBar method)
(RulerCtrl method)
(SButton method)
(ScrolledThumbnail method)
(SwitcherDialog method)
(ToasterBoxWindow method)
(ToolTipWindowBase method)
(TreeListHeaderWindow method)
(TreeListMainWindow method)
(UltimateListHeaderWindow method)
(UltimateListMainWindow method)
(ZoomBar method)
OnPaneButton() (AuiManager method)
OnPaneDocked() (AuiManager method)
OnPanelEraseBg() (TabNavigatorWindow method), [1]
OnPanelPaint() (TabNavigatorWindow method), [1]
OnPopUpCopy() (HyperLinkCtrl method)
OnPressCaption() (FoldPanelBar method)
(FoldPanelItem method)
OnPulseTimer() (AquaButton method)
OnRenameAccept() (AuiNotebook method)
(UltimateListMainWindow method)
OnRenameCancelled() (AuiNotebook method)
(UltimateListMainWindow method)
OnRenameTimer() (UltimateListMainWindow method)
OnRender() (AuiManager method)
OnResize() (ScrolledThumbnail method)
OnRestoreDefaults() (ShortcutEditor method)
OnRestoreMinimizedPane() (AuiManager method)
OnRightDown() (AuiTabCtrl method)
(AuiToolBar method)
(PageContainer method)
OnRightUp() (AuiTabCtrl method)
(AuiToolBar method)
OnScroll() (TreeListMainWindow method)
(UltimateListMainWindow method)
OnScrollTimer() (ToasterBoxWindow method)
OnSelChanged() (ListShortcut method)
(MultiDirDialog method)
OnSelectItem() (SwitcherDialog method)
OnSetCursor() (AuiManager method)
(AuiToolBar method)
OnSetFilter() (ShortcutEditor method)
OnSetFocus() (AuiTabCtrl method)
(CustomTreeCtrl method)
(GenericTreeItem method)
(PageContainer method)
(TreeListHeaderWindow method)
(TreeListItem method)
(UltimateListCtrl method)
(UltimateListHeaderWindow method)
(UltimateListItem method)
(UltimateListMainWindow method)
OnShortcut() (ListShortcut method)
OnShowAlpha() (CubeColourDialog method)
OnSize() (AquaButton method)
(AuiDockingHintWindow method)
(AuiFloatingFrame method)
(AuiManager method)
(AuiNotebook method)
(AuiTabCtrl method)
(AuiToolBar method)
(BaseLineCtrl method)
(BasePyControl method)
(BufferedWindow method), [1]
(ButtonPanel method)
(CaptionBar method)
(ColourPanel method)
(CustomPanel method)
(CustomTreeCtrl method)
(FlatMenuBar method)
(FloatSpin method)
(FourWaySplitter method)
(GTKExpander method)
(GradientButton method)
(HyperTreeList method)
(ImageContainer method)
(ImageContainerBase method)
(LabelBook method)
(LabelContainer method)
(PageContainer method)
(PeakMeterCtrl method)
(PieCtrl method)
(PyCollapsiblePane method)
(RibbonBar method)
(RibbonButtonBar method)
(RibbonGallery method)
(RibbonPage method)
(RibbonPanel method)
(RibbonToolBar method)
(RulerCtrl method)
(SButton method)
(ToolTipWindowBase method)
(UltimateListCtrl method)
(ZoomBar method)
OnSizePanel() (FoldPanelBar method)
OnSpinCtrl() (CubeColourDialog method)
OnSpinDown() (FloatSpin method)
OnSpinMouseDown() (FloatSpin method)
OnSpinUp() (FloatSpin method)
OnStartTimer() (SuperToolTip method)
OnStateChange() (PyCollapsiblePane method)
OnStatusBarTimer() (ButtonPanel method)
(FlatMenuBar method)
OnSysColourChange() (ArtManager method)
OnSysColourChanged() (AuiManager method)
OnTabBeginDrag() (AuiManager method)
(AuiNotebook method)
OnTabBgDClick() (AuiNotebook method)
OnTabButton() (AuiNotebook method)
OnTabCancelDrag() (AuiNotebook method)
OnTabClicked() (AuiNotebook method)
OnTabDClick() (AuiNotebook method)
OnTabDragMotion() (AuiNotebook method)
OnTabEndDrag() (AuiNotebook method)
OnTabMenuSelection() (PageContainer method)
OnTabMiddleDown() (AuiNotebook method)
OnTabMiddleUp() (AuiNotebook method)
OnTabPageClose() (AuiManager method)
OnTabRightDown() (AuiNotebook method)
OnTabRightUp() (AuiNotebook method)
OnTabSelected() (AuiManager method)
OnTaskBarMove() (BalloonTip method)
OnTextEnter() (FloatSpin method)
OnThumbChanged() (ScrolledThumbnail method)
OnTimer() (FlatMenu method)
(PeakMeterCtrl method)
(PyGauge method)
OnUpdateUI() (HTMLHelpWindow method)
OnWidgetEnter() (BalloonTip method)
(SuperToolTip method)
OnWidgetLeave() (BalloonTip method)
(SuperToolTip method)
OnWidgetMotion() (BalloonTip method)
OnYes() (GenericMessageDialog method)
OpenInSameWindow() (HyperLinkCtrl method)
OpenItemContextMenu() (FlatMenu method)
opj() (in module shapedbutton)
(in module thumbnailctrl)
optionActive (AuiPaneInfo attribute)
optionBottomDockable (AuiPaneInfo attribute)
optionBottomSnapped (AuiPaneInfo attribute)
optionCaption (AuiPaneInfo attribute)
optionCaptionLeft (AuiPaneInfo attribute)
optionDestroyOnClose (AuiPaneInfo attribute)
optionDockFixed (AuiPaneInfo attribute)
optionFloatable (AuiPaneInfo attribute)
optionFloating (AuiPaneInfo attribute)
optionFlyOut (AuiPaneInfo attribute)
optionGripper (AuiPaneInfo attribute)
optionGripperTop (AuiPaneInfo attribute)
optionHidden (AuiPaneInfo attribute)
optionLeftDockable (AuiPaneInfo attribute)
optionLeftSnapped (AuiPaneInfo attribute)
optionMaximized (AuiPaneInfo attribute)
optionMinimized (AuiPaneInfo attribute)
optionMovable (AuiPaneInfo attribute)
optionNotebookDockable (AuiPaneInfo attribute)
optionPaneBorder (AuiPaneInfo attribute)
optionResizable (AuiPaneInfo attribute)
optionRightDockable (AuiPaneInfo attribute)
optionRightSnapped (AuiPaneInfo attribute)
optionToolbar (AuiPaneInfo attribute)
optionTopDockable (AuiPaneInfo attribute)
optionTopSnapped (AuiPaneInfo attribute)
OrderPageTabInfoBySmallWidthAsc() (RibbonBar method)

P

Page (CommandNotebookEvent attribute)
(FlatBookBase attribute)
PageContainer (class in flatnotebook)
PageCount (FlatBookBase attribute)
PageImage (FlatBookBase attribute)
PageInfo (class in flatnotebook)
PageText (FlatBookBase attribute)
PaintCrescentGradientBox() (ArtManager method)
PaintCustomColour() (CustomPanel method)
PaintCustomColours() (CustomPanel method)
PaintDiagonalGradientBox() (ArtManager method)
PaintGradientRegion() (ArtManager method)
PaintHighlight() (CustomPanel method)
PaintItem() (CustomTreeCtrl method)
(TreeListMainWindow method)
PaintItems() (SwitcherItems method)
PaintLevel() (CustomTreeCtrl method)
(TreeListMainWindow method)
PaintStraightGradientBox() (ArtManager method)
(in module flatnotebook)
PaintWaterMark() (UltimateListMainWindow method)
PaneBorder() (AuiPaneInfo method)
PaneCreateStippleBitmap() (in module aui.aui_utilities)
PaneFromTabEvent() (AuiManager method)
PaneHitTest() (AuiManager method)
PaneSortFunc() (in module aui.framemanager)
peakmeter (module)
PeakMeterCtrl (class in peakmeter)
PeakMeterData (class in peakmeter)
persist (module)
persist.persist_handlers (module)
persist.persistencemanager (module)
PersistenceManager (class in persist.persistencemanager)
PersistentObject (class in persist.persistencemanager)
PieCtrl (class in piectrl)
piectrl (module)
PieCtrlLegend (class in piectrl)
PiePart (class in piectrl)
PILImageHandler (class in thumbnailctrl)
PinButton() (AuiPaneInfo method)
Play() (ToasterBox method)
(ToasterBoxWindow method)
PointOnLine() (in module cubecolourdialog)
PointOnSash() (ImageContainerBase method)
Populate() (ListShortcut method)
PopulateGrid() (XLSGrid method)
PopulateListControl() (TabNavigatorWindow method), [1]
Popup() (FlatMenu method)
(FlatMenuBase method)
PopupMenu() (RibbonButtonBarEvent method)
(RibbonToolBarEvent method)
(UltimateListCtrl method)
PopupMoreMenu() (FlatMenuBar method)
PopupTabsMenu() (PageContainer method)
Position() (AuiPaneInfo method)
PositionAUI() (FlatMenuBar method)
Prepend() (BoxSizer method)
(FlatMenu method)
PrependItem() (CustomTreeCtrl method)
(FlatMenu method)
(HyperTreeList method)
PrependSeparator() (CustomTreeCtrl method)
PreShow() (ShortcutEditor method)
ProcessDockResult() (AuiManager method)
ProcessEvent() (AuiCommandCapture method)
(MenuKbdRedirector method)
(ToolbarCommandCapture method)
ProcessLeftDown() (FlatMenuButton method)
ProcessLeftUp() (FlatMenuButton method)
ProcessMgrEvent() (AuiManager method)
ProcessMouseLClick() (FlatMenu method)
ProcessMouseLClickEnd() (FlatMenu method)
ProcessMouseMove() (FlatMenu method)
(FlatMenuButton method)
ProcessMouseMoveFromMenu() (FlatMenuBar method)
ProcessMouseRClick() (FlatMenu method)
ProgressGauge (class in pyprogress)
ProgressPie (class in piectrl)
PtFromAngle() (in module cubecolourdialog)
PyBusyInfo (class in pybusyinfo)
pybusyinfo (module)
PyCollapsiblePane (class in pycollapsiblepane)
pycollapsiblepane (module)
PyDate2wxDate() (in module persist.persist_handlers)
PyGauge (class in pygauge)
pygauge (module)
PyImageList (class in ultimatelistctrl)
PyInfoFrame (class in pybusyinfo)
PyProgress (class in pyprogress)
pyprogress (module)

R

rad2deg() (in module cubecolourdialog)
RadioBoxHandler (class in persist.persist_handlers)
RadioButtonHandler (class in persist.persist_handlers)
RandomColour() (ArtManager method)
(in module flatnotebook)
ReadExcelCOM() (in module xlsgrid)
Realise() (RibbonControl method)
Realize() (AuiToolBar method)
(RibbonBar method)
(RibbonButtonBar method)
(RibbonControl method)
(RibbonGallery method)
(RibbonPage method)
(RibbonPanel method)
(RibbonToolBar method)
(StdDialogButtonSizer method)
ReallyDrawTabSeparator() (RibbonMSWArtProvider method)
RecalculateMinSize() (RibbonBar method)
RecalculatePositions() (UltimateListMainWindow method)
RecalculateTabSizes() (RibbonBar method)
RecreateBackground() (PieCtrlLegend method)
RecreateCanvas() (PieCtrl method)
RecreateComboBox() (ThumbnailCtrl method)
ReCreateSizer() (ButtonPanel method)
RecreateTree() (ListShortcut method)
Rect (ButtonInfo attribute)
RecurseOnChildren() (CustomTreeCtrl method)
RecurseTopDir() (MultiDirDialog method)
RedisplayFoldPanelItems() (FoldPanelBar method)
ReDockPage() (AuiNotebook method)
RedrawIconBitmap() (CaptionBar method)
ReenableOtherWindows() (PyProgress method)
Refresh() (HyperTreeList method)
(UltimateListCtrl method)
RefreshAfter() (UltimateListMainWindow method)
RefreshAll() (UltimateListMainWindow method)
RefreshButton() (AuiManager method)
RefreshCaptions() (AuiManager method)
RefreshChilds() (FlatMenu method)
RefreshColLabel() (TreeListHeaderWindow method)
RefreshColour() (ColourPanel method)
RefreshDockingGuides() (in module aui.framemanager)
RefreshItem() (UltimateListCtrl method)
RefreshItems() (UltimateListCtrl method)
RefreshItemWithWindows() (CustomTreeCtrl method)
RefreshLine() (CustomTreeCtrl method)
(UltimateListMainWindow method)
RefreshLines() (UltimateListMainWindow method)
RefreshOverflowState() (AuiToolBar method)
RefreshPanelsFrom() (FoldPanelBar method)
RefreshSelected() (CustomTreeCtrl method)
(UltimateListMainWindow method)
RefreshSelectedUnder() (CustomTreeCtrl method)
RefreshSubtree() (CustomTreeCtrl method)
RefreshTabBar() (RibbonBar method)
Register() (PersistenceManager method)
RegisterAndRestore() (PersistenceManager method)
RegisterAndRestoreAll() (PersistenceManager method)
Reload() (RibbonMSWArtProvider method)
Remove() (BoxSizer method)
(FlatMenu method)
(FlatMenuBar method)
(FlatMenuItemGroup method)
(PyImageList method)
RemoveAll() (PyImageList method)
RemoveAllButtons() (ButtonPanel method)
RemoveAllSeparators() (ButtonPanel method)
RemoveAutoNBCaption() (AuiManager method)
RemoveButton() (AuiTabContainer method)
(InfoBar method)
RemoveChild() (RibbonPage method)
(RibbonPanel method)
RemoveColumn() (HyperTreeList method)
(TreeListHeaderWindow method)
RemoveControlFromPage() (AuiNotebook method)
RemoveEmptyTabFrames() (AuiNotebook method)
RemoveFileFromHistory() (FileHistory method)
RemoveHelp() (ButtonPanel method)
(FlatMenuBar method)
RemoveItemAt() (ScrolledThumbnail method)
RemoveMenu() (FileHistory method)
RemovePage() (AuiNotebook method)
(AuiTabContainer method)
(FlatBookBase method)
(FlatNotebook method)
RemovePaneFromDocks() (in module aui.framemanager)
RemovePanelPadding() (RibbonMSWArtProvider method)
RemoveTabAreaButton() (AuiNotebook method)
RemoveText() (ButtonPanel method)
Render() (AuiManager method)
(AuiTabContainer method)
RendererBase (class in artmanager)
RendererMSOffice2007 (class in artmanager)
RendererXP (class in artmanager)
RenumberDockRows() (in module aui.framemanager)
Repaint() (AuiManager method)
RepaintOldSelection() (ButtonPanel method)
ReparentControl() (AuiNotebook method)
Replace() (PyImageList method)
ReplaceDoubleZero() (FloatSpin method)
ReplaceIcon() (PyImageList method)
ReplaceWindow() (FourWaySplitter method)
ReportErrors() (HyperLinkCtrl method)
Reposition() (FoldPanelItem method)
(ZoomBar method)
RepositionCollapsedToBottom() (FoldPanelBar method)
RepositionPage() (RibbonBar method)
RepositionPane() (AuiManager method)
RequestUserAttention() (AuiDefaultDockArt method)
(AuiManager method)
(ModernDockArt method)
RescaleScreenShot() (in module aui.aui_utilities)
ResetButtons() (AuiPaneInfo method)
ResetControl() (PeakMeterCtrl method)
ResetCurrent() (UltimateListMainWindow method)
ResetDefaults() (CaptionBarStyle method)
ResetDimensions() (UltimateListLineData method)
ResetEditControl() (CustomTreeCtrl method)
ResetLineDimensions() (UltimateListMainWindow method)
ResetSize() (ZoomBar method)
ResetTextControl() (AuiNotebook method)
(UltimateListMainWindow method)
ResetToolbarItems() (FlatMenuBar method)
ResetVisibility() (Shortcut method)
ResetVisibleLinesRange() (UltimateListMainWindow method)
Resizable() (AuiPaneInfo method)
Resize() (LabelContainer method)
ResizeColumns() (UltimateListMainWindow method)
ResizeItem() (FoldWindowItem method)
ResizeMenu() (FlatMenu method)
ResizePanel() (FoldPanelItem method)
ResizeTabArea() (FlatBookBase method)
Restore() (AbstractHandler method)
(AuiPaneInfo method)
(PersistenceManager method)
(PersistentObject method)
RestoreCtrlValue() (PersistenceManager method)
(PersistentObject method)
RestoreDefaults() (Shortcut method)
RestoreMaximizedPane() (AuiManager method)
RestoreMinimizedPane() (AuiManager method)
RestoreOldDC() (in module cubecolourdialog)
RestorePane() (AuiManager method)
RestoreValue() (PersistenceManager method)
(PersistentObject method)
RestrictResize() (AuiManager method)
ReverseHighlight() (UltimateListLineData method)
(UltimateListMainWindow method)
rgb2html() (in module cubecolourdialog)
RGBCube (class in cubecolourdialog)
ribbon (module)
ribbon.art_aui (module)
ribbon.art_internal (module)
ribbon.art_msw (module)
ribbon.bar (module)
ribbon.buttonbar (module)
ribbon.control (module)
ribbon.gallery (module)
ribbon.page (module)
ribbon.panel (module)
ribbon.toolbar (module)
RibbonAUIArtProvider (class in ribbon.art_aui)
RibbonBar (class in ribbon.bar)
RibbonBarEvent (class in ribbon.bar)
RibbonButtonBar (class in ribbon.buttonbar)
RibbonButtonBarButtonBase (class in ribbon.buttonbar)
RibbonButtonBarButtonInstance (class in ribbon.buttonbar)
RibbonButtonBarButtonSizeInfo (class in ribbon.buttonbar)
RibbonButtonBarEvent (class in ribbon.buttonbar)
RibbonButtonBarLayout (class in ribbon.buttonbar)
RibbonCanLabelBreakAtPosition() (in module ribbon.art_internal)
RibbonControl (class in ribbon.control)
RibbonDrawParallelGradientLines() (in module ribbon.art_internal)
RibbonGallery (class in ribbon.gallery)
RibbonGalleryEvent (class in ribbon.gallery)
RibbonGalleryItem (class in ribbon.gallery)
RibbonHSLColour (class in ribbon.art_internal)
RibbonInterpolateColour() (in module ribbon.art_internal)
RibbonLoadPixmap() (in module ribbon.art_internal)
RibbonMSWArtProvider (class in ribbon.art_msw)
RibbonPage (class in ribbon.page)
RibbonPageScrollButton (class in ribbon.page)
RibbonPageTabInfo (class in ribbon.art_internal)
RibbonPanel (class in ribbon.panel)
RibbonShiftLuminance() (in module ribbon.art_internal)
RibbonToolBar (class in ribbon.toolbar)
RibbonToolBarEvent (class in ribbon.toolbar)
RibbonToolBarToolBase (class in ribbon.toolbar)
RibbonToolBarToolGroup (class in ribbon.toolbar)
Right() (AuiDockingGuideInfo method)
(AuiPaneInfo method)
RightDockable() (AuiPaneInfo method)
RightSnappable() (AuiPaneInfo method)
Rotate() (ScrolledThumbnail method)
RotateImage() (Indicator method)
RotateLeft() (PageContainer method)
RotateRight() (PageContainer method)
Row() (AuiPaneInfo method)
RulerCtrl (class in rulerctrl)
rulerctrl (module)
RulerCtrlEvent (class in rulerctrl)

S

Saturated() (RibbonHSLColour method)
Save() (AbstractHandler method)
(FileHistory method)
(PersistenceManager method)
(PersistentObject method)
SaveAndUnregister() (PersistenceManager method)
SaveCtrlValue() (PersistenceManager method)
(PersistentObject method)
savedHiddenState (AuiPaneInfo attribute)
SavePaneInfo() (AuiManager method)
SavePerspective() (AuiManager method)
(AuiNotebook method)
SavePreviousDockSizes() (AuiManager method)
SaveValue() (PersistenceManager method)
(PersistentObject method)
SBitmapButton (class in shapedbutton)
SBitmapTextButton (class in shapedbutton)
SBitmapTextToggleButton (class in shapedbutton)
SBitmapToggleButton (class in shapedbutton)
SButton (class in shapedbutton)
SButtonEvent (class in shapedbutton)
scaletomax() (in module cubecolourdialog)
ScreenToClient() (UltimateListCtrl method)
ScreenToClientXY() (UltimateListCtrl method)
ScrollDown() (FlatMenu method)
(FlatMenuBase method)
(ToasterBoxWindow method)
ScrolledThumbnail (class in thumbnailctrl)
ScrolledWindowHandler (class in persist.persist_handlers)
ScrollLines() (RibbonGallery method)
(RibbonPage method)
ScrollList() (UltimateListCtrl method)
(UltimateListMainWindow method)
ScrollPixels() (RibbonPage method)
ScrollTabBar() (RibbonBar method)
ScrollTo() (CustomTreeCtrl method)
(HyperTreeList method)
(TreeListMainWindow method)
ScrollToSelected() (ScrolledThumbnail method)
ScrollUp() (FlatMenu method)
(FlatMenuBase method)
(ToasterBoxWindow method)
SecondColourUsed() (CaptionBarStyle method)
Select() (FlatToolbarItem method)
(UltimateListCtrl method)
SelectAll() (CustomTreeCtrl method)
(HyperTreeList method)
SelectAllChildren() (CustomTreeCtrl method)
(HyperTreeList method)
Selection (CommandNotebookEvent attribute)
(FlatBookBase attribute)
SelectionStore (class in ultimatelistctrl)
SelectItem() (CustomTreeCtrl method)
(HyperTreeList method)
(SelectionStore method)
SelectItemRange() (CustomTreeCtrl method)
SelectRange() (SelectionStore method)
SendCmdEvent() (FlatMenu method)
SendDeleteEvent() (CustomTreeCtrl method)
SendListEvent() (TreeListHeaderWindow method)
(UltimateListHeaderWindow method)
SendNotify() (UltimateListMainWindow method)
SendOverItem() (FlatMenu method)
SendUIEvent() (FlatMenu method)
Separator (class in buttonpanel)
Set3State() (GenericTreeItem method)
Set3StateValue() (GenericTreeItem method)
SET_FLAG() (in module ribbon.bar)
set_precision() (FixedPoint method)
SetAccelerator() (Shortcut method)
(ShortcutEvent method)
SetActive() (AuiToolBarItem method)
SetActivePage() (AuiTabContainer method)
(RibbonBar method)
SetActivePageByIndex() (RibbonBar method)
SetActivePageByPage() (RibbonBar method)
SetActivePane() (in module aui.framemanager)
SetActiveTabColour() (FlatNotebook method)
SetActiveTabTextColour() (FlatNotebook method)
SetAffirmativeButton() (StdDialogButtonSizer method)
SetAGWFlags() (AuiDefaultTabArt method)
(AuiDefaultToolBarArt method)
(AuiManager method)
(AuiSimpleTabArt method)
(AuiTabContainer method)
(ChromeTabArt method)
SetAGWWindowStyleFlag() (AuiNotebook method)
(AuiToolBar method)
(CubeColourDialog method)
(CustomTreeCtrl method)
(FlatBookBase method)
(FlatNotebook method)
(FourWaySplitter method)
(HyperTreeList method)
(PageContainer method)
(PeakMeterCtrl method)
(PyCollapsiblePane method)
(RibbonBar method)
(UltimateListCtrl method)
SetAlign() (UltimateListItem method)
SetAlignment() (AuiToolBarItem method)
(ButtonPanel method)
(TreeListColumnInfo method)
SetAllPagesShapeAngle() (FlatNotebook method)
SetAngle() (PieCtrl method)
SetAngleOfRotation() (SButton method)
SetAngleRange() (SpeedMeter method)
SetAngularRange() (KnobCtrl method)
SetAnimationStep() (AuiManager method)
SetArcColour() (SpeedMeter method)
SetArtProvider() (AuiManager method)
(AuiNotebook method)
(AuiTabContainer method)
(AuiToolBar method)
(RibbonBar method)
(RibbonButtonBar method)
(RibbonControl method)
(RibbonPage method)
(RibbonPanel method)
SetAttr() (UltimateListItemData method)
(UltimateListLineData method)
SetAttributes() (AuiManager method)
(GenericTreeItem method)
(UltimateListLineData method)
SetAuiManager() (AuiToolBar method)
SetAutoNotebookStyle() (AuiManager method)
SetAutoNotebookTabArt() (AuiManager method)
SetBackColour() (PieCtrl method)
(PieCtrlLegend method)
SetBackground() (PieCtrl method)
SetBackgroundBitmap() (FlatMenu method)
(LabelContainer method)
SetBackgroundColor() (AquaButton method)
SetBackgroundColour() (AquaButton method)
(CustomTreeCtrl method)
(FlatMenuBar method)
(HyperTreeList method)
(PeakMeterCtrl method)
(RulerCtrl method)
(SwitcherItems method)
(TreeItemAttr method)
(UltimateListCtrl method)
(UltimateListItem method)
(UltimateListItemAttr method)
(UltimateListItemData method)
SetBackgroundImage() (CustomTreeCtrl method)
(HyperTreeList method)
(UltimateListCtrl method)
(UltimateListMainWindow method)
SetBalloonColour() (BalloonTip method)
SetBalloonIcon() (BalloonTip method)
SetBalloonMessage() (BalloonTip method)
SetBalloonShape() (BalloonFrame method)
(BalloonTip method)
SetBalloonTipStyle() (BalloonTip method)
SetBalloonTitle() (BalloonTip method)
SetBandsColour() (PeakMeterCtrl method)
SetBar() (CaptionBarEvent method)
(RibbonButtonBarEvent method)
(RibbonToolBarEvent method)
SetBarColor() (PyGauge method)
SetBarColour() (ImageBar method)
(PyGauge method)
(ZoomBar method)
SetBarGradient() (PyGauge method)
SetBarHeight() (FlatMenuBar method)
SetBarText() (ButtonPanel method)
SetBaseColour() (AuiDefaultTabArt method)
SetBaseColours() (GradientButton method)
SetBaseId() (FileHistory method)
SetBestSize() (AquaButton method)
(GradientButton method)
(SButton method)
SetBitmap() (AuiToolBarItem method)
(ButtonInfo method)
(FlatToolbarItem method)
(RibbonGalleryItem method)
(Shortcut method)
(SwitcherItem method)
(Thumb method)
SetBitmapDisabled() (SBitmapButton method)
SetBitmapFocus() (SBitmapButton method)
SetBitmapLabel() (AquaButton method)
(SBitmapButton method)
SetBitmaps() (ChromeTabArt method)
SetBitmapSelected() (SBitmapButton method)
SetBlindMode() (AuiDockingHintWindow method)
SetBodyImage() (SuperToolTip method)
SetBold() (GenericTreeItem method)
(HyperLinkCtrl method)
SetBoldFont() (CaptionBar method)
SetBorderColor() (PyGauge method)
SetBorderColour() (PyGauge method)
(SwitcherDialog method)
SetBorderPadding() (PyGauge method)
SetBorderPen() (CustomTreeCtrl method)
(HyperTreeList method)
SetBottomEndColour() (GradientButton method)
SetBottomGradientColor() (SuperToolTip method)
SetBottomGradientColour() (SuperToolTip method)
SetBottomStartColour() (GradientButton method)
SetBoundingColour() (KnobCtrl method)
SetBounds() (RulerCtrl method)
SetBPArt() (ButtonPanel method)
SetBuffered() (HyperTreeList method)
(TreeListHeaderWindow method)
(TreeListMainWindow method)
SetBusyShape() (PyInfoFrame method)
SetButton() (AuiManagerEvent method)
(PyCollapsiblePane method)
SetButtonColour() (SButton method)
SetButtonFont() (PyCollapsiblePane method)
SetButtonObj() (AquaButtonEvent method)
(GradientButtonEvent method)
(SButtonEvent method)
SetButtonsImageList() (CustomTreeCtrl method)
(HyperTreeList method)
SetButtonSize() (ZoomBar method)
SetCancelButton() (StdDialogButtonSizer method)
SetCanVeto() (AuiManagerEvent method)
SetCaption() (ImageInfo method)
(PageInfo method)
(ScrolledThumbnail method)
(Thumb method)
SetCaptionColour() (CaptionBarStyle method)
SetCaptionFont() (CaptionBarStyle method)
(ScrolledThumbnail method)
SetCaptionStyle() (CaptionBar method)
(CaptionBarStyle method)
SetCellSize() (XLSCell method)
SetCenterZoom() (ZoomBar method)
(ZoomBarImage method)
SetCheckedState() (TreeCtrlHandler method)
SetCheckedStateOfChildren() (TreeCtrlHandler method)
SetCheckedStateOfItem() (TreeCtrlHandler method)
SetClickPoint() (CommandToolBarEvent method)
SetClientData() (RibbonGalleryItem method)
SetCloseButton() (AuiNotebook method)
SetCodes() (CubeColourDialog method)
SetColor() (AuiDefaultDockArt method)
(BPArt method)
SetColour() (AuiDefaultDockArt method)
(BPArt method)
(Indicator method)
(LabelBook method)
(LabelContainer method)
(PageInfo method)
(PiePart method)
(RibbonAUIArtProvider method)
(RibbonMSWArtProvider method)
(TreeListColumnInfo method)
(UltimateListItemData method)
(UltimateListLineData method)
SetColours() (HyperLinkCtrl method)
SetColourScheme() (RibbonAUIArtProvider method)
(RibbonMSWArtProvider method)
SetColPos() (SwitcherItem method)
SetColumn() (HyperTreeList method)
(TreeListHeaderWindow method)
(UltimateListCtrl method)
(UltimateListItem method)
(UltimateListMainWindow method)
SetColumnAlignment() (HyperTreeList method)
(TreeListHeaderWindow method)
SetColumnColour() (HyperTreeList method)
(TreeListHeaderWindow method)
SetColumnCount() (SwitcherItems method)
SetColumnCustomRenderer() (UltimateListCtrl method)
(UltimateListMainWindow method)
SetColumnEditable() (HyperTreeList method)
SetColumnFont() (HyperTreeList method)
SetColumnImage() (HyperTreeList method)
(UltimateListCtrl method)
SetColumnShown() (HyperTreeList method)
(UltimateListCtrl method)
SetColumnText() (HyperTreeList method)
(TreeListHeaderWindow method)
SetColumnToolTip() (UltimateListCtrl method)
SetColumnWidth() (HyperTreeList method)
(TreeListHeaderWindow method)
(UltimateListCtrl method)
(UltimateListMainWindow method)
SetColumnWidths() (ShortcutEditor method)
SetConfigurationHandler() (PersistenceManager method)
SetConnectionPen() (CustomTreeCtrl method)
(HyperTreeList method)
SetContextMenu() (FlatMenuItem method)
SetCursor() (UltimateListCtrl method)
SetCustomButton() (AuiDefaultTabArt method)
(AuiSimpleTabArt method)
SetCustomOverflowItems() (AuiToolBar method)
SetCustomPage() (FlatNotebook method)
SetCustomPaneBitmap() (AuiDefaultDockArt method)
SetCustomRenderer() (TreeListHeaderWindow method)
(UltimateListHeaderData method)
(UltimateListHeaderWindow method)
(UltimateListItem method)
(UltimateListItemData method)
SetData() (GenericTreeItem method)
(PeakMeterCtrl method)
(UltimateListItem method)
(UltimateListItemData method)
SetDC() (AuiManagerEvent method)
SetDefault() (AquaButton method)
(GradientButton method)
(SButton method)
SetDefaultColours() (AuiDefaultDockArt method)
(AuiDefaultTabArt method)
(AuiDefaultToolBarArt method)
SetDefaultPaneBitmaps() (AuiDefaultDockArt method)
SetDefaultValue() (FloatSpin method)
SetDescription() (SwitcherItem method)
SetDigits() (FloatSpin method)
SetDirection() (SpeedMeter method)
SetDisabledBitmap() (AuiToolBarItem method)
(FlatMenuItem method)
(FlatToolbarItem method)
SetDisabledColor() (AquaButton method)
SetDisabledColour() (AquaButton method)
(CustomTreeCtrl method)
(HyperTreeList method)
SetDisabledTextColour() (UltimateListCtrl method)
(UltimateListMainWindow method)
SetDispatched() (CommandNotebookEvent method)
SetDockPos() (AuiPaneInfo method)
SetDockSizeConstraint() (AuiManager method)
SetDragItem() (HyperTreeList method)
(TreeListMainWindow method)
SetDragSource() (CommandNotebookEvent method)
SetDrawFooterLine() (SuperToolTip method)
SetDrawHeaderLine() (SuperToolTip method)
SetDrawingParent() (RulerCtrl method)
SetDropDownClicked() (CommandToolBarEvent method)
SetDropShadow() (ScrolledThumbnail method)
(SuperToolTip method)
SetDropTarget() (UltimateListCtrl method)
SetEditable() (TreeListColumnInfo method)
SetEditCanceled() (CommandListEvent method)
(CommandNotebookEvent method)
(CommandTreeEvent method)
SetEffectDuration() (InfoBar method)
SetElementSize() (AuiDefaultToolBarArt method)
SetEllipseAxis() (SButton method)
SetEndDelay() (BalloonTip method)
(SuperToolTip method)
SetExpanded() (FourWaySplitter method)
SetExpanderDimensions() (PyCollapsiblePane method)
SetExpansionState() (TreeCtrlHandler method)
SetExpansionStateOfChildren() (TreeCtrlHandler method)
SetExpansionStateOfItem() (TreeCtrlHandler method)
SetExtendedMessage() (GenericMessageDialog method)
SetExtraNavigationKey() (MultiColumnListCtrl method)
(SwitcherDialog method)
SetFalloffDelay() (PeakMeterCtrl method)
SetFalloffEffect() (PeakMeterCtrl method)
SetFileName() (Thumb method)
SetFilledColour() (ProgressPie method)
SetFillerColour() (SpeedMeter method)
SetFilter() (ListShortcut method)
SetFirstColour() (CaptionBarStyle method)
SetFirstGradientColour() (CustomTreeCtrl method)
(HyperTreeList method)
(KnobCtrl method)
(ProgressGauge method)
(PyProgress method)
(SpeedMeter method)
(UltimateListCtrl method)
(UltimateListMainWindow method)
SetFlag() (AuiPaneInfo method)
SetFlags() (RibbonMSWArtProvider method)
SetFlip() (RulerCtrl method)
SetFocus() (Control method)
(HyperTreeList method)
(UltimateListCtrl method)
SetFocusedPage() (PageContainer method)
SetFont() (AuiDefaultDockArt method)
(AuiDefaultToolBarArt method)
(AuiNotebook method)
(AuiToolBar method)
(BPArt method)
(CustomTreeCtrl method)
(FlatMenuItem method)
(FloatSpin method)
(HyperTreeList method)
(InfoBar method)
(RibbonAUIArtProvider method)
(RibbonMSWArtProvider method)
(SwitcherItem method)
(ToolTipWindowBase method)
(TreeItemAttr method)
(TreeListColumnInfo method)
(UltimateListCtrl method)
(UltimateListHeaderData method)
(UltimateListItem method)
(UltimateListItemAttr method)
(UltimateListItemData method)
(UltimateListMainWindow method)
SetFontBold() (FlatBookBase method)
SetFonts() (RulerCtrl method)
SetFontSizeMultiple() (FlatBookBase method)
SetFooter() (SuperToolTip method)
SetFooterAlign() (UltimateListItem method)
SetFooterBackgroundColour() (UltimateListItem method)
(UltimateListItemAttr method)
SetFooterBitmap() (SuperToolTip method)
SetFooterCustomRenderer() (UltimateListCtrl method)
SetFooterFont() (SuperToolTip method)
(UltimateListHeaderData method)
(UltimateListItem method)
(UltimateListItemAttr method)
SetFooterFormat() (UltimateListHeaderData method)
(UltimateListItem method)
SetFooterHeight() (UltimateListCtrl method)
SetFooterImage() (UltimateListItem method)
SetFooterKind() (UltimateListHeaderData method)
(UltimateListItem method)
SetFooterText() (UltimateListItem method)
SetFooterTextColour() (UltimateListItem method)
(UltimateListItemAttr method)
SetForegroundColour() (AquaButton method)
(CustomTreeCtrl method)
(GradientButton method)
(HyperTreeList method)
(UltimateListCtrl method)
SetFormat() (FloatSpin method)
(RulerCtrl method)
(UltimateListHeaderData method)
SetFrame() (AuiManager method)
SetGallery() (RibbonGalleryEvent method)
SetGalleryItem() (RibbonGalleryEvent method)
SetGaugeBackground() (ProgressGauge method)
(PyProgress method)
SetGaugeProportion() (ProgressGauge method)
(PyProgress method)
SetGaugeSteps() (ProgressGauge method)
(PyProgress method)
SetGlobalPopupMenu() (ScrolledThumbnail method)
SetGradientColourBorder() (FlatNotebook method)
SetGradientColourFrom() (FlatNotebook method)
SetGradientColours() (FlatNotebook method)
SetGradientColourTo() (FlatNotebook method)
SetGradientStyle() (CustomTreeCtrl method)
(HyperTreeList method)
(UltimateListCtrl method)
(UltimateListMainWindow method)
SetGradientType() (BPArt method)
SetGripperVisible() (AuiToolBar method)
SetGroup() (FlatToolbarItem method)
SetGuideShape() (AuiCenterDockingGuide method)
(AuiSingleDockingGuide method)
SetHandColour() (SpeedMeter method)
SetHandStyle() (SpeedMeter method)
SetHasDropDown() (AuiToolBarItem method)
SetHasPlus() (GenericTreeItem method)
SetHeader() (SuperToolTip method)
SetHeaderBitmap() (SuperToolTip method)
SetHeaderCustomRenderer() (HyperTreeList method)
(UltimateListCtrl method)
SetHeaderFont() (HyperTreeList method)
(SuperToolTip method)
SetHeaderHeight() (UltimateListCtrl method)
SetHeight() (GenericTreeItem method)
(PieCtrl method)
(UltimateListHeaderData method)
(UltimateListLineData method)
SetHelp() (FlatMenuItem method)
SetHelpBitmap() (GenericMessageDialog method)
SetHelpLabel() (GenericMessageDialog method)
SetHighlightPointed() (ScrolledThumbnail method)
SetHilight() (GenericTreeItem method)
SetHilightFocusColour() (CustomTreeCtrl method)
(HyperTreeList method)
SetHilightNonFocusColour() (CustomTreeCtrl method)
(HyperTreeList method)
SetHorizontalBorder() (PieCtrlLegend method)
SetHotBitmap() (FlatMenuItem method)
SetHoverBitmap() (AuiToolBarItem method)
SetHoverColor() (AquaButton method)
SetHoverColour() (AquaButton method)
SetHoverItem() (AuiToolBar method)
SetHSplit() (FourWaySplitter method)
SetHTMLHelpFile() (ShortcutEditor method)
SetHyperlinkFont() (SuperToolTip method)
SetHyperText() (GenericTreeItem method)
(UltimateListItem method)
(UltimateListItemData method)
SetHyperTextFont() (CustomTreeCtrl method)
(HyperTreeList method)
(UltimateListCtrl method)
(UltimateListMainWindow method)
SetHyperTextNewColour() (CustomTreeCtrl method)
(HyperTreeList method)
(UltimateListCtrl method)
(UltimateListMainWindow method)
SetHyperTextVisitedColour() (CustomTreeCtrl method)
(HyperTreeList method)
(UltimateListCtrl method)
(UltimateListMainWindow method)
SetId() (AuiToolBarItem method)
(ButtonInfo method)
(RibbonGalleryItem method)
(SwitcherItem method)
(Thumb method)
(UltimateListItem method)
SetImage() (GenericTreeItem method)
(Thumb method)
(TreeListColumnInfo method)
(TreeListItem method)
(UltimateListItem method)
(UltimateListItemData method)
(UltimateListLineData method)
SetImageIndex() (ImageInfo method)
(PageInfo method)
SetImageList() (AuiNotebook method)
(CustomTreeCtrl method)
(FlatNotebook method)
(HyperTreeList method)
(PageContainer method)
(UltimateListCtrl method)
(UltimateListMainWindow method)
SetImageListCheck() (CustomTreeCtrl method)
(HyperTreeList method)
(UltimateListMainWindow method)
SetIncrement() (FloatSpin method)
SetIndent() (CustomTreeCtrl method)
(HyperTreeList method)
SetIndicatorColour() (RulerCtrl method)
SetIndicatorValue() (RulerCtrl method)
SetInitialSize() (AquaButton method)
(GradientButton method)
SetIntervalColours() (SpeedMeter method)
SetIntervals() (SpeedMeter method)
SetIsDown() (SButtonEvent method)
SetIsGroup() (SwitcherItem method)
SetIsVisible() (RibbonGalleryItem method)
SetItalic() (GenericTreeItem method)
SetItem() (CommandTreeEvent method)
(UltimateListCtrl method)
(UltimateListHeaderData method)
(UltimateListItemData method)
(UltimateListLineData method)
(UltimateListMainWindow method)
SetItem3State() (CustomTreeCtrl method)
(HyperTreeList method)
SetItem3StateValue() (CustomTreeCtrl method)
(HyperTreeList method)
SetItemBackgroundColour() (CustomTreeCtrl method)
(HyperTreeList method)
(UltimateListCtrl method)
SetItemBold() (CustomTreeCtrl method)
(HyperTreeList method)
SetItemClientData() (RibbonGallery method)
SetItemColumnImage() (UltimateListCtrl method)
SetItemCount() (SelectionStore method)
(UltimateListCtrl method)
(UltimateListMainWindow method)
SetItemCustomRenderer() (UltimateListCtrl method)
(UltimateListMainWindow method)
SetItemData() (UltimateListCtrl method)
SetItemDropHighlight() (CustomTreeCtrl method)
(HyperTreeList method)
SetItemFont() (CustomTreeCtrl method)
(FlatMenu method)
(HyperTreeList method)
(SwitcherItems method)
(UltimateListCtrl method)
SetItemHasChildren() (CustomTreeCtrl method)
(HyperTreeList method)
SetItemHyperText() (CustomTreeCtrl method)
(HyperTreeList method)
(UltimateListCtrl method)
(UltimateListMainWindow method)
SetItemImage() (CustomTreeCtrl method)
(HyperTreeList method)
(TreeListMainWindow method)
(UltimateListCtrl method)
SetItemItalic() (CustomTreeCtrl method)
(HyperTreeList method)
SetItemKind() (UltimateListCtrl method)
(UltimateListMainWindow method)
SetItemLeftImage() (CustomTreeCtrl method)
SetItemOverFlow() (UltimateListCtrl method)
(UltimateListMainWindow method)
SetItemPosition() (UltimateListCtrl method)
SetItemPyData() (CustomTreeCtrl method)
(HyperTreeList method)
(UltimateListCtrl method)
SetItemRect() (CommandToolBarEvent method)
SetItems() (MultiColumnListCtrl method)
SetItemSpacing() (UltimateListCtrl method)
(UltimateListMainWindow method)
SetItemState() (UltimateListCtrl method)
(UltimateListMainWindow method)
SetItemStateAll() (UltimateListMainWindow method)
SetItemText() (CustomTreeCtrl method)
(HyperTreeList method)
(TreeListMainWindow method)
(UltimateListCtrl method)
(UltimateListMainWindow method)
SetItemTextColour() (CustomTreeCtrl method)
(FlatMenu method)
(HyperTreeList method)
(UltimateListCtrl method)
SetItemType() (CustomTreeCtrl method)
(HyperTreeList method)
SetItemVisited() (CustomTreeCtrl method)
(HyperTreeList method)
(UltimateListCtrl method)
(UltimateListMainWindow method)
SetItemWindow() (CustomTreeCtrl method)
(HyperTreeList method)
(TreeListMainWindow method)
(UltimateListCtrl method)
(UltimateListMainWindow method)
SetItemWindowEnabled() (CustomTreeCtrl method)
(HyperTreeList method)
(TreeListMainWindow method)
(UltimateListCtrl method)
(UltimateListMainWindow method)
SetKeyEvent() (CommandTreeEvent method)
SetKind() (AuiToolBarItem method)
(ButtonInfo method)
(UltimateListHeaderData method)
(UltimateListItem method)
(UltimateListItemData method)
(UltimateListLineData method)
SetKnobRadius() (KnobCtrl method)
SetLabel() (AuiToolBarItem method)
(CommandNotebookEvent method)
(CommandTreeEvent method)
(FlatMenu method)
(FlatMenuItem method)
(FlatToolbarItem method)
(PiePart method)
(PyCollapsiblePane method)
(SButton method)
(ZoomBarEvent method)
(ZoomBarImage method)
SetLabelColour() (PieCtrlLegend method)
(RulerCtrl method)
(SButton method)
SetLabelControl() (ScrolledThumbnail method)
SetLabelEdges() (RulerCtrl method)
SetLabelFont() (PieCtrlLegend method)
SetLCDMonitor() (FlatMenuBar method)
SetLeftImage() (GenericTreeItem method)
SetLeftImageList() (CustomTreeCtrl method)
SetLinkCursor() (HyperLinkCtrl method)
SetLog() (RulerCtrl method)
SetLongHelp() (AuiToolBarItem method)
(ButtonInfo method)
(FlatMenuItem method)
(FlatToolbarItem method)
SetMainColumn() (HyperTreeList method)
(TreeListMainWindow method)
SetManagedWindow() (AuiManager method)
SetManager() (AuiManagerEvent method)
SetManagerStyle() (PersistenceManager method)
SetMargin() (FlatMenuBar method)
SetMargins() (AuiToolBar method)
SetMarginsSize() (AuiToolBar method)
SetMarginsXY() (AuiToolBar method)
SetMask() (UltimateListItem method)
SetMasterManager() (AuiManager method)
SetMaxValue() (ProgressPie method)
SetMBVerticalGradient() (ArtManager method)
SetMeasuringFont() (AuiDefaultTabArt method)
(AuiNotebook method)
(AuiSimpleTabArt method)
(AuiTabContainer method)
SetMenu() (FlatMenuItem method)
(FocusHandler method)
(MenuKbdRedirector method)
SetMenuBar() (FlatMenu method)
(FlatMenuItem method)
SetMenuBarColour() (ArtManager method)
SetMenuBarHighlightColour() (FMRenderer method)
SetMenuHighlightColour() (FMRenderer method)
SetMenuTheme() (ArtManager method)
SetMessage() (GenericMessageDialog method)
(SuperToolTip method)
SetMessageColour() (BalloonTip method)
SetMessageFont() (BalloonTip method)
(SuperToolTip method)
SetMeterBands() (PeakMeterCtrl method)
SetMetric() (AuiDefaultDockArt method)
(BPArt method)
(RibbonMSWArtProvider method)
SetMiddleGradientColor() (SuperToolTip method)
SetMiddleGradientColour() (SuperToolTip method)
SetMiddleIcon() (SpeedMeter method)
SetMiddleText() (SpeedMeter method)
SetMiddleTextColour() (SpeedMeter method)
SetMiddleTextFont() (SpeedMeter method)
SetMinMaxTabWidth() (AuiNotebook method)
SetMinSize() (AuiToolBarItem method)
SetModifierKey() (MultiColumnListCtrl method)
(SwitcherDialog method)
SetMS2007ButtonSunken() (ArtManager method)
SetName() (SwitcherItem method)
SetNameFromNotebookId() (AuiPaneInfo method)
SetNavigatorIcon() (AuiNotebook method)
(FlatNotebook method)
SetNegativeButton() (StdDialogButtonSizer method)
SetNonActiveTabTextColour() (FlatNotebook method)
SetNoneActive() (AuiTabContainer method)
SetNormalBitmap() (FlatMenuItem method)
SetNormalFont() (AuiDefaultTabArt method)
(AuiNotebook method)
(AuiSimpleTabArt method)
(AuiTabContainer method)
(CaptionBar method)
SetNotebook() (FlatNotebookDragEvent method)
SetNumberColumns() (FlatMenu method)
SetNumberOfSecondaryTicks() (SpeedMeter method)
SetOKBitmap() (GenericMessageDialog method)
SetOKCancelBitmaps() (GenericMessageDialog method)
SetOKCancelLabels() (GenericMessageDialog method)
SetOKLabel() (GenericMessageDialog method)
SetOldAccelerator() (ShortcutEvent method)
SetOldItem() (CommandTreeEvent method)
SetOldNotebook() (FlatNotebookDragEvent method)
SetOldSelection() (CommandNotebookEvent method)
(FlatNotebookEvent method)
(ImageNotebookEvent method)
SetOldValue() (KnobCtrlEvent method)
(RulerCtrlEvent method)
SetOptions() (FlatMenuBar method)
SetOrientation() (AuiDefaultToolBarArt method)
(AuiToolBar method)
(AuiToolBarItem method)
(RulerCtrl method)
(ScrolledThumbnail method)
SetOverFlow() (UltimateListItem method)
(UltimateListItemData method)
SetOverflowVisible() (AuiToolBar method)
SetOwnerHeight() (FlatMenuBase method)
SetPadding() (FlatNotebook method)
SetPage() (RibbonBarEvent method)
SetPageBitmap() (AuiNotebook method)
SetPageImage() (AuiNotebook method)
(FlatBookBase method)
(FlatNotebook method)
(ImageContainerBase method)
(PageContainer method)
SetPageShapeAngle() (FlatNotebook method)
SetPageText() (AuiNotebook method)
(FlatBookBase method)
(FlatNotebook method)
(ImageContainerBase method)
(PageContainer method)
SetPageTextColour() (AuiNotebook method)
(FlatNotebook method)
(PageContainer method)
(PageInfo method)
SetPane() (AuiManagerEvent method)
SetPanelColours() (CubeColourDialog method)
SetPaneWindow() (AuiFloatingFrame method)
SetPersistenceFile() (PersistenceManager method)
SetPersistenceKey() (PersistenceManager method)
SetPoint() (CommandTreeEvent method)
SetPopupBackgroundColour() (ToasterBox method)
(ToasterBoxWindow method)
SetPopupBitmap() (ToasterBox method)
(ToasterBoxWindow method)
SetPopupMenu() (ScrolledThumbnail method)
SetPopupPauseTime() (ToasterBox method)
(ToasterBoxWindow method)
SetPopupPosition() (ToasterBox method)
(ToasterBoxWindow method)
SetPopupPositionByInt() (ToasterBox method)
(ToasterBoxWindow method)
SetPopupScrollSpeed() (ToasterBox method)
(ToasterBoxWindow method)
SetPopupSize() (ToasterBox method)
(ToasterBoxWindow method)
SetPopupText() (ToasterBox method)
(ToasterBoxWindow method)
SetPopupTextColour() (ToasterBox method)
(ToasterBoxWindow method)
SetPopupTextFont() (ToasterBox method)
(ToasterBoxWindow method)
SetPosition() (FloatSpinEvent method)
(HyperLinkEvent method)
(ImageBar method)
(ImageInfo method)
(PageInfo method)
(RibbonGalleryItem method)
(UltimateListHeaderData method)
(UltimateListItemData method)
(UltimateListLineData method)
SetPressedBottomColour() (GradientButton method)
SetPressedItem() (AuiToolBar method)
SetPressedTopColour() (GradientButton method)
SetProperties() (CubeColourDialog method)
(MultiDirDialog method)
SetProportion() (AuiToolBarItem method)
SetPulseOnFocus() (AquaButton method)
SetPyData() (CustomTreeCtrl method)
(HyperTreeList method)
(UltimateListCtrl method)
(UltimateListItem method)
SetRaiseToolbar() (ArtManager method)
SetRange() (FloatSpin method)
(PyGauge method)
(RulerCtrl method)
SetRangeDontClampValue() (FloatSpin method)
SetRangeValue() (PeakMeterCtrl method)
SetRect() (ButtonInfo method)
(FlatMenuItem method)
(MenuEntryInfo method)
(SwitcherItem method)
SetRegion() (PageInfo method)
SetRenamable() (AuiNotebook method)
SetReportView() (UltimateListLineData method)
(UltimateListMainWindow method)
SetRightClickMenu() (FlatNotebook method)
SetRightIndent() (CaptionBar method)
SetRotatedImage() (Thumb method)
SetRotation() (Thumb method)
SetRotationAngle() (PieCtrl method)
SetRowCount() (SwitcherItems method)
SetRowPos() (SwitcherItem method)
SetRows() (RibbonToolBar method)
SetSashDClickUnsplit() (AuiNotebook method)
SetSashIdx() (FourWaySplitterEvent method)
SetSashPosition() (FourWaySplitterEvent method)
SetScrollPos() (UltimateListCtrl method)
SetSecondColour() (CaptionBarStyle method)
SetSecondGradientColour() (CustomTreeCtrl method)
(HyperTreeList method)
(KnobCtrl method)
(ProgressGauge method)
(PyProgress method)
(SpeedMeter method)
(UltimateListCtrl method)
(UltimateListMainWindow method)
SetSelectedFont() (AuiDefaultTabArt method)
(AuiNotebook method)
(AuiSimpleTabArt method)
(AuiTabContainer method)
SetSelectedImage() (TreeListColumnInfo method)
SetSelectedStateOfChildren() (TreeCtrlHandler method)
SetSelectedStateOfItem() (TreeCtrlHandler method)
SetSelectedTextBitmap() (MenuEntryInfo method)
SetSelection() (AuiNotebook method)
(CommandNotebookEvent method)
(FlatBookBase method)
(FlatMenuItemGroup method)
(FlatNotebook method)
(FlatNotebookCompatible method)
(FlatNotebookEvent method)
(ImageNotebookEvent method)
(PageContainer method)
(RibbonGallery method)
(ScrolledThumbnail method)
(SwitcherItems method)
(ZoomBarEvent method)
SetSelectionByName() (SwitcherItems method)
SetSelectionColour() (ScrolledThumbnail method)
(SwitcherItems method)
SetSelectionOutlineColour() (SwitcherItems method)
SetSelectionState() (TreeCtrlHandler method)
SetSelectionToPage() (AuiNotebook method)
SetSelectionToWindow() (AuiNotebook method)
SetSeparatorColour() (CustomTreeCtrl method)
SetShadowColour() (SpeedMeter method)
SetShape() (AuiDockingHintWindow method)
(AuiSingleDockingGuide method)
SetShortcut() (ShortcutEvent method)
SetShortHelp() (AuiToolBarItem method)
(ButtonInfo method)
(FlatToolbarItem method)
SetShowEdges() (PieCtrl method)
SetShowHideEffects() (InfoBar method)
SetShowLabels() (ZoomBar method)
SetShown() (TreeListColumnInfo method)
(UltimateListItem method)
SetShowReflections() (ZoomBar method)
SetSingleStyle() (UltimateListCtrl method)
SetSize() (FlatMenuButton method)
(ImageBar method)
(ImageInfo method)
(PageInfo method)
(UltimateListItemData method)
(ZoomBarImage method)
SetSizerItem() (AuiToolBarItem method)
SetSizeWithScrollButtonAdjustment() (RibbonPage method)
SetSizingInfo() (AuiDefaultTabArt method)
(AuiSimpleTabArt method)
(ChromeTabArt method)
(VC8TabArt method)
SetSnapLimits() (AuiManager method)
SetSnapToTicks() (FloatSpin method)
SetSpacerPixels() (AuiToolBarItem method)
SetSpacing() (CustomTreeCtrl method)
(FlatMenuBar method)
(HyperTreeList method)
(RulerCtrl method)
SetSpeedBackground() (SpeedMeter method)
SetSpeedValue() (SpeedMeter method)
SetSpinVals() (CubeColourDialog method)
SetSplashShape() (AdvancedSplash method)
SetStartDelay() (BalloonTip method)
(SuperToolTip method)
SetState() (AuiToolBarItem method)
(MenuEntryInfo method)
(UltimateListHeaderData method)
(UltimateListItem method)
SetStateImageList() (CustomTreeCtrl method)
(HyperTreeList method)
SetStateMask() (UltimateListItem method)
SetStatus() (ButtonInfo method)
SetSticky() (AuiToolBarItem method)
SetStringItem() (UltimateListCtrl method)
SetStyle() (ButtonPanel method)
SetSubMenu() (FlatMenuItem method)
SetSubMenuBar() (FlatMenu method)
SetTabAngle() (PageInfo method)
SetTabAreaColour() (FlatNotebook method)
SetTabAreaWidth() (LabelContainer method)
SetTabCtrlHeight() (AuiNotebook method)
(TabFrame method)
SetTabCtrlMargins() (RibbonBar method)
SetTabOffset() (AuiTabContainer method)
SetTabRect() (AuiTabContainer method)
SetTag() (CaptionBarEvent method)
SetTags() (KnobCtrl method)
SetTagsColour() (KnobCtrl method)
SetTarget() (BalloonTip method)
(SuperToolTip method)
SetText() (AdvancedSplash method)
(ButtonInfo method)
(ButtonPanelText method)
(FlatMenuItem method)
(GenericTreeItem method)
(TreeListColumnInfo method)
(TreeListItem method)
(UltimateListHeaderData method)
(UltimateListItem method)
(UltimateListItemData method)
(UltimateListLineData method)
SetTextAlignment() (ButtonInfo method)
SetTextBitmap() (MenuEntryInfo method)
SetTextColor() (SuperToolTip method)
SetTextColour() (AdvancedSplash method)
(FlatMenuItem method)
(SuperToolTip method)
(SwitcherItem method)
(SwitcherItems method)
(TreeItemAttr method)
(UltimateListCtrl method)
(UltimateListItem method)
(UltimateListItemAttr method)
SetTextFont() (AdvancedSplash method)
SetTextOrientation() (AuiDefaultToolBarArt method)
SetTextPosition() (AdvancedSplash method)
SetTextRect() (ImageInfo method)
SetTextX() (TreeListItem method)
SetTheme() (FMRendererMgr method)
SetThumbOutline() (ScrolledThumbnail method)
SetThumbSize() (ScrolledThumbnail method)
SetTickPenColour() (RulerCtrl method)
SetTicks() (SpeedMeter method)
SetTicksColour() (SpeedMeter method)
SetTicksFont() (SpeedMeter method)
SetTimeFormat() (RulerCtrl method)
SetTimeLabel() (PyProgress method)
SetTitle() (SwitcherItem method)
(ToasterBox method)
SetTitleColour() (BalloonTip method)
SetTitleFont() (BalloonTip method)
SetToDefaultValue() (FloatSpin method)
SetToggle() (__SToggleMixin method)
(__ToggleMixin method)
SetToggled() (ButtonInfo method)
SetToolAlignment() (AuiToolBar method)
SetToolbarMargin() (FlatMenuBar method)
SetToolbarSpacing() (FlatMenuBar method)
SetToolBitmap() (AuiToolBar method)
SetToolBitmapSize() (AuiToolBar method)
SetToolBorderPadding() (AuiToolBar method)
SetToolDisabledBitmap() (AuiToolBar method)
SetToolDropDown() (AuiToolBar method)
SetToolId() (CommandToolBarEvent method)
SetToolLabel() (AuiToolBar method)
SetToolLongHelp() (AuiToolBar method)
SetToolNormalBitmap() (AuiToolBar method)
SetToolOrientation() (AuiToolBar method)
SetToolPacking() (AuiToolBar method)
SetToolProportion() (AuiToolBar method)
SetToolSeparation() (AuiToolBar method)
SetToolShortHelp() (AuiToolBar method)
SetToolSticky() (AuiToolBar method)
SetToolTextOrientation() (AuiToolBar method)
SetToolTip() (CommandTreeEvent method)
(UltimateListHeaderData method)
(UltimateListItem method)
(UltimateListItemData method)
(UltimateListLineData method)
SetTopEndColour() (GradientButton method)
SetTopGradientColor() (SuperToolTip method)
SetTopGradientColour() (SuperToolTip method)
SetTopStartColour() (GradientButton method)
SetTrackPosition() (KnobCtrl method)
SetTransparency() (ArtManager method)
(MultiColumnListCtrl method)
SetTransparent() (PieCtrlLegend method)
SetType() (GenericTreeItem method)
SetUnderlines() (HyperLinkCtrl method)
SetUnfilledColour() (ProgressPie method)
SetUniformBitmapSize() (AuiNotebook method)
SetUnits() (RulerCtrl method)
SetupCell() (XLSCell method)
SetUpdateInterval() (FlatMenuBar method)
SetupDirCtrl() (MultiDirDialog method)
SetupHyperlink() (XLSText method)
SetupPositions() (ToasterBoxWindow method)
SetupProps() (ZoomBarImage method)
SetURL() (HyperLinkCtrl method)
SetUseFade() (SuperToolTip method)
SetUseFocus() (ToasterBox method)
(ToasterBoxWindow method)
SetUseFocusIndicator() (SButton method)
SetUseHelp() (ButtonPanel method)
SetUserData() (AuiToolBarItem method)
SetUserLineHeight() (UltimateListCtrl method)
(UltimateListMainWindow method)
SetValid() (AuiDockingGuideWindow method)
(AuiSingleDockingGuide method)
SetValue() (__SToggleMixin method)
(FloatSpin method)
(Indicator method)
(KnobCtrl method)
(KnobCtrlEvent method)
(PiePart method)
(ProgressPie method)
(PyGauge method)
(RulerCtrlEvent method)
(XLSCell method)
(XLSTable method)
(__ToggleMixin method)
SetVerticalBorder() (PieCtrlLegend method)
SetVisited() (GenericTreeItem method)
(HyperLinkCtrl method)
(UltimateListItem method)
(UltimateListItemData method)
SetVSplit() (FourWaySplitter method)
SetWaterMark() (UltimateListCtrl method)
(UltimateListMainWindow method)
SetWidth() (GenericTreeItem method)
(TreeListColumnInfo method)
(UltimateListHeaderData method)
(UltimateListItem method)
(UltimateListLineData method)
SetWindow() (AuiToolBarItem method)
(GenericTreeItem method)
(SwitcherItem method)
(TreeListItem method)
(UltimateListItem method)
(UltimateListItemData method)
SetWindowEnabled() (GenericTreeItem method)
(TreeListItem method)
(UltimateListItem method)
(UltimateListItemData method)
SetWindowStyleFlag() (AuiToolBar method)
SetX() (GenericTreeItem method)
(UltimateListLineData method)
SetXRect() (PageInfo method)
SetY() (GenericTreeItem method)
(UltimateListLineData method)
SetYesNoBitmaps() (GenericMessageDialog method)
SetYesNoCancelBitmaps() (GenericMessageDialog method)
SetYesNoCancelLabels() (GenericMessageDialog method)
SetYesNoLabels() (GenericMessageDialog method)
SetZoomFactor() (ScrolledThumbnail method)
(ZoomBar method)
(ZoomBarImage method)
ShadowBitmap() (AdvancedSplash method)
ShadowPopupWindow (class in flatmenu)
shapedbutton (module)
ShiftHue() (RibbonHSLColour method)
Shortcut (class in shortcuteditor)
ShortcutEditor (class in shortcuteditor)
shortcuteditor (module)
ShortcutEvent (class in shortcuteditor)
ShouldInheritColours() (AquaButton method)
(CustomTreeCtrl method)
(GradientButton method)
(HyperTreeList method)
(SButton method)
ShouldSendEventToDummy() (RibbonPanel method)
Show() (AuiDockingHintWindow method)
(AuiPaneInfo method)
(BoxSizer method)
(Control method)
(FlatMenuItem method)
(RibbonPage method)
(ShortcutEditor method)
(TabFrame method)
ShowComboBox() (ThumbnailCtrl method)
ShowCustomize() (FlatMenuBar method)
ShowCustomPage() (FlatNotebook method)
ShowDescription() (SwitcherDialog method)
ShowDialog() (PyProgress method)
ShowDir() (ScrolledThumbnail method)
ShowDockingGuides() (in module aui.framemanager)
ShowDropDown() (AuiDefaultTabArt method)
(AuiDefaultToolBarArt method)
(AuiSimpleTabArt method)
ShowExpanded() (RibbonPanel method)
ShowFileNames() (ScrolledThumbnail method)
ShowGrid() (PeakMeterCtrl method)
ShowHierarchy() (Shortcut method)
ShowHint() (AuiManager method)
ShowMessage() (InfoBar method)
ShowModal() (CubeColourDialog method)
(GenericMessageDialog method)
(ShortcutEditor method)
ShowPane() (AuiManager method)
ShowPanels() (RibbonBar method)
ShowScrollButtons() (RibbonPage method)
ShowShortcutText() (ListShortcut method)
ShowTabs() (FlatNotebook method)
ShowTabTooltip() (PageContainer method)
ShowThumbs() (ScrolledThumbnail method)
ShowWindowMenu() (AuiNotebook method)
SingleLine() (in module ribbon.art_msw)
SizeLayout() (ButtonPanel method)
Sizer (class in buttonpanel)
SlideIn() (AuiManager method)
SlideOut() (AuiManager method)
SliderHandler (class in persist.persist_handlers)
Slope() (in module cubecolourdialog)
SmartShrink() (AuiManager method)
SmoothDock() (AuiManager method)
Snap() (AuiManager method)
Snappable() (AuiPaneInfo method)
SnapPane() (AuiManager method)
SnapToBottom() (ZoomBar method)
SnapToScreen() (AuiManager method)
SortChildren() (CustomTreeCtrl method)
(HyperTreeList method)
SortFiles() (in module thumbnailctrl)
SortForDisplay() (PyGauge method)
SortItems() (ScrolledThumbnail method)
(UltimateListCtrl method)
(UltimateListMainWindow method)
SpeedMeter (class in speedmeter)
speedmeter (module)
SpinHandler (class in persist.persist_handlers)
Split() (AuiNotebook method)
SplitterHandler (class in persist.persist_handlers)
SplitThousands() (in module xlsgrid)
Start() (PeakMeterCtrl method)
StartAlpha() (ToolTipWindowBase method)
StartPreviewTimer() (AuiManager method)
(AuiToolBar method)
Status (ButtonInfo attribute)
StatusBarTimer (class in buttonpanel)
(class in flatmenu)
StdDialogButtonSizer (class in genericmessagedialog)
StepColour() (in module aui.aui_utilities)
SToggleButton (class in shapedbutton)
Stop() (PeakMeterCtrl method)
StopEditing() (EditCtrl method)
(TabTextCtrl method)
(TreeTextCtrl method)
(UltimateListTextCtrl method)
StopPreviewTimer() (AuiManager method)
(AuiToolBar method)
SuperToolTip (class in supertooltip)
supertooltip (module)
SwitcherDialog (class in aui.aui_switcherdialog)
SwitcherItem (class in aui.aui_switcherdialog)
SwitcherItems (class in aui.aui_switcherdialog)
SwitchFocus() (GenericMessageDialog method)
SwitchToolBarOrientation() (AuiManager method)
SyncSpinToText() (FloatSpin method)

T

TabDragImage (class in aui.aui_utilities)
TabFrame (class in aui.auibook)
TabHasImage() (PageContainer method)
TabHitTest() (AuiTabContainer method)
TabNavigatorProps (class in aui.auibook)
TabNavigatorWindow (class in aui.auibook)
(class in flatnotebook)
TabTextCtrl (class in aui.auibook)
TagAllChildrenUntilLast() (CustomTreeCtrl method)
TagNextChildren() (CustomTreeCtrl method)
TakeScreenShot() (ArtManager method)
(in module aui.aui_utilities)
TaskBarTimer() (BalloonTip method)
TearDown() (ToasterBoxWindow method)
TearUp() (ToasterBoxWindow method)
TestButtonHover() (RibbonGallery method)
TestPositionForHover() (RibbonPanel method)
TextCtrlHandler (class in persist.persist_handlers)
TextEntryHandler (class in persist.persist_handlers)
Thaw() (CustomTreeCtrl method)
ThreadImage() (ScrolledThumbnail method)
Thumb (class in thumbnailctrl)
ThumbnailCtrl (class in thumbnailctrl)
thumbnailctrl (module)
ThumbnailEvent (class in thumbnailctrl)
Tick() (RulerCtrl method)
TickMajor() (RulerCtrl method)
TickMinor() (RulerCtrl method)
Tile() (FlatNotebook method)
TileBackground() (CustomTreeCtrl method)
(UltimateListMainWindow method)
TLWHandler (class in persist.persist_handlers)
to_list() (in module ultimatelistctrl)
ToAcceleratorItem() (Shortcut method)
ToAcceleratorTable() (ShortcutEditor method)
ToasterBox (class in toasterbox)
toasterbox (module)
ToasterBoxWindow (class in toasterbox)
Toggle() (CustomTreeCtrl method)
(FlatToolbarItem method)
(HyperTreeList method)
ToggleButton() (RibbonButtonBar method)
ToggleButtonHandler (class in persist.persist_handlers)
ToggleItemSelection() (CustomTreeCtrl method)
(HyperTreeList method)
ToggleTool() (AuiToolBar method)
ToHSV() (Colour method)
ToMenuBar() (ShortcutEditor method)
ToMenuItem() (Shortcut method)
ToolbarCommandCapture (class in aui.auibar)
ToolBarHandler (class in persist.persist_handlers)
ToolBarItem (class in flatmenu)
ToolbarPane() (AuiPaneInfo method)
ToolTipWindow (class in supertooltip)
ToolTipWindowBase (class in supertooltip)
Top() (AuiDockingGuideInfo method)
(AuiPaneInfo method)
TopDockable() (AuiPaneInfo method)
TopSnappable() (AuiPaneInfo method)
ToRGB() (Colour method)
(RibbonHSLColour method)
toscale() (in module cubecolourdialog)
TrackPoint() (AlphaCtrl method)
(BrightCtrl method)
(HSVWheel method)
TransientPopup (class in xlsgrid)
Transparent() (AuiPaneInfo method)
TreebookHandler (class in persist.persist_handlers)
TreeCtrlHandler (class in persist.persist_handlers)
TreeEditTimer (class in customtreectrl)
TreeEvent (class in customtreectrl)
TreeFindTimer (class in customtreectrl)
TreeItemAttr (class in customtreectrl)
TreeListColumnInfo (class in hypertreelist)
TreeListCtrlHandler (class in persist.persist_handlers)
TreeListHeaderWindow (class in hypertreelist)
TreeListItem (class in hypertreelist)
TreeListMainWindow (class in hypertreelist)
TreeTextCtrl (class in customtreectrl)
TruncateText() (ArtManager method)
TryAfter() (RibbonPanel method)
TryCollapseLayout() (RibbonButtonBar method)
TryOpenSubMenu() (FlatMenu method)
TryScrollButtons() (FlatMenu method)
typeBackground (AuiDockUIPart attribute)
typeCaption (AuiDockUIPart attribute)
typeDock (AuiDockUIPart attribute)
typeDockSizer (AuiDockUIPart attribute)
typeGripper (AuiDockUIPart attribute)
typePane (AuiDockUIPart attribute)
typePaneBorder (AuiDockUIPart attribute)
typePaneButton (AuiDockUIPart attribute)
typePaneSizer (AuiDockUIPart attribute)

U

UltimateListCtrl (class in ultimatelistctrl)
ultimatelistctrl (module)
UltimateListEvent (class in ultimatelistctrl)
UltimateListHeaderData (class in ultimatelistctrl)
UltimateListHeaderWindow (class in ultimatelistctrl)
UltimateListItem (class in ultimatelistctrl)
UltimateListItemAttr (class in ultimatelistctrl)
UltimateListItemData (class in ultimatelistctrl)
UltimateListLineData (class in ultimatelistctrl)
UltimateListMainWindow (class in ultimatelistctrl)
UltimateListRenameTimer (class in ultimatelistctrl)
UltimateListTextCtrl (class in ultimatelistctrl)
UnCheckRadioParent() (CustomTreeCtrl method)
(HyperTreeList method)
UnInit() (AuiManager method)
Unregister() (PersistenceManager method)
Unselect() (CustomTreeCtrl method)
(HyperTreeList method)
UnselectAll() (CustomTreeCtrl method)
(HyperTreeList method)
UnselectAllChildren() (CustomTreeCtrl method)
UNSET_FLAG() (in module ribbon.bar)
UnSplit() (AuiNotebook method)
UnsplitDClick() (AuiNotebook method)
Update() (AuiManager method)
(AuiManager_DCP method)
(ProgressGauge method)
(PyGauge method)
(RulerCtrl method)
(TabFrame method)
(UltimateListCtrl method)
UpdateAcceleratorTable() (FlatMenuBar method)
UpdateButtonOnScreen() (AuiManager method)
UpdateCurrent() (UltimateListMainWindow method)
UpdateDockGuide() (AuiCenterDockingGuide method)
(AuiDockingGuideWindow method)
(AuiSingleDockingGuide method)
UpdateDockingGuides() (AuiManager method)
UpdateDrawing() (BufferedWindow method), [1]
UpdateHintWindowSize() (AuiNotebook method)
UpdateItem() (FlatMenu method)
(FlatMenuBar method)
UpdateItems() (ScrolledThumbnail method)
UpdateLink() (HyperLinkCtrl method)
UpdateNotebook() (AuiManager method)
UpdateParent() (InfoBar method)
UpdateProp() (ScrolledThumbnail method)
UpdatePulse() (PyProgress method)
UpdateRadioGroup() (FlatMenu method)
UpdateShow() (ScrolledThumbnail method)
UpdateTabCtrlHeight() (AuiNotebook method)
UseMenu() (FileHistory method)

V

ValidateNotebookDocking() (AuiCenterDockingGuide method)
(AuiDockingGuide method)
VC71TabArt (class in aui.tabart)
VC8TabArt (class in aui.tabart)
Veto() (AuiManagerEvent method)
(AuiNotebookEvent method)
(AuiToolBarEvent method)
(FlatNotebookEvent method)
(FourWaySplitterEvent method)
(ImageNotebookEvent method)
(RibbonBarEvent method)
(TreeEvent method)
(UltimateListEvent method)

W

wasMaximized (AuiPaneInfo attribute)
Window() (AuiPaneInfo method)
WrapMessage() (GenericMessageDialog method)
wxDate2PyDate() (in module persist.persist_handlers)

X

XLSBackground (class in xlsgrid)
XLSBorder (class in xlsgrid)
XLSBorderFactory (class in xlsgrid)
XLSCell (class in xlsgrid)
XLSComment (class in xlsgrid)
XLSGrid (class in xlsgrid)
xlsgrid (module)
XLSRenderer (class in xlsgrid)
XLSRichText (class in xlsgrid)
XLSTable (class in xlsgrid)
XLSText (class in xlsgrid)
XToCol() (TreeListHeaderWindow method)

Z

ZoomBar (class in zoombar)
zoombar (module)
ZoomBarEvent (class in zoombar)
ZoomBarImage (class in zoombar)
ZoomImage() (ZoomBarImage method)
ZoomIn() (ScrolledThumbnail method)
ZoomOut() (ScrolledThumbnail method)

Navigation

  • index
  • modules |
  • Home |
  • Gallery |
  • Index


Index

  • modules |
  • Home |
  • Gallery |
  • Contents»
  • Index

Index – B

BackgroundColour() (ArtManager method)
BalloonFrame (class in balloontip)
BalloonTip (class in balloontip)
balloontip (module)
BaseLineCtrl (class in cubecolourdialog)
BasePyControl (class in cubecolourdialog)
BestSize() (AuiPaneInfo method)
BestSize1() (AuiPaneInfo method)
BestSize2() (AuiPaneInfo method)
BindEvents() (MultiDirDialog method)
(ShortcutEditor method)
Bitmap (ButtonInfo attribute)
BitmapFromBits() (in module aui.aui_utilities)
BlendColour() (in module aui.aui_utilities)
BookHandler (class in persist.persist_handlers)
Bottom() (AuiDockingGuideInfo method)
(AuiPaneInfo method)
BottomDockable() (AuiPaneInfo method)
BottomSnappable() (AuiPaneInfo method)
BoxSizer (class in buttonpanel)
BPArt (class in buttonpanel)
BreakCaption() (Thumb method)
BreakColumn() (SwitcherItem method)
BrightCtrl (class in cubecolourdialog)
BrightenColour() (in module buttonpanel)
BufferedWindow (class in knobctrl)
(class in speedmeter)
BuildChunks() (XLSRichText method)
BuildImageList() (ListShortcut method)
BuildRect() (BaseLineCtrl method)
BuildToolBar() (HTMLHelpWindow method)
buttonClose (AuiPaneInfo attribute)
buttonCustom1 (AuiPaneInfo attribute)
buttonCustom2 (AuiPaneInfo attribute)
buttonCustom3 (AuiPaneInfo attribute)
ButtonHitTest() (AuiTabContainer method)
ButtonInfo (class in buttonpanel)
buttonMaximize (AuiPaneInfo attribute)
buttonMinimize (AuiPaneInfo attribute)
ButtonPanel (class in buttonpanel)
buttonpanel (module)
ButtonPanelText (class in buttonpanel)
buttonPin (AuiPaneInfo attribute)

Navigation

  • index
  • modules |
  • Home |
  • Gallery |
  • Index


Index

  • modules |
  • Home |
  • Gallery |
  • Contents»
  • Index

Index – C

CacheLineData() (UltimateListMainWindow method)
CalcButtonBestSize() (ArtManager method)
CalcCuboid() (CubeColourDialog method)
CalcRects() (CubeColourDialog method)
CalcSlopes() (CubeColourDialog method)
CalcTabHeight() (FNBRenderer method)
CalcTabWidth() (FNBRenderer method)
(FNBRendererRibbonTabs method)
CalculateAndSetHeaderHeight() (HyperTreeList method)
CalculateBestCaption() (ScrolledThumbnail method)
CalculateBestPosition() (ToolTipWindowBase method)
CalculateBestSize() (ToolTipWindowBase method)
CalculateDockSizerLimits() (AuiManager method)
CalculateHintRect() (AuiManager method)
CalculateItemSize() (SwitcherItems method)
CalculateLayout() (MultiColumnListCtrl method)
CalculateLevel() (CustomTreeCtrl method)
(TreeListMainWindow method)
CalculateLineHeight() (CustomTreeCtrl method)
CalculateMinSize() (RibbonGallery method)
CalculateNewSplitSize() (AuiNotebook method)
CalculateOffset() (ListShortcut method)
CalculateOverallSize() (RibbonButtonBarLayout method)
CalculatePaneSizerLimits() (AuiManager method)
CalculatePositions() (CustomTreeCtrl method)
(TreeListMainWindow method)
CalculateSize() (CustomTreeCtrl method)
(TreeListMainWindow method)
(UltimateListLineData method)
CalculateTabCtrlHeight() (AuiNotebook method)
CalendarCtrlHandler (class in persist.persist_handlers)
CanAutoMinimise() (RibbonPanel method)
CanDoBottomStyle() (ImageContainer method)
(ImageContainerBase method)
(LabelContainer method)
CanDockPanel() (AuiManager method)
CanFitToScreen() (PageContainer method)
CanMakeWindowsTransparent() (ArtManager method)
CanUseModernDockArt() (AuiManager method)
CanVeto() (AuiManagerEvent method)
Caption() (AuiPaneInfo method)
CaptionBar (class in foldpanelbar)
CaptionBarEvent (class in foldpanelbar)
CaptionBarStyle (class in foldpanelbar)
CaptionColourUsed() (CaptionBarStyle method)
CaptionFontUsed() (CaptionBarStyle method)
CaptionStyleUsed() (CaptionBarStyle method)
CaptionVisible() (AuiPaneInfo method)
Center() (AuiDockingGuideInfo method)
(AuiPaneInfo method)
CenterOnParent() (ToasterBox method)
CenterOnScreen() (ToasterBox method)
CenterPane() (AuiPaneInfo method)
Centre() (AuiDockingGuideInfo method)
(AuiPaneInfo method)
CentreOnParent() (ToasterBox method)
CentreOnScreen() (ToasterBox method)
CentrePane() (AuiPaneInfo method)
ChangeCurrent() (UltimateListMainWindow method)
ChangeSelection() (FlatBookBase method)
(FlatNotebookCompatible method)
Check() (FlatMenuItem method)
(GenericTreeItem method)
(UltimateListHeaderData method)
(UltimateListItem method)
(UltimateListItemData method)
(UltimateListLineData method)
CheckAccelerator() (Shortcut method)
CheckBoxHandler (class in persist.persist_handlers)
CheckChilds() (CustomTreeCtrl method)
(HyperTreeList method)
CheckEdgeDrop() (in module aui.framemanager)
CheckFooter() (UltimateListHeaderData method)
(UltimateListItem method)
CheckItem() (CustomTreeCtrl method)
(HyperTreeList method)
(UltimateListMainWindow method)
CheckItem2() (CustomTreeCtrl method)
(HyperTreeList method)
CheckListBoxHandler (class in persist.persist_handlers)
CheckMovableSizer() (AuiManager method)
CheckOutOfWindow() (in module aui.framemanager)
CheckPaneMove() (AuiManager method)
CheckRefresh() (ButtonInfo method)
CheckSameLevel() (CustomTreeCtrl method)
(HyperTreeList method)
CheckStyle() (RulerCtrl method)
CheckVariableRowHeight() (in module ultimatelistctrl)
ChildrenClosing() (CustomTreeCtrl method)
(TreeListMainWindow method)
ChoiceComboHandler (class in persist.persist_handlers)
ChoiceDialogHandler (class in persist.persist_handlers)
ChopText() (in module aui.aui_utilities)
(in module customtreectrl)
ChromeTabArt (class in aui.tabart)
CircleCoords() (KnobCtrl method)
(SpeedMeter method)
ClampValue() (FloatSpin method)
CleanList() (ToasterBox method)
Clear() (AuiToolBar method)
(ButtonPanel method)
(FlatMenu method)
(RibbonGallery method)
(ScrolledThumbnail method)
(SelectionStore method)
(SwitcherItems method)
(UltimateListItem method)
ClearAGWFlag() (PageContainer method)
ClearAll() (ImageContainerBase method)
(UltimateListCtrl method)
ClearAttributes() (UltimateListItem method)
ClearBitmaps() (FlatMenuBar method)
ClearButtons() (RibbonButtonBar method)
ClearColumnImage() (UltimateListCtrl method)
ClearFlag() (ImageContainerBase method)
ClearTools() (AuiToolBar method)
ClientToScreen() (UltimateListCtrl method)
ClientToScreenXY() (UltimateListCtrl method)
Clip() (in module aui.aui_utilities)
Clone() (AuiDefaultTabArt method)
(AuiDefaultToolBarArt method)
(AuiSimpleTabArt method)
(ChromeTabArt method)
(FF2TabArt method)
(RibbonAUIArtProvider method)
(RibbonMSWArtProvider method)
(VC71TabArt method)
(VC8TabArt method)
CloneButtons() (AuiTabContainer method)
CloneTabAreaButtons() (AuiNotebook method)
CloneTo() (RibbonMSWArtProvider method)
Close() (Excel method)
CloseButton() (AuiPaneInfo method)
CloseDialog() (FMCustomizeDlg method)
(TabNavigatorWindow method), [1]
ClosePane() (AuiManager method)
CloseSubMenu() (FlatMenu method)
CmpThumb() (in module thumbnailctrl)
Collapse() (CaptionBar method)
(CustomTreeCtrl method)
(FoldPanelBar method)
(FoldPanelItem method)
(GenericTreeItem method)
(HyperTreeList method)
(PyCollapsiblePane method)
CollapseAndReset() (CustomTreeCtrl method)
(HyperTreeList method)
CollapsePanels() (RibbonPage method)
CollapsiblePaneHandler (class in persist.persist_handlers)
Colour (class in cubecolourdialog)
ColourDialogHandler (class in persist.persist_handlers)
ColourPanel (class in cubecolourdialog)
ColourPickerHandler (class in persist.persist_handlers)
ColourToHexString() (SwitcherDialog method)
column() (EditCtrl method)
ColWidthInfo (class in ultimatelistctrl)
CombineAttr() (XLSBackground method)
(XLSText method)
CommandListEvent (class in ultimatelistctrl)
CommandNotebookEvent (class in aui.auibook)
CommandToolBarEvent (class in aui.auibar)
CommandTreeEvent (class in customtreectrl)
CommonInit() (RibbonBar method)
(RibbonButtonBar method)
(RibbonGallery method)
(RibbonPage method)
(RibbonPanel method)
(RibbonToolBar method)
ConflictDialog (class in shortcuteditor)
ConnectEvents() (FMCustomizeDlg method)
Contains() (FlatMenuButton method)
Control (class in buttonpanel)
ConvertPILToWX() (in module rulerctrl)
(SButton method)
ConvertToBitmap() (ArtManager method)
(FMRenderer method)
ConvertToMonochrome() (in module flatmenu)
ConvertWXToPIL() (in module rulerctrl)
(SButton method)
copy() (FixedPoint method)
Copy() (SwitcherItem method)
(SwitcherItems method)
CopyAttributes() (AuiFloatingFrame method)
(in module aui.aui_utilities)
CopyDocksAndPanes() (in module aui.framemanager)
CopyDocksAndPanes2() (in module aui.framemanager)
CopyTarget() (AuiManager method)
CountButtons() (AuiPaneInfo method)
create_delegator_for() (in module hypertreelist)
CreateAlignment() (XLSText method)
CreateBackgroundColour() (XLSBackground method)
CreateBitmap() (DragImage method)
(TabDragImage method)
CreateButtons() (MultiDirDialog method)
CreateButtonSizer() (GenericMessageDialog method)
CreateDC() (ButtonPanelText method)
CreateDialog() (FMCustomizeDlg method)
CreateEditCtrl() (HyperTreeList method)
CreateFloatingFrame() (AuiManager method)
CreateFont() (in module persist.persist_handlers)
(XLSText method)
CreateFormat() (XLSText method)
CreateGreyBitmap() (ArtManager method)
CreateGuideWindows() (AuiManager method)
CreateHintWindow() (AuiManager method)
CreateImageContainer() (FlatImageBook method)
(LabelBook method)
CreateLabel() (PyProgress method)
CreateListItem() (in module ultimatelistctrl)
CreateMenusPage() (FMCustomizeDlg method)
CreateMessageDialog() (GenericMessageDialog method)
CreateMoreMenu() (FlatMenuBar method)
CreateNotebook() (AuiManager method)
CreateNotebookBase() (AuiManager method)
CreateOptionsPage() (FMCustomizeDlg method)
CreateOrDestroyFooterWindowAsNeeded() (UltimateListCtrl method)
CreateOrDestroyHeaderWindowAsNeeded() (UltimateListCtrl method)
CreateSeparatedButtonSizer() (GenericMessageDialog method)
CreateShapesWithStyle() (AuiCenterDockingGuide method)
(AuiSingleDockingGuide method)
CreateShortcutsPage() (FMCustomizeDlg method)
CreateStdDialogButtonSizer() (GenericMessageDialog method)
CreateTextColour() (XLSText method)
CreateWidgets() (ShortcutEditor method)
CubeColourDialog (class in cubecolourdialog)
cubecolourdialog (module)
CurrentPage (FlatBookBase attribute)
CustomPanel (class in cubecolourdialog)
CustomTreeCtrl (class in customtreectrl)
customtreectrl (module)

Navigation

  • index
  • modules |
  • Home |
  • Gallery |
  • Index


Index

  • modules |
  • Home |
  • Gallery |
  • Contents»
  • Index

Index – D

DarkColour() (ArtManager method)
DarkenBitmap() (in module aui.aui_utilities)
DarkenColour() (in module peakmeter)
Darker() (RibbonHSLColour method)
DatePickerHandler (class in persist.persist_handlers)
DCSaver (class in artmanager)
DefaultPane() (AuiPaneInfo method)
deg2rad() (in module cubecolourdialog)
Delete() (CustomTreeCtrl method)
(FlatMenu method)
(HyperTreeList method)
(TreeListMainWindow method)
DeleteAllColumns() (UltimateListCtrl method)
DeleteAllItems() (CustomTreeCtrl method)
(HyperTreeList method)
(TreeListMainWindow method)
(UltimateListCtrl method)
(UltimateListMainWindow method)
DeleteAllPages() (FlatBookBase method)
(FlatNotebook method)
(PageContainer method)
DeleteButton() (RibbonButtonBar method)
DeleteChildren() (CustomTreeCtrl method)
(GenericTreeItem method)
(HyperTreeList method)
(TreeListItem method)
DeleteColumn() (UltimateListCtrl method)
(UltimateListMainWindow method)
DeleteEverything() (UltimateListMainWindow method)
DeleteFiles() (ScrolledThumbnail method)
DeleteItem() (UltimateListCtrl method)
(UltimateListMainWindow method)
DeleteItemWindow() (CustomTreeCtrl method)
(UltimateListCtrl method)
(UltimateListMainWindow method)
DeletePage() (AuiNotebook method)
(FlatBookBase method)
(FlatNotebook method)
(PageContainer method)
DeleteRoot() (HyperTreeList method)
(TreeListMainWindow method)
DeleteTool() (AuiToolBar method)
DeleteToolByPos() (AuiToolBar method)
DeleteWindow() (GenericTreeItem method)
(TreeListItem method)
(UltimateListItem method)
(UltimateListItemData method)
Desaturated() (RibbonHSLColour method)
Destroy() (AuiNotebook method)
(FlatMenu method)
DestroyGuideWindows() (AuiManager method)
DestroyHintWindow() (AuiManager method)
DestroyOnClose() (AuiPaneInfo method)
DestroyTimer() (BalloonTip method)
DestroyTip() (XLSGrid method)
DetachPane() (AuiManager method)
DetachWindow() (FourWaySplitter method)
Direction() (AuiPaneInfo method)
Disable() (Control method)
DisableAbort() (PyProgress method)
DisableRestoring() (PersistenceManager method)
DisableSaving() (PersistenceManager method)
DisableShortcut() (ListShortcut method)
Dismiss() (FlatMenu method)
(FlatMenuBase method)
(InfoBar method)
DismissExpandedPanel() (RibbonBar method)
(RibbonPage method)
DisplayError() (HyperLinkCtrl method)
Distance() (in module cubecolourdialog)
DoAction() (FlatMenu method)
Dock() (AuiPaneInfo method)
dock_direction (AuiPaneInfo attribute)
dock_direction_get() (AuiPaneInfo method)
dock_direction_set() (AuiPaneInfo method)
Dockable() (AuiPaneInfo method)
DockFixed() (AuiPaneInfo method)
DoDeleteAllItems() (UltimateListMainWindow method)
DoDeletePage() (ImageContainerBase method)
(PageContainer method)
DoDrop() (AuiManager method)
DoDropFloatingPane() (AuiManager method)
DoDropLayer() (AuiManager method)
DoDropNonFloatingPane() (AuiManager method)
DoDropPane() (AuiManager method)
DoDropRow() (AuiManager method)
DoDropToolbar() (AuiManager method)
DoEndResizeAction() (AuiManager method)
DoEraseBackground() (RibbonBar method)
DoFrameLayout() (AuiManager method)
DoGetBestSize() (AquaButton method)
(AuiTabCtrl method)
(AuiToolBar method)
(BaseLineCtrl method)
(BasePyControl method)
(ButtonPanel method)
(CaptionBar method)
(CustomPanel method)
(CustomTreeCtrl method)
(FlatNotebook method)
(FloatSpin method)
(FourWaySplitter method)
(GTKExpander method)
(GradientButton method)
(HyperTreeList method)
(MultiColumnListCtrl method)
(PeakMeterCtrl method)
(PyCollapsiblePane method)
(PyGauge method)
(RibbonBar method)
(RibbonButtonBar method)
(RibbonGallery method)
(RibbonPage method)
(RibbonPanel method)
(RibbonToolBar method)
(SButton method)
(UltimateListCtrl method)
(UltimateListHeaderWindow method)
(UltimateListMainWindow method)
(ZoomBar method)
DoGetClientSize() (TabFrame method)
DoGetNextLargerSize() (RibbonButtonBar method)
(RibbonControl method)
(RibbonGallery method)
(RibbonPanel method)
(RibbonToolBar method)
DoGetNextSmallerSize() (RibbonButtonBar method)
(RibbonControl method)
(RibbonGallery method)
(RibbonPanel method)
(RibbonToolBar method)
DoGetSize() (TabFrame method)
DoGiveHelp() (ButtonPanel method)
(FlatMenuBar method)
DoHeaderLayout() (HyperTreeList method)
DoHide() (InfoBar method)
DoIdleUpdate() (AuiToolBar method)
DoInsertDockLayer() (in module aui.framemanager)
DoInsertDockRow() (in module aui.framemanager)
DoInsertItem() (CustomTreeCtrl method)
(TreeListMainWindow method)
DoInsertPane() (in module aui.framemanager)
DoLayout() (ButtonPanel method)
(CubeColourDialog method)
(ShortcutEditor method)
(UltimateListCtrl method)
(ZoomBar method)
DoMouseButtonCommon() (RibbonBar method)
DoMouseMove() (FlatMenuBar method)
DoPopup() (HyperLinkCtrl method)
DoRestoreValue() (PersistenceManager method)
DoSaveValue() (PersistenceManager method)
DoSelectItem() (CustomTreeCtrl method)
DoSendChangingEvent() (FourWaySplitter method)
DoSendEvent() (FloatSpin method)
DoSetSelection() (FlatBookBase method)
(PageContainer method)
DoSetSize() (AuiToolBar method)
(RibbonPage method)
(RibbonPanel method)
(TabFrame method)
DoShow() (InfoBar method)
DoShowHide() (AuiTabContainer method)
DoShowNow() (SuperToolTip method)
DoSizing() (AuiNotebook method)
(TabFrame method)
DoTimerProcessing() (PeakMeterCtrl method)
DoToolbarAction() (FlatMenuBar method)
DragFinish() (UltimateListMainWindow method)
DragImage (class in customtreectrl)
Draw() (AuiDockingGuideWindow method)
(BufferedWindow method), [1]
(ButtonInfo method)
(ButtonPanelText method)
(Control method)
(FlatMenuButton method)
(Indicator method)
(KnobCtrl method)
(PieCtrl method)
(PyImageList method)
(RulerCtrl method)
(Separator method)
(Sizer method)
(SpeedMeter method)
(UltimateListLineData method)
(XLSBackground method)
(XLSBorder method)
(XLSBorderFactory method)
(XLSComment method)
(XLSRenderer method)
(XLSRichText method)
(XLSText method)
DrawAll() (CubeColourDialog method)
DrawAlpha() (CubeColourDialog method)
DrawAlphaShading() (AlphaCtrl method)
DrawArrow() (AuiDockingGuideWindow method)
DrawArrowAccordingToState() (FNBRenderer method)
DrawBackground() (AuiDefaultDockArt method)
(AuiDefaultTabArt method)
(AuiDefaultToolBarArt method)
(AuiDockingGuideWindow method)
(AuiSimpleTabArt method)
DrawBackgroundBitmap() (LabelContainer method)
DrawBitmapArea() (RendererBase method)
DrawBitmapBorders() (RendererBase method)
DrawBitmapShadow() (ArtManager method)
(FMRenderer method)
DrawBorder() (AuiDefaultDockArt method)
(XLSBorder method)
DrawBoundingCircle() (KnobCtrl method)
DrawBright() (CubeColourDialog method)
DrawButton() (ArtManager method)
(AuiDefaultTabArt method)
(AuiDefaultToolBarArt method)
(AuiSimpleTabArt method)
(BPArt method)
(FMRenderer method)
(FMRendererMSOffice2007 method)
(RendererMSOffice2007 method)
(RendererXP method)
(in module flatnotebook)
DrawButtonBarBackground() (RibbonAUIArtProvider method)
(RibbonMSWArtProvider method)
DrawButtonBarButton() (RibbonAUIArtProvider method)
(RibbonMSWArtProvider method)
DrawButtonBarButtonForeground() (RibbonMSWArtProvider method)
DrawButtonBorders() (RendererBase method)
DrawButtonColour() (ArtManager method)
(FMRendererMSOffice2007 method)
(FMRendererVista method)
(RendererMSOffice2007 method)
(RendererXP method)
DrawButtonPanel() (BPArt method)
DrawButtons() (AuiSimpleTabArt method)
(ZoomBar method)
DrawButtonTheme() (ArtManager method)
(RendererXP method)
DrawCaption() (AuiDefaultDockArt method)
(BPArt method)
(ModernDockArt method)
DrawCaptionBackground() (AuiDefaultDockArt method)
(ModernDockArt method)
DrawCheckbox() (UltimateListMainWindow method)
DrawCheckerBoard() (in module cubecolourdialog)
DrawControlLabel() (AuiDefaultToolBarArt method)
DrawCurrent() (TreeListHeaderWindow method)
(UltimateListHeaderWindow method)
DrawDiagonalGradient() (KnobCtrl method)
DrawDiagonals() (XLSBorder method)
DrawDnDArrow() (UltimateListMainWindow method)
DrawDottedLine() (AuiDockingGuideWindow method)
DrawDragHint() (FNBRenderer method)
(PageContainer method)
DrawDragSash() (ArtManager method)
DrawDropDownArrow() (FNBRenderer method)
DrawDropdownArrow() (RibbonMSWArtProvider method)
DrawDropDownButton() (AuiDefaultToolBarArt method)
DrawExternalArc() (SpeedMeter method)
DrawFocusIndicator() (SButton method)
DrawFocusRectangle() (AuiDefaultTabArt method)
(FNBRenderer method)
DrawGalleryBackground() (RibbonAUIArtProvider method)
(RibbonMSWArtProvider method)
DrawGalleryBackgroundCommon() (RibbonMSWArtProvider method)
DrawGalleryButton() (RibbonAUIArtProvider method)
(RibbonMSWArtProvider method)
DrawGalleryItemBackground() (RibbonAUIArtProvider method)
(RibbonMSWArtProvider method)
DrawGradientRectangle() (in module aui.aui_utilities)
DrawGripper() (AuiDefaultDockArt method)
(AuiDefaultToolBarArt method)
DrawHintRect() (AuiManager method)
DrawHorizontalGradient() (CaptionBar method)
(CustomTreeCtrl method)
(UltimateListLineData method)
DrawHorzBand() (PeakMeterCtrl method)
DrawHSB() (CubeColourDialog method)
DrawIcon() (AuiDefaultDockArt method)
(AuiDockingGuideWindow method)
DrawImage() (UltimateListMainWindow method)
DrawInReportMode() (UltimateListLineData method)
DrawInsetCircle() (KnobCtrl method)
DrawLabel() (AuiDefaultToolBarArt method)
(BPArt method)
(LabelContainer method)
(SBitmapButton method)
(SBitmapTextButton method)
(SButton method)
DrawLabels() (ZoomBar method)
DrawLeftArrow() (FNBRenderer method)
DrawLeftMargin() (FMRenderer method)
(FMRendererMSOffice2007 method)
(FMRendererXP method)
DrawLines() (BasePyControl method)
(RGBCube method)
DrawMACCloseButton() (in module aui.aui_utilities)
DrawMainButton() (SButton method)
DrawMarkers() (AlphaCtrl method)
(BasePyControl method)
(BrightCtrl method)
(CubeColourDialog method)
(HSVWheel method)
(RGBCube method)
DrawMenu() (FMRenderer method)
DrawMenuBar() (FMRenderer method)
DrawMenuBarBackground() (FMRenderer method)
(FMRendererMSOffice2007 method)
(FMRendererXP method)
DrawMenuBarBg() (ArtManager method)
(RendererMSOffice2007 method)
(RendererXP method)
DrawMenuBarBorder() (ArtManager method)
DrawMenuBarButton() (FMRenderer method)
(FMRendererMSOffice2007 method)
DrawMenuButton() (FMRenderer method)
(FMRendererMSOffice2007 method)
DrawMenuItem() (FMRenderer method)
DrawMinimisedPanel() (RibbonAUIArtProvider method)
(RibbonMSWArtProvider method)
DrawMinimisedPanelCommon() (RibbonMSWArtProvider method)
DrawMoreButton() (FlatMenuBar method)
DrawOnParent() (RulerCtrl method)
DrawOverflowButton() (AuiDefaultToolBarArt method)
DrawPageBackground() (RibbonAUIArtProvider method)
(RibbonMSWArtProvider method)
DrawPaneButton() (AuiDefaultDockArt method)
(AuiManager method)
(ModernDockArt method)
DrawPanelBackground() (RibbonAUIArtProvider method)
(RibbonMSWArtProvider method)
DrawPanelBorder() (RibbonMSWArtProvider method)
DrawPartialPageBackground() (RibbonMSWArtProvider method)
DrawPartialPageBackground1() (RibbonMSWArtProvider method)
DrawPartialPageBackground2() (RibbonMSWArtProvider method)
DrawPartialPanelBackground() (RibbonAUIArtProvider method)
DrawParts() (PieCtrl method)
DrawPin() (ImageContainerBase method)
DrawPlainBackground() (AuiDefaultToolBarArt method)
DrawProgress() (ProgressGauge method)
DrawReflections() (ZoomBar method)
DrawRegularHover() (LabelContainer method)
DrawResizeHint() (in module aui.framemanager)
DrawRGB() (CubeColourDialog method)
DrawRightArrow() (FNBRenderer method)
DrawSash() (AuiDefaultDockArt method)
DrawSashGripper() (AuiDefaultDockArt method)
DrawScrollButton() (FMRenderer method)
(RibbonAUIArtProvider method)
(RibbonMSWArtProvider method)
DrawSelection() (FlatMenu method)
DrawSeparator() (AuiDefaultToolBarArt method)
(BPArt method)
(FMRenderer method)
DrawSingleColour() (CaptionBar method)
DrawSingleRectangle() (CaptionBar method)
DrawSplitter() (FourWaySplitter method)
DrawTab() (AuiDefaultTabArt method)
(AuiSimpleTabArt method)
(ChromeTabArt method)
(FF2TabArt method)
(FNBRendererDefault method)
(FNBRendererFancy method)
(FNBRendererFirefox2 method)
(FNBRendererRibbonTabs method)
(FNBRendererVC71 method)
(FNBRendererVC8 method)
(RibbonAUIArtProvider method)
(RibbonMSWArtProvider method)
(VC71TabArt method)
(VC8TabArt method)
DrawTabBackground() (FF2TabArt method)
DrawTabCtrlBackground() (RibbonAUIArtProvider method)
(RibbonMSWArtProvider method)
DrawTabs() (FNBRenderer method)
(FNBRendererRibbonTabs method)
(FNBRendererVC8 method)
DrawTabSeparator() (RibbonAUIArtProvider method)
(RibbonMSWArtProvider method)
DrawTabsLine() (FNBRenderer method)
DrawTabX() (FNBRenderer method)
DrawTags() (KnobCtrl method)
DrawText() (ToasterBoxWindow method)
DrawTextAndBitmap() (ArtManager method)
DrawTextFormatted() (UltimateListHeaderWindow method)
(UltimateListLineData method)
DrawThumbnail() (ScrolledThumbnail method)
DrawTool() (RibbonAUIArtProvider method)
(RibbonMSWArtProvider method)
DrawToolbar() (FlatMenuBar method)
DrawToolBarBackground() (RibbonAUIArtProvider method)
(RibbonMSWArtProvider method)
DrawToolBarBg() (ArtManager method)
(FMRenderer method)
(FMRendererMSOffice2007 method)
(FMRendererXP method)
(RendererMSOffice2007 method)
(RendererXP method)
DrawToolbarItem() (FlatMenuBar method)
DrawToolbarSeparator() (FMRenderer method)
DrawToolGroupBackground() (RibbonAUIArtProvider method)
(RibbonMSWArtProvider method)
DrawTrackSplitter() (FourWaySplitter method)
DrawTreeItemButton() (in module customtreectrl)
DrawVertBand() (PeakMeterCtrl method)
DrawVerticalGradient() (CaptionBar method)
(CustomTreeCtrl method)
(UltimateListLineData method)
DrawVistaRectangle() (CustomTreeCtrl method)
(UltimateListLineData method)
DrawWebHover() (LabelContainer method)
DrawX() (FNBRenderer method)
DropShadow() (ArtManager method)
(ToolTipWindowBase method)

Navigation

  • index
  • modules |
  • Home |
  • Gallery |
  • Index


Index

  • modules |
  • Home |
  • Gallery |
  • Contents»
  • Index

Index – E

Edit() (CustomTreeCtrl method)
EditCtrl (class in hypertreelist)
EditLabel() (CustomTreeCtrl method)
(HyperTreeList method)
(TreeListMainWindow method)
(UltimateListCtrl method)
(UltimateListMainWindow method)
EditTab() (AuiNotebook method)
EditTextCtrl (class in hypertreelist)
Enable() (AquaButton method)
(ButtonInfo method)
(Control method)
(FlatMenuItem method)
(FlatToolbarItem method)
(GenericTreeItem method)
(GradientButton method)
(SButton method)
(UltimateListItem method)
(UltimateListItemAttr method)
(UltimateListItemData method)
(ZoomBarImage method)
EnableAbort() (PyProgress method)
EnableButton() (RibbonButtonBar method)
(ZoomBar method)
EnableChildren() (CustomTreeCtrl method)
(HyperTreeList method)
EnableClose() (PyProgress method)
EnableDragging() (ScrolledThumbnail method)
EnableItem() (CustomTreeCtrl method)
(HyperTreeList method)
(TreeListMainWindow method)
(UltimateListCtrl method)
(UltimateListMainWindow method)
EnableRestoring() (PersistenceManager method)
EnableRollover() (HyperLinkCtrl method)
EnableSaving() (PersistenceManager method)
EnableSelectionGradient() (CustomTreeCtrl method)
(HyperTreeList method)
(UltimateListCtrl method)
(UltimateListMainWindow method)
EnableSelectionVista() (CustomTreeCtrl method)
(HyperTreeList method)
(UltimateListCtrl method)
(UltimateListMainWindow method)
EnableTab() (AuiNotebook method)
(AuiTabContainer method)
(FlatBookBase method)
(FlatNotebook method)
(ImageContainerBase method)
(ImageInfo method)
(PageContainer method)
(PageInfo method)
EnableTip() (BalloonTip method)
(SuperToolTip method)
EnableTool() (AuiToolBar method)
EnableToolTips() (ScrolledThumbnail method)
EndDialog() (GenericMessageDialog method)
EnsureVisible() (AuiNotebook method)
(CustomTreeCtrl method)
(FlatNotebook method)
(HyperTreeList method)
(RibbonGallery method)
(UltimateListCtrl method)
(UltimateListMainWindow method)
EscapeDelimiters() (in module aui.framemanager)
EventFlagsToSelType() (in module customtreectrl)
Excel (class in xlsgrid)
ExchangeWindows() (FourWaySplitter method)
Exist() (FlatMenuItemGroup method)
Expand() (CaptionBar method)
(CustomTreeCtrl method)
(FoldPanelBar method)
(FoldPanelItem method)
(GenericTreeItem method)
(HyperTreeList method)
(PyCollapsiblePane method)
ExpandAll() (CustomTreeCtrl method)
(HyperTreeList method)
ExpandAllChildren() (CustomTreeCtrl method)
(HyperTreeList method)
ExpandPanels() (RibbonPage method)
ExtendWidth() (GeometryInfo method)
ExtractLink() (in module supertooltip)

Navigation

  • index
  • modules |
  • Home |
  • Gallery |
  • Index


Index

  • modules |
  • Home |
  • Gallery |
  • Contents»
  • Index

Index – F

FadeOut() (AuiFloatingFrame method)
FetchButtonSizeInfo() (RibbonButtonBar method)
FF2TabArt (class in aui.tabart)
FileDirDialogHandler (class in persist.persist_handlers)
FileDirPickerHandler (class in persist.persist_handlers)
FileHistory (class in flatmenu)
FileHistoryHandler (class in persist.persist_handlers)
FillArray() (CustomTreeCtrl method)
FillCaptionBackground() (CaptionBar method)
FillGradientColour() (BPArt method)
FillStockBitmaps() (ArtManager method)
FillVC8GradientColour() (FNBRendererVC8 method)
(VC8TabArt method)
Find() (PersistenceManager method)
FindC() (in module cubecolourdialog)
FindControl() (AuiToolBar method)
FindDocks() (in module aui.framemanager)
FindFocusDescendant() (in module aui.aui_utilities)
FindHandler() (in module persist.persist_handlers)
FindItem() (CustomTreeCtrl method)
(FlatMenu method)
(HyperTreeList method)
(UltimateListCtrl method)
(UltimateListMainWindow method)
FindItemAtPos() (UltimateListCtrl method)
(UltimateListMainWindow method)
FindItemById() (SwitcherItems method)
FindItemByName() (SwitcherItems method)
FindItemData() (UltimateListCtrl method)
(UltimateListMainWindow method)
FindLinearTickSizes() (RulerCtrl method)
FindMenu() (FlatMenuBar method)
FindMenuItem() (FlatMenuBar method)
FindMenuItemPos() (FlatMenu method)
FindMenuItemPosSimple() (FlatMenu method)
FindNextActiveTab() (AuiNotebook method)
FindOppositeDocks() (in module aui.framemanager)
FindPaneInDock() (in module aui.framemanager)
FindReplaceHandler (class in persist.persist_handlers)
FindSimilarInstance() (RibbonButtonBarLayout method)
FindTab() (AuiNotebook method)
FindTool() (AuiToolBar method)
FindToolByIndex() (AuiToolBar method)
FindToolByLabel() (AuiToolBar method)
FindToolForPosition() (AuiToolBar method)
FindToolForPositionWithPacking() (AuiToolBar method)
Finish() (EditCtrl method)
(TabTextCtrl method)
(TreeTextCtrl method)
(UltimateListTextCtrl method)
FireEvent() (AuiManager method)
(PageContainer method)
FireShortcutChanged() (ListShortcut method)
FireShortcutChanging() (ListShortcut method)
FirstColourUsed() (CaptionBarStyle method)
Fixed() (AuiPaneInfo method)
FixedPoint (class in floatspin)
FixTextSize() (ImageContainerBase method)
FlatBookBase (class in labelbook)
FlatImageBook (class in labelbook)
FlatMenu (class in flatmenu)
flatmenu (module)
FlatMenuBar (class in flatmenu)
FlatMenuBase (class in flatmenu)
FlatMenuButton (class in flatmenu)
FlatMenuEvent (class in flatmenu)
FlatMenuItem (class in flatmenu)
FlatMenuItemGroup (class in flatmenu)
FlatNotebook (class in flatnotebook)
flatnotebook (module)
FlatNotebookCompatible (class in flatnotebook)
FlatNotebookDragEvent (class in flatnotebook)
FlatNotebookEvent (class in flatnotebook)
FlatToolbarItem (class in flatmenu)
FlexibleLayout() (ButtonPanel method)
Float() (AuiPaneInfo method)
Floatable() (AuiPaneInfo method)
FloatingPosition() (AuiPaneInfo method)
FloatingSize() (AuiPaneInfo method)
FloatPage() (AuiNotebook method)
FloatSpin (class in floatspin)
floatspin (module)
FloatSpinEvent (class in floatspin)
FloatTextCtrl (class in floatspin)
FlyOut() (AuiFloatingFrame method)
(AuiPaneInfo method)
FMCustomizeDlg (class in fmcustomizedlg)
fmcustomizedlg (module)
FMRenderer (class in flatmenu)
FMRendererMgr (class in flatmenu)
FMRendererMSOffice2007 (class in flatmenu)
FMRendererVista (class in flatmenu)
FMRendererXP (class in flatmenu)
FMTitlePanel (class in fmcustomizedlg)
FNBDragInfo (class in flatnotebook)
FNBDropSource (class in flatnotebook)
FNBDropTarget (class in flatnotebook)
FNBRenderer (class in flatnotebook)
FNBRendererDefault (class in flatnotebook)
FNBRendererFancy (class in flatnotebook)
FNBRendererFirefox2 (class in flatnotebook)
FNBRendererMgr (class in flatnotebook)
FNBRendererRibbonTabs (class in flatnotebook)
FNBRendererVC71 (class in flatnotebook)
FNBRendererVC8 (class in flatnotebook)
Focus() (UltimateListCtrl method)
FocusHandler (class in flatmenu)
FoldPanelBar (class in foldpanelbar)
foldpanelbar (module)
FoldPanelBarHandler (class in persist.persist_handlers)
FoldPanelItem (class in foldpanelbar)
FoldWindowItem (class in foldpanelbar)
Font (TabNavigatorProps attribute)
FontDialogHandler (class in persist.persist_handlers)
FontFromFont() (in module ribbon.art_aui)
(in module shortcuteditor)
(in module xlsgrid)
FontPickerHandler (class in persist.persist_handlers)
FormatCell() (XLSGrid method)
FormatColour() (in module flatnotebook)
FormatString() (XLSText method)
FourWaySplitter (class in fourwaysplitter)
fourwaysplitter (module)
FourWaySplitterEvent (class in fourwaysplitter)
frac() (FixedPoint method)
FrameColour() (ArtManager method)
Free() (artmanager.ArtManager class method)
(persist.persistencemanager.PersistenceManager class method)
Freeze() (CustomTreeCtrl method)
FromAcceleratorTable() (ShortcutEditor method)
FromMenuBar() (ShortcutEditor method)
FromMenuItem() (Shortcut method)

Navigation

  • index
  • modules |
  • Home |
  • Gallery |
  • Index


Index

  • modules |
  • Home |
  • Gallery |
  • Contents»
  • Index

Index – G

GenerateSelectionEvent() (MultiColumnListCtrl method)
GenericMessageDialog (class in genericmessagedialog)
genericmessagedialog (module)
GenericTreeItem (class in customtreectrl)
GeometryInfo (class in ultimatelistctrl)
Get() (artmanager.ArtManager class method)
(Shortcut method)
(persist.persistencemanager.PersistenceManager class method)
Get3StateValue() (GenericTreeItem method)
get_precision() (FixedPoint method)
GetAccelArray() (FlatMenu method)
GetAccelerator() (Shortcut method)
(ShortcutEvent method)
GetAcceleratorEntry() (FlatMenuItem method)
GetAccelIndex() (ArtManager method)
(in module flatmenu)
GetAccelString() (FlatMenuItem method)
GetAccelTable() (FlatMenu method)
GetActiveItem() (RibbonGallery method)
GetActivePage() (AuiTabContainer method)
(RibbonBar method)
GetActiveTabColour() (FlatNotebook method)
GetActiveTabCtrl() (AuiNotebook method)
GetActiveTabTextColour() (FlatNotebook method)
GetActiveToolbarItem() (FlatMenuBar method)
GetAGWFlags() (AuiDefaultTabArt method)
(AuiDefaultToolBarArt method)
(AuiManager method)
(AuiSimpleTabArt method)
(AuiTabContainer method)
GetAGWWindowStyleFlag() (AuiNotebook method)
(AuiToolBar method)
(CubeColourDialog method)
(CustomTreeCtrl method)
(FlatBookBase method)
(FlatNotebook method)
(FourWaySplitter method)
(HyperTreeList method)
(PageContainer method)
(PeakMeterCtrl method)
(PyCollapsiblePane method)
(RibbonBar method)
(UltimateListCtrl method)
GetAlign() (UltimateListItem method)
GetAlignBuffer() (ArtManager method)
GetAlignment() (AuiToolBarItem method)
(ButtonPanel method)
(TreeListColumnInfo method)
GetAllItems() (FlatMenu method)
GetAllPanes() (AuiManager method)
GetAngle() (PieCtrl method)
GetAngleFromCoord() (KnobCtrl method)
GetAngleOfRotation() (SButton method)
GetAngleRange() (SpeedMeter method)
GetAngularRange() (KnobCtrl method)
GetAnimationStep() (AuiManager method)
GetArcColour() (SpeedMeter method)
GetArtProvider() (AuiManager method)
(AuiNotebook method)
(AuiTabContainer method)
(AuiToolBar method)
(RibbonControl method)
GetAttr() (UltimateListItemData method)
(UltimateListLineData method)
(XLSCell method)
(XLSTable method)
GetAttributes() (AuiManager method)
(GenericTreeItem method)
(UltimateListItem method)
GetAuiManager() (AuiNotebook method)
(AuiToolBar method)
GetAutoNotebookStyle() (AuiManager method)
GetAutoNotebookTabArt() (AuiManager method)
GetBackColour() (PieCtrl method)
(PieCtrlLegend method)
GetBackground() (PieCtrl method)
GetBackgroundBitmap() (FlatMenu method)
GetBackgroundColour() (AquaButton method)
(FlatMenuBar method)
(SwitcherItems method)
(TreeItemAttr method)
(UltimateListCtrl method)
(UltimateListItem method)
(UltimateListItemAttr method)
(UltimateListItemData method)
GetBackgroundImage() (CustomTreeCtrl method)
(HyperTreeList method)
(UltimateListCtrl method)
(UltimateListMainWindow method)
GetBalloonColour() (BalloonTip method)
GetBalloonIcon() (BalloonTip method)
GetBalloonMessage() (BalloonTip method)
GetBalloonShape() (BalloonTip method)
GetBalloonTipStyle() (BalloonTip method)
GetBalloonTitle() (BalloonTip method)
GetBar() (CaptionBarEvent method)
(RibbonButtonBarEvent method)
(RibbonToolBarEvent method)
GetBarColor() (PyGauge method)
GetBarColour() (ImageBar method)
(PyGauge method)
(ZoomBar method)
GetBarGradient() (PyGauge method)
GetBarPlacement() (InfoBar method)
GetBarTabWidth() (RibbonAUIArtProvider method)
(RibbonMSWArtProvider method)
GetBarText() (ButtonPanel method)
GetBaseColour() (in module aui.aui_utilities)
GetBaseId() (FileHistory method)
GetBestColumnWidth() (TreeListMainWindow method)
GetBestSize() (ButtonInfo method)
(ButtonPanelText method)
(Control method)
(Separator method)
(Sizer method)
GetBestTabCtrlSize() (AuiDefaultTabArt method)
(AuiSimpleTabArt method)
GetBitmap() (AuiToolBarItem method)
(ButtonInfo method)
(FlatMenuItem method)
(FlatToolbarItem method)
(ImageBar method)
(PyImageList method)
(RibbonGalleryItem method)
(Shortcut method)
(SwitcherItem method)
(Thumb method)
(ZoomBarImage method)
GetBitmapDisabled() (SBitmapButton method)
GetBitmapFocus() (SBitmapButton method)
GetBitmapLabel() (SBitmapButton method)
GetBitmapSelected() (SBitmapButton method)
GetBitmapStartLocation() (ArtManager method)
GetBodyImage() (SuperToolTip method)
GetBold() (HyperLinkCtrl method)
GetBorder() (PyCollapsiblePane method)
GetBorderColor() (PyGauge method)
GetBorderColour() (FlatNotebook method)
(PyGauge method)
GetBorderPadding() (PyGauge method)
GetBorderPen() (CustomTreeCtrl method)
(HyperTreeList method)
GetBorderXWidth() (FlatMenu method)
GetBorderYWidth() (FlatMenu method)
GetBottomEndColour() (GradientButton method)
GetBottomGradientColor() (SuperToolTip method)
GetBottomGradientColour() (SuperToolTip method)
GetBottomLeft() (FourWaySplitter method)
GetBottomRight() (FourWaySplitter method)
GetBottomStartColour() (GradientButton method)
GetBoundingColour() (KnobCtrl method)
GetBoundingRect() (CustomTreeCtrl method)
(HyperTreeList method)
GetBounds() (RulerCtrl method)
GetBPArt() (ButtonPanel method)
GetBreakColumn() (SwitcherItem method)
GetBtnLabel() (PyCollapsiblePane method)
GetButton() (AuiManagerEvent method)
(PyCollapsiblePane method)
GetButtonBarButtonSize() (RibbonMSWArtProvider method)
GetButtonColour() (SButton method)
GetButtonFont() (PyCollapsiblePane method)
GetButtonObj() (AquaButtonEvent method)
(GradientButtonEvent method)
(SButtonEvent method)
GetButtonsAreaLength() (FNBRenderer method)
GetButtonsImageList() (CustomTreeCtrl method)
(HyperTreeList method)
GetButtonSize() (ZoomBar method)
GetById() (Shortcut method)
GetCacheFrom() (CommandListEvent method)
GetCacheTo() (CommandListEvent method)
GetCaption() (GenericMessageDialog method)
(ImageInfo method)
(PageInfo method)
(ScrolledThumbnail method)
(Thumb method)
GetCaptionColour() (CaptionBarStyle method)
GetCaptionFont() (CaptionBarStyle method)
(ScrolledThumbnail method)
GetCaptionHeight() (ScrolledThumbnail method)
GetCaptionLength() (FoldPanelItem method)
GetCaptionLinesCount() (Thumb method)
GetCaptionStyle() (CaptionBar method)
(CaptionBarStyle method)
(FoldPanelBar method)
(FoldPanelItem method)
GetCenterZoom() (ZoomBar method)
GetCheckboxImageSize() (UltimateListMainWindow method)
GetCheckedImage() (GenericTreeItem method)
GetCheckedState() (TreeCtrlHandler method)
GetCheckedStateOfChildren() (TreeCtrlHandler method)
GetCheckedStateOfItem() (TreeCtrlHandler method)
GetChildren() (GenericTreeItem method)
GetChildrenCount() (CustomTreeCtrl method)
(GenericTreeItem method)
(HyperTreeList method)
GetClassDefaultAttributes() (customtreectrl.CustomTreeCtrl class method)
(UltimateListCtrl method)
(hypertreelist.HyperTreeList class method)
GetClickPoint() (CommandToolBarEvent method)
GetClientData() (RibbonGalleryItem method)
GetClientRect() (FlatMenuButton method)
GetCloseButtonBitmap() (in module infobar)
GetCmdId() (MenuEntryInfo method)
GetColor() (AuiDefaultDockArt method)
(BPArt method)
GetColour() (AuiDefaultDockArt method)
(BPArt method)
(LabelBook method)
(LabelContainer method)
(PageInfo method)
(PiePart method)
(RibbonAUIArtProvider method)
(RibbonMSWArtProvider method)
(TreeListColumnInfo method)
(UltimateListItemData method)
GetColourData() (CubeColourDialog method)
GetColours() (HyperLinkCtrl method)
GetColoursAccordingToState() (FMRenderer method)
(RendererMSOffice2007 method)
GetColourScheme() (RibbonMSWArtProvider method)
GetColourSchemes() (ArtManager method)
GetColPos() (SwitcherItem method)
GetColumn() (CommandListEvent method)
(HyperTreeList method)
(TreeListHeaderWindow method)
(UltimateListCtrl method)
(UltimateListItem method)
(UltimateListMainWindow method)
GetColumnAlignment() (HyperTreeList method)
(TreeListHeaderWindow method)
GetColumnColour() (HyperTreeList method)
(TreeListHeaderWindow method)
GetColumnCount() (HyperTreeList method)
(SwitcherItems method)
(TreeListHeaderWindow method)
(TreeListMainWindow method)
(UltimateListCtrl method)
(UltimateListMainWindow method)
GetColumnCustomRenderer() (UltimateListMainWindow method)
GetColumnFont() (HyperTreeList method)
GetColumnImage() (HyperTreeList method)
GetColumnText() (HyperTreeList method)
(TreeListHeaderWindow method)
GetColumnWidth() (HyperTreeList method)
(TreeListHeaderWindow method)
(UltimateListCtrl method)
(UltimateListMainWindow method)
GetCommandId() (AuiCommandCapture method)
(ToolbarCommandCapture method)
GetComment() (XLSCell method)
GetCommentsRange() (Excel method)
GetConfigurationHandler() (PersistenceManager method)
GetConnectionPen() (CustomTreeCtrl method)
(HyperTreeList method)
GetContainer() (FNBDragInfo method)
GetContextMenu() (FlatMenuItem method)
GetControlBmp() (CustomTreeCtrl method)
(UltimateListMainWindow method)
GetControls() (ButtonPanel method)
GetCount() (CustomTreeCtrl method)
(FileHistory method)
(FoldPanelBar method)
(RibbonGallery method)
GetCountPerPage() (UltimateListCtrl method)
(UltimateListMainWindow method)
GetCreationDate() (Thumb method)
GetCurrentCheckedImage() (GenericTreeItem method)
GetCurrentImage() (GenericTreeItem method)
(TreeListItem method)
GetCurrentItem() (HyperTreeList method)
(TreeListMainWindow method)
GetCurrentPage() (AuiNotebook method)
(FlatBookBase method)
(FlatNotebook method)
GetCustomCancelBitmap() (GenericMessageDialog method)
GetCustomCancelLabel() (GenericMessageDialog method)
GetCustomControl() (FlatToolbarItem method)
GetCustomHelpBitmap() (GenericMessageDialog method)
GetCustomHelpLabel() (GenericMessageDialog method)
GetCustomNoBitmap() (GenericMessageDialog method)
GetCustomNoLabel() (GenericMessageDialog method)
GetCustomOKBitmap() (GenericMessageDialog method)
GetCustomOKLabel() (GenericMessageDialog method)
GetCustomPage() (FlatNotebook method)
GetCustomRenderer() (UltimateListHeaderData method)
(UltimateListItem method)
(UltimateListItemData method)
GetCustomYesBitmap() (GenericMessageDialog method)
GetCustomYesLabel() (GenericMessageDialog method)
GetData() (CommandListEvent method)
(GenericTreeItem method)
(UltimateListItem method)
getDataBL() (in module thumbnailctrl)
getDataSH() (in module thumbnailctrl)
getDataTR() (in module thumbnailctrl)
GetDC() (AuiManagerEvent method)
GetDefaultAttributes() (AquaButton method)
(GradientButton method)
GetDefaultBorder() (AuiNotebook method)
(AuiTabCtrl method)
(InfoBar method)
(RibbonBar method)
(RibbonButtonBar method)
(RibbonGallery method)
(RibbonPage method)
(RibbonPanel method)
(RibbonToolBar method)
(UltimateListCtrl method)
GetDefaultCancelBitmap() (GenericMessageDialog method)
GetDefaultCancelLabel() (GenericMessageDialog method)
GetDefaultFontData() (XLSGrid method)
GetDefaultHelpBitmap() (GenericMessageDialog method)
GetDefaultHelpLabel() (GenericMessageDialog method)
GetDefaultNoBitmap() (GenericMessageDialog method)
GetDefaultNoLabel() (GenericMessageDialog method)
GetDefaultOKBitmap() (GenericMessageDialog method)
GetDefaultOKLabel() (GenericMessageDialog method)
GetDefaultValue() (FloatSpin method)
GetDefaultYesBitmap() (GenericMessageDialog method)
GetDefaultYesLabel() (GenericMessageDialog method)
GetDescription() (SwitcherItem method)
GetDigits() (FloatSpin method)
GetDirection() (SpeedMeter method)
GetDisabledBitmap() (AuiToolBarItem method)
(FlatMenuItem method)
(FlatToolbarItem method)
GetDisabledColor() (AquaButton method)
GetDisabledColour() (AquaButton method)
(CustomTreeCtrl method)
(HyperTreeList method)
GetDisabledTextColour() (UltimateListCtrl method)
(UltimateListMainWindow method)
GetDispatched() (CommandNotebookEvent method)
GetDockingImage() (in module aui.aui_utilities)
GetDockPixelOffset() (AuiManager method)
GetDockSizeConstraint() (AuiManager method)
GetDownButtonState() (RibbonGallery method)
GetdragcursorBitmap() (in module ultimatelistctrl)
GetdragcursorData() (in module ultimatelistctrl)
GetdragcursorImage() (in module ultimatelistctrl)
GetDragSource() (CommandNotebookEvent method)
GetDrawFooterLine() (SuperToolTip method)
GetDrawHeaderLine() (SuperToolTip method)
GetDrawingParent() (RulerCtrl method)
GetDropArrowButtonPos() (FNBRenderer method)
GetDropShadow() (ScrolledThumbnail method)
(SuperToolTip method)
GetDropTarget() (UltimateListCtrl method)
GetDummyLine() (UltimateListMainWindow method)
GetEditControl() (CustomTreeCtrl method)
(HyperTreeList method)
(UltimateListCtrl method)
GetEffectDuration() (InfoBar method)
GetElementSize() (AuiDefaultToolBarArt method)
GetEllipseAxis() (SButton method)
GetEnabled() (AuiNotebook method)
(AuiTabContainer method)
(FlatBookBase method)
(FlatNotebook method)
(ImageContainerBase method)
(ImageInfo method)
(PageContainer method)
(PageInfo method)
GetEndDelay() (BalloonTip method)
(SuperToolTip method)
GetEndX() (FNBRendererVC8 method)
GetExpandedDummy() (RibbonPanel method)
GetExpandedPanel() (RibbonPanel method)
GetExpandedPosition() (RibbonPanel method)
GetExpanderDimensions() (PyCollapsiblePane method)
GetExpansionState() (TreeCtrlHandler method)
GetExpansionStateOfChildren() (TreeCtrlHandler method)
GetExpansionStateOfItem() (TreeCtrlHandler method)
GetExtendedMessage() (GenericMessageDialog method)
GetExtensionButtonState() (RibbonGallery method)
GetExtraNavigationKey() (MultiColumnListCtrl method)
(SwitcherDialog method)
GetFalloffEffect() (PeakMeterCtrl method)
GetFileName() (Thumb method)
GetFileSize() (Thumb method)
GetFilledColour() (ProgressPie method)
GetFillerColour() (SpeedMeter method)
GetFirstChild() (CustomTreeCtrl method)
(HyperTreeList method)
(Shortcut method)
GetFirstColour() (CaptionBarStyle method)
GetFirstExpandedItem() (HyperTreeList method)
(TreeListMainWindow method)
GetFirstGradientColour() (CustomTreeCtrl method)
(HyperTreeList method)
(KnobCtrl method)
(ProgressGauge method)
(PyProgress method)
(SpeedMeter method)
(UltimateListCtrl method)
(UltimateListMainWindow method)
GetFirstSelected() (UltimateListCtrl method)
GetFirstVisibleItem() (CustomTreeCtrl method)
(HyperTreeList method)
(TreeListMainWindow method)
GetFlags() (RibbonMSWArtProvider method)
GetFocusedItem() (UltimateListCtrl method)
GetFoldPanel() (FoldPanelBar method)
GetFoldStatus() (CaptionBarEvent method)
GetFont() (ArtManager method)
(AuiDefaultDockArt method)
(AuiDefaultToolBarArt method)
(BPArt method)
(FlatMenuItem method)
(FloatSpin method)
(RendererBase method)
(RibbonMSWArtProvider method)
(SwitcherItem method)
(TreeItemAttr method)
(TreeListColumnInfo method)
(UltimateListHeaderData method)
(UltimateListItem method)
(UltimateListItemAttr method)
(UltimateListItemData method)
GetFontBold() (FlatBookBase method)
GetFontSizeMultiple() (FlatBookBase method)
GetFooter() (SuperToolTip method)
GetFooterAlign() (UltimateListItem method)
GetFooterBackgroundColour() (UltimateListItem method)
(UltimateListItemAttr method)
GetFooterBitmap() (SuperToolTip method)
GetFooterFont() (SuperToolTip method)
(UltimateListItem method)
(UltimateListItemAttr method)
GetFooterFormat() (UltimateListHeaderData method)
(UltimateListItem method)
GetFooterHeight() (UltimateListCtrl method)
GetFooterImage() (UltimateListHeaderData method)
(UltimateListItem method)
GetFooterKind() (UltimateListHeaderData method)
(UltimateListItem method)
GetFooterText() (UltimateListItem method)
GetFooterTextColour() (UltimateListItem method)
(UltimateListItemAttr method)
GetForegroundColour() (AquaButton method)
(UltimateListCtrl method)
GetFormat() (FloatSpin method)
(RulerCtrl method)
(UltimateListHeaderData method)
(UltimateListItem method)
GetFrame() (AuiManager method)
GetFullFileName() (Thumb method)
GetFullMessage() (GenericMessageDialog method)
GetGallery() (RibbonGalleryEvent method)
GetGalleryClientSize() (RibbonMSWArtProvider method)
GetGalleryItem() (RibbonGalleryEvent method)
GetGallerySize() (RibbonMSWArtProvider method)
GetGaugeBackground() (ProgressGauge method)
(PyProgress method)
GetGaugeProportion() (ProgressGauge method)
(PyProgress method)
GetGaugeSteps() (ProgressGauge method)
(PyProgress method)
GetGlobalPopupMenu() (ScrolledThumbnail method)
GetGradientColourBorder() (FlatNotebook method)
GetGradientColourFrom() (FlatNotebook method)
GetGradientColourTo() (FlatNotebook method)
GetGradientStyle() (CustomTreeCtrl method)
(HyperTreeList method)
(UltimateListCtrl method)
(UltimateListMainWindow method)
GetGradientType() (BPArt method)
GetGripperVisible() (AuiToolBar method)
GetGroup() (FlatToolbarItem method)
GetHandColour() (SpeedMeter method)
GetHandStyle() (SpeedMeter method)
GetHeader() (SuperToolTip method)
GetHeaderBitmap() (SuperToolTip method)
GetHeaderFont() (SuperToolTip method)
GetHeaderHeight() (UltimateListCtrl method)
GetHeaderWidth() (UltimateListMainWindow method)
GetHeaderWindow() (HyperTreeList method)
GetHeight() (FlatMenuItem method)
(GenericTreeItem method)
(PieCtrl method)
(UltimateListItemData method)
(UltimateListLineData method)
GetHeightForPageHeight() (AuiNotebook method)
GetHelp() (FlatMenuItem method)
GetHideEffect() (InfoBar method)
GetHighlightBrush() (UltimateListMainWindow method)
GetHighlightPointed() (ScrolledThumbnail method)
GetHilightFocusColour() (CustomTreeCtrl method)
(HyperTreeList method)
GetHilightNonFocusColour() (CustomTreeCtrl method)
(HyperTreeList method)
GetHistoryFile() (FileHistory method)
GetHorizontalBorder() (PieCtrlLegend method)
GetHotBitmap() (FlatMenuItem method)
GetHoverBitmap() (AuiToolBarItem method)
GetHoverColor() (AquaButton method)
GetHoverColour() (AquaButton method)
GetHoveredItem() (RibbonGallery method)
GetHSVAColour() (CubeColourDialog method)
GetHyperlinkFont() (SuperToolTip method)
GetHyperTextFont() (CustomTreeCtrl method)
(HyperTreeList method)
(UltimateListCtrl method)
(UltimateListMainWindow method)
GetHyperTextNewColour() (CustomTreeCtrl method)
(HyperTreeList method)
(UltimateListCtrl method)
(UltimateListMainWindow method)
GetHyperTextVisitedColour() (CustomTreeCtrl method)
(HyperTreeList method)
(UltimateListCtrl method)
(UltimateListMainWindow method)
GetIcon() (PyImageList method)
(RibbonPage method)
GetId() (AuiToolBarItem method)
(ButtonInfo method)
(Control method)
(FlatMenuItem method)
(FlatToolbarItem method)
(Indicator method)
(Shortcut method)
(SwitcherItem method)
(Thumb method)
(UltimateListItem method)
GetIdxFromWindow() (AuiTabContainer method)
GetImage() (CommandListEvent method)
(GenericTreeItem method)
(Thumb method)
(TreeListColumnInfo method)
(TreeListItem method)
(UltimateListHeaderData method)
(UltimateListItem method)
(UltimateListItemData method)
(UltimateListLineData method)
GetImageCount() (PyImageList method)
GetImageIndex() (ImageInfo method)
(PageInfo method)
(Shortcut method)
GetImageList() (AuiNotebook method)
(CustomTreeCtrl method)
(FlatBookBase method)
(FlatNotebook method)
(HyperTreeList method)
(ImageContainerBase method)
(PageContainer method)
(UltimateListCtrl method)
GetImageListCheck() (CustomTreeCtrl method)
(HyperTreeList method)
GetImageSize() (ImageContainerBase method)
(Indicator method)
(UltimateListMainWindow method)
GetIncrement() (FloatSpin method)
GetIndent() (CustomTreeCtrl method)
(HyperTreeList method)
GetIndentSize() (AuiDefaultTabArt method)
(AuiSimpleTabArt method)
GetIndex() (CommandListEvent method)
GetIndexForFocus() (SwitcherItems method)
GetIndexOfItem() (TreeCtrlHandler method)
GetIndicator() (RulerCtrl method)
GetIndicatorBitmap() (in module rulerctrl)
GetIndicatorData() (in module rulerctrl)
GetIndicatorImage() (in module rulerctrl)
GetInternalFrameRect() (in module aui.framemanager)
GetIntersection() (SpeedMeter method)
GetIntervalColours() (SpeedMeter method)
GetIntervals() (SpeedMeter method)
GetInvisibleMenuItemCount() (FlatMenuBar method)
GetInvisibleToolbarItemCount() (FlatMenuBar method)
GetIsDown() (SButtonEvent method)
GetIsGroup() (SwitcherItem method)
GetItem() (CommandListEvent method)
(CommandTreeEvent method)
(RibbonGallery method)
(ScrolledThumbnail method)
(SwitcherItems method)
(UltimateListCtrl method)
(UltimateListHeaderData method)
(UltimateListItemData method)
(UltimateListLineData method)
(UltimateListMainWindow method)
GetItem3StateValue() (CustomTreeCtrl method)
(HyperTreeList method)
GetItemBackgroundColour() (CustomTreeCtrl method)
(HyperTreeList method)
(UltimateListCtrl method)
GetItemChildren() (TreeCtrlHandler method)
GetItemClientData() (RibbonGallery method)
GetItemCount() (ScrolledThumbnail method)
(SwitcherItems method)
(UltimateListCtrl method)
(UltimateListMainWindow method)
GetItemCustomRenderer() (UltimateListCtrl method)
(UltimateListMainWindow method)
GetItemData() (UltimateListCtrl method)
GetItemFont() (CustomTreeCtrl method)
(FlatMenu method)
(HyperTreeList method)
(SwitcherItems method)
(UltimateListCtrl method)
GetItemHeight() (FlatMenu method)
GetItemIdentity() (ListShortcut method)
(TreeCtrlHandler method)
GetItemImage() (CustomTreeCtrl method)
(HyperTreeList method)
(TreeListMainWindow method)
GetItemIndex() (ScrolledThumbnail method)
GetItemKind() (UltimateListCtrl method)
(UltimateListMainWindow method)
GetItemLeftImage() (CustomTreeCtrl method)
GetItemOverFlow() (UltimateListCtrl method)
(UltimateListMainWindow method)
GetItemParent() (CustomTreeCtrl method)
(HyperTreeList method)
GetItemPos() (FoldPanelItem method)
GetItemPosition() (UltimateListCtrl method)
(UltimateListMainWindow method)
GetItemPyData() (CustomTreeCtrl method)
(HyperTreeList method)
(UltimateListCtrl method)
GetItemRect() (CommandToolBarEvent method)
(UltimateListCtrl method)
(UltimateListMainWindow method)
GetItems() (MultiColumnListCtrl method)
GetItemSize() (ButtonPanel method)
(CustomTreeCtrl method)
GetItemSpacing() (UltimateListCtrl method)
(UltimateListMainWindow method)
GetItemState() (UltimateListCtrl method)
(UltimateListMainWindow method)
GetItemText() (CustomTreeCtrl method)
(HyperTreeList method)
(TreeListMainWindow method)
(UltimateListCtrl method)
(UltimateListMainWindow method)
GetItemTextColour() (CustomTreeCtrl method)
(FlatMenu method)
(HyperTreeList method)
(UltimateListCtrl method)
GetItemTextSize() (UltimateListMainWindow method)
GetItemType() (CustomTreeCtrl method)
(HyperTreeList method)
GetItemVisited() (CustomTreeCtrl method)
(HyperTreeList method)
(UltimateListCtrl method)
(UltimateListMainWindow method)
GetItemWidth() (TreeListMainWindow method)
GetItemWidthWithImage() (UltimateListMainWindow method)
GetItemWindow() (CustomTreeCtrl method)
(HyperTreeList method)
(TreeListMainWindow method)
(UltimateListCtrl method)
(UltimateListMainWindow method)
GetItemWindowEnabled() (CustomTreeCtrl method)
(HyperTreeList method)
(TreeListMainWindow method)
(UltimateListCtrl method)
(UltimateListMainWindow method)
GetKey() (PersistenceManager method)
GetKeyCode() (CommandListEvent method)
(CommandTreeEvent method)
GetKeyEvent() (CommandTreeEvent method)
GetKind() (AbstractHandler method)
(AuiToolBarItem method)
(ButtonInfo method)
(FlatMenuItem method)
(PersistentObject method)
(UltimateListHeaderData method)
(UltimateListItem method)
(UltimateListItemData method)
(UltimateListLineData method)
GetKnobRadius() (KnobCtrl method)
GetLabel() (AuiToolBarItem method)
(CommandListEvent method)
(CommandNotebookEvent method)
(CommandTreeEvent method)
(FlatMenu method)
(FlatMenuItem method)
(FlatToolbarItem method)
(PiePart method)
(PyCollapsiblePane method)
(SButton method)
(Shortcut method)
(ZoomBarEvent method)
(ZoomBarImage method)
GetLabelColour() (PieCtrlLegend method)
(SButton method)
GetLabelFont() (PieCtrlLegend method)
GetLabelSize() (AuiDefaultToolBarArt method)
(AuiToolBar method)
(in module aui.aui_utilities)
GetLargestSize() (RibbonButtonBarButtonBase method)
GetLastChild() (CustomTreeCtrl method)
(HyperTreeList method)
GetLastVisibleMenu() (FlatMenuBar method)
GetLastVisibleTab() (PageContainer method)
GetLeftButtonPos() (FNBRenderer method)
GetLeftImage() (GenericTreeItem method)
GetLeftImageList() (CustomTreeCtrl method)
GetLeftMarginWidth() (FlatMenu method)
GetLeftSpacing() (FoldWindowItem method)
GetLegend() (PieCtrl method)
GetLine() (UltimateListMainWindow method)
GetLineCheckboxRect() (UltimateListMainWindow method)
GetLineColour() (FoldWindowItem method)
GetLineHeight() (CustomTreeCtrl method)
(UltimateListMainWindow method)
GetLineHighlightRect() (UltimateListMainWindow method)
GetLineIconRect() (UltimateListMainWindow method)
GetLineLabelRect() (UltimateListMainWindow method)
GetLineLength() (FoldWindowItem method)
GetLineRect() (UltimateListMainWindow method)
GetLineSize() (UltimateListMainWindow method)
GetLineY() (FoldWindowItem method)
(UltimateListMainWindow method)
GetLinkCursor() (HyperLinkCtrl method)
GetListCtrl() (UltimateListMainWindow method)
GetLongHelp() (AuiToolBarItem method)
(ButtonInfo method)
(FlatMenuItem method)
(FlatToolbarItem method)
GetMainColumn() (TreeListMainWindow method)
GetMainWindow() (HyperTreeList method)
GetMainWindowOfCompositeControl() (UltimateListMainWindow method)
GetMajorAxis() (RibbonPage method)
GetManagedWindow() (AuiManager method)
GetManager() (AuiManagerEvent method)
(in module aui.framemanager)
GetManagerStyle() (PersistenceManager method)
GetMask() (CommandListEvent method)
(UltimateListItem method)
GetMax() (FloatSpin method)
GetMaxFiles() (FileHistory method)
GetMaxLayer() (in module aui.framemanager)
GetMaxRow() (in module aui.framemanager)
GetMaxValue() (KnobCtrl method)
(ProgressPie method)
GetMaxWidth() (CustomTreeCtrl method)
GetMBVerticalGradient() (ArtManager method)
GetMeasuringFont() (AuiDefaultTabArt method)
(AuiSimpleTabArt method)
GetMenu() (FlatMenuBar method)
(FlatMenuItem method)
(MenuEntryInfo method)
GetMenuBar() (FlatMenu method)
GetMenuBarBorder() (ArtManager method)
GetMenuBarColourScheme() (ArtManager method)
GetMenuBarFaceColour() (ArtManager method)
GetMenuBarForSubMenu() (FlatMenu method)
GetMenuBarSelectionColour() (ArtManager method)
GetMenuBgFactor() (ArtManager method)
GetMenuCount() (FlatMenuBar method)
GetMenuFaceColour() (ArtManager method)
(RendererBase method)
GetMenuItemCount() (FlatMenu method)
GetMenuItems() (FlatMenu method)
GetMenuItemWidth() (FlatMenu method)
GetMenuOwner() (FlatMenuBase method)
GetMenuRect() (FlatMenu method)
GetMenus() (FileHistory method)
GetMenuTheme() (ArtManager method)
GetMenuWidth() (FlatMenu method)
GetMessage() (GenericMessageDialog method)
(SuperToolTip method)
GetMessageColour() (BalloonTip method)
GetMessageDialogStyle() (GenericMessageDialog method)
GetMessageFont() (BalloonTip method)
(SuperToolTip method)
GetMetric() (AuiDefaultDockArt method)
(BPArt method)
(RibbonMSWArtProvider method)
GetMiddleGradientColor() (SuperToolTip method)
GetMiddleGradientColour() (SuperToolTip method)
GetMiddleIcon() (SpeedMeter method)
GetMiddleIconDimens() (SpeedMeter method)
GetMiddleText() (SpeedMeter method)
GetMiddleTextColour() (SpeedMeter method)
GetMiddleTextFont() (SpeedMeter method)
GetMin() (FloatSpin method)
GetMinimisedIcon() (RibbonPanel method)
GetMinimisedPanelMinimumSize() (RibbonMSWArtProvider method)
GetMinimizeMode() (AuiPaneInfo method)
GetMinMaxTabWidth() (AuiNotebook method)
GetMinNotMinimisedSize() (RibbonPanel method)
GetMinSize() (AuiToolBarItem method)
(RibbonButtonBar method)
(RibbonPage method)
(RibbonPanel method)
GetMinValue() (KnobCtrl method)
GetMnemonicChar() (FlatMenuItem method)
GetMode() (FourWaySplitter method)
(UltimateListLineData method)
GetModifierKey() (MultiColumnListCtrl method)
(SwitcherDialog method)
GetMondrianBitmap() (in module thumbnailctrl)
GetMondrianData() (in module thumbnailctrl)
GetMondrianImage() (in module thumbnailctrl)
GetMoreMenuButtonRect() (FlatMenuBar method)
GetMRUEntryLabel() (in module flatmenu)
GetMS2007ButtonSunken() (ArtManager method)
GetName() (PersistentObject method)
(SwitcherItem method)
GetNext() (CustomTreeCtrl method)
(HyperTreeList method)
GetNextActiveItem() (CustomTreeCtrl method)
(UltimateListMainWindow method)
GetNextChild() (CustomTreeCtrl method)
(HyperTreeList method)
(Shortcut method)
GetNextExpanded() (CustomTreeCtrl method)
(HyperTreeList method)
(TreeListMainWindow method)
GetNextItem() (UltimateListCtrl method)
(UltimateListMainWindow method)
GetNextLargerSize() (RibbonControl method)
GetNextSelected() (UltimateListCtrl method)
GetNextSibling() (CustomTreeCtrl method)
(HyperTreeList method)
GetNextSmallerSize() (RibbonControl method)
GetNextVisible() (CustomTreeCtrl method)
(HyperTreeList method)
GetNoHistoryFiles() (FileHistory method)
GetNonActiveTabTextColour() (FlatNotebook method)
GetNonFlexibleChildren() (ButtonPanel method)
GetNormalFont() (AuiDefaultTabArt method)
(AuiSimpleTabArt method)
GetNotebook() (FlatNotebookDragEvent method)
GetNotebookRoot() (in module aui.framemanager)
GetNotebooks() (AuiManager method)
GetNotifyEvent() (AuiNotebookEvent method)
(AuiToolBarEvent method)
(FlatNotebookEvent method)
(TreeEvent method)
(UltimateListEvent method)
GetNumberCols() (XLSTable method)
GetNumberColumns() (FlatMenu method)
GetNumberOfSecondaryTicks() (SpeedMeter method)
GetNumberRows() (XLSTable method)
GetNumOfVisibleTabs() (PageContainer method)
GetNumTabsCanScrollLeft() (PageContainer method)
GetOldAccelerator() (ShortcutEvent method)
GetOldItem() (CommandTreeEvent method)
GetOldNotebook() (FlatNotebookDragEvent method)
GetOldSelection() (CommandNotebookEvent method)
(FlatNotebookEvent method)
(ImageNotebookEvent method)
GetOldValue() (KnobCtrlEvent method)
(RulerCtrlEvent method)
GetOppositeDockTotalSize() (AuiManager method)
GetOptions() (FlatMenuBar method)
GetOrientation() (AuiDefaultToolBarArt method)
(AuiToolBarItem method)
GetOriginalImage() (ScrolledThumbnail method)
(Thumb method)
GetOriginalSize() (Thumb method)
GetOverFlow() (UltimateListItem method)
(UltimateListItemData method)
GetOverflowRect() (AuiToolBar method)
GetOverflowState() (AuiToolBar method)
GetOverflowVisible() (AuiToolBar method)
GetOwner() (UltimateListHeaderWindow method)
GetOwnerManager() (AuiFloatingFrame method)
GetPadding() (FlatNotebook method)
GetPage() (AuiNotebook method)
(AuiTabContainer method)
(FlatBookBase method)
(FlatNotebook method)
(RibbonBar method)
(RibbonBarEvent method)
GetPageBackgroundRedrawArea() (RibbonMSWArtProvider method)
GetPageBestSize() (FlatNotebook method)
GetPageBitmap() (AuiNotebook method)
GetPageCount() (AuiNotebook method)
(AuiTabContainer method)
(FlatBookBase method)
(FlatNotebook method)
(PageContainer method)
GetPageImage() (AuiNotebook method)
(FlatBookBase method)
(FlatNotebook method)
(ImageContainerBase method)
(PageContainer method)
GetPageIndex() (AuiNotebook method)
(FNBDragInfo method)
(FlatNotebook method)
GetPageInfo() (AuiNotebook method)
GetPages() (AuiTabContainer method)
GetPageShapeAngle() (FlatNotebook method)
GetPageText() (AuiNotebook method)
(FlatBookBase method)
(FlatNotebook method)
(ImageContainerBase method)
(PageContainer method)
GetPageTextColour() (AuiNotebook method)
(FlatNotebook method)
(PageContainer method)
(PageInfo method)
GetPaintRect() (ScrolledThumbnail method)
GetPane() (AuiManager method)
(AuiManagerEvent method)
(PyCollapsiblePane method)
GetPaneByName() (AuiManager method)
GetPaneByWidget() (AuiManager method)
GetPanelClientSize() (RibbonAUIArtProvider method)
(RibbonMSWArtProvider method)
GetPanelLength() (FoldPanelItem method)
GetPanelSize() (RibbonAUIArtProvider method)
(RibbonMSWArtProvider method)
GetPanelSizerBestSize() (RibbonPanel method)
GetPanelSizerMinSize() (RibbonPanel method)
GetPanelsLength() (FoldPanelBar method)
GetPanePart() (AuiManager method)
GetPanePositionsAndSizes() (AuiManager method)
GetParent() (GenericTreeItem method)
GetPartAngles() (PieCtrl method)
GetPartnerDock() (AuiManager method)
GetPartnerPane() (AuiManager method)
GetPartSizerRect() (AuiManager method)
GetPath() (AquaButton method)
(GradientButton method)
GetPaths() (MultiDirDialog method)
GetPersistenceDirectory() (PersistenceManager method)
GetPersistenceFile() (PersistenceManager method)
GetPersistenceKey() (PersistenceManager method)
GetPoint() (CommandListEvent method)
(CommandTreeEvent method)
GetPointed() (ScrolledThumbnail method)
GetPointedItem() (ScrolledThumbnail method)
GetPopupMenu() (ScrolledThumbnail method)
GetPopupText() (ToasterBoxWindow method)
GetPosition() (FloatSpinEvent method)
(HyperLinkEvent method)
(ImageBar method)
(ImageInfo method)
(Indicator method)
(PageInfo method)
(RibbonGalleryItem method)
(ZoomBarImage method)
GetPressedBottomColour() (GradientButton method)
GetPressedTopColour() (GradientButton method)
GetPrev() (CustomTreeCtrl method)
(HyperTreeList method)
GetPrevChild() (HyperTreeList method)
(TreeListMainWindow method)
GetPrevExpanded() (CustomTreeCtrl method)
(HyperTreeList method)
(TreeListMainWindow method)
GetPreviousSelection() (FlatNotebook method)
GetPrevSibling() (CustomTreeCtrl method)
(HyperTreeList method)
GetPrevVisible() (CustomTreeCtrl method)
(HyperTreeList method)
(TreeListMainWindow method)
GetProportion() (AuiToolBarItem method)
GetPulseOnFocus() (AquaButton method)
GetPyColour() (Colour method)
GetPyData() (CustomTreeCtrl method)
(HyperTreeList method)
(UltimateListCtrl method)
(UltimateListItem method)
GetRaiseToolbar() (ArtManager method)
GetRange() (PyGauge method)
GetRangeValue() (PeakMeterCtrl method)
GetRawValue() (XLSTable method)
GetRect() (ButtonInfo method)
(FlatMenuItem method)
(Indicator method)
(MenuEntryInfo method)
(SwitcherItem method)
GetRegion() (PageInfo method)
GetRenderer() (FlatMenuBar method)
(FMRendererMgr method)
(FNBRendererMgr method)
(FlatMenuBase method)
GetRendererManager() (FlatMenuBar method)
GetRGBAColour() (CubeColourDialog method)
GetRightButtonPos() (FNBRenderer method)
GetRightMarginWidth() (FlatMenu method)
GetRightSpacing() (FoldWindowItem method)
GetRootItem() (CustomTreeCtrl method)
(HyperTreeList method)
GetRootMenu() (FlatMenuBase method)
GetRotatedBitmap() (AuiToolBarItem method)
GetRotatedImage() (Thumb method)
GetRotation() (Thumb method)
GetRotationAngle() (PieCtrl method)
GetRowCount() (SwitcherItems method)
GetRowPos() (SwitcherItem method)
GetRuleColour() (UltimateListMainWindow method)
GetSashDClickUnsplit() (AuiNotebook method)
GetSashIdx() (FourWaySplitterEvent method)
GetSashPosition() (FourWaySplitterEvent method)
GetScrollButtonMinimumSize() (RibbonAUIArtProvider method)
(RibbonMSWArtProvider method)
GetScrolledWin() (UltimateListCtrl method)
GetScrollPos() (UltimateListCtrl method)
GetScrollRange() (UltimateListCtrl method)
GetScrollThumb() (UltimateListCtrl method)
GetSecondColour() (CaptionBarStyle method)
GetSecondGradientColour() (CustomTreeCtrl method)
(HyperTreeList method)
(KnobCtrl method)
(ProgressGauge method)
(PyProgress method)
(SpeedMeter method)
(UltimateListCtrl method)
(UltimateListMainWindow method)
GetSelectedCount() (SelectionStore method)
GetSelectedFont() (AuiDefaultTabArt method)
(AuiSimpleTabArt method)
GetSelectedImage() (TreeListColumnInfo method)
GetSelectedItem() (FlatMenuItemGroup method)
(ScrolledThumbnail method)
GetSelectedItemCount() (UltimateListCtrl method)
(UltimateListMainWindow method)
GetSelectedPage() (TabNavigatorWindow method)
GetSelectedTextBitmap() (MenuEntryInfo method)
GetSelection() (AuiNotebook method)
(CommandNotebookEvent method)
(CustomTreeCtrl method)
(FlatBookBase method)
(FlatNotebook method)
(FlatNotebookEvent method)
(HyperTreeList method)
(ImageNotebookEvent method)
(PageContainer method)
(RibbonGallery method)
(ScrolledThumbnail method)
(SwitcherDialog method)
(SwitcherItems method)
(ZoomBarEvent method)
GetSelectionColour() (ScrolledThumbnail method)
(SwitcherItems method)
GetSelectionOutlineColour() (SwitcherItems method)
GetSelections() (CustomTreeCtrl method)
(HyperTreeList method)
(ListBoxHandler method)
GetSelectionState() (TreeCtrlHandler method)
GetSelectionStateOfChildren() (TreeCtrlHandler method)
GetSelectionStateOfItem() (TreeCtrlHandler method)
GetSeparatorColour() (CustomTreeCtrl method)
getShadow() (in module thumbnailctrl)
GetShadowColour() (SpeedMeter method)
GetShortcut() (ShortcutEvent method)
GetShortcutManager() (ShortcutEditor method)
GetShortHelp() (AuiToolBarItem method)
(ButtonInfo method)
(FlatMenuItem method)
(FlatToolbarItem method)
GetShowComboBox() (ThumbnailCtrl method)
GetShowDir() (ScrolledThumbnail method)
GetShowEdges() (PieCtrl method)
GetShowEffect() (InfoBar method)
GetShowLabels() (ZoomBar method)
GetShowReflections() (ZoomBar method)
GetSiblingGroupItem() (FlatMenu method)
GetSingleLineBorderColour() (PageContainer method)
GetSize() (GenericTreeItem method)
(ImageBar method)
(ImageInfo method)
(PageInfo method)
(PyImageList method)
(ZoomBarImage method)
GetSizeInOrientation() (in module ribbon.page)
(in module ribbon.toolbar)
GetSizerItem() (AuiToolBarItem method)
GetSlidingPoints() (in module aui.aui_utilities)
GetSmallerSize() (RibbonButtonBarButtonBase method)
GetSnapPosition() (AuiManager method)
GetSnapToTicks() (FloatSpin method)
GetSpacerPixels() (AuiToolBarItem method)
GetSpacing() (CustomTreeCtrl method)
(FoldWindowItem method)
(HyperTreeList method)
GetSpeedBackground() (SpeedMeter method)
GetSpeedStyle() (SpeedMeter method)
GetSpeedValue() (SpeedMeter method)
GetSplashStyle() (AdvancedSplash method)
GetStartDelay() (BalloonTip method)
(SuperToolTip method)
GetStartX() (FNBRendererVC8 method)
GetState() (AuiToolBarItem method)
(MenuEntryInfo method)
(UltimateListHeaderData method)
(UltimateListItem method)
GetStateImageList() (CustomTreeCtrl method)
(HyperTreeList method)
GetStatus() (ButtonInfo method)
GetStockBitmap() (ArtManager method)
GetStyle() (ButtonPanel method)
GetStyleKeys() (in module supertooltip)
GetSubItemRect() (UltimateListCtrl method)
(UltimateListMainWindow method)
GetSubMenu() (FlatMenuItem method)
GetSuitableBitmap() (FlatMenuItem method)
GetTabAngle() (PageInfo method)
GetTabArea() (FlatNotebook method)
GetTabAreaColour() (FlatNotebook method)
GetTabAreaWidth() (LabelContainer method)
GetTabContainer() (AuiNotebook method)
GetTabCtrlFromPoint() (AuiNotebook method)
GetTabCtrlHeight() (AuiNotebook method)
(RibbonAUIArtProvider method)
(RibbonMSWArtProvider method)
GetTabFrameFromTabCtrl() (AuiNotebook method)
GetTabFrameFromWindow() (AuiNotebook method)
GetTabOffset() (AuiTabContainer method)
GetTabSize() (AuiDefaultTabArt method)
(AuiSimpleTabArt method)
(ChromeTabArt method)
(FF2TabArt method)
(VC8TabArt method)
GetTag() (CaptionBarEvent method)
GetTags() (KnobCtrl method)
GetTagsColour() (KnobCtrl method)
GetTarget() (BalloonTip method)
(SuperToolTip method)
GetText() (AdvancedSplash method)
(ButtonInfo method)
(ButtonPanelText method)
(CommandListEvent method)
(Excel method)
(FlatMenuItem method)
(GenericTreeItem method)
(TreeListColumnInfo method)
(TreeListItem method)
(UltimateListHeaderData method)
(UltimateListItem method)
(UltimateListItemData method)
(UltimateListLineData method)
GetTextAlignment() (ButtonInfo method)
GetTextBitmap() (MenuEntryInfo method)
GetTextColor() (SuperToolTip method)
GetTextColour() (AdvancedSplash method)
(FlatMenuItem method)
(SuperToolTip method)
(SwitcherItem method)
(SwitcherItems method)
(TreeItemAttr method)
(UltimateListCtrl method)
(UltimateListItem method)
(UltimateListItemAttr method)
GetTextColourDisable() (ArtManager method)
(RendererBase method)
GetTextColourEnable() (ArtManager method)
(FMRendererMSOffice2007 method)
(FMRendererXP method)
(RendererBase method)
(RendererMSOffice2007 method)
(RendererXP method)
GetTextCtrl() (FloatSpin method)
GetTextCtrlAlignmentStyle() (HyperTreeList method)
GetTextCtrlStyle() (HyperTreeList method)
GetTextFont() (AdvancedSplash method)
GetTextForMeasuring() (UltimateListItemData method)
GetTextHeight() (UltimateListHeaderWindow method)
GetTextLength() (UltimateListMainWindow method)
GetTextOrientation() (AuiDefaultToolBarArt method)
GetTextPosition() (AdvancedSplash method)
GetTextRect() (ImageInfo method)
GetTextStartLocation() (ArtManager method)
GetTextX() (TreeListItem method)
GetThemeBaseColour() (ArtManager method)
GetThumbBorder() (ScrolledThumbnail method)
GetThumbHeight() (ScrolledThumbnail method)
GetThumbInfo() (ScrolledThumbnail method)
GetThumbOutline() (ScrolledThumbnail method)
GetThumbSize() (ScrolledThumbnail method)
GetThumbWidth() (ScrolledThumbnail method)
GetTicks() (SpeedMeter method)
GetTicksColour() (SpeedMeter method)
GetTicksFont() (SpeedMeter method)
GetTileOrientation() (FlatNotebook method)
GetTimeFormat() (RulerCtrl method)
GetTimer() (FlatMenuButton method)
GetTimerId() (FlatMenuButton method)
GetTipWindow() (SuperToolTip method)
GetTitle() (MenuEntryInfo method)
(SwitcherItem method)
GetTitleColour() (BalloonTip method)
GetTitleFont() (BalloonTip method)
GetToasterBoxWindow() (ToasterBox method)
GetToggle() (__SToggleMixin method)
(__ToggleMixin method)
GetToggled() (ButtonInfo method)
GetToolBarDockOffsets() (in module aui.framemanager)
GetToolBarFits() (AuiToolBar method)
GetToolBitmap() (AuiToolBar method)
GetToolBitmapSize() (AuiToolBar method)
GetToolBorderPadding() (AuiToolBar method)
GetToolCount() (AuiToolBar method)
GetToolDropDown() (AuiToolBar method)
GetToolEnabled() (AuiToolBar method)
GetToolFits() (AuiToolBar method)
GetToolFitsByIndex() (AuiToolBar method)
GetToolId() (CommandToolBarEvent method)
GetToolIndex() (AuiToolBar method)
GetToolLabel() (AuiToolBar method)
GetToolLongHelp() (AuiToolBar method)
GetToolOrientation() (AuiToolBar method)
GetToolPacking() (AuiToolBar method)
GetToolPos() (AuiToolBar method)
GetToolProportion() (AuiToolBar method)
GetToolRect() (AuiToolBar method)
GetToolSeparation() (AuiToolBar method)
GetToolShortHelp() (AuiToolBar method)
GetToolSize() (AuiDefaultToolBarArt method)
(RibbonMSWArtProvider method)
GetToolsPosition() (AuiDefaultToolBarArt method)
GetToolSticky() (AuiToolBar method)
GetToolTextOrientation() (AuiToolBar method)
GetToolTip() (CommandTreeEvent method)
(UltimateListHeaderData method)
(UltimateListItem method)
(UltimateListItemData method)
(UltimateListLineData method)
GetToolToggled() (AuiToolBar method)
GetTopEndColour() (GradientButton method)
GetTopGradientColor() (SuperToolTip method)
GetTopGradientColour() (SuperToolTip method)
GetTopItem() (UltimateListCtrl method)
GetTopLeft() (FourWaySplitter method)
GetTopRight() (FourWaySplitter method)
GetTopStartColour() (GradientButton method)
GetTotalPixSizeAndProportion() (AuiManager method)
GetTotalWidth() (UltimateListMainWindow method)
GetTrackPosition() (KnobCtrl method)
GetTransparency() (ArtManager method)
GetType() (FoldWindowItem method)
(GenericTreeItem method)
GetUnderlines() (HyperLinkCtrl method)
GetUnfilledColour() (ProgressPie method)
GetUpButtonState() (RibbonGallery method)
GetURL() (HyperLinkCtrl method)
GetUseFade() (SuperToolTip method)
GetUseFocus() (ToasterBox method)
GetUseFocusIndicator() (SButton method)
GetUseHelp() (ButtonPanel method)
GetUserData() (AuiToolBarItem method)
GetUserLineHeight() (UltimateListCtrl method)
(UltimateListMainWindow method)
GetValue() (__SToggleMixin method)
(FloatSpin method)
(GenericTreeItem method)
(Indicator method)
(KnobCtrl method)
(KnobCtrlEvent method)
(PiePart method)
(ProgressPie method)
(PyGauge method)
(RulerCtrlEvent method)
(XLSCell method)
(XLSTable method)
(XLSText method)
(__ToggleMixin method)
GetVerticalBorder() (PieCtrlLegend method)
GetVeto() (AuiManagerEvent method)
GetViewRect() (UltimateListCtrl method)
(UltimateListMainWindow method)
GetVisibleLinesRange() (UltimateListMainWindow method)
GetVisited() (GenericTreeItem method)
(HyperLinkCtrl method)
(UltimateListItem method)
(UltimateListItemData method)
GetWaterMark() (UltimateListCtrl method)
(UltimateListMainWindow method)
GetWidth() (GenericTreeItem method)
(TreeListColumnInfo method)
(TreeListHeaderWindow method)
(UltimateListHeaderData method)
(UltimateListItem method)
(UltimateListItemData method)
(UltimateListLineData method)
GetWindow() (AuiToolBarItem method)
(FourWaySplitter method)
(GenericTreeItem method)
(PersistentObject method)
(SwitcherItem method)
(TreeListItem method)
(UltimateListItem method)
(UltimateListItemData method)
GetWindowEnabled() (GenericTreeItem method)
(TreeListItem method)
(UltimateListItem method)
(UltimateListItemData method)
GetWindowFromIdx() (AuiTabContainer method)
GetWindowHeight() (UltimateListHeaderWindow method)
GetWindowLength() (FoldWindowItem method)
GetWindowSize() (GenericTreeItem method)
(TreeListItem method)
(UltimateListItem method)
(UltimateListItemData method)
GetX() (GenericTreeItem method)
(UltimateListItemData method)
(UltimateListLineData method)
GetXPos() (FNBRenderer method)
GetXRect() (PageInfo method)
GetY() (GenericTreeItem method)
(UltimateListItemData method)
(UltimateListLineData method)
GetZoomFactor() (ScrolledThumbnail method)
(ZoomBar method)
GiveFeedback() (FNBDropSource method)
GotoURL() (HyperLinkCtrl method)
GradientButton (class in gradientbutton)
gradientbutton (module)
GradientButtonEvent (class in gradientbutton)
Gripper() (AuiPaneInfo method)
GripperTop() (AuiPaneInfo method)
GTKExpander (class in pycollapsiblepane)

Navigation

  • index
  • modules |
  • Home |
  • Gallery |
  • Index


Index

  • modules |
  • Home |
  • Gallery |
  • Contents»
  • Index

Index – H

HandleColumnCheck() (UltimateListHeaderWindow method)
HandleHyperLink() (CustomTreeCtrl method)
(UltimateListMainWindow method)
HasAGWFlag() (CustomTreeCtrl method)
(FlatBookBase method)
(FlatNotebook method)
(HyperTreeList method)
(ImageContainerBase method)
(PageContainer method)
(PyCollapsiblePane method)
(UltimateListCtrl method)
(UltimateListMainWindow method)
HasAttributes() (UltimateListItem method)
HasBackgroundColour() (TreeItemAttr method)
(UltimateListItemAttr method)
(UltimateListItemData method)
HasBarText() (ButtonPanel method)
HasBorder() (AuiPaneInfo method)
HasButtons() (CustomTreeCtrl method)
HasCaption() (AuiPaneInfo method)
HasCaptionLeft() (AuiPaneInfo method)
HasChanged() (Shortcut method)
HasChildren() (CustomTreeCtrl method)
(GenericTreeItem method)
(HyperTreeList method)
HasCloseButton() (AuiNotebook method)
(AuiPaneInfo method)
HasColour() (UltimateListItemData method)
HasCtrlHandler() (in module persist.persist_handlers)
HasCurrent() (UltimateListMainWindow method)
HasCustomBitmaps() (GenericMessageDialog method)
HasCustomLabels() (GenericMessageDialog method)
HasDropDown() (AuiToolBarItem method)
HasFlag() (AuiPaneInfo method)
(ListShortcut method)
HasFocus() (Control method)
(UltimateListMainWindow method)
HasFont() (TreeItemAttr method)
(UltimateListItemAttr method)
(UltimateListItemData method)
HasFooter() (UltimateListCtrl method)
(UltimateListMainWindow method)
HasFooterBackgroundColour() (UltimateListItemAttr method)
HasFooterFont() (UltimateListItemAttr method)
HasFooterImage() (UltimateListHeaderData method)
HasFooterTextColour() (UltimateListItemAttr method)
HasGripper() (AuiPaneInfo method)
HasGripperTop() (AuiPaneInfo method)
HasHeader() (UltimateListCtrl method)
(UltimateListMainWindow method)
HasImage() (UltimateListHeaderData method)
(UltimateListItemData method)
(UltimateListLineData method)
HasMaximizeButton() (AuiPaneInfo method)
HasMinimizeButton() (AuiPaneInfo method)
HasMode() (UltimateListLineData method)
HasMultiplePages() (AuiNotebook method)
(RibbonBar method)
HasNotebook() (AuiPaneInfo method)
HasPinButton() (AuiPaneInfo method)
HasPlus() (GenericTreeItem method)
HasRange() (FloatSpin method)
HasText() (ButtonInfo method)
(UltimateListHeaderData method)
(UltimateListItemData method)
(UltimateListLineData method)
HasTextColour() (TreeItemAttr method)
(UltimateListItemAttr method)
Hide() (AuiPaneInfo method)
(Control method)
(TreeListItem method)
HideAllTabs() (AuiNotebook method)
HideExpanded() (RibbonPanel method)
HideHint() (AuiManager method)
HideItem() (HyperTreeList method)
(TreeListMainWindow method)
HideItemWindow() (UltimateListLineData method)
HideScrollButtons() (RibbonPage method)
HideTabs() (FlatNotebook method)
HideWindows() (CustomTreeCtrl method)
(TreeListMainWindow method)
(UltimateListMainWindow method)
Highlight() (UltimateListLineData method)
HighlightAll() (UltimateListMainWindow method)
HighlightBackgroundColour() (ArtManager method)
HighlightImage() (NativeImageHandler method)
(PILImageHandler method)
HighlightLine() (UltimateListMainWindow method)
HighlightLines() (UltimateListMainWindow method)
HitTest() (AuiCenterDockingGuide method)
(AuiDockingGuide method)
(AuiManager method)
(AuiSingleDockingGuide method)
(AuiToolBar method)
(ButtonPanel method)
(CustomTreeCtrl method)
(FlatMenu method)
(FlatMenuBar method)
(GenericTreeItem method)
(HyperTreeList method)
(ImageContainerBase method)
(PageContainer method)
(TreeListItem method)
(TreeListMainWindow method)
(UltimateListCtrl method)
(UltimateListMainWindow method)
(ZoomBar method)
HitTestColumn() (UltimateListHeaderWindow method)
HitTestLine() (UltimateListMainWindow method)
HitTestTabs() (RibbonBar method)
Host() (AuiDockingGuideInfo method)
HSVWheel (class in cubecolourdialog)
HTMLHelpWindow (class in shortcuteditor)
hyperlink (module)
HyperLinkCtrl (class in hyperlink)
HyperLinkEvent (class in hyperlink)
HyperTreeList (class in hypertreelist)
hypertreelist (module)

Navigation

  • index
  • modules |
  • Home |
  • Gallery |
  • Index


Index

  • modules |
  • Home |
  • Gallery |
  • Contents»
  • Index

Index – I

Icon (TabNavigatorProps attribute)
Icon() (AuiPaneInfo method)
Id (ButtonInfo attribute)
ImageBar (class in zoombar)
ImageContainer (class in labelbook)
ImageContainerBase (class in labelbook)
ImageInfo (class in labelbook)
ImageNotebookEvent (class in labelbook)
InCircle() (HSVWheel method)
IndentPressedBitmap() (in module aui.aui_utilities)
Indicator (class in rulerctrl)
InfoBar (class in infobar)
infobar (module)
Init() (AuiDefaultDockArt method)
(FlatNotebook method)
(InfoBar method)
(ModernDockArt method)
(ShortcutEditor method)
(UltimateListHeaderData method)
(UltimateListItem method)
(UltimateListItemData method)
(UltimateListMainWindow method)
InitColours() (ArtManager method)
(SButton method)
InitData() (PeakMeterCtrl method)
InitDialog() (CubeColourDialog method)
InitFont() (SuperToolTip method)
Initialise() (FMCustomizeDlg method)
Initialize() (ArtManager method)
InitializeColours() (CustomPanel method)
(LabelContainer method)
InitialReposition() (ZoomBar method)
InitItems() (UltimateListLineData method)
InitNotebook() (AuiNotebook method)
InRange() (FloatSpin method)
(in module peakmeter)
InReportView() (UltimateListLineData method)
(UltimateListMainWindow method)
Insert() (BoxSizer method)
(FlatMenu method)
(FlatMenuBar method)
(GenericTreeItem method)
InsertColumn() (HyperTreeList method)
(TreeListHeaderWindow method)
(UltimateListCtrl method)
(UltimateListMainWindow method)
InsertColumnInfo() (HyperTreeList method)
(TreeListHeaderWindow method)
(UltimateListCtrl method)
InsertImageItem() (UltimateListCtrl method)
InsertImageStringItem() (UltimateListCtrl method)
InsertItem() (CustomTreeCtrl method)
(FlatMenu method)
(HyperTreeList method)
(ScrolledThumbnail method)
(UltimateListCtrl method)
(UltimateListMainWindow method)
InsertItemByIndex() (CustomTreeCtrl method)
InsertItemByItem() (CustomTreeCtrl method)
InsertPage() (AuiNotebook method)
(AuiTabContainer method)
(FlatBookBase method)
(FlatNotebook method)
(ImageContainerBase method)
(PageContainer method)
InsertPane() (AuiManager method)
InsertSeparator() (CustomTreeCtrl method)
(FlatMenu method)
InsertStringItem() (UltimateListCtrl method)
InsertWindow() (FourWaySplitter method)
InstallGridHint() (XLSGrid method)
Intersection() (in module cubecolourdialog)
InTileView() (UltimateListMainWindow method)
Invalidate() (AquaButton method)
(RulerCtrl method)
(ToolTipWindowBase method)
Is3State() (GenericTreeItem method)
IsActive() (AuiToolBarItem method)
IsAllowed() (AuiNotebookEvent method)
(AuiToolBarEvent method)
(FlatNotebookEvent method)
(FourWaySplitterEvent method)
(ImageNotebookEvent method)
(RibbonBarEvent method)
(TreeEvent method)
(UltimateListEvent method)
IsAncestorOf() (in module ribbon.panel)
IsAudio() (ScrolledThumbnail method)
IsAudioVideo() (ScrolledThumbnail method)
IsBold() (CustomTreeCtrl method)
(GenericTreeItem method)
(HyperTreeList method)
IsBottomDockable() (AuiPaneInfo method)
IsBottomSnappable() (AuiPaneInfo method)
IsBufferingSupported() (in module hypertreelist)
IsButtonEnabled() (RibbonButtonBar method)
(ZoomBar method)
IsCheckable() (FlatMenuItem method)
IsChecked() (FlatMenuItem method)
(FlatToolbarItem method)
(GenericTreeItem method)
(UltimateListHeaderData method)
(UltimateListItem method)
(UltimateListItemData method)
(UltimateListLineData method)
IsCheckItem() (FlatToolbarItem method)
IsCollapsed() (CaptionBar method)
(PyCollapsiblePane method)
IsColumnEditable() (HyperTreeList method)
(TreeListHeaderWindow method)
IsColumnShown() (HyperTreeList method)
(TreeListHeaderWindow method)
(UltimateListCtrl method)
(UltimateListHeaderWindow method)
(UltimateListMainWindow method)
IsCustomControl() (FlatToolbarItem method)
IsDark() (ArtManager method)
IsDefaultTabs() (PageContainer method)
IsDefaultValue() (FloatSpin method)
IsDescendantOf() (CustomTreeCtrl method)
(HyperTreeList method)
IsDestroyOnClose() (AuiPaneInfo method)
IsDifferentDockingPosition() (in module aui.framemanager)
IsDockable() (AuiPaneInfo method)
IsDocked() (AuiPaneInfo method)
IsDragging() (AuiTabCtrl method)
IsDropDownClicked() (CommandToolBarEvent method)
IsEditable() (TreeListColumnInfo method)
IsEditCancelled() (CommandListEvent method)
(CommandNotebookEvent method)
(CommandTreeEvent method)
IsEmpty() (RibbonGallery method)
(UltimateListMainWindow method)
IsEnabled() (ButtonInfo method)
(FlatMenuItem method)
(FlatToolbarItem method)
(GenericTreeItem method)
(SButton method)
(UltimateListItem method)
(UltimateListItemAttr method)
(UltimateListItemData method)
(ZoomBarImage method)
IsEqual() (PeakMeterData method)
IsExpanded() (CustomTreeCtrl method)
(FoldPanelItem method)
(GenericTreeItem method)
(HyperTreeList method)
(PyCollapsiblePane method)
IsFinite() (FloatSpin method)
IsFixed() (AuiPaneInfo method)
IsFloatable() (AuiPaneInfo method)
IsFloating() (AuiPaneInfo method)
IsFlyOut() (AuiPaneInfo method)
IsFooterChecked() (UltimateListHeaderData method)
(UltimateListItem method)
IsGreater() (PeakMeterData method)
IsGridVisible() (PeakMeterCtrl method)
IsHidden() (TreeListItem method)
IsHighlighted() (UltimateListLineData method)
(UltimateListMainWindow method)
IsHit() (UltimateListHeaderData method)
(UltimateListItemData method)
IsHorizontal() (AuiDockInfo method)
(AuiPaneInfo method)
IsHovered() (RibbonGallery method)
(RibbonPanel method)
IsHyperLink() (XLSText method)
IsHyperText() (GenericTreeItem method)
(UltimateListItem method)
(UltimateListItemData method)
IsItalic() (CustomTreeCtrl method)
(GenericTreeItem method)
IsItem3State() (CustomTreeCtrl method)
(HyperTreeList method)
IsItemChecked() (CustomTreeCtrl method)
(HyperTreeList method)
(UltimateListCtrl method)
(UltimateListMainWindow method)
IsItemEnabled() (CustomTreeCtrl method)
(HyperTreeList method)
(TreeListMainWindow method)
(UltimateListCtrl method)
(UltimateListMainWindow method)
IsItemHyperText() (CustomTreeCtrl method)
(HyperTreeList method)
(UltimateListCtrl method)
(UltimateListMainWindow method)
IsItemSeparator() (CustomTreeCtrl method)
IsItemVisible() (HyperTreeList method)
(TreeListMainWindow method)
IsLeftDockable() (AuiPaneInfo method)
IsLeftSnappable() (AuiPaneInfo method)
IsLower() (PeakMeterData method)
IsMaximized() (AuiPaneInfo method)
IsMinimised() (RibbonPanel method)
IsMinimised1() (RibbonPanel method)
IsMinimised2() (RibbonPanel method)
IsMinimized() (AuiPaneInfo method)
IsMouseHovering() (PageContainer method)
IsMouseWellOutsideWindow() (AuiNotebook method)
IsMovable() (AuiPaneInfo method)
IsMultiline() (AuiNotebookPage method)
IsNotebookControl() (AuiPaneInfo method)
IsNotebookDockable() (AuiPaneInfo method)
IsNotebookPage() (AuiPaneInfo method)
IsOk() (AuiDockInfo method)
(AuiPaneInfo method)
(GenericTreeItem method)
IsOutside() (SButton method)
IsPaneButtonVisible() (AuiManager method)
IsPaneMinimized() (AuiToolBar method)
IsRadioItem() (FlatMenuItem method)
(FlatToolbarItem method)
IsRegularItem() (FlatToolbarItem method)
IsRenamable() (AuiNotebook method)
IsResizeable() (AuiPaneInfo method)
IsRightDockable() (AuiPaneInfo method)
IsRightSnappable() (AuiPaneInfo method)
IsSelected() (CustomTreeCtrl method)
(FlatToolbarItem method)
(GenericTreeItem method)
(HyperTreeList method)
(ScrolledThumbnail method)
(SelectionStore method)
(UltimateListCtrl method)
IsSeparator() (FlatMenuItem method)
(FlatToolbarItem method)
(GenericTreeItem method)
IsShown() (AuiPaneInfo method)
(Control method)
(FlatMenuItem method)
(TreeListColumnInfo method)
(UltimateListItem method)
IsSingleSel() (UltimateListMainWindow method)
IsSizingContinuous() (RibbonButtonBar method)
(RibbonControl method)
(RibbonGallery method)
(RibbonPanel method)
(RibbonToolBar method)
IsSnappable() (AuiPaneInfo method)
IsStandard() (ButtonPanel method)
IsStarted() (PeakMeterCtrl method)
IsSticky() (AuiToolBarItem method)
IsSubMenu() (FlatMenuItem method)
IsTabVisible() (AuiTabContainer method)
(PageContainer method)
IsToolbar() (AuiPaneInfo method)
IsTop() (Shortcut method)
IsTopDockable() (AuiPaneInfo method)
IsTopSnappable() (AuiPaneInfo method)
IsTransparent() (PieCtrlLegend method)
IsValid() (AuiDockingGuideWindow method)
(AuiSingleDockingGuide method)
IsVertical() (AuiDockInfo method)
(AuiPaneInfo method)
(ButtonPanel method)
(CaptionBar method)
(FoldPanelBar method)
(FoldPanelItem method)
IsVideo() (ScrolledThumbnail method)
IsVirtual() (TreeListMainWindow method)
(UltimateListCtrl method)
(UltimateListLineData method)
(UltimateListMainWindow method)
IsVisible() (CustomTreeCtrl method)
(RibbonGalleryItem method)
IsZoomed() (ZoomBarImage method)
item() (EditCtrl method)
(TabTextCtrl method)
(TreeTextCtrl method)
ItemHasChildren() (CustomTreeCtrl method)
(HyperTreeList method)

Navigation

  • index
  • modules |
  • Home |
  • Gallery |
  • Index


Index

  • modules |
  • Home |
  • Gallery |
  • Contents»
  • Index

Index – K

KnobCtrl (class in knobctrl)
knobctrl (module)
KnobCtrlEvent (class in knobctrl)

Navigation

  • index
  • modules |
  • Home |
  • Gallery |
  • Index


Index

  • modules |
  • Home |
  • Gallery |
  • Contents»
  • Index

Index – L

Label (class in rulerctrl)
LabelBook (class in labelbook)
labelbook (module)
LabelContainer (class in labelbook)
LabelMajor() (RulerCtrl method)
LabelMinor() (RulerCtrl method)
LabelString() (RulerCtrl method)
Layer() (AuiPaneInfo method)
Layout() (BoxSizer method)
(PyCollapsiblePane method)
(RibbonGallery method)
(RibbonPage method)
(RibbonPanel method)
LayoutAddDock() (AuiManager method)
LayoutAddPane() (AuiManager method)
LayoutAll() (AuiManager method)
LayoutItems() (ButtonPanel method)
(MultiDirDialog method)
Left() (AuiDockingGuideInfo method)
(AuiPaneInfo method)
LeftDockable() (AuiPaneInfo method)
LeftSnappable() (AuiPaneInfo method)
LightColour() (AquaButton method)
(ArtManager method)
(GradientButton method)
(in module aui.aui_utilities)
(in module flatnotebook)
LightContrastColour() (in module aui.aui_utilities)
LightenColour() (in module peakmeter)
Lighter() (RibbonHSLColour method)
LikePrimary() (in module ribbon.art_msw)
LikeSecondary() (in module ribbon.art_msw)
LineDescription (class in cubecolourdialog)
ListBoxHandler (class in persist.persist_handlers)
ListCtrlHandler (class in persist.persist_handlers)
ListDirectory() (ScrolledThumbnail method)
ListShortcut (class in shortcuteditor)
Load() (FileHistory method)
LoadImages() (ScrolledThumbnail method)
LoadPaneInfo() (AuiManager method)
LoadPerspective() (AuiManager method)
(AuiNotebook method)
LoadThumbnail() (NativeImageHandler method)
(PILImageHandler method)
LoopScales() (ZoomBarImage method)

Navigation

  • index
  • modules |
  • Home |
  • Gallery |
  • Index


Index

  • modules |
  • Home |
  • Gallery |
  • Contents»
  • Index

Index – M

MakeBold() (in module supertooltip)
MakeDarker() (RibbonHSLColour method)
MakeDisabledBitmap() (in module aui.aui_utilities)
(RibbonButtonBar method)
(RibbonToolBar method)
(in module buttonpanel)
(in module customtreectrl)
(in module ultimatelistctrl)
(in module zoombar)
MakeGray() (in module aui.aui_utilities)
MakeImageList() (ListShortcut method)
MakeLayouts() (RibbonButtonBar method)
MakePalette() (in module rulerctrl)
(SButton method)
MakeResizedBitmap() (RibbonButtonBar method)
MakeTabVisible() (AuiTabContainer method)
MakeVenetianBlinds() (AuiDockingHintWindow method)
MakeWindowTransparent() (ArtManager method)
(ToasterBoxWindow method)
(ToolTipWindowBase method)
Match() (Shortcut method)
Maximize() (AuiPaneInfo method)
MaximizeButton() (AuiPaneInfo method)
MaximizePane() (AuiManager method)
MaxSize() (AuiPaneInfo method)
MaxSize1() (AuiPaneInfo method)
MaxSize2() (AuiPaneInfo method)
mcPopupWindow (class in flatmenu)
Measure() (XLSRichText method)
MediaCtrlHandler (class in persist.persist_handlers)
MenuBarHandler (class in persist.persist_handlers)
MenuEntryInfo (class in flatmenu)
MenuKbdRedirector (class in flatmenu)
Minimize() (AuiPaneInfo method)
MinimizeButton() (AuiPaneInfo method)
MinimizeMode() (AuiPaneInfo method)
MinimizePane() (AuiManager method)
MinimizeTabOffset() (AuiTabContainer method)
MinimizeTarget() (AuiPaneInfo method)
MinSize (TabNavigatorProps attribute)
MinSize() (AuiPaneInfo method)
MinSize1() (AuiPaneInfo method)
MinSize2() (AuiPaneInfo method)
MixColours() (ArtManager method)
ModernDockArt (class in aui.dockart)
Movable() (AuiPaneInfo method)
Move() (FlatMenuButton method)
MoveAbove() (ToasterBox method)
MovePage() (AuiTabContainer method)
MoveSplit() (FourWaySplitter method)
MoveTabPage() (PageContainer method)
MoveToFocus() (UltimateListMainWindow method)
MoveToItem() (UltimateListMainWindow method)
MultiColumnListCtrl (class in aui.aui_switcherdialog)
MultiDirDialog (class in multidirdialog)
multidirdialog (module)

Navigation

  • index
  • modules |
  • Home |
  • Gallery |
  • Index


Index

  • modules |
  • Home |
  • Gallery |
  • Contents»
  • Index

Index – N

Name() (AuiPaneInfo method)
NativeImageHandler (class in thumbnailctrl)
NavigatorProps (AuiNotebook attribute)
needsRestore (AuiPaneInfo attribute)
NewInstance() (RibbonButtonBarButtonBase method)
NotebookControl() (AuiPaneInfo method)
NotebookDockable() (AuiPaneInfo method)
NotebookPage() (AuiPaneInfo method)
NotebookPreview() (AuiNotebook method)
Notify() (AquaButton method)
(GradientButton method)
(SButton method)
(StatusBarTimer method), [1]
(ToasterBox method)
(TreeEditTimer method)
(TreeFindTimer method)
(UltimateListRenameTimer method)
NotifyTimer() (BalloonTip method)
(ToasterBoxWindow method)
NumberTabsCanFit() (FNBRenderer method)
(FNBRendererVC8 method)

Navigation

  • index
  • modules |
  • Home |
  • Gallery |
  • Index


Index

  • modules |
  • Home |
  • Gallery |
  • Contents»
  • Index

Index – O

OfflimitsPixels() (RulerCtrl method)
OffsetColour() (KnobCtrl method)
OnAccelCmd() (FlatMenuBar method)
OnAcceptEdit() (CustomTreeCtrl method)
(TreeListMainWindow method)
OnActivate() (AuiFloatingFrame method)
(SwitcherDialog method)
OnAddCustom() (CubeColourDialog method)
OnAlphaSpin() (CubeColourDialog method)
OnArrowChar() (UltimateListMainWindow method)
OnButton() (AuiTabCtrl method)
(InfoBar method)
(PyCollapsiblePane method)
OnCancel() (CubeColourDialog method)
(GenericMessageDialog method)
(MultiDirDialog method)
(PyProgress method)
OnCancelEdit() (CustomTreeCtrl method)
(TreeListMainWindow method)
OnCaptionDoubleClicked() (AuiManager method)
OnCaptureLost() (AuiManager method)
(AuiTabCtrl method)
OnChangeStyle() (FMCustomizeDlg method)
OnChar() (CaptionBar method)
(EditTextCtrl method)
(FlatMenu method)
(FloatSpin method)
(FloatTextCtrl method)
(MultiColumnListCtrl method)
(ScrolledThumbnail method)
(TabTextCtrl method)
(TreeTextCtrl method)
(UltimateListMainWindow method)
(UltimateListTextCtrl method)
OnCharEvents() (AdvancedSplash method)
OnCheckFlyTimer() (AuiFloatingFrame method)
OnChildDismiss() (FlatMenuBase method)
OnChildFocus() (AuiManager method)
(UltimateListMainWindow method)
OnChildFocusNotebook() (AuiNotebook method)
OnChildKillFocus() (RibbonPanel method)
OnClearFilter() (ShortcutEditor method)
OnClose() (AuiFloatingFrame method)
(BalloonFrame method)
(HTMLHelpWindow method)
(MultiDirDialog method)
(PyProgress method)
(ToasterBoxWindow method)
OnCloseFloatingPage() (AuiNotebook method)
OnCloseWindow() (AdvancedSplash method)
(CubeColourDialog method)
(SwitcherDialog method)
OnComboBox() (ThumbnailCtrl method)
OnCompareItems() (CustomTreeCtrl method)
(HyperTreeList method)
(UltimateListMainWindow method)
OnCustomizeDlg() (FlatMenuBar method)
OnCustomRender() (AuiToolBar method)
OnData() (FNBDropTarget method)
OnDestroy() (BalloonTip method)
(CustomTreeCtrl method)
(FloatSpin method)
(FloatTextCtrl method)
(PyProgress method)
(SuperToolTip method)
(ToolTipWindowBase method)
OnDismiss() (FlatMenuBase method)
OnDrawGTKExpander() (GTKExpander method)
(PyCollapsiblePane method)
OnDrawGTKStyle() (PyCollapsiblePane method)
OnDrawGTKText() (GTKExpander method)
(PyCollapsiblePane method)
OnDropTarget() (FlatNotebook method)
(PageContainer method)
OnEditTimer() (CustomTreeCtrl method)
(TreeListMainWindow method)
OnEndTimer() (SuperToolTip method)
OnEnterButton() (BalloonFrame method)
OnEnterWindow() (FourWaySplitter method)
(UltimateListHeaderWindow method)
OnErase() (PyInfoFrame method)
OnEraseBackground() (AuiCenterDockingGuide method)
(AuiDockingGuideWindow method)
(AuiManager method)
(AuiTabCtrl method)
(AuiToolBar method)
(BaseLineCtrl method)
(BasePyControl method)
(ButtonPanel method)
(ColourPanel method)
(CustomPanel method)
(CustomTreeCtrl method)
(FMTitlePanel method)
(FlatMenu method)
(FlatMenuBar method)
(ImageContainer method)
(ImageContainerBase method)
(LabelContainer method)
(MultiColumnListCtrl method)
(PageContainer method)
(PeakMeterCtrl method)
(ProgressGauge method)
(PyGauge method)
(RibbonBar method)
(RibbonButtonBar method)
(RibbonGallery method)
(RibbonPage method)
(RibbonPageScrollButton method)
(RibbonPanel method)
(RibbonToolBar method)
(RulerCtrl method)
(ToolTipWindowBase method)
(TreeListMainWindow method)
(UltimateListMainWindow method)
(ZoomBar method)
OnExpandCollapse() (ListShortcut method)
OnFindManager() (AuiFloatingFrame method)
(AuiManager method)
OnFloatingPaneActivated() (AuiManager method)
OnFloatingPaneClosed() (AuiManager method)
OnFloatingPaneMoved() (AuiManager method)
OnFloatingPaneResized() (AuiManager method)
OnFlyTimer() (AuiFloatingFrame method)
OnFocus() (FloatSpin method)
OnGainFocus() (AquaButton method)
(GradientButton method)
(SButton method)
OnGetItemAttr() (UltimateListCtrl method)
OnGetItemCheck() (UltimateListCtrl method)
OnGetItemColumnCheck() (UltimateListCtrl method)
OnGetItemColumnImage() (UltimateListCtrl method)
OnGetItemColumnKind() (UltimateListCtrl method)
OnGetItemImage() (UltimateListCtrl method)
OnGetItemKind() (UltimateListCtrl method)
OnGetItemText() (HyperTreeList method)
(UltimateListCtrl method)
OnGetItemTextColour() (UltimateListCtrl method)
OnGetItemToolTip() (UltimateListCtrl method)
OnGetToolTip() (CustomTreeCtrl method)
OnGripperClicked() (AuiManager method)
OnHelp() (GenericMessageDialog method)
OnHintFadeTimer() (AuiManager method)
OnHoverTimer() (UltimateListMainWindow method)
OnHTMLHelp() (ShortcutEditor method)
OnHTMLToolbar() (HTMLHelpWindow method)
OnIdle() (AuiFloatingFrame method)
(AuiToolBar method)
(FlatMenuBar method)
OnInternalIdle() (CustomTreeCtrl method)
(UltimateListCtrl method)
(UltimateListHeaderWindow method)
OnItemDelete() (SelectionStore method)
OnItemSelected() (TabNavigatorWindow method), [1]
OnKey() (MultiColumnListCtrl method)
OnKeyDown() (__SToggleMixin method)
(AquaButton method)
(AuiTabCtrl method)
(CustomTreeCtrl method)
(FlatMenu method)
(FocusHandler method)
(GenericMessageDialog method)
(GradientButton method)
(PageContainer method)
(SButton method)
(UltimateListMainWindow method)
(__ToggleMixin method)
OnKeyDown2() (AuiTabCtrl method)
OnKeyUp() (__SToggleMixin method)
(AquaButton method)
(CubeColourDialog method)
(EditTextCtrl method)
(GradientButton method)
(MultiDirDialog method)
(SButton method)
(TabNavigatorWindow method), [1]
(TabTextCtrl method)
(TreeTextCtrl method)
(UltimateListMainWindow method)
(UltimateListTextCtrl method)
(__ToggleMixin method)
OnKillFocus() (AuiTabCtrl method)
(CustomTreeCtrl method)
(EditCtrl method)
(FlatMenu method)
(FloatSpin method)
(FloatTextCtrl method)
(FocusHandler method)
(ListShortcut method)
(PageContainer method)
(RibbonPanel method)
(TabTextCtrl method)
(TreeTextCtrl method)
(UltimateListMainWindow method)
(UltimateListTextCtrl method)
OnLeaveButton() (BalloonFrame method)
OnLeaveMenuBar() (FlatMenuBar method)
OnLeaveWindow() (AuiManager method)
(AuiTabCtrl method)
(AuiToolBar method)
(FlatMenuBar method)
(FourWaySplitter method)
(UltimateListHeaderWindow method)
(ZoomBar method)
(mcPopupWindow method)
OnLeftDClick() (AuiManager method)
(AuiTabCtrl method)
(PageContainer method)
OnLeftDown() (__SToggleMixin method)
(AquaButton method)
(AuiManager method)
(AuiTabCtrl method)
(AuiToolBar method)
(BaseLineCtrl method)
(BasePyControl method)
(ButtonPanel method)
(CustomPanel method)
(FlatMenuBar method)
(FourWaySplitter method)
(GradientButton method)
(HSVWheel method)
(ListShortcut method)
(PageContainer method)
(RGBCube method)
(SButton method)
(ZoomBar method)
(__ToggleMixin method)
OnLeftUp() (__SToggleMixin method)
(AquaButton method)
(AuiManager method)
(AuiTabCtrl method)
(AuiToolBar method)
(BaseLineCtrl method)
(BasePyControl method)
(ButtonPanel method)
(FlatMenuBar method)
(FourWaySplitter method)
(GradientButton method)
(HSVWheel method)
(PageContainer method)
(RGBCube method)
(SButton method)
(ZoomBar method)
(__ToggleMixin method)
OnLeftUp_ClickButton() (AuiManager method)
OnLeftUp_DragFloatingPane() (AuiManager method)
OnLeftUp_DragToolbarPane() (AuiManager method)
OnLeftUp_Resize() (AuiManager method)
OnLoseFocus() (AquaButton method)
(GradientButton method)
(SButton method)
OnMenuChecked() (FMCustomizeDlg method)
OnMenuDismissed() (FlatMenuBar method)
OnMiddleDown() (AuiTabCtrl method)
(AuiToolBar method)
(PageContainer method)
OnMiddleUp() (AuiTabCtrl method)
(AuiToolBar method)
OnMotion() (__SToggleMixin method)
(AuiManager method)
(AuiTabCtrl method)
(AuiToolBar method)
(BaseLineCtrl method)
(BasePyControl method)
(FourWaySplitter method)
(HSVWheel method)
(RGBCube method)
(SButton method)
(ZoomBar method)
(__ToggleMixin method)
OnMotion_ClickCaption() (AuiManager method)
OnMotion_DragFloatingPane() (AuiManager method)
OnMotion_DragToolbarPane() (AuiManager method)
OnMotion_Other() (AuiManager method)
OnMotion_Resize() (AuiManager method)
OnMouse() (CustomTreeCtrl method)
(TreeListHeaderWindow method)
(TreeListMainWindow method)
(UltimateListHeaderWindow method)
(UltimateListMainWindow method)
OnMouseClick() (RibbonPanel method)
OnMouseDClick() (RibbonGallery method)
(ScrolledThumbnail method)
OnMouseDoubleClick() (RibbonBar method)
OnMouseDown() (RibbonButtonBar method)
(RibbonGallery method)
(RibbonPageScrollButton method)
(RibbonToolBar method)
(ScrolledThumbnail method)
(ToasterBoxWindow method)
OnMouseEnter() (AquaButton method)
(GradientButton method)
(RibbonButtonBar method)
(RibbonGallery method)
(RibbonPageScrollButton method)
(RibbonPanel method)
(RibbonToolBar method)
OnMouseEnterChild() (RibbonPanel method)
OnMouseEnterWindow() (ButtonPanel method)
(FlatMenu method)
(PageContainer method)
OnMouseEvent() (CaptionBar method)
(Control method)
(HyperLinkCtrl method)
(MultiColumnListCtrl method)
OnMouseEvents() (AdvancedSplash method)
(KnobCtrl method)
(RulerCtrl method)
OnMouseLeave() (AquaButton method)
(ButtonPanel method)
(GradientButton method)
(PageContainer method)
(RibbonBar method)
(RibbonButtonBar method)
(RibbonGallery method)
(RibbonPageScrollButton method)
(RibbonPanel method)
(RibbonToolBar method)
(ScrolledThumbnail method)
OnMouseLeaveChild() (RibbonPanel method)
OnMouseLeaveWindow() (FlatMenu method)
(ImageContainer method)
(ImageContainerBase method)
(LabelContainer method)
OnMouseLeftDown() (FlatMenu method)
(ImageContainer method)
(ImageContainerBase method)
(LabelContainer method)
(RibbonBar method)
OnMouseLeftUp() (FlatMenu method)
(ImageContainer method)
(ImageContainerBase method)
(LabelContainer method)
(RibbonBar method)
OnMouseMiddleDown() (RibbonBar method)
OnMouseMiddleUp() (RibbonBar method)
OnMouseMotion() (SpeedMeter method)
(ToolTipWindowBase method)
OnMouseMove() (ButtonPanel method)
(FlatMenu method)
(FlatMenuBar method)
(ImageContainer method)
(ImageContainerBase method)
(LabelContainer method)
(PageContainer method)
(RibbonBar method)
(RibbonButtonBar method)
(RibbonGallery method)
(RibbonToolBar method)
(ScrolledThumbnail method)
OnMouseRightDown() (FlatMenu method)
(RibbonBar method)
OnMouseRightUp() (RibbonBar method)
OnMouseUp() (RibbonButtonBar method)
(RibbonGallery method)
(RibbonPageScrollButton method)
(RibbonToolBar method)
(ScrolledThumbnail method)
OnMouseWheel() (FloatSpin method)
(PageContainer method)
(ScrolledThumbnail method)
OnMove() (AuiFloatingFrame method)
(AuiManager method)
OnMoveEvent() (AuiFloatingFrame method)
OnMoveFinished() (AuiFloatingFrame method)
OnMoveStart() (AuiFloatingFrame method)
OnMoveTimer() (ToasterBox method)
OnMoving() (AuiFloatingFrame method)
OnNavigation() (GenericMessageDialog method)
OnNavigationKey() (FlatBookBase method)
(FlatNotebook method)
(TabNavigatorWindow method), [1]
OnNavigationKeyNotebook() (AuiNotebook method)
OnNo() (GenericMessageDialog method)
OnNotify() (AdvancedSplash method)
OnOk() (CubeColourDialog method)
(GenericMessageDialog method)
(MultiDirDialog method)
OnPaint() (__ToggleMixin method)
(AdvancedSplash method)
(AlphaCtrl method)
(AquaButton method)
(AuiCenterDockingGuide method)
(AuiDockingGuideWindow method)
(AuiManager method)
(AuiTabCtrl method)
(AuiToolBar method)
(BasePyControl method)
(BrightCtrl method)
(BufferedWindow method), [1]
(ButtonPanel method)
(CaptionBar method)
(ColourPanel method)
(CustomPanel method)
(CustomTreeCtrl method)
(FMTitlePanel method)
(FlatMenu method)
(FlatMenuBar method)
(FoldPanelItem method)
(FourWaySplitter method)
(GradientButton method)
(ImageContainer method)
(LabelContainer method)
(MultiColumnListCtrl method)
(PageContainer method)
(PeakMeterCtrl method)
(PieCtrl method)
(PieCtrlLegend method)
(ProgressGauge method)
(PyGauge method)
(PyInfoFrame method)
(RibbonBar method)
(RibbonButtonBar method)
(RibbonGallery method)
(RibbonPage method)
(RibbonPageScrollButton method)
(RibbonPanel method)
(RibbonToolBar method)
(RulerCtrl method)
(SButton method)
(ScrolledThumbnail method)
(SwitcherDialog method)
(ToasterBoxWindow method)
(ToolTipWindowBase method)
(TreeListHeaderWindow method)
(TreeListMainWindow method)
(UltimateListHeaderWindow method)
(UltimateListMainWindow method)
(ZoomBar method)
OnPaneButton() (AuiManager method)
OnPaneDocked() (AuiManager method)
OnPanelEraseBg() (TabNavigatorWindow method), [1]
OnPanelPaint() (TabNavigatorWindow method), [1]
OnPopUpCopy() (HyperLinkCtrl method)
OnPressCaption() (FoldPanelBar method)
(FoldPanelItem method)
OnPulseTimer() (AquaButton method)
OnRenameAccept() (AuiNotebook method)
(UltimateListMainWindow method)
OnRenameCancelled() (AuiNotebook method)
(UltimateListMainWindow method)
OnRenameTimer() (UltimateListMainWindow method)
OnRender() (AuiManager method)
OnResize() (ScrolledThumbnail method)
OnRestoreDefaults() (ShortcutEditor method)
OnRestoreMinimizedPane() (AuiManager method)
OnRightDown() (AuiTabCtrl method)
(AuiToolBar method)
(PageContainer method)
OnRightUp() (AuiTabCtrl method)
(AuiToolBar method)
OnScroll() (TreeListMainWindow method)
(UltimateListMainWindow method)
OnScrollTimer() (ToasterBoxWindow method)
OnSelChanged() (ListShortcut method)
(MultiDirDialog method)
OnSelectItem() (SwitcherDialog method)
OnSetCursor() (AuiManager method)
(AuiToolBar method)
OnSetFilter() (ShortcutEditor method)
OnSetFocus() (AuiTabCtrl method)
(CustomTreeCtrl method)
(GenericTreeItem method)
(PageContainer method)
(TreeListHeaderWindow method)
(TreeListItem method)
(UltimateListCtrl method)
(UltimateListHeaderWindow method)
(UltimateListItem method)
(UltimateListMainWindow method)
OnShortcut() (ListShortcut method)
OnShowAlpha() (CubeColourDialog method)
OnSize() (AquaButton method)
(AuiDockingHintWindow method)
(AuiFloatingFrame method)
(AuiManager method)
(AuiNotebook method)
(AuiTabCtrl method)
(AuiToolBar method)
(BaseLineCtrl method)
(BasePyControl method)
(BufferedWindow method), [1]
(ButtonPanel method)
(CaptionBar method)
(ColourPanel method)
(CustomPanel method)
(CustomTreeCtrl method)
(FlatMenuBar method)
(FloatSpin method)
(FourWaySplitter method)
(GTKExpander method)
(GradientButton method)
(HyperTreeList method)
(ImageContainer method)
(ImageContainerBase method)
(LabelBook method)
(LabelContainer method)
(PageContainer method)
(PeakMeterCtrl method)
(PieCtrl method)
(PyCollapsiblePane method)
(RibbonBar method)
(RibbonButtonBar method)
(RibbonGallery method)
(RibbonPage method)
(RibbonPanel method)
(RibbonToolBar method)
(RulerCtrl method)
(SButton method)
(ToolTipWindowBase method)
(UltimateListCtrl method)
(ZoomBar method)
OnSizePanel() (FoldPanelBar method)
OnSpinCtrl() (CubeColourDialog method)
OnSpinDown() (FloatSpin method)
OnSpinMouseDown() (FloatSpin method)
OnSpinUp() (FloatSpin method)
OnStartTimer() (SuperToolTip method)
OnStateChange() (PyCollapsiblePane method)
OnStatusBarTimer() (ButtonPanel method)
(FlatMenuBar method)
OnSysColourChange() (ArtManager method)
OnSysColourChanged() (AuiManager method)
OnTabBeginDrag() (AuiManager method)
(AuiNotebook method)
OnTabBgDClick() (AuiNotebook method)
OnTabButton() (AuiNotebook method)
OnTabCancelDrag() (AuiNotebook method)
OnTabClicked() (AuiNotebook method)
OnTabDClick() (AuiNotebook method)
OnTabDragMotion() (AuiNotebook method)
OnTabEndDrag() (AuiNotebook method)
OnTabMenuSelection() (PageContainer method)
OnTabMiddleDown() (AuiNotebook method)
OnTabMiddleUp() (AuiNotebook method)
OnTabPageClose() (AuiManager method)
OnTabRightDown() (AuiNotebook method)
OnTabRightUp() (AuiNotebook method)
OnTabSelected() (AuiManager method)
OnTaskBarMove() (BalloonTip method)
OnTextEnter() (FloatSpin method)
OnThumbChanged() (ScrolledThumbnail method)
OnTimer() (FlatMenu method)
(PeakMeterCtrl method)
(PyGauge method)
OnUpdateUI() (HTMLHelpWindow method)
OnWidgetEnter() (BalloonTip method)
(SuperToolTip method)
OnWidgetLeave() (BalloonTip method)
(SuperToolTip method)
OnWidgetMotion() (BalloonTip method)
OnYes() (GenericMessageDialog method)
OpenInSameWindow() (HyperLinkCtrl method)
OpenItemContextMenu() (FlatMenu method)
opj() (in module shapedbutton)
(in module thumbnailctrl)
optionActive (AuiPaneInfo attribute)
optionBottomDockable (AuiPaneInfo attribute)
optionBottomSnapped (AuiPaneInfo attribute)
optionCaption (AuiPaneInfo attribute)
optionCaptionLeft (AuiPaneInfo attribute)
optionDestroyOnClose (AuiPaneInfo attribute)
optionDockFixed (AuiPaneInfo attribute)
optionFloatable (AuiPaneInfo attribute)
optionFloating (AuiPaneInfo attribute)
optionFlyOut (AuiPaneInfo attribute)
optionGripper (AuiPaneInfo attribute)
optionGripperTop (AuiPaneInfo attribute)
optionHidden (AuiPaneInfo attribute)
optionLeftDockable (AuiPaneInfo attribute)
optionLeftSnapped (AuiPaneInfo attribute)
optionMaximized (AuiPaneInfo attribute)
optionMinimized (AuiPaneInfo attribute)
optionMovable (AuiPaneInfo attribute)
optionNotebookDockable (AuiPaneInfo attribute)
optionPaneBorder (AuiPaneInfo attribute)
optionResizable (AuiPaneInfo attribute)
optionRightDockable (AuiPaneInfo attribute)
optionRightSnapped (AuiPaneInfo attribute)
optionToolbar (AuiPaneInfo attribute)
optionTopDockable (AuiPaneInfo attribute)
optionTopSnapped (AuiPaneInfo attribute)
OrderPageTabInfoBySmallWidthAsc() (RibbonBar method)

Navigation

  • index
  • modules |
  • Home |
  • Gallery |
  • Index


Index

  • modules |
  • Home |
  • Gallery |
  • Contents»
  • Index

Index – P

Page (CommandNotebookEvent attribute)
(FlatBookBase attribute)
PageContainer (class in flatnotebook)
PageCount (FlatBookBase attribute)
PageImage (FlatBookBase attribute)
PageInfo (class in flatnotebook)
PageText (FlatBookBase attribute)
PaintCrescentGradientBox() (ArtManager method)
PaintCustomColour() (CustomPanel method)
PaintCustomColours() (CustomPanel method)
PaintDiagonalGradientBox() (ArtManager method)
PaintGradientRegion() (ArtManager method)
PaintHighlight() (CustomPanel method)
PaintItem() (CustomTreeCtrl method)
(TreeListMainWindow method)
PaintItems() (SwitcherItems method)
PaintLevel() (CustomTreeCtrl method)
(TreeListMainWindow method)
PaintStraightGradientBox() (ArtManager method)
(in module flatnotebook)
PaintWaterMark() (UltimateListMainWindow method)
PaneBorder() (AuiPaneInfo method)
PaneCreateStippleBitmap() (in module aui.aui_utilities)
PaneFromTabEvent() (AuiManager method)
PaneHitTest() (AuiManager method)
PaneSortFunc() (in module aui.framemanager)
peakmeter (module)
PeakMeterCtrl (class in peakmeter)
PeakMeterData (class in peakmeter)
persist (module)
persist.persist_handlers (module)
persist.persistencemanager (module)
PersistenceManager (class in persist.persistencemanager)
PersistentObject (class in persist.persistencemanager)
PieCtrl (class in piectrl)
piectrl (module)
PieCtrlLegend (class in piectrl)
PiePart (class in piectrl)
PILImageHandler (class in thumbnailctrl)
PinButton() (AuiPaneInfo method)
Play() (ToasterBox method)
(ToasterBoxWindow method)
PointOnLine() (in module cubecolourdialog)
PointOnSash() (ImageContainerBase method)
Populate() (ListShortcut method)
PopulateGrid() (XLSGrid method)
PopulateListControl() (TabNavigatorWindow method), [1]
Popup() (FlatMenu method)
(FlatMenuBase method)
PopupMenu() (RibbonButtonBarEvent method)
(RibbonToolBarEvent method)
(UltimateListCtrl method)
PopupMoreMenu() (FlatMenuBar method)
PopupTabsMenu() (PageContainer method)
Position() (AuiPaneInfo method)
PositionAUI() (FlatMenuBar method)
Prepend() (BoxSizer method)
(FlatMenu method)
PrependItem() (CustomTreeCtrl method)
(FlatMenu method)
(HyperTreeList method)
PrependSeparator() (CustomTreeCtrl method)
PreShow() (ShortcutEditor method)
ProcessDockResult() (AuiManager method)
ProcessEvent() (AuiCommandCapture method)
(MenuKbdRedirector method)
(ToolbarCommandCapture method)
ProcessLeftDown() (FlatMenuButton method)
ProcessLeftUp() (FlatMenuButton method)
ProcessMgrEvent() (AuiManager method)
ProcessMouseLClick() (FlatMenu method)
ProcessMouseLClickEnd() (FlatMenu method)
ProcessMouseMove() (FlatMenu method)
(FlatMenuButton method)
ProcessMouseMoveFromMenu() (FlatMenuBar method)
ProcessMouseRClick() (FlatMenu method)
ProgressGauge (class in pyprogress)
ProgressPie (class in piectrl)
PtFromAngle() (in module cubecolourdialog)
PyBusyInfo (class in pybusyinfo)
pybusyinfo (module)
PyCollapsiblePane (class in pycollapsiblepane)
pycollapsiblepane (module)
PyDate2wxDate() (in module persist.persist_handlers)
PyGauge (class in pygauge)
pygauge (module)
PyImageList (class in ultimatelistctrl)
PyInfoFrame (class in pybusyinfo)
PyProgress (class in pyprogress)
pyprogress (module)

Navigation

  • index
  • modules |
  • Home |
  • Gallery |
  • Index


Index

  • modules |
  • Home |
  • Gallery |
  • Contents»
  • Index

Index – R

rad2deg() (in module cubecolourdialog)
RadioBoxHandler (class in persist.persist_handlers)
RadioButtonHandler (class in persist.persist_handlers)
RandomColour() (ArtManager method)
(in module flatnotebook)
ReadExcelCOM() (in module xlsgrid)
Realise() (RibbonControl method)
Realize() (AuiToolBar method)
(RibbonBar method)
(RibbonButtonBar method)
(RibbonControl method)
(RibbonGallery method)
(RibbonPage method)
(RibbonPanel method)
(RibbonToolBar method)
(StdDialogButtonSizer method)
ReallyDrawTabSeparator() (RibbonMSWArtProvider method)
RecalculateMinSize() (RibbonBar method)
RecalculatePositions() (UltimateListMainWindow method)
RecalculateTabSizes() (RibbonBar method)
RecreateBackground() (PieCtrlLegend method)
RecreateCanvas() (PieCtrl method)
RecreateComboBox() (ThumbnailCtrl method)
ReCreateSizer() (ButtonPanel method)
RecreateTree() (ListShortcut method)
Rect (ButtonInfo attribute)
RecurseOnChildren() (CustomTreeCtrl method)
RecurseTopDir() (MultiDirDialog method)
RedisplayFoldPanelItems() (FoldPanelBar method)
ReDockPage() (AuiNotebook method)
RedrawIconBitmap() (CaptionBar method)
ReenableOtherWindows() (PyProgress method)
Refresh() (HyperTreeList method)
(UltimateListCtrl method)
RefreshAfter() (UltimateListMainWindow method)
RefreshAll() (UltimateListMainWindow method)
RefreshButton() (AuiManager method)
RefreshCaptions() (AuiManager method)
RefreshChilds() (FlatMenu method)
RefreshColLabel() (TreeListHeaderWindow method)
RefreshColour() (ColourPanel method)
RefreshDockingGuides() (in module aui.framemanager)
RefreshItem() (UltimateListCtrl method)
RefreshItems() (UltimateListCtrl method)
RefreshItemWithWindows() (CustomTreeCtrl method)
RefreshLine() (CustomTreeCtrl method)
(UltimateListMainWindow method)
RefreshLines() (UltimateListMainWindow method)
RefreshOverflowState() (AuiToolBar method)
RefreshPanelsFrom() (FoldPanelBar method)
RefreshSelected() (CustomTreeCtrl method)
(UltimateListMainWindow method)
RefreshSelectedUnder() (CustomTreeCtrl method)
RefreshSubtree() (CustomTreeCtrl method)
RefreshTabBar() (RibbonBar method)
Register() (PersistenceManager method)
RegisterAndRestore() (PersistenceManager method)
RegisterAndRestoreAll() (PersistenceManager method)
Reload() (RibbonMSWArtProvider method)
Remove() (BoxSizer method)
(FlatMenu method)
(FlatMenuBar method)
(FlatMenuItemGroup method)
(PyImageList method)
RemoveAll() (PyImageList method)
RemoveAllButtons() (ButtonPanel method)
RemoveAllSeparators() (ButtonPanel method)
RemoveAutoNBCaption() (AuiManager method)
RemoveButton() (AuiTabContainer method)
(InfoBar method)
RemoveChild() (RibbonPage method)
(RibbonPanel method)
RemoveColumn() (HyperTreeList method)
(TreeListHeaderWindow method)
RemoveControlFromPage() (AuiNotebook method)
RemoveEmptyTabFrames() (AuiNotebook method)
RemoveFileFromHistory() (FileHistory method)
RemoveHelp() (ButtonPanel method)
(FlatMenuBar method)
RemoveItemAt() (ScrolledThumbnail method)
RemoveMenu() (FileHistory method)
RemovePage() (AuiNotebook method)
(AuiTabContainer method)
(FlatBookBase method)
(FlatNotebook method)
RemovePaneFromDocks() (in module aui.framemanager)
RemovePanelPadding() (RibbonMSWArtProvider method)
RemoveTabAreaButton() (AuiNotebook method)
RemoveText() (ButtonPanel method)
Render() (AuiManager method)
(AuiTabContainer method)
RendererBase (class in artmanager)
RendererMSOffice2007 (class in artmanager)
RendererXP (class in artmanager)
RenumberDockRows() (in module aui.framemanager)
Repaint() (AuiManager method)
RepaintOldSelection() (ButtonPanel method)
ReparentControl() (AuiNotebook method)
Replace() (PyImageList method)
ReplaceDoubleZero() (FloatSpin method)
ReplaceIcon() (PyImageList method)
ReplaceWindow() (FourWaySplitter method)
ReportErrors() (HyperLinkCtrl method)
Reposition() (FoldPanelItem method)
(ZoomBar method)
RepositionCollapsedToBottom() (FoldPanelBar method)
RepositionPage() (RibbonBar method)
RepositionPane() (AuiManager method)
RequestUserAttention() (AuiDefaultDockArt method)
(AuiManager method)
(ModernDockArt method)
RescaleScreenShot() (in module aui.aui_utilities)
ResetButtons() (AuiPaneInfo method)
ResetControl() (PeakMeterCtrl method)
ResetCurrent() (UltimateListMainWindow method)
ResetDefaults() (CaptionBarStyle method)
ResetDimensions() (UltimateListLineData method)
ResetEditControl() (CustomTreeCtrl method)
ResetLineDimensions() (UltimateListMainWindow method)
ResetSize() (ZoomBar method)
ResetTextControl() (AuiNotebook method)
(UltimateListMainWindow method)
ResetToolbarItems() (FlatMenuBar method)
ResetVisibility() (Shortcut method)
ResetVisibleLinesRange() (UltimateListMainWindow method)
Resizable() (AuiPaneInfo method)
Resize() (LabelContainer method)
ResizeColumns() (UltimateListMainWindow method)
ResizeItem() (FoldWindowItem method)
ResizeMenu() (FlatMenu method)
ResizePanel() (FoldPanelItem method)
ResizeTabArea() (FlatBookBase method)
Restore() (AbstractHandler method)
(AuiPaneInfo method)
(PersistenceManager method)
(PersistentObject method)
RestoreCtrlValue() (PersistenceManager method)
(PersistentObject method)
RestoreDefaults() (Shortcut method)
RestoreMaximizedPane() (AuiManager method)
RestoreMinimizedPane() (AuiManager method)
RestoreOldDC() (in module cubecolourdialog)
RestorePane() (AuiManager method)
RestoreValue() (PersistenceManager method)
(PersistentObject method)
RestrictResize() (AuiManager method)
ReverseHighlight() (UltimateListLineData method)
(UltimateListMainWindow method)
rgb2html() (in module cubecolourdialog)
RGBCube (class in cubecolourdialog)
ribbon (module)
ribbon.art_aui (module)
ribbon.art_internal (module)
ribbon.art_msw (module)
ribbon.bar (module)
ribbon.buttonbar (module)
ribbon.control (module)
ribbon.gallery (module)
ribbon.page (module)
ribbon.panel (module)
ribbon.toolbar (module)
RibbonAUIArtProvider (class in ribbon.art_aui)
RibbonBar (class in ribbon.bar)
RibbonBarEvent (class in ribbon.bar)
RibbonButtonBar (class in ribbon.buttonbar)
RibbonButtonBarButtonBase (class in ribbon.buttonbar)
RibbonButtonBarButtonInstance (class in ribbon.buttonbar)
RibbonButtonBarButtonSizeInfo (class in ribbon.buttonbar)
RibbonButtonBarEvent (class in ribbon.buttonbar)
RibbonButtonBarLayout (class in ribbon.buttonbar)
RibbonCanLabelBreakAtPosition() (in module ribbon.art_internal)
RibbonControl (class in ribbon.control)
RibbonDrawParallelGradientLines() (in module ribbon.art_internal)
RibbonGallery (class in ribbon.gallery)
RibbonGalleryEvent (class in ribbon.gallery)
RibbonGalleryItem (class in ribbon.gallery)
RibbonHSLColour (class in ribbon.art_internal)
RibbonInterpolateColour() (in module ribbon.art_internal)
RibbonLoadPixmap() (in module ribbon.art_internal)
RibbonMSWArtProvider (class in ribbon.art_msw)
RibbonPage (class in ribbon.page)
RibbonPageScrollButton (class in ribbon.page)
RibbonPageTabInfo (class in ribbon.art_internal)
RibbonPanel (class in ribbon.panel)
RibbonShiftLuminance() (in module ribbon.art_internal)
RibbonToolBar (class in ribbon.toolbar)
RibbonToolBarEvent (class in ribbon.toolbar)
RibbonToolBarToolBase (class in ribbon.toolbar)
RibbonToolBarToolGroup (class in ribbon.toolbar)
Right() (AuiDockingGuideInfo method)
(AuiPaneInfo method)
RightDockable() (AuiPaneInfo method)
RightSnappable() (AuiPaneInfo method)
Rotate() (ScrolledThumbnail method)
RotateImage() (Indicator method)
RotateLeft() (PageContainer method)
RotateRight() (PageContainer method)
Row() (AuiPaneInfo method)
RulerCtrl (class in rulerctrl)
rulerctrl (module)
RulerCtrlEvent (class in rulerctrl)

Navigation

  • index
  • modules |
  • Home |
  • Gallery |
  • Index


Index

  • modules |
  • Home |
  • Gallery |
  • Contents»
  • Index

Index – S

Saturated() (RibbonHSLColour method)
Save() (AbstractHandler method)
(FileHistory method)
(PersistenceManager method)
(PersistentObject method)
SaveAndUnregister() (PersistenceManager method)
SaveCtrlValue() (PersistenceManager method)
(PersistentObject method)
savedHiddenState (AuiPaneInfo attribute)
SavePaneInfo() (AuiManager method)
SavePerspective() (AuiManager method)
(AuiNotebook method)
SavePreviousDockSizes() (AuiManager method)
SaveValue() (PersistenceManager method)
(PersistentObject method)
SBitmapButton (class in shapedbutton)
SBitmapTextButton (class in shapedbutton)
SBitmapTextToggleButton (class in shapedbutton)
SBitmapToggleButton (class in shapedbutton)
SButton (class in shapedbutton)
SButtonEvent (class in shapedbutton)
scaletomax() (in module cubecolourdialog)
ScreenToClient() (UltimateListCtrl method)
ScreenToClientXY() (UltimateListCtrl method)
ScrollDown() (FlatMenu method)
(FlatMenuBase method)
(ToasterBoxWindow method)
ScrolledThumbnail (class in thumbnailctrl)
ScrolledWindowHandler (class in persist.persist_handlers)
ScrollLines() (RibbonGallery method)
(RibbonPage method)
ScrollList() (UltimateListCtrl method)
(UltimateListMainWindow method)
ScrollPixels() (RibbonPage method)
ScrollTabBar() (RibbonBar method)
ScrollTo() (CustomTreeCtrl method)
(HyperTreeList method)
(TreeListMainWindow method)
ScrollToSelected() (ScrolledThumbnail method)
ScrollUp() (FlatMenu method)
(FlatMenuBase method)
(ToasterBoxWindow method)
SecondColourUsed() (CaptionBarStyle method)
Select() (FlatToolbarItem method)
(UltimateListCtrl method)
SelectAll() (CustomTreeCtrl method)
(HyperTreeList method)
SelectAllChildren() (CustomTreeCtrl method)
(HyperTreeList method)
Selection (CommandNotebookEvent attribute)
(FlatBookBase attribute)
SelectionStore (class in ultimatelistctrl)
SelectItem() (CustomTreeCtrl method)
(HyperTreeList method)
(SelectionStore method)
SelectItemRange() (CustomTreeCtrl method)
SelectRange() (SelectionStore method)
SendCmdEvent() (FlatMenu method)
SendDeleteEvent() (CustomTreeCtrl method)
SendListEvent() (TreeListHeaderWindow method)
(UltimateListHeaderWindow method)
SendNotify() (UltimateListMainWindow method)
SendOverItem() (FlatMenu method)
SendUIEvent() (FlatMenu method)
Separator (class in buttonpanel)
Set3State() (GenericTreeItem method)
Set3StateValue() (GenericTreeItem method)
SET_FLAG() (in module ribbon.bar)
set_precision() (FixedPoint method)
SetAccelerator() (Shortcut method)
(ShortcutEvent method)
SetActive() (AuiToolBarItem method)
SetActivePage() (AuiTabContainer method)
(RibbonBar method)
SetActivePageByIndex() (RibbonBar method)
SetActivePageByPage() (RibbonBar method)
SetActivePane() (in module aui.framemanager)
SetActiveTabColour() (FlatNotebook method)
SetActiveTabTextColour() (FlatNotebook method)
SetAffirmativeButton() (StdDialogButtonSizer method)
SetAGWFlags() (AuiDefaultTabArt method)
(AuiDefaultToolBarArt method)
(AuiManager method)
(AuiSimpleTabArt method)
(AuiTabContainer method)
(ChromeTabArt method)
SetAGWWindowStyleFlag() (AuiNotebook method)
(AuiToolBar method)
(CubeColourDialog method)
(CustomTreeCtrl method)
(FlatBookBase method)
(FlatNotebook method)
(FourWaySplitter method)
(HyperTreeList method)
(PageContainer method)
(PeakMeterCtrl method)
(PyCollapsiblePane method)
(RibbonBar method)
(UltimateListCtrl method)
SetAlign() (UltimateListItem method)
SetAlignment() (AuiToolBarItem method)
(ButtonPanel method)
(TreeListColumnInfo method)
SetAllPagesShapeAngle() (FlatNotebook method)
SetAngle() (PieCtrl method)
SetAngleOfRotation() (SButton method)
SetAngleRange() (SpeedMeter method)
SetAngularRange() (KnobCtrl method)
SetAnimationStep() (AuiManager method)
SetArcColour() (SpeedMeter method)
SetArtProvider() (AuiManager method)
(AuiNotebook method)
(AuiTabContainer method)
(AuiToolBar method)
(RibbonBar method)
(RibbonButtonBar method)
(RibbonControl method)
(RibbonPage method)
(RibbonPanel method)
SetAttr() (UltimateListItemData method)
(UltimateListLineData method)
SetAttributes() (AuiManager method)
(GenericTreeItem method)
(UltimateListLineData method)
SetAuiManager() (AuiToolBar method)
SetAutoNotebookStyle() (AuiManager method)
SetAutoNotebookTabArt() (AuiManager method)
SetBackColour() (PieCtrl method)
(PieCtrlLegend method)
SetBackground() (PieCtrl method)
SetBackgroundBitmap() (FlatMenu method)
(LabelContainer method)
SetBackgroundColor() (AquaButton method)
SetBackgroundColour() (AquaButton method)
(CustomTreeCtrl method)
(FlatMenuBar method)
(HyperTreeList method)
(PeakMeterCtrl method)
(RulerCtrl method)
(SwitcherItems method)
(TreeItemAttr method)
(UltimateListCtrl method)
(UltimateListItem method)
(UltimateListItemAttr method)
(UltimateListItemData method)
SetBackgroundImage() (CustomTreeCtrl method)
(HyperTreeList method)
(UltimateListCtrl method)
(UltimateListMainWindow method)
SetBalloonColour() (BalloonTip method)
SetBalloonIcon() (BalloonTip method)
SetBalloonMessage() (BalloonTip method)
SetBalloonShape() (BalloonFrame method)
(BalloonTip method)
SetBalloonTipStyle() (BalloonTip method)
SetBalloonTitle() (BalloonTip method)
SetBandsColour() (PeakMeterCtrl method)
SetBar() (CaptionBarEvent method)
(RibbonButtonBarEvent method)
(RibbonToolBarEvent method)
SetBarColor() (PyGauge method)
SetBarColour() (ImageBar method)
(PyGauge method)
(ZoomBar method)
SetBarGradient() (PyGauge method)
SetBarHeight() (FlatMenuBar method)
SetBarText() (ButtonPanel method)
SetBaseColour() (AuiDefaultTabArt method)
SetBaseColours() (GradientButton method)
SetBaseId() (FileHistory method)
SetBestSize() (AquaButton method)
(GradientButton method)
(SButton method)
SetBitmap() (AuiToolBarItem method)
(ButtonInfo method)
(FlatToolbarItem method)
(RibbonGalleryItem method)
(Shortcut method)
(SwitcherItem method)
(Thumb method)
SetBitmapDisabled() (SBitmapButton method)
SetBitmapFocus() (SBitmapButton method)
SetBitmapLabel() (AquaButton method)
(SBitmapButton method)
SetBitmaps() (ChromeTabArt method)
SetBitmapSelected() (SBitmapButton method)
SetBlindMode() (AuiDockingHintWindow method)
SetBodyImage() (SuperToolTip method)
SetBold() (GenericTreeItem method)
(HyperLinkCtrl method)
SetBoldFont() (CaptionBar method)
SetBorderColor() (PyGauge method)
SetBorderColour() (PyGauge method)
(SwitcherDialog method)
SetBorderPadding() (PyGauge method)
SetBorderPen() (CustomTreeCtrl method)
(HyperTreeList method)
SetBottomEndColour() (GradientButton method)
SetBottomGradientColor() (SuperToolTip method)
SetBottomGradientColour() (SuperToolTip method)
SetBottomStartColour() (GradientButton method)
SetBoundingColour() (KnobCtrl method)
SetBounds() (RulerCtrl method)
SetBPArt() (ButtonPanel method)
SetBuffered() (HyperTreeList method)
(TreeListHeaderWindow method)
(TreeListMainWindow method)
SetBusyShape() (PyInfoFrame method)
SetButton() (AuiManagerEvent method)
(PyCollapsiblePane method)
SetButtonColour() (SButton method)
SetButtonFont() (PyCollapsiblePane method)
SetButtonObj() (AquaButtonEvent method)
(GradientButtonEvent method)
(SButtonEvent method)
SetButtonsImageList() (CustomTreeCtrl method)
(HyperTreeList method)
SetButtonSize() (ZoomBar method)
SetCancelButton() (StdDialogButtonSizer method)
SetCanVeto() (AuiManagerEvent method)
SetCaption() (ImageInfo method)
(PageInfo method)
(ScrolledThumbnail method)
(Thumb method)
SetCaptionColour() (CaptionBarStyle method)
SetCaptionFont() (CaptionBarStyle method)
(ScrolledThumbnail method)
SetCaptionStyle() (CaptionBar method)
(CaptionBarStyle method)
SetCellSize() (XLSCell method)
SetCenterZoom() (ZoomBar method)
(ZoomBarImage method)
SetCheckedState() (TreeCtrlHandler method)
SetCheckedStateOfChildren() (TreeCtrlHandler method)
SetCheckedStateOfItem() (TreeCtrlHandler method)
SetClickPoint() (CommandToolBarEvent method)
SetClientData() (RibbonGalleryItem method)
SetCloseButton() (AuiNotebook method)
SetCodes() (CubeColourDialog method)
SetColor() (AuiDefaultDockArt method)
(BPArt method)
SetColour() (AuiDefaultDockArt method)
(BPArt method)
(Indicator method)
(LabelBook method)
(LabelContainer method)
(PageInfo method)
(PiePart method)
(RibbonAUIArtProvider method)
(RibbonMSWArtProvider method)
(TreeListColumnInfo method)
(UltimateListItemData method)
(UltimateListLineData method)
SetColours() (HyperLinkCtrl method)
SetColourScheme() (RibbonAUIArtProvider method)
(RibbonMSWArtProvider method)
SetColPos() (SwitcherItem method)
SetColumn() (HyperTreeList method)
(TreeListHeaderWindow method)
(UltimateListCtrl method)
(UltimateListItem method)
(UltimateListMainWindow method)
SetColumnAlignment() (HyperTreeList method)
(TreeListHeaderWindow method)
SetColumnColour() (HyperTreeList method)
(TreeListHeaderWindow method)
SetColumnCount() (SwitcherItems method)
SetColumnCustomRenderer() (UltimateListCtrl method)
(UltimateListMainWindow method)
SetColumnEditable() (HyperTreeList method)
SetColumnFont() (HyperTreeList method)
SetColumnImage() (HyperTreeList method)
(UltimateListCtrl method)
SetColumnShown() (HyperTreeList method)
(UltimateListCtrl method)
SetColumnText() (HyperTreeList method)
(TreeListHeaderWindow method)
SetColumnToolTip() (UltimateListCtrl method)
SetColumnWidth() (HyperTreeList method)
(TreeListHeaderWindow method)
(UltimateListCtrl method)
(UltimateListMainWindow method)
SetColumnWidths() (ShortcutEditor method)
SetConfigurationHandler() (PersistenceManager method)
SetConnectionPen() (CustomTreeCtrl method)
(HyperTreeList method)
SetContextMenu() (FlatMenuItem method)
SetCursor() (UltimateListCtrl method)
SetCustomButton() (AuiDefaultTabArt method)
(AuiSimpleTabArt method)
SetCustomOverflowItems() (AuiToolBar method)
SetCustomPage() (FlatNotebook method)
SetCustomPaneBitmap() (AuiDefaultDockArt method)
SetCustomRenderer() (TreeListHeaderWindow method)
(UltimateListHeaderData method)
(UltimateListHeaderWindow method)
(UltimateListItem method)
(UltimateListItemData method)
SetData() (GenericTreeItem method)
(PeakMeterCtrl method)
(UltimateListItem method)
(UltimateListItemData method)
SetDC() (AuiManagerEvent method)
SetDefault() (AquaButton method)
(GradientButton method)
(SButton method)
SetDefaultColours() (AuiDefaultDockArt method)
(AuiDefaultTabArt method)
(AuiDefaultToolBarArt method)
SetDefaultPaneBitmaps() (AuiDefaultDockArt method)
SetDefaultValue() (FloatSpin method)
SetDescription() (SwitcherItem method)
SetDigits() (FloatSpin method)
SetDirection() (SpeedMeter method)
SetDisabledBitmap() (AuiToolBarItem method)
(FlatMenuItem method)
(FlatToolbarItem method)
SetDisabledColor() (AquaButton method)
SetDisabledColour() (AquaButton method)
(CustomTreeCtrl method)
(HyperTreeList method)
SetDisabledTextColour() (UltimateListCtrl method)
(UltimateListMainWindow method)
SetDispatched() (CommandNotebookEvent method)
SetDockPos() (AuiPaneInfo method)
SetDockSizeConstraint() (AuiManager method)
SetDragItem() (HyperTreeList method)
(TreeListMainWindow method)
SetDragSource() (CommandNotebookEvent method)
SetDrawFooterLine() (SuperToolTip method)
SetDrawHeaderLine() (SuperToolTip method)
SetDrawingParent() (RulerCtrl method)
SetDropDownClicked() (CommandToolBarEvent method)
SetDropShadow() (ScrolledThumbnail method)
(SuperToolTip method)
SetDropTarget() (UltimateListCtrl method)
SetEditable() (TreeListColumnInfo method)
SetEditCanceled() (CommandListEvent method)
(CommandNotebookEvent method)
(CommandTreeEvent method)
SetEffectDuration() (InfoBar method)
SetElementSize() (AuiDefaultToolBarArt method)
SetEllipseAxis() (SButton method)
SetEndDelay() (BalloonTip method)
(SuperToolTip method)
SetExpanded() (FourWaySplitter method)
SetExpanderDimensions() (PyCollapsiblePane method)
SetExpansionState() (TreeCtrlHandler method)
SetExpansionStateOfChildren() (TreeCtrlHandler method)
SetExpansionStateOfItem() (TreeCtrlHandler method)
SetExtendedMessage() (GenericMessageDialog method)
SetExtraNavigationKey() (MultiColumnListCtrl method)
(SwitcherDialog method)
SetFalloffDelay() (PeakMeterCtrl method)
SetFalloffEffect() (PeakMeterCtrl method)
SetFileName() (Thumb method)
SetFilledColour() (ProgressPie method)
SetFillerColour() (SpeedMeter method)
SetFilter() (ListShortcut method)
SetFirstColour() (CaptionBarStyle method)
SetFirstGradientColour() (CustomTreeCtrl method)
(HyperTreeList method)
(KnobCtrl method)
(ProgressGauge method)
(PyProgress method)
(SpeedMeter method)
(UltimateListCtrl method)
(UltimateListMainWindow method)
SetFlag() (AuiPaneInfo method)
SetFlags() (RibbonMSWArtProvider method)
SetFlip() (RulerCtrl method)
SetFocus() (Control method)
(HyperTreeList method)
(UltimateListCtrl method)
SetFocusedPage() (PageContainer method)
SetFont() (AuiDefaultDockArt method)
(AuiDefaultToolBarArt method)
(AuiNotebook method)
(AuiToolBar method)
(BPArt method)
(CustomTreeCtrl method)
(FlatMenuItem method)
(FloatSpin method)
(HyperTreeList method)
(InfoBar method)
(RibbonAUIArtProvider method)
(RibbonMSWArtProvider method)
(SwitcherItem method)
(ToolTipWindowBase method)
(TreeItemAttr method)
(TreeListColumnInfo method)
(UltimateListCtrl method)
(UltimateListHeaderData method)
(UltimateListItem method)
(UltimateListItemAttr method)
(UltimateListItemData method)
(UltimateListMainWindow method)
SetFontBold() (FlatBookBase method)
SetFonts() (RulerCtrl method)
SetFontSizeMultiple() (FlatBookBase method)
SetFooter() (SuperToolTip method)
SetFooterAlign() (UltimateListItem method)
SetFooterBackgroundColour() (UltimateListItem method)
(UltimateListItemAttr method)
SetFooterBitmap() (SuperToolTip method)
SetFooterCustomRenderer() (UltimateListCtrl method)
SetFooterFont() (SuperToolTip method)
(UltimateListHeaderData method)
(UltimateListItem method)
(UltimateListItemAttr method)
SetFooterFormat() (UltimateListHeaderData method)
(UltimateListItem method)
SetFooterHeight() (UltimateListCtrl method)
SetFooterImage() (UltimateListItem method)
SetFooterKind() (UltimateListHeaderData method)
(UltimateListItem method)
SetFooterText() (UltimateListItem method)
SetFooterTextColour() (UltimateListItem method)
(UltimateListItemAttr method)
SetForegroundColour() (AquaButton method)
(CustomTreeCtrl method)
(GradientButton method)
(HyperTreeList method)
(UltimateListCtrl method)
SetFormat() (FloatSpin method)
(RulerCtrl method)
(UltimateListHeaderData method)
SetFrame() (AuiManager method)
SetGallery() (RibbonGalleryEvent method)
SetGalleryItem() (RibbonGalleryEvent method)
SetGaugeBackground() (ProgressGauge method)
(PyProgress method)
SetGaugeProportion() (ProgressGauge method)
(PyProgress method)
SetGaugeSteps() (ProgressGauge method)
(PyProgress method)
SetGlobalPopupMenu() (ScrolledThumbnail method)
SetGradientColourBorder() (FlatNotebook method)
SetGradientColourFrom() (FlatNotebook method)
SetGradientColours() (FlatNotebook method)
SetGradientColourTo() (FlatNotebook method)
SetGradientStyle() (CustomTreeCtrl method)
(HyperTreeList method)
(UltimateListCtrl method)
(UltimateListMainWindow method)
SetGradientType() (BPArt method)
SetGripperVisible() (AuiToolBar method)
SetGroup() (FlatToolbarItem method)
SetGuideShape() (AuiCenterDockingGuide method)
(AuiSingleDockingGuide method)
SetHandColour() (SpeedMeter method)
SetHandStyle() (SpeedMeter method)
SetHasDropDown() (AuiToolBarItem method)
SetHasPlus() (GenericTreeItem method)
SetHeader() (SuperToolTip method)
SetHeaderBitmap() (SuperToolTip method)
SetHeaderCustomRenderer() (HyperTreeList method)
(UltimateListCtrl method)
SetHeaderFont() (HyperTreeList method)
(SuperToolTip method)
SetHeaderHeight() (UltimateListCtrl method)
SetHeight() (GenericTreeItem method)
(PieCtrl method)
(UltimateListHeaderData method)
(UltimateListLineData method)
SetHelp() (FlatMenuItem method)
SetHelpBitmap() (GenericMessageDialog method)
SetHelpLabel() (GenericMessageDialog method)
SetHighlightPointed() (ScrolledThumbnail method)
SetHilight() (GenericTreeItem method)
SetHilightFocusColour() (CustomTreeCtrl method)
(HyperTreeList method)
SetHilightNonFocusColour() (CustomTreeCtrl method)
(HyperTreeList method)
SetHorizontalBorder() (PieCtrlLegend method)
SetHotBitmap() (FlatMenuItem method)
SetHoverBitmap() (AuiToolBarItem method)
SetHoverColor() (AquaButton method)
SetHoverColour() (AquaButton method)
SetHoverItem() (AuiToolBar method)
SetHSplit() (FourWaySplitter method)
SetHTMLHelpFile() (ShortcutEditor method)
SetHyperlinkFont() (SuperToolTip method)
SetHyperText() (GenericTreeItem method)
(UltimateListItem method)
(UltimateListItemData method)
SetHyperTextFont() (CustomTreeCtrl method)
(HyperTreeList method)
(UltimateListCtrl method)
(UltimateListMainWindow method)
SetHyperTextNewColour() (CustomTreeCtrl method)
(HyperTreeList method)
(UltimateListCtrl method)
(UltimateListMainWindow method)
SetHyperTextVisitedColour() (CustomTreeCtrl method)
(HyperTreeList method)
(UltimateListCtrl method)
(UltimateListMainWindow method)
SetId() (AuiToolBarItem method)
(ButtonInfo method)
(RibbonGalleryItem method)
(SwitcherItem method)
(Thumb method)
(UltimateListItem method)
SetImage() (GenericTreeItem method)
(Thumb method)
(TreeListColumnInfo method)
(TreeListItem method)
(UltimateListItem method)
(UltimateListItemData method)
(UltimateListLineData method)
SetImageIndex() (ImageInfo method)
(PageInfo method)
SetImageList() (AuiNotebook method)
(CustomTreeCtrl method)
(FlatNotebook method)
(HyperTreeList method)
(PageContainer method)
(UltimateListCtrl method)
(UltimateListMainWindow method)
SetImageListCheck() (CustomTreeCtrl method)
(HyperTreeList method)
(UltimateListMainWindow method)
SetIncrement() (FloatSpin method)
SetIndent() (CustomTreeCtrl method)
(HyperTreeList method)
SetIndicatorColour() (RulerCtrl method)
SetIndicatorValue() (RulerCtrl method)
SetInitialSize() (AquaButton method)
(GradientButton method)
SetIntervalColours() (SpeedMeter method)
SetIntervals() (SpeedMeter method)
SetIsDown() (SButtonEvent method)
SetIsGroup() (SwitcherItem method)
SetIsVisible() (RibbonGalleryItem method)
SetItalic() (GenericTreeItem method)
SetItem() (CommandTreeEvent method)
(UltimateListCtrl method)
(UltimateListHeaderData method)
(UltimateListItemData method)
(UltimateListLineData method)
(UltimateListMainWindow method)
SetItem3State() (CustomTreeCtrl method)
(HyperTreeList method)
SetItem3StateValue() (CustomTreeCtrl method)
(HyperTreeList method)
SetItemBackgroundColour() (CustomTreeCtrl method)
(HyperTreeList method)
(UltimateListCtrl method)
SetItemBold() (CustomTreeCtrl method)
(HyperTreeList method)
SetItemClientData() (RibbonGallery method)
SetItemColumnImage() (UltimateListCtrl method)
SetItemCount() (SelectionStore method)
(UltimateListCtrl method)
(UltimateListMainWindow method)
SetItemCustomRenderer() (UltimateListCtrl method)
(UltimateListMainWindow method)
SetItemData() (UltimateListCtrl method)
SetItemDropHighlight() (CustomTreeCtrl method)
(HyperTreeList method)
SetItemFont() (CustomTreeCtrl method)
(FlatMenu method)
(HyperTreeList method)
(SwitcherItems method)
(UltimateListCtrl method)
SetItemHasChildren() (CustomTreeCtrl method)
(HyperTreeList method)
SetItemHyperText() (CustomTreeCtrl method)
(HyperTreeList method)
(UltimateListCtrl method)
(UltimateListMainWindow method)
SetItemImage() (CustomTreeCtrl method)
(HyperTreeList method)
(TreeListMainWindow method)
(UltimateListCtrl method)
SetItemItalic() (CustomTreeCtrl method)
(HyperTreeList method)
SetItemKind() (UltimateListCtrl method)
(UltimateListMainWindow method)
SetItemLeftImage() (CustomTreeCtrl method)
SetItemOverFlow() (UltimateListCtrl method)
(UltimateListMainWindow method)
SetItemPosition() (UltimateListCtrl method)
SetItemPyData() (CustomTreeCtrl method)
(HyperTreeList method)
(UltimateListCtrl method)
SetItemRect() (CommandToolBarEvent method)
SetItems() (MultiColumnListCtrl method)
SetItemSpacing() (UltimateListCtrl method)
(UltimateListMainWindow method)
SetItemState() (UltimateListCtrl method)
(UltimateListMainWindow method)
SetItemStateAll() (UltimateListMainWindow method)
SetItemText() (CustomTreeCtrl method)
(HyperTreeList method)
(TreeListMainWindow method)
(UltimateListCtrl method)
(UltimateListMainWindow method)
SetItemTextColour() (CustomTreeCtrl method)
(FlatMenu method)
(HyperTreeList method)
(UltimateListCtrl method)
SetItemType() (CustomTreeCtrl method)
(HyperTreeList method)
SetItemVisited() (CustomTreeCtrl method)
(HyperTreeList method)
(UltimateListCtrl method)
(UltimateListMainWindow method)
SetItemWindow() (CustomTreeCtrl method)
(HyperTreeList method)
(TreeListMainWindow method)
(UltimateListCtrl method)
(UltimateListMainWindow method)
SetItemWindowEnabled() (CustomTreeCtrl method)
(HyperTreeList method)
(TreeListMainWindow method)
(UltimateListCtrl method)
(UltimateListMainWindow method)
SetKeyEvent() (CommandTreeEvent method)
SetKind() (AuiToolBarItem method)
(ButtonInfo method)
(UltimateListHeaderData method)
(UltimateListItem method)
(UltimateListItemData method)
(UltimateListLineData method)
SetKnobRadius() (KnobCtrl method)
SetLabel() (AuiToolBarItem method)
(CommandNotebookEvent method)
(CommandTreeEvent method)
(FlatMenu method)
(FlatMenuItem method)
(FlatToolbarItem method)
(PiePart method)
(PyCollapsiblePane method)
(SButton method)
(ZoomBarEvent method)
(ZoomBarImage method)
SetLabelColour() (PieCtrlLegend method)
(RulerCtrl method)
(SButton method)
SetLabelControl() (ScrolledThumbnail method)
SetLabelEdges() (RulerCtrl method)
SetLabelFont() (PieCtrlLegend method)
SetLCDMonitor() (FlatMenuBar method)
SetLeftImage() (GenericTreeItem method)
SetLeftImageList() (CustomTreeCtrl method)
SetLinkCursor() (HyperLinkCtrl method)
SetLog() (RulerCtrl method)
SetLongHelp() (AuiToolBarItem method)
(ButtonInfo method)
(FlatMenuItem method)
(FlatToolbarItem method)
SetMainColumn() (HyperTreeList method)
(TreeListMainWindow method)
SetManagedWindow() (AuiManager method)
SetManager() (AuiManagerEvent method)
SetManagerStyle() (PersistenceManager method)
SetMargin() (FlatMenuBar method)
SetMargins() (AuiToolBar method)
SetMarginsSize() (AuiToolBar method)
SetMarginsXY() (AuiToolBar method)
SetMask() (UltimateListItem method)
SetMasterManager() (AuiManager method)
SetMaxValue() (ProgressPie method)
SetMBVerticalGradient() (ArtManager method)
SetMeasuringFont() (AuiDefaultTabArt method)
(AuiNotebook method)
(AuiSimpleTabArt method)
(AuiTabContainer method)
SetMenu() (FlatMenuItem method)
(FocusHandler method)
(MenuKbdRedirector method)
SetMenuBar() (FlatMenu method)
(FlatMenuItem method)
SetMenuBarColour() (ArtManager method)
SetMenuBarHighlightColour() (FMRenderer method)
SetMenuHighlightColour() (FMRenderer method)
SetMenuTheme() (ArtManager method)
SetMessage() (GenericMessageDialog method)
(SuperToolTip method)
SetMessageColour() (BalloonTip method)
SetMessageFont() (BalloonTip method)
(SuperToolTip method)
SetMeterBands() (PeakMeterCtrl method)
SetMetric() (AuiDefaultDockArt method)
(BPArt method)
(RibbonMSWArtProvider method)
SetMiddleGradientColor() (SuperToolTip method)
SetMiddleGradientColour() (SuperToolTip method)
SetMiddleIcon() (SpeedMeter method)
SetMiddleText() (SpeedMeter method)
SetMiddleTextColour() (SpeedMeter method)
SetMiddleTextFont() (SpeedMeter method)
SetMinMaxTabWidth() (AuiNotebook method)
SetMinSize() (AuiToolBarItem method)
SetModifierKey() (MultiColumnListCtrl method)
(SwitcherDialog method)
SetMS2007ButtonSunken() (ArtManager method)
SetName() (SwitcherItem method)
SetNameFromNotebookId() (AuiPaneInfo method)
SetNavigatorIcon() (AuiNotebook method)
(FlatNotebook method)
SetNegativeButton() (StdDialogButtonSizer method)
SetNonActiveTabTextColour() (FlatNotebook method)
SetNoneActive() (AuiTabContainer method)
SetNormalBitmap() (FlatMenuItem method)
SetNormalFont() (AuiDefaultTabArt method)
(AuiNotebook method)
(AuiSimpleTabArt method)
(AuiTabContainer method)
(CaptionBar method)
SetNotebook() (FlatNotebookDragEvent method)
SetNumberColumns() (FlatMenu method)
SetNumberOfSecondaryTicks() (SpeedMeter method)
SetOKBitmap() (GenericMessageDialog method)
SetOKCancelBitmaps() (GenericMessageDialog method)
SetOKCancelLabels() (GenericMessageDialog method)
SetOKLabel() (GenericMessageDialog method)
SetOldAccelerator() (ShortcutEvent method)
SetOldItem() (CommandTreeEvent method)
SetOldNotebook() (FlatNotebookDragEvent method)
SetOldSelection() (CommandNotebookEvent method)
(FlatNotebookEvent method)
(ImageNotebookEvent method)
SetOldValue() (KnobCtrlEvent method)
(RulerCtrlEvent method)
SetOptions() (FlatMenuBar method)
SetOrientation() (AuiDefaultToolBarArt method)
(AuiToolBar method)
(AuiToolBarItem method)
(RulerCtrl method)
(ScrolledThumbnail method)
SetOverFlow() (UltimateListItem method)
(UltimateListItemData method)
SetOverflowVisible() (AuiToolBar method)
SetOwnerHeight() (FlatMenuBase method)
SetPadding() (FlatNotebook method)
SetPage() (RibbonBarEvent method)
SetPageBitmap() (AuiNotebook method)
SetPageImage() (AuiNotebook method)
(FlatBookBase method)
(FlatNotebook method)
(ImageContainerBase method)
(PageContainer method)
SetPageShapeAngle() (FlatNotebook method)
SetPageText() (AuiNotebook method)
(FlatBookBase method)
(FlatNotebook method)
(ImageContainerBase method)
(PageContainer method)
SetPageTextColour() (AuiNotebook method)
(FlatNotebook method)
(PageContainer method)
(PageInfo method)
SetPane() (AuiManagerEvent method)
SetPanelColours() (CubeColourDialog method)
SetPaneWindow() (AuiFloatingFrame method)
SetPersistenceFile() (PersistenceManager method)
SetPersistenceKey() (PersistenceManager method)
SetPoint() (CommandTreeEvent method)
SetPopupBackgroundColour() (ToasterBox method)
(ToasterBoxWindow method)
SetPopupBitmap() (ToasterBox method)
(ToasterBoxWindow method)
SetPopupMenu() (ScrolledThumbnail method)
SetPopupPauseTime() (ToasterBox method)
(ToasterBoxWindow method)
SetPopupPosition() (ToasterBox method)
(ToasterBoxWindow method)
SetPopupPositionByInt() (ToasterBox method)
(ToasterBoxWindow method)
SetPopupScrollSpeed() (ToasterBox method)
(ToasterBoxWindow method)
SetPopupSize() (ToasterBox method)
(ToasterBoxWindow method)
SetPopupText() (ToasterBox method)
(ToasterBoxWindow method)
SetPopupTextColour() (ToasterBox method)
(ToasterBoxWindow method)
SetPopupTextFont() (ToasterBox method)
(ToasterBoxWindow method)
SetPosition() (FloatSpinEvent method)
(HyperLinkEvent method)
(ImageBar method)
(ImageInfo method)
(PageInfo method)
(RibbonGalleryItem method)
(UltimateListHeaderData method)
(UltimateListItemData method)
(UltimateListLineData method)
SetPressedBottomColour() (GradientButton method)
SetPressedItem() (AuiToolBar method)
SetPressedTopColour() (GradientButton method)
SetProperties() (CubeColourDialog method)
(MultiDirDialog method)
SetProportion() (AuiToolBarItem method)
SetPulseOnFocus() (AquaButton method)
SetPyData() (CustomTreeCtrl method)
(HyperTreeList method)
(UltimateListCtrl method)
(UltimateListItem method)
SetRaiseToolbar() (ArtManager method)
SetRange() (FloatSpin method)
(PyGauge method)
(RulerCtrl method)
SetRangeDontClampValue() (FloatSpin method)
SetRangeValue() (PeakMeterCtrl method)
SetRect() (ButtonInfo method)
(FlatMenuItem method)
(MenuEntryInfo method)
(SwitcherItem method)
SetRegion() (PageInfo method)
SetRenamable() (AuiNotebook method)
SetReportView() (UltimateListLineData method)
(UltimateListMainWindow method)
SetRightClickMenu() (FlatNotebook method)
SetRightIndent() (CaptionBar method)
SetRotatedImage() (Thumb method)
SetRotation() (Thumb method)
SetRotationAngle() (PieCtrl method)
SetRowCount() (SwitcherItems method)
SetRowPos() (SwitcherItem method)
SetRows() (RibbonToolBar method)
SetSashDClickUnsplit() (AuiNotebook method)
SetSashIdx() (FourWaySplitterEvent method)
SetSashPosition() (FourWaySplitterEvent method)
SetScrollPos() (UltimateListCtrl method)
SetSecondColour() (CaptionBarStyle method)
SetSecondGradientColour() (CustomTreeCtrl method)
(HyperTreeList method)
(KnobCtrl method)
(ProgressGauge method)
(PyProgress method)
(SpeedMeter method)
(UltimateListCtrl method)
(UltimateListMainWindow method)
SetSelectedFont() (AuiDefaultTabArt method)
(AuiNotebook method)
(AuiSimpleTabArt method)
(AuiTabContainer method)
SetSelectedImage() (TreeListColumnInfo method)
SetSelectedStateOfChildren() (TreeCtrlHandler method)
SetSelectedStateOfItem() (TreeCtrlHandler method)
SetSelectedTextBitmap() (MenuEntryInfo method)
SetSelection() (AuiNotebook method)
(CommandNotebookEvent method)
(FlatBookBase method)
(FlatMenuItemGroup method)
(FlatNotebook method)
(FlatNotebookCompatible method)
(FlatNotebookEvent method)
(ImageNotebookEvent method)
(PageContainer method)
(RibbonGallery method)
(ScrolledThumbnail method)
(SwitcherItems method)
(ZoomBarEvent method)
SetSelectionByName() (SwitcherItems method)
SetSelectionColour() (ScrolledThumbnail method)
(SwitcherItems method)
SetSelectionOutlineColour() (SwitcherItems method)
SetSelectionState() (TreeCtrlHandler method)
SetSelectionToPage() (AuiNotebook method)
SetSelectionToWindow() (AuiNotebook method)
SetSeparatorColour() (CustomTreeCtrl method)
SetShadowColour() (SpeedMeter method)
SetShape() (AuiDockingHintWindow method)
(AuiSingleDockingGuide method)
SetShortcut() (ShortcutEvent method)
SetShortHelp() (AuiToolBarItem method)
(ButtonInfo method)
(FlatToolbarItem method)
SetShowEdges() (PieCtrl method)
SetShowHideEffects() (InfoBar method)
SetShowLabels() (ZoomBar method)
SetShown() (TreeListColumnInfo method)
(UltimateListItem method)
SetShowReflections() (ZoomBar method)
SetSingleStyle() (UltimateListCtrl method)
SetSize() (FlatMenuButton method)
(ImageBar method)
(ImageInfo method)
(PageInfo method)
(UltimateListItemData method)
(ZoomBarImage method)
SetSizerItem() (AuiToolBarItem method)
SetSizeWithScrollButtonAdjustment() (RibbonPage method)
SetSizingInfo() (AuiDefaultTabArt method)
(AuiSimpleTabArt method)
(ChromeTabArt method)
(VC8TabArt method)
SetSnapLimits() (AuiManager method)
SetSnapToTicks() (FloatSpin method)
SetSpacerPixels() (AuiToolBarItem method)
SetSpacing() (CustomTreeCtrl method)
(FlatMenuBar method)
(HyperTreeList method)
(RulerCtrl method)
SetSpeedBackground() (SpeedMeter method)
SetSpeedValue() (SpeedMeter method)
SetSpinVals() (CubeColourDialog method)
SetSplashShape() (AdvancedSplash method)
SetStartDelay() (BalloonTip method)
(SuperToolTip method)
SetState() (AuiToolBarItem method)
(MenuEntryInfo method)
(UltimateListHeaderData method)
(UltimateListItem method)
SetStateImageList() (CustomTreeCtrl method)
(HyperTreeList method)
SetStateMask() (UltimateListItem method)
SetStatus() (ButtonInfo method)
SetSticky() (AuiToolBarItem method)
SetStringItem() (UltimateListCtrl method)
SetStyle() (ButtonPanel method)
SetSubMenu() (FlatMenuItem method)
SetSubMenuBar() (FlatMenu method)
SetTabAngle() (PageInfo method)
SetTabAreaColour() (FlatNotebook method)
SetTabAreaWidth() (LabelContainer method)
SetTabCtrlHeight() (AuiNotebook method)
(TabFrame method)
SetTabCtrlMargins() (RibbonBar method)
SetTabOffset() (AuiTabContainer method)
SetTabRect() (AuiTabContainer method)
SetTag() (CaptionBarEvent method)
SetTags() (KnobCtrl method)
SetTagsColour() (KnobCtrl method)
SetTarget() (BalloonTip method)
(SuperToolTip method)
SetText() (AdvancedSplash method)
(ButtonInfo method)
(ButtonPanelText method)
(FlatMenuItem method)
(GenericTreeItem method)
(TreeListColumnInfo method)
(TreeListItem method)
(UltimateListHeaderData method)
(UltimateListItem method)
(UltimateListItemData method)
(UltimateListLineData method)
SetTextAlignment() (ButtonInfo method)
SetTextBitmap() (MenuEntryInfo method)
SetTextColor() (SuperToolTip method)
SetTextColour() (AdvancedSplash method)
(FlatMenuItem method)
(SuperToolTip method)
(SwitcherItem method)
(SwitcherItems method)
(TreeItemAttr method)
(UltimateListCtrl method)
(UltimateListItem method)
(UltimateListItemAttr method)
SetTextFont() (AdvancedSplash method)
SetTextOrientation() (AuiDefaultToolBarArt method)
SetTextPosition() (AdvancedSplash method)
SetTextRect() (ImageInfo method)
SetTextX() (TreeListItem method)
SetTheme() (FMRendererMgr method)
SetThumbOutline() (ScrolledThumbnail method)
SetThumbSize() (ScrolledThumbnail method)
SetTickPenColour() (RulerCtrl method)
SetTicks() (SpeedMeter method)
SetTicksColour() (SpeedMeter method)
SetTicksFont() (SpeedMeter method)
SetTimeFormat() (RulerCtrl method)
SetTimeLabel() (PyProgress method)
SetTitle() (SwitcherItem method)
(ToasterBox method)
SetTitleColour() (BalloonTip method)
SetTitleFont() (BalloonTip method)
SetToDefaultValue() (FloatSpin method)
SetToggle() (__SToggleMixin method)
(__ToggleMixin method)
SetToggled() (ButtonInfo method)
SetToolAlignment() (AuiToolBar method)
SetToolbarMargin() (FlatMenuBar method)
SetToolbarSpacing() (FlatMenuBar method)
SetToolBitmap() (AuiToolBar method)
SetToolBitmapSize() (AuiToolBar method)
SetToolBorderPadding() (AuiToolBar method)
SetToolDisabledBitmap() (AuiToolBar method)
SetToolDropDown() (AuiToolBar method)
SetToolId() (CommandToolBarEvent method)
SetToolLabel() (AuiToolBar method)
SetToolLongHelp() (AuiToolBar method)
SetToolNormalBitmap() (AuiToolBar method)
SetToolOrientation() (AuiToolBar method)
SetToolPacking() (AuiToolBar method)
SetToolProportion() (AuiToolBar method)
SetToolSeparation() (AuiToolBar method)
SetToolShortHelp() (AuiToolBar method)
SetToolSticky() (AuiToolBar method)
SetToolTextOrientation() (AuiToolBar method)
SetToolTip() (CommandTreeEvent method)
(UltimateListHeaderData method)
(UltimateListItem method)
(UltimateListItemData method)
(UltimateListLineData method)
SetTopEndColour() (GradientButton method)
SetTopGradientColor() (SuperToolTip method)
SetTopGradientColour() (SuperToolTip method)
SetTopStartColour() (GradientButton method)
SetTrackPosition() (KnobCtrl method)
SetTransparency() (ArtManager method)
(MultiColumnListCtrl method)
SetTransparent() (PieCtrlLegend method)
SetType() (GenericTreeItem method)
SetUnderlines() (HyperLinkCtrl method)
SetUnfilledColour() (ProgressPie method)
SetUniformBitmapSize() (AuiNotebook method)
SetUnits() (RulerCtrl method)
SetupCell() (XLSCell method)
SetUpdateInterval() (FlatMenuBar method)
SetupDirCtrl() (MultiDirDialog method)
SetupHyperlink() (XLSText method)
SetupPositions() (ToasterBoxWindow method)
SetupProps() (ZoomBarImage method)
SetURL() (HyperLinkCtrl method)
SetUseFade() (SuperToolTip method)
SetUseFocus() (ToasterBox method)
(ToasterBoxWindow method)
SetUseFocusIndicator() (SButton method)
SetUseHelp() (ButtonPanel method)
SetUserData() (AuiToolBarItem method)
SetUserLineHeight() (UltimateListCtrl method)
(UltimateListMainWindow method)
SetValid() (AuiDockingGuideWindow method)
(AuiSingleDockingGuide method)
SetValue() (__SToggleMixin method)
(FloatSpin method)
(Indicator method)
(KnobCtrl method)
(KnobCtrlEvent method)
(PiePart method)
(ProgressPie method)
(PyGauge method)
(RulerCtrlEvent method)
(XLSCell method)
(XLSTable method)
(__ToggleMixin method)
SetVerticalBorder() (PieCtrlLegend method)
SetVisited() (GenericTreeItem method)
(HyperLinkCtrl method)
(UltimateListItem method)
(UltimateListItemData method)
SetVSplit() (FourWaySplitter method)
SetWaterMark() (UltimateListCtrl method)
(UltimateListMainWindow method)
SetWidth() (GenericTreeItem method)
(TreeListColumnInfo method)
(UltimateListHeaderData method)
(UltimateListItem method)
(UltimateListLineData method)
SetWindow() (AuiToolBarItem method)
(GenericTreeItem method)
(SwitcherItem method)
(TreeListItem method)
(UltimateListItem method)
(UltimateListItemData method)
SetWindowEnabled() (GenericTreeItem method)
(TreeListItem method)
(UltimateListItem method)
(UltimateListItemData method)
SetWindowStyleFlag() (AuiToolBar method)
SetX() (GenericTreeItem method)
(UltimateListLineData method)
SetXRect() (PageInfo method)
SetY() (GenericTreeItem method)
(UltimateListLineData method)
SetYesNoBitmaps() (GenericMessageDialog method)
SetYesNoCancelBitmaps() (GenericMessageDialog method)
SetYesNoCancelLabels() (GenericMessageDialog method)
SetYesNoLabels() (GenericMessageDialog method)
SetZoomFactor() (ScrolledThumbnail method)
(ZoomBar method)
(ZoomBarImage method)
ShadowBitmap() (AdvancedSplash method)
ShadowPopupWindow (class in flatmenu)
shapedbutton (module)
ShiftHue() (RibbonHSLColour method)
Shortcut (class in shortcuteditor)
ShortcutEditor (class in shortcuteditor)
shortcuteditor (module)
ShortcutEvent (class in shortcuteditor)
ShouldInheritColours() (AquaButton method)
(CustomTreeCtrl method)
(GradientButton method)
(HyperTreeList method)
(SButton method)
ShouldSendEventToDummy() (RibbonPanel method)
Show() (AuiDockingHintWindow method)
(AuiPaneInfo method)
(BoxSizer method)
(Control method)
(FlatMenuItem method)
(RibbonPage method)
(ShortcutEditor method)
(TabFrame method)
ShowComboBox() (ThumbnailCtrl method)
ShowCustomize() (FlatMenuBar method)
ShowCustomPage() (FlatNotebook method)
ShowDescription() (SwitcherDialog method)
ShowDialog() (PyProgress method)
ShowDir() (ScrolledThumbnail method)
ShowDockingGuides() (in module aui.framemanager)
ShowDropDown() (AuiDefaultTabArt method)
(AuiDefaultToolBarArt method)
(AuiSimpleTabArt method)
ShowExpanded() (RibbonPanel method)
ShowFileNames() (ScrolledThumbnail method)
ShowGrid() (PeakMeterCtrl method)
ShowHierarchy() (Shortcut method)
ShowHint() (AuiManager method)
ShowMessage() (InfoBar method)
ShowModal() (CubeColourDialog method)
(GenericMessageDialog method)
(ShortcutEditor method)
ShowPane() (AuiManager method)
ShowPanels() (RibbonBar method)
ShowScrollButtons() (RibbonPage method)
ShowShortcutText() (ListShortcut method)
ShowTabs() (FlatNotebook method)
ShowTabTooltip() (PageContainer method)
ShowThumbs() (ScrolledThumbnail method)
ShowWindowMenu() (AuiNotebook method)
SingleLine() (in module ribbon.art_msw)
SizeLayout() (ButtonPanel method)
Sizer (class in buttonpanel)
SlideIn() (AuiManager method)
SlideOut() (AuiManager method)
SliderHandler (class in persist.persist_handlers)
Slope() (in module cubecolourdialog)
SmartShrink() (AuiManager method)
SmoothDock() (AuiManager method)
Snap() (AuiManager method)
Snappable() (AuiPaneInfo method)
SnapPane() (AuiManager method)
SnapToBottom() (ZoomBar method)
SnapToScreen() (AuiManager method)
SortChildren() (CustomTreeCtrl method)
(HyperTreeList method)
SortFiles() (in module thumbnailctrl)
SortForDisplay() (PyGauge method)
SortItems() (ScrolledThumbnail method)
(UltimateListCtrl method)
(UltimateListMainWindow method)
SpeedMeter (class in speedmeter)
speedmeter (module)
SpinHandler (class in persist.persist_handlers)
Split() (AuiNotebook method)
SplitterHandler (class in persist.persist_handlers)
SplitThousands() (in module xlsgrid)
Start() (PeakMeterCtrl method)
StartAlpha() (ToolTipWindowBase method)
StartPreviewTimer() (AuiManager method)
(AuiToolBar method)
Status (ButtonInfo attribute)
StatusBarTimer (class in buttonpanel)
(class in flatmenu)
StdDialogButtonSizer (class in genericmessagedialog)
StepColour() (in module aui.aui_utilities)
SToggleButton (class in shapedbutton)
Stop() (PeakMeterCtrl method)
StopEditing() (EditCtrl method)
(TabTextCtrl method)
(TreeTextCtrl method)
(UltimateListTextCtrl method)
StopPreviewTimer() (AuiManager method)
(AuiToolBar method)
SuperToolTip (class in supertooltip)
supertooltip (module)
SwitcherDialog (class in aui.aui_switcherdialog)
SwitcherItem (class in aui.aui_switcherdialog)
SwitcherItems (class in aui.aui_switcherdialog)
SwitchFocus() (GenericMessageDialog method)
SwitchToolBarOrientation() (AuiManager method)
SyncSpinToText() (FloatSpin method)

Navigation

  • index
  • modules |
  • Home |
  • Gallery |
  • Index


Index

  • modules |
  • Home |
  • Gallery |
  • Contents»
  • Index

Index – T

TabDragImage (class in aui.aui_utilities)
TabFrame (class in aui.auibook)
TabHasImage() (PageContainer method)
TabHitTest() (AuiTabContainer method)
TabNavigatorProps (class in aui.auibook)
TabNavigatorWindow (class in aui.auibook)
(class in flatnotebook)
TabTextCtrl (class in aui.auibook)
TagAllChildrenUntilLast() (CustomTreeCtrl method)
TagNextChildren() (CustomTreeCtrl method)
TakeScreenShot() (ArtManager method)
(in module aui.aui_utilities)
TaskBarTimer() (BalloonTip method)
TearDown() (ToasterBoxWindow method)
TearUp() (ToasterBoxWindow method)
TestButtonHover() (RibbonGallery method)
TestPositionForHover() (RibbonPanel method)
TextCtrlHandler (class in persist.persist_handlers)
TextEntryHandler (class in persist.persist_handlers)
Thaw() (CustomTreeCtrl method)
ThreadImage() (ScrolledThumbnail method)
Thumb (class in thumbnailctrl)
ThumbnailCtrl (class in thumbnailctrl)
thumbnailctrl (module)
ThumbnailEvent (class in thumbnailctrl)
Tick() (RulerCtrl method)
TickMajor() (RulerCtrl method)
TickMinor() (RulerCtrl method)
Tile() (FlatNotebook method)
TileBackground() (CustomTreeCtrl method)
(UltimateListMainWindow method)
TLWHandler (class in persist.persist_handlers)
to_list() (in module ultimatelistctrl)
ToAcceleratorItem() (Shortcut method)
ToAcceleratorTable() (ShortcutEditor method)
ToasterBox (class in toasterbox)
toasterbox (module)
ToasterBoxWindow (class in toasterbox)
Toggle() (CustomTreeCtrl method)
(FlatToolbarItem method)
(HyperTreeList method)
ToggleButton() (RibbonButtonBar method)
ToggleButtonHandler (class in persist.persist_handlers)
ToggleItemSelection() (CustomTreeCtrl method)
(HyperTreeList method)
ToggleTool() (AuiToolBar method)
ToHSV() (Colour method)
ToMenuBar() (ShortcutEditor method)
ToMenuItem() (Shortcut method)
ToolbarCommandCapture (class in aui.auibar)
ToolBarHandler (class in persist.persist_handlers)
ToolBarItem (class in flatmenu)
ToolbarPane() (AuiPaneInfo method)
ToolTipWindow (class in supertooltip)
ToolTipWindowBase (class in supertooltip)
Top() (AuiDockingGuideInfo method)
(AuiPaneInfo method)
TopDockable() (AuiPaneInfo method)
TopSnappable() (AuiPaneInfo method)
ToRGB() (Colour method)
(RibbonHSLColour method)
toscale() (in module cubecolourdialog)
TrackPoint() (AlphaCtrl method)
(BrightCtrl method)
(HSVWheel method)
TransientPopup (class in xlsgrid)
Transparent() (AuiPaneInfo method)
TreebookHandler (class in persist.persist_handlers)
TreeCtrlHandler (class in persist.persist_handlers)
TreeEditTimer (class in customtreectrl)
TreeEvent (class in customtreectrl)
TreeFindTimer (class in customtreectrl)
TreeItemAttr (class in customtreectrl)
TreeListColumnInfo (class in hypertreelist)
TreeListCtrlHandler (class in persist.persist_handlers)
TreeListHeaderWindow (class in hypertreelist)
TreeListItem (class in hypertreelist)
TreeListMainWindow (class in hypertreelist)
TreeTextCtrl (class in customtreectrl)
TruncateText() (ArtManager method)
TryAfter() (RibbonPanel method)
TryCollapseLayout() (RibbonButtonBar method)
TryOpenSubMenu() (FlatMenu method)
TryScrollButtons() (FlatMenu method)
typeBackground (AuiDockUIPart attribute)
typeCaption (AuiDockUIPart attribute)
typeDock (AuiDockUIPart attribute)
typeDockSizer (AuiDockUIPart attribute)
typeGripper (AuiDockUIPart attribute)
typePane (AuiDockUIPart attribute)
typePaneBorder (AuiDockUIPart attribute)
typePaneButton (AuiDockUIPart attribute)
typePaneSizer (AuiDockUIPart attribute)

Navigation

  • index
  • modules |
  • Home |
  • Gallery |
  • Index


Index

  • modules |
  • Home |
  • Gallery |
  • Contents»
  • Index

Index – U

UltimateListCtrl (class in ultimatelistctrl)
ultimatelistctrl (module)
UltimateListEvent (class in ultimatelistctrl)
UltimateListHeaderData (class in ultimatelistctrl)
UltimateListHeaderWindow (class in ultimatelistctrl)
UltimateListItem (class in ultimatelistctrl)
UltimateListItemAttr (class in ultimatelistctrl)
UltimateListItemData (class in ultimatelistctrl)
UltimateListLineData (class in ultimatelistctrl)
UltimateListMainWindow (class in ultimatelistctrl)
UltimateListRenameTimer (class in ultimatelistctrl)
UltimateListTextCtrl (class in ultimatelistctrl)
UnCheckRadioParent() (CustomTreeCtrl method)
(HyperTreeList method)
UnInit() (AuiManager method)
Unregister() (PersistenceManager method)
Unselect() (CustomTreeCtrl method)
(HyperTreeList method)
UnselectAll() (CustomTreeCtrl method)
(HyperTreeList method)
UnselectAllChildren() (CustomTreeCtrl method)
UNSET_FLAG() (in module ribbon.bar)
UnSplit() (AuiNotebook method)
UnsplitDClick() (AuiNotebook method)
Update() (AuiManager method)
(AuiManager_DCP method)
(ProgressGauge method)
(PyGauge method)
(RulerCtrl method)
(TabFrame method)
(UltimateListCtrl method)
UpdateAcceleratorTable() (FlatMenuBar method)
UpdateButtonOnScreen() (AuiManager method)
UpdateCurrent() (UltimateListMainWindow method)
UpdateDockGuide() (AuiCenterDockingGuide method)
(AuiDockingGuideWindow method)
(AuiSingleDockingGuide method)
UpdateDockingGuides() (AuiManager method)
UpdateDrawing() (BufferedWindow method), [1]
UpdateHintWindowSize() (AuiNotebook method)
UpdateItem() (FlatMenu method)
(FlatMenuBar method)
UpdateItems() (ScrolledThumbnail method)
UpdateLink() (HyperLinkCtrl method)
UpdateNotebook() (AuiManager method)
UpdateParent() (InfoBar method)
UpdateProp() (ScrolledThumbnail method)
UpdatePulse() (PyProgress method)
UpdateRadioGroup() (FlatMenu method)
UpdateShow() (ScrolledThumbnail method)
UpdateTabCtrlHeight() (AuiNotebook method)
UseMenu() (FileHistory method)

Navigation

  • index
  • modules |
  • Home |
  • Gallery |
  • Index


Index

  • modules |
  • Home |
  • Gallery |
  • Contents»
  • Index

Index – V

ValidateNotebookDocking() (AuiCenterDockingGuide method)
(AuiDockingGuide method)
VC71TabArt (class in aui.tabart)
VC8TabArt (class in aui.tabart)
Veto() (AuiManagerEvent method)
(AuiNotebookEvent method)
(AuiToolBarEvent method)
(FlatNotebookEvent method)
(FourWaySplitterEvent method)
(ImageNotebookEvent method)
(RibbonBarEvent method)
(TreeEvent method)
(UltimateListEvent method)

Navigation

  • index
  • modules |
  • Home |
  • Gallery |
  • Index


Index

  • modules |
  • Home |
  • Gallery |
  • Contents»
  • Index

Index – W

wasMaximized (AuiPaneInfo attribute)
Window() (AuiPaneInfo method)
WrapMessage() (GenericMessageDialog method)
wxDate2PyDate() (in module persist.persist_handlers)

Navigation

  • index
  • modules |
  • Home |
  • Gallery |
  • Index


Index

  • modules |
  • Home |
  • Gallery |
  • Contents»
  • Index

Index – X

XLSBackground (class in xlsgrid)
XLSBorder (class in xlsgrid)
XLSBorderFactory (class in xlsgrid)
XLSCell (class in xlsgrid)
XLSComment (class in xlsgrid)
XLSGrid (class in xlsgrid)
xlsgrid (module)
XLSRenderer (class in xlsgrid)
XLSRichText (class in xlsgrid)
XLSTable (class in xlsgrid)
XLSText (class in xlsgrid)
XToCol() (TreeListHeaderWindow method)

Navigation

  • index
  • modules |
  • Home |
  • Gallery |
  • Index


Index

  • modules |
  • Home |
  • Gallery |
  • Contents»
  • Index

Index – Z

ZoomBar (class in zoombar)
zoombar (module)
ZoomBarEvent (class in zoombar)
ZoomBarImage (class in zoombar)
ZoomImage() (ZoomBarImage method)
ZoomIn() (ScrolledThumbnail method)
ZoomOut() (ScrolledThumbnail method)

Navigation

  • index
  • modules |
  • Home |
  • Gallery |
  • Index


GradientButton

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • gradientbutton »
  • GradientButton

GradientButton

This is the main class implementation of GradientButton.

hierarchy Inheritance Diagram

Inheritance diagram for: GradientButton

Inheritance diagram of GradientButton

appearance Control Appearance

GradientButton

Methods Summary

__init__ | Default class constructor.
AcceptsFocus | Can this window be given focus by mouse click? ..
DoGetBestSize | Overridden base class virtual.
Enable | Enables/disables the button.
GetBottomEndColour | Returns the bottom end colour for the gradient shading.
GetBottomStartColour | Returns the bottom start colour for the gradient shading.
GetDefaultAttributes | Overridden base class virtual.
GetPath | Returns a rounded wx.GraphicsPath rectangle.
GetPressedBottomColour | Returns the pressed bottom start colour for the gradient shading.
GetPressedTopColour | Returns the pressed top start colour for the gradient shading.
GetTopEndColour | Returns the top end colour for the gradient shading.
GetTopStartColour | Returns the top start colour for the gradient shading.
LightColour | Return light contrast of colour.
Notify | Actually sends a wx.EVT_BUTTON event to the listener (if any).
OnGainFocus | Handles the wx.EVT_SET_FOCUS event for GradientButton.
OnKeyDown | Handles the wx.EVT_KEY_DOWN event for GradientButton.
OnKeyUp | Handles the wx.EVT_KEY_UP event for GradientButton.
OnLeftDown | Handles the wx.EVT_LEFT_DOWN event for GradientButton.
OnLeftUp | Handles the wx.EVT_LEFT_UP event for GradientButton.
OnLoseFocus | Handles the wx.EVT_KILL_FOCUS event for GradientButton.
OnMouseEnter | Handles the wx.EVT_ENTER_WINDOW event for GradientButton.
OnMouseLeave | Handles the wx.EVT_LEAVE_WINDOW event for GradientButton.
OnPaint | Handles the wx.EVT_PAINT event for GradientButton.
OnSize | Handles the wx.EVT_SIZE event for GradientButton.
SetBaseColours | Sets the bottom, top, pressed and foreground colour
SetBestSize | Given the current font and bezel width settings, calculate and set a good size.
SetBottomEndColour | Sets the bottom end colour for the gradient shading.
SetBottomStartColour | Sets the top bottom colour for the gradient shading.
SetDefault | Sets the default button.
SetForegroundColour | Sets the GradientButton foreground (text) colour.
SetInitialSize | Given the current font and bezel width settings, calculate and set a good size.
SetPressedBottomColour | Sets the pressed bottom start colour for the gradient shading.
SetPressedTopColour | Sets the pressed top start colour for the gradient shading.
SetTopEndColour | Sets the top end colour for the gradient shading.
SetTopStartColour | Sets the top start colour for the gradient shading.
ShouldInheritColours | Overridden base class virtual.

API Class API

class GradientButton(wx.PyControl) [source]

This is the main class implementation of GradientButton.

__init__(parent, id=wx.ID_ANY, bitmap=None, label="", pos=wx.DefaultPosition, size=wx.DefaultSize, style=wx.NO_BORDER, validator=wx.DefaultValidator, name="gradientbutton") [source]

Default class constructor.

Parameters:
  • parent – the GradientButton parent;
  • id – window identifier. A value of -1 indicates a default value;
  • bitmap – the button bitmap (if any);
  • label – the button text label;
  • pos – the control position. A value of (-1, -1) indicates a default position, chosen by either the windowing system or wxPython, depending on platform;
  • size – the control size. A value of (-1, -1) indicates a default size, chosen by either the windowing system or wxPython, depending on platform;
  • style – the button style (unused);
  • validator – the validator associated to the button;
  • name – the button name.

AcceptsFocus() [source]

Can this window be given focus by mouse click?

Note

Overridden from wx.PyControl.

DoGetBestSize() [source]

Overridden base class virtual. Determines the best size of the button based on the label and bezel size.

Note

Overridden from wx.PyControl.

Enable(enable=True) [source]

Enables/disables the button.

Parameters: enable – True to enable the button, False to disable it.

Note

Overridden from wx.PyControl.

GetBottomEndColour() [source]

Returns the bottom end colour for the gradient shading.

GetBottomStartColour() [source]

Returns the bottom start colour for the gradient shading.

GetDefaultAttributes() [source]

Overridden base class virtual. By default we should use the same font/colour attributes as the native wx.Button.

GetPath(gc, rc, r) [source]

Returns a rounded wx.GraphicsPath rectangle.

Parameters:
  • gc – an instance of wx.GraphicsContext;
  • rc – a client rectangle;
  • r – the radious of the rounded part of the rectangle.

GetPressedBottomColour() [source]

Returns the pressed bottom start colour for the gradient shading.

GetPressedTopColour() [source]

Returns the pressed top start colour for the gradient shading.

GetTopEndColour() [source]

Returns the top end colour for the gradient shading.

GetTopStartColour() [source]

Returns the top start colour for the gradient shading.

LightColour(colour, percent) [source]

Return light contrast of colour. The colour returned is from the scale of colour ==> white.

Parameters:
  • colour – the input colour to be brightened;
  • percent – determines how light the colour will be. percent = 100 returns white, percent = 0 returns colour.

Notify() [source]

Actually sends a wx.EVT_BUTTON event to the listener (if any).

OnGainFocus(event) [source]

Handles the wx.EVT_SET_FOCUS event for GradientButton.

Parameters: event – a wx.FocusEvent event to be processed.

OnKeyDown(event) [source]

Handles the wx.EVT_KEY_DOWN event for GradientButton.

Parameters: event – a wx.KeyEvent event to be processed.

OnKeyUp(event) [source]

Handles the wx.EVT_KEY_UP event for GradientButton.

Parameters: event – a wx.KeyEvent event to be processed.

OnLeftDown(event) [source]

Handles the wx.EVT_LEFT_DOWN event for GradientButton.

Parameters: event – a wx.MouseEvent event to be processed.

OnLeftUp(event) [source]

Handles the wx.EVT_LEFT_UP event for GradientButton.

Parameters: event – a wx.MouseEvent event to be processed.

OnLoseFocus(event) [source]

Handles the wx.EVT_KILL_FOCUS event for GradientButton.

Parameters: event – a wx.FocusEvent event to be processed.

OnMouseEnter(event) [source]

Handles the wx.EVT_ENTER_WINDOW event for GradientButton.

Parameters: event – a wx.MouseEvent event to be processed.

OnMouseLeave(event) [source]

Handles the wx.EVT_LEAVE_WINDOW event for GradientButton.

Parameters: event – a wx.MouseEvent event to be processed.

OnPaint(event) [source]

Handles the wx.EVT_PAINT event for GradientButton.

Parameters: event – a wx.PaintEvent event to be processed.

OnSize(event) [source]

Handles the wx.EVT_SIZE event for GradientButton.

Parameters: event – a wx.SizeEvent event to be processed.

SetBaseColours(startcolour=wx.BLACK, foregroundcolour=wx.WHITE) [source]

Sets the bottom, top, pressed and foreground colour

Parameters:
  • startcolour – based colour to be used for bottom, top and pressed
  • foregroundcolour – colour used for the text

SetBestSize(size=None)

Given the current font and bezel width settings, calculate and set a good size.

Parameters: size – an instance of wx.Size.

SetBottomEndColour(colour) [source]

Sets the bottom end colour for the gradient shading.

Parameters: colour – a valid wx.Colour object.

SetBottomStartColour(colour) [source]

Sets the top bottom colour for the gradient shading.

Parameters: colour – a valid wx.Colour object.

SetDefault() [source]

Sets the default button.

SetForegroundColour(colour) [source]

Sets the GradientButton foreground (text) colour.

Parameters: colour – a valid wx.Colour object.

Note

Overridden from wx.PyControl.

SetInitialSize(size=None) [source]

Given the current font and bezel width settings, calculate and set a good size.

Parameters: size – an instance of wx.Size.

SetPressedBottomColour(colour) [source]

Sets the pressed bottom start colour for the gradient shading.

Parameters: colour – a valid wx.Colour object.

SetPressedTopColour(colour) [source]

Sets the pressed top start colour for the gradient shading.

Parameters: colour – a valid wx.Colour object.

SetTopEndColour(colour) [source]

Sets the top end colour for the gradient shading.

Parameters: colour – a valid wx.Colour object.

SetTopStartColour(colour) [source]

Sets the top start colour for the gradient shading.

Parameters: colour – a valid wx.Colour object.

ShouldInheritColours() [source]

Overridden base class virtual. Buttons usually don’t inherit the parent’s colours.

Note

Overridden from wx.PyControl.

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • infobar
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • gradientbutton »
  • GradientButton


GradientButtonEvent

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • gradientbutton »
  • GradientButtonEvent

GradientButtonEvent

Event sent from GradientButton when the button is activated.

hierarchy Inheritance Diagram

Inheritance diagram for: GradientButtonEvent

Inheritance diagram of GradientButtonEvent

Methods Summary

__init__ | Default class constructor.
GetButtonObj | Returns the object associated with this event.
SetButtonObj | Sets the event object for the event.

API Class API

class GradientButtonEvent(wx.PyCommandEvent) [source]

Event sent from GradientButton when the button is activated.

__init__(eventType, eventId) [source]

Default class constructor.

Parameters:
  • eventType – the event type;
  • eventId – the event identifier.

GetButtonObj() [source]

Returns the object associated with this event.

SetButtonObj(btn) [source]

Sets the event object for the event.

Parameters: btn – the button object, an instance of GradientButton.

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • infobar
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • gradientbutton »
  • GradientButtonEvent


SVN Revision 68362 For gradientbutton

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • gradientbutton »
  • SVN Revision 68362 For gradientbutton

svn SVN Revision 68362 For gradientbutton

This file contains the SVN revision history for gradientbutton, at revision 68362.

Available information include commit date, the name of the committer, the file size, the SVN log messages and a diff from the previous version (if available).

File Information

  • Commit Date: 20-Oct-2008 20:05:15 UTC
  • Committer: AG
  • File Size: 19286 byte(s)

Log Messages

The following log message was entered by the committer:

  • All of AGW: change my work e-mail from KPO to Maersk Oil (silly commit)

Diff To Previous Version (65377)

Version SVN diff:

--- wxPython/3rdParty/AGW/agw/gradientbutton.py     2010/08/21 20:27:02     65377
+++ wxPython/3rdParty/AGW/agw/gradientbutton.py     2011/07/24 21:36:47     68362
@@ -14,7 +14,7 @@
# write to me at:
#
# andrea.gavana@gmail.com
-# gavana@kpo.kz
+# andrea.gavana@maerskoil.com
#
# Or, obviously, to the wxPython mailing list!!!
#

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • gradientbutton »
  • SVN Revision 68362 For gradientbutton


SVN Revision 68881 For gradientbutton

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • gradientbutton »
  • SVN Revision 68881 For gradientbutton

svn SVN Revision 68881 For gradientbutton

This file contains the SVN revision history for gradientbutton, at revision 68881.

Available information include commit date, the name of the committer, the file size, the SVN log messages and a diff from the previous version (if available).

File Information

  • Commit Date: 17-Oct-2008 20:51:43 UTC
  • Committer: AG
  • File Size: 20134 byte(s)

Log Messages

The following log message was entered by the committer:

  • AGW: General overhaul of the documentation, much improved. All the widgets have their own sample usage in the docs as well;

  • FlatNotebook: Added the FNB_NAV_BUTTONS_WHEN_NEEDED style, which hides the navigation left/right arrows if all tabs fit;

  • RibbonBar: - Added the EVT_RIBBONBAR_TAB_LEFT_DCLICK event, which generates a special event

    when a ribbon bar tab is double-clicked;

    • Added support for toggle buttons;
    • Improved support for ribbon panel sizers: panels with sizers should now automatically minimise at small sizes, and behave properly when popping up from a minimised state;
    • Added tooltips via SetToolTip for those buttons which have the help_string attribute set.

  • XLSGrid: a new widget was added to AGW, termed XLSGrid. It’s based on wx.grid.Grid and can be used to faithfully reproduce the appearance of a Microsoft Excel spreadsheets.

Diff To Previous Version (68362)

Version SVN diff:

--- wxPython/3rdParty/AGW/agw/gradientbutton.py     2011/07/24 21:36:47     68362
+++ wxPython/3rdParty/AGW/agw/gradientbutton.py     2011/08/25 16:40:17     68881
@@ -2,7 +2,7 @@
# GRADIENTBUTTON wxPython IMPLEMENTATION
#
# Andrea Gavana, @ 07 October 2008
-# Latest Revision: 27 Nov 2009, 17.00 GMT
+# Latest Revision: 17 Aug 2011, 15.00 GMT
#
#
# TODO List
@@ -23,16 +23,16 @@
# --------------------------------------------------------------------------------- #

"""
-GradientButton is another custom-drawn button class which mimics Windows CE mobile
+L{GradientButton} is another custom-drawn button class which mimics Windows CE mobile
gradient buttons.

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

-GradientButton is another custom-drawn button class which mimics Windows CE mobile
+L{GradientButton} is another custom-drawn button class which mimics Windows CE mobile
gradient buttons, using a tri-vertex blended gradient plus some ClearType bold
-font (best effect with Tahoma Bold). GradientButton supports:
+font (best effect with Tahoma Bold). L{GradientButton} supports:

* Triple blended gradient background, with customizable colours;
* Custom colours for the "pressed" state;
@@ -42,10 +42,46 @@
And a lot more. Check the demo for an almost complete review of the functionalities.

+Usage
+=====
+
+Usage example::
+
+    import wx
+    import wx.lib.agw.gradientbutton as GB
+
+    class MyFrame(wx.Frame):
+
+        def __init__(self, parent):
+
+            wx.Frame.__init__(self, parent, -1, "GradientButton Demo")
+
+            panel = wx.Panel(self, -1)
+
+            # One button without bitmap
+            button_1 = GB.GradientButton(panel, -1, None, "Hello World", (100, 50))
+
+            # One button with bitmap
+            my_bitmap = wx.Bitmap("my_bitmap.png", wx.BITMAP_TYPE_PNG)
+            button_2 = GB.GradientButton(panel, -1, my_bitmap, "GradientButton", (100, 150))
+
+
+    # our normal wxApp-derived class, as usual
+
+    app = wx.PySimpleApp()
+
+    frame = MyFrame(None)
+    app.SetTopWindow(frame)
+    frame.Show()
+
+    app.MainLoop()
+
+
+
Supported Platforms
===================

-GradientButton has been tested on the following platforms:
+L{GradientButton} has been tested on the following platforms:
* Windows (Windows XP).

@@ -70,9 +106,9 @@
License And Version
===================

-GradientButton is distributed under the wxPython license.
+L{GradientButton} is distributed under the wxPython license.

-Latest Revision: Andrea Gavana @ 27 Nov 2009, 17.00 GMT
+Latest Revision: Andrea Gavana @ 17 Aug 2011, 15.00 GMT

Version 0.3

@@ -624,6 +660,8 @@
"""
Overridden base class virtual. Determines the best size of the
button based on the label and bezel size.
+
+        :note: Overridden from `wx.PyControl`.
"""

label = self.GetLabel()

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • gradientbutton »
  • SVN Revision 68881 For gradientbutton


SVN Revision 70555 For gradientbutton

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • gradientbutton »
  • SVN Revision 70555 For gradientbutton

svn SVN Revision 70555 For gradientbutton

This file contains the SVN revision history for gradientbutton, at revision 70555.

Available information include commit date, the name of the committer, the file size, the SVN log messages and a diff from the previous version (if available).

File Information

  • Commit Date: 17-Oct-2008 19:15:31 UTC
  • Committer: AG
  • File Size: 20173 byte(s)

Log Messages

The following log message was entered by the committer:

  • GradientButton: applied patch from Werner and cleaned up a bit the useless parts of the code;
  • AuiToolBar/AuiDefaultDockArt: applied patch from Werner for default colour settings for AUI toolbars;
  • UltimateListCtrl: Fixed bug #13938. Also, don’t throw an error on key down if the list is empty.

Diff To Previous Version (68881)

Version SVN diff:

--- wxPython/3rdParty/AGW/agw/gradientbutton.py     2011/08/25 16:40:17     68881
+++ wxPython/3rdParty/AGW/agw/gradientbutton.py     2012/02/09 20:52:26     70555
@@ -2,7 +2,7 @@
# GRADIENTBUTTON wxPython IMPLEMENTATION
#
# Andrea Gavana, @ 07 October 2008
-# Latest Revision: 17 Aug 2011, 15.00 GMT
+# Latest Revision: 09 Feb 2012, 21.00 GMT
#
#
# TODO List
@@ -108,7 +108,7 @@

L{GradientButton} is distributed under the wxPython license.

-Latest Revision: Andrea Gavana @ 17 Aug 2011, 15.00 GMT
+Latest Revision: Andrea Gavana @ 09 Feb 2012, 21.00 GMT

Version 0.3

@@ -198,8 +198,17 @@
self.InheritAttributes()
self.SetInitialSize(size)

-        # The following defaults are better suited to draw the text outline
-        self._bottomStartColour = wx.BLACK
+        self.SetBaseColours()
+
+
+    def SetBaseColours(self, startcolour=wx.BLACK, foregroundcolour=wx.WHITE):
+        """Sets the bottom, top, pressed and foreground colour
+
+        :param startcolour: based colour to be used for bottom, top and pressed
+        :param foregroundcolour: colour used for the text
+
+        """
+        self._bottomStartColour = startcolour
rgba = self._bottomStartColour.Red(), self._bottomStartColour.Green(), \
self._bottomStartColour.Blue(), self._bottomStartColour.Alpha()
self._bottomEndColour = self.LightColour(self._bottomStartColour, 20)
@@ -207,14 +216,8 @@
self._topEndColour = self.LightColour(self._bottomStartColour, 25)
self._pressedTopColour = self.LightColour(self._bottomStartColour, 20)
self._pressedBottomColour = wx.Colour(*rgba)
-        self.SetForegroundColour(wx.WHITE)
+        self.SetForegroundColour(foregroundcolour)

-        for method in dir(self):
-            if method.endswith("Colour"):
-                newMethod = method[0:-6] + "Colour"
-                if not hasattr(self, newMethod):
-                    setattr(self, newMethod, method)
-

def LightColour(self, colour, percent):
"""

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • gradientbutton »
  • SVN Revision 70555 For gradientbutton


HyperLinkCtrl

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • hyperlink »
  • HyperLinkCtrl

HyperLinkCtrl

HyperLinkCtrl is a control for wxPython that acts like a hyper link in a typical browser. Latest features include the ability to capture your own left, middle, and right click events to perform your own custom event handling and ability to open link in a new or current browser window.

hierarchy Inheritance Diagram

Inheritance diagram for: HyperLinkCtrl

Inheritance diagram of HyperLinkCtrl

appearance Control Appearance

HyperLinkCtrl

Methods Summary

__init__ | Default class constructor.
AutoBrowse | Automatically browse to URL when clicked.
DisplayError | Displays an error message (according to the ReportErrors parameter) in a
DoPopup | Sets whether to show popup menu on right click or not.
EnableRollover | Enable/disable rollover.
GetBold | Returns whether the HyperLinkCtrl has text in bold or not.
GetColours | Gets the colours for the link, the visited link and the mouse
GetLinkCursor | Gets the link cursor.
GetURL | Retrieve the URL associated to the HyperLinkCtrl.
GetUnderlines | Returns if link is underlined, if the mouse rollover is
GetVisited | Returns whether a link has been visited or not.
GotoURL | Goto the specified URL.
OnMouseEvent | Handles the wx.EVT_MOUSE_EVENTS events for HyperLinkCtrl.
OnPopUpCopy | Handles the wx.EVT_MENU event for HyperLinkCtrl.
OpenInSameWindow | Open multiple URL in the same window (if possible).
ReportErrors | Set whether to report browser errors or not.
SetBold | Sets the HyperLinkCtrl label in bold text.
SetColours | Sets the colours for the link, the visited link and the mouse rollover.
SetLinkCursor | Sets link cursor properties.
SetURL | Sets the HyperLinkCtrl text to the specified URL.
SetUnderlines | Sets whether the text should be underlined or not for new links, visited links and rollovers.
SetVisited | Sets a link as visited.
UpdateLink | Updates the link, changing text properties if:

API Class API

class HyperLinkCtrl(StaticText) [source]

HyperLinkCtrl is a control for wxPython that acts like a hyper link in a typical browser. Latest features include the ability to capture your own left, middle, and right click events to perform your own custom event handling and ability to open link in a new or current browser window.

__init__(parent, id=-1, label="", pos=wx.DefaultPosition, size=wx.DefaultSize, style=0, name="staticText", URL="") [source]

Default class constructor.

Parameters:
  • parent – the window parent. Must not be None;
  • id – window identifier. A value of -1 indicates a default value;
  • label – the control label;
  • pos – the control position. A value of (-1, -1) indicates a default position, chosen by either the windowing system or wxPython, depending on platform;
  • size – the control size. A value of (-1, -1) indicates a default size, chosen by either the windowing system or wxPython, depending on platform;
  • style – the window style;
  • name – the window name;
  • URL – a string specifying the url link to navigate to.

Note

Pass URL=”” to use the label as the url link to navigate to.

AutoBrowse(AutoBrowse=True) [source]

Automatically browse to URL when clicked.

Parameters: AutoBrowse – True to automatically browse to an URL when clicked, False otherwise.

Note

Set AutoBrowse to False to receive EVT_HYPERLINK_LEFT events.

DisplayError(ErrorMessage, ReportErrors=True) [source]

Displays an error message (according to the ReportErrors parameter) in a wx.MessageBox.

Parameters:
  • ErrorMessage – a string representing the error to display;
  • ReportErrors – True to display error dialog if an error occurrs navigating to the URL.

DoPopup(DoPopup=True) [source]

Sets whether to show popup menu on right click or not.

Parameters: DoPopup – True to show a popup menu on right click, False otherwise.

EnableRollover(EnableRollover=False) [source]

Enable/disable rollover.

Parameters: EnableRollover – True to enable text effects during rollover, False to disable them.

GetBold() [source]

Returns whether the HyperLinkCtrl has text in bold or not.

GetColours() [source]

Gets the colours for the link, the visited link and the mouse rollover.

GetLinkCursor() [source]

Gets the link cursor.

GetURL() [source]

Retrieve the URL associated to the HyperLinkCtrl.

GetUnderlines() [source]

Returns if link is underlined, if the mouse rollover is underlined and if the visited link is underlined.

GetVisited() [source]

Returns whether a link has been visited or not.

GotoURL(URL, ReportErrors=True, NotSameWinIfPossible=False) [source]

Goto the specified URL.

Parameters:
  • URL – the url link we wish to navigate;
  • ReportErrors – Use True to display error dialog if an error occurrs navigating to the URL;
  • NotSameWinIfPossible – Use True to attempt to open the URL in new browser window.

OnMouseEvent(event) [source]

Handles the wx.EVT_MOUSE_EVENTS events for HyperLinkCtrl.

Parameters: event – a wx.MouseEvent event to be processed.

OnPopUpCopy(event) [source]

Handles the wx.EVT_MENU event for HyperLinkCtrl.

Parameters: event – a wx.MenuEvent event to be processed.

Note

This method copies the data from the HyperLinkCtrl to the clipboard.

OpenInSameWindow(NotSameWinIfPossible=False) [source]

Open multiple URL in the same window (if possible).

Parameters: NotSameWinIfPossible – True to open an hyperlink in a new browser window, False to use an existing browser window.

ReportErrors(ReportErrors=True) [source]

Set whether to report browser errors or not.

Parameters: ReportErrors – Use True to display error dialog if an error occurrs navigating to the URL;

SetBold(Bold=False) [source]

Sets the HyperLinkCtrl label in bold text.

Parameters: Bold – True to set the HyperLinkCtrl label as bold, False otherwise.

SetColours(link=wx.Colour(0, 0, 255), visited=wx.Colour(79, 47, 79), rollover=wx.Colour(0, 0, 255)) [source]

Sets the colours for the link, the visited link and the mouse rollover.

  • Visited link: VIOLET
  • Rollover: BLUE
Parameters:
  • link – a valid wx.Colour to use as text foreground for new links (default=RED);
  • visited – a valid wx.Colour to use as text foreground for visited links (default=VIOLET);

  • rollover – a valid wx.Colour to use as text foreground for links rollovers (default=BLUE).

SetLinkCursor(cur=wx.CURSOR_HAND) [source]

Sets link cursor properties.

Parameters: cur – an integer representing a wx.StockCursor constant.

SetURL(URL) [source]

Sets the HyperLinkCtrl text to the specified URL.

Parameters: URL – the new URL associated with HyperLinkCtrl.

SetUnderlines(link=True, visited=True, rollover=True) [source]

Sets whether the text should be underlined or not for new links, visited links and rollovers.

Parameters:
  • link – True to set the text of new links as underlined, False otherwise;
  • visited – True to set the text of visited links as underlined, False otherwise;
  • rollover – True to set the text of rollovers as underlined, False otherwise.

SetVisited(Visited=False) [source]

Sets a link as visited.

Parameters: Visited – True to set a link as visited, False otherwise.

UpdateLink(OnRefresh=True) [source]

Updates the link, changing text properties if:

  • User specific setting;
  • Link visited;
  • New link;
Parameters: OnRefresh – True to refresh the control, False otherwise.

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • infobar
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • hyperlink »
  • HyperLinkCtrl


HyperLinkEvent

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • hyperlink »
  • HyperLinkEvent

HyperLinkEvent

Event object sent in response to clicking on a HyperLinkCtrl.

hierarchy Inheritance Diagram

Inheritance diagram for: HyperLinkEvent

Inheritance diagram of HyperLinkEvent

Methods Summary

__init__ | Default Class Constructor.
GetPosition | Returns the event position.
SetPosition | Sets the event position.

API Class API

class HyperLinkEvent(wx.PyCommandEvent) [source]

Event object sent in response to clicking on a HyperLinkCtrl.

__init__(eventType, eventId) [source]

Default Class Constructor.

Parameters:
  • eventType – the event type;
  • eventId – the event identifier.

GetPosition() [source]

Returns the event position.

SetPosition(pos) [source]

Sets the event position.

Parameters: pos – an instance of wx.Point.

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • infobar
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • hyperlink »
  • HyperLinkEvent


SVN Revision 68362 For hyperlink

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • hyperlink »
  • SVN Revision 68362 For hyperlink

svn SVN Revision 68362 For hyperlink

This file contains the SVN revision history for hyperlink, at revision 68362.

Available information include commit date, the name of the committer, the file size, the SVN log messages and a diff from the previous version (if available).

File Information

  • Commit Date: 17-Oct-2008 20:51:43 UTC
  • Committer: AG
  • File Size: 17879 byte(s)

Log Messages

The following log message was entered by the committer:

  • All of AGW: change my work e-mail from KPO to Maersk Oil (silly commit)

Diff To Previous Version (62856)

Version SVN diff:

--- wxPython/3rdParty/AGW/agw/hyperlink.py  2009/12/11 11:51:15     62856
+++ wxPython/3rdParty/AGW/agw/hyperlink.py  2011/07/24 21:36:47     68362
@@ -17,7 +17,7 @@
# write to me at:
#
# andrea.gavana@gmail.com
-# gavana@kpo.kz
+# andrea.gavana@maerskoil.com
#
# Or, obviously, to the wxPython mailing list!!!
#

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • hyperlink »
  • SVN Revision 68362 For hyperlink


SVN Revision 68881 For hyperlink

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • hyperlink »
  • SVN Revision 68881 For hyperlink

svn SVN Revision 68881 For hyperlink

This file contains the SVN revision history for hyperlink, at revision 68881.

Available information include commit date, the name of the committer, the file size, the SVN log messages and a diff from the previous version (if available).

File Information

  • Commit Date: 17-Oct-2008 19:15:31 UTC
  • Committer: AG
  • File Size: 19173 byte(s)

Log Messages

The following log message was entered by the committer:

  • AGW: General overhaul of the documentation, much improved. All the widgets have their own sample usage in the docs as well;

  • FlatNotebook: Added the FNB_NAV_BUTTONS_WHEN_NEEDED style, which hides the navigation left/right arrows if all tabs fit;

  • RibbonBar: - Added the EVT_RIBBONBAR_TAB_LEFT_DCLICK event, which generates a special event

    when a ribbon bar tab is double-clicked;

    • Added support for toggle buttons;
    • Improved support for ribbon panel sizers: panels with sizers should now automatically minimise at small sizes, and behave properly when popping up from a minimised state;
    • Added tooltips via SetToolTip for those buttons which have the help_string attribute set.

  • XLSGrid: a new widget was added to AGW, termed XLSGrid. It’s based on wx.grid.Grid and can be used to faithfully reproduce the appearance of a Microsoft Excel spreadsheets.

Diff To Previous Version (68362)

Version SVN diff:

--- wxPython/3rdParty/AGW/agw/hyperlink.py  2011/07/24 21:36:47     68362
+++ wxPython/3rdParty/AGW/agw/hyperlink.py  2011/08/25 16:40:17     68881
@@ -3,7 +3,7 @@
# Ported From Angelo Mandato C++ Code By:
#
# Andrea Gavana, @ 27 Mar 2005
-# Latest Revision: 27 Nov 2009, 17.00 GMT
+# Latest Revision: 17 Aug 2011, 15.00 GMT
#
#
# Original Web Site (For The C++ Code):
@@ -26,14 +26,14 @@
# --------------------------------------------------------------------------- #

"""
-HyperLinkCtrl is a control for wxPython that acts like a hyper link
+L{HyperLinkCtrl} is a control for wxPython that acts like a hyper link
in a typical browser.

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

-`HyperLinkCtrl` is a control for wxPython that acts like a hyper link
+L{HyperLinkCtrl} is a control for wxPython that acts like a hyper link
in a typical browser. Latest features include the ability to capture
your own left, middle, and right click events to perform your own
custom event handling and ability to open link in a new or current
@@ -42,6 +42,53 @@
Special thanks to Robin Dunn for the event binder for the 3 mouse buttons.

+Usage
+=====
+
+Usage example::
+
+    import wx
+    import wx.lib.agw.hyperlink as hl
+
+    class MyFrame(wx.Frame):
+
+        def __init__(self, parent):
+
+            wx.Frame.__init__(self, parent, -1, "HyperLink Demo")
+
+            panel = wx.Panel(self, -1)
+
+            # Default Web links:
+            hyper1 = hl.HyperLinkCtrl(panel, -1, "wxPython Main Page", pos=(100, 100),
+                                      URL="http://www.wxpython.org/")
+
+
+            # Web link with underline rollovers, opens in same window
+            hyper2 = hl.HyperLinkCtrl(panel, -1, "My Home Page", pos=(100, 150),
+                                      URL="http://xoomer.virgilio.it/infinity77/")
+
+            hyper2.AutoBrowse(False)
+            hyper2.SetColours("BLUE", "BLUE", "BLUE")
+            hyper2.EnableRollover(True)
+            hyper2.SetUnderlines(False, False, True)
+            hyper2.SetBold(True)
+            hyper2.OpenInSameWindow(True)
+            hyper2.SetToolTip(wx.ToolTip("Hello World!"))
+            hyper2.UpdateLink()
+
+
+    # our normal wxApp-derived class, as usual
+
+    app = wx.PySimpleApp()
+
+    frame = MyFrame(None)
+    app.SetTopWindow(frame)
+    frame.Show()
+
+    app.MainLoop()
+
+
+
Window Styles
=============

@@ -65,9 +112,9 @@
License And Version
===================

-HyperLinkCtrl is distributed under the wxPython license.
+L{HyperLinkCtrl} is distributed under the wxPython license.

-Latest Revision: Andrea Gavana @ 27 Nov 2009, 17.00 GMT
+Latest Revision: Andrea Gavana @ 17 Aug 2011, 15.00 GMT

Version 0.6

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • hyperlink »
  • SVN Revision 68881 For hyperlink


hypertreelist functions

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • hypertreelist »
  • hypertreelist functions

hypertreelist functions

This is the description of standalone Python functions in the hypertreelist module.

Functions Summary

IsBufferingSupported | Utility function which checks if a platform handles correctly double buffering for the header.
create_delegator_for | Creates a method that forwards calls to self._main_win (an instance of TreeListMainWindow).

API Functions API

IsBufferingSupported() [source]

Utility function which checks if a platform handles correctly double buffering for the header. Currently returns False for all platforms except Windows XP.

create_delegator_for(method) [source]

Creates a method that forwards calls to self._main_win (an instance of TreeListMainWindow).

Parameters: method – one method inside the TreeListMainWindow local scope.

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • infobar
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • hypertreelist »
  • hypertreelist functions


EditCtrl

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • hypertreelist »
  • EditCtrl

EditCtrl

Base class for controls used for in-place edit.

hierarchy Inheritance Diagram

Inheritance diagram for: EditCtrl

Inheritance diagram of EditCtrl

subclasses Known Subclasses

  • hypertreelist.EditTextCtrl

Methods Summary

__init__ | Default class constructor.
AcceptChanges | Accepts/refuses the changes made by the user.
Finish | Finish editing.
OnKillFocus | Handles the wx.EVT_KILL_FOCUS event for EditCtrl
StopEditing | Suddenly stops the editing.
column | Returns the column currently edited.
item | Returns the item currently edited.

API Class API

class EditCtrl(object) [source]

Base class for controls used for in-place edit.

__init__(parent, id=wx.ID_ANY, item=None, column=None, owner=None, value="", pos=wx.DefaultPosition, size=wx.DefaultSize, style=0, validator=wx.DefaultValidator, name="editctrl", **kwargs) [source]

Default class constructor.

Parameters:
  • parent – the window parent. Must not be None;
  • id – window identifier. A value of -1 indicates a default value;
  • item – an instance of TreeListItem;
  • column – if not None, an integer specifying the column index. If it is None, the main column index is used;
  • owner – the window owner, in this case an instance of TreeListMainWindow;
  • value – the initial value in the control;
  • pos – the control position. A value of (-1, -1) indicates a default position, chosen by either the windowing system or wxPython, depending on platform;
  • size – the control size. A value of (-1, -1) indicates a default size, chosen by either the windowing system or wxPython, depending on platform;
  • style – the window style;
  • validator – the window validator;
  • name – the window name.

AcceptChanges() [source]

Accepts/refuses the changes made by the user.

Finish() [source]

Finish editing.

OnKillFocus(event) [source]

Handles the wx.EVT_KILL_FOCUS event for EditCtrl

Parameters: event – a wx.FocusEvent event to be processed.

StopEditing() [source]

Suddenly stops the editing.

column() [source]

Returns the column currently edited.

item() [source]

Returns the item currently edited.

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • infobar
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • hypertreelist »
  • EditCtrl


EditTextCtrl

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • hypertreelist »
  • EditTextCtrl

EditTextCtrl

Text control used for in-place edit.

hierarchy Inheritance Diagram

Inheritance diagram for: EditTextCtrl

Inheritance diagram of EditTextCtrl

supclasses Known Superclasses

  • hypertreelist.EditCtrl

Methods Summary

__init__ | Default class constructor.
OnChar | Handles the wx.EVT_CHAR event for EditTextCtrl.
OnKeyUp | Handles the wx.EVT_KEY_UP event for EditTextCtrl.

API Class API

class EditTextCtrl(EditCtrl, wx.TextCtrl) [source]

Text control used for in-place edit.

__init__(parent, id=wx.ID_ANY, item=None, column=None, owner=None, value="", pos=wx.DefaultPosition, size=wx.DefaultSize, style=0, validator=wx.DefaultValidator, name="edittextctrl", **kwargs) [source]

Default class constructor. For internal use: do not call it in your code!

Parameters:
  • parent – the window parent. Must not be None;
  • id – window identifier. A value of -1 indicates a default value;
  • item – an instance of TreeListItem;
  • column – if not None, an integer specifying the column index. If it is None, the main column index is used;
  • owner – the window owner, in this case an instance of TreeListMainWindow;
  • value – the initial value in the text control;
  • pos – the control position. A value of (-1, -1) indicates a default position, chosen by either the windowing system or wxPython, depending on platform;
  • size – the control size. A value of (-1, -1) indicates a default size, chosen by either the windowing system or wxPython, depending on platform;
  • style – the window style;
  • validator – the window validator;
  • name – the window name.

OnChar(event) [source]

Handles the wx.EVT_CHAR event for EditTextCtrl.

Parameters: event – a wx.KeyEvent event to be processed.

OnKeyUp(event) [source]

Handles the wx.EVT_KEY_UP event for EditTextCtrl.

Parameters: event – a wx.KeyEvent event to be processed.

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • infobar
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • hypertreelist »
  • EditTextCtrl


HyperTreeList

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • hypertreelist »
  • HyperTreeList

HyperTreeList

HyperTreeList is a class that mimics the behaviour of wx.gizmos.TreeListCtrl, with almost the same base functionalities plus some more enhancements. This class does not rely on the native control, as it is a full owner-drawn tree-list control.

hierarchy Inheritance Diagram

Inheritance diagram for: HyperTreeList

Inheritance diagram of HyperTreeList

subclasses Known Subclasses

  • shortcuteditor.ListShortcut

appearance Control Appearance

HyperTreeList

Methods Summary

__init__ | Default class constructor.
AddColumn | Appends a column to the HyperTreeList.
AddColumnInfo | Appends a column to the HyperTreeList.
AddRoot |
AppendItem |
AssignButtonsImageList |
AssignImageList |
AssignStateImageList |
AutoCheckChild |
AutoCheckParent |
AutoToggleChild |
CalculateAndSetHeaderHeight | Calculates the best header height and stores it.
CheckChilds |
CheckItem |
CheckItem2 |
CheckSameLevel |
Collapse |
CollapseAndReset |
CreateEditCtrl | Create an edit control for editing a label of an item.
Delete |
DeleteAllItems |
DeleteChildren |
DeleteRoot |
DoGetBestSize | Gets the size which best suits the window: for a control, it would be the
DoHeaderLayout | Layouts the header control.
EditLabel |
EnableChildren |
EnableItem |
EnableSelectionGradient |
EnableSelectionVista |
EnsureVisible |
Expand |
ExpandAll |
ExpandAllChildren |
FindItem |
GetAGWWindowStyleFlag | Returns the HyperTreeList window style flag.
GetBackgroundImage |
GetBorderPen |
GetBoundingRect |
GetButtonsImageList |
GetChildrenCount |
GetClassDefaultAttributes | Returns the default font and colours which are used by the control.
GetColumn | Returns an instance of TreeListColumnInfo containing column information.
GetColumnAlignment | Returns the column text alignment.
GetColumnColour | Returns the column text colour.
GetColumnCount |
GetColumnFont | Returns the column text font.
GetColumnImage | Returns the image assigned to the specified column.
GetColumnText | Returns the column text label.
GetColumnWidth | Returns the column width, in pixels.
GetConnectionPen |
GetCurrentItem |
GetDisabledColour |
GetEditControl |
GetFirstChild |
GetFirstExpandedItem |
GetFirstGradientColour |
GetFirstVisibleItem |
GetGradientStyle |
GetHeaderWindow | Returns the header window, an instance of TreeListHeaderWindow.
GetHilightFocusColour |
GetHilightNonFocusColour |
GetHyperTextFont |
GetHyperTextNewColour |
GetHyperTextVisitedColour |
GetImageList |
GetImageListCheck |
GetIndent |
GetItem3StateValue |
GetItemBackgroundColour |
GetItemFont |
GetItemImage |
GetItemParent |
GetItemPyData |
GetItemText |
GetItemTextColour |
GetItemType |
GetItemVisited |
GetItemWindow |
GetItemWindowEnabled |
GetLastChild |
GetMainWindow | Returns the main window, an instance of TreeListMainWindow.
GetNext |
GetNextChild |
GetNextExpanded |
GetNextSibling |
GetNextVisible |
GetPrev |
GetPrevChild |
GetPrevExpanded |
GetPrevSibling |
GetPrevVisible |
GetPyData |
GetRootItem |
GetSecondGradientColour |
GetSelection |
GetSelections |
GetSpacing |
GetStateImageList |
GetTextCtrlAlignmentStyle | Return the alignment style to use for the text control that is used to edit labels of items.
GetTextCtrlStyle | Return the style to use for the text control that is used to edit labels of items.
HasAGWFlag | Returns whether a flag is present in the HyperTreeList style.
HasChildren |
HideItem |
HitTest |
InsertColumn | Inserts a column to the HyperTreeList at the position specified
InsertColumnInfo | Inserts a column to the HyperTreeList at the position specified
InsertItem |
IsBold |
IsColumnEditable | Returns True if the column is editable, False otherwise.
IsColumnShown | Returns True if the column is shown, False otherwise.
IsDescendantOf |
IsExpanded |
IsItem3State |
IsItemChecked |
IsItemEnabled |
IsItemHyperText |
IsItemVisible |
IsSelected |
ItemHasChildren |
OnCompareItems | Returns whether 2 items have the same text.
OnGetItemText | This function must be overloaded in the derived class for a control
OnSize | Handles the wx.EVT_SIZE event for HyperTreeList.
PrependItem |
Refresh | Causes this window, and all of its children recursively (except under wxGTK1
RemoveColumn | Removes a column from the HyperTreeList.
ScrollTo |
SelectAll |
SelectAllChildren |
SelectItem |
SetAGWWindowStyleFlag | Sets the window style for HyperTreeList.
SetBackgroundColour | Changes the background colour of HyperTreeList.
SetBackgroundImage |
SetBorderPen |
SetBuffered | Sets/unsets the double buffering for the header and the main window.
SetButtonsImageList |
SetColumn | Sets a column using an instance of TreeListColumnInfo.
SetColumnAlignment | Sets the column text alignment.
SetColumnColour | Sets the column text colour.
SetColumnEditable | Sets the column as editable or non-editable.
SetColumnFont | Sets the column text font.
SetColumnImage | Sets an image on the specified column.
SetColumnShown | Sets the column as shown or hidden.
SetColumnText | Sets the column text label.
SetColumnWidth | Sets the column width, in pixels.
SetConnectionPen |
SetDisabledColour |
SetDragItem |
SetFirstGradientColour |
SetFocus | This sets the window to receive keyboard input.
SetFont | Sets the default font for the header window and the main window.
SetForegroundColour | Changes the foreground colour of HyperTreeList.
SetGradientStyle |
SetHeaderCustomRenderer | Associate a custom renderer with the header - all columns will use it :param renderer: a class able to correctly render header buttons ..
SetHeaderFont | Sets the default font for the header window..
SetHilightFocusColour |
SetHilightNonFocusColour |
SetHyperTextFont |
SetHyperTextNewColour |
SetHyperTextVisitedColour |
SetImageList |
SetImageListCheck |
SetIndent |
SetItem3State |
SetItem3StateValue |
SetItemBackgroundColour |
SetItemBold |
SetItemDropHighlight |
SetItemFont |
SetItemHasChildren |
SetItemHyperText |
SetItemImage |
SetItemItalic |
SetItemPyData |
SetItemText |
SetItemTextColour |
SetItemType |
SetItemVisited |
SetItemWindow |
SetItemWindowEnabled |
SetMainColumn |
SetPyData |
SetSecondGradientColour |
SetSpacing |
SetStateImageList |
ShouldInheritColours |
SortChildren | Sorts the children of the given item using OnCompareItems method of HyperTreeList.
Toggle |
ToggleItemSelection |
UnCheckRadioParent |
Unselect |
UnselectAll |

API Class API

class HyperTreeList(wx.PyControl) [source]

HyperTreeList is a class that mimics the behaviour of wx.gizmos.TreeListCtrl, with almost the same base functionalities plus some more enhancements. This class does not rely on the native control, as it is a full owner-drawn tree-list control.

__init__(parent, id=wx.ID_ANY, pos=wx.DefaultPosition, size=wx.DefaultSize, style=0, agwStyle=wx.TR_DEFAULT_STYLE, validator=wx.DefaultValidator, name="HyperTreeList") [source]

Default class constructor.

Parameters:
  • parent – parent window. Must not be None;
  • id – window identifier. A value of -1 indicates a default value;
  • pos – the control position. A value of (-1, -1) indicates a default position, chosen by either the windowing system or wxPython, depending on platform;
  • size – the control size. A value of (-1, -1) indicates a default size, chosen by either the windowing system or wxPython, depending on platform;
  • style – the underlying wx.PyScrolledWindow style;
  • agwStyle – the AGW-specific HyperTreeList window style. This can be a combination of the following bits:

    Window Styles | Hex Value | Description
    TR_NO_BUTTONS | 0x0 | For convenience to document that no buttons are to be drawn.
    TR_SINGLE | 0x0 | For convenience to document that only one item may be selected at a time. Selecting another item causes the current selection, if any, to be deselected. This is the default.
    TR_HAS_BUTTONS | 0x1 | Use this style to show + and - buttons to the left of parent items.
    TR_NO_LINES | 0x4 | Use this style to hide vertical level connectors.
    TR_LINES_AT_ROOT | 0x8 | Use this style to show lines between root nodes. Only applicable if TR_HIDE_ROOT is set and TR_NO_LINES is not set.
    TR_DEFAULT_STYLE | 0x9 | The set of flags that are closest to the defaults for the native control for a particular toolkit.
    TR_TWIST_BUTTONS | 0x10 | Use old Mac-twist style buttons.
    TR_MULTIPLE | 0x20 | Use this style to allow a range of items to be selected. If a second range is selected, the current range, if any, is deselected.
    TR_EXTENDED | 0x40 | Use this style to allow disjoint items to be selected. (Only partially implemented; may not work in all cases).
    TR_HAS_VARIABLE_ROW_HEIGHT | 0x80 | Use this style to cause row heights to be just big enough to fit the content. If not set, all rows use the largest row height. The default is that this flag is unset.
    TR_EDIT_LABELS | 0x200 | Use this style if you wish the user to be able to edit labels in the tree control.
    TR_ROW_LINES | 0x400 | Use this style to draw a contrasting border between displayed rows.
    TR_HIDE_ROOT | 0x800 | Use this style to suppress the display of the root node, effectively causing the first-level nodes to appear as a series of root nodes.
    TR_COLUMN_LINES | 0x1000 | Use this style to draw a contrasting border between displayed columns.
    TR_FULL_ROW_HIGHLIGHT | 0x2000 | Use this style to have the background colour and the selection highlight extend over the entire horizontal row of the tree control window.
    TR_AUTO_CHECK_CHILD | 0x4000 | Only meaningful foe checkbox-type items: when a parent item is checked/unchecked its children are checked/unchecked as well.
    TR_AUTO_TOGGLE_CHILD | 0x8000 | Only meaningful foe checkbox-type items: when a parent item is checked/unchecked its children are toggled accordingly.
    TR_AUTO_CHECK_PARENT | 0x10000 | Only meaningful foe checkbox-type items: when a child item is checked/unchecked its parent item is checked/unchecked as well.
    TR_ALIGN_WINDOWS | 0x20000 | Flag used to align windows (in items with windows) at the same horizontal position.
    TR_NO_HEADER | 0x40000 | Use this style to hide the columns header.
    TR_ELLIPSIZE_LONG_ITEMS | 0x80000 | Flag used to ellipsize long items when the horizontal space for CustomTreeCtrl is low.
    TR_VIRTUAL | 0x100000 | HyperTreeList will have virtual behaviour.
  • validator – window validator;
  • name – window name.

AddColumn(text, width=_DEFAULT_COL_WIDTH, flag=wx.ALIGN_LEFT, image=-1, shown=True, colour=None, edit=False) [source]

Appends a column to the HyperTreeList.

Parameters:
  • text – the column text label;
  • width – the column width in pixels;
  • flag – the column alignment flag, one of wx.ALIGN_LEFT, wx.ALIGN_RIGHT, wx.ALIGN_CENTER;
  • image – an index within the normal image list assigned to HyperTreeList specifying the image to use for the column;
  • shown – True to show the column, False to hide it;
  • colour – a valid wx.Colour, representing the text foreground colour for the column;
  • edit – True to set the column as editable, False otherwise.

AddColumnInfo(colInfo) [source]

Appends a column to the HyperTreeList.

Parameters: colInfo – an instance of TreeListColumnInfo.

AddRoot(*args, **kwargs)

AppendItem(*args, **kwargs)

AssignButtonsImageList(*args, **kwargs)

AssignImageList(*args, **kwargs)

AssignStateImageList(*args, **kwargs)

AutoCheckChild(*args, **kwargs)

AutoCheckParent(*args, **kwargs)

AutoToggleChild(*args, **kwargs)

CalculateAndSetHeaderHeight() [source]

Calculates the best header height and stores it.

CheckChilds(*args, **kwargs)

CheckItem(*args, **kwargs)

CheckItem2(*args, **kwargs)

CheckSameLevel(*args, **kwargs)

Collapse(*args, **kwargs)

CollapseAndReset(*args, **kwargs)

CreateEditCtrl(item, column) [source]

Create an edit control for editing a label of an item. By default, this returns a text control.

Override this function in the derived class to return a different type of control.

Parameters:
  • item – an instance of TreeListItem;
  • column – an integer specifying the column index.

Delete(*args, **kwargs)

DeleteAllItems(*args, **kwargs)

DeleteChildren(*args, **kwargs)

DeleteRoot(*args, **kwargs)

DoGetBestSize() [source]

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

Note

Overridden from wx.PyControl.

DoHeaderLayout() [source]

Layouts the header control.

EditLabel(*args, **kwargs)

EnableChildren(*args, **kwargs)

EnableItem(*args, **kwargs)

EnableSelectionGradient(*args, **kwargs)

EnableSelectionVista(*args, **kwargs)

EnsureVisible(*args, **kwargs)

Expand(*args, **kwargs)

ExpandAll(*args, **kwargs)

ExpandAllChildren(*args, **kwargs)

FindItem(*args, **kwargs)

GetAGWWindowStyleFlag() [source]

Returns the HyperTreeList window style flag.

See also

SetAGWWindowStyleFlag for a list of valid window styles.

GetBackgroundImage(*args, **kwargs)

GetBorderPen(*args, **kwargs)

GetBoundingRect(*args, **kwargs)

GetButtonsImageList(*args, **kwargs)

GetChildrenCount(*args, **kwargs)

classmethod GetClassDefaultAttributes() [source]

Returns the default font and colours which are used by the control. This is useful if you want to use the same font or colour in your own control as in a standard control – which is a much better idea than hard coding specific colours or fonts which might look completely out of place on the users system, especially if it uses themes.

This static method is “overridden’’ in many derived classes and so calling, for example, wx.Button.GetClassDefaultAttributes() will typically return the values appropriate for a button which will be normally different from those returned by, say, wx.ListCtrl.GetClassDefaultAttributes().

Note

The wx.VisualAttributes structure has at least the fields font, colFg and colBg. All of them may be invalid if it was not possible to determine the default control appearance or, especially for the background colour, if the field doesn’t make sense as is the case for colBg for the controls with themed background.

GetColumn(column) [source]

Returns an instance of TreeListColumnInfo containing column information.

Parameters: column – an integer specifying the column index.

GetColumnAlignment(column) [source]

Returns the column text alignment.

Parameters: column – an integer specifying the column index.

GetColumnColour(column) [source]

Returns the column text colour.

Parameters: column – an integer specifying the column index.

GetColumnCount(*args, **kwargs)

GetColumnFont(column) [source]

Returns the column text font.

Parameters: column – an integer specifying the column index.

GetColumnImage(column) [source]

Returns the image assigned to the specified column.

Parameters: column – an integer specifying the column index.

GetColumnText(column) [source]

Returns the column text label.

Parameters: column – an integer specifying the column index.

GetColumnWidth(column) [source]

Returns the column width, in pixels.

Parameters: column – an integer specifying the column index.

GetConnectionPen(*args, **kwargs)

GetCurrentItem(*args, **kwargs)

GetDisabledColour(*args, **kwargs)

GetEditControl(*args, **kwargs)

GetFirstChild(*args, **kwargs)

GetFirstExpandedItem(*args, **kwargs)

GetFirstGradientColour(*args, **kwargs)

GetFirstVisibleItem(*args, **kwargs)

GetGradientStyle(*args, **kwargs)

GetHeaderWindow() [source]

Returns the header window, an instance of TreeListHeaderWindow.

GetHilightFocusColour(*args, **kwargs)

GetHilightNonFocusColour(*args, **kwargs)

GetHyperTextFont(*args, **kwargs)

GetHyperTextNewColour(*args, **kwargs)

GetHyperTextVisitedColour(*args, **kwargs)

GetImageList(*args, **kwargs)

GetImageListCheck(*args, **kwargs)

GetIndent(*args, **kwargs)

GetItem3StateValue(*args, **kwargs)

GetItemBackgroundColour(*args, **kwargs)

GetItemFont(*args, **kwargs)

GetItemImage(*args, **kwargs)

GetItemParent(*args, **kwargs)

GetItemPyData(*args, **kwargs)

GetItemText(*args, **kwargs)

GetItemTextColour(*args, **kwargs)

GetItemType(*args, **kwargs)

GetItemVisited(*args, **kwargs)

GetItemWindow(*args, **kwargs)

GetItemWindowEnabled(*args, **kwargs)

GetLastChild(*args, **kwargs)

GetMainWindow() [source]

Returns the main window, an instance of TreeListMainWindow.

GetNext(*args, **kwargs)

GetNextChild(*args, **kwargs)

GetNextExpanded(*args, **kwargs)

GetNextSibling(*args, **kwargs)

GetNextVisible(*args, **kwargs)

GetPrev(*args, **kwargs)

GetPrevChild(*args, **kwargs)

GetPrevExpanded(*args, **kwargs)

GetPrevSibling(*args, **kwargs)

GetPrevVisible(*args, **kwargs)

GetPyData(*args, **kwargs)

GetRootItem(*args, **kwargs)

GetSecondGradientColour(*args, **kwargs)

GetSelection(*args, **kwargs)

GetSelections(*args, **kwargs)

GetSpacing(*args, **kwargs)

GetStateImageList(*args, **kwargs)

GetTextCtrlAlignmentStyle(column) [source]

Return the alignment style to use for the text control that is used to edit labels of items. The alignment style is derived from the column alignment.

Parameters: column – an integer specifying the column index.

GetTextCtrlStyle(column) [source]

Return the style to use for the text control that is used to edit labels of items.

Override this function in the derived class to support a different style, e.g. wx.TE_MULTILINE.

Parameters: column – an integer specifying the column index.

HasAGWFlag(flag) [source]

Returns whether a flag is present in the HyperTreeList style.

Parameters: flag – one of the possible HyperTreeList window styles.

See also

SetAGWWindowStyleFlag for a list of possible window style flags.

HasChildren(*args, **kwargs)

HideItem(*args, **kwargs)

HitTest(*args, **kwargs)

InsertColumn(before, text, width=_DEFAULT_COL_WIDTH, flag=wx.ALIGN_LEFT, image=-1, shown=True, colour=None, edit=False) [source]

Inserts a column to the HyperTreeList at the position specified by before.

Parameters:
  • before – the index at which we wish to insert the new column;
  • text – the column text label;
  • width – the column width in pixels;
  • flag – the column alignment flag, one of wx.ALIGN_LEFT, wx.ALIGN_RIGHT, wx.ALIGN_CENTER;
  • image – an index within the normal image list assigned to HyperTreeList specifying the image to use for the column;
  • shown – True to show the column, False to hide it;
  • colour – a valid wx.Colour, representing the text foreground colour for the column;

  • edit – True to set the column as editable, False otherwise.

InsertColumnInfo(before, colInfo) [source]

Inserts a column to the HyperTreeList at the position specified by before.

Parameters:
  • before – the index at which we wish to insert the new column;
  • colInfo – an instance of TreeListColumnInfo.

InsertItem(*args, **kwargs)

IsBold(*args, **kwargs)

IsColumnEditable(column) [source]

Returns True if the column is editable, False otherwise.

Parameters: column – an integer specifying the column index.

IsColumnShown(column) [source]

Returns True if the column is shown, False otherwise.

Parameters: column – an integer specifying the column index.

IsDescendantOf(*args, **kwargs)

IsExpanded(*args, **kwargs)

IsItem3State(*args, **kwargs)

IsItemChecked(*args, **kwargs)

IsItemEnabled(*args, **kwargs)

IsItemHyperText(*args, **kwargs)

IsItemVisible(*args, **kwargs)

IsSelected(*args, **kwargs)

ItemHasChildren(*args, **kwargs)

OnCompareItems(item1, item2) [source]

Returns whether 2 items have the same text.

Override this function in the derived class to change the sort order of the items in the HyperTreeList. The function should return a negative, zero or positive value if the first item is less than, equal to or greater than the second one.

Parameters:
  • item1 – an instance of TreeListItem;
  • item2 – another instance of TreeListItem.

Note

The base class version compares items alphabetically.

OnGetItemText(item, column) [source]

This function must be overloaded in the derived class for a control with TR_VIRTUAL style. It should return the string containing the text of the given column for the specified item.

Parameters:
  • item – an instance of TreeListItem;
  • column – an integer specifying the column index.

OnSize(event) [source]

Handles the wx.EVT_SIZE event for HyperTreeList.

Parameters: event – a wx.SizeEvent event to be processed.

PrependItem(*args, **kwargs)

Refresh(erase=True, rect=None) [source]

Causes this window, and all of its children recursively (except under wxGTK1 where this is not implemented), to be repainted.

Parameters:
  • erase – If True, the background will be erased;
  • rect – If not None, only the given rectangle will be treated as damaged.

Note

Note that repainting doesn’t happen immediately but only during the next event loop iteration, if you need to update the window immediately you should use Update instead.

Note

Overridden from wx.PyControl.

RemoveColumn(column) [source]

Removes a column from the HyperTreeList.

Parameters: column – an integer specifying the column index.

ScrollTo(*args, **kwargs)

SelectAll(*args, **kwargs)

SelectAllChildren(*args, **kwargs)

SelectItem(*args, **kwargs)

SetAGWWindowStyleFlag(agwStyle) [source]

Sets the window style for HyperTreeList.

Parameters: agwStyle – can be a combination of the following bits:

Window Styles | Hex Value | Description
TR_NO_BUTTONS | 0x0 | For convenience to document that no buttons are to be drawn.
TR_SINGLE | 0x0 | For convenience to document that only one item may be selected at a time. Selecting another item causes the current selection, if any, to be deselected. This is the default.
TR_HAS_BUTTONS | 0x1 | Use this style to show + and - buttons to the left of parent items.
TR_NO_LINES | 0x4 | Use this style to hide vertical level connectors.
TR_LINES_AT_ROOT | 0x8 | Use this style to show lines between root nodes. Only applicable if TR_HIDE_ROOT is set and TR_NO_LINES is not set.
TR_DEFAULT_STYLE | 0x9 | The set of flags that are closest to the defaults for the native control for a particular toolkit.
TR_TWIST_BUTTONS | 0x10 | Use old Mac-twist style buttons.
TR_MULTIPLE | 0x20 | Use this style to allow a range of items to be selected. If a second range is selected, the current range, if any, is deselected.
TR_EXTENDED | 0x40 | Use this style to allow disjoint items to be selected. (Only partially implemented; may not work in all cases).
TR_HAS_VARIABLE_ROW_HEIGHT | 0x80 | Use this style to cause row heights to be just big enough to fit the content. If not set, all rows use the largest row height. The default is that this flag is unset.
TR_EDIT_LABELS | 0x200 | Use this style if you wish the user to be able to edit labels in the tree control.
TR_ROW_LINES | 0x400 | Use this style to draw a contrasting border between displayed rows.
TR_HIDE_ROOT | 0x800 | Use this style to suppress the display of the root node, effectively causing the first-level nodes to appear as a series of root nodes.
TR_COLUMN_LINES | 0x1000 | Use this style to draw a contrasting border between displayed columns.
TR_FULL_ROW_HIGHLIGHT | 0x2000 | Use this style to have the background colour and the selection highlight extend over the entire horizontal row of the tree control window.
TR_AUTO_CHECK_CHILD | 0x4000 | Only meaningful foe checkbox-type items: when a parent item is checked/unchecked its children are checked/unchecked as well.
TR_AUTO_TOGGLE_CHILD | 0x8000 | Only meaningful foe checkbox-type items: when a parent item is checked/unchecked its children are toggled accordingly.
TR_AUTO_CHECK_PARENT | 0x10000 | Only meaningful foe checkbox-type items: when a child item is checked/unchecked its parent item is checked/unchecked as well.
TR_ALIGN_WINDOWS | 0x20000 | Flag used to align windows (in items with windows) at the same horizontal position.
TR_NO_HEADER | 0x40000 | Use this style to hide the columns header.
TR_ELLIPSIZE_LONG_ITEMS | 0x80000 | Flag used to ellipsize long items when the horizontal space for CustomTreeCtrl is low.
TR_VIRTUAL | 0x100000 | HyperTreeList will have virtual behaviour.

Note

Please note that some styles cannot be changed after the window creation and that Refresh() might need to be be called after changing the others for the change to take place immediately.

SetBackgroundColour(colour) [source]

Changes the background colour of HyperTreeList.

Parameters: colour – the colour to be used as the background colour, pass wx.NullColour to reset to the default colour.

Note

The background colour is usually painted by the default wx.EraseEvent event handler function under Windows and automatically under GTK.

Note

Setting the background colour does not cause an immediate refresh, so you may wish to call wx.Window.ClearBackground or wx.Window.Refresh after calling this function.

Note

Overridden from wx.PyControl.

SetBackgroundImage(*args, **kwargs)

SetBorderPen(*args, **kwargs)

SetBuffered(buffered) [source]

Sets/unsets the double buffering for the header and the main window.

Parameters: buffered – True to use double-buffering, False otherwise.

Note

Currently we are using double-buffering only on Windows XP.

SetButtonsImageList(*args, **kwargs)

SetColumn(column, colInfo) [source]

Sets a column using an instance of TreeListColumnInfo.

Parameters:
  • column – an integer specifying the column index;
  • info – an instance of TreeListColumnInfo.

SetColumnAlignment(column, flag) [source]

Sets the column text alignment.

Parameters:
  • column – an integer specifying the column index;
  • flag – the alignment flag, one of wx.ALIGN_LEFT, wx.ALIGN_RIGHT, wx.ALIGN_CENTER.

SetColumnColour(column, colour) [source]

Sets the column text colour.

Parameters:
  • column – an integer specifying the column index;
  • colour – a valid wx.Colour object.

SetColumnEditable(column, edit) [source]

Sets the column as editable or non-editable.

Parameters:
  • column – an integer specifying the column index;
  • edit – True if the column should be editable, False otherwise.

SetColumnFont(column, font) [source]

Sets the column text font.

Parameters:
  • column – an integer specifying the column index;
  • font – a valid wx.Font object.

SetColumnImage(column, image) [source]

Sets an image on the specified column.

Parameters:
  • column – an integer specifying the column index.
  • image – an index within the normal image list assigned to HyperTreeList specifying the image to use for the column.

SetColumnShown(column, shown) [source]

Sets the column as shown or hidden.

Parameters:
  • column – an integer specifying the column index;
  • shown – True if the column should be shown, False if it should be hidden.

SetColumnText(column, text) [source]

Sets the column text label.

Parameters:
  • column – an integer specifying the column index;
  • text – the new column label.

SetColumnWidth(column, width) [source]

Sets the column width, in pixels.

Parameters:
  • column – an integer specifying the column index;
  • width – the new column width, in pixels.

SetConnectionPen(*args, **kwargs)

SetDisabledColour(*args, **kwargs)

SetDragItem(*args, **kwargs)

SetFirstGradientColour(*args, **kwargs)

SetFocus() [source]

This sets the window to receive keyboard input.

SetFont(font) [source]

Sets the default font for the header window and the main window.

Parameters: font – a valid wx.Font object.

SetForegroundColour(colour) [source]

Changes the foreground colour of HyperTreeList.

Parameters: colour – the colour to be used as the foreground colour, pass wx.NullColour to reset to the default colour.

Note

Overridden from wx.PyControl.

SetGradientStyle(*args, **kwargs)

SetHeaderCustomRenderer(renderer=None) [source]

Associate a custom renderer with the header - all columns will use it

Parameters: renderer – a class able to correctly render header buttons

Note

the renderer class must implement the method DrawHeaderButton

SetHeaderFont(font) [source]

Sets the default font for the header window..

Parameters: font – a valid wx.Font object.

SetHilightFocusColour(*args, **kwargs)

SetHilightNonFocusColour(*args, **kwargs)

SetHyperTextFont(*args, **kwargs)

SetHyperTextNewColour(*args, **kwargs)

SetHyperTextVisitedColour(*args, **kwargs)

SetImageList(*args, **kwargs)

SetImageListCheck(*args, **kwargs)

SetIndent(*args, **kwargs)

SetItem3State(*args, **kwargs)

SetItem3StateValue(*args, **kwargs)

SetItemBackgroundColour(*args, **kwargs)

SetItemBold(*args, **kwargs)

SetItemDropHighlight(*args, **kwargs)

SetItemFont(*args, **kwargs)

SetItemHasChildren(*args, **kwargs)

SetItemHyperText(*args, **kwargs)

SetItemImage(*args, **kwargs)

SetItemItalic(*args, **kwargs)

SetItemPyData(*args, **kwargs)

SetItemText(*args, **kwargs)

SetItemTextColour(*args, **kwargs)

SetItemType(*args, **kwargs)

SetItemVisited(*args, **kwargs)

SetItemWindow(*args, **kwargs)

SetItemWindowEnabled(*args, **kwargs)

SetMainColumn(*args, **kwargs)

SetPyData(*args, **kwargs)

SetSecondGradientColour(*args, **kwargs)

SetSpacing(*args, **kwargs)

SetStateImageList(*args, **kwargs)

ShouldInheritColours(*args, **kwargs)

SortChildren(item) [source]

Sorts the children of the given item using OnCompareItems method of HyperTreeList. You should override that method to change the sort order (the default is ascending case-sensitive alphabetical order).

Parameters: item – an instance of TreeListItem;

Toggle(*args, **kwargs)

ToggleItemSelection(*args, **kwargs)

UnCheckRadioParent(*args, **kwargs)

Unselect(*args, **kwargs)

UnselectAll(*args, **kwargs)

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • infobar
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • hypertreelist »
  • HyperTreeList


TreeListColumnInfo

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • hypertreelist »
  • TreeListColumnInfo

TreeListColumnInfo

Class used to store information (width, alignment flags, colours, etc...) about a HyperTreeList column header.

hierarchy Inheritance Diagram

Inheritance diagram for: TreeListColumnInfo

Inheritance diagram of TreeListColumnInfo

Methods Summary

__init__ | Default class constructor.
GetAlignment | Returns the column text alignment.
GetColour | Returns the column text colour.
GetFont | Returns the column text font.
GetImage | Returns the column image index.
GetSelectedImage | Returns the column image index in the selected state.
GetText | Returns the column header label.
GetWidth | Returns the column header width in pixels.
IsEditable | Returns True if the column is editable, False otherwise.
IsShown | Returns True if the column is shown, False if it is hidden.
SetAlignment | Sets the column text alignment.
SetColour | Sets the column text colour.
SetEditable | Sets the column as editable or non-editable.
SetFont | Sets the column text font.
SetImage | Sets the column image index.
SetSelectedImage | Sets the column image index in the selected state.
SetShown | Sets the column as shown or hidden.
SetText | Sets the column header label.
SetWidth | Sets the column header width.

API Class API

class TreeListColumnInfo(object) [source]

Class used to store information (width, alignment flags, colours, etc...) about a HyperTreeList column header.

__init__(input="", width=_DEFAULT_COL_WIDTH, flag=wx.ALIGN_LEFT, image=-1, shown=True, colour=None, edit=False) [source]

Default class constructor.

Parameters:
  • input – can be a string (representing the column header text) or another instance of TreeListColumnInfo. In the latter case, all the other input parameters are not used;
  • width – the column width in pixels;
  • flag – the column alignment flag, one of wx.ALIGN_LEFT, wx.ALIGN_RIGHT, wx.ALIGN_CENTER;
  • image – an index within the normal image list assigned to HyperTreeList specifying the image to use for the column;
  • shown – True to show the column, False to hide it;
  • colour – a valid wx.Colour, representing the text foreground colour for the column;
  • edit – True to set the column as editable, False otherwise.

GetAlignment() [source]

Returns the column text alignment.

GetColour() [source]

Returns the column text colour.

GetFont() [source]

Returns the column text font.

GetImage() [source]

Returns the column image index.

GetSelectedImage() [source]

Returns the column image index in the selected state.

GetText() [source]

Returns the column header label.

GetWidth() [source]

Returns the column header width in pixels.

IsEditable() [source]

Returns True if the column is editable, False otherwise.

IsShown() [source]

Returns True if the column is shown, False if it is hidden.

SetAlignment(flag) [source]

Sets the column text alignment.

Parameters: flag – the alignment flag, one of wx.ALIGN_LEFT, wx.ALIGN_RIGHT, wx.ALIGN_CENTER.

SetColour(colour) [source]

Sets the column text colour.

Parameters: colour – a valid wx.Colour object.

SetEditable(edit) [source]

Sets the column as editable or non-editable.

Parameters: edit – True if the column should be editable, False otherwise.

SetFont(font) [source]

Sets the column text font.

Parameters: font – a valid wx.Font object.

SetImage(image) [source]

Sets the column image index.

Parameters: image – an index within the normal image list assigned to HyperTreeList specifying the image to use for the column.

SetSelectedImage(image) [source]

Sets the column image index in the selected state.

Parameters: image – an index within the normal image list assigned to HyperTreeList specifying the image to use for the column when in selected state.

SetShown(shown) [source]

Sets the column as shown or hidden.

Parameters: shown – True if the column should be shown, False if it should be hidden.

SetText(text) [source]

Sets the column header label.

Parameters: text – the new column header text.

SetWidth(width) [source]

Sets the column header width.

Parameters: width – the column header width, in pixels.

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • infobar
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • hypertreelist »
  • TreeListColumnInfo


TreeListHeaderWindow

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • hypertreelist »
  • TreeListHeaderWindow

TreeListHeaderWindow

A window which holds the header of HyperTreeList.

hierarchy Inheritance Diagram

Inheritance diagram for: TreeListHeaderWindow

Inheritance diagram of TreeListHeaderWindow

Methods Summary

__init__ | Default class constructor.
AddColumn | Appends a column to the TreeListHeaderWindow.
AddColumnInfo | Appends a column to the TreeListHeaderWindow.
AdjustDC | Shifts the wx.DC origin to match the position of the main window horizontal
DrawCurrent | Draws the column resize line on a wx.ScreenDC.
GetColumn | Returns a column item, an instance of TreeListItem.
GetColumnAlignment | Returns the column text alignment.
GetColumnColour | Returns the column text colour.
GetColumnCount | Returns the total number of columns.
GetColumnText | Returns the column text label.
GetColumnWidth | Returns the column width, in pixels.
GetWidth | Returns the total width of all columns.
InsertColumn | Inserts a column to the TreeListHeaderWindow at the position specified
InsertColumnInfo | Inserts a column to the TreeListHeaderWindow at the position specified
IsColumnEditable | Returns True if the column is editable, False otherwise.
IsColumnShown | Returns True if the column is shown, False if it is hidden.
OnMouse | Handles the wx.EVT_MOUSE_EVENTS event for TreeListHeaderWindow.
OnPaint | Handles the wx.EVT_PAINT event for TreeListHeaderWindow.
OnSetFocus | Handles the wx.EVT_SET_FOCUS event for TreeListHeaderWindow.
RefreshColLabel | Redraws the column.
RemoveColumn | Removes a column from the TreeListHeaderWindow.
SendListEvent | Sends a wx.ListEvent for the parent window.
SetBuffered | Sets/unsets the double buffering for the header.
SetColumn | Sets a column using an instance of TreeListColumnInfo.
SetColumnAlignment | Sets the column text alignment.
SetColumnColour | Sets the column text colour.
SetColumnText | Sets the column text label.
SetColumnWidth | Sets the column width, in pixels.
SetCustomRenderer | Associate a custom renderer with the header - all columns will use it :param renderer: a class able to correctly render header buttons ..
XToCol | Returns the column that corresponds to the logical input x coordinate.

API Class API

class TreeListHeaderWindow(wx.Window) [source]

A window which holds the header of HyperTreeList.

__init__(parent, id=wx.ID_ANY, owner=None, pos=wx.DefaultPosition, size=wx.DefaultSize, style=0, name="wxtreelistctrlcolumntitles") [source]

Default class constructor.

Parameters:
  • parent – the window parent. Must not be None;
  • id – window identifier. A value of -1 indicates a default value;
  • owner – the window owner, in this case an instance of TreeListMainWindow;
  • pos – the control position. A value of (-1, -1) indicates a default position, chosen by either the windowing system or wxPython, depending on platform;
  • size – the control size. A value of (-1, -1) indicates a default size, chosen by either the windowing system or wxPython, depending on platform;
  • style – the window style;
  • name – the window name.

AddColumn(text, width=_DEFAULT_COL_WIDTH, flag=wx.ALIGN_LEFT, image=-1, shown=True, colour=None, edit=False) [source]

Appends a column to the TreeListHeaderWindow.

Parameters:
  • text – the column text label;
  • width – the column width in pixels;
  • flag – the column alignment flag, one of wx.ALIGN_LEFT, wx.ALIGN_RIGHT, wx.ALIGN_CENTER;
  • image – an index within the normal image list assigned to HyperTreeList specifying the image to use for the column;
  • shown – True to show the column, False to hide it;
  • colour – a valid wx.Colour, representing the text foreground colour for the column;
  • edit – True to set the column as editable, False otherwise.

AddColumnInfo(colInfo) [source]

Appends a column to the TreeListHeaderWindow.

Parameters: colInfo – an instance of TreeListColumnInfo.

AdjustDC(dc) [source]

Shifts the wx.DC origin to match the position of the main window horizontal scrollbar: this allows us to always use logical coordinates.

Parameters: dc – an instance of wx.DC.

DrawCurrent() [source]

Draws the column resize line on a wx.ScreenDC.

GetColumn(column) [source]

Returns a column item, an instance of TreeListItem.

Parameters: column – an integer specifying the column index.

GetColumnAlignment(column) [source]

Returns the column text alignment.

Parameters: column – an integer specifying the column index.

GetColumnColour(column) [source]

Returns the column text colour.

Parameters: column – an integer specifying the column index.

GetColumnCount() [source]

Returns the total number of columns.

GetColumnText(column) [source]

Returns the column text label.

Parameters: column – an integer specifying the column index.

GetColumnWidth(column) [source]

Returns the column width, in pixels.

Parameters: column – an integer specifying the column index.

GetWidth() [source]

Returns the total width of all columns.

InsertColumn(before, text, width=_DEFAULT_COL_WIDTH, flag=wx.ALIGN_LEFT, image=-1, shown=True, colour=None, edit=False) [source]

Inserts a column to the TreeListHeaderWindow at the position specified by before.

Parameters:
  • before – the index at which we wish to insert the new column;
  • text – the column text label;
  • width – the column width in pixels;
  • flag – the column alignment flag, one of wx.ALIGN_LEFT, wx.ALIGN_RIGHT, wx.ALIGN_CENTER;
  • image – an index within the normal image list assigned to HyperTreeList specifying the image to use for the column;
  • shown – True to show the column, False to hide it;
  • colour – a valid wx.Colour, representing the text foreground colour for the column;

  • edit – True to set the column as editable, False otherwise.

InsertColumnInfo(before, colInfo) [source]

Inserts a column to the TreeListHeaderWindow at the position specified by before.

Parameters:
  • before – the index at which we wish to insert the new column;
  • colInfo – an instance of TreeListColumnInfo.

IsColumnEditable(column) [source]

Returns True if the column is editable, False otherwise.

Parameters: column – an integer specifying the column index.

IsColumnShown(column) [source]

Returns True if the column is shown, False if it is hidden.

Parameters: column – an integer specifying the column index.

OnMouse(event) [source]

Handles the wx.EVT_MOUSE_EVENTS event for TreeListHeaderWindow.

Parameters: event – a wx.MouseEvent event to be processed.

OnPaint(event) [source]

Handles the wx.EVT_PAINT event for TreeListHeaderWindow.

Parameters: event – a wx.PaintEvent event to be processed.

OnSetFocus(event) [source]

Handles the wx.EVT_SET_FOCUS event for TreeListHeaderWindow.

Parameters: event – a wx.FocusEvent event to be processed.

RefreshColLabel(col) [source]

Redraws the column.

Parameters: col – the index of the column to redraw.

RemoveColumn(column) [source]

Removes a column from the TreeListHeaderWindow.

Parameters: column – an integer specifying the column index.

SendListEvent(evtType, pos) [source]

Sends a wx.ListEvent for the parent window.

Parameters:
  • evtType – the event type;
  • pos – an instance of wx.Point.

SetBuffered(buffered) [source]

Sets/unsets the double buffering for the header.

Parameters: buffered – True to use double-buffering, False otherwise.

Note

Currently we are using double-buffering only on Windows XP.

SetColumn(column, info) [source]

Sets a column using an instance of TreeListColumnInfo.

Parameters:
  • column – an integer specifying the column index;
  • info – an instance of TreeListColumnInfo.

SetColumnAlignment(column, flag) [source]

Sets the column text alignment.

Parameters:
  • column – an integer specifying the column index;
  • flag – the new text alignment flag.

See also

TreeListColumnInfo.SetAlignment() for a list of valid alignment flags.

SetColumnColour(column, colour) [source]

Sets the column text colour.

Parameters:
  • column – an integer specifying the column index;
  • colour – a valid wx.Colour object.

SetColumnText(column, text) [source]

Sets the column text label.

Parameters:
  • column – an integer specifying the column index;
  • text – the new column label.

SetColumnWidth(column, width) [source]

Sets the column width, in pixels.

Parameters:
  • column – an integer specifying the column index;
  • width – the new width for the column, in pixels.

SetCustomRenderer(renderer=None) [source]

Associate a custom renderer with the header - all columns will use it

Parameters: renderer – a class able to correctly render header buttons

Note

the renderer class must implement the method DrawHeaderButton

XToCol(x) [source]

Returns the column that corresponds to the logical input x coordinate.

Parameters: x – the x position to evaluate.
Returns: The column that corresponds to the logical input x coordinate, or wx.NOT_FOUND if there is no column at the x position.

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • infobar
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • hypertreelist »
  • TreeListHeaderWindow


TreeListItem

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • hypertreelist »
  • TreeListItem

TreeListItem

This class holds all the information and methods for every single item in HyperTreeList.

Note

Subclassed from GenericTreeItem.

hierarchy Inheritance Diagram

Inheritance diagram for: TreeListItem

Inheritance diagram of TreeListItem

supclasses Known Superclasses

  • customtreectrl.GenericTreeItem

Methods Summary

__init__ | Default class constructor.
DeleteChildren | Deletes the item children.
DeleteWindow | Deletes the window associated to the item (if any).
GetCurrentImage | Returns the current item image.
GetImage | Returns the item image for a particular item state.
GetText | Returns the item text label.
GetTextX | Returns the x position of the item text.
GetWindow | Returns the window associated to the item.
GetWindowEnabled | Returns whether the window associated with an item is enabled or not.
GetWindowSize | Returns the associated window size.
Hide | Hides/shows the TreeListItem.
HitTest | HitTest method for an item. Called from the main window HitTest.
IsHidden | Returns whether the item is hidden or not.
OnSetFocus | Handles the wx.EVT_SET_FOCUS event for a window associated to an item.
SetImage | Sets the item image for a particular item state.
SetText | Sets the item text label.
SetTextX | Sets the x position of the item text.
SetWindow | Sets the window associated to the item.
SetWindowEnabled | Sets whether the window associated with an item is enabled or not.

API Class API

class TreeListItem(GenericTreeItem) [source]

This class holds all the information and methods for every single item in HyperTreeList.

Note

Subclassed from GenericTreeItem.

__init__(mainWin, parent, text=[], ct_type=0, wnd=None, image=-1, selImage=-1, data=None) [source]

Default class constructor. For internal use: do not call it in your code!

Parameters:
  • mainWin – the main HyperTreeList window, in this case an instance of TreeListMainWindow;
  • parent – the tree item parent (may be None for root items);
  • text – the tree item text;
  • ct_type – the tree item kind. May be one of the following integers:

    ct_type Value | Description
    0 | A normal item
    1 | A checkbox-like item
    2 | A radiobutton-type item
  • wnd – if not None, a non-toplevel window to be displayed next to the item;
  • image – an index within the normal image list specifying the image to use for the item in unselected state;
  • selImage – an index within the normal image list specifying the image to use for the item in selected state; if image > -1 and selImage is -1, the same image is used for both selected and unselected items;
  • data – associate the given Python object data with the item.

Note

Regarding radiobutton-type items (with ct_type = 2), the following approach is used:

  • All peer-nodes that are radiobuttons will be mutually exclusive. In other words, only one of a set of radiobuttons that share a common parent can be checked at once. If a radiobutton node becomes checked, then all of its peer radiobuttons must be unchecked.
  • If a radiobutton node becomes unchecked, then all of its child nodes will become inactive.

DeleteChildren(tree) [source]

Deletes the item children.

Parameters: tree – the main TreeListMainWindow instance.

DeleteWindow(column=None) [source]

Deletes the window associated to the item (if any).

Parameters: column – if not None, an integer specifying the column index. If it is None, the main column index is used.

GetCurrentImage(column=None) [source]

Returns the current item image.

Parameters: column – if not None, an integer specifying the column index. If it is None, the main column index is used.

GetImage(which=wx.TreeItemIcon_Normal, column=None) [source]

Returns the item image for a particular item state.

Parameters:
  • which – can be one of the following bits:

    Item State | Description
    TreeItemIcon_Normal | To get the normal item image
    TreeItemIcon_Selected | To get the selected item image (i.e. the image which is shown when the item is currently selected)
    TreeItemIcon_Expanded | To get the expanded image (this only makes sense for items which have children - then this image is shown when the item is expanded and the normal image is shown when it is collapsed)
    TreeItemIcon_SelectedExpanded | To get the selected expanded image (which is shown when an expanded item is currently selected)
  • column – if not None, an integer specifying the column index. If it is None, the main column index is used.

GetText(column=None) [source]

Returns the item text label.

Parameters: column – if not None, an integer specifying the column index. If it is None, the main column index is used.

GetTextX() [source]

Returns the x position of the item text.

GetWindow(column=None) [source]

Returns the window associated to the item.

Parameters: column – if not None, an integer specifying the column index. If it is None, the main column index is used.

GetWindowEnabled(column=None) [source]

Returns whether the window associated with an item is enabled or not.

Parameters: column – if not None, an integer specifying the column index. If it is None, the main column index is used.

GetWindowSize(column=None) [source]

Returns the associated window size.

Parameters: column – if not None, an integer specifying the column index. If it is None, the main column index is used.

Hide(hide) [source]

Hides/shows the TreeListItem.

Parameters: hide – True to hide the item, False to show it.

HitTest(point, theCtrl, flags, column, level) [source]

HitTest method for an item. Called from the main window HitTest.

Parameters:
  • point – the point to test for the hit (an instance of wx.Point);
  • theCtrl – the main TreeListMainWindow tree;
  • flags – a bitlist of hit locations;
  • column – an integer specifying the column index;
  • level – the item’s level inside the tree hierarchy.

See also

TreeListMainWindow.HitTest() method for the flags explanation.

IsHidden() [source]

Returns whether the item is hidden or not.

OnSetFocus(event) [source]

Handles the wx.EVT_SET_FOCUS event for a window associated to an item.

Parameters: event – a wx.FocusEvent event to be processed.

SetImage(column, image, which) [source]

Sets the item image for a particular item state.

Parameters:
  • column – if not None, an integer specifying the column index. If it is None, the main column index is used;
  • image – an index within the normal image list specifying the image to use;
  • which – the item state.

See also

GetImage for a list of valid item states.

SetText(column, text) [source]

Sets the item text label.

Parameters:
  • column – if not None, an integer specifying the column index. If it is None, the main column index is used;
  • text – a string specifying the new item label.

SetTextX(text_x) [source]

Sets the x position of the item text.

Parameters: text_x – the x position of the item text.

SetWindow(wnd, column=None) [source]

Sets the window associated to the item.

Parameters:
  • wnd – a non-toplevel window to be displayed next to the item;
  • column – if not None, an integer specifying the column index. If it is None, the main column index is used.

SetWindowEnabled(enable=True, column=None) [source]

Sets whether the window associated with an item is enabled or not.

Parameters:
  • enable – True to enable the associated window, False to disable it;
  • column – if not None, an integer specifying the column index. If it is None, the main column index is used.

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • infobar
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • hypertreelist »
  • TreeListItem


TreeListMainWindow

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • hypertreelist »
  • TreeListMainWindow

TreeListMainWindow

This class represents the main window (and thus the main column) in HyperTreeList.

Note

This is a subclass of CustomTreeCtrl.

hierarchy Inheritance Diagram

Inheritance diagram for: TreeListMainWindow

Inheritance diagram of TreeListMainWindow

supclasses Known Superclasses

  • customtreectrl.CustomTreeCtrl

Methods Summary

__init__ | Default class constructor.
AddRoot | Adds a root item to the TreeListMainWindow.
AdjustMyScrollbars | Internal method used to adjust the wx.PyScrolledWindow scrollbars.
CalculateLevel | Calculates the level of an item inside the tree hierarchy.
CalculatePositions | Recalculates all the items positions.
CalculateSize | Calculates overall position and size of an item.
ChildrenClosing | We are about to destroy the item’s children.
Delete | Deletes an item.
DeleteAllItems | Delete all items in the TreeListMainWindow.
DeleteRoot | Removes the tree root item (and subsequently all the items in
DoInsertItem | Actually inserts an item in the tree.
EditLabel | Starts editing an item label.
EnableItem | Enables/disables an item.
GetBestColumnWidth | Returns the best column’s width based on the items width in this column.
GetColumnCount | Returns the total number of columns.
GetCurrentItem | Returns the current item.
GetFirstExpandedItem | Returns the first item which is in the expanded state.
GetFirstVisibleItem | Returns the first visible item.
GetItemImage | Returns the item image.
GetItemText | Returns the item text label.
GetItemWidth | Returns the item width.
GetItemWindow | Returns the window associated with an item.
GetItemWindowEnabled | Returns whether the window associated with an item is enabled or not.
GetMainColumn | Returns the HyperTreeList main column (i.e. the position of the underlying
GetNextExpanded | Returns the next expanded item after the input one.
GetPrevChild | Returns the previous child of an item.
GetPrevExpanded | Returns the previous expanded item before the input one.
GetPrevVisible | Returns the previous visible item before the input one.
HideItem | Hides/shows an item.
HideWindows | Hides the windows associated to the items.
HitTest | Calculates which (if any) item is under the given point, returning the tree item at this point plus extra information flags plus the item’s column.
IsItemEnabled | Returns whether an item is enabled or disabled.
IsItemVisible | Returns whether the item is visible or not.
IsVirtual | Returns True if TreeListMainWindow has the TR_VIRTUAL flag set.
OnAcceptEdit | Called by EditTextCtrl, to accept the changes and to send the
OnCancelEdit | Called by EditCtrl, to cancel the changes and to send the
OnEditTimer | The timer for editing has expired.
OnEraseBackground | Handles the wx.EVT_ERASE_BACKGROUND event for TreeListMainWindow.
OnMouse | Handles the wx.EVT_MOUSE_EVENTS event for TreeListMainWindow.
OnPaint | Handles the wx.EVT_PAINT event for TreeListMainWindow.
OnScroll | Handles the wx.EVT_SCROLLWIN event for TreeListMainWindow.
PaintItem | Actually draws an item.
PaintLevel | Paint a level in the hierarchy of TreeListMainWindow.
ScrollTo | Scrolls the specified item into view.
SetBuffered | Sets/unsets the double buffering for the main window.
SetDragItem | Sets the specified item as member of a current drag and drop operation.
SetItemImage | Sets the item image for a particular item state.
SetItemText | Sets the item text label.
SetItemWindow | Sets the window associated to an item.
SetItemWindowEnabled | Sets whether the window associated with an item is enabled or not.
SetMainColumn | Sets the HyperTreeList main column (i.e. the position of the underlying

API Class API

class TreeListMainWindow(CustomTreeCtrl) [source]

This class represents the main window (and thus the main column) in HyperTreeList.

Note

This is a subclass of CustomTreeCtrl.

__init__(parent, id=wx.ID_ANY, pos=wx.DefaultPosition, size=wx.DefaultSize, style=0, agwStyle=wx.TR_DEFAULT_STYLE, validator=wx.DefaultValidator, name="wxtreelistmainwindow") [source]

Default class constructor.

Parameters:
  • parent – parent window. Must not be None;
  • id – window identifier. A value of -1 indicates a default value;
  • pos – the control position. A value of (-1, -1) indicates a default position, chosen by either the windowing system or wxPython, depending on platform;
  • size – the control size. A value of (-1, -1) indicates a default size, chosen by either the windowing system or wxPython, depending on platform;
  • style – the underlying wx.PyScrolledWindow style;
  • agwStyle – the AGW-specific TreeListMainWindow window style. This can be a combination of the following bits:

    Window Styles | Hex Value | Description
    TR_NO_BUTTONS | 0x0 | For convenience to document that no buttons are to be drawn.
    TR_SINGLE | 0x0 | For convenience to document that only one item may be selected at a time. Selecting another item causes the current selection, if any, to be deselected. This is the default.
    TR_HAS_BUTTONS | 0x1 | Use this style to show + and - buttons to the left of parent items.
    TR_NO_LINES | 0x4 | Use this style to hide vertical level connectors.
    TR_LINES_AT_ROOT | 0x8 | Use this style to show lines between root nodes. Only applicable if TR_HIDE_ROOT is set and TR_NO_LINES is not set.
    TR_DEFAULT_STYLE | 0x9 | The set of flags that are closest to the defaults for the native control for a particular toolkit.
    TR_TWIST_BUTTONS | 0x10 | Use old Mac-twist style buttons.
    TR_MULTIPLE | 0x20 | Use this style to allow a range of items to be selected. If a second range is selected, the current range, if any, is deselected.
    TR_EXTENDED | 0x40 | Use this style to allow disjoint items to be selected. (Only partially implemented; may not work in all cases).
    TR_HAS_VARIABLE_ROW_HEIGHT | 0x80 | Use this style to cause row heights to be just big enough to fit the content. If not set, all rows use the largest row height. The default is that this flag is unset.
    TR_EDIT_LABELS | 0x200 | Use this style if you wish the user to be able to edit labels in the tree control.
    TR_ROW_LINES | 0x400 | Use this style to draw a contrasting border between displayed rows.
    TR_HIDE_ROOT | 0x800 | Use this style to suppress the display of the root node, effectively causing the first-level nodes to appear as a series of root nodes.
    TR_FULL_ROW_HIGHLIGHT | 0x2000 | Use this style to have the background colour and the selection highlight extend over the entire horizontal row of the tree control window.
    TR_AUTO_CHECK_CHILD | 0x4000 | Only meaningful foe checkbox-type items: when a parent item is checked/unchecked its children are checked/unchecked as well.
    TR_AUTO_TOGGLE_CHILD | 0x8000 | Only meaningful foe checkbox-type items: when a parent item is checked/unchecked its children are toggled accordingly.
    TR_AUTO_CHECK_PARENT | 0x10000 | Only meaningful foe checkbox-type items: when a child item is checked/unchecked its parent item is checked/unchecked as well.
    TR_ALIGN_WINDOWS | 0x20000 | Flag used to align windows (in items with windows) at the same horizontal position.
    TR_NO_HEADER | 0x40000 | Use this style to hide the columns header.
    TR_ELLIPSIZE_LONG_ITEMS | 0x80000 | Flag used to ellipsize long items when the horizontal space for CustomTreeCtrl is low.
    TR_VIRTUAL | 0x100000 | HyperTreeList will have virtual behaviour.
  • validator – window validator;
  • name – window name.

AddRoot(text, ct_type=0, wnd=None, image=-1, selImage=-1, data=None) [source]

Adds a root item to the TreeListMainWindow.

Parameters:
  • text – the item text label;
  • ct_type – the item type (see CustomTreeCtrl.SetItemType() for a list of valid item types);
  • wnd – if not None, a non-toplevel window to show next to the item;
  • image – an index within the normal image list specifying the image to use for the item in unselected state;
  • selImage – an index within the normal image list specifying the image to use for the item in selected state; if image > -1 and selImage is -1, the same image is used for both selected and unselected items;
  • data – associate the given Python object data with the item.

Warning

only one root is allowed to exist in any given instance of TreeListMainWindow.

AdjustMyScrollbars() [source]

Internal method used to adjust the wx.PyScrolledWindow scrollbars.

CalculateLevel(item, dc, level, y, x_colstart) [source]

Calculates the level of an item inside the tree hierarchy.

Parameters:
  • item – an instance of TreeListItem;
  • dc – an instance of wx.DC;
  • level – the item level in the tree hierarchy;
  • y – the current vertical position inside the wx.PyScrolledWindow;
  • x_colstart – the x coordinate at which the item’s column starts.

CalculatePositions() [source]

Recalculates all the items positions.

CalculateSize(item, dc) [source]

Calculates overall position and size of an item.

Parameters:
  • item – an instance of TreeListItem;
  • dc – an instance of wx.DC.

ChildrenClosing(item) [source]

We are about to destroy the item’s children.

Parameters: item – an instance of TreeListItem.

Delete(item) [source]

Deletes an item.

Parameters: item – an instance of TreeListItem.

DeleteAllItems() [source]

Delete all items in the TreeListMainWindow.

DeleteRoot() [source]

Removes the tree root item (and subsequently all the items in TreeListMainWindow.

DoInsertItem(parent, previous, text, ct_type=0, wnd=None, image=-1, selImage=-1, data=None) [source]

Actually inserts an item in the tree.

Parameters:
  • parentId – an instance of TreeListItem representing the item’s parent;
  • previous – the index at which we should insert the item;
  • text – the item text label;
  • ct_type – the item type (see CustomTreeCtrl.SetItemType() for a list of valid item types);
  • wnd – if not None, a non-toplevel window to show next to the item;
  • image – an index within the normal image list specifying the image to use for the item in unselected state;
  • selImage – an index within the normal image list specifying the image to use for the item in selected state; if image > -1 and selImage is -1, the same image is used for both selected and unselected items;
  • data – associate the given Python object data with the item.

EditLabel(item, column=None) [source]

Starts editing an item label.

Parameters:
  • item – an instance of TreeListItem;
  • column – if not None, an integer specifying the column index. If it is None, the main column index is used.

EnableItem(item, enable=True, torefresh=True) [source]

Enables/disables an item.

Parameters:
  • item – an instance of TreeListItem;
  • enable – True to enable the item, False otherwise;
  • torefresh – whether to redraw the item or not.

GetBestColumnWidth(column, parent=None) [source]

Returns the best column’s width based on the items width in this column.

Parameters:
  • column – an integer specifying the column index;
  • parent – an instance of TreeListItem.

GetColumnCount() [source]

Returns the total number of columns.

GetCurrentItem() [source]

Returns the current item.

GetFirstExpandedItem() [source]

Returns the first item which is in the expanded state.

GetFirstVisibleItem() [source]

Returns the first visible item.

GetItemImage(item, column=None, which=wx.TreeItemIcon_Normal) [source]

Returns the item image.

Parameters:
  • item – an instance of TreeListItem;
  • column – if not None, an integer specifying the column index. If it is None, the main column index is used;
  • which – can be one of the following bits:

    Item State | Description
    TreeItemIcon_Normal | To get the normal item image
    TreeItemIcon_Selected | To get the selected item image (i.e. the image which is shown when the item is currently selected)
    TreeItemIcon_Expanded | To get the expanded image (this only makes sense for items which have children - then this image is shown when the item is expanded and the normal image is shown when it is collapsed)
    TreeItemIcon_SelectedExpanded | To get the selected expanded image (which is shown when an expanded item is currently selected)

GetItemText(item, column=None) [source]

Returns the item text label.

Parameters:
  • item – an instance of TreeListItem;
  • column – if not None, an integer specifying the column index. If it is None, the main column index is used.

GetItemWidth(item, column) [source]

Returns the item width.

Parameters:
  • item – an instance of TreeListItem;
  • column – an integer specifying the column index.

GetItemWindow(item, column=None) [source]

Returns the window associated with an item.

Parameters:
  • item – an instance of TreeListItem;
  • column – if not None, an integer specifying the column index. If it is None, the main column index is used.

GetItemWindowEnabled(item, column=None) [source]

Returns whether the window associated with an item is enabled or not.

Parameters:
  • item – an instance of TreeListItem;
  • column – if not None, an integer specifying the column index. If it is None, the main column index is used.

GetMainColumn() [source]

Returns the HyperTreeList main column (i.e. the position of the underlying CustomTreeCtrl.

GetNextExpanded(item) [source]

Returns the next expanded item after the input one.

Parameters: item – an instance of TreeListItem.

GetPrevChild(item, cookie) [source]

Returns the previous child of an item.

Parameters:
  • item – an instance of TreeListItem;
  • cookie – a parameter which is opaque for the application but is necessary for the library to make these functions reentrant (i.e. allow more than one enumeration on one and the same object simultaneously).

Note

This method returns None if there are no further siblings.

GetPrevExpanded(item) [source]

Returns the previous expanded item before the input one.

Parameters: item – an instance of TreeListItem.

GetPrevVisible(item) [source]

Returns the previous visible item before the input one.

Parameters: item – an instance of TreeListItem.

HideItem(item, hide=True) [source]

Hides/shows an item.

Parameters:
  • item – an instance of TreeListItem;
  • hide – True to hide the item, False to show it.

HideWindows() [source]

Hides the windows associated to the items. Used internally.

HitTest(point, flags=0) [source]

Calculates which (if any) item is under the given point, returning the tree item at this point plus extra information flags plus the item’s column.

Parameters:
  • point – an instance of wx.Point, a point to test for hits;
  • flags – a bitlist of the following values:

    HitTest Flags | Hex Value | Description
    TREE_HITTEST_ABOVE | 0x1 | Above the client area
    TREE_HITTEST_BELOW | 0x2 | Below the client area
    TREE_HITTEST_NOWHERE | 0x4 | No item has been hit
    TREE_HITTEST_ONITEMBUTTON | 0x8 | On the button associated to an item
    TREE_HITTEST_ONITEMICON | 0x10 | On the icon associated to an item
    TREE_HITTEST_ONITEMINDENT | 0x20 | On the indent associated to an item
    TREE_HITTEST_ONITEMLABEL | 0x40 | On the label (string) associated to an item
    TREE_HITTEST_ONITEM | 0x50 | Anywhere on the item
    TREE_HITTEST_ONITEMRIGHT | 0x80 | On the right of the label associated to an item
    TREE_HITTEST_TOLEFT | 0x200 | On the left of the client area
    TREE_HITTEST_TORIGHT | 0x400 | On the right of the client area
    TREE_HITTEST_ONITEMUPPERPART | 0x800 | On the upper part (first half) of the item
    TREE_HITTEST_ONITEMLOWERPART | 0x1000 | On the lower part (second half) of the item
    TREE_HITTEST_ONITEMCHECKICON | 0x2000 | On the check/radio icon, if present
Returns:

the item (if any, None otherwise), the flags and the column are always returned as a tuple.

IsItemEnabled(item) [source]

Returns whether an item is enabled or disabled.

Parameters: item – an instance of TreeListItem.

IsItemVisible(item) [source]

Returns whether the item is visible or not.

Parameters: item – an instance of TreeListItem;

IsVirtual() [source]

Returns True if TreeListMainWindow has the TR_VIRTUAL flag set.

OnAcceptEdit(value) [source]

Called by EditTextCtrl, to accept the changes and to send the EVT_TREE_END_LABEL_EDIT event.

Parameters: value – the new value of the item label.

OnCancelEdit() [source]

Called by EditCtrl, to cancel the changes and to send the EVT_TREE_END_LABEL_EDIT event.

OnEditTimer() [source]

The timer for editing has expired. Start editing.

OnEraseBackground(event) [source]

Handles the wx.EVT_ERASE_BACKGROUND event for TreeListMainWindow.

Parameters: event – a wx.EraseEvent event to be processed.

OnMouse(event) [source]

Handles the wx.EVT_MOUSE_EVENTS event for TreeListMainWindow.

Parameters: event – a wx.MouseEvent event to be processed.

OnPaint(event) [source]

Handles the wx.EVT_PAINT event for TreeListMainWindow.

Parameters: event – a wx.PaintEvent event to be processed.

OnScroll(event) [source]

Handles the wx.EVT_SCROLLWIN event for TreeListMainWindow.

Parameters: event – a wx.ScrollEvent event to be processed.

PaintItem(item, dc) [source]

Actually draws an item.

Parameters:
  • item – an instance of TreeListItem;
  • dc – an instance of wx.DC.

PaintLevel(item, dc, level, y, x_maincol) [source]

Paint a level in the hierarchy of TreeListMainWindow.

Parameters:
  • item – an instance of TreeListItem;
  • dc – an instance of wx.DC;

  • level – the item level in the tree hierarchy;
  • y – the current vertical position in the wx.PyScrolledWindow;
  • x_maincol – the horizontal position of the main column.

ScrollTo(item) [source]

Scrolls the specified item into view.

Parameters: item – an instance of TreeListItem.

SetBuffered(buffered) [source]

Sets/unsets the double buffering for the main window.

Parameters: buffered – True to use double-buffering, False otherwise.

Note

Currently we are using double-buffering only on Windows XP.

SetDragItem(item) [source]

Sets the specified item as member of a current drag and drop operation.

Parameters: item – an instance of TreeListItem.

SetItemImage(item, image, column=None, which=wx.TreeItemIcon_Normal) [source]

Sets the item image for a particular item state.

Parameters:
  • item – an instance of TreeListItem;
  • image – an index within the normal image list specifying the image to use;
  • column – if not None, an integer specifying the column index. If it is None, the main column index is used;
  • which – the item state.

See also

GetItemImage for a list of valid item states.

SetItemText(item, text, column=None) [source]

Sets the item text label.

Parameters:
  • item – an instance of TreeListItem;
  • text – a string specifying the new item label;
  • column – if not None, an integer specifying the column index. If it is None, the main column index is used.

SetItemWindow(item, window, column=None) [source]

Sets the window associated to an item.

Parameters:
  • item – an instance of TreeListItem;
  • wnd – a non-toplevel window to be displayed next to the item;
  • column – if not None, an integer specifying the column index. If it is None, the main column index is used.

Note

The window parent should not be the HyperTreeList itself, but actually an instance of TreeListMainWindow. The current solution here is to reparent the window to this class.

SetItemWindowEnabled(item, enable=True, column=None) [source]

Sets whether the window associated with an item is enabled or not.

Parameters:
  • item – an instance of TreeListItem;
  • enable – True to enable the associated window, False to disable it;
  • column – if not None, an integer specifying the column index. If it is None, the main column index is used.

SetMainColumn(column) [source]

Sets the HyperTreeList main column (i.e. the position of the underlying CustomTreeCtrl.

Parameters: column – if not None, an integer specifying the column index. If it is None, the main column index is used.

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • infobar
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • hypertreelist »
  • TreeListMainWindow


SVN Revision 68021 For hypertreelist

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • hypertreelist »
  • SVN Revision 68021 For hypertreelist

svn SVN Revision 68021 For hypertreelist

This file contains the SVN revision history for hypertreelist, at revision 68021.

Available information include commit date, the name of the committer, the file size, the SVN log messages and a diff from the previous version (if available).

File Information

  • Commit Date: 28-Apr-2009 10:32:34 UTC
  • Committer: AG
  • File Size: 185344 byte(s)

Log Messages

The following log message was entered by the committer:

  • Fixed bug #13269 for CustomTreeCtrl and HyperTreeList (thanks to Frank Niessink);
  • Fixed bug #13268 for AuiToolBar;
  • Fixed bug #13107 on AuiNotebook.

Diff To Previous Version (66701)

Version SVN diff:

--- wxPython/3rdParty/AGW/agw/hypertreelist.py      2011/01/17 15:11:31     66701
+++ wxPython/3rdParty/AGW/agw/hypertreelist.py      2011/06/22 19:56:23     68021
@@ -3,7 +3,7 @@
# Inspired By And Heavily Based On wx.gizmos.TreeListCtrl.
#
# Andrea Gavana, @ 08 May 2006
-# Latest Revision: 17 Jan 2011, 15.00 GMT
+# Latest Revision: 21 Jun 2011, 22.00 GMT
#
#
# TODO List
@@ -214,7 +214,7 @@

HyperTreeList is distributed under the wxPython license.

-Latest Revision: Andrea Gavana @ 17 Jan 2011, 15.00 GMT
+Latest Revision: Andrea Gavana @ 21 Jun 2011, 22.00 GMT

Version 1.2

@@ -225,7 +225,7 @@

from customtreectrl import CustomTreeCtrl
from customtreectrl import DragImage, TreeEvent, GenericTreeItem
-from customtreectrl import TreeRenameTimer as TreeListRenameTimer
+from customtreectrl import TreeEditTimer as TreeListEditTimer
from customtreectrl import EVT_TREE_ITEM_CHECKING, EVT_TREE_ITEM_CHECKED, EVT_TREE_ITEM_HYPERLINK

# Version Info
@@ -251,7 +251,7 @@

_DRAG_TIMER_TICKS = 250   # minimum drag wait time in ms
_FIND_TIMER_TICKS = 500   # minimum find wait time in ms
-_RENAME_TIMER_TICKS = 250 # minimum rename wait time in ms
+_EDIT_TIMER_TICKS = 250 # minimum edit wait time in ms

# --------------------------------------------------------------------------
# Additional HitTest style
@@ -1712,17 +1712,17 @@
# EditTextCtrl (internal)
#-----------------------------------------------------------------------------

-class EditTextCtrl(wx.TextCtrl):
+
+class EditCtrl(object):
"""
-    Control used for in-place edit.
+    Base class for controls used for in-place edit.
"""
-
+
def __init__(self, parent, id=wx.ID_ANY, item=None, column=None, owner=None,
value="", pos=wx.DefaultPosition, size=wx.DefaultSize, style=0,
-                 validator=wx.DefaultValidator, name="edittextctrl"):
+                 validator=wx.DefaultValidator, name="editctrl", **kwargs):
"""
Default class constructor.
-        For internal use: do not call it in your code!

:param `parent`: the window parent. Must not be ``None``;
:param `id`: window identifier. A value of -1 indicates a default value;
@@ -1730,7 +1730,7 @@
:param `column`: if not ``None``, an integer specifying the column index.
If it is ``None``, the main column index is used;
:param `owner`: the window owner, in this case an instance of L{TreeListMainWindow};
-        :param `value`: the initial value in the text control;
+        :param `value`: the initial value in the control;
:param `pos`: the control position. A value of (-1, -1) indicates a default position,
chosen by either the windowing system or wxPython, depending on platform;
:param `size`: the control size. A value of (-1, -1) indicates a default size,
@@ -1739,12 +1739,11 @@
:param `validator`: the window validator;
:param `name`: the window name.
"""
-
self._owner = owner
self._startValue = value
-        self._finished = False
self._itemEdited = item
-
+        self._finished = False
+
column = (column is not None and [column] or [self._owner.GetMainColumn()])[0]

self._column = column
@@ -1801,19 +1800,48 @@
x += image_w + wcheck
w -= image_w + 2*_MARGIN + wcheck

-        wx.TextCtrl.__init__(self, parent, id, value, wx.Point(x, y),
-                             wx.Size(w + 15, h), style|wx.SIMPLE_BORDER, validator, name)
+        super(EditCtrl, self).__init__(parent, id, value, wx.Point(x,y),
+                                       wx.Size(w+15, h),
+                                       style=style|wx.SIMPLE_BORDER,
+                                       name=name, **kwargs)

if wx.Platform == "__WXMAC__":
self.SetFont(owner.GetFont())
bs = self.GetBestSize()
self.SetSize((-1, bs.height))
-
-        self.Bind(wx.EVT_CHAR, self.OnChar)
-        self.Bind(wx.EVT_KEY_UP, self.OnKeyUp)
+
self.Bind(wx.EVT_KILL_FOCUS, self.OnKillFocus)

+    def item(self):
+        """Returns the item currently edited."""
+
+        return self._itemEdited
+
+
+    def column(self):
+        """Returns the column currently edited."""
+
+        return self._column
+
+
+    def StopEditing(self):
+        """Suddenly stops the editing."""
+
+        self._owner.OnCancelEdit()
+        self.Finish()
+
+
+    def Finish(self):
+        """Finish editing."""
+
+        if not self._finished:
+
+            self._finished = True
+            self._owner.SetFocusIgnoringChildren()
+            self._owner.ResetEditControl()
+
+
def AcceptChanges(self):
"""Accepts/refuses the changes made by the user."""

@@ -1825,25 +1853,61 @@
# needs to be notified that the user decided
# not to change the tree item label, and that
# the edit has been cancelled
-            self._owner.OnRenameCancelled()
+            self._owner.OnCancelEdit()
return True
+        else:
+            return self._owner.OnAcceptEdit(value)

-        if not self._owner.OnRenameAccept(value):
-            # vetoed by the user
-            return False
-
-        return True

+    def OnKillFocus(self, event):
+        """
+        Handles the ``wx.EVT_KILL_FOCUS`` event for L{EditCtrl}

-    def Finish(self):
-        """Finish editing."""
+        :param `event`: a `wx.FocusEvent` event to be processed.
+        """
+
+        # We must let the native control handle focus, too, otherwise
+        # it could have problems with the cursor (e.g., in wxGTK).
+        event.Skip()
+
+
+
+class EditTextCtrl(EditCtrl, wx.TextCtrl):
+    """
+    Text control used for in-place edit.
+    """
+
+    def __init__(self, parent, id=wx.ID_ANY, item=None, column=None, owner=None,
+                 value="", pos=wx.DefaultPosition, size=wx.DefaultSize, style=0,
+                 validator=wx.DefaultValidator, name="edittextctrl", **kwargs):
+        """
+        Default class constructor.
+        For internal use: do not call it in your code!
+
+        :param `parent`: the window parent. Must not be ``None``;
+        :param `id`: window identifier. A value of -1 indicates a default value;
+        :param `item`: an instance of L{TreeListItem};
+        :param `column`: if not ``None``, an integer specifying the column index.
+         If it is ``None``, the main column index is used;
+        :param `owner`: the window owner, in this case an instance of L{TreeListMainWindow};
+        :param `value`: the initial value in the text control;
+        :param `pos`: the control position. A value of (-1, -1) indicates a default position,
+         chosen by either the windowing system or wxPython, depending on platform;
+        :param `size`: the control size. A value of (-1, -1) indicates a default size,
+         chosen by either the windowing system or wxPython, depending on platform;
+        :param `style`: the window style;
+        :param `validator`: the window validator;
+        :param `name`: the window name.
+        """
+
+        super(EditTextCtrl, self).__init__(parent, id, item, column, owner,
+                                           value, pos, size, style, validator,
+                                           name, **kwargs)
+        self.SelectAll()
+
+        self.Bind(wx.EVT_CHAR, self.OnChar)
+        self.Bind(wx.EVT_KEY_UP, self.OnKeyUp)

-        if not self._finished:
-
-            self._finished = True
-            self._owner.SetFocusIgnoringChildren()
-            self._owner.ResetTextControl()
-

def OnChar(self, event):
"""
@@ -1854,8 +1918,7 @@

keycode = event.GetKeyCode()

-        if keycode in [wx.WXK_RETURN, wx.WXK_NUMPAD_ENTER]:
-            self._aboutToFinish = True
+        if keycode in [wx.WXK_RETURN, wx.WXK_NUMPAD_ENTER] and not event.ShiftDown():
# Notify the owner about the changes
self.AcceptChanges()
# Even if vetoed, close the control (consistent with MSW)
@@ -1891,39 +1954,9 @@
self.SetSize((sx, -1))

event.Skip()
-
-
-    def OnKillFocus(self, event):
-        """
-        Handles the ``wx.EVT_KILL_FOCUS`` event for L{EditTextCtrl}
-
-        :param `event`: a `wx.FocusEvent` event to be processed.
-        """
-
-        # We must let the native text control handle focus, too, otherwise
-        # it could have problems with the cursor (e.g., in wxGTK).
-        event.Skip()
-
-
-    def StopEditing(self):
-        """Suddenly stops the editing."""
-
-        self._owner.OnRenameCancelled()
-        self.Finish()

-
-    def item(self):
-        """Returns the item currently edited."""
-
-        return self._itemEdited
-
-
-    def column(self):
-        """Returns the column currently edited."""
-
-        return self._column
-
-
+
+
# ---------------------------------------------------------------------------
# TreeListMainWindow implementation
# ---------------------------------------------------------------------------
@@ -1980,6 +2013,8 @@
:param `name`: window name.
"""

+        self._buffered = False
+
CustomTreeCtrl.__init__(self, parent, id, pos, size, style, agwStyle, validator, name)

self._shiftItem = None
@@ -2001,7 +2036,7 @@
self._current = None

# TextCtrl initial settings for editable items
-        self._renameTimer = TreeListRenameTimer(self)
+        self._editTimer = TreeListEditTimer(self)
self._left_down_selection = False

self._dragTimer = wx.Timer(self)
@@ -2378,9 +2413,9 @@

self._dirty = True     # do this first so stuff below doesn't cause flicker

-        if self._textCtrl != None and self.IsDescendantOf(item, self._textCtrl.item()):
+        if self._editCtrl != None and self.IsDescendantOf(item, self._editCtrl.item()):
# can't delete the item being edited, cancel editing it first
-            self._textCtrl.StopEditing()
+            self._editCtrl.StopEditing()

# don't stay with invalid self._shiftItem or we will crash in the next call to OnChar()
changeKeyCurrent = False
@@ -2426,8 +2461,8 @@
:param `item`: an instance of L{TreeListItem}.
"""

-        if self._textCtrl != None and item != self._textCtrl.item() and self.IsDescendantOf(item, self._textCtrl.item()):
-            self._textCtrl.StopEditing()
+        if self._editCtrl != None and item != self._editCtrl.item() and self.IsDescendantOf(item, self._editCtrl.item()):
+            self._editCtrl.StopEditing()

if self.IsDescendantOf(item, self._selectItem):
self._selectItem = item
@@ -3263,10 +3298,11 @@
return

column = (column is not None and [column] or [self._main_column])[0]
-
+
if column < 0 or column >= self.GetColumnCount():
return

+        self._curColumn = column
self._editItem = item

te = TreeEvent(wx.wxEVT_COMMAND_TREE_BEGIN_LABEL_EDIT, self._owner.GetId())
@@ -3281,33 +3317,21 @@
# ensure that the position of the item it calculated in any case
if self._dirty:
self.CalculatePositions()
+
+        if self._editCtrl != None and (item != self._editCtrl.item() or column != self._editCtrl.column()):
+            self._editCtrl.StopEditing()
+
+        self._editCtrl = self._owner.CreateEditCtrl(item, column)
+        self._editCtrl.SetFocus()
+

-        header_win = self._owner.GetHeaderWindow()
-        alignment = header_win.GetColumnAlignment(column)
-        if alignment == wx.ALIGN_LEFT:
-            style = wx.TE_LEFT
-        elif alignment == wx.ALIGN_RIGHT:
-            style = wx.TE_RIGHT
-        elif alignment == wx.ALIGN_CENTER:
-            style = wx.TE_CENTER
-
-        if self._textCtrl != None and (item != self._textCtrl.item() or column != self._textCtrl.column()):
-            self._textCtrl.StopEditing()
-
-        self._textCtrl = EditTextCtrl(self, -1, self._editItem, column,
-                                      self, self._editItem.GetText(column),
-                                      style=style|wx.TE_PROCESS_ENTER)
-        self._textCtrl.SelectAll()
-        self._textCtrl.SetFocus()
-
-
-    def OnRenameTimer(self):
-        """ The timer for renaming has expired. Start editing. """
+    def OnEditTimer(self):
+        """ The timer for editing has expired. Start editing. """

self.EditLabel(self._current, self._curColumn)

-    def OnRenameAccept(self, value):
+    def OnAcceptEdit(self, value):
"""
Called by L{EditTextCtrl}, to accept the changes and to send the
``EVT_TREE_END_LABEL_EDIT`` event.
@@ -3330,12 +3354,12 @@
if self._curColumn == -1:
self._curColumn = 0

-        self.SetItemText(self._editItem, value, self._curColumn)
+        self.SetItemText(self._editItem, unicode(value), self._curColumn)

-    def OnRenameCancelled(self):
+    def OnCancelEdit(self):
"""
-        Called by L{EditTextCtrl}, to cancel the changes and to send the
+        Called by L{EditCtrl}, to cancel the changes and to send the
``EVT_TREE_END_LABEL_EDIT`` event.
"""

@@ -3383,7 +3407,7 @@
underMouseChanged = underMouse != self._underMouse

if underMouse and (flags & wx.TREE_HITTEST_ONITEM) and not event.LeftIsDown() and \
-           not self._isDragging and (not self._renameTimer or not self._renameTimer.IsRunning()):
+           not self._isDragging and (not self._editTimer or not self._editTimer.IsRunning()):
underMouse = underMouse
else:
underMouse = None
@@ -3400,11 +3424,11 @@

if (event.LeftDown() or event.LeftUp() or event.RightDown() or \
event.RightUp() or event.LeftDClick() or event.Dragging()):
-            if self._textCtrl != None and (item != self._textCtrl.item() or column != self._textCtrl.column()):
-                self._textCtrl.StopEditing()
+            if self._editCtrl != None and (item != self._editCtrl.item() or column != self._editCtrl.column()):
+                self._editCtrl.StopEditing()

-        # We do not want a tooltip if we are dragging, or if the rename timer is running
-        if underMouseChanged and not self._isDragging and (not self._renameTimer or not self._renameTimer.IsRunning()):
+        # We do not want a tooltip if we are dragging, or if the edit timer is running
+        if underMouseChanged and not self._isDragging and (not self._editTimer or not self._editTimer.IsRunning()):

if hoverItem is not None:
# Ask the tree control what tooltip (if any) should be shown
@@ -3572,7 +3596,7 @@
if item == self._current and self._curColumn != -1 and \
self._owner.GetHeaderWindow().IsColumnEditable(self._curColumn) and \
flags & (wx.TREE_HITTEST_ONITEMLABEL | wx.TREE_HITTEST_ONITEMCOLUMN):
-                    self._renameTimer.Start(_RENAME_TIMER_TICKS, wx.TIMER_ONE_SHOT)
+                    self._editTimer.Start(_EDIT_TIMER_TICKS, wx.TIMER_ONE_SHOT)

self._lastOnSame = False

@@ -3640,7 +3664,7 @@
if event.LeftDClick():

# double clicking should not start editing the item label
-                self._renameTimer.Stop()
+                self._editTimer.Stop()
self._lastOnSame = False

# send activate event first
@@ -4687,6 +4711,50 @@

return self.GetItemText(item1) == self.GetItemText(item2)

+
+    def CreateEditCtrl(self, item, column):
+        """
+        Create an edit control for editing a label of an item. By default, this
+        returns a text control.
+
+        Override this function in the derived class to return a different type
+        of control.
+
+        :param `item`: an instance of L{TreeListItem};
+        :param `column`: an integer specifying the column index.
+        """
+        return EditTextCtrl(self.GetMainWindow(), -1, item, column,
+                            self.GetMainWindow(), item.GetText(column),
+                            style=self.GetTextCtrlStyle(column))
+
+
+    def GetTextCtrlStyle(self, column):
+        """
+        Return the style to use for the text control that is used to edit
+        labels of items.
+
+        Override this function in the derived class to support a different
+        style, e.g. wx.TE_MULTILINE.
+
+        :param `column`: an integer specifying the column index.
+        """
+        return self.GetTextCtrlAlignmentStyle(column) | wx.TE_PROCESS_ENTER
+
+
+    def GetTextCtrlAlignmentStyle(self, column):
+        """
+        Return the alignment style to use for the text control that is used
+        to edit labels of items. The alignment style is derived from the
+        column alignment.
+
+        :param `column`: an integer specifying the column index.
+        """
+        header_win = self.GetHeaderWindow()
+        alignment = header_win.GetColumnAlignment(column)
+        return {wx.ALIGN_LEFT: wx.TE_LEFT,
+                wx.ALIGN_RIGHT: wx.TE_RIGHT,
+                wx.ALIGN_CENTER: wx.TE_CENTER}[alignment]
+

def GetClassDefaultAttributes(self):
"""

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • hypertreelist »
  • SVN Revision 68021 For hypertreelist


SVN Revision 68063 For hypertreelist

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • hypertreelist »
  • SVN Revision 68063 For hypertreelist

svn SVN Revision 68063 For hypertreelist

This file contains the SVN revision history for hypertreelist, at revision 68063.

Available information include commit date, the name of the committer, the file size, the SVN log messages and a diff from the previous version (if available).

File Information

  • Commit Date: 26-Apr-2009 20:12:50 UTC
  • Committer: RD
  • File Size: 184498 byte(s)

Log Messages

The following log message was entered by the committer:

Remove unneeded PrepareDC call. Use CallAfter to update the header window after the main window scrolls

Diff To Previous Version (68021)

Version SVN diff:

--- wxPython/3rdParty/AGW/agw/hypertreelist.py      2011/06/22 19:56:23     68021
+++ wxPython/3rdParty/AGW/agw/hypertreelist.py      2011/06/27 21:30:54     68063
@@ -253,6 +253,7 @@
_FIND_TIMER_TICKS = 500   # minimum find wait time in ms
_EDIT_TIMER_TICKS = 250 # minimum edit wait time in ms

+
# --------------------------------------------------------------------------
# Additional HitTest style
# --------------------------------------------------------------------------
@@ -780,7 +781,6 @@
else:
dc = wx.PaintDC(self)

-        self.PrepareDC(dc)
self.AdjustDC(dc)

x = 0
@@ -2044,15 +2044,7 @@

self.Bind(wx.EVT_PAINT, self.OnPaint)
self.Bind(wx.EVT_MOUSE_EVENTS, self.OnMouse)
-
-        # Listen for EVT_SCROLLWIN in a separate event handler so that the
-        # default handler can be called without entering an infinite loop.
-        # See OnScroll for why calling the default handler manually is needed.
-        # Store the default handler in _default_evt_handler.
-        scroll_evt_handler = wx.EvtHandler()
-        self.PushEventHandler(scroll_evt_handler)
-        scroll_evt_handler.Bind(wx.EVT_SCROLLWIN, self.OnScroll)
-        self._default_evt_handler = scroll_evt_handler.GetNextHandler()
+        self.Bind(wx.EVT_SCROLLWIN, self.OnScroll)

# Sets the focus to ourselves: this is useful if you have items
# with associated widgets.
@@ -3693,21 +3685,16 @@
:param `event`: a `wx.ScrollEvent` event to be processed.
"""

-        # Let wx.PyScrolledWindow compute the new scroll position so that
-        # TreeListHeaderWindow is repainted with the same scroll position as
-        # TreeListMainWindow.
-        #
-        # event.Skip() would not work, Update() would call
-        # TreeListHeaderWindow.OnPaint() synchronously, before
-        # wx.PyScrolledWindow.OnScroll() is called by the event handler. OnPaint()
-        # would not use the latest scroll position so the header and the tree
-        # scrolling positions would be unsynchronized.
-        self._default_evt_handler.ProcessEvent(event)
-
+        def _updateHeaderWindow(header):
+            header.Refresh()
+            header.Update()
+
+        # Update the header window after this scroll event has fully finished
+        # processing, and the scoll action is complete.
if event.GetOrientation() == wx.HORIZONTAL:
-            self._owner.GetHeaderWindow().Refresh()
-            self._owner.GetHeaderWindow().Update()
-
+            wx.CallAfter(_updateHeaderWindow, self._owner.GetHeaderWindow())
+        event.Skip()
+

def CalculateSize(self, item, dc):
"""

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • hypertreelist »
  • SVN Revision 68063 For hypertreelist


SVN Revision 68362 For hypertreelist

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • hypertreelist »
  • SVN Revision 68362 For hypertreelist

svn SVN Revision 68362 For hypertreelist

This file contains the SVN revision history for hypertreelist, at revision 68362.

Available information include commit date, the name of the committer, the file size, the SVN log messages and a diff from the previous version (if available).

File Information

  • Commit Date: 26-Apr-2009 08:34:30 UTC
  • Committer: AG
  • File Size: 184512 byte(s)

Log Messages

The following log message was entered by the committer:

  • All of AGW: change my work e-mail from KPO to Maersk Oil (silly commit)

Diff To Previous Version (68063)

Version SVN diff:

--- wxPython/3rdParty/AGW/agw/hypertreelist.py      2011/06/27 21:30:54     68063
+++ wxPython/3rdParty/AGW/agw/hypertreelist.py      2011/07/24 21:36:47     68362
@@ -31,7 +31,7 @@
# Write To Me At:
#
# andrea.gavana@gmail.com
-# gavana@kpo.kz
+# andrea.gavana@maerskoil.com
#
# Or, Obviously, To The wxPython Mailing List!!!
#

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • hypertreelist »
  • SVN Revision 68362 For hypertreelist


SVN Revision 68881 For hypertreelist

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • hypertreelist »
  • SVN Revision 68881 For hypertreelist

svn SVN Revision 68881 For hypertreelist

This file contains the SVN revision history for hypertreelist, at revision 68881.

Available information include commit date, the name of the committer, the file size, the SVN log messages and a diff from the previous version (if available).

File Information

  • Commit Date: 25-Apr-2009 07:54:27 UTC
  • Committer: AG
  • File Size: 185440 byte(s)

Log Messages

The following log message was entered by the committer:

  • AGW: General overhaul of the documentation, much improved. All the widgets have their own sample usage in the docs as well;

  • FlatNotebook: Added the FNB_NAV_BUTTONS_WHEN_NEEDED style, which hides the navigation left/right arrows if all tabs fit;

  • RibbonBar: - Added the EVT_RIBBONBAR_TAB_LEFT_DCLICK event, which generates a special event

    when a ribbon bar tab is double-clicked;

    • Added support for toggle buttons;
    • Improved support for ribbon panel sizers: panels with sizers should now automatically minimise at small sizes, and behave properly when popping up from a minimised state;
    • Added tooltips via SetToolTip for those buttons which have the help_string attribute set.

  • XLSGrid: a new widget was added to AGW, termed XLSGrid. It’s based on wx.grid.Grid and can be used to faithfully reproduce the appearance of a Microsoft Excel spreadsheets.

Diff To Previous Version (68436)

Version SVN diff:

--- wxPython/3rdParty/AGW/agw/hypertreelist.py      2011/07/26 20:21:45     68436
+++ wxPython/3rdParty/AGW/agw/hypertreelist.py      2011/08/25 16:40:17     68881
@@ -3,7 +3,7 @@
# Inspired By And Heavily Based On wx.gizmos.TreeListCtrl.
#
# Andrea Gavana, @ 08 May 2006
-# Latest Revision: 26 Jul 2011, 22.00 GMT
+# Latest Revision: 17 Aug 2011, 15.00 GMT
#
#
# TODO List
@@ -41,25 +41,25 @@

"""
-HyperTreeList is a class that mimics the behaviour of `wx.gizmos.TreeListCtrl`, with
+L{HyperTreeList} is a class that mimics the behaviour of `wx.gizmos.TreeListCtrl`, with
some more functionalities.

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

-HyperTreeList is a class that mimics the behaviour of `wx.gizmos.TreeListCtrl`, with
+L{HyperTreeList} is a class that mimics the behaviour of `wx.gizmos.TreeListCtrl`, with
almost the same base functionalities plus some more enhancements. This class does
not rely on the native control, as it is a full owner-drawn tree-list control.

-HyperTreeList is somewhat an hybrid between L{CustomTreeCtrl} and `wx.gizmos.TreeListCtrl`.
+L{HyperTreeList} is somewhat an hybrid between L{CustomTreeCtrl} and `wx.gizmos.TreeListCtrl`.

In addition to the standard `wx.gizmos.TreeListCtrl` behaviour this class supports:

* CheckBox-type items: checkboxes are easy to handle, just selected or unselected
state with no particular issues in handling the item's children;
* Added support for 3-state value checkbox items;
-* RadioButton-type items: since I elected to put radiobuttons in CustomTreeCtrl, I
+* RadioButton-type items: since I elected to put radiobuttons in L{CustomTreeCtrl}, I
needed some way to handle them, that made sense. So, I used the following approach:

- All peer-nodes that are radiobuttons will be mutually exclusive. In other words,
@@ -79,10 +79,10 @@
* Default selection style, gradient (horizontal/vertical) selection style and Windows
Vista selection style;
* Customized drag and drop images built on the fly;
-* Setting the HyperTreeList item buttons to a personalized imagelist;
-* Setting the HyperTreeList check/radio item icons to a personalized imagelist;
+* Setting the L{HyperTreeList} item buttons to a personalized imagelist;
+* Setting the L{HyperTreeList} check/radio item icons to a personalized imagelist;
* Changing the style of the lines that connect the items (in terms of `wx.Pen` styles);
-* Using an image as a HyperTreeList background (currently only in "tile" mode);
+* Using an image as a L{HyperTreeList} background (currently only in "tile" mode);

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

@@ -90,7 +90,7 @@
Base Functionalities
====================

-HyperTreeList supports all the `wx.gizmos.TreeListCtrl` styles, except:
+L{HyperTreeList} supports all the `wx.gizmos.TreeListCtrl` styles, except:

- ``TR_EXTENDED``: supports for this style is on the todo list (Am I sure of this?).

@@ -102,16 +102,54 @@

And a style useful to hide the TreeListCtrl header:

-- ``TR_NO_HEADER``: hides the HyperTreeList header.
+- ``TR_NO_HEADER``: hides the L{HyperTreeList} header.

-All the methods available in `wx.gizmos.TreeListCtrl` are also available in HyperTreeList.
+All the methods available in `wx.gizmos.TreeListCtrl` are also available in L{HyperTreeList}.
+
+
+Usage
+=====
+
+Usage example::
+
+    import wx
+    import wx.lib.agw.hypertreelist as HTL
+
+    class MyFrame(wx.Frame):
+
+        def __init__(self, parent):
+
+            wx.Frame.__init__(self, parent, -1, "HyperTreeList Demo")
+
+            tree_list = HTL.HyperTreeList(self)
+
+            tree_list.AddColumn("First column")
+
+            root = tree_list.AddRoot("Root", ct_type=1)
+
+            parent = tree_list.AppendItem(root, "First child", ct_type=1)
+            child = tree_list.AppendItem(parent, "First Grandchild", ct_type=1)
+
+            tree_list.AppendItem(root, "Second child", ct_type=1)
+
+
+    # our normal wxApp-derived class, as usual
+
+    app = wx.PySimpleApp()
+
+    frame = MyFrame(None)
+    app.SetTopWindow(frame)
+    frame.Show()
+
+    app.MainLoop()
+

Events
======

-All the events supported by `wx.gizmos.TreeListCtrl` are also available in HyperTreeList,
+All the events supported by `wx.gizmos.TreeListCtrl` are also available in L{HyperTreeList},
with a few exceptions:

- ``EVT_TREE_GET_INFO`` (don't know what this means);
@@ -119,7 +157,7 @@
- ``EVT_TREE_ITEM_MIDDLE_CLICK`` (not implemented, but easy to add);
- ``EVT_TREE_STATE_IMAGE_CLICK`` (no need for that, look at the checking events below).

-Plus, HyperTreeList supports the events related to the checkbutton-type items:
+Plus, L{HyperTreeList} supports the events related to the checkbutton-type items:

- ``EVT_TREE_ITEM_CHECKING``: an item is being checked;
- ``EVT_TREE_ITEM_CHECKED``: an item has been checked.
@@ -133,7 +171,7 @@
Supported Platforms
===================

-HyperTreeList has been tested on the following platforms:
+L{HyperTreeList} has been tested on the following platforms:
* Windows (Windows XP);

@@ -165,7 +203,7 @@
``TR_AUTO_CHECK_PARENT``           0x10000 Only meaningful foe checkbox-type items: when a child item is checked/unchecked its parent item is checked/unchecked as well.
``TR_ALIGN_WINDOWS``               0x20000 Flag used to align windows (in items with windows) at the same horizontal position.
``TR_NO_HEADER``                   0x40000 Use this style to hide the columns header.
-``TR_VIRTUAL``                     0x80000 `HyperTreeList` will have virtual behaviour.
+``TR_VIRTUAL``                     0x80000 L{HyperTreeList} will have virtual behaviour.
============================== =========== ==================================================

@@ -183,38 +221,38 @@
``EVT_LIST_COL_END_DRAG``      A column has been resized by the user.
``EVT_LIST_COL_RIGHT_CLICK``   A column has been right-clicked.
``EVT_TREE_BEGIN_DRAG``        Begin dragging with the left mouse button.
-``EVT_TREE_BEGIN_LABEL_EDIT``  Begin editing a label. This can be prevented by calling `Veto()`.
+``EVT_TREE_BEGIN_LABEL_EDIT``  Begin editing a label. This can be prevented by calling L{TreeEvent.Veto}.
``EVT_TREE_BEGIN_RDRAG``       Begin dragging with the right mouse button.
``EVT_TREE_DELETE_ITEM``       Delete an item.
``EVT_TREE_END_DRAG``          End dragging with the left or right mouse button.
-``EVT_TREE_END_LABEL_EDIT``    End editing a label. This can be prevented by calling `Veto()`.
-``EVT_TREE_GET_INFO``          Request information from the application (not implemented in `CustomTreeCtrl`).
+``EVT_TREE_END_LABEL_EDIT``    End editing a label. This can be prevented by calling L{TreeEvent.Veto}.
+``EVT_TREE_GET_INFO``          Request information from the application (not implemented in L{HyperTreeList}).
``EVT_TREE_ITEM_ACTIVATED``    The item has been activated, i.e. chosen by double clicking it with mouse or from keyboard.
``EVT_TREE_ITEM_CHECKED``      A checkbox or radiobox type item has been checked.
``EVT_TREE_ITEM_CHECKING``     A checkbox or radiobox type item is being checked.
``EVT_TREE_ITEM_COLLAPSED``    The item has been collapsed.
-``EVT_TREE_ITEM_COLLAPSING``   The item is being collapsed. This can be prevented by calling `Veto()`.
-``EVT_TREE_ITEM_EXPANDED``     The item has been expanded.
-``EVT_TREE_ITEM_EXPANDING``    The item is being expanded. This can be prevented by calling `Veto()`.
-``EVT_TREE_ITEM_GETTOOLTIP``   The opportunity to set the item tooltip is being given to the application (call `TreeEvent.SetToolTip`).
+``EVT_TREE_ITEM_COLLAPSING``   The item is being collapsed. This can be prevented by calling L{TreeEvent.Veto}.
+``EVT_TREE_ITEM_EXPANDED``     The item has been expanded.s
+``EVT_TREE_ITEM_EXPANDING``    The item is being expanded. This can be prevented by calling L{TreeEvent.Veto}.
+``EVT_TREE_ITEM_GETTOOLTIP``   The opportunity to set the item tooltip is being given to the application (call L{TreeEvent.SetToolTip}).
``EVT_TREE_ITEM_HYPERLINK``    An hyperlink type item has been clicked.
``EVT_TREE_ITEM_MENU``         The context menu for the selected item has been requested, either by a right click or by using the menu key.
-``EVT_TREE_ITEM_MIDDLE_CLICK`` The user has clicked the item with the middle mouse button (not implemented in `CustomTreeCtrl`).
+``EVT_TREE_ITEM_MIDDLE_CLICK`` The user has clicked the item with the middle mouse button (not implemented in L{HyperTreeList}).
``EVT_TREE_ITEM_RIGHT_CLICK``  The user has clicked the item with the right mouse button.
``EVT_TREE_KEY_DOWN``          A key has been pressed.
``EVT_TREE_SEL_CHANGED``       Selection has changed.
-``EVT_TREE_SEL_CHANGING``      Selection is changing. This can be prevented by calling `Veto()`.
-``EVT_TREE_SET_INFO``          Information is being supplied to the application (not implemented in `CustomTreeCtrl`).
-``EVT_TREE_STATE_IMAGE_CLICK`` The state image has been clicked (not implemented in `CustomTreeCtrl`).
+``EVT_TREE_SEL_CHANGING``      Selection is changing. This can be prevented by calling L{TreeEvent.Veto}.
+``EVT_TREE_SET_INFO``          Information is being supplied to the application (not implemented in L{HyperTreeList}).
+``EVT_TREE_STATE_IMAGE_CLICK`` The state image has been clicked (not implemented in L{HyperTreeList}).
============================== ==================================================

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

-HyperTreeList is distributed under the wxPython license.
+L{HyperTreeList} is distributed under the wxPython license.

-Latest Revision: Andrea Gavana @ 26 Jul 2011, 22.00 GMT
+Latest Revision: Andrea Gavana @ 17 Aug 2011, 15.00 GMT

Version 1.2

@@ -306,7 +344,7 @@
TR_ALIGN_WINDOWS = 0x20000                                     # to align windows horizontally for items at the same level
""" Flag used to align windows (in items with windows) at the same horizontal position. """
TR_VIRTUAL = 0x80000
-""" `HyperTreeList` will have virtual behaviour. """
+""" L{HyperTreeList} will have virtual behaviour. """

# --------------------------------------------------------------------------
# Additional HyperTreeList style to hide the header
@@ -4019,7 +4057,7 @@

class HyperTreeList(wx.PyControl):
"""
-    HyperTreeList is a class that mimics the behaviour of `wx.gizmos.TreeListCtrl`, with
+    L{HyperTreeList} is a class that mimics the behaviour of `wx.gizmos.TreeListCtrl`, with
almost the same base functionalities plus some more enhancements. This class does
not rely on the native control, as it is a full owner-drawn tree-list control.
"""
@@ -4282,7 +4320,7 @@
you may wish to call `wx.Window.ClearBackground` or `wx.Window.Refresh` after
calling this function.

-        :note: Overridden from `wx.PyControl`.
+        :note: Overridden from `wx.PyControl`.
"""

if not self._main_win:
@@ -4644,6 +4682,8 @@
Gets the size which best suits the window: for a control, it would be the
minimal size which doesn't truncate the control, for a panel - the same size
as it would have after a call to `Fit()`.
+
+        :note: Overridden from `wx.PyControl`.
"""

# something is better than nothing...

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • hypertreelist »
  • SVN Revision 68881 For hypertreelist


SVN Revision 68955 For hypertreelist

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • hypertreelist »
  • SVN Revision 68955 For hypertreelist

svn SVN Revision 68955 For hypertreelist

This file contains the SVN revision history for hypertreelist, at revision 68955.

Available information include commit date, the name of the committer, the file size, the SVN log messages and a diff from the previous version (if available).

File Information

  • Commit Date: 15-Apr-2009 08:00:48 UTC
  • Committer: AG
  • File Size: 185482 byte(s)

Log Messages

The following log message was entered by the committer:

  • Fix GetPrevExpanded/GetNextExpanded issues with CustomTreeCtrl and HyperTreeList. Thanks to struppimoppi for the partial patch.

Diff To Previous Version (68881)

Version SVN diff:

--- wxPython/3rdParty/AGW/agw/hypertreelist.py      2011/08/25 16:40:17     68881
+++ wxPython/3rdParty/AGW/agw/hypertreelist.py      2011/08/29 19:08:33     68955
@@ -2299,7 +2299,7 @@
:param `item`: an instance of L{TreeListItem}.
"""

-        return self.GetNext(item, False)
+        return CustomTreeCtrl.GetNextExpanded(self, item)

def GetPrevExpanded(self, item):
@@ -2309,7 +2309,7 @@
:param `item`: an instance of L{TreeListItem}.
"""

-        return self.GetPrev(item, False)
+        return CustomTreeCtrl.GetPrevExpanded(self, item)

def GetFirstVisibleItem(self):
@@ -2325,7 +2325,7 @@
:param `item`: an instance of L{TreeListItem}.
"""

-        i = self.GetNext(item, False)
+        i = self.GetPrev(item)
while i:
if self.IsItemVisible(i):
return i
@@ -4750,6 +4750,7 @@
:param `item`: an instance of L{TreeListItem};
:param `column`: an integer specifying the column index.
"""
+
return EditTextCtrl(self.GetMainWindow(), -1, item, column,
self.GetMainWindow(), item.GetText(column),
style=self.GetTextCtrlStyle(column))
@@ -4761,10 +4762,11 @@
labels of items.

Override this function in the derived class to support a different
-        style, e.g. wx.TE_MULTILINE.
+        style, e.g. ``wx.TE_MULTILINE``.

:param `column`: an integer specifying the column index.
"""
+
return self.GetTextCtrlAlignmentStyle(column) | wx.TE_PROCESS_ENTER

@@ -4776,6 +4778,7 @@

:param `column`: an integer specifying the column index.
"""
+
header_win = self.GetHeaderWindow()
alignment = header_win.GetColumnAlignment(column)
return {wx.ALIGN_LEFT: wx.TE_LEFT,

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • hypertreelist »
  • SVN Revision 68955 For hypertreelist


SVN Revision 69315 For hypertreelist

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • hypertreelist »
  • SVN Revision 69315 For hypertreelist

svn SVN Revision 69315 For hypertreelist

This file contains the SVN revision history for hypertreelist, at revision 69315.

Available information include commit date, the name of the committer, the file size, the SVN log messages and a diff from the previous version (if available).

File Information

  • Commit Date: 17-Oct-2008 20:51:43 UTC
  • Committer: AG
  • File Size: 185486 byte(s)

Log Messages

The following log message was entered by the committer:

  • HyperTreeList: fixed missing GetPrev method and associated TypeError;
  • AuiToolBar: don’t draw the gripper if the AuiToolBar style doesn’t contain the AUI_TB_GRIPPER bit.

Diff To Previous Version (68955)

Version SVN diff:

--- wxPython/3rdParty/AGW/agw/hypertreelist.py      2011/08/29 19:08:33     68955
+++ wxPython/3rdParty/AGW/agw/hypertreelist.py      2011/10/05 19:01:34     69315
@@ -2329,7 +2329,7 @@
while i:
if self.IsItemVisible(i):
return i
-            i = self.GetPrev(i, False)
+            i = self.GetPrev(i)

return None

@@ -4052,7 +4052,7 @@
"IsDescendantOf", "SetItemHyperText", "IsItemHyperText", "SetItemBold", "SetItemDropHighlight", "SetItemItalic",
"GetEditControl", "ShouldInheritColours", "GetItemWindow", "SetItemWindow", "SetItemTextColour", "HideItem",
"DeleteAllItems", "ItemHasChildren", "ToggleItemSelection", "SetItemType", "GetCurrentItem",
-            "SetItem3State", "SetItem3StateValue", "GetItem3StateValue", "IsItem3State"]
+            "SetItem3State", "SetItem3StateValue", "GetItem3StateValue", "IsItem3State", "GetPrev"]

class HyperTreeList(wx.PyControl):

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • hypertreelist »
  • SVN Revision 69315 For hypertreelist


SVN Revision 70819 For hypertreelist

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • hypertreelist »
  • SVN Revision 70819 For hypertreelist

svn SVN Revision 70819 For hypertreelist

This file contains the SVN revision history for hypertreelist, at revision 70819.

Available information include commit date, the name of the committer, the file size, the SVN log messages and a diff from the previous version (if available).

File Information

  • Commit Date: 17-Oct-2008 19:15:31 UTC
  • Committer: AG
  • File Size: 187484 byte(s)

Log Messages

The following log message was entered by the committer:

  • Added the new widget ShortcutEditor.
  • GenericMessageDialog:
    • Added the possibility to have custom labels for the buttons;
    • Added the possibility to have custom icons for the buttons.
  • CustomTreeCtrl:
    • Added the style TR_ELLIPSIZE_LONG_ITEMS, which ellipsizes long items when the horizontal space for CustomTreeCtrl is low;
    • Added the style TR_TOOLTIP_ON_LONG_ITEMS which shows tooltips on long items when the horizontal space for CustomTreeCtrl is low.
  • HyperTreeList:
    • Added the style TR_ELLIPSIZE_LONG_ITEMS, which ellipsizes long items when the horizontal space for HyperTreeList is low.

Diff To Previous Version (69315)

Version SVN diff:

--- wxPython/3rdParty/AGW/agw/hypertreelist.py      2011/10/05 19:01:34     69315
+++ wxPython/3rdParty/AGW/agw/hypertreelist.py      2012/03/05 20:59:35     70819
@@ -3,7 +3,7 @@
# Inspired By And Heavily Based On wx.gizmos.TreeListCtrl.
#
# Andrea Gavana, @ 08 May 2006
-# Latest Revision: 17 Aug 2011, 15.00 GMT
+# Latest Revision: 03 Mar 2012, 21.00 GMT
#
#
# TODO List
@@ -83,6 +83,8 @@
* Setting the L{HyperTreeList} check/radio item icons to a personalized imagelist;
* Changing the style of the lines that connect the items (in terms of `wx.Pen` styles);
* Using an image as a L{HyperTreeList} background (currently only in "tile" mode);
+* Ellipsization of long items when the horizontal space is low, via the ``TR_ELLIPSIZE_LONG_ITEMS``
+  style (`New in version 0.9.3`).

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

@@ -104,6 +106,12 @@

- ``TR_NO_HEADER``: hides the L{HyperTreeList} header.

+And a style related to long items (with a lot of text in them), which can be
+ellipsized:
+
+- ``TR_ELLIPSIZE_LONG_ITEMS``: ellipsizes long items when the horizontal space for
+  L{HyperTreeList} is low (`New in version 0.9.3`).
+

All the methods available in `wx.gizmos.TreeListCtrl` are also available in L{HyperTreeList}.

@@ -188,7 +196,7 @@
``TR_HAS_BUTTONS``                     0x1 Use this style to show + and - buttons to the left of parent items.
``TR_NO_LINES``                        0x4 Use this style to hide vertical level connectors.
``TR_LINES_AT_ROOT``                   0x8 Use this style to show lines between root nodes. Only applicable if ``TR_HIDE_ROOT`` is set and ``TR_NO_LINES`` is not set.
-``TR_DEFAULT_STYLE``                   0x9 No Docs
+``TR_DEFAULT_STYLE``                   0x9 The set of flags that are closest to the defaults for the native control for a particular toolkit.
``TR_TWIST_BUTTONS``                  0x10 Use old Mac-twist style buttons.
``TR_MULTIPLE``                       0x20 Use this style to allow a range of items to be selected. If a second range is selected, the current range, if any, is deselected.
``TR_EXTENDED``                       0x40 Use this style to allow disjoint items to be selected. (Only partially implemented; may not work in all cases).
@@ -196,14 +204,15 @@
``TR_EDIT_LABELS``                   0x200 Use this style if you wish the user to be able to edit labels in the tree control.
``TR_ROW_LINES``                     0x400 Use this style to draw a contrasting border between displayed rows.
``TR_HIDE_ROOT``                     0x800 Use this style to suppress the display of the root node, effectively causing the first-level nodes to appear as a series of root nodes.
-``TR_COLUMN_LINES``                 0x1000 No Docs
+``TR_COLUMN_LINES``                 0x1000 Use this style to draw a contrasting border between displayed columns.
``TR_FULL_ROW_HIGHLIGHT``           0x2000 Use this style to have the background colour and the selection highlight extend  over the entire horizontal row of the tree control window.
``TR_AUTO_CHECK_CHILD``             0x4000 Only meaningful foe checkbox-type items: when a parent item is checked/unchecked its children are checked/unchecked as well.
``TR_AUTO_TOGGLE_CHILD``            0x8000 Only meaningful foe checkbox-type items: when a parent item is checked/unchecked its children are toggled accordingly.
``TR_AUTO_CHECK_PARENT``           0x10000 Only meaningful foe checkbox-type items: when a child item is checked/unchecked its parent item is checked/unchecked as well.
``TR_ALIGN_WINDOWS``               0x20000 Flag used to align windows (in items with windows) at the same horizontal position.
``TR_NO_HEADER``                   0x40000 Use this style to hide the columns header.
-``TR_VIRTUAL``                     0x80000 L{HyperTreeList} will have virtual behaviour.
+``TR_ELLIPSIZE_LONG_ITEMS``        0x80000 Flag used to ellipsize long items when the horizontal space for L{HyperTreeList} columns is low.
+``TR_VIRTUAL``                    0x100000 L{HyperTreeList} will have virtual behaviour.
============================== =========== ==================================================

@@ -252,9 +261,9 @@

L{HyperTreeList} is distributed under the wxPython license.

-Latest Revision: Andrea Gavana @ 17 Aug 2011, 15.00 GMT
+Latest Revision: Andrea Gavana @ 03 Mar 2012, 21.00 GMT

-Version 1.2
+Version 1.3

"""

@@ -262,12 +271,12 @@
import wx.gizmos

from customtreectrl import CustomTreeCtrl
-from customtreectrl import DragImage, TreeEvent, GenericTreeItem
+from customtreectrl import DragImage, TreeEvent, GenericTreeItem, ChopText
from customtreectrl import TreeEditTimer as TreeListEditTimer
from customtreectrl import EVT_TREE_ITEM_CHECKING, EVT_TREE_ITEM_CHECKED, EVT_TREE_ITEM_HYPERLINK

# Version Info
-__version__ = "1.2"
+__version__ = "1.3"

# --------------------------------------------------------------------------
# Constants
@@ -343,7 +352,9 @@
""" its parent item is checked/unchecked as well. """
TR_ALIGN_WINDOWS = 0x20000                                     # to align windows horizontally for items at the same level
""" Flag used to align windows (in items with windows) at the same horizontal position. """
-TR_VIRTUAL = 0x80000
+TR_ELLIPSIZE_LONG_ITEMS = 0x80000                              # to ellipsize long items when horizontal space is low
+""" Flag used to ellipsize long items when the horizontal space for L{HyperTreeList} columns is low."""
+TR_VIRTUAL = 0x100000
""" L{HyperTreeList} will have virtual behaviour. """

# --------------------------------------------------------------------------
@@ -2044,7 +2055,8 @@
``TR_AUTO_CHECK_PARENT``           0x10000 Only meaningful foe checkbox-type items: when a child item is checked/unchecked its parent item is checked/unchecked as well.
``TR_ALIGN_WINDOWS``               0x20000 Flag used to align windows (in items with windows) at the same horizontal position.
``TR_NO_HEADER``                   0x40000 Use this style to hide the columns header.
-         ``TR_VIRTUAL``                     0x80000 L{HyperTreeList} will have virtual behaviour.
+         ``TR_ELLIPSIZE_LONG_ITEMS``        0x80000 Flag used to ellipsize long items when the horizontal space for L{CustomTreeCtrl} is low.
+         ``TR_VIRTUAL``                    0x100000 L{HyperTreeList} will have virtual behaviour.
============================== =========== ==================================================

:param `validator`: window validator;
@@ -2969,6 +2981,14 @@
text_extraH = (total_h > text_h and [(total_h - text_h)/2] or [0])[0]
text_y = item.GetY() + text_extraH
textrect = wx.Rect(text_x, text_y, text_w, text_h)
+
+            if self.HasAGWFlag(TR_ELLIPSIZE_LONG_ITEMS):
+                if i == self.GetMainColumn():
+                    maxsize = col_w - text_x - _MARGIN
+                else:
+                    maxsize = col_w - (wcheck + image_w + _MARGIN)
+
+                text = ChopText(dc, text, maxsize)

if not item.IsEnabled():
foreground = dc.GetTextForeground()
@@ -3930,8 +3950,8 @@
font = self.GetHyperTextFont()
else:
font = self._normalFont
-
-        dc = wx.ClientDC(self)
+
+        dc = wx.ClientDC(self)
dc.SetFont(font)
w, h, dummy = dc.GetMultiLineTextExtent(item.GetText(column))
w += 2*_MARGIN
@@ -3961,7 +3981,7 @@
wnd = item.GetWindow(column)
if wnd:
width += wnd.GetSize()[0] + 2*_MARGIN
-
+
return width

@@ -3976,6 +3996,10 @@
maxWidth, h = self.GetClientSize()
width = 0

+        if maxWidth < 5:
+            # Not shown on screen
+            maxWidth = 1000
+
# get root if on item
if not parent:
parent = self.GetRootItem()
@@ -4086,7 +4110,7 @@
``TR_HAS_BUTTONS``                     0x1 Use this style to show + and - buttons to the left of parent items.
``TR_NO_LINES``                        0x4 Use this style to hide vertical level connectors.
``TR_LINES_AT_ROOT``                   0x8 Use this style to show lines between root nodes. Only applicable if ``TR_HIDE_ROOT`` is set and ``TR_NO_LINES`` is not set.
-         ``TR_DEFAULT_STYLE``                   0x9 No Docs
+         ``TR_DEFAULT_STYLE``                   0x9 The set of flags that are closest to the defaults for the native control for a particular toolkit.
``TR_TWIST_BUTTONS``                  0x10 Use old Mac-twist style buttons.
``TR_MULTIPLE``                       0x20 Use this style to allow a range of items to be selected. If a second range is selected, the current range, if any, is deselected.
``TR_EXTENDED``                       0x40 Use this style to allow disjoint items to be selected. (Only partially implemented; may not work in all cases).
@@ -4094,14 +4118,15 @@
``TR_EDIT_LABELS``                   0x200 Use this style if you wish the user to be able to edit labels in the tree control.
``TR_ROW_LINES``                     0x400 Use this style to draw a contrasting border between displayed rows.
``TR_HIDE_ROOT``                     0x800 Use this style to suppress the display of the root node, effectively causing the first-level nodes to appear as a series of root nodes.
-         ``TR_COLUMN_LINES``                 0x1000 No Docs
+         ``TR_COLUMN_LINES``                 0x1000 Use this style to draw a contrasting border between displayed columns.
``TR_FULL_ROW_HIGHLIGHT``           0x2000 Use this style to have the background colour and the selection highlight extend  over the entire horizontal row of the tree control window.
``TR_AUTO_CHECK_CHILD``             0x4000 Only meaningful foe checkbox-type items: when a parent item is checked/unchecked its children are checked/unchecked as well.
``TR_AUTO_TOGGLE_CHILD``            0x8000 Only meaningful foe checkbox-type items: when a parent item is checked/unchecked its children are toggled accordingly.
``TR_AUTO_CHECK_PARENT``           0x10000 Only meaningful foe checkbox-type items: when a child item is checked/unchecked its parent item is checked/unchecked as well.
``TR_ALIGN_WINDOWS``               0x20000 Flag used to align windows (in items with windows) at the same horizontal position.
``TR_NO_HEADER``                   0x40000 Use this style to hide the columns header.
-         ``TR_VIRTUAL``                     0x80000 L{HyperTreeList} will have virtual behaviour.
+         ``TR_ELLIPSIZE_LONG_ITEMS``        0x80000 Flag used to ellipsize long items when the horizontal space for L{CustomTreeCtrl} is low.
+         ``TR_VIRTUAL``                    0x100000 L{HyperTreeList} will have virtual behaviour.
============================== =========== ==================================================

:param `validator`: window validator;
@@ -4246,7 +4271,7 @@
``TR_HAS_BUTTONS``                     0x1 Use this style to show + and - buttons to the left of parent items.
``TR_NO_LINES``                        0x4 Use this style to hide vertical level connectors.
``TR_LINES_AT_ROOT``                   0x8 Use this style to show lines between root nodes. Only applicable if ``TR_HIDE_ROOT`` is set and ``TR_NO_LINES`` is not set.
-         ``TR_DEFAULT_STYLE``                   0x9 No Docs
+         ``TR_DEFAULT_STYLE``                   0x9 The set of flags that are closest to the defaults for the native control for a particular toolkit.
``TR_TWIST_BUTTONS``                  0x10 Use old Mac-twist style buttons.
``TR_MULTIPLE``                       0x20 Use this style to allow a range of items to be selected. If a second range is selected, the current range, if any, is deselected.
``TR_EXTENDED``                       0x40 Use this style to allow disjoint items to be selected. (Only partially implemented; may not work in all cases).
@@ -4254,14 +4279,15 @@
``TR_EDIT_LABELS``                   0x200 Use this style if you wish the user to be able to edit labels in the tree control.
``TR_ROW_LINES``                     0x400 Use this style to draw a contrasting border between displayed rows.
``TR_HIDE_ROOT``                     0x800 Use this style to suppress the display of the root node, effectively causing the first-level nodes to appear as a series of root nodes.
-         ``TR_COLUMN_LINES``                 0x1000 No Docs
+         ``TR_COLUMN_LINES``                 0x1000 Use this style to draw a contrasting border between displayed columns.
``TR_FULL_ROW_HIGHLIGHT``           0x2000 Use this style to have the background colour and the selection highlight extend  over the entire horizontal row of the tree control window.
``TR_AUTO_CHECK_CHILD``             0x4000 Only meaningful foe checkbox-type items: when a parent item is checked/unchecked its children are checked/unchecked as well.
``TR_AUTO_TOGGLE_CHILD``            0x8000 Only meaningful foe checkbox-type items: when a parent item is checked/unchecked its children are toggled accordingly.
``TR_AUTO_CHECK_PARENT``           0x10000 Only meaningful foe checkbox-type items: when a child item is checked/unchecked its parent item is checked/unchecked as well.
``TR_ALIGN_WINDOWS``               0x20000 Flag used to align windows (in items with windows) at the same horizontal position.
``TR_NO_HEADER``                   0x40000 Use this style to hide the columns header.
-         ``TR_VIRTUAL``                     0x80000 L{HyperTreeList} will have virtual behaviour.
+         ``TR_ELLIPSIZE_LONG_ITEMS``        0x80000 Flag used to ellipsize long items when the horizontal space for L{CustomTreeCtrl} is low.
+         ``TR_VIRTUAL``                    0x100000 L{HyperTreeList} will have virtual behaviour.
============================== =========== ==================================================

:note: Please note that some styles cannot be changed after the window creation

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • hypertreelist »
  • SVN Revision 70819 For hypertreelist


infobar functions

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • infobar »
  • infobar functions

infobar functions

This is the description of standalone Python functions in the infobar module.

Functions Summary

GetCloseButtonBitmap For platforms supporting it (namely wxMSW and wxMAC), this method uses wx.RendererNative

API Functions API

GetCloseButtonBitmap(win, size, colBg, flags=0) [source]

For platforms supporting it (namely wxMSW and wxMAC), this method uses wx.RendererNative to draw a natively-looking close button on the InfoBar itself.

Parameters:
  • win – the window in which we wish to draw the close button (an instance of InfoBar);
  • size (tuple) – the close button size, a tuple of (width, height) dimensions in pixels;
  • colBg – the background colour of the parent window, an instance of wx.Colour;
  • flags (integer) – may have the wx.CONTROL_PRESSED, wx.CONTROL_CURRENT or wx.CONTROL_ISDEFAULT bit set.

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • infobar
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • infobar »
  • infobar functions


InfoBar

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • infobar »
  • InfoBar

InfoBar

An info bar is a transient window shown at top or bottom of its parent window to display non-critical information to the user.

This is the main class implementation, plainly translated from C++.

hierarchy Inheritance Diagram

Inheritance diagram for: InfoBar

Inheritance diagram of InfoBar

appearance Control Appearance

InfoBar

Methods Summary

__init__ | Default class constructor.
AddButton | Adds a button to be shown in the info bar.
Dismiss | Hides the InfoBar window.
DoHide | Hides this InfoBar with whatever hiding effect has been chosen.
DoShow | Shows this InfoBar with whatever showing effect has been chosen.
GetBarPlacement | Determines the placement of the bar from its position in the containing sizer.
GetDefaultBorder | Returns the default border style for InfoBar.
GetEffectDuration | Return the effect animation duration currently used, in milliseconds.
GetHideEffect | Return the effect currently used for hiding the bar.
GetShowEffect | Return the effect currently used for showing the bar.
Init | Common initialization code.
OnButton | Default event handler for the Close button in InfoBar.
RemoveButton | Remove a button previously added by AddButton.
SetEffectDuration | Sets the duration of the animation used when showing or hiding the bar.
SetFont | Overridden base class methods changes the font of the text message.
SetShowHideEffects | Set the effects to use when showing and hiding the bar.
ShowMessage | Show a message in the bar.
UpdateParent | Updates the parent layout appearance, but only if this InfoBar parent is not managed

API Class API

class InfoBar(wx.PyControl) [source]

An info bar is a transient window shown at top or bottom of its parent window to display non-critical information to the user.

This is the main class implementation, plainly translated from C++.

__init__(parent, id=wx.ID_ANY, pos=wx.DefaultPosition, size=wx.DefaultSize, style=0, name='InfoBar') [source]

Default class constructor.

Parameters:
  • parent – parent window. Must not be None;
  • id (integer) – window identifier. A value of -1 indicates a default value;
  • pos (tuple or wx.Point) – the control position. A value of (-1, -1) indicates a default position, chosen by either the windowing system or wxPython, depending on platform;
  • size (tuple or wx.Size) – the control size. A value of (-1, -1) indicates a default size, chosen by either the windowing system or wxPython, depending on platform;
  • style (integer) – the InfoBar style (unused at present);
  • name (string) – the control name.

AddButton(btnid, label, bitmap=wx.NullBitmap) [source]

Adds a button to be shown in the info bar.

The button added by this method will be shown to the right of the text (in LTR layout), with each successive button being added to the right of the previous one. If any buttons are added to the info bar using this method, the default Close button is not shown as it is assumed that the extra buttons already allow the user to close it.

Clicking the button will generate a normal wx.wxEVT_COMMAND_BUTTON_CLICKED event which can be handled as usual. The default handler in InfoBar itself closes the window whenever a button in it is clicked so if you wish the info bar to be hidden when the button is clicked, simply call event.Skip() in the button handler to let the base class handler do it (calling Dismiss explicitly works too, of course). On the other hand, if you don’t skip the event, the info bar will remain opened so make sure to do it for at least some buttons to allow the user to close it.

Parameters:
  • btnid (integer) – id of the button. It will be used in the button message clicking this button will generate;
  • label (string) – the label of the button. It may only be empty if btnid is one of the stock ids in which case the corresponding stock label will be used;
  • bitmap – if not equal to wx.NullBitmap, a valid wx.Bitmap image to show beside the button text.

Note

Notice that the generic InfoBar implementation handles the button events itself and so they are not propagated to the info bar parent and you need to either inherit from InfoBar and handle them in your derived class or use self.Bind(...) to handle the button events in the parent frame.

Dismiss() [source]

Hides the InfoBar window.

This method hides the window and lays out the parent window to account for its disappearance (unlike a simple Hide()), but only if this InfoBar parent is not managed by AuiManager or wx.aui.AuiManager.

DoHide() [source]

Hides this InfoBar with whatever hiding effect has been chosen.

DoShow() [source]

Shows this InfoBar with whatever showing effect has been chosen.

GetBarPlacement() [source]

Determines the placement of the bar from its position in the containing sizer.

Returns: One of these integer bits:
string parameter settings
Placement Flag | Hex Value | Description
BarPlacement_Unknown | 0x0 | Unknown placement of InfoBar (not good).
BarPlacement_Top | 0x1 | InfoBar is placed at the top of its parent.
BarPlacement_Bottom | 0x2 | InfoBar is placed at the bottom of its parent.

GetDefaultBorder() [source]

Returns the default border style for InfoBar.

GetEffectDuration() [source]

Return the effect animation duration currently used, in milliseconds.

GetHideEffect() [source]

Return the effect currently used for hiding the bar.

Returns: One of the following integer bits:
ShowEffect Flag | Hex Value | Description
wx.SHOW_EFFECT_NONE | 0x0 | No effect, equivalent to normal Show() or Hide() call.
wx.SHOW_EFFECT_SLIDE_TO_TOP | 0x7 | Slide the InfoBar window to the top.
wx.SHOW_EFFECT_SLIDE_TO_BOTTOM | 0x8 | Slide the InfoBar window to the bottom.

GetShowEffect() [source]

Return the effect currently used for showing the bar.

Returns: One of the following integer bits:
ShowEffect Flag | Hex Value | Description
wx.SHOW_EFFECT_NONE | 0x0 | No effect, equivalent to normal Show() or Hide() call.
wx.SHOW_EFFECT_SLIDE_TO_TOP | 0x7 | Slide the InfoBar window to the top.
wx.SHOW_EFFECT_SLIDE_TO_BOTTOM | 0x8 | Slide the InfoBar window to the bottom.

Init() [source]

Common initialization code.

OnButton(event) [source]

Default event handler for the Close button in InfoBar.

Parameters: event – a wx.CommandEvent to be processed.

Note

Notice that the generic InfoBar implementation handles the button events itself and so they are not propagated to the info bar parent and you need to either inherit from InfoBar and handle them in your derived class or use self.Bind(...) to handle the button events in the parent frame.

RemoveButton(btnid) [source]

Remove a button previously added by AddButton.

Parameters: btnid (integer) – id of the button to remove. If more than one button with the same id is used in the InfoBar (which is in any case not recommended), the last, i.e. most recently added, button with this id is removed.

SetEffectDuration(duration) [source]

Sets the duration of the animation used when showing or hiding the bar.

By default, 500ms duration is used.

Parameters: duration (integer) – duration of the animation, in milliseconds.

SetFont(font) [source]

Overridden base class methods changes the font of the text message.

InfoBar overrides this method to use the font passed to it for its text message part. By default a larger and bold version of the standard font is used.

Parameters: font – a valid instance of wx.Font.

Note

Reimplemented from wx.Window.

SetShowHideEffects(showEffect, hideEffect) [source]

Set the effects to use when showing and hiding the bar.

Either or both of the parameters can be set to wx.SHOW_EFFECT_NONE to disable using effects entirely.

By default, the info bar uses wx.SHOW_EFFECT_SLIDE_TO_BOTTOM effect for showing itself and wx.SHOW_EFFECT_SLIDE_TO_TOP for hiding if it is the first element of the containing sizer and reverse effects if it’s the last one. If it is neither the first nor the last element, no effect is used to avoid the use of an inappropriate one and this function must be called if an effect is desired.

Parameters:
  • showEffect (integer) – the effect to use when showing the bar;
  • hideEffect (integer) – the effect to use when hiding the bar.

The showEffect and hideEffect parameters can take one of the following bit:

integer parameter settings
ShowEffect Flag | Description
SHOW_EFFECT_NONE | No effect, equivalent to normal Show() or Hide() call.
SHOW_EFFECT_ROLL_TO_LEFT | Roll window to the left.
SHOW_EFFECT_ROLL_TO_RIGHT | Roll window to the right.
SHOW_EFFECT_ROLL_TO_TOP | Roll window to the top.
SHOW_EFFECT_ROLL_TO_BOTTOM | Roll window to the bottom.
SHOW_EFFECT_SLIDE_TO_LEFT | Slide window to the left.
SHOW_EFFECT_SLIDE_TO_RIGHT | Slide window to the right.
SHOW_EFFECT_SLIDE_TO_TOP | Slide window to the top.
SHOW_EFFECT_SLIDE_TO_BOTTOM | Slide window to the bottom.
SHOW_EFFECT_BLEND | Fade in or out effect.
SHOW_EFFECT_EXPAND | Expanding or collapsing effect.

ShowMessage(msg, flags=wx.ICON_INFORMATION) [source]

Show a message in the bar.

If the bar is currently hidden, it will be shown. Otherwise its message will be updated in place.

Parameters:
  • msg (string) – the text of the message;
  • flags (integer) – one of wx.ICON_NONE, wx.ICON_INFORMATION (default), wx.ICON_QUESTION, wx.ICON_WARNING or wx.ICON_ERROR values.

    Note

    These flags have the same meaning as in wx.MessageDialog for the generic version, i.e. show (or not, in case of wx.ICON_NONE) the corresponding icon in the bar but can be interpreted by the native versions. For example, the GTK+ native implementation doesn’t show icons at all but uses this parameter to select the appropriate background colour for the notification.

UpdateParent() [source]

Updates the parent layout appearance, but only if this InfoBar parent is not managed by AuiManager or wx.aui.AuiManager.

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • infobar
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • infobar »
  • InfoBar


SVN Revision 70886 For infobar

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • infobar »
  • SVN Revision 70886 For infobar

svn SVN Revision 70886 For infobar

This file contains the SVN revision history for infobar, at revision 70886.

Available information include commit date, the name of the committer, the file size, the SVN log messages and a diff from the previous version (if available).

File Information

  • Commit Date: 12-Mar-2012 19:32:35 UTC
  • Committer: AG
  • File Size: 28134 byte(s)

Log Messages

The following log message was entered by the committer:

Added the pure-Python implementation of InfoBar to work around a couple of bugs/limitations in the C++ version.

Diff To Previous Version (Unavailable)

Version SVN diff:

No diff available.

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • infobar »
  • SVN Revision 70886 For infobar


BufferedWindow

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • knobctrl »
  • BufferedWindow

BufferedWindow

A Buffered window class.

To use it, subclass it and define a Draw(dc) method that takes a dc to draw to. In that method, put the code needed to draw the picture you want. The window will automatically be double buffered, and the screen will be automatically updated when a Paint event is received.

When the drawing needs to change, you app needs to call the UpdateDrawing method. Since the drawing is stored in a bitmap, you can also save the drawing to file by calling the SaveToFile(self, file_name, file_type) method.

hierarchy Inheritance Diagram

Inheritance diagram for: BufferedWindow

Inheritance diagram of BufferedWindow

subclasses Known Subclasses

  • knobctrl.KnobCtrl

Methods Summary

__init__ | Default class constructor.
Draw | This method should be overridden when sub-classed.
OnPaint | Handles the wx.EVT_PAINT event for BufferedWindow.
OnSize | Handles the wx.EVT_SIZE event for BufferedWindow.
UpdateDrawing | This would get called if the drawing needed to change, for whatever reason.

API Class API

class BufferedWindow(wx.Window) [source]

A Buffered window class.

To use it, subclass it and define a Draw(dc) method that takes a dc to draw to. In that method, put the code needed to draw the picture you want. The window will automatically be double buffered, and the screen will be automatically updated when a Paint event is received.

When the drawing needs to change, you app needs to call the BufferedWindow.UpdateDrawing() method. Since the drawing is stored in a bitmap, you can also save the drawing to file by calling the SaveToFile(self, file_name, file_type) method.

__init__(parent, id=wx.ID_ANY, pos=wx.DefaultPosition, size=wx.DefaultSize, style=wx.NO_FULL_REPAINT_ON_RESIZE, agwStyle=KC_BUFFERED_DC) [source]

Default class constructor.

Parameters:
  • parent – parent window. Must not be None;
  • id – window identifier. A value of -1 indicates a default value;
  • pos – the control position. A value of (-1, -1) indicates a default position, chosen by either the windowing system or wxPython, depending on platform;
  • size – the control size. A value of (-1, -1) indicates a default size, chosen by either the windowing system or wxPython, depending on platform;
  • style – the window style;
  • agwStyle – if set to KC_BUFFERED_DC, double-buffering will be used.

Draw(dc) [source]

This method should be overridden when sub-classed.

Parameters: dc – an instance of wx.DC.

OnPaint(event) [source]

Handles the wx.EVT_PAINT event for BufferedWindow.

Parameters: event – a wx.PaintEvent event to be processed.

OnSize(event) [source]

Handles the wx.EVT_SIZE event for BufferedWindow.

Parameters: event – a wx.SizeEvent event to be processed.

UpdateDrawing() [source]

This would get called if the drawing needed to change, for whatever reason.

The idea here is that the drawing is based on some data generated elsewhere in the system. If that data changes, the drawing needs to be updated.

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • infobar
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • knobctrl »
  • BufferedWindow


KnobCtrl

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • knobctrl »
  • KnobCtrl

KnobCtrl

This class can be used to simulate a knob volume control often found in PC music players.

hierarchy Inheritance Diagram

Inheritance diagram for: KnobCtrl

Inheritance diagram of KnobCtrl

supclasses Known Superclasses

  • knobctrl.BufferedWindow

appearance Control Appearance

KnobCtrl

Methods Summary

__init__ | Default class constructor.
CircleCoords | Converts the input values into logical x and y coordinates.
Draw | Draws everything on the empty bitmap.
DrawBoundingCircle | Draws the KnobCtrl bounding circle.
DrawDiagonalGradient | Draw a shading of diagonal gradient to KnobCtrl.
DrawInsetCircle | Draws the small knob.
DrawTags | Draws the tags.
GetAngleFromCoord | Returns the angular position based on the input logical coordinates.
GetAngularRange | Returns the angular range for KnobCtrl as a tuple. The start and end
GetBoundingColour | Returns the bounding circle colour.
GetFirstGradientColour | Returns the first gradient colour for shading.
GetKnobRadius | Returns the knob radius, in pixels.
GetMaxValue | Returns the maximum value for KnobCtrl.
GetMinValue | Returns the minimum value for KnobCtrl.
GetSecondGradientColour | Returns the second gradient colour for shading.
GetTags | Returns the KnobCtrl tags.
GetTagsColour | Returns the tags colour.
GetTrackPosition | Used internally.
GetValue | Returns the value of KnobCtrl.
OffsetColour | Changes the input colour by the offset value.
OnMouseEvents | Handles the wx.EVT_MOUSE_EVENTS event for KnobCtrl.
SetAngularRange | Sets the angular range for KnobCtrl.
SetBoundingColour | Sets the bounding circle colour.
SetFirstGradientColour | Sets the first gradient colour for shading.
SetKnobRadius | Sets the knob radius.
SetSecondGradientColour | Sets the second gradient colour for shading.
SetTags | Sets the tags for KnobCtrl.
SetTagsColour | Sets the tags colour.
SetTrackPosition | Used internally.
SetValue | Sets programmatically the value of KnobCtrl.

API Class API

class KnobCtrl(BufferedWindow) [source]

This class can be used to simulate a knob volume control often found in PC music players.

__init__(parent, id=wx.ID_ANY, pos=wx.DefaultPosition, size=wx.DefaultSize, agwStyle=KC_BUFFERED_DC) [source]

Default class constructor.

Parameters:
  • parent – parent window. Must not be None;
  • id – window identifier. A value of -1 indicates a default value;
  • pos – the control position. A value of (-1, -1) indicates a default position, chosen by either the windowing system or wxPython, depending on platform;
  • size – the control size. A value of (-1, -1) indicates a default size, chosen by either the windowing system or wxPython, depending on platform;
  • style – the window style;
  • agwStyle – if set to KC_BUFFERED_DC, double-buffering will be used.

CircleCoords(radius, angle, centerX, centerY) [source]

Converts the input values into logical x and y coordinates.

Parameters:
  • radius – the KnobCtrl radius;
  • angle – the angular position of the mouse;
  • centerX – the x position of the KnobCtrl center;
  • centerX – the y position of the KnobCtrl center.

Draw(dc) [source]

Draws everything on the empty bitmap. Here all the chosen styles are applied.

Parameters: dc – an instance of wx.DC.

DrawBoundingCircle(dc, size) [source]

Draws the KnobCtrl bounding circle.

Parameters:
  • dc – an instance of wx.DC;

  • size – the control size.

DrawDiagonalGradient(dc, size) [source]

Draw a shading of diagonal gradient to KnobCtrl.

Parameters:
  • dc – an instance of wx.DC;

  • size – the control size.

DrawInsetCircle(dc, pencolour) [source]

Draws the small knob.

Parameters:
  • dc – an instance of wx.DC;

  • pencolour – the colour to use for drawing the inset circle.

DrawTags(dc, size) [source]

Draws the tags.

Parameters:
  • dc – an instance of wx.DC;

  • size – the control size.

GetAngleFromCoord(cx, cy) [source]

Returns the angular position based on the input logical coordinates. Used internally.

Parameters:
  • cx – the x logical position;
  • cy – the y logical position.

GetAngularRange() [source]

Returns the angular range for KnobCtrl as a tuple. The start and end angles in the returned tuple are given in degrees, clockwise.

GetBoundingColour() [source]

Returns the bounding circle colour.

GetFirstGradientColour() [source]

Returns the first gradient colour for shading.

GetKnobRadius() [source]

Returns the knob radius, in pixels.

GetMaxValue() [source]

Returns the maximum value for KnobCtrl.

GetMinValue() [source]

Returns the minimum value for KnobCtrl.

GetSecondGradientColour() [source]

Returns the second gradient colour for shading.

GetTags() [source]

Returns the KnobCtrl tags.

GetTagsColour() [source]

Returns the tags colour.

GetTrackPosition() [source]

Used internally.

GetValue() [source]

Returns the value of KnobCtrl.

OffsetColour(colour, offset) [source]

Changes the input colour by the offset value. Used internally.

Parameters:
  • colour – a valid wx.Colour object;
  • offset – an integer value for offsetting the input colour.

OnMouseEvents(event) [source]

Handles the wx.EVT_MOUSE_EVENTS event for KnobCtrl.

Parameters: event – a wx.MouseEvent event to be processed.

SetAngularRange(start, end) [source]

Sets the angular range for KnobCtrl.

Parameters:
  • start – the starting angle, in degrees, clockwise;
  • start – the ending angle, in degrees, clockwise.

SetBoundingColour(colour) [source]

Sets the bounding circle colour.

Parameters: colour – a valid wx.Colour object.

SetFirstGradientColour(colour) [source]

Sets the first gradient colour for shading.

Parameters: colour – a valid wx.Colour object.

SetKnobRadius(radius) [source]

Sets the knob radius.

Parameters: radius – the knob radius, in pixels.

SetSecondGradientColour(colour) [source]

Sets the second gradient colour for shading.

Parameters: colour – a valid wx.Colour object.

SetTags(tags) [source]

Sets the tags for KnobCtrl.

Parameters: tags – a list of integers ranging from minvalue to maxvalue.

SetTagsColour(colour) [source]

Sets the tags colour.

Parameters: colour – a valid wx.Colour object.

SetTrackPosition() [source]

Used internally.

SetValue(val) [source]

Sets programmatically the value of KnobCtrl.

Parameters: val – an integer specifying the new KnobCtrl value.

Note

This method does not send a KnobCtrlEvent.

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • infobar
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • knobctrl »
  • KnobCtrl


KnobCtrlEvent

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • knobctrl »
  • KnobCtrlEvent

KnobCtrlEvent

Represent details of the events that the KnobCtrl object sends.

hierarchy Inheritance Diagram

Inheritance diagram for: KnobCtrlEvent

Inheritance diagram of KnobCtrlEvent

Methods Summary

__init__ | Default class constructor.
GetOldValue | Returns the old KnobCtrl value for this event.
GetValue | Returns the new KnobCtrl value for this event.
SetOldValue | Sets the old KnobCtrl value for this event.
SetValue | Sets the new KnobCtrl value for this event.

API Class API

class KnobCtrlEvent(wx.PyCommandEvent) [source]

Represent details of the events that the KnobCtrl object sends.

__init__(eventType, eventId=1) [source]

Default class constructor. For internal use: do not call it in your code!

Parameters:
  • eventType – the event type;
  • eventId – the event identifier.

GetOldValue() [source]

Returns the old KnobCtrl value for this event.

GetValue() [source]

Returns the new KnobCtrl value for this event.

SetOldValue(oldValue) [source]

Sets the old KnobCtrl value for this event.

Parameters: oldValue – an integer representing the old value.

SetValue(value) [source]

Sets the new KnobCtrl value for this event.

Parameters: value – an integer representing the new value.

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • infobar
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • knobctrl »
  • KnobCtrlEvent


SVN Revision 68362 For knobctrl

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • knobctrl »
  • SVN Revision 68362 For knobctrl

svn SVN Revision 68362 For knobctrl

This file contains the SVN revision history for knobctrl, at revision 68362.

Available information include commit date, the name of the committer, the file size, the SVN log messages and a diff from the previous version (if available).

File Information

  • Commit Date: 17-Oct-2008 20:51:43 UTC
  • Committer: AG
  • File Size: 24855 byte(s)

Log Messages

The following log message was entered by the committer:

  • All of AGW: change my work e-mail from KPO to Maersk Oil (silly commit)

Diff To Previous Version (65377)

Version SVN diff:

--- wxPython/3rdParty/AGW/agw/knobctrl.py   2010/08/21 20:27:02     65377
+++ wxPython/3rdParty/AGW/agw/knobctrl.py   2011/07/24 21:36:47     68362
@@ -12,7 +12,7 @@
# For All Kind Of Problems, Requests Of Enhancements And Bug Reports, Please
# Write To Me At:
#
-# gavana@kpo.kz
+# andrea.gavana@maerskoil.com
# andrea.gavana@gmail.com
#
# Or, Obviously, To The wxPython Mailing List!!!

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • knobctrl »
  • SVN Revision 68362 For knobctrl


SVN Revision 68881 For knobctrl

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • knobctrl »
  • SVN Revision 68881 For knobctrl

svn SVN Revision 68881 For knobctrl

This file contains the SVN revision history for knobctrl, at revision 68881.

Available information include commit date, the name of the committer, the file size, the SVN log messages and a diff from the previous version (if available).

File Information

  • Commit Date: 17-Oct-2008 19:15:31 UTC
  • Committer: AG
  • File Size: 25935 byte(s)

Log Messages

The following log message was entered by the committer:

  • AGW: General overhaul of the documentation, much improved. All the widgets have their own sample usage in the docs as well;

  • FlatNotebook: Added the FNB_NAV_BUTTONS_WHEN_NEEDED style, which hides the navigation left/right arrows if all tabs fit;

  • RibbonBar: - Added the EVT_RIBBONBAR_TAB_LEFT_DCLICK event, which generates a special event

    when a ribbon bar tab is double-clicked;

    • Added support for toggle buttons;
    • Improved support for ribbon panel sizers: panels with sizers should now automatically minimise at small sizes, and behave properly when popping up from a minimised state;
    • Added tooltips via SetToolTip for those buttons which have the help_string attribute set.

  • XLSGrid: a new widget was added to AGW, termed XLSGrid. It’s based on wx.grid.Grid and can be used to faithfully reproduce the appearance of a Microsoft Excel spreadsheets.

Diff To Previous Version (68362)

Version SVN diff:

--- wxPython/3rdParty/AGW/agw/knobctrl.py   2011/07/24 21:36:47     68362
+++ wxPython/3rdParty/AGW/agw/knobctrl.py   2011/08/25 16:40:17     68881
@@ -2,7 +2,7 @@
# KNOBCTRL wxPython IMPLEMENTATION
#
# Andrea Gavana, @ 03 Nov 2006
-# Latest Revision: 14 Apr 2010, 12.00 GMT
+# Latest Revision: 17 Aug 2011, 15.00 GMT
#
#
# TODO List
@@ -22,13 +22,13 @@
# --------------------------------------------------------------------------------- #

"""
-KnobCtrl lets the user select a numerical value by rotating it.
+L{KnobCtrl} lets the user select a numerical value by rotating it.

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

-KnobCtrl lets the user select a numerical value by rotating it. It works like a
+L{KnobCtrl} lets the user select a numerical value by rotating it. It works like a
scrollbar: just set the ticks range property and read the value property in the
associated ``EVT_KC_ANGLE_CHANGING``/``EVT_KC_ANGLE_CHANGED`` events. Simple but
effective.
@@ -37,10 +37,57 @@
or similar functionalities.

+Usage
+=====
+
+Usage example::
+
+    import wx
+    import wx.lib.agw.knobctrl as KC
+
+    class MyFrame(wx.Frame):
+
+        def __init__(self, parent):
+
+            wx.Frame.__init__(self, parent, -1, "KnobCtrl Demo")
+
+            panel = wx.Panel(self)
+
+            knob1 = KC.KnobCtrl(panel, -1, size=(100, 100))
+            knob2 = KC.KnobCtrl(panel, -1, size=(100, 100))
+
+            knob1.SetTags(range(0, 151, 10))
+            knob1.SetAngularRange(-45, 225)
+            knob1.SetValue(45)
+
+            knob2.SetTags(range(0, 151, 10))
+            knob2.SetAngularRange(0, 270)
+            knob2.SetValue(100)
+
+            main_sizer = wx.BoxSizer(wx.VERTICAL)
+            main_sizer.Add(knob1, 0, wx.EXPAND|wx.ALL, 20)
+            main_sizer.Add(knob2, 0, wx.EXPAND|wx.ALL, 20)
+
+            panel.SetSizer(main_sizer)
+            main_sizer.Layout()
+
+
+    # our normal wxApp-derived class, as usual
+
+    app = wx.PySimpleApp()
+
+    frame = MyFrame(None)
+    app.SetTopWindow(frame)
+    frame.Show()
+
+    app.MainLoop()
+
+
+
Events
======

-KnobCtrl implements two events that can be intercepted by the user:
+L{KnobCtrl} implements two events that can be intercepted by the user:

- ``EVT_KC_ANGLE_CHANGING``;
- ``EVT_KC_ANGLE_CHANGED``.
@@ -52,7 +99,7 @@
Supported Platforms
===================

-KnobCtrl has been tested on the following platforms:
+L{KnobCtrl} has been tested on the following platforms:
* Windows (Windows XP);
* Linux Ubuntu (Dapper 6.06)

@@ -85,9 +132,9 @@
License And Version
===================

-KnobCtrl is distributed under the wxPython license.
+L{KnobCtrl} is distributed under the wxPython license.

-Latest Revision: Andrea Gavana @ 14 Apr 2010, 12.00 GMT
+Latest Revision: Andrea Gavana @ 17 Aug 2011, 15.00 GMT

Version 0.3

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • knobctrl »
  • SVN Revision 68881 For knobctrl


FlatBookBase

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • labelbook »
  • FlatBookBase

FlatBookBase

Base class for the containing window for LabelBook and FlatImageBook.

hierarchy Inheritance Diagram

Inheritance diagram for: FlatBookBase

Inheritance diagram of FlatBookBase

subclasses Known Subclasses

  • labelbook.FlatImageBook
  • labelbook.LabelBook

Methods Summary

__init__ | Default class constructor.
AddPage | Adds a page to the book.
AdvanceSelection | Cycles through the tabs.
AssignImageList | Assigns an image list to the control.
ChangeSelection | Changes the selection for the given page, returning the previous selection.
DeleteAllPages | Deletes all the pages in the book.
DeletePage | Deletes the specified page, and the associated window.
DoSetSelection | Select the window by the provided pointer.
EnableTab | Enables or disables a tab.
GetAGWWindowStyleFlag | Returns the FlatBookBase window style.
GetCurrentPage | Returns the currently selected notebook page or None.
GetEnabled | Returns whether a tab is enabled or not.
GetFontBold | Gets the font bold status.
GetFontSizeMultiple | Gets the font size multiple for the page captions.
GetImageList | Returns the associated image list.
GetPage | Returns the window at the given page position.
GetPageCount | Returns the number of pages in the book.
GetPageImage | Returns the image index for the given page.
GetPageText | Returns the text for the given page.
GetSelection | Returns the current selection.
HasAGWFlag | Returns whether a flag is present in the FlatBookBase style.
InsertPage | Inserts a page into the book at the specified position.
OnNavigationKey | Handles the wx.EVT_NAVIGATION_KEY event for FlatBookBase.
RemovePage | Deletes the specified page, without deleting the associated window.
ResizeTabArea | Resizes the tab area if the control has the INB_FIT_LABELTEXT style set.
SetAGWWindowStyleFlag | Sets the window style.
SetFontBold | Sets whether the page captions are bold or not.
SetFontSizeMultiple | Sets the font size multiple for the page captions.
SetPageImage | Sets the image index for the given page.
SetPageText | Sets the text for the given page.
SetSelection | Changes the selection from currently visible/selected page to the page given by page.

API Class API

class FlatBookBase(wx.Panel) [source]

Base class for the containing window for LabelBook and FlatImageBook.

__init__(parent, id=wx.ID_ANY, pos=wx.DefaultPosition, size=wx.DefaultSize, style=0, agwStyle=0, name="FlatBookBase") [source]

Default class constructor.

Parameters:
  • parent – parent window. Must not be None;
  • id – window identifier. A value of -1 indicates a default value;
  • pos – the control position. A value of (-1, -1) indicates a default position, chosen by either the windowing system or wxPython, depending on platform;
  • size – the control size. A value of (-1, -1) indicates a default size, chosen by either the windowing system or wxPython, depending on platform;
  • style – the underlying wx.Panel window style;
  • agwStyle – the AGW-specific window style. This can be a combination of the following bits:

    Window Styles | Hex Value | Description
    INB_BOTTOM | 0x1 | Place labels below the page area. Available only for FlatImageBook.
    INB_LEFT | 0x2 | Place labels on the left side. Available only for FlatImageBook.
    INB_RIGHT | 0x4 | Place labels on the right side.
    INB_TOP | 0x8 | Place labels above the page area.
    INB_BORDER | 0x10 | Draws a border around LabelBook or FlatImageBook.
    INB_SHOW_ONLY_TEXT | 0x20 | Shows only text labels and no images. Available only for LabelBook.
    INB_SHOW_ONLY_IMAGES | 0x40 | Shows only tab images and no label texts. Available only for LabelBook.
    INB_FIT_BUTTON | 0x80 | Displays a pin button to show/hide the book control.
    INB_DRAW_SHADOW | 0x100 | Draw shadows below the book tabs. Available only for LabelBook.
    INB_USE_PIN_BUTTON | 0x200 | Displays a pin button to show/hide the book control.
    INB_GRADIENT_BACKGROUND | 0x400 | Draws a gradient shading on the tabs background. Available only for LabelBook.
    INB_WEB_HILITE | 0x800 | On mouse hovering, tabs behave like html hyperlinks. Available only for LabelBook.
    INB_NO_RESIZE | 0x1000 | Don’t allow resizing of the tab area.
    INB_FIT_LABELTEXT | 0x2000 | Will fit the tab area to the longest text (or text+image if you have images) in all the tabs.
    INB_BOLD_TAB_SELECTION | 0x4000 | Show the selected tab text using a bold font.
  • name – the window name.

AddPage(page, text, select=False, imageId=-1) [source]

Adds a page to the book.

Parameters:
  • page – specifies the new page;
  • text – specifies the text for the new page;
  • select – specifies whether the page should be selected;
  • imageId – specifies the optional image index for the new page.

Note

The call to this function generates the page changing events.

AdvanceSelection(forward=True) [source]

Cycles through the tabs.

Parameters: forward – if True, the selection is advanced in ascending order (to the right), otherwise the selection is advanced in descending order.

Note

The call to this function generates the page changing events.

AssignImageList(imglist) [source]

Assigns an image list to the control.

Parameters: imglist – an instance of wx.ImageList.

ChangeSelection(page) [source]

Changes the selection for the given page, returning the previous selection.

Parameters: page – an integer specifying the page to be selected.

Note

The call to this function does not generate the page changing events.

CurrentPage

See GetCurrentPage

DeleteAllPages() [source]

Deletes all the pages in the book.

DeletePage(page) [source]

Deletes the specified page, and the associated window.

Parameters: page – an integer specifying the page to be deleted.

Note

The call to this function generates the page changing events.

DoSetSelection(window) [source]

Select the window by the provided pointer.

Parameters: window – an instance of wx.Window.

EnableTab(page, enabled=True) [source]

Enables or disables a tab.

Parameters:
  • page – an integer specifying the page index;
  • enabled – True to enable a tab, False to disable it.

GetAGWWindowStyleFlag() [source]

Returns the FlatBookBase window style.

See also

SetAGWWindowStyleFlag for a list of possible window style flags.

GetCurrentPage() [source]

Returns the currently selected notebook page or None.

GetEnabled(page) [source]

Returns whether a tab is enabled or not.

Parameters: page – an integer specifying the page index.

GetFontBold() [source]

Gets the font bold status.

GetFontSizeMultiple() [source]

Gets the font size multiple for the page captions.

GetImageList() [source]

Returns the associated image list.

GetPage(page) [source]

Returns the window at the given page position.

Parameters: page – an integer specifying the page to be returned.

GetPageCount() [source]

Returns the number of pages in the book.

GetPageImage(page) [source]

Returns the image index for the given page.

Parameters: page – an integer specifying the page index.

GetPageText(page) [source]

Returns the text for the given page.

Parameters: page – an integer specifying the page index.

GetSelection() [source]

Returns the current selection.

HasAGWFlag(flag) [source]

Returns whether a flag is present in the FlatBookBase style.

Parameters: flag – one of the possible FlatBookBase window styles.

See also

SetAGWWindowStyleFlag for a list of possible window style flags.

InsertPage(page_idx, page, text, select=False, imageId=-1) [source]

Inserts a page into the book at the specified position.

Parameters:
  • page_idx – specifies the position for the new page;
  • page – specifies the new page;
  • text – specifies the text for the new page;
  • select – specifies whether the page should be selected;
  • imageId – specifies the optional image index for the new page.

Note

The call to this function generates the page changing events.

OnNavigationKey(event) [source]

Handles the wx.EVT_NAVIGATION_KEY event for FlatBookBase.

Parameters: event – a wx.NavigationKeyEvent event to be processed.

Page

See GetPage

PageCount

See GetPageCount

PageImage

See GetPageImage, SetPageImage

PageText

See GetPageText, SetPageText

RemovePage(page) [source]

Deletes the specified page, without deleting the associated window.

Parameters: page – an integer specifying the page to be removed.

Note

The call to this function generates the page changing events.

ResizeTabArea() [source]

Resizes the tab area if the control has the INB_FIT_LABELTEXT style set.

Selection

See GetSelection, SetSelection

SetAGWWindowStyleFlag(agwStyle) [source]

Sets the window style.

Parameters: agwStyle – can be a combination of the following bits:

Window Styles | Hex Value | Description
INB_BOTTOM | 0x1 | Place labels below the page area. Available only for FlatImageBook.
INB_LEFT | 0x2 | Place labels on the left side. Available only for FlatImageBook.
INB_RIGHT | 0x4 | Place labels on the right side.
INB_TOP | 0x8 | Place labels above the page area.
INB_BORDER | 0x10 | Draws a border around LabelBook or FlatImageBook.
INB_SHOW_ONLY_TEXT | 0x20 | Shows only text labels and no images. Available only for LabelBook.
INB_SHOW_ONLY_IMAGES | 0x40 | Shows only tab images and no label texts. Available only for LabelBook.
INB_FIT_BUTTON | 0x80 | Displays a pin button to show/hide the book control.
INB_DRAW_SHADOW | 0x100 | Draw shadows below the book tabs. Available only for LabelBook.
INB_USE_PIN_BUTTON | 0x200 | Displays a pin button to show/hide the book control.
INB_GRADIENT_BACKGROUND | 0x400 | Draws a gradient shading on the tabs background. Available only for LabelBook.
INB_WEB_HILITE | 0x800 | On mouse hovering, tabs behave like html hyperlinks. Available only for LabelBook.
INB_NO_RESIZE | 0x1000 | Don’t allow resizing of the tab area.
INB_FIT_LABELTEXT | 0x2000 | Will fit the tab area to the longest text (or text+image if you have images) in all the tabs.
INB_BOLD_TAB_SELECTION | 0x4000 | Show the selected tab text using a bold font.

SetFontBold(bold) [source]

Sets whether the page captions are bold or not.

Parameters: bold – True or False.

SetFontSizeMultiple(multiple) [source]

Sets the font size multiple for the page captions.

Parameters: multiple – The multiple to be applied to the system font to get the our font size.

SetPageImage(page, imageId) [source]

Sets the image index for the given page.

Parameters:
  • page – an integer specifying the page index;
  • image – an index into the image list.

SetPageText(page, text) [source]

Sets the text for the given page.

Parameters:
  • page – an integer specifying the page index;
  • text – the new tab label.

SetSelection(page) [source]

Changes the selection from currently visible/selected page to the page given by page.

Parameters: page – an integer specifying the page to be selected.

Note

The call to this function generates the page changing events.

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • infobar
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • labelbook »
  • FlatBookBase


FlatImageBook

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • labelbook »
  • FlatImageBook

FlatImageBook

Default implementation of the image book, it is like a wx.Notebook, except that images are used to control the different pages. This container is usually used for configuration dialogs etc.

Note

Currently, this control works properly for images of size 32x32 and bigger.

hierarchy Inheritance Diagram

Inheritance diagram for: FlatImageBook

Inheritance diagram of FlatImageBook

supclasses Known Superclasses

  • labelbook.FlatBookBase

appearance Control Appearance

FlatImageBook

Methods Summary

__init__ | Default class constructor.
CreateImageContainer | Creates the image container class for FlatImageBook.

API Class API

class FlatImageBook(FlatBookBase) [source]

Default implementation of the image book, it is like a wx.Notebook, except that images are used to control the different pages. This container is usually used for configuration dialogs etc.

Note

Currently, this control works properly for images of size 32x32 and bigger.

__init__(parent, id=wx.ID_ANY, pos=wx.DefaultPosition, size=wx.DefaultSize, style=0, agwStyle=0, name="FlatImageBook") [source]

Default class constructor.

Parameters:
  • parent – parent window. Must not be None;
  • id – window identifier. A value of -1 indicates a default value;
  • pos – the control position. A value of (-1, -1) indicates a default position, chosen by either the windowing system or wxPython, depending on platform;
  • size – the control size. A value of (-1, -1) indicates a default size, chosen by either the windowing system or wxPython, depending on platform;
  • style – the underlying wx.Panel window style;
  • agwStyle – the AGW-specific window style. This can be a combination of the following bits:

    Window Styles | Hex Value | Description
    INB_BOTTOM | 0x1 | Place labels below the page area. Available only for FlatImageBook.
    INB_LEFT | 0x2 | Place labels on the left side. Available only for FlatImageBook.
    INB_RIGHT | 0x4 | Place labels on the right side.
    INB_TOP | 0x8 | Place labels above the page area.
    INB_BORDER | 0x10 | Draws a border around LabelBook or FlatImageBook.
    INB_SHOW_ONLY_TEXT | 0x20 | Shows only text labels and no images. Available only for LabelBook.
    INB_SHOW_ONLY_IMAGES | 0x40 | Shows only tab images and no label texts. Available only for LabelBook.
    INB_FIT_BUTTON | 0x80 | Displays a pin button to show/hide the book control.
    INB_DRAW_SHADOW | 0x100 | Draw shadows below the book tabs. Available only for LabelBook.
    INB_USE_PIN_BUTTON | 0x200 | Displays a pin button to show/hide the book control.
    INB_GRADIENT_BACKGROUND | 0x400 | Draws a gradient shading on the tabs background. Available only for LabelBook.
    INB_WEB_HILITE | 0x800 | On mouse hovering, tabs behave like html hyperlinks. Available only for LabelBook.
    INB_NO_RESIZE | 0x1000 | Don’t allow resizing of the tab area.
    INB_FIT_LABELTEXT | 0x2000 | Will fit the tab area to the longest text (or text+image if you have images) in all the tabs.
    INB_BOLD_TAB_SELECTION | 0x4000 | Show the selected tab text using a bold font.
  • name – the window name.

CreateImageContainer() [source]

Creates the image container class for FlatImageBook.

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • infobar
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • labelbook »
  • FlatImageBook


ImageContainer

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • labelbook »
  • ImageContainer

ImageContainer

Base class for FlatImageBook image container.

hierarchy Inheritance Diagram

Inheritance diagram for: ImageContainer

Inheritance diagram of ImageContainer

supclasses Known Superclasses

  • labelbook.ImageContainerBase

Methods Summary

__init__ | Default class constructor.
CanDoBottomStyle | Allows the parent to examine the children type.
OnEraseBackground | Handles the wx.EVT_ERASE_BACKGROUND event for ImageContainer.
OnMouseLeaveWindow | Handles the wx.EVT_LEAVE_WINDOW event for ImageContainer.
OnMouseLeftDown | Handles the wx.EVT_LEFT_DOWN event for ImageContainer.
OnMouseLeftUp | Handles the wx.EVT_LEFT_UP event for ImageContainer.
OnMouseMove | Handles the wx.EVT_MOTION event for ImageContainer.
OnPaint | Handles the wx.EVT_PAINT event for ImageContainer.
OnSize | Handles the wx.EVT_SIZE event for ImageContainer.

API Class API

class ImageContainer(ImageContainerBase) [source]

Base class for FlatImageBook image container.

__init__(parent, id=wx.ID_ANY, pos=wx.DefaultPosition, size=wx.DefaultSize, style=0, agwStyle=0, name="ImageContainer") [source]

Default class constructor.

Parameters:
  • parent – parent window. Must not be None;
  • id – window identifier. A value of -1 indicates a default value;
  • pos – the control position. A value of (-1, -1) indicates a default position, chosen by either the windowing system or wxPython, depending on platform;
  • size – the control size. A value of (-1, -1) indicates a default size, chosen by either the windowing system or wxPython, depending on platform;
  • style – the underlying wx.Panel window style;
  • agwStyle – the AGW-specific window style. This can be a combination of the following bits:

    Window Styles | Hex Value | Description
    INB_BOTTOM | 0x1 | Place labels below the page area. Available only for FlatImageBook.
    INB_LEFT | 0x2 | Place labels on the left side. Available only for FlatImageBook.
    INB_RIGHT | 0x4 | Place labels on the right side.
    INB_TOP | 0x8 | Place labels above the page area.
    INB_BORDER | 0x10 | Draws a border around LabelBook or FlatImageBook.
    INB_SHOW_ONLY_TEXT | 0x20 | Shows only text labels and no images. Available only for LabelBook.
    INB_SHOW_ONLY_IMAGES | 0x40 | Shows only tab images and no label texts. Available only for LabelBook.
    INB_FIT_BUTTON | 0x80 | Displays a pin button to show/hide the book control.
    INB_DRAW_SHADOW | 0x100 | Draw shadows below the book tabs. Available only for LabelBook.
    INB_USE_PIN_BUTTON | 0x200 | Displays a pin button to show/hide the book control.
    INB_GRADIENT_BACKGROUND | 0x400 | Draws a gradient shading on the tabs background. Available only for LabelBook.
    INB_WEB_HILITE | 0x800 | On mouse hovering, tabs behave like html hyperlinks. Available only for LabelBook.
    INB_NO_RESIZE | 0x1000 | Don’t allow resizing of the tab area.
    INB_FIT_LABELTEXT | 0x2000 | Will fit the tab area to the longest text (or text+image if you have images) in all the tabs.
    INB_BOLD_TAB_SELECTION | 0x4000 | Show the selected tab text using a bold font.
  • name – the window name.

CanDoBottomStyle() [source]

Allows the parent to examine the children type. Some implementation (such as LabelBook), does not support top/bottom images, only left/right.

OnEraseBackground(event) [source]

Handles the wx.EVT_ERASE_BACKGROUND event for ImageContainer.

Parameters: event – a wx.EraseEvent event to be processed.

OnMouseLeaveWindow(event) [source]

Handles the wx.EVT_LEAVE_WINDOW event for ImageContainer.

Parameters: event – a wx.MouseEvent event to be processed.

OnMouseLeftDown(event) [source]

Handles the wx.EVT_LEFT_DOWN event for ImageContainer.

Parameters: event – a wx.MouseEvent event to be processed.

OnMouseLeftUp(event) [source]

Handles the wx.EVT_LEFT_UP event for ImageContainer.

Parameters: event – a wx.MouseEvent event to be processed.

OnMouseMove(event) [source]

Handles the wx.EVT_MOTION event for ImageContainer.

Parameters: event – a wx.MouseEvent event to be processed.

OnPaint(event) [source]

Handles the wx.EVT_PAINT event for ImageContainer.

Parameters: event – a wx.PaintEvent event to be processed.

OnSize(event) [source]

Handles the wx.EVT_SIZE event for ImageContainer.

Parameters: event – a wx.SizeEvent event to be processed.

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • infobar
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • labelbook »
  • ImageContainer


ImageContainerBase

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • labelbook »
  • ImageContainerBase

ImageContainerBase

Base class for FlatImageBook image container.

hierarchy Inheritance Diagram

Inheritance diagram for: ImageContainerBase

Inheritance diagram of ImageContainerBase

subclasses Known Subclasses

  • labelbook.ImageContainer
  • labelbook.LabelContainer

Methods Summary

__init__ | Default class constructor.
AddPage | Adds a page to the container.
AssignImageList | Assigns an image list to the ImageContainerBase.
CanDoBottomStyle | Allows the parent to examine the children type.
ClearAll | Deletes all the pages in the container.
ClearFlag | Removes flag from the style.
DoDeletePage | Does the actual page deletion.
DrawPin | Draw a pin button, that allows collapsing of the image panel.
EnableTab | Enables or disables a tab.
FixTextSize | Fixes the text, to fit maxWidth value. If the text length exceeds
GetEnabled | Returns whether a tab is enabled or not.
GetImageList | Return the image list for ImageContainerBase.
GetImageSize | Returns the image size inside the ImageContainerBase image list.
GetPageImage | Returns the image index for the given page.
GetPageText | Returns the tab caption for the given page.
HasAGWFlag | Tests for existance of flag in the style.
HitTest | Returns the index of the tab at the specified position or wx.NOT_FOUND
InsertPage | Inserts a page into the container at the specified position.
OnEraseBackground | Handles the wx.EVT_ERASE_BACKGROUND event for ImageContainerBase.
OnMouseLeaveWindow | Handles the wx.EVT_LEAVE_WINDOW event for ImageContainerBase.
OnMouseLeftDown | Handles the wx.EVT_LEFT_DOWN event for ImageContainerBase.
OnMouseLeftUp | Handles the wx.EVT_LEFT_UP event for ImageContainerBase.
OnMouseMove | Handles the wx.EVT_MOTION event for ImageContainerBase.
OnSize | Handles the wx.EVT_SIZE event for ImageContainerBase.
PointOnSash | Tests whether pt is located on the sash.
SetPageImage | Sets the image for the given page.
SetPageText | Sets the tab caption for the given page.

API Class API

class ImageContainerBase(wx.Panel) [source]

Base class for FlatImageBook image container.

__init__(parent, id=wx.ID_ANY, pos=wx.DefaultPosition, size=wx.DefaultSize, style=0, agwStyle=0, name="ImageContainerBase") [source]

Default class constructor.

Parameters:
  • parent – parent window. Must not be None;
  • id – window identifier. A value of -1 indicates a default value;
  • pos – the control position. A value of (-1, -1) indicates a default position, chosen by either the windowing system or wxPython, depending on platform;
  • size – the control size. A value of (-1, -1) indicates a default size, chosen by either the windowing system or wxPython, depending on platform;
  • style – the underlying wx.Panel window style;
  • agwStyle – the AGW-specific window style. This can be a combination of the following bits:

    Window Styles | Hex Value | Description
    INB_BOTTOM | 0x1 | Place labels below the page area. Available only for FlatImageBook.
    INB_LEFT | 0x2 | Place labels on the left side. Available only for FlatImageBook.
    INB_RIGHT | 0x4 | Place labels on the right side.
    INB_TOP | 0x8 | Place labels above the page area.
    INB_BORDER | 0x10 | Draws a border around LabelBook or FlatImageBook.
    INB_SHOW_ONLY_TEXT | 0x20 | Shows only text labels and no images. Available only for LabelBook.
    INB_SHOW_ONLY_IMAGES | 0x40 | Shows only tab images and no label texts. Available only for LabelBook.
    INB_FIT_BUTTON | 0x80 | Displays a pin button to show/hide the book control.
    INB_DRAW_SHADOW | 0x100 | Draw shadows below the book tabs. Available only for LabelBook.
    INB_USE_PIN_BUTTON | 0x200 | Displays a pin button to show/hide the book control.
    INB_GRADIENT_BACKGROUND | 0x400 | Draws a gradient shading on the tabs background. Available only for LabelBook.
    INB_WEB_HILITE | 0x800 | On mouse hovering, tabs behave like html hyperlinks. Available only for LabelBook.
    INB_NO_RESIZE | 0x1000 | Don’t allow resizing of the tab area.
    INB_FIT_LABELTEXT | 0x2000 | Will fit the tab area to the longest text (or text+image if you have images) in all the tabs.
    INB_BOLD_TAB_SELECTION | 0x4000 | Show the selected tab text using a bold font.
  • name – the window name.

AddPage(caption, selected=False, imgIdx=-1) [source]

Adds a page to the container.

Parameters:
  • caption – specifies the text for the new tab;
  • selected – specifies whether the page should be selected;
  • imgIdx – specifies the optional image index for the new tab.

AssignImageList(imglist) [source]

Assigns an image list to the ImageContainerBase.

Parameters: imglist – an instance of wx.ImageList.

CanDoBottomStyle() [source]

Allows the parent to examine the children type. Some implementation (such as LabelBook), does not support top/bottom images, only left/right.

ClearAll() [source]

Deletes all the pages in the container.

ClearFlag(flag) [source]

Removes flag from the style.

Parameters: flag – a window style flag.

See also

HasAGWFlag for a list of possible window style flags.

DoDeletePage(page) [source]

Does the actual page deletion.

Parameters: page – the index of the tab.

DrawPin(dc, rect, downPin) [source]

Draw a pin button, that allows collapsing of the image panel.

Parameters:
  • dc – an instance of wx.DC;
  • rect – the pin button client rectangle;
  • downPin – True if the pin button is facing downwards, False if it is facing leftwards.

EnableTab(page, enabled=True) [source]

Enables or disables a tab.

Parameters:
  • page – an integer specifying the page index;
  • enabled – True to enable a tab, False to disable it.

FixTextSize(dc, text, maxWidth) [source]

Fixes the text, to fit maxWidth value. If the text length exceeds maxWidth value this function truncates it and appends two dots at the end. (“Long Long Long Text” might become “Long Long...”).

Parameters:
  • dc – an instance of wx.DC;

  • text – the text to fix/truncate;
  • maxWidth – the maximum allowed width for the text, in pixels.

GetEnabled(page) [source]

Returns whether a tab is enabled or not.

Parameters: page – an integer specifying the page index.

GetImageList() [source]

Return the image list for ImageContainerBase.

GetImageSize() [source]

Returns the image size inside the ImageContainerBase image list.

GetPageImage(page) [source]

Returns the image index for the given page.

Parameters: page – the index of the tab.

GetPageText(page) [source]

Returns the tab caption for the given page.

Parameters: page – the index of the tab.

HasAGWFlag(flag) [source]

Tests for existance of flag in the style.

Parameters: flag – a window style. This can be a combination of the following bits:

Window Styles | Hex Value | Description
INB_BOTTOM | 0x1 | Place labels below the page area. Available only for FlatImageBook.
INB_LEFT | 0x2 | Place labels on the left side. Available only for FlatImageBook.
INB_RIGHT | 0x4 | Place labels on the right side.
INB_TOP | 0x8 | Place labels above the page area.
INB_BORDER | 0x10 | Draws a border around LabelBook or FlatImageBook.
INB_SHOW_ONLY_TEXT | 0x20 | Shows only text labels and no images. Available only for LabelBook.
INB_SHOW_ONLY_IMAGES | 0x40 | Shows only tab images and no label texts. Available only for LabelBook.
INB_FIT_BUTTON | 0x80 | Displays a pin button to show/hide the book control.
INB_DRAW_SHADOW | 0x100 | Draw shadows below the book tabs. Available only for LabelBook.
INB_USE_PIN_BUTTON | 0x200 | Displays a pin button to show/hide the book control.
INB_GRADIENT_BACKGROUND | 0x400 | Draws a gradient shading on the tabs background. Available only for LabelBook.
INB_WEB_HILITE | 0x800 | On mouse hovering, tabs behave like html hyperlinks. Available only for LabelBook.
INB_NO_RESIZE | 0x1000 | Don’t allow resizing of the tab area.
INB_FIT_LABELTEXT | 0x2000 | Will fit the tab area to the longest text (or text+image if you have images) in all the tabs.
INB_BOLD_TAB_SELECTION | 0x4000 | Show the selected tab text using a bold font.

HitTest(pt) [source]

Returns the index of the tab at the specified position or wx.NOT_FOUND if None, plus the flag style of HitTest.

Parameters: pt – an instance of wx.Point, to test for hits.
Returns: The index of the tab at the specified position plus the hit test flag, which can be one of the following bits:
HitTest Flags | Value | Description
IMG_OVER_IMG | 0 | The mouse is over the tab icon
IMG_OVER_PIN | 1 | The mouse is over the pin button
IMG_OVER_EW_BORDER | 2 | The mouse is over the east-west book border
IMG_NONE | 3 | Nowhere

InsertPage(page_idx, caption, selected=False, imgIdx=-1) [source]

Inserts a page into the container at the specified position.

Parameters:
  • page_idx – specifies the position for the new tab;
  • caption – specifies the text for the new tab;
  • selected – specifies whether the page should be selected;
  • imgIdx – specifies the optional image index for the new tab.

OnEraseBackground(event) [source]

Handles the wx.EVT_ERASE_BACKGROUND event for ImageContainerBase.

Parameters: event – a wx.EraseEvent event to be processed.

Note

This method is intentionally empty to reduce flicker.

OnMouseLeaveWindow(event) [source]

Handles the wx.EVT_LEAVE_WINDOW event for ImageContainerBase.

Parameters: event – a wx.MouseEvent event to be processed.

OnMouseLeftDown(event) [source]

Handles the wx.EVT_LEFT_DOWN event for ImageContainerBase.

Parameters: event – a wx.MouseEvent event to be processed.

OnMouseLeftUp(event) [source]

Handles the wx.EVT_LEFT_UP event for ImageContainerBase.

Parameters: event – a wx.MouseEvent event to be processed.

OnMouseMove(event) [source]

Handles the wx.EVT_MOTION event for ImageContainerBase.

Parameters: event – a wx.MouseEvent event to be processed.

OnSize(event) [source]

Handles the wx.EVT_SIZE event for ImageContainerBase.

Parameters: event – a wx.SizeEvent event to be processed.

PointOnSash(pt) [source]

Tests whether pt is located on the sash.

Parameters: pt – an instance of wx.Point, to test for hits.

SetPageImage(page, imgIdx) [source]

Sets the image for the given page.

Parameters:
  • page – the index of the tab;
  • imgIdx – specifies the optional image index for the tab.

SetPageText(page, text) [source]

Sets the tab caption for the given page.

Parameters:
  • page – the index of the tab;
  • text – the new tab caption.

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • infobar
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • labelbook »
  • ImageContainerBase


ImageInfo

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • labelbook »
  • ImageInfo

ImageInfo

This class holds all the information (caption, image, etc...) belonging to a single tab in LabelBook.

hierarchy Inheritance Diagram

Inheritance diagram for: ImageInfo

Inheritance diagram of ImageInfo

Methods Summary

__init__ | Default class constructor.
EnableTab | Sets the tab enabled or disabled.
GetCaption | Returns the tab caption.
GetEnabled | Returns whether the tab is enabled or not.
GetImageIndex | Returns the tab image index.
GetPosition | Returns the tab position.
GetSize | Returns the tab size.
GetTextRect | Returns the client rectangle available for the tab text.
SetCaption | Sets the tab caption.
SetImageIndex | Sets the tab image index.
SetPosition | Sets the tab position.
SetSize | Sets the tab size.
SetTextRect | Sets the client rectangle available for the tab text.

API Class API

class ImageInfo(object) [source]

This class holds all the information (caption, image, etc...) belonging to a single tab in LabelBook.

__init__(strCaption='', imageIndex=-1, enabled=True) [source]

Default class constructor.

Parameters:
  • strCaption – the tab caption;
  • imageIndex – the tab image index based on the assigned (set) wx.ImageList (if any);
  • enabled – sets the tab as enabled or disabled.

EnableTab(enabled) [source]

Sets the tab enabled or disabled.

Parameters: enabled – True to enable a tab, False to disable it.

GetCaption() [source]

Returns the tab caption.

GetEnabled() [source]

Returns whether the tab is enabled or not.

GetImageIndex() [source]

Returns the tab image index.

GetPosition() [source]

Returns the tab position.

GetSize() [source]

Returns the tab size.

GetTextRect() [source]

Returns the client rectangle available for the tab text.

SetCaption(value) [source]

Sets the tab caption.

Parameters: value – the new tab caption.

SetImageIndex(value) [source]

Sets the tab image index.

Parameters: value – an index into the image list..

SetPosition(value) [source]

Sets the tab position.

Parameters: value – the new tab position, an instance of wx.Point.

SetSize(value) [source]

Sets the tab size.

Parameters: value – the new tab size, an instance of wx.Size.

SetTextRect(rect) [source]

Sets the client rectangle available for the tab text.

Parameters: rect – the tab text client rectangle, an instance of wx.Rect.

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • infobar
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • labelbook »
  • ImageInfo


ImageNotebookEvent

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • labelbook »
  • ImageNotebookEvent

ImageNotebookEvent

This events will be sent when a EVT_IMAGENOTEBOOK_PAGE_CHANGED, EVT_IMAGENOTEBOOK_PAGE_CHANGING, EVT_IMAGENOTEBOOK_PAGE_CLOSING, EVT_IMAGENOTEBOOK_PAGE_CLOSED is mapped in the parent.

hierarchy Inheritance Diagram

Inheritance diagram for: ImageNotebookEvent

Inheritance diagram of ImageNotebookEvent

Methods Summary

__init__ | Default class constructor.
Allow | This is the opposite of Veto: it explicitly allows the event to be processed.
GetOldSelection | Returns the old event selection.
GetSelection | Returns the event selection.
IsAllowed | Returns True if the change is allowed (Veto hasn’t been called) or
SetOldSelection | Sets the event old selection.
SetSelection | Sets the event selection.
Veto | Prevents the change announced by this event from happening.

API Class API

class ImageNotebookEvent(wx.PyCommandEvent) [source]

This events will be sent when a EVT_IMAGENOTEBOOK_PAGE_CHANGED, EVT_IMAGENOTEBOOK_PAGE_CHANGING, EVT_IMAGENOTEBOOK_PAGE_CLOSING, EVT_IMAGENOTEBOOK_PAGE_CLOSED is mapped in the parent.

__init__(eventType, eventId=1, sel=-1, oldsel=-1) [source]

Default class constructor.

Parameters:
  • eventType – the event type;
  • eventId – the event identifier;
  • sel – the current selection;
  • oldsel – the old selection.

Allow() [source]

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

GetOldSelection() [source]

Returns the old event selection.

GetSelection() [source]

Returns the event selection.

IsAllowed() [source]

Returns True if the change is allowed (Veto hasn’t been called) or False otherwise (if it was).

SetOldSelection(s) [source]

Sets the event old selection.

Parameters: s – an integer specifying the old selection.

SetSelection(s) [source]

Sets the event selection.

Parameters: s – an integer specifying the new selection.

Veto() [source]

Prevents the change announced by this event from happening.

Note

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

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • infobar
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • labelbook »
  • ImageNotebookEvent


LabelBook

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • labelbook »
  • LabelBook

LabelBook

An implementation of a notebook control - except that instead of having tabs to show labels, it labels to the right or left (arranged horizontally).

hierarchy Inheritance Diagram

Inheritance diagram for: LabelBook

Inheritance diagram of LabelBook

supclasses Known Superclasses

  • labelbook.FlatBookBase

appearance Control Appearance

LabelBook

Methods Summary

__init__ | Default class constructor.
CreateImageContainer | Creates the image container (LabelContainer) class for FlatImageBook.
GetColour | Returns the colour for the specified parameter.
OnSize | Handles the wx.EVT_SIZE event for LabelBook.
SetColour | Sets the colour for the specified parameter.

API Class API

class LabelBook(FlatBookBase) [source]

An implementation of a notebook control - except that instead of having tabs to show labels, it labels to the right or left (arranged horizontally).

__init__(parent, id=wx.ID_ANY, pos=wx.DefaultPosition, size=wx.DefaultSize, style=0, agwStyle=0, name="LabelBook") [source]

Default class constructor.

Parameters:
  • parent – parent window. Must not be None;
  • id – window identifier. A value of -1 indicates a default value;
  • pos – the control position. A value of (-1, -1) indicates a default position, chosen by either the windowing system or wxPython, depending on platform;
  • size – the control size. A value of (-1, -1) indicates a default size, chosen by either the windowing system or wxPython, depending on platform;
  • style – the underlying wx.Panel window style;
  • agwStyle – the AGW-specific window style. This can be a combination of the following bits:

    Window Styles | Hex Value | Description
    INB_BOTTOM | 0x1 | Place labels below the page area. Available only for FlatImageBook.
    INB_LEFT | 0x2 | Place labels on the left side. Available only for FlatImageBook.
    INB_RIGHT | 0x4 | Place labels on the right side.
    INB_TOP | 0x8 | Place labels above the page area.
    INB_BORDER | 0x10 | Draws a border around LabelBook or FlatImageBook.
    INB_SHOW_ONLY_TEXT | 0x20 | Shows only text labels and no images. Available only for LabelBook.
    INB_SHOW_ONLY_IMAGES | 0x40 | Shows only tab images and no label texts. Available only for LabelBook.
    INB_FIT_BUTTON | 0x80 | Displays a pin button to show/hide the book control.
    INB_DRAW_SHADOW | 0x100 | Draw shadows below the book tabs. Available only for LabelBook.
    INB_USE_PIN_BUTTON | 0x200 | Displays a pin button to show/hide the book control.
    INB_GRADIENT_BACKGROUND | 0x400 | Draws a gradient shading on the tabs background. Available only for LabelBook.
    INB_WEB_HILITE | 0x800 | On mouse hovering, tabs behave like html hyperlinks. Available only for LabelBook.
    INB_NO_RESIZE | 0x1000 | Don’t allow resizing of the tab area.
    INB_FIT_LABELTEXT | 0x2000 | Will fit the tab area to the longest text (or text+image if you have images) in all the tabs.
    INB_BOLD_TAB_SELECTION | 0x4000 | Show the selected tab text using a bold font.
  • name – the window name.

CreateImageContainer() [source]

Creates the image container (LabelContainer) class for FlatImageBook.

GetColour(which) [source]

Returns the colour for the specified parameter.

Parameters: which – the colour key.

See also

LabelContainer.SetColour() for a list of valid colour keys.

OnSize(event) [source]

Handles the wx.EVT_SIZE event for LabelBook.

Parameters: event – a wx.SizeEvent event to be processed.

SetColour(which, colour) [source]

Sets the colour for the specified parameter.

Parameters:
  • which – the colour key;
  • colour – a valid wx.Colour instance.

See also

LabelContainer.SetColour() for a list of valid colour keys.

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • infobar
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • labelbook »
  • LabelBook


LabelContainer

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • labelbook »
  • LabelContainer

LabelContainer

Base class for LabelBook.

hierarchy Inheritance Diagram

Inheritance diagram for: LabelContainer

Inheritance diagram of LabelContainer

supclasses Known Superclasses

  • labelbook.ImageContainerBase

Methods Summary

__init__ | Default class constructor.
CanDoBottomStyle | Allows the parent to examine the children type.
DrawBackgroundBitmap | Draws a bitmap as the background of the control.
DrawLabel | Draws a label using the specified dc.
DrawRegularHover | Draws a rounded rectangle around the current tab.
DrawWebHover | Draws a web style hover effect (cursor set to hand & text is underlined).
GetColour | Returns a colour for a parameter.
GetTabAreaWidth | Returns the width of the tab area.
InitializeColours | Initializes the colours map to be used for this control.
OnEraseBackground | Handles the wx.EVT_ERASE_BACKGROUND event for LabelContainer.
OnMouseLeaveWindow | Handles the wx.EVT_LEAVE_WINDOW event for LabelContainer.
OnMouseLeftDown | Handles the wx.EVT_LEFT_DOWN event for LabelContainer.
OnMouseLeftUp | Handles the wx.EVT_LEFT_UP event for LabelContainer.
OnMouseMove | Handles the wx.EVT_MOTION event for LabelContainer.
OnPaint | Handles the wx.EVT_PAINT event for LabelContainer.
OnSize | Handles the wx.EVT_SIZE event for LabelContainer.
Resize | Actually resizes the tab area.
SetBackgroundBitmap | Sets the background bitmap for the control.
SetColour | Sets a colour for a parameter.
SetTabAreaWidth | Sets the width of the tab area.

API Class API

class LabelContainer(ImageContainerBase) [source]

Base class for LabelBook.

__init__(parent, id=wx.ID_ANY, pos=wx.DefaultPosition, size=wx.DefaultSize, style=0, agwStyle=0, name="LabelContainer") [source]

Default class constructor.

Parameters:
  • parent – parent window. Must not be None;
  • id – window identifier. A value of -1 indicates a default value;
  • pos – the control position. A value of (-1, -1) indicates a default position, chosen by either the windowing system or wxPython, depending on platform;
  • size – the control size. A value of (-1, -1) indicates a default size, chosen by either the windowing system or wxPython, depending on platform;
  • style – the underlying wx.Panel window style;
  • agwStyle – the AGW-specific window style. This can be a combination of the following bits:

    Window Styles | Hex Value | Description
    INB_BOTTOM | 0x1 | Place labels below the page area. Available only for FlatImageBook.
    INB_LEFT | 0x2 | Place labels on the left side. Available only for FlatImageBook.
    INB_RIGHT | 0x4 | Place labels on the right side.
    INB_TOP | 0x8 | Place labels above the page area.
    INB_BORDER | 0x10 | Draws a border around LabelBook or FlatImageBook.
    INB_SHOW_ONLY_TEXT | 0x20 | Shows only text labels and no images. Available only for LabelBook.
    INB_SHOW_ONLY_IMAGES | 0x40 | Shows only tab images and no label texts. Available only for LabelBook.
    INB_FIT_BUTTON | 0x80 | Displays a pin button to show/hide the book control.
    INB_DRAW_SHADOW | 0x100 | Draw shadows below the book tabs. Available only for LabelBook.
    INB_USE_PIN_BUTTON | 0x200 | Displays a pin button to show/hide the book control.
    INB_GRADIENT_BACKGROUND | 0x400 | Draws a gradient shading on the tabs background. Available only for LabelBook.
    INB_WEB_HILITE | 0x800 | On mouse hovering, tabs behave like html hyperlinks. Available only for LabelBook.
    INB_NO_RESIZE | 0x1000 | Don’t allow resizing of the tab area.
    INB_FIT_LABELTEXT | 0x2000 | Will fit the tab area to the longest text (or text+image if you have images) in all the tabs.
    INB_BOLD_TAB_SELECTION | 0x4000 | Show the selected tab text using a bold font.
  • name – the window name.

CanDoBottomStyle() [source]

Allows the parent to examine the children type. Some implementation (such as LabelBook), does not support top/bottom images, only left/right.

DrawBackgroundBitmap(dc) [source]

Draws a bitmap as the background of the control.

Parameters: dc – an instance of wx.DC.

DrawLabel(dc, rect, text, bmp, imgInfo, orientationLeft, imgIdx, selected, hover) [source]

Draws a label using the specified dc.

Parameters:
  • dc – an instance of wx.DC;

  • rect – the text client rectangle;
  • text – the actual text string;
  • bmp – a bitmap to be drawn next to the text;
  • imgInfo – an instance of ImageInfo;
  • orientationLeft – True if the book has the INB_RIGHT or INB_LEFT style set;
  • imgIdx – the tab image index;
  • selected – True if the tab is selected, False otherwise;
  • hover – True if the tab is being hovered with the mouse, False otherwise.

DrawRegularHover(dc, rect) [source]

Draws a rounded rectangle around the current tab.

Parameters:
  • dc – an instance of wx.DC;

  • rect – the current tab client rectangle.

DrawWebHover(dc, caption, xCoord, yCoord, selected) [source]

Draws a web style hover effect (cursor set to hand & text is underlined).

Parameters:
  • dc – an instance of wx.DC;

  • caption – the tab caption text;
  • xCoord – the x position of the tab caption;
  • yCoord – the y position of the tab caption;
  • selected – True if the tab is selected, False otherwise.

GetColour(which) [source]

Returns a colour for a parameter.

Parameters: which – the colour key.

See also

SetColour for a list of valid colour keys.

GetTabAreaWidth() [source]

Returns the width of the tab area.

InitializeColours() [source]

Initializes the colours map to be used for this control.

OnEraseBackground(event) [source]

Handles the wx.EVT_ERASE_BACKGROUND event for LabelContainer.

Parameters: event – a wx.EraseEvent event to be processed.

OnMouseLeaveWindow(event) [source]

Handles the wx.EVT_LEAVE_WINDOW event for LabelContainer.

Parameters: event – a wx.MouseEvent event to be processed.

OnMouseLeftDown(event) [source]

Handles the wx.EVT_LEFT_DOWN event for LabelContainer.

Parameters: event – a wx.MouseEvent event to be processed.

OnMouseLeftUp(event) [source]

Handles the wx.EVT_LEFT_UP event for LabelContainer.

Parameters: event – a wx.MouseEvent event to be processed.

OnMouseMove(event) [source]

Handles the wx.EVT_MOTION event for LabelContainer.

Parameters: event – a wx.MouseEvent event to be processed.

OnPaint(event) [source]

Handles the wx.EVT_PAINT event for LabelContainer.

Parameters: event – a wx.PaintEvent event to be processed.

OnSize(event) [source]

Handles the wx.EVT_SIZE event for LabelContainer.

Parameters: event – a wx.SizeEvent event to be processed.

Resize(event) [source]

Actually resizes the tab area.

Parameters: event – an instance of wx.SizeEvent.

SetBackgroundBitmap(bmp) [source]

Sets the background bitmap for the control.

Parameters: bmp – a valid wx.Bitmap object.

SetColour(which, colour) [source]

Sets a colour for a parameter.

Parameters:
  • which – can be one of the following parameters:

    Colour Key | Value | Description
    INB_TAB_AREA_BACKGROUND_COLOUR | 100 | The tab area background colour
    INB_ACTIVE_TAB_COLOUR | 101 | The active tab background colour
    INB_TABS_BORDER_COLOUR | 102 | The tabs border colour
    INB_TEXT_COLOUR | 103 | The tab caption text colour
    INB_ACTIVE_TEXT_COLOUR | 104 | The active tab caption text colour
    INB_HILITE_TAB_COLOUR | 105 | The tab caption highlight text colour
  • colour – a valid wx.Colour object.

SetTabAreaWidth(width) [source]

Sets the width of the tab area.

Parameters: width – the width of the tab area, in pixels.

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • infobar
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • labelbook »
  • LabelContainer


SVN Revision 68362 For labelbook

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • labelbook »
  • SVN Revision 68362 For labelbook

svn SVN Revision 68362 For labelbook

This file contains the SVN revision history for labelbook, at revision 68362.

Available information include commit date, the name of the committer, the file size, the SVN log messages and a diff from the previous version (if available).

File Information

  • Commit Date: 12-May-2009 15:04:45 UTC
  • Committer: AG
  • File Size: 106199 byte(s)

Log Messages

The following log message was entered by the committer:

  • All of AGW: change my work e-mail from KPO to Maersk Oil (silly commit)

Diff To Previous Version (66701)

Version SVN diff:

--- wxPython/3rdParty/AGW/agw/labelbook.py  2011/01/17 15:11:31     66701
+++ wxPython/3rdParty/AGW/agw/labelbook.py  2011/07/24 21:36:47     68362
@@ -17,7 +17,7 @@
# Write To Me At:
#
# andrea.gavana@gmail.com
-# gavana@kpo.kz
+# andrea.gavana@maerskoil.com
#
# Or, Obviously, To The wxPython Mailing List!!!
#

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • labelbook »
  • SVN Revision 68362 For labelbook


SVN Revision 68775 For labelbook

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • labelbook »
  • SVN Revision 68775 For labelbook

svn SVN Revision 68775 For labelbook

This file contains the SVN revision history for labelbook, at revision 68775.

Available information include commit date, the name of the committer, the file size, the SVN log messages and a diff from the previous version (if available).

File Information

  • Commit Date: 12-May-2009 14:58:36 UTC
  • Committer: AG
  • File Size: 107380 byte(s)

Log Messages

The following log message was entered by the committer:

  • LabelBook &amp; FlatImageBook: don’t use GetName() to get the class, use isinstance(). Fixes ticket #13410.

Diff To Previous Version (68362)

Version SVN diff:

--- wxPython/3rdParty/AGW/agw/labelbook.py  2011/07/24 21:36:47     68362
+++ wxPython/3rdParty/AGW/agw/labelbook.py  2011/08/18 19:31:19     68775
@@ -10,7 +10,7 @@
# Python Code By:
#
# Andrea Gavana, @ 03 Nov 2006
-# Latest Revision: 17 Jan 2011, 15.00 GMT
+# Latest Revision: 17 Aug 2011, 15.00 GMT
#
#
# For All Kind Of Problems, Requests Of Enhancements And Bug Reports, Please
@@ -23,7 +23,7 @@
#
# TODO:
# LabelBook - Support IMB_SHOW_ONLY_IMAGES
-# LabelBook - An option for the draw border to only draw the border
+# LabelBook - An option to only draw the border
#             between the controls and the pages so the background
#             colour can flow into the window background
#
@@ -33,17 +33,17 @@
# --------------------------------------------------------------------------- #

"""
-LabelBook and FlatImageBook are a quasi-full generic and owner-drawn
+L{LabelBook} and L{FlatImageBook} are a quasi-full generic and owner-drawn
implementations of `wx.Notebook`.

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

-LabelBook and FlatImageBook are a quasi-full implementations of the `wx.Notebook`,
+L{LabelBook} and L{FlatImageBook} are quasi-full implementations of the `wx.Notebook`,
and designed to be a drop-in replacement for `wx.Notebook`. The API functions are
similar so one can expect the function to behave in the same way.
-LabelBook anf FlatImageBook share their appearance with `wx.Toolbook` and
+L{LabelBook} anf L{FlatImageBook} share their appearance with `wx.Toolbook` and
`wx.Listbook`, while having more options for custom drawings, label positioning,
mouse pointing and so on. Moreover, they retain also some visual characteristics
of the Outlook address book.
@@ -51,25 +51,68 @@
Some features:

- They are generic controls;
-- Supports for left, right, top (FlatImageBook only), bottom (FlatImageBook
+- Supports for left, right, top (L{FlatImageBook} only), bottom (L{FlatImageBook}
only) book styles;
-- Possibility to draw images only, text only or both (FlatImageBook only);
+- Possibility to draw images only, text only or both (L{FlatImageBook} only);
- Support for a "pin-button", that allows the user to shrink/expand the book
tab area;
-- Shadows behind tabs (LabelBook only);
-- Gradient shading of the tab area (LabelBook only);
-- Web-like mouse pointing on tabs style (LabelBook only);
+- Shadows behind tabs (L{LabelBook} only);
+- Gradient shading of the tab area (L{LabelBook} only);
+- Web-like mouse pointing on tabs style (L{LabelBook} only);
- Many customizable colours (tab area, active tab text, tab borders, active
-  tab, highlight) - LabelBook only.
+  tab, highlight) - L{LabelBook} only.

And much more. See the demo for a quasi-complete review of all the functionalities
-of LabelBook and FlatImageBook.
+of L{LabelBook} and L{FlatImageBook}.
+
+
+Usage
+=====
+
+Usage example::
+
+    import wx
+    import wx.lib.agw.labelbook as LB
+
+    class MyFrame(wx.Frame):
+
+        def __init__(self, parent):
+
+            wx.Frame.__init__(self, parent)
+
+            # Possible values for Tab placement are INB_TOP, INB_BOTTOM, INB_RIGHT, INB_LEFT
+
+            notebook = LB.LabelBook(self, -1, agwStyle=LB.INB_FIT_LABELTEXT|LB.INB_LEFT| \
+                                                       LB.INB_DRAW_SHADOW| \
+                                                       LB.INB_GRADIENT_BACKGROUND|LB.INB_BORDER)
+
+            pane1 = wx.Panel(notebook)
+            pane2 = wx.Panel(notebook)
+
+            imagelist = wx.ImageList(32, 32)
+            imagelist.Add(wx.Bitmap("my_bitmap.png", wx.BITMAP_TYPE_PNG))
+            notebook.AssignImageList(imagelist)
+
+            notebook.AddPage(pane_1, "Tab1", 1, 0)
+            notebook.AddPage(pane_2, "Tab2", 0, 0)
+
+
+    # our normal wxApp-derived class, as usual
+
+    app = wx.PySimpleApp()
+
+    frame = MyFrame(None)
+    app.SetTopWindow(frame)
+    frame.Show()
+
+    app.MainLoop()
+

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

-LabelBook and FlatImageBook have been tested on the following platforms:
+L{LabelBook} and L{FlatImageBook} have been tested on the following platforms:
* Windows (Windows XP);
* Linux Ubuntu (Dapper 6.06)

@@ -82,18 +125,18 @@
=========================== =========== ==================================================
Window Styles               Hex Value   Description
=========================== =========== ==================================================
-``INB_BOTTOM``                      0x1 Place labels below the page area. Available only for `FlatImageBook`.
-``INB_LEFT``                        0x2 Place labels on the left side. Available only for `FlatImageBook`.
+``INB_BOTTOM``                      0x1 Place labels below the page area. Available only for L{FlatImageBook}.
+``INB_LEFT``                        0x2 Place labels on the left side. Available only for L{FlatImageBook}.
``INB_RIGHT``                       0x4 Place labels on the right side.
``INB_TOP``                         0x8 Place labels above the page area.
-``INB_BORDER``                     0x10 Draws a border around `LabelBook` or `FlatImageBook`.
-``INB_SHOW_ONLY_TEXT``             0x20 Shows only text labels and no images. Available only for `LabelBook`.
-``INB_SHOW_ONLY_IMAGES``           0x40 Shows only tab images and no label texts. Available only for `LabelBook`.
+``INB_BORDER``                     0x10 Draws a border around L{LabelBook} or L{FlatImageBook}.
+``INB_SHOW_ONLY_TEXT``             0x20 Shows only text labels and no images. Available only for L{LabelBook}.
+``INB_SHOW_ONLY_IMAGES``           0x40 Shows only tab images and no label texts. Available only for L{LabelBook}.
``INB_FIT_BUTTON``                 0x80 Displays a pin button to show/hide the book control.
-``INB_DRAW_SHADOW``               0x100 Draw shadows below the book tabs. Available only for `LabelBook`.
+``INB_DRAW_SHADOW``               0x100 Draw shadows below the book tabs. Available only for L{LabelBook}.
``INB_USE_PIN_BUTTON``            0x200 Displays a pin button to show/hide the book control.
-``INB_GRADIENT_BACKGROUND``       0x400 Draws a gradient shading on the tabs background. Available only for `LabelBook`.
-``INB_WEB_HILITE``                0x800 On mouse hovering, tabs behave like html hyperlinks. Available only for `LabelBook`.
+``INB_GRADIENT_BACKGROUND``       0x400 Draws a gradient shading on the tabs background. Available only for L{LabelBook}.
+``INB_WEB_HILITE``                0x800 On mouse hovering, tabs behave like html hyperlinks. Available only for L{LabelBook}.
``INB_NO_RESIZE``                0x1000 Don't allow resizing of the tab area.
``INB_FIT_LABELTEXT``            0x2000 Will fit the tab area to the longest text (or text+image if you have images) in all the tabs.
=========================== =========== ==================================================
@@ -107,19 +150,19 @@
=================================== ==================================================
Event Name                          Description
=================================== ==================================================
-``EVT_IMAGENOTEBOOK_PAGE_CHANGED``  Notify client objects when the active page in `ImageNotebook` has changed.
-``EVT_IMAGENOTEBOOK_PAGE_CHANGING`` Notify client objects when the active page in `ImageNotebook` is about to change.
-``EVT_IMAGENOTEBOOK_PAGE_CLOSED``   Notify client objects when a page in `ImageNotebook` has been closed.
-``EVT_IMAGENOTEBOOK_PAGE_CLOSING``  Notify client objects when a page in `ImageNotebook` is closing.
+``EVT_IMAGENOTEBOOK_PAGE_CHANGED``  Notify client objects when the active page in L{FlatImageBook} or L{LabelBook} has changed.
+``EVT_IMAGENOTEBOOK_PAGE_CHANGING`` Notify client objects when the active page in L{FlatImageBook} or L{LabelBook} is about to change.
+``EVT_IMAGENOTEBOOK_PAGE_CLOSED``   Notify client objects when a page in L{FlatImageBook} or L{LabelBook} has been closed.
+``EVT_IMAGENOTEBOOK_PAGE_CLOSING``  Notify client objects when a page in L{FlatImageBook} or L{LabelBook} is closing.
=================================== ==================================================

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

-LabelBook and FlatImageBook are distributed under the wxPython license.
+L{LabelBook} and L{FlatImageBook} are distributed under the wxPython license.

-Latest Revision: Andrea Gavana @ 17 Jan 2011, 15.00 GMT
+Latest Revision: Andrea Gavana @ 17 Aug 2011, 15.00 GMT

Version 0.5.

@@ -143,29 +186,29 @@

# FlatImageBook and LabelBook styles
INB_BOTTOM = 1
-""" Place labels below the page area. Available only for `FlatImageBook`."""
+""" Place labels below the page area. Available only for L{FlatImageBook}."""
INB_LEFT = 2
-""" Place labels on the left side. Available only for `FlatImageBook`."""
+""" Place labels on the left side. Available only for L{FlatImageBook}."""
INB_RIGHT = 4
""" Place labels on the right side. """
INB_TOP = 8
""" Place labels above the page area. """
INB_BORDER = 16
-""" Draws a border around `LabelBook` or `FlatImageBook`. """
+""" Draws a border around L{LabelBook} or L{FlatImageBook}. """
INB_SHOW_ONLY_TEXT = 32
-""" Shows only text labels and no images. Available only for `LabelBook`."""
+""" Shows only text labels and no images. Available only for L{LabelBook}."""
INB_SHOW_ONLY_IMAGES = 64
-""" Shows only tab images and no label texts. Available only for `LabelBook`."""
+""" Shows only tab images and no label texts. Available only for L{LabelBook}."""
INB_FIT_BUTTON = 128
""" Displays a pin button to show/hide the book control. """
INB_DRAW_SHADOW = 256
-""" Draw shadows below the book tabs. Available only for `LabelBook`."""
+""" Draw shadows below the book tabs. Available only for L{LabelBook}."""
INB_USE_PIN_BUTTON = 512
""" Displays a pin button to show/hide the book control. """
INB_GRADIENT_BACKGROUND = 1024
-""" Draws a gradient shading on the tabs background. Available only for `LabelBook`."""
+""" Draws a gradient shading on the tabs background. Available only for L{LabelBook}."""
INB_WEB_HILITE = 2048
-""" On mouse hovering, tabs behave like html hyperlinks. Available only for `LabelBook`."""
+""" On mouse hovering, tabs behave like html hyperlinks. Available only for L{LabelBook}."""
INB_NO_RESIZE = 4096
""" Don't allow resizing of the tab area. """
INB_FIT_LABELTEXT = 8192
@@ -181,13 +224,13 @@
#-----------------------------------#

EVT_IMAGENOTEBOOK_PAGE_CHANGED = wx.EVT_NOTEBOOK_PAGE_CHANGED
-""" Notify client objects when the active page in `ImageNotebook` has changed. """
+""" Notify client objects when the active page in L{FlatImageBook} or L{LabelBook} has changed. """
EVT_IMAGENOTEBOOK_PAGE_CHANGING = wx.EVT_NOTEBOOK_PAGE_CHANGING
-""" Notify client objects when the active page in `ImageNotebook` is about to change. """
+""" Notify client objects when the active page in L{FlatImageBook} or L{LabelBook} is about to change. """
EVT_IMAGENOTEBOOK_PAGE_CLOSING = wx.PyEventBinder(wxEVT_IMAGENOTEBOOK_PAGE_CLOSING, 1)
-""" Notify client objects when a page in `ImageNotebook` is closing. """
+""" Notify client objects when a page in L{FlatImageBook} or L{LabelBook} is closing. """
EVT_IMAGENOTEBOOK_PAGE_CLOSED = wx.PyEventBinder(wxEVT_IMAGENOTEBOOK_PAGE_CLOSED, 1)
-""" Notify client objects when a page in `ImageNotebook` has been closed. """
+""" Notify client objects when a page in L{FlatImageBook} or L{LabelBook} has been closed. """

# ---------------------------------------------------------------------------- #
@@ -2153,10 +2196,7 @@

self._mainSizer.Detach(self._pages)

-        # Create new sizer with the requested orientaion
-        className = self.GetName()
-
-        if className == "LabelBook":
+        if isinstance(self, LabelBook):
self._mainSizer = wx.BoxSizer(wx.HORIZONTAL)
else:
if agwStyle & INB_LEFT or agwStyle & INB_RIGHT:
@@ -2169,8 +2209,7 @@
# Add the tab container and the separator
self._mainSizer.Add(self._pages, 0, wx.EXPAND)

-        if className == "FlatImageBook":
-
+        if isinstance(self, FlatImageBook):
if agwStyle & INB_LEFT or agwStyle & INB_RIGHT:
self._pages.SetSizeHints(self._pages._nImgSize * 2, -1)
else:

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • labelbook »
  • SVN Revision 68775 For labelbook


SVN Revision 68881 For labelbook

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • labelbook »
  • SVN Revision 68881 For labelbook

svn SVN Revision 68881 For labelbook

This file contains the SVN revision history for labelbook, at revision 68881.

Available information include commit date, the name of the committer, the file size, the SVN log messages and a diff from the previous version (if available).

File Information

  • Commit Date: 20-Oct-2008 20:05:15 UTC
  • Committer: AG
  • File Size: 107272 byte(s)

Log Messages

The following log message was entered by the committer:

  • AGW: General overhaul of the documentation, much improved. All the widgets have their own sample usage in the docs as well;

  • FlatNotebook: Added the FNB_NAV_BUTTONS_WHEN_NEEDED style, which hides the navigation left/right arrows if all tabs fit;

  • RibbonBar: - Added the EVT_RIBBONBAR_TAB_LEFT_DCLICK event, which generates a special event

    when a ribbon bar tab is double-clicked;

    • Added support for toggle buttons;
    • Improved support for ribbon panel sizers: panels with sizers should now automatically minimise at small sizes, and behave properly when popping up from a minimised state;
    • Added tooltips via SetToolTip for those buttons which have the help_string attribute set.

  • XLSGrid: a new widget was added to AGW, termed XLSGrid. It’s based on wx.grid.Grid and can be used to faithfully reproduce the appearance of a Microsoft Excel spreadsheets.

Diff To Previous Version (68775)

Version SVN diff:

--- wxPython/3rdParty/AGW/agw/labelbook.py  2011/08/18 19:31:19     68775
+++ wxPython/3rdParty/AGW/agw/labelbook.py  2011/08/25 16:40:17     68881
@@ -78,13 +78,11 @@

def __init__(self, parent):

-            wx.Frame.__init__(self, parent)
+            wx.Frame.__init__(self, parent, -1, "LabelBook Demo")

# Possible values for Tab placement are INB_TOP, INB_BOTTOM, INB_RIGHT, INB_LEFT

-            notebook = LB.LabelBook(self, -1, agwStyle=LB.INB_FIT_LABELTEXT|LB.INB_LEFT| \
-                                                       LB.INB_DRAW_SHADOW| \
-                                                       LB.INB_GRADIENT_BACKGROUND|LB.INB_BORDER)
+            notebook = LB.LabelBook(self, -1, agwStyle=LB.INB_FIT_LABELTEXT|LB.INB_LEFT|LB.INB_DRAW_SHADOW|LB.INB_GRADIENT_BACKGROUND)

pane1 = wx.Panel(notebook)
pane2 = wx.Panel(notebook)

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • labelbook »
  • SVN Revision 68881 For labelbook


SVN Revision 69803 For labelbook

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • labelbook »
  • SVN Revision 69803 For labelbook

svn SVN Revision 69803 For labelbook

This file contains the SVN revision history for labelbook, at revision 69803.

Available information include commit date, the name of the committer, the file size, the SVN log messages and a diff from the previous version (if available).

File Information

  • Commit Date: 17-Oct-2008 20:51:43 UTC
  • Committer: AG
  • File Size: 107288 byte(s)

Log Messages

The following log message was entered by the committer:

LabelBook: add page changing/changed events when using AddPage/InsertPage.

Diff To Previous Version (68881)

Version SVN diff:

--- wxPython/3rdParty/AGW/agw/labelbook.py  2011/08/25 16:40:17     68881
+++ wxPython/3rdParty/AGW/agw/labelbook.py  2011/11/23 17:47:12     69803
@@ -10,7 +10,7 @@
# Python Code By:
#
# Andrea Gavana, @ 03 Nov 2006
-# Latest Revision: 17 Aug 2011, 15.00 GMT
+# Latest Revision: 23 Nov 2011, 18.00 GMT
#
#
# For All Kind Of Problems, Requests Of Enhancements And Bug Reports, Please
@@ -160,7 +160,7 @@

L{LabelBook} and L{FlatImageBook} are distributed under the wxPython license.

-Latest Revision: Andrea Gavana @ 17 Aug 2011, 15.00 GMT
+Latest Revision: Andrea Gavana @ 23 Nov 2011, 18.00 GMT

Version 0.5.

@@ -2270,7 +2270,7 @@
self._windows.append(page)

if select or len(self._windows) == 1:
-            self.DoSetSelection(page)
+            self.SetSelection(len(self._windows)-1)
else:
page.Hide()

@@ -2300,7 +2300,7 @@
self._windows.insert(page_idx, page)

if select or len(self._windows) == 1:
-            self.DoSetSelection(page)
+            self.SetSelection(page_idx)
else:
page.Hide()

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • labelbook »
  • SVN Revision 69803 For labelbook


SVN Revision 69946 For labelbook

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • labelbook »
  • SVN Revision 69946 For labelbook

svn SVN Revision 69946 For labelbook

This file contains the SVN revision history for labelbook, at revision 69946.

Available information include commit date, the name of the committer, the file size, the SVN log messages and a diff from the previous version (if available).

File Information

  • Commit Date: 17-Oct-2008 19:15:31 UTC
  • Committer: AG
  • File Size: 111405 byte(s)

Log Messages

The following log message was entered by the committer:

  • LabelBook: added the ability to have enabled/disabled tabs (thanks to David Hughes for the patch);
  • LabelBook: now Ctrl+Tab switches between tabs as the normal wx.Notebook does;
  • LabelBook: Added the new style INB_BOLD_TAB_SELECTION to use a bold font for the selected tab text.

Diff To Previous Version (69803)

Version SVN diff:

--- wxPython/3rdParty/AGW/agw/labelbook.py  2011/11/23 17:47:12     69803
+++ wxPython/3rdParty/AGW/agw/labelbook.py  2011/12/07 20:16:28     69946
@@ -10,7 +10,7 @@
# Python Code By:
#
# Andrea Gavana, @ 03 Nov 2006
-# Latest Revision: 23 Nov 2011, 18.00 GMT
+# Latest Revision: 07 Dec 2011, 21.00 GMT
#
#
# For All Kind Of Problems, Requests Of Enhancements And Bug Reports, Please
@@ -137,6 +137,7 @@
``INB_WEB_HILITE``                0x800 On mouse hovering, tabs behave like html hyperlinks. Available only for L{LabelBook}.
``INB_NO_RESIZE``                0x1000 Don't allow resizing of the tab area.
``INB_FIT_LABELTEXT``            0x2000 Will fit the tab area to the longest text (or text+image if you have images) in all the tabs.
+``INB_BOLD_TAB_SELECTION``       0x4000 Show the selected tab text using a bold font.
=========================== =========== ==================================================

@@ -155,18 +156,27 @@
=================================== ==================================================

+TODOs
+=====
+
+- L{LabelBook}: support ``IMB_SHOW_ONLY_IMAGES``;
+- L{LabelBook}: an option to only draw the border between the controls and the pages so the background
+  colour can flow into the window background.
+
+
License And Version
===================

L{LabelBook} and L{FlatImageBook} are distributed under the wxPython license.

-Latest Revision: Andrea Gavana @ 23 Nov 2011, 18.00 GMT
+Latest Revision: Andrea Gavana @ 07 Dec 2011, 21.00 GMT

-Version 0.5.
+Version 0.6.

"""

__docformat__ = "epytext"
+__version__ = "0.6"

#----------------------------------------------------------------------
@@ -211,6 +221,8 @@
""" Don't allow resizing of the tab area. """
INB_FIT_LABELTEXT = 8192
""" Will fit the tab area to the longest text (or text+image if you have images) in all the tabs. """
+INB_BOLD_TAB_SELECTION = 16384
+""" Show the selected tab text using a bold font. """

wxEVT_IMAGENOTEBOOK_PAGE_CHANGED = wx.wxEVT_COMMAND_NOTEBOOK_PAGE_CHANGED
wxEVT_IMAGENOTEBOOK_PAGE_CHANGING = wx.wxEVT_COMMAND_NOTEBOOK_PAGE_CHANGING
@@ -332,13 +344,14 @@
This class holds all the information (caption, image, etc...) belonging to a
single tab in L{LabelBook}.
"""
-    def __init__(self, strCaption="", imageIndex=-1):
+    def __init__(self, strCaption="", imageIndex=-1, enabled=True):
"""
Default class constructor.

:param `strCaption`: the tab caption;
:param `imageIndex`: the tab image index based on the assigned (set)
-         `wx.ImageList` (if any).
+         `wx.ImageList` (if any);
+        :param `enabled`: sets the tab as enabled or disabled.
"""

self._pos = wx.Point()
@@ -346,6 +359,7 @@
self._strCaption = strCaption
self._ImageIndex = imageIndex
self._captionRect = wx.Rect()
+        self._bEnabled = enabled

def SetCaption(self, value):
@@ -428,6 +442,22 @@
return self._captionRect

+    def GetEnabled(self):
+        """ Returns whether the tab is enabled or not. """
+
+        return self._bEnabled
+
+
+    def EnableTab(self, enabled):
+        """
+        Sets the tab enabled or disabled.
+
+        :param `enabled`: ``True`` to enable a tab, ``False`` to disable it.
+        """
+
+        self._bEnabled = enabled
+
+
# ---------------------------------------------------------------------------- #
# Class ImageContainerBase
# ---------------------------------------------------------------------------- #
@@ -468,6 +498,7 @@
``INB_WEB_HILITE``                0x800 On mouse hovering, tabs behave like html hyperlinks. Available only for L{LabelBook}.
``INB_NO_RESIZE``                0x1000 Don't allow resizing of the tab area.
``INB_FIT_LABELTEXT``            0x2000 Will fit the tab area to the longest text (or text+image if you have images) in all the tabs.
+         ``INB_BOLD_TAB_SELECTION``       0x4000 Show the selected tab text using a bold font.
=========================== =========== ==================================================

:param `name`: the window name.
@@ -476,7 +507,7 @@
self._nIndex = -1
self._nImgSize = 16
self._ImageList = None
-        self._nHoeveredImgIdx = -1
+        self._nHoveredImgIdx = -1
self._bCollapsed = False
self._tabAreaSize = (-1, -1)
self._nPinButtonStatus = INB_PIN_NONE
@@ -509,6 +540,7 @@
``INB_WEB_HILITE``                0x800 On mouse hovering, tabs behave like html hyperlinks. Available only for L{LabelBook}.
``INB_NO_RESIZE``                0x1000 Don't allow resizing of the tab area.
``INB_FIT_LABELTEXT``            0x2000 Will fit the tab area to the longest text (or text+image if you have images) in all the tabs.
+         ``INB_BOLD_TAB_SELECTION``       0x4000 Show the selected tab text using a bold font.
=========================== =========== ==================================================
"""

@@ -661,7 +693,36 @@
imgInfo = self._pagesInfoVec[page]
return imgInfo.GetCaption()

+
+    def GetEnabled(self, page):
+        """
+        Returns whether a tab is enabled or not.
+
+        :param `page`: an integer specifying the page index.
+        """
+
+        if page >= len(self._pagesInfoVec):
+            return True # Adding a page - enabled by default
+
+        imgInfo = self._pagesInfoVec[page]
+        return imgInfo.GetEnabled()
+
+
+    def EnableTab(self, page, enabled=True):
+        """
+        Enables or disables a tab.
+
+        :param `page`: an integer specifying the page index;
+        :param `enabled`: ``True`` to enable a tab, ``False`` to disable it.
+        """
+
+        if page >= len(self._pagesInfoVec):
+            return
+
+        imgInfo = self._pagesInfoVec[page]
+        imgInfo.EnableTab(enabled)

+
def ClearAll(self):
""" Deletes all the pages in the container. """

@@ -822,7 +883,7 @@
tabIdx, where = self.HitTest(event.GetPosition())

if where == IMG_OVER_IMG:
-            self._nHoeveredImgIdx = -1
+            self._nHoveredImgIdx = -1

if tabIdx == -1:
return
@@ -837,8 +898,8 @@
:param `event`: a `wx.MouseEvent` event to be processed.
"""

-        bRepaint = self._nHoeveredImgIdx != -1
-        self._nHoeveredImgIdx = -1
+        bRepaint = self._nHoveredImgIdx != -1
+        self._nHoveredImgIdx = -1

# Make sure the pin button status is NONE
# incase we were in pin button style
@@ -928,29 +989,25 @@
self.DrawPin(dc, self._pinBtnRect, not self._bCollapsed)

imgIdx, where = self.HitTest(event.GetPosition())
-        self._nHoeveredImgIdx = imgIdx
+
+        # Allow hovering unless over current tab or tab is disabled
+        self._nHoveredImgIdx = -1
+
+        if imgIdx < len(self._pagesInfoVec) and self.GetEnabled(imgIdx) and imgIdx != self._nIndex:
+            self._nHoveredImgIdx = imgIdx

if not self._bCollapsed:

-            if self._nHoeveredImgIdx >= 0 and self._nHoeveredImgIdx < len(self._pagesInfoVec):
+            if self._nHoveredImgIdx >= 0 and self.HasAGWFlag(INB_WEB_HILITE):

-                # Change the cursor to be Hand
-                if self.HasAGWFlag(INB_WEB_HILITE) and self._nHoeveredImgIdx != self._nIndex:
-                    wx.SetCursor(wx.StockCursor(wx.CURSOR_HAND))
+                # Change the cursor to be Hand if we have the Web hover style set
+                wx.SetCursor(wx.StockCursor(wx.CURSOR_HAND))

-            else:
+            elif not self.PointOnSash(event.GetPosition()):

-                # Restore the cursor only if we have the Web hover style set,
-                # and we are not currently hovering the sash
-                if self.HasAGWFlag(INB_WEB_HILITE) and not self.PointOnSash(event.GetPosition()):
-                    wx.SetCursor(wx.StockCursor(wx.CURSOR_ARROW))
-
-        # Dont display hover effect when hoevering the
-        # selected label
-
-        if self._nHoeveredImgIdx == self._nIndex:
-            self._nHoeveredImgIdx = -1
-
+                # Restore the cursor if we are not currently hovering the sash
+                wx.SetCursor(wx.StockCursor(wx.CURSOR_ARROW))
+
self.Refresh()

@@ -1046,6 +1103,7 @@
``INB_WEB_HILITE``                0x800 On mouse hovering, tabs behave like html hyperlinks. Available only for L{LabelBook}.
``INB_NO_RESIZE``                0x1000 Don't allow resizing of the tab area.
``INB_FIT_LABELTEXT``            0x2000 Will fit the tab area to the longest text (or text+image if you have images) in all the tabs.
+         ``INB_BOLD_TAB_SELECTION``       0x4000 Show the selected tab text using a bold font.
=========================== =========== ==================================================

:param `name`: the window name.
@@ -1204,6 +1262,9 @@
nTextPaddingLeft = 2

count = 0
+        normalFont = wx.SystemSettings_GetFont(wx.SYS_DEFAULT_GUI_FONT)
+        boldFont = wx.SystemSettings_GetFont(wx.SYS_DEFAULT_GUI_FONT)
+        boldFont.SetWeight(wx.BOLD)

for i in xrange(len(self._pagesInfoVec)):

@@ -1213,15 +1274,13 @@
# text width plus padding
# Incase the style IS applied, but the style is either LEFT or RIGHT
# we ignore it
-            normalFont = wx.SystemSettings_GetFont(wx.SYS_DEFAULT_GUI_FONT)
dc.SetFont(normalFont)

+            if style & INB_BOLD_TAB_SELECTION and self._nIndex == i:
+                dc.SetFont(boldFont)
+
textWidth, textHeight = dc.GetTextExtent(self._pagesInfoVec[i].GetCaption())

-            # Restore font to be normal
-            normalFont.SetWeight(wx.FONTWEIGHT_NORMAL)
-            dc.SetFont(normalFont)
-
# Default values for the surronounding rectangle
# around a button
rectWidth = self._nImgSize * 2  # To avoid the recangle to 'touch' the borders
@@ -1277,7 +1336,7 @@

dc.DrawRectangleRect(buttonRect)

-            if self._nHoeveredImgIdx == i:
+            if self._nHoveredImgIdx == i:

# Set the colours
penColour = wx.SystemSettings_GetColour(wx.SYS_COLOUR_ACTIVECAPTION)
@@ -1331,8 +1390,11 @@

# Draw the text
if not style & INB_SHOW_ONLY_IMAGES and not self._pagesInfoVec[i].GetCaption() == "":
-
-                dc.SetFont(normalFont)
+
+                if style & INB_BOLD_TAB_SELECTION and self._nIndex == i:
+                    dc.SetFont(boldFont)
+                else:
+                    dc.SetFont(normalFont)

# Check if the text can fit the size of the rectangle,
# if not truncate it
@@ -1416,6 +1478,7 @@
``INB_WEB_HILITE``                0x800 On mouse hovering, tabs behave like html hyperlinks. Available only for L{LabelBook}.
``INB_NO_RESIZE``                0x1000 Don't allow resizing of the tab area.
``INB_FIT_LABELTEXT``            0x2000 Will fit the tab area to the longest text (or text+image if you have images) in all the tabs.
+         ``INB_BOLD_TAB_SELECTION``       0x4000 Show the selected tab text using a bold font.
=========================== =========== ==================================================

:param `name`: the window name.
@@ -1576,8 +1639,12 @@
if self.HasAGWFlag(INB_SHOW_ONLY_TEXT):
font = wx.SystemSettings_GetFont(wx.SYS_DEFAULT_GUI_FONT)
font.SetPointSize(font.GetPointSize() * self.GetParent().GetFontSizeMultiple())
+
if self.GetParent().GetFontBold():
font.SetWeight(wx.FONTWEIGHT_BOLD)
+                elif self.HasAGWFlag(INB_BOLD_TAB_SELECTION) and self._nIndex == i:
+                    font.SetWeight(wx.FONTWEIGHT_BOLD)
+
dc.SetFont(font)
w, h = dc.GetTextExtent(self._pagesInfoVec[i].GetCaption())
rectHeight = h * 2
@@ -1601,7 +1668,7 @@

self.DrawLabel(dc, buttonRect, self._pagesInfoVec[i].GetCaption(), bmp,
self._pagesInfoVec[i], self.HasAGWFlag(INB_LEFT) or self.HasAGWFlag(INB_TOP),
-                           i, self._nIndex == i, self._nHoeveredImgIdx == i)
+                           i, self._nIndex == i, self._nHoveredImgIdx == i)

posy += rectHeight

@@ -1874,14 +1941,15 @@
dc.DrawLine(rect.x, rect.y + rect.height, rect.x + rect.width, rect.y + rect.height)

-    def DrawWebHover(self, dc, caption, xCoord, yCoord):
+    def DrawWebHover(self, dc, caption, xCoord, yCoord, selected):
"""
Draws a web style hover effect (cursor set to hand & text is underlined).

:param `dc`: an instance of `wx.DC`;
:param `caption`: the tab caption text;
:param `xCoord`: the x position of the tab caption;
-        :param `yCoord`: the y position of the tab caption.
+        :param `yCoord`: the y position of the tab caption;
+        :param `selected`: ``True`` if the tab is selected, ``False`` otherwise.
"""

# Redraw the text with underlined font
@@ -1889,6 +1957,9 @@
underLinedFont.SetPointSize(underLinedFont.GetPointSize() * self.GetParent().GetFontSizeMultiple())
if self.GetParent().GetFontBold():
underLinedFont.SetWeight(wx.FONTWEIGHT_BOLD)
+        elif self.HasAGWFlag(INB_BOLD_TAB_SELECTION) and selected:
+            underLinedFont.SetWeight(wx.FONTWEIGHT_BOLD)
+
underLinedFont.SetUnderlined(True)
dc.SetFont(underLinedFont)
dc.DrawText(caption, xCoord, yCoord)
@@ -1983,8 +2054,12 @@

font = wx.SystemSettings_GetFont(wx.SYS_DEFAULT_GUI_FONT)
font.SetPointSize(font.GetPointSize() * self.GetParent().GetFontSizeMultiple())
+
if self.GetParent().GetFontBold():
font.SetWeight(wx.FONTWEIGHT_BOLD)
+        elif self.HasAGWFlag(INB_BOLD_TAB_SELECTION) and selected:
+            font.SetWeight(wx.FONTWEIGHT_BOLD)
+
dc.SetFont(font)

# First we define the rectangle for the text
@@ -2076,15 +2151,14 @@

else:

-                if imgIdx+1 != self._nHoeveredImgIdx:
-
+                if imgIdx+1 != self._nHoveredImgIdx:
ArtManager.Get().DrawBitmapShadow(dc, rect, sstyle)

# Draw hover effect
if hover:

if self.HasAGWFlag(INB_WEB_HILITE) and caption != "":
-                self.DrawWebHover(dc, caption, textRect.x, textRect.y)
+                self.DrawWebHover(dc, caption, textRect.x, textRect.y, selected)
else:
self.DrawRegularHover(dc, rect)

@@ -2132,6 +2206,7 @@
``INB_WEB_HILITE``                0x800 On mouse hovering, tabs behave like html hyperlinks. Available only for L{LabelBook}.
``INB_NO_RESIZE``                0x1000 Don't allow resizing of the tab area.
``INB_FIT_LABELTEXT``            0x2000 Will fit the tab area to the longest text (or text+image if you have images) in all the tabs.
+         ``INB_BOLD_TAB_SELECTION``       0x4000 Show the selected tab text using a bold font.
=========================== =========== ==================================================

:param `name`: the window name.
@@ -2151,6 +2226,8 @@
wx.Panel.__init__(self, parent, id, pos, size, style, name)
self._bInitializing = False

+        self.Bind(wx.EVT_NAVIGATION_KEY, self.OnNavigationKey)
+

def SetAGWWindowStyleFlag(self, agwStyle):
"""
@@ -2175,6 +2252,7 @@
``INB_WEB_HILITE``                0x800 On mouse hovering, tabs behave like html hyperlinks. Available only for L{LabelBook}.
``INB_NO_RESIZE``                0x1000 Don't allow resizing of the tab area.
``INB_FIT_LABELTEXT``            0x2000 Will fit the tab area to the longest text (or text+image if you have images) in all the tabs.
+         ``INB_BOLD_TAB_SELECTION``       0x4000 Show the selected tab text using a bold font.
=========================== =========== ==================================================

"""
@@ -2421,7 +2499,7 @@
dc.SelectObject(wx.EmptyBitmap(1, 1))
font = wx.SystemSettings_GetFont(wx.SYS_DEFAULT_GUI_FONT)
font.SetPointSize(font.GetPointSize()*self._fontSizeMultiple)
-            if self.GetFontBold():
+            if self.GetFontBold() or agwStyle & INB_BOLD_TAB_SELECTION:
font.SetWeight(wx.FONTWEIGHT_BOLD)
dc.SetFont(font)
maxW = 0
@@ -2473,6 +2551,9 @@
if page >= len(self._windows):
return

+        if not self.GetEnabled(page):
+            return
+
if page == self.GetSelection() and not self._bForceSelection:
return

@@ -2645,6 +2726,31 @@
return self._pages.GetPageImage(page)

+    def GetEnabled(self, page):
+        """
+        Returns whether a tab is enabled or not.
+
+        :param `page`: an integer specifying the page index.
+        """
+
+        return self._pages.GetEnabled(page)
+
+
+    def EnableTab(self, page, enabled=True):
+        """
+        Enables or disables a tab.
+
+        :param `page`: an integer specifying the page index;
+        :param `enabled`: ``True`` to enable a tab, ``False`` to disable it.
+        """
+
+        if page >= len(self._windows):
+            return
+
+        self._windows[page].Enable(enabled)
+        self._pages.EnableTab(page, enabled)
+
+
def GetPage(self, page):
"""
Returns the window at the given page position.
@@ -2667,6 +2773,24 @@
return self.GetPage(self.GetSelection())

+    def OnNavigationKey(self, event):
+        """
+        Handles the ``wx.EVT_NAVIGATION_KEY`` event for L{FlatBookBase}.
+
+        :param `event`: a `wx.NavigationKeyEvent` event to be processed.
+        """
+
+        if event.IsWindowChange():
+            if self.GetPageCount() == 0:
+                return
+
+            # change pages
+            self.AdvanceSelection(event.GetDirection())
+
+        else:
+            event.Skip()
+
+
def AdvanceSelection(self, forward=True):
"""
Cycles through the tabs.
@@ -2762,6 +2886,7 @@
``INB_WEB_HILITE``                0x800 On mouse hovering, tabs behave like html hyperlinks. Available only for L{LabelBook}.
``INB_NO_RESIZE``                0x1000 Don't allow resizing of the tab area.
``INB_FIT_LABELTEXT``            0x2000 Will fit the tab area to the longest text (or text+image if you have images) in all the tabs.
+         ``INB_BOLD_TAB_SELECTION``       0x4000 Show the selected tab text using a bold font.
=========================== =========== ==================================================

:param `name`: the window name.
@@ -2837,6 +2962,7 @@
``INB_WEB_HILITE``                0x800 On mouse hovering, tabs behave like html hyperlinks. Available only for L{LabelBook}.
``INB_NO_RESIZE``                0x1000 Don't allow resizing of the tab area.
``INB_FIT_LABELTEXT``            0x2000 Will fit the tab area to the longest text (or text+image if you have images) in all the tabs.
+         ``INB_BOLD_TAB_SELECTION``       0x4000 Show the selected tab text using a bold font.
=========================== =========== ==================================================

:param `name`: the window name.

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • labelbook »
  • SVN Revision 69946 For labelbook


MultiDirDialog

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • multidirdialog »
  • MultiDirDialog

MultiDirDialog

A different implementation of wx.DirDialog which allows multiple folders to be selected at once.

hierarchy Inheritance Diagram

Inheritance diagram for: MultiDirDialog

Inheritance diagram of MultiDirDialog

appearance Control Appearance

MultiDirDialog

Methods Summary

__init__ | Default class constructor.
BindEvents | Binds the events to specific methods.
CreateButtons | Creates the OK, Cancel and Make New Folder bitmap buttons.
GetPaths | Returns the folders selected by the user, or the default path.
LayoutItems | Layout the widgets using sizers.
OnCancel | Handles the wx.EVT_BUTTON event for the dialog.
OnClose | Handles the wx.EVT_CLOSE event for the dialog.
OnKeyUp | Handles the wx.EVT_CHAR_HOOK event for the dialog.
OnOk | Handles the wx.EVT_BUTTON event for the dialog.
OnSelChanged | Handles the wx.EVT_TREE_SEL_CHANGED event for the tree control associated
RecurseTopDir | Recurse a directory tree to include the parent-folder.
SetProperties | Sets few properties for the dialog.
SetupDirCtrl | Setup the internal wx.GenericDirCtrl (icons, labels, etc...).

API Class API

class MultiDirDialog(wx.Dialog) [source]

A different implementation of wx.DirDialog which allows multiple folders to be selected at once.

__init__(parent, message=_("Choose one or more folders:"), title=_("Browse For Folders"), defaultPath="", style=wx.DD_DEFAULT_STYLE, agwStyle=DD_MULTIPLE, pos=wx.DefaultPosition, size=wx.DefaultSize, name="multidirdialog") [source]

Default class constructor.

Parameters:
  • parent – the dialog parent widget;
  • message – the message to show on the dialog;
  • title – the dialog title;
  • defaultPath – the default path, or the empty string;
  • style – the underlying wx.Dialog window style;
  • agwStyle – the AGW-specific dialog style; this can be a combination of the following bits:

    Window Styles | Hex Value | Description
    DD_NEW_DIR_BUTTON | 0x000 | Enable/disable the “Make new folder” button
    DD_DIR_MUST_EXIST | 0x200 | The dialog will allow the user to choose only an existing folder. When this style is not given, a “Create new directory” button is added to the dialog (on Windows) or some other way is provided to the user to type the name of a new folder.
    DD_MULTIPLE | 0x400 | Allows the selection of multiple folders.
  • pos – the dialog position;
  • size – the dialog size;
  • name – the dialog name.

BindEvents() [source]

Binds the events to specific methods.

CreateButtons() [source]

Creates the OK, Cancel and Make New Folder bitmap buttons.

GetPaths() [source]

Returns the folders selected by the user, or the default path.

LayoutItems(message) [source]

Layout the widgets using sizers.

OnCancel(event) [source]

Handles the wx.EVT_BUTTON event for the dialog.

Parameters: event – a wx.CommandEvent event to be processed.

Note

This method handles the Cancel button press.

OnClose(event) [source]

Handles the wx.EVT_CLOSE event for the dialog.

Parameters: event – a wx.CloseEvent event to be processed.

OnKeyUp(event) [source]

Handles the wx.EVT_CHAR_HOOK event for the dialog.

Parameters: event – a wx.KeyEvent event to be processed.

OnOk(event) [source]

Handles the wx.EVT_BUTTON event for the dialog.

Parameters: event – a wx.CommandEvent event to be processed.

Note

This method handles the OK button press.

OnSelChanged(event) [source]

Handles the wx.EVT_TREE_SEL_CHANGED event for the tree control associated with MultiDirDialog.

Parameters: event – a wx.TreeEvent event to be processed.

RecurseTopDir(treeCtrl, item, itemText) [source]

Recurse a directory tree to include the parent-folder.

Parameters:
  • treeCtrl – the tree control associated with teh internal wx.GenericDirCtrl;

  • item – the selected tree control item;
  • itemText – the selected tree control item text.

SetProperties(title) [source]

Sets few properties for the dialog.

Parameters: title – the dialog title.

SetupDirCtrl(defaultPath) [source]

Setup the internal wx.GenericDirCtrl (icons, labels, etc...).

Parameters: defaultPath – the default path for MultiDirDialog, can be an empty string.

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • infobar
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • multidirdialog »
  • MultiDirDialog


SVN Revision 68362 For multidirdialog

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • multidirdialog »
  • SVN Revision 68362 For multidirdialog

svn SVN Revision 68362 For multidirdialog

This file contains the SVN revision history for multidirdialog, at revision 68362.

Available information include commit date, the name of the committer, the file size, the SVN log messages and a diff from the previous version (if available).

File Information

  • Commit Date: 17-Oct-2008 20:51:43 UTC
  • Committer: AG
  • File Size: 24317 byte(s)

Log Messages

The following log message was entered by the committer:

  • All of AGW: change my work e-mail from KPO to Maersk Oil (silly commit)

Diff To Previous Version (65529)

Version SVN diff:

--- wxPython/3rdParty/AGW/agw/multidirdialog.py     2010/09/12 11:58:40     65529
+++ wxPython/3rdParty/AGW/agw/multidirdialog.py     2011/07/24 21:36:47     68362
@@ -17,7 +17,7 @@
# write to me at:
#
# andrea.gavana@gmail.com
-# gavana@kpo.kz
+# andrea.gavana@maerskoil.com
#
# Or, obviously, to the wxPython mailing list!!!
#

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • multidirdialog »
  • SVN Revision 68362 For multidirdialog


SVN Revision 68881 For multidirdialog

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • multidirdialog »
  • SVN Revision 68881 For multidirdialog

svn SVN Revision 68881 For multidirdialog

This file contains the SVN revision history for multidirdialog, at revision 68881.

Available information include commit date, the name of the committer, the file size, the SVN log messages and a diff from the previous version (if available).

File Information

  • Commit Date: 17-Oct-2008 19:15:31 UTC
  • Committer: AG
  • File Size: 24955 byte(s)

Log Messages

The following log message was entered by the committer:

  • AGW: General overhaul of the documentation, much improved. All the widgets have their own sample usage in the docs as well;

  • FlatNotebook: Added the FNB_NAV_BUTTONS_WHEN_NEEDED style, which hides the navigation left/right arrows if all tabs fit;

  • RibbonBar: - Added the EVT_RIBBONBAR_TAB_LEFT_DCLICK event, which generates a special event

    when a ribbon bar tab is double-clicked;

    • Added support for toggle buttons;
    • Improved support for ribbon panel sizers: panels with sizers should now automatically minimise at small sizes, and behave properly when popping up from a minimised state;
    • Added tooltips via SetToolTip for those buttons which have the help_string attribute set.

  • XLSGrid: a new widget was added to AGW, termed XLSGrid. It’s based on wx.grid.Grid and can be used to faithfully reproduce the appearance of a Microsoft Excel spreadsheets.

Diff To Previous Version (68362)

Version SVN diff:

--- wxPython/3rdParty/AGW/agw/multidirdialog.py     2011/07/24 21:36:47     68362
+++ wxPython/3rdParty/AGW/agw/multidirdialog.py     2011/08/25 16:40:17     68881
@@ -2,7 +2,7 @@
# MULTIDIRDIALOG wxPython IMPLEMENTATION
#
# Andrea Gavana, @ 07 October 2008
-# Latest Revision: 12 Sep 2010, 10.00 GMT
+# Latest Revision: 17 Aug 2011, 15.00 GMT
#
#
# TODO List
@@ -36,7 +36,7 @@
This class represents a possible replacement for `wx.DirDialog`, with the additional
ability of selecting multiple folders at once. It may be useful when you wish to
present to the user a directory browser which allows multiple folder selections.
-MultiDirDialog sports the following features:
+L{MultiDirDialog} sports the following features:

* Ability to select a single or mutliple folders, depending on the style passed;
* More colourful and eye-catching buttons;
@@ -45,10 +45,41 @@
And a lot more. Check the demo for an almost complete review of the functionalities.

+Usage
+=====
+
+Usage example::
+
+    import os
+    import wx
+
+    import wx.lib.agw.multidirdialog as MDD
+
+    # Our normal wxApp-derived class, as usual
+    app = wx.App(0)
+
+    dlg = MDD.MultiDirDialog(None, title="Custom MultiDirDialog", defaultPath=os.getcwd(),
+                             agwStyle=MDD.DD_MULTIPLE|MDD.DD_DIR_MUST_EXIST)
+
+    if dlg.ShowModal() != wx.ID_OK:
+        print "You Cancelled The Dialog!"
+        dlg.Destroy()
+        return
+
+    paths = dlg.GetPaths()
+    for indx, path in enumerate(paths):
+        print "Path %d: %s"%(indx+1, path)
+
+    dlg.Destroy()
+
+    app.MainLoop()
+
+
+
Supported Platforms
===================

-MultiDirDialog has been tested on the following platforms:
+L{MultiDirDialog} has been tested on the following platforms:
* Windows (Windows XP).

@@ -75,9 +106,9 @@
License And Version
===================

-MultiDirDialog is distributed under the wxPython license.
+L{MultiDirDialog} is distributed under the wxPython license.

-Latest Revision: Andrea Gavana @ 12 Sep 2010, 10.00 GMT
+Latest Revision: Andrea Gavana @ 17 Aug 2011, 15.00 GMT

Version 0.3

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • multidirdialog »
  • SVN Revision 68881 For multidirdialog


SVN Revision 68881 For page

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • ribbon library »
  • ribbon.page »
  • SVN Revision 68881 For page

svn SVN Revision 68881 For page

This file contains the SVN revision history for page, at revision 68881.

Available information include commit date, the name of the committer, the file size, the SVN log messages and a diff from the previous version (if available).

File Information

  • Commit Date: 18-Nov-2009 22:19:25 UTC
  • Committer: AG
  • File Size: 31746 byte(s)

Log Messages

The following log message was entered by the committer:

  • AGW: General overhaul of the documentation, much improved. All the widgets have their own sample usage in the docs as well;

  • FlatNotebook: Added the FNB_NAV_BUTTONS_WHEN_NEEDED style, which hides the navigation left/right arrows if all tabs fit;

  • RibbonBar: - Added the EVT_RIBBONBAR_TAB_LEFT_DCLICK event, which generates a special event

    when a ribbon bar tab is double-clicked;

    • Added support for toggle buttons;
    • Improved support for ribbon panel sizers: panels with sizers should now automatically minimise at small sizes, and behave properly when popping up from a minimised state;
    • Added tooltips via SetToolTip for those buttons which have the help_string attribute set.

  • XLSGrid: a new widget was added to AGW, termed XLSGrid. It’s based on wx.grid.Grid and can be used to faithfully reproduce the appearance of a Microsoft Excel spreadsheets.

Diff To Previous Version (65158)

Version SVN diff:

--- wxPython/3rdParty/AGW/agw/ribbon/page.py        2010/08/02 20:03:09     65158
+++ wxPython/3rdParty/AGW/agw/ribbon/page.py        2011/08/25 16:40:17     68881
@@ -50,7 +50,6 @@
self._sibling = sibling
self._flags = (style & RIBBON_SCROLL_BTN_DIRECTION_MASK) | RIBBON_SCROLL_BTN_FOR_PAGE

-
self.Bind(wx.EVT_ENTER_WINDOW, self.OnMouseEnter)
self.Bind(wx.EVT_ERASE_BACKGROUND, self.OnEraseBackground)
self.Bind(wx.EVT_LEAVE_WINDOW, self.OnMouseLeave)
@@ -138,6 +137,8 @@
self._icon = icon
self._scroll_left_btn = None
self._scroll_right_btn = None
+        self._size_calc_array = None
+        self._size_calc_array_size = 0
self._scroll_amount = 0
self._scroll_buttons_visible = False
self._collapse_stack = []
@@ -354,6 +355,11 @@
height -= h
self._scroll_right_btn.SetPosition(wx.Point(x, y + height))

+        if width < 0:
+            width = 0
+        if height < 0:
+            height = 0
+
self.SetDimensions(x, y, width, height)

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • ribbon library »
  • ribbon.page »
  • SVN Revision 68881 For page


SVN Revision 68881 For panel

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • ribbon library »
  • ribbon.panel »
  • SVN Revision 68881 For panel

svn SVN Revision 68881 For panel

This file contains the SVN revision history for panel, at revision 68881.

Available information include commit date, the name of the committer, the file size, the SVN log messages and a diff from the previous version (if available).

File Information

  • Commit Date: 18-Nov-2009 22:19:25 UTC
  • Committer: AG
  • File Size: 34677 byte(s)

Log Messages

The following log message was entered by the committer:

  • AGW: General overhaul of the documentation, much improved. All the widgets have their own sample usage in the docs as well;

  • FlatNotebook: Added the FNB_NAV_BUTTONS_WHEN_NEEDED style, which hides the navigation left/right arrows if all tabs fit;

  • RibbonBar: - Added the EVT_RIBBONBAR_TAB_LEFT_DCLICK event, which generates a special event

    when a ribbon bar tab is double-clicked;

    • Added support for toggle buttons;
    • Improved support for ribbon panel sizers: panels with sizers should now automatically minimise at small sizes, and behave properly when popping up from a minimised state;
    • Added tooltips via SetToolTip for those buttons which have the help_string attribute set.

  • XLSGrid: a new widget was added to AGW, termed XLSGrid. It’s based on wx.grid.Grid and can be used to faithfully reproduce the appearance of a Microsoft Excel spreadsheets.

Diff To Previous Version (63994)

Version SVN diff:

--- wxPython/3rdParty/AGW/agw/ribbon/panel.py       2010/04/16 11:45:03     63994
+++ wxPython/3rdParty/AGW/agw/ribbon/panel.py       2011/08/25 16:40:17     68881
@@ -133,8 +133,8 @@
self.SetName(label)
self.SetLabel(label)

-        self._minimised_size = wx.Size() # Unknown / none
-        self._smallest_unminimised_size = wx.Size(0, 0) # Unknown / none
+        self._minimised_size = wx.Size(-1, -1) # Unknown / none
+        self._smallest_unminimised_size = wx.Size(-1, -1) # Unknown / none
self._preferred_expand_direction = wx.SOUTH
self._expanded_dummy = None
self._expanded_panel = None
@@ -290,6 +290,15 @@

"""

+        if self.GetSizer():
+            # we have no information on size change direction
+            # so check both
+            size = self.GetMinNotMinimisedSize()
+            if size.x > at_size.x or size.y > at_size.y:
+                return True
+
+            return False
+
if not self._minimised_size.IsFullySpecified():
return False

@@ -330,34 +339,53 @@
# expanded panel
return self._expanded_panel.DoGetNextSmallerSize(direction, relative_to)

-        # TODO: Check for, and delegate to, a sizer
+        if self._art is not None:
+
+            dc = wx.ClientDC(self)
+            child_relative, dummy = self._art.GetPanelClientSize(dc, self, wx.Size(*relative_to), None)
+            smaller = wx.Size(-1, -1)
+            minimise = False

-        # Simple (and common) case of single ribbon child
-        if len(self.GetChildren()) == 1:
-            child = self.GetChildren()[0]
+            if self.GetSizer():

-            if self._art != None and isinstance(child, RibbonControl):
-                dc = wx.ClientDC(self)
-                child_relative, dummy = self._art.GetPanelClientSize(dc, self, wx.Size(*relative_to), None)
-                smaller = child.GetNextSmallerSize(direction, child_relative)
-
-                if smaller == child_relative:
-                    if self.CanAutoMinimise():
-                        minimised = wx.Size(*self._minimised_size)
-
-                        if direction == wx.HORIZONTAL:
-                            minimised.SetHeight(relative_to.GetHeight())
-                        elif direction == wx.VERTICAL:
-                            minimised.SetWidth(relative_to.GetWidth())
-
-                        return minimised
-
-                    else:
-                        return relative_to
+                # Get smallest non minimised size
+                smaller = self.GetMinSize()
+
+                # and adjust to child_relative for parent page
+                if self._art.GetFlags() & RIBBON_BAR_FLOW_VERTICAL:
+                     minimise = child_relative.y <= smaller.y
+                     if smaller.x < child_relative.x:
+                        smaller.x = child_relative.x
+                else:
+                    minimise = child_relative.x <= smaller.x
+                    if smaller.y < child_relative.y:
+                        smaller.y = child_relative.y
+
+            elif len(self.GetChildren()) == 1:
+
+                # Simple (and common) case of single ribbon child or Sizer
+                ribbon_child = self.GetChildren()[0]
+                if isinstance(ribbon_child, RibbonControl):
+                    smaller = ribbon_child.GetNextSmallerSize(direction, child_relative)
+                    minimise = smaller == child_relative
+
+            if minimise:
+                if self.CanAutoMinimise():
+                    minimised = wx.Size(*self._minimised_size)
+
+                    if direction == wx.HORIZONTAL:
+                        minimised.SetHeight(relative_to.GetHeight())
+                    elif direction == wx.VERTICAL:
+                        minimised.SetWidth(relative_to.GetWidth())

-                else:
-                    return self._art.GetPanelSize(dc, self, wx.Size(*smaller), None)
+                    return minimised

+                else:
+                    return relative_to
+
+            elif smaller.IsFullySpecified(): # Use fallback if !(sizer/child = 1)
+                return self._art.GetPanelSize(dc, self, wx.Size(*smaller), None)
+
# Fallback: Decrease by 20% (or minimum size, whichever larger)
current = wx.Size(*relative_to)
minimum = wx.Size(*self.GetMinSize())
@@ -398,23 +426,40 @@
if min_size.x > current.x and min_size.y > current.y:
return min_size

-        # TODO: Check for, and delegate to, a sizer
+        if self._art is not None:
+
+            dc = wx.ClientDC(self)
+            child_relative, dummy = self._art.GetPanelClientSize(dc, self, wx.Size(*relative_to), None)
+            larger = wx.Size(-1, -1)

-        # Simple (and common) case of single ribbon child
-        if len(self.GetChildren()) == 1:
-            child = self.GetChildren()[0]
+            if self.GetSizer():

-            if isinstance(child, RibbonControl):
-                dc = wx.ClientDC(self)
-                child_relative, dummy = self._art.GetPanelClientSize(dc, self, wx.Size(*relative_to), None)
-                larger = child.GetNextLargerSize(direction, child_relative)
+                # We could just let the sizer expand in flow direction but see comment
+                # in IsSizingContinuous()
+                larger = self.GetPanelSizerBestSize()

-                if larger == child_relative:
+                # and adjust for page in non flow direction
+                if self._art.GetFlags() & RIBBON_BAR_FLOW_VERTICAL:
+                     if larger.x != child_relative.x:
+                        larger.x = child_relative.x
+
+                elif larger.y != child_relative.y:
+                    larger.y = child_relative.y
+
+            elif len(self.GetChildren()) == 1:
+
+                # Simple (and common) case of single ribbon child
+                ribbon_child = self.GetChildren()[0]
+                if isinstance(ribbon_child, RibbonControl):
+                    larger = ribbon_child.GetNextLargerSize(direction, child_relative)
+
+            if larger.IsFullySpecified(): # Use fallback if !(sizer/child = 1)
+                if larger == child_relative:
return relative_to
-                else:
-                    dc = wx.ClientDC(self)
+                else:
return self._art.GetPanelSize(dc, self, wx.Size(*larger), None)

+
# Fallback: Increase by 25% (equal to a prior or subsequent 20% decrease)
# Note that due to rounding errors, this increase may not exactly equal a
# matching decrease - an ideal solution would not have these errors, but
@@ -432,6 +477,7 @@
return current

+
def CanAutoMinimise(self):
""" Query if the panel can automatically minimise itself at small sizes. """

@@ -454,10 +500,13 @@

def GetMinNotMinimisedSize(self):

-        # TODO: Ask sizer
-
+        # Ask sizer if present
+        if self.GetSizer():
+            dc = wx.ClientDC(self)
+            return self._art.GetPanelSize(dc, self, wx.Size(*self.GetPanelSizerMinSize()), None)
+
# Common case of no sizer and single child taking up the entire panel
-        if len(self.GetChildren()) == 1:
+        elif len(self.GetChildren()) == 1:
child = self.GetChildren()[0]
dc = wx.ClientDC(self)
return self._art.GetPanelSize(dc, self, wx.Size(*child.GetMinSize()), None)
@@ -465,12 +514,41 @@
return wx.Size(*RibbonControl.GetMinSize(self))

-    def DoGetBestSize(self):
+    def GetPanelSizerMinSize(self):
+
+        # Called from Realize() to set self._smallest_unminimised_size and from other
+        # functions to get the minimum size.
+        # The panel will be invisible when minimised and sizer calcs will be 0
+        # Uses self._smallest_unminimised_size in preference to self.GetSizer().CalcMin()
+        # to eliminate flicker.
+
+        # Check if is visible and not previously calculated
+        if self.IsShown() and not self._smallest_unminimised_size.IsFullySpecified():
+             return self.GetSizer().CalcMin()
+
+        # else use previously calculated self._smallest_unminimised_size
+        dc = wx.ClientDC(self)
+        return self._art.GetPanelClientSize(dc, self, wx.Size(*self._smallest_unminimised_size), None)[0]
+
+
+    def GetPanelSizerBestSize(self):
+
+        size = self.GetPanelSizerMinSize()
+        # TODO allow panel to increase its size beyond minimum size
+        # by steps similarly to ribbon control panels (preferred for aesthetics)
+        # or continuously.
+        return size

-        # TODO: Ask sizer

+    def DoGetBestSize(self):
+
+        # Ask sizer if present
+        if self.GetSizer():
+            dc = wx.ClientDC(self)
+            return self._art.GetPanelSize(dc, self, wx.Size(*self.GetPanelSizerBestSize()), None)
+
# Common case of no sizer and single child taking up the entire panel
-        if len(self.GetChildren()) == 1:
+        elif len(self.GetChildren()) == 1:
child = self.GetChildren()[0]
dc = wx.ClientDC(self)
return self._art.GetPanelSize(dc, self, wx.Size(*child.GetBestSize()), None)
@@ -496,9 +574,11 @@
status = False

minimum_children_size = wx.Size(0, 0)
-        # TODO: Ask sizer if there is one

-        if len(children) == 1:
+        # Ask sizer if there is one present
+        if self.GetSizer():
+            minimum_children_size = wx.Size(*self.GetPanelSizerMinSize())
+        elif len(children) == 1:
minimum_children_size = wx.Size(*children[0].GetMinSize())

if self._art != None:
@@ -537,14 +617,16 @@
# Children are all invisible when minimised
return True

-        # TODO: Delegate to a sizer
+        dc = wx.ClientDC(self)
+        size, position = self._art.GetPanelClientSize(dc, self, wx.Size(*self.GetSize()), wx.Point())

-        # Common case of no sizer and single child taking up the entire panel
children = self.GetChildren()
-        if len(children) == 1:
-            dc = wx.ClientDC(self)
-            size, position = self._art.GetPanelClientSize(dc, self, wx.Size(*self.GetSize()), wx.Point())
-            children[0].SetDimensions(position.x, position.y, size.GetWidth(), size.GetHeight())
+
+        if self.GetSizer():
+            self.GetSizer().SetDimension(position.x, position.y, size.x, size.y) # SetSize and Layout()
+        elif len(children) == 1:
+           # Common case of no sizer and single child taking up the entire panel
+             children[0].SetDimensions(position.x, position.y, size.GetWidth(), size.GetHeight())

return True

@@ -632,7 +714,13 @@
child.Reparent(self._expanded_panel)
child.Show()

-        # TODO: Move sizer to new panel
+
+        # Move sizer to new panel
+        if self.GetSizer():
+            sizer = self.GetSizer()
+            self.SetSizer(None, False)
+            self._expanded_panel.SetSizer(sizer)
+
self._expanded_panel.Realize()
self.Refresh()
container.Show()

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • ribbon library »
  • ribbon.panel »
  • SVN Revision 68881 For panel


peakmeter functions

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • peakmeter »
  • peakmeter functions

peakmeter functions

This is the description of standalone Python functions in the peakmeter module.

Functions Summary

DarkenColour | Darkens a colour.
InRange | Returns whether the value val is between valMin and valMax.
LightenColour | Lightens a colour.

API Functions API

DarkenColour(crColour, byReduceVal) [source]

Darkens a colour.

Parameters:
  • crColour – a valid wx.Colour object;
  • byReduceVal – an integer specifying the amount for which the input colour should be darkened.

InRange(val, valMin, valMax) [source]

Returns whether the value val is between valMin and valMax.

Parameters:
  • val – the value to test;
  • valMin – the minimum range value;
  • valMax – the maximum range value.

LightenColour(crColour, byIncreaseVal) [source]

Lightens a colour.

Parameters:
  • crColour – a valid wx.Colour object;

  • byIncreaseVal – an integer specifying the amount for which the input colour should be brightened.

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • infobar
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • peakmeter »
  • peakmeter functions


PeakMeterCtrl

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • peakmeter »
  • PeakMeterCtrl

PeakMeterCtrl

The main PeakMeterCtrl implementation.

hierarchy Inheritance Diagram

Inheritance diagram for: PeakMeterCtrl

Inheritance diagram of PeakMeterCtrl

appearance Control Appearance

PeakMeterCtrl

Methods Summary

__init__ | Default class constructor.
DoGetBestSize | Gets the size which best suits the window: for a control, it would be the
DoTimerProcessing | PeakMeterCtrl animation, does the wx.EVT_TIMER processing.
DrawHorzBand | Draws horizontal bands.
DrawVertBand | Draws vertical bands.
GetAGWWindowStyleFlag | Returns the PeakMeterCtrl window style.
GetFalloffEffect | Returns the falloff effect flag.
GetRangeValue | Get range value of PeakMeterCtrl.
InitData | Initializes the control.
IsGridVisible | Returns if gridlines are visible.
IsStarted | Check if animation is active.
OnEraseBackground | Handles the wx.EVT_ERASE_BACKGROUND event for PeakMeterCtrl.
OnPaint | Handles the wx.EVT_PAINT event for PeakMeterCtrl.
OnSize | Handles the wx.EVT_SIZE event for PeakMeterCtrl.
OnTimer | Handles the wx.EVT_TIMER event for PeakMeterCtrl.
ResetControl | Resets the PeakMeterCtrl.
SetAGWWindowStyleFlag | Sets the PeakMeterCtrl window style flags.
SetBackgroundColour | Changes the background colour of PeakMeterCtrl.
SetBandsColour | Set bands colour for PeakMeterCtrl.
SetData | Change data value.
SetFalloffDelay | Set peak value speed before falling off.
SetFalloffEffect | Set falloff effect flag.
SetMeterBands | Set number of vertical or horizontal bands to display.
SetRangeValue | Sets the ranges for low, medium and high bands.
ShowGrid | Request to have gridlines visible or not.
Start | Start the timer and animation effect.
Stop | Stop the timer and animation effect.

API Class API

class PeakMeterCtrl(wx.PyControl) [source]

The main PeakMeterCtrl implementation.

__init__(parent, id=wx.ID_ANY, pos=wx.DefaultPosition, size=wx.DefaultSize, style=0, agwStyle=PM_VERTICAL) [source]

Default class constructor.

Parameters:
  • parent – the PeakMeterCtrl parent. Must not be None
  • id – window identifier. A value of -1 indicates a default value;
  • pos – the control position. A value of (-1, -1) indicates a default position, chosen by either the windowing system or wxPython, depending on platform;
  • size – the control size. A value of (-1, -1) indicates a default size, chosen by either the windowing system or wxPython, depending on platform;
  • style – the underlying wx.PyControl window style;
  • agwStyle – the AGW-specific window style, which can be one of the following bits:

    Window Styles | Hex Value | Description
    PM_HORIZONTAL | 0x0 | Shows horizontal bands in PeakMeterCtrl.
    PM_VERTICAL | 0x1 | Shows vertical bands in PeakMeterCtrl.

DoGetBestSize() [source]

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

Note

Overridden from wx.PyControl.

DoTimerProcessing() [source]

PeakMeterCtrl animation, does the wx.EVT_TIMER processing.

DrawHorzBand(dc, rect) [source]

Draws horizontal bands.

Parameters:
  • dc – an instance of wx.DC;
  • rect – the horizontal bands client rectangle.

Todo

Implement falloff effect for horizontal bands.

DrawVertBand(dc, rect) [source]

Draws vertical bands.

Parameters:
  • dc – an instance of wx.DC;

  • rect – the vertical bands client rectangle.

GetAGWWindowStyleFlag() [source]

Returns the PeakMeterCtrl window style.

See also

SetAGWWindowStyleFlag for a list of possible window style flags.

GetFalloffEffect() [source]

Returns the falloff effect flag.

GetRangeValue() [source]

Get range value of PeakMeterCtrl.

InitData() [source]

Initializes the control.

IsGridVisible() [source]

Returns if gridlines are visible.

IsStarted() [source]

Check if animation is active.

OnEraseBackground(event) [source]

Handles the wx.EVT_ERASE_BACKGROUND event for PeakMeterCtrl.

Parameters: event – a wx.EraseEvent event to be processed.

Note

This method is intentionally empty to reduce flicker.

OnPaint(event) [source]

Handles the wx.EVT_PAINT event for PeakMeterCtrl.

Parameters: event – a wx.PaintEvent event to be processed.

OnSize(event) [source]

Handles the wx.EVT_SIZE event for PeakMeterCtrl.

Parameters: event – a wx.SizeEvent event to be processed.

OnTimer(event) [source]

Handles the wx.EVT_TIMER event for PeakMeterCtrl.

Parameters: event – a wx.TimerEvent event to be processed.

ResetControl() [source]

Resets the PeakMeterCtrl.

SetAGWWindowStyleFlag(agwStyle) [source]

Sets the PeakMeterCtrl window style flags.

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

Window Styles | Hex Value | Description
PM_HORIZONTAL | 0x0 | Shows horizontal bands in PeakMeterCtrl.
PM_VERTICAL | 0x1 | Shows vertical bands in PeakMeterCtrl.

SetBackgroundColour(colourBgnd) [source]

Changes the background colour of PeakMeterCtrl.

Parameters: colourBgnd – the colour to be used as the background colour, pass wx.NullColour to reset to the default colour.

Note

The background colour is usually painted by the default wx.EraseEvent event handler function under Windows and automatically under GTK.

Note

Setting the background colour does not cause an immediate refresh, so you may wish to call wx.Window.ClearBackground or wx.Window.Refresh after calling this function.

Note

Overridden from wx.PyControl.

SetBandsColour(colourNormal, colourMedium, colourHigh) [source]

Set bands colour for PeakMeterCtrl.

Parameters:
  • colourNormal – the colour for normal (low) bands, a valid wx.Colour object;
  • colourMedium – the colour for medium bands, a valid wx.Colour object;

  • colourHigh – the colour for high bands, a valid wx.Colour object.

SetData(arrayValue, offset, size) [source]

Change data value. Use this function to change only a set of values. All bands can be changed or only 1 band, depending on the application.

Parameters:
  • arrayValue – a Python list containing the PeakMeterData values;
  • offset – the (optional) offset where to start applying the new data;
  • size – the size of the input data.

SetFalloffDelay(speed) [source]

Set peak value speed before falling off.

Parameters: speed – the speed at which the falloff happens.

SetFalloffEffect(falloffEffect) [source]

Set falloff effect flag.

Parameters: falloffEffect – True to enable the falloff effect, False to disable it.

SetMeterBands(numBands, ledBands) [source]

Set number of vertical or horizontal bands to display.

Parameters:
  • numBands – number of bands to display (either vertical or horizontal);
  • ledBands – the number of leds per band.

Note

You can obtain a smooth effect by setting nHorz or nVert to “1”, these cannot be 0.

SetRangeValue(minVal, medVal, maxVal) [source]

Sets the ranges for low, medium and high bands.

Parameters:
  • minVal – the value for low bands;
  • medVal – the value for medium bands;
  • maxVal – the value for high bands.

Note

The conditions to be satisfied are:

Min: [0 - nMin[, Med: [nMin - nMed[, Max: [nMed - nMax]

ShowGrid(showGrid) [source]

Request to have gridlines visible or not.

Parameters: showGrid – True to show grid lines, False otherwise.

Start(delay) [source]

Start the timer and animation effect.

Parameters: delay – the animation effect delay, in milliseconds.

Stop() [source]

Stop the timer and animation effect.

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • infobar
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • peakmeter »
  • PeakMeterCtrl


PeakMeterData

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • peakmeter »
  • PeakMeterData

PeakMeterData

A simple class which holds data for our PeakMeterCtrl.

hierarchy Inheritance Diagram

Inheritance diagram for: PeakMeterData

Inheritance diagram of PeakMeterData

Methods Summary

__init__ | Default class constructor.
IsEqual | Returns whether 2 instances of PeakMeterData are the same.
IsGreater | Returns whether one PeakMeterData is greater than another.
IsLower | Returns whether one PeakMeterData is smaller than another.

API Class API

class PeakMeterData(object) [source]

A simple class which holds data for our PeakMeterCtrl.

__init__(value=0, falloff=0, peak=0) [source]

Default class constructor.

Parameters:
  • value – the current PeakMeterCtrl value;
  • falloff – the falloff effect. True to enable it, False to disable it;
  • peak – the peak value.

IsEqual(pm) [source]

Returns whether 2 instances of PeakMeterData are the same.

Parameters: pm – another instance of PeakMeterData.

IsGreater(pm) [source]

Returns whether one PeakMeterData is greater than another.

Parameters: pm – another instance of PeakMeterData.

IsLower(pm) [source]

Returns whether one PeakMeterData is smaller than another.

Parameters: pm – another instance of PeakMeterData.

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • infobar
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • peakmeter »
  • PeakMeterData


SVN Revision 68362 For peakmeter

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • peakmeter »
  • SVN Revision 68362 For peakmeter

svn SVN Revision 68362 For peakmeter

This file contains the SVN revision history for peakmeter, at revision 68362.

Available information include commit date, the name of the committer, the file size, the SVN log messages and a diff from the previous version (if available).

File Information

  • Commit Date: 17-Oct-2008 20:51:43 UTC
  • Committer: AG
  • File Size: 23788 byte(s)

Log Messages

The following log message was entered by the committer:

  • All of AGW: change my work e-mail from KPO to Maersk Oil (silly commit)

Diff To Previous Version (65377)

Version SVN diff:

--- wxPython/3rdParty/AGW/agw/peakmeter.py  2010/08/21 20:27:02     65377
+++ wxPython/3rdParty/AGW/agw/peakmeter.py  2011/07/24 21:36:47     68362
@@ -16,7 +16,7 @@
# write to me at:
#
# andrea.gavana@gmail.com
-# gavana@kpo.kz
+# andrea.gavana@maerskoil.com
#
# Or, obviously, to the wxPython mailing list!!!
#

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • peakmeter »
  • SVN Revision 68362 For peakmeter


SVN Revision 68881 For peakmeter

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • peakmeter »
  • SVN Revision 68881 For peakmeter

svn SVN Revision 68881 For peakmeter

This file contains the SVN revision history for peakmeter, at revision 68881.

Available information include commit date, the name of the committer, the file size, the SVN log messages and a diff from the previous version (if available).

File Information

  • Commit Date: 17-Oct-2008 19:15:31 UTC
  • Committer: AG
  • File Size: 26021 byte(s)

Log Messages

The following log message was entered by the committer:

  • AGW: General overhaul of the documentation, much improved. All the widgets have their own sample usage in the docs as well;

  • FlatNotebook: Added the FNB_NAV_BUTTONS_WHEN_NEEDED style, which hides the navigation left/right arrows if all tabs fit;

  • RibbonBar: - Added the EVT_RIBBONBAR_TAB_LEFT_DCLICK event, which generates a special event

    when a ribbon bar tab is double-clicked;

    • Added support for toggle buttons;
    • Improved support for ribbon panel sizers: panels with sizers should now automatically minimise at small sizes, and behave properly when popping up from a minimised state;
    • Added tooltips via SetToolTip for those buttons which have the help_string attribute set.

  • XLSGrid: a new widget was added to AGW, termed XLSGrid. It’s based on wx.grid.Grid and can be used to faithfully reproduce the appearance of a Microsoft Excel spreadsheets.

Diff To Previous Version (68362)

Version SVN diff:

--- wxPython/3rdParty/AGW/agw/peakmeter.py  2011/07/24 21:36:47     68362
+++ wxPython/3rdParty/AGW/agw/peakmeter.py  2011/08/25 16:40:17     68881
@@ -2,7 +2,7 @@
# PEAKMETERCTRL wxPython IMPLEMENTATION
#
# Andrea Gavana, @ 07 October 2008
-# Latest Revision: 14 Apr 2010, 12.00 GMT
+# Latest Revision: 17 Aug 2011, 15.00 GMT
#
#
# TODO List
@@ -25,14 +25,14 @@
# --------------------------------------------------------------------------------- #

"""
-PeakMeterCtrl mimics the behaviour of equalizers that are usually found in stereos
+L{PeakMeterCtrl} mimics the behaviour of equalizers that are usually found in stereos
and MP3 players.

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

-PeakMeterCtrl mimics the behaviour of equalizers that are usually found in stereos
+L{PeakMeterCtrl} mimics the behaviour of equalizers that are usually found in stereos
and MP3 players. This widgets supports:

* Vertical and horizontal led bands;
@@ -44,10 +44,90 @@
And a lot more. Check the demo for an almost complete review of the functionalities.

+Usage
+=====
+
+Usage example::
+
+    import wx
+    import random
+
+    import wx.lib.agw.peakmeter as PM
+
+    class MyFrame(wx.Frame):
+
+        def __init__(self, parent):
+
+            wx.Frame.__init__(self, parent, -1, "PeakMeterCtrl Demo")
+
+            panel = wx.Panel(self)
+
+            # Initialize Peak Meter control 1
+            self.vertPeak = PM.PeakMeterCtrl(panel, -1, style=wx.SIMPLE_BORDER, agwStyle=PM.PM_VERTICAL)
+            # Initialize Peak Meter control 2
+            self.horzPeak = PM.PeakMeterCtrl(panel, -1, style=wx.SUNKEN_BORDER, agwStyle=PM.PM_HORIZONTAL)
+
+            self.vertPeak.SetMeterBands(10, 15)
+            self.horzPeak.SetMeterBands(10, 15)
+
+            # Layout the two PeakMeterCtrl
+            mainSizer = wx.BoxSizer(wx.HORIZONTAL)
+            mainSizer.Add(self.vertPeak, 0, wx.EXPAND|wx.ALL, 15)
+            mainSizer.Add(self.horzPeak, 0, wx.EXPAND|wx.ALL, 15)
+
+            panel.SetSizer(mainSizer)
+            mainSizer.Layout()
+
+            self.timer = wx.Timer(self)
+            self.Bind(wx.EVT_TIMER, self.OnTimer)
+
+            wx.CallLater(500, self.Start)
+
+
+        def Start(self):
+            ''' Starts the PeakMeterCtrl. '''
+
+            self.timer.Start(1000/2)            # 2 fps
+
+            self.vertPeak.Start(1000/18)        # 18 fps
+            self.horzPeak.Start(1000/20)        # 20 fps
+
+
+        def OnTimer(self, event):
+            '''
+            Handles the ``wx.EVT_TIMER`` event for L{PeakMeterCtrl}.
+
+            :param `event`: a `wx.TimerEvent` event to be processed.
+            '''
+
+            # Generate 15 random number and set them as data for the meter
+            nElements = 15
+            arrayData = []
+
+            for i in xrange(nElements):
+                nRandom = random.randint(0, 100)
+                arrayData.append(nRandom)
+
+            self.vertPeak.SetData(arrayData, 0, nElements)
+            self.horzPeak.SetData(arrayData, 0, nElements)
+
+
+    # our normal wxApp-derived class, as usual
+
+    app = wx.PySimpleApp()
+
+    frame = MyFrame(None)
+    app.SetTopWindow(frame)
+    frame.Show()
+
+    app.MainLoop()
+
+
+
Supported Platforms
===================

-PeakMeterCtrl has been tested on the following platforms:
+L{PeakMeterCtrl} has been tested on the following platforms:
* Windows (Windows XP).

@@ -59,8 +139,8 @@
================= =========== ==================================================
Window Styles     Hex Value   Description
================= =========== ==================================================
-``PM_HORIZONTAL``         0x0 Shows horizontal bands in `PeakMeterCtrl`.
-``PM_VERTICAL``           0x1 Shows vertical bands in `PeakMeterCtrl`.
+``PM_HORIZONTAL``         0x0 Shows horizontal bands in L{PeakMeterCtrl}.
+``PM_VERTICAL``           0x1 Shows vertical bands in L{PeakMeterCtrl}.
================= =========== ==================================================

@@ -73,9 +153,9 @@
License And Version
===================

-PeakMeterCtrl is distributed under the wxPython license.
+L{PeakMeterCtrl} is distributed under the wxPython license.

-Latest Revision: Andrea Gavana @ 12 Apr 2010, 12.00 GMT
+Latest Revision: Andrea Gavana @ 17 Aug 2011, 15.00 GMT

Version 0.3

@@ -85,9 +165,9 @@

# Horizontal or vertical PeakMeterCtrl
PM_HORIZONTAL = 0
-""" Shows horizontal bands in `PeakMeterCtrl`. """
+""" Shows horizontal bands in L{PeakMeterCtrl}. """
PM_VERTICAL = 1
-""" Shows vertical bands in `PeakMeterCtrl`. """
+""" Shows vertical bands in L{PeakMeterCtrl}. """

# Some useful constants...
BAND_DEFAULT = 8
@@ -559,6 +639,8 @@
Gets the size which best suits the window: for a control, it would be the
minimal size which doesn't truncate the control, for a panel - the same size
as it would have after a call to `Fit()`.
+
+        :note: Overridden from `wx.PyControl`.
"""

# something is better than nothing...

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • peakmeter »
  • SVN Revision 68881 For peakmeter


persist.persist_handlers functions

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • persist library »
  • persist.persist_handlers »
  • persist.persist_handlers functions

persist.persist_handlers functions

This is the description of standalone Python functions in the persist.persist_handlers module.

Functions Summary

CreateFont | Creates a tuple of 7 wx.Font attributes from the font input parameter.
FindHandler | Finds a suitable handler for the input Persistent Object depending on the
HasCtrlHandler | Is there a suitable handler for this control
PyDate2wxDate | Transforms a datetime.date object into a wx.DateTime one.
wxDate2PyDate | Transforms a wx.DateTime object into a datetime.date one.

API Functions API

CreateFont(font) [source]

Creates a tuple of 7 wx.Font attributes from the font input parameter.

Parameters: font – a wx.Font instance.
Returns: A tuple of 7 wx.Font attributes from the font input parameter.

FindHandler(pObject) [source]

Finds a suitable handler for the input Persistent Object depending on the widget kind.

Parameters: pObject – an instance of PersistentObject class.

HasCtrlHandler(control) [source]

Is there a suitable handler for this control

Parameters: control – the control instance to check if a handler for it exists.

PyDate2wxDate(date) [source]

Transforms a datetime.date object into a wx.DateTime one.

Parameters: date – a datetime.date object.

wxDate2PyDate(date) [source]

Transforms a wx.DateTime object into a datetime.date one.

Parameters: date – a wx.DateTime object.

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • infobar
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • persist library »
  • persist.persist_handlers »
  • persist.persist_handlers functions


AbstractHandler

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • persist library »
  • persist.persist_handlers »
  • AbstractHandler

AbstractHandler

Base class for persistent windows, uses the window name as persistent name by default and automatically reacts to the window destruction.

Note

This is an abstract class. If you wish to add another (custom) handler for your widgets, you should derive from AbstractHandler and override the Save, Restore and GetKind methods.

hierarchy Inheritance Diagram

Inheritance diagram for: AbstractHandler

Inheritance diagram of AbstractHandler

subclasses Known Subclasses

  • persist.persist_handlers.AUIHandler
  • persist.persist_handlers.BookHandler
  • persist.persist_handlers.CalendarCtrlHandler
  • persist.persist_handlers.CheckBoxHandler
  • persist.persist_handlers.ChoiceComboHandler
  • persist.persist_handlers.CollapsiblePaneHandler
  • persist.persist_handlers.ColourPickerHandler
  • persist.persist_handlers.DatePickerHandler
  • persist.persist_handlers.FileDirPickerHandler
  • persist.persist_handlers.FileHistoryHandler
  • persist.persist_handlers.FoldPanelBarHandler
  • persist.persist_handlers.FontPickerHandler
  • persist.persist_handlers.ListBoxHandler
  • persist.persist_handlers.MediaCtrlHandler
  • persist.persist_handlers.MenuBarHandler
  • persist.persist_handlers.RadioBoxHandler
  • persist.persist_handlers.RadioButtonHandler
  • persist.persist_handlers.ScrolledWindowHandler
  • persist.persist_handlers.SliderHandler
  • persist.persist_handlers.SpinHandler
  • persist.persist_handlers.SplitterHandler
  • persist.persist_handlers.TextCtrlHandler
  • persist.persist_handlers.ToggleButtonHandler
  • persist.persist_handlers.ToolBarHandler
  • persist.persist_handlers.TreeCtrlHandler

Methods Summary

__init__ | Default class constructor.
GetKind | Returns a short and meaningful string description of your widget.
Restore | Restores the widget’s settings by calling PersistentObject.RestoreValue(), which in
Save | Saves the widget’s settings by calling PersistentObject.SaveValue(), which in

API Class API

class AbstractHandler(object) [source]

Base class for persistent windows, uses the window name as persistent name by default and automatically reacts to the window destruction.

Note

This is an abstract class. If you wish to add another (custom) handler for your widgets, you should derive from AbstractHandler and override the AbstractHandler.Save(), AbstractHandler.Restore() and AbstractHandler.GetKind() methods.

__init__(pObject) [source]

Default class constructor.

Parameters: pObject – a PersistentObject containing information about the persistent widget.

GetKind() [source]

Returns a short and meaningful string description of your widget.

Note

This method must be overridden in derived classes.

Restore() [source]

Restores the widget’s settings by calling PersistentObject.RestoreValue(), which in turns calls PersistenceManager.RestoreValue().

Note

This method must be overridden in derived classes.

Save() [source]

Saves the widget’s settings by calling PersistentObject.SaveValue(), which in turns calls PersistenceManager.SaveValue().

Note

This method must be overridden in derived classes.

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • infobar
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • persist library »
  • persist.persist_handlers »
  • AbstractHandler


AUIHandler

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • persist library »
  • persist.persist_handlers »
  • AUIHandler

AUIHandler

Supports saving/restoring wx.aui.AuiManager and AuiManager perspectives.

hierarchy Inheritance Diagram

Inheritance diagram for: AUIHandler

Inheritance diagram of AUIHandler

subclasses Known Subclasses

  • persist.persist_handlers.TLWHandler

supclasses Known Superclasses

  • persist.persist_handlers.AbstractHandler

Methods Summary

__init__
GetKind
Restore
Save

API Class API

class AUIHandler(AbstractHandler) [source]

Supports saving/restoring wx.aui.AuiManager and AuiManager perspectives.

__init__(pObject) [source]

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • infobar
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • persist library »
  • persist.persist_handlers »
  • AUIHandler


BookHandler

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • persist library »
  • persist.persist_handlers »
  • BookHandler

BookHandler

Supports saving/restoring book control selection.

This class handles the following wxPython widgets:

  • wx.Toolbook;
  • wx.Choicebook;
  • wx.Listbook;
  • wx.Treebook (except for opened tree branches, see TreebookHandler for this);
  • wx.Notebook;
  • wx.aui.AuiNotebook;
  • AuiNotebook;
  • FlatNotebook;
  • LabelBook;
  • FlatImageBook.

hierarchy Inheritance Diagram

Inheritance diagram for: BookHandler

Inheritance diagram of BookHandler

subclasses Known Subclasses

  • persist.persist_handlers.TreebookHandler

supclasses Known Superclasses

  • persist.persist_handlers.AbstractHandler

Methods Summary

__init__
GetKind
Restore
Save

API Class API

class BookHandler(AbstractHandler) [source]

Supports saving/restoring book control selection.

This class handles the following wxPython widgets:

  • wx.Toolbook;
  • wx.Choicebook;
  • wx.Listbook;
  • wx.Treebook (except for opened tree branches, see TreebookHandler for this);
  • wx.Notebook;
  • wx.aui.AuiNotebook;
  • AuiNotebook;
  • FlatNotebook;
  • LabelBook;
  • FlatImageBook.

__init__(pObject) [source]

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • infobar
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • persist library »
  • persist.persist_handlers »
  • BookHandler


CalendarCtrlHandler

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • persist library »
  • persist.persist_handlers »
  • CalendarCtrlHandler

CalendarCtrlHandler

Supports saving/restoring a wx.calendar.CalendarCtrl date.

This class handles the following wxPython widgets:

  • wx.lib.calendar.CalendarCtrl.

hierarchy Inheritance Diagram

Inheritance diagram for: CalendarCtrlHandler

Inheritance diagram of CalendarCtrlHandler

supclasses Known Superclasses

  • persist.persist_handlers.AbstractHandler

Methods Summary

__init__
GetKind
Restore
Save

API Class API

class CalendarCtrlHandler(AbstractHandler) [source]

Supports saving/restoring a wx.calendar.CalendarCtrl date.

This class handles the following wxPython widgets:

  • wx.lib.calendar.CalendarCtrl.

__init__(pObject) [source]

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • infobar
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • persist library »
  • persist.persist_handlers »
  • CalendarCtrlHandler


CheckBoxHandler

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • persist library »
  • persist.persist_handlers »
  • CheckBoxHandler

CheckBoxHandler

Supports saving/restoring a wx.CheckBox state.

This class handles the following wxPython widgets:

  • wx.CheckBox.

hierarchy Inheritance Diagram

Inheritance diagram for: CheckBoxHandler

Inheritance diagram of CheckBoxHandler

supclasses Known Superclasses

  • persist.persist_handlers.AbstractHandler

Methods Summary

__init__
GetKind
Restore
Save

API Class API

class CheckBoxHandler(AbstractHandler) [source]

Supports saving/restoring a wx.CheckBox state.

This class handles the following wxPython widgets:

  • wx.CheckBox.

__init__(pObject) [source]

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • infobar
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • persist library »
  • persist.persist_handlers »
  • CheckBoxHandler


CheckListBoxHandler

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • persist library »
  • persist.persist_handlers »
  • CheckListBoxHandler

CheckListBoxHandler

Supports saving/restoring checked and selected items in wx.CheckListBox.

This class handles the following wxPython widgets:

  • wx.CheckListBox (only for checked items. For selected items see ListBoxHandler).

hierarchy Inheritance Diagram

Inheritance diagram for: CheckListBoxHandler

Inheritance diagram of CheckListBoxHandler

supclasses Known Superclasses

  • persist.persist_handlers.ListBoxHandler

Methods Summary

__init__
GetKind
Restore
Save

API Class API

class CheckListBoxHandler(ListBoxHandler) [source]

Supports saving/restoring checked and selected items in wx.CheckListBox.

This class handles the following wxPython widgets:

  • wx.CheckListBox (only for checked items. For selected items see ListBoxHandler).

__init__(pObject) [source]

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • infobar
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • persist library »
  • persist.persist_handlers »
  • CheckListBoxHandler


ChoiceComboHandler

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • persist library »
  • persist.persist_handlers »
  • ChoiceComboHandler

ChoiceComboHandler

Supports saving/restoring wx.Choice, wx.ComboBox and wx.combo.OwnerDrawnComboBox selection.

This class handles the following wxPython widgets:

  • wx.Choice;
  • wx.ComboBox;
  • wx.combo.OwnerDrawnComboBox.

hierarchy Inheritance Diagram

Inheritance diagram for: ChoiceComboHandler

Inheritance diagram of ChoiceComboHandler

supclasses Known Superclasses

  • persist.persist_handlers.AbstractHandler

Methods Summary

__init__
GetKind
Restore
Save

API Class API

class ChoiceComboHandler(AbstractHandler) [source]

Supports saving/restoring wx.Choice, wx.ComboBox and wx.combo.OwnerDrawnComboBox selection.

This class handles the following wxPython widgets:

  • wx.Choice;
  • wx.ComboBox;
  • wx.combo.OwnerDrawnComboBox.

__init__(pObject) [source]

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • infobar
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • persist library »
  • persist.persist_handlers »
  • ChoiceComboHandler


ChoiceDialogHandler

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • persist library »
  • persist.persist_handlers »
  • ChoiceDialogHandler

ChoiceDialogHandler

Supports saving/restoring a wx.MultiChoiceDialog / wx.SingleChoiceDialog choices.

This class handles the following wxPython widgets:

  • wx.SingleChoiceDialog;
  • wx.MultiChoiceDialog.

hierarchy Inheritance Diagram

Inheritance diagram for: ChoiceDialogHandler

Inheritance diagram of ChoiceDialogHandler

supclasses Known Superclasses

  • persist.persist_handlers.TLWHandler

Methods Summary

__init__
GetKind
Restore
Save

API Class API

class ChoiceDialogHandler(TLWHandler) [source]

Supports saving/restoring a wx.MultiChoiceDialog / wx.SingleChoiceDialog choices.

This class handles the following wxPython widgets:

  • wx.SingleChoiceDialog;
  • wx.MultiChoiceDialog.

__init__(pObject) [source]

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • infobar
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • persist library »
  • persist.persist_handlers »
  • ChoiceDialogHandler


CollapsiblePaneHandler

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • persist library »
  • persist.persist_handlers »
  • CollapsiblePaneHandler

CollapsiblePaneHandler

Supports saving/restoring a wx.CollapsiblePane state.

This class handles the following wxPython widgets:

  • wx.CollapsiblePane.

hierarchy Inheritance Diagram

Inheritance diagram for: CollapsiblePaneHandler

Inheritance diagram of CollapsiblePaneHandler

supclasses Known Superclasses

  • persist.persist_handlers.AbstractHandler

Methods Summary

__init__
GetKind
Restore
Save

API Class API

class CollapsiblePaneHandler(AbstractHandler) [source]

Supports saving/restoring a wx.CollapsiblePane state.

This class handles the following wxPython widgets:

  • wx.CollapsiblePane.

__init__(pObject) [source]

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • infobar
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • persist library »
  • persist.persist_handlers »
  • CollapsiblePaneHandler


ColourDialogHandler

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • persist library »
  • persist.persist_handlers »
  • ColourDialogHandler

ColourDialogHandler

Supports saving/restoring a wx.ColourDialog data (colour, custom colours and full choice in the dialog).

This class handles the following wxPython widgets:

  • wx.ColourDialog;
  • CubeColourDialog.

Todo

Find a way to properly save and restore dialog data (wx.ColourDialog, wx.FontDialog etc...).

hierarchy Inheritance Diagram

Inheritance diagram for: ColourDialogHandler

Inheritance diagram of ColourDialogHandler

supclasses Known Superclasses

  • persist.persist_handlers.TLWHandler

Methods Summary

__init__
GetKind
Restore
Save

API Class API

class ColourDialogHandler(TLWHandler) [source]

Supports saving/restoring a wx.ColourDialog data (colour, custom colours and full choice in the dialog).

This class handles the following wxPython widgets:

  • wx.ColourDialog;
  • CubeColourDialog.

Todo

Find a way to properly save and restore dialog data (wx.ColourDialog, wx.FontDialog etc...).

__init__(pObject) [source]

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • infobar
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • persist library »
  • persist.persist_handlers »
  • ColourDialogHandler


ColourPickerHandler

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • persist library »
  • persist.persist_handlers »
  • ColourPickerHandler

ColourPickerHandler

Supports saving/restoring a wx.ColourPickerCtrl / wx.lib.colourselect.ColourSelect colour.

This class handles the following wxPython widgets:

  • wx.ColourPickerCtrl;
  • wx.lib.colourselect.ColourSelect.

hierarchy Inheritance Diagram

Inheritance diagram for: ColourPickerHandler

Inheritance diagram of ColourPickerHandler

supclasses Known Superclasses

  • persist.persist_handlers.AbstractHandler

Methods Summary

__init__
GetKind
Restore
Save

API Class API

class ColourPickerHandler(AbstractHandler) [source]

Supports saving/restoring a wx.ColourPickerCtrl / wx.lib.colourselect.ColourSelect colour.

This class handles the following wxPython widgets:

  • wx.ColourPickerCtrl;
  • wx.lib.colourselect.ColourSelect.

__init__(pObject) [source]

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • infobar
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • persist library »
  • persist.persist_handlers »
  • ColourPickerHandler


DatePickerHandler

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • persist library »
  • persist.persist_handlers »
  • DatePickerHandler

DatePickerHandler

Supports saving/restoring a wx.DatePickerCtrl / wx.GenericDatePickerCtrl date.

This class handles the following wxPython widgets:

  • wx.DatePickerCtrl;
  • wx.GenericDatePickerCtrl.

hierarchy Inheritance Diagram

Inheritance diagram for: DatePickerHandler

Inheritance diagram of DatePickerHandler

supclasses Known Superclasses

  • persist.persist_handlers.AbstractHandler

Methods Summary

__init__
GetKind
Restore
Save

API Class API

class DatePickerHandler(AbstractHandler) [source]

Supports saving/restoring a wx.DatePickerCtrl / wx.GenericDatePickerCtrl date.

This class handles the following wxPython widgets:

  • wx.DatePickerCtrl;
  • wx.GenericDatePickerCtrl.

__init__(pObject) [source]

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • infobar
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • persist library »
  • persist.persist_handlers »
  • DatePickerHandler


FileDirDialogHandler

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • persist library »
  • persist.persist_handlers »
  • FileDirDialogHandler

FileDirDialogHandler

Supports saving/restoring a wx.DirDialog / wx.FileDialog path.

This class handles the following wxPython widgets:

  • wx.DirDialog;
  • wx.FileDialog.

hierarchy Inheritance Diagram

Inheritance diagram for: FileDirDialogHandler

Inheritance diagram of FileDirDialogHandler

supclasses Known Superclasses

  • persist.persist_handlers.FileDirPickerHandler
  • persist.persist_handlers.TLWHandler

Methods Summary

__init__
GetKind
Restore
Save

API Class API

class FileDirDialogHandler(TLWHandler, FileDirPickerHandler) [source]

Supports saving/restoring a wx.DirDialog / wx.FileDialog path.

This class handles the following wxPython widgets:

  • wx.DirDialog;
  • wx.FileDialog.

__init__(pObject) [source]

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • infobar
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • persist library »
  • persist.persist_handlers »
  • FileDirDialogHandler


FileDirPickerHandler

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • persist library »
  • persist.persist_handlers »
  • FileDirPickerHandler

FileDirPickerHandler

Supports saving/restoring a wx.FilePickerCtrl / wx.DirPickerCtrl path.

This class handles the following wxPython widgets:

  • wx.FilePickerCtrl;
  • wx.DirPickerCtrl.

hierarchy Inheritance Diagram

Inheritance diagram for: FileDirPickerHandler

Inheritance diagram of FileDirPickerHandler

subclasses Known Subclasses

  • persist.persist_handlers.FileDirDialogHandler

supclasses Known Superclasses

  • persist.persist_handlers.AbstractHandler

Methods Summary

__init__
GetKind
Restore
Save

API Class API

class FileDirPickerHandler(AbstractHandler) [source]

Supports saving/restoring a wx.FilePickerCtrl / wx.DirPickerCtrl path.

This class handles the following wxPython widgets:

  • wx.FilePickerCtrl;
  • wx.DirPickerCtrl.

__init__(pObject) [source]

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • infobar
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • persist library »
  • persist.persist_handlers »
  • FileDirPickerHandler


FileHistoryHandler

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • persist library »
  • persist.persist_handlers »
  • FileHistoryHandler

FileHistoryHandler

Supports saving/restoring a wx.FileHistory list of file names.

This class handles the following wxPython widgets:

  • wx.FileHistory.

hierarchy Inheritance Diagram

Inheritance diagram for: FileHistoryHandler

Inheritance diagram of FileHistoryHandler

supclasses Known Superclasses

  • persist.persist_handlers.AbstractHandler

Methods Summary

__init__
GetKind
Restore
Save

API Class API

class FileHistoryHandler(AbstractHandler) [source]

Supports saving/restoring a wx.FileHistory list of file names.

This class handles the following wxPython widgets:

  • wx.FileHistory.

__init__(pObject) [source]

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • infobar
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • persist library »
  • persist.persist_handlers »
  • FileHistoryHandler


FindReplaceHandler

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • persist library »
  • persist.persist_handlers »
  • FindReplaceHandler

FindReplaceHandler

Supports saving/restoring a wx.FindReplaceDialog data (search string, replace string and flags).

This class handles the following wxPython widgets:

  • wx.FindReplaceDialog.

Todo

Find a way to properly save and restore dialog data (wx.ColourDialog, wx.FontDialog etc...).

hierarchy Inheritance Diagram

Inheritance diagram for: FindReplaceHandler

Inheritance diagram of FindReplaceHandler

supclasses Known Superclasses

  • persist.persist_handlers.TLWHandler

Methods Summary

__init__
GetKind
Restore
Save

API Class API

class FindReplaceHandler(TLWHandler) [source]

Supports saving/restoring a wx.FindReplaceDialog data (search string, replace string and flags).

This class handles the following wxPython widgets:

  • wx.FindReplaceDialog.

Todo

Find a way to properly save and restore dialog data (wx.ColourDialog, wx.FontDialog etc...).

__init__(pObject) [source]

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • infobar
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • persist library »
  • persist.persist_handlers »
  • FindReplaceHandler


FoldPanelBarHandler

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • persist library »
  • persist.persist_handlers »
  • FoldPanelBarHandler

FoldPanelBarHandler

Supports saving/restoring of FoldPanelBar.

This class handles the following wxPython widgets

  • L{foldpanelbar.FoldPanelBar

hierarchy Inheritance Diagram

Inheritance diagram for: FoldPanelBarHandler

Inheritance diagram of FoldPanelBarHandler

supclasses Known Superclasses

  • persist.persist_handlers.AbstractHandler

Methods Summary

__init__
GetKind
Restore
Save

API Class API

class FoldPanelBarHandler(AbstractHandler) [source]

Supports saving/restoring of FoldPanelBar.

This class handles the following wxPython widgets

  • L{foldpanelbar.FoldPanelBar

__init__(pObject) [source]

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • infobar
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • persist library »
  • persist.persist_handlers »
  • FoldPanelBarHandler


FontDialogHandler

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • persist library »
  • persist.persist_handlers »
  • FontDialogHandler

FontDialogHandler

Supports saving/restoring a wx.FontDialog data (effects, symbols, colour, font, help).

This class handles the following wxPython widgets:

  • wx.FontDialog.

Todo

Find a way to properly save and restore dialog data (wx.ColourDialog, wx.FontDialog etc...).

hierarchy Inheritance Diagram

Inheritance diagram for: FontDialogHandler

Inheritance diagram of FontDialogHandler

supclasses Known Superclasses

  • persist.persist_handlers.TLWHandler

Methods Summary

__init__
GetKind
Restore
Save

API Class API

class FontDialogHandler(TLWHandler) [source]

Supports saving/restoring a wx.FontDialog data (effects, symbols, colour, font, help).

This class handles the following wxPython widgets:

  • wx.FontDialog.

Todo

Find a way to properly save and restore dialog data (wx.ColourDialog, wx.FontDialog etc...).

__init__(pObject) [source]

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • infobar
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • persist library »
  • persist.persist_handlers »
  • FontDialogHandler


FontPickerHandler

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • persist library »
  • persist.persist_handlers »
  • FontPickerHandler

FontPickerHandler

Supports saving/restoring a wx.FontPickerCtrl font.

This class handles the following wxPython widgets:

  • wx.FontPickerCtrl.

hierarchy Inheritance Diagram

Inheritance diagram for: FontPickerHandler

Inheritance diagram of FontPickerHandler

supclasses Known Superclasses

  • persist.persist_handlers.AbstractHandler

Methods Summary

__init__
GetKind
Restore
Save

API Class API

class FontPickerHandler(AbstractHandler) [source]

Supports saving/restoring a wx.FontPickerCtrl font.

This class handles the following wxPython widgets:

  • wx.FontPickerCtrl.

__init__(pObject) [source]

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • infobar
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • persist library »
  • persist.persist_handlers »
  • FontPickerHandler


ListBoxHandler

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • persist library »
  • persist.persist_handlers »
  • ListBoxHandler

ListBoxHandler

Supports saving/restoring selected items in wx.ListBox, wx.ListCtrl, wx.ListView, wx.VListBox, wx.HtmlListBox, wx.SimpleHtmlListBox, wx.gizmos.EditableListBox.

This class handles the following wxPython widgets:

  • wx.ListBox;
  • wx.ListCtrl (only for selected items. For column sizes see ListCtrlHandler);
  • wx.ListView (only for selected items. For column sizes see ListCtrlHandler);
  • wx.VListBox;
  • wx.HtmlListBox;
  • wx.SimpleHtmlListBox;
  • wx.gizmos.EditableListBox.

hierarchy Inheritance Diagram

Inheritance diagram for: ListBoxHandler

Inheritance diagram of ListBoxHandler

subclasses Known Subclasses

  • persist.persist_handlers.CheckListBoxHandler
  • persist.persist_handlers.ListCtrlHandler

supclasses Known Superclasses

  • persist.persist_handlers.AbstractHandler

Methods Summary

__init__ |
GetKind |
GetSelections | Returns a list of selected items for wx.ListBox, wx.ListCtrl, wx.ListView,
Restore |
Save |

API Class API

class ListBoxHandler(AbstractHandler) [source]

Supports saving/restoring selected items in wx.ListBox, wx.ListCtrl, wx.ListView, wx.VListBox, wx.HtmlListBox, wx.SimpleHtmlListBox, wx.gizmos.EditableListBox.

This class handles the following wxPython widgets:

  • wx.ListBox;
  • wx.ListCtrl (only for selected items. For column sizes see ListCtrlHandler);
  • wx.ListView (only for selected items. For column sizes see ListCtrlHandler);
  • wx.VListBox;
  • wx.HtmlListBox;
  • wx.SimpleHtmlListBox;
  • wx.gizmos.EditableListBox.

__init__(pObject) [source]

GetSelections(listBox) [source]

Returns a list of selected items for wx.ListBox, wx.ListCtrl, wx.ListView, wx.VListBox, wx.HtmlListBox, wx.SimpleHtmlListBox, wx.gizmos.EditableListBox.

Parameters: listBox – an instance of wx.ListBox, wx.ListCtrl, wx.ListView, wx.VListBox, wx.HtmlListBox, wx.SimpleHtmlListBox, wx.gizmos.EditableListBox..

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • infobar
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • persist library »
  • persist.persist_handlers »
  • ListBoxHandler


ListCtrlHandler

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • persist library »
  • persist.persist_handlers »
  • ListCtrlHandler

ListCtrlHandler

Supports saving/restoring selected items and column sizes in wx.ListCtrl.

This class handles the following wxPython widgets:

  • wx.ListCtrl (only for column sizes. For selected items see ListBoxHandler);
  • wx.ListView (only for column sizes. For selected items see ListBoxHandler).

hierarchy Inheritance Diagram

Inheritance diagram for: ListCtrlHandler

Inheritance diagram of ListCtrlHandler

supclasses Known Superclasses

  • persist.persist_handlers.ListBoxHandler

Methods Summary

__init__
GetKind
Restore
Save

API Class API

class ListCtrlHandler(ListBoxHandler) [source]

Supports saving/restoring selected items and column sizes in wx.ListCtrl.

This class handles the following wxPython widgets:

  • wx.ListCtrl (only for column sizes. For selected items see ListBoxHandler);
  • wx.ListView (only for column sizes. For selected items see ListBoxHandler).

__init__(pObject) [source]

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • infobar
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • persist library »
  • persist.persist_handlers »
  • ListCtrlHandler


MediaCtrlHandler

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • persist library »
  • persist.persist_handlers »
  • MediaCtrlHandler

MediaCtrlHandler

Supports saving/restoring a wx.media.MediaCtrl movie position, volume and playback rate.

This class handles the following wxPython widgets:

  • wx.media.MediaCtrl.

hierarchy Inheritance Diagram

Inheritance diagram for: MediaCtrlHandler

Inheritance diagram of MediaCtrlHandler

supclasses Known Superclasses

  • persist.persist_handlers.AbstractHandler

Methods Summary

__init__
GetKind
Restore
Save

API Class API

class MediaCtrlHandler(AbstractHandler) [source]

Supports saving/restoring a wx.media.MediaCtrl movie position, volume and playback rate.

This class handles the following wxPython widgets:

  • wx.media.MediaCtrl.

__init__(pObject) [source]

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • infobar
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • persist library »
  • persist.persist_handlers »
  • MediaCtrlHandler


MenuBarHandler

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • persist library »
  • persist.persist_handlers »
  • MenuBarHandler

MenuBarHandler

Supports saving/restoring the wx.MenuBar and FlatMenuBar items state.

This class handles the following wxPython widgets:

  • wx.MenuBar;
  • FlatMenuBar.

hierarchy Inheritance Diagram

Inheritance diagram for: MenuBarHandler

Inheritance diagram of MenuBarHandler

supclasses Known Superclasses

  • persist.persist_handlers.AbstractHandler

Methods Summary

__init__
GetKind
Restore
Save

API Class API

class MenuBarHandler(AbstractHandler) [source]

Supports saving/restoring the wx.MenuBar and FlatMenuBar items state.

This class handles the following wxPython widgets:

  • wx.MenuBar;
  • FlatMenuBar.

__init__(pObject) [source]

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • infobar
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • persist library »
  • persist.persist_handlers »
  • MenuBarHandler


RadioBoxHandler

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • persist library »
  • persist.persist_handlers »
  • RadioBoxHandler

RadioBoxHandler

Supports saving/restoring a wx.RadioBox state.

This class handles the following wxPython widgets:

  • wx.RadioBox.

hierarchy Inheritance Diagram

Inheritance diagram for: RadioBoxHandler

Inheritance diagram of RadioBoxHandler

supclasses Known Superclasses

  • persist.persist_handlers.AbstractHandler

Methods Summary

__init__
GetKind
Restore
Save

API Class API

class RadioBoxHandler(AbstractHandler) [source]

Supports saving/restoring a wx.RadioBox state.

This class handles the following wxPython widgets:

  • wx.RadioBox.

__init__(pObject) [source]

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • infobar
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • persist library »
  • persist.persist_handlers »
  • RadioBoxHandler


RadioButtonHandler

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • persist library »
  • persist.persist_handlers »
  • RadioButtonHandler

RadioButtonHandler

Supports saving/restoring a wx.RadioButton state.

This class handles the following wxPython widgets:

  • wx.RadioButton.

hierarchy Inheritance Diagram

Inheritance diagram for: RadioButtonHandler

Inheritance diagram of RadioButtonHandler

supclasses Known Superclasses

  • persist.persist_handlers.AbstractHandler

Methods Summary

__init__
GetKind
Restore
Save

API Class API

class RadioButtonHandler(AbstractHandler) [source]

Supports saving/restoring a wx.RadioButton state.

This class handles the following wxPython widgets:

  • wx.RadioButton.

__init__(pObject) [source]

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • infobar
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • persist library »
  • persist.persist_handlers »
  • RadioButtonHandler


ScrolledWindowHandler

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • persist library »
  • persist.persist_handlers »
  • ScrolledWindowHandler

ScrolledWindowHandler

Supports saving/restoring a wx.ScrolledWindow / wx.lib.scrolledpanel.ScrolledPanel scroll position.

This class handles the following wxPython widgets:

  • wx.ScrolledWindow;
  • wx.lib.scrolledpanel.ScrolledPanel.

hierarchy Inheritance Diagram

Inheritance diagram for: ScrolledWindowHandler

Inheritance diagram of ScrolledWindowHandler

supclasses Known Superclasses

  • persist.persist_handlers.AbstractHandler

Methods Summary

__init__
GetKind
Restore
Save

API Class API

class ScrolledWindowHandler(AbstractHandler) [source]

Supports saving/restoring a wx.ScrolledWindow / wx.lib.scrolledpanel.ScrolledPanel scroll position.

This class handles the following wxPython widgets:

  • wx.ScrolledWindow;
  • wx.lib.scrolledpanel.ScrolledPanel.

__init__(pObject) [source]

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • infobar
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • persist library »
  • persist.persist_handlers »
  • ScrolledWindowHandler


SliderHandler

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • persist library »
  • persist.persist_handlers »
  • SliderHandler

SliderHandler

Supports saving/restoring a wx.Slider / KnobCtrl thumb position.

This class handles the following wxPython widgets:

  • wx.Slider;
  • KnobCtrl.

hierarchy Inheritance Diagram

Inheritance diagram for: SliderHandler

Inheritance diagram of SliderHandler

supclasses Known Superclasses

  • persist.persist_handlers.AbstractHandler

Methods Summary

__init__
GetKind
Restore
Save

API Class API

class SliderHandler(AbstractHandler) [source]

Supports saving/restoring a wx.Slider / KnobCtrl thumb position.

This class handles the following wxPython widgets:

  • wx.Slider;
  • KnobCtrl.

__init__(pObject) [source]

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • infobar
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • persist library »
  • persist.persist_handlers »
  • SliderHandler


SpinHandler

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • persist library »
  • persist.persist_handlers »
  • SpinHandler

SpinHandler

Supports saving/restoring a wx.SpinButton / wx.SpinCtrl value.

This class handles the following wxPython widgets:

  • wx.SpinCtrl;
  • wx.SpinButton.

hierarchy Inheritance Diagram

Inheritance diagram for: SpinHandler

Inheritance diagram of SpinHandler

supclasses Known Superclasses

  • persist.persist_handlers.AbstractHandler

Methods Summary

__init__
GetKind
Restore
Save

API Class API

class SpinHandler(AbstractHandler) [source]

Supports saving/restoring a wx.SpinButton / wx.SpinCtrl value.

This class handles the following wxPython widgets:

  • wx.SpinCtrl;
  • wx.SpinButton.

__init__(pObject) [source]

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • infobar
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • persist library »
  • persist.persist_handlers »
  • SpinHandler


SplitterHandler

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • persist library »
  • persist.persist_handlers »
  • SplitterHandler

SplitterHandler

Supports saving/restoring a wx.SplitterWindow splitter position.

This class handles the following wxPython widgets:

  • wx.SplitterWindow.

hierarchy Inheritance Diagram

Inheritance diagram for: SplitterHandler

Inheritance diagram of SplitterHandler

supclasses Known Superclasses

  • persist.persist_handlers.AbstractHandler

Methods Summary

__init__
GetKind
Restore
Save

API Class API

class SplitterHandler(AbstractHandler) [source]

Supports saving/restoring a wx.SplitterWindow splitter position.

This class handles the following wxPython widgets:

  • wx.SplitterWindow.

__init__(pObject) [source]

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • infobar
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • persist library »
  • persist.persist_handlers »
  • SplitterHandler


TextCtrlHandler

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • persist library »
  • persist.persist_handlers »
  • TextCtrlHandler

TextCtrlHandler

Supports saving/restoring a wx.TextCtrl entered string.

This class handles the following wxPython widgets:

  • wx.TextCtrl;
  • wx.SearchCtrl;
  • wx.lib.expando.ExpandoTextCtrl;
  • wx.lib.masked.TextCtrl;
  • wx.lib.masked.ComboBox;
  • wx.lib.masked.IpAddrCtrl;
  • wx.lib.masked.TimeCtrl;
  • wx.lib.masked.NumCtrl;

hierarchy Inheritance Diagram

Inheritance diagram for: TextCtrlHandler

Inheritance diagram of TextCtrlHandler

subclasses Known Subclasses

  • persist.persist_handlers.TextEntryHandler

supclasses Known Superclasses

  • persist.persist_handlers.AbstractHandler

Methods Summary

__init__
GetKind
Restore
Save

API Class API

class TextCtrlHandler(AbstractHandler) [source]

Supports saving/restoring a wx.TextCtrl entered string.

This class handles the following wxPython widgets:

  • wx.TextCtrl;
  • wx.SearchCtrl;
  • wx.lib.expando.ExpandoTextCtrl;
  • wx.lib.masked.TextCtrl;
  • wx.lib.masked.ComboBox;
  • wx.lib.masked.IpAddrCtrl;
  • wx.lib.masked.TimeCtrl;
  • wx.lib.masked.NumCtrl;

__init__(pObject) [source]

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • infobar
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • persist library »
  • persist.persist_handlers »
  • TextCtrlHandler


TextEntryHandler

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • persist library »
  • persist.persist_handlers »
  • TextEntryHandler

TextEntryHandler

Supports saving/restoring a wx.TextEntryDialog string.

This class handles the following wxPython widgets:

  • wx.TextEntryDialog;
  • wx.PasswordEntryDialog.

hierarchy Inheritance Diagram

Inheritance diagram for: TextEntryHandler

Inheritance diagram of TextEntryHandler

supclasses Known Superclasses

  • persist.persist_handlers.TLWHandler
  • persist.persist_handlers.TextCtrlHandler

Methods Summary

__init__
GetKind
Restore
Save

API Class API

class TextEntryHandler(TLWHandler, TextCtrlHandler) [source]

Supports saving/restoring a wx.TextEntryDialog string.

This class handles the following wxPython widgets:

  • wx.TextEntryDialog;
  • wx.PasswordEntryDialog.

__init__(pObject) [source]

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • infobar
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • persist library »
  • persist.persist_handlers »
  • TextEntryHandler


TLWHandler

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • persist library »
  • persist.persist_handlers »
  • TLWHandler

TLWHandler

Supports saving/restoring window position and size as well as maximized/iconized/restore state for toplevel windows.

This class handles the following wxPython widgets:

  • All wx.Frame derived classes;
  • All wx.Dialog derived classes.

In addition, if the toplevel window has an associated AuiManager (whether it is wx.aui.AuiManager or AuiManager and PersistenceManager has the PM_SAVE_RESTORE_AUI_PERSPECTIVES style set (the default), this class will also save and restore AUI perspectives using the underlying AUIHandler class.

hierarchy Inheritance Diagram

Inheritance diagram for: TLWHandler

Inheritance diagram of TLWHandler

subclasses Known Subclasses

  • persist.persist_handlers.ChoiceDialogHandler
  • persist.persist_handlers.ColourDialogHandler
  • persist.persist_handlers.FileDirDialogHandler
  • persist.persist_handlers.FindReplaceHandler
  • persist.persist_handlers.FontDialogHandler
  • persist.persist_handlers.TextEntryHandler

supclasses Known Superclasses

  • persist.persist_handlers.AUIHandler

Methods Summary

__init__
GetKind
Restore
Save

API Class API

class TLWHandler(AUIHandler) [source]

Supports saving/restoring window position and size as well as maximized/iconized/restore state for toplevel windows.

This class handles the following wxPython widgets:

  • All wx.Frame derived classes;
  • All wx.Dialog derived classes.

In addition, if the toplevel window has an associated AuiManager (whether it is wx.aui.AuiManager or AuiManager and PersistenceManager has the PM_SAVE_RESTORE_AUI_PERSPECTIVES style set (the default), this class will also save and restore AUI perspectives using the underlying AUIHandler class.

__init__(pObject) [source]

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • infobar
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • persist library »
  • persist.persist_handlers »
  • TLWHandler


ToggleButtonHandler

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • persist library »
  • persist.persist_handlers »
  • ToggleButtonHandler

ToggleButtonHandler

Supports saving/restoring a wx.ToggleButton and friends state.

This class handles the following wxPython widgets:

  • wx.ToggleButton;
  • wx.lib.buttons.GenToggleButton;
  • wx.lib.buttons.GenBitmapToggleButton;
  • wx.lib.buttons.GenBitmapTextToggleButton;
  • SToggleButton;
  • SBitmapToggleButton;
  • SBitmapTextToggleButton.

hierarchy Inheritance Diagram

Inheritance diagram for: ToggleButtonHandler

Inheritance diagram of ToggleButtonHandler

supclasses Known Superclasses

  • persist.persist_handlers.AbstractHandler

Methods Summary

__init__
GetKind
Restore
Save

API Class API

class ToggleButtonHandler(AbstractHandler) [source]

Supports saving/restoring a wx.ToggleButton and friends state.

This class handles the following wxPython widgets:

  • wx.ToggleButton;
  • wx.lib.buttons.GenToggleButton;
  • wx.lib.buttons.GenBitmapToggleButton;
  • wx.lib.buttons.GenBitmapTextToggleButton;
  • SToggleButton;
  • SBitmapToggleButton;
  • SBitmapTextToggleButton.

__init__(pObject) [source]

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • infobar
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • persist library »
  • persist.persist_handlers »
  • ToggleButtonHandler


ToolBarHandler

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • persist library »
  • persist.persist_handlers »
  • ToolBarHandler

ToolBarHandler

Supports saving/restoring the AuiToolBar items state.

This class handles the following wxPython widgets:

  • AuiToolBar.

Todo

Find a way to handle wx.ToolBar UI settings as it has been done for AuiToolBar: currently wx.ToolBar doesn’t seem to have easy access to the underlying toolbar tools.

hierarchy Inheritance Diagram

Inheritance diagram for: ToolBarHandler

Inheritance diagram of ToolBarHandler

supclasses Known Superclasses

  • persist.persist_handlers.AbstractHandler

Methods Summary

__init__
GetKind
Restore
Save

API Class API

class ToolBarHandler(AbstractHandler) [source]

Supports saving/restoring the AuiToolBar items state.

This class handles the following wxPython widgets:

  • AuiToolBar.

Todo

Find a way to handle wx.ToolBar UI settings as it has been done for AuiToolBar: currently wx.ToolBar doesn’t seem to have easy access to the underlying toolbar tools.

__init__(pObject) [source]

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • infobar
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • persist library »
  • persist.persist_handlers »
  • ToolBarHandler


TreebookHandler

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • persist library »
  • persist.persist_handlers »
  • TreebookHandler

TreebookHandler

Supports saving/restoring open tree branches.

This class handles the following wxPython widgets:

  • wx.Treebook (except for page selection, see BookHandler for this).

hierarchy Inheritance Diagram

Inheritance diagram for: TreebookHandler

Inheritance diagram of TreebookHandler

supclasses Known Superclasses

  • persist.persist_handlers.BookHandler

Methods Summary

__init__
GetKind
Restore
Save

API Class API

class TreebookHandler(BookHandler) [source]

Supports saving/restoring open tree branches.

This class handles the following wxPython widgets:

  • wx.Treebook (except for page selection, see BookHandler for this).

__init__(pObject) [source]

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • infobar
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • persist library »
  • persist.persist_handlers »
  • TreebookHandler


TreeCtrlHandler

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • persist library »
  • persist.persist_handlers »
  • TreeCtrlHandler

TreeCtrlHandler

Supports saving/restoring a wx.TreeCtrl expansion state, selections and checked items state (meaningful only for CustomTreeCtrl).

This class handles the following wxPython widgets:

  • wx.TreeCtrl;
  • wx.GenericDirCtrl;
  • CustomTreeCtrl;
  • HyperTreeList;

hierarchy Inheritance Diagram

Inheritance diagram for: TreeCtrlHandler

Inheritance diagram of TreeCtrlHandler

subclasses Known Subclasses

  • persist.persist_handlers.TreeListCtrlHandler

supclasses Known Superclasses

  • persist.persist_handlers.AbstractHandler

Methods Summary

__init__ |
GetCheckedState | Returns a list of checked items.
GetCheckedStateOfChildren | Returns the checked/unchecked state of the children of a tree item.
GetCheckedStateOfItem | Returns the checked/unchecked state of a tree item.
GetExpansionState | Returns list of expanded items.
GetExpansionStateOfChildren | Returns the expansion state of the children of a tree item.
GetExpansionStateOfItem | Returns the expansion state of a tree item.
GetIndexOfItem | Return the index of item.
GetItemChildren | Return the children of item as a list.
GetItemIdentity | Return a hashable object that represents the identity of the item.
GetKind |
GetSelectionState | Returns a list of selected items.
GetSelectionStateOfChildren | Returns the selection state of the children of a tree item.
GetSelectionStateOfItem | Returns the selection state of a tree item.
Restore |
Save |
SetCheckedState | Checks all tree items whose identity, as determined by TreeCtrlHandler.GetItemIdentity(), is present
SetCheckedStateOfChildren | Sets the checked/unchecked state of the children of a tree item.
SetCheckedStateOfItem | Sets the checked/unchecked state of a tree item.
SetExpansionState | Expands all tree items whose identity, as determined by TreeCtrlHandler.GetItemIdentity(),
SetExpansionStateOfChildren | Sets the expansion state of the children of a tree item (expanded or collapsed).
SetExpansionStateOfItem | Sets the expansion state of a tree item (expanded or collapsed).
SetSelectedStateOfChildren | Sets the selection state of the children of a tree item.
SetSelectedStateOfItem | Sets the selection state of a tree item.
SetSelectionState | Selects all tree items whose identity, as determined by TreeCtrlHandler.GetItemIdentity(),

API Class API

class TreeCtrlHandler(AbstractHandler) [source]

Supports saving/restoring a wx.TreeCtrl expansion state, selections and checked items state (meaningful only for CustomTreeCtrl).

This class handles the following wxPython widgets:

  • wx.TreeCtrl;
  • wx.GenericDirCtrl;
  • CustomTreeCtrl;
  • HyperTreeList;

__init__(pObject) [source]

GetCheckedState() [source]

Returns a list of checked items. Checked items are coded as determined by the result of TreeCtrlHandler.GetItemIdentity().

Note

This is meaningful only for CustomTreeCtrl and HyperTreeList.

GetCheckedStateOfChildren(item) [source]

Returns the checked/unchecked state of the children of a tree item.

Parameters: item – a CustomTreeCtrl item.

GetCheckedStateOfItem(item) [source]

Returns the checked/unchecked state of a tree item.

Parameters: item – a CustomTreeCtrl item.

GetExpansionState() [source]

Returns list of expanded items. Expanded items are coded as determined by the result of TreeCtrlHandler.GetItemIdentity().

GetExpansionStateOfChildren(item) [source]

Returns the expansion state of the children of a tree item.

Parameters: item – a wx.TreeCtrl item or a CustomTreeCtrl item.

GetExpansionStateOfItem(item) [source]

Returns the expansion state of a tree item.

Parameters: item – a wx.TreeCtrl item or a CustomTreeCtrl item.

GetIndexOfItem(item) [source]

Return the index of item.

Parameters: item – a wx.TreeCtrl item or a CustomTreeCtrl item;

GetItemChildren(item=None, recursively=False) [source]

Return the children of item as a list.

Parameters:
  • item – a wx.TreeCtrl item or a CustomTreeCtrl item;

  • recursively – whether to recurse into the item hierarchy or not.

GetItemIdentity(item) [source]

Return a hashable object that represents the identity of the item. By default this returns the position of the item in the tree. You may want to override this to return the item label (if you know that labels are unique and don’t change), or return something that represents the underlying domain object, e.g. a database key.

Parameters: item – a wx.TreeCtrl item or a CustomTreeCtrl item;

GetSelectionState() [source]

Returns a list of selected items. Selected items are coded as determined by the result of TreeCtrlHandler.GetItemIdentity().

GetSelectionStateOfChildren(item) [source]

Returns the selection state of the children of a tree item.

Parameters: item – a wx.TreeCtrl item or a CustomTreeCtrl item.

GetSelectionStateOfItem(item) [source]

Returns the selection state of a tree item.

Parameters: item – a wx.TreeCtrl item or a CustomTreeCtrl item.

SetCheckedState(listOfCheckedItems) [source]

Checks all tree items whose identity, as determined by TreeCtrlHandler.GetItemIdentity(), is present in the list and unchecks all other tree items.

Parameters: listOfCheckedItems – a list of checked CustomTreeCtrl items.

Note

This is meaningful only for CustomTreeCtrl and HyperTreeList.

SetCheckedStateOfChildren(listOfCheckedItems, item) [source]

Sets the checked/unchecked state of the children of a tree item.

Parameters:
  • listOfCheckedItems – a list of checked CustomTreeCtrl items;
  • item – a CustomTreeCtrl item.

SetCheckedStateOfItem(listOfCheckedItems, item) [source]

Sets the checked/unchecked state of a tree item.

Parameters:
  • listOfCheckedItems – a list of checked CustomTreeCtrl items;
  • item – a CustomTreeCtrl item.

SetExpansionState(listOfExpandedItems) [source]

Expands all tree items whose identity, as determined by TreeCtrlHandler.GetItemIdentity(), is present in the list and collapses all other tree items.

Parameters: listOfExpandedItems – a list of expanded wx.TreeCtrl or CustomTreeCtrl items.

SetExpansionStateOfChildren(listOfExpandedItems, item) [source]

Sets the expansion state of the children of a tree item (expanded or collapsed).

Parameters:
  • listOfExpandedItems – a list of expanded wx.TreeCtrl or CustomTreeCtrl items;

  • item – a wx.TreeCtrl item or a CustomTreeCtrl item.

SetExpansionStateOfItem(listOfExpandedItems, item) [source]

Sets the expansion state of a tree item (expanded or collapsed).

Parameters:
  • listOfExpandedItems – a list of expanded wx.TreeCtrl or CustomTreeCtrl items;

  • item – a wx.TreeCtrl item or a CustomTreeCtrl item.

SetSelectedStateOfChildren(listOfSelectedItems, item) [source]

Sets the selection state of the children of a tree item.

Parameters:
  • listOfSelectedItems – a list of selected wx.TreeCtrl or CustomTreeCtrl items;

  • item – a wx.TreeCtrl item or a CustomTreeCtrl item.

SetSelectedStateOfItem(listOfSelectedItems, item) [source]

Sets the selection state of a tree item.

Parameters:
  • listOfSelectedItems – a list of selected wx.TreeCtrl or CustomTreeCtrl items;

  • item – a wx.TreeCtrl item or a CustomTreeCtrl item.

SetSelectionState(listOfSelectedItems) [source]

Selects all tree items whose identity, as determined by TreeCtrlHandler.GetItemIdentity(), is present in the list and unselects all other tree items.

Parameters: listOfSelectedItems – a list of selected wx.TreeCtrl or CustomTreeCtrl items.

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • infobar
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • persist library »
  • persist.persist_handlers »
  • TreeCtrlHandler


TreeListCtrlHandler

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • persist library »
  • persist.persist_handlers »
  • TreeListCtrlHandler

TreeListCtrlHandler

Supports saving/restoring a wx.gizmos.TreeListCtrl / HyperTreeList expansion state, selections, column widths and checked items state (meaningful only for HyperTreeList).

This class handles the following wxPython widgets:

  • wx.gizmos.TreeListCtrl;
  • HyperTreeList.

hierarchy Inheritance Diagram

Inheritance diagram for: TreeListCtrlHandler

Inheritance diagram of TreeListCtrlHandler

supclasses Known Superclasses

  • persist.persist_handlers.TreeCtrlHandler

Methods Summary

__init__
GetKind
Restore
Save

API Class API

class TreeListCtrlHandler(TreeCtrlHandler) [source]

Supports saving/restoring a wx.gizmos.TreeListCtrl / HyperTreeList expansion state, selections, column widths and checked items state (meaningful only for HyperTreeList).

This class handles the following wxPython widgets:

  • wx.gizmos.TreeListCtrl;
  • HyperTreeList.

__init__(pObject) [source]

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • infobar
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • persist library »
  • persist.persist_handlers »
  • TreeListCtrlHandler


persist.persist_handlers

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • persist library »
  • persist.persist_handlers

persist.persist_handlers

This module contains different classes which handle different kind of saving/restoring actions depending on the widget kind.

Module author: Andrea Gavana <andrea.gavana@gmail.com>

hierarchy Inheritance Diagram

Inheritance diagram for module: persist.persist_handlers

SVN Revisions

A graphical representation of the SVN commits in the last year.

Click on any date in the picture to jump to that particular revision page, containing information about committers, log messages and SVN diffs.

Revision Graph For persist_handlers

2to3 Python 3 Issues (via 2to3)

No issues have been detected by 2to3.py.

Function Summary

  • CreateFont
  • FindHandler
  • HasCtrlHandler
  • PyDate2wxDate
  • wxDate2PyDate

Class Summary

  • AUIHandler
  • AbstractHandler
  • BookHandler
  • CalendarCtrlHandler
  • CheckBoxHandler
  • CheckListBoxHandler
  • ChoiceComboHandler
  • ChoiceDialogHandler
  • CollapsiblePaneHandler
  • ColourDialogHandler
  • ColourPickerHandler
  • DatePickerHandler
  • FileDirDialogHandler
  • FileDirPickerHandler
  • FileHistoryHandler
  • FindReplaceHandler
  • FoldPanelBarHandler
  • FontDialogHandler
  • FontPickerHandler
  • ListBoxHandler
  • ListCtrlHandler
  • MediaCtrlHandler
  • MenuBarHandler
  • RadioBoxHandler
  • RadioButtonHandler
  • ScrolledWindowHandler
  • SliderHandler
  • SpinHandler
  • SplitterHandler
  • TLWHandler
  • TextCtrlHandler
  • TextEntryHandler
  • ToggleButtonHandler
  • ToolBarHandler
  • TreeCtrlHandler
  • TreeListCtrlHandler
  • TreebookHandler

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • infobar
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • persist library »
  • persist.persist_handlers


PersistenceManager

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • persist library »
  • persist.persistencemanager »
  • PersistenceManager

PersistenceManager

PersistenceManager: global aspects of persistent windows.

Provides support for automatically saving and restoring object properties to persistent storage.

This class is the central element of wxPython persistence framework, see the Persistent Object Overview in the __init__.py file for its overview.

This is a singleton class and its unique instance can be retrieved using Get method.

hierarchy Inheritance Diagram

Inheritance diagram for: PersistenceManager

Inheritance diagram of PersistenceManager

Methods Summary

__init__ | Default class constructor.
AddBadDefaultName | Adds a name to the BAD_DEFAULT_NAMES constant.
DisableRestoring | Globally disables restoring the persistent properties (enabled by default).
DisableSaving | Globally disables saving the persistent properties (enabled by default).
DoRestoreValue | Method used by the persistent objects to restore the data.
DoSaveValue | Method used by the persistent objects to save the data.
EnableRestoring | Globally enables restoring the persistent properties (enabled by default).
EnableSaving | Globally enables saving the persistent properties (enabled by default).
Find | Checks if the object is registered and return the associated PersistentObject
Free | Destructor for the unique persistence manager object.
Get | Accessor to the unique persistence manager object.
GetConfigurationHandler | Returns the persistent configuration handler for PersistenceManager.
GetKey | Returns a correctly formatted key name for the object obj and keyName parameters.
GetManagerStyle | Returns the PersistenceManager style.
GetPersistenceDirectory | Returns a default persistent option directory for PersistenceManager.
GetPersistenceFile | Returns the persistent configuration file for PersistenceManager.
GetPersistenceKey | Returns the persistent key name inside the configuration file for PersistenceManager.
Register | Register an object with the manager.
RegisterAndRestore | Combines both Register and Restore calls.
RegisterAndRestoreAll | Recursively registers and restore the state of the input window and of all of its children.
Restore | Restores the state of an object.
RestoreCtrlValue | Check if we persist the widget value, if so pass it to DoRestoreValue.
RestoreValue | Convenience method, all the action is done in DoRestoreValue.
Save | Saves the state of an object.
SaveAndUnregister | Combines both Save and Unregister calls.
SaveCtrlValue | Check if we persist the widget value, if so pass it to DoSaveValue.
SaveValue | Convenience method, all the action is done in DoSaveValue.
SetConfigurationHandler | Sets the persistent configuration handler for PersistenceManager.
SetManagerStyle | Sets the PersistenceManager style.
SetPersistenceFile | Sets the persistent configuration file for PersistenceManager.
SetPersistenceKey | Sets the persistent key name inside the configuration file for PersistenceManager.
Unregister | Unregister the object, this is called by PersistentObject itself so there is

API Class API

class PersistenceManager(object) [source]

PersistenceManager: global aspects of persistent windows.

Provides support for automatically saving and restoring object properties to persistent storage.

This class is the central element of wxPython persistence framework, see the Persistent Object Overview in the __init__.py file for its overview.

This is a singleton class and its unique instance can be retrieved using PersistenceManager.Get() method.

__init__() [source]

Default class constructor.

This method should not be called directly: you should use the object obtained by PersistenceManager.Get() and assign manager styles, custom configuration files and custom configuration handlers using the appropriate methods in this class.

Interesting attributes you can set for this class are:

  • configFile: the persistent configuration file for PersistenceManager, a custom file name to which wx.FileConfig will access to store and retrieve UI settings;

  • configKey: the persistent key name inside the configuration file for PersistenceManager;

  • customConfigHandler: the persistent configuration handler for PersistenceManager; this attribute is an object capable of saving/restoring UI settings. This can be a cPickle object or a ConfigObj one, for example.

  • style: a combination of the following values:

    Flag name

    Description

    PM_SAVE_RESTORE_AUI_PERSPECTIVES

    If a toplevel window has an AUI manager associated, the manager will save and restore its AUI perspective

    PM_SAVE_RESTORE_TREE_LIST_SELECTIONS

    If set, the manager will save items selections in list and tree controls

    PM_PERSIST_CONTROL_VALUE

    If set, control values will be persisted. This is handy for e.g. applications using a database, where the data (control value) is persisted in the database and persisting it with PM again would only cause confusion.

    PM_DEFAULT_STYLE

    Same as PM_SAVE_RESTORE_AUI_PERSPECTIVES

Note

UI settings are stored as dictionaries key <=> tuple: the tuple value contains two items. The first is the value type (i.e., float, int, bool etc...) while the second is the actual key value.

AddBadDefaultName(name) [source]

Adds a name to the BAD_DEFAULT_NAMES constant.

Parameters: name – a string specifying the control’s default name.

DisableRestoring() [source]

Globally disables restoring the persistent properties (enabled by default).

Note

By default, restoring properties in Restore is enabled but this function allows to disable it. This is mostly useful for testing.

DisableSaving() [source]

Globally disables saving the persistent properties (enabled by default).

Note

By default, saving properties in Save is enabled but the program may wish to disable if, for example, it detects that it is running on a system which shouldn’t be modified in any way and so configuration file (or Windows registry) shouldn’t be written to.

DoRestoreValue(obj, keyName) [source]

Method used by the persistent objects to restore the data.

By default this method simply use wx.FileConfig but this behaviour may be overridden by passing a custom config handler in the PersistenceManager constructor.

Parameters:
  • obj – an instance of PersistentObject;
  • keyName – a string specifying the key name.

DoSaveValue(obj, keyName, value) [source]

Method used by the persistent objects to save the data.

By default this method simply use wx.FileConfig but this behaviour may be overridden by passing a custom configuration handler in the PersistenceManager constructor.

Parameters:
  • obj – an instance of PersistentObject;
  • keyName – a string specifying the key name;
  • value – the value to store in the configuration file.

EnableRestoring() [source]

Globally enables restoring the persistent properties (enabled by default).

Note

By default, restoring properties in Restore is enabled but this function allows to disable it. This is mostly useful for testing.

EnableSaving() [source]

Globally enables saving the persistent properties (enabled by default).

Note

By default, saving properties in Save is enabled but the program may wish to disable if, for example, it detects that it is running on a system which shouldn’t be modified in any way and so configuration file (or Windows registry) shouldn’t be written to.

Find(window) [source]

Checks if the object is registered and return the associated PersistentObject if it is or None otherwise.

Parameters: window – an instance of wx.Window.

classmethod Free() [source]

Destructor for the unique persistence manager object.

classmethod Get() [source]

Accessor to the unique persistence manager object.

GetConfigurationHandler() [source]

Returns the persistent configuration handler for PersistenceManager.

GetKey(obj, keyName) [source]

Returns a correctly formatted key name for the object obj and keyName parameters.

Parameters:
  • obj – an instance of PersistentObject;
  • keyName – a string specifying the key name.

GetManagerStyle() [source]

Returns the PersistenceManager style.

See also

SetManagerStyle for a list of possible styles.

GetPersistenceDirectory() [source]

Returns a default persistent option directory for PersistenceManager.

Note

The return value of this method is not used if you are using your own custom configuration handler (i.e., by using ConfigObj/ConfigParser/cPickle etc...) or if you have specified a custom configuration file to use with wx.FileConfig.

GetPersistenceFile() [source]

Returns the persistent configuration file for PersistenceManager.

Note

The return value of this method is not used if you are using your own custom configuration handler (i.e., by using ConfigObj/ConfigParser/cPickle etc...).

GetPersistenceKey() [source]

Returns the persistent key name inside the configuration file for PersistenceManager.

Note

The return value of this method is not used if you are using your own custom configuration handler (i.e., by using ConfigObj/ConfigParser/cPickle etc...).

Register(window, persistenceHandler=None) [source]

Register an object with the manager.

Parameters:
  • window – an instance of wx.Window;

  • persistenceHandler – if not None, this should a custom handler derived from AbstractHandler.

Note

Note that registering the object doesn’t do anything except allowing to call Restore for it later. If you want to register the object and restore its properties, use RegisterAndRestore.

Note

The manager takes ownership of the PersistentObject and will delete it when it is unregistered.

RegisterAndRestore(window) [source]

Combines both Register and Restore calls.

Parameters: window – an instance of wx.Window.

RegisterAndRestoreAll(window, children=None) [source]

Recursively registers and restore the state of the input window and of all of its children.

Parameters:
  • window – an instance of wx.Window;

  • children – list of children of the input window, on first call it is equal to None.

Restore(window) [source]

Restores the state of an object.

Parameters: window – an instance of wx.Window.
Returns: True if the object properties were restored or False if nothing was found to restore or the saved settings were invalid.

Note

This methods does nothing if DisableRestoring was called.

RestoreCtrlValue(obj, keyName) [source]

Check if we persist the widget value, if so pass it to DoRestoreValue.

Parameters:
  • obj – an instance of PersistentObject;
  • keyName – a string specifying the key name.

RestoreValue(obj, keyName) [source]

Convenience method, all the action is done in DoRestoreValue.

Parameters:
  • obj – an instance of PersistentObject;
  • keyName – a string specifying the key name.

Save(window) [source]

Saves the state of an object.

Parameters: window – an instance of wx.Window.

Note

This methods does nothing if DisableSaving was called.

SaveAndUnregister(window=None) [source]

Combines both Save and Unregister calls.

Parameters: window – an instance of wx.Window. If it is None, all the windows previously registered are saved and then unregistered.

SaveCtrlValue(obj, keyName, value) [source]

Check if we persist the widget value, if so pass it to DoSaveValue.

Parameters:
  • obj – an instance of PersistentObject;
  • keyName – a string specifying the key name;
  • value – the value to store in the configuration file.

SaveValue(obj, keyName, value) [source]

Convenience method, all the action is done in DoSaveValue.

Parameters:
  • obj – an instance of PersistentObject;
  • keyName – a string specifying the key name;
  • value – the value to store in the configuration file.

SetConfigurationHandler(handler) [source]

Sets the persistent configuration handler for PersistenceManager.

Parameters: handler – an object capable of saving/restoring UI settings. This can be a cPickle object or a ConfigObj one, for example.

Note

UI settings are stored as dictionaries key <=> tuple: the tuple value contains two items. The first is the value type (i.e., float, int, bool etc...) while the second is the actual key value.

SetManagerStyle(style) [source]

Sets the PersistenceManager style.

Parameters: style – a combination of the following values:

Flag name | Description
PM_SAVE_RESTORE_AUI_PERSPECTIVES | If a toplevel window has an AUI manager associated, the manager will save and restore its AUI perspective
PM_SAVE_RESTORE_TREE_LIST_SELECTIONS | If set, the manager will save items selections in list and tree controls
PM_PERSIST_CONTROL_VALUE | If set, control values will be persisted. This is handy for e.g. applications using a database, where the data (control value) is persisted in the database and persisting it with PM again would only cause confusion.
PM_DEFAULT_STYLE | Same as PM_SAVE_RESTORE_AUI_PERSPECTIVES.

SetPersistenceFile(fileName) [source]

Sets the persistent configuration file for PersistenceManager.

Parameters: fileName – the file name where to store the persistent options.

Note

Calling this method has no influence if you are using your own custom configuration handler (i.e., by using ConfigObj/ConfigParser/cPickle etc...).

SetPersistenceKey(key) [source]

Sets the persistent key name inside the configuration file for PersistenceManager.

Parameters: key – a short meaningful name for your unique preferences key.

Note

Calling this method has no influence if you are using your own custom configuration handler (i.e., by using ConfigObj/ConfigParser/cPickle etc...).

Unregister(window) [source]

Unregister the object, this is called by PersistentObject itself so there is usually no need to do it explicitly.

Parameters: window – an instance of wx.Window, which must have been previously registered with Register.

Note

For the persistent windows this is done automatically (via SaveAndUnregister) when the window is destroyed so you only need to call this function explicitly if you are using custom persistent objects or if you want to prevent the object properties from being saved.

Note

This deletes the associated PersistentObject.

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • infobar
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • persist library »
  • persist.persistencemanager »
  • PersistenceManager


PersistentObject

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • persist library »
  • persist.persistencemanager »
  • PersistentObject

PersistentObject

PersistentObject: ABC for anything persistent.

This is the base class for persistent object adapters. wxPython persistence framework is non-intrusive, i.e. can work with the classes which have no relationship to nor knowledge of it. To allow this, an intermediate persistence adapter is used: this is just a simple object which provides the methods used by PersistenceManager to save and restore the object properties and implements them using the concrete class methods.

You may derive your own classes from PersistentObject to implement persistence support for your common classes, see Defining Custom Persistent Windows in the __init__.py file.

hierarchy Inheritance Diagram

Inheritance diagram for: PersistentObject

Inheritance diagram of PersistentObject

Methods Summary

__init__ | Default class constructor.
GetKind | Returns the string uniquely identifying the objects supported by this adapter.
GetName | Returns the string uniquely identifying the window we’re associated with among all the other objects of the same type.
GetWindow | Returns the actual associated window.
Restore | Restores the corresponding window settings.
RestoreCtrlValue | Restore the value saved by SaveCtrlValue, should be used only for
RestoreValue | Restore the value saved by SaveValue.
Save | Saves the corresponding window settings.
SaveCtrlValue | Save the specified value using the given name, should be used only for controls data value.
SaveValue | Save the specified value using the given name.

API Class API

class PersistentObject(object) [source]

PersistentObject: ABC for anything persistent.

This is the base class for persistent object adapters. wxPython persistence framework is non-intrusive, i.e. can work with the classes which have no relationship to nor knowledge of it. To allow this, an intermediate persistence adapter is used: this is just a simple object which provides the methods used by PersistenceManager to save and restore the object properties and implements them using the concrete class methods.

You may derive your own classes from PersistentObject to implement persistence support for your common classes, see Defining Custom Persistent Windows in the __init__.py file.

__init__(window, persistenceHandler=None) [source]

Default class constructor.

Parameters:
  • window – an instance of wx.Window;
  • persistenceHandler – if not None, this should a custom handler derived from AbstractHandler.

GetKind() [source]

Returns the string uniquely identifying the objects supported by this adapter.

Note

This method is called from SaveValue and RestoreValue and normally returns some short (but not too cryptic) strings, e.g. “Checkbox”.

GetName() [source]

Returns the string uniquely identifying the window we’re associated with among all the other objects of the same type.

Note

This method is used together with GetKind to construct the unique full name of the object in e.g. a configuration file.

GetWindow() [source]

Returns the actual associated window.

Restore() [source]

Restores the corresponding window settings.

Note

This method shouldn’t be used directly as it doesn’t respect the global PersistenceManager.DisableRestoring() settings, use PersistenceManager methods with the same name instead.

RestoreCtrlValue(name) [source]

Restore the value saved by SaveCtrlValue, should be used only for controls data value.

Parameters: name – the same name as was used by SaveCtrlValue.
Returns: True if the value was successfully read or False if it was not found or an error occurred.

RestoreValue(name) [source]

Restore the value saved by SaveValue.

Parameters: name – the same name as was used by SaveValue.
Returns: True if the value was successfully read or False if it was not found or an error occurred.

Save() [source]

Saves the corresponding window settings.

Note

This method shouldn’t be used directly as it doesn’t respect the global PersistenceManager.DisableSaving() settings, use PersistenceManager methods with the same name instead.

SaveCtrlValue(name, value) [source]

Save the specified value using the given name, should be used only for controls data value.

Parameters:
  • name – the name of the value in the configuration file;
  • value – the value to save.
Returns:

True if the value was saved or False if an error occurred.

SaveValue(name, value) [source]

Save the specified value using the given name.

Parameters:
  • name – the name of the value in the configuration file;
  • value – the value to save.
Returns:

True if the value was saved or False if an error occurred.

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • infobar
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • persist library »
  • persist.persistencemanager »
  • PersistentObject


persist.persistencemanager

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • persist library »
  • persist.persistencemanager

persist.persistencemanager

This module contains the definitions of PersistentObject and PersistenceManager objects.

Module author: Andrea Gavana <andrea.gavana@gmail.com>

hierarchy Inheritance Diagram

Inheritance diagram for module: persist.persistencemanager

Inheritance diagram of persist.persistencemanager.PersistenceManager, persist.persistencemanager.PersistentObject

SVN Revisions

A graphical representation of the SVN commits in the last year.

Click on any date in the picture to jump to that particular revision page, containing information about committers, log messages and SVN diffs.

Revision Graph For persistencemanager

2to3 Python 3 Issues (via 2to3)

No issues have been detected by 2to3.py.

Class Summary

  • PersistenceManager
  • PersistentObject

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • infobar
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • persist library »
  • persist.persistencemanager


SVN Revision 69550 For persist_handlers

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • persist library »
  • persist.persist_handlers »
  • SVN Revision 69550 For persist_handlers

svn SVN Revision 69550 For persist_handlers

This file contains the SVN revision history for persist_handlers, at revision 69550.

Available information include commit date, the name of the committer, the file size, the SVN log messages and a diff from the previous version (if available).

File Information

  • Commit Date: 01-Nov-2011 19:42:21 UTC
  • Committer: AG
  • File Size: 74120 byte(s)

Log Messages

The following log message was entered by the committer:

PersistentControls: Still trying to remove the garbage TortoiseSVN has put in...

Diff To Previous Version (Unavailable)

Version SVN diff:

No diff available.

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • persist library »
  • persist.persist_handlers »
  • SVN Revision 69550 For persist_handlers


SVN Revision 69627 For persist_handlers

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • persist library »
  • persist.persist_handlers »
  • SVN Revision 69627 For persist_handlers

svn SVN Revision 69627 For persist_handlers

This file contains the SVN revision history for persist_handlers, at revision 69627.

Available information include commit date, the name of the committer, the file size, the SVN log messages and a diff from the previous version (if available).

File Information

  • Commit Date: 26-Oct-2011 18:51:45 UTC
  • Committer: AG
  • File Size: 74140 byte(s)

Log Messages

The following log message was entered by the committer:

  • AuiManager: fix the assertion error in the demo;
  • Others: minor fixes to the docstrings.

Diff To Previous Version (69550)

Version SVN diff:

--- wxPython/3rdParty/AGW/agw/persist/persist_handlers.py   2011/10/26 18:51:45     69550
+++ wxPython/3rdParty/AGW/agw/persist/persist_handlers.py   2011/11/01 19:42:21     69627
@@ -1344,7 +1344,9 @@
Returns a list of checked items. Checked items are coded as determined by
the result of L{TreeCtrlHandler.GetItemIdentity}.

-        :note: This is meaningful only for L{customtreectrl.CustomTreeCtrl} and
+        :note:
+
+         This is meaningful only for L{customtreectrl.CustomTreeCtrl} and
L{hypertreelist.HyperTreeList}.
"""

@@ -1364,7 +1366,9 @@

:param `listOfCheckedItems`: a list of checked L{customtreectrl.CustomTreeCtrl} items.

-        :note: This is meaningful only for L{customtreectrl.CustomTreeCtrl} and
+        :note:
+
+         This is meaningful only for L{customtreectrl.CustomTreeCtrl} and
L{hypertreelist.HyperTreeList}.
"""

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • persist library »
  • persist.persist_handlers »
  • SVN Revision 69627 For persist_handlers


SVN Revision 69550 For persistencemanager

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • persist library »
  • persist.persistencemanager »
  • SVN Revision 69550 For persistencemanager

svn SVN Revision 69550 For persistencemanager

This file contains the SVN revision history for persistencemanager, at revision 69550.

Available information include commit date, the name of the committer, the file size, the SVN log messages and a diff from the previous version (if available).

File Information

  • Commit Date: 01-Nov-2011 19:42:21 UTC
  • Committer: AG
  • File Size: 26313 byte(s)

Log Messages

The following log message was entered by the committer:

PersistentControls: Still trying to remove the garbage TortoiseSVN has put in...

Diff To Previous Version (Unavailable)

Version SVN diff:

No diff available.

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • persist library »
  • persist.persistencemanager »
  • SVN Revision 69550 For persistencemanager


SVN Revision 69627 For persistencemanager

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • persist library »
  • persist.persistencemanager »
  • SVN Revision 69627 For persistencemanager

svn SVN Revision 69627 For persistencemanager

This file contains the SVN revision history for persistencemanager, at revision 69627.

Available information include commit date, the name of the committer, the file size, the SVN log messages and a diff from the previous version (if available).

File Information

  • Commit Date: 26-Oct-2011 18:51:45 UTC
  • Committer: AG
  • File Size: 26333 byte(s)

Log Messages

The following log message was entered by the committer:

  • AuiManager: fix the assertion error in the demo;
  • Others: minor fixes to the docstrings.

Diff To Previous Version (69550)

Version SVN diff:

--- wxPython/3rdParty/AGW/agw/persist/persistencemanager.py 2011/10/26 18:51:45     69550
+++ wxPython/3rdParty/AGW/agw/persist/persistencemanager.py 2011/11/01 19:42:21     69627
@@ -440,9 +440,12 @@
:param `persistenceHandler`: if not ``None``, this should a custom handler derived
from L{persist_handlers.AbstractHandler}.

-        :note: Note that registering the object doesn't do anything except allowing to call
+        :note:
+
+         Note that registering the object doesn't do anything except allowing to call
L{Restore} for it later. If you want to register the object and restore its
properties, use L{RegisterAndRestore}.
+

:note: The manager takes ownership of the L{PersistentObject} and will delete it when
it is unregistered.

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • persist library »
  • persist.persistencemanager »
  • SVN Revision 69627 For persistencemanager


PieCtrl

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • piectrl »
  • PieCtrl

PieCtrl

PieCtrl is somewhat a “static” control, that you may create in order to display a simple pie chart on a wx.Panel or similar.

hierarchy Inheritance Diagram

Inheritance diagram for: PieCtrl

Inheritance diagram of PieCtrl

subclasses Known Subclasses

  • piectrl.ProgressPie

appearance Control Appearance

PieCtrl

Methods Summary

__init__ | Default class constructor.
Draw | Draws all the sectors of PieCtrl.
DrawParts | Draws the PieCtrl external edges.
GetAngle | Returns the orientation angle for PieCtrl, in radians.
GetBackColour | Returns the PieCtrl background colour.
GetBackground | Returns the PieCtrl background image.
GetHeight | Returns the height (in pixels) of the PieCtrl.
GetLegend | Returns the PieCtrl legend.
GetPartAngles | Returns the angles associated to all segments.
GetRotationAngle | Returns the angle at which the first sector starts, in radians.
GetShowEdges | Returns whether the PieCtrl edges are visible or not.
OnPaint | Handles the wx.EVT_PAINT event for PieCtrl.
OnSize | Handles the wx.EVT_SIZE event for PieCtrl.
RecreateCanvas | Recreates the PieCtrl container (canvas).
SetAngle | Sets the orientation angle for PieCtrl.
SetBackColour | Sets the PieCtrl background colour.
SetBackground | Sets the PieCtrl background image.
SetHeight | Sets the height (in pixels) of the PieCtrl.
SetRotationAngle | Sets the angle at which the first sector starts.
SetShowEdges | Sets whether the PieCtrl edges are visible or not.

API Class API

class PieCtrl(wx.Window) [source]

PieCtrl is somewhat a “static” control, that you may create in order to display a simple pie chart on a wx.Panel or similar.

__init__(parent, id=wx.ID_ANY, pos=wx.DefaultPosition, size=wx.DefaultSize, style=0, name="PieCtrl") [source]

Default class constructor.

Parameters:
  • parent – the PieCtrl parent. Must not be None;
  • id – window identifier. A value of -1 indicates a default value;
  • pos – the control position. A value of (-1, -1) indicates a default position, chosen by either the windowing system or wxPython, depending on platform;
  • size – the control size. A value of (-1, -1) indicates a default size, chosen by either the windowing system or wxPython, depending on platform;
  • style – the window style (unused);
  • name – the window name.

Draw(pdc) [source]

Draws all the sectors of PieCtrl.

Parameters: dc – an instance of wx.DC.

DrawParts(dc, cx, cy, w, h) [source]

Draws the PieCtrl external edges.

Parameters:
  • dc – an instance of wx.DC;

  • cx – the part x coordinate;
  • cy – the part y coordinate;
  • w – the control’s width;
  • h – the control’s height.

GetAngle() [source]

Returns the orientation angle for PieCtrl, in radians.

GetBackColour() [source]

Returns the PieCtrl background colour.

GetBackground() [source]

Returns the PieCtrl background image.

GetHeight() [source]

Returns the height (in pixels) of the PieCtrl.

GetLegend() [source]

Returns the PieCtrl legend.

GetPartAngles() [source]

Returns the angles associated to all segments.

GetRotationAngle() [source]

Returns the angle at which the first sector starts, in radians.

GetShowEdges() [source]

Returns whether the PieCtrl edges are visible or not.

OnPaint(event) [source]

Handles the wx.EVT_PAINT event for PieCtrl.

Parameters: event – a wx.PaintEvent event to be processed.

OnSize(event) [source]

Handles the wx.EVT_SIZE event for PieCtrl.

Parameters: event – a wx.SizeEvent event to be processed.

RecreateCanvas() [source]

Recreates the PieCtrl container (canvas).

SetAngle(angle) [source]

Sets the orientation angle for PieCtrl.

Parameters: angle – the orientation angle for PieCtrl, in radians.

SetBackColour(colour) [source]

Sets the PieCtrl background colour.

Parameters: colour – a valid wx.Colour object.

SetBackground(bmp) [source]

Sets the PieCtrl background image.

Parameters: bmp – a valid wx.Bitmap object.

SetHeight(value) [source]

Sets the height (in pixels) of the PieCtrl.

Parameters: value – the new height of the widget, in pixels.

SetRotationAngle(angle) [source]

Sets the angle at which the first sector starts.

Parameters: angle – the first sector angle, in radians.

SetShowEdges(value=True) [source]

Sets whether the PieCtrl edges are visible or not.

Parameters: value – True to show the edges, False to hide them.

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • infobar
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • piectrl »
  • PieCtrl


PieCtrlLegend

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • piectrl »
  • PieCtrlLegend

PieCtrlLegend

This class displays a legend window for the classic PieCtrl.

hierarchy Inheritance Diagram

Inheritance diagram for: PieCtrlLegend

Inheritance diagram of PieCtrlLegend

Methods Summary

__init__ | Default class constructor.
GetBackColour | Returns the legend background colour.
GetHorizontalBorder | Returns the legend’s horizontal border, in pixels.
GetLabelColour | Returns the legend label colour.
GetLabelFont | Returns the legend label font.
GetVerticalBorder | Returns the legend’s vertical border, in pixels.
IsTransparent | Returns whether the legend background is transparent or not.
OnPaint | Handles the wx.EVT_PAINT event for PieCtrlLegend.
RecreateBackground | Recreates the legend background.
SetBackColour | Sets the legend background colour.
SetHorizontalBorder | Sets the legend’s horizontal border.
SetLabelColour | Sets the legend label colour.
SetLabelFont | Sets the legend label font.
SetTransparent | Toggles the legend transparency (visibility).
SetVerticalBorder | Sets the legend’s vertical border.

API Class API

class PieCtrlLegend(wx.Window) [source]

This class displays a legend window for the classic PieCtrl.

__init__(parent, title, id=wx.ID_ANY, pos=wx.DefaultPosition, size=wx.DefaultSize, style=0) [source]

Default class constructor.

Parameters:
  • parent – the PieCtrlLegend parent;
  • title – the legend title;
  • id – window identifier. A value of -1 indicates a default value;
  • pos – the control position. A value of (-1, -1) indicates a default position, chosen by either the windowing system or wxPython, depending on platform;
  • size – the control size. A value of (-1, -1) indicates a default size, chosen by either the windowing system or wxPython, depending on platform;
  • style – the window style (unused).

GetBackColour() [source]

Returns the legend background colour.

GetHorizontalBorder() [source]

Returns the legend’s horizontal border, in pixels.

GetLabelColour() [source]

Returns the legend label colour.

GetLabelFont() [source]

Returns the legend label font.

GetVerticalBorder() [source]

Returns the legend’s vertical border, in pixels.

IsTransparent() [source]

Returns whether the legend background is transparent or not.

OnPaint(event) [source]

Handles the wx.EVT_PAINT event for PieCtrlLegend.

Parameters: event – a wx.PaintEvent event to be processed.

RecreateBackground(parentdc) [source]

Recreates the legend background.

Parameters: parentdc – an instance of wx.DC.

SetBackColour(colour) [source]

Sets the legend background colour.

Parameters: colour – a valid wx.Colour object.

SetHorizontalBorder(value) [source]

Sets the legend’s horizontal border.

Parameters: value – the horizontal border thickness, in pixels.

SetLabelColour(colour) [source]

Sets the legend label colour.

Parameters: colour – a valid wx.Colour object.

SetLabelFont(font) [source]

Sets the legend label font.

Parameters: font – a valid wx.Font object.

SetTransparent(value=False) [source]

Toggles the legend transparency (visibility).

Parameters: value – True to set the legend as transparent, False otherwise.

SetVerticalBorder(value) [source]

Sets the legend’s vertical border.

Parameters: value – the horizontal border thickness, in pixels.

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • infobar
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • piectrl »
  • PieCtrlLegend


PiePart

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • piectrl »
  • PiePart

PiePart

This class handles the legend segments properties, such as value, colour and label.

hierarchy Inheritance Diagram

Inheritance diagram for: PiePart

Inheritance diagram of PiePart

Methods Summary

__init__ | Default class constructor.
GetColour | Returns the segment colour.
GetLabel | Returns the segment label.
GetValue | Returns the segment absolute value.
SetColour | Sets the segment colour.
SetLabel | Sets the segment label.
SetValue | Sets the segment absolute value.

API Class API

class PiePart(object) [source]

This class handles the legend segments properties, such as value, colour and label.

__init__(value=0, colour=wx.BLACK, label="") [source]

Default class constructor.

Parameters:
  • value – the pie part value;
  • colour – the pie part colour;
  • label – the pie part text label.

GetColour() [source]

Returns the segment colour.

GetLabel() [source]

Returns the segment label.

GetValue() [source]

Returns the segment absolute value.

SetColour(colour) [source]

Sets the segment colour.

Parameters: colour – a valid wx.Colour object.

SetLabel(label) [source]

Sets the segment label.

Parameters: label – the pie part text label.

SetValue(value) [source]

Sets the segment absolute value.

Parameters: value – a floating point number representing the PiePart value.

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • infobar
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • piectrl »
  • PiePart


ProgressPie

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • piectrl »
  • ProgressPie

ProgressPie

ProgressPie tries to emulate the behavior of wx.ProgressDialog, but using a pie chart instead of a gauge.

hierarchy Inheritance Diagram

Inheritance diagram for: ProgressPie

Inheritance diagram of ProgressPie

supclasses Known Superclasses

  • piectrl.PieCtrl

appearance Control Appearance

ProgressPie

Methods Summary

__init__ | Default class constructor.
GetFilledColour | Returns the colour that progressively fills the ProgressPie.
GetMaxValue | Returns the ProgressPie maximum value.
GetUnfilledColour | Returns the colour that is filled.
GetValue | Returns the ProgressPie value.
SetFilledColour | Sets the colour that progressively fills the ProgressPie .
SetMaxValue | Sets the ProgressPie maximum value.
SetUnfilledColour | Sets the colour that is filled.
SetValue | Sets the ProgressPie value.

API Class API

class ProgressPie(PieCtrl) [source]

ProgressPie tries to emulate the behavior of wx.ProgressDialog, but using a pie chart instead of a gauge.

__init__(parent, maxvalue, value, id=wx.ID_ANY, pos=wx.DefaultPosition, size=wx.DefaultSize, style=0) [source]

Default class constructor.

Parameters:
  • parent – the PieCtrl parent. Must not be None;
  • id – window identifier. A value of -1 indicates a default value;
  • pos – the control position. A value of (-1, -1) indicates a default position, chosen by either the windowing system or wxPython, depending on platform;
  • size – the control size. A value of (-1, -1) indicates a default size, chosen by either the windowing system or wxPython, depending on platform;
  • style – the window style (unused);
  • name – the window name.

GetFilledColour() [source]

Returns the colour that progressively fills the ProgressPie.

GetMaxValue() [source]

Returns the ProgressPie maximum value.

GetUnfilledColour() [source]

Returns the colour that is filled.

GetValue() [source]

Returns the ProgressPie value.

SetFilledColour(colour) [source]

Sets the colour that progressively fills the ProgressPie .

Parameters: colour – a valid wx.Colour object.

SetMaxValue(value) [source]

Sets the ProgressPie maximum value.

Parameters: value – a floating point number representing the maximum value.

SetUnfilledColour(colour) [source]

Sets the colour that is filled.

Parameters: colour – a valid wx.Colour object.

SetValue(value) [source]

Sets the ProgressPie value.

Parameters: value – a floating point number representing the new value.

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • infobar
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • piectrl »
  • ProgressPie


SVN Revision 68362 For piectrl

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • piectrl »
  • SVN Revision 68362 For piectrl

svn SVN Revision 68362 For piectrl

This file contains the SVN revision history for piectrl, at revision 68362.

Available information include commit date, the name of the committer, the file size, the SVN log messages and a diff from the previous version (if available).

File Information

  • Commit Date: 17-Oct-2008 20:51:43 UTC
  • Committer: AG
  • File Size: 27152 byte(s)

Log Messages

The following log message was entered by the committer:

  • All of AGW: change my work e-mail from KPO to Maersk Oil (silly commit)

Diff To Previous Version (65377)

Version SVN diff:

--- wxPython/3rdParty/AGW/agw/piectrl.py    2010/08/21 20:27:02     65377
+++ wxPython/3rdParty/AGW/agw/piectrl.py    2011/07/24 21:36:47     68362
@@ -18,7 +18,7 @@
# Write To Me At:
#
# andrea.gavana@gmail.com
-# gavana@kpo.kz
+# andrea.gavana@maerskoil.com
#
# Or, Obviously, To The wxPython Mailing List!!!
#

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • piectrl »
  • SVN Revision 68362 For piectrl


SVN Revision 68881 For piectrl

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • piectrl »
  • SVN Revision 68881 For piectrl

svn SVN Revision 68881 For piectrl

This file contains the SVN revision history for piectrl, at revision 68881.

Available information include commit date, the name of the committer, the file size, the SVN log messages and a diff from the previous version (if available).

File Information

  • Commit Date: 17-Oct-2008 19:15:31 UTC
  • Committer: AG
  • File Size: 27970 byte(s)

Log Messages

The following log message was entered by the committer:

  • AGW: General overhaul of the documentation, much improved. All the widgets have their own sample usage in the docs as well;

  • FlatNotebook: Added the FNB_NAV_BUTTONS_WHEN_NEEDED style, which hides the navigation left/right arrows if all tabs fit;

  • RibbonBar: - Added the EVT_RIBBONBAR_TAB_LEFT_DCLICK event, which generates a special event

    when a ribbon bar tab is double-clicked;

    • Added support for toggle buttons;
    • Improved support for ribbon panel sizers: panels with sizers should now automatically minimise at small sizes, and behave properly when popping up from a minimised state;
    • Added tooltips via SetToolTip for those buttons which have the help_string attribute set.

  • XLSGrid: a new widget was added to AGW, termed XLSGrid. It’s based on wx.grid.Grid and can be used to faithfully reproduce the appearance of a Microsoft Excel spreadsheets.

Diff To Previous Version (68362)

Version SVN diff:

--- wxPython/3rdParty/AGW/agw/piectrl.py    2011/07/24 21:36:47     68362
+++ wxPython/3rdParty/AGW/agw/piectrl.py    2011/08/25 16:40:17     68881
@@ -3,7 +3,7 @@
# Python Code By:
#
# Andrea Gavana, @ 31 Oct 2005
-# Latest Revision: 30 Nov 2009, 17.00 GMT
+# Latest Revision: 17 Aug 2011, 15.00 GMT
#
#
# TODO List/Caveats
@@ -28,73 +28,100 @@

"""
-PieCtrl/ProgressPie are simple classes that reproduce the behavior of a pie
+L{PieCtrl} and L{ProgressPie} are simple classes that reproduce the behavior of a pie
chart.

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

-PieCtrl/ProgressPie are simple classes that reproduce the behavior of a pie
+L{PieCtrl} and L{ProgressPie} are simple classes that reproduce the behavior of a pie
chart. They use only pure wxPython classes/methods, without external dependencies.
-PieCtrl is somewhat a "static" control, that you may create in order to display
-a simple pie chart on a `wx.Panel` or similar. ProgressPie tries to emulate the
+L{PieCtrl} is somewhat a "static" control, that you may create in order to display
+a simple pie chart on a `wx.Panel` or similar. L{ProgressPie} tries to emulate the
behavior of `wx.ProgressDialog`, but using a pie chart instead of a gauge.

Usage
=====

-An example of use of PieCtrl is as follows::
+Usage example::

-    # create a simple PieCtrl with 3 sectors
-    mypie = PieCtrl(panel, -1, wx.DefaultPosition, wx.Size(180,270))
+    import wx
+    import wx.lib.agw.piectrl as PC

-    part = PiePart()
+    class MyFrame(wx.Frame):

-    part.SetLabel("serieslabel_1")
-    part.SetValue(300)
-    part.SetColour(wx.Colour(200, 50, 50))
-    mypie._series.append(part)
+        def __init__(self, parent):
+
+            wx.Frame.__init__(self, parent, -1, "PieCtrl Demo")

-    part = PiePart()
+            panel = wx.Panel(self)
+
+            # create a simple PieCtrl with 3 sectors
+            mypie = PC.PieCtrl(panel, -1, wx.DefaultPosition, wx.Size(180,270))
+
+            part = PC.PiePart()
+
+            part.SetLabel("Label 1")
+            part.SetValue(300)
+            part.SetColour(wx.Colour(200, 50, 50))
+            mypie._series.append(part)
+
+            part = PC.PiePart()
+
+            part.SetLabel("Label 2")
+            part.SetValue(200)
+            part.SetColour(wx.Colour(50, 200, 50))
+            mypie._series.append(part)
+
+            part = PC.PiePart()
+
+            part.SetLabel("helloworld label 3")
+            part.SetValue(50)
+            part.SetColour(wx.Colour(50, 50, 200))
+            mypie._series.append(part)
+
+            # create a ProgressPie
+            progress_pie = PC.ProgressPie(panel, 100, 50, -1, wx.DefaultPosition,
+                                          wx.Size(180, 200), wx.SIMPLE_BORDER)
+
+            progress_pie.SetBackColour(wx.Colour(150, 200, 255))
+            progress_pie.SetFilledcolour(wx.Colour(255, 0, 0))
+            progress_pie.SetUnfilledColour(wx.WHITE)
+            progress_pie.SetHeight(20)
+
+            main_sizer = wx.BoxSizer(wx.HORIZONTAL)

-    part.SetLabel("series label 2")
-    part.SetValue(200)
-    part.SetColour(wx.Colour(50, 200, 50))
-    mypie._series.append(part)
+            main_sizer.Add(mypie, 1, wx.EXPAND | wx.ALL, 5)
+            main_sizer.Add(progress_pie, 1, wx.EXPAND | wx.ALL, 5)

-    part = PiePart()
+            panel.SetSizer(main_sizer)
+            main_sizer.Layout()

-    part.SetLabel("helloworld label 3")
-    part.SetValue(50)
-    part.SetColour(wx.Colour(50, 50, 200))
-    mypie._series.append(part)

+    # our normal wxApp-derived class, as usual

-An example of use of ProgressPie is as follows::
+    app = wx.PySimpleApp()

-    # create a progresspie
-    MyProgressPie = ProgressPie(panel, 100, 50, -1, wx.DefaultPosition,
-                                wx.Size(180, 200), wx.SIMPLE_BORDER)
+    frame = MyFrame(None)
+    app.SetTopWindow(frame)
+    frame.Show()

-    MyProgressPie.SetBackColour(wx.Colour(150, 200, 255))
-    myprogresspie.SetFilledcolour(wx.Colour(255, 0, 0))
-    MyProgressPie.SetUnfilledColour(wx.WHITE)
-    MyProgressPie.SetHeight(20)
+    app.MainLoop()

Methods and Settings
====================

-With PieCtrl you can:
+With L{PieCtrl} you can:

-- Create a PieCtrl with different sectors;
+- Create a L{PieCtrl} with different sectors;
- Set the sector values, colours and labels;
-- Assign a legend to the PieCtrl;
-- Use an image as the PieCtrl background;
-- Change the vertical rotation (perspective) of the PieCtrl;
+- Assign a legend to the L{PieCtrl};
+- Use an image as the L{PieCtrl} background;
+- Change the vertical rotation (perspective) of the L{PieCtrl};
- Show/hide the segment edges.

@@ -113,9 +140,9 @@
License And Version
===================

-PieCtrl is distributed under the wxPython license.
+L{PieCtrl} is distributed under the wxPython license.

-Latest revision: Andrea Gavana @ 30 Nov 2009, 17.00 GMT
+Latest revision: Andrea Gavana @ 17 Aug 2011, 15.00 GMT

Version 0.2

@@ -424,7 +451,7 @@

class PieCtrl(wx.Window):
"""
-    PieCtrl is somewhat a "static" control, that you may create in order to display
+    L{PieCtrl} is somewhat a "static" control, that you may create in order to display
a simple pie chart on a `wx.Panel` or similar.
"""

@@ -847,7 +874,7 @@

class ProgressPie(PieCtrl):
"""
-    ProgressPie tries to emulate the behavior of `wx.ProgressDialog`, but
+    L{ProgressPie} tries to emulate the behavior of `wx.ProgressDialog`, but
using a pie chart instead of a gauge.
"""

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • piectrl »
  • SVN Revision 68881 For piectrl


PyBusyInfo

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • pybusyinfo »
  • PyBusyInfo

PyBusyInfo

Constructs a busy info window as child of parent and displays a message in it.

hierarchy Inheritance Diagram

Inheritance diagram for: PyBusyInfo

Inheritance diagram of PyBusyInfo

appearance Control Appearance

PyBusyInfo

Methods Summary

__init__ | Default class constructor.
__del__ | Overloaded method, for compatibility with wxWidgets.

API Class API

class PyBusyInfo(object) [source]

Constructs a busy info window as child of parent and displays a message in it.

__init__(message, parent=None, title=_("Busy"), icon=wx.NullBitmap) [source]

Default class constructor.

Parameters:
  • parent – the PyBusyInfo parent;
  • message – the message to display in the PyBusyInfo;
  • title – the main PyBusyInfo title;
  • icon – an icon to draw as the frame icon, an instance of wx.Bitmap.

Note

If parent is not None you must ensure that it is not closed while the busy info is shown.

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • infobar
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • pybusyinfo »
  • PyBusyInfo


PyInfoFrame

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • pybusyinfo »
  • PyInfoFrame

PyInfoFrame

Base class for PyBusyInfo.

hierarchy Inheritance Diagram

Inheritance diagram for: PyInfoFrame

Inheritance diagram of PyInfoFrame

Methods Summary

__init__ | Default class constructor.
OnErase | Handles the wx.EVT_ERASE_BACKGROUND event for PyInfoFrame.
OnPaint | Handles the wx.EVT_PAINT event for PyInfoFrame.
SetBusyShape | Sets PyInfoFrame shape using the region created from the bitmap.

API Class API

class PyInfoFrame(wx.Frame) [source]

Base class for PyBusyInfo.

__init__(parent, message, title, icon) [source]

Default class constructor.

Parameters:
  • parent – the frame parent;
  • message – the message to display in the PyBusyInfo;
  • title – the main PyBusyInfo title;
  • icon – an icon to draw as the frame icon, an instance of wx.Bitmap.

OnErase(event) [source]

Handles the wx.EVT_ERASE_BACKGROUND event for PyInfoFrame.

Parameters: event – a wx.EraseEvent event to be processed.

Note

This method is intentionally empty to reduce flicker.

OnPaint(event) [source]

Handles the wx.EVT_PAINT event for PyInfoFrame.

Parameters: event – a wx.PaintEvent to be processed.

SetBusyShape(event=None) [source]

Sets PyInfoFrame shape using the region created from the bitmap.

Parameters: event – a wx.WindowCreateEvent event (GTK only, as GTK supports setting the window shape only during window creation).

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • infobar
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • pybusyinfo »
  • PyInfoFrame


SVN Revision 68881 For pybusyinfo

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • pybusyinfo »
  • SVN Revision 68881 For pybusyinfo

svn SVN Revision 68881 For pybusyinfo

This file contains the SVN revision history for pybusyinfo, at revision 68881.

Available information include commit date, the name of the committer, the file size, the SVN log messages and a diff from the previous version (if available).

File Information

  • Commit Date: 11-Dec-2009 11:51:15 UTC
  • Committer: AG
  • File Size: 8102 byte(s)

Log Messages

The following log message was entered by the committer:

  • AGW: General overhaul of the documentation, much improved. All the widgets have their own sample usage in the docs as well;

  • FlatNotebook: Added the FNB_NAV_BUTTONS_WHEN_NEEDED style, which hides the navigation left/right arrows if all tabs fit;

  • RibbonBar: - Added the EVT_RIBBONBAR_TAB_LEFT_DCLICK event, which generates a special event

    when a ribbon bar tab is double-clicked;

    • Added support for toggle buttons;
    • Improved support for ribbon panel sizers: panels with sizers should now automatically minimise at small sizes, and behave properly when popping up from a minimised state;
    • Added tooltips via SetToolTip for those buttons which have the help_string attribute set.

  • XLSGrid: a new widget was added to AGW, termed XLSGrid. It’s based on wx.grid.Grid and can be used to faithfully reproduce the appearance of a Microsoft Excel spreadsheets.

Diff To Previous Version (63107)

Version SVN diff:

--- wxPython/3rdParty/AGW/agw/pybusyinfo.py 2010/01/09 21:39:59     63107
+++ wxPython/3rdParty/AGW/agw/pybusyinfo.py 2011/08/25 16:40:17     68881
@@ -1,14 +1,14 @@
"""
-PyBusyInfo constructs a busy info window and displays a message in it.
+L{PyBusyInfo} constructs a busy info window and displays a message in it.

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

-PyBusyInfo constructs a busy info window and displays a message in it.
+L{PyBusyInfo} constructs a busy info window and displays a message in it.

This class makes it easy to tell your user that the program is temporarily busy.
-Just create a PyBusyInfo object, and within the current scope, a message window
+Just create a L{PyBusyInfo} object, and within the current scope, a message window
will be shown.

For example::
@@ -26,10 +26,55 @@
it had been obscured by other windows, for example).

+Usage
+=====
+
+Usage example::
+
+    import wx
+    import wx.lib.agw.pybusyinfo as PBI
+
+    class MyFrame(wx.Frame):
+
+        def __init__(self, parent):
+
+            wx.Frame.__init__(self, parent, -1, "PyBusyInfo Demo")
+
+            panel = wx.Panel(self)
+
+            b = wx.Button(panel, -1, "Test PyBusyInfo ", (50,50))
+            self.Bind(wx.EVT_BUTTON, self.OnButton, b)
+
+
+        def OnButton(self, event):
+
+            message = "Please wait 5 seconds, working..."
+            busy = PBI.PyBusyInfo(message, parent=self, title="Really Busy")
+
+            wx.Yield()
+
+            for indx in xrange(5):
+                wx.MilliSleep(1000)
+
+            del busy
+
+
+    # our normal wxApp-derived class, as usual
+
+    app = wx.PySimpleApp()
+
+    frame = MyFrame(None)
+    app.SetTopWindow(frame)
+    frame.Show()
+
+    app.MainLoop()
+
+
+
Supported Platforms
===================

-PyBusyInfo has been tested on the following platforms:
+L{PyBusyInfo} has been tested on the following platforms:
* Windows (Windows XP).

@@ -48,7 +93,7 @@
License And Version
===================

-PyBusyInfo is distributed under the wxPython license.
+L{PyBusyInfo} is distributed under the wxPython license.

Latest Revision: Andrea Gavana @ 03 Dec 2009, 09.00 GMT

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • pybusyinfo »
  • SVN Revision 68881 For pybusyinfo


SVN Revision 68933 For pybusyinfo

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • pybusyinfo »
  • SVN Revision 68933 For pybusyinfo

svn SVN Revision 68933 For pybusyinfo

This file contains the SVN revision history for pybusyinfo, at revision 68933.

Available information include commit date, the name of the committer, the file size, the SVN log messages and a diff from the previous version (if available).

File Information

  • Commit Date: 10-Dec-2009 18:09:38 UTC
  • Committer: AG
  • File Size: 8102 byte(s)

Log Messages

The following log message was entered by the committer:

AGW: Some further refactoring of the docs: - Added downloadable snippets of code in the Sphinx documentation itself; - Re-run 2to3 afresh so that the patches are up-to-date for Python 3.

Diff To Previous Version (68881)

Version SVN diff:

--- wxPython/3rdParty/AGW/agw/pybusyinfo.py 2011/08/25 16:40:17     68881
+++ wxPython/3rdParty/AGW/agw/pybusyinfo.py 2011/08/27 17:11:41     68933
@@ -95,7 +95,7 @@

L{PyBusyInfo} is distributed under the wxPython license.

-Latest Revision: Andrea Gavana @ 03 Dec 2009, 09.00 GMT
+Latest Revision: Andrea Gavana @ 17 Aug 2011, 15.00 GMT

Version 0.1

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • pybusyinfo »
  • SVN Revision 68933 For pybusyinfo


GTKExpander

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • pycollapsiblepane »
  • GTKExpander

GTKExpander

A GTKExpander allows the user to hide or show its child by clicking on an expander triangle.

hierarchy Inheritance Diagram

Inheritance diagram for: GTKExpander

Inheritance diagram of GTKExpander

Methods Summary

__init__ | Default class constructor.
DoGetBestSize | Gets the size which best suits the window: for a control, it would be the
OnDrawGTKExpander | Draws the GTKExpander triangle.
OnDrawGTKText | Draws the GTKExpander text label.
OnSize | Handles the wx.EVT_SIZE event for GTKExpander.

API Class API

class GTKExpander(wx.PyControl) [source]

A GTKExpander allows the user to hide or show its child by clicking on an expander triangle.

__init__(parent, id=wx.ID_ANY, label="", pos=wx.DefaultPosition, size=wx.DefaultSize, style=wx.NO_BORDER) [source]

Default class constructor.

Parameters:
  • parent – the GTKExpander parent. Must not be None;
  • id – window identifier. A value of -1 indicates a default value;
  • label – the expander text label;
  • pos – the control position. A value of (-1, -1) indicates a default position, chosen by either the windowing system or wxPython, depending on platform;
  • size – the control size. A value of (-1, -1) indicates a default size, chosen by either the windowing system or wxPython, depending on platform;
  • style – the expander style.

DoGetBestSize() [source]

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

Note

Overridden from wx.PyControl.

OnDrawGTKExpander(dc) [source]

Draws the GTKExpander triangle.

Parameters: dc – an instance of wx.DC.

OnDrawGTKText(dc) [source]

Draws the GTKExpander text label.

Parameters: dc – an instance of wx.DC.

OnSize(event) [source]

Handles the wx.EVT_SIZE event for GTKExpander.

Parameters: event – a wx.SizeEvent event to be processed.

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • infobar
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • pycollapsiblepane »
  • GTKExpander


PyCollapsiblePane

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • pycollapsiblepane »
  • PyCollapsiblePane

PyCollapsiblePane

PyCollapsiblePane is a container with an embedded button-like control which can be used by the user to collapse or expand the pane’s contents.

hierarchy Inheritance Diagram

Inheritance diagram for: PyCollapsiblePane

Inheritance diagram of PyCollapsiblePane

appearance Control Appearance

PyCollapsiblePane

Methods Summary

__init__ | Default class constructor.
Collapse | Collapses or expands the pane window.
DoGetBestSize | Gets the size which best suits the window: for a control, it would be the
Expand | Same as Collapse (False).
GetAGWWindowStyleFlag | Returns the PyCollapsiblePane window style.
GetBorder | Returns the PyCollapsiblePane border in pixels (platform dependent).
GetBtnLabel | Returns the button label.
GetButton | Returns the button associated with PyCollapsiblePane.
GetButtonFont | Returns the button font.
GetExpanderDimensions | Returns the expander dimensions, a tuple of integers representing the
GetLabel | Returns the button label.
GetPane | Returns a reference to the pane window.
HasAGWFlag | Returns whether a flag is present in the PyCollapsiblePane style.
IsCollapsed | Returns True if the pane window is currently hidden.
IsExpanded | Returns True if the pane window is currently shown.
Layout | Layout the PyCollapsiblePane.
OnButton | Handles the wx.EVT_BUTTON event for PyCollapsiblePane.
OnDrawGTKExpander | Overridable method to draw the GTK-style expander.
OnDrawGTKStyle | Handles the wx.EVT_PAINT event for PyCollapsiblePane.
OnDrawGTKText | Overridable method to draw the PyCollapsiblePane text in the expander.
OnSize | Handles the wx.EVT_SIZE event for PyCollapsiblePane.
OnStateChange | Handles the status changes (collapsing/expanding).
SetAGWWindowStyleFlag | Sets the PyCollapsiblePane window style flags.
SetButton | Assign a new button to PyCollapsiblePane.
SetButtonFont | Sets the button font.
SetExpanderDimensions | Sets the expander width and height.
SetLabel | Sets the button label.

API Class API

class PyCollapsiblePane(wx.PyPanel) [source]

PyCollapsiblePane is a container with an embedded button-like control which can be used by the user to collapse or expand the pane’s contents.

__init__(parent, id=wx.ID_ANY, label="", pos=wx.DefaultPosition, size=wx.DefaultSize, style=0, agwStyle=wx.CP_DEFAULT_STYLE, validator=wx.DefaultValidator, name="PyCollapsiblePane") [source]

Default class constructor.

Parameters:
  • parent – the PyCollapsiblePane parent. Must not be None;
  • id – window identifier. A value of -1 indicates a default value;
  • label – The initial label shown in the button which allows the user to expand or collapse the pane window.
  • pos – the control position. A value of (-1, -1) indicates a default position, chosen by either the windowing system or wxPython, depending on platform;
  • size – the control size. A value of (-1, -1) indicates a default size, chosen by either the windowing system or wxPython, depending on platform;
  • style – the underlying wx.PyPanel window style;
  • agwStyle – the AGW-specifi window style. This can be a combination of the following bits:

    Window Styles | Hex Value | Description
    CP_NO_TLW_RESIZE | 0x2 | By default PyCollapsiblePane resizes the top level window containing it when its own size changes. This allows to easily implement dialogs containing an optionally shown part, for example, and so is the default behaviour but can be inconvenient in some specific cases – use this flag to disable this automatic parent resizing then.
    CP_GTK_EXPANDER | 0x4 | Uses a GTK expander instead of a button.
    CP_USE_STATICBOX | 0x8 | Uses a wx.StaticBox around PyCollapsiblePane.
    CP_LINE_ABOVE | 0x10 | Draws a line above PyCollapsiblePane.
  • validator – the validator associated to the PyCollapsiblePane;
  • name – the widget name.

Collapse(collapse=True) [source]

Collapses or expands the pane window.

Parameters: collapse – True to collapse the pane window, False to expand it.

DoGetBestSize() [source]

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

Note

Overridden from wx.PyPanel.

Expand() [source]

Same as Collapse (False).

GetAGWWindowStyleFlag() [source]

Returns the PyCollapsiblePane window style.

See also

SetAGWWindowStyleFlag for a list of possible window style flags.

GetBorder() [source]

Returns the PyCollapsiblePane border in pixels (platform dependent).

GetBtnLabel() [source]

Returns the button label.

GetButton() [source]

Returns the button associated with PyCollapsiblePane.

GetButtonFont() [source]

Returns the button font.

GetExpanderDimensions() [source]

Returns the expander dimensions, a tuple of integers representing the width and height of the expander, in pixels.

GetLabel() [source]

Returns the button label.

Note

Overridden from wx.PyPanel.

GetPane() [source]

Returns a reference to the pane window. Use the returned wx.Window as the parent of widgets to make them part of the collapsible area.

HasAGWFlag(flag) [source]

Returns whether a flag is present in the PyCollapsiblePane style.

Parameters: flag – one of the possible PyCollapsiblePane window styles.

See also

SetAGWWindowStyleFlag for a list of possible window style flags.

IsCollapsed() [source]

Returns True if the pane window is currently hidden.

IsExpanded() [source]

Returns True if the pane window is currently shown.

Layout() [source]

Layout the PyCollapsiblePane.

OnButton(event) [source]

Handles the wx.EVT_BUTTON event for PyCollapsiblePane.

Parameters: event – a wx.CommandEvent event to be processed.

OnDrawGTKExpander(dc) [source]

Overridable method to draw the GTK-style expander.

Parameters: dc – an instance of wx.DC.

OnDrawGTKStyle(event) [source]

Handles the wx.EVT_PAINT event for PyCollapsiblePane.

Parameters: event – a wx.PaintEvent event to be processed.

Note

This is a drawing routine to paint the GTK-style expander.

OnDrawGTKText(dc) [source]

Overridable method to draw the PyCollapsiblePane text in the expander.

Parameters: dc – an instance of wx.DC.

OnSize(event) [source]

Handles the wx.EVT_SIZE event for PyCollapsiblePane.

Parameters: event – a wx.SizeEvent event to be processed.

OnStateChange(sz) [source]

Handles the status changes (collapsing/expanding).

Parameters: sz – an instance of wx.Size.

SetAGWWindowStyleFlag(agwStyle) [source]

Sets the PyCollapsiblePane window style flags.

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

Window Styles | Hex Value | Description
CP_NO_TLW_RESIZE | 0x2 | By default PyCollapsiblePane resizes the top level window containing it when its own size changes. This allows to easily implement dialogs containing an optionally shown part, for example, and so is the default behaviour but can be inconvenient in some specific cases – use this flag to disable this automatic parent resizing then.
CP_GTK_EXPANDER | 0x4 | Uses a GTK expander instead of a button.
CP_USE_STATICBOX | 0x8 | Uses a wx.StaticBox around PyCollapsiblePane.
CP_LINE_ABOVE | 0x10 | Draws a line above PyCollapsiblePane.

SetButton(button) [source]

Assign a new button to PyCollapsiblePane.

Parameters: button – can be the standard wx.Button or any of the generic implementations which live in wx.lib.buttons.

SetButtonFont(font) [source]

Sets the button font.

Parameters: font – a valid wx.Font object.

SetExpanderDimensions(width, height) [source]

Sets the expander width and height.

Parameters:
  • width – an integer specifying the expander width in pixels;
  • height – an integer specifying the expander height in pixels.

SetLabel(label) [source]

Sets the button label.

Parameters: label – the new button label.

Note

Overridden from wx.PyPanel.

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • infobar
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • pycollapsiblepane »
  • PyCollapsiblePane


SVN Revision 68362 For pycollapsiblepane

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • pycollapsiblepane »
  • SVN Revision 68362 For pycollapsiblepane

svn SVN Revision 68362 For pycollapsiblepane

This file contains the SVN revision history for pycollapsiblepane, at revision 68362.

Available information include commit date, the name of the committer, the file size, the SVN log messages and a diff from the previous version (if available).

File Information

  • Commit Date: 08-Apr-2009 04:09:23 UTC
  • Committer: AG
  • File Size: 29359 byte(s)

Log Messages

The following log message was entered by the committer:

  • All of AGW: change my work e-mail from KPO to Maersk Oil (silly commit)

Diff To Previous Version (65607)

Version SVN diff:

--- wxPython/3rdParty/AGW/agw/pycollapsiblepane.py  2010/09/23 18:27:32     65607
+++ wxPython/3rdParty/AGW/agw/pycollapsiblepane.py  2011/07/24 21:36:47     68362
@@ -9,7 +9,7 @@
# For All Kind Of Problems, Requests Of Enhancements And Bug Reports, Please
# Write To Me At:
#
-# gavana@kpo.kz
+# andrea.gavana@maerskoil.com
# andrea.gavana@gmail.com
#
# Or, Obviously, To The wxPython Mailing List!!!

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • pycollapsiblepane »
  • SVN Revision 68362 For pycollapsiblepane


SVN Revision 68453 For pycollapsiblepane

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • pycollapsiblepane »
  • SVN Revision 68453 For pycollapsiblepane

svn SVN Revision 68453 For pycollapsiblepane

This file contains the SVN revision history for pycollapsiblepane, at revision 68453.

Available information include commit date, the name of the committer, the file size, the SVN log messages and a diff from the previous version (if available).

File Information

  • Commit Date: 17-Oct-2008 21:01:24 UTC
  • Committer: RD
  • File Size: 29418 byte(s)

Log Messages

The following log message was entered by the committer:

Ensure that self and self._pButton still exist before trying to use them in a call-after function.

Diff To Previous Version (68362)

Version SVN diff:

--- wxPython/3rdParty/AGW/agw/pycollapsiblepane.py  2011/07/24 21:36:47     68362
+++ wxPython/3rdParty/AGW/agw/pycollapsiblepane.py  2011/07/29 17:27:11     68453
@@ -314,8 +314,9 @@
# others.
def paint(evt):
def updateBtn():
-                        self._pButton.Refresh()
-                        self._pButton.Update()
+                        if self and self._pButton:
+                            self._pButton.Refresh()
+                            self._pButton.Update()
wx.CallAfter(updateBtn)
evt.Skip()
self._pStaticBox.Bind(wx.EVT_PAINT, paint)

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • pycollapsiblepane »
  • SVN Revision 68453 For pycollapsiblepane


SVN Revision 68881 For pycollapsiblepane

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • pycollapsiblepane »
  • SVN Revision 68881 For pycollapsiblepane

svn SVN Revision 68881 For pycollapsiblepane

This file contains the SVN revision history for pycollapsiblepane, at revision 68881.

Available information include commit date, the name of the committer, the file size, the SVN log messages and a diff from the previous version (if available).

File Information

  • Commit Date: 17-Oct-2008 19:15:31 UTC
  • Committer: AG
  • File Size: 31713 byte(s)

Log Messages

The following log message was entered by the committer:

  • AGW: General overhaul of the documentation, much improved. All the widgets have their own sample usage in the docs as well;

  • FlatNotebook: Added the FNB_NAV_BUTTONS_WHEN_NEEDED style, which hides the navigation left/right arrows if all tabs fit;

  • RibbonBar: - Added the EVT_RIBBONBAR_TAB_LEFT_DCLICK event, which generates a special event

    when a ribbon bar tab is double-clicked;

    • Added support for toggle buttons;
    • Improved support for ribbon panel sizers: panels with sizers should now automatically minimise at small sizes, and behave properly when popping up from a minimised state;
    • Added tooltips via SetToolTip for those buttons which have the help_string attribute set.

  • XLSGrid: a new widget was added to AGW, termed XLSGrid. It’s based on wx.grid.Grid and can be used to faithfully reproduce the appearance of a Microsoft Excel spreadsheets.

Diff To Previous Version (68453)

Version SVN diff:

--- wxPython/3rdParty/AGW/agw/pycollapsiblepane.py  2011/07/29 17:27:11     68453
+++ wxPython/3rdParty/AGW/agw/pycollapsiblepane.py  2011/08/25 16:40:17     68881
@@ -3,7 +3,7 @@
# Generic Implementation Based On wx.CollapsiblePane.
#
# Andrea Gavana, @ 09 Aug 2007
-# Latest Revision: 12 Apr 2010, 12.00 GMT
+# Latest Revision: 17 Aug 2011, 15.00 GMT
#
#
# For All Kind Of Problems, Requests Of Enhancements And Bug Reports, Please
@@ -19,7 +19,7 @@
# --------------------------------------------------------------------------------- #

"""
-PyCollapsiblePane is a container with an embedded button-like control which
+L{PyCollapsiblePane} is a container with an embedded button-like control which
can be used by the user to collapse or expand the pane's contents.

@@ -30,11 +30,11 @@
can be used by the user to collapse or expand the pane's contents.
Once constructed you should use the L{GetPane} function to access the pane and
add your controls inside it (i.e. use the window returned from L{GetPane} as the
-parent for the controls which must go in the pane, **not** the PyCollapsiblePane
+parent for the controls which must go in the pane, **not** the L{PyCollapsiblePane}
itself!).

:note: Note that because of its nature of control which can dynamically (and drastically)
- change its size at run-time under user-input, when putting PyCollapsiblePane
+ change its size at run-time under user-input, when putting L{PyCollapsiblePane}
inside a `wx.Sizer` you should be careful to add it with a proportion value of zero;
this is because otherwise all other windows with non-null proportion values would
automatically get resized each time the user expands or collapse the pane window
@@ -44,19 +44,85 @@
Usage
=====

-A simple example::
+Usage example::

-    collpane = PyCollapsiblePane(self, -1, "Details:")
+    import wx
+    import wx.lib.agw.pycollapsiblepane as PCP

-    # add the pane with a zero proportion value to the 'sz' sizer which contains it
-    sz.Add(collpane, 0, wx.GROW|wx.ALL, 5)
+    class MyFrame(wx.Frame):

-    # now add a test label in the collapsible pane using a sizer to layout it:
-    win = collpane.GetPane()
-    paneSz = wx.BoxSizer(wx.VERTICAL)
-    paneSz.Add(wx.StaticText(win, -1, "test!"), 1, wx.GROW|wx.ALL, 2)
-    win.SetSizer(paneSz)
-    paneSz.SetSizeHints(win)
+        def __init__(self, parent):
+
+            wx.Frame.__init__(self, parent, -1, "PyCollapsiblePane Demo")
+
+            panel = wx.Panel(self)
+
+            title = wx.StaticText(panel, label="PyCollapsiblePane")
+            title.SetFont(wx.Font(18, wx.SWISS, wx.NORMAL, wx.BOLD))
+            title.SetForegroundColour("blue")
+
+            self.cp = cp = PCP.PyCollapsiblePane(panel, label=label1,
+                                                 style=wx.CP_DEFAULT_STYLE|wx.CP_NO_TLW_RESIZE)
+
+            self.MakePaneContent(cp.GetPane())
+
+            sizer = wx.BoxSizer(wx.VERTICAL)
+            sizer.Add(title, 0, wx.ALL, 25)
+            sizer.Add(cp, 0, wx.RIGHT|wx.LEFT|wx.EXPAND, 25)
+
+            panel.SetSizer(sizer)
+            sizer.Layout()
+
+
+        def MakePaneContent(self, pane):
+            ''' Just makes a few controls to put on `PyCollapsiblePane`. '''
+
+            nameLbl = wx.StaticText(pane, -1, "Name:")
+            name = wx.TextCtrl(pane, -1, "");
+
+            addrLbl = wx.StaticText(pane, -1, "Address:")
+            addr1 = wx.TextCtrl(pane, -1, "");
+            addr2 = wx.TextCtrl(pane, -1, "");
+
+            cstLbl = wx.StaticText(pane, -1, "City, State, Zip:")
+            city  = wx.TextCtrl(pane, -1, "", size=(150,-1));
+            state = wx.TextCtrl(pane, -1, "", size=(50,-1));
+            zip   = wx.TextCtrl(pane, -1, "", size=(70,-1));
+
+            addrSizer = wx.FlexGridSizer(cols=2, hgap=5, vgap=5)
+            addrSizer.AddGrowableCol(1)
+            addrSizer.Add(nameLbl, 0,
+                          wx.ALIGN_RIGHT|wx.ALIGN_CENTER_VERTICAL)
+            addrSizer.Add(name, 0, wx.EXPAND)
+            addrSizer.Add(addrLbl, 0,
+                          wx.ALIGN_RIGHT|wx.ALIGN_CENTER_VERTICAL)
+            addrSizer.Add(addr1, 0, wx.EXPAND)
+            addrSizer.Add((5,5))
+            addrSizer.Add(addr2, 0, wx.EXPAND)
+
+            addrSizer.Add(cstLbl, 0,
+                          wx.ALIGN_RIGHT|wx.ALIGN_CENTER_VERTICAL)
+
+            cstSizer = wx.BoxSizer(wx.HORIZONTAL)
+            cstSizer.Add(city, 1)
+            cstSizer.Add(state, 0, wx.LEFT|wx.RIGHT, 5)
+            cstSizer.Add(zip)
+            addrSizer.Add(cstSizer, 0, wx.EXPAND)
+
+            border = wx.BoxSizer()
+            border.Add(addrSizer, 1, wx.EXPAND|wx.ALL, 5)
+            pane.SetSizer(border)
+
+
+    # our normal wxApp-derived class, as usual
+
+    app = wx.PySimpleApp()
+
+    frame = MyFrame(None)
+    app.SetTopWindow(frame)
+    frame.Show()
+
+    app.MainLoop()

@@ -68,10 +134,10 @@
==================== =========== ==================================================
Window Styles        Hex Value   Description
==================== =========== ==================================================
-``CP_NO_TLW_RESIZE``         0x2 By default `PyCollapsiblePane` resizes the top level window containing it when its own size changes. This allows to easily implement dialogs containing an optionally shown part, for example, and so is the default behaviour but can be inconvenient in some specific cases -- use this flag to disable this automatic parent resizing then.
+``CP_NO_TLW_RESIZE``         0x2 By default L{PyCollapsiblePane} resizes the top level window containing it when its own size changes. This allows to easily implement dialogs containing an optionally shown part, for example, and so is the default behaviour but can be inconvenient in some specific cases -- use this flag to disable this automatic parent resizing then.
``CP_GTK_EXPANDER``          0x4 Uses a GTK expander instead of a button.
-``CP_USE_STATICBOX``         0x8 Uses a `wx.StaticBox` around `PyCollapsiblePane`.
-``CP_LINE_ABOVE``           0x10 Draws a line above `PyCollapsiblePane`.
+``CP_USE_STATICBOX``         0x8 Uses a `wx.StaticBox` around L{PyCollapsiblePane}.
+``CP_LINE_ABOVE``           0x10 Draws a line above L{PyCollapsiblePane}.
==================== =========== ==================================================

@@ -90,9 +156,9 @@
License And Version
===================

-PyCollapsiblePane is distributed under the wxPython license.
+L{PyCollapsiblePane} is distributed under the wxPython license.

-Latest Revision: Andrea Gavana @ 12 Apr 2010, 12.00 GMT
+Latest Revision: Andrea Gavana @ 17 Aug 2011, 15.00 GMT

Version 0.4

@@ -103,13 +169,13 @@
CP_GTK_EXPANDER = 4
""" Uses a GTK expander instead of a button. """
CP_USE_STATICBOX = 8
-""" Uses a `wx.StaticBox` around `PyCollapsiblePane`. """
+""" Uses a `wx.StaticBox` around L{PyCollapsiblePane}. """
CP_LINE_ABOVE = 16
-""" Draws a line above `PyCollapsiblePane`. """
+""" Draws a line above L{PyCollapsiblePane}. """
CP_DEFAULT_STYLE = wx.CP_DEFAULT_STYLE
""" The default style. It includes ``wx.TAB_TRAVERSAL`` and ``wx.BORDER_NONE``. """
CP_NO_TLW_RESIZE = wx.CP_NO_TLW_RESIZE
-""" By default `PyCollapsiblePane` resizes the top level window containing it when its""" \
+""" By default L{PyCollapsiblePane} resizes the top level window containing it when its""" \
""" own size changes. This allows to easily implement dialogs containing an optionally""" \
""" shown part, for example, and so is the default behaviour but can be inconvenient""" \
""" in some specific cases -- use this flag to disable this automatic parent resizing then. """
@@ -136,7 +202,7 @@

class GTKExpander(wx.PyControl):
"""
-    A GtkExpander allows the user to hide or show its child by clicking on an expander
+    A L{GTKExpander} allows the user to hide or show its child by clicking on an expander
triangle.
"""

@@ -216,6 +282,8 @@
Gets the size which best suits the window: for a control, it would be the
minimal size which doesn't truncate the control, for a panel - the same size
as it would have after a call to `Fit()`.
+
+        :note: Overridden from `wx.PyControl`.
"""

triangleWidth, triangleHeight = self._parent.GetExpanderDimensions()
@@ -246,13 +314,13 @@

class PyCollapsiblePane(wx.PyPanel):
"""
-    PyCollapsiblePane is a container with an embedded button-like control which
+    L{PyCollapsiblePane} is a container with an embedded button-like control which
can be used by the user to collapse or expand the pane's contents.
"""

def __init__(self, parent, id=wx.ID_ANY, label="", pos=wx.DefaultPosition,
-                 size=wx.DefaultSize, style=wx.CP_DEFAULT_STYLE, agwStyle=0,
-                 validator=wx.DefaultValidator, name="CollapsiblePane"):
+                 size=wx.DefaultSize, style=0, agwStyle=wx.CP_DEFAULT_STYLE,
+                 validator=wx.DefaultValidator, name="PyCollapsiblePane"):
"""
Default class constructor.

@@ -264,7 +332,7 @@
chosen by either the windowing system or wxPython, depending on platform;
:param `size`: the control size. A value of (-1, -1) indicates a default size,
chosen by either the windowing system or wxPython, depending on platform;
-        :param `style`: the underlying `wx.PyControl` window style;
+        :param `style`: the underlying `wx.PyPanel` window style;
:param `agwStyle`: the AGW-specifi window style. This can be a combination of the
following bits:

@@ -530,7 +598,7 @@

:param `label`: the new button label.

-        :note: Overridden from `wx.PyControl`.
+        :note: Overridden from `wx.PyPanel`.
"""

self._strLabel =  label
@@ -545,7 +613,7 @@
"""
Returns the button label.

-        :note: Overridden from `wx.PyControl`.
+        :note: Overridden from `wx.PyPanel`.
"""

return self._strLabel
@@ -610,6 +678,8 @@
Gets the size which best suits the window: for a control, it would be the
minimal size which doesn't truncate the control, for a panel - the same size
as it would have after a call to `Fit()`.
+
+        :note: Overridden from `wx.PyPanel`.
"""

if self.HasAGWFlag(CP_USE_STATICBOX):

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • pycollapsiblepane »
  • SVN Revision 68881 For pycollapsiblepane


PyGauge

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • pygauge »
  • PyGauge

PyGauge

This class provides a visual alternative for wx.Gauge. It currently only support determinate mode (see SetValue and SetRange)

hierarchy Inheritance Diagram

Inheritance diagram for: PyGauge

Inheritance diagram of PyGauge

appearance Control Appearance

PyGauge

Methods Summary

__init__ | Default class constructor.
DoGetBestSize | Gets the size which best suits PyGauge: for a control, it would be
GetBarColor | Returns the PyGauge main bar colour.
GetBarColour | Returns the PyGauge main bar colour.
GetBarGradient | Returns a tuple containing the gradient start and end colours.
GetBorderColor | Returns the PyGauge border colour.
GetBorderColour | Returns the PyGauge border colour.
GetBorderPadding | Gets the border padding.
GetRange | Returns the maximum value of the gauge.
GetValue | Returns the current position of the gauge.
OnEraseBackground | Handles the wx.EVT_ERASE_BACKGROUND event for PyGauge.
OnPaint | Handles the wx.EVT_PAINT event for PyGauge.
OnTimer | Handles the wx.EVT_TIMER event for PyGauge.
SetBarColor | Sets the PyGauge main bar colour.
SetBarColour | Sets the PyGauge main bar colour.
SetBarGradient | Sets the bar gradient.
SetBorderColor | Sets the PyGauge border colour.
SetBorderColour | Sets the PyGauge border colour.
SetBorderPadding | Sets the border padding.
SetRange | Sets the range of the gauge.
SetValue | Sets the current position of the gauge.
SortForDisplay | Internal method which sorts things so we draw the longest bar first.
Update | Update the gauge by adding value to it over time milliseconds.

API Class API

class PyGauge(wx.PyWindow) [source]

This class provides a visual alternative for wx.Gauge. It currently only support determinate mode (see PyGauge.SetValue() and PyGauge.SetRange())

__init__(parent, id=wx.ID_ANY, range=100, pos=wx.DefaultPosition, size=(-1, 30), style=0) [source]

Default class constructor.

Parameters:
  • parent – parent window. Must not be None;
  • id – window identifier. A value of -1 indicates a default value;
  • pos – the control position. A value of (-1, -1) indicates a default position, chosen by either the windowing system or wxPython, depending on platform;
  • size – the control size. A value of (-1, -1) indicates a default size, chosen by either the windowing system or wxPython, depending on platform;
  • style – the underlying wx.PyWindow window style.

DoGetBestSize() [source]

Gets the size which best suits PyGauge: for a control, it would be the minimal size which doesn’t truncate the control, for a panel - the same size as it would have after a call to Fit().

Note

Overridden from wx.PyWindow.

GetBarColor()

Returns the PyGauge main bar colour.

GetBarColour() [source]

Returns the PyGauge main bar colour.

GetBarGradient() [source]

Returns a tuple containing the gradient start and end colours.

GetBorderColor()

Returns the PyGauge border colour.

GetBorderColour() [source]

Returns the PyGauge border colour.

GetBorderPadding() [source]

Gets the border padding.

GetRange() [source]

Returns the maximum value of the gauge.

GetValue() [source]

Returns the current position of the gauge.

OnEraseBackground(event) [source]

Handles the wx.EVT_ERASE_BACKGROUND event for PyGauge.

Parameters: event – a wx.EraseEvent event to be processed.

Note

This method is intentionally empty to reduce flicker.

OnPaint(event) [source]

Handles the wx.EVT_PAINT event for PyGauge.

Parameters: event – a wx.PaintEvent event to be processed.

OnTimer(event) [source]

Handles the wx.EVT_TIMER event for PyGauge.

Parameters: event – a wx.TimerEvent event to be processed.

SetBarColor(colour)

Sets the PyGauge main bar colour.

Parameters: colour – an instance of wx.Colour.

SetBarColour(colour) [source]

Sets the PyGauge main bar colour.

Parameters: colour – an instance of wx.Colour.

SetBarGradient(gradient) [source]

Sets the bar gradient.

Parameters: gradient – a tuple containing the gradient start and end colours.

Note

This overrides the bar colour previously set with SetBarColour.

SetBorderColor(colour)

Sets the PyGauge border colour.

Parameters: colour – an instance of wx.Colour.

SetBorderColour(colour) [source]

Sets the PyGauge border colour.

Parameters: colour – an instance of wx.Colour.

SetBorderPadding(padding) [source]

Sets the border padding.

Parameters: padding – pixels between the border and the progress bar.

SetRange(range) [source]

Sets the range of the gauge. The gauge length is its value as a proportion of the range.

Parameters: range – The maximum value of the gauge.

SetValue(value) [source]

Sets the current position of the gauge.

Parameters: value – an integer specifying the current position of the gauge.

SortForDisplay() [source]

Internal method which sorts things so we draw the longest bar first.

Update(value, time=0) [source]

Update the gauge by adding value to it over time milliseconds. The time parameter must be a multiple of 50 milliseconds.

Parameters:
  • value – The value to be added to the gauge;
  • time – The length of time in milliseconds that it will take to move the gauge.

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • infobar
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • pygauge »
  • PyGauge


SVN Revision 68362 For pygauge

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • pygauge »
  • SVN Revision 68362 For pygauge

svn SVN Revision 68362 For pygauge

This file contains the SVN revision history for pygauge, at revision 68362.

Available information include commit date, the name of the committer, the file size, the SVN log messages and a diff from the previous version (if available).

File Information

  • Commit Date: 21-Aug-2010 20:27:02 UTC
  • Committer: AG
  • File Size: 11424 byte(s)

Log Messages

The following log message was entered by the committer:

  • All of AGW: change my work e-mail from KPO to Maersk Oil (silly commit)

Diff To Previous Version (65377)

Version SVN diff:

--- wxPython/3rdParty/AGW/agw/pygauge.py    2010/08/21 20:27:02     65377
+++ wxPython/3rdParty/AGW/agw/pygauge.py    2011/07/24 21:36:47     68362
@@ -1,368 +1,368 @@
-# --------------------------------------------------------------------------------- #
-# PYGAUGE wxPython IMPLEMENTATION
-#
-# Mark Reed, @ 28 Jul 2010
-# Latest Revision: 02 Aug 2010, 09.00 GMT
-#
-# TODO List
-#
-# 1. Indeterminate mode (see wx.Gauge)
-# 2. Vertical bar
-# 3. Bitmap support (bar, background)
-# 4. UpdateFunction - Pass a function to PyGauge which will be called every X
-#    milliseconds and the value will be updated to the returned value.
-# 5. Currently the full gradient is drawn from 0 to value. Perhaps the gradient
-#    should be drawn from 0 to range and clipped at 0 to value.
-# 6. Add a label?
-#
-# For All Kind Of Problems, Requests Of Enhancements And Bug Reports, Please
-# Write To The:
-#
-# wxPython Mailing List!!!
-#
-# End Of Comments
-# --------------------------------------------------------------------------------- #
-
-"""
-PyGauge is a generic `wx.Gauge` implementation.
-
-
-Description
-===========
-
-PyGauge supports the determinate mode functions as `wx.Gauge` and adds an L{Update} function
-which takes a value and a time parameter. The `value` is added to the current value over
-a period of `time` milliseconds.
-
-
-Supported Platforms
-===================
-
-PyGauge has been tested on the following platforms:
-  * Windows (Windows XP);
-
-
-License And Version
-===================
-
-PyGauge is distributed under the wxPython license.
-PyGauge has been kindly contributed to the AGW library by Mark Reed.
-
-Latest Revision: Andrea Gavana @ 02 Aug 2010, 09.00 GMT
-
-Version 0.1
-"""
-
-import wx
-import copy
-
-
-class PyGauge(wx.PyWindow):
-    """
-    This class provides a visual alternative for `wx.Gauge`. It currently
-    only support determinate mode (see L{PyGauge.SetValue} and L{PyGauge.SetRange})
-    """
-
-    def __init__(self, parent, id=wx.ID_ANY, range=100, pos=wx.DefaultPosition,
-                 size=(-1,30), style=0):
-        """
-        Default class constructor.
-
-        :param `parent`: parent window. Must not be ``None``;
-        :param `id`: window identifier. A value of -1 indicates a default value;
-        :param `pos`: the control position. A value of (-1, -1) indicates a default position,
-         chosen by either the windowing system or wxPython, depending on platform;
-        :param `size`: the control size. A value of (-1, -1) indicates a default size,
-         chosen by either the windowing system or wxPython, depending on platform;
-        :param `style`: the underlying `wx.PyWindow` window style.
-        """
-
-        wx.PyWindow.__init__(self, parent, id, pos, size, style)
-
-        self._size = size
-
-        self._border_colour = None
-        self._barColour    = self._barColourSorted   = [wx.Colour(212,228,255)]
-        self._barGradient  = self._barGradientSorted = None
-
-        self._border_padding = 0
-        self._range = range
-        self._value = [0]
-        self._valueSorted = [0]
-
-        self._timerId = wx.NewId()
-        self._timer = None
-
-        self.Bind(wx.EVT_PAINT, self.OnPaint)
-        self.Bind(wx.EVT_ERASE_BACKGROUND, self.OnEraseBackground)
-        self.Bind(wx.EVT_TIMER, self.OnTimer)
-
-
-    def DoGetBestSize(self):
-        """
-        Overridden base class virtual. Determines the best size of the
-        button based on the label and bezel size.
-        """
-
-        return wx.Size(self._size[0], self._size[1])
-
-
-    def GetBorderColour(self):
-        """ Returns the L{PyGauge} border colour. """
-
-        return self._border_colour
-
-
-    def SetBorderColour(self, colour):
-        """
-        Sets the L{PyGauge} border colour.
-
-        :param `colour`: an instance of `wx.Colour`.
-        """
-
-        self._border_colour = colour
-
-    SetBorderColor = SetBorderColour
-    GetBorderColor = GetBorderColour
-
-
-    def GetBarColour(self):
-        """ Returns the L{PyGauge} main bar colour. """
-
-        return self._barColour[0]
-
-
-    def SetBarColour(self, colour):
-        """
-        Sets the L{PyGauge} main bar colour.
-
-        :param `colour`: an instance of `wx.Colour`.
-        """
-
-        if type(colour) != type([]):
-            self._barColour = [colour]
-        else:
-            self._barColour = list(colour)
-
-        self.SortForDisplay()
-
-    SetBarColor = SetBarColour
-    GetBarColor = GetBarColour
-
-
-    def GetBarGradient(self):
-        """ Returns a tuple containing the gradient start and end colours. """
-
-        if self._barGradient == None:
-            return None
-
-        return self._barGradient[0]
-
-
-    def SetBarGradient(self, gradient):
-        """
-        Sets the bar gradient.
-
-        :param `gradient`: a tuple containing the gradient start and end colours.
-
-        :note: This overrides the bar colour previously set with L{SetBarColour}.
-        """
-
-        if type(gradient) != type([]):
-            self._barGradient = [gradient]
-        else:
-            self._barGradient = list(gradient)
-
-        self.SortForDisplay()
-
-
-    def GetBorderPadding(self):
-        """ Gets the border padding. """
-
-        return self._border_padding
-
-
-    def SetBorderPadding(self, padding):
-        """
-        Sets the border padding.
-
-        :param `padding`: pixels between the border and the progress bar.
-        """
-
-        self._border_padding = padding
-
-
-    def GetRange(self):
-        """ Returns the maximum value of the gauge. """
-
-        return self._range
-
-
-    def SetRange(self, range):
-        """
-        Sets the range of the gauge. The gauge length is its
-        value as a proportion of the range.
-
-        :param `range`: The maximum value of the gauge.
-        """
-
-        if range <= 0:
-            raise Exception("ERROR:\n Gauge range must be greater than 0.")
-
-        self._range = range
-
-
-    def GetValue(self):
-        """ Returns the current position of the gauge. """
-
-        return self._value[0]
-
-
-    def SetValue(self, value):
-        """
-        Sets the current position of the gauge.
-
-        :param `value`: an integer specifying the current position of the gauge.
-        """
-
-        if type(value) != type([]):
-            self._value = [value]
-        else:
-            self._value = list(value)
-
-        self.SortForDisplay()
-
-        for v in self._value:
-            if v < 0 or v > self._range:
-                raise Exception("ERROR:\n Gauge value must be between 0 and its range.")
-
-
-    def OnEraseBackground(self, event):
-        """
-        Handles the ``wx.EVT_ERASE_BACKGROUND`` event for L{PyGauge}.
-
-        :param `event`: a `wx.EraseEvent` event to be processed.
-
-        :note: This method is intentionally empty to reduce flicker.
-        """
-
-        pass
-
-
-    def OnPaint(self, event):
-        """
-        Handles the ``wx.EVT_PAINT`` event for L{PyGauge}.
-
-        :param `event`: a `wx.PaintEvent` event to be processed.
-        """
-
-        dc = wx.BufferedPaintDC(self)
-        rect = self.GetClientRect()
-
-        dc.SetBackground(wx.Brush(self.GetBackgroundColour()))
-        dc.Clear()
-        colour = self.GetBackgroundColour()
-        dc.SetBrush(wx.Brush(colour))
-        dc.SetPen(wx.Pen(colour))
-        dc.DrawRectangleRect(rect)
-
-
-        if self._border_colour:
-            dc.SetPen(wx.Pen(self.GetBorderColour()))
-            dc.DrawRectangleRect(rect)
-            pad = 1 + self.GetBorderPadding()
-            rect.Deflate(pad,pad)
-
-
-        if self.GetBarGradient():
-            for i, gradient in enumerate(self._barGradientSorted):
-                c1,c2 = gradient
-                w = rect.width * (float(self._valueSorted[i]) / self._range)
-                r = copy.copy(rect)
-                r.width = w
-                dc.GradientFillLinear(r, c1, c2, wx.EAST)
-        else:
-            for i, colour in enumerate(self._barColourSorted):
-                dc.SetBrush(wx.Brush(colour))
-                dc.SetPen(wx.Pen(colour))
-                w = rect.width * (float(self._valueSorted[i]) / self._range)
-                r = copy.copy(rect)
-                r.width = w
-                dc.DrawRectangleRect(r)
-
-
-    def OnTimer(self,event):
-        """
-        Handles the ``wx.EVT_TIMER`` event for L{PyGauge}.
-
-        :param `event`: a `wx.TimerEvent` event to be processed.
-        """
-
-        if self._timerId == event.GetId():
-            stop_timer = True
-            for i, v in enumerate(self._value):
-                self._value[i] += self._update_step[i]
-
-                if self._update_step[i] > 0:
-                    if self._value[i] > self._update_value[i]:
-                        self._value[i] = self._update_value[i]
-                    else: stop_timer = False
-                else:
-                    if self._value[i] < self._update_value[i]:
-                        self._value[i] = self._update_value[i]
-                    else: stop_timer = False
-
-            if stop_timer:
-                self._timer.Stop()
-
-            self.SortForDisplay()
-
-            self.Refresh()
-
-
-    def Update(self, value, time=0):
-        """
-        Update the gauge by adding `value` to it over `time` milliseconds. The `time` parameter
-        **must** be a multiple of 50 milliseconds.
-
-        :param `value`: The value to be added to the gauge;
-        :param `time`: The length of time in milliseconds that it will take to move the gauge.
-        """
-
-        if type(value) != type([]):
-            value = [value]
-
-        if len(value) != len(self._value):
-            raise Exception("ERROR:\n len(value) != len(self.GetValue())")
-
-        self._update_value = []
-        self._update_step  = []
-        for i, v in enumerate(self._value):
-            if value[i]+v <= 0 or value[i]+v > self._range:
-                raise Exception("ERROR:\n Gauge value must be between 0 and its range. ")
-
-            self._update_value.append(value[i] + v)
-            self._update_step.append(float(value[i])/(time/50))
-
-        #print self._update_
-
-        if not self._timer:
-            self._timer = wx.Timer(self, self._timerId)
-
-        self._timer.Start(100)
-
-
-    def SortForDisplay(self):
-        """ Internal method which sorts things so we draw the longest bar first. """
-
-        if self.GetBarGradient():
-            tmp = sorted(zip(self._value,self._barGradient)); tmp.reverse()
-            a,b = zip(*tmp)
-            self._valueSorted       = list(a)
-            self._barGradientSorted = list(b)
-        else:
-            tmp = sorted(zip(self._value,self._barColour)); tmp.reverse()
-            a,b = zip(*tmp)
-            self._valueSorted     = list(a)
-            self._barColourSorted = list(b)
-
+# --------------------------------------------------------------------------------- #
+# PYGAUGE wxPython IMPLEMENTATION
+#
+# Mark Reed, @ 28 Jul 2010
+# Latest Revision: 02 Aug 2010, 09.00 GMT
+#
+# TODO List
+#
+# 1. Indeterminate mode (see wx.Gauge)
+# 2. Vertical bar
+# 3. Bitmap support (bar, background)
+# 4. UpdateFunction - Pass a function to PyGauge which will be called every X
+#    milliseconds and the value will be updated to the returned value.
+# 5. Currently the full gradient is drawn from 0 to value. Perhaps the gradient
+#    should be drawn from 0 to range and clipped at 0 to value.
+# 6. Add a label?
+#
+# For All Kind Of Problems, Requests Of Enhancements And Bug Reports, Please
+# Write To The:
+#
+# wxPython Mailing List!!!
+#
+# End Of Comments
+# --------------------------------------------------------------------------------- #
+
+"""
+PyGauge is a generic `wx.Gauge` implementation.
+
+
+Description
+===========
+
+PyGauge supports the determinate mode functions as `wx.Gauge` and adds an L{Update} function
+which takes a value and a time parameter. The `value` is added to the current value over
+a period of `time` milliseconds.
+
+
+Supported Platforms
+===================
+
+PyGauge has been tested on the following platforms:
+  * Windows (Windows XP);
+
+
+License And Version
+===================
+
+PyGauge is distributed under the wxPython license.
+PyGauge has been kindly contributed to the AGW library by Mark Reed.
+
+Latest Revision: Andrea Gavana @ 02 Aug 2010, 09.00 GMT
+
+Version 0.1
+"""
+
+import wx
+import copy
+
+
+class PyGauge(wx.PyWindow):
+    """
+    This class provides a visual alternative for `wx.Gauge`. It currently
+    only support determinate mode (see L{PyGauge.SetValue} and L{PyGauge.SetRange})
+    """
+
+    def __init__(self, parent, id=wx.ID_ANY, range=100, pos=wx.DefaultPosition,
+                 size=(-1,30), style=0):
+        """
+        Default class constructor.
+
+        :param `parent`: parent window. Must not be ``None``;
+        :param `id`: window identifier. A value of -1 indicates a default value;
+        :param `pos`: the control position. A value of (-1, -1) indicates a default position,
+         chosen by either the windowing system or wxPython, depending on platform;
+        :param `size`: the control size. A value of (-1, -1) indicates a default size,
+         chosen by either the windowing system or wxPython, depending on platform;
+        :param `style`: the underlying `wx.PyWindow` window style.
+        """
+
+        wx.PyWindow.__init__(self, parent, id, pos, size, style)
+
+        self._size = size
+
+        self._border_colour = None
+        self._barColour    = self._barColourSorted   = [wx.Colour(212,228,255)]
+        self._barGradient  = self._barGradientSorted = None
+
+        self._border_padding = 0
+        self._range = range
+        self._value = [0]
+        self._valueSorted = [0]
+
+        self._timerId = wx.NewId()
+        self._timer = None
+
+        self.Bind(wx.EVT_PAINT, self.OnPaint)
+        self.Bind(wx.EVT_ERASE_BACKGROUND, self.OnEraseBackground)
+        self.Bind(wx.EVT_TIMER, self.OnTimer)
+
+
+    def DoGetBestSize(self):
+        """
+        Overridden base class virtual. Determines the best size of the
+        button based on the label and bezel size.
+        """
+
+        return wx.Size(self._size[0], self._size[1])
+
+
+    def GetBorderColour(self):
+        """ Returns the L{PyGauge} border colour. """
+
+        return self._border_colour
+
+
+    def SetBorderColour(self, colour):
+        """
+        Sets the L{PyGauge} border colour.
+
+        :param `colour`: an instance of `wx.Colour`.
+        """
+
+        self._border_colour = colour
+
+    SetBorderColor = SetBorderColour
+    GetBorderColor = GetBorderColour
+
+
+    def GetBarColour(self):
+        """ Returns the L{PyGauge} main bar colour. """
+
+        return self._barColour[0]
+
+
+    def SetBarColour(self, colour):
+        """
+        Sets the L{PyGauge} main bar colour.
+
+        :param `colour`: an instance of `wx.Colour`.
+        """
+
+        if type(colour) != type([]):
+            self._barColour = [colour]
+        else:
+            self._barColour = list(colour)
+
+        self.SortForDisplay()
+
+    SetBarColor = SetBarColour
+    GetBarColor = GetBarColour
+
+
+    def GetBarGradient(self):
+        """ Returns a tuple containing the gradient start and end colours. """
+
+        if self._barGradient == None:
+            return None
+
+        return self._barGradient[0]
+
+
+    def SetBarGradient(self, gradient):
+        """
+        Sets the bar gradient.
+
+        :param `gradient`: a tuple containing the gradient start and end colours.
+
+        :note: This overrides the bar colour previously set with L{SetBarColour}.
+        """
+
+        if type(gradient) != type([]):
+            self._barGradient = [gradient]
+        else:
+            self._barGradient = list(gradient)
+
+        self.SortForDisplay()
+
+
+    def GetBorderPadding(self):
+        """ Gets the border padding. """
+
+        return self._border_padding
+
+
+    def SetBorderPadding(self, padding):
+        """
+        Sets the border padding.
+
+        :param `padding`: pixels between the border and the progress bar.
+        """
+
+        self._border_padding = padding
+
+
+    def GetRange(self):
+        """ Returns the maximum value of the gauge. """
+
+        return self._range
+
+
+    def SetRange(self, range):
+        """
+        Sets the range of the gauge. The gauge length is its
+        value as a proportion of the range.
+
+        :param `range`: The maximum value of the gauge.
+        """
+
+        if range <= 0:
+            raise Exception("ERROR:\n Gauge range must be greater than 0.")
+
+        self._range = range
+
+
+    def GetValue(self):
+        """ Returns the current position of the gauge. """
+
+        return self._value[0]
+
+
+    def SetValue(self, value):
+        """
+        Sets the current position of the gauge.
+
+        :param `value`: an integer specifying the current position of the gauge.
+        """
+
+        if type(value) != type([]):
+            self._value = [value]
+        else:
+            self._value = list(value)
+
+        self.SortForDisplay()
+
+        for v in self._value:
+            if v < 0 or v > self._range:
+                raise Exception("ERROR:\n Gauge value must be between 0 and its range.")
+
+
+    def OnEraseBackground(self, event):
+        """
+        Handles the ``wx.EVT_ERASE_BACKGROUND`` event for L{PyGauge}.
+
+        :param `event`: a `wx.EraseEvent` event to be processed.
+
+        :note: This method is intentionally empty to reduce flicker.
+        """
+
+        pass
+
+
+    def OnPaint(self, event):
+        """
+        Handles the ``wx.EVT_PAINT`` event for L{PyGauge}.
+
+        :param `event`: a `wx.PaintEvent` event to be processed.
+        """
+
+        dc = wx.BufferedPaintDC(self)
+        rect = self.GetClientRect()
+
+        dc.SetBackground(wx.Brush(self.GetBackgroundColour()))
+        dc.Clear()
+        colour = self.GetBackgroundColour()
+        dc.SetBrush(wx.Brush(colour))
+        dc.SetPen(wx.Pen(colour))
+        dc.DrawRectangleRect(rect)
+
+
+        if self._border_colour:
+            dc.SetPen(wx.Pen(self.GetBorderColour()))
+            dc.DrawRectangleRect(rect)
+            pad = 1 + self.GetBorderPadding()
+            rect.Deflate(pad,pad)
+
+
+        if self.GetBarGradient():
+            for i, gradient in enumerate(self._barGradientSorted):
+                c1,c2 = gradient
+                w = rect.width * (float(self._valueSorted[i]) / self._range)
+                r = copy.copy(rect)
+                r.width = w
+                dc.GradientFillLinear(r, c1, c2, wx.EAST)
+        else:
+            for i, colour in enumerate(self._barColourSorted):
+                dc.SetBrush(wx.Brush(colour))
+                dc.SetPen(wx.Pen(colour))
+                w = rect.width * (float(self._valueSorted[i]) / self._range)
+                r = copy.copy(rect)
+                r.width = w
+                dc.DrawRectangleRect(r)
+
+
+    def OnTimer(self,event):
+        """
+        Handles the ``wx.EVT_TIMER`` event for L{PyGauge}.
+
+        :param `event`: a `wx.TimerEvent` event to be processed.
+        """
+
+        if self._timerId == event.GetId():
+            stop_timer = True
+            for i, v in enumerate(self._value):
+                self._value[i] += self._update_step[i]
+
+                if self._update_step[i] > 0:
+                    if self._value[i] > self._update_value[i]:
+                        self._value[i] = self._update_value[i]
+                    else: stop_timer = False
+                else:
+                    if self._value[i] < self._update_value[i]:
+                        self._value[i] = self._update_value[i]
+                    else: stop_timer = False
+
+            if stop_timer:
+                self._timer.Stop()
+
+            self.SortForDisplay()
+
+            self.Refresh()
+
+
+    def Update(self, value, time=0):
+        """
+        Update the gauge by adding `value` to it over `time` milliseconds. The `time` parameter
+        **must** be a multiple of 50 milliseconds.
+
+        :param `value`: The value to be added to the gauge;
+        :param `time`: The length of time in milliseconds that it will take to move the gauge.
+        """
+
+        if type(value) != type([]):
+            value = [value]
+
+        if len(value) != len(self._value):
+            raise Exception("ERROR:\n len(value) != len(self.GetValue())")
+
+        self._update_value = []
+        self._update_step  = []
+        for i, v in enumerate(self._value):
+            if value[i]+v <= 0 or value[i]+v > self._range:
+                raise Exception("ERROR:\n Gauge value must be between 0 and its range. ")
+
+            self._update_value.append(value[i] + v)
+            self._update_step.append(float(value[i])/(time/50))
+
+        #print self._update_
+
+        if not self._timer:
+            self._timer = wx.Timer(self, self._timerId)
+
+        self._timer.Start(100)
+
+
+    def SortForDisplay(self):
+        """ Internal method which sorts things so we draw the longest bar first. """
+
+        if self.GetBarGradient():
+            tmp = sorted(zip(self._value,self._barGradient)); tmp.reverse()
+            a,b = zip(*tmp)
+            self._valueSorted       = list(a)
+            self._barGradientSorted = list(b)
+        else:
+            tmp = sorted(zip(self._value,self._barColour)); tmp.reverse()
+            a,b = zip(*tmp)
+            self._valueSorted     = list(a)
+            self._barColourSorted = list(b)
+

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • pygauge »
  • SVN Revision 68362 For pygauge


SVN Revision 68881 For pygauge

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • pygauge »
  • SVN Revision 68881 For pygauge

svn SVN Revision 68881 For pygauge

This file contains the SVN revision history for pygauge, at revision 68881.

Available information include commit date, the name of the committer, the file size, the SVN log messages and a diff from the previous version (if available).

File Information

  • Commit Date: 02-Aug-2010 20:03:09 UTC
  • Committer: AG
  • File Size: 13272 byte(s)

Log Messages

The following log message was entered by the committer:

  • AGW: General overhaul of the documentation, much improved. All the widgets have their own sample usage in the docs as well;

  • FlatNotebook: Added the FNB_NAV_BUTTONS_WHEN_NEEDED style, which hides the navigation left/right arrows if all tabs fit;

  • RibbonBar: - Added the EVT_RIBBONBAR_TAB_LEFT_DCLICK event, which generates a special event

    when a ribbon bar tab is double-clicked;

    • Added support for toggle buttons;
    • Improved support for ribbon panel sizers: panels with sizers should now automatically minimise at small sizes, and behave properly when popping up from a minimised state;
    • Added tooltips via SetToolTip for those buttons which have the help_string attribute set.

  • XLSGrid: a new widget was added to AGW, termed XLSGrid. It’s based on wx.grid.Grid and can be used to faithfully reproduce the appearance of a Microsoft Excel spreadsheets.

Diff To Previous Version (68362)

Version SVN diff:

--- wxPython/3rdParty/AGW/agw/pygauge.py    2011/07/24 21:36:47     68362
+++ wxPython/3rdParty/AGW/agw/pygauge.py    2011/08/25 16:40:17     68881
@@ -2,7 +2,7 @@
# PYGAUGE wxPython IMPLEMENTATION
#
# Mark Reed, @ 28 Jul 2010
-# Latest Revision: 02 Aug 2010, 09.00 GMT
+# Latest Revision: 17 Aug 2011, 15.00 GMT
#
# TODO List
#
@@ -24,33 +24,90 @@
# --------------------------------------------------------------------------------- #

"""
-PyGauge is a generic `wx.Gauge` implementation.
+L{PyGauge} is a generic `wx.Gauge` implementation.

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

-PyGauge supports the determinate mode functions as `wx.Gauge` and adds an L{Update} function
+L{PyGauge} supports the determinate mode functions as `wx.Gauge` and adds an L{Update} function
which takes a value and a time parameter. The `value` is added to the current value over
a period of `time` milliseconds.

+Usage
+=====
+
+Usage example::
+
+    import wx
+    import wx.lib.agw.pygauge as PG
+
+    class MyFrame(wx.Frame):
+
+        def __init__(self, parent):
+
+            wx.Frame.__init__(self, parent, -1, "PyGauge Demo")
+
+            panel = wx.Panel(self)
+
+            gauge1 = PG.PyGauge(panel, -1, size=(100, 25), style=wx.GA_HORIZONTAL)
+            gauge1.SetValue(80)
+            gauge1.SetBackgroundColour(wx.WHITE)
+            gauge1.SetBorderColor(wx.BLACK)
+
+            gauge2 = PG.PyGauge(panel, -1, size=(100, 25), style=wx.GA_HORIZONTAL)
+            gauge2.SetValue([20, 80])
+            gauge2.SetBarColor([wx.Colour(162, 255, 178), wx.Colour(159, 176, 255)])
+            gauge2.SetBackgroundColour(wx.WHITE)
+            gauge2.SetBorderColor(wx.BLACK)
+            gauge2.SetBorderPadding(2)
+            gauge2.Update([30, 0], 2000)
+
+            gauge3 = PG.PyGauge(panel, -1, size=(100, 25), style=wx.GA_HORIZONTAL)
+            gauge3.SetValue(50)
+            gauge3.SetBarColor(wx.GREEN)
+            gauge3.SetBackgroundColour(wx.WHITE)
+            gauge3.SetBorderColor(wx.BLACK)
+
+            sizer = wx.BoxSizer(wx.VERTICAL)
+            sizer.Add(gauge1, 0, wx.ALIGN_CENTER_VERTICAL|wx.ALL, 20)
+            sizer.Add(gauge2, 0, wx.ALIGN_CENTER_VERTICAL|wx.ALL, 20)
+            sizer.Add(gauge3, 0, wx.ALIGN_CENTER_VERTICAL|wx.ALL, 20)
+
+            panel.SetSizer(sizer)
+            sizer.Layout()
+
+
+    # our normal wxApp-derived class, as usual
+
+    app = wx.PySimpleApp()
+
+    frame = MyFrame(None)
+    app.SetTopWindow(frame)
+    frame.Show()
+
+    app.MainLoop()
+
+
Supported Platforms
===================

-PyGauge has been tested on the following platforms:
+L{PyGauge} has been tested on the following platforms:
* Windows (Windows XP);

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

-PyGauge is distributed under the wxPython license.
-PyGauge has been kindly contributed to the AGW library by Mark Reed.
+L{PyGauge} is distributed under the wxPython license.
+
+L{PyGauge} has been kindly contributed to the AGW library by Mark Reed.

-Latest Revision: Andrea Gavana @ 02 Aug 2010, 09.00 GMT
+Latest Revision: Andrea Gavana @ 17 Aug 2011, 15.00 GMT

Version 0.1
+
"""

import wx
@@ -100,8 +157,11 @@

def DoGetBestSize(self):
"""
-        Overridden base class virtual. Determines the best size of the
-        button based on the label and bezel size.
+        Gets the size which best suits L{PyGauge}: for a control, it would be
+        the minimal size which doesn't truncate the control, for a panel - the
+        same size as it would have after a call to `Fit()`.
+
+        :note: Overridden from `wx.PyWindow`.
"""

return wx.Size(self._size[0], self._size[1])

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • pygauge »
  • SVN Revision 68881 For pygauge


ProgressGauge

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • pyprogress »
  • ProgressGauge

ProgressGauge

This class provides a visual alternative for wx.Gauge.

hierarchy Inheritance Diagram

Inheritance diagram for: ProgressGauge

Inheritance diagram of ProgressGauge

Methods Summary

__init__ | Default class constructor.
DrawProgress | Actually draws the sliding bar.
GetFirstGradientColour | Returns the first gradient colour.
GetGaugeBackground | Returns the gauge background colour.
GetGaugeProportion | Returns the relative proportion between the sliding bar and the
GetGaugeSteps | Returns the number of steps the gauge performs before switching from
GetSecondGradientColour | Returns the second gradient colour.
OnEraseBackground | Handles the wx.EVT_ERASE_BACKGROUND event for ProgressGauge.
OnPaint | Handles the wx.EVT_PAINT event for ProgressGauge.
SetFirstGradientColour | Sets the first gradient colour.
SetGaugeBackground | Sets the gauge background colour.
SetGaugeProportion | Sets the relative proportion between the sliding bar and the whole gauge.
SetGaugeSteps | Sets the number of steps the gauge performs before switching from forward to backward (or vice-versa) movement.
SetSecondGradientColour | Sets the second gradient colour.
Update | Updates the gauge with a new value.

API Class API

class ProgressGauge(wx.PyWindow) [source]

This class provides a visual alternative for wx.Gauge.

__init__(parent, id=wx.ID_ANY, pos=wx.DefaultPosition, size=(-1, 30)) [source]

Default class constructor.

Parameters:
  • parent – parent window. Must not be None;
  • id – window identifier. A value of -1 indicates a default value;
  • pos – the control position. A value of (-1, -1) indicates a default position, chosen by either the windowing system or wxPython, depending on platform;
  • size – the control size. A value of (-1, -1) indicates a default size, chosen by either the windowing system or wxPython, depending on platform.

DrawProgress(dc, xsize, ysize, increment) [source]

Actually draws the sliding bar.

Parameters:
  • dc – an instance of wx.DC;
  • xsize – the width of the whole progress bar;
  • ysize – the height of the whole progress bar;
  • increment – a positive value if we are spinning from left to right, a negative one if we are spinning from right to left.

GetFirstGradientColour() [source]

Returns the first gradient colour.

GetGaugeBackground() [source]

Returns the gauge background colour.

GetGaugeProportion() [source]

Returns the relative proportion between the sliding bar and the whole gauge.

GetGaugeSteps() [source]

Returns the number of steps the gauge performs before switching from forward to backward (or vice-versa) movement.

GetSecondGradientColour() [source]

Returns the second gradient colour.

OnEraseBackground(event) [source]

Handles the wx.EVT_ERASE_BACKGROUND event for ProgressGauge.

Parameters: event – a wx.EraseEvent event to be processed.

Note

This method is intentionally empty to reduce flicker.

OnPaint(event) [source]

Handles the wx.EVT_PAINT event for ProgressGauge.

Parameters: event – a wx.PaintEvent event to be processed.

SetFirstGradientColour(colour) [source]

Sets the first gradient colour.

Parameters: colour – a valid wx.Colour object.

SetGaugeBackground(colour) [source]

Sets the gauge background colour.

Parameters: colour – a valid wx.Colour object.

SetGaugeProportion(proportion) [source]

Sets the relative proportion between the sliding bar and the whole gauge.

Parameters: proportion – a floating point number representing the relative proportion between the sliding bar and the whole gauge.

SetGaugeSteps(steps) [source]

Sets the number of steps the gauge performs before switching from forward to backward (or vice-versa) movement.

Parameters: steps – the number of steps the gauge performs before switching from forward to backward (or vice-versa) movement.

SetSecondGradientColour(colour) [source]

Sets the second gradient colour.

Parameters: colour – a valid wx.Colour object.

Update() [source]

Updates the gauge with a new value.

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • infobar
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • pyprogress »
  • ProgressGauge


PyProgress

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • pyprogress »
  • PyProgress

PyProgress

PyProgress is similar to wx.ProgressDialog in indeterminated mode, but with a different gauge appearance and a different spinning behavior. The moving gauge can be drawn with a single solid colour or with a shading gradient foreground. The gauge background colour is user customizable. The bar does not move always from the beginning to the end as in wx.ProgressDialog in indeterminated mode, but spins cyclically forward and backward.

hierarchy Inheritance Diagram

Inheritance diagram for: PyProgress

Inheritance diagram of PyProgress

appearance Control Appearance

PyProgress

Methods Summary

__init__ | Default class constructor.
CreateLabel | Creates the wx.StaticText that holds the elapsed time label.
DisableAbort | Disables the Cancel button.
EnableAbort | Enables or disables the Cancel button.
EnableClose | Enables or disables the Close button.
GetFirstGradientColour | Returns the gauge first gradient colour.
GetGaugeBackground | Returns the gauge background colour.
GetGaugeProportion | Returns the relative proportion between the sliding bar and the
GetGaugeSteps | Returns the number of steps the gauge performs before switching from
GetSecondGradientColour | Returns the gauge second gradient colour.
OnCancel | Handles the wx.EVT_BUTTON event for the dialog.
OnClose | Handles the wx.EVT_CLOSE event for PyProgress.
OnDestroy | Handles the wx.EVT_WINDOW_DESTROY event for PyProgress.
ReenableOtherWindows | Re-enables the other windows if using wx.WindowDisabler.
SetFirstGradientColour | Sets the gauge first gradient colour.
SetGaugeBackground | Sets the gauge background colour.
SetGaugeProportion | Sets the relative proportion between the sliding bar and the whole gauge.
SetGaugeSteps | Sets the number of steps the gauge performs before switching from forward to backward (or vice-versa) movement.
SetSecondGradientColour | Sets the gauge second gradient colour.
SetTimeLabel | Sets the elapsed time label.
ShowDialog | Show the dialog.
UpdatePulse | Updates the dialog, setting the progress bar to the new value and, if given changes the message above it.

API Class API

class PyProgress(wx.Dialog) [source]

PyProgress is similar to wx.ProgressDialog in indeterminated mode, but with a different gauge appearance and a different spinning behavior. The moving gauge can be drawn with a single solid colour or with a shading gradient foreground. The gauge background colour is user customizable. The bar does not move always from the beginning to the end as in wx.ProgressDialog in indeterminated mode, but spins cyclically forward and backward.

__init__(parent=None, id=-1, title="", message="", agwStyle=wx.PD_APP_MODAL|wx.PD_AUTO_HIDE) [source]

Default class constructor.

Parameters:
  • parent – parent window;
  • id – window identifier. A value of -1 indicates a default value;
  • title – dialog title to show in titlebar;
  • message – message displayed above the progress bar;
  • style – the dialog style. This can be a combination of the following bits:

    Window Styles | Hex Value | Description
    PD_CAN_ABORT | 0x1 | This flag tells the dialog that it should have a Cancel button which the user may press. If this happens, the next call to UpdatePulse will return False.
    PD_APP_MODAL | 0x2 | Make the progress dialog modal. If this flag is not given, it is only ‘locally’ modal - that is the input to the parent window is disabled, but not to the other ones.
    PD_AUTO_HIDE | 0x4 | Causes the progress dialog to disappear from screen as soon as the maximum value of the progress meter has been reached.
    PD_ELAPSED_TIME | 0x8 | This flag tells the dialog that it should show elapsed time (since creating the dialog).

CreateLabel(text, sizer) [source]

Creates the wx.StaticText that holds the elapsed time label.

Parameters:
  • text – the dialog message to be displayed above the gauge;
  • sizer – the main wx.BoxSizer for PyProgress.

DisableAbort() [source]

Disables the Cancel button.

EnableAbort(enable=True) [source]

Enables or disables the Cancel button.

Parameters: enable – True to enable the Cancel button, False to disable it.

EnableClose(enable=True) [source]

Enables or disables the Close button.

Parameters: enable – True to enable the Close button, False to disable it.

GetFirstGradientColour() [source]

Returns the gauge first gradient colour.

GetGaugeBackground() [source]

Returns the gauge background colour.

GetGaugeProportion() [source]

Returns the relative proportion between the sliding bar and the whole gauge.

GetGaugeSteps() [source]

Returns the number of steps the gauge performs before switching from forward to backward (or vice-versa) movement.

GetSecondGradientColour() [source]

Returns the gauge second gradient colour.

OnCancel(event) [source]

Handles the wx.EVT_BUTTON event for the dialog.

Parameters: event – a wx.CommandEvent event to be processed.

Note

This method handles the Cancel button press.

OnClose(event) [source]

Handles the wx.EVT_CLOSE event for PyProgress.

Parameters: event – a wx.CloseEvent event to be processed.

OnDestroy(event) [source]

Handles the wx.EVT_WINDOW_DESTROY event for PyProgress.

Parameters: event – a wx.WindowDestroyEvent event to be processed.

ReenableOtherWindows() [source]

Re-enables the other windows if using wx.WindowDisabler.

SetFirstGradientColour(colour) [source]

Sets the gauge first gradient colour.

Parameters: colour – a valid wx.Colour object.

SetGaugeBackground(colour) [source]

Sets the gauge background colour.

Parameters: colour – a valid wx.Colour object.

SetGaugeProportion(proportion) [source]

Sets the relative proportion between the sliding bar and the whole gauge.

Parameters: proportion – a floating point number representing the relative proportion between the sliding bar and the whole gauge.

SetGaugeSteps(steps) [source]

Sets the number of steps the gauge performs before switching from forward to backward (or vice-versa) movement.

Parameters: steps – the number of steps the gauge performs before switching from forward to backward (or vice-versa) movement.

SetSecondGradientColour(colour) [source]

Sets the gauge second gradient colour.

Parameters: colour – a valid wx.Colour object.

SetTimeLabel(val, label=None) [source]

Sets the elapsed time label.

Parameters:
  • val – the elapsed time since the dialog was shown, in seconds;
  • label – the new message to display in the elapsed time text.

ShowDialog(show=True) [source]

Show the dialog.

Parameters: show – True to show the dialog and re-enable all the other windows, False otherwise.

UpdatePulse(newmsg='') [source]

Updates the dialog, setting the progress bar to the new value and, if given changes the message above it. Returns True unless the Cancel button has been pressed.

If False is returned, the application can either immediately destroy the dialog or ask the user for the confirmation.

Parameters: newmsg – The new messages for the progress dialog text, if it is empty (which is the default) the message is not changed.

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • infobar
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • pyprogress »
  • PyProgress


SVN Revision 68362 For pyprogress

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • pyprogress »
  • SVN Revision 68362 For pyprogress

svn SVN Revision 68362 For pyprogress

This file contains the SVN revision history for pyprogress, at revision 68362.

Available information include commit date, the name of the committer, the file size, the SVN log messages and a diff from the previous version (if available).

File Information

  • Commit Date: 17-Oct-2008 20:51:43 UTC
  • Committer: AG
  • File Size: 27252 byte(s)

Log Messages

The following log message was entered by the committer:

  • All of AGW: change my work e-mail from KPO to Maersk Oil (silly commit)

Diff To Previous Version (65377)

Version SVN diff:

--- wxPython/3rdParty/AGW/agw/pyprogress.py 2010/08/21 20:27:02     65377
+++ wxPython/3rdParty/AGW/agw/pyprogress.py 2011/07/24 21:36:47     68362
@@ -15,7 +15,7 @@
# For All Kind Of Problems, Requests Of Enhancements And Bug Reports, Please
# Write To Me At:
#
-# gavana@kpo.kz
+# andrea.gavana@maerskoil.com
# andrea.gavana@gmail.com
#
# Or, Obviously, To The wxPython Mailing List!!!

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • pyprogress »
  • SVN Revision 68362 For pyprogress


SVN Revision 68881 For pyprogress

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • pyprogress »
  • SVN Revision 68881 For pyprogress

svn SVN Revision 68881 For pyprogress

This file contains the SVN revision history for pyprogress, at revision 68881.

Available information include commit date, the name of the committer, the file size, the SVN log messages and a diff from the previous version (if available).

File Information

  • Commit Date: 17-Oct-2008 19:15:31 UTC
  • Committer: AG
  • File Size: 28134 byte(s)

Log Messages

The following log message was entered by the committer:

  • AGW: General overhaul of the documentation, much improved. All the widgets have their own sample usage in the docs as well;

  • FlatNotebook: Added the FNB_NAV_BUTTONS_WHEN_NEEDED style, which hides the navigation left/right arrows if all tabs fit;

  • RibbonBar: - Added the EVT_RIBBONBAR_TAB_LEFT_DCLICK event, which generates a special event

    when a ribbon bar tab is double-clicked;

    • Added support for toggle buttons;
    • Improved support for ribbon panel sizers: panels with sizers should now automatically minimise at small sizes, and behave properly when popping up from a minimised state;
    • Added tooltips via SetToolTip for those buttons which have the help_string attribute set.

  • XLSGrid: a new widget was added to AGW, termed XLSGrid. It’s based on wx.grid.Grid and can be used to faithfully reproduce the appearance of a Microsoft Excel spreadsheets.

Diff To Previous Version (68362)

Version SVN diff:

--- wxPython/3rdParty/AGW/agw/pyprogress.py 2011/07/24 21:36:47     68362
+++ wxPython/3rdParty/AGW/agw/pyprogress.py 2011/08/25 16:40:17     68881
@@ -2,7 +2,7 @@
# PYPROGRESS wxPython IMPLEMENTATION
#
# Andrea Gavana, @ 03 Nov 2006
-# Latest Revision: 14 Apr 2010, 12.00 GMT
+# Latest Revision: 17 Aug 2011, 15.00 GMT
#
#
# TODO List
@@ -25,14 +25,14 @@
# --------------------------------------------------------------------------------- #

"""
-PyProgress is similar to `wx.ProgressDialog` in indeterminated mode, but with a
+L{PyProgress} is similar to `wx.ProgressDialog` in indeterminated mode, but with a
different gauge appearance and a different spinning behavior.

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

-PyProgress is similar to `wx.ProgressDialog` in indeterminated mode, but with a
+L{PyProgress} is similar to `wx.ProgressDialog` in indeterminated mode, but with a
different gauge appearance and a different spinning behavior. The moving gauge
can be drawn with a single solid colour or with a shading gradient foreground.
The gauge background colour is user customizable.
@@ -47,14 +47,54 @@
- Modifying the number of steps the spinning bar performs before a forward
(or backward) loop reverses.

-PyProgress can optionally display a ``Cancel`` button, and a `wx.StaticText` which
+L{PyProgress} can optionally display a ``Cancel`` button, and a `wx.StaticText` which
outputs the elapsed time from the starting of the process.

+Usage
+=====
+
+Usage example::
+
+    import wx
+    import wx.lib.agw.pyprogress as PP
+
+    # Our normal wxApp-derived class, as usual
+    app = wx.App(0)
+
+    dlg = PP.PyProgress(None, -1, "PyProgress Example",
+                        "An Informative Message",
+                        agwStyle=wx.PD_APP_MODAL|wx.PD_ELAPSED_TIME)
+
+    dlg.SetGaugeProportion(0.2)
+    dlg.SetGaugeSteps(50)
+    dlg.SetGaugeBackground(wx.WHITE)
+    dlg.SetFirstGradientColour(wx.WHITE)
+    dlg.SetSecondGradientColour(wx.BLUE)
+
+    max = 400
+    keepGoing = True
+    count = 0
+
+    while keepGoing and count < max:
+        count += 1
+        wx.MilliSleep(30)
+
+        if count >= max / 2:
+            keepGoing = dlg.UpdatePulse("Half-time!")
+        else:
+            keepGoing = dlg.UpdatePulse()
+
+    dlg.Destroy()
+
+    app.MainLoop()
+
+
+
Supported Platforms
===================

-PyProgress has been tested on the following platforms:
+L{PyProgress} has been tested on the following platforms:
* Windows (Windows XP);
* Linux Ubuntu (Dapper 6.06)

@@ -83,9 +123,9 @@
License And Version
===================

-PyProgress is distributed under the wxPython license.
+L{PyProgress} is distributed under the wxPython license.

-Latest Revision: Andrea Gavana @ 14 Apr 2010, 12.00 GMT
+Latest Revision: Andrea Gavana @ 17 Aug 2011, 15.00 GMT

Version 0.4

@@ -354,7 +394,7 @@

class PyProgress(wx.Dialog):
"""
-    PyProgress is similar to `wx.ProgressDialog` in indeterminated mode, but with a
+    L{PyProgress} is similar to `wx.ProgressDialog` in indeterminated mode, but with a
different gauge appearance and a different spinning behavior. The moving gauge
can be drawn with a single solid colour or with a shading gradient foreground.
The gauge background colour is user customizable.

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • pyprogress »
  • SVN Revision 68881 For pyprogress


ribbon.art_aui functions

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • ribbon library »
  • ribbon.art_aui »
  • ribbon.art_aui functions

ribbon.art_aui functions

This is the description of standalone Python functions in the ribbon.art_aui module.

Functions Summary

FontFromFont

API Functions API

FontFromFont(original) [source]

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • infobar
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • ribbon library »
  • ribbon.art_aui »
  • ribbon.art_aui functions


RibbonAUIArtProvider

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • ribbon library »
  • ribbon.art_aui »
  • RibbonAUIArtProvider

RibbonAUIArtProvider

hierarchy Inheritance Diagram

Inheritance diagram for: RibbonAUIArtProvider

Inheritance diagram of RibbonAUIArtProvider

supclasses Known Superclasses

  • ribbon.art_msw.RibbonMSWArtProvider

Methods Summary

__init__ |
Clone | Create a new art provider which is a clone of this one.
DrawButtonBarBackground | Draw the background for a RibbonButtonBar control.
DrawButtonBarButton | Draw a single button for a RibbonButtonBar control.
DrawGalleryBackground | Draw the background and chrome for a RibbonGallery control.
DrawGalleryButton |
DrawGalleryItemBackground | Draw the background of a single item in a RibbonGallery control.
DrawMinimisedPanel | Draw a minimised ribbon panel.
DrawPageBackground | Draw the background of a ribbon page.
DrawPanelBackground | Draw the background and chrome for a ribbon panel.
DrawPartialPanelBackground |
DrawScrollButton | Draw a ribbon-style scroll button.
DrawTab | Draw a single tab in the tab region of a ribbon bar.
DrawTabCtrlBackground | Draw the background of the tab region of a ribbon bar.
DrawTabSeparator | Draw a separator between two tabs in a ribbon bar.
DrawTool | Draw a single tool (for a RibbonToolBar control).
DrawToolBarBackground | Draw the background for a RibbonToolBar control.
DrawToolGroupBackground | Draw the background for a group of tools on a RibbonToolBar control.
GetBarTabWidth | Calculate the ideal and minimum width (in pixels) of a tab in a ribbon bar.
GetColour | Get the value of a certain colour setting.
GetPanelClientSize | Calculate the client size of a panel for a given overall size.
GetPanelSize | Calculate the size of a panel for a given client size.
GetScrollButtonMinimumSize | Calculate the minimum size (in pixels) of a scroll button.
GetTabCtrlHeight | Calculate the height (in pixels) of the tab region of a ribbon bar.
SetColour | Set the value of a certain colour setting to the value.
SetColourScheme | Set all applicable colour settings from a few base colours.
SetFont | Set the value of a certain font setting to the value.

API Class API

class RibbonAUIArtProvider(RibbonMSWArtProvider) [source]

__init__() [source]

Clone() [source]

Create a new art provider which is a clone of this one.

DrawButtonBarBackground(dc, wnd, rect) [source]

Draw the background for a RibbonButtonBar control.

Parameters:
  • dc – The device context to draw onto;
  • wnd – The window which is being drawn onto (which will typically be the button bar itself, though this is not guaranteed);
  • rect – The rectangle within which to draw.

DrawButtonBarButton(dc, wnd, rect, kind, state, label, bitmap_large, bitmap_small) [source]

Draw a single button for a RibbonButtonBar control.

Parameters:
  • dc – The device context to draw onto;
  • wnd – The window which is being drawn onto;
  • rect – The rectangle within which to draw. The size of this rectangle will be a size previously returned by RibbonMSWArtProvider.GetButtonBarButtonSize(), and the rectangle will be entirely within a rectangle on the same device context previously painted with DrawButtonBarBackground;
  • kind – The kind of button to draw (normal, dropdown or hybrid);
  • state – Combination of a size flag and state flags from the RibbonButtonBarButtonState enumeration;
  • label – The label of the button;
  • bitmap_large – The large bitmap of the button (or the large disabled bitmap when RIBBON_BUTTONBAR_BUTTON_DISABLED is set in );
  • bitmap_small – The small bitmap of the button (or the small disabled bitmap when RIBBON_BUTTONBAR_BUTTON_DISABLED is set in ).

DrawGalleryBackground(dc, wnd, rect) [source]

Draw the background and chrome for a RibbonGallery control.

This should draw the border, brackground, scroll buttons, extension button, and any other UI elements which are not attached to a specific gallery item.

Parameters:
  • dc – The device context to draw onto;
  • wnd – The window which is being drawn onto, which is always the gallery whose background and chrome is being drawn. Attributes used during drawing like the gallery hover state and individual button states can be queried from this parameter by RibbonGallery.IsHovered(), RibbonGallery.GetExtensionButtonState(), RibbonGallery.GetUpButtonState(), and RibbonGallery.GetDownButtonState();
  • rect – The rectangle within which to draw. This rectangle is the entire area of the gallery control, not just the client rectangle.

DrawGalleryButton(dc, rect, state, bitmaps) [source]

DrawGalleryItemBackground(dc, wnd, rect, item) [source]

Draw the background of a single item in a RibbonGallery control.

This is painted on top of a gallery background, and behind the items bitmap. Unlike DrawButtonBarButton and DrawTool, it is not expected to draw the item bitmap - that is done by the gallery control itself.

Parameters:
  • dc – The device context to draw onto;
  • wnd – The window which is being drawn onto, which is always the gallery which contains the item being drawn;
  • rect – The rectangle within which to draw. The size of this rectangle will be the size of the item’s bitmap, expanded by gallery item padding values (RIBBON_ART_GALLERY_BITMAP_PADDING_LEFT_SIZE, RIBBON_ART_GALLERY_BITMAP_PADDING_RIGHT_SIZE, RIBBON_ART_GALLERY_BITMAP_PADDING_TOP_SIZE, and RIBBON_ART_GALLERY_BITMAP_PADDING_BOTTOM_SIZE). The drawing rectangle will be entirely within a rectangle on the same device context previously painted with DrawGalleryBackground;
  • item – The item whose background is being painted. Typically the background will vary if the item is hovered, active, or selected; RibbonGallery.GetSelection(), RibbonGallery.GetActiveItem(), and RibbonGallery.GetHoveredItem() can be called to test if the given item is in one of these states.

DrawMinimisedPanel(dc, wnd, rect, bitmap) [source]

Draw a minimised ribbon panel.

Parameters:
  • dc – The device context to draw onto;
  • wnd – The window which is being drawn onto, which is always the panel which is minimised. The panel label can be obtained from this window. The minimised icon obtained from querying the window may not be the size requested by RibbonMSWArtProvider.GetMinimisedPanelMinimumSize() - the argument contains the icon in the requested size;
  • rect – The rectangle within which to draw. The size of the rectangle will be at least the size returned by RibbonMSWArtProvider.GetMinimisedPanelMinimumSize();
  • bitmap – A copy of the panel’s minimised bitmap rescaled to the size returned by RibbonMSWArtProvider.GetMinimisedPanelMinimumSize().

DrawPageBackground(dc, wnd, rect) [source]

Draw the background of a ribbon page.

Parameters:
  • dc – The device context to draw onto;
  • wnd – The window which is being drawn onto (which is commonly the RibbonPage whose background is being drawn, but doesn’t have to be);
  • rect – The rectangle within which to draw.

See also

RibbonMSWArtProvider.GetPageBackgroundRedrawArea()

DrawPanelBackground(dc, wnd, rect) [source]

Draw the background and chrome for a ribbon panel.

This should draw the border, background, label, and any other items of a panel which are outside the client area of a panel. Note that when a panel is minimised, this function is not called - only DrawMinimisedPanel is called, so a background should be explicitly painted by that if required.

Parameters:
  • dc – The device context to draw onto;
  • wnd – The window which is being drawn onto, which is always the panel whose background and chrome is being drawn. The panel label and other panel attributes can be obtained by querying this;
  • rect – The rectangle within which to draw.

DrawPartialPanelBackground(dc, wnd, rect) [source]

DrawScrollButton(dc, wnd, rect, style) [source]

Draw a ribbon-style scroll button.

Parameters:
  • dc – The device context to draw onto;
  • wnd – The window which is being drawn onto;
  • rect – The rectangle within which to draw. The size of this rectangle will be at least the size returned by GetScrollButtonMinimumSize for a scroll button with the same style. For tab scroll buttons, this rectangle will be entirely within a rectangle on the same device context previously painted with DrawTabCtrlBackground, but this is not guaranteed for other types of button (for example, page scroll buttons will not be painted on an area previously painted with DrawPageBackground);
  • style – A combination of flags from RibbonScrollButtonStyle, including a direction, a for flag, and one or more states.

DrawTab(dc, wnd, tab) [source]

Draw a single tab in the tab region of a ribbon bar.

Parameters:
  • dc – The device context to draw onto;
  • wnd – The window which is being drawn onto (not the RibbonPage associated with the tab being drawn);
  • tab – The rectangle within which to draw, and also the tab label, icon, and state (active and/or hovered). The drawing rectangle will be entirely within a rectangle on the same device context previously painted with DrawTabCtrlBackground. The rectangle’s width will be at least the minimum value returned by GetBarTabWidth, and height will be the value returned by GetTabCtrlHeight.

DrawTabCtrlBackground(dc, wnd, rect) [source]

Draw the background of the tab region of a ribbon bar.

Parameters:
  • dc – The device context to draw onto;
  • wnd – The window which is being drawn onto;
  • rect – The rectangle within which to draw.

DrawTabSeparator(dc, wnd, rect, visibility) [source]

Draw a separator between two tabs in a ribbon bar.

Parameters:
  • dc – The device context to draw onto;
  • wnd – The window which is being drawn onto;
  • rect – The rectangle within which to draw, which will be entirely within a rectangle on the same device context previously painted with DrawTabCtrlBackground;
  • visibility – The opacity with which to draw the separator. Values are in the range [0, 1], with 0 being totally transparent, and 1 being totally opaque.

DrawTool(dc, wnd, rect, bitmap, kind, state) [source]

Draw a single tool (for a RibbonToolBar control).

Parameters:
  • dc – The device context to draw onto;
  • wnd – The window which is being drawn onto. In most cases this will be a RibbonToolBar, but it doesn’t have to be;
  • rect – The rectangle within which to draw. The size of this rectangle will at least the size returned by RibbonMSWArtProvider.GetToolSize(), and the height of it will be equal for all tools within the same group. The rectangle will be entirely within a rectangle on the same device context previously painted with DrawToolGroupBackground;
  • bitmap – The bitmap to use as the tool’s foreground. If the tool is a hybrid or dropdown tool, then the foreground should also contain a standard dropdown button;
  • kind – The kind of tool to draw (normal, dropdown, or hybrid);
  • state – A combination of RibbonToolBarToolState flags giving the state of the tool and it’s relative position within a tool group.

DrawToolBarBackground(dc, wnd, rect) [source]

Draw the background for a RibbonToolBar control.

Parameters:
  • dc – The device context to draw onto;
  • wnd – The which is being drawn onto. In most cases this will be a RibbonToolBar, but it doesn’t have to be;
  • rect – The rectangle within which to draw. Some of this rectangle will later be drawn over using DrawToolGroupBackground and DrawTool, but not all of it will (unless there is only a single group of tools).

DrawToolGroupBackground(dc, wnd, rect) [source]

Draw the background for a group of tools on a RibbonToolBar control.

Parameters:
  • dc – The device context to draw onto;
  • wnd – The window which is being drawn onto. In most cases this will be a RibbonToolBar, but it doesn’t have to be;
  • rect – The rectangle within which to draw. This rectangle is a union of the individual tools’ rectangles. As there are no gaps between tools, this rectangle will be painted over exactly once by calls to DrawTool. The group background could therefore be painted by DrawTool, though it can be conceptually easier and more efficient to draw it all at once here. The rectangle will be entirely within a rectangle on the same device context previously painted with DrawToolBarBackground.

GetBarTabWidth(dc, wnd, label, bitmap, ideal=None, small_begin_need_separator=None, small_must_have_separator=None, minimum=None) [source]

Calculate the ideal and minimum width (in pixels) of a tab in a ribbon bar.

Parameters:
  • dc – A device context to use when one is required for size calculations;
  • wnd – The window onto which the tab will eventually be drawn;
  • label – The tab’s label (or an empty string if it has none);
  • bitmap – The tab’s icon (or wx.NullBitmap if it has none);
  • ideal – The ideal width (in pixels) of the tab;
  • small_begin_need_separator – A size less than the size, at which a tab separator should begin to be drawn (i.e. drawn, but still fairly transparent);
  • small_must_have_separator – A size less than the size, at which a tab separator must be drawn (i.e. drawn at full opacity);
  • minimum – A size less than the size, and greater than or equal to zero, which is the minimum pixel width for the tab.

GetColour(id) [source]

Get the value of a certain colour setting.

can be one of the colour values of RibbonArtSetting.

Parameters: id – the colour id.

GetPanelClientSize(dc, wnd, size, client_offset=None) [source]

Calculate the client size of a panel for a given overall size.

This should act as the inverse to GetPanelSize, and decrement the given size by enough to fit the panel label and other chrome.

Parameters:
  • dc – A device context to use if one is required for size calculations;
  • wnd – The ribbon panel in question;
  • size – The overall size to calculate client size for;
  • client_offset – The offset where the returned client size begins within the given (may be None).

See also

GetPanelSize

GetPanelSize(dc, wnd, client_size, client_offset=None) [source]

Calculate the size of a panel for a given client size.

This should increment the given size by enough to fit the panel label and other chrome.

Parameters:
  • dc – A device context to use if one is required for size calculations;
  • wnd – The ribbon panel in question;
  • client_size – The client size;
  • client_offset – The offset where the client rectangle begins within the panel (may be None).

See also

GetPanelClientSize

GetScrollButtonMinimumSize(dc, wnd, style) [source]

Calculate the minimum size (in pixels) of a scroll button.

Parameters:
  • dc – A device context to use when one is required for size calculations;
  • wnd – The window onto which the scroll button will eventually be drawn;
  • style – A combination of flags from RibbonScrollButtonStyle, including a direction, and a for flag (state flags may be given too, but should be ignored, as a button should retain a constant size, regardless of its state).

GetTabCtrlHeight(dc, wnd, pages) [source]

Calculate the height (in pixels) of the tab region of a ribbon bar.

Note that as the tab region can contain scroll buttons, the height should be greater than or equal to the minimum height for a tab scroll button.

Parameters:
  • dc – A device context to use when one is required for size calculations;
  • wnd – The window onto which the tabs will eventually be drawn;
  • pages – The tabs which will acquire the returned height.

SetColour(id, colour) [source]

Set the value of a certain colour setting to the value.

can be one of the colour values of RibbonArtSetting, though not all colour settings will have an affect on every art provider.

Parameters:
  • id – the colour id;
  • colour – MISSING DESCRIPTION.

See also

SetColourScheme

SetColourScheme(primary, secondary, tertiary) [source]

Set all applicable colour settings from a few base colours.

Uses any or all of the three given colours to create a colour scheme, and then sets all colour settings which are relevant to the art provider using that scheme. Note that some art providers may not use the tertiary colour for anything, and some may not use the secondary colour either.

Parameters:
  • primary – MISSING DESCRIPTION;
  • secondary – MISSING DESCRIPTION;
  • tertiary – MISSING DESCRIPTION.

See also

SetColour, RibbonMSWArtProvider.GetColourScheme()

SetFont(id, font) [source]

Set the value of a certain font setting to the value.

can be one of the font values of RibbonArtSetting.

Parameters:
  • id – the font id;
  • font – MISSING DESCRIPTION.

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • infobar
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • ribbon library »
  • ribbon.art_aui »
  • RibbonAUIArtProvider


ribbon.art_aui

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • ribbon library »
  • ribbon.art_aui

ribbon.art_aui

RibbonAUIArtProvider is responsible for drawing all the components of the ribbon interface using an AUI-compatible appearance.

description Description

This allows a ribbon bar to have a pluggable look-and-feel, while retaining the same underlying behaviour. As a single art provider is used for all ribbon components, a ribbon bar usually has a consistent (though unique) appearance.

By default, a RibbonBar uses an instance of a class called RibbonDefaultArtProvider, which resolves to RibbonAUIArtProvider, RibbonMSWArtProvider, or RibbonOSXArtProvider - whichever is most appropriate to the current platform. These art providers are all slightly configurable with regard to colours and fonts, but for larger modifications, you can derive from one of these classes, or write a completely new art provider class.

Call SetArtProvider to change the art provider being used.

link See Also

RibbonBar

Module author: Andrea Gavana <andrea.gavana@gmail.com>

hierarchy Inheritance Diagram

Inheritance diagram for module: ribbon.art_aui

Inheritance diagram of ribbon.art_aui.RibbonAUIArtProvider

SVN Revisions

A graphical representation of the SVN commits in the last year.

Click on any date in the picture to jump to that particular revision page, containing information about committers, log messages and SVN diffs.

Revision Graph For art_aui

2to3 Python 3 Issues (via 2to3)

No issues have been detected by 2to3.py.

Function Summary

  • FontFromFont

Class Summary

  • RibbonAUIArtProvider

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • infobar
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • ribbon library »
  • ribbon.art_aui


ribbon.art_internal functions

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • ribbon library »
  • ribbon.art_internal »
  • ribbon.art_internal functions

ribbon.art_internal functions

This is the description of standalone Python functions in the ribbon.art_internal module.

Functions Summary

RibbonCanLabelBreakAtPosition
RibbonDrawParallelGradientLines
RibbonInterpolateColour
RibbonLoadPixmap
RibbonShiftLuminance

API Functions API

RibbonCanLabelBreakAtPosition(label, pos) [source]

RibbonDrawParallelGradientLines(dc, nlines, line_origins, stepx, stepy, numsteps, offset_x, offset_y, start_colour, end_colour) [source]

RibbonInterpolateColour(start_colour, end_colour, position, start_position, end_position) [source]

RibbonLoadPixmap(bits, fore) [source]

RibbonShiftLuminance(colour, amount) [source]

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • infobar
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • ribbon library »
  • ribbon.art_internal »
  • ribbon.art_internal functions


RibbonHSLColour

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • ribbon library »
  • ribbon.art_internal »
  • RibbonHSLColour

RibbonHSLColour

hierarchy Inheritance Diagram

Inheritance diagram for: RibbonHSLColour

Inheritance diagram of RibbonHSLColour

Methods Summary

__init__
Darker
Desaturated
Lighter
MakeDarker
Saturated
ShiftHue
ToRGB

API Class API

class RibbonHSLColour(object) [source]

__init__(h=0.0, s=0.0, l=0.0) [source]

Darker(delta) [source]

Desaturated(delta) [source]

Lighter(delta) [source]

MakeDarker(delta) [source]

Saturated(delta) [source]

ShiftHue(delta) [source]

ToRGB() [source]

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • infobar
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • ribbon library »
  • ribbon.art_internal »
  • RibbonHSLColour


RibbonPageTabInfo

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • ribbon library »
  • ribbon.art_internal »
  • RibbonPageTabInfo

RibbonPageTabInfo

hierarchy Inheritance Diagram

Inheritance diagram for: RibbonPageTabInfo

Inheritance diagram of RibbonPageTabInfo

Methods Summary

__init__

API Class API

class RibbonPageTabInfo(object) [source]

__init__() [source]

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • infobar
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • ribbon library »
  • ribbon.art_internal »
  • RibbonPageTabInfo


ribbon.art_internal

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • ribbon library »
  • ribbon.art_internal

ribbon.art_internal

This module contains methods used throughout the RibbonBar library.

Module author: Andrea Gavana <andrea.gavana@gmail.com>

hierarchy Inheritance Diagram

Inheritance diagram for module: ribbon.art_internal

Inheritance diagram of ribbon.art_internal.RibbonHSLColour, ribbon.art_internal.RibbonPageTabInfo

SVN Revisions

A graphical representation of the SVN commits in the last year.

Click on any date in the picture to jump to that particular revision page, containing information about committers, log messages and SVN diffs.

Revision Graph For art_internal

2to3 Python 3 Issues (via 2to3)

No issues have been detected by 2to3.py.

Function Summary

  • RibbonCanLabelBreakAtPosition
  • RibbonDrawParallelGradientLines
  • RibbonInterpolateColour
  • RibbonLoadPixmap
  • RibbonShiftLuminance

Class Summary

  • RibbonHSLColour
  • RibbonPageTabInfo

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • infobar
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • ribbon library »
  • ribbon.art_internal


ribbon.art_msw functions

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • ribbon library »
  • ribbon.art_msw »
  • ribbon.art_msw functions

ribbon.art_msw functions

This is the description of standalone Python functions in the ribbon.art_msw module.

Functions Summary

LikePrimary
LikeSecondary
SingleLine

API Functions API

LikePrimary(primary_hsl, is_gray, h, s, l) [source]

LikeSecondary(secondary_hsl, is_gray, h, s, l) [source]

SingleLine(dc, rect, start, finish) [source]

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • infobar
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • ribbon library »
  • ribbon.art_msw »
  • ribbon.art_msw functions


RibbonMSWArtProvider

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • ribbon library »
  • ribbon.art_msw »
  • RibbonMSWArtProvider

RibbonMSWArtProvider

hierarchy Inheritance Diagram

Inheritance diagram for: RibbonMSWArtProvider

Inheritance diagram of RibbonMSWArtProvider

subclasses Known Subclasses

  • ribbon.art_aui.RibbonAUIArtProvider
  • ribbon.art_default.RibbonDefaultArtProvider

Methods Summary

__init__ |
Clone | Create a new art provider which is a clone of this one.
CloneTo |
DrawButtonBarBackground | Draw the background for a RibbonButtonBar control.
DrawButtonBarButton | Draw a single button for a RibbonButtonBar control.
DrawButtonBarButtonForeground |
DrawDropdownArrow |
DrawGalleryBackground | Draw the background and chrome for a RibbonGallery control.
DrawGalleryBackgroundCommon |
DrawGalleryButton |
DrawGalleryItemBackground | Draw the background of a single item in a RibbonGallery control.
DrawMinimisedPanel | Draw a minimised ribbon panel.
DrawMinimisedPanelCommon |
DrawPageBackground | Draw the background of a ribbon page.
DrawPanelBackground | Draw the background and chrome for a ribbon panel.
DrawPanelBorder |
DrawPartialPageBackground |
DrawPartialPageBackground1 |
DrawPartialPageBackground2 |
DrawScrollButton | Draw a ribbon-style scroll button.
DrawTab | Draw a single tab in the tab region of a ribbon bar.
DrawTabCtrlBackground | Draw the background of the tab region of a ribbon bar.
DrawTabSeparator | Draw a separator between two tabs in a ribbon bar.
DrawTool | Draw a single tool (for a RibbonToolBar control).
DrawToolBarBackground | Draw the background for a RibbonToolBar control.
DrawToolGroupBackground | Draw the background for a group of tools on a RibbonToolBar control.
GetBarTabWidth | Calculate the ideal and minimum width (in pixels) of a tab in a ribbon bar.
GetButtonBarButtonSize | Calculate the size of a button within a RibbonButtonBar.
GetColour | Get the value of a certain colour setting.
GetColourScheme | Get the current colour scheme.
GetFlags | Get the previously set style flags.
GetFont | Get the value of a certain font setting.
GetGalleryClientSize | Calculate the client size of a RibbonGallery control for a given size.
GetGallerySize | Calculate the size of a RibbonGallery control for a given client size.
GetMetric | Get the value of a certain integer setting.
GetMinimisedPanelMinimumSize | Calculate the size of a minimised ribbon panel.
GetPageBackgroundRedrawArea | Calculate the portion of a page background which needs to be redrawn when a page is resized.
GetPanelClientSize | Calculate the client size of a panel for a given overall size.
GetPanelSize | Calculate the size of a panel for a given client size.
GetScrollButtonMinimumSize | Calculate the minimum size (in pixels) of a scroll button.
GetTabCtrlHeight | Calculate the height (in pixels) of the tab region of a ribbon bar.
GetToolSize | Calculate the size of a tool within a RibbonToolBar.
ReallyDrawTabSeparator |
Reload |
RemovePanelPadding |
SetColour | Set the value of a certain colour setting to the value.
SetColourScheme | Set all applicable colour settings from a few base colours.
SetFlags | Set the style flags.
SetFont | Set the value of a certain font setting to the value.
SetMetric | Set the value of a certain integer setting to the value.

API Class API

class RibbonMSWArtProvider(object) [source]

__init__(set_colour_scheme=True) [source]

Clone() [source]

Create a new art provider which is a clone of this one.

CloneTo(copy) [source]

DrawButtonBarBackground(dc, wnd, rect) [source]

Draw the background for a RibbonButtonBar control.

Parameters:
  • dc – The device context to draw onto;
  • wnd – The window which is being drawn onto (which will typically be the button bar itself, though this is not guaranteed);
  • rect – The rectangle within which to draw.

DrawButtonBarButton(dc, wnd, rect, kind, state, label, bitmap_large, bitmap_small) [source]

Draw a single button for a RibbonButtonBar control.

Parameters:
  • dc – The device context to draw onto;
  • wnd – The window which is being drawn onto;
  • rect – The rectangle within which to draw. The size of this rectangle will be a size previously returned by GetButtonBarButtonSize, and the rectangle will be entirely within a rectangle on the same device context previously painted with DrawButtonBarBackground;
  • kind – The kind of button to draw (normal, dropdown or hybrid);
  • state – Combination of a size flag and state flags from the RibbonButtonBarButtonState enumeration;
  • label – The label of the button;
  • bitmap_large – The large bitmap of the button (or the large disabled bitmap when RIBBON_BUTTONBAR_BUTTON_DISABLED is set in );
  • bitmap_small – The small bitmap of the button (or the small disabled bitmap when RIBBON_BUTTONBAR_BUTTON_DISABLED is set in ).

DrawButtonBarButtonForeground(dc, rect, kind, state, label, bitmap_large, bitmap_small) [source]

DrawDropdownArrow(dc, x, y, colour) [source]

DrawGalleryBackground(dc, wnd, rect) [source]

Draw the background and chrome for a RibbonGallery control.

This should draw the border, brackground, scroll buttons, extension button, and any other UI elements which are not attached to a specific gallery item.

Parameters:
  • dc – The device context to draw onto;
  • wnd – The window which is being drawn onto, which is always the gallery whose background and chrome is being drawn. Attributes used during drawing like the gallery hover state and individual button states can be queried from this parameter by RibbonGallery.IsHovered(), RibbonGallery.GetExtensionButtonState(), RibbonGallery.GetUpButtonState(), and RibbonGallery.GetDownButtonState();
  • rect – The rectangle within which to draw. This rectangle is the entire area of the gallery control, not just the client rectangle.

DrawGalleryBackgroundCommon(dc, wnd, rect) [source]

DrawGalleryButton(dc, rect, state, bitmaps) [source]

DrawGalleryItemBackground(dc, wnd, rect, item) [source]

Draw the background of a single item in a RibbonGallery control.

This is painted on top of a gallery background, and behind the items bitmap. Unlike DrawButtonBarButton and DrawTool, it is not expected to draw the item bitmap - that is done by the gallery control itself.

Parameters:
  • dc – The device context to draw onto;
  • wnd – The window which is being drawn onto, which is always the gallery which contains the item being drawn;
  • rect – The rectangle within which to draw. The size of this rectangle will be the size of the item’s bitmap, expanded by gallery item padding values (RIBBON_ART_GALLERY_BITMAP_PADDING_LEFT_SIZE, RIBBON_ART_GALLERY_BITMAP_PADDING_RIGHT_SIZE, RIBBON_ART_GALLERY_BITMAP_PADDING_TOP_SIZE, and RIBBON_ART_GALLERY_BITMAP_PADDING_BOTTOM_SIZE). The drawing rectangle will be entirely within a rectangle on the same device context previously painted with DrawGalleryBackground;
  • item – The item whose background is being painted. Typically the background will vary if the item is hovered, active, or selected; RibbonGallery.GetSelection(), RibbonGallery.GetActiveItem(), and RibbonGallery.GetHoveredItem() can be called to test if the given item is in one of these states.

DrawMinimisedPanel(dc, wnd, rect, bitmap) [source]

Draw a minimised ribbon panel.

Parameters:
  • dc – The device context to draw onto;
  • wnd – The window which is being drawn onto, which is always the panel which is minimised. The panel label can be obtained from this window. The minimised icon obtained from querying the window may not be the size requested by GetMinimisedPanelMinimumSize - the argument contains the icon in the requested size;
  • rect – The rectangle within which to draw. The size of the rectangle will be at least the size returned by GetMinimisedPanelMinimumSize;
  • bitmap – A copy of the panel’s minimised bitmap rescaled to the size returned by GetMinimisedPanelMinimumSize.

DrawMinimisedPanelCommon(dc, wnd, true_rect) [source]

DrawPageBackground(dc, wnd, rect) [source]

Draw the background of a ribbon page.

Parameters:
  • dc – The device context to draw onto;
  • wnd – The window which is being drawn onto (which is commonly the RibbonPage whose background is being drawn, but doesn’t have to be);
  • rect – The rectangle within which to draw.

See also

GetPageBackgroundRedrawArea

DrawPanelBackground(dc, wnd, rect) [source]

Draw the background and chrome for a ribbon panel.

This should draw the border, background, label, and any other items of a panel which are outside the client area of a panel. Note that when a panel is minimised, this function is not called - only DrawMinimisedPanel is called, so a background should be explicitly painted by that if required.

Parameters:
  • dc – The device context to draw onto;
  • wnd – The window which is being drawn onto, which is always the panel whose background and chrome is being drawn. The panel label and other panel attributes can be obtained by querying this;
  • rect – The rectangle within which to draw.

DrawPanelBorder(dc, rect, primary_colour, secondary_colour) [source]

DrawPartialPageBackground(dc, wnd, rect, allow_hovered_or_page=True, offset=None, hovered=False) [source]

DrawPartialPageBackground1(dc, wnd, rect, page, offset, hovered=False) [source]

DrawPartialPageBackground2(dc, wnd, rect, allow_hovered=True) [source]

DrawScrollButton(dc, wnd, rect_, style) [source]

Draw a ribbon-style scroll button.

Parameters:
  • dc – The device context to draw onto;
  • wnd – The window which is being drawn onto;
  • rect – The rectangle within which to draw. The size of this rectangle will be at least the size returned by GetScrollButtonMinimumSize for a scroll button with the same style. For tab scroll buttons, this rectangle will be entirely within a rectangle on the same device context previously painted with DrawTabCtrlBackground, but this is not guaranteed for other types of button (for example, page scroll buttons will not be painted on an area previously painted with DrawPageBackground );
  • style – A combination of flags from RibbonScrollButtonStyle, including a direction, a for flag, and one or more states.

DrawTab(dc, wnd, tab) [source]

Draw a single tab in the tab region of a ribbon bar.

Parameters:
  • dc – The device context to draw onto;
  • wnd – The window which is being drawn onto (not the RibbonPage associated with the tab being drawn);
  • tab – The rectangle within which to draw, and also the tab label, icon, and state (active and/or hovered). The drawing rectangle will be entirely within a rectangle on the same device context previously painted with DrawTabCtrlBackground. The rectangle’s width will be at least the minimum value returned by GetBarTabWidth, and height will be the value returned by GetTabCtrlHeight.

DrawTabCtrlBackground(dc, wnd, rect) [source]

Draw the background of the tab region of a ribbon bar.

Parameters:
  • dc – The device context to draw onto;
  • wnd – The window which is being drawn onto;
  • rect – The rectangle within which to draw.

DrawTabSeparator(dc, wnd, rect, visibility) [source]

Draw a separator between two tabs in a ribbon bar.

Parameters:
  • dc – The device context to draw onto;
  • wnd – The window which is being drawn onto;
  • rect – The rectangle within which to draw, which will be entirely within a rectangle on the same device context previously painted with DrawTabCtrlBackground;
  • visibility – The opacity with which to draw the separator. Values are in the range [0, 1], with 0 being totally transparent, and 1 being totally opaque.

DrawTool(dc, wnd, rect, bitmap, kind, state) [source]

Draw a single tool (for a RibbonToolBar control).

Parameters:
  • dc – The device context to draw onto;
  • wnd – The window which is being drawn onto. In most cases this will be a RibbonToolBar, but it doesn’t have to be;
  • rect – The rectangle within which to draw. The size of this rectangle will at least the size returned by GetToolSize, and the height of it will be equal for all tools within the same group. The rectangle will be entirely within a rectangle on the same device context previously painted with DrawToolGroupBackground;
  • bitmap – The bitmap to use as the tool’s foreground. If the tool is a hybrid or dropdown tool, then the foreground should also contain a standard dropdown button;
  • kind – The kind of tool to draw (normal, dropdown, or hybrid);
  • state – A combination of RibbonToolBarToolState flags giving the state of the tool and it’s relative position within a tool group.

DrawToolBarBackground(dc, wnd, rect) [source]

Draw the background for a RibbonToolBar control.

Parameters:
  • dc – The device context to draw onto;
  • wnd – The which is being drawn onto. In most cases this will be a RibbonToolBar, but it doesn’t have to be;
  • rect – The rectangle within which to draw. Some of this rectangle will later be drawn over using DrawToolGroupBackground and DrawTool, but not all of it will (unless there is only a single group of tools).

DrawToolGroupBackground(dc, wnd, rect) [source]

Draw the background for a group of tools on a RibbonToolBar control.

Parameters:
  • dc – The device context to draw onto;
  • wnd – The window which is being drawn onto. In most cases this will be a RibbonToolBar, but it doesn’t have to be;
  • rect – The rectangle within which to draw. This rectangle is a union of the individual tools’ rectangles. As there are no gaps between tools, this rectangle will be painted over exactly once by calls to DrawTool. The group background could therefore be painted by DrawTool, though it can be conceptually easier and more efficient to draw it all at once here. The rectangle will be entirely within a rectangle on the same device context previously painted with DrawToolBarBackground.

GetBarTabWidth(dc, wnd, label, bitmap, ideal=None, small_begin_need_separator=None, small_must_have_separator=None, minimum=None) [source]

Calculate the ideal and minimum width (in pixels) of a tab in a ribbon bar.

Parameters:
  • dc – A device context to use when one is required for size calculations;
  • wnd – The window onto which the tab will eventually be drawn;
  • label – The tab’s label (or “” if it has none);
  • bitmap – The tab’s icon (or wx.NullBitmap if it has none);
  • ideal – The ideal width (in pixels) of the tab;
  • small_begin_need_separator – A size less than the size, at which a tab separator should begin to be drawn (i.e. drawn, but still fairly transparent);
  • small_must_have_separator – A size less than the size, at which a tab separator must be drawn (i.e. drawn at full opacity);
  • minimum – A size less than the size, and greater than or equal to zero, which is the minimum pixel width for the tab.

GetButtonBarButtonSize(dc, wnd, kind, size, label, bitmap_size_large, bitmap_size_small, button_size=None, normal_region=None, dropdown_region=None) [source]

Calculate the size of a button within a RibbonButtonBar.

Parameters:
  • dc – A device context to use when one is required for size calculations;
  • wnd – The window onto which the button will eventually be drawn (which is normally a RibbonButtonBar, though this is not guaranteed);
  • kind – The kind of button;
  • size – The size-class to calculate the size for. Buttons on a button bar can have three distinct sizes: RIBBON_BUTTONBAR_BUTTON_SMALL, RIBBON_BUTTONBAR_BUTTON_MEDIUM, and RIBBON_BUTTONBAR_BUTTON_LARGE. If the requested size-class is not applicable, then False should be returned;
  • label – The label of the button;
  • bitmap_size_large – The size of all “large” bitmaps on the button bar;
  • bitmap_size_small – The size of all “small” bitmaps on the button bar;
  • button_size – The size, in pixels, of the button;
  • normal_region – The region of the button which constitutes the normal button;
  • dropdown_region – The region of the button which constitutes the dropdown button.
Returns:

True if a size exists for the button, False otherwise.

GetColour(id) [source]

Get the value of a certain colour setting.

can be one of the colour values of RibbonArtSetting.

Parameters: id – the colour id.

GetColourScheme(primary, secondary, tertiary) [source]

Get the current colour scheme.

Returns three colours such that if SetColourScheme were called with them, the colour scheme would be restored to what it was when SetColourScheme was last called. In practice, this usually means that the returned values are the three colours given in the last call to SetColourScheme, however if SetColourScheme performs an idempotent operation upon the colours it is given (like clamping a component of the colour), then the returned values may not be the three colours given in the last call to SetColourScheme.

If SetColourScheme has not been called, then the returned values should result in a colour scheme similar to, if not identical to, the default colours of the art provider. Note that if SetColour is called, then GetColourScheme does not try and return a colour scheme similar to colours being used - it’s return values are dependant upon the last values given to SetColourScheme, as described above.

Parameters:
  • primary – Pointer to a location to store the primary colour, or None;
  • secondary – Pointer to a location to store the secondary colour, or None;
  • tertiary – Pointer to a location to store the tertiary colour, or None.

GetFlags() [source]

Get the previously set style flags.

GetFont(id) [source]

Get the value of a certain font setting.

can be one of the font values of RibbonArtSetting.

Parameters: id – the font id.

GetGalleryClientSize(dc, wnd, size, client_offset=None, scroll_up_button=None, scroll_down_button=None, extension_button=None) [source]

Calculate the client size of a RibbonGallery control for a given size.

This should act as the inverse to GetGallerySize, and decrement the given size by enough to fir the gallery border, buttons, and other chrome.

Parameters:
  • dc – A device context to use if one is required for size calculations;
  • wnd – The gallery in question;
  • size – The overall size to calculate the client size for;
  • client_offset – The position within the given size at which the returned client size begins;
  • scroll_up_button – The rectangle within the given size which the scroll up button occupies;
  • scroll_down_button – The rectangle within the given size which the scroll down button occupies;
  • extension_button – The rectangle within the given size which the extension button occupies.

GetGallerySize(dc, wnd, client_size) [source]

Calculate the size of a RibbonGallery control for a given client size.

This should increment the given size by enough to fit the gallery border, buttons, and any other chrome.

Parameters:
  • dc – A device context to use if one is required for size calculations;
  • wnd – The gallery in question;
  • client_size – The client size.

See also

GetGalleryClientSize

GetMetric(id) [source]

Get the value of a certain integer setting.

can be one of the size values of RibbonArtSetting.

Parameters: id – a metric id.

GetMinimisedPanelMinimumSize(dc, wnd, desired_bitmap_size=None, expanded_panel_direction=None) [source]

Calculate the size of a minimised ribbon panel.

Parameters:
  • dc – A device context to use when one is required for size calculations;
  • wnd – The ribbon panel in question. Attributes like the panel label can be queried from this;
  • desired_bitmap_size – MISSING DESCRIPTION;
  • expanded_panel_direction – MISSING DESCRIPTION.

GetPageBackgroundRedrawArea(dc, wnd, page_old_size, page_new_size) [source]

Calculate the portion of a page background which needs to be redrawn when a page is resized.

To optimise the drawing of page backgrounds, as small an area as possible should be returned. Of couse, if the way in which a background is drawn means that the entire background needs to be repainted on resize, then the entire new size should be returned.

Parameters:
  • dc – A device context to use when one is required for size calculations;
  • wnd – The page which is being resized;
  • page_old_size – The size of the page prior to the resize (which has already been painted);
  • page_new_size – The size of the page after the resize.

GetPanelClientSize(dc, wnd, size, client_offset=None) [source]

Calculate the client size of a panel for a given overall size.

This should act as the inverse to GetPanelSize, and decrement the given size by enough to fit the panel label and other chrome.

Parameters:
  • dc – A device context to use if one is required for size calculations;
  • wnd – The ribbon panel in question;
  • size – The overall size to calculate client size for;
  • client_offset – The offset where the returned client size begins within the given (may be None).

See also

GetPanelSize

GetPanelSize(dc, wnd, client_size, client_offset=None) [source]

Calculate the size of a panel for a given client size.

This should increment the given size by enough to fit the panel label and other chrome.

Parameters:
  • dc – A device context to use if one is required for size calculations;
  • wnd – The ribbon panel in question;
  • client_size – The client size;
  • client_offset – The offset where the client rectangle begins within the panel (may be None).

See also

GetPanelClientSize

GetScrollButtonMinimumSize(dc, wnd, style) [source]

Calculate the minimum size (in pixels) of a scroll button.

Parameters:
  • dc – A device context to use when one is required for size calculations;
  • wnd – The window onto which the scroll button will eventually be drawn;
  • style – A combination of flags from RibbonScrollButtonStyle, including a direction, and a for flag (state flags may be given too, but should be ignored, as a button should retain a constant size, regardless of its state).

GetTabCtrlHeight(dc, wnd, pages) [source]

Calculate the height (in pixels) of the tab region of a ribbon bar.

Note that as the tab region can contain scroll buttons, the height should be greater than or equal to the minimum height for a tab scroll button.

Parameters:
  • dc – A device context to use when one is required for size calculations;
  • wnd – The window onto which the tabs will eventually be drawn;
  • pages – The tabs which will acquire the returned height.

GetToolSize(dc, wnd, bitmap_size, kind, is_first, is_last, dropdown_region=None) [source]

Calculate the size of a tool within a RibbonToolBar.

Parameters:
  • dc – A device context to use when one is required for size calculations;
  • wnd – The window onto which the tool will eventually be drawn;
  • bitmap_size – The size of the tool’s foreground bitmap;
  • kind – The kind of tool (normal, dropdown, or hybrid);
  • is_first – True if the tool is the first within its group. False otherwise;
  • is_last – True if the tool is the last within its group. False otherwise;
  • dropdown_region – For dropdown and hybrid tools, the region within the returned size which counts as the dropdown part.

ReallyDrawTabSeparator(wnd, rect, visibility) [source]

Reload(setting) [source]

RemovePanelPadding(rect) [source]

SetColour(id, colour) [source]

Set the value of a certain colour setting to the value.

can be one of the colour values of RibbonArtSetting, though not all colour settings will have an affect on every art provider.

Parameters:
  • id – the colour id;
  • colour – the colour.

See also

SetColourScheme

SetColourScheme(primary, secondary, tertiary) [source]

Set all applicable colour settings from a few base colours.

Uses any or all of the three given colours to create a colour scheme, and then sets all colour settings which are relevant to the art provider using that scheme. Note that some art providers may not use the tertiary colour for anything, and some may not use the secondary colour either.

Parameters:
  • primary – MISSING DESCRIPTION;
  • secondary – MISSING DESCRIPTION;
  • tertiary – MISSING DESCRIPTION.

See also

SetColour, GetColourScheme

SetFlags(flags) [source]

Set the style flags.

Normally called automatically by RibbonBar.SetArtProvider() with the ribbon bar’s style flags, so that the art provider has the same flags as the bar which it is serving.

Parameters: flags – MISSING DESCRIPTION.

SetFont(id, font) [source]

Set the value of a certain font setting to the value.

can be one of the font values of RibbonArtSetting.

Parameters:
  • id – a font id;
  • font – the new font.

SetMetric(id, new_val) [source]

Set the value of a certain integer setting to the value.

can be one of the size values of RibbonArtSetting.

Parameters:
  • id – a metric id;
  • new_val – the new value of the metric setting.

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • infobar
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • ribbon library »
  • ribbon.art_msw »
  • RibbonMSWArtProvider


ribbon.art_msw

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • ribbon library »
  • ribbon.art_msw

ribbon.art_msw

RibbonMSWArtProvider is responsible for drawing all the components of the ribbon interface using a Windows appearance.

description Description

This allows a ribbon bar to have a pluggable look-and-feel, while retaining the same underlying behaviour. As a single art provider is used for all ribbon components, a ribbon bar usually has a consistent (though unique) appearance.

By default, a RibbonBar uses an instance of a class called RibbonDefaultArtProvider, which resolves to RibbonAUIArtProvider, RibbonMSWArtProvider, or RibbonOSXArtProvider - whichever is most appropriate to the current platform. These art providers are all slightly configurable with regard to colours and fonts, but for larger modifications, you can derive from one of these classes, or write a completely new art provider class.

Call SetArtProvider to change the art provider being used.

link See Also

RibbonBar

Module author: Andrea Gavana <andrea.gavana@gmail.com>

hierarchy Inheritance Diagram

Inheritance diagram for module: ribbon.art_msw

Inheritance diagram of ribbon.art_msw.RibbonMSWArtProvider

SVN Revisions

A graphical representation of the SVN commits in the last year.

Click on any date in the picture to jump to that particular revision page, containing information about committers, log messages and SVN diffs.

Revision Graph For art_msw

2to3 Python 3 Issues (via 2to3)

No issues have been detected by 2to3.py.

Function Summary

  • LikePrimary
  • LikeSecondary
  • SingleLine

Class Summary

  • RibbonMSWArtProvider

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • infobar
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • ribbon library »
  • ribbon.art_msw


ribbon.bar functions

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • ribbon library »
  • ribbon.bar »
  • ribbon.bar functions

ribbon.bar functions

This is the description of standalone Python functions in the ribbon.bar module.

Functions Summary

SET_FLAG
UNSET_FLAG

API Functions API

SET_FLAG(variable, flag) [source]

UNSET_FLAG(variable, flag) [source]

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • infobar
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • ribbon library »
  • ribbon.bar »
  • ribbon.bar functions


RibbonBar

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • ribbon library »
  • ribbon.bar »
  • RibbonBar

RibbonBar

hierarchy Inheritance Diagram

Inheritance diagram for: RibbonBar

Inheritance diagram of RibbonBar

supclasses Known Superclasses

  • ribbon.control.RibbonControl

appearance Control Appearance

RibbonBar

Methods Summary

__init__ | Default constructor.
AddPage |
CommonInit |
DismissExpandedPanel | Dismiss the expanded panel of the currently active page.
DoEraseBackground |
DoGetBestSize |
DoMouseButtonCommon |
GetAGWWindowStyleFlag | Returns the RibbonBar window style flag.
GetActivePage | Get the index of the active page.
GetDefaultBorder |
GetPage | Get a page by index.
HasMultiplePages |
HitTestTabs |
OnEraseBackground |
OnMouseDoubleClick |
OnMouseLeave |
OnMouseLeftDown |
OnMouseLeftUp |
OnMouseMiddleDown |
OnMouseMiddleUp |
OnMouseMove |
OnMouseRightDown |
OnMouseRightUp |
OnPaint |
OnSize |
OrderPageTabInfoBySmallWidthAsc |
Realize | Perform initial layout and size calculations of the bar and its children.
RecalculateMinSize |
RecalculateTabSizes |
RefreshTabBar |
RepositionPage |
ScrollTabBar |
SetAGWWindowStyleFlag | Sets the window style for RibbonBar.
SetActivePage | See comments on SetActivePageByIndex and SetActivePageByPage.
SetActivePageByIndex | Set the active page by index, without triggering any events.
SetActivePageByPage | Set the active page, without triggering any events.
SetArtProvider | Set the art provider to be used be the ribbon bar.
SetTabCtrlMargins | Set the margin widths (in pixels) on the left and right sides of the tab bar region of the ribbon bar.
ShowPanels | Shows or hides the panels inside RibbonBar.

API Class API

class RibbonBar(RibbonControl) [source]

__init__(parent, id=wx.ID_ANY, pos=wx.DefaultPosition, size=wx.DefaultSize, agwStyle=RIBBON_BAR_DEFAULT_STYLE, validator=wx.DefaultValidator, name="RibbonBar") [source]

Default constructor.

Parameters:
  • parent – Pointer to a parent window;
  • id – Window identifier. If wx.ID_ANY, will automatically create an identifier;
  • pos – Window position. wx.DefaultPosition indicates that wxPython should generate a default position for the window;
  • 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;
  • agwStyle – the AGW-specific window style. This can be a combination of the following bits:

    Window Styles | Hex Value | Description
    RIBBON_BAR_DEFAULT_STYLE | 0x9 | Defined as RIBBON_BAR_FLOW_HORIZONTAL | RIBBON_BAR_SHOW_PAGE_LABELS | RIBBON_BAR_SHOW_PANEL_EXT_BUTTONS
    RIBBON_BAR_FOLDBAR_STYLE | 0x1e | Defined as RIBBON_BAR_FLOW_VERTICAL | RIBBON_BAR_SHOW_PAGE_ICONS | RIBBON_BAR_SHOW_PANEL_EXT_BUTTONS | RIBBON_BAR_SHOW_PANEL_MINIMISE_BUTTONS
    RIBBON_BAR_SHOW_PAGE_LABELS | 0x1 | Causes labels to be shown on the tabs in the ribbon bar.
    RIBBON_BAR_SHOW_PAGE_ICONS | 0x2 | Causes icons to be shown on the tabs in the ribbon bar.
    RIBBON_BAR_FLOW_HORIZONTAL | 0x0 | Causes panels within pages to stack horizontally.
    RIBBON_BAR_FLOW_VERTICAL | 0x4 | Causes panels within pages to stack vertically.
    RIBBON_BAR_SHOW_PANEL_EXT_BUTTONS | 0x8 | Causes extension buttons to be shown on panels (where the panel has such a button).
    RIBBON_BAR_SHOW_PANEL_MINIMISE_BUTTONS | 0x10 | Causes minimise buttons to be shown on panels (where the panel has such a button).
  • validator – the window validator;
  • name – the window name.

AddPage(page) [source]

CommonInit(agwStyle) [source]

DismissExpandedPanel() [source]

Dismiss the expanded panel of the currently active page.

Calls and returns the value from RibbonPage.DismissExpandedPanel() for the currently active page, or False if there is no active page.

DoEraseBackground(dc) [source]

DoGetBestSize() [source]

DoMouseButtonCommon(event, tab_event_type) [source]

GetAGWWindowStyleFlag() [source]

Returns the RibbonBar window style flag.

See also

SetAGWWindowStyleFlag for a list of valid window styles.

GetActivePage() [source]

Get the index of the active page.

In the rare case of no page being active, -1 is returned.

GetDefaultBorder() [source]

GetPage(n) [source]

Get a page by index.

None will be returned if the given index is out of range.

Parameters: n – MISSING DESCRIPTION.

HasMultiplePages() [source]

HitTestTabs(position) [source]

OnEraseBackground(event) [source]

OnMouseDoubleClick(event) [source]

OnMouseLeave(event) [source]

OnMouseLeftDown(event) [source]

OnMouseLeftUp(event) [source]

OnMouseMiddleDown(event) [source]

OnMouseMiddleUp(event) [source]

OnMouseMove(event) [source]

OnMouseRightDown(event) [source]

OnMouseRightUp(event) [source]

OnPaint(event) [source]

OnSize(event) [source]

OrderPageTabInfoBySmallWidthAsc(first, second) [source]

Realize() [source]

Perform initial layout and size calculations of the bar and its children.

This must be called after all of the bar’s children have been created (and their children created, etc.) - if it is not, then windows may not be laid out or sized correctly. Also calls RibbonPage.Realize() on each child page.

Reimplemented from RibbonControl.

RecalculateMinSize() [source]

RecalculateTabSizes() [source]

RefreshTabBar() [source]

RepositionPage(page) [source]

ScrollTabBar(amount) [source]

SetAGWWindowStyleFlag(agwStyle) [source]

Sets the window style for RibbonBar.

Parameters: agwStyle – can be a combination of the following bits:

Window Styles | Hex Value | Description
RIBBON_BAR_DEFAULT_STYLE | 0x9 | Defined as RIBBON_BAR_FLOW_HORIZONTAL | RIBBON_BAR_SHOW_PAGE_LABELS | RIBBON_BAR_SHOW_PANEL_EXT_BUTTONS
RIBBON_BAR_FOLDBAR_STYLE | 0x1e | Defined as RIBBON_BAR_FLOW_VERTICAL | RIBBON_BAR_SHOW_PAGE_ICONS | RIBBON_BAR_SHOW_PANEL_EXT_BUTTONS | RIBBON_BAR_SHOW_PANEL_MINIMISE_BUTTONS
RIBBON_BAR_SHOW_PAGE_LABELS | 0x1 | Causes labels to be shown on the tabs in the ribbon bar.
RIBBON_BAR_SHOW_PAGE_ICONS | 0x2 | Causes icons to be shown on the tabs in the ribbon bar.
RIBBON_BAR_FLOW_HORIZONTAL | 0x0 | Causes panels within pages to stack horizontally.
RIBBON_BAR_FLOW_VERTICAL | 0x4 | Causes panels within pages to stack vertically.
RIBBON_BAR_SHOW_PANEL_EXT_BUTTONS | 0x8 | Causes extension buttons to be shown on panels (where the panel has such a button).
RIBBON_BAR_SHOW_PANEL_MINIMISE_BUTTONS | 0x10 | Causes minimise buttons to be shown on panels (where the panel has such a button).

Note

Please note that some styles cannot be changed after the window creation and that Refresh() might need to be be called after changing the others for the change to take place immediately.

SetActivePage(page) [source]

See comments on SetActivePageByIndex and SetActivePageByPage.

SetActivePageByIndex(page) [source]

Set the active page by index, without triggering any events.

Parameters: page – The zero-based index of the page to activate.
Returns: True if the specified page is now active, False if it could not be activated (for example because the page index is invalid).

SetActivePageByPage(page) [source]

Set the active page, without triggering any events.

Parameters: page – The page to activate.
Returns: True if the specified page is now active, False if it could not be activated (for example because the given page is not a child of the ribbon bar).

SetArtProvider(art) [source]

Set the art provider to be used be the ribbon bar.

Also sets the art provider on all current RibbonPage children, and any RibbonPage children added in the future.

Note that unlike most other ribbon controls, the ribbon bar creates a default art provider when initialised, so an explicit call to SetArtProvider is not required if the default art provider is sufficient. Also unlike other ribbon controls, the ribbon bar takes ownership of the given pointer, and will delete it when the art provider is changed or the bar is destroyed.

If this behaviour is not desired, then clone the art provider before setting it.

Reimplemented from RibbonControl.

Parameters: art – MISSING DESCRIPTION.

SetTabCtrlMargins(left, right) [source]

Set the margin widths (in pixels) on the left and right sides of the tab bar region of the ribbon bar.

These margins will be painted with the tab background, but tabs and scroll buttons will never be painted in the margins. The left margin could be used for rendering something equivalent to the “Office Button”, though this is not currently implemented. The right margin could be used for rendering a help button, and/or MDI buttons, but again, this is not currently implemented.

Parameters:
  • left – MISSING DESCRIPTION;
  • right – MISSING DESCRIPTION.

ShowPanels(show=True) [source]

Shows or hides the panels inside RibbonBar.

Parameters: show – True to show the panels, False to hide them.

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • infobar
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • ribbon library »
  • ribbon.bar »
  • RibbonBar


RibbonBarEvent

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • ribbon library »
  • ribbon.bar »
  • RibbonBarEvent

RibbonBarEvent

Event used to indicate various actions relating to a RibbonBar.

See RibbonBar for available event types.

hierarchy Inheritance Diagram

Inheritance diagram for: RibbonBarEvent

Inheritance diagram of RibbonBarEvent

Methods Summary

__init__ |
Allow |
GetPage | Returns the page being changed to, or being clicked on.
IsAllowed |
SetPage | Sets the page relating to this event.
Veto |

API Class API

class RibbonBarEvent(wx.NotifyEvent) [source]

Event used to indicate various actions relating to a RibbonBar.

See RibbonBar for available event types.

__init__(command_type=None, win_id=0, page=None) [source]

Allow() [source]

GetPage() [source]

Returns the page being changed to, or being clicked on.

IsAllowed() [source]

SetPage(page) [source]

Sets the page relating to this event.

Parameters: page – MISSING DESCRIPTION.

Veto() [source]

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • infobar
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • ribbon library »
  • ribbon.bar »
  • RibbonBarEvent


ribbon.bar

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • ribbon library »
  • ribbon.bar

ribbon.bar

Top-level control in a ribbon user interface.

description Description

Serves as a tabbed container for RibbonPage - a ribbon user interface typically has a ribbon bar, which contains one or more RibbonPages, which in turn each contains one or more RibbonPanels, which in turn contain controls. While a RibbonBar has tabs similar to a wx.Notebook, it does not follow the same API for adding pages. Containers like wx.Notebook can contain any type of window as a page, hence the normal procedure is to create the sub-window and then call wx.BookCtrlBase.AddPage().

As RibbonBar can only have RibbonPage as children (and a RibbonPage can only have a RibbonBar as parent), when a page is created, it is automatically added to the bar - there is no AddPage equivalent to call.

After all pages have been created, and all controls and panels placed on those pages, Realize must be called.

styles Window Styles

This class supports the following window styles:

Window styles for ribbon.bar
Window Styles | Hex Value | Description
RIBBON_BAR_DEFAULT_STYLE | 0x9 | Defined as RIBBON_BAR_FLOW_HORIZONTAL | RIBBON_BAR_SHOW_PAGE_LABELS | RIBBON_BAR_SHOW_PANEL_EXT_BUTTONS
RIBBON_BAR_FOLDBAR_STYLE | 0x1e | Defined as RIBBON_BAR_FLOW_VERTICAL | RIBBON_BAR_SHOW_PAGE_ICONS | RIBBON_BAR_SHOW_PANEL_EXT_BUTTONS | RIBBON_BAR_SHOW_PANEL_MINIMISE_BUTTONS
RIBBON_BAR_SHOW_PAGE_LABELS | 0x1 | Causes labels to be shown on the tabs in the ribbon bar.
RIBBON_BAR_SHOW_PAGE_ICONS | 0x2 | Causes icons to be shown on the tabs in the ribbon bar.
RIBBON_BAR_FLOW_HORIZONTAL | 0x0 | Causes panels within pages to stack horizontally.
RIBBON_BAR_FLOW_VERTICAL | 0x4 | Causes panels within pages to stack vertically.
RIBBON_BAR_SHOW_PANEL_EXT_BUTTONS | 0x8 | Causes extension buttons to be shown on panels (where the panel has such a button).
RIBBON_BAR_SHOW_PANEL_MINIMISE_BUTTONS | 0x10 | Causes minimise buttons to be shown on panels (where the panel has such a button).

events Events Processing

This class processes the following events:

Events processing for ribbon.bar
Event Name | Description
EVT_RIBBONBAR_PAGE_CHANGED | Triggered after the transition from one page being active to a different page being active.
EVT_RIBBONBAR_PAGE_CHANGING | Triggered prior to the transition from one page being active to a different page being active, and can veto the change.
EVT_RIBBONBAR_TAB_MIDDLE_DOWN | Triggered when the middle mouse button is pressed on a tab.
EVT_RIBBONBAR_TAB_MIDDLE_UP | Triggered when the middle mouse button is released on a tab.
EVT_RIBBONBAR_TAB_RIGHT_DOWN | Triggered when the right mouse button is pressed on a tab.
EVT_RIBBONBAR_TAB_RIGHT_UP | Triggered when the right mouse button is released on a tab.
EVT_RIBBONBAR_TAB_LEFT_DCLICK | Triggered when the user double-clicks on a tab.

link See Also

RibbonPage, RibbonPanel

Module author: Andrea Gavana <andrea.gavana@gmail.com>

hierarchy Inheritance Diagram

Inheritance diagram for module: ribbon.bar

Inheritance diagram of ribbon.bar.RibbonBar, ribbon.bar.RibbonBarEvent

SVN Revisions

A graphical representation of the SVN commits in the last year.

Click on any date in the picture to jump to that particular revision page, containing information about committers, log messages and SVN diffs.

Revision Graph For bar

2to3 Python 3 Issues (via 2to3)

No issues have been detected by 2to3.py.

Function Summary

  • SET_FLAG
  • UNSET_FLAG

Class Summary

  • RibbonBar
  • RibbonBarEvent

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • infobar
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • ribbon library »
  • ribbon.bar


RibbonButtonBar

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • ribbon library »
  • ribbon.buttonbar »
  • RibbonButtonBar

RibbonButtonBar

hierarchy Inheritance Diagram

Inheritance diagram for: RibbonButtonBar

Inheritance diagram of RibbonButtonBar

supclasses Known Superclasses

  • ribbon.control.RibbonControl

appearance Control Appearance

RibbonButtonBar

Methods Summary

__init__ | Default class constructor.
AddButton | Add a button to the button bar.
AddDropdownButton | Add a dropdown button to the button bar (simple version).
AddHybridButton | Add a hybrid button to the button bar (simple version).
AddSimpleButton | Add a button to the button bar (simple version).
AddToggleButton | Add a toggle button to the button bar.
ClearButtons | Delete all buttons from the button bar.
CommonInit |
DeleteButton | Delete a single button from the button bar.
DoGetBestSize |
DoGetNextLargerSize |
DoGetNextSmallerSize |
EnableButton | Enable or disable a single button on the bar.
FetchButtonSizeInfo |
GetDefaultBorder |
GetMinSize |
IsButtonEnabled | Returns whether a button in the bar is enabled or not.
IsSizingContinuous |
MakeDisabledBitmap |
MakeLayouts |
MakeResizedBitmap |
OnEraseBackground |
OnMouseDown |
OnMouseEnter |
OnMouseLeave |
OnMouseMove |
OnMouseUp |
OnPaint |
OnSize |
Realize | Calculate button layouts and positions.
SetArtProvider |
ToggleButton | Toggles/untoggles a RibbonButtonBar toggle button.
TryCollapseLayout |

API Class API

class RibbonButtonBar(RibbonControl) [source]

__init__(parent, id=wx.ID_ANY, pos=wx.DefaultPosition, size=wx.DefaultSize, agwStyle=0) [source]

Default class constructor.

Parameters:
  • parent – pointer to a parent window;
  • id – window identifier. If wx.ID_ANY, will automatically create an identifier;
  • pos – window position. wx.DefaultPosition indicates that wxPython should generate a default position for the window;
  • 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;
  • agwStyle – the AGW-specific window style.

AddButton(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) [source]

Add a button to the button bar.

Parameters:
  • button_id – ID of the new button (used for event callbacks);
  • label – label of the new button;
  • bitmap – large bitmap of the new button. Must be the same size as all other large bitmaps used on the button bar;
  • bitmap_small – small bitmap of the new button. If left as None, then a small bitmap will be automatically generated. Must be the same size as all other small bitmaps used on the button bar;
  • bitmap_disabled – large bitmap of the new button when it is disabled. If left as None, then a bitmap will be automatically generated from bitmap;
  • bitmap_small_disabled – small bitmap of the new button when it is disabled. If left as None, then a bitmap will be automatically generated from bitmap_small;
  • kind – the kind of button to add;
  • help_string – the UI help string to associate with the new button;
  • client_data – client data to associate with the new button.
Returns:

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

See also

AddDropdownButton, AddHybridButton

AddDropdownButton(button_id, label, bitmap, help_string='') [source]

Add a dropdown button to the button bar (simple version).

Parameters:
  • button_id – ID of the button;
  • label – label of the new button;
  • bitmap – large bitmap of the new button. Must be the same size as all other large bitmaps used on the button bar;
  • help_string – the UI help string to associate with the new button.

See also

AddButton

AddHybridButton(button_id, label, bitmap, help_string='') [source]

Add a hybrid button to the button bar (simple version).

Parameters:
  • button_id – ID of the button;
  • label – label of the new button;
  • bitmap – large bitmap of the new button. Must be the same size as all other large bitmaps used on the button bar;
  • help_string – the UI help string to associate with the new button.

See also

AddButton

AddSimpleButton(button_id, label, bitmap, help_string, kind=RIBBON_BUTTON_NORMAL) [source]

Add a button to the button bar (simple version).

Parameters:
  • button_id – ID of the button;
  • label – label of the new button;
  • bitmap – large bitmap of the new button. Must be the same size as all other large bitmaps used on the button bar;
  • help_string – the UI help string to associate with the new button;
  • kind – The kind of button to add.

AddToggleButton(button_id, label, bitmap, help_string='') [source]

Add a toggle button to the button bar.

Parameters:
  • button_id – ID of the button;
  • label – label of the new button;
  • bitmap – large bitmap of the new button. Must be the same size as all other large bitmaps used on the button bar;
  • help_string – the UI help string to associate with the new button.

See also

AddButton

ClearButtons() [source]

Delete all buttons from the button bar.

See also

DeleteButton

CommonInit(agwStyle) [source]

DeleteButton(button_id) [source]

Delete a single button from the button bar.

Parameters: button_id – ID of the button to delete.

See also

ClearButtons

DoGetBestSize() [source]

DoGetNextLargerSize(direction, _result) [source]

DoGetNextSmallerSize(direction, _result) [source]

EnableButton(button_id, enable=True) [source]

Enable or disable a single button on the bar.

Parameters:
  • button_id – ID of the button to enable or disable;
  • enable – True to enable the button, False to disable it.

FetchButtonSizeInfo(button, size, dc) [source]

GetDefaultBorder() [source]

GetMinSize() [source]

IsButtonEnabled(button_id) [source]

Returns whether a button in the bar is enabled or not.

Parameters: button_id – ID of the button to check.

IsSizingContinuous() [source]

MakeDisabledBitmap(original) [source]

MakeLayouts() [source]

MakeResizedBitmap(original, size) [source]

OnEraseBackground(event) [source]

OnMouseDown(event) [source]

OnMouseEnter(event) [source]

OnMouseLeave(event) [source]

OnMouseMove(event) [source]

OnMouseUp(event) [source]

OnPaint(event) [source]

OnSize(event) [source]

Realize() [source]

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 RibbonBar.Realize() is called.

Note

Reimplemented from RibbonControl.

SetArtProvider(art) [source]

ToggleButton(button_id, checked=True) [source]

Toggles/untoggles a RibbonButtonBar toggle button.

Parameters:
  • button_id – ID of the button to be toggles/untoggled;
  • checked – True to toggle the button, False to untoggle it.

TryCollapseLayout(original, first_btn, last_button=None) [source]

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • infobar
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • ribbon library »
  • ribbon.buttonbar »
  • RibbonButtonBar


RibbonButtonBarButtonBase

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • ribbon library »
  • ribbon.buttonbar »
  • RibbonButtonBarButtonBase

RibbonButtonBarButtonBase

hierarchy Inheritance Diagram

Inheritance diagram for: RibbonButtonBarButtonBase

Inheritance diagram of RibbonButtonBarButtonBase

Methods Summary

__init__
GetLargestSize
GetSmallerSize
NewInstance

API Class API

class RibbonButtonBarButtonBase(object) [source]

__init__() [source]

GetLargestSize() [source]

GetSmallerSize(size, n=1) [source]

NewInstance() [source]

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • infobar
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • ribbon library »
  • ribbon.buttonbar »
  • RibbonButtonBarButtonBase


RibbonButtonBarButtonInstance

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • ribbon library »
  • ribbon.buttonbar »
  • RibbonButtonBarButtonInstance

RibbonButtonBarButtonInstance

hierarchy Inheritance Diagram

Inheritance diagram for: RibbonButtonBarButtonInstance

Inheritance diagram of RibbonButtonBarButtonInstance

Methods Summary

__init__

API Class API

class RibbonButtonBarButtonInstance(object) [source]

__init__() [source]

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • infobar
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • ribbon library »
  • ribbon.buttonbar »
  • RibbonButtonBarButtonInstance


RibbonButtonBarButtonSizeInfo

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • ribbon library »
  • ribbon.buttonbar »
  • RibbonButtonBarButtonSizeInfo

RibbonButtonBarButtonSizeInfo

hierarchy Inheritance Diagram

Inheritance diagram for: RibbonButtonBarButtonSizeInfo

Inheritance diagram of RibbonButtonBarButtonSizeInfo

Methods Summary

__init__

API Class API

class RibbonButtonBarButtonSizeInfo(object) [source]

__init__() [source]

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • infobar
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • ribbon library »
  • ribbon.buttonbar »
  • RibbonButtonBarButtonSizeInfo


RibbonButtonBarEvent

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • ribbon library »
  • ribbon.buttonbar »
  • RibbonButtonBarEvent

RibbonButtonBarEvent

Event used to indicate various actions relating to a button on a RibbonButtonBar.

See RibbonButtonBar for available event types.

hierarchy Inheritance Diagram

Inheritance diagram for: RibbonButtonBarEvent

Inheritance diagram of RibbonButtonBarEvent

Methods Summary

__init__ |
GetBar | Returns the bar which contains the button which the event relates to.
PopupMenu | Display a popup menu as a result of this (dropdown clicked) event.
SetBar | Sets the button bar relating to this event.

API Class API

class RibbonButtonBarEvent(wx.PyCommandEvent) [source]

Event used to indicate various actions relating to a button on a RibbonButtonBar.

See RibbonButtonBar for available event types.

__init__(command_type=None, win_id=0, bar=None) [source]

GetBar() [source]

Returns the bar which contains the button which the event relates to.

PopupMenu(menu) [source]

Display a popup menu as a result of this (dropdown clicked) event.

Parameters: menu – MISSING DESCRIPTION.

SetBar(bar) [source]

Sets the button bar relating to this event.

Parameters: bar – MISSING DESCRIPTION.

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • infobar
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • ribbon library »
  • ribbon.buttonbar »
  • RibbonButtonBarEvent


RibbonButtonBarLayout

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • ribbon library »
  • ribbon.buttonbar »
  • RibbonButtonBarLayout

RibbonButtonBarLayout

hierarchy Inheritance Diagram

Inheritance diagram for: RibbonButtonBarLayout

Inheritance diagram of RibbonButtonBarLayout

Methods Summary

__init__
CalculateOverallSize
FindSimilarInstance

API Class API

class RibbonButtonBarLayout(object) [source]

__init__() [source]

CalculateOverallSize() [source]

FindSimilarInstance(inst) [source]

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • infobar
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • ribbon library »
  • ribbon.buttonbar »
  • RibbonButtonBarLayout


ribbon.buttonbar

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • ribbon library »
  • ribbon.buttonbar

ribbon.buttonbar

A ribbon button bar is similar to a traditional toolbar.

description Description

It contains one or more buttons (button bar buttons, not wx.Button), each of which has a label and an icon. It differs from a RibbonToolBar 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 Events Processing

This class processes the following events:

Events processing for ribbon.buttonbar
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. 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).

Module author: Andrea Gavana <andrea.gavana@gmail.com>

hierarchy Inheritance Diagram

Inheritance diagram for module: ribbon.buttonbar

Inheritance diagram of ribbon.buttonbar.RibbonButtonBar, ribbon.buttonbar.RibbonButtonBarButtonBase, ribbon.buttonbar.RibbonButtonBarButtonInstance, ribbon.buttonbar.RibbonButtonBarButtonSizeInfo, ribbon.buttonbar.RibbonButtonBarEvent, ribbon.buttonbar.RibbonButtonBarLayout

SVN Revisions

A graphical representation of the SVN commits in the last year.

Click on any date in the picture to jump to that particular revision page, containing information about committers, log messages and SVN diffs.

Revision Graph For buttonbar

2to3 Python 3 Issues (via 2to3)

No issues have been detected by 2to3.py.

Class Summary

  • RibbonButtonBar
  • RibbonButtonBarButtonBase
  • RibbonButtonBarButtonInstance
  • RibbonButtonBarButtonSizeInfo
  • RibbonButtonBarEvent
  • RibbonButtonBarLayout

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • infobar
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • ribbon library »
  • ribbon.buttonbar


RibbonControl

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • ribbon library »
  • ribbon.control »
  • RibbonControl

RibbonControl

hierarchy Inheritance Diagram

Inheritance diagram for: RibbonControl

Inheritance diagram of RibbonControl

subclasses Known Subclasses

  • ribbon.bar.RibbonBar
  • ribbon.buttonbar.RibbonButtonBar
  • ribbon.gallery.RibbonGallery
  • ribbon.page.RibbonPage
  • ribbon.page.RibbonPageScrollButton
  • ribbon.panel.RibbonPanel
  • ribbon.toolbar.RibbonToolBar

Methods Summary

__init__
DoGetNextLargerSize | Implementation of GetNextLargerSize.
DoGetNextSmallerSize | Implementation of GetNextSmallerSize.
GetArtProvider | Get the art provider to be used.
GetNextLargerSize | If sizing is not continuous, then return a suitable size for the control which is larger then the given size.
GetNextSmallerSize | If sizing is not continuous, then return a suitable size for the control which is smaller than the given size.
IsSizingContinuous
returns: True if this window can take any size (greater than its minimum size),
RibbonControl.Realise | Alias for Realize.
RibbonControl.Realize | Perform initial size and layout calculations after children have been added,
RibbonControl.SetArtProvider | Set the art provider to be used.

API Class API

class RibbonControl(wx.PyControl) [source]

__init__(parent, id=wx.ID_ANY, pos=wx.DefaultPosition, size=wx.DefaultSize, style=0, validator=wx.DefaultValidator, name="RibbonControl") [source]

DoGetNextLargerSize(direction, size) [source]

Implementation of GetNextLargerSize.

Controls which have non-continuous sizing must override this virtual function rather than GetNextLargerSize.

Parameters:
  • direction – MISSING DESCRIPTION;
  • relative_to – MISSING DESCRIPTION.

DoGetNextSmallerSize(direction, size) [source]

Implementation of GetNextSmallerSize.

Controls which have non-continuous sizing must override this virtual function rather than GetNextSmallerSize.

Parameters:
  • direction – MISSING DESCRIPTION;
  • relative_to – MISSING DESCRIPTION.

GetArtProvider() [source]

Get the art provider to be used.

Note that until an art provider has been set in some way, this function may return None.

GetNextLargerSize(direction, relative_to=None) [source]

If sizing is not continuous, then return a suitable size for the control which is larger then the given size.

Parameters:
  • direction – The direction(s) in which the size should increase;
  • relative_to – The size for which a larger size should be found.
Returns:

if there is no larger size, otherwise a suitable size which is larger in the given direction(s), and the same as in the other direction (if any).

See also

IsSizingContinuous, DoGetNextLargerSize

GetNextSmallerSize(direction, relative_to=None) [source]

If sizing is not continuous, then return a suitable size for the control which is smaller than the given size.

Parameters:
  • direction – The direction(s) in which the size should reduce;
  • relative_to – The size for which a smaller size should be found.
Returns:

if there is no smaller size, otherwise a suitable size which is smaller in the given direction(s), and the same as in the other direction (if any).

See also

IsSizingContinuous, DoGetNextSmallerSize

IsSizingContinuous() [source]
Returns: True if this window can take any size (greater than its minimum size), False if it can only take certain sizes.

See also

GetNextSmallerSize, GetNextLargerSize

Realise() [source]

Alias for Realize.

Realize() [source]

Perform initial size and layout calculations after children have been added, and/or realize children.

SetArtProvider(art) [source]

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 RibbonControl. In most cases, controls will not take ownership of the given pointer, with the notable exception being RibbonBar.SetArtProvider().

Parameters: art – MISSING DESCRIPTION.

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • infobar
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • ribbon library »
  • ribbon.control »
  • RibbonControl


ribbon.control

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • ribbon library »
  • ribbon.control

ribbon.control

RibbonControl serves as a base class for all controls which share the ribbon charactertics of having a ribbon art provider, and (optionally) non-continous resizing.

description Description

Despite what the name may imply, it is not the top-level control for creating a ribbon interface - that is RibbonBar. Ribbon controls often have a region which is “transparent”, and shows the contents of the ribbon page or panel behind it.

If implementing a new ribbon control, then it may be useful to realise that this effect is done by the art provider when painting the background of the control, and hence in the paint handler for the new control, you should call a draw background method on the art provider (DrawButtonBarBackground and DrawToolBarBackground typically just redraw what is behind the rectangle being painted) if you want transparent regions.

Module author: Andrea Gavana <andrea.gavana@gmail.com>

hierarchy Inheritance Diagram

Inheritance diagram for module: ribbon.control

Inheritance diagram of ribbon.control.RibbonControl

SVN Revisions

A graphical representation of the SVN commits in the last year.

Click on any date in the picture to jump to that particular revision page, containing information about committers, log messages and SVN diffs.

Revision Graph For control

2to3 Python 3 Issues (via 2to3)

No issues have been detected by 2to3.py.

Class Summary

  • RibbonControl

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • infobar
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • ribbon library »
  • ribbon.control


RibbonGallery

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • ribbon library »
  • ribbon.gallery »
  • RibbonGallery

RibbonGallery

hierarchy Inheritance Diagram

Inheritance diagram for: RibbonGallery

Inheritance diagram of RibbonGallery

supclasses Known Superclasses

  • ribbon.control.RibbonControl

appearance Control Appearance

RibbonGallery

Methods Summary

__init__ | Default class constructor.
Append | Add an item to the gallery (with complex client data).
CalculateMinSize |
Clear | Remove all items from the gallery.
CommonInit |
DoGetBestSize |
DoGetNextLargerSize |
DoGetNextSmallerSize |
EnsureVisible | Scroll the gallery to ensure that the given item is visible.
GetActiveItem | Get the currently active item, or None if there is none.
GetCount | Get the number of items in the gallery.
GetDefaultBorder |
GetDownButtonState | Get the state of the scroll down button.
GetExtensionButtonState | Get the state of the “extension” button.
GetHoveredItem | Get the currently hovered item, or None if there is none.
GetItem | Get an item by index.
GetItemClientData | Get the client data associated with a gallery item.
GetSelection | Get the currently selected item, or None if there is none.
GetUpButtonState | Get the state of the scroll up button.
IsEmpty | Query if the gallery has no items in it.
IsHovered | Query is the mouse is currently hovered over the gallery.
IsSizingContinuous |
Layout |
OnEraseBackground |
OnMouseDClick |
OnMouseDown |
OnMouseEnter |
OnMouseLeave |
OnMouseMove |
OnMouseUp |
OnPaint |
OnSize |
Realize |
ScrollLines | Scroll the gallery contents by some amount.
SetItemClientData | Set the client data associated with a gallery item.
SetSelection | Set the selection to the given item, or removes the selection if item == None.
TestButtonHover |

API Class API

class RibbonGallery(RibbonControl) [source]

__init__(parent, id=wx.ID_ANY, pos=wx.DefaultPosition, size=wx.DefaultSize, agwStyle=0, name="RibbonGallery") [source]

Default class constructor.

Parameters:
  • parent – Pointer to a parent window;
  • id – Window identifier. If wx.ID_ANY, will automatically create an identifier;
  • pos – Window position. wx.DefaultPosition indicates that wxPython should generate a default position for the window;
  • 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;
  • agwStyle – the AGW-specific window style;
  • name – the window name.

Append(bitmap, id, clientData=None) [source]

Add an item to the gallery (with complex client data).

Parameters:
  • bitmap – The bitmap to display for the item. Note that all items must have equally sized bitmaps;
  • id – ID number to associate with the item. Not currently used for anything important;
  • clientData – An object which contains data to associate with the item. The item takes ownership of this pointer, and will delete it when the item client data is changed to something else, or when the item is destroyed.

CalculateMinSize() [source]

Clear() [source]

Remove all items from the gallery.

CommonInit(agwStyle) [source]

DoGetBestSize() [source]

DoGetNextLargerSize(direction, relative_to) [source]

DoGetNextSmallerSize(direction, relative_to) [source]

EnsureVisible(item) [source]

Scroll the gallery to ensure that the given item is visible.

Parameters: item – MISSING DESCRIPTION.

GetActiveItem() [source]

Get the currently active item, or None if there is none.

The active item is the item being pressed by the user, and will thus become the selected item if the user releases the mouse button.

GetCount() [source]

Get the number of items in the gallery.

GetDefaultBorder() [source]

GetDownButtonState() [source]

Get the state of the scroll down button.

GetExtensionButtonState() [source]

Get the state of the “extension” button.

GetHoveredItem() [source]

Get the currently hovered item, or None if there is none.

The hovered item is the item underneath the mouse cursor.

GetItem(n) [source]

Get an item by index.

Parameters: n – MISSING DESCRIPTION.

GetItemClientData(item) [source]

Get the client data associated with a gallery item.

Parameters: item – MISSING DESCRIPTION.

GetSelection() [source]

Get the currently selected item, or None if there is none.

The selected item is set by SetSelection, or by the user clicking on an item.

GetUpButtonState() [source]

Get the state of the scroll up button.

IsEmpty() [source]

Query if the gallery has no items in it.

IsHovered() [source]

Query is the mouse is currently hovered over the gallery.

Returns: True if the cursor is within the bounds of the gallery (not just hovering over an item), False otherwise.

IsSizingContinuous() [source]

Layout() [source]

OnEraseBackground(event) [source]

OnMouseDClick(event) [source]

OnMouseDown(event) [source]

OnMouseEnter(event) [source]

OnMouseLeave(event) [source]

OnMouseMove(event) [source]

OnMouseUp(event) [source]

OnPaint(event) [source]

OnSize(event) [source]

Realize() [source]

ScrollLines(lines) [source]

Scroll the gallery contents by some amount.

Reimplemented from wx.Window.

Parameters: lines – Positive values scroll toward the end of the gallery, while negative values scroll toward the start.
Returns: True if the gallery scrolled at least one pixel in the given direction, False if it did not scroll.

SetItemClientData(item, data) [source]

Set the client data associated with a gallery item.

Parameters:
  • item – MISSING DESCRIPTION;
  • data – MISSING DESCRIPTION.

SetSelection(item) [source]

Set the selection to the given item, or removes the selection if item == None.

Note that this not cause any events to be emitted.

Parameters: item – MISSING DESCRIPTION.

TestButtonHover(rect, pos, state) [source]

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • infobar
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • ribbon library »
  • ribbon.gallery »
  • RibbonGallery


RibbonGalleryEvent

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • ribbon library »
  • ribbon.gallery »
  • RibbonGalleryEvent

RibbonGalleryEvent

hierarchy Inheritance Diagram

Inheritance diagram for: RibbonGalleryEvent

Inheritance diagram of RibbonGalleryEvent

Methods Summary

__init__
GetGallery
GetGalleryItem
SetGallery
SetGalleryItem

API Class API

class RibbonGalleryEvent(wx.PyCommandEvent) [source]

__init__(command_type=None, win_id=0, gallery=None, item=None) [source]

GetGallery() [source]

GetGalleryItem() [source]

SetGallery(gallery) [source]

SetGalleryItem(item) [source]

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • infobar
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • ribbon library »
  • ribbon.gallery »
  • RibbonGalleryEvent


RibbonGalleryItem

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • ribbon library »
  • ribbon.gallery »
  • RibbonGalleryItem

RibbonGalleryItem

hierarchy Inheritance Diagram

Inheritance diagram for: RibbonGalleryItem

Inheritance diagram of RibbonGalleryItem

Methods Summary

__init__
GetBitmap
GetClientData
GetPosition
IsVisible
SetBitmap
SetClientData
SetId
SetIsVisible
SetPosition

API Class API

class RibbonGalleryItem(object) [source]

__init__() [source]

GetBitmap() [source]

GetClientData() [source]

GetPosition() [source]

IsVisible() [source]

SetBitmap(bitmap) [source]

SetClientData(data) [source]

SetId(id) [source]

SetIsVisible(visible) [source]

SetPosition(x, y, size) [source]

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • infobar
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • ribbon library »
  • ribbon.gallery »
  • RibbonGalleryItem


ribbon.gallery

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • ribbon library »
  • ribbon.gallery

ribbon.gallery

A ribbon gallery is like a wx.ListBox, but for bitmaps rather than strings.

description Description

It displays a collection of bitmaps arranged in a grid and allows the user to choose one. As there are typically more bitmaps in a gallery than can be displayed in the space used for a ribbon, a gallery always has scroll buttons to allow the user to navigate through the entire gallery.

It also has an “extension” button, the behaviour of which is outside the scope of the gallery control itself, though it typically displays some kind of dialog related to the gallery.

events Events Processing

This class processes the following events:

Events processing for ribbon.gallery
Event Name | Description
EVT_RIBBONGALLERY_SELECTED | Triggered when the user selects an item from the gallery. Note that the ID is that of the gallery, not of the item.
EVT_RIBBONGALLERY_HOVER_CHANGED | Triggered when the item being hovered over by the user changes. The item in the event will be the new item being hovered, or None if there is no longer an item being hovered. Note that the ID is that of the gallery, not of the item.
EVT_RIBBONGALLERY_CLICKED | Triggered when the user clicks on an item in the gallery.
EVT_BUTTON | Triggered when the “extension” button of the gallery is pressed.

Module author: Andrea Gavana <andrea.gavana@gmail.com>

hierarchy Inheritance Diagram

Inheritance diagram for module: ribbon.gallery

Inheritance diagram of ribbon.gallery.RibbonGallery, ribbon.gallery.RibbonGalleryEvent, ribbon.gallery.RibbonGalleryItem

SVN Revisions

A graphical representation of the SVN commits in the last year.

Click on any date in the picture to jump to that particular revision page, containing information about committers, log messages and SVN diffs.

Revision Graph For gallery

2to3 Python 3 Issues (via 2to3)

No issues have been detected by 2to3.py.

Class Summary

  • RibbonGallery
  • RibbonGalleryEvent
  • RibbonGalleryItem

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • infobar
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • ribbon library »
  • ribbon.gallery


ribbon.page functions

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • ribbon library »
  • ribbon.page »
  • ribbon.page functions

ribbon.page functions

This is the description of standalone Python functions in the ribbon.page module.

Functions Summary

GetSizeInOrientation

API Functions API

GetSizeInOrientation(size, orientation) [source]

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • infobar
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • ribbon library »
  • ribbon.page »
  • ribbon.page functions


RibbonPage

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • ribbon library »
  • ribbon.page »
  • RibbonPage

RibbonPage

hierarchy Inheritance Diagram

Inheritance diagram for: RibbonPage

Inheritance diagram of RibbonPage

supclasses Known Superclasses

  • ribbon.control.RibbonControl

appearance Control Appearance

RibbonPage

Methods Summary

__init__ | Default class constructor.
AdjustRectToIncludeScrollButtons | Expand a rectangle of the page to include external scroll buttons (if any).
CollapsePanels |
CommonInit |
DismissExpandedPanel | Dismiss the current externally expanded panel, if there is one.
DoGetBestSize |
DoSetSize |
ExpandPanels |
GetDefaultBorder |
GetIcon | Get the icon used for the page in the ribbon bar tab area (only displayed if the
GetMajorAxis | Get the direction in which ribbon panels are stacked within the page.
GetMinSize |
HideScrollButtons |
Layout |
OnEraseBackground |
OnPaint |
OnSize |
Realize | Perform a full re-layout of all panels on the page.
RemoveChild |
ScrollLines | Scroll the page by some amount up / down / left / right.
ScrollPixels | Scroll the page by a set number of pixels up / down / left / right.
SetArtProvider | Set the art provider to be used.
SetSizeWithScrollButtonAdjustment | Set the size of the page and the external scroll buttons (if any).
Show |
ShowScrollButtons |

API Class API

class RibbonPage(RibbonControl) [source]

__init__(parent, id=wx.ID_ANY, label="", icon=wx.NullBitmap, style=0) [source]

Default class constructor.

Parameters:
  • parent – Pointer to a parent window;
  • id – Window identifier. If wx.ID_ANY, will automatically create an identifier;
  • label – Label of the new button;
  • icon – the icon used for the page in the ribbon bar tab area;
  • style – Window style.

AdjustRectToIncludeScrollButtons(rect) [source]

Expand a rectangle of the page to include external scroll buttons (if any).

When no scroll buttons are shown, has no effect.

Parameters: rect – The rectangle to adjust. The width and height will not be reduced, and the x and y will not be increased.

CollapsePanels(direction, minimum_amount) [source]

CommonInit(label, icon) [source]

DismissExpandedPanel() [source]

Dismiss the current externally expanded panel, if there is one.

When a ribbon panel automatically minimises, it can be externally expanded into a floating window. When the user clicks a button in such a panel, the panel should generally re-minimise. Event handlers for buttons on ribbon panels should call this method to achieve this behaviour.

Returns: True if a panel was minimised, False otherwise.

DoGetBestSize() [source]

DoSetSize(x, y, width, height, sizeFlags=wx.SIZE_AUTO) [source]

ExpandPanels(direction, maximum_amount) [source]

GetDefaultBorder() [source]

GetIcon() [source]

Get the icon used for the page in the ribbon bar tab area (only displayed if the ribbon bar is actually showing icons).

GetMajorAxis() [source]

Get the direction in which ribbon panels are stacked within the page.

This is controlled by the style of the containing RibbonBar, meaning that all pages within a bar will have the same major axis. As well as being the direction in which panels are stacked, it is also the axis in which scrolling will occur (when required).

Returns: wx.HORIZONTAL or wx.VERTICAL (never wx.BOTH).

GetMinSize() [source]

HideScrollButtons() [source]

Layout() [source]

OnEraseBackground(event) [source]

OnPaint(event) [source]

OnSize(event) [source]

Realize() [source]

Perform a full re-layout of all panels on the page.

Should be called after panels are added to the page, or the sizing behaviour of a panel on the page changes (i.e. due to children being added to it). Usually called automatically when RibbonBar.Realize() is called. Will invoke RibbonPanel.Realize() for all child panels.

Reimplemented from RibbonControl.

RemoveChild(child) [source]

ScrollLines(lines) [source]

Scroll the page by some amount up / down / left / right.

When the page’s children are too big to fit in the onscreen area given to the page, scroll buttons will appear, and the page can be programatically scrolled. Positive values of will scroll right or down, while negative values will scroll up or left (depending on the direction in which panels are stacked). A line is equivalent to a constant number of pixels.

Reimplemented from wx.Window.

Parameters: lines – MISSING DESCRIPTION.
Returns: True if the page scrolled at least one pixel in the given direction, False if it did not scroll.

See also

GetMajorAxis, ScrollPixels

ScrollPixels(pixels) [source]

Scroll the page by a set number of pixels up / down / left / right.

When the page’s children are too big to fit in the onscreen area given to the page, scroll buttons will appear, and the page can be programatically scrolled. Positive values of will scroll right or down, while negative values will scroll up or left (depending on the direction in which panels are stacked).

Parameters: pixels – MISSING DESCRIPTION.
Returns: True if the page scrolled at least one pixel in the given direction, False if it did not scroll.

See also

GetMajorAxis, ScrollLines

SetArtProvider(art) [source]

Set the art provider to be used.

Normally called automatically by RibbonBar when the page is created, or the art provider changed on the bar. The new art provider will be propagated to the children of the page.

Reimplemented from RibbonControl.

Parameters: art – MISSING DESCRIPTION.

SetSizeWithScrollButtonAdjustment(x, y, width, height) [source]

Set the size of the page and the external scroll buttons (if any).

When a page is too small to display all of its children, scroll buttons will appear (and if the page is sized up enough, they will disappear again). Slightly counter-intuively, these buttons are created as siblings of the page rather than children of the page (to achieve correct cropping and paint ordering of the children and the buttons).

When there are no scroll buttons, this function behaves the same as SetSize, however when there are scroll buttons, it positions them at the edges of the given area, and then calls SetSize with the remaining area. This is provided as a separate function to SetSize rather than within the implementation of SetSize, as iteracting algorithms may not expect SetSize to also set the size of siblings.

Parameters:
  • x – MISSING DESCRIPTION;
  • y – MISSING DESCRIPTION;
  • width – MISSING DESCRIPTION;
  • height – MISSING DESCRIPTION.

Show(show=True) [source]

ShowScrollButtons() [source]

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • infobar
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • ribbon library »
  • ribbon.page »
  • RibbonPage


RibbonPageScrollButton

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • ribbon library »
  • ribbon.page »
  • RibbonPageScrollButton

RibbonPageScrollButton

hierarchy Inheritance Diagram

Inheritance diagram for: RibbonPageScrollButton

Inheritance diagram of RibbonPageScrollButton

supclasses Known Superclasses

  • ribbon.control.RibbonControl

Methods Summary

__init__
OnEraseBackground
OnMouseDown
OnMouseEnter
OnMouseLeave
OnMouseUp
OnPaint

API Class API

class RibbonPageScrollButton(RibbonControl) [source]

__init__(sibling, id=wx.ID_ANY, pos=wx.DefaultPosition, size=wx.DefaultSize, style=0) [source]

OnEraseBackground(event) [source]

OnMouseDown(event) [source]

OnMouseEnter(event) [source]

OnMouseLeave(event) [source]

OnMouseUp(event) [source]

OnPaint(event) [source]

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • infobar
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • ribbon library »
  • ribbon.page »
  • RibbonPageScrollButton


ribbon.page

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • ribbon library »
  • ribbon.page

ribbon.page

description Description

Container for related ribbon panels, and a tab within a ribbon bar.

link See Also

RibbonBar, RibbonPanel

Module author: Andrea Gavana <andrea.gavana@gmail.com>

hierarchy Inheritance Diagram

Inheritance diagram for module: ribbon.page

Inheritance diagram of ribbon.page.RibbonPage, ribbon.page.RibbonPageScrollButton

SVN Revisions

A graphical representation of the SVN commits in the last year.

Click on any date in the picture to jump to that particular revision page, containing information about committers, log messages and SVN diffs.

Revision Graph For page

2to3 Python 3 Issues (via 2to3)

No issues have been detected by 2to3.py.

Function Summary

  • GetSizeInOrientation

Class Summary

  • RibbonPage
  • RibbonPageScrollButton

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • infobar
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • ribbon library »
  • ribbon.page


ribbon.panel functions

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • ribbon library »
  • ribbon.panel »
  • ribbon.panel functions

ribbon.panel functions

This is the description of standalone Python functions in the ribbon.panel module.

Functions Summary

IsAncestorOf

API Functions API

IsAncestorOf(ancestor, window) [source]

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • infobar
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • ribbon library »
  • ribbon.panel »
  • ribbon.panel functions


RibbonPanel

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • ribbon library »
  • ribbon.panel »
  • RibbonPanel

RibbonPanel

This is the main implementation of RibbonPanel.

hierarchy Inheritance Diagram

Inheritance diagram for: RibbonPanel

Inheritance diagram of RibbonPanel

supclasses Known Superclasses

  • ribbon.control.RibbonControl

appearance Control Appearance

RibbonPanel

Methods Summary

__init__ | Default class constructor.
AddChild |
CanAutoMinimise | Query if the panel can automatically minimise itself at small sizes.
CommonInit |
DoGetBestSize |
DoGetNextLargerSize |
DoGetNextSmallerSize |
DoSetSize |
GetDefaultBorder |
GetExpandedDummy | Get the dummy panel of an expanded panel.
GetExpandedPanel | Get the expanded panel of a dummy panel.
GetExpandedPosition |
GetMinNotMinimisedSize |
GetMinSize |
GetMinimisedIcon | Get the bitmap to be used in place of the panel children when it is minimised.
GetPanelSizerBestSize |
GetPanelSizerMinSize |
HideExpanded | Hide the panel’s external expansion.
IsHovered | Query is the mouse is currently hovered over the panel.
IsMinimised | Query if the panel would be minimised at a given size.
IsMinimised1 | Query if the panel is currently minimised.
IsMinimised2 | Query if the panel would be minimised at a given size.
IsSizingContinuous |
Layout |
OnChildKillFocus |
OnEraseBackground |
OnKillFocus |
OnMouseClick |
OnMouseEnter |
OnMouseEnterChild |
OnMouseLeave |
OnMouseLeaveChild |
OnPaint |
OnSize |
Realize | Realize all children of the panel.
RemoveChild |
SetArtProvider | Set the art provider to be used.
ShouldSendEventToDummy |
ShowExpanded | Show the panel externally expanded.
TestPositionForHover |
TryAfter |
__del__ |

API Class API

class RibbonPanel(RibbonControl) [source]

This is the main implementation of RibbonPanel.

__init__(parent, id=wx.ID_ANY, label="", minimised_icon=wx.NullBitmap, pos=wx.DefaultPosition, size=wx.DefaultSize, agwStyle=RIBBON_PANEL_DEFAULT_STYLE, name="RibbonPanel") [source]

Default class constructor.

Parameters:
  • parent – Pointer to a parent window;
  • id – Window identifier. If wx.ID_ANY, will automatically create an identifier;
  • label – Label of the new button;
  • minimised_icon – the bitmap to be used in place of the panel children when it is minimised;
  • pos – Window position. wx.DefaultPosition indicates that wxPython should generate a default position for the window;
  • 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;
  • agwStyle – the AGW-specific window style. This can be one of the following bits:

    Window Styles | Hex Value | Description
    RIBBON_PANEL_DEFAULT_STYLE | 0x0 | Defined as no other flags set.
    RIBBON_PANEL_NO_AUTO_MINIMISE | 0x1 | Prevents the panel from automatically minimising to conserve screen space.
    RIBBON_PANEL_EXT_BUTTON | 0x8 | Causes an extension button to be shown in the panel’s chrome (if the bar in which it is contained has RIBBON_BAR_SHOW_PANEL_EXT_BUTTONS set). The behaviour of this button is application controlled, but typically will show an extended drop-down menu relating to the panel.
    RIBBON_PANEL_MINIMISE_BUTTON | 0x10 | Causes a (de)minimise button to be shown in the panel’s chrome (if the bar in which it is contained has the RIBBON_BAR_SHOW_PANEL_MINIMISE_BUTTONS style set). This flag is typically combined with RIBBON_PANEL_NO_AUTO_MINIMISE to make a panel which the user always has manual control over when it minimises.
  • name – the window name.

AddChild(child) [source]

CanAutoMinimise() [source]

Query if the panel can automatically minimise itself at small sizes.

CommonInit(label, icon, agwStyle) [source]

DoGetBestSize() [source]

DoGetNextLargerSize(direction, relative_to) [source]

DoGetNextSmallerSize(direction, relative_to) [source]

DoSetSize(x, y, width, height, sizeFlags=wx.SIZE_AUTO) [source]

GetDefaultBorder() [source]

GetExpandedDummy() [source]

Get the dummy panel of an expanded panel.

Note

This should be called on an expanded panel to get the dummy associated with it - it will return None when called on the dummy itself.

See also

ShowExpanded, GetExpandedPanel

GetExpandedPanel() [source]

Get the expanded panel of a dummy panel.

Note

This should be called on a dummy panel to get the expanded panel associated with it - it will return None when called on the expanded panel itself.

See also

ShowExpanded, GetExpandedDummy

GetExpandedPosition(panel, expanded_size, direction) [source]

GetMinNotMinimisedSize() [source]

GetMinSize() [source]

GetMinimisedIcon() [source]

Get the bitmap to be used in place of the panel children when it is minimised.

GetPanelSizerBestSize() [source]

GetPanelSizerMinSize() [source]

HideExpanded() [source]

Hide the panel’s external expansion.

Returns: True if the panel was un-expanded, False if it was not (normally due to it not being expanded in the first place).

See also

HideExpanded, GetExpandedPanel

IsHovered() [source]

Query is the mouse is currently hovered over the panel.

Returns: True if the cursor is within the bounds of the panel (i.e. hovered over the panel or one of its children), False otherwise.

IsMinimised(at_size=None) [source]

Query if the panel would be minimised at a given size.

Parameters: at_size – MISSING DESCRIPTION.

IsMinimised1() [source]

Query if the panel is currently minimised.

IsMinimised2(at_size) [source]

Query if the panel would be minimised at a given size.

Parameters: at_size – MISSING DESCRIPTION.

IsSizingContinuous() [source]

Layout() [source]

OnChildKillFocus(event) [source]

OnEraseBackground(event) [source]

OnKillFocus(event) [source]

OnMouseClick(event) [source]

OnMouseEnter(event) [source]

OnMouseEnterChild(event) [source]

OnMouseLeave(event) [source]

OnMouseLeaveChild(event) [source]

OnPaint(event) [source]

OnSize(event) [source]

Realize() [source]

Realize all children of the panel.

Reimplemented from RibbonControl.

RemoveChild(child) [source]

SetArtProvider(art) [source]

Set the art provider to be used.

Normally called automatically by RibbonPage when the panel is created, or the art provider changed on the page. The new art provider will be propagated to the children of the panel.

Reimplemented from RibbonControl.

Parameters: art – MISSING DESCRIPTION.

ShouldSendEventToDummy(event) [source]

ShowExpanded() [source]

Show the panel externally expanded.

When a panel is minimised, it can be shown full-size in a pop-out window, which is refered to as being (externally) expanded.

Returns: True if the panel was expanded, False if it was not (possibly due to it not being minimised, or already being expanded).

Note

When a panel is expanded, there exist two panels - the original panel (which is refered to as the dummy panel) and the expanded panel. The original is termed a dummy as it sits in the ribbon bar doing nothing, while the expanded panel holds the panel children.

See also

HideExpanded, GetExpandedPanel

TestPositionForHover(pos) [source]

TryAfter(event) [source]

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • infobar
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • ribbon library »
  • ribbon.panel »
  • RibbonPanel


ribbon.panel

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • ribbon library »
  • ribbon.panel

ribbon.panel

Serves as a container for a group of (ribbon) controls.

description Description

A RibbonPage will typically have panels for children, with the controls for that page placed on the panels. A panel adds a border and label to a group of controls, and can be minimised (either automatically to conserve space, or manually by the user).

styles Window Styles

This class supports the following window styles:

Window styles for ribbon.panel
Window Styles | Hex Value | Description
RIBBON_PANEL_DEFAULT_STYLE | 0x0 | Defined as no other flags set.
RIBBON_PANEL_NO_AUTO_MINIMISE | 0x1 | Prevents the panel from automatically minimising to conserve screen space.
RIBBON_PANEL_EXT_BUTTON | 0x8 | Causes an extension button to be shown in the panel’s chrome (if the bar in which it is contained has RIBBON_BAR_SHOW_PANEL_EXT_BUTTONS set). The behaviour of this button is application controlled, but typically will show an extended drop-down menu relating to the panel.
RIBBON_PANEL_MINIMISE_BUTTON | 0x10 | Causes a (de)minimise button to be shown in the panel’s chrome (if the bar in which it is contained has the RIBBON_BAR_SHOW_PANEL_MINIMISE_BUTTONS style set). This flag is typically combined with RIBBON_PANEL_NO_AUTO_MINIMISE to make a panel which the user always has manual control over when it minimises.

link See Also

RibbonPage

Module author: Andrea Gavana <andrea.gavana@gmail.com>

hierarchy Inheritance Diagram

Inheritance diagram for module: ribbon.panel

Inheritance diagram of ribbon.panel.RibbonPanel

SVN Revisions

A graphical representation of the SVN commits in the last year.

Click on any date in the picture to jump to that particular revision page, containing information about committers, log messages and SVN diffs.

Revision Graph For panel

2to3 Python 3 Issues (via 2to3)

No issues have been detected by 2to3.py.

Function Summary

  • IsAncestorOf

Class Summary

  • RibbonPanel

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • infobar
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • ribbon library »
  • ribbon.panel


ribbon.toolbar functions

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • ribbon library »
  • ribbon.toolbar »
  • ribbon.toolbar functions

ribbon.toolbar functions

This is the description of standalone Python functions in the ribbon.toolbar module.

Functions Summary

GetSizeInOrientation

API Functions API

GetSizeInOrientation(size, orientation) [source]

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • infobar
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • ribbon library »
  • ribbon.toolbar »
  • ribbon.toolbar functions


RibbonToolBar

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • ribbon library »
  • ribbon.toolbar »
  • RibbonToolBar

RibbonToolBar

hierarchy Inheritance Diagram

Inheritance diagram for: RibbonToolBar

Inheritance diagram of RibbonToolBar

supclasses Known Superclasses

  • ribbon.control.RibbonControl

appearance Control Appearance

RibbonToolBar

Methods Summary

__init__ | Default class constructor.
AddDropdownTool | Add a dropdown tool to the tool bar (simple version).
AddHybridTool | Add a hybrid tool to the tool bar (simple version).
AddSeparator | Add a separator to the tool bar.
AddSimpleTool | Add a tool to the tool bar (simple version).
AddTool | Add a tool to the tool bar.
AppendGroup |
CommonInit |
DoGetBestSize |
DoGetNextLargerSize |
DoGetNextSmallerSize |
GetDefaultBorder |
IsSizingContinuous |
MakeDisabledBitmap |
OnEraseBackground |
OnMouseDown |
OnMouseEnter |
OnMouseLeave |
OnMouseMove |
OnMouseUp |
OnPaint |
OnSize |
Realize |
SetRows | Set the number of rows to distribute tool groups over.

API Class API

class RibbonToolBar(RibbonControl) [source]

__init__(parent, id=wx.ID_ANY, pos=wx.DefaultPosition, size=wx.DefaultSize, style=0, name="RibbonToolbar") [source]

Default class constructor.

Parameters:
  • parent – Pointer to a parent window;
  • id – Window identifier. If wx.ID_ANY, will automatically create an identifier;
  • pos – Window position. wx.DefaultPosition indicates that wxPython should generate a default position for the window;
  • 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;
  • style – Window style;
  • name – the window name.

AddDropdownTool(tool_id, bitmap, help_string='') [source]

Add a dropdown tool to the tool bar (simple version).

Parameters:
  • tool_id – ID of the new tool (used for event callbacks);
  • bitmap – Large bitmap of the new button. Must be the same size as all other large bitmaps used on the button bar;
  • help_string – The UI help string to associate with the new button.

See also

AddTool

AddHybridTool(tool_id, bitmap, help_string='') [source]

Add a hybrid tool to the tool bar (simple version).

Parameters:
  • tool_id – ID of the new tool (used for event callbacks);
  • bitmap – Large bitmap of the new button. Must be the same size as all other large bitmaps used on the button bar;
  • help_string – The UI help string to associate with the new button.

See also

AddTool

AddSeparator() [source]

Add a separator to the tool bar.

Separators are used to separate tools into groups. As such, a separator is not explicity drawn, but is visually seen as the gap between tool groups.

AddSimpleTool(tool_id, bitmap, help_string, kind=RIBBON_BUTTON_NORMAL) [source]

Add a tool to the tool bar (simple version).

Parameters:
  • tool_id – ID of the new tool (used for event callbacks);
  • bitmap – Large bitmap of the new button. Must be the same size as all other large bitmaps used on the button bar;
  • help_string – The UI help string to associate with the new button;
  • kind – The kind of button to add.

See also

AddDropdownTool, AddHybridTool, AddTool

AddTool(tool_id, bitmap, bitmap_disabled=wx.NullBitmap, help_string="", kind=RIBBON_BUTTON_NORMAL, client_data=None) [source]

Add a tool to the tool bar.

Parameters:
  • tool_id – ID of the new tool (used for event callbacks);
  • bitmap – Bitmap to use as the foreground for the new tool. Does not have to be the same size as other tool bitmaps, but should be similar as otherwise it will look visually odd;
  • bitmap_disabled – Bitmap to use when the tool is disabled. If left as wx.NullBitmap, then a bitmap will be automatically generated from bitmap;
  • help_string – The UI help string to associate with the new tool;
  • kind – The kind of tool to add;
  • client_data – Client data to associate with the new tool.
Returns:

An opaque pointer which can be used only with other tool bar methods.

See also

AddDropdownTool, AddHybridTool, AddSeparator

AppendGroup() [source]

CommonInit(style) [source]

DoGetBestSize() [source]

DoGetNextLargerSize(direction, relative_to) [source]

DoGetNextSmallerSize(direction, relative_to) [source]

GetDefaultBorder() [source]

IsSizingContinuous() [source]

MakeDisabledBitmap(original) [source]

OnEraseBackground(event) [source]

OnMouseDown(event) [source]

OnMouseEnter(event) [source]

OnMouseLeave(event) [source]

OnMouseMove(event) [source]

OnMouseUp(event) [source]

OnPaint(event) [source]

OnSize(event) [source]

Realize() [source]

SetRows(nMin, nMax) [source]

Set the number of rows to distribute tool groups over.

Tool groups can be distributed over a variable number of rows. The way in which groups are assigned to rows is not specificed, and the order of groups may change, but they will be distributed in such a way as to minimise the overall size of the tool bar.

Parameters:
  • nMin – The minimum number of rows to use;
  • nMax – The maximum number of rows to use (defaults to nMin).

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • infobar
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • ribbon library »
  • ribbon.toolbar »
  • RibbonToolBar


RibbonToolBarEvent

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • ribbon library »
  • ribbon.toolbar »
  • RibbonToolBarEvent

RibbonToolBarEvent

hierarchy Inheritance Diagram

Inheritance diagram for: RibbonToolBarEvent

Inheritance diagram of RibbonToolBarEvent

Methods Summary

__init__
GetBar
PopupMenu
SetBar

API Class API

class RibbonToolBarEvent(wx.PyCommandEvent) [source]

__init__(command_type=None, win_id=0, bar=None) [source]

GetBar() [source]

PopupMenu(menu) [source]

SetBar(bar) [source]

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • infobar
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • ribbon library »
  • ribbon.toolbar »
  • RibbonToolBarEvent


RibbonToolBarToolBase

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • ribbon library »
  • ribbon.toolbar »
  • RibbonToolBarToolBase

RibbonToolBarToolBase

hierarchy Inheritance Diagram

Inheritance diagram for: RibbonToolBarToolBase

Inheritance diagram of RibbonToolBarToolBase

Methods Summary

__init__

API Class API

class RibbonToolBarToolBase(object) [source]

__init__() [source]

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • infobar
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • ribbon library »
  • ribbon.toolbar »
  • RibbonToolBarToolBase


RibbonToolBarToolGroup

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • ribbon library »
  • ribbon.toolbar »
  • RibbonToolBarToolGroup

RibbonToolBarToolGroup

hierarchy Inheritance Diagram

Inheritance diagram for: RibbonToolBarToolGroup

Inheritance diagram of RibbonToolBarToolGroup

Methods Summary

__init__

API Class API

class RibbonToolBarToolGroup(object) [source]

__init__() [source]

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • infobar
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • ribbon library »
  • ribbon.toolbar »
  • RibbonToolBarToolGroup


ribbon.toolbar

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • ribbon library »
  • ribbon.toolbar

ribbon.toolbar

A ribbon tool bar is similar to a traditional toolbar which has no labels.

description Description

It contains one or more tool groups, each of which contains one or more tools. Each tool is represented by a (generally small, i.e. 16x15) bitmap.

events Events Processing

This class processes the following events:

Events processing for ribbon.toolbar
Event Name | Description
EVT_RIBBONTOOLBAR_CLICKED | Triggered when the normal (non-dropdown) region of a tool on the tool bar is clicked.
EVT_RIBBONTOOLBAR_DROPDOWN_CLICKED | Triggered when the dropdown region of a tool on the tool bar is clicked. PopupMenu should be called by the event handler if it wants to display a popup menu (which is what most dropdown tools should be doing).

Module author: Andrea Gavana <andrea.gavana@gmail.com>

hierarchy Inheritance Diagram

Inheritance diagram for module: ribbon.toolbar

Inheritance diagram of ribbon.toolbar.RibbonToolBar, ribbon.toolbar.RibbonToolBarEvent, ribbon.toolbar.RibbonToolBarToolBase, ribbon.toolbar.RibbonToolBarToolGroup

SVN Revisions

A graphical representation of the SVN commits in the last year.

Click on any date in the picture to jump to that particular revision page, containing information about committers, log messages and SVN diffs.

Revision Graph For toolbar

2to3 Python 3 Issues (via 2to3)

No issues have been detected by 2to3.py.

Function Summary

  • GetSizeInOrientation

Class Summary

  • RibbonToolBar
  • RibbonToolBarEvent
  • RibbonToolBarToolBase
  • RibbonToolBarToolGroup

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • infobar
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • ribbon library »
  • ribbon.toolbar


rulerctrl functions

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • rulerctrl »
  • rulerctrl functions

rulerctrl functions

This is the description of standalone Python functions in the rulerctrl module.

Functions Summary

ConvertPILToWX | Converts a PIL image into a wx.Image.
ConvertWXToPIL | Converts a wx.Image into a PIL image.
GetIndicatorBitmap | Returns the image indicator as a wx.Bitmap.
GetIndicatorData | Returns the image indicator as a decompressed stream of characters.
GetIndicatorImage | Returns the image indicator as a wx.Image.
MakePalette | Creates a palette to be applied on an image based on input colour.

API Functions API

ConvertPILToWX(pil, alpha=True) [source]

Converts a PIL image into a wx.Image.

Parameters:
  • pil – a PIL image;
  • alpha – True if the image contains alpha transparency, False otherwise.

Note

Requires PIL (Python Imaging Library), which can be downloaded from http://www.pythonware.com/products/pil/

ConvertWXToPIL(bmp) [source]

Converts a wx.Image into a PIL image.

Parameters: bmp – an instance of wx.Image.

Note

Requires PIL (Python Imaging Library), which can be downloaded from http://www.pythonware.com/products/pil/

GetIndicatorBitmap() [source]

Returns the image indicator as a wx.Bitmap.

GetIndicatorData() [source]

Returns the image indicator as a decompressed stream of characters.

GetIndicatorImage() [source]

Returns the image indicator as a wx.Image.

MakePalette(tr, tg, tb) [source]

Creates a palette to be applied on an image based on input colour.

Parameters:
  • tr – the red intensity of the input colour;
  • tg – the green intensity of the input colour;
  • tb – the blue intensity of the input colour.

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • infobar
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • rulerctrl »
  • rulerctrl functions


Indicator

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • rulerctrl »
  • Indicator

Indicator

This class holds all the information about a single indicator inside RulerCtrl.

You should not call this class directly. Use:

ruler.AddIndicator(id, value)

to add an indicator to your RulerCtrl.

hierarchy Inheritance Diagram

Inheritance diagram for: Indicator

Inheritance diagram of Indicator

Methods Summary

__init__ | Default class constructor.
Draw | Actually draws the indicator.
GetId | Returns the indicator id.
GetImageSize | Returns the indicator bitmap size.
GetPosition | Returns the position at which we should draw the indicator bitmap.
GetRect | Returns the indicator client rectangle.
GetValue | Returns the indicator value.
RotateImage | Rotates the default indicator bitmap.
SetColour | Sets the indicator colour.
SetValue | Sets the indicator value.

API Class API

class Indicator(object) [source]

This class holds all the information about a single indicator inside RulerCtrl.

You should not call this class directly. Use:

ruler.AddIndicator(id, value)

to add an indicator to your RulerCtrl.

__init__(parent, id=wx.ID_ANY, value=0) [source]

Default class constructor.

Parameters:
  • parent – the parent window, an instance of RulerCtrl;
  • id – the indicator identifier;
  • value – the initial value of the indicator.

Draw(dc) [source]

Actually draws the indicator.

Parameters: dc – an instance of wx.DC.

GetId() [source]

Returns the indicator id.

GetImageSize() [source]

Returns the indicator bitmap size.

GetPosition() [source]

Returns the position at which we should draw the indicator bitmap.

GetRect() [source]

Returns the indicator client rectangle.

GetValue() [source]

Returns the indicator value.

RotateImage(img=None) [source]

Rotates the default indicator bitmap.

Parameters: img – if not None, the indicator image.

SetColour(colour) [source]

Sets the indicator colour.

Parameters: colour – the new indicator colour, an instance of wx.Colour.

Note

Requires PIL (Python Imaging Library), which can be downloaded from http://www.pythonware.com/products/pil/

SetValue(value) [source]

Sets the indicator value.

Parameters: value – the new indicator value.

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • infobar
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • rulerctrl »
  • Indicator


Label

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • rulerctrl »
  • Label

Label

Auxilary class. Just holds information about a label in RulerCtrl.

hierarchy Inheritance Diagram

Inheritance diagram for: Label

Inheritance diagram of Label

Methods Summary

__init__ Default class constructor.

API Class API

class Label(object) [source]

Auxilary class. Just holds information about a label in RulerCtrl.

__init__(pos=-1, lx=-1, ly=-1, text='') [source]

Default class constructor.

Parameters:
  • pos – the indicator position;
  • lx – the indicator x coordinate;
  • ly – the indicator y coordinate;
  • text – the label text.

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • infobar
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • rulerctrl »
  • Label


RulerCtrl

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • rulerctrl »
  • RulerCtrl

RulerCtrl

RulerCtrl implements a ruler window that can be placed on top, bottom, left or right to any wxPython widget. It is somewhat similar to the rulers you can find in text editors software, though not so powerful.

hierarchy Inheritance Diagram

Inheritance diagram for: RulerCtrl

Inheritance diagram of RulerCtrl

appearance Control Appearance

RulerCtrl

Methods Summary

__init__ | Default class constructor.
AddIndicator | Adds an indicator to RulerCtrl. You should pass a unique id and a starting
CheckStyle | Adjust the RulerCtrl style accordingly to borders, units, etc...
Draw | Actually draws the whole RulerCtrl.
DrawOnParent | Actually draws the thin line over the drawing parent window.
FindLinearTickSizes | Used internally.
GetBounds | Returns the RulerCtrl bounds (its client rectangle).
GetDrawingParent | Returns the window to which RulerCtrl draws a thin line over.
GetFormat | Returns the format used to display values in RulerCtrl.
GetIndicator | Returns the indicator located at the mouse position mousePos (if any).
GetTimeFormat | Returns the time format.
Invalidate | Invalidates the ticks calculations.
LabelMajor | Sets whether the major ticks should be labeled or not.
LabelMinor | Sets whether the minor ticks should be labeled or not.
LabelString | Used internally.
OfflimitsPixels | Used internally.
OnEraseBackground | Handles the wx.EVT_ERASE_BACKGROUND event for RulerCtrl.
OnMouseEvents | Handles the wx.EVT_MOUSE_EVENTS event for RulerCtrl.
OnPaint | Handles the wx.EVT_PAINT event for RulerCtrl.
OnSize | Handles the wx.EVT_SIZE event for RulerCtrl.
SetBackgroundColour | Sets the RulerCtrl background colour.
SetBounds | Sets the bounds for RulerCtrl (its client rectangle).
SetDrawingParent | Sets the window to which RulerCtrl draws a thin line over.
SetFlip | Sets whether the orientation of the tick marks should be reversed.
SetFonts | Sets the fonts for minor and major tick labels.
SetFormat | Sets the format for RulerCtrl.
SetIndicatorColour | Sets the indicator colour.
SetIndicatorValue | Sets the indicator value.
SetLabelColour | Sets the labels colour.
SetLabelEdges | Sets whether the edge values should always be displayed or not.
SetLog | Sets whether RulerCtrl should have a logarithmic scale or not.
SetOrientation | Sets the RulerCtrl orientation.
SetRange | Sets the RulerCtrl range.
SetSpacing | Sets the RulerCtrl spacing between labels.
SetTickPenColour | Sets the pen colour to draw the ticks.
SetTimeFormat | Sets the time format.
SetUnits | Sets the units that should be displayed beside the labels.
Tick | Ticks a particular position.
TickMajor | Sets whether the major ticks should be ticked or not.
TickMinor | Sets whether the minor ticks should be ticked or not.
Update | Updates all the ticks calculations.

API Class API

class RulerCtrl(wx.PyPanel) [source]

RulerCtrl implements a ruler window that can be placed on top, bottom, left or right to any wxPython widget. It is somewhat similar to the rulers you can find in text editors software, though not so powerful.

__init__(parent, id=-1, pos=wx.DefaultPosition, size=wx.DefaultSize, style=wx.STATIC_BORDER, orient=wx.HORIZONTAL) [source]

Default class constructor.

Parameters:
  • parent – parent window. Must not be None;
  • id – window identifier. A value of -1 indicates a default value;
  • pos – the control position. A value of (-1, -1) indicates a default position, chosen by either the windowing system or wxPython, depending on platform;
  • size – the control size. A value of (-1, -1) indicates a default size, chosen by either the windowing system or wxPython, depending on platform;
  • style – the window style;
  • orient – sets the orientation of the RulerCtrl, and can be either wx.HORIZONTAL of wx.VERTICAL.

AddIndicator(id, value) [source]

Adds an indicator to RulerCtrl. You should pass a unique id and a starting value for the indicator.

Parameters:
  • id – the indicator identifier;
  • value – the indicator initial value.

CheckStyle() [source]

Adjust the RulerCtrl style accordingly to borders, units, etc...

Draw(dc) [source]

Actually draws the whole RulerCtrl.

Parameters: dc – an instance of wx.DC.

DrawOnParent(indicator) [source]

Actually draws the thin line over the drawing parent window.

Parameters: indicator – the current indicator, an instance of Indicator.

Note

This method is currently not available on wxMac as it uses wx.ScreenDC.

FindLinearTickSizes(UPP) [source]

Used internally.

GetBounds() [source]

Returns the RulerCtrl bounds (its client rectangle).

GetDrawingParent() [source]

Returns the window to which RulerCtrl draws a thin line over.

GetFormat() [source]

Returns the format used to display values in RulerCtrl.

See also

SetFormat for a list of possible formats.

GetIndicator(mousePos) [source]

Returns the indicator located at the mouse position mousePos (if any).

Parameters: mousePos – the mouse position, an instance of wx.Point.

GetTimeFormat() [source]

Returns the time format.

Invalidate() [source]

Invalidates the ticks calculations.

LabelMajor(label=True) [source]

Sets whether the major ticks should be labeled or not.

Parameters: label – True to label major ticks, False otherwise.

LabelMinor(label=True) [source]

Sets whether the minor ticks should be labeled or not.

Parameters: label – True to label minor ticks, False otherwise.

LabelString(d, major=None) [source]

Used internally.

OfflimitsPixels(start, end) [source]

Used internally.

OnEraseBackground(event) [source]

Handles the wx.EVT_ERASE_BACKGROUND event for RulerCtrl.

Parameters: event – a wx.EraseEvent event to be processed.

Note

This method is intentionally empty to reduce flicker.

OnMouseEvents(event) [source]

Handles the wx.EVT_MOUSE_EVENTS event for RulerCtrl.

Parameters: event – a wx.MouseEvent event to be processed.

OnPaint(event) [source]

Handles the wx.EVT_PAINT event for RulerCtrl.

Parameters: event – a wx.PaintEvent event to be processed.

OnSize(event) [source]

Handles the wx.EVT_SIZE event for RulerCtrl.

Parameters: event – a wx.SizeEvent event to be processed.

SetBackgroundColour(colour) [source]

Sets the RulerCtrl background colour.

Parameters: colour – an instance of wx.Colour.

Note

Overridden from wx.PyPanel.

SetBounds(left, top, right, bottom) [source]

Sets the bounds for RulerCtrl (its client rectangle).

Parameters:
  • left – the left corner of the client rectangle;
  • top – the top corner of the client rectangle;
  • right – the right corner of the client rectangle;
  • bottom – the bottom corner of the client rectangle.

SetDrawingParent(dparent) [source]

Sets the window to which RulerCtrl draws a thin line over.

Parameters: dparent – an instance of wx.Window, representing the window to which RulerCtrl draws a thin line over.

SetFlip(flip=True) [source]

Sets whether the orientation of the tick marks should be reversed.

Parameters: flip – True to reverse the orientation of the tick marks, False otherwise.

SetFonts(minorFont, majorFont) [source]

Sets the fonts for minor and major tick labels.

Parameters:
  • minorFont – the font used to draw minor ticks, a valid wx.Font object;
  • majorFont – the font used to draw major ticks, a valid wx.Font object.

SetFormat(format) [source]

Sets the format for RulerCtrl.

Parameters: format – the format used to display values in RulerCtrl. This can be one of the following bits:

Format | Value | Description
IntFormat | 1 | Integer format
RealFormat | 2 | Real format
TimeFormat | 3 | Time format
LinearDBFormat | 4 | Linear DB format
HHMMSS_Format | 5 | HHMMSS format

SetIndicatorColour(id, colour=None) [source]

Sets the indicator colour.

Parameters:
  • id – the indicator identifier;
  • colour – a valid wx.Colour object.

Note

This method requires PIL to change the image palette.

SetIndicatorValue(sendEvent=True) [source]

Sets the indicator value.

Parameters: sendEvent – True to send a RulerCtrlEvent, False otherwise.

SetLabelColour(colour=wx.BLACK) [source]

Sets the labels colour.

Parameters: colour – a valid wx.Colour object.

SetLabelEdges(labelEdges=True) [source]

Sets whether the edge values should always be displayed or not.

Parameters: labelEdges – True to always display edge labels, False otherwise/

SetLog(log=True) [source]

Sets whether RulerCtrl should have a logarithmic scale or not.

Parameters: log – True to use a logarithmic scake, False to use a linear one.

SetOrientation(orient=None) [source]

Sets the RulerCtrl orientation.

Parameters: orient – can be wx.HORIZONTAL or wx.VERTICAL.

SetRange(minVal, maxVal) [source]

Sets the RulerCtrl range.

Parameters:
  • minVal – the minimum value of RulerCtrl;
  • maxVal – the maximum value of RulerCtrl.

SetSpacing(spacing) [source]

Sets the RulerCtrl spacing between labels.

Parameters: spacing – the spacing between labels, in pixels.

SetTickPenColour(colour=wx.BLACK) [source]

Sets the pen colour to draw the ticks.

Parameters: colour – a valid wx.Colour object.

SetTimeFormat(format=TimeFormat) [source]

Sets the time format.

Parameters: format – the format used to display time values.

SetUnits(units) [source]

Sets the units that should be displayed beside the labels.

Parameters: units – the units that should be displayed beside the labels.

Tick(dc, pos, d, major) [source]

Ticks a particular position.

Parameters:
  • dc – an instance of wx.DC;

  • pos – the label position;
  • d – the current label value;
  • major – True if it is a major ticks, False if it is a minor one.

TickMajor(tick=True) [source]

Sets whether the major ticks should be ticked or not.

Parameters: tick – True to show major ticks, False otherwise.

TickMinor(tick=True) [source]

Sets whether the minor ticks should be ticked or not.

Parameters: tick – True to show minor ticks, False otherwise.

Update(dc) [source]

Updates all the ticks calculations.

Parameters: dc – an instance of wx.DC.

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • infobar
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • rulerctrl »
  • RulerCtrl


RulerCtrlEvent

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • rulerctrl »
  • RulerCtrlEvent

RulerCtrlEvent

Represent details of the events that the RulerCtrl object sends.

hierarchy Inheritance Diagram

Inheritance diagram for: RulerCtrlEvent

Inheritance diagram of RulerCtrlEvent

Methods Summary

__init__ | Default class constructor.
GetOldValue | Returns the event old value.
GetValue | Returns the event value.
SetOldValue | Sets the event old value.
SetValue | Sets the event value.

API Class API

class RulerCtrlEvent(wx.PyCommandEvent) [source]

Represent details of the events that the RulerCtrl object sends.

__init__(eventType, eventId=1) [source]

Default class constructor.

Parameters:
  • eventType – the event type;
  • eventId – the event identifier.

GetOldValue() [source]

Returns the event old value.

GetValue() [source]

Returns the event value.

SetOldValue(oldValue) [source]

Sets the event old value.

Parameters: value – the old indicator position.

SetValue(value) [source]

Sets the event value.

Parameters: value – the new indicator position.

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • infobar
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • rulerctrl »
  • RulerCtrlEvent


SVN Revision 68362 For rulerctrl

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • rulerctrl »
  • SVN Revision 68362 For rulerctrl

svn SVN Revision 68362 For rulerctrl

This file contains the SVN revision history for rulerctrl, at revision 68362.

Available information include commit date, the name of the committer, the file size, the SVN log messages and a diff from the previous version (if available).

File Information

  • Commit Date: 17-Oct-2008 20:51:43 UTC
  • Committer: AG
  • File Size: 54167 byte(s)

Log Messages

The following log message was entered by the committer:

  • All of AGW: change my work e-mail from KPO to Maersk Oil (silly commit)

Diff To Previous Version (65377)

Version SVN diff:

--- wxPython/3rdParty/AGW/agw/rulerctrl.py  2010/08/21 20:27:02     65377
+++ wxPython/3rdParty/AGW/agw/rulerctrl.py  2011/07/24 21:36:47     68362
@@ -12,7 +12,7 @@
# For All Kind Of Problems, Requests Of Enhancements And Bug Reports, Please
# Write To Me At:
#
-# gavana@kpo.kz
+# andrea.gavana@maerskoil.com
# andrea.gavana@gmail.com
#
# Or, Obviously, To The wxPython Mailing List!!!

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • rulerctrl »
  • SVN Revision 68362 For rulerctrl


SVN Revision 68881 For rulerctrl

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • rulerctrl »
  • SVN Revision 68881 For rulerctrl

svn SVN Revision 68881 For rulerctrl

This file contains the SVN revision history for rulerctrl, at revision 68881.

Available information include commit date, the name of the committer, the file size, the SVN log messages and a diff from the previous version (if available).

File Information

  • Commit Date: 17-Oct-2008 19:15:31 UTC
  • Committer: AG
  • File Size: 55645 byte(s)

Log Messages

The following log message was entered by the committer:

  • AGW: General overhaul of the documentation, much improved. All the widgets have their own sample usage in the docs as well;

  • FlatNotebook: Added the FNB_NAV_BUTTONS_WHEN_NEEDED style, which hides the navigation left/right arrows if all tabs fit;

  • RibbonBar: - Added the EVT_RIBBONBAR_TAB_LEFT_DCLICK event, which generates a special event

    when a ribbon bar tab is double-clicked;

    • Added support for toggle buttons;
    • Improved support for ribbon panel sizers: panels with sizers should now automatically minimise at small sizes, and behave properly when popping up from a minimised state;
    • Added tooltips via SetToolTip for those buttons which have the help_string attribute set.

  • XLSGrid: a new widget was added to AGW, termed XLSGrid. It’s based on wx.grid.Grid and can be used to faithfully reproduce the appearance of a Microsoft Excel spreadsheets.

Diff To Previous Version (68362)

Version SVN diff:

--- wxPython/3rdParty/AGW/agw/rulerctrl.py  2011/07/24 21:36:47     68362
+++ wxPython/3rdParty/AGW/agw/rulerctrl.py  2011/08/25 16:40:17     68881
@@ -2,7 +2,7 @@
# RULERCTRL wxPython IMPLEMENTATION
#
# Andrea Gavana, @ 03 Nov 2006
-# Latest Revision: 01 Dec 2009, 09.00 GMT
+# Latest Revision: 17 Aug 2011, 15.00 GMT
#
#
# TODO List
@@ -22,18 +22,18 @@
# --------------------------------------------------------------------------------- #

"""
-RulerCtrl implements a ruler window that can be placed on top, bottom, left or right
+L{RulerCtrl} implements a ruler window that can be placed on top, bottom, left or right
to any wxPython widget.

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

-RulerCtrl implements a ruler window that can be placed on top, bottom, left or right
+L{RulerCtrl} implements a ruler window that can be placed on top, bottom, left or right
to any wxPython widget. It is somewhat similar to the rulers you can find in text
editors software, though not so powerful.

-RulerCtrl has the following characteristics:
+L{RulerCtrl} has the following characteristics:

- Can be horizontal or vertical;
- 4 built-in formats: integer, real, time and linearDB formats;
@@ -53,10 +53,62 @@
And a lot more. See the demo for a review of the functionalities.

+Usage
+=====
+
+Usage example::
+
+    import wx
+    import wx.lib.agw.rulerctrl as RC
+
+    class MyFrame(wx.Frame):
+
+        def __init__(self, parent):
+
+            wx.Frame.__init__(self, parent, -1, "RulerCtrl Demo")
+
+            panel = wx.Panel(self)
+
+            text = wx.TextCtrl(panel, -1, "Hello World! wxPython rules", style=wx.TE_MULTILINE)
+
+            ruler1 = RC.RulerCtrl(panel, -1, orient=wx.HORIZONTAL, style=wx.SUNKEN_BORDER)
+            ruler2 = RC.RulerCtrl(panel, -1, orient=wx.VERTICAL, style=wx.SUNKEN_BORDER)
+
+            mainsizer = wx.BoxSizer(wx.HORIZONTAL)
+            leftsizer = wx.BoxSizer(wx.VERTICAL)
+            bottomleftsizer = wx.BoxSizer(wx.HORIZONTAL)
+            topsizer = wx.BoxSizer(wx.HORIZONTAL)
+
+            leftsizer.Add((20, 20), 0, wx.ADJUST_MINSIZE, 0)
+            topsizer.Add((39, 0), 0, wx.ADJUST_MINSIZE, 0)
+            topsizer.Add(ruler1, 1, wx.EXPAND, 0)
+            leftsizer.Add(topsizer, 0, wx.EXPAND, 0)
+
+            bottomleftsizer.Add((10, 0))
+            bottomleftsizer.Add(ruler2, 0, wx.EXPAND, 0)
+            bottomleftsizer.Add(text, 1, wx.EXPAND, 0)
+            leftsizer.Add(bottomleftsizer, 1, wx.EXPAND, 0)
+            mainsizer.Add(leftsizer, 3, wx.EXPAND, 0)
+
+            panel.SetSizer(mainsizer)
+
+
+    # our normal wxApp-derived class, as usual
+
+    app = wx.PySimpleApp()
+
+    frame = MyFrame(None)
+    app.SetTopWindow(frame)
+    frame.Show()
+
+    app.MainLoop()
+
+
+
Events
======

-RulerCtrl implements the following events related to indicators:
+L{RulerCtrl} implements the following events related to indicators:

- ``EVT_INDICATOR_CHANGING``: the user is about to change the position of one indicator;
- ``EVT_INDICATOR_CHANGED``: the user has changed the position of one indicator.
@@ -65,7 +117,7 @@
Supported Platforms
===================

-RulerCtrl has been tested on the following platforms:
+L{RulerCtrl} has been tested on the following platforms:
* Windows (Windows XP);
* Linux Ubuntu (Dapper 6.06)

@@ -92,9 +144,9 @@
License And Version
===================

-RulerCtrl is distributed under the wxPython license.
+L{RulerCtrl} is distributed under the wxPython license.

-Latest Revision: Andrea Gavana @ 01 Dec 2009, 09.00 GMT
+Latest Revision: Andrea Gavana @ 17 Aug 2011, 15.00 GMT

Version 0.3

@@ -496,7 +548,7 @@

class RulerCtrl(wx.PyPanel):
"""
-    RulerCtrl implements a ruler window that can be placed on top, bottom, left or right
+    L{RulerCtrl} implements a ruler window that can be placed on top, bottom, left or right
to any wxPython widget. It is somewhat similar to the rulers you can find in text
editors software, though not so powerful.
"""

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • rulerctrl »
  • SVN Revision 68881 For rulerctrl


shapedbutton functions

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • shapedbutton »
  • shapedbutton functions

shapedbutton functions

This is the description of standalone Python functions in the shapedbutton module.

Functions Summary

opj Convert paths to the platform-specific separator.

API Functions API

opj(path) [source]

Convert paths to the platform-specific separator.

Parameters: path – the path to convert.

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • infobar
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • shapedbutton »
  • shapedbutton functions


__SToggleMixin

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • shapedbutton »
  • __SToggleMixin

__SToggleMixin

A mixin that allows to transform any of SButton, SBitmapButton and SBitmapTextButton in the corresponding toggle buttons.

hierarchy Inheritance Diagram

Inheritance diagram for: __SToggleMixin

subclasses Known Subclasses

  • shapedbutton.SBitmapTextToggleButton
  • shapedbutton.SBitmapToggleButton
  • shapedbutton.SToggleButton

Methods Summary

GetToggle | Returns the toggled state of a button.
GetValue | Returns the toggled state of a button.
OnKeyDown | Handles the wx.EVT_KEY_DOWN event for the button.
OnKeyUp | Handles the wx.EVT_KEY_UP event for the button.
OnLeftDown | Handles the wx.EVT_LEFT_DOWN event for the button.
OnLeftUp | Handles the wx.EVT_LEFT_UP event for the button.
OnMotion | Handles the wx.EVT_MOTION event for the button.
SetToggle | Sets the button as toggled/not toggled.
SetValue | Sets the button as toggled/not toggled.

API Class API

class __SToggleMixin(object) [source]

A mixin that allows to transform any of SButton, SBitmapButton and SBitmapTextButton in the corresponding toggle buttons.

GetToggle() [source]

Returns the toggled state of a button.

GetValue()

Returns the toggled state of a button.

OnKeyDown(event) [source]

Handles the wx.EVT_KEY_DOWN event for the button.

Parameters: event – a wx.KeyEvent event to be processed.

OnKeyUp(event) [source]

Handles the wx.EVT_KEY_UP event for the button.

Parameters: event – a wx.KeyEvent event to be processed.

OnLeftDown(event) [source]

Handles the wx.EVT_LEFT_DOWN event for the button.

Parameters: event – a wx.MouseEvent event to be processed.

OnLeftUp(event) [source]

Handles the wx.EVT_LEFT_UP event for the button.

Parameters: event – a wx.MouseEvent event to be processed.

OnMotion(event) [source]

Handles the wx.EVT_MOTION event for the button.

Parameters: event – a wx.MouseEvent event to be processed.

SetToggle(flag) [source]

Sets the button as toggled/not toggled.

Parameters: flag – True to set the button as toggled, False otherwise.

SetValue(flag)

Sets the button as toggled/not toggled.

Parameters: flag – True to set the button as toggled, False otherwise.

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • infobar
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • shapedbutton »
  • __SToggleMixin


SBitmapButton

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • shapedbutton »
  • SBitmapButton

SBitmapButton

Subclass of SButton which displays a bitmap, acting like a wx.BitmapButton.

hierarchy Inheritance Diagram

Inheritance diagram for: SBitmapButton

Inheritance diagram of SBitmapButton

subclasses Known Subclasses

  • shapedbutton.SBitmapTextButton
  • shapedbutton.SBitmapToggleButton

supclasses Known Superclasses

  • shapedbutton.SButton

appearance Control Appearance

SBitmapButton

Methods Summary

__init__ | Default class constructor.
DrawLabel | Draws the bitmap in the middle of the button.
GetBitmapDisabled | Returns the bitmap displayed when the button is disabled.
GetBitmapFocus | Returns the bitmap displayed when the button has the focus.
GetBitmapLabel | Returns the bitmap associated with the button in the normal state.
GetBitmapSelected | Returns the bitmap displayed when the button is selected (pressed).
SetBitmapDisabled | Sets the bitmap to display when the button is disabled.
SetBitmapFocus | Sets the bitmap to display when the button has the focus.
SetBitmapLabel | Sets the bitmap to display normally.
SetBitmapSelected | Sets the bitmap to display when the button is selected (pressed).
_GetLabelSize | Used internally.

API Class API

class SBitmapButton(SButton) [source]

Subclass of SButton which displays a bitmap, acting like a wx.BitmapButton.

__init__(parent, id, bitmap, pos=wx.DefaultPosition, size=wx.DefaultSize) [source]

Default class constructor.

Parameters:
  • parent – the SBitmapButton parent. Must not be None;
  • id – window identifier. A value of -1 indicates a default value;
  • bitmap – the button bitmap (if any);
  • pos – the control position. A value of (-1, -1) indicates a default position, chosen by either the windowing system or wxPython, depending on platform;
  • size – the control size. A value of (-1, -1) indicates a default size, chosen by either the windowing system or wxPython, depending on platform.

DrawLabel(dc, width, height, dw=0, dh=0) [source]

Draws the bitmap in the middle of the button.

Parameters:
  • dc – an instance of wx.DC;
  • width – the button width;
  • height – the button height;
  • dw – width differential, to show a 3D effect;
  • dh – height differential, to show a 3D effect.

GetBitmapDisabled() [source]

Returns the bitmap displayed when the button is disabled.

GetBitmapFocus() [source]

Returns the bitmap displayed when the button has the focus.

GetBitmapLabel() [source]

Returns the bitmap associated with the button in the normal state.

GetBitmapSelected() [source]

Returns the bitmap displayed when the button is selected (pressed).

SetBitmapDisabled(bitmap) [source]

Sets the bitmap to display when the button is disabled.

Parameters: bitmap – a valid wx.Bitmap object.

SetBitmapFocus(bitmap) [source]

Sets the bitmap to display when the button has the focus.

Parameters: bitmap – a valid wx.Bitmap object.

SetBitmapLabel(bitmap, createothers=True) [source]

Sets the bitmap to display normally. This is the only one that is required.

Parameters:
  • bitmap – a valid wx.Bitmap object;

  • createothers – if set to True, then the other bitmaps will be generated on the fly. Currently, only the disabled bitmap is generated.

SetBitmapSelected(bitmap) [source]

Sets the bitmap to display when the button is selected (pressed).

Parameters: bitmap – a valid wx.Bitmap object.

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • infobar
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • shapedbutton »
  • SBitmapButton


SBitmapTextButton

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • shapedbutton »
  • SBitmapTextButton

SBitmapTextButton

Subclass of SButton which displays a bitmap and a label.

hierarchy Inheritance Diagram

Inheritance diagram for: SBitmapTextButton

Inheritance diagram of SBitmapTextButton

subclasses Known Subclasses

  • shapedbutton.SBitmapTextToggleButton

supclasses Known Superclasses

  • shapedbutton.SBitmapButton

appearance Control Appearance

SBitmapTextButton

Methods Summary

__init__ | Default class constructor.
DrawLabel | Draws the bitmap and the text label.
_GetLabelSize | Used internally.

API Class API

class SBitmapTextButton(SBitmapButton) [source]

Subclass of SButton which displays a bitmap and a label.

__init__(parent, id, bitmap, label, pos=wx.DefaultPosition, size=wx.DefaultSize) [source]

Default class constructor.

Parameters:
  • parent – the SBitmapTextButton parent. Must not be None;
  • id – window identifier. A value of -1 indicates a default value;
  • bitmap – the button bitmap (if any);
  • label – the button text label;
  • pos – the control position. A value of (-1, -1) indicates a default position, chosen by either the windowing system or wxPython, depending on platform;
  • size – the control size. A value of (-1, -1) indicates a default size, chosen by either the windowing system or wxPython, depending on platform.

DrawLabel(dc, width, height, dw=0, dh=0) [source]

Draws the bitmap and the text label.

Parameters:
  • dc – an instance of wx.DC;
  • width – the button width;
  • height – the button height;
  • dw – width differential, to show a 3D effect;
  • dh – height differential, to show a 3D effect.

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • infobar
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • shapedbutton »
  • SBitmapTextButton


SBitmapTextToggleButton

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • shapedbutton »
  • SBitmapTextToggleButton

SBitmapTextToggleButton

A ShapedButton toggle bitmap button with a text label.

hierarchy Inheritance Diagram

Inheritance diagram for: SBitmapTextToggleButton

Inheritance diagram of SBitmapTextToggleButton

supclasses Known Superclasses

  • shapedbutton.SBitmapTextButton
  • shapedbutton.__SToggleMixin

appearance Control Appearance

SBitmapTextToggleButton

API Class API

class SBitmapTextToggleButton(__SToggleMixin, SBitmapTextButton) [source]

A ShapedButton toggle bitmap button with a text label.

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • infobar
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • shapedbutton »
  • SBitmapTextToggleButton


SBitmapToggleButton

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • shapedbutton »
  • SBitmapToggleButton

SBitmapToggleButton

A ShapedButton toggle bitmap button.

hierarchy Inheritance Diagram

Inheritance diagram for: SBitmapToggleButton

Inheritance diagram of SBitmapToggleButton

supclasses Known Superclasses

  • shapedbutton.SBitmapButton
  • shapedbutton.__SToggleMixin

appearance Control Appearance

SBitmapToggleButton

API Class API

class SBitmapToggleButton(__SToggleMixin, SBitmapButton) [source]

A ShapedButton toggle bitmap button.

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • infobar
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • shapedbutton »
  • SBitmapToggleButton


SButton

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • shapedbutton »
  • SButton

SButton

This is the main implementation of ShapedButton.

hierarchy Inheritance Diagram

Inheritance diagram for: SButton

Inheritance diagram of SButton

subclasses Known Subclasses

  • shapedbutton.SBitmapButton
  • shapedbutton.SToggleButton

Methods Summary

__init__ | Default class constructor.
AcceptsFocus | Can this window be given focus by mouse click? ..
ConvertPILToWX | Converts a PIL image into a wx.Image.
ConvertWXToPIL | Converts a wx.Image into a PIL image.
DoGetBestSize | Overridden base class virtual.
DrawFocusIndicator | Draws the focus indicator.
DrawLabel | Draws the label on the button.
DrawMainButton | Draws the main button, in whichever state it is.
Enable | Enables/disables the button.
GetAngleOfRotation | Returns angle of button label rotation, in degrees.
GetButtonColour | Returns the button colour.
GetEllipseAxis | Returns the ellipse axes.
GetLabel | Returns the button label.
GetLabelColour | Returns the button label colour.
GetUseFocusIndicator | Returns focus indicator flag.
InitColours | Calculates a new set of focus indicator colour and indicator pen
IsEnabled | Returns wheter the button is enabled or not.
IsOutside | Checks if a mouse events occurred inside the circle/ellipse or not.
MakePalette | Creates a palette to be applied on an image based on input colour.
Notify | Notifies an event and let it be processed.
OnGainFocus | Handles the wx.EVT_SET_FOCUS event for SButton.
OnKeyDown | Handles the wx.EVT_KEY_DOWN event for SButton.
OnKeyUp | Handles the wx.EVT_KEY_UP event for SButton.
OnLeftDown | Handles the wx.EVT_LEFT_DOWN event for SButton.
OnLeftUp | Handles the wx.EVT_LEFT_UP event for SButton.
OnLoseFocus | Handles the wx.EVT_KILL_FOCUS event for SButton.
OnMotion | Handles the wx.EVT_MOTION event for SButton.
OnPaint | Handles the wx.EVT_PAINT event for SButton.
OnSize | Handles the wx.EVT_SIZE event for SButton.
SetAngleOfRotation | Sets angle of button label rotation.
SetBestSize | Given the current font settings, calculate and set a good size.
SetButtonColour | Sets the button colour, for all button states.
SetDefault | Sets the button as default item.
SetEllipseAxis | Sets the ellipse axis.
SetLabel | Sets the button label.
SetLabelColour | Sets the button label colour.
SetUseFocusIndicator | Specifies if a focus indicator (dotted line) should be used.
ShouldInheritColours | Overridden base class virtual.
_GetLabelSize | Used internally

API Class API

class SButton(wx.Window) [source]

This is the main implementation of ShapedButton.

__init__(parent, id=wx.ID_ANY, label="", pos=wx.DefaultPosition, size=wx.DefaultSize) [source]

Default class constructor.

Parameters:
  • parent – the SButton parent. Must not be None;
  • id – window identifier. A value of -1 indicates a default value;
  • label – the button text label;
  • pos – the control position. A value of (-1, -1) indicates a default position, chosen by either the windowing system or wxPython, depending on platform;
  • size – the control size. A value of (-1, -1) indicates a default size, chosen by either the windowing system or wxPython, depending on platform.

AcceptsFocus() [source]

Can this window be given focus by mouse click?

Note

Overridden from wx.Window.

ConvertPILToWX(pil, alpha=True) [source]

Converts a PIL image into a wx.Image.

Parameters:
  • pil – a PIL image;
  • alpha – True if the image contains alpha transparency, False otherwise.

ConvertWXToPIL(bmp) [source]

Converts a wx.Image into a PIL image.

Parameters: bmp – an instance of wx.Image.

DoGetBestSize() [source]

Overridden base class virtual. Determines the best size of the button based on the label size.

Note

Overridden from wx.Window.

DrawFocusIndicator(dc, width, height) [source]

Draws the focus indicator. This is a circle/ellipse inside the button drawn with a dotted-style pen, to let the user know which button has the focus.

Parameters:
  • dc – an instance of wx.DC;
  • width – the button width;
  • height – the button height.

DrawLabel(dc, width, height, dw=0, dh=0) [source]

Draws the label on the button.

Parameters:
  • dc – an instance of wx.DC;

  • width – the button width;
  • height – the button height;
  • dw – width differential, to show a 3D effect;
  • dh – height differential, to show a 3D effect.

DrawMainButton(dc, width, height) [source]

Draws the main button, in whichever state it is.

Parameters:
  • dc – an instance of wx.DC;

  • width – the button width;
  • height – the button height.

Enable(enable=True) [source]

Enables/disables the button.

Parameters: enable – True to enable the button, False to disable it.

Note

Overridden from wx.Window.

GetAngleOfRotation() [source]

Returns angle of button label rotation, in degrees.

GetButtonColour() [source]

Returns the button colour.

GetEllipseAxis() [source]

Returns the ellipse axes.

GetLabel() [source]

Returns the button label.

GetLabelColour() [source]

Returns the button label colour.

GetUseFocusIndicator() [source]

Returns focus indicator flag.

InitColours() [source]

Calculates a new set of focus indicator colour and indicator pen based on button colour and label colour.

IsEnabled() [source]

Returns wheter the button is enabled or not.

IsOutside(x, y) [source]

Checks if a mouse events occurred inside the circle/ellipse or not.

Parameters:
  • x – the mouse x position;
  • y – the mouse y position.

MakePalette(tr, tg, tb) [source]

Creates a palette to be applied on an image based on input colour.

Parameters:
  • tr – the red intensity of the input colour;
  • tg – the green intensity of the input colour;
  • tb – the blue intensity of the input colour.

Notify() [source]

Notifies an event and let it be processed.

OnGainFocus(event) [source]

Handles the wx.EVT_SET_FOCUS event for SButton.

Parameters: event – a wx.FocusEvent event to be processed.

OnKeyDown(event) [source]

Handles the wx.EVT_KEY_DOWN event for SButton.

Parameters: event – a wx.KeyEvent event to be processed.

OnKeyUp(event) [source]

Handles the wx.EVT_KEY_UP event for SButton.

Parameters: event – a wx.KeyEvent event to be processed.

OnLeftDown(event) [source]

Handles the wx.EVT_LEFT_DOWN event for SButton.

Parameters: event – a wx.MouseEvent event to be processed.

OnLeftUp(event) [source]

Handles the wx.EVT_LEFT_UP event for SButton.

Parameters: event – a wx.MouseEvent event to be processed.

OnLoseFocus(event) [source]

Handles the wx.EVT_KILL_FOCUS event for SButton.

Parameters: event – a wx.FocusEvent event to be processed.

OnMotion(event) [source]

Handles the wx.EVT_MOTION event for SButton.

Parameters: event – a wx.MouseEvent event to be processed.

OnPaint(event) [source]

Handles the wx.EVT_PAINT event for SButton.

Parameters: event – a wx.PaintEvent event to be processed.

OnSize(event) [source]

Handles the wx.EVT_SIZE event for SButton.

Parameters: event – a wx.SizeEvent event to be processed.

SetAngleOfRotation(angle=None) [source]

Sets angle of button label rotation.

Parameters: angle – the label rotation, in degrees.

SetBestSize(size=None) [source]

Given the current font settings, calculate and set a good size.

Parameters: size – if not None, an instance of wx.Size to pass to SetInitialSize.

SetButtonColour(colour=None) [source]

Sets the button colour, for all button states.

Parameters: colour – an instance of wx.Colour.

Note

The original button images are greyscale with a lot of pixels with different colours. Changing smoothly the button colour in order to give the same 3D effect can be efficiently done only with PIL.

SetDefault() [source]

Sets the button as default item.

SetEllipseAxis(main=None, secondary=None) [source]

Sets the ellipse axis. What it is important is not their absolute values but their ratio.

Parameters:
  • main – a floating point number representing the absolute dimension of the main ellipse axis;
  • secondary – a floating point number representing the absolute dimension of the secondary ellipse axis.

SetLabel(label=None) [source]

Sets the button label.

Parameters: label – the new button label.

SetLabelColour(colour=None) [source]

Sets the button label colour.

Parameters: colour – an instance of wx.Colour.

SetUseFocusIndicator(flag) [source]

Specifies if a focus indicator (dotted line) should be used.

Parameters: flag – True to use the focus indicator, False otherwise.

ShouldInheritColours() [source]

Overridden base class virtual. Buttons usually do not inherit parent’s colours.

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • infobar
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • shapedbutton »
  • SButton


SButtonEvent

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • shapedbutton »
  • SButtonEvent

SButtonEvent

Event sent from the generic buttons when the button is activated.

hierarchy Inheritance Diagram

Inheritance diagram for: SButtonEvent

Inheritance diagram of SButtonEvent

Methods Summary

__init__ | Default class constructor.
GetButtonObj | Returns the object associated with this event.
GetIsDown | Returns True if the button event is “pressed”.
SetButtonObj | Sets the event object for the event.
SetIsDown | Sets the button event as pressed.

API Class API

class SButtonEvent(wx.PyCommandEvent) [source]

Event sent from the generic buttons when the button is activated.

__init__(eventType, eventId) [source]

Default class constructor.

Parameters:
  • eventType – the event type;
  • eventId – the event identifier.

GetButtonObj() [source]

Returns the object associated with this event.

GetIsDown() [source]

Returns True if the button event is “pressed”.

SetButtonObj(btn) [source]

Sets the event object for the event.

Parameters: btn – the button object.

SetIsDown(isDown) [source]

Sets the button event as pressed.

Parameters: isDown – True to set the event as “pressed”, False otherwise.

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • infobar
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • shapedbutton »
  • SButtonEvent


SToggleButton

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • shapedbutton »
  • SToggleButton

SToggleButton

A ShapedButton toggle button.

hierarchy Inheritance Diagram

Inheritance diagram for: SToggleButton

Inheritance diagram of SToggleButton

supclasses Known Superclasses

  • shapedbutton.SButton
  • shapedbutton.__SToggleMixin

API Class API

class SToggleButton(__SToggleMixin, SButton) [source]

A ShapedButton toggle button.

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • infobar
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • shapedbutton »
  • SToggleButton


SVN Revision 68362 For shapedbutton

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • shapedbutton »
  • SVN Revision 68362 For shapedbutton

svn SVN Revision 68362 For shapedbutton

This file contains the SVN revision history for shapedbutton, at revision 68362.

Available information include commit date, the name of the committer, the file size, the SVN log messages and a diff from the previous version (if available).

File Information

  • Commit Date: 02-Jan-2009 03:09:18 UTC
  • Committer: AG
  • File Size: 67953 byte(s)

Log Messages

The following log message was entered by the committer:

  • All of AGW: change my work e-mail from KPO to Maersk Oil (silly commit)

Diff To Previous Version (65377)

Version SVN diff:

--- wxPython/3rdParty/AGW/agw/shapedbutton.py       2010/08/21 20:27:02     65377
+++ wxPython/3rdParty/AGW/agw/shapedbutton.py       2011/07/24 21:36:47     68362
@@ -30,7 +30,7 @@
# Write To Me At:
#
# andrea.gavana@gmail.com
-# gavana@kpo.kz
+# andrea.gavana@maerskoil.com
#
# Or, Obviously, To The wxPython Mailing List!!!
#

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • shapedbutton »
  • SVN Revision 68362 For shapedbutton


SVN Revision 68881 For shapedbutton

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • shapedbutton »
  • SVN Revision 68881 For shapedbutton

svn SVN Revision 68881 For shapedbutton

This file contains the SVN revision history for shapedbutton, at revision 68881.

Available information include commit date, the name of the committer, the file size, the SVN log messages and a diff from the previous version (if available).

File Information

  • Commit Date: 17-Oct-2008 20:51:43 UTC
  • Committer: AG
  • File Size: 68352 byte(s)

Log Messages

The following log message was entered by the committer:

  • AGW: General overhaul of the documentation, much improved. All the widgets have their own sample usage in the docs as well;

  • FlatNotebook: Added the FNB_NAV_BUTTONS_WHEN_NEEDED style, which hides the navigation left/right arrows if all tabs fit;

  • RibbonBar: - Added the EVT_RIBBONBAR_TAB_LEFT_DCLICK event, which generates a special event

    when a ribbon bar tab is double-clicked;

    • Added support for toggle buttons;
    • Improved support for ribbon panel sizers: panels with sizers should now automatically minimise at small sizes, and behave properly when popping up from a minimised state;
    • Added tooltips via SetToolTip for those buttons which have the help_string attribute set.

  • XLSGrid: a new widget was added to AGW, termed XLSGrid. It’s based on wx.grid.Grid and can be used to faithfully reproduce the appearance of a Microsoft Excel spreadsheets.

Diff To Previous Version (68362)

Version SVN diff:

--- wxPython/3rdParty/AGW/agw/shapedbutton.py       2011/07/24 21:36:47     68362
+++ wxPython/3rdParty/AGW/agw/shapedbutton.py       2011/08/25 16:40:17     68881
@@ -3,7 +3,7 @@
# Python Code By:
#
# Andrea Gavana, @ 18 Oct 2005
-# Latest Revision: 15 Aug 2010, 15.00 GMT
+# Latest Revision: 17 Aug 2011, 15.00 GMT
#
#
# TODO List/Caveats
@@ -40,14 +40,14 @@

"""
-ShapedButton tries to fill the lack of "custom shaped" controls in wxPython
+`ShapedButton` tries to fill the lack of "custom shaped" controls in wxPython
and it can be used to build round or elliptic-shaped buttons.

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

-ShapedButton tries to fill the lack of "custom shaped" controls in wxPython
+`ShapedButton` tries to fill the lack of "custom shaped" controls in wxPython
(that depends on the same lack in wxWidgets). It can be used to build round
buttons or elliptic buttons.

@@ -57,55 +57,72 @@
classes (with "Gen" replaced by "S"), with the same event handling, but they
are rounded/elliptical buttons.

-ShapedButton is based on a `wx.Window`, in which 2 images are drawn depending
+`ShapedButton` is based on a `wx.Window`, in which 2 images are drawn depending
on the button state (pressed or not pressed). The 2 images have been stolen
from Audacity (written with wxWidgets) and rearranged/reshaped/restyled
using adobe PhotoShop.
Changing the button colour in runtime was more difficult, but using some
intelligent instruction from the PIL library it can be done.

-ShapedButton reacts on mouse events *only* if the mouse event occurred inside
-the circle/ellipse, even if ShapedButton is built on a rectangular window.
+`ShapedButton` reacts on mouse events *only* if the mouse event occurred inside
+the circle/ellipse, even if `ShapedButton` is built on a rectangular window.
This behavior is a lot different with respect to Audacity round buttons.

Usage
=====

-The ShapedButton constructions, excluding wxPython parameter are, for the
-6 Classes::
+Usage example::

-    MyShapedButton = SButton(parent, label)
+    import wx
+    import wx.lib.agw.shapedbutton as SB

-    MyShapedButton = SBitmapButton(parent, bitmap)
+    class MyFrame(wx.Frame):

-    MyShapedButton = SBitmapTextButton(parent, bitmap, label)
+        def __init__(self, parent):
+
+            wx.Frame.__init__(self, parent, -1, "ShapedButton Demo")
+
+            panel = wx.Panel(self)

-    MyShapedButton = SToggleButton(parent, label)
+            # Create 2 bitmaps for the button
+            upbmp = wx.Bitmap("play.png", wx.BITMAP_TYPE_PNG)
+            disbmp = wx.Bitmap("playdisabled.png", wx.BITMAP_TYPE_PNG)
+
+            play = SB.SBitmapToggleButton(panel, -1, upbmp, (100, 50))
+            play.SetUseFocusIndicator(False)
+            play.SetBitmapDisabled(disbmp)
+
+
+    # our normal wxApp-derived class, as usual

-    MyShapedButton = SBitmapToggleButton(parent, bitmap)
+    app = wx.PySimpleApp()

-    MyShapedButton = SBitmapTextToggleButton(parent, bitmap, label)
+    frame = MyFrame(None)
+    app.SetTopWindow(frame)
+    frame.Show()

+    app.MainLoop()

-The ShapedButton construction and usage is quite similar to the `wx.lib.buttons`
+
+The `ShapedButton` construction and usage is quite similar to the `wx.lib.buttons`
implementation.

Methods and Settings
====================

-With ShapedButton you can:
+With `ShapedButton` you can:

-- create rounded/elliptical buttons/togglebuttons;
+- Create rounded/elliptical buttons/togglebuttons;
- Set images for the enabled/disabled/focused/selected state of the button;
- Draw the focus indicator (or disable it);
- Set label colour and font;
-- Apply a rotation to the ShapedButton label;
-- Change ShapedButton shape and text orientation in runtime.
+- Apply a rotation to the `ShapedButton` label;
+- Change `ShapedButton` shape and text orientation in runtime.

-:note: ShapedButton **requires** PIL (Python Imaging Library) library to be installed,
+:note: `ShapedButton` **requires** PIL (Python Imaging Library) library to be installed,
which can be downloaded from http://www.pythonware.com/products/pil/ .

@@ -130,9 +147,9 @@
License And Version
===================

-ShapedButton is distributed under the wxPython license.
+`ShapedButton` is distributed under the wxPython license.

-Latest revision: Andrea Gavana @ 15 Aug 2010, 15.00 GMT
+Latest revision: Andrea Gavana @ 17 Aug 2011, 15.00 GMT

Version 0.4

@@ -144,7 +161,6 @@
#----------------------------------------------------------------------

import wx
-from wx.lib import imageutils

# First Check If PIL Is Installed Properly
try:
@@ -252,7 +268,7 @@
#----------------------------------------------------------------------

class SButton(wx.Window):
-    """ This is the main implementation of ShapedButton. """
+    """ This is the main implementation of `ShapedButton`. """

_labeldelta = 1

@@ -394,6 +410,8 @@
"""
Overridden base class virtual. Determines the best size of the button
based on the label size.
+
+        :note: Overridden from `wx.Window`.
"""

w, h, usemin = self._GetLabelSize()
@@ -906,7 +924,7 @@

if alpha:
image = apply(wx.EmptyImage, pil.size)
-            image.SetData( pil.convert("RGB").tostring() )
+            image.SetData(pil.convert("RGB").tostring())
image.SetAlphaData(pil.convert("RGBA").tostring()[3::4])
else:
image = wx.EmptyImage(pil.size[0], pil.size[1])
@@ -1065,9 +1083,8 @@
self._bmplabel = bitmap

if bitmap is not None and createothers:
-            image = wx.ImageFromBitmap(bitmap)
-            imageutils.grayOut(image)
-            self.SetBitmapDisabled(wx.BitmapFromImage(image))
+            dis_bitmap = wx.BitmapFromImage(bitmap.ConvertToImage().ConvertToGreyscale())
+            self.SetBitmapDisabled(dis_bitmap)

def _GetLabelSize(self):
@@ -1368,7 +1385,7 @@
#----------------------------------------------------------------------

class SToggleButton(__SToggleMixin, SButton):
-    """ A ShapedButton toggle button. """
+    """ A `ShapedButton` toggle button. """
pass

@@ -1377,7 +1394,7 @@
#----------------------------------------------------------------------

class SBitmapToggleButton(__SToggleMixin, SBitmapButton):
-    """ A ShapedButton toggle bitmap button. """
+    """ A `ShapedButton` toggle bitmap button. """
pass

@@ -1386,7 +1403,7 @@
#----------------------------------------------------------------------

class SBitmapTextToggleButton(__SToggleMixin, SBitmapTextButton):
-    """ A ShapedButton toggle bitmap button with a text label. """
+    """ A `ShapedButton` toggle bitmap button with a text label. """
pass

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • shapedbutton »
  • SVN Revision 68881 For shapedbutton


SVN Revision 70370 For shapedbutton

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • shapedbutton »
  • SVN Revision 70370 For shapedbutton

svn SVN Revision 70370 For shapedbutton

This file contains the SVN revision history for shapedbutton, at revision 70370.

Available information include commit date, the name of the committer, the file size, the SVN log messages and a diff from the previous version (if available).

File Information

  • Commit Date: 17-Oct-2008 19:15:31 UTC
  • Committer: AG
  • File Size: 68358 byte(s)

Log Messages

The following log message was entered by the committer:

ShapedButton: fix incorrect KeyCode() (just replace it with GetKeyCode()). Closes ticket #13842.

Diff To Previous Version (68881)

Version SVN diff:

--- wxPython/3rdParty/AGW/agw/shapedbutton.py       2011/08/25 16:40:17     68881
+++ wxPython/3rdParty/AGW/agw/shapedbutton.py       2012/01/16 20:37:28     70370
@@ -3,7 +3,7 @@
# Python Code By:
#
# Andrea Gavana, @ 18 Oct 2005
-# Latest Revision: 17 Aug 2011, 15.00 GMT
+# Latest Revision: 16 Jan 2012, 20.00 GMT
#
#
# TODO List/Caveats
@@ -149,7 +149,7 @@

`ShapedButton` is distributed under the wxPython license.

-Latest revision: Andrea Gavana @ 17 Aug 2011, 15.00 GMT
+Latest revision: Andrea Gavana @ 16 Jan 2012, 20.00 GMT

Version 0.4

@@ -859,7 +859,7 @@
:param `event`: a `wx.KeyEvent` event to be processed.
"""

-        if self._hasfocus and event.KeyCode() == ord(" "):
+        if self._hasfocus and event.GetKeyCode() == ord(" "):

self._isup = False
self.Refresh()
@@ -1371,7 +1371,7 @@
:param `event`: a `wx.KeyEvent` event to be processed.
"""

-        if self._hasfocus and event.KeyCode() == ord(" "):
+        if self._hasfocus and event.GetKeyCode() == ord(" "):

self._isup = not self._isup
self.Notify()

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • shapedbutton »
  • SVN Revision 70370 For shapedbutton


shortcuteditor functions

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • shortcuteditor »
  • shortcuteditor functions

shortcuteditor functions

This is the description of standalone Python functions in the shortcuteditor module.

Functions Summary

FontFromFont Creates a copy of the input font.

API Functions API

FontFromFont(font) [source]

Creates a copy of the input font.

Parameters: font – an instance of wx.Font.

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • infobar
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • shortcuteditor »
  • shortcuteditor functions


ConflictDialog

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • shortcuteditor »
  • ConflictDialog

ConflictDialog

ConflictDialog is a subclass of GenericMessageDialog, customized to look like the GIMP conflict dialog. This class is used to resolve shortcut conflicts when the user assigns a shortcut that is already taken by another entry in the shortcut list.

hierarchy Inheritance Diagram

Inheritance diagram for: ConflictDialog

Inheritance diagram of ConflictDialog

supclasses Known Superclasses

  • genericmessagedialog.GenericMessageDialog

Methods Summary

__init__ Default class constructor.

API Class API

class ConflictDialog(GMD.GenericMessageDialog) [source]

ConflictDialog is a subclass of GenericMessageDialog, customized to look like the GIMP conflict dialog. This class is used to resolve shortcut conflicts when the user assigns a shortcut that is already taken by another entry in the shortcut list.

__init__(parent, conflict) [source]

Default class constructor.

Parameters:
  • parent – an instance of ShortcutEditor;
  • conflict – an instance of Shortcut, representing the conflicting shortcut.

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • infobar
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • shortcuteditor »
  • ConflictDialog


HTMLHelpWindow

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • shortcuteditor »
  • HTMLHelpWindow

HTMLHelpWindow

A simple wx.Frame container for the basic help provided to ShortcutEditor. The help page is actually straightly derived from:

http://graphicssoft.about.com/od/gimptutorials/tp/keyboard-shortcut-editor.htm

hierarchy Inheritance Diagram

Inheritance diagram for: HTMLHelpWindow

Inheritance diagram of HTMLHelpWindow

Methods Summary

__init__ | Default class constructor.
BuildToolBar | Creates a toolbar for HTMLHelpWindow containing the standard browsing
OnClose | Handles the wx.EVT_CLOSE event for HTMLHelpWindow.
OnHTMLToolbar | Handles all the wx.EVT_TOOL events for HTMLHelpWindow.
OnUpdateUI | Handles all the wx.EVT_UPDATE_UI events for HTMLHelpWindow.

API Class API

class HTMLHelpWindow(wx.Frame) [source]

A simple wx.Frame container for the basic help provided to ShortcutEditor. The help page is actually straightly derived from:

http://graphicssoft.about.com/od/gimptutorials/tp/keyboard-shortcut-editor.htm

__init__(parent, htmlFile) [source]

Default class constructor.

Parameters:
  • parent – an instance of ShortcutEditor;
  • htmlFile (string) – a valid HTML file containing either the default help or your particular definition of help.

BuildToolBar(toolbar) [source]

Creates a toolbar for HTMLHelpWindow containing the standard browsing buttons like Back, Forward, Home, Refresh and Print.

Parameters: toolbar – an instance of wx.ToolBar.

OnClose(event) [source]

Handles the wx.EVT_CLOSE event for HTMLHelpWindow.

Parameters: event – an instance of wx.CloseEvent.

OnHTMLToolbar(event) [source]

Handles all the wx.EVT_TOOL events for HTMLHelpWindow.

Parameters: event – an instance of wx.CommandEvent.

OnUpdateUI(event) [source]

Handles all the wx.EVT_UPDATE_UI events for HTMLHelpWindow.

Parameters: event – an instance of wx.UpdateUIEvent.

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • infobar
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • shortcuteditor »
  • HTMLHelpWindow


ListShortcut

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • shortcuteditor »
  • ListShortcut

ListShortcut

ListShortcut is a subclass of HyperTreeList, customized to look like the GIMP main shortcut list. This class is used to display the shortcut label (with an optional bitmap next to it), its accelerator and the help string associated with it (if present).

This information is displayed in 3 columns inside ListShortcut.

hierarchy Inheritance Diagram

Inheritance diagram for: ListShortcut

Inheritance diagram of ListShortcut

supclasses Known Superclasses

  • hypertreelist.HyperTreeList

Methods Summary

__init__ | Default class constructor.
AcceptShortcut | Returns True if the input accelerator is a valid shortcut, False otherwise.
BuildImageList | Recursively builds the ListShortcut image list based on the bitmaps in the
CalculateOffset | Calculates an offset (in pixels) so that the Shortcut items without
DisableShortcut | If the user decides to reassign a shortcut to another item, this method will disable
FireShortcutChanged | Fires the EVT_SHORTCUT_CHANGED event for ListShortcut.
FireShortcutChanging | Fires the EVT_SHORTCUT_CHANGING event for ListShortcut.
GetItemIdentity | Return a hashable object that represents the identity of a ListShortcut item.
HasFlag | Overridden from wx.Window as a workaround on the conflicts between treemixin and
MakeImageList | Builds the ListShortcut image list based on the bitmaps in the Shortcut hierarchy.
OnExpandCollapse | Handles the wx.EVT_TREE_ITEM_COLLAPSED / wx.EVT_TREE_ITEM_EXPANDED events for ListShortcut.
OnKillFocus | Handles the wx.EVT_KILL_FOCUS event for ListShortcut.
OnLeftDown | Handles the wx.EVT_LEFT_DOWN event for ListShortcut.
OnSelChanged | Handles the wx.EVT_TREE_SEL_CHANGED event for ListShortcut.
OnShortcut | Handles the wx.EVT_CHAR_HOOK event for ShortcutEditor, implemented in ListShortcut
Populate | Recursively populates the ListShortcut with information from the Shortcut tree.
RecreateTree | Recreates the entire ListShortcut (columns excluded).
SetFilter | Sets the filter string against all the shortcuts in the ListShortcut are matched.
ShowShortcutText | Shows/Hides a wx.TextCtrl used to display the combination of keystrokes the user

API Class API

class ListShortcut(HTL.HyperTreeList, treemixin.ExpansionState) [source]

ListShortcut is a subclass of HyperTreeList, customized to look like the GIMP main shortcut list. This class is used to display the shortcut label (with an optional bitmap next to it), its accelerator and the help string associated with it (if present).

This information is displayed in 3 columns inside ListShortcut.

__init__(parent) [source]

Default class constructor.

Parameters: parent – an instance of ShortcutEditor.

AcceptShortcut(shortcut, accelerator) [source]

Returns True if the input accelerator is a valid shortcut, False otherwise.

Parameters:
  • shortcut – an instance of Shortcut;
  • accelerator (string) – the new accelerator to check.

Note

Conflicting shortcuts are handled inside this method by presenting the user with a conflict dialog. At this point the user can decide to reassign an existing shortcut or to back away, in which case this method will return False.

BuildImageList(shortcut=None, index=None) [source]

Recursively builds the ListShortcut image list based on the bitmaps in the Shortcut hierarchy.

Parameters:
  • shortcut – an instance of Shortcut. If None, it is defaulted to self.manager to make this function reentrant (i.e. allow more than one enumeration on one and the same object simultaneously);
  • index (integer) – the current image index inside the ListShortcut own wx.ImageList.

CalculateOffset() [source]

Calculates an offset (in pixels) so that the Shortcut items without a bitmap look parallel to the ones with a bitmap.

DisableShortcut(conflict, item=None) [source]

If the user decides to reassign a shortcut to another item, this method will disable the conflicting shortcut (by putting a “Disabled” string as its accelerator).

Parameters:
  • conflict – an instance of Shortcut to reset;
  • item – an instance of GenericTreeItem. If defaulted to None, it is set to the ListShortcut root item and used only to make this function reentrant (i.e. allow more than one enumeration on one and the same object simultaneously).

FireShortcutChanged(shortcut, newAccel) [source]

Fires the EVT_SHORTCUT_CHANGED event for ListShortcut.

Parameters:
  • shortcut – an instance of Shortcut that has been renamed;
  • newAccel (string) – the new accelerator just entered by the user.

FireShortcutChanging(shortcut, newAccel) [source]

Fires the EVT_SHORTCUT_CHANGING event for ListShortcut.

The event propagation (and thus the shortcut renaming by the user) can be interrupted by not calling event.Skip() in your handler for this event.

Parameters:
  • shortcut – an instance of Shortcut that is about to be renamed;
  • newAccel (string) – the new accelerator just entered by the user.

GetItemIdentity(item) [source]

Return a hashable object that represents the identity of a ListShortcut item.

In this implementation this returns the item label.

Parameters: item – an instance of GenericTreeItem.

HasFlag(flag) [source]

Overridden from wx.Window as a workaround on the conflicts between treemixin and HyperTreeList with the wx.TR_HIDE_ROOT agwStyle set.

Parameters: flag (integer) – an integer bit flag specifying the agwStyle style.
Returns: True if the ListShortcut has the input flag set, False otherwise.

Note

Overridden from wx.Window.

MakeImageList() [source]

Builds the ListShortcut image list based on the bitmaps in the Shortcut hierarchy.

OnExpandCollapse(event) [source]

Handles the wx.EVT_TREE_ITEM_COLLAPSED / wx.EVT_TREE_ITEM_EXPANDED events for ListShortcut.

Parameters: event – an instance of wx.TreeEvent.

OnKillFocus(event) [source]

Handles the wx.EVT_KILL_FOCUS event for ListShortcut.

Parameters: event – an instance of wx.FocusEvent.

OnLeftDown(event) [source]

Handles the wx.EVT_LEFT_DOWN event for ListShortcut.

Parameters: event – an instance of wx.MouseEvent.

OnSelChanged(event) [source]

Handles the wx.EVT_TREE_SEL_CHANGED event for ListShortcut.

Parameters: event – an instance of wx.TreeEvent.

OnShortcut(event) [source]

Handles the wx.EVT_CHAR_HOOK event for ShortcutEditor, implemented in ListShortcut as it is easier to deal with in this class.

Parameters: event – an instance of wx.KeyEvent.

Populate(item=None, shortcut=None) [source]

Recursively populates the ListShortcut with information from the Shortcut tree.

Parameters:
  • item – an instance of GenericTreeItem. If None, it is defaulted to the ListShortcut root item to make this function reentrant (i.e. allow more than one enumeration on one and the same object simultaneously);
  • shortcut – an instance of Shortcut. If None, it is defaulted to self.manager to make this function reentrant (i.e. allow more than one enumeration on one and the same object simultaneously).

RecreateTree() [source]

Recreates the entire ListShortcut (columns excluded).

SetFilter(filter=u'') [source]

Sets the filter string against all the shortcuts in the ListShortcut are matched.

Parameters: filter (string) – a string to match.

ShowShortcutText(show) [source]

Shows/Hides a wx.TextCtrl used to display the combination of keystrokes the user has entered. This wx.TextCtrl remains visible only for a short amount of time and only when some keys are down.

Parameters: show (bool) – True to show the wx.TextCtrl, False to hide it.

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • infobar
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • shortcuteditor »
  • ListShortcut


Shortcut

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • shortcuteditor »
  • Shortcut

Shortcut

Shortcut is a class containing the details for a shortcut, whether from a menu item, an accelerator or a user-defined shortcut. It behaves like a tree, with children and parents.

hierarchy Inheritance Diagram

Inheritance diagram for: Shortcut

Inheritance diagram of Shortcut

Methods Summary

__init__ | Default class constructor.
AppendItem | Appends a Shortcut item as a last child of its parent.
CheckAccelerator | Checks if a shortcut string entered by the user has already been taken by another entry
FromMenuItem | Constructs this Shortcut starting from a wx.Menu or wx.MenuItem.
Get | Returns an instance of Shortcut whose label matches the input label string.
GetAccelerator | Returns the string accelerator associated with this shortcut.
GetBitmap | Returns the bitmap associated with this Shortcut.
GetById | Returns an instance of Shortcut whose ID matches the input id.
GetFirstChild | Returns this Shortcut‘s first child and an integer value ‘cookie’.
GetId | Returns this Shortcut ID.
GetImageIndex | Returns an integer index to be used in the ListShortcut own wx.ImageList.
GetLabel | Returns the string label associated with this shortcut.
GetNextChild | Returns this Shortcut‘s next child.
HasChanged | Returns True if the current accelerator associated with this Shortcut is
IsTop | Returns True if this Shortcut is associated with a top-level wx.Menu,
Match | Matches this Shortcut label string against the filter input variable.
ResetVisibility | Set the status of this Shortcut and its parent as hidden in the
RestoreDefaults | Restore the original shortcut string for this Shortcut.
SetAccelerator | Sets the string accelerator associated with this shortcut.
SetBitmap | Sets the bitmap associated with this Shortcut.
ShowHierarchy | Set the status of this Shortcut ans its parent as shown in the
ToAcceleratorItem | Dumps this Shortcut into a tuple of 3 elements:
ToMenuItem | Dumps this Shortcut into a wx.Menu or wx.MenuItem.

API Class API

class Shortcut(object) [source]

Shortcut is a class containing the details for a shortcut, whether from a menu item, an accelerator or a user-defined shortcut. It behaves like a tree, with children and parents.

__init__(label='', accelerator='', bitmap=wx.NullBitmap, help='', menuItem=None, accelId=None) [source]

Default class constructor.

Parameters:
  • label (string) – the shortcut label string;
  • accelerator (string) – the shortcut accelerator string;
  • bitmap – an instance of wx.Bitmap, to display along the shortcut label in the interface tree;
  • help (string) – the help string for this shortcut, to display in the interface tree;
  • menuItem – if this Shortcut is derived from a wx.MenuItem, the wx.MenuItem to which it should be associated;

  • accelId (integer) – if this Shortcut is derived from an accelerator in a wx.AcceleratorTable or from a custom, developer-defined shortcut, it represents the ID it is associated with.

AppendItem(item) [source]

Appends a Shortcut item as a last child of its parent.

Parameters: item – an instance of Shortcut.

CheckAccelerator(item, shortcut, accelerator) [source]

Checks if a shortcut string entered by the user has already been taken by another entry in the Shortcut hierarchy.

Parameters:
  • item – an instance of Shortcut;
  • shortcut – another instance of Shortcut, to compare with the previous item;
  • accelerator (string) – the user-edited accelerator string to check.
Returns:

An instance of Shortcut if the shortcut string entered by the user conflicts with an existing one, None otherwise.

FromMenuItem() [source]

Constructs this Shortcut starting from a wx.Menu or wx.MenuItem.

The attributes needed to properly construct a Shortcut are the label, the accelerator string, the help string (optional) and the bitmap associated with it (optional).

Get(label, item=None) [source]

Returns an instance of Shortcut whose label matches the input label string.

Parameters:
  • label (string) – the string label to compare against this Shortcut label;
  • item – an instance of Shortcut, used only to make this function reentrant (i.e. allow more than one enumeration on one and the same object simultaneously).
Returns:

An instance of Shortcut or None if no match was found.

GetAccelerator() [source]

Returns the string accelerator associated with this shortcut.

GetBitmap() [source]

Returns the bitmap associated with this Shortcut.

Note

You should always check if the returned bitmap is a valid one or not:

bitmap = shortcut.GetBitmap()
if bitmap.IsOk():
    DoSomething()

as the default bitmap associated with a Shortcut is wx.NullBitmap.

GetById(id, item=None) [source]

Returns an instance of Shortcut whose ID matches the input id.

Parameters:
  • id (integer) – an integer ID to compare against this Shortcut id;
  • item – an instance of Shortcut, used only to make this function reentrant (i.e. allow more than one enumeration on one and the same object simultaneously).
Returns:

An instance of Shortcut or None if no match was found.

GetFirstChild(item) [source]

Returns this Shortcut‘s first child and an integer value ‘cookie’. Call GetNextChild for the next child using this very ‘cookie’ return value as an input.

Parameters: item – an instance of Shortcut.
Returns: A tuple with the first value being an instance of Shortcut or None if there are no further children, and as second value an integer parameter ‘cookie’.

Note

This method returns None if there are no further children.

GetId() [source]

Returns this Shortcut ID.

GetImageIndex() [source]

Returns an integer index to be used in the ListShortcut own wx.ImageList.

GetLabel() [source]

Returns the string label associated with this shortcut.

GetNextChild(item, cookie) [source]

Returns this Shortcut‘s next child.

Parameters:
  • item – an instance of Shortcut;
  • cookie (integer) – a parameter which is opaque for the application but is necessary for the library to make this function reentrant (i.e. allow more than one enumeration on one and the same object simultaneously).
Returns:

A tuple with the first value being an instance of Shortcut or None if there are no further children, and as second value an integer parameter ‘cookie’.

Note

This method returns None if there are no further children.

HasChanged() [source]

Returns True if the current accelerator associated with this Shortcut is different from the original one, False otherwise.

IsTop() [source]

Returns True if this Shortcut is associated with a top-level wx.Menu, (i.e., in the top wx.MenuBar level), False otherwise.

Match(filter=u'', item=None) [source]

Matches this Shortcut label string against the filter input variable.

Parameters:
  • filter (string) – a string to match;
  • item – an instance of Shortcut: its label string is compared with the filter string to look for a match.
Returns:

An instance of Shortcut if the filter string is contained in the item lable, None otherwise.

Note

The string-matching is case-insensitive.

ResetVisibility(item=None) [source]

Set the status of this Shortcut and its parent as hidden in the ListShortcut tree hierarchy.

Parameters: item – an instance of Shortcut, used only to make this function reentrant (i.e. allow more than one enumeration on one and the same object simultaneously).

RestoreDefaults(item=None) [source]

Restore the original shortcut string for this Shortcut.

Parameters: item – an instance of Shortcut, used only to make this function reentrant (i.e. allow more than one enumeration on one and the same object simultaneously).

SetAccelerator(accelerator) [source]

Sets the string accelerator associated with this shortcut.

Parameters: accelerator (string) – a string representing the shortcut string (accelerator).

SetBitmap(bitmap) [source]

Sets the bitmap associated with this Shortcut.

Parameters: bitmap – an instance of wx.Bitmap (can be invalid, i.e., wx.NullBitmap).

ShowHierarchy(item) [source]

Set the status of this Shortcut ans its parent as shown in the ListShortcut tree hierarchy.

Parameters: item – an instance of Shortcut.

ToAcceleratorItem(table) [source]

Dumps this Shortcut into a tuple of 3 elements:

  • flags: a bitmask of wx.ACCEL_ALT, wx.ACCEL_SHIFT, wx.ACCEL_CTRL, wx.ACCEL_CMD or wx.ACCEL_NORMAL used to specify which modifier keys are held down;
  • keyCode: the keycode to be detected (i.e., ord(‘b’), wx.WXK_F10, etc...);
  • cmdID: the menu or control command ID to use for the accelerator event.
Parameters: table – a list of tuples, with the above specifications.

ToMenuItem(menuBar) [source]

Dumps this Shortcut into a wx.Menu or wx.MenuItem.

The attributes needed to properly dump a Shortcut into a wx.Menu or wx.MenuBar are the label and the accelerator string.

Parameters: menuBar – an instance of wx.MenuBar.

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • infobar
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • shortcuteditor »
  • Shortcut


ShortcutEditor

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • shortcuteditor »
  • ShortcutEditor

ShortcutEditor

ShortcutEditor is a widget that allows the user to customize and change keyboard shortcuts via a dialog. It can be used to edit wx.MenuItem shortcuts or accelerators defined in a wx.AcceleratorTable.

The interface itself is very much inpired by the GIMP shortcut editor:

http://graphicssoft.about.com/od/gimptutorials/tp/keyboard-shortcut-editor.htm

There are very few minor UI differences between ShortcutEditor and the GIMP one, although the behaviour should be pretty much equivalent.

hierarchy Inheritance Diagram

Inheritance diagram for: ShortcutEditor

Inheritance diagram of ShortcutEditor

appearance Control Appearance

ShortcutEditor

Methods Summary

__init__ | Default class constructor.
BindEvents | Binds a few events we will need to process:
CreateWidgets | Creates all the widgets needed to populate the interface, such as buttons,
DoLayout | Lays out the widgets using sizers in a platform-independent way.
FromAcceleratorTable | Builds the entire shortcut hierarchy starting from a modified version of a wx.AcceleratorTable.
FromMenuBar | Builds the entire shortcut hierarchy starting from a wx.MenuBar.
GetShortcutManager | Returns the root Shortcut containing the whole shortcut hierarchy.
Init | Common initialization procedures.
OnClearFilter | Handles the wx.EVT_BUTTON event for ShortcutEditor when the user clears the
OnHTMLHelp | Handles the wx.EVT_BUTTON event for ShortcutEditor when the user presses the Help
OnRestoreDefaults | Handles the wx.EVT_BUTTON event for ShortcutEditor when the user restores the
OnSetFilter | Handles the wx.EVT_TEXT event for ShortcutEditor.
PreShow | Does some more common initialization before showing ShortcutEditor.
SetColumnWidths | Sets the ListShortcut columns widths to acceptable and eye-pleasing
SetHTMLHelpFile | Sets a new HTML help file (a valid html file) to be loaded when the user seeks
Show | Hides or shows the ShortcutEditor dialog.
ShowModal | Shows the ShortcutEditor dialog in an application-modal way.
ToAcceleratorTable | Dumps the entire shortcut hierarchy (for shortcuts associated with a wx.AcceleratorTable), into
ToMenuBar | Dumps the entire shortcut hierarchy (for shortcuts associated with a wx.MenuItem), into

API Class API

class ShortcutEditor(wx.Dialog) [source]

ShortcutEditor is a widget that allows the user to customize and change keyboard shortcuts via a dialog. It can be used to edit wx.MenuItem shortcuts or accelerators defined in a wx.AcceleratorTable.

The interface itself is very much inpired by the GIMP shortcut editor:

http://graphicssoft.about.com/od/gimptutorials/tp/keyboard-shortcut-editor.htm

There are very few minor UI differences between ShortcutEditor and the GIMP one, although the behaviour should be pretty much equivalent.

__init__(parent) [source]

Default class constructor.

Parameters: parent – an instance of wx.Window, it can also be None.

BindEvents() [source]

Binds a few events we will need to process:

  • wx.EVT_TEXT for the label filtering;
  • wx.EVT_BUTTON for clearing the filtering, for the HTML help window and to reset all the shortcuts to their defaults.

CreateWidgets() [source]

Creates all the widgets needed to populate the interface, such as buttons, texts and, most importantly, ListShortcut.

DoLayout() [source]

Lays out the widgets using sizers in a platform-independent way.

FromAcceleratorTable(accelTable) [source]

Builds the entire shortcut hierarchy starting from a modified version of a wx.AcceleratorTable.

Parameters: accelTable – a modified version of wx.AcceleratorTable, is a list of tuples (4 elements per tuple), populated like this:

accelTable = []

# Every tuple is defined in this way:

for label, flags, keyCode, cmdID in my_accelerators:
    # label:   the string used to show the accelerator into the ShortcutEditor dialog
    # flags:   a bitmask of wx.ACCEL_ALT, wx.ACCEL_SHIFT, wx.ACCEL_CTRL, wx.ACCEL_CMD,
    #          or wx.ACCEL_NORMAL used to specify which modifier keys are held down
    # keyCode: the keycode to be detected (i.e., ord('b'), wx.WXK_F10, etc...)
    # cmdID:   the menu or control command ID to use for the accelerator event.

    accel_tuple = (label, flags, keyCode, cmdID)
    accelTable.append(accel_tuple)

FromMenuBar(topWindow) [source]

Builds the entire shortcut hierarchy starting from a wx.MenuBar.

Parameters: topWindow – an instance of wx.TopLevelWindow, containing the wx.MenuBar we wish to scan.

GetShortcutManager() [source]

Returns the root Shortcut containing the whole shortcut hierarchy.

Init() [source]

Common initialization procedures.

OnClearFilter(event) [source]

Handles the wx.EVT_BUTTON event for ShortcutEditor when the user clears the label filter at the top of the user interface.

Parameters: event – an instance of wx.CommandEvent.

OnHTMLHelp(event) [source]

Handles the wx.EVT_BUTTON event for ShortcutEditor when the user presses the Help button.

Parameters: event – an instance of wx.CommandEvent.

Note

By default, this method launches a wx.html.HtmlWindow containing the default HTML help file. If you wish to load another help file, you should call SetHTMLHelpFile with another input HTML file.

OnRestoreDefaults(event) [source]

Handles the wx.EVT_BUTTON event for ShortcutEditor when the user restores the original shortcuts.

Parameters: event – an instance of wx.CommandEvent.

OnSetFilter(event=None) [source]

Handles the wx.EVT_TEXT event for ShortcutEditor.

Parameters: event – if not None, an instance of wx.KeyEvent.

PreShow() [source]

Does some more common initialization before showing ShortcutEditor.

SetColumnWidths() [source]

Sets the ListShortcut columns widths to acceptable and eye-pleasing numbers (in pixels).

SetHTMLHelpFile(htmlFile) [source]

Sets a new HTML help file (a valid html file) to be loaded when the user seeks for an explanation on how the UI works.

Parameters: htmlFile (string) – a valid HTML file.

Show(show=True) [source]

Hides or shows the ShortcutEditor dialog.

The preferred way of dismissing a modal dialog is to use EndModal.

Parameters: show (bool) – if True, the dialog box is shown and brought to the front, otherwise the box is hidden. If False and the dialog is modal, control is returned to the calling program.

Note

Reimplemented from wx.Window.

ShowModal() [source]

Shows the ShortcutEditor dialog in an application-modal way.

Program flow does not return until the dialog has been dismissed with EndModal.

Returns: The value set with SetReturnCode.

Note

Notice that it is possible to call ShowModal for a dialog which had been previously shown with Show, this allows to make an existing modeless dialog modal. However ShowModal can’t be called twice without intervening EndModal calls.

Note

Note that this function creates a temporary event loop which takes precedence over the application’s main event loop (see wx.EventLoopBase) and which is destroyed when the dialog is dismissed. This also results in a call to wx.App.ProcessPendingEvents().

ToAcceleratorTable(window) [source]

Dumps the entire shortcut hierarchy (for shortcuts associated with a wx.AcceleratorTable), into a wx.AcceleratorTable. This method does rebuild the wx.AcceleratorTable and sets it back to the input window.

Parameters: window – an instance of wx.Window, to which the new wx.AcceleratorTable should be set.

ToMenuBar(topWindow) [source]

Dumps the entire shortcut hierarchy (for shortcuts associated with a wx.MenuItem), into a wx.MenuBar, changing only the wx.Menu / wx.MenuItem labels (it does not rebuild the wx.MenuBar).

Parameters: topWindow – an instance of wx.TopLevelWindow, containing the wx.MenuBar we wish to repopulate.

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • infobar
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • shortcuteditor »
  • ShortcutEditor


ShortcutEvent

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • shortcuteditor »
  • ShortcutEvent

ShortcutEvent

ShortcutEvent is a special subclassing of wx.PyCommandEvent.

This event gets emitted when the user is about to change a shortcut (via EVT_SHORTCUT_CHANGING) and when the user has changed a shortcut (via EVT_SHORTCUT_CHANGED).

hierarchy Inheritance Diagram

Inheritance diagram for: ShortcutEvent

Inheritance diagram of ShortcutEvent

Methods Summary

__init__ | Default class constructor.
GetAccelerator | Gets the shortcut string for which the operation was performed for EVT_SHORTCUT_CHANGED
GetOldAccelerator | Returns the previous shortcut string for EVT_SHORTCUT_CHANGED and
GetShortcut | Returns the shortcut class used for EVT_SHORTCUT_CHANGED and
SetAccelerator | Sets the shortcut string for which the operation was performed for EVT_SHORTCUT_CHANGED
SetOldAccelerator | Sets the previous shortcut string for EVT_SHORTCUT_CHANGED and
SetShortcut | Sets the shortcut class used for EVT_SHORTCUT_CHANGED and

API Class API

class ShortcutEvent(wx.PyCommandEvent) [source]

ShortcutEvent is a special subclassing of wx.PyCommandEvent.

This event gets emitted when the user is about to change a shortcut (via EVT_SHORTCUT_CHANGING) and when the user has changed a shortcut (via EVT_SHORTCUT_CHANGED).

__init__(evtType, evtId) [source]

Default class constructor. For internal use: do not call it in your code!

Parameters:
  • evtType (integer) – the event type;
  • evtId (integer) – the event identifier.

GetAccelerator() [source]

Gets the shortcut string for which the operation was performed for EVT_SHORTCUT_CHANGED and EVT_SHORTCUT_CHANGING events.

Returns: A string representing the new shortcut string (accelerator).

GetOldAccelerator() [source]

Returns the previous shortcut string for EVT_SHORTCUT_CHANGED and EVT_SHORTCUT_CHANGING events.

Returns: A string representing the old shortcut string (accelerator).

GetShortcut() [source]

Returns the shortcut class used for EVT_SHORTCUT_CHANGED and EVT_SHORTCUT_CHANGING events.

Returns: An instance of Shortcut.

SetAccelerator(accelerator) [source]

Sets the shortcut string for which the operation was performed for EVT_SHORTCUT_CHANGED and EVT_SHORTCUT_CHANGING events.

Parameters: accelerator (string) – a string representing the new shortcut string (accelerator).

SetOldAccelerator(accelerator) [source]

Sets the previous shortcut string for EVT_SHORTCUT_CHANGED and EVT_SHORTCUT_CHANGING events.

Parameters: accelerator (string) – a string representing the old shortcut string (accelerator).

SetShortcut(shortcut) [source]

Sets the shortcut class used for EVT_SHORTCUT_CHANGED and EVT_SHORTCUT_CHANGING events.

Parameters: shortcut – an instance of Shortcut.

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • infobar
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • shortcuteditor »
  • ShortcutEvent


SVN Revision 70819 For shortcuteditor

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • shortcuteditor »
  • SVN Revision 70819 For shortcuteditor

svn SVN Revision 70819 For shortcuteditor

This file contains the SVN revision history for shortcuteditor, at revision 70819.

Available information include commit date, the name of the committer, the file size, the SVN log messages and a diff from the previous version (if available).

File Information

  • Commit Date: 06-Mar-2012 21:10:55 UTC
  • Committer: AG
  • File Size: 105660 byte(s)

Log Messages

The following log message was entered by the committer:

  • Added the new widget ShortcutEditor.
  • GenericMessageDialog:
    • Added the possibility to have custom labels for the buttons;
    • Added the possibility to have custom icons for the buttons.
  • CustomTreeCtrl:
    • Added the style TR_ELLIPSIZE_LONG_ITEMS, which ellipsizes long items when the horizontal space for CustomTreeCtrl is low;
    • Added the style TR_TOOLTIP_ON_LONG_ITEMS which shows tooltips on long items when the horizontal space for CustomTreeCtrl is low.
  • HyperTreeList:
    • Added the style TR_ELLIPSIZE_LONG_ITEMS, which ellipsizes long items when the horizontal space for HyperTreeList is low.

Diff To Previous Version (Unavailable)

Version SVN diff:

No diff available.

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • shortcuteditor »
  • SVN Revision 70819 For shortcuteditor


BufferedWindow

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • speedmeter »
  • BufferedWindow

BufferedWindow

A buffered window class.

To use it, subclass it and define a Draw(dc) method that takes a dc to draw to. In that method, put the code needed to draw the picture you want. The window will automatically be double buffered, and the screen will be automatically updated when a Paint event is received.

When the drawing needs to change, you app needs to call the UpdateDrawing method. Since the drawing is stored in a bitmap, you can also save the drawing to file by calling the SaveToFile(self, file_name, file_type) method.

hierarchy Inheritance Diagram

Inheritance diagram for: BufferedWindow

Inheritance diagram of BufferedWindow

subclasses Known Subclasses

  • speedmeter.SpeedMeter

Methods Summary

__init__ | Default class constructor.
Draw | This method should be overridden when sub-classed.
OnPaint | Handles the wx.EVT_PAINT event for BufferedWindow.
OnSize | Handles the wx.EVT_SIZE event for BufferedWindow.
UpdateDrawing | This would get called if the drawing needed to change, for whatever reason.

API Class API

class BufferedWindow(wx.Window) [source]

A buffered window class.

To use it, subclass it and define a Draw(dc) method that takes a dc to draw to. In that method, put the code needed to draw the picture you want. The window will automatically be double buffered, and the screen will be automatically updated when a Paint event is received.

When the drawing needs to change, you app needs to call the BufferedWindow.UpdateDrawing() method. Since the drawing is stored in a bitmap, you can also save the drawing to file by calling the SaveToFile(self, file_name, file_type) method.

__init__(parent, id=wx.ID_ANY, pos=wx.DefaultPosition, size=wx.DefaultSize, style=wx.NO_FULL_REPAINT_ON_RESIZE, bufferedstyle=SM_BUFFERED_DC) [source]

Default class constructor.

Parameters:
  • parent – parent window. Must not be None;
  • id – window identifier. A value of -1 indicates a default value;
  • pos – the control position. A value of (-1, -1) indicates a default position, chosen by either the windowing system or wxPython, depending on platform;
  • size – the control size. A value of (-1, -1) indicates a default size, chosen by either the windowing system or wxPython, depending on platform;
  • style – the window style;
  • bufferedstyle – if set to SM_BUFFERED_DC, double-buffering will be used.

Draw(dc) [source]

This method should be overridden when sub-classed.

Parameters: dc – an instance of wx.DC.

OnPaint(event) [source]

Handles the wx.EVT_PAINT event for BufferedWindow.

Parameters: event – a wx.PaintEvent event to be processed.

OnSize(event) [source]

Handles the wx.EVT_SIZE event for BufferedWindow.

Parameters: event – a wx.SizeEvent event to be processed.

UpdateDrawing() [source]

This would get called if the drawing needed to change, for whatever reason.

The idea here is that the drawing is based on some data generated elsewhere in the system. if that data changes, the drawing needs to be updated.

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • infobar
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • speedmeter »
  • BufferedWindow


SpeedMeter

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • speedmeter »
  • SpeedMeter

SpeedMeter

SpeedMeter tries to reproduce the behavior of some car controls (but not only), by creating an “angular” control (actually, circular).

This is the main class implementation.

hierarchy Inheritance Diagram

Inheritance diagram for: SpeedMeter

Inheritance diagram of SpeedMeter

supclasses Known Superclasses

  • speedmeter.BufferedWindow

appearance Control Appearance

SpeedMeter

Methods Summary

__init__ | Default class constructor.
CircleCoords | Converts the input values into logical x, y coordinates.
Draw | Draws everything on the empty bitmap.
DrawExternalArc | Specify wheter or not you wish to draw the external (thicker) arc.
GetAngleRange | Returns the range of existence for SpeedMeter.
GetArcColour | Returns the external arc colour.
GetDirection | Returns the direction of advancing SpeedMeter value.
GetFillerColour | Returns the partial filler colour.
GetFirstGradientColour | Returns the first gradient colour (near the ticks).
GetHandColour | Returns the hand (arrow indicator) colour.
GetHandStyle | Returns the style for the hand (arrow indicator).
GetIntersection | Used internally.
GetIntervalColours | Returns the colours for the intervals.
GetIntervals | Returns the intervals for SpeedMeter, a Python list of main ticks displayed.
GetMiddleIcon | Returns the icon to be drawn near the center of SpeedMeter.
GetMiddleIconDimens | Used internally.
GetMiddleText | Returns the text to be drawn near the center of SpeedMeter.
GetMiddleTextColour | Returns the colour for the text in the middle.
GetMiddleTextFont | Returns the font for the text in the middle.
GetNumberOfSecondaryTicks | Returns the number of secondary (intermediate) ticks.
GetSecondGradientColour | Returns the first gradient colour (near the center).
GetShadowColour | Returns the hand’s shadow colour.
GetSpeedBackground | Returns the background colour outside the SpeedMeter control.
GetSpeedStyle | Returns a list of strings and a list of integers containing the styles.
GetSpeedValue | Returns the current value for SpeedMeter.
GetTicks | Returns the ticks for SpeedMeter intervals (main ticks string values).
GetTicksColour | Returns the ticks colour.
GetTicksFont | Returns the ticks font.
OnMouseMotion | Handles the wx.EVT_MOUSE_EVENTS event for SpeedMeter.
SetAngleRange | Sets the range of existence for SpeedMeter.
SetArcColour | Sets the external arc colour (thicker line).
SetDirection | Sets the direction of advancing SpeedMeter value.
SetFillerColour | Sets the partial filler colour.
SetFirstGradientColour | Sets the first gradient colour (near the ticks).
SetHandColour | Sets the hand (arrow indicator) colour.
SetHandStyle | Sets the style for the hand (arrow indicator).
SetIntervalColours | Sets the colours for the intervals.
SetIntervals | Sets the intervals for SpeedMeter (main ticks numeric values).
SetMiddleIcon | Sets the icon to be drawn near the center of SpeedMeter.
SetMiddleText | Sets the text to be drawn near the center of SpeedMeter.
SetMiddleTextColour | Sets the colour for the text in the middle.
SetMiddleTextFont | Sets the font for the text in the middle.
SetNumberOfSecondaryTicks | Sets the number of secondary (intermediate) ticks.
SetSecondGradientColour | Sets the second gradient colour (near the center).
SetShadowColour | Sets the hand’s shadow colour.
SetSpeedBackground | Sets the background colour outside the SpeedMeter control.
SetSpeedValue | Sets the current value for SpeedMeter.
SetTicks | Sets the ticks for SpeedMeter intervals (main ticks string values).
SetTicksColour | Sets the ticks colour.
SetTicksFont | Sets the ticks font.

API Class API

class SpeedMeter(BufferedWindow) [source]

SpeedMeter tries to reproduce the behavior of some car controls (but not only), by creating an “angular” control (actually, circular).

This is the main class implementation.

__init__(parent, id=wx.ID_ANY, pos=wx.DefaultPosition, size=wx.DefaultSize, agwStyle=SM_DRAW_HAND, bufferedstyle=SM_BUFFERED_DC, mousestyle=0) [source]

Default class constructor.

Parameters:
  • parent – parent window. Must not be None;
  • id – window identifier. A value of -1 indicates a default value;
  • pos – the control position. A value of (-1, -1) indicates a default position, chosen by either the windowing system or wxPython, depending on platform;
  • size – the control size. A value of (-1, -1) indicates a default size, chosen by either the windowing system or wxPython, depending on platform;
  • agwStyle – this value specifies the SpeedMeter styles, and can be a combination of the following bits:

    Window Styles | Hex Value | Description
    SM_ROTATE_TEXT | 0x1 | Draws the ticks rotated: the ticks are rotated accordingly to the tick marks positions.
    SM_DRAW_SECTORS | 0x2 | Different intervals are painted in differend colours (every sector of the circle has its own colour).
    SM_DRAW_PARTIAL_SECTORS | 0x4 | Every interval has its own colour, but only a circle corona is painted near the ticks.
    SM_DRAW_HAND | 0x8 | The hand (arrow indicator) is drawn.
    SM_DRAW_SHADOW | 0x10 | A shadow for the hand is drawn.
    SM_DRAW_PARTIAL_FILLER | 0x20 | A circle corona that follows the hand position is drawn near the ticks.
    SM_DRAW_SECONDARY_TICKS | 0x40 | Intermediate (smaller) ticks are drawn between principal ticks.
    SM_DRAW_MIDDLE_TEXT | 0x80 | Some text is printed in the middle of the control near the center.
    SM_DRAW_MIDDLE_ICON | 0x100 | An icon is drawn in the middle of the control near the center.
    SM_DRAW_GRADIENT | 0x200 | A gradient of colours will fill the control.
    SM_DRAW_FANCY_TICKS | 0x400 | With this style you can use xml tags to create some custom text and draw it at the ticks position. See wx.lib.fancytext for the tags.
  • bufferedstyle – this value allows you to use the normal wx.PaintDC or the double buffered drawing options:

    Buffered Styles | Hex Value | Description
    SM_NORMAL_DC | 0x0 | Uses the normal wx.PaintDC
    SM_BUFFERED_DC | 0x1 | Uses the double buffered drawing style
  • mousestyle – this value allows you to use the mouse to change the SpeedMeter value interactively with left click/drag events. If set to SM_MOUSE_TRACK, the mouse left click/drag allow you to change the SpeedMeter value interactively.

CircleCoords(radius, angle, centerX, centerY) [source]

Converts the input values into logical x, y coordinates.

Parameters:
  • radius – the SpeedMeter radius;
  • angle – the angular position of the mouse;
  • centerX – the x position of the SpeedMeter center;
  • centerX – the y position of the SpeedMeter center.

Draw(dc) [source]

Draws everything on the empty bitmap. Here all the chosen styles are applied.

Parameters: dc – an instance of wx.DC.

DrawExternalArc(draw=True) [source]

Specify wheter or not you wish to draw the external (thicker) arc.

Parameters: draw – True to draw the external arc, False otherwise.

GetAngleRange() [source]

Returns the range of existence for SpeedMeter. The returned values are in radians.

GetArcColour() [source]

Returns the external arc colour.

GetDirection() [source]

Returns the direction of advancing SpeedMeter value.

GetFillerColour() [source]

Returns the partial filler colour.

GetFirstGradientColour() [source]

Returns the first gradient colour (near the ticks).

GetHandColour() [source]

Returns the hand (arrow indicator) colour.

GetHandStyle() [source]

Returns the style for the hand (arrow indicator).

GetIntersection(current, intervals) [source]

Used internally.

GetIntervalColours() [source]

Returns the colours for the intervals.

GetIntervals() [source]

Returns the intervals for SpeedMeter, a Python list of main ticks displayed.

GetMiddleIcon() [source]

Returns the icon to be drawn near the center of SpeedMeter.

GetMiddleIconDimens() [source]

Used internally.

GetMiddleText() [source]

Returns the text to be drawn near the center of SpeedMeter.

GetMiddleTextColour() [source]

Returns the colour for the text in the middle.

GetMiddleTextFont() [source]

Returns the font for the text in the middle.

GetNumberOfSecondaryTicks() [source]

Returns the number of secondary (intermediate) ticks.

GetSecondGradientColour() [source]

Returns the first gradient colour (near the center).

GetShadowColour() [source]

Returns the hand’s shadow colour.

GetSpeedBackground() [source]

Returns the background colour outside the SpeedMeter control.

GetSpeedStyle() [source]

Returns a list of strings and a list of integers containing the styles.

GetSpeedValue() [source]

Returns the current value for SpeedMeter.

GetTicks() [source]

Returns the ticks for SpeedMeter intervals (main ticks string values).

GetTicksColour() [source]

Returns the ticks colour.

GetTicksFont() [source]

Returns the ticks font.

OnMouseMotion(event) [source]

Handles the wx.EVT_MOUSE_EVENTS event for SpeedMeter.

Parameters: event – a wx.MouseEvent event to be processed.

Note

Here only left clicks/drags are involved. Should SpeedMeter have something more?

SetAngleRange(start=0, end=3.141592653589793) [source]

Sets the range of existence for SpeedMeter.

Parameters:
  • start – the starting angle, in radians;
  • end – the ending angle, in radians.

SetArcColour(colour=None) [source]

Sets the external arc colour (thicker line).

Parameters: colour – a valid wx.Colour object. If defaulted to None, the arc colour will be black.

SetDirection(direction=None) [source]

Sets the direction of advancing SpeedMeter value.

Parameters: direction – specifying “advance” will move the hand in clock-wise direction (like normal car speed control), while using “reverse” will move it counterclock-wise direction. If defaulted to None, then “advance” will be used.

SetFillerColour(colour=None) [source]

Sets the partial filler colour.

A circle corona near the ticks will be filled with this colour, from the starting value to the current value of SpeedMeter.

Parameters: colour – a valid wx.Colour object.

SetFirstGradientColour(colour=None) [source]

Sets the first gradient colour (near the ticks).

Parameters: colour – a valid wx.Colour object.

SetHandColour(colour=None) [source]

Sets the hand (arrow indicator) colour.

Parameters: colour – a valid wx.Colour object. If defaulted to None, the arrow indicator will be red.

SetHandStyle(style=None) [source]

Sets the style for the hand (arrow indicator).

Parameters: style – by specifying “Hand”, SpeedMeter will draw a polygon that simulates the car speed control indicator. Using “Arrow” will force SpeedMeter to draw a simple arrow. If defaulted to None, “Hand” will be used.

SetIntervalColours(colours=None) [source]

Sets the colours for the intervals.

Parameters: colours – a Python list of colours. The length of this list should be the same as the number of circle sectors in SpeedMeter. If defaulted to None, all the intervals will have a white colour.

Note

Every interval (circle sector) should have a colour.

SetIntervals(intervals=None) [source]

Sets the intervals for SpeedMeter (main ticks numeric values).

Parameters: intervals – a Python list of main ticks to be displayed. If defaulted to None, the list [0, 50, 100] is used.

SetMiddleIcon(icon) [source]

Sets the icon to be drawn near the center of SpeedMeter.

Parameters: icon – a valid wx.Bitmap object.

SetMiddleText(text=None) [source]

Sets the text to be drawn near the center of SpeedMeter.

Parameters: text – the text to be drawn near the center of SpeedMeter. If defaulted to None, an empty string will be used.

SetMiddleTextColour(colour=None) [source]

Sets the colour for the text in the middle.

Parameters: colour – a valid wx.Colour object. If defaulted to None, the text in the middle will be painted in blue.

SetMiddleTextFont(font=None) [source]

Sets the font for the text in the middle.

Parameters: font – a valid wx.Font object. If defaulted to None, some standard font will be generated.

SetNumberOfSecondaryTicks(ticknum=None) [source]

Sets the number of secondary (intermediate) ticks.

Parameters: ticknum – the number of intermediate ticks. If defaulted to None, 3 ticks are used.

SetSecondGradientColour(colour=None) [source]

Sets the second gradient colour (near the center).

Parameters: colour – a valid wx.Colour object.

SetShadowColour(colour=None) [source]

Sets the hand’s shadow colour.

Parameters: colour – a valid wx.Colour object. If defaulted to None, the shadow colour will be light grey.

SetSpeedBackground(colour=None) [source]

Sets the background colour outside the SpeedMeter control.

Parameters: colour – a valid wx.Colour object. If defaulted to None, the SpeedMeter background will be taken from the system default.

SetSpeedValue(value=None) [source]

Sets the current value for SpeedMeter.

Parameters: value – a floating point number representing the current value. If defaulted to None, the SpeedMeter value will be the middle point of the control range.

SetTicks(ticks=None) [source]

Sets the ticks for SpeedMeter intervals (main ticks string values).

Parameters: ticks – a Python list of strings, representing the ticks values. If defaulted to None, the ticks will be taken from the interval values.

SetTicksColour(colour=None) [source]

Sets the ticks colour.

Parameters: colour – a valid wx.Colour object. If defaulted to None, the ticks colour will be set as blue.

SetTicksFont(font=None) [source]

Sets the ticks font.

Parameters: font – a valid wx.Font object. If defaulted to None, some standard font will be chosen automatically.

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • infobar
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • speedmeter »
  • SpeedMeter


SVN Revision 68362 For speedmeter

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • speedmeter »
  • SVN Revision 68362 For speedmeter

svn SVN Revision 68362 For speedmeter

This file contains the SVN revision history for speedmeter, at revision 68362.

Available information include commit date, the name of the committer, the file size, the SVN log messages and a diff from the previous version (if available).

File Information

  • Commit Date: 17-Oct-2008 20:51:43 UTC
  • Committer: AG
  • File Size: 62119 byte(s)

Log Messages

The following log message was entered by the committer:

  • All of AGW: change my work e-mail from KPO to Maersk Oil (silly commit)

Diff To Previous Version (65377)

Version SVN diff:

--- wxPython/3rdParty/AGW/agw/speedmeter.py 2010/08/21 20:27:02     65377
+++ wxPython/3rdParty/AGW/agw/speedmeter.py 2011/07/24 21:36:47     68362
@@ -25,7 +25,7 @@
# Write To Me At:
#
# andrea.gavana@gmail.com
-# gavana@kpo.kz
+# andrea.gavana@maerskoil.com
#
# Or, Obviously, To The wxPython Mailing List!!!
#

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • speedmeter »
  • SVN Revision 68362 For speedmeter


SVN Revision 68881 For speedmeter

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • speedmeter »
  • SVN Revision 68881 For speedmeter

svn SVN Revision 68881 For speedmeter

This file contains the SVN revision history for speedmeter, at revision 68881.

Available information include commit date, the name of the committer, the file size, the SVN log messages and a diff from the previous version (if available).

File Information

  • Commit Date: 17-Oct-2008 19:15:31 UTC
  • Committer: AG
  • File Size: 64278 byte(s)

Log Messages

The following log message was entered by the committer:

  • AGW: General overhaul of the documentation, much improved. All the widgets have their own sample usage in the docs as well;

  • FlatNotebook: Added the FNB_NAV_BUTTONS_WHEN_NEEDED style, which hides the navigation left/right arrows if all tabs fit;

  • RibbonBar: - Added the EVT_RIBBONBAR_TAB_LEFT_DCLICK event, which generates a special event

    when a ribbon bar tab is double-clicked;

    • Added support for toggle buttons;
    • Improved support for ribbon panel sizers: panels with sizers should now automatically minimise at small sizes, and behave properly when popping up from a minimised state;
    • Added tooltips via SetToolTip for those buttons which have the help_string attribute set.

  • XLSGrid: a new widget was added to AGW, termed XLSGrid. It’s based on wx.grid.Grid and can be used to faithfully reproduce the appearance of a Microsoft Excel spreadsheets.

Diff To Previous Version (68362)

Version SVN diff:

--- wxPython/3rdParty/AGW/agw/speedmeter.py 2011/07/24 21:36:47     68362
+++ wxPython/3rdParty/AGW/agw/speedmeter.py 2011/08/25 16:40:17     68881
@@ -3,7 +3,7 @@
# Python Code By:
#
# Andrea Gavana, @ 25 Sep 2005
-# Latest Revision: 14 Apr 2010, 12.00 GMT
+# Latest Revision: 17 Aug 2011, 15.00 GMT
#
#
# TODO List/Caveats
@@ -35,20 +35,20 @@

"""
-SpeedMeter tries to reproduce the behavior of some car controls (but not only),
+L{SpeedMeter} tries to reproduce the behavior of some car controls (but not only),
by creating an "angular" control (actually, circular).

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

-SpeedMeter tries to reproduce the behavior of some car controls (but not only),
+L{SpeedMeter} tries to reproduce the behavior of some car controls (but not only),
by creating an "angular" control (actually, circular). I remember to have seen
it somewhere, and i decided to implement it in wxPython.

-SpeedMeter starts its construction from an empty bitmap, and it uses some
+L{SpeedMeter} starts its construction from an empty bitmap, and it uses some
functions of the `wx.DC` class to create the rounded effects. everything is
-processed in the `Draw()` method of SpeedMeter class.
+processed in the `Draw()` method of L{SpeedMeter} class.

This implementation allows you to use either directly the `wx.PaintDC`, or the
better (for me) double buffered style with `wx.BufferedPaintDC`. the double
@@ -60,27 +60,84 @@
Usage
=====

-Sample usage::
+Usage example::

-    speedwindow1 = SM.SpeedMeter(parent, bufferedstyle,
-                                 agwStyle, mousestyle)
+    import wx
+    import wx.lib.agw.speedmeter as SM

+    class MyFrame(wx.Frame):
+
+        def __init__(self, parent):
+
+            wx.Frame.__init__(self, parent, -1, "SpeedMeter Demo")
+
+            speed = SM.SpeedMeter(self, agwStyle=SM.SM_DRAW_HAND|SM.SM_DRAW_SECTORS|SM.SM_DRAW_MIDDLE_TEXT|SM.SM_DRAW_SECONDARY_TICKS)
+
+            # Set The Region Of Existence Of SpeedMeter (Always In Radians!!!!)
+            speed.SetAngleRange(-pi/6, 7*pi/6)
+
+            # Create The Intervals That Will Divide Our SpeedMeter In Sectors
+            intervals = range(0, 201, 20)
+            speed.SetIntervals(intervals)
+
+            # Assign The Same Colours To All Sectors (We Simulate A Car Control For Speed)
+            # Usually This Is Black
+            colours = [wx.BLACK]*10
+            speed.SetIntervalColours(colours)
+
+            # Assign The Ticks: Here They Are Simply The String Equivalent Of The Intervals
+            ticks = [str(interval) for interval in intervals]
+            speed.SetTicks(ticks)
+            # Set The Ticks/Tick Markers Colour
+            speed.SetTicksColour(wx.WHITE)
+            # We Want To Draw 5 Secondary Ticks Between The Principal Ticks
+            speed.SetNumberOfSecondaryTicks(5)
+
+            # Set The Font For The Ticks Markers
+            speed.SetTicksFont(wx.Font(7, wx.SWISS, wx.NORMAL, wx.NORMAL))
+
+            # Set The Text In The Center Of SpeedMeter
+            speed.SetMiddleText("Km/h")
+            # Assign The Colour To The Center Text
+            speed.SetMiddleTextColour(wx.WHITE)
+            # Assign A Font To The Center Text
+            speed.SetMiddleTextFont(wx.Font(8, wx.SWISS, wx.NORMAL, wx.BOLD))
+
+            # Set The Colour For The Hand Indicator
+            speed.SetHandColour(wx.Colour(255, 50, 0))
+
+            # Do Not Draw The External (Container) Arc. Drawing The External Arc May
+            # Sometimes Create Uglier Controls. Try To Comment This Line And See It
+            # For Yourself!
+            speed.DrawExternalArc(False)
+
+            # Set The Current Value For The SpeedMeter
+            speed.SetSpeedValue(44)
+
+
+    # our normal wxApp-derived class, as usual
+
+    app = wx.PySimpleApp()
+
+    frame = MyFrame(None)
+    app.SetTopWindow(frame)
+    frame.Show()
+
+    app.MainLoop()

-None of the options (a part of parent class) are strictly required, if you
-use the defaults you get a very simple SpeedMeter.

Methods and Settings
====================

-SpeedMeter is highly customizable, and in particular you can set:
+L{SpeedMeter} is highly customizable, and in particular you can set:

-- The start and end angle of existence for SpeedMeter;
-- The intervals in which you divide the SpeedMeter (numerical values);
+- The start and end angle of existence for L{SpeedMeter};
+- The intervals in which you divide the L{SpeedMeter} (numerical values);
- The corresponding thicks for the intervals;
- The interval colours (different intervals may have different filling colours);
- The ticks font and colour;
-- The background colour (outsize the SpeedMeter region);
+- The background colour (outsize the L{SpeedMeter} region);
- The external arc colour;
- The hand (arrow) colour;
- The hand's shadow colour;
@@ -90,7 +147,7 @@
- The direction of increasing speed ("advance" or "reverse");
- The text to be drawn in the middle and its font;
- The icon to be drawn in the middle;
-- The first and second gradient colours (that fills the SpeedMeter control);
+- The first and second gradient colours (that fills the L{SpeedMeter} control);
- The current value.

@@ -125,9 +182,9 @@
License And Version
===================

-SpeedMeter is distributed under the wxPython license.
+L{SpeedMeter} is distributed under the wxPython license.

-Latest revision: Andrea Gavana @ 14 Apr 2010, 12.00 GMT
+Latest revision: Andrea Gavana @ 17 Aug 2011, 15.00 GMT

Version 0.3

@@ -231,7 +288,7 @@

class BufferedWindow(wx.Window):
"""
-    A Buffered window class.
+    A buffered window class.

To use it, subclass it and define a `Draw(dc)` method that takes a `dc`
to draw to. In that method, put the code needed to draw the picture
@@ -353,7 +410,7 @@

class SpeedMeter(BufferedWindow):
"""
-    SpeedMeter tries to reproduce the behavior of some car controls (but not only),
+    L{SpeedMeter} tries to reproduce the behavior of some car controls (but not only),
by creating an "angular" control (actually, circular).

This is the main class implementation.

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • speedmeter »
  • SVN Revision 68881 For speedmeter


supertooltip functions

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • supertooltip »
  • supertooltip functions

supertooltip functions

This is the description of standalone Python functions in the supertooltip module.

Functions Summary

ExtractLink | Extract the link from an hyperlink line.
GetStyleKeys | Returns the predefined styles keywords.
MakeBold | Makes a font bold.

API Functions API

ExtractLink(line) [source]

Extract the link from an hyperlink line.

Parameters: line – the line of text to be processed.

GetStyleKeys() [source]

Returns the predefined styles keywords.

MakeBold(font) [source]

Makes a font bold. Utility method.

Parameters: font – the font to be made bold.

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • infobar
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • supertooltip »
  • supertooltip functions


SuperToolTip

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • supertooltip »
  • SuperToolTip

SuperToolTip

The main class for SuperToolTip, which holds all the methods and setters/getters available to the user.

hierarchy Inheritance Diagram

Inheritance diagram for: SuperToolTip

Inheritance diagram of SuperToolTip

subclasses Known Subclasses

  • xlsgrid.TransientPopup

appearance Control Appearance

SuperToolTip

Methods Summary

__init__ | Default class constructor.
ApplyStyle | Applies none of the predefined styles.
DoShowNow | Create the SuperToolTip immediately.
EnableTip | Globally (application-wide) enables/disables SuperToolTip.
GetBodyImage | Returns the main body bitmap used in SuperToolTip.
GetBottomGradientColor | Returns the bottom gradient colour.
GetBottomGradientColour | Returns the bottom gradient colour.
GetDrawFooterLine | Returns whether the separator line before the footer is drawn or not.
GetDrawHeaderLine | Returns whether the separator line after the header is drawn or not.
GetDropShadow | Returns whether a shadow below SuperToolTip is drawn or not.
GetEndDelay | Returns the delay time (in seconds) after which the SuperToolTip is destroyed.
GetFooter | Returns the footer text.
GetFooterBitmap | Returns the footer bitmap.
GetFooterFont | Returns the font used for the footer text.
GetHeader | Returns the header text.
GetHeaderBitmap | Returns the header bitmap.
GetHeaderFont | Returns the font used for the header text.
GetHyperlinkFont | Returns the font used for the hyperlink text.
GetMessage | Returns the main body message in SuperToolTip.
GetMessageFont | Returns the font used in the main body message.
GetMiddleGradientColor | Returns the middle gradient colour.
GetMiddleGradientColour | Returns the middle gradient colour.
GetStartDelay | Returns the tim delay (in seconds) after which the SuperToolTip is created.
GetTarget | Returns the target window for SuperToolTip.
GetTextColor | Returns the text colour.
GetTextColour | Returns the text colour.
GetTipWindow | Return the TipWindow, will return None if not yet created
GetTopGradientColor | Returns the top gradient colour.
GetTopGradientColour | Returns the top gradient colour.
GetUseFade | Returns whether a fade in/fade out effect is used or not.
InitFont | Initalizes the fonts for SuperToolTip.
OnDestroy | Handles the SuperToolTip target destruction.
OnEndTimer | The show time for SuperToolTip has expired, destroy the SuperToolTip.
OnStartTimer | The creation time has expired, create the SuperToolTip.
OnWidgetEnter | Starts the SuperToolTip timer for creation, handles the wx.EVT_ENTER_WINDOW event.
OnWidgetLeave | Handles the wx.EVT_LEAVE_WINDOW event for the target widgets.
SetBodyImage | Sets the main body bitmap for SuperToolTip.
SetBottomGradientColor | Sets the bottom gradient colour for SuperToolTip.
SetBottomGradientColour | Sets the bottom gradient colour for SuperToolTip.
SetDrawFooterLine | Sets whether to draw a separator line before the footer or not.
SetDrawHeaderLine | Sets whether to draw a separator line after the header or not.
SetDropShadow | Whether to draw a shadow below SuperToolTip or not.
SetEndDelay | Sets the delay time (in seconds) after which the SuperToolTip is destroyed.
SetFooter | Sets the footer text.
SetFooterBitmap | Sets the footer bitmap for SuperToolTip.
SetFooterFont | Sets the font for the footer text.
SetHeader | Sets the header text.
SetHeaderBitmap | Sets the header bitmap for SuperToolTip.
SetHeaderFont | Sets the font for the header text.
SetHyperlinkFont | Sets the font for the hyperlink text.
SetMessage | Sets the main body message for SuperToolTip.
SetMessageFont | Sets the font for the main body message.
SetMiddleGradientColor | Sets the middle gradient colour for SuperToolTip.
SetMiddleGradientColour | Sets the middle gradient colour for SuperToolTip.
SetStartDelay | Sets the time delay (in seconds) after which the SuperToolTip is created.
SetTarget | Sets the target window for SuperToolTip.
SetTextColor | Sets the text colour for SuperToolTip.
SetTextColour | Sets the text colour for SuperToolTip.
SetTopGradientColor | Sets the top gradient colour for SuperToolTip.
SetTopGradientColour | Sets the top gradient colour for SuperToolTip.
SetUseFade | Whether to use a fade in/fade out effect or not.

API Class API

class SuperToolTip(object) [source]

The main class for SuperToolTip, which holds all the methods and setters/getters available to the user.

__init__(message, bodyImage=wx.NullBitmap, header="", headerBmp=wx.NullBitmap, footer="", footerBmp=wx.NullBitmap) [source]

Default class constructor.

Parameters:
  • message – the main message in SuperToolTip body;
  • bodyImage – the image in the SuperToolTip body;
  • header – the header text;
  • headerBmp – the header bitmap;
  • footer – the footer text;
  • footerBmp – the footer bitmap.

ApplyStyle(style) [source]

Applies none of the predefined styles.

Parameters: style – one of the predefined styles available at the beginning of the module.

DoShowNow() [source]

Create the SuperToolTip immediately.

EnableTip(enable=True) [source]

Globally (application-wide) enables/disables SuperToolTip.

Parameters: enable – True to enable SuperToolTip globally, False otherwise.

GetBodyImage() [source]

Returns the main body bitmap used in SuperToolTip.

GetBottomGradientColor()

Returns the bottom gradient colour.

GetBottomGradientColour() [source]

Returns the bottom gradient colour.

GetDrawFooterLine() [source]

Returns whether the separator line before the footer is drawn or not.

GetDrawHeaderLine() [source]

Returns whether the separator line after the header is drawn or not.

GetDropShadow() [source]

Returns whether a shadow below SuperToolTip is drawn or not.

Note

This method is available only on Windows and requires Mark Hammond’s pywin32 package.

GetEndDelay() [source]

Returns the delay time (in seconds) after which the SuperToolTip is destroyed.

GetFooter() [source]

Returns the footer text.

GetFooterBitmap() [source]

Returns the footer bitmap.

GetFooterFont() [source]

Returns the font used for the footer text.

GetHeader() [source]

Returns the header text.

GetHeaderBitmap() [source]

Returns the header bitmap.

GetHeaderFont() [source]

Returns the font used for the header text.

GetHyperlinkFont() [source]

Returns the font used for the hyperlink text.

GetMessage() [source]

Returns the main body message in SuperToolTip.

GetMessageFont() [source]

Returns the font used in the main body message.

GetMiddleGradientColor()

Returns the middle gradient colour.

GetMiddleGradientColour() [source]

Returns the middle gradient colour.

GetStartDelay() [source]

Returns the tim delay (in seconds) after which the SuperToolTip is created.

GetTarget() [source]

Returns the target window for SuperToolTip.

GetTextColor()

Returns the text colour.

GetTextColour() [source]

Returns the text colour.

GetTipWindow() [source]

Return the TipWindow, will return None if not yet created

GetTopGradientColor()

Returns the top gradient colour.

GetTopGradientColour() [source]

Returns the top gradient colour.

GetUseFade() [source]

Returns whether a fade in/fade out effect is used or not.

Note

This method is available only on Windows and requires Mark Hammond’s pywin32 package.

InitFont() [source]

Initalizes the fonts for SuperToolTip.

OnDestroy(event) [source]

Handles the SuperToolTip target destruction.

OnEndTimer() [source]

The show time for SuperToolTip has expired, destroy the SuperToolTip.

OnStartTimer() [source]

The creation time has expired, create the SuperToolTip.

OnWidgetEnter(event) [source]

Starts the SuperToolTip timer for creation, handles the wx.EVT_ENTER_WINDOW event.

Parameters: event – a wx.MouseEvent event to be processed.

OnWidgetLeave(event) [source]

Handles the wx.EVT_LEAVE_WINDOW event for the target widgets.

Parameters: event – a wx.MouseEvent event to be processed.

SetBodyImage(bmp) [source]

Sets the main body bitmap for SuperToolTip.

Parameters: bmp – the body bitmap, a valid wx.Bitmap object.

SetBottomGradientColor(colour)

Sets the bottom gradient colour for SuperToolTip.

Parameters: colour – the colour to use as bottom colour, a valid wx.Colour object.

SetBottomGradientColour(colour) [source]

Sets the bottom gradient colour for SuperToolTip.

Parameters: colour – the colour to use as bottom colour, a valid wx.Colour object.

SetDrawFooterLine(draw) [source]

Sets whether to draw a separator line before the footer or not.

Parameters: draw – True to draw a separator line before the footer, False otherwise.

SetDrawHeaderLine(draw) [source]

Sets whether to draw a separator line after the header or not.

Parameters: draw – True to draw a separator line after the header, False otherwise.

SetDropShadow(drop) [source]

Whether to draw a shadow below SuperToolTip or not.

Parameters: drop – True to drop a shadow below the control, False otherwise.

Note

This method is available only on Windows and requires Mark Hammond’s pywin32 package.

SetEndDelay(delay=1000000.0) [source]

Sets the delay time (in seconds) after which the SuperToolTip is destroyed.

Parameters: delay – the delay in seconds.

SetFooter(footer) [source]

Sets the footer text.

Parameters: footer – the footer text to display.

SetFooterBitmap(bmp) [source]

Sets the footer bitmap for SuperToolTip.

Parameters: bmp – the footer bitmap, a valid wx.Bitmap object.

SetFooterFont(font) [source]

Sets the font for the footer text.

Parameters: font – the font to use for the footer text, a valid wx.Font object.

SetHeader(header) [source]

Sets the header text.

Parameters: header – the header text to display.

SetHeaderBitmap(bmp) [source]

Sets the header bitmap for SuperToolTip.

Parameters: bmp – the header bitmap, a valid wx.Bitmap object.

SetHeaderFont(font) [source]

Sets the font for the header text.

Parameters: font – the font to use for the header text, a valid wx.Font object.

SetHyperlinkFont(font) [source]

Sets the font for the hyperlink text.

Parameters: font – the font to use for the hyperlink text, a valid wx.Font object.

SetMessage(message) [source]

Sets the main body message for SuperToolTip.

Parameters: message – the message to display in the body.

SetMessageFont(font) [source]

Sets the font for the main body message.

Parameters: font – the font to use for the main body message, a valid wx.Font object.

SetMiddleGradientColor(colour)

Sets the middle gradient colour for SuperToolTip.

Parameters: colour – the colour to use as middle colour, a valid wx.Colour object.

SetMiddleGradientColour(colour) [source]

Sets the middle gradient colour for SuperToolTip.

Parameters: colour – the colour to use as middle colour, a valid wx.Colour object.

SetStartDelay(delay=1) [source]

Sets the time delay (in seconds) after which the SuperToolTip is created.

Parameters: delay – the delay in seconds.

SetTarget(widget) [source]

Sets the target window for SuperToolTip.

Parameters: widget – the widget to which SuperToolTip is associated.

SetTextColor(colour)

Sets the text colour for SuperToolTip.

Parameters: colour – the colour to use as text colour, a valid wx.Colour object.

SetTextColour(colour) [source]

Sets the text colour for SuperToolTip.

Parameters: colour – the colour to use as text colour, a valid wx.Colour object.

SetTopGradientColor(colour)

Sets the top gradient colour for SuperToolTip.

Parameters: colour – the colour to use as top colour, a valid wx.Colour object.

SetTopGradientColour(colour) [source]

Sets the top gradient colour for SuperToolTip.

Parameters: colour – the colour to use as top colour, a valid wx.Colour object.

SetUseFade(fade) [source]

Whether to use a fade in/fade out effect or not.

Parameters: fade – True to use a fade in/fade out effect, False otherwise.

Note

This method is available only on Windows and requires Mark Hammond’s pywin32 package.

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • infobar
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • supertooltip »
  • SuperToolTip


ToolTipWindow

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • supertooltip »
  • ToolTipWindow

ToolTipWindow

A simple wx.PopupWindow that holds fancy tooltips. Not available on Mac as wx.PopupWindow is not implemented there.

hierarchy Inheritance Diagram

Inheritance diagram for: ToolTipWindow

Inheritance diagram of ToolTipWindow

supclasses Known Superclasses

  • supertooltip.ToolTipWindowBase

Methods Summary

__init__ Default class constructor.

API Class API

class ToolTipWindow(ToolTipWindowBase, wx.PopupWindow) [source]

A simple wx.PopupWindow that holds fancy tooltips. Not available on Mac as wx.PopupWindow is not implemented there.

__init__(parent, classParent) [source]

Default class constructor.

Parameters:
  • parent – the SuperToolTip parent widget;
  • classParent – the SuperToolTip class object.

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • infobar
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • supertooltip »
  • ToolTipWindow


ToolTipWindowBase

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • supertooltip »
  • ToolTipWindowBase

ToolTipWindowBase

Base class for the different Windows and Mac implementation.

hierarchy Inheritance Diagram

Inheritance diagram for: ToolTipWindowBase

Inheritance diagram of ToolTipWindowBase

subclasses Known Subclasses

  • supertooltip.ToolTipWindow

Methods Summary

__init__ | Default class constructor.
AlphaCycle | Handles the wx.EVT_TIMER event for SuperToolTip.
CalculateBestPosition |
CalculateBestSize | Calculates the SuperToolTip window best size.
DropShadow | Adds a shadow under the window.
Invalidate | Invalidate SuperToolTip size and repaint it.
MakeWindowTransparent | Makes the SuperToolTip window transparent.
OnDestroy | Handles the wx.EVT_LEFT_DOWN, wx.EVT_LEFT_DCLICK and wx.EVT_KILL_FOCUS
OnEraseBackground | Handles the wx.EVT_ERASE_BACKGROUND event for SuperToolTip.
OnMouseMotion | Handles the wx.EVT_MOTION event for SuperToolTip.
OnPaint | Handles the wx.EVT_PAINT event for SuperToolTip.
OnSize | Handles the wx.EVT_SIZE event for SuperToolTip.
SetFont | Sets the SuperToolTip font globally.
StartAlpha | Start the timer which set the alpha channel for SuperToolTip.

API Class API

class ToolTipWindowBase(object) [source]

Base class for the different Windows and Mac implementation.

__init__(parent, classParent) [source]

Default class constructor.

Parameters:
  • parent – the SuperToolTip parent widget;
  • classParent – the SuperToolTip class object.

AlphaCycle(event) [source]

Handles the wx.EVT_TIMER event for SuperToolTip.

Parameters: event – a wx.TimerEvent event to be processed.

CalculateBestPosition(widget) [source]

CalculateBestSize() [source]

Calculates the SuperToolTip window best size.

DropShadow(drop=True) [source]

Adds a shadow under the window.

Parameters: drop – whether to drop a shadow or not.

Note

This method is available only on Windows and requires Mark Hammond’s pywin32 package.

Invalidate() [source]

Invalidate SuperToolTip size and repaint it.

MakeWindowTransparent(amount) [source]

Makes the SuperToolTip window transparent.

Parameters: amount – the alpha channel value.

Note

This method is available only on Windows and requires Mark Hammond’s pywin32 package.

OnDestroy(event) [source]

Handles the wx.EVT_LEFT_DOWN, wx.EVT_LEFT_DCLICK and wx.EVT_KILL_FOCUS events for SuperToolTip. All these events destroy the SuperToolTip, unless the user clicked on one hyperlink.

Parameters: event – a wx.MouseEvent or a wx.FocusEvent event to be processed.

OnEraseBackground(event) [source]

Handles the wx.EVT_ERASE_BACKGROUND event for SuperToolTip.

Parameters: event – a wx.EraseEvent event to be processed.

Note

This method is intentionally empty to reduce flicker.

OnMouseMotion(event) [source]

Handles the wx.EVT_MOTION event for SuperToolTip.

Parameters: event – a wx.MouseEvent event to be processed.

OnPaint(event) [source]

Handles the wx.EVT_PAINT event for SuperToolTip.

Parameters: event – a wx.PaintEvent event to be processed.

OnSize(event) [source]

Handles the wx.EVT_SIZE event for SuperToolTip.

Parameters: event – a wx.SizeEvent event to be processed.

SetFont(font) [source]

Sets the SuperToolTip font globally.

Parameters: font – the font to set.

StartAlpha(isShow) [source]

Start the timer which set the alpha channel for SuperToolTip.

Parameters: isShow – whether SuperToolTip is being shown or deleted.

Note

This method is available only on Windows and requires Mark Hammond’s pywin32 package.

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • infobar
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • supertooltip »
  • ToolTipWindowBase


SVN Revision 68343 For supertooltip

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • supertooltip »
  • SVN Revision 68343 For supertooltip

svn SVN Revision 68343 For supertooltip

This file contains the SVN revision history for supertooltip, at revision 68343.

Available information include commit date, the name of the committer, the file size, the SVN log messages and a diff from the previous version (if available).

File Information

  • Commit Date: 29-May-2009 08:06:58 UTC
  • Committer: AG
  • File Size: 44721 byte(s)

Log Messages

The following log message was entered by the committer:

  • AquaButton: added the possibility to use it as a toggle button;
  • SuperToolTip: Simple check to avoid starting many SuperToolTips at once.

Diff To Previous Version (65377)

Version SVN diff:

--- wxPython/3rdParty/AGW/agw/supertooltip.py       2010/08/21 20:27:02     65377
+++ wxPython/3rdParty/AGW/agw/supertooltip.py       2011/07/23 19:24:24     68343
@@ -2,7 +2,7 @@
# SUPERTOOLTIP wxPython IMPLEMENTATION
#
# Andrea Gavana, @ 07 October 2008
-# Latest Revision: 02 Aug 2010, 09.00 GMT
+# Latest Revision: 22 Jul 2011, 21.00 GMT
#
#
# TODO List
@@ -27,7 +27,7 @@

"""
SuperToolTip is a class that mimics the behaviour of `wx.TipWindow` and generic tooltip
-windows, although it is a custom-drawn widget.
+windows, although it is a custom-drawn widget.

Description
@@ -77,7 +77,7 @@

SuperToolTip is distributed under the wxPython license.

-Latest Revision: Andrea Gavana @ 02 Aug 2010, 09.00 GMT
+Latest Revision: Andrea Gavana @ 22 Jul 2011, 21.00 GMT

Version 0.4

@@ -186,8 +186,8 @@
hl = line[indxStart+1:indxEnd].strip()
line = line[0:indxStart].strip()

-    return line, hl
-
+    return line, hl
+

class ToolTipWindowBase(object):
""" Base class for the different Windows and Mac implementation. """
@@ -203,11 +203,11 @@
self._spacing = 6
self._wasOnLink = False
self._hyperlinkRect, self._hyperlinkWeb = [], []
-
+
self._classParent = classParent
self._alphaTimer = wx.Timer(self, wx.ID_ANY)

-        # Bind the events
+        # Bind the events
self.Bind(wx.EVT_PAINT, self.OnPaint)
self.Bind(wx.EVT_SIZE, self.OnSize)
self.Bind(wx.EVT_ERASE_BACKGROUND, self.OnEraseBackground)
@@ -216,7 +216,7 @@
self.Bind(wx.EVT_KILL_FOCUS, self.OnDestroy)
self.Bind(wx.EVT_LEFT_DOWN, self.OnDestroy)
self.Bind(wx.EVT_LEFT_DCLICK, self.OnDestroy)
-
+

def OnPaint(self, event):
"""
@@ -227,7 +227,7 @@

# Go with double buffering...
dc = wx.BufferedPaintDC(self)
-
+
frameRect = self.GetClientRect()
x, y, width, height = frameRect
# Store the rects for the hyperlink lines
@@ -239,7 +239,7 @@
classParent.GetMiddleGradientColour(), \
classParent.GetBottomGradientColour()

-        # Get the user options for header, bitmaps etc...
+        # Get the user options for header, bitmaps etc...
drawHeader, drawFooter = classParent.GetDrawHeaderLine(), classParent.GetDrawFooterLine()
topRect = wx.Rect(frameRect.x, frameRect.y, frameRect.width, frameRect.height/2)
bottomRect = wx.Rect(frameRect.x, frameRect.y+frameRect.height/2, frameRect.width, frameRect.height/2+1)
@@ -250,7 +250,7 @@
header, headerBmp = classParent.GetHeader(), classParent.GetHeaderBitmap()
headerFont, messageFont, footerFont, hyperlinkFont = classParent.GetHeaderFont(), classParent.GetMessageFont(), \
classParent.GetFooterFont(), classParent.GetHyperlinkFont()
-
+
xPos, yPos = self._spacing, 0
bmpXPos = bmpYPos = 0
bmpHeight = textHeight = bmpWidth = 0
@@ -259,7 +259,7 @@
# We got the header bitmap
bmpHeight, bmpWidth = headerBmp.GetHeight(), headerBmp.GetWidth()
bmpXPos = self._spacing
-
+
if header:
# We got the header text
dc.SetFont(headerFont)
@@ -280,7 +280,7 @@
dc.DrawLine(self._spacing, yPos+self._spacing, width-self._spacing, yPos+self._spacing)

# Get the big body image (if any)
-        embeddedImage = classParent.GetBodyImage()
+        embeddedImage = classParent.GetBodyImage()
bmpWidth = bmpHeight = -1
if embeddedImage and embeddedImage.IsOk():
bmpWidth, bmpHeight = embeddedImage.GetWidth(), embeddedImage.GetHeight()
@@ -292,7 +292,7 @@
yText = yPos
normalText = wx.SystemSettings_GetColour(wx.SYS_COLOUR_MENUTEXT)
hyperLinkText = wx.BLUE
-
+
for indx, line in enumerate(lines):
# Loop over all the lines in the message
isLink = False
@@ -318,7 +318,7 @@

xText = (bmpWidth > 0 and [bmpWidth+2*self._spacing] or [self._spacing])[0]
yText += textHeight/2+self._spacing
-
+
dc.DrawText(line, xText, yText)
if isLink:
# Store the hyperlink rectangle and link
@@ -334,21 +334,21 @@
toAdd = self._spacing
else:
yPos += messageHeight + 2*self._spacing
-
+
yText = max(messageHeight, bmpHeight+2*self._spacing)
if embeddedImage and embeddedImage.IsOk():
# Draw the main body image
dc.DrawBitmap(embeddedImage, self._spacing, messagePos, True)
-
+
footer, footerBmp = classParent.GetFooter(), classParent.GetFooterBitmap()
bmpHeight = bmpWidth = textHeight = textWidth = 0
bmpXPos = bmpYPos = 0
-
+
if footerBmp and footerBmp.IsOk():
# Got the footer bitmap
bmpHeight, bmpWidth = footerBmp.GetHeight(), footerBmp.GetWidth()
bmpXPos = self._spacing
-
+
if footer:
# Got the footer text
dc.SetFont(footerFont)
@@ -376,10 +376,10 @@

:param `event`: a `wx.EraseEvent` event to be processed.

-        :note: This method is intentionally empty to reduce flicker.
+        :note: This method is intentionally empty to reduce flicker.
"""

-        # This is intentionally empty to reduce flicker
+        # This is intentionally empty to reduce flicker
pass

@@ -428,7 +428,7 @@
# We haven't clicked a link
self.Destroy()
return
-
+
x, y = event.GetPosition()
for indx, rect in enumerate(self._hyperlinkRect):
if rect.Contains((x, y)):
@@ -456,12 +456,12 @@
if self._alphaTimer.IsRunning():
return

-        # Calculate starting alpha value and its step
+        # Calculate starting alpha value and its step
self.amount = (isShow and [0] or [255])[0]
self.delta = (isShow and [5] or [-5])[0]
# Start the timer
self._alphaTimer.Start(30)
-
+

def SetFont(self, font):
"""
@@ -474,14 +474,14 @@
self._classParent.InitFont()
self.Invalidate()

-
+
def Invalidate(self):
""" Invalidate L{SuperToolTip} size and repaint it. """

if not self._classParent.GetMessage():
# No message yet...
return
-
+
self.CalculateBestSize()
self.Refresh()

@@ -499,7 +499,7 @@
if not _libimported:
# No Mark Hammond's win32all extension
return
-
+
if wx.Platform != "__WXMSW__":
# This works only on Windows XP
return
@@ -512,12 +512,12 @@
if hasattr(win32gui, "CreateRoundRectRgn"):
rgn = win32gui.CreateRoundRectRgn(0, 0, size.x, size.y, 9, 9)
win32gui.SetWindowRgn(hwnd, rgn, True)
-
+
CS_DROPSHADOW = 0x00020000
# Load the user32 library
if not hasattr(self, "_winlib"):
self._winlib = win32api.LoadLibrary("user32")
-
+
csstyle = win32api.GetWindowLong(hwnd, win32con.GCL_STYLE)
if drop:
if csstyle & CS_DROPSHADOW:
@@ -527,7 +527,7 @@
else:
csstyle &= ~CS_DROPSHADOW

-        # Drop the shadow underneath the window
+        # Drop the shadow underneath the window
GCL_STYLE= -26
cstyle= win32gui.GetClassLong(hwnd, GCL_STYLE)
if drop:
@@ -546,7 +546,7 @@

# Increase (or decrease) the alpha channel
self.amount += self.delta
-
+
if self.amount > 255 or self.amount < 0:
# We're done, stop the timer
self._alphaTimer.Stop()
@@ -555,7 +555,7 @@
self.Destroy()
return

-        # Make the SuperToolTip more or less transparent
+        # Make the SuperToolTip more or less transparent
self.MakeWindowTransparent(self.amount)
if not self.IsShown():
self.Show()
@@ -574,30 +574,30 @@
if not _libimported:
# No way, only Windows XP with Mark Hammond's win32all
return
-
+
# this API call is not in all SDKs, only the newer ones, so
# we will runtime bind this
if wx.Platform != "__WXMSW__":
return
-
+
hwnd = self.GetHandle()

-        if not hasattr(self, "_winlib"):
+        if not hasattr(self, "_winlib"):
self._winlib = win32api.LoadLibrary("user32")
-
+
pSetLayeredWindowAttributes = win32api.GetProcAddress(self._winlib,
"SetLayeredWindowAttributes")
-
+
if pSetLayeredWindowAttributes == None:
return
-
+
exstyle = win32api.GetWindowLong(hwnd, win32con.GWL_EXSTYLE)
if 0 == (exstyle & 0x80000):
-            win32api.SetWindowLong(hwnd, win32con.GWL_EXSTYLE, exstyle | 0x80000)
-
+            win32api.SetWindowLong(hwnd, win32con.GWL_EXSTYLE, exstyle | 0x80000)
+
winxpgui.SetLayeredWindowAttributes(hwnd, 0, amount, 2)
-
-
+
+
def CalculateBestSize(self):
""" Calculates the L{SuperToolTip} window best size. """

@@ -635,7 +635,7 @@
messageHeight = 0
textSpacing = (bmpWidth and [3*self._spacing] or [2*self._spacing])[0]
lines = classParent.GetMessage().split("\n")
-
+
for line in lines:
if line.startswith("</b>"):      # is a bold line
font = MakeBold(messageFont)
@@ -667,7 +667,7 @@
footer, footerBmp = classParent.GetFooter(), classParent.GetFooterBitmap()
textHeight, bmpHeight = 0, 0

-        # See the OnPaint method for explanations...
+        # See the OnPaint method for explanations...
if footer:
dc.SetFont(footerFont)
textWidth, textHeight = dc.GetTextExtent(footer)
@@ -690,7 +690,7 @@
# Handle Mac and Windows/GTK differences...

if wx.Platform == "__WXMAC__":
-
+
class ToolTipWindow(wx.Frame, ToolTipWindowBase):
""" Popup window that works on wxMac. """

@@ -701,7 +701,7 @@
:param `parent`: the L{SuperToolTip} parent widget;
:param `classParent`: the L{SuperToolTip} class object.
"""
-
+
wx.Frame.__init__(self, parent, style=wx.NO_BORDER|wx.FRAME_FLOAT_ON_PARENT|wx.FRAME_NO_TASKBAR|wx.POPUP_WINDOW)
# Call the base class
ToolTipWindowBase.__init__(self, parent, classParent)
@@ -713,7 +713,7 @@
A simple `wx.PopupWindow` that holds fancy tooltips.
Not available on Mac as `wx.PopupWindow` is not implemented there.
"""
-
+
def __init__(self, parent, classParent):
"""
Default class constructor.
@@ -726,7 +726,7 @@
# Call the base class
ToolTipWindowBase.__init__(self, parent, classParent)

-
+
class SuperToolTip(object):
"""
The main class for L{SuperToolTip}, which holds all the methods
@@ -745,10 +745,10 @@
:param `footer`: the footer text;
:param `footerBmp`: the footer bitmap.
"""
-
+
self._superToolTip = None

-        # Set all the initial options
+        # Set all the initial options
self.SetMessage(message)
self.SetBodyImage(bodyImage)
self.SetHeader(header)
@@ -762,15 +762,15 @@
self._bottomLine = False

self.InitFont()
-
-        # Get the running applications
+
+        # Get the running applications
self._runningApp = wx.GetApp()
self._runningApp.__superToolTip = True

# Build a couple of timers...
self._startTimer = wx.PyTimer(self.OnStartTimer)
self._endTimer = wx.PyTimer(self.OnEndTimer)
-
+
self.SetStartDelay()
self.SetEndDelay()
self.ApplyStyle("XP Blue")
@@ -780,23 +780,23 @@
"""
Sets the target window for L{SuperToolTip}.

-        :param `widget`: the widget to which L{SuperToolTip} is associated.
+        :param `widget`: the widget to which L{SuperToolTip} is associated.
"""

self._widget = widget
-
+
self._widget.Bind(wx.EVT_ENTER_WINDOW, self.OnWidgetEnter)
self._widget.Bind(wx.EVT_LEAVE_WINDOW, self.OnWidgetLeave)
-
+

def GetTarget(self):
""" Returns the target window for L{SuperToolTip}. """
-
+
if not hasattr(self, "_widget"):
raise Exception("\nError: the widget target for L{SuperToolTip} has not been set.")

return self._widget
-
+

def SetStartDelay(self, delay=1):
"""
@@ -804,15 +804,15 @@

:param `delay`: the delay in seconds.
"""
-
-        self._startDelayTime = float(delay)
-
+
+        self._startDelayTime = float(delay)
+

def GetStartDelay(self):
""" Returns the tim delay (in seconds) after which the L{SuperToolTip} is created."""

return self._startDelayTime
-
+

def SetEndDelay(self, delay=1e6):
"""
@@ -820,15 +820,15 @@

:param `delay`: the delay in seconds.
"""
-
+
self._endDelayTime = float(delay)
-
+

def GetEndDelay(self):
""" Returns the delay time (in seconds) after which the L{SuperToolTip} is destroyed."""
-
+
return self._endDelayTime
-
+

def OnWidgetEnter(self, event):
"""
@@ -836,7 +836,7 @@

:param `event`: a `wx.MouseEvent` event to be processed.
"""
-
+
if self._superToolTip:
# Not yet created
return
@@ -853,7 +853,7 @@
self._startTimer.Start(self._startDelayTime*1000)
event.Skip()

-
+
def OnWidgetLeave(self, event):
"""
Handles the ``wx.EVT_LEAVE_WINDOW`` event for the target widgets.
@@ -864,7 +864,7 @@
pos = wx.GetMousePosition()
realPos = self._widget.ScreenToClient(pos)
rect = self._widget.GetClientRect()
-
+
if rect.Contains(realPos):
# We get fake leave events...
event.Skip()
@@ -879,18 +879,23 @@

self._startTimer.Stop()
self._endTimer.Stop()
-
+
event.Skip()

def GetTipWindow(self):
""" Return the TipWindow, will return None if not yet created """
-
+
return self._superToolTip
-
+

def OnStartTimer(self):
""" The creation time has expired, create the L{SuperToolTip}. """

+        # target widget might already be destroyed
+        if not self._widget:
+            self._startTimer.Stop()
+            return
+
tip = ToolTipWindow(self._widget, self)
self._superToolTip = tip
self._superToolTip.CalculateBestSize()
@@ -901,10 +906,10 @@
self._superToolTip.StartAlpha(True)
else:
self._superToolTip.Show()
-
+
self._startTimer.Stop()
self._endTimer.Start(self._endDelayTime*1000)
-
+

def OnEndTimer(self):
""" The show time for L{SuperToolTip} has expired, destroy the L{SuperToolTip}. """
@@ -914,15 +919,15 @@
self._superToolTip.StartAlpha(False)
else:
self._superToolTip.Destroy()
-
+
self._endTimer.Stop()
-
+

def DoShowNow(self):
""" Create the L{SuperToolTip} immediately. """

if self._superToolTip:
-            # need to destroy it if already exists,
+            # need to destroy it if already exists,
# otherwise we might end up with many of them
self._superToolTip.Destroy()

@@ -931,15 +936,15 @@
self._superToolTip.CalculateBestSize()
self._superToolTip.SetPosition(wx.GetMousePosition())
self._superToolTip.DropShadow(self.GetDropShadow())
-
+
# need to stop this, otherwise we get into trouble when leaving the window
self._startTimer.Stop()
-
+
if self.GetUseFade():
self._superToolTip.StartAlpha(True)
else:
self._superToolTip.Show()
-
+
self._endTimer.Start(self._endDelayTime*1000)

@@ -950,11 +955,11 @@
# Unbind the events!
self._widget.Unbind(wx.EVT_LEAVE_WINDOW)
self._widget.Unbind(wx.EVT_ENTER_WINDOW)
-
+
self._superToolTip.Destroy()
del self._superToolTip
self._superToolTip = None
-
+

def SetHeaderBitmap(self, bmp):
"""
@@ -972,7 +977,7 @@
""" Returns the header bitmap. """

return self._headerBmp
-
+

def SetHeader(self, header):
"""
@@ -981,7 +986,7 @@
:param `header`: the header text to display.
"""

-        self._header = header
+        self._header = header
if self._superToolTip:
self._superToolTip.Invalidate()

@@ -990,7 +995,7 @@
""" Returns the header text. """

return self._header
-
+

def SetDrawHeaderLine(self, draw):
"""
@@ -1009,7 +1014,7 @@
""" Returns whether the separator line after the header is drawn or not. """

return self._topLine
-
+

def SetBodyImage(self, bmp):
"""
@@ -1022,11 +1027,11 @@
if self._superToolTip:
self._superToolTip.Invalidate()

-
+
def GetBodyImage(self):
""" Returns the main body bitmap used in L{SuperToolTip}. """

-        return self._embeddedImage
+        return self._embeddedImage

def SetDrawFooterLine(self, draw):
@@ -1046,7 +1051,7 @@
""" Returns whether the separator line before the footer is drawn or not. """

return self._bottomLine
-
+

def SetFooterBitmap(self, bmp):
"""
@@ -1063,7 +1068,7 @@
def GetFooterBitmap(self):
""" Returns the footer bitmap. """

-        return self._footerBmp
+        return self._footerBmp

def SetFooter(self, footer):
@@ -1073,17 +1078,17 @@
:param `footer`: the footer text to display.
"""

-        self._footer = footer
+        self._footer = footer
if self._superToolTip:
self._superToolTip.Invalidate()

-
+
def GetFooter(self):
""" Returns the footer text. """

return self._footer

-
+
def SetMessage(self, message):
"""
Sets the main body message for L{SuperToolTip}.
@@ -1125,7 +1130,7 @@
if self._superToolTip:
self._superToolTip.Refresh()

-
+
def SetBottomGradientColour(self, colour):
"""
Sets the bottom gradient colour for L{SuperToolTip}.
@@ -1148,7 +1153,7 @@
self._textColour = colour
if self._superToolTip:
self._superToolTip.Refresh()
-
+

def GetTopGradientColour(self):
""" Returns the top gradient colour. """
@@ -1161,18 +1166,18 @@

return self._middleColour

-
+
def GetBottomGradientColour(self):
""" Returns the bottom gradient colour. """

return self._bottomColour
-
+

def GetTextColour(self):
""" Returns the text colour. """

return self._textColour
-
+

SetTopGradientColor = SetTopGradientColour
SetMiddleGradientColor = SetMiddleGradientColour
@@ -1182,7 +1187,7 @@
GetBottomGradientColor = GetBottomGradientColour
SetTextColor = SetTextColour
GetTextColor = GetTextColour
-
+

def InitFont(self):
""" Initalizes the fonts for L{SuperToolTip}. """
@@ -1234,7 +1239,7 @@
self._footerFont = font
if self._superToolTip:
self._superToolTip.Invalidate()
-
+

def SetHyperlinkFont(self, font):
"""
@@ -1247,7 +1252,7 @@
self._hyperlinkFont = font
if self._superToolTip:
self._superToolTip.Invalidate()
-
+

def GetMessageFont(self):
""" Returns the font used in the main body message. """
@@ -1264,21 +1269,21 @@
def GetFooterFont(self):
""" Returns the font used for the footer text. """

-        return self._footerFont
+        return self._footerFont

def GetHyperlinkFont(self):
""" Returns the font used for the hyperlink text. """

-        return self._hyperlinkFont
-
+        return self._hyperlinkFont
+

def SetDropShadow(self, drop):
"""
Whether to draw a shadow below L{SuperToolTip} or not.

:param `drop`: ``True`` to drop a shadow below the control, ``False`` otherwise.
-
+
:note: This method is available only on Windows and requires Mark Hammond's
pywin32 package.
"""
@@ -1297,20 +1302,20 @@
"""

return self._dropShadow
-
+

def SetUseFade(self, fade):
"""
Whether to use a fade in/fade out effect or not.

:param `fade`: ``True`` to use a fade in/fade out effect, ``False`` otherwise.
-
+
:note: This method is available only on Windows and requires Mark Hammond's
pywin32 package.
"""
-
+
self._useFade = fade
-
+

def GetUseFade(self):
"""
@@ -1322,7 +1327,7 @@

return self._useFade

-
+
def ApplyStyle(self, style):
"""
Applies none of the predefined styles.
@@ -1343,7 +1348,7 @@
if self._superToolTip:
self._superToolTip.Refresh()

-
+
def EnableTip(self, enable=True):
"""
Globally (application-wide) enables/disables L{SuperToolTip}.

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • supertooltip »
  • SVN Revision 68343 For supertooltip


SVN Revision 68881 For supertooltip

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • supertooltip »
  • SVN Revision 68881 For supertooltip

svn SVN Revision 68881 For supertooltip

This file contains the SVN revision history for supertooltip, at revision 68881.

Available information include commit date, the name of the committer, the file size, the SVN log messages and a diff from the previous version (if available).

File Information

  • Commit Date: 17-Oct-2008 20:51:43 UTC
  • Committer: AG
  • File Size: 45578 byte(s)

Log Messages

The following log message was entered by the committer:

  • AGW: General overhaul of the documentation, much improved. All the widgets have their own sample usage in the docs as well;

  • FlatNotebook: Added the FNB_NAV_BUTTONS_WHEN_NEEDED style, which hides the navigation left/right arrows if all tabs fit;

  • RibbonBar: - Added the EVT_RIBBONBAR_TAB_LEFT_DCLICK event, which generates a special event

    when a ribbon bar tab is double-clicked;

    • Added support for toggle buttons;
    • Improved support for ribbon panel sizers: panels with sizers should now automatically minimise at small sizes, and behave properly when popping up from a minimised state;
    • Added tooltips via SetToolTip for those buttons which have the help_string attribute set.

  • XLSGrid: a new widget was added to AGW, termed XLSGrid. It’s based on wx.grid.Grid and can be used to faithfully reproduce the appearance of a Microsoft Excel spreadsheets.

Diff To Previous Version (68362)

Version SVN diff:

--- wxPython/3rdParty/AGW/agw/supertooltip.py       2011/07/24 21:36:47     68362
+++ wxPython/3rdParty/AGW/agw/supertooltip.py       2011/08/25 16:40:17     68881
@@ -2,7 +2,7 @@
# SUPERTOOLTIP wxPython IMPLEMENTATION
#
# Andrea Gavana, @ 07 October 2008
-# Latest Revision: 22 Jul 2011, 21.00 GMT
+# Latest Revision: 17 Aug 2011, 15.00 GMT
#
#
# TODO List
@@ -26,14 +26,14 @@
# --------------------------------------------------------------------------------- #

"""
-SuperToolTip is a class that mimics the behaviour of `wx.TipWindow` and generic tooltip
+L{SuperToolTip} is a class that mimics the behaviour of `wx.TipWindow` and generic tooltip
windows, although it is a custom-drawn widget.

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

-SuperToolTip is a class that mimics the behaviour of `wx.TipWindow` and generic tooltip
+L{SuperToolTip} is a class that mimics the behaviour of `wx.TipWindow` and generic tooltip
windows, although it is a custom-drawn widget.

This class supports:
@@ -53,10 +53,50 @@
And a lot more. Check the demo for an almost complete review of the functionalities.

+Usage
+=====
+
+Usage example::
+
+    import wx
+    import wx.lib.agw.supertooltip as STT
+
+    class MyFrame(wx.Frame):
+
+        def __init__(self, parent):
+
+            wx.Frame.__init__(self, parent, -1, "SuperToolTip Demo")
+
+            panel = wx.Panel(self)
+            button = wx.Button(panel, -1, "I am the SuperToolTip target", pos=(100, 50))
+
+            tip = STT.SuperToolTip("A nice tooltip message")
+
+            tip.SetHeader("Hello World")
+            tip.SetTarget(button)
+            tip.SetDrawHeaderLine(True)
+
+            tip.ApplyStyle("Office 2007 Blue")
+
+            tip.SetDropShadow(True)
+
+
+    # our normal wxApp-derived class, as usual
+
+    app = wx.PySimpleApp()
+
+    frame = MyFrame(None)
+    app.SetTopWindow(frame)
+    frame.Show()
+
+    app.MainLoop()
+
+
+
Supported Platforms
===================

-SuperToolTip has been tested on the following platforms:
+L{SuperToolTip} has been tested on the following platforms:
* Windows (Windows XP).

@@ -75,9 +115,9 @@
License And Version
===================

-SuperToolTip is distributed under the wxPython license.
+L{SuperToolTip} is distributed under the wxPython license.

-Latest Revision: Andrea Gavana @ 22 Jul 2011, 21.00 GMT
+Latest Revision: Andrea Gavana @ 17 Aug 2011, 15.00 GMT

Version 0.4

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • supertooltip »
  • SVN Revision 68881 For supertooltip


SVN Revision 69086 For supertooltip

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • supertooltip »
  • SVN Revision 69086 For supertooltip

svn SVN Revision 69086 For supertooltip

This file contains the SVN revision history for supertooltip, at revision 69086.

Available information include commit date, the name of the committer, the file size, the SVN log messages and a diff from the previous version (if available).

File Information

  • Commit Date: 17-Oct-2008 19:15:31 UTC
  • Committer: AG
  • File Size: 46076 byte(s)

Log Messages

The following log message was entered by the committer:

  • Fixed bug #13437 for SuperToolTip;
  • Fixed bug #13477 for UltimateListCtrl.

Diff To Previous Version (68881)

Version SVN diff:

--- wxPython/3rdParty/AGW/agw/supertooltip.py       2011/08/25 16:40:17     68881
+++ wxPython/3rdParty/AGW/agw/supertooltip.py       2011/09/14 19:39:08     69086
@@ -2,7 +2,7 @@
# SUPERTOOLTIP wxPython IMPLEMENTATION
#
# Andrea Gavana, @ 07 October 2008
-# Latest Revision: 17 Aug 2011, 15.00 GMT
+# Latest Revision: 14 Sep 2011, 21.00 GMT
#
#
# TODO List
@@ -117,7 +117,7 @@

L{SuperToolTip} is distributed under the wxPython license.

-Latest Revision: Andrea Gavana @ 17 Aug 2011, 15.00 GMT
+Latest Revision: Andrea Gavana @ 14 Sep 2011, 21.00 GMT

Version 0.4

@@ -726,6 +726,21 @@
maxHeight += toAdd
self.SetSize((maxWidth, maxHeight))

+    def CalculateBestPosition(self,widget):
+        screen = wx.ClientDisplayRect()[2:]
+        left,top = widget.ClientToScreenXY(0,0)
+        right,bottom = widget.ClientToScreenXY(*widget.GetClientRect()[2:])
+        size = self.GetSize()
+        if right+size[0]>screen[0]:
+            xpos = left-size[0]
+        else:
+            xpos = right
+        if bottom+size[1]>screen[1]:
+            ypos = top-size[1]
+        else:
+            ypos = bottom
+        self.SetPosition((xpos,ypos))
+

# Handle Mac and Windows/GTK differences...

@@ -939,7 +954,7 @@
tip = ToolTipWindow(self._widget, self)
self._superToolTip = tip
self._superToolTip.CalculateBestSize()
-        self._superToolTip.SetPosition(wx.GetMousePosition())
+        self._superToolTip.CalculateBestPosition(self._widget)
self._superToolTip.DropShadow(self.GetDropShadow())

if self.GetUseFade():
@@ -974,7 +989,7 @@
tip = ToolTipWindow(self._widget, self)
self._superToolTip = tip
self._superToolTip.CalculateBestSize()
-        self._superToolTip.SetPosition(wx.GetMousePosition())
+        self._superToolTip.CalculateBestPosition(self._widget)
self._superToolTip.DropShadow(self.GetDropShadow())

# need to stop this, otherwise we get into trouble when leaving the window

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • supertooltip »
  • SVN Revision 69086 For supertooltip


SVN Revision 69382 For tabart

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • aui library »
  • aui.tabart »
  • SVN Revision 69382 For tabart

svn SVN Revision 69382 For tabart

This file contains the SVN revision history for tabart, at revision 69382.

Available information include commit date, the name of the committer, the file size, the SVN log messages and a diff from the previous version (if available).

File Information

  • Commit Date: 31-Mar-2009 15:36:51 UTC
  • Committer: AG
  • File Size: 107044 byte(s)

Log Messages

The following log message was entered by the committer:

AuiNotebook: possibly fix (?) un-reproduceable bug on tab size/text clipped.

Diff To Previous Version (66750)

Version SVN diff:

--- wxPython/3rdParty/AGW/agw/aui/tabart.py 2011/01/24 22:53:12     66750
+++ wxPython/3rdParty/AGW/agw/aui/tabart.py 2011/10/11 19:17:58     69382
@@ -2208,6 +2208,10 @@

# add some padding
tab_width += 10
+
+        if not bitmap.IsOk():
+            tab_width += 5
+
tab_height += 2

return (tab_width, tab_height), x_extent

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • aui library »
  • aui.tabart »
  • SVN Revision 69382 For tabart


thumbnailctrl functions

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • thumbnailctrl »
  • thumbnailctrl functions

thumbnailctrl functions

This is the description of standalone Python functions in the thumbnailctrl module.

Functions Summary

CmpThumb | Compares two thumbnails in terms of file names and ids.
GetMondrianBitmap | Returns a default image placeholder as a wx.Bitmap.
GetMondrianData | Returns a default image placeholder as a decompressed stream of characters.
GetMondrianImage | Returns a default image placeholder as a wx.Image.
SortFiles | Sort files in alphabetical order.
getDataBL | Return the second part of the shadow dropped behind thumbnails.
getDataSH | Return the first part of the shadow dropped behind thumbnails.
getDataTR | Return the third part of the shadow dropped behind thumbnails.
getShadow | Creates a shadow behind every thumbnail.
opj | Convert paths to the platform-specific separator.

API Functions API

CmpThumb(first, second) [source]

Compares two thumbnails in terms of file names and ids.

Parameters:
  • first – an instance of Thumb;
  • second – another instance of Thumb.

GetMondrianBitmap() [source]

Returns a default image placeholder as a wx.Bitmap.

GetMondrianData() [source]

Returns a default image placeholder as a decompressed stream of characters.

GetMondrianImage() [source]

Returns a default image placeholder as a wx.Image.

SortFiles(items, sorteditems, filenames) [source]

Sort files in alphabetical order.

Parameters:
  • sorteditems – a list of Thumb objects;
  • filenames – a list of image filenames.

getDataBL() [source]

Return the second part of the shadow dropped behind thumbnails.

getDataSH() [source]

Return the first part of the shadow dropped behind thumbnails.

getDataTR() [source]

Return the third part of the shadow dropped behind thumbnails.

getShadow() [source]

Creates a shadow behind every thumbnail.

opj(path) [source]

Convert paths to the platform-specific separator.

Parameters: path – the path to convert.

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • infobar
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • thumbnailctrl »
  • thumbnailctrl functions


NativeImageHandler

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • thumbnailctrl »
  • NativeImageHandler

NativeImageHandler

This image handler loads and manipulates the thumbnails with the help of wxPython’s own image related functions.

hierarchy Inheritance Diagram

Inheritance diagram for: NativeImageHandler

Inheritance diagram of NativeImageHandler

Methods Summary

HighlightImage | Adjust overall image brightness to highlight.
LoadThumbnail | Load the file and rescale it.

API Class API

class NativeImageHandler(object) [source]

This image handler loads and manipulates the thumbnails with the help of wxPython’s own image related functions.

HighlightImage(img, factor) [source]

Adjust overall image brightness to highlight.

Parameters:
  • img – an instance of wx.Image;
  • factor – a floating point number representing the highlight factor.

LoadThumbnail(filename, thumbnailsize) [source]

Load the file and rescale it.

Parameters:
  • filename – a file containing an image;
  • thumbnailsize – the desired size of the thumbnail.

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • infobar
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • thumbnailctrl »
  • NativeImageHandler


PILImageHandler

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • thumbnailctrl »
  • PILImageHandler

PILImageHandler

This image handler loads and manipulates the thumbnails with the help of PIL (the Python Imaging Library).

hierarchy Inheritance Diagram

Inheritance diagram for: PILImageHandler

Inheritance diagram of PILImageHandler

Methods Summary

__init__ | Default class constructor.
HighlightImage | Adjust overall image brightness to highlight.
LoadThumbnail | Load the file and rescale it.

API Class API

class PILImageHandler(object) [source]

This image handler loads and manipulates the thumbnails with the help of PIL (the Python Imaging Library).

__init__() [source]

Default class constructor.

Note

If PIL is not installed, this will raise an exception. PIL can be downloaded from http://www.pythonware.com/products/pil/ .

HighlightImage(img, factor) [source]

Adjust overall image brightness to highlight.

Parameters:
  • img – an instance of wx.Image;
  • factor – unused in PILImageHandler.

LoadThumbnail(filename, thumbnailsize) [source]

Load the file and rescale it.

Parameters:
  • filename – a file containing an image;
  • thumbnailsize – the desired size of the thumbnail.

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • infobar
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • thumbnailctrl »
  • PILImageHandler


ScrolledThumbnail

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • thumbnailctrl »
  • ScrolledThumbnail

ScrolledThumbnail

This is the main class implementation of ThumbnailCtrl.

hierarchy Inheritance Diagram

Inheritance diagram for: ScrolledThumbnail

Inheritance diagram of ScrolledThumbnail

Methods Summary

__init__ | Default class constructor.
CalculateBestCaption | Calculates the best caption string to show based on the actual zoom factor.
Clear | Clears ThumbnailCtrl.
DeleteFiles | Deletes the selected thumbnails and their associated files.
DrawThumbnail | Draws a visible thumbnail.
EnableDragging | Enables/disables thumbnails drag and drop.
EnableToolTips | Globally enables/disables thumbnail file information.
GetCaption | Returns the thumbnail caption.
GetCaptionFont | Returns the font for all the thumbnail captions.
GetCaptionHeight | Returns the height for the file name caption.
GetDropShadow | Returns whether to drop a shadow behind thumbnails or not.
GetGlobalPopupMenu | Returns the global thumbnailss popup menu (no need of thumbnail selection).
GetHighlightPointed | Returns whether the thumbnail pointed should be highlighted or not.
GetItem | Returns the item at position index.
GetItemCount | Returns the number of thumbnails.
GetItemIndex | Returns the thumbnail index at position (x, y).
GetOriginalImage | Returns the original image associated to a thumbnail.
GetPaintRect | Returns the paint bounding rect for the OnPaint method.
GetPointed | Returns the pointed thumbnail index.
GetPointedItem | Returns the pointed thumbnail.
GetPopupMenu | Returns the thumbnails popup menu when at least one thumbnail is selected.
GetSelectedItem | Returns the selected thumbnail.
GetSelection | Returns the selected thumbnail.
GetSelectionColour | Returns the colour used to indicate a selected thumbnail.
GetShowDir | Returns the working directory with images.
GetThumbBorder | Returns the thumbnail border.
GetThumbHeight | Returns the thumbnail height.
GetThumbInfo | Returns the thumbnail information.
GetThumbOutline | Returns the thumbnail outline style on selection.
GetThumbSize | Returns the thumbnail size as width, height and border.
GetThumbWidth | Returns the thumbnail width.
GetZoomFactor | Returns the zoom factor.
InsertItem | Inserts a thumbnail in the specified position.
IsAudio | Returns True if a file contains audio data.
IsAudioVideo | Returns True if a file contains either audio or video data.
IsSelected | Returns whether a thumbnail is selected or not.
IsVideo | Returns True if a file contains video data.
ListDirectory | Returns list of file info objects for files of particular extensions.
LoadImages | Threaded method to load images.
OnChar | Handles the wx.EVT_CHAR event for ThumbnailCtrl.
OnMouseDClick | Handles the wx.EVT_LEFT_DCLICK event for ThumbnailCtrl.
OnMouseDown | Handles the wx.EVT_LEFT_DOWN and wx.EVT_RIGHT_DOWN events for ThumbnailCtrl.
OnMouseLeave | Handles the wx.EVT_LEAVE_WINDOW event for ThumbnailCtrl.
OnMouseMove | Handles the wx.EVT_MOTION event for ThumbnailCtrl.
OnMouseUp | Handles the wx.EVT_LEFT_UP and wx.EVT_RIGHT_UP events for ThumbnailCtrl.
OnMouseWheel | Handles the wx.EVT_MOUSEWHEEL event for ThumbnailCtrl.
OnPaint | Handles the wx.EVT_PAINT event for ThumbnailCtrl.
OnResize | Handles the wx.EVT_SIZE event for ThumbnailCtrl.
OnThumbChanged | Handles the EVT_THUMBNAILS_THUMB_CHANGED event for ThumbnailCtrl.
RemoveItemAt | Removes a thumbnail at the specified position.
Rotate | Rotates the selected thumbnails by the angle specified by angle.
ScrollToSelected | Scrolls the wx.ScrolledWindow to the selected thumbnail.
SetCaption | Sets the current caption string.
SetCaptionFont | Sets the font for all the thumbnail captions.
SetDropShadow | Sets whether to drop a shadow behind thumbnails or not.
SetGlobalPopupMenu | Sets the global thumbnails popup menu (no need of thumbnail selection).
SetHighlightPointed | Sets whether the thumbnail pointed should be highlighted or not.
SetLabelControl | Sets the thumbnail label as wx.StaticText.
SetOrientation | Set the ThumbnailCtrl orientation (partially implemented).
SetPopupMenu | Sets the thumbnails popup menu when at least one thumbnail is selected.
SetSelection | Sets thumbnail selection.
SetSelectionColour | Sets the colour used to indicate a selected thumbnail.
SetThumbOutline | Sets the thumbnail outline style on selection.
SetThumbSize | Sets the thumbnail size as width, height and border.
SetZoomFactor | Sets the zoom factor.
ShowDir | Shows thumbnails for a particular folder.
ShowFileNames | Sets whether the user wants to show file names under the thumbnails or not.
ShowThumbs | Shows all the thumbnails.
SortItems | Sorts the items accordingly to the CmpThumb function.
ThreadImage | Threaded method to load images.
UpdateItems | Updates thumbnail items.
UpdateProp | Updates ThumbnailCtrl and its visible thumbnails.
UpdateShow | Updates thumbnail items.
ZoomIn | Zooms the thumbnails in.
ZoomOut | Zooms the thumbnails out.

API Class API

class ScrolledThumbnail(wx.ScrolledWindow) [source]

This is the main class implementation of ThumbnailCtrl.

__init__(parent, id=wx.ID_ANY, pos=wx.DefaultPosition, size=wx.DefaultSize, thumboutline=THUMB_OUTLINE_IMAGE, thumbfilter=THUMB_FILTER_IMAGES, imagehandler=PILImageHandler) [source]

Default class constructor.

Parameters:
  • parent – parent window. Must not be None;
  • id – window identifier. A value of -1 indicates a default value;
  • pos – the control position. A value of (-1, -1) indicates a default position, chosen by either the windowing system or wxPython, depending on platform;
  • size – the control size. A value of (-1, -1) indicates a default size, chosen by either the windowing system or wxPython, depending on platform;
  • thumboutline – outline style for ScrolledThumbnail, which may be:

    Outline Flag | Value | Description
    THUMB_OUTLINE_NONE | 0 | No outline is drawn on selection
    THUMB_OUTLINE_FULL | 1 | Full outline (image+caption) is drawn on selection
    THUMB_OUTLINE_RECT | 2 | Only thumbnail bounding rectangle is drawn on selection (default)
    THUMB_OUTLINE_IMAGE | 4 | Only image bounding rectangle is drawn.
  • thumbfilter – filter for image/video/audio files. Actually only THUMB_FILTER_IMAGES is implemented;
  • imagehandler – can be PILImageHandler if PIL is installed (faster), or NativeImageHandler which only uses wxPython image methods.

CalculateBestCaption(dc, caption, sw, width) [source]

Calculates the best caption string to show based on the actual zoom factor.

Parameters:
  • dc – an instance of wx.DC;
  • caption – the original caption string;
  • sw – the maximum width allowed for the caption string, in pixels;
  • width – the caption string width, in pixels.

Clear() [source]

Clears ThumbnailCtrl.

DeleteFiles() [source]

Deletes the selected thumbnails and their associated files.

Warning

This method deletes the original files too.

DrawThumbnail(bmp, thumb, index) [source]

Draws a visible thumbnail.

Parameters:
  • bmp – the thumbnail version of the original image;
  • thumb – an instance of Thumb;
  • index – the index of the thumbnail to draw.

EnableDragging(enable=True) [source]

Enables/disables thumbnails drag and drop.

Parameters: enable – True to enable drag and drop, False to disable it.

EnableToolTips(enable=True) [source]

Globally enables/disables thumbnail file information.

Parameters: enable – True to enable thumbnail file information, False to disable it.

GetCaption() [source]

Returns the thumbnail caption.

GetCaptionFont() [source]

Returns the font for all the thumbnail captions.

GetCaptionHeight(begRow, count=1) [source]

Returns the height for the file name caption.

Parameters:
  • begRow – the caption line at which we start measuring the height;
  • count – the number of lines to measure.

GetDropShadow() [source]

Returns whether to drop a shadow behind thumbnails or not.

GetGlobalPopupMenu() [source]

Returns the global thumbnailss popup menu (no need of thumbnail selection).

GetHighlightPointed() [source]

Returns whether the thumbnail pointed should be highlighted or not.

Note

Please be aware that this functionality may be slow on slower computers.

GetItem(index) [source]

Returns the item at position index.

Parameters: index – the thumbnail index position.

GetItemCount() [source]

Returns the number of thumbnails.

GetItemIndex(x, y) [source]

Returns the thumbnail index at position (x, y).

Parameters:
  • x – the mouse x position;
  • y – the mouse y position.

GetOriginalImage(index=None) [source]

Returns the original image associated to a thumbnail.

Parameters: index – the index of the thumbnail. If defaulted to None, the current selection is used.

GetPaintRect() [source]

Returns the paint bounding rect for the OnPaint method.

GetPointed() [source]

Returns the pointed thumbnail index.

GetPointedItem() [source]

Returns the pointed thumbnail.

GetPopupMenu() [source]

Returns the thumbnails popup menu when at least one thumbnail is selected.

GetSelectedItem(index) [source]

Returns the selected thumbnail.

Parameters: index – the thumbnail index (i.e., the selection).

GetSelection(selIndex=-1) [source]

Returns the selected thumbnail.

Parameters: selIndex – if not equal to -1, the index of the selected thumbnail.

GetSelectionColour() [source]

Returns the colour used to indicate a selected thumbnail.

GetShowDir() [source]

Returns the working directory with images.

GetThumbBorder() [source]

Returns the thumbnail border.

GetThumbHeight() [source]

Returns the thumbnail height.

GetThumbInfo(thumb=-1) [source]

Returns the thumbnail information.

Parameters: thumb – the index of the thumbnail for which we are collecting information.

GetThumbOutline() [source]

Returns the thumbnail outline style on selection.

See also

SetThumbOutline for a list of possible return values.

GetThumbSize() [source]

Returns the thumbnail size as width, height and border.

GetThumbWidth() [source]

Returns the thumbnail width.

GetZoomFactor() [source]

Returns the zoom factor.

InsertItem(thumb, pos) [source]

Inserts a thumbnail in the specified position.

Parameters: pos – the index at which we wish to insert the new thumbnail.

IsAudio(fname) [source]

Returns True if a file contains audio data. Currently unused as ThumbnailCtrl recognizes only image files.

Parameters: fname – a file name.

Todo

Find a way to create thumbnails of video, audio and other formats.

IsAudioVideo(fname) [source]

Returns True if a file contains either audio or video data. Currently unused as ThumbnailCtrl recognizes only image files.

Parameters: fname – a file name.

Todo

Find a way to create thumbnails of video, audio and other formats.

IsSelected(indx) [source]

Returns whether a thumbnail is selected or not.

Parameters: indx – the index of the thumbnail to check for selection.

IsVideo(fname) [source]

Returns True if a file contains video data. Currently unused as ThumbnailCtrl recognizes only image files.

Parameters: fname – a file name.

Todo

Find a way to create thumbnails of video, audio and other formats.

ListDirectory(directory, fileExtList) [source]

Returns list of file info objects for files of particular extensions.

Parameters:
  • directory – the folder containing the images to thumbnail;
  • fileExtList – a Python list of file extensions to consider.

LoadImages(newfile, imagecount) [source]

Threaded method to load images. Used internally.

Parameters:
  • newfile – a file name containing an image to thumbnail;
  • imagecount – the number of images loaded until now.

OnChar(event) [source]

Handles the wx.EVT_CHAR event for ThumbnailCtrl.

Parameters: event – a wx.KeyEvent event to be processed.

Note

You have these choices:

  1. d key rotates 90 degrees clockwise the selected thumbnails;
  2. s key rotates 90 degrees counter-clockwise the selected thumbnails;
  3. a key rotates 180 degrees the selected thumbnails;
  4. Del key deletes the selected thumbnails;
  5. + key zooms in;
  6. - key zooms out.

OnMouseDClick(event) [source]

Handles the wx.EVT_LEFT_DCLICK event for ThumbnailCtrl.

Parameters: event – a wx.MouseEvent event to be processed.

OnMouseDown(event) [source]

Handles the wx.EVT_LEFT_DOWN and wx.EVT_RIGHT_DOWN events for ThumbnailCtrl.

Parameters: event – a wx.MouseEvent event to be processed.

OnMouseLeave(event) [source]

Handles the wx.EVT_LEAVE_WINDOW event for ThumbnailCtrl.

Parameters: event – a wx.MouseEvent event to be processed.

OnMouseMove(event) [source]

Handles the wx.EVT_MOTION event for ThumbnailCtrl.

Parameters: event – a wx.MouseEvent event to be processed.

OnMouseUp(event) [source]

Handles the wx.EVT_LEFT_UP and wx.EVT_RIGHT_UP events for ThumbnailCtrl.

Parameters: event – a wx.MouseEvent event to be processed.

OnMouseWheel(event) [source]

Handles the wx.EVT_MOUSEWHEEL event for ThumbnailCtrl.

Parameters: event – a wx.MouseEvent event to be processed.

Note

If you hold down the Ctrl key, you can zoom in/out with the mouse wheel.

OnPaint(event) [source]

Handles the wx.EVT_PAINT event for ThumbnailCtrl.

Parameters: event – a wx.PaintEvent event to be processed.

OnResize(event) [source]

Handles the wx.EVT_SIZE event for ThumbnailCtrl.

Parameters: event – a wx.SizeEvent event to be processed.

OnThumbChanged(event) [source]

Handles the EVT_THUMBNAILS_THUMB_CHANGED event for ThumbnailCtrl.

Parameters: event – a ThumbnailEvent event to be processed.

RemoveItemAt(pos) [source]

Removes a thumbnail at the specified position.

Parameters: pos – the index at which we wish to remove the thumbnail.

Rotate(angle=90) [source]

Rotates the selected thumbnails by the angle specified by angle.

Parameters: angle – the rotation angle for the thumbnail, in degrees.

ScrollToSelected() [source]

Scrolls the wx.ScrolledWindow to the selected thumbnail.

SetCaption(caption='') [source]

Sets the current caption string.

Parameters: caption – the current caption string.

SetCaptionFont(font=None) [source]

Sets the font for all the thumbnail captions.

Parameters: font – a valid wx.Font object. If defaulted to None, a standard font will be generated.

SetDropShadow(drop) [source]

Sets whether to drop a shadow behind thumbnails or not.

Parameters: drop – True to drop a shadow behind each thumbnail, False otheriwise.

SetGlobalPopupMenu(gpmenu) [source]

Sets the global thumbnails popup menu (no need of thumbnail selection).

Parameters: gpmenu – an instance of wx.Menu.

SetHighlightPointed(highlight=True) [source]

Sets whether the thumbnail pointed should be highlighted or not.

Parameters: highlight – True to enable highlight-on-point with the mouse, False otherwise.

Note

Please be aware that this functionality may be slow on slower computers.

SetLabelControl(statictext) [source]

Sets the thumbnail label as wx.StaticText.

Parameters: statictext – an instance of wx.StaticText.

SetOrientation(orient=THUMB_VERTICAL) [source]

Set the ThumbnailCtrl orientation (partially implemented).

Parameters: orient – one of THUMB_VERTICAL, THUMB_HORIZONTAL.

Todo

Correctly implement the THUMB_HORIZONTAL orientation.

SetPopupMenu(menu) [source]

Sets the thumbnails popup menu when at least one thumbnail is selected.

Parameters: menu – an instance of wx.Menu.

SetSelection(value=-1) [source]

Sets thumbnail selection.

Parameters: value – the thumbnail index to select.

SetSelectionColour(colour=None) [source]

Sets the colour used to indicate a selected thumbnail.

Parameters: colour – a valid wx.Colour object. If defaulted to None, it will be taken from the system settings.

SetThumbOutline(outline) [source]

Sets the thumbnail outline style on selection.

Parameters: outline – the outline to use on selection. This can be one of the following bits:

Outline Flag | Value | Description
THUMB_OUTLINE_NONE | 0 | No outline is drawn on selection
THUMB_OUTLINE_FULL | 1 | Full outline (image+caption) is drawn on selection
THUMB_OUTLINE_RECT | 2 | Only thumbnail bounding rectangle is drawn on selection (default)
THUMB_OUTLINE_IMAGE | 4 | Only image bounding rectangle is drawn.

SetThumbSize(width, height, border=6) [source]

Sets the thumbnail size as width, height and border.

Parameters:
  • width – the desired thumbnail width;
  • height – the desired thumbnail height;
  • border – the spacing between thumbnails.

SetZoomFactor(zoom=1.4) [source]

Sets the zoom factor.

Parameters: zoom – a floating point number representing the zoom factor. Must be greater than or equal to 1.0.

ShowDir(folder, filter=THUMB_FILTER_IMAGES) [source]

Shows thumbnails for a particular folder.

Parameters:
  • folder – a directory containing the images to thumbnail;
  • filter – filter images, video audio (currently implemented only for images).

Todo

Find a way to create thumbnails of video, audio and other formats.

ShowFileNames(show=True) [source]

Sets whether the user wants to show file names under the thumbnails or not.

Parameters: show – True to show file names under the thumbnails, False otherwise.

ShowThumbs(thumbs, caption) [source]

Shows all the thumbnails.

Parameters:
  • thumbs – should be a sequence with instances of Thumb;
  • caption – the caption text for the current selected thumbnail.

SortItems() [source]

Sorts the items accordingly to the CmpThumb function.

ThreadImage(filenames) [source]

Threaded method to load images. Used internally.

Parameters: filenames – a Python list of file names containing images.

UpdateItems() [source]

Updates thumbnail items.

UpdateProp(checkSize=True) [source]

Updates ThumbnailCtrl and its visible thumbnails.

Parameters: checkSize – True to update the items visibility if the window size has changed.

UpdateShow() [source]

Updates thumbnail items.

ZoomIn() [source]

Zooms the thumbnails in.

ZoomOut() [source]

Zooms the thumbnails out.

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • infobar
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • thumbnailctrl »
  • ScrolledThumbnail


Thumb

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • thumbnailctrl »
  • Thumb

Thumb

This is an auxiliary class, to handle single thumbnail information for every thumb.

Used internally.

hierarchy Inheritance Diagram

Inheritance diagram for: Thumb

Inheritance diagram of Thumb

Methods Summary

__init__ | Default class constructor.
BreakCaption | Breaks the caption in several lines of text (if needed).
GetBitmap | Returns the associated bitmap.
GetCaption | Returns the caption associated to a thumbnail.
GetCaptionLinesCount | Returns the number of lines for the caption.
GetCreationDate | Returns the file last modification date associated to a thumbnail.
GetFileName | Returns the file name associated with this thumbnail.
GetFileSize | Returns the file size associated to a thumbnail.
GetFullFileName | Returns the full filename of the thumbnail.
GetId | Returns the thumbnail identifier.
GetImage | Returns the thumbnail image.
GetOriginalImage | Returns the bitmap associated to a thumbnail, as a file name.
GetOriginalSize | Returns a tuple containing the original image width and height, in pixels.
GetRotatedImage | Returns a rotated image.
GetRotation | Returns the thumbnail rotation, in radians.
SetBitmap | Sets the thumbnail bitmap.
SetCaption | Sets the thumbnail caption.
SetFileName | Sets the file name associated with this thumbnail.
SetId | Sets the thumbnail identifier.
SetImage | Sets the thumbnail image.
SetRotatedImage | Sets the image as rotated (fast).
SetRotation | Sets the thumbnail rotation.

API Class API

class Thumb(object) [source]

This is an auxiliary class, to handle single thumbnail information for every thumb.

Used internally.

__init__(parent, folder, filename, caption='', size=0, lastmod=0) [source]

Default class constructor.

Parameters:
  • parent – the main ThumbnailCtrl window;
  • folder – the directory containing the images;
  • filename – a file containing an image;
  • caption – the thumbnail caption string;
  • size – the file size;
  • lastmod – the file last modification time.

BreakCaption(width) [source]

Breaks the caption in several lines of text (if needed).

Parameters: width – the maximum width, in pixels, available for the caption text.

GetBitmap(width, height) [source]

Returns the associated bitmap.

Parameters:
  • width – the associated bitmap width;
  • height – the associated bitmap height.

GetCaption(line) [source]

Returns the caption associated to a thumbnail.

Parameters: line – the caption line we wish to retrieve (useful for multilines caption strings).

GetCaptionLinesCount(width) [source]

Returns the number of lines for the caption.

Parameters: width – the maximum width, in pixels, available for the caption text.

GetCreationDate() [source]

Returns the file last modification date associated to a thumbnail.

GetFileName() [source]

Returns the file name associated with this thumbnail.

GetFileSize() [source]

Returns the file size associated to a thumbnail.

GetFullFileName() [source]

Returns the full filename of the thumbnail.

GetId() [source]

Returns the thumbnail identifier.

GetImage() [source]

Returns the thumbnail image.

GetOriginalImage() [source]

Returns the bitmap associated to a thumbnail, as a file name.

GetOriginalSize() [source]

Returns a tuple containing the original image width and height, in pixels.

GetRotatedImage() [source]

Returns a rotated image.

GetRotation() [source]

Returns the thumbnail rotation, in radians.

SetBitmap(bmp) [source]

Sets the thumbnail bitmap.

Parameters: bmp – a wx.Bitmap object.

SetCaption(caption='') [source]

Sets the thumbnail caption.

Parameters: caption – the thumbnail caption string.

SetFileName(filename) [source]

Sets the file name associated with this thumbnail.

Parameters: filename – the file containing the image.

SetId(id=-1) [source]

Sets the thumbnail identifier.

Parameters: id – an integer specifying the thumbnail identifier.

SetImage(image) [source]

Sets the thumbnail image.

Parameters: image – a wx.Image object.

SetRotatedImage(image) [source]

Sets the image as rotated (fast).

Parameters: image – the rotated image, an instance of wx.Image.

SetRotation(angle=0) [source]

Sets the thumbnail rotation.

Parameters: angle – the thumbnail rotation, in radians.

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • infobar
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • thumbnailctrl »
  • Thumb


ThumbnailCtrl

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • thumbnailctrl »
  • ThumbnailCtrl

ThumbnailCtrl

ThumbnailCtrl is a widget that can be used to display a series of images in a “thumbnail” format.

hierarchy Inheritance Diagram

Inheritance diagram for: ThumbnailCtrl

Inheritance diagram of ThumbnailCtrl

appearance Control Appearance

ThumbnailCtrl

Methods Summary

__init__ | Default class constructor.
GetShowComboBox | Returns whether the folder combobox is shown.
OnComboBox | Handles the wx.EVT_COMBOBOX for the folder combobox.
RecreateComboBox | Recreates the folder combobox every time a new directory is explored.
ShowComboBox | Shows/Hide the top folder wx.ComboBox.

API Class API

class ThumbnailCtrl(wx.Panel) [source]

ThumbnailCtrl is a widget that can be used to display a series of images in a “thumbnail” format.

__init__(parent, id=wx.ID_ANY, pos=wx.DefaultPosition, size=wx.DefaultSize, thumboutline=THUMB_OUTLINE_IMAGE, thumbfilter=THUMB_FILTER_IMAGES, imagehandler=PILImageHandler) [source]

Default class constructor.

Parameters:
  • parent – parent window. Must not be None;
  • id – window identifier. A value of -1 indicates a default value;
  • pos – the control position. A value of (-1, -1) indicates a default position, chosen by either the windowing system or wxPython, depending on platform;
  • size – the control size. A value of (-1, -1) indicates a default size, chosen by either the windowing system or wxPython, depending on platform;
  • thumboutline – outline style for ThumbnailCtrl, which may be:

    Outline Flag | Value | Description
    THUMB_OUTLINE_NONE | 0 | No outline is drawn on selection
    THUMB_OUTLINE_FULL | 1 | Full outline (image+caption) is drawn on selection
    THUMB_OUTLINE_RECT | 2 | Only thumbnail bounding rectangle is drawn on selection (default)
    THUMB_OUTLINE_IMAGE | 4 | Only image bounding rectangle is drawn.
  • thumbfilter – filter for image/video/audio files. Actually only THUMB_FILTER_IMAGES is implemented;
  • imagehandler – can be PILImageHandler if PIL is installed (faster), or NativeImageHandler which only uses wxPython image methods.

GetShowComboBox() [source]

Returns whether the folder combobox is shown.

OnComboBox(event) [source]

Handles the wx.EVT_COMBOBOX for the folder combobox.

Parameters: event – a wx.CommandEvent event to be processed.

RecreateComboBox(newdir) [source]

Recreates the folder combobox every time a new directory is explored.

Parameters: newdir – the new folder to be explored.

ShowComboBox(show=True) [source]

Shows/Hide the top folder wx.ComboBox.

Parameters: show – True to show the combobox, False otherwise.

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • infobar
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • thumbnailctrl »
  • ThumbnailCtrl


ThumbnailEvent

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • thumbnailctrl »
  • ThumbnailEvent

ThumbnailEvent

This class is used to send events when a thumbnail is hovered, selected, double-clicked or when its caption has been changed.

hierarchy Inheritance Diagram

Inheritance diagram for: ThumbnailEvent

Inheritance diagram of ThumbnailEvent

Methods Summary

__init__ Default class constructor.

API Class API

class ThumbnailEvent(wx.PyCommandEvent) [source]

This class is used to send events when a thumbnail is hovered, selected, double-clicked or when its caption has been changed.

__init__(evtType, evtId=-1) [source]

Default class constructor.

Parameters:
  • evtType – the event type;
  • evtId – the event identifier.

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • infobar
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • thumbnailctrl »
  • ThumbnailEvent


SVN Revision 68362 For thumbnailctrl

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • thumbnailctrl »
  • SVN Revision 68362 For thumbnailctrl

svn SVN Revision 68362 For thumbnailctrl

This file contains the SVN revision history for thumbnailctrl, at revision 68362.

Available information include commit date, the name of the committer, the file size, the SVN log messages and a diff from the previous version (if available).

File Information

  • Commit Date: 17-Oct-2008 21:01:24 UTC
  • Committer: AG
  • File Size: 84973 byte(s)

Log Messages

The following log message was entered by the committer:

  • All of AGW: change my work e-mail from KPO to Maersk Oil (silly commit)

Diff To Previous Version (65530)

Version SVN diff:

--- wxPython/3rdParty/AGW/agw/thumbnailctrl.py      2010/09/12 12:20:09     65530
+++ wxPython/3rdParty/AGW/agw/thumbnailctrl.py      2011/07/24 21:36:47     68362
@@ -22,7 +22,7 @@
# Write To Me At:
#
# andrea.gavana@gmail.com
-# gavana@kpo.kz
+# andrea.gavana@maerskoil.com
#
# Or, Obviously, To The wxPython Mailing List!!!
#

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • thumbnailctrl »
  • SVN Revision 68362 For thumbnailctrl


SVN Revision 68881 For thumbnailctrl

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • thumbnailctrl »
  • SVN Revision 68881 For thumbnailctrl

svn SVN Revision 68881 For thumbnailctrl

This file contains the SVN revision history for thumbnailctrl, at revision 68881.

Available information include commit date, the name of the committer, the file size, the SVN log messages and a diff from the previous version (if available).

File Information

  • Commit Date: 17-Oct-2008 19:15:31 UTC
  • Committer: AG
  • File Size: 85481 byte(s)

Log Messages

The following log message was entered by the committer:

  • AGW: General overhaul of the documentation, much improved. All the widgets have their own sample usage in the docs as well;

  • FlatNotebook: Added the FNB_NAV_BUTTONS_WHEN_NEEDED style, which hides the navigation left/right arrows if all tabs fit;

  • RibbonBar: - Added the EVT_RIBBONBAR_TAB_LEFT_DCLICK event, which generates a special event

    when a ribbon bar tab is double-clicked;

    • Added support for toggle buttons;
    • Improved support for ribbon panel sizers: panels with sizers should now automatically minimise at small sizes, and behave properly when popping up from a minimised state;
    • Added tooltips via SetToolTip for those buttons which have the help_string attribute set.

  • XLSGrid: a new widget was added to AGW, termed XLSGrid. It’s based on wx.grid.Grid and can be used to faithfully reproduce the appearance of a Microsoft Excel spreadsheets.

Diff To Previous Version (68362)

Version SVN diff:

--- wxPython/3rdParty/AGW/agw/thumbnailctrl.py      2011/07/24 21:36:47     68362
+++ wxPython/3rdParty/AGW/agw/thumbnailctrl.py      2011/08/25 16:40:17     68881
@@ -3,7 +3,7 @@
# Python Code By:
#
# Andrea Gavana And Peter Damoc, @ 12 Dec 2005
-# Latest Revision: 12 Sep 2010, 10.00 GMT
+# Latest Revision: 17 Aug 2011, 15.00 GMT
#
#
# TODO List/Caveats
@@ -32,22 +32,22 @@

"""
-Thumbnailctrl is a widget that can be used to display a series of images in
+L{ThumbnailCtrl} is a widget that can be used to display a series of images in
a "thumbnail" format.

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

-Thumbnailctrl is a widget that can be used to display a series of images in
+L{ThumbnailCtrl} is a widget that can be used to display a series of images in
a "thumbnail" format; it mimics, for example, the windows explorer behavior
when you select the "view thumbnails" option.
Basically, by specifying a folder that contains some image files, the files
in the folder are displayed as miniature versions of the actual images in
a `wx.ScrolledWindow`.

-The code is partly based on wxVillaLib, a wxWidgets implementation of this
-control. However, ThumbnailCtrl wouldn't have been so fast and complete
+The code is partly based on `wxVillaLib`, a wxWidgets implementation of this
+control. However, L{ThumbnailCtrl} wouldn't have been so fast and complete
without the suggestions and hints from Peter Damoc. So, if he accepts the
mention, this control is his as much as mine.

@@ -55,17 +55,46 @@
Usage
=====

-Sample construction::
+Usage example::
+
+    import os
+
+    import wx
+    import wx.lib.agw.thumbnailctrl as TC
+
+    class MyFrame(wx.Frame):
+
+        def __init__(self, parent):
+
+            wx.Frame.__init__(self, parent, -1, "ThumbnailCtrl Demo")
+
+            panel = wx.Panel(self)
+
+            sizer = wx.BoxSizer(wx.VERTICAL)
+
+            thumbnail = TC.ThumbnailCtrl(panel, imagehandler=TC.NativeImageHandler)
+            sizer.Add(thumbnail, 1, wx.EXPAND | wx.ALL, 10)
+
+            thumbnail.ShowDir(os.getcwd())
+            panel.SetSizer(sizer)
+
+
+    # our normal wxApp-derived class, as usual
+
+    app = wx.PySimpleApp()
+
+    frame = MyFrame(None)
+    app.SetTopWindow(frame)
+    frame.Show()
+
+    app.MainLoop()

-    ThumbnailCtrl.__init__(self, parent, id=wx.ID_ANY, pos=wx.DefaultPosition,
-                           size=wx.DefaultSize, thumboutline=THUMB_OUTLINE_RECT,
-                           thumbfilter=THUMB_FILTER_IMAGES)

Methods and Settings
====================

-With ThumbnailCtrl you can:
+With L{ThumbnailCtrl} you can:

- Create different thumbnail outlines (none, images only, full, etc...);
- Highlight thumbnails on mouse hovering;
@@ -80,10 +109,10 @@
c) ``a`` key rotates 180 degrees.

- Delete files/thumbnails (via the ``del`` key);
-- Drag and drop thumbnails from ThumbnailCtrl to whatever application you want;
+- Drag and drop thumbnails from L{ThumbnailCtrl} to whatever application you want;
- Use local (when at least one thumbnail is selected) or global (no need for
thumbnail selection) popup menus;
-- Show/hide a `wx.ComboBox` at the top of ThumbnailCtrl: this combobox contains
+- Show/hide a `wx.ComboBox` at the top of L{ThumbnailCtrl}: this combobox contains
working directory information and it has history entries;
- possibility to show tooltips on thumbnails, which display file information
(like file name, size, last modification date and thumbnail size).
@@ -118,9 +147,9 @@
License And Version
===================

-ThumbnailCtrl is distributed under the wxPython license.
+L{ThumbnailCtrl} is distributed under the wxPython license.

-Latest revision: Andrea Gavana @ 12 Sep 2010, 10.00 GMT
+Latest revision: Andrea Gavana @ 17 Aug 2011, 15.00 GMT

Version 0.9

@@ -869,7 +898,7 @@

class ThumbnailCtrl(wx.Panel):
"""
-    ThumbnailCtrl is a widget that can be used to display a series of images in
+    L{ThumbnailCtrl} is a widget that can be used to display a series of images in
a "thumbnail" format.
"""

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • thumbnailctrl »
  • SVN Revision 68881 For thumbnailctrl


ToasterBox

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • toasterbox »
  • ToasterBox

ToasterBox

ToasterBox is a cross-platform widget to make the creation of MSN style “toaster” popups easier.

hierarchy Inheritance Diagram

Inheritance diagram for: ToasterBox

Inheritance diagram of ToasterBox

appearance Control Appearance

ToasterBox

Methods Summary

__init__ | Default class constructor.
AddPanel | Adds a panel to the ToasterBox.
CenterOnParent | Centres the window on its parent (if any).
CenterOnScreen | Centres the ToasterBox on screen.
CentreOnParent | Centres the window on its parent (if any).
CentreOnScreen | Centres the ToasterBox on screen.
CleanList | Cleans the window list, erasing the stack of ToasterBox objects.
GetToasterBoxWindow | Returns the ToasterBox frame.
GetUseFocus | Returns whether ToasterBox will steal the focus from the parent application.
MoveAbove | If a ToasterBox already exists, move the new one above the existing one.
Notify | It’s time to hide a ToasterBox.
OnMoveTimer | Handles the wx.EVT_TIMER event for ToasterBox, moving the new window
Play | Creates the ToasterBoxWindow, that does all the job.
SetPopupBackgroundColour | Sets the ToasterBox background colour.
SetPopupBitmap | Sets the ToasterBox background image.
SetPopupPauseTime | Sets the time after which the ToasterBox is destroyed (linger).
SetPopupPosition | Sets the ToasterBox position on screen.
SetPopupPositionByInt | Sets the ToasterBox position on screen, at one of the screen corners.
SetPopupScrollSpeed | Sets the ToasterBox scroll speed.
SetPopupSize | Sets the ToasterBox size.
SetPopupText | Sets the ToasterBox text label.
SetPopupTextColour | Sets the ToasterBox foreground colour.
SetPopupTextFont | Sets the ToasterBox text font.
SetTitle | Sets the ToasterBox title if it was created with TB_CAPTION window style.
SetUseFocus | If focus is True, Instructs ToasterBox to steal the focus from the

API Class API

class ToasterBox(wx.Timer) [source]

ToasterBox is a cross-platform widget to make the creation of MSN style “toaster” popups easier.

__init__(parent, tbstyle=TB_SIMPLE, windowstyle=TB_DEFAULT_STYLE, closingstyle=TB_ONTIME, scrollType=TB_SCR_TYPE_DU) [source]

Default class constructor.

Parameters:
  • parent – the window parent;
  • tbstyle – the ToasterBox main style. Can be one of the following bits:

    ToasterBox Style | Value | Description
    TB_SIMPLE | 0x1 | A simple ToasterBox, with background image and text customization can be created
    TB_COMPLEX | 0x2 | ToasterBoxes with different degree of complexity can be created. You can add as many controls as you want, provided that you call the AddPanel method and pass to it a dummy frame and a wx.Panel.
  • windowstyle – this parameter influences the visual appearance of ToasterBox, and can be one of the following styles:

    Window Style | Hex Value | Description
    TB_DEFAULT_STYLE | 0x2008002 | Default window style for ToasterBox, with no caption nor close box.
    TB_CAPTION | 0x22009806 | ToasterBox will have a caption, with the possibility to set a title for the ToasterBox frame, and a close box.
  • closingstyle – the closing style for ToasterBox. Can be one of the following bits:

    Closing Styles | Hex Value | Description
    TB_ONTIME | 0x1 | ToasterBox will close after a specified amount of time.
    TB_ONCLICK | 0x2 | ToasterBox can be closed by clicking anywhere on the ToasterBox frame.
  • scrollType – the scrolling direction for ToasterBox. Can be one of the following bits:

    Scroll Styles | Hex Value | Description
    TB_SCR_TYPE_UD | 0x1 | ToasterBox will scroll from up to down
    TB_SCR_TYPE_DU | 0x2 | ToasterBox will scroll from down to up
    TB_SCR_TYPE_FADE | 0x4 | ToasterBox will fade in/out (without scrolling).

AddPanel(panel) [source]

Adds a panel to the ToasterBox.

Parameters: panel – an instance of wx.Window.

Note

Use this method only for a ToasterBox created with the TB_COMPLEX style.

CenterOnParent(direction=wx.BOTH) [source]

Centres the window on its parent (if any). If the ToasterBox parent is None, it calls CenterOnScreen.

Parameters: direction – specifies the direction for the centering. May be wx.HORIZONTAL, wx.VERTICAL or wx.BOTH.

Note

This methods provides for a way to center ToasterBox over their parents instead of the entire screen. If there is no parent, then behaviour is the same as CenterOnScreen.

See also

CenterOnScreen.

CenterOnScreen(direction=wx.BOTH) [source]

Centres the ToasterBox on screen.

Parameters: direction – specifies the direction for the centering. May be wx.HORIZONTAL, wx.VERTICAL or wx.BOTH.

See also

CenterOnParent.

CentreOnParent(direction=12)

Centres the window on its parent (if any). If the ToasterBox parent is None, it calls CenterOnScreen.

Parameters: direction – specifies the direction for the centering. May be wx.HORIZONTAL, wx.VERTICAL or wx.BOTH.

Note

This methods provides for a way to center ToasterBox over their parents instead of the entire screen. If there is no parent, then behaviour is the same as CenterOnScreen.

See also

CenterOnScreen.

CentreOnScreen(direction=12)

Centres the ToasterBox on screen.

Parameters: direction – specifies the direction for the centering. May be wx.HORIZONTAL, wx.VERTICAL or wx.BOTH.

See also

CenterOnParent.

CleanList() [source]

Cleans the window list, erasing the stack of ToasterBox objects.

GetToasterBoxWindow() [source]

Returns the ToasterBox frame.

GetUseFocus() [source]

Returns whether ToasterBox will steal the focus from the parent application.

MoveAbove(tb) [source]

If a ToasterBox already exists, move the new one above the existing one.

Parameters: tb – another instance of ToasterBox.

Notify() [source]

It’s time to hide a ToasterBox.

OnMoveTimer(event) [source]

Handles the wx.EVT_TIMER event for ToasterBox, moving the new window on top of the last one created.

Parameters: event – a wx.TimerEvent event to be processed.

Play() [source]

Creates the ToasterBoxWindow, that does all the job.

SetPopupBackgroundColour(colour=None) [source]

Sets the ToasterBox background colour.

Parameters: colour – a valid wx.Colour object. If defaulted to None, then the background colour will be white.

Note

Use this method only for a ToasterBox created with the TB_SIMPLE style.

SetPopupBitmap(bitmap=None) [source]

Sets the ToasterBox background image.

Parameters: bitmap – a valid wx.Bitmap object or filename. If defaulted to None, then no background bitmap is used.

Note

Use this method only for a ToasterBox created with the TB_SIMPLE style.

SetPopupPauseTime(pausetime) [source]

Sets the time after which the ToasterBox is destroyed (linger).

Parameters: pausetime – the delay after which the control is destroyed, in seconds.

SetPopupPosition(pos) [source]

Sets the ToasterBox position on screen.

Parameters: pos – the widget position, an instance of wx.Point.

SetPopupPositionByInt(pos) [source]

Sets the ToasterBox position on screen, at one of the screen corners.

Parameters: pos – an integer specifying the screen corner, namely:

Corner Number | Position
0 | Top left screen corner
1 | Top right screen corner
2 | Bottom left screen corner
3 | Bottom right screen corner

SetPopupScrollSpeed(speed) [source]

Sets the ToasterBox scroll speed.

Parameters: speed – it is the pause time (in milliseconds) for every step in the ScrollUp method.

SetPopupSize(size) [source]

Sets the ToasterBox size.

Parameters: size – the new control size, an instance of wx.Size.

SetPopupText(text) [source]

Sets the ToasterBox text label.

Parameters: text – the widget label.

Note

Use this method only for a ToasterBox created with the TB_SIMPLE style.

SetPopupTextColour(colour=None) [source]

Sets the ToasterBox foreground colour.

Parameters: colour – a valid wx.Colour object. If defaulted to None, then the background colour will be black.

Note

Use this method only for a ToasterBox created with the TB_SIMPLE style.

SetPopupTextFont(font=None) [source]

Sets the ToasterBox text font.

Parameters: colour – a valid wx.Colour object. If defaulted to None, then a simple generic font will be generated.

Note

Use this method only for a ToasterBox created with the TB_SIMPLE style.

SetTitle(title) [source]

Sets the ToasterBox title if it was created with TB_CAPTION window style.

Parameters: title – the ToasterBox caption title.

SetUseFocus(focus) [source]

If focus is True, Instructs ToasterBox to steal the focus from the parent application, otherwise it returns the focus to the original owner.

Parameters: focus – True to set the focus on ToasterBox, False to return it to the original owner.

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • infobar
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • toasterbox »
  • ToasterBox


ToasterBoxWindow

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • toasterbox »
  • ToasterBoxWindow

ToasterBoxWindow

This class does all the job, by handling background images, text properties and panel adding. Depending on the style you choose, ToasterBoxWindow will behave differently in order to handle widgets inside it.

hierarchy Inheritance Diagram

Inheritance diagram for: ToasterBoxWindow

Inheritance diagram of ToasterBoxWindow

Methods Summary

__init__ | Default class constructor.
AddPanel | Adds a panel to the ToasterBox.
AlphaCycle | Handles the wx.EVT_TIMER event for ToasterBoxWindow.
DrawText | Draws the text label for a ToasterBox with TB_SIMPLE style set.
GetPopupText | Returns the ToasterBox text.
MakeWindowTransparent | Makes the ToasterBoxWindow window transparent.
NotifyTimer | Hides gradually the ToasterBoxWindow.
OnClose | Handles the wx.EVT_CLOSE event for ToasterBoxWindow.
OnMouseDown | Handles the wx.EVT_LEFT_DOWN event for ToasterBoxWindow.
OnPaint | Handles the wx.EVT_PAINT event for ToasterBoxWindow.
OnScrollTimer | Handles the wx.EVT_TIMER event for ToasterBoxWindow scrolling up/down.
Play | Creates the ToasterBoxWindow, that does all the job.
ScrollDown | Scrolls the ToasterBox down, which means gradually hiding it.
ScrollUp | Scrolls the ToasterBox up, which means gradually showing it.
SetPopupBackgroundColour | Sets the ToasterBox background colour.
SetPopupBitmap | Sets the ToasterBox background image.
SetPopupPauseTime | Sets the time after which the ToasterBox is destroyed (linger).
SetPopupPosition | Sets the ToasterBox position on screen.
SetPopupPositionByInt | Sets the ToasterBox position on screen, at one of the screen corners.
SetPopupScrollSpeed | Sets the ToasterBox scroll speed.
SetPopupSize | Sets the ToasterBox size.
SetPopupText | Sets the ToasterBox text label.
SetPopupTextColour | Sets the ToasterBox foreground colour.
SetPopupTextFont | Sets the ToasterBox text font.
SetUseFocus | If focus is True, Instructs ToasterBoxWindow to steal the focus from the
SetupPositions | Sets up the position, size and scrolling step for ToasterBoxWindow.
TearDown | Scrolls the ToasterBox down, which means gradually hiding it.
TearUp | Scrolls the ToasterBox up, which means gradually showing it.
_getTextCoords | Draw the user specified text.

API Class API

class ToasterBoxWindow(wx.Frame) [source]

This class does all the job, by handling background images, text properties and panel adding. Depending on the style you choose, ToasterBoxWindow will behave differently in order to handle widgets inside it.

__init__(parent, parent2, tbstyle, windowstyle, closingstyle, scrollType=TB_SCR_TYPE_DU) [source]

Default class constructor. Used internally. Do not call directly this class in your application!

Parameters:
  • parent – the window parent;
  • parent2 – the ToasterBox calling this window;
  • tbstyle – the ToasterBoxWindow main style. Can be one of the following bits:

    ToasterBox Style | Value | Description
    TB_SIMPLE | 0x1 | A simple ToasterBox, with background image and text customization can be created
    TB_COMPLEX | 0x2 | ToasterBoxes with different degree of complexity can be created. You can add as many controls as you want, provided that you call the AddPanel method and pass to it a dummy frame and a wx.Panel.
  • windowstyle – this parameter influences the visual appearance of ToasterBoxWindow, and can be one of the following styles:

    Window Style | Hex Value | Description
    TB_DEFAULT_STYLE | 0x2008002 | Default window style for ToasterBox, with no caption nor close box.
    TB_CAPTION | 0x22009806 | ToasterBox will have a caption, with the possibility to set a title for the ToasterBox frame, and a close box.
  • closingstyle – the closing style for ToasterBoxWindow. Can be one of the following bits:

    Closing Styles | Hex Value | Description
    TB_ONTIME | 0x1 | ToasterBox will close after a specified amount of time.
    TB_ONCLICK | 0x2 | ToasterBox can be closed by clicking anywhere on the ToasterBox frame.
  • scrollType – the scrolling direction for ToasterBoxWindow. Can be one of the following bits:

    Scroll Styles | Hex Value | Description
    TB_SCR_TYPE_UD | 0x1 | ToasterBox will scroll from up to down
    TB_SCR_TYPE_DU | 0x2 | ToasterBox will scroll from down to up
    TB_SCR_TYPE_FADE | 0x4 | ToasterBox will fade in/out (without scrolling).

AddPanel(panel) [source]

Adds a panel to the ToasterBox.

Parameters: panel – an instance of wx.Window.

Note

Use this method only for a ToasterBox created with the TB_COMPLEX style.

AlphaCycle(event) [source]

Handles the wx.EVT_TIMER event for ToasterBoxWindow.

Parameters: event – a wx.TimerEvent event to be processed.

DrawText(dc=None) [source]

Draws the text label for a ToasterBox with TB_SIMPLE style set.

Parameters: dc – an instance of wx.DC. If defaulted to None, a wx.ClientDC will be created on the fly.

GetPopupText() [source]

Returns the ToasterBox text.

Note

Use this method only for a ToasterBox created with the TB_SIMPLE style.

MakeWindowTransparent(amount) [source]

Makes the ToasterBoxWindow window transparent.

Parameters: amount – the alpha channel value.

NotifyTimer(event) [source]

Hides gradually the ToasterBoxWindow.

OnClose(event) [source]

Handles the wx.EVT_CLOSE event for ToasterBoxWindow.

Parameters: event – a wx.CloseEvent event to be processed.

OnMouseDown(event) [source]

Handles the wx.EVT_LEFT_DOWN event for ToasterBoxWindow.

Parameters: event – a wx.MouseEvent event to be processed.

OnPaint(event) [source]

Handles the wx.EVT_PAINT event for ToasterBoxWindow.

Parameters: event – a wx.PaintEvent event to be processed.

Note

This event is handled and processed only if the style TB_SIMPLE is given to ToasterBox.

OnScrollTimer(event) [source]

Handles the wx.EVT_TIMER event for ToasterBoxWindow scrolling up/down.

Parameters: event – a wx.TimerEvent event to be processed.

Play() [source]

Creates the ToasterBoxWindow, that does all the job.

ScrollDown() [source]

Scrolls the ToasterBox down, which means gradually hiding it.

ScrollUp() [source]

Scrolls the ToasterBox up, which means gradually showing it.

SetPopupBackgroundColour(colour) [source]

Sets the ToasterBox background colour.

Parameters: colour – a valid wx.Colour object. If defaulted to None, then the background colour will be white.

Note

Use this method only for a ToasterBox created with the TB_SIMPLE style.

SetPopupBitmap(bitmap=None) [source]

Sets the ToasterBox background image.

Parameters: bitmap – a valid wx.Bitmap object. If defaulted to None, then no background bitmap is used.

Note

Use this method only for a ToasterBox created with the TB_SIMPLE style.

SetPopupPauseTime(pausetime) [source]

Sets the time after which the ToasterBox is destroyed (linger).

Parameters: pausetime – the delay after which the control is destroyed, in seconds.

SetPopupPosition(pos) [source]

Sets the ToasterBox position on screen.

Parameters: pos – the widget position, an instance of wx.Point.

SetPopupPositionByInt(pos) [source]

Sets the ToasterBox position on screen, at one of the screen corners.

Parameters: pos – an integer specifying the screen corner, namely:

Corner Number | Position
0 | Top left screen corner
1 | Top right screen corner
2 | Bottom left screen corner
3 | Bottom right screen corner

SetPopupScrollSpeed(speed) [source]

Sets the ToasterBox scroll speed.

Parameters: speed – it is the pause time (in milliseconds) for every step in the ScrollUp method.

SetPopupSize(size) [source]

Sets the ToasterBox size.

Parameters: size – the new control size, an instance of wx.Size.

SetPopupText(text) [source]

Sets the ToasterBox text label.

Parameters: text – the widget label.

Note

Use this method only for a ToasterBox created with the TB_SIMPLE style.

SetPopupTextColour(colour) [source]

Sets the ToasterBox foreground colour.

Parameters: colour – a valid wx.Colour object. If defaulted to None, then the background colour will be black.

Note

Use this method only for a ToasterBox created with the TB_SIMPLE style.

SetPopupTextFont(font) [source]

Sets the ToasterBox text font.

Parameters: colour – a valid wx.Colour object. If defaulted to None, then a simple generic font will be generated.

Note

Use this method only for a ToasterBox created with the TB_SIMPLE style.

SetUseFocus(focus, originalfocus) [source]

If focus is True, Instructs ToasterBoxWindow to steal the focus from the parent application, otherwise it returns the focus to the original owner.

Parameters:
  • focus – True to set the focus on ToasterBoxWindow, False to return it to the original owner;
  • originalfocus – an instance of wx.Window, representing a pointer to the window which originally had the focus

SetupPositions() [source]

Sets up the position, size and scrolling step for ToasterBoxWindow.

TearDown() [source]

Scrolls the ToasterBox down, which means gradually hiding it.

TearUp() [source]

Scrolls the ToasterBox up, which means gradually showing it.

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • infobar
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • toasterbox »
  • ToasterBoxWindow


SVN Revision 68342 For toasterbox

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • toasterbox »
  • SVN Revision 68342 For toasterbox

svn SVN Revision 68342 For toasterbox

This file contains the SVN revision history for toasterbox, at revision 68342.

Available information include commit date, the name of the committer, the file size, the SVN log messages and a diff from the previous version (if available).

File Information

  • Commit Date: 13-Jan-2009 17:09:05 UTC
  • Committer: AG
  • File Size: 43528 byte(s)

Log Messages

The following log message was entered by the committer:

  • ToasterBox: fixed ticket #13258. It appears wx.FRAME_TOOL_WINDOW doesn’t work as expected on Windows 7
  • AuiNotebook: fixed tickets #12800 and #12919

Diff To Previous Version (66289)

Version SVN diff:

--- wxPython/3rdParty/AGW/agw/toasterbox.py 2010/11/28 15:31:03     66289
+++ wxPython/3rdParty/AGW/agw/toasterbox.py 2011/07/23 19:06:24     68342
@@ -108,7 +108,7 @@
""" to it a dummy frame and a wx.Panel. See the demo for details. """
TB_DEFAULT_STYLE = wx.SIMPLE_BORDER | wx.STAY_ON_TOP | wx.FRAME_NO_TASKBAR
""" Default window style for `ToasterBox`, with no caption nor close box. """
-TB_CAPTION = TB_DEFAULT_STYLE | wx.CAPTION | wx.SYSTEM_MENU | wx.CLOSE_BOX | wx.FRAME_TOOL_WINDOW
+TB_CAPTION = TB_DEFAULT_STYLE | wx.CAPTION | wx.SYSTEM_MENU | wx.CLOSE_BOX | wx.FRAME_NO_TASKBAR
""" `ToasterBox` will have a caption, with the possibility to set a title """ \
""" for the `ToasterBox` frame, and a close box. """
TB_ONTIME = 1
@@ -957,8 +957,9 @@
def NotifyTimer(self, event):
""" Hides gradually the L{ToasterBoxWindow}. """

-        self.showtime.Stop()
-        del self.showtime
+        if self._scrollType != TB_SCR_TYPE_FADE:
+            self.showtime.Stop()
+            del self.showtime

self._direction = wx.DOWN
self.SetupPositions()

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • toasterbox »
  • SVN Revision 68342 For toasterbox


SVN Revision 68881 For toasterbox

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • toasterbox »
  • SVN Revision 68881 For toasterbox

svn SVN Revision 68881 For toasterbox

This file contains the SVN revision history for toasterbox, at revision 68881.

Available information include commit date, the name of the committer, the file size, the SVN log messages and a diff from the previous version (if available).

File Information

  • Commit Date: 17-Oct-2008 19:15:31 UTC
  • Committer: AG
  • File Size: 44418 byte(s)

Log Messages

The following log message was entered by the committer:

  • AGW: General overhaul of the documentation, much improved. All the widgets have their own sample usage in the docs as well;

  • FlatNotebook: Added the FNB_NAV_BUTTONS_WHEN_NEEDED style, which hides the navigation left/right arrows if all tabs fit;

  • RibbonBar: - Added the EVT_RIBBONBAR_TAB_LEFT_DCLICK event, which generates a special event

    when a ribbon bar tab is double-clicked;

    • Added support for toggle buttons;
    • Improved support for ribbon panel sizers: panels with sizers should now automatically minimise at small sizes, and behave properly when popping up from a minimised state;
    • Added tooltips via SetToolTip for those buttons which have the help_string attribute set.

  • XLSGrid: a new widget was added to AGW, termed XLSGrid. It’s based on wx.grid.Grid and can be used to faithfully reproduce the appearance of a Microsoft Excel spreadsheets.

Diff To Previous Version (68362)

Version SVN diff:

--- wxPython/3rdParty/AGW/agw/toasterbox.py 2011/07/24 21:36:47     68362
+++ wxPython/3rdParty/AGW/agw/toasterbox.py 2011/08/25 16:40:17     68881
@@ -3,7 +3,7 @@
# Ported And Enhanced From wxWidgets Contribution (Aj Bommarito) By:
#
# Andrea Gavana, @ 16 September 2005
-# Latest Revision: 22 Jul 2011, 21.00 GMT
+# Latest Revision: 17 Aug 2011, 15.00 GMT
#
#
# TODO/Caveats List
@@ -49,6 +49,48 @@
speed of ToasterBox.

+Usage
+=====
+
+Usage example::
+
+    import wx
+    import wx.lib.agw.toasterbox as TB
+
+    class MyFrame(wx.Frame):
+
+        def __init__(self, parent):
+
+            wx.Frame.__init__(self, parent, -1, "ToasterBox Demo")
+
+            toaster = TB.ToasterBox(self, tbstyle=TB.TB_COMPLEX)
+            toaster.SetPopupPauseTime(3000)
+
+            tbpanel = toaster.GetToasterBoxWindow()
+            panel = wx.Panel(tbpanel, -1)
+            sizer = wx.BoxSizer(wx.VERTICAL)
+
+            button = wx.Button(panel, wx.ID_ANY, "Simple button")
+            sizer.Add(button, 0, wx.EXPAND)
+
+            panel.SetSizer(sizer)
+            toaster.AddPanel(panel)
+
+            wx.CallLater(1000, toaster.Play)
+
+
+    # our normal wxApp-derived class, as usual
+
+    app = wx.PySimpleApp()
+
+    frame = MyFrame(None)
+    app.SetTopWindow(frame)
+    frame.Show()
+
+    app.MainLoop()
+
+
+
Supported Platforms
===================

@@ -87,7 +129,7 @@

ToasterBox is distributed under the wxPython license.

-Latest revision: Andrea Gavana @ 22 Jul 2011, 21.00 GMT
+Latest revision: Andrea Gavana @ 17 Aug 2011, 15.00 GMT

Version 0.3

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • toasterbox »
  • SVN Revision 68881 For toasterbox


SVN Revision 68881 For toolbar

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • ribbon library »
  • ribbon.toolbar »
  • SVN Revision 68881 For toolbar

svn SVN Revision 68881 For toolbar

This file contains the SVN revision history for toolbar, at revision 68881.

Available information include commit date, the name of the committer, the file size, the SVN log messages and a diff from the previous version (if available).

File Information

  • Commit Date: 18-Nov-2009 22:19:25 UTC
  • Committer: AG
  • File Size: 23925 byte(s)

Log Messages

The following log message was entered by the committer:

  • AGW: General overhaul of the documentation, much improved. All the widgets have their own sample usage in the docs as well;

  • FlatNotebook: Added the FNB_NAV_BUTTONS_WHEN_NEEDED style, which hides the navigation left/right arrows if all tabs fit;

  • RibbonBar: - Added the EVT_RIBBONBAR_TAB_LEFT_DCLICK event, which generates a special event

    when a ribbon bar tab is double-clicked;

    • Added support for toggle buttons;
    • Improved support for ribbon panel sizers: panels with sizers should now automatically minimise at small sizes, and behave properly when popping up from a minimised state;
    • Added tooltips via SetToolTip for those buttons which have the help_string attribute set.

  • XLSGrid: a new widget was added to AGW, termed XLSGrid. It’s based on wx.grid.Grid and can be used to faithfully reproduce the appearance of a Microsoft Excel spreadsheets.

Diff To Previous Version (65529)

Version SVN diff:

--- wxPython/3rdParty/AGW/agw/ribbon/toolbar.py     2010/09/12 11:58:40     65529
+++ wxPython/3rdParty/AGW/agw/ribbon/toolbar.py     2011/08/25 16:40:17     68881
@@ -588,6 +588,11 @@
new_hover = tool
break
break
+
+        if new_hover and new_hover != self._hover_tool:
+            self.SetToolTipString(new_hover.help_string)
+        elif self.GetToolTip() and new_hover != self._hover_tool:
+            self.SetToolTipString("")

if new_hover != self._hover_tool:
if self._hover_tool:
@@ -658,10 +663,13 @@
notification.SetBar(self)
self.ProcessEvent(notification)

-            self._active_tool.state &= ~RIBBON_TOOLBAR_TOOL_ACTIVE_MASK
-            self._active_tool = None
-            self.Refresh(False)
-
+            # Notice that m_active_tool could have been reset by the event handler
+            # above so we need to test it again.
+            if self._active_tool:
+                self._active_tool.state &= ~RIBBON_TOOLBAR_TOOL_ACTIVE_MASK
+                self._active_tool = None
+                self.Refresh(False)
+

def OnMouseEnter(self, event):

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • ribbon library »
  • ribbon.toolbar »
  • SVN Revision 68881 For toolbar


ultimatelistctrl functions

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • ultimatelistctrl »
  • ultimatelistctrl functions

ultimatelistctrl functions

This is the description of standalone Python functions in the ultimatelistctrl module.

Functions Summary

CheckVariableRowHeight | Checks whether a text contains multiline strings and if the listCtrl window
CreateListItem | Creates a new instance of UltimateListItem.
GetdragcursorBitmap | Returns the drag and drop cursor image as a wx.Bitmap.
GetdragcursorData | Returns the drag and drop cursor image as a decompressed stream of characters.
GetdragcursorImage | Returns the drag and drop cursor image as a wx.Image.
MakeDisabledBitmap | Creates a disabled-looking bitmap starting from the input one.
to_list | Converts the input data into a Python list.

API Functions API

CheckVariableRowHeight(listCtrl, text) [source]

Checks whether a text contains multiline strings and if the listCtrl window style is compatible with multiline strings.

Parameters:
  • listCtrl – an instance of UltimateListCtrl;
  • text – the text to analyze.

CreateListItem(itemOrId, col) [source]

Creates a new instance of UltimateListItem.

Parameters:
  • itemOrId – can be an instance of UltimateListItem or an integer;
  • col – the item column.

GetdragcursorBitmap() [source]

Returns the drag and drop cursor image as a wx.Bitmap.

GetdragcursorData() [source]

Returns the drag and drop cursor image as a decompressed stream of characters.

GetdragcursorImage() [source]

Returns the drag and drop cursor image as a wx.Image.

MakeDisabledBitmap(original) [source]

Creates a disabled-looking bitmap starting from the input one.

Parameters: original – an instance of wx.Bitmap to be greyed-out.

to_list(input) [source]

Converts the input data into a Python list.

Parameters: input – can be an integer or a Python list (in which case nothing will be done to input.

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • infobar
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • ultimatelistctrl »
  • ultimatelistctrl functions


ColWidthInfo

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • ultimatelistctrl »
  • ColWidthInfo

ColWidthInfo

A simple class which holds information about UltimateListCtrl columns.

hierarchy Inheritance Diagram

Inheritance diagram for: ColWidthInfo

Inheritance diagram of ColWidthInfo

Methods Summary

__init__ Default class constructor

API Class API

class ColWidthInfo(object) [source]

A simple class which holds information about UltimateListCtrl columns.

__init__(w=0, needsUpdate=True) [source]

Default class constructor

Parameters:
  • w – the initial width of the column;
  • needsUpdate – True if the column needs refreshing, False otherwise.

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • infobar
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • ultimatelistctrl »
  • ColWidthInfo


CommandListEvent

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • ultimatelistctrl »
  • CommandListEvent

CommandListEvent

A list event holds information about events associated with UltimateListCtrl objects.

hierarchy Inheritance Diagram

Inheritance diagram for: CommandListEvent

Inheritance diagram of CommandListEvent

subclasses Known Subclasses

  • ultimatelistctrl.UltimateListEvent

Methods Summary

__init__ | Default class constructor.
GetCacheFrom | Returns the first item which the list control advises us to cache.
GetCacheTo | Returns the last item (inclusive) which the list control advises us to cache.
GetColumn | Returns the column position: it is only used with COL events.
GetData | Returns the item data.
GetImage | Returns the item image.
GetIndex | Returns the item index.
GetItem | Returns the item itself.
GetKeyCode | Returns the key code if the event is a keypress event.
GetLabel | Returns the (new) item label for EVT_LIST_END_LABEL_EDIT event.
GetMask | Returns the item mask.
GetPoint | Returns the position of the mouse pointer if the event is a drag event.
GetText | Returns the item text.
IsEditCancelled | Returns True if it the label editing has been cancelled by the user
SetEditCanceled | Sets the item editing as cancelled/not cancelled.

API Class API

class CommandListEvent(wx.PyCommandEvent) [source]

A list event holds information about events associated with UltimateListCtrl objects.

__init__(commandTypeOrEvent=None, winid=0) [source]

Default class constructor. For internal use: do not call it in your code!

Parameters:
  • commandTypeOrEvent – the event type or another instance of wx.PyCommandEvent;
  • winid – the event identifier.

GetCacheFrom() [source]

Returns the first item which the list control advises us to cache.

Note

This method is meaningful for EVT_LIST_CACHE_HINT event only.

GetCacheTo() [source]

Returns the last item (inclusive) which the list control advises us to cache.

Note

This method is meaningful for EVT_LIST_CACHE_HINT event only.

GetColumn() [source]

Returns the column position: it is only used with COL events.

For the column dragging events, it is the column to the left of the divider being dragged, for the column click events it may be -1 if the user clicked in the list control header outside any column.

GetData() [source]

Returns the item data.

GetImage() [source]

Returns the item image.

GetIndex() [source]

Returns the item index.

GetItem() [source]

Returns the item itself.

GetKeyCode() [source]

Returns the key code if the event is a keypress event.

GetLabel() [source]

Returns the (new) item label for EVT_LIST_END_LABEL_EDIT event.

GetMask() [source]

Returns the item mask.

GetPoint() [source]

Returns the position of the mouse pointer if the event is a drag event.

GetText() [source]

Returns the item text.

IsEditCancelled() [source]

Returns True if it the label editing has been cancelled by the user (GetLabel returns an empty string in this case but it doesn’t allow the application to distinguish between really cancelling the edit and the admittedly rare case when the user wants to rename it to an empty string).

Note

This method only makes sense for EVT_LIST_END_LABEL_EDIT messages.

SetEditCanceled(editCancelled) [source]

Sets the item editing as cancelled/not cancelled.

Parameters: editCancelled – True to set the item editing as cancelled, False otherwise.

Note

This method only makes sense for EVT_LIST_END_LABEL_EDIT messages.

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • infobar
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • ultimatelistctrl »
  • CommandListEvent


GeometryInfo

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • ultimatelistctrl »
  • GeometryInfo

GeometryInfo

A simple class which holds items geometries for UltimateListCtrl not in report mode.

hierarchy Inheritance Diagram

Inheritance diagram for: GeometryInfo

Inheritance diagram of GeometryInfo

Methods Summary

__init__ | Default class constructor.
ExtendWidth | Extends all our rectangles to be centered inside the one of given width.

API Class API

class GeometryInfo(object) [source]

A simple class which holds items geometries for UltimateListCtrl not in report mode.

__init__() [source]

Default class constructor.

ExtendWidth(w) [source]

Extends all our rectangles to be centered inside the one of given width.

Parameters: w – the given width.

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • infobar
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • ultimatelistctrl »
  • GeometryInfo


PyImageList

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • ultimatelistctrl »
  • PyImageList

PyImageList

A PyImageList contains a list of images. Images can have masks for transparent drawing, and can be made from a variety of sources including bitmaps and icons.

PyImageList is used in conjunction with UltimateListCtrl.

Note

The main improvements that PyImageList introduces is the removal of the limitation of same-size images inside the image list. If you use the style IL_VARIABLE_SIZE then each image can have any size (in terms of width and height).

hierarchy Inheritance Diagram

Inheritance diagram for: PyImageList

Inheritance diagram of PyImageList

Methods Summary

__init__ | Default class constructor.
Add | Adds a new image or images using a bitmap.
AddIcon | Adds a new image using an icon.
AddWithColourMask | Adds a new image or images using a bitmap and a colour mask.
Draw | Draws a specified image onto a device context.
GetBitmap | Returns the bitmap corresponding to the given index, or wx.NullBitmap
GetIcon | Returns the icon corresponding to the given index, or wx.NullIcon
GetImageCount | Returns the number of images in the list.
GetSize | Retrieves the size of an image in the list.
Remove | Removes the image at the given position.
RemoveAll | Removes all the images in the list.
Replace | Replaces the existing image with the new bitmap.
ReplaceIcon | Replaces the existing image with the new icon.

API Class API

class PyImageList(object) [source]

A PyImageList contains a list of images. Images can have masks for transparent drawing, and can be made from a variety of sources including bitmaps and icons.

PyImageList is used in conjunction with UltimateListCtrl.

Note

The main improvements that PyImageList introduces is the removal of the limitation of same-size images inside the image list. If you use the style IL_VARIABLE_SIZE then each image can have any size (in terms of width and height).

__init__(width, height, mask=True, initialCount=1, style=IL_VARIABLE_SIZE) [source]

Default class constructor.

Parameters:
  • width – the width of the images in the image list, in pixels (unused if you specify the IL_VARIABLE_SIZE style;
  • height – the height of the images in the image list, in pixels (unused if you specify the IL_VARIABLE_SIZE style;
  • mask – True if masks should be created for all images (unused in PyImageList);
  • initialCount – the initial size of the list (unused in PyImageList);
  • style – can be one of the following bits:

    Style Flag | Value | Description
    IL_FIXED_SIZE | 0 | All the images in PyImageList have the same size (width, height)
    IL_VARIABLE_SIZE | 1 | Each image can have any size (in terms of width and height)

Add(bitmap) [source]

Adds a new image or images using a bitmap.

Parameters: bitmap – a valid wx.Bitmap object.
Returns: The new zero-based image index.

Note

If the bitmap is wider than the images in the list and you are not using the IL_VARIABLE_SIZE style, then the bitmap will automatically be split into smaller images, each matching the dimensions of the image list.

AddIcon(icon) [source]

Adds a new image using an icon.

Parameters: icon – a valid wx.Icon object.
Returns: The new zero-based image index.

Note

If the icon is wider than the images in the list and you are not using the IL_VARIABLE_SIZE style, then the icon will automatically be split into smaller images, each matching the dimensions of the image list.

AddWithColourMask(bitmap, maskColour) [source]

Adds a new image or images using a bitmap and a colour mask.

Parameters:
  • bitmap – a valid wx.Bitmap object;

  • colour – an instance of wx.Colour, a colour indicating which parts of the image are transparent.
Returns:

The new zero-based image index.

Note

If the bitmap is wider than the images in the list and you are not using the IL_VARIABLE_SIZE style, then the bitmap will automatically be split into smaller images, each matching the dimensions of the image list.

Draw(index, dc, x, y, flags, solidBackground=True) [source]

Draws a specified image onto a device context.

Parameters:
  • index – the image index, starting from zero;
  • dc – an instance of wx.DC;
  • x – x position on the device context;
  • y – y position on the device context;
  • flags – how to draw the image. A bitlist of a selection of the following:

    Flag Paarameter | Description
    wx.IMAGELIST_DRAW_NORMAL | Draw the image normally
    wx.IMAGELIST_DRAW_TRANSPARENT | Draw the image with transparency
    wx.IMAGELIST_DRAW_SELECTED | Draw the image in selected state
    wx.IMAGELIST_DRAW_FOCUSED | Draw the image in a focused state
  • solidBackground – currently unused.

GetBitmap(index) [source]

Returns the bitmap corresponding to the given index, or wx.NullBitmap if the index is invalid.

Parameters: index – the bitmap index.

GetIcon(index) [source]

Returns the icon corresponding to the given index, or wx.NullIcon if the index is invalid.

Parameters: index – the icon index.

GetImageCount() [source]

Returns the number of images in the list.

GetSize(index) [source]

Retrieves the size of an image in the list.

Parameters: index – the zero-based index of the image.
Returns: a tuple of (width, height) properties of the chosen bitmap.

Remove(index) [source]

Removes the image at the given position.

Parameters: index – the zero-based index of the image to be removed.

RemoveAll() [source]

Removes all the images in the list.

Replace(index, bitmap) [source]

Replaces the existing image with the new bitmap.

Parameters:
  • index – the index at which the image should be replaced;
  • bitmap – the new bitmap to add to the image list, an instance of wx.Bitmap.

ReplaceIcon(index, icon) [source]

Replaces the existing image with the new icon.

Parameters:
  • index – the index at which the image should be replaced;
  • icon – the new icon to add to the image list, an instance of wx.Icon.

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • infobar
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • ultimatelistctrl »
  • PyImageList


SelectionStore

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • ultimatelistctrl »
  • SelectionStore

SelectionStore

SelectionStore is used to store the selected items in the virtual controls, i.e. it is well suited for storing even when the control contains a huge (practically infinite) number of items.

Of course, internally it still has to store the selected items somehow (as an array currently) but the advantage is that it can handle the selection of all items (common operation) efficiently and that it could be made even smarter in the future (e.g. store the selections as an array of ranges + individual items) without changing its API.

hierarchy Inheritance Diagram

Inheritance diagram for: SelectionStore

Inheritance diagram of SelectionStore

Methods Summary

__init__ | Default class constructor.
Clear | Clears the number of selected items.
GetSelectedCount | Return the total number of selected items.
IsSelected | Returns True if the given item is selected.
OnItemDelete | Must be called when an item is deleted.
SelectItem | Selects the given item.
SelectRange | Selects a range of items.
SetItemCount | Sets the total number of items we handle.

API Class API

class SelectionStore(object) [source]

SelectionStore is used to store the selected items in the virtual controls, i.e. it is well suited for storing even when the control contains a huge (practically infinite) number of items.

Of course, internally it still has to store the selected items somehow (as an array currently) but the advantage is that it can handle the selection of all items (common operation) efficiently and that it could be made even smarter in the future (e.g. store the selections as an array of ranges + individual items) without changing its API.

__init__() [source]

Default class constructor.

Clear() [source]

Clears the number of selected items.

GetSelectedCount() [source]

Return the total number of selected items.

IsSelected(item) [source]

Returns True if the given item is selected.

Parameters: item – the item to check for selection state.

OnItemDelete(item) [source]

Must be called when an item is deleted.

Parameters: item – the item that is being deleted.

SelectItem(item, select=True) [source]

Selects the given item.

Parameters:
  • item – the item to select;
  • select – True to select the item, False otherwise.
Returns:

True if the items selection really changed.

SelectRange(itemFrom, itemTo, select=True) [source]

Selects a range of items.

Parameters:
  • itemFrom – the first index of the selection range;
  • itemTo – the last index of the selection range;
  • select – True to select the items, False otherwise.
Returns:

True and fill the itemsChanged array with the indices of items which have changed state if “few” of them did, otherwise return False (meaning that too many items changed state to bother counting them individually).

SetItemCount(count) [source]

Sets the total number of items we handle.

Parameters: count – the total number of items we handle.

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • infobar
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • ultimatelistctrl »
  • SelectionStore


UltimateListCtrl

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • ultimatelistctrl »
  • UltimateListCtrl

UltimateListCtrl

UltimateListCtrl is a class that mimics the behaviour of wx.ListCtrl, with almost the same base functionalities plus some more enhancements. This class does not rely on the native control, as it is a full owner-drawn list control.

hierarchy Inheritance Diagram

Inheritance diagram for: UltimateListCtrl

Inheritance diagram of UltimateListCtrl

appearance Control Appearance

UltimateListCtrl

Methods Summary

__init__ | Default class constructor.
Append | Append an item to the UltimateListCtrl.
Arrange | Arranges the items in icon or small icon view.
AssignImageList | Assigns the image list associated with the control.
ClearAll | Deletes everything in UltimateListCtrl.
ClearColumnImage | Clears all the images in the specified column.
ClientToScreen | Converts to screen coordinates from coordinates relative to this window.
ClientToScreenXY | Converts to screen coordinates from coordinates relative to this window.
CreateOrDestroyFooterWindowAsNeeded | Creates or destroys the footer window depending on the window style flags.
CreateOrDestroyHeaderWindowAsNeeded | Creates or destroys the header window depending on the window style flags.
DeleteAllColumns | Deletes all the column in UltimateListCtrl.
DeleteAllItems | Deletes all items in the UltimateListCtrl.
DeleteColumn | Deletes the specified column.
DeleteItem | Deletes the specified item.
DeleteItemWindow | Deletes the window associated to an item (if any).
DoGetBestSize | Gets the size which best suits the window: for a control, it would be the
DoLayout | Layouts the header, main and footer windows.
EditLabel | Starts editing an item label.
EnableItem | Enables/disables an item.
EnableSelectionGradient | Globally enables/disables drawing of gradient selections.
EnableSelectionVista | Globally enables/disables drawing of Windows Vista selections.
EnsureVisible | Ensures this item is visible.
FindItem | Find an item whose label matches this string.
FindItemAtPos | Find an item nearest this position.
FindItemData | Find an item whose data matches this data.
Focus | Focus and show the given item.
GetAGWWindowStyleFlag | Returns the UltimateListCtrl AGW-specific style flag.
GetBackgroundColour | Returns the background colour of the window.
GetBackgroundImage | Returns the UltimateListCtrl background image (if any).
GetClassDefaultAttributes | Returns the default font and colours which are used by the control.
GetColumn | Returns information about this column.
GetColumnCount | Returns the total number of columns in the UltimateListCtrl.
GetColumnWidth | Returns the column width for the input column.
GetCountPerPage | Returns the number of items that can fit vertically in the visible area
GetDefaultBorder | Returns the default window border.
GetDisabledTextColour | Returns the items disabled colour.
GetDropTarget | Returns the associated drop target, which may be None.
GetEditControl | Returns a pointer to the edit UltimateListTextCtrl if the item is being edited or
GetFirstGradientColour | Returns the first gradient colour for gradient-style selections.
GetFirstSelected | Return first selected item, or -1 when none is selected.
GetFocusedItem | Returns the currently focused item or -1 if none is focused.
GetFooterHeight | Returns the UltimateListHeaderWindow height, in pixels.
GetForegroundColour | Returns the foreground colour of the window.
GetGradientStyle | Returns the gradient style for gradient-style selections.
GetHeaderHeight | Returns the UltimateListHeaderWindow height, in pixels.
GetHyperTextFont | Returns the font used to render an hypertext item.
GetHyperTextNewColour | Returns the colour used to render a non-visited hypertext item.
GetHyperTextVisitedColour | Returns the colour used to render a visited hypertext item.
GetImageList | Returns the image list associated with the control.
GetItem | Returns the information about the input item.
GetItemBackgroundColour | Returns the item background colour.
GetItemCount | Returns the number of items in the UltimateListCtrl.
GetItemCustomRenderer | Returns the custom renderer used to draw the input item (if any).
GetItemData | Gets the application-defined data associated with this item.
GetItemFont | Returns the item font.
GetItemKind | Returns the item kind.
GetItemOverFlow | Returns if the item is in the overflow state.
GetItemPosition | Returns the position of the item, in icon or small icon view.
GetItemPyData | Returns the data for the item, which can be any Python object.
GetItemRect | Returns the rectangle representing the item’s size and position, in physical coordinates.
GetItemSpacing | Returns the spacing between item texts and icons, in pixels.
GetItemState | Returns the item state flags for the input item.
GetItemText | Returns the item text.
GetItemTextColour | Returns the item text colour.
GetItemVisited | Returns whether an hypertext item was visited.
GetItemWindow | Returns the window associated to the item (if any).
GetItemWindowEnabled | Returns whether the window associated to the item is enabled.
GetNextItem | Searches for an item with the given geometry or state, starting from item but excluding the item itself.
GetNextSelected | Returns subsequent selected items, or -1 when no more are selected.
GetPyData | Returns the data for the item, which can be any Python object.
GetScrollPos | Returns the scrollbar position.
GetScrollRange | Returns the scrollbar range in pixels.
GetScrollThumb | Returns the scrollbar size in pixels.
GetScrolledWin | Returns the header window owner.
GetSecondGradientColour | Returns the second gradient colour for gradient-style selections.
GetSelectedItemCount | Returns the number of selected items in UltimateListCtrl.
GetSubItemRect | Returns the rectangle representing the size and position, in physical coordinates, of the given subitem, i.e.
GetTextColour | Returns the UltimateListCtrl foreground colour.
GetTopItem | Gets the index of the topmost visible item when in list or report view.
GetUserLineHeight | Returns the custom value for the UltimateListCtrl item height, if previously set with
GetViewRect | Returns the rectangle taken by all items in the control.
GetWaterMark | Returns the UltimateListCtrl watermark image (if any), displayed in the
HasAGWFlag | Returns True if the window has the given flag bit set.
HasFooter | Returns True if UltimateListCtrl has a footer window.
HasHeader | Returns True if UltimateListCtrl has a header window.
HitTest | HitTest method for a UltimateListCtrl.
InsertColumn | Inserts a column into UltimateListCtrl.
InsertColumnInfo | Inserts a column into UltimateListCtrl.
InsertImageItem | Inserts an image item at the given location.
InsertImageStringItem | Inserts an image+string item at the given location.
InsertItem | Inserts an item into UltimateListCtrl.
InsertStringItem | Inserts a string item at the given location.
IsColumnShown | Returns True if the input column is shown, False if it is hidden.
IsItemChecked | Returns whether an item is checked or not.
IsItemEnabled | Returns whether an item is enabled or not.
IsItemHyperText | Returns whether an item is hypertext or not.
IsSelected | Returns True if the item is selected.
IsVirtual | Returns True if the UltimateListCtrl has the ULC_VIRTUAL style set.
OnGetItemAttr | This function may be overloaded in the derived class for a control with
OnGetItemCheck | This function may be overloaded in the derived class for a control with
OnGetItemColumnCheck | This function must be overloaded in the derived class for a control with
OnGetItemColumnImage | This function must be overloaded in the derived class for a control with
OnGetItemColumnKind | This function must be overloaded in the derived class for a control with
OnGetItemImage | This function must be overloaded in the derived class for a control with
OnGetItemKind | This function must be overloaded in the derived class for a control with
OnGetItemText | This function must be overloaded in the derived class for a control with
OnGetItemTextColour | This function must be overloaded in the derived class for a control with
OnGetItemToolTip | This function must be overloaded in the derived class for a control with
OnInternalIdle | This method is normally only used internally, but sometimes an application
OnSetFocus | Handles the wx.EVT_SET_FOCUS event for UltimateListCtrl.
OnSize | Handles the wx.EVT_SIZE event for UltimateListCtrl.
PopupMenu | Pops up the given menu at the specified coordinates, relative to this window, and returns control when the user has dismissed the menu.
Refresh | Causes this window, and all of its children recursively (except under wxGTK1
RefreshItem | Redraws the given item.
RefreshItems | Redraws the items between itemFrom and itemTo.
ScreenToClient | Converts from screen to client window coordinates.
ScreenToClientXY | Converts from screen to client window coordinates.
ScrollList | Scrolls the UltimateListCtrl.
Select | Selects/deselects an item.
SetAGWWindowStyleFlag | Sets the UltimateListCtrl AGW-specific style flag.
SetBackgroundColour | Changes the background colour of UltimateListCtrl.
SetBackgroundImage | Sets the UltimateListCtrl background image.
SetColumn | Sets information about this column.
SetColumnCustomRenderer | Associate a custom renderer to this column’s header.
SetColumnImage | Sets one or more images to the specified column.
SetColumnShown | Sets the specified column as shown or hidden.
SetColumnToolTip | Sets the tooltip for the column header
SetColumnWidth | Sets the column width.
SetCursor | Sets the window’s cursor.
SetDisabledTextColour | Sets the items disabled colour.
SetDropTarget | Associates a drop target with this window.
SetFirstGradientColour | Sets the first gradient colour for gradient-style selections.
SetFocus | This sets the window to receive keyboard input.
SetFont | Sets the UltimateListCtrl font.
SetFooterCustomRenderer | Associate a custom renderer with the footer - all columns will use it.
SetFooterHeight | Sets the UltimateListHeaderWindow height, in pixels. This overrides the default
SetForegroundColour | Changes the foreground colour of UltimateListCtrl.
SetGradientStyle | Sets the gradient style for gradient-style selections.
SetHeaderCustomRenderer | Associate a custom renderer with the header - all columns will use it.
SetHeaderHeight | Sets the UltimateListHeaderWindow height, in pixels. This overrides the default
SetHyperTextFont | Sets the font used to render hypertext items.
SetHyperTextNewColour | Sets the colour used to render a non-visited hypertext item.
SetHyperTextVisitedColour | Sets the colour used to render a visited hypertext item.
SetImageList | Sets the image list associated with the control.
SetItem | Sets the information about the input item.
SetItemBackgroundColour | Sets the item background colour.
SetItemColumnImage | Sets a Python list of image indexes associated with the item in the input
SetItemCount | Sets the total number of items we handle.
SetItemCustomRenderer | Associate a custom renderer to this item.
SetItemData | Sets the application-defined data associated with this item.
SetItemFont | Sets the item font.
SetItemHyperText | Sets whether the item is hypertext or not.
SetItemImage | Sets a Python list of image indexes associated with the item.
SetItemKind | Sets the item kind.
SetItemOverFlow | Sets the item in the overflow/non overflow state.
SetItemPosition | Sets the position of the item, in icon or small icon view.
SetItemPyData | Sets the data for the item, which can be any Python object.
SetItemSpacing | Sets the spacing between item texts and icons.
SetItemState | Sets the item state flags for the input item.
SetItemText | Sets the item text.
SetItemTextColour | Sets the item text colour.
SetItemVisited | Sets whether an hypertext item was visited or not.
SetItemWindow | Sets the window for the given item.
SetItemWindowEnabled | Enables/disables the window associated to the item.
SetPyData | Sets the data for the item, which can be any Python object.
SetScrollPos | Sets the scrollbar position.
SetSecondGradientColour | Sets the second gradient colour for gradient-style selections.
SetSingleStyle | Adds or removes a single window style.
SetStringItem | Sets a string or image at the given location.
SetTextColour | Sets the UltimateListCtrl foreground colour.
SetUserLineHeight | Sets a custom value for the UltimateListCtrl item height.
SetWaterMark | Sets the UltimateListCtrl watermark image to be displayed in the bottom
SortItems | Call this function to sort the items in the UltimateListCtrl. Sorting is done
Update | Calling this method immediately repaints the invalidated area of the window and all of its children recursively while this would usually only happen when the flow of control returns to the event loop.

API Class API

class UltimateListCtrl(wx.PyControl) [source]

UltimateListCtrl is a class that mimics the behaviour of wx.ListCtrl, with almost the same base functionalities plus some more enhancements. This class does not rely on the native control, as it is a full owner-drawn list control.

__init__(parent, id=wx.ID_ANY, pos=wx.DefaultPosition, size=wx.DefaultSize, style=0, agwStyle=0, validator=wx.DefaultValidator, name="UltimateListCtrl") [source]

Default class constructor.

Parameters:
  • parent – parent window. Must not be None;
  • id – window identifier. A value of -1 indicates a default value;
  • pos – the control position. A value of (-1, -1) indicates a default position, chosen by either the windowing system or wxPython, depending on platform;
  • size – the control size. A value of (-1, -1) indicates a default size, chosen by either the windowing system or wxPython, depending on platform;
  • style – the underlying wx.PyControl window style;
  • agwStyle – the AGW-specific window style; can be almost any combination of the following bits:

    Window Styles | Hex Value | Description
    ULC_VRULES | 0x1 | Draws light vertical rules between rows in report mode.
    ULC_HRULES | 0x2 | Draws light horizontal rules between rows in report mode.
    ULC_ICON | 0x4 | Large icon view, with optional labels.
    ULC_SMALL_ICON | 0x8 | Small icon view, with optional labels.
    ULC_LIST | 0x10 | Multicolumn list view, with optional small icons. Columns are computed automatically, i.e. you don’t set columns as in ULC_REPORT. In other words, the list wraps, unlike a wx.ListBox.
    ULC_REPORT | 0x20 | Single or multicolumn report view, with optional header.
    ULC_ALIGN_TOP | 0x40 | Icons align to the top. Win32 default, Win32 only.
    ULC_ALIGN_LEFT | 0x80 | Icons align to the left.
    ULC_AUTOARRANGE | 0x100 | Icons arrange themselves. Win32 only.
    ULC_VIRTUAL | 0x200 | The application provides items text on demand. May only be used with ULC_REPORT.
    ULC_EDIT_LABELS | 0x400 | Labels are editable: the application will be notified when editing starts.
    ULC_NO_HEADER | 0x800 | No header in report mode.
    ULC_NO_SORT_HEADER | 0x1000 | No Docs.
    ULC_SINGLE_SEL | 0x2000 | Single selection (default is multiple).
    ULC_SORT_ASCENDING | 0x4000 | Sort in ascending order. (You must still supply a comparison callback in wx.ListCtrl.SortItems.)
    ULC_SORT_DESCENDING | 0x8000 | Sort in descending order. (You must still supply a comparison callback in wx.ListCtrl.SortItems.)
    ULC_TILE | 0x10000 | Each item appears as a full-sized icon with a label of one or more lines beside it (partially implemented).
    ULC_NO_HIGHLIGHT | 0x20000 | No highlight when an item is selected.
    ULC_STICKY_HIGHLIGHT | 0x40000 | Items are selected by simply hovering on them, with no need to click on them.
    ULC_STICKY_NOSELEVENT | 0x80000 | Don’t send a selection event when using ULC_STICKY_HIGHLIGHT style.
    ULC_SEND_LEFTCLICK | 0x100000 | Send a left click event when an item is selected.
    ULC_HAS_VARIABLE_ROW_HEIGHT | 0x200000 | The list has variable row heights.
    ULC_AUTO_CHECK_CHILD | 0x400000 | When a column header has a checkbox associated, auto-check all the subitems in that column.
    ULC_AUTO_TOGGLE_CHILD | 0x800000 | When a column header has a checkbox associated, toggle all the subitems in that column.
    ULC_AUTO_CHECK_PARENT | 0x1000000 | Only meaningful foe checkbox-type items: when an item is checked/unchecked its column header item is checked/unchecked as well.
    ULC_SHOW_TOOLTIPS | 0x2000000 | Show tooltips for ellipsized items/subitems (text too long to be shown in the available space) containing the full item/subitem text.
    ULC_HOT_TRACKING | 0x4000000 | Enable hot tracking of items on mouse motion.
    ULC_BORDER_SELECT | 0x8000000 | Changes border colour whan an item is selected, instead of highlighting the item.
    ULC_TRACK_SELECT | 0x10000000 | Enables hot-track selection in a list control. Hot track selection means that an item is automatically selected when the cursor remains over the item for a certain period of time. The delay is retrieved on Windows using the win32api call win32gui.SystemParametersInfo(win32con.SPI_GETMOUSEHOVERTIME), and is defaulted to 400ms on other platforms. This style applies to all views of UltimateListCtrl.
    ULC_HEADER_IN_ALL_VIEWS | 0x20000000 | Show column headers in all view modes.
    ULC_NO_FULL_ROW_SELECT | 0x40000000 | When an item is selected, the only the item in the first column is highlighted.
    ULC_FOOTER | 0x80000000 | Show a footer too (only when header is present).
    ULC_USER_ROW_HEIGHT | 0x100000000 | Allows to set a custom row height (one value for all the items, only in report mode).
  • validator – the window validator;
  • name – the window name.

Append(entry) [source]

Append an item to the UltimateListCtrl.

Parameters: entry – should be a sequence with an item for each column.

Arrange(flag) [source]

Arranges the items in icon or small icon view.

Parameters: flag – one of the following bits:

Alignment Flag | Hex Value | Description
ULC_ALIGN_DEFAULT | 0x0 | Default alignment
ULC_ALIGN_SNAP_TO_GRID | 0x3 | Snap to grid

Note

This method is currently unimplemented and does nothing.

AssignImageList(imageList, which) [source]

Assigns the image list associated with the control.

Parameters:
  • imageList – an instance of wx.ImageList or an instance of PyImageList;
  • which – one of wx.IMAGE_LIST_NORMAL, wx.IMAGE_LIST_SMALL, wx.IMAGE_LIST_STATE (the last is unimplemented).

Note

Using PyImageList enables you to have images of different size inside the image list. In your derived class, instead of doing this:

imageList = wx.ImageList(16, 16)
imageList.Add(someBitmap)
self.SetImageList(imageList, wx.IMAGE_LIST_SMALL)

You should do this:

imageList = PyImageList(16, 16)
imageList.Add(someBitmap)
self.SetImageList(imageList, wx.IMAGE_LIST_SMALL)

ClearAll() [source]

Deletes everything in UltimateListCtrl.

ClearColumnImage(col) [source]

Clears all the images in the specified column.

Parameters: col – the column index;

ClientToScreen(pointOrTuple) [source]

Converts to screen coordinates from coordinates relative to this window.

Parameters: pointOrTuple – an instance of wx.Point or a tuple representing the x, y coordinates for this point.
Returns: the coordinates relative to the screen.

Note

Overridden from wx.PyControl.

ClientToScreenXY(x, y) [source]

Converts to screen coordinates from coordinates relative to this window.

Parameters:
  • x – an integer specifying the x client coordinate;
  • y – an integer specifying the y client coordinate.
Returns:

the coordinates relative to the screen.

Note

Overridden from wx.PyControl.

CreateOrDestroyFooterWindowAsNeeded() [source]

Creates or destroys the footer window depending on the window style flags.

CreateOrDestroyHeaderWindowAsNeeded() [source]

Creates or destroys the header window depending on the window style flags.

DeleteAllColumns() [source]

Deletes all the column in UltimateListCtrl.

DeleteAllItems() [source]

Deletes all items in the UltimateListCtrl.

Note

This function does not send the EVT_LIST_DELETE_ITEM event because deleting many items from the control would be too slow then (unlike DeleteItem).

DeleteColumn(col) [source]

Deletes the specified column.

Parameters: col – the index of the column to delete.

DeleteItem(item) [source]

Deletes the specified item.

Parameters: item – the index of the item to delete.

Note

This function sends the EVT_LIST_DELETE_ITEM event for the item being deleted.

DeleteItemWindow(itemOrId, col=0) [source]

Deletes the window associated to an item (if any).

Parameters:
  • itemOrId – an instance of UltimateListItem or the item index;
  • col – the column index to which the input item belongs to.

DoGetBestSize() [source]

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

DoLayout() [source]

Layouts the header, main and footer windows. This is an auxiliary method to avoid code duplication.

EditLabel(item) [source]

Starts editing an item label.

Parameters: item – the index of the item to edit.

EnableItem(itemOrId, col=0, enable=True) [source]

Enables/disables an item.

Parameters:
  • itemOrId – an instance of UltimateListItem or the item index;
  • col – the column index to which the input item belongs to;
  • enable – True to enable the item, False otherwise.

EnableSelectionGradient(enable=True) [source]

Globally enables/disables drawing of gradient selections.

Parameters: enable – True to enable gradient-style selections, False to disable it.

Note

Calling this method disables any Vista-style selection previously enabled.

EnableSelectionVista(enable=True) [source]

Globally enables/disables drawing of Windows Vista selections.

Parameters: enable – True to enable Vista-style selections, False to disable it.

Note

Calling this method disables any gradient-style selection previously enabled.

EnsureVisible(item) [source]

Ensures this item is visible.

Parameters: index – the index of the item to scroll into view.

FindItem(start, str, partial=False) [source]

Find an item whose label matches this string.

Parameters:
  • start – the starting point of the input string or the beginning if start is -1;
  • string – the string to look for matches;
  • partial – if True then this method will look for items which begin with string.

Note

The string comparison is case insensitive.

FindItemAtPos(start, pt) [source]

Find an item nearest this position.

Parameters: pt – an instance of wx.Point.

FindItemData(start, data) [source]

Find an item whose data matches this data.

Parameters:
  • start – the starting point of the input data or the beginning if start is -1;
  • data – the data to look for matches.

Focus(idx) [source]

Focus and show the given item.

Parameters: idx – the index of the item to be focused.

GetAGWWindowStyleFlag() [source]

Returns the UltimateListCtrl AGW-specific style flag.

See also

SetAGWWindowStyleFlag for a list of possible style flags.

GetBackgroundColour() [source]

Returns the background colour of the window.

Note

Overridden from wx.PyControl.

GetBackgroundImage() [source]

Returns the UltimateListCtrl background image (if any).

Note

At present, the background image can only be used in “tile” mode.

Todo

Support background images also in stretch and centered modes.

GetClassDefaultAttributes(variant) [source]

Returns the default font and colours which are used by the control. This is useful if you want to use the same font or colour in your own control as in a standard control – which is a much better idea than hard coding specific colours or fonts which might look completely out of place on the users system, especially if it uses themes.

This static method is “overridden’’ in many derived classes and so calling, for example, wx.Button.GetClassDefaultAttributes() will typically return the values appropriate for a button which will be normally different from those returned by, say, wx.ListCtrl.GetClassDefaultAttributes().

Note

The wx.VisualAttributes structure has at least the fields font, colFg and colBg. All of them may be invalid if it was not possible to determine the default control appearance or, especially for the background colour, if the field doesn’t make sense as is the case for colBg for the controls with themed background.

Note

Overridden from wx.PyControl.

GetColumn(col) [source]

Returns information about this column.

Parameters: col – an integer specifying the column index.

GetColumnCount() [source]

Returns the total number of columns in the UltimateListCtrl.

GetColumnWidth(col) [source]

Returns the column width for the input column.

Parameters: col – an integer specifying the column index.

GetCountPerPage() [source]

Returns the number of items that can fit vertically in the visible area of the UltimateListCtrl (list or report view) or the total number of items in the list control (icon or small icon view).

GetDefaultBorder() [source]

Returns the default window border.

GetDisabledTextColour() [source]

Returns the items disabled colour.

GetDropTarget() [source]

Returns the associated drop target, which may be None.

Note

Overridden from wx.PyControl.

GetEditControl() [source]

Returns a pointer to the edit UltimateListTextCtrl if the item is being edited or None otherwise (it is assumed that no more than one item may be edited simultaneously).

GetFirstGradientColour() [source]

Returns the first gradient colour for gradient-style selections.

GetFirstSelected() [source]

Return first selected item, or -1 when none is selected.

GetFocusedItem() [source]

Returns the currently focused item or -1 if none is focused.

GetFooterHeight() [source]

Returns the UltimateListHeaderWindow height, in pixels.

GetForegroundColour() [source]

Returns the foreground colour of the window.

Note

Overridden from wx.PyControl.

GetGradientStyle() [source]

Returns the gradient style for gradient-style selections.

Returns: 0 for horizontal gradient-style selections, 1 for vertical gradient-style selections.

GetHeaderHeight() [source]

Returns the UltimateListHeaderWindow height, in pixels.

GetHyperTextFont() [source]

Returns the font used to render an hypertext item.

GetHyperTextNewColour() [source]

Returns the colour used to render a non-visited hypertext item.

GetHyperTextVisitedColour() [source]

Returns the colour used to render a visited hypertext item.

GetImageList(which) [source]

Returns the image list associated with the control.

Parameters: which – one of wx.IMAGE_LIST_NORMAL, wx.IMAGE_LIST_SMALL, wx.IMAGE_LIST_STATE (the last is unimplemented).

Note

As UltimateListCtrl allows you to use a standard wx.ImageList or PyImageList, the returned object depends on which kind of image list you chose.

GetItem(itemOrId, col=0) [source]

Returns the information about the input item.

Parameters:
  • itemOrId – an instance of UltimateListItem or an integer specifying the item index;
  • col – the column to which the item belongs to.

GetItemBackgroundColour(item) [source]

Returns the item background colour.

Parameters: item – the index of the item.

GetItemCount() [source]

Returns the number of items in the UltimateListCtrl.

GetItemCustomRenderer(itemOrId, col=0) [source]

Returns the custom renderer used to draw the input item (if any).

Parameters:
  • itemOrId – an instance of UltimateListItem or the item index;
  • col – the column index to which the input item belongs to.

GetItemData(item) [source]

Gets the application-defined data associated with this item.

Parameters: item – an integer specifying the item index.

GetItemFont(item) [source]

Returns the item font.

Parameters: item – the index of the item.

GetItemKind(itemOrId, col=0) [source]

Returns the item kind.

Parameters:
  • itemOrId – an instance of UltimateListItem or the item index;
  • col – the column index to which the input item belongs to.

See also

SetItemKind for a list of valid item kinds.

GetItemOverFlow(itemOrId, col=0) [source]

Returns if the item is in the overflow state.

An item/subitem may overwrite neighboring items/subitems if its text would not normally fit in the space allotted to it.

Parameters:
  • itemOrId – an instance of UltimateListItem or the item index;
  • col – the column index to which the input item belongs to.

GetItemPosition(item) [source]

Returns the position of the item, in icon or small icon view.

Parameters: item – the row in which the item lives.

GetItemPyData(item) [source]

Returns the data for the item, which can be any Python object.

Parameters: item – an integer specifying the item index.

Note

Please note that Python data is associated with the item and not with subitems.

GetItemRect(item, code=ULC_RECT_BOUNDS) [source]

Returns the rectangle representing the item’s size and position, in physical coordinates.

Parameters:
  • item – the row in which the item lives;
  • code – one of ULC_RECT_BOUNDS, ULC_RECT_ICON, ULC_RECT_LABEL.

GetItemSpacing(isSmall=False) [source]

Returns the spacing between item texts and icons, in pixels.

Parameters: isSmall – True if using a wx.IMAGE_LIST_SMALL image list, False if using a wx.IMAGE_LIST_NORMAL image list.

GetItemState(item, stateMask) [source]

Returns the item state flags for the input item.

Parameters:
  • item – the index of the item;
  • stateMask – the bitmask for the state flag.

See also

SetItemState for a list of valid state flags.

GetItemText(item) [source]

Returns the item text.

Parameters: item – an instance of UltimateListItem or an integer specifying the item index.

GetItemTextColour(item) [source]

Returns the item text colour.

Parameters: item – the index of the item.

GetItemVisited(itemOrId, col=0) [source]

Returns whether an hypertext item was visited.

Parameters:
  • itemOrId – an instance of UltimateListItem or the item index;
  • col – the column index to which the input item belongs to.

GetItemWindow(itemOrId, col=0) [source]

Returns the window associated to the item (if any).

Parameters:
  • itemOrId – an instance of UltimateListItem or the item index;
  • col – the column index to which the input item belongs to.

GetItemWindowEnabled(itemOrId, col=0) [source]

Returns whether the window associated to the item is enabled.

Parameters:
  • itemOrId – an instance of UltimateListItem or the item index;
  • col – the column index to which the input item belongs to;

GetNextItem(item, geometry=ULC_NEXT_ALL, state=ULC_STATE_DONTCARE) [source]

Searches for an item with the given geometry or state, starting from item but excluding the item itself.

Parameters:
  • item – the item at which starting the search. If set to -1, the first item that matches the specified flags will be returned.
  • geometry – can be one of:

    Geometry Flag | Hex Value | Description
    ULC_NEXT_ABOVE | 0x0 | Searches for an item above the specified item
    ULC_NEXT_ALL | 0x1 | Searches for subsequent item by index
    ULC_NEXT_BELOW | 0x2 | Searches for an item below the specified item
    ULC_NEXT_LEFT | 0x3 | Searches for an item to the left of the specified item
    ULC_NEXT_RIGHT | 0x4 | Searches for an item to the right of the specified item
  • state – any combination of the following bits:

    State Bits | Hex Value | Description
    ULC_STATE_DONTCARE | 0x0 | Don’t care what the state is
    ULC_STATE_DROPHILITED | 0x1 | The item is highlighted to receive a drop event
    ULC_STATE_FOCUSED | 0x2 | The item has the focus
    ULC_STATE_SELECTED | 0x4 | The item is selected
    ULC_STATE_CUT | 0x8 | The item is in the cut state
    ULC_STATE_DISABLED | 0x10 | The item is disabled
    ULC_STATE_FILTERED | 0x20 | The item has been filtered
    ULC_STATE_INUSE | 0x40 | The item is in use
    ULC_STATE_PICKED | 0x80 | The item has been picked
    ULC_STATE_SOURCE | 0x100 | The item is a drag and drop source
Returns:

The first item with given state following item or -1 if no such item found.

Note

This function may be used to find all selected items in the control like this:

item = -1

while 1:
    item = listctrl.GetNextItem(item, ULC_NEXT_ALL, ULC_STATE_SELECTED)

    if item == -1:
        break

    # This item is selected - do whatever is needed with it

    wx.LogMessage("Item %ld is selected."%item)

GetNextSelected(item) [source]

Returns subsequent selected items, or -1 when no more are selected.

Parameters: item – the index of the item.

GetPyData(item)

Returns the data for the item, which can be any Python object.

Parameters: item – an integer specifying the item index.

Note

Please note that Python data is associated with the item and not with subitems.

GetScrollPos() [source]

Returns the scrollbar position.

Note

This method is forwarded to UltimateListMainWindow.

GetScrollRange() [source]

Returns the scrollbar range in pixels.

Note

This method is forwarded to UltimateListMainWindow.

GetScrollThumb() [source]

Returns the scrollbar size in pixels.

Note

This method is forwarded to UltimateListMainWindow.

GetScrolledWin() [source]

Returns the header window owner.

GetSecondGradientColour() [source]

Returns the second gradient colour for gradient-style selections.

GetSelectedItemCount() [source]

Returns the number of selected items in UltimateListCtrl.

GetSubItemRect(item, subItem, code) [source]

Returns the rectangle representing the size and position, in physical coordinates, of the given subitem, i.e. the part of the row item in the column subItem.

Parameters:
  • item – the row in which the item lives;
  • subItem – the column in which the item lives. If set equal to the special value ULC_GETSUBITEMRECT_WHOLEITEM the return value is the same as for GetItemRect;
  • code – one of ULC_RECT_BOUNDS, ULC_RECT_ICON, ULC_RECT_LABEL.

Note

This method is only meaningful when the UltimateListCtrl is in the report mode.

GetTextColour() [source]

Returns the UltimateListCtrl foreground colour.

GetTopItem() [source]

Gets the index of the topmost visible item when in list or report view.

GetUserLineHeight() [source]

Returns the custom value for the UltimateListCtrl item height, if previously set with SetUserLineHeight.

Note

This method can be used only with ULC_REPORT and ULC_USER_ROW_HEIGHT styles set.

GetViewRect() [source]

Returns the rectangle taken by all items in the control. In other words, if the controls client size were equal to the size of this rectangle, no scrollbars would be needed and no free space would be left.

Note

This function only works in the icon and small icon views, not in list or report views.

GetWaterMark() [source]

Returns the UltimateListCtrl watermark image (if any), displayed in the bottom right part of the window.

Todo

Better support for this is needed.

HasAGWFlag(flag) [source]

Returns True if the window has the given flag bit set.

Parameters: flag – the window style to check.

See also

SetAGWWindowStyleFlag for a list of valid window styles.

HasFooter() [source]

Returns True if UltimateListCtrl has a footer window.

HasHeader() [source]

Returns True if UltimateListCtrl has a header window.

HitTest(pointOrTuple) [source]

HitTest method for a UltimateListCtrl.

Parameters: pointOrTuple – an instance of wx.Point or a tuple representing the mouse x, y position.

See also

UltimateListMainWindow.HitTestLine() for a list of return flags.

InsertColumn(col, heading, format=ULC_FORMAT_LEFT, width=-1) [source]

Inserts a column into UltimateListCtrl.

Parameters:
  • col – the column index at which we wish to insert a column;
  • heading – the header text;
  • format – the column alignment flag. This can be one of the following bits:

    Alignment Bits | Hex Value | Description
    ULC_FORMAT_LEFT | 0x0 | The item is left-aligned
    ULC_FORMAT_RIGHT | 0x1 | The item is right-aligned
    ULC_FORMAT_CENTRE | 0x2 | The item is centre-aligned
    ULC_FORMAT_CENTER | 0x2 | The item is center-aligned
  • width – can be a width in pixels or wx.LIST_AUTOSIZE (-1) or wx.LIST_AUTOSIZE_USEHEADER (-2) or LIST_AUTOSIZE_FILL (-3). wx.LIST_AUTOSIZE will resize the column to the length of its longest item. wx.LIST_AUTOSIZE_USEHEADER will resize the column to the length of the header (Win32) or 80 pixels (other platforms). LIST_AUTOSIZE_FILL will resize the column fill the remaining width of the window.

InsertColumnInfo(col, item) [source]

Inserts a column into UltimateListCtrl.

Parameters:
  • col – the column index at which we wish to insert a column;
  • item – an instance of UltimateListItem.

InsertImageItem(index, imageIds, it_kind=0) [source]

Inserts an image item at the given location.

Parameters:
  • index – the index at which we wish to insert the item;
  • imageIds – a Python list containing the image indexes for the images associated to this item;
  • it_kind – the item kind.

See also

SetStringItem for a list of valid item kinds.

InsertImageStringItem(index, label, imageIds, it_kind=0) [source]

Inserts an image+string item at the given location.

Parameters:
  • index – the index at which we wish to insert the item;
  • label – the item text;
  • imageIds – a Python list containing the image indexes for the images associated to this item;
  • it_kind – the item kind.

See also

SetStringItem for a list of valid item kinds.

InsertItem(info) [source]

Inserts an item into UltimateListCtrl.

Parameters: info – an instance of UltimateListItem.

InsertStringItem(index, label, it_kind=0) [source]

Inserts a string item at the given location.

Parameters:
  • index – the index at which we wish to insert the item;
  • label – the item text;
  • it_kind – the item kind.

See also

SetStringItem for a list of valid item kinds.

IsColumnShown(column) [source]

Returns True if the input column is shown, False if it is hidden.

Parameters: column – an integer specifying the column index.

IsItemChecked(itemOrId, col=0) [source]

Returns whether an item is checked or not.

Parameters:
  • itemOrId – an instance of UltimateListItem or the item index;
  • col – the column index to which the input item belongs to.

IsItemEnabled(itemOrId, col=0) [source]

Returns whether an item is enabled or not.

Parameters:
  • itemOrId – an instance of UltimateListItem or the item index;
  • col – the column index to which the input item belongs to.

IsItemHyperText(itemOrId, col=0) [source]

Returns whether an item is hypertext or not.

Parameters:
  • itemOrId – an instance of UltimateListItem or the item index;
  • col – the column index to which the input item belongs to.

IsSelected(idx) [source]

Returns True if the item is selected.

Parameters: idx – the index of the item to check for selection.

IsVirtual() [source]

Returns True if the UltimateListCtrl has the ULC_VIRTUAL style set.

OnGetItemAttr(item) [source]

This function may be overloaded in the derived class for a control with ULC_VIRTUAL style. It should return the attribute for the specified item or None to use the default appearance parameters.

Parameters: item – an integer specifying the item index.

Note

UltimateListCtrl will not delete the pointer or keep a reference of it. You can return the same UltimateListItemAttr pointer for every OnGetItemAttr call.

Note

The base class version always returns None.

OnGetItemCheck(item) [source]

This function may be overloaded in the derived class for a control with ULC_VIRTUAL style. It should return whether a checkbox-like item or a radiobutton-like item is checked or unchecked.

Parameters: item – an integer specifying the item index.

Note

The base class version always returns an empty list.

OnGetItemColumnCheck(item, column=0) [source]

This function must be overloaded in the derived class for a control with ULC_VIRTUAL and ULC_REPORT style. It should return whether a checkbox-like item or a radiobutton-like item in the column header is checked or unchecked.

Parameters: item – an integer specifying the item index.

Note

The base class version always returns an empty Python list.

OnGetItemColumnImage(item, column=0) [source]

This function must be overloaded in the derived class for a control with ULC_VIRTUAL and ULC_REPORT style. It should return a Python list of indexes representing the images associated to the input item or an empty list for no images.

Parameters: item – an integer specifying the item index.

Note

The base class version always returns an empty Python list.

OnGetItemColumnKind(item, column=0) [source]

This function must be overloaded in the derived class for a control with ULC_VIRTUAL style. It should return the item kind for the input item in the header window.

Parameters:
  • item – an integer specifying the item index;
  • column – the column index.

Note

The base class version always returns 0 (a standard item).

See also

SetItemKind for a list of valid item kinds.

OnGetItemImage(item) [source]

This function must be overloaded in the derived class for a control with ULC_VIRTUAL style having an image list (if the control doesn’t have an image list, it is not necessary to overload it). It should return a Python list of indexes representing the images associated to the input item or an empty list for no images.

Parameters: item – an integer specifying the item index;

Note

In a control with ULC_REPORT style, OnGetItemImage only gets called for the first column of each line.

Note

The base class version always returns an empty Python list.

OnGetItemKind(item) [source]

This function must be overloaded in the derived class for a control with ULC_VIRTUAL style. It should return the item kind for the input item.

Parameters: item – an integer specifying the item index.

Note

The base class version always returns 0 (a standard item).

See also

SetItemKind for a list of valid item kinds.

OnGetItemText(item, col) [source]

This function must be overloaded in the derived class for a control with ULC_VIRTUAL style. It should return the string containing the text of the given column for the specified item.

Parameters:
  • item – an integer specifying the item index;
  • col – the column index to which the item belongs to.

OnGetItemTextColour(item, col) [source]

This function must be overloaded in the derived class for a control with ULC_VIRTUAL style. It should return a wx.Colour object or None for the default color.

Parameters:
  • item – an integer specifying the item index;
  • col – the column index to which the item belongs to.

OnGetItemToolTip(item, col) [source]

This function must be overloaded in the derived class for a control with ULC_VIRTUAL style. It should return the string containing the text of the tooltip for the specified item.

Parameters:
  • item – an integer specifying the item index;
  • col – the column index to which the item belongs to.

OnInternalIdle() [source]

This method is normally only used internally, but sometimes an application may need it to implement functionality that should not be disabled by an application defining an OnIdle handler in a derived class.

This method may be used to do delayed painting, for example, and most implementations call wx.Window.UpdateWindowUI in order to send update events to the window in idle time.

OnSetFocus(event) [source]

Handles the wx.EVT_SET_FOCUS event for UltimateListCtrl.

Parameters: event – a wx.FocusEvent event to be processed.

OnSize(event) [source]

Handles the wx.EVT_SIZE event for UltimateListCtrl.

Parameters: event – a wx.SizeEvent event to be processed.

PopupMenu(menu, pos=wx.DefaultPosition) [source]

Pops up the given menu at the specified coordinates, relative to this window, and returns control when the user has dismissed the menu. If a menu item is selected, the corresponding menu event is generated and will be processed as usual. If the coordinates are not specified, the current mouse cursor position is used.

Parameters:
  • menu – an instance of wx.Menu to pop up;
  • pos – the position where the menu will appear.

Note

Overridden from wx.PyControl.

Refresh(eraseBackground=True, rect=None) [source]

Causes this window, and all of its children recursively (except under wxGTK1 where this is not implemented), to be repainted.

Parameters:
  • eraseBackground – If True, the background will be erased;
  • rect – If not None, only the given rectangle will be treated as damaged.

Note

Note that repainting doesn’t happen immediately but only during the next event loop iteration, if you need to update the window immediately you should use Update instead.

Note

Overridden from wx.PyControl.

RefreshItem(item) [source]

Redraws the given item.

Parameters: item – an integer specifying the item index;

Note

This is only useful for the virtual list controls as without calling this function the displayed value of the item doesn’t change even when the underlying data does change.

RefreshItems(itemFrom, itemTo) [source]

Redraws the items between itemFrom and itemTo. The starting item must be less than or equal to the ending one.

Just as RefreshItem this is only useful for virtual list controls

Parameters:
  • itemFrom – the first index of the refresh range;
  • itemTo – the last index of the refresh range.

ScreenToClient(pointOrTuple) [source]

Converts from screen to client window coordinates.

Parameters: pointOrTuple – an instance of wx.Point or a tuple representing the x, y coordinates for this point.
Returns: the coordinates relative to this window.

Note

Overridden from wx.PyControl.

ScreenToClientXY(x, y) [source]

Converts from screen to client window coordinates.

Parameters:
  • x – an integer specifying the x screen coordinate;
  • y – an integer specifying the y screen coordinate.
Returns:

the coordinates relative to this window.

Note

Overridden from wx.PyControl.

ScrollList(dx, dy) [source]

Scrolls the UltimateListCtrl.

Parameters:
  • dx – if in icon, small icon or report view mode, specifies the number of pixels to scroll. If in list view mode, dx specifies the number of columns to scroll.
  • dy – always specifies the number of pixels to scroll vertically.

Select(idx, on=True) [source]

Selects/deselects an item.

Parameters:
  • idx – the index of the item to select;
  • on – True to select the item, False to deselect it.

SetAGWWindowStyleFlag(style) [source]

Sets the UltimateListCtrl AGW-specific style flag.

Parameters: style – the AGW-specific window style; can be almost any combination of the following bits:

Window Styles | Hex Value | Description
ULC_VRULES | 0x1 | Draws light vertical rules between rows in report mode.
ULC_HRULES | 0x2 | Draws light horizontal rules between rows in report mode.
ULC_ICON | 0x4 | Large icon view, with optional labels.
ULC_SMALL_ICON | 0x8 | Small icon view, with optional labels.
ULC_LIST | 0x10 | Multicolumn list view, with optional small icons. Columns are computed automatically, i.e. you don’t set columns as in ULC_REPORT. In other words, the list wraps, unlike a wx.ListBox.
ULC_REPORT | 0x20 | Single or multicolumn report view, with optional header.
ULC_ALIGN_TOP | 0x40 | Icons align to the top. Win32 default, Win32 only.
ULC_ALIGN_LEFT | 0x80 | Icons align to the left.
ULC_AUTOARRANGE | 0x100 | Icons arrange themselves. Win32 only.
ULC_VIRTUAL | 0x200 | The application provides items text on demand. May only be used with ULC_REPORT.
ULC_EDIT_LABELS | 0x400 | Labels are editable: the application will be notified when editing starts.
ULC_NO_HEADER | 0x800 | No header in report mode.
ULC_NO_SORT_HEADER | 0x1000 | No Docs.
ULC_SINGLE_SEL | 0x2000 | Single selection (default is multiple).
ULC_SORT_ASCENDING | 0x4000 | Sort in ascending order. (You must still supply a comparison callback in wx.ListCtrl.SortItems.)
ULC_SORT_DESCENDING | 0x8000 | Sort in descending order. (You must still supply a comparison callback in wx.ListCtrl.SortItems.)
ULC_TILE | 0x10000 | Each item appears as a full-sized icon with a label of one or more lines beside it (partially implemented).
ULC_NO_HIGHLIGHT | 0x20000 | No highlight when an item is selected.
ULC_STICKY_HIGHLIGHT | 0x40000 | Items are selected by simply hovering on them, with no need to click on them.
ULC_STICKY_NOSELEVENT | 0x80000 | Don’t send a selection event when using ULC_STICKY_HIGHLIGHT style.
ULC_SEND_LEFTCLICK | 0x100000 | Send a left click event when an item is selected.
ULC_HAS_VARIABLE_ROW_HEIGHT | 0x200000 | The list has variable row heights.
ULC_AUTO_CHECK_CHILD | 0x400000 | When a column header has a checkbox associated, auto-check all the subitems in that column.
ULC_AUTO_TOGGLE_CHILD | 0x800000 | When a column header has a checkbox associated, toggle all the subitems in that column.
ULC_AUTO_CHECK_PARENT | 0x1000000 | Only meaningful foe checkbox-type items: when an item is checked/unchecked its column header item is checked/unchecked as well.
ULC_SHOW_TOOLTIPS | 0x2000000 | Show tooltips for ellipsized items/subitems (text too long to be shown in the available space) containing the full item/subitem text.
ULC_HOT_TRACKING | 0x4000000 | Enable hot tracking of items on mouse motion.
ULC_BORDER_SELECT | 0x8000000 | Changes border colour whan an item is selected, instead of highlighting the item.
ULC_TRACK_SELECT | 0x10000000 | Enables hot-track selection in a list control. Hot track selection means that an item is automatically selected when the cursor remains over the item for a certain period of time. The delay is retrieved on Windows using the win32api call win32gui.SystemParametersInfo(win32con.SPI_GETMOUSEHOVERTIME), and is defaulted to 400ms on other platforms. This style applies to all views of UltimateListCtrl.
ULC_HEADER_IN_ALL_VIEWS | 0x20000000 | Show column headers in all view modes.
ULC_NO_FULL_ROW_SELECT | 0x40000000 | When an item is selected, the only the item in the first column is highlighted.
ULC_FOOTER | 0x80000000 | Show a footer too (only when header is present).
ULC_USER_ROW_HEIGHT | 0x100000000 | Allows to set a custom row height (one value for all the items, only in report mode).

SetBackgroundColour(colour) [source]

Changes the background colour of UltimateListCtrl.

Parameters: colour – the colour to be used as the background colour, pass wx.NullColour to reset to the default colour.

Note

The background colour is usually painted by the default wx.EraseEvent event handler function under Windows and automatically under GTK.

Note

Setting the background colour does not cause an immediate refresh, so you may wish to call wx.Window.ClearBackground or wx.Window.Refresh after calling this function.

Note

Overridden from wx.PyControl.

SetBackgroundImage(image=None) [source]

Sets the UltimateListCtrl background image.

Parameters: image – if not None, an instance of wx.Bitmap.

Note

At present, the background image can only be used in “tile” mode.

Todo

Support background images also in stretch and centered modes.

SetColumn(col, item) [source]

Sets information about this column.

Parameters:
  • col – an integer specifying the column index;
  • item – an instance of UltimateListItem.

SetColumnCustomRenderer(col=0, renderer=None) [source]

Associate a custom renderer to this column’s header.

Parameters:
  • col – the column index.
  • renderer – a class able to correctly render the input item.

Note

the renderer class must implement the methods DrawHeaderButton and GetForegroundColor.

SetColumnImage(col, image) [source]

Sets one or more images to the specified column.

Parameters:
  • col – the column index;
  • image – a Python list containing the image indexes for the images associated to this column item.

SetColumnShown(column, shown=True) [source]

Sets the specified column as shown or hidden.

Parameters:
  • column – an integer specifying the column index;
  • shown – True to show the column, False to hide it.

SetColumnToolTip(col, tip) [source]

Sets the tooltip for the column header

Parameters:
  • col – the column index;
  • tip – the tooltip text

SetColumnWidth(col, width) [source]

Sets the column width.

Parameters: width – can be a width in pixels or wx.LIST_AUTOSIZE (-1) or wx.LIST_AUTOSIZE_USEHEADER (-2) or LIST_AUTOSIZE_FILL (-3). wx.LIST_AUTOSIZE will resize the column to the length of its longest item. wx.LIST_AUTOSIZE_USEHEADER will resize the column to the length of the header (Win32) or 80 pixels (other platforms). LIST_AUTOSIZE_FILL will resize the column fill the remaining width of the window.

Note

In small or normal icon view, col must be -1, and the column width is set for all columns.

SetCursor(cursor) [source]

Sets the window’s cursor.

Parameters: cursor – specifies the cursor that the window should normally display. The cursor may be wx.NullCursor in which case the window cursor will be reset back to default.

Note

The window cursor also sets it for the children of the window implicitly.

Note

Overridden from wx.PyControl.

SetDisabledTextColour(colour) [source]

Sets the items disabled colour.

Parameters: colour – an instance of wx.Colour.

SetDropTarget(dropTarget) [source]

Associates a drop target with this window. If the window already has a drop target, it is deleted.

Parameters: dropTarget – an instance of wx.DropTarget.

Note

Overridden from wx.PyControl.

SetFirstGradientColour(colour=None) [source]

Sets the first gradient colour for gradient-style selections.

Parameters: colour – if not None, a valid wx.Colour instance. Otherwise, the colour is taken from the system value wx.SYS_COLOUR_HIGHLIGHT.

SetFocus() [source]

This sets the window to receive keyboard input.

SetFont(font) [source]

Sets the UltimateListCtrl font.

Parameters: font – a valid wx.Font instance.

Note

Overridden from wx.PyControl.

SetFooterCustomRenderer(renderer=None) [source]

Associate a custom renderer with the footer - all columns will use it.

Parameters: renderer – a class able to correctly render header buttons

Note

the renderer class must implement the methods DrawHeaderButton and GetForegroundColor.

SetFooterHeight(height) [source]

Sets the UltimateListHeaderWindow height, in pixels. This overrides the default footer window size derived from wx.RendererNative. If height is None, the default behaviour is restored.

Parameters: height – the footer window height, in pixels (if it is None, the default height obtained using wx.RendererNative is used).

SetForegroundColour(colour) [source]

Changes the foreground colour of UltimateListCtrl.

Parameters: colour – the colour to be used as the foreground colour, pass wx.NullColour to reset to the default colour.

Note

Overridden from wx.PyControl.

SetGradientStyle(vertical=0) [source]

Sets the gradient style for gradient-style selections.

Parameters: vertical – 0 for horizontal gradient-style selections, 1 for vertical gradient-style selections.

SetHeaderCustomRenderer(renderer=None) [source]

Associate a custom renderer with the header - all columns will use it.

Parameters: renderer – a class able to correctly render header buttons

Note

the renderer class must implement the methods DrawHeaderButton and GetForegroundColor.

SetHeaderHeight(height) [source]

Sets the UltimateListHeaderWindow height, in pixels. This overrides the default header window size derived from wx.RendererNative. If height is None, the default behaviour is restored.

Parameters: height – the header window height, in pixels (if it is None, the default height obtained using wx.RendererNative is used).

SetHyperTextFont(font) [source]

Sets the font used to render hypertext items.

Parameters: font – a valid wx.Font instance.

SetHyperTextNewColour(colour) [source]

Sets the colour used to render a non-visited hypertext item.

Parameters: colour – a valid wx.Colour instance.

SetHyperTextVisitedColour(colour) [source]

Sets the colour used to render a visited hypertext item.

Parameters: colour – a valid wx.Colour instance.

SetImageList(imageList, which) [source]

Sets the image list associated with the control.

Parameters:
  • imageList – an instance of wx.ImageList or an instance of PyImageList;

  • which – one of wx.IMAGE_LIST_NORMAL, wx.IMAGE_LIST_SMALL, wx.IMAGE_LIST_STATE (the last is unimplemented).

Note

Using PyImageList enables you to have images of different size inside the image list. In your derived class, instead of doing this:

imageList = wx.ImageList(16, 16)
imageList.Add(someBitmap)
self.SetImageList(imageList, wx.IMAGE_LIST_SMALL)

You should do this:

imageList = PyImageList(16, 16)
imageList.Add(someBitmap)
self.SetImageList(imageList, wx.IMAGE_LIST_SMALL)

SetItem(info) [source]

Sets the information about the input item.

Parameters: info – an instance of UltimateListItem.

SetItemBackgroundColour(item, col) [source]

Sets the item background colour.

Parameters:
  • item – the index of the item;
  • col – a valid wx.Colour object.

SetItemColumnImage(item, column, image) [source]

Sets a Python list of image indexes associated with the item in the input column.

Parameters:
  • item – an integer specifying the item index;
  • column – the column to which the item belongs to;
  • image – a Python list of indexes into the image list associated with the UltimateListCtrl.

SetItemCount(count) [source]

Sets the total number of items we handle.

Parameters: count – the total number of items we handle.

SetItemCustomRenderer(itemOrId, col=0, renderer=None) [source]

Associate a custom renderer to this item.

Parameters:
  • itemOrId – an instance of UltimateListItem or the item index;
  • col – the column index to which the input item belongs to;
  • renderer – a class able to correctly render the input item.

Note

the renderer class must implement the methods DrawSubItem, GetLineHeight and GetSubItemWidth.

SetItemData(item, data) [source]

Sets the application-defined data associated with this item.

Parameters:
  • item – an integer specifying the item index;
  • data – the data to be associated with the input item.

Note

This function cannot be used to associate pointers with the control items, use SetItemPyData instead.

SetItemFont(item, f) [source]

Sets the item font.

Parameters:
  • item – the index of the item;
  • f – a valid wx.Font object.

SetItemHyperText(itemOrId, col=0, hyper=True) [source]

Sets whether the item is hypertext or not.

Parameters:
  • itemOrId – an instance of UltimateListItem or the item index;
  • col – the column index to which the input item belongs to;
  • hyper – True to have an item with hypertext behaviour, False otherwise.

SetItemImage(item, image, selImage=-1) [source]

Sets a Python list of image indexes associated with the item.

Parameters:
  • item – an integer specifying the item index;
  • image – a Python list of indexes into the image list associated with the UltimateListCtrl. In report view, this only sets the images for the first column;
  • selImage – not used at present.

SetItemKind(itemOrId, col=0, kind=0) [source]

Sets the item kind.

Parameters:
  • itemOrId – an instance of UltimateListItem or the item index;
  • col – the column index to which the input item belongs to;
  • kind – may be one of the following integers:

    Item Kind | Description
    0 | A normal item
    1 | A checkbox-like item
    2 | A radiobutton-type item

SetItemOverFlow(itemOrId, col=0, over=True) [source]

Sets the item in the overflow/non overflow state.

An item/subitem may overwrite neighboring items/subitems if its text would not normally fit in the space allotted to it.

Parameters:
  • itemOrId – an instance of UltimateListItem or the item index;
  • col – the column index to which the input item belongs to;
  • over – True to set the item in a overflow state, False otherwise.

SetItemPosition(item, pos) [source]

Sets the position of the item, in icon or small icon view.

Parameters:
  • item – the row in which the item lives;
  • pos – the item position.

Note

This method is currently unimplemented and does nothing.

SetItemPyData(item, pyData) [source]

Sets the data for the item, which can be any Python object.

Parameters:
  • item – an integer specifying the item index;
  • pyData – any Python object.

Note

Please note that Python data is associated with the item and not with subitems.

SetItemSpacing(spacing, isSmall=False) [source]

Sets the spacing between item texts and icons.

Parameters:
  • spacing – the spacing between item texts and icons, in pixels;
  • isSmall – True if using a wx.IMAGE_LIST_SMALL image list, False if using a wx.IMAGE_LIST_NORMAL image list.

SetItemState(item, state, stateMask) [source]

Sets the item state flags for the input item.

Parameters:
  • item – the index of the item; if defaulted to -1, the state flag will be set for all the items;
  • state – any combination of the following bits:

    State Bits | Hex Value | Description
    ULC_STATE_DONTCARE | 0x0 | Don’t care what the state is
    ULC_STATE_DROPHILITED | 0x1 | The item is highlighted to receive a drop event
    ULC_STATE_FOCUSED | 0x2 | The item has the focus
    ULC_STATE_SELECTED | 0x4 | The item is selected
    ULC_STATE_CUT | 0x8 | The item is in the cut state
    ULC_STATE_DISABLED | 0x10 | The item is disabled
    ULC_STATE_FILTERED | 0x20 | The item has been filtered
    ULC_STATE_INUSE | 0x40 | The item is in use
    ULC_STATE_PICKED | 0x80 | The item has been picked
    ULC_STATE_SOURCE | 0x100 | The item is a drag and drop source
  • stateMask – the bitmask for the state flag.

SetItemText(item, text) [source]

Sets the item text.

Parameters:
  • item – an instance of UltimateListItem or an integer specifying the item index;
  • text – the new item text.

SetItemTextColour(item, col) [source]

Sets the item text colour.

Parameters:
  • item – the index of the item;
  • col – a valid wx.Colour object.

SetItemVisited(itemOrId, col=0, visited=True) [source]

Sets whether an hypertext item was visited or not.

Parameters:
  • itemOrId – an instance of UltimateListItem or the item index;
  • col – the column index to which the input item belongs to;
  • visited – True to mark an hypertext item as visited, False otherwise.

SetItemWindow(itemOrId, col=0, wnd=None, expand=False) [source]

Sets the window for the given item.

Parameters:
  • itemOrId – an instance of UltimateListItem or the item index;
  • col – the column index to which the input item belongs to;
  • wnd – a non-toplevel window to be displayed next to the item;
  • expand – True to expand the column where the item/subitem lives, so that the window will be fully visible.

SetItemWindowEnabled(itemOrId, col=0, enable=True) [source]

Enables/disables the window associated to the item.

Parameters:
  • itemOrId – an instance of UltimateListItem or the item index;
  • col – the column index to which the input item belongs to;
  • enable – True to enable the associated window, False to disable it.

SetPyData(item, pyData)

Sets the data for the item, which can be any Python object.

Parameters:
  • item – an integer specifying the item index;
  • pyData – any Python object.

Note

Please note that Python data is associated with the item and not with subitems.

SetScrollPos(orientation, pos, refresh=True) [source]

Sets the scrollbar position.

Parameters:
  • orientation – determines the scrollbar whose position is to be set. May be wx.HORIZONTAL or wx.VERTICAL;
  • pos – the scrollbar position in scroll units;
  • refresh – True to redraw the scrollbar, False otherwise.

Note

This method is forwarded to UltimateListMainWindow.

SetSecondGradientColour(colour=None) [source]

Sets the second gradient colour for gradient-style selections.

Parameters: colour – if not None, a valid wx.Colour instance. Otherwise, the colour generated is a slightly darker version of the UltimateListCtrl background colour.

SetSingleStyle(style, add=True) [source]

Adds or removes a single window style.

Parameters:
  • style – can be one of the following bits:

    Window Styles | Hex Value | Description
    ULC_VRULES | 0x1 | Draws light vertical rules between rows in report mode.
    ULC_HRULES | 0x2 | Draws light horizontal rules between rows in report mode.
    ULC_ICON | 0x4 | Large icon view, with optional labels.
    ULC_SMALL_ICON | 0x8 | Small icon view, with optional labels.
    ULC_LIST | 0x10 | Multicolumn list view, with optional small icons. Columns are computed automatically, i.e. you don’t set columns as in ULC_REPORT. In other words, the list wraps, unlike a wx.ListBox.
    ULC_REPORT | 0x20 | Single or multicolumn report view, with optional header.
    ULC_ALIGN_TOP | 0x40 | Icons align to the top. Win32 default, Win32 only.
    ULC_ALIGN_LEFT | 0x80 | Icons align to the left.
    ULC_AUTOARRANGE | 0x100 | Icons arrange themselves. Win32 only.
    ULC_VIRTUAL | 0x200 | The application provides items text on demand. May only be used with ULC_REPORT.
    ULC_EDIT_LABELS | 0x400 | Labels are editable: the application will be notified when editing starts.
    ULC_NO_HEADER | 0x800 | No header in report mode.
    ULC_NO_SORT_HEADER | 0x1000 | No Docs.
    ULC_SINGLE_SEL | 0x2000 | Single selection (default is multiple).
    ULC_SORT_ASCENDING | 0x4000 | Sort in ascending order. (You must still supply a comparison callback in wx.ListCtrl.SortItems.)
    ULC_SORT_DESCENDING | 0x8000 | Sort in descending order. (You must still supply a comparison callback in wx.ListCtrl.SortItems.)
    ULC_TILE | 0x10000 | Each item appears as a full-sized icon with a label of one or more lines beside it (partially implemented).
    ULC_NO_HIGHLIGHT | 0x20000 | No highlight when an item is selected.
    ULC_STICKY_HIGHLIGHT | 0x40000 | Items are selected by simply hovering on them, with no need to click on them.
    ULC_STICKY_NOSELEVENT | 0x80000 | Don’t send a selection event when using ULC_STICKY_HIGHLIGHT style.
    ULC_SEND_LEFTCLICK | 0x100000 | Send a left click event when an item is selected.
    ULC_HAS_VARIABLE_ROW_HEIGHT | 0x200000 | The list has variable row heights.
    ULC_AUTO_CHECK_CHILD | 0x400000 | When a column header has a checkbox associated, auto-check all the subitems in that column.
    ULC_AUTO_TOGGLE_CHILD | 0x800000 | When a column header has a checkbox associated, toggle all the subitems in that column.
    ULC_AUTO_CHECK_PARENT | 0x1000000 | Only meaningful foe checkbox-type items: when an item is checked/unchecked its column header item is checked/unchecked as well.
    ULC_SHOW_TOOLTIPS | 0x2000000 | Show tooltips for ellipsized items/subitems (text too long to be shown in the available space) containing the full item/subitem text.
    ULC_HOT_TRACKING | 0x4000000 | Enable hot tracking of items on mouse motion.
    ULC_BORDER_SELECT | 0x8000000 | Changes border colour whan an item is selected, instead of highlighting the item.
    ULC_TRACK_SELECT | 0x10000000 | Enables hot-track selection in a list control. Hot track selection means that an item is automatically selected when the cursor remains over the item for a certain period of time. The delay is retrieved on Windows using the win32api call win32gui.SystemParametersInfo(win32con.SPI_GETMOUSEHOVERTIME), and is defaulted to 400ms on other platforms. This style applies to all views of UltimateListCtrl.
    ULC_HEADER_IN_ALL_VIEWS | 0x20000000 | Show column headers in all view modes.
    ULC_NO_FULL_ROW_SELECT | 0x40000000 | When an item is selected, the only the item in the first column is highlighted.
    ULC_FOOTER | 0x80000000 | Show a footer too (only when header is present).
  • add – True to add the window style, False to remove it.

Note

The style ULC_VIRTUAL can not be set/unset after construction.

SetStringItem(index, col, label, imageIds=[], it_kind=0) [source]

Sets a string or image at the given location.

Parameters:
  • index – the item index;
  • col – the column to which the item belongs to;
  • label – the item text;
  • imageIds – a Python list containing the image indexes for the images associated to this item;
  • it_kind – the item kind. May be one of the following integers:

    Item Kind | Description
    0 | A normal item
    1 | A checkbox-like item
    2 | A radiobutton-type item

SetTextColour(col) [source]

Sets the UltimateListCtrl foreground colour.

Parameters: col – a valid wx.Colour object.

SetUserLineHeight(height) [source]

Sets a custom value for the UltimateListCtrl item height.

Parameters: height – the custom height for all the items, in pixels.

Note

This method can be used only with ULC_REPORT and ULC_USER_ROW_HEIGHT styles set.

SetWaterMark(watermark=None) [source]

Sets the UltimateListCtrl watermark image to be displayed in the bottom right part of the window.

Parameters: watermark – if not None, an instance of wx.Bitmap.

Todo

Better support for this is needed.

SortItems(func=None) [source]

Call this function to sort the items in the UltimateListCtrl. Sorting is done using the specified function func. This function must have the following prototype:

def OnCompareItems(self, line1, line2):

    DoSomething(line1, line2)
    # function code

It is called each time when the two items must be compared and should return 0 if the items are equal, negative value if the first item is less than the second one and positive value if the first one is greater than the second one.

Parameters: func – the method to use to sort the items. The default is to use the UltimateListMainWindow.OnCompareItems() method.

Update() [source]

Calling this method immediately repaints the invalidated area of the window and all of its children recursively while this would usually only happen when the flow of control returns to the event loop.

Note

This function doesn’t invalidate any area of the window so nothing happens if nothing has been invalidated (i.e. marked as requiring a redraw). Use Refresh first if you want to immediately redraw the window unconditionally.

Note

Overridden from wx.PyControl.

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • infobar
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • ultimatelistctrl »
  • UltimateListCtrl


UltimateListEvent

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • ultimatelistctrl »
  • UltimateListEvent

UltimateListEvent

A list event holds information about events associated with UltimateListCtrl objects.

hierarchy Inheritance Diagram

Inheritance diagram for: UltimateListEvent

Inheritance diagram of UltimateListEvent

supclasses Known Superclasses

  • ultimatelistctrl.CommandListEvent

Methods Summary

__init__ | Default class constructor.
Allow | This is the opposite of Veto: it explicitly allows the event to be processed.
GetNotifyEvent | Returns the actual wx.NotifyEvent.
IsAllowed | Returns True if the change is allowed (Veto hasn’t been called) or
Veto | Prevents the change announced by this event from happening.

API Class API

class UltimateListEvent(CommandListEvent) [source]

A list event holds information about events associated with UltimateListCtrl objects.

__init__(commandTypeOrEvent=None, winid=0) [source]

Default class constructor. For internal use: do not call it in your code!

Parameters:
  • commandTypeOrEvent – the event type or another instance of wx.PyCommandEvent;
  • winid – the event identifier.

Allow() [source]

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

GetNotifyEvent() [source]

Returns the actual wx.NotifyEvent.

IsAllowed() [source]

Returns True if the change is allowed (Veto hasn’t been called) or False otherwise (if it was).

Veto() [source]

Prevents the change announced by this event from happening.

Note

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

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • infobar
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • ultimatelistctrl »
  • UltimateListEvent


UltimateListHeaderData

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • ultimatelistctrl »
  • UltimateListHeaderData

UltimateListHeaderData

A simple class which holds information about UltimateListItem visual attributes for the header/footer items (client rectangles, positions, etc...).

hierarchy Inheritance Diagram

Inheritance diagram for: UltimateListHeaderData

Inheritance diagram of UltimateListHeaderData

Methods Summary

__init__ | Default class constructor.
Check | Checks/unchecks a header item.
CheckFooter | Checks/unchecks a footer item.
GetCustomRenderer | Returns the custom renderer associated with this item (if any).
GetFont | Returns the header/footer item font.
GetFooterFormat | Returns the footer item format.
GetFooterImage | Returns a Python list with the zero-based indexes of the images associated
GetFooterKind | Returns the footer item kind.
GetFormat | Returns the header item format.
GetImage | Returns a Python list with the zero-based indexes of the images associated
GetItem | Returns information about the item.
GetKind | Returns the header item kind.
GetState | Returns a bit field representing the state of the item.
GetText | Returns the header/footer item text.
GetToolTip | Returns the header/footer item tooltip.
GetWidth | Returns the header/footer item width, in pixels.
HasFooterImage | Returns True if the footer item has at least one image associated
HasImage | Returns True if the header item has at least one image associated
HasText | Returns True if the currently set text colour is valid.
Init | Initializes the header/footer item.
IsChecked | Returns whether the header item is checked or not.
IsFooterChecked | Returns whether the footer item is checked or not.
IsHit | Returns True if the input position is inside the item client rectangle.
SetCustomRenderer | Associate a custom renderer to this item.
SetFont | Sets a new font for the header item.
SetFooterFont | Sets a new font for the footer item.
SetFooterFormat | Sets the footer item format.
SetFooterKind | Sets the footer item kind.
SetFormat | Sets the header item format.
SetHeight | Sets the header/footer item height, in pixels.
SetItem | Sets information about the header/footer item.
SetKind | Sets the header item kind.
SetPosition | Sets the header/footer item position.
SetState | Sets the item state flags.
SetText | Sets the header/footer item text.
SetToolTip | Sets the header/footer item tooltip.
SetWidth | Sets the header/footer item width, in pixels.

API Class API

class UltimateListHeaderData(object) [source]

A simple class which holds information about UltimateListItem visual attributes for the header/footer items (client rectangles, positions, etc...).

__init__(item=None) [source]

Default class constructor.

Parameters: item – another instance of UltimateListHeaderData.

Check(checked=True) [source]

Checks/unchecks a header item.

Parameters: checked – True to check an item, False to uncheck it.

Note

This method is meaningful only for check and radio header items.

CheckFooter(check=True) [source]

Checks/unchecks a footer item.

Parameters: checked – True to check an item, False to uncheck it.

Note

This method is meaningful only for check and radio footer items.

GetCustomRenderer() [source]

Returns the custom renderer associated with this item (if any).

GetFont() [source]

Returns the header/footer item font.

GetFooterFormat() [source]

Returns the footer item format.

GetFooterImage() [source]

Returns a Python list with the zero-based indexes of the images associated with the footer item into the image list.

GetFooterKind() [source]

Returns the footer item kind.

See also

SetKind for a list of valid item kinds.

GetFormat() [source]

Returns the header item format.

GetImage() [source]

Returns a Python list with the zero-based indexes of the images associated with the header item into the image list.

GetItem(item) [source]

Returns information about the item.

Parameters: item – an instance of UltimateListHeaderData.

GetKind() [source]

Returns the header item kind.

See also

SetKind for a list of valid item kinds.

GetState() [source]

Returns a bit field representing the state of the item.

See also

SetState for a list of valid item states.

GetText() [source]

Returns the header/footer item text.

GetToolTip() [source]

Returns the header/footer item tooltip.

GetWidth() [source]

Returns the header/footer item width, in pixels.

HasFooterImage() [source]

Returns True if the footer item has at least one image associated with it.

HasImage() [source]

Returns True if the header item has at least one image associated with it.

HasText() [source]

Returns True if the currently set text colour is valid.

Init() [source]

Initializes the header/footer item.

IsChecked() [source]

Returns whether the header item is checked or not.

IsFooterChecked() [source]

Returns whether the footer item is checked or not.

IsHit(x, y) [source]

Returns True if the input position is inside the item client rectangle.

Parameters:
  • x – the x mouse position;
  • y – the y mouse position.

SetCustomRenderer(renderer) [source]

Associate a custom renderer to this item.

Parameters: renderer – a class able to correctly render the item.

Note

the renderer class must implement the methods DrawHeaderButton and GetForegroundColor.

SetFont(font) [source]

Sets a new font for the header item.

Parameters: font – an instance of wx.Font.

SetFooterFont(font) [source]

Sets a new font for the footer item.

Parameters: font – an instance of wx.Font.

SetFooterFormat(format) [source]

Sets the footer item format.

Parameters: format – the footer item format.

SetFooterKind(kind) [source]

Sets the footer item kind.

Parameters: kind – the footer item kind.

See also

SetKind for a list of valid item kinds.

SetFormat(format) [source]

Sets the header item format.

Parameters: format – the header item format.

SetHeight(h) [source]

Sets the header/footer item height, in pixels.

Parameters: h – an integer value representing the header/footer height.

SetItem(item) [source]

Sets information about the header/footer item.

Parameters: info – an instance of UltimateListHeaderData.

SetKind(kind) [source]

Sets the header item kind.

Parameters: kind – may be one of the following integers:

Item Kind | Description
0 | A normal item
1 | A checkbox-like item
2 | A radiobutton-type item

SetPosition(x, y) [source]

Sets the header/footer item position.

Parameters:
  • x – the item x position;
  • y – the item y position.

SetState(flag) [source]

Sets the item state flags.

Parameters: state – any combination of the following bits:

State Bits | Hex Value | Description
ULC_STATE_DONTCARE | 0x0 | Don’t care what the state is
ULC_STATE_DROPHILITED | 0x1 | The item is highlighted to receive a drop event
ULC_STATE_FOCUSED | 0x2 | The item has the focus
ULC_STATE_SELECTED | 0x4 | The item is selected
ULC_STATE_CUT | 0x8 | The item is in the cut state
ULC_STATE_DISABLED | 0x10 | The item is disabled
ULC_STATE_FILTERED | 0x20 | The item has been filtered
ULC_STATE_INUSE | 0x40 | The item is in use
ULC_STATE_PICKED | 0x80 | The item has been picked
ULC_STATE_SOURCE | 0x100 | The item is a drag and drop source

SetText(text) [source]

Sets the header/footer item text.

Parameters: text – the new header/footer text.

SetToolTip(tip) [source]

Sets the header/footer item tooltip.

Parameters: tip – the new header/footer tooltip.

SetWidth(w) [source]

Sets the header/footer item width, in pixels.

Parameters: w – an integer value representing the header/footer width.

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • infobar
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • ultimatelistctrl »
  • UltimateListHeaderData


UltimateListHeaderWindow

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • ultimatelistctrl »
  • UltimateListHeaderWindow

UltimateListHeaderWindow

This class holds the header window for UltimateListCtrl.

hierarchy Inheritance Diagram

Inheritance diagram for: UltimateListHeaderWindow

Inheritance diagram of UltimateListHeaderWindow

Methods Summary

__init__ | Default class constructor.
AdjustDC | Shifts the wx.DC origin to match the position of the main window horizontal
DoGetBestSize | Gets the size which best suits the window: for a control, it would be the
DrawCurrent | Force the redrawing of the column window.
DrawTextFormatted | Draws the item text, correctly formatted.
GetOwner | Returns the header window owner, an instance of UltimateListCtrl.
GetTextHeight | Returns the column text height, in pixels.
GetWindowHeight | Returns the UltimateListHeaderWindow height, in pixels.
HandleColumnCheck | Handles the case in which a column contains a checkbox-like item.
HitTestColumn | HitTest method for column headers.
IsColumnShown | Returns True if the input column is shown, False if it is hidden.
OnEnterWindow | Handles the wx.EVT_ENTER_WINDOW event for UltimateListHeaderWindow.
OnInternalIdle | This method is normally only used internally, but sometimes an application
OnLeaveWindow | Handles the wx.EVT_LEAVE_WINDOW event for UltimateListHeaderWindow.
OnMouse | Handles the wx.EVT_MOUSE_EVENTS event for UltimateListHeaderWindow.
OnPaint | Handles the wx.EVT_PAINT event for UltimateListHeaderWindow.
OnSetFocus | Handles the wx.EVT_SET_FOCUS event for UltimateListHeaderWindow.
SendListEvent | Sends a UltimateListEvent for the parent window.
SetCustomRenderer | Associate a custom renderer with the header - all columns will use it :param renderer: a class able to correctly render header buttons ..

API Class API

class UltimateListHeaderWindow(wx.PyControl) [source]

This class holds the header window for UltimateListCtrl.

__init__(win, id, owner, pos=wx.DefaultPosition, size=wx.DefaultSize, style=0, validator=wx.DefaultValidator, name="UltimateListCtrlcolumntitles", isFooter=False) [source]

Default class constructor.

Parameters:
  • parent – parent window. Must not be None;
  • id – window identifier. A value of -1 indicates a default value;
  • owner – an instance of UltimateListCtrl;
  • pos – the control position. A value of (-1, -1) indicates a default position, chosen by either the windowing system or wxPython, depending on platform;
  • size – the control size. A value of (-1, -1) indicates a default size, chosen by either the windowing system or wxPython, depending on platform;
  • style – the window style;
  • validator – the window validator;
  • name – the window name;
  • isFooter – True if the UltimateListHeaderWindow is in a footer position, False otherwise.

AdjustDC(dc) [source]

Shifts the wx.DC origin to match the position of the main window horizontal scrollbar: this allows us to always use logical coordinates.

Parameters: dc – an instance of wx.DC.

DoGetBestSize() [source]

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

DrawCurrent() [source]

Force the redrawing of the column window.

DrawTextFormatted(dc, text, rect) [source]

Draws the item text, correctly formatted.

Parameters:
  • dc – an instance of wx.DC;

  • text – the item text;
  • rect – the item client rectangle.

GetOwner() [source]

Returns the header window owner, an instance of UltimateListCtrl.

GetTextHeight() [source]

Returns the column text height, in pixels.

GetWindowHeight() [source]

Returns the UltimateListHeaderWindow height, in pixels.

HandleColumnCheck(column, pos) [source]

Handles the case in which a column contains a checkbox-like item.

Parameters:
  • column – the column index;
  • pos – the mouse position.

HitTestColumn(x, y) [source]

HitTest method for column headers.

Parameters:
  • x – the mouse x position;
  • y – the mouse y position.
Returns:

The column index if any column client rectangle contains the mouse position, wx.NOT_FOUND otherwise.

IsColumnShown(column) [source]

Returns True if the input column is shown, False if it is hidden.

Parameters: column – an integer specifying the column index.

OnEnterWindow(event) [source]

Handles the wx.EVT_ENTER_WINDOW event for UltimateListHeaderWindow.

Parameters: event – a wx.MouseEvent event to be processed.

OnInternalIdle() [source]

This method is normally only used internally, but sometimes an application may need it to implement functionality that should not be disabled by an application defining an OnIdle handler in a derived class.

This method may be used to do delayed painting, for example, and most implementations call wx.Window.UpdateWindowUI in order to send update events to the window in idle time.

OnLeaveWindow(event) [source]

Handles the wx.EVT_LEAVE_WINDOW event for UltimateListHeaderWindow.

Parameters: event – a wx.MouseEvent event to be processed.

OnMouse(event) [source]

Handles the wx.EVT_MOUSE_EVENTS event for UltimateListHeaderWindow.

Parameters: event – a wx.MouseEvent event to be processed.

OnPaint(event) [source]

Handles the wx.EVT_PAINT event for UltimateListHeaderWindow.

Parameters: event – a wx.PaintEvent event to be processed.

OnSetFocus(event) [source]

Handles the wx.EVT_SET_FOCUS event for UltimateListHeaderWindow.

Parameters: event – a wx.FocusEvent event to be processed.

SendListEvent(eventType, pos) [source]

Sends a UltimateListEvent for the parent window.

Parameters:
  • eventType – the event type;
  • pos – an instance of wx.Point.

SetCustomRenderer(renderer=None) [source]

Associate a custom renderer with the header - all columns will use it

Parameters: renderer – a class able to correctly render header buttons

Note

the renderer class must implement the methods DrawHeaderButton and GetForegroundColor.

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • infobar
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • ultimatelistctrl »
  • UltimateListHeaderWindow


UltimateListItem

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • ultimatelistctrl »
  • UltimateListItem

UltimateListItem

This class stores information about a UltimateListCtrl item or column.

hierarchy Inheritance Diagram

Inheritance diagram for: UltimateListItem

Inheritance diagram of UltimateListItem

Methods Summary

__init__ | Default class constructor.
Attributes | Returns the associated attributes if they exist, or create a new UltimateListItemAttr
Check | Checks/unchecks an item.
CheckFooter | Checks/unchecks a footer item.
Clear | Resets the item state to the default.
ClearAttributes | Deletes the item attributes if they have been stored.
DeleteWindow | Deletes the window associated to the item (if any).
Enable | Enables or disables the item.
GetAlign | Returns the alignment for the item.
GetAttributes | Returns the associated UltimateListItemAttr attributes.
GetBackgroundColour | Returns the background colour.
GetColumn | Returns the zero-based column.
GetCustomRenderer | Returns the custom renderer associated with this item (if any).
GetData | Returns client data associated with the control.
GetFont | Returns the item font.
GetFooterAlign | Returns the alignment for the footer item.
GetFooterBackgroundColour | Returns the footer item background colour.
GetFooterFont | Returns the footer item font.
GetFooterFormat | Returns the footer item format.
GetFooterImage | Returns the zero-based index of the image associated with the footer item into
GetFooterKind | Returns the footer item kind.
GetFooterText | Returns the footer text.
GetFooterTextColour | Returns the footer item text colour.
GetFormat | Returns the header item format.
GetId | Returns the zero-based item position.
GetImage | Returns a Python list with the zero-based indexes of the images associated
GetKind | Returns the item kind.
GetMask | Returns a bit mask indicating which fields of the structure are valid.
GetOverFlow | Returns if the item is in the overflow state.
GetPyData | Returns data for the item, which can be any Python object.
GetState | Returns a bit field representing the state of the item.
GetText | Returns the label/header text.
GetTextColour | Returns the text colour.
GetToolTip | Returns the label/header tooltip.
GetVisited | Returns whether an hypertext item was visited or not.
GetWidth | Returns the column width.
GetWindow | Returns the window associated to the item.
GetWindowEnabled | Returns whether the associated window is enabled or not.
GetWindowSize | Returns the associated window size.
HasAttributes | Returns True if the item has attributes associated with it.
Init | Initializes an empty UltimateListItem.
IsChecked | Returns whether the item is checked or not.
IsEnabled | Returns True if the item is enabled.
IsFooterChecked | Returns whether the footer item is checked or not.
IsHyperText | Returns whether the item is hypetext or not.
IsShown | Returns True if the item is shown, or False if it is hidden.
OnSetFocus | Handles the wx.EVT_SET_FOCUS event for the window associated to an item.
SetAlign | Sets the alignment for the item.
SetBackgroundColour | Sets the background colour for the item.
SetColumn | Sets the zero-based column.
SetCustomRenderer | Associate a custom renderer to this item.
SetData | Sets client data for the item.
SetFont | Sets the font for the item.
SetFooterAlign | Sets the alignment for the footer item.
SetFooterBackgroundColour | Sets the background colour for the footer item.
SetFooterFont | Sets the font for the footer item.
SetFooterFormat | Sets the footer item format.
SetFooterImage | Sets the zero-based index of the image associated with the footer item into the image list.
SetFooterKind | Sets the footer item kind.
SetFooterText | Sets the text label for the footer item.
SetFooterTextColour | Sets the text colour for the footer item.
SetHyperText | Sets whether the item is hypertext or not.
SetId | Sets the zero-based item position.
SetImage | Sets the zero-based indexes of the images associated with the item into the image list.
SetKind | Sets the item kind.
SetMask | Sets the mask of valid fields.
SetOverFlow | Sets the item in the overflow/non overflow state.
SetPyData | Sets data for the item, which can be any Python object.
SetShown | Sets an item as shown/hidden.
SetState | Sets the item state flags.
SetStateMask | Sets the bitmask that is used to determine which of the state flags are to be set.
SetText | Sets the text label for the item.
SetTextColour | Sets the text colour for the item.
SetToolTip | Sets the tooltip text for the item.
SetVisited | Sets whether an hypertext item was visited or not.
SetWidth | Sets the column width.
SetWindow | Sets the window associated to the item.
SetWindowEnabled | Sets whether the associated window is enabled or not.

API Class API

class UltimateListItem(wx.Object) [source]

This class stores information about a UltimateListCtrl item or column.

__init__(item=None) [source]

Default class constructor.

Parameters: item – if not None, another instance of UltimateListItem.

Attributes() [source]

Returns the associated attributes if they exist, or create a new UltimateListItemAttr structure and associate it with this item.

Check(checked=True) [source]

Checks/unchecks an item.

Parameters: checked – True to check an item, False to uncheck it.

Note

This method is meaningful only for check and radio items.

CheckFooter(checked=True) [source]

Checks/unchecks a footer item.

Parameters: checked – True to check an item, False to uncheck it.

Note

This method is meaningful only for check and radio footer items.

Clear() [source]

Resets the item state to the default.

ClearAttributes() [source]

Deletes the item attributes if they have been stored.

DeleteWindow() [source]

Deletes the window associated to the item (if any).

Enable(enable=True) [source]

Enables or disables the item.

Parameters: enable – True to enable the item, False to disable it.

GetAlign() [source]

Returns the alignment for the item.

See also

SetAlign for a list of valid alignment bits.

GetAttributes() [source]

Returns the associated UltimateListItemAttr attributes.

GetBackgroundColour() [source]

Returns the background colour.

GetColumn() [source]

Returns the zero-based column.

Note

This method is meaningful only in report mode.

GetCustomRenderer() [source]

Returns the custom renderer associated with this item (if any).

GetData() [source]

Returns client data associated with the control.

Note

Please note that client data is associated with the item and not with subitems.

GetFont() [source]

Returns the item font.

GetFooterAlign() [source]

Returns the alignment for the footer item.

See also

SetAlign for a list of valid alignment flags.

GetFooterBackgroundColour() [source]

Returns the footer item background colour.

GetFooterFont() [source]

Returns the footer item font.

GetFooterFormat() [source]

Returns the footer item format.

GetFooterImage() [source]

Returns the zero-based index of the image associated with the footer item into the image list.

GetFooterKind() [source]

Returns the footer item kind.

See also

SetKind for a list of valid items kind.

GetFooterText() [source]

Returns the footer text.

GetFooterTextColour() [source]

Returns the footer item text colour.

GetFormat() [source]

Returns the header item format.

GetId() [source]

Returns the zero-based item position.

GetImage() [source]

Returns a Python list with the zero-based indexes of the images associated with the item into the image list.

GetKind() [source]

Returns the item kind.

See also

SetKind for a valid list of item’s kind.

GetMask() [source]

Returns a bit mask indicating which fields of the structure are valid.

See also

SetMask for a list of valid bit masks.

GetOverFlow() [source]

Returns if the item is in the overflow state.

An item/subitem may overwrite neighboring items/subitems if its text would not normally fit in the space allotted to it.

GetPyData() [source]

Returns data for the item, which can be any Python object.

Note

Please note that Python data is associated with the item and not with subitems.

GetState() [source]

Returns a bit field representing the state of the item.

See also

SetState for a list of valid item states.

GetText() [source]

Returns the label/header text.

GetTextColour() [source]

Returns the text colour.

GetToolTip() [source]

Returns the label/header tooltip.

GetVisited() [source]

Returns whether an hypertext item was visited or not.

GetWidth() [source]

Returns the column width.

Note

This method is meaningful only for column headers in report mode.

GetWindow() [source]

Returns the window associated to the item.

GetWindowEnabled() [source]

Returns whether the associated window is enabled or not.

GetWindowSize() [source]

Returns the associated window size.

HasAttributes() [source]

Returns True if the item has attributes associated with it.

Init() [source]

Initializes an empty UltimateListItem.

IsChecked() [source]

Returns whether the item is checked or not.

IsEnabled() [source]

Returns True if the item is enabled.

IsFooterChecked() [source]

Returns whether the footer item is checked or not.

IsHyperText() [source]

Returns whether the item is hypetext or not.

IsShown() [source]

Returns True if the item is shown, or False if it is hidden.

OnSetFocus(event) [source]

Handles the wx.EVT_SET_FOCUS event for the window associated to an item.

Parameters: event – a wx.FocusEvent event to be processed.

SetAlign(align) [source]

Sets the alignment for the item.

Parameters: align – one of the following bits:

Alignment Bits | Hex Value | Description
ULC_FORMAT_LEFT | 0x0 | The item is left-aligned
ULC_FORMAT_RIGHT | 0x1 | The item is right-aligned
ULC_FORMAT_CENTRE | 0x2 | The item is centre-aligned
ULC_FORMAT_CENTER | 0x2 | The item is center-aligned

SetBackgroundColour(colBack) [source]

Sets the background colour for the item.

Parameters: colBack – a valid wx.Colour object.

SetColumn(col) [source]

Sets the zero-based column.

Parameters: col – the zero-based column.

Note

This method is neaningful only in report mode.

SetCustomRenderer(renderer) [source]

Associate a custom renderer to this item.

Parameters: renderer – a class able to correctly render the item.

Note

the renderer class must implement the methods DrawSubItem, GetLineHeight and GetSubItemWidth.

SetData(data) [source]

Sets client data for the item.

Parameters: data – the client data associated to the item.

Note

Please note that client data is associated with the item and not with subitems.

SetFont(font) [source]

Sets the font for the item.

Parameters: font – a valid wx.Font object.

SetFooterAlign(align) [source]

Sets the alignment for the footer item.

See also

SetAlign for a list of valid alignment flags.

SetFooterBackgroundColour(colBack) [source]

Sets the background colour for the footer item.

Parameters: colBack – a valid wx.Colour object.

SetFooterFont(font) [source]

Sets the font for the footer item.

Parameters: font – a valid wx.Font object.

SetFooterFormat(format) [source]

Sets the footer item format.

Parameters: format – the footer item format.

SetFooterImage(image) [source]

Sets the zero-based index of the image associated with the footer item into the image list.

Parameters: image – the zero-based index of the image associated with the footer item into the image list.

SetFooterKind(kind) [source]

Sets the footer item kind.

See also

SetKind for a list of valid items kind.

SetFooterText(text) [source]

Sets the text label for the footer item.

Parameters: text – the text label for the footer item.

SetFooterTextColour(colText) [source]

Sets the text colour for the footer item.

Parameters: colText – a valid wx.Colour object.

SetHyperText(hyper=True) [source]

Sets whether the item is hypertext or not.

Parameters: hyper – True to set hypertext behaviour, False otherwise.

SetId(id) [source]

Sets the zero-based item position.

Parameters: id – the zero-based item position.

SetImage(image) [source]

Sets the zero-based indexes of the images associated with the item into the image list.

Parameters: image – a Python list with the zero-based indexes of the images associated with the item into the image list.

SetKind(kind) [source]

Sets the item kind.

Parameters: kind – may be one of the following integers:

Item Kind | Description
0 | A normal item
1 | A checkbox-like item
2 | A radiobutton-type item

SetMask(mask) [source]

Sets the mask of valid fields.

Parameters: mask – any combination of the following bits:

Mask Bits | Hex Value | Description
ULC_MASK_STATE | 0x1 | GetState is valid
ULC_MASK_TEXT | 0x2 | GetText is valid
ULC_MASK_IMAGE | 0x4 | GetImage is valid
ULC_MASK_DATA | 0x8 | GetData is valid
ULC_MASK_WIDTH | 0x20 | GetWidth is valid
ULC_MASK_FORMAT | 0x40 | GetFormat is valid
ULC_MASK_FONTCOLOUR | 0x80 | GetTextColour is valid
ULC_MASK_FONT | 0x100 | GetFont is valid
ULC_MASK_BACKCOLOUR | 0x200 | GetBackgroundColour is valid
ULC_MASK_KIND | 0x400 | GetKind is valid
ULC_MASK_ENABLE | 0x800 | IsEnabled is valid
ULC_MASK_CHECK | 0x1000 | IsChecked is valid
ULC_MASK_HYPERTEXT | 0x2000 | IsHyperText is valid
ULC_MASK_WINDOW | 0x4000 | GetWindow is valid
ULC_MASK_PYDATA | 0x8000 | GetPyData is valid
ULC_MASK_SHOWN | 0x10000 | IsShown is valid
ULC_MASK_RENDERER | 0x20000 | GetCustomRenderer is valid
ULC_MASK_OVERFLOW | 0x40000 | GetOverFlow is valid
ULC_MASK_FOOTER_TEXT | 0x80000 | GetFooterText is valid
ULC_MASK_FOOTER_IMAGE | 0x100000 | GetFooterImage is valid
ULC_MASK_FOOTER_FORMAT | 0x200000 | GetFooterFormat is valid
ULC_MASK_FOOTER_FONT | 0x400000 | GetFooterFont is valid
ULC_MASK_FOOTER_CHECK | 0x800000 | IsFooterChecked is valid
ULC_MASK_FOOTER_KIND | 0x1000000 | GetFooterKind is valid

SetOverFlow(over=True) [source]

Sets the item in the overflow/non overflow state.

An item/subitem may overwrite neighboring items/subitems if its text would not normally fit in the space allotted to it.

Parameters: over – True to set the item in a overflow state, False otherwise.

SetPyData(pyData) [source]

Sets data for the item, which can be any Python object.

Parameters: data – any Python object associated to the item.

Note

Please note that Python data is associated with the item and not with subitems.

SetShown(shown=True) [source]

Sets an item as shown/hidden.

Parameters: shown – True to show the item, False to hide it.

SetState(state) [source]

Sets the item state flags.

Parameters: state – any combination of the following bits:

State Bits | Hex Value | Description
ULC_STATE_DONTCARE | 0x0 | Don’t care what the state is
ULC_STATE_DROPHILITED | 0x1 | The item is highlighted to receive a drop event
ULC_STATE_FOCUSED | 0x2 | The item has the focus
ULC_STATE_SELECTED | 0x4 | The item is selected
ULC_STATE_CUT | 0x8 | The item is in the cut state
ULC_STATE_DISABLED | 0x10 | The item is disabled
ULC_STATE_FILTERED | 0x20 | The item has been filtered
ULC_STATE_INUSE | 0x40 | The item is in use
ULC_STATE_PICKED | 0x80 | The item has been picked
ULC_STATE_SOURCE | 0x100 | The item is a drag and drop source

Note

The valid state flags are influenced by the value of the state mask.

See also

SetStateMask

SetStateMask(stateMask) [source]

Sets the bitmask that is used to determine which of the state flags are to be set.

Parameters: stateMask – the state bitmask.

See also

SetState for a list of valid state bits.

SetText(text) [source]

Sets the text label for the item.

Parameters: text – the text label for the item.

SetTextColour(colText) [source]

Sets the text colour for the item.

Parameters: colText – a valid wx.Colour object.

SetToolTip(text) [source]

Sets the tooltip text for the item.

Parameters: text – the tooltip text for the item.

SetVisited(visited=True) [source]

Sets whether an hypertext item was visited or not.

Parameters: visited – True to set a hypertext item as visited, False otherwise.

SetWidth(width) [source]

Sets the column width.

Parameters: width – the column width.

Note

This method is meaningful only for column headers in report mode.

SetWindow(wnd, expand=False) [source]

Sets the window associated to the item.

Parameters:
  • wnd – a non-toplevel window to be displayed next to the item;
  • expand – True to expand the column where the item/subitem lives, so that the window will be fully visible.

SetWindowEnabled(enable=True) [source]

Sets whether the associated window is enabled or not.

Parameters: enable – True to enable the associated window, False to disable it.

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • infobar
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • ultimatelistctrl »
  • UltimateListItem


UltimateListItemAttr

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • ultimatelistctrl »
  • UltimateListItemAttr

UltimateListItemAttr

Represents the attributes (colour, font, ...) of a UltimateListCtrl UltimateListItem.

hierarchy Inheritance Diagram

Inheritance diagram for: UltimateListItemAttr

Inheritance diagram of UltimateListItemAttr

Methods Summary

__init__ | Default class constructor.
Enable | Enables or disables the item.
GetBackgroundColour | Returns the currently set background colour.
GetFont | Returns the currently set item font.
GetFooterBackgroundColour | Returns the currently set background colour for a footer item.
GetFooterFont | Returns the currently set font for a footer item.
GetFooterTextColour | Returns the currently set text colour for a footer item.
GetTextColour | Returns the currently set text colour.
HasBackgroundColour | Returns True if the currently set background colour is valid.
HasFont | Returns True if the currently set font is valid.
HasFooterBackgroundColour | Returns True if the currently set background colour for the footer item
HasFooterFont | Returns True if the currently set font for the footer item
HasFooterTextColour | Returns True if the currently set text colour for the footer item
HasTextColour | Returns True if the currently set text colour is valid.
IsEnabled | Returns True if the item is enabled.
SetBackgroundColour | Sets a new background colour.
SetFont | Sets a new font for the item.
SetFooterBackgroundColour | Sets a new footer item background colour.
SetFooterFont | Sets a new font for the footer item.
SetFooterTextColour | Sets a new footer item text colour.
SetTextColour | Sets a new text colour.

API Class API

class UltimateListItemAttr(object) [source]

Represents the attributes (colour, font, ...) of a UltimateListCtrl UltimateListItem.

__init__(colText=wx.NullColour, colBack=wx.NullColour, font=wx.NullFont, enabled=True, footerColText=wx.NullColour, footerColBack=wx.NullColour, footerFont=wx.NullFont) [source]

Default class constructor.

Parameters:
  • colText – the item text colour;
  • colBack – the item background colour;
  • font – the item font;
  • enabled – True if the item should be enabled, False if it is disabled;
  • footerColText – for footer items, the item text colour;
  • footerColBack – for footer items, the item background colour;
  • footerFont – for footer items, the item font.

Enable(enable=True) [source]

Enables or disables the item.

Parameters: enable – True to enable the item, False to disable it.

GetBackgroundColour() [source]

Returns the currently set background colour.

GetFont() [source]

Returns the currently set item font.

GetFooterBackgroundColour() [source]

Returns the currently set background colour for a footer item.

GetFooterFont() [source]

Returns the currently set font for a footer item.

GetFooterTextColour() [source]

Returns the currently set text colour for a footer item.

GetTextColour() [source]

Returns the currently set text colour.

HasBackgroundColour() [source]

Returns True if the currently set background colour is valid.

HasFont() [source]

Returns True if the currently set font is valid.

HasFooterBackgroundColour() [source]

Returns True if the currently set background colour for the footer item is valid.

HasFooterFont() [source]

Returns True if the currently set font for the footer item is valid.

HasFooterTextColour() [source]

Returns True if the currently set text colour for the footer item is valid.

HasTextColour() [source]

Returns True if the currently set text colour is valid.

IsEnabled() [source]

Returns True if the item is enabled.

SetBackgroundColour(colBack) [source]

Sets a new background colour.

Parameters: colBack – an instance of wx.Colour.

SetFont(font) [source]

Sets a new font for the item.

Parameters: font – an instance of wx.Font.

SetFooterBackgroundColour(colBack) [source]

Sets a new footer item background colour.

Parameters: colBack – an instance of wx.Colour.

SetFooterFont(font) [source]

Sets a new font for the footer item.

Parameters: font – an instance of wx.Font.

SetFooterTextColour(colText) [source]

Sets a new footer item text colour.

Parameters: colText – an instance of wx.Colour.

SetTextColour(colText) [source]

Sets a new text colour.

Parameters: colText – an instance of wx.Colour.

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • infobar
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • ultimatelistctrl »
  • UltimateListItemAttr


UltimateListItemData

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • ultimatelistctrl »
  • UltimateListItemData

UltimateListItemData

A simple class which holds information about UltimateListItem visual attributes (client rectangles, positions, etc...).

hierarchy Inheritance Diagram

Inheritance diagram for: UltimateListItemData

Inheritance diagram of UltimateListItemData

Methods Summary

__init__ | Default class constructor
Check | Checks/unchecks an item.
DeleteWindow | Deletes the window associated to the item (if any).
Enable | Enables or disables the item.
GetAttr | Returns the item attributes.
GetBackgroundColour | Returns the currently set background colour.
GetColour | Returns the currently set text colour.
GetCustomRenderer | Returns the custom renderer associated with this item (if any).
GetFont | Returns the currently set font.
GetHeight | Returns the item height, in pixels.
GetImage | Returns a Python list with the zero-based indexes of the images associated
GetItem | Returns information about the item.
GetKind | Returns the item kind.
GetOverFlow | Returns if the item is in the overflow state.
GetText | Returns the item text.
GetTextForMeasuring | Returns the item text or a simple string if the item text is the
GetToolTip | Returns the item tooltip.
GetVisited | Returns whether an hypertext item was visited or not.
GetWidth | Returns the item width, in pixels.
GetWindow | Returns the window associated to the item.
GetWindowEnabled | Returns whether the associated window is enabled or not.
GetWindowSize | Returns the associated window size.
GetX | Returns the item x position.
GetY | Returns the item y position.
HasBackgroundColour | Returns True if the currently set background colour is valid.
HasColour | Returns True if the currently set text colour is valid.
HasFont | Returns True if the currently set font is valid.
HasImage | Returns True if the item has at least one image associated with it.
HasText | Returns True if the item text is not the empty string.
Init | Initializes the item data structure.
IsChecked | Returns whether the item is checked or not.
IsEnabled | Returns True if the item is enabled, False if it is disabled.
IsHit | Returns True if the input position is inside the item client rectangle.
IsHyperText | Returns whether the item is hypetext or not.
SetAttr | Sets the item attributes.
SetBackgroundColour | Sets the background colour for the item.
SetColour | Sets the text colour for the item.
SetCustomRenderer | Associate a custom renderer to this item.
SetData | Sets client data for the item.
SetFont | Sets the text font for the item.
SetHyperText | Sets whether the item is hypertext or not.
SetImage | Sets the zero-based indexes of the images associated with the item into the image list.
SetItem | Sets information about the item.
SetKind | Sets the item kind.
SetOverFlow | Sets the item in the overflow/non overflow state.
SetPosition | Sets the item position.
SetSize | Sets the item size.
SetText | Sets the text label for the item.
SetToolTip | Sets the tooltip for the item
SetVisited | Sets whether an hypertext item was visited or not.
SetWindow | Sets the window associated to the item.
SetWindowEnabled | Sets whether the associated window is enabled or not.

API Class API

class UltimateListItemData(object) [source]

A simple class which holds information about UltimateListItem visual attributes (client rectangles, positions, etc...).

__init__(owner) [source]

Default class constructor

Parameters: owner – an instance of UltimateListCtrl.

Check(checked=True) [source]

Checks/unchecks an item.

Parameters: checked – True to check an item, False to uncheck it.

Note

This method is meaningful only for check and radio items.

DeleteWindow() [source]

Deletes the window associated to the item (if any).

Enable(enable=True) [source]

Enables or disables the item.

Parameters: enable – True to enable the item, False to disable it.

GetAttr() [source]

Returns the item attributes.

GetBackgroundColour() [source]

Returns the currently set background colour.

GetColour() [source]

Returns the currently set text colour.

GetCustomRenderer() [source]

Returns the custom renderer associated with this item (if any).

GetFont() [source]

Returns the currently set font.

GetHeight() [source]

Returns the item height, in pixels.

GetImage() [source]

Returns a Python list with the zero-based indexes of the images associated with the item into the image list.

GetItem(info) [source]

Returns information about the item.

Parameters: info – an instance of UltimateListItemData.

GetKind() [source]

Returns the item kind.

See also

SetKind for a list of valid item kinds.

GetOverFlow() [source]

Returns if the item is in the overflow state.

An item/subitem may overwrite neighboring items/subitems if its text would not normally fit in the space allotted to it.

GetText() [source]

Returns the item text.

GetTextForMeasuring() [source]

Returns the item text or a simple string if the item text is the empty string.

GetToolTip() [source]

Returns the item tooltip.

GetVisited() [source]

Returns whether an hypertext item was visited or not.

GetWidth() [source]

Returns the item width, in pixels.

GetWindow() [source]

Returns the window associated to the item.

GetWindowEnabled() [source]

Returns whether the associated window is enabled or not.

GetWindowSize() [source]

Returns the associated window size.

GetX() [source]

Returns the item x position.

GetY() [source]

Returns the item y position.

HasBackgroundColour() [source]

Returns True if the currently set background colour is valid.

HasColour() [source]

Returns True if the currently set text colour is valid.

HasFont() [source]

Returns True if the currently set font is valid.

HasImage() [source]

Returns True if the item has at least one image associated with it.

HasText() [source]

Returns True if the item text is not the empty string.

Init() [source]

Initializes the item data structure.

IsChecked() [source]

Returns whether the item is checked or not.

IsEnabled() [source]

Returns True if the item is enabled, False if it is disabled.

IsHit(x, y) [source]

Returns True if the input position is inside the item client rectangle.

Parameters:
  • x – the x mouse position;
  • y – the y mouse position.

IsHyperText() [source]

Returns whether the item is hypetext or not.

SetAttr(attr) [source]

Sets the item attributes.

Parameters: attr – an instance of UltimateListItemAttr.

SetBackgroundColour(colour) [source]

Sets the background colour for the item.

Parameters: colour – an instance of wx.Colour.

SetColour(colour) [source]

Sets the text colour for the item.

Parameters: colour – an instance of wx.Colour.

SetCustomRenderer(renderer) [source]

Associate a custom renderer to this item.

Parameters: renderer – a class able to correctly render the item.

Note

the renderer class must implement the methods DrawSubItem, GetLineHeight and GetSubItemWidth.

SetData(data) [source]

Sets client data for the item.

Parameters: data – the client data associated to the item.

Note

Please note that client data is associated with the item and not with subitems.

SetFont(font) [source]

Sets the text font for the item.

Parameters: font – an instance of wx.Font.

SetHyperText(hyper=True) [source]

Sets whether the item is hypertext or not.

Parameters: hyper – True to set hypertext behaviour, False otherwise.

SetImage(image) [source]

Sets the zero-based indexes of the images associated with the item into the image list.

Parameters: image – a Python list with the zero-based indexes of the images associated with the item into the image list.

SetItem(info) [source]

Sets information about the item.

Parameters: info – an instance of UltimateListItemData.

SetKind(kind) [source]

Sets the item kind.

Parameters: kind – may be one of the following integers:

Item Kind | Description
0 | A normal item
1 | A checkbox-like item
2 | A radiobutton-type item

SetOverFlow(over=True) [source]

Sets the item in the overflow/non overflow state.

An item/subitem may overwrite neighboring items/subitems if its text would not normally fit in the space allotted to it.

Parameters: over – True to set the item in a overflow state, False otherwise.

SetPosition(x, y) [source]

Sets the item position.

Parameters:
  • x – the item x position;
  • y – the item y position.

SetSize(width, height) [source]

Sets the item size.

Parameters:
  • width – the item width, in pixels;
  • height – the item height, in pixels.

SetText(text) [source]

Sets the text label for the item.

Parameters: text – the text label for the item.

SetToolTip(tooltip) [source]

Sets the tooltip for the item

Parameters: tooltip – the tooltip text

SetVisited(visited=True) [source]

Sets whether an hypertext item was visited or not.

Parameters: visited – True to set a hypertext item as visited, False otherwise.

SetWindow(wnd, expand=False) [source]

Sets the window associated to the item.

Parameters:
  • wnd – a non-toplevel window to be displayed next to the item;
  • expand – True to expand the column where the item/subitem lives, so that the window will be fully visible.

SetWindowEnabled(enable=True) [source]

Sets whether the associated window is enabled or not.

Parameters: enable – True to enable the associated window, False to disable it.

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • infobar
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • ultimatelistctrl »
  • UltimateListItemData


UltimateListLineData

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • ultimatelistctrl »
  • UltimateListLineData

UltimateListLineData

A simple class which holds line geometries for UltimateListCtrl.

hierarchy Inheritance Diagram

Inheritance diagram for: UltimateListLineData

Inheritance diagram of UltimateListLineData

Methods Summary

__init__ | Default class constructor.
CalculateSize | Calculates the line size and item positions.
Check | Checks/unchecks an item.
Draw | Draws the line on the specified device context.
DrawHorizontalGradient | Gradient fill from colour 1 to colour 2 from left to right.
DrawInReportMode | Draws the line on the specified device context when the parent UltimateListCtrl
DrawTextFormatted | Draws the item text, correctly formatted.
DrawVerticalGradient | Gradient fill from colour 1 to colour 2 from top to bottom.
DrawVistaRectangle | Draws the selected item(s) with the Windows Vista style.
GetAttr | Returns an instance of UltimateListItemAttr associated with the first item
GetHeight | Returns the line height, in pixels.
GetImage | Returns a Python list with the zero-based indexes of the images associated
GetItem | Returns information about the item.
GetKind | Returns the item kind.
GetMode | Returns the current highlighting mode.
GetText | Returns the item text at the position index.
GetToolTip | Returns the item tooltip at the position index.
GetWidth | Returns the line width.
GetX | Returns the line x position.
GetY | Returns the line y position.
HasImage | Returns True if the first item in the line has at least one image
HasMode | Returns True if the parent UltimateListCtrl has the window
HasText | Returns True if the text of first item in the line is not the empty
HideItemWindow | If the input item has a window associated with it, hide it.
Highlight | Sets the current line as highlighted or not highlighted.
InReportView | Returns True if the parent UltimateListCtrl is in report view.
InitItems | Initializes the list of items.
IsChecked | Returns whether the item is checked or not.
IsHighlighted | Returns True if the line is highlighted.
IsVirtual | Returns True if the parent UltimateListCtrl has the ULC_VIRTUAL style set.
ResetDimensions | Resets the line dimensions (client rectangle).
ReverseHighlight | Reverses the line highlighting, switching it off if it was on and vice-versa.
SetAttr | Sets an instance of UltimateListItemAttr to the first item in the line.
SetAttributes | Sets various attributes to the input device context.
SetColour | Sets the text colour for the item.
SetHeight | Sets the line height.
SetImage | Sets the zero-based indexes of the images associated with the item into the image list.
SetItem | Sets information about the item.
SetKind | Sets the item kind.
SetPosition | Sets the line position.
SetReportView | Sets whether UltimateListLineData is in report view or not.
SetText | Sets the item text at the position index.
SetToolTip | Sets the item tooltip at the position index.
SetWidth | Sets the line width.
SetX | Sets the line x position.
SetY | Sets the line y position.

API Class API

class UltimateListLineData(object) [source]

A simple class which holds line geometries for UltimateListCtrl.

__init__(owner) [source]

Default class constructor.

Parameters: owner – an instance of UltimateListCtrl.

CalculateSize(dc, spacing) [source]

Calculates the line size and item positions.

Parameters:
  • dc – an instance of wx.DC;
  • spacing – the spacing between the items, in pixels.

Check(index, checked=True) [source]

Checks/unchecks an item.

Parameters:
  • index – the index of the item;
  • checked – True to check an item, False to uncheck it.

Note

This method is meaningful only for check and radio items.

Draw(line, dc) [source]

Draws the line on the specified device context.

Parameters:
  • line – an instance of UltimateListLineData;
  • dc – an instance of wx.DC.

DrawHorizontalGradient(dc, rect, hasfocus) [source]

Gradient fill from colour 1 to colour 2 from left to right.

Parameters:
  • dc – an instance of wx.DC;

  • rect – the rectangle to be filled with the gradient shading;
  • hasfocus – True if the main UltimateListCtrl has focus, False otherwise.

DrawInReportMode(dc, line, rect, rectHL, highlighted, current, enabled, oldPN, oldBR) [source]

Draws the line on the specified device context when the parent UltimateListCtrl is in report mode.

Parameters:
  • dc – an instance of wx.DC;

  • line – an instance of UltimateListLineData;
  • rect – the item client rectangle;
  • rectHL – the item client rectangle when the item is highlighted;
  • highlighted – True if the item is highlighted, False otherwise;
  • current – True if the item is the current item;
  • enabled – True if the item is enabled, False otherwise;
  • oldPN – an instance of wx.Pen, to save and restore at the end of the drawing;
  • oldBR – an instance of wx.Brush, to save and restore at the end of the drawing.

DrawTextFormatted(dc, text, row, col, itemRect, overflow) [source]

Draws the item text, correctly formatted.

Parameters:
  • dc – an instance of wx.DC;

  • text – the item text;
  • row – the line number to which this item belongs to;
  • col – the column number to which this item belongs to;
  • itemRect – the item client rectangle;
  • overflow – True if the item should overflow into neighboring columns, False otherwise.

DrawVerticalGradient(dc, rect, hasfocus) [source]

Gradient fill from colour 1 to colour 2 from top to bottom.

Parameters:
  • dc – an instance of wx.DC;

  • rect – the rectangle to be filled with the gradient shading;
  • hasfocus – True if the main UltimateListCtrl has focus, False otherwise.

DrawVistaRectangle(dc, rect, hasfocus) [source]

Draws the selected item(s) with the Windows Vista style.

Parameters:
  • dc – an instance of wx.DC;

  • rect – the rectangle to be filled with the gradient shading;
  • hasfocus – True if the main UltimateListCtrl has focus, False otherwise.

GetAttr() [source]

Returns an instance of UltimateListItemAttr associated with the first item in the line.

GetHeight() [source]

Returns the line height, in pixels.

GetImage(index=0) [source]

Returns a Python list with the zero-based indexes of the images associated with the item into the image list.

Parameters: index – the index of the item.

GetItem(index, info) [source]

Returns information about the item.

Parameters:
  • index – the index of the item;
  • info – an instance of UltimateListItem.

GetKind(index=0) [source]

Returns the item kind.

Parameters: index – the index of the item.

See also

SetKind for a list of valid item kinds.

GetMode() [source]

Returns the current highlighting mode.

GetText(index) [source]

Returns the item text at the position index.

Parameters: index – the index of the item.

GetToolTip(index) [source]

Returns the item tooltip at the position index.

Parameters: index – the index of the item.

GetWidth() [source]

Returns the line width.

GetX() [source]

Returns the line x position.

GetY() [source]

Returns the line y position.

HasImage(col=0) [source]

Returns True if the first item in the line has at least one image associated with it.

HasMode(mode) [source]

Returns True if the parent UltimateListCtrl has the window style specified by mode.

Parameters: mode – the window style to check.

HasText() [source]

Returns True if the text of first item in the line is not the empty string.

HideItemWindow(item) [source]

If the input item has a window associated with it, hide it.

Parameters: item – an instance of UltimateListItem.

Highlight(on) [source]

Sets the current line as highlighted or not highlighted.

Parameters: on – True to set the current line as highlighted, False otherwise.

InReportView() [source]

Returns True if the parent UltimateListCtrl is in report view.

InitItems(num) [source]

Initializes the list of items.

Parameters: num – the initial number of items to store.

IsChecked(index) [source]

Returns whether the item is checked or not.

Parameters: index – the index of the item.

IsHighlighted() [source]

Returns True if the line is highlighted.

IsVirtual() [source]

Returns True if the parent UltimateListCtrl has the ULC_VIRTUAL style set.

ResetDimensions() [source]

Resets the line dimensions (client rectangle).

ReverseHighlight() [source]

Reverses the line highlighting, switching it off if it was on and vice-versa.

SetAttr(attr) [source]

Sets an instance of UltimateListItemAttr to the first item in the line.

Parameters: attr – an instance of UltimateListItemAttr.

SetAttributes(dc, attr, highlighted) [source]

Sets various attributes to the input device context.

Parameters:
  • dc – an instance of wx.DC;

  • attr – an instance of UltimateListItemAttr;
  • highlighted – True if the item is highlighted, False otherwise.

SetColour(index, c) [source]

Sets the text colour for the item.

Parameters:
  • index – the index of the item;
  • c – an instance of wx.Colour.

SetHeight(height) [source]

Sets the line height.

Parameters: height – the new line height.

SetImage(index, image) [source]

Sets the zero-based indexes of the images associated with the item into the image list.

Parameters:
  • index – the index of the item;
  • image – a Python list with the zero-based indexes of the images associated with the item into the image list.

SetItem(index, info) [source]

Sets information about the item.

Parameters:
  • index – the index of the item;
  • info – an instance of UltimateListItem.

SetKind(index, kind=0) [source]

Sets the item kind.

Parameters:
  • index – the index of the item;
  • kind – may be one of the following integers:

    Item Kind | Description
    0 | A normal item
    1 | A checkbox-like item
    2 | A radiobutton-type item

SetPosition(x, y, spacing) [source]

Sets the line position.

Parameters:
  • x – the current x coordinate;
  • y – the current y coordinate;
  • spacing – the spacing between items, in pixels.

SetReportView(inReportView) [source]

Sets whether UltimateListLineData is in report view or not.

Parameters: inReportView – True to set UltimateListLineData in report view, False otherwise.

SetText(index, s) [source]

Sets the item text at the position index.

Parameters:
  • index – the index of the item;
  • s – the new item text.

SetToolTip(index, s) [source]

Sets the item tooltip at the position index.

Parameters:
  • index – the index of the item;
  • s – the new item tooltip.

SetWidth(width) [source]

Sets the line width.

Parameters: width – the new line width.

SetX(x) [source]

Sets the line x position.

Parameters: x – the new line x position.

SetY(y) [source]

Sets the line y position.

Parameters: y – the new line y position.

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • infobar
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • ultimatelistctrl »
  • UltimateListLineData


UltimateListMainWindow

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • ultimatelistctrl »
  • UltimateListMainWindow

UltimateListMainWindow

This is the main widget implementation of UltimateListCtrl.

hierarchy Inheritance Diagram

Inheritance diagram for: UltimateListMainWindow

Inheritance diagram of UltimateListMainWindow

Methods Summary

__init__ | Default class constructor.
AutoCheckChild | Checks/unchecks all the items.
AutoToggleChild | Toggles all the items.
CacheLineData | Saves the current line attributes.
ChangeCurrent | Changes the current line to the specified one.
CheckItem | Actually checks/uncheks an item, sending (eventually) the two
DeleteAllItems | Deletes all items in the UltimateListCtrl.
DeleteColumn | Deletes the specified column.
DeleteEverything | Deletes all items in the UltimateListCtrl, resetting column widths to zero.
DeleteItem | Deletes the specified item.
DeleteItemWindow | Deletes the window associated to an item (if any).
DoDeleteAllItems | Actually performs the deletion of all the items.
DoGetBestSize | Gets the size which best suits the window: for a control, it would be the
DragFinish | A drag and drop operation has just finished.
DrawCheckbox | Draws the item checkbox/radiobutton image.
DrawDnDArrow | Draws a drag and drop visual representation of an arrow.
DrawImage | Draws one of the item images.
EditLabel | Starts editing an item label.
EnableItem | Enables/disables an item.
EnableSelectionGradient | Globally enables/disables drawing of gradient selections.
EnableSelectionVista | Globally enables/disables drawing of Windows Vista selections.
EnsureVisible | Ensures this item is visible.
FindItem | Find an item whose label matches this string.
FindItemAtPos | Find an item nearest this position.
FindItemData | Find an item whose data matches this data.
GetBackgroundImage | Returns the UltimateListCtrl background image (if any).
GetCheckboxImageSize | Returns the checkbox/radiobutton image size.
GetColumn | Returns information about this column.
GetColumnCount | Returns the total number of columns in the UltimateListCtrl.
GetColumnCustomRenderer | Returns the custom renderer used to draw the column header
GetColumnWidth | Returns the column width for the input column.
GetControlBmp | Returns a native looking checkbox or radio button bitmap.
GetCountPerPage | Returns the number of items that can fit vertically in the visible area
GetDisabledTextColour | Returns the items disabled colour.
GetDummyLine | Returns a dummy line.
GetFirstGradientColour | Returns the first gradient colour for gradient-style selections.
GetGradientStyle | Returns the gradient style for gradient-style selections.
GetHeaderWidth | Returns the header window width, in pixels.
GetHighlightBrush | Returns the brush to use for the item highlighting.
GetHyperTextFont | Returns the font used to render an hypertext item.
GetHyperTextNewColour | Returns the colour used to render a non-visited hypertext item.
GetHyperTextVisitedColour | Returns the colour used to render a visited hypertext item.
GetImageSize | Returns the image size for the item.
GetItem | Returns the information about the input item.
GetItemCount | Returns the number of items in the UltimateListCtrl.
GetItemCustomRenderer | Returns the custom renderer used to draw the input item (if any).
GetItemKind | Returns the item kind.
GetItemOverFlow | Returns if the item is in the overflow state.
GetItemPosition | Returns the position of the item, in icon or small icon view.
GetItemRect | Returns the rectangle representing the item’s size and position, in physical coordinates.
GetItemSpacing | Returns the spacing between item texts and icons, in pixels.
GetItemState | Returns the item state flags for the input item.
GetItemText | Returns the item text.
GetItemTextSize | Returns the item width, in pixels, considering only the item text.
GetItemVisited | Returns whether an hypertext item was visited.
GetItemWidthWithImage | Returns the item width, in pixels, considering the item text and its images.
GetItemWindow | Returns the window associated to the item (if any).
GetItemWindowEnabled | Returns whether the window associated to the item is enabled.
GetLine | Returns the line data for the given index.
GetLineCheckboxRect | Returns the line client rectangle for the item checkbox image only.
GetLineHeight | Returns the line height for a specific item.
GetLineHighlightRect | Returns the line client rectangle when the line is highlighted.
GetLineIconRect | Returns the line client rectangle for the item image only.
GetLineLabelRect | Returns the line client rectangle for the item text only.
GetLineRect | Returns the line client rectangle.
GetLineSize | Returns the size of the total line client rectangle.
GetLineY | Returns the line y position.
GetListCtrl | Returns the parent widget, an instance of UltimateListCtrl.
GetMainWindowOfCompositeControl | Returns the UltimateListMainWindow parent.
GetNextActiveItem | Returns the next active item.
GetNextItem | Searches for an item with the given geometry or state, starting from item but excluding the item itself.
GetRuleColour | Returns the colour to be used for drawing the horizontal and vertical rules.
GetSecondGradientColour | Returns the second gradient colour for gradient-style selections.
GetSelectedItemCount | Returns the number of selected items in UltimateListCtrl.
GetSubItemRect | Returns the rectangle representing the size and position, in physical coordinates, of the given subitem, i.e.
GetTextLength | Returns the text width for the input string.
GetTotalWidth | Returns the total width of the columns in UltimateListCtrl.
GetUserLineHeight | Returns the custom value for the UltimateListMainWindow item height, if previously set with
GetViewRect | Returns the rectangle taken by all items in the control.
GetVisibleLinesRange | Returns the range of visible items on screen.
GetWaterMark | Returns the UltimateListCtrl watermark image (if any), displayed in the
HandleHyperLink | Handles the hyperlink items, sending the EVT_LIST_ITEM_HYPERLINK event.
HasAGWFlag | Returns True if the window has the given flag bit set.
HasCurrent | Returns True if the current item has been set, either programmatically
HasFocus | Returns True if the window has focus.
HasFooter | Returns True if the footer window is shown.
HasHeader | Returns True if the header window is shown.
HideWindows | Hides the windows associated to the items.
HighlightAll | Highlights/unhighlights all the lines in UltimateListCtrl.
HighlightLine | Highlights a line in UltimateListCtrl.
HighlightLines | Highlights a range of lines in UltimateListCtrl.
HitTest | HitTest method for a UltimateListCtrl.
HitTestLine | HitTest method for a UltimateListCtrl line.
InReportView | Returns True if the window is in report mode.
InTileView | Returns True if the window is in tile mode (partially implemented).
Init | Initializes the UltimateListMainWindow widget.
InsertColumn | Inserts a column into UltimateListCtrl.
InsertItem | Inserts an item into UltimateListCtrl.
IsColumnShown | Returns True if the input column is shown, False if it is hidden.
IsEmpty | Returns True if the window has no items in it.
IsHighlighted | Returns True if the input line is highlighted.
IsItemChecked | Returns whether an item is checked or not.
IsItemEnabled | Returns whether an item is enabled or not.
IsItemHyperText | Returns whether an item is hypertext or not.
IsSingleSel | Returns True if we are in single selection mode, False if multi selection.
IsVirtual | Returns True if the window has the ULC_VIRTUAL style set.
MoveToFocus | Brings tyhe current item into view.
MoveToItem | Scrolls the input item into view.
OnArrowChar | Handles the keyboard arrows key events.
OnChar | Handles the wx.EVT_CHAR event for UltimateListMainWindow.
OnChildFocus | Handles the wx.EVT_CHILD_FOCUS event for UltimateListMainWindow.
OnCompareItems | Returns whether 2 lines have the same index.
OnEraseBackground | Handles the wx.EVT_ERASE_BACKGROUND event for UltimateListMainWindow.
OnHoverTimer | Handles the wx.EVT_TIMER event for UltimateListMainWindow.
OnKeyDown | Handles the wx.EVT_KEY_DOWN event for UltimateListMainWindow.
OnKeyUp | Handles the wx.EVT_KEY_UP event for UltimateListMainWindow.
OnKillFocus | Handles the wx.EVT_KILL_FOCUS event for UltimateListMainWindow.
OnMouse | Handles the wx.EVT_MOUSE_EVENTS event for UltimateListMainWindow.
OnPaint | Handles the wx.EVT_PAINT event for UltimateListMainWindow.
OnRenameAccept | Called by UltimateListTextCtrl, to accept the changes and to send the
OnRenameCancelled | Called by UltimateListTextCtrl, to cancel the changes and to send the
OnRenameTimer | The timer for renaming has expired.
OnScroll | Handles the wx.EVT_SCROLLWIN event for UltimateListMainWindow.
OnSetFocus | Handles the wx.EVT_SET_FOCUS event for UltimateListMainWindow.
PaintWaterMark | Draws a watermark at the bottom right of UltimateListCtrl.
RecalculatePositions | Recalculates all the items positions, and sets the scrollbars positions too.
RefreshAfter | Redraws all the lines after the input one.
RefreshAll | Refreshes the entire UltimateListCtrl.
RefreshLine | Redraws the input line.
RefreshLines | Redraws a range of lines in UltimateListCtrl.
RefreshSelected | Redraws the selected lines.
ResetCurrent | Resets the current item to None.
ResetLineDimensions | Resets the line dimensions, so that client rectangles and positions are recalculated.
ResetTextControl | Called by UltimateListTextCtrl when it marks itself for deletion.
ResetVisibleLinesRange | Forces us to recalculate the range of visible lines.
ResizeColumns | If ULC_AUTOSIZE_FILL was passed to UltimateListCtrl.SetColumnWidth() then
ReverseHighlight | Toggles the line state and refreshes it.
ScrollList | Scrolls the UltimateListCtrl.
SendNotify | Actually sends a UltimateListEvent.
SetBackgroundImage | Sets the UltimateListCtrl background image.
SetColumn | Sets information about this column.
SetColumnCustomRenderer | Associate a custom renderer to this column’s header :param col: the column index.
SetColumnWidth | Sets the column width.
SetDisabledTextColour | Sets the items disabled colour.
SetFirstGradientColour | Sets the first gradient colour for gradient-style selections.
SetFont | Overridden base class virtual to reset the line height when the font changes.
SetGradientStyle | Sets the gradient style for gradient-style selections.
SetHyperTextFont | Sets the font used to render hypertext items.
SetHyperTextNewColour | Sets the colour used to render a non-visited hypertext item.
SetHyperTextVisitedColour | Sets the colour used to render a visited hypertext item.
SetImageList | Sets the image list associated with the control.
SetImageListCheck | Sets the checkbox/radiobutton image list.
SetItem | Sets information about the item.
SetItemCount | This method can only be used with virtual UltimateListCtrl. It is used to
SetItemCustomRenderer | Associate a custom renderer to this item.
SetItemHyperText | Sets whether the item is hypertext or not.
SetItemKind | Sets the item kind.
SetItemOverFlow | Sets the item in the overflow/non overflow state.
SetItemSpacing | Sets the spacing between item texts and icons.
SetItemState | Sets the item state flags for the input item.
SetItemStateAll | Sets the item state flags for all the items.
SetItemText | Sets the item text.
SetItemVisited | Sets whether an hypertext item was visited.
SetItemWindow | Sets the window for the given item.
SetItemWindowEnabled | Enables/disables the window associated to the item.
SetReportView | Sets whether UltimateListCtrl is in report view or not.
SetSecondGradientColour | Sets the second gradient colour for gradient-style selections.
SetUserLineHeight | Sets a custom value for the UltimateListMainWindow item height.
SetWaterMark | Sets the UltimateListCtrl watermark image to be displayed in the bottom
SortItems | Call this function to sort the items in the UltimateListCtrl. Sorting is done
TileBackground | Tiles the background image to fill all the available area.
UpdateCurrent | Updates the current line selection.

API Class API

class UltimateListMainWindow(wx.PyScrolledWindow) [source]

This is the main widget implementation of UltimateListCtrl.

__init__(parent, id, pos=wx.DefaultPosition, size=wx.DefaultSize, style=0, agwStyle=0, name="listctrlmainwindow") [source]

Default class constructor.

Parameters:
  • parent – parent window. Must not be None;
  • id – window identifier. A value of -1 indicates a default value;
  • pos – the control position. A value of (-1, -1) indicates a default position, chosen by either the windowing system or wxPython, depending on platform;
  • size – the control size. A value of (-1, -1) indicates a default size, chosen by either the windowing system or wxPython, depending on platform;
  • style – the underlying wx.PyScrolledWindow window style;
  • agwStyle – the AGW-specific window style; can be almost any combination of the following bits:

    Window Styles | Hex Value | Description
    ULC_VRULES | 0x1 | Draws light vertical rules between rows in report mode.
    ULC_HRULES | 0x2 | Draws light horizontal rules between rows in report mode.
    ULC_ICON | 0x4 | Large icon view, with optional labels.
    ULC_SMALL_ICON | 0x8 | Small icon view, with optional labels.
    ULC_LIST | 0x10 | Multicolumn list view, with optional small icons. Columns are computed automatically, i.e. you don’t set columns as in ULC_REPORT. In other words, the list wraps, unlike a wx.ListBox.
    ULC_REPORT | 0x20 | Single or multicolumn report view, with optional header.
    ULC_ALIGN_TOP | 0x40 | Icons align to the top. Win32 default, Win32 only.
    ULC_ALIGN_LEFT | 0x80 | Icons align to the left.
    ULC_AUTOARRANGE | 0x100 | Icons arrange themselves. Win32 only.
    ULC_VIRTUAL | 0x200 | The application provides items text on demand. May only be used with ULC_REPORT.
    ULC_EDIT_LABELS | 0x400 | Labels are editable: the application will be notified when editing starts.
    ULC_NO_HEADER | 0x800 | No header in report mode.
    ULC_NO_SORT_HEADER | 0x1000 | No Docs.
    ULC_SINGLE_SEL | 0x2000 | Single selection (default is multiple).
    ULC_SORT_ASCENDING | 0x4000 | Sort in ascending order. (You must still supply a comparison callback in wx.ListCtrl.SortItems.)
    ULC_SORT_DESCENDING | 0x8000 | Sort in descending order. (You must still supply a comparison callback in wx.ListCtrl.SortItems.)
    ULC_TILE | 0x10000 | Each item appears as a full-sized icon with a label of one or more lines beside it (partially implemented).
    ULC_NO_HIGHLIGHT | 0x20000 | No highlight when an item is selected.
    ULC_STICKY_HIGHLIGHT | 0x40000 | Items are selected by simply hovering on them, with no need to click on them.
    ULC_STICKY_NOSELEVENT | 0x80000 | Don’t send a selection event when using ULC_STICKY_HIGHLIGHT style.
    ULC_SEND_LEFTCLICK | 0x100000 | Send a left click event when an item is selected.
    ULC_HAS_VARIABLE_ROW_HEIGHT | 0x200000 | The list has variable row heights.
    ULC_AUTO_CHECK_CHILD | 0x400000 | When a column header has a checkbox associated, auto-check all the subitems in that column.
    ULC_AUTO_TOGGLE_CHILD | 0x800000 | When a column header has a checkbox associated, toggle all the subitems in that column.
    ULC_AUTO_CHECK_PARENT | 0x1000000 | Only meaningful foe checkbox-type items: when an item is checked/unchecked its column header item is checked/unchecked as well.
    ULC_SHOW_TOOLTIPS | 0x2000000 | Show tooltips for ellipsized items/subitems (text too long to be shown in the available space) containing the full item/subitem text.
    ULC_HOT_TRACKING | 0x4000000 | Enable hot tracking of items on mouse motion.
    ULC_BORDER_SELECT | 0x8000000 | Changes border colour whan an item is selected, instead of highlighting the item.
    ULC_TRACK_SELECT | 0x10000000 | Enables hot-track selection in a list control. Hot track selection means that an item is automatically selected when the cursor remains over the item for a certain period of time. The delay is retrieved on Windows using the win32api call win32gui.SystemParametersInfo(win32con.SPI_GETMOUSEHOVERTIME), and is defaulted to 400ms on other platforms. This style applies to all views of UltimateListCtrl.
    ULC_HEADER_IN_ALL_VIEWS | 0x20000000 | Show column headers in all view modes.
    ULC_NO_FULL_ROW_SELECT | 0x40000000 | When an item is selected, the only the item in the first column is highlighted.
    ULC_FOOTER | 0x80000000 | Show a footer too (only when header is present).
    ULC_USER_ROW_HEIGHT | 0x100000000 | Allows to set a custom row height (one value for all the items, only in report mode).
  • name – the window name.

AutoCheckChild(isChecked, column) [source]

Checks/unchecks all the items.

Parameters:
  • isChecked – True to check the items, False to uncheck them;
  • column – the column to which the items belongs to.

Note

This method is meaningful only for checkbox-like and radiobutton-like items.

AutoToggleChild(column) [source]

Toggles all the items.

Parameters: column – the column to which the items belongs to.

Note

This method is meaningful only for checkbox-like and radiobutton-like items.

CacheLineData(line) [source]

Saves the current line attributes.

Parameters: line – an instance of UltimateListLineData.

Note

This method is used only if the UltimateListCtrl has the ULC_VIRTUAL style set.

ChangeCurrent(current) [source]

Changes the current line to the specified one.

Parameters: current – an integer specifying the index of the current line.

CheckItem(item, checked=True, sendEvent=True) [source]

Actually checks/uncheks an item, sending (eventually) the two events EVT_LIST_ITEM_CHECKING / EVT_LIST_ITEM_CHECKED.

Parameters:
  • item – an instance of UltimateListItem;
  • checked – True to check an item, False to uncheck it;
  • sendEvent – True to send a {UltimateListEvent}, False otherwise.

Note

This method is meaningful only for checkbox-like and radiobutton-like items.

DeleteAllItems() [source]

Deletes all items in the UltimateListCtrl.

Note

This function does not send the EVT_LIST_DELETE_ITEM event because deleting many items from the control would be too slow then (unlike DeleteItem).

DeleteColumn(col) [source]

Deletes the specified column.

Parameters: col – the index of the column to delete.

DeleteEverything() [source]

Deletes all items in the UltimateListCtrl, resetting column widths to zero.

DeleteItem(lindex) [source]

Deletes the specified item.

Parameters: lindex – the index of the item to delete.

Note

This function sends the EVT_LIST_DELETE_ITEM event for the item being deleted.

DeleteItemWindow(item) [source]

Deletes the window associated to an item (if any).

Parameters: item – an instance of UltimateListItem.

DoDeleteAllItems() [source]

Actually performs the deletion of all the items.

DoGetBestSize() [source]

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

DragFinish(event) [source]

A drag and drop operation has just finished.

Parameters: event – a wx.MouseEvent event to be processed.

DrawCheckbox(dc, x, y, kind, checked, enabled) [source]

Draws the item checkbox/radiobutton image.

Parameters:
  • dc – an instance of wx.DC;
  • x – the x position where to draw the image;
  • y – the y position where to draw the image;
  • kind – may be one of the following integers:

    Item Kind | Description
    0 | A normal item
    1 | A checkbox-like item
    2 | A radiobutton-type item
  • checked – True if the item is checked, False otherwise;
  • enabled – True if the item is enabled, False if it is disabled.

DrawDnDArrow() [source]

Draws a drag and drop visual representation of an arrow.

DrawImage(index, dc, x, y, enabled) [source]

Draws one of the item images.

Parameters:
  • index – the index of the image inside the image list;
  • dc – an instance of wx.DC;

  • x – the x position where to draw the image;
  • y – the y position where to draw the image;
  • enabled – True if the item is enabled, False if it is disabled.

EditLabel(item) [source]

Starts editing an item label.

Parameters: item – an instance of UltimateListItem.

EnableItem(item, enable=True) [source]

Enables/disables an item.

Parameters:
  • item – an instance of UltimateListItem;
  • enable – True to enable the item, False otherwise.

EnableSelectionGradient(enable=True) [source]

Globally enables/disables drawing of gradient selections.

Parameters: enable – True to enable gradient-style selections, False to disable it.

Note

Calling this method disables any Vista-style selection previously enabled.

EnableSelectionVista(enable=True) [source]

Globally enables/disables drawing of Windows Vista selections.

Parameters: enable – True to enable Vista-style selections, False to disable it.

Note

Calling this method disables any gradient-style selection previously enabled.

EnsureVisible(index) [source]

Ensures this item is visible.

Parameters: index – the index of the item to scroll into view.

FindItem(start, string, partial=False) [source]

Find an item whose label matches this string.

Parameters:
  • start – the starting point of the input string or the beginning if start is -1;
  • string – the string to look for matches;
  • partial – if True then this method will look for items which begin with string.

Note

The string comparison is case insensitive.

FindItemAtPos(pt) [source]

Find an item nearest this position.

Parameters: pt – an instance of wx.Point.

FindItemData(start, data) [source]

Find an item whose data matches this data.

Parameters:
  • start – the starting point of the input data or the beginning if start is -1;
  • data – the data to look for matches.

GetBackgroundImage() [source]

Returns the UltimateListCtrl background image (if any).

Note

At present, the background image can only be used in “tile” mode.

Todo

Support background images also in stretch and centered modes.

GetCheckboxImageSize() [source]

Returns the checkbox/radiobutton image size.

GetColumn(col) [source]

Returns information about this column.

Parameters: col – an integer specifying the column index.

GetColumnCount() [source]

Returns the total number of columns in the UltimateListCtrl.

GetColumnCustomRenderer(col) [source]

Returns the custom renderer used to draw the column header

Parameters: col – the column index.

GetColumnWidth(col) [source]

Returns the column width for the input column.

Parameters: col – an integer specifying the column index.

GetControlBmp(checkbox=True, checked=False, enabled=True, x=16, y=16) [source]

Returns a native looking checkbox or radio button bitmap.

Parameters:
  • checkbox – True to get a checkbox image, False for a radiobutton one;
  • checked – True if the control is marked, False if it is not;
  • enabled – True if the control is enabled, False if it is not;
  • x – the width of the bitmap, in pixels;
  • y – the height of the bitmap, in pixels.

GetCountPerPage() [source]

Returns the number of items that can fit vertically in the visible area of the UltimateListCtrl (list or report view) or the total number of items in the list control (icon or small icon view).

GetDisabledTextColour() [source]

Returns the items disabled colour.

GetDummyLine() [source]

Returns a dummy line.

Note

This method is used only if the UltimateListCtrl has the ULC_VIRTUAL style set.

GetFirstGradientColour() [source]

Returns the first gradient colour for gradient-style selections.

GetGradientStyle() [source]

Returns the gradient style for gradient-style selections.

Returns: 0 for horizontal gradient-style selections, 1 for vertical gradient-style selections.

GetHeaderWidth() [source]

Returns the header window width, in pixels.

GetHighlightBrush() [source]

Returns the brush to use for the item highlighting.

GetHyperTextFont() [source]

Returns the font used to render an hypertext item.

GetHyperTextNewColour() [source]

Returns the colour used to render a non-visited hypertext item.

GetHyperTextVisitedColour() [source]

Returns the colour used to render a visited hypertext item.

GetImageSize(index) [source]

Returns the image size for the item.

Parameters: index – the image index.

GetItem(item, col=0) [source]

Returns the information about the input item.

Parameters:
  • item – an instance of UltimateListItem;
  • col – the column to which the item belongs to.

GetItemCount() [source]

Returns the number of items in the UltimateListCtrl.

GetItemCustomRenderer(item) [source]

Returns the custom renderer used to draw the input item (if any).

Parameters: item – an instance of UltimateListItem.

GetItemKind(item) [source]

Returns the item kind.

Parameters: item – an instance of UltimateListItem.

See also

SetItemKind for a list of valid item kinds.

GetItemOverFlow(item) [source]

Returns if the item is in the overflow state.

An item/subitem may overwrite neighboring items/subitems if its text would not normally fit in the space allotted to it.

Parameters: item – an instance of UltimateListItem.

GetItemPosition(item) [source]

Returns the position of the item, in icon or small icon view.

Parameters: item – the row in which the item lives.

GetItemRect(item) [source]

Returns the rectangle representing the item’s size and position, in physical coordinates.

Parameters: item – the row in which the item lives.

GetItemSpacing(isSmall=False) [source]

Returns the spacing between item texts and icons, in pixels.

Parameters: isSmall – True if using a wx.IMAGE_LIST_SMALL image list, False if using a wx.IMAGE_LIST_NORMAL image list.

GetItemState(item, stateMask) [source]

Returns the item state flags for the input item.

Parameters:
  • item – the index of the item;
  • stateMask – the bitmask for the state flag.

See also

SetItemStateAll for a list of valid state flags.

GetItemText(item) [source]

Returns the item text.

Parameters: item – an instance of UltimateListItem.

GetItemTextSize(item) [source]

Returns the item width, in pixels, considering only the item text.

Parameters: item – an instance of UltimateListItem.

GetItemVisited(item) [source]

Returns whether an hypertext item was visited.

Parameters: item – an instance of UltimateListItem.

GetItemWidthWithImage(item) [source]

Returns the item width, in pixels, considering the item text and its images.

Parameters: item – an instance of UltimateListItem.

GetItemWindow(item) [source]

Returns the window associated to the item (if any).

Parameters: item – an instance of UltimateListItem.

GetItemWindowEnabled(item) [source]

Returns whether the window associated to the item is enabled.

Parameters: item – an instance of UltimateListItem.

GetLine(n) [source]

Returns the line data for the given index.

Parameters: n – the line index.

GetLineCheckboxRect(line) [source]

Returns the line client rectangle for the item checkbox image only.

Parameters: line – an instance of UltimateListLineData.

GetLineHeight(item=None) [source]

Returns the line height for a specific item.

Parameters: item – if not None, an instance of UltimateListItem.

GetLineHighlightRect(line) [source]

Returns the line client rectangle when the line is highlighted.

Parameters: line – an instance of UltimateListLineData.

GetLineIconRect(line) [source]

Returns the line client rectangle for the item image only.

Parameters: line – an instance of UltimateListLineData.

GetLineLabelRect(line, col=0) [source]

Returns the line client rectangle for the item text only. Note this is the full column width unless an image or checkbox exists. It is not the width of the text itself

Parameters: line – an instance of UltimateListLineData.

GetLineRect(line) [source]

Returns the line client rectangle.

Parameters: line – an instance of UltimateListLineData.

GetLineSize(line) [source]

Returns the size of the total line client rectangle.

Parameters: line – an instance of UltimateListLineData.

GetLineY(line) [source]

Returns the line y position.

Parameters: line – an instance of UltimateListLineData.

GetListCtrl() [source]

Returns the parent widget, an instance of UltimateListCtrl.

GetMainWindowOfCompositeControl() [source]

Returns the UltimateListMainWindow parent.

GetNextActiveItem(item, down=True) [source]

Returns the next active item. Used Internally at present.

Parameters:
  • item – an instance of UltimateListItem;
  • down – True to search downwards for an active item, False to search upwards.

GetNextItem(item, geometry=ULC_NEXT_ALL, state=ULC_STATE_DONTCARE) [source]

Searches for an item with the given geometry or state, starting from item but excluding the item itself.

Parameters:
  • item – the item at which starting the search. If set to -1, the first item that matches the specified flags will be returned.
  • geometry – can be one of:

    Geometry Flag | Hex Value | Description
    ULC_NEXT_ABOVE | 0x0 | Searches for an item above the specified item
    ULC_NEXT_ALL | 0x1 | Searches for subsequent item by index
    ULC_NEXT_BELOW | 0x2 | Searches for an item below the specified item
    ULC_NEXT_LEFT | 0x3 | Searches for an item to the left of the specified item
    ULC_NEXT_RIGHT | 0x4 | Searches for an item to the right of the specified item
  • state – any combination of the following bits:

    State Bits | Hex Value | Description
    ULC_STATE_DONTCARE | 0x0 | Don’t care what the state is
    ULC_STATE_DROPHILITED | 0x1 | The item is highlighted to receive a drop event
    ULC_STATE_FOCUSED | 0x2 | The item has the focus
    ULC_STATE_SELECTED | 0x4 | The item is selected
    ULC_STATE_CUT | 0x8 | The item is in the cut state
    ULC_STATE_DISABLED | 0x10 | The item is disabled
    ULC_STATE_FILTERED | 0x20 | The item has been filtered
    ULC_STATE_INUSE | 0x40 | The item is in use
    ULC_STATE_PICKED | 0x80 | The item has been picked
    ULC_STATE_SOURCE | 0x100 | The item is a drag and drop source
Returns:

The first item with given state following item or -1 if no such item found.

Note

This function may be used to find all selected items in the control like this:

item = -1

while 1:
    item = listctrl.GetNextItem(item, ULC_NEXT_ALL, ULC_STATE_SELECTED)

    if item == -1:
        break

    # This item is selected - do whatever is needed with it

    wx.LogMessage("Item %ld is selected."%item)

GetRuleColour() [source]

Returns the colour to be used for drawing the horizontal and vertical rules.

GetSecondGradientColour() [source]

Returns the second gradient colour for gradient-style selections.

GetSelectedItemCount() [source]

Returns the number of selected items in UltimateListCtrl.

GetSubItemRect(item, subItem) [source]

Returns the rectangle representing the size and position, in physical coordinates, of the given subitem, i.e. the part of the row item in the column subItem.

Parameters:
  • item – the row in which the item lives;
  • subItem – the column in which the item lives. If set equal to the special value ULC_GETSUBITEMRECT_WHOLEITEM the return value is the same as for GetItemRect.

Note

This method is only meaningful when the UltimateListCtrl is in the report mode.

GetTextLength(s) [source]

Returns the text width for the input string.

Parameters: s – the string to measure.

GetTotalWidth() [source]

Returns the total width of the columns in UltimateListCtrl.

GetUserLineHeight() [source]

Returns the custom value for the UltimateListMainWindow item height, if previously set with SetUserLineHeight.

Note

This method can be used only with ULC_REPORT and ULC_USER_ROW_HEIGHT styles set.

GetViewRect() [source]

Returns the rectangle taken by all items in the control. In other words, if the controls client size were equal to the size of this rectangle, no scrollbars would be needed and no free space would be left.

Note

This function only works in the icon and small icon views, not in list or report views.

GetVisibleLinesRange() [source]

Returns the range of visible items on screen.

Note

This method can be used only if UltimateListCtrl has the ULC_REPORT style set.

GetWaterMark() [source]

Returns the UltimateListCtrl watermark image (if any), displayed in the bottom right part of the window.

Todo

Better support for this is needed.

HandleHyperLink(item) [source]

Handles the hyperlink items, sending the EVT_LIST_ITEM_HYPERLINK event.

Parameters: item – an instance of UltimateListItem.

HasAGWFlag(flag) [source]

Returns True if the window has the given flag bit set.

Parameters: flag – the bit to check.

See also

UltimateListCtrl.SetSingleStyle() for a list of valid flags.

HasCurrent() [source]

Returns True if the current item has been set, either programmatically or by user intervention.

HasFocus() [source]

Returns True if the window has focus.

HasFooter() [source]

Returns True if the footer window is shown.

HasHeader() [source]

Returns True if the header window is shown.

HideWindows() [source]

Hides the windows associated to the items. Used internally.

HighlightAll(on=True) [source]

Highlights/unhighlights all the lines in UltimateListCtrl.

Parameters: on – True to highlight all the lines, False to unhighlight them.

HighlightLine(line, highlight=True) [source]

Highlights a line in UltimateListCtrl.

Parameters:
  • line – an instance of UltimateListLineData;
  • highlight – True to highlight the line, False otherwise.

HighlightLines(lineFrom, lineTo, highlight=True) [source]

Highlights a range of lines in UltimateListCtrl.

Parameters:
  • lineFrom – an integer representing the first line to highlight;
  • lineTo – an integer representing the last line to highlight;
  • highlight – True to highlight the lines, False otherwise.

HitTest(x, y) [source]

HitTest method for a UltimateListCtrl.

Parameters:
  • x – the mouse x position;
  • y – the mouse y position.

See also

HitTestLine for a list of return flags.

HitTestLine(line, x, y) [source]

HitTest method for a UltimateListCtrl line.

Parameters:
  • line – an instance of UltimateListLineData;
  • x – the mouse x position;
  • y – the mouse y position.
Returns:

a tuple of values, representing the item hit and a hit flag. The hit flag can be one of the following bits:

HitTest Flag

Hex Value

Description

ULC_HITTEST_ABOVE

0x1

Above the client area

ULC_HITTEST_BELOW

0x2

Below the client area

ULC_HITTEST_NOWHERE

0x4

In the client area but below the last item

ULC_HITTEST_ONITEM

0x2a0

Anywhere on the item (text, icon, checkbox image)

ULC_HITTEST_ONITEMICON

0x20

On the bitmap associated with an item

ULC_HITTEST_ONITEMLABEL

0x80

On the label (string) associated with an item

ULC_HITTEST_ONITEMRIGHT

0x100

In the area to the right of an item

ULC_HITTEST_ONITEMSTATEICON

0x200

On the state icon for a list view item that is in a user-defined state

ULC_HITTEST_TOLEFT

0x400

To the left of the client area

ULC_HITTEST_TORIGHT

0x800

To the right of the client area

ULC_HITTEST_ONITEMCHECK

0x1000

On the item checkbox (if any)

InReportView() [source]

Returns True if the window is in report mode.

InTileView() [source]

Returns True if the window is in tile mode (partially implemented).

Todo

Fully implement tile view for UltimateListCtrl.

Init() [source]

Initializes the UltimateListMainWindow widget.

InsertColumn(col, item) [source]

Inserts a column into UltimateListCtrl.

Parameters:
  • col – the column index at which we wish to insert a new column;
  • item – an instance of UltimateListItem.

Note

This method is meaningful only if UltimateListCtrl has the ULC_REPORT or the ULC_TILE styles set.

InsertItem(item) [source]

Inserts an item into UltimateListCtrl.

Parameters: item – an instance of UltimateListItem.

IsColumnShown(column) [source]

Returns True if the input column is shown, False if it is hidden.

Parameters: column – an integer specifying the column index.

IsEmpty() [source]

Returns True if the window has no items in it.

IsHighlighted(line) [source]

Returns True if the input line is highlighted.

Parameters: line – an instance of UltimateListLineData.

IsItemChecked(item) [source]

Returns whether an item is checked or not.

Parameters: item – an instance of UltimateListItem.

IsItemEnabled(item) [source]

Returns whether an item is enabled or not.

Parameters: item – an instance of UltimateListItem.

IsItemHyperText(item) [source]

Returns whether an item is hypertext or not.

Parameters: item – an instance of UltimateListItem.

IsSingleSel() [source]

Returns True if we are in single selection mode, False if multi selection.

IsVirtual() [source]

Returns True if the window has the ULC_VIRTUAL style set.

MoveToFocus() [source]

Brings tyhe current item into view.

MoveToItem(item) [source]

Scrolls the input item into view.

Parameters: item – an instance of UltimateListItem.

OnArrowChar(newCurrent, event) [source]

Handles the keyboard arrows key events.

Parameters:
  • newCurrent – an integer specifying the new current item;
  • event – a wx.KeyEvent event to be processed.

OnChar(event) [source]

Handles the wx.EVT_CHAR event for UltimateListMainWindow.

Parameters: event – a wx.KeyEvent event to be processed.

OnChildFocus(event) [source]

Handles the wx.EVT_CHILD_FOCUS event for UltimateListMainWindow.

Parameters: event – a wx.ChildFocusEvent event to be processed.

Note

This method is intentionally empty to prevent the default handler in wx.PyScrolledWindow from needlessly scrolling the window when the edit control is dismissed.

OnCompareItems(line1, line2) [source]

Returns whether 2 lines have the same index.

Override this function in the derived class to change the sort order of the items in the UltimateListCtrl. The function should return a negative, zero or positive value if the first line is less than, equal to or greater than the second one.

Parameters:
  • line1 – an instance of UltimateListItem;
  • line2 – another instance of UltimateListItem.

Note

The base class version compares lines by their index.

OnEraseBackground(event) [source]

Handles the wx.EVT_ERASE_BACKGROUND event for UltimateListMainWindow.

Parameters: event – a wx.EraseEvent event to be processed.

Note

This method is intentionally empty to reduce flicker.

OnHoverTimer(event) [source]

Handles the wx.EVT_TIMER event for UltimateListMainWindow.

Parameters: event – a wx.TimerEvent event to be processed.

OnKeyDown(event) [source]

Handles the wx.EVT_KEY_DOWN event for UltimateListMainWindow.

Parameters: event – a wx.KeyEvent event to be processed.

OnKeyUp(event) [source]

Handles the wx.EVT_KEY_UP event for UltimateListMainWindow.

Parameters: event – a wx.KeyEvent event to be processed.

OnKillFocus(event) [source]

Handles the wx.EVT_KILL_FOCUS event for UltimateListMainWindow.

Parameters: event – a wx.FocusEvent event to be processed.

OnMouse(event) [source]

Handles the wx.EVT_MOUSE_EVENTS event for UltimateListMainWindow.

Parameters: event – a wx.MouseEvent event to be processed.

OnPaint(event) [source]

Handles the wx.EVT_PAINT event for UltimateListMainWindow.

Parameters: event – a wx.PaintEvent event to be processed.

OnRenameAccept(itemEdit, value) [source]

Called by UltimateListTextCtrl, to accept the changes and to send the EVT_LIST_END_LABEL_EDIT event.

Parameters:
  • itemEdit – an instance of UltimateListItem;
  • value – the new value of the item label.

OnRenameCancelled(itemEdit) [source]

Called by UltimateListTextCtrl, to cancel the changes and to send the EVT_LIST_END_LABEL_EDIT event.

Parameters: item – an instance of UltimateListItem.

OnRenameTimer() [source]

The timer for renaming has expired. Start editing.

OnScroll(event) [source]

Handles the wx.EVT_SCROLLWIN event for UltimateListMainWindow.

Parameters: event – a wx.ScrollEvent event to be processed.

OnSetFocus(event) [source]

Handles the wx.EVT_SET_FOCUS event for UltimateListMainWindow.

Parameters: event – a wx.FocusEvent event to be processed.

PaintWaterMark(dc) [source]

Draws a watermark at the bottom right of UltimateListCtrl.

Parameters: dc – an instance of wx.DC.

Todo

Better support for this is needed.

RecalculatePositions(noRefresh=False) [source]

Recalculates all the items positions, and sets the scrollbars positions too.

Parameters: noRefresh – True to avoid calling Refresh, False otherwise.

RefreshAfter(lineFrom) [source]

Redraws all the lines after the input one.

Parameters: lineFrom – an integer representing the first line to refresh.

RefreshAll() [source]

Refreshes the entire UltimateListCtrl.

RefreshLine(line) [source]

Redraws the input line.

Parameters: line – an instance of UltimateListLineData.

RefreshLines(lineFrom, lineTo) [source]

Redraws a range of lines in UltimateListCtrl.

Parameters:
  • lineFrom – an integer representing the first line to refresh;
  • lineTo – an integer representing the last line to refresh.

RefreshSelected() [source]

Redraws the selected lines.

ResetCurrent() [source]

Resets the current item to None.

ResetLineDimensions(force=False) [source]

Resets the line dimensions, so that client rectangles and positions are recalculated.

Parameters: force – True to reset all line dimensions.

ResetTextControl() [source]

Called by UltimateListTextCtrl when it marks itself for deletion.

ResetVisibleLinesRange(reset=False) [source]

Forces us to recalculate the range of visible lines.

Parameters: reset – True to reset all line dimensions, which will then be recalculated.

ResizeColumns() [source]

If ULC_AUTOSIZE_FILL was passed to UltimateListCtrl.SetColumnWidth() then that column’s width will be expanded to fill the window on a resize event.

Called by UltimateListCtrl.OnSize() when the window is resized.

ReverseHighlight(line) [source]

Toggles the line state and refreshes it.

Parameters: line – an instance of UltimateListLineData.

ScrollList(dx, dy) [source]

Scrolls the UltimateListCtrl.

Parameters:
  • dx – if in icon, small icon or report view mode, specifies the number of pixels to scroll. If in list view mode, dx specifies the number of columns to scroll.
  • dy – always specifies the number of pixels to scroll vertically.

SendNotify(line, command, point=wx.DefaultPosition) [source]

Actually sends a UltimateListEvent.

Parameters:
  • line – an instance of UltimateListLineData;
  • command – the event type to send;
  • point – an instance of wx.Point.

SetBackgroundImage(image) [source]

Sets the UltimateListCtrl background image.

Parameters: image – if not None, an instance of wx.Bitmap.

Note

At present, the background image can only be used in “tile” mode.

Todo

Support background images also in stretch and centered modes.

SetColumn(col, item) [source]

Sets information about this column.

Parameters:
  • col – an integer specifying the column index;
  • item – an instance of UltimateListItem.

SetColumnCustomRenderer(col=0, renderer=None) [source]

Associate a custom renderer to this column’s header

Parameters:
  • col – the column index.
  • renderer – a class able to correctly render the input item.

Note

the renderer class must implement the methods DrawHeaderButton and GetForegroundColor.

SetColumnWidth(col, width) [source]

Sets the column width.

Parameters: width – can be a width in pixels or wx.LIST_AUTOSIZE (-1) or wx.LIST_AUTOSIZE_USEHEADER (-2) or ULC_AUTOSIZE_FILL (-3). wx.LIST_AUTOSIZE will resize the column to the length of its longest item. wx.LIST_AUTOSIZE_USEHEADER will resize the column to the length of the header (Win32) or 80 pixels (other platforms). ULC_AUTOSIZE_FILL will resize the column fill the remaining width of the window.

Note

In small or normal icon view, col must be -1, and the column width is set for all columns.

SetDisabledTextColour(colour) [source]

Sets the items disabled colour.

Parameters: colour – an instance of wx.Colour.

SetFirstGradientColour(colour=None) [source]

Sets the first gradient colour for gradient-style selections.

Parameters: colour – if not None, a valid wx.Colour instance. Otherwise, the colour is taken from the system value wx.SYS_COLOUR_HIGHLIGHT.

SetFont(font) [source]

Overridden base class virtual to reset the line height when the font changes.

Parameters: font – a valid wx.Font object.

Note

Overridden from wx.PyScrolledWindow.

SetGradientStyle(vertical=0) [source]

Sets the gradient style for gradient-style selections.

Parameters: vertical – 0 for horizontal gradient-style selections, 1 for vertical gradient-style selections.

SetHyperTextFont(font) [source]

Sets the font used to render hypertext items.

Parameters: font – a valid wx.Font instance.

SetHyperTextNewColour(colour) [source]

Sets the colour used to render a non-visited hypertext item.

Parameters: colour – a valid wx.Colour instance.

SetHyperTextVisitedColour(colour) [source]

Sets the colour used to render a visited hypertext item.

Parameters: colour – a valid wx.Colour instance.

SetImageList(imageList, which) [source]

Sets the image list associated with the control.

Parameters:
  • imageList – an instance of wx.ImageList or an instance of PyImageList;
  • which – one of wx.IMAGE_LIST_NORMAL, wx.IMAGE_LIST_SMALL, wx.IMAGE_LIST_STATE (the last is unimplemented).

Note

Using PyImageList enables you to have images of different size inside the image list. In your derived class, instead of doing this:

imageList = wx.ImageList(16, 16)
imageList.Add(someBitmap)
self.SetImageList(imageList, wx.IMAGE_LIST_SMALL)

You should do this:

imageList = PyImageList(16, 16)
imageList.Add(someBitmap)
self.SetImageList(imageList, wx.IMAGE_LIST_SMALL)

SetImageListCheck(sizex, sizey, imglist=None) [source]

Sets the checkbox/radiobutton image list.

Parameters:
  • sizex – the width of the bitmaps in the imglist;
  • sizey – the height of the bitmaps in the imglist;
  • imglist – an instance of wx.ImageList.

SetItem(item) [source]

Sets information about the item.

Parameters: item – an instance of UltimateListItemData.

SetItemCount(count) [source]

This method can only be used with virtual UltimateListCtrl. It is used to indicate to the control the number of items it contains. After calling it, the main program should be ready to handle calls to various item callbacks (such as UltimateListCtrl.OnGetItemText()) for all items in the range from 0 to count.

Parameters: count – the total number of items in UltimateListCtrl.

SetItemCustomRenderer(item, renderer=None) [source]

Associate a custom renderer to this item.

Parameters:
  • item – an instance of UltimateListItem;
  • renderer – a class able to correctly render the item.

Note

the renderer class must implement the methods DrawSubItem, GetLineHeight and GetSubItemWidth.

SetItemHyperText(item, hyper=True) [source]

Sets whether the item is hypertext or not.

Parameters:
  • item – an instance of UltimateListItem;
  • hyper – True to have an item with hypertext behaviour, False otherwise.

SetItemKind(item, kind) [source]

Sets the item kind.

Parameters:
  • item – an instance of UltimateListItem;
  • kind – may be one of the following integers:

    Item Kind | Description
    0 | A normal item
    1 | A checkbox-like item
    2 | A radiobutton-type item

SetItemOverFlow(item, over=True) [source]

Sets the item in the overflow/non overflow state.

An item/subitem may overwrite neighboring items/subitems if its text would not normally fit in the space allotted to it.

Parameters:
  • item – an instance of UltimateListItem;
  • over – True to set the item in a overflow state, False otherwise.

SetItemSpacing(spacing, isSmall=False) [source]

Sets the spacing between item texts and icons.

Parameters:
  • spacing – the spacing between item texts and icons, in pixels;
  • isSmall – True if using a wx.IMAGE_LIST_SMALL image list, False if using a wx.IMAGE_LIST_NORMAL image list.

SetItemState(litem, state, stateMask) [source]

Sets the item state flags for the input item.

Parameters:
  • litem – the index of the item; if defaulted to -1, the state flag will be set for all the items;
  • state – the item state flag;
  • stateMask – the bitmask for the state flag.

See also

SetItemStateAll for a list of valid state flags.

SetItemStateAll(state, stateMask) [source]

Sets the item state flags for all the items.

Parameters:
  • state – any combination of the following bits:

    State Bits | Hex Value | Description
    ULC_STATE_DONTCARE | 0x0 | Don’t care what the state is
    ULC_STATE_DROPHILITED | 0x1 | The item is highlighted to receive a drop event
    ULC_STATE_FOCUSED | 0x2 | The item has the focus
    ULC_STATE_SELECTED | 0x4 | The item is selected
    ULC_STATE_CUT | 0x8 | The item is in the cut state
    ULC_STATE_DISABLED | 0x10 | The item is disabled
    ULC_STATE_FILTERED | 0x20 | The item has been filtered
    ULC_STATE_INUSE | 0x40 | The item is in use
    ULC_STATE_PICKED | 0x80 | The item has been picked
    ULC_STATE_SOURCE | 0x100 | The item is a drag and drop source
  • stateMask – the bitmask for the state flag.

Note

The valid state flags are influenced by the value of the state mask.

SetItemText(item, value) [source]

Sets the item text.

Parameters:
  • item – an instance of UltimateListItem;
  • value – the new item text.

SetItemVisited(item, visited=True) [source]

Sets whether an hypertext item was visited.

Parameters:
  • item – an instance of UltimateListItem;
  • visited – True to mark an hypertext item as visited, False otherwise.

SetItemWindow(item, wnd, expand=False) [source]

Sets the window for the given item.

Parameters:
  • item – an instance of UltimateListItem;
  • wnd – if not None, a non-toplevel window to be displayed next to the item;
  • expand – True to expand the column where the item/subitem lives, so that the window will be fully visible.

SetItemWindowEnabled(item, enable=True) [source]

Enables/disables the window associated to the item.

Parameters:
  • item – an instance of UltimateListItem;
  • enable – True to enable the associated window, False to disable it.

SetReportView(inReportView) [source]

Sets whether UltimateListCtrl is in report view or not.

Parameters: inReportView – True to set UltimateListCtrl in report view, False otherwise.

SetSecondGradientColour(colour=None) [source]

Sets the second gradient colour for gradient-style selections.

Parameters: colour – if not None, a valid wx.Colour instance. Otherwise, the colour generated is a slightly darker version of the UltimateListCtrl background colour.

SetUserLineHeight(height) [source]

Sets a custom value for the UltimateListMainWindow item height.

Parameters: height – the custom height for all the items, in pixels.

Note

This method can be used only with ULC_REPORT and ULC_USER_ROW_HEIGHT styles set.

SetWaterMark(watermark) [source]

Sets the UltimateListCtrl watermark image to be displayed in the bottom right part of the window.

Parameters: watermark – if not None, an instance of wx.Bitmap.

Todo

Better support for this is needed.

SortItems(func) [source]

Call this function to sort the items in the UltimateListCtrl. Sorting is done using the specified function func. This function must have the following prototype:

def OnCompareItems(self, line1, line2):

    DoSomething(line1, line2)
    # function code

It is called each time when the two items must be compared and should return 0 if the items are equal, negative value if the first item is less than the second one and positive value if the first one is greater than the second one.

Parameters: func – the method to use to sort the items. The default is to use the OnCompareItems method.

TileBackground(dc) [source]

Tiles the background image to fill all the available area.

Parameters: dc – an instance of wx.DC.

Todo

Support background images also in stretch and centered modes.

UpdateCurrent() [source]

Updates the current line selection.

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • infobar
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • ultimatelistctrl »
  • UltimateListMainWindow


UltimateListRenameTimer

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • ultimatelistctrl »
  • UltimateListRenameTimer

UltimateListRenameTimer

Timer used for enabling in-place edit.

hierarchy Inheritance Diagram

Inheritance diagram for: UltimateListRenameTimer

Inheritance diagram of UltimateListRenameTimer

Methods Summary

__init__ | Default class constructor.
Notify | The timer has expired.

API Class API

class UltimateListRenameTimer(wx.Timer) [source]

Timer used for enabling in-place edit.

__init__(owner) [source]

Default class constructor. For internal use: do not call it in your code!

Parameters: owner – an instance of UltimateListCtrl.

Notify() [source]

The timer has expired.

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • infobar
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • ultimatelistctrl »
  • UltimateListRenameTimer


UltimateListTextCtrl

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • ultimatelistctrl »
  • UltimateListTextCtrl

UltimateListTextCtrl

Control used for in-place edit.

This is a subclass of ExpandoTextCtrl as UltimateListCtrl supports multiline text items.

Note

To add a newline character in a multiline item, press Shift + Enter as the Enter key alone is consumed by UltimateListCtrl to finish the editing and Ctrl + Enter is consumed by the platform for tab navigation.

hierarchy Inheritance Diagram

Inheritance diagram for: UltimateListTextCtrl

Inheritance diagram of UltimateListTextCtrl

Methods Summary

__init__ | Default class constructor.
AcceptChanges | Accepts/refuses the changes made by the user.
Finish | Finish editing.
OnChar | Handles the wx.EVT_CHAR event for UltimateListTextCtrl.
OnKeyUp | Handles the wx.EVT_KEY_UP event for UltimateListTextCtrl.
OnKillFocus | Handles the wx.EVT_KILL_FOCUS event for UltimateListTextCtrl.
StopEditing | Suddenly stops the editing.

API Class API

class UltimateListTextCtrl(ExpandoTextCtrl) [source]

Control used for in-place edit.

This is a subclass of ExpandoTextCtrl as UltimateListCtrl supports multiline text items.

Note

To add a newline character in a multiline item, press Shift + Enter as the Enter key alone is consumed by UltimateListCtrl to finish the editing and Ctrl + Enter is consumed by the platform for tab navigation.

__init__(owner, itemEdit) [source]

Default class constructor. For internal use: do not call it in your code!

Parameters:
  • owner – the control parent (an instance of UltimateListCtrl );
  • itemEdit – an instance of UltimateListItem.

AcceptChanges() [source]

Accepts/refuses the changes made by the user.

Finish() [source]

Finish editing.

OnChar(event) [source]

Handles the wx.EVT_CHAR event for UltimateListTextCtrl.

Parameters: event – a wx.KeyEvent event to be processed.

OnKeyUp(event) [source]

Handles the wx.EVT_KEY_UP event for UltimateListTextCtrl.

Parameters: event – a wx.KeyEvent event to be processed.

OnKillFocus(event) [source]

Handles the wx.EVT_KILL_FOCUS event for UltimateListTextCtrl.

Parameters: event – a wx.FocusEvent event to be processed.

StopEditing() [source]

Suddenly stops the editing.

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • infobar
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • ultimatelistctrl »
  • UltimateListTextCtrl


SVN Revision 67824 For ultimatelistctrl

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • ultimatelistctrl »
  • SVN Revision 67824 For ultimatelistctrl

svn SVN Revision 67824 For ultimatelistctrl

This file contains the SVN revision history for ultimatelistctrl, at revision 67824.

Available information include commit date, the name of the committer, the file size, the SVN log messages and a diff from the previous version (if available).

File Information

  • Commit Date: 16-Apr-2010 11:45:03 UTC
  • Committer: RD
  • File Size: 453606 byte(s)

Log Messages

The following log message was entered by the committer:

Don’t call PrepareDC for a widget that is not a wx.ScrolledWindow

Diff To Previous Version (67166)

Version SVN diff:

--- wxPython/3rdParty/AGW/agw/ultimatelistctrl.py   2011/03/10 13:52:18     67166
+++ wxPython/3rdParty/AGW/agw/ultimatelistctrl.py   2011/05/31 20:20:04     67824
@@ -5062,7 +5062,6 @@
dc.SetPen(wx.TRANSPARENT_PEN)
dc.DrawRectangle(0, -1, w, h+2)

-        self.PrepareDC(dc)
self.AdjustDC(dc)

dc.SetBackgroundMode(wx.TRANSPARENT)

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • ultimatelistctrl »
  • SVN Revision 67824 For ultimatelistctrl


SVN Revision 68347 For ultimatelistctrl

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • ultimatelistctrl »
  • SVN Revision 68347 For ultimatelistctrl

svn SVN Revision 68347 For ultimatelistctrl

This file contains the SVN revision history for ultimatelistctrl, at revision 68347.

Available information include commit date, the name of the committer, the file size, the SVN log messages and a diff from the previous version (if available).

File Information

  • Commit Date: 13-Apr-2010 17:11:04 UTC
  • Committer: AG
  • File Size: 453607 byte(s)

Log Messages

The following log message was entered by the committer:

Use Refresh instead of Update in UltimateListCtrl after sorting the items.

Diff To Previous Version (67824)

Version SVN diff:

--- wxPython/3rdParty/AGW/agw/ultimatelistctrl.py   2011/05/31 20:20:04     67824
+++ wxPython/3rdParty/AGW/agw/ultimatelistctrl.py   2011/07/23 22:56:39     68347
@@ -3,7 +3,7 @@
# Inspired by and heavily based on the wxWidgets C++ generic version of wxListCtrl.
#
# Andrea Gavana, @ 08 May 2009
-# Latest Revision: 10 Mar 2011, 15.00 GMT
+# Latest Revision: 22 Jul 2011, 21.00 GMT
#
#
# TODO List
@@ -176,7 +176,7 @@

UltimateListCtrl is distributed under the wxPython license.

-Latest Revision: Andrea Gavana @ 10 Mar 2011, 15.00 GMT
+Latest Revision: Andrea Gavana @ 22 Jul 2011, 21.00 GMT

Version 0.8

@@ -12099,7 +12099,7 @@
"""

self._mainWin.SortItems(func)
-        wx.CallAfter(self.Update)
+        wx.CallAfter(self.Refresh)

return True

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • ultimatelistctrl »
  • SVN Revision 68347 For ultimatelistctrl


SVN Revision 68881 For ultimatelistctrl

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • ultimatelistctrl »
  • SVN Revision 68881 For ultimatelistctrl

svn SVN Revision 68881 For ultimatelistctrl

This file contains the SVN revision history for ultimatelistctrl, at revision 68881.

Available information include commit date, the name of the committer, the file size, the SVN log messages and a diff from the previous version (if available).

File Information

  • Commit Date: 30-Mar-2010 23:32:07 UTC
  • Committer: AG
  • File Size: 457488 byte(s)

Log Messages

The following log message was entered by the committer:

  • AGW: General overhaul of the documentation, much improved. All the widgets have their own sample usage in the docs as well;

  • FlatNotebook: Added the FNB_NAV_BUTTONS_WHEN_NEEDED style, which hides the navigation left/right arrows if all tabs fit;

  • RibbonBar: - Added the EVT_RIBBONBAR_TAB_LEFT_DCLICK event, which generates a special event

    when a ribbon bar tab is double-clicked;

    • Added support for toggle buttons;
    • Improved support for ribbon panel sizers: panels with sizers should now automatically minimise at small sizes, and behave properly when popping up from a minimised state;
    • Added tooltips via SetToolTip for those buttons which have the help_string attribute set.

  • XLSGrid: a new widget was added to AGW, termed XLSGrid. It’s based on wx.grid.Grid and can be used to faithfully reproduce the appearance of a Microsoft Excel spreadsheets.

Diff To Previous Version (68362)

Version SVN diff:

--- wxPython/3rdParty/AGW/agw/ultimatelistctrl.py   2011/07/24 21:36:47     68362
+++ wxPython/3rdParty/AGW/agw/ultimatelistctrl.py   2011/08/25 16:40:17     68881
@@ -3,7 +3,7 @@
# Inspired by and heavily based on the wxWidgets C++ generic version of wxListCtrl.
#
# Andrea Gavana, @ 08 May 2009
-# Latest Revision: 22 Jul 2011, 21.00 GMT
+# Latest Revision: 17 Aug 2011, 15.00 GMT
#
#
# TODO List
@@ -78,6 +78,55 @@
And a lot more. Check the demo for an almost complete review of the functionalities.

+Usage
+=====
+
+Usage example::
+
+    import sys
+
+    import wx
+    import wx.lib.agw.ultimatelistctrl as ULC
+
+    class MyFrame(wx.Frame):
+
+        def __init__(self):
+
+            wx.Frame.__init__(self, parent, -1, "UltimateListCtrl Demo")
+
+            list = ULC.UltimateListCtrl(self, wx.ID_ANY, agwStyle=wx.LC_REPORT|wx.LC_VRULES|wx.LC_HRULES|wx.LC_SINGLE_SEL)
+
+            list.InsertColumn(0, "Column 1")
+            list.InsertColumn(1, "Column 2")
+
+            index = list.InsertStringItem(sys.maxint, "Item 1")
+            list.SetStringItem(index, 1, "Sub-item 1")
+
+            index = list.InsertStringItem(sys.maxint, "Item 2")
+            list.SetStringItem(index, 1, "Sub-item 2")
+
+            choice = wx.Choice(list, -1, choices=["one", "two"])
+            index = list.InsertStringItem(sys.maxint, "A widget")
+
+            list.SetItemWindow(index, 1, choice, expand=True)
+
+            sizer = wx.BoxSizer(wx.VERTICAL)
+            sizer.Add(list, 1, wx.EXPAND)
+            self.SetSizer(sizer)
+
+
+    # our normal wxApp-derived class, as usual
+
+    app = wx.PySimpleApp()
+
+    frame = MyFrame(None)
+    app.SetTopWindow(frame)
+    frame.Show()
+
+    app.MainLoop()
+
+
+
Window Styles
=============

@@ -176,7 +225,7 @@

UltimateListCtrl is distributed under the wxPython license.

-Latest Revision: Andrea Gavana @ 22 Jul 2011, 21.00 GMT
+Latest Revision: Andrea Gavana @ 17 Aug 2011, 15.00 GMT

Version 0.8

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • ultimatelistctrl »
  • SVN Revision 68881 For ultimatelistctrl


SVN Revision 69086 For ultimatelistctrl

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • ultimatelistctrl »
  • SVN Revision 69086 For ultimatelistctrl

svn SVN Revision 69086 For ultimatelistctrl

This file contains the SVN revision history for ultimatelistctrl, at revision 69086.

Available information include commit date, the name of the committer, the file size, the SVN log messages and a diff from the previous version (if available).

File Information

  • Commit Date: 30-Mar-2010 23:21:03 UTC
  • Committer: AG
  • File Size: 457492 byte(s)

Log Messages

The following log message was entered by the committer:

  • Fixed bug #13437 for SuperToolTip;
  • Fixed bug #13477 for UltimateListCtrl.

Diff To Previous Version (68881)

Version SVN diff:

--- wxPython/3rdParty/AGW/agw/ultimatelistctrl.py   2011/08/25 16:40:17     68881
+++ wxPython/3rdParty/AGW/agw/ultimatelistctrl.py   2011/09/14 19:39:08     69086
@@ -3,7 +3,7 @@
# Inspired by and heavily based on the wxWidgets C++ generic version of wxListCtrl.
#
# Andrea Gavana, @ 08 May 2009
-# Latest Revision: 17 Aug 2011, 15.00 GMT
+# Latest Revision: 14 Sep 2011, 21.00 GMT
#
#
# TODO List
@@ -7455,7 +7455,7 @@
if event.RightDown():
self.SendNotify(-1, wxEVT_COMMAND_LIST_ITEM_RIGHT_CLICK, event.GetPosition())

-                evtCtx = wx.ContextMenuEvent(wx.EVT_CONTEXT_MENU, self.GetParent().GetId(),
+                evtCtx = wx.ContextMenuEvent(wx.wxEVT_CONTEXT_MENU, self.GetParent().GetId(),
self.ClientToScreen(event.GetPosition()))
evtCtx.SetEventObject(self.GetParent())
self.GetParent().GetEventHandler().ProcessEvent(evtCtx)
@@ -7626,7 +7626,7 @@
# outside of any item
if event.RightDown():
self.SendNotify(-1, wxEVT_COMMAND_LIST_ITEM_RIGHT_CLICK, event.GetPosition())
-                evtCtx = wx.ContextMenuEvent(wx.EVT_CONTEXT_MENU, self.GetParent().GetId(),
+                evtCtx = wx.ContextMenuEvent(wx.wxEVT_CONTEXT_MENU, self.GetParent().GetId(),
self.ClientToScreen(event.GetPosition()))
evtCtx.SetEventObject(self.GetParent())
self.GetParent().GetEventHandler().ProcessEvent(evtCtx)

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • ultimatelistctrl »
  • SVN Revision 69086 For ultimatelistctrl


SVN Revision 69347 For ultimatelistctrl

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • ultimatelistctrl »
  • SVN Revision 69347 For ultimatelistctrl

svn SVN Revision 69347 For ultimatelistctrl

This file contains the SVN revision history for ultimatelistctrl, at revision 69347.

Available information include commit date, the name of the committer, the file size, the SVN log messages and a diff from the previous version (if available).

File Information

  • Commit Date: 11-Dec-2009 11:51:15 UTC
  • Committer: AG
  • File Size: 457502 byte(s)

Log Messages

The following log message was entered by the committer:

UltimateListCtrl: close ticket #11864.

Diff To Previous Version (69087)

Version SVN diff:

--- wxPython/3rdParty/AGW/agw/ultimatelistctrl.py   2011/09/14 19:50:15     69087
+++ wxPython/3rdParty/AGW/agw/ultimatelistctrl.py   2011/10/09 18:54:23     69347
@@ -3,7 +3,7 @@
# Inspired by and heavily based on the wxWidgets C++ generic version of wxListCtrl.
#
# Andrea Gavana, @ 08 May 2009
-# Latest Revision: 14 Sep 2011, 21.00 GMT
+# Latest Revision: 09 Oct 2011, 21.00 GMT
#
#
# TODO List
@@ -225,7 +225,7 @@

UltimateListCtrl is distributed under the wxPython license.

-Latest Revision: Andrea Gavana @ 17 Aug 2011, 15.00 GMT
+Latest Revision: Andrea Gavana @ 09 Oct 2011, 21.00 GMT

Version 0.8

@@ -6443,7 +6443,7 @@
Called by L{UltimateListCtrl.OnSize} when the window is resized.
"""

-        if not self: # Avoid PyDeadObjectError's on Mac
+        if not self: # Avoid PyDeadObjectErrors on Mac
return

if self._resizeColumn == -1:
@@ -6469,7 +6469,7 @@

totColWidth = 0 # Width of all columns except last one.
for col in range(numCols):
-            if col != (resizeCol):
+            if col != (resizeCol) and self.IsColumnShown(col):
totColWidth = totColWidth + self.GetColumnWidth(col)

resizeColWidth = self.GetColumnWidth(resizeCol)

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • ultimatelistctrl »
  • SVN Revision 69347 For ultimatelistctrl


SVN Revision 69620 For ultimatelistctrl

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • ultimatelistctrl »
  • SVN Revision 69620 For ultimatelistctrl

svn SVN Revision 69620 For ultimatelistctrl

This file contains the SVN revision history for ultimatelistctrl, at revision 69620.

Available information include commit date, the name of the committer, the file size, the SVN log messages and a diff from the previous version (if available).

File Information

  • Commit Date: 10-Dec-2009 18:09:38 UTC
  • Committer: AG
  • File Size: 457330 byte(s)

Log Messages

The following log message was entered by the committer:

  • UltimateListCtrl: fixed a few bugs and added a new demo (Windows7Explorer_Contents.py) showing an emulation of the Windows 7 Explorer behaviour when “Contents” is selected as a view;
  • AUI: Added a self._mgr.UnInit to the demo to no avail, wxPython still crashes with an assert.

Diff To Previous Version (69347)

Version SVN diff:

--- wxPython/3rdParty/AGW/agw/ultimatelistctrl.py   2011/10/09 18:54:23     69347
+++ wxPython/3rdParty/AGW/agw/ultimatelistctrl.py   2011/10/31 21:11:23     69620
@@ -3,7 +3,7 @@
# Inspired by and heavily based on the wxWidgets C++ generic version of wxListCtrl.
#
# Andrea Gavana, @ 08 May 2009
-# Latest Revision: 09 Oct 2011, 21.00 GMT
+# Latest Revision: 31 Oct 2011, 21.00 GMT
#
#
# TODO List
@@ -225,7 +225,7 @@

UltimateListCtrl is distributed under the wxPython license.

-Latest Revision: Andrea Gavana @ 09 Oct 2011, 21.00 GMT
+Latest Revision: Andrea Gavana @ 31 Oct 2011, 21.00 GMT

Version 0.8

@@ -4598,7 +4598,6 @@
dc.SetTextForeground(item.GetColour())
elif useVista and drawn:
dc.SetTextForeground(wx.BLACK)
-                        dc.SetFont(boldFont)

if item.IsHyperText():
dc.SetFont(self._owner.GetHyperTextFont())
@@ -10376,10 +10375,10 @@

if not func:
self.__func = None
-            self._lines.sort(self.OnCompareItems)
else:
self.__func = func
-            self._lines.sort(self.OnCompareItems)
+
+        self._lines.sort(self.OnCompareItems)

if self.IsShownOnScreen():
self._dirty = True
@@ -10862,7 +10861,7 @@

self._headerWin = UltimateListHeaderWindow(self, wx.ID_ANY, self._mainWin,
wx.Point(0, 0),
-                                                       wx.Size(self.GetClientSize().x, self._headerHeight),
+                                                       wx.DefaultSize,
wx.TAB_TRAVERSAL, isFooter=False)

# ----------------------------------------------------
@@ -10900,7 +10899,7 @@

self._footerWin = UltimateListHeaderWindow(self, wx.ID_ANY, self._mainWin,
wx.Point(0, 0),
-                                                       wx.Size(self.GetClientSize().x, self._footerHeight),
+                                                       wx.DefaultSize,
wx.TAB_TRAVERSAL, isFooter=True)

# ----------------------------------------------------

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • ultimatelistctrl »
  • SVN Revision 69620 For ultimatelistctrl


SVN Revision 69824 For ultimatelistctrl

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • ultimatelistctrl »
  • SVN Revision 69824 For ultimatelistctrl

svn SVN Revision 69824 For ultimatelistctrl

This file contains the SVN revision history for ultimatelistctrl, at revision 69824.

Available information include commit date, the name of the committer, the file size, the SVN log messages and a diff from the previous version (if available).

File Information

  • Commit Date: 19-Nov-2009 10:19:40 UTC
  • Committer: AG
  • File Size: 457466 byte(s)

Log Messages

The following log message was entered by the committer:

UltimateListCtrl: fixed issues with int/long types passed to CreateListItem.

Diff To Previous Version (69627)

Version SVN diff:

--- wxPython/3rdParty/AGW/agw/ultimatelistctrl.py   2011/11/01 19:42:21     69627
+++ wxPython/3rdParty/AGW/agw/ultimatelistctrl.py   2011/11/27 12:17:50     69824
@@ -3,7 +3,7 @@
# Inspired by and heavily based on the wxWidgets C++ generic version of wxListCtrl.
#
# Andrea Gavana, @ 08 May 2009
-# Latest Revision: 31 Oct 2011, 21.00 GMT
+# Latest Revision: 27 Nov 2011, 13.00 GMT
#
#
# TODO List
@@ -225,7 +225,7 @@

UltimateListCtrl is distributed under the wxPython license.

-Latest Revision: Andrea Gavana @ 31 Oct 2011, 21.00 GMT
+Latest Revision: Andrea Gavana @ 27 Nov 2011, 13.00 GMT

Version 0.8

@@ -550,6 +550,10 @@
IL_FIXED_SIZE = 0
IL_VARIABLE_SIZE = 1

+# Python integers, to make long types to work with CreateListItem
+INTEGER_TYPES = [types.IntType, types.LongType]
+
+
# ----------------------------------------------------------------------------
# Functions
# ----------------------------------------------------------------------------
@@ -593,7 +597,7 @@
:param `col`: the item column.
"""

-    if type(itemOrId) == types.IntType:
+    if type(itemOrId) in INTEGER_TYPES:
item = UltimateListItem()
item._itemId = itemOrId
item._col = col

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • ultimatelistctrl »
  • SVN Revision 69824 For ultimatelistctrl


SVN Revision 70555 For ultimatelistctrl

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • ultimatelistctrl »
  • SVN Revision 70555 For ultimatelistctrl

svn SVN Revision 70555 For ultimatelistctrl

This file contains the SVN revision history for ultimatelistctrl, at revision 70555.

Available information include commit date, the name of the committer, the file size, the SVN log messages and a diff from the previous version (if available).

File Information

  • Commit Date: 07-Oct-2009 08:07:28 UTC
  • Committer: AG
  • File Size: 458458 byte(s)

Log Messages

The following log message was entered by the committer:

  • GradientButton: applied patch from Werner and cleaned up a bit the useless parts of the code;
  • AuiToolBar/AuiDefaultDockArt: applied patch from Werner for default colour settings for AUI toolbars;
  • UltimateListCtrl: Fixed bug #13938. Also, don’t throw an error on key down if the list is empty.

Diff To Previous Version (69824)

Version SVN diff:

--- wxPython/3rdParty/AGW/agw/ultimatelistctrl.py   2011/11/27 12:17:50     69824
+++ wxPython/3rdParty/AGW/agw/ultimatelistctrl.py   2012/02/09 20:52:26     70555
@@ -3,7 +3,7 @@
# Inspired by and heavily based on the wxWidgets C++ generic version of wxListCtrl.
#
# Andrea Gavana, @ 08 May 2009
-# Latest Revision: 27 Nov 2011, 13.00 GMT
+# Latest Revision: 09 Feb 2012, 21.00 GMT
#
#
# TODO List
@@ -225,7 +225,7 @@

UltimateListCtrl is distributed under the wxPython license.

-Latest Revision: Andrea Gavana @ 27 Nov 2011, 13.00 GMT
+Latest Revision: Andrea Gavana @ 09 Feb 2012, 21.00 GMT

Version 0.8

@@ -8054,7 +8054,11 @@
"""

parent = self.GetParent()
-
+
+        if self.IsVirtual() and self.GetItemCount() == 0:
+            event.Skip()
+            return
+
# we send a list_key event up
if self.HasCurrent():
le = UltimateListEvent(wxEVT_COMMAND_LIST_KEY_DOWN, self.GetParent().GetId())
@@ -12427,7 +12431,22 @@
return self._mainWin.PopupMenu(menu, pos)

-    def ClientToScreen(self, x, y):
+    def ClientToScreen(self, pointOrTuple):
+        """
+        Converts to screen coordinates from coordinates relative to this window.
+
+        :param `pointOrTuple`: an instance of `wx.Point` or a tuple representing the
+         `x`, `y` coordinates for this point.
+
+        :return: the coordinates relative to the screen.
+
+        :note: Overridden from `wx.PyControl`.
+        """
+
+        return self._mainWin.ClientToScreen(*pointOrTuple)
+
+
+    def ClientToScreenXY(self, x, y):
"""
Converts to screen coordinates from coordinates relative to this window.

@@ -12442,7 +12461,22 @@
return self._mainWin.ClientToScreen(x, y)

-    def ScreenToClient(self, x, y):
+    def ScreenToClient(self, pointOrTuple):
+        """
+        Converts from screen to client window coordinates.
+
+        :param `pointOrTuple`: an instance of `wx.Point` or a tuple representing the
+         `x`, `y` coordinates for this point.
+
+        :return: the coordinates relative to this window.
+
+        :note: Overridden from `wx.PyControl`.
+        """
+
+        return self._mainWin.ScreenToClient(*pointOrTuple)
+
+
+    def ScreenToClientXY(self, x, y):
"""
Converts from screen to client window coordinates.

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • ultimatelistctrl »
  • SVN Revision 70555 For ultimatelistctrl


xlsgrid functions

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • xlsgrid »
  • xlsgrid functions

xlsgrid functions

This is the description of standalone Python functions in the xlsgrid module.

Functions Summary

FontFromFont | Creates a copy of the input font.
ReadExcelCOM | Reads and Excel spreadsheet (a single worksheet) using Mark Hammonds’ pywin32
SplitThousands | Splits a general float on thousands.

API Functions API

FontFromFont(font) [source]

Creates a copy of the input font.

Parameters: font – an instance of wx.Font.

ReadExcelCOM(filename, sheetname, rows, cols) [source]

Reads and Excel spreadsheet (a single worksheet) using Mark Hammonds’ pywin32 package. If this package is not available, it returns two empty nested lists.

Parameters:
  • filename – a valid Excel xls filename;
  • sheetname – the worksheet name inside the Excel file (i.e., the label on the workbook tab at the bottom of the workbook);
  • rows – the number of significant rows in the worksheet, as returned by xlrd;
  • cols – the number of significant columns in the worksheet, as returned by xlrd.
Returns:

two nested lists representing the comments (notes) on every cell and the WYSIWYG representation of the cell content.

Note

If Mark Hammonds’ pywin32 package is not available, this method returns two empty nested lists.

SplitThousands(s, tSep=', ', dSep='.') [source]

Splits a general float on thousands. GIGO on general input.

Parameters:
  • s – can be a float or a string, representing a number;
  • tSep – the character to be used as thousands separator;
  • dSep – the character to be used as decimal separator.
Returns:

a string properly formatted with thousands and decimal separators in it.

Note

This method is used only if Mark Hammonds’ pywin32 package is not available to try and format a number in an intelligent way.

Note

This code has been obtained from the public domain:

http://code.activestate.com/recipes/498181-add-thousands-separator-commas-to-formatted-number/#c14

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • infobar
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • xlsgrid »
  • xlsgrid functions


Excel

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • xlsgrid »
  • Excel

Excel

A simple class that holds a COM interface to Excel.

By using the win32com module from Mark Hammonds’ pywin32 package, we can manipulate various workbook/worksheet methods inside this class.

hierarchy Inheritance Diagram

Inheritance diagram for: Excel

Inheritance diagram of Excel

Methods Summary

__init__ | Default class constructor.
Close | Closes the Excel workbook, interrupting the COM interface.
GetCommentsRange | Returns a range of cells containing comments, using the VBA API.
GetText | Returns the WYSIWYG text contained in a cell.

API Class API

class Excel(object) [source]

A simple class that holds a COM interface to Excel.

By using the win32com module from Mark Hammonds’ pywin32 package, we can manipulate various workbook/worksheet methods inside this class.

__init__(filename, sheetname) [source]

Default class constructor.

Parameters:
  • filename – a valid Excel xls filename;
  • sheetname – the worksheet name inside the Excel file (i.e., the label on the workbook tab at the bottom of the workbook).

Close(save=False) [source]

Closes the Excel workbook, interrupting the COM interface.

Parameters: save – True to save the changes you made to the workbook, False otherwise.

GetCommentsRange() [source]

Returns a range of cells containing comments, using the VBA API.

GetText(row, col) [source]

Returns the WYSIWYG text contained in a cell.

Parameters:
  • row – the row in which the cell lives;
  • col – the column in which the cell lives.

Note

The row and col parameters are not real Python index, as they use the Excel indexing mode (i.e., first index is 1 and not 0).

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • infobar
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • xlsgrid »
  • Excel


TransientPopup

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • xlsgrid »
  • TransientPopup

TransientPopup

This is a sublass of SuperToolTip and it is used to display a “comment-window” on the cells containing a comment (a note).

Note

If Mark Hammonds’ pywin32 package is not available, this class is never invoked.

hierarchy Inheritance Diagram

Inheritance diagram for: TransientPopup

Inheritance diagram of TransientPopup

supclasses Known Superclasses

  • supertooltip.SuperToolTip

Methods Summary

__init__ Default class constructor.

API Class API

class TransientPopup(STT.SuperToolTip) [source]

This is a sublass of SuperToolTip and it is used to display a “comment-window” on the cells containing a comment (a note).

Note

If Mark Hammonds’ pywin32 package is not available, this class is never invoked.

__init__(grid_window, comment, position) [source]

Default class constructor.

Parameters:
  • grid_window – the actual window representing the grid;
  • comment – an instance of XLSComment, containing the text for this comment;
  • position – the position at which we pop up the comment window (currently unused).

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • infobar
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • xlsgrid »
  • TransientPopup


XLSBackground

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • xlsgrid »
  • XLSBackground

XLSBackground

This is a class which holds information about the cell background, in terms of background colour and background pattern (hatching).

hierarchy Inheritance Diagram

Inheritance diagram for: XLSBackground

Inheritance diagram of XLSBackground

Methods Summary

__init__ | Default class constructor.
CombineAttr | Combines the input attribute attr with the features of the XLSBackground class.
CreateBackgroundColour | Creates a suitable wxPython colour for the cell background starting from
Draw | Actually draws the cell background and pattern hatching on a grid cell.

API Class API

class XLSBackground(object) [source]

This is a class which holds information about the cell background, in terms of background colour and background pattern (hatching).

__init__(book, xf_index) [source]

Default class constructor.

Parameters:
  • book – an instance of the xlrd.Book class;
  • xf_index – an index into xlrd.Book.xf_list, which holds a reference to the xlrd.sheet.Cell class (the actual cell for xlrd).

CombineAttr(attr) [source]

Combines the input attribute attr with the features of the XLSBackground class.

Parameters: attr – an instance of wx.grid.GridCellAttr.

CreateBackgroundColour(background_colour, pattern_colour, fill_pattern) [source]

Creates a suitable wxPython colour for the cell background starting from a xlrd tuple representing this colour.

Parameters:
  • background_colour – a tuple representing the RGB components of the cell background colour. If background_colour is None, use the default wx.SYS_COLOUR_WINDOW;
  • pattern_colour – a tuple representing the RGB components of the cell pattern colour;
  • fill_pattern – the pattern to use to draw hatches on top of the background.

Draw(dc, rect) [source]

Actually draws the cell background and pattern hatching on a grid cell.

Parameters:
  • dc – an instance of wx.DC;
  • rect – an instance of wx.Rect, representing the cell rectangle.

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • infobar
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • xlsgrid »
  • XLSBackground


XLSBorder

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • xlsgrid »
  • XLSBorder

XLSBorder

This is a class which holds information about a single cell border, in terms of its location (top, left, bottom, right, diagonal), its colour, width and shape.

hierarchy Inheritance Diagram

Inheritance diagram for: XLSBorder

Inheritance diagram of XLSBorder

Methods Summary

__init__ | Default class constructor.
Draw | Actually draws the cell border.
DrawBorder | Actually draws the cell border (one of left, right, bottom, top).
DrawDiagonals | Actually draws the cell diagonal border.

API Class API

class XLSBorder(object) [source]

This is a class which holds information about a single cell border, in terms of its location (top, left, bottom, right, diagonal), its colour, width and shape.

__init__(location, line_style, border_colour, default_colour, diagonals) [source]

Default class constructor.

Parameters:
  • location – the actual border location (top, left, bottom, right, diagonal);
  • line_style – the line style used by Excel to draw this border;
  • border_colour – the colour used by Excel to draw this border;
  • default_colour – the “magic” colour used by Excel to draw non-custom border lines;
  • diagonals – a tuple containing whether or not to draw the up and down diagonal borders.

Draw(dc, rect) [source]

Actually draws the cell border.

Parameters:
  • dc – an instance of wx.DC;
  • rect – an instance of wx.Rect, representing the cell rectangle.

DrawBorder(dc, rect) [source]

Actually draws the cell border (one of left, right, bottom, top).

Parameters:
  • dc – an instance of wx.DC;

  • rect – an instance of wx.Rect, representing the cell rectangle.

DrawDiagonals(dc, rect) [source]

Actually draws the cell diagonal border.

Parameters:
  • dc – an instance of wx.DC;

  • rect – an instance of wx.Rect, representing the cell rectangle.

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • infobar
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • xlsgrid »
  • XLSBorder


XLSBorderFactory

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • xlsgrid »
  • XLSBorderFactory

XLSBorderFactory

This is a factory class which holds information about all the borders in a cell. Its implementation and use is merely to simplify the handling of the different cell borders (left, top, bottom, right, diagonal).

hierarchy Inheritance Diagram

Inheritance diagram for: XLSBorderFactory

Inheritance diagram of XLSBorderFactory

Methods Summary

__init__ | Default class constructor.
Draw | Actually draws all the cell borders based on their drawing priority.

API Class API

class XLSBorderFactory(object) [source]

This is a factory class which holds information about all the borders in a cell. Its implementation and use is merely to simplify the handling of the different cell borders (left, top, bottom, right, diagonal).

__init__(book, border, default_colour) [source]

Default class constructor.

Parameters:
  • book – an instance of the xlrd.Book class;
  • border – an instance of xlrd.formatting.XFBorder class;
  • default_colour – the “magic” colour used by Excel to draw non-custom border lines.

Draw(dc, rect) [source]

Actually draws all the cell borders based on their drawing priority.

Parameters:
  • dc – an instance of wx.DC;
  • rect – an instance of wx.Rect, representing the cell rectangle.

Note

The drawing priority is assigned depending on if the border is a custom one or not. Customized borders are drawn last.

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • infobar
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • xlsgrid »
  • XLSBorderFactory


XLSCell

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • xlsgrid »
  • XLSCell

XLSCell

This is a class which holds information about a single cell in XLSGrid. It stores (via auxiliary classes), all details about cell background, text, font, colours and borders.

hierarchy Inheritance Diagram

Inheritance diagram for: XLSCell

Inheritance diagram of XLSCell

Methods Summary

__init__ | Default class constructor.
GetAttr | Returns the attribute to use for this specific cell.
GetComment | Returns the cell comment, if any.
GetValue | Returns the actual WYSIWYG representation of the cell value.
SetCellSize | Sets the size of the cell.
SetValue | Sets the actual WYSIWYG representation of the cell value.
SetupCell | Actually sets up the XLSCell class. This is an auxiliary method to

API Class API

class XLSCell(object) [source]

This is a class which holds information about a single cell in XLSGrid. It stores (via auxiliary classes), all details about cell background, text, font, colours and borders.

__init__(book, cell, xf_index, xls_text, xls_comment, hyperlink, rich_text, default_width, default_colour) [source]

Default class constructor.

Parameters:
  • book – an instance of the xlrd.Book class;
  • cell – an instance of xlrd.sheet.Cell class;
  • xf_index – an index into xlrd.Book.xf_list, which holds a reference to the xlrd.sheet.Cell class (the actual cell for xlrd);
  • xls_text – the actual WYSIWYG cell text, if available;
  • xls_comment – the cell comment (note), if any;
  • hyperlink – an instance of xlrd.sheet.hyperlink;
  • rich_text – if this cell contains text in rich text format, XLSGrid will do its best to render the text as rich text;
  • default_width – this is the default width of the text in 1/256 of the width of the zero character, using default Excel font (first FONT record in the Excel file);
  • default_colour – the “magic” colour used by Excel to draw non-custom border lines.

Note

If you are using version 0.7.1 or lower for xlrd, the hyperlink parameter will always be None as this feature is available only in xlrd 0.7.2 (SVN).

Note

If you are using version 0.7.1 or lower for xlrd, the rich_text parameter will always be None as this feature is available only in xlrd 0.7.2 (SVN).

Note

if Mark Hammonds’ pywin32 package is not available, the xls_text parameter will almost surely not be the WYSIWYG representation of the cell text.

Note

If Mark Hammonds’ pywin32 package is not available, the xls_comment parameter will always be None.

GetAttr() [source]

Returns the attribute to use for this specific cell.

Returns: an instance of wx.grid.GridCellAttr.

GetComment() [source]

Returns the cell comment, if any.

Returns: an instance of XLSComment.

Note

If Mark Hammonds’ pywin32 package is not available, this method always returns None.

GetValue() [source]

Returns the actual WYSIWYG representation of the cell value.

SetCellSize(rows, cols) [source]

Sets the size of the cell.

Specifying a value of more than 1 in rows or cols will make the cell at (row, col) span the block of the specified size, covering the other cells which would be normally shown in it. Passing 1 for both arguments resets the cell to normal appearance.

Parameters:
  • rows – number of rows to be occupied by this cell, must be >= 1;
  • cols – number of columns to be occupied by this cell, must be >= 1.

SetValue(value) [source]

Sets the actual WYSIWYG representation of the cell value.

Parameters: value – the current text value to insert in the cell.

Note

This method is currently unused as everything is handled inside the XLSText class.

See also

GetValue

SetupCell(book, cell, xf_index, xls_text, xls_comment, hyperlink, rich_text, default_width, default_colour) [source]

Actually sets up the XLSCell class. This is an auxiliary method to avoid cluttering the __init__ method.

Parameters:
  • book – an instance of the xlrd.Book class;
  • cell – an instance of xlrd.sheet.Cell class;
  • xf_index – an index into xlrd.Book.xf_list, which holds a reference to the xlrd.sheet.Cell class (the actual cell for xlrd);
  • xls_text – the actual WYSIWYG cell text, if available;
  • xls_comment – the cell comment (note), if any;
  • hyperlink – an instance of xlrd.sheet.hyperlink;
  • rich_text – if this cell contains text in rich text format, XLSGrid will do its best to render the text as rich text;
  • default_width – this is the default width of the text in 1/256 of the width of the zero character, using default Excel font (first FONT record in the Excel file);
  • default_colour – the “magic” colour used by Excel to draw non-custom border lines.

Note

If you are using version 0.7.1 or lower for xlrd, the hyperlink parameter will always be None as this feature is available only in xlrd 0.7.2 (SVN).

Note

If you are using version 0.7.1 or lower for xlrd, the rich_text parameter will always be None as this feature is available only in xlrd 0.7.2 (SVN).

Note

if Mark Hammonds’ pywin32 package is not available, the xls_text parameter will almost surely not be the WYSIWYG representation of the cell text.

Note

If Mark Hammonds’ pywin32 package is not available, the xls_comment parameter will always be None.

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • infobar
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • xlsgrid »
  • XLSCell


XLSComment

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • xlsgrid »
  • XLSComment

XLSComment

This is a class which holds information about the content of the “comment window” (aka note) in Excel.

Note

If Mark Hammonds’ pywin32 package is not available, this class can not be used.

hierarchy Inheritance Diagram

Inheritance diagram for: XLSComment

Inheritance diagram of XLSComment

Methods Summary

__init__ | Default class constructor.
Draw | Actually draws a small red triangle in the top-right corder of the cell to indicate that a comment is present.

API Class API

class XLSComment(object) [source]

This is a class which holds information about the content of the “comment window” (aka note) in Excel.

Note

If Mark Hammonds’ pywin32 package is not available, this class can not be used.

__init__(comment) [source]

Default class constructor.

Parameters: comment – the actual text contained in the Excel cell comment (note).

Draw(dc, rect) [source]

Actually draws a small red triangle in the top-right corder of the cell to indicate that a comment is present.

Parameters:
  • dc – an instance of wx.DC;
  • rect – an instance of wx.Rect, representing the cell rectangle.

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • infobar
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • xlsgrid »
  • XLSComment


XLSGrid

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • xlsgrid »
  • XLSGrid

XLSGrid

XLSGrid is a class based on wx.grid.Grid that can be used to faithfully reproduce the appearance of a Microsoft Excel spreadsheet (one worksheet per every instance of XLSGrid).

XLSGrid is a completely owner-drawn control, and it relies on the power of wx.grid.PyGridTableBase and wx.grid.PyGridCellRenderer to draw the cell content. For this reasons (and for some others, see the TODOs section), it will work efficiently only for relatively small Excel files.

hierarchy Inheritance Diagram

Inheritance diagram for: XLSGrid

Inheritance diagram of XLSGrid

appearance Control Appearance

XLSGrid

Methods Summary

__init__ | Default class constructor.
DestroyTip | If a comment window or a tooltip over a hyperlink have been created, this
FormatCell | Processes the creation of a single cell (an instance of XLSCell).
GetDefaultFontData | Returns suitable width and height (in pixels) starting from Excel’s own
InstallGridHint | Auxiliary method used to bind a wx.EVT_MOTION event to XLSGrid.
PopulateGrid | This is the main method of this class, and it is used to actually create the cells, size the columns and rows, merging cells, etc...

API Class API

class XLSGrid(gridlib.Grid) [source]

XLSGrid is a class based on wx.grid.Grid that can be used to faithfully reproduce the appearance of a Microsoft Excel spreadsheet (one worksheet per every instance of XLSGrid).

XLSGrid is a completely owner-drawn control, and it relies on the power of wx.grid.PyGridTableBase and wx.grid.PyGridCellRenderer to draw the cell content. For this reasons (and for some others, see the TODOs section), it will work efficiently only for relatively small Excel files.

__init__(parent) [source]

Default class constructor.

Parameters: parent – the grid parent window. Must not be None.

DestroyTip() [source]

If a comment window or a tooltip over a hyperlink have been created, this method destroys them.

FormatCell(book, sheet, row, col, display_texts, comments, hyperlink, rich_text, default_width, default_colour) [source]

Processes the creation of a single cell (an instance of XLSCell).

Parameters:
  • book – an instance of the xlrd.Book class;
  • sheet – an instance of the xlrd.sheet class;
  • row – the row in which this cell lives;
  • col – the column in which this cell lives;
  • display_texts – if Mark Hammonds’ pywin32 package is available, this is the WYSIWYG cell content for all the cells in the Excel worksheet;
  • comments – if Mark Hammonds’ pywin32 package is available, this is a nested list of cell comments (notes) for all the cells in the Excel worksheet;
  • hyperlink – if this cell contains a hyperlink, it will be displayed accordingly;
  • rich_text – if this cell contains text in rich text format, XLSGrid will do its best to render the text as rich text;
  • default_width – this is the default width of the text in 1/256 of the width of the zero character, using default Excel font (first FONT record in the Excel file);
  • default_colour – the “magic” colour used by Excel to draw non-custom border lines.

Note

If you are using version 0.7.1 or lower for xlrd, the hyperlink parameter will always be None as this feature is available only in xlrd 0.7.2 (SVN).

Note

If you are using version 0.7.1 or lower for xlrd, the rich_text parameter will always be None as this feature is available only in xlrd 0.7.2 (SVN).

Note

If Mark Hammonds’ pywin32 package is not available, the display_texts and comments parameter will be two empty nested lists.

GetDefaultFontData(book) [source]

Returns suitable width and height (in pixels) starting from Excel’s own measurements (in characters, whatever that means).

Parameters: book – an instance of the xlrd.Book class.
Returns: a default_width and default_height in pixels, based on the default width of the text in 1/256 of the width of the zero character, using default Excel font (first FONT record in the Excel file).

InstallGridHint() [source]

Auxiliary method used to bind a wx.EVT_MOTION event to XLSGrid.

PopulateGrid(book, sheet, display_texts, comments) [source]

This is the main method of this class, and it is used to actually create the cells, size the columns and rows, merging cells, etc...

Parameters:
  • book – an instance of the xlrd.Book class;
  • sheet – an instance of the xlrd.sheet class;
  • display_texts – if Mark Hammonds’ pywin32 package is available, this is the WYSIWYG cell content for all the cells in the Excel worksheet;
  • comments – if Mark Hammonds’ pywin32 package is available, this is a nested list of cell comments (notes) for all the cells in the Excel worksheet.

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • infobar
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • xlsgrid »
  • XLSGrid


XLSRenderer

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • xlsgrid »
  • XLSRenderer

XLSRenderer

This class is responsible for actually drawing the cell in the grid.

hierarchy Inheritance Diagram

Inheritance diagram for: XLSRenderer

Inheritance diagram of XLSRenderer

Methods Summary

__init__ | Default class constructor.
Draw | Draw the given cell on the provided dc inside the given rectangle using

API Class API

class XLSRenderer(gridlib.PyGridCellRenderer) [source]

This class is responsible for actually drawing the cell in the grid.

__init__(cell) [source]

Default class constructor.

Parameters: cell – an instance of XLSCell.

Draw(grid, attr, dc, rect, row, col, isSelected) [source]

Draw the given cell on the provided dc inside the given rectangle using default or selected state corresponding to the isSelected value.

Parameters:
  • grid – an instance of wx.grid.Grid;
  • attr – an instance of wx.grid.GridCellAttr;
  • dc – an instance of wx.DC;
  • rect – an instance of wx.Rect, representing the cell rectangle;
  • row – the row in which this cell lives;
  • col – the column in which this cell lives;
  • isSelected – True if the cell is selected, False otherwise.

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • infobar
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • xlsgrid »
  • XLSRenderer


XLSRichText

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • xlsgrid »
  • XLSRichText

XLSRichText

This is a class which holds information about the cell content, in terms of actual cell value, font, text colour, alignment and formatting. In addition to what XLSText does, this class attempts to handle cells with rich text content.

hierarchy Inheritance Diagram

Inheritance diagram for: XLSRichText

Inheritance diagram of XLSRichText

supclasses Known Superclasses

  • xlsgrid.XLSText

Methods Summary

__init__ | Default class constructor.
BuildChunks | Splits the cell content accordingly to their rich text format index.
Draw | Actually draws all the chunks of text on a grid cell, one by one.
Measure | Convenience method to measure the maximum height and total width of all the chunks of text composing our rich text string.

API Class API

class XLSRichText(XLSText) [source]

This is a class which holds information about the cell content, in terms of actual cell value, font, text colour, alignment and formatting. In addition to what XLSText does, this class attempts to handle cells with rich text content.

__init__(book, cell, xf_index, display_text=None, hyperlink=None, rich_text=None, default_width=10) [source]

Default class constructor.

Parameters:
  • book – an instance of the xlrd.Book class;
  • cell – an instance of xlrd.sheet.Cell class;
  • xf_index – an index into xlrd.Book.xf_list, which holds a reference to the xlrd.sheet.Cell class (the actual cell for xlrd);
  • display_text – if Mark Hammonds’ pywin32 package is available, this is the WYSIWYG cell content;
  • hyperlink – if this cell contains a hyperlink, it will be displayed accordingly;
  • rich_text – if this cell contains text in rich text format, XLSGrid will do its best to render the text as rich text;
  • default_width – this is the default width of the text in 1/256 of the width of the zero character, using default Excel font (first FONT record in the Excel file).

Note

If you are using version 0.7.1 or lower for xlrd, the hyperlink parameter will always be None as this feature is available only in xlrd 0.7.2 (SVN).

Note

If you are using version 0.7.1 or lower for xlrd, this class will note be used by XLSGrid.

Warning

This class currently supports only single-line non-rotated text, and it discards properties like shrink-to-fit and wrapping.

BuildChunks(book, xf_index, rich_text) [source]

Splits the cell content accordingly to their rich text format index.

Parameters:
  • book – an instance of the xlrd.Book class;
  • xf_index – an index into xlrd.Book.xf_list, which holds a reference to the xlrd.sheet.Cell class (the actual cell for xlrd);
  • rich_text – if this cell contains text in rich text format, XLSGrid will do its best to render the text as rich text.

Draw(dc, rect) [source]

Actually draws all the chunks of text on a grid cell, one by one.

Parameters:
  • dc – an instance of wx.DC;
  • rect – an instance of wx.Rect, representing the cell rectangle.

Measure(dc) [source]

Convenience method to measure the maximum height and total width of all the chunks of text composing our rich text string.

Parameters: dc – an instance of wx.DC.

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • infobar
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • xlsgrid »
  • XLSRichText


XLSTable

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • xlsgrid »
  • XLSTable

XLSTable

The almost abstract base class for grid tables.

A grid table is responsible for storing the grid data and, indirectly, grid cell attributes. The data can be stored in the way most convenient for the application but has to be provided in string form to wx.grid.Grid.

hierarchy Inheritance Diagram

Inheritance diagram for: XLSTable

Inheritance diagram of XLSTable

Methods Summary

__init__ | Default class constructor.
GetAttr | Return the attribute for the given cell.
GetNumberCols | Returns the number of columns in the table.
GetNumberRows | Returns the number of rows in the table.
GetRawValue | Returns the “raw” value for the cell content.
GetValue | Returns the cell content for the specified row and column.
SetValue | sets the cell content for the specified row and column.

API Class API

class XLSTable(gridlib.PyGridTableBase) [source]

The almost abstract base class for grid tables.

A grid table is responsible for storing the grid data and, indirectly, grid cell attributes. The data can be stored in the way most convenient for the application but has to be provided in string form to wx.grid.Grid.

__init__(grid, cells, rows, cols) [source]

Default class constructor.

Parameters:
  • grid – an instance of wx.grid.Grid;

  • cells – a Python dictionary. For every key (row, col), the corresponding value is an instance of XLSCell;
  • rows – the number of rows in the table;
  • cols – the number of columns in the table.

GetAttr(row, col, kind) [source]

Return the attribute for the given cell.

Parameters:
  • row – the row in which this cell lives;
  • col – the column in which this cell lives;
  • kind – the kind of the attribute to return.

GetNumberCols() [source]

Returns the number of columns in the table.

GetNumberRows() [source]

Returns the number of rows in the table.

GetRawValue(row, col) [source]

Returns the “raw” value for the cell content.

Parameters:
  • row – the row in which this cell lives;
  • col – the column in which this cell lives.

GetValue(row, col) [source]

Returns the cell content for the specified row and column.

Parameters:
  • row – the row in which this cell lives;
  • col – the column in which this cell lives.

SetValue(row, col, value) [source]

sets the cell content for the specified row and column.

Parameters:
  • row – the row in which this cell lives;
  • col – the column in which this cell lives;
  • value – the new value to assign to the specified cell.

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • infobar
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • xlsgrid »
  • XLSTable


XLSText

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • xlsgrid »
  • XLSText

XLSText

This is a class which holds information about the cell content, in terms of actual cell value, font, text colour, alignment and formatting.

hierarchy Inheritance Diagram

Inheritance diagram for: XLSText

Inheritance diagram of XLSText

subclasses Known Subclasses

  • xlsgrid.XLSRichText

Methods Summary

__init__ | Default class constructor.
CombineAttr | Combines the input attribute attr with the features of the XLSText class.
CreateAlignment | Creates a suitable wxPython alignment flag for the text starting from a
CreateFont | Creates a suitable wxPython font starting from an Excel font.
CreateFormat | This method tries to guess the best format to apply to the current text value.
CreateTextColour | Creates a suitable wxPython colour for the text starting from a xlrd
Draw | Actually draws the text value on a grid cell.
FormatString | This method tries to guess the best format to apply to the current text value.
GetValue | Returns the string representation of the cell text value.
IsHyperLink | Returns whether the cell text is representing a hyperlink.
SetupHyperlink | Sets up the cell text value in case it represents a hyperlink.

API Class API

class XLSText(object) [source]

This is a class which holds information about the cell content, in terms of actual cell value, font, text colour, alignment and formatting.

__init__(book, cell, xf_index, display_text=None, hyperlink=None, default_width=10) [source]

Default class constructor.

Parameters:
  • book – an instance of the xlrd.Book class;
  • cell – an instance of xlrd.sheet.Cell class;
  • xf_index – an index into xlrd.Book.xf_list, which holds a reference to the xlrd.sheet.Cell class (the actual cell for xlrd);
  • display_text – if Mark Hammonds’ pywin32 package is available, this is the WYSIWYG cell content;
  • hyperlink – if this cell contains a hyperlink, it will be displayed accordingly;
  • default_width – this is the default width of the text in 1/256 of the width of the zero character, using default Excel font (first FONT record in the Excel file).

Note

If you are using version 0.7.1 or lower for xlrd, the hyperlink parameter will always be None as this feature is available only in xlrd 0.7.2 (SVN).

CombineAttr(attr) [source]

Combines the input attribute attr with the features of the XLSText class.

Parameters: attr – an instance of wx.grid.GridCellAttr.

CreateAlignment(alignment, default_width) [source]

Creates a suitable wxPython alignment flag for the text starting from a xlrd class representing this alignment.

Parameters:
  • alignment – an instance of xlrd.formatting.XFAlignment class;
  • default_width – this is the default width of the text in 1/256 of the width of the zero character, using default Excel font (first FONT record in the Excel file).

CreateFont(font) [source]

Creates a suitable wxPython font starting from an Excel font.

Parameters: font – an instance of xlrd.formatting.Font class.

Note

There is currently no support for strikethrough fonts, although xlrd correctly reports this format. The issue is a bug in wxWidgets itself which doesn’t allow the creation of strikethrough fonts. See (http://trac.wxwidgets.org/ticket/9907).

CreateFormat(format, cell, datemode) [source]

This method tries to guess the best format to apply to the current text value.

Parameters:
  • format – an instance of xlrd.formatting.Format class;
  • cell – an instance of xlrd.sheet.Cell class;
  • datemode – the datemode associated with this Excel workbook.

Note

This method is used only if Mark Hammonds’ pywin32 package is not available to try and format the cell text in an intelligent way.

Warning

The formatting applied by this method is severely limited; for instance, you won’t probably get the exact WYSIWYG between the Excel spreadsheet and XLSGrid.

CreateTextColour(text_colour) [source]

Creates a suitable wxPython colour for the text starting from a xlrd tuple representing this colour.

Parameters: text_colour – a tuple representing the RGB components of the colour. If text_colour is None, use the default wx.SYS_COLOUR_WINDOWTEXT.

Draw(dc, rect) [source]

Actually draws the text value on a grid cell.

Parameters:
  • dc – an instance of wx.DC;
  • rect – an instance of wx.Rect, representing the cell rectangle.

FormatString(value, isDate, format_str) [source]

This method tries to guess the best format to apply to the current text value.

Parameters:
  • value – the actual raw cell text value;
  • isDate – True if this value represents a xlrd date object, False otherwise;
  • format_str – the actual formatting string as extracted from Excel.

Note

This method is used only if Mark Hammonds’ pywin32 package is not available to try and format the cell text in an intelligent way.

Warning

The formatting applied by this method is severely limited; for instance, you won’t probably get the exact WYSIWYG between the Excel spreadsheet and XLSGrid.

GetValue() [source]

Returns the string representation of the cell text value.

IsHyperLink() [source]

Returns whether the cell text is representing a hyperlink.

Returns: True if the cell text represents a hyperlink, False otherwise.

SetupHyperlink(hyperlink) [source]

Sets up the cell text value in case it represents a hyperlink.

Parameters: hyperlink – an instance of xlrd.sheet.hyperlink.

Note

If you are using version 0.7.1 or lower for xlrd, the hyperlink parameter will always be None as this feature is available only in xlrd 0.7.2 (SVN).

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • infobar
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • xlsgrid »
  • XLSText


SVN Revision 68881 For xlsgrid

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • xlsgrid »
  • SVN Revision 68881 For xlsgrid

svn SVN Revision 68881 For xlsgrid

This file contains the SVN revision history for xlsgrid, at revision 68881.

Available information include commit date, the name of the committer, the file size, the SVN log messages and a diff from the previous version (if available).

File Information

  • Commit Date: 01-Nov-2011 19:42:21 UTC
  • Committer: AG
  • File Size: 74528 byte(s)

Log Messages

The following log message was entered by the committer:

  • AGW: General overhaul of the documentation, much improved. All the widgets have their own sample usage in the docs as well;

  • FlatNotebook: Added the FNB_NAV_BUTTONS_WHEN_NEEDED style, which hides the navigation left/right arrows if all tabs fit;

  • RibbonBar: - Added the EVT_RIBBONBAR_TAB_LEFT_DCLICK event, which generates a special event

    when a ribbon bar tab is double-clicked;

    • Added support for toggle buttons;
    • Improved support for ribbon panel sizers: panels with sizers should now automatically minimise at small sizes, and behave properly when popping up from a minimised state;
    • Added tooltips via SetToolTip for those buttons which have the help_string attribute set.

  • XLSGrid: a new widget was added to AGW, termed XLSGrid. It’s based on wx.grid.Grid and can be used to faithfully reproduce the appearance of a Microsoft Excel spreadsheets.

Diff To Previous Version (Unavailable)

Version SVN diff:

No diff available.

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • xlsgrid »
  • SVN Revision 68881 For xlsgrid


SVN Revision 68933 For xlsgrid

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • xlsgrid »
  • SVN Revision 68933 For xlsgrid

svn SVN Revision 68933 For xlsgrid

This file contains the SVN revision history for xlsgrid, at revision 68933.

Available information include commit date, the name of the committer, the file size, the SVN log messages and a diff from the previous version (if available).

File Information

  • Commit Date: 02-Oct-2011 19:32:45 UTC
  • Committer: AG
  • File Size: 74543 byte(s)

Log Messages

The following log message was entered by the committer:

AGW: Some further refactoring of the docs: - Added downloadable snippets of code in the Sphinx documentation itself; - Re-run 2to3 afresh so that the patches are up-to-date for Python 3.

Diff To Previous Version (68898)

Version SVN diff:

--- wxPython/3rdParty/AGW/agw/xlsgrid.py    2011/08/25 20:02:59     68898
+++ wxPython/3rdParty/AGW/agw/xlsgrid.py    2011/08/27 17:11:41     68933
@@ -601,7 +601,7 @@
of the width of the zero character, using default Excel font (first FONT
record in the Excel file).

-        :note: If you are using version 0.7.1 or lower for `xlrd`, the `hyperlink`
+        :note: If you are using version 0.7.1 or lower for `xlrd`, the *hyperlink*
parameter will always be ``None`` as this feature is available only in
`xlrd` 0.7.2 (SVN).
"""
@@ -839,7 +839,7 @@

:param `hyperlink`: an instance of `xlrd.sheet.hyperlink`.

-        :note: If you are using version 0.7.1 or lower for `xlrd`, the `hyperlink`
+        :note: If you are using version 0.7.1 or lower for `xlrd`, the *hyperlink*
parameter will always be ``None`` as this feature is available only in
`xlrd` 0.7.2 (SVN).
"""
@@ -975,7 +975,7 @@
of the width of the zero character, using default Excel font (first FONT
record in the Excel file).

-        :note: If you are using version 0.7.1 or lower for `xlrd`, the `hyperlink`
+        :note: If you are using version 0.7.1 or lower for `xlrd`, the *hyperlink*
parameter will always be ``None`` as this feature is available only in
`xlrd` 0.7.2 (SVN).

@@ -1484,7 +1484,7 @@
:param `default_colour`: the "magic" colour used by Excel to draw non-custom
border lines.

-        :note: If you are using version 0.7.1 or lower for `xlrd`, the `hyperlink`
+        :note: If you are using version 0.7.1 or lower for `xlrd`, the *hyperlink*
parameter will always be ``None`` as this feature is available only in
`xlrd` 0.7.2 (SVN).

@@ -1493,7 +1493,7 @@
`xlrd` 0.7.2 (SVN).

:note: if Mark Hammonds' `pywin32` package is not available, the `xls_text`
-         parameter will almost surely not be thw WYSIWYG representation of the cell
+         parameter will almost surely not be the WYSIWYG representation of the cell
text.

:note: If Mark Hammonds' `pywin32` package is not available, the `xls_comment`
@@ -1528,7 +1528,7 @@
:param `default_colour`: the "magic" colour used by Excel to draw non-custom
border lines.

-        :note: If you are using version 0.7.1 or lower for `xlrd`, the `hyperlink`
+        :note: If you are using version 0.7.1 or lower for `xlrd`, the *hyperlink*
parameter will always be ``None`` as this feature is available only in
`xlrd` 0.7.2 (SVN).

@@ -1537,7 +1537,7 @@
`xlrd` 0.7.2 (SVN).

:note: if Mark Hammonds' `pywin32` package is not available, the `xls_text`
-         parameter will almost surely not be thw WYSIWYG representation of the cell
+         parameter will almost surely not be the WYSIWYG representation of the cell
text.

:note: If Mark Hammonds' `pywin32` package is not available, the `xls_comment`
@@ -1986,7 +1986,7 @@
:param `default_colour`: the "magic" colour used by Excel to draw non-custom
border lines.

-        :note: If you are using version 0.7.1 or lower for `xlrd`, the `hyperlink`
+        :note: If you are using version 0.7.1 or lower for `xlrd`, the *hyperlink*
parameter will always be ``None`` as this feature is available only in
`xlrd` 0.7.2 (SVN).

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • xlsgrid »
  • SVN Revision 68933 For xlsgrid


SVN Revision 68988 For xlsgrid

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • xlsgrid »
  • SVN Revision 68988 For xlsgrid

svn SVN Revision 68988 For xlsgrid

This file contains the SVN revision history for xlsgrid, at revision 68988.

Available information include commit date, the name of the committer, the file size, the SVN log messages and a diff from the previous version (if available).

File Information

  • Commit Date: 03-Sep-2011 04:44:14 UTC
  • Committer: RD
  • File Size: 72454 byte(s)

Log Messages

The following log message was entered by the committer:

set native EOL

Diff To Previous Version (68933)

Version SVN diff:

--- wxPython/3rdParty/AGW/agw/xlsgrid.py    2011/08/27 17:11:41     68933
+++ wxPython/3rdParty/AGW/agw/xlsgrid.py    2011/09/03 04:44:14     68988
@@ -1,2090 +1,2090 @@
-# --------------------------------------------------------------------------------- #
-# XLSGRID wxPython IMPLEMENTATION
-#
-# Andrea Gavana @ 08 Aug 2011
-# Latest Revision: 17 Aug 2011, 15.00 GMT
-#
-#
-# TODO List
-#
-# Current todo list:
-#
-# 1. There is currently no support for rich text, i.e. strings containing partial
-#    bold, italic and underlined text, change of font inside a string, etc... xlrd
-#    supports those (from version 0.7.2 in SVN) but there is no easy way to handle
-#    changing fonts/colours/formatting in the same string in wxPython;
-#
-# 2. XLSGrid is sufficiently efficient and fast for reasonably small Excel files.
-#    There might be some improvement to be made in the code to make it work with
-#    bigger files and in a faster way;
-#
-# 3. There is currently no support for strikethrough fonts, although xlrd correctly
-#    reports this format. The issue is a bug in wxWidgets itself which doesn't
-#    allow the creation of strikethrough fonts (http://trac.wxwidgets.org/ticket/9907).
-#
-# 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
-# --------------------------------------------------------------------------------- #
-
-
-"""
-L{XLSGrid} is a class based on `wx.grid.Grid` that can be used to faithfully
-reproduce the appearance of a Microsoft Excel spreadsheet (one worksheet per
-every instance of L{XLSGrid}).
-
-
-Description
-===========
-
-L{XLSGrid} is a class based on `wx.grid.Grid` that can be used to faithfully
-reproduce the appearance of a Microsoft Excel spreadsheet (one worksheet per
-every instance of L{XLSGrid}).
-
-L{XLSGrid} is a completely owner-drawn control, and it relies on the power of
-`wx.grid.PyGridTableBase` and `wx.grid.PyGridCellRenderer` to draw the cell
-content. For this reasons (and for some others, see the TODOs section), it will
-work efficiently only for relatively small Excel files.
-
-:note: L{XLSGrid} **requires** the `xlrd` package from:
-
- http://pypi.python.org/pypi/xlrd
-
- Minimum version requirement for `xlrd` is 0.7.1. If you wish to have
- support for hyperlinks inside cells and rich text content, you need the
- SVN version of `xlrd`.
-
-:note: On Windows, it is **strongly** recommended to install Mark Hammonds'
- `pywin32` package:
-
- http://sourceforge.net/projects/pywin32/
-
- This will allow you to perfectly reproduce the appearance of the Excel
- worksheet in your instance of L{XLSGrid}.
-
-:warning: If Mark Hammonds' `pywin32` package is not available, the formatting
- capabilities of L{XLSGrid} are severely limited; for instance, you won't
- probably get the exact WYSIWYG between the Excel spreadsheet and L{XLSGrid}.
-
-:warning: L{XLSGrid} can only read Excel `.xls` files, not the newer versions
- `.xlsx` generated by Office 2007/2010. If you have a `.xlsx` file, you will
- need to save it in 1997-2003 Office compatibility mode.
-
-
-Currently this class provides a read-only subclass of `wx.grid.Grid`, with
-the following formatting features already implemented:
-
-* Cell background: support for any cell background colour and fill pattern
-  (hatching) in the Excel default set. There currently is no support for
-  gradient shading inside a cell as `xlrd` doesn't report this information.
-
-* Cell borders: support for all the border types and colours exposed by Excel
-  (left, top, bottom, right and diagonal borders, thin, double, thick, ect...
-  line styles).
-
-* Cell text: support for all kind of fonts (except strikethrough, but this is
-  a bug in wxWidgets), and font colours. As a subset of text/font capabilities,
-  L{XLSGrid} supports the following features found in Excel:
-
-  - Horizontal alignment: left, right, centered, left-indented;
-  - Vertical alignment: left, right, centered;
-  - Text direction: left-to-right or right-to-left;
-  - Text-wrapping: wrapping long texts inside a grid cell;
-  - Shrink-to-fit: text font is reduced until the text can fit in a one-line
-    inside the grid cell;
-  - Text rotation: text can be rotated from +90 to -90 degrees.
-
-* Cell rich text (new in version 0.2): support for strings containing partial
-  bold, italic and underlined text, change of font inside a string etc...
-  Cells with rich text content can not be multi-line and they will not honour
-  the `shrink-to-fit` and `wrapping` settings.
-
-* Cell text appearance: if you are using Mark Hammonds' `pywin32` package, the
-  text displayed in the L{XLSGrid} cells has exactly the same appearance as in
-  the Excel spreadsheet.
-
-* Cell comments (notes): if you are using Mark Hammonds' `pywin32` package,
-  cell comments (notes) are extracted and you will see a small red triangle at
-  the top-right corner of any cell containing a comment. Hovering with the
-  mouse on that cell will pop-up a "comment-window" displaying the comment
-  text (the comment window is based on `wx.lib.agw.supertooltip`).
-
-* Cell hyperlinks: starting from version 0.7.2 (SVN), `xlrd` is capable of
-  extracting hyperlinks from Excel cells. This will be appropriately displayed
-  in L{XLSGrid} with a cursor changing and a tooltip on that cell.
-
-* Cell merging: merged cells in the Excel spreadsheet will be correctly handled
-  by L{XLSGrid}.
-
-* Columns and rows sizes: L{XLSGrid} calculates the correct rows and columns
-  sizes based on the Excel reported values in characters. The calculations are
-  based on the default width of the text in 1/256 of the width of the zero
-  character, using default Excel font (first FONT record in the Excel file).
-
-
-And a lot more. Check the demo for an almost complete review of the functionalities.
-
-
-Usage
-=====
-
-Sample usage::
-
-    import wx
-    import xlrd
-    import os
-
-    import xlsgrid as XG
-
-    class MyFrame(wx.Frame):
-
-        def __init__(self):
-
-            wx.Frame.__init__(self, parent, -1, "XLSGrid Demo", size=(1000, 800))
-
-            filename = os.path.join(os.getcwd(), "Excel", "Example_1.xls")
-            sheetname = "Example_1"
-
-            book = xlrd.open_workbook(filename, formatting_info=1)
-
-            sheet = book.sheet_by_name(sheetname)
-            rows, cols = sheet.nrows, sheet.ncols
-
-            comments, texts = XG.ReadExcelCOM(filename, sheetname, rows, cols)
-
-            xls_grid = XG.XLSGrid(self)
-            xls_grid.PopulateGrid(book, sheet, texts, comments)
-
-
-    # our normal wxApp-derived class, as usual
-
-    app = wx.PySimpleApp()
-
-    frame = MyFrame(None)
-    app.SetTopWindow(frame)
-    frame.Show()
-
-    app.MainLoop()
-
-
-:note: Please note that you **have to** pass the keyword `formatting_info` to
- the method `xlrd.open_workbook` to obtain the cell formatting.
-
-
-TODOs
-=====
-
-1. L{XLSGrid} is sufficiently efficient and fast for reasonably small Excel files.
-   There might be some improvement to be made in the code to make it work with
-   bigger files and in a faster way;
-2. `wx.grid.Grid` seems to completely redraw itself at every resize event, even
-   if the cell content has not changed and it has not been damaged (this seems
-   to be fixed in wxPython 2.9.2.1);
-3. There is currently no support for strikethrough fonts, although `xlrd` correctly
-   reports this format. The issue is a bug in wxWidgets itself which doesn't
-   allow the creation of strikethrough fonts (http://trac.wxwidgets.org/ticket/9907).
-
-
-Supported Platforms
-===================
-
-L{XLSGrid} has been tested on the following platforms:
-  * Windows (Windows Vista and 7);
-
-
-Window Styles
-=============
-
-`No particular window styles are available for this class.`
-
-
-Events Processing
-=================
-
-`No custom events are available for this class.`
-
-
-License And Version
-===================
-
-L{XLSGrid} is distributed under the wxPython license.
-
-Latest Revision: Andrea Gavana @ 17 Aug 2011, 15.00 GMT
-
-Version 0.3
-
-"""
-
-# Version Info
-__version__ = "0.3"
-
-# Start the imports
-import wx
-import os
-
-try:
-    import xlrd
-except ImportError:
-    pass
-
-import datetime
-import string
-
-import wx.grid as gridlib
-
-from wx.lib.embeddedimage import PyEmbeddedImage
-from wx.lib.wordwrap import wordwrap
-
-import supertooltip as STT
-
-from math import pi, sin, cos
-from operator import attrgetter
-
-_hasWin32 = False
-
-if wx.Platform == "__WXMSW__":
-    try:
-        from win32com.client import Dispatch
-        import pywintypes
-        _hasWin32 = True
-    except ImportError:
-        pass
-
-
-#----------------------------------------------------------------------
-# Constants used to translate xlrd stuff into wxPython stuff
-#----------------------------------------------------------------------
-
-BOTTOM = wx.BOTTOM
-TOP = wx.TOP
-LEFT = wx.LEFT
-RIGHT = wx.RIGHT
-DIAGONAL = 2 << 7
-
-XF_BORDER_STYLES = {"bottom": BOTTOM, "left": LEFT, "right": RIGHT,
-                    "top": TOP, "diag": DIAGONAL}
-
-HORIZONTAL_ALIGNMENTS = {0: 0, 1: 0, 2: wx.ALIGN_CENTER_HORIZONTAL, 3: wx.ALIGN_RIGHT}
-VERTICAL_ALIGNMENTS   = {0: 0, 1: wx.ALIGN_CENTER_VERTICAL, 2: wx.ALIGN_BOTTOM,
-                         3: wx.ALIGN_CENTER_VERTICAL, 4:wx.ALIGN_CENTER_VERTICAL}
-
-NO_LINE = 0x0
-THIN = 0x1
-MEDIUM = 0x2
-DASHED = 0x3
-DOTTED = 0x4
-THICK = 0x5
-DOUBLE = 0x6
-HAIR = 0x7
-MEDIUM_DASHED = 0x8
-THIN_DASH_DOTTED = 0x9
-MEDIUM_DASH_DOTTED = 0xA
-THIN_DASH_DOT_DOTTED = 0xB
-MEDIUM_DASH_DOT_DOTTED = 0xC
-SLANTED_MEDIUM_DASH_DOTTED = 0xD
-
-XF_PEN_STYLES = {NO_LINE: (0, None), THIN: (1, wx.SOLID), MEDIUM: (2, wx.SOLID),
-                 DASHED: (1, wx.SHORT_DASH), DOTTED: (1, wx.DOT),
-                 THICK: (3, wx.SOLID), DOUBLE: (1, wx.SOLID), HAIR: (1, wx.DOT),
-                 MEDIUM_DASHED: (2, wx.LONG_DASH), THIN_DASH_DOTTED: (1, wx.DOT_DASH),
-                 MEDIUM_DASH_DOTTED: (2, wx.DOT_DASH), THIN_DASH_DOT_DOTTED: (1, wx.DOT_DASH),
-                 MEDIUM_DASH_DOT_DOTTED: (2, wx.DOT_DASH),
-                 SLANTED_MEDIUM_DASH_DOTTED: (2, wx.DOT_DASH)
-                 }
-
-XF_FONT_FAMILY = {0: wx.SWISS, 1: wx.ROMAN, 2: wx.SWISS,
-                  3: wx.MODERN, 4: wx.SCRIPT, 5: wx.DECORATIVE}
-
-# Unicode ordinals for Hebrew, Arabic and Syriac
-# I don't know if there are other RTL languages
-RTL_UNICODE = range(1424, 1872)
-
-# To guess text direction we exclude digits and punctuation
-USELESS_CHARS = string.punctuation + string.digits + " "
-
-
-#----------------------------------------------------------------------
-# Images used to draw the hatching on Excel cells background
-#----------------------------------------------------------------------
-
-_xls_background_01 = PyEmbeddedImage(
-    "iVBORw0KGgoAAAANSUhEUgAAAAQAAAAECAIAAAAmkwkpAAAAA3NCSVQICAjb4U/gAAAADElE"
-    "QVQImWNgIB0AAAA0AAEjQ4N1AAAAAElFTkSuQmCC")
-
-#----------------------------------------------------------------------
-_xls_background_02 = PyEmbeddedImage(
-    "iVBORw0KGgoAAAANSUhEUgAAAAQAAAAECAIAAAAmkwkpAAAAA3NCSVQICAjb4U/gAAAAFklE"
-    "QVQImWNgYGD4//8/lESwIAC7DABt4hfpI2a12wAAAABJRU5ErkJggg==")
-
-#----------------------------------------------------------------------
-_xls_background_03 = PyEmbeddedImage(
-    "iVBORw0KGgoAAAANSUhEUgAAAAQAAAAECAIAAAAmkwkpAAAAA3NCSVQICAjb4U/gAAAAE0lE"
-    "QVQImWP4//8/AxqACuGUAQBI+Qv1NTPP3AAAAABJRU5ErkJggg==")
-
-#----------------------------------------------------------------------
-_xls_background_04 = PyEmbeddedImage(
-    "iVBORw0KGgoAAAANSUhEUgAAAAQAAAAECAIAAAAmkwkpAAAAA3NCSVQICAjb4U/gAAAAH0lE"
-    "QVQImXXJsQ0AIAAEIc79d34LazsSwjbgPFXoOxdcCQwBh7OgqgAAAABJRU5ErkJggg==")
-
-#----------------------------------------------------------------------
-_xls_background_05 = PyEmbeddedImage(
-    "iVBORw0KGgoAAAANSUhEUgAAAAQAAAAECAIAAAAmkwkpAAAAA3NCSVQICAjb4U/gAAAAFUlE"
-    "QVQImWNgwAUY////D+cwIcsAAEggAwHHgMubAAAAAElFTkSuQmCC")
-
-#----------------------------------------------------------------------
-_xls_background_06 = PyEmbeddedImage(
-    "iVBORw0KGgoAAAANSUhEUgAAAAQAAAAECAIAAAAmkwkpAAAAA3NCSVQICAjb4U/gAAAAG0lE"
-    "QVQImWNkYGBgYGD4//8/AwMDEwMSwM0BAISAAwUnufp7AAAAAElFTkSuQmCC")
-
-#----------------------------------------------------------------------
-_xls_background_07 = PyEmbeddedImage(
-    "iVBORw0KGgoAAAANSUhEUgAAAAQAAAAECAIAAAAmkwkpAAAAA3NCSVQICAjb4U/gAAAAHklE"
-    "QVQImWNkYGBgYGD4//8/EgVh/P//H86HikH4APOCFO3yiGicAAAAAElFTkSuQmCC")
-
-#----------------------------------------------------------------------
-_xls_background_08 = PyEmbeddedImage(
-    "iVBORw0KGgoAAAANSUhEUgAAAAQAAAAECAIAAAAmkwkpAAAAA3NCSVQICAjb4U/gAAAAHUlE"
-    "QVQImWP4////////GSAAzvr//z8jmhADXCUAQSkU7eggG3gAAAAASUVORK5CYII=")
-
-#----------------------------------------------------------------------
-_xls_background_09 = PyEmbeddedImage(
-    "iVBORw0KGgoAAAANSUhEUgAAAAQAAAAECAIAAAAmkwkpAAAAA3NCSVQICAjb4U/gAAAAIElE"
-    "QVQImWNkYGBgYGD4//8/AwMDEwMy+P//P0QYXQYACtQI/cTE6U0AAAAASUVORK5CYII=")
-
-#----------------------------------------------------------------------
-_xls_background_10 = PyEmbeddedImage(
-    "iVBORw0KGgoAAAANSUhEUgAAAAQAAAAECAIAAAAmkwkpAAAAA3NCSVQICAjb4U/gAAAAG0lE"
-    "QVQImW3IsQ0AAAjAIPz/6LobGRmgclVfswpsCPmQczsGAAAAAElFTkSuQmCC")
-
-#----------------------------------------------------------------------
-_xls_background_11 = PyEmbeddedImage(
-    "iVBORw0KGgoAAAANSUhEUgAAAAQAAAAECAIAAAAmkwkpAAAAA3NCSVQICAjb4U/gAAAAFklE"
-    "QVQImWNgQAKM////h3OYkGVQOABvOgMD4NUKkwAAAABJRU5ErkJggg==")
-
-#----------------------------------------------------------------------
-_xls_background_12 = PyEmbeddedImage(
-    "iVBORw0KGgoAAAANSUhEUgAAAAQAAAAECAIAAAAmkwkpAAAAA3NCSVQICAjb4U/gAAAAG0lE"
-    "QVQImWNkYGD4//8/AwMDAwMDEwMSwM0BAI13AwWY+Mx+AAAAAElFTkSuQmCC")
-
-#----------------------------------------------------------------------
-_xls_background_13 = PyEmbeddedImage(
-    "iVBORw0KGgoAAAANSUhEUgAAAAQAAAAECAIAAAAmkwkpAAAAA3NCSVQICAjb4U/gAAAAI0lE"
-    "QVQImT3KsQ0AMAyAMMj/P9MhUUcLBCoAmEo9bFn7H/UBXEwMBN75abEAAAAASUVORK5CYII=")
-
-#----------------------------------------------------------------------
-_xls_background_14 = PyEmbeddedImage(
-    "iVBORw0KGgoAAAANSUhEUgAAAAQAAAAECAIAAAAmkwkpAAAAA3NCSVQICAjb4U/gAAAAIElE"
-    "QVQImT3KoQEAAAwCINz/P7tmI5C2QJKb2t6EYPMBOOUMBIWcMEIAAAAASUVORK5CYII=")
-
-#----------------------------------------------------------------------
-_xls_background_15 = PyEmbeddedImage(
-    "iVBORw0KGgoAAAANSUhEUgAAAAQAAAAECAIAAAAmkwkpAAAAA3NCSVQICAjb4U/gAAAAGUlE"
-    "QVQImWNgQAKMDAwM////h3CYkGVQOABmQwMDJpgq9gAAAABJRU5ErkJggg==")
-
-#----------------------------------------------------------------------
-_xls_background_16 = PyEmbeddedImage(
-    "iVBORw0KGgoAAAANSUhEUgAAAAQAAAAECAIAAAAmkwkpAAAAA3NCSVQICAjb4U/gAAAAHklE"
-    "QVQImWNgYGD4//8/lISzIAwEnxEqwMDAyMgIALKwF+2ym+hoAAAAAElFTkSuQmCC")
-
-#----------------------------------------------------------------------
-_xls_background_17 = PyEmbeddedImage(
-    "iVBORw0KGgoAAAANSUhEUgAAAAQAAAAECAIAAAAmkwkpAAAAA3NCSVQICAjb4U/gAAAAIklE"
-    "QVQImWNkYGD4//8/AwMDAwMDI5zFwMDABBVjZESXAQAc+AkAQ4bzDAAAAABJRU5ErkJggg==")
-
-#----------------------------------------------------------------------
-_xls_background_18 = PyEmbeddedImage(
-    "iVBORw0KGgoAAAANSUhEUgAAAAgAAAAECAIAAAA8r+mnAAAAA3NCSVQICAjb4U/gAAAAH0lE"
-    "QVQImWNkYGD4//8/AwZgxCrKwMDAhKKKkZGwDgA83QkAy10JvwAAAABJRU5ErkJggg==")
-
-#----------------------------------------------------------------------
-
-
-def SplitThousands(s, tSep=',', dSep='.'):
-    """
-    Splits a general float on thousands. GIGO on general input.
-
-    :param `s`: can be a float or a string, representing a number;
-    :param `tSep`: the character to be used as thousands separator;
-    :param `dSep`: the character to be used as decimal separator.
-
-    :returns: a string properly formatted with thousands and decimal
-     separators in it.
-
-    :note: This method is used only if Mark Hammonds' `pywin32` package is
-     not available to try and format a number in an intelligent way.
-
-    :note: This code has been obtained from the public domain:
-
-     http://code.activestate.com/recipes/498181-add-thousands-separator-commas-to-formatted-number/#c14
-
-    """
-
-    if not isinstance(s, basestring):
-        s = unicode(s, "utf-8", "ignore")
-
-    cnt = 0
-    numChars = dSep + '0123456789'
-    ls = len(s)
-
-    while cnt < ls and s[cnt] not in numChars:
-        cnt += 1
-
-    lhs = s[0:cnt]
-    s = s[cnt:]
-
-    if dSep == '':
-        cnt = -1
-    else:
-        cnt = s.rfind(dSep)
-
-    if cnt > 0:
-        rhs = dSep + s[cnt+1:]
-        s = s[:cnt]
-    else:
-        rhs = ''
-
-    splt = ''
-    while s != '':
-        splt = s[-3:] + tSep + splt
-        s = s[:-3]
-
-    return lhs + splt[:-1] + rhs
-
-
-def ReadExcelCOM(filename, sheetname, rows, cols):
-    """
-    Reads and Excel spreadsheet (a single worksheet) using Mark Hammonds' `pywin32`
-    package. If this package is not available, it returns two empty nested lists.
-
-    :param `filename`: a valid Excel `.xls` filename;
-    :param `sheetname`: the worksheet name inside the Excel file (i.e., the label
-     on the workbook tab at the bottom of the workbook);
-    :param `rows`: the number of significant rows in the worksheet, as returned
-     by `xlrd`;
-    :param `cols`: the number of significant columns in the worksheet, as returned
-     by `xlrd`.
-
-    :returns: two nested lists representing the comments (notes) on every cell and
-     the WYSIWYG representation of the cell content.
-
-    :note: If Mark Hammonds' `pywin32` package is not available, this method
-     returns two empty nested lists.
-    """
-
-    comments = [["" for i in range(cols)] for j in range(rows)]
-    texts    = [[None for i in range(cols)] for j in range(rows)]
-
-    if not _hasWin32:
-        return comments, texts
-
-    workbook = Excel(filename, sheetname)
-
-    for i in xrange(1, rows+1):
-        for j in xrange(1, cols+1):
-            texts[i-1][j-1]    = workbook.GetText(i, j)
-
-    comm_range = workbook.GetCommentsRange()
-    if comm_range is not None:
-        for comm in comm_range:
-            comments[comm.Row-1][comm.Column-1] = comm.Comment.Text()
-
-    workbook.Close()
-    return comments, texts
-
-
-def FontFromFont(font):
-    """
-    Creates a copy of the input `font`.
-
-    :param `font`: an instance of `wx.Font`.
-    """
-
-    new_font = wx.Font(font.GetPointSize(), font.GetFamily(), font.GetStyle(),
-                       font.GetWeight(), font.GetUnderlined(),
-                       font.GetFaceName(), font.GetEncoding())
-
-    return new_font
-
-
-class Excel(object):
-    """
-    A simple class that holds a COM interface to Excel.
-
-    By using the `win32com` module from Mark Hammonds' `pywin32` package, we
-    can manipulate various workbook/worksheet methods inside this class.
-    """
-
-    def __init__(self, filename, sheetname):
-        """
-        Default class constructor.
-
-        :param `filename`: a valid Excel `.xls` filename;
-        :param `sheetname`: the worksheet name inside the Excel file (i.e., the label
-         on the workbook tab at the bottom of the workbook).
-        """
-
-        self.xlApp = Dispatch('Excel.Application')
-        self.filename = filename
-        self.xlBook = self.xlApp.Workbooks.Open(filename)
-        self.sheet = self.xlBook.Worksheets(sheetname)
-
-        self.xlApp.Visible = 0
-
-
-    def Close(self, save=False):
-        """
-        Closes the Excel workbook, interrupting the COM interface.
-
-        :param `save`: ``True`` to save the changes you made to the workbook,
-         ``False`` otherwise.
-        """
-
-        self.xlBook.Close(SaveChanges=save)
-        del self.xlApp
-
-
-    def GetCommentsRange(self):
-        """
-        Returns a range of cells containing comments, using the VBA API.
-
-        """
-
-        try:
-            return self.sheet.Cells.SpecialCells(-4144)
-        except pywintypes.com_error:
-            return None
-
-
-    def GetText(self, row, col):
-        """
-        Returns the WYSIWYG text contained in a cell.
-
-        :param `row`: the row in which the cell lives;
-        :param `col`: the column in which the cell lives.
-
-        :note: The `row` and `col` parameters are not real Python index, as they
-         use the Excel indexing mode (i.e., first index is 1 and not 0).
-        """
-
-        cell = self.sheet.Cells(row, col)
-
-        if cell:
-            return cell.Text
-
-
-class XLSText(object):
-    """
-    This is a class which holds information about the cell content, in terms
-    of actual cell value, font, text colour, alignment and formatting.
-    """
-
-    def __init__(self, book, cell, xf_index, display_text=None, hyperlink=None, default_width=10):
-        """
-        Default class constructor.
-
-        :param `book`: an instance of the `xlrd.Book` class;
-        :param `cell`: an instance of `xlrd.sheet.Cell` class;
-        :param `xf_index`: an index into `xlrd.Book.xf_list`, which holds a
-         reference to the `xlrd.sheet.Cell` class (the actual cell for `xlrd`);
-        :param `display_text`: if Mark Hammonds' `pywin32` package is available,
-         this is the WYSIWYG cell content;
-        :param `hyperlink`: if this cell contains a hyperlink, it will be displayed
-         accordingly;
-        :param `default_width`: this is the default width of the text in 1/256
-         of the width of the zero character, using default Excel font (first FONT
-         record in the Excel file).
-
-        :note: If you are using version 0.7.1 or lower for `xlrd`, the *hyperlink*
-         parameter will always be ``None`` as this feature is available only in
-         `xlrd` 0.7.2 (SVN).
-        """
-
-        XFClass = book.xf_list[xf_index]
-
-        font = book.font_list[XFClass.font_index]
-        self.font = self.CreateFont(font)
-
-        text_colour = book.colour_map[font.colour_index]
-        self.text_colour = self.CreateTextColour(text_colour)
-
-        if display_text is not None:
-            self.value = display_text
-        else:
-            format = book.format_map[XFClass.format_key]
-            self.CreateFormat(format, cell, book.datemode)
-
-        alignment = XFClass.alignment
-        self.CreateAlignment(alignment, default_width)
-
-        if hyperlink is not None:
-            self.SetupHyperlink(hyperlink)
-        else:
-            self.tooltip = None
-
-
-    def CreateFont(self, font):
-        """
-        Creates a suitable wxPython font starting from an Excel font.
-
-        :param `font`: an instance of `xlrd.formatting.Font` class.
-
-        :note: There is currently no support for strikethrough fonts, although
-         `xlrd` correctly reports this format. The issue is a bug in wxWidgets
-         itself which doesn't allow the creation of strikethrough fonts. See
-         (http://trac.wxwidgets.org/ticket/9907).
-        """
-
-        style, bold, underline = wx.FONTSTYLE_NORMAL, wx.NORMAL, False
-        if font.italic:
-            style = wx.FONTSTYLE_ITALIC
-        if font.underline_type > 0:
-            underline = True
-        if font.weight > 600:
-            bold = wx.BOLD
-
-        family = XF_FONT_FAMILY[font.family]
-        name = font.name
-        size = int(font.height/20.0)
-
-        if font.escapement_type > 0:
-            # subscript/superscript
-            size = int(size*0.7)
-
-        # No support for strike-through fonts in wxWidgets
-#        if font.struck_out:
-#            style = wx.FONTFLAG_DEFAULT
-#            if bold:
-#                style += wx.FONTFLAG_BOLD
-#            if underline:
-#                style += wx.FONTFLAG_UNDERLINED
-#            if font.italic:
-#                style += wx.FONTFLAG_ITALIC
-#
-#            style += wx.FONTFLAG_STRIKETHROUGH
-#            self.font = wx.FFont(size, family, style, name.encode())
-#        else:
-
-        return wx.Font(size, family, style, bold, underline, name.encode())
-
-
-    def CreateTextColour(self, text_colour):
-        """
-        Creates a suitable wxPython colour for the text starting from a `xlrd`
-        tuple representing this colour.
-
-        :param `text_colour`: a tuple representing the RGB components of the
-         colour. If `text_colour` is ``None``, use the default ``wx.SYS_COLOUR_WINDOWTEXT``.
-        """
-
-        if text_colour is not None:
-            text_colour = wx.Colour(*text_colour)
-        else:
-            text_colour = wx.SystemSettings.GetColour(wx.SYS_COLOUR_WINDOWTEXT)
-
-        return text_colour
-
-
-    def CreateAlignment(self, alignment, default_width):
-        """
-        Creates a suitable wxPython alignment flag for the text starting from a
-        `xlrd` class representing this alignment.
-
-        :param `alignment`: an instance of `xlrd.formatting.XFAlignment` class;
-        :param `default_width`: this is the default width of the text in 1/256
-         of the width of the zero character, using default Excel font (first FONT
-         record in the Excel file).
-        """
-
-        hor_align, vert_align = alignment.hor_align, alignment.vert_align
-        self.horizontal_alignment = HORIZONTAL_ALIGNMENTS[hor_align]
-        self.vertical_alignment = VERTICAL_ALIGNMENTS[vert_align]
-
-        self.indent_level = alignment.indent_level
-        self.shrink_to_fit = alignment.shrink_to_fit
-        self.text_wrapped = alignment.text_wrapped
-
-        text_direction = 1
-
-        if alignment.text_direction == 0:
-            for char in self.value:
-                if char not in USELESS_CHARS:
-                    if ord(char) in RTL_UNICODE:
-                        text_direction = 2
-                        break
-
-        self.text_direction = text_direction
-        self.default_width = default_width
-
-        if alignment.rotation > 90:
-            self.rotation = 90 - alignment.rotation
-        else:
-            self.rotation = alignment.rotation
-
-
-    def CreateFormat(self, format, cell, datemode):
-        """
-        This method tries to guess the best format to apply to the current text
-        value.
-
-        :param `format`: an instance of `xlrd.formatting.Format` class;
-        :param `cell`: an instance of `xlrd.sheet.Cell` class;
-        :param `datemode`: the datemode associated with this Excel workbook.
-
-        :note: This method is used only if Mark Hammonds' `pywin32` package is
-         not available to try and format the cell text in an intelligent way.
-
-        :warning: The formatting applied by this method is severely limited; for
-         instance, you won't probably get the exact WYSIWYG between the Excel
-         spreadsheet and L{XLSGrid}.
-        """
-
-        ctype, value = cell.ctype, cell.value
-
-        self.value = "%s"%value
-        isDate = False
-
-        if ctype == xlrd.XL_CELL_DATE:
-            value = xlrd.xldate_as_tuple(value, datemode)
-            isDate = True
-        elif ctype in [xlrd.XL_CELL_EMPTY, xlrd.XL_CELL_BLANK]:
-            return
-        elif ctype == xlrd.XL_CELL_TEXT:
-            self.value = "%s"%value
-            return
-        elif ctype == xlrd.XL_CELL_ERROR:
-            value = xlrd.error_text_from_code(ctype)
-            self.value = "%s"%value
-            return
-
-        self.FormatString(value, isDate, format.format_str)
-
-
-    def FormatString(self, value, isDate, format_str):
-        """
-        This method tries to guess the best format to apply to the current text
-        value.
-
-        :param `value`: the actual raw cell text value;
-        :param `isDate`: ``True`` if this value represents a `xlrd` date object,
-         ``False`` otherwise;
-        :param `format_str`: the actual formatting string as extracted from Excel.
-
-        :note: This method is used only if Mark Hammonds' `pywin32` package is
-         not available to try and format the cell text in an intelligent way.
-
-        :warning: The formatting applied by this method is severely limited; for
-         instance, you won't probably get the exact WYSIWYG between the Excel
-         spreadsheet and L{XLSGrid}.
-        """
-
-        if "General" in format_str:
-            self.value = "%s"%value
-            return
-
-        number_format = format_str
-        currency = percentage = ""
-
-        if not isDate:
-            symbol = ""
-            split = format_str.split()
-            if len(split) > 1:
-                # Accounting and currency shit
-                currency = split[0].split(".")[0] + "."
-                number_format = ".".join(split[1:])
-
-            if "%" in number_format:
-                percentage = "%"
-                value = 100*value
-                number_format = number_format[0:-1]
-
-            representation = "%d"
-            if "." in number_format:
-                split = number_format.split(".")
-                num_decimals = len(split[1])
-                representation = "%0." + str(num_decimals) + "f"
-
-            try:
-                value = representation%value
-            except ValueError:
-                # Fall back to string
-                value = unicode(value, "utf-8", "ignore")
-
-            if "#," in number_format:
-                value = SplitThousands(value)
-
-            value = currency + value + percentage
-
-        else:
-            number_format = format_str.replace("\\", "")
-            number_format = number_format.replace("-", "-%").replace("/", "/%")
-            value = datetime.datetime(*value)
-            try:
-                value = value.strftime(number_format)
-            except (ValueError, TypeError):
-                value = value.strftime("%d.%m.%Y")
-
-        self.value = value
-
-
-    def SetupHyperlink(self, hyperlink):
-        """
-        Sets up the cell text value in case it represents a hyperlink.
-
-        :param `hyperlink`: an instance of `xlrd.sheet.hyperlink`.
-
-        :note: If you are using version 0.7.1 or lower for `xlrd`, the *hyperlink*
-         parameter will always be ``None`` as this feature is available only in
-         `xlrd` 0.7.2 (SVN).
-        """
-
-        url = (hyperlink.url_or_path and [hyperlink.url_or_path] or [hyperlink.textmark])[0]
-        self.tooltip = url
-
-
-    def IsHyperLink(self):
-        """
-        Returns whether the cell text is representing a hyperlink.
-
-        :returns: ``True`` if the cell text represents a hyperlink, ``False``
-         otherwise.
-        """
-
-        return self.tooltip is not None
-
-
-    def CombineAttr(self, attr):
-        """
-        Combines the input attribute `attr` with the features of the L{XLSText} class.
-
-        :param `attr`: an instance of `wx.grid.GridCellAttr`.
-        """
-
-        attr.SetAlignment(self.horizontal_alignment, self.vertical_alignment)
-        attr.SetTextColour(self.text_colour)
-        attr.SetFont(self.font)
-
-
-    def GetValue(self):
-        """ Returns the string representation of the cell text value. """
-
-        return self.value
-
-
-    def Draw(self, dc, rect):
-        """
-        Actually draws the text value on a grid cell.
-
-        :param `dc`: an instance of `wx.DC`;
-        :param `rect`: an instance of `wx.Rect`, representing the cell rectangle.
-        """
-
-        new_rect = wx.Rect(*rect)
-
-        xshift = yshift = 0
-        if self.rotation:
-            xshift = cos(self.rotation*pi/180)
-            yshift = sin(self.rotation*pi/180)
-
-        dc.SetTextForeground(self.text_colour)
-        dc.SetFont(self.font)
-
-        value = self.value
-        text_width, text_height = dc.GetTextExtent(value)
-
-        default_width = int(round(float(self.default_width)*text_width/256.0))
-
-        indentation = int(256.0*default_width/float(self.default_width))
-
-        if xshift == 0 and self.indent_level:
-            new_rect.SetLeft(new_rect.x + indentation)
-        else:
-            if self.horizontal_alignment == wx.ALIGN_LEFT:
-                new_rect.SetLeft(new_rect.x + 3)
-            elif self.horizontal_alignment == wx.ALIGN_RIGHT:
-                new_rect.SetWidth(new_rect.width - 1)
-
-        new_width = rect.width
-
-        if xshift > 0:
-            new_width = new_width/xshift
-
-        if self.shrink_to_fit:
-
-            font = FontFromFont(self.font)
-            point_size = font.GetPointSize()
-
-            while 1:
-                value = wordwrap(self.value, new_width, dc)
-                if "\n" not in value or point_size < 2:
-                    break
-
-                point_size -= 1
-                font.SetPointSize(point_size)
-                dc.SetFont(font)
-
-        elif self.text_wrapped:
-
-            value = wordwrap(self.value, new_width, dc)
-            text_width, text_height, dummy = dc.GetMultiLineTextExtent(value)
-
-        if self.rotation:
-            if self.shrink_to_fit:
-                text_width, text_height = dc.GetTextExtent(value)
-
-            xc, yc = (rect.x+rect.width/2, rect.y+rect.height/2)
-            xp = xc - (text_width/2)*xshift - (text_height/2)*yshift
-            yp = yc + (text_width/2)*yshift - (text_height/2)*xshift
-
-            dc.DrawRotatedText(value, xp, yp, self.rotation)
-
-        else:
-
-            dc.DrawLabel(value, new_rect, self.horizontal_alignment|self.vertical_alignment)
-
-
-class XLSRichText(XLSText):
-    """
-    This is a class which holds information about the cell content, in terms
-    of actual cell value, font, text colour, alignment and formatting. In addition
-    to what L{XLSText} does, this class attempts to handle cells with rich text
-    content.
-    """
-
-    def __init__(self, book, cell, xf_index, display_text=None, hyperlink=None, rich_text=None, default_width=10):
-        """
-        Default class constructor.
-
-        :param `book`: an instance of the `xlrd.Book` class;
-        :param `cell`: an instance of `xlrd.sheet.Cell` class;
-        :param `xf_index`: an index into `xlrd.Book.xf_list`, which holds a
-         reference to the `xlrd.sheet.Cell` class (the actual cell for `xlrd`);
-        :param `display_text`: if Mark Hammonds' `pywin32` package is available,
-         this is the WYSIWYG cell content;
-        :param `hyperlink`: if this cell contains a hyperlink, it will be displayed
-         accordingly;
-        :param `rich_text`: if this cell contains text in rich text format, L{XLSGrid}
-         will do its best to render the text as rich text;
-        :param `default_width`: this is the default width of the text in 1/256
-         of the width of the zero character, using default Excel font (first FONT
-         record in the Excel file).
-
-        :note: If you are using version 0.7.1 or lower for `xlrd`, the *hyperlink*
-         parameter will always be ``None`` as this feature is available only in
-         `xlrd` 0.7.2 (SVN).
-
-        :note: If you are using version 0.7.1 or lower for `xlrd`, this class will
-         note be used by L{XLSGrid}.
-
-        :warning: This class currently supports only single-line non-rotated text,
-         and it discards properties like `shrink-to-fit` and `wrapping`.
-        """
-
-        XLSText.__init__(self, book, cell, xf_index, display_text, hyperlink, default_width)
-
-        self.BuildChunks(book, xf_index, rich_text)
-
-
-    def BuildChunks(self, book, xf_index, rich_text):
-        """
-        Splits the cell content accordingly to their rich text format index.
-
-        :param `book`: an instance of the `xlrd.Book` class;
-        :param `xf_index`: an index into `xlrd.Book.xf_list`, which holds a
-         reference to the `xlrd.sheet.Cell` class (the actual cell for `xlrd`);
-        :param `rich_text`: if this cell contains text in rich text format, L{XLSGrid}
-         will do its best to render the text as rich text.
-        """
-
-        XFClass = book.xf_list[xf_index]
-        offset, index = rich_text[0]
-
-        if offset != 0:
-            new_tuple = (0, XFClass.font_index)
-            rich_text.insert(0, new_tuple)
-
-        value = self.value
-        rich_text.append((len(value), rich_text[-1][1]))
-        attributes = []
-
-        for indx in xrange(len(rich_text)-1):
-            offset_start, index_start = rich_text[indx]
-            offset_end, index_end = rich_text[indx+1]
-
-            chunk = value[offset_start:offset_end]
-
-            font = book.font_list[index_start]
-            ffont = self.CreateFont(font)
-            text_colour = book.colour_map[font.colour_index]
-            colour = self.CreateTextColour(text_colour)
-
-            ffont.escapement = font.escapement_type
-            attributes.append([chunk, ffont, colour])
-
-        self.attributes = attributes
-
-
-    def Measure(self, dc):
-        """
-        Convenience method to measure the maximum height and total width of all
-        the chunks of text composing our rich text string.
-
-        :param `dc`: an instance of `wx.DC`.
-        """
-
-        maxH = -1
-        full_width = 0
-        for chunk, font, colour in self.attributes:
-            dc.SetFont(font)
-            width, height, descent, leading = dc.GetFullTextExtent(chunk, font)
-            maxH = max(maxH, height-leading)
-            full_width += width
-
-        return maxH, full_width
-
-
-    def Draw(self, dc, rect):
-        """
-        Actually draws all the chunks of text on a grid cell, one by one.
-
-        :param `dc`: an instance of `wx.DC`;
-        :param `rect`: an instance of `wx.Rect`, representing the cell rectangle.
-        """
-
-        new_rect = wx.Rect(*rect)
-
-        text_width, text_height = dc.GetTextExtent(self.value)
-        default_width = int(round(float(self.default_width)*text_width/256.0))
-        indentation = int(256.0*default_width/float(self.default_width))
-
-        maxH, full_width = self.Measure(dc)
-
-        if self.indent_level:
-            new_rect.SetLeft(new_rect.x + indentation)
-        else:
-            if self.horizontal_alignment == wx.ALIGN_LEFT:
-                new_rect.SetLeft(new_rect.x + 3)
-            elif self.horizontal_alignment == wx.ALIGN_RIGHT:
-                new_rect.SetLeft(new_rect.x + (new_rect.width - full_width) - 1)
-            else:
-                space = int((new_rect.width - full_width)/2.0)
-                new_rect.SetLeft(new_rect.x + space)
-                new_rect.SetWidth(full_width+space)
-
-        if self.vertical_alignment == wx.ALIGN_TOP:
-            vspace = 0
-        elif self.vertical_alignment == wx.ALIGN_BOTTOM:
-            vspace = (new_rect.height - maxH - 1)
-        else:
-            vspace = int((new_rect.height - maxH)/2.0)
-
-        start = new_rect.x
-        y = new_rect.y
-
-        for chunk, font, colour in self.attributes:
-            dc.SetTextForeground(colour)
-            dc.SetFont(font)
-            width, height, descent, leading = dc.GetFullTextExtent(chunk, font)
-            if font.escapement > 0:
-                height = height*0.7
-
-            ypos = y-height+maxH+vspace
-
-            if font.escapement == 1:
-                ypos = ypos - maxH + height
-
-            dc.DrawText(chunk, start, ypos)
-            start += width
-
-
-class XLSBackground(object):
-    """
-    This is a class which holds information about the cell background, in terms
-    of background colour and background pattern (hatching).
-    """
-
-    def __init__(self, book, xf_index):
-        """
-        Default class constructor.
-
-        :param `book`: an instance of the `xlrd.Book` class;
-        :param `xf_index`: an index into `xlrd.Book.xf_list`, which holds a
-         reference to the `xlrd.sheet.Cell` class (the actual cell for `xlrd`).
-        """
-
-        XFClass = book.xf_list[xf_index]
-
-        background = XFClass.background
-        background_colour = book.colour_map[background.background_colour_index]
-        pattern_colour = book.colour_map[background.pattern_colour_index]
-        fill_pattern = background.fill_pattern
-
-        self.CreateBackgroundColour(background_colour, pattern_colour, fill_pattern)
-
-
-    def CreateBackgroundColour(self, background_colour, pattern_colour, fill_pattern):
-        """
-        Creates a suitable wxPython colour for the cell background starting from
-        a `xlrd` tuple representing this colour.
-
-        :param `background_colour`: a tuple representing the RGB components of the
-         cell background colour. If `background_colour` is ``None``, use the
-         default ``wx.SYS_COLOUR_WINDOW``;
-        :param `pattern_colour`: a tuple representing the RGB components of the
-         cell pattern colour;
-        :param `fill_pattern`: the pattern to use to draw hatches on top of the
-         background.
-        """
-
-        if background_colour is not None:
-            background_colour = wx.Colour(*background_colour)
-        else:
-            background_colour = wx.SystemSettings.GetColour(wx.SYS_COLOUR_WINDOW)
-
-        if pattern_colour is not None:
-            pattern_colour = wx.Colour(*pattern_colour)
-
-        self.background_brush = wx.Brush(background_colour)
-        self.background_colour = background_colour
-
-        self.fill_brush = None
-
-        if fill_pattern <= 0:
-            return
-
-        r, g, b = pattern_colour
-
-        fill_image = eval("_xls_background_%02d.GetImage()"%fill_pattern)
-        fill_image.Replace(0, 0, 0, r, g, b)
-        r, g, b = background_colour.Red(), background_colour.Green(), background_colour.Blue()
-        fill_image.Replace(255, 255, 255, r, g, b)
-        fill_bitmap = fill_image.ConvertToBitmap()
-
-        self.fill_brush = wx.BrushFromBitmap(fill_bitmap)
-
-
-    def CombineAttr(self, attr):
-        """
-        Combines the input attribute `attr` with the features of the L{XLSBackground} class.
-
-        :param `attr`: an instance of `wx.grid.GridCellAttr`.
-        """
-
-        attr.SetBackgroundColour(self.background_colour)
-        return attr
-
-
-    def Draw(self, dc, rect):
-        """
-        Actually draws the cell background and pattern hatching on a grid cell.
-
-        :param `dc`: an instance of `wx.DC`;
-        :param `rect`: an instance of `wx.Rect`, representing the cell rectangle.
-        """
-
-        dc.SetClippingRect(rect)
-
-        dc.SetBackgroundMode(wx.SOLID)
-        dc.SetBrush(self.background_brush)
-        dc.SetPen(wx.TRANSPARENT_PEN)
-        dc.DrawRectangleRect(rect)
-
-        if self.fill_brush:
-
-            dc.SetBrush(self.fill_brush)
-            dc.SetBackgroundMode(wx.TRANSPARENT)
-            dc.DrawRectangleRect(rect)
-
-        dc.DestroyClippingRegion()
-
-
-class XLSBorder(object):
-    """
-    This is a class which holds information about a single cell border, in terms
-    of its location (top, left, bottom, right, diagonal), its colour, width and
-    shape.
-    """
-
-    def __init__(self, location, line_style, border_colour, default_colour, diagonals):
-        """
-        Default class constructor.
-
-        :param `location`: the actual border location (top, left, bottom, right,
-         diagonal);
-        :param `line_style`: the line style used by Excel to draw this border;
-        :param `border_colour`: the colour used by Excel to draw this border;
-        :param `default_colour`: the "magic" colour used by Excel to draw non-custom
-         border lines;
-        :param `diagonals`: a tuple containing whether or not to draw the up and down
-         diagonal borders.
-        """
-
-        self.draw_priority = 2
-
-        if line_style == NO_LINE:
-
-            if border_colour == (0, 0, 0):
-                self.draw_priority = 0
-                border_colour = wx.Colour(*default_colour)
-            else:
-                self.draw_priority = 1
-                border_colour = wx.BLACK
-
-            self.pen = wx.Pen(border_colour, 1, wx.SOLID)
-            pen_style = THIN
-
-        else:
-
-            if border_colour == (0, 0, 0):
-                border_colour = wx.Colour(*default_colour)
-                self.draw_priority = 2
-            elif border_colour is None:
-                border_colour = wx.BLACK
-                self.draw_priority = 2
-            else:
-                border_colour = wx.Colour(*border_colour)
-
-            pen_width, pen_style = XF_PEN_STYLES[line_style]
-            if pen_width > 2:
-                self.draw_priority = 4
-            elif pen_width > 1:
-                self.draw_priority = 3
-
-            self.pen = wx.Pen(border_colour, pen_width, pen_style)
-
-        self.diagonals = diagonals
-        self.location = location
-        self.pen_style = pen_style
-        self.line_style = line_style
-
-
-    def Draw(self, dc, rect):
-        """
-        Actually draws the cell border.
-
-        :param `dc`: an instance of `wx.DC`;
-        :param `rect`: an instance of `wx.Rect`, representing the cell rectangle.
-        """
-
-        dc.SetBackgroundMode(wx.TRANSPARENT)
-        dc.SetPen(self.pen)
-
-        if self.location == DIAGONAL:
-            self.DrawDiagonals(dc, rect)
-        else:
-            self.DrawBorder(dc, rect)
-
-
-    def DrawDiagonals(self, dc, rect):
-        """
-        Actually draws the cell diagonal border.
-
-        :param `dc`: an instance of `wx.DC`;
-        :param `rect`: an instance of `wx.Rect`, representing the cell rectangle.
-        """
-
-        diag_up, diag_down = self.diagonals
-
-        if diag_down:
-            xstart, ystart = rect.GetTopLeft()
-            xend, yend = rect.GetBottomRight()
-
-            if self.line_style == DOUBLE:
-                dc.DrawLine(xstart+2, ystart, xend, yend-2)
-                dc.DrawLine(xstart, ystart+2, xend-2, yend)
-            else:
-                dc.DrawLine(xstart, ystart, xend, yend)
-
-        if diag_up:
-
-            xstart, ystart = rect.GetBottomLeft()
-            xend, yend = rect.GetTopRight()
-
-            if self.line_style == DOUBLE:
-                dc.DrawLine(xstart, ystart-2, xend-2, yend)
-                dc.DrawLine(xstart+2, ystart, xend, yend+2)
-            else:
-                dc.DrawLine(xstart, ystart, xend, yend)
-
-
-    def DrawBorder(self, dc, rect):
-        """
-        Actually draws the cell border (one of left, right, bottom, top).
-
-        :param `dc`: an instance of `wx.DC`;
-        :param `rect`: an instance of `wx.Rect`, representing the cell rectangle.
-        """
-
-        pen_width = self.pen.GetWidth()
-        location = self.location
-        new_rect = wx.Rect(*rect)
-
-        x, y, w, h = new_rect
-        line_style = self.line_style
-
-        shift = 0
-        if pen_width == 2:
-            shift = pen_width - 1
-        if pen_width > 2:
-            shift = pen_width - 2
-
-        if location == BOTTOM:
-
-            if self.draw_priority < 2:
-                return
-
-            if line_style == DOUBLE:
-                dc.DrawLine(x, y+h-1, x+w, y+h-1)
-                dc.DrawLine(x, y+h+1, x+w, y+h+1)
-            else:
-                dc.DrawLine(x+1, y+h,   x+w, y+h)
-
-
-        elif location == TOP:
-
-            if line_style == DOUBLE:
-                dc.DrawLine(x, y-1, x+w, y-1)
-                dc.DrawLine(x, y+1, x+w, y+1)
-            else:
-                dc.DrawLine(x+1, y+shift,   x+w, y+shift)
-
-        elif location == LEFT:
-
-            if line_style == DOUBLE:
-                dc.DrawLine(x-1, y, x-1, y+h)
-                dc.DrawLine(x+1, y, x+1, y+h)
-            else:
-                dc.DrawLine(x+shift,   y+1, x+shift,   y+h)
-
-        elif location == RIGHT:
-
-            if self.draw_priority < 2:
-                return
-
-            if line_style == DOUBLE:
-                dc.DrawLine(x+w-1, y, x+w-1, y+h)
-                dc.DrawLine(x+w+1, y, x+w+1, y+h)
-            else:
-                dc.DrawLine(x+w+1, y+1, x+w+1, y+h)
-
-
-class XLSBorderFactory(object):
-    """
-    This is a factory class which holds information about all the borders in a
-    cell. Its implementation and use is merely to simplify the handling of the
-    different cell borders (left, top, bottom, right, diagonal).
-    """
-
-    def __init__(self, book, border, default_colour):
-        """
-        Default class constructor.
-
-        :param `book`: an instance of the `xlrd.Book` class;
-        :param `border`: an instance of `xlrd.formatting.XFBorder` class;
-        :param `default_colour`: the "magic" colour used by Excel to draw non-custom
-         border lines.
-        """
-
-        borders = {}
-        diagonals = border.diag_up, border.diag_down
-
-        for label, location in XF_BORDER_STYLES.items():
-            line_style = getattr(border, "%s_line_style"%label)
-            colour_index = getattr(border, "%s_colour_index"%label)
-            border_colour = book.colour_map[colour_index]
-
-            border_class = XLSBorder(location, line_style, border_colour, default_colour, diagonals)
-            borders[location] = border_class
-
-        self.draw_priority = sorted(borders.values(), key=attrgetter('draw_priority'))
-
-
-    def Draw(self, dc, rect):
-        """
-        Actually draws all the cell borders based on their drawing priority.
-
-        :param `dc`: an instance of `wx.DC`;
-        :param `rect`: an instance of `wx.Rect`, representing the cell rectangle.
-
-        :note: The drawing priority is assigned depending on if the border is a
-         custom one or not. Customized borders are drawn last.
-        """
-
-        for border in self.draw_priority:
-            border.Draw(dc, rect)
-
-
-class XLSComment(object):
-    """
-    This is a class which holds information about the content of the "comment
-    window" (aka note) in Excel.
-
-    :note: If Mark Hammonds' `pywin32` package is not available, this class can
-     not be used.
-    """
-
-    def __init__(self, comment):
-        """
-        Default class constructor.
-
-        :param `comment`: the actual text contained in the Excel cell comment (note).
-        """
-
-        self.comment = comment
-
-
-    def Draw(self, dc, rect):
-        """
-        Actually draws a small red triangle in the top-right corder of the cell
-        to indicate that a comment is present.
-
-        :param `dc`: an instance of `wx.DC`;
-        :param `rect`: an instance of `wx.Rect`, representing the cell rectangle.
-        """
-
-        right = rect.GetTopRight()
-        points = [wx.Point(right.x-5, right.y),
-                  right,
-                  wx.Point(right.x, right.y+5)]
-
-        dc.SetBrush(wx.RED_BRUSH)
-        dc.SetPen(wx.RED_PEN)
-        dc.DrawPolygon(points)
-
-
-class XLSCell(object):
-    """
-    This is a class which holds information about a single cell in L{XLSGrid}.
-    It stores (via auxiliary classes), all details about cell background, text,
-    font, colours and borders.
-    """
-
-    def __init__(self, book, cell, xf_index, xls_text, xls_comment, hyperlink, rich_text, default_width, default_colour):
-        """
-        Default class constructor.
-
-        :param `book`: an instance of the `xlrd.Book` class;
-        :param `cell`: an instance of `xlrd.sheet.Cell` class;
-        :param `xf_index`: an index into `xlrd.Book.xf_list`, which holds a
-         reference to the `xlrd.sheet.Cell` class (the actual cell for `xlrd`);
-        :param `xls_text`: the actual WYSIWYG cell text, if available;
-        :param `xls_comment`: the cell comment (note), if any;
-        :param `hyperlink`: an instance of `xlrd.sheet.hyperlink`;
-        :param `rich_text`: if this cell contains text in rich text format, L{XLSGrid}
-         will do its best to render the text as rich text;
-        :param `default_width`: this is the default width of the text in 1/256
-         of the width of the zero character, using default Excel font (first FONT
-         record in the Excel file);
-        :param `default_colour`: the "magic" colour used by Excel to draw non-custom
-         border lines.
-
-        :note: If you are using version 0.7.1 or lower for `xlrd`, the *hyperlink*
-         parameter will always be ``None`` as this feature is available only in
-         `xlrd` 0.7.2 (SVN).
-
-        :note: If you are using version 0.7.1 or lower for `xlrd`, the `rich_text`
-         parameter will always be ``None`` as this feature is available only in
-         `xlrd` 0.7.2 (SVN).
-
-        :note: if Mark Hammonds' `pywin32` package is not available, the `xls_text`
-         parameter will almost surely not be the WYSIWYG representation of the cell
-         text.
-
-        :note: If Mark Hammonds' `pywin32` package is not available, the `xls_comment`
-         parameter will always be ``None``.
-        """
-
-        self.size = 1, 1
-
-        self.comment = None
-        self.hyperlink = None
-
-        self.SetupCell(book, cell, xf_index, xls_text, xls_comment, hyperlink, rich_text, default_width, default_colour)
-
-
-    def SetupCell(self, book, cell, xf_index, xls_text, xls_comment, hyperlink, rich_text, default_width, default_colour):
-        """
-        Actually sets up the L{XLSCell} class. This is an auxiliary method to
-        avoid cluttering the L{__init__} method.
-
-        :param `book`: an instance of the `xlrd.Book` class;
-        :param `cell`: an instance of `xlrd.sheet.Cell` class;
-        :param `xf_index`: an index into `xlrd.Book.xf_list`, which holds a
-         reference to the `xlrd.sheet.Cell` class (the actual cell for `xlrd`);
-        :param `xls_text`: the actual WYSIWYG cell text, if available;
-        :param `xls_comment`: the cell comment (note), if any;
-        :param `hyperlink`: an instance of `xlrd.sheet.hyperlink`;
-        :param `rich_text`: if this cell contains text in rich text format, L{XLSGrid}
-         will do its best to render the text as rich text;
-        :param `default_width`: this is the default width of the text in 1/256
-         of the width of the zero character, using default Excel font (first FONT
-         record in the Excel file);
-        :param `default_colour`: the "magic" colour used by Excel to draw non-custom
-         border lines.
-
-        :note: If you are using version 0.7.1 or lower for `xlrd`, the *hyperlink*
-         parameter will always be ``None`` as this feature is available only in
-         `xlrd` 0.7.2 (SVN).
-
-        :note: If you are using version 0.7.1 or lower for `xlrd`, the `rich_text`
-         parameter will always be ``None`` as this feature is available only in
-         `xlrd` 0.7.2 (SVN).
-
-        :note: if Mark Hammonds' `pywin32` package is not available, the `xls_text`
-         parameter will almost surely not be the WYSIWYG representation of the cell
-         text.
-
-        :note: If Mark Hammonds' `pywin32` package is not available, the `xls_comment`
-         parameter will always be ``None``.
-        """
-
-        cvalue = cell.value
-        self.raw_value = cvalue
-
-        if rich_text:
-            self.text = XLSRichText(book, cell, xf_index, xls_text, hyperlink, rich_text, default_width)
-        else:
-            self.text = XLSText(book, cell, xf_index, xls_text, hyperlink, default_width)
-
-        self.background = XLSBackground(book, xf_index)
-
-        XFClass = book.xf_list[xf_index]
-        border = XFClass.border
-
-        self.borders = XLSBorderFactory(book, border, default_colour)
-
-        if xls_comment:
-            self.comment = XLSComment(xls_comment)
-
-        self.attr = None
-
-
-    def GetAttr(self):
-        """
-        Returns the attribute to use for this specific cell.
-
-        :returns: an instance of `wx.grid.GridCellAttr`.
-        """
-
-        if self.attr is not None:
-            self.attr.IncRef()
-            return self.attr
-
-        attr = gridlib.GridCellAttr()
-
-        attr.SetRenderer(XLSRenderer(self))
-
-        attr.SetSize(*self.size)
-        attr.SetOverflow(True)
-        self.attr = attr
-        self.attr.IncRef()
-
-        return self.attr
-
-
-    def GetValue(self):
-        """ Returns the actual WYSIWYG representation of the cell value. """
-
-        return self.text.GetValue()
-
-
-    def SetValue(self, value):
-        """
-        Sets the actual WYSIWYG representation of the cell value.
-
-        :param `value`: the current text value to insert in the cell.
-
-        :note: This method is currently unused as everything is handled inside the
-         L{XLSText} class.
-
-        :see: L{GetValue}
-        """
-
-        self.value = value
-
-
-    def SetCellSize(self, rows, cols):
-        """
-        Sets the size of the cell.
-
-        Specifying a value of more than 1 in `rows` or `cols` will make the cell
-        at (`row`, `col`) span the block of the specified size, covering the other
-        cells which would be normally shown in it. Passing 1 for both arguments
-        resets the cell to normal appearance.
-
-        :param `rows`: number of rows to be occupied by this cell, must be >= 1;
-        :param `cols`: number of columns to be occupied by this cell, must be >= 1.
-        """
-
-        self.size = (rows, cols)
-
-
-    def GetComment(self):
-        """
-        Returns the cell comment, if any.
-
-        :returns: an instance of L{XLSComment}.
-
-        :note: If Mark Hammonds' `pywin32` package is not available, this method
-         always returns ``None``.
-        """
-
-        return self.comment
-
-
-class XLSRenderer(gridlib.PyGridCellRenderer):
-    """
-    This class is responsible for actually drawing the cell in the grid.
-
-    """
-
-    def __init__(self, cell):
-        """
-        Default class constructor.
-
-        :param `cell`: an instance of L{XLSCell}.
-        """
-
-        gridlib.PyGridCellRenderer.__init__(self)
-        self.cell = cell
-
-
-    def Draw(self, grid, attr, dc, rect, row, col, isSelected):
-        """
-        Draw the given cell on the provided `dc` inside the given rectangle using
-        default or selected state corresponding to the `isSelected` value.
-
-        :param `grid`: an instance of `wx.grid.Grid`;
-        :param `attr`: an instance of `wx.grid.GridCellAttr`;
-        :param `dc`: an instance of `wx.DC`;
-        :param `rect`: an instance of `wx.Rect`, representing the cell rectangle;
-        :param `row`: the row in which this cell lives;
-        :param `col`: the column in which this cell lives;
-        :param `isSelected`: ``True`` if the cell is selected, ``False`` otherwise.
-        """
-
-        # clear the background
-        dc.SetBackgroundMode(wx.SOLID)
-
-        cell = self.cell
-
-        cell.background.Draw(dc, rect)
-
-        if cell.borders:
-            cell.borders.Draw(dc, rect)
-
-        cell.text.Draw(dc, rect)
-
-        if cell.comment:
-            cell.comment.Draw(dc, rect)
-
-        if isSelected:
-
-            gdc = wx.GCDC(dc)
-
-            sys_colour = wx.SystemSettings.GetColour(wx.SYS_COLOUR_HIGHLIGHT)
-            brush_colour = wx.Colour(sys_colour.Red(), sys_colour.Green(), sys_colour.Blue(), 90)
-
-            gdc.SetBrush(wx.Brush(brush_colour))
-            gdc.SetPen(wx.TRANSPARENT_PEN)
-
-            gdc.DrawRectangleRect(rect)
-
-
-class XLSTable(gridlib.PyGridTableBase):
-    """
-    The almost abstract base class for grid tables.
-
-    A grid table is responsible for storing the grid data and, indirectly, grid
-    cell attributes. The data can be stored in the way most convenient for the
-    application but has to be provided in string form to `wx.grid.Grid`.
-    """
-
-    def __init__(self, grid, cells, rows, cols):
-        """
-        Default class constructor.
-
-        :param `grid`: an instance of `wx.grid.Grid`;
-        :param `cells`: a Python dictionary. For every key `(row, col)`, the
-         corresponding value is an instance of L{XLSCell};
-        :param `rows`: the number of rows in the table;
-        :param `cols`: the number of columns in the table.
-        """
-
-        # The base class must be initialized *first*
-        gridlib.PyGridTableBase.__init__(self)
-
-        self.cells = cells
-        self.dimens = (rows, cols)
-
-
-    def GetNumberCols(self):
-        """ Returns the number of columns in the table. """
-
-        return self.dimens[1]
-
-
-    def GetNumberRows(self):
-        """ Returns the number of rows in the table. """
-
-        return self.dimens[0]
-
-
-    def GetValue(self, row, col):
-        """
-        Returns the cell content for the specified row and column.
-
-        :param `row`: the row in which this cell lives;
-        :param `col`: the column in which this cell lives.
-        """
-
-        cell = self.cells[(row, col)]
-        return cell.GetValue()
-
-
-    def SetValue(self, row, col, value):
-        """
-        sets the cell content for the specified row and column.
-
-        :param `row`: the row in which this cell lives;
-        :param `col`: the column in which this cell lives;
-        :param `value`: the new value to assign to the specified cell.
-        """
-
-        cell = self.cells[(row, col)]
-        cell.SetValue(value)
-
-
-    def GetAttr(self, row, col, kind):
-        """
-        Return the attribute for the given cell.
-
-        :param `row`: the row in which this cell lives;
-        :param `col`: the column in which this cell lives;
-        :param `kind`: the kind of the attribute to return.
-        """
-
-        cell = self.cells[(row, col)]
-        return cell.GetAttr()
-
-
-    def GetRawValue(self, row, col):
-        """
-        Returns the "raw" value for the cell content.
-
-        :param `row`: the row in which this cell lives;
-        :param `col`: the column in which this cell lives.
-        """
-
-        cell = self.cells[(row, col)]
-        return cell.raw_value
-
-
-class XLSGrid(gridlib.Grid):
-    """
-    L{XLSGrid} is a class based on `wx.grid.Grid` that can be used to faithfully
-    reproduce the appearance of a Microsoft Excel spreadsheet (one worksheet per
-    every instance of L{XLSGrid}).
-
-    L{XLSGrid} is a completely owner-drawn control, and it relies on the power of
-    `wx.grid.PyGridTableBase` and `wx.grid.PyGridCellRenderer` to draw the cell
-    content. For this reasons (and for some others, see the TODOs section), it will
-    work efficiently only for relatively small Excel files.
-    """
-
-    def __init__(self, parent):
-        """
-        Default class constructor.
-
-        :param `parent`: the grid parent window. Must not be ``None``.
-        """
-
-        gridlib.Grid.__init__(self, parent)
-
-        self.SetMargins(0, 0)
-        self.SetDefaultCellBackgroundColour(parent.GetBackgroundColour())
-        self.SetDefaultCellOverflow(True)
-
-        self.tip_window = None
-        self.tip_shown = False
-
-
-    def DestroyTip(self):
-        """
-        If a comment window or a tooltip over a hyperlink have been created, this
-        method destroys them.
-        """
-
-        if self.tip_window:
-            try:
-                self.tip_window.GetTipWindow().Destroy()
-            except wx.PyDeadObjectError:
-                pass
-
-            del self.tip_window
-            self.tip_window = None
-
-        if self.tip_shown:
-            self.GetGridWindow().SetToolTipString("")
-            self.GetGridWindow().SetCursor(wx.NullCursor)
-            self.tip_shown = False
-
-
-    def InstallGridHint(self):
-        """
-        Auxiliary method used to bind a ``wx.EVT_MOTION`` event to L{XLSGrid}.
-        """
-
-        self.prev_rowcol = [None, None]
-
-        def OnMouseMotion(event):
-            """
-            Handles a the ``wx.EVT_MOTION`` events for L{XLSGrid}.
-
-            :param `event`: a `wx.MouseEvent` event to be processed.
-            """
-
-            # evt.GetRow() and evt.GetCol() would be nice to have here,
-            # but as this is a mouse event, not a grid event, they are not
-            # available and we need to compute them by hand.
-            position = event.GetPosition()
-            x, y = self.CalcUnscrolledPosition(position)
-            row = self.YToRow(y)
-            col = self.XToCol(x)
-
-            if [row, col] != self.prev_rowcol and row >= 0 and col >= 0:
-
-                self.prev_rowcol[:] = [row, col]
-                self.DestroyTip()
-                cell = self.cells[(row, col)]
-                rect = self.CellToRect(row, col)
-                comment = cell.GetComment()
-
-                window = self.GetGridWindow()
-                if cell.text.IsHyperLink():
-                    window.SetCursor(wx.StockCursor(wx.CURSOR_HAND))
-                    window.SetToolTipString(cell.text.tooltip)
-                    self.tip_shown = True
-                    if not comment:
-                        return
-
-                if comment:
-                    self.tip_window = TransientPopup(window, comment, wx.GetMousePosition())
-                    event.Skip()
-
-        self.GetGridWindow().Bind(wx.EVT_MOTION, OnMouseMotion)
-
-
-    def PopulateGrid(self, book, sheet, display_texts, comments):
-        """
-        This is the main method of this class, and it is used to actually create
-        the cells, size the columns and rows, merging cells, etc...
-
-        :param `book`: an instance of the `xlrd.Book` class;
-        :param `sheet`: an instance of the `xlrd.sheet` class;
-        :param `display_texts`: if Mark Hammonds' `pywin32` package is available,
-         this is the WYSIWYG cell content for all the cells in the Excel worksheet;
-        :param `comments`: if Mark Hammonds' `pywin32` package is available,
-         this is a nested list of cell comments (notes) for all the cells in the
-         Excel worksheet.
-        """
-
-        self.BeginBatch()
-
-        nrows = sheet.nrows
-        ncols = sheet.ncols
-
-        default_width, default_height = self.GetDefaultFontData(book)
-        default_colour = self.GetGridLineColour()
-
-        hyperlinks, rich_text_list = {}, {}
-        if hasattr(sheet, "hyperlink_map"):
-            # New in xlrd version 0.7.2 from SVN
-            hyperlinks = sheet.hyperlink_map
-
-        if hasattr(sheet, "rich_text_runlist_map"):
-            # New in xlrd version 0.7.2 from SVN
-            rich_text_list = sheet.rich_text_runlist_map
-
-        self.cells = {}
-
-        for i in xrange(nrows):
-
-            for j in xrange(ncols):
-
-                hyperlink = rich_text = None
-
-                if (i, j) in hyperlinks:
-                    hyperlink = hyperlinks[(i, j)]
-                if (i, j) in rich_text_list:
-                    rich_text = rich_text_list[(i, j)]
-
-                self.FormatCell(book, sheet, i, j, display_texts, comments, hyperlink, rich_text, default_width, default_colour)
-
-        self.table = XLSTable(self, self.cells, nrows, ncols)
-        self.SetTable(self.table)
-
-        row_height = sheet.default_row_height
-        col_width = sheet.defcolwidth
-
-        for i in xrange(nrows):
-            if i in sheet.rowinfo_map:
-                current = sheet.rowinfo_map[i].height
-            else:
-                current = sheet.default_row_height
-
-            row_height = int(round(float(default_height)*current/256.0))
-            self.SetRowSize(i, row_height)
-
-        for j in xrange(ncols):
-            if j in sheet.colinfo_map:
-                current = sheet.colinfo_map[j].width
-            else:
-                current = sheet.defcolwidth
-
-            col_width = int(round(float(default_width)*current/256.0))
-            self.SetColSize(j, col_width)
-
-        for merged in sheet.merged_cells:
-            rlo, rhi, clo, chi = merged
-            if rlo >= 0 and rlo < len(self.cells) and clo >= 0:
-                self.cells[(rlo, clo)].SetCellSize(rhi-rlo, chi-clo)
-
-        self.EnableEditing(False)
-        self.EnableGridLines(False)
-        self.EndBatch()
-        self.ForceRefresh()
-        self.InstallGridHint()
-
-
-    def FormatCell(self, book, sheet, row, col, display_texts, comments, hyperlink, rich_text, default_width, default_colour):
-        """
-        Processes the creation of a single cell (an instance of L{XLSCell}).
-
-        :param `book`: an instance of the `xlrd.Book` class;
-        :param `sheet`: an instance of the `xlrd.sheet` class;
-        :param `row`: the row in which this cell lives;
-        :param `col`: the column in which this cell lives;
-        :param `display_texts`: if Mark Hammonds' `pywin32` package is available,
-         this is the WYSIWYG cell content for all the cells in the Excel worksheet;
-        :param `comments`: if Mark Hammonds' `pywin32` package is available,
-         this is a nested list of cell comments (notes) for all the cells in the
-         Excel worksheet;
-        :param `hyperlink`: if this cell contains a hyperlink, it will be displayed
-         accordingly;
-        :param `rich_text`: if this cell contains text in rich text format, L{XLSGrid}
-         will do its best to render the text as rich text;
-        :param `default_width`: this is the default width of the text in 1/256
-         of the width of the zero character, using default Excel font (first FONT
-         record in the Excel file);
-        :param `default_colour`: the "magic" colour used by Excel to draw non-custom
-         border lines.
-
-        :note: If you are using version 0.7.1 or lower for `xlrd`, the *hyperlink*
-         parameter will always be ``None`` as this feature is available only in
-         `xlrd` 0.7.2 (SVN).
-
-        :note: If you are using version 0.7.1 or lower for `xlrd`, the `rich_text`
-         parameter will always be ``None`` as this feature is available only in
-         `xlrd` 0.7.2 (SVN).
-
-        :note: If Mark Hammonds' `pywin32` package is not available, the `display_texts`
-         and `comments` parameter will be two empty nested lists.
-        """
-
-        cell = sheet.cell(row, col)
-
-        xf_index = sheet.cell_xf_index(row, col)
-        xls_text, xls_comment = display_texts[row][col], comments[row][col]
-
-        gridCell = XLSCell(book, cell, xf_index, xls_text, xls_comment, hyperlink, rich_text, default_width, default_colour)
-
-        self.cells[(row, col)] = gridCell
-
-
-    def GetDefaultFontData(self, book):
-        """
-        Returns suitable width and height (in pixels) starting from Excel's own
-        measurements (in characters, whatever that means).
-
-        :param `book`: an instance of the `xlrd.Book` class.
-
-        :returns: a `default_width` and `default_height` in pixels, based on the
-         default width of the text in 1/256 of the width of the zero character,
-         using default Excel font (first FONT record in the Excel file).
-        """
-
-        font = book.font_list[0]
-        style, bold, underline = wx.FONTSTYLE_NORMAL, wx.NORMAL, False
-
-        if font.italic:
-            style = wx.FONTSTYLE_ITALIC
-        if font.underline_type > 0:
-            underline = True
-        if font.weight > 600:
-            bold = wx.BOLD
-
-        family = XF_FONT_FAMILY[font.family]
-        name = font.name
-        size = int(font.height/20.0)
-
-        dc = wx.ClientDC(self)
-        font = wx.Font(size, family, style, bold, underline, name.encode())
-        dc.SetFont(font)
-        width, height, descent, leading = dc.GetFullTextExtent("0", font)
-
-        return width, height + descent - leading
-
-
-class TransientPopup(STT.SuperToolTip):
-    """
-    This is a sublass of L{SuperToolTip} and it is used to display a
-    "comment-window" on the cells containing a comment (a note).
-
-    :note: If Mark Hammonds' `pywin32` package is not available, this class is
-     never invoked.
-    """
-
-    def __init__(self, grid_window, comment, position):
-        """
-        Default class constructor.
-
-        :param `grid_window`: the actual window representing the grid;
-        :param `comment`: an instance of L{XLSComment}, containing the
-         text for this comment;
-        :param `position`: the position at which we pop up the comment
-         window (currently unused).
-        """
-
-        STT.SuperToolTip.__init__(self, grid_window)
-
-        xls_comment = comment.comment
-
-        split = xls_comment.split(":")
-        header, rest = split[0], split[1:]
-        rest = ":".join(rest)
-
-        dc = wx.ClientDC(grid_window)
-        rest = wordwrap(rest, 400, dc)
-
-        self.SetHeader(header)
-        self.SetMessage(rest)
-        self.SetTarget(grid_window)
-        self.SetDrawHeaderLine(True)
-
-        self.SetStartDelay(100000)
-        self.SetEndDelay(100000)
-        self.ApplyStyle("Office 2007 Blue")
-
-        self.SetDropShadow(True)
-        self.DoShowNow()
-
-        grid_window.SetFocus()
-
+# --------------------------------------------------------------------------------- #
+# XLSGRID wxPython IMPLEMENTATION
+#
+# Andrea Gavana @ 08 Aug 2011
+# Latest Revision: 17 Aug 2011, 15.00 GMT
+#
+#
+# TODO List
+#
+# Current todo list:
+#
+# 1. There is currently no support for rich text, i.e. strings containing partial
+#    bold, italic and underlined text, change of font inside a string, etc... xlrd
+#    supports those (from version 0.7.2 in SVN) but there is no easy way to handle
+#    changing fonts/colours/formatting in the same string in wxPython;
+#
+# 2. XLSGrid is sufficiently efficient and fast for reasonably small Excel files.
+#    There might be some improvement to be made in the code to make it work with
+#    bigger files and in a faster way;
+#
+# 3. There is currently no support for strikethrough fonts, although xlrd correctly
+#    reports this format. The issue is a bug in wxWidgets itself which doesn't
+#    allow the creation of strikethrough fonts (http://trac.wxwidgets.org/ticket/9907).
+#
+# 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
+# --------------------------------------------------------------------------------- #
+
+
+"""
+L{XLSGrid} is a class based on `wx.grid.Grid` that can be used to faithfully
+reproduce the appearance of a Microsoft Excel spreadsheet (one worksheet per
+every instance of L{XLSGrid}).
+
+
+Description
+===========
+
+L{XLSGrid} is a class based on `wx.grid.Grid` that can be used to faithfully
+reproduce the appearance of a Microsoft Excel spreadsheet (one worksheet per
+every instance of L{XLSGrid}).
+
+L{XLSGrid} is a completely owner-drawn control, and it relies on the power of
+`wx.grid.PyGridTableBase` and `wx.grid.PyGridCellRenderer` to draw the cell
+content. For this reasons (and for some others, see the TODOs section), it will
+work efficiently only for relatively small Excel files.
+
+:note: L{XLSGrid} **requires** the `xlrd` package from:
+
+ http://pypi.python.org/pypi/xlrd
+
+ Minimum version requirement for `xlrd` is 0.7.1. If you wish to have
+ support for hyperlinks inside cells and rich text content, you need the
+ SVN version of `xlrd`.
+
+:note: On Windows, it is **strongly** recommended to install Mark Hammonds'
+ `pywin32` package:
+
+ http://sourceforge.net/projects/pywin32/
+
+ This will allow you to perfectly reproduce the appearance of the Excel
+ worksheet in your instance of L{XLSGrid}.
+
+:warning: If Mark Hammonds' `pywin32` package is not available, the formatting
+ capabilities of L{XLSGrid} are severely limited; for instance, you won't
+ probably get the exact WYSIWYG between the Excel spreadsheet and L{XLSGrid}.
+
+:warning: L{XLSGrid} can only read Excel `.xls` files, not the newer versions
+ `.xlsx` generated by Office 2007/2010. If you have a `.xlsx` file, you will
+ need to save it in 1997-2003 Office compatibility mode.
+
+
+Currently this class provides a read-only subclass of `wx.grid.Grid`, with
+the following formatting features already implemented:
+
+* Cell background: support for any cell background colour and fill pattern
+  (hatching) in the Excel default set. There currently is no support for
+  gradient shading inside a cell as `xlrd` doesn't report this information.
+
+* Cell borders: support for all the border types and colours exposed by Excel
+  (left, top, bottom, right and diagonal borders, thin, double, thick, ect...
+  line styles).
+
+* Cell text: support for all kind of fonts (except strikethrough, but this is
+  a bug in wxWidgets), and font colours. As a subset of text/font capabilities,
+  L{XLSGrid} supports the following features found in Excel:
+
+  - Horizontal alignment: left, right, centered, left-indented;
+  - Vertical alignment: left, right, centered;
+  - Text direction: left-to-right or right-to-left;
+  - Text-wrapping: wrapping long texts inside a grid cell;
+  - Shrink-to-fit: text font is reduced until the text can fit in a one-line
+    inside the grid cell;
+  - Text rotation: text can be rotated from +90 to -90 degrees.
+
+* Cell rich text (new in version 0.2): support for strings containing partial
+  bold, italic and underlined text, change of font inside a string etc...
+  Cells with rich text content can not be multi-line and they will not honour
+  the `shrink-to-fit` and `wrapping` settings.
+
+* Cell text appearance: if you are using Mark Hammonds' `pywin32` package, the
+  text displayed in the L{XLSGrid} cells has exactly the same appearance as in
+  the Excel spreadsheet.
+
+* Cell comments (notes): if you are using Mark Hammonds' `pywin32` package,
+  cell comments (notes) are extracted and you will see a small red triangle at
+  the top-right corner of any cell containing a comment. Hovering with the
+  mouse on that cell will pop-up a "comment-window" displaying the comment
+  text (the comment window is based on `wx.lib.agw.supertooltip`).
+
+* Cell hyperlinks: starting from version 0.7.2 (SVN), `xlrd` is capable of
+  extracting hyperlinks from Excel cells. This will be appropriately displayed
+  in L{XLSGrid} with a cursor changing and a tooltip on that cell.
+
+* Cell merging: merged cells in the Excel spreadsheet will be correctly handled
+  by L{XLSGrid}.
+
+* Columns and rows sizes: L{XLSGrid} calculates the correct rows and columns
+  sizes based on the Excel reported values in characters. The calculations are
+  based on the default width of the text in 1/256 of the width of the zero
+  character, using default Excel font (first FONT record in the Excel file).
+
+
+And a lot more. Check the demo for an almost complete review of the functionalities.
+
+
+Usage
+=====
+
+Sample usage::
+
+    import wx
+    import xlrd
+    import os
+
+    import xlsgrid as XG
+
+    class MyFrame(wx.Frame):
+
+        def __init__(self):
+
+            wx.Frame.__init__(self, parent, -1, "XLSGrid Demo", size=(1000, 800))
+
+            filename = os.path.join(os.getcwd(), "Excel", "Example_1.xls")
+            sheetname = "Example_1"
+
+            book = xlrd.open_workbook(filename, formatting_info=1)
+
+            sheet = book.sheet_by_name(sheetname)
+            rows, cols = sheet.nrows, sheet.ncols
+
+            comments, texts = XG.ReadExcelCOM(filename, sheetname, rows, cols)
+
+            xls_grid = XG.XLSGrid(self)
+            xls_grid.PopulateGrid(book, sheet, texts, comments)
+
+
+    # our normal wxApp-derived class, as usual
+
+    app = wx.PySimpleApp()
+
+    frame = MyFrame(None)
+    app.SetTopWindow(frame)
+    frame.Show()
+
+    app.MainLoop()
+
+
+:note: Please note that you **have to** pass the keyword `formatting_info` to
+ the method `xlrd.open_workbook` to obtain the cell formatting.
+
+
+TODOs
+=====
+
+1. L{XLSGrid} is sufficiently efficient and fast for reasonably small Excel files.
+   There might be some improvement to be made in the code to make it work with
+   bigger files and in a faster way;
+2. `wx.grid.Grid` seems to completely redraw itself at every resize event, even
+   if the cell content has not changed and it has not been damaged (this seems
+   to be fixed in wxPython 2.9.2.1);
+3. There is currently no support for strikethrough fonts, although `xlrd` correctly
+   reports this format. The issue is a bug in wxWidgets itself which doesn't
+   allow the creation of strikethrough fonts (http://trac.wxwidgets.org/ticket/9907).
+
+
+Supported Platforms
+===================
+
+L{XLSGrid} has been tested on the following platforms:
+  * Windows (Windows Vista and 7);
+
+
+Window Styles
+=============
+
+`No particular window styles are available for this class.`
+
+
+Events Processing
+=================
+
+`No custom events are available for this class.`
+
+
+License And Version
+===================
+
+L{XLSGrid} is distributed under the wxPython license.
+
+Latest Revision: Andrea Gavana @ 17 Aug 2011, 15.00 GMT
+
+Version 0.3
+
+"""
+
+# Version Info
+__version__ = "0.3"
+
+# Start the imports
+import wx
+import os
+
+try:
+    import xlrd
+except ImportError:
+    pass
+
+import datetime
+import string
+
+import wx.grid as gridlib
+
+from wx.lib.embeddedimage import PyEmbeddedImage
+from wx.lib.wordwrap import wordwrap
+
+import supertooltip as STT
+
+from math import pi, sin, cos
+from operator import attrgetter
+
+_hasWin32 = False
+
+if wx.Platform == "__WXMSW__":
+    try:
+        from win32com.client import Dispatch
+        import pywintypes
+        _hasWin32 = True
+    except ImportError:
+        pass
+
+
+#----------------------------------------------------------------------
+# Constants used to translate xlrd stuff into wxPython stuff
+#----------------------------------------------------------------------
+
+BOTTOM = wx.BOTTOM
+TOP = wx.TOP
+LEFT = wx.LEFT
+RIGHT = wx.RIGHT
+DIAGONAL = 2 << 7
+
+XF_BORDER_STYLES = {"bottom": BOTTOM, "left": LEFT, "right": RIGHT,
+                    "top": TOP, "diag": DIAGONAL}
+
+HORIZONTAL_ALIGNMENTS = {0: 0, 1: 0, 2: wx.ALIGN_CENTER_HORIZONTAL, 3: wx.ALIGN_RIGHT}
+VERTICAL_ALIGNMENTS   = {0: 0, 1: wx.ALIGN_CENTER_VERTICAL, 2: wx.ALIGN_BOTTOM,
+                         3: wx.ALIGN_CENTER_VERTICAL, 4:wx.ALIGN_CENTER_VERTICAL}
+
+NO_LINE = 0x0
+THIN = 0x1
+MEDIUM = 0x2
+DASHED = 0x3
+DOTTED = 0x4
+THICK = 0x5
+DOUBLE = 0x6
+HAIR = 0x7
+MEDIUM_DASHED = 0x8
+THIN_DASH_DOTTED = 0x9
+MEDIUM_DASH_DOTTED = 0xA
+THIN_DASH_DOT_DOTTED = 0xB
+MEDIUM_DASH_DOT_DOTTED = 0xC
+SLANTED_MEDIUM_DASH_DOTTED = 0xD
+
+XF_PEN_STYLES = {NO_LINE: (0, None), THIN: (1, wx.SOLID), MEDIUM: (2, wx.SOLID),
+                 DASHED: (1, wx.SHORT_DASH), DOTTED: (1, wx.DOT),
+                 THICK: (3, wx.SOLID), DOUBLE: (1, wx.SOLID), HAIR: (1, wx.DOT),
+                 MEDIUM_DASHED: (2, wx.LONG_DASH), THIN_DASH_DOTTED: (1, wx.DOT_DASH),
+                 MEDIUM_DASH_DOTTED: (2, wx.DOT_DASH), THIN_DASH_DOT_DOTTED: (1, wx.DOT_DASH),
+                 MEDIUM_DASH_DOT_DOTTED: (2, wx.DOT_DASH),
+                 SLANTED_MEDIUM_DASH_DOTTED: (2, wx.DOT_DASH)
+                 }
+
+XF_FONT_FAMILY = {0: wx.SWISS, 1: wx.ROMAN, 2: wx.SWISS,
+                  3: wx.MODERN, 4: wx.SCRIPT, 5: wx.DECORATIVE}
+
+# Unicode ordinals for Hebrew, Arabic and Syriac
+# I don't know if there are other RTL languages
+RTL_UNICODE = range(1424, 1872)
+
+# To guess text direction we exclude digits and punctuation
+USELESS_CHARS = string.punctuation + string.digits + " "
+
+
+#----------------------------------------------------------------------
+# Images used to draw the hatching on Excel cells background
+#----------------------------------------------------------------------
+
+_xls_background_01 = PyEmbeddedImage(
+    "iVBORw0KGgoAAAANSUhEUgAAAAQAAAAECAIAAAAmkwkpAAAAA3NCSVQICAjb4U/gAAAADElE"
+    "QVQImWNgIB0AAAA0AAEjQ4N1AAAAAElFTkSuQmCC")
+
+#----------------------------------------------------------------------
+_xls_background_02 = PyEmbeddedImage(
+    "iVBORw0KGgoAAAANSUhEUgAAAAQAAAAECAIAAAAmkwkpAAAAA3NCSVQICAjb4U/gAAAAFklE"
+    "QVQImWNgYGD4//8/lESwIAC7DABt4hfpI2a12wAAAABJRU5ErkJggg==")
+
+#----------------------------------------------------------------------
+_xls_background_03 = PyEmbeddedImage(
+    "iVBORw0KGgoAAAANSUhEUgAAAAQAAAAECAIAAAAmkwkpAAAAA3NCSVQICAjb4U/gAAAAE0lE"
+    "QVQImWP4//8/AxqACuGUAQBI+Qv1NTPP3AAAAABJRU5ErkJggg==")
+
+#----------------------------------------------------------------------
+_xls_background_04 = PyEmbeddedImage(
+    "iVBORw0KGgoAAAANSUhEUgAAAAQAAAAECAIAAAAmkwkpAAAAA3NCSVQICAjb4U/gAAAAH0lE"
+    "QVQImXXJsQ0AIAAEIc79d34LazsSwjbgPFXoOxdcCQwBh7OgqgAAAABJRU5ErkJggg==")
+
+#----------------------------------------------------------------------
+_xls_background_05 = PyEmbeddedImage(
+    "iVBORw0KGgoAAAANSUhEUgAAAAQAAAAECAIAAAAmkwkpAAAAA3NCSVQICAjb4U/gAAAAFUlE"
+    "QVQImWNgwAUY////D+cwIcsAAEggAwHHgMubAAAAAElFTkSuQmCC")
+
+#----------------------------------------------------------------------
+_xls_background_06 = PyEmbeddedImage(
+    "iVBORw0KGgoAAAANSUhEUgAAAAQAAAAECAIAAAAmkwkpAAAAA3NCSVQICAjb4U/gAAAAG0lE"
+    "QVQImWNkYGBgYGD4//8/AwMDEwMSwM0BAISAAwUnufp7AAAAAElFTkSuQmCC")
+
+#----------------------------------------------------------------------
+_xls_background_07 = PyEmbeddedImage(
+    "iVBORw0KGgoAAAANSUhEUgAAAAQAAAAECAIAAAAmkwkpAAAAA3NCSVQICAjb4U/gAAAAHklE"
+    "QVQImWNkYGBgYGD4//8/EgVh/P//H86HikH4APOCFO3yiGicAAAAAElFTkSuQmCC")
+
+#----------------------------------------------------------------------
+_xls_background_08 = PyEmbeddedImage(
+    "iVBORw0KGgoAAAANSUhEUgAAAAQAAAAECAIAAAAmkwkpAAAAA3NCSVQICAjb4U/gAAAAHUlE"
+    "QVQImWP4////////GSAAzvr//z8jmhADXCUAQSkU7eggG3gAAAAASUVORK5CYII=")
+
+#----------------------------------------------------------------------
+_xls_background_09 = PyEmbeddedImage(
+    "iVBORw0KGgoAAAANSUhEUgAAAAQAAAAECAIAAAAmkwkpAAAAA3NCSVQICAjb4U/gAAAAIElE"
+    "QVQImWNkYGBgYGD4//8/AwMDEwMy+P//P0QYXQYACtQI/cTE6U0AAAAASUVORK5CYII=")
+
+#----------------------------------------------------------------------
+_xls_background_10 = PyEmbeddedImage(
+    "iVBORw0KGgoAAAANSUhEUgAAAAQAAAAECAIAAAAmkwkpAAAAA3NCSVQICAjb4U/gAAAAG0lE"
+    "QVQImW3IsQ0AAAjAIPz/6LobGRmgclVfswpsCPmQczsGAAAAAElFTkSuQmCC")
+
+#----------------------------------------------------------------------
+_xls_background_11 = PyEmbeddedImage(
+    "iVBORw0KGgoAAAANSUhEUgAAAAQAAAAECAIAAAAmkwkpAAAAA3NCSVQICAjb4U/gAAAAFklE"
+    "QVQImWNgQAKM////h3OYkGVQOABvOgMD4NUKkwAAAABJRU5ErkJggg==")
+
+#----------------------------------------------------------------------
+_xls_background_12 = PyEmbeddedImage(
+    "iVBORw0KGgoAAAANSUhEUgAAAAQAAAAECAIAAAAmkwkpAAAAA3NCSVQICAjb4U/gAAAAG0lE"
+    "QVQImWNkYGD4//8/AwMDAwMDEwMSwM0BAI13AwWY+Mx+AAAAAElFTkSuQmCC")
+
+#----------------------------------------------------------------------
+_xls_background_13 = PyEmbeddedImage(
+    "iVBORw0KGgoAAAANSUhEUgAAAAQAAAAECAIAAAAmkwkpAAAAA3NCSVQICAjb4U/gAAAAI0lE"
+    "QVQImT3KsQ0AMAyAMMj/P9MhUUcLBCoAmEo9bFn7H/UBXEwMBN75abEAAAAASUVORK5CYII=")
+
+#----------------------------------------------------------------------
+_xls_background_14 = PyEmbeddedImage(
+    "iVBORw0KGgoAAAANSUhEUgAAAAQAAAAECAIAAAAmkwkpAAAAA3NCSVQICAjb4U/gAAAAIElE"
+    "QVQImT3KoQEAAAwCINz/P7tmI5C2QJKb2t6EYPMBOOUMBIWcMEIAAAAASUVORK5CYII=")
+
+#----------------------------------------------------------------------
+_xls_background_15 = PyEmbeddedImage(
+    "iVBORw0KGgoAAAANSUhEUgAAAAQAAAAECAIAAAAmkwkpAAAAA3NCSVQICAjb4U/gAAAAGUlE"
+    "QVQImWNgQAKMDAwM////h3CYkGVQOABmQwMDJpgq9gAAAABJRU5ErkJggg==")
+
+#----------------------------------------------------------------------
+_xls_background_16 = PyEmbeddedImage(
+    "iVBORw0KGgoAAAANSUhEUgAAAAQAAAAECAIAAAAmkwkpAAAAA3NCSVQICAjb4U/gAAAAHklE"
+    "QVQImWNgYGD4//8/lISzIAwEnxEqwMDAyMgIALKwF+2ym+hoAAAAAElFTkSuQmCC")
+
+#----------------------------------------------------------------------
+_xls_background_17 = PyEmbeddedImage(
+    "iVBORw0KGgoAAAANSUhEUgAAAAQAAAAECAIAAAAmkwkpAAAAA3NCSVQICAjb4U/gAAAAIklE"
+    "QVQImWNkYGD4//8/AwMDAwMDI5zFwMDABBVjZESXAQAc+AkAQ4bzDAAAAABJRU5ErkJggg==")
+
+#----------------------------------------------------------------------
+_xls_background_18 = PyEmbeddedImage(
+    "iVBORw0KGgoAAAANSUhEUgAAAAgAAAAECAIAAAA8r+mnAAAAA3NCSVQICAjb4U/gAAAAH0lE"
+    "QVQImWNkYGD4//8/AwZgxCrKwMDAhKKKkZGwDgA83QkAy10JvwAAAABJRU5ErkJggg==")
+
+#----------------------------------------------------------------------
+
+
+def SplitThousands(s, tSep=',', dSep='.'):
+    """
+    Splits a general float on thousands. GIGO on general input.
+
+    :param `s`: can be a float or a string, representing a number;
+    :param `tSep`: the character to be used as thousands separator;
+    :param `dSep`: the character to be used as decimal separator.
+
+    :returns: a string properly formatted with thousands and decimal
+     separators in it.
+
+    :note: This method is used only if Mark Hammonds' `pywin32` package is
+     not available to try and format a number in an intelligent way.
+
+    :note: This code has been obtained from the public domain:
+
+     http://code.activestate.com/recipes/498181-add-thousands-separator-commas-to-formatted-number/#c14
+
+    """
+
+    if not isinstance(s, basestring):
+        s = unicode(s, "utf-8", "ignore")
+
+    cnt = 0
+    numChars = dSep + '0123456789'
+    ls = len(s)
+
+    while cnt < ls and s[cnt] not in numChars:
+        cnt += 1
+
+    lhs = s[0:cnt]
+    s = s[cnt:]
+
+    if dSep == '':
+        cnt = -1
+    else:
+        cnt = s.rfind(dSep)
+
+    if cnt > 0:
+        rhs = dSep + s[cnt+1:]
+        s = s[:cnt]
+    else:
+        rhs = ''
+
+    splt = ''
+    while s != '':
+        splt = s[-3:] + tSep + splt
+        s = s[:-3]
+
+    return lhs + splt[:-1] + rhs
+
+
+def ReadExcelCOM(filename, sheetname, rows, cols):
+    """
+    Reads and Excel spreadsheet (a single worksheet) using Mark Hammonds' `pywin32`
+    package. If this package is not available, it returns two empty nested lists.
+
+    :param `filename`: a valid Excel `.xls` filename;
+    :param `sheetname`: the worksheet name inside the Excel file (i.e., the label
+     on the workbook tab at the bottom of the workbook);
+    :param `rows`: the number of significant rows in the worksheet, as returned
+     by `xlrd`;
+    :param `cols`: the number of significant columns in the worksheet, as returned
+     by `xlrd`.
+
+    :returns: two nested lists representing the comments (notes) on every cell and
+     the WYSIWYG representation of the cell content.
+
+    :note: If Mark Hammonds' `pywin32` package is not available, this method
+     returns two empty nested lists.
+    """
+
+    comments = [["" for i in range(cols)] for j in range(rows)]
+    texts    = [[None for i in range(cols)] for j in range(rows)]
+
+    if not _hasWin32:
+        return comments, texts
+
+    workbook = Excel(filename, sheetname)
+
+    for i in xrange(1, rows+1):
+        for j in xrange(1, cols+1):
+            texts[i-1][j-1]    = workbook.GetText(i, j)
+
+    comm_range = workbook.GetCommentsRange()
+    if comm_range is not None:
+        for comm in comm_range:
+            comments[comm.Row-1][comm.Column-1] = comm.Comment.Text()
+
+    workbook.Close()
+    return comments, texts
+
+
+def FontFromFont(font):
+    """
+    Creates a copy of the input `font`.
+
+    :param `font`: an instance of `wx.Font`.
+    """
+
+    new_font = wx.Font(font.GetPointSize(), font.GetFamily(), font.GetStyle(),
+                       font.GetWeight(), font.GetUnderlined(),
+                       font.GetFaceName(), font.GetEncoding())
+
+    return new_font
+
+
+class Excel(object):
+    """
+    A simple class that holds a COM interface to Excel.
+
+    By using the `win32com` module from Mark Hammonds' `pywin32` package, we
+    can manipulate various workbook/worksheet methods inside this class.
+    """
+
+    def __init__(self, filename, sheetname):
+        """
+        Default class constructor.
+
+        :param `filename`: a valid Excel `.xls` filename;
+        :param `sheetname`: the worksheet name inside the Excel file (i.e., the label
+         on the workbook tab at the bottom of the workbook).
+        """
+
+        self.xlApp = Dispatch('Excel.Application')
+        self.filename = filename
+        self.xlBook = self.xlApp.Workbooks.Open(filename)
+        self.sheet = self.xlBook.Worksheets(sheetname)
+
+        self.xlApp.Visible = 0
+
+
+    def Close(self, save=False):
+        """
+        Closes the Excel workbook, interrupting the COM interface.
+
+        :param `save`: ``True`` to save the changes you made to the workbook,
+         ``False`` otherwise.
+        """
+
+        self.xlBook.Close(SaveChanges=save)
+        del self.xlApp
+
+
+    def GetCommentsRange(self):
+        """
+        Returns a range of cells containing comments, using the VBA API.
+
+        """
+
+        try:
+            return self.sheet.Cells.SpecialCells(-4144)
+        except pywintypes.com_error:
+            return None
+
+
+    def GetText(self, row, col):
+        """
+        Returns the WYSIWYG text contained in a cell.
+
+        :param `row`: the row in which the cell lives;
+        :param `col`: the column in which the cell lives.
+
+        :note: The `row` and `col` parameters are not real Python index, as they
+         use the Excel indexing mode (i.e., first index is 1 and not 0).
+        """
+
+        cell = self.sheet.Cells(row, col)
+
+        if cell:
+            return cell.Text
+
+
+class XLSText(object):
+    """
+    This is a class which holds information about the cell content, in terms
+    of actual cell value, font, text colour, alignment and formatting.
+    """
+
+    def __init__(self, book, cell, xf_index, display_text=None, hyperlink=None, default_width=10):
+        """
+        Default class constructor.
+
+        :param `book`: an instance of the `xlrd.Book` class;
+        :param `cell`: an instance of `xlrd.sheet.Cell` class;
+        :param `xf_index`: an index into `xlrd.Book.xf_list`, which holds a
+         reference to the `xlrd.sheet.Cell` class (the actual cell for `xlrd`);
+        :param `display_text`: if Mark Hammonds' `pywin32` package is available,
+         this is the WYSIWYG cell content;
+        :param `hyperlink`: if this cell contains a hyperlink, it will be displayed
+         accordingly;
+        :param `default_width`: this is the default width of the text in 1/256
+         of the width of the zero character, using default Excel font (first FONT
+         record in the Excel file).
+
+        :note: If you are using version 0.7.1 or lower for `xlrd`, the *hyperlink*
+         parameter will always be ``None`` as this feature is available only in
+         `xlrd` 0.7.2 (SVN).
+        """
+
+        XFClass = book.xf_list[xf_index]
+
+        font = book.font_list[XFClass.font_index]
+        self.font = self.CreateFont(font)
+
+        text_colour = book.colour_map[font.colour_index]
+        self.text_colour = self.CreateTextColour(text_colour)
+
+        if display_text is not None:
+            self.value = display_text
+        else:
+            format = book.format_map[XFClass.format_key]
+            self.CreateFormat(format, cell, book.datemode)
+
+        alignment = XFClass.alignment
+        self.CreateAlignment(alignment, default_width)
+
+        if hyperlink is not None:
+            self.SetupHyperlink(hyperlink)
+        else:
+            self.tooltip = None
+
+
+    def CreateFont(self, font):
+        """
+        Creates a suitable wxPython font starting from an Excel font.
+
+        :param `font`: an instance of `xlrd.formatting.Font` class.
+
+        :note: There is currently no support for strikethrough fonts, although
+         `xlrd` correctly reports this format. The issue is a bug in wxWidgets
+         itself which doesn't allow the creation of strikethrough fonts. See
+         (http://trac.wxwidgets.org/ticket/9907).
+        """
+
+        style, bold, underline = wx.FONTSTYLE_NORMAL, wx.NORMAL, False
+        if font.italic:
+            style = wx.FONTSTYLE_ITALIC
+        if font.underline_type > 0:
+            underline = True
+        if font.weight > 600:
+            bold = wx.BOLD
+
+        family = XF_FONT_FAMILY[font.family]
+        name = font.name
+        size = int(font.height/20.0)
+
+        if font.escapement_type > 0:
+            # subscript/superscript
+            size = int(size*0.7)
+
+        # No support for strike-through fonts in wxWidgets
+#        if font.struck_out:
+#            style = wx.FONTFLAG_DEFAULT
+#            if bold:
+#                style += wx.FONTFLAG_BOLD
+#            if underline:
+#                style += wx.FONTFLAG_UNDERLINED
+#            if font.italic:
+#                style += wx.FONTFLAG_ITALIC
+#
+#            style += wx.FONTFLAG_STRIKETHROUGH
+#            self.font = wx.FFont(size, family, style, name.encode())
+#        else:
+
+        return wx.Font(size, family, style, bold, underline, name.encode())
+
+
+    def CreateTextColour(self, text_colour):
+        """
+        Creates a suitable wxPython colour for the text starting from a `xlrd`
+        tuple representing this colour.
+
+        :param `text_colour`: a tuple representing the RGB components of the
+         colour. If `text_colour` is ``None``, use the default ``wx.SYS_COLOUR_WINDOWTEXT``.
+        """
+
+        if text_colour is not None:
+            text_colour = wx.Colour(*text_colour)
+        else:
+            text_colour = wx.SystemSettings.GetColour(wx.SYS_COLOUR_WINDOWTEXT)
+
+        return text_colour
+
+
+    def CreateAlignment(self, alignment, default_width):
+        """
+        Creates a suitable wxPython alignment flag for the text starting from a
+        `xlrd` class representing this alignment.
+
+        :param `alignment`: an instance of `xlrd.formatting.XFAlignment` class;
+        :param `default_width`: this is the default width of the text in 1/256
+         of the width of the zero character, using default Excel font (first FONT
+         record in the Excel file).
+        """
+
+        hor_align, vert_align = alignment.hor_align, alignment.vert_align
+        self.horizontal_alignment = HORIZONTAL_ALIGNMENTS[hor_align]
+        self.vertical_alignment = VERTICAL_ALIGNMENTS[vert_align]
+
+        self.indent_level = alignment.indent_level
+        self.shrink_to_fit = alignment.shrink_to_fit
+        self.text_wrapped = alignment.text_wrapped
+
+        text_direction = 1
+
+        if alignment.text_direction == 0:
+            for char in self.value:
+                if char not in USELESS_CHARS:
+                    if ord(char) in RTL_UNICODE:
+                        text_direction = 2
+                        break
+
+        self.text_direction = text_direction
+        self.default_width = default_width
+
+        if alignment.rotation > 90:
+            self.rotation = 90 - alignment.rotation
+        else:
+            self.rotation = alignment.rotation
+
+
+    def CreateFormat(self, format, cell, datemode):
+        """
+        This method tries to guess the best format to apply to the current text
+        value.
+
+        :param `format`: an instance of `xlrd.formatting.Format` class;
+        :param `cell`: an instance of `xlrd.sheet.Cell` class;
+        :param `datemode`: the datemode associated with this Excel workbook.
+
+        :note: This method is used only if Mark Hammonds' `pywin32` package is
+         not available to try and format the cell text in an intelligent way.
+
+        :warning: The formatting applied by this method is severely limited; for
+         instance, you won't probably get the exact WYSIWYG between the Excel
+         spreadsheet and L{XLSGrid}.
+        """
+
+        ctype, value = cell.ctype, cell.value
+
+        self.value = "%s"%value
+        isDate = False
+
+        if ctype == xlrd.XL_CELL_DATE:
+            value = xlrd.xldate_as_tuple(value, datemode)
+            isDate = True
+        elif ctype in [xlrd.XL_CELL_EMPTY, xlrd.XL_CELL_BLANK]:
+            return
+        elif ctype == xlrd.XL_CELL_TEXT:
+            self.value = "%s"%value
+            return
+        elif ctype == xlrd.XL_CELL_ERROR:
+            value = xlrd.error_text_from_code(ctype)
+            self.value = "%s"%value
+            return
+
+        self.FormatString(value, isDate, format.format_str)
+
+
+    def FormatString(self, value, isDate, format_str):
+        """
+        This method tries to guess the best format to apply to the current text
+        value.
+
+        :param `value`: the actual raw cell text value;
+        :param `isDate`: ``True`` if this value represents a `xlrd` date object,
+         ``False`` otherwise;
+        :param `format_str`: the actual formatting string as extracted from Excel.
+
+        :note: This method is used only if Mark Hammonds' `pywin32` package is
+         not available to try and format the cell text in an intelligent way.
+
+        :warning: The formatting applied by this method is severely limited; for
+         instance, you won't probably get the exact WYSIWYG between the Excel
+         spreadsheet and L{XLSGrid}.
+        """
+
+        if "General" in format_str:
+            self.value = "%s"%value
+            return
+
+        number_format = format_str
+        currency = percentage = ""
+
+        if not isDate:
+            symbol = ""
+            split = format_str.split()
+            if len(split) > 1:
+                # Accounting and currency shit
+                currency = split[0].split(".")[0] + "."
+                number_format = ".".join(split[1:])
+
+            if "%" in number_format:
+                percentage = "%"
+                value = 100*value
+                number_format = number_format[0:-1]
+
+            representation = "%d"
+            if "." in number_format:
+                split = number_format.split(".")
+                num_decimals = len(split[1])
+                representation = "%0." + str(num_decimals) + "f"
+
+            try:
+                value = representation%value
+            except ValueError:
+                # Fall back to string
+                value = unicode(value, "utf-8", "ignore")
+
+            if "#," in number_format:
+                value = SplitThousands(value)
+
+            value = currency + value + percentage
+
+        else:
+            number_format = format_str.replace("\\", "")
+            number_format = number_format.replace("-", "-%").replace("/", "/%")
+            value = datetime.datetime(*value)
+            try:
+                value = value.strftime(number_format)
+            except (ValueError, TypeError):
+                value = value.strftime("%d.%m.%Y")
+
+        self.value = value
+
+
+    def SetupHyperlink(self, hyperlink):
+        """
+        Sets up the cell text value in case it represents a hyperlink.
+
+        :param `hyperlink`: an instance of `xlrd.sheet.hyperlink`.
+
+        :note: If you are using version 0.7.1 or lower for `xlrd`, the *hyperlink*
+         parameter will always be ``None`` as this feature is available only in
+         `xlrd` 0.7.2 (SVN).
+        """
+
+        url = (hyperlink.url_or_path and [hyperlink.url_or_path] or [hyperlink.textmark])[0]
+        self.tooltip = url
+
+
+    def IsHyperLink(self):
+        """
+        Returns whether the cell text is representing a hyperlink.
+
+        :returns: ``True`` if the cell text represents a hyperlink, ``False``
+         otherwise.
+        """
+
+        return self.tooltip is not None
+
+
+    def CombineAttr(self, attr):
+        """
+        Combines the input attribute `attr` with the features of the L{XLSText} class.
+
+        :param `attr`: an instance of `wx.grid.GridCellAttr`.
+        """
+
+        attr.SetAlignment(self.horizontal_alignment, self.vertical_alignment)
+        attr.SetTextColour(self.text_colour)
+        attr.SetFont(self.font)
+
+
+    def GetValue(self):
+        """ Returns the string representation of the cell text value. """
+
+        return self.value
+
+
+    def Draw(self, dc, rect):
+        """
+        Actually draws the text value on a grid cell.
+
+        :param `dc`: an instance of `wx.DC`;
+        :param `rect`: an instance of `wx.Rect`, representing the cell rectangle.
+        """
+
+        new_rect = wx.Rect(*rect)
+
+        xshift = yshift = 0
+        if self.rotation:
+            xshift = cos(self.rotation*pi/180)
+            yshift = sin(self.rotation*pi/180)
+
+        dc.SetTextForeground(self.text_colour)
+        dc.SetFont(self.font)
+
+        value = self.value
+        text_width, text_height = dc.GetTextExtent(value)
+
+        default_width = int(round(float(self.default_width)*text_width/256.0))
+
+        indentation = int(256.0*default_width/float(self.default_width))
+
+        if xshift == 0 and self.indent_level:
+            new_rect.SetLeft(new_rect.x + indentation)
+        else:
+            if self.horizontal_alignment == wx.ALIGN_LEFT:
+                new_rect.SetLeft(new_rect.x + 3)
+            elif self.horizontal_alignment == wx.ALIGN_RIGHT:
+                new_rect.SetWidth(new_rect.width - 1)
+
+        new_width = rect.width
+
+        if xshift > 0:
+            new_width = new_width/xshift
+
+        if self.shrink_to_fit:
+
+            font = FontFromFont(self.font)
+            point_size = font.GetPointSize()
+
+            while 1:
+                value = wordwrap(self.value, new_width, dc)
+                if "\n" not in value or point_size < 2:
+                    break
+
+                point_size -= 1
+                font.SetPointSize(point_size)
+                dc.SetFont(font)
+
+        elif self.text_wrapped:
+
+            value = wordwrap(self.value, new_width, dc)
+            text_width, text_height, dummy = dc.GetMultiLineTextExtent(value)
+
+        if self.rotation:
+            if self.shrink_to_fit:
+                text_width, text_height = dc.GetTextExtent(value)
+
+            xc, yc = (rect.x+rect.width/2, rect.y+rect.height/2)
+            xp = xc - (text_width/2)*xshift - (text_height/2)*yshift
+            yp = yc + (text_width/2)*yshift - (text_height/2)*xshift
+
+            dc.DrawRotatedText(value, xp, yp, self.rotation)
+
+        else:
+
+            dc.DrawLabel(value, new_rect, self.horizontal_alignment|self.vertical_alignment)
+
+
+class XLSRichText(XLSText):
+    """
+    This is a class which holds information about the cell content, in terms
+    of actual cell value, font, text colour, alignment and formatting. In addition
+    to what L{XLSText} does, this class attempts to handle cells with rich text
+    content.
+    """
+
+    def __init__(self, book, cell, xf_index, display_text=None, hyperlink=None, rich_text=None, default_width=10):
+        """
+        Default class constructor.
+
+        :param `book`: an instance of the `xlrd.Book` class;
+        :param `cell`: an instance of `xlrd.sheet.Cell` class;
+        :param `xf_index`: an index into `xlrd.Book.xf_list`, which holds a
+         reference to the `xlrd.sheet.Cell` class (the actual cell for `xlrd`);
+        :param `display_text`: if Mark Hammonds' `pywin32` package is available,
+         this is the WYSIWYG cell content;
+        :param `hyperlink`: if this cell contains a hyperlink, it will be displayed
+         accordingly;
+        :param `rich_text`: if this cell contains text in rich text format, L{XLSGrid}
+         will do its best to render the text as rich text;
+        :param `default_width`: this is the default width of the text in 1/256
+         of the width of the zero character, using default Excel font (first FONT
+         record in the Excel file).
+
+        :note: If you are using version 0.7.1 or lower for `xlrd`, the *hyperlink*
+         parameter will always be ``None`` as this feature is available only in
+         `xlrd` 0.7.2 (SVN).
+
+        :note: If you are using version 0.7.1 or lower for `xlrd`, this class will
+         note be used by L{XLSGrid}.
+
+        :warning: This class currently supports only single-line non-rotated text,
+         and it discards properties like `shrink-to-fit` and `wrapping`.
+        """
+
+        XLSText.__init__(self, book, cell, xf_index, display_text, hyperlink, default_width)
+
+        self.BuildChunks(book, xf_index, rich_text)
+
+
+    def BuildChunks(self, book, xf_index, rich_text):
+        """
+        Splits the cell content accordingly to their rich text format index.
+
+        :param `book`: an instance of the `xlrd.Book` class;
+        :param `xf_index`: an index into `xlrd.Book.xf_list`, which holds a
+         reference to the `xlrd.sheet.Cell` class (the actual cell for `xlrd`);
+        :param `rich_text`: if this cell contains text in rich text format, L{XLSGrid}
+         will do its best to render the text as rich text.
+        """
+
+        XFClass = book.xf_list[xf_index]
+        offset, index = rich_text[0]
+
+        if offset != 0:
+            new_tuple = (0, XFClass.font_index)
+            rich_text.insert(0, new_tuple)
+
+        value = self.value
+        rich_text.append((len(value), rich_text[-1][1]))
+        attributes = []
+
+        for indx in xrange(len(rich_text)-1):
+            offset_start, index_start = rich_text[indx]
+            offset_end, index_end = rich_text[indx+1]
+
+            chunk = value[offset_start:offset_end]
+
+            font = book.font_list[index_start]
+            ffont = self.CreateFont(font)
+            text_colour = book.colour_map[font.colour_index]
+            colour = self.CreateTextColour(text_colour)
+
+            ffont.escapement = font.escapement_type
+            attributes.append([chunk, ffont, colour])
+
+        self.attributes = attributes
+
+
+    def Measure(self, dc):
+        """
+        Convenience method to measure the maximum height and total width of all
+        the chunks of text composing our rich text string.
+
+        :param `dc`: an instance of `wx.DC`.
+        """
+
+        maxH = -1
+        full_width = 0
+        for chunk, font, colour in self.attributes:
+            dc.SetFont(font)
+            width, height, descent, leading = dc.GetFullTextExtent(chunk, font)
+            maxH = max(maxH, height-leading)
+            full_width += width
+
+        return maxH, full_width
+
+
+    def Draw(self, dc, rect):
+        """
+        Actually draws all the chunks of text on a grid cell, one by one.
+
+        :param `dc`: an instance of `wx.DC`;
+        :param `rect`: an instance of `wx.Rect`, representing the cell rectangle.
+        """
+
+        new_rect = wx.Rect(*rect)
+
+        text_width, text_height = dc.GetTextExtent(self.value)
+        default_width = int(round(float(self.default_width)*text_width/256.0))
+        indentation = int(256.0*default_width/float(self.default_width))
+
+        maxH, full_width = self.Measure(dc)
+
+        if self.indent_level:
+            new_rect.SetLeft(new_rect.x + indentation)
+        else:
+            if self.horizontal_alignment == wx.ALIGN_LEFT:
+                new_rect.SetLeft(new_rect.x + 3)
+            elif self.horizontal_alignment == wx.ALIGN_RIGHT:
+                new_rect.SetLeft(new_rect.x + (new_rect.width - full_width) - 1)
+            else:
+                space = int((new_rect.width - full_width)/2.0)
+                new_rect.SetLeft(new_rect.x + space)
+                new_rect.SetWidth(full_width+space)
+
+        if self.vertical_alignment == wx.ALIGN_TOP:
+            vspace = 0
+        elif self.vertical_alignment == wx.ALIGN_BOTTOM:
+            vspace = (new_rect.height - maxH - 1)
+        else:
+            vspace = int((new_rect.height - maxH)/2.0)
+
+        start = new_rect.x
+        y = new_rect.y
+
+        for chunk, font, colour in self.attributes:
+            dc.SetTextForeground(colour)
+            dc.SetFont(font)
+            width, height, descent, leading = dc.GetFullTextExtent(chunk, font)
+            if font.escapement > 0:
+                height = height*0.7
+
+            ypos = y-height+maxH+vspace
+
+            if font.escapement == 1:
+                ypos = ypos - maxH + height
+
+            dc.DrawText(chunk, start, ypos)
+            start += width
+
+
+class XLSBackground(object):
+    """
+    This is a class which holds information about the cell background, in terms
+    of background colour and background pattern (hatching).
+    """
+
+    def __init__(self, book, xf_index):
+        """
+        Default class constructor.
+
+        :param `book`: an instance of the `xlrd.Book` class;
+        :param `xf_index`: an index into `xlrd.Book.xf_list`, which holds a
+         reference to the `xlrd.sheet.Cell` class (the actual cell for `xlrd`).
+        """
+
+        XFClass = book.xf_list[xf_index]
+
+        background = XFClass.background
+        background_colour = book.colour_map[background.background_colour_index]
+        pattern_colour = book.colour_map[background.pattern_colour_index]
+        fill_pattern = background.fill_pattern
+
+        self.CreateBackgroundColour(background_colour, pattern_colour, fill_pattern)
+
+
+    def CreateBackgroundColour(self, background_colour, pattern_colour, fill_pattern):
+        """
+        Creates a suitable wxPython colour for the cell background starting from
+        a `xlrd` tuple representing this colour.
+
+        :param `background_colour`: a tuple representing the RGB components of the
+         cell background colour. If `background_colour` is ``None``, use the
+         default ``wx.SYS_COLOUR_WINDOW``;
+        :param `pattern_colour`: a tuple representing the RGB components of the
+         cell pattern colour;
+        :param `fill_pattern`: the pattern to use to draw hatches on top of the
+         background.
+        """
+
+        if background_colour is not None:
+            background_colour = wx.Colour(*background_colour)
+        else:
+            background_colour = wx.SystemSettings.GetColour(wx.SYS_COLOUR_WINDOW)
+
+        if pattern_colour is not None:
+            pattern_colour = wx.Colour(*pattern_colour)
+
+        self.background_brush = wx.Brush(background_colour)
+        self.background_colour = background_colour
+
+        self.fill_brush = None
+
+        if fill_pattern <= 0:
+            return
+
+        r, g, b = pattern_colour
+
+        fill_image = eval("_xls_background_%02d.GetImage()"%fill_pattern)
+        fill_image.Replace(0, 0, 0, r, g, b)
+        r, g, b = background_colour.Red(), background_colour.Green(), background_colour.Blue()
+        fill_image.Replace(255, 255, 255, r, g, b)
+        fill_bitmap = fill_image.ConvertToBitmap()
+
+        self.fill_brush = wx.BrushFromBitmap(fill_bitmap)
+
+
+    def CombineAttr(self, attr):
+        """
+        Combines the input attribute `attr` with the features of the L{XLSBackground} class.
+
+        :param `attr`: an instance of `wx.grid.GridCellAttr`.
+        """
+
+        attr.SetBackgroundColour(self.background_colour)
+        return attr
+
+
+    def Draw(self, dc, rect):
+        """
+        Actually draws the cell background and pattern hatching on a grid cell.
+
+        :param `dc`: an instance of `wx.DC`;
+        :param `rect`: an instance of `wx.Rect`, representing the cell rectangle.
+        """
+
+        dc.SetClippingRect(rect)
+
+        dc.SetBackgroundMode(wx.SOLID)
+        dc.SetBrush(self.background_brush)
+        dc.SetPen(wx.TRANSPARENT_PEN)
+        dc.DrawRectangleRect(rect)
+
+        if self.fill_brush:
+
+            dc.SetBrush(self.fill_brush)
+            dc.SetBackgroundMode(wx.TRANSPARENT)
+            dc.DrawRectangleRect(rect)
+
+        dc.DestroyClippingRegion()
+
+
+class XLSBorder(object):
+    """
+    This is a class which holds information about a single cell border, in terms
+    of its location (top, left, bottom, right, diagonal), its colour, width and
+    shape.
+    """
+
+    def __init__(self, location, line_style, border_colour, default_colour, diagonals):
+        """
+        Default class constructor.
+
+        :param `location`: the actual border location (top, left, bottom, right,
+         diagonal);
+        :param `line_style`: the line style used by Excel to draw this border;
+        :param `border_colour`: the colour used by Excel to draw this border;
+        :param `default_colour`: the "magic" colour used by Excel to draw non-custom
+         border lines;
+        :param `diagonals`: a tuple containing whether or not to draw the up and down
+         diagonal borders.
+        """
+
+        self.draw_priority = 2
+
+        if line_style == NO_LINE:
+
+            if border_colour == (0, 0, 0):
+                self.draw_priority = 0
+                border_colour = wx.Colour(*default_colour)
+            else:
+                self.draw_priority = 1
+                border_colour = wx.BLACK
+
+            self.pen = wx.Pen(border_colour, 1, wx.SOLID)
+            pen_style = THIN
+
+        else:
+
+            if border_colour == (0, 0, 0):
+                border_colour = wx.Colour(*default_colour)
+                self.draw_priority = 2
+            elif border_colour is None:
+                border_colour = wx.BLACK
+                self.draw_priority = 2
+            else:
+                border_colour = wx.Colour(*border_colour)
+
+            pen_width, pen_style = XF_PEN_STYLES[line_style]
+            if pen_width > 2:
+                self.draw_priority = 4
+            elif pen_width > 1:
+                self.draw_priority = 3
+
+            self.pen = wx.Pen(border_colour, pen_width, pen_style)
+
+        self.diagonals = diagonals
+        self.location = location
+        self.pen_style = pen_style
+        self.line_style = line_style
+
+
+    def Draw(self, dc, rect):
+        """
+        Actually draws the cell border.
+
+        :param `dc`: an instance of `wx.DC`;
+        :param `rect`: an instance of `wx.Rect`, representing the cell rectangle.
+        """
+
+        dc.SetBackgroundMode(wx.TRANSPARENT)
+        dc.SetPen(self.pen)
+
+        if self.location == DIAGONAL:
+            self.DrawDiagonals(dc, rect)
+        else:
+            self.DrawBorder(dc, rect)
+
+
+    def DrawDiagonals(self, dc, rect):
+        """
+        Actually draws the cell diagonal border.
+
+        :param `dc`: an instance of `wx.DC`;
+        :param `rect`: an instance of `wx.Rect`, representing the cell rectangle.
+        """
+
+        diag_up, diag_down = self.diagonals
+
+        if diag_down:
+            xstart, ystart = rect.GetTopLeft()
+            xend, yend = rect.GetBottomRight()
+
+            if self.line_style == DOUBLE:
+                dc.DrawLine(xstart+2, ystart, xend, yend-2)
+                dc.DrawLine(xstart, ystart+2, xend-2, yend)
+            else:
+                dc.DrawLine(xstart, ystart, xend, yend)
+
+        if diag_up:
+
+            xstart, ystart = rect.GetBottomLeft()
+            xend, yend = rect.GetTopRight()
+
+            if self.line_style == DOUBLE:
+                dc.DrawLine(xstart, ystart-2, xend-2, yend)
+                dc.DrawLine(xstart+2, ystart, xend, yend+2)
+            else:
+                dc.DrawLine(xstart, ystart, xend, yend)
+
+
+    def DrawBorder(self, dc, rect):
+        """
+        Actually draws the cell border (one of left, right, bottom, top).
+
+        :param `dc`: an instance of `wx.DC`;
+        :param `rect`: an instance of `wx.Rect`, representing the cell rectangle.
+        """
+
+        pen_width = self.pen.GetWidth()
+        location = self.location
+        new_rect = wx.Rect(*rect)
+
+        x, y, w, h = new_rect
+        line_style = self.line_style
+
+        shift = 0
+        if pen_width == 2:
+            shift = pen_width - 1
+        if pen_width > 2:
+            shift = pen_width - 2
+
+        if location == BOTTOM:
+
+            if self.draw_priority < 2:
+                return
+
+            if line_style == DOUBLE:
+                dc.DrawLine(x, y+h-1, x+w, y+h-1)
+                dc.DrawLine(x, y+h+1, x+w, y+h+1)
+            else:
+                dc.DrawLine(x+1, y+h,   x+w, y+h)
+
+
+        elif location == TOP:
+
+            if line_style == DOUBLE:
+                dc.DrawLine(x, y-1, x+w, y-1)
+                dc.DrawLine(x, y+1, x+w, y+1)
+            else:
+                dc.DrawLine(x+1, y+shift,   x+w, y+shift)
+
+        elif location == LEFT:
+
+            if line_style == DOUBLE:
+                dc.DrawLine(x-1, y, x-1, y+h)
+                dc.DrawLine(x+1, y, x+1, y+h)
+            else:
+                dc.DrawLine(x+shift,   y+1, x+shift,   y+h)
+
+        elif location == RIGHT:
+
+            if self.draw_priority < 2:
+                return
+
+            if line_style == DOUBLE:
+                dc.DrawLine(x+w-1, y, x+w-1, y+h)
+                dc.DrawLine(x+w+1, y, x+w+1, y+h)
+            else:
+                dc.DrawLine(x+w+1, y+1, x+w+1, y+h)
+
+
+class XLSBorderFactory(object):
+    """
+    This is a factory class which holds information about all the borders in a
+    cell. Its implementation and use is merely to simplify the handling of the
+    different cell borders (left, top, bottom, right, diagonal).
+    """
+
+    def __init__(self, book, border, default_colour):
+        """
+        Default class constructor.
+
+        :param `book`: an instance of the `xlrd.Book` class;
+        :param `border`: an instance of `xlrd.formatting.XFBorder` class;
+        :param `default_colour`: the "magic" colour used by Excel to draw non-custom
+         border lines.
+        """
+
+        borders = {}
+        diagonals = border.diag_up, border.diag_down
+
+        for label, location in XF_BORDER_STYLES.items():
+            line_style = getattr(border, "%s_line_style"%label)
+            colour_index = getattr(border, "%s_colour_index"%label)
+            border_colour = book.colour_map[colour_index]
+
+            border_class = XLSBorder(location, line_style, border_colour, default_colour, diagonals)
+            borders[location] = border_class
+
+        self.draw_priority = sorted(borders.values(), key=attrgetter('draw_priority'))
+
+
+    def Draw(self, dc, rect):
+        """
+        Actually draws all the cell borders based on their drawing priority.
+
+        :param `dc`: an instance of `wx.DC`;
+        :param `rect`: an instance of `wx.Rect`, representing the cell rectangle.
+
+        :note: The drawing priority is assigned depending on if the border is a
+         custom one or not. Customized borders are drawn last.
+        """
+
+        for border in self.draw_priority:
+            border.Draw(dc, rect)
+
+
+class XLSComment(object):
+    """
+    This is a class which holds information about the content of the "comment
+    window" (aka note) in Excel.
+
+    :note: If Mark Hammonds' `pywin32` package is not available, this class can
+     not be used.
+    """
+
+    def __init__(self, comment):
+        """
+        Default class constructor.
+
+        :param `comment`: the actual text contained in the Excel cell comment (note).
+        """
+
+        self.comment = comment
+
+
+    def Draw(self, dc, rect):
+        """
+        Actually draws a small red triangle in the top-right corder of the cell
+        to indicate that a comment is present.
+
+        :param `dc`: an instance of `wx.DC`;
+        :param `rect`: an instance of `wx.Rect`, representing the cell rectangle.
+        """
+
+        right = rect.GetTopRight()
+        points = [wx.Point(right.x-5, right.y),
+                  right,
+                  wx.Point(right.x, right.y+5)]
+
+        dc.SetBrush(wx.RED_BRUSH)
+        dc.SetPen(wx.RED_PEN)
+        dc.DrawPolygon(points)
+
+
+class XLSCell(object):
+    """
+    This is a class which holds information about a single cell in L{XLSGrid}.
+    It stores (via auxiliary classes), all details about cell background, text,
+    font, colours and borders.
+    """
+
+    def __init__(self, book, cell, xf_index, xls_text, xls_comment, hyperlink, rich_text, default_width, default_colour):
+        """
+        Default class constructor.
+
+        :param `book`: an instance of the `xlrd.Book` class;
+        :param `cell`: an instance of `xlrd.sheet.Cell` class;
+        :param `xf_index`: an index into `xlrd.Book.xf_list`, which holds a
+         reference to the `xlrd.sheet.Cell` class (the actual cell for `xlrd`);
+        :param `xls_text`: the actual WYSIWYG cell text, if available;
+        :param `xls_comment`: the cell comment (note), if any;
+        :param `hyperlink`: an instance of `xlrd.sheet.hyperlink`;
+        :param `rich_text`: if this cell contains text in rich text format, L{XLSGrid}
+         will do its best to render the text as rich text;
+        :param `default_width`: this is the default width of the text in 1/256
+         of the width of the zero character, using default Excel font (first FONT
+         record in the Excel file);
+        :param `default_colour`: the "magic" colour used by Excel to draw non-custom
+         border lines.
+
+        :note: If you are using version 0.7.1 or lower for `xlrd`, the *hyperlink*
+         parameter will always be ``None`` as this feature is available only in
+         `xlrd` 0.7.2 (SVN).
+
+        :note: If you are using version 0.7.1 or lower for `xlrd`, the `rich_text`
+         parameter will always be ``None`` as this feature is available only in
+         `xlrd` 0.7.2 (SVN).
+
+        :note: if Mark Hammonds' `pywin32` package is not available, the `xls_text`
+         parameter will almost surely not be the WYSIWYG representation of the cell
+         text.
+
+        :note: If Mark Hammonds' `pywin32` package is not available, the `xls_comment`
+         parameter will always be ``None``.
+        """
+
+        self.size = 1, 1
+
+        self.comment = None
+        self.hyperlink = None
+
+        self.SetupCell(book, cell, xf_index, xls_text, xls_comment, hyperlink, rich_text, default_width, default_colour)
+
+
+    def SetupCell(self, book, cell, xf_index, xls_text, xls_comment, hyperlink, rich_text, default_width, default_colour):
+        """
+        Actually sets up the L{XLSCell} class. This is an auxiliary method to
+        avoid cluttering the L{__init__} method.
+
+        :param `book`: an instance of the `xlrd.Book` class;
+        :param `cell`: an instance of `xlrd.sheet.Cell` class;
+        :param `xf_index`: an index into `xlrd.Book.xf_list`, which holds a
+         reference to the `xlrd.sheet.Cell` class (the actual cell for `xlrd`);
+        :param `xls_text`: the actual WYSIWYG cell text, if available;
+        :param `xls_comment`: the cell comment (note), if any;
+        :param `hyperlink`: an instance of `xlrd.sheet.hyperlink`;
+        :param `rich_text`: if this cell contains text in rich text format, L{XLSGrid}
+         will do its best to render the text as rich text;
+        :param `default_width`: this is the default width of the text in 1/256
+         of the width of the zero character, using default Excel font (first FONT
+         record in the Excel file);
+        :param `default_colour`: the "magic" colour used by Excel to draw non-custom
+         border lines.
+
+        :note: If you are using version 0.7.1 or lower for `xlrd`, the *hyperlink*
+         parameter will always be ``None`` as this feature is available only in
+         `xlrd` 0.7.2 (SVN).
+
+        :note: If you are using version 0.7.1 or lower for `xlrd`, the `rich_text`
+         parameter will always be ``None`` as this feature is available only in
+         `xlrd` 0.7.2 (SVN).
+
+        :note: if Mark Hammonds' `pywin32` package is not available, the `xls_text`
+         parameter will almost surely not be the WYSIWYG representation of the cell
+         text.
+
+        :note: If Mark Hammonds' `pywin32` package is not available, the `xls_comment`
+         parameter will always be ``None``.
+        """
+
+        cvalue = cell.value
+        self.raw_value = cvalue
+
+        if rich_text:
+            self.text = XLSRichText(book, cell, xf_index, xls_text, hyperlink, rich_text, default_width)
+        else:
+            self.text = XLSText(book, cell, xf_index, xls_text, hyperlink, default_width)
+
+        self.background = XLSBackground(book, xf_index)
+
+        XFClass = book.xf_list[xf_index]
+        border = XFClass.border
+
+        self.borders = XLSBorderFactory(book, border, default_colour)
+
+        if xls_comment:
+            self.comment = XLSComment(xls_comment)
+
+        self.attr = None
+
+
+    def GetAttr(self):
+        """
+        Returns the attribute to use for this specific cell.
+
+        :returns: an instance of `wx.grid.GridCellAttr`.
+        """
+
+        if self.attr is not None:
+            self.attr.IncRef()
+            return self.attr
+
+        attr = gridlib.GridCellAttr()
+
+        attr.SetRenderer(XLSRenderer(self))
+
+        attr.SetSize(*self.size)
+        attr.SetOverflow(True)
+        self.attr = attr
+        self.attr.IncRef()
+
+        return self.attr
+
+
+    def GetValue(self):
+        """ Returns the actual WYSIWYG representation of the cell value. """
+
+        return self.text.GetValue()
+
+
+    def SetValue(self, value):
+        """
+        Sets the actual WYSIWYG representation of the cell value.
+
+        :param `value`: the current text value to insert in the cell.
+
+        :note: This method is currently unused as everything is handled inside the
+         L{XLSText} class.
+
+        :see: L{GetValue}
+        """
+
+        self.value = value
+
+
+    def SetCellSize(self, rows, cols):
+        """
+        Sets the size of the cell.
+
+        Specifying a value of more than 1 in `rows` or `cols` will make the cell
+        at (`row`, `col`) span the block of the specified size, covering the other
+        cells which would be normally shown in it. Passing 1 for both arguments
+        resets the cell to normal appearance.
+
+        :param `rows`: number of rows to be occupied by this cell, must be >= 1;
+        :param `cols`: number of columns to be occupied by this cell, must be >= 1.
+        """
+
+        self.size = (rows, cols)
+
+
+    def GetComment(self):
+        """
+        Returns the cell comment, if any.
+
+        :returns: an instance of L{XLSComment}.
+
+        :note: If Mark Hammonds' `pywin32` package is not available, this method
+         always returns ``None``.
+        """
+
+        return self.comment
+
+
+class XLSRenderer(gridlib.PyGridCellRenderer):
+    """
+    This class is responsible for actually drawing the cell in the grid.
+
+    """
+
+    def __init__(self, cell):
+        """
+        Default class constructor.
+
+        :param `cell`: an instance of L{XLSCell}.
+        """
+
+        gridlib.PyGridCellRenderer.__init__(self)
+        self.cell = cell
+
+
+    def Draw(self, grid, attr, dc, rect, row, col, isSelected):
+        """
+        Draw the given cell on the provided `dc` inside the given rectangle using
+        default or selected state corresponding to the `isSelected` value.
+
+        :param `grid`: an instance of `wx.grid.Grid`;
+        :param `attr`: an instance of `wx.grid.GridCellAttr`;
+        :param `dc`: an instance of `wx.DC`;
+        :param `rect`: an instance of `wx.Rect`, representing the cell rectangle;
+        :param `row`: the row in which this cell lives;
+        :param `col`: the column in which this cell lives;
+        :param `isSelected`: ``True`` if the cell is selected, ``False`` otherwise.
+        """
+
+        # clear the background
+        dc.SetBackgroundMode(wx.SOLID)
+
+        cell = self.cell
+
+        cell.background.Draw(dc, rect)
+
+        if cell.borders:
+            cell.borders.Draw(dc, rect)
+
+        cell.text.Draw(dc, rect)
+
+        if cell.comment:
+            cell.comment.Draw(dc, rect)
+
+        if isSelected:
+
+            gdc = wx.GCDC(dc)
+
+            sys_colour = wx.SystemSettings.GetColour(wx.SYS_COLOUR_HIGHLIGHT)
+            brush_colour = wx.Colour(sys_colour.Red(), sys_colour.Green(), sys_colour.Blue(), 90)
+
+            gdc.SetBrush(wx.Brush(brush_colour))
+            gdc.SetPen(wx.TRANSPARENT_PEN)
+
+            gdc.DrawRectangleRect(rect)
+
+
+class XLSTable(gridlib.PyGridTableBase):
+    """
+    The almost abstract base class for grid tables.
+
+    A grid table is responsible for storing the grid data and, indirectly, grid
+    cell attributes. The data can be stored in the way most convenient for the
+    application but has to be provided in string form to `wx.grid.Grid`.
+    """
+
+    def __init__(self, grid, cells, rows, cols):
+        """
+        Default class constructor.
+
+        :param `grid`: an instance of `wx.grid.Grid`;
+        :param `cells`: a Python dictionary. For every key `(row, col)`, the
+         corresponding value is an instance of L{XLSCell};
+        :param `rows`: the number of rows in the table;
+        :param `cols`: the number of columns in the table.
+        """
+
+        # The base class must be initialized *first*
+        gridlib.PyGridTableBase.__init__(self)
+
+        self.cells = cells
+        self.dimens = (rows, cols)
+
+
+    def GetNumberCols(self):
+        """ Returns the number of columns in the table. """
+
+        return self.dimens[1]
+
+
+    def GetNumberRows(self):
+        """ Returns the number of rows in the table. """
+
+        return self.dimens[0]
+
+
+    def GetValue(self, row, col):
+        """
+        Returns the cell content for the specified row and column.
+
+        :param `row`: the row in which this cell lives;
+        :param `col`: the column in which this cell lives.
+        """
+
+        cell = self.cells[(row, col)]
+        return cell.GetValue()
+
+
+    def SetValue(self, row, col, value):
+        """
+        sets the cell content for the specified row and column.
+
+        :param `row`: the row in which this cell lives;
+        :param `col`: the column in which this cell lives;
+        :param `value`: the new value to assign to the specified cell.
+        """
+
+        cell = self.cells[(row, col)]
+        cell.SetValue(value)
+
+
+    def GetAttr(self, row, col, kind):
+        """
+        Return the attribute for the given cell.
+
+        :param `row`: the row in which this cell lives;
+        :param `col`: the column in which this cell lives;
+        :param `kind`: the kind of the attribute to return.
+        """
+
+        cell = self.cells[(row, col)]
+        return cell.GetAttr()
+
+
+    def GetRawValue(self, row, col):
+        """
+        Returns the "raw" value for the cell content.
+
+        :param `row`: the row in which this cell lives;
+        :param `col`: the column in which this cell lives.
+        """
+
+        cell = self.cells[(row, col)]
+        return cell.raw_value
+
+
+class XLSGrid(gridlib.Grid):
+    """
+    L{XLSGrid} is a class based on `wx.grid.Grid` that can be used to faithfully
+    reproduce the appearance of a Microsoft Excel spreadsheet (one worksheet per
+    every instance of L{XLSGrid}).
+
+    L{XLSGrid} is a completely owner-drawn control, and it relies on the power of
+    `wx.grid.PyGridTableBase` and `wx.grid.PyGridCellRenderer` to draw the cell
+    content. For this reasons (and for some others, see the TODOs section), it will
+    work efficiently only for relatively small Excel files.
+    """
+
+    def __init__(self, parent):
+        """
+        Default class constructor.
+
+        :param `parent`: the grid parent window. Must not be ``None``.
+        """
+
+        gridlib.Grid.__init__(self, parent)
+
+        self.SetMargins(0, 0)
+        self.SetDefaultCellBackgroundColour(parent.GetBackgroundColour())
+        self.SetDefaultCellOverflow(True)
+
+        self.tip_window = None
+        self.tip_shown = False
+
+
+    def DestroyTip(self):
+        """
+        If a comment window or a tooltip over a hyperlink have been created, this
+        method destroys them.
+        """
+
+        if self.tip_window:
+            try:
+                self.tip_window.GetTipWindow().Destroy()
+            except wx.PyDeadObjectError:
+                pass
+
+            del self.tip_window
+            self.tip_window = None
+
+        if self.tip_shown:
+            self.GetGridWindow().SetToolTipString("")
+            self.GetGridWindow().SetCursor(wx.NullCursor)
+            self.tip_shown = False
+
+
+    def InstallGridHint(self):
+        """
+        Auxiliary method used to bind a ``wx.EVT_MOTION`` event to L{XLSGrid}.
+        """
+
+        self.prev_rowcol = [None, None]
+
+        def OnMouseMotion(event):
+            """
+            Handles a the ``wx.EVT_MOTION`` events for L{XLSGrid}.
+
+            :param `event`: a `wx.MouseEvent` event to be processed.
+            """
+
+            # evt.GetRow() and evt.GetCol() would be nice to have here,
+            # but as this is a mouse event, not a grid event, they are not
+            # available and we need to compute them by hand.
+            position = event.GetPosition()
+            x, y = self.CalcUnscrolledPosition(position)
+            row = self.YToRow(y)
+            col = self.XToCol(x)
+
+            if [row, col] != self.prev_rowcol and row >= 0 and col >= 0:
+
+                self.prev_rowcol[:] = [row, col]
+                self.DestroyTip()
+                cell = self.cells[(row, col)]
+                rect = self.CellToRect(row, col)
+                comment = cell.GetComment()
+
+                window = self.GetGridWindow()
+                if cell.text.IsHyperLink():
+                    window.SetCursor(wx.StockCursor(wx.CURSOR_HAND))
+                    window.SetToolTipString(cell.text.tooltip)
+                    self.tip_shown = True
+                    if not comment:
+                        return
+
+                if comment:
+                    self.tip_window = TransientPopup(window, comment, wx.GetMousePosition())
+                    event.Skip()
+
+        self.GetGridWindow().Bind(wx.EVT_MOTION, OnMouseMotion)
+
+
+    def PopulateGrid(self, book, sheet, display_texts, comments):
+        """
+        This is the main method of this class, and it is used to actually create
+        the cells, size the columns and rows, merging cells, etc...
+
+        :param `book`: an instance of the `xlrd.Book` class;
+        :param `sheet`: an instance of the `xlrd.sheet` class;
+        :param `display_texts`: if Mark Hammonds' `pywin32` package is available,
+         this is the WYSIWYG cell content for all the cells in the Excel worksheet;
+        :param `comments`: if Mark Hammonds' `pywin32` package is available,
+         this is a nested list of cell comments (notes) for all the cells in the
+         Excel worksheet.
+        """
+
+        self.BeginBatch()
+
+        nrows = sheet.nrows
+        ncols = sheet.ncols
+
+        default_width, default_height = self.GetDefaultFontData(book)
+        default_colour = self.GetGridLineColour()
+
+        hyperlinks, rich_text_list = {}, {}
+        if hasattr(sheet, "hyperlink_map"):
+            # New in xlrd version 0.7.2 from SVN
+            hyperlinks = sheet.hyperlink_map
+
+        if hasattr(sheet, "rich_text_runlist_map"):
+            # New in xlrd version 0.7.2 from SVN
+            rich_text_list = sheet.rich_text_runlist_map
+
+        self.cells = {}
+
+        for i in xrange(nrows):
+
+            for j in xrange(ncols):
+
+                hyperlink = rich_text = None
+
+                if (i, j) in hyperlinks:
+                    hyperlink = hyperlinks[(i, j)]
+                if (i, j) in rich_text_list:
+                    rich_text = rich_text_list[(i, j)]
+
+                self.FormatCell(book, sheet, i, j, display_texts, comments, hyperlink, rich_text, default_width, default_colour)
+
+        self.table = XLSTable(self, self.cells, nrows, ncols)
+        self.SetTable(self.table)
+
+        row_height = sheet.default_row_height
+        col_width = sheet.defcolwidth
+
+        for i in xrange(nrows):
+            if i in sheet.rowinfo_map:
+                current = sheet.rowinfo_map[i].height
+            else:
+                current = sheet.default_row_height
+
+            row_height = int(round(float(default_height)*current/256.0))
+            self.SetRowSize(i, row_height)
+
+        for j in xrange(ncols):
+            if j in sheet.colinfo_map:
+                current = sheet.colinfo_map[j].width
+            else:
+                current = sheet.defcolwidth
+
+            col_width = int(round(float(default_width)*current/256.0))
+            self.SetColSize(j, col_width)
+
+        for merged in sheet.merged_cells:
+            rlo, rhi, clo, chi = merged
+            if rlo >= 0 and rlo < len(self.cells) and clo >= 0:
+                self.cells[(rlo, clo)].SetCellSize(rhi-rlo, chi-clo)
+
+        self.EnableEditing(False)
+        self.EnableGridLines(False)
+        self.EndBatch()
+        self.ForceRefresh()
+        self.InstallGridHint()
+
+
+    def FormatCell(self, book, sheet, row, col, display_texts, comments, hyperlink, rich_text, default_width, default_colour):
+        """
+        Processes the creation of a single cell (an instance of L{XLSCell}).
+
+        :param `book`: an instance of the `xlrd.Book` class;
+        :param `sheet`: an instance of the `xlrd.sheet` class;
+        :param `row`: the row in which this cell lives;
+        :param `col`: the column in which this cell lives;
+        :param `display_texts`: if Mark Hammonds' `pywin32` package is available,
+         this is the WYSIWYG cell content for all the cells in the Excel worksheet;
+        :param `comments`: if Mark Hammonds' `pywin32` package is available,
+         this is a nested list of cell comments (notes) for all the cells in the
+         Excel worksheet;
+        :param `hyperlink`: if this cell contains a hyperlink, it will be displayed
+         accordingly;
+        :param `rich_text`: if this cell contains text in rich text format, L{XLSGrid}
+         will do its best to render the text as rich text;
+        :param `default_width`: this is the default width of the text in 1/256
+         of the width of the zero character, using default Excel font (first FONT
+         record in the Excel file);
+        :param `default_colour`: the "magic" colour used by Excel to draw non-custom
+         border lines.
+
+        :note: If you are using version 0.7.1 or lower for `xlrd`, the *hyperlink*
+         parameter will always be ``None`` as this feature is available only in
+         `xlrd` 0.7.2 (SVN).
+
+        :note: If you are using version 0.7.1 or lower for `xlrd`, the `rich_text`
+         parameter will always be ``None`` as this feature is available only in
+         `xlrd` 0.7.2 (SVN).
+
+        :note: If Mark Hammonds' `pywin32` package is not available, the `display_texts`
+         and `comments` parameter will be two empty nested lists.
+        """
+
+        cell = sheet.cell(row, col)
+
+        xf_index = sheet.cell_xf_index(row, col)
+        xls_text, xls_comment = display_texts[row][col], comments[row][col]
+
+        gridCell = XLSCell(book, cell, xf_index, xls_text, xls_comment, hyperlink, rich_text, default_width, default_colour)
+
+        self.cells[(row, col)] = gridCell
+
+
+    def GetDefaultFontData(self, book):
+        """
+        Returns suitable width and height (in pixels) starting from Excel's own
+        measurements (in characters, whatever that means).
+
+        :param `book`: an instance of the `xlrd.Book` class.
+
+        :returns: a `default_width` and `default_height` in pixels, based on the
+         default width of the text in 1/256 of the width of the zero character,
+         using default Excel font (first FONT record in the Excel file).
+        """
+
+        font = book.font_list[0]
+        style, bold, underline = wx.FONTSTYLE_NORMAL, wx.NORMAL, False
+
+        if font.italic:
+            style = wx.FONTSTYLE_ITALIC
+        if font.underline_type > 0:
+            underline = True
+        if font.weight > 600:
+            bold = wx.BOLD
+
+        family = XF_FONT_FAMILY[font.family]
+        name = font.name
+        size = int(font.height/20.0)
+
+        dc = wx.ClientDC(self)
+        font = wx.Font(size, family, style, bold, underline, name.encode())
+        dc.SetFont(font)
+        width, height, descent, leading = dc.GetFullTextExtent("0", font)
+
+        return width, height + descent - leading
+
+
+class TransientPopup(STT.SuperToolTip):
+    """
+    This is a sublass of L{SuperToolTip} and it is used to display a
+    "comment-window" on the cells containing a comment (a note).
+
+    :note: If Mark Hammonds' `pywin32` package is not available, this class is
+     never invoked.
+    """
+
+    def __init__(self, grid_window, comment, position):
+        """
+        Default class constructor.
+
+        :param `grid_window`: the actual window representing the grid;
+        :param `comment`: an instance of L{XLSComment}, containing the
+         text for this comment;
+        :param `position`: the position at which we pop up the comment
+         window (currently unused).
+        """
+
+        STT.SuperToolTip.__init__(self, grid_window)
+
+        xls_comment = comment.comment
+
+        split = xls_comment.split(":")
+        header, rest = split[0], split[1:]
+        rest = ":".join(rest)
+
+        dc = wx.ClientDC(grid_window)
+        rest = wordwrap(rest, 400, dc)
+
+        self.SetHeader(header)
+        self.SetMessage(rest)
+        self.SetTarget(grid_window)
+        self.SetDrawHeaderLine(True)
+
+        self.SetStartDelay(100000)
+        self.SetEndDelay(100000)
+        self.ApplyStyle("Office 2007 Blue")
+
+        self.SetDropShadow(True)
+        self.DoShowNow()
+
+        grid_window.SetFocus()
+

\ No newline at end of file

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • xlsgrid »
  • SVN Revision 68988 For xlsgrid


SVN Revision 69294 For xlsgrid

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • xlsgrid »
  • SVN Revision 69294 For xlsgrid

svn SVN Revision 69294 For xlsgrid

This file contains the SVN revision history for xlsgrid, at revision 69294.

Available information include commit date, the name of the committer, the file size, the SVN log messages and a diff from the previous version (if available).

File Information

  • Commit Date: 27-Aug-2011 17:11:41 UTC
  • Committer: AG
  • File Size: 144929 byte(s)

Log Messages

The following log message was entered by the committer:

ModernDockArt for AUI: fixed an unreferenced link to winxptheme.

Diff To Previous Version (68988)

Version SVN diff:

--- wxPython/3rdParty/AGW/agw/xlsgrid.py    2011/09/03 04:44:14     68988
+++ wxPython/3rdParty/AGW/agw/xlsgrid.py    2011/10/02 19:32:45     69294
@@ -1,3 +1,2093 @@
+<<<<<<< .mine
+# --------------------------------------------------------------------------------- #
+# XLSGRID wxPython IMPLEMENTATION
+#
+# Andrea Gavana @ 08 Aug 2011
+# Latest Revision: 17 Aug 2011, 15.00 GMT
+#
+#
+# TODO List
+#
+# Current todo list:
+#
+# 1. There is currently no support for rich text, i.e. strings containing partial
+#    bold, italic and underlined text, change of font inside a string, etc... xlrd
+#    supports those (from version 0.7.2 in SVN) but there is no easy way to handle
+#    changing fonts/colours/formatting in the same string in wxPython;
+#
+# 2. XLSGrid is sufficiently efficient and fast for reasonably small Excel files.
+#    There might be some improvement to be made in the code to make it work with
+#    bigger files and in a faster way;
+#
+# 3. There is currently no support for strikethrough fonts, although xlrd correctly
+#    reports this format. The issue is a bug in wxWidgets itself which doesn't
+#    allow the creation of strikethrough fonts (http://trac.wxwidgets.org/ticket/9907).
+#
+# 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
+# --------------------------------------------------------------------------------- #
+
+
+"""
+L{XLSGrid} is a class based on `wx.grid.Grid` that can be used to faithfully
+reproduce the appearance of a Microsoft Excel spreadsheet (one worksheet per
+every instance of L{XLSGrid}).
+
+
+Description
+===========
+
+L{XLSGrid} is a class based on `wx.grid.Grid` that can be used to faithfully
+reproduce the appearance of a Microsoft Excel spreadsheet (one worksheet per
+every instance of L{XLSGrid}).
+
+L{XLSGrid} is a completely owner-drawn control, and it relies on the power of
+`wx.grid.PyGridTableBase` and `wx.grid.PyGridCellRenderer` to draw the cell
+content. For this reasons (and for some others, see the TODOs section), it will
+work efficiently only for relatively small Excel files.
+
+:note: L{XLSGrid} **requires** the `xlrd` package from:
+
+ http://pypi.python.org/pypi/xlrd
+
+ Minimum version requirement for `xlrd` is 0.7.1. If you wish to have
+ support for hyperlinks inside cells and rich text content, you need the
+ SVN version of `xlrd`.
+
+:note: On Windows, it is **strongly** recommended to install Mark Hammonds'
+ `pywin32` package:
+
+ http://sourceforge.net/projects/pywin32/
+
+ This will allow you to perfectly reproduce the appearance of the Excel
+ worksheet in your instance of L{XLSGrid}.
+
+:warning: If Mark Hammonds' `pywin32` package is not available, the formatting
+ capabilities of L{XLSGrid} are severely limited; for instance, you won't
+ probably get the exact WYSIWYG between the Excel spreadsheet and L{XLSGrid}.
+
+:warning: L{XLSGrid} can only read Excel `.xls` files, not the newer versions
+ `.xlsx` generated by Office 2007/2010. If you have a `.xlsx` file, you will
+ need to save it in 1997-2003 Office compatibility mode.
+
+
+Currently this class provides a read-only subclass of `wx.grid.Grid`, with
+the following formatting features already implemented:
+
+* Cell background: support for any cell background colour and fill pattern
+  (hatching) in the Excel default set. There currently is no support for
+  gradient shading inside a cell as `xlrd` doesn't report this information.
+
+* Cell borders: support for all the border types and colours exposed by Excel
+  (left, top, bottom, right and diagonal borders, thin, double, thick, ect...
+  line styles).
+
+* Cell text: support for all kind of fonts (except strikethrough, but this is
+  a bug in wxWidgets), and font colours. As a subset of text/font capabilities,
+  L{XLSGrid} supports the following features found in Excel:
+
+  - Horizontal alignment: left, right, centered, left-indented;
+  - Vertical alignment: left, right, centered;
+  - Text direction: left-to-right or right-to-left;
+  - Text-wrapping: wrapping long texts inside a grid cell;
+  - Shrink-to-fit: text font is reduced until the text can fit in a one-line
+    inside the grid cell;
+  - Text rotation: text can be rotated from +90 to -90 degrees.
+
+* Cell rich text (new in version 0.2): support for strings containing partial
+  bold, italic and underlined text, change of font inside a string etc...
+  Cells with rich text content can not be multi-line and they will not honour
+  the `shrink-to-fit` and `wrapping` settings.
+
+* Cell text appearance: if you are using Mark Hammonds' `pywin32` package, the
+  text displayed in the L{XLSGrid} cells has exactly the same appearance as in
+  the Excel spreadsheet.
+
+* Cell comments (notes): if you are using Mark Hammonds' `pywin32` package,
+  cell comments (notes) are extracted and you will see a small red triangle at
+  the top-right corner of any cell containing a comment. Hovering with the
+  mouse on that cell will pop-up a "comment-window" displaying the comment
+  text (the comment window is based on `wx.lib.agw.supertooltip`).
+
+* Cell hyperlinks: starting from version 0.7.2 (SVN), `xlrd` is capable of
+  extracting hyperlinks from Excel cells. This will be appropriately displayed
+  in L{XLSGrid} with a cursor changing and a tooltip on that cell.
+
+* Cell merging: merged cells in the Excel spreadsheet will be correctly handled
+  by L{XLSGrid}.
+
+* Columns and rows sizes: L{XLSGrid} calculates the correct rows and columns
+  sizes based on the Excel reported values in characters. The calculations are
+  based on the default width of the text in 1/256 of the width of the zero
+  character, using default Excel font (first FONT record in the Excel file).
+
+
+And a lot more. Check the demo for an almost complete review of the functionalities.
+
+
+Usage
+=====
+
+Sample usage::
+
+    import wx
+    import xlrd
+    import os
+
+    import xlsgrid as XG
+
+    class MyFrame(wx.Frame):
+
+        def __init__(self):
+
+            wx.Frame.__init__(self, parent, -1, "XLSGrid Demo", size=(1000, 800))
+
+            filename = os.path.join(os.getcwd(), "Excel", "Example_1.xls")
+            sheetname = "Example_1"
+
+            book = xlrd.open_workbook(filename, formatting_info=1)
+
+            sheet = book.sheet_by_name(sheetname)
+            rows, cols = sheet.nrows, sheet.ncols
+
+            comments, texts = XG.ReadExcelCOM(filename, sheetname, rows, cols)
+
+            xls_grid = XG.XLSGrid(self)
+            xls_grid.PopulateGrid(book, sheet, texts, comments)
+
+
+    # our normal wxApp-derived class, as usual
+
+    app = wx.PySimpleApp()
+
+    frame = MyFrame(None)
+    app.SetTopWindow(frame)
+    frame.Show()
+
+    app.MainLoop()
+
+
+:note: Please note that you **have to** pass the keyword `formatting_info` to
+ the method `xlrd.open_workbook` to obtain the cell formatting.
+
+
+TODOs
+=====
+
+1. L{XLSGrid} is sufficiently efficient and fast for reasonably small Excel files.
+   There might be some improvement to be made in the code to make it work with
+   bigger files and in a faster way;
+2. `wx.grid.Grid` seems to completely redraw itself at every resize event, even
+   if the cell content has not changed and it has not been damaged (this seems
+   to be fixed in wxPython 2.9.2.1);
+3. There is currently no support for strikethrough fonts, although `xlrd` correctly
+   reports this format. The issue is a bug in wxWidgets itself which doesn't
+   allow the creation of strikethrough fonts (http://trac.wxwidgets.org/ticket/9907).
+
+
+Supported Platforms
+===================
+
+L{XLSGrid} has been tested on the following platforms:
+  * Windows (Windows Vista and 7);
+
+
+Window Styles
+=============
+
+`No particular window styles are available for this class.`
+
+
+Events Processing
+=================
+
+`No custom events are available for this class.`
+
+
+License And Version
+===================
+
+L{XLSGrid} is distributed under the wxPython license.
+
+Latest Revision: Andrea Gavana @ 17 Aug 2011, 15.00 GMT
+
+Version 0.3
+
+"""
+
+# Version Info
+__version__ = "0.3"
+
+# Start the imports
+import wx
+import os
+
+try:
+    import xlrd
+except ImportError:
+    pass
+
+import datetime
+import string
+
+import wx.grid as gridlib
+
+from wx.lib.embeddedimage import PyEmbeddedImage
+from wx.lib.wordwrap import wordwrap
+
+import supertooltip as STT
+
+from math import pi, sin, cos
+from operator import attrgetter
+
+_hasWin32 = False
+
+if wx.Platform == "__WXMSW__":
+    try:
+        from win32com.client import Dispatch
+        import pywintypes
+        _hasWin32 = True
+    except ImportError:
+        pass
+
+
+#----------------------------------------------------------------------
+# Constants used to translate xlrd stuff into wxPython stuff
+#----------------------------------------------------------------------
+
+BOTTOM = wx.BOTTOM
+TOP = wx.TOP
+LEFT = wx.LEFT
+RIGHT = wx.RIGHT
+DIAGONAL = 2 << 7
+
+XF_BORDER_STYLES = {"bottom": BOTTOM, "left": LEFT, "right": RIGHT,
+                    "top": TOP, "diag": DIAGONAL}
+
+HORIZONTAL_ALIGNMENTS = {0: 0, 1: 0, 2: wx.ALIGN_CENTER_HORIZONTAL, 3: wx.ALIGN_RIGHT}
+VERTICAL_ALIGNMENTS   = {0: 0, 1: wx.ALIGN_CENTER_VERTICAL, 2: wx.ALIGN_BOTTOM,
+                         3: wx.ALIGN_CENTER_VERTICAL, 4:wx.ALIGN_CENTER_VERTICAL}
+
+NO_LINE = 0x0
+THIN = 0x1
+MEDIUM = 0x2
+DASHED = 0x3
+DOTTED = 0x4
+THICK = 0x5
+DOUBLE = 0x6
+HAIR = 0x7
+MEDIUM_DASHED = 0x8
+THIN_DASH_DOTTED = 0x9
+MEDIUM_DASH_DOTTED = 0xA
+THIN_DASH_DOT_DOTTED = 0xB
+MEDIUM_DASH_DOT_DOTTED = 0xC
+SLANTED_MEDIUM_DASH_DOTTED = 0xD
+
+XF_PEN_STYLES = {NO_LINE: (0, None), THIN: (1, wx.SOLID), MEDIUM: (2, wx.SOLID),
+                 DASHED: (1, wx.SHORT_DASH), DOTTED: (1, wx.DOT),
+                 THICK: (3, wx.SOLID), DOUBLE: (1, wx.SOLID), HAIR: (1, wx.DOT),
+                 MEDIUM_DASHED: (2, wx.LONG_DASH), THIN_DASH_DOTTED: (1, wx.DOT_DASH),
+                 MEDIUM_DASH_DOTTED: (2, wx.DOT_DASH), THIN_DASH_DOT_DOTTED: (1, wx.DOT_DASH),
+                 MEDIUM_DASH_DOT_DOTTED: (2, wx.DOT_DASH),
+                 SLANTED_MEDIUM_DASH_DOTTED: (2, wx.DOT_DASH)
+                 }
+
+XF_FONT_FAMILY = {0: wx.SWISS, 1: wx.ROMAN, 2: wx.SWISS,
+                  3: wx.MODERN, 4: wx.SCRIPT, 5: wx.DECORATIVE}
+
+# Unicode ordinals for Hebrew, Arabic and Syriac
+# I don't know if there are other RTL languages
+RTL_UNICODE = range(1424, 1872)
+
+# To guess text direction we exclude digits and punctuation
+USELESS_CHARS = string.punctuation + string.digits + " "
+
+
+#----------------------------------------------------------------------
+# Images used to draw the hatching on Excel cells background
+#----------------------------------------------------------------------
+
+_xls_background_01 = PyEmbeddedImage(
+    "iVBORw0KGgoAAAANSUhEUgAAAAQAAAAECAIAAAAmkwkpAAAAA3NCSVQICAjb4U/gAAAADElE"
+    "QVQImWNgIB0AAAA0AAEjQ4N1AAAAAElFTkSuQmCC")
+
+#----------------------------------------------------------------------
+_xls_background_02 = PyEmbeddedImage(
+    "iVBORw0KGgoAAAANSUhEUgAAAAQAAAAECAIAAAAmkwkpAAAAA3NCSVQICAjb4U/gAAAAFklE"
+    "QVQImWNgYGD4//8/lESwIAC7DABt4hfpI2a12wAAAABJRU5ErkJggg==")
+
+#----------------------------------------------------------------------
+_xls_background_03 = PyEmbeddedImage(
+    "iVBORw0KGgoAAAANSUhEUgAAAAQAAAAECAIAAAAmkwkpAAAAA3NCSVQICAjb4U/gAAAAE0lE"
+    "QVQImWP4//8/AxqACuGUAQBI+Qv1NTPP3AAAAABJRU5ErkJggg==")
+
+#----------------------------------------------------------------------
+_xls_background_04 = PyEmbeddedImage(
+    "iVBORw0KGgoAAAANSUhEUgAAAAQAAAAECAIAAAAmkwkpAAAAA3NCSVQICAjb4U/gAAAAH0lE"
+    "QVQImXXJsQ0AIAAEIc79d34LazsSwjbgPFXoOxdcCQwBh7OgqgAAAABJRU5ErkJggg==")
+
+#----------------------------------------------------------------------
+_xls_background_05 = PyEmbeddedImage(
+    "iVBORw0KGgoAAAANSUhEUgAAAAQAAAAECAIAAAAmkwkpAAAAA3NCSVQICAjb4U/gAAAAFUlE"
+    "QVQImWNgwAUY////D+cwIcsAAEggAwHHgMubAAAAAElFTkSuQmCC")
+
+#----------------------------------------------------------------------
+_xls_background_06 = PyEmbeddedImage(
+    "iVBORw0KGgoAAAANSUhEUgAAAAQAAAAECAIAAAAmkwkpAAAAA3NCSVQICAjb4U/gAAAAG0lE"
+    "QVQImWNkYGBgYGD4//8/AwMDEwMSwM0BAISAAwUnufp7AAAAAElFTkSuQmCC")
+
+#----------------------------------------------------------------------
+_xls_background_07 = PyEmbeddedImage(
+    "iVBORw0KGgoAAAANSUhEUgAAAAQAAAAECAIAAAAmkwkpAAAAA3NCSVQICAjb4U/gAAAAHklE"
+    "QVQImWNkYGBgYGD4//8/EgVh/P//H86HikH4APOCFO3yiGicAAAAAElFTkSuQmCC")
+
+#----------------------------------------------------------------------
+_xls_background_08 = PyEmbeddedImage(
+    "iVBORw0KGgoAAAANSUhEUgAAAAQAAAAECAIAAAAmkwkpAAAAA3NCSVQICAjb4U/gAAAAHUlE"
+    "QVQImWP4////////GSAAzvr//z8jmhADXCUAQSkU7eggG3gAAAAASUVORK5CYII=")
+
+#----------------------------------------------------------------------
+_xls_background_09 = PyEmbeddedImage(
+    "iVBORw0KGgoAAAANSUhEUgAAAAQAAAAECAIAAAAmkwkpAAAAA3NCSVQICAjb4U/gAAAAIElE"
+    "QVQImWNkYGBgYGD4//8/AwMDEwMy+P//P0QYXQYACtQI/cTE6U0AAAAASUVORK5CYII=")
+
+#----------------------------------------------------------------------
+_xls_background_10 = PyEmbeddedImage(
+    "iVBORw0KGgoAAAANSUhEUgAAAAQAAAAECAIAAAAmkwkpAAAAA3NCSVQICAjb4U/gAAAAG0lE"
+    "QVQImW3IsQ0AAAjAIPz/6LobGRmgclVfswpsCPmQczsGAAAAAElFTkSuQmCC")
+
+#----------------------------------------------------------------------
+_xls_background_11 = PyEmbeddedImage(
+    "iVBORw0KGgoAAAANSUhEUgAAAAQAAAAECAIAAAAmkwkpAAAAA3NCSVQICAjb4U/gAAAAFklE"
+    "QVQImWNgQAKM////h3OYkGVQOABvOgMD4NUKkwAAAABJRU5ErkJggg==")
+
+#----------------------------------------------------------------------
+_xls_background_12 = PyEmbeddedImage(
+    "iVBORw0KGgoAAAANSUhEUgAAAAQAAAAECAIAAAAmkwkpAAAAA3NCSVQICAjb4U/gAAAAG0lE"
+    "QVQImWNkYGD4//8/AwMDAwMDEwMSwM0BAI13AwWY+Mx+AAAAAElFTkSuQmCC")
+
+#----------------------------------------------------------------------
+_xls_background_13 = PyEmbeddedImage(
+    "iVBORw0KGgoAAAANSUhEUgAAAAQAAAAECAIAAAAmkwkpAAAAA3NCSVQICAjb4U/gAAAAI0lE"
+    "QVQImT3KsQ0AMAyAMMj/P9MhUUcLBCoAmEo9bFn7H/UBXEwMBN75abEAAAAASUVORK5CYII=")
+
+#----------------------------------------------------------------------
+_xls_background_14 = PyEmbeddedImage(
+    "iVBORw0KGgoAAAANSUhEUgAAAAQAAAAECAIAAAAmkwkpAAAAA3NCSVQICAjb4U/gAAAAIElE"
+    "QVQImT3KoQEAAAwCINz/P7tmI5C2QJKb2t6EYPMBOOUMBIWcMEIAAAAASUVORK5CYII=")
+
+#----------------------------------------------------------------------
+_xls_background_15 = PyEmbeddedImage(
+    "iVBORw0KGgoAAAANSUhEUgAAAAQAAAAECAIAAAAmkwkpAAAAA3NCSVQICAjb4U/gAAAAGUlE"
+    "QVQImWNgQAKMDAwM////h3CYkGVQOABmQwMDJpgq9gAAAABJRU5ErkJggg==")
+
+#----------------------------------------------------------------------
+_xls_background_16 = PyEmbeddedImage(
+    "iVBORw0KGgoAAAANSUhEUgAAAAQAAAAECAIAAAAmkwkpAAAAA3NCSVQICAjb4U/gAAAAHklE"
+    "QVQImWNgYGD4//8/lISzIAwEnxEqwMDAyMgIALKwF+2ym+hoAAAAAElFTkSuQmCC")
+
+#----------------------------------------------------------------------
+_xls_background_17 = PyEmbeddedImage(
+    "iVBORw0KGgoAAAANSUhEUgAAAAQAAAAECAIAAAAmkwkpAAAAA3NCSVQICAjb4U/gAAAAIklE"
+    "QVQImWNkYGD4//8/AwMDAwMDI5zFwMDABBVjZESXAQAc+AkAQ4bzDAAAAABJRU5ErkJggg==")
+
+#----------------------------------------------------------------------
+_xls_background_18 = PyEmbeddedImage(
+    "iVBORw0KGgoAAAANSUhEUgAAAAgAAAAECAIAAAA8r+mnAAAAA3NCSVQICAjb4U/gAAAAH0lE"
+    "QVQImWNkYGD4//8/AwZgxCrKwMDAhKKKkZGwDgA83QkAy10JvwAAAABJRU5ErkJggg==")
+
+#----------------------------------------------------------------------
+
+
+def SplitThousands(s, tSep=',', dSep='.'):
+    """
+    Splits a general float on thousands. GIGO on general input.
+
+    :param `s`: can be a float or a string, representing a number;
+    :param `tSep`: the character to be used as thousands separator;
+    :param `dSep`: the character to be used as decimal separator.
+
+    :returns: a string properly formatted with thousands and decimal
+     separators in it.
+
+    :note: This method is used only if Mark Hammonds' `pywin32` package is
+     not available to try and format a number in an intelligent way.
+
+    :note: This code has been obtained from the public domain:
+
+     http://code.activestate.com/recipes/498181-add-thousands-separator-commas-to-formatted-number/#c14
+
+    """
+
+    if not isinstance(s, basestring):
+        s = unicode(s, "utf-8", "ignore")
+
+    cnt = 0
+    numChars = dSep + '0123456789'
+    ls = len(s)
+
+    while cnt < ls and s[cnt] not in numChars:
+        cnt += 1
+
+    lhs = s[0:cnt]
+    s = s[cnt:]
+
+    if dSep == '':
+        cnt = -1
+    else:
+        cnt = s.rfind(dSep)
+
+    if cnt > 0:
+        rhs = dSep + s[cnt+1:]
+        s = s[:cnt]
+    else:
+        rhs = ''
+
+    splt = ''
+    while s != '':
+        splt = s[-3:] + tSep + splt
+        s = s[:-3]
+
+    return lhs + splt[:-1] + rhs
+
+
+def ReadExcelCOM(filename, sheetname, rows, cols):
+    """
+    Reads and Excel spreadsheet (a single worksheet) using Mark Hammonds' `pywin32`
+    package. If this package is not available, it returns two empty nested lists.
+
+    :param `filename`: a valid Excel `.xls` filename;
+    :param `sheetname`: the worksheet name inside the Excel file (i.e., the label
+     on the workbook tab at the bottom of the workbook);
+    :param `rows`: the number of significant rows in the worksheet, as returned
+     by `xlrd`;
+    :param `cols`: the number of significant columns in the worksheet, as returned
+     by `xlrd`.
+
+    :returns: two nested lists representing the comments (notes) on every cell and
+     the WYSIWYG representation of the cell content.
+
+    :note: If Mark Hammonds' `pywin32` package is not available, this method
+     returns two empty nested lists.
+    """
+
+    comments = [["" for i in range(cols)] for j in range(rows)]
+    texts    = [[None for i in range(cols)] for j in range(rows)]
+
+    if not _hasWin32:
+        return comments, texts
+
+    workbook = Excel(filename, sheetname)
+
+    for i in xrange(1, rows+1):
+        for j in xrange(1, cols+1):
+            texts[i-1][j-1]    = workbook.GetText(i, j)
+
+    comm_range = workbook.GetCommentsRange()
+    if comm_range is not None:
+        for comm in comm_range:
+            comments[comm.Row-1][comm.Column-1] = comm.Comment.Text()
+
+    workbook.Close()
+    return comments, texts
+
+
+def FontFromFont(font):
+    """
+    Creates a copy of the input `font`.
+
+    :param `font`: an instance of `wx.Font`.
+    """
+
+    new_font = wx.Font(font.GetPointSize(), font.GetFamily(), font.GetStyle(),
+                       font.GetWeight(), font.GetUnderlined(),
+                       font.GetFaceName(), font.GetEncoding())
+
+    return new_font
+
+
+class Excel(object):
+    """
+    A simple class that holds a COM interface to Excel.
+
+    By using the `win32com` module from Mark Hammonds' `pywin32` package, we
+    can manipulate various workbook/worksheet methods inside this class.
+    """
+
+    def __init__(self, filename, sheetname):
+        """
+        Default class constructor.
+
+        :param `filename`: a valid Excel `.xls` filename;
+        :param `sheetname`: the worksheet name inside the Excel file (i.e., the label
+         on the workbook tab at the bottom of the workbook).
+        """
+
+        self.xlApp = Dispatch('Excel.Application')
+        self.filename = filename
+        self.xlBook = self.xlApp.Workbooks.Open(filename)
+        self.sheet = self.xlBook.Worksheets(sheetname)
+
+        self.xlApp.Visible = 0
+
+
+    def Close(self, save=False):
+        """
+        Closes the Excel workbook, interrupting the COM interface.
+
+        :param `save`: ``True`` to save the changes you made to the workbook,
+         ``False`` otherwise.
+        """
+
+        self.xlBook.Close(SaveChanges=save)
+        del self.xlApp
+
+
+    def GetCommentsRange(self):
+        """
+        Returns a range of cells containing comments, using the VBA API.
+
+        """
+
+        try:
+            return self.sheet.Cells.SpecialCells(-4144)
+        except pywintypes.com_error:
+            return None
+
+
+    def GetText(self, row, col):
+        """
+        Returns the WYSIWYG text contained in a cell.
+
+        :param `row`: the row in which the cell lives;
+        :param `col`: the column in which the cell lives.
+
+        :note: The `row` and `col` parameters are not real Python index, as they
+         use the Excel indexing mode (i.e., first index is 1 and not 0).
+        """
+
+        cell = self.sheet.Cells(row, col)
+
+        if cell:
+            return cell.Text
+
+
+class XLSText(object):
+    """
+    This is a class which holds information about the cell content, in terms
+    of actual cell value, font, text colour, alignment and formatting.
+    """
+
+    def __init__(self, book, cell, xf_index, display_text=None, hyperlink=None, default_width=10):
+        """
+        Default class constructor.
+
+        :param `book`: an instance of the `xlrd.Book` class;
+        :param `cell`: an instance of `xlrd.sheet.Cell` class;
+        :param `xf_index`: an index into `xlrd.Book.xf_list`, which holds a
+         reference to the `xlrd.sheet.Cell` class (the actual cell for `xlrd`);
+        :param `display_text`: if Mark Hammonds' `pywin32` package is available,
+         this is the WYSIWYG cell content;
+        :param `hyperlink`: if this cell contains a hyperlink, it will be displayed
+         accordingly;
+        :param `default_width`: this is the default width of the text in 1/256
+         of the width of the zero character, using default Excel font (first FONT
+         record in the Excel file).
+
+        :note: If you are using version 0.7.1 or lower for `xlrd`, the *hyperlink*
+         parameter will always be ``None`` as this feature is available only in
+         `xlrd` 0.7.2 (SVN).
+        """
+
+        XFClass = book.xf_list[xf_index]
+
+        font = book.font_list[XFClass.font_index]
+        self.font = self.CreateFont(font)
+
+        text_colour = book.colour_map[font.colour_index]
+        self.text_colour = self.CreateTextColour(text_colour)
+
+        if display_text is not None:
+            self.value = display_text
+        else:
+            format = book.format_map[XFClass.format_key]
+            self.CreateFormat(format, cell, book.datemode)
+
+        alignment = XFClass.alignment
+        self.CreateAlignment(alignment, default_width)
+
+        if hyperlink is not None:
+            self.SetupHyperlink(hyperlink)
+        else:
+            self.tooltip = None
+
+
+    def CreateFont(self, font):
+        """
+        Creates a suitable wxPython font starting from an Excel font.
+
+        :param `font`: an instance of `xlrd.formatting.Font` class.
+
+        :note: There is currently no support for strikethrough fonts, although
+         `xlrd` correctly reports this format. The issue is a bug in wxWidgets
+         itself which doesn't allow the creation of strikethrough fonts. See
+         (http://trac.wxwidgets.org/ticket/9907).
+        """
+
+        style, bold, underline = wx.FONTSTYLE_NORMAL, wx.NORMAL, False
+        if font.italic:
+            style = wx.FONTSTYLE_ITALIC
+        if font.underline_type > 0:
+            underline = True
+        if font.weight > 600:
+            bold = wx.BOLD
+
+        family = XF_FONT_FAMILY[font.family]
+        name = font.name
+        size = int(font.height/20.0)
+
+        if font.escapement_type > 0:
+            # subscript/superscript
+            size = int(size*0.7)
+
+        # No support for strike-through fonts in wxWidgets
+#        if font.struck_out:
+#            style = wx.FONTFLAG_DEFAULT
+#            if bold:
+#                style += wx.FONTFLAG_BOLD
+#            if underline:
+#                style += wx.FONTFLAG_UNDERLINED
+#            if font.italic:
+#                style += wx.FONTFLAG_ITALIC
+#
+#            style += wx.FONTFLAG_STRIKETHROUGH
+#            self.font = wx.FFont(size, family, style, name.encode())
+#        else:
+
+        return wx.Font(size, family, style, bold, underline, name.encode())
+
+
+    def CreateTextColour(self, text_colour):
+        """
+        Creates a suitable wxPython colour for the text starting from a `xlrd`
+        tuple representing this colour.
+
+        :param `text_colour`: a tuple representing the RGB components of the
+         colour. If `text_colour` is ``None``, use the default ``wx.SYS_COLOUR_WINDOWTEXT``.
+        """
+
+        if text_colour is not None:
+            text_colour = wx.Colour(*text_colour)
+        else:
+            text_colour = wx.SystemSettings.GetColour(wx.SYS_COLOUR_WINDOWTEXT)
+
+        return text_colour
+
+
+    def CreateAlignment(self, alignment, default_width):
+        """
+        Creates a suitable wxPython alignment flag for the text starting from a
+        `xlrd` class representing this alignment.
+
+        :param `alignment`: an instance of `xlrd.formatting.XFAlignment` class;
+        :param `default_width`: this is the default width of the text in 1/256
+         of the width of the zero character, using default Excel font (first FONT
+         record in the Excel file).
+        """
+
+        hor_align, vert_align = alignment.hor_align, alignment.vert_align
+        self.horizontal_alignment = HORIZONTAL_ALIGNMENTS[hor_align]
+        self.vertical_alignment = VERTICAL_ALIGNMENTS[vert_align]
+
+        self.indent_level = alignment.indent_level
+        self.shrink_to_fit = alignment.shrink_to_fit
+        self.text_wrapped = alignment.text_wrapped
+
+        text_direction = 1
+
+        if alignment.text_direction == 0:
+            for char in self.value:
+                if char not in USELESS_CHARS:
+                    if ord(char) in RTL_UNICODE:
+                        text_direction = 2
+                        break
+
+        self.text_direction = text_direction
+        self.default_width = default_width
+
+        if alignment.rotation > 90:
+            self.rotation = 90 - alignment.rotation
+        else:
+            self.rotation = alignment.rotation
+
+
+    def CreateFormat(self, format, cell, datemode):
+        """
+        This method tries to guess the best format to apply to the current text
+        value.
+
+        :param `format`: an instance of `xlrd.formatting.Format` class;
+        :param `cell`: an instance of `xlrd.sheet.Cell` class;
+        :param `datemode`: the datemode associated with this Excel workbook.
+
+        :note: This method is used only if Mark Hammonds' `pywin32` package is
+         not available to try and format the cell text in an intelligent way.
+
+        :warning: The formatting applied by this method is severely limited; for
+         instance, you won't probably get the exact WYSIWYG between the Excel
+         spreadsheet and L{XLSGrid}.
+        """
+
+        ctype, value = cell.ctype, cell.value
+
+        self.value = "%s"%value
+        isDate = False
+
+        if ctype == xlrd.XL_CELL_DATE:
+            value = xlrd.xldate_as_tuple(value, datemode)
+            isDate = True
+        elif ctype in [xlrd.XL_CELL_EMPTY, xlrd.XL_CELL_BLANK]:
+            return
+        elif ctype == xlrd.XL_CELL_TEXT:
+            self.value = "%s"%value
+            return
+        elif ctype == xlrd.XL_CELL_ERROR:
+            value = xlrd.error_text_from_code(ctype)
+            self.value = "%s"%value
+            return
+
+        self.FormatString(value, isDate, format.format_str)
+
+
+    def FormatString(self, value, isDate, format_str):
+        """
+        This method tries to guess the best format to apply to the current text
+        value.
+
+        :param `value`: the actual raw cell text value;
+        :param `isDate`: ``True`` if this value represents a `xlrd` date object,
+         ``False`` otherwise;
+        :param `format_str`: the actual formatting string as extracted from Excel.
+
+        :note: This method is used only if Mark Hammonds' `pywin32` package is
+         not available to try and format the cell text in an intelligent way.
+
+        :warning: The formatting applied by this method is severely limited; for
+         instance, you won't probably get the exact WYSIWYG between the Excel
+         spreadsheet and L{XLSGrid}.
+        """
+
+        if "General" in format_str:
+            self.value = "%s"%value
+            return
+
+        number_format = format_str
+        currency = percentage = ""
+
+        if not isDate:
+            symbol = ""
+            split = format_str.split()
+            if len(split) > 1:
+                # Accounting and currency shit
+                currency = split[0].split(".")[0] + "."
+                number_format = ".".join(split[1:])
+
+            if "%" in number_format:
+                percentage = "%"
+                value = 100*value
+                number_format = number_format[0:-1]
+
+            representation = "%d"
+            if "." in number_format:
+                split = number_format.split(".")
+                num_decimals = len(split[1])
+                representation = "%0." + str(num_decimals) + "f"
+
+            try:
+                value = representation%value
+            except ValueError:
+                # Fall back to string
+                value = unicode(value, "utf-8", "ignore")
+
+            if "#," in number_format:
+                value = SplitThousands(value)
+
+            value = currency + value + percentage
+
+        else:
+            number_format = format_str.replace("\\", "")
+            number_format = number_format.replace("-", "-%").replace("/", "/%")
+            value = datetime.datetime(*value)
+            try:
+                value = value.strftime(number_format)
+            except (ValueError, TypeError):
+                value = value.strftime("%d.%m.%Y")
+
+        self.value = value
+
+
+    def SetupHyperlink(self, hyperlink):
+        """
+        Sets up the cell text value in case it represents a hyperlink.
+
+        :param `hyperlink`: an instance of `xlrd.sheet.hyperlink`.
+
+        :note: If you are using version 0.7.1 or lower for `xlrd`, the *hyperlink*
+         parameter will always be ``None`` as this feature is available only in
+         `xlrd` 0.7.2 (SVN).
+        """
+
+        url = (hyperlink.url_or_path and [hyperlink.url_or_path] or [hyperlink.textmark])[0]
+        self.tooltip = url
+
+
+    def IsHyperLink(self):
+        """
+        Returns whether the cell text is representing a hyperlink.
+
+        :returns: ``True`` if the cell text represents a hyperlink, ``False``
+         otherwise.
+        """
+
+        return self.tooltip is not None
+
+
+    def CombineAttr(self, attr):
+        """
+        Combines the input attribute `attr` with the features of the L{XLSText} class.
+
+        :param `attr`: an instance of `wx.grid.GridCellAttr`.
+        """
+
+        attr.SetAlignment(self.horizontal_alignment, self.vertical_alignment)
+        attr.SetTextColour(self.text_colour)
+        attr.SetFont(self.font)
+
+
+    def GetValue(self):
+        """ Returns the string representation of the cell text value. """
+
+        return self.value
+
+
+    def Draw(self, dc, rect):
+        """
+        Actually draws the text value on a grid cell.
+
+        :param `dc`: an instance of `wx.DC`;
+        :param `rect`: an instance of `wx.Rect`, representing the cell rectangle.
+        """
+
+        new_rect = wx.Rect(*rect)
+
+        xshift = yshift = 0
+        if self.rotation:
+            xshift = cos(self.rotation*pi/180)
+            yshift = sin(self.rotation*pi/180)
+
+        dc.SetTextForeground(self.text_colour)
+        dc.SetFont(self.font)
+
+        value = self.value
+        text_width, text_height = dc.GetTextExtent(value)
+
+        default_width = int(round(float(self.default_width)*text_width/256.0))
+
+        indentation = int(256.0*default_width/float(self.default_width))
+
+        if xshift == 0 and self.indent_level:
+            new_rect.SetLeft(new_rect.x + indentation)
+        else:
+            if self.horizontal_alignment == wx.ALIGN_LEFT:
+                new_rect.SetLeft(new_rect.x + 3)
+            elif self.horizontal_alignment == wx.ALIGN_RIGHT:
+                new_rect.SetWidth(new_rect.width - 1)
+
+        new_width = rect.width
+
+        if xshift > 0:
+            new_width = new_width/xshift
+
+        if self.shrink_to_fit:
+
+            font = FontFromFont(self.font)
+            point_size = font.GetPointSize()
+
+            while 1:
+                value = wordwrap(self.value, new_width, dc)
+                if "\n" not in value or point_size < 2:
+                    break
+
+                point_size -= 1
+                font.SetPointSize(point_size)
+                dc.SetFont(font)
+
+        elif self.text_wrapped:
+
+            value = wordwrap(self.value, new_width, dc)
+            text_width, text_height, dummy = dc.GetMultiLineTextExtent(value)
+
+        if self.rotation:
+            if self.shrink_to_fit:
+                text_width, text_height = dc.GetTextExtent(value)
+
+            xc, yc = (rect.x+rect.width/2, rect.y+rect.height/2)
+            xp = xc - (text_width/2)*xshift - (text_height/2)*yshift
+            yp = yc + (text_width/2)*yshift - (text_height/2)*xshift
+
+            dc.DrawRotatedText(value, xp, yp, self.rotation)
+
+        else:
+
+            dc.DrawLabel(value, new_rect, self.horizontal_alignment|self.vertical_alignment)
+
+
+class XLSRichText(XLSText):
+    """
+    This is a class which holds information about the cell content, in terms
+    of actual cell value, font, text colour, alignment and formatting. In addition
+    to what L{XLSText} does, this class attempts to handle cells with rich text
+    content.
+    """
+
+    def __init__(self, book, cell, xf_index, display_text=None, hyperlink=None, rich_text=None, default_width=10):
+        """
+        Default class constructor.
+
+        :param `book`: an instance of the `xlrd.Book` class;
+        :param `cell`: an instance of `xlrd.sheet.Cell` class;
+        :param `xf_index`: an index into `xlrd.Book.xf_list`, which holds a
+         reference to the `xlrd.sheet.Cell` class (the actual cell for `xlrd`);
+        :param `display_text`: if Mark Hammonds' `pywin32` package is available,
+         this is the WYSIWYG cell content;
+        :param `hyperlink`: if this cell contains a hyperlink, it will be displayed
+         accordingly;
+        :param `rich_text`: if this cell contains text in rich text format, L{XLSGrid}
+         will do its best to render the text as rich text;
+        :param `default_width`: this is the default width of the text in 1/256
+         of the width of the zero character, using default Excel font (first FONT
+         record in the Excel file).
+
+        :note: If you are using version 0.7.1 or lower for `xlrd`, the *hyperlink*
+         parameter will always be ``None`` as this feature is available only in
+         `xlrd` 0.7.2 (SVN).
+
+        :note: If you are using version 0.7.1 or lower for `xlrd`, this class will
+         note be used by L{XLSGrid}.
+
+        :warning: This class currently supports only single-line non-rotated text,
+         and it discards properties like `shrink-to-fit` and `wrapping`.
+        """
+
+        XLSText.__init__(self, book, cell, xf_index, display_text, hyperlink, default_width)
+
+        self.BuildChunks(book, xf_index, rich_text)
+
+
+    def BuildChunks(self, book, xf_index, rich_text):
+        """
+        Splits the cell content accordingly to their rich text format index.
+
+        :param `book`: an instance of the `xlrd.Book` class;
+        :param `xf_index`: an index into `xlrd.Book.xf_list`, which holds a
+         reference to the `xlrd.sheet.Cell` class (the actual cell for `xlrd`);
+        :param `rich_text`: if this cell contains text in rich text format, L{XLSGrid}
+         will do its best to render the text as rich text.
+        """
+
+        XFClass = book.xf_list[xf_index]
+        offset, index = rich_text[0]
+
+        if offset != 0:
+            new_tuple = (0, XFClass.font_index)
+            rich_text.insert(0, new_tuple)
+
+        value = self.value
+        rich_text.append((len(value), rich_text[-1][1]))
+        attributes = []
+
+        for indx in xrange(len(rich_text)-1):
+            offset_start, index_start = rich_text[indx]
+            offset_end, index_end = rich_text[indx+1]
+
+            chunk = value[offset_start:offset_end]
+
+            font = book.font_list[index_start]
+            ffont = self.CreateFont(font)
+            text_colour = book.colour_map[font.colour_index]
+            colour = self.CreateTextColour(text_colour)
+
+            ffont.escapement = font.escapement_type
+            attributes.append([chunk, ffont, colour])
+
+        self.attributes = attributes
+
+
+    def Measure(self, dc):
+        """
+        Convenience method to measure the maximum height and total width of all
+        the chunks of text composing our rich text string.
+
+        :param `dc`: an instance of `wx.DC`.
+        """
+
+        maxH = -1
+        full_width = 0
+        for chunk, font, colour in self.attributes:
+            dc.SetFont(font)
+            width, height, descent, leading = dc.GetFullTextExtent(chunk, font)
+            maxH = max(maxH, height-leading)
+            full_width += width
+
+        return maxH, full_width
+
+
+    def Draw(self, dc, rect):
+        """
+        Actually draws all the chunks of text on a grid cell, one by one.
+
+        :param `dc`: an instance of `wx.DC`;
+        :param `rect`: an instance of `wx.Rect`, representing the cell rectangle.
+        """
+
+        new_rect = wx.Rect(*rect)
+
+        text_width, text_height = dc.GetTextExtent(self.value)
+        default_width = int(round(float(self.default_width)*text_width/256.0))
+        indentation = int(256.0*default_width/float(self.default_width))
+
+        maxH, full_width = self.Measure(dc)
+
+        if self.indent_level:
+            new_rect.SetLeft(new_rect.x + indentation)
+        else:
+            if self.horizontal_alignment == wx.ALIGN_LEFT:
+                new_rect.SetLeft(new_rect.x + 3)
+            elif self.horizontal_alignment == wx.ALIGN_RIGHT:
+                new_rect.SetLeft(new_rect.x + (new_rect.width - full_width) - 1)
+            else:
+                space = int((new_rect.width - full_width)/2.0)
+                new_rect.SetLeft(new_rect.x + space)
+                new_rect.SetWidth(full_width+space)
+
+        if self.vertical_alignment == wx.ALIGN_TOP:
+            vspace = 0
+        elif self.vertical_alignment == wx.ALIGN_BOTTOM:
+            vspace = (new_rect.height - maxH - 1)
+        else:
+            vspace = int((new_rect.height - maxH)/2.0)
+
+        start = new_rect.x
+        y = new_rect.y
+
+        for chunk, font, colour in self.attributes:
+            dc.SetTextForeground(colour)
+            dc.SetFont(font)
+            width, height, descent, leading = dc.GetFullTextExtent(chunk, font)
+            if font.escapement > 0:
+                height = height*0.7
+
+            ypos = y-height+maxH+vspace
+
+            if font.escapement == 1:
+                ypos = ypos - maxH + height
+
+            dc.DrawText(chunk, start, ypos)
+            start += width
+
+
+class XLSBackground(object):
+    """
+    This is a class which holds information about the cell background, in terms
+    of background colour and background pattern (hatching).
+    """
+
+    def __init__(self, book, xf_index):
+        """
+        Default class constructor.
+
+        :param `book`: an instance of the `xlrd.Book` class;
+        :param `xf_index`: an index into `xlrd.Book.xf_list`, which holds a
+         reference to the `xlrd.sheet.Cell` class (the actual cell for `xlrd`).
+        """
+
+        XFClass = book.xf_list[xf_index]
+
+        background = XFClass.background
+        background_colour = book.colour_map[background.background_colour_index]
+        pattern_colour = book.colour_map[background.pattern_colour_index]
+        fill_pattern = background.fill_pattern
+
+        self.CreateBackgroundColour(background_colour, pattern_colour, fill_pattern)
+
+
+    def CreateBackgroundColour(self, background_colour, pattern_colour, fill_pattern):
+        """
+        Creates a suitable wxPython colour for the cell background starting from
+        a `xlrd` tuple representing this colour.
+
+        :param `background_colour`: a tuple representing the RGB components of the
+         cell background colour. If `background_colour` is ``None``, use the
+         default ``wx.SYS_COLOUR_WINDOW``;
+        :param `pattern_colour`: a tuple representing the RGB components of the
+         cell pattern colour;
+        :param `fill_pattern`: the pattern to use to draw hatches on top of the
+         background.
+        """
+
+        if background_colour is not None:
+            background_colour = wx.Colour(*background_colour)
+        else:
+            background_colour = wx.SystemSettings.GetColour(wx.SYS_COLOUR_WINDOW)
+
+        if pattern_colour is not None:
+            pattern_colour = wx.Colour(*pattern_colour)
+
+        self.background_brush = wx.Brush(background_colour)
+        self.background_colour = background_colour
+
+        self.fill_brush = None
+
+        if fill_pattern <= 0:
+            return
+
+        r, g, b = pattern_colour
+
+        fill_image = eval("_xls_background_%02d.GetImage()"%fill_pattern)
+        fill_image.Replace(0, 0, 0, r, g, b)
+        r, g, b = background_colour.Red(), background_colour.Green(), background_colour.Blue()
+        fill_image.Replace(255, 255, 255, r, g, b)
+        fill_bitmap = fill_image.ConvertToBitmap()
+
+        self.fill_brush = wx.BrushFromBitmap(fill_bitmap)
+
+
+    def CombineAttr(self, attr):
+        """
+        Combines the input attribute `attr` with the features of the L{XLSBackground} class.
+
+        :param `attr`: an instance of `wx.grid.GridCellAttr`.
+        """
+
+        attr.SetBackgroundColour(self.background_colour)
+        return attr
+
+
+    def Draw(self, dc, rect):
+        """
+        Actually draws the cell background and pattern hatching on a grid cell.
+
+        :param `dc`: an instance of `wx.DC`;
+        :param `rect`: an instance of `wx.Rect`, representing the cell rectangle.
+        """
+
+        dc.SetClippingRect(rect)
+
+        dc.SetBackgroundMode(wx.SOLID)
+        dc.SetBrush(self.background_brush)
+        dc.SetPen(wx.TRANSPARENT_PEN)
+        dc.DrawRectangleRect(rect)
+
+        if self.fill_brush:
+
+            dc.SetBrush(self.fill_brush)
+            dc.SetBackgroundMode(wx.TRANSPARENT)
+            dc.DrawRectangleRect(rect)
+
+        dc.DestroyClippingRegion()
+
+
+class XLSBorder(object):
+    """
+    This is a class which holds information about a single cell border, in terms
+    of its location (top, left, bottom, right, diagonal), its colour, width and
+    shape.
+    """
+
+    def __init__(self, location, line_style, border_colour, default_colour, diagonals):
+        """
+        Default class constructor.
+
+        :param `location`: the actual border location (top, left, bottom, right,
+         diagonal);
+        :param `line_style`: the line style used by Excel to draw this border;
+        :param `border_colour`: the colour used by Excel to draw this border;
+        :param `default_colour`: the "magic" colour used by Excel to draw non-custom
+         border lines;
+        :param `diagonals`: a tuple containing whether or not to draw the up and down
+         diagonal borders.
+        """
+
+        self.draw_priority = 2
+
+        if line_style == NO_LINE:
+
+            if border_colour == (0, 0, 0):
+                self.draw_priority = 0
+                border_colour = wx.Colour(*default_colour)
+            else:
+                self.draw_priority = 1
+                border_colour = wx.BLACK
+
+            self.pen = wx.Pen(border_colour, 1, wx.SOLID)
+            pen_style = THIN
+
+        else:
+
+            if border_colour == (0, 0, 0):
+                border_colour = wx.Colour(*default_colour)
+                self.draw_priority = 2
+            elif border_colour is None:
+                border_colour = wx.BLACK
+                self.draw_priority = 2
+            else:
+                border_colour = wx.Colour(*border_colour)
+
+            pen_width, pen_style = XF_PEN_STYLES[line_style]
+            if pen_width > 2:
+                self.draw_priority = 4
+            elif pen_width > 1:
+                self.draw_priority = 3
+
+            self.pen = wx.Pen(border_colour, pen_width, pen_style)
+
+        self.diagonals = diagonals
+        self.location = location
+        self.pen_style = pen_style
+        self.line_style = line_style
+
+
+    def Draw(self, dc, rect):
+        """
+        Actually draws the cell border.
+
+        :param `dc`: an instance of `wx.DC`;
+        :param `rect`: an instance of `wx.Rect`, representing the cell rectangle.
+        """
+
+        dc.SetBackgroundMode(wx.TRANSPARENT)
+        dc.SetPen(self.pen)
+
+        if self.location == DIAGONAL:
+            self.DrawDiagonals(dc, rect)
+        else:
+            self.DrawBorder(dc, rect)
+
+
+    def DrawDiagonals(self, dc, rect):
+        """
+        Actually draws the cell diagonal border.
+
+        :param `dc`: an instance of `wx.DC`;
+        :param `rect`: an instance of `wx.Rect`, representing the cell rectangle.
+        """
+
+        diag_up, diag_down = self.diagonals
+
+        if diag_down:
+            xstart, ystart = rect.GetTopLeft()
+            xend, yend = rect.GetBottomRight()
+
+            if self.line_style == DOUBLE:
+                dc.DrawLine(xstart+2, ystart, xend, yend-2)
+                dc.DrawLine(xstart, ystart+2, xend-2, yend)
+            else:
+                dc.DrawLine(xstart, ystart, xend, yend)
+
+        if diag_up:
+
+            xstart, ystart = rect.GetBottomLeft()
+            xend, yend = rect.GetTopRight()
+
+            if self.line_style == DOUBLE:
+                dc.DrawLine(xstart, ystart-2, xend-2, yend)
+                dc.DrawLine(xstart+2, ystart, xend, yend+2)
+            else:
+                dc.DrawLine(xstart, ystart, xend, yend)
+
+
+    def DrawBorder(self, dc, rect):
+        """
+        Actually draws the cell border (one of left, right, bottom, top).
+
+        :param `dc`: an instance of `wx.DC`;
+        :param `rect`: an instance of `wx.Rect`, representing the cell rectangle.
+        """
+
+        pen_width = self.pen.GetWidth()
+        location = self.location
+        new_rect = wx.Rect(*rect)
+
+        x, y, w, h = new_rect
+        line_style = self.line_style
+
+        shift = 0
+        if pen_width == 2:
+            shift = pen_width - 1
+        if pen_width > 2:
+            shift = pen_width - 2
+
+        if location == BOTTOM:
+
+            if self.draw_priority < 2:
+                return
+
+            if line_style == DOUBLE:
+                dc.DrawLine(x, y+h-1, x+w, y+h-1)
+                dc.DrawLine(x, y+h+1, x+w, y+h+1)
+            else:
+                dc.DrawLine(x+1, y+h,   x+w, y+h)
+
+
+        elif location == TOP:
+
+            if line_style == DOUBLE:
+                dc.DrawLine(x, y-1, x+w, y-1)
+                dc.DrawLine(x, y+1, x+w, y+1)
+            else:
+                dc.DrawLine(x+1, y+shift,   x+w, y+shift)
+
+        elif location == LEFT:
+
+            if line_style == DOUBLE:
+                dc.DrawLine(x-1, y, x-1, y+h)
+                dc.DrawLine(x+1, y, x+1, y+h)
+            else:
+                dc.DrawLine(x+shift,   y+1, x+shift,   y+h)
+
+        elif location == RIGHT:
+
+            if self.draw_priority < 2:
+                return
+
+            if line_style == DOUBLE:
+                dc.DrawLine(x+w-1, y, x+w-1, y+h)
+                dc.DrawLine(x+w+1, y, x+w+1, y+h)
+            else:
+                dc.DrawLine(x+w+1, y+1, x+w+1, y+h)
+
+
+class XLSBorderFactory(object):
+    """
+    This is a factory class which holds information about all the borders in a
+    cell. Its implementation and use is merely to simplify the handling of the
+    different cell borders (left, top, bottom, right, diagonal).
+    """
+
+    def __init__(self, book, border, default_colour):
+        """
+        Default class constructor.
+
+        :param `book`: an instance of the `xlrd.Book` class;
+        :param `border`: an instance of `xlrd.formatting.XFBorder` class;
+        :param `default_colour`: the "magic" colour used by Excel to draw non-custom
+         border lines.
+        """
+
+        borders = {}
+        diagonals = border.diag_up, border.diag_down
+
+        for label, location in XF_BORDER_STYLES.items():
+            line_style = getattr(border, "%s_line_style"%label)
+            colour_index = getattr(border, "%s_colour_index"%label)
+            border_colour = book.colour_map[colour_index]
+
+            border_class = XLSBorder(location, line_style, border_colour, default_colour, diagonals)
+            borders[location] = border_class
+
+        self.draw_priority = sorted(borders.values(), key=attrgetter('draw_priority'))
+
+
+    def Draw(self, dc, rect):
+        """
+        Actually draws all the cell borders based on their drawing priority.
+
+        :param `dc`: an instance of `wx.DC`;
+        :param `rect`: an instance of `wx.Rect`, representing the cell rectangle.
+
+        :note: The drawing priority is assigned depending on if the border is a
+         custom one or not. Customized borders are drawn last.
+        """
+
+        for border in self.draw_priority:
+            border.Draw(dc, rect)
+
+
+class XLSComment(object):
+    """
+    This is a class which holds information about the content of the "comment
+    window" (aka note) in Excel.
+
+    :note: If Mark Hammonds' `pywin32` package is not available, this class can
+     not be used.
+    """
+
+    def __init__(self, comment):
+        """
+        Default class constructor.
+
+        :param `comment`: the actual text contained in the Excel cell comment (note).
+        """
+
+        self.comment = comment
+
+
+    def Draw(self, dc, rect):
+        """
+        Actually draws a small red triangle in the top-right corder of the cell
+        to indicate that a comment is present.
+
+        :param `dc`: an instance of `wx.DC`;
+        :param `rect`: an instance of `wx.Rect`, representing the cell rectangle.
+        """
+
+        right = rect.GetTopRight()
+        points = [wx.Point(right.x-5, right.y),
+                  right,
+                  wx.Point(right.x, right.y+5)]
+
+        dc.SetBrush(wx.RED_BRUSH)
+        dc.SetPen(wx.RED_PEN)
+        dc.DrawPolygon(points)
+
+
+class XLSCell(object):
+    """
+    This is a class which holds information about a single cell in L{XLSGrid}.
+    It stores (via auxiliary classes), all details about cell background, text,
+    font, colours and borders.
+    """
+
+    def __init__(self, book, cell, xf_index, xls_text, xls_comment, hyperlink, rich_text, default_width, default_colour):
+        """
+        Default class constructor.
+
+        :param `book`: an instance of the `xlrd.Book` class;
+        :param `cell`: an instance of `xlrd.sheet.Cell` class;
+        :param `xf_index`: an index into `xlrd.Book.xf_list`, which holds a
+         reference to the `xlrd.sheet.Cell` class (the actual cell for `xlrd`);
+        :param `xls_text`: the actual WYSIWYG cell text, if available;
+        :param `xls_comment`: the cell comment (note), if any;
+        :param `hyperlink`: an instance of `xlrd.sheet.hyperlink`;
+        :param `rich_text`: if this cell contains text in rich text format, L{XLSGrid}
+         will do its best to render the text as rich text;
+        :param `default_width`: this is the default width of the text in 1/256
+         of the width of the zero character, using default Excel font (first FONT
+         record in the Excel file);
+        :param `default_colour`: the "magic" colour used by Excel to draw non-custom
+         border lines.
+
+        :note: If you are using version 0.7.1 or lower for `xlrd`, the *hyperlink*
+         parameter will always be ``None`` as this feature is available only in
+         `xlrd` 0.7.2 (SVN).
+
+        :note: If you are using version 0.7.1 or lower for `xlrd`, the `rich_text`
+         parameter will always be ``None`` as this feature is available only in
+         `xlrd` 0.7.2 (SVN).
+
+        :note: if Mark Hammonds' `pywin32` package is not available, the `xls_text`
+         parameter will almost surely not be the WYSIWYG representation of the cell
+         text.
+
+        :note: If Mark Hammonds' `pywin32` package is not available, the `xls_comment`
+         parameter will always be ``None``.
+        """
+
+        self.size = 1, 1
+
+        self.comment = None
+        self.hyperlink = None
+
+        self.SetupCell(book, cell, xf_index, xls_text, xls_comment, hyperlink, rich_text, default_width, default_colour)
+
+
+    def SetupCell(self, book, cell, xf_index, xls_text, xls_comment, hyperlink, rich_text, default_width, default_colour):
+        """
+        Actually sets up the L{XLSCell} class. This is an auxiliary method to
+        avoid cluttering the L{__init__} method.
+
+        :param `book`: an instance of the `xlrd.Book` class;
+        :param `cell`: an instance of `xlrd.sheet.Cell` class;
+        :param `xf_index`: an index into `xlrd.Book.xf_list`, which holds a
+         reference to the `xlrd.sheet.Cell` class (the actual cell for `xlrd`);
+        :param `xls_text`: the actual WYSIWYG cell text, if available;
+        :param `xls_comment`: the cell comment (note), if any;
+        :param `hyperlink`: an instance of `xlrd.sheet.hyperlink`;
+        :param `rich_text`: if this cell contains text in rich text format, L{XLSGrid}
+         will do its best to render the text as rich text;
+        :param `default_width`: this is the default width of the text in 1/256
+         of the width of the zero character, using default Excel font (first FONT
+         record in the Excel file);
+        :param `default_colour`: the "magic" colour used by Excel to draw non-custom
+         border lines.
+
+        :note: If you are using version 0.7.1 or lower for `xlrd`, the *hyperlink*
+         parameter will always be ``None`` as this feature is available only in
+         `xlrd` 0.7.2 (SVN).
+
+        :note: If you are using version 0.7.1 or lower for `xlrd`, the `rich_text`
+         parameter will always be ``None`` as this feature is available only in
+         `xlrd` 0.7.2 (SVN).
+
+        :note: if Mark Hammonds' `pywin32` package is not available, the `xls_text`
+         parameter will almost surely not be the WYSIWYG representation of the cell
+         text.
+
+        :note: If Mark Hammonds' `pywin32` package is not available, the `xls_comment`
+         parameter will always be ``None``.
+        """
+
+        cvalue = cell.value
+        self.raw_value = cvalue
+
+        if rich_text:
+            self.text = XLSRichText(book, cell, xf_index, xls_text, hyperlink, rich_text, default_width)
+        else:
+            self.text = XLSText(book, cell, xf_index, xls_text, hyperlink, default_width)
+
+        self.background = XLSBackground(book, xf_index)
+
+        XFClass = book.xf_list[xf_index]
+        border = XFClass.border
+
+        self.borders = XLSBorderFactory(book, border, default_colour)
+
+        if xls_comment:
+            self.comment = XLSComment(xls_comment)
+
+        self.attr = None
+
+
+    def GetAttr(self):
+        """
+        Returns the attribute to use for this specific cell.
+
+        :returns: an instance of `wx.grid.GridCellAttr`.
+        """
+
+        if self.attr is not None:
+            self.attr.IncRef()
+            return self.attr
+
+        attr = gridlib.GridCellAttr()
+
+        attr.SetRenderer(XLSRenderer(self))
+
+        attr.SetSize(*self.size)
+        attr.SetOverflow(True)
+        self.attr = attr
+        self.attr.IncRef()
+
+        return self.attr
+
+
+    def GetValue(self):
+        """ Returns the actual WYSIWYG representation of the cell value. """
+
+        return self.text.GetValue()
+
+
+    def SetValue(self, value):
+        """
+        Sets the actual WYSIWYG representation of the cell value.
+
+        :param `value`: the current text value to insert in the cell.
+
+        :note: This method is currently unused as everything is handled inside the L{XLSText} class.
+
+        :see: L{GetValue}
+        """
+
+        self.value = value
+
+
+    def SetCellSize(self, rows, cols):
+        """
+        Sets the size of the cell.
+
+        Specifying a value of more than 1 in `rows` or `cols` will make the cell
+        at (`row`, `col`) span the block of the specified size, covering the other
+        cells which would be normally shown in it. Passing 1 for both arguments
+        resets the cell to normal appearance.
+
+        :param `rows`: number of rows to be occupied by this cell, must be >= 1;
+        :param `cols`: number of columns to be occupied by this cell, must be >= 1.
+        """
+
+        self.size = (rows, cols)
+
+
+    def GetComment(self):
+        """
+        Returns the cell comment, if any.
+
+        :returns: an instance of L{XLSComment}.
+
+        :note: If Mark Hammonds' `pywin32` package is not available, this method
+         always returns ``None``.
+        """
+
+        return self.comment
+
+
+class XLSRenderer(gridlib.PyGridCellRenderer):
+    """
+    This class is responsible for actually drawing the cell in the grid.
+
+    """
+
+    def __init__(self, cell):
+        """
+        Default class constructor.
+
+        :param `cell`: an instance of L{XLSCell}.
+        """
+
+        gridlib.PyGridCellRenderer.__init__(self)
+        self.cell = cell
+
+
+    def Draw(self, grid, attr, dc, rect, row, col, isSelected):
+        """
+        Draw the given cell on the provided `dc` inside the given rectangle using
+        default or selected state corresponding to the `isSelected` value.
+
+        :param `grid`: an instance of `wx.grid.Grid`;
+        :param `attr`: an instance of `wx.grid.GridCellAttr`;
+        :param `dc`: an instance of `wx.DC`;
+        :param `rect`: an instance of `wx.Rect`, representing the cell rectangle;
+        :param `row`: the row in which this cell lives;
+        :param `col`: the column in which this cell lives;
+        :param `isSelected`: ``True`` if the cell is selected, ``False`` otherwise.
+        """
+
+        # clear the background
+        dc.SetBackgroundMode(wx.SOLID)
+
+        cell = self.cell
+
+        cell.background.Draw(dc, rect)
+
+        if cell.borders:
+            cell.borders.Draw(dc, rect)
+
+        cell.text.Draw(dc, rect)
+
+        if cell.comment:
+            cell.comment.Draw(dc, rect)
+
+        if isSelected:
+
+            gdc = wx.GCDC(dc)
+
+            sys_colour = wx.SystemSettings.GetColour(wx.SYS_COLOUR_HIGHLIGHT)
+            brush_colour = wx.Colour(sys_colour.Red(), sys_colour.Green(), sys_colour.Blue(), 90)
+
+            gdc.SetBrush(wx.Brush(brush_colour))
+            gdc.SetPen(wx.TRANSPARENT_PEN)
+
+            gdc.DrawRectangleRect(rect)
+
+
+class XLSTable(gridlib.PyGridTableBase):
+    """
+    The almost abstract base class for grid tables.
+
+    A grid table is responsible for storing the grid data and, indirectly, grid
+    cell attributes. The data can be stored in the way most convenient for the
+    application but has to be provided in string form to `wx.grid.Grid`.
+    """
+
+    def __init__(self, grid, cells, rows, cols):
+        """
+        Default class constructor.
+
+        :param `grid`: an instance of `wx.grid.Grid`;
+        :param `cells`: a Python dictionary. For every key `(row, col)`, the
+         corresponding value is an instance of L{XLSCell};
+        :param `rows`: the number of rows in the table;
+        :param `cols`: the number of columns in the table.
+        """
+
+        # The base class must be initialized *first*
+        gridlib.PyGridTableBase.__init__(self)
+
+        self.cells = cells
+        self.dimens = (rows, cols)
+
+
+    def GetNumberCols(self):
+        """ Returns the number of columns in the table. """
+
+        return self.dimens[1]
+
+
+    def GetNumberRows(self):
+        """ Returns the number of rows in the table. """
+
+        return self.dimens[0]
+
+
+    def GetValue(self, row, col):
+        """
+        Returns the cell content for the specified row and column.
+
+        :param `row`: the row in which this cell lives;
+        :param `col`: the column in which this cell lives.
+        """
+
+        cell = self.cells[(row, col)]
+        return cell.GetValue()
+
+
+    def SetValue(self, row, col, value):
+        """
+        sets the cell content for the specified row and column.
+
+        :param `row`: the row in which this cell lives;
+        :param `col`: the column in which this cell lives;
+        :param `value`: the new value to assign to the specified cell.
+        """
+
+        cell = self.cells[(row, col)]
+        cell.SetValue(value)
+
+
+    def GetAttr(self, row, col, kind):
+        """
+        Return the attribute for the given cell.
+
+        :param `row`: the row in which this cell lives;
+        :param `col`: the column in which this cell lives;
+        :param `kind`: the kind of the attribute to return.
+        """
+
+        cell = self.cells[(row, col)]
+        return cell.GetAttr()
+
+
+    def GetRawValue(self, row, col):
+        """
+        Returns the "raw" value for the cell content.
+
+        :param `row`: the row in which this cell lives;
+        :param `col`: the column in which this cell lives.
+        """
+
+        cell = self.cells[(row, col)]
+        return cell.raw_value
+
+
+class XLSGrid(gridlib.Grid):
+    """
+    L{XLSGrid} is a class based on `wx.grid.Grid` that can be used to faithfully
+    reproduce the appearance of a Microsoft Excel spreadsheet (one worksheet per
+    every instance of L{XLSGrid}).
+
+    L{XLSGrid} is a completely owner-drawn control, and it relies on the power of
+    `wx.grid.PyGridTableBase` and `wx.grid.PyGridCellRenderer` to draw the cell
+    content. For this reasons (and for some others, see the TODOs section), it will
+    work efficiently only for relatively small Excel files.
+    """
+
+    def __init__(self, parent):
+        """
+        Default class constructor.
+
+        :param `parent`: the grid parent window. Must not be ``None``.
+        """
+
+        gridlib.Grid.__init__(self, parent)
+
+        self.SetMargins(0, 0)
+        self.SetDefaultCellBackgroundColour(parent.GetBackgroundColour())
+        self.SetDefaultCellOverflow(True)
+
+        self.tip_window = None
+        self.tip_shown = False
+
+
+    def DestroyTip(self):
+        """
+        If a comment window or a tooltip over a hyperlink have been created, this
+        method destroys them.
+        """
+
+        if self.tip_window:
+            try:
+                self.tip_window.GetTipWindow().Destroy()
+            except wx.PyDeadObjectError:
+                pass
+
+            del self.tip_window
+            self.tip_window = None
+
+        if self.tip_shown:
+            self.GetGridWindow().SetToolTipString("")
+            self.GetGridWindow().SetCursor(wx.NullCursor)
+            self.tip_shown = False
+
+
+    def InstallGridHint(self):
+        """
+        Auxiliary method used to bind a ``wx.EVT_MOTION`` event to L{XLSGrid}.
+        """
+
+        self.prev_rowcol = [None, None]
+
+        def OnMouseMotion(event):
+            """
+            Handles a the ``wx.EVT_MOTION`` events for L{XLSGrid}.
+
+            :param `event`: a `wx.MouseEvent` event to be processed.
+            """
+
+            # evt.GetRow() and evt.GetCol() would be nice to have here,
+            # but as this is a mouse event, not a grid event, they are not
+            # available and we need to compute them by hand.
+            position = event.GetPosition()
+            x, y = self.CalcUnscrolledPosition(position)
+            row = self.YToRow(y)
+            col = self.XToCol(x)
+
+            if [row, col] != self.prev_rowcol and row >= 0 and col >= 0:
+
+                self.prev_rowcol[:] = [row, col]
+                self.DestroyTip()
+                cell = self.cells[(row, col)]
+                rect = self.CellToRect(row, col)
+                comment = cell.GetComment()
+
+                window = self.GetGridWindow()
+                if cell.text.IsHyperLink():
+                    window.SetCursor(wx.StockCursor(wx.CURSOR_HAND))
+                    window.SetToolTipString(cell.text.tooltip)
+                    self.tip_shown = True
+                    if not comment:
+                        return
+
+                if comment:
+                    self.tip_window = TransientPopup(window, comment, wx.GetMousePosition())
+                    event.Skip()
+
+        self.GetGridWindow().Bind(wx.EVT_MOTION, OnMouseMotion)
+
+
+    def PopulateGrid(self, book, sheet, display_texts, comments):
+        """
+        This is the main method of this class, and it is used to actually create
+        the cells, size the columns and rows, merging cells, etc...
+
+        :param `book`: an instance of the `xlrd.Book` class;
+        :param `sheet`: an instance of the `xlrd.sheet` class;
+        :param `display_texts`: if Mark Hammonds' `pywin32` package is available,
+         this is the WYSIWYG cell content for all the cells in the Excel worksheet;
+        :param `comments`: if Mark Hammonds' `pywin32` package is available,
+         this is a nested list of cell comments (notes) for all the cells in the
+         Excel worksheet.
+        """
+
+        self.BeginBatch()
+
+        nrows = sheet.nrows
+        ncols = sheet.ncols
+
+        default_width, default_height = self.GetDefaultFontData(book)
+        default_colour = self.GetGridLineColour()
+
+        hyperlinks, rich_text_list = {}, {}
+        if hasattr(sheet, "hyperlink_map"):
+            # New in xlrd version 0.7.2 from SVN
+            hyperlinks = sheet.hyperlink_map
+
+        if hasattr(sheet, "rich_text_runlist_map"):
+            # New in xlrd version 0.7.2 from SVN
+            rich_text_list = sheet.rich_text_runlist_map
+
+        self.cells = {}
+
+        for i in xrange(nrows):
+
+            for j in xrange(ncols):
+
+                hyperlink = rich_text = None
+
+                if (i, j) in hyperlinks:
+                    hyperlink = hyperlinks[(i, j)]
+                if (i, j) in rich_text_list:
+                    rich_text = rich_text_list[(i, j)]
+
+                self.FormatCell(book, sheet, i, j, display_texts, comments, hyperlink, rich_text, default_width, default_colour)
+
+        self.table = XLSTable(self, self.cells, nrows, ncols)
+        self.SetTable(self.table)
+
+        row_height = sheet.default_row_height
+        col_width = sheet.defcolwidth
+
+        for i in xrange(nrows):
+            if i in sheet.rowinfo_map:
+                current = sheet.rowinfo_map[i].height
+            else:
+                current = sheet.default_row_height
+
+            row_height = int(round(float(default_height)*current/256.0))
+            self.SetRowSize(i, row_height)
+
+        for j in xrange(ncols):
+            if j in sheet.colinfo_map:
+                current = sheet.colinfo_map[j].width
+            else:
+                current = sheet.defcolwidth
+
+            col_width = int(round(float(default_width)*current/256.0))
+            self.SetColSize(j, col_width)
+
+        for merged in sheet.merged_cells:
+            rlo, rhi, clo, chi = merged
+            if rlo >= 0 and rlo < len(self.cells) and clo >= 0:
+                self.cells[(rlo, clo)].SetCellSize(rhi-rlo, chi-clo)
+
+        self.EnableEditing(False)
+        self.EnableGridLines(False)
+        self.EndBatch()
+        self.ForceRefresh()
+        self.InstallGridHint()
+
+
+    def FormatCell(self, book, sheet, row, col, display_texts, comments, hyperlink, rich_text, default_width, default_colour):
+        """
+        Processes the creation of a single cell (an instance of L{XLSCell}).
+
+        :param `book`: an instance of the `xlrd.Book` class;
+        :param `sheet`: an instance of the `xlrd.sheet` class;
+        :param `row`: the row in which this cell lives;
+        :param `col`: the column in which this cell lives;
+        :param `display_texts`: if Mark Hammonds' `pywin32` package is available,
+         this is the WYSIWYG cell content for all the cells in the Excel worksheet;
+        :param `comments`: if Mark Hammonds' `pywin32` package is available,
+         this is a nested list of cell comments (notes) for all the cells in the
+         Excel worksheet;
+        :param `hyperlink`: if this cell contains a hyperlink, it will be displayed
+         accordingly;
+        :param `rich_text`: if this cell contains text in rich text format, L{XLSGrid}
+         will do its best to render the text as rich text;
+        :param `default_width`: this is the default width of the text in 1/256
+         of the width of the zero character, using default Excel font (first FONT
+         record in the Excel file);
+        :param `default_colour`: the "magic" colour used by Excel to draw non-custom
+         border lines.
+
+        :note: If you are using version 0.7.1 or lower for `xlrd`, the *hyperlink*
+         parameter will always be ``None`` as this feature is available only in
+         `xlrd` 0.7.2 (SVN).
+
+        :note: If you are using version 0.7.1 or lower for `xlrd`, the `rich_text`
+         parameter will always be ``None`` as this feature is available only in
+         `xlrd` 0.7.2 (SVN).
+
+        :note: If Mark Hammonds' `pywin32` package is not available, the `display_texts`
+         and `comments` parameter will be two empty nested lists.
+        """
+
+        cell = sheet.cell(row, col)
+
+        xf_index = sheet.cell_xf_index(row, col)
+        xls_text, xls_comment = display_texts[row][col], comments[row][col]
+
+        gridCell = XLSCell(book, cell, xf_index, xls_text, xls_comment, hyperlink, rich_text, default_width, default_colour)
+
+        self.cells[(row, col)] = gridCell
+
+
+    def GetDefaultFontData(self, book):
+        """
+        Returns suitable width and height (in pixels) starting from Excel's own
+        measurements (in characters, whatever that means).
+
+        :param `book`: an instance of the `xlrd.Book` class.
+
+        :returns: a `default_width` and `default_height` in pixels, based on the
+         default width of the text in 1/256 of the width of the zero character,
+         using default Excel font (first FONT record in the Excel file).
+        """
+
+        font = book.font_list[0]
+        style, bold, underline = wx.FONTSTYLE_NORMAL, wx.NORMAL, False
+
+        if font.italic:
+            style = wx.FONTSTYLE_ITALIC
+        if font.underline_type > 0:
+            underline = True
+        if font.weight > 600:
+            bold = wx.BOLD
+
+        family = XF_FONT_FAMILY[font.family]
+        name = font.name
+        size = int(font.height/20.0)
+
+        dc = wx.ClientDC(self)
+        font = wx.Font(size, family, style, bold, underline, name.encode())
+        dc.SetFont(font)
+        width, height, descent, leading = dc.GetFullTextExtent("0", font)
+
+        return width, height + descent - leading
+
+
+class TransientPopup(STT.SuperToolTip):
+    """
+    This is a sublass of L{SuperToolTip} and it is used to display a
+    "comment-window" on the cells containing a comment (a note).
+
+    :note: If Mark Hammonds' `pywin32` package is not available, this class is
+     never invoked.
+    """
+
+    def __init__(self, grid_window, comment, position):
+        """
+        Default class constructor.
+
+        :param `grid_window`: the actual window representing the grid;
+        :param `comment`: an instance of L{XLSComment}, containing the
+         text for this comment;
+        :param `position`: the position at which we pop up the comment
+         window (currently unused).
+        """
+
+        STT.SuperToolTip.__init__(self, grid_window)
+
+        xls_comment = comment.comment
+
+        split = xls_comment.split(":")
+        header, rest = split[0], split[1:]
+        rest = ":".join(rest)
+
+        dc = wx.ClientDC(grid_window)
+        rest = wordwrap(rest, 400, dc)
+
+        self.SetHeader(header)
+        self.SetMessage(rest)
+        self.SetTarget(grid_window)
+        self.SetDrawHeaderLine(True)
+
+        self.SetStartDelay(100000)
+        self.SetEndDelay(100000)
+        self.ApplyStyle("Office 2007 Blue")
+
+        self.SetDropShadow(True)
+        self.DoShowNow()
+
+        grid_window.SetFocus()
+
+=======
# --------------------------------------------------------------------------------- #
# XLSGRID wxPython IMPLEMENTATION
#
@@ -2087,4 +4177,5 @@

grid_window.SetFocus()

+>>>>>>> .r69293

\ No newline at end of file

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • xlsgrid »
  • SVN Revision 69294 For xlsgrid


SVN Revision 69621 For xlsgrid

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • xlsgrid »
  • SVN Revision 69621 For xlsgrid

svn SVN Revision 69621 For xlsgrid

This file contains the SVN revision history for xlsgrid, at revision 69621.

Available information include commit date, the name of the committer, the file size, the SVN log messages and a diff from the previous version (if available).

File Information

  • Commit Date: 25-Aug-2011 20:02:59 UTC
  • Committer: AG
  • File Size: 72436 byte(s)

Log Messages

The following log message was entered by the committer:

XLSGrid: remove the crappy “&gt;&gt;&gt;&gt;” and “&lt;&lt;&lt;&lt;” stuff TortoiseSVN has put in the files.

Diff To Previous Version (69294)

Version SVN diff:

--- wxPython/3rdParty/AGW/agw/xlsgrid.py    2011/10/02 19:32:45     69294
+++ wxPython/3rdParty/AGW/agw/xlsgrid.py    2011/10/31 21:27:59     69621
@@ -1,4 +1,3 @@
-<<<<<<< .mine
# --------------------------------------------------------------------------------- #
# XLSGRID wxPython IMPLEMENTATION
#
@@ -2086,2096 +2085,3 @@
self.DoShowNow()

grid_window.SetFocus()
-
-=======
-# --------------------------------------------------------------------------------- #
-# XLSGRID wxPython IMPLEMENTATION
-#
-# Andrea Gavana @ 08 Aug 2011
-# Latest Revision: 17 Aug 2011, 15.00 GMT
-#
-#
-# TODO List
-#
-# Current todo list:
-#
-# 1. There is currently no support for rich text, i.e. strings containing partial
-#    bold, italic and underlined text, change of font inside a string, etc... xlrd
-#    supports those (from version 0.7.2 in SVN) but there is no easy way to handle
-#    changing fonts/colours/formatting in the same string in wxPython;
-#
-# 2. XLSGrid is sufficiently efficient and fast for reasonably small Excel files.
-#    There might be some improvement to be made in the code to make it work with
-#    bigger files and in a faster way;
-#
-# 3. There is currently no support for strikethrough fonts, although xlrd correctly
-#    reports this format. The issue is a bug in wxWidgets itself which doesn't
-#    allow the creation of strikethrough fonts (http://trac.wxwidgets.org/ticket/9907).
-#
-# 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
-# --------------------------------------------------------------------------------- #
-
-
-"""
-L{XLSGrid} is a class based on `wx.grid.Grid` that can be used to faithfully
-reproduce the appearance of a Microsoft Excel spreadsheet (one worksheet per
-every instance of L{XLSGrid}).
-
-
-Description
-===========
-
-L{XLSGrid} is a class based on `wx.grid.Grid` that can be used to faithfully
-reproduce the appearance of a Microsoft Excel spreadsheet (one worksheet per
-every instance of L{XLSGrid}).
-
-L{XLSGrid} is a completely owner-drawn control, and it relies on the power of
-`wx.grid.PyGridTableBase` and `wx.grid.PyGridCellRenderer` to draw the cell
-content. For this reasons (and for some others, see the TODOs section), it will
-work efficiently only for relatively small Excel files.
-
-:note: L{XLSGrid} **requires** the `xlrd` package from:
-
- http://pypi.python.org/pypi/xlrd
-
- Minimum version requirement for `xlrd` is 0.7.1. If you wish to have
- support for hyperlinks inside cells and rich text content, you need the
- SVN version of `xlrd`.
-
-:note: On Windows, it is **strongly** recommended to install Mark Hammonds'
- `pywin32` package:
-
- http://sourceforge.net/projects/pywin32/
-
- This will allow you to perfectly reproduce the appearance of the Excel
- worksheet in your instance of L{XLSGrid}.
-
-:warning: If Mark Hammonds' `pywin32` package is not available, the formatting
- capabilities of L{XLSGrid} are severely limited; for instance, you won't
- probably get the exact WYSIWYG between the Excel spreadsheet and L{XLSGrid}.
-
-:warning: L{XLSGrid} can only read Excel `.xls` files, not the newer versions
- `.xlsx` generated by Office 2007/2010. If you have a `.xlsx` file, you will
- need to save it in 1997-2003 Office compatibility mode.
-
-
-Currently this class provides a read-only subclass of `wx.grid.Grid`, with
-the following formatting features already implemented:
-
-* Cell background: support for any cell background colour and fill pattern
-  (hatching) in the Excel default set. There currently is no support for
-  gradient shading inside a cell as `xlrd` doesn't report this information.
-
-* Cell borders: support for all the border types and colours exposed by Excel
-  (left, top, bottom, right and diagonal borders, thin, double, thick, ect...
-  line styles).
-
-* Cell text: support for all kind of fonts (except strikethrough, but this is
-  a bug in wxWidgets), and font colours. As a subset of text/font capabilities,
-  L{XLSGrid} supports the following features found in Excel:
-
-  - Horizontal alignment: left, right, centered, left-indented;
-  - Vertical alignment: left, right, centered;
-  - Text direction: left-to-right or right-to-left;
-  - Text-wrapping: wrapping long texts inside a grid cell;
-  - Shrink-to-fit: text font is reduced until the text can fit in a one-line
-    inside the grid cell;
-  - Text rotation: text can be rotated from +90 to -90 degrees.
-
-* Cell rich text (new in version 0.2): support for strings containing partial
-  bold, italic and underlined text, change of font inside a string etc...
-  Cells with rich text content can not be multi-line and they will not honour
-  the `shrink-to-fit` and `wrapping` settings.
-
-* Cell text appearance: if you are using Mark Hammonds' `pywin32` package, the
-  text displayed in the L{XLSGrid} cells has exactly the same appearance as in
-  the Excel spreadsheet.
-
-* Cell comments (notes): if you are using Mark Hammonds' `pywin32` package,
-  cell comments (notes) are extracted and you will see a small red triangle at
-  the top-right corner of any cell containing a comment. Hovering with the
-  mouse on that cell will pop-up a "comment-window" displaying the comment
-  text (the comment window is based on `wx.lib.agw.supertooltip`).
-
-* Cell hyperlinks: starting from version 0.7.2 (SVN), `xlrd` is capable of
-  extracting hyperlinks from Excel cells. This will be appropriately displayed
-  in L{XLSGrid} with a cursor changing and a tooltip on that cell.
-
-* Cell merging: merged cells in the Excel spreadsheet will be correctly handled
-  by L{XLSGrid}.
-
-* Columns and rows sizes: L{XLSGrid} calculates the correct rows and columns
-  sizes based on the Excel reported values in characters. The calculations are
-  based on the default width of the text in 1/256 of the width of the zero
-  character, using default Excel font (first FONT record in the Excel file).
-
-
-And a lot more. Check the demo for an almost complete review of the functionalities.
-
-
-Usage
-=====
-
-Sample usage::
-
-    import wx
-    import xlrd
-    import os
-
-    import xlsgrid as XG
-
-    class MyFrame(wx.Frame):
-
-        def __init__(self):
-
-            wx.Frame.__init__(self, parent, -1, "XLSGrid Demo", size=(1000, 800))
-
-            filename = os.path.join(os.getcwd(), "Excel", "Example_1.xls")
-            sheetname = "Example_1"
-
-            book = xlrd.open_workbook(filename, formatting_info=1)
-
-            sheet = book.sheet_by_name(sheetname)
-            rows, cols = sheet.nrows, sheet.ncols
-
-            comments, texts = XG.ReadExcelCOM(filename, sheetname, rows, cols)
-
-            xls_grid = XG.XLSGrid(self)
-            xls_grid.PopulateGrid(book, sheet, texts, comments)
-
-
-    # our normal wxApp-derived class, as usual
-
-    app = wx.PySimpleApp()
-
-    frame = MyFrame(None)
-    app.SetTopWindow(frame)
-    frame.Show()
-
-    app.MainLoop()
-
-
-:note: Please note that you **have to** pass the keyword `formatting_info` to
- the method `xlrd.open_workbook` to obtain the cell formatting.
-
-
-TODOs
-=====
-
-1. L{XLSGrid} is sufficiently efficient and fast for reasonably small Excel files.
-   There might be some improvement to be made in the code to make it work with
-   bigger files and in a faster way;
-2. `wx.grid.Grid` seems to completely redraw itself at every resize event, even
-   if the cell content has not changed and it has not been damaged (this seems
-   to be fixed in wxPython 2.9.2.1);
-3. There is currently no support for strikethrough fonts, although `xlrd` correctly
-   reports this format. The issue is a bug in wxWidgets itself which doesn't
-   allow the creation of strikethrough fonts (http://trac.wxwidgets.org/ticket/9907).
-
-
-Supported Platforms
-===================
-
-L{XLSGrid} has been tested on the following platforms:
-  * Windows (Windows Vista and 7);
-
-
-Window Styles
-=============
-
-`No particular window styles are available for this class.`
-
-
-Events Processing
-=================
-
-`No custom events are available for this class.`
-
-
-License And Version
-===================
-
-L{XLSGrid} is distributed under the wxPython license.
-
-Latest Revision: Andrea Gavana @ 17 Aug 2011, 15.00 GMT
-
-Version 0.3
-
-"""
-
-# Version Info
-__version__ = "0.3"
-
-# Start the imports
-import wx
-import os
-
-try:
-    import xlrd
-except ImportError:
-    pass
-
-import datetime
-import string
-
-import wx.grid as gridlib
-
-from wx.lib.embeddedimage import PyEmbeddedImage
-from wx.lib.wordwrap import wordwrap
-
-import supertooltip as STT
-
-from math import pi, sin, cos
-from operator import attrgetter
-
-_hasWin32 = False
-
-if wx.Platform == "__WXMSW__":
-    try:
-        from win32com.client import Dispatch
-        import pywintypes
-        _hasWin32 = True
-    except ImportError:
-        pass
-
-
-#----------------------------------------------------------------------
-# Constants used to translate xlrd stuff into wxPython stuff
-#----------------------------------------------------------------------
-
-BOTTOM = wx.BOTTOM
-TOP = wx.TOP
-LEFT = wx.LEFT
-RIGHT = wx.RIGHT
-DIAGONAL = 2 << 7
-
-XF_BORDER_STYLES = {"bottom": BOTTOM, "left": LEFT, "right": RIGHT,
-                    "top": TOP, "diag": DIAGONAL}
-
-HORIZONTAL_ALIGNMENTS = {0: 0, 1: 0, 2: wx.ALIGN_CENTER_HORIZONTAL, 3: wx.ALIGN_RIGHT}
-VERTICAL_ALIGNMENTS   = {0: 0, 1: wx.ALIGN_CENTER_VERTICAL, 2: wx.ALIGN_BOTTOM,
-                         3: wx.ALIGN_CENTER_VERTICAL, 4:wx.ALIGN_CENTER_VERTICAL}
-
-NO_LINE = 0x0
-THIN = 0x1
-MEDIUM = 0x2
-DASHED = 0x3
-DOTTED = 0x4
-THICK = 0x5
-DOUBLE = 0x6
-HAIR = 0x7
-MEDIUM_DASHED = 0x8
-THIN_DASH_DOTTED = 0x9
-MEDIUM_DASH_DOTTED = 0xA
-THIN_DASH_DOT_DOTTED = 0xB
-MEDIUM_DASH_DOT_DOTTED = 0xC
-SLANTED_MEDIUM_DASH_DOTTED = 0xD
-
-XF_PEN_STYLES = {NO_LINE: (0, None), THIN: (1, wx.SOLID), MEDIUM: (2, wx.SOLID),
-                 DASHED: (1, wx.SHORT_DASH), DOTTED: (1, wx.DOT),
-                 THICK: (3, wx.SOLID), DOUBLE: (1, wx.SOLID), HAIR: (1, wx.DOT),
-                 MEDIUM_DASHED: (2, wx.LONG_DASH), THIN_DASH_DOTTED: (1, wx.DOT_DASH),
-                 MEDIUM_DASH_DOTTED: (2, wx.DOT_DASH), THIN_DASH_DOT_DOTTED: (1, wx.DOT_DASH),
-                 MEDIUM_DASH_DOT_DOTTED: (2, wx.DOT_DASH),
-                 SLANTED_MEDIUM_DASH_DOTTED: (2, wx.DOT_DASH)
-                 }
-
-XF_FONT_FAMILY = {0: wx.SWISS, 1: wx.ROMAN, 2: wx.SWISS,
-                  3: wx.MODERN, 4: wx.SCRIPT, 5: wx.DECORATIVE}
-
-# Unicode ordinals for Hebrew, Arabic and Syriac
-# I don't know if there are other RTL languages
-RTL_UNICODE = range(1424, 1872)
-
-# To guess text direction we exclude digits and punctuation
-USELESS_CHARS = string.punctuation + string.digits + " "
-
-
-#----------------------------------------------------------------------
-# Images used to draw the hatching on Excel cells background
-#----------------------------------------------------------------------
-
-_xls_background_01 = PyEmbeddedImage(
-    "iVBORw0KGgoAAAANSUhEUgAAAAQAAAAECAIAAAAmkwkpAAAAA3NCSVQICAjb4U/gAAAADElE"
-    "QVQImWNgIB0AAAA0AAEjQ4N1AAAAAElFTkSuQmCC")
-
-#----------------------------------------------------------------------
-_xls_background_02 = PyEmbeddedImage(
-    "iVBORw0KGgoAAAANSUhEUgAAAAQAAAAECAIAAAAmkwkpAAAAA3NCSVQICAjb4U/gAAAAFklE"
-    "QVQImWNgYGD4//8/lESwIAC7DABt4hfpI2a12wAAAABJRU5ErkJggg==")
-
-#----------------------------------------------------------------------
-_xls_background_03 = PyEmbeddedImage(
-    "iVBORw0KGgoAAAANSUhEUgAAAAQAAAAECAIAAAAmkwkpAAAAA3NCSVQICAjb4U/gAAAAE0lE"
-    "QVQImWP4//8/AxqACuGUAQBI+Qv1NTPP3AAAAABJRU5ErkJggg==")
-
-#----------------------------------------------------------------------
-_xls_background_04 = PyEmbeddedImage(
-    "iVBORw0KGgoAAAANSUhEUgAAAAQAAAAECAIAAAAmkwkpAAAAA3NCSVQICAjb4U/gAAAAH0lE"
-    "QVQImXXJsQ0AIAAEIc79d34LazsSwjbgPFXoOxdcCQwBh7OgqgAAAABJRU5ErkJggg==")
-
-#----------------------------------------------------------------------
-_xls_background_05 = PyEmbeddedImage(
-    "iVBORw0KGgoAAAANSUhEUgAAAAQAAAAECAIAAAAmkwkpAAAAA3NCSVQICAjb4U/gAAAAFUlE"
-    "QVQImWNgwAUY////D+cwIcsAAEggAwHHgMubAAAAAElFTkSuQmCC")
-
-#----------------------------------------------------------------------
-_xls_background_06 = PyEmbeddedImage(
-    "iVBORw0KGgoAAAANSUhEUgAAAAQAAAAECAIAAAAmkwkpAAAAA3NCSVQICAjb4U/gAAAAG0lE"
-    "QVQImWNkYGBgYGD4//8/AwMDEwMSwM0BAISAAwUnufp7AAAAAElFTkSuQmCC")
-
-#----------------------------------------------------------------------
-_xls_background_07 = PyEmbeddedImage(
-    "iVBORw0KGgoAAAANSUhEUgAAAAQAAAAECAIAAAAmkwkpAAAAA3NCSVQICAjb4U/gAAAAHklE"
-    "QVQImWNkYGBgYGD4//8/EgVh/P//H86HikH4APOCFO3yiGicAAAAAElFTkSuQmCC")
-
-#----------------------------------------------------------------------
-_xls_background_08 = PyEmbeddedImage(
-    "iVBORw0KGgoAAAANSUhEUgAAAAQAAAAECAIAAAAmkwkpAAAAA3NCSVQICAjb4U/gAAAAHUlE"
-    "QVQImWP4////////GSAAzvr//z8jmhADXCUAQSkU7eggG3gAAAAASUVORK5CYII=")
-
-#----------------------------------------------------------------------
-_xls_background_09 = PyEmbeddedImage(
-    "iVBORw0KGgoAAAANSUhEUgAAAAQAAAAECAIAAAAmkwkpAAAAA3NCSVQICAjb4U/gAAAAIElE"
-    "QVQImWNkYGBgYGD4//8/AwMDEwMy+P//P0QYXQYACtQI/cTE6U0AAAAASUVORK5CYII=")
-
-#----------------------------------------------------------------------
-_xls_background_10 = PyEmbeddedImage(
-    "iVBORw0KGgoAAAANSUhEUgAAAAQAAAAECAIAAAAmkwkpAAAAA3NCSVQICAjb4U/gAAAAG0lE"
-    "QVQImW3IsQ0AAAjAIPz/6LobGRmgclVfswpsCPmQczsGAAAAAElFTkSuQmCC")
-
-#----------------------------------------------------------------------
-_xls_background_11 = PyEmbeddedImage(
-    "iVBORw0KGgoAAAANSUhEUgAAAAQAAAAECAIAAAAmkwkpAAAAA3NCSVQICAjb4U/gAAAAFklE"
-    "QVQImWNgQAKM////h3OYkGVQOABvOgMD4NUKkwAAAABJRU5ErkJggg==")
-
-#----------------------------------------------------------------------
-_xls_background_12 = PyEmbeddedImage(
-    "iVBORw0KGgoAAAANSUhEUgAAAAQAAAAECAIAAAAmkwkpAAAAA3NCSVQICAjb4U/gAAAAG0lE"
-    "QVQImWNkYGD4//8/AwMDAwMDEwMSwM0BAI13AwWY+Mx+AAAAAElFTkSuQmCC")
-
-#----------------------------------------------------------------------
-_xls_background_13 = PyEmbeddedImage(
-    "iVBORw0KGgoAAAANSUhEUgAAAAQAAAAECAIAAAAmkwkpAAAAA3NCSVQICAjb4U/gAAAAI0lE"
-    "QVQImT3KsQ0AMAyAMMj/P9MhUUcLBCoAmEo9bFn7H/UBXEwMBN75abEAAAAASUVORK5CYII=")
-
-#----------------------------------------------------------------------
-_xls_background_14 = PyEmbeddedImage(
-    "iVBORw0KGgoAAAANSUhEUgAAAAQAAAAECAIAAAAmkwkpAAAAA3NCSVQICAjb4U/gAAAAIElE"
-    "QVQImT3KoQEAAAwCINz/P7tmI5C2QJKb2t6EYPMBOOUMBIWcMEIAAAAASUVORK5CYII=")
-
-#----------------------------------------------------------------------
-_xls_background_15 = PyEmbeddedImage(
-    "iVBORw0KGgoAAAANSUhEUgAAAAQAAAAECAIAAAAmkwkpAAAAA3NCSVQICAjb4U/gAAAAGUlE"
-    "QVQImWNgQAKMDAwM////h3CYkGVQOABmQwMDJpgq9gAAAABJRU5ErkJggg==")
-
-#----------------------------------------------------------------------
-_xls_background_16 = PyEmbeddedImage(
-    "iVBORw0KGgoAAAANSUhEUgAAAAQAAAAECAIAAAAmkwkpAAAAA3NCSVQICAjb4U/gAAAAHklE"
-    "QVQImWNgYGD4//8/lISzIAwEnxEqwMDAyMgIALKwF+2ym+hoAAAAAElFTkSuQmCC")
-
-#----------------------------------------------------------------------
-_xls_background_17 = PyEmbeddedImage(
-    "iVBORw0KGgoAAAANSUhEUgAAAAQAAAAECAIAAAAmkwkpAAAAA3NCSVQICAjb4U/gAAAAIklE"
-    "QVQImWNkYGD4//8/AwMDAwMDI5zFwMDABBVjZESXAQAc+AkAQ4bzDAAAAABJRU5ErkJggg==")
-
-#----------------------------------------------------------------------
-_xls_background_18 = PyEmbeddedImage(
-    "iVBORw0KGgoAAAANSUhEUgAAAAgAAAAECAIAAAA8r+mnAAAAA3NCSVQICAjb4U/gAAAAH0lE"
-    "QVQImWNkYGD4//8/AwZgxCrKwMDAhKKKkZGwDgA83QkAy10JvwAAAABJRU5ErkJggg==")
-
-#----------------------------------------------------------------------
-
-
-def SplitThousands(s, tSep=',', dSep='.'):
-    """
-    Splits a general float on thousands. GIGO on general input.
-
-    :param `s`: can be a float or a string, representing a number;
-    :param `tSep`: the character to be used as thousands separator;
-    :param `dSep`: the character to be used as decimal separator.
-
-    :returns: a string properly formatted with thousands and decimal
-     separators in it.
-
-    :note: This method is used only if Mark Hammonds' `pywin32` package is
-     not available to try and format a number in an intelligent way.
-
-    :note: This code has been obtained from the public domain:
-
-     http://code.activestate.com/recipes/498181-add-thousands-separator-commas-to-formatted-number/#c14
-
-    """
-
-    if not isinstance(s, basestring):
-        s = unicode(s, "utf-8", "ignore")
-
-    cnt = 0
-    numChars = dSep + '0123456789'
-    ls = len(s)
-
-    while cnt < ls and s[cnt] not in numChars:
-        cnt += 1
-
-    lhs = s[0:cnt]
-    s = s[cnt:]
-
-    if dSep == '':
-        cnt = -1
-    else:
-        cnt = s.rfind(dSep)
-
-    if cnt > 0:
-        rhs = dSep + s[cnt+1:]
-        s = s[:cnt]
-    else:
-        rhs = ''
-
-    splt = ''
-    while s != '':
-        splt = s[-3:] + tSep + splt
-        s = s[:-3]
-
-    return lhs + splt[:-1] + rhs
-
-
-def ReadExcelCOM(filename, sheetname, rows, cols):
-    """
-    Reads and Excel spreadsheet (a single worksheet) using Mark Hammonds' `pywin32`
-    package. If this package is not available, it returns two empty nested lists.
-
-    :param `filename`: a valid Excel `.xls` filename;
-    :param `sheetname`: the worksheet name inside the Excel file (i.e., the label
-     on the workbook tab at the bottom of the workbook);
-    :param `rows`: the number of significant rows in the worksheet, as returned
-     by `xlrd`;
-    :param `cols`: the number of significant columns in the worksheet, as returned
-     by `xlrd`.
-
-    :returns: two nested lists representing the comments (notes) on every cell and
-     the WYSIWYG representation of the cell content.
-
-    :note: If Mark Hammonds' `pywin32` package is not available, this method
-     returns two empty nested lists.
-    """
-
-    comments = [["" for i in range(cols)] for j in range(rows)]
-    texts    = [[None for i in range(cols)] for j in range(rows)]
-
-    if not _hasWin32:
-        return comments, texts
-
-    workbook = Excel(filename, sheetname)
-
-    for i in xrange(1, rows+1):
-        for j in xrange(1, cols+1):
-            texts[i-1][j-1]    = workbook.GetText(i, j)
-
-    comm_range = workbook.GetCommentsRange()
-    if comm_range is not None:
-        for comm in comm_range:
-            comments[comm.Row-1][comm.Column-1] = comm.Comment.Text()
-
-    workbook.Close()
-    return comments, texts
-
-
-def FontFromFont(font):
-    """
-    Creates a copy of the input `font`.
-
-    :param `font`: an instance of `wx.Font`.
-    """
-
-    new_font = wx.Font(font.GetPointSize(), font.GetFamily(), font.GetStyle(),
-                       font.GetWeight(), font.GetUnderlined(),
-                       font.GetFaceName(), font.GetEncoding())
-
-    return new_font
-
-
-class Excel(object):
-    """
-    A simple class that holds a COM interface to Excel.
-
-    By using the `win32com` module from Mark Hammonds' `pywin32` package, we
-    can manipulate various workbook/worksheet methods inside this class.
-    """
-
-    def __init__(self, filename, sheetname):
-        """
-        Default class constructor.
-
-        :param `filename`: a valid Excel `.xls` filename;
-        :param `sheetname`: the worksheet name inside the Excel file (i.e., the label
-         on the workbook tab at the bottom of the workbook).
-        """
-
-        self.xlApp = Dispatch('Excel.Application')
-        self.filename = filename
-        self.xlBook = self.xlApp.Workbooks.Open(filename)
-        self.sheet = self.xlBook.Worksheets(sheetname)
-
-        self.xlApp.Visible = 0
-
-
-    def Close(self, save=False):
-        """
-        Closes the Excel workbook, interrupting the COM interface.
-
-        :param `save`: ``True`` to save the changes you made to the workbook,
-         ``False`` otherwise.
-        """
-
-        self.xlBook.Close(SaveChanges=save)
-        del self.xlApp
-
-
-    def GetCommentsRange(self):
-        """
-        Returns a range of cells containing comments, using the VBA API.
-
-        """
-
-        try:
-            return self.sheet.Cells.SpecialCells(-4144)
-        except pywintypes.com_error:
-            return None
-
-
-    def GetText(self, row, col):
-        """
-        Returns the WYSIWYG text contained in a cell.
-
-        :param `row`: the row in which the cell lives;
-        :param `col`: the column in which the cell lives.
-
-        :note: The `row` and `col` parameters are not real Python index, as they
-         use the Excel indexing mode (i.e., first index is 1 and not 0).
-        """
-
-        cell = self.sheet.Cells(row, col)
-
-        if cell:
-            return cell.Text
-
-
-class XLSText(object):
-    """
-    This is a class which holds information about the cell content, in terms
-    of actual cell value, font, text colour, alignment and formatting.
-    """
-
-    def __init__(self, book, cell, xf_index, display_text=None, hyperlink=None, default_width=10):
-        """
-        Default class constructor.
-
-        :param `book`: an instance of the `xlrd.Book` class;
-        :param `cell`: an instance of `xlrd.sheet.Cell` class;
-        :param `xf_index`: an index into `xlrd.Book.xf_list`, which holds a
-         reference to the `xlrd.sheet.Cell` class (the actual cell for `xlrd`);
-        :param `display_text`: if Mark Hammonds' `pywin32` package is available,
-         this is the WYSIWYG cell content;
-        :param `hyperlink`: if this cell contains a hyperlink, it will be displayed
-         accordingly;
-        :param `default_width`: this is the default width of the text in 1/256
-         of the width of the zero character, using default Excel font (first FONT
-         record in the Excel file).
-
-        :note: If you are using version 0.7.1 or lower for `xlrd`, the *hyperlink*
-         parameter will always be ``None`` as this feature is available only in
-         `xlrd` 0.7.2 (SVN).
-        """
-
-        XFClass = book.xf_list[xf_index]
-
-        font = book.font_list[XFClass.font_index]
-        self.font = self.CreateFont(font)
-
-        text_colour = book.colour_map[font.colour_index]
-        self.text_colour = self.CreateTextColour(text_colour)
-
-        if display_text is not None:
-            self.value = display_text
-        else:
-            format = book.format_map[XFClass.format_key]
-            self.CreateFormat(format, cell, book.datemode)
-
-        alignment = XFClass.alignment
-        self.CreateAlignment(alignment, default_width)
-
-        if hyperlink is not None:
-            self.SetupHyperlink(hyperlink)
-        else:
-            self.tooltip = None
-
-
-    def CreateFont(self, font):
-        """
-        Creates a suitable wxPython font starting from an Excel font.
-
-        :param `font`: an instance of `xlrd.formatting.Font` class.
-
-        :note: There is currently no support for strikethrough fonts, although
-         `xlrd` correctly reports this format. The issue is a bug in wxWidgets
-         itself which doesn't allow the creation of strikethrough fonts. See
-         (http://trac.wxwidgets.org/ticket/9907).
-        """
-
-        style, bold, underline = wx.FONTSTYLE_NORMAL, wx.NORMAL, False
-        if font.italic:
-            style = wx.FONTSTYLE_ITALIC
-        if font.underline_type > 0:
-            underline = True
-        if font.weight > 600:
-            bold = wx.BOLD
-
-        family = XF_FONT_FAMILY[font.family]
-        name = font.name
-        size = int(font.height/20.0)
-
-        if font.escapement_type > 0:
-            # subscript/superscript
-            size = int(size*0.7)
-
-        # No support for strike-through fonts in wxWidgets
-#        if font.struck_out:
-#            style = wx.FONTFLAG_DEFAULT
-#            if bold:
-#                style += wx.FONTFLAG_BOLD
-#            if underline:
-#                style += wx.FONTFLAG_UNDERLINED
-#            if font.italic:
-#                style += wx.FONTFLAG_ITALIC
-#
-#            style += wx.FONTFLAG_STRIKETHROUGH
-#            self.font = wx.FFont(size, family, style, name.encode())
-#        else:
-
-        return wx.Font(size, family, style, bold, underline, name.encode())
-
-
-    def CreateTextColour(self, text_colour):
-        """
-        Creates a suitable wxPython colour for the text starting from a `xlrd`
-        tuple representing this colour.
-
-        :param `text_colour`: a tuple representing the RGB components of the
-         colour. If `text_colour` is ``None``, use the default ``wx.SYS_COLOUR_WINDOWTEXT``.
-        """
-
-        if text_colour is not None:
-            text_colour = wx.Colour(*text_colour)
-        else:
-            text_colour = wx.SystemSettings.GetColour(wx.SYS_COLOUR_WINDOWTEXT)
-
-        return text_colour
-
-
-    def CreateAlignment(self, alignment, default_width):
-        """
-        Creates a suitable wxPython alignment flag for the text starting from a
-        `xlrd` class representing this alignment.
-
-        :param `alignment`: an instance of `xlrd.formatting.XFAlignment` class;
-        :param `default_width`: this is the default width of the text in 1/256
-         of the width of the zero character, using default Excel font (first FONT
-         record in the Excel file).
-        """
-
-        hor_align, vert_align = alignment.hor_align, alignment.vert_align
-        self.horizontal_alignment = HORIZONTAL_ALIGNMENTS[hor_align]
-        self.vertical_alignment = VERTICAL_ALIGNMENTS[vert_align]
-
-        self.indent_level = alignment.indent_level
-        self.shrink_to_fit = alignment.shrink_to_fit
-        self.text_wrapped = alignment.text_wrapped
-
-        text_direction = 1
-
-        if alignment.text_direction == 0:
-            for char in self.value:
-                if char not in USELESS_CHARS:
-                    if ord(char) in RTL_UNICODE:
-                        text_direction = 2
-                        break
-
-        self.text_direction = text_direction
-        self.default_width = default_width
-
-        if alignment.rotation > 90:
-            self.rotation = 90 - alignment.rotation
-        else:
-            self.rotation = alignment.rotation
-
-
-    def CreateFormat(self, format, cell, datemode):
-        """
-        This method tries to guess the best format to apply to the current text
-        value.
-
-        :param `format`: an instance of `xlrd.formatting.Format` class;
-        :param `cell`: an instance of `xlrd.sheet.Cell` class;
-        :param `datemode`: the datemode associated with this Excel workbook.
-
-        :note: This method is used only if Mark Hammonds' `pywin32` package is
-         not available to try and format the cell text in an intelligent way.
-
-        :warning: The formatting applied by this method is severely limited; for
-         instance, you won't probably get the exact WYSIWYG between the Excel
-         spreadsheet and L{XLSGrid}.
-        """
-
-        ctype, value = cell.ctype, cell.value
-
-        self.value = "%s"%value
-        isDate = False
-
-        if ctype == xlrd.XL_CELL_DATE:
-            value = xlrd.xldate_as_tuple(value, datemode)
-            isDate = True
-        elif ctype in [xlrd.XL_CELL_EMPTY, xlrd.XL_CELL_BLANK]:
-            return
-        elif ctype == xlrd.XL_CELL_TEXT:
-            self.value = "%s"%value
-            return
-        elif ctype == xlrd.XL_CELL_ERROR:
-            value = xlrd.error_text_from_code(ctype)
-            self.value = "%s"%value
-            return
-
-        self.FormatString(value, isDate, format.format_str)
-
-
-    def FormatString(self, value, isDate, format_str):
-        """
-        This method tries to guess the best format to apply to the current text
-        value.
-
-        :param `value`: the actual raw cell text value;
-        :param `isDate`: ``True`` if this value represents a `xlrd` date object,
-         ``False`` otherwise;
-        :param `format_str`: the actual formatting string as extracted from Excel.
-
-        :note: This method is used only if Mark Hammonds' `pywin32` package is
-         not available to try and format the cell text in an intelligent way.
-
-        :warning: The formatting applied by this method is severely limited; for
-         instance, you won't probably get the exact WYSIWYG between the Excel
-         spreadsheet and L{XLSGrid}.
-        """
-
-        if "General" in format_str:
-            self.value = "%s"%value
-            return
-
-        number_format = format_str
-        currency = percentage = ""
-
-        if not isDate:
-            symbol = ""
-            split = format_str.split()
-            if len(split) > 1:
-                # Accounting and currency shit
-                currency = split[0].split(".")[0] + "."
-                number_format = ".".join(split[1:])
-
-            if "%" in number_format:
-                percentage = "%"
-                value = 100*value
-                number_format = number_format[0:-1]
-
-            representation = "%d"
-            if "." in number_format:
-                split = number_format.split(".")
-                num_decimals = len(split[1])
-                representation = "%0." + str(num_decimals) + "f"
-
-            try:
-                value = representation%value
-            except ValueError:
-                # Fall back to string
-                value = unicode(value, "utf-8", "ignore")
-
-            if "#," in number_format:
-                value = SplitThousands(value)
-
-            value = currency + value + percentage
-
-        else:
-            number_format = format_str.replace("\\", "")
-            number_format = number_format.replace("-", "-%").replace("/", "/%")
-            value = datetime.datetime(*value)
-            try:
-                value = value.strftime(number_format)
-            except (ValueError, TypeError):
-                value = value.strftime("%d.%m.%Y")
-
-        self.value = value
-
-
-    def SetupHyperlink(self, hyperlink):
-        """
-        Sets up the cell text value in case it represents a hyperlink.
-
-        :param `hyperlink`: an instance of `xlrd.sheet.hyperlink`.
-
-        :note: If you are using version 0.7.1 or lower for `xlrd`, the *hyperlink*
-         parameter will always be ``None`` as this feature is available only in
-         `xlrd` 0.7.2 (SVN).
-        """
-
-        url = (hyperlink.url_or_path and [hyperlink.url_or_path] or [hyperlink.textmark])[0]
-        self.tooltip = url
-
-
-    def IsHyperLink(self):
-        """
-        Returns whether the cell text is representing a hyperlink.
-
-        :returns: ``True`` if the cell text represents a hyperlink, ``False``
-         otherwise.
-        """
-
-        return self.tooltip is not None
-
-
-    def CombineAttr(self, attr):
-        """
-        Combines the input attribute `attr` with the features of the L{XLSText} class.
-
-        :param `attr`: an instance of `wx.grid.GridCellAttr`.
-        """
-
-        attr.SetAlignment(self.horizontal_alignment, self.vertical_alignment)
-        attr.SetTextColour(self.text_colour)
-        attr.SetFont(self.font)
-
-
-    def GetValue(self):
-        """ Returns the string representation of the cell text value. """
-
-        return self.value
-
-
-    def Draw(self, dc, rect):
-        """
-        Actually draws the text value on a grid cell.
-
-        :param `dc`: an instance of `wx.DC`;
-        :param `rect`: an instance of `wx.Rect`, representing the cell rectangle.
-        """
-
-        new_rect = wx.Rect(*rect)
-
-        xshift = yshift = 0
-        if self.rotation:
-            xshift = cos(self.rotation*pi/180)
-            yshift = sin(self.rotation*pi/180)
-
-        dc.SetTextForeground(self.text_colour)
-        dc.SetFont(self.font)
-
-        value = self.value
-        text_width, text_height = dc.GetTextExtent(value)
-
-        default_width = int(round(float(self.default_width)*text_width/256.0))
-
-        indentation = int(256.0*default_width/float(self.default_width))
-
-        if xshift == 0 and self.indent_level:
-            new_rect.SetLeft(new_rect.x + indentation)
-        else:
-            if self.horizontal_alignment == wx.ALIGN_LEFT:
-                new_rect.SetLeft(new_rect.x + 3)
-            elif self.horizontal_alignment == wx.ALIGN_RIGHT:
-                new_rect.SetWidth(new_rect.width - 1)
-
-        new_width = rect.width
-
-        if xshift > 0:
-            new_width = new_width/xshift
-
-        if self.shrink_to_fit:
-
-            font = FontFromFont(self.font)
-            point_size = font.GetPointSize()
-
-            while 1:
-                value = wordwrap(self.value, new_width, dc)
-                if "\n" not in value or point_size < 2:
-                    break
-
-                point_size -= 1
-                font.SetPointSize(point_size)
-                dc.SetFont(font)
-
-        elif self.text_wrapped:
-
-            value = wordwrap(self.value, new_width, dc)
-            text_width, text_height, dummy = dc.GetMultiLineTextExtent(value)
-
-        if self.rotation:
-            if self.shrink_to_fit:
-                text_width, text_height = dc.GetTextExtent(value)
-
-            xc, yc = (rect.x+rect.width/2, rect.y+rect.height/2)
-            xp = xc - (text_width/2)*xshift - (text_height/2)*yshift
-            yp = yc + (text_width/2)*yshift - (text_height/2)*xshift
-
-            dc.DrawRotatedText(value, xp, yp, self.rotation)
-
-        else:
-
-            dc.DrawLabel(value, new_rect, self.horizontal_alignment|self.vertical_alignment)
-
-
-class XLSRichText(XLSText):
-    """
-    This is a class which holds information about the cell content, in terms
-    of actual cell value, font, text colour, alignment and formatting. In addition
-    to what L{XLSText} does, this class attempts to handle cells with rich text
-    content.
-    """
-
-    def __init__(self, book, cell, xf_index, display_text=None, hyperlink=None, rich_text=None, default_width=10):
-        """
-        Default class constructor.
-
-        :param `book`: an instance of the `xlrd.Book` class;
-        :param `cell`: an instance of `xlrd.sheet.Cell` class;
-        :param `xf_index`: an index into `xlrd.Book.xf_list`, which holds a
-         reference to the `xlrd.sheet.Cell` class (the actual cell for `xlrd`);
-        :param `display_text`: if Mark Hammonds' `pywin32` package is available,
-         this is the WYSIWYG cell content;
-        :param `hyperlink`: if this cell contains a hyperlink, it will be displayed
-         accordingly;
-        :param `rich_text`: if this cell contains text in rich text format, L{XLSGrid}
-         will do its best to render the text as rich text;
-        :param `default_width`: this is the default width of the text in 1/256
-         of the width of the zero character, using default Excel font (first FONT
-         record in the Excel file).
-
-        :note: If you are using version 0.7.1 or lower for `xlrd`, the *hyperlink*
-         parameter will always be ``None`` as this feature is available only in
-         `xlrd` 0.7.2 (SVN).
-
-        :note: If you are using version 0.7.1 or lower for `xlrd`, this class will
-         note be used by L{XLSGrid}.
-
-        :warning: This class currently supports only single-line non-rotated text,
-         and it discards properties like `shrink-to-fit` and `wrapping`.
-        """
-
-        XLSText.__init__(self, book, cell, xf_index, display_text, hyperlink, default_width)
-
-        self.BuildChunks(book, xf_index, rich_text)
-
-
-    def BuildChunks(self, book, xf_index, rich_text):
-        """
-        Splits the cell content accordingly to their rich text format index.
-
-        :param `book`: an instance of the `xlrd.Book` class;
-        :param `xf_index`: an index into `xlrd.Book.xf_list`, which holds a
-         reference to the `xlrd.sheet.Cell` class (the actual cell for `xlrd`);
-        :param `rich_text`: if this cell contains text in rich text format, L{XLSGrid}
-         will do its best to render the text as rich text.
-        """
-
-        XFClass = book.xf_list[xf_index]
-        offset, index = rich_text[0]
-
-        if offset != 0:
-            new_tuple = (0, XFClass.font_index)
-            rich_text.insert(0, new_tuple)
-
-        value = self.value
-        rich_text.append((len(value), rich_text[-1][1]))
-        attributes = []
-
-        for indx in xrange(len(rich_text)-1):
-            offset_start, index_start = rich_text[indx]
-            offset_end, index_end = rich_text[indx+1]
-
-            chunk = value[offset_start:offset_end]
-
-            font = book.font_list[index_start]
-            ffont = self.CreateFont(font)
-            text_colour = book.colour_map[font.colour_index]
-            colour = self.CreateTextColour(text_colour)
-
-            ffont.escapement = font.escapement_type
-            attributes.append([chunk, ffont, colour])
-
-        self.attributes = attributes
-
-
-    def Measure(self, dc):
-        """
-        Convenience method to measure the maximum height and total width of all
-        the chunks of text composing our rich text string.
-
-        :param `dc`: an instance of `wx.DC`.
-        """
-
-        maxH = -1
-        full_width = 0
-        for chunk, font, colour in self.attributes:
-            dc.SetFont(font)
-            width, height, descent, leading = dc.GetFullTextExtent(chunk, font)
-            maxH = max(maxH, height-leading)
-            full_width += width
-
-        return maxH, full_width
-
-
-    def Draw(self, dc, rect):
-        """
-        Actually draws all the chunks of text on a grid cell, one by one.
-
-        :param `dc`: an instance of `wx.DC`;
-        :param `rect`: an instance of `wx.Rect`, representing the cell rectangle.
-        """
-
-        new_rect = wx.Rect(*rect)
-
-        text_width, text_height = dc.GetTextExtent(self.value)
-        default_width = int(round(float(self.default_width)*text_width/256.0))
-        indentation = int(256.0*default_width/float(self.default_width))
-
-        maxH, full_width = self.Measure(dc)
-
-        if self.indent_level:
-            new_rect.SetLeft(new_rect.x + indentation)
-        else:
-            if self.horizontal_alignment == wx.ALIGN_LEFT:
-                new_rect.SetLeft(new_rect.x + 3)
-            elif self.horizontal_alignment == wx.ALIGN_RIGHT:
-                new_rect.SetLeft(new_rect.x + (new_rect.width - full_width) - 1)
-            else:
-                space = int((new_rect.width - full_width)/2.0)
-                new_rect.SetLeft(new_rect.x + space)
-                new_rect.SetWidth(full_width+space)
-
-        if self.vertical_alignment == wx.ALIGN_TOP:
-            vspace = 0
-        elif self.vertical_alignment == wx.ALIGN_BOTTOM:
-            vspace = (new_rect.height - maxH - 1)
-        else:
-            vspace = int((new_rect.height - maxH)/2.0)
-
-        start = new_rect.x
-        y = new_rect.y
-
-        for chunk, font, colour in self.attributes:
-            dc.SetTextForeground(colour)
-            dc.SetFont(font)
-            width, height, descent, leading = dc.GetFullTextExtent(chunk, font)
-            if font.escapement > 0:
-                height = height*0.7
-
-            ypos = y-height+maxH+vspace
-
-            if font.escapement == 1:
-                ypos = ypos - maxH + height
-
-            dc.DrawText(chunk, start, ypos)
-            start += width
-
-
-class XLSBackground(object):
-    """
-    This is a class which holds information about the cell background, in terms
-    of background colour and background pattern (hatching).
-    """
-
-    def __init__(self, book, xf_index):
-        """
-        Default class constructor.
-
-        :param `book`: an instance of the `xlrd.Book` class;
-        :param `xf_index`: an index into `xlrd.Book.xf_list`, which holds a
-         reference to the `xlrd.sheet.Cell` class (the actual cell for `xlrd`).
-        """
-
-        XFClass = book.xf_list[xf_index]
-
-        background = XFClass.background
-        background_colour = book.colour_map[background.background_colour_index]
-        pattern_colour = book.colour_map[background.pattern_colour_index]
-        fill_pattern = background.fill_pattern
-
-        self.CreateBackgroundColour(background_colour, pattern_colour, fill_pattern)
-
-
-    def CreateBackgroundColour(self, background_colour, pattern_colour, fill_pattern):
-        """
-        Creates a suitable wxPython colour for the cell background starting from
-        a `xlrd` tuple representing this colour.
-
-        :param `background_colour`: a tuple representing the RGB components of the
-         cell background colour. If `background_colour` is ``None``, use the
-         default ``wx.SYS_COLOUR_WINDOW``;
-        :param `pattern_colour`: a tuple representing the RGB components of the
-         cell pattern colour;
-        :param `fill_pattern`: the pattern to use to draw hatches on top of the
-         background.
-        """
-
-        if background_colour is not None:
-            background_colour = wx.Colour(*background_colour)
-        else:
-            background_colour = wx.SystemSettings.GetColour(wx.SYS_COLOUR_WINDOW)
-
-        if pattern_colour is not None:
-            pattern_colour = wx.Colour(*pattern_colour)
-
-        self.background_brush = wx.Brush(background_colour)
-        self.background_colour = background_colour
-
-        self.fill_brush = None
-
-        if fill_pattern <= 0:
-            return
-
-        r, g, b = pattern_colour
-
-        fill_image = eval("_xls_background_%02d.GetImage()"%fill_pattern)
-        fill_image.Replace(0, 0, 0, r, g, b)
-        r, g, b = background_colour.Red(), background_colour.Green(), background_colour.Blue()
-        fill_image.Replace(255, 255, 255, r, g, b)
-        fill_bitmap = fill_image.ConvertToBitmap()
-
-        self.fill_brush = wx.BrushFromBitmap(fill_bitmap)
-
-
-    def CombineAttr(self, attr):
-        """
-        Combines the input attribute `attr` with the features of the L{XLSBackground} class.
-
-        :param `attr`: an instance of `wx.grid.GridCellAttr`.
-        """
-
-        attr.SetBackgroundColour(self.background_colour)
-        return attr
-
-
-    def Draw(self, dc, rect):
-        """
-        Actually draws the cell background and pattern hatching on a grid cell.
-
-        :param `dc`: an instance of `wx.DC`;
-        :param `rect`: an instance of `wx.Rect`, representing the cell rectangle.
-        """
-
-        dc.SetClippingRect(rect)
-
-        dc.SetBackgroundMode(wx.SOLID)
-        dc.SetBrush(self.background_brush)
-        dc.SetPen(wx.TRANSPARENT_PEN)
-        dc.DrawRectangleRect(rect)
-
-        if self.fill_brush:
-
-            dc.SetBrush(self.fill_brush)
-            dc.SetBackgroundMode(wx.TRANSPARENT)
-            dc.DrawRectangleRect(rect)
-
-        dc.DestroyClippingRegion()
-
-
-class XLSBorder(object):
-    """
-    This is a class which holds information about a single cell border, in terms
-    of its location (top, left, bottom, right, diagonal), its colour, width and
-    shape.
-    """
-
-    def __init__(self, location, line_style, border_colour, default_colour, diagonals):
-        """
-        Default class constructor.
-
-        :param `location`: the actual border location (top, left, bottom, right,
-         diagonal);
-        :param `line_style`: the line style used by Excel to draw this border;
-        :param `border_colour`: the colour used by Excel to draw this border;
-        :param `default_colour`: the "magic" colour used by Excel to draw non-custom
-         border lines;
-        :param `diagonals`: a tuple containing whether or not to draw the up and down
-         diagonal borders.
-        """
-
-        self.draw_priority = 2
-
-        if line_style == NO_LINE:
-
-            if border_colour == (0, 0, 0):
-                self.draw_priority = 0
-                border_colour = wx.Colour(*default_colour)
-            else:
-                self.draw_priority = 1
-                border_colour = wx.BLACK
-
-            self.pen = wx.Pen(border_colour, 1, wx.SOLID)
-            pen_style = THIN
-
-        else:
-
-            if border_colour == (0, 0, 0):
-                border_colour = wx.Colour(*default_colour)
-                self.draw_priority = 2
-            elif border_colour is None:
-                border_colour = wx.BLACK
-                self.draw_priority = 2
-            else:
-                border_colour = wx.Colour(*border_colour)
-
-            pen_width, pen_style = XF_PEN_STYLES[line_style]
-            if pen_width > 2:
-                self.draw_priority = 4
-            elif pen_width > 1:
-                self.draw_priority = 3
-
-            self.pen = wx.Pen(border_colour, pen_width, pen_style)
-
-        self.diagonals = diagonals
-        self.location = location
-        self.pen_style = pen_style
-        self.line_style = line_style
-
-
-    def Draw(self, dc, rect):
-        """
-        Actually draws the cell border.
-
-        :param `dc`: an instance of `wx.DC`;
-        :param `rect`: an instance of `wx.Rect`, representing the cell rectangle.
-        """
-
-        dc.SetBackgroundMode(wx.TRANSPARENT)
-        dc.SetPen(self.pen)
-
-        if self.location == DIAGONAL:
-            self.DrawDiagonals(dc, rect)
-        else:
-            self.DrawBorder(dc, rect)
-
-
-    def DrawDiagonals(self, dc, rect):
-        """
-        Actually draws the cell diagonal border.
-
-        :param `dc`: an instance of `wx.DC`;
-        :param `rect`: an instance of `wx.Rect`, representing the cell rectangle.
-        """
-
-        diag_up, diag_down = self.diagonals
-
-        if diag_down:
-            xstart, ystart = rect.GetTopLeft()
-            xend, yend = rect.GetBottomRight()
-
-            if self.line_style == DOUBLE:
-                dc.DrawLine(xstart+2, ystart, xend, yend-2)
-                dc.DrawLine(xstart, ystart+2, xend-2, yend)
-            else:
-                dc.DrawLine(xstart, ystart, xend, yend)
-
-        if diag_up:
-
-            xstart, ystart = rect.GetBottomLeft()
-            xend, yend = rect.GetTopRight()
-
-            if self.line_style == DOUBLE:
-                dc.DrawLine(xstart, ystart-2, xend-2, yend)
-                dc.DrawLine(xstart+2, ystart, xend, yend+2)
-            else:
-                dc.DrawLine(xstart, ystart, xend, yend)
-
-
-    def DrawBorder(self, dc, rect):
-        """
-        Actually draws the cell border (one of left, right, bottom, top).
-
-        :param `dc`: an instance of `wx.DC`;
-        :param `rect`: an instance of `wx.Rect`, representing the cell rectangle.
-        """
-
-        pen_width = self.pen.GetWidth()
-        location = self.location
-        new_rect = wx.Rect(*rect)
-
-        x, y, w, h = new_rect
-        line_style = self.line_style
-
-        shift = 0
-        if pen_width == 2:
-            shift = pen_width - 1
-        if pen_width > 2:
-            shift = pen_width - 2
-
-        if location == BOTTOM:
-
-            if self.draw_priority < 2:
-                return
-
-            if line_style == DOUBLE:
-                dc.DrawLine(x, y+h-1, x+w, y+h-1)
-                dc.DrawLine(x, y+h+1, x+w, y+h+1)
-            else:
-                dc.DrawLine(x+1, y+h,   x+w, y+h)
-
-
-        elif location == TOP:
-
-            if line_style == DOUBLE:
-                dc.DrawLine(x, y-1, x+w, y-1)
-                dc.DrawLine(x, y+1, x+w, y+1)
-            else:
-                dc.DrawLine(x+1, y+shift,   x+w, y+shift)
-
-        elif location == LEFT:
-
-            if line_style == DOUBLE:
-                dc.DrawLine(x-1, y, x-1, y+h)
-                dc.DrawLine(x+1, y, x+1, y+h)
-            else:
-                dc.DrawLine(x+shift,   y+1, x+shift,   y+h)
-
-        elif location == RIGHT:
-
-            if self.draw_priority < 2:
-                return
-
-            if line_style == DOUBLE:
-                dc.DrawLine(x+w-1, y, x+w-1, y+h)
-                dc.DrawLine(x+w+1, y, x+w+1, y+h)
-            else:
-                dc.DrawLine(x+w+1, y+1, x+w+1, y+h)
-
-
-class XLSBorderFactory(object):
-    """
-    This is a factory class which holds information about all the borders in a
-    cell. Its implementation and use is merely to simplify the handling of the
-    different cell borders (left, top, bottom, right, diagonal).
-    """
-
-    def __init__(self, book, border, default_colour):
-        """
-        Default class constructor.
-
-        :param `book`: an instance of the `xlrd.Book` class;
-        :param `border`: an instance of `xlrd.formatting.XFBorder` class;
-        :param `default_colour`: the "magic" colour used by Excel to draw non-custom
-         border lines.
-        """
-
-        borders = {}
-        diagonals = border.diag_up, border.diag_down
-
-        for label, location in XF_BORDER_STYLES.items():
-            line_style = getattr(border, "%s_line_style"%label)
-            colour_index = getattr(border, "%s_colour_index"%label)
-            border_colour = book.colour_map[colour_index]
-
-            border_class = XLSBorder(location, line_style, border_colour, default_colour, diagonals)
-            borders[location] = border_class
-
-        self.draw_priority = sorted(borders.values(), key=attrgetter('draw_priority'))
-
-
-    def Draw(self, dc, rect):
-        """
-        Actually draws all the cell borders based on their drawing priority.
-
-        :param `dc`: an instance of `wx.DC`;
-        :param `rect`: an instance of `wx.Rect`, representing the cell rectangle.
-
-        :note: The drawing priority is assigned depending on if the border is a
-         custom one or not. Customized borders are drawn last.
-        """
-
-        for border in self.draw_priority:
-            border.Draw(dc, rect)
-
-
-class XLSComment(object):
-    """
-    This is a class which holds information about the content of the "comment
-    window" (aka note) in Excel.
-
-    :note: If Mark Hammonds' `pywin32` package is not available, this class can
-     not be used.
-    """
-
-    def __init__(self, comment):
-        """
-        Default class constructor.
-
-        :param `comment`: the actual text contained in the Excel cell comment (note).
-        """
-
-        self.comment = comment
-
-
-    def Draw(self, dc, rect):
-        """
-        Actually draws a small red triangle in the top-right corder of the cell
-        to indicate that a comment is present.
-
-        :param `dc`: an instance of `wx.DC`;
-        :param `rect`: an instance of `wx.Rect`, representing the cell rectangle.
-        """
-
-        right = rect.GetTopRight()
-        points = [wx.Point(right.x-5, right.y),
-                  right,
-                  wx.Point(right.x, right.y+5)]
-
-        dc.SetBrush(wx.RED_BRUSH)
-        dc.SetPen(wx.RED_PEN)
-        dc.DrawPolygon(points)
-
-
-class XLSCell(object):
-    """
-    This is a class which holds information about a single cell in L{XLSGrid}.
-    It stores (via auxiliary classes), all details about cell background, text,
-    font, colours and borders.
-    """
-
-    def __init__(self, book, cell, xf_index, xls_text, xls_comment, hyperlink, rich_text, default_width, default_colour):
-        """
-        Default class constructor.
-
-        :param `book`: an instance of the `xlrd.Book` class;
-        :param `cell`: an instance of `xlrd.sheet.Cell` class;
-        :param `xf_index`: an index into `xlrd.Book.xf_list`, which holds a
-         reference to the `xlrd.sheet.Cell` class (the actual cell for `xlrd`);
-        :param `xls_text`: the actual WYSIWYG cell text, if available;
-        :param `xls_comment`: the cell comment (note), if any;
-        :param `hyperlink`: an instance of `xlrd.sheet.hyperlink`;
-        :param `rich_text`: if this cell contains text in rich text format, L{XLSGrid}
-         will do its best to render the text as rich text;
-        :param `default_width`: this is the default width of the text in 1/256
-         of the width of the zero character, using default Excel font (first FONT
-         record in the Excel file);
-        :param `default_colour`: the "magic" colour used by Excel to draw non-custom
-         border lines.
-
-        :note: If you are using version 0.7.1 or lower for `xlrd`, the *hyperlink*
-         parameter will always be ``None`` as this feature is available only in
-         `xlrd` 0.7.2 (SVN).
-
-        :note: If you are using version 0.7.1 or lower for `xlrd`, the `rich_text`
-         parameter will always be ``None`` as this feature is available only in
-         `xlrd` 0.7.2 (SVN).
-
-        :note: if Mark Hammonds' `pywin32` package is not available, the `xls_text`
-         parameter will almost surely not be the WYSIWYG representation of the cell
-         text.
-
-        :note: If Mark Hammonds' `pywin32` package is not available, the `xls_comment`
-         parameter will always be ``None``.
-        """
-
-        self.size = 1, 1
-
-        self.comment = None
-        self.hyperlink = None
-
-        self.SetupCell(book, cell, xf_index, xls_text, xls_comment, hyperlink, rich_text, default_width, default_colour)
-
-
-    def SetupCell(self, book, cell, xf_index, xls_text, xls_comment, hyperlink, rich_text, default_width, default_colour):
-        """
-        Actually sets up the L{XLSCell} class. This is an auxiliary method to
-        avoid cluttering the L{__init__} method.
-
-        :param `book`: an instance of the `xlrd.Book` class;
-        :param `cell`: an instance of `xlrd.sheet.Cell` class;
-        :param `xf_index`: an index into `xlrd.Book.xf_list`, which holds a
-         reference to the `xlrd.sheet.Cell` class (the actual cell for `xlrd`);
-        :param `xls_text`: the actual WYSIWYG cell text, if available;
-        :param `xls_comment`: the cell comment (note), if any;
-        :param `hyperlink`: an instance of `xlrd.sheet.hyperlink`;
-        :param `rich_text`: if this cell contains text in rich text format, L{XLSGrid}
-         will do its best to render the text as rich text;
-        :param `default_width`: this is the default width of the text in 1/256
-         of the width of the zero character, using default Excel font (first FONT
-         record in the Excel file);
-        :param `default_colour`: the "magic" colour used by Excel to draw non-custom
-         border lines.
-
-        :note: If you are using version 0.7.1 or lower for `xlrd`, the *hyperlink*
-         parameter will always be ``None`` as this feature is available only in
-         `xlrd` 0.7.2 (SVN).
-
-        :note: If you are using version 0.7.1 or lower for `xlrd`, the `rich_text`
-         parameter will always be ``None`` as this feature is available only in
-         `xlrd` 0.7.2 (SVN).
-
-        :note: if Mark Hammonds' `pywin32` package is not available, the `xls_text`
-         parameter will almost surely not be the WYSIWYG representation of the cell
-         text.
-
-        :note: If Mark Hammonds' `pywin32` package is not available, the `xls_comment`
-         parameter will always be ``None``.
-        """
-
-        cvalue = cell.value
-        self.raw_value = cvalue
-
-        if rich_text:
-            self.text = XLSRichText(book, cell, xf_index, xls_text, hyperlink, rich_text, default_width)
-        else:
-            self.text = XLSText(book, cell, xf_index, xls_text, hyperlink, default_width)
-
-        self.background = XLSBackground(book, xf_index)
-
-        XFClass = book.xf_list[xf_index]
-        border = XFClass.border
-
-        self.borders = XLSBorderFactory(book, border, default_colour)
-
-        if xls_comment:
-            self.comment = XLSComment(xls_comment)
-
-        self.attr = None
-
-
-    def GetAttr(self):
-        """
-        Returns the attribute to use for this specific cell.
-
-        :returns: an instance of `wx.grid.GridCellAttr`.
-        """
-
-        if self.attr is not None:
-            self.attr.IncRef()
-            return self.attr
-
-        attr = gridlib.GridCellAttr()
-
-        attr.SetRenderer(XLSRenderer(self))
-
-        attr.SetSize(*self.size)
-        attr.SetOverflow(True)
-        self.attr = attr
-        self.attr.IncRef()
-
-        return self.attr
-
-
-    def GetValue(self):
-        """ Returns the actual WYSIWYG representation of the cell value. """
-
-        return self.text.GetValue()
-
-
-    def SetValue(self, value):
-        """
-        Sets the actual WYSIWYG representation of the cell value.
-
-        :param `value`: the current text value to insert in the cell.
-
-        :note: This method is currently unused as everything is handled inside the
-         L{XLSText} class.
-
-        :see: L{GetValue}
-        """
-
-        self.value = value
-
-
-    def SetCellSize(self, rows, cols):
-        """
-        Sets the size of the cell.
-
-        Specifying a value of more than 1 in `rows` or `cols` will make the cell
-        at (`row`, `col`) span the block of the specified size, covering the other
-        cells which would be normally shown in it. Passing 1 for both arguments
-        resets the cell to normal appearance.
-
-        :param `rows`: number of rows to be occupied by this cell, must be >= 1;
-        :param `cols`: number of columns to be occupied by this cell, must be >= 1.
-        """
-
-        self.size = (rows, cols)
-
-
-    def GetComment(self):
-        """
-        Returns the cell comment, if any.
-
-        :returns: an instance of L{XLSComment}.
-
-        :note: If Mark Hammonds' `pywin32` package is not available, this method
-         always returns ``None``.
-        """
-
-        return self.comment
-
-
-class XLSRenderer(gridlib.PyGridCellRenderer):
-    """
-    This class is responsible for actually drawing the cell in the grid.
-
-    """
-
-    def __init__(self, cell):
-        """
-        Default class constructor.
-
-        :param `cell`: an instance of L{XLSCell}.
-        """
-
-        gridlib.PyGridCellRenderer.__init__(self)
-        self.cell = cell
-
-
-    def Draw(self, grid, attr, dc, rect, row, col, isSelected):
-        """
-        Draw the given cell on the provided `dc` inside the given rectangle using
-        default or selected state corresponding to the `isSelected` value.
-
-        :param `grid`: an instance of `wx.grid.Grid`;
-        :param `attr`: an instance of `wx.grid.GridCellAttr`;
-        :param `dc`: an instance of `wx.DC`;
-        :param `rect`: an instance of `wx.Rect`, representing the cell rectangle;
-        :param `row`: the row in which this cell lives;
-        :param `col`: the column in which this cell lives;
-        :param `isSelected`: ``True`` if the cell is selected, ``False`` otherwise.
-        """
-
-        # clear the background
-        dc.SetBackgroundMode(wx.SOLID)
-
-        cell = self.cell
-
-        cell.background.Draw(dc, rect)
-
-        if cell.borders:
-            cell.borders.Draw(dc, rect)
-
-        cell.text.Draw(dc, rect)
-
-        if cell.comment:
-            cell.comment.Draw(dc, rect)
-
-        if isSelected:
-
-            gdc = wx.GCDC(dc)
-
-            sys_colour = wx.SystemSettings.GetColour(wx.SYS_COLOUR_HIGHLIGHT)
-            brush_colour = wx.Colour(sys_colour.Red(), sys_colour.Green(), sys_colour.Blue(), 90)
-
-            gdc.SetBrush(wx.Brush(brush_colour))
-            gdc.SetPen(wx.TRANSPARENT_PEN)
-
-            gdc.DrawRectangleRect(rect)
-
-
-class XLSTable(gridlib.PyGridTableBase):
-    """
-    The almost abstract base class for grid tables.
-
-    A grid table is responsible for storing the grid data and, indirectly, grid
-    cell attributes. The data can be stored in the way most convenient for the
-    application but has to be provided in string form to `wx.grid.Grid`.
-    """
-
-    def __init__(self, grid, cells, rows, cols):
-        """
-        Default class constructor.
-
-        :param `grid`: an instance of `wx.grid.Grid`;
-        :param `cells`: a Python dictionary. For every key `(row, col)`, the
-         corresponding value is an instance of L{XLSCell};
-        :param `rows`: the number of rows in the table;
-        :param `cols`: the number of columns in the table.
-        """
-
-        # The base class must be initialized *first*
-        gridlib.PyGridTableBase.__init__(self)
-
-        self.cells = cells
-        self.dimens = (rows, cols)
-
-
-    def GetNumberCols(self):
-        """ Returns the number of columns in the table. """
-
-        return self.dimens[1]
-
-
-    def GetNumberRows(self):
-        """ Returns the number of rows in the table. """
-
-        return self.dimens[0]
-
-
-    def GetValue(self, row, col):
-        """
-        Returns the cell content for the specified row and column.
-
-        :param `row`: the row in which this cell lives;
-        :param `col`: the column in which this cell lives.
-        """
-
-        cell = self.cells[(row, col)]
-        return cell.GetValue()
-
-
-    def SetValue(self, row, col, value):
-        """
-        sets the cell content for the specified row and column.
-
-        :param `row`: the row in which this cell lives;
-        :param `col`: the column in which this cell lives;
-        :param `value`: the new value to assign to the specified cell.
-        """
-
-        cell = self.cells[(row, col)]
-        cell.SetValue(value)
-
-
-    def GetAttr(self, row, col, kind):
-        """
-        Return the attribute for the given cell.
-
-        :param `row`: the row in which this cell lives;
-        :param `col`: the column in which this cell lives;
-        :param `kind`: the kind of the attribute to return.
-        """
-
-        cell = self.cells[(row, col)]
-        return cell.GetAttr()
-
-
-    def GetRawValue(self, row, col):
-        """
-        Returns the "raw" value for the cell content.
-
-        :param `row`: the row in which this cell lives;
-        :param `col`: the column in which this cell lives.
-        """
-
-        cell = self.cells[(row, col)]
-        return cell.raw_value
-
-
-class XLSGrid(gridlib.Grid):
-    """
-    L{XLSGrid} is a class based on `wx.grid.Grid` that can be used to faithfully
-    reproduce the appearance of a Microsoft Excel spreadsheet (one worksheet per
-    every instance of L{XLSGrid}).
-
-    L{XLSGrid} is a completely owner-drawn control, and it relies on the power of
-    `wx.grid.PyGridTableBase` and `wx.grid.PyGridCellRenderer` to draw the cell
-    content. For this reasons (and for some others, see the TODOs section), it will
-    work efficiently only for relatively small Excel files.
-    """
-
-    def __init__(self, parent):
-        """
-        Default class constructor.
-
-        :param `parent`: the grid parent window. Must not be ``None``.
-        """
-
-        gridlib.Grid.__init__(self, parent)
-
-        self.SetMargins(0, 0)
-        self.SetDefaultCellBackgroundColour(parent.GetBackgroundColour())
-        self.SetDefaultCellOverflow(True)
-
-        self.tip_window = None
-        self.tip_shown = False
-
-
-    def DestroyTip(self):
-        """
-        If a comment window or a tooltip over a hyperlink have been created, this
-        method destroys them.
-        """
-
-        if self.tip_window:
-            try:
-                self.tip_window.GetTipWindow().Destroy()
-            except wx.PyDeadObjectError:
-                pass
-
-            del self.tip_window
-            self.tip_window = None
-
-        if self.tip_shown:
-            self.GetGridWindow().SetToolTipString("")
-            self.GetGridWindow().SetCursor(wx.NullCursor)
-            self.tip_shown = False
-
-
-    def InstallGridHint(self):
-        """
-        Auxiliary method used to bind a ``wx.EVT_MOTION`` event to L{XLSGrid}.
-        """
-
-        self.prev_rowcol = [None, None]
-
-        def OnMouseMotion(event):
-            """
-            Handles a the ``wx.EVT_MOTION`` events for L{XLSGrid}.
-
-            :param `event`: a `wx.MouseEvent` event to be processed.
-            """
-
-            # evt.GetRow() and evt.GetCol() would be nice to have here,
-            # but as this is a mouse event, not a grid event, they are not
-            # available and we need to compute them by hand.
-            position = event.GetPosition()
-            x, y = self.CalcUnscrolledPosition(position)
-            row = self.YToRow(y)
-            col = self.XToCol(x)
-
-            if [row, col] != self.prev_rowcol and row >= 0 and col >= 0:
-
-                self.prev_rowcol[:] = [row, col]
-                self.DestroyTip()
-                cell = self.cells[(row, col)]
-                rect = self.CellToRect(row, col)
-                comment = cell.GetComment()
-
-                window = self.GetGridWindow()
-                if cell.text.IsHyperLink():
-                    window.SetCursor(wx.StockCursor(wx.CURSOR_HAND))
-                    window.SetToolTipString(cell.text.tooltip)
-                    self.tip_shown = True
-                    if not comment:
-                        return
-
-                if comment:
-                    self.tip_window = TransientPopup(window, comment, wx.GetMousePosition())
-                    event.Skip()
-
-        self.GetGridWindow().Bind(wx.EVT_MOTION, OnMouseMotion)
-
-
-    def PopulateGrid(self, book, sheet, display_texts, comments):
-        """
-        This is the main method of this class, and it is used to actually create
-        the cells, size the columns and rows, merging cells, etc...
-
-        :param `book`: an instance of the `xlrd.Book` class;
-        :param `sheet`: an instance of the `xlrd.sheet` class;
-        :param `display_texts`: if Mark Hammonds' `pywin32` package is available,
-         this is the WYSIWYG cell content for all the cells in the Excel worksheet;
-        :param `comments`: if Mark Hammonds' `pywin32` package is available,
-         this is a nested list of cell comments (notes) for all the cells in the
-         Excel worksheet.
-        """
-
-        self.BeginBatch()
-
-        nrows = sheet.nrows
-        ncols = sheet.ncols
-
-        default_width, default_height = self.GetDefaultFontData(book)
-        default_colour = self.GetGridLineColour()
-
-        hyperlinks, rich_text_list = {}, {}
-        if hasattr(sheet, "hyperlink_map"):
-            # New in xlrd version 0.7.2 from SVN
-            hyperlinks = sheet.hyperlink_map
-
-        if hasattr(sheet, "rich_text_runlist_map"):
-            # New in xlrd version 0.7.2 from SVN
-            rich_text_list = sheet.rich_text_runlist_map
-
-        self.cells = {}
-
-        for i in xrange(nrows):
-
-            for j in xrange(ncols):
-
-                hyperlink = rich_text = None
-
-                if (i, j) in hyperlinks:
-                    hyperlink = hyperlinks[(i, j)]
-                if (i, j) in rich_text_list:
-                    rich_text = rich_text_list[(i, j)]
-
-                self.FormatCell(book, sheet, i, j, display_texts, comments, hyperlink, rich_text, default_width, default_colour)
-
-        self.table = XLSTable(self, self.cells, nrows, ncols)
-        self.SetTable(self.table)
-
-        row_height = sheet.default_row_height
-        col_width = sheet.defcolwidth
-
-        for i in xrange(nrows):
-            if i in sheet.rowinfo_map:
-                current = sheet.rowinfo_map[i].height
-            else:
-                current = sheet.default_row_height
-
-            row_height = int(round(float(default_height)*current/256.0))
-            self.SetRowSize(i, row_height)
-
-        for j in xrange(ncols):
-            if j in sheet.colinfo_map:
-                current = sheet.colinfo_map[j].width
-            else:
-                current = sheet.defcolwidth
-
-            col_width = int(round(float(default_width)*current/256.0))
-            self.SetColSize(j, col_width)
-
-        for merged in sheet.merged_cells:
-            rlo, rhi, clo, chi = merged
-            if rlo >= 0 and rlo < len(self.cells) and clo >= 0:
-                self.cells[(rlo, clo)].SetCellSize(rhi-rlo, chi-clo)
-
-        self.EnableEditing(False)
-        self.EnableGridLines(False)
-        self.EndBatch()
-        self.ForceRefresh()
-        self.InstallGridHint()
-
-
-    def FormatCell(self, book, sheet, row, col, display_texts, comments, hyperlink, rich_text, default_width, default_colour):
-        """
-        Processes the creation of a single cell (an instance of L{XLSCell}).
-
-        :param `book`: an instance of the `xlrd.Book` class;
-        :param `sheet`: an instance of the `xlrd.sheet` class;
-        :param `row`: the row in which this cell lives;
-        :param `col`: the column in which this cell lives;
-        :param `display_texts`: if Mark Hammonds' `pywin32` package is available,
-         this is the WYSIWYG cell content for all the cells in the Excel worksheet;
-        :param `comments`: if Mark Hammonds' `pywin32` package is available,
-         this is a nested list of cell comments (notes) for all the cells in the
-         Excel worksheet;
-        :param `hyperlink`: if this cell contains a hyperlink, it will be displayed
-         accordingly;
-        :param `rich_text`: if this cell contains text in rich text format, L{XLSGrid}
-         will do its best to render the text as rich text;
-        :param `default_width`: this is the default width of the text in 1/256
-         of the width of the zero character, using default Excel font (first FONT
-         record in the Excel file);
-        :param `default_colour`: the "magic" colour used by Excel to draw non-custom
-         border lines.
-
-        :note: If you are using version 0.7.1 or lower for `xlrd`, the *hyperlink*
-         parameter will always be ``None`` as this feature is available only in
-         `xlrd` 0.7.2 (SVN).
-
-        :note: If you are using version 0.7.1 or lower for `xlrd`, the `rich_text`
-         parameter will always be ``None`` as this feature is available only in
-         `xlrd` 0.7.2 (SVN).
-
-        :note: If Mark Hammonds' `pywin32` package is not available, the `display_texts`
-         and `comments` parameter will be two empty nested lists.
-        """
-
-        cell = sheet.cell(row, col)
-
-        xf_index = sheet.cell_xf_index(row, col)
-        xls_text, xls_comment = display_texts[row][col], comments[row][col]
-
-        gridCell = XLSCell(book, cell, xf_index, xls_text, xls_comment, hyperlink, rich_text, default_width, default_colour)
-
-        self.cells[(row, col)] = gridCell
-
-
-    def GetDefaultFontData(self, book):
-        """
-        Returns suitable width and height (in pixels) starting from Excel's own
-        measurements (in characters, whatever that means).
-
-        :param `book`: an instance of the `xlrd.Book` class.
-
-        :returns: a `default_width` and `default_height` in pixels, based on the
-         default width of the text in 1/256 of the width of the zero character,
-         using default Excel font (first FONT record in the Excel file).
-        """
-
-        font = book.font_list[0]
-        style, bold, underline = wx.FONTSTYLE_NORMAL, wx.NORMAL, False
-
-        if font.italic:
-            style = wx.FONTSTYLE_ITALIC
-        if font.underline_type > 0:
-            underline = True
-        if font.weight > 600:
-            bold = wx.BOLD
-
-        family = XF_FONT_FAMILY[font.family]
-        name = font.name
-        size = int(font.height/20.0)
-
-        dc = wx.ClientDC(self)
-        font = wx.Font(size, family, style, bold, underline, name.encode())
-        dc.SetFont(font)
-        width, height, descent, leading = dc.GetFullTextExtent("0", font)
-
-        return width, height + descent - leading
-
-
-class TransientPopup(STT.SuperToolTip):
-    """
-    This is a sublass of L{SuperToolTip} and it is used to display a
-    "comment-window" on the cells containing a comment (a note).
-
-    :note: If Mark Hammonds' `pywin32` package is not available, this class is
-     never invoked.
-    """
-
-    def __init__(self, grid_window, comment, position):
-        """
-        Default class constructor.
-
-        :param `grid_window`: the actual window representing the grid;
-        :param `comment`: an instance of L{XLSComment}, containing the
-         text for this comment;
-        :param `position`: the position at which we pop up the comment
-         window (currently unused).
-        """
-
-        STT.SuperToolTip.__init__(self, grid_window)
-
-        xls_comment = comment.comment
-
-        split = xls_comment.split(":")
-        header, rest = split[0], split[1:]
-        rest = ":".join(rest)
-
-        dc = wx.ClientDC(grid_window)
-        rest = wordwrap(rest, 400, dc)
-
-        self.SetHeader(header)
-        self.SetMessage(rest)
-        self.SetTarget(grid_window)
-        self.SetDrawHeaderLine(True)
-
-        self.SetStartDelay(100000)
-        self.SetEndDelay(100000)
-        self.ApplyStyle("Office 2007 Blue")
-
-        self.SetDropShadow(True)
-        self.DoShowNow()
-
-        grid_window.SetFocus()
-
->>>>>>> .r69293
-
\ No newline at end of file

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • xlsgrid »
  • SVN Revision 69621 For xlsgrid


zoombar functions

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • zoombar »
  • zoombar functions

zoombar functions

This is the description of standalone Python functions in the zoombar module.

Functions Summary

MakeDisabledBitmap Creates a disabled-looking bitmap starting from the input one.

API Functions API

MakeDisabledBitmap(original) [source]

Creates a disabled-looking bitmap starting from the input one.

Parameters: original – an instance of wx.Bitmap to be greyed-out.

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • infobar
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • zoombar »
  • zoombar functions


ImageBar

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • zoombar »
  • ImageBar

ImageBar

This class holds the background button bar on which the buttons float.

hierarchy Inheritance Diagram

Inheritance diagram for: ImageBar

Inheritance diagram of ImageBar

Methods Summary

__init__ | Default class constructor.
GetBarColour | Returns the background button bar colour.
GetBitmap | Returns the background button bar on which the buttons float.
GetPosition | Returns the position of ImageBar, as a wx.Point.
GetSize | Returns the size of ImageBar, as a wx.Size.
SetBarColour | Sets the background button bar colour.
SetPosition | Sets the position of ImageBar.
SetSize | Sets the size of ImageBar.

API Class API

class ImageBar(object) [source]

This class holds the background button bar on which the buttons float.

__init__(bitmap=None) [source]

Default class constructor.

Parameters: bitmap – if not None, the bitmap to use as a background button bar on which the buttons float. It should be an instance of wx.Image.

GetBarColour() [source]

Returns the background button bar colour.

GetBitmap() [source]

Returns the background button bar on which the buttons float.

GetPosition() [source]

Returns the position of ImageBar, as a wx.Point.

GetSize() [source]

Returns the size of ImageBar, as a wx.Size.

SetBarColour(colour, xSize=None, ySize=None) [source]

Sets the background button bar colour.

Parameters:
  • colour – an instance of wx.Colour;
  • xSize – if not None, the new ImageBar width;
  • ySize – if not None, the new ImageBar height.

SetPosition(xpos, ypos) [source]

Sets the position of ImageBar.

Parameters:
  • xpos – the x position of the bar;
  • ypos – the y position of the bar.

SetSize(xSize, ySize) [source]

Sets the size of ImageBar.

Parameters:
  • xSize – the width of the bar, in pixels;
  • ySize – the height of the bar, in pixels.

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • infobar
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • zoombar »
  • ImageBar


ZoomBar

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • zoombar »
  • ZoomBar

ZoomBar

ZoomBar is a class that appoximatively mimics the behaviour of the Mac Dock, inside a wx.Panel.

This is the main class implementation.

hierarchy Inheritance Diagram

Inheritance diagram for: ZoomBar

Inheritance diagram of ZoomBar

appearance Control Appearance

ZoomBar

Methods Summary

__init__ | Default class constructor.
AddButton | Adds a button to ZoomBar.
AddSeparator | Adds a separator to ZoomBar.
DoGetBestSize | Gets the size which best suits the window: for a control, it would be the
DoLayout | Common method to re-layout ZoomBar.
DrawButtons | Draws all the main button bitmaps on the ZoomBar client window.
DrawLabels | Draws all the button labels on the ZoomBar client window.
DrawReflections | Draws all the reflection button bitmaps on the ZoomBar client window.
EnableButton | Enables/disables the button at position index.
GetBarColour | Returns the background button bar colour.
GetButtonSize | Returns the original (not zoomed) button size, in pixels.
GetCenterZoom | Returns True if buttons zoom upwards.
GetShowLabels | Returns True if button labels are currently shown.
GetShowReflections | Returns True if reflections bitmap are currently shown.
GetZoomFactor | Returns the current zoom factor.
HitTest | HitTest method for ZoomBar.
InitialReposition | Sets up the initial buttons and sizes them from the center.
IsButtonEnabled | Returns True if the button at position index is enabled, False
OnEraseBackground | Handles the wx.EVT_ERASE_BACKGROUND event for ZoomBar.
OnLeaveWindow | Handles the wx.EVT_LEAVE_WINDOW event for ZoomBar.
OnLeftDown | Handles the wx.EVT_LEFT_DOWN and wx.EVT_LEFT_DCLICK events for ZoomBar.
OnLeftUp | Handles the wx.EVT_LEFT_UP event for ZoomBar.
OnMotion | Handles the wx.EVT_MOTION event for ZoomBar.
OnPaint | Handles the wx.EVT_PAINT event for ZoomBar.
OnSize | Handles the wx.EVT_SIZE event for ZoomBar.
Reposition | Repositions all the buttons inside the ZoomBar.
ResetSize | Resets all the button sizes and positions, recalculating the optimal ZoomBar
SetBarColour | Sets the background button bar colour.
SetButtonSize | Sets the original button size.
SetCenterZoom | Sets to zoom from the center.
SetShowLabels | Sets whether to show button labels or not.
SetShowReflections | Sets whether to show reflections or not.
SetZoomFactor | Sets the zoom factor for all the buttons.
SnapToBottom | Snaps the background button bar bitmap and all the buttons to the bottom

API Class API

class ZoomBar(wx.PyControl) [source]

ZoomBar is a class that appoximatively mimics the behaviour of the Mac Dock, inside a wx.Panel.

This is the main class implementation.

__init__(parent, id=wx.ID_ANY, pos=wx.DefaultPosition, size=wx.DefaultSize, name="ZoomBar") [source]

Default class constructor.

Parameters:
  • parent – the ZoomBar parent. Must not be None;
  • id – window identifier. A value of -1 indicates a default value;
  • pos – the control position. A value of (-1, -1) indicates a default position, chosen by either the windowing system or wxPython, depending on platform;
  • size – the control size. A value of (-1, -1) indicates a default size, chosen by either the windowing system or wxPython, depending on platform;
  • name – the window name.

AddButton(normalBmp, reflectionBmp=wx.NullBitmap, label="", disabledBmp=wx.NullBitmap, disabledReflectionBmp=wx.NullBitmap) [source]

Adds a button to ZoomBar.

Parameters:
  • normalBmp – the button main bitmap, an instance of wx.Bitmap;
  • reflectionBmp – a bitmap representing a reflection of the main bitmap, an instance of wx.Bitmap;

  • label – the button label;
  • disabledBmp – the button main bitmap when the button is in a disabled state, an instance of wx.Bitmap;

  • disabledReflectionBmp – a bitmap representing a reflection of the main bitmap, when the button is in a disabled state, an instance of wx.Bitmap.

AddSeparator(normalBmp, reflectionBmp=wx.NullBitmap) [source]

Adds a separator to ZoomBar.

Parameters:
  • normalBmp – the separator main bitmap, an instance of wx.Bitmap;

  • reflectionBmp – a bitmap representing a reflection of the main bitmap, an instance of wx.Bitmap.

DoGetBestSize() [source]

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

Note

Overridden from wx.PyControl.

DoLayout() [source]

Common method to re-layout ZoomBar.

DrawButtons(dc) [source]

Draws all the main button bitmaps on the ZoomBar client window.

Parameters: dc – an instance of wx.DC.

DrawLabels(dc) [source]

Draws all the button labels on the ZoomBar client window.

Parameters: dc – an instance of wx.DC.

DrawReflections(dc) [source]

Draws all the reflection button bitmaps on the ZoomBar client window.

Parameters: dc – an instance of wx.DC.

EnableButton(index, enable=True) [source]

Enables/disables the button at position index.

Parameters:
  • index – the index of the button to enable/disable;
  • enable – True to enable the button, False to disable it.

GetBarColour() [source]

Returns the background button bar colour.

GetButtonSize() [source]

Returns the original (not zoomed) button size, in pixels.

GetCenterZoom() [source]

Returns True if buttons zoom upwards.

GetShowLabels() [source]

Returns True if button labels are currently shown.

GetShowReflections() [source]

Returns True if reflections bitmap are currently shown.

GetZoomFactor() [source]

Returns the current zoom factor.

HitTest(pos) [source]

HitTest method for ZoomBar.

Parameters: pos – the current mouse position.
Returns: an index representing the button on which the mouse is hovering, or wx.NOT_FOUND if no button has been hit.

InitialReposition() [source]

Sets up the initial buttons and sizes them from the center.

IsButtonEnabled(index) [source]

Returns True if the button at position index is enabled, False otherwise.

Parameters: index – the index of the button to check.

OnEraseBackground(event) [source]

Handles the wx.EVT_ERASE_BACKGROUND event for ZoomBar.

Parameters: event – a wx.EraseEvent event to be processed.

Note

This method is intentionally empty to avoid flicker.

OnLeaveWindow(event) [source]

Handles the wx.EVT_LEAVE_WINDOW event for ZoomBar.

Parameters: event – a wx.MouseEvent event to be processed.

OnLeftDown(event) [source]

Handles the wx.EVT_LEFT_DOWN and wx.EVT_LEFT_DCLICK events for ZoomBar.

Parameters: event – a wx.MouseEvent event to be processed.

OnLeftUp(event) [source]

Handles the wx.EVT_LEFT_UP event for ZoomBar.

Parameters: event – a wx.MouseEvent event to be processed.

OnMotion(event) [source]

Handles the wx.EVT_MOTION event for ZoomBar.

Parameters: event – a wx.MouseEvent event to be processed.

OnPaint(event) [source]

Handles the wx.EVT_PAINT event for ZoomBar.

Parameters: event – a wx.PaintEvent event to be processed.

OnSize(event) [source]

Handles the wx.EVT_SIZE event for ZoomBar.

Parameters: event – a wx.SizeEvent event to be processed.

Reposition(toButton) [source]

Repositions all the buttons inside the ZoomBar.

Parameters: toButton – the button currently hovered by the mouse (and hence zoomed).

ResetSize() [source]

Resets all the button sizes and positions, recalculating the optimal ZoomBar size.

SetBarColour(colour) [source]

Sets the background button bar colour.

Parameters: colour – an instance of wx.Colour;

SetButtonSize(size) [source]

Sets the original button size.

Parameters: size – the new (not-zoomed) button size, in pixels.

SetCenterZoom(center=True) [source]

Sets to zoom from the center.

Parameters: center – if True button zooms upwards.

SetShowLabels(show) [source]

Sets whether to show button labels or not.

Parameters: show – True to show button labels, False otherwise.

SetShowReflections(show) [source]

Sets whether to show reflections or not.

Parameters: show – True to show reflections, False otherwise.

SetZoomFactor(zoom) [source]

Sets the zoom factor for all the buttons. Larger number gives a greater zoom effect.

Parameters: zoom – a floating point number, greater than or equal to 1.0.

SnapToBottom(size) [source]

Snaps the background button bar bitmap and all the buttons to the bottom of ZoomBar.

Parameters: size – the current ZoomBar size.

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • infobar
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • zoombar »
  • ZoomBar


ZoomBarEvent

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • zoombar »
  • ZoomBarEvent

ZoomBarEvent

Event sent from the ZoomBar when a button is activated.

hierarchy Inheritance Diagram

Inheritance diagram for: ZoomBarEvent

Inheritance diagram of ZoomBarEvent

Methods Summary

__init__ | Default class constructor.
GetLabel | Returns the text label of the selected button.
GetSelection | Returns the index of the selected button.
SetLabel | Sets the text label of the selected button.
SetSelection | Sets the index of the selected button.

API Class API

class ZoomBarEvent(wx.PyCommandEvent) [source]

Event sent from the ZoomBar when a button is activated.

__init__(eventType, eventId=1) [source]

Default class constructor.

Parameters:
  • eventType – the event type;
  • eventId – the event identifier.

GetLabel() [source]

Returns the text label of the selected button.

GetSelection() [source]

Returns the index of the selected button.

SetLabel(label) [source]

Sets the text label of the selected button.

Parameters: label – the text label of the selected button.

SetSelection(selection) [source]

Sets the index of the selected button.

Parameters: selection – an integer indicating the current selected button.

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • infobar
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • zoombar »
  • ZoomBarEvent


ZoomBarImage

  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • zoombar »
  • ZoomBarImage

ZoomBarImage

This simple class holds information about a ZoomBar button, such as normal bitmaps, disabled bitmap, button label, etc...

hierarchy Inheritance Diagram

Inheritance diagram for: ZoomBarImage

Inheritance diagram of ZoomBarImage

Methods Summary

__init__ | Default class constructor.
Enable | Enables/disables a button.
GetBitmap | Returns the button bitmap, which may be a scaled up version of the original
GetLabel | Returns the button label (if any).
GetPosition | Returns the button position.
GetSize | Returns the button size.
IsEnabled | Returns True if the button is enabled, False otherwise.
IsZoomed | Returns True if the button is zoomed, False otherwise.
LoopScales | Caches the bitmaps at various zoom levels to avoid calling every time
SetCenterZoom | Sets to zoom from the center.
SetLabel | Sets the button label.
SetSize | Sets the button size.
SetZoomFactor | Sets the zoom factor for the button.
SetupProps | Set up the button position and size.
ZoomImage | Zooms the button bitmap depending on the mouse x position.

API Class API

class ZoomBarImage(object) [source]

This simple class holds information about a ZoomBar button, such as normal bitmaps, disabled bitmap, button label, etc...

__init__(parent, bitmap, disabledBmp=wx.NullBitmap, label="") [source]

Default class constructor.

Parameters:
  • parent – the main ZoomBar window;
  • bitmap – the button bitmap, an instance of wx.Bitmap;
  • disabledBmp – the button bitmap when the button is in a disabled state;
  • label – the button label.

Enable(enable=True) [source]

Enables/disables a button.

Parameters: enable – True to enable a button, False to disable it.

GetBitmap() [source]

Returns the button bitmap, which may be a scaled up version of the original bitmap is the button is being zoomed.

GetLabel() [source]

Returns the button label (if any).

GetPosition() [source]

Returns the button position.

GetSize() [source]

Returns the button size.

IsEnabled() [source]

Returns True if the button is enabled, False otherwise.

IsZoomed() [source]

Returns True if the button is zoomed, False otherwise.

LoopScales(size) [source]

Caches the bitmaps at various zoom levels to avoid calling every time image.Scale on the button bitmap.

Parameters: size – the original button size, in pixels.

SetCenterZoom(center=True) [source]

Sets to zoom from the center.

Parameters: center – if True button zooms upwards.

SetLabel(label) [source]

Sets the button label.

Parameters: label – a string specifying the button label. May be an empty string for no label.

SetSize(width, height) [source]

Sets the button size.

Parameters:
  • width – the button width;
  • height – the button height.

SetZoomFactor(zoom) [source]

Sets the zoom factor for the button. Larger number gives a greater zoom effect.

Parameters: zoom – a floating point number, greater than or equal to 1.0.

SetupProps(buttonSize) [source]

Set up the button position and size.

Parameters: buttonSize – the button original size (not zoomed), in pixels.

ZoomImage(nxcoord) [source]

Zooms the button bitmap depending on the mouse x position.

Parameters: nxcoord – the mouse x position relative to the button center.

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • infobar
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • next |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • zoombar »
  • ZoomBarImage


SVN Revision 68881 For zoombar

  • modules |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • zoombar »
  • SVN Revision 68881 For zoombar

svn SVN Revision 68881 For zoombar

This file contains the SVN revision history for zoombar, at revision 68881.

Available information include commit date, the name of the committer, the file size, the SVN log messages and a diff from the previous version (if available).

File Information

  • Commit Date: 10-Dec-2009 18:09:38 UTC
  • Committer: AG
  • File Size: 46414 byte(s)

Log Messages

The following log message was entered by the committer:

  • AGW: General overhaul of the documentation, much improved. All the widgets have their own sample usage in the docs as well;

  • FlatNotebook: Added the FNB_NAV_BUTTONS_WHEN_NEEDED style, which hides the navigation left/right arrows if all tabs fit;

  • RibbonBar: - Added the EVT_RIBBONBAR_TAB_LEFT_DCLICK event, which generates a special event

    when a ribbon bar tab is double-clicked;

    • Added support for toggle buttons;
    • Improved support for ribbon panel sizers: panels with sizers should now automatically minimise at small sizes, and behave properly when popping up from a minimised state;
    • Added tooltips via SetToolTip for those buttons which have the help_string attribute set.

  • XLSGrid: a new widget was added to AGW, termed XLSGrid. It’s based on wx.grid.Grid and can be used to faithfully reproduce the appearance of a Microsoft Excel spreadsheets.

Diff To Previous Version (65377)

Version SVN diff:

--- wxPython/3rdParty/AGW/agw/zoombar.py    2010/08/21 20:27:02     65377
+++ wxPython/3rdParty/AGW/agw/zoombar.py    2011/08/25 16:40:17     68881
@@ -1,15 +1,15 @@
"""
-ZoomBar is a class that *appoximatively* mimics the behaviour of the Mac Dock,
+L{ZoomBar} is a class that *appoximatively* mimics the behaviour of the Mac Dock,
inside a `wx.Panel`.

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

-ZoomBar is a class that *appoximatively* mimics the behaviour of the Mac Dock,
+L{ZoomBar} is a class that *appoximatively* mimics the behaviour of the Mac Dock,
inside a `wx.Panel`.

-Once you hover mouse over the ZoomBar correct button will bubble up, grow to
+Once you hover mouse over the L{ZoomBar} correct button will bubble up, grow to
predefined size, so you can easily see the button you are about to click and
have larger area to click. Difference this makes is amazing.

@@ -18,31 +18,67 @@
remaining buttons around the zoomed button.

-Example Usage
-=============
+Usage
+=====
+
+Usage example::

-Sample usage for ZoomBar::
+    import os
+    import random
+    import glob
+
+    import wx
+    import wx.lib.agw.zoombar as ZB

-    bar = ZB.ZoomBar(self, -1)
+    class MyFrame(wx.Frame):

-    normalImages = glob.glob(bitmapDir + "/*96.png")
-    reflectionImages = glob.glob(bitmapDir + "/*96Flip40.png")
+        def __init__(self, parent):

-    for std, ref in zip(normalImages, reflectionImages):
-
-        bname = os.path.split(std)[1][0:-6]
+            wx.Frame.__init__(self, parent, -1, "ZoomBar Demo")

-        normalBmp = wx.Bitmap(std, wx.BITMAP_TYPE_PNG)
-        reflectionBmp = wx.Bitmap(ref, wx.BITMAP_TYPE_PNG)
-        bar.AddButton(normalBmp, reflectionBmp, bname)
+            panel = wx.Panel(self)
+
+            bar = ZB.ZoomBar(panel, -1)

-    bar.ResetSize()
+            standard = glob.glob(bitmapDir + "/*96.png")
+            reflections = glob.glob(bitmapDir + "/*96Flip40.png")
+
+            separatorImage = bitmapDir + "/separator.gif"
+            separatorReflection = bitmapDir + "/separatorFlip.png"
+            count = 0
+
+            for std, ref in zip(standard, reflections):
+                if random.randint(0, 1) == 1 and count > 0:
+                    sep1 = wx.Bitmap(separatorImage, wx.BITMAP_TYPE_GIF)
+                    sep2 = wx.Bitmap(separatorReflection, wx.BITMAP_TYPE_PNG)
+                    bar.AddSeparator(sep1, sep2)
+
+                bname = os.path.split(std)[1][0:-6]
+                bar.AddButton(wx.Bitmap(std, wx.BITMAP_TYPE_PNG), wx.Bitmap(ref, wx.BITMAP_TYPE_PNG), bname)
+                count += 1
+
+            bar.ResetSize()
+
+            sizer = wx.BoxSizer(wx.HORIZONTAL)
+            sizer.Add(bar, 0, wx.ALIGN_CENTER_HORIZONTAL|wx.ALIGN_CENTER_VERTICAL|wx.ALL, 15)
+            panel.SetSizer(sizer)
+
+
+    # our normal wxApp-derived class, as usual
+
+    app = wx.PySimpleApp()
+
+    frame = MyFrame(None)
+    app.SetTopWindow(frame)
+    frame.Show()
+
+    app.MainLoop()

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

-ZoomBar has been tested on the following platforms:
+L{ZoomBar} has been tested on the following platforms:
* Windows (Windows XP).

@@ -60,16 +96,16 @@
============================== ==================================================
Event Name                     Description
============================== ==================================================
-``EVT_ZOOMBAR``                Process a `wxEVT_ZOOMBAR` event, when a `ZoomBar` button is clicked.
+``EVT_ZOOMBAR``                Process a ``wxEVT_ZOOMBAR`` event, when a L{ZoomBar} button is clicked.
============================== ==================================================

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

-ZoomBar is distributed under the wxPython license.
+L{ZoomBar} is distributed under the wxPython license.

-Latest Revision: Andrea Gavana @ 03 Dec 2009, 09.00 GMT
+Latest Revision: Andrea Gavana @ 17 Aug 2011, 15.00 GMT

Version 0.1

@@ -265,7 +301,7 @@

wxEVT_ZOOMBAR = wx.NewEventType()
EVT_ZOOMBAR = wx.PyEventBinder(wxEVT_ZOOMBAR, 1)
-""" Process a `wxEVT_ZOOMBAR` event, when a `ZoomBar` button is clicked. """
+""" Process a `wxEVT_ZOOMBAR` event, when a L{ZoomBar} button is clicked. """

# ----------------------------------------------------------------------------

@@ -671,7 +707,7 @@

class ZoomBar(wx.PyControl):
"""
-    ZoomBar is a class that *appoximatively* mimics the behaviour of the Mac Dock,
+    L{ZoomBar} is a class that *appoximatively* mimics the behaviour of the Mac Dock,
inside a `wx.Panel`.

This is the main class implementation.
@@ -734,6 +770,8 @@
Gets the size which best suits the window: for a control, it would be the
minimal size which doesn't truncate the control, for a panel - the same size
as it would have after a call to `Fit()`.
+
+        :note: Overridden from `wx.PyControl`.
"""

xSize = self._buttonSize*len(self._buttons) + len(self._buttons) + self._buttonSize
@@ -751,8 +789,7 @@
"""
Repositions all the buttons inside the L{ZoomBar}.

-        :param `toButton`: the button currently hovered by the mouse (and hence
-         zoomed).
+        :param `toButton`: the button currently hovered by the mouse (and hence zoomed).
"""

nLeft = toButton._left

AGW

  • advancedsplash
  • aquabutton
  • artmanager
  • aui
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar
Tree

Navigation

  • index
  • modules |
  • previous |
  • Home |
  • Gallery |
  • Contents»
  • zoombar »
  • SVN Revision 68881 For zoombar


advancedsplash

  • modules |
  • Home |
  • Gallery |
  • Contents»
  • Module code »
  • advancedsplash

Source code for advancedsplash

# --------------------------------------------------------------------------- #
# ADVANCEDSPLASH Control wxPython IMPLEMENTATION
# Python Code By:
#
# Andrea Gavana, @ 10 Oct 2005
# Latest Revision: 17 Aug 2011, 15.00 GMT
#
#
# TODO List/Caveats
#
# 1. Actually, Setting The Shape Of AdvancedSplash Is Done Using "SetShape"
#    Function On A Frame. This Works, AFAIK, On This Following Platforms:
#
#    - MSW
#    - UNIX/Linux
#    - MacOS Carbon
#
#    Obviously I May Be Wrong Here. Could Someone Verify That Lines 139-145
#    Work Correctly On Other Platforms Than Mine (MSW XP/2000)?
#    Moreover, Is There A Way To Avoid The Use Of The "SetShape" Method?
#    I Don't Know.
#
#
# 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
# --------------------------------------------------------------------------- #

"""
L{AdvancedSplash} tries to reproduce the behavior of `wx.SplashScreen`, with
some enhancements.

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

L{AdvancedSplash} tries to reproduce the behavior of `wx.SplashScreen`, but with
some enhancements (in my opinion).

L{AdvancedSplash} starts its construction from a simple frame. Then, depending on
the options passed to it, it sets the frame shape accordingly to the image passed
as input. L{AdvancedSplash} behaves somewhat like `wx.SplashScreen`, and almost
all the methods available in `wx.SplashScreen` are available also in
this module.

Usage
=====

Sample usage::

    import wx
    import wx.lib.agw.advancedsplash as AS

    app = wx.App(0)

    frame = wx.Frame(None, -1, "AdvancedSplash Test")

    imagePath = "my_splash_image.png"
    bitmap = wx.Bitmap(imagePath, wx.BITMAP_TYPE_PNG)
    shadow = wx.WHITE

    splash = AS.AdvancedSplash(frame, bitmap=bitmap, timeout=5000,
                               agwStyle=AS.AS_TIMEOUT |
                               AS.AS_CENTER_ON_PARENT |
                               AS.AS_SHADOW_BITMAP,
                               shadowcolour=shadow)

    app.MainLoop()

None of the options are strictly required (a part of the `bitmap` parameter).
If you use the defaults you get a very simple L{AdvancedSplash}.

Methods and Settings
====================

L{AdvancedSplash} is customizable, and in particular you can set:

- Whether you want to mask a colour or not in your input bitmap;
- Where to center the splash screen (on screen, on parent or nowhere);
- Whether it is a "timeout" splashscreen or not;
- The time after which L{AdvancedSplash} is destroyed (if it is a timeout splashscreen);
- The (optional) text you wish to display;
- The font, colour and position of the displayed text (optional).

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

This class supports the following window styles:

======================= =========== ==================================================
Window Styles           Hex Value   Description
======================= =========== ==================================================
``AS_TIMEOUT``                  0x1 L{AdvancedSplash} will be destroyed after `timeout` milliseconds.
``AS_NOTIMEOUT``                0x2 L{AdvancedSplash} can be destroyed by clicking on it, pressing a key or by explicitly call the `Close()` method.
``AS_CENTER_ON_SCREEN``         0x4 L{AdvancedSplash} will be centered on screen.
``AS_CENTER_ON_PARENT``         0x8 L{AdvancedSplash} will be centered on parent.
``AS_NO_CENTER``               0x10 L{AdvancedSplash} will not be centered.
``AS_SHADOW_BITMAP``           0x20 If the bitmap you pass as input has no transparency, you can choose one colour that will be masked in your bitmap. the final shape of L{AdvancedSplash} will be defined only by non-transparent (non-masked) pixels.
======================= =========== ==================================================

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

`No custom events are available for this class.`

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

L{AdvancedSplash} control is distributed under the wxPython license.

Latest revision: Andrea Gavana @ 17 Aug 2011, 15.00 GMT

Version 0.4

"""

#----------------------------------------------------------------------
# Beginning Of ADVANCEDSPLASH wxPython Code
#----------------------------------------------------------------------

import wx

# These Are Used To Declare If The AdvancedSplash Should Be Destroyed After The
# Timeout Or Not

AS_TIMEOUT = 1
""" L{AdvancedSplash} will be destroyed after `timeout` milliseconds. """
AS_NOTIMEOUT = 2
""" L{AdvancedSplash} can be destroyed by clicking on it, pressing a key or by explicitly call the `Close()` method. """

# These Flags Are Used To Position AdvancedSplash Correctly On Screen
AS_CENTER_ON_SCREEN = 4
""" L{AdvancedSplash} will be centered on screen. """
AS_CENTER_ON_PARENT = 8
""" L{AdvancedSplash} will be centered on parent. """
AS_NO_CENTER = 16
""" L{AdvancedSplash} will not be centered. """

# This Option Allow To Mask A Colour In The Input Bitmap
AS_SHADOW_BITMAP = 32
""" If the bitmap you pass as input has no transparency, you can choose one colour that will be masked in your bitmap. the final shape of L{AdvancedSplash} will be defined only by non-transparent (non-masked) pixels. """

#----------------------------------------------------------------------
# ADVANCEDSPLASH Class
# This Is The Main Class Implementation. See __init__() Method For
# Details.
#----------------------------------------------------------------------

[docs]class AdvancedSplash(wx.Frame):
    """
    L{AdvancedSplash} tries to reproduce the behavior of `wx.SplashScreen`, with
    some enhancements.

    This is the main class implementation.
    """

[docs]    def __init__(self, parent, id=-1, pos=wx.DefaultPosition, size=wx.DefaultSize,
                 style=wx.FRAME_NO_TASKBAR | wx.FRAME_SHAPED | wx.STAY_ON_TOP,
                 bitmap=None, timeout=5000,
                 agwStyle=AS_TIMEOUT | AS_CENTER_ON_SCREEN,
                 shadowcolour=wx.NullColour):
        """
        Default class constructor.

        :param `parent`: parent window;
        :param integer `id`: window identifier. A value of -1 indicates a default value;
        :param `pos`: the control position. A value of (-1, -1) indicates a default position,
         chosen by either the windowing system or wxPython, depending on platform;
        :param `size`: the control size. A value of (-1, -1) indicates a default size,
         chosen by either the windowing system or wxPython, depending on platform;
        :param integer `style`: the underlying `wx.Frame` style;
        :param `bitmap`: this must be a valid bitmap, that you may construct using
         whatever image file format supported by wxPython. If the file you load
         already supports mask/transparency (like png), the transparent areas
         will not be drawn on screen, and the L{AdvancedSplash} frame will have
         the shape defined only by *non-transparent* pixels.
         If you use other file formats that does not supports transparency, you
         can obtain the same effect as above by masking a specific colour in
         your `wx.Bitmap`.
        :param integer `timeout`: if you construct L{AdvancedSplash} using the style ``AS_TIMEOUT``,
         L{AdvancedSplash} will be destroyed after `timeout` milliseconds;
        :param integer `agwStyle`: this value specifies the L{AdvancedSplash} styles:

         ======================= =========== ==================================================
         Window Styles           Hex Value   Description
         ======================= =========== ==================================================
         ``AS_TIMEOUT``                  0x1 L{AdvancedSplash} will be destroyed after `timeout` milliseconds.
         ``AS_NOTIMEOUT``                0x2 L{AdvancedSplash} can be destroyed by clicking on it, pressing a key or by explicitly call the `Close()` method.
         ``AS_CENTER_ON_SCREEN``         0x4 L{AdvancedSplash} will be centered on screen.
         ``AS_CENTER_ON_PARENT``         0x8 L{AdvancedSplash} will be centered on parent.
         ``AS_NO_CENTER``               0x10 L{AdvancedSplash} will not be centered.
         ``AS_SHADOW_BITMAP``           0x20 If the bitmap you pass as input has no transparency, you can choose one colour that will be masked in your bitmap. the final shape of L{AdvancedSplash} will be defined only by non-transparent (non-masked) pixels.
         ======================= =========== ==================================================

        :param `shadowcolour`: if you construct L{AdvancedSplash} using the style
         ``AS_SHADOW_BITMAP``, here you can specify the colour that will be masked on
         your input bitmap. This has to be a valid wxPython colour.

        :type parent: `wx.Window`
        :type pos: tuple or `wx.Point`
        :type size: tuple or `wx.Size`
        :type bitmap: `wx.Bitmap`
        :type shadowcolour: `wx.Colour`

        :raise: `Exception` in the following cases:

         - The ``AS_TIMEOUT`` style is set but `timeout` is not a positive integer;
         - The ``AS_SHADOW_BITMAP`` style is set but `shadowcolour` is not a valid wxPython colour;
         - The L{AdvancedSplash} bitmap is an invalid `wx.Bitmap`.

        """

        wx.Frame.__init__(self, parent, id, "", pos, size, style)

        # Some Error Checking
        if agwStyle & AS_TIMEOUT and timeout <= 0:
            raise Exception('\nERROR: Style "AS_TIMEOUT" Used With Invalid "timeout" Parameter Value (' \
                            + str(timeout) + ')')

        if agwStyle & AS_SHADOW_BITMAP and not shadowcolour.IsOk():
            raise Exception('\nERROR: Style "AS_SHADOW_BITMAP" Used With Invalid "shadowcolour" Parameter')

        if not bitmap or not bitmap.IsOk():
            raise Exception("\nERROR: Bitmap Passed To AdvancedSplash Is Invalid.")

        if agwStyle & AS_SHADOW_BITMAP:
            # Our Bitmap Is Masked Accordingly To User Input
            self.bmp = self.ShadowBitmap(bitmap, shadowcolour)
        else:
            self.bmp = bitmap

        self._agwStyle = agwStyle

        # Setting Initial Properties
        self.SetText()
        self.SetTextFont()
        self.SetTextPosition()
        self.SetTextColour()

        # Calculate The Shape Of AdvancedSplash Using The Input-Modified Bitmap
        self.reg = wx.RegionFromBitmap(self.bmp)

        # Don't Know If It Works On Other Platforms!!
        # Tested Only In Windows XP/2000

        if wx.Platform == "__WXGTK__":
            self.Bind(wx.EVT_WINDOW_CREATE, self.SetSplashShape)
        else:
            self.SetSplashShape()

        w = self.bmp.GetWidth()
        h = self.bmp.GetHeight()

        # Set The AdvancedSplash Size To The Bitmap Size
        self.SetSize((w, h))

        if agwStyle & AS_CENTER_ON_SCREEN:
            self.CenterOnScreen()
        elif agwStyle & AS_CENTER_ON_PARENT:
            self.CenterOnParent()

        if agwStyle & AS_TIMEOUT:
            # Starts The Timer. Once Expired, AdvancedSplash Is Destroyed
            self._splashtimer = wx.PyTimer(self.OnNotify)
            self._splashtimer.Start(timeout)

        # Catch Some Mouse Events, To Behave Like wx.SplashScreen
        self.Bind(wx.EVT_PAINT, self.OnPaint)
        self.Bind(wx.EVT_CLOSE, self.OnCloseWindow)
        self.Bind(wx.EVT_MOUSE_EVENTS, self.OnMouseEvents)
        self.Bind(wx.EVT_CHAR, self.OnCharEvents)

        self.Show()

[docs]    def SetSplashShape(self, event=None):
        """
        Sets L{AdvancedSplash} shape using the region created from the bitmap.

        :param `event`: a `wx.WindowCreateEvent` event (GTK only, as GTK supports setting
         the window shape only during window creation).
        """

        self.SetShape(self.reg)

        if event is not None:
            event.Skip()

[docs]    def ShadowBitmap(self, bmp, shadowcolour):
        """
        Applies a mask on the bitmap accordingly to user input.

        :param `bmp`: the bitmap to which we want to apply the mask colour `shadowcolour`;
        :param `shadowcolour`: the mask colour for our bitmap.
        :type bmp: `wx.Bitmap`
        :type shadowcolour: `wx.Colour`

        :return: A masked version of the input bitmap, an instance of `wx.Bitmap`.
        """

        mask = wx.Mask(bmp, shadowcolour)
        bmp.SetMask(mask)

        return bmp

[docs]    def OnPaint(self, event):
        """
        Handles the ``wx.EVT_PAINT`` event for L{AdvancedSplash}.

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

        dc = wx.PaintDC(self)

        # Here We Redraw The Bitmap Over The Frame
        dc.DrawBitmap(self.bmp, 0, 0, True)

        # We Draw The Text Anyway, Wheter It Is Empty ("") Or Not
        textcolour = self.GetTextColour()
        textfont = self.GetTextFont()
        textpos = self.GetTextPosition()
        text = self.GetText()

        dc.SetFont(textfont[0])
        dc.SetTextForeground(textcolour)
        dc.DrawText(text, textpos[0], textpos[1])

        # Seems like this only helps on OS X.
        if wx.Platform == "__WXMAC__":
            wx.SafeYield(self, True)

[docs]    def OnNotify(self):
        """ Handles the timer expiration, and calls the `Close()` method. """

        self.Close()

[docs]    def OnMouseEvents(self, event):
        """
        Handles the ``wx.EVT_MOUSE_EVENTS`` events for L{AdvancedSplash}.

        :param `event`: a `wx.MouseEvent` to be processed.

        :note: This reproduces the behavior of `wx.SplashScreen`.
        """

        if event.LeftDown() or event.RightDown():
            self.Close()

        event.Skip()

[docs]    def OnCharEvents(self, event):
        """
        Handles the ``wx.EVT_CHAR`` event for L{AdvancedSplash}.

        :param `event`: a `wx.KeyEvent` to be processed.

        :note: This reproduces the behavior of `wx.SplashScreen`.
        """

        self.Close()

[docs]    def OnCloseWindow(self, event):
        """
        Handles the ``wx.EVT_CLOSE`` event for L{AdvancedSplash}.

        :param `event`: a `wx.CloseEvent` to be processed.

        :note: This reproduces the behavior of `wx.SplashScreen`.
        """

        if hasattr(self, "_splashtimer"):
            self._splashtimer.Stop()
            del self._splashtimer

        self.Destroy()

[docs]    def SetText(self, text=None):
        """
        Sets the text to be displayed on L{AdvancedSplash}.

        :param `text`: the text we want to display on top of the bitmap. If `text` is
         set to ``None``, nothing will be drawn on top of the bitmap.
        :type text: string or ``None``
        """

        if text is None:
            text = ""

        self._text = text

        self.Refresh()
        self.Update()

[docs]    def GetText(self):
        """
        Returns the text displayed on L{AdvancedSplash}.

        :return: A string representing the text drawn on top of the L{AdvancedSplash} bitmap.
        """

        return self._text

[docs]    def SetTextFont(self, font=None):
        """
        Sets the font for the text in L{AdvancedSplash}.

        :param `font`: the font to use while drawing the text on top of our bitmap. If `font`
         is ``None``, a simple generic font is generated.
        :type font: `wx.Font` or ``None``
        """

        if font is None:
            self._textfont = wx.Font(1, wx.SWISS, wx.NORMAL, wx.BOLD, False)
            self._textsize = 10.0
            self._textfont.SetPointSize(self._textsize)
        else:
            self._textfont = font
            self._textsize = font.GetPointSize()
            self._textfont.SetPointSize(self._textsize)

        self.Refresh()
        self.Update()

[docs]    def GetTextFont(self):
        """
        Gets the font for the text in L{AdvancedSplash}.

        :return: An instance of `wx.Font` to draw the text and a `wx.Size` object containing
         the text width an height, in pixels.
        """

        return self._textfont, self._textsize

[docs]    def SetTextColour(self, colour=None):
        """
        Sets the colour for the text in L{AdvancedSplash}.

        :param `colour`: the text colour to use while drawing the text on top of our
         bitmap. If `colour` is ``None``, then ``wx.BLACK`` is used.
        :type colour: `wx.Colour` or ``None``
        """

        if colour is None:
            colour = wx.BLACK

        self._textcolour = colour
        self.Refresh()
        self.Update()

[docs]    def GetTextColour(self):
        """
        Gets the colour for the text in L{AdvancedSplash}.

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

        return self._textcolour

[docs]    def SetTextPosition(self, position=None):
        """
        Sets the text position inside L{AdvancedSplash} frame.

        :param `position`: the text position inside our bitmap. If `position` is ``None``,
         the text will be placed at the top-left corner.
        :type position: tuple or ``None``
        """

        if position is None:
            position = (0, 0)

        self._textpos = position
        self.Refresh()
        self.Update()

[docs]    def GetTextPosition(self):
        """
        Returns the text position inside L{AdvancedSplash} frame.

        :return: A tuple containing the text `x` and `y` position inside the L{AdvancedSplash} frame.
        """

        return self._textpos

[docs]    def GetSplashStyle(self):
        """
        Returns a list of strings and a list of integers containing the styles.

        :return: Two Python lists containing the style name and style values for L{AdvancedSplash}.
        """

        stringstyle = []
        integerstyle = []

        if self._agwStyle & AS_TIMEOUT:
            stringstyle.append("AS_TIMEOUT")
            integerstyle.append(AS_TIMEOUT)

        if self._agwStyle & AS_NOTIMEOUT:
            stringstyle.append("AS_NOTIMEOUT")
            integerstyle.append(AS_NOTIMEOUT)

        if self._agwStyle & AS_CENTER_ON_SCREEN:
            stringstyle.append("AS_CENTER_ON_SCREEN")
            integerstyle.append(AS_CENTER_ON_SCREEN)

        if self._agwStyle & AS_CENTER_ON_PARENT:
            stringstyle.append("AS_CENTER_ON_PARENT")
            integerstyle.append(AS_CENTER_ON_PARENT)

        if self._agwStyle & AS_NO_CENTER:
            stringstyle.append("AS_NO_CENTER")
            integerstyle.append(AS_NO_CENTER)

        if self._agwStyle & AS_SHADOW_BITMAP:
            stringstyle.append("AS_SHADOW_BITMAP")
            integerstyle.append(AS_SHADOW_BITMAP)

        return stringstyle, integerstyle

Navigation

  • index
  • modules |
  • Home |
  • Gallery |
  • Contents»
  • Module code »
  • advancedsplash


aquabutton

  • modules |
  • Home |
  • Gallery |
  • Contents»
  • Module code »
  • aquabutton

Source code for aquabutton

# --------------------------------------------------------------------------------- #
# AQUABUTTON wxPython IMPLEMENTATION
#
# Andrea Gavana, @ 07 October 2008
# Latest Revision: 24 Nov 2011, 22.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
# --------------------------------------------------------------------------------- #

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

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

L{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 `wx.wxEVT_COMMAND_BUTTON_CLICKED` event, when the button is clicked.
================= ==================================================

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

L{AquaButton} control is distributed under the wxPython license.

Latest Revision: Andrea Gavana @ 22 Nov 2011, 22.00 GMT

Version 0.4

"""

import wx

# Constants for the hovering and clicking effects
HOVER = 1
""" Indicates that the mouse is hovering over L{AquaButton} """
CLICK = 2
""" Indicates that L{AquaButton} has been clicked """

[docs]class AquaButtonEvent(wx.PyCommandEvent):
    """ Event sent from the L{AquaButton} buttons when the button is activated. """

[docs]    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

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

        :param `btn`: the button object, an instance of L{AquaButton}.
        """

        self.theButton = btn

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

        :return: An instance of L{AquaButton}.
        """

        return self.theButton

[docs]class AquaButton(wx.PyControl):
    """ This is the main class implementation of L{AquaButton}. """

[docs]    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 `wx.Window` `parent`: parent window. Must not be ``None``;
        :param integer `id`: window identifier. A value of -1 indicates a default value;
        :param `wx.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 `wx.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 `wx.Size`
        :param integer `style`: the button style (unused);
        :param `wx.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
        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

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

        :param `bitmap`: the bitmap label to set, an instance of `wx.Bitmap`.
        """

        self._bitmap = bitmap
        self.Refresh()

[docs]    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 `wx.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 `wx.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)

[docs]    def OnPaint(self, event):
        """
        Handles the ``wx.EVT_PAINT`` event for L{AquaButton}.

        :param `event`: a `wx.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 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, 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()

[docs]    def GetPath(self, gc, rc, r):
        """
        Returns a rounded `wx.GraphicsPath` rectangle.

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

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

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

[docs]    def OnSize(self, event):
        """
        Handles the ``wx.EVT_SIZE`` event for L{AquaButton}.

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

        self.Invalidate()

[docs]    def OnLeftDown(self, event):
        """
        Handles the ``wx.EVT_LEFT_DOWN`` event for L{AquaButton}.

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

        if not self.IsEnabled():
            return

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

[docs]    def OnLeftUp(self, event):
        """
        Handles the ``wx.EVT_LEFT_UP`` event for L{AquaButton}.

        :param `event`: a `wx.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()

[docs]    def OnMouseEnter(self, event):
        """
        Handles the ``wx.EVT_ENTER_WINDOW`` event for L{AquaButton}.

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

        if not self.IsEnabled():
            return

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

[docs]    def OnMouseLeave(self, event):
        """
        Handles the ``wx.EVT_LEAVE_WINDOW`` event for L{AquaButton}.

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

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

[docs]    def OnGainFocus(self, event):
        """
        Handles the ``wx.EVT_SET_FOCUS`` event for L{AquaButton}.

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

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

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

[docs]    def OnLoseFocus(self, event):
        """
        Handles the ``wx.EVT_KILL_FOCUS`` event for L{AquaButton}.

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

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

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

[docs]    def OnKeyDown(self, event):
        """
        Handles the ``wx.EVT_KEY_DOWN`` event for L{AquaButton}.

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

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

[docs]    def OnKeyUp(self, event):
        """
        Handles the ``wx.EVT_KEY_UP`` event for L{AquaButton}.

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

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

[docs]    def OnPulseTimer(self, event):
        """
        Handles the ``wx.EVT_TIMER`` event for L{AquaButton}.

        :param `event`: a `wx.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)

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

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

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

    SetBestSize = SetInitialSize

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

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

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

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

        :return: an instance of `wx.VisualAttributes`.

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

        return wx.Button.GetClassDefaultAttributes()

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

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

        return False

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

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

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

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

[docs]    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 L{AquaButton} gains focus,
         ``False`` to disable this effect.
        """

        if pulse == self._pulseOnFocus:
            return

        self._pulseOnFocus = pulse
        self.Invalidate()

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

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

        return self._pulseOnFocus

[docs]    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 `wx.Size`.

        :note: Overridden from `wx.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)

[docs]    def SetBackgroundColour(self, colour):
        """
        Sets the L{AquaButton} background colour.

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

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

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

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

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

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

        return self._backColour

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

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

        self._hoverColour = colour
        self.Invalidate()

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

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

        return self._hoverColour

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

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

        self._disableColour = colour
        self.Invalidate()

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

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

        return self._disableColour

    SetBackgroundColor = SetBackgroundColour
    SetHoverColor = SetHoverColour
    GetHoverColor = GetHoverColour
    SetDisabledColor = SetDisabledColour
    GetDisabledColor = GetDisabledColour

[docs]    def SetForegroundColour(self, colour):
        """
        Sets the L{AquaButton} foreground (text) colour.

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

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

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

[docs]    def GetForegroundColour(self):
        """
        Returns the text colour for L{AquaButton}.

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

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

        return self._textColour

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

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

        self.Refresh()

[docs]    def SetDefault(self):
        """
        This sets the L{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 `wx.Window.SetFocus` which sets the
         keyboard focus for windows and text panel items, and `wx.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 L{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)

[docs]    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)

[docs]class __ToggleMixin(object):
    """
    A mixin that allows to transform L{AquaButton} in the corresponding toggle button.
    """

[docs]    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

[docs]    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

[docs]    def OnLeftDown(self, event):
        """
        Handles the ``wx.EVT_LEFT_DOWN`` event for L{AquaButton} when used as toggle button.

        :param `event`: a `wx.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()

[docs]    def OnLeftUp(self, event):
        """
        Handles the ``wx.EVT_LEFT_UP`` event for L{AquaButton} when used as toggle button.

        :param `event`: a `wx.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()

[docs]    def OnKeyDown(self, event):
        """
        Handles the ``wx.EVT_KEY_DOWN`` event for L{AquaButton} when used as toggle button.

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

        event.Skip()

[docs]    def OnMotion(self, event):
        """
        Handles the ``wx.EVT_MOTION`` event for L{AquaButton} when used as toggle button.

        :param `event`: a `wx.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()

[docs]    def OnKeyUp(self, event):
        """
        Handles the ``wx.EVT_KEY_UP`` event for L{AquaButton} when used as toggle button.

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

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

        event.Skip()

[docs]    def OnPaint(self, event):
        """
        Handles the ``wx.EVT_PAINT`` event for L{AquaButton} when used as toggle button.

        :param `event`: a `wx.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()

[docs]class AquaToggleButton(__ToggleMixin, AquaButton):
    """ An L{AquaButton} toggle button. """
    pass

Navigation

  • index
  • modules |
  • Home |
  • Gallery |
  • Contents»
  • Module code »
  • aquabutton


artmanager

  • modules |
  • Home |
  • Gallery |
  • Contents»
  • Module code »
  • artmanager

Source code for artmanager

"""
This module contains drawing routines and customizations for the AGW widgets
L{LabelBook} and L{FlatMenu}.
"""

import wx
import cStringIO
import random

from fmresources import *

# ---------------------------------------------------------------------------- #
# Class DCSaver
# ---------------------------------------------------------------------------- #

_ = wx.GetTranslation

_libimported = None

if wx.Platform == "__WXMSW__":
    osVersion = wx.GetOsVersion()
    # Shadows behind menus are supported only in XP
    if osVersion[1] == 5 and osVersion[2] == 1:
        try:
            import win32api
            import win32con
            import winxpgui
            _libimported = "MH"
        except:
            try:
                import ctypes
                _libimported = "ctypes"
            except:
                pass
    else:
        _libimported = None

[docs]class DCSaver(object):
    """
    Construct a DC saver. The dc is copied as-is.
    """

[docs]    def __init__(self, pdc):
        """
        Default class constructor.

        :param `pdc`: an instance of `wx.DC`.
        """

        self._pdc = pdc
        self._pen = pdc.GetPen()
        self._brush = pdc.GetBrush()

    def __del__(self):
        """ While destructing, restores the dc pen and brush. """

        if self._pdc:
            self._pdc.SetPen(self._pen)
            self._pdc.SetBrush(self._brush)

# ---------------------------------------------------------------------------- #
# Class RendererBase
# ---------------------------------------------------------------------------- #

[docs]class RendererBase(object):
    """ Base class for all theme renderers. """

[docs]    def __init__(self):
        """ Default class constructor. Intentionally empty. """

        pass

[docs]    def DrawButtonBorders(self, dc, rect, penColour, brushColour):
        """
        Draws borders for buttons.

        :param `dc`: an instance of `wx.DC`;
        :param `wx.Rect` `rect`: the button's client rectangle;
        :param `penColour`: a valid `wx.Colour` for the pen border;
        :param `brushColour`: a valid `wx.Colour` for the brush.
        """

        # Keep old pen and brush
        dcsaver = DCSaver(dc)
        dc.SetPen(wx.Pen(penColour))
        dc.SetBrush(wx.Brush(brushColour))
        dc.DrawRectangleRect(rect)

[docs]    def DrawBitmapArea(self, dc, xpm_name, rect, baseColour, flipSide):
        """
        Draws the area below a bitmap and the bitmap itself using a gradient shading.

        :param `dc`: an instance of `wx.DC`;
        :param string `xpm_name`: a name of a XPM bitmap;
        :param `wx.Rect` `rect`: the bitmap client rectangle;
        :param `baseColour`: a valid `wx.Colour` for the bitmap background;
        :param bool `flipSide`: ``True`` to flip the gradient direction, ``False`` otherwise.
        """

        # draw the gradient area
        if not flipSide:
            ArtManager.Get().PaintDiagonalGradientBox(dc, rect, wx.WHITE,
                                                      ArtManager.Get().LightColour(baseColour, 20),
                                                      True, False)
        else:
            ArtManager.Get().PaintDiagonalGradientBox(dc, rect, ArtManager.Get().LightColour(baseColour, 20),
                                                      wx.WHITE, True, False)

        # draw arrow
        arrowDown = wx.BitmapFromXPMData(xpm_name)
        arrowDown.SetMask(wx.Mask(arrowDown, wx.WHITE))
        dc.DrawBitmap(arrowDown, rect.x + 1 , rect.y + 1, True)

[docs]    def DrawBitmapBorders(self, dc, rect, penColour, bitmapBorderUpperLeftPen):
        """
        Draws borders for a bitmap.

        :param `dc`: an instance of `wx.DC`;
        :param `wx.Rect` `rect`: the button's client rectangle;
        :param `penColour`: a valid `wx.Colour` for the pen border;
        :param `bitmapBorderUpperLeftPen`: a valid `wx.Colour` for the pen upper
         left border.
        """

        # Keep old pen and brush
        dcsaver = DCSaver(dc)

        # lower right size
        dc.SetPen(wx.Pen(penColour))
        dc.DrawLine(rect.x, rect.y + rect.height - 1, rect.x + rect.width, rect.y + rect.height - 1)
        dc.DrawLine(rect.x + rect.width - 1, rect.y, rect.x + rect.width - 1, rect.y + rect.height)

        # upper left side
        dc.SetPen(wx.Pen(bitmapBorderUpperLeftPen))
        dc.DrawLine(rect.x, rect.y, rect.x + rect.width, rect.y)
        dc.DrawLine(rect.x, rect.y, rect.x, rect.y + rect.height)

[docs]    def GetMenuFaceColour(self):
        """
        Returns the foreground colour for the menu.

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

        return ArtManager.Get().LightColour(wx.SystemSettings_GetColour(wx.SYS_COLOUR_3DFACE), 80)

[docs]    def GetTextColourEnable(self):
        """
        Returns the colour used for text colour when enabled.

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

        return wx.BLACK

[docs]    def GetTextColourDisable(self):
        """
        Returns the colour used for text colour when disabled.

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

        return ArtManager.Get().LightColour(wx.SystemSettings_GetColour(wx.SYS_COLOUR_GRAYTEXT), 30)

[docs]    def GetFont(self):
        """
        Returns the font used for text.

        :return: An instance of `wx.Font`.
        """

        return wx.SystemSettings_GetFont(wx.SYS_DEFAULT_GUI_FONT)

# ---------------------------------------------------------------------------- #
# Class RendererXP
# ---------------------------------------------------------------------------- #

[docs]class RendererXP(RendererBase):
    """ Xp-Style renderer. """

[docs]    def __init__(self):
        """ Default class constructor. """

        RendererBase.__init__(self)

[docs]    def DrawButton(self, dc, rect, state, input=None):
        """
        Draws a button using the XP theme.

        :param `dc`: an instance of `wx.DC`;
        :param `wx.Rect` `rect`: the button's client rectangle;
        :param integer `state`: the button state;
        :param `input`: a flag used to call the right method.
        """

        if input is None or type(input) == type(False):
            self.DrawButtonTheme(dc, rect, state, input)
        else:
            self.DrawButtonColour(dc, rect, state, input)

[docs]    def DrawButtonTheme(self, dc, rect, state, useLightColours=None):
        """
        Draws a button using the XP theme.

        :param `dc`: an instance of `wx.DC`;
        :param `wx.Rect` `rect`: the button's client rectangle;
        :param integer `state`: the button state;
        :param bool `useLightColours`: ``True`` to use light colours, ``False`` otherwise.
        """

        # switch according to the status
        if state == ControlFocus:
            penColour = ArtManager.Get().FrameColour()
            brushColour = ArtManager.Get().BackgroundColour()
        elif state == ControlPressed:
            penColour = ArtManager.Get().FrameColour()
            brushColour = ArtManager.Get().HighlightBackgroundColour()
        else:
            penColour = ArtManager.Get().FrameColour()
            brushColour = ArtManager.Get().BackgroundColour()

        # Draw the button borders
        self.DrawButtonBorders(dc, rect, penColour, brushColour)

[docs]    def DrawButtonColour(self, dc, rect, state, colour):
        """
        Draws a button using the XP theme.

        :param `dc`: an instance of `wx.DC`;
        :param `wx.Rect` `rect`: the button's client rectangle;
        :param integer `state`: the button state;
        :param `colour`: a valid `wx.Colour` instance.
        """

        # switch according to the status
        if statet == ControlFocus:
            penColour = colour
            brushColour = ArtManager.Get().LightColour(colour, 75)
        elif state == ControlPressed:
            penColour = colour
            brushColour = ArtManager.Get().LightColour(colour, 60)
        else:
            penColour = colour
            brushColour = ArtManager.Get().LightColour(colour, 75)

        # Draw the button borders
        self.DrawButtonBorders(dc, rect, penColour, brushColour)

[docs]    def DrawMenuBarBg(self, dc, rect):
        """
        Draws the menu bar background according to the active theme.

        :param `dc`: an instance of `wx.DC`;
        :param `wx.Rect` `rect`: the menu bar's client rectangle.
        """

        # For office style, we simple draw a rectangle with a gradient colouring
        artMgr = ArtManager.Get()
        vertical = artMgr.GetMBVerticalGradient()

        dcsaver = DCSaver(dc)

        # fill with gradient
        startColour = artMgr.GetMenuBarFaceColour()
        if artMgr.IsDark(startColour):
            startColour = artMgr.LightColour(startColour, 50)

        endColour = artMgr.LightColour(startColour, 90)
        artMgr.PaintStraightGradientBox(dc, rect, startColour, endColour, vertical)

        # Draw the border
        if artMgr.GetMenuBarBorder():

            dc.SetPen(wx.Pen(startColour))
            dc.SetBrush(wx.TRANSPARENT_BRUSH)
            dc.DrawRectangleRect(rect)

[docs]    def DrawToolBarBg(self, dc, rect):
        """
        Draws the toolbar background according to the active theme.

        :param `dc`: an instance of `wx.DC`;
        :param `wx.Rect` `rect`: the toolbar's client rectangle.
        """

        artMgr = ArtManager.Get()

        if not artMgr.GetRaiseToolbar():
            return

        # For office style, we simple draw a rectangle with a gradient colouring
        vertical = artMgr.GetMBVerticalGradient()

        dcsaver = DCSaver(dc)

        # fill with gradient
        startColour = artMgr.GetMenuBarFaceColour()
        if artMgr.IsDark(startColour):
            startColour = artMgr.LightColour(startColour, 50)

        startColour = artMgr.LightColour(startColour, 20)

        endColour   = artMgr.LightColour(startColour, 90)
        artMgr.PaintStraightGradientBox(dc, rect, startColour, endColour, vertical)
        artMgr.DrawBitmapShadow(dc, rect)

[docs]    def GetTextColourEnable(self):
        """
        Returns the colour used for text colour when enabled.

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

        return wx.BLACK

# ---------------------------------------------------------------------------- #
# Class RendererMSOffice2007
# ---------------------------------------------------------------------------- #

[docs]class RendererMSOffice2007(RendererBase):
    """ Windows MS Office 2007 style. """

[docs]    def __init__(self):
        """ Default class constructor. """

        RendererBase.__init__(self)

[docs]    def GetColoursAccordingToState(self, state):
        """
        Returns a `wx.Colour` according to the menu item state.

        :param integer `state`: one of the following bits:

         ==================== ======= ==========================
         Item State            Value  Description
         ==================== ======= ==========================
         ``ControlPressed``         0 The item is pressed
         ``ControlFocus``           1 The item is focused
         ``ControlDisabled``        2 The item is disabled
         ``ControlNormal``          3 Normal state
         ==================== ======= ==========================

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

        # switch according to the status
        if state == ControlFocus:
            upperBoxTopPercent = 95
            upperBoxBottomPercent = 50
            lowerBoxTopPercent = 40
            lowerBoxBottomPercent = 90
            concaveUpperBox = True
            concaveLowerBox = True

        elif state == ControlPressed:
            upperBoxTopPercent = 75
            upperBoxBottomPercent = 90
            lowerBoxTopPercent = 90
            lowerBoxBottomPercent = 40
            concaveUpperBox = True
            concaveLowerBox = True

        elif state == ControlDisabled:
            upperBoxTopPercent = 100
            upperBoxBottomPercent = 100
            lowerBoxTopPercent = 70
            lowerBoxBottomPercent = 70
            concaveUpperBox = True
            concaveLowerBox = True

        else:
            upperBoxTopPercent = 90
            upperBoxBottomPercent = 50
            lowerBoxTopPercent = 30
            lowerBoxBottomPercent = 75
            concaveUpperBox = True
            concaveLowerBox = True

        return upperBoxTopPercent, upperBoxBottomPercent, lowerBoxTopPercent, lowerBoxBottomPercent, \
               concaveUpperBox, concaveLowerBox

[docs]    def DrawButton(self, dc, rect, state, useLightColours):
        """
        Draws a button using the MS Office 2007 theme.

        :param `dc`: an instance of `wx.DC`;
        :param `wx.Rect` `rect`: the button's client rectangle;
        :param integer `state`: the button state;
        :param bool `useLightColours`: ``True`` to use light colours, ``False`` otherwise.
        """

        self.DrawButtonColour(dc, rect, state, ArtManager.Get().GetThemeBaseColour(useLightColours))

[docs]    def DrawButtonColour(self, dc, rect, state, colour):
        """
        Draws a button using the MS Office 2007 theme.

        :param `dc`: an instance of `wx.DC`;
        :param `wx.Rect` `rect`: the button's client rectangle;
        :param integer `state`: the button state;
        :param `colour`: a valid `wx.Colour` instance.
        """

        artMgr = ArtManager.Get()

        # Keep old pen and brush
        dcsaver = DCSaver(dc)

        # Define the rounded rectangle base on the given rect
        # we need an array of 9 points for it
        baseColour = colour

        # Define the middle points
        leftPt = wx.Point(rect.x, rect.y + (rect.height / 2))
        rightPt = wx.Point(rect.x + rect.width-1, rect.y + (rect.height / 2))

        # Define the top region
        top = wx.RectPP((rect.GetLeft(), rect.GetTop()), rightPt)
        bottom = wx.RectPP(leftPt, (rect.GetRight(), rect.GetBottom()))

        upperBoxTopPercent, upperBoxBottomPercent, lowerBoxTopPercent, lowerBoxBottomPercent, \
                            concaveUpperBox, concaveLowerBox = self.GetColoursAccordingToState(state)

        topStartColour = artMgr.LightColour(baseColour, upperBoxTopPercent)
        topEndColour = artMgr.LightColour(baseColour, upperBoxBottomPercent)
        bottomStartColour = artMgr.LightColour(baseColour, lowerBoxTopPercent)
        bottomEndColour = artMgr.LightColour(baseColour, lowerBoxBottomPercent)

        artMgr.PaintStraightGradientBox(dc, top, topStartColour, topEndColour)
        artMgr.PaintStraightGradientBox(dc, bottom, bottomStartColour, bottomEndColour)

        rr = wx.Rect(rect.x, rect.y, rect.width, rect.height)
        dc.SetBrush(wx.TRANSPARENT_BRUSH)

        frameColour = artMgr.LightColour(baseColour, 60)
        dc.SetPen(wx.Pen(frameColour))
        dc.DrawRectangleRect(rr)

        wc = artMgr.LightColour(baseColour, 80)
        dc.SetPen(wx.Pen(wc))
        rr.Deflate(1, 1)
        dc.DrawRectangleRect(rr)

[docs]    def DrawMenuBarBg(self, dc, rect):
        """
        Draws the menu bar background according to the active theme.

        :param `dc`: an instance of `wx.DC`;
        :param `wx.Rect` `rect`: the menu bar's client rectangle.
        """

        # Keep old pen and brush
        dcsaver = DCSaver(dc)
        artMgr = ArtManager.Get()
        baseColour = artMgr.GetMenuBarFaceColour()

        dc.SetBrush(wx.Brush(wx.SystemSettings_GetColour(wx.SYS_COLOUR_3DFACE)))
        dc.SetPen(wx.Pen(wx.SystemSettings_GetColour(wx.SYS_COLOUR_3DFACE)))
        dc.DrawRectangleRect(rect)

        # Define the rounded rectangle base on the given rect
        # we need an array of 9 points for it
        regPts = [wx.Point() for ii in xrange(9)]
        radius = 2

        regPts[0] = wx.Point(rect.x, rect.y + radius)
        regPts[1] = wx.Point(rect.x+radius, rect.y)
        regPts[2] = wx.Point(rect.x+rect.width-radius-1, rect.y)
        regPts[3] = wx.Point(rect.x+rect.width-1, rect.y + radius)
        regPts[4] = wx.Point(rect.x+rect.width-1, rect.y + rect.height - radius - 1)
        regPts[5] = wx.Point(rect.x+rect.width-radius-1, rect.y + rect.height-1)
        regPts[6] = wx.Point(rect.x+radius, rect.y + rect.height-1)
        regPts[7] = wx.Point(rect.x, rect.y + rect.height - radius - 1)
        regPts[8] = regPts[0]

        # Define the middle points

        factor = artMgr.GetMenuBgFactor()

        leftPt1 = wx.Point(rect.x, rect.y + (rect.height / factor))
        leftPt2 = wx.Point(rect.x, rect.y + (rect.height / factor)*(factor-1))

        rightPt1 = wx.Point(rect.x + rect.width, rect.y + (rect.height / factor))
        rightPt2 = wx.Point(rect.x + rect.width, rect.y + (rect.height / factor)*(factor-1))

        # Define the top region
        topReg = [wx.Point() for ii in xrange(7)]
        topReg[0] = regPts[0]
        topReg[1] = regPts[1]
        topReg[2] = wx.Point(regPts[2].x+1, regPts[2].y)
        topReg[3] = wx.Point(regPts[3].x + 1, regPts[3].y)
        topReg[4] = wx.Point(rightPt1.x, rightPt1.y+1)
        topReg[5] = wx.Point(leftPt1.x, leftPt1.y+1)
        topReg[6] = topReg[0]

        # Define the middle region
        middle = wx.RectPP(leftPt1, wx.Point(rightPt2.x - 2, rightPt2.y))

        # Define the bottom region
        bottom = wx.RectPP(leftPt2, wx.Point(rect.GetRight() - 1, rect.GetBottom()))

        topStartColour   = artMgr.LightColour(baseColour, 90)
        topEndColour = artMgr.LightColour(baseColour, 60)
        bottomStartColour = artMgr.LightColour(baseColour, 40)
        bottomEndColour   = artMgr.LightColour(baseColour, 20)

        topRegion = wx.RegionFromPoints(topReg)

        artMgr.PaintGradientRegion(dc, topRegion, topStartColour, topEndColour)
        artMgr.PaintStraightGradientBox(dc, bottom, bottomStartColour, bottomEndColour)
        artMgr.PaintStraightGradientBox(dc, middle, topEndColour, bottomStartColour)

[docs]    def DrawToolBarBg(self, dc, rect):
        """
        Draws the toolbar background according to the active theme.

        :param `dc`: an instance of `wx.DC`;
        :param `wx.Rect` `rect`: the toolbar's client rectangle.
        """

        artMgr = ArtManager.Get()

        if not artMgr.GetRaiseToolbar():
            return

        # Keep old pen and brush
        dcsaver = DCSaver(dc)

        baseColour = artMgr.GetMenuBarFaceColour()
        baseColour = artMgr.LightColour(baseColour, 20)

        dc.SetBrush(wx.Brush(wx.SystemSettings_GetColour(wx.SYS_COLOUR_3DFACE)))
        dc.SetPen(wx.Pen(wx.SystemSettings_GetColour(wx.SYS_COLOUR_3DFACE)))
        dc.DrawRectangleRect(rect)

        radius = 2

        # Define the rounded rectangle base on the given rect
        # we need an array of 9 points for it
        regPts = [None]*9

        regPts[0] = wx.Point(rect.x, rect.y + radius)
        regPts[1] = wx.Point(rect.x+radius, rect.y)
        regPts[2] = wx.Point(rect.x+rect.width-radius-1, rect.y)
        regPts[3] = wx.Point(rect.x+rect.width-1, rect.y + radius)
        regPts[4] = wx.Point(rect.x+rect.width-1, rect.y + rect.height - radius - 1)
        regPts[5] = wx.Point(rect.x+rect.width-radius-1, rect.y + rect.height-1)
        regPts[6] = wx.Point(rect.x+radius, rect.y + rect.height-1)
        regPts[7] = wx.Point(rect.x, rect.y + rect.height - radius - 1)
        regPts[8] = regPts[0]

        # Define the middle points
        factor = artMgr.GetMenuBgFactor()

        leftPt1 = wx.Point(rect.x, rect.y + (rect.height / factor))
        rightPt1 = wx.Point(rect.x + rect.width, rect.y + (rect.height / factor))

        leftPt2 = wx.Point(rect.x, rect.y + (rect.height / factor)*(factor-1))
        rightPt2 = wx.Point(rect.x + rect.width, rect.y + (rect.height / factor)*(factor-1))

        # Define the top region
        topReg = [None]*7
        topReg[0] = regPts[0]
        topReg[1] = regPts[1]
        topReg[2] = wx.Point(regPts[2].x+1, regPts[2].y)
        topReg[3] = wx.Point(regPts[3].x + 1, regPts[3].y)
        topReg[4] = wx.Point(rightPt1.x, rightPt1.y+1)
        topReg[5] = wx.Point(leftPt1.x, leftPt1.y+1)
        topReg[6] = topReg[0]

        # Define the middle region
        middle = wx.RectPP(leftPt1, wx.Point(rightPt2.x - 2, rightPt2.y))

        # Define the bottom region
        bottom = wx.RectPP(leftPt2, wx.Point(rect.GetRight() - 1, rect.GetBottom()))

        topStartColour   = artMgr.LightColour(baseColour, 90)
        topEndColour = artMgr.LightColour(baseColour, 60)
        bottomStartColour = artMgr.LightColour(baseColour, 40)
        bottomEndColour   = artMgr.LightColour(baseColour, 20)

        topRegion = wx.RegionFromPoints(topReg)

        artMgr.PaintGradientRegion(dc, topRegion, topStartColour, topEndColour)
        artMgr.PaintStraightGradientBox(dc, bottom, bottomStartColour, bottomEndColour)
        artMgr.PaintStraightGradientBox(dc, middle, topEndColour, bottomStartColour)

        artMgr.DrawBitmapShadow(dc, rect)

[docs]    def GetTextColourEnable(self):
        """
        Returns the colour used for text colour when enabled.

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

        return wx.NamedColour("MIDNIGHT BLUE")

# ---------------------------------------------------------------------------- #
# Class ArtManager
# ---------------------------------------------------------------------------- #

[docs]class ArtManager(wx.EvtHandler):

    """
    This class provides various art utilities, such as creating shadow, providing
    lighter / darker colours for a given colour, etc...
    """

    _alignmentBuffer = 7
    _menuTheme = StyleXP
    _verticalGradient = False
    _renderers = {StyleXP: None, Style2007: None}
    _bmpShadowEnabled = False
    _ms2007sunken = False
    _drowMBBorder = True
    _menuBgFactor = 5
    _menuBarColourScheme = _("Default")
    _raiseTB = True
    _bitmaps = {}
    _transparency = 255

[docs]    def __init__(self):
        """ Default class constructor. """

        wx.EvtHandler.__init__(self)
        self._menuBarBgColour = wx.SystemSettings_GetColour(wx.SYS_COLOUR_3DFACE)

        # connect an event handler to the system colour change event
        self.Bind(wx.EVT_SYS_COLOUR_CHANGED, self.OnSysColourChange)

[docs]    def SetTransparency(self, amount):
        """
        Sets the alpha channel value for transparent windows.

        :param integer `amount`: the actual transparency value (between 0 and 255).

        :raise: `Exception` if the `amount` parameter is lower than ``0`` or greater than ``255``.
        """

        if self._transparency == amount:
            return

        if amount < 0 or amount > 255:
            raise Exception("Invalid transparency value")

        self._transparency = amount

[docs]    def GetTransparency(self):
        """
        Returns the alpha channel value for transparent windows.

        :return: An integer representing the alpha channel value.
        """

        return self._transparency

[docs]    def ConvertToBitmap(self, xpm, alpha=None):
        """
        Convert the given image to a bitmap, optionally overlaying an alpha
        channel to it.

        :param `xpm`: a list of strings formatted as XPM;
        :type `xpm`: list of strings
        :param `alpha`: a list of alpha values, the same size as the xpm bitmap.
        :type `alpha`: list of integers

        :return: An instance of `wx.Bitmap`.
        """

        if alpha is not None:

            img = wx.BitmapFromXPMData(xpm)
            img = img.ConvertToImage()
            x, y = img.GetWidth(), img.GetHeight()
            img.InitAlpha()
            for jj in xrange(y):
                for ii in xrange(x):
                    img.SetAlpha(ii, jj, alpha[jj*x+ii])

        else:

            stream = cStringIO.StringIO(xpm)
            img = wx.ImageFromStream(stream)

        return wx.BitmapFromImage(img)

[docs]    def Initialize(self):
        """ Initializes the bitmaps and colours. """

        # create wxBitmaps from the xpm's
        self._rightBottomCorner = self.ConvertToBitmap(shadow_center_xpm, shadow_center_alpha)
        self._bottom = self.ConvertToBitmap(shadow_bottom_xpm, shadow_bottom_alpha)
        self._bottomLeft = self.ConvertToBitmap(shadow_bottom_left_xpm, shadow_bottom_left_alpha)
        self._rightTop = self.ConvertToBitmap(shadow_right_top_xpm, shadow_right_top_alpha)
        self._right = self.ConvertToBitmap(shadow_right_xpm, shadow_right_alpha)

        # initialise the colour map
        self.InitColours()
        self.SetMenuBarColour(self._menuBarColourScheme)

        # Create common bitmaps
        self.FillStockBitmaps()

[docs]    def FillStockBitmaps(self):
        """ Initializes few standard bitmaps. """

        bmp = self.ConvertToBitmap(arrow_down, alpha=None)
        bmp.SetMask(wx.Mask(bmp, wx.Colour(0, 128, 128)))
        self._bitmaps.update({"arrow_down": bmp})

        bmp = self.ConvertToBitmap(arrow_up, alpha=None)
        bmp.SetMask(wx.Mask(bmp, wx.Colour(0, 128, 128)))
        self._bitmaps.update({"arrow_up": bmp})

[docs]    def GetStockBitmap(self, name):
        """
        Returns a bitmap from a stock.

        :param string `name`: the bitmap name.

        :return: The stock bitmap, if `name` was found in the stock bitmap dictionary.
         Othewise, `wx.NullBitmap` is returned.
        """

        if self._bitmaps.has_key(name):
            return self._bitmaps[name]

        return wx.NullBitmap

[docs]    def Get(self):
        """
        Accessor to the unique art manager object.

        :return: A unique instance of L{ArtManager}.
        """

        if not hasattr(self, "_instance"):

            self._instance = ArtManager()
            self._instance.Initialize()

            # Initialize the renderers map
            self._renderers[StyleXP] = RendererXP()
            self._renderers[Style2007] = RendererMSOffice2007()

        return self._instance

    Get = classmethod(Get)

[docs]    def Free(self):
        """ Destructor for the unique art manager object. """

        if hasattr(self, "_instance"):

            del self._instance

    Free = classmethod(Free)

[docs]    def OnSysColourChange(self, event):
        """
        Handles the ``wx.EVT_SYS_COLOUR_CHANGED`` event for L{ArtManager}.

        :param `event`: a `wx.SysColourChangedEvent` event to be processed.
        """

        # reinitialise the colour map
        self.InitColours()

[docs]    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, an instance of `wx.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 `wx.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)

[docs]    def DarkColour(self, colour, percent):
        """
        Like the L{LightColour} function, but create the colour darker by `percent`.

        :param `colour`: the input colour to be darkened, an instance of `wx.Colour`;
        :param integer `percent`: determines how dark the colour will be. `percent` = ``100``
         returns black, `percent` = ``0`` returns `colour`.

        :return: A dark contrast of the input `colour`, an instance of `wx.Colour`.
        """

        end_colour = wx.BLACK
        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)

[docs]    def PaintStraightGradientBox(self, dc, rect, startColour, endColour, vertical=True):
        """
        Paint the rectangle with gradient colouring; the gradient lines are either
        horizontal or vertical.

        :param `dc`: an instance of `wx.DC`;
        :param `wx.Rect` `rect`: the rectangle to be filled with gradient shading;
        :param `wx.Colour` `startColour`: the first colour of the gradient shading;
        :param `wx.Colour` `endColour`: the second colour of the gradient shading;
        :param bool `vertical`: ``True`` for gradient colouring in the vertical direction,
         ``False`` for horizontal shading.
        """

        dcsaver = DCSaver(dc)

        if vertical:
            high = rect.GetHeight()-1
            direction = wx.SOUTH
        else:
            high = rect.GetWidth()-1
            direction = wx.EAST

        if high < 1:
            return

        dc.GradientFillLinear(rect, startColour, endColour, direction)

[docs]    def PaintGradientRegion(self, dc, region, startColour, endColour, vertical=True):
        """
        Paint a region with gradient colouring.

        :param `dc`: an instance of `wx.DC`;
        :param `region`: a region to be filled with gradient shading (an instance of
         `wx.Region`);
        :param `wx.Colour` `startColour`: the first colour of the gradient shading;
        :param `wx.Colour` `endColour`: the second colour of the gradient shading;
        :param bool `vertical`: ``True`` for gradient colouring in the vertical direction,
         ``False`` for horizontal shading.

        """

        # The way to achieve non-rectangle
        memDC = wx.MemoryDC()
        rect = region.GetBox()
        bitmap = wx.EmptyBitmap(rect.width, rect.height)
        memDC.SelectObject(bitmap)

        # Colour the whole rectangle with gradient
        rr = wx.Rect(0, 0, rect.width, rect.height)
        self.PaintStraightGradientBox(memDC, rr, startColour, endColour, vertical)

        # Convert the region to a black and white bitmap with the white pixels being inside the region
        # we draw the bitmap over the gradient coloured rectangle, with mask set to white,
        # this will cause our region to be coloured with the gradient, while area outside the
        # region will be painted with black. then we simply draw the bitmap to the dc with mask set to
        # black
        tmpRegion = wx.Region(rect.x, rect.y, rect.width, rect.height)
        tmpRegion.Offset(-rect.x, -rect.y)
        regionBmp = tmpRegion.ConvertToBitmap()
        regionBmp.SetMask(wx.Mask(regionBmp, wx.WHITE))

        # The function ConvertToBitmap() return a rectangle bitmap
        # which is shorter by 1 pixl on the height and width (this is correct behavior, since
        # DrawLine does not include the second point as part of the line)
        # we fix this issue by drawing our own line at the bottom and left side of the rectangle
        memDC.SetPen(wx.BLACK_PEN)
        memDC.DrawBitmap(regionBmp, 0, 0, True)
        memDC.DrawLine(0, rr.height - 1, rr.width, rr.height - 1)
        memDC.DrawLine(rr.width - 1, 0, rr.width - 1, rr.height)

        memDC.SelectObject(wx.NullBitmap)
        bitmap.SetMask(wx.Mask(bitmap, wx.BLACK))
        dc.DrawBitmap(bitmap, rect.x, rect.y, True)

[docs]    def PaintDiagonalGradientBox(self, dc, rect, startColour, endColour,
                                 startAtUpperLeft=True, trimToSquare=True):
        """
        Paint rectangle with gradient colouring; the gradient lines are diagonal
        and may start from the upper left corner or from the upper right corner.

        :param `dc`: an instance of `wx.DC`;
        :param `wx.Rect` `rect`: the rectangle to be filled with gradient shading;
        :param `wx.Colour` `startColour`: the first colour of the gradient shading;
        :param `wx.Colour` `endColour`: the second colour of the gradient shading;
        :param bool `startAtUpperLeft`: ``True`` to start the gradient lines at the upper
         left corner of the rectangle, ``False`` to start at the upper right corner;
        :param bool `trimToSquare`: ``True`` to trim the gradient lines in a square.
        """

        # Save the current pen and brush
        savedPen = dc.GetPen()
        savedBrush = dc.GetBrush()

        # gradient fill from colour 1 to colour 2 with top to bottom
        if rect.height < 1 or rect.width < 1:
            return

        # calculate some basic numbers
        size = rect.width
        sizeX = sizeY = 0
        proportion = 1

        if rect.width > rect.height:

            if trimToSquare:

                size = rect.height
                sizeX = sizeY = rect.height - 1

            else:

                proportion = float(rect.height)/float(rect.width)
                size = rect.width
                sizeX = rect.width - 1
                sizeY = rect.height -1

        else:

            if trimToSquare:

                size = rect.width
                sizeX = sizeY = rect.width - 1

            else:

                sizeX = rect.width - 1
                size = rect.height
                sizeY = rect.height - 1
                proportion = float(rect.width)/float(rect.height)

        # calculate gradient coefficients
        col2 = endColour
        col1 = startColour

        rf, gf, bf = 0, 0, 0
        rstep = float(col2.Red() - col1.Red())/float(size)
        gstep = float(col2.Green() - col1.Green())/float(size)
        bstep = float(col2.Blue() - col1.Blue())/float(size)

        # draw the upper triangle
        for i in xrange(size):

            currCol = wx.Colour(col1.Red() + rf, col1.Green() + gf, col1.Blue() + bf)
            dc.SetBrush(wx.Brush(currCol, wx.SOLID))
            dc.SetPen(wx.Pen(currCol))

            if startAtUpperLeft:

                if rect.width > rect.height:

                    dc.DrawLine(rect.x + i, rect.y, rect.x, int(rect.y + proportion*i))
                    dc.DrawPoint(rect.x, int(rect.y + proportion*i))

                else:

                    dc.DrawLine(int(rect.x + proportion*i), rect.y, rect.x, rect.y + i)
                    dc.DrawPoint(rect.x, rect.y + i)

            else:

                if rect.width > rect.height:

                    dc.DrawLine(rect.x + sizeX - i, rect.y, rect.x + sizeX, int(rect.y + proportion*i))
                    dc.DrawPoint(rect.x + sizeX, int(rect.y + proportion*i))

                else:

                    xTo = (int(rect.x + sizeX - proportion * i) > rect.x and [int(rect.x + sizeX - proportion*i)] or [rect.x])[0]
                    dc.DrawLine(xTo, rect.y, rect.x + sizeX, rect.y + i)
                    dc.DrawPoint(rect.x + sizeX, rect.y + i)

            rf += rstep/2
            gf += gstep/2
            bf += bstep/2

        # draw the lower triangle
        for i in xrange(size):

            currCol = wx.Colour(col1.Red() + rf, col1.Green() + gf, col1.Blue() + bf)
            dc.SetBrush(wx.Brush(currCol, wx.SOLID))
            dc.SetPen(wx.Pen(currCol))

            if startAtUpperLeft:

                if rect.width > rect.height:

                    dc.DrawLine(rect.x + i, rect.y + sizeY, rect.x + sizeX, int(rect.y + proportion * i))
                    dc.DrawPoint(rect.x + sizeX, int(rect.y + proportion * i))

                else:

                    dc.DrawLine(int(rect.x + proportion * i), rect.y + sizeY, rect.x + sizeX, rect.y + i)
                    dc.DrawPoint(rect.x + sizeX, rect.y + i)

            else:

                if rect.width > rect.height:

                    dc.DrawLine(rect.x, (int)(rect.y + proportion * i), rect.x + sizeX - i, rect.y + sizeY)
                    dc.DrawPoint(rect.x + sizeX - i, rect.y + sizeY)

                else:

                    xTo = (int(rect.x + sizeX - proportion*i) > rect.x and [int(rect.x + sizeX - proportion*i)] or [rect.x])[0]
                    dc.DrawLine(rect.x, rect.y + i, xTo, rect.y + sizeY)
                    dc.DrawPoint(xTo, rect.y + sizeY)

            rf += rstep/2
            gf += gstep/2
            bf += bstep/2

        # Restore the pen and brush
        dc.SetPen( savedPen )
        dc.SetBrush( savedBrush )

[docs]    def PaintCrescentGradientBox(self, dc, rect, startColour, endColour, concave=True):
        """
        Paint a region with gradient colouring. The gradient is in crescent shape
        which fits the 2007 style.

        :param `dc`: an instance of `wx.DC`;
        :param `wx.Rect` `rect`: the rectangle to be filled with gradient shading;
        :param `wx.Colour` `startColour`: the first colour of the gradient shading;
        :param `wx.Colour` `endColour`: the second colour of the gradient shading;
        :param bool `concave`: ``True`` for a concave effect, ``False`` for a convex one.
        """

        diagonalRectWidth = rect.GetWidth()/4
        spare = rect.width - 4*diagonalRectWidth
        leftRect = wx.Rect(rect.x, rect.y, diagonalRectWidth, rect.GetHeight())
        rightRect = wx.Rect(rect.x + 3 * diagonalRectWidth + spare, rect.y, diagonalRectWidth, rect.GetHeight())

        if concave:

            self.PaintStraightGradientBox(dc, rect, self.MixColours(startColour, endColour, 50), endColour)
            self.PaintDiagonalGradientBox(dc, leftRect, startColour, endColour, True, False)
            self.PaintDiagonalGradientBox(dc, rightRect, startColour, endColour, False, False)

        else:

            self.PaintStraightGradientBox(dc, rect, endColour, self.MixColours(endColour, startColour, 50))
            self.PaintDiagonalGradientBox(dc, leftRect, endColour, startColour, False, False)
            self.PaintDiagonalGradientBox(dc, rightRect, endColour, startColour, True, False)

[docs]    def FrameColour(self):
        """
        Return the surrounding colour for a control.

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

        return wx.SystemSettings_GetColour(wx.SYS_COLOUR_ACTIVECAPTION)

[docs]    def BackgroundColour(self):
        """
        Returns the background colour of a control when not in focus.

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

        return self.LightColour(self.FrameColour(), 75)

[docs]    def HighlightBackgroundColour(self):
        """
        Returns the background colour of a control when it is in focus.

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

        return self.LightColour(self.FrameColour(), 60)

[docs]    def MixColours(self, firstColour, secondColour, percent):
        """
        Return mix of input colours.

        :param `firstColour`: the first colour to be mixed, an instance of `wx.Colour`;
        :param `secondColour`: the second colour to be mixed, an instance of `wx.Colour`;
        :param integer `percent`: the relative percentage of `firstColour` with respect to
         `secondColour`.

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

        # calculate gradient coefficients
        redOffset = float((secondColour.Red() * (100 - percent) / 100) - (firstColour.Red() * percent / 100))
        greenOffset = float((secondColour.Green() * (100 - percent) / 100) - (firstColour.Green() * percent / 100))
        blueOffset = float((secondColour.Blue() * (100 - percent) / 100) -  (firstColour.Blue() * percent / 100))

        return wx.Colour(firstColour.Red() + redOffset, firstColour.Green() + greenOffset,
                        firstColour.Blue() + blueOffset)

[docs]    def RandomColour():
        """
        Creates a random colour.

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

        r = random.randint(0, 255) # Random value betweem 0-255
        g = random.randint(0, 255) # Random value betweem 0-255
        b = random.randint(0, 255) # Random value betweem 0-255

        return wx.Colour(r, g, b)

[docs]    def IsDark(self, colour):
        """
        Returns whether a colour is dark or light.

        :param `colour`: an instance of `wx.Colour`.

        :return: ``True`` if the average RGB values are dark, ``False`` otherwise.
        """

        evg = (colour.Red() + colour.Green() + colour.Blue())/3

        if evg < 127:
            return True

        return False

[docs]    def TruncateText(self, dc, text, maxWidth):
        """
        Truncates a given string to fit given width size. if the text does not fit
        into the given width it is truncated to fit. the format of the fixed text
        is <truncate text ...>.

        :param `dc`: an instance of `wx.DC`;
        :param string `text`: the text to be (eventually) truncated;
        :param integer `maxWidth`: the maximum width allowed for the text.

        :return: A new string containining the (possibly) truncated text.
        """

        textLen = len(text)
        tempText = text
        rectSize = maxWidth

        fixedText = ""

        textW, textH = dc.GetTextExtent(text)

        if rectSize >= textW:
            return text

        # The text does not fit in the designated area,
        # so we need to truncate it a bit
        suffix = ".."
        w, h = dc.GetTextExtent(suffix)
        rectSize -= w

        for i in xrange(textLen, -1, -1):

            textW, textH = dc.GetTextExtent(tempText)
            if rectSize >= textW:
                fixedText = tempText
                fixedText += ".."
                return fixedText

            tempText = tempText[:-1]

[docs]    def DrawButton(self, dc, rect, theme, state, input=None):
        """
        Colour rectangle according to the theme.

        :param `dc`: an instance of `wx.DC`;
        :param `wx.Rect` `rect`: the rectangle to be filled with gradient shading;
        :param string `theme`: the theme to use to draw the button;
        :param integer `state`: the button state;
        :param `input`: a flag used to call the right method.
        """

        if input is None or type(input) == type(False):
            self.DrawButtonTheme(dc, rect, theme, state, input)
        else:
            self.DrawButtonColour(dc, rect, theme, state, input)

[docs]    def DrawButtonTheme(self, dc, rect, theme, state, useLightColours=True):
        """
        Draws a button using the appropriate theme.

        :param `dc`: an instance of `wx.DC`;
        :param `wx.Rect` `rect`: the button's client rectangle;
        :param string `theme`: the theme to use to draw the button;
        :param integer `state`: the button state;
        :param bool  `useLightColours`: ``True`` to use light colours, ``False`` otherwise.
        """

        renderer = self._renderers[theme]

        # Set background colour if non given by caller
        renderer.DrawButton(dc, rect, state, useLightColours)

[docs]    def DrawButtonColour(self, dc, rect, theme, state, colour):
        """
        Draws a button using the appropriate theme.

        :param `dc`: an instance of `wx.DC`;
        :param `wx.Rect` `rect`: the button's client rectangle;
        :param string `theme`: the theme to use to draw the button;
        :param integer `state`: the button state;
        :param `colour`: a valid `wx.Colour` instance.
        """

        renderer = self._renderers[theme]
        renderer.DrawButton(dc, rect, state, colour)

[docs]    def CanMakeWindowsTransparent(self):
        """
        Used internally.

        :return: ``True`` if the system supports transparency of toplevel windows,
         otherwise returns ``False``.
        """

        if wx.Platform == "__WXMSW__":

            version = wx.GetOsDescription()
            found = version.find("XP") >= 0 or version.find("2000") >= 0 or version.find("NT") >= 0
            return found

        elif wx.Platform == "__WXMAC__":
            return True
        else:
            return False

    # on supported windows systems (Win2000 and greater), this function
    # will make a frame window transparent by a certain amount

[docs]    def MakeWindowTransparent(self, wnd, amount):
        """
        Used internally. Makes a toplevel window transparent if the system supports it.

        :param `wnd`: the toplevel window to make transparent, an instance of `wx.TopLevelWindow`;
        :param integer `amount`: the window transparency to apply.
        """

        if wnd.GetSize() == (0, 0):
            return

        # this API call is not in all SDKs, only the newer ones, so
        # we will runtime bind this
        if wx.Platform == "__WXMSW__":
            hwnd = wnd.GetHandle()

            if not hasattr(self, "_winlib"):
                if _libimported == "MH":
                    self._winlib = win32api.LoadLibrary("user32")
                elif _libimported == "ctypes":
                    self._winlib = ctypes.windll.user32

            if _libimported == "MH":
                pSetLayeredWindowAttributes = win32api.GetProcAddress(self._winlib,
                                                                      "SetLayeredWindowAttributes")

                if pSetLayeredWindowAttributes == None:
                    return

                exstyle = win32api.GetWindowLong(hwnd, win32con.GWL_EXSTYLE)
                if 0 == (exstyle & 0x80000):
                    win32api.SetWindowLong(hwnd, win32con.GWL_EXSTYLE, exstyle | 0x80000)

                winxpgui.SetLayeredWindowAttributes(hwnd, 0, amount, 2)

            elif _libimported == "ctypes":
                style = self._winlib.GetWindowLongA(hwnd, 0xffffffecL)
                style |= 0x00080000
                self._winlib.SetWindowLongA(hwnd, 0xffffffecL, style)
                self._winlib.SetLayeredWindowAttributes(hwnd, 0, amount, 2)
        else:
            if not wnd.CanSetTransparent():
                return
            wnd.SetTransparent(amount)
            return

    # assumption: the background was already drawn on the dc

[docs]    def DrawBitmapShadow(self, dc, rect, where=BottomShadow|RightShadow):
        """
        Draws a shadow using background bitmap.

        :param `dc`: an instance of `wx.DC`;
        :param `wx.Rect` `rect`: the bitmap's client rectangle;
        :param integer `where`: where to draw the shadow. This can be any combination of the
         following bits:

         ========================== ======= ================================
         Shadow Settings             Value  Description
         ========================== ======= ================================
         ``RightShadow``                  1 Right side shadow
         ``BottomShadow``                 2 Not full bottom shadow
         ``BottomShadowFull``             4 Full bottom shadow
         ========================== ======= ================================

        """

        shadowSize = 5

        # the rect must be at least 5x5 pixles
        if rect.height < 2*shadowSize or rect.width < 2*shadowSize:
            return

        # Start by drawing the right bottom corner
        if where & BottomShadow or where & BottomShadowFull:
            dc.DrawBitmap(self._rightBottomCorner, rect.x+rect.width, rect.y+rect.height, True)

        # Draw right side shadow
        xx = rect.x + rect.width
        yy = rect.y + rect.height - shadowSize

        if where & RightShadow:
            while yy - rect.y > 2*shadowSize:
                dc.DrawBitmap(self._right, xx, yy, True)
                yy -= shadowSize

            dc.DrawBitmap(self._rightTop, xx, yy - shadowSize, True)

        if where & BottomShadow:
            xx = rect.x + rect.width - shadowSize
            yy = rect.height + rect.y
            while xx - rect.x > 2*shadowSize:
                dc.DrawBitmap(self._bottom, xx, yy, True)
                xx -= shadowSize

            dc.DrawBitmap(self._bottomLeft, xx - shadowSize, yy, True)

        if where & BottomShadowFull:
            xx = rect.x + rect.width - shadowSize
            yy = rect.height + rect.y
            while xx - rect.x >= 0:
                dc.DrawBitmap(self._bottom, xx, yy, True)
                xx -= shadowSize

            dc.DrawBitmap(self._bottom, xx, yy, True)

[docs]    def DropShadow(self, wnd, drop=True):
        """
        Adds a shadow under the window (Windows only).

        :param `wnd`: the window for which we are dropping a shadow, an instance of `wx.TopLevelWindow`;
        :param bool `drop`: ``True`` to drop a shadow, ``False`` to remove it.
        """

        if not self.CanMakeWindowsTransparent() or not _libimported:
            return

        if "__WXMSW__" in wx.Platform:

            hwnd = wnd.GetHandle()

            if not hasattr(self, "_winlib"):
                if _libimported == "MH":
                    self._winlib = win32api.LoadLibrary("user32")
                elif _libimported == "ctypes":
                    self._winlib = ctypes.windll.user32

            if _libimported == "MH":
                csstyle = win32api.GetWindowLong(hwnd, win32con.GCL_STYLE)
            else:
                csstyle = self._winlib.GetWindowLongA(hwnd, win32con.GCL_STYLE)

            if drop:
                if csstyle & CS_DROPSHADOW:
                    return
                else:
                    csstyle |= CS_DROPSHADOW     #Nothing to be done

            else:

                if csstyle & CS_DROPSHADOW:
                    csstyle &= ~(CS_DROPSHADOW)
                else:
                    return  #Nothing to be done

            win32api.SetWindowLong(hwnd, win32con.GCL_STYLE, csstyle)

[docs]    def GetBitmapStartLocation(self, dc, rect, bitmap, text="", style=0):
        """
        Returns the top left `x` and `y` cordinates of the bitmap drawing.

        :param `dc`: an instance of `wx.DC`;
        :param `wx.Rect` `rect`: the bitmap's client rectangle;
        :param `wx.Bitmap` `bitmap`: the bitmap associated with the button;
        :param string `text`: the button label;
        :param integer `style`: the button style. This can be one of the following bits:

         ============================== ======= ================================
         Button style                    Value  Description
         ============================== ======= ================================
         ``BU_EXT_XP_STYLE``               1    A button with a XP style
         ``BU_EXT_2007_STYLE``             2    A button with a MS Office 2007 style
         ``BU_EXT_LEFT_ALIGN_STYLE``       4    A left-aligned button
         ``BU_EXT_CENTER_ALIGN_STYLE``     8    A center-aligned button
         ``BU_EXT_RIGHT_ALIGN_STYLE``      16   A right-aligned button
         ``BU_EXT_RIGHT_TO_LEFT_STYLE``    32   A button suitable for right-to-left languages
         ============================== ======= ================================

        :return: A tuple containining the top left `x` and `y` cordinates of the bitmap drawing.
        """

        alignmentBuffer = self.GetAlignBuffer()

        # get the startLocationY
        fixedTextWidth = fixedTextHeight = 0

        if not text:
            fixedTextHeight = bitmap.GetHeight()
        else:
            fixedTextWidth, fixedTextHeight = dc.GetTextExtent(text)

        startLocationY = rect.y + (rect.height - fixedTextHeight)/2

        # get the startLocationX
        if style & BU_EXT_RIGHT_TO_LEFT_STYLE:

            startLocationX = rect.x + rect.width - alignmentBuffer - bitmap.GetWidth()

        else:

            if style & BU_EXT_RIGHT_ALIGN_STYLE:

                maxWidth = rect.x + rect.width - (2 * alignmentBuffer) - bitmap.GetWidth() # the alignment is for both sides

                # get the truncated text. The text may stay as is, it is not a must that is will be trancated
                fixedText = self.TruncateText(dc, text, maxWidth)

                # get the fixed text dimentions
                fixedTextWidth, fixedTextHeight = dc.GetTextExtent(fixedText)

                # calculate the start location
                startLocationX = maxWidth - fixedTextWidth

            elif style & BU_EXT_LEFT_ALIGN_STYLE:

                # calculate the start location
                startLocationX = alignmentBuffer

            else: # meaning BU_EXT_CENTER_ALIGN_STYLE

                maxWidth = rect.x + rect.width - (2 * alignmentBuffer) - bitmap.GetWidth() # the alignment is for both sides

                # get the truncated text. The text may stay as is, it is not a must that is will be trancated
                fixedText = self.TruncateText(dc, text, maxWidth)

                # get the fixed text dimentions
                fixedTextWidth, fixedTextHeight = dc.GetTextExtent(fixedText)

                if maxWidth > fixedTextWidth:

                    # calculate the start location
                    startLocationX = (maxWidth - fixedTextWidth) / 2

                else:

                    # calculate the start location
                    startLocationX = maxWidth - fixedTextWidth

        # it is very important to validate that the start location is not less than the alignment buffer
        if startLocationX < alignmentBuffer:
            startLocationX = alignmentBuffer

        return startLocationX, startLocationY

[docs]    def GetTextStartLocation(self, dc, rect, bitmap, text, style=0):
        """
        Returns the top left `x` and `y` cordinates of the text drawing.
        In case the text is too long, the text is being fixed (the text is cut and
        a '...' mark is added in the end).

        :param `dc`: an instance of `wx.DC`;
        :param `wx.Rect` `rect`: the text's client rectangle;
        :param `wx.Bitmap` `bitmap`: the bitmap associated with the button;
        :param string `text`: the button label;
        :param integer `style`: the button style.

        :return: A tuple containining the top left `x` and `y` cordinates of the text drawing, plus
         the truncated version of the input `text`.

        :see: L{GetBitmapStartLocation} for a list of valid button styles.
        """

        alignmentBuffer = self.GetAlignBuffer()

        # get the bitmap offset
        bitmapOffset = 0
        if bitmap != wx.NullBitmap:
            bitmapOffset = bitmap.GetWidth()

        # get the truncated text. The text may stay as is, it is not a must that is will be trancated
        maxWidth = rect.x + rect.width - (2 * alignmentBuffer) - bitmapOffset # the alignment is for both sides

        fixedText = self.TruncateText(dc, text, maxWidth)

        # get the fixed text dimentions
        fixedTextWidth, fixedTextHeight = dc.GetTextExtent(fixedText)
        startLocationY = (rect.height - fixedTextHeight) / 2 + rect.y

        # get the startLocationX
        if style & BU_EXT_RIGHT_TO_LEFT_STYLE:

            startLocationX = maxWidth - fixedTextWidth + alignmentBuffer

        else:

            if style & BU_EXT_LEFT_ALIGN_STYLE:

                # calculate the start location
                startLocationX = bitmapOffset + alignmentBuffer

            elif style & BU_EXT_RIGHT_ALIGN_STYLE:

                # calculate the start location
                startLocationX = maxWidth - fixedTextWidth + bitmapOffset + alignmentBuffer

            else: # meaning wxBU_EXT_CENTER_ALIGN_STYLE

                # calculate the start location
                startLocationX = (maxWidth - fixedTextWidth) / 2 + bitmapOffset + alignmentBuffer

        # it is very important to validate that the start location is not less than the alignment buffer
        if startLocationX < alignmentBuffer:
            startLocationX = alignmentBuffer

        return startLocationX, startLocationY, fixedText

[docs]    def DrawTextAndBitmap(self, dc, rect, text, enable=True, font=wx.NullFont,
                          fontColour=wx.BLACK, bitmap=wx.NullBitmap,
                          grayBitmap=wx.NullBitmap, style=0):
        """
        Draws the text & bitmap on the input dc.

        :param `dc`: an instance of `wx.DC`;
        :param `wx.Rect` `rect`: the text and bitmap client rectangle;
        :param string `text`: the button label;
        :param bool `enable`: ``True`` if the button is enabled, ``False`` otherwise;
        :param `font`: the font to use to draw the text, an instance of `wx.Font`;
        :param `fontColour`: the colour to use to draw the text, an instance of
         `wx.Colour`;
        :param `bitmap`: the bitmap associated with the button, an instance of `wx.Bitmap`;
        :param `grayBitmap`: a greyed-out version of the input `bitmap` representing
         a disabled bitmap, an instance of `wx.Bitmap`;
        :param integer `style`: the button style.

        :see: L{GetBitmapStartLocation} for a list of valid button styles.
        """

        # enable colours
        if enable:
            dc.SetTextForeground(fontColour)
        else:
            dc.SetTextForeground(wx.SystemSettings_GetColour(wx.SYS_COLOUR_GRAYTEXT))

        # set the font

        if font == wx.NullFont:
            font = wx.SystemSettings_GetFont(wx.SYS_DEFAULT_GUI_FONT)

        dc.SetFont(font)

        startLocationX = startLocationY = 0

        if bitmap != wx.NullBitmap:

            # calculate the bitmap start location
            startLocationX, startLocationY = self.GetBitmapStartLocation(dc, rect, bitmap, text, style)

            # draw the bitmap
            if enable:
                dc.DrawBitmap(bitmap, startLocationX, startLocationY, True)
            else:
                dc.DrawBitmap(grayBitmap, startLocationX, startLocationY, True)

        # calculate the text start location
        location, labelOnly = self.GetAccelIndex(text)
        startLocationX, startLocationY, fixedText = self.GetTextStartLocation(dc, rect, bitmap, labelOnly, style)

        # after all the caculations are finished, it is time to draw the text
        # underline the first letter that is marked with a '&'
        if location == -1 or font.GetUnderlined() or location >= len(fixedText):
            # draw the text
            dc.DrawText(fixedText, startLocationX, startLocationY)

        else:

            # underline the first '&'
            before = fixedText[0:location]
            underlineLetter = fixedText[location]
            after = fixedText[location+1:]

            # before
            dc.DrawText(before, startLocationX, startLocationY)

            # underlineLetter
            if "__WXGTK__" not in wx.Platform:
                w1, h = dc.GetTextExtent(before)
                font.SetUnderlined(True)
                dc.SetFont(font)
                dc.DrawText(underlineLetter, startLocationX + w1, startLocationY)
            else:
                w1, h = dc.GetTextExtent(before)
                dc.DrawText(underlineLetter, startLocationX + w1, startLocationY)

                # Draw the underline ourselves since using the Underline in GTK,
                # causes the line to be too close to the letter
                uderlineLetterW, uderlineLetterH = dc.GetTextExtent(underlineLetter)

                curPen = dc.GetPen()
                dc.SetPen(wx.BLACK_PEN)

                dc.DrawLine(startLocationX + w1, startLocationY + uderlineLetterH - 2,
                            startLocationX + w1 + uderlineLetterW, startLocationY + uderlineLetterH - 2)
                dc.SetPen(curPen)

            # after
            w2, h = dc.GetTextExtent(underlineLetter)
            font.SetUnderlined(False)
            dc.SetFont(font)
            dc.DrawText(after, startLocationX + w1 + w2, startLocationY)

[docs]    def CalcButtonBestSize(self, label, bmp):
        """
        Returns the best fit size for the supplied label & bitmap.

        :param string `label`: the button label;
        :param `bmp`: the bitmap associated with the button, an instance of `wx.Bitmap`.

        :return: An instance of `wx.Size`, representing the best fit size for the supplied label & bitmap.
        """

        if "__WXMSW__" in wx.Platform:
            HEIGHT = 22
        else:
            HEIGHT = 26

        dc = wx.MemoryDC()
        dc.SelectBitmap(wx.EmptyBitmap(1, 1))

        dc.SetFont(wx.SystemSettings_GetFont(wx.SYS_DEFAULT_GUI_FONT))
        width, height, dummy = dc.GetMultiLineTextExtent(label)

        width += 2*self.GetAlignBuffer()

        if bmp.Ok():

            # allocate extra space for the bitmap
            heightBmp = bmp.GetHeight() + 2
            if height < heightBmp:
                height = heightBmp

            width += bmp.GetWidth() + 2

        if height < HEIGHT:
            height = HEIGHT

        dc.SelectBitmap(wx.NullBitmap)

        return wx.Size(width, height)

[docs]    def GetMenuFaceColour(self):
        """
        Returns the colour used for the menu foreground.

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

        renderer = self._renderers[self.GetMenuTheme()]
        return renderer.GetMenuFaceColour()

[docs]    def GetTextColourEnable(self):
        """
        Returns the colour used for enabled menu items.

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

        renderer = self._renderers[self.GetMenuTheme()]
        return renderer.GetTextColourEnable()

[docs]    def GetTextColourDisable(self):
        """
        Returns the colour used for disabled menu items.

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

        renderer = self._renderers[self.GetMenuTheme()]
        return renderer.GetTextColourDisable()

[docs]    def GetFont(self):
        """
        Returns the font used by this theme.

        :return: An instance of `wx.Font`.
        """

        renderer = self._renderers[self.GetMenuTheme()]
        return renderer.GetFont()

[docs]    def GetAccelIndex(self, label):
        """
        Returns the mnemonic index of the label and the label stripped of the ampersand mnemonic
        (e.g. 'lab&el' ==> will result in 3 and labelOnly = label).

        :param string `label`: a string containining an ampersand.

        :return: A tuple containining the mnemonic index of the label and the label
         stripped of the ampersand mnemonic.
        """

        indexAccel = 0
        while True:
            indexAccel = label.find("&", indexAccel)
            if indexAccel == -1:
                return indexAccel, label
            if label[indexAccel:indexAccel+2] == "&&":
                label = label[0:indexAccel] + label[indexAccel+1:]
                indexAccel += 1
            else:
                break

        labelOnly = label[0:indexAccel] + label[indexAccel+1:]

        return indexAccel, labelOnly

[docs]    def GetThemeBaseColour(self, useLightColours=True):
        """
        Returns the theme (Blue, Silver, Green etc.) base colour, if no theme is active
        it return the active caption colour, lighter in 30%.

        :param bool `useLightColours`: ``True`` to use light colours, ``False`` otherwise.

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

        if not useLightColours and not self.IsDark(self.FrameColour()):
            return wx.NamedColour("GOLD")
        else:
            return self.LightColour(self.FrameColour(), 30)

[docs]    def GetAlignBuffer(self):
        """
        Return the padding buffer for a text or bitmap.

        :return: An integer representing the padding buffer.
        """

        return self._alignmentBuffer

[docs]    def SetMenuTheme(self, theme):
        """
        Set the menu theme, possible values (Style2007, StyleXP, StyleVista).

        :param string `theme`: a rendering theme class, either `StyleXP`, `Style2007` or `StyleVista`.
        """

        self._menuTheme = theme

[docs]    def GetMenuTheme(self):
        """
        Returns the currently used menu theme.

        :return: A string containining the currently used theme for the menu.
        """

        return self._menuTheme

[docs]    def AddMenuTheme(self, render):
        """
        Adds a new theme to the stock.

        :param `render`: a rendering theme class, which must be derived from
         L{RendererBase}.

        :return: An integer representing the size of the renderers dictionary.
        """

        # Add new theme
        lastRenderer = len(self._renderers)
        self._renderers[lastRenderer] = render

        return lastRenderer

[docs]    def SetMS2007ButtonSunken(self, sunken):
        """
        Sets MS 2007 button style sunken or not.

        :param bool `sunken`: ``True`` to have a sunken border effect, ``False`` otherwise.
        """

        self._ms2007sunken = sunken

[docs]    def GetMS2007ButtonSunken(self):
        """
        Returns the sunken flag for MS 2007 buttons.

        :return: ``True`` if the MS 2007 buttons are sunken, ``False`` otherwise.
        """

        return self._ms2007sunken

[docs]    def GetMBVerticalGradient(self):
        """ Returns ``True`` if the menu bar should be painted with vertical gradient. """

        return self._verticalGradient

[docs]    def SetMBVerticalGradient(self, v):
        """
        Sets the menu bar gradient style.

        :param bool `v`: ``True`` for a vertical shaded gradient, ``False`` otherwise.
        """

        self._verticalGradient = v

[docs]    def DrawMenuBarBorder(self, border):
        """
        Enables menu border drawing (XP style only).

        :param bool `border`: ``True`` to draw the menubar border, ``False`` otherwise.
        """

        self._drowMBBorder = border

[docs]    def GetMenuBarBorder(self):
        """
        Returns menu bar border drawing flag.

        :return: ``True`` if the menu bar border is to be drawn, ``False`` otherwise.
        """

        return self._drowMBBorder

[docs]    def GetMenuBgFactor(self):
        """
        Gets the visibility depth of the menu in Metallic style.
        The higher the value, the menu bar will look more raised
        """

        return self._menuBgFactor

[docs]    def DrawDragSash(self, rect):
        """
        Draws resize sash.

        :param `wx.Rect` `rect`: the sash client rectangle.
        """

        dc = wx.ScreenDC()
        mem_dc = wx.MemoryDC()

        bmp = wx.EmptyBitmap(rect.width, rect.height)
        mem_dc.SelectObject(bmp)
        mem_dc.SetBrush(wx.WHITE_BRUSH)
        mem_dc.SetPen(wx.Pen(wx.WHITE, 1))
        mem_dc.DrawRectangle(0, 0, rect.width, rect.height)

        dc.Blit(rect.x, rect.y, rect.width, rect.height, mem_dc, 0, 0, wx.XOR)

[docs]    def TakeScreenShot(self, rect, bmp):
        """
        Takes a screenshot of the screen at given position & size (rect).

        :param `wx.Rect` `rect`: the screen rectangle we wish to capture;
        :param `wx.Bitmap` `bmp`: currently unused.
        """

        # Create a DC for the whole screen area
        dcScreen = wx.ScreenDC()

        # Create a Bitmap that will later on hold the screenshot image
        # Note that the Bitmap must have a size big enough to hold the screenshot
        # -1 means using the current default colour depth
        bmp = wx.EmptyBitmap(rect.width, rect.height)

        # Create a memory DC that will be used for actually taking the screenshot
        memDC = wx.MemoryDC()

        # Tell the memory DC to use our Bitmap
        # all drawing action on the memory DC will go to the Bitmap now
        memDC.SelectObject(bmp)

        # Blit (in this case copy) the actual screen on the memory DC
        # and thus the Bitmap
        memDC.Blit( 0,   # Copy to this X coordinate
            0,           # Copy to this Y coordinate
            rect.width,  # Copy this width
            rect.height, # Copy this height
            dcScreen,    # From where do we copy?
            rect.x,      # What's the X offset in the original DC?
            rect.y       # What's the Y offset in the original DC?
            )

        # Select the Bitmap out of the memory DC by selecting a new
        # uninitialized Bitmap
        memDC.SelectObject(wx.NullBitmap)

[docs]    def DrawToolBarBg(self, dc, rect):
        """
        Draws the toolbar background according to the active theme.

        :param `dc`: an instance of `wx.DC`;
        :param `wx.Rect` `rect`: the toolbar's client rectangle.
        """

        renderer = self._renderers[self.GetMenuTheme()]

        # Set background colour if non given by caller
        renderer.DrawToolBarBg(dc, rect)

[docs]    def DrawMenuBarBg(self, dc, rect):
        """
        Draws the menu bar background according to the active theme.

        :param `dc`: an instance of `wx.DC`;
        :param `wx.Rect` `rect`: the menubar's client rectangle.
        """

        renderer = self._renderers[self.GetMenuTheme()]
        # Set background colour if non given by caller
        renderer.DrawMenuBarBg(dc, rect)

[docs]    def SetMenuBarColour(self, scheme):
        """
        Sets the menu bar colour scheme to use.

        :param string `scheme`: a string representing a colour scheme (i.e., 'Default',
         'Dark', 'Dark Olive Green', 'Generic').
        """

        self._menuBarColourScheme = scheme
        # set default colour
        if scheme in self._colourSchemeMap.keys():
            self._menuBarBgColour = self._colourSchemeMap[scheme]

[docs]    def GetMenuBarColourScheme(self):
        """
        Returns the current colour scheme.

        :return: A string representing the current colour scheme.
        """

        return self._menuBarColourScheme

[docs]    def GetMenuBarFaceColour(self):
        """
        Returns the menu bar face colour.

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

        return self._menuBarBgColour

[docs]    def GetMenuBarSelectionColour(self):
        """
        Returns the menu bar selection colour.

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

        return self._menuBarSelColour

[docs]    def InitColours(self):
        """ Initialise the colour map. """

        self._colourSchemeMap = {_("Default"): wx.SystemSettings_GetColour(wx.SYS_COLOUR_3DFACE),
                                _("Dark"): wx.BLACK,
                                _("Dark Olive Green"): wx.NamedColour("DARK OLIVE GREEN"),
                                _("Generic"): wx.SystemSettings_GetColour(wx.SYS_COLOUR_ACTIVECAPTION)}

[docs]    def GetColourSchemes(self):
        """
        Returns the available colour schemes.

        :return: A list of strings representing the available colour schemes.
        """

        return self._colourSchemeMap.keys()

[docs]    def CreateGreyBitmap(self, bmp):
        """
        Creates a grey bitmap image from the input bitmap.

        :param `bmp`: a valid `wx.Bitmap` object to be greyed out.

        :return: A greyed-out representation of the input bitmap, an instance of `wx.Bitmap`.
        """

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

[docs]    def GetRaiseToolbar(self):
        """ Returns ``True`` if we are dropping a shadow under a toolbar. """

        return self._raiseTB

[docs]    def SetRaiseToolbar(self, rais):
        """
        Enables/disables toobar shadow drop.

        :param bool `rais`: ``True`` to drop a shadow below a toolbar, ``False`` otherwise.
        """

        self._raiseTB = rais

Navigation

  • index
  • modules |
  • Home |
  • Gallery |
  • Contents»
  • Module code »
  • artmanager


balloontip

  • modules |
  • Home |
  • Gallery |
  • Contents»
  • Module code »
  • balloontip

Source code for balloontip

# --------------------------------------------------------------------------- #
# BALLOONTIP wxPython IMPLEMENTATION
# Python Code By:
#
# Andrea Gavana, @ 29 May 2005
# Latest Revision: 17 Aug 2011, 15.00 GMT
#
#
# TODO List/Caveats
#
# 1. With wx.ListBox (And Probably Other Controls), The BalloonTip Sometimes
#    Flashes (It Is Created And Suddenly Destroyed). I Don't Know What Is
#    Happening. Probably I Don't Handle Correctly The wx.EVT_ENTER_WINDOW
#    wx.EVT_LEAVE_WINDOW?
#
# 2. wx.RadioBox Seems Not To Receive The wx.EVT_ENTER_WINDOW Event
#
# 3. wx.SpinCtrl (And Probably Other Controls), When Put In A Sizer, Does Not
#    Return The Correct Size/Position. Probably Is Something I Am Missing.
#
# 4. Other Issues?
#
#
# FIXED Problems
#
# 1. Now BalloonTip Control Works Also For TaskBarIcon (Thanks To Everyone
#    For The Suggetions I Read In The wxPython Mailing List)
#
#
# 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
# --------------------------------------------------------------------------- #

"""
L{BalloonTip} is a class that allows you to display tooltips in a balloon style
window.

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

L{BalloonTip} is a class that allows you to display tooltips in a balloon style
window (actually a frame), similarly to the windows XP balloon help. There is
also an arrow that points to the center of the control designed as a "target"
for the L{BalloonTip}.

What it can do:

- Set the balloon shape as a rectangle or a rounded rectangle;
- Set an icon to the top-left of the L{BalloonTip} frame;
- Set a title at the top of the L{BalloonTip} frame;
- Automatic "best" placement of L{BalloonTip} frame depending on the target
  control/window position;
- Runtime customization of title/tip fonts and foreground colours;
- Runtime change of L{BalloonTip} frame shape;
- Set the balloon background colour;
- Possibility to set the delay after which the L{BalloonTip} is displayed;
- Possibility to set the delay after which the L{BalloonTip} is destroyed;
- Three different behaviors for the L{BalloonTip} window (regardless the delay
  destruction time set):

  a) Destroy by leave: the L{BalloonTip} is destroyed when the mouse leaves the
     target control/window;
  b) Destroy by click: the L{BalloonTip} is destroyed when you click on any area
     of the target control/window;
  c) Destroy by button: the L{BalloonTip} is destroyed when you click on the
     top-right close button;
- Possibility to enable/disable globally the L{BalloonTip} on you application;
- Set the L{BalloonTip} also for the taskbar icon.

Usage
=====

Usage example::

    import wx
    import wx.lib.agw.balloontip as BT

    class MyFrame(wx.Frame):

        def __init__(self, parent):

            wx.Frame.__init(self, parent, -1, "BalloonTip Demo")

            panel = wx.Panel(self)

            # Let's suppose that in your application you have a wx.TextCtrl defined as:
            mytextctrl = wx.TextCtrl(panel, -1, "I am a textctrl", pos=(100, 100))

            # You can define your BalloonTip as follows:
            tipballoon = BT.BalloonTip(topicon=None, toptitle="textctrl",
                                       message="this is a textctrl",
                                       shape=BT.BT_ROUNDED,
                                       tipstyle=BT.BT_LEAVE)

            # Set the BalloonTip target
            tipballoon.SetTarget(mytextctrl)
            # Set the BalloonTip background colour
            tipballoon.SetBalloonColour(wx.WHITE)
            # Set the font for the balloon title
            tipballoon.SetTitleFont(wx.Font(9, wx.SWISS, wx.NORMAL, wx.BOLD, False))
            # Set the colour for the balloon title
            tipballoon.SetTitleColour(wx.BLACK)
            # Leave the message font as default
            tipballoon.SetMessageFont()
            # Set the message (tip) foreground colour
            tipballoon.SetMessageColour(wx.LIGHT_GREY)
            # Set the start delay for the BalloonTip
            tipballoon.SetStartDelay(1000)
            # Set the time after which the BalloonTip is destroyed
            tipballoon.SetEndDelay(3000)

    # our normal wxApp-derived class, as usual

    app = wx.PySimpleApp()

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

    app.MainLoop()

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

This class supports the following window styles:

================ =========== ==================================================
Window Styles    Hex Value   Description
================ =========== ==================================================
``BT_ROUNDED``           0x1 L{BalloonTip} will have a rounded rectangular shape.
``BT_RECTANGLE``         0x2 L{BalloonTip} will have a rectangular shape.
``BT_LEAVE``             0x3 L{BalloonTip} will be destroyed when the user moves the mouse outside the target window.
``BT_CLICK``             0x4 L{BalloonTip} will be destroyed when the user click on L{BalloonTip}.
``BT_BUTTON``            0x5 L{BalloonTip} will be destroyed when the user click on the close button.
================ =========== ==================================================

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

`No custom events are available for this class.`

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

BalloonTip is distributed under the wxPython license.

Latest revision: Andrea Gavana @ 17 Aug 2011, 15.00 GMT

Version 0.2

"""

import wx
import time
from wx.lib.buttons import GenButton

# Define The Values For The BalloonTip Frame Shape
BT_ROUNDED = 1
""" L{BalloonTip} will have a rounded rectangular shape. """
BT_RECTANGLE = 2
""" L{BalloonTip} will have a rectangular shape. """

# Define The Value For The BalloonTip Destruction Behavior
BT_LEAVE = 3
""" L{BalloonTip} will be destroyed when the user moves the mouse outside the target window. """
BT_CLICK = 4
""" L{BalloonTip} will be destroyed when the user click on L{BalloonTip}. """
BT_BUTTON = 5
""" L{BalloonTip} will be destroyed when the user click on the close button. """

# ---------------------------------------------------------------
# Class BalloonFrame
# ---------------------------------------------------------------
# This Class Is Called By The Main BalloonTip Class, And It Is
# Responsible For The Frame Creation/Positioning On Screen
# Depending On Target Control/Window, The Frame Can Position
# Itself To NW (Default), NE, SW, SE. The Switch On Positioning
# Is Done By Calculating The Absolute Position Of The Target
# Control/Window Plus/Minus The BalloonTip Size. The Pointing
# Arrow Is Positioned Accordingly.
# ---------------------------------------------------------------

[docs]class BalloonFrame(wx.Frame):
    """
    This class is called by the main L{BalloonTip} class, and it is
    responsible for the frame creation/positioning on screen
    depending on target control/window, the frame can position
    itself to NW (default), NE, SW, SE. The switch on positioning
    is done by calculating the absolute position of the target
    control/window plus/minus the balloontip size. The pointing
    arrow is positioned accordingly.
    """

[docs]    def __init__(self, parent, id=wx.ID_ANY, pos=wx.DefaultPosition,
                 size=wx.DefaultSize, classparent=None):
        """
        Default class constructor.

        Used internally. Do not call directly this class in your application!
        """

        wx.Frame.__init__(self, None, -1, "BalloonTip", pos, size,
                          style=wx.FRAME_SHAPED |
                          wx.SIMPLE_BORDER |
                          wx.FRAME_NO_TASKBAR |
                          wx.STAY_ON_TOP)

        self._parent = classparent
        self._toptitle = self._parent._toptitle
        self._topicon = self._parent._topicon
        self._message = self._parent._message
        self._shape = self._parent._shape
        self._tipstyle = self._parent._tipstyle

        self._ballooncolour = self._parent._ballooncolour
        self._balloonmsgcolour = self._parent._balloonmsgcolour
        self._balloonmsgfont = self._parent._balloonmsgfont

        if self._toptitle != "":
            self._balloontitlecolour = self._parent._balloontitlecolour
            self._balloontitlefont = self._parent._balloontitlefont

        panel = wx.Panel(self, -1)
        sizer = wx.BoxSizer(wx.VERTICAL)

        self.panel = panel

        subsizer = wx.BoxSizer(wx.VERTICAL)
        hsizer = wx.BoxSizer(wx.HORIZONTAL)
        subsizer.Add((0,20), 0, wx.EXPAND)

        if self._topicon is not None:
            stb = wx.StaticBitmap(panel, -1, self._topicon)
            hsizer.Add(stb, 0, wx.EXPAND | wx.LEFT | wx.RIGHT | wx.TOP, 10)
            self._balloonbmp = stb

        if self._toptitle != "":
            stt = wx.StaticText(panel, -1, self._toptitle)
            stt.SetFont(wx.Font(9, wx.SWISS, wx.NORMAL, wx.BOLD, False))
            if self._topicon is None:
                hsizer.Add((10,0), 0, wx.EXPAND)

            hsizer.Add(stt, 1, wx.EXPAND | wx.TOP, 10)

            self._balloontitle = stt
            self._balloontitle.SetForegroundColour(self._balloontitlecolour)
            self._balloontitle.SetFont(self._balloontitlefont)

        if self._tipstyle == BT_BUTTON:
            self._closebutton = GenButton(panel, -1, "X", style=wx.NO_BORDER)
            self._closebutton.SetMinSize((16,16))
            self._closebutton.SetFont(wx.Font(9, wx.SWISS, wx.NORMAL, wx.BOLD, False))
            self._closebutton.Bind(wx.EVT_ENTER_WINDOW, self.OnEnterButton)
            self._closebutton.Bind(wx.EVT_LEAVE_WINDOW, self.OnLeaveButton)
            self._closebutton.SetUseFocusIndicator(False)
            if self._toptitle != "":
                hsizer.Add(self._closebutton, 0, wx.TOP | wx.RIGHT, 5)
            else:
                hsizer.Add((10,0), 1, wx.EXPAND)
                hsizer.Add(self._closebutton, 0, wx.ALIGN_RIGHT | wx.TOP
                           | wx.RIGHT, 5)

        if self._topicon is not None or self._toptitle != "" \
           or self._tipstyle == BT_BUTTON:

            subsizer.Add(hsizer, 0, wx.EXPAND | wx.BOTTOM, 5)

        self._firstline = line = wx.StaticLine(panel, -1, style=wx.LI_HORIZONTAL)

        if self._topicon is not None or self._toptitle != "" \
           or self._tipstyle == BT_BUTTON:
            subsizer.Add(self._firstline, 0, wx.EXPAND | wx.LEFT | wx.RIGHT
                         | wx.BOTTOM, 10)
        else:
            subsizer.Add(self._firstline, 0, wx.EXPAND | wx.LEFT | wx.RIGHT
                         | wx.BOTTOM | wx.TOP, 10)

        mainstt = wx.StaticText(panel, -1, self._message)

        self._balloonmsg = mainstt
        self._balloonmsg.SetForegroundColour(self._balloonmsgcolour)
        self._balloonmsg.SetFont(self._balloonmsgfont)

        subsizer.Add(self._balloonmsg, 1, wx.EXPAND | wx.LEFT | wx.RIGHT |
                     wx.BOTTOM, 10)
        self._secondline = wx.StaticLine(panel, -1, style=wx.LI_HORIZONTAL)
        subsizer.Add(self._secondline, 0, wx.EXPAND | wx.LEFT | wx.RIGHT, 10)
        subsizer.Add((0,0),1)
        panel.SetSizer(subsizer)

        sizer.Add(panel, 1, wx.EXPAND)
        self.SetSizerAndFit(sizer)
        sizer.Layout()

        if self._tipstyle == BT_CLICK:
            if self._toptitle != "":
                self._balloontitle.Bind(wx.EVT_LEFT_DOWN, self.OnClose)

            if self._topicon is not None:
                self._balloonbmp.Bind(wx.EVT_LEFT_DOWN, self.OnClose)

            self._balloonmsg.Bind(wx.EVT_LEFT_DOWN, self.OnClose)
            self.panel.Bind(wx.EVT_LEFT_DOWN, self.OnClose)

        elif self._tipstyle == BT_BUTTON:
            self._closebutton.Bind(wx.EVT_BUTTON, self.OnClose)

        self.panel.SetBackgroundColour(self._ballooncolour)

        if wx.Platform == "__WXGTK__":
            self.Bind(wx.EVT_WINDOW_CREATE, self.SetBalloonShape)
        else:
            self.SetBalloonShape()

        self.Show(True)

[docs]    def SetBalloonShape(self, event=None):
        """
        Sets the balloon shape.

        :param `event`: on wxGTK, a `wx.WindowCreateEvent` event to process.
        """

        size = self.GetSize()
        pos = self.GetPosition()

        dc = wx.MemoryDC(wx.EmptyBitmap(1,1))
        textlabel = self._balloonmsg.GetLabel()
        textfont = self._balloonmsg.GetFont()
        textextent = dc.GetFullTextExtent(textlabel, textfont)

        boxheight = size.y - textextent[1]*len(textlabel.split("\n"))
        boxwidth = size.x

        position = wx.GetMousePosition()

        xpos = position[0]
        ypos = position[1]

        if xpos > 20 and ypos > 20:

            # This Is NW Positioning
            positioning = "NW"
            xpos = position[0] - boxwidth + 20
            ypos = position[1] - boxheight - 20

        elif xpos <= 20 and ypos <= 20:

            # This Is SE Positioning
            positioning = "SE"
            xpos = position[0] - 20
            ypos = position[1]

        elif xpos > 20 and ypos <= 20:

            # This Is SW Positioning
            positioning = "SW"
            xpos = position[0] - boxwidth + 20
            ypos = position[1]

        else:

            # This Is NE Positioning
            positioning = "NE"
            xpos = position[0]
            ypos = position[1] - boxheight + 20

        bmp = wx.EmptyBitmap(size.x,size.y)
        dc = wx.BufferedDC(None, bmp)
        dc.BeginDrawing()
        dc.SetBackground(wx.Brush(wx.Colour(0,0,0), wx.SOLID))
        dc.Clear()
        dc.SetPen(wx.Pen(wx.Colour(0,0,0), 1, wx.TRANSPARENT))

        if self._shape == BT_ROUNDED:
            dc.DrawRoundedRectangle(0, 20, boxwidth, boxheight-20, 12)

        elif self._shape == BT_RECTANGLE:
            dc.DrawRectangle(0, 20, boxwidth, boxheight-20)

        if positioning == "NW":
            dc.DrawPolygon(((boxwidth-40, boxheight), (boxwidth-20, boxheight+20),
                            (boxwidth-20, boxheight)))
        elif positioning == "SE":
            dc.DrawPolygon(((20, 20), (20, 0), (40, 20)))

        elif positioning == "SW":
            dc.DrawPolygon(((boxwidth-40, 20), (boxwidth-20, 0), (boxwidth-20, 20)))

        else:
            dc.DrawPolygon(((20, boxheight), (20, boxheight+20), (40, boxheight)))

        dc.EndDrawing()

        r = wx.RegionFromBitmapColour(bmp, wx.Colour(0,0,0))
        self.hasShape = self.SetShape(r)

        if self._tipstyle == BT_BUTTON:
            colour = self.panel.GetBackgroundColour()
            self._closebutton.SetBackgroundColour(colour)

        self.SetPosition((xpos, ypos))

[docs]    def OnEnterButton(self, event):
        """
        Handles the ``wx.EVT_ENTER_WINDOW`` for the L{BalloonTip} button.

        When the L{BalloonTip} is created with the `tipstyle` = ``BT_BUTTON``, this event
        provide some kind of 3D effect when the mouse enters the button area.

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

        button = event.GetEventObject()
        colour = button.GetBackgroundColour()
        red = colour.Red()
        green = colour.Green()
        blue = colour.Blue()

        if red < 30:
            red = red + 30
        if green < 30:
            green = green + 30
        if blue < 30:
            blue = blue + 30

        colour = wx.Colour(red-30, green-30, blue-30)
        button.SetBackgroundColour(colour)
        button.SetForegroundColour(wx.WHITE)
        button.Refresh()
        event.Skip()

[docs]    def OnLeaveButton(self, event):
        """
        Handles the ``wx.EVT_LEAVE_WINDOW`` for the L{BalloonTip} button.

        When the L{BalloonTip} is created with the `tipstyle` = ``BT_BUTTON``, this event
        provide some kind of 3D effect when the mouse enters the button area.

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

        button = event.GetEventObject()
        colour = self.panel.GetBackgroundColour()
        button.SetBackgroundColour(colour)
        button.SetForegroundColour(wx.BLACK)
        button.Refresh()
        event.Skip()

[docs]    def OnClose(self, event):
        """
        Handles the ``wx.EVT_CLOSE`` event for L{BalloonTip}.

        :param `event`: a `wx.CloseEvent` event to be processed.
        """

        if isinstance(self._parent._widget, wx.TaskBarIcon):
            self._parent.taskbarcreation = 0
            self._parent.taskbartime.Stop()
            del self._parent.taskbartime
            del self._parent.BalloonFrame

        self.Destroy()

# ---------------------------------------------------------------
# Class BalloonTip
# ---------------------------------------------------------------
# This Is The Main BalloonTip Implementation
# ---------------------------------------------------------------

[docs]class BalloonTip(object):
    """
    L{BalloonTip} is a class that allows you to display tooltips in a balloon style
    window.

    This is the main class implementation.
    """

[docs]    def __init__(self, topicon=None, toptitle="",
                 message="", shape=BT_ROUNDED, tipstyle=BT_LEAVE):
        """
        Default class constructor.

        :param `topicon`: an icon that will be displayed on the top-left part of the
         L{BalloonTip} frame. If set to ``None``, no icon will be displayed;
        :type `topicon`: `wx.Bitmap` or ``None``
        :param string `toptitle`: a title that will be displayed on the top part of the
         L{BalloonTip} frame. If set to an empty string, no title will be displayed;
        :param string `message`: the tip message that will be displayed. It can not be set to
         an empty string;
        :param integer `shape`: the L{BalloonTip} shape. It can be one of the following:

         ======================= ========= ====================================
         Shape Flag              Hex Value  Description
         ======================= ========= ====================================
         ``BT_ROUNDED``           0x1      L{BalloonTip} will have a rounded rectangular shape.
         ``BT_RECTANGLE``         0x2      L{BalloonTip} will have a rectangular shape.
         ======================= ========= ====================================

        :param integer `tipstyle`: the L{BalloonTip} destruction behavior. It can be one of:

         ======================= ========= ====================================
         Tip Flag                Hex Value  Description
         ======================= ========= ====================================
         ``BT_LEAVE``                  0x3 L{BalloonTip} will be destroyed when the user moves the mouse outside the target window.
         ``BT_CLICK``                  0x4 L{BalloonTip} will be destroyed when the user click on L{BalloonTip}.
         ``BT_BUTTON``                 0x5 L{BalloonTip} will be destroyed when the user click on the close button.
         ======================= ========= ====================================

        :raise: `Exception` in the following cases:

         - The `message` parameter is an empty string;
         - The `shape` parameter has an invalid value (i.e., it's not one of ``BT_ROUNDED``, ``BT_RECTANGLE``);
         - The `tipstyle` parameter has an invalid value (i.e., it's not one of ``BT_LEAVE``, ``BT_CLICK``, ``BT_BUTTON``).

        """

        self._shape = shape
        self._topicon = topicon
        self._toptitle = toptitle
        self._message = message
        self._tipstyle = tipstyle

        app = wx.GetApp()
        self._runningapp = app
        self._runningapp.__tooltipenabled__ = True

        if self._message == "":
            raise Exception("\nERROR: You Should At Least Set The Message For The BalloonTip")

        if self._shape not in [BT_ROUNDED, BT_RECTANGLE]:
            raise Exception('\nERROR: BalloonTip Shape Should Be One Of "BT_ROUNDED", "BT_RECTANGLE"')

        if self._tipstyle not in [BT_LEAVE, BT_CLICK, BT_BUTTON]:
            raise Exception('\nERROR: BalloonTip TipStyle Should Be One Of "BT_LEAVE", '\
                            '"BT_CLICK", "BT_BUTTON"')

        self.SetStartDelay()
        self.SetEndDelay()
        self.SetBalloonColour()

        if toptitle != "":
            self.SetTitleFont()
            self.SetTitleColour()

        if topicon is not None:
            self.SetBalloonIcon(topicon)

        self.SetMessageFont()
        self.SetMessageColour()

[docs]    def SetTarget(self, widget):
        """
        Sets the target control/window for the L{BalloonTip}.

        :param `widget`: any subclass of `wx.Window`.
        """

        self._widget = widget

        if isinstance(widget, wx.TaskBarIcon):
            self._widget.Bind(wx.EVT_TASKBAR_MOVE, self.OnTaskBarMove)
            self._widget.Bind(wx.EVT_WINDOW_DESTROY, self.OnDestroy)
            self.taskbarcreation = 0
        else:
            self._widget.Bind(wx.EVT_ENTER_WINDOW, self.OnWidgetEnter)
            self._widget.Bind(wx.EVT_LEAVE_WINDOW, self.OnWidgetLeave)
            self._widget.Bind(wx.EVT_MOTION, self.OnWidgetMotion)
            self._widget.Bind(wx.EVT_WINDOW_DESTROY, self.OnDestroy)

[docs]    def GetTarget(self):
        """
        Returns the target window for the L{BalloonTip}.

        :return: An instance of `wx.Window`.

        :raise: `Exception` if the L{SetTarget} method has not previously called.
        """

        if not hasattr(self, "_widget"):
            raise Exception("\nERROR: BalloonTip Target Has Not Been Set")

        return self._widget

[docs]    def SetStartDelay(self, delay=1):
        """
        Sets the delay time after which the L{BalloonTip} is created.

        :param integer `delay`: the number of milliseconds after which L{BalloonTip} is created.

        :raise: `Exception` if `delay` is less than ``1`` milliseconds.
        """

        if delay < 1:
            raise Exception("\nERROR: Delay Time For BalloonTip Creation Should Be Greater Than 1 ms")

        self._startdelaytime = float(delay)

[docs]    def GetStartDelay(self):
        """
        Returns the delay time after which the L{BalloonTip} is created.

        :return: the delay time, in milliseconds.
        """

        return self._startdelaytime

[docs]    def SetEndDelay(self, delay=1e6):
        """
        Sets the delay time after which the BalloonTip is destroyed.

        :param integer `delay`: the number of milliseconds after which L{BalloonTip} is destroyed.

        :raise: `Exception` if `delay` is less than ``1`` milliseconds.
        """

        if delay < 1:
            raise Exception("\nERROR: Delay Time For BalloonTip Destruction Should Be Greater Than 1 ms")

        self._enddelaytime = float(delay)

[docs]    def GetEndDelay(self):
        """
        Returns the delay time after which the L{BalloonTip} is destroyed.

        :return: the delay time, in milliseconds.
        """

        return self._enddelaytime

[docs]    def OnWidgetEnter(self, event):
        """
        Handles the ``wx.EVT_ENTER_WINDOW`` for the target control/window and
        starts the L{BalloonTip} timer for creation.

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

        if hasattr(self, "BalloonFrame"):
            if self.BalloonFrame:
                return

        if not self._runningapp.__tooltipenabled__:
            return

        self.showtime = wx.PyTimer(self.NotifyTimer)
        self.showtime.Start(self._startdelaytime)

        event.Skip()

[docs]    def OnWidgetLeave(self, event):
        """
        Handles the ``wx.EVT_LEAVE_WINDOW`` for the target control/window.

        :param `event`: a `wx.MouseEvent` event to be processed.

        :note: If the BalloonTip `tipstyle` is set to ``BT_LEAVE``, the L{BalloonTip} is destroyed.
        """

        if hasattr(self, "showtime"):
            if self.showtime:
                self.showtime.Stop()
                del self.showtime

        if hasattr(self, "BalloonFrame"):
            if self.BalloonFrame:
                if self._tipstyle == BT_LEAVE:
                    endtime = time.time()
                    if endtime - self.starttime > 0.1:
                        try:
                            self.BalloonFrame.Destroy()
                        except:
                            pass
                else:
                    event.Skip()
            else:
                event.Skip()
        else:
            event.Skip()

[docs]    def OnTaskBarMove(self, event):
        """
        Handles the mouse motion inside the taskbar icon area.

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

        if not hasattr(self, "BalloonFrame"):
            if self.taskbarcreation == 0:
                self.mousepos = wx.GetMousePosition()
                self.currentmousepos = self.mousepos
                self.taskbartime = wx.PyTimer(self.TaskBarTimer)
                self.taskbartime.Start(100)
                self.showtime = wx.PyTimer(self.NotifyTimer)
                self.showtime.Start(self._startdelaytime)

            if self.taskbarcreation == 0:
                self.taskbarcreation = 1

            return

        event.Skip()

[docs]    def OnWidgetMotion(self, event):
        """
        Handle the mouse motion inside the target.

        This prevents the annoying behavior of L{BalloonTip} to display when the
        user does something else inside the window. The L{BalloonTip} window is
        displayed only when the mouse does *not* move for the start delay time.

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

        if hasattr(self, "BalloonFrame"):
            if self.BalloonFrame:
                return

        if hasattr(self, "showtime"):
            if self.showtime:
                self.showtime.Start(self._startdelaytime)

        event.Skip()

[docs]    def NotifyTimer(self):
        """ The creation timer has expired. Creates the L{BalloonTip} frame."""

        self.BalloonFrame = BalloonFrame(self._widget, classparent=self)
        self.BalloonFrame.Show(True)
        self.starttime = time.time()

        self.showtime.Stop()
        del self.showtime

        self.destroytime = wx.PyTimer(self.DestroyTimer)
        self.destroytime.Start(self._enddelaytime)

[docs]    def TaskBarTimer(self):
        """
        This timer check periodically the mouse position.

        If the current mouse position is sufficiently far from the coordinates
        it had when entered the taskbar icon and the L{BalloonTip} style is
        ``BT_LEAVE``, the L{BalloonTip} frame is destroyed.
        """

        self.currentmousepos = wx.GetMousePosition()
        mousepos = self.mousepos

        if abs(self.currentmousepos[0] - mousepos[0]) > 30 or \
           abs(self.currentmousepos[1] - mousepos[1]) > 30:
            if hasattr(self, "BalloonFrame"):
                if self._tipstyle == BT_LEAVE:
                    try:
                        self.BalloonFrame.Destroy()
                        self.taskbartime.Stop()
                        del self.taskbartime
                        del self.BalloonFrame
                        self.taskbarcreation = 0
                    except:
                        pass

[docs]    def DestroyTimer(self):
        """ The destruction timer has expired. Destroys the L{BalloonTip} frame."""

        self.destroytime.Stop()
        del self.destroytime

        try:
            self.BalloonFrame.Destroy()
        except:
            pass

[docs]    def SetBalloonShape(self, shape=BT_ROUNDED):
        """
        Sets the L{BalloonTip} frame shape.

        :param integer `shape`: should be one of ``BT_ROUNDED`` or ``BT_RECTANGLE``.

        :raise: `Exception` if the `shape` parameter is not a valid value
         (i.e., it's not one of ``BT_ROUNDED``, ``BT_RECTANGLE``);
        """

        if shape not in [BT_ROUNDED, BT_RECTANGLE]:
            raise Exception('\nERROR: BalloonTip Shape Should Be One Of "BT_ROUNDED", "BT_RECTANGLE"')

        self._shape = shape

[docs]    def GetBalloonShape(self):
        """
        Returns the L{BalloonTip} frame shape.

        :return: An integer, one of ``BT_ROUNDED``, ``BT_RECTANGLE``.
        """

        return self._shape

[docs]    def SetBalloonIcon(self, icon):
        """
        Sets the L{BalloonTip} top-left icon.

        :param `icon`: an instance of `wx.Bitmap`.

        :raise: `Exception` if the `icon` bitmap is not a valid `wx.Bitmap`.
        """

        if icon.Ok():
            self._topicon = icon
        else:
            raise Exception("\nERROR: Invalid Image Passed To BalloonTip")

[docs]    def GetBalloonIcon(self):
        """
        Returns the L{BalloonTip} top-left icon.

        :return: An instance of `wx.Bitmap`.
        """

        return self._topicon

[docs]    def SetBalloonTitle(self, title=""):
        """
        Sets the L{BalloonTip} top title.

        :param string `title`: a string to use as a L{BalloonTip} title.
        """

        self._toptitle = title

[docs]    def GetBalloonTitle(self):
        """
        Returns the L{BalloonTip} top title.

        :return: A string containing the top title.
        """

        return self._toptitle

[docs]    def SetBalloonMessage(self, message):
        """
        Sets the L{BalloonTip} tip message.

        :param string `message`: a string identifying the main message body of L{BalloonTip}.

        :raise: `Exception` if the message is an empty string.

        :note: The L{BalloonTip} message should never be empty.
        """

        if len(message.strip()) < 1:
            raise Exception("\nERROR: BalloonTip Message Can Not Be Empty")

        self._message = message

[docs]    def GetBalloonMessage(self):
        """
        Returns the L{BalloonTip} tip message.

        :return: A string containing the main message.
        """

        return self._message

[docs]    def SetBalloonTipStyle(self, tipstyle=BT_LEAVE):
        """
        Sets the L{BalloonTip} `tipstyle` parameter.

        :param integer `tipstyle`: one of the following bit set:

         ============== ========== =====================================
         Tip Style      Hex Value  Description
         ============== ========== =====================================
         ``BT_LEAVE``          0x3 L{BalloonTip} will be destroyed when the user moves the mouse outside the target window.
         ``BT_CLICK``          0x4 L{BalloonTip} will be destroyed when the user click on L{BalloonTip}.
         ``BT_BUTTON``         0x5 L{BalloonTip} will be destroyed when the user click on the close button.
         ============== ========== =====================================

        :raise: `Exception` if the `tipstyle` parameter has an invalid value
         (i.e., it's not one of ``BT_LEAVE``, ``BT_CLICK``, ``BT_BUTTON``).
        """

        if tipstyle not in [BT_LEAVE, BT_CLICK, BT_BUTTON]:
            raise Exception('\nERROR: BalloonTip TipStyle Should Be One Of "BT_LEAVE", '\
                            '"BT_CLICK", "BT_BUTTON"')

        self._tipstyle = tipstyle

[docs]    def GetBalloonTipStyle(self):
        """
        Returns the L{BalloonTip} `tipstyle` parameter.

        :return: An integer representing the style.

        :see: L{SetBalloonTipStyle}
        """

        return self._tipstyle

[docs]    def SetBalloonColour(self, colour=None):
        """
        Sets the L{BalloonTip} background colour.

        :param `colour`: a valid `wx.Colour` instance.
        """

        if colour is None:
            colour = wx.Colour(255, 250, 205)

        self._ballooncolour = colour

[docs]    def GetBalloonColour(self):
        """
        Returns the L{BalloonTip} background colour.

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

        return self._ballooncolour

[docs]    def SetTitleFont(self, font=None):
        """
        Sets the font for the top title.

        :param `font`: a valid `wx.Font` instance.
        """

        if font is None:
            font = wx.Font(9, wx.SWISS, wx.NORMAL, wx.BOLD, False)

        self._balloontitlefont = font

[docs]    def GetTitleFont(self):
        """
        Returns the font for the top title.

        :return: An instance of `wx.Font`.
        """

        return self._balloontitlefont

[docs]    def SetMessageFont(self, font=None):
        """
        Sets the font for the tip message.

        :param `font`: a valid `wx.Font` instance.
        """

        if font is None:
            font = wx.Font(8, wx.SWISS, wx.NORMAL, wx.NORMAL, False)

        self._balloonmsgfont = font

[docs]    def GetMessageFont(self):
        """
        Returns the font for the tip message.

        :return: An instance of `wx.Font`.
        """

        return self._balloonmsgfont

[docs]    def SetTitleColour(self, colour=None):
        """
        Sets the colour for the top title.

        :param `colour`: a valid `wx.Colour` instance.
        """

        if colour is None:
            colour = wx.BLACK

        self._balloontitlecolour = colour

[docs]    def GetTitleColour(self):
        """
        Returns the colour for the top title.

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

        return self._balloontitlecolour

[docs]    def SetMessageColour(self, colour=None):
        """
        Sets the colour for the tip message.

        :param `colour`: a valid `wx.Colour` instance.
        """

        if colour is None:
            colour = wx.BLACK

        self._balloonmsgcolour = colour

[docs]    def GetMessageColour(self):
        """
        Returns the colour for the tip message.

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

        return self._balloonmsgcolour

[docs]    def OnDestroy(self, event):
        """
        Handles the target destruction, specifically handling the ``wx.EVT_WINDOW_DESTROY``
        event.

        :param `event`: a `wx.WindowDestroyEvent` event to be processed.
        """

        if hasattr(self, "BalloonFrame"):
            if self.BalloonFrame:
                try:
                    if isinstance(self._widget, wx.TaskBarIcon):
                        self._widget.Unbind(wx.EVT_TASKBAR_MOVE)
                        self.taskbartime.Stop()
                        del self.taskbartime
                    else:
                        self._widget.Unbind(wx.EVT_MOTION)
                        self._widget.Unbind(wx.EVT_LEAVE_WINDOW)
                        self._widget.Unbind(wx.EVT_ENTER_WINDOW)

                    self.BalloonFrame.Destroy()

                except:
                    pass

                del self.BalloonFrame

[docs]    def EnableTip(self, enable=True):
        """
        Enable/disable globally the L{BalloonTip}.

        :param bool `enable`: ``True`` to enable L{BalloonTip}, ``False`` otherwise.
        """

        self._runningapp.__tooltipenabled__ = enable

Navigation

  • index
  • modules |
  • Home |
  • Gallery |
  • Contents»
  • Module code »
  • balloontip


buttonpanel

  • modules |
  • Home |
  • Gallery |
  • Contents»
  • Module code »
  • buttonpanel

Source code for buttonpanel

# --------------------------------------------------------------------------- #
# BUTTONPANEL Widget wxPython IMPLEMENTATION
#
# Original C++ Code From Eran. You Can Find It At:
#
# http://wxforum.shadonet.com/viewtopic.php?t=6619
#
# License: wxWidgets license
#
#
# Python Code By:
#
# Andrea Gavana, @ 02 Oct 2006
# Latest Revision: 17 Aug 2011, 15.00 GMT
#
#
# 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
# --------------------------------------------------------------------------- #

"""
A custom panel class with gradient background shading with the possibility to
add buttons and controls still respecting the gradient background.

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

With L{ButtonPanel} class you have a panel with gradient colouring
on it and with the possibility to place some buttons on it. Using a
standard panel with normal `wx.Buttons` leads to an ugly result: the
buttons are placed correctly on the panel - but with grey area around
them. Gradient colouring is kept behind the images - this was achieved
due to the PNG format and the transparency of the bitmaps.

The image are functioning like a buttons and can be caught in your
code using the usual::

  self.Bind(wx.EVT_BUTTON, self.OnButton)

method.

The control is generic, and support theming (well, I tested it under
Windows with the three defauls themes: grey, blue, silver and the
classic look).

Usage
=====

L{ButtonPanel} supports 4 alignments: left, right, top, bottom, which have a
different meaning and behavior with respect to `wx.Toolbar`. The easiest
thing is to try the demo to understand, but I'll try to explain how it works.

**CASE 1**: L{ButtonPanel} has a main caption text.

- Left alignment means L{ButtonPanel} is horizontal, with the text aligned to the
  left. When you shrink the demo frame, if there is not enough room for all
  the controls to be shown, the controls closest to the text are hidden;

- Right alignment means L{ButtonPanel} is horizontal, with the text aligned to the
  right. Item layout as above;

- Top alignment means L{ButtonPanel} is vertical, with the text aligned to the top.
  Item layout as above;

- Bottom alignment means L{ButtonPanel} is vertical, with the text aligned to the
  bottom. Item layout as above.

**CASE 2**: L{ButtonPanel} has **no** main caption text.

- In this case, left and right alignment are the same (as top and bottom are the same),
  but the layout strategy changes: now if there is not enough room for all the controls
  to be shown, the last added items are hidden ("last" means on the far right for an
  horizontal L{ButtonPanel} and far bottom for a vertical L{ButtonPanel}).

Usage example::

    import wx
    import wx.lib.agw.buttonpanel as BP

    class MyFrame(wx.Frame):

        def __init__(self, parent, id=-1, title="ButtonPanel", pos=wx.DefaultPosition,
                     size=(800, 600), style=wx.DEFAULT_FRAME_STYLE):

            wx.Frame.__init__(self, parent, id, title, pos, size, style)

            mainPanel = wx.Panel(self, -1)
            self.logtext = wx.TextCtrl(mainPanel, -1, "", style=wx.TE_MULTILINE)

            vSizer = wx.BoxSizer(wx.VERTICAL)
            mainPanel.SetSizer(vSizer)

            titleBar = BP.ButtonPanel(mainPanel, -1, "A Simple Test & Demo")

            btn1 = BP.ButtonInfo(titleBar, wx.NewId(), wx.Bitmap("png4.png", wx.BITMAP_TYPE_PNG))
            titleBar.AddButton(btn1)
            self.Bind(wx.EVT_BUTTON, self.OnButton, btn1)

            btn2 = BP.ButtonInfo(titleBar, wx.NewId(), wx.Bitmap("png3.png", wx.BITMAP_TYPE_PNG))
            titleBar.AddButton(btn2)
            self.Bind(wx.EVT_BUTTON, self.OnButton, btn2)

            btn3 = BP.ButtonInfo(titleBar, wx.NewId(), wx.Bitmap("png2.png", wx.BITMAP_TYPE_PNG))
            titleBar.AddButton(btn3)
            self.Bind(wx.EVT_BUTTON, self.OnButton, btn3)

            btn4 = BP.ButtonInfo(titleBar, wx.NewId(), wx.Bitmap("png1.png", wx.BITMAP_TYPE_PNG))
            titleBar.AddButton(btn4)
            self.Bind(wx.EVT_BUTTON, self.OnButton, btn4)

            vSizer.Add(titleBar, 0, wx.EXPAND)
            vSizer.Add((20, 20))
            vSizer.Add(self.logtext, 1, wx.EXPAND|wx.ALL, 5)

            titleBar.DoLayout()
            vSizer.Layout()

        def OnButton(self, event):
            ''' Handler for the ``wx.EVT_BUTTON`` event. '''

            obj = event.GetEventObject()

            # This will print the button label
            print obj.GetText()

    # our normal wxApp-derived class, as usual

    app = wx.PySimpleApp()

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

    app.MainLoop()

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

This class supports the following window styles:

==================== =========== ==================================================
Window Styles        Hex Value   Description
==================== =========== ==================================================
``BP_DEFAULT_STYLE``         0x1 L{ButtonPanel} has a plain solid background.
``BP_USE_GRADIENT``          0x2 L{ButtonPanel} has a gradient shading background.
==================== =========== ==================================================

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

This class processes the following events:

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

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

L{ButtonPanel} is distributed under the wxPython license.

Latest Revision: Andrea Gavana @ 17 Aug 2011, 15.00 GMT

Version 0.6.

"""

import wx

# Some constants to tune the BPArt class
BP_BACKGROUND_COLOUR = 0
""" Background brush colour when no gradient shading exists. """
BP_GRADIENT_COLOUR_FROM = 1
""" Starting gradient colour, used only when ``BP_USE_GRADIENT`` style is applied. """
BP_GRADIENT_COLOUR_TO = 2
""" Ending gradient colour, used only when ``BP_USE_GRADIENT`` style is applied. """
BP_BORDER_COLOUR = 3
""" Pen colour to paint the border of L{ButtonPanel}. """
BP_TEXT_COLOUR = 4
""" Main L{ButtonPanel} caption colour. """
BP_BUTTONTEXT_COLOUR = 5
""" Text colour for buttons with text. """
BP_BUTTONTEXT_INACTIVE_COLOUR = 6
""" Text colour for inactive buttons with text. """
BP_SELECTION_BRUSH_COLOUR = 7
""" Brush colour to be used when hovering or selecting a button. """
BP_SELECTION_PEN_COLOUR = 8
""" Pen colour to be used when hovering or selecting a button. """
BP_SEPARATOR_COLOUR = 9
""" Pen colour used to paint the separators. """
BP_TEXT_FONT = 10
""" Font of the L{ButtonPanel} main caption. """
BP_BUTTONTEXT_FONT = 11
""" Text font for the buttons with text. """

BP_BUTTONTEXT_ALIGN_BOTTOM = 12
""" Flag that indicates the image and text in buttons is stacked. """
BP_BUTTONTEXT_ALIGN_RIGHT = 13
""" Flag that indicates the text is shown alongside the image in buttons with text. """

BP_SEPARATOR_SIZE = 14
""" Separator size. NB: This is not the line width, but the sum of the space before and after the separator line plus the width of the line. """
BP_MARGINS_SIZE = 15
""" Size of the left/right margins in L{ButtonPanel} (top/bottom for vertically aligned L{ButtonPanel})."""
BP_BORDER_SIZE = 16
""" Size of the border. """
BP_PADDING_SIZE = 17
""" Inter-tool separator size. """

# Caption Gradient Type
BP_GRADIENT_NONE = 0
""" No gradient shading should be used to paint the background. """
BP_GRADIENT_VERTICAL = 1
""" Vertical gradient shading should be used to paint the background. """
BP_GRADIENT_HORIZONTAL = 2
""" Horizontal gradient shading should be used to paint the background. """

# Flags for HitTest() method
BP_HT_BUTTON = 200
""" This flag indicates that the user has hit a button inside L{ButtonPanel}. """
BP_HT_NONE = 201
""" This flag indicates that no buttons were hit inside L{ButtonPanel}. """

# Alignment of buttons in the panel
BP_ALIGN_RIGHT = 1
""" Aligns the buttons to the right (for an horizontal L{ButtonPanel}). """
BP_ALIGN_LEFT = 2
""" Aligns the buttons to the left (for an horizontal L{ButtonPanel}). """
BP_ALIGN_TOP = 4
""" Aligns the buttons at the top (for a vertical L{ButtonPanel}). """
BP_ALIGN_BOTTOM = 8
""" Aligns the buttons at the bottom (for a vertical L{ButtonPanel}). """

# ButtonPanel styles
BP_DEFAULT_STYLE = 1
""" L{ButtonPanel} has a plain solid background. """
BP_USE_GRADIENT = 2
""" L{ButtonPanel} has a gradient shading background. """

# Delay used to cancel the longHelp in the statusbar field
_DELAY = 3000

# Check for the new method in 2.7 (not present in 2.6.3.3)
if wx.VERSION_STRING < "2.7":
    wx.Rect.Contains = lambda self, point: wx.Rect.Inside(self, point)

[docs]def BrightenColour(colour, factor):
    """
    Brighten the input colour by a factor.

    :param `colour`: a valid `wx.Colour` instance;
    :param integer `factor`: the factor by which the input colour should be brightened.

    :return: An instance of `wx.Colour`, a brightened version of the input `colour`.
    """

    val = colour.Red()*factor
    if val > 255:
        red = 255
    else:
        red = val

    val = colour.Green()*factor
    if val > 255:
        green = 255
    else:
        green = val

    val = colour.Blue()*factor
    if val > 255:
        blue = 255
    else:
        blue = val

    return wx.Colour(red, green, blue)

# ----------------------------------------------------------------------------

[docs]def MakeDisabledBitmap(original):
    """
    Creates a disabled-looking bitmap starting from the input one.

    :param `original`: an instance of `wx.Bitmap` to be greyed-out.

    :return: A greyed-out representation of the input bitmap, an instance of `wx.Bitmap`.
    """

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

# ---------------------------------------------------------------------------- #
# Class BPArt
# Handles all the drawings for buttons, separators and text and allows the
# programmer to set colours, sizes and gradient shadings for ButtonPanel
# ---------------------------------------------------------------------------- #

[docs]class BPArt(object):
    """
    L{BPArt} is an art provider class which does all of the drawing for L{ButtonPanel}.
    This allows the library caller to customize the L{BPArt} or to completely replace
    all drawing with custom BPArts.
    """

[docs]    def __init__(self, parentStyle):
        """
        Default class constructor.

        :param integer `parentStyle`: the window style for L{ButtonPanel}.
        """

        base_colour = wx.SystemSettings_GetColour(wx.SYS_COLOUR_3DFACE)

        self._background_brush = wx.Brush(base_colour, wx.SOLID)
        self._gradient_colour_to = wx.WHITE
        self._gradient_colour_from = wx.SystemSettings_GetColour(wx.SYS_COLOUR_ACTIVECAPTION)

        if parentStyle & BP_USE_GRADIENT:
            self._border_pen = wx.Pen(wx.WHITE, 3)
            self._caption_text_colour = wx.WHITE
            self._buttontext_colour = wx.Colour(70, 143, 255)
            self._separator_pen = wx.Pen(BrightenColour(self._gradient_colour_from, 1.4))
            self._gradient_type = BP_GRADIENT_VERTICAL
        else:
            self._border_pen = wx.Pen(BrightenColour(base_colour, 0.9), 3)
            self._caption_text_colour = wx.BLACK
            self._buttontext_colour = wx.SystemSettings_GetColour(wx.SYS_COLOUR_BTNTEXT)
            self._separator_pen = wx.Pen(BrightenColour(base_colour, 0.9))
            self._gradient_type = BP_GRADIENT_NONE

        self._buttontext_inactive_colour = wx.SystemSettings_GetColour(wx.SYS_COLOUR_GRAYTEXT)
        self._selection_brush = wx.Brush(wx.Colour(225, 225, 255))
        self._selection_pen = wx.Pen(wx.SystemSettings_GetColour(wx.SYS_COLOUR_ACTIVECAPTION))

        sysfont = wx.SystemSettings.GetFont(wx.SYS_DEFAULT_GUI_FONT)
        self._caption_font = wx.Font(sysfont.GetPointSize(), wx.DEFAULT, wx.NORMAL, wx.BOLD,
                                     False, sysfont.GetFaceName())
        self._buttontext_font = wx.Font(sysfont.GetPointSize(), wx.DEFAULT, wx.NORMAL, wx.NORMAL,
                                        False, sysfont.GetFaceName())

        self._separator_size = 7
        self._margins_size = wx.Size(6, 6)
        self._caption_border_size = 3
        self._padding_size = wx.Size(6, 6)

[docs]    def GetMetric(self, id):
        """
        Returns the option value for the specified size `id`.

        :param integer `id`: the identification bit for the size value. This can be one of the
         following bits:

         ============================== ======= =====================================
         Size Id                         Value  Description
         ============================== ======= =====================================
         ``BP_SEPARATOR_SIZE``               14 Separator size. Note: This is not the line width, but the sum of the space before and after the separator line plus the width of the line
         ``BP_MARGINS_SIZE``                 15 Size of the left/right margins in L{ButtonPanel} (top/bottom for vertically aligned L{ButtonPanel})
         ``BP_BORDER_SIZE``                  16 Size of the border
         ``BP_PADDING_SIZE``                 17 Inter-tool separator size
         ============================== ======= =====================================

        :return: An integer representing the option value for the input `id`.

        :raise: `Exception` if the `id` is not recognized.
        """

        if id == BP_SEPARATOR_SIZE:
            return self._separator_size
        elif id == BP_MARGINS_SIZE:
            return self._margins_size
        elif id == BP_BORDER_SIZE:
            return self._caption_border_size
        elif id == BP_PADDING_SIZE:
            return self._padding_size
        else:
            raise Exception("\nERROR: Invalid Metric Ordinal. ")

[docs]    def SetMetric(self, id, new_val):
        """
        Sets the option value for the specified size `id`.

        :param integer `id`: the identification bit for the size value;
        :param input`new_val`: the new value for the size.

        :raise: `Exception` if the `id` is not recognized.

        :see: L{GetMetric} for a list of meaningful size ids.
        """

        if id == BP_SEPARATOR_SIZE:
            self._separator_size = new_val
        elif id == BP_MARGINS_SIZE:
            self._margins_size = new_val
        elif id == BP_BORDER_SIZE:
            self._caption_border_size = new_val
            self._border_pen.SetWidth(new_val)
        elif id == BP_PADDING_SIZE:
            self._padding_size = new_val
        else:
            raise Exception("\nERROR: Invalid Metric Ordinal. ")

[docs]    def GetColour(self, id):
        """
        Returns the option value for the specified colour `id`.

        :param internal`id`: the identification bit for the colour value. This can be one of the
         following bits:

         ================================== ======= =====================================
         Colour Id                           Value  Description
         ================================== ======= =====================================
         ``BP_BACKGROUND_COLOUR``                 0 Background brush colour when no gradient shading exists
         ``BP_GRADIENT_COLOUR_FROM``              1 Starting gradient colour, used only when ``BP_USE_GRADIENT`` style is applied
         ``BP_GRADIENT_COLOUR_TO``                2 Ending gradient colour, used only when ``BP_USE_GRADIENT`` style is applied
         ``BP_BORDER_COLOUR``                     3 Pen colour to paint the border of L{ButtonPanel}
         ``BP_TEXT_COLOUR``                       4 Main L{ButtonPanel} caption colour
         ``BP_BUTTONTEXT_COLOUR``                 5 Text colour for buttons with text
         ``BP_BUTTONTEXT_INACTIVE_COLOUR``        6 Text colour for inactive buttons with text
         ``BP_SELECTION_BRUSH_COLOUR``            7 Brush colour to be used when hovering or selecting a button
         ``BP_SELECTION_PEN_COLOUR``              8 Pen colour to be used when hovering or selecting a button
         ``BP_SEPARATOR_COLOUR``                  9 Pen colour used to paint the separators
         ================================== ======= =====================================

        :return: An instance of `wx.Colour` for the input `id`.

        :raise: `Exception` if the `id` is not recognized.
        """

        if id == BP_BACKGROUND_COLOUR:
            return self._background_brush.GetColour()
        elif id == BP_GRADIENT_COLOUR_FROM:
            return self._gradient_colour_from
        elif id == BP_GRADIENT_COLOUR_TO:
            return self._gradient_colour_to
        elif id == BP_BORDER_COLOUR:
            return self._border_pen.GetColour()
        elif id == BP_TEXT_COLOUR:
            return self._caption_text_colour
        elif id == BP_BUTTONTEXT_COLOUR:
            return self._buttontext_colour
        elif id == BP_BUTTONTEXT_INACTIVE_COLOUR:
            return self._buttontext_inactive_colour
        elif id == BP_SELECTION_BRUSH_COLOUR:
            return self._selection_brush.GetColour()
        elif id == BP_SELECTION_PEN_COLOUR:
            return self._selection_pen.GetColour()
        elif id == BP_SEPARATOR_COLOUR:
            return self._separator_pen.GetColour()
        else:
            raise Exception("\nERROR: Invalid Colour Ordinal. ")

[docs]    def SetColour(self, id, colour):
        """
        Sets the option value for the specified colour `id`.

        :param integer `id`: the identification bit for the colour value;
        :param `colour`: the new value for the colour (a valid `wx.Colour` instance).

        :raise: `Exception` if the `id` is not recognized.

        :see: L{GetColour} for a list of meaningful colour ids.
        """

        if id == BP_BACKGROUND_COLOUR:
            self._background_brush.SetColour(colour)
        elif id == BP_GRADIENT_COLOUR_FROM:
            self._gradient_colour_from = colour
        elif id == BP_GRADIENT_COLOUR_TO:
            self._gradient_colour_to = colour
        elif id == BP_BORDER_COLOUR:
            self._border_pen.SetColour(colour)
        elif id == BP_TEXT_COLOUR:
            self._caption_text_colour = colour
        elif id == BP_BUTTONTEXT_COLOUR:
            self._buttontext_colour = colour
        elif id == BP_BUTTONTEXT_INACTIVE_COLOUR:
            self._buttontext_inactive_colour = colour
        elif id == BP_SELECTION_BRUSH_COLOUR:
            self._selection_brush.SetColour(colour)
        elif id == BP_SELECTION_PEN_COLOUR:
            self._selection_pen.SetColour(colour)
        elif id == BP_SEPARATOR_COLOUR:
            self._separator_pen.SetColour(colour)
        else:
            raise Exception("\nERROR: Invalid Colour Ordinal. ")

    GetColor = GetColour
    SetColor = SetColour

[docs]    def GetFont(self, id):
        """
        Returns the option value for the specified font `id`.

        :param integer `id`: the identification bit for the font value. This can be one of the
         following bits:

         ============================== ======= =====================================
         Size Id                         Value  Description
         ============================== ======= =====================================
         ``BP_TEXT_FONT``                    10 Font of the L{ButtonPanel} main caption
         ``BP_BUTTONTEXT_FONT``              11 Text font for the buttons with text
         ============================== ======= =====================================

        :return: An instance of `wx.Font` for the input `id`.

        :raise: `Exception` if the `id` is not recognized.
        """

        if id == BP_TEXT_FONT:
            return self._caption_font
        elif id == BP_BUTTONTEXT_FONT:
            return self._buttontext_font

        return wx.NoneFont

[docs]    def SetFont(self, id, font):
        """
        Sets the option value for the specified font `id`.

        :param integer `id`: the identification bit for the font value;
        :param `colour`: the new value for the font (a valid `wx.Font` instance).

        :raise: `Exception` if the `id` is not recognized.

        :see: L{GetFont} for a list of meaningful font ids.
        """

        if id == BP_TEXT_FONT:
            self._caption_font = font
        elif id == BP_BUTTONTEXT_FONT:
            self._buttontext_font = font

[docs]    def SetGradientType(self, gradient):
        """
        Sets the gradient type for L{BPArt} drawings.

        :param integer `gradient`: can be one of the following bits:

         ============================ ======= ============================
         Gradient Type                 Value  Description
         ============================ ======= ============================
         ``BP_GRADIENT_NONE``               0 No gradient shading should be used to paint the background
         ``BP_GRADIENT_VERTICAL``           1 Vertical gradient shading should be used to paint the background
         ``BP_GRADIENT_HORIZONTAL``         2 Horizontal gradient shading should be used to paint the background
         ============================ ======= ============================

        """

        self._gradient_type = gradient

[docs]    def GetGradientType(self):
        """
        Returns the gradient type for L{BPArt} drawings.

        :return: An integer representing the gradient type.

        :see: L{SetGradientType} for a list of possible gradient types.
        """

        return self._gradient_type

[docs]    def DrawSeparator(self, dc, rect, isVertical):
        """
        Draws a separator in L{ButtonPanel}.

        :param `dc`: an instance of `wx.DC`;
        :param `wx.Rect` `rect`: the separator client rectangle;
        :param bool `isVertical`: ``True`` if L{ButtonPanel} is in vertical orientation,
         ``False`` otherwise.
        """

        dc.SetPen(self._separator_pen)

        if isVertical:
            ystart = yend = rect.y + rect.height/2
            xstart = int(rect.x + 1.5*self._caption_border_size)
            xend = int(rect.x + rect.width - 1.5*self._caption_border_size)
            dc.DrawLine(xstart, ystart, xend, yend)
        else:
            xstart = xend = rect.x + rect.width/2
            ystart = int(rect.y + 1.5*self._caption_border_size)
            yend = int(rect.y + rect.height - 1.5*self._caption_border_size)
            dc.DrawLine(xstart, ystart, xend, yend)

[docs]    def DrawCaption(self, dc, rect, captionText):
        """
        Draws the main caption text in L{ButtonPanel}.

        :param `dc`: an instance of `wx.DC`;
        :param `wx.Rect` `rect`: the main caption text rectangle;
        :param string `captionText`: the caption text string.
        """

        textColour = self._caption_text_colour
        textFont = self._caption_font
        padding = self._padding_size

        dc.SetTextForeground(textColour)
        dc.SetFont(textFont)

        dc.DrawText(captionText, rect.x + padding.x, rect.y+padding.y)

[docs]    def DrawButton(self, dc, rect, buttonBitmap, isVertical, buttonStatus,
                   isToggled, textAlignment, text=""):
        """
        Draws a button in L{ButtonPanel}, together with its text (if any).

        :param `dc`: an instance of `wx.DC`;
        :param `wx.Rect` `rect`: the button client rectangle;
        :param `wx.Bitmap` `buttonBitmap`: the bitmap associated with the button;
        :param bool `isVertical`: ``True`` if L{ButtonPanel} is in vertical orientation,
         ``False`` otherwise;
        :param string `buttonStatus`: one of "Normal", "Toggled", "Pressed", "Disabled" or "Hover";
        :param bool `isToggled`: whether the button is toggled or not;
        :param integer `textAlignment`: the text alignment inside the button;
        :param string `text`: the button label.
        """

        bmpxsize, bmpysize = buttonBitmap.GetWidth(), buttonBitmap.GetHeight()
        dx = dy = focus = 0

        borderw = self._caption_border_size
        padding = self._padding_size

        buttonFont = self._buttontext_font
        dc.SetFont(buttonFont)

        if isVertical:

            rect = wx.Rect(borderw, rect.y, rect.width-2*borderw, rect.height)

            if text != "":

                textW, textH = dc.GetTextExtent(text)

                if textAlignment == BP_BUTTONTEXT_ALIGN_RIGHT:
                    fullExtent = bmpxsize + padding.x/2 + textW
                    bmpypos = rect.y + (rect.height - bmpysize)/2
                    bmpxpos = rect.x + (rect.width - fullExtent)/2
                    textxpos = bmpxpos + padding.x/2 + bmpxsize
                    textypos = bmpypos + (bmpysize - textH)/2
                else:
                    bmpxpos = rect.x + (rect.width - bmpxsize)/2
                    bmpypos = rect.y + padding.y
                    textxpos = rect.x + (rect.width - textW)/2
                    textypos = bmpypos + bmpysize + padding.y/2
            else:
                bmpxpos = rect.x + (rect.width - bmpxsize)/2
                bmpypos = rect.y + (rect.height - bmpysize)/2

        else:

            rect = wx.Rect(rect.x, borderw, rect.width, rect.height-2*borderw)

            if text != "":

                textW, textH = dc.GetTextExtent(text)

                if textAlignment == BP_BUTTONTEXT_ALIGN_RIGHT:
                    fullExtent = bmpxsize + padding.x/2 + textW
                    bmpypos = rect.y + (rect.height - bmpysize)/2
                    bmpxpos = rect.x + (rect.width - fullExtent)/2
                    textxpos = bmpxpos + padding.x/2 + bmpxsize
                    textypos = bmpypos + (bmpysize - textH)/2
                else:
                    fullExtent = bmpysize + padding.y/2 + textH
                    bmpxpos = rect.x + (rect.width - bmpxsize)/2
                    bmpypos = rect.y + (rect.height - fullExtent)/2
                    textxpos = rect.x + (rect.width - textW)/2
                    textypos = bmpypos + bmpysize + padding.y/2
            else:
                bmpxpos = rect.x + (rect.width - bmpxsize)/2
                bmpypos = rect.y + (rect.height - bmpysize)/2

        # Draw a button
        # [ Padding | Text | .. Buttons .. | Padding ]

        if buttonStatus in ["Pressed", "Toggled", "Hover"]:
            dc.SetBrush(self._selection_brush)
            dc.SetPen(self._selection_pen)
            dc.DrawRoundedRectangleRect(rect, 4)

        if buttonStatus == "Pressed" or isToggled:
            dx = dy = 1

        if buttonBitmap:
            dc.DrawBitmap(buttonBitmap, bmpxpos+dx, bmpypos+dy, True)

        if text != "":
            isEnabled = buttonStatus != "Disabled"
            self.DrawLabel(dc, text, isEnabled, textxpos+dx, textypos+dy)

[docs]    def DrawLabel(self, dc, text, isEnabled, xpos, ypos):
        """
        Draws the label for a button.

        :param `dc`: an instance of `wx.DC`;
        :param string `text`: the button label;
        :param bool `isEnabled`: ``True`` if the button is enabled, ``False`` otherwise;
        :param integer `xpos`: the text `x` position inside the button;
        :param integer `ypos`: the text `y` position inside the button.
        """

        if not isEnabled:
            dc.SetTextForeground(self._buttontext_inactive_colour)
        else:
            dc.SetTextForeground(self._buttontext_colour)

        dc.DrawText(text, xpos, ypos)

[docs]    def DrawButtonPanel(self, dc, rect, style):
        """
        Paint the L{ButtonPanel}'s background.

        :param `dc`: an instance of `wx.DC`;
        :param `wx.Rect` `rect`: the L{ButtonPanel} client rectangle;
        :param integer `style`: the L{ButtonPanel} window style.
        """

        if style & BP_USE_GRADIENT:
            # Draw gradient colour in the backgroud of the panel
            self.FillGradientColour(dc, rect)

        # Draw a rectangle around the panel
        backBrush = (style & BP_USE_GRADIENT and [wx.TRANSPARENT_BRUSH] or \
                     [self._background_brush])[0]

        dc.SetBrush(backBrush)
        dc.SetPen(self._border_pen)
        dc.DrawRectangleRect(rect)

[docs]    def FillGradientColour(self, dc, rect):
        """
        Gradient fill from colour 1 to colour 2 with top to bottom or left to right.

        :param `dc`: an instance of `wx.DC`;
        :param `wx.Rect` `rect`: the L{ButtonPanel} client rectangle.
        """

        if rect.height < 1 or rect.width < 1:
            return

        isVertical = self._gradient_type == BP_GRADIENT_VERTICAL
        size = (isVertical and [rect.height] or [rect.width])[0]
        start = (isVertical and [rect.y] or [rect.x])[0]

        # calculate gradient coefficients

        col2 = self._gradient_colour_from
        col1 = self._gradient_colour_to

        rf, gf, bf = 0, 0, 0
        rstep = float((col2.Red() - col1.Red()))/float(size)
        gstep = float((col2.Green() - col1.Green()))/float(size)
        bstep = float((col2.Blue() - col1.Blue()))/float(size)

        for coord in xrange(start, start + size):

            currCol = wx.Colour(col1.Red() + rf, col1.Green() + gf, col1.Blue() + bf)
            dc.SetBrush(wx.Brush(currCol, wx.SOLID))
            dc.SetPen(wx.Pen(currCol))
            if isVertical:
                dc.DrawLine(rect.x, coord, rect.x + rect.width, coord)
            else:
                dc.DrawLine(coord, rect.y, coord, rect.y + rect.height)

            rf += rstep
            gf += gstep
            bf += bstep

[docs]class StatusBarTimer(wx.Timer):
    """ Timer used for deleting `wx.StatusBar` long help after ``_DELAY`` seconds."""

[docs]    def __init__(self, owner):
        """
        Default class constructor.
        For internal use: do not call it in your code!

        :param `owner`: an instance of L{ButtonPanel}.
        """

        wx.Timer.__init__(self)
        self._owner = owner

[docs]    def Notify(self):
        """ The timer has expired. """

        self._owner.OnStatusBarTimer()

[docs]class Control(wx.EvtHandler):
    """
    This class represents a base class for all pseudo controls used in
    L{ButtonPanel}.
    """

[docs]    def __init__(self, parent, size=wx.Size(-1, -1), id=wx.ID_ANY):
        """
        Default class constructor.

        :param `wx.Window` `parent`: the control parent object. Must not be ``None``;
        :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 `wx.Size`
        :param integer `id`: window identifier. A value of -1 indicates a default value.
        """

        wx.EvtHandler.__init__(self)

        self._parent = parent

        if id == wx.ID_ANY:
            self._id = wx.NewId()
        else:
            self._id = id

        self._size = size
        self._isshown = True
        self._focus = False

[docs]    def Show(self, show=True):
        """
        Shows or hide the control.

        :param bool `show`: If ``True`` displays the window. Otherwise, it hides it.
        """

        self._isshown = show

[docs]    def Hide(self):
        """
        Hides the control.

        :note: This is functionally equivalent of calling L{Show} with a ``False`` input.
        """

        self.Show(False)

[docs]    def IsShown(self):
        """ Returns ``True`` if the window is shown, ``False`` if it has been hidden. """

        return self._isshown

[docs]    def GetId(self):
        """
        Returns the identifier of the window.

        :return: An integer representing the identifier of the window.

        :note: Each window has an integer identifier. If the application has not provided
         one (or the default ``wx.ID_ANY``) an unique identifier with a negative value will
         be generated.
        """

        return self._id

[docs]    def GetBestSize(self):
        """
        This functions returns the best acceptable minimal size for the window. For
        example, for a static control, it will be the minimal size such that the control
        label is not truncated. For windows containing subwindows (typically `wx.Panel`),
        the size returned by this function will be the same as the size the window would
        have had after calling `Fit()`.

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

        return self._size

[docs]    def Disable(self):
        """
        Disables the control.

        :returns: ``True`` if the window has been disabled, ``False`` if it had been
         already disabled before the call to this function.

        :note: This is functionally equivalent of calling L{Enable} with a ``False`` flag.
        """

        return self.Enable(False)

[docs]    def Enable(self, value=True):
        """
        Enable or disable the window for user input.

        :param bool `enable`: If ``True``, enables the window for input. If ``False``, disables the window.

        :returns: ``True`` if the window has been enabled or disabled, ``False`` if nothing was
         done, i.e. if the window had already been in the specified state.

        :note: Note that when a parent window is disabled, all of its children are disabled as
         well and they are reenabled again when the parent is.
        """

        self.disabled = not value
        return True

[docs]    def SetFocus(self, focus=True):
        """
        Sets or kills the focus on the control.

        :param bool `focus`: whether the control can receive keyboard inputs or not.
        """

        self._focus = focus

[docs]    def HasFocus(self):
        """
        Returns whether the control has the focus or not.

        :return: ``True`` if the control has the focus, ``False`` otherwise.
        """

        return self._focus

[docs]    def OnMouseEvent(self, x, y, event):
        """
        Handles the ``wx.EVT_MOUSE_EVENTS`` events for the control.

        :param integer `x`: the mouse `x` position;
        :param integer `y`: the mouse `y` position;
        :param `event`: the `wx.MouseEvent` event to be processed.
        """

        pass

[docs]    def Draw(self, rect):
        """
        Handles the drawing of the control.

        :param `wx.Rect` `rect`: the control client rectangle.
        """

        pass

[docs]class Sizer(object):
    """
    This is a mix-in class to add pseudo support to `wx.Sizer`. Just create
    a new class that derives from this class and `wx.Sizer` and intercepts
    any methods that add to the wx sizer.
    """

[docs]    def __init__(self):
        """
        Default class constructor.
        For internal use: do not call it in your code!
        """

        self.children = [] # list of child Pseudo Controls

    # Sizer doesn't use the x1,y1,x2,y2 so allow it to
    # be called with or without the coordinates

[docs]    def Draw(self, dc, x1=0, y1=0, x2=0, y2=0):
        """ Draws all the children of the sizer. """

        for item in self.children:
            # use sizer coordinates rather than
            # what is passed in
            c = item.GetUserData()
            c.Draw(dc, item.GetRect())

[docs]    def GetBestSize(self):
        """
        This functions returns the best acceptable minimal size for the sizer object.

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

        # this should be handled by the wx.Sizer based class
        return self.GetMinSize()

# Pseudo BoxSizer

[docs]class BoxSizer(Sizer, wx.BoxSizer):
    """ Pseudo-class that imitates `wx.BoxSizer`. """

[docs]    def __init__(self, orient=wx.HORIZONTAL):
        """
        Constructor for L{BoxSizer}.

        :param integer `orient`: may be one of ``wx.VERTICAL`` or ``wx.HORIZONTAL`` for creating
         either a column sizer or a row sizer.
        """

        wx.BoxSizer.__init__(self, orient)
        Sizer.__init__(self)

    #-------------------------------------------
    # sizer overrides (only called from Python)
    #-------------------------------------------
    # no support for user data if it's a pseudocontrol
    # since that is already used

[docs]    def Add(self, item, proportion=0, flag=0, border=0, userData=None):
        """
        Appends a child item to the sizer.

        :param `item`: the item to be added to L{BoxSizer}. Can be an instance of `wx.Window`,
         `wx.Sizer` or a spacer;
        :param integer `proportion`: this parameter is used in L{BoxSizer} to indicate if a child of
         a sizer can change its size in the main orientation of the L{BoxSizer} - where 0
         stands for not changeable and a value of more than zero is interpreted relative
         to the value of other children of the same L{BoxSizer}. For example, you might have
         a horizontal L{BoxSizer} with three children, two of which are supposed to change their
         size with the sizer. Then the two stretchable windows would get a value of 1 each to
         make them grow and shrink equally with the sizer's horizontal dimension.
        :param integer `flag`: this parameter can be used to set a number of flags which can be combined using the binary OR operator ``|``.
         Two main behaviours are defined using these flags. One is the border around a window: the border parameter determines the border
         width whereas the flags given here determine which side(s) of the item that the border will be added. The other flags determine
         how the sizer item behaves when the space allotted to the sizer changes, and is somewhat dependent on the specific kind of sizer used:

         +---------------------------------------------------------------------+-----------------------------------------------------------------------------+
         | Sizer Flag                                                          | Description                                                                 |
         +=====================================================================+=============================================================================+
         | ``wx.TOP``                                                          | These flags are used to specify which side(s) of the sizer                  |
         +---------------------------------------------------------------------+ item the border width will apply to.                                        |
         | ``wx.BOTTOM``                                                       |                                                                             |
         +---------------------------------------------------------------------+                                                                             |
         | ``wx.LEFT``                                                         |                                                                             |
         +---------------------------------------------------------------------+                                                                             |
         | ``wx.RIGHT``                                                        |                                                                             |
         +---------------------------------------------------------------------+                                                                             |
         | ``wx.ALL``                                                          |                                                                             |
         +---------------------------------------------------------------------+-----------------------------------------------------------------------------+
         | ``wx.EXPAND``                                                       | The item will be expanded to fill the space assigned to                     |
         |                                                                     | the item.                                                                   |
         +---------------------------------------------------------------------+-----------------------------------------------------------------------------+
         | ``wx.SHAPED``                                                       | The item will be expanded as much as possible while also                    |
         |                                                                     | maintaining its aspect ratio                                                |
         +---------------------------------------------------------------------+-----------------------------------------------------------------------------+
         | ``wx.FIXED_MINSIZE``                                                | Normally `wx.Sizers` will use                                               |
         |                                                                     | ``wx.Window.GetAdjustedBestSize`` to                                        |
         |                                                                     | determine what the minimal size of window items should be, and will use that|
         |                                                                     | size to calculate the layout. This allows layouts to adjust when an item    |
         |                                                                     | changes and its best size becomes different. If you would rather have a     |
         |                                                                     | window item stay the size it started with then use ``wx.FIXED_MINSIZE``.    |
         +---------------------------------------------------------------------+-----------------------------------------------------------------------------+
         | ``wx.RESERVE_SPACE_EVEN_IF_HIDDEN``                                 | Normally `wx.Sizers` don't allocate space for hidden windows or other items.|
         |                                                                     | This flag overrides this behavior so that sufficient space is allocated for |
         |                                                                     | the window even if it isn't visible. This makes it possible to dynamically  |
         |                                                                     | show and hide controls without resizing parent dialog, for example. This    |
         |                                                                     | function is new since wxWidgets version 2.8.8                               |
         +---------------------------------------------------------------------+-----------------------------------------------------------------------------+
         | ``wx.ALIGN_CENTER`` **or** ``wx.ALIGN_CENTRE``                      | The ``wx.ALIGN*`` flags allow you to specify the alignment of the item      |
         +---------------------------------------------------------------------+ within the space allotted to it by the sizer, adjusted for the border if    |
         | ``wx.ALIGN_LEFT``                                                   | any.                                                                        |
         +---------------------------------------------------------------------+                                                                             |
         | ``wx.ALIGN_RIGHT``                                                  |                                                                             |
         +---------------------------------------------------------------------+                                                                             |
         | ``wx.ALIGN_TOP``                                                    |                                                                             |
         +---------------------------------------------------------------------+                                                                             |
         | ``wx.ALIGN_BOTTOM``                                                 |                                                                             |
         +---------------------------------------------------------------------+                                                                             |
         | ``wx.ALIGN_CENTER_VERTICAL`` **or** ``wx.ALIGN_CENTRE_VERTICAL``    |                                                                             |
         +---------------------------------------------------------------------+                                                                             |
         | ``wx.ALIGN_CENTER_HORIZONTAL`` **or** ``wx.ALIGN_CENTRE_HORIZONTAL``|                                                                             |
         +---------------------------------------------------------------------+-----------------------------------------------------------------------------+

        :param integer `border`: determines the border width, if the flag parameter is set
         to include any border flag.
        :param object `userData`: Allows an extra object to be attached to the sizer item,
         for use in derived classes when sizing information is more complex than the
         proportion and flag will allow for.

        :note: there is no support for `userData` parameter if `item` is a pseudocontrol,
         since that is already used.
        """

        # check to see if it's a pseudo object or sizer
        if isinstance(item, Sizer):
            szitem = wx.BoxSizer.Add(self, item, proportion, flag, border, item)
            self.children.append(szitem)
        elif isinstance(item, Control): # Control should be what ever class your controls come from
            sz = item.GetBestSize()
            # add a spacer to track this object
            szitem = wx.BoxSizer.Add(self, sz, proportion, flag, border, item)
            self.children.append(szitem)
        else:
            wx.BoxSizer.Add(self, item, proportion, flag, border, userData)

[docs]    def Prepend(self, item, proportion=0, flag=0, border=0, userData=None):
        """
        Prepends a child item to the sizer.

        :see: L{Add} method for an explanation of the input parameters.
        """

        # check to see if it's a pseudo object or sizer
        if isinstance(item, Sizer):
            szitem = wx.BoxSizer.Prepend(self, item, proportion, flag, border, item)
            self.children.append(szitem)
        elif isinstance(item, Control): # Control should be what ever class your controls come from
            sz = item.GetBestSize()
            # add a spacer to track this object
            szitem = wx.BoxSizer.Prepend(self, sz, proportion, flag, border, item)
            self.children.insert(0,szitem)
        else:
            wx.BoxSizer.Prepend(self, item, proportion, flag, border, userData)

[docs]    def Insert(self, before, item, proportion=0, flag=0, border=0, userData=None, realIndex=None):
        """
        Inserts a child item into the sizer.

        :see: L{Add} method for an explanation of the input parameters.
        """

        # check to see if it's a pseudo object or sizer
        if isinstance(item, Sizer):
            szitem = wx.BoxSizer.Insert(self, before, item, proportion, flag, border, item)
            self.children.append(szitem)
        elif isinstance(item, Control): # Control should be what ever class your controls come from
            sz = item.GetBestSize()
            # add a spacer to track this object
            szitem = wx.BoxSizer.Insert(self, before, sz, proportion, flag, border, item)
            if realIndex is not None:
                self.children.insert(realIndex,szitem)
            else:
                self.children.insert(before,szitem)

        else:
            wx.BoxSizer.Insert(self, before, item, proportion, flag, border, userData)

[docs]    def Remove(self, indx, pop=-1):
        """
        Removes an item from the sizer and destroys it.

        This method does not cause any layout or resizing to take place, call
        L{BoxSizer.Layout} to update the layout on screen after removing a child from
        the sizer.

        :param integer `indx`: the zero-based index of an item to remove;
        :param bool `pop`: whether to remove the sizer item from the list of children.
        """

        if pop >= 0:
            self.children.pop(pop)

        wx.BoxSizer.Remove(self, indx)

[docs]    def Layout(self):
        """
        Call this to force layout of the children anew, e.g. after having added a
        child to or removed a child (window, other sizer or space) from the sizer
        while keeping the current dimension.
        """

        for ii, child in enumerate(self.GetChildren()):
            item = child.GetUserData()
            if item and child.IsShown():
                self.SetItemMinSize(ii, *item.GetBestSize())

        wx.BoxSizer.Layout(self)

[docs]    def Show(self, item, show=True):
        """
        Shows or hides the sizer item.

        :param `item`: the sizer item we want to show/hide;
        :param bool `show`: ``True`` to show the item, ``False`` to hide it.
        """

        child = self.GetChildren()[item]
        if child and child.GetUserData():
            child.GetUserData().Show(show)

        wx.BoxSizer.Show(self, item, show)

# ---------------------------------------------------------------------------- #
# Class Separator
# This class holds all the information to size and draw a separator inside
# ButtonPanel
# ---------------------------------------------------------------------------- #

[docs]class Separator(Control):
    """
    This class holds all the information to size and draw a separator inside
    L{ButtonPanel}.
    """

[docs]    def __init__(self, parent):
        """
        Default class constructor.

        :param `parent`: the separator parent object, an instance of L{ButtonPanel}.
        """

        self._isshown = True
        self._parent = parent
        Control.__init__(self, parent)

[docs]    def GetBestSize(self):
        """
        Returns the separator best size.

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

        # 10 is completely arbitrary, but it works anyhow
        if self._parent.IsVertical():
            return wx.Size(10, self._parent._art.GetMetric(BP_SEPARATOR_SIZE))
        else:
            return wx.Size(self._parent._art.GetMetric(BP_SEPARATOR_SIZE), 10)

[docs]    def Draw(self, dc, rect):
        """
        Draws the separator. Actually the drawing is done in L{BPArt}.

        :param `dc`: an instance of `wx.DC`;
        :param `wx.Rect` `rect`: the separator client rectangle.
        """

        if not self.IsShown():
            return

        isVertical = self._parent.IsVertical()
        self._parent._art.DrawSeparator(dc, rect, isVertical)

# ---------------------------------------------------------------------------- #
# Class ButtonPanelText
# This class is used to hold data about the main caption in ButtonPanel
# ---------------------------------------------------------------------------- #

[docs]class ButtonPanelText(Control):
    """ This class is used to hold data about the main caption in L{ButtonPanel}. """

[docs]    def __init__(self, parent, text=""):
        """
        Default class constructor.

        :param `parent`: the text parent object, an instance of L{ButtonPanel};
        :param string `text`: the actual main caption string.
        """

        self._text = text
        self._isshown = True
        self._parent = parent

        Control.__init__(self, parent)

[docs]    def GetText(self):
        """
        Returns the caption text.

        :return: A string representing the caption text.
        """

        return self._text

[docs]    def SetText(self, text=""):
        """
        Sets the caption text.

        :param string `text`: the main caption string.
        """

        self._text = text

[docs]    def CreateDC(self):
        """ Convenience function to create a `wx.DC`. """

        dc = wx.ClientDC(self._parent)
        textFont = self._parent._art.GetFont(BP_TEXT_FONT)
        dc.SetFont(textFont)

        return dc

[docs]    def GetBestSize(self):
        """
        Returns the best size for the main caption in L{ButtonPanel}.

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

        if self._text == "":
            return wx.Size(0, 0)

        dc = self.CreateDC()
        rect = self._parent.GetClientRect()

        tw, th = dc.GetTextExtent(self._text)
        padding = self._parent._art.GetMetric(BP_PADDING_SIZE)
        self._size = wx.Size(tw+2*padding.x, th+2*padding.y)

        return self._size

[docs]    def Draw(self, dc, rect):
        """
        Draws the main caption. Actually the drawing is done in L{BPArt}.

        :param `dc`: an instance of `wx.DC`;
        :param `wx.Rect` `rect`: the main caption text client rectangle.
        """

        if not self.IsShown():
            return

        captionText = self.GetText()
        self._parent._art.DrawCaption(dc, rect, captionText)

# -- ButtonInfo class implementation ----------------------------------------
# This class holds information about every button that is added to
# ButtonPanel.  It is an auxiliary class that you should use
# every time you add a button.

[docs]class ButtonInfo(Control):
    """
    This class holds information about every button that is added to
    L{ButtonPanel}. It is an auxiliary class that you should use
    every time you add a button.
    """

[docs]    def __init__(self, parent, id=wx.ID_ANY, bmp=wx.NullBitmap,
                 status="Normal", text="", kind=wx.ITEM_NORMAL,
                 shortHelp="", longHelp=""):
        """
        Default class constructor.

        :param `parent`: the parent window (L{ButtonPanel});
        :param integer `id`: the button id;
        :param `wx.Bitmap` `bmp`: the associated bitmap;
        :param string `status`: button status ("Pressed", "Hover", "Normal", "Toggled", "Disabled");
        :param string `text`: text to be displayed either below of to the right of the button;
        :param integer `kind`: button kind, may be ``wx.ITEM_NORMAL`` for standard buttons or
         ``wx.ITEM_CHECK`` for toggle buttons;
        :param string `shortHelp`: a short help to be shown in the button tooltip;
        :param string `longHelp`: this string is shown in the statusbar (if any) of the parent
         frame when the mouse pointer is inside the button.
        """

        if id == wx.ID_ANY:
            id = wx.NewId()

        self._status = status
        self._rect = wx.Rect()
        self._text = text
        self._kind = kind
        self._toggle = False
        self._textAlignment = BP_BUTTONTEXT_ALIGN_BOTTOM
        self._shortHelp = shortHelp
        self._longHelp = longHelp

        if bmp and bmp.IsOk():
            disabledbmp = MakeDisabledBitmap(bmp)
        else:
            disabledbmp = wx.NullBitmap

        self._bitmaps = {"Normal": bmp, "Toggled": None, "Disabled": disabledbmp,
                         "Hover": None, "Pressed": None}

        Control.__init__(self, parent, id=id)

[docs]    def GetBestSize(self):
        """
        Returns the best size for the button.

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

        xsize = self.GetBitmap().GetWidth()
        ysize = self.GetBitmap().GetHeight()

        if self.HasText():
            # We have text in the button
            dc = wx.ClientDC(self._parent)
            normalFont = self._parent._art.GetFont(BP_BUTTONTEXT_FONT)
            dc.SetFont(normalFont)
            tw, th = dc.GetTextExtent(self.GetText())

            if self.GetTextAlignment() == BP_BUTTONTEXT_ALIGN_BOTTOM:
                xsize = max(xsize, tw)
                ysize = ysize + th
            else:
                xsize = xsize + tw
                ysize = max(ysize, th)

        border = self._parent._art.GetMetric(BP_BORDER_SIZE)
        padding = self._parent._art.GetMetric(BP_PADDING_SIZE)

        if self._parent.IsVertical():
            xsize = xsize + 2*border
        else:
            ysize = ysize + 2*border

        self._size = wx.Size(xsize+2*padding.x, ysize+2*padding.y)

        return self._size

[docs]    def Draw(self, dc, rect):
        """
        Draws the button on L{ButtonPanel}. Actually the drawing is done in L{BPArt}.

        :param `dc`: an instance of `wx.DC`;
        :param `wx.Rect` `rect`: the main caption text client rectangle.
        """

        if not self.IsShown():
            return

        buttonBitmap = self.GetBitmap()
        isVertical = self._parent.IsVertical()
        text = self.GetText()
        buttonStatus = self.GetStatus()
        isToggled = self.GetToggled()
        textAlignment = self.GetTextAlignment()

        self._parent._art.DrawButton(dc, rect, buttonBitmap, isVertical,
                                     buttonStatus, isToggled, textAlignment, text)

        self.SetRect(rect)

[docs]    def CheckRefresh(self, status):
        """
        Checks whether a L{ButtonPanel} repaint is needed or not. This is a convenience function.

        :param bool `status`: the status of a newly added L{ButtonInfo} or a change in the
         L{ButtonInfo} status.
        """

        if status == self._status:
            self._parent.RefreshRect(self.GetRect())

[docs]    def SetBitmap(self, bmp, status="Normal"):
        """
        Sets the bitmap associated with this instance of L{ButtonInfo}.

        :param `bmp`: a valid `wx.Bitmap` object;
        :param string `status`: the L{ButtonInfo} status ("Pressed", "Hover", "Normal",
         "Toggled", "Disabled").
        """

        self._bitmaps[status] = bmp
        self.CheckRefresh(status)

[docs]    def GetBitmap(self, status=None):
        """
        Returns the bitmap associated with this instance of L{ButtonInfo}.

        :param string `status`: the L{ButtonInfo} status ("Pressed", "Hover", "Normal",
         "Toggled", "Disabled").

        :return: An instance of `wx.Bitmap`.
        """

        if status is None:
            status = self._status

        if not self.IsEnabled():
            status = "Disabled"

        if self._bitmaps[status] is None:
            if self.GetToggled():
                if self._bitmaps["Toggled"] is not None:
                    return self._bitmaps["Toggled"]
            return self._bitmaps["Normal"]

        return self._bitmaps[status]

[docs]    def GetRect(self):
        """
        Returns the L{ButtonInfo} client rectangle.

        :return: An instance of `wx.Rect`.
        """

        return self._rect

[docs]    def GetStatus(self):
        """
        Returns the L{ButtonInfo} status.

        :return: A string containing the L{ButtonInfo} status (one of "Pressed", "Hover", "Normal",
         "Toggled", "Disabled").
        """

        return self._status

[docs]    def GetId(self):
        """
        Returns the L{ButtonInfo} id.

        :return: An integer representing the button id.
        """

        return self._id

[docs]    def SetRect(self, rect):
        """
        Sets the L{ButtonInfo} client rectangle.

        :param `rect`: an instance of `wx.Rect`.
        """

        self._rect = rect

[docs]    def SetStatus(self, status):
        """
        Sets the L{ButtonInfo} status.

        :param string `status`: one of "Pressed", "Hover", "Normal", "Toggled", "Disabled".
        """

        if status == self._status:
            return

        if self.GetToggled() and status == "Normal":
            status = "Toggled"

        self._status = status
        self._parent.RefreshRect(self.GetRect())

[docs]    def GetTextAlignment(self):
        """
        Returns the text alignment in the button (bottom or right).

        :return: An integer representing the L{ButtonInfo} text alignment.
        """

        return self._textAlignment

[docs]    def SetTextAlignment(self, alignment):
        """
        Sets the text alignment in the button (bottom or right).

        :param integer `alignment`: the text alignment in this L{ButtonInfo} instance.
        """

        if alignment == self._textAlignment:
            return

        self._textAlignment = alignment

[docs]    def GetToggled(self):
        """
        Returns whether a ``wx.ITEM_CHECK`` button is toggled or not.

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

        if self._kind == wx.ITEM_NORMAL:
            return False

        return self._toggle

[docs]    def SetToggled(self, toggle=True):
        """
        Sets a ``wx.ITEM_CHECK`` button toggled/not toggled.

        :param bool `toggle`: ``True`` to toggle the button, ``False`` otherwise.
        """

        if self._kind == wx.ITEM_NORMAL:
            return

        self._toggle = toggle

[docs]    def SetId(self, id):
        """
        Sets the L{ButtonInfo} identifier.

        :param integer `id`: the identifier of the window.
        """

        self._id = id

[docs]    def AddStatus(self, name="Custom", bmp=wx.NullBitmap):
        """
        Add a programmer-defined status in addition to the 5 default status:

         - Normal;
         - Disabled;
         - Hover;
         - Pressed;
         - Toggled.

        :param string `name`: the new status name;
        :param `wx.Bitmap` `bmp`: the bitmap associated with the new status.
        """

        self._bitmaps.update({name: bmp})

[docs]    def Enable(self, enable=True):
        """
        Enables/disables this instance of L{ButtonInfo}.

        :param bool `enable`: ``True`` to enable the button, ``False`` otherwise.
        """

        if enable:
            self._status = "Normal"
        else:
            self._status = "Disabled"

[docs]    def IsEnabled(self):
        """
        Returns ``True`` if this instance of L{ButtonInfo} is enabled for input,
        ``False`` otherwise.
        """

        return self._status != "Disabled"

[docs]    def SetText(self, text=""):
        """
        Sets the button label text.

        :param string `text`: the button label string.
        """

        self._text = text

[docs]    def GetText(self):
        """
        Returns the text associated to the button.

        :return: A string containing the L{ButtonInfo} text.
        """

        return self._text

[docs]    def HasText(self):
        """
        Returns whether the button has text or not.

        :return: ``True`` if this L{ButtonInfo} instance has a label, ``False`` otherwise.
        """

        return self._text != ""

[docs]    def SetKind(self, kind=wx.ITEM_NORMAL):
        """
        Sets the button type (standard or toggle).

        :param integer `kind`: one of ``wx.ITEM_NORMAL``, ``wx.ITEM_CHECK``.
        """

        self._kind = kind

[docs]    def GetKind(self):
        """
        Returns the button type (standard or toggle).

        :return: An integer representing the button type, one of ``wx.ITEM_NORMAL``, ``wx.ITEM_CHECK``.
        """

        return self._kind

[docs]    def SetShortHelp(self, help=""):
        """
        Sets the help string to be shown in a tooltip.

        :param string `help`: the string for the short help.
        """

        self._shortHelp = help

[docs]    def GetShortHelp(self):
        """
        Returns the help string shown in a tooltip.

        :return: A string containing the L{ButtonInfo} short help string.
        """

        return self._shortHelp

[docs]    def SetLongHelp(self, help=""):
        """
        Sets the help string to be shown in the statusbar.

        :param string `help`: the string for the long help.
        """

        self._longHelp = help

[docs]    def GetLongHelp(self):
        """
        Returns the help string shown in the statusbar.

        :return: A string containing the L{ButtonInfo} long help string.
        """

        return self._longHelp

    Bitmap = property(GetBitmap, SetBitmap)
    Id     = property(GetId, SetId)
    Rect   = property(GetRect, SetRect)
    Status = property(GetStatus, SetStatus)

# -- ButtonPanel class implementation ----------------------------------
# This is the main class.

[docs]class ButtonPanel(wx.PyPanel):
    """
    A custom panel class with gradient background shading with the possibility to
    add buttons and controls still respecting the gradient background.
    """

[docs]    def __init__(self, parent, id=wx.ID_ANY, text="", agwStyle=BP_DEFAULT_STYLE,
                 alignment=BP_ALIGN_LEFT, name="buttonPanel"):
        """
        Default class constructor.

        :param `wx.Window` `parent`: the parent window. Must not be ``None``;
        :param integer `id`: window identifier. If ``wx.ID_ANY``, will automatically create an identifier;
        :param string `text`: the main caption text for L{ButtonPanel};
        :param integer `agwStyle`: the AGW-specific window style (one of ``BP_DEFAULT_STYLE``, ``BP_USE_GRADIENT``);
        :param integer `alignment`: alignment of buttons (left or right);
        :param string `name`: window class name.
        """

        wx.PyPanel.__init__(self, parent, id, wx.DefaultPosition, wx.DefaultSize,
                            wx.NO_BORDER, name=name)

        self._vButtons = []
        self._vSeparators = []

        self._agwStyle = agwStyle
        self._alignment = alignment
        self._statusTimer = None
        self._useHelp = True
        self._freezeCount = 0
        self._currentButton = -1
        self._haveTip = False

        self._art = BPArt(agwStyle)

        self._controlCreated = False

        direction = (self.IsVertical() and [wx.VERTICAL] or [wx.HORIZONTAL])[0]
        self._mainsizer = BoxSizer(direction)
        self.SetSizer(self._mainsizer)

        margins = self._art.GetMetric(BP_MARGINS_SIZE)

        # First spacer to create some room before the first text/button/control
        self._mainsizer.Add((margins.x, margins.y), 0)

        # Last spacer to create some room before the last text/button/control
        self._mainsizer.Add((margins.x, margins.y), 0)

        self.Bind(wx.EVT_SIZE, self.OnSize)
        self.Bind(wx.EVT_PAINT, self.OnPaint)
        self.Bind(wx.EVT_ERASE_BACKGROUND, self.OnEraseBackground)
        self.Bind(wx.EVT_MOTION, self.OnMouseMove)
        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.OnMouseEnterWindow)

        self.SetBarText(text)
        self.LayoutItems()

[docs]    def SetBarText(self, text):
        """
        Sets the main caption text.

        :param string `text`: the main caption text label. An empty string erases the
         main caption text.
         """

        self.Freeze()

        text = text.strip()

        if self._controlCreated:
            self.RemoveText()

        self._text = ButtonPanelText(self, text)
        lenChildren = len(self._mainsizer.GetChildren())

        if text == "":
            # Even if we have no text, we insert it an empty spacer anyway
            # it is easier to handle if you have to recreate the sizer after.
            if self.IsStandard():
                self._mainsizer.Insert(1, self._text, 0, wx.ALIGN_CENTER,
                                       userData=self._text, realIndex=0)
            else:
                self._mainsizer.Insert(lenChildren-1, self._text, 0, wx.ALIGN_CENTER,
                                       userData=self._text, realIndex=lenChildren)

            return

        # We have text, so insert the text and an expandable spacer
        # alongside it. "Standard" ButtonPanel are left or top aligned.
        if self.IsStandard():
            self._mainsizer.Insert(1, self._text, 0, wx.ALIGN_CENTER,
                                    userData=self._text, realIndex=0)
            self._mainsizer.Insert(2, (0, 0), 1, wx.EXPAND)

        else:
            self._mainsizer.Insert(lenChildren-1, self._text, 0, wx.ALIGN_CENTER,
                                   userData=self._text, realIndex=lenChildren)
            self._mainsizer.Insert(lenChildren-1, (0, 0), 1, wx.EXPAND)

[docs]    def RemoveText(self):
        """ Removes the main caption text. """

        lenChildren = len(self._mainsizer.GetChildren())
        lenCustom = len(self._vButtons) + len(self._vSeparators) + 1

        if self.IsStandard():
            # Detach the text
            self._mainsizer.Remove(1, 0)
            if self.HasBarText():
                # Detach the expandable spacer
                self._mainsizer.Remove(1, -1)
        else:
            # Detach the text
            self._mainsizer.Remove(lenChildren-2, lenCustom-1)
            if self.HasBarText():
                # Detach the expandable spacer
                self._mainsizer.Remove(lenChildren-3, -1)

[docs]    def GetBarText(self):
        """
        Returns the main caption text.

        :return: A string representing the caption text.
        """

        return self._text.GetText()

[docs]    def HasBarText(self):
        """
        Returns whether L{ButtonPanel} has a main caption text or not.

        :return: ``True`` if L{ButtonPanel} has a main caption text, ``False`` otherwise.
        """

        return hasattr(self, "_text") and self._text.GetText() != ""

[docs]    def AddButton(self, btnInfo):
        """
        Adds a button to L{ButtonPanel}.

        :param `btnInfo`: an instance of L{ButtonInfo}.

        :note: Remember to pass a L{ButtonInfo} instance to this method, and not a
         standard `wx.Button` or a `wx.ToolBar` tool.
        """

        lenChildren = len(self._mainsizer.GetChildren())
        self._mainsizer.Insert(lenChildren-1, btnInfo, 0, wx.ALIGN_CENTER|wx.EXPAND, userData=btnInfo)

        self._vButtons.append(btnInfo)

[docs]    def AddSpacer(self, size=(0, 0), proportion=1, flag=wx.EXPAND):
        """
        Adds a spacer (stretchable or fixed-size) to L{ButtonPanel}.

        :param tuple `size`: the spacer size as a tuple;
        :param integer `proportion`: the spacer proportion (0 for fixed-size, 1 or more for a
         stretchable one);
        :param integer `flag`: one of the `wx.BoxSizer` flags.
        """

        lenChildren = len(self._mainsizer.GetChildren())
        self._mainsizer.Insert(lenChildren-1, size, proportion, flag)

[docs]    def AddControl(self, control, proportion=0, flag=wx.ALIGN_CENTER|wx.ALL, border=None):
        """
        Adds a wxPython control to L{ButtonPanel}.

        :param `control`: an instance of `wx.Window`;
        :param integer `proportion`: the control proportion (0 for fixed-size, 1 or more for a
         stretchable one);
        :param integer `flag`: one of the `wx.BoxSizer` flags;
        :param integer `border`: the control border width (in pixels), if the `flag` parameter
         is set to include any border flag.
        """

        lenChildren = len(self._mainsizer.GetChildren())

        if border is None:
            border = self._art.GetMetric(BP_PADDING_SIZE)
            border = max(border.x, border.y)

        self._mainsizer.Insert(lenChildren-1, control, proportion, flag, border)

[docs]    def AddSeparator(self):
        """ Adds a separator line to L{ButtonPanel}. """

        lenChildren = len(self._mainsizer.GetChildren())
        separator = Separator(self)

        self._mainsizer.Insert(lenChildren-1, separator, 0, wx.EXPAND)
        self._vSeparators.append(separator)

[docs]    def RemoveAllButtons(self):
        """
        Remove all the buttons from L{ButtonPanel}.

        :note: This function is for internal use only. If you are interested in
         manipulating a L{ButtonPanel} in real time (ie. removing things on it)
         have a look at the L{Clear} method.
        """

        self._vButtons = []

[docs]    def RemoveAllSeparators(self):
        """
        Remove all the separators from L{ButtonPanel}.

        :note: This function is for internal use only. If you are interested in
         manipulating a L{ButtonPanel} in real time (ie. removing things on it)
         have a look at the L{Clear} method.
        """

        self._vSeparators = []

[docs]    def Clear(self):
        """
        Clears the L{ButtonPanel}.

        Can be used to reset the L{ButtonPanel} if you'd like have a new set of
        buttons on the panel.
        """

        if self.HasBarText():
            bartext = self.GetBarText()
        else:
            bartext = None

        self.Freeze()

        self._currentButton = -1
        self._mainsizer.Clear()
        self.ReCreateSizer(bartext)

[docs]    def GetAlignment(self):
        """
        Returns the buttons alignment.

        :return: An integer specifying the buttons alignment.

        :see: L{SetAlignment} for a set of valid alignment bits.
        """

        return self._alignment

[docs]    def SetAlignment(self, alignment):
        """
        Sets the buttons alignment.

        :param integer `alignment`: can be one of the following bits:

         ====================== ======= ==========================
         Alignment Flag          Value  Description
         ====================== ======= ==========================
         ``BP_ALIGN_RIGHT``           1 Buttons are aligned on the right
         ``BP_ALIGN_LEFT``            2 Buttons are aligned on the left
         ``BP_ALIGN_TOP``             4 Buttons are aligned at the top
         ``BP_ALIGN_BOTTOM``          8 Buttons are aligned at the bottom
         ====================== ======= ==========================
        """

        if alignment == self._alignment:
            return

        self.Freeze()

        text = self.GetBarText()

        # Remove the text in any case
        self.RemoveText()

        # Remove the first and last spacers
        self._mainsizer.Remove(0, -1)
        self._mainsizer.Remove(len(self._mainsizer.GetChildren())-1, -1)

        self._alignment = alignment

        # Recreate the sizer accordingly to the new alignment
        self.ReCreateSizer(text)

[docs]    def IsVertical(self):
        """
        Returns whether L{ButtonPanel} is vertically aligned or not.

        :return: ``True`` if L{ButtonPanel} is vertically aligned, ``False`` otherwise.
        """

        return self._alignment not in [BP_ALIGN_RIGHT, BP_ALIGN_LEFT]

[docs]    def IsStandard(self):
        """
        Returns whether L{ButtonPanel} is aligned "Standard" (left/top) or not.

        :return: ``True`` if L{ButtonPanel} is aligned "standard", ``False`` otherwise.
        """

        return self._alignment in [BP_ALIGN_LEFT, BP_ALIGN_TOP]

[docs]    def DoLayout(self):
        """
        Do the Layout for L{ButtonPanel}.

        :note: Call this method every time you make a modification to the layout
         or to the customizable sizes of the pseudo controls.
        """

        margins = self._art.GetMetric(BP_MARGINS_SIZE)
        lenChildren = len(self._mainsizer.GetChildren())

        self._mainsizer.SetItemMinSize(0, (margins.x, margins.y))
        self._mainsizer.SetItemMinSize(lenChildren-1, (margins.x, margins.y))

        self._controlCreated = True
        self.LayoutItems()

        # *VERY* WEIRD: the sizer seems not to respond to any layout until I
        # change the ButtonPanel size and restore it back
        size = self.GetSize()
        self.SetSize((size.x+1, size.y+1))
        self.SetSize((size.x, size.y))

        if self.IsFrozen():
            self.Thaw()

[docs]    def ReCreateSizer(self, text=None):
        """
        Recreates the L{ButtonPanel} sizer accordingly to the alignment specified.

        :param string `text`: the text to display as main caption. If `text` is set to ``None``,
         the main caption will not be displayed.
        """

        children = self._mainsizer.GetChildren()
        self.RemoveAllButtons()
        self.RemoveAllSeparators()

        # Create a new sizer depending on the alignment chosen
        direction = (self.IsVertical() and [wx.VERTICAL] or [wx.HORIZONTAL])[0]
        self._mainsizer = BoxSizer(direction)

        margins = self._art.GetMetric(BP_MARGINS_SIZE)
        # First spacer to create some room before the first text/button/control
        self._mainsizer.Add((margins.x, margins.y), 0)

        # Last spacer to create some room before the last text/button/control
        self._mainsizer.Add((margins.x, margins.y), 0)

        # This is needed otherwise SetBarText goes mad
        self._controlCreated = False

        for child in children:
            userData = child.GetUserData()
            if userData:
                if isinstance(userData, ButtonInfo):
                    # It is a ButtonInfo, can't be anything else
                    self.AddButton(child.GetUserData())
                elif isinstance(userData, Separator):
                    self.AddSeparator()

            else:
                if child.IsSpacer():
                    # This is a spacer, expandable or not
                    self.AddSpacer(child.GetSize(), child.GetProportion(),
                                   child.GetFlag())
                else:
                    # This is a wxPython control
                    self.AddControl(child.GetWindow(), child.GetProportion(),
                                    child.GetFlag(), child.GetBorder())

        self.SetSizer(self._mainsizer)

        if text is not None:
            self.SetBarText(text)

        self.DoLayout()

        self.Thaw()

[docs]    def DoGetBestSize(self):
        """
        Gets the size which best suits L{ButtonPanel}: 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 `wx.Size`.

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

        w = h = btnWidth = btnHeight = 0
        isVertical = self.IsVertical()

        padding = self._art.GetMetric(BP_PADDING_SIZE)
        border = self._art.GetMetric(BP_BORDER_SIZE)
        margins = self._art.GetMetric(BP_MARGINS_SIZE)
        separator_size = self._art.GetMetric(BP_SEPARATOR_SIZE)

        # Add the space required for the main caption
        if self.HasBarText():
            w, h = self._text.GetBestSize()
            if isVertical:
                h += padding.y
            else:
                w += padding.x
        else:
            w = h = border

        # Add the button's sizes
        for btn in self._vButtons:

            bw, bh = btn.GetBestSize()
            btnWidth = max(btnWidth, bw)
            btnHeight = max(btnHeight, bh)

            if isVertical:
                w = max(w, btnWidth)
                h += bh
            else:
                h = max(h, btnHeight)
                w += bw

        # Add the control's sizes
        for control in self.GetControls():
            cw, ch = control.GetSize()
            if isVertical:
                h += ch
                w = max(w, cw)
            else:
                w += cw
                h = max(h, ch)

        # Add the separator's sizes and the 2 SizerItems at the beginning
        # and at the end
        if self.IsVertical():
            h += 2*margins.y + len(self._vSeparators)*separator_size
        else:
            w += 2*margins.x + len(self._vSeparators)*separator_size

        return wx.Size(w, h)

[docs]    def OnPaint(self, event):
        """
        Handles the ``wx.EVT_PAINT`` event for L{ButtonPanel}.

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

        dc = wx.BufferedPaintDC(self)
        rect = self.GetClientRect()

        self._art.DrawButtonPanel(dc, rect, self._agwStyle)
        self._mainsizer.Draw(dc)

[docs]    def OnEraseBackground(self, event):
        """
        Handles the ``wx.EVT_ERASE_BACKGROUND`` event for L{ButtonPanel}.

        :param `event`: a `wx.EraseEvent` event to be processed.

        :note: This is intentionally empty to reduce flicker.
        """

        pass

[docs]    def OnSize(self, event):
        """
        Handles the ``wx.EVT_SIZE`` event for L{ButtonPanel}.

        :param `event`: a `wx.SizeEvent` event to be processed.

        :todo: Improve the chain of methods L{OnSize} ==> L{DoLayout} ==> L{LayoutItems}
         to avoid multiple calls to L{LayoutItems}.
        """

        # NOTE: It seems like LayoutItems number of calls can be optimized in some way.
        # Currently every DoLayout (or every parent Layout()) calls about 3 times
        # the LayoutItems method. Any idea on how to improve it?
        self.LayoutItems()
        self.Refresh()

        event.Skip()

[docs]    def LayoutItems(self):
        """
        Layout the items using a different algorithms depending on the existance
        of the main caption.
        """

        nonspacers, allchildren = self.GetNonFlexibleChildren()

        if self.HasBarText():
            self.FlexibleLayout(nonspacers, allchildren)
        else:
            self.SizeLayout(nonspacers, allchildren)

        self._mainsizer.Layout()

[docs]    def SizeLayout(self, nonspacers, children):
        """
        Layout the items when no main caption exists.

        :param list `nonspacers`: a list of items which are not spacers;
        :param list `children`: a list of all the children of L{ButtonPanel}.
        """

        size = self.GetSize()
        isVertical = self.IsVertical()

        corner = 0
        indx1 = len(nonspacers)

        for item in nonspacers:
            corner += self.GetItemSize(item, isVertical)
            if corner > size[isVertical]:
                indx1 = nonspacers.index(item)
                break

        # Leave out the last spacer, it has to be there always
        for ii in xrange(len(nonspacers)-1):
            indx = children.index(nonspacers[ii])
            self._mainsizer.Show(indx, ii < indx1)

[docs]    def GetItemSize(self, item, isVertical):
        """
        Returns the size of an item in the main L{ButtonPanel} sizer.

        :param `item`: an instance of L{ButtonInfo};
        :param bool `isVertical`: ``True`` if L{ButtonPanel} is in vertical orientation,
         ``False`` otherwise.

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

        if item.GetUserData():
            return item.GetUserData().GetBestSize()[isVertical]
        else:
            return item.GetSize()[isVertical]

[docs]    def FlexibleLayout(self, nonspacers, allchildren):
        """
        Layout the items when the main caption exists.

        :param list `nonspacers`: a list of items which are not spacers;
        :param list `allchildren`: a list of all the children of L{ButtonPanel}.
        """

        if len(nonspacers) < 2:
            return

        isVertical = self.IsVertical()
        isStandard = self.IsStandard()

        size = self.GetSize()[isVertical]
        padding = self._art.GetMetric(BP_PADDING_SIZE)

        fixed = (isStandard and [nonspacers[1]] or [nonspacers[-2]])[0]

        if isStandard:
            nonspacers.reverse()
            leftendx = fixed.GetSize()[isVertical] + padding.x
        else:
            rightstartx = size - fixed.GetSize()[isVertical]
            size = 0

        count = lennonspacers = len(nonspacers)

        for item in nonspacers:
            if isStandard:
                size -= self.GetItemSize(item, isVertical)
                if size < leftendx:
                    break
            else:
                size += self.GetItemSize(item, isVertical)
                if size > rightstartx:
                    break

            count = count - 1

        nonspacers.reverse()

        for jj in xrange(2, lennonspacers):
            indx = allchildren.index(nonspacers[jj])
            self._mainsizer.Show(indx, jj >= count)

[docs]    def GetNonFlexibleChildren(self):
        """
        Returns all the L{ButtonPanel} main sizer's children that are not
        flexible spacers.

        :return: A list of items inside L{ButtonPanel} that are not flexible spacers.
        """

        children1 = []
        children2 = list(self._mainsizer.GetChildren())

        for child in children2:
            if child.IsSpacer():
                if child.GetUserData() or child.GetProportion() == 0:
                    children1.append(child)
            else:
                children1.append(child)

        return children1, children2

[docs]    def GetControls(self):
        """
        Returns the wxPython controls that belongs to L{ButtonPanel}.

        :return: A list of items inside L{ButtonPanel} that are wxPython controls.
        """

        children2 = self._mainsizer.GetChildren()
        children1 = [child for child in children2 if not child.IsSpacer()]

        return children1

[docs]    def SetStyle(self, agwStyle):
        """
        Sets the L{ButtonPanel} window style.

        :param integer `agwStyle`: one of the following bits:

         ==================== =========== ==================================================
         Window Styles        Hex Value   Description
         ==================== =========== ==================================================
         ``BP_DEFAULT_STYLE``         0x1 L{ButtonPanel} has a plain solid background.
         ``BP_USE_GRADIENT``          0x2 L{ButtonPanel} has a gradient shading background.
         ==================== =========== ==================================================

        """

        if agwStyle == self._agwStyle:
            return

        self._agwStyle = agwStyle
        self.Refresh()

[docs]    def GetStyle(self):
        """
        Returns the L{ButtonPanel} window style.

        :see: L{SetStyle} for a list of valid window styles.
        """

        return self._agwStyle

[docs]    def OnMouseMove(self, event):
        """
        Handles the ``wx.EVT_MOTION`` event for L{ButtonPanel}.

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

        # Check to see if we are hovering a button
        tabId, flags = self.HitTest(event.GetPosition())

        if flags != BP_HT_BUTTON:
            self.RemoveHelp()
            self.RepaintOldSelection()
            self._currentButton = -1
            return

        btn = self._vButtons[tabId]

        if not btn.IsEnabled():
            self.RemoveHelp()
            self.RepaintOldSelection()
            return

        if tabId != self._currentButton:
            self.RepaintOldSelection()

        if btn.GetRect().Contains(event.GetPosition()):
            if btn.GetStatus() != "Pressed":
                btn.SetStatus("Hover")
        else:
            btn.SetStatus("Normal")

        if tabId != self._currentButton:
            self.RemoveHelp()
            self.DoGiveHelp(btn)

        self._currentButton = tabId

        event.Skip()

[docs]    def OnLeftDown(self, event):
        """
        Handles the ``wx.EVT_LEFT_DOWN`` event for L{ButtonPanel}.

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

        tabId, hit = self.HitTest(event.GetPosition())

        if hit == BP_HT_BUTTON:
            btn = self._vButtons[tabId]
            if btn.IsEnabled():
                btn.SetStatus("Pressed")
                self._currentButton = tabId

[docs]    def OnLeftUp(self, event):
        """
        Handles the ``wx.EVT_LEFT_UP`` event for L{ButtonPanel}.

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

        tabId, flags = self.HitTest(event.GetPosition())

        if flags != BP_HT_BUTTON:
            return

        hit = self._vButtons[tabId]

        if hit.GetStatus() == "Disabled":
            return

        for btn in self._vButtons:
            if btn != hit:
                btn.SetFocus(False)

        if hit.GetStatus() == "Pressed":
            hit.SetToggled(not hit.GetToggled())

            # Update the button status to be hovered
            hit.SetStatus("Hover")
            hit.SetFocus()
            self._currentButton = tabId

            # Fire a button click event
            btnEvent = wx.CommandEvent(wx.wxEVT_COMMAND_BUTTON_CLICKED, hit.GetId())
            btnEvent.SetEventObject(hit)
            self.GetEventHandler().ProcessEvent(btnEvent)

[docs]    def OnMouseLeave(self, event):
        """
        Handles the ``wx.EVT_LEAVE_WINDOW`` event for L{ButtonPanel}.

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

        # Reset all buttons statuses
        for btn in self._vButtons:
            if not btn.IsEnabled():
                continue
            btn.SetStatus("Normal")

        self.RemoveHelp()

        event.Skip()

[docs]    def OnMouseEnterWindow(self, event):
        """
        Handles the ``wx.EVT_ENTER_WINDOW`` event for L{ButtonPanel}.

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

        tabId, flags = self.HitTest(event.GetPosition())

        if flags == BP_HT_BUTTON:

            hit = self._vButtons[tabId]

            if hit.GetStatus() == "Disabled":
                event.Skip()
                return

            self.DoGiveHelp(hit)
            self._currentButton = tabId

        event.Skip()

[docs]    def DoGiveHelp(self, hit):
        """
        Shows tooltips and long help strings in `wx.StatusBar`.

        :param `hit`: an instance of L{ButtonInfo} where the mouse is hovering.
        """

        if not self.GetUseHelp():
            return

        shortHelp = hit.GetShortHelp()
        if shortHelp:
            self.SetToolTipString(shortHelp)
            self._haveTip = True

        longHelp = hit.GetLongHelp()
        if not longHelp:
            return

        topLevel = wx.GetTopLevelParent(self)

        if isinstance(topLevel, wx.Frame) and topLevel.GetStatusBar():
            statusBar = topLevel.GetStatusBar()

            if self._statusTimer and self._statusTimer.IsRunning():
                self._statusTimer.Stop()
                statusBar.PopStatusText(0)

            statusBar.PushStatusText(longHelp, 0)
            self._statusTimer = StatusBarTimer(self)
            self._statusTimer.Start(_DELAY, wx.TIMER_ONE_SHOT)

[docs]    def RemoveHelp(self):
        """ Removes the tooltips and statusbar help (if any) for a button. """

        if not self.GetUseHelp():
            return

        if self._haveTip:
            self.SetToolTipString("")
            self._haveTip = False

        if self._statusTimer and self._statusTimer.IsRunning():
            topLevel = wx.GetTopLevelParent(self)
            statusBar = topLevel.GetStatusBar()
            self._statusTimer.Stop()
            statusBar.PopStatusText(0)
            self._statusTimer = None

[docs]    def RepaintOldSelection(self):
        """ Repaints the old selected/hovered button. """

        current = self._currentButton

        if current == -1:
            return

        btn = self._vButtons[current]
        if not btn.IsEnabled():
            return

        btn.SetStatus("Normal")

[docs]    def OnStatusBarTimer(self):
        """ Handles the timer expiring to delete the long help string in `wx.StatusBar`. """

        topLevel = wx.GetTopLevelParent(self)
        statusBar = topLevel.GetStatusBar()
        statusBar.PopStatusText(0)

[docs]    def SetUseHelp(self, useHelp=True):
        """
        Sets whether or not short and long help strings should be displayed as tooltips
        and `wx.StatusBar` items respectively.

        :param bool `useHelp`: ``True`` to display short and long help strings as tooltips
         and `wx.StatusBar` items respectively, ``False`` otherwise.
        """

        self._useHelp = useHelp

[docs]    def GetUseHelp(self):
        """
        Returns whether or not short and long help strings should be displayed as tooltips
        and `wx.StatusBar` items respectively.

        :return: ``True`` if the short and long help strings should be displayed as tooltips
         and `wx.StatusBar` items respectively, ``False`` otherwise.
        """

        return self._useHelp

[docs]    def HitTest(self, pt):
        """
        HitTest method for L{ButtonPanel}.

        :param `pt`: the mouse position, an instance of `wx.Point`.

        :returns: an instance of L{ButtonInfo} and the hit flag ``BP_HT_BUTTON`` if a button
         client rectangle contains the input point `pt`, or ``wx.NOT_FOUND`` and ``BP_HT_NONE``.
        """

        for ii in xrange(len(self._vButtons)):
            if not self._vButtons[ii].IsEnabled():
                continue
            if self._vButtons[ii].GetRect().Contains(pt):
                return ii, BP_HT_BUTTON

        return wx.NOT_FOUND, BP_HT_NONE

[docs]    def GetBPArt(self):
        """ Returns the associated L{BPArt} art provider. """

        return self._art

[docs]    def SetBPArt(self, art):
        """
        Sets a new L{BPArt} art provider to L{ButtonPanel}.

        :param `art`: an instance of L{BPArt}.
        """

        self._art = art
        self.Refresh()

    if wx.VERSION < (2,7,1,1):
        def Freeze(self):
            """
            Freezes the window or, in other words, prevents any updates from taking place
            on screen, the window is not redrawn at all. L{Thaw} must be called to reenable
            window redrawing. Calls to these two functions may be nested.

            :note: This method is useful for visual appearance optimization.
            """

            self._freezeCount = self._freezeCount + 1
            wx.PyPanel.Freeze(self)

        def Thaw(self):
            """
            Reenables window updating after a previous call to L{Freeze}. To really thaw the
            control, it must be called exactly the same number of times as L{Freeze}.
            """

            if self._freezeCount == 0:
                raise Exception("\nERROR: Thawing Unfrozen ButtonPanel?")

            self._freezeCount = self._freezeCount - 1
            wx.PyPanel.Thaw(self)

        def IsFrozen(self):
            """ Returns ``True`` if the window is currently frozen by a call to L{Freeze}. """

            return self._freezeCount != 0

Navigation

  • index
  • modules |
  • Home |
  • Gallery |
  • Contents»
  • Module code »
  • buttonpanel


cubecolourdialog

  • modules |
  • Home |
  • Gallery |
  • Contents»
  • Module code »
  • cubecolourdialog

Source code for cubecolourdialog

# --------------------------------------------------------------------------- #
# CUBECOLOURDIALOG Widget wxPython IMPLEMENTATION
#
# Python Code By:
#
# Andrea Gavana, @ 16 Aug 2007
# Latest Revision: 26 Feb 2012, 15.00 GMT
#
#
# TODO List
#
# 1. Find A Way To Reduce Flickering On The 2 ColourPanels;
#
# 2. See Why wx.GCDC Doesn't Work As I Thought (!). It Looks Slow As A Turtle,
#    But Probably I Am Doing Something Wrong While Painting The Alpha Textures.
#
#
# 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
# --------------------------------------------------------------------------- #

"""
L{CubeColourDialog} is an alternative implementation of `wx.ColourDialog`.

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

The L{CubeColourDialog} is an alternative implementation of `wx.ColourDialog`, and it
offers different functionalities with respect to the default wxPython one. It
can be used as a replacement of `wx.ColourDialog` with exactly the same syntax and
methods.

Some features:

- RGB components may be controlled using spin controls or with mouse gestures
  on a 3D RGB cube, with the 3 components laying on the X, Y, Z axes;
- HSB components may be controlled using spin controls or with mouse gestures
  on a 2D colour wheel;
- Brightness has its own vertical slider to play with;
- The colour alpha channel can be controlled using another vertical slider, or
  via spin control;
- The colour alpha channel controls can be completely hidden at startup or the
  choice to use the alpha channel can be left to the user while playing with the
  dialog, via a simple `wx.CheckBox`;
- The "old colour" and "new colour" are displayed in two small custom panel,
  which support alpha transparency and texture;
- L{CubeColourDialog} displays also the HTML colour code in hexadecimal format;
- When available, a corresponding "Web Safe" colour is generated using a 500
  web colours "database" (a dictionary inside the widget source code). Web Safe
  colours are recognized by all the browsers;
- When available, a corresponding "HTML name" for the selected colour is displayed,
  by using the same 500 web colours "database";
- When available, a corresponding "Microsoft Access Code" for the selected colour
  is displayed, by using the same 500 web colours "database".

And much more.

Usage
=====

Usage example::

    import wx
    import wx.lib.agw.cubecolourdialog as CCD

    # Our normal wxApp-derived class, as usual
    app = wx.App(0)

    colourData = wx.ColourData()
    dlg = CCD.CubeColourDialog(None, colourData)

    if dlg.ShowModal() == wx.ID_OK:

        # If the user selected OK, then the dialog's wx.ColourData will
        # contain valid information. Fetch the data ...
        colourData = dlg.GetColourData()
        h, s, v, a = dlg.GetHSVAColour()

        # ... then do something with it. The actual colour data will be
        # returned as a three-tuple (r, g, b) in this particular case.
        colour = colourData.GetColour()
        r, g, b, alpha = colour.Red(), colour.Green(), colour.Blue(), colour.Alpha()
        print "You selected (RGBA): %d, %d, %d, %d"%(r, g, b, alpha)
        print "You selected (HSVA): %d, %d, %d, %d"%(h, s, v, a)

    # Once the dialog is destroyed, Mr. wx.ColourData is no longer your
    # friend. Don't use it again!
    dlg.Destroy()

    app.MainLoop()

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

This class supports the following window styles:

================== =========== ==================================================
Window Styles      Hex Value   Description
================== =========== ==================================================
``CCD_SHOW_ALPHA``         0x1 Show the widget used to control colour alpha channels in L{CubeColourDialog}.
================== =========== ==================================================

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

`No custom events are available for this class.`

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

L{CubeColourDialog} is distributed under the wxPython license.

Latest Revision: Andrea Gavana @ 26 Feb 2012, 15.00 GMT

Version 0.4.

"""

__docformat__ = "epytext"

#----------------------------------------------------------------------
# Beginning Of CUBECOLOURDIALOG wxPython Code
#----------------------------------------------------------------------

import wx
import colorsys

from math import pi, sin, cos, sqrt, atan2

from wx.lib.embeddedimage import PyEmbeddedImage

# Define a translation string
_ = wx.GetTranslation

# Show the alpha control in the dialog
CCD_SHOW_ALPHA = 1
""" Show the widget used to control colour alpha channels in L{CubeColourDialog}. """

# Radius of the HSB colour wheel
RADIUS = 100
""" Radius of the HSB colour wheel. """

# Width of the mouse-controlled colour pointer
RECT_WIDTH = 5
""" Width of the mouse-controlled colour pointer. """

# Dictionary keys for the RGB colour cube
RED, GREEN, BLUE = 0, 1, 2
""" Dictionary keys for the RGB colour cube. """

Vertex = wx.Point(95, 109)
Top = wx.Point(95, 10)
Left = wx.Point(16, 148)
Right = wx.Point(174, 148)

colourAttributes = ["r", "g", "b", "h", "s", "v"]
colourMaxValues = [255, 255, 255, 359, 255, 255]
checkColour = wx.Colour(200, 200, 200)

HTMLCodes = {'#B0171F': ['Indian red', '2037680', ''],
             '#DC143C': ['Crimson', '3937500', '#CC0033'],
             '#FFB6C1': ['Lightpink', '12695295', '#FFCCCC'],
             '#FFAEB9': ['Lightpink 1', '12168959', ''],
             '#EEA2AD': ['Lightpink 2', '11379438', ''],
             '#CD8C95': ['Lightpink 3', '9800909', ''],
             '#8B5F65': ['Lightpink 4', '6643595', ''],
             '#FFC0CB': ['Pink', '13353215', '#FFCCCC'],
             '#FFB5C5': ['Pink 1', '12957183', ''],
             '#EEA9B8': ['Pink 2', '12102126', ''],
             '#CD919E': ['Pink 3', '10392013', ''],
             '#8B636C': ['Pink 4', '7103371', ''],
             '#DB7093': ['Palevioletred', '9662683', '#CC6699'],
             '#FF82AB': ['Palevioletred 1', '11240191', ''],
             '#EE799F': ['Palevioletred 2', '10451438', ''],
             '#CD6889': ['Palevioletred 3', '9005261', ''],
             '#8B475D': ['Palevioletred 4', '6113163', ''],
             '#FFF0F5': ['Lavenderblush 1 (lavenderblush)', '16118015', '#FFFFFF'],
             '#EEE0E5': ['Lavenderblush 2', '15065326', ''],
             '#CDC1C5': ['Lavenderblush 3', '12960205', ''],
             '#8B8386': ['Lavenderblush 4', '8815499', ''],
             '#FF3E96': ['Violetred 1', '9846527', ''],
             '#EE3A8C': ['Violetred 2', '9190126', ''],
             '#CD3278': ['Violetred 3', '7877325', ''],
             '#8B2252': ['Violetred 4', '5382795', ''],
             '#FF69B4': ['Hotpink', '11823615', '#FF66CC'],
             '#FF6EB4': ['Hotpink 1', '11824895', ''],
             '#EE6AA7': ['Hotpink 2', '10971886', ''],
             '#CD6090': ['Hotpink 3', '9461965', ''],
             '#8B3A62': ['Hotpink 4', '6437515', ''],
             '#872657': ['Raspberry', '5711495', ''],
             '#FF1493': ['Deeppink 1 (deeppink)', '9639167', '#FF0099'],
             '#EE1289': ['Deeppink 2', '8983278', ''],
             '#CD1076': ['Deeppink 3', '7737549', ''],
             '#8B0A50': ['Deeppink 4', '5245579', ''],
             '#FF34B3': ['Maroon 1', '11744511', ''],
             '#EE30A7': ['Maroon 2', '10957038', ''],
             '#CD2990': ['Maroon 3', '9447885', ''],
             '#8B1C62': ['Maroon 4', '6429835', ''],
             '#C71585': ['Mediumvioletred', '8721863', '#CC0066'],
             '#D02090': ['Violetred', '9445584', ''],
             '#DA70D6': ['Orchid', '14053594', '#CC66CC'],
             '#FF83FA': ['Orchid 1', '16417791', ''],
             '#EE7AE9': ['Orchid 2', '15301358', ''],
             '#CD69C9': ['Orchid 3', '13199821', ''],
             '#8B4789': ['Orchid 4', '8996747', ''],
             '#D8BFD8': ['Thistle', '14204888', '#CCCCCC'],
             '#FFE1FF': ['Thistle 1', '16769535', ''],
             '#EED2EE': ['Thistle 2', '15651566', ''],
             '#CDB5CD': ['Thistle 3', '13481421', ''],
             '#8B7B8B': ['Thistle 4', '9141131', ''],
             '#FFBBFF': ['Plum 1', '16759807', ''],
             '#EEAEEE': ['Plum 2', '15642350', ''],
             '#CD96CD': ['Plum 3', '13473485', ''],
             '#8B668B': ['Plum 4', '9135755', ''],
             '#DDA0DD': ['Plum', '14524637', '#CC99CC'],
             '#EE82EE': ['Violet', '15631086', '#FF99FF'],
             '#FF00FF': ['Magenta (fuchsia)', '16711935', '#FF00FF'],
             '#EE00EE': ['Magenta 2', '15597806', ''],
             '#CD00CD': ['Magenta 3', '13435085', ''],
             '#8B008B': ['Magenta 4 (darkmagenta)', '9109643', '#990099'],
             '#800080': ['Purple', '8388736', '#990099'],
             '#BA55D3': ['Mediumorchid', '13850042', '#CC66CC'],
             '#E066FF': ['Mediumorchid 1', '16738016', ''],
             '#D15FEE': ['Mediumorchid 2', '15622097', ''],
             '#B452CD': ['Mediumorchid 3', '13456052', ''],
             '#7A378B': ['Mediumorchid 4', '9123706', ''],
             '#9400D3': ['Darkviolet', '13828244', '#9900CC'],
             '#9932CC': ['Darkorchid', '13382297', '#9933CC'],
             '#BF3EFF': ['Darkorchid 1', '16727743', ''],
             '#B23AEE': ['Darkorchid 2', '15612594', ''],
             '#9A32CD': ['Darkorchid 3', '13447834', ''],
             '#68228B': ['Darkorchid 4', '9118312', ''],
             '#4B0082': ['Indigo', '8519755', '#330099'],
             '#8A2BE2': ['Blueviolet', '14822282', '#9933FF'],
             '#9B30FF': ['Purple 1', '16724123', ''],
             '#912CEE': ['Purple 2', '15608977', ''],
             '#7D26CD': ['Purple 3', '13444733', ''],
             '#551A8B': ['Purple 4', '9116245', ''],
             '#9370DB': ['Mediumpurple', '14381203', '#9966CC'],
             '#AB82FF': ['Mediumpurple 1', '16745131', ''],
             '#9F79EE': ['Mediumpurple 2', '15628703', ''],
             '#8968CD': ['Mediumpurple 3', '13461641', ''],
             '#5D478B': ['Mediumpurple 4', '9127773', ''],
             '#483D8B': ['Darkslateblue', '9125192', '#333399'],
             '#8470FF': ['Lightslateblue', '16740484', ''],
             '#7B68EE': ['Mediumslateblue', '15624315', '#6666FF'],
             '#6A5ACD': ['Slateblue', '13458026', '#6666CC'],
             '#836FFF': ['Slateblue 1', '16740227', ''],
             '#7A67EE': ['Slateblue 2', '15624058', ''],
             '#6959CD': ['Slateblue 3', '13457769', ''],
             '#473C8B': ['Slateblue 4', '9124935', ''],
             '#F8F8FF': ['Ghostwhite', '16775416', '#FFFFFF'],
             '#E6E6FA': ['Lavender', '16443110', '#FFFFFF'],
             '#0000FF': ['Blue', '16711680', '#0000FF'],
             '#0000EE': ['Blue 2', '15597568', ''],
             '#0000CD': ['Blue 3 (mediumblue)', '13434880', '#0000CC'],
             '#00008B': ['Blue 4 (darkblue)', '9109504', '#000099'],
             '#000080': ['Navy', '8388608', '#000099'],
             '#191970': ['Midnightblue', '7346457', '#000066'],
             '#3D59AB': ['Cobalt', '11229501', ''],
             '#4169E1': ['Royalblue', '14772545', '#3366CC'],
             '#4876FF': ['Royalblue 1', '16741960', ''],
             '#436EEE': ['Royalblue 2', '15625795', ''],
             '#3A5FCD': ['Royalblue 3', '13459258', ''],
             '#27408B': ['Royalblue 4', '9125927', ''],
             '#6495ED': ['Cornflowerblue', '15570276', '#6699FF'],
             '#B0C4DE': ['Lightsteelblue', '14599344', '#99CCCC'],
             '#CAE1FF': ['Lightsteelblue 1', '16769482', ''],
             '#BCD2EE': ['Lightsteelblue 2', '15651516', ''],
             '#A2B5CD': ['Lightsteelblue 3', '13481378', ''],
             '#6E7B8B': ['Lightsteelblue 4', '9141102', ''],
             '#778899': ['Lightslategray', '10061943', '#669999'],
             '#708090': ['Slategray', '9470064', '#669999'],
             '#C6E2FF': ['Slategray 1', '16769734', ''],
             '#B9D3EE': ['Slategray 2', '15651769', ''],
             '#9FB6CD': ['Slategray 3', '13481631', ''],
             '#6C7B8B': ['Slategray 4', '9141100', ''],
             '#1E90FF': ['Dodgerblue 1 (dodgerblue)', '16748574', '#3399FF'],
             '#1C86EE': ['Dodgerblue 2', '15631900', ''],
             '#1874CD': ['Dodgerblue 3', '13464600', ''],
             '#104E8B': ['Dodgerblue 4', '9129488', ''],
             '#F0F8FF': ['Aliceblue', '16775408', '#FFFFFF'],
             '#4682B4': ['Steelblue', '11829830', '#3399CC'],
             '#63B8FF': ['Steelblue 1', '16758883', ''],
             '#5CACEE': ['Steelblue 2', '15641692', ''],
             '#4F94CD': ['Steelblue 3', '13472847', ''],
             '#36648B': ['Steelblue 4', '9135158', ''],
             '#87CEFA': ['Lightskyblue', '16436871', '#99CCFF'],
             '#B0E2FF': ['Lightskyblue 1', '16769712', ''],
             '#A4D3EE': ['Lightskyblue 2', '15651748', ''],
             '#8DB6CD': ['Lightskyblue 3', '13481613', ''],
             '#607B8B': ['Lightskyblue 4', '9141088', ''],
             '#87CEFF': ['Skyblue 1', '16764551', ''],
             '#7EC0EE': ['Skyblue 2', '15646846', ''],
             '#6CA6CD': ['Skyblue 3', '13477484', ''],
             '#4A708B': ['Skyblue 4', '9138250', ''],
             '#87CEEB': ['Skyblue', '15453831', '#99CCFF'],
             '#00BFFF': ['Deepskyblue 1 (deepskyblue)', '16760576', '#00CCFF'],
             '#00B2EE': ['Deepskyblue 2', '15643136', ''],
             '#009ACD': ['Deepskyblue 3', '13474304', ''],
             '#00688B': ['Deepskyblue 4', '9136128', ''],
             '#33A1C9': ['Peacock', '13214003', ''],
             '#ADD8E6': ['Lightblue', '15128749', '#99CCFF'],
             '#BFEFFF': ['Lightblue 1', '16773055', ''],
             '#B2DFEE': ['Lightblue 2', '15654834', ''],
             '#9AC0CD': ['Lightblue 3', '13484186', ''],
             '#68838B': ['Lightblue 4', '9143144', ''],
             '#B0E0E6': ['Powderblue', '15130800', '#CCCCFF'],
             '#98F5FF': ['Cadetblue 1', '16774552', ''],
             '#8EE5EE': ['Cadetblue 2', '15656334', ''],
             '#7AC5CD': ['Cadetblue 3', '13485434', ''],
             '#53868B': ['Cadetblue 4', '9143891', ''],
             '#00F5FF': ['Turquoise 1', '16774400', ''],
             '#00E5EE': ['Turquoise 2', '15656192', ''],
             '#00C5CD': ['Turquoise 3', '13485312', ''],
             '#00868B': ['Turquoise 4', '9143808', ''],
             '#5F9EA0': ['Cadetblue', '10526303', '#669999'],
             '#00CED1': ['Darkturquoise', '13749760', '#00CCCC'],
             '#F0FFFF': ['Azure 1 (azure)', '16777200', '#FFFFFF'],
             '#E0EEEE': ['Azure 2', '15658720', ''],
             '#C1CDCD': ['Azure 3', '13487553', ''],
             '#838B8B': ['Azure 4', '9145219', ''],
             '#E0FFFF': ['Lightcyan 1 (lightcyan)', '16777184', '#CCFFFF'],
             '#D1EEEE': ['Lightcyan 2', '15658705', ''],
             '#B4CDCD': ['Lightcyan 3', '13487540', ''],
             '#7A8B8B': ['Lightcyan 4', '9145210', ''],
             '#BBFFFF': ['Paleturquoise 1', '16777147', ''],
             '#AEEEEE': ['Paleturquoise 2 (paleturquoise)', '15658670', ''],
             '#96CDCD': ['Paleturquoise 3', '13487510', ''],
             '#668B8B': ['Paleturquoise 4', '9145190', ''],
             '#2F4F4F': ['Darkslategray', '5197615', '#336666'],
             '#97FFFF': ['Darkslategray 1', '16777111', ''],
             '#8DEEEE': ['Darkslategray 2', '15658637', ''],
             '#79CDCD': ['Darkslategray 3', '13487481', ''],
             '#528B8B': ['Darkslategray 4', '9145170', ''],
             '#00FFFF': ['Cyan / aqua', '16776960', '#00FFFF'],
             '#00EEEE': ['Cyan 2', '15658496', ''],
             '#00CDCD': ['Cyan 3', '13487360', ''],
             '#008B8B': ['Cyan 4 (darkcyan)', '9145088', '#009999'],
             '#008080': ['Teal', '8421376', '#009999'],
             '#48D1CC': ['Mediumturquoise', '13422920', '#33CCCC'],
             '#20B2AA': ['Lightseagreen', '11186720', '#339999'],
             '#03A89E': ['Manganeseblue', '10397699', ''],
             '#40E0D0': ['Turquoise', '13688896', '#33CCCC'],
             '#808A87': ['Coldgrey', '8882816', ''],
             '#00C78C': ['Turquoiseblue', '9225984', ''],
             '#7FFFD4': ['Aquamarine 1 (aquamarine)', '13959039', '#66FFCC'],
             '#76EEC6': ['Aquamarine 2', '13037174', ''],
             '#66CDAA': ['Aquamarine 3 (mediumaquamarine)', '11193702', '#66CC99'],
             '#458B74': ['Aquamarine 4', '7637829', ''],
             '#00FA9A': ['Mediumspringgreen', '10156544', '#00FF99'],
             '#F5FFFA': ['Mintcream', '16449525', '#FFFFFF'],
             '#00FF7F': ['Springgreen', '8388352', '#00FF66'],
             '#00EE76': ['Springgreen 1', '7794176', ''],
             '#00CD66': ['Springgreen 2', '6737152', ''],
             '#008B45': ['Springgreen 3', '4557568', ''],
             '#3CB371': ['Mediumseagreen', '7451452', '#33CC66'],
             '#54FF9F': ['Seagreen 1', '10485588', ''],
             '#4EEE94': ['Seagreen 2', '9760334', ''],
             '#43CD80': ['Seagreen 3', '8441155', ''],
             '#2E8B57': ['Seagreen 4 (seagreen)', '5737262', '#339966'],
             '#00C957': ['Emeraldgreen', '5753088', ''],
             '#BDFCC9': ['Mint', '13237437', ''],
             '#3D9140': ['Cobaltgreen', '4231485', ''],
             '#F0FFF0': ['Honeydew 1 (honeydew)', '15794160', '#FFFFFF'],
             '#E0EEE0': ['Honeydew 2', '14741216', ''],
             '#C1CDC1': ['Honeydew 3', '12701121', ''],
             '#838B83': ['Honeydew 4', '8620931', ''],
             '#8FBC8F': ['Darkseagreen', '9419919', '#99CC99'],
             '#C1FFC1': ['Darkseagreen 1', '12713921', ''],
             '#B4EEB4': ['Darkseagreen 2', '11857588', ''],
             '#9BCD9B': ['Darkseagreen 3', '10210715', ''],
             '#698B69': ['Darkseagreen 4', '6916969', ''],
             '#98FB98': ['Palegreen', '10025880', '#99FF99'],
             '#9AFF9A': ['Palegreen 1', '10157978', ''],
             '#90EE90': ['Palegreen 2 (lightgreen)', '9498256', '#99FF99'],
             '#7CCD7C': ['Palegreen 3', '8179068', ''],
             '#548B54': ['Palegreen 4', '5540692', ''],
             '#32CD32': ['Limegreen', '3329330', '#33CC33'],
             '#228B22': ['Forestgreen', '2263842', '#339933'],
             '#00FF00': ['Green 1 (lime)', '65280', '#00FF00'],
             '#00EE00': ['Green 2', '60928', ''],
             '#00CD00': ['Green 3', '52480', ''],
             '#008B00': ['Green 4', '35584', ''],
             '#008000': ['Green', '32768', '#009900'],
             '#006400': ['Darkgreen', '25600', '#006600'],
             '#308014': ['Sapgreen', '1343536', ''],
             '#7CFC00': ['Lawngreen', '64636', '#66FF00'],
             '#7FFF00': ['Chartreuse 1 (chartreuse)', '65407', '#66FF00'],
             '#76EE00': ['Chartreuse 2', '61046', ''],
             '#66CD00': ['Chartreuse 3', '52582', ''],
             '#458B00': ['Chartreuse 4', '35653', ''],
             '#ADFF2F': ['Greenyellow', '3145645', '#99FF33'],
             '#CAFF70': ['Darkolivegreen 1', '7405514', ''],
             '#BCEE68': ['Darkolivegreen 2', '6876860', ''],
             '#A2CD5A': ['Darkolivegreen 3', '5950882', ''],
             '#6E8B3D': ['Darkolivegreen 4', '4033390', ''],
             '#556B2F': ['Darkolivegreen', '3107669', '#666633'],
             '#6B8E23': ['Olivedrab', '2330219', '#669933'],
             '#C0FF3E': ['Olivedrab 1', '4128704', ''],
             '#B3EE3A': ['Olivedrab 2', '3862195', ''],
             '#9ACD32': ['Olivedrab 3 (yellowgreen)', '3329434', '#99CC33'],
             '#698B22': ['Olivedrab 4', '2263913', ''],
             '#FFFFF0': ['Ivory 1 (ivory)', '15794175', '#FFFFFF'],
             '#EEEEE0': ['Ivory 2', '14741230', ''],
             '#CDCDC1': ['Ivory 3', '12701133', ''],
             '#8B8B83': ['Ivory 4', '8620939', ''],
             '#F5F5DC': ['Beige', '14480885', '#FFFFCC'],
             '#FFFFE0': ['Lightyellow 1 (lightyellow)', '14745599', '#FFFFFF'],
             '#EEEED1': ['Lightyellow 2', '13758190', ''],
             '#CDCDB4': ['Lightyellow 3', '11849165', ''],
             '#8B8B7A': ['Lightyellow 4', '8031115', ''],
             '#FAFAD2': ['Lightgoldenrodyellow', '13826810', '#FFFFCC'],
             '#FFFF00': ['Yellow 1 (yellow)', '65535', '#FFFF00'],
             '#EEEE00': ['Yellow 2', '61166', ''],
             '#CDCD00': ['Yellow 3', '52685', ''],
             '#8B8B00': ['Yellow 4', '35723', ''],
             '#808069': ['Warmgrey', '6914176', ''],
             '#808000': ['Olive', '32896', '#999900'],
             '#BDB76B': ['Darkkhaki', '7059389', '#CCCC66'],
             '#FFF68F': ['Khaki 1', '9434879', ''],
             '#EEE685': ['Khaki 2', '8775406', ''],
             '#CDC673': ['Khaki 3', '7587533', ''],
             '#8B864E': ['Khaki 4', '5146251', ''],
             '#F0E68C': ['Khaki', '9234160', ''],
             '#EEE8AA': ['Palegoldenrod', '11200750', '#FFFF99'],
             '#FFFACD': ['Lemonchiffon 1 (lemonchiffon)', '13499135', '#FFFFCC'],
             '#EEE9BF': ['Lemonchiffon 2', '12577262', ''],
             '#CDC9A5': ['Lemonchiffon 3', '10865101', ''],
             '#8B8970': ['Lemonchiffon 4', '7375243', ''],
             '#FFEC8B': ['Lightgoldenrod 1', '9170175', ''],
             '#EEDC82': ['Lightgoldenrod 2', '8576238', ''],
             '#CDBE70': ['Lightgoldenrod 3', '7388877', ''],
             '#8B814C': ['Lightgoldenrod 4', '5013899', ''],
             '#E3CF57': ['Banana', '5754851', ''],
             '#FFD700': ['Gold 1 (gold)', '55295', '#FFCC00'],
             '#EEC900': ['Gold 2', '51694', ''],
             '#CDAD00': ['Gold 3', '44493', ''],
             '#8B7500': ['Gold 4', '30091', ''],
             '#FFF8DC': ['Cornsilk 1 (cornsilk)', '14481663', '#FFFFCC'],
             '#EEE8CD': ['Cornsilk 2', '13494510', ''],
             '#CDC8B1': ['Cornsilk 3', '11651277', ''],
             '#8B8878': ['Cornsilk 4', '7899275', ''],
             '#DAA520': ['Goldenrod', '2139610', '#CC9933'],
             '#FFC125': ['Goldenrod 1', '2474495', ''],
             '#EEB422': ['Goldenrod 2', '2274542', ''],
             '#CD9B1D': ['Goldenrod 3', '1940429', ''],
             '#8B6914': ['Goldenrod 4', '1337739', ''],
             '#B8860B': ['Darkgoldenrod', '755384', '#CC9900'],
             '#FFB90F': ['Darkgoldenrod 1', '1030655', ''],
             '#EEAD0E': ['Darkgoldenrod 2', '962030', ''],
             '#CD950C': ['Darkgoldenrod 3', '824781', ''],
             '#8B6508': ['Darkgoldenrod 4', '550283', ''],
             '#FFA500': ['Orange 1 (orange)', '42495', '#FF9900'],
             '#EE9A00': ['Orange 2', '39662', ''],
             '#CD8500': ['Orange 3', '34253', ''],
             '#8B5A00': ['Orange 4', '23179', ''],
             '#FFFAF0': ['Floralwhite', '15792895', '#FFFFFF'],
             '#FDF5E6': ['Oldlace', '15136253', '#FFFFFF'],
             '#F5DEB3': ['Wheat', '11788021', '#FFCCCC'],
             '#FFE7BA': ['Wheat 1', '12249087', ''],
             '#EED8AE': ['Wheat 2', '11458798', ''],
             '#CDBA96': ['Wheat 3', '9878221', ''],
             '#8B7E66': ['Wheat 4', '6717067', ''],
             '#FFE4B5': ['Moccasin', '11920639', '#FFCCCC'],
             '#FFEFD5': ['Papayawhip', '14020607', '#FFFFCC'],
             '#FFEBCD': ['Blanchedalmond', '13495295', '#FFFFCC'],
             '#FFDEAD': ['Navajowhite 1 (navajowhite)', '11394815', '#FFCC99'],
             '#EECFA1': ['Navajowhite 2', '10604526', ''],
             '#CDB38B': ['Navajowhite 3', '9155533', ''],
             '#8B795E': ['Navajowhite 4', '6191499', ''],
             '#FCE6C9': ['Eggshell', '13231868', ''],
             '#D2B48C': ['Tan', '9221330', '#CCCC99'],
             '#9C661F': ['Brick', '2057884', ''],
             '#FF9912': ['Cadmiumyellow', '1219071', ''],
             '#FAEBD7': ['Antiquewhite', '14150650', '#FFFFCC'],
             '#FFEFDB': ['Antiquewhite 1', '14413823', ''],
             '#EEDFCC': ['Antiquewhite 2', '13426670', ''],
             '#CDC0B0': ['Antiquewhite 3', '11583693', ''],
             '#8B8378': ['Antiquewhite 4', '7897995', ''],
             '#DEB887': ['Burlywood', '8894686', '#CCCC99'],
             '#FFD39B': ['Burlywood 1', '10212351', ''],
             '#EEC591': ['Burlywood 2', '9553390', ''],
             '#CDAA7D': ['Burlywood 3', '8235725', ''],
             '#8B7355': ['Burlywood 4', '5600139', ''],
             '#FFE4C4': ['Bisque 1 (bisque)', '12903679', '#FFFFCC'],
             '#EED5B7': ['Bisque 2', '12047854', ''],
             '#CDB79E': ['Bisque 3', '10401741', ''],
             '#8B7D6B': ['Bisque 4', '7044491', ''],
             '#E3A869': ['Melon', '6924515', ''],
             '#ED9121': ['Carrot', '2200045', ''],
             '#FF8C00': ['Darkorange', '36095', '#FF9900'],
             '#FF7F00': ['Darkorange 1', '32767', ''],
             '#EE7600': ['Darkorange 2', '30446', ''],
             '#CD6600': ['Darkorange 3', '26317', ''],
             '#8B4500': ['Darkorange 4', '17803', ''],
             '#FF8000': ['Orange', '33023', ''],
             '#FFA54F': ['Tan 1', '5219839', ''],
             '#EE9A49': ['Tan 2', '4823790', ''],
             '#CD853F': ['Tan 3 (peru)', '4163021', '#CC9933'],
             '#8B5A2B': ['Tan 4', '2841227', ''],
             '#FAF0E6': ['Linen', '15134970', '#FFFFFF'],
             '#FFDAB9': ['Peachpuff 1 (peachpuff)', '12180223', '#FFCCCC'],
             '#EECBAD': ['Peachpuff 2', '11389934', ''],
             '#CDAF95': ['Peachpuff 3', '9809869', ''],
             '#8B7765': ['Peachpuff 4', '6649739', ''],
             '#FFF5EE': ['Seashell 1 (seashell)', '15660543', '#FFFFFF'],
             '#EEE5DE': ['Seashell 2', '14607854', ''],
             '#CDC5BF': ['Seashell 3', '12568013', ''],
             '#8B8682': ['Seashell 4', '8554123', ''],
             '#F4A460': ['Sandybrown', '6333684', '#FF9966'],
             '#C76114': ['Rawsienna', '1335751', ''],
             '#D2691E': ['Chocolate', '1993170', '#CC6633'],
             '#FF7F24': ['Chocolate 1', '2392063', ''],
             '#EE7621': ['Chocolate 2', '2193134', ''],
             '#CD661D': ['Chocolate 3', '1926861', ''],
             '#8B4513': ['Chocolate 4 (saddlebrown)', '1262987', '#993300'],
             '#292421': ['Ivoryblack', '2171945', ''],
             '#FF7D40': ['Flesh', '4226559', ''],
             '#FF6103': ['Cadmiumorange', '221695', ''],
             '#8A360F': ['Burntsienna', '997002', ''],
             '#A0522D': ['Sienna', '2970272', '#996633'],
             '#FF8247': ['Sienna 1', '4686591', ''],
             '#EE7942': ['Sienna 2', '4356590', ''],
             '#CD6839': ['Sienna 3', '3762381', ''],
             '#8B4726': ['Sienna 4', '2508683', ''],
             '#FFA07A': ['Lightsalmon 1 (lightsalmon)', '8036607', '#FF9966'],
             '#EE9572': ['Lightsalmon 2', '7509486', ''],
             '#CD8162': ['Lightsalmon 3', '6455757', ''],
             '#8B5742': ['Lightsalmon 4', '4347787', ''],
             '#FF7F50': ['Coral', '5275647', '#FF6666'],
             '#FF4500': ['Orangered 1 (orangered)', '17919', '#FF3300'],
             '#EE4000': ['Orangered 2', '16622', ''],
             '#CD3700': ['Orangered 3', '14285', ''],
             '#8B2500': ['Orangered 4', '9611', ''],
             '#5E2612': ['Sepia', '1189470', ''],
             '#E9967A': ['Darksalmon', '8034025', '#FF9966'],
             '#FF8C69': ['Salmon 1', '6917375', ''],
             '#EE8262': ['Salmon 2', '6456046', ''],
             '#CD7054': ['Salmon 3', '5533901', ''],
             '#8B4C39': ['Salmon 4', '3755147', ''],
             '#FF7256': ['Coral 1', '5665535', ''],
             '#EE6A50': ['Coral 2', '5270254', ''],
             '#CD5B45': ['Coral 3', '4545485', ''],
             '#8B3E2F': ['Coral 4', '3096203', ''],
             '#8A3324': ['Burntumber', '2372490', ''],
             '#FF6347': ['Tomato 1 (tomato)', '4678655', '#FF6633'],
             '#EE5C42': ['Tomato 2', '4349166', ''],
             '#CD4F39': ['Tomato 3', '3755981', ''],
             '#8B3626': ['Tomato 4', '2504331', ''],
             '#FA8072': ['Salmon', '7504122', '#FF9966'],
             '#FFE4E1': ['Mistyrose 1 (mistyrose)', '14804223', '#FFCCFF'],
             '#EED5D2': ['Mistyrose 2', '13817326', ''],
             '#CDB7B5': ['Mistyrose 3', '11909069', ''],
             '#8B7D7B': ['Mistyrose 4', '8093067', ''],
             '#FFFAFA': ['Snow 1 (snow)', '16448255', '#FFFFFF'],
             '#EEE9E9': ['Snow 2', '15329774', ''],
             '#CDC9C9': ['Snow 3', '13224397', ''],
             '#8B8989': ['Snow 4', '9013643', ''],
             '#BC8F8F': ['Rosybrown', '9408444', '#CC9999'],
             '#FFC1C1': ['Rosybrown 1', '12698111', ''],
             '#EEB4B4': ['Rosybrown 2', '11842798', ''],
             '#CD9B9B': ['Rosybrown 3', '10197965', ''],
             '#8B6969': ['Rosybrown 4', '6908299', ''],
             '#F08080': ['Lightcoral', '8421616', '#FF9999'],
             '#CD5C5C': ['Indianred', '6053069', '#CC6666'],
             '#FF6A6A': ['Indianred 1', '6974207', ''],
             '#EE6363': ['Indianred 2', '6513646', ''],
             '#8B3A3A': ['Indianred 4', '3816075', ''],
             '#CD5555': ['Indianred 3', '5592525', ''],
             '#A52A2A': ['Brown', '2763429', '#993333'],
             '#FF4040': ['Brown 1', '4210943', ''],
             '#EE3B3B': ['Brown 2', '3881966', ''],
             '#CD3333': ['Brown 3', '3355597', ''],
             '#8B2323': ['Brown 4', '2302859', ''],
             '#B22222': ['Firebrick', '2237106', '#993333'],
             '#FF3030': ['Firebrick 1', '3158271', ''],
             '#EE2C2C': ['Firebrick 2', '2895086', ''],
             '#CD2626': ['Firebrick 3', '2500301', ''],
             '#8B1A1A': ['Firebrick 4', '1710731', ''],
             '#FF0000': ['Red 1 (red)', '255', '#FF0000'],
             '#EE0000': ['Red 2', '238', ''],
             '#CD0000': ['Red 3', '205', ''],
             '#8B0000': ['Red 4 (darkred)', '139', '#990000'],
             '#800000': ['Maroon', '128', '#990000'],
             '#8E388E': ['Sgi beet', '9320590', ''],
             '#7171C6': ['Sgi slateblue', '13005169', ''],
             '#7D9EC0': ['Sgi lightblue', '12623485', ''],
             '#388E8E': ['Sgi teal', '9342520', ''],
             '#71C671': ['Sgi chartreuse', '7456369', ''],
             '#8E8E38': ['Sgi olivedrab', '3706510', ''],
             '#C5C1AA': ['Sgi brightgray', '11190725', ''],
             '#C67171': ['Sgi salmon', '7434694', ''],
             '#555555': ['Sgi darkgray', '5592405', ''],
             '#1E1E1E': ['Sgi gray 12', '1973790', ''],
             '#282828': ['Sgi gray 16', '2631720', ''],
             '#515151': ['Sgi gray 32', '5329233', ''],
             '#5B5B5B': ['Sgi gray 36', '5987163', ''],
             '#848484': ['Sgi gray 52', '8684676', ''],
             '#8E8E8E': ['Sgi gray 56', '9342606', ''],
             '#AAAAAA': ['Sgi lightgray', '11184810', ''],
             '#B7B7B7': ['Sgi gray 72', '12040119', ''],
             '#C1C1C1': ['Sgi gray 76', '12698049', ''],
             '#EAEAEA': ['Sgi gray 92', '15395562', ''],
             '#F4F4F4': ['Sgi gray 96', '16053492', ''],
             '#FFFFFF': ['White', '16777215', '#FFFFFF'],
             '#F5F5F5': ['White smoke (gray)', '16119285', '#FFFFFF'],
             '#DCDCDC': ['Gainsboro', '14474460', '#CCCCCC'],
             '#D3D3D3': ['Lightgrey', '13882323', '#CCCCCC'],
             '#C0C0C0': ['Silver', '12632256', '#CCCCCC'],
             '#A9A9A9': ['Darkgray', '11119017', '#999999'],
             '#808080': ['Gray', '8421504', ''],
             '#696969': ['Dimgray (gray 42)', '6908265', '#666666'],
             '#000000': ['Black', '0', '#000000'],
             '#FCFCFC': ['Gray 99', '16579836', ''],
             '#FAFAFA': ['Gray 98', '16448250', ''],
             '#F7F7F7': ['Gray 97', '16250871', ''],
             '#F2F2F2': ['Gray 95', '15921906', ''],
             '#F0F0F0': ['Gray 94', '15790320', ''],
             '#EDEDED': ['Gray 93', '15592941', ''],
             '#EBEBEB': ['Gray 92', '15461355', ''],
             '#E8E8E8': ['Gray 91', '15263976', ''],
             '#E5E5E5': ['Gray 90', '15066597', ''],
             '#E3E3E3': ['Gray 89', '14935011', ''],
             '#E0E0E0': ['Gray 88', '14737632', ''],
             '#DEDEDE': ['Gray 87', '14606046', ''],
             '#DBDBDB': ['Gray 86', '14408667', ''],
             '#D9D9D9': ['Gray 85', '14277081', ''],
             '#D6D6D6': ['Gray 84', '14079702', ''],
             '#D4D4D4': ['Gray 83', '13948116', ''],
             '#D1D1D1': ['Gray 82', '13750737', ''],
             '#CFCFCF': ['Gray 81', '13619151', ''],
             '#CCCCCC': ['Gray 80', '13421772', ''],
             '#C9C9C9': ['Gray 79', '13224393', ''],
             '#C7C7C7': ['Gray 78', '13092807', ''],
             '#C4C4C4': ['Gray 77', '12895428', ''],
             '#C2C2C2': ['Gray 76', '12763842', ''],
             '#BFBFBF': ['Gray 75', '12566463', ''],
             '#BDBDBD': ['Gray 74', '12434877', ''],
             '#BABABA': ['Gray 73', '12237498', ''],
             '#B8B8B8': ['Gray 72', '12105912', ''],
             '#B5B5B5': ['Gray 71', '11908533', ''],
             '#B3B3B3': ['Gray 70', '11776947', ''],
             '#B0B0B0': ['Gray 69', '11579568', ''],
             '#ADADAD': ['Gray 68', '11382189', ''],
             '#ABABAB': ['Gray 67', '11250603', ''],
             '#A8A8A8': ['Gray 66', '11053224', ''],
             '#A6A6A6': ['Gray 65', '10921638', ''],
             '#A3A3A3': ['Gray 64', '10724259', ''],
             '#A1A1A1': ['Gray 63', '10592673', ''],
             '#9E9E9E': ['Gray 62', '10395294', ''],
             '#9C9C9C': ['Gray 61', '10263708', ''],
             '#999999': ['Gray 60', '10066329', ''],
             '#969696': ['Gray 59', '9868950', ''],
             '#949494': ['Gray 58', '9737364', ''],
             '#919191': ['Gray 57', '9539985', ''],
             '#8F8F8F': ['Gray 56', '9408399', ''],
             '#8C8C8C': ['Gray 55', '9211020', ''],
             '#8A8A8A': ['Gray 54', '9079434', ''],
             '#878787': ['Gray 53', '8882055', ''],
             '#858585': ['Gray 52', '8750469', ''],
             '#828282': ['Gray 51', '8553090', ''],
             '#7F7F7F': ['Gray 50', '8355711', ''],
             '#7D7D7D': ['Gray 49', '8224125', ''],
             '#7A7A7A': ['Gray 48', '8026746', ''],
             '#787878': ['Gray 47', '7895160', ''],
             '#757575': ['Gray 46', '7697781', ''],
             '#737373': ['Gray 45', '7566195', ''],
             '#707070': ['Gray 44', '7368816', ''],
             '#6E6E6E': ['Gray 43', '7237230', ''],
             '#6B6B6B': ['Gray 42', '7039851', ''],
             '#696969': ['Dimgray (gray 42)', '6908265', '#666666'],
             '#666666': ['Gray 40', '6710886', ''],
             '#636363': ['Gray 39', '6513507', ''],
             '#616161': ['Gray 38', '6381921', ''],
             '#5E5E5E': ['Gray 37', '6184542', ''],
             '#5C5C5C': ['Gray 36', '6052956', ''],
             '#595959': ['Gray 35', '5855577', ''],
             '#575757': ['Gray 34', '5723991', ''],
             '#545454': ['Gray 33', '5526612', ''],
             '#525252': ['Gray 32', '5395026', ''],
             '#4F4F4F': ['Gray 31', '5197647', ''],
             '#4D4D4D': ['Gray 30', '5066061', ''],
             '#4A4A4A': ['Gray 29', '4868682', ''],
             '#474747': ['Gray 28', '4671303', ''],
             '#454545': ['Gray 27', '4539717', ''],
             '#424242': ['Gray 26', '4342338', ''],
             '#404040': ['Gray 25', '4210752', ''],
             '#3D3D3D': ['Gray 24', '4013373', ''],
             '#3B3B3B': ['Gray 23', '3881787', ''],
             '#383838': ['Gray 22', '3684408', ''],
             '#363636': ['Gray 21', '3552822', ''],
             '#333333': ['Gray 20', '3355443', ''],
             '#303030': ['Gray 19', '3158064', ''],
             '#2E2E2E': ['Gray 18', '3026478', ''],
             '#2B2B2B': ['Gray 17', '2829099', ''],
             '#292929': ['Gray 16', '2697513', ''],
             '#262626': ['Gray 15', '2500134', ''],
             '#242424': ['Gray 14', '2368548', ''],
             '#212121': ['Gray 13', '2171169', ''],
             '#1F1F1F': ['Gray 12', '2039583', ''],
             '#1C1C1C': ['Gray 11', '1842204', ''],
             '#1A1A1A': ['Gray 10', '1710618', ''],
             '#171717': ['Gray 9', '1513239', ''],
             '#141414': ['Gray 8', '1315860', ''],
             '#121212': ['Gray 7', '1184274', ''],
             '#0F0F0F': ['Gray 6', '986895', ''],
             '#0D0D0D': ['Gray 5', '855309', ''],
             '#0A0A0A': ['Gray 4', '657930', ''],
             '#080808': ['Gray 3', '526344', ''],
             '#050505': ['Gray 2', '328965', ''],
             '#030303': ['Gray 1', '197379', ''],
             }

HSVWheelImage = PyEmbeddedImage(
    "iVBORw0KGgoAAAANSUhEUgAAAMoAAADJCAIAAADtkzpRAAAAA3NCSVQICAjb4U/gAAAgAElE"
    "QVR4nO2decgsz3fWn6q5MWLcgsaoqAiKRBM14gJuNCj0T9SIuEVRiEIwSDSCElFJBPegKGqI"
    "a1QigiYuqFHQEeU3RtSgRjQ/0ASXgBqXuGBihPh7u45/VJ1znnOqet737vd+vzZz5/b09PQs"
    "/ennPPVUdb/lox/9KP7/NE1/ddsrUIELwDPLhz/qdn3bn/cdnZ697Q/wNqcv3/YSWCkVYg+B"
    "Akhfs9zdzse2/YzC7/fhJu/DhdcfIJ4uKBWlQApQUAtQgIJyQa2QAikoFejrF5qpNKPLRV/e"
    "bx1KKcB/3XZm7rt+yGj74OP1O+MOrkQSEVONGABAqQMjQw3pVlczypkogvZCKQAg/4c/zIcA"
    "tQ8mXl+07cUlysWps6U7/lJdbAroWSMGSmGZFCuyFTBK8xFQ0XsBofYdH1DUPlB4fWHwUh2p"
    "XgGdrV4K6yQ/3WwV4mmpVcuHzBlp2HhISJnCSULtuyhq/+uDxdkHAa8v2HYMrapa1IrVO8SC"
    "aPMYDzscJULDy2Wug5OeSYJskjShNZk2CXoG+WRtJfzXDwRn7zdenzcO+nJBKa49Nm8qVVS9"
    "2G+xShUlrJj8KCt9axmyOnGWwJpkbKYtsGVSB0iBfL9tvwD/4T2H7L3E61eQXFE5qxGvoVDk"
    "t4wnLoKdp6KK1TDm+wsby9iZA5u9fPL1NepZHUsWbPFTQPtBKmb/5v3k7D3D65cOz97lyg3W"
    "dDPpKlC/VRQROFgueBXA8PulogINQMWFKHnUk61FS99FCKzCYJGS+ZIyVhti9sO2/QL8y/cN"
    "svcGr1+odbAGfeoy47e5RCaGdE2k0AuQilrHHkXFpasXF9NYNOeayA/npuLa1BfHsUUxk1nM"
    "Pn3bL8C/eH8gew/w+rnaP6MKFG59JxZNrBSRZMKG/CAs7I7KoGy6/VZRFbJnBU1V5FTAuNn4"
    "mPcKNbEGti4EFrQuG3NjBaB95rZfgH/6PkD2TuP1szS+wgSWOqpagysflisVyhpnVLeKalXR"
    "GKybrWcF0msrRn1c+K1owpK1ytlEnUQrJhSt4KLS2FTPSvH7PAO0n7DtF+AfvtuQvaN47dsO"
    "4JkSoykDsxWqJLkrhsmNv+UU+vBiu0pTDClOZyWGvNlYI2RpPvn38yqZwrAOetawdKs0o35O"
    "gPaTt/0C/L13FbL6+CpvfNq3nwnUilr8Vgou/VbxrISn+u1CM12HLiXf14JL9flaUCs+wdaB"
    "vkv1V10KatW3ps+QHvJbX+ztani7S0WtY2v8kWz7NX02XTiW18VvMpzA9lP3t73T1tO7pV77"
    "9nMwpKVC7Y7mVW62pgyiFpccbzYWFz9vKvbmoYqc0Ba6KoyaeHHjHwRsKovB4MdsIgRdNeuZ"
    "mffQhGSDX9FUZU3Vmq7jVRIQQLaftKPh9o/eLRl7V/Dat58PoAzfw7EQusTa8VqASFiNuZf3"
    "/Bhn9HKptNocpery7utr9bJ152bNSV/znC2HCQu2rFAK2a95BloiW0VFA1qDCKRtP37HgdvX"
    "vSuQvRN47dtnY3QwLw9os1k1YpSNF2kVNx5BAuZUEYh93lSnGh9wrxa817KbiIdLMEyRvGZa"
    "GK29ffd0dLXkwLrxwlCy0qmCVIhACqQBsv3o/fbP3wnC3j5e+/ZLVflhyXVsohsoNeZbhXDp"
    "hc/vuXrGyL6S6+fuSFgfpb324t1KbdatabhEkqi5A7u3T/n4AbUw/Itzi9JqYkUrmrLWEaMI"
    "RCCAiN4wZOwz9tvH3j5hbxOvffscaCOOG1NxB/QffSgWAljcYGQZQySsL0kRvzGUZkL3UZ8i"
    "lC0JGHNWc1lEiSTN6Vd1sFizuUUplAAPyIbxkjZEqzU0QWuQijZkbPvhOw7cvvFtQvbW8Nq3"
    "zyWnFX76pGEFwCCsQxPMFht/NvIIUT6rFEsaqFb6vMX6FaWqbqUY7MRmGW3By9OSJGbLh4tI"
    "gqyYrWw1UYACaYMzljG07Yfut3/91gh7O3jt2+dp4y7gpYep/bLdZduu6h6/wCELYFGzcR2x"
    "1iBOVUcomLvySgr3XhdiJcgVx2Ap96KvVsqKrQrUIYSJJ3SBrKMCZvulkDW0ApGgW2a/3I0B"
    "TbYfvN++6e0Q9qbx2rfPRyyI6cieHiaPXzGk6H7LMekZyLE5ScUlyrsUi4pWRblot2MsgukW"
    "4JvHpnLho29nvgoUN3TmLojtxAmyVlAhgmZmq6jHF7VnHbthy7YfuOPA7ZvfNGRvFK99+7Xw"
    "3o9gfvngnrwX1PEUKGEUKt65mVANwWOJ6u0v3VSXutbDiJ6N9c9c8ayiUbCeG48TZ6lWSuRs"
    "yVb3+8UqYPT4nrpVtNFybAyTUPtR7dcAC/4U2vap++2/vFHC3hxe+/bry0q0av7p54dCVqlY"
    "0FoHNJxZLAnz1iW1IosNkbAt0zqiLv6iKJwKWDxOWLQWSqZCZfGV9TaG4mhyZcYfzrdMYUR/"
    "CLf5XiURsJO2fe/99t/eHGFvCK99+w32O841MaIWCoq+5KK1w6GBO30wYamFWL16mhsbq1Hf"
    "diWfVIoOl9Amxbo/e1q+8F7ktJJoDbdOvY0uZvaSHsrryjpowmEi1BrQuFy2geUolC5m2yfv"
    "t//5hgh7E3jt22/up+VEmBZ+i/jzp5S5WnzGyhnbdnf0dl8BOJFppiivtnGup50SHk54lqmy"
    "95qzCW7rJbb4KWvTFBpyaBUzhRF1iFYXqg7WkCshxRrWfkDWmqdi332/feubIOy147VvX0xj"
    "3sdBOctYfGitKnsqeRGjJ6DGtBUALmkWTNj5jJU2BSWpf4AaEekGn8vc2Y1zYK/yKeuqC7aG"
    "blUSnHiDKZwSo0KVwSJr38kD+zCbadsn7bdvf+2EvV689u23UiNxeHZOuWqEjFDz2IIFjwhb"
    "jABTrRpmizTM8zCyXyABM0Gyl7tWwV+VpYvzCBp4PXsvifxlerj3WstodvcFgAhaGa1Codxr"
    "VqwG4o/xamijkm6fuN++4/US9hrx2rffUcfYhGY/t3GmS1oUrcRTWshHc4ETVnXX+kzJ914u"
    "CSzudkQfYq9G3kIyHw89e69Zq2YfdiJjpljD4EeSRrilLkIqWhmJ/HkY0TSMACPFLcru5XzJ"
    "9mzHgZu8LsheC1779iUYfnyETFQTTRi6klkQxd6r6C/r9ZSPZjXFxbQKFFJMwwxDuxKOGqDG"
    "33C5aIksgK7ZXaN3B02Q2Sf0b0EJRWiyRMWyGLnwt2PRYuNFMNl8h6YLEiG1Viwz+1Nz8thv"
    "l9dC2GtSLwu3kpsx72W/uw1PSNbehix7GY14AdRHFJFahhQsYF4l4YUStKYUX6eUcdYQD2Fd"
    "GHy6P6uPrs1PCSPo2RRGyPBVLmMnYUSrOiSMlQwQDCgtEvu/++07vXrCXj1e+/b7Uyif7HzN"
    "cjXfz63IFveWiZzfVMlGbDGd0LFuP5KCdjlsZvu06dAqPsGy+5WAcQVMhVKIV4nLGTsLI7wm"
    "khmwBqOKVjdevag2NvWsTzLqYCfMlKxplTRVU8JeOQl45Xjt2x/koKgueAqcxZkZL08lJncP"
    "OrenEE+euJ4M/2I7z0+J1VkNBSrQKp5hnDt0Fnd5WYzqlewXZxYtMmdhhEcS7O4nF2/OnYug"
    "BHosj/CQDEoYzZPObf9nv32XVyxgrxKvffuylG9xdbCHE1U5D2Plm70XYefjCjFm7OEcgM08"
    "gQLYsMTCsN5QmEdJ3PFe0weG1jtDzbRqroPBeBlkaGX0W3tvT3FTH5xW17OZKlFfH1ELGla2"
    "b9tv3+1VEvbK8Nq3P8pj5eoJT2dVkvHih7S3Go+nSCHF1PlYAaQwbB5jCBczQ00uI8EHRpFN"
    "hS97LzZbVM1nsEzGiq6WNCyFEeMlqlKUO5iMNfZYsvJYMrzXwtebmPGStv3P/fbJr4ywV4PX"
    "vv0JeCOfdct2SeIpiZatYKaqRchCIyBKHdJQaR7RWkfcgBSGmbUn5vrHuERcSskYZQGj3Iut"
    "2Lo+EnDzOWcmV9Cuaynmt7J/l9Edb1qVW4sUfc1UtYZW0Io6M2tdCkS2b9lvn/JqCHsFeO3b"
    "n8KoiQ7W7L1mGSM+OLYYMKlisXgkMRh7C45XmW6I2oZJybhiQuts1qc6cCx1FYNFhuwYC/GE"
    "fdkIk6Tv0nuBoKsthtKvx0Sk+6nxKMuyqO3HNmnYf95v3/cVEPayeO3bV1gMoT9rmaCxheua"
    "SGyxtpmj9w6iyeCbZrivT1WSC6IhBWfOJK1/jEKfLY0D6ze7piEY/fveK1pGbpr0bzdzZq1F"
    "lqsuSNRa9B6hyFOLhInFEy0q1qpW6sLtP+y3H/CyhL28el1mTeKfft4NBJ+YwvFeiUomego1"
    "athbYVchMMSnEiGd/3ju9MVCV4OsoABSRo9TOJvjzHstNaxmmwUe5lUgddUX5DZrjIZI9msK"
    "IzjKahRDBMKIp0FnVez0Nn7gVxBVvBRe+/bn9JRU8x+FKuOiOE6O6pGiqd0mQe1ID7hWMl7r"
    "Kkn3gHZTcipB5JmYCXcWzVSxl6/hGOD5kpTM5DzWSih5RFXoBVrFpx5l2XItgrDyxxSq99JS"
    "uFCv1tDK9k377Qe/lIC9OF779lWg8SqxQGSkzr18bkuWvGaNbIUWJXN2UhxzPME1kQWs0rzp"
    "GYB+vriegJ/DVZoxa5XKoj+s4dMub06hF75GMpYUy+zX3AsklZKIqGHzzXSxS5eR147tX++3"
    "H/rihL2Mel0iIpgfxsLBbM3MneEVXAt7OHIqtiQR5qcSVdUt5OKIBBy8kvb3HaMgoe3K2XvN"
    "9ZFom9niKhlO1qj6O6jRTqZ+ik+z/RLSJ85RqdvR0ZHhwxhBwKtqewUl8gXx2re/Es9yXv7Q"
    "C/KibuWyuJKxUGVi63LWMGPFQ4qpFYm4pCh8oHFpUEtktHm39+y9uCDGh/yxWdKCXOk7NrVc"
    "hYZtyQSWjDro8Sl1+GRfbyUyNAz195szMBkPoeW41e1f7bdPe0EBexG89u2rEa7dLXqyTS6L"
    "CbUSOLOf3imcZSxCFsriKqQwGuZ+7mzCqBPJeLKGpC1p1YVNElWkx3w4zWwlpPgDd/IKvyr3"
    "Xjf4mIg7YcQikVcFalMj0eqm+bCmNdEeSrVnt4/tt894EcJeTL3sWlmwtk88ppN6Zb+VFCsK"
    "m69cwsvTfRCGSN4gCYu2JCbUQmCRGpJk3Vq8DgVW3zd4L/7kRJuFETA3zko2DbkRwDx79Pgm"
    "SK2FdDQD1MbHCVXPPJbWypHE2kOJUisvxMnz47Vvf9POnGGPVc8f1gVns7W3JS5U6dniW/AO"
    "IqKN99OyFZkIQ42c0bDVXrM4rXhGVWzhvayyp/nEVqUwQkXrJIyQpFhssGIYwbY9jJKYwq2G"
    "abnWSrE8jHBsWjFb3f7Zfvsxzy1gz4fXvv1tuL0Va+lQyQhSz8IWbS+XgyRswYFNVbI/G5qT"
    "0ZMZYU86C7JGzth4Ff2bMdW/y+Pei+s+s0VUpVsxJVG73XuvU2txiuPlbnwaHNW0sLFQnT/0"
    "5Q1Stn+833788xH2vOrFSeDsQnLoRZYrAMRH+VL22FotOUveK3ImKlT38WLCWLegnHEAZlbs"
    "nveKVZLBmqlC1C0UGyfo5wKtxnI1c/fnGmbGq/GbDEpC4tU4hphcl7Vbx/LnLpHPgde+3bi1"
    "yId1jbQtTf0sVCfeKwjVrF7xYWCLF04kjZCCBw/etV+ITzV4bV0YfP7wDNmqzWhhRG8e6YnX"
    "PL55cKYFsSWPRf3W3OibdSsnpVXbhkLVUF0XyHXZbTRFR76//YP99pOeQ8Ceite+/X3kJCKg"
    "w45kablmB5bqJm+K9OyOeq2VzGolFvbLrDqKN1C4Iem6pSJdAGHvFQ8wPoQSRksHNswDDUy1"
    "y3TNYYTxtBrF1fd6zk5TPMHR11xYG/1g2gjw1zJnpmfYbvtteyphT1evuvxZJ9TckHHRnMrH"
    "rF5SJhyXMkZe3ncqiRYXypmqfEv5Kp1aUvTTWg99JXeVBCzVRCuICSzhQlnJeGWbxbUphxEc"
    "n8qkT1QErajNvoq9fxMdki+hXNtqvLzV5wpan4TXvn0twmDwkESwo4qtKl+Symj13eAvrycw"
    "EXyL+lhoR04GH4wRiRlOmpDAwKh/PJM3P1qW3osONgY9lOx4AiPYE5F5L9QLlMbRk2g1yYrl"
    "+nRWH6PNkph1SQsWza39lPJLgZTt7+y3n/4kAXuievlF4WM5SIfvApdJ25YSyK1CWyGXRWo3"
    "BK+zgsx2KhO2Dils4KFSyN9uwHcZQJxCVsJhM7OVjsym725jnfUyXX3c6RycWinMALWsTyGG"
    "0ALnpo2qoT+bKqDyNJ6Fr/OcHv9xvPbt67Doa/PdPNULscpiyyMcS3PGo8RkekkooJG2cB9p"
    "M1jvtCJhV8ckEyZkwqSgAFJ1pFd0manoS6RteYG4ABlEgBRrpSESFJ8yVcKd1mqkbGygpakh"
    "3LK25xRuCVt+az/qiJ3EXCvb39xvP+NxAXuKel0qAIdmWQTTDHuUXEz52bn0JLzOauK0JEPG"
    "C58SUlQqkUm6IjqLGzkt+3aMERdr7r0uRfQEjbMwIg8lncdyreLT5KtafGhNRf5o1uEdlqsE"
    "+kiKovr6JAF7BK99+xjoIhGrupBtFpyMwntltmgrQ8Z7kc2ZC1sqiyxmtl9JyWw3B+O1OjvN"
    "YILO+HUlqi9sq28t8QM3OqJ4IKGl9tZ7neogdfjw2MDg6FOgyt7o3Fflh73RQKZq2QLw0lmp"
    "y2hscPvq/fZZjwjYo+plf3Zgvok22hNqWa4SWJMhSwimoomJpOXCpG18ABrrJZ0FqTeDDMxc"
    "P6tWn2p65Cwu98V+CxC+0JIJ2BRGIHcj6p8+CHFUaCfykAeWqNRg5Jf3H4AechuQnTumxCt4"
    "/IMgg5bRxwXsHl779g3Rdcn0sz5uyOI+YCWYYVrwRBVWrLfgzHglvKLvcZVCaEjmeILv9a86"
    "diu2GA8dayKTDaJKathvFkbUABbm8H0aEDG3GeduxEZplg9MjYFWqw7TkC7QvPkthUwiZH2m"
    "le0v7beff0/A7qvXRaVrYTvqhI6JVkStzFxOdTDjSxVndvRggJYyRqix72GYels4XDynz5Oe"
    "2QcrBQJdfz5sGHcGa6qPyzDibBSXgZUGRFg15DRBY6qFzeIuRQXFTzdiMSOFawUCNCNJaXNz"
    "VsfFEF9Mvfbt3wIV/d8pT65DE3xZw6K7Yh0KRXPCaGztRN4WJixBlgij0x5z43E6v8PZquPv"
    "djf+OgQT/yYz3FYT7U9scNf18gQNxCTiLD6dfT03Hpp/9WTCeChOslkeQOhLEGvioO3oh8n2"
    "5/bbLzkVsDvqNUbdYFSljJTNc6My1ousVSvUwvKEJmnDndKZ3dhdDStYj6RgwrzBSOMpAA+r"
    "0jHDkAnJGGNtZr//kanUC7SKT4VD+TSyeaqPfs4PtwpPAtJFy5EHR+iYVS+OhzIXX3VgIPgC"
    "6oWphxFBexyFGb4zuXpsodio1yVS8U1Z2IQsWrZlETJMYC0SihhP2MN6oZbj9JWXYA22qvde"
    "l9ClOOvWMpRPA0oFHm4FHWpxhXTGR9QnQ8qliLIJJozX51eNr1CeG699+2YeM2gzGCYX1mCE"
    "/75BkM5TiSxapG3ZuvHDGTtaOJszUdoYMitVj4QU+gGKvsU4fwRj/fng4WMsWK74Nxmt95pT"
    "U3P3J+NqchGcKiOHW6FLUTIc5ugbidMIVOGne4BJQlTBA1IU7m4WsX3FfvucdX08Uy8/w8wA"
    "gv6gWDGXDujZjREuYVjY8oVLQ2YUTjVxbfaT9yIN4/NsC84H59RHvtfsvYQWFmvZmFTHExXN"
    "1HOUFcOtfPURxMRLf1F7iOrPckY6h14BMm08Qt0VKo5jrHMQUkIKOvK5csfgL/Dat2/B8L/5"
    "B40kZXVZ8eQqdf/ZGvQgvWrsKq6Sk4bdx4sNvkzVcEEYCVghcU2ZapBP3tsURoB3sqqF9TPG"
    "OH6dcqWklKshsmcKPYO8MDYbA3mqUlYlm37Rxt+AWpqD+wLpeGH74/vtVy4EbKlefDkrAdFg"
    "PytcusISWi1bsfOjP+wtY+vckC2anAzT7PFZ7YwwupTXCCkqWXu7VyvWD+10oa+kW6aOiGHE"
    "6L1Wd8zGy6x9jCGWJ5MtGo9FRS6dFMT5woSU56LUTkza1mnzdmIE19e35HZt8Jd42WnyGZ0k"
    "ab1RqYZM5tVWPOVAPy1PLo3lai5J9PLQFIjqBSuOHFJAQ/xVv9CYIe6fJelK3qvQW9PXsZk2"
    "eq+NoWzqDTIsvFc8q4Iaj2abKHBvxSkZ/LUoPyva3Gal7NQ9lgb9tJqxeCzpmvDat28DXR3Z"
    "ftAkV0zS0pDRFgpXt7k4cgY21c1g9u+qV3L9iyppB7KicNZ4zBqm756akwl0ro9cUfqNdWsV"
    "RuQhpnT9rXZis4J5is7dqq1lFsmHtahDh7Uc2blzFW7jWWiaag1M3fL2pfvt1+T6OKuXjU5x"
    "jJYMFV/HMEolI/m2oEn3C2jyVWWxMitWKJ0lzMx4QX8zxCbkMp6wY6N/jKd4r8GWXj2gldFa"
    "PIkhzrLTWcmWNktStdJaFgpftFlcH9lmDZ+ubzGexcKWia0MHFZqFwZ/xsvTVJ0pEbjMRDJk"
    "y5kSeVqhliQhg1gDTFnDZuaiFXNJIw0Turbq4s8skLu3YdA1frzZe81hxPxHpjiViB3V5p+4"
    "J3F12jRZey2R8aSxmG+tXH87lDCs3JUWxHGvbcYDKmB2tMLL6H289u3/9gKYdnBaArqPrHil"
    "w6ReSyLTflqVSNMefgsnqUTUmKcYf7j3IockS/vFlwRTv28vYUNmn9zuz8KI6gWxaRiRTq32"
    "UVwsNuc2KzT94uB6lh+jxG2W8SdhRkjbWsVBWsgdAxbii6rXuC/b791vXxjqY1Kv8bN2tw6g"
    "QKwgIvysvmTJX3pJxCK4+yV/hUC5I2YqS/5UjFt5O08KKaY+IhOwQrWV2eK3e1oY4SXvfnwa"
    "wy2ZbVZy9DFKXSYU7sl0yweXTnsX0zZY36LVeb8/uD524c71MeHlDW9M9/PDBBNjBD2msUIk"
    "vUsSgzOqmCSWveTPIlvZfiUl0+1YQQyneJDZ768qWv74A8g006z3GqKm3oekxvh0vrSp++XJ"
    "deUKSObd65rNk7syX+UGKyIYHJVpGLcZ9dKbwtVTE5tO4dR+zOoFMrNlaJjoD+24nAE3K9xM"
    "Ekvasr+SeU0kLTVMGfLoNTUqywoyDinKGM41UtaTq391D3yp4fMzpqyIUpH+yBRbe2swJvMe"
    "O3zYdbmYTdaeQbECZ6xYTQxpFsVavjL0vcTLqBm1A8QoW7Te8OxF8xyvfXuWFAsrONKSSuvr"
    "ci+s3Jys00tOJC24KyxIdYcXXxu0bWpL5qiCUFuUyIkw2HWEE+LRfnkYUVCo9zqGET7WeVkZ"
    "hR6SKxqC1CbVqWvaHDWKHoSGPyRirMaNhzIajLyaIAihqJofR29Cbr9tv/0Wt1+sXuPifYZI"
    "gSDcL1DDk72/gYIARKF1cu2bmHPLlWhLKYaVUa6eyyqpePUvXpYDDOl7yXTheym+taeFEevQ"
    "IZ1pyAzF6KtR4Ztt1kxbyC/g9/ZeoiMZoQrUJjm222FbjpB1i34cyX0xXhfa05mSM2ISN4SF"
    "7TOpsbAutTAaMjNwkpLV9JK6XoGRSjKWNYwgS83GNPzL2F14L2OLi6PWMm0t5sE2y/IXbdbY"
    "/WSz8nB4QpBtVoCJ/RYPueGqF+tdM+dODUNR0A+xrsaxkePwnu9ov4J6wdt0BRGImYlHsTt7"
    "4WpNCzltly/WXyUCjNqCpxrICI3HhFeBnPcR2WdrJauXea/C+9x1qxXNt2b1usNZHxXDwJFE"
    "jXmyWRJtVovuyp464OwaSdCHBxZEWp3tyjS+VPOXC903oybitW/fPeFyBhbOn2UiFZfTwvpo"
    "ulEyT4G8+96fX1LotWTLPLYgyLBK8KFLpE7n5MX2QdN7PvMnjQ08GZGM2WbNEqUr54yUaqXn"
    "UmazLFOwtzsGB0fMTrlheMDf+lD1OpShIwZmBtYBCLbfuN++5JrUy/uCQDPz/R3sztQOdx/2"
    "Qx+uSd4a4JewbzMiST8WzCX1ipGY1dNFSJEG3ds5jwjX92LRAs9DZGhVDiNOwi0vVdzbzTaL"
    "Ay0E2lyHSHWkZFZSo8+SrQbyW6Z2ALT3OqBTcVh+axvUca39VUdj+2V4XUiYHmFL24ZC0WuI"
    "TGcdwurhff6iMi1UDSdiVsNeDxp2FlWQhvUt1xhPLC4LPTUbtcEoRalixbI+nKkPcXnadHJa"
    "ByvQFD1kJZtubPa5r7AhbsEclerZoV2KI9ZqqmFF6y+0jakQ9/bBhFcehDPP38Hu/grzBk2o"
    "kg4RYc7ufVITc1PxuqNhoTJySEHXwmQZs5SOkSWwhus6j09zFk9pVj5pLDkt6qVm527N0sSH"
    "YzqXP3NIdXg+M+8HYjqvuJhnz7rV30WIVG27THhd4DuysJDYlFx/slYg3Xph7OYbphmmR3+n"
    "vAWqs0HD4om4uS1p8xjfLp2dJglfBQvKQmeFwwj19TmGsC6apZFaqg7ZrGZDmXnQFb3qONzI"
    "h35G+DYDoFaOjVTxTRlbHaOuxweVb1iDVFFjvPbt+zMKEamw59I8r3a25hlbS+xMt7ic4VTh"
    "5iAtMMc4xjzC255zHqYUcs+j1Uc+z1HU87kJm+LTk1FcQ5Dma4AX2tMnNsv5m0QraFUa+te7"
    "qJVICxeoQ1qNWgv6xJrX1zkkADq08AJgvPbA9vn77cuuUPUy4yX3gVhSdR/BO8+eSdqdhcxN"
    "vLlKnbcuQwugrmSM7NQ8/AtTxiZ8ozCC8y0aHvOozWIBW9qsAFPJEJiKjDJX9QQke0gRvJU/"
    "az+ywzvU1yc7b6JlR8WD4GijUxVVR30NBet41eVOPZteCYLwFkDoJ6CaC6rXa1jTU+dVMmjY"
    "iSFLGob5b0FarEqwNr0XrSk0cH5uJJrlarPNshpHLbhkswwyLmdi8sFkG4cAACAASURBVNZc"
    "TlzeSKXYkD0oebDzHLk6K3wP4vP9h2x6hDw0HN1pXcb+PB4GglofB14vQ9ISxEdXfnm1myWt"
    "tyXvojZ0a5a9KaSQ1EekuFeSz6Z/dB1jiPDihB+yWXNXtJc8GkflQhXP4clyNd/PRc2aeKo9"
    "BqL36ojDd0jcSBnwjQIqOGQE96OyA60AFNIewsH9KI6rPS3UISjnICWeRv4e5+3l0u8LwPpE"
    "Ly+mWE/EbgZuaciYpEnMhB5aJMYlEjqSwv1WHQuldt2SOYyYbFZbIXXHZnkcdfi+dBuEsHDR"
    "uCPBc/07cEiom6FF2S1aPOEMFw9++721Bga1DaDmZ9Md/qh6MT1ne33e3+fw3bt/ysqznsUl"
    "woDOt7piLrJlS3JIQYplSmmu6058al2H8czV+zbL7rPZAi1JM/AWXzLjfZ3eq3NoEfeV9eN1"
    "fRofCf6OB8lSEzxIOD2kqYC5q6s4Dsbrwu013VvFIfT9Lqt5pkISAXfmnwvBO8CljS/bmDOI"
    "CbWkYbRCPq2jEIjq6GlEV7P4lJ37+SmEs81aO/c0r2RYWOAJlg2914euTA8eW3TzxOsw5fZe"
    "nIoNU1UhgoeHEMUdOtAIdTgwwmutXk8H5Q40d6YnbE1sq+fYiQV1PJ9KISJ5JS+RVbk0B1aI"
    "M8smTLrUaQ2qprEPPjqPzvfKzUAaDsrCdsDv7VkrW0FCOP1ibqiRONjitxbKJmSEDod6LNGa"
    "29lCRRMcB442WqnWkCw6Nt++7KN4vdj0vDjeh/L+FnD3nh/WvBGZB8rWCS+KZ/mPWzFb2rfY"
    "zsIt62BufqyHZhrIXVlh0hkpOk7hcMKcNl2hWcTQW3B2X0YjsZHMNGWoce6FcRaQdSr0D2CJ"
    "PC44HnAIcIGIX3hC1H6NdxQcsKsyPdu3z4w7hsUg64TWxMK6Qk/hZMn87MzQaAfoPIcUmBoZ"
    "/sI7CN4Bjm81qpoxR61ITH96F+PnbzqW61Gb5dozOfdG6HAz0LuiuYuQ7FcXlYMSCg5I+2c4"
    "qGd6ABQHjTmaBcehGwRBI4ObBwAVDw+jSo572j690faL9ttXXZ89XboeVYvnun/h6SmKeGfN"
    "c+AMqWUeBvtDySpvJXZdFzVeNl5+OejqLE04uU/q0iwypXEyQvz1cIFHzoQ6yy7KGOripBuE"
    "9vkModWW4AGUio8/qJeveqmmlr/XkEAAeNZ9Pe2Ref7OzPyq56Dkhe+fsvE7hTgtmRMyUrUU"
    "Uri80Tmx5rTioCspoahx4UuZgomHS5ruWpYZt1zAAw20agUPBxU+2qZ5qX74mIVCj6+0I3K0"
    "FTDEiYMxMYltY53DhE3fl/keHm7siOdQr3dnehkcl9hpT+XitCXuqVQHRmGEO3EeKpiCAytb"
    "cwOQVxBv5QUFAhWj4r00Pa3t5czVi9J8TuofDsBqq+Ch+THATPSmycPHx0v6EnNUjbbcQezb"
    "fziILTtUBO8pXs87PRFEnqmRsOqEoQA0MkItV2LlLFOw7CDlDp4vCI2y6h2IlE4dHx+xp7fs"
    "ONqoOB5oVBYgXY3UffsSXd7lx0Tx0EilZxZu7cUpbNPW2Bfa+lQceeLiiKc9tVyegv47D5fz"
    "KejHqmFxv2Q/33QGXHHvbyMp+GQyZULIU3t1O5uvIz032RA1VRZB9R35YL2BID+kKRfU2g+O"
    "+wY1eTIIgvsmP26yZ3wMLqflASChhbHdwBqmeH3w1etlJrZoI3b2v1vG7b4oYKlY+D4TPIia"
    "J2h/sw46EKuMbazTmXtogPotL2SKo5WwxvNTg8DkJ1slZkicsyRIrq/H9KoViAMvWdjlmoz7"
    "S+yYl5yewv6dN6qr+dQ8nJfcubmxbcrEU+8l1LVhulukoZGRaqHlH+55nWkfe/1NS4reN5o/"
    "uz9b53jCa4FjVJJnZvJ5alPJfHRHzvv1TthVnjDPn4QMeLjnglonFvtnMDIEuKx4vU+w6Mco"
    "wOqvPb8XNzzP/dOnx7fzDO2R3zr5qXkXLueNrTo9u7RIjAvP8/r87k0DFQtFGbLy/D+VvYVE"
    "pHq9qjLi8dKHBEJewua9jkleaP7+krNpdthn90m9eM+XUSKF5gG0gos66SJjN1d96lk02aXv"
    "mwKIvrBABKUAQjgWNMEz3bhYH04Z+5G9PQoKUAS13FM+tuf2nWSFkSAEWFBjfVG2IChlQFbQ"
    "PZa1GXumIfn+paZ5C4s9d3fJ0+fPltyfnrJ+L47tVHW4RDbgE3S+xJULrckogPTGXsK9y/aq"
    "Eoup6H79hChF/SW2Zn95o1fxs4JADH/BGbK098YHkHFc9YZ/758SQbE2oJ2L0dMB1AhcvXt/"
    "ie8Z9kqcP9uXb1g/XwTcZ2hoGLrCU4tuppwbMvup5qLWt/Ms+rCqKFxoC0IYgaitUXuYwvRG"
    "6SsuiVmuYLXOsHY6RSErA6QCFO6Q9pvqGaCjzlUVIf6UTwekapG1+3kJ3b+did+XpeNR99HV"
    "6wAmR5XUAnGXsFYZK8/icpCKsD23VyV7NPPHK/NqEmfmeX6j+T59kUIzojar0esLUApa8RXQ"
    "UEF9iByuijqzxtgyJfrQR34+sZ7Sy8M966UBWvPyoAxnAvliUnpv/Wf9Jz+o63G5/+YNszjZ"
    "TIk7uGjhM73hHdzoNEvEp8r07ne+2Z1faKlhplIXzUftILEP2frOkjGW3sgbL2+lCPVVdzfW"
    "CDJACyXdS1xolRTi63ORzfPzz3A2P/1IcsTSjGl+vj9/9vE3HdOz67+4feRHbIj2WYBSIBK8"
    "EU5aZELttbY6TGy3HVELMZW/MRVAsoez5cuvNbPFnkxIn2xJWC4Rsv7uggpIUWbsVaIOTOwc"
    "RqESmS5AEg3Z3BTAuZ7Nqha0sNI88vyrn+jXdTG2e4n41tv1K9Hlo7TFxlicGvlokOTM++lC"
    "r7XdfCH1AsmbxIfz97gvTvNqEt9U4kKDg2tijcttu6Xf+7jBIWmFACjGEHcgskqJGX/aJebM"
    "HAUOO1IlRVjTVrb59TQXYgnu0E7HSMvDHpjn50gC07PBGD8D0NpAp8aXGgQXqnr8DvNAvOlb"
    "+m62JWZink1FU+Iun7cGJsZERXx9IbZA22GkLHGoNkBcv07TFxQJbA3v1ZuQOhKnCCE1ekLE"
    "G5W9+wV0TkdfE3oqhExFENE2AdPCKW+zjbue6Wo2n+2r3U+/Lhfi9XwlZEGIzwc+MJQoBvdc"
    "U6xeFIXszDgzHxfalMT1G9VZrkfP6K2DqEzbn5ekjwH6JNy2yBUQLkWmW0ZYwfgTCaK+vgFV"
    "TRhkQOYhhY0ObaDzzJQ50dGK4+9rmmDYedst7kt91dIA2X4980lpcgSR4ZBpy887+bFOCOr0"
    "rO/PRgY87d07OXja07YRdlSJ50ov4WOqxSRMIuUzRuBfTNPXRFW6ndksmG7BCXO2rET24lhG"
    "YWld4TikCPVRwE8Je/9YPZMzy/teZ2z/wXbn8h6PrTD3N4j/f69hUf0TLiSwz+ewaOAF8We4"
    "RM4ykFazdZZBgyhtz3RhstgtyiFjMX8Jfnjm3JOMDbc0HTO23B6OPKL3GQhKHaJVKu3oQuVY"
    "NKTwEXzMGV1xPvyJg2jIzIdxVMYe2QTMta1/Sls5acacTaQSKavVkOcfmVJjouZ53cIojkzG"
    "MXkX0xKGk/foWUruu3nl3yXOy7QCpo9hW7Nil9qDiAdDpeNf2GbxVaiondhEXVd/YYXoiM6C"
    "YaiK4jU226AhhTYb56y1MVicwZJF6wHuMG3n3p8lJDUeYV9V8rz/lLK+T9O9lWP7dz2NX5fU"
    "q4zZbnhR9DjuzkN/dFuTP0o/pvkde3se3QjH3d83DlrOX2oubbPgXeLWeJ0mQaUYqRKNPL99"
    "x0tkWEwPI6z10N+iEXnit2KDoedC2aZ2pbmxRuVmoEYwheoZd/Zy39vHcuzIfQSx0U+PuAIk"
    "3jPWcWXWirCyvYSLo6Dpr171vmCxnyrNpLdK+5uViRmaNQ/xXVJmsVQv+63u2CzjKS2stJDb"
    "if1+BF2cR1BkLxh4QHTjejmc4g1G3bSnX9M1w9mQOWoJqZOAo+/LVvK+N0YzduoFs5HinzIl"
    "vayLtPfG250UX+H9LI7X9T/d9k/ZCJjsVCx3SJTw3l2mCemhDUNggBIiZ2zZzNJmjUJZ6DAm"
    "hkpczd7DHH0xy1W0hbhkq6C18S4NRJiPpEhG3lqRChA3KtmNpQKKSgyxA1MJBGK6oTt+FiHH"
    "It2DXsjzUfZstSc2NgUAbtcvdbyAYL/STp3np62NGdsNBh+3HzmO4vn0FrwFxKpXoAVrhZrf"
    "otPyVmF/qBa+31XTrd6iLMMVBLYKHU5FP4Nt5zSkSM3JqVEpBBxoOdR+ITYCgiEjLLj7PLRD"
    "7SUMhNHD2jMR4/zN2kY7LX2SIGCA4xWDe2YilUh7NrXdViSPdRahPBuyMkzP/C5LmxWoWpU/"
    "UAABWjP7enX0NmNhxJAJiiT8TSkltR3aBGi4YKIqyJhVTMrGDLgz78/OLC0Je72Eh6ZwSRch"
    "Cwph25fhevLCGT4rsjxv/PkOd7yaBEfV4oAZkD7ZPDPEq83Kx8SUM9WZSEKUokVNfILNCuGW"
    "zctoxJiRAsZfJrK4qy7rY9ca814M2VlIkTQsNSrNnDWaN0PWf4LwR7Jpxhyb7WZGIaWybsL4"
    "uJzqox/9U5F1Gu6uQPOkXhJ2YTLsBsdc1JitFrHDJH4hG2MNi9A8glSnYVrTY09ajb/yHJ+a"
    "qe9Nwm68Olt9CGGwbiZpvHeEIBshhYb1c9zKumWjXpdgCW0BEbUEEzcw01AzUyzrm/KHxl+E"
    "DPat7hdZTKUWvjDhdf3ft498543BGzRQ5WLzPssPouBZ69KQWioWE5nC22XhC1uYVsg2K60T"
    "FWtQJRDRvzXV96w4W4Eqro9s7SXcCkvU4gITJdbX82GJbZKoYOqjIeMKldKNxt7faqgCMWa4"
    "AUjreAk27OZGaMKu3q6/O+MF2DVzsiU32hoN7ZrrJssYJxe878dnYIGhDubnslkGXKfkzGaF"
    "L2ABBMYxXE/CiFa1GVHym46g1dSxH3t2HRMQYc2SsBVk4TapWi6CjzkzjtBgO54Nmf2CLEvx"
    "oS0MuNg9r5OaBbpwGsFB4/nCH4MZb9Srw6BNKwXXzWV2Jb5J3+vzOrzQn5W1zvkenXNX/YQW"
    "OlQl2MWM8dJ7UbtZ+y4rBFDnrEfKhaSLUda3KKI1tIcUIdyq+tep9bPOVKWGpEcbBBa7NJM9"
    "6DGBElFbwkTFzr2/fgdulqYhQ6ZkYSGUYJNAGZSc4QVxFbEfFKRMupvWoCC+JKSvk81KDJ0i"
    "dUJb4izVU6OKzVbAq4+J0DDCA/rEVlSvpoMmbL/Y3qmiYiZKGFt7fzj95dhE3jIS8xYoG3zq"
    "I+enDCYTFQs+bAamRpSysv5ZDxUL1cCIK2k7T1YjXtd222WzAQuG1LCA2uxK4ercsc0MIT5k"
    "m2U1cbZZa9qIMyvfC4z6Q4pP7SnBOO2nQjnoYyRrjiQCWyV8ntZQUnAfHVgPKaroaOlFK5Iu"
    "Dd8mCnOaP6mX0ZYxmuJZBm4O0oKRUm4YoGaytNRCrIwXbtcvXuMFjIFfEnehIcKTwZT8OBIc"
    "FKa/vM2qar2xslmWvgbCSLTmMKICUoGmspSSCE0onOm+X2bvpZWBr+JbBK5bi7h1/iMuyYFF"
    "CoMbM4y62qkIheQiNiOMkjk/a6ZkESBEOXSq+GEM1aYp4tV8j/qeLqOVNOihtjqTx6wsyxym"
    "mUdsFnTnRYjzEFMJ61d2YFZDJSwZ9cu4L6gV7fAGo9XEVB97j1CjAau+nARMb6X4X0GLJAmn"
    "EojlMjqw5OhDGNvf0oxdtE2BJDKCWYSstWhognjVly/HCM2hWk7QE17ihPGyJR+Ixa6eyI9u"
    "1VdYRAz2I0h+iqFZxhb3wq1JsURbi0X8D1/nMMI0DB6G+VvT+bT2AS4nhBWGJkjRSZdRSMhY"
    "hMpEFTMq/k0Whiw6fRZCaPABJdW4aRLqoOGLO97fuDjB6/qJt/3bt3R2q72Qf+UOwTyAYlaj"
    "pv1CTQdpSdz4MtA6816I4TumcKuDNVfG1FocYQS8wTjCiDrY8kiCCEPVv4sN3Zq+aYWOOmne"
    "hBRYSJEgo6jC41ZSMiMsq445M0MnXUA/tQlqRCo6tkd6Ng1BZIWzYWr2RhCg3q6//h5eAHDQ"
    "r0mZglmxxKfQCkXCOmkmMYfJ1KcK2Ohd2Fd5a1HoQ+hkYKXK6Ol8f3HRMMIu8XcEa+8ZGL/j"
    "gRIzUXddqli4E1KEqGLSrVCh2I0ZczwClnUreX9qhJ4hNZjgGdIzJ5g2yxIVFAv+zadpwkt9"
    "SVhStMhOqBkZ8wDXpD1pV83Asakq0wuxcl05PlX+lroFtfNN+3yq7RG9BqA3GzEG57gP6xrc"
    "xvhKYXdIkHFI0d/xJKSYR+ywx5eJOQTBCGeLrFqLNtNOkDqrnsLRCzmwuVcKCFCupozX9Xvc"
    "9v++BU0iaDCO/AAB7MPMDukMqUhSI31icNnd+6ZiSQpKdoKXcBihJ15bJBmsi7LF9dG/QtH9"
    "Qjra6F1Yxka7quESEodlEkachWZjXBgwtaoXwWpT2QqKyM/SzCx1lpBxy3GdbgzCbtdf/The"
    "gyl9CxOMS/yh4XszIBhApMLHxNhescAiaCHLFUGGO+HWymwhxaf6VA8jejsxJPWM1In3cgHT"
    "5aZbIQmzPqL+1BhJMWlVvp8S1xSGLRuVXklPyqtrUsRuvobUbMjA9VTOiynmNuM5XjJ+QUQy"
    "AiV6+DJ59WzlqUUZVo4lr9jBw7ol4ePZDNv8JFqGF4cR/RQgkZFID8hUwELDUNOvrL62m8xj"
    "sW5Bl0cNk9zVHZUsRxXcwEz2axmPUR0Mzin68fmEpUcNWSN3L5SQpSIrvFcew+v6fW77f9yg"
    "fitBxgJmS2YszpqQSRSxIg+zzWIt5KfIwvtMHC0oFEaU4udbFB4/aDaLHf259+LDzOu1auQl"
    "EdYgmAbjy0lIwSWMy2KwWYlUClo5jM0FNFq3eaEVfn8qpf9cT/VbAABu1899Kl59t5mA5Taj"
    "jJmzmsg4NspFK+0k5smpumOzELe+GhsIa5FMY7mGbln3ItXEpgO8ZrYW3gtD2Ibg6SHt30i0"
    "3GvvkIcUi65uqKjMBotEK9e+uIIBFAKwqElr7594iiWY1e7eULMyXNrJtMbr+gNu+zdtEoUK"
    "9EM3uzKg6KhOyTvDkYqQhb1FaRZjtAi3piQidyyu4lObgRBb9HfvalEXmIyXccNaRR1ciLlX"
    "IsxRE4D7uZPf8pCCFCvpFsetQZxmQxbHU8jK5jfmKUpUI2WVSNLakHVJw+36Oc+HV0fJKwL8"
    "MqoMxxI72+sJskVp6xsXnzeGluHW3E4M3mt1X9UhoTPE1eAApqTeqqSVRTb142FVZS3hxCFM"
    "Z6dlyJoStoZs2dVtKmXCM9uvFInNYytmm6+/I4dnoFeF5IxmwnDFe6b+MbxkXDmHa5+xAiWJ"
    "NQlRlnLtsxXmsQ+ptchNwhg6jIVn7cSTMKIYW9Z7rb/5ki0rgo6amYEKOfQYKN7jaWVxTVg/"
    "VsdICiIshxS2a1cVM91Sy3FpyFrUpLUhm5NYylfXEkgvfzG8rj/ktn/DJp2zSbFaGoqjjakZ"
    "qbJCrUYlK/Ehk2Si5ctV3k7xojBCZHRejQGG/fCzVAJxp8Cbjf0eCJ9cgHbkQWCOEZywtgwp"
    "Rom0/Y1QEIUVq5GEJImKhixU1WjIgvww0KmeTja/xbZkqq3WqEQBLrfrZ78IXv2nlUY00G9i"
    "rj83D2NpSy9htpJtMm6YPNthYPulq6UGY1IsaGuxdiEvoxRW0UCVHS1UyaCqBl0YD4yiDgyF"
    "+h/tW0drP8cTg7BmmrnK7gNn9Czrlpc/qnpz9BUMGdXEBFZYQUZs4zwlyDphl0kJnhOv66fd"
    "9q/frBRagbA9vaiJyklo9E1WPXeqJH2KH5stfOGNCABCKo7lstZiKXoZkhqSiMxWqo+xJlpl"
    "HJlqVTtVQ4MxnZ3WhJTMqqR7/Kod0lhY+2zzT8ZQcGYWDFnsWVo4+tQU4GQfoeVoL/HaWvvw"
    "itv15704Xn2Pdmfai4s1JIPhjZUx2CxuVaUKuLJZQecItVmrgGC2kOJTrpL2k/KwwRIiCSOm"
    "TPUxSFfDpTtgHVEoh37xBtiPIIE5CylAnD0+Hp/N2bpczolr1K0W3RKPgF0Or0g84axEUhPy"
    "sekRvK4/6rZ/nQtY352Wiwbh0WclLqyxMuY0i5v3Rkl/IbcxhRqkkSfTRaH41HTOB3XZ4arD"
    "BnMkcQBs6kv4dv75j3GBoNBgpMK9PDvNadNf59K0WudAa0ofUkNSCClXI2R0kiFzZWJPUBxZ"
    "sD5hkjqupMPD3q6f9bJ49R1pDgzJZpXAU7JZYWFEx/hglUoFdHgs7QnAFG5B542nTpj5ng6B"
    "yZVBNthS0ZJUFslytRIPjE5e09NrVa7CfAMs3z/hDDJakbnYJci6osy27F5zcmKulYBFcGDV"
    "L7q5tvx1/Ild3mDPJu42GJ8Dr+uPve1fuxk3eIJzZ6v+qM0q9DCUS8NOwgqNroAqGAYLpFsu"
    "Y6mdGGVimC3J1j55r/k4qeq3gnSRte8/yMWak1NI0aSfVFJKMD0zbdX/dmRmq4aaaLFWzsPI"
    "hEk0Z7JyY0HtkvenAgrcrh95NXgBQHPj1eYxM08ZqjUJFa+Q/hDGOj41HK32nYQRfOL1cI2U"
    "1EtUrMSWmy19GCojhj5ZNgGu9S1k9+OQEFKyFjRMRkjB+rGEzNCJ3ZRz4sqceTVs8cBKz6rC"
    "BTfGNdHAIoP/BNf1HHhdf+Jt/5qt/4gsNinONu0pjFoizx5KeItEGGuVUzUj1QUMOq+QVXG5"
    "ajZs0LRK7rIV62OojNDGI1+HnAlbnZ2mWrWOKmJXN1GyLJecaflqmJaklmbsDp8NWaDKOK6Z"
    "tla0F+invUq8+tSORcq1GIQjMdwiQUpZV7L5VcsKiLMcn1oPjyLFuZf1AoFGokLNlqQbYpUk"
    "1PyYmXOvhkvRPEGGQIIiCa+YdtpVC+XSIVue0j0KnFWiOQ+rpzKW4UsDyLhRWVTGJVMV1lz1"
    "iK//cNnL4XX9qbf9724mTgmyPp3arKl5iPOxgakXKImWyKCwX/bNuhRFUUMKIw60ohe94Ugi"
    "OTCsHp7nXgBK1a+pehy8V0OBfzYzZGgYJ32chRSuWGqrZ++VIgw29cHdJzWKMtbrZm4WrEaP"
    "ccsUl9v1p7x6vABcf9pt/9tbnXhi0cKJzTqjyksk6xAtT3h1npZhhPUCXczIjxa0hg566CKx"
    "pS7N2YqFkqWrYhgPP5m2xSak/Rp6JNwPKYrEPx6TZ+i8D7539UpNy1UYlvOICR1vVLZFVfU1"
    "5Xb9yU8HBs+FFzA8PutWsFkEWVGXw5EYtwMMyhk+RjBfSZAUi72XmfoKja+IGwu6fCEo8Yok"
    "NbpsSfJefeY4gOLidCnu5QNPCtlZPOGcPSmkiHGXs9Xc+DN58/VRWtpCLHwmh0HDFNnh6J+j"
    "LL4IXteP3Pa/sS3t1x2bldec1MsTr/NwK1+XCy5dEC+Ohb08uXv7m4x9OE0a4NU46Fp5r+Tu"
    "ezsUTWWv+FE3NImQ4ibkvZAihewLyMqapKBbbLYmo8ZLEjr57RRoa1cCt+uPe714Abj+rNv+"
    "17bERyGkgs3SFXgm1Ee1WTUC2qwvxZ61wc0965IgdT7qhn4ihwxjDJwnFMxWCrqi95J0q2gf"
    "R6ldcryvCUJnb3PcBXXxVjqnMRTuwEIrElFCpqgiRPOcSsy5F8JCKYHOkHrElbUmQsoLsIUX"
    "wAvIJdKkazni1GN97l6cslOkmohxWLeIFOAF0dxxoRzVElQYQ9q+K2S/ZraS0+IVwB6/oVa0"
    "B/0kQj8FKZOt7K1jJQxzPze3Ir2fe1YaFqoW8oWlG8sLDcc4sMfey7RTYmFt9YkZ/Ty9CF7X"
    "n3vb/+LmcsUWKj7MY5qJqjk7BaUPgLsrWx7GoGLMm6m/KFJAaCeGG3uyQlWS6+DkvdLtOOi0"
    "PPb1COUvW7EI2cWsPYlZ/ivdASAeBhgVa55JGWkuo1woMbE4DfxCvV0//QU4wQuqF3D9Bbf9"
    "K7dgs+ZOaGLLWgBBt2QEVHO7kgMIvgfl9WLDuTBAKdpRPf6yeoIMq3n2XiZmhn70XiOeUIj5"
    "zw15K2cOI5LOKWG1ARRStD5aGisOzkKK4LrOZIwlkBKynHJZTK/dUIrg7fppLwYJXhgvABDv"
    "BuFKl/sQ7VCmmZydim+Vxzv0+1Qo2dRzGIHqBbHpeWZN1oFq48GDXB8JO0YqeK8DAEpFbeO1"
    "TfyKZd2KMWGi/e5zas+Bftezy5NCihVkzYop26+paZluYbWoYe35+n+W04vjdf3Ft/3Pbuy6"
    "mCSuidlgcdc1ixbXRHhlRLT2hXqEgGG8zF2lmgj+JaF/77NMfmtVH5MbC3aKZrq961ctdPtV"
    "glaNnyVe4XcVT3TgWLTmgmjpFAJkHFWkDu9EYUgu5vDCmgu9tfhDXpgQvJR6Addfdtu/YmPP"
    "Ptss6wi3ZxfxqZY80WJXWefI2osNkeCRg0oSjIY6fiL+q582wKsg9mpPXp6zCZkEzB8WJanv"
    "6EM/VaHUPtqvplsJIUVuS/aQQjykCIUyyZX+vhmj2Im5rIxJqIJM9tbiS7GFl8QLAATtiD2P"
    "5uspMs2NSo6yoEu48ZgUK5p6VzUKIwZMQnu9umK5jBEWTR1bU/eW5SrlXqpPHVZvDKpjg2gT"
    "1c5RUGXyJqRyNrQwyVg/pdto8E9DoATjNaUPwcufpBK5/zF2FkmD1Nv1B70sGy+P1/WX3/Yv"
    "31qjRVGibElY+IT41BQLcN2y4iiKWjjxOioWRxLjZooVK6PJXqNuR0zSNa7vJQB9u+T9vbUI"
    "xyhY+5XxAtsyDymST6qnkAXa5hGIsep5cUypB436ejnLZdNLqxdw/dzb/sc2NyUEk9fNSBUj"
    "yMwVtl+GlBqs1iAIpt7GOkNrIhJhRWslwp5ikkZC8Vg2wd4raEHFGQAAC5JJREFURDAkeBal"
    "el8Q5fhu18iEBciaczaFFGq5TMlmDRsi1PLyNkuUEiapVlZNIj715cHAK8ELwPXzbvuXbS3p"
    "lj5M3itbLupPTFo1llsYoSXGrh9e9OSfLlG9nYg6sTUn9ekiXma2ovdKjccUT0CL4PhDvjbi"
    "stFpKdR4HC3NFFKcPFx0RLLMWAtxrWE1a5UQUi0CannHOFIvt+v3eiVU4FXhBeD6+bf9Dylh"
    "VPL6VCJwLeLFY7ZgWsVhBNVK7wXqokWaBK6JpmFqs7zZmNJUdvcsRTxPNyhhRbsKhgiV0IE9"
    "miZtfKNHQwoGaxxXS6flhTJeNyCL2dS9E1CLfUfUVrhdv+erQgKvEC8A1y+47b9/k1TykGsi"
    "NFkAgm5JjE8rHf3WdW1pKv+RKesF4rK4iCT0z23YwpI0jNxYromxIdmH5bSGi252VMDipdBt"
    "VjT1nTC7SFM448NSDAspwslhE2eZpDkPO0lcF09VCG7X7/YKecCrxQvA9dfd9t+75YZhqokT"
    "Xr3SnfUzJkNmQZffZPxcRQnzvN6cu0TdMrtGqDlMPK4w3Yo6ql4B2+DpUgFttGJCahxarG1m"
    "HxHAWnR1Z9Fa0db0a8yG7A5nEdZXzhZeOV4Arl9423/3tmgYcmvL8KJ7TGEEYxd6gcri5J/+"
    "m8PGRxzh2UZghbIoka3ovWbLNVbWV3Wd7m1Jbi3a1xSVMVAeEUqhYdfO+7n9lIrmRXPWsBS3"
    "PnqKETUIbtfv/MpJwOvAq0/tiNEogLOxgaswwmag61vvtUALnyJSJ8j48K6JrWjtja25LLrf"
    "nwulEmZ10IJiUaQgXtyFhKpZphpjMFg/d6MwdhFSWJRKrivLVV+nBYx8Jg74aeV2/U6vCYPX"
    "gtf1N93237H1uDVVybluptEQHSwulCZaYx3zWCZXrFKab41hg3XBFpOEEkg6K4vLxuPAqCtl"
    "HRkpaM3K/Y9wqfNM1dKK1M9tkEn/80TxG5ogJ2u/rIxrDfNKers+9xjUp0+vS72uX3QDsH/x"
    "NodbaUnCy8MIgWgrkjsZK3VdQ8MIP4Gx6Az/GYRJt/xs7OKC5AzNf8Zx6hrS8j6Y4K6LRpAZ"
    "WHNqX7Xch1Siu7ppUOvqunM6MmzR/0NCxWnZoia2vOde6fS68OrT9bff9t+8pQqICSm+5zCC"
    "YwhwCqDOPaUPDtNEVXZgFEl4fYS/PDUVA1i0gr9WL3XjBkm8hrqMMTeqUuAwLNky7Req3hEZ"
    "NSwXRAStSqjFqOJ2fXitex+vKvu/M11/160d6DfRmXQ7HtAOtAdd8oDjwHGgtbCONEhDO4A2"
    "5u3WpiXjdtA6hy6JM4irjeVH2GzTe0C30yBC30s30h4gAjkAoXfk950+G+bPbyuLL1REuiYp"
    "VUfCCDgqWh3LDyqI3oSskHq7fsfr3vV4A3gBuP6eWwfroHsjKWD3oM8+QPrDhwHf4MP2us0r"
    "IrxOO/Lu9D0tg1rbiy2u0OI+9k0dkAPHxx2XPiTa15lpfoiwEoUSvwL0QPLPIPFIaBAhwg66"
    "DxhVmqm6cobsdv32N7Df8WbwAnD9fbd+ZBtSxwMd+kvgHvJCjJ+Y1Et3TFcLUWFDIobY4n3W"
    "lNSwJuNyIpCDaahWKStdYpseD13eOGXgLyvTBg1B8Kci1DJMpkbLKCtw5jX0dv3WN7PT8cbw"
    "AnD9A7dRLyJVVhmPuTg++J5GcwJa3OtoURWshgoJxiROLVXPI1co060kYE7Jx30hoCr4EF8u"
    "Ua4kvGmbIObvCPGHsUSWIV0sWkd1MVvcqrL1P97YHsebxAvA9UsDYUGfzpwZFUdzKog7hqub"
    "3QfrI3GXq+x5eZ28V4veK2D3EN+XZNhXk3g8PKyqp8kV66vJlSpZN/i2QpSuSbTaamG/x+V2"
    "/ZY3ubvxuluO83T9wzcA++duheJToUvu2pgI7t4GnZ3V7O+1YGQQiGGEjZ4oaXlqNlrQFduP"
    "bXWOUJuGExY9w7FAoy8LHaBDVQtdTU7TijsDWXNIEUZPeFpWc5uRW5Hr9uPt+s1veEf36Y2q"
    "l03XL7+Z+TWnZZZfVA+OBxwrgTFhyNYqlhgWDFe7aJZzfeQiGC1X60KVNOyI87OjEq1x9FG9"
    "8Rs/efeCi4rJ6tsg3X71FiI3IdnCH5UK4r9/K3sZbwsvANc/PQplyiOYsxat+rK4hN0ZV3N3"
    "dYSZgNoKX9/N0Xv1mrt8bXKETHmb3zTRHDmzL7t4iR9g3WbhtEqO+8vt+u/e1i7Gmy+OPF3/"
    "zA3A/ou3o9EYVM0Y7bLhtaBV6gXS2lS19jWs/wwCYjSf0lTveUSomCE+nTuFNOUuOsSIB6/m"
    "Pko6regSs/sxMK6ddnKj91HaClYudSZ2dadhzb0gfuPb2KthemvqZdP1z0e/H6XLwgj2wi4e"
    "FEZke95IUU4euuqwRLVJXeiWloyPJ7TQ/P4D0Ovmg3/s8OFj+zGUePrASE+5gM1twwqxgvgv"
    "3/aOBd4FvABc/8INgtY0jHjIv3iLVcNL4UnD3v0N7UWva8nfTNWKa2UOMngHQw2ZNVR5C2ab"
    "xFuvoCYhw+RbMH3SD+/0y3i4aEVyJIHL7fr1b3uXjultFkeern/5BmD/rK0dsMvdVL6ch7YT"
    "rdMahYYN6nwvlK34yC17eW4k0riJBq+evOSsM3tcpvBA7cMSGxpwKWiHXjynF99GI6Sb1kTB"
    "BQB3L+owinBNihb6ucXGLYq+tk1nE6Herv/kre7GPL0rePXp+tU3APtHNuFT+OlSg+OermrZ"
    "QwfRIak2Jif4MEaHxqkm78VmC2UBllHYHnTErF0HoKEU1DZyhIFv049kVzqh5EImwiye4PtE"
    "W4P3c0NQu/2C3K5f+zb33Mn0ThTHNF3/1k3PZdCakmoTuZbG9Su2EL3kxVZYaBhSv1Aj75U8"
    "Fj8ctVs8j2gP/qb2Ru3j9Bms81u/UUuNzTMrRluYg9nuTYF6u/6Dt73T1tO7pV42/a3rDcDP"
    "3rdx1NIYr+Wt2SguoSFfLFE0IKefRhbkqpA+Fbo/EzBLR1WHoJXRFEuEAl6TXmTFskFvOVmN"
    "YoY2tR+BA/ia6+3t7qn70zuKV5/++vUG4OftWy8KlUcLluGB7D6Uwum8oPXMufeabyOgNy+F"
    "SGQb3Q/jeLBSaH8Xp1HogPFiG3LY4xg03Wzze9ty0/frWH/tuw1Wn95pvPr0l683AJ9NSmZ+"
    "K/T/TGwNreJeoKhhUggsU5cJuxRrVTVnTc/vHTNFL9YFUi/rm4qyBABCJC3Ps13egH/yPoDV"
    "p/cArz595fUG4JcZZKk46sUmml5SlZuNzJD3LSp8btgBKHnLoc8MXAEu2u3o7cROQB2c2ch6"
    "QEXL6qDNE2EpVs1xK/Cx9wesPr03ePXpz15vAH7FvtkvzhfAGWOjLYNQ7MDixPVRvJGYG4wl"
    "8LQul3RNr85EtUvem7XiRiIAkEaqVnn3dou0wT3WN7xvYPXpPcOrT39af+tfRWLW6Jwzi7VQ"
    "opKB2LJ44uQcoVNTD/qjaP1KheOfP/RSyDxBYwuip8H7i8IZ24IGfNP7SZVN7yVeNv2R6w3A"
    "F+xb75lJOWquhtb5OEWs3FQETjlLPY9Fzw0S6n8UxMInQeeaXfaMrpZjCz19Bb75PQerT+83"
    "Xn36Q7onfsO+QagIElue3Sdfn7KJ2GycwQoO7Bg49qlIhqzPHA3PKtpD4OnChKlWCfDfPxBU"
    "2fRBwMum36P75reoOfMKqEhhqo88UKLRaY93wEoP+zSsVcvr9Ey4ml3D8Gp2xYMGfPsHiyqb"
    "ykc/+tG3/Rle7/Ql+9YvVHHpt4Jq90AtY3mfGfe6ctXbJd0XXApqC8/aq/pftrKVi+gKLayM"
    "DyhSPH3w8eLpD+5bBmUGjilc4lVRWgbuUpyqS0E5dJviqxXgkz4ESPH04cIrTX8y0rZQqZOn"
    "GLXKVElYoQCf+iHjKU0farzuTF+9b/cJs4UF+JEfbobuTP8PvRhXFuF66lUAAAAASUVORK5C"
    "YII=")

#----------------------------------------------------------------------
RGBCubeImage = PyEmbeddedImage(
    "iVBORw0KGgoAAAANSUhEUgAAAL4AAAC+CAIAAAAEFiLKAAAAA3NCSVQICAjb4U/gAAAWGUlE"
    "QVR4nO1df+g0xXn/zD5qWzR/qBQlRZQSSSumIbZUli4y0L6lNAqNaUkiIRpItSVSKi+0Fpsm"
    "oCmSWtJYIUmbxgZepMGS2hQ0JU0zhA3S8KbBJBClQQzBUg1Jg00wUfemf8zt7jO/du/ue3c7"
    "ezcfRJ7v3N7s7MxnPvM8z8zeK5RSyMhYH8XUDciYKzJ1MjZEpk7GhsjUydgQmTpDkFJO3YR0"
    "kakThZRSZ/bEkakThuENgMyeGDJ1Auh4Y5DZE0SmjgvDEmH/h8weDyJnk4OoTkk0oEY3gmr1"
    "71M3J0WcM3UDkkN1vcTLaAAABDRAKU8Rilr968QtSwyZOj2qN0kslqRZtIWdUcrrCVSrf56g"
    "ZUkiUwcAqrf1SmO40rQfNfaVpXwTgWr1j/trXKo4dupU73CVJqY6HKV8G4FqdWbn7UsYx0ud"
    "6taw0gyrDkcp30GgWj24qyamjWOkTvVuiWaENMOqw1HKWwlFrT6y5VYmj+OiTnVa4qWVSLOK"
    "6nCU8t2EolZ/vZ2GzgHHQp3qzlWVZl3V4SjlaUJRq784UVtngsOnTvXecZ/m5KrDUco7CUWt"
    "/nyT5s4Hh0yd6p6h6GnYPgl1DEr5XgLV6s82rSB1HCZ1qvs2V5qTLFg+SnkPgWr1JyerJkUc"
    "GnWqD51UaU6+YPko5X0EqtUd26gsFRwOdaqPbkdptqs6HKX8EIFqdfv2qpwSh0Cd6uObRE/D"
    "pNmu6nCU8qOEola/u+2K9415U6d6aL08zeqk2YXqcJTy44SiVrfspvp9YK7UqR7eldLsWnU4"
    "SvkQoajVW3d5k11hftSpPr19n2b/qsNRyocJRa3evPtbbRNzok712DajpxRUh6OUnyZQrd64"
    "rxueFPOgTvX5/SnN/lWHo5SPEahWv77f226C1KlT1ftWmqlUh6OUnydQra6b4uarIl3qVGen"
    "UZptbUScHKWsCVSrcromDCFF6lRP7CN62s9GxMlRyrOEolbXTN0QF2lRp3pqt3maqTYiTo5S"
    "PkEoavW6qRvSIxXqVE+nojSpqQ5HKZ8iFLW6cuqGAClQp3p2ep8mNTd5GKV8mlDU6oppmzEl"
    "darnp4ye0gzOV0cpnyVQrS6dqgHTUKd6IV2lSV91OEr5PIFqdfH+b71v6lQvpq40c1EdjlK+"
    "QKBanb/Pm+6POpWeh9LMS3U4SvkigWp13n5utw/qVOdINGg0MB/SzJE6BqXUhKJWevzSk2G3"
    "1KkukHgJzQKYG2nmtWD5KOU5hKJWL+3uFruiTnWhRDNj0sxXdThKeQGhqNULu6h8+9SpLpV4"
    "efakmbvqcJTyQkJRq+9ut9ptUqe6TGKBpgHmT5rDUB2OUl5KoFo9u60Kt0Od6kqJlw+KNIek"
    "OhylvIxAtXrm5FWdlDrVVYemNIeqOhylvJJAtXryJJVsTp3qmsNUmsNWHY5SXkWgWn1ts69v"
    "Qp3q2kOIno5ZdThKeQ2hqNXZdb+4NnWqUh4DaY5BdThKeS2hqNXjq39lbeo0x0Ga41GdjbE2"
    "dRbHQZpMnVHsSnXmTppjW7A2wPZV5zBIk1VnFNtUnUMiTVadUWxHdQ6PNFl1RnFS1TlU0mTV"
    "GcXmqnPYpMmqM4pNVOcYSJNVZxT7SAnOkTRZdUax25TgfEmTqTOKdDciUlgWuZHhIMWNiBRI"
    "k1VnFGltRKRDmqw6o0hlIyI10mTVGcX0GxFpkiarziim3IhImTRZdUYxzUZE+qTJqjOKfW9E"
    "zIU0WXVGsb+NiHmRJqvOKNJNCaawLHIjw0GKKcEUSJOpM4q0UoLpkCYvWKNIJSWYGmmOU3XE"
    "OhdPnxJMkzTHqTprsSGfTR76lBsZDvLZ5CGbGxkO8tnkIZsbGQ7y2eQhmxsZDvLZ5CGbGxkO"
    "8tnkoW8hUyeOdDciUlgWuZHhIMWNiBRIk1VnFGltRKRDmqw6o0hlIyI10mTVGcX0GxFpkiar"
    "zijy2eQhmxsZDvLZ5CGbGxkO8tnkIZsbGQ7y2eQhmxsZDtJNCaawLHIjw0GKKcEUSJOpM4q0"
    "UoLpkCYvWKNIJSWYGmmy6oxi+pRgmqTJqjOKfDZ56FNuZDjIZ5OHbG5kOMhnk4dsbmQ4yGeT"
    "h2xuZDjIZ5OHbG5kOMhnk4e+hUydONLdiEhhWeRGhoMUNyJSIE1WnVGktRGRDmmy6owilY2I"
    "1EiTVWcU029EpEmarDqjyGeTh2xuZDjIZ5OHbG5kOMhnk4dsbmQ4yGeTo7ZuNIBGN0KchwwP"
    "6aYEpyTNjzQAcZ5AUwDQugEgxKvcvjhupJgSnJI039cAxPkCTYGiAAiAoJ8EoPWPAAhxkd8n"
    "x4m0UoJTkuY7GoC4SGBRoChQEBYAFWgIAFAIehVAWn8fgBCvDvXNcSGVlOCUpPm2BiAuEUAB"
    "KgBCUWABEKEBUCyNosACgn4aKLR+DoAQl0e76QgwfUpwStI8rQGIywUWLWlQoAAWS6UBCATj"
    "8fBPBb0aIK2/DUCI10a66sBxpGeT9Tc0APGauNKYBQtLdwdUoAFAyz+XCvSzQKH1NwEIcXW0"
    "yw4UR3c2WX9VAxBXCzQFzi2wGFAaQgEsChDQUFyBfh6A1t8AIMQvDfXdYeGIzibrL2kA4g0C"
    "6BzhAkAvMI5r7ChNoLz7eiHoFwDS+isAhCij3XdAOIqzyfqLGoAobaUBel3hBgD4SuOUM6Ov"
    "hwT9MgCtvwRACDnQjQeAAz+brD+nAQjJQ+5eKtrhN74LM7pyS2nYgkXEjI52nQL9CkBafwGA"
    "EKeGenPOONizyfozGoA4xaIn4whzA+hj79419so7AwCoX7Cccrt+Qb8KQOvPARDihmiHzhbp"
    "bkRsTppHNABxg0BTgIqlQiwdYeYRd0rTu8axcltpQPFy90aCfgMotH4UgBA3DvftvJDiRsTm"
    "pHlYAxA3spA74NLCir2XrrEnMH1wjojS2C7z4I0E/RZQaP0pAELcNNrJs0BaGxGbk+aMBiBu"
    "CobczKeB7RHHYvKR4NyL0l3fmd+IK9BbAGj9SQBC3LxGpyeJVDYiNifNgxqAuLkNue2YuTVg"
    "7yeQVR7I/q0WnDtKY/nOiLVE0NsB0voTAIS4bbi3U8b0GxGbk+bDGoC4rVWaaMzsx96h8o2D"
    "c+eOQ9F7fyNB7wKg9ccACHH7GgOQDGZ5NlnfrwGI273knjPvnZAbTADglHOjDbnhBedASGD4"
    "HYMtCd7RhPG/D5DWDwAQ4nSsz9PEzM4m6w9oAOK0wIIpDWDFxo5OdCF3HzzbAtOvXMY1iQfn"
    "rsB0KxciLeEXcM2zWiLoDgBafxCAEHeuMgopYDZnk/X7NQBxlx1yA3bszaZ1rxORmLzP/nWO"
    "yGrB+XpROpeuyAVFgQUJ+iOg0Ppe088k7h4YhRQwg7PJ+j0agHifmfrnggoAy1HvfNumQMEW"
    "FDDxWP7pG+zrA9G7+dRxjYtWaRxdMd9qPCUzuhUo7wwYH1+cd5fRJ63fB4DEvWMDMhnSTQku"
    "AH2nBiDe36ZeePRrprLr5GJECQJftwUAdm2Wb8Rj71WCf6ZkjoCtENILuhsotL4LAIkPrjo8"
    "e0SKKcEFoO/QAMRfEhqA2FznYXanGb3rENn6NobruwwojVMtP8oTz/65rRrdkOeRfLhVgj4A"
    "kNanAZB4YK2R2jXSSgkuAH27BiDub3u/m5R+FL1cI1rfNhxdjwXPsSi9u8z1ncdi71i1a7XK"
    "rlbQ/QC0/gMAJD627pDtCKmkBBeAfpcGIP6G0ADnOuk1rgS2JETLR4Pn4Wq7y1ao1lKaWPA/"
    "8PXRao0f/WGAtL4VAIlPDI7SPjB9SnAB6Js1APEgUxrAimm5EwpPafqNJ9t3GQ+eg2F8XGkC"
    "1XKlWTH4755ulZifh/RGgR4EoPU7AZD45LrDt0VMfDZZv0UDEA8RFp7SBMLsgSiaTVln6o9m"
    "5yyP26t/3OOOJf3s5lnbEaFmO/WEQ/pOgc4AhdY3ASDxKXeQ9oLJzibrGzUA8XDbO+Gpxqbs"
    "cmb7W9+OErRGrNwVMDsIXzE475QgXL6L+gPdIuhhAFr/DgASj64+iFvBBGeT9W9qAOJfWp9m"
    "4cXMnRGLckeD5+GYPFzPXOsX9AhAWt8AgMRnx4dwS9jr2WR9SgMQn7VD7t6liJzKi87g4Km/"
    "uBIcdP2CPgOQ1qcAkPjC2DBuAXs6m6yv0wCEYo6wE446HvFAlBsLnp3yo6xfkAKgtQRA4vGN"
    "KLEqdn42WZcagHicsGDRUywKtXxDVr6t4Pk46hf0RaDQugRA4iujY7oZdqg6+g0agPhy+6gj"
    "wS3b4g6X+7G3F9y60a83U4fK/fPL3Uqx6/q95MKynkiUPhpSFMCCBH0ZgNa/CIDE19cd6FHs"
    "RHX01RqA+LofcgeDT77FPRyTrxbcBhL/bKb69fe7HHb9MSVwg/9IFB0767N2cuFE9Qv6KlBo"
    "fTUAEt/E9rBl1dGv0QDEU+2jxmJjf+PGFRg7Jg+4nKtMUK9+f4KOurSuUvLgn9c/3AB27BCh"
    "+v0H6ZwY9wGHfWe/fuNEPwVA69cCIPGtdQc9iK2pjr5cAxDfYiE3sJyyFIktY+V+7Bp6U643"
    "/HqcwzqjN+p8jlgDovVEyp3kgn/scMUbjTdgjZ4U9DRAWl8OgMRzwfGVUiqlgh852ILq6Es0"
    "APFcu0kU3nD25oc/76NvxI3GtLZH6ShBtAFe/YOv5IWUbHgPvPNhI0/q1x+L0mPvHAa2wIIN"
    "cN4t/G+AtL4EAInvrUuADqtSpyMjVx19kQYgvtdSIeBRtg9geY7+tPDy/U7ICm/+uS4nv5E9"
    "QQMN6OoJnfixGhC8kf2kQzcafNLYg4SV5oRP6napoO8ApPVFAEj8sBvlFfmAtVTHsMeojj5f"
    "AxA/bEPuXmBs+rse69i0CPyMTWDeuB5xfyOvAYHg1txoteDZfSMn/qTujQae1G5JwLcdvFH/"
    "dvPokzo3CjypoP8DCq3PB0DiJQCAllKssmats2BpSCG11gDES+ZRz0UBgE1TAlD0RncSzynv"
    "j4eyr4OWua9AeWsgVL9f7tTfVxgrt+vvDKd+/0ZOPf2VTjmLjHg93doULo/X7zjXndFJjlN/"
    "uLwL4w1pfgLQWBlr+joaQgj8uHDLqV3GouXF8n8LWMZyirSXGaN3+rgBtni1iVfA8kZ5eec+"
    "F+wymPgOyzMSvNx8zQRNYPU45c64dvVYvFmZQN2i41zgjLT/UodVztUdlngbKQqmIZx8xI/P"
    "WYs32MBNhgbEAq+cC2pPkvvt4AmSbsXtoiHjFS2Y0YkT7GDYPwRDZqQLLFoHq/OFrXJumE/b"
    "zi2YnhOsdcHc2ve0zAA3rG2uwZra2GtNFxA0hdUGfzEie303t+57pn0oYkbTdoi/g+EfsCen"
    "P5eNVI/WANZxcjamzpI9LyulZHW9u4L2C7C94loeHIKOWz+ZnF6IHUiIhXKjDlDA7VjhLLqp"
    "x2lbd0GQ+rzNHfV5uSUA6F2W2NvNQ8E/6/muPztWWVmMZSPVP9VmPKWUtuSs5O6sQx1h/dXF"
    "XLL67WVHBzw4NmbhN6Qcxy0eIAwPVS/1o+d17KFyhmSNoYrRbngLkwuDd6rQoVcvmbw8Etub"
    "JjVOfzqjUKAAiNSZmo9jYHRXocOK+Z9RyOrtQDvqi3bUzaA2zFh+Gitvv25cVMtoO46Xo10u"
    "0a6STasZDbtgWd4a3SqJdlHgTe2/RWhCBm+qadKiM0w7fcNuatc5vdHW4zYVaIr+iZxe6jvZ"
    "aaHdt6yT1d/1pDkhNlqwQlD1GQCyeudS58NrkOdIxrJwlkcZTL4FYxbb5ey8bMt1dXxYr6kx"
    "J9dZ71bxgle6IHhlpM1d/qxrvCn3I1ayKlQf2RpjOmxNdRzI6ve8SUkBAeD6EZhejjB4AjAw"
    "7bgSdCIHYioVlwowSeg1z5eK7u6OyJE36WOa4clYWHGZXHUyNiK9S0P91fZJY7Ar6hjI6g/Z"
    "WLLFIqzqsJenYVVn8u6MUGCobCoEhiq2tjL9t2jnDxXYHIiUL3wjRjtuOItsfG7Y/anu3RVp"
    "DHZLHQNZ3QmEpt3wUC2CUuEpAefZNocq1FRrCIPUJ8uh4VNiwKGJSq8zc+w2x7zJBam7d0sa"
    "g31Qx0BW7wkPai/vITEPTjtfzDnPwmMWGqqojAVp1349MGYhAbBWSc5Cu4XBRdZdhvymwp4w"
    "7fL0p/sgjcHW3ORRqPpuALK6Z+m+FZHdxK7EGMTzql46NeBuEwB34ybmJlvudtz5LZysP69n"
    "LS8Ytks76JibtN7ABWipSaT+eH+M6bA/1XEgq/viYh4JbpvItFsElSCmEEHXNbg4rp8sCLuu"
    "3ioZyxoElsvQKsmWS3X7BKQxmIw6BrJ6AIi5QRRW9YHgwhmqfszaC+BlTfyIyU/8uP5QaCUK"
    "Lz0hVg0sPdyhia2SraFum4w0BhNTx0BWfwv4YzYoFQNDFZYKrBfchiPwsbyiI2M+9WNZO8eh"
    "GcgaNKRumZg0BklQx0BWf9+vTQOqzsfMCdFXGrPBDJAzVK6MwVaIYNbAy/cM54LXSRaotyZB"
    "GoP9ucmjUPUtAGT1D0uvMPybfo7DGH9hZXlB527baWsnPR1zcp0XeP0LfC94wIjlgp2HWni5"
    "4DcnxJgOCamOA1k9Eglu7bRhLK9jrUfxvGLAoYG1ETbk0MQ0I5QK8r1+30vzHZo3pkgag3Sp"
    "YyCrx4BYXieSAo7l6AZSwLFkHUIJntX3SZwEj5UBiueCzdr0a+mSxiB16hjI6t8ibpAjFcx7"
    "iA3hgD/kyNhwLnhke8T3h3wZi+SCr0udNAbzoI6BrGpb1REaM08hYltaASVwFGI0F8wuWCWv"
    "M5YsUNfOgzQGc6KOgazOhtN3vusTyOuPDSoGEjxrJQvieyaOc2Mye6+fE2kMEoqwVoSql/+q"
    "r6y+BjIxSysM/hk/ft6bKHBUuelOASPyUunqv0Lq734gEMQ1/Ul4ddX8GNNhftTpoOrXAZDV"
    "fwEARl+R5PF2qDxwLtNc32pV7KcFnXcOnQu6ZIEx2pPw6soZk8ZgxtQxUPWVAGT1zHJaO3md"
    "LusTUwgKyVWMf7Ef8w7+cmVExtRlsyeNweypY6DqKwDI6n+W5LDevY0rAbV+jNEeXyGC9HJ+"
    "vGL4ZSi2SqqLD4Q0BgdCHQNVXwpAVv/brkHtoMJeehx6BX9Gw3FoOnenM4LlLqtaL/jCgyKN"
    "wUFRx0DVFxpDVi+2fnQb8vhv2TkCE3wBBbBXQ0fVorsf6rwDZEyHA6ROB1X/FABZveIO8JIu"
    "nr9spGLo1S3mR/s8Y56N0odMGoNDpo6Bqs8BICuyHRq4u6qdYT5yFyzHj46+5aleOXzSGBw+"
    "dQxU/QoAWV0Q8qMx8pan6+iE/SH1g2MhjcGxUMdA1T8AIKuLAdipoI4oYJke28uOv5Crnj8u"
    "0hgcF3UMVP1dY8jqZ0Aw/3KilY9mwVH0x5pA6tljZEyHY6ROB1U/C0BWV4TzOl4KuHdonjlq"
    "0hgcNXUMVP0MAFn9nKsrQYfmyUyaJTJ1llD1kwBk9Xrm2YC7Qeo/M2ksZOpYUPUTAGR1LYBu"
    "wVJnM2kCyNQJQNX/MXUTZoBi6gZkzBWZOhkbIlMnY0Nk6mRsiP8H0trOAD1A8ycAAAAASUVO"
    "RK5CYII=")

[docs]def rad2deg(x):
    """
    Transforms radians into degrees.

    :param `x`: a float representing an angle in radians.
    """

    return 180.0*x/pi

[docs]def deg2rad(x):
    """
    Transforms degrees into radians.

    :param `x`: a float representing an angle in degrees.
    """

    return x*pi/180.0

[docs]def toscale(x):
    """
    Normalize a value as a function of the radius.

    :param `x`: a float value to normalize
    """

    return x*RADIUS/255.0

[docs]def scaletomax(x):
    """
    Normalize a value as a function of the radius.

    :param `x`: a float value to normalize
    """

    return x*255.0/RADIUS

[docs]def rgb2html(colour):
    """
    Transforms a RGB triplet into an html hex string.

    :param `colour`: a tuple of red, green, blue integers.
    """

    hexColour = "#%02x%02x%02x"%(colour.r, colour.g, colour.b)
    return hexColour.upper()

[docs]def Slope(pt1, pt2):
    """
    Calculates the slope of the line connecting 2 points.

    :param `pt1`: an instance of `wx.Point`;
    :param `pt2`: another instance of `wx.Point`.
    """

    y = float(pt2.y - pt1.y)
    x = float(pt2.x - pt1.x)

    if x:
        return y/x
    else:
        return None

[docs]def Intersection(line1, line2):
    """
    Calculates the intersection point between 2 lines.

    :param `line1`: an instance of L{LineDescription};
    :param `line2`: another instance of L{LineDescription}.
    """

    if line1.slope == line2.slope:

        # Parallel lines, no intersection
        return wx.Point(0, 0)

    elif line1.slope is None:

        # First Line is vertical, eqn is x=0
        # Put x = 0 in second line eqn to get y
        x = line1.x
        y = line2.slope*x + line2.c

    elif line2.slope is None:

        # second line is vertical Equation of line is x=0
        # Put x = 0 in first line eqn to get y
        x = line2.x
        y = line1.slope*line2.x + line1.c

    else:

        y = ((line1.c*line2.slope) - (line2.c*line1.slope))/(line2.slope - line1.slope)
        x = (y - line1.c)/line1.slope

    return wx.Point(int(x), int(y))

[docs]def FindC(line):
    """ Internal function. """

    if line.slope is None:
        c = line.y
    else:
        c = line.y - line.slope*line.x

    return c

[docs]def PointOnLine(pt1, pt2, length, maxLen):
    """ Internal function. """

    a = float(length)

    if pt2.x != pt1.x:

        m = float((pt2.y - pt1.y))/(pt2.x - pt1.x)
        m2 = m*m
        a2 = a*a
        c = pt1.y - m*pt1.x
        c2 = c*c

        A = 1.0

        x = pt1.x

        B = 2.0 * pt1.x

        x *= x
        C = x - a2/(m2 + 1)

        x = (B + sqrt(B*B - (4.0*A*C)))/(2.0*A)
        y = m*x + c
        pt = wx.Point(int(x), int(y))

        if Distance(pt, pt1) > maxLen or Distance(pt, pt2) > maxLen:

            x = (B - sqrt(B*B - (4.0*A*C)))/(2.0*A)
            y = m*x + c
            pt = wx.Point(int(x), int(y))

    else:

        a2 = a*a
        y = sqrt(a2)
        x = 0.0
        pt = wx.Point(int(x), int(y))
        pt.x += pt1.x
        pt.y += pt1.y

        if Distance(pt, pt1) > maxLen or Distance(pt, pt2) > maxLen:

            y = -1.0*y
            pt = wx.Point(int(x), int(y))
            pt.x += pt1.x
            pt.y += pt1.y

    return pt

[docs]def Distance(pt1, pt2):
    """
    Returns the distance between 2 points.

    :param `pt1`: an instance of `wx.Point`;
    :param `pt2`: another instance of `wx.Point`.
    """

    distance = sqrt((pt1.x - pt2.x)**2.0 + (pt1.y - pt2.y)**2.0)
    return int(distance)

[docs]def AngleFromPoint(pt, center):
    """
    Returns the angle between the x-axis and the line connecting the center and
    the point `pt`.

    :param `pt`: an instance of `wx.Point`;
    :param `center`: a float value representing the center.
    """

    y = -1*(pt.y - center.y)
    x = pt.x - center.x
    if x == 0 and y == 0:

        return 0.0

    else:

        return atan2(y, x)

[docs]def PtFromAngle(angle, sat, center):
    """
    Given the angle with respect to the x-axis, returns the point based on
    the saturation value.

    :param `angle`: a float representing an angle;
    :param `sat`: a float representing the colour saturation value;
    :param `center`: a float value representing the center.
    """

    angle = deg2rad(angle)
    sat = toscale(sat)

    x = sat*cos(angle)
    y = sat*sin(angle)

    pt = wx.Point(int(x), -int(y))
    pt.x += center.x
    pt.y += center.y

    return pt

[docs]def RestoreOldDC(dc, oldPen, oldBrush, oldMode):
    """
    Restores the old settings for a `wx.DC`.

    :param `dc`: an instance of `wx.DC`;
    :param `oldPen`: an instance of `wx.Pen`;
    :param `oldBrush`: an instance of `wx.Brush`;
    :param `oldMode`: the `wx.DC` drawing mode bit.
    """

    dc.SetPen(oldPen)
    dc.SetBrush(oldBrush)
    dc.SetLogicalFunction(oldMode)

[docs]def DrawCheckerBoard(dc, rect, checkColour, box=5):
    """
    Draws a checkerboard on a `wx.DC`.

    :param `dc`: an instance of `wx.DC`;
    :param `rect`: the client rectangle on which to draw the checkerboard;
    :param `checkColour`: the colour used for the dark checkerboards;
    :param `box`: the checkerboards box sizes.

    :note: Used for the Alpha channel control and the colour panels.
    """

    y = rect.y
    checkPen = wx.Pen(checkColour)
    checkBrush = wx.Brush(checkColour)

    dc.SetPen(checkPen)
    dc.SetBrush(checkBrush)
    dc.SetClippingRect(rect)

    while y < rect.height:
        x = box*((y/box)%2) + 2
        while x < rect.width:
            dc.DrawRectangle(x, y, box, box)
            x += box*2
        y += box

[docs]class Colour(wx.Colour):
    """
    This is a subclass of `wx.Colour`, which adds Hue, Saturation and Brightness
    capability to the base class. It contains also methods to convert RGB triplets
    into HSB triplets and vice-versa.
    """

[docs]    def __init__(self, colour):
        """
        Default class constructor.

        :param `colour`: a standard `wx.Colour`.
        """

        wx.Colour.__init__(self)

        self.r = colour.Red()
        self.g = colour.Green()
        self.b = colour.Blue()
        self._alpha = colour.Alpha()

        self.ToHSV()

[docs]    def ToRGB(self):
        """ Converts a HSV triplet into a RGB triplet. """

        maxVal = self.v
        delta = (maxVal*self.s)/255.0
        minVal = maxVal - delta

        hue = float(self.h)

        if self.h > 300 or self.h <= 60:

            self.r = maxVal

            if self.h > 300:

                self.g = int(minVal)
                hue = (hue - 360.0)/60.0
                self.b = int(-(hue*delta - minVal))

            else:

                self.b = int(minVal)
                hue = hue/60.0
                self.g = int(hue*delta + minVal)

        elif self.h > 60 and self.h < 180:

            self.g = int(maxVal)

            if self.h < 120:

                self.b = int(minVal)
                hue = (hue/60.0 - 2.0)*delta
                self.r = int(minVal - hue)

            else:

                self.r = int(minVal)
                hue = (hue/60.0 - 2.0)*delta
                self.b = int(minVal + hue)

        else:

            self.b = int(maxVal)

            if self.h < 240:

                self.r = int(minVal)
                hue = (hue/60.0 - 4.0)*delta
                self.g = int(minVal - hue)

            else:

                self.g = int(minVal)
                hue = (hue/60.0 - 4.0)*delta
                self.r = int(minVal + hue)

[docs]    def ToHSV(self):
        """ Converts a RGB triplet into a HSV triplet. """

        minVal = float(min(self.r, min(self.g, self.b)))
        maxVal = float(max(self.r, max(self.g, self.b)))
        delta = maxVal - minVal

        self.v = int(maxVal)

        if abs(delta) < 1e-6:

            self.h = self.s = 0

        else:

            temp = delta/maxVal
            self.s = int(temp*255.0)

            if self.r == int(maxVal):

                temp = float(self.g-self.b)/delta

            elif self.g == int(maxVal):

                temp = 2.0 + (float(self.b-self.r)/delta)

            else:

                temp = 4.0 + (float(self.r-self.g)/delta)

            temp *= 60
            if temp < 0:

                temp += 360

            elif temp >= 360.0:

                temp = 0

            self.h = int(temp)

[docs]    def GetPyColour(self):
        """ Returns the wxPython `wx.Colour` associated with this instance. """

        return wx.Colour(self.r, self.g, self.b, self._alpha)

[docs]class LineDescription(object):
    """ Simple class to store description and constants for a line in 2D space. """

[docs]    def __init__(self, x=0, y=0, slope=None, c=None):
        """
        Default class constructor.

        Used internally. Do not call it in your code!

        :param `x`: the x coordinate of the first point;
        :param `y`: the y coordinate of the first point;
        :param `slope`: the line's slope;
        :param `c`: a floating point constant.
        """

        self.x = x
        self.y = y
        self.slope = slope
        self.c = c

[docs]class BasePyControl(wx.PyControl):
    """
    Base class used to hold common code for the HSB colour wheel and the RGB
    colour cube.
    """

[docs]    def __init__(self, parent, bitmap=None):
        """
        Default class constructor.
        Used internally. Do not call it in your code!

        :param `parent`: the control parent;
        :param `bitmap`: the background bitmap for this custom control.
        """

        wx.PyControl.__init__(self, parent, style=wx.NO_BORDER)
        self.SetBackgroundStyle(wx.BG_STYLE_CUSTOM)

        self._bitmap = bitmap
        mask = wx.Mask(self._bitmap, wx.Colour(192, 192, 192))
        self._bitmap.SetMask(mask)

        self._mainDialog = wx.GetTopLevelParent(self)

        self.Bind(wx.EVT_SIZE, self.OnSize)
        self.Bind(wx.EVT_PAINT, self.OnPaint)
        self.Bind(wx.EVT_ERASE_BACKGROUND, self.OnEraseBackground)
        self.Bind(wx.EVT_LEFT_DOWN, self.OnLeftDown)
        self.Bind(wx.EVT_LEFT_UP, self.OnLeftUp)
        self.Bind(wx.EVT_MOTION, self.OnMotion)

[docs]    def OnPaint(self, event):
        """
        Handles the ``wx.EVT_PAINT`` for L{BasePyControl}.

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

        dc = wx.AutoBufferedPaintDC(self)
        dc.SetBackground(wx.Brush(self.GetParent().GetBackgroundColour()))

        dc.Clear()
        dc.DrawBitmap(self._bitmap, 0, 0, True)

        if self._mainDialog._initOver:
            self.DrawMarkers(dc)

[docs]    def OnEraseBackground(self, event):
        """
        Handles the ``wx.EVT_ERASE_BACKGROUND`` for L{BasePyControl}.

        :param `event`: a `wx.EraseEvent` event to be processed.

        :note: This is intentionally empty to reduce flicker.
        """

        pass

[docs]    def DrawMarkers(self, dc=None):
        """
        Draws the markers on top of the background bitmap.

        :param `dc`: an instance of `wx.DC`.

        :note: This method must be overridden in derived classes.
        """

        pass

[docs]    def DrawLines(self, dc):
        """
        Draws the lines connecting the markers on top of the background bitmap.

        :param `dc`: an instance of `wx.DC`.

        :note: This method must be overridden in derived classes.
        """

        pass

[docs]    def AcceptsFocusFromKeyboard(self):
        """
        Can this window be given focus by keyboard navigation? If not, the
        only way to give it focus (provided it accepts it at all) is to click
        it.

        :note: This method always returns ``False`` as we do not accept focus from
         the keyboard.

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

        return False

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

        :note: This method always returns ``False`` as we do not accept focus from
         mouse click.

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

        return False

[docs]    def OnLeftDown(self, event):
        """
        Handles the ``wx.EVT_LEFT_DOWN`` for L{BasePyControl}.

        :param `event`: a `wx.MouseEvent` event to be processed.

        :note: This method must be overridden in derived classes.
        """

        pass

[docs]    def OnLeftUp(self, event):
        """
        Handles the ``wx.EVT_LEFT_UP`` for L{BasePyControl}.

        :param `event`: a `wx.MouseEvent` event to be processed.

        :note: This method must be overridden in derived classes.
        """

        pass

[docs]    def OnMotion(self, event):
        """
        Handles the ``wx.EVT_MOTION`` for L{BasePyControl}.

        :param `event`: a `wx.MouseEvent` event to be processed.

        :note: This method must be overridden in derived classes.
        """

        pass

[docs]    def OnSize(self, event):
        """
        Handles the ``wx.EVT_SIZE`` for L{BasePyControl}.

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

        self.Refresh()

[docs]    def DoGetBestSize(self):
        """
        Overridden base class virtual. Determines the best size of the
        control based on the bitmap size.

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

        return wx.Size(self._bitmap.GetWidth(), self._bitmap.GetHeight())

[docs]class RGBCube(BasePyControl):
    """
    Implements the drawing, mouse handling and sizing routines for the RGB
    cube colour.
    """

[docs]    def __init__(self, parent):
        """
        Default class constructor.
        Used internally. Do not call it in your code!

        :param `parent`: the control parent window.
        """

        BasePyControl.__init__(self, parent, bitmap=RGBCubeImage.GetBitmap())
        self._index = -1

[docs]    def DrawMarkers(self, dc=None):
        """
        Draws the markers on top of the background bitmap.

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

        if dc is None:
            dc = wx.ClientDC(self)

        oldPen, oldBrush, oldMode = dc.GetPen(), dc.GetBrush(), dc.GetLogicalFunction()
        dc.SetPen(wx.WHITE_PEN)
        dc.SetBrush(wx.TRANSPARENT_BRUSH)
        dc.SetLogicalFunction(wx.XOR)

        rects = []
        blueLen = self._mainDialog._blueLen
        greenLen = self._mainDialog._greenLen
        redLen = self._mainDialog._redLen
        colour = self._mainDialog._colour

        pt = [wx.Point() for i in xrange(3)]
        pt[0] = PointOnLine(Vertex, Top, (colour.r*redLen)/255, redLen)
        pt[1] = PointOnLine(Vertex, Left, (colour.g*greenLen)/255, greenLen)
        pt[2] = PointOnLine(Vertex, Right, (colour.b*blueLen)/255, blueLen)

        for i in xrange(3):
            rect = wx.Rect(pt[i].x - RECT_WIDTH, pt[i].y - RECT_WIDTH, 2*RECT_WIDTH, 2*RECT_WIDTH)
            rects.append(rect)
            dc.DrawRectangleRect(rect)

        self.DrawLines(dc)
        RestoreOldDC(dc, oldPen, oldBrush, oldMode)

        self._rects = rects

[docs]    def DrawLines(self, dc):
        """
        Draws the lines connecting the markers on top of the background bitmap.

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

        cuboid = self._mainDialog._cuboid

        dc.DrawLinePoint(cuboid[1], cuboid[2])
        dc.DrawLinePoint(cuboid[2], cuboid[3])
        dc.DrawLinePoint(cuboid[3], cuboid[4])
        dc.DrawLinePoint(cuboid[4], cuboid[5])
        dc.DrawLinePoint(cuboid[5], cuboid[2])

        dc.DrawLinePoint(cuboid[5], cuboid[6])
        dc.DrawLinePoint(cuboid[6], cuboid[7])
        dc.DrawLinePoint(cuboid[7], cuboid[4])

        dc.DrawLinePoint(cuboid[1], cuboid[6])

[docs]    def OnLeftDown(self, event):
        """
        Handles the ``wx.EVT_LEFT_DOWN`` for L{RGBCube}.

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

        point = wx.Point(event.GetX(), event.GetY())
        self._mouseIn = False

        if self._rects[RED].Contains(point):
            self.CaptureMouse()
            self._mouseIn = True
            self._index = RED

        elif self._rects[GREEN].Contains(point):
            self.CaptureMouse()
            self._mouseIn = True
            self._index = GREEN

        elif self._rects[BLUE].Contains(point):
            self.CaptureMouse()
            self._mouseIn = True
            self._index = BLUE

[docs]    def OnLeftUp(self, event):
        """
        Handles the ``wx.EVT_LEFT_UP`` for L{RGBCube}.

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

        if self.GetCapture():
            self.ReleaseMouse()
            self._mouseIn = False

[docs]    def OnMotion(self, event):
        """
        Handles the ``wx.EVT_MOTION`` for L{RGBCube}.

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

        point = wx.Point(event.GetX(), event.GetY())

        if not (self.GetCapture() and self._mouseIn):
            event.Skip()
            return

        bChange = False
        mainDialog = self._mainDialog
        colour = mainDialog._colour
        redLen, greenLen, blueLen = mainDialog._redLen, mainDialog._greenLen, mainDialog._blueLen

        dc = wx.ClientDC(self)
        self.DrawMarkers(dc)

        if self._index == RED:

            if point.y > Vertex.y:
                point.y = Vertex.y

            point.x = Vertex.x
            val = Distance(point, Vertex)
            if val > redLen:
                val = redLen

            val = (float(val)/redLen)*255
            colour.r = int(val)

            pt = PointOnLine(Vertex, Top, (colour.r*redLen)/255, redLen)
            self._rects[RED] = wx.Rect(pt.x - RECT_WIDTH, pt.y - RECT_WIDTH,
                                       2*RECT_WIDTH, 2*RECT_WIDTH)

            bChange = True

        elif self._index == GREEN:

            if point.x > Vertex.x:
                point.x = Vertex.x

            point.y = self._rects[GREEN].GetTop() + RECT_WIDTH
            val = Distance(point, Vertex)
            if val > greenLen:
                val = greenLen

            val = (float(val)/greenLen)*255
            colour.g = int(val)

            pt = PointOnLine(Vertex, Left, (colour.g*greenLen)/255, greenLen)
            self._rects[GREEN] = wx.Rect(pt.x - RECT_WIDTH, pt.y - RECT_WIDTH,
                                         2*RECT_WIDTH, 2*RECT_WIDTH)

            bChange = True

        elif self._index == BLUE:

            if point.x < Vertex.x:
                point.x = Vertex.x

            point.y = self._rects[BLUE].GetTop() + RECT_WIDTH
            val = Distance(point, Vertex)
            if val > blueLen:
                val = blueLen

            val = (float(val)/blueLen)*255
            colour.b = int(val)

            pt = PointOnLine(Vertex, Right, (colour.b*blueLen)/255, blueLen)
            self._rects[BLUE] = wx.Rect(pt.x - RECT_WIDTH, pt.y - RECT_WIDTH,
                                        2*RECT_WIDTH, 2*RECT_WIDTH)

            bChange = True

        if bChange:

            mainDialog.CalcCuboid()
            self.DrawMarkers(dc)

            colour.ToHSV()
            mainDialog.SetSpinVals()
            mainDialog.CalcRects()

            mainDialog.DrawHSB()
            mainDialog.DrawBright()
            mainDialog.DrawAlpha()

[docs]class HSVWheel(BasePyControl):
    """
    Implements the drawing, mouse handling and sizing routines for the HSV
    colour wheel.
    """

[docs]    def __init__(self, parent):
        """
        Default class constructor.
        Used internally. Do not call it in your code!

        :param `parent`: the control parent window.
        """

        BasePyControl.__init__(self, parent, bitmap=HSVWheelImage.GetBitmap())
        self._mouseIn = False

[docs]    def DrawMarkers(self, dc=None):
        """
        Draws the markers on top of the background bitmap.

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

        if dc is None:
            dc = wx.ClientDC(self)

        oldPen, oldBrush, oldMode = dc.GetPen(), dc.GetBrush(), dc.GetLogicalFunction()
        dc.SetPen(wx.WHITE_PEN)
        dc.SetBrush(wx.TRANSPARENT_BRUSH)
        dc.SetLogicalFunction(wx.XOR)

        dc.DrawRectangleRect(self._mainDialog._currentRect)
        RestoreOldDC(dc, oldPen, oldBrush, oldMode)

[docs]    def OnLeftDown(self, event):
        """
        Handles the ``wx.EVT_LEFT_DOWN`` for L{HSVWheel}.

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

        point = wx.Point(event.GetX(), event.GetY())
        self._mouseIn = False

        if self.InCircle(point):
            self._mouseIn = True

        if self._mouseIn:
            self.CaptureMouse()
            self.TrackPoint(point)

[docs]    def OnLeftUp(self, event):
        """
        Handles the ``wx.EVT_LEFT_UP`` for L{HSVWheel}.

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

        if self.GetCapture():
            self.ReleaseMouse()
            self._mouseIn = False

[docs]    def OnMotion(self, event):
        """
        Handles the ``wx.EVT_MOTION`` for L{HSVWheel}.

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

        point = wx.Point(event.GetX(), event.GetY())

        if self.GetCapture() and self._mouseIn:
            self.TrackPoint(point)

[docs]    def InCircle(self, pt):
        """
        Returns whether a point is inside the HSV wheel or not.

        :param `pt`: an instance of `wx.Point`.
        """

        return Distance(pt, self._mainDialog._centre) <= RADIUS

[docs]    def TrackPoint(self, pt):
        """
        Track a mouse event inside the HSV colour wheel.

        :param `pt`: an instance of `wx.Point`.
        """

        if not self._mouseIn:
            return

        dc = wx.ClientDC(self)
        self.DrawMarkers(dc)
        mainDialog = self._mainDialog
        colour = mainDialog._colour

        colour.h = int(rad2deg(AngleFromPoint(pt, mainDialog._centre)))
        if colour.h < 0:
            colour.h += 360

        colour.s = int(scaletomax(Distance(pt, mainDialog._centre)))
        if colour.s > 255:
            colour.s = 255

        mainDialog.CalcRects()
        self.DrawMarkers(dc)
        colour.ToRGB()
        mainDialog.SetSpinVals()

        mainDialog.CalcCuboid()
        mainDialog.DrawRGB()
        mainDialog.DrawBright()
        mainDialog.DrawAlpha()

[docs]class BaseLineCtrl(wx.PyControl):
    """
    Base class used to hold common code for the Alpha channel control and the
    brightness palette control.
    """

[docs]    def __init__(self, parent):
        """
        Default class constructor.
        Used internally. Do not call it in your code!

        :param `parent`: the control parent window.
        """

        wx.PyControl.__init__(self, parent, size=(20, 200), style=wx.NO_BORDER)
        self.SetBackgroundStyle(wx.BG_STYLE_CUSTOM)

        self._mainDialog = wx.GetTopLevelParent(self)

        self.Bind(wx.EVT_SIZE, self.OnSize)
        self.Bind(wx.EVT_ERASE_BACKGROUND, self.OnEraseBackground)
        self.Bind(wx.EVT_LEFT_DOWN, self.OnLeftDown)
        self.Bind(wx.EVT_LEFT_UP, self.OnLeftUp)
        self.Bind(wx.EVT_MOTION, self.OnMotion)

[docs]    def OnEraseBackground(self, event):
        """
        Handles the ``wx.EVT_ERASE_BACKGROUND`` for L{BaseLineCtrl}.

        :param `event`: a `wx.EraseEvent` event to be processed.

        :note: This is intentionally empty to reduce flicker.
        """

        pass

[docs]    def OnLeftDown(self, event):
        """
        Handles the ``wx.EVT_LEFT_DOWN`` for L{BaseLineCtrl}.

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

        point = wx.Point(event.GetX(), event.GetY())
        theRect = self.GetClientRect()

        if not theRect.Contains(point):
            event.Skip()
            return

        self.CaptureMouse()
        self.TrackPoint(point)

[docs]    def OnLeftUp(self, event):
        """
        Handles the ``wx.EVT_LEFT_UP`` for L{BaseLineCtrl}.

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

        if self.GetCapture():
            self.ReleaseMouse()

[docs]    def OnMotion(self, event):
        """
        Handles the ``wx.EVT_MOTION`` for L{BaseLineCtrl}.

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

        point = wx.Point(event.GetX(), event.GetY())

        if self.GetCapture():
            self.TrackPoint(point)

[docs]    def OnSize(self, event):
        """
        Handles the ``wx.EVT_SIZE`` for L{BaseLineCtrl}.

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

        self.Refresh()

[docs]    def DoGetBestSize(self):
        """
        Overridden base class virtual. Determines the best size of the control.

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

        return wx.Size(24, 208)

[docs]    def BuildRect(self):
        """ Internal method. """

        brightRect = wx.Rect(*self.GetClientRect())
        brightRect.x += 2
        brightRect.y += 6
        brightRect.width -= 4
        brightRect.height -= 8

        return brightRect

[docs]    def AcceptsFocusFromKeyboard(self):
        """
        Can this window be given focus by keyboard navigation? If not, the
        only way to give it focus (provided it accepts it at all) is to click
        it.

        :note: This method always returns ``False`` as we do not accept focus from
         the keyboard.

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

        return False

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

        :note: This method always returns ``False`` as we do not accept focus from
         mouse click.

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

        return False

[docs]class BrightCtrl(BaseLineCtrl):
    """
    Implements the drawing, mouse handling and sizing routines for the brightness
    palette control.
    """

[docs]    def __init__(self, parent):
        """
        Default class constructor.
        Used internally. Do not call it in your code!

        :param `parent`: the control parent window.
        """

        BaseLineCtrl.__init__(self, parent)
        self.Bind(wx.EVT_PAINT, self.OnPaint)

[docs]    def OnPaint(self, event):
        """
        Handles the ``wx.EVT_PAINT`` for L{BrightCtrl}.

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

        dc = wx.AutoBufferedPaintDC(self)
        dc.SetBackground(wx.Brush(self.GetParent().GetBackgroundColour()))
        dc.Clear()

        colour = self._mainDialog._colour.GetPyColour()
        brightRect = self.BuildRect()

        target_red = colour.Red()
        target_green = colour.Green()
        target_blue = colour.Blue()

        h, s, v = colorsys.rgb_to_hsv(target_red / 255.0, target_green / 255.0,
                                      target_blue / 255.0)
        v = 1.0
        vstep = 1.0/(brightRect.height-1)

        for y_pos in range(brightRect.y, brightRect.height+brightRect.y):
            r, g, b = [c * 255.0 for c in colorsys.hsv_to_rgb(h, s, v)]
            colour = wx.Colour(int(r), int(g), int(b))
            dc.SetPen(wx.Pen(colour, 1, wx.SOLID))
            dc.DrawRectangle(brightRect.x, y_pos, brightRect.width, 1)
            v = v - vstep

        dc.SetPen(wx.BLACK_PEN)
        dc.SetBrush(wx.TRANSPARENT_BRUSH)
        dc.DrawRectangleRect(brightRect)

        self.DrawMarkers(dc)

[docs]    def TrackPoint(self, pt):
        """
        Tracks a mouse action inside the palette control.

        :param `pt`: an instance of `wx.Point`.
        """

        brightRect = self.BuildRect()
        d = brightRect.GetBottom() - pt.y
        d *= 255
        d /= brightRect.height
        if d < 0:
           d = 0
        if d > 255:
            d = 255;

        mainDialog = self._mainDialog
        colour = mainDialog._colour

        mainDialog.DrawMarkers()
        colour.v = int(d)

        colour.ToRGB()
        mainDialog.SetSpinVals()

        mainDialog.CalcRects()
        mainDialog.CalcCuboid()
        mainDialog.DrawMarkers()
        mainDialog.DrawAlpha()

[docs]    def DrawMarkers(self, dc=None):
        """
        Draws square markers used with mouse gestures.

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

        if dc is None:
            dc = wx.ClientDC(self)

        colour = self._mainDialog._colour
        brightRect = self.BuildRect()

        y = int(colour.v/255.0*brightRect.height)
        y = brightRect.GetBottom() - y
        brightMark = wx.Rect(brightRect.x-2, y-4, brightRect.width+4, 8)

        oldPen, oldBrush, oldMode = dc.GetPen(), dc.GetBrush(), dc.GetLogicalFunction()
        dc.SetPen(wx.Pen(wx.WHITE, 2))
        dc.SetBrush(wx.TRANSPARENT_BRUSH)
        dc.SetLogicalFunction(wx.XOR)

        dc.DrawRectangleRect(brightMark)
        RestoreOldDC(dc, oldPen, oldBrush, oldMode)

[docs]class AlphaCtrl(BaseLineCtrl):
    """
    Implements the drawing, mouse handling and sizing routines for the alpha
    channel control.
    """

[docs]    def __init__(self, parent):
        """
        Default class constructor.
        Used internally. Do not call it in your code!

        :param `parent`: the control parent window.
        """

        BaseLineCtrl.__init__(self, parent)
        self.Bind(wx.EVT_PAINT, self.OnPaint)

[docs]    def OnPaint(self, event):
        """
        Handles the ``wx.EVT_PAINT`` for L{AlphaCtrl}.

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

        pdc = wx.PaintDC(self)
        dc = wx.GCDC(pdc)

        mem_dc = wx.MemoryDC()
        fullRect = self.GetClientRect()
        bmp = wx.EmptyBitmap(fullRect.width, fullRect.height)
        mem_dc.SelectObject(bmp)

        rect = self.BuildRect()
        backBrush = wx.Brush(self.GetParent().GetBackgroundColour())
        mem_dc.SetBackground(backBrush)
        mem_dc.Clear()

        mem_dc.SetBrush(wx.WHITE_BRUSH)
        mem_dc.DrawRectangleRect(rect)

        DrawCheckerBoard(mem_dc, rect, checkColour)
        self.DrawAlphaShading(mem_dc, rect)
        mem_dc.DestroyClippingRegion()

        self.DrawMarkers(mem_dc)

        mem_dc.SetBrush(wx.TRANSPARENT_BRUSH)
        mem_dc.SetPen(wx.BLACK_PEN)
        mem_dc.DrawRectangleRect(rect)

        mem_dc.SelectObject(wx.NullBitmap)
        pdc.DrawBitmap(bmp, 0, 0)

[docs]    def DrawAlphaShading(self, dc, rect):
        """
        Draws the alpha shading on top of the checkerboard.

        :param `dc`: an instance of `wx.DC`;
        :param `rect`: the L{AlphaCtrl} client rectangle.
        """

        gcdc = wx.GCDC(dc)

        colour = self._mainDialog._colour.GetPyColour()

        alpha = 255.0
        vstep = 255.0*2/(rect.height-1)
        r, g, b = colour.Red(), colour.Green(), colour.Blue()

        colour_gcdc = wx.Colour(r, g, b, alpha)
        gcdc.SetBrush(wx.TRANSPARENT_BRUSH)

        for y_pos in range(rect.y, rect.height+rect.y, 2):
            colour_gcdc = wx.Colour(r, g, b, int(alpha))
            gcdc.SetPen(wx.Pen(colour_gcdc, 1, wx.SOLID))
            gcdc.DrawRectangle(rect.x, y_pos, rect.width, 2)
            alpha = alpha - vstep

[docs]    def TrackPoint(self, pt):
        """
        Tracks a mouse action inside the Alpha channel control.

        :param `pt`: an instance of `wx.Point`.
        """

        alphaRect = self.BuildRect()
        d = alphaRect.GetBottom() - pt.y
        d *= 255
        d /= alphaRect.height
        if d < 0:
           d = 0
        if d > 255:
            d = 255

        self._mainDialog._colour._alpha = int(d)
        self.Refresh()
        self._mainDialog.SetSpinVals()

[docs]    def DrawMarkers(self, dc=None):
        """
        Draws square markers used with mouse gestures.

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

        if dc is None:
            dc = wx.ClientDC(self)

        colour = self._mainDialog._colour
        alphaRect = self.BuildRect()

        y = int(colour._alpha/255.0*alphaRect.height)
        y = alphaRect.GetBottom() - y
        alphaMark = wx.Rect(alphaRect.x-2, y-4, alphaRect.width+4, 8)

        oldPen, oldBrush, oldMode = dc.GetPen(), dc.GetBrush(), dc.GetLogicalFunction()
        dc.SetPen(wx.Pen(wx.WHITE, 2))
        dc.SetBrush(wx.TRANSPARENT_BRUSH)
        dc.SetLogicalFunction(wx.XOR)

        dc.DrawRectangleRect(alphaMark)
        RestoreOldDC(dc, oldPen, oldBrush, oldMode)

[docs]class ColourPanel(wx.PyPanel):
    """
    Simple custom class used to display "old" and "new" colour panels, with alpha
    blending capabilities.
    """

[docs]    def __init__(self, parent, style=wx.SIMPLE_BORDER):
        """
        Default class constructor.
        Used internally. Do not call it in your code!

        :param `parent`: the control parent window;
        :param `style`: the L{ColourPanel} window style.
        """

        wx.PyPanel.__init__(self, parent, style=style)
        self._mainDialog = wx.GetTopLevelParent(self)

        self.Bind(wx.EVT_PAINT, self.OnPaint)
        self.Bind(wx.EVT_ERASE_BACKGROUND, self.OnEraseBackground)
        self.Bind(wx.EVT_SIZE, self.OnSize)

        self._colour = Colour(wx.WHITE)

[docs]    def OnPaint(self, event):
        """
        Handles the ``wx.EVT_PAINT`` for L{ColourPanel}.

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

        pdc = wx.PaintDC(self)
        dc = wx.GCDC(pdc)

        mem_dc = wx.MemoryDC()
        rect = self.GetClientRect()
        bmp = wx.EmptyBitmap(rect.width, rect.height)
        mem_dc.SelectObject(bmp)

        backBrush = wx.Brush(self.GetParent().GetBackgroundColour())
        mem_dc.SetBackground(backBrush)
        mem_dc.Clear()

        mem_dc.SetBrush(wx.WHITE_BRUSH)
        mem_dc.DrawRectangleRect(rect)

        DrawCheckerBoard(mem_dc, rect, checkColour, box=10)

        gcdc = wx.GCDC(mem_dc)
        colour_gcdc = wx.Colour(self._colour.r, self._colour.g, self._colour.b, self._colour._alpha)
        gcdc.SetBrush(wx.Brush(colour_gcdc))
        gcdc.SetPen(wx.Pen(colour_gcdc))
        gcdc.DrawRectangleRect(rect)

        mem_dc.SelectObject(wx.NullBitmap)
        dc.DrawBitmap(bmp, 0, 0)

[docs]    def OnEraseBackground(self, event):
        """
        Handles the ``wx.EVT_ERASE_BACKGROUND`` for L{ColourPanel}.

        :param `event`: a `wx.EraseEvent` event to be processed.

        :note: This is intentionally empty to reduce flicker.
        """

        pass

[docs]    def OnSize(self, event):
        """
        Handles the ``wx.EVT_SIZE`` for L{ColourPanel}.

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

        self.Refresh()

[docs]    def RefreshColour(self, colour):
        """
        Refresh the panel after a colour/alpha change.

        :param `colour`: the new background colour of L{ColourPanel}.
        """

        self._colour = colour
        self.Refresh()

[docs]    def AcceptsFocusFromKeyboard(self):
        """
        Can this window be given focus by keyboard navigation? If not, the
        only way to give it focus (provided it accepts it at all) is to click
        it.

        :note: This method always returns ``False`` as we do not accept focus from
         the keyboard.

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

        return False

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

        :note: This method always returns ``False`` as we do not accept focus from
         mouse click.

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

        return False

[docs]class CustomPanel(wx.PyControl):
    """
    This panel displays a series of custom colours (chosen by the user) just like
    the standard `wx.ColourDialog`.
    """

[docs]    def __init__(self, parent, colourData):
        """
        Default class constructor.
        Used internally. Do not call it in your code!

        :param `parent`: the control parent window;
        :param `colourData`: an instance of `wx.ColourData`.
        """

        wx.PyControl.__init__(self, parent, style=wx.NO_BORDER)
        self.SetBackgroundStyle(wx.BG_STYLE_CUSTOM)

        self._colourData = colourData
        self._customColours = [None]*16
        self._mainDialog = wx.GetTopLevelParent(self)

        self.InitializeColours()

        self._smallRectangleSize = wx.Size(20, 16)
        self._gridSpacing = 4
        self._customColourRect = wx.Rect(2, 2, (8*self._smallRectangleSize.x) + (7*self._gridSpacing),
                                         (2*self._smallRectangleSize.y) + (1*self._gridSpacing))

        self.Bind(wx.EVT_PAINT, self.OnPaint)
        self.Bind(wx.EVT_ERASE_BACKGROUND, self.OnEraseBackground)
        self.Bind(wx.EVT_SIZE, self.OnSize)
        self.Bind(wx.EVT_LEFT_DOWN, self.OnLeftDown)

[docs]    def InitializeColours(self):
        """ Initializes the 16 custom colours in L{CustomPanel}. """

        curr = self._colourData.GetColour()
        self._colourSelection = -1

        for i in xrange(16):
            c = self._colourData.GetCustomColour(i)
            if c.Ok():
                self._customColours[i] = self._colourData.GetCustomColour(i)
            else:
                self._customColours[i] = wx.Colour(255, 255, 255)

            if c == curr:
                self._colourSelection = i

[docs]    def DoGetBestSize(self):
        """
        Overridden base class virtual. Determines the best size of the control.

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

        return self._customColourRect.width+4, self._customColourRect.height+4

[docs]    def OnPaint(self, event):
        """
        Handles the ``wx.EVT_PAINT`` for L{CustomPanel}.

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

        dc = wx.AutoBufferedPaintDC(self)
        dc.SetBackground(wx.Brush(self.GetParent().GetBackgroundColour()))
        dc.Clear()

        self.PaintCustomColours(dc)
        self.PaintHighlight(dc, True)

[docs]    def OnEraseBackground(self, event):
        """
        Handles the ``wx.EVT_ERASE_BACKGROUND`` for L{CustomPanel}.

        :param `event`: a `wx.EraseEvent` event to be processed.

        :note: This is intentionally empty to reduce flicker.
        """

        pass

[docs]    def OnSize(self, event):
        """
        Handles the ``wx.EVT_SIZE`` for L{CustomPanel}.

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

        self.Refresh()

[docs]    def OnLeftDown(self, event):
        """
        Handles the ``wx.EVT_LEFT_DOWN`` for L{CustomPanel}.

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

        x, y = event.GetX(), event.GetY()

        selX = (x - self._customColourRect.x)/(self._smallRectangleSize.x + self._gridSpacing)
        selY = (y - self._customColourRect.y)/(self._smallRectangleSize.y + self._gridSpacing)
        ptr = selX + selY*8

        dc = wx.ClientDC(self)
        self.PaintHighlight(dc, False)
        self._colourSelection = ptr

        self._mainDialog._colour = Colour(self._customColours[self._colourSelection])

        self.PaintCustomColour(dc, selX, selY)
        self.PaintHighlight(dc, True)
        self._mainDialog.DrawAll()

[docs]    def PaintCustomColours(self, dc):
        """
        Draws all the 16 subpanels with their custom colours.

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

        for i in xrange(2):
            for j in xrange(8):

                ptr = i*8 + j
                x = (j*(self._smallRectangleSize.x+self._gridSpacing)) + self._customColourRect.x
                y = (i*(self._smallRectangleSize.y+self._gridSpacing)) + self._customColourRect.y

                dc.SetPen(wx.BLACK_PEN)

                brush = wx.Brush(self._customColours[ptr])
                dc.SetBrush(brush)

                dc.DrawRectangle(x, y, self._smallRectangleSize.x, self._smallRectangleSize.y)

[docs]    def PaintHighlight(self, dc, draw=True):
        """
        Highlight the current custom colour selection (if any).

        :param `dc`: an instance of `wx.DC`;
        :param `draw`: whether to draw a thin black border around the selected custom
         colour or not.
        """

        if self._colourSelection < 0:
            return

        # Number of pixels bigger than the standard rectangle size
        # for drawing a highlight
        deltaX = deltaY = 2

        # User-defined colours
        y = self._colourSelection/8
        x = self._colourSelection - (y*8)

        x = (x*(self._smallRectangleSize.x + self._gridSpacing) + self._customColourRect.x) - deltaX
        y = (y*(self._smallRectangleSize.y + self._gridSpacing) + self._customColourRect.y) - deltaY

        if draw:
            dc.SetPen(wx.BLACK_PEN)
        else:
            dc.SetPen(wx.LIGHT_GREY_PEN)

        dc.SetBrush(wx.TRANSPARENT_BRUSH)
        dc.DrawRectangle(x, y, (self._smallRectangleSize.x + (2*deltaX)), (self._smallRectangleSize.y + (2*deltaY)))

[docs]    def PaintCustomColour(self, dc, selX, selY):
        """
        Paints a newly added custom colour subpanel.

        :param `dc`: an instance of `wx.DC`;
        :param `selX`: the x coordinate of the custom colour subpanel;
        :param `selY`: the y coordinate of the custom colour subpanel.
        """

        dc.SetPen(wx.BLACK_PEN)

        brush = wx.Brush(self._customColours[self._colourSelection])
        dc.SetBrush(brush)

        ptr = selX*8 + selY
        x = (selX*(self._smallRectangleSize.x+self._gridSpacing)) + self._customColourRect.x
        y = (selY*(self._smallRectangleSize.y+self._gridSpacing)) + self._customColourRect.y

        dc.DrawRectangle(x, y, self._smallRectangleSize.x, self._smallRectangleSize.y)

        dc.SetBrush(wx.NullBrush)

[docs]    def AddCustom(self, colour):
        """
        Adds a user-chosen colour to the list of custom colours.

        :param `colour`: an instance of `wx.Colour`.
        """

        self._colourSelection += 1
        self._colourSelection = self._colourSelection%16

        dc = wx.ClientDC(self)
        self._customColours[self._colourSelection] = colour.GetPyColour()
        self._colourData.SetCustomColour(self._colourSelection, self._customColours[self._colourSelection])

        self.PaintCustomColours(dc)

[docs]class CubeColourDialog(wx.Dialog):
    """
    This is the CubeColourDialog main class implementation.
    """

[docs]    def __init__(self, parent, colourData=None, agwStyle=CCD_SHOW_ALPHA):
        """
        Default class constructor.

        :param `colourData`: a standard `wx.ColourData` (as used in `wx.ColourDialog`);
        :param `agwStyle`: can be either ``None`` or ``CCD_SHOW_ALPHA``, depending if you want
         to hide the alpha channel control or not.
        """

        wx.Dialog.__init__(self, parent, id=wx.ID_ANY, title=_("CubeColourDialog: Choose Colour"),
                           pos=wx.DefaultPosition, size=(900, 900), style=wx.DEFAULT_DIALOG_STYLE)

        if colourData:
            self._colourData = colourData
        else:
            self._colourData = wx.ColourData()
            self._colourData.SetColour(wx.Colour(128, 128, 128))

        self._colour = Colour(self._colourData.GetColour())
        self._oldColour = Colour(self._colourData.GetColour())

        self._inMouse = False
        self._initOver = False
        self._inDrawAll = False
        self._agwStyle = agwStyle

        self.mainPanel = wx.Panel(self, -1)

        self.hsvSizer_staticbox = wx.StaticBox(self.mainPanel, -1, _("HSB"))
        self.rgbValueSizer_staticbox = wx.StaticBox(self.mainPanel, -1, _("RGB Values"))
        self.hsvValueSizer_staticbox = wx.StaticBox(self.mainPanel, -1, _("HSB Values"))
        self.rgbSizer_staticbox = wx.StaticBox(self.mainPanel, -1, _("RGB"))
        self.alphaSizer_staticbox = wx.StaticBox(self.mainPanel, -1, _("Alpha"))
        self.alphaValueSizer_staticbox = wx.StaticBox(self.mainPanel, -1, _("Alpha"))

        self.rgbBitmap = RGBCube(self.mainPanel)
        self.hsvBitmap = HSVWheel(self.mainPanel)
        self.brightCtrl = BrightCtrl(self.mainPanel)
        self.alphaCtrl = AlphaCtrl(self.mainPanel)

        self.showAlpha = wx.CheckBox(self.mainPanel, -1, _("Show Alpha Control"))
        self.customColours = CustomPanel(self.mainPanel, self._colourData)
        self.addCustom = wx.Button(self.mainPanel, -1, _("Add to custom colours"))

        self.okButton = wx.Button(self.mainPanel, -1, _("OK"))
        self.cancelButton = wx.Button(self.mainPanel, -1, _("Cancel"))

        self.oldColourPanel = ColourPanel(self.mainPanel, style=wx.SIMPLE_BORDER)
        self.newColourPanel = ColourPanel(self.mainPanel, style=wx.SIMPLE_BORDER)

        self.redSpin = wx.SpinCtrl(self.mainPanel, -1, "180", min=0, max=255,
                                   style=wx.SP_ARROW_KEYS)
        self.greenSpin = wx.SpinCtrl(self.mainPanel, -1, "180", min=0, max=255,
                                     style=wx.SP_ARROW_KEYS)
        self.blueSpin = wx.SpinCtrl(self.mainPanel, -1, "180", min=0, max=255,
                                    style=wx.SP_ARROW_KEYS)
        self.hueSpin = wx.SpinCtrl(self.mainPanel, -1, "0", min=0, max=359,
                                   style=wx.SP_ARROW_KEYS)
        self.saturationSpin = wx.SpinCtrl(self.mainPanel, -1, "", min=0, max=255,
                                          style=wx.SP_ARROW_KEYS)
        self.brightnessSpin = wx.SpinCtrl(self.mainPanel, -1, "", min=0, max=255,
                                          style=wx.SP_ARROW_KEYS)
        self.alphaSpin = wx.SpinCtrl(self.mainPanel, -1, "", min=0, max=255,
                                     style=wx.SP_ARROW_KEYS)
        self.accessCode = wx.TextCtrl(self.mainPanel, -1, "", style=wx.TE_READONLY)
        self.htmlCode = wx.TextCtrl(self.mainPanel, -1, "", style=wx.TE_READONLY)
        self.webSafe = wx.TextCtrl(self.mainPanel, -1, "", style=wx.TE_READONLY)
        self.htmlName = wx.TextCtrl(self.mainPanel, -1, "", style=wx.TE_READONLY)

        self.SetProperties()
        self.DoLayout()

        self.spinCtrls = [self.redSpin, self.greenSpin, self.blueSpin,
                          self.hueSpin, self.saturationSpin, self.brightnessSpin]

        for spin in self.spinCtrls:
            spin.Bind(wx.EVT_SPINCTRL, self.OnSpinCtrl)

        self.Bind(wx.EVT_SPINCTRL, self.OnAlphaSpin, self.alphaSpin)

        self.Bind(wx.EVT_BUTTON, self.OnOk, self.okButton)
        self.Bind(wx.EVT_BUTTON, self.OnCancel, self.cancelButton)
        self.Bind(wx.EVT_BUTTON, self.OnAddCustom, self.addCustom)

        self.Bind(wx.EVT_CHECKBOX, self.OnShowAlpha)
        self.Bind(wx.EVT_CLOSE, self.OnCloseWindow)
        self.Bind(wx.EVT_CHAR_HOOK, self.OnKeyUp)

        self.Centre(wx.BOTH)

        wx.CallAfter(self.InitDialog)

[docs]    def SetProperties(self):
        """ Sets some initial properties for L{CubeColourDialog} (sizes, values). """

        self.okButton.SetDefault()
        self.oldColourPanel.SetMinSize((-1, 50))
        self.newColourPanel.SetMinSize((-1, 50))
        self.redSpin.SetMinSize((60, -1))
        self.greenSpin.SetMinSize((60, -1))
        self.blueSpin.SetMinSize((60, -1))
        self.hueSpin.SetMinSize((60, -1))
        self.saturationSpin.SetMinSize((60, -1))
        self.brightnessSpin.SetMinSize((60, -1))
        self.alphaSpin.SetMinSize((60, -1))
        self.showAlpha.SetValue(1)
        self.accessCode.SetInitialSize((80, -1))
        self.webSafe.SetInitialSize((80, -1))
        self.htmlCode.SetInitialSize((80, -1))

[docs]    def DoLayout(self):
        """ Layouts all the controls in the L{CubeColourDialog}. """

        dialogSizer = wx.BoxSizer(wx.VERTICAL)
        mainSizer = wx.GridBagSizer(10, 5)
        hsvValueSizer = wx.StaticBoxSizer(self.hsvValueSizer_staticbox, wx.VERTICAL)
        hsvGridSizer = wx.GridSizer(2, 3, 2, 10)
        rgbValueSizer = wx.StaticBoxSizer(self.rgbValueSizer_staticbox, wx.HORIZONTAL)
        rgbGridSizer = wx.GridSizer(2, 3, 2, 10)
        alphaValueSizer = wx.StaticBoxSizer(self.alphaValueSizer_staticbox, wx.VERTICAL)
        alphaGridSizer = wx.BoxSizer(wx.VERTICAL)
        customSizer = wx.BoxSizer(wx.VERTICAL)
        buttonSizer = wx.BoxSizer(wx.VERTICAL)
        accessSizer = wx.BoxSizer(wx.VERTICAL)
        panelSizer = wx.BoxSizer(wx.VERTICAL)
        htmlSizer1 = wx.BoxSizer(wx.HORIZONTAL)
        htmlSizer2 = wx.BoxSizer(wx.VERTICAL)
        htmlSizer_a = wx.BoxSizer(wx.VERTICAL)
        htmlSizer_b = wx.BoxSizer(wx.VERTICAL)

        hsvSizer = wx.StaticBoxSizer(self.hsvSizer_staticbox, wx.HORIZONTAL)
        rgbSizer = wx.StaticBoxSizer(self.rgbSizer_staticbox, wx.VERTICAL)
        alphaSizer = wx.StaticBoxSizer(self.alphaSizer_staticbox, wx.VERTICAL)

        mainSizer.Add(self.showAlpha, (0, 0), (1, 1), wx.LEFT|wx.TOP, 10)

        htmlLabel1 = wx.StaticText(self.mainPanel, -1, _("HTML Code"))
        htmlLabel2 = wx.StaticText(self.mainPanel, -1, _("Web Safe"))
        htmlSizer_a.Add(htmlLabel1, 0, wx.TOP, 3)
        htmlSizer_b.Add(htmlLabel2, 0, wx.TOP, 3)
        htmlSizer_a.Add(self.htmlCode, 0, wx.TOP, 3)
        htmlSizer_b.Add(self.webSafe, 0, wx.TOP, 3)

        htmlSizer1.Add(htmlSizer_a, 0)
        htmlSizer1.Add(htmlSizer_b, 0, wx.LEFT, 10)
        mainSizer.Add(htmlSizer1, (1, 0), (1, 1), wx.LEFT|wx.RIGHT, 10)

        htmlLabel3 = wx.StaticText(self.mainPanel, -1, _("HTML Name"))
        htmlSizer2.Add(htmlLabel3, 0, wx.TOP|wx.BOTTOM, 3)
        htmlSizer2.Add(self.htmlName, 0)

        mainSizer.Add(htmlSizer2, (1, 1), (1, 1), wx.LEFT|wx.RIGHT, 10)

        customLabel = wx.StaticText(self.mainPanel, -1, _("Custom Colours"))
        customSizer.Add(customLabel, 0, wx.BOTTOM, 3)
        customSizer.Add(self.customColours, 0)
        customSizer.Add(self.addCustom, 0, wx.TOP|wx.ALIGN_LEFT|wx.ALIGN_CENTER_VERTICAL, 5)
        mainSizer.Add(customSizer, (0, 2), (2, 2), wx.ALIGN_CENTER|wx.LEFT|wx.RIGHT, 5)

        rgbSizer.Add(self.rgbBitmap, 0, wx.ALL, 15)
        mainSizer.Add(rgbSizer, (2, 0), (1, 1), wx.ALL|wx.EXPAND, 10)
        hsvSizer.Add(self.hsvBitmap, 0, wx.ALL, 15)
        hsvSizer.Add(self.brightCtrl, 0, wx.RIGHT|wx.TOP|wx.BOTTOM, 15)
        mainSizer.Add(hsvSizer, (2, 1), (1, 1), wx.ALL|wx.EXPAND, 10)
        alphaSizer.Add(self.alphaCtrl, 0, wx.TOP|wx.ALIGN_CENTER, 15)
        mainSizer.Add(alphaSizer, (2, 2), (1, 1), wx.ALL|wx.EXPAND, 10)

        oldLabel = wx.StaticText(self.mainPanel, -1, _("Old Colour"))
        panelSizer.Add(oldLabel, 0, wx.BOTTOM, 3)
        panelSizer.Add(self.oldColourPanel, 0, wx.BOTTOM|wx.EXPAND, 20)
        newLabel = wx.StaticText(self.mainPanel, -1, _("New Colour"))
        accessLabel = wx.StaticText(self.mainPanel, -1, _("MS Access Code"))
        accessSizer.Add(accessLabel, 0, wx.BOTTOM, 3)
        accessSizer.Add(self.accessCode, 0)
        panelSizer.Add(newLabel, 0, wx.BOTTOM, 3)
        panelSizer.Add(self.newColourPanel, 0, wx.EXPAND)
        panelSizer.Add((0, 0), 1, wx.EXPAND)
        panelSizer.Add(accessSizer, 0, wx.TOP, 5)
        mainSizer.Add(panelSizer, (2, 3), (1, 1), wx.ALL|wx.EXPAND, 10)
        redLabel = wx.StaticText(self.mainPanel, -1, _("Red"))
        rgbGridSizer.Add(redLabel, 0)
        greenLabel = wx.StaticText(self.mainPanel, -1, _("Green"))
        rgbGridSizer.Add(greenLabel, 0)
        blueLabel = wx.StaticText(self.mainPanel, -1, _("Blue"))
        rgbGridSizer.Add(blueLabel, 0)
        rgbGridSizer.Add(self.redSpin, 0, wx.EXPAND)
        rgbGridSizer.Add(self.greenSpin, 0, wx.EXPAND)
        rgbGridSizer.Add(self.blueSpin, 0, wx.EXPAND)
        rgbValueSizer.Add(rgbGridSizer, 1, 0, 0)
        mainSizer.Add(rgbValueSizer, (3, 0), (1, 1), wx.LEFT|wx.RIGHT|wx.BOTTOM|wx.EXPAND, 10)
        hueLabel = wx.StaticText(self.mainPanel, -1, _("Hue"))
        hsvGridSizer.Add(hueLabel, 0)
        saturationLabel = wx.StaticText(self.mainPanel, -1, _("Saturation"))
        hsvGridSizer.Add(saturationLabel, 0)
        brightnessLabel = wx.StaticText(self.mainPanel, -1, _("Brightness"))
        hsvGridSizer.Add(brightnessLabel, 0)
        hsvGridSizer.Add(self.hueSpin, 0, wx.EXPAND)
        hsvGridSizer.Add(self.saturationSpin, 0, wx.EXPAND)
        hsvGridSizer.Add(self.brightnessSpin, 0, wx.EXPAND)
        hsvValueSizer.Add(hsvGridSizer, 1, wx.EXPAND)
        mainSizer.Add(hsvValueSizer, (3, 1), (1, 1), wx.LEFT|wx.RIGHT|wx.BOTTOM|wx.EXPAND, 10)
        alphaLabel = wx.StaticText(self.mainPanel, -1, _("Alpha"))
        alphaGridSizer.Add(alphaLabel, 0)
        alphaGridSizer.Add(self.alphaSpin, 0, wx.EXPAND|wx.TOP, 10)
        alphaValueSizer.Add(alphaGridSizer, 1, wx.EXPAND)
        mainSizer.Add(alphaValueSizer, (3, 2), (1, 1), wx.LEFT|wx.RIGHT|wx.BOTTOM|wx.EXPAND, 10)
        buttonSizer.Add(self.okButton, 0, wx.BOTTOM, 3)
        buttonSizer.Add(self.cancelButton, 0)
        mainSizer.Add(buttonSizer, (3, 3), (1, 1), wx.ALIGN_CENTER|wx.LEFT|wx.RIGHT, 5)

        self.mainPanel.SetAutoLayout(True)
        self.mainPanel.SetSizer(mainSizer)
        mainSizer.Fit(self.mainPanel)
        mainSizer.SetSizeHints(self.mainPanel)

        if self.GetAGWWindowStyleFlag() & CCD_SHOW_ALPHA == 0:
            mainSizer.Hide(self.showAlpha)
            mainSizer.Hide(alphaSizer)
            mainSizer.Hide(alphaValueSizer)

        dialogSizer.Add(self.mainPanel, 1, wx.EXPAND)
        self.SetAutoLayout(True)
        self.SetSizer(dialogSizer)
        dialogSizer.Fit(self)
        dialogSizer.SetSizeHints(self)
        self.Layout()

        self.mainSizer = mainSizer
        self.dialogSizer = dialogSizer
        self.alphaSizers = [alphaSizer, alphaValueSizer]

[docs]    def InitDialog(self):
        """ Initialize the L{CubeColourDialog}. """

        hsvRect = self.hsvBitmap.GetClientRect()
        self._centre = wx.Point(hsvRect.x + hsvRect.width/2, hsvRect.y + hsvRect.height/2)

        self._redLen = Distance(Vertex, Top)
        self._greenLen = Distance(Vertex, Left)
        self._blueLen = Distance(Vertex, Right)

        self.CalcSlopes()
        self.CalcCuboid()
        self.CalcRects()

        self.SetSpinVals()

        self._initOver = True
        wx.CallAfter(self.Refresh)

[docs]    def CalcSlopes(self):
        """ Calculates the line slopes in the RGB colour cube. """

        self._lines = {RED: LineDescription(), GREEN: LineDescription(), BLUE: LineDescription}

        self._lines[RED].slope = Slope(Top, Vertex)
        self._lines[GREEN].slope = Slope(Left, Vertex)
        self._lines[BLUE].slope = Slope(Right, Vertex)

        for i in xrange(3):
            self._lines[i].x = Vertex.x
            self._lines[i].y = Vertex.y
            self._lines[i].c = FindC(self._lines[i])

[docs]    def CalcCuboid(self):
        """ Calculates the RGB colour cube vertices. """

        rLen = (self._colour.r*self._redLen)/255.0
        gLen = (self._colour.g*self._greenLen)/255.0
        bLen = (self._colour.b*self._blueLen)/255.0

        lines = [LineDescription() for i in xrange(12)]
        self._cuboid = [None]*8

        self._cuboid[0] = Vertex
        self._cuboid[1] = PointOnLine(Vertex, Top, int(rLen), self._redLen)
        self._cuboid[3] = PointOnLine(Vertex, Left, int(gLen), self._greenLen)
        self._cuboid[7] = PointOnLine(Vertex, Right, int(bLen), self._blueLen)

        lines[0] = self._lines[RED]
        lines[1] = self._lines[GREEN]
        lines[2] = self._lines[BLUE]

        lines[3].slope = self._lines[GREEN].slope
        lines[3].x = self._cuboid[1].x
        lines[3].y = self._cuboid[1].y
        lines[3].c = FindC(lines[3])

        lines[4].slope = self._lines[RED].slope
        lines[4].x = self._cuboid[3].x
        lines[4].y = self._cuboid[3].y
        lines[4].c = FindC(lines[4])

        lines[5].slope = self._lines[BLUE].slope
        lines[5].x = self._cuboid[3].x
        lines[5].y = self._cuboid[3].y
        lines[5].c = FindC(lines[5])

        lines[6].slope = self._lines[GREEN].slope
        lines[6].x = self._cuboid[7].x
        lines[6].y = self._cuboid[7].y
        lines[6].c = FindC(lines[6])

        lines[10].slope = self._lines[BLUE].slope
        lines[10].x = self._cuboid[1].x
        lines[10].y = self._cuboid[1].y
        lines[10].c = FindC(lines[10])

        lines[11].slope = self._lines[RED].slope
        lines[11].x = self._cuboid[7].x
        lines[11].y = self._cuboid[7].y
        lines[11].c = FindC(lines[11])

        self._cuboid[2] = Intersection(lines[3], lines[4])
        self._cuboid[4] = Intersection(lines[5], lines[6])
        self._cuboid[6] = Intersection(lines[10], lines[11])

        lines[7].slope = self._lines[RED].slope
        lines[7].x = self._cuboid[4].x
        lines[7].y = self._cuboid[4].y
        lines[7].c = FindC(lines[7])

        lines[8].slope = self._lines[BLUE].slope
        lines[8].x = self._cuboid[2].x
        lines[8].y = self._cuboid[2].y
        lines[8].c = FindC(lines[8])

        self._cuboid[5] = Intersection(lines[7], lines[8])

[docs]    def CalcRects(self):
        """ Calculates the brightness control user-selected rect. """

        pt = PtFromAngle(self._colour.h, self._colour.s, self._centre)
        self._currentRect = wx.Rect(pt.x - RECT_WIDTH, pt.y - RECT_WIDTH,
                                    2*RECT_WIDTH, 2*RECT_WIDTH)

[docs]    def DrawMarkers(self, dc=None):
        """
        Draws the markers for all the controls.

        :param `dc`: an instance of `wx.DC`. If `dc` is ``None``, a `wx.ClientDC` is
         created on the fly.
        """

        if dc is None:
            dc = wx.ClientDC(self)

        self.hsvBitmap.DrawMarkers()
        self.rgbBitmap.DrawMarkers()
        self.brightCtrl.DrawMarkers()

[docs]    def DrawRGB(self):
        """ Refreshes the RGB colour cube. """

        self.rgbBitmap.Refresh()

[docs]    def DrawHSB(self):
        """ Refreshes the HSB colour wheel. """

        self.hsvBitmap.Refresh()

[docs]    def DrawBright(self):
        """ Refreshes the brightness control. """

        self.brightCtrl.Refresh()

[docs]    def DrawAlpha(self):
        """ Refreshes the alpha channel control. """

        self.alphaCtrl.Refresh()

[docs]    def SetSpinVals(self):
        """ Sets the values for all the spin controls. """

        self.redSpin.SetValue(self._colour.r)
        self.greenSpin.SetValue(self._colour.g)
        self.blueSpin.SetValue(self._colour.b)

        self.hueSpin.SetValue(self._colour.h)
        self.saturationSpin.SetValue(self._colour.s)
        self.brightnessSpin.SetValue(self._colour.v)

        self.alphaSpin.SetValue(self._colour._alpha)

        self.SetPanelColours()
        self.SetCodes()

[docs]    def SetPanelColours(self):
        """ Assigns colours to the colour panels. """

        self.oldColourPanel.RefreshColour(self._oldColour)
        self.newColourPanel.RefreshColour(self._colour)

[docs]    def SetCodes(self):
        """ Sets the HTML/MS Access codes (if any) in the text controls. """

        colour = rgb2html(self._colour)
        self.htmlCode.SetValue(colour)
        self.htmlCode.Refresh()

        if colour in HTMLCodes:
            colourName, access, webSafe = HTMLCodes[colour]
            self.webSafe.SetValue(webSafe)
            self.accessCode.SetValue(access)
            self.htmlName.SetValue(colourName)
        else:
            self.webSafe.SetValue("")
            self.accessCode.SetValue("")
            self.htmlName.SetValue("")

[docs]    def OnCloseWindow(self, event):
        """
        Handles the ``wx.EVT_CLOSE`` event for L{CubeColourDialog}.

        :param `event`: a `wx.CloseEvent` event to be processed.
        """

        self.EndModal(wx.ID_CANCEL)

[docs]    def OnKeyUp(self, event):
        """
        Handles the ``wx.EVT_CHAR_HOOK`` event for L{CubeColourDialog}.

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

        if event.GetKeyCode() == wx.WXK_ESCAPE:
            self.EndModal(wx.ID_CANCEL)

        event.Skip()

[docs]    def ShowModal(self):
        """
        Shows L{CubeColourDialog} as a modal dialog. Program flow does
        not return until the dialog has been dismissed with `EndModal`.

        :note: Overridden from `wx.Dialog`.
        """

        return wx.Dialog.ShowModal(self)

[docs]    def SetAGWWindowStyleFlag(self, agwStyle):
        """
        Sets the L{CubeColourDialog} window style flags.

        :param `agwStyle`: can only be ``CCD_SHOW_ALPHA`` or ``None``.
        """

        show = self.GetAGWWindowStyleFlag() & CCD_SHOW_ALPHA
        self._agwStyle = agwStyle

        self.mainSizer.Show(self.alphaSizers[0], show)
        self.mainSizer.Show(self.alphaSizers[1], show)

        self.mainSizer.Fit(self.mainPanel)
        self.mainSizer.SetSizeHints(self.mainPanel)
        self.mainSizer.Layout()
        self.dialogSizer.Fit(self)
        self.dialogSizer.SetSizeHints(self)
        self.Layout()

        self.Refresh()
        self.Update()

[docs]    def GetAGWWindowStyleFlag(self):
        """
        Returns the L{CubeColourDialog} window style flags.

        :see: L{SetAGWWindowStyleFlag} for a list of possible flags.
        """

        return self._agwStyle

[docs]    def OnOk(self, event):
        """
        Handles the Ok ``wx.EVT_BUTTON`` event for L{CubeColourDialog}.

        :param `event`: a `wx.CommandEvent` event to be processed.
        """

        self.EndModal(wx.ID_OK)

[docs]    def OnCancel(self, event):
        """
        Handles the Cancel ``wx.EVT_BUTTON`` event for L{CubeColourDialog}.

        :param `event`: a `wx.CommandEvent` event to be processed.
        """

        self.OnCloseWindow(event)

[docs]    def OnAddCustom(self, event):
        """
        Handles the Add Custom ``wx.EVT_BUTTON`` event for L{CubeColourDialog}.

        :param `event`: a `wx.CommandEvent` event to be processed.
        """

        self.customColours.AddCustom(self._colour)

[docs]    def OnShowAlpha(self, event):
        """
        Shows/hides the alpha channel control in L{CubeColourDialog}.

        :param `event`: a `wx.CommandEvent` event to be processed.
        """

        agwStyle = self.GetAGWWindowStyleFlag()
        show = event.IsChecked()

        if show:
            agwStyle |= CCD_SHOW_ALPHA
        else:
            agwStyle &= ~CCD_SHOW_ALPHA

        self.SetAGWWindowStyleFlag(agwStyle)

[docs]    def OnSpinCtrl(self, event):
        """
        Handles the ``wx.EVT_SPINCTRL`` event for RGB and HSB colours.

        :param `event`: a `wx.SpinEvent` event to be processed.
        """

        obj = event.GetEventObject()
        position = self.spinCtrls.index(obj)
        colourVal = event.GetInt()

        attribute, maxVal = colourAttributes[position], colourMaxValues[position]

        self.AssignColourValue(attribute, colourVal, maxVal, position)

[docs]    def OnAlphaSpin(self, event):
        """
        Handles the ``wx.EVT_SPINCTRL`` event for the alpha channel.

        :param `event`: a `wx.SpinEvent` event to be processed.
        """

        colourVal = event.GetInt()
        originalVal = self._colour._alpha
        if colourVal != originalVal and self._initOver:
            if colourVal < 0:
                colourVal = 0
            if colourVal > 255:
                colourVal = 255

            self._colour._alpha = colourVal
            self.DrawAlpha()

[docs]    def AssignColourValue(self, attribute, colourVal, maxVal, position):
        """ Common code to handle spin control changes. """

        originalVal = getattr(self._colour, attribute)
        if colourVal != originalVal and self._initOver:

            if colourVal < 0:
                colourVal = 0
            if colourVal > maxVal:
                colourVal = maxVal

            setattr(self._colour, attribute, colourVal)
            if position < 3:
                self._colour.ToHSV()
            else:
                self._colour.ToRGB()

            self.DrawAll()

[docs]    def DrawAll(self):
        """ Draws all the custom controls after a colour change. """

        if self._initOver and not self._inDrawAll:
            self._inDrawAll = True

            dc1 = wx.ClientDC(self.hsvBitmap)
            self.hsvBitmap.DrawMarkers(dc1)

            dc2 = wx.ClientDC(self.rgbBitmap)
            self.rgbBitmap.DrawMarkers(dc2)
            self.rgbBitmap.DrawLines(dc2)

            dc3 = wx.ClientDC(self.brightCtrl)
            self.brightCtrl.DrawMarkers(dc3)

            dc4 = wx.ClientDC(self.alphaCtrl)
            self.alphaCtrl.DrawMarkers(dc4)

            self.CalcCuboid()
            self.CalcRects()

            self.DrawRGB()
            self.DrawHSB()
            self.DrawBright()
            self.DrawAlpha()

            self.SetSpinVals()
            self._inDrawAll = False

[docs]    def GetColourData(self):
        """ Returns a wxPython compatible `wx.ColourData`. """

        self._colourData.SetColour(self._colour.GetPyColour())
        return self._colourData

[docs]    def GetRGBAColour(self):
        """ Returns a 4-elements tuple of red, green, blue, alpha components. """

        return (self._colour.r, self._colour.g, self._colour.b, self._colour._alpha)

[docs]    def GetHSVAColour(self):
        """ Returns a 4-elements tuple of hue, saturation, brightness, alpha components. """

        return (self._colour.h, self._colour.s, self._colour.v, self._colour._alpha)

Navigation

  • index
  • modules |
  • Home |
  • Gallery |
  • Contents»
  • Module code »
  • cubecolourdialog


customtreectrl

  • modules |
  • Home |
  • Gallery |
  • Contents»
  • Module code »
  • customtreectrl

Source code for customtreectrl

# --------------------------------------------------------------------------------- #
# CUSTOMTREECTRL wxPython IMPLEMENTATION
# Inspired By And Heavily Based On wxGenericTreeCtrl.
#
# Andrea Gavana, @ 17 May 2006
# Latest Revision: 10 Mar 2012, 21.00 GMT
#
#
# TODO List
#
# Almost All The Features Of wx.TreeCtrl Are Available, And There Is Practically
# No Limit In What Could Be Added To This Class. The First Things That Comes
# To My Mind Are:
#
# 1. Try To Implement A More Flicker-Free Background Image In Cases Like
#    Centered Or Stretched Image (Now CustomTreeCtrl Supports Only Tiled
#    Background Images).
#
# 2. Try To Mimic Windows wx.TreeCtrl Expanding/Collapsing behaviour: CustomTreeCtrl
#    Suddenly Expands/Collapses The Nodes On Mouse Click While The Native Control
#    Has Some Kind Of "Smooth" Expanding/Collapsing, Like A Wave. I Don't Even
#    Know Where To Start To Do That.
#
# 3. Speed Up General OnPaint Things? I Have No Idea, Here CustomTreeCtrl Is Quite
#    Fast, But We Should See On Slower Machines.
#
#
# For All Kind Of Problems, Requests Of Enhancements And Bug Reports, Please
# Write To Me At:
#
# andrea.gavana@maerskoil.com
# andrea.gavana@gmail.com
#
# Or, Obviously, To The wxPython Mailing List!!!
#
#
# End Of Comments
# --------------------------------------------------------------------------------- #

"""
L{CustomTreeCtrl} is a class that mimics the behaviour of `wx.TreeCtrl`, with some more
enhancements.

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

L{CustomTreeCtrl} is a class that mimics the behaviour of `wx.TreeCtrl`, with almost the
same base functionalities plus some more enhancements. This class does not rely on
the native control, as it is a full owner-drawn tree control.
Apart of the base functionalities of L{CustomTreeCtrl} (described below), in addition
to the standard `wx.TreeCtrl` behaviour this class supports:

* CheckBox-type items: checkboxes are easy to handle, just selected or unselected
  state with no particular issues in handling the item's children;
* Added support for 3-state value checkbox items;
* RadioButton-type items: since I elected to put radiobuttons in L{CustomTreeCtrl}, I
  needed some way to handle them, that made sense. So, I used the following approach:

  - All peer-nodes that are radiobuttons will be mutually exclusive. In other words,
    only one of a set of radiobuttons that share a common parent can be checked at
    once. If a radiobutton node becomes checked, then all of its peer radiobuttons
    must be unchecked.
  - If a radiobutton node becomes unchecked, then all of its child nodes will become
    inactive.

* Hyperlink-type items: they look like an hyperlink, with the proper mouse cursor on
  hovering;
* Multiline text items (**note**: to add a newline character in a multiline item, press
  ``Shift`` + ``Enter`` as the ``Enter`` key alone is consumed by L{CustomTreeCtrl} to finish
  the editing and ``Ctrl`` + ``Enter`` is consumed by the platform for tab navigation);
* Enabling/disabling items (together with their plain or grayed out icons);
* Whatever non-toplevel widget can be attached next to an item;
* Possibility to horizontally align the widgets attached to tree items on the
  same tree level.
* Possibility to align the widgets attached to tree items to the rightmost edge of L{CustomTreeCtrl};
* Default selection style, gradient (horizontal/vertical) selection style and Windows
  Vista selection style;
* Customized drag and drop images built on the fly;
* Setting the L{CustomTreeCtrl} item buttons to a personalized imagelist;
* Setting the L{CustomTreeCtrl} check/radio item icons to a personalized imagelist;
* Changing the style of the lines that connect the items (in terms of `wx.Pen` styles);
* Using an image as a L{CustomTreeCtrl} background (currently only in "tile" mode);
* Adding images to any item in the leftmost area of the L{CustomTreeCtrl} client window.
* Separator-type items which are simply visual indicators that are meant to set apart
  or divide tree items, with the following caveats:

  - Separator items should not have children, labels, data or an associated window;
  - You can change the color of individual separators by using L{SetItemTextColour}, or you can use
    L{SetSeparatorColour} to change the color of all separators. The default separator colour
    is that returned by `wx.SystemSettings.GetColour(wx.SYS_COLOUR_GRAYTEXT)`;
  - Separators can be selected just like any other tree item;
  - Separators cannot have text;
  - Separators cannot have children;
  - Separators cannot be edited via the ``EVT_TREE_BEGIN_LABEL_EDIT`` event.

* Ellipsization of long items when the horizontal space is low, via the ``TR_ELLIPSIZE_LONG_ITEMS``
  style (`New in version 0.9.3`);
* Tooltips on long items when the horizontal space is low, via the ``TR_TOOLTIP_ON_LONG_ITEMS``
  style (`New in version 0.9.3`).

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

Base Functionalities
====================

L{CustomTreeCtrl} supports all the `wx.TreeCtrl` styles, except:

- ``TR_EXTENDED``: supports for this style is on the todo list (am I sure of this?).

Plus it has 3 more styles to handle checkbox-type items:

- ``TR_AUTO_CHECK_CHILD``: automatically checks/unchecks the item children;
- ``TR_AUTO_CHECK_PARENT``: automatically checks/unchecks the item parent;
- ``TR_AUTO_TOGGLE_CHILD``: automatically toggles the item children.

And two styles you can use to force the horizontal alignment of all the widgets
attached to the tree items:

- ``TR_ALIGN_WINDOWS``: aligns horizontally the windows belonging to the item on the
  same tree level.
- ``TR_ALIGN_WINDOWS_RIGHT``: aligns to the rightmost position the windows belonging
  to the item on the same tree level.

And two styles related to long items (with a lot of text in them), which can be
ellipsized and/or highlighted with a tooltip:

- ``TR_ELLIPSIZE_LONG_ITEMS``: ellipsizes long items when the horizontal space for
  L{CustomTreeCtrl} is low (`New in version 0.9.3`);
- ``TR_TOOLTIP_ON_LONG_ITEMS``: shows tooltips on long items when the horizontal space
  for L{CustomTreeCtrl} is low (`New in version 0.9.3`);.

All the methods available in `wx.TreeCtrl` are also available in L{CustomTreeCtrl}.

Usage
=====

Usage example::

    import wx
    import wx.lib.agw.customtreectrl as CT

    class MyFrame(wx.Frame):

        def __init__(self, parent):

            wx.Frame.__init(self, parent, -1, "CustomTreeCtrl Demo")

            # Create a CustomTreeCtrl instance
            custom_tree = CT.CustomTreeCtrl(self, agwStyle=wx.TR_DEFAULT_STYLE)

            # Add a root node to it
            root = custom_tree.AddRoot("The Root Item")

            # Create an image list to add icons next to an item
            il = wx.ImageList(16, 16)
            fldridx     = il.Add(wx.ArtProvider_GetBitmap(wx.ART_FOLDER,      wx.ART_OTHER, 16))
            fldropenidx = il.Add(wx.ArtProvider_GetBitmap(wx.ART_FILE_OPEN,   wx.ART_OTHER, 16))
            fileidx     = il.Add(wx.ArtProvider_GetBitmap(wx.ART_NORMAL_FILE, wx.ART_OTHER, 16))

            custom_tree.SetImageList(il)

            custom_tree.SetItemImage(root, fldridx, wx.TreeItemIcon_Normal)
            custom_tree.SetItemImage(root, fldropenidx, wx.TreeItemIcon_Expanded)

            for x in range(15):
                child = custom_tree.AppendItem(root, "Item %d" % x)
                custom_tree.SetItemImage(child, fldridx, wx.TreeItemIcon_Normal)
                custom_tree.SetItemImage(child, fldropenidx, wx.TreeItemIcon_Expanded)

                for y in range(5):
                    last = custom_tree.AppendItem(child, "item %d-%s" % (x, chr(ord("a")+y)))
                    custom_tree.SetItemImage(last, fldridx, wx.TreeItemIcon_Normal)
                    custom_tree.SetItemImage(last, fldropenidx, wx.TreeItemIcon_Expanded)

                    for z in range(5):
                        item = custom_tree.AppendItem(last,  "item %d-%s-%d" % (x, chr(ord("a")+y), z))
                        custom_tree.SetItemImage(item, fileidx, wx.TreeItemIcon_Normal)
                        custom_tree.SetItemImage(item, smileidx, wx.TreeItemIcon_Selected)

            custom_tree.Expand(self.root)

    # our normal wxApp-derived class, as usual

    app = wx.PySimpleApp()

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

    app.MainLoop()

Events
======

All the events supported by `wx.TreeCtrl` are also available in L{CustomTreeCtrl}, with
a few exceptions:

- ``EVT_TREE_GET_INFO`` (don't know what this means);
- ``EVT_TREE_SET_INFO`` (don't know what this means);
- ``EVT_TREE_ITEM_MIDDLE_CLICK`` (not implemented, but easy to add);
- ``EVT_TREE_STATE_IMAGE_CLICK`` (no need for that, look at the checking events below).

Plus, L{CustomTreeCtrl} supports the events related to the checkbutton-type items:

- ``EVT_TREE_ITEM_CHECKING``: an item is being checked;
- ``EVT_TREE_ITEM_CHECKED``: an item has been checked.

And to hyperlink-type items:

- ``EVT_TREE_ITEM_HYPERLINK``: an hyperlink item has been clicked (this event is sent
  after the ``EVT_TREE_SEL_CHANGED`` event).

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

L{CustomTreeCtrl} has been tested on the following platforms:
  * Windows (Windows XP);
  * GTK (Thanks to Michele Petrazzo);
  * Mac OS (Thanks to John Jackson).

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

This class supports the following window styles:

============================== =========== ==================================================
Window Styles                  Hex Value   Description
============================== =========== ==================================================
``TR_NO_BUTTONS``                      0x0 For convenience to document that no buttons are to be drawn.
``TR_SINGLE``                          0x0 For convenience to document that only one item may be selected at a time. Selecting another item causes the current selection, if any, to be deselected. This is the default.
``TR_HAS_BUTTONS``                     0x1 Use this style to show + and - buttons to the left of parent items.
``TR_NO_LINES``                        0x4 Use this style to hide vertical level connectors.
``TR_LINES_AT_ROOT``                   0x8 Use this style to show lines between root nodes. Only applicable if ``TR_HIDE_ROOT`` is set and ``TR_NO_LINES`` is not set.
``TR_DEFAULT_STYLE``                   0x9 The set of flags that are closest to the defaults for the native control for a particular toolkit.
``TR_TWIST_BUTTONS``                  0x10 Use old Mac-twist style buttons.
``TR_MULTIPLE``                       0x20 Use this style to allow a range of items to be selected. If a second range is selected, the current range, if any, is deselected.
``TR_EXTENDED``                       0x40 Use this style to allow disjoint items to be selected. (Only partially implemented; may not work in all cases).
``TR_HAS_VARIABLE_ROW_HEIGHT``        0x80 Use this style to cause row heights to be just big enough to fit the content. If not set, all rows use the largest row height. The default is that this flag is unset.
``TR_EDIT_LABELS``                   0x200 Use this style if you wish the user to be able to edit labels in the tree control.
``TR_ROW_LINES``                     0x400 Use this style to draw a contrasting border between displayed rows.
``TR_HIDE_ROOT``                     0x800 Use this style to suppress the display of the root node, effectively causing the first-level nodes to appear as a series of root nodes.
``TR_FULL_ROW_HIGHLIGHT``           0x2000 Use this style to have the background colour and the selection highlight extend  over the entire horizontal row of the tree control window.
``TR_AUTO_CHECK_CHILD``             0x4000 Only meaningful foe checkbox-type items: when a parent item is checked/unchecked its children are checked/unchecked as well.
``TR_AUTO_TOGGLE_CHILD``            0x8000 Only meaningful foe checkbox-type items: when a parent item is checked/unchecked its children are toggled accordingly.
``TR_AUTO_CHECK_PARENT``           0x10000 Only meaningful foe checkbox-type items: when a child item is checked/unchecked its parent item is checked/unchecked as well.
``TR_ALIGN_WINDOWS``               0x20000 Flag used to align windows (in items with windows) at the same horizontal position.
``TR_ALIGN_WINDOWS_RIGHT``         0x40000 Flag used to align windows (in items with windows) to the rightmost edge of L{CustomTreeCtrl}.
``TR_ELLIPSIZE_LONG_ITEMS``        0x80000 Flag used to ellipsize long items when the horizontal space for L{CustomTreeCtrl} is low.
``TR_TOOLTIP_ON_LONG_ITEMS``      0x100000 Flag used to show tooltips on long items when the horizontal space for L{CustomTreeCtrl} is low.
============================== =========== ==================================================

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

This class processes the following events:

============================== ==================================================
Event Name                     Description
============================== ==================================================
``EVT_TREE_BEGIN_DRAG``        Begin dragging with the left mouse button.
``EVT_TREE_BEGIN_LABEL_EDIT``  Begin editing a label. This can be prevented by calling L{Veto}.
``EVT_TREE_BEGIN_RDRAG``       Begin dragging with the right mouse button.
``EVT_TREE_DELETE_ITEM``       Delete an item.
``EVT_TREE_END_DRAG``          End dragging with the left or right mouse button.
``EVT_TREE_END_LABEL_EDIT``    End editing a label. This can be prevented by calling L{Veto}.
``EVT_TREE_GET_INFO``          Request information from the application (not implemented in L{CustomTreeCtrl}).
``EVT_TREE_ITEM_ACTIVATED``    The item has been activated, i.e. chosen by double clicking it with mouse or from keyboard.
``EVT_TREE_ITEM_CHECKED``      A checkbox or radiobox type item has been checked.
``EVT_TREE_ITEM_CHECKING``     A checkbox or radiobox type item is being checked.
``EVT_TREE_ITEM_COLLAPSED``    The item has been collapsed.
``EVT_TREE_ITEM_COLLAPSING``   The item is being collapsed. This can be prevented by calling L{Veto}.
``EVT_TREE_ITEM_EXPANDED``     The item has been expanded.
``EVT_TREE_ITEM_EXPANDING``    The item is being expanded. This can be prevented by calling L{Veto}.
``EVT_TREE_ITEM_GETTOOLTIP``   The opportunity to set the item tooltip is being given to the application (call `TreeEvent.SetToolTip`).
``EVT_TREE_ITEM_HYPERLINK``    An hyperlink type item has been clicked.
``EVT_TREE_ITEM_MENU``         The context menu for the selected item has been requested, either by a right click or by using the menu key.
``EVT_TREE_ITEM_MIDDLE_CLICK`` The user has clicked the item with the middle mouse button (not implemented in L{CustomTreeCtrl}).
``EVT_TREE_ITEM_RIGHT_CLICK``  The user has clicked the item with the right mouse button.
``EVT_TREE_KEY_DOWN``          A key has been pressed.
``EVT_TREE_SEL_CHANGED``       Selection has changed.
``EVT_TREE_SEL_CHANGING``      Selection is changing. This can be prevented by calling L{Veto}.
``EVT_TREE_SET_INFO``          Information is being supplied to the application (not implemented in L{CustomTreeCtrl}).
``EVT_TREE_STATE_IMAGE_CLICK`` The state image has been clicked (not implemented in L{CustomTreeCtrl}).
============================== ==================================================

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

L{CustomTreeCtrl} is distributed under the wxPython license.

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

Version 2.6

"""

# Version Info
__version__ = "2.6"

import wx
from wx.lib.expando import ExpandoTextCtrl

# ----------------------------------------------------------------------------
# Constants
# ----------------------------------------------------------------------------

_NO_IMAGE = -1
_PIXELS_PER_UNIT = 10

# Start editing the current item after half a second (if the mouse hasn't
# been clicked/moved)
_DELAY = 500

# wxPython version string
_VERSION_STRING = wx.VERSION_STRING

# ----------------------------------------------------------------------------
# Constants
# ----------------------------------------------------------------------------

# Enum for different images associated with a treectrl item
TreeItemIcon_Normal = 0              # not selected, not expanded
""" The tree item is not selected and not expanded. """
TreeItemIcon_Selected = 1            #     selected, not expanded
""" The tree item is selected and not expanded. """
TreeItemIcon_Expanded = 2            # not selected,     expanded
""" The tree item is not selected but expanded. """
TreeItemIcon_SelectedExpanded = 3    #     selected,     expanded
""" The tree item is selected and expanded. """
TreeItemIcon_Checked = 0             # check button,     checked
""" The item's check button is checked. """
TreeItemIcon_NotChecked = 1          # check button, not checked
""" The item's check button is not checked. """
TreeItemIcon_Undetermined = 2        # check button, undetermined
""" The item's check button is in undetermined state (used only for a 3-state check button). """
TreeItemIcon_Flagged = 3             # radio button,     selected
""" The item's radio button is checked. """
TreeItemIcon_NotFlagged = 4          # radio button, not selected
""" The item's radio button is not checked. """

# ----------------------------------------------------------------------------
# CustomTreeCtrl flags
# ----------------------------------------------------------------------------

TR_NO_BUTTONS = wx.TR_NO_BUTTONS                               # for convenience
""" For convenience to document that no buttons are to be drawn. """
TR_HAS_BUTTONS = wx.TR_HAS_BUTTONS                             # draw collapsed/expanded btns
""" Use this style to show + and - buttons to the left of parent items. """
TR_NO_LINES = wx.TR_NO_LINES                                   # don't draw lines at all
""" Use this style to hide vertical level connectors. """
TR_LINES_AT_ROOT = wx.TR_LINES_AT_ROOT                         # connect top-level nodes
""" Use this style to show lines between root nodes. Only applicable if ``TR_HIDE_ROOT`` is""" \
""" set and ``TR_NO_LINES`` is not set. """
TR_TWIST_BUTTONS = wx.TR_TWIST_BUTTONS                         # still used by wxTreeListCtrl
""" Use old Mac-twist style buttons. """
TR_SINGLE = wx.TR_SINGLE                                       # for convenience
""" For convenience to document that only one item may be selected at a time. Selecting another""" \
""" item causes the current selection, if any, to be deselected. This is the default. """
TR_MULTIPLE = wx.TR_MULTIPLE                                   # can select multiple items
""" Use this style to allow a range of items to be selected. If a second range is selected,""" \
""" the current range, if any, is deselected. """
TR_EXTENDED = wx.TR_EXTENDED                                   # TODO: allow extended selection
""" Use this style to allow disjoint items to be selected. (Only partially implemented;""" \
""" may not work in all cases). """
TR_HAS_VARIABLE_ROW_HEIGHT = wx.TR_HAS_VARIABLE_ROW_HEIGHT     # what it says
""" Use this style to cause row heights to be just big enough to fit the content.""" \
""" If not set, all rows use the largest row height. The default is that this flag is unset. """
TR_EDIT_LABELS = wx.TR_EDIT_LABELS                             # can edit item labels
""" Use this style if you wish the user to be able to edit labels in the tree control. """
TR_ROW_LINES = wx.TR_ROW_LINES                                 # put border around items
""" Use this style to draw a contrasting border between displayed rows. """
TR_HIDE_ROOT = wx.TR_HIDE_ROOT                                 # don't display root node
""" Use this style to suppress the display of the root node, effectively causing the""" \
""" first-level nodes to appear as a series of root nodes. """
TR_FULL_ROW_HIGHLIGHT = wx.TR_FULL_ROW_HIGHLIGHT               # highlight full horz space
""" Use this style to have the background colour and the selection highlight extend """ \
""" over the entire horizontal row of the tree control window. """

TR_AUTO_CHECK_CHILD = 0x04000                                  # only meaningful for checkboxes
""" Only meaningful foe checkbox-type items: when a parent item is checked/unchecked""" \
""" its children are checked/unchecked as well. """
TR_AUTO_TOGGLE_CHILD = 0x08000                                 # only meaningful for checkboxes
""" Only meaningful foe checkbox-type items: when a parent item is checked/unchecked""" \
""" its children are toggled accordingly. """
TR_AUTO_CHECK_PARENT = 0x10000                                 # only meaningful for checkboxes
""" Only meaningful foe checkbox-type items: when a child item is checked/unchecked""" \
""" its parent item is checked/unchecked as well. """
TR_ALIGN_WINDOWS = 0x20000                                     # to align windows horizontally for items at the same level
""" Flag used to align windows (in items with windows) at the same horizontal position. """
TR_ALIGN_WINDOWS_RIGHT = 0x40000                               # to align windows to the rightmost edge of CustomTreeCtrl
""" Flag used to align windows (in items with windows) to the rightmost edge of L{CustomTreeCtrl}."""
TR_ELLIPSIZE_LONG_ITEMS = 0x80000                              # to ellipsize long items when horizontal space is low
""" Flag used to ellipsize long items when the horizontal space for L{CustomTreeCtrl} is low."""
TR_TOOLTIP_ON_LONG_ITEMS = 0x100000                            # to display tooltips on long items when horizontal space is low
""" Flag used to show tooltips on long items when the horizontal space for L{CustomTreeCtrl} is low."""

TR_DEFAULT_STYLE = wx.TR_DEFAULT_STYLE                         # default style for the tree control
""" The set of flags that are closest to the defaults for the native control for a""" \
""" particular toolkit. """

# Values for the `flags` parameter of CustomTreeCtrl.HitTest() which determine
# where exactly the specified point is situated:

TREE_HITTEST_ABOVE            = wx.TREE_HITTEST_ABOVE
TREE_HITTEST_BELOW            = wx.TREE_HITTEST_BELOW
TREE_HITTEST_NOWHERE          = wx.TREE_HITTEST_NOWHERE
# on the button associated with an item.
TREE_HITTEST_ONITEMBUTTON     = wx.TREE_HITTEST_ONITEMBUTTON
# on the bitmap associated with an item.
TREE_HITTEST_ONITEMICON       = wx.TREE_HITTEST_ONITEMICON
# on the indent associated with an item.
TREE_HITTEST_ONITEMINDENT     = wx.TREE_HITTEST_ONITEMINDENT
# on the label (string) associated with an item.
TREE_HITTEST_ONITEMLABEL      = wx.TREE_HITTEST_ONITEMLABEL
# on the right of the label associated with an item.
TREE_HITTEST_ONITEMRIGHT      = wx.TREE_HITTEST_ONITEMRIGHT
# on the label (string) associated with an item.
TREE_HITTEST_ONITEMSTATEICON  = wx.TREE_HITTEST_ONITEMSTATEICON
# on the left of the CustomTreeCtrl.
TREE_HITTEST_TOLEFT           = wx.TREE_HITTEST_TOLEFT
# on the right of the CustomTreeCtrl.
TREE_HITTEST_TORIGHT          = wx.TREE_HITTEST_TORIGHT
# on the upper part (first half) of the item.
TREE_HITTEST_ONITEMUPPERPART  = wx.TREE_HITTEST_ONITEMUPPERPART
# on the lower part (second half) of the item.
TREE_HITTEST_ONITEMLOWERPART  = wx.TREE_HITTEST_ONITEMLOWERPART
# on the check icon, if present
TREE_HITTEST_ONITEMCHECKICON  = 0x4000
# anywhere on the item
TREE_HITTEST_ONITEM  = TREE_HITTEST_ONITEMICON | TREE_HITTEST_ONITEMLABEL | TREE_HITTEST_ONITEMCHECKICON

TREE_ITEMTYPE_NORMAL = 0
TREE_ITEMTYPE_CHECK = 1
TREE_ITEMTYPE_RADIO = 2

# Background Image Style
_StyleTile = 0
_StyleStretch = 1

# Windows Vista Colours
_rgbSelectOuter = wx.Colour(170, 200, 245)
_rgbSelectInner = wx.Colour(230, 250, 250)
_rgbSelectTop = wx.Colour(210, 240, 250)
_rgbSelectBottom = wx.Colour(185, 215, 250)
_rgbNoFocusTop = wx.Colour(250, 250, 250)
_rgbNoFocusBottom = wx.Colour(235, 235, 235)
_rgbNoFocusOuter = wx.Colour(220, 220, 220)
_rgbNoFocusInner = wx.Colour(245, 245, 245)

# Flags for wx.RendererNative
_CONTROL_EXPANDED = 8
_CONTROL_CURRENT = 16

# ----------------------------------------------------------------------------
# CustomTreeCtrl events and binding for handling them
# ----------------------------------------------------------------------------

wxEVT_TREE_BEGIN_DRAG = wx.wxEVT_COMMAND_TREE_BEGIN_DRAG
wxEVT_TREE_BEGIN_RDRAG = wx.wxEVT_COMMAND_TREE_BEGIN_RDRAG
wxEVT_TREE_BEGIN_LABEL_EDIT = wx.wxEVT_COMMAND_TREE_BEGIN_LABEL_EDIT
wxEVT_TREE_END_LABEL_EDIT = wx.wxEVT_COMMAND_TREE_END_LABEL_EDIT
wxEVT_TREE_DELETE_ITEM = wx.wxEVT_COMMAND_TREE_DELETE_ITEM
wxEVT_TREE_GET_INFO = wx.wxEVT_COMMAND_TREE_GET_INFO
wxEVT_TREE_SET_INFO = wx.wxEVT_COMMAND_TREE_SET_INFO
wxEVT_TREE_ITEM_EXPANDED = wx.wxEVT_COMMAND_TREE_ITEM_EXPANDED
wxEVT_TREE_ITEM_EXPANDING = wx.wxEVT_COMMAND_TREE_ITEM_EXPANDING
wxEVT_TREE_ITEM_COLLAPSED = wx.wxEVT_COMMAND_TREE_ITEM_COLLAPSED
wxEVT_TREE_ITEM_COLLAPSING = wx.wxEVT_COMMAND_TREE_ITEM_COLLAPSING
wxEVT_TREE_SEL_CHANGED = wx.wxEVT_COMMAND_TREE_SEL_CHANGED
wxEVT_TREE_SEL_CHANGING = wx.wxEVT_COMMAND_TREE_SEL_CHANGING
wxEVT_TREE_KEY_DOWN = wx.wxEVT_COMMAND_TREE_KEY_DOWN
wxEVT_TREE_ITEM_ACTIVATED = wx.wxEVT_COMMAND_TREE_ITEM_ACTIVATED
wxEVT_TREE_ITEM_RIGHT_CLICK = wx.wxEVT_COMMAND_TREE_ITEM_RIGHT_CLICK
wxEVT_TREE_ITEM_MIDDLE_CLICK = wx.wxEVT_COMMAND_TREE_ITEM_MIDDLE_CLICK
wxEVT_TREE_END_DRAG = wx.wxEVT_COMMAND_TREE_END_DRAG
wxEVT_TREE_STATE_IMAGE_CLICK = wx.wxEVT_COMMAND_TREE_STATE_IMAGE_CLICK
wxEVT_TREE_ITEM_GETTOOLTIP = wx.wxEVT_COMMAND_TREE_ITEM_GETTOOLTIP
wxEVT_TREE_ITEM_MENU = wx.wxEVT_COMMAND_TREE_ITEM_MENU
wxEVT_TREE_ITEM_CHECKING = wx.NewEventType()
wxEVT_TREE_ITEM_CHECKED = wx.NewEventType()
wxEVT_TREE_ITEM_HYPERLINK = wx.NewEventType()

EVT_TREE_BEGIN_DRAG = wx.EVT_TREE_BEGIN_DRAG
""" Begin dragging with the left mouse button. """
EVT_TREE_BEGIN_RDRAG = wx.EVT_TREE_BEGIN_RDRAG
""" Begin dragging with the right mouse button. """
EVT_TREE_BEGIN_LABEL_EDIT = wx.EVT_TREE_BEGIN_LABEL_EDIT
""" Begin editing a label. This can be prevented by calling L{Veto}. """
EVT_TREE_END_LABEL_EDIT = wx.EVT_TREE_END_LABEL_EDIT
""" End editing a label. This can be prevented by calling L{Veto}. """
EVT_TREE_DELETE_ITEM = wx.EVT_TREE_DELETE_ITEM
""" Delete an item. """
EVT_TREE_GET_INFO = wx.EVT_TREE_GET_INFO
""" Request information from the application (not implemented in L{CustomTreeCtrl}). """
EVT_TREE_SET_INFO = wx.EVT_TREE_SET_INFO
""" Information is being supplied to the application (not implemented in L{CustomTreeCtrl}). """
EVT_TREE_ITEM_EXPANDED = wx.EVT_TREE_ITEM_EXPANDED
""" The item has been expanded. """
EVT_TREE_ITEM_EXPANDING = wx.EVT_TREE_ITEM_EXPANDING
""" The item is being expanded. This can be prevented by calling L{Veto}. """
EVT_TREE_ITEM_COLLAPSED = wx.EVT_TREE_ITEM_COLLAPSED
""" The item has been collapsed. """
EVT_TREE_ITEM_COLLAPSING = wx.EVT_TREE_ITEM_COLLAPSING
""" The item is being collapsed. This can be prevented by calling L{Veto}. """
EVT_TREE_SEL_CHANGED = wx.EVT_TREE_SEL_CHANGED
""" Selection has changed. """
EVT_TREE_SEL_CHANGING = wx.EVT_TREE_SEL_CHANGING
""" Selection is changing. This can be prevented by calling L{Veto}. """
EVT_TREE_KEY_DOWN = wx.EVT_TREE_KEY_DOWN
""" A key has been pressed. """
EVT_TREE_ITEM_ACTIVATED = wx.EVT_TREE_ITEM_ACTIVATED
""" The item has been activated, i.e. chosen by double clicking it with mouse or from keyboard. """
EVT_TREE_ITEM_RIGHT_CLICK = wx.EVT_TREE_ITEM_RIGHT_CLICK
""" The user has clicked the item with the right mouse button. """
EVT_TREE_ITEM_MIDDLE_CLICK = wx.EVT_TREE_ITEM_MIDDLE_CLICK
""" The user has clicked the item with the middle mouse button (not implemented in L{CustomTreeCtrl}). """
EVT_TREE_END_DRAG = wx.EVT_TREE_END_DRAG
""" End dragging with the left or right mouse button. """
EVT_TREE_STATE_IMAGE_CLICK = wx.EVT_TREE_STATE_IMAGE_CLICK
""" The state image has been clicked (not implemented in L{CustomTreeCtrl}). """
EVT_TREE_ITEM_GETTOOLTIP = wx.EVT_TREE_ITEM_GETTOOLTIP
""" The opportunity to set the item tooltip is being given to the application (call `TreeEvent.SetToolTip`). """
EVT_TREE_ITEM_MENU = wx.EVT_TREE_ITEM_MENU
""" The context menu for the selected item has been requested, either by a right click or by using the menu key. """
EVT_TREE_ITEM_CHECKING = wx.PyEventBinder(wxEVT_TREE_ITEM_CHECKING, 1)
""" A checkbox or radiobox type item is being checked. """
EVT_TREE_ITEM_CHECKED = wx.PyEventBinder(wxEVT_TREE_ITEM_CHECKED, 1)
""" A checkbox or radiobox type item has been checked. """
EVT_TREE_ITEM_HYPERLINK = wx.PyEventBinder(wxEVT_TREE_ITEM_HYPERLINK, 1)
""" An hyperlink type item has been clicked. """

# ----------------------------------------------------------------------------

[docs]def MakeDisabledBitmap(original):
    """
    Creates a disabled-looking bitmap starting from the input one.

    :param `original`: an instance of `wx.Bitmap` to be greyed-out.

    :return: An instance of `wx.Bitmap`, containing a disabled-looking
     representation of the original item image.
    """

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

# ----------------------------------------------------------------------------

[docs]def DrawTreeItemButton(win, dc, rect, flags):
    """
    Draw the expanded/collapsed icon for a tree control item.

    :param `win`: an instance of `wx.Window`;
    :param `dc`: an instance of `wx.DC`;
    :param `wx.Rect` `rect`: the client rectangle where to draw the tree item button;
    :param integer `flags`: contains ``wx.CONTROL_EXPANDED`` bit for expanded tree items.

    :note: This is a simple replacement of `wx.RendererNative.DrawTreeItemButton`.

    :note: This method is never used in wxPython versions newer than 2.6.2.1.
    """

    # white background
    dc.SetPen(wx.GREY_PEN)
    dc.SetBrush(wx.WHITE_BRUSH)
    dc.DrawRectangleRect(rect)

    # black lines
    xMiddle = rect.x + rect.width/2
    yMiddle = rect.y + rect.height/2

    # half of the length of the horz lines in "-" and "+"
    halfWidth = rect.width/2 - 2
    dc.SetPen(wx.BLACK_PEN)
    dc.DrawLine(xMiddle - halfWidth, yMiddle,
                xMiddle + halfWidth + 1, yMiddle)

    if not flags & _CONTROL_EXPANDED:

        # turn "-" into "+"
        halfHeight = rect.height/2 - 2
        dc.DrawLine(xMiddle, yMiddle - halfHeight,
                    xMiddle, yMiddle + halfHeight + 1)

# ----------------------------------------------------------------------------

[docs]def EventFlagsToSelType(style, shiftDown=False, ctrlDown=False):
    """
    Translate the key or mouse event flag to the type of selection we
    are dealing with.

    :param integer `style`: the main L{CustomTreeCtrl} window style flag;
    :param bool `shiftDown`: ``True`` if the ``Shift`` key is pressed, ``False`` otherwise;
    :param bool `ctrlDown`: ``True`` if the ``Ctrl`` key is pressed, ``False`` otherwise;

    :return: A 3-elements tuple, with the following elements:

     - `is_multiple`: ``True`` if L{CustomTreeCtrl} has the ``TR_MULTIPLE`` flag set, ``False`` otherwise;
     - `extended_select`: ``True`` if the ``Shift`` key is pressend and if L{CustomTreeCtrl} has the
       ``TR_MULTIPLE`` flag set, ``False`` otherwise;
     - `unselect_others`: ``True`` if the ``Ctrl`` key is pressend and if L{CustomTreeCtrl} has the
       ``TR_MULTIPLE`` flag set, ``False`` otherwise.
    """

    is_multiple = (style & TR_MULTIPLE) != 0
    extended_select = shiftDown and is_multiple
    unselect_others = not (extended_select or (ctrlDown and is_multiple))

    return is_multiple, extended_select, unselect_others

# ----------------------------------------------------------------------------

[docs]def ChopText(dc, text, max_size):
    """
    Chops the input `text` if its size does not fit in `max_size`, by cutting the
    text and adding ellipsis at the end.

    :param `dc`: a `wx.DC` device context;
    :param `text`: the text to chop;
    :param `max_size`: the maximum size in which the text should fit.

    :note: This method is used exclusively when L{CustomTreeCtrl} has the ``TR_ELLIPSIZE_LONG_ITEMS``
     style set.

    .. versionadded:: 0.9.3
    """

    # first check if the text fits with no problems
    x, y, dummy = dc.GetMultiLineTextExtent(text)

    if x <= max_size:
        return text

    textLen = len(text)
    last_good_length = 0

    for i in xrange(textLen, -1, -1):
        s = text[0:i]
        s += "..."

        x, y = dc.GetTextExtent(s)
        last_good_length = i

        if x < max_size:
            break

    ret = text[0:last_good_length] + "..."
    return ret

#---------------------------------------------------------------------------
# DragImage Implementation
# This Class Handles The Creation Of A Custom Image In Case Of Item Drag
# And Drop.
#---------------------------------------------------------------------------

[docs]class DragImage(wx.DragImage):
    """
    This class handles the creation of a custom image in case of item drag
    and drop.
    """

[docs]    def __init__(self, treeCtrl, item):
        """
        Default class constructor.
        For internal use: do not call it in your code!

        :param `treeCtrl`: the parent L{CustomTreeCtrl};
        :param `item`: one of the tree control item (an instance of L{GenericTreeItem}).
        """

        text = item.GetText()
        font = item.Attr().GetFont()
        colour = item.Attr().GetTextColour()
        if not colour:
            colour = wx.BLACK
        if not font:
            font = treeCtrl._normalFont

        backcolour = treeCtrl.GetBackgroundColour()
        r, g, b = int(backcolour.Red()), int(backcolour.Green()), int(backcolour.Blue())
        backcolour = ((r >> 1) + 20, (g >> 1) + 20, (b >> 1) + 20)
        backcolour = wx.Colour(backcolour[0], backcolour[1], backcolour[2])
        self._backgroundColour = backcolour

        tempdc = wx.ClientDC(treeCtrl)
        tempdc.SetFont(font)
        width, height, dummy = tempdc.GetMultiLineTextExtent(text + "M")

        image = item.GetCurrentImage()

        image_w, image_h = 0, 0
        wcheck, hcheck = 0, 0
        itemcheck = None
        itemimage = None
        ximagepos = 0
        yimagepos = 0
        xcheckpos = 0
        ycheckpos = 0

        if image != _NO_IMAGE:
            if treeCtrl._imageListNormal:
                image_w, image_h = treeCtrl._imageListNormal.GetSize(image)
                image_w += 4
                itemimage = treeCtrl._imageListNormal.GetBitmap(image)

        checkimage = item.GetCurrentCheckedImage()

        if checkimage is not None:
            if treeCtrl._imageListCheck:
                wcheck, hcheck = treeCtrl._imageListCheck.GetSize(checkimage)
                wcheck += 4
                itemcheck = treeCtrl._imageListCheck.GetBitmap(checkimage)

        total_h = max(hcheck, height)
        total_h = max(image_h, total_h)

        if image_w:
            ximagepos = wcheck
            yimagepos = ((total_h > image_h) and [(total_h-image_h)/2] or [0])[0]

        if checkimage is not None:
            xcheckpos = 2
            ycheckpos = ((total_h > image_h) and [(total_h-image_h)/2] or [0])[0] + 2

        extraH = ((total_h > height) and [(total_h - height)/2] or [0])[0]

        xtextpos = wcheck + image_w
        ytextpos = extraH

        total_h = max(image_h, hcheck)
        total_h = max(total_h, height)

        if total_h < 30:
            total_h += 2            # at least 2 pixels
        else:
            total_h += total_h/10   # otherwise 10% extra spacing

        total_w = image_w + wcheck + width

        self._total_w = total_w
        self._total_h = total_h
        self._itemimage = itemimage
        self._itemcheck = itemcheck
        self._text = text
        self._colour = colour
        self._font = font
        self._xtextpos = xtextpos
        self._ytextpos = ytextpos
        self._ximagepos = ximagepos
        self._yimagepos = yimagepos
        self._xcheckpos = xcheckpos
        self._ycheckpos = ycheckpos
        self._textwidth = width
        self._textheight = height
        self._extraH = extraH

        self._bitmap = self.CreateBitmap()

        wx.DragImage.__init__(self, self._bitmap)

[docs]    def CreateBitmap(self):
        """
        Actually creates the drag and drop bitmap for L{DragImage}.

        :return: An instance of L{DragImage}, a close representation of the item's
         appearance (i.e., a screenshot of the item).
        """

        memory = wx.MemoryDC()

        bitmap = wx.EmptyBitmap(self._total_w, self._total_h)
        memory.SelectObject(bitmap)

        if wx.Platform == '__WXMAC__':
            memory.SetBackground(wx.TRANSPARENT_BRUSH)
        else:
            memory.SetBackground(wx.Brush(self._backgroundColour))
        memory.SetBackgroundMode(wx.TRANSPARENT)
        memory.SetFont(self._font)
        memory.SetTextForeground(self._colour)
        memory.Clear()

        if self._itemimage:
            memory.DrawBitmap(self._itemimage, self._ximagepos, self._yimagepos, True)

        if self._itemcheck:
            memory.DrawBitmap(self._itemcheck, self._xcheckpos, self._ycheckpos, True)

        textrect = wx.Rect(self._xtextpos, self._ytextpos+self._extraH, self._textwidth, self._textheight)
        memory.DrawLabel(self._text, textrect)

        memory.SelectObject(wx.NullBitmap)

        # Gtk and Windows unfortunatly don't do so well with transparent
        # drawing so this hack corrects the image to have a transparent
        # background.
        if wx.Platform != '__WXMAC__':
            timg = bitmap.ConvertToImage()
            if not timg.HasAlpha():
                timg.InitAlpha()
            for y in xrange(timg.GetHeight()):
                for x in xrange(timg.GetWidth()):
                    pix = wx.Colour(timg.GetRed(x, y),
                                    timg.GetGreen(x, y),
                                    timg.GetBlue(x, y))
                    if pix == self._backgroundColour:
                        timg.SetAlpha(x, y, 0)
            bitmap = timg.ConvertToBitmap()
        return bitmap

# ----------------------------------------------------------------------------
# TreeItemAttr: a structure containing the visual attributes of an item
# ----------------------------------------------------------------------------

[docs]class TreeItemAttr(object):
    """
    Creates the item attributes (text colour, background colour and font).

    :note: This class is inspired by the wxWidgets generic implementation of `wx.TreeItemAttr`.
    """

[docs]    def __init__(self, colText=wx.NullColour, colBack=wx.NullColour, font=wx.NullFont):
        """
        Default class constructor.
        For internal use: do not call it in your code!

        :param `colText`: the text colour, an instance of `wx.Colour`;
        :param `colBack`: the tree item background colour, an instance of `wx.Colour`;
        :param `font`: the tree item font, an instance of `wx.Font`.
        """

        self._colText = colText
        self._colBack = colBack
        self._font = font

    # setters

[docs]    def SetTextColour(self, colText):
        """
        Sets the text colour attribute.

        :param `colText`: an instance of `wx.Colour`.
        """

        self._colText = colText

[docs]    def SetBackgroundColour(self, colBack):
        """
        Sets the item background colour attribute.

        :param `colBack`: an instance of `wx.Colour`.
        """

        self._colBack = colBack

[docs]    def SetFont(self, font):
        """
        Sets the item font attribute.

        :param `font`: an instance of `wx.Font`.
        """

        self._font = font

    # accessors

[docs]    def HasTextColour(self):
        """
        Returns whether the attribute has text colour.

        :return: ``True`` if the text colour attribute has been set, ``False`` otherwise.
        """

        return self._colText != wx.NullColour

[docs]    def HasBackgroundColour(self):
        """
        Returns whether the attribute has background colour.

        :return: ``True`` if the background colour attribute has been set, ``False`` otherwise.
        """

        return self._colBack != wx.NullColour

[docs]    def HasFont(self):
        """
        Returns whether the attribute has font.

        :return: ``True`` if the font attribute has been set, ``False`` otherwise.
        """

        return self._font != wx.NullFont

    # getters

[docs]    def GetTextColour(self):
        """
        Returns the attribute text colour.

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

        return self._colText

[docs]    def GetBackgroundColour(self):
        """
        Returns the attribute background colour.

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

        return self._colBack

[docs]    def GetFont(self):
        """
        Returns the attribute font.

        :return: An instance of `wx.Font`.
        """

        return self._font

# ----------------------------------------------------------------------------
# CommandTreeEvent Is A Special Subclassing Of wx.PyCommandEvent
#
# NB: Note That Not All The Accessors Make Sense For All The Events, See The
# Event Description Below.
# ----------------------------------------------------------------------------

[docs]class CommandTreeEvent(wx.PyCommandEvent):
    """
    L{CommandTreeEvent} is a special subclassing of `wx.PyCommandEvent`.

    :note: Not all the accessors make sense for all the events, see the event description for every method in this class.
    """

[docs]    def __init__(self, evtType, evtId, item=None, evtKey=None, point=None,
                 label=None, **kwargs):
        """
        Default class constructor.
        For internal use: do not call it in your code!

        :param integer `evtType`: the event type;
        :param integer `evtId`: the event identifier;
        :param `item`: an instance of L{GenericTreeItem};
        :param integer `evtKey`: a character ordinal;
        :param `point`: an instance of `wx.Point`;
        :param string `label`: a L{GenericTreeItem} text label.
        """

        wx.PyCommandEvent.__init__(self, evtType, evtId, **kwargs)
        self._item = item
        self._evtKey = evtKey
        self._pointDrag = point
        self._label = label

[docs]    def GetItem(self):
        """
        Gets the item on which the operation was performed or the newly selected
        item for ``EVT_TREE_SEL_CHANGED`` and ``EVT_TREE_SEL_CHANGING`` events.

        :return: An instance of L{GenericTreeItem}.
        """

        return self._item

[docs]    def SetItem(self, item):
        """
        Sets the item on which the operation was performed or the newly selected
        item for ``EVT_TREE_SEL_CHANGED`` and ``EVT_TREE_SEL_CHANGING`` events.

        :param `item`: an instance of L{GenericTreeItem}.
        """

        self._item = item

[docs]    def GetOldItem(self):
        """
        Returns the previously selected item for ``EVT_TREE_SEL_CHANGED`` and
        ``EVT_TREE_SEL_CHANGING`` events.

        :return: An instance of L{GenericTreeItem}.
        """

        return self._itemOld

[docs]    def SetOldItem(self, item):
        """
        Returns the previously selected item for ``EVT_TREE_SEL_CHANGED`` and
        ``EVT_TREE_SEL_CHANGING`` events.

        :param `item`: an instance of L{GenericTreeItem}.
        """

        self._itemOld = item

[docs]    def GetPoint(self):
        """
        Returns the point where the mouse was when the drag operation started
        (for ``EVT_TREE_BEGIN_DRAG`` and ``EVT_TREE_BEGIN_RDRAG`` events only)
        or the click position.

        :return: An instance of `wx.Point`.
        """

        return self._pointDrag

[docs]    def SetPoint(self, pt):
        """
        Sets the point where the mouse was when the drag operation started
        (for ``EVT_TREE_BEGIN_DRAG`` and ``EVT_TREE_BEGIN_RDRAG`` events only)
        or the click position.

        :param `pt`: an instance of `wx.Point`.
        """

        self._pointDrag = pt

[docs]    def GetKeyEvent(self):
        """
        Returns the keyboard data (for ``EVT_TREE_KEY_DOWN`` event only).

        :return: An instance of `wx.KeyEvent`.
        """

        return self._evtKey

[docs]    def GetKeyCode(self):
        """
        Returns the virtual key code. ASCII events return normal ASCII values, while
        non-ASCII events return values such as ``wx.WXK_LEFT`` for the left cursor key.

        This method is for ``EVT_TREE_KEY_DOWN`` events only.

        :return: An integer representing the virtual key code.

        :note: In Unicode build, the returned value is meaningful only if the user entered
         a character that can be represented in current locale's default charset. You can
         obtain the corresponding Unicode character using `GetUnicodeKey`.
        """

        return self._evtKey.GetKeyCode()

[docs]    def SetKeyEvent(self, event):
        """
        Sets the keyboard data (for ``EVT_TREE_KEY_DOWN`` event only).

        :param `event`: a L{TreeEvent} event to be processed.
        """

        self._evtKey = event

[docs]    def GetLabel(self):
        """
        Returns the item text (for ``EVT_TREE_BEGIN_LABEL_EDIT`` and
        ``EVT_TREE_END_LABEL_EDIT`` events only).

        :return: A string containing the item text.
        """

        return self._label

[docs]    def SetLabel(self, label):
        """
        Sets the item text (for ``EVT_TREE_BEGIN_LABEL_EDIT`` and
        ``EVT_TREE_END_LABEL_EDIT`` events only).

        :param string `label`: a string containing the new item text.
        """

        self._label = label

[docs]    def IsEditCancelled(self):
        """
        Returns the edit cancel flag (for ``EVT_TREE_BEGIN_LABEL_EDIT`` and
        ``EVT_TREE_END_LABEL_EDIT`` events only).

        :return: ``True`` is the item editing has been cancelled, ``False`` otherwise.
        """

        return self._editCancelled

[docs]    def SetEditCanceled(self, editCancelled):
        """
        Sets the edit cancel flag (for ``EVT_TREE_BEGIN_LABEL_EDIT`` and
        ``EVT_TREE_END_LABEL_EDIT`` events only).

        :param bool `editCancelled`: ``True`` to cancel the editing, ``False`` otherwise.
        """

        self._editCancelled = editCancelled

[docs]    def SetToolTip(self, toolTip):
        """
        Sets the tooltip for the item (for ``EVT_TREE_ITEM_GETTOOLTIP`` events).

        :param string `tooltip`: a string representing the item tooltip.
        """

        self._label = toolTip

[docs]    def GetToolTip(self):
        """
        Returns the tooltip for the item (for ``EVT_TREE_ITEM_GETTOOLTIP`` events).

        :return: A string containing the item tooltip.
        """

        return self._label

# ----------------------------------------------------------------------------
# TreeEvent is a special class for all events associated with tree controls
#
# NB: note that not all accessors make sense for all events, see the event
#     descriptions below
# ----------------------------------------------------------------------------

[docs]class TreeEvent(CommandTreeEvent):
    """
    L{TreeEvent} is a special class for all events associated with tree controls.

    :note: Not all accessors make sense for all events, see the event descriptions below.
    """

[docs]    def __init__(self, evtType, evtId, item=None, evtKey=None, point=None,
                 label=None, **kwargs):
        """
        Default class constructor.
        For internal use: do not call it in your code!

        :param integer `evtType`: the event type;
        :param integer `evtId`: the event identifier;
        :param `item`: an instance of L{GenericTreeItem};
        :param integer `evtKey`: a character ordinal;
        :param `point`: an instance of `wx.Point`;
        :param string `label`: a L{GenericTreeItem} text label.
        """

        CommandTreeEvent.__init__(self, evtType, evtId, item, evtKey, point, label, **kwargs)
        self.notify = wx.NotifyEvent(evtType, evtId)

[docs]    def GetNotifyEvent(self):
        """
        Returns the actual `wx.NotifyEvent`.

        :return: An instance of `wx.NotifyEvent`.
        """

        return self.notify

[docs]    def IsAllowed(self):
        """
        Returns ``True`` if the change is allowed (L{Veto} hasn't been called) or
        ``False`` otherwise (if it was).
        """

        return self.notify.IsAllowed()

[docs]    def Veto(self):
        """
        Prevents the change announced by this event from happening.

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

        self.notify.Veto()

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

        self.notify.Allow()

# -----------------------------------------------------------------------------
# Auxiliary Classes: TreeEditTimer
# -----------------------------------------------------------------------------

[docs]class TreeEditTimer(wx.Timer):
    """ Timer used for enabling in-place edit."""

[docs]    def __init__(self, owner):
        """
        Default class constructor.
        For internal use: do not call it in your code!

        :param `owner`: the `wx.Timer` owner (an instance of L{CustomTreeCtrl}).
        """

        wx.Timer.__init__(self)
        self._owner = owner

[docs]    def Notify(self):
        """ The timer has expired, starts the item editing. """

        self._owner.OnEditTimer()

# -----------------------------------------------------------------------------
# Auxiliary Classes: TreeTextCtrl
# This Is The Temporary ExpandoTextCtrl Created When You Edit The Text Of An Item
# -----------------------------------------------------------------------------

[docs]class TreeTextCtrl(ExpandoTextCtrl):
    """
    Control used for in-place edit.

    This is a subclass of `wx.lib.expando.ExpandoTextCtrl` as L{CustomTreeCtrl} supports multiline
    text items.

    :note: To add a newline character in a multiline item, press ``Shift`` + ``Enter`` as the ``Enter``
     key alone is consumed by L{CustomTreeCtrl} to finish the editing and ``Ctrl`` + ``Enter`` is
     consumed by the platform for tab navigation.
    """

[docs]    def __init__(self, owner, item=None):
        """
        Default class constructor.
        For internal use: do not call it in your code!

        :param `owner`: the control parent (an instance of L{CustomTreeCtrl});
        :param `item`: an instance of L{GenericTreeItem}.

        :raise: `Exception` when the item has an associated image but the parent
         L{CustomTreeCtrl} does not have a `wx.ImageList` assigned.
        """

        self._owner = owner
        self._itemEdited = item
        self._startValue = item.GetText()
        self._finished = False
        self._aboutToFinish = False
        self._currentValue = self._startValue

        w = self._itemEdited.GetWidth()
        h = self._itemEdited.GetHeight()

        wnd = self._itemEdited.GetWindow()
        if wnd:
            w = w - self._itemEdited.GetWindowSize()[0]
            h = 0

        x, y = self._owner.CalcScrolledPosition(item.GetX(), item.GetY())

        image_h = 0
        image_w = 0

        image = item.GetCurrentImage()

        if image != _NO_IMAGE:

            if self._owner._imageListNormal:
                image_w, image_h = self._owner._imageListNormal.GetSize(image)
                image_w += 4

            else:

                raise Exception("\n ERROR: You Must Create An Image List To Use Images!")

        checkimage = item.GetCurrentCheckedImage()

        if checkimage is not None:
            wcheck, hcheck = self._owner._imageListCheck.GetSize(checkimage)
            wcheck += 4
        else:
            wcheck = hcheck = 0

        if wnd:
            h = max(hcheck, image_h)
            dc = wx.ClientDC(self._owner)
            h = max(h, dc.GetTextExtent("Aq")[1])
            h = h + 2

        # FIXME: what are all these hardcoded 4, 8 and 11s really?
        x += image_w + wcheck
        w -= image_w + 4 + wcheck

        expandoStyle = wx.WANTS_CHARS
        if wx.Platform in ["__WXGTK__", "__WXMAC__"]:
            expandoStyle |= wx.SIMPLE_BORDER
            xSize, ySize = w + 25, h
        else:
            expandoStyle |= wx.SUNKEN_BORDER
            xSize, ySize = w + 25, h+2

        ExpandoTextCtrl.__init__(self, self._owner, wx.ID_ANY, self._startValue,
                                 wx.Point(x - 4, y), wx.Size(xSize, ySize),
                                 expandoStyle)

        if wx.Platform == "__WXMAC__":
            self.SetFont(owner.GetFont())
            bs = self.GetBestSize()
            self.SetSize((-1, bs.height))

        self.Bind(wx.EVT_CHAR, self.OnChar)
        self.Bind(wx.EVT_KEY_UP, self.OnKeyUp)
        self.Bind(wx.EVT_KILL_FOCUS, self.OnKillFocus)

[docs]    def AcceptChanges(self):
        """
        Accepts/rejects the changes made by the user.

        :return: ``True`` if the changes to the item text have been accepted, ``False``
         if they have been rejected (i.e., vetoed by the user).
        """

        value = self.GetValue()

        if value == self._startValue:
            # nothing changed, always accept
            # when an item remains unchanged, the owner
            # needs to be notified that the user decided
            # not to change the tree item label, and that
            # the edit has been cancelled
            self._owner.OnCancelEdit(self._itemEdited)
            return True

        if not self._owner.OnAcceptEdit(self._itemEdited, value):
            # vetoed by the user
            return False

        # accepted, do rename the item
        self._owner.SetItemText(self._itemEdited, value)

        return True

[docs]    def Finish(self):
        """ Finish editing. """

        if not self._finished:
            self._finished = True
            self._owner.SetFocusIgnoringChildren()
            self._owner.ResetEditControl()

[docs]    def OnChar(self, event):
        """
        Handles the ``wx.EVT_CHAR`` event for L{TreeTextCtrl}.

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

        keycode = event.GetKeyCode()
        shiftDown = event.ShiftDown()

        if keycode in [wx.WXK_RETURN, wx.WXK_NUMPAD_ENTER]:
            if shiftDown:
                event.Skip()
            else:
                self._aboutToFinish = True
                self.SetValue(self._currentValue)
                # Notify the owner about the changes
                self.AcceptChanges()
                # Even if vetoed, close the control (consistent with MSW)
                wx.CallAfter(self.Finish)

        elif keycode == wx.WXK_ESCAPE:
            self.StopEditing()

        else:
            event.Skip()

[docs]    def OnKeyUp(self, event):
        """
        Handles the ``wx.EVT_KEY_UP`` event for L{TreeTextCtrl}.

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

        if not self._finished:

            # auto-grow the textctrl:
            parentSize = self._owner.GetSize()
            myPos = self.GetPosition()
            mySize = self.GetSize()

            dc = wx.ClientDC(self)
            sx, sy, dummy = dc.GetMultiLineTextExtent(self.GetValue() + "M")

            if myPos.x + sx > parentSize.x:
                sx = parentSize.x - myPos.x
            if mySize.x > sx:
                sx = mySize.x

            self.SetSize((sx, -1))
            self._currentValue = self.GetValue()

        event.Skip()

[docs]    def OnKillFocus(self, event):
        """
        Handles the ``wx.EVT_KILL_FOCUS`` event for L{TreeTextCtrl}.

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

        if not self._finished and not self._aboutToFinish:

            # We must finish regardless of success, otherwise we'll get
            # focus problems:

            if not self.AcceptChanges():
                self._owner.OnCancelEdit(self._itemEdited)

        # We must let the native text control handle focus, too, otherwise
        # it could have problems with the cursor (e.g., in wxGTK).
        event.Skip()

[docs]    def StopEditing(self):
        """ Suddenly stops the editing. """

        self._owner.OnCancelEdit(self._itemEdited)
        self.Finish()

[docs]    def item(self):
        """
        Returns the item currently edited.

        :return: An instance of L{GenericTreeItem}.
        """

        return self._itemEdited

# -----------------------------------------------------------------------------
# Auxiliary Classes: TreeFindTimer
# Timer Used To Clear CustomTreeCtrl._findPrefix If No Key Was Pressed For A
# Sufficiently Long Time.
# -----------------------------------------------------------------------------

[docs]class TreeFindTimer(wx.Timer):
    """
    Timer used to clear the L{CustomTreeCtrl} `_findPrefix` attribute if no
    key was pressed for a sufficiently long time.
    """

[docs]    def __init__(self, owner):
        """
        Default class constructor.
        For internal use: do not call it in your code!

        :param `owner`: the `wx.Timer` owner (an instance of L{CustomTreeCtrl}).
        """

        wx.Timer.__init__(self)
        self._owner = owner

[docs]    def Notify(self):
        """ The timer has expired, clear the `_findPrefix` attribute in L{CustomTreeCtrl}. """

        self._owner._findPrefix = ""

# -----------------------------------------------------------------------------
# GenericTreeItem Implementation.
# This Class Holds All The Information And Methods For Every Single Item In
# CustomTreeCtrl.
# -----------------------------------------------------------------------------

[docs]class GenericTreeItem(object):
    """
    This class holds all the information and methods for every single item in
    L{CustomTreeCtrl}. This is a generic implementation of `wx.TreeItem`.
    """

[docs]    def __init__(self, parent, text="", ct_type=0, wnd=None, image=-1, selImage=-1, data=None, separator=False):
        """
        Default class constructor.
        For internal use: do not call it in your code!

        :param `parent`: the tree item parent, an instance of L{GenericTreeItem} (may
         be ``None`` for root items);
        :param string `text`: the tree item text;
        :param integer `ct_type`: the tree item kind. May be one of the following integers:

         =============== =========================================
         `ct_type` Value Description
         =============== =========================================
                0        A normal item
                1        A checkbox-like item
                2        A radiobutton-type item
         =============== =========================================

        :param `wnd`: if not ``None``, a non-toplevel window to be displayed next to
         the item, an instance of `wx.Window`;
        :param integer `image`: an index within the normal image list specifying the image to
         use for the item in unselected state;
        :param integer `selImage`: an index within the normal image list specifying the image to
         use for the item in selected state; if `image` > -1 and `selImage` is -1, the
         same image is used for both selected and unselected items;
        :param object `data`: associate the given Python object `data` with the item;
        :param bool `separator`: ``True`` if the item is a separator, ``False`` otherwise.

        :note: Regarding radiobutton-type items (with `ct_type` = 2), the following
         approach is used:

         - All peer-nodes that are radiobuttons will be mutually exclusive. In other words,
           only one of a set of radiobuttons that share a common parent can be checked at
           once. If a radiobutton node becomes checked, then all of its peer radiobuttons
           must be unchecked.
         - If a radiobutton node becomes unchecked, then all of its child nodes will become
           inactive.

        :note: Separator items should not have children, labels, data or an associated window.
         Other issues/features associated to separator items:

         - You can change the color of individual separators by using L{CustomTreeCtrl.SetItemTextColour},
           or you can use L{CustomTreeCtrl.SetSeparatorColour} to change the color of all
           separators. The default separator colour is that returned by `wx.SystemSettings.GetColour(wx.SYS_COLOUR_GRAYTEXT)`;
         - Separators can be selected just like any other tree item;
         - Separators cannot have text;
         - Separators cannot have children;
         - Separators cannot be edited via the ``EVT_TREE_BEGIN_LABEL_EDIT`` event.

        """

        # since there can be very many of these, we save size by chosing
        # the smallest representation for the elements and by ordering
        # the members to avoid padding.
        self._text = text       # label to be rendered for item
        self._data = data       # user-provided data

        self._children  = []    # list of children
        self._parent = parent   # parent of this item

        self._attr = None       # attributes???

        self._separator = separator

        # tree ctrl images for the normal, selected, expanded and
        # expanded+selected states
        self._images = [-1, -1, -1, -1]
        self._images[TreeItemIcon_Normal] = image
        self._images[TreeItemIcon_Selected] = selImage
        self._images[TreeItemIcon_Expanded] = _NO_IMAGE
        self._images[TreeItemIcon_SelectedExpanded] = _NO_IMAGE

        self._checkedimages = [None, None, None, None, None]
        self._leftimage = _NO_IMAGE

        self._x = 0             # (virtual) offset from top
        self._y = 0             # (virtual) offset from left
        self._width = 0         # width of this item
        self._height = 0        # height of this item

        self._isCollapsed = True
        self._hasHilight = False    # same as focused
        self._hasPlus = False       # used for item which doesn't have
                                    # children but has a [+] button
        self._isBold = False        # render the label in bold font
        self._isItalic = False      # render the label in italic font
        self._ownsAttr = False      # delete attribute when done
        self._type = ct_type        # item type: 0=normal, 1=check, 2=radio
        self._is3State = False      # true for 3-state checkbox items
        self._checked = 0           # only meaningful for check and radio items
        self._enabled = True        # flag to enable/disable an item
        self._hypertext = False     # indicates if the item is hypertext
        self._visited = False       # visited state for an hypertext item

        if self._type > 0:
            # do not construct the array for normal items
            self._checkedimages[TreeItemIcon_Checked] = 0
            self._checkedimages[TreeItemIcon_NotChecked] = 1
            self._checkedimages[TreeItemIcon_Undetermined] = 2
            self._checkedimages[TreeItemIcon_Flagged] = 3
            self._checkedimages[TreeItemIcon_NotFlagged] = 4

        if parent:
            if parent.GetType() == 2 and not parent.IsChecked():
                # if the node parent is a radio not enabled, we are disabled
                self._enabled = False

        self._wnd = wnd             # are we holding a window?

        if wnd:
            self.SetWindow(wnd)

[docs]    def IsOk(self):
        """
        Returns whether the item is ok or not.

        :note: This method always returns ``True``, it has been added for
         backward compatibility with the wxWidgets C++ implementation.
        """

        return True

[docs]    def IsSeparator(self):
        """
        Returns whether the item is meant to be an horizontal line separator or not.

        :return: ``True`` if this item is a separator, ``False`` otherwise.
        """

        return self._separator

[docs]    def GetChildren(self):
        """
        Returns the item's children.

        :return: A Python list containing instances of L{GenericTreeItem}, representing
         this item's children.
        """

        return self._children

[docs]    def GetText(self):
        """
        Returns the item text.

        :return: A string containing the item text.
        """

        return self._text

[docs]    def GetImage(self, which=TreeItemIcon_Normal):
        """
        Returns the item image for a particular item state.

        :param integer `which`: can be one of the following bits:

         ================================= ========================
         Item State                        Description
         ================================= ========================
         ``TreeItemIcon_Normal``           To get the normal item image
         ``TreeItemIcon_Selected``         To get the selected item image (i.e. the image which is shown when the item is currently selected)
         ``TreeItemIcon_Expanded``         To get the expanded image (this only makes sense for items which have children - then this image is shown when the item is expanded and the normal image is shown when it is collapsed)
         ``TreeItemIcon_SelectedExpanded`` To get the selected expanded image (which is shown when an expanded item is currently selected)
         ================================= ========================

        :return: An integer index that can be used to retrieve the item image inside
         a `wx.ImageList`.
        """

        return self._images[which]

[docs]    def GetCheckedImage(self, which=TreeItemIcon_Checked):
        """
        Returns the item check image.

        :param integer `which`: can be one of the following bits:

         ================================= ========================
         Item State                        Description
         ================================= ========================
         ``TreeItemIcon_Checked``          To get the checkbox checked item image
         ``TreeItemIcon_NotChecked``       To get the checkbox unchecked item image
         ``TreeItemIcon_Undetermined``     To get the checkbox undetermined state item image
         ``TreeItemIcon_Flagged``          To get the radiobutton checked image
         ``TreeItemIcon_NotFlagged``       To get the radiobutton unchecked image
         ================================= ========================

        :return: An integer index that can be used to retrieve the item check image inside
         a `wx.ImageList`.

        :note: This method is meaningful only for radio & check items.
        """

        return self._checkedimages[which]

[docs]    def GetLeftImage(self):
        """
        Returns the leftmost image associated to this item, i.e. the image on the
        leftmost part of the client area of L{CustomTreeCtrl}.

        :return: An integer index that can be used to retrieve the item leftmost image inside
         a `wx.ImageList`.
        """

        return self._leftimage

[docs]    def GetData(self):
        """
        Returns the data associated to this item.

        :return: A Python object representing the item data, or ``None`` if no data
         has been assigned to this item.
        """

        return self._data

[docs]    def SetImage(self, image, which):
        """
        Sets the item image.

        :param integer `image`: an index within the normal image list specifying the image to use;
        :param integer `which`: the image kind.

        :see: L{GetImage} for a description of the `which` parameter.
        """

        self._images[which] = image

[docs]    def SetLeftImage(self, image):
        """
        Sets the item leftmost image, i.e. the image associated to the item on the leftmost
        part of the L{CustomTreeCtrl} client area.

        :param integer `image`: an index within the left image list specifying the image to
         use for the item in the leftmost part of the client area.
        """

        self._leftimage = image

[docs]    def SetData(self, data):
        """
        Sets the data associated to this item.

        :param object `data`: can be any Python object.
        """

        self._data = data

[docs]    def SetHasPlus(self, has=True):
        """
        Sets whether an item has the 'plus' button.

        :param bool `has`: ``True`` to set the 'plus' button on the item, ``False`` otherwise.
        """

        self._hasPlus = has

[docs]    def SetBold(self, bold):
        """
        Sets the item font bold.

        :parameter bool `bold`: ``True`` to have a bold font item, ``False`` otherwise.
        """

        self._isBold = bold

[docs]    def SetItalic(self, italic):
        """
        Sets the item font italic.

        :parameter bool `italic`: ``True`` to have an italic font item, ``False`` otherwise.
        """

        self._isItalic = italic

[docs]    def GetX(self):
        """ Returns the `x` position on an item, in logical coordinates. """

        return self._x

[docs]    def GetY(self):
        """ Returns the `y` position on an item, in logical coordinates. """

        return self._y

[docs]    def SetX(self, x):
        """
        Sets the `x` position on an item, in logical coordinates.

        :param integer `x`: an integer specifying the x position of the item.
        """

        self._x = x

[docs]    def SetY(self, y):
        """
        Sets the `y` position on an item, in logical coordinates.

        :param integer `y`: an integer specifying the y position of the item.
        """

        self._y = y

[docs]    def GetHeight(self):
        """ Returns the height of the item, in pixels. """

        return self._height

[docs]    def GetWidth(self):
        """ Returns the width of the item, in pixels. """

        return self._width

[docs]    def SetHeight(self, h):
        """
        Sets the item's height.

        :param integer `h`: an integer specifying the item's height, in pixels.
        """

        self._height = h

[docs]    def SetWidth(self, w):
        """
        Sets the item's width.

        :param integer `w`: an integer specifying the item's width, in pixels.
        """

        self._width = w

[docs]    def SetWindow(self, wnd):
        """
        Sets the window associated to the item.

        :param `wnd`: a non-toplevel window to be displayed next to the item, any
         subclass of `wx.Window`.

        :raise: `Exception` if the input `item` is a separator and `wnd` is not ``None``.
        """

        if self.IsSeparator() and wnd is not None:
            raise Exception("Separator items can not have an associated window")

        self._wnd = wnd

        if wnd.GetSizer():      # the window is a complex one hold by a sizer
            size = wnd.GetBestSize()
        else:                   # simple window, without sizers
            size = wnd.GetSize()

        # We have to bind the wx.EVT_SET_FOCUS for the associated window
        # No other solution to handle the focus changing from an item in
        # CustomTreeCtrl and the window associated to an item
        # Do better strategies exist?
        self._wnd.Bind(wx.EVT_SET_FOCUS, self.OnSetFocus)

        self._height = size.GetHeight() + 2
        self._width = size.GetWidth()
        self._windowsize = size

        # We don't show the window if the item is collapsed
        if self._isCollapsed:
            self._wnd.Show(False)

        # The window is enabled only if the item is enabled
        self._wnd.Enable(self._enabled)
        self._windowenabled = self._enabled

[docs]    def GetWindow(self):
        """
        Returns the window associated to the item (if any).

        :return: An instance of any `wx.Window` derived class, excluding top-level windows.
        """

        return self._wnd

[docs]    def DeleteWindow(self):
        """ Deletes the window associated to the item (if any). """

        if self._wnd:
            self._wnd.Destroy()
            self._wnd = None

[docs]    def GetWindowEnabled(self):
        """
        Returns whether the associated window is enabled or not.

        :return: ``True`` if the associated window is enabled, ``False`` if it is disabled.

        :raise: `Exception` when the item has no associated window.
        """

        if not self._wnd:
            raise Exception("\nERROR: This Item Has No Window Associated")

        return self._windowenabled

[docs]    def SetWindowEnabled(self, enable=True):
        """
        Sets whether the associated window is enabled or not.

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

        :raise: `Exception` when the item has no associated window.
        """

        if not self._wnd:
            raise Exception("\nERROR: This Item Has No Window Associated")

        self._windowenabled = enable
        self._wnd.Enable(enable)

[docs]    def GetWindowSize(self):
        """ Returns the associated window size. """

        return self._windowsize

[docs]    def OnSetFocus(self, event):
        """
        Handles the ``wx.EVT_SET_FOCUS`` event for the window associated with the item.

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

        treectrl = self._wnd.GetParent()
        select = treectrl.GetSelection()

        # If the window is associated to an item that currently is selected
        # (has focus) we don't kill the focus. Otherwise we do it.
        if select != self:
            treectrl._hasFocus = False
        else:
            treectrl._hasFocus = True

        event.Skip()

[docs]    def GetType(self):
        """
        Returns the item type.

        :see: L{SetType} and L{__init__} for a description of valid item types.
        """

        return self._type

[docs]    def SetType(self, ct_type):
        """
        Sets the item type.

        :param integer `ct_type`: may be one of the following integers:

         =============== =========================================
         `ct_type` Value Description
         =============== =========================================
                0        A normal item
                1        A checkbox-like item
                2        A radiobutton-type item
         =============== =========================================

        :note: Regarding radiobutton-type items (with `ct_type` = 2), the following
         approach is used:

         - All peer-nodes that are radiobuttons will be mutually exclusive. In other words,
           only one of a set of radiobuttons that share a common parent can be checked at
           once. If a radiobutton node becomes checked, then all of its peer radiobuttons
           must be unchecked.
         - If a radiobutton node becomes unchecked, then all of its child nodes will become
           inactive.
        """

        self._type = ct_type

[docs]    def SetHyperText(self, hyper=True):
        """
        Sets whether the item is hypertext or not.

        :param bool `hyper`: ``True`` to set hypertext behaviour, ``False`` otherwise.
        """

        self._hypertext = hyper

[docs]    def SetVisited(self, visited=True):
        """
        Sets whether an hypertext item was visited or not.

        :param bool `visited`: ``True`` to set a hypertext item as visited, ``False`` otherwise.
        """

        self._visited = visited

[docs]    def GetVisited(self):
        """ Returns whether an hypertext item was visited or not. """

        return self._visited

[docs]    def IsHyperText(self):
        """ Returns whether the item is hypetext or not. """

        return self._hypertext

[docs]    def GetParent(self):
        """
        Gets the item parent (another instance of L{GenericTreeItem} or ``None`` for
        root items.

        :return: An instance of L{GenericTreeItem} or ``None`` for root items.
        """

        return self._parent

[docs]    def Insert(self, child, index):
        """
        Inserts an item in the item children list for this item.

        :param `child`: an instance of L{GenericTreeItem};
        :param integer `index`: the index at which we should insert the new child.
        """

        self._children.insert(index, child)

[docs]    def Expand(self):
        """ Expands the item. """

        self._isCollapsed = False

[docs]    def Collapse(self):
        """ Collapses the item. """

        self._isCollapsed = True

[docs]    def SetHilight(self, set=True):
        """
        Sets the item focus/unfocus.

        :param bool `set`: ``True`` to set the focus to the item, ``False`` otherwise.
        """

        self._hasHilight = set

[docs]    def HasChildren(self):
        """
        Returns whether the item has children or not.

        :return: ``True`` if the item has children, ``False`` otherwise.
        """

        return len(self._children) > 0

[docs]    def IsSelected(self):
        """
        Returns whether the item is selected or not.

        :return: ``True`` if the item is selected, ``False`` otherwise.
        """

        return self._hasHilight != 0

[docs]    def IsExpanded(self):
        """
        Returns whether the item is expanded or not.

        :return: ``True`` if the item is expanded, ``False`` if it is collapsed.
        """

        return not self._isCollapsed

[docs]    def GetValue(self):
        """
        Returns whether the item is checked or not.

        :note: This is meaningful only for checkbox-like and radiobutton-like items.
        """

        if self.Is3State():
            return self.Get3StateValue()

        return self._checked

[docs]    def Get3StateValue(self):
        """
        Gets the state of a 3-state checkbox item.

        :return: ``wx.CHK_UNCHECKED`` when the checkbox is unchecked, ``wx.CHK_CHECKED``
         when it is checked and ``wx.CHK_UNDETERMINED`` when it's in the undetermined
         state.

        :raise: `Exception` when the item is not a 3-state checkbox item.

        :note: This method raises an exception when the function is used with a 2-state
         checkbox item.

        :note: This method is meaningful only for checkbox-like items.
        """

        if not self.Is3State():
            raise Exception("Get3StateValue can only be used with 3-state checkbox items.")

        return self._checked

[docs]    def Is3State(self):
        """
        Returns whether or not the checkbox item is a 3-state checkbox.

        :return: ``True`` if this checkbox is a 3-state checkbox, ``False`` if it's a
         2-state checkbox item.

        :note: This method is meaningful only for checkbox-like items.
        """

        return self._is3State

[docs]    def Set3StateValue(self, state):
        """
        Sets the checkbox item to the given `state`.

        :param integer `state`: can be one of: ``wx.CHK_UNCHECKED`` (check is off), ``wx.CHK_CHECKED``
         (check is on) or ``wx.CHK_UNDETERMINED`` (check is mixed).

        :raise: `Exception` when the item is not a 3-state checkbox item.

        :note: This method raises an exception when the checkbox item is a 2-state checkbox
         and setting the state to ``wx.CHK_UNDETERMINED``.

        :note: This method is meaningful only for checkbox-like items.
        """

        if not self._is3State and state == wx.CHK_UNDETERMINED:
            raise Exception("Set3StateValue can only be used with 3-state checkbox items.")

        self._checked = state

[docs]    def Set3State(self, allow):
        """
        Sets whether the item has a 3-state value checkbox assigned to it or not.

        :param bool `allow`: ``True`` to set an item as a 3-state checkbox, ``False`` to set it
         to a 2-state checkbox.

        :return: ``True`` if the change was successful, ``False`` otherwise.

        :note: This method is meaningful only for checkbox-like items.
        """

        if self._type != 1:
            return False

        self._is3State = allow
        return True

[docs]    def IsChecked(self):
        """
        This is just a maybe more readable synonym for L{GetValue}.
        Returns whether the item is checked or not.

        :note: This is meaningful only for checkbox-like and radiobutton-like items.
        """

        return self.GetValue()

[docs]    def Check(self, checked=True):
        """
        Checks/unchecks an item.

        :param bool `checked`: ``True`` to check an item, ``False`` to uncheck it.

        :note: This is meaningful only for checkbox-like and radiobutton-like items.
        """

        self._checked = checked

[docs]    def HasPlus(self):
        """
        Returns whether the item has the plus button or not.

        :return: ``True`` if the item has a 'plus' mark, ``False`` otherwise.
        """

        return self._hasPlus or self.HasChildren()

[docs]    def IsBold(self):
        """
        Returns whether the item font is bold or not.

        :return: ``True`` if the item has bold text, ``False`` otherwise.
        """

        return self._isBold != 0

[docs]    def IsItalic(self):
        """
        Returns whether the item font is italic or not.

        :return: ``True`` if the item has italic text, ``False`` otherwise.
        """

        return self._isItalic != 0

[docs]    def Enable(self, enable=True):
        """
        Enables/disables the item.

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

        self._enabled = enable

[docs]    def IsEnabled(self):
        """
        Returns whether the item is enabled or not.

        :return: ``True`` if the item is enabled, ``False`` if it is disabled.
        """

        return self._enabled

[docs]    def GetAttributes(self):
        """
        Returns the item attributes (font, colours, etc...).

        :return: An instance of L{TreeItemAttr}.
        """

        return self._attr

[docs]    def Attr(self):
        """
        Creates a new attribute (font, colours, etc...) for this item.

        :return: An instance of L{TreeItemAttr}.
        """

        if not self._attr:

            self._attr = TreeItemAttr()
            self._ownsAttr = True

        return self._attr

[docs]    def SetAttributes(self, attr):
        """
        Sets the item attributes (font, colours, etc...).

        :param `attr`: an instance of L{TreeItemAttr}.
        """

        if self._ownsAttr:
             del self._attr

        self._attr = attr
        self._ownsAttr = False

[docs]    def AssignAttributes(self, attr):
        """
        Assigns the item attributes (font, colours, etc...) for this item.

        :param `attr`: an instance of L{TreeItemAttr}.
        """

        self.SetAttributes(attr)
        self._ownsAttr = True

[docs]    def DeleteChildren(self, tree):
        """
        Deletes the item children.

        :param `tree`: the main L{CustomTreeCtrl} instance.
        """

        for child in self._children:
            if tree:
                tree.SendDeleteEvent(child)

            child.DeleteChildren(tree)

            if child == tree._select_me:
                tree._select_me = None

            # We have to destroy the associated window
            wnd = child.GetWindow()
            if wnd:
                wnd.Destroy()
                child._wnd = None

            if child in tree._itemWithWindow:
                tree._itemWithWindow.remove(child)

            del child

        self._children = []

[docs]    def SetText(self, text):
        """
        Sets the item text.

        :param string `text`: the new item label.

        :raise: `Exception` if the item is a separator.
        """

        if self.IsSeparator():
            raise Exception("Separator items can not have text")

        self._text = text

[docs]    def GetChildrenCount(self, recursively=True):
        """
        Gets the number of children of this item.

        :param bool `recursively`: if ``True``, returns the total number of descendants,
         otherwise only one level of children is counted.
        """

        count = len(self._children)

        if not recursively:
            return count

        total = count

        for n in xrange(count):
            total += self._children[n].GetChildrenCount()

        return total

[docs]    def GetSize(self, x, y, theButton):
        """
        Returns the item size.

        :param integer `x`: the current item's x position;
        :param integer `y`: the current item's y position;
        :param `theButton`: an instance of the main L{CustomTreeCtrl}.

        :return: A tuple of (`x`, `y`) dimensions, in pixels, representing the
         item's width and height.
        """

        bottomY = self._y + theButton.GetLineHeight(self)

        if y < bottomY:
            y = bottomY

        width = self._x + self._width

        if x < width:
            x = width

        if self.IsExpanded():
            for child in self._children:
                x, y = child.GetSize(x, y, theButton)

        return x, y

[docs]    def HitTest(self, point, theCtrl, flags=0, level=0):
        """
        L{HitTest} method for an item. Called from the main window L{CustomTreeCtrl.HitTest}.

        :param `point`: the point to test for the hit (an instance of `wx.Point`);
        :param `theCtrl`: the main L{CustomTreeCtrl} tree;
        :param integer `flags`: a bitlist of hit locations;
        :param integer `level`: the item's level inside the tree hierarchy.

        :see: L{CustomTreeCtrl.HitTest} method for the flags explanation.
        """

        # for a hidden root node, don't evaluate it, but do evaluate children
        if not (level == 0 and theCtrl.HasAGWFlag(TR_HIDE_ROOT)):

            # evaluate the item
            h = theCtrl.GetLineHeight(self)

            if point.y > self._y and point.y < self._y + h:

                y_mid = self._y + h/2

                if point.y < y_mid:
                    flags |= TREE_HITTEST_ONITEMUPPERPART
                else:
                    flags |= TREE_HITTEST_ONITEMLOWERPART

                xCross = self._x - theCtrl.GetSpacing()

                if wx.Platform == "__WXMAC__":
                    # according to the drawing code the triangels are drawn
                    # at -4 , -4  from the position up to +10/+10 max
                    if point.x > xCross-4 and point.x < xCross+10 and point.y > y_mid-4 and \
                       point.y < y_mid+10 and self.HasPlus() and theCtrl.HasButtons():

                        flags |= TREE_HITTEST_ONITEMBUTTON
                        return self, flags
                else:
                    # 5 is the size of the plus sign
                    if point.x > xCross-6 and point.x < xCross+6 and point.y > y_mid-6 and \
                       point.y < y_mid+6 and self.HasPlus() and theCtrl.HasButtons():

                        flags |= TREE_HITTEST_ONITEMBUTTON
                        return self, flags

                if point.x >= self._x and point.x <= self._x + self._width:

                    image_w = -1
                    wcheck = 0

                    # assuming every image (normal and selected) has the same size!
                    if self.GetImage() != _NO_IMAGE and theCtrl._imageListNormal:
                        image_w, image_h = theCtrl._imageListNormal.GetSize(self.GetImage())

                    if self.GetCheckedImage() is not None:
                        wcheck, hcheck = theCtrl._imageListCheck.GetSize(self.GetCheckedImage())

                    if wcheck and point.x <= self._x + wcheck + 1:
                        flags |= TREE_HITTEST_ONITEMCHECKICON
                        return self, flags

                    if image_w != -1 and point.x <= self._x + wcheck + image_w + 1:
                        flags |= TREE_HITTEST_ONITEMICON
                    else:
                        flags |= TREE_HITTEST_ONITEMLABEL

                    return self, flags

                if point.x < self._x:
                    if theCtrl.HasAGWFlag(TR_FULL_ROW_HIGHLIGHT):
                        flags |= TREE_HITTEST_ONITEM
                    else:
                        flags |= TREE_HITTEST_ONITEMINDENT
                if point.x > self._x + self._width:
                    if theCtrl.HasAGWFlag(TR_FULL_ROW_HIGHLIGHT):
                        flags |= TREE_HITTEST_ONITEM
                    else:
                        flags |= TREE_HITTEST_ONITEMRIGHT

                return self, flags

            # if children are expanded, fall through to evaluate them
            if self._isCollapsed:
                return None, 0

        # evaluate children
        for child in self._children:
            res, flags = child.HitTest(point, theCtrl, flags, level + 1)
            if res != None:
                return res, flags

        return None, 0

[docs]    def GetCurrentImage(self):
        """
        Returns the current item image.

        :return: An integer index that can be used to retrieve the item image inside
         a `wx.ImageList`.
        """

        image = _NO_IMAGE

        if self.IsExpanded():

            if self.IsSelected():

                image = self._images[TreeItemIcon_SelectedExpanded]

            if image == _NO_IMAGE:

                # we usually fall back to the normal item, but try just the
                # expanded one (and not selected) first in this case
                image = self._images[TreeItemIcon_Expanded]

        else: # not expanded

            if self.IsSelected():
                image = self._images[TreeItemIcon_Selected]

        # maybe it doesn't have the specific image we want,
        # try the default one instead
        if image == _NO_IMAGE:
            image = self._images[TreeItemIcon_Normal]

        return image

[docs]    def GetCurrentCheckedImage(self):
        """
        Returns the current item check image.

        :return: An integer index that can be used to retrieve the item check image inside
         a `wx.ImageList`.
        """

        if self._type == 0:
            return None

        checked = self.IsChecked()

        if checked > 0:
            if self._type == 1:     # Checkbox
                if checked == wx.CHK_CHECKED:
                    return self._checkedimages[TreeItemIcon_Checked]
                else:
                    return self._checkedimages[TreeItemIcon_Undetermined]
            else:                   # Radiobutton
                return self._checkedimages[TreeItemIcon_Flagged]
        else:
            if self._type == 1:     # Checkbox
                return self._checkedimages[TreeItemIcon_NotChecked]
            else:                   # Radiobutton
                return self._checkedimages[TreeItemIcon_NotFlagged]

# -----------------------------------------------------------------------------
# CustomTreeCtrl Main Implementation.
# This Is The Main Class.
# -----------------------------------------------------------------------------

[docs]class CustomTreeCtrl(wx.PyScrolledWindow):
    """
    L{CustomTreeCtrl} is a class that mimics the behaviour of `wx.TreeCtrl`, with almost the
    same base functionalities plus some more enhancements. This class does not rely on
    the native control, as it is a full owner-drawn tree control.
    """

[docs]    def __init__(self, parent, id=wx.ID_ANY, pos=wx.DefaultPosition, size=wx.DefaultSize,
                 style=0, agwStyle=TR_DEFAULT_STYLE, validator=wx.DefaultValidator,
                 name="CustomTreeCtrl"):
        """
        Default class constructor.

        :param `wx.Window` `parent`: parent window. Must not be ``None``;
        :param integer `id`: window identifier. A value of -1 indicates a default value;
        :param `pos`: the control position. A value of (-1, -1) indicates a default position,
         chosen by either the windowing system or wxPython, depending on platform;
        :type `pos`: tuple or `wx.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 `wx.Size`
        :param integer `style`: the underlying `wx.PyScrolledWindow` style;
        :param integer `agwStyle`: the AGW-specific window style for L{CustomTreeCtrl}. It can be a
         combination of the following bits:

         ============================== =========== ==================================================
         Window Styles                  Hex Value   Description
         ============================== =========== ==================================================
         ``TR_NO_BUTTONS``                      0x0 For convenience to document that no buttons are to be drawn.
         ``TR_SINGLE``                          0x0 For convenience to document that only one item may be selected at a time. Selecting another item causes the current selection, if any, to be deselected. This is the default.
         ``TR_HAS_BUTTONS``                     0x1 Use this style to show + and - buttons to the left of parent items.
         ``TR_NO_LINES``                        0x4 Use this style to hide vertical level connectors.
         ``TR_LINES_AT_ROOT``                   0x8 Use this style to show lines between root nodes. Only applicable if ``TR_HIDE_ROOT`` is set and ``TR_NO_LINES`` is not set.
         ``TR_DEFAULT_STYLE``                   0x9 The set of flags that are closest to the defaults for the native control for a particular toolkit.
         ``TR_TWIST_BUTTONS``                  0x10 Use old Mac-twist style buttons.
         ``TR_MULTIPLE``                       0x20 Use this style to allow a range of items to be selected. If a second range is selected, the current range, if any, is deselected.
         ``TR_EXTENDED``                       0x40 Use this style to allow disjoint items to be selected. (Only partially implemented; may not work in all cases).
         ``TR_HAS_VARIABLE_ROW_HEIGHT``        0x80 Use this style to cause row heights to be just big enough to fit the content. If not set, all rows use the largest row height. The default is that this flag is unset.
         ``TR_EDIT_LABELS``                   0x200 Use this style if you wish the user to be able to edit labels in the tree control.
         ``TR_ROW_LINES``                     0x400 Use this style to draw a contrasting border between displayed rows.
         ``TR_HIDE_ROOT``                     0x800 Use this style to suppress the display of the root node, effectively causing the first-level nodes to appear as a series of root nodes.
         ``TR_FULL_ROW_HIGHLIGHT``           0x2000 Use this style to have the background colour and the selection highlight extend  over the entire horizontal row of the tree control window.
         ``TR_AUTO_CHECK_CHILD``             0x4000 Only meaningful foe checkbox-type items: when a parent item is checked/unchecked its children are checked/unchecked as well.
         ``TR_AUTO_TOGGLE_CHILD``            0x8000 Only meaningful foe checkbox-type items: when a parent item is checked/unchecked its children are toggled accordingly.
         ``TR_AUTO_CHECK_PARENT``           0x10000 Only meaningful foe checkbox-type items: when a child item is checked/unchecked its parent item is checked/unchecked as well.
         ``TR_ALIGN_WINDOWS``               0x20000 Flag used to align windows (in items with windows) at the same horizontal position.
         ``TR_ALIGN_WINDOWS_RIGHT``         0x40000 Flag used to align windows (in items with windows) to the rightmost edge of L{CustomTreeCtrl}.
         ``TR_ELLIPSIZE_LONG_ITEMS``        0x80000 Flag used to ellipsize long items when the horizontal space for L{CustomTreeCtrl} is low.
         ``TR_TOOLTIP_ON_LONG_ITEMS``      0x100000 Flag used to show tooltips on long items when the horizontal space for L{CustomTreeCtrl} is low.
         ============================== =========== ==================================================

        :param `wx.Validator` `validator`: window validator;
        :param string `name`: window name.
        """

        self._current = self._key_current = self._anchor = self._select_me = None
        self._hasFocus = False
        self._dirty = False

        # Default line height: it will soon be changed
        self._lineHeight = 10
        # Item indent wrt parent
        self._indent = 15
        # item horizontal spacing between the start and the text
        self._spacing = 18

        # Brushes for focused/unfocused items (also gradient type)
        self._hilightBrush = wx.Brush(wx.SystemSettings_GetColour(wx.SYS_COLOUR_HIGHLIGHT))
        btnshadow = wx.SystemSettings_GetColour(wx.SYS_COLOUR_BTNSHADOW)
        self._hilightUnfocusedBrush = wx.Brush(btnshadow)
        r, g, b = btnshadow.Red(), btnshadow.Green(), btnshadow.Blue()
        backcolour = (max((r >> 1) - 20, 0),
                      max((g >> 1) - 20, 0),
                      max((b >> 1) - 20, 0))
        backcolour = wx.Colour(backcolour[0], backcolour[1], backcolour[2])
        self._hilightUnfocusedBrush2 = wx.Brush(backcolour)

        # image list for icons
        self._imageListNormal = self._imageListButtons = self._imageListState = self._imageListCheck = self._imageListLeft = None
        self._ownsImageListNormal = self._ownsImageListButtons = self._ownsImageListState = self._ownsImageListLeft = False

        # Drag and drop initial settings
        self._dragCount = 0
        self._countDrag = 0
        self._isDragging = False
        self._dropTarget = self._oldSelection = None
        self._dragImage = None
        self._underMouse = None

        # EditCtrl initial settings for editable items
        self._editCtrl = None
        self._editTimer = None

        # This one allows us to handle Freeze() and Thaw() calls
        self._freezeCount = 0

        self._findPrefix = ""
        self._findTimer = None

        self._dropEffectAboveItem = False
        self._lastOnSame = False

        # Default normal and bold fonts for an item
        self._hasFont = True
        self._normalFont = wx.SystemSettings_GetFont(wx.SYS_DEFAULT_GUI_FONT)
        family = self._normalFont.GetFamily()
        if family == wx.FONTFAMILY_UNKNOWN:
            family = wx.FONTFAMILY_SWISS
        self._boldFont = wx.Font(self._normalFont.GetPointSize(), family,
                                 self._normalFont.GetStyle(), wx.BOLD, self._normalFont.GetUnderlined(),
                                 self._normalFont.GetFaceName(), self._normalFont.GetEncoding())
        self._italicFont = wx.Font(self._normalFont.GetPointSize(), family,
                                   wx.FONTSTYLE_ITALIC, wx.NORMAL, self._normalFont.GetUnderlined(),
                                   self._normalFont.GetFaceName(), self._normalFont.GetEncoding())

        # Hyperlinks things
        self._hypertextfont = wx.Font(self._normalFont.GetPointSize(), family,
                                      self._normalFont.GetStyle(), wx.NORMAL, True,
                                      self._normalFont.GetFaceName(), self._normalFont.GetEncoding())
        self._hypertextnewcolour = wx.BLUE
        self._hypertextvisitedcolour = wx.Colour(200, 47, 200)
        self._isonhyperlink = False

        # Default CustomTreeCtrl background colour.
        self._backgroundColour = wx.WHITE

        # Background image settings
        self._backgroundImage = None
        self._imageStretchStyle = _StyleTile

        # Disabled items colour
        self._disabledColour = wx.Colour(180, 180, 180)

        # Gradient selection colours
        self._firstcolour = colour = wx.SystemSettings_GetColour(wx.SYS_COLOUR_HIGHLIGHT)
        self._secondcolour = wx.WHITE
        self._usegradients = False
        self._gradientstyle = 0   # Horizontal Gradient

        # Vista Selection Styles
        self._vistaselection = False

        # To speed up ExpandAll and SelectAll
        self._sendEvent = True

        # Connection lines style
        grey = (160,160,160)
        if wx.Platform != "__WXMAC__":
            self._dottedPen = wx.Pen(grey, 1, wx.USER_DASH)
            self._dottedPen.SetDashes([1,1])
            self._dottedPen.SetCap(wx.CAP_BUTT)
        else:
            self._dottedPen = wx.Pen(grey, 1)

        # Pen Used To Draw The Border Around Selected Items
        self._borderPen = wx.BLACK_PEN
        self._cursor = wx.StockCursor(wx.CURSOR_ARROW)

        # For Appended Windows
        self._hasWindows = False
        self._itemWithWindow = []

        if wx.Platform == "__WXMAC__":
            agwStyle &= ~TR_LINES_AT_ROOT
            agwStyle |= TR_NO_LINES

            platform, major, minor = wx.GetOsVersion()
            if major < 10:
                agwStyle |= TR_ROW_LINES

        # A constant to use my translation of RendererNative.DrawTreeItemButton
        # if the wxPython version is less than 2.6.2.1.
        if _VERSION_STRING < "2.6.2.1":
            self._drawingfunction = DrawTreeItemButton
        else:
            self._drawingfunction = wx.RendererNative.Get().DrawTreeItemButton

        # Set the separator pen default colour
        self._separatorPen = wx.Pen(wx.SystemSettings.GetColour(wx.SYS_COLOUR_GRAYTEXT))

        # Create our container... at last!
        wx.PyScrolledWindow.__init__(self, parent, id, pos, size, style|wx.HSCROLL|wx.VSCROLL, name)

        self._agwStyle = agwStyle

        # Create the default check image list
        self.SetImageListCheck(16, 16)

        # If the tree display has no buttons, but does have
        # connecting lines, we can use a narrower layout.
        # It may not be a good idea to force this...
        if not self.HasButtons() and not self.HasAGWFlag(TR_NO_LINES):
            self._indent= 10
            self._spacing = 10

        self.SetValidator(validator)

        attr = self.GetDefaultAttributes()
        self.SetOwnForegroundColour(attr.colFg)
        self.SetOwnBackgroundColour(attr.colBg)

        if not self._hasFont:
            self.SetOwnFont(attr.font)

        self.SetSize(size)

        # Bind the events
        self.Bind(wx.EVT_PAINT, self.OnPaint)
        self.Bind(wx.EVT_ERASE_BACKGROUND, self.OnEraseBackground)
        self.Bind(wx.EVT_SIZE, self.OnSize)
        self.Bind(wx.EVT_MOUSE_EVENTS, self.OnMouse)
        self.Bind(wx.EVT_KEY_DOWN, self.OnKeyDown)
        self.Bind(wx.EVT_SET_FOCUS, self.OnSetFocus)
        self.Bind(wx.EVT_KILL_FOCUS, self.OnKillFocus)
        self.Bind(EVT_TREE_ITEM_GETTOOLTIP, self.OnGetToolTip)
        self.Bind(wx.EVT_WINDOW_DESTROY, self.OnDestroy)

        # Sets the focus to ourselves: this is useful if you have items
        # with associated widgets.
        self.SetFocus()

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

        :note: This method always returns ``True`` as we always accept focus from
         mouse click.

        :note: Overridden from `wx.PyScrolledWindow`.
        """

        # overridden base class method, allows this ctrl to
        # participate in the tab-order, etc.  It's overridable because
        # of deriving this class from wx.PyScrolledWindow...
        return True

[docs]    def OnDestroy(self, event):
        """
        Handles the ``wx.EVT_WINDOW_DESTROY`` event for L{CustomTreeCtrl}.

        :param `event`: a `wx.WindowDestroyEvent` event to be processed.
        """

        # Here there may be something I miss... do I have to destroy
        # something else?
        if self._editTimer and self._editTimer.IsRunning():
            self._editTimer.Stop()
            del self._editTimer
            self._editTimer = None

        if self._findTimer and self._findTimer.IsRunning():
            self._findTimer.Stop()
            del self._findTimer

        event.Skip()

[docs]    def GetControlBmp(self, checkbox=True, checked=False, enabled=True, x=16, y=16):
        """
        Returns a native looking checkbox or radio button bitmap.

        :param bool `checkbox`: ``True`` to get a checkbox image, ``False`` for a radiobutton one;
        :param bool `checked`: ``True`` if the control is marked, ``False`` if it is not;
        :param bool `enabled`: ``True`` if the control is enabled, ``False`` if it is not;
        :param integer `x`: the width of the bitmap;
        :param integer `y`: the height of the bitmap.

        :return: An instance of `wx.Bitmap`, representing a native looking checkbox or radiobutton.
        """

        bmp = wx.EmptyBitmap(x, y)
        mdc = wx.MemoryDC(bmp)
        mask = wx.Colour(0xfe, 0xfe, 0xfe)
        mdc.SetBackground(wx.Brush(mask))
        mdc.Clear()

        render = wx.RendererNative.Get()

        if checked == wx.CHK_CHECKED:
            flag = wx.CONTROL_CHECKED
        elif checked == wx.CHK_UNDETERMINED:
            flag = wx.CONTROL_UNDETERMINED
        else:
            flag = 0

        if not enabled:
            flag |= wx.CONTROL_DISABLED

        if checkbox:
            render.DrawCheckBox(self, mdc, (0, 0, x, y), flag)
        else:
            if _VERSION_STRING < "2.9":
                render.DrawRadioButton(self, mdc, (0, 0, x, y), flag)
            else:
                render.DrawRadioBitmap(self, mdc, (0, 0, x, y), flag)

        mdc.SelectObject(wx.NullBitmap)
        bmp.SetMaskColour(mask)
        return bmp

[docs]    def GetCount(self):
        """ Returns the global number of items in the tree. """

        if not self._anchor:
            # the tree is empty
            return 0

        count = self._anchor.GetChildrenCount()

        if not self.HasAGWFlag(TR_HIDE_ROOT):
            # take the root itself into account
            count = count + 1

        return count

[docs]    def GetIndent(self):
        """ Returns the item indentation, in pixels. """

        return self._indent

[docs]    def GetSpacing(self):
        """ Returns the spacing between the start and the text, in pixels. """

        return self._spacing

[docs]    def GetRootItem(self):
        """ Returns the root item, an instance of L{GenericTreeItem}. """

        return self._anchor

[docs]    def GetSelection(self):
        """
        Returns the current selection.

        :return: An instance of L{GenericTreeItem}.

        :note:

         This method is valid only with the style ``TR_SINGLE`` set. Use
         L{GetSelections} for multiple-selections trees.
        """

        return self._current

[docs]    def ToggleItemSelection(self, item):
        """
        Toggles the item selection.

        :param `item`: an instance of L{GenericTreeItem}.
        """

        self.SelectItem(item, not self.IsSelected(item))

[docs]    def EnableChildren(self, item, enable=True):
        """
        Enables/disables the item children.

        :param `item`: an instance of L{GenericTreeItem};
        :param bool `enable`: ``True`` to enable the children, ``False`` to disable them.

        :note: This method is used internally.
        """

        torefresh = False
        if item.IsExpanded():
            torefresh = True

        if item.GetType() == 2 and enable and not item.IsChecked():
            # We hit a radiobutton item not checked, we don't want to
            # enable the children
            return

        child, cookie = self.GetFirstChild(item)
        while child:
            self.EnableItem(child, enable, torefresh=torefresh)
            # Recurse on tree
            if child.GetType != 2 or (child.GetType() == 2 and item.IsChecked()):
                self.EnableChildren(child, enable)
            (child, cookie) = self.GetNextChild(item, cookie)

[docs]    def EnableItem(self, item, enable=True, torefresh=True):
        """
        Enables/disables an item.

        :param `item`: an instance of L{GenericTreeItem};
        :param bool `enable`: ``True`` to enable the item, ``False`` to disable it;
        :param bool `torefresh`: whether to redraw the item or not.
        """

        if item.IsEnabled() == enable:
            return

        if not enable and item.IsSelected():
            self.SelectItem(item, False)

        item.Enable(enable)
        wnd = item.GetWindow()

        # Handles the eventual window associated to the item
        if wnd:
            wndenable = item.GetWindowEnabled()
            wnd.Enable(enable)

        if torefresh:
            # We have to refresh the item line
            dc = wx.ClientDC(self)
            self.CalculateSize(item, dc)
            self.RefreshLine(item)

[docs]    def IsItemEnabled(self, item):
        """
        Returns whether an item is enabled or disabled.

        :param `item`: an instance of L{GenericTreeItem}.
        """

        return item.IsEnabled()

[docs]    def SetDisabledColour(self, colour):
        """
        Sets the colour for items in a disabled state.

        :param `colour`: a valid `wx.Colour` instance.
        """

        self._disabledColour = colour
        self._dirty = True

[docs]    def GetDisabledColour(self):
        """
        Returns the colour for items in a disabled state.

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

        return self._disabledColour

[docs]    def IsItemChecked(self, item):
        """
        Returns whether an item is checked or not.

        :param `item`: an instance of L{GenericTreeItem}.

        :return: ``True`` if the item is in a 'checked' state, ``False`` otherwise.

        :note: This method is meaningful only for checkbox-like and radiobutton-like items.
        """

        return item.IsChecked()

[docs]    def GetItem3StateValue(self, item):
        """
        Gets the state of a 3-state checkbox item.

        :param `item`: an instance of L{GenericTreeItem}.

        :return: ``wx.CHK_UNCHECKED`` when the checkbox is unchecked, ``wx.CHK_CHECKED``
         when it is checked and ``wx.CHK_UNDETERMINED`` when it's in the undetermined
         state.

        :note: This method raises an exception when the function is used with a 2-state
         checkbox item.

        :note: This method is meaningful only for checkbox-like items.
        """

        return item.Get3StateValue()

[docs]    def IsItem3State(self, item):
        """
        Returns whether or not the checkbox item is a 3-state checkbox.

        :param `item`: an instance of L{GenericTreeItem}.

        :return: ``True`` if this checkbox is a 3-state checkbox, ``False`` if it's a
         2-state checkbox item.

        :note: This method is meaningful only for checkbox-like items.
        """

        return item.Is3State()

[docs]    def SetItem3StateValue(self, item, state):
        """
        Sets the checkbox item to the given `state`.

        :param `item`: an instance of L{GenericTreeItem};
        :param integer `state`: can be one of: ``wx.CHK_UNCHECKED`` (check is off), ``wx.CHK_CHECKED``
         (check is on) or ``wx.CHK_UNDETERMINED`` (check is mixed).

        :note: This method raises an exception when the checkbox item is a 2-state checkbox
         and setting the state to ``wx.CHK_UNDETERMINED``.

        :note: This method is meaningful only for checkbox-like items.
        """

        item.Set3StateValue(state)

[docs]    def SetItem3State(self, item, allow):
        """
        Sets whether the item has a 3-state value checkbox assigned to it or not.

        :param `item`: an instance of L{GenericTreeItem};
        :param bool `allow`: ``True`` to set an item as a 3-state checkbox, ``False`` to set it
         to a 2-state checkbox.

        :return: ``True`` if the change was successful, ``False`` otherwise.

        :note: This method is meaningful only for checkbox-like items.
        """

        return item.Set3State(allow)

[docs]    def CheckItem2(self, item, checked=True, torefresh=False):
        """
        Used internally to avoid ``EVT_TREE_ITEM_CHECKED`` events.

        :param `item`: an instance of L{GenericTreeItem};
        :param bool `checked`: ``True`` to check an item, ``False`` to uncheck it;
        :param bool `torefresh`: whether to redraw the item or not.
        """

        if item.GetType() == 0:
            return

        item.Check(checked)

        if torefresh:
            dc = wx.ClientDC(self)
            self.CalculateSize(item, dc)
            self.RefreshLine(item)

[docs]    def UnCheckRadioParent(self, item, checked=False):
        """
        Used internally to handle radio node parent correctly.

        :param `item`: an instance of L{GenericTreeItem};
        :param bool `checked`: ``True`` to check an item, ``False`` to uncheck it.
        """

        e = TreeEvent(wxEVT_TREE_ITEM_CHECKING, self.GetId())
        e.SetItem(item)
        e.SetEventObject(self)

        if self.GetEventHandler().ProcessEvent(e):
            return False

        item.Check(checked)
        self.RefreshLine(item)
        self.EnableChildren(item, checked)
        e = TreeEvent(wxEVT_TREE_ITEM_CHECKED, self.GetId())
        e.SetItem(item)
        e.SetEventObject(self)
        self.GetEventHandler().ProcessEvent(e)

        return True

[docs]    def CheckItem(self, item, checked=True):
        """
        Actually checks/uncheks an item, sending (eventually) the two
        events ``EVT_TREE_ITEM_CHECKING`` and ``EVT_TREE_ITEM_CHECKED``.

        :param `item`: an instance of L{GenericTreeItem};
        :param bool `checked`: for a radiobutton-type item, ``True`` to check it, ``False``
         to uncheck it. For a checkbox-type item, it can be one of ``wx.CHK_UNCHECKED``
         when the checkbox is unchecked, ``wx.CHK_CHECKED`` when it is checked and
         ``wx.CHK_UNDETERMINED`` when it's in the undetermined state.
        """

        # Should we raise an error here?!?
        if item.GetType() == 0:
            return

        if item.GetType() == 2:    # it's a radio button
            if not checked and item.IsChecked():  # Try To Unckeck?
                return
            else:
                if not self.UnCheckRadioParent(item, checked):
                    return

                self.CheckSameLevel(item, False)
                return

        # Radiobuttons are done, let's handle checkbuttons...
        e = TreeEvent(wxEVT_TREE_ITEM_CHECKING, self.GetId())
        e.SetItem(item)
        e.SetEventObject(self)

        if self.GetEventHandler().ProcessEvent(e):
            # Blocked by user
            return

        if item.Is3State():
            item.Set3StateValue(checked)
        else:
            item.Check(checked)

        dc = wx.ClientDC(self)
        self.RefreshLine(item)

        if self.HasAGWFlag(TR_AUTO_CHECK_CHILD):
            ischeck = self.IsItemChecked(item)
            self.AutoCheckChild(item, ischeck)
        if self.HasAGWFlag(TR_AUTO_CHECK_PARENT):
            ischeck = self.IsItemChecked(item)
            self.AutoCheckParent(item, ischeck)
        elif self.HasAGWFlag(TR_AUTO_TOGGLE_CHILD):
            self.AutoToggleChild(item)

        e = TreeEvent(wxEVT_TREE_ITEM_CHECKED, self.GetId())
        e.SetItem(item)
        e.SetEventObject(self)
        self.GetEventHandler().ProcessEvent(e)

[docs]    def AutoToggleChild(self, item):
        """
        Transverses the tree and toggles the items.

        :param `item`: an instance of L{GenericTreeItem}.

        :note: This method is meaningful only for checkbox-like and radiobutton-like items.
        """

        child, cookie = self.GetFirstChild(item)

        torefresh = False
        if item.IsExpanded():
            torefresh = True

        # Recurse on tree
        while child:
            if child.GetType() == 1 and child.IsEnabled():
                self.CheckItem2(child, not child.IsChecked(), torefresh=torefresh)
            self.AutoToggleChild(child)
            (child, cookie) = self.GetNextChild(item, cookie)

[docs]    def AutoCheckChild(self, item, checked):
        """
        Transverses the tree and checks/unchecks the items.

        :param `item`: an instance of L{GenericTreeItem};
        :param bool `checked`: ``True`` to check an item, ``False`` to uncheck it.

        :note: This method is meaningful only for checkbox-like and radiobutton-like items.
        """

        (child, cookie) = self.GetFirstChild(item)

        torefresh = False
        if item.IsExpanded():
            torefresh = True

        while child:
            if child.GetType() == 1 and child.IsEnabled():
                self.CheckItem2(child, checked, torefresh=torefresh)
            self.AutoCheckChild(child, checked)
            (child, cookie) = self.GetNextChild(item, cookie)

[docs]    def AutoCheckParent(self, item, checked):
        """
        Traverses up the tree and checks/unchecks parent items.

        :param `item`: an instance of L{GenericTreeItem};
        :param bool `checked`: ``True`` to check an item, ``False`` to uncheck it.

        :note: This method is meaningful only for checkbox-like and radiobutton-like items.
        """

        parent = item.GetParent()
        if not parent or parent.GetType() != 1:
            return

        (child, cookie) = self.GetFirstChild(parent)
        while child:
            if child.GetType() == 1 and child.IsEnabled():
                if checked != child.IsChecked():
                    return
            (child, cookie) = self.GetNextChild(parent, cookie)

        self.CheckItem2(parent, checked, torefresh=True)
        self.AutoCheckParent(parent, checked)

[docs]    def CheckChilds(self, item, checked=True):
        """
        Programatically check/uncheck item children.

        :param `item`: an instance of L{GenericTreeItem};
        :param bool `checked`: ``True`` to check an item, ``False`` to uncheck it.

        :note: This method is meaningful only for checkbox-like and radiobutton-like items.

        :note: This method does not generate ``EVT_TREE_ITEM_CHECKING`` and
         ``EVT_TREE_ITEM_CHECKED`` events.
        """

        if checked == None:
            self.AutoToggleChild(item)
        else:
            self.AutoCheckChild(item, checked)

[docs]    def CheckSameLevel(self, item, checked=False):
        """
        Uncheck radio items which are on the same level of the checked one.
        Used internally.

        :param `item`: an instance of L{GenericTreeItem};
        :param bool `checked`: ``True`` to check an item, ``False`` to uncheck it.

        :note: This method is meaningful only for radiobutton-like items.
        """

        parent = item.GetParent()

        if not parent:
            return

        torefresh = False
        if parent.IsExpanded():
            torefresh = True

        (child, cookie) = self.GetFirstChild(parent)
        while child:
            if child.GetType() == 2 and child != item:
                self.CheckItem2(child, checked, torefresh=torefresh)
                if child.GetType != 2 or (child.GetType() == 2 and child.IsChecked()):
                    self.EnableChildren(child, checked)
            (child, cookie) = self.GetNextChild(parent, cookie)

[docs]    def EditLabel(self, item):
        """
        Starts editing an item label.

        :param `item`: an instance of L{GenericTreeItem}.
        """

        self.Edit(item)

[docs]    def ShouldInheritColours(self):
        """
        Return ``True`` from here to allow the colours of this window to be
        changed by `InheritAttributes`, returning ``False`` forbids inheriting them
        from the parent window.

        The base class version returns ``False``, but this method is overridden in
        `wx.Control` where it returns ``True``.

        L{CustomTreeCtrl} does not inherit colours from anyone.
        """

        return False

[docs]    def SetIndent(self, indent):
        """
        Sets the indentation for L{CustomTreeCtrl}.

        :param integer `indent`: an integer representing the indentation for the items in the tree.
        """

        self._indent = indent
        self._dirty = True

[docs]    def SetSpacing(self, spacing):
        """
        Sets the spacing between items in L{CustomTreeCtrl}.

        :param integer `spacing`: an integer representing the spacing between items in the tree.
        """

        self._spacing = spacing
        self._dirty = True

[docs]    def HasChildren(self, item):
        """
        Returns whether an item has children or not.

        :param `item`: an instance of L{GenericTreeItem}.
        """

        return len(item.GetChildren()) > 0

[docs]    def GetChildrenCount(self, item, recursively=True):
        """
        Returns the item children count.

        :param `item`: an instance of L{GenericTreeItem};
        :param bool `recursively`: if ``True``, returns the total number of descendants,
         otherwise only one level of children is counted.
        """

        return item.GetChildrenCount(recursively)

[docs]    def HasAGWFlag(self, flag):
        """
        Returns ``True`` if L{CustomTreeCtrl} has the `flag` bit set.

        :param integer `flag`: any possible window style for L{CustomTreeCtrl}.

        :see: The L{__init__} method for the `flag` parameter description.
        """

        return self._agwStyle & flag

[docs]    def SetAGWWindowStyleFlag(self, agwStyle):
        """
        Sets the L{CustomTreeCtrl} window style.

        :param integer `agwStyle`: the new L{CustomTreeCtrl} window style.

        :see: The L{__init__} method for the `agwStyle` parameter description.
        """

        # Do not try to expand the root node if it hasn't been created yet
        if self._anchor and not self.HasAGWFlag(TR_HIDE_ROOT) and agwStyle & TR_HIDE_ROOT:

            # if we will hide the root, make sure children are visible
            self._anchor.SetHasPlus()
            self._anchor.Expand()
            self.CalculatePositions()

        # right now, just sets the styles.  Eventually, we may
        # want to update the inherited styles, but right now
        # none of the parents has updatable styles

        if self.HasAGWFlag(TR_MULTIPLE) and not (agwStyle & TR_MULTIPLE):
            selections = self.GetSelections()
            for select in selections[0:-1]:
                self.SelectItem(select, False)

        self._agwStyle = agwStyle
        self._dirty = True

[docs]    def GetAGWWindowStyleFlag(self):
        """
        Returns the L{CustomTreeCtrl} style.

        :see: The L{__init__} method for a list of possible style flags.
        """

        return self._agwStyle

[docs]    def HasButtons(self):
        """
        Returns whether L{CustomTreeCtrl} has the ``TR_HAS_BUTTONS`` flag set.

        :return: ``True`` if L{CustomTreeCtrl} has the ``TR_HAS_BUTTONS`` flag set,
         ``False`` otherwise.
        """

        return self.HasAGWFlag(TR_HAS_BUTTONS)

# -----------------------------------------------------------------------------
# functions to work with tree items
# -----------------------------------------------------------------------------

[docs]    def GetItemText(self, item):
        """
        Returns the item text.

        :param `item`: an instance of L{GenericTreeItem}.
        """

        return item.GetText()

[docs]    def GetItemSize(self, item):
        """
        Returns the horizontal space available in L{CustomTreeCtrl}, in pixels, to draw this item.

        :param `item`: an instance of L{GenericTreeItem}.

        .. versionadded:: 0.9.3
        """

        w, h = self.GetClientSize()
        xa, ya = self.CalcScrolledPosition((0, item.GetY()))

        wcheck = image_w = 0

        if item.GetType() != 0:
            wcheck, dummy = self._imageListCheck.GetSize(item.GetType())
            wcheck += 4

        image = item.GetCurrentImage()

        if image != _NO_IMAGE:
            if self._imageListNormal:
                image_w, dummy = self._imageListNormal.GetSize(image)
                image_w += 4

        maxsize = w - (wcheck + image_w + item.GetX()) + xa
        return maxsize

[docs]    def GetItemImage(self, item, which=TreeItemIcon_Normal):
        """
        Returns the item image.

        :param `item`: an instance of L{GenericTreeItem};
        :param integer `which`: can be one of the following bits:

         ================================= ========================
         Item State                        Description
         ================================= ========================
         ``TreeItemIcon_Normal``           To get the normal item image
         ``TreeItemIcon_Selected``         To get the selected item image (i.e. the image which is shown when the item is currently selected)
         ``TreeItemIcon_Expanded``         To get the expanded image (this only makes sense for items which have children - then this image is shown when the item is expanded and the normal image is shown when it is collapsed)
         ``TreeItemIcon_SelectedExpanded`` To get the selected expanded image (which is shown when an expanded item is currently selected)
         ================================= ========================

        :return: An integer index that can be used to retrieve the item image inside
         a `wx.ImageList`.
        """

        return item.GetImage(which)

[docs]    def GetItemLeftImage(self, item):
        """
        Returns the item leftmost image, i.e. the image associated to the item on the leftmost
        part of the L{CustomTreeCtrl} client area.

        :param `item`: an instance of L{GenericTreeItem}.

        :return: An integer index that can be used to retrieve the item leftmost image inside
         a `wx.ImageList`.
        """

        return item.GetLeftImage()

[docs]    def GetPyData(self, item):
        """
        Returns the data associated to an item.

        :param `item`: an instance of L{GenericTreeItem}.

        :return: A Python object representing the item data, or ``None`` if no data
         has been assigned to this item.
        """

        return item.GetData()

    GetItemPyData = GetPyData

[docs]    def GetItemTextColour(self, item):
        """
        Returns the item text colour or separator horizontal line colour.

        :param `item`: an instance of L{GenericTreeItem}.

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

        return item.Attr().GetTextColour()

[docs]    def GetItemBackgroundColour(self, item):
        """
        Returns the item background colour.

        :param `item`: an instance of L{GenericTreeItem}.

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

        return item.Attr().GetBackgroundColour()

[docs]    def GetItemFont(self, item):
        """
        Returns the item font.

        :param `item`: an instance of L{GenericTreeItem}.

        :return: An instance of `wx.Font`.
        """

        font = item.Attr().GetFont()
        if font.IsOk():
            return font

        return wx.NullFont

[docs]    def IsItemHyperText(self, item):
        """
        Returns whether an item is hypertext or not.

        :param `item`: an instance of L{GenericTreeItem}.

        :return: ``True`` if the item is hypertext-like, ``False`` otherwise.
        """

        return item.IsHyperText()

[docs]    def SetItemText(self, item, text):
        """
        Sets the item text.

        :param `item`: an instance of L{GenericTreeItem};
        :param string `text`: the new item label.

        :raise: `Exception` if the input `item` is a separator.
        """

        if item.IsSeparator():
            raise Exception("Separator items can not have text")

        dc = wx.ClientDC(self)
        item.SetText(text)
        self.CalculateSize(item, dc)
        self.RefreshLine(item)

[docs]    def SetItemImage(self, item, image, which=TreeItemIcon_Normal):
        """
        Sets the item image, depending on the item state.

        :param `item`: an instance of L{GenericTreeItem};
        :param integer `image`: an index within the normal image list specifying the image to
         use for the item in the state specified by the `which` parameter;
        :param integer `which`: the item state.

        :see: L{GetItemImage} for an explanation of the `which` parameter.
        """

        item.SetImage(image, which)

        dc = wx.ClientDC(self)
        self.CalculateSize(item, dc)
        self.RefreshLine(item)

[docs]    def SetItemLeftImage(self, item, image):
        """
        Sets the item leftmost image, i.e. the image associated to the item on the leftmost
        part of the L{CustomTreeCtrl} client area.

        :param `item`: an instance of L{GenericTreeItem};
        :param integer `image`: an index within the left image list specifying the image to
         use for the item in the leftmost part of the client area.
        """

        item.SetLeftImage(image)

        dc = wx.ClientDC(self)
        self.CalculateSize(item, dc)
        self.RefreshLine(item)

[docs]    def SetPyData(self, item, data):
        """
        Sets the data associated to an item.

        :param `item`: an instance of L{GenericTreeItem};
        :param object `data`: can be any Python object.
        """

        item.SetData(data)

    SetItemPyData = SetPyData

[docs]    def SetItemHasChildren(self, item, has=True):
        """
        Forces the appearance/disappearance of the button next to the item.

        :param `item`: an instance of L{GenericTreeItem};
        :param bool `has`: ``True`` to have a button next to an item, ``False`` otherwise.
        """

        item.SetHasPlus(has)
        self.RefreshLine(item)

[docs]    def SetItemBold(self, item, bold=True):
        """
        Sets the item font as bold/unbold.

        :param `item`: an instance of L{GenericTreeItem};
        :param bool `bold`: ``True`` to set the item font as bold, ``False`` otherwise.
        """

        # avoid redrawing the tree if no real change
        if item.IsBold() != bold:
            item.SetBold(bold)
            self._dirty = True

[docs]    def SetItemItalic(self, item, italic=True):
        """
        Sets the item font as italic/non-italic.

        :param `item`: an instance of L{GenericTreeItem};
        :param bool `italic`: ``True`` to set the item font as italic, ``False`` otherwise.
        """

        if item.IsItalic() != italic:
            item.SetItalic(italic)
            self._dirty = True

[docs]    def SetItemDropHighlight(self, item, highlight=True):
        """
        Gives the item the visual feedback for drag and drop operations.
        This is useful when something is dragged from outside the L{CustomTreeCtrl}.

        :param `item`: an instance of L{GenericTreeItem};
        :param bool `highlight`: ``True`` to highlight the dragged items, ``False`` otherwise.
        """

        if highlight:
            bg = wx.SystemSettings_GetColour(wx.SYS_COLOUR_HIGHLIGHT)
            fg = wx.SystemSettings_GetColour(wx.SYS_COLOUR_HIGHLIGHTTEXT)

        item.Attr().SetTextColour(fg)
        item.Attr.SetBackgroundColour(bg)
        self.RefreshLine(item)

[docs]    def SetItemTextColour(self, item, colour):
        """
        Sets the item text colour or separator horizontal line colour.

        :param `item`: an instance of L{GenericTreeItem};
        :param `colour`: a valid `wx.Colour` instance.
        """

        item.Attr().SetTextColour(colour)
        self.RefreshLine(item)

[docs]    def SetItemBackgroundColour(self, item, colour):
        """
        Sets the item background colour.

        :param `item`: an instance of L{GenericTreeItem};
        :param `colour`: a valid `wx.Colour` instance.
        """

        item.Attr().SetBackgroundColour(colour)
        self.RefreshLine(item)

[docs]    def SetItemHyperText(self, item, hyper=True):
        """
        Sets whether the item is hypertext or not.

        :param `item`: an instance of L{GenericTreeItem};
        :param bool `hyper`: ``True`` to have an item with hypertext behaviour, ``False`` otherwise.
        """

        item.SetHyperText(hyper)
        self.RefreshLine(item)

[docs]    def SetItemFont(self, item, font):
        """
        Sets the item font.

        :param `item`: an instance of L{GenericTreeItem};
        :param `font`: a valid `wx.Font` instance.
        """

        item.Attr().SetFont(font)
        self._dirty = True

[docs]    def SetFont(self, font):
        """
        Sets the L{CustomTreeCtrl} font.

        :param `font`: a valid `wx.Font` instance.

        :note: Overridden from `wx.PyScrolledWindow`.
        """

        wx.PyScrolledWindow.SetFont(self, font)

        self._normalFont = font
        family = self._normalFont.GetFamily()
        if family == wx.FONTFAMILY_UNKNOWN:
            family = wx.FONTFAMILY_SWISS
        self._boldFont = wx.Font(self._normalFont.GetPointSize(), family,
                                 self._normalFont.GetStyle(), wx.BOLD, self._normalFont.GetUnderlined(),
                                 self._normalFont.GetFaceName(), self._normalFont.GetEncoding())
        self._italicFont = wx.Font(self._normalFont.GetPointSize(), family,
                                   wx.FONTSTYLE_ITALIC, wx.NORMAL, self._normalFont.GetUnderlined(),
                                   self._normalFont.GetFaceName(), self._normalFont.GetEncoding())

        return True

[docs]    def GetHyperTextFont(self):
        """
        Returns the font used to render hypertext items.

        :return: An instance of `wx.Font`.

        :note: This method is meaningful only for hypertext-like items.
        """

        return self._hypertextfont

[docs]    def SetHyperTextFont(self, font):
        """
        Sets the font used to render hypertext items.

        :param `font`: a valid `wx.Font` instance.

        :note: This method is meaningful only for hypertext-like items.
        """

        self._hypertextfont = font
        self._dirty = True

[docs]    def SetHyperTextNewColour(self, colour):
        """
        Sets the colour used to render a non-visited hypertext item.

        :param `colour`: a valid `wx.Colour` instance.

        :note: This method is meaningful only for hypertext-like items.
        """

        self._hypertextnewcolour = colour
        self._dirty = True

[docs]    def GetHyperTextNewColour(self):
        """
        Returns the colour used to render a non-visited hypertext item.

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

        :note: This method is meaningful only for hypertext-like items.
        """

        return self._hypertextnewcolour

[docs]    def SetHyperTextVisitedColour(self, colour):
        """
        Sets the colour used to render a visited hypertext item.

        :param `colour`: a valid `wx.Colour` instance.

        :note: This method is meaningful only for hypertext-like items.
        """

        self._hypertextvisitedcolour = colour
        self._dirty = True

[docs]    def GetHyperTextVisitedColour(self):
        """
        Returns the colour used to render a visited hypertext item.

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

        :note: This method is meaningful only for hypertext-like items.
        """

        return self._hypertextvisitedcolour

[docs]    def SetItemVisited(self, item, visited=True):
        """
        Sets whether an hypertext item was visited.

        :param `item`: an instance of L{GenericTreeItem};
        :param bool `visited`: ``True`` to mark an hypertext item as visited, ``False`` otherwise.

        :note: This method is meaningful only for hypertext-like items.
        """

        item.SetVisited(visited)
        self.RefreshLine(item)

[docs]    def GetItemVisited(self, item):
        """
        Returns whether an hypertext item was visited.

        :param `item`: an instance of L{GenericTreeItem}.

        :return: ``True`` if the hypertext item has been visited, ``False`` otherwise.

        :note: This method is meaningful only for hypertext-like items.
        """

        return item.GetVisited()

[docs]    def SetHilightFocusColour(self, colour):
        """
        Sets the colour used to highlight focused selected items.

        :param `colour`: a valid `wx.Colour` instance.

        :note: This is applied only if gradient and Windows Vista selection
         styles are disabled.
        """

        self._hilightBrush = wx.Brush(colour)
        self.RefreshSelected()

[docs]    def SetHilightNonFocusColour(self, colour):
        """
        Sets the colour used to highlight unfocused selected items.

        :param `colour`: a valid `wx.Colour` instance.

        :note: This is applied only if gradient and Windows Vista selection
         styles are disabled.
        """

        self._hilightUnfocusedBrush = wx.Brush(colour)
        self.RefreshSelected()

[docs]    def GetHilightFocusColour(self):
        """
        Returns the colour used to highlight focused selected items.

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

        :note: This is used only if gradient and Windows Vista selection
         styles are disabled.
        """

        return self._hilightBrush.GetColour()

[docs]    def GetHilightNonFocusColour(self):
        """
        Returns the colour used to highlight unfocused selected items.

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

        :note: This is used only if gradient and Windows Vista selection
         styles are disabled.
        """

        return self._hilightUnfocusedBrush.GetColour()

[docs]    def SetFirstGradientColour(self, colour=None):
        """
        Sets the first gradient colour for gradient-style selections.

        :param `colour`: if not ``None``, a valid `wx.Colour` instance. Otherwise,
         the colour is taken from the system value ``wx.SYS_COLOUR_HIGHLIGHT``.
        """

        if colour is None:
            colour = wx.SystemSettings_GetColour(wx.SYS_COLOUR_HIGHLIGHT)

        self._firstcolour = colour
        if self._usegradients:
            self.RefreshSelected()

[docs]    def SetSecondGradientColour(self, colour=None):
        """
        Sets the second gradient colour for gradient-style selections.

        :param `colour`: if not ``None``, a valid `wx.Colour` instance. Otherwise,
         the colour generated is a slightly darker version of the L{CustomTreeCtrl}
         background colour.
        """

        if colour is None:
            # No colour given, generate a slightly darker from the
            # CustomTreeCtrl background colour
            colour = self.GetBackgroundColour()
            r, g, b = int(colour.Red()), int(colour.Green()), int(colour.Blue())
            colour = ((r >> 1) + 20, (g >> 1) + 20, (b >> 1) + 20)
            colour = wx.Colour(colour[0], colour[1], colour[2])

        self._secondcolour = colour

        if self._usegradients:
            self.RefreshSelected()

[docs]    def GetFirstGradientColour(self):
        """
        Returns the first gradient colour for gradient-style selections.

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

        return self._firstcolour

[docs]    def GetSecondGradientColour(self):
        """
        Returns the second gradient colour for gradient-style selections.

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

        return self._secondcolour

[docs]    def EnableSelectionGradient(self, enable=True):
        """
        Globally enables/disables drawing of gradient selections.

        :param bool `enable`: ``True`` to enable gradient-style selections, ``False``
         to disable it.

        :note: Calling this method disables any Vista-style selection previously
         enabled.
        """

        self._usegradients = enable
        self._vistaselection = False
        self.RefreshSelected()

[docs]    def SetGradientStyle(self, vertical=0):
        """
        Sets the gradient style for gradient-style selections.

        :param integer `vertical`: ``0`` for horizontal gradient-style selections, ``1`` for vertical
         gradient-style selections.
        """

        # 0 = Horizontal, 1 = Vertical
        self._gradientstyle = vertical

        if self._usegradients:
            self.RefreshSelected()

[docs]    def GetGradientStyle(self):
        """
        Returns the gradient style for gradient-style selections.

        :return: ``0`` for horizontal gradient-style selections, ``1`` for vertical
         gradient-style selections.
        """

        return self._gradientstyle

[docs]    def EnableSelectionVista(self, enable=True):
        """
        Globally enables/disables drawing of Windows Vista selections.

        :param bool `enable`: ``True`` to enable Vista-style selections, ``False`` to
         disable it.

        :note: Calling this method disables any gradient-style selection previously
         enabled.
        """

        self._usegradients = False
        self._vistaselection = enable
        self.RefreshSelected()

[docs]    def SetBorderPen(self, pen):
        """
        Sets the pen used to draw the selected item border.

        :param `pen`: an instance of `wx.Pen`.

        :note: The border pen is not used if the Windows Vista selection style is applied.
        """

        self._borderPen = pen
        self.RefreshSelected()

[docs]    def GetBorderPen(self):
        """
        Returns the pen used to draw the selected item border.

        :return: An instance of `wx.Pen`.

        :note: The border pen is not used if the Windows Vista selection style is applied.
        """

        return self._borderPen

[docs]    def SetConnectionPen(self, pen):
        """
        Sets the pen used to draw the connecting lines between items.

        :param `pen`: an instance of `wx.Pen`.
        """

        self._dottedPen = pen
        self._dirty = True

[docs]    def GetConnectionPen(self):
        """
        Returns the pen used to draw the connecting lines between items.

        :return: An instance of `wx.Pen`.
        """

        return self._dottedPen

[docs]    def SetBackgroundImage(self, image):
        """
        Sets the L{CustomTreeCtrl} background image.

        :param `image`: if not ``None``, an instance of `wx.Bitmap`.

        :note: At present, the background image can only be used in "tile" mode.

        :todo: Support background images also in stretch and centered modes.
        """

        self._backgroundImage = image
        self.Refresh()

[docs]    def GetBackgroundImage(self):
        """
        Returns the L{CustomTreeCtrl} background image (if any).

        :return: An instance of `wx.Bitmap` if a background image is present, ``None`` otherwise.

        :note: At present, the background image can only be used in "tile" mode.

        :todo: Support background images also in stretch and centered modes.
        """

        return self._backgroundImage

[docs]    def SetSeparatorColour(self, colour):
        """
        Sets the pen colour for separator-type items.

        :param `colour`: a valid instance of `wx.Colour`.
        """

        self._separatorPen = wx.Pen(colour, 1)
        self.Refresh()

[docs]    def GetSeparatorColour(self, colour):
        """
        Returns the pen colour for separator-type items.

        :return: An instance of `wx.Colour` representing the separator pen colour.
        """

        return self._separatorPen.GetColour()

[docs]    def IsItemSeparator(self, item):
        """
        Returns whether an item is of separator type or not.

        :param `item`: an instance of L{GenericTreeItem}.
        """

        return item.IsSeparator()

[docs]    def GetItemWindow(self, item):
        """
        Returns the window associated to the item (if any).

        :param `item`: an instance of L{GenericTreeItem}.

        :return: An instance of `wx.Window` if the item has an associated window, ``None`` otherwise.
        """

        return item.GetWindow()

[docs]    def SetItemWindow(self, item, wnd):
        """
        Sets the window for the given item.

        :param `item`: an instance of L{GenericTreeItem};
        :param `wnd`: if not ``None``, a non-toplevel window to be displayed next to
         the item.

        :raise: `Exception` if the input `item` is a separator and `wnd` is not ``None``.
        """

        if item.IsSeparator() and wnd is not None:
            raise Exception("Separator items can not have an associated window")

        if wnd is not None:
            self._hasWindows = True
            if item not in self._itemWithWindow:
                self._itemWithWindow.append(item)
            else:
                self.DeleteItemWindow(item)
        else:
            self.DeleteItemWindow(item)

        item.SetWindow(wnd)
        self.CalculatePositions()
        self.Refresh()
        self.AdjustMyScrollbars()

[docs]    def DeleteItemWindow(self, item):
        """
        Deletes the window associated to an item (if any).

        :param `item`: an instance of L{GenericTreeItem}.
        """

        if item.GetWindow() is None:
            return

        item.DeleteWindow()
        if item in self._itemWithWindow:
            self._itemWithWindow.remove(item)

[docs]    def GetItemWindowEnabled(self, item):
        """
        Returns whether the window associated to the item is enabled.

        :param `item`: an instance of L{GenericTreeItem}.

        :return: ``True`` if the item has an associated window and this window is
         enabled, ``False`` in all other cases.
        """

        return item.GetWindowEnabled()

[docs]    def SetItemWindowEnabled(self, item, enable=True):
        """
        Enables/disables the window associated to the item.

        :param `item`: an instance of L{GenericTreeItem};
        :param bool `enable`: ``True`` to enable the associated window, ``False`` to
         disable it.
        """

        item.SetWindowEnabled(enable)

[docs]    def GetItemType(self, item):
        """
        Returns the item type.

        :param `item`: an instance of L{GenericTreeItem}.

        :return: An integer representing the item type.

        :see: L{SetItemType} for a description of valid item types.
        """

        return item.GetType()

[docs]    def SetItemType(self, item, ct_type):
        """
        Sets the item type.

        :param `item`: an instance of L{GenericTreeItem};
        :param integer `ct_type`: may be one of the following integers:

         =============== =========================================
         `ct_type` Value Description
         =============== =========================================
                0        A normal item
                1        A checkbox-like item
                2        A radiobutton-type item
         =============== =========================================

        :note: Regarding radiobutton-type items (with `ct_type` = 2), the following
         approach is used:

         - All peer-nodes that are radiobuttons will be mutually exclusive. In other words,
           only one of a set of radiobuttons that share a common parent can be checked at
           once. If a radiobutton node becomes checked, then all of its peer radiobuttons
           must be unchecked.
         - If a radiobutton node becomes unchecked, then all of its child nodes will become
           inactive.

        """

        item.SetType(ct_type)
        self.CalculatePositions()
        self.Refresh()

# -----------------------------------------------------------------------------
# item status inquiries
# -----------------------------------------------------------------------------

[docs]    def IsVisible(self, item):
        """
        Returns whether the item is visible or not (i.e., its hierarchy is expanded
        enough to show the item).

        :param `item`: an instance of L{GenericTreeItem}.

        :return: ``True`` if the item is visible, ``False`` if it is hidden.
        """

        # An item is only visible if it's not a descendant of a collapsed item
        parent = item.GetParent()

        while parent:

            if not parent.IsExpanded():
                return False

            parent = parent.GetParent()

        startX, startY = self.GetViewStart()
        clientSize = self.GetClientSize()

        rect = self.GetBoundingRect(item)

        if not rect:
            return False
        if rect.GetWidth() == 0 or rect.GetHeight() == 0:
            return False
        if rect.GetBottom() < 0 or rect.GetTop() > clientSize.y:
            return False
        if rect.GetRight() < 0 or rect.GetLeft() > clientSize.x:
            return False

        return True

[docs]    def ItemHasChildren(self, item):
        """
        Returns whether the item has children or not.

        :param `item`: an instance of L{GenericTreeItem}.

        :return: ``True`` if the item has children, ``False`` otherwise.
        """

        # consider that the item does have children if it has the "+" button: it
        # might not have them (if it had never been expanded yet) but then it
        # could have them as well and it's better to err on this side rather than
        # disabling some operations which are restricted to the items with
        # children for an item which does have them
        return item.HasPlus()

[docs]    def IsExpanded(self, item):
        """
        Returns whether the item is expanded or not.

        :param `item`: an instance of L{GenericTreeItem}.

        :return: ``True`` if the item is expanded, ``False`` if it is collapsed.
        """

        return item.IsExpanded()

[docs]    def IsSelected(self, item):
        """
        Returns whether the item is selected or not.

        :param `item`: an instance of L{GenericTreeItem}.

        :return: ``True`` if the item is selected, ``False`` otherwise.
        """

        return item.IsSelected()

[docs]    def IsBold(self, item):
        """
        Returns whether the item font is bold or not.

        :param `item`: an instance of L{GenericTreeItem}.

        :return: ``True`` if the item has bold text, ``False`` otherwise.
        """

        return item.IsBold()

[docs]    def IsItalic(self, item):
        """
        Returns whether the item font is italic or not.

        :param `item`: an instance of L{GenericTreeItem}.

        :return: ``True`` if the item has italic text, ``False`` otherwise.
        """

        return item.IsItalic()

# -----------------------------------------------------------------------------
# navigation
# -----------------------------------------------------------------------------

[docs]    def GetItemParent(self, item):
        """
        Returns the item parent (can be ``None`` for root items).

        :param `item`: an instance of L{GenericTreeItem}.

        :return: An instance of L{GenericTreeItem} or ``None`` for root items.
        """

        return item.GetParent()

[docs]    def GetFirstChild(self, item):
        """
        Returns the item's first child and an integer value 'cookie'.
        Call L{GetNextChild} for the next child using this very 'cookie' return
        value as an input.

        :param `item`: an instance of L{GenericTreeItem}.

        :return: A tuple with the first value being an instance of L{GenericTreeItem} or ``None`` if there are no
         further children, and as second value an integer parameter 'cookie'.

        :note: This method returns ``None`` if there are no further children.
        """

        cookie = 0
        return self.GetNextChild(item, cookie)

[docs]    def GetNextChild(self, item, cookie):
        """
        Returns the item's next child.

        :param `item`: an instance of L{GenericTreeItem};
        :param `cookie`: a parameter which is opaque for the application but is necessary
         for the library to make these functions reentrant (i.e. allow more than one
         enumeration on one and the same object simultaneously).

        :return: A tuple with the first value being an instance of L{GenericTreeItem} or ``None`` if there are no
         further children, and as second value an integer parameter 'cookie'.

        :note: This method returns ``None`` if there are no further children.
        """

        children = item.GetChildren()

        # it's ok to cast cookie to size_t, we never have indices big enough to
        # overflow "void *"

        if cookie < len(children):

            return children[cookie], cookie+1

        else:

            # there are no more of them
            return None, cookie

[docs]    def GetLastChild(self, item):
        """
        Returns the item last child.

        :param `item`: an instance of L{GenericTreeItem}.

        :return: An instance of L{GenericTreeItem} or ``None`` if there are no
         further children.
        """

        children = item.GetChildren()
        return (len(children) == 0 and [None] or [children[-1]])[0]

[docs]    def GetNextSibling(self, item):
        """
        Returns the next sibling of an item.

        :param `item`: an instance of L{GenericTreeItem}.

        :return: An instance of L{GenericTreeItem} or ``None`` if there are no
         further siblings.

        :note: This method returns ``None`` if there are no further siblings.
        """

        i = item
        parent = i.GetParent()

        if parent == None:

            # root item doesn't have any siblings
            return None

        siblings = parent.GetChildren()
        index = siblings.index(i)

        n = index + 1
        return (n == len(siblings) and [None] or [siblings[n]])[0]

[docs]    def GetPrevSibling(self, item):
        """
        Returns the previous sibling of an item.

        :param `item`: an instance of L{GenericTreeItem}.

        :return: An instance of L{GenericTreeItem} or ``None`` if there are no
         further siblings.

        :note: This method returns ``None`` if there are no further siblings.
        """

        i = item
        parent = i.GetParent()

        if parent == None:

            # root item doesn't have any siblings
            return None

        siblings = parent.GetChildren()
        index = siblings.index(i)

        return (index == 0 and [None] or [siblings[index-1]])[0]

[docs]    def GetNext(self, item):
        """
        Returns the next item. Only for internal use right now.

        :return: An instance of L{GenericTreeItem} or ``None`` if there are no
         further items.

        :param `item`: an instance of L{GenericTreeItem}.
        """

        i = item

        # First see if there are any children.
        children = i.GetChildren()
        if len(children) > 0:
             return children[0]
        else:
             # Try a sibling of this or ancestor instead
             p = item
             toFind = None
             while p and not toFind:
                  toFind = self.GetNextSibling(p)
                  p = self.GetItemParent(p)

             return toFind

[docs]    def GetPrev(self, item):
        """
        Returns the previous item. Only for internal use right now.

        :param `item`: an instance of L{GenericTreeItem}.

        :return: An instance of L{GenericTreeItem}
        """

        # Look for a previous sibling of this item
        prevSibling = self.GetPrevSibling(item)
        if prevSibling:

            # return it's last child or itself if has not got any children
            if len(prevSibling.GetChildren()) > 0:
                return self.GetLastChild(prevSibling)

            return prevSibling

        # item has not got a previous sibling, return it's parent
        return self.GetItemParent(item)

[docs]    def GetNextExpanded(self, item):
        """
        Returns the next expanded item after the input one.

        :param `item`: an instance of L{TreeListItem}.
        """

        nextSibling = self.GetNextSibling(item)
        if nextSibling:
            if nextSibling.IsExpanded():
                return nextSibling

            return self.GetNextExpanded(prevSibling)

        return None

[docs]    def GetPrevExpanded(self, item):
        """
        Returns the previous expanded item before the input one.

        :param `item`: an instance of L{TreeListItem}.
        """

        prevSibling = self.GetPrevSibling(item)
        if prevSibling:
            if prevSibling.IsExpanded():
                return prevSibling

            return self.GetPrevExpanded(prevSibling)

        return None

[docs]    def GetFirstVisibleItem(self):
        """
        Returns the first visible item.

        :return: An instance of L{GenericTreeItem} or ``None`` if there are no
         visible items.
        """

        id = self.GetRootItem()
        if not id:
            return id

        while id:
            if self.IsVisible(id):
                return id
            id = self.GetNext(id)

        return None

[docs]    def GetNextVisible(self, item):
        """
        Returns the next visible item.

        :param `item`: an instance of L{GenericTreeItem}.

        :return: An instance of L{GenericTreeItem} or ``None`` if there are no
         next visible items.
        """

        id = item

        while id:
            id = self.GetNext(id)
            if id and self.IsVisible(id):
                return id

        return None

[docs]    def GetPrevVisible(self, item):
        """
        Returns the previous visible item.

        :param `item`: an instance of L{GenericTreeItem}.

        :return: An instance of L{GenericTreeItem} or ``None`` if there are no
         previous visible items.
        """

        # find a previous sibling or parent which is visible
        lastGoodItem = self.GetPrevSibling(item)
        if not lastGoodItem or not self.IsVisible(lastGoodItem):
            parent = self.GetItemParent(item)
            rootHidden = self.HasAGWFlag(TR_HIDE_ROOT)
            rootItem = self.GetRootItem()

            while parent and not (rootHidden and parent == rootItem):
                if self.IsVisible(parent):
                    lastGoodItem = parent
                    break
                parent = self.GetItemParent(parent)

            if not lastGoodItem:
                return None

        # test if found item has visible children, if so and if the found item is not the
        # parent of the current item traverse the found item to the last visible child
        if not self.HasChildren(lastGoodItem) or not self.IsExpanded(lastGoodItem) or \
           (self.GetItemParent(item) == lastGoodItem):
            return lastGoodItem

        lastChild = self.GetLastChild(lastGoodItem)
        while lastChild and self.IsVisible(lastChild):
            lastGoodItem = lastChild
            lastChild = self.GetLastChild(lastGoodItem)

        return lastGoodItem

[docs]    def ResetEditControl(self):
        """ Called by L{TreeTextCtrl} when it marks itself for deletion. """

        if self._editCtrl is not None:
            self._editCtrl.Destroy()
            self._editCtrl = None

        self.CalculatePositions()
        self.Refresh()
        self.AdjustMyScrollbars()

[docs]    def FindItem(self, idParent, prefixOrig):
        """
        Finds the first item starting with the given prefix after the given parent.

        :param integer `idParent`: an instance of L{GenericTreeItem};
        :param string `prefixOrig`: a string containing the item text prefix.

        :return: An instance of L{GenericTreeItem} or ``None`` if no item has been found.
        """

        # match is case insensitive as this is more convenient to the user: having
        # to press Shift-letter to go to the item starting with a capital letter
        # would be too bothersome
        prefix = prefixOrig.lower()

        # determine the starting point: we shouldn't take the current item (this
        # allows to switch between two items starting with the same letter just by
        # pressing it) but we shouldn't jump to the next one if the user is
        # continuing to type as otherwise he might easily skip the item he wanted
        id = idParent

        if len(prefix) == 1:
            id = self.GetNext(id)

        # look for the item starting with the given prefix after it
        while id and not self.GetItemText(id).lower().startswith(prefix):

            id = self.GetNext(id)

        # if we haven't found anything...
        if not id:

            # ... wrap to the beginning
            id = self.GetRootItem()
            if self.HasAGWFlag(TR_HIDE_ROOT):
                # can't select virtual root
                id = self.GetNext(id)
                if idParent == self.GetRootItem():
                    # no tree item selected and idParent is not reachable
                    return id

            # and try all the items (stop when we get to the one we started from)
            while id != idParent and not self.GetItemText(id).lower().startswith(prefix):
                id = self.GetNext(id)

        return id

# -----------------------------------------------------------------------------
# operations
# -----------------------------------------------------------------------------

[docs]    def DoInsertItem(self, parentId, previous, text, ct_type=0, wnd=None, image=-1, selImage=-1, data=None, separator=False):
        """
        Actually inserts an item in the tree.

        :param `parentId`: an instance of L{GenericTreeItem} representing the
         item's parent;
        :param integer `previous`: the index at which we should insert the item;
        :param string `text`: the item text label;
        :param integer `ct_type`: the item type (see L{SetItemType} for a list of valid
         item types);
        :param `wnd`: if not ``None``, a non-toplevel window to show next to the item, any
         subclass of `wx.Window` except top-level windows;
        :param integer `image`: an index within the normal image list specifying the image to
         use for the item in unselected state;
        :param integer `selImage`: an index within the normal image list specifying the image to
         use for the item in selected state; if `image` > -1 and `selImage` is -1, the
         same image is used for both selected and unselected items;
        :param object `data`: associate the given Python object `data` with the item;
        :param bool `separator`: ``True`` if the item is a separator, ``False`` otherwise.

        :return: An instance of L{GenericTreeItem} upon successful insertion.

        :raise: `Exception` in the following cases:

         - The item window is not ``None`` but the ``TR_HAS_VARIABLE_ROW_HEIGHT`` flag has not been
           set for L{CustomTreeCtrl};
         - The item has multiline text (with line-breaks in it) but the ``TR_HAS_VARIABLE_ROW_HEIGHT``
           flag has not been set for L{CustomTreeCtrl};
         - The `ct_type` attribute is less than ``0`` or greater than ``2``;
         - The parent item is a separator;
         - The item is a separator but it has text or an associated window.

        :note: Separator items should not have children, text labels or an associated window.
        """

        if wnd is not None and not self.HasAGWFlag(TR_HAS_VARIABLE_ROW_HEIGHT):
            raise Exception("\nERROR: In Order To Append/Insert Controls You Have To Use The Style TR_HAS_VARIABLE_ROW_HEIGHT")

        if text.find("\n") >= 0 and not self.HasAGWFlag(TR_HAS_VARIABLE_ROW_HEIGHT):
            raise Exception("\nERROR: In Order To Append/Insert A MultiLine Text You Have To Use The Style TR_HAS_VARIABLE_ROW_HEIGHT")

        if ct_type < 0 or ct_type > 2:
            raise Exception("\nERROR: Item Type Should Be 0 (Normal), 1 (CheckBox) or 2 (RadioButton). ")

        if separator:
            if wnd:
                raise Exception("Separator items can not have associated windows")
            if text.strip():
                raise Exception("Separator items can not text labels")

        parent = parentId

        if not parent:
            # should we give a warning here?
            return self.AddRoot(text, ct_type, wnd, image, selImage, data)

        self._dirty = True     # do this first so stuff below doesn't cause flicker

        item = GenericTreeItem(parent, text, ct_type, wnd, image, selImage, data, separator)

        if wnd is not None:
            self._hasWindows = True
            self._itemWithWindow.append(item)

        parent.Insert(item, previous)

        return item

[docs]    def AddRoot(self, text, ct_type=0, wnd=None, image=-1, selImage=-1, data=None):
        """
        Adds a root item to the L{CustomTreeCtrl}.

        :param string `text`: the item text label;
        :param integer `ct_type`: the item type (see L{SetItemType} for a list of valid
         item types);
        :param `wnd`: if not ``None``, a non-toplevel window to show next to the item,
         any subclass of `wx.Window` except top-level windows;
        :param integer `image`: an index within the normal image list specifying the image to
         use for the item in unselected state;
        :param  integer `selImage`: an index within the normal image list specifying the image to
         use for the item in selected state; if `image` > -1 and `selImage` is -1, the
         same image is used for both selected and unselected items;
        :param object `data`: associate the given Python object `data` with the item.

        :return: An instance of L{GenericTreeItem} upon successful insertion.

        :raise: `Exception` in the following cases:

         - There already is a root item in the tree;
         - The item window is not ``None`` but the ``TR_HAS_VARIABLE_ROW_HEIGHT`` flag has not been
           set for L{CustomTreeCtrl};
         - The item has multiline text (with line-breaks in it) but the ``TR_HAS_VARIABLE_ROW_HEIGHT``
           flag has not been set for L{CustomTreeCtrl};
         - The `ct_type` attribute is less than ``0`` or greater than ``2``.

        :warning: only one root is allowed to exist in any given instance of L{CustomTreeCtrl}.
        """

        if self._anchor:
            raise Exception("\nERROR: Tree Can Have Only One Root")

        if wnd is not None and not self.HasAGWFlag(TR_HAS_VARIABLE_ROW_HEIGHT):
            raise Exception("\nERROR: In Order To Append/Insert Controls You Have To Use The Style TR_HAS_VARIABLE_ROW_HEIGHT")

        if text.find("\n") >= 0 and not self.HasAGWFlag(TR_HAS_VARIABLE_ROW_HEIGHT):
            raise Exception("\nERROR: In Order To Append/Insert A MultiLine Text You Have To Use The Style TR_HAS_VARIABLE_ROW_HEIGHT")

        if ct_type < 0 or ct_type > 2:
            raise Exception("\nERROR: Item Type Should Be 0 (Normal), 1 (CheckBox) or 2 (RadioButton). ")

        self._dirty = True     # do this first so stuff below doesn't cause flicker

        self._anchor = GenericTreeItem(None, text, ct_type, wnd, image, selImage, data)

        if wnd is not None:
            self._hasWindows = True
            self._itemWithWindow.append(self._anchor)

        if self.HasAGWFlag(TR_HIDE_ROOT):

            # if root is hidden, make sure we can navigate
            # into children
            self._anchor.SetHasPlus()
            self._anchor.Expand()
            self.CalculatePositions()

        if not self.HasAGWFlag(TR_MULTIPLE):

            self._current = self._key_current = self._anchor
            self._current.SetHilight(True)

        return self._anchor

[docs]    def PrependItem(self, parent, text, ct_type=0, wnd=None, image=-1, selImage=-1, data=None, separator=False):
        """
        Prepends an item as a first child of parent.

        :param `parent`: an instance of L{GenericTreeItem} representing the
         item's parent;
        :param string `text`: the item text label;
        :param integer `ct_type`: the item type (see L{SetItemType} for a list of valid
         item types);
        :param `wnd`: if not ``None``, a non-toplevel window to show next to the item, any
         subclass of `wx.Window` except top-level windows;
        :param integer `image`: an index within the normal image list specifying the image to
         use for the item in unselected state;
        :param integer `selImage`: an index within the normal image list specifying the image to
         use for the item in selected state; if `image` > -1 and `selImage` is -1, the
         same image is used for both selected and unselected items;
        :param object `data`: associate the given Python object `data` with the item;
        :param bool `separator`: ``True`` if the item is a separator, ``False`` otherwise.

        :return: An instance of L{GenericTreeItem} upon successful insertion.

        :see: L{DoInsertItem} for possible exceptions generated by this method.
        """

        return self.DoInsertItem(parent, 0, text, ct_type, wnd, image, selImage, data, separator)

[docs]    def InsertItemByItem(self, parentId, idPrevious, text, ct_type=0, wnd=None, image=-1, selImage=-1, data=None, separator=False):
        """
        Inserts an item after the given previous.

        :param `parentId`: an instance of L{GenericTreeItem} representing the
         item's parent;
        :param `idPrevious`: an instance of L{GenericTreeItem} representing the
         previous item;
        :param string `text`: the item text label;
        :param integer `ct_type`: the item type (see L{SetItemType} for a list of valid
         item types);
        :param `wnd`: if not ``None``, a non-toplevel window to show next to the item,
         any subclass of `wx.Window`;
        :param integer `image`: an index within the normal image list specifying the image to
         use for the item in unselected state;
        :param integer `selImage`: an index within the normal image list specifying the image to
         use for the item in selected state; if `image` > -1 and `selImage` is -1, the
         same image is used for both selected and unselected items;
        :param object `data`: associate the given Python object `data` with the item;
        :param bool `separator`: ``True`` if the item is a separator, ``False`` otherwise.

        :return: An instance of L{GenericTreeItem} upon successful insertion.

        :raise: `Exception` if the previous item is not a sibling.

        :see: L{DoInsertItem} for other possible exceptions generated by this method.
        """

        parent = parentId

        if not parent:
            # should we give a warning here?
            return self.AddRoot(text, ct_type, wnd, image, selImage, data)

        index = -1
        if idPrevious:

            try:
                index = parent.GetChildren().index(idPrevious)
            except:
                raise Exception("ERROR: Previous Item In CustomTreeCtrl.InsertItem() Is Not A Sibling")

        return self.DoInsertItem(parentId, index+1, text, ct_type, wnd, image, selImage, data, separator)

[docs]    def InsertItemByIndex(self, parentId, idPrevious, text, ct_type=0, wnd=None, image=-1, selImage=-1, data=None, separator=False):
        """
        Inserts an item after the given previous.

        :param `parentId`: an instance of L{GenericTreeItem} representing the
         item's parent;
        :param `idPrevious`: the index at which we should insert the new item;
        :param string `text`: the item text label;
        :param integer `ct_type`: the item type (see L{SetItemType} for a list of valid
         item types);
        :param `wnd`: if not ``None``, a non-toplevel window to show next to the item,
         any subclass of `wx.Window`;
        :param integer `image`: an index within the normal image list specifying the image to
         use for the item in unselected state;
        :param integer `selImage`: an index within the normal image list specifying the image to
         use for the item in selected state; if `image` > -1 and `selImage` is -1, the
         same image is used for both selected and unselected items;
        :param object `data`: associate the given Python object `data` with the item;
        :param bool `separator`: ``True`` if the item is a separator, ``False`` otherwise.

        :return: An instance of L{GenericTreeItem} upon successful insertion.

        :see: L{DoInsertItem} for possible exceptions generated by this method.
        """

        parent = parentId

        if not parent:
            # should we give a warning here?
            return self.AddRoot(text, ct_type, wnd, image, selImage, data)

        return self.DoInsertItem(parentId, idPrevious, text, ct_type, wnd, image, selImage, data, separator)

[docs]    def InsertItem(self, parentId, input, text, ct_type=0, wnd=None, image=-1, selImage=-1, data=None, separator=False):
        """
        Inserts an item after the given previous.

        :return: An instance of L{GenericTreeItem} upon successful insertion.

        :see: L{InsertItemByIndex} and L{InsertItemByItem} for an explanation of
         the input parameters.

        :see: L{DoInsertItem} for possible exceptions generated by this method.
        """

        if type(input) == type(1):
            return self.InsertItemByIndex(parentId, input, text, ct_type, wnd, image, selImage, data, separator)
        else:
            return self.InsertItemByItem(parentId, input, text, ct_type, wnd, image, selImage, data, separator)

[docs]    def AppendItem(self, parentId, text, ct_type=0, wnd=None, image=-1, selImage=-1, data=None):
        """
        Appends an item as a last child of its parent.

        :param `parentId`: an instance of L{GenericTreeItem} representing the
         item's parent;
        :param string `text`: the item text label;
        :param integer `ct_type`: the item type (see L{SetItemType} for a list of valid
         item types);
        :param `wnd`: if not ``None``, a non-toplevel window to show next to the item,
         any subclass of `wx.Window`;
        :param integer `image`: an index within the normal image list specifying the image to
         use for the item in unselected state;
        :param integer `selImage`: an index within the normal image list specifying the image to
         use for the item in selected state; if `image` > -1 and `selImage` is -1, the
         same image is used for both selected and unselected items;
        :param object `data`: associate the given Python object `data` with the item.

        :return: An instance of L{GenericTreeItem} upon successful insertion.

        :see: L{DoInsertItem} for possible exceptions generated by this method.
        """

        parent = parentId

        if not parent:
            # should we give a warning here?
            return self.AddRoot(text, ct_type, wnd, image, selImage, data)

        return self.DoInsertItem(parent, len(parent.GetChildren()), text, ct_type, wnd, image, selImage, data)

[docs]    def AppendSeparator(self, parentId):
        """
        Appends an horizontal line separator as a last child of its parent.

        :param `parentId`: an instance of L{GenericTreeItem} representing the
         separator's parent.

        :return: An instance of L{GenericTreeItem} upon successful insertion.

        :see: L{DoInsertItem} for possible exceptions generated by this method.
        """

        parent = parentId
        return self.DoInsertItem(parent, len(parent.GetChildren()), "", separator=True)

[docs]    def InsertSeparator(self, parentId, input):
        """
        Inserts a separator item after the given previous.

        :return: An instance of L{GenericTreeItem} upon successful insertion.

        :see: L{InsertItemByIndex} and L{InsertItemByItem} for an explanation of
         the input parameters.

        :see: L{DoInsertItem} for possible exceptions generated by this method.
        """

        return self.InsertItem(parentId, input, "", separator=True)

[docs]    def PrependSeparator(self, parent):
        """
        Prepends a separator item as a first child of parent.

        :param `parent`: an instance of L{GenericTreeItem} representing the
         item's parent.

        :return: An instance of L{GenericTreeItem} upon successful insertion.

        :see: L{DoInsertItem} for possible exceptions generated by this method.
        """

        return self.PrependItem(parent, 0, separator=True)

[docs]    def SendDeleteEvent(self, item):
        """
        Actually sends the ``EVT_TREE_DELETE_ITEM`` event.

        :param `item`: an instance of L{GenericTreeItem}.
        """

        event = TreeEvent(wxEVT_TREE_DELETE_ITEM, self.GetId())
        event._item = item
        event.SetEventObject(self)
        self.GetEventHandler().ProcessEvent(event)

[docs]    def IsDescendantOf(self, parent, item):
        """
        Checks if the given item is under another one in the tree hierarchy.

        :param `parent`: an instance of L{GenericTreeItem}, representing the possible
         parent of `item`;
        :param `item`: another instance of L{GenericTreeItem}.

        :return: ``True`` if `item` is a descendant of `parent`, ``False`` otherwise.
        """

        while item:

            if item == parent:

                # item is a descendant of parent
                return True

            item = item.GetParent()

        return False

    # Don't leave edit or selection on a child which is about to disappear

[docs]    def ChildrenClosing(self, item):
        """
        We are about to destroy the item children.

        :param `item`: an instance of L{GenericTreeItem}.
        """

        if self._editCtrl != None and item != self._editCtrl.item() and self.IsDescendantOf(item, self._editCtrl.item()):
            self._editCtrl.StopEditing()

        if item != self._key_current and self.IsDescendantOf(item, self._key_current):
            self._key_current = None

        if self.IsDescendantOf(item, self._select_me):
            self._select_me = item

        if item != self._current and self.IsDescendantOf(item, self._current):
            self._current.SetHilight(False)
            self._current = None
            self._select_me = item

[docs]    def DeleteChildren(self, item):
        """
        Delete all the item's children.

        :param `item`: an instance of L{GenericTreeItem}.
        """

        self._dirty = True     # do this first so stuff below doesn't cause flicker

        self.ChildrenClosing(item)
        item.DeleteChildren(self)

[docs]    def Delete(self, item):
        """
        Deletes an item.

        :param `item`: an instance of L{GenericTreeItem}.

        :note: This method sends the ``EVT_TREE_DELETE_ITEM`` event.
        """

        self._dirty = True     # do this first so stuff below doesn't cause flicker

        if self._editCtrl != None and self.IsDescendantOf(item, self._editCtrl.item()):
            # can't delete the item being edited, cancel editing it first
            self._editCtrl.StopEditing()

        parent = item.GetParent()

        # don't keep stale pointers around!
        if self.IsDescendantOf(item, self._key_current):

            # Don't silently change the selection:
            # do it properly in idle time, so event
            # handlers get called.

            # self._key_current = parent
            self._key_current = None

        # self._select_me records whether we need to select
        # a different item, in idle time.
        if self._select_me and self.IsDescendantOf(item, self._select_me):
            self._select_me = parent

        if self.IsDescendantOf(item, self._current):

            # Don't silently change the selection:
            # do it properly in idle time, so event
            # handlers get called.

            # self._current = parent
            self._current = None
            self._select_me = parent

        # remove the item from the tree
        if parent:

            parent.GetChildren().remove(item)  # remove by value

        else: # deleting the root

            # nothing will be left in the tree
            self._anchor = None

        # and delete all of its children and the item itself now
        item.DeleteChildren(self)
        self.SendDeleteEvent(item)

        if item == self._select_me:
            self._select_me = None

        # Remove the item with window
        if item in self._itemWithWindow:
            wnd = item.GetWindow()
            wnd.Hide()
            wnd.Destroy()
            item._wnd = None
            self._itemWithWindow.remove(item)

        del item

[docs]    def DeleteAllItems(self):
        """ Deletes all items in the L{CustomTreeCtrl}. """

        if self._anchor:
            self.Delete(self._anchor)

[docs]    def Expand(self, item):
        """
        Expands an item, sending a ``EVT_TREE_ITEM_EXPANDING`` and
        ``EVT_TREE_ITEM_EXPANDED`` events.

        :param `item`: an instance of L{GenericTreeItem}.

        :raise: `Exception` if you try to expand a hidden root (i.e., when the ``TR_HIDE_ROOT``
         style is set for L{CustomTreeCtrl}).
        """

        if self.HasAGWFlag(TR_HIDE_ROOT) and item == self.GetRootItem():
             raise Exception("\nERROR: Can't Expand An Hidden Root. ")

        if not item.HasPlus():
            return

        if item.IsExpanded():
            return

        if self._sendEvent:
            event = TreeEvent(wxEVT_TREE_ITEM_EXPANDING, self.GetId())
            event._item = item
            event.SetEventObject(self)

            if self.GetEventHandler().ProcessEvent(event) and not event.IsAllowed():
                # cancelled by program
                return

        item.Expand()

        if not self._sendEvent:
            # We are in ExpandAll/ExpandAllChildren
            return

        self.CalculatePositions()
        self.RefreshSubtree(item)

        if self._hasWindows:
            # We hide the associated window here, we may show it after
            self.HideWindows()

        event.SetEventType(wxEVT_TREE_ITEM_EXPANDED)
        self.GetEventHandler().ProcessEvent(event)

[docs]    def ExpandAllChildren(self, item):
        """
        Expands all the items children of the input item.

        :param `item`: an instance of L{GenericTreeItem}.

        :note: This method suppresses the ``EVT_TREE_ITEM_EXPANDING`` and
         ``EVT_TREE_ITEM_EXPANDED`` events because expanding many items int the
         control would be too slow then.
        """

        self._sendEvent = False
        if not self.HasAGWFlag(TR_HIDE_ROOT) or item != self.GetRootItem():
            self.Expand(item)
            if not self.IsExpanded(item):
                self._sendEvent = True
                return

        child, cookie = self.GetFirstChild(item)

        while child:
            self.ExpandAllChildren(child)
            child, cookie = self.GetNextChild(item, cookie)

        self._sendEvent = True

[docs]    def ExpandAll(self):
        """
        Expands all L{CustomTreeCtrl} items.

        :note: This method suppresses the ``EVT_TREE_ITEM_EXPANDING`` and
         ``EVT_TREE_ITEM_EXPANDED`` events because expanding many items int the
         control would be too slow then.
        """

        if self._anchor:
            self.ExpandAllChildren(self._anchor)

        self._sendEvent = True
        self._dirty = True

[docs]    def Collapse(self, item):
        """
        Collapse an item, sending a ``EVT_TREE_ITEM_COLLAPSING`` and
        ``EVT_TREE_ITEM_COLLAPSED`` events.

        :param `item`: an instance of L{GenericTreeItem}.

        :raise: `Exception` if you try to collapse a hidden root (i.e., when the ``TR_HIDE_ROOT``
         style is set for L{CustomTreeCtrl}).
        """

        if self.HasAGWFlag(TR_HIDE_ROOT) and item == self.GetRootItem():
             raise Exception("\nERROR: Can't Collapse An Hidden Root. ")

        if not item.IsExpanded():
            return

        event = TreeEvent(wxEVT_TREE_ITEM_COLLAPSING, self.GetId())
        event._item = item
        event.SetEventObject(self)
        if self.GetEventHandler().ProcessEvent(event) and not event.IsAllowed():
            # cancelled by program
            return

        self.ChildrenClosing(item)
        item.Collapse()

        self.CalculatePositions()
        self.Refresh()

        if self._hasWindows:
            self.HideWindows()

        self.AdjustMyScrollbars()

        event.SetEventType(wxEVT_TREE_ITEM_COLLAPSED)
        self.GetEventHandler().ProcessEvent(event)

[docs]    def CollapseAndReset(self, item):
        """
        Collapse the given item and deletes its children.

        :param `item`: an instance of L{GenericTreeItem}.
        """

        self.Collapse(item)
        self.DeleteChildren(item)

[docs]    def Toggle(self, item):
        """
        Toggles the item state (collapsed/expanded).

        :param `item`: an instance of L{GenericTreeItem}.
        """

        if item.IsExpanded():
            self.Collapse(item)
        else:
            self.Expand(item)

[docs]    def HideWindows(self):
        """ Hides the windows associated to the items. Used internally. """

        for child in self._itemWithWindow:
            if not self.IsVisible(child):
                wnd = child.GetWindow()
                if wnd:
                    wnd.Hide()

[docs]    def Unselect(self):
        """ Unselects the current selection. """

        if self._current:
            self._current.SetHilight(False)
            self.RefreshLine(self._current)

        self._current = None
        self._select_me = None

[docs]    def UnselectAllChildren(self, item):
        """
        Unselects all the children of the given item.

        :param `item`: an instance of L{GenericTreeItem}.
        """

        if item.IsSelected():
            item.SetHilight(False)
            self.RefreshLine(item)

        if item.HasChildren():
            for child in item.GetChildren():
                self.UnselectAllChildren(child)

[docs]    def SelectAllChildren(self, item):
        """
        Selects all the children of the given item.

        :param `item`: an instance of L{GenericTreeItem}.

        :raise: `Exception` if used without the ``TR_EXTENDED`` or ``TR_MULTIPLE`` style set.

        :note: This method can be used only if L{CustomTreeCtrl} has the ``TR_MULTIPLE`` or ``TR_EXTENDED``
         style set.
        """

        if not self.HasAGWFlag(TR_MULTIPLE) and not self.HasAGWFlag(TR_EXTENDED):
            raise Exception("SelectAllChildren can be used only with multiple selection enabled.")

        if not item.IsSelected():
            item.SetHilight(True)
            self.RefreshLine(item)

        if item.HasChildren():
            for child in item.GetChildren():
                self.SelectAllChildren(child)

[docs]    def UnselectAll(self):
        """ Unselect all the items. """

        rootItem = self.GetRootItem()

        # the tree might not have the root item at all
        if rootItem:
            self.UnselectAllChildren(rootItem)

        self.Unselect()

[docs]    def SelectAll(self):
        """
        Selects all the item in the tree.

        :raise: `Exception` if used without the ``TR_EXTENDED`` or ``TR_MULTIPLE`` style set.

        :note: This method can be used only if L{CustomTreeCtrl} has the ``TR_MULTIPLE`` or ``TR_EXTENDED``
         style set.
        """

        if not self.HasAGWFlag(TR_MULTIPLE) and not self.HasAGWFlag(TR_EXTENDED):
            raise Exception("SelectAll can be used only with multiple selection enabled.")

        rootItem = self.GetRootItem()

        # the tree might not have the root item at all
        if rootItem:
            self.SelectAllChildren(rootItem)

    # Recursive function !
    # To stop we must have crt_item<last_item
    # Algorithm :
    # Tag all next children, when no more children,
    # Move to parent (not to tag)
    # Keep going... if we found last_item, we stop.

[docs]    def TagNextChildren(self, crt_item, last_item, select):
        """ Used internally. """

        parent = crt_item.GetParent()

        if parent == None: # This is root item
            return self.TagAllChildrenUntilLast(crt_item, last_item, select)

        children = parent.GetChildren()
        index = children.index(crt_item)

        count = len(children)

        for n in xrange(index+1, count):
            if self.TagAllChildrenUntilLast(children[n], last_item, select):
                return True

        return self.TagNextChildren(parent, last_item, select)

[docs]    def TagAllChildrenUntilLast(self, crt_item, last_item, select):
        """ Used internally. """

        crt_item.SetHilight(select)
        self.RefreshLine(crt_item)

        if crt_item == last_item:
            return True

        if crt_item.HasChildren():
            for child in crt_item.GetChildren():
                if self.TagAllChildrenUntilLast(child, last_item, select):
                    return True

        return False

[docs]    def SelectItemRange(self, item1, item2):
        """
        Selects all the items between `item1` and `item2`.

        :param `item1`: an instance of L{GenericTreeItem}, representing the first
         item in the range to select;
        :param `item2`: an instance of L{GenericTreeItem}, representing the last
         item in the range to select.

        :raise: `Exception` if used without the ``TR_EXTENDED`` or ``TR_MULTIPLE`` style set.

        :note: This method can be used only if L{CustomTreeCtrl} has the ``TR_MULTIPLE`` or ``TR_EXTENDED``
         style set.
        """

        if not self.HasAGWFlag(TR_MULTIPLE) and not self.HasAGWFlag(TR_EXTENDED):
            raise Exception("SelectItemRange can be used only with multiple selection enabled.")

        self._select_me = None

        # item2 is not necessary after item1
        # choice first' and 'last' between item1 and item2
        first = (item1.GetY() < item2.GetY() and [item1] or [item2])[0]
        last = (item1.GetY() < item2.GetY() and [item2] or [item1])[0]

        select = self._current.IsSelected()

        if self.TagAllChildrenUntilLast(first, last, select):
            return

        self.TagNextChildren(first, last, select)

[docs]    def DoSelectItem(self, item, unselect_others=True, extended_select=False):
        """
        Actually selects/unselects an item, sending ``EVT_TREE_SEL_CHANGING`` and
        ``EVT_TREE_SEL_CHANGED`` events.

        :param `item`: an instance of L{GenericTreeItem};
        :param bool `unselect_others`: if ``True``, all the other selected items are
         unselected.
        :param bool `extended_select`: ``True`` if the L{CustomTreeCtrl} is using the
         ``TR_EXTENDED`` style.
        """

        self._select_me = None

        is_single = not (self.GetAGWWindowStyleFlag() & TR_MULTIPLE)

        # to keep going anyhow !!!
        if is_single:
            if item.IsSelected():
                # Handles hypertext items
                self.HandleHyperLink(item)
                return # nothing else to do
            unselect_others = True
            extended_select = False

        elif unselect_others and item.IsSelected():

            # selection change if there is more than one item currently selected
            if len(self.GetSelections()) == 1:
                # Handles hypertext items
                self.HandleHyperLink(item)
                return

        event = TreeEvent(wxEVT_TREE_SEL_CHANGING, self.GetId())
        event._item = item
        event._itemOld = self._current
        event.SetEventObject(self)
        # TODO : Here we don't send any selection mode yet !

        if self.GetEventHandler().ProcessEvent(event) and not event.IsAllowed():
            return

        parent = self.GetItemParent(item)
        while parent:
            if not self.IsExpanded(parent):
                self.Expand(parent)

            parent = self.GetItemParent(parent)

        # ctrl press
        if unselect_others:
            if is_single:
                self.Unselect() # to speed up thing
            else:
                self.UnselectAll()

        # shift press
        if extended_select:
            if not self._current:
                self._current = self._key_current = self.GetRootItem()

            # don't change the mark (self._current)
            self.SelectItemRange(self._current, item)

        else:

            select = True # the default

            # Check if we need to toggle hilight (ctrl mode)
            if not unselect_others:
                select = not item.IsSelected()

            self._current = self._key_current = item
            self._current.SetHilight(select)
            self.RefreshLine(self._current)

        # This can cause idle processing to select the root
        # if no item is selected, so it must be after the
        # selection is set
        self.EnsureVisible(item)

        event.SetEventType(wxEVT_TREE_SEL_CHANGED)
        self.GetEventHandler().ProcessEvent(event)

        # Handles hypertext items
        self.HandleHyperLink(item)

[docs]    def SelectItem(self, item, select=True):
        """
        Selects/deselects an item.

        :param `item`: an instance of L{GenericTreeItem};
        :param bool `select`: ``True`` to select an item, ``False`` to deselect it.
        """

        if select:

            self.DoSelectItem(item, not self.HasAGWFlag(TR_MULTIPLE))

        else: # deselect

            item.SetHilight(False)
            self.RefreshLine(item)

[docs]    def FillArray(self, item, array=[]):
        """
        Internal function. Used to populate an array of selected items when
        the style ``TR_MULTIPLE`` is used.

        :param `item`: an instance of L{GenericTreeItem};
        :param list `array`: a Python list containing the selected items.

        :return: A Python list containing the selected items.
        """

        if not array:
            array = []

        if item.IsSelected():
            array.append(item)

        if item.HasChildren() and item.IsExpanded():
            for child in item.GetChildren():
                array = self.FillArray(child, array)

        return array

[docs]    def GetSelections(self):
        """
        Returns a list of selected items.

        :note: This method can be used only if L{CustomTreeCtrl} has the ``TR_MULTIPLE`` or ``TR_EXTENDED``
         style set.

        :return: A Python list containing the selected items, all instances of L{GenericTreeItem}.
        """

        array = []
        idRoot = self.GetRootItem()
        if idRoot:
            array = self.FillArray(idRoot, array)

        #else: the tree is empty, so no selections

        return array

[docs]    def HandleHyperLink(self, item):
        """
        Handles the hyperlink items, sending the ``EVT_TREE_ITEM_HYPERLINK`` event.

        :param `item`: an instance of L{GenericTreeItem}.
        """

        if self.IsItemHyperText(item):
            event = TreeEvent(wxEVT_TREE_ITEM_HYPERLINK, self.GetId())
            event._item = item
            self.GetEventHandler().ProcessEvent(event)

[docs]    def EnsureVisible(self, item):
        """
        Scrolls and/or expands items to ensure that the given item is visible.

        :param `item`: an instance of L{GenericTreeItem}.
        """

        # first expand all parent branches
        parent = item.GetParent()

        if self.HasAGWFlag(TR_HIDE_ROOT):
            while parent and parent != self._anchor:
                self.Expand(parent)
                parent = parent.GetParent()
        else:
            while parent:
                self.Expand(parent)
                parent = parent.GetParent()

        self.ScrollTo(item)

[docs]    def ScrollTo(self, item):
        """
        Scrolls the specified item into view.

        :param `item`: an instance of L{GenericTreeItem}.
        """

        if not item:
            return

        # We have to call this here because the label in
        # question might just have been added and no screen
        # update taken place.
        if self._dirty:
            if wx.Platform in ["__WXMSW__", "__WXMAC__"]:
                self.Update()
        else:
            wx.YieldIfNeeded()

        # now scroll to the item
        item_y = item.GetY()
        start_x, start_y = self.GetViewStart()
        start_y *= _PIXELS_PER_UNIT

        client_w, client_h = self.GetClientSize()

        x, y = 0, 0

        if item_y < start_y+3:

            # going down
            x, y = self._anchor.GetSize(x, y, self)
            y += _PIXELS_PER_UNIT + 2 # one more scrollbar unit + 2 pixels
            x += _PIXELS_PER_UNIT + 2 # one more scrollbar unit + 2 pixels
            x_pos = self.GetScrollPos(wx.HORIZONTAL)
            # Item should appear at top
            self.SetScrollbars(_PIXELS_PER_UNIT, _PIXELS_PER_UNIT, x/_PIXELS_PER_UNIT, y/_PIXELS_PER_UNIT, x_pos, item_y/_PIXELS_PER_UNIT)

        elif item_y+self.GetLineHeight(item) > start_y+client_h:

            # going up
            x, y = self._anchor.GetSize(x, y, self)
            y += _PIXELS_PER_UNIT + 2 # one more scrollbar unit + 2 pixels
            x += _PIXELS_PER_UNIT + 2 # one more scrollbar unit + 2 pixels
            item_y += _PIXELS_PER_UNIT+2
            x_pos = self.GetScrollPos(wx.HORIZONTAL)
            # Item should appear at bottom
            self.SetScrollbars(_PIXELS_PER_UNIT, _PIXELS_PER_UNIT, x/_PIXELS_PER_UNIT, y/_PIXELS_PER_UNIT, x_pos, (item_y+self.GetLineHeight(item)-client_h)/_PIXELS_PER_UNIT )

[docs]    def OnCompareItems(self, item1, item2):
        """
        Returns whether 2 items have the same text.

        Override this function in the derived class to change the sort order of the items
        in the L{CustomTreeCtrl}. The function should return a negative, zero or positive
        value if the first item is less than, equal to or greater than the second one.

        :param `item1`: an instance of L{GenericTreeItem};
        :param `item2`: another instance of L{GenericTreeItem}.

        :return: The return value is negative if `item1` < `item2`, zero if `item1` == `item2`
         and strictly positive if `item1` < `item2`.

        :note: The base class version compares items alphabetically.
        """

        return cmp(self.GetItemText(item1), self.GetItemText(item2))

[docs]    def SortChildren(self, item):
        """
        Sorts the children of the given item using the L{OnCompareItems} method of
        L{CustomTreeCtrl}.

        :param `item`: an instance of L{GenericTreeItem}.

        :note: You should override the L{OnCompareItems} method in your derived class to change
         the sort order (the default is ascending case-sensitive alphabetical order).
        """

        children = item.GetChildren()

        if len(children) > 1:
            self._dirty = True
            children.sort(self.OnCompareItems)

[docs]    def GetImageList(self):
        """
        Returns the normal image list associated with L{CustomTreeCtrl}.

        :return: An instance of `wx.ImageList`.
        """

        return self._imageListNormal

[docs]    def GetButtonsImageList(self):
        """
        Returns the buttons image list associated with L{CustomTreeCtrl} (from
        which application-defined button images are taken).

        :return: An instance of `wx.ImageList`.
        """

        return self._imageListButtons

[docs]    def GetStateImageList(self):
        """
        Returns the state image list associated with L{CustomTreeCtrl} (from which
        application-defined state images are taken).

        :return: An instance of `wx.ImageList`.
        """

        return self._imageListState

[docs]    def GetImageListCheck(self):
        """
        Returns the image list used to build the check/radio buttons in L{CustomTreeCtrl}.

        :return: An instance of `wx.ImageList`.
        """

        return self._imageListCheck

[docs]    def GetLeftImageList(self):
        """
        Returns the image list for L{CustomTreeCtrl} filled with images to be used on
        the leftmost part of the client area. Any item can have a leftmost image associated
        with it.

        :return: An instance of `wx.ImageList`.
        """

        return self._imageListLeft

[docs]    def CalculateLineHeight(self):
        """ Calculates the height of a line. """

        dc = wx.ClientDC(self)
        self._lineHeight = dc.GetCharHeight()

        if self._imageListNormal:

            # Calculate a self._lineHeight value from the normal Image sizes.
            # May be toggle off. Then CustomTreeCtrl will spread when
            # necessary (which might look ugly).
            n = self._imageListNormal.GetImageCount()

            for i in xrange(n):

                width, height = self._imageListNormal.GetSize(i)

                if height > self._lineHeight:
                    self._lineHeight = height

        if self._imageListButtons:

            # Calculate a self._lineHeight value from the Button image sizes.
            # May be toggle off. Then CustomTreeCtrl will spread when
            # necessary (which might look ugly).
            n = self._imageListButtons.GetImageCount()

            for i in xrange(n):

                width, height = self._imageListButtons.GetSize(i)

                if height > self._lineHeight:
                    self._lineHeight = height

        if self._imageListCheck:

            # Calculate a self._lineHeight value from the check/radio image sizes.
            # May be toggle off. Then CustomTreeCtrl will spread when
            # necessary (which might look ugly).
            n = self._imageListCheck.GetImageCount()

            for i in xrange(n):

                width, height = self._imageListCheck.GetSize(i)

                if height > self._lineHeight:
                    self._lineHeight = height

        if self._imageListLeft:

            # Calculate a self._lineHeight value from the leftmost image sizes.
            # May be toggle off. Then CustomTreeCtrl will spread when
            # necessary (which might look ugly).
            n = self._imageListLeft.GetImageCount()

            for i in xrange(n):

                width, height = self._imageListLeft.GetSize(i)

                if height > self._lineHeight:
                    self._lineHeight = height

        if self._lineHeight < 30:
            self._lineHeight += 2                 # at least 2 pixels
        else:
            self._lineHeight += self._lineHeight/10   # otherwise 10% extra spacing

[docs]    def SetImageList(self, imageList):
        """
        Sets the normal image list for L{CustomTreeCtrl}.

        :param `imageList`: an instance of `wx.ImageList`.
        """

        if self._ownsImageListNormal:
            del self._imageListNormal

        self._imageListNormal = imageList
        self._ownsImageListNormal = False
        self._dirty = True

        # Don't do any drawing if we're setting the list to NULL,
        # since we may be in the process of deleting the tree control.
        if imageList:
            self.CalculateLineHeight()

            # We gray out the image list to use the grayed icons with disabled items
            sz = imageList.GetSize(0)
            self._grayedImageList = wx.ImageList(sz[0], sz[1], True, 0)

            for ii in xrange(imageList.GetImageCount()):
                bmp = imageList.GetBitmap(ii)
                newbmp = MakeDisabledBitmap(bmp)
                self._grayedImageList.Add(newbmp)

[docs]    def SetLeftImageList(self, imageList):
        """
        Sets the image list for L{CustomTreeCtrl} filled with images to be used on
        the leftmost part of the client area. Any item can have a leftmost image associated
        with it.

        :param `imageList`: an instance of `wx.ImageList`.
        """

        self._imageListLeft = imageList
        self._ownsImageListLeft = False
        self._dirty = True

        # Don't do any drawing if we're setting the list to NULL,
        # since we may be in the process of deleting the tree control.
        if imageList:
            self.CalculateLineHeight()

            # We gray out the image list to use the grayed icons with disabled items
            sz = imageList.GetSize(0)
            self._grayedImageListLeft = wx.ImageList(sz[0], sz[1], True, 0)

            for ii in xrange(imageList.GetImageCount()):
                bmp = imageList.GetBitmap(ii)
                newbmp = MakeDisabledBitmap(bmp)
                self._grayedImageListLeft.Add(newbmp)

[docs]    def SetStateImageList(self, imageList):
        """
        Sets the state image list for L{CustomTreeCtrl} (from which application-defined
        state images are taken).

        :param `imageList`: an instance of `wx.ImageList`.
        """

        if self._ownsImageListState:
            del self._imageListState

        self._imageListState = imageList
        self._ownsImageListState = False

[docs]    def SetButtonsImageList(self, imageList):
        """
        Sets the buttons image list for L{CustomTreeCtrl} (from which application-defined
        button images are taken).

        :param `imageList`: an instance of `wx.ImageList`.
        """

        if self._ownsImageListButtons:
            del self._imageListButtons

        self._imageListButtons = imageList
        self._ownsImageListButtons = False
        self._dirty = True
        self.CalculateLineHeight()

[docs]    def SetImageListCheck(self, sizex, sizey, imglist=None):
        """
        Sets the checkbox/radiobutton image list.

        :param integer `sizex`: the width of the bitmaps in the `imglist`, in pixels;
        :param integer `sizey`: the height of the bitmaps in the `imglist`, in pixels;
        :param `imglist`: an instance of `wx.ImageList`.
        """

        # Image list to hold disabled versions of each control
        self._grayedCheckList = wx.ImageList(sizex, sizey, True, 0)

        if imglist is None:

            self._imageListCheck = wx.ImageList(sizex, sizey)

            # Get the Checkboxes
            self._imageListCheck.Add(self.GetControlBmp(checkbox=True,
                                                        checked=True,
                                                        enabled=True,
                                                        x=sizex, y=sizey))
            self._grayedCheckList.Add(self.GetControlBmp(checkbox=True,
                                                         checked=True,
                                                         enabled=False,
                                                         x=sizex, y=sizey))

            self._imageListCheck.Add(self.GetControlBmp(checkbox=True,
                                                        checked=False,
                                                        enabled=True,
                                                        x=sizex, y=sizey))
            self._grayedCheckList.Add(self.GetControlBmp(checkbox=True,
                                                         checked=False,
                                                         enabled=False,
                                                         x=sizex, y=sizey))

            self._imageListCheck.Add(self.GetControlBmp(checkbox=True,
                                                        checked=2,
                                                        enabled=True,
                                                        x=sizex, y=sizey))
            self._grayedCheckList.Add(self.GetControlBmp(checkbox=True,
                                                         checked=2,
                                                         enabled=False,
                                                         x=sizex, y=sizey))

            # Get the Radio Buttons
            self._imageListCheck.Add(self.GetControlBmp(checkbox=False,
                                                        checked=True,
                                                        enabled=True,
                                                        x=sizex, y=sizey))
            self._grayedCheckList.Add(self.GetControlBmp(checkbox=False,
                                                         checked=True,
                                                         enabled=False,
                                                         x=sizex, y=sizey))

            self._imageListCheck.Add(self.GetControlBmp(checkbox=False,
                                                        checked=False,
                                                        enabled=True,
                                                        x=sizex, y=sizey))
            self._grayedCheckList.Add(self.GetControlBmp(checkbox=False,
                                                        checked=False,
                                                        enabled=False,
                                                        x=sizex, y=sizey))

        else:

            sizex, sizey = imglist.GetSize(0)
            self._imageListCheck = imglist

            for ii in xrange(self._imageListCheck.GetImageCount()):

                bmp = self._imageListCheck.GetBitmap(ii)
                newbmp = MakeDisabledBitmap(bmp)
                self._grayedCheckList.Add(newbmp)

        self._dirty = True

        if imglist:
            self.CalculateLineHeight()

[docs]    def AssignImageList(self, imageList):
        """
        Assigns the normal image list.

        :param `imageList`: an instance of `wx.ImageList`.
        """

        self.SetImageList(imageList)
        self._ownsImageListNormal = True

[docs]    def AssignStateImageList(self, imageList):
        """
        Assigns the state image list.

        :param `imageList`: an instance of `wx.ImageList`.
        """

        self.SetStateImageList(imageList)
        self._ownsImageListState = True

[docs]    def AssignButtonsImageList(self, imageList):
        """
        Assigns the button image list.

        :param `imageList`: an instance of `wx.ImageList`.
        """

        self.SetButtonsImageList(imageList)
        self._ownsImageListButtons = True

[docs]    def AssignLeftImageList(self, imageList):
        """
        Assigns the image list for L{CustomTreeCtrl} filled with images to be used on
        the leftmost part of the client area. Any item can have a leftmost image associated
        with it.

        :param `imageList`: an instance of `wx.ImageList`.
        """

        self.SetLeftImageList(imageList)
        self._ownsImageListLeft = True

# -----------------------------------------------------------------------------
# helpers
# -----------------------------------------------------------------------------

[docs]    def AdjustMyScrollbars(self):
        """ Internal method used to adjust the `wx.PyScrolledWindow` scrollbars. """

        if self._anchor:

            x, y = self._anchor.GetSize(0, 0, self)
            y += _PIXELS_PER_UNIT + 2 # one more scrollbar unit + 2 pixels
            x += _PIXELS_PER_UNIT + 2 # one more scrollbar unit + 2 pixels
            x_pos = self.GetScrollPos(wx.HORIZONTAL)
            y_pos = self.GetScrollPos(wx.VERTICAL)
            self.SetScrollbars(_PIXELS_PER_UNIT, _PIXELS_PER_UNIT, x/_PIXELS_PER_UNIT, y/_PIXELS_PER_UNIT, x_pos, y_pos)

        else:

            self.SetScrollbars(0, 0, 0, 0)

[docs]    def GetLineHeight(self, item):
        """
        Returns the line height for the given item.

        :param `item`: an instance of L{GenericTreeItem}.

        :return: the item height, in pixels.
        """

        if self.GetAGWWindowStyleFlag() & TR_HAS_VARIABLE_ROW_HEIGHT:
            return int(item.GetHeight())
        else:
            return int(self._lineHeight)

[docs]    def DrawVerticalGradient(self, dc, rect, hasfocus):
        """
        Gradient fill from colour 1 to colour 2 from top to bottom.

        :param `dc`: an instance of `wx.DC`;
        :param `wx.Rect` `rect`: the rectangle to be filled with the gradient shading;
        :param bool `hasfocus`: ``True`` if the main L{CustomTreeCtrl} has focus, ``False``
         otherwise.
        """

        oldpen = dc.GetPen()
        oldbrush = dc.GetBrush()
        dc.SetPen(wx.TRANSPARENT_PEN)

        # calculate gradient coefficients
        if hasfocus:
            col2 = self._secondcolour
            col1 = self._firstcolour
        else:
            col2 = self._hilightUnfocusedBrush.GetColour()
            col1 = self._hilightUnfocusedBrush2.GetColour()

        r1, g1, b1 = int(col1.Red()), int(col1.Green()), int(col1.Blue())
        r2, g2, b2 = int(col2.Red()), int(col2.Green()), int(col2.Blue())

        flrect = float(rect.height)

        rstep = float((r2 - r1)) / flrect
        gstep = float((g2 - g1)) / flrect
        bstep = float((b2 - b1)) / flrect

        rf, gf, bf = 0, 0, 0

        for y in xrange(rect.y, rect.y + rect.height):
            currCol = (r1 + rf, g1 + gf, b1 + bf)
            dc.SetBrush(wx.Brush(currCol, wx.SOLID))
            dc.DrawRectangle(rect.x, y, rect.width, 1)
            rf = rf + rstep
            gf = gf + gstep
            bf = bf + bstep

        dc.SetPen(oldpen)
        dc.SetBrush(wx.TRANSPARENT_BRUSH)
        dc.DrawRectangleRect(rect)
        dc.SetBrush(oldbrush)

[docs]    def DrawHorizontalGradient(self, dc, rect, hasfocus):
        """
        Gradient fill from colour 1 to colour 2 from left to right.

        :param `dc`: an instance of `wx.DC`;
        :param `wx.Rect` `rect`: the rectangle to be filled with the gradient shading;
        :param bool `hasfocus`: ``True`` if the main L{CustomTreeCtrl} has focus, ``False``
         otherwise.
        """

        oldpen = dc.GetPen()
        oldbrush = dc.GetBrush()
        dc.SetPen(wx.TRANSPARENT_PEN)

        # calculate gradient coefficients

        if hasfocus:
            col2 = self._secondcolour
            col1 = self._firstcolour
        else:
            col2 = self._hilightUnfocusedBrush.GetColour()
            col1 = self._hilightUnfocusedBrush2.GetColour()

        r1, g1, b1 = int(col1.Red()), int(col1.Green()), int(col1.Blue())
        r2, g2, b2 = int(col2.Red()), int(col2.Green()), int(col2.Blue())

        flrect = float(rect.width)

        rstep = float((r2 - r1)) / flrect
        gstep = float((g2 - g1)) / flrect
        bstep = float((b2 - b1)) / flrect

        rf, gf, bf = 0, 0, 0

        for x in xrange(rect.x, rect.x + rect.width):
            currCol = (int(r1 + rf), int(g1 + gf), int(b1 + bf))
            dc.SetBrush(wx.Brush(currCol, wx.SOLID))
            dc.DrawRectangle(x, rect.y, 1, rect.height)
            rf = rf + rstep
            gf = gf + gstep
            bf = bf + bstep

        dc.SetPen(oldpen)
        dc.SetBrush(wx.TRANSPARENT_BRUSH)
        dc.DrawRectangleRect(rect)
        dc.SetBrush(oldbrush)

[docs]    def DrawVistaRectangle(self, dc, rect, hasfocus):
        """
        Draws the selected item(s) with the Windows Vista style.

        :param `dc`: an instance of `wx.DC`;
        :param `wx.Rect` `rect`: the rectangle to be filled with the gradient shading;
        :param bool `hasfocus`: ``True`` if the main L{CustomTreeCtrl} has focus, ``False``
         otherwise.
        """

        if hasfocus:

            outer = _rgbSelectOuter
            inner = _rgbSelectInner
            top = _rgbSelectTop
            bottom = _rgbSelectBottom

        else:

            outer = _rgbNoFocusOuter
            inner = _rgbNoFocusInner
            top = _rgbNoFocusTop
            bottom = _rgbNoFocusBottom

        oldpen = dc.GetPen()
        oldbrush = dc.GetBrush()

        bdrRect = wx.Rect(*rect.Get())
        filRect = wx.Rect(*rect.Get())
        filRect.Deflate(1,1)

        r1, g1, b1 = int(top.Red()), int(top.Green()), int(top.Blue())
        r2, g2, b2 = int(bottom.Red()), int(bottom.Green()), int(bottom.Blue())

        flrect = float(filRect.height)
        if flrect < 1:
            flrect = self._lineHeight

        rstep = float((r2 - r1)) / flrect
        gstep = float((g2 - g1)) / flrect
        bstep = float((b2 - b1)) / flrect

        rf, gf, bf = 0, 0, 0
        dc.SetPen(wx.TRANSPARENT_PEN)

        for y in xrange(filRect.y, filRect.y + filRect.height):
            currCol = (r1 + rf, g1 + gf, b1 + bf)
            dc.SetBrush(wx.Brush(currCol, wx.SOLID))
            dc.DrawRectangle(filRect.x, y, filRect.width, 1)
            rf = rf + rstep
            gf = gf + gstep
            bf = bf + bstep

        dc.SetBrush(wx.TRANSPARENT_BRUSH)
        dc.SetPen(wx.Pen(outer))
        dc.DrawRoundedRectangleRect(bdrRect, 3)
        bdrRect.Deflate(1, 1)
        dc.SetPen(wx.Pen(inner))
        dc.DrawRoundedRectangleRect(bdrRect, 2)

        dc.SetPen(oldpen)
        dc.SetBrush(oldbrush)

[docs]    def PaintItem(self, item, dc, level, align):
        """
        Actually draws an item.

        :param `item`: an instance of L{GenericTreeItem};
        :param `dc`: an instance of `wx.DC`;
        :param integer `level`: the item level in the tree hierarchy;
        :param integer `align`: an integer specifying the alignment type:

         =============== =========================================
         `align` Value   Description
         =============== =========================================
                0        No horizontal alignment of windows (in items with windows).
                1        Windows (in items with windows) are aligned at the same horizontal position.
                2        Windows (in items with windows) are aligned at the rightmost edge of L{CustomTreeCtrl}.
         =============== =========================================
        """

        attr = item.GetAttributes()

        if attr and attr.HasFont():
            dc.SetFont(attr.GetFont())
        else:
            if item.IsBold():
                dc.SetFont(self._boldFont)
            elif item.IsItalic():
                dc.SetFont(self._italicFont)
        if item.IsHyperText():
            dc.SetFont(self.GetHyperTextFont())
            if item.GetVisited():
                dc.SetTextForeground(self.GetHyperTextVisitedColour())
            else:
                dc.SetTextForeground(self.GetHyperTextNewColour())

        text_w, text_h, dummy = dc.GetMultiLineTextExtent(item.GetText())
        w, h = self.GetClientSize()

        image = item.GetCurrentImage()
        checkimage = item.GetCurrentCheckedImage()
        leftimage = _NO_IMAGE
        separator = item.IsSeparator()

        if self._imageListLeft:
            leftimage = item.GetLeftImage()

        image_w, image_h = 0, 0

        if image != _NO_IMAGE:

            if self._imageListNormal:

                image_w, image_h = self._imageListNormal.GetSize(image)
                image_w += 4

            else:

                image = _NO_IMAGE

        if item.GetType() != 0:
            wcheck, hcheck = self._imageListCheck.GetSize(item.GetType())
            wcheck += 4
        else:
            wcheck, hcheck = 0, 0

        if leftimage != _NO_IMAGE:
            l_image_w, l_image_h = self._imageListLeft.GetSize(leftimage)

        total_h = self.GetLineHeight(item)
        drawItemBackground = False

        if item.IsSelected():

            # under mac selections are only a rectangle in case they don't have the focus
            if wx.Platform == "__WXMAC__":
                if not self._hasFocus:
                    dc.SetBrush(wx.TRANSPARENT_BRUSH)
                    dc.SetPen(wx.Pen(wx.SystemSettings_GetColour(wx.SYS_COLOUR_HIGHLIGHT), 1, wx.SOLID))
                else:
                    dc.SetBrush(self._hilightBrush)
            else:
                    dc.SetBrush((self._hasFocus and [self._hilightBrush] or [self._hilightUnfocusedBrush])[0])
                    drawItemBackground = True
        else:
            if attr and attr.HasBackgroundColour():
                drawItemBackground = True
                colBg = attr.GetBackgroundColour()
            else:
                colBg = self._backgroundColour

            dc.SetBrush(wx.Brush(colBg, wx.SOLID))
            dc.SetPen(wx.TRANSPARENT_PEN)

        offset = (self.HasAGWFlag(TR_ROW_LINES) and [1] or [0])[0]

        if self.HasAGWFlag(TR_FULL_ROW_HIGHLIGHT):
            x = 0

            itemrect = wx.Rect(x, item.GetY()+offset, w, total_h-offset)

            if item.IsSelected():
                if self._usegradients:
                    if self._gradientstyle == 0:   # Horizontal
                        self.DrawHorizontalGradient(dc, itemrect, self._hasFocus)
                    else:                          # Vertical
                        self.DrawVerticalGradient(dc, itemrect, self._hasFocus)
                elif self._vistaselection:
                    self.DrawVistaRectangle(dc, itemrect, self._hasFocus)
                else:
                    if wx.Platform in ["__WXGTK2__", "__WXMAC__"]:
                        flags = wx.CONTROL_SELECTED
                        if self._hasFocus: flags = flags | wx.CONTROL_FOCUSED
                        wx.RendererNative.Get().DrawItemSelectionRect(self, dc, itemrect, flags)
                    else:
                        dc.DrawRectangleRect(itemrect)
            else:
               if drawItemBackground:
                   minusicon = wcheck + image_w - 2
                   itemrect = wx.Rect(item.GetX()+minusicon,
                                      item.GetY()+offset,
                                      item.GetWidth()-minusicon,
                                      total_h-offset)
                   dc.DrawRectangleRect(itemrect)

        else:

            if item.IsSelected():

                # If it's selected, and there's an image, then we should
                # take care to leave the area under the image painted in the
                # background colour.

                wnd = item.GetWindow()
                wndx = 0
                if wnd:
                    wndx, wndy = item.GetWindowSize()

                if separator:
                    item_width = w
                else:
                    item_width = item.GetWidth() - image_w - wcheck + 2 - wndx

                itemrect = wx.Rect(item.GetX() + wcheck + image_w - 2,
                                   item.GetY()+offset,
                                   item_width,
                                   total_h-offset)

                if self._usegradients:
                    if self._gradientstyle == 0:   # Horizontal
                        self.DrawHorizontalGradient(dc, itemrect, self._hasFocus)
                    else:                          # Vertical
                        self.DrawVerticalGradient(dc, itemrect, self._hasFocus)
                elif self._vistaselection:
                    self.DrawVistaRectangle(dc, itemrect, self._hasFocus)
                else:
                    if wx.Platform in ["__WXGTK2__", "__WXMAC__"]:
                        flags = wx.CONTROL_SELECTED
                        if self._hasFocus: flags = flags | wx.CONTROL_FOCUSED
                        wx.RendererNative.Get().DrawItemSelectionRect(self, dc, itemrect, flags)
                    else:
                        dc.DrawRectangleRect(itemrect)

            # On GTK+ 2, drawing a 'normal' background is wrong for themes that
            # don't allow backgrounds to be customized. Not drawing the background,
            # except for custom item backgrounds, works for both kinds of theme.
            elif drawItemBackground:

                minusicon = wcheck + image_w - 2

                if separator:
                    item_width = w
                else:
                    item_width = item.GetWidth()-minusicon,

                itemrect = wx.Rect(item.GetX()+minusicon,
                                   item.GetY()+offset,
                                   item_width,
                                   total_h-offset)

                if self._usegradients and self._hasFocus:
                    if self._gradientstyle == 0:   # Horizontal
                        self.DrawHorizontalGradient(dc, itemrect, self._hasFocus)
                    else:                          # Vertical
                        self.DrawVerticalGradient(dc, itemrect, self._hasFocus)
                else:
                    dc.DrawRectangleRect(itemrect)

        if image != _NO_IMAGE:

            dc.SetClippingRegion(item.GetX(), item.GetY(), wcheck+image_w-2, total_h)
            if item.IsEnabled():
                imglist = self._imageListNormal
            else:
                imglist = self._grayedImageList

            imglist.Draw(image, dc,
                         item.GetX() + wcheck,
                         item.GetY() + ((total_h > image_h) and [(total_h-image_h)/2] or [0])[0],
                         wx.IMAGELIST_DRAW_TRANSPARENT)

            dc.DestroyClippingRegion()

        if wcheck:
            if item.IsEnabled():
                imglist = self._imageListCheck
            else:
                imglist = self._grayedCheckList

            imglist.Draw(checkimage, dc,
                         item.GetX(),
                         item.GetY() + ((total_h > hcheck) and [(total_h-hcheck)/2] or [0])[0],
                         wx.IMAGELIST_DRAW_TRANSPARENT)

        if leftimage != _NO_IMAGE:
            if item.IsEnabled():
                imglist = self._imageListLeft
            else:
                imglist = self._grayedImageListLeft

            imglist.Draw(leftimage, dc,
                         4,
                         item.GetY() + ((total_h > l_image_h) and [(total_h-l_image_h)/2] or [0])[0],
                         wx.IMAGELIST_DRAW_TRANSPARENT)

        dc.SetBackgroundMode(wx.TRANSPARENT)
        extraH = ((total_h > text_h) and [(total_h - text_h)/2] or [0])[0]

        textrect = wx.Rect(wcheck + image_w + item.GetX(), item.GetY() + extraH, text_w, text_h)

        itemText = item.GetText()
        if self.HasAGWFlag(TR_ELLIPSIZE_LONG_ITEMS) and not separator:
            xa, ya = self.CalcScrolledPosition((0, item.GetY()))
            maxsize = w - (wcheck + image_w + item.GetX()) + xa
            itemText = ChopText(dc, itemText, maxsize)

        if not item.IsEnabled():
            foreground = dc.GetTextForeground()
            dc.SetTextForeground(self._disabledColour)
            dc.DrawLabel(itemText, textrect)
            dc.SetTextForeground(foreground)
        else:
            if wx.Platform == "__WXMAC__" and item.IsSelected() and self._hasFocus:
                dc.SetTextForeground(wx.WHITE)
            dc.DrawLabel(itemText, textrect)

        wnd = item.GetWindow()
        if wnd:
            wndx = wcheck + image_w + item.GetX() + text_w + 4
            xa, ya = self.CalcScrolledPosition((0, item.GetY()))
            wndx += xa
            if item.GetHeight() > item.GetWindowSize()[1]:
                ya += (item.GetHeight() - item.GetWindowSize()[1])/2

            if align == 1:
                # Horizontal alignment of windows
                if level in self.absoluteWindows:
                    wndx = self.absoluteWindows[level] + item.GetX() + 2 + xa

            elif align == 2:
                # Rightmost alignment of windows
                wndx = w - item.GetWindowSize().x - 2 + xa

            if not wnd.IsShown():
                wnd.Show()
            if wnd.GetPosition() != (wndx, ya):
                wnd.SetPosition((wndx, ya))

        if separator:
            oldPen = dc.GetPen()

            if item.IsEnabled():
                if attr and attr.HasTextColour():
                    separatorPen = wx.Pen(attr.GetTextColour(), 1)
                else:
                    separatorPen = self._separatorPen
            else:
                separatorPen = wx.GREY_PEN

            dc.SetPen(separatorPen)
            dc.DrawLine(item.GetX()+2, item.GetY()+total_h/2, w, item.GetY()+total_h/2)
            dc.SetPen(oldPen)

        # restore normal font
        dc.SetFont(self._normalFont)

    # Now y stands for the top of the item, whereas it used to stand for middle !

[docs]    def PaintLevel(self, item, dc, level, y, align):
        """
        Paint a level in the hierarchy of L{CustomTreeCtrl}.

        :param `item`: an instance of L{GenericTreeItem};
        :param `dc`: an instance of `wx.DC`;
        :param integer `level`: the item level in the tree hierarchy;
        :param integer `y`: the current vertical position in the `wx.PyScrolledWindow`;
        :param integer `align`: an integer specifying the alignment type:

         =============== =========================================
         `align` Value   Description
         =============== =========================================
                0        No horizontal alignment of windows (in items with windows).
                1        Windows (in items with windows) are aligned at the same horizontal position.
                2        Windows (in items with windows) are aligned at the rightmost edge of L{CustomTreeCtrl}.
         =============== =========================================

        """

        x = level*self._indent

        left_image_list = 0
        if self._imageListLeft:
            left_image_list += self._imageListLeft.GetBitmap(0).GetWidth()

        x += left_image_list

        if not self.HasAGWFlag(TR_HIDE_ROOT):

            x += self._indent

        elif level == 0:

            # always expand hidden root
            origY = y
            children = item.GetChildren()
            count = len(children)

            if count > 0:
                n = 0
                while n < count:
                    oldY = y
                    y = self.PaintLevel(children[n], dc, 1, y, align)
                    n = n + 1

                if not self.HasAGWFlag(TR_NO_LINES) and self.HasAGWFlag(TR_LINES_AT_ROOT) and count > 0:

                    # draw line down to last child
                    origY += self.GetLineHeight(children[0])>>1
                    oldY += self.GetLineHeight(children[n-1])>>1
                    oldPen = dc.GetPen()
                    dc.SetPen(self._dottedPen)
                    dc.DrawLine(3, origY, 3, oldY)
                    dc.SetPen(oldPen)

            return y

        item.SetX(x+self._spacing)
        item.SetY(y)

        h = self.GetLineHeight(item)
        y_top = y
        y_mid = y_top + (h>>1)
        y += h

        exposed_x = dc.LogicalToDeviceX(0)
        exposed_y = dc.LogicalToDeviceY(y_top)

        if self.IsExposed(exposed_x, exposed_y, 10000, h):  # 10000 = very much
            if wx.Platform == "__WXMAC__":
                # don't draw rect outline if we already have the
                # background colour under Mac
                pen = ((item.IsSelected() and self._hasFocus) and [self._borderPen] or [wx.TRANSPARENT_PEN])[0]
            else:
                pen = self._borderPen

            if item.IsSelected():
                if (wx.Platform == "__WXMAC__" and self._hasFocus):
                    colText = wx.SystemSettings_GetColour(wx.SYS_COLOUR_HIGHLIGHTTEXT)
                else:
                    colText = wx.SystemSettings_GetColour(wx.SYS_COLOUR_HIGHLIGHTTEXT)
            else:
                attr = item.GetAttributes()
                if attr and attr.HasTextColour():
                    colText = attr.GetTextColour()
                else:
                    colText = self.GetForegroundColour()

            if self._vistaselection:
                colText = wx.BLACK

            # prepare to draw
            dc.SetTextForeground(colText)
            dc.SetPen(pen)
            oldpen = pen

            # draw
            self.PaintItem(item, dc, level, align)

            if self.HasAGWFlag(TR_ROW_LINES):

                # if the background colour is white, choose a
                # contrasting colour for the lines
                medium_grey = wx.Pen(wx.Colour(200, 200, 200))
                dc.SetPen(((self.GetBackgroundColour() == wx.WHITE) and [medium_grey] or [wx.WHITE_PEN])[0])
                dc.DrawLine(0, y_top, 10000, y_top)
                dc.DrawLine(0, y, 10000, y)

            # restore DC objects
            dc.SetBrush(wx.WHITE_BRUSH)
            dc.SetTextForeground(wx.BLACK)

            if not self.HasAGWFlag(TR_NO_LINES):

                # draw the horizontal line here
                dc.SetPen(self._dottedPen)
                x_start = x
                if x > self._indent+left_image_list:
                    x_start -= self._indent
                elif self.HasAGWFlag(TR_LINES_AT_ROOT):
                    x_start = 3
                dc.DrawLine(x_start, y_mid, x + self._spacing, y_mid)
                dc.SetPen(oldpen)

            # should the item show a button?
            if item.HasPlus() and self.HasButtons():

                if self._imageListButtons:

                    # draw the image button here
                    image_h = 0
                    image_w = 0
                    image = (item.IsExpanded() and [TreeItemIcon_Expanded] or [TreeItemIcon_Normal])[0]
                    if item.IsSelected():
                        image += TreeItemIcon_Selected - TreeItemIcon_Normal

                    image_w, image_h = self._imageListButtons.GetSize(image)
                    xx = x - image_w/2
                    yy = y_mid - image_h/2

                    dc.SetClippingRegion(xx, yy, image_w, image_h)
                    self._imageListButtons.Draw(image, dc, xx, yy,
                                                wx.IMAGELIST_DRAW_TRANSPARENT)
                    dc.DestroyClippingRegion()

                else: # no custom buttons

                    if self.HasAGWFlag(TR_TWIST_BUTTONS):
                        # We draw something like the Mac twist buttons

                        dc.SetPen(wx.BLACK_PEN)
                        dc.SetBrush(self._hilightBrush)
                        button = [wx.Point(), wx.Point(), wx.Point()]

                        if item.IsExpanded():
                            button[0].x = x - 5
                            button[0].y = y_mid - 3
                            button[1].x = x + 5
                            button[1].y = button[0].y
                            button[2].x = x
                            button[2].y = button[0].y + 6
                        else:
                            button[0].x = x - 3
                            button[0].y = y_mid - 5
                            button[1].x = button[0].x
                            button[1].y = y_mid + 5
                            button[2].x = button[0].x + 5
                            button[2].y = y_mid

                        dc.DrawPolygon(button)

                    else:
                        # These are the standard wx.TreeCtrl buttons as wx.RendererNative knows

                        wImage = 11
                        hImage = 11

                        flag = 0

                        if item.IsExpanded():
                            flag |= _CONTROL_EXPANDED
                        if item == self._underMouse:
                            flag |= _CONTROL_CURRENT

                        self._drawingfunction(self, dc, wx.Rect(x - wImage/2, y_mid - hImage/2, wImage, hImage), flag)

        if item.IsExpanded():

            children = item.GetChildren()
            count = len(children)

            if count > 0:

                n = 0
                level = level + 1

                while n < count:
                    oldY = y
                    y = self.PaintLevel(children[n], dc, level, y, align)
                    n = n + 1

                if not self.HasAGWFlag(TR_NO_LINES) and count > 0:

                    # draw line down to last child
                    oldY += self.GetLineHeight(children[n-1])>>1
                    if self.HasButtons():
                        y_mid += 5

                    # Only draw the portion of the line that is visible, in case it is huge
                    xOrigin, yOrigin = dc.GetDeviceOrigin()
                    yOrigin = abs(yOrigin)
                    width, height = self.GetClientSize()

                    # Move end points to the begining/end of the view?
                    if y_mid < yOrigin:
                        y_mid = yOrigin
                    if oldY > yOrigin + height:
                        oldY = yOrigin + height

                    # after the adjustments if y_mid is larger than oldY then the line
                    # isn't visible at all so don't draw anything
                    if y_mid < oldY:
                        dc.SetPen(self._dottedPen)
                        dc.DrawLine(x, y_mid, x, oldY)

        return y

# -----------------------------------------------------------------------------
# wxWidgets callbacks
# -----------------------------------------------------------------------------

[docs]    def OnPaint(self, event):
        """
        Handles the ``wx.EVT_PAINT`` event for L{CustomTreeCtrl}.

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

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

        if not self._anchor:
            return

        dc.SetFont(self._normalFont)
        dc.SetPen(self._dottedPen)

        align = 0

        if self.HasAGWFlag(TR_ALIGN_WINDOWS):
            align = 1
        elif self.HasAGWFlag(TR_ALIGN_WINDOWS_RIGHT):
            align = 2

        y = 2
        self.PaintLevel(self._anchor, dc, 0, y, align)

[docs]    def OnSize(self, event):
        """
        Handles the ``wx.EVT_SIZE`` event for L{CustomTreeCtrl}.

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

        if self.HasAGWFlag(TR_ELLIPSIZE_LONG_ITEMS):
            self.Refresh()
            event.Skip()
            return

        if self.HasAGWFlag(TR_ALIGN_WINDOWS_RIGHT) and self._itemWithWindow:
            self.RefreshItemWithWindows()
        else:
            self.RefreshSelected()

        event.Skip()

[docs]    def OnEraseBackground(self, event):
        """
        Handles the ``wx.EVT_ERASE_BACKGROUND`` event for L{CustomTreeCtrl}.

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

        # Can we actually do something here (or in OnPaint()) To Handle
        # background images that are stretchable or always centered?
        # I tried but I get enormous flickering...

        if not self._backgroundImage:
            event.Skip()
            return

        if self._imageStretchStyle == _StyleTile:
            dc = event.GetDC()

            if not dc:
                dc = wx.ClientDC(self)
                rect = self.GetUpdateRegion().GetBox()
                dc.SetClippingRect(rect)

            self.TileBackground(dc)

[docs]    def TileBackground(self, dc):
        """
        Tiles the background image to fill all the available area.

        :param `dc`: an instance of `wx.DC`.

        :todo: Support background images also in stretch and centered modes.
        """

        sz = self.GetClientSize()
        w = self._backgroundImage.GetWidth()
        h = self._backgroundImage.GetHeight()

        x = 0

        while x < sz.width:
            y = 0

            while y < sz.height:
                dc.DrawBitmap(self._backgroundImage, x, y, True)
                y = y + h

            x = x + w

[docs]    def OnSetFocus(self, event):
        """
        Handles the ``wx.EVT_SET_FOCUS`` event for L{CustomTreeCtrl}.

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

        self._hasFocus = True
        self.RefreshSelected()
        event.Skip()

[docs]    def OnKillFocus(self, event):
        """
        Handles the ``wx.EVT_KILL_FOCUS`` event for L{CustomTreeCtrl}.

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

        self._hasFocus = False
        self.RefreshSelected()
        event.Skip()

[docs]    def OnKeyDown(self, event):
        """
        Handles the ``wx.EVT_KEY_DOWN`` event for L{CustomTreeCtrl}, sending a
        ``EVT_TREE_KEY_DOWN`` event.

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

        te = TreeEvent(wxEVT_TREE_KEY_DOWN, self.GetId())
        te._evtKey = event
        te.SetEventObject(self)

        if self.GetEventHandler().ProcessEvent(te):
            # intercepted by the user code
            return

        if self._current is None or self._key_current is None:

            self._current = self._key_current = self.GetFirstVisibleItem()

        # how should the selection work for this event?
        is_multiple, extended_select, unselect_others = EventFlagsToSelType(self.GetAGWWindowStyleFlag(),
                                                                            event.ShiftDown(), event.CmdDown())

        # + : Expand
        # - : Collaspe
        # * : Expand all/Collapse all
        # ' ' | return : activate
        # up    : go up (not last children!)
        # down  : go down
        # left  : go to parent
        # right : open if parent and go next
        # home  : go to root
        # end   : go to last item without opening parents
        # alnum : start or continue searching for the item with this prefix

        keyCode = event.GetKeyCode()

        if keyCode in [ord("+"), wx.WXK_ADD]:       # "+"
            if self._current.HasPlus() and not self.IsExpanded(self._current) and self.IsItemEnabled(self._current):
                self.Expand(self._current)

        elif keyCode in [ord("*"), wx.WXK_MULTIPLY]:  # "*"
            if not self.IsExpanded(self._current) and self.IsItemEnabled(self._current):
                # expand all
                self.ExpandAll(self._current)

        elif keyCode in [ord("-"), wx.WXK_SUBTRACT]:  # "-"
            if self.IsExpanded(self._current):
                self.Collapse(self._current)

        elif keyCode == wx.WXK_MENU:
            # Use the item's bounding rectangle to determine position for the event
            itemRect = self.GetBoundingRect(self._current, True)
            event = TreeEvent(wxEVT_TREE_ITEM_MENU, self.GetId())
            event._item = self._current
            # Use the left edge, vertical middle
            event._pointDrag = wx.Point(itemRect.GetX(), itemRect.GetY() + itemRect.GetHeight()/2)
            event.SetEventObject(self)
            self.GetEventHandler().ProcessEvent(event)

        elif keyCode in [wx.WXK_RETURN, wx.WXK_SPACE, wx.WXK_NUMPAD_ENTER]:

            if not self.IsItemEnabled(self._current):
                event.Skip()
                return

            if not event.HasModifiers():
                event = TreeEvent(wxEVT_TREE_ITEM_ACTIVATED, self.GetId())
                event._item = self._current
                event.SetEventObject(self)
                self.GetEventHandler().ProcessEvent(event)

                if keyCode == wx.WXK_SPACE and self.GetItemType(self._current) > 0:
                    if self.IsItem3State(self._current):
                        checked = self.GetItem3StateValue(self._current)
                        checked = (checked+1)%3
                    else:
                        checked = not self.IsItemChecked(self._current)

                    self.CheckItem(self._current, checked)

            # in any case, also generate the normal key event for this key,
            # even if we generated the ACTIVATED event above: this is what
            # wxMSW does and it makes sense because you might not want to
            # process ACTIVATED event at all and handle Space and Return
            # directly (and differently) which would be impossible otherwise
            event.Skip()

        # up goes to the previous sibling or to the last
        # of its children if it's expanded
        elif keyCode == wx.WXK_UP:
            prev = self.GetPrevSibling(self._key_current)
            if not prev:
                prev = self.GetItemParent(self._key_current)
                if prev == self.GetRootItem() and self.HasAGWFlag(TR_HIDE_ROOT):
                    return

                if prev:
                    current = self._key_current
                    # TODO: Huh?  If we get here, we'd better be the first child of our parent.  How else could it be?
                    if current == self.GetFirstChild(prev)[0] and self.IsItemEnabled(prev):
                        # otherwise we return to where we came from
                        self.DoSelectItem(prev, unselect_others, extended_select)
                        self._key_current = prev

            else:
                current = self._key_current

                # We are going to another parent node
                while self.IsExpanded(prev) and self.HasChildren(prev):
                    child = self.GetLastChild(prev)
                    if child:
                        prev = child
                        current = prev

                # Try to get the previous siblings and see if they are active
                while prev and not self.IsItemEnabled(prev):
                    prev = self.GetPrevSibling(prev)

                if not prev:
                    # No previous siblings active: go to the parent and up
                    prev = self.GetItemParent(current)
                    while prev and not self.IsItemEnabled(prev):
                        prev = self.GetItemParent(prev)

                if prev:
                    self.DoSelectItem(prev, unselect_others, extended_select)
                    self._key_current = prev

        # left arrow goes to the parent
        elif keyCode == wx.WXK_LEFT:

            prev = self.GetItemParent(self._current)
            if prev == self.GetRootItem() and self.HasAGWFlag(TR_HIDE_ROOT):
                # don't go to root if it is hidden
                prev = self.GetPrevSibling(self._current)

            if self.IsExpanded(self._current):
                self.Collapse(self._current)
            else:
                if prev and self.IsItemEnabled(prev):
                    self.DoSelectItem(prev, unselect_others, extended_select)

        elif keyCode == wx.WXK_RIGHT:
            # this works the same as the down arrow except that we
            # also expand the item if it wasn't expanded yet
            if self.IsExpanded(self._current) and self.HasChildren(self._current):
                child, cookie = self.GetFirstChild(self._key_current)
                if self.IsItemEnabled(child):
                    self.DoSelectItem(child, unselect_others, extended_select)
                    self._key_current = child
            else:
                self.Expand(self._current)
            # fall through

        elif keyCode == wx.WXK_DOWN:
            if self.IsExpanded(self._key_current) and self.HasChildren(self._key_current):

                child = self.GetNextActiveItem(self._key_current)

                if child:
                    self.DoSelectItem(child, unselect_others, extended_select)
                    self._key_current = child

            else:

                next = self.GetNextSibling(self._key_current)

                if not next:
                    current = self._key_current
                    while current and not next:
                        current = self.GetItemParent(current)
                        if current:
                            next = self.GetNextSibling(current)
                            if not next or not self.IsItemEnabled(next):
                                next = None

                else:
                    while next and not self.IsItemEnabled(next):
                        next = self.GetNext(next)

                if next:
                    self.DoSelectItem(next, unselect_others, extended_select)
                    self._key_current = next

        # <End> selects the last visible tree item
        elif keyCode == wx.WXK_END:

            last = self.GetRootItem()

            while last and self.IsExpanded(last):

                lastChild = self.GetLastChild(last)

                # it may happen if the item was expanded but then all of
                # its children have been deleted - so IsExpanded() returned
                # true, but GetLastChild() returned invalid item
                if not lastChild:
                    break

                last = lastChild

            if last and self.IsItemEnabled(last):

                self.DoSelectItem(last, unselect_others, extended_select)

        # <Home> selects the root item
        elif keyCode == wx.WXK_HOME:

            prev = self.GetRootItem()

            if not prev:
                return

            if self.HasAGWFlag(TR_HIDE_ROOT):
                prev, cookie = self.GetFirstChild(prev)
                if not prev:
                    return

            if self.IsItemEnabled(prev):
                self.DoSelectItem(prev, unselect_others, extended_select)

        else:

            if not event.HasModifiers() and ((keyCode >= ord('0') and keyCode <= ord('9')) or \
                                             (keyCode >= ord('a') and keyCode <= ord('z')) or \
                                             (keyCode >= ord('A') and keyCode <= ord('Z'))):

                # find the next item starting with the given prefix
                ch = chr(keyCode)
                id = self.FindItem(self._current, self._findPrefix + ch)

                if not id:
                    # no such item
                    return

                if self.IsItemEnabled(id):
                    self.SelectItem(id)
                self._findPrefix += ch

                # also start the timer to reset the current prefix if the user
                # doesn't press any more alnum keys soon -- we wouldn't want
                # to use this prefix for a new item search
                if not self._findTimer:
                    self._findTimer = TreeFindTimer(self)

                self._findTimer.Start(_DELAY, wx.TIMER_ONE_SHOT)

            else:

                event.Skip()

[docs]    def GetNextActiveItem(self, item, down=True):
        """
        Returns the next active item. Used Internally at present.

        :param `item`: an instance of L{GenericTreeItem};
        :param bool `down`: ``True`` to search downwards in the hierarchy for an active item,
         ``False`` to search upwards.

        :return: An instance of L{GenericTreeItem} if an active item has been found or
         ``None`` if none has been found.
        """

        if down:
            sibling = self.GetNextSibling
        else:
            sibling = self.GetPrevSibling

        if self.GetItemType(item) == 2 and not self.IsItemChecked(item):
            # Is an unchecked radiobutton... all its children are inactive
            # try to get the next/previous sibling
            found = 0

            while 1:
                child = sibling(item)
                if (child and self.IsItemEnabled(child)) or not child:
                    break
                item = child

        else:
            # Tha's not a radiobutton... but some of its children can be
            # inactive
            child, cookie = self.GetFirstChild(item)
            while child and not self.IsItemEnabled(child):
                child, cookie = self.GetNextChild(item, cookie)

        if child and self.IsItemEnabled(child):
            return child

        return None

[docs]    def HitTest(self, point, flags=0):
        """
        Calculates which (if any) item is under the given point, returning the tree item
        at this point plus extra information flags.

        :param `point`: an instance of `wx.Point`, a point to test for hits;
        :param integer `flags`: a bitlist of the following values:

         ================================== =============== =================================
         HitTest Flags                      Hex Value       Description
         ================================== =============== =================================
         ``TREE_HITTEST_ABOVE``                         0x1 Above the client area
         ``TREE_HITTEST_BELOW``                         0x2 Below the client area
         ``TREE_HITTEST_NOWHERE``                       0x4 No item has been hit
         ``TREE_HITTEST_ONITEMBUTTON``                  0x8 On the button associated to an item
         ``TREE_HITTEST_ONITEMICON``                   0x10 On the icon associated to an item
         ``TREE_HITTEST_ONITEMINDENT``                 0x20 On the indent associated to an item
         ``TREE_HITTEST_ONITEMLABEL``                  0x40 On the label (string) associated to an item
         ``TREE_HITTEST_ONITEM``                       0x50 Anywhere on the item
         ``TREE_HITTEST_ONITEMRIGHT``                  0x80 On the right of the label associated to an item
         ``TREE_HITTEST_TOLEFT``                      0x200 On the left of the client area
         ``TREE_HITTEST_TORIGHT``                     0x400 On the right of the client area
         ``TREE_HITTEST_ONITEMUPPERPART``             0x800 On the upper part (first half) of the item
         ``TREE_HITTEST_ONITEMLOWERPART``            0x1000 On the lower part (second half) of the item
         ``TREE_HITTEST_ONITEMCHECKICON``            0x2000 On the check/radio icon, if present
         ================================== =============== =================================

        :return: A tuple with the first value being an instance of L{GenericTreeItem} or ``None`` if
         no item has been hit-tested, and as second value an integer parameter `flag`.

        :note: both the item (if any, ``None`` otherwise) and the `flags` are always returned as a tuple.
        """

        w, h = self.GetSize()
        flags = 0

        if point.x < 0:
            flags |= TREE_HITTEST_TOLEFT
        if point.x > w:
            flags |= TREE_HITTEST_TORIGHT
        if point.y < 0:
            flags |= TREE_HITTEST_ABOVE
        if point.y > h:
            flags |= TREE_HITTEST_BELOW

        if flags:
            return None, flags

        if self._anchor == None:
            flags = TREE_HITTEST_NOWHERE
            return None, flags

        hit, flags = self._anchor.HitTest(self.CalcUnscrolledPosition(point), self, flags, 0)

        if hit == None:
            flags = TREE_HITTEST_NOWHERE
            return None, flags

        if not self.IsItemEnabled(hit):
            return None, flags

        return hit, flags

[docs]    def GetBoundingRect(self, item, textOnly=False):
        """
        Retrieves the rectangle bounding the item.

        :param `item`: an instance of L{GenericTreeItem};
        :param bool `textOnly`: if ``True``, only the rectangle around the item's label will
         be returned, otherwise the item's image is also taken into account.

        :return: An instance of `wx.Rect`.

        :note: The rectangle coordinates are logical, not physical ones. So, for example,
         the `x` coordinate may be negative if the tree has a horizontal scrollbar and its
         position is not ``0``.
        """

        i = item

        startX, startY = self.GetViewStart()
        rect = wx.Rect()

        rect.x = i.GetX() - startX*_PIXELS_PER_UNIT
        rect.y = i.GetY() - startY*_PIXELS_PER_UNIT
        rect.width = i.GetWidth()
        rect.height = self.GetLineHeight(i)

        return rect

[docs]    def Edit(self, item):
        """
        Internal function. Starts the editing of an item label, sending a
        ``EVT_TREE_BEGIN_LABEL_EDIT`` event.

        :param `item`: an instance of L{GenericTreeItem}.

        :warning: Separator-type items can not be edited.
        """

        if item.IsSeparator():
            return

        te = TreeEvent(wxEVT_TREE_BEGIN_LABEL_EDIT, self.GetId())
        te._item = item
        te.SetEventObject(self)
        if self.GetEventHandler().ProcessEvent(te) and not te.IsAllowed():
            # vetoed by user
            return

        # We have to call this here because the label in
        # question might just have been added and no screen
        # update taken place.
        if self._dirty:
            if wx.Platform in ["__WXMSW__", "__WXMAC__"]:
                self.Update()
            else:
                wx.YieldIfNeeded()

        if self._editCtrl != None and item != self._editCtrl.item():
            self._editCtrl.StopEditing()

        self._editCtrl = TreeTextCtrl(self, item=item)
        self._editCtrl.SetFocus()

[docs]    def GetEditControl(self):
        """
        Returns a pointer to the edit L{TreeTextCtrl} if the item is being edited or
        ``None`` otherwise (it is assumed that no more than one item may be edited
        simultaneously).
        """

        return self._editCtrl

[docs]    def OnAcceptEdit(self, item, value):
        """
        Called by L{TreeTextCtrl}, to accept the changes and to send the
        ``EVT_TREE_END_LABEL_EDIT`` event.

        :param `item`: an instance of L{GenericTreeItem};
        :param string `value`: the new value of the item label.

        :return: ``True`` if the editing has not been vetoed, ``False`` otherwise.
        """

        le = TreeEvent(wxEVT_TREE_END_LABEL_EDIT, self.GetId())
        le._item = item
        le.SetEventObject(self)
        le._label = value
        le._editCancelled = False

        return not self.GetEventHandler().ProcessEvent(le) or le.IsAllowed()

[docs]    def OnCancelEdit(self, item):
        """
        Called by L{TreeTextCtrl}, to cancel the changes and to send the
        ``EVT_TREE_END_LABEL_EDIT`` event.

        :param `item`: an instance of L{GenericTreeItem}.
        """

        # let owner know that the edit was cancelled
        le = TreeEvent(wxEVT_TREE_END_LABEL_EDIT, self.GetId())
        le._item = item
        le.SetEventObject(self)
        le._label = ""
        le._editCancelled = True

        self.GetEventHandler().ProcessEvent(le)

[docs]    def OnEditTimer(self):
        """ The timer for editing has expired. Start editing. """

        self.Edit(self._current)

[docs]    def OnMouse(self, event):
        """
        Handles a bunch of ``wx.EVT_MOUSE_EVENTS`` events for L{CustomTreeCtrl}.

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

        if not self._anchor:
            return

        pt = self.CalcUnscrolledPosition(event.GetPosition())

        # Is the mouse over a tree item button?
        flags = 0
        thisItem, flags = self._anchor.HitTest(pt, self, flags, 0)
        underMouse = thisItem
        underMouseChanged = underMouse != self._underMouse

        if underMouse and (flags & TREE_HITTEST_ONITEM) and not event.LeftIsDown() and \
           not self._isDragging and (not self._editTimer or not self._editTimer.IsRunning()):
            underMouse = underMouse
        else:
            underMouse = None

        if underMouse != self._underMouse:
            if self._underMouse:
                # unhighlight old item
                self._underMouse = None

            self._underMouse = underMouse

        # Determines what item we are hovering over and need a tooltip for
        hoverItem = thisItem

        # We do not want a tooltip if we are dragging, or if the edit timer is running
        if underMouseChanged and not self._isDragging and (not self._editTimer or not self._editTimer.IsRunning()):

            if hoverItem is not None:
                # Ask the tree control what tooltip (if any) should be shown
                hevent = TreeEvent(wxEVT_TREE_ITEM_GETTOOLTIP, self.GetId())
                hevent._item = hoverItem
                hevent.SetEventObject(self)

                if self.GetEventHandler().ProcessEvent(hevent) and hevent.IsAllowed():
                    self.SetToolTip(hevent._label)

                elif self.HasAGWFlag(TR_TOOLTIP_ON_LONG_ITEMS):

                    tip = self.GetToolTipString()

                    if hoverItem.IsSeparator():
                        if tip:
                            self.SetToolTipString('')
                    else:
                        maxsize = self.GetItemSize(hoverItem)
                        itemText = hoverItem.GetText()

                        dc = wx.ClientDC(self)

                        if dc.GetMultiLineTextExtent(itemText)[0] > maxsize:
                            if tip != itemText:
                                self.SetToolTipString(itemText)
                        else:
                            if tip:
                                self.SetToolTipString('')

                if hoverItem.IsHyperText() and (flags & TREE_HITTEST_ONITEMLABEL) and hoverItem.IsEnabled():
                    self.SetCursor(wx.StockCursor(wx.CURSOR_HAND))
                    self._isonhyperlink = True
                else:
                    if self._isonhyperlink:
                        self.SetCursor(wx.StockCursor(wx.CURSOR_ARROW))
                        self._isonhyperlink = False

        # we process left mouse up event (enables in-place edit), right down
        # (pass to the user code), left dbl click (activate item) and
        # dragging/moving events for items drag-and-drop

        if not (event.LeftDown() or event.LeftUp() or event.RightDown() or event.LeftDClick() or \
                event.Dragging() or ((event.Moving() or event.RightUp()) and self._isDragging)):

            event.Skip()
            return

        flags = 0
        item, flags = self._anchor.HitTest(pt, self, flags, 0)

        if event.Dragging() and not self._isDragging and ((flags & TREE_HITTEST_ONITEMICON) or (flags & TREE_HITTEST_ONITEMLABEL)):

            if self._dragCount == 0:
                self._dragStart = pt

            self._countDrag = 0
            self._dragCount = self._dragCount + 1

            if self._dragCount != 3:
                # wait until user drags a bit further...
                return

            command = (event.RightIsDown() and [wxEVT_TREE_BEGIN_RDRAG] or [wxEVT_TREE_BEGIN_DRAG])[0]

            nevent = TreeEvent(command, self.GetId())
            nevent._item = self._current
            nevent.SetEventObject(self)
            newpt = self.CalcScrolledPosition(pt)
            nevent.SetPoint(newpt)

            # by default the dragging is not supported, the user code must
            # explicitly allow the event for it to take place
            nevent.Veto()

            if self.GetEventHandler().ProcessEvent(nevent) and nevent.IsAllowed():

                # we're going to drag this item
                self._isDragging = True

                # remember the old cursor because we will change it while
                # dragging
                self._oldCursor = self._cursor

                # in a single selection control, hide the selection temporarily
                if not (self.GetAGWWindowStyleFlag() & TR_MULTIPLE):
                    self._oldSelection = self.GetSelection()

                    if self._oldSelection:

                        self._oldSelection.SetHilight(False)
                        self.RefreshLine(self._oldSelection)
                else:
                    selections = self.GetSelections()
                    if len(selections) == 1:
                        self._oldSelection = selections[0]
                        self._oldSelection.SetHilight(False)
                        self.RefreshLine(self._oldSelection)

                if self._dragImage:
                    del self._dragImage

                # Create the custom draw image from the icons and the text of the item
                self._dragImage = DragImage(self, self._current)
                self._dragImage.BeginDrag(wx.Point(0,0), self)
                self._dragImage.Show()
                self._dragImage.Move(self.CalcScrolledPosition(pt))

        elif event.Dragging() and self._isDragging:

            self._dragImage.Move(self.CalcScrolledPosition(pt))

            if self._countDrag == 0 and item:
                self._oldItem = item

            if item != self._dropTarget:

                # unhighlight the previous drop target
                if self._dropTarget:
                    self._dropTarget.SetHilight(False)
                    self.RefreshLine(self._dropTarget)
                if item:
                    item.SetHilight(True)
                    self.RefreshLine(item)
                    self._countDrag = self._countDrag + 1
                self._dropTarget = item

                self.Update()

            if self._countDrag >= 3:
                # Here I am trying to avoid ugly repainting problems... hope it works
                self.RefreshLine(self._oldItem)
                self._countDrag = 0

        elif (event.LeftUp() or event.RightUp()) and self._isDragging:

            if self._dragImage:
                self._dragImage.EndDrag()

            if self._dropTarget:
                self._dropTarget.SetHilight(False)

            if self._oldSelection:

                self._oldSelection.SetHilight(True)
                self.RefreshLine(self._oldSelection)
                self._oldSelection = None

            # generate the drag end event
            event = TreeEvent(wxEVT_TREE_END_DRAG, self.GetId())
            event._item = item
            event._pointDrag = self.CalcScrolledPosition(pt)
            event.SetEventObject(self)

            self.GetEventHandler().ProcessEvent(event)

            self._isDragging = False
            self._dropTarget = None

            self.SetCursor(self._oldCursor)

            if wx.Platform in ["__WXMSW__", "__WXMAC__"]:
                self.Refresh()
            else:
                # Probably this is not enough on GTK. Try a Refresh() if it does not work.
                wx.YieldIfNeeded()

        else:

            # If we got to this point, we are not dragging or moving the mouse.
            # Because the code in carbon/toplevel.cpp will only set focus to the tree
            # if we skip for EVT_LEFT_DOWN, we MUST skip this event here for focus to work.
            # We skip even if we didn't hit an item because we still should
            # restore focus to the tree control even if we didn't exactly hit an item.
            if event.LeftDown():
                self._hasFocus = True
                self.SetFocusIgnoringChildren()
                event.Skip()

            # here we process only the messages which happen on tree items

            self._dragCount = 0

            if item == None:
                if self._editCtrl != None and item != self._editCtrl.item():
                    self._editCtrl.StopEditing()
                return  # we hit the blank area

            if event.RightDown():

                if self._editCtrl != None and item != self._editCtrl.item():
                    self._editCtrl.StopEditing()

                self._hasFocus = True
                self.SetFocusIgnoringChildren()

                # If the item is already selected, do not update the selection.
                # Multi-selections should not be cleared if a selected item is clicked.
                if not self.IsSelected(item):

                    self.DoSelectItem(item, True, False)

                nevent = TreeEvent(wxEVT_TREE_ITEM_RIGHT_CLICK, self.GetId())
                nevent._item = item
                nevent._pointDrag = self.CalcScrolledPosition(pt)
                nevent.SetEventObject(self)
                event.Skip(not self.GetEventHandler().ProcessEvent(nevent))

                # Consistent with MSW (for now), send the ITEM_MENU *after*
                # the RIGHT_CLICK event. TODO: This behaviour may change.
                nevent2 = TreeEvent(wxEVT_TREE_ITEM_MENU, self.GetId())
                nevent2._item = item
                nevent2._pointDrag = self.CalcScrolledPosition(pt)
                nevent2.SetEventObject(self)
                self.GetEventHandler().ProcessEvent(nevent2)

            elif event.LeftUp():

                # this facilitates multiple-item drag-and-drop

                if self.HasAGWFlag(TR_MULTIPLE):

                    selections = self.GetSelections()

                    if len(selections) > 1 and not event.CmdDown() and not event.ShiftDown():

                        self.DoSelectItem(item, True, False)

                if self._lastOnSame:

                    if item == self._current and (flags & TREE_HITTEST_ONITEMLABEL) and self.HasAGWFlag(TR_EDIT_LABELS):

                        if self._editTimer:

                            if self._editTimer.IsRunning():

                                self._editTimer.Stop()

                        else:

                            self._editTimer = TreeEditTimer(self)

                        self._editTimer.Start(_DELAY, True)

                    self._lastOnSame = False

            else: # !RightDown() && !LeftUp() ==> LeftDown() || LeftDClick()

                if not item or not item.IsEnabled():
                    if self._editCtrl != None and item != self._editCtrl.item():
                        self._editCtrl.StopEditing()
                    return

                if self._editCtrl != None and item != self._editCtrl.item():
                    self._editCtrl.StopEditing()

                self._hasFocus = True
                self.SetFocusIgnoringChildren()

                if event.LeftDown():

                    self._lastOnSame = item == self._current

                if flags & TREE_HITTEST_ONITEMBUTTON:

                    # only toggle the item for a single click, double click on
                    # the button doesn't do anything (it toggles the item twice)
                    if event.LeftDown():

                        self.Toggle(item)

                    # don't select the item if the button was clicked
                    return

                if item.GetType() > 0 and (flags & TREE_HITTEST_ONITEMCHECKICON):

                    if event.LeftDown():
                        if flags & TREE_HITTEST_ONITEM and self.HasAGWFlag(TR_FULL_ROW_HIGHLIGHT):
                            self.DoSelectItem(item, not self.HasAGWFlag(TR_MULTIPLE))

                        if self.IsItem3State(item):
                            checked = self.GetItem3StateValue(item)
                            checked = (checked+1)%3
                        else:
                            checked = not self.IsItemChecked(item)

                        self.CheckItem(item, checked)

                    return

                # clear the previously selected items, if the
                # user clicked outside of the present selection.
                # otherwise, perform the deselection on mouse-up.
                # this allows multiple drag and drop to work.
                # but if Cmd is down, toggle selection of the clicked item
                if not self.IsSelected(item) or event.CmdDown():

                    if flags & TREE_HITTEST_ONITEM:
                        # how should the selection work for this event?
                        if item.IsHyperText():
                            self.SetItemVisited(item, True)

                        is_multiple, extended_select, unselect_others = EventFlagsToSelType(self.GetAGWWindowStyleFlag(),
                                                                                event.ShiftDown(),
                                                                                event.CmdDown())

                        self.DoSelectItem(item, unselect_others, extended_select)

                # Handle hyperlink items... which are a bit odd sometimes
                elif self.IsSelected(item) and item.IsHyperText():
                    self.HandleHyperLink(item)

                # For some reason, Windows isn't recognizing a left double-click,
                # so we need to simulate it here.  Allow 200 milliseconds for now.
                if event.LeftDClick():

                    # double clicking should not start editing the item label
                    if self._editTimer:
                        self._editTimer.Stop()

                    self._lastOnSame = False

                    # send activate event first
                    nevent = TreeEvent(wxEVT_TREE_ITEM_ACTIVATED, self.GetId())
                    nevent._item = item
                    nevent._pointDrag = self.CalcScrolledPosition(pt)
                    nevent.SetEventObject(self)
                    if not self.GetEventHandler().ProcessEvent(nevent):

                        # if the user code didn't process the activate event,
                        # handle it ourselves by toggling the item when it is
                        # double clicked
##                        if item.HasPlus():
                        self.Toggle(item)

[docs]    def OnInternalIdle(self):
        """
        This method is normally only used internally, but sometimes an application
        may need it to implement functionality that should not be disabled by an
        application defining an `OnIdle` handler in a derived class.

        This method may be used to do delayed painting, for example, and most
        implementations call `wx.Window.UpdateWindowUI` in order to send update events
        to the window in idle time.
        """

        # Check if we need to select the root item
        # because nothing else has been selected.
        # Delaying it means that we can invoke event handlers
        # as required, when a first item is selected.
        if not self.HasAGWFlag(TR_MULTIPLE) and not self.GetSelection():

            if self._select_me:
                self.SelectItem(self._select_me)
            elif self.GetRootItem():
                self.SelectItem(self.GetRootItem())

        # after all changes have been done to the tree control,
        # we actually redraw the tree when everything is over

        if not self._dirty:
            return
        if self._freezeCount:
            return

        self._dirty = False

        self.CalculatePositions()
        self.Refresh()
        self.AdjustMyScrollbars()

#        event.Skip()

[docs]    def CalculateSize(self, item, dc, level=-1, align=0):
        """
        Calculates overall position and size of an item.

        :param `item`: an instance of L{GenericTreeItem};
        :param `dc`: an instance of `wx.DC`;
        :param integer `level`: the item level in the tree hierarchy;
        :param integer `align`: an integer specifying the alignment type:

         =============== =========================================
         `align` Value   Description
         =============== =========================================
                0        No horizontal alignment of windows (in items with windows).
                1        Windows (in items with windows) are aligned at the same horizontal position.
                2        Windows (in items with windows) are aligned at the rightmost edge of L{CustomTreeCtrl}.
         =============== =========================================

        """

        attr = item.GetAttributes()

        if attr and attr.HasFont():
            dc.SetFont(attr.GetFont())
        else:
            if item.IsBold():
                dc.SetFont(self._boldFont)
            elif item.IsItalic():
                dc.SetFont(self._italicFont)
            else:
                dc.SetFont(self._normalFont)

        text_w, text_h, dummy = dc.GetMultiLineTextExtent(item.GetText())
        text_h+=2

        # restore normal font
        dc.SetFont(self._normalFont)

        image_w, image_h = 0, 0
        image = item.GetCurrentImage()

        if image != _NO_IMAGE:

            if self._imageListNormal:

                image_w, image_h = self._imageListNormal.GetSize(image)
                image_w += 4

        total_h = ((image_h > text_h) and [image_h] or [text_h])[0]

        checkimage = item.GetCurrentCheckedImage()
        if checkimage is not None:
            wcheck, hcheck = self._imageListCheck.GetSize(checkimage)
            wcheck += 4
        else:
            wcheck = 0

        if total_h < 30:
            total_h += 2            # at least 2 pixels
        else:
            total_h += total_h/10   # otherwise 10% extra spacing

        if total_h > self._lineHeight:
            self._lineHeight = total_h

        wnd = item.GetWindow()
        if not wnd:
            totalWidth = image_w+text_w+wcheck+2
            totalHeight = total_h
        else:
            totalWidth = item.GetWindowSize()[0]+image_w+text_w+wcheck+2
            totalHeight = max(total_h, item.GetWindowSize()[1])

        if level >= 0 and wnd:
            if align == 0:
                if level in self.absoluteWindows:
                    self.absoluteWindows[level] = max(self.absoluteWindows[level], image_w+text_w+wcheck+2)
                else:
                    self.absoluteWindows[level] = image_w+text_w+wcheck+2
            elif align == 1:
                self.absoluteWindows[level] = max(self.absoluteWindows[level], image_w+text_w+wcheck+2)

        if item.IsSeparator():
            totalWidth = self.GetClientSize()[0]
            totalHeight = total_h

        item.SetWidth(totalWidth)
        item.SetHeight(totalHeight)

[docs]    def CalculateLevel(self, item, dc, level, y, align=0):
        """
        Calculates the level of an item inside the tree hierarchy.

        :param `item`: an instance of L{GenericTreeItem};
        :param `dc`: an instance of `wx.DC`;
        :param integer `level`: the item level in the tree hierarchy;
        :param integer `y`: the current vertical position inside the `wx.PyScrolledWindow`;
        :param integer `align`: an integer specifying the alignment type:

         =============== =========================================
         `align` Value   Description
         =============== =========================================
                0        No horizontal alignment of windows (in items with windows).
                1        Windows (in items with windows) are aligned at the same horizontal position.
                2        Windows (in items with windows) are aligned at the rightmost edge of L{CustomTreeCtrl}.
         =============== =========================================

        :return: The new `y` vertical position inside the `wx.PyScrolledWindow`.
        """

        x = level*self._indent

        if not self.HasAGWFlag(TR_HIDE_ROOT):

            x += self._indent

        elif level == 0:

            # a hidden root is not evaluated, but its
            # children are always calculated
            children = item.GetChildren()
            count = len(children)
            level = level + 1
            for n in xrange(count):
                y = self.CalculateLevel(children[n], dc, level, y, align)  # recurse

            return y

        self.CalculateSize(item, dc, level, align)

        # set its position
        item.SetX(x+self._spacing)
        item.SetY(y)
        y += self.GetLineHeight(item)

        if not item.IsExpanded():
            # we don't need to calculate collapsed branches
            return y

        children = item.GetChildren()
        count = len(children)
        level = level + 1
        for n in xrange(count):
            y = self.CalculateLevel(children[n], dc, level, y, align)  # recurse

        return y

[docs]    def CalculatePositions(self):
        """ Calculates all the positions of the visible items. """

        if not self._anchor:
            return

        self.absoluteWindows = {}

        dc = wx.ClientDC(self)
        self.PrepareDC(dc)

        dc.SetFont(self._normalFont)
        dc.SetPen(self._dottedPen)
        y = 2
        y = self.CalculateLevel(self._anchor, dc, 0, y) # start recursion

        if self.HasAGWFlag(TR_ALIGN_WINDOWS) or self.HasAGWFlag(TR_ALIGN_WINDOWS_RIGHT):
            align = (self.HasAGWFlag(TR_ALIGN_WINDOWS) and [1] or [2])[0]
            y = 2
            y = self.CalculateLevel(self._anchor, dc, 0, y, align) # start recursion

[docs]    def RefreshSubtree(self, item):
        """
        Refreshes a damaged subtree of an item.

        :param `item`: an instance of L{GenericTreeItem}.
        """

        if self._dirty:
            return
        if self._freezeCount:
            return

        client = self.GetClientSize()

        rect = wx.Rect()
        x, rect.y = self.CalcScrolledPosition(0, item.GetY())
        rect.width = client.x
        rect.height = client.y

        self.Refresh(True, rect)
        self.AdjustMyScrollbars()

[docs]    def RefreshLine(self, item):
        """
        Refreshes a damaged item line.

        :param `item`: an instance of L{GenericTreeItem}.
        """

        if self._dirty:
            return
        if self._freezeCount:
            return

        rect = wx.Rect()
        x, rect.y = self.CalcScrolledPosition(0, item.GetY())
        rect.width = self.GetClientSize().x
        rect.height = self.GetLineHeight(item)

        self.Refresh(True, rect)

[docs]    def RefreshSelected(self):
        """ Refreshes a damaged selected item line. """

        if self._freezeCount:
            return

        # TODO: this is awfully inefficient, we should keep the list of all
        #       selected items internally, should be much faster
        if self._anchor:
            self.RefreshSelectedUnder(self._anchor)

[docs]    def RefreshSelectedUnder(self, item):
        """
        Refreshes the selected items under the given item.

        :param `item`: an instance of L{GenericTreeItem}.
        """

        if self._freezeCount:
            return

        if item.IsSelected():
            self.RefreshLine(item)

        children = item.GetChildren()
        for child in children:
            self.RefreshSelectedUnder(child)

[docs]    def RefreshItemWithWindows(self, item=None):
        """
        Refreshes the items with which a window is associated.

        :param `item`: an instance of L{GenericTreeItem}. If `item` is ``None``, then the
         recursive refresh starts from the root node.

        :note: This method is called only if the style ``TR_ALIGN_WINDOWS_RIGHT`` is used.
        """

        if self._freezeCount:
            return

        if item is None:
            if self._anchor:
                self.RefreshItemWithWindows(self._anchor)
                return

        wnd = item.GetWindow()
        if wnd and wnd.IsShown():
            self.RefreshLine(item)

        children = item.GetChildren()
        for child in children:
            self.RefreshItemWithWindows(child)

[docs]    def Freeze(self):
        """
        Freeze L{CustomTreeCtrl}.

        Freezes the window or, in other words, prevents any updates from taking place
        on screen, the window is not redrawn at all. L{Thaw} must be called to reenable
        window redrawing. Calls to these two functions may be nested.

        :note: This method is useful for visual appearance optimization (for example,
         it is a good idea to use it before doing many large text insertions in a row
         into a `wx.TextCtrl` under wxGTK) but is not implemented on all platforms nor
         for all controls so it is mostly just a hint to wxWidgets and not a mandatory
         directive.
        """

        self._freezeCount = self._freezeCount + 1

[docs]    def Thaw(self):
        """
        Thaw L{CustomTreeCtrl}.

        Reenables window updating after a previous call to L{Freeze}. To really thaw the
        control, it must be called exactly the same number of times as L{Freeze}.

        :raise: `Exception` if L{Thaw} has been called without an un-matching L{Freeze}.
        """

        if self._freezeCount == 0:
            raise Exception("\nERROR: Thawing Unfrozen Tree Control?")

        self._freezeCount = self._freezeCount - 1

        if not self._freezeCount:
            self.Refresh()

    # ----------------------------------------------------------------------------
    # changing colours: we need to refresh the tree control
    # ----------------------------------------------------------------------------

[docs]    def SetBackgroundColour(self, colour):
        """
        Changes the background colour of L{CustomTreeCtrl}.

        :param `colour`: the colour to be used as the background colour, pass
         `wx.NullColour` to reset to the default colour.

        :return: ``False`` if the underlying `wx.PyScrolledWindow` does not accept
         the new colour, ``True`` otherwise.

        :note: The background colour is usually painted by the default `wx.EraseEvent`
         event handler function under Windows and automatically under GTK.

        :note: Setting the background colour does not cause an immediate refresh, so
         you may wish to call `wx.Window.ClearBackground` or `wx.Window.Refresh` after
         calling this function.

        :note: Overridden from `wx.PyScrolledWindow`.
        """

        if not wx.PyScrolledWindow.SetBackgroundColour(self, colour):
            return False

        if self._freezeCount:
            return True

        self.Refresh()

        return True

[docs]    def SetForegroundColour(self, colour):
        """
        Changes the foreground colour of L{CustomTreeCtrl}.

        :param `colour`: the colour to be used as the foreground colour, pass
         `wx.NullColour` to reset to the default colour.

        :return: ``False`` if the underlying `wx.PyScrolledWindow` does not accept
         the new colour, ``True`` otherwise.

        :note: Overridden from `wx.PyScrolledWindow`.
        """

        if not wx.PyScrolledWindow.SetForegroundColour(self, colour):
            return False

        if self._freezeCount:
            return True

        self.Refresh()

        return True

[docs]    def OnGetToolTip(self, event):
        """
        Process the tooltip event, to speed up event processing. Does not actually
        get a tooltip.

        :param `event`: a L{TreeEvent} event to be processed.
        """

        event.Veto()

[docs]    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 `wx.Size`.

        :note: Overridden from `wx.PyScrolledWindow`.
        """

        # something is better than nothing...
        # 100x80 is what the MSW version will get from the default
        # wxControl::DoGetBestSize

        return wx.Size(100, 80)

[docs]    def GetMaxWidth(self, respect_expansion_state=True):
        """
        Returns the maximum width of the L{CustomTreeCtrl}.

        :param bool `respect_expansion_state`: if ``True``, only the expanded items (and their
         children) will be measured. Otherwise all the items are expanded and
         their width measured.

        :return: the maximum width of L{CustomTreeCtrl}, in pixels.
        """

        self.Freeze()

        root = self.GetRootItem()
        rect = self.GetBoundingRect(root, True)

        # It looks like the space between the "+" and the node
        # rect occupies 4 pixels approximatively
        maxwidth = rect.x + rect.width + 4
        lastheight = rect.y + rect.height

        if not self.IsExpanded(root):
            if respect_expansion_state:
                return maxwidth

        if not respect_expansion_state:
            self.ExpandAll()

        maxwidth, lastheight = self.RecurseOnChildren(root, maxwidth, respect_expansion_state)

        self.Thaw()

        return maxwidth

[docs]    def RecurseOnChildren(self, item, maxwidth, respect_expansion_state):
        """
        Recurses over all the children of the spcified items, calculating their
        maximum width.

        :param `item`: an instance of L{GenericTreeItem};
        :param integer `maxwidth`: the current maximum width for L{CustomTreeCtrl}, in pixels;
        :param bool `respect_expansion_state`: if ``True``, only the expanded items (and their
         children) will be measured. Otherwise all the items are expanded and
         their width measured.

        :return: A tuple containing the maximum width and item height, in pixels.
        """

        child, cookie = self.GetFirstChild(item)
        lastheight = 0

        while child:

            rect = self.GetBoundingRect(child, True)

            # It looks like the space between the "+" and the node
            # rect occupies 4 pixels approximatively
            maxwidth = max(maxwidth, rect.x + rect.width + 4)
            lastheight = rect.y + rect.height

            if self.IsExpanded(child) or not respect_expansion_state:
                maxwidth, lastheight = self.RecurseOnChildren(child, maxwidth, respect_expansion_state)

            child, cookie = self.GetNextChild(item, cookie)

        return maxwidth, lastheight

[docs]    def GetClassDefaultAttributes(self):
        """
        Returns the default font and colours which are used by the control. This is
        useful if you want to use the same font or colour in your own control as in
        a standard control -- which is a much better idea than hard coding specific
        colours or fonts which might look completely out of place on the users system,
        especially if it uses themes.

        This static method is "overridden'' in many derived classes and so calling,
        for example, `wx.Button.GetClassDefaultAttributes()` will typically return the
        values appropriate for a button which will be normally different from those
        returned by, say, `wx.ListCtrl.GetClassDefaultAttributes()`.

        :return: An instance of `wx.VisualAttributes`.

        :note: The `wx.VisualAttributes` structure has at least the fields `font`,
         `colFg` and `colBg`. All of them may be invalid if it was not possible to
         determine the default control appearance or, especially for the background
         colour, if the field doesn't make sense as is the case for `colBg` for the
         controls with themed background.

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

        attr = wx.VisualAttributes()
        attr.colFg = wx.SystemSettings_GetColour(wx.SYS_COLOUR_WINDOWTEXT)
        attr.colBg = wx.SystemSettings_GetColour(wx.SYS_COLOUR_LISTBOX)
        attr.font  = wx.SystemSettings_GetFont(wx.SYS_DEFAULT_GUI_FONT)
        return attr

    GetClassDefaultAttributes = classmethod(GetClassDefaultAttributes)

Navigation

  • index
  • modules |
  • Home |
  • Gallery |
  • Contents»
  • Module code »
  • customtreectrl


flatmenu

  • modules |
  • Home |
  • Gallery |
  • Contents»
  • Module code »
  • flatmenu

Source code for flatmenu

# --------------------------------------------------------------------------------- #
# FLATMENU wxPython IMPLEMENTATION
#
# Andrea Gavana, @ 03 Nov 2006
# Latest Revision: 07 Mar 2012, 21.00 GMT
#
# TODO List
#
# 1. Work is still in progress, so other functionalities may be added in the future;
# 2. No shadows under MAC, but it may be possible to create them using Carbon.
#
#
# For All Kind Of Problems, Requests Of Enhancements And Bug Reports, Please
# Write To Me At:
#
# andrea.gavana@maerskoil.com
# andrea.gavana@gmail.com
#
# Or, Obviously, To The wxPython Mailing List!!!
#
#
# End Of Comments
# --------------------------------------------------------------------------------- #

"""
L{FlatMenu} is a generic menu implementation.

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

L{FlatMenu}, like the name implies, it is a generic menu implementation.
I tried to provide a full functionality for menus, menubar and toolbar.

L{FlatMenu} supports the following features:

- Fires all the events (UI & Cmd);
- Check items;
- Separators;
- Enabled / Disabled menu items;
- Images on items;
- Toolbar support, with images and separators;
- Controls in toolbar (work in progress);
- Toolbar tools tooltips (done: thanks to Peter Kort);
- Accelerators for menus;
- Accelerators for menubar;
- Radio items in menus;
- Integration with AUI;
- Scrolling when menu is too big to fit the screen;
- Menu navigation with keyboard;
- Drop down arrow button to the right of the menu, it always contains the
  "Customize" option, which will popup an options dialog. The dialog has the
  following abilities:

  (a) Ability to add/remove menus;
  (b) Select different colour schemes for the menu bar / toolbar;
  (c) Control various options, such as: colour for highlight menu item, draw
      border around menus (classic look only);
  (d) Toolbar floating appearance.

- Allows user to specify grey bitmap for disabled menus/toolbar tools;
- If no grey bitmap is provided, it generates one from the existing bitmap;
- Hidden toolbar items / menu bar items - will appear in a small popmenu
  to the right if they are hidden;
- 4 different colour schemes for the menu bar (more can easily added);
- Scrolling is available if the menu height is greater than the screen height;
- Context menus for menu items;
- Show/hide the drop down arrow which allows the customization of L{FlatMenu};
- Multiple columns menu window;
- Tooltips for menus and toolbar items on a `wx.StatusBar` (if present);
- Transparency (alpha channel) for menu windows (for platforms supporting it);
- FileHistory support through a pure-Python `wx.FileHistory` implementation;
- Possibility to set a background bitmap for a L{FlatMenu};
- First attempt in adding controls to FlatToolbar;
- Added a MiniBar (thanks to Vladiuz);
- Added `wx.ToolBar` methods AddCheckTool/AddRadioTool (thanks to Vladiuz).

Usage
=====

Usage example::

    import wx
    import wx.lib.agw.flatmenu as FM

    class MyFrame(wx.Frame):

        def __init__(self, parent):

            wx.Frame.__init__(self, parent, -1, "FlatMenu Demo")

            self.CreateMenu()

            panel = wx.Panel(self, -1)
            btn = wx.Button(panel, -1, "Hello", (15, 12), (100, 120))

            main_sizer = wx.BoxSizer(wx.VERTICAL)
            main_sizer.Add(self.menubar, 0, wx.EXPAND)
            main_sizer.Add(panel, 1, wx.EXPAND)

            self.SetSizer(main_sizer)
            main_sizer.Layout()

        def CreateMenu(self):

            self.menubar = FM.FlatMenuBar(self, -1)

            f_menu = FM.FlatMenu()
            e_menu = FM.FlatMenu()
            v_menu = FM.FlatMenu()
            t_menu = FM.FlatMenu()
            w_menu = FM.FlatMenu()

            # Append the menu items to the menus
            f_menu.Append(-1, "Simple\tCtrl+N", "Text", None)
            e_menu.Append(-1, "FlatMenu", "Text", None)
            v_menu.Append(-1, "Example", "Text", None)
            t_menu.Append(-1, "Hello", "Text", None)
            w_menu.Append(-1, "World", "Text", None)

            # Append menus to the menubar
            self.menubar.Append(f_menu, "&File")
            self.menubar.Append(e_menu, "&Edit")
            self.menubar.Append(v_menu, "&View")
            self.menubar.Append(t_menu, "&Options")
            self.menubar.Append(w_menu, "&Help")

    # our normal wxApp-derived class, as usual

    app = wx.PySimpleApp()

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

    app.MainLoop()

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

L{FlatMenu} has been tested on the following platforms:
  * Windows (Windows XP, Vista);
  * Linux Ubuntu (Dapper 6.06)

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

This class supports the following window styles:

========================= =========== ==================================================
Window Styles             Hex Value   Description
========================= =========== ==================================================
``FM_OPT_IS_LCD``                 0x1 Use this style if your computer uses a LCD screen.
``FM_OPT_MINIBAR``                0x2 Use this if you plan to use the toolbar only.
``FM_OPT_SHOW_CUSTOMIZE``         0x4 Show "customize link" in the `More` menu, you will need to write your own handler. See demo.
``FM_OPT_SHOW_TOOLBAR``           0x8 Set this option is you are planning to use the toolbar.
========================= =========== ==================================================

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

This class processes the following events:

================================= ==================================================
Event Name                        Description
================================= ==================================================
``EVT_FLAT_MENU_DISMISSED``       Used internally.
``EVT_FLAT_MENU_ITEM_MOUSE_OUT``  Fires an event when the mouse leaves a L{FlatMenuItem}.
``EVT_FLAT_MENU_ITEM_MOUSE_OVER`` Fires an event when the mouse enters a L{FlatMenuItem}.
``EVT_FLAT_MENU_SELECTED``        Fires the `wx.EVT_MENU` event for L{FlatMenu}.
================================= ==================================================

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

L{FlatMenu} is distributed under the wxPython license.

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

Version 1.0

"""

__docformat__ = "epytext"
__version__ = "1.0"

import wx
import os
import math
import cStringIO

import wx.lib.colourutils as colourutils

from fmcustomizedlg import FMCustomizeDlg
from artmanager import ArtManager, DCSaver
from fmresources import *

# FlatMenu styles
FM_OPT_IS_LCD = 1
""" Use this style if your computer uses a LCD screen. """
FM_OPT_MINIBAR = 2
""" Use this if you plan to use the toolbar only. """
FM_OPT_SHOW_CUSTOMIZE = 4
""" Show "customize link" in the `More` menu, you will need to write your own handler. See demo. """
FM_OPT_SHOW_TOOLBAR = 8
""" Set this option is you are planning to use the toolbar. """

# Some checking to see if we can draw shadows behind the popup menus
# at least on Windows. *REQUIRES* Mark Hammond's win32all extensions
# and ctypes, on Windows obviouly. Mac and GTK have no shadows under
# the menus, and it has been reported that shadows don't work well
# on Windows 2000 and previous.

_libimported = None
_DELAY = 5000

# Define a translation string
_ = wx.GetTranslation

if wx.Platform == "__WXMSW__":
    osVersion = wx.GetOsVersion()
    # Shadows behind menus are supported only in XP
    if osVersion[1] == 5 and osVersion[2] == 1:
        try:
            import win32api
            import win32gui
            _libimported = "MH"
        except:
            try:
                import ctypes
                _libimported = "ctypes"
            except:
                pass
    else:
        _libimported = None

# Simple hack, but I don't know how to make it work on Mac
# I don't have  Mac ;-)
#if wx.Platform == "__WXMAC__":
#    try:
#        import ctypes
#        _carbon_dll = ctypes.cdll.LoadLibrary(r'/System/Frameworks/Carbon.framework/Carbon')
#    except:
#        _carbon_dll = None

# FIXME: No way to get shadows on Windows with the original code...
# May anyone share some suggestion on how to make it work??
# Right now I am using win32api to create shadows behind wx.PopupWindow,
# but this will result in *all* the popup windows in an application
# to have shadows behind them, even the user defined wx.PopupWindow
# that do not derive from FlatMenu.

import wx.aui as AUI
AuiPaneInfo = AUI.AuiPaneInfo

try:
    import aui as PyAUI
    PyAuiPaneInfo = PyAUI.AuiPaneInfo
except ImportError:
    pass

# Check for the new method in 2.7 (not present in 2.6.3.3)
if wx.VERSION_STRING < "2.7":
    wx.Rect.Contains = lambda self, point: wx.Rect.Inside(self, point)

wxEVT_FLAT_MENU_DISMISSED = wx.NewEventType()
wxEVT_FLAT_MENU_SELECTED = wx.wxEVT_COMMAND_MENU_SELECTED
wxEVT_FLAT_MENU_ITEM_MOUSE_OVER = wx.NewEventType()
wxEVT_FLAT_MENU_ITEM_MOUSE_OUT = wx.NewEventType()

EVT_FLAT_MENU_DISMISSED = wx.PyEventBinder(wxEVT_FLAT_MENU_DISMISSED, 1)
""" Used internally. """
EVT_FLAT_MENU_SELECTED = wx.PyEventBinder(wxEVT_FLAT_MENU_SELECTED, 2)
""" Fires the wx.EVT_MENU event for L{FlatMenu}. """
EVT_FLAT_MENU_RANGE = wx.PyEventBinder(wxEVT_FLAT_MENU_SELECTED, 2)
""" Fires the wx.EVT_MENU event for a series of L{FlatMenu}. """
EVT_FLAT_MENU_ITEM_MOUSE_OUT = wx.PyEventBinder(wxEVT_FLAT_MENU_ITEM_MOUSE_OUT, 1)
""" Fires an event when the mouse leaves a L{FlatMenuItem}. """
EVT_FLAT_MENU_ITEM_MOUSE_OVER = wx.PyEventBinder(wxEVT_FLAT_MENU_ITEM_MOUSE_OVER, 1)
""" Fires an event when the mouse enters a L{FlatMenuItem}. """

[docs]def GetAccelIndex(label):
    """
    Returns the mnemonic index of the label and the label stripped of the ampersand mnemonic
    (e.g. 'lab&el' ==> will result in 3 and labelOnly = label).

    :param string `label`: a string possibly containining an ampersand.
    """

    indexAccel = 0
    while True:
        indexAccel = label.find("&", indexAccel)
        if indexAccel == -1:
            return indexAccel, label
        if label[indexAccel:indexAccel+2] == "&&":
            label = label[0:indexAccel] + label[indexAccel+1:]
            indexAccel += 1
        else:
            break

    labelOnly = label[0:indexAccel] + label[indexAccel+1:]

    return indexAccel, labelOnly

[docs]def ConvertToMonochrome(bmp):
    """
    Converts a bitmap to monochrome colour.

    :param `bmp`: a valid `wx.Bitmap` object.
    """

    mem_dc = wx.MemoryDC()
    shadow = wx.EmptyBitmap(bmp.GetWidth(), bmp.GetHeight())
    mem_dc.SelectObject(shadow)
    mem_dc.DrawBitmap(bmp, 0, 0, True)
    mem_dc.SelectObject(wx.NullBitmap)
    img = shadow.ConvertToImage()
    img = img.ConvertToMono(0, 0, 0)

    # we now have black where the original bmp was drawn,
    # white elsewhere
    shadow = wx.BitmapFromImage(img)
    shadow.SetMask(wx.Mask(shadow, wx.BLACK))

    # Convert the black to grey
    tmp = wx.EmptyBitmap(bmp.GetWidth(), bmp.GetHeight())
    col = wx.SystemSettings_GetColour(wx.SYS_COLOUR_BTNSHADOW)
    mem_dc.SelectObject(tmp)
    mem_dc.SetPen(wx.Pen(col))
    mem_dc.SetBrush(wx.Brush(col))
    mem_dc.DrawRectangle(0, 0, bmp.GetWidth(), bmp.GetHeight())
    mem_dc.DrawBitmap(shadow, 0, 0, True)   # now contains a bitmap with grey where the image was, white elsewhere
    mem_dc.SelectObject(wx.NullBitmap)
    shadow = tmp
    shadow.SetMask(wx.Mask(shadow, wx.WHITE))

    return shadow

# ---------------------------------------------------------------------------- #
# Class FMRendererMgr
# ---------------------------------------------------------------------------- #

[docs]class FMRendererMgr(object):
    """
    This class represents a manager that handles all the renderers defined.
    Every instance of this class will share the same state, so everyone can
    instantiate their own and a call to L{FMRendererMgr.SetTheme} anywhere will affect everyone.
    """

    def __new__(cls, *p, **k):
        if not '_instance' in cls.__dict__:
            cls._instance = object.__new__(cls)
        return cls._instance

[docs]    def __init__(self):
        """ Default class constructor. """

        # If we have already initialized don't do it again. There is only one
        # FMRendererMgr process-wide.

        if hasattr(self, '_alreadyInitialized'):
            return

        self._alreadyInitialized = True

        self._currentTheme = StyleDefault
        self._renderers = []
        self._renderers.append(FMRenderer())
        self._renderers.append(FMRendererXP())
        self._renderers.append(FMRendererMSOffice2007())
        self._renderers.append(FMRendererVista())

[docs]    def GetRenderer(self):
        """ Returns the current theme's renderer. """

        return self._renderers[self._currentTheme]

[docs]    def AddRenderer(self, renderer):
        """
        Adds a user defined custom renderer.

        :param `renderer`: a class derived from L{FMRenderer}.
        """

        lastRenderer = len(self._renderers)
        self._renderers.append(renderer)

        return lastRenderer

[docs]    def SetTheme(self, theme):
        """
        Sets the current theme.

        :param `theme`: an integer specifying the theme to use.
        """

        if theme < 0 or theme > len(self._renderers):
            raise ValueError("Error invalid theme specified.")

        self._currentTheme = theme

# ---------------------------------------------------------------------------- #
# Class FMRenderer
# ---------------------------------------------------------------------------- #

[docs]class FMRenderer(object):
    """
    Base class for the L{FlatMenu} renderers. This class implements the common
    methods of all the renderers.
    """

[docs]    def __init__(self):
        """ Default class constructor. """

        self.separatorHeight = 5
        self.drawLeftMargin = False
        self.highlightCheckAndRadio = False
        self.scrollBarButtons = False   # Display scrollbar buttons if the menu doesn't fit on the screen
                                        # otherwise default to up and down arrow menu items

        self.itemTextColourDisabled = ArtManager.Get().LightColour(wx.SystemSettings_GetColour(wx.SYS_COLOUR_GRAYTEXT), 30)

        # Background Colours
        self.menuFaceColour     = wx.WHITE
        self.menuBarFaceColour  = ArtManager.Get().LightColour(wx.SystemSettings_GetColour(wx.SYS_COLOUR_3DFACE), 80)

        self.menuBarFocusFaceColour     = wx.SystemSettings_GetColour(wx.SYS_COLOUR_HIGHLIGHT)
        self.menuBarFocusBorderColour   = wx.SystemSettings_GetColour(wx.SYS_COLOUR_HIGHLIGHT)
        self.menuBarPressedFaceColour   = wx.SystemSettings_GetColour(wx.SYS_COLOUR_HIGHLIGHT)
        self.menuBarPressedBorderColour = wx.SystemSettings_GetColour(wx.SYS_COLOUR_HIGHLIGHT)

        self.menuFocusFaceColour     = wx.SystemSettings_GetColour(wx.SYS_COLOUR_HIGHLIGHT)
        self.menuFocusBorderColour   = wx.SystemSettings_GetColour(wx.SYS_COLOUR_HIGHLIGHT)
        self.menuPressedFaceColour   = wx.SystemSettings_GetColour(wx.SYS_COLOUR_HIGHLIGHT)
        self.menuPressedBorderColour = wx.SystemSettings_GetColour(wx.SYS_COLOUR_HIGHLIGHT)

        self.buttonFaceColour          = wx.SystemSettings_GetColour(wx.SYS_COLOUR_HIGHLIGHT)
        self.buttonBorderColour        = wx.SystemSettings_GetColour(wx.SYS_COLOUR_HIGHLIGHT)
        self.buttonFocusFaceColour     = wx.SystemSettings_GetColour(wx.SYS_COLOUR_HIGHLIGHT)
        self.buttonFocusBorderColour   = wx.SystemSettings_GetColour(wx.SYS_COLOUR_HIGHLIGHT)
        self.buttonPressedFaceColour   = wx.SystemSettings_GetColour(wx.SYS_COLOUR_HIGHLIGHT)
        self.buttonPressedBorderColour = wx.SystemSettings_GetColour(wx.SYS_COLOUR_HIGHLIGHT)

        # create wxBitmaps from the xpm's
        self._rightBottomCorner = self.ConvertToBitmap(shadow_center_xpm, shadow_center_alpha)
        self._bottom = self.ConvertToBitmap(shadow_bottom_xpm, shadow_bottom_alpha)
        self._bottomLeft = self.ConvertToBitmap(shadow_bottom_left_xpm, shadow_bottom_left_alpha)
        self._rightTop = self.ConvertToBitmap(shadow_right_top_xpm, shadow_right_top_alpha)
        self._right = self.ConvertToBitmap(shadow_right_xpm, shadow_right_alpha)

        self._bitmaps = {}
        bmp = self.ConvertToBitmap(arrow_down, alpha=None)
        bmp.SetMask(wx.Mask(bmp, wx.Colour(0, 128, 128)))
        self._bitmaps.update({"arrow_down": bmp})

        bmp = self.ConvertToBitmap(arrow_up, alpha=None)
        bmp.SetMask(wx.Mask(bmp, wx.Colour(0, 128, 128)))
        self._bitmaps.update({"arrow_up": bmp})

        self._toolbarSeparatorBitmap = wx.NullBitmap
        self.raiseToolbar = False

[docs]    def SetMenuBarHighlightColour(self, colour):
        """
        Set the colour to highlight focus on the menu bar.

        :param `colour`: a valid instance of `wx.Colour`.
        """

        self.menuBarFocusFaceColour    = colour
        self.menuBarFocusBorderColour  = colour
        self.menuBarPressedFaceColour  = colour
        self.menuBarPressedBorderColour= colour

[docs]    def SetMenuHighlightColour(self,colour):
        """
        Set the colour to highlight focus on the menu.

        :param `colour`: a valid instance of `wx.Colour`.
        """

        self.menuFocusFaceColour    = colour
        self.menuFocusBorderColour  = colour
        self.menuPressedFaceColour     = colour
        self.menuPressedBorderColour   = colour

[docs]    def GetColoursAccordingToState(self, state):
        """
        Returns a `wx.Colour` according to the menu item state.

        :param integer `state`: one of the following bits:

         ==================== ======= ==========================
         Item State            Value  Description
         ==================== ======= ==========================
         ``ControlPressed``         0 The item is pressed
         ``ControlFocus``           1 The item is focused
         ``ControlDisabled``        2 The item is disabled
         ``ControlNormal``          3 Normal state
         ==================== ======= ==========================

        """

        # switch according to the status
        if state == ControlFocus:
            upperBoxTopPercent = 95
            upperBoxBottomPercent = 50
            lowerBoxTopPercent = 40
            lowerBoxBottomPercent = 90
            concaveUpperBox = True
            concaveLowerBox = True

        elif state == ControlPressed:
            upperBoxTopPercent = 75
            upperBoxBottomPercent = 90
            lowerBoxTopPercent = 90
            lowerBoxBottomPercent = 40
            concaveUpperBox = True
            concaveLowerBox = True

        elif state == ControlDisabled:
            upperBoxTopPercent = 100
            upperBoxBottomPercent = 100
            lowerBoxTopPercent = 70
            lowerBoxBottomPercent = 70
            concaveUpperBox = True
            concaveLowerBox = True

        else:
            upperBoxTopPercent = 90
            upperBoxBottomPercent = 50
            lowerBoxTopPercent = 30
            lowerBoxBottomPercent = 75
            concaveUpperBox = True
            concaveLowerBox = True

        return upperBoxTopPercent, upperBoxBottomPercent, lowerBoxTopPercent, lowerBoxBottomPercent, \
               concaveUpperBox, concaveLowerBox

[docs]    def ConvertToBitmap(self, xpm, alpha=None):
        """
        Convert the given image to a bitmap, optionally overlaying an alpha
        channel to it.

        :param `xpm`: a list of strings formatted as XPM;
        :param `alpha`: a list of alpha values, the same size as the xpm bitmap.
        """

        if alpha is not None:

            img = wx.BitmapFromXPMData(xpm)
            img = img.ConvertToImage()
            x, y = img.GetWidth(), img.GetHeight()
            img.InitAlpha()
            for jj in xrange(y):
                for ii in xrange(x):
                    img.SetAlpha(ii, jj, alpha[jj*x+ii])

        else:

            stream = cStringIO.StringIO(xpm)
            img = wx.ImageFromStream(stream)

        return wx.BitmapFromImage(img)

[docs]    def DrawLeftMargin(self, item, dc, menuRect):
        """
        Draws the menu left margin.

        :param `item`: an instance of L{FlatMenuItem};
        :param `dc`: an instance of `wx.DC`;
        :param `menuRect`: an instance of `wx.Rect`, representing the menu client rectangle.
        """

        raise Exception("This style doesn't support Drawing a Left Margin")

[docs]    def DrawToolbarSeparator(self, dc, rect):
        """
        Draws a separator inside the toolbar in L{FlatMenuBar}.

        :param `dc`: an instance of `wx.DC`;
        :param `rect`: an instance of `wx.Rect`, representing the bitmap client rectangle.
        """

        # Place a separator bitmap
        bmp = wx.EmptyBitmap(rect.width, rect.height)
        mem_dc = wx.MemoryDC()
        mem_dc.SelectObject(bmp)
        mem_dc.SetPen(wx.BLACK_PEN)
        mem_dc.SetBrush(wx.BLACK_BRUSH)

        mem_dc.DrawRectangle(0, 0, bmp.GetWidth(), bmp.GetHeight())

        col = self.menuBarFaceColour
        col1 = ArtManager.Get().LightColour(col, 40)
        col2 = ArtManager.Get().LightColour(col, 70)

        mem_dc.SetPen(wx.Pen(col2))
        mem_dc.DrawLine(5, 0, 5, bmp.GetHeight())

        mem_dc.SetPen(wx.Pen(col1))
        mem_dc.DrawLine(6, 0, 6, bmp.GetHeight())

        mem_dc.SelectObject(wx.NullBitmap)
        bmp.SetMask(wx.Mask(bmp, wx.BLACK))

        dc.DrawBitmap(bmp, rect.x, rect.y, True)

    # assumption: the background was already drawn on the dc

[docs]    def DrawBitmapShadow(self, dc, rect, where=BottomShadow|RightShadow):
        """
        Draws a shadow using background bitmap.

        :param `dc`: an instance of `wx.DC`;
        :param `rect`: an instance of `wx.Rect`, representing the bitmap client rectangle;
        :param integer `where`: where to draw the shadow. This can be any combination of the
         following bits:

         ========================== ======= ================================
         Shadow Settings             Value  Description
         ========================== ======= ================================
         ``RightShadow``                  1 Right side shadow
         ``BottomShadow``                 2 Not full bottom shadow
         ``BottomShadowFull``             4 Full bottom shadow
         ========================== ======= ================================

        """

        shadowSize = 5

        # the rect must be at least 5x5 pixles
        if rect.height < 2*shadowSize or rect.width < 2*shadowSize:
            return

        # Start by drawing the right bottom corner
        if where & BottomShadow or where & BottomShadowFull:
            dc.DrawBitmap(self._rightBottomCorner, rect.x+rect.width, rect.y+rect.height, True)

        # Draw right side shadow
        xx = rect.x + rect.width
        yy = rect.y + rect.height - shadowSize

        if where & RightShadow:
            while yy - rect.y > 2*shadowSize:
                dc.DrawBitmap(self._right, xx, yy, True)
                yy -= shadowSize

            dc.DrawBitmap(self._rightTop, xx, yy - shadowSize, True)

        if where & BottomShadow:
            xx = rect.x + rect.width - shadowSize
            yy = rect.height + rect.y
            while xx - rect.x > 2*shadowSize:
                dc.DrawBitmap(self._bottom, xx, yy, True)
                xx -= shadowSize

            dc.DrawBitmap(self._bottomLeft, xx - shadowSize, yy, True)

        if where & BottomShadowFull:
            xx = rect.x + rect.width - shadowSize
            yy = rect.height + rect.y
            while xx - rect.x >= 0:
                dc.DrawBitmap(self._bottom, xx, yy, True)
                xx -= shadowSize

            dc.DrawBitmap(self._bottom, xx, yy, True)

[docs]    def DrawToolBarBg(self, dc, rect):
        """
        Draws the toolbar background

        :param `dc`: an instance of `wx.DC`;
        :param `rect`: an instance of `wx.Rect`, representing the toolbar client rectangle.
        """

        if not self.raiseToolbar:
            return

        dcsaver = DCSaver(dc)

        # fill with gradient
        colour = self.menuBarFaceColour

        dc.SetPen(wx.Pen(colour))
        dc.SetBrush(wx.Brush(colour))

        dc.DrawRectangleRect(rect)
        self.DrawBitmapShadow(dc, rect)

[docs]    def DrawSeparator(self, dc, xCoord, yCoord, textX, sepWidth):
        """
        Draws a separator inside a L{FlatMenu}.

        :param `dc`: an instance of `wx.DC`;
        :param integer `xCoord`: the current x position where to draw the separator;
        :param integer `yCoord`: the current y position where to draw the separator;
        :param integer `textX`: the menu item label x position;
        :param integer `sepWidth`: the width of the separator, in pixels.
        """

        dcsaver = DCSaver(dc)
        sepRect1 = wx.Rect(xCoord + textX, yCoord + 1, sepWidth/2, 1)
        sepRect2 = wx.Rect(xCoord + textX + sepWidth/2, yCoord + 1, sepWidth/2-1, 1)

        artMgr = ArtManager.Get()
        backColour = artMgr.GetMenuFaceColour()
        lightColour = wx.NamedColour("LIGHT GREY")

        artMgr.PaintStraightGradientBox(dc, sepRect1, backColour, lightColour, False)
        artMgr.PaintStraightGradientBox(dc, sepRect2, lightColour, backColour, False)

[docs]    def DrawMenuItem(self, item, dc, xCoord, yCoord, imageMarginX, markerMarginX, textX, rightMarginX, selected=False, backgroundImage=None):
        """
        Draws the menu item.

        :param `item`: a L{FlatMenuItem} instance;
        :param `dc`: an instance of `wx.DC`;
        :param integer `xCoord`: the current x position where to draw the menu;
        :param integer `yCoord`: the current y position where to draw the menu;
        :param integer `imageMarginX`: the spacing between the image and the menu border;
        :param integer `markerMarginX`: the spacing between the checkbox/radio marker and
         the menu border;
        :param integer `textX`: the menu item label x position;
        :param integer `rightMarginX`: the right margin between the text and the menu border;
        :param bool `selected`: ``True`` if this menu item is currentl hovered by the mouse,
         ``False`` otherwise.
        :param `backgroundImage`: if not ``None``, an instance of `wx.Bitmap` which will
         become the background image for this L{FlatMenu}.
        """

        borderXSize = item._parentMenu.GetBorderXWidth()
        itemHeight = item._parentMenu.GetItemHeight()
        menuWidth  = item._parentMenu.GetMenuWidth()

        # Define the item actual rectangle area
        itemRect = wx.Rect(xCoord, yCoord, menuWidth, itemHeight)

        # Define the drawing area
        rect = wx.Rect(xCoord+2, yCoord, menuWidth - 4, itemHeight)

        # Draw the background
        backColour = self.menuFaceColour
        penColour  = backColour
        backBrush = wx.Brush(backColour)
        leftMarginWidth = item._parentMenu.GetLeftMarginWidth()

        if backgroundImage is None:
            pen = wx.Pen(penColour)
            dc.SetPen(pen)
            dc.SetBrush(backBrush)
            dc.DrawRectangleRect(rect)

        # Draw the left margin gradient
        if self.drawLeftMargin:
            self.DrawLeftMargin(item, dc, itemRect)

        # check if separator
        if item.IsSeparator():
            # Separator is a small grey line separating between menu items.
            sepWidth = xCoord + menuWidth - textX - 1
            self.DrawSeparator(dc, xCoord, yCoord, textX, sepWidth)
            return

        # Keep the item rect
        item._rect = itemRect

        # Get the bitmap base on the item state (disabled, selected ..)
        bmp = item.GetSuitableBitmap(selected)

        # First we draw the selection rectangle
        if selected:
            self.DrawMenuButton(dc, rect.Deflate(1,0), ControlFocus)
            #copy.Inflate(0, menubar._spacer)

        if bmp.Ok():

            # Calculate the postion to place the image
            imgHeight = bmp.GetHeight()
            imgWidth  = bmp.GetWidth()

            if imageMarginX == 0:
                xx = rect.x + (leftMarginWidth - imgWidth)/2
            else:
                xx = rect.x + ((leftMarginWidth - rect.height) - imgWidth)/2 + rect.height

            yy = rect.y + (rect.height - imgHeight)/2
            dc.DrawBitmap(bmp, xx, yy, True)

        if item.GetKind() == wx.ITEM_CHECK:

            # Checkable item
            if item.IsChecked():

                # Draw surrounding rectangle around the selection box
                xx = rect.x + 1
                yy = rect.y + 1
                rr = wx.Rect(xx, yy, rect.height-2, rect.height-2)

                if not selected and self.highlightCheckAndRadio:
                    self.DrawButton(dc, rr, ControlFocus)

                dc.DrawBitmap(item._checkMarkBmp, rr.x + (rr.width - 16)/2, rr.y + (rr.height - 16)/2, True)

        if item.GetKind() == wx.ITEM_RADIO:

            # Checkable item
            if item.IsChecked():

                # Draw surrounding rectangle around the selection box
                xx = rect.x + 1
                yy = rect.y + 1
                rr = wx.Rect(xx, yy, rect.height-2, rect.height-2)

                if not selected and self.highlightCheckAndRadio:
                    self.DrawButton(dc, rr, ControlFocus)

                dc.DrawBitmap(item._radioMarkBmp, rr.x + (rr.width - 16)/2, rr.y + (rr.height - 16)/2, True)

        # Draw text - without accelerators
        text = item.GetLabel()

        if text:

            font = item.GetFont()
            if font is None:
                font = wx.SystemSettings_GetFont(wx.SYS_DEFAULT_GUI_FONT)

            if selected:
                enabledTxtColour = colourutils.BestLabelColour(self.menuFocusFaceColour, bw=True)
            else:
                enabledTxtColour = colourutils.BestLabelColour(self.menuFaceColour, bw=True)

            disabledTxtColour = self.itemTextColourDisabled
            textColour = (item.IsEnabled() and [enabledTxtColour] or [disabledTxtColour])[0]

            if item.IsEnabled() and item.GetTextColour():
                textColour = item.GetTextColour()

            dc.SetFont(font)
            w, h = dc.GetTextExtent(text)
            dc.SetTextForeground(textColour)

            if item._mnemonicIdx != wx.NOT_FOUND:

                # We divide the drawing to 3 parts
                text1 = text[0:item._mnemonicIdx]
                text2 = text[item._mnemonicIdx]
                text3 = text[item._mnemonicIdx+1:]

                w1, dummy = dc.GetTextExtent(text1)
                w2, dummy = dc.GetTextExtent(text2)
                w3, dummy = dc.GetTextExtent(text3)

                posx = xCoord + textX + borderXSize
                posy = (itemHeight - h)/2 + yCoord

                # Draw first part
                dc.DrawText(text1, posx, posy)

                # mnemonic
                if "__WXGTK__" not in wx.Platform:
                    font.SetUnderlined(True)
                    dc.SetFont(font)

                posx += w1
                dc.DrawText(text2, posx, posy)

                # last part
                font.SetUnderlined(False)
                dc.SetFont(font)
                posx += w2
                dc.DrawText(text3, posx, posy)

            else:

                w, h = dc.GetTextExtent(text)
                dc.DrawText(text, xCoord + textX + borderXSize, (itemHeight - h)/2 + yCoord)

        # Now draw accelerator
        # Accelerators are aligned to the right
        if item.GetAccelString():

            accelWidth, accelHeight = dc.GetTextExtent(item.GetAccelString())
            dc.DrawText(item.GetAccelString(), xCoord + rightMarginX - accelWidth, (itemHeight - accelHeight)/2 + yCoord)

        # Check if this item has sub-menu - if it does, draw
        # right arrow on the right margin
        if item.GetSubMenu():

            # Draw arrow
            rightArrowBmp = wx.BitmapFromXPMData(menu_right_arrow_xpm)
            rightArrowBmp.SetMask(wx.Mask(rightArrowBmp, wx.WHITE))

            xx = xCoord + rightMarginX + borderXSize
            rr = wx.Rect(xx, rect.y + 1, rect.height-2, rect.height-2)
            dc.DrawBitmap(rightArrowBmp, rr.x + 4, rr.y +(rr.height-16)/2, True)

[docs]    def DrawMenuBarButton(self, dc, rect, state):
        """
        Draws the highlight on a L{FlatMenuBar}.

        :param `dc`: an instance of `wx.DC`;
        :param `rect`: an instance of `wx.Rect`, representing the button client rectangle;
        :param integer `state`: the button state.
        """

        # switch according to the status
        if state == ControlFocus:
            penColour   = self.menuBarFocusBorderColour
            brushColour = self.menuBarFocusFaceColour
        elif state == ControlPressed:
            penColour   = self.menuBarPressedBorderColour
            brushColour = self.menuBarPressedFaceColour

        dcsaver = DCSaver(dc)
        dc.SetPen(wx.Pen(penColour))
        dc.SetBrush(wx.Brush(brushColour))
        dc.DrawRectangleRect(rect)

[docs]    def DrawMenuButton(self, dc, rect, state):
        """
        Draws the highlight on a FlatMenu

        :param `dc`: an instance of `wx.DC`;
        :param `rect`: an instance of `wx.Rect`, representing the button client rectangle;
        :param integer `state`: the button state.
        """

        # switch according to the status
        if state == ControlFocus:
            penColour   = self.menuFocusBorderColour
            brushColour = self.menuFocusFaceColour
        elif state == ControlPressed:
            penColour   = self.menuPressedBorderColour
            brushColour = self.menuPressedFaceColour

        dcsaver = DCSaver(dc)
        dc.SetPen(wx.Pen(penColour))
        dc.SetBrush(wx.Brush(brushColour))
        dc.DrawRectangleRect(rect)

[docs]    def DrawScrollButton(self, dc, rect, state):
        """
        Draws the scroll button

        :param `dc`: an instance of `wx.DC`;
        :param `rect`: an instance of `wx.Rect`, representing the button client rectangle;
        :param integer `state`: the button state.
        """

        if not self.scrollBarButtons:
            return

        colour = wx.SystemSettings_GetColour(wx.SYS_COLOUR_ACTIVECAPTION)
        colour = ArtManager.Get().LightColour(colour, 30)

        artMgr = ArtManager.Get()

        # Keep old pen and brush
        dcsaver = DCSaver(dc)

        # Define the rounded rectangle base on the given rect
        # we need an array of 9 points for it
        baseColour = colour

        # Define the middle points
        leftPt = wx.Point(rect.x, rect.y + (rect.height / 2))
        rightPt = wx.Point(rect.x + rect.width-1, rect.y + (rect.height / 2))

        # Define the top region
        top = wx.RectPP((rect.GetLeft(), rect.GetTop()), rightPt)
        bottom = wx.RectPP(leftPt, (rect.GetRight(), rect.GetBottom()))

        upperBoxTopPercent, upperBoxBottomPercent, lowerBoxTopPercent, lowerBoxBottomPercent, \
                            concaveUpperBox, concaveLowerBox = self.GetColoursAccordingToState(state)

        topStartColour = artMgr.LightColour(baseColour, upperBoxTopPercent)
        topEndColour = artMgr.LightColour(baseColour, upperBoxBottomPercent)
        bottomStartColour = artMgr.LightColour(baseColour, lowerBoxTopPercent)
        bottomEndColour = artMgr.LightColour(baseColour, lowerBoxBottomPercent)

        artMgr.PaintStraightGradientBox(dc, top, topStartColour, topEndColour)
        artMgr.PaintStraightGradientBox(dc, bottom, bottomStartColour, bottomEndColour)

        rr = wx.Rect(rect.x, rect.y, rect.width, rect.height)
        dc.SetBrush(wx.TRANSPARENT_BRUSH)

        frameColour = artMgr.LightColour(baseColour, 60)
        dc.SetPen(wx.Pen(frameColour))
        dc.DrawRectangleRect(rr)

        wc = artMgr.LightColour(baseColour, 80)
        dc.SetPen(wx.Pen(wc))
        rr.Deflate(1, 1)
        dc.DrawRectangleRect(rr)

[docs]    def DrawButton(self, dc, rect, state, colour=None):
        """
        Draws a button.

        :param `dc`: an instance of `wx.DC`;
        :param `rect`: an instance of `wx.Rect`, representing the button client rectangle;
        :param integer `state`: the button state;
        :param `colour`: if not ``None``, an instance of `wx.Colour` to be used to draw
         the L{FlatMenuItem} background.
        """

        # switch according to the status
        if state == ControlFocus:
            if colour == None:
                penColour   = self.buttonFocusBorderColour
                brushColour = self.buttonFocusFaceColour
            else:
                penColour   = colour
                brushColour = ArtManager.Get().LightColour(colour, 75)

        elif state == ControlPressed:
            if colour == None:
                penColour   = self.buttonPressedBorderColour
                brushColour = self.buttonPressedFaceColour
            else:
                penColour   = colour
                brushColour = ArtManager.Get().LightColour(colour, 60)
        else:
            if colour == None:
                penColour   = self.buttonBorderColour
                brushColour = self.buttonFaceColour
            else:
                penColour   = colour
                brushColour = ArtManager.Get().LightColour(colour, 75)

        dcsaver = DCSaver(dc)
        dc.SetPen(wx.Pen(penColour))
        dc.SetBrush(wx.Brush(brushColour))
        dc.DrawRectangleRect(rect)

[docs]    def DrawMenuBarBackground(self, dc, rect):
        """
        Draws the menu bar background colour according to the menubar.GetBackgroundColour

        :param `dc`: an instance of `wx.DC`;
        :param `rect`: an instance of `wx.Rect`, representing the menubar client rectangle.
        """

        dcsaver = DCSaver(dc)

        # fill with gradient
        colour = self.menuBarFaceColour

        dc.SetPen(wx.Pen(colour))
        dc.SetBrush(wx.Brush(colour))
        dc.DrawRectangleRect(rect)

[docs]    def DrawMenuBar(self, menubar, dc):
        """
        Draws everything for L{FlatMenuBar}.

        :param `menubar`: an instance of L{FlatMenuBar}.
        :param `dc`: an instance of `wx.DC`.
        """

        #artMgr = ArtManager.Get()
        fnt = wx.SystemSettings_GetFont(wx.SYS_DEFAULT_GUI_FONT)
        textColour = colourutils.BestLabelColour(menubar.GetBackgroundColour(), bw=True)
        highlightTextColour = colourutils.BestLabelColour(self.menuBarFocusFaceColour, bw=True)

        dc.SetFont(fnt)
        dc.SetTextForeground(textColour)

        clientRect = menubar.GetClientRect()

        self.DrawMenuBarBackground(dc, clientRect)

        padding, dummy = dc.GetTextExtent("W")

        posx = 0
        posy = menubar._margin

        # ---------------------------------------------------------------------------
        # Draw as much items as we can if the screen is not wide enough, add all
        # missing items to a drop down menu
        # ---------------------------------------------------------------------------
        menuBarRect = menubar.GetClientRect()

        # mark all items as non-visibles at first
        for item in menubar._items:
            item.SetRect(wx.Rect())

        for item in menubar._items:

            # Handle accelerator ('&')
            title = item.GetTitle()

            fixedText = title
            location, labelOnly = GetAccelIndex(fixedText)

            # Get the menu item rect
            textWidth, textHeight = dc.GetTextExtent(fixedText)
            #rect = wx.Rect(posx+menubar._spacer/2, posy, textWidth, textHeight)
            rect = wx.Rect(posx+padding/2, posy, textWidth, textHeight)

            # Can we draw more??
            # the +DROP_DOWN_ARROW_WIDTH  is the width of the drop down arrow
            if posx + rect.width + DROP_DOWN_ARROW_WIDTH >= menuBarRect.width:
                break

            # In this style the button highlight includes the menubar margin
            button_rect = wx.Rect(*rect)
            button_rect.height = menubar._menuBarHeight
            #button_rect.width = rect.width + menubar._spacer
            button_rect.width = rect.width + padding
            button_rect.x = posx
            button_rect.y = 0

            # Keep the item rectangle, will be used later in functions such
            # as 'OnLeftDown', 'OnMouseMove'
            copy = wx.Rect(*button_rect)
            #copy.Inflate(0, menubar._spacer)
            item.SetRect(copy)

            selected = False
            if item.GetState() == ControlFocus:
                self.DrawMenuBarButton(dc, button_rect, ControlFocus)
                dc.SetTextForeground(highlightTextColour)
                selected = True
            else:
                dc.SetTextForeground(textColour)

            ww, hh = dc.GetTextExtent(labelOnly)
            textOffset = (rect.width - ww) / 2

            if not menubar._isLCD and item.GetTextBitmap().Ok() and not selected:
                dc.DrawBitmap(item.GetTextBitmap(), rect.x, rect.y, True)
            elif not menubar._isLCD and item.GetSelectedTextBitmap().Ok() and selected:
                dc.DrawBitmap(item.GetSelectedTextBitmap(), rect.x, rect.y, True)
            else:
                if not menubar._isLCD:
                    # Draw the text on a bitmap using memory dc,
                    # so on following calls we will use this bitmap instead
                    # of calculating everything from scratch
                    bmp = wx.EmptyBitmap(rect.width, rect.height)
                    memDc = wx.MemoryDC()
                    memDc.SelectObject(bmp)
                    if selected:
                        memDc.SetTextForeground(highlightTextColour)
                    else:
                        memDc.SetTextForeground(textColour)

                    # Fill the bitmap with the masking colour
                    memDc.SetPen(wx.Pen(wx.Colour(255, 0, 0)) )
                    memDc.SetBrush(wx.Brush(wx.Colour(255, 0, 0)) )
                    memDc.DrawRectangle(0, 0, rect.width, rect.height)
                    memDc.SetFont(fnt)

                if location == wx.NOT_FOUND or location >= len(fixedText):
                    # draw the text
                    if not menubar._isLCD:
                        memDc.DrawText(title, textOffset, 0)
                    dc.DrawText(title, rect.x + textOffset, rect.y)

                else:

                    # underline the first '&'
                    before = labelOnly[0:location]
                    underlineLetter = labelOnly[location]
                    after = labelOnly[location+1:]

                    # before
                    if not menubar._isLCD:
                        memDc.DrawText(before, textOffset, 0)
                    dc.DrawText(before, rect.x + textOffset, rect.y)

                    # underlineLetter
                    if "__WXGTK__" not in wx.Platform:
                        w1, h = dc.GetTextExtent(before)
                        fnt.SetUnderlined(True)
                        dc.SetFont(fnt)
                        dc.DrawText(underlineLetter, rect.x + w1 + textOffset, rect.y)
                        if not menubar._isLCD:
                            memDc.SetFont(fnt)
                            memDc.DrawText(underlineLetter, textOffset + w1, 0)

                    else:
                        w1, h = dc.GetTextExtent(before)
                        dc.DrawText(underlineLetter, rect.x + w1 + textOffset, rect.y)
                        if not menubar._isLCD:
                            memDc.DrawText(underlineLetter, textOffset + w1, 0)

                        # Draw the underline ourselves since using the Underline in GTK,
                        # causes the line to be too close to the letter

                        uderlineLetterW, uderlineLetterH = dc.GetTextExtent(underlineLetter)
                        dc.DrawLine(rect.x + w1 + textOffset, rect.y + uderlineLetterH - 2,
                                    rect.x + w1 + textOffset + uderlineLetterW, rect.y + uderlineLetterH - 2)

                    # after
                    w2, h = dc.GetTextExtent(underlineLetter)
                    fnt.SetUnderlined(False)
                    dc.SetFont(fnt)
                    dc.DrawText(after, rect.x + w1 + w2 + textOffset, rect.y)
                    if not menubar._isLCD:
                        memDc.SetFont(fnt)
                        memDc.DrawText(after,  w1 + w2 + textOffset, 0)

                    if not menubar._isLCD:
                        memDc.SelectObject(wx.NullBitmap)
                        # Set masking colour to the bitmap
                        bmp.SetMask(wx.Mask(bmp, wx.Colour(255, 0, 0)))
                        if selected:
                            item.SetSelectedTextBitmap(bmp)
                        else:
                            item.SetTextBitmap(bmp)

            posx += rect.width + padding # + menubar._spacer

        # Get a background image of the more menu button
        moreMenubtnBgBmpRect = wx.Rect(*menubar.GetMoreMenuButtonRect())
        if not menubar._moreMenuBgBmp:
            menubar._moreMenuBgBmp = wx.EmptyBitmap(moreMenubtnBgBmpRect.width, moreMenubtnBgBmpRect.height)

        if menubar._showToolbar and len(menubar._tbButtons) > 0:
            rectX      = 0
            rectWidth  = clientRect.width - moreMenubtnBgBmpRect.width
            if len(menubar._items) == 0:
                rectHeight = clientRect.height
                rectY      = 0
            else:
                rectHeight = clientRect.height - menubar._menuBarHeight
                rectY      = menubar._menuBarHeight
            rr = wx.Rect(rectX, rectY, rectWidth, rectHeight)
            self.DrawToolBarBg(dc, rr)
            menubar.DrawToolbar(dc, rr)

        if menubar._showCustomize or menubar.GetInvisibleMenuItemCount() > 0 or  menubar.GetInvisibleToolbarItemCount() > 0:
            memDc = wx.MemoryDC()
            memDc.SelectObject(menubar._moreMenuBgBmp)
            try:
                memDc.Blit(0, 0, menubar._moreMenuBgBmp.GetWidth(), menubar._moreMenuBgBmp.GetHeight(), dc,
                           moreMenubtnBgBmpRect.x, moreMenubtnBgBmpRect.y)
            except:
                pass
            memDc.SelectObject(wx.NullBitmap)

            # Draw the drop down arrow button
            menubar.DrawMoreButton(dc, menubar._dropDownButtonState)
            # Set the button rect
            menubar._dropDownButtonArea = moreMenubtnBgBmpRect

[docs]    def DrawMenu(self, flatmenu, dc):
        """
        Draws the menu.

        :param `flatmenu`: the L{FlatMenu} instance we need to paint;
        :param `dc`: an instance of `wx.DC`.
        """

        menuRect = flatmenu.GetClientRect()
        menuBmp = wx.EmptyBitmap(menuRect.width, menuRect.height)

        mem_dc = wx.MemoryDC()
        mem_dc.SelectObject(menuBmp)

        # colour the menu face with background colour
        backColour = self.menuFaceColour
        penColour  = wx.SystemSettings_GetColour(wx.SYS_COLOUR_BTNSHADOW)

        backBrush = wx.Brush(backColour)
        pen = wx.Pen(penColour)

        mem_dc.SetPen(pen)
        mem_dc.SetBrush(backBrush)
        mem_dc.DrawRectangleRect(menuRect)

        backgroundImage = flatmenu._backgroundImage

        if backgroundImage:
            mem_dc.DrawBitmap(backgroundImage, flatmenu._leftMarginWidth, 0, True)

        # draw items
        posy = 3
        nItems = len(flatmenu._itemsArr)

        # make all items as non-visible first
        for item in flatmenu._itemsArr:
            item.Show(False)

        visibleItems = 0
        screenHeight = wx.SystemSettings_GetMetric(wx.SYS_SCREEN_Y)

        numCols = flatmenu.GetNumberColumns()
        switch, posx, index = 1e6, 0, 0
        if numCols > 1:
            switch = int(math.ceil((nItems - flatmenu._first)/float(numCols)))

        # If we have to scroll and are not using the scroll bar buttons we need to draw
        # the scroll up menu item at the top.
        if not self.scrollBarButtons and flatmenu._showScrollButtons:
            posy += flatmenu.GetItemHeight()

        for nCount in xrange(flatmenu._first, nItems):

            visibleItems += 1
            item = flatmenu._itemsArr[nCount]
            self.DrawMenuItem(item, mem_dc, posx, posy,
                              flatmenu._imgMarginX, flatmenu._markerMarginX,
                              flatmenu._textX, flatmenu._rightMarginPosX,
                              nCount == flatmenu._selectedItem,
                              backgroundImage=backgroundImage)
            posy += item.GetHeight()
            item.Show()

            if visibleItems >= switch:
                posy = 2
                index += 1
                posx = flatmenu._menuWidth*index
                visibleItems = 0

            # make sure we draw only visible items
            pp = flatmenu.ClientToScreen(wx.Point(0, posy))

            menuBottom = (self.scrollBarButtons and [pp.y] or [pp.y + flatmenu.GetItemHeight()*2])[0]

            if menuBottom > screenHeight:
                break

        if flatmenu._showScrollButtons:
            if flatmenu._upButton:
                flatmenu._upButton.Draw(mem_dc)
            if flatmenu._downButton:
                flatmenu._downButton.Draw(mem_dc)

        dc.Blit(0, 0, menuBmp.GetWidth(), menuBmp.GetHeight(), mem_dc, 0, 0)

# ---------------------------------------------------------------------------- #
# Class FMRendererMSOffice2007
# ---------------------------------------------------------------------------- #

[docs]class FMRendererMSOffice2007(FMRenderer):
    """ Windows Office 2007 style. """

[docs]    def __init__(self):
        """ Default class constructor. """

        FMRenderer.__init__(self)

        self.drawLeftMargin = True
        self.separatorHeight = 3
        self.highlightCheckAndRadio = True
        self.scrollBarButtons = True   # Display scrollbar buttons if the menu doesn't fit on the screen

        self.menuBarFaceColour   = wx.SystemSettings_GetColour(wx.SYS_COLOUR_3DFACE)

        self.buttonBorderColour        = wx.SystemSettings_GetColour(wx.SYS_COLOUR_ACTIVECAPTION)
        self.buttonFaceColour          = ArtManager.Get().LightColour(self.buttonBorderColour, 75)
        self.buttonFocusBorderColour   = wx.SystemSettings_GetColour(wx.SYS_COLOUR_ACTIVECAPTION)
        self.buttonFocusFaceColour     = ArtManager.Get().LightColour(self.buttonFocusBorderColour, 75)
        self.buttonPressedBorderColour = wx.SystemSettings_GetColour(wx.SYS_COLOUR_ACTIVECAPTION)
        self.buttonPressedFaceColour   = ArtManager.Get().LightColour(self.buttonPressedBorderColour, 60)

        self.menuFocusBorderColour   = wx.SystemSettings_GetColour(wx.SYS_COLOUR_ACTIVECAPTION)
        self.menuFocusFaceColour     = ArtManager.Get().LightColour(self.buttonFocusBorderColour, 75)
        self.menuPressedBorderColour = wx.SystemSettings_GetColour(wx.SYS_COLOUR_ACTIVECAPTION)
        self.menuPressedFaceColour   = ArtManager.Get().LightColour(self.buttonPressedBorderColour, 60)

        self.menuBarFocusBorderColour   = wx.SystemSettings_GetColour(wx.SYS_COLOUR_ACTIVECAPTION)
        self.menuBarFocusFaceColour     = ArtManager.Get().LightColour(self.buttonFocusBorderColour, 75)
        self.menuBarPressedBorderColour = wx.SystemSettings_GetColour(wx.SYS_COLOUR_ACTIVECAPTION)
        self.menuBarPressedFaceColour   = ArtManager.Get().LightColour(self.buttonPressedBorderColour, 60)

[docs]    def DrawLeftMargin(self, item, dc, menuRect):
        """
        Draws the menu left margin.

        :param `item`: the L{FlatMenuItem} to paint;
        :param `dc`: an instance of `wx.DC`;
        :param `menuRect`: an instance of `wx.Rect`, representing the menu client rectangle.
        """

        # Construct the margin rectangle
        marginRect = wx.Rect(menuRect.x+1, menuRect.y, item._parentMenu.GetLeftMarginWidth(), menuRect.height)

        # Set the gradient colours
        artMgr = ArtManager.Get()
        faceColour = self.menuFaceColour

        dcsaver = DCSaver(dc)
        marginColour = artMgr.DarkColour(faceColour, 5)
        dc.SetPen(wx.Pen(marginColour))
        dc.SetBrush(wx.Brush(marginColour))
        dc.DrawRectangleRect(marginRect)

        dc.SetPen(wx.WHITE_PEN)
        dc.DrawLine(marginRect.x + marginRect.width, marginRect.y, marginRect.x + marginRect.width, marginRect.y + marginRect.height)

        borderColour = artMgr.DarkColour(faceColour, 10)
        dc.SetPen(wx.Pen(borderColour))
        dc.DrawLine(marginRect.x + marginRect.width-1, marginRect.y, marginRect.x + marginRect.width-1, marginRect.y + marginRect.height)

[docs]    def DrawMenuButton(self, dc, rect, state):
        """
        Draws the highlight on a L{FlatMenu}.

        :param `dc`: an instance of `wx.DC`;
        :param `rect`: an instance of `wx.Rect`, representing the button client rectangle;
        :param integer `state`: the button state.
        """

        self.DrawButton(dc, rect, state)

[docs]    def DrawMenuBarButton(self, dc, rect, state):
        """
        Draws the highlight on a L{FlatMenuBar}.

        :param `dc`: an instance of `wx.DC`;
        :param `rect`: an instance of `wx.Rect`, representing the button client rectangle;
        :param integer `state`: the button state.
        """

        self.DrawButton(dc, rect, state)

[docs]    def DrawButton(self, dc, rect, state, colour=None):
        """
        Draws a button using the Office 2007 theme.

        :param `dc`: an instance of `wx.DC`;
        :param `rect`: an instance of `wx.Rect`, representing the button client rectangle;
        :param integer `state`: the button state;
        :param `colour`: if not ``None``, an instance of `wx.Colour` to be used to draw
         the L{FlatMenuItem} background.
        """

        colour = wx.SystemSettings_GetColour(wx.SYS_COLOUR_ACTIVECAPTION)
        colour = ArtManager.Get().LightColour(colour, 30)
        self.DrawButtonColour(dc, rect, state, colour)

[docs]    def DrawButtonColour(self, dc, rect, state, colour):
        """
        Draws a button using the Office 2007 theme.

        :param `dc`: an instance of `wx.DC`;
        :param `rect`: an instance of `wx.Rect`, representing the button client rectangle;
        :param integer `state`: the button state;
        :param `colour`: a valid `wx.Colour` instance.
        """

        artMgr = ArtManager.Get()

        # Keep old pen and brush
        dcsaver = DCSaver(dc)

        # Define the rounded rectangle base on the given rect
        # we need an array of 9 points for it
        baseColour = colour

        # Define the middle points
        leftPt = wx.Point(rect.x, rect.y + (rect.height / 2))
        rightPt = wx.Point(rect.x + rect.width-1, rect.y + (rect.height / 2))

        # Define the top region
        top = wx.RectPP((rect.GetLeft(), rect.GetTop()), rightPt)
        bottom = wx.RectPP(leftPt, (rect.GetRight(), rect.GetBottom()))

        upperBoxTopPercent, upperBoxBottomPercent, lowerBoxTopPercent, lowerBoxBottomPercent, \
                            concaveUpperBox, concaveLowerBox = self.GetColoursAccordingToState(state)

        topStartColour = artMgr.LightColour(baseColour, upperBoxTopPercent)
        topEndColour = artMgr.LightColour(baseColour, upperBoxBottomPercent)
        bottomStartColour = artMgr.LightColour(baseColour, lowerBoxTopPercent)
        bottomEndColour = artMgr.LightColour(baseColour, lowerBoxBottomPercent)

        artMgr.PaintStraightGradientBox(dc, top, topStartColour, topEndColour)
        artMgr.PaintStraightGradientBox(dc, bottom, bottomStartColour, bottomEndColour)

        rr = wx.Rect(rect.x, rect.y, rect.width, rect.height)
        dc.SetBrush(wx.TRANSPARENT_BRUSH)

        frameColour = artMgr.LightColour(baseColour, 60)
        dc.SetPen(wx.Pen(frameColour))
        dc.DrawRectangleRect(rr)

        wc = artMgr.LightColour(baseColour, 80)
        dc.SetPen(wx.Pen(wc))
        rr.Deflate(1, 1)
        dc.DrawRectangleRect(rr)

[docs]    def DrawMenuBarBackground(self, dc, rect):
        """
        Draws the menu bar background according to the active theme.

        :param `dc`: an instance of `wx.DC`;
        :param `rect`: an instance of `wx.Rect`, representing the menubar client rectangle.
        """

        # Keep old pen and brush
        dcsaver = DCSaver(dc)
        artMgr = ArtManager.Get()
        baseColour = self.menuBarFaceColour

        dc.SetBrush(wx.Brush(wx.SystemSettings_GetColour(wx.SYS_COLOUR_3DFACE)))
        dc.SetPen(wx.Pen(wx.SystemSettings_GetColour(wx.SYS_COLOUR_3DFACE)))
        dc.DrawRectangleRect(rect)

        # Define the rounded rectangle base on the given rect
        # we need an array of 9 points for it
        regPts = [wx.Point() for ii in xrange(9)]
        radius = 2

        regPts[0] = wx.Point(rect.x, rect.y + radius)
        regPts[1] = wx.Point(rect.x+radius, rect.y)
        regPts[2] = wx.Point(rect.x+rect.width-radius-1, rect.y)
        regPts[3] = wx.Point(rect.x+rect.width-1, rect.y + radius)
        regPts[4] = wx.Point(rect.x+rect.width-1, rect.y + rect.height - radius - 1)
        regPts[5] = wx.Point(rect.x+rect.width-radius-1, rect.y + rect.height-1)
        regPts[6] = wx.Point(rect.x+radius, rect.y + rect.height-1)
        regPts[7] = wx.Point(rect.x, rect.y + rect.height - radius - 1)
        regPts[8] = regPts[0]

        # Define the middle points

        factor = artMgr.GetMenuBgFactor()

        leftPt1 = wx.Point(rect.x, rect.y + (rect.height / factor))
        leftPt2 = wx.Point(rect.x, rect.y + (rect.height / factor)*(factor-1))

        rightPt1 = wx.Point(rect.x + rect.width, rect.y + (rect.height / factor))
        rightPt2 = wx.Point(rect.x + rect.width, rect.y + (rect.height / factor)*(factor-1))

        # Define the top region
        topReg = [wx.Point() for ii in xrange(7)]
        topReg[0] = regPts[0]
        topReg[1] = regPts[1]
        topReg[2] = wx.Point(regPts[2].x+1, regPts[2].y)
        topReg[3] = wx.Point(regPts[3].x + 1, regPts[3].y)
        topReg[4] = wx.Point(rightPt1.x, rightPt1.y+1)
        topReg[5] = wx.Point(leftPt1.x, leftPt1.y+1)
        topReg[6] = topReg[0]

        # Define the middle region
        middle = wx.RectPP(leftPt1, wx.Point(rightPt2.x - 2, rightPt2.y))

        # Define the bottom region
        bottom = wx.RectPP(leftPt2, wx.Point(rect.GetRight() - 1, rect.GetBottom()))

        topStartColour    = artMgr.LightColour(baseColour, 90)
        topEndColour      = artMgr.LightColour(baseColour, 60)
        bottomStartColour = artMgr.LightColour(baseColour, 40)
        bottomEndColour   = artMgr.LightColour(baseColour, 20)

        topRegion = wx.RegionFromPoints(topReg)

        artMgr.PaintGradientRegion(dc, topRegion, topStartColour, topEndColour)
        artMgr.PaintStraightGradientBox(dc, bottom, bottomStartColour, bottomEndColour)
        artMgr.PaintStraightGradientBox(dc, middle, topEndColour, bottomStartColour)

[docs]    def DrawToolBarBg(self, dc, rect):
        """
        Draws the toolbar background according to the active theme.

        :param `dc`: an instance of `wx.DC`;
        :param `rect`: an instance of `wx.Rect`, representing the toolbar client rectangle.
        """

        artMgr = ArtManager.Get()

        if not artMgr.GetRaiseToolbar():
            return

        # Keep old pen and brush
        dcsaver = DCSaver(dc)

        baseColour = self.menuBarFaceColour
        baseColour = artMgr.LightColour(baseColour, 20)

        dc.SetBrush(wx.Brush(wx.SystemSettings_GetColour(wx.SYS_COLOUR_3DFACE)))
        dc.SetPen(wx.Pen(wx.SystemSettings_GetColour(wx.SYS_COLOUR_3DFACE)))
        dc.DrawRectangleRect(rect)

        radius = 2

        # Define the rounded rectangle base on the given rect
        # we need an array of 9 points for it
        regPts = [None]*9

        regPts[0] = wx.Point(rect.x, rect.y + radius)
        regPts[1] = wx.Point(rect.x+radius, rect.y)
        regPts[2] = wx.Point(rect.x+rect.width-radius-1, rect.y)
        regPts[3] = wx.Point(rect.x+rect.width-1, rect.y + radius)
        regPts[4] = wx.Point(rect.x+rect.width-1, rect.y + rect.height - radius - 1)
        regPts[5] = wx.Point(rect.x+rect.width-radius-1, rect.y + rect.height-1)
        regPts[6] = wx.Point(rect.x+radius, rect.y + rect.height-1)
        regPts[7] = wx.Point(rect.x, rect.y + rect.height - radius - 1)
        regPts[8] = regPts[0]

        # Define the middle points
        factor = artMgr.GetMenuBgFactor()

        leftPt1 = wx.Point(rect.x, rect.y + (rect.height / factor))
        rightPt1 = wx.Point(rect.x + rect.width, rect.y + (rect.height / factor))

        leftPt2 = wx.Point(rect.x, rect.y + (rect.height / factor)*(factor-1))
        rightPt2 = wx.Point(rect.x + rect.width, rect.y + (rect.height / factor)*(factor-1))

        # Define the top region
        topReg = [None]*7
        topReg[0] = regPts[0]
        topReg[1] = regPts[1]
        topReg[2] = wx.Point(regPts[2].x+1, regPts[2].y)
        topReg[3] = wx.Point(regPts[3].x + 1, regPts[3].y)
        topReg[4] = wx.Point(rightPt1.x, rightPt1.y+1)
        topReg[5] = wx.Point(leftPt1.x, leftPt1.y+1)
        topReg[6] = topReg[0]

        # Define the middle region
        middle = wx.RectPP(leftPt1, wx.Point(rightPt2.x - 2, rightPt2.y))

        # Define the bottom region
        bottom = wx.RectPP(leftPt2, wx.Point(rect.GetRight() - 1, rect.GetBottom()))

        topStartColour   = artMgr.LightColour(baseColour, 90)
        topEndColour = artMgr.LightColour(baseColour, 60)
        bottomStartColour = artMgr.LightColour(baseColour, 40)
        bottomEndColour   = artMgr.LightColour(baseColour, 20)

        topRegion = wx.RegionFromPoints(topReg)

        artMgr.PaintGradientRegion(dc, topRegion, topStartColour, topEndColour)
        artMgr.PaintStraightGradientBox(dc, bottom, bottomStartColour, bottomEndColour)
        artMgr.PaintStraightGradientBox(dc, middle, topEndColour, bottomStartColour)

        artMgr.DrawBitmapShadow(dc, rect)

[docs]    def GetTextColourEnable(self):
        """ Returns the colour used for text colour when enabled. """

        return wx.NamedColour("MIDNIGHT BLUE")

# ---------------------------------------------------------------------------- #
# Class FMRendererVista
# ---------------------------------------------------------------------------- #

[docs]class FMRendererVista(FMRendererMSOffice2007):
    """ Windows Vista-like style. """

[docs]    def __init__(self):
        """ Default class constructor. """

        FMRendererMSOffice2007.__init__(self)

[docs]    def DrawButtonColour(self, dc, rect, state, colour):
        """
        Draws a button using the Vista theme.

        :param `dc`: an instance of `wx.DC`;
        :param `rect`: the an instance of `wx.Rect`, representing the button client rectangle;
        :param integer `state`: the button state;
        :param `colour`: a valid `wx.Colour` instance.
        """

        artMgr = ArtManager.Get()

        # Keep old pen and brush
        dcsaver = DCSaver(dc)

        outer = rgbSelectOuter
        inner = rgbSelectInner
        top = rgbSelectTop
        bottom = rgbSelectBottom

        bdrRect = wx.Rect(*rect)
        filRect = wx.Rect(*rect)
        filRect.Deflate(1,1)

        r1, g1, b1 = int(top.Red()), int(top.Green()), int(top.Blue())
        r2, g2, b2 = int(bottom.Red()), int(bottom.Green()), int(bottom.Blue())
        dc.GradientFillLinear(filRect, top, bottom, wx.SOUTH)

        dc.SetBrush(wx.TRANSPARENT_BRUSH)
        dc.SetPen(wx.Pen(outer))
        dc.DrawRoundedRectangleRect(bdrRect, 3)
        bdrRect.Deflate(1, 1)
        dc.SetPen(wx.Pen(inner))
        dc.DrawRoundedRectangleRect(bdrRect, 2)

# ---------------------------------------------------------------------------- #
# Class FMRendererXP
# ---------------------------------------------------------------------------- #

[docs]class FMRendererXP(FMRenderer):
    """ Xp-Style renderer. """

[docs]    def __init__(self):
        """ Default class constructor. """

        FMRenderer.__init__(self)

        self.drawLeftMargin = True
        self.separatorHeight = 3
        self.highlightCheckAndRadio = True
        self.scrollBarButtons = True   # Display scrollbar buttons if the menu doesn't fit on the screen

        self.buttonBorderColour        = wx.SystemSettings_GetColour(wx.SYS_COLOUR_ACTIVECAPTION)
        self.buttonFaceColour          = ArtManager.Get().LightColour(self.buttonBorderColour, 75)
        self.buttonFocusBorderColour   = wx.SystemSettings_GetColour(wx.SYS_COLOUR_ACTIVECAPTION)
        self.buttonFocusFaceColour     = ArtManager.Get().LightColour(self.buttonFocusBorderColour, 75)
        self.buttonPressedBorderColour = wx.SystemSettings_GetColour(wx.SYS_COLOUR_ACTIVECAPTION)
        self.buttonPressedFaceColour   = ArtManager.Get().LightColour(self.buttonPressedBorderColour, 60)

        self.menuFocusBorderColour   = wx.SystemSettings_GetColour(wx.SYS_COLOUR_ACTIVECAPTION)
        self.menuFocusFaceColour     = ArtManager.Get().LightColour(self.buttonFocusBorderColour, 75)
        self.menuPressedBorderColour = wx.SystemSettings_GetColour(wx.SYS_COLOUR_ACTIVECAPTION)
        self.menuPressedFaceColour   = ArtManager.Get().LightColour(self.buttonPressedBorderColour, 60)

        self.menuBarFocusBorderColour   = wx.SystemSettings_GetColour(wx.SYS_COLOUR_ACTIVECAPTION)
        self.menuBarFocusFaceColour     = ArtManager.Get().LightColour(self.buttonFocusBorderColour, 75)
        self.menuBarPressedBorderColour = wx.SystemSettings_GetColour(wx.SYS_COLOUR_ACTIVECAPTION)
        self.menuBarPressedFaceColour   = ArtManager.Get().LightColour(self.buttonPressedBorderColour, 60)

[docs]    def DrawLeftMargin(self, item, dc, menuRect):
        """
        Draws the menu left margin.

        :param `item`: the L{FlatMenuItem} to paint;
        :param `dc`: an instance of `wx.DC`;
        :param `menuRect`: an instance of `wx.Rect`, representing the menu client rectangle.
        """

        # Construct the margin rectangle
        marginRect = wx.Rect(menuRect.x+1, menuRect.y, item._parentMenu.GetLeftMarginWidth(), menuRect.height)

        # Set the gradient colours
        artMgr = ArtManager.Get()
        faceColour = self.menuFaceColour

        startColour = artMgr.DarkColour(faceColour, 20)
        endColour   = faceColour
        artMgr.PaintStraightGradientBox(dc, marginRect, startColour, endColour, False)

[docs]    def DrawMenuBarBackground(self, dc, rect):
        """
        Draws the menu bar background according to the active theme.

        :param `dc`: an instance of `wx.DC`;
        :param `rect`: an instance of `wx.Rect`, representing the menubar client rectangle.
        """

        # For office style, we simple draw a rectangle with a gradient colouring
        artMgr = ArtManager.Get()
        vertical = artMgr.GetMBVerticalGradient()

        dcsaver = DCSaver(dc)

        # fill with gradient
        startColour = artMgr.GetMenuBarFaceColour()
        if artMgr.IsDark(startColour):
            startColour = artMgr.LightColour(startColour, 50)

        endColour = artMgr.LightColour(startColour, 90)
        artMgr.PaintStraightGradientBox(dc, rect, startColour, endColour, vertical)

        # Draw the border
        if artMgr.GetMenuBarBorder():

            dc.SetPen(wx.Pen(startColour))
            dc.SetBrush(wx.TRANSPARENT_BRUSH)
            dc.DrawRectangleRect(rect)

[docs]    def DrawToolBarBg(self, dc, rect):
        """
        Draws the toolbar background according to the active theme.

        :param `dc`: an instance of `wx.DC`;
        :param `rect`: an instance of `wx.Rect`, representing the toolbar client rectangle.
        """

        artMgr = ArtManager.Get()

        if not artMgr.GetRaiseToolbar():
            return

        # For office style, we simple draw a rectangle with a gradient colouring
        vertical = artMgr.GetMBVerticalGradient()

        dcsaver = DCSaver(dc)

        # fill with gradient
        startColour = artMgr.GetMenuBarFaceColour()
        if artMgr.IsDark(startColour):
            startColour = artMgr.LightColour(startColour, 50)

        startColour = artMgr.LightColour(startColour, 20)

        endColour   = artMgr.LightColour(startColour, 90)
        artMgr.PaintStraightGradientBox(dc, rect, startColour, endColour, vertical)
        artMgr.DrawBitmapShadow(dc, rect)

[docs]    def GetTextColourEnable(self):
        """ Returns the colour used for text colour when enabled. """

        return wx.BLACK

# ----------------------------------------------------------------------------
# File history (a.k.a. MRU, most recently used, files list)
# ----------------------------------------------------------------------------

[docs]def GetMRUEntryLabel(n, path):
    """
    Returns the string used for the MRU list items in the menu.

    :param integer `n`: the index of the file name in the MRU list;
    :param string `path`: the full path of the file name.

    :note: The index `n` is 0-based, as usual, but the strings start from 1.
    """

    # we need to quote '&' characters which are used for mnemonics
    pathInMenu = path.replace("&", "&&")
    return "&%d %s"%(n + 1, pathInMenu)

# ----------------------------------------------------------------------------
# File history management
# ----------------------------------------------------------------------------

[docs]class FileHistory(object):
    """
    The L{FileHistory} encapsulates a user interface convenience, the list of most
    recently visited files as shown on a menu (usually the File menu).

    L{FileHistory} can manage one or more file menus. More than one menu may be
    required in an MDI application, where the file history should appear on each MDI
    child menu as well as the MDI parent frame.
    """

[docs]    def __init__(self, maxFiles=9, idBase=wx.ID_FILE1):
        """
        Default class constructor.

        :param integer `maxFiles`: the maximum number of files that should be stored and displayed;
        :param integer `idBase`: defaults to ``wx.ID_FILE1`` and represents the id given to the first
         history menu item.

        :note: Since menu items can't share the same ID you should change `idBase` to one of
         your own defined IDs when using more than one L{FileHistory} in your application.
        """

        # The ID of the first history menu item (Doesn't have to be wxID_FILE1)
        self._idBase = idBase

        # Last n files
        self._fileHistory = []

        # Menus to maintain (may need several for an MDI app)
        self._fileMenus = []

        # Max files to maintain
        self._fileMaxFiles = maxFiles

[docs]    def GetMaxFiles(self):
        """ Returns the maximum number of files that can be stored. """

        return self._fileMaxFiles

    # Accessors

[docs]    def GetHistoryFile(self, index):
        """
        Returns the file at this index (zero-based).

        :param integer `index`: the index at which the file is stored in the file list (zero-based).
        """

        return self._fileHistory[index]

[docs]    def GetCount(self):
        """ Returns the number of files currently stored in the file history. """

        return len(self._fileHistory)

[docs]    def GetMenus(self):
        """
        Returns the list of menus that are managed by this file history object.

        :see: L{UseMenu}.
        """

        return self._fileMenus

    # Set/get base id

[docs]    def SetBaseId(self, baseId):
        """
        Sets the base identifier for the range used for appending items.

        :param integer `baseId`: the base identifier for the range used for appending items.
        """

        self._idBase = baseId

[docs]    def GetBaseId(self):
        """ Returns the base identifier for the range used for appending items. """

        return self._idBase

[docs]    def GetNoHistoryFiles(self):
        """ Returns the number of files currently stored in the file history. """

        return self.GetCount()

[docs]    def AddFileToHistory(self, fnNew):
        """
        Adds a file to the file history list, if the object has a pointer to an
        appropriate file menu.

        :param string `fnNew`: the file name to add to the history list.
        """

        # check if we don't already have this file
        numFiles = len(self._fileHistory)

        for index, fileH in enumerate(self._fileHistory):
            if fnNew == fileH:
                # we do have it, move it to the top of the history
                self.RemoveFileFromHistory(index)
                numFiles -= 1
                break

        # if we already have a full history, delete the one at the end
        if numFiles == self._fileMaxFiles:
            self.RemoveFileFromHistory(numFiles-1)

        # add a new menu item to all file menus (they will be updated below)
        for menu in self._fileMenus:
            if numFiles == 0 and menu.GetMenuItemCount() > 0:
                menu.AppendSeparator()

            # label doesn't matter, it will be set below anyhow, but it can't
            # be empty (this is supposed to indicate a stock item)
            menu.Append(self._idBase + numFiles, " ")

        # insert the new file in the beginning of the file history
        self._fileHistory.insert(0, fnNew)
        numFiles += 1

        # update the labels in all menus
        for index in xrange(numFiles):

            # if in same directory just show the filename otherwise the full path
            fnOld = self._fileHistory[index]
            oldPath, newPath = os.path.split(fnOld)[0], os.path.split(fnNew)[0]

            if oldPath == newPath:
                pathInMenu = os.path.split(fnOld)[1]

            else:
                # file in different directory
                # absolute path could also set relative path
                pathInMenu = self._fileHistory[index]

            for menu in self._fileMenus:
                menu.SetLabel(self._idBase + index, GetMRUEntryLabel(index, pathInMenu))

[docs]    def RemoveFileFromHistory(self, index):
        """
        Removes the specified file from the history.

        :param integer `index`: the zero-based index indicating the file name position in
         the file list.
        """

        numFiles = len(self._fileHistory)
        if index >= numFiles:
            raise Exception("Invalid index in RemoveFileFromHistory: %d (only %d files)"%(index, numFiles))

        # delete the element from the array
        self._fileHistory.pop(index)
        numFiles -= 1

        for menu in self._fileMenus:
            # shift filenames up
            for j in xrange(numFiles):
                menu.SetLabel(self._idBase + j, GetMRUEntryLabel(j, self._fileHistory[j]))

            # delete the last menu item which is unused now
            lastItemId = self._idBase + numFiles
            if menu.FindItem(lastItemId):
                menu.Delete(lastItemId)

            if not self._fileHistory:
                lastMenuItem = menu.GetMenuItems()[-1]
                if lastMenuItem.IsSeparator():
                    menu.Delete(lastMenuItem)

                #else: menu is empty somehow

[docs]    def UseMenu(self, menu):
        """
        Adds this menu to the list of those menus that are managed by this file history
        object.

        :param `menu`: an instance of L{FlatMenu}.

        :see: L{AddFilesToMenu} for initializing the menu with filenames that are already
         in the history when this function is called, as this is not done automatically.
        """

        if menu not in self._fileMenus:
            self._fileMenus.append(menu)

[docs]    def RemoveMenu(self, menu):
        """
        Removes this menu from the list of those managed by this object.

        :param `menu`: an instance of L{FlatMenu}.
        """

        self._fileMenus.remove(menu)

[docs]    def Load(self, config):
        """
        Loads the file history from the given `config` object.

        :param `config`: an instance of `wx.Config`.

        :note: This function should be called explicitly by the application.

        :see: L{Save}.
        """

        self._fileHistory = []
        buffer = "file%d"
        count = 1

        while 1:
            historyFile = config.Read(buffer%count)
            if not historyFile or len(self._fileHistory) >= self._fileMaxFiles:
                break

            self._fileHistory.append(historyFile)
            count += 1

        self.AddFilesToMenu()

[docs]    def Save(self, config):
        """
        Saves the file history to the given `config` object.

        :param `config`: an instance of `wx.Config`.

        :note: This function should be called explicitly by the application.

        :see: L{Load}.
        """

        buffer = "file%d"

        for index in xrange(self._fileMaxFiles):

            if index < len(self._fileHistory):
                config.Write(buffer%(index+1), self._fileHistory[i])
            else:
                config.Write(buffer%(index+1), "")

[docs]    def AddFilesToMenu(self, menu=None):
        """
        Appends the files in the history list, to all menus managed by the file history object
        if `menu` is ``None``. Otherwise it calls the auxiliary method L{AddFilesToMenu2}.

        :param `menu`: if not ``None``, an instance of L{FlatMenu}.
        """

        if not self._fileHistory:
            return

        if menu is not None:
            self.AddFilesToMenu2(menu)
            return

        for menu in self._fileMenus:
            self.AddFilesToMenu2(menu)

[docs]    def AddFilesToMenu2(self, menu):
        """
        Appends the files in the history list, to the given menu only.

        :param `menu`: an instance of L{FlatMenu}.
        """

        if not self._fileHistory:
            return

        if menu.GetMenuItemCount():
            menu.AppendSeparator()

        for index in xrange(len(self._fileHistory)):
            menu.Append(self._idBase + index, GetMRUEntryLabel(index, self._fileHistory[i]))

# ---------------------------------------------------------------------------- #
# Class FlatMenuEvent
# ---------------------------------------------------------------------------- #

[docs]class FlatMenuEvent(wx.PyCommandEvent):
    """
    Event class that supports the L{FlatMenu}-compatible event called
    ``EVT_FLAT_MENU_SELECTED``.
    """

[docs]    def __init__(self, eventType, eventId=1):
        """
        Default class constructor.

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

        wx.PyCommandEvent.__init__(self, eventType, eventId)
        self._eventType = eventType

# ---------------------------------------------------------------------------- #
# Class MenuEntryInfo
# ---------------------------------------------------------------------------- #

[docs]class MenuEntryInfo(object):
    """
    Internal class which holds information about a menu.
    """

[docs]    def __init__(self, titleOrMenu="", menu=None, state=ControlNormal, cmd=wx.ID_ANY):
        """
        Default class constructor.

        Used internally. Do not call it in your code!

        :param `titleOrMenu`: if it is a string, it represents the new menu label,
         otherwise it is another instance of L{MenuEntryInfo} from which the attributes
         are copied;
        :param `menu`: the associated L{FlatMenu} object;
        :param integer `state`: the menu item state. This can be one of the following:

         ==================== ======= ==========================
         Item State            Value  Description
         ==================== ======= ==========================
         ``ControlPressed``         0 The item is pressed
         ``ControlFocus``           1 The item is focused
         ``ControlDisabled``        2 The item is disabled
         ``ControlNormal``          3 Normal state
         ==================== ======= ==========================

        :param integer `cmd`: the menu accelerator identifier.
        """

        if isinstance(titleOrMenu, basestring):

            self._title = titleOrMenu
            self._menu = menu

            self._rect = wx.Rect()
            self._state = state
            if cmd == wx.ID_ANY:
                cmd = wx.NewId()

            self._cmd = cmd             # the menu itself accelerator id

        else:

            self._title = titleOrMenu._title
            self._menu = titleOrMenu._menu
            self._rect = titleOrMenu._rect
            self._state = titleOrMenu._state
            self._cmd = titleOrMenu._cmd

        self._textBmp = wx.NullBitmap
        self._textSelectedBmp = wx.NullBitmap

[docs]    def GetTitle(self):
        """ Returns the associated menu title. """

        return self._title

[docs]    def GetMenu(self):
        """ Returns the associated menu. """

        return self._menu

[docs]    def SetRect(self, rect):
        """
        Sets the associated menu client rectangle.

        :param `rect`: an instance of `wx.Rect`, representing the menu client rectangle.
        """

        self._rect = rect

[docs]    def GetRect(self):
        """ Returns the associated menu client rectangle. """

        return self._rect

[docs]    def SetState(self, state):
        """
        Sets the associated menu state.

        :param integer `state`: the menu item state. This can be one of the following:

         ==================== ======= ==========================
         Item State            Value  Description
         ==================== ======= ==========================
         ``ControlPressed``         0 The item is pressed
         ``ControlFocus``           1 The item is focused
         ``ControlDisabled``        2 The item is disabled
         ``ControlNormal``          3 Normal state
         ==================== ======= ==========================
        """

        self._state = state

[docs]    def GetState(self):
        """
        Returns the associated menu state.

        :see: L{SetState} for a list of valid menu states.
        """

        return self._state

[docs]    def SetTextBitmap(self, bmp):
        """
        Sets the associated menu bitmap.

        :param `bmp`: a valid `wx.Bitmap` object.
        """

        self._textBmp = bmp

[docs]    def SetSelectedTextBitmap(self, bmp):
        """
        Sets the associated selected menu bitmap.

        :param `bmp`: a valid `wx.Bitmap` object.
        """

        self._textSelectedBmp = bmp

[docs]    def GetTextBitmap(self):
        """ Returns the associated menu bitmap. """

        return self._textBmp

[docs]    def GetSelectedTextBitmap(self):
        """ Returns the associated selected menu bitmap. """

        return self._textSelectedBmp

[docs]    def GetCmdId(self):
        """ Returns the associated menu accelerator identifier. """

        return self._cmd

# ---------------------------------------------------------------------------- #
# Class StatusBarTimer
# ---------------------------------------------------------------------------- #

[docs]class StatusBarTimer(wx.Timer):
    """ Timer used for deleting `wx.StatusBar` long help after ``_DELAY`` seconds. """

[docs]    def __init__(self, owner):
        """
        Default class constructor.
        For internal use: do not call it in your code!

        :param `owner`: the `wx.Timer` owner (L{FlatMenuBar}).
        """

        wx.Timer.__init__(self)
        self._owner = owner

[docs]    def Notify(self):
        """ The timer has expired. """

        self._owner.OnStatusBarTimer()

# ---------------------------------------------------------------------------- #
# Class FlatMenuBar
# ---------------------------------------------------------------------------- #

[docs]class FlatMenuBar(wx.Panel):
    """
    Implements the generic owner-drawn menu bar for L{FlatMenu}.
    """

[docs]    def __init__(self, parent, id=wx.ID_ANY, iconSize=SmallIcons,
                 spacer=SPACER, options=FM_OPT_SHOW_CUSTOMIZE|FM_OPT_IS_LCD):
        """
        Default class constructor.

        :param `parent`: the menu bar parent, must not be ``None``;
        :param integer `id`: the window identifier. If ``wx.ID_ANY``, will automatically create an identifier;
        :param integer `iconSize`: size of the icons in the toolbar. This can be one of the
         following values (in pixels):

         ==================== ======= =============================
         `iconSize` Bit        Value  Description
         ==================== ======= =============================
         ``LargeIcons``            32 Use large 32x32 icons
         ``SmallIcons``            16 Use standard 16x16 icons
         ==================== ======= =============================

        :param integer `spacer`: the space between the menu bar text and the menu bar border;
        :param integer `options`: a combination of the following bits:

         ========================= ========= =============================
         `options` Bit             Hex Value  Description
         ========================= ========= =============================
         ``FM_OPT_IS_LCD``               0x1 Use this style if your computer uses a LCD screen
         ``FM_OPT_MINIBAR``              0x2 Use this if you plan to use toolbar only
         ``FM_OPT_SHOW_CUSTOMIZE``       0x4 Show "customize link" in more menus, you will need to write your own handler. See demo.
         ``FM_OPT_SHOW_TOOLBAR``         0x8 Set this option is you are planing to use the toolbar
         ========================= ========= =============================

        """

        self._rendererMgr = FMRendererMgr()
        self._parent = parent
        self._curretHiliteItem = -1

        self._items = []
        self._dropDownButtonArea = wx.Rect()
        self._tbIconSize = iconSize
        self._tbButtons = []
        self._interval = 20      # 20 milliseconds
        self._showTooltip = -1

        self._haveTip = False
        self._statusTimer = None
        self._spacer = SPACER
        self._margin = spacer
        self._toolbarSpacer = TOOLBAR_SPACER
        self._toolbarMargin = TOOLBAR_MARGIN

        self._showToolbar = options & FM_OPT_SHOW_TOOLBAR
        self._showCustomize = options & FM_OPT_SHOW_CUSTOMIZE
        self._isLCD = options & FM_OPT_IS_LCD
        self._isMinibar = options & FM_OPT_MINIBAR
        self._options = options

        self._dropDownButtonState = ControlNormal
        self._moreMenu = None
        self._dlg = None
        self._tbMenu = None
        self._moreMenuBgBmp = None
        self._lastRadioGroup = 0
        self._mgr = None

        self._barHeight = 0
        self._menuBarHeight = 0
        self.SetBarHeight()

        wx.Panel.__init__(self, parent, id, size=(-1, self._barHeight), style=wx.WANTS_CHARS)

        self.Bind(wx.EVT_ERASE_BACKGROUND, self.OnEraseBackground)
        self.Bind(wx.EVT_PAINT, self.OnPaint)
        self.Bind(wx.EVT_SIZE, self.OnSize)
        self.Bind(wx.EVT_MOTION, self.OnMouseMove)
        self.Bind(EVT_FLAT_MENU_DISMISSED, self.OnMenuDismissed)
        self.Bind(wx.EVT_LEAVE_WINDOW, self.OnLeaveMenuBar)
        self.Bind(wx.EVT_LEFT_DOWN, self.OnLeftDown)
        self.Bind(wx.EVT_LEFT_DCLICK, self.OnLeftDown)
        self.Bind(wx.EVT_LEFT_UP, self.OnLeftUp)
        self.Bind(wx.EVT_IDLE, self.OnIdle)

        if "__WXGTK__" in wx.Platform:
            self.Bind(wx.EVT_LEAVE_WINDOW, self.OnLeaveWindow)

        self.SetFocus()

        # start the stop watch
        self._watch = wx.StopWatch()
        self._watch.Start()

[docs]    def Append(self, menu, title):
        """
        Adds the item to the end of the menu bar.

        :param `menu`: the menu to which we are appending a new item, an instance of L{FlatMenu};
        :param string `title`: the menu item label, must not be empty.

        :see: L{Insert}.
        """

        menu._menuBarFullTitle = title
        position, label = GetAccelIndex(title)
        menu._menuBarLabelOnly = label

        return self.Insert(len(self._items), menu, title)

[docs]    def OnIdle(self, event):
        """
        Handles the ``wx.EVT_IDLE`` event for L{FlatMenuBar}.

        :param `event`: a `wx.IdleEvent` event to be processed.
        """

        refresh = False

        if self._watch.Time() > self._interval:

            # it is time to process UpdateUIEvents
            for but in self._tbButtons:
                event = wx.UpdateUIEvent(but._tbItem.GetId())
                event.Enable(but._tbItem.IsEnabled())
                event.SetText(but._tbItem.GetLabel())
                event.SetEventObject(self)

                self.GetEventHandler().ProcessEvent(event)

                if but._tbItem.GetLabel() != event.GetText() or but._tbItem.IsEnabled() != event.GetEnabled():
                    refresh = True

                but._tbItem.SetLabel(event.GetText())
                but._tbItem.Enable(event.GetEnabled())

            self._watch.Start() # Reset the timer

        # we need to update the menu bar
        if refresh:
            self.Refresh()

[docs]    def SetBarHeight(self):
        """ Recalculates the L{FlatMenuBar} height when its settings change. """

        mem_dc = wx.MemoryDC()
        mem_dc.SelectObject(wx.EmptyBitmap(1, 1))
        dummy, self._barHeight = mem_dc.GetTextExtent("Tp")
        mem_dc.SelectObject(wx.NullBitmap)

        if not self._isMinibar:
            self._barHeight += 2*self._margin # The menu bar margin
        else:
            self._barHeight  = 0

        self._menuBarHeight = self._barHeight

        if self._showToolbar :
            # add the toolbar height to the menubar height
            self._barHeight += self._tbIconSize + 2*self._toolbarMargin

        if self._mgr is None:
            return

        pn = self._mgr.GetPane("flat_menu_bar")
        pn.MinSize(wx.Size(-1, self._barHeight))
        self._mgr.Update()
        self.Refresh()

[docs]    def SetOptions(self, options):
        """
        Sets the L{FlatMenuBar} options, whether to show a toolbar, to use LCD screen settings etc...

        :param integer `options`: a combination of the following bits:

         ========================= ========= =============================
         `options` Bit             Hex Value  Description
         ========================= ========= =============================
         ``FM_OPT_IS_LCD``               0x1 Use this style if your computer uses a LCD screen
         ``FM_OPT_MINIBAR``              0x2 Use this if you plan to use toolbar only
         ``FM_OPT_SHOW_CUSTOMIZE``       0x4 Show "customize link" in more menus, you will need to write your own handler. See demo.
         ``FM_OPT_SHOW_TOOLBAR``         0x8 Set this option is you are planing to use the toolbar
         ========================= ========= =============================

        """

        self._options = options

        self._showToolbar = options & FM_OPT_SHOW_TOOLBAR
        self._showCustomize = options & FM_OPT_SHOW_CUSTOMIZE
        self._isLCD = options & FM_OPT_IS_LCD
        self._isMinibar = options & FM_OPT_MINIBAR

        self.SetBarHeight()

        self.Refresh()
        self.Update()

[docs]    def GetOptions(self):
        """
        Returns the L{FlatMenuBar} options, whether to show a toolbar, to use LCD screen settings etc...

        :see: L{SetOptions} for a list of valid options.
        """

        return self._options

[docs]    def GetRendererManager(self):
        """
        Returns the L{FlatMenuBar} renderer manager.
        """

        return self._rendererMgr

[docs]    def GetRenderer(self):
        """
        Returns the renderer associated with this instance.
        """

        return self._rendererMgr.GetRenderer()

[docs]    def UpdateItem(self, item):
        """
        An item was modified. This function is called by L{FlatMenu} in case
        an item was modified directly and not via a `wx.UpdateUIEvent` event.

        :param `item`: an instance of L{FlatMenu}.
        """

        if not self._showToolbar:
            return

        # search for a tool bar with id
        refresh = False

        for but in self._tbButtons:
            if but._tbItem.GetId() == item.GetId():
                if but._tbItem.IsEnabled() != item.IsEnabled():
                    refresh = True

                but._tbItem.Enable(item.IsEnabled())
                break

        if refresh:
            self.Refresh()

[docs]    def OnPaint(self, event):
        """
        Handles the ``wx.EVT_PAINT`` event for L{FlatMenuBar}.

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

        # on GTK, dont use the bitmap for drawing,
        # draw directly on the DC

        if "__WXGTK__" in wx.Platform and not self._isLCD:
            self.ClearBitmaps(0)

        dc = wx.BufferedPaintDC(self)
        self.GetRenderer().DrawMenuBar(self, dc)

[docs]    def DrawToolbar(self, dc, rect):
        """
        Draws the toolbar (if present).

        :param `dc`: an instance of `wx.DC`;
        :param `rect`: the toolbar client rectangle, an instance of `wx.Rect`.
        """

        highlight_width = self._tbIconSize + self._toolbarSpacer
        highlight_height = self._tbIconSize + self._toolbarMargin

        xx = rect.x + self._toolbarMargin
        #yy = rect.y #+ self._toolbarMargin #+ (rect.height - height)/2

        # by default set all toolbar items as invisible
        for but in self._tbButtons:
            but._visible = False

        counter = 0
        # Get all the toolbar items
        for i in xrange(len(self._tbButtons)):

            xx += self._toolbarSpacer

            tbItem = self._tbButtons[i]._tbItem
            # the button width depends on its type
            if tbItem.IsSeparator():
                hightlight_width = SEPARATOR_WIDTH
            elif tbItem.IsCustomControl():
                control = tbItem.GetCustomControl()
                hightlight_width = control.GetSize().x + self._toolbarSpacer
            else:
                hightlight_width = self._tbIconSize + self._toolbarSpacer   # normal bitmap's width

            # can we keep drawing?
            if xx + highlight_width >= rect.width:
                break

            counter += 1

            # mark this item as visible
            self._tbButtons[i]._visible = True

            bmp = wx.NullBitmap

            #------------------------------------------
            # special handling for separator
            #------------------------------------------
            if tbItem.IsSeparator():

                # draw the separator
                buttonRect = wx.Rect(xx, rect.y+1, SEPARATOR_WIDTH, rect.height-2)
                self.GetRenderer().DrawToolbarSeparator(dc, buttonRect)

                xx += buttonRect.width
                self._tbButtons[i]._rect = buttonRect
                continue

            elif tbItem.IsCustomControl():
                control = tbItem.GetCustomControl()
                ctrlSize = control.GetSize()
                ctrlPos = wx.Point(xx, rect.y + (rect.height - ctrlSize.y)/2)
                if control.GetPosition() != ctrlPos:
                    control.SetPosition(ctrlPos)

                if not control.IsShown():
                    control.Show()

                buttonRect = wx.RectPS(ctrlPos, ctrlSize)
                xx += buttonRect.width
                self._tbButtons[i]._rect = buttonRect
                continue
            else:
                if tbItem.IsEnabled():
                    bmp = tbItem.GetBitmap()
                else:
                    bmp = tbItem.GetDisabledBitmap()

            # Draw the toolbar image
            if bmp.Ok():

                x = xx - self._toolbarSpacer/2
                #y = rect.y + (rect.height - bmp.GetHeight())/2 - 1
                y = rect.y + self._toolbarMargin/2

                buttonRect = wx.Rect(x, y, highlight_width, highlight_height)

                if i < len(self._tbButtons) and i >= 0:

                    if self._tbButtons[i]._tbItem.IsSelected():
                        tmpState = ControlPressed
                    else:
                        tmpState = ControlFocus

                    if self._tbButtons[i]._state == ControlFocus or self._tbButtons[i]._tbItem.IsSelected():
                        self.GetRenderer().DrawMenuBarButton(dc, buttonRect, tmpState) # TODO DrawToolbarButton? With separate toolbar colors
                    else:
                        self._tbButtons[i]._state = ControlNormal

                imgx = buttonRect.x + (buttonRect.width - bmp.GetWidth())/2
                imgy = buttonRect.y + (buttonRect.height - bmp.GetHeight())/2

                if self._tbButtons[i]._state == ControlFocus and not self._tbButtons[i]._tbItem.IsSelected():

                    # in case we the button is in focus, place it
                    # once pixle up and left
                    # place a dark image under the original image to provide it
                    # with some shadow
                    # shadow = ConvertToMonochrome(bmp)
                    # dc.DrawBitmap(shadow, imgx, imgy, True)

                    imgx -= 1
                    imgy -= 1

                dc.DrawBitmap(bmp, imgx, imgy, True)
                xx += buttonRect.width

                self._tbButtons[i]._rect = buttonRect
                #Edited by P.Kort

                if self._showTooltip == -1:
                    self.RemoveHelp()
                else:
                    try:
                        self.DoGiveHelp(self._tbButtons[self._showTooltip]._tbItem)
                    except:
                        if _debug:
                            print "FlatMenu.py; fn : DrawToolbar; Can't create Tooltip "
                        pass

        for j in xrange(counter, len(self._tbButtons)):
            if self._tbButtons[j]._tbItem.IsCustomControl():
                control = self._tbButtons[j]._tbItem.GetCustomControl()
                control.Hide()

[docs]    def GetMoreMenuButtonRect(self):
        """ Returns a rectangle region, as an instance of `wx.Rect`, surrounding the menu button. """

        clientRect = self.GetClientRect()
        rect = wx.Rect(*clientRect)
        rect.SetWidth(DROP_DOWN_ARROW_WIDTH)
        rect.SetX(clientRect.GetWidth() + rect.GetX() - DROP_DOWN_ARROW_WIDTH - 3)
        rect.SetY(2)
        rect.SetHeight(rect.GetHeight() - self._spacer)

        return rect

[docs]    def DrawMoreButton(self, dc, state):
        """
        Draws 'more' button to the right side of the menu bar.

        :param `dc`: an instance of `wx.DC`;
        :param integer `state`: the 'more' button state.

        :see: L{MenuEntryInfo.SetState} for a list of valid menu states.
        """

        if (not self._showCustomize) and self.GetInvisibleMenuItemCount() < 1 and  self.GetInvisibleToolbarItemCount() < 1:
            return

        # Draw a drop down menu at the right position of the menu bar
        # we use xpm file with 16x16 size, another 4 pixels we take as spacer
        # from the right side of the frame, this will create a DROP_DOWN_ARROW_WIDTH  pixels width
        # of unwanted zone on the right side

        rect = self.GetMoreMenuButtonRect()

        # Draw the bitmap
        if state != ControlNormal:
            # Draw background according to state
            self.GetRenderer().DrawButton(dc, rect, state)
        else:
            # Delete current image
            if self._moreMenuBgBmp.Ok():
                dc.DrawBitmap(self._moreMenuBgBmp, rect.x, rect.y, True)

        dropArrowBmp = self.GetRenderer()._bitmaps["arrow_down"]

        # Calc the image coordinates
        xx = rect.x + (DROP_DOWN_ARROW_WIDTH - dropArrowBmp.GetWidth())/2
        yy = rect.y + (rect.height - dropArrowBmp.GetHeight())/2

        dc.DrawBitmap(dropArrowBmp, xx, yy + self._spacer, True)
        self._dropDownButtonState = state

[docs]    def HitTest(self, pt):
        """
        HitTest method for L{FlatMenuBar}.

        :param `pt`: an instance of `wx.Point`, specifying the hit test position.

        :return: A tuple representing one of the following combinations:

         ========================= ==================================================
         Return Tuple              Description
         ========================= ==================================================
         (-1, 0)                   The L{HitTest} method didn't find any item with the specified input point `pt` (``NoWhere`` = 0)
         (`integer`, 1)            A menu item has been hit, its position specified by the tuple item `integer` (``MenuItem`` = 1)
         (`integer`, 2)            A toolbar item has ben hit, its position specified by the tuple item `integer` (``ToolbarItem`` = 2)
         (-1, 3)                   The drop-down area button has been hit (``DropDownArrowButton`` = 3)
         ========================= ==================================================

        """

        if self._dropDownButtonArea.Contains(pt):
            return -1, DropDownArrowButton

        for ii, item in enumerate(self._items):
            if item.GetRect().Contains(pt):
                return ii, MenuItem

        # check for tool bar items
        if self._showToolbar:
            for ii, but in enumerate(self._tbButtons):
                if but._rect.Contains(pt):
                    # locate the corresponded menu item
                    enabled  = but._tbItem.IsEnabled()
                    separator = but._tbItem.IsSeparator()
                    visible  = but._visible
                    if enabled and not separator and visible:
                        self._showTooltip = ii
                        return ii, ToolbarItem

        self._showTooltip = -1
        return -1, NoWhere

[docs]    def FindMenuItem(self, id):
        """
        Finds the menu item object associated with the given menu item identifier.

        :param integer `id`: the identifier for the sought L{FlatMenuItem}.

        :return: The found menu item object, or ``None`` if one was not found.
        """

        for item in self._items:
            mi = item.GetMenu().FindItem(id)
            if mi:
                return mi
        return None

[docs]    def OnSize(self, event):
        """
        Handles the ``wx.EVT_SIZE`` event for L{FlatMenuBar}.

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

        self.ClearBitmaps(0)
        self.Refresh()

[docs]    def OnEraseBackground(self, event):
        """
        Handles the ``wx.EVT_ERASE_BACKGROUND`` event for L{FlatMenuBar}.

        :param `event`: a `wx.EraseEvent` event to be processed.

        :note: This method is intentionally empty to reduce flicker.
        """

        pass

[docs]    def ShowCustomize(self, show=True):
        """
        Shows/hides the drop-down arrow which allows customization of L{FlatMenu}.

        :param bool `show`: ``True`` to show the customize menu, ``False`` to hide it.
        """

        if self._showCustomize == show:
            return

        self._showCustomize = show
        self.Refresh()

[docs]    def SetMargin(self, margin):
        """
        Sets the margin above and below the menu bar text.

        :param integer `margin`: height in pixels of the margin.
        """

        self._margin = margin

[docs]    def SetSpacing(self, spacer):
        """
        Sets the spacing between the menubar items.

        :param integer `spacer`: number of pixels between each menu item.
        """

        self._spacer = spacer

[docs]    def SetToolbarMargin(self, margin):
        """
        Sets the margin around the toolbar.

        :param integer `margin`: width in pixels of the margin around the tools in the toolbar.
        """

        self._toolbarMargin = margin

[docs]    def SetToolbarSpacing(self, spacer):
        """
        Sets the spacing between the toolbar tools.

        :param integer `spacer`: number of pixels between each tool in the toolbar.
        """

        self._toolbarSpacer = spacer

[docs]    def SetLCDMonitor(self, lcd=True):
        """
        Sets whether the PC monitor is an LCD or not.

        :param bool `lcd`: ``True`` to use the settings appropriate for a LCD monitor,
         ``False`` otherwise.
        """

        if self._isLCD == lcd:
            return

        self._isLCD = lcd
        self.Refresh()

[docs]    def ProcessMouseMoveFromMenu(self, pt):
        """
        This function is called from child menus, this allow a child menu to
        pass the mouse movement event to the menu bar.

        :param `pt`: an instance of `wx.Point`.
        """

        idx, where = self.HitTest(pt)
        if where == MenuItem:
            self.ActivateMenu(self._items[idx])

[docs]    def DoMouseMove(self, pt, leftIsDown):
        """
        Handles mouse move event.

        :param `pt`: an instance of `wx.Point`;
        :param bool `leftIsDown`: ``True`` is the left mouse button is down, ``False`` otherwise.
        """

        # Reset items state
        for item in self._items:
            item.SetState(ControlNormal)

        idx, where = self.HitTest(pt)

        if where == DropDownArrowButton:
            self.RemoveHelp()
            if self._dropDownButtonState != ControlFocus and not leftIsDown:
                dc = wx.ClientDC(self)
                self.DrawMoreButton(dc, ControlFocus)

        elif where == MenuItem:
            self._dropDownButtonState = ControlNormal
            # On Item
            self._items[idx].SetState(ControlFocus)

            # If this item is already selected, dont draw it again
            if self._curretHiliteItem == idx:
                return

            self._curretHiliteItem = idx
            if self._showToolbar:

                # mark all toolbar items as non-hilited
                for but in self._tbButtons:
                    but._state = ControlNormal

            self.Refresh()

        elif where == ToolbarItem:

            if self._showToolbar:
                if idx < len(self._tbButtons) and idx >= 0:
                    if self._tbButtons[idx]._state == ControlFocus:
                        return

                    # we need to refresh the toolbar
                    active = self.GetActiveToolbarItem()
                    if active != wx.NOT_FOUND:
                        self._tbButtons[active]._state = ControlNormal

                    for but in self._tbButtons:
                        but._state = ControlNormal

                    self._tbButtons[idx]._state = ControlFocus
                    self.DoGiveHelp(self._tbButtons[idx]._tbItem)
                    self.Refresh()

        elif where == NoWhere:

            refresh = False
            self.RemoveHelp()

            if self._dropDownButtonState != ControlNormal:
                refresh = True
                self._dropDownButtonState = ControlNormal

            if self._showToolbar:
                tbActiveItem = self.GetActiveToolbarItem()
                if tbActiveItem != wx.NOT_FOUND:
                    self._tbButtons[tbActiveItem]._state = ControlNormal
                    refresh = True

            if self._curretHiliteItem != -1:

                self._items[self._curretHiliteItem].SetState(ControlNormal)
                self._curretHiliteItem = -1
                self.Refresh()

            if refresh:
                self.Refresh()

[docs]    def OnMouseMove(self, event):
        """
        Handles the ``wx.EVT_MOTION`` event for L{FlatMenuBar}.

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

        pt = event.GetPosition()
        self.DoMouseMove(pt, event.LeftIsDown())

[docs]    def OnLeaveMenuBar(self, event):
        """
        Handles the ``wx.EVT_LEAVE_WINDOW`` event for L{FlatMenuBar}.

        :param `event`: a `wx.MouseEvent` event to be processed.

        :note: This method is for MSW only.
        """

        pt = event.GetPosition()
        self.DoMouseMove(pt, event.LeftIsDown())

[docs]    def ResetToolbarItems(self):
        """ Used internally. """

        for but in self._tbButtons:
            but._state = ControlNormal

[docs]    def GetActiveToolbarItem(self):
        """ Returns the active toolbar item. """

        for but in self._tbButtons:

            if but._state == ControlFocus or but._state == ControlPressed:
                return self._tbButtons.index(but)

        return wx.NOT_FOUND

[docs]    def GetBackgroundColour(self):
        """ Returns the menu bar background colour. """

        return self.GetRenderer().menuBarFaceColour

[docs]    def SetBackgroundColour(self, colour):
        """
        Sets the menu bar background colour.

        :param `colour`: a valid `wx.Colour`.
        """

        self.GetRenderer().menuBarFaceColour = colour

[docs]    def OnLeaveWindow(self, event):
        """
        Handles the ``wx.EVT_LEAVE_WINDOW`` event for L{FlatMenuBar}.

        :param `event`: a `wx.MouseEvent` event to be processed.

        :note: This method is for GTK only.
        """

        self._curretHiliteItem = -1
        self._dropDownButtonState = ControlNormal

        # Reset items state
        for item in self._items:
            item.SetState(ControlNormal)

        for but in self._tbButtons:
            but._state = ControlNormal

        self.Refresh()

[docs]    def OnMenuDismissed(self, event):
        """
        Handles the ``EVT_FLAT_MENU_DISMISSED`` event for L{FlatMenuBar}.

        :param `event`: a L{FlatMenuEvent} event to be processed.
        """

        pt = wx.GetMousePosition()
        pt = self.ScreenToClient(pt)

        idx, where = self.HitTest(pt)
        self.RemoveHelp()

        if where not in [MenuItem, DropDownArrowButton]:
            self._dropDownButtonState = ControlNormal
            self._curretHiliteItem = -1
            for item in self._items:
                item.SetState(ControlNormal)

            self.Refresh()

[docs]    def OnLeftDown(self, event):
        """
        Handles the ``wx.EVT_LEFT_DOWN`` event for L{FlatMenuBar}.

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

        pt = event.GetPosition()
        idx, where = self.HitTest(pt)

        if where == DropDownArrowButton:
            dc = wx.ClientDC(self)
            self.DrawMoreButton(dc, ControlPressed)
            self.PopupMoreMenu()

        elif where == MenuItem:
            # Position the menu, the GetPosition() return the coords
            # of the button relative to its parent, we need to translate
            # them into the screen coords
            self.ActivateMenu(self._items[idx])

        elif where == ToolbarItem:
            redrawAll = False
            item = self._tbButtons[idx]._tbItem
            # try to toggle if its a check item:
            item.Toggle()
            # switch is if its a unselected radio item
            if not item.IsSelected() and item.IsRadioItem():
                group = item.GetGroup()
                for i in xrange(len(self._tbButtons)):
                    if self._tbButtons[i]._tbItem.GetGroup() == group and \
                      i != idx and self._tbButtons[i]._tbItem.IsSelected():
                        self._tbButtons[i]._state = ControlNormal
                        self._tbButtons[i]._tbItem.Select(False)
                        redrawAll = True
                item.Select(True)
            # Over a toolbar item
            if redrawAll:
                self.Refresh()
                if "__WXMSW__" in wx.Platform:
                    dc = wx.BufferedDC(wx.ClientDC(self))
                else:
                    dc = wx.ClientDC(self)
            else:
                dc = wx.ClientDC(self)
                self.DrawToolbarItem(dc, idx, ControlPressed)

            # TODO:: Do the action specified in this button
            self.DoToolbarAction(idx)

[docs]    def OnLeftUp(self, event):
        """
        Handles the ``wx.EVT_LEFT_UP`` event for L{FlatMenuBar}.

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

        pt = event.GetPosition()
        idx, where = self.HitTest(pt)

        if where == ToolbarItem:
            # Over a toolbar item
            dc = wx.ClientDC(self)
            self.DrawToolbarItem(dc, idx, ControlFocus)

[docs]    def DrawToolbarItem(self, dc, idx, state):
        """
        Draws a toolbar item button.

        :param `dc`: an instance of `wx.DC`;
        :param integer `idx`: the tool index in the toolbar;
        :param integer `state`: the button state.

        :see: L{MenuEntryInfo.SetState} for a list of valid menu states.
        """

        if idx >= len(self._tbButtons) or idx < 0:
            return

        if self._tbButtons[idx]._tbItem.IsSelected():
            state = ControlPressed
        rect = self._tbButtons[idx]._rect
        self.GetRenderer().DrawButton(dc, rect, state)

        # draw the bitmap over the highlight
        buttonRect = wx.Rect(*rect)
        x = rect.x + (buttonRect.width - self._tbButtons[idx]._tbItem.GetBitmap().GetWidth())/2
        y = rect.y + (buttonRect.height - self._tbButtons[idx]._tbItem.GetBitmap().GetHeight())/2

        if state == ControlFocus:

            # place a dark image under the original image to provide it
            # with some shadow
            # shadow = ConvertToMonochrome(self._tbButtons[idx]._tbItem.GetBitmap())
            # dc.DrawBitmap(shadow, x, y, True)

            # in case we the button is in focus, place it
            # once pixle up and left
            x -= 1
            y -= 1
        dc.DrawBitmap(self._tbButtons[idx]._tbItem.GetBitmap(), x, y, True)

[docs]    def ActivateMenu(self, menuInfo):
        """
        Activates a menu.

        :param `menuInfo`: an instance of L{MenuEntryInfo}.
        """

        # first make sure all other menus are not popedup
        if menuInfo.GetMenu().IsShown():
            return

        idx = wx.NOT_FOUND

        for item in self._items:
            item.GetMenu().Dismiss(False, True)
            if item.GetMenu() == menuInfo.GetMenu():
                idx = self._items.index(item)

        # Remove the popup menu as well
        if self._moreMenu and self._moreMenu.IsShown():
            self._moreMenu.Dismiss(False, True)

        # make sure that the menu item button is highlited
        if idx != wx.NOT_FOUND:
            self._dropDownButtonState = ControlNormal
            self._curretHiliteItem = idx
            for item in self._items:
                item.SetState(ControlNormal)

            self._items[idx].SetState(ControlFocus)
            self.Refresh()

        rect = menuInfo.GetRect()
        menuPt = self.ClientToScreen(wx.Point(rect.x, rect.y))
        menuInfo.GetMenu().SetOwnerHeight(rect.height)
        menuInfo.GetMenu().Popup(wx.Point(menuPt.x, menuPt.y), self)

[docs]    def DoToolbarAction(self, idx):
        """
        Performs a toolbar button pressed action.

        :param integer `idx`: the tool index in the toolbar.
        """

        # we handle only button clicks
        tbItem = self._tbButtons[idx]._tbItem
        if tbItem.IsRegularItem() or tbItem.IsCheckItem() or tbItem.IsRadioItem():
            # Create the event
            event = wx.CommandEvent(wxEVT_FLAT_MENU_SELECTED, tbItem.GetId())
            event.SetEventObject(self)

            # all events are handled by this control and its parents
            self.GetEventHandler().ProcessEvent(event)

[docs]    def FindMenu(self, title):
        """
        Returns the index of the menu with the given title or ``wx.NOT_FOUND`` if
        no such menu exists in this menubar.

        :param string `title`: may specify either the menu title (with accelerator characters,
         i.e. "&File") or just the menu label ("File") indifferently.
        """

        for ii, item in enumerate(self._items):
            accelIdx, labelOnly = GetAccelIndex(item.GetTitle())

            if labelOnly == title or item.GetTitle() == title:
                return ii

        return wx.NOT_FOUND

[docs]    def GetMenu(self, menuIdx):
        """
        Returns the menu at the specified index `menuIdx` (zero-based).

        :param integer `menuIdx`: the index of the sought menu.

        :return: The found menu item object, or ``None`` if one was not found.
        """

        if menuIdx >= len(self._items) or menuIdx < 0:
            return None

        return self._items[menuIdx].GetMenu()

[docs]    def GetMenuCount(self):
        """ Returns the number of menus in the menubar. """

        return len(self._items)

[docs]    def Insert(self, pos, menu, title):
        """
        Inserts the menu at the given position into the menu bar.

        :param integer `pos`: the position of the new menu in the menu bar;
        :param `menu`: the menu to add, an instance of L{FlatMenu}. L{FlatMenuBar} owns the menu and will free it;
        :param string `title`: the title of the menu.

        :note: Inserting menu at position 0 will insert it in the very beginning of it,
         inserting at position L{GetMenuCount} is the same as calling L{Append}.
        """

        menu.SetMenuBar(self)
        self._items.insert(pos, MenuEntryInfo(title, menu))
        self.UpdateAcceleratorTable()

        self.ClearBitmaps(pos)
        self.Refresh()
        return True

[docs]    def Remove(self, pos):
        """
        Removes the menu from the menu bar and returns the menu object - the
        caller is responsible for deleting it.

        :param integer `pos`: the position of the menu in the menu bar.

        :note: This function may be used together with L{Insert} to change the menubar
         dynamically.
        """

        if pos >= len(self._items):
            return None

        menu = self._items[pos].GetMenu()
        self._items.pop(pos)
        self.UpdateAcceleratorTable()

        # Since we use bitmaps to optimize our drawings, we need
        # to reset all bitmaps from pos and until end of vector
        # to force size/position changes to the menu bar
        self.ClearBitmaps(pos)
        self.Refresh()

        # remove the connection to this menubar
        menu.SetMenuBar(None)
        return menu

[docs]    def UpdateAcceleratorTable(self):
        """ Updates the parent accelerator table. """

        # first get the number of items we have
        updatedTable = []
        parent = self.GetParent()

        for item in self._items:

            updatedTable = item.GetMenu().GetAccelArray() + updatedTable

            # create accelerator for every menu (if it exist)
            title = item.GetTitle()
            mnemonic, labelOnly = GetAccelIndex(title)

            if mnemonic != wx.NOT_FOUND:

                # Get the accelrator character
                accelChar = labelOnly[mnemonic]
                accelString = "\tAlt+" + accelChar
                title += accelString

                accel = wx.GetAccelFromString(title)
                itemId = item.GetCmdId()

                if accel:

                    # connect an event to this cmd
                    parent.Connect(itemId, -1, wxEVT_FLAT_MENU_SELECTED, self.OnAccelCmd)
                    accel.Set(accel.GetFlags(), accel.GetKeyCode(), itemId)
                    updatedTable.append(accel)

        entries = [wx.AcceleratorEntry() for ii in xrange(len(updatedTable))]

        # Add the new menu items
        for i in xrange(len(updatedTable)):
            entries[i] = updatedTable[i]

        table = wx.AcceleratorTable(entries)
        del entries

        parent.SetAcceleratorTable(table)

[docs]    def ClearBitmaps(self, start=0):
        """
        Restores a `wx.NullBitmap` for all the items in the menu.

        :param integer `start`: the index at which to start resetting the bitmaps.
        """

        if self._isLCD:
            return

        for item in self._items[start:]:
            item.SetTextBitmap(wx.NullBitmap)
            item.SetSelectedTextBitmap(wx.NullBitmap)

[docs]    def OnAccelCmd(self, event):
        """
        Single function to handle any accelerator key used inside the menubar.

        :param `event`: a L{FlatMenuEvent} event to be processed.
        """

        for item in self._items:
            if item.GetCmdId() == event.GetId():
                self.ActivateMenu(item)

[docs]    def ActivateNextMenu(self):
        """ Activates next menu and make sure all others are non-active. """

        last_item = self.GetLastVisibleMenu()
        # find the current active menu
        for i in xrange(last_item+1):
            if self._items[i].GetMenu().IsShown():
                nextMenu = i + 1
                if nextMenu >= last_item:
                    nextMenu = 0
                self.ActivateMenu(self._items[nextMenu])
                return

[docs]    def GetLastVisibleMenu(self):
        """ Returns the index of the last visible menu on the menu bar. """

        last_item = 0

        # find the last visible item
        rect = wx.Rect()

        for item in self._items:

            if item.GetRect() == rect:
                break

            last_item += 1

        return last_item

[docs]    def ActivatePreviousMenu(self):
        """ Activates previous menu and make sure all others are non-active. """

        # find the current active menu
        last_item = self.GetLastVisibleMenu()

        for i in xrange(last_item):
            if self._items[i].GetMenu().IsShown():
                prevMenu = i - 1
                if prevMenu < 0:
                    prevMenu = last_item - 1

                if prevMenu < 0:
                    return

                self.ActivateMenu(self._items[prevMenu])
                return

[docs]    def CreateMoreMenu(self):
        """ Creates the drop down menu and populate it. """

        if not self._moreMenu:
            # first time
            self._moreMenu = FlatMenu(self)
            self._popupDlgCmdId = wx.NewId()

            # Connect an event handler for this event
            self.Connect(self._popupDlgCmdId, -1, wxEVT_FLAT_MENU_SELECTED, self.OnCustomizeDlg)

        # Remove all items from the popup menu
        self._moreMenu.Clear()

        invM = self.GetInvisibleMenuItemCount()

        for i in xrange(len(self._items) - invM, len(self._items)):
            item = FlatMenuItem(self._moreMenu, wx.ID_ANY, self._items[i].GetTitle(),
                                "", wx.ITEM_NORMAL, self._items[i].GetMenu())
            self._moreMenu.AppendItem(item)

        # Add invisible toolbar items
        invT = self.GetInvisibleToolbarItemCount()

        if self._showToolbar and invT > 0:
            if self.GetInvisibleMenuItemCount() > 0:
                self._moreMenu.AppendSeparator()

            for i in xrange(len(self._tbButtons) - invT, len(self._tbButtons)):
                if self._tbButtons[i]._tbItem.IsSeparator():
                    self._moreMenu.AppendSeparator()
                elif not self._tbButtons[i]._tbItem.IsCustomControl():
                    tbitem = self._tbButtons[i]._tbItem
                    item = FlatMenuItem(self._tbMenu, tbitem.GetId(), tbitem.GetLabel(), "", wx.ITEM_NORMAL, None, tbitem.GetBitmap(), tbitem.GetDisabledBitmap())
                    item.Enable(tbitem.IsEnabled())
                    self._moreMenu.AppendItem(item)

        if self._showCustomize:
            if invT + invM > 0:
                self._moreMenu.AppendSeparator()
            item = FlatMenuItem(self._moreMenu, self._popupDlgCmdId, _(u"Customize..."))
            self._moreMenu.AppendItem(item)

[docs]    def GetInvisibleMenuItemCount(self):
        """
        Returns the number of invisible menu items.

        :note: Valid only after the `wx.PaintEvent` has been processed after a resize.
        """

        return len(self._items) - self.GetLastVisibleMenu()

[docs]    def GetInvisibleToolbarItemCount(self):
        """
        Returns the number of invisible toolbar items.

        :note: Valid only after the `wx.PaintEvent` has been processed after a resize.
        """

        count = 0
        for i in xrange(len(self._tbButtons)):
            if self._tbButtons[i]._visible == False:
                break
            count = i

        return len(self._tbButtons) - count - 1

[docs]    def PopupMoreMenu(self):
        """ Pops up the 'more' menu. """

        if (not self._showCustomize) and self.GetInvisibleMenuItemCount() + self.GetInvisibleToolbarItemCount() < 1:
            return

        self.CreateMoreMenu()

        pt = self._dropDownButtonArea.GetTopLeft()
        pt = self.ClientToScreen(pt)
        pt.y += self._dropDownButtonArea.GetHeight()
        self._moreMenu.Popup(pt, self)

[docs]    def OnCustomizeDlg(self, event):
        """
        Handles the customize dialog here.

        :param `event`: a L{FlatMenuEvent} event to be processed.
        """

        if not self._dlg:
            self._dlg = FMCustomizeDlg(self)
        else:
            # intialize the dialog
            self._dlg.Initialise()

        if self._dlg.ShowModal() == wx.ID_OK:
            # Handle customize requests here
            pass

        if "__WXGTK__" in wx.Platform:
            # Reset the more button
            dc = wx.ClientDC(self)
            self.DrawMoreButton(dc, ControlNormal)

[docs]    def AppendToolbarItem(self, item):
        """
        Appends a tool to the L{FlatMenuBar}.

        :warning: This method is now deprecated.

        :see: L{AddTool}
        """

        newItem = ToolBarItem(item, wx.Rect(), ControlNormal)
        self._tbButtons.append(newItem)

[docs]    def AddTool(self, toolId, label="", bitmap1=wx.NullBitmap, bitmap2=wx.NullBitmap,
                kind=wx.ITEM_NORMAL, shortHelp="", longHelp=""):
        """
        Adds a tool to the toolbar.

        :param integer `toolId`: an integer by which the tool may be identified in subsequent
         operations;
        :param string `label`: the tool label string;
        :param integer `kind`: may be ``wx.ITEM_NORMAL`` for a normal button (default),
         ``wx.ITEM_CHECK`` for a checkable tool (such tool stays pressed after it had been
         toggled) or ``wx.ITEM_RADIO`` for a checkable tool which makes part of a radio
         group of tools each of which is automatically unchecked whenever another button
         in the group is checked;
        :param `bitmap1`: the primary tool bitmap, an instance of `wx.Bitmap`;
        :param `bitmap2`: the bitmap used when the tool is disabled. If it is equal to
         `wx.NullBitmap`, the disabled bitmap is automatically generated by greing out
         the normal one;
        :param string `shortHelp`: a string used for the tools tooltip;
        :param string `longHelp`: this string is shown in the `wx.StatusBar` (if any) of the
         parent frame when the mouse pointer is inside the tool.
        """

        self._tbButtons.append(ToolBarItem(FlatToolbarItem(bitmap1, toolId, label, bitmap2, kind, shortHelp, longHelp), wx.Rect(), ControlNormal))

[docs]    def AddSeparator(self):
        """ Adds a separator for spacing groups of tools in toolbar. """

        if len(self._tbButtons) > 0 and not self._tbButtons[len(self._tbButtons)-1]._tbItem.IsSeparator():
            self._tbButtons.append(ToolBarItem(FlatToolbarItem(), wx.Rect(), ControlNormal))

[docs]    def AddControl(self, control):
        """
        Adds any control to the toolbar, typically e.g. a combobox.

        :param `control`: the control to be added, a subclass of `wx.Window` (but no `wx.TopLevelWindow`).
        """

        self._tbButtons.append(ToolBarItem(FlatToolbarItem(control), wx.Rect(), ControlNormal))

[docs]    def AddCheckTool(self, toolId, label="", bitmap1=wx.NullBitmap, bitmap2=wx.NullBitmap, shortHelp="", longHelp=""):
        """
        Adds a new check (or toggle) tool to the toolbar.

        :see: L{AddTool} for parameter descriptions.
        """

        self.AddTool(toolId, label, bitmap1, bitmap2, kind=wx.ITEM_CHECK, shortHelp=shortHelp, longHelp=longHelp)

[docs]    def AddRadioTool(self, toolId, label= "", bitmap1=wx.NullBitmap, bitmap2=wx.NullBitmap, shortHelp="", longHelp=""):
        """
        Adds a new radio tool to the toolbar.

        Consecutive radio tools form a radio group such that exactly one button in the
        group is pressed at any moment, in other words whenever a button in the group is
        pressed the previously pressed button is automatically released.

        You should avoid having the radio groups of only one element as it would be
        impossible for the user to use such button.

        By default, the first button in the radio group is initially pressed, the others are not.

        :see: L{AddTool} for parameter descriptions.
        """

        self.AddTool(toolId, label, bitmap1, bitmap2, kind=wx.ITEM_RADIO, shortHelp=shortHelp, longHelp=longHelp)

        if len(self._tbButtons)<1 or not self._tbButtons[len(self._tbButtons)-2]._tbItem.IsRadioItem():
            self._tbButtons[len(self._tbButtons)-1]._tbItem.Select(True)
            self._lastRadioGroup += 1

        self._tbButtons[len(self._tbButtons)-1]._tbItem.SetGroup(self._lastRadioGroup)

[docs]    def SetUpdateInterval(self, interval):
        """
        Sets the UpdateUI interval for toolbar items. All UpdateUI events are
        sent from within L{OnIdle} handler, the default is 20 milliseconds.

        :param integer `interval`: the updateUI interval in milliseconds.
        """

        self._interval = interval

[docs]    def PositionAUI(self, mgr, fixToolbar=True):
        """
        Positions the control inside a wxAUI / PyAUI frame manager.

        :param `mgr`: an instance of `wx.aui.AuiManager` or L{AuiManager};
        :param bool `fixToolbar`: ``True`` if L{FlatMenuBar} can not be floated.
        """

        if isinstance(mgr, wx.aui.AuiManager):
            pn = AuiPaneInfo()
        else:
            pn = PyAuiPaneInfo()

        xx = wx.SystemSettings_GetMetric(wx.SYS_SCREEN_X)

        # We add our menu bar as a toolbar, with the following settings

        pn.Name("flat_menu_bar")
        pn.Caption("Menu Bar")
        pn.Top()
        pn.MinSize(wx.Size(xx/2, self._barHeight))
        pn.LeftDockable(False)
        pn.RightDockable(False)
        pn.ToolbarPane()

        if not fixToolbar:
            # We add our menu bar as a toolbar, with the following settings
            pn.BestSize(wx.Size(xx, self._barHeight))
            pn.FloatingSize(wx.Size(300, self._barHeight))
            pn.Floatable(True)
            pn.MaxSize(wx.Size(xx, self._barHeight))
            pn.Gripper(True)

        else:
            pn.BestSize(wx.Size(xx, self._barHeight))
            pn.Gripper(False)

        pn.Resizable(False)
        pn.PaneBorder(False)
        mgr.AddPane(self, pn)

        self._mgr = mgr

[docs]    def DoGiveHelp(self, hit):
        """
        Gives tooltips and help in `wx.StatusBar`.

        :param `hit`: the toolbar tool currently hovered by the mouse.
        """

        shortHelp = hit.GetShortHelp()
        if shortHelp:
            self.SetToolTipString(shortHelp)
            self._haveTip = True

        longHelp = hit.GetLongHelp()
        if not longHelp:
            return

        topLevel = wx.GetTopLevelParent(self)

        if isinstance(topLevel, wx.Frame) and topLevel.GetStatusBar():
            statusBar = topLevel.GetStatusBar()

            if self._statusTimer and self._statusTimer.IsRunning():
                self._statusTimer.Stop()
                statusBar.PopStatusText(0)

            statusBar.PushStatusText(longHelp, 0)
            self._statusTimer = StatusBarTimer(self)
            self._statusTimer.Start(_DELAY, wx.TIMER_ONE_SHOT)

[docs]    def RemoveHelp(self):
        """ Removes the tooltips and statusbar help (if any) for a button. """

        if self._haveTip:
            self.SetToolTipString("")
            self._haveTip = False

        if self._statusTimer and self._statusTimer.IsRunning():
            topLevel = wx.GetTopLevelParent(self)
            statusBar = topLevel.GetStatusBar()
            self._statusTimer.Stop()
            statusBar.PopStatusText(0)
            self._statusTimer = None

[docs]    def OnStatusBarTimer(self):
        """ Handles the timer expiring to delete the `longHelp` string in the `wx.StatusBar`. """

        topLevel = wx.GetTopLevelParent(self)
        statusBar = topLevel.GetStatusBar()
        statusBar.PopStatusText(0)

[docs]class mcPopupWindow(wx.MiniFrame):
    """ Since Max OS does not support `wx.PopupWindow`, this is an alternative. """

[docs]    def __init__(self, parent):
        """
        Default class constructor.

        :param `parent`: the L{mcPopupWindow} parent window.
        """

        wx.MiniFrame.__init__(self, parent, style = wx.POPUP_WINDOW)
        self.SetExtraStyle(wx.WS_EX_TRANSIENT)
        self._parent = parent
        self.Bind(wx.EVT_LEAVE_WINDOW, self.OnLeaveWindow)

[docs]    def OnLeaveWindow(self, event):
        """
        Handles the ``wx.EVT_LEAVE_WINDOW`` event for L{mcPopupWindow}.

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

        event.Skip()

havePopupWindow = 1

if wx.Platform == '__WXMAC__':
    havePopupWindow = 0
    wx.PopupWindow = mcPopupWindow

# ---------------------------------------------------------------------------- #
# Class ShadowPopupWindow
# ---------------------------------------------------------------------------- #

[docs]class ShadowPopupWindow(wx.PopupWindow):
    """ Base class for generic L{FlatMenu} derived from `wx.PopupWindow`. """

[docs]    def __init__(self, parent=None):
        """
        Default class constructor.

        :param `parent`: the L{ShadowPopupWindow} parent (tipically your main frame).
        """

        if not parent:
            parent = wx.GetApp().GetTopWindow()

        if not parent:
            raise Exception("Can't create menu without parent!")

        wx.PopupWindow.__init__(self, parent)

        if "__WXMSW__" in wx.Platform and _libimported == "MH":

            GCL_STYLE= -26
            cstyle= win32gui.GetClassLong(self.GetHandle(), GCL_STYLE)
            if cstyle & CS_DROPSHADOW == 0:
                win32api.SetClassLong(self.GetHandle(),
                                      GCL_STYLE, cstyle | CS_DROPSHADOW)

        # popup windows are created hidden by default
        self.Hide()

#--------------------------------------------------------
# Class FlatMenuButton
#--------------------------------------------------------

[docs]class FlatMenuButton(object):
    """
    A nice small class that functions like `wx.BitmapButton`, the reason I did
    not used `wx.BitmapButton` is that on Linux, it has some extra margins that
    I can't seem to be able to remove.
    """

[docs]    def __init__(self, menu, up, normalBmp, disabledBmp=wx.NullBitmap, scrollOnHover=False):
        """
        Default class constructor.

        :param `menu`: the parent menu associated with this button, an instance of L{FlatMenu};
        :param bool `up`: ``True`` for up arrow or ``False`` for down arrow;
        :param `normalBmp`: normal state bitmap, an instance of `wx.Bitmap`;
        :param `disabledBmp`: disabled state bitmap, an instance of `wx.Bitmap`.
        """

        self._normalBmp = normalBmp
        self._up = up
        self._parent = menu
        self._pos = wx.Point()
        self._size = wx.Size()
        self._timerID = wx.NewId()
        self._scrollOnHover = scrollOnHover

        if not disabledBmp.Ok():
            self._disabledBmp = wx.BitmapFromImage(self._normalBmp.ConvertToImage().ConvertToGreyscale())
        else:
            self._disabledBmp = disabledBmp

        self._state = ControlNormal
        self._timer = wx.Timer(self._parent, self._timerID)
        self._timer.Stop()

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

        if self._timer:
            if self._timer.IsRunning():
                self._timer.Stop()

            del self._timer

[docs]    def Contains(self, pt):
        """ Used internally. """

        rect = wx.RectPS(self._pos, self._size)
        if not rect.Contains(pt):
            return False

        return True

[docs]    def Draw(self, dc):
        """
        Draws self at rect using dc.

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

        rect = wx.RectPS(self._pos, self._size)
        xx = rect.x + (rect.width - self._normalBmp.GetWidth())/2
        yy = rect.y + (rect.height - self._normalBmp.GetHeight())/2

        self._parent.GetRenderer().DrawScrollButton(dc, rect, self._state)
        dc.DrawBitmap(self._normalBmp, xx, yy, True)

[docs]    def ProcessLeftDown(self, pt):
        """
        Handles left down mouse events.

        :param `pt`: an instance of `wx.Point` where the left mouse button was pressed.
        """

        if not self.Contains(pt):
            return False

        self._state = ControlPressed
        self._parent.Refresh()

        if self._up:
            self._parent.ScrollUp()
        else:
            self._parent.ScrollDown()

        self._timer.Start(100)
        return True

[docs]    def ProcessLeftUp(self, pt):
        """
        Handles left up mouse events.

        :param `pt`: an instance of `wx.Point` where the left mouse button was released.
        """

        # always stop the timer
        self._timer.Stop()

        if not self.Contains(pt):
            return False

        self._state = ControlFocus
        self._parent.Refresh()

        return True

[docs]    def ProcessMouseMove(self, pt):
        """
        Handles mouse motion events. This is called any time the mouse moves in the parent menu,
        so we must check to see if the mouse is over the button.

        :param `pt`: an instance of `wx.Point` where the mouse pointer was moved.
        """

        if not self.Contains(pt):

            self._timer.Stop()
            if self._state != ControlNormal:

                self._state = ControlNormal
                self._parent.Refresh()

            return False

        if self._scrollOnHover and not self._timer.IsRunning():
            self._timer.Start(100)

        # Process mouse move event
        if self._state != ControlFocus:
            if self._state != ControlPressed:
                self._state = ControlFocus
                self._parent.Refresh()

        return True

[docs]    def GetTimerId(self):
        """ Returns the timer object identifier. """

        return self._timerID

[docs]    def GetTimer(self):
        """ Returns the timer object. """

        return self._timer

[docs]    def Move(self, input1, input2=None):
        """
        Moves L{FlatMenuButton} to the specified position.

        :param `input1`: if it is an instance of `wx.Point`, it represents the L{FlatMenuButton}
         position and the `input2` parameter is not used. Otherwise it is an integer representing
         the button `x` position;
        :param `input2`: if not ``None``, it is an integer representing the button `y` position.
        """

        if type(input) == type(1):
            self._pos = wx.Point(input1, input2)
        else:
            self._pos = input1

[docs]    def SetSize(self, input1, input2=None):
        """
        Sets the size for L{FlatMenuButton}.

        :param `input1`: if it is an instance of `wx.Size`, it represents the L{FlatMenuButton}
         size and the `input2` parameter is not used. Otherwise it is an integer representing
         the button width;
        :param `input2`: if not ``None``, it is an integer representing the button height.
        """

        if type(input) == type(1):
            self._size = wx.Size(input1, input2)
        else:
            self._size = input1

[docs]    def GetClientRect(self):
        """ Returns the client rectangle for L{FlatMenuButton}. """

        return wx.RectPS(self._pos, self._size)

#--------------------------------------------------------
# Class FlatMenuItemGroup
#--------------------------------------------------------

[docs]class FlatMenuItemGroup(object):
    """
    A class that manages a group of radio menu items.
    """

[docs]    def __init__(self):
        """ Default class constructor. """

        self._items = []

[docs]    def GetSelectedItem(self):
        """ Returns the selected item. """

        for item in self._items:
            if item.IsChecked():
                return item

        return None

[docs]    def Add(self, item):
        """
        Adds a new item to the group.

        :param `item`: an instance of L{FlatMenu}.
        """

        if item.IsChecked():
            # uncheck all other items
            for exitem in self._items:
                exitem._bIsChecked = False

        self._items.append(item)

[docs]    def Exist(self, item):
        """
        Checks if an item is in the group.

        :param `item`: an instance of L{FlatMenu}.
        """

        if item in self._items:
            return True

        return False

[docs]    def SetSelection(self, item):
        """
        Selects a particular item.

        :param `item`: an instance of L{FlatMenu}.
        """

        # make sure this item exist in our group
        if not self.Exist(item):
            return

        # uncheck all other items
        for exitem in self._items:
            exitem._bIsChecked = False

        item._bIsChecked = True

[docs]    def Remove(self, item):
        """
        Removes a particular item.

        :param `item`: an instance of L{FlatMenu}.
        """

        if item not in self._items:
            return

        self._items.remove(item)

        if item.IsChecked() and len(self._items) > 0:
            #if the removed item was the selected one,
            # select the first one in the group
            self._items[0]._bIsChecked = True

#--------------------------------------------------------
# Class FlatMenuBase
#--------------------------------------------------------

[docs]class FlatMenuBase(ShadowPopupWindow):
    """
    Base class for generic flat menu derived from `wx.PopupWindow`.
    """

[docs]    def __init__(self, parent=None):
        """
        Default class constructor.

        :param `parent`: the L{ShadowPopupWindow} parent window.
        """

        self._rendererMgr = FMRendererMgr()
        self._parentMenu = parent
        self._openedSubMenu = None
        self._owner = None
        self._popupPtOffset = 0
        self._showScrollButtons = False
        self._upButton = None
        self._downButton = None
        self._is_dismiss = False

        ShadowPopupWindow.__init__(self, parent)

[docs]    def OnDismiss(self):
        """ Fires an event ``EVT_FLAT_MENU_DISMISSED`` and handle menu dismiss. """

        # Release mouse capture if needed
        if self.HasCapture():
            self.ReleaseMouse()

        self._is_dismiss = True

        # send an event about our dismissal to the parent (unless we are a sub menu)
        if self.IsShown() and not self._parentMenu:

            event = FlatMenuEvent(wxEVT_FLAT_MENU_DISMISSED, self.GetId())
            event.SetEventObject(self)

            # Send it
            if self.GetMenuOwner():
                self.GetMenuOwner().GetEventHandler().ProcessEvent(event)
            else:
                self.GetEventHandler().ProcessEvent(event)

[docs]    def Popup(self, pt, parent):
        """
        Popups menu at the specified point.

        :param `pt`: an instance of `wx.Point`, assumed to be in screen coordinates. However,
         if `parent` is not ``None``, `pt` is translated into the screen coordinates using
         `parent.ClientToScreen()`;
        :param `parent`: if not ``None``, an instance of `wx.Window`.
        """

        # some controls update themselves from OnIdle() call - let them do it
        wx.GetApp().ProcessIdle()

        # The mouse was pressed in the parent coordinates,
        # e.g. pressing on the left top of a text ctrl
        # will result in (1, 1), these coordinates needs
        # to be converted into screen coords
        self._parentMenu = parent

        # If we are topmost menu, we use the given pt
        # else we use the logical
        # parent (second argument provided to this function)

        if self._parentMenu:
            pos = self._parentMenu.ClientToScreen(pt)
        else:
            pos = pt

        # Fit the menu into screen
        pos = self.AdjustPosition(pos)
        if self._showScrollButtons:

            sz = self.GetSize()
            # Get the screen height
            scrHeight = wx.SystemSettings_GetMetric(wx.SYS_SCREEN_Y)

            # position the scrollbar - If we are doing scroll bar buttons put them in the top right and
            # bottom right or else place them as menu items at the top and bottom.
            if self.GetRenderer().scrollBarButtons:
                if not self._upButton:
                    self._upButton = FlatMenuButton(self, True, ArtManager.Get().GetStockBitmap("arrow_up"))

                if not self._downButton:
                    self._downButton = FlatMenuButton(self, False, ArtManager.Get().GetStockBitmap("arrow_down"))

                self._upButton.SetSize((SCROLL_BTN_HEIGHT, SCROLL_BTN_HEIGHT))
                self._downButton.SetSize((SCROLL_BTN_HEIGHT, SCROLL_BTN_HEIGHT))

                self._upButton.Move((sz.x - SCROLL_BTN_HEIGHT - 4, 4))
                self._downButton.Move((sz.x - SCROLL_BTN_HEIGHT - 4, scrHeight - pos.y - 2 - SCROLL_BTN_HEIGHT))
            else:
                if not self._upButton:
                    self._upButton = FlatMenuButton(self, True, getMenuUpArrowBitmap(), scrollOnHover=True)

                if not self._downButton:
                    self._downButton = FlatMenuButton(self, False, getMenuDownArrowBitmap(), scrollOnHover=True)

                self._upButton.SetSize((sz.x-2, self.GetItemHeight()))
                self._downButton.SetSize((sz.x-2, self.GetItemHeight()))

                self._upButton.Move((1, 3))
                self._downButton.Move((1, scrHeight - pos.y - 3 - self.GetItemHeight()))

        self.Move(pos)
        self.Show()

        # Capture mouse event and direct them to us
        if not self.HasCapture():
            self.CaptureMouse()

        self._is_dismiss = False

[docs]    def AdjustPosition(self, pos):
        """
        Adjusts position so the menu will be fully visible on screen.

        :param `pos`: an instance of `wx.Point` specifying the menu position.
        """

        # Check that the menu can fully appear in the screen
        scrWidth  = wx.SystemSettings_GetMetric(wx.SYS_SCREEN_X)
        scrHeight = wx.SystemSettings_GetMetric(wx.SYS_SCREEN_Y)

        scrollBarButtons = self.GetRenderer().scrollBarButtons
        scrollBarMenuItems = not scrollBarButtons

        size = self.GetSize()
        if scrollBarMenuItems:
            size.y += self.GetItemHeight()*2

        # always assume that we have scrollbuttons on
        self._showScrollButtons = False
        pos.y += self._popupPtOffset

        if size.y + pos.y > scrHeight:
            # the menu will be truncated
            if self._parentMenu is None:
                # try to flip the menu
                flippedPosy = pos.y - size.y
                flippedPosy -= self._popupPtOffset

                if flippedPosy >= 0 and flippedPosy + size.y < scrHeight:
                    pos.y = flippedPosy
                    return pos
                else:
                    # We need to popup scrollbuttons!
                    self._showScrollButtons = True

            else:
                # we are a submenu
                # try to decrease the y value of the menu position
                newy = pos.y
                newy -= (size.y + pos.y) - scrHeight

                if newy + size.y > scrHeight:
                    # probably the menu size is too high to fit
                    # the screen, we need scrollbuttons
                    self._showScrollButtons = True
                else:
                    pos.y = newy

        menuMaxX = pos.x + size.x

        if menuMaxX > scrWidth and pos.x < scrWidth:

            if self._parentMenu:

                # We are submenu
                self._shiftePos = (size.x + self._parentMenu.GetSize().x)
                pos.x -= self._shiftePos
                pos.x += 10

            else:

                self._shiftePos  = ((size.x + pos.x) - scrWidth)
                pos.x -= self._shiftePos

        else:

            if self._parentMenu:
                pos.x += 5

        return pos

[docs]    def Dismiss(self, dismissParent, resetOwner):
        """
        Dismisses the popup window.

        :param bool `dismissParent`: whether to dismiss the parent menu or not;
        :param bool `resetOwner`: ``True`` to delete the link between this menu and the
         owner menu, ``False`` otherwise.
        """

        # Check if child menu is poped, if so, dismiss it
        if self._openedSubMenu:
            self._openedSubMenu.Dismiss(False, resetOwner)

        self.OnDismiss()

        # Reset menu owner
        if resetOwner:
            self._owner = None

        self.Show(False)

        if self._parentMenu and dismissParent:

            self._parentMenu.OnChildDismiss()
            self._parentMenu.Dismiss(dismissParent, resetOwner)

        self._parentMenu = None

[docs]    def OnChildDismiss(self):
        """ Handles children dismiss. """

        self._openedSubMenu = None

[docs]    def GetRenderer(self):
        """ Returns the renderer for this class. """

        return self._rendererMgr.GetRenderer()

[docs]    def GetRootMenu(self):
        """ Returns the top level menu. """

        root = self
        while root._parentMenu:
            root = root._parentMenu

        return root

[docs]    def SetOwnerHeight(self, height):
        """
        Sets the menu owner height, this will be used to position the menu below
        or above the owner.

        :param integer `height`: an integer representing the menu owner height.
        """

        self._popupPtOffset = height

    # by default do nothing

[docs]    def ScrollDown(self):
        """
        Scroll one unit down.
        By default this function is empty, let derived class do something.
        """

        pass

    # by default do nothing

[docs]    def ScrollUp(self):
        """
        Scroll one unit up.
        By default this function is empty, let derived class do something.
        """

        pass

[docs]    def GetMenuOwner(self):
        """
        Returns the menu logical owner, the owner does not necessarly mean the
        menu parent, it can also be the window that popped up it.
        """

        return self._owner

#--------------------------------------------------------
# Class ToolBarItem
#--------------------------------------------------------

[docs]class ToolBarItem(object):
    """
    A simple class that holds information about a toolbar item.
    """

[docs]    def __init__(self, tbItem, rect, state):
        """
        Default class constructor.

        :param `tbItem`: an instance of L{FlatToolbarItem};
        :param `rect`: the client rectangle for the toolbar item, an instance of `wx.Rect`;
        :param integer `state`: the toolbar item state.

        :see: L{MenuEntryInfo.SetState} for a list of valid item states.
        """

        self._tbItem = tbItem
        self._rect = rect
        self._state = state
        self._visible = True

#--------------------------------------------------------
# Class FlatToolBarItem
#--------------------------------------------------------

[docs]class FlatToolbarItem(object):
    """
    This class represents a toolbar item.
    """

[docs]    def __init__(self, controlType=None, id=wx.ID_ANY, label="", disabledBmp=wx.NullBitmap, kind=wx.ITEM_NORMAL,
                 shortHelp="", longHelp=""):
        """
        Default class constructor.

        :param `controlType`: can be ``None`` for a toolbar separator, an instance
         of `wx.Window` for a control or an instance of `wx.Bitmap` for a standard
         toolbar tool;
        :param integer `id`: the toolbar tool id. If set to ``wx.ID_ANY``, a new id is
         automatically assigned;
        :param string `label`: the toolbar tool label;
        :param `disabledBmp`: the bitmap used when the tool is disabled. If the tool
         is a standard one (i.e., not a control or a separator), and `disabledBmp`
         is equal to `wx.NullBitmap`, the disabled bitmap is automatically generated
         by greing the normal one;
        :param integer `kind`: may be ``wx.ITEM_NORMAL`` for a normal button (default),
         ``wx.ITEM_CHECK`` for a checkable tool (such tool stays pressed after it had been
         toggled) or ``wx.ITEM_RADIO`` for a checkable tool which makes part of a radio
         group of tools each of which is automatically unchecked whenever another button
         in the group is checked;
        :param string `shortHelp`: a string used for the tool's tooltip;
        :param string `longHelp`: this string is shown in the `wx.StatusBar` (if any) of the
         parent frame when the mouse pointer is inside the tool.
        """

        if id == wx.ID_ANY:
            id = wx.NewId()

        if controlType is None:    # Is a separator
            self._normalBmp = wx.NullBitmap
            self._id = wx.NewId()
            self._label = ""
            self._disabledImg = wx.NullBitmap
            self._customCtrl = None
            kind = wx.ITEM_SEPARATOR

        elif isinstance(controlType, wx.Window): # is a wxControl
            self._normalBmp = wx.NullBitmap
            self._id = id
            self._label = ""
            self._disabledImg = wx.NullBitmap
            self._customCtrl = controlType
            kind = FTB_ITEM_CUSTOM

        elif isinstance(controlType, wx.Bitmap):   # Bitmap construction, simple tool
            self._normalBmp = controlType
            self._id = id
            self._label = label
            self._disabledImg = disabledBmp
            self._customCtrl = None

            if not self._disabledImg.Ok():
                # Create a grey bitmap from the normal bitmap
                self._disabledImg = wx.BitmapFromImage(self._normalBmp.ConvertToImage().ConvertToGreyscale())

        self._kind = kind
        self._enabled = True
        self._selected = False
        self._group = -1 # group id for radio items

        if not shortHelp:
            shortHelp = label

        self._shortHelp = shortHelp
        self._longHelp = longHelp

[docs]    def GetLabel(self):
        """ Returns the tool label. """

        return self._label

[docs]    def SetLabel(self, label):
        """
        Sets the tool label.

        :param string `label`: the new tool string.
        """

        self._label = label

[docs]    def GetBitmap(self):
        """ Returns the tool bitmap. """

        return self._normalBmp

[docs]    def SetBitmap(self, bmp):
        """
        Sets the tool bitmap.

        :param `bmp`: the new tool bitmap, a valid `wx.Bitmap` object.
        """

        self._normalBmp = bmp

[docs]    def GetDisabledBitmap(self):
        """ Returns the tool disabled bitmap. """

        return self._disabledImg

[docs]    def SetDisabledBitmap(self, bmp):
        """
        Sets the tool disabled bitmap.

        :param `bmp`: the new tool disabled bitmap, a valid `wx.Bitmap` object.
        """

        self._disabledImg = bmp

[docs]    def GetId(self):
        """ Gets the tool id. """

        return self._id

[docs]    def IsSeparator(self):
        """ Returns whether the tool is a separator or not. """

        return self._kind == wx.ITEM_SEPARATOR

[docs]    def IsRadioItem(self):
        """ Returns ``True`` if the item is a radio item. """

        return self._kind == wx.ITEM_RADIO

[docs]    def IsCheckItem(self):
        """ Returns ``True`` if the item is a radio item. """

        return self._kind == wx.ITEM_CHECK

[docs]    def IsCustomControl(self):
        """ Returns whether the tool is a custom control or not. """

        return self._kind == FTB_ITEM_CUSTOM

[docs]    def IsRegularItem(self):
        """ Returns whether the tool is a standard tool or not. """

        return self._kind == wx.ITEM_NORMAL

[docs]    def GetCustomControl(self):
        """ Returns the associated custom control. """

        return self._customCtrl

[docs]    def IsSelected(self):
        """ Returns whether the tool is selected or checked."""

        return self._selected

[docs]    def IsChecked(self):
        """ Same as L{IsSelected}. More intuitive for check items though. """

        return self._selected

[docs]    def Select(self, select=True):
        """
        Selects or checks a radio or check item.

        :param bool `select`: ``True`` to select or check a tool, ``False`` to unselect
         or uncheck it.
        """

        self._selected = select

[docs]    def Toggle(self):
        """ Toggles a check item. """

        if self.IsCheckItem():
            self._selected = not self._selected

[docs]    def SetGroup(self, group):
        """
        Sets group id for a radio item, for other items does nothing.

        :param `group`: an instance of L{FlatMenuItemGroup}.
        """

        if self.IsRadioItem():
            self._group = group

[docs]    def GetGroup(self):
        """ Returns group id for radio item, or -1 for other item types. """

        return self._group

[docs]    def IsEnabled(self):
        """ Returns whether the tool is enabled or not. """

        return self._enabled

[docs]    def Enable(self, enable=True):
        """
        Enables or disables the tool.

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

        self._enabled = enable

[docs]    def GetShortHelp(self):
        """ Returns the tool short help string (displayed in the tool's tooltip). """

        if self._kind == wx.ITEM_NORMAL:
            return self._shortHelp

        return ""

[docs]    def SetShortHelp(self, help):
        """
        Sets the tool short help string (displayed in the tool's tooltip).

        :param string `help`: the new tool short help string.
        """

        if self._kind == wx.ITEM_NORMAL:
            self._shortHelp = help

[docs]    def SetLongHelp(self, help):
        """
        Sets the tool long help string (displayed in the parent frame `wx.StatusBar`).

        :param string `help`: the new tool long help string.
        """

        if self._kind == wx.ITEM_NORMAL:
            self._longHelp = help

[docs]    def GetLongHelp(self):
        """ Returns the tool long help string (displayed in the parent frame `wx.StatusBar`). """

        if self._kind == wx.ITEM_NORMAL:
            return self._longHelp

        return ""

#--------------------------------------------------------
# Class FlatMenuItem
#--------------------------------------------------------

[docs]class FlatMenuItem(object):
    """
    A class that represents an item in a menu.
    """

[docs]    def __init__(self, parent, id=wx.ID_SEPARATOR, label="", helpString="",
                 kind=wx.ITEM_NORMAL, subMenu=None, normalBmp=wx.NullBitmap,
                 disabledBmp=wx.NullBitmap,
                 hotBmp=wx.NullBitmap):
        """
        Default class constructor.

        :param `parent`: menu that the menu item belongs to, an instance of L{FlatMenu};
        :param integer `id`: the menu item identifier;
        :param string `label`: text for the menu item, as shown on the menu. An accelerator
         key can be specified using the ampersand '&' character. In order to embed
         an ampersand character in the menu item text, the ampersand must be doubled;
        :param string `helpString`: optional help string that will be shown on the status bar;
        :param integer `kind`: may be ``wx.ITEM_SEPARATOR``, ``wx.ITEM_NORMAL``, ``wx.ITEM_CHECK``
         or ``wx.ITEM_RADIO``;
        :param `subMenu`: if not ``None``, the sub menu this item belongs to (an instance of L{FlatMenu});
        :param `normalBmp`: normal bitmap to draw to the side of the text, this bitmap
         is used when the menu is enabled (an instance of `wx.Bitmap`);
        :param `disabledBmp`: 'greyed' bitmap to draw to the side of the text, this
         bitmap is used when the menu is disabled, if none supplied normal is used (an instance of `wx.Bitmap`);
        :param `hotBmp`: hot bitmap to draw to the side of the text, this bitmap is
         used when the menu is hovered, if non supplied, normal is used (an instance of `wx.Bitmap`).
        """

        self._text = label
        self._kind = kind
        self._helpString = helpString

        if id == wx.ID_ANY:
            id = wx.NewId()

        self._id = id
        self._parentMenu = parent
        self._subMenu = subMenu
        self._normalBmp = normalBmp
        self._disabledBmp = disabledBmp
        self._hotBmp = hotBmp
        self._bIsChecked = False
        self._bIsEnabled = True
        self._mnemonicIdx = wx.NOT_FOUND
        self._isAttachedToMenu = False
        self._accelStr = ""
        self._rect = wx.Rect()
        self._groupPtr = None
        self._visible = False
        self._contextMenu = None
        self._font = None
        self._textColour = None

        self.SetLabel(self._text)
        self.SetMenuBar()

        self._checkMarkBmp = wx.BitmapFromXPMData(check_mark_xpm)
        self._checkMarkBmp.SetMask(wx.Mask(self._checkMarkBmp, wx.WHITE))
        self._radioMarkBmp = wx.BitmapFromXPMData(radio_item_xpm)
        self._radioMarkBmp.SetMask(wx.Mask(self._radioMarkBmp, wx.WHITE))

[docs]    def SetLongHelp(self, help):
        """
        Sets the item long help string (displayed in the parent frame `wx.StatusBar`).

        :param string `help`: the new item long help string.
        """

        self._helpString = help

[docs]    def GetLongHelp(self):
        """ Returns the item long help string (displayed in the parent frame `wx.StatusBar`). """

        return self._helpString

[docs]    def GetShortHelp(self):
        """ Returns the item short help string (displayed in the tool's tooltip). """

        return ""

[docs]    def Enable(self, enable=True):
        """
        Enables or disables a menu item.

        :param bool `enable`: ``True`` to enable the menu item, ``False`` to disable it.
        """

        self._bIsEnabled = enable
        if self._parentMenu:
            self._parentMenu.UpdateItem(self)

[docs]    def GetBitmap(self):
        """
        Returns the normal bitmap associated to the menu item or `wx.NullBitmap` if
        none has been supplied.
        """

        return self._normalBmp

[docs]    def GetDisabledBitmap(self):
        """
        Returns the disabled bitmap associated to the menu item or `wx.NullBitmap`
        if none has been supplied.
        """

        return self._disabledBmp

[docs]    def GetHotBitmap(self):
        """
        Returns the hot bitmap associated to the menu item or `wx.NullBitmap` if
        none has been supplied.
        """

        return self._hotBmp

[docs]    def GetHelp(self):
        """ Returns the item help string. """

        return self._helpString

[docs]    def GetId(self):
        """ Returns the item id. """

        return self._id

[docs]    def GetKind(self):
        """
        Returns the menu item kind, can be one of ``wx.ITEM_SEPARATOR``, ``wx.ITEM_NORMAL``,
        ``wx.ITEM_CHECK`` or ``wx.ITEM_RADIO``.
        """

        return self._kind

[docs]    def GetLabel(self):
        """ Returns the menu item label (without the accelerator if it is part of the string). """

        return self._label

[docs]    def GetMenu(self):
        """ Returns the parent menu. """

        return self._parentMenu

[docs]    def GetContextMenu(self):
        """ Returns the context menu associated with this item (if any). """

        return self._contextMenu

[docs]    def SetContextMenu(self, context_menu):
        """
        Assigns a context menu to this item.

        :param `context_menu`: an instance of L{FlatMenu}.
        """

        self._contextMenu = context_menu

[docs]    def GetText(self):
        """ Returns the text associated with the menu item including the accelerator. """

        return self._text

[docs]    def GetSubMenu(self):
        """ Returns the sub-menu of this menu item (if any). """

        return self._subMenu

[docs]    def IsCheckable(self):
        """ Returns ``True`` if this item is of type ``wx.ITEM_CHECK``, ``False`` otherwise. """

        return self._kind == wx.ITEM_CHECK

[docs]    def IsChecked(self):
        """
        Returns whether an item is checked or not.

        :note: This method is meaningful only for items of kind ``wx.ITEM_CHECK`` or
         ``wx.ITEM_RADIO``.
        """

        return self._bIsChecked

[docs]    def IsRadioItem(self):
        """ Returns ``True`` if this item is of type ``wx.ITEM_RADIO``, ``False`` otherwise. """

        return self._kind == wx.ITEM_RADIO

[docs]    def IsEnabled(self):
        """ Returns whether an item is enabled or not. """

        return self._bIsEnabled

[docs]    def IsSeparator(self):
        """ Returns ``True`` if this item is of type ``wx.ITEM_SEPARATOR``, ``False`` otherwise. """

        return self._id == wx.ID_SEPARATOR

[docs]    def IsSubMenu(self):
        """ Returns whether an item is a sub-menu or not. """

        return self._subMenu != None

[docs]    def SetNormalBitmap(self, bmp):
        """
        Sets the menu item normal bitmap.

        :param `bmp`: an instance of `wx.Bitmap`.
        """

        self._normalBmp = bmp

[docs]    def SetDisabledBitmap(self, bmp):
        """
        Sets the menu item disabled bitmap.

        :param `bmp`: an instance of `wx.Bitmap`.
        """

        self._disabledBmp = bmp

[docs]    def SetHotBitmap(self, bmp):
        """
        Sets the menu item hot bitmap.

        :param `bmp`: an instance of `wx.Bitmap`.
        """

        self._hotBmp = bmp

[docs]    def SetHelp(self, helpString):
        """
        Sets the menu item help string.

        :param string `helpString`: the new menu item help string.
        """

        self._helpString = helpString

[docs]    def SetMenu(self, menu):
        """
        Sets the menu item parent menu.

        :param `menu`: an instance of L{FlatMenu}.
        """

        self._parentMenu = menu

[docs]    def SetSubMenu(self, menu):
        """
        Sets the menu item sub-menu.

        :param `menu`: an instance of L{FlatMenu}.
        """

        self._subMenu = menu

        # Fix toolbar update
        self.SetMenuBar()

[docs]    def GetAccelString(self):
        """ Returns the accelerator string. """

        return self._accelStr

[docs]    def SetRect(self, rect):
        """
        Sets the menu item client rectangle.

        :param `rect`: the menu item client rectangle, an instance of `wx.Rect`.
        """

        self._rect = rect

[docs]    def GetRect(self):
        """ Returns the menu item client rectangle. """

        return self._rect

[docs]    def IsShown(self):
        """ Returns whether an item is shown or not. """

        return self._visible

[docs]    def Show(self, show=True):
        """
        Actually shows/hides the menu item.

        :param bool `show`: ``True`` to show the menu item, ``False`` to hide it.
        """

        self._visible = show

[docs]    def GetHeight(self):
        """ Returns the menu item height, in pixels. """

        if self.IsSeparator():
            return self._parentMenu.GetRenderer().separatorHeight
        else:
            return self._parentMenu._itemHeight

[docs]    def GetSuitableBitmap(self, selected):
        """
        Gets the bitmap that should be used based on the item state.

        :param bool `selected`: ``True`` if this menu item is currently hovered by the mouse,
         ``False`` otherwise.
        """

        normalBmp = self._normalBmp
        gBmp = (self._disabledBmp.Ok() and [self._disabledBmp] or [self._normalBmp])[0]
        hotBmp = (self._hotBmp.Ok() and [self._hotBmp] or [self._normalBmp])[0]

        if not self.IsEnabled():
            return gBmp
        elif selected:
            return hotBmp
        else:
            return normalBmp

[docs]    def SetLabel(self, text):
        """
        Sets the label text for this item from the text (excluding the accelerator).

        :param string `text`: the new item label (excluding the accelerator).
        """

        if text:

            indx = text.find("\t")
            if indx >= 0:
                self._accelStr = text[indx+1:]
                label = text[0:indx]
            else:
                self._accelStr = ""
                label = text

            self._mnemonicIdx, self._label = GetAccelIndex(label)

        else:

            self._mnemonicIdx = wx.NOT_FOUND
            self._label = ""

        if self._parentMenu:
            self._parentMenu.UpdateItem(self)

[docs]    def SetText(self, text):
        """
        Sets the text for this menu item (including accelerators).

        :param string `text`: the new item label (including the accelerator).
        """

        self._text = text
        self.SetLabel(self._text)

[docs]    def SetMenuBar(self):
        """ Links the current menu item with the main L{FlatMenuBar}. """

        # Fix toolbar update
        if self._subMenu and self._parentMenu:
            self._subMenu.SetSubMenuBar(self._parentMenu.GetMenuBarForSubMenu())

[docs]    def GetAcceleratorEntry(self):
        """ Returns the accelerator entry associated to this menu item. """

        return wx.GetAccelFromString(self.GetText())

[docs]    def GetMnemonicChar(self):
        """ Returns the shortcut char for this menu item. """

        if self._mnemonicIdx == wx.NOT_FOUND:
            return 0

        mnemonic = self._label[self._mnemonicIdx]
        return mnemonic.lower()

[docs]    def Check(self, check=True):
        """
        Checks or unchecks the menu item.

        :param bool `check`: ``True`` to check the menu item, ``False`` to uncheck it.

        :note: This method is meaningful only for menu items of ``wx.ITEM_CHECK``
         or ``wx.ITEM_RADIO`` kind.
        """

        if self.IsRadioItem() and not self._isAttachedToMenu:

            # radio items can be checked only after they are attached to menu
            return

        self._bIsChecked = check

        # update group
        if self.IsRadioItem() and check:
            self._groupPtr.SetSelection(self)

        # Our parent menu might want to do something with this change
        if self._parentMenu:
            self._parentMenu.UpdateItem(self)

[docs]    def SetFont(self, font=None):
        """
        Sets the L{FlatMenuItem} font.

        :param `font`: an instance of a valid `wx.Font`.
        """

        self._font = font

        if self._parentMenu:
            self._parentMenu.UpdateItem(self)

[docs]    def GetFont(self):
        """ Returns this L{FlatMenuItem} font. """

        return self._font

[docs]    def SetTextColour(self, colour=None):
        """
        Sets the L{FlatMenuItem} foreground colour for the menu label.

        :param `colour`: an instance of a valid `wx.Colour`.
        """

        self._textColour = colour

[docs]    def GetTextColour(self):
        """ Returns this L{FlatMenuItem} foreground text colour. """

        return self._textColour

#--------------------------------------------------------
# Class FlatMenu
#--------------------------------------------------------

[docs]class FlatMenu(FlatMenuBase):
    """
    A Flat popup menu generic implementation.
    """

[docs]    def __init__(self, parent=None):
        """
        Default class constructor.

        :param `parent`: the L{FlatMenu} parent window (used to initialize the
         underlying L{ShadowPopupWindow}).
        """

        self._menuWidth = 2*26
        self._leftMarginWidth = 26
        self._rightMarginWidth = 30
        self._borderXWidth = 1
        self._borderYWidth = 2
        self._activeWin = None
        self._focusWin = None
        self._imgMarginX = 0
        self._markerMarginX = 0
        self._textX = 26
        self._rightMarginPosX = -1
        self._itemHeight = 20
        self._selectedItem = -1
        self._clearCurrentSelection = True
        self._textPadding = 8
        self._marginHeight = 20
        self._marginWidth = 26
        self._accelWidth = 0
        self._mb = None
        self._itemsArr = []
        self._accelArray = []
        self._ptLast = wx.Point()
        self._resizeMenu = True
        self._shiftePos = 0
        self._first = 0
        self._mb_submenu = 0
        self._is_dismiss = False
        self._numCols = 1
        self._backgroundImage = None
        self._originalBackgroundImage = None

        FlatMenuBase.__init__(self, parent)

        self.SetSize(wx.Size(self._menuWidth, self._itemHeight+4))

        self.Bind(wx.EVT_PAINT, self.OnPaint)
        self.Bind(wx.EVT_ERASE_BACKGROUND, self.OnEraseBackground)
        self.Bind(wx.EVT_MOTION, self.OnMouseMove)
        self.Bind(wx.EVT_ENTER_WINDOW, self.OnMouseEnterWindow)
        self.Bind(wx.EVT_LEAVE_WINDOW, self.OnMouseLeaveWindow)
        self.Bind(wx.EVT_LEFT_DOWN, self.OnMouseLeftDown)
        self.Bind(wx.EVT_LEFT_UP, self.OnMouseLeftUp)
        self.Bind(wx.EVT_LEFT_DCLICK, self.OnMouseLeftDown)
        self.Bind(wx.EVT_RIGHT_DOWN, self.OnMouseRightDown)
        self.Bind(wx.EVT_KILL_FOCUS, self.OnKillFocus)
        self.Bind(wx.EVT_TIMER, self.OnTimer)

[docs]    def SetMenuBar(self, mb):
        """
        Attaches this menu to a menubar.

        :param `mb`: an instance of L{FlatMenuBar}.
        """

        self._mb = mb

[docs]    def SetSubMenuBar(self, mb):
        """
        Attaches this menu to a menubar.

        :param `mb`: an instance of L{FlatMenuBar}.
        """

        self._mb_submenu = mb

[docs]    def GetMenuBar(self):
        """ Returns the menubar associated with this menu item. """

        if self._mb_submenu:
            return self._mb_submenu

        return self._mb

[docs]    def GetMenuBarForSubMenu(self):
        """ Returns the menubar associated with this menu item. """

        return self._mb

[docs]    def Popup(self, pt, owner=None, parent=None):
        """
        Pops up the menu.

        :param `pt`: the point at which the menu should be popped up (an instance
         of `wx.Point`);
        :param `owner`: the owner of the menu. The owner does not necessarly mean the
         menu parent, it can also be the window that popped up it;
        :param `parent`: the menu parent window.
        """

        if "__WXMSW__" in wx.Platform:
            self._mousePtAtStartup = wx.GetMousePosition()

        # each time we popup, need to reset the starting index
        self._first = 0

        # Loop over self menu and send update UI event for
        # every item in the menu
        numEvents = len(self._itemsArr)
        cc = 0
        self._shiftePos = 0

        # Set the owner of the menu. All events will be directed to it.
        # If owner is None, the Default GetParent() is used as the owner
        self._owner = owner

        for cc in xrange(numEvents):
            self.SendUIEvent(cc)

        # Adjust menu position and show it
        FlatMenuBase.Popup(self, pt, parent)

        artMgr = ArtManager.Get()
        artMgr.MakeWindowTransparent(self, artMgr.GetTransparency())

        # Replace the event handler of the active window to direct
        # all keyboard events to us and the focused window to direct char events to us
        self._activeWin = wx.GetActiveWindow()
        if self._activeWin:

            oldHandler = self._activeWin.GetEventHandler()
            newEvtHandler = MenuKbdRedirector(self, oldHandler)
            self._activeWin.PushEventHandler(newEvtHandler)

        if "__WXMSW__" in wx.Platform:
            self._focusWin = wx.Window.FindFocus()
        elif "__WXGTK__" in wx.Platform:
            self._focusWin = self
        else:
            self._focusWin = None

        if self._focusWin:
            newEvtHandler = FocusHandler(self)
            self._focusWin.PushEventHandler(newEvtHandler)

[docs]    def Append(self, id, item, helpString="", kind=wx.ITEM_NORMAL):
        """
        Appends an item to this menu.

        :param integer `id`: the menu item identifier;
        :param string `item`: the string to appear on the menu item;
        :param string `helpString`: an optional help string associated with the item. By default,
         the handler for the ``EVT_FLAT_MENU_ITEM_MOUSE_OVER`` event displays this string
         in the status line;
        :param integer `kind`: may be ``wx.ITEM_NORMAL`` for a normal button (default),
         ``wx.ITEM_CHECK`` for a checkable tool (such tool stays pressed after it had been
         toggled) or ``wx.ITEM_RADIO`` for a checkable tool which makes part of a radio
         group of tools each of which is automatically unchecked whenever another button
         in the group is checked;
        """

        newItem = FlatMenuItem(self, id, item, helpString, kind)
        return self.AppendItem(newItem)

[docs]    def Prepend(self, id, item, helpString="", kind=wx.ITEM_NORMAL):
        """
        Prepends an item to this menu.

        :param integer `id`: the menu item identifier;
        :param string `item`: the string to appear on the menu item;
        :param string `helpString`: an optional help string associated with the item. By default,
         the handler for the ``EVT_FLAT_MENU_ITEM_MOUSE_OVER`` event displays this string
         in the status line;
        :param integer `kind`: may be ``wx.ITEM_NORMAL`` for a normal button (default),
         ``wx.ITEM_CHECK`` for a checkable tool (such tool stays pressed after it had been
         toggled) or ``wx.ITEM_RADIO`` for a checkable tool which makes part of a radio
         group of tools each of which is automatically unchecked whenever another button
         in the group is checked;
        """

        newItem = FlatMenuItem(self, id, item, helpString, kind)
        return self.PrependItem(newItem)

[docs]    def AppendSubMenu(self, subMenu, item, helpString=""):
        """
        Adds a pull-right submenu to the end of the menu.

        This function is added to duplicate the API of `wx.Menu`.

        :see: L{AppendMenu} for an explanation of the input parameters.
        """

        return self.AppendMenu(wx.ID_ANY, item, subMenu, helpString)

[docs]    def AppendMenu(self, id, item, subMenu, helpString=""):
        """
        Adds a pull-right submenu to the end of the menu.

        :param integer `id`: the menu item identifier;
        :param string `item`: the string to appear on the menu item;
        :param `subMenu`: an instance of L{FlatMenu}, the submenu to append;
        :param string `helpString`: an optional help string associated with the item. By default,
         the handler for the ``EVT_FLAT_MENU_ITEM_MOUSE_OVER`` event displays this string
         in the status line.
        """

        newItem = FlatMenuItem(self, id, item, helpString, wx.ITEM_NORMAL, subMenu)
        return self.AppendItem(newItem)

[docs]    def AppendItem(self, menuItem):
        """
        Appends an item to this menu.

        :param `menuItem`: an instance of L{FlatMenuItem}.
        """

        self._itemsArr.append(menuItem)
        return self.AddItem(menuItem)

[docs]    def PrependItem(self, menuItem):
        """
        Prepends an item to this menu.

        :param `menuItem`: an instance of L{FlatMenuItem}.
        """

        self._itemsArr.insert(0,menuItem)
        return self.AddItem(menuItem)

[docs]    def AddItem(self, menuItem):
        """
        Internal function to add the item to this menu. The item must
        already be in the `self._itemsArr` attribute.

        :param `menuItem`: an instance of L{FlatMenuItem}.
        """

        if not menuItem:
            raise Exception("Adding None item?")

        # Reparent to us
        menuItem.SetMenu(self)
        menuItem._isAttachedToMenu = True

        # Update the menu width if necessary
        menuItemWidth = self.GetMenuItemWidth(menuItem)
        self._menuWidth = (self._menuWidth > menuItemWidth + self._accelWidth and \
                           [self._menuWidth] or [menuItemWidth + self._accelWidth])[0]

        menuHeight = 0
        switch = 1e6

        if self._numCols > 1:
            nItems = len(self._itemsArr)
            switch = int(math.ceil((nItems - self._first)/float(self._numCols)))

        for indx, item in enumerate(self._itemsArr):

            if indx >= switch:
                break

            if item.IsSeparator():
                menuHeight += self.GetRenderer().separatorHeight
            else:
                menuHeight += self._itemHeight

        self.SetSize(wx.Size(self._menuWidth*self._numCols, menuHeight+4))

        if self._originalBackgroundImage:
            img = wx.ImageFromBitmap(self._originalBackgroundImage)
            img = img.Scale(self._menuWidth*self._numCols-2-self._leftMarginWidth, menuHeight, wx.IMAGE_QUALITY_HIGH)
            self._backgroundImage = img.ConvertToBitmap()

        # Add accelerator entry to the menu if needed
        accel = menuItem.GetAcceleratorEntry()

        if accel:
            accel.Set(accel.GetFlags(), accel.GetKeyCode(), menuItem.GetId())
            self._accelArray.append(accel)

        self.UpdateRadioGroup(menuItem)

        return menuItem

[docs]    def GetMenuItems(self):
        """ Returns the list of menu items in the menu. """

        return self._itemsArr

[docs]    def GetMenuItemWidth(self, menuItem):
        """
        Returns the width of a particular item.

        :param `menuItem`: an instance of L{FlatMenuItem}.
        """

        menuItemWidth = 0
        text = menuItem.GetLabel() # Without accelerator
        accel = menuItem.GetAccelString()

        dc = wx.ClientDC(self)

        font = menuItem.GetFont()
        if font is None:
            font = ArtManager.Get().GetFont()

        dc.SetFont(font)

        accelFiller = "XXXX"     # 4 spaces betweem text and accel column

        # Calc text length/height
        dummy, itemHeight = dc.GetTextExtent("Tp")
        width, height = dc.GetTextExtent(text)
        accelWidth, accelHeight = dc.GetTextExtent(accel)
        filler, dummy = dc.GetTextExtent(accelFiller)

        bmpHeight = bmpWidth = 0

        if menuItem.GetBitmap().Ok():
            bmpHeight = menuItem.GetBitmap().GetHeight()
            bmpWidth  = menuItem.GetBitmap().GetWidth()

        if itemHeight < self._marginHeight:
            itemHeight = self._marginHeight

        itemHeight = (bmpHeight > self._itemHeight and [bmpHeight] or [itemHeight])[0]
        itemHeight += 2*self._borderYWidth

        # Update the global menu item height if needed
        self._itemHeight = (self._itemHeight > itemHeight and [self._itemHeight] or [itemHeight])[0]
        self._marginWidth = (self._marginWidth > bmpWidth and [self._marginWidth] or [bmpWidth])[0]

        # Update the accel width
        accelWidth += filler
        if accel:
            self._accelWidth = (self._accelWidth > accelWidth and [self._accelWidth] or [accelWidth])[0]

        # In case the item has image & is type radio or check, we need double size
        # left margin
        factor = (((menuItem.GetBitmap() != wx.NullBitmap) and \
                   (menuItem.IsCheckable() or (menuItem.GetKind() == wx.ITEM_RADIO))) and [2] or [1])[0]

        if factor == 2:

            self._imgMarginX = self._marginWidth + 2*self._borderXWidth
            self._leftMarginWidth = 2 * self._marginWidth + 2*self._borderXWidth

        else:

            self._leftMarginWidth = ((self._leftMarginWidth > self._marginWidth + 2*self._borderXWidth) and \
                                    [self._leftMarginWidth] or [self._marginWidth + 2*self._borderXWidth])[0]

        menuItemWidth = self.GetLeftMarginWidth() + 2*self.GetBorderXWidth() + width + self.GetRightMarginWidth()
        self._textX = self._imgMarginX + self._marginWidth + self._textPadding

        # update the rightMargin X position
        self._rightMarginPosX = ((self._textX + width + self._accelWidth> self._rightMarginPosX) and \
                                 [self._textX + width + self._accelWidth] or [self._rightMarginPosX])[0]

        return menuItemWidth

[docs]    def GetMenuWidth(self):
        """ Returns the menu width in pixels. """

        return self._menuWidth

[docs]    def GetLeftMarginWidth(self):
        """ Returns the menu left margin width, in pixels. """

        return self._leftMarginWidth

[docs]    def GetRightMarginWidth(self):
        """ Returns the menu right margin width, in pixels. """

        return self._rightMarginWidth

[docs]    def GetBorderXWidth(self):
        """ Returns the menu border x-width, in pixels. """

        return self._borderXWidth

[docs]    def GetBorderYWidth(self):
        """ Returns the menu border y-width, in pixels. """

        return self._borderYWidth

[docs]    def GetItemHeight(self):
        """ Returns the height of a particular item, in pixels. """

        return self._itemHeight

[docs]    def AppendCheckItem(self, id, item, helpString=""):
        """
        Adds a checkable item to the end of the menu.

        :see: L{Append} for the explanation of the input parameters.
        """

        newItem = FlatMenuItem(self, id, item, helpString, wx.ITEM_CHECK)
        return self.AppendItem(newItem)

[docs]    def AppendRadioItem(self, id, item, helpString=""):
        """
        Adds a radio item to the end of the menu.

        All consequent radio items form a group and when an item in the group is
        checked, all the others are automatically unchecked.

        :see: L{Append} for the explanation of the input parameters.
        """

        newItem = FlatMenuItem(self, id, item, helpString, wx.ITEM_RADIO)
        return self.AppendItem(newItem)

[docs]    def AppendSeparator(self):
        """ Appends a separator item to the end of this menu. """

        newItem = FlatMenuItem(self)
        return self.AppendItem(newItem)

[docs]    def InsertSeparator(self, pos):
        """
        Inserts a separator at the given position.

        :param integer `pos`: the index at which we want to insert the separator.
        """

        newItem = FlatMenuItem(self)
        return self.Insert(pos, newItem)

[docs]    def Dismiss(self, dismissParent, resetOwner):
        """
        Dismisses the popup window.

        :param bool `dismissParent`: whether to dismiss the parent menu or not;
        :param bool `resetOwner`: ``True`` to delete the link between this menu and the
         owner menu, ``False`` otherwise.
        """

        if self._activeWin:

            self._activeWin.PopEventHandler(True)
            self._activeWin = None

        if self._focusWin:

            self._focusWin.PopEventHandler(True)
            self._focusWin = None

        self._selectedItem = -1

        if self._mb:
            self._mb.RemoveHelp()

        FlatMenuBase.Dismiss(self, dismissParent, resetOwner)

[docs]    def OnPaint(self, event):
        """
        Handles the ``wx.EVT_PAINT`` event for L{FlatMenu}.

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

        dc = wx.PaintDC(self)
        self.GetRenderer().DrawMenu(self, dc)

        # We need to redraw all our child menus
        self.RefreshChilds()

[docs]    def UpdateItem(self, item):
        """
        Updates an item.

        :param `item`: an instance of L{FlatMenuItem}.
        """

        # notify menu bar that an item was modified directly
        if item and self._mb:
            self._mb.UpdateItem(item)

[docs]    def OnEraseBackground(self, event):
        """
        Handles the ``wx.EVT_ERASE_BACKGROUND`` event for L{FlatMenu}.

        :param `event`: a `wx.EraseEvent` event to be processed.

        :note: This method is intentionally empty to avoid flicker.
        """

        pass

[docs]    def DrawSelection(self, dc, oldSelection=-1):
        """
        Redraws the menu.

        :param `dc`: an instance of `wx.DC`;
        :param integer `oldSelection`: if non-negative, the index representing the previous selected
         menu item.
        """

        self.Refresh()

[docs]    def RefreshChilds(self):
        """
        In some cases, we need to perform a recursive refresh for all opened submenu
        from this.
        """

        # Draw all childs menus of self menu as well
        child = self._openedSubMenu
        while child:
            dc = wx.ClientDC(child)
            self.GetRenderer().DrawMenu(child, dc)
            child = child._openedSubMenu

[docs]    def GetMenuRect(self):
        """ Returns the menu client rectangle. """

        clientRect = self.GetClientRect()
        return wx.Rect(clientRect.x, clientRect.y, clientRect.width, clientRect.height)

[docs]    def OnKeyDown(self, event):
        """
        Handles the ``wx.EVT_KEY_DOWN`` event for L{FlatMenu}.

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

        self.OnChar(event.GetKeyCode())

[docs]    def OnChar(self, key):
        """
        Handles key events for L{FlatMenu}.

        :param `key`: the keyboard key integer code.
        """

        processed = True

        if key == wx.WXK_ESCAPE:

            if self._parentMenu:
                self._parentMenu.CloseSubMenu(-1)
            else:
                self.Dismiss(True, True)

        elif key == wx.WXK_LEFT:

            if self._parentMenu:
                # We are a submenu, dismiss us.
                self._parentMenu.CloseSubMenu(-1)
            else:
                # try to find our root menu, if we are attached to menubar,
                # let it try and open the previous menu
                root = self.GetRootMenu()
                if root:
                    if root._mb:
                        root._mb.ActivatePreviousMenu()

        elif key == wx.WXK_RIGHT:

            if not self.TryOpenSubMenu(self._selectedItem, True):
                # try to find our root menu, if we are attached to menubar,
                # let it try and open the previous menu
                root = self.GetRootMenu()
                if root:
                    if root._mb:
                        root._mb.ActivateNextMenu()

        elif key == wx.WXK_UP:
            self.AdvanceSelection(False)

        elif key == wx.WXK_DOWN:

            self.AdvanceSelection()

        elif key in [wx.WXK_RETURN, wx.WXK_NUMPAD_ENTER]:
            self.DoAction(self._selectedItem)

        elif key == wx.WXK_HOME:

            # Select first item of the menu
            if self._selectedItem != 0:
                oldSel = self._selectedItem
                self._selectedItem = 0
                dc = wx.ClientDC(self)
                self.DrawSelection(dc, oldSel)

        elif key == wx.WXK_END:

            # Select last item of the menu
            if self._selectedItem != len(self._itemsArr)-1:
                oldSel = self._selectedItem
                self._selectedItem = len(self._itemsArr)-1
                dc = wx.ClientDC(self)
                self.DrawSelection(dc, oldSel)

        elif key in [wx.WXK_CONTROL, wx.WXK_ALT]:
            # Alt was pressed
            root = self.GetRootMenu()
            root.Dismiss(False, True)

        else:
            try:
                chrkey = chr(key)
            except:
                return processed

            if chrkey.isalnum():

                ch = chrkey.lower()

                # Iterate over all the menu items
                itemIdx = -1
                occur = 0

                for i in xrange(len(self._itemsArr)):

                    item = self._itemsArr[i]
                    mnemonic = item.GetMnemonicChar()

                    if mnemonic == ch:

                        if itemIdx == -1:

                            itemIdx = i
                            # We keep the index of only
                            # the first occurence

                        occur += 1

                        # Keep on looping until no more items for self menu

                if itemIdx != -1:

                    if occur > 1:

                        # We select the first item
                        if self._selectedItem == itemIdx:
                            return processed

                        oldSel = self._selectedItem
                        self._selectedItem = itemIdx
                        dc = wx.ClientDC(self)
                        self.DrawSelection(dc, oldSel)

                    elif occur == 1:

                        # Activate the item, if self is a submenu item we first select it
                        item = self._itemsArr[itemIdx]
                        if item.IsSubMenu() and self._selectedItem != itemIdx:

                            oldSel = self._selectedItem
                            self._selectedItem = itemIdx
                            dc = wx.ClientDC(self)
                            self.DrawSelection(dc, oldSel)

                        self.DoAction(itemIdx)

                else:

                    processed = False

        return processed

[docs]    def AdvanceSelection(self, down=True):
        """
        Advance forward or backward the current selection.

        :param bool `down`: ``True`` to advance the selection forward, ``False`` otherwise.
        """

        # make sure we have at least two items in the menu (which are not
        # separators)
        num=0
        singleItemIdx = -1

        for i in xrange(len(self._itemsArr)):

            item = self._itemsArr[i]
            if item.IsSeparator():
                continue
            num += 1
            singleItemIdx = i

        if num < 1:
            return

        if num == 1:
            # Select the current one
            self._selectedItem = singleItemIdx
            dc = wx.ClientDC(self)
            self.DrawSelection(dc, -1)
            return

        oldSelection = self._selectedItem

        if not down:

            # find the next valid item
            while 1:

                self._selectedItem -= 1
                if self._selectedItem < 0:
                    self._selectedItem = len(self._itemsArr)-1
                if not self._itemsArr[self._selectedItem].IsSeparator():
                    break

        else:

            # find the next valid item
            while 1:

                self._selectedItem += 1
                if self._selectedItem > len(self._itemsArr)-1:
                    self._selectedItem = 0
                if not self._itemsArr[self._selectedItem].IsSeparator():
                    break

        dc = wx.ClientDC(self)
        self.DrawSelection(dc, oldSelection)

[docs]    def HitTest(self, pos):
        """
        HitTest method for L{FlatMenu}.

        :param `pos`: an instance of `wx.Point`, a point to test for hits.

        :return: A tuple representing one of the following combinations:

         ========================= ==================================================
         Return Tuple              Description
         ========================= ==================================================
         (0, -1)                   The L{HitTest} method didn't find any item with the specified input point `pt` (``MENU_HT_NONE`` = 0)
         (1, `integer`)            A menu item has been hit (``MENU_HT_ITEM`` = 1)
         (2, -1)                   The `Scroll Up` button has been hit (``MENU_HT_SCROLL_UP`` = 2)
         (3, -1)                   The `Scroll Down` button has been hit (``MENU_HT_SCROLL_DOWN`` = 3)
         ========================= ==================================================

        """

        if self._showScrollButtons:

            if self._upButton and self._upButton.GetClientRect().Contains(pos):
                return MENU_HT_SCROLL_UP, -1

            if self._downButton and self._downButton.GetClientRect().Contains(pos):
                return MENU_HT_SCROLL_DOWN, -1

        for ii, item in enumerate(self._itemsArr):

            if item.GetRect().Contains(pos) and item.IsEnabled() and item.IsShown():
                return MENU_HT_ITEM, ii

        return MENU_HT_NONE, -1

[docs]    def OnMouseMove(self, event):
        """
        Handles the ``wx.EVT_MOTION`` event for L{FlatMenu}.

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

        if "__WXMSW__" in wx.Platform:
            # Ignore dummy mouse move events
            pt = wx.GetMousePosition()
            if self._mousePtAtStartup == pt:
                return

        pos = event.GetPosition()

        # we need to ignore extra mouse events: example when this happens is when
        # the mouse is on the menu and we open a submenu from keyboard - Windows
        # then sends us a dummy mouse move event, we (correctly) determine that it
        # happens in the parent menu and so immediately close the just opened
        # submenunot

        if "__WXMSW__" in wx.Platform:

            ptCur = self.ClientToScreen(pos)
            if ptCur == self._ptLast:
                return

            self._ptLast = ptCur

        # first let the scrollbar handle it
        self.TryScrollButtons(event)
        self.ProcessMouseMove(pos)

[docs]    def OnMouseLeftDown(self, event):
        """
        Handles the ``wx.EVT_LEFT_DOWN`` event for L{FlatMenu}.

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

        if self.TryScrollButtons(event):
            return

        pos = event.GetPosition()
        self.ProcessMouseLClick(pos)

[docs]    def OnMouseLeftUp(self, event):
        """
        Handles the ``wx.EVT_LEFT_UP`` event for L{FlatMenu}.

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

        if self.TryScrollButtons(event):
            return

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

        if not rect.Contains(pos):

            # The event is not in our coords,
            # so we try our parent
            win = self._parentMenu

            while win:

                # we need to translate our client coords to the client coords of the
                # window we forward this event to
                ptScreen = self.ClientToScreen(pos)
                p = win.ScreenToClient(ptScreen)

                if win.GetClientRect().Contains(p):

                    event.m_x = p.x
                    event.m_y = p.y
                    win.OnMouseLeftUp(event)
                    return

                else:
                    # try the grandparent
                    win = win._parentMenu

        else:
            self.ProcessMouseLClickEnd(pos)

        if self._showScrollButtons:

            if self._upButton:
                self._upButton.ProcessLeftUp(pos)
            if self._downButton:
                self._downButton.ProcessLeftUp(pos)

[docs]    def OnMouseRightDown(self, event):
        """
        Handles the ``wx.EVT_RIGHT_DOWN`` event for L{FlatMenu}.

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

        if self.TryScrollButtons(event):
            return

        pos = event.GetPosition()
        self.ProcessMouseRClick(pos)

[docs]    def ProcessMouseRClick(self, pos):
        """
        Processes mouse right clicks.

        :param `pos`: the position at which the mouse right button was pressed,
         an instance of `wx.Point`.
        """

        rect = self.GetClientRect()

        if not rect.Contains(pos):

            # The event is not in our coords,
            # so we try our parent

            win = self._parentMenu
            while win:

                # we need to translate our client coords to the client coords of the
                # window we forward self event to
                ptScreen = self.ClientToScreen(pos)
                p = win.ScreenToClient(ptScreen)

                if win.GetClientRect().Contains(p):
                    win.ProcessMouseRClick(p)
                    return

                else:
                    # try the grandparent
                    win = win._parentMenu

            # At this point we can assume that the event was not
            # processed, so we dismiss the menu and its children
            self.Dismiss(True, True)
            return

        # test if we are on a menu item
        res, itemIdx = self.HitTest(pos)
        if res == MENU_HT_ITEM:
            self.OpenItemContextMenu(itemIdx)

[docs]    def OpenItemContextMenu(self, itemIdx):
        """
        Open an item's context menu (if any).

        :param integer `itemIdx`: the index of the item for which we want to open the context menu.
        """

        item = self._itemsArr[itemIdx]
        context_menu = item.GetContextMenu()

        # If we have a context menu, close any opened submenu
        if context_menu:
            self.CloseSubMenu(itemIdx, True)

        if context_menu and not context_menu.IsShown():
            # Popup child menu
            pos = wx.Point()
            pos.x = item.GetRect().GetWidth() + item.GetRect().GetX() - 5
            pos.y = item.GetRect().GetY()
            self._clearCurrentSelection = False
            self._openedSubMenu = context_menu
            context_menu.Popup(self.ScreenToClient(wx.GetMousePosition()), self._owner, self)
            return True

        return False

[docs]    def ProcessMouseLClick(self, pos):
        """
        Processes mouse left clicks.

        :param `pos`: the position at which the mouse left button was pressed,
         an instance of `wx.Point`.
        """

        rect = self.GetClientRect()

        if not rect.Contains(pos):

            # The event is not in our coords,
            # so we try our parent

            win = self._parentMenu
            while win:

                # we need to translate our client coords to the client coords of the
                # window we forward self event to
                ptScreen = self.ClientToScreen(pos)
                p = win.ScreenToClient(ptScreen)

                if win.GetClientRect().Contains(p):
                    win.ProcessMouseLClick(p)
                    return

                else:
                    # try the grandparent
                    win = win._parentMenu

            # At this point we can assume that the event was not
            # processed, so we dismiss the menu and its children
            self.Dismiss(True, True)
            return

[docs]    def ProcessMouseLClickEnd(self, pos):
        """
        Processes mouse left clicks.

        :param `pos`: the position at which the mouse left button was pressed,
         an instance of `wx.Point`.
        """

        self.ProcessMouseLClick(pos)

        # test if we are on a menu item
        res, itemIdx = self.HitTest(pos)

        if res == MENU_HT_ITEM:
            self.DoAction(itemIdx)

        elif res == MENU_HT_SCROLL_UP:
            if self._upButton:
                self._upButton.ProcessLeftDown(pos)

        elif res == MENU_HT_SCROLL_DOWN:
            if self._downButton:
                self._downButton.ProcessLeftDown(pos)

        else:
            self._selectedItem = -1

[docs]    def ProcessMouseMove(self, pos):
        """
        Processes mouse movements.

        :param `pos`: the position at which the mouse was moved, an instance of `wx.Point`.
        """

        rect = self.GetClientRect()

        if not rect.Contains(pos):

            # The event is not in our coords,
            # so we try our parent

            win = self._parentMenu
            while win:

                # we need to translate our client coords to the client coords of the
                # window we forward self event to
                ptScreen = self.ClientToScreen(pos)
                p = win.ScreenToClient(ptScreen)

                if win.GetClientRect().Contains(p):
                    win.ProcessMouseMove(p)
                    return

                else:
                    # try the grandparent
                    win = win._parentMenu

            # If we are attached to a menu bar,
            # let him process the event as well
            if self._mb:

                ptScreen = self.ClientToScreen(pos)
                p = self._mb.ScreenToClient(ptScreen)

                if self._mb.GetClientRect().Contains(p):

                    # let the menu bar process it
                    self._mb.ProcessMouseMoveFromMenu(p)
                    return

            if self._mb_submenu:
                ptScreen = self.ClientToScreen(pos)
                p = self._mb_submenu.ScreenToClient(ptScreen)
                if self._mb_submenu.GetClientRect().Contains(p):
                    # let the menu bar process it
                    self._mb_submenu.ProcessMouseMoveFromMenu(p)
                    return

            return

        # test if we are on a menu item
        res, itemIdx = self.HitTest(pos)

        if res == MENU_HT_SCROLL_DOWN:

            if self._downButton:
                self._downButton.ProcessMouseMove(pos)

        elif res == MENU_HT_SCROLL_UP:

            if self._upButton:
                self._upButton.ProcessMouseMove(pos)

        elif res == MENU_HT_ITEM:

            if self._downButton:
                self._downButton.ProcessMouseMove(pos)

            if self._upButton:
                self._upButton.ProcessMouseMove(pos)

            if self._selectedItem == itemIdx:
                return

            # Message to send when out of last selected item
            if self._selectedItem != -1:
                self.SendOverItem(self._selectedItem, False)
            self.SendOverItem(itemIdx, True)   # Message to send when over an item

            oldSelection = self._selectedItem
            self._selectedItem = itemIdx
            self.CloseSubMenu(self._selectedItem)

            dc = wx.ClientDC(self)
            self.DrawSelection(dc, oldSelection)

            self.TryOpenSubMenu(self._selectedItem)

            if self._mb:
                self._mb.RemoveHelp()
                if itemIdx >= 0:
                    self._mb.DoGiveHelp(self._itemsArr[itemIdx])

        else:

            # Message to send when out of last selected item
            if self._selectedItem != -1:
                item = self._itemsArr[self._selectedItem]
                if item.IsSubMenu() and item.GetSubMenu().IsShown():
                    return

                # Message to send when out of last selected item
                if self._selectedItem != -1:
                    self.SendOverItem(self._selectedItem, False)

            oldSelection = self._selectedItem
            self._selectedItem = -1
            dc = wx.ClientDC(self)
            self.DrawSelection(dc, oldSelection)

[docs]    def OnMouseLeaveWindow(self, event):
        """
        Handles the ``wx.EVT_LEAVE_WINDOW`` event for L{FlatMenu}.

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

        if self._mb:
            self._mb.RemoveHelp()

        if self._clearCurrentSelection:

            # Message to send when out of last selected item
            if self._selectedItem != -1:
                item = self._itemsArr[self._selectedItem]
                if item.IsSubMenu() and item.GetSubMenu().IsShown():
                    return

                # Message to send when out of last selected item
                if self._selectedItem != -1:
                    self.SendOverItem(self._selectedItem, False)

            oldSelection = self._selectedItem
            self._selectedItem = -1
            dc = wx.ClientDC(self)
            self.DrawSelection(dc, oldSelection)

        self._clearCurrentSelection = True

        if "__WXMSW__" in wx.Platform:
            self.SetCursor(self._oldCur)

[docs]    def OnMouseEnterWindow(self, event):
        """
        Handles the ``wx.EVT_ENTER_WINDOW`` event for L{FlatMenu}.

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

        if "__WXMSW__" in wx.Platform:
            self._oldCur = self.GetCursor()
            self.SetCursor(wx.StockCursor(wx.CURSOR_ARROW))

        event.Skip()

[docs]    def OnKillFocus(self, event):
        """
        Handles the ``wx.EVT_KILL_FOCUS`` event for L{FlatMenu}.

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

        self.Dismiss(True, True)

[docs]    def CloseSubMenu(self, itemIdx, alwaysClose=False):
        """
        Closes a child sub-menu.

        :param integer `itemIdx`: the index of the item for which we want to close the submenu;
        :param bool `alwaysClose`: if ``True``, always close the submenu irrespectively of
         other conditions.
        """

        item = None
        subMenu = None

        if itemIdx >= 0 and itemIdx < len(self._itemsArr):
            item = self._itemsArr[itemIdx]

        # Close sub-menu first
        if item:
            subMenu = item.GetSubMenu()

        if self._openedSubMenu:
            if self._openedSubMenu != subMenu or alwaysClose:
                # We have another sub-menu open, close it
                self._openedSubMenu.Dismiss(False, True)
                self._openedSubMenu = None

[docs]    def DoAction(self, itemIdx):
        """
        Performs an action based on user selection.

        :param integer `itemIdx`: the index of the item for which we want to perform the action.
        """

        if itemIdx < 0 or itemIdx >= len(self._itemsArr):
            raise Exception("Invalid menu item")
            return

        item = self._itemsArr[itemIdx]

        if not item.IsEnabled() or item.IsSeparator():
            return

        # Close sub-menu if needed
        self.CloseSubMenu(itemIdx)

        if item.IsSubMenu() and not item.GetSubMenu().IsShown():

            # Popup child menu
            self.TryOpenSubMenu(itemIdx)
            return

        if item.IsRadioItem():
            # if the radio item is already checked,
            # just send command event. Else, check it, uncheck the current
            # checked item in the radio item group, and send command event
            if not item.IsChecked():
                item._groupPtr.SetSelection(item)

        elif item.IsCheckable():

            item.Check(not item.IsChecked())
            dc = wx.ClientDC(self)
            self.DrawSelection(dc)

        if not item.IsSubMenu():

            self.Dismiss(True, False)

            # Send command event
            self.SendCmdEvent(itemIdx)

[docs]    def TryOpenSubMenu(self, itemIdx, selectFirst=False):
        """
        If `itemIdx` is an item with submenu, open it.

        :param integer `itemIdx`: the index of the item for which we want to open the submenu;
        :param bool `selectFirst`: if ``True``, the first item of the submenu will be shown
         as selected.
        """

        if itemIdx < 0 or itemIdx >= len(self._itemsArr):
            return False

        item = self._itemsArr[itemIdx]
        if item.IsSubMenu() and not item.GetSubMenu().IsShown():

            pos = wx.Point()

            # Popup child menu
            pos.x = item.GetRect().GetWidth()+ item.GetRect().GetX()-5
            pos.y = item.GetRect().GetY()
            self._clearCurrentSelection = False
            self._openedSubMenu = item.GetSubMenu()
            item.GetSubMenu().Popup(pos, self._owner, self)

            # Select the first child
            if selectFirst:

                dc = wx.ClientDC(item.GetSubMenu())
                item.GetSubMenu()._selectedItem = 0
                item.GetSubMenu().DrawSelection(dc)

            return True

        return False

    def _RemoveById(self, id):
        """ Used internally. """

        # First we search for the menu item (recursively)
        menuParent = None
        item = None
        idx = wx.NOT_FOUND
        idx, menuParent = self.FindMenuItemPos(id)

        if idx != wx.NOT_FOUND:

            # Remove the menu item
            item = menuParent._itemsArr[idx]
            menuParent._itemsArr.pop(idx)

            # update group
            if item._groupPtr and item.IsRadioItem():
                item._groupPtr.Remove(item)

            # Resize the menu
            menuParent.ResizeMenu()

        return item

[docs]    def Remove(self, item):
        """
        Removes the menu item from the menu but doesn't delete the associated menu
        object. This allows to reuse the same item later by adding it back to the
        menu (especially useful with submenus).

        :param `item`: can be either a menu item identifier or a plain L{FlatMenuItem}.
        """

        if type(item) != type(1):
            item = item.GetId()

        return self._RemoveById(item)

    Delete = Remove

    def _DestroyById(self, id):
        """ Used internally. """

        item = None
        item = self.Remove(id)

        if item:
            del item

[docs]    def Destroy(self, item):
        """
        Deletes the menu item from the menu. If the item is a submenu, it will be
        deleted. Use L{Remove} if you want to keep the submenu (for example, to reuse
        it later).

        :param `item`: can be either a menu item identifier or a plain L{FlatMenuItem}.
        """

        if type(item) != type(1):
            item = item.GetId()

        self._DestroyById(item)

[docs]    def Insert(self, pos, id, item, helpString="", kind=wx.ITEM_NORMAL):
        """
        Inserts the given `item` before the position `pos`.

        :param integer `pos`: the position at which to insert the new menu item;
        :param integer `id`: the menu item identifier;
        :param string `item`: the string to appear on the menu item;
        :param string `helpString`: an optional help string associated with the item. By default,
         the handler for the ``EVT_FLAT_MENU_ITEM_MOUSE_OVER`` event displays this string
         in the status line;
        :param integer `kind`: may be ``wx.ITEM_NORMAL`` for a normal button (default),
         ``wx.ITEM_CHECK`` for a checkable tool (such tool stays pressed after it had been
         toggled) or ``wx.ITEM_RADIO`` for a checkable tool which makes part of a radio
         group of tools each of which is automatically unchecked whenever another button
         in the group is checked;
        """

        newitem = FlatMenuItem(self, id, item, helpString, kind)
        return self.InsertItem(pos, newitem)

[docs]    def InsertItem(self, pos, item):
        """
        Inserts an item into the menu.

        :param integer `pos`: the position at which to insert the new menu item;
        :param `item`: an instance of L{FlatMenuItem}.
        """

        if pos == len(self._itemsArr):
            # Append it
            return self.AppendItem(item)

        # Insert the menu item
        self._itemsArr.insert(pos, item)
        item._isAttachedToMenu = True

        # Recalculate the menu geometry
        self.ResizeMenu()

        # Update radio groups
        self.UpdateRadioGroup(item)

        return item

[docs]    def UpdateRadioGroup(self, item):
        """
        Updates a group of radio items.

        :param `item`: an instance of L{FlatMenuItem}.
        """

        if item.IsRadioItem():

            # Udpate radio groups in case this item is a radio item
            sibling = self.GetSiblingGroupItem(item)
            if sibling:

                item._groupPtr = sibling._groupPtr
                item._groupPtr.Add(item)

                if item.IsChecked():

                    item._groupPtr.SetSelection(item)

            else:

                # first item in group
                item._groupPtr = FlatMenuItemGroup()
                item._groupPtr.Add(item)
                item._groupPtr.SetSelection(item)

[docs]    def ResizeMenu(self):
        """ Resizes the menu to the correct size. """

        # can we do the resize?
        if not self._resizeMenu:
            return

        items = self._itemsArr
        self._itemsArr = []

        # Clear accelerator table
        self._accelArray = []

        # Reset parameters and menu size
        self._menuWidth =  2*self._marginWidth
        self._imgMarginX = 0
        self._markerMarginX = 0
        self._textX = self._marginWidth
        self._rightMarginPosX = -1
        self._itemHeight = self._marginHeight
        self.SetSize(wx.Size(self._menuWidth*self._numCols, self._itemHeight+4))

        # Now we simply add the items
        for item in items:
            self.AppendItem(item)

[docs]    def SetNumberColumns(self, numCols):
        """
        Sets the number of columns for a menu window.

        :param integer `numCols`: the number of columns for this L{FlatMenu} window.
        """

        if self._numCols == numCols:
            return

        self._numCols = numCols
        self.ResizeMenu()
        self.Refresh()

[docs]    def GetNumberColumns(self):
        """ Returns the number of columns for a menu window. """

        return self._numCols

[docs]    def FindItem(self, itemId, menu=None):
        """
        Finds the menu item object associated with the given menu item identifier and,
        optionally, the (sub)menu it belongs to.

        :param integer `itemId`: menu item identifier;
        :param `menu`: if not ``None``, it will be filled with the item's parent menu
         (if the item was found).

        :return: The found menu item object, or ``None`` if one was not found.
        """

        idx = wx.NOT_FOUND

        if menu:

            idx, menu = self.FindMenuItemPos(itemId, menu)
            if idx != wx.NOT_FOUND:
                return menu._itemsArr[idx]
            else:
                return None

        else:

            idx, parentMenu = self.FindMenuItemPos(itemId, None)
            if idx != wx.NOT_FOUND:
                return parentMenu._itemsArr[idx]
            else:
                return None

[docs]    def SetItemFont(self, itemId, font=None):
        """
        Sets the L{FlatMenuItem} font.

        :param integer `itemId`: the menu item identifier;
        :param `font`: an instance of a valid `wx.Font`.
        """

        item = self.FindItem(itemId)
        item.SetFont(font)

[docs]    def GetItemFont(self, itemId):
        """
        Returns this L{FlatMenuItem} font.

        :param integer `itemId`: the menu item identifier.
        """

        item = self.FindItem(itemId)
        return item.GetFont()

[docs]    def SetItemTextColour(self, itemId, colour=None):
        """
        Sets the L{FlatMenuItem} foreground text colour.

        :param integer `itemId`: the menu item identifier;
        :param `colour`: an instance of a valid `wx.Colour`.
        """

        item = self.FindItem(itemId)
        item.SetTextColour(colour)

[docs]    def GetItemTextColour(self, itemId):
        """
        Returns this L{FlatMenuItem} foreground text colour.

        :param integer `itemId`: the menu item identifier.
        """

        item = self.FindItem(itemId)
        return item.GetTextColour()

[docs]    def SetLabel(self, itemId, label):
        """
        Sets the label of a L{FlatMenuItem}.

        :param integer `itemId`: the menu item identifier;
        :param string `label`: the menu item label to set.

        :see: L{GetLabel}.
        """

        item = self.FindItem(itemId)
        item.SetLabel(label)
        item.SetText(label)

        self.ResizeMenu()

[docs]    def GetLabel(self, itemId):
        """
        Returns the label of a L{FlatMenuItem}.

        :param integer `id`: the menu item identifier;

        :see: L{SetLabel}.
        """

        item = self.FindItem(itemId)
        return item.GetText()

[docs]    def FindMenuItemPos(self, itemId, menu=None):
        """
        Finds an item and its position inside the menu based on its id.

        :param integer `itemId`: menu item identifier;
        :param `menu`: if not ``None``, it will be filled with the item's parent menu
         (if the item was found).

        :return: The found menu item object, or ``None`` if one was not found.
        """

        menu = None
        item = None

        idx = wx.NOT_FOUND

        for i in xrange(len(self._itemsArr)):

            item = self._itemsArr[i]

            if item.GetId() == itemId:

                menu = self
                idx = i
                break

            elif item.IsSubMenu():

                idx, menu = item.GetSubMenu().FindMenuItemPos(itemId, menu)
                if idx != wx.NOT_FOUND:
                    break

            else:

                item = None

        return idx, menu

[docs]    def GetAccelTable(self):
        """ Returns the menu accelerator table, an instance of `wx.AcceleratorTable`. """

        n = len(self._accelArray)
        if n == 0:
            return wx.NullAcceleratorTable

        entries = [wx.AcceleratorEntry() for ii in xrange(n)]

        for counter in len(entries):
            entries[counter] = self._accelArray[counter]

        table = wx.AcceleratorTable(entries)
        del entries

        return table

[docs]    def GetMenuItemCount(self):
        """ Returns the number of items in the L{FlatMenu}. """

        return len(self._itemsArr)

[docs]    def GetAccelArray(self):
        """ Returns a list filled with the accelerator entries for the menu. """

        return self._accelArray

    # events

[docs]    def SendCmdEvent(self, itemIdx):
        """
        Actually sends menu command events.

        :param integer `itemIdx`: the menu item index for which we want to send a command event.
        """

        if itemIdx < 0 or itemIdx >= len(self._itemsArr):
            raise Exception("Invalid menu item")
            return

        item = self._itemsArr[itemIdx]

        # Create the event
        event = wx.CommandEvent(wxEVT_FLAT_MENU_SELECTED, item.GetId())

        # For checkable item, set the IsChecked() value
        if item.IsCheckable():
            event.SetInt((item.IsChecked() and [1] or [0])[0])

        event.SetEventObject(self)

        if self._owner:
            self._owner.GetEventHandler().ProcessEvent(event)
        else:
            self.GetEventHandler().ProcessEvent(event)

[docs]    def SendOverItem(self, itemIdx, over):
        """
        Sends the ``EVT_FLAT_MENU_ITEM_MOUSE_OVER`` and ``EVT_FLAT_MENU_ITEM_MOUSE_OUT``
        events.

        :param integer `itemIdx`: the menu item index for which we want to send an event;
        :param bool `over`: ``True`` to send a ``EVT_FLAT_MENU_ITEM_MOUSE_OVER`` event, ``False`` to
         send a ``EVT_FLAT_MENU_ITEM_MOUSE_OUT`` event.
        """

        item = self._itemsArr[itemIdx]

        # Create the event
        event = FlatMenuEvent((over and [wxEVT_FLAT_MENU_ITEM_MOUSE_OVER] or [wxEVT_FLAT_MENU_ITEM_MOUSE_OUT])[0], item.GetId())

        # For checkable item, set the IsChecked() value
        if item.IsCheckable():
            event.SetInt((item.IsChecked() and [1] or [0])[0])

        event.SetEventObject(self)

        if self._owner:
            self._owner.GetEventHandler().ProcessEvent(event)
        else:
            self.GetEventHandler().ProcessEvent(event)

[docs]    def SendUIEvent(self, itemIdx):
        """
        Actually sends menu UI events.

        :param integer `itemIdx`: the menu item index for which we want to send a UI event.
        """

        if itemIdx < 0 or itemIdx >= len(self._itemsArr):
            raise Exception("Invalid menu item")
            return

        item = self._itemsArr[itemIdx]
        event = wx.UpdateUIEvent(item.GetId())

        event.Check(item.IsChecked())
        event.Enable(item.IsEnabled())
        event.SetText(item.GetText())
        event.SetEventObject(self)

        if self._owner:
            self._owner.GetEventHandler().ProcessEvent(event)
        else:
            self.GetEventHandler().ProcessEvent(event)

        item.Check(event.GetChecked())
        item.SetLabel(event.GetText())
        item.Enable(event.GetEnabled())

[docs]    def Clear(self):
        """ Clears the menu items. """

        # since Destroy() call ResizeMenu(), we turn this flag on
        # to avoid resizing the menu for every item removed
        self._resizeMenu = False

        lenItems = len(self._itemsArr)
        for ii in xrange(lenItems):
            self.Destroy(self._itemsArr[0].GetId())

        # Now we can resize the menu
        self._resizeMenu = True
        self.ResizeMenu()

[docs]    def FindMenuItemPosSimple(self, item):
        """
        Finds an item and its position inside the menu based on its id.

        :param `item`: an instance of L{FlatMenuItem}.

        :return: An integer specifying the index found menu item object, or
         ``wx.NOT_FOUND`` if one was not found.
        """

        if item == None or len(self._itemsArr) == 0:
            return wx.NOT_FOUND

        for i in xrange(len(self._itemsArr)):
            if self._itemsArr[i] == item:
                return i

        return wx.NOT_FOUND

[docs]    def SetBackgroundBitmap(self, bitmap=None):
        """
        Sets a background bitmap for this particular L{FlatMenu}.

        :param `bitmap`: an instance of `wx.Bitmap`. Set `bitmap` to ``None`` if you
         wish to remove the background bitmap altogether.

        :note: the bitmap is rescaled to fit the menu width and height.
        """

        self._originalBackgroundImage = bitmap
        # Now we can resize the menu
        self._resizeMenu = True
        self.ResizeMenu()

[docs]    def GetBackgroundBitmap(self):
        """ Returns the background bitmap for this particular L{FlatMenu}, if any. """

        return self._originalBackgroundImage

[docs]    def GetAllItems(self, menu=None, items=[]):
        """
        Internal function to help recurse through all the menu items.

        :param `menu`: the menu from which we start accumulating items;
        :param list `items`: the array which is recursively filled with menu items.

        :return: a list of L{FlatMenuItem}.
        """

        # first copy the current menu items
        newitems = [item for item in items]

        if not menu:
            return newitems

        # if any item in this menu has sub-menu, copy them as well
        for i in xrange(len(menu._itemsArr)):
            if menu._itemsArr[i].IsSubMenu():
                newitems = self.GetAllItems(menu._itemsArr[i].GetSubMenu(), newitems)

        return newitems

[docs]    def GetSiblingGroupItem(self, item):
        """
        Used internally.

        :param `item`: an instance of L{FlatMenuItem}.
        """

        pos = self.FindMenuItemPosSimple(item)
        if pos in [wx.NOT_FOUND, 0]:
            return None

        if self._itemsArr[pos-1].IsRadioItem():
            return self._itemsArr[pos-1]

        return None

[docs]    def ScrollDown(self):
        """ Scrolls the menu down (for very tall menus). """

        # increase the self._from index
        if not self._itemsArr[-1].IsShown():
            self._first += 1
            self.Refresh()

            return True

        else:
            if self._downButton:
                self._downButton.GetTimer().Stop()

            return False

[docs]    def ScrollUp(self):
        """ Scrolls the menu up (for very tall menus). """

        if self._first == 0:
            if self._upButton:
                self._upButton.GetTimer().Stop()

            return False

        else:

            self._first -= 1
            self.Refresh()
            return True

    # Not used anymore

[docs]    def TryScrollButtons(self, event):
        """ Used internally. """

        return False

[docs]    def OnTimer(self, event):
        """
        Handles the ``wx.EVT_TIMER`` event for L{FlatMenu}.

        :param `event`: a `wx.TimerEvent` event to be processed.
        """

        if self._upButton and self._upButton.GetTimerId() == event.GetId():

            self.ScrollUp()

        elif self._downButton and self._downButton.GetTimerId() == event.GetId():

            self.ScrollDown()

        else:

            event.Skip()

#--------------------------------------------------------
# Class MenuKbdRedirector
#--------------------------------------------------------

[docs]class MenuKbdRedirector(wx.EvtHandler):
    """ A keyboard event handler. """

[docs]    def __init__(self, menu, oldHandler):
        """
        Default class constructor.

        :param `menu`: an instance of L{FlatMenu} for which we want to redirect
         keyboard inputs;
        :param `oldHandler`: a previous (if any) `wx.EvtHandler` associated with
         the menu.
        """

        self._oldHandler = oldHandler
        self.SetMenu(menu)
        wx.EvtHandler.__init__(self)

[docs]    def SetMenu(self, menu):
        """
        Sets the listener menu.

        :param `menu`: an instance of L{FlatMenu}.
        """

        self._menu = menu

[docs]    def ProcessEvent(self, event):
        """
        Processes the inout event.

        :param `event`: any kind of keyboard-generated events.
        """

        if event.GetEventType() in [wx.EVT_KEY_DOWN, wx.EVT_CHAR, wx.EVT_CHAR_HOOK]:
            return self._menu.OnChar(event.GetKeyCode())
        else:
            return self._oldHandler.ProcessEvent(event)

#--------------------------------------------------------
# Class FocusHandler
#--------------------------------------------------------

[docs]class FocusHandler(wx.EvtHandler):
    """ A focus event handler. """

[docs]    def __init__(self, menu):
        """
        Default class constructor.

        :param `menu`: an instance of L{FlatMenu} for which we want to redirect
         focus inputs.
        """

        wx.EvtHandler.__init__(self)
        self.SetMenu(menu)

        self.Bind(wx.EVT_KEY_DOWN, self.OnKeyDown)
        self.Bind(wx.EVT_KILL_FOCUS, self.OnKillFocus)

[docs]    def SetMenu(self, menu):
        """
        Sets the listener menu.

        :param `menu`: an instance of L{FlatMenu}.
        """

        self._menu = menu

[docs]    def OnKeyDown(self, event):
        """
        Handles the ``wx.EVT_KEY_DOWN`` event for L{FocusHandler}.

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

        # Let parent process it
        self._menu.OnKeyDown(event)

[docs]    def OnKillFocus(self, event):
        """
        Handles the ``wx.EVT_KILL_FOCUS`` event for L{FocusHandler}.

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

        wx.PostEvent(self._menu, event)

Navigation

  • index
  • modules |
  • Home |
  • Gallery |
  • Contents»
  • Module code »
  • flatmenu


flatnotebook

  • modules |
  • Home |
  • Gallery |
  • Contents»
  • Module code »
  • flatnotebook

Source code for flatnotebook

# --------------------------------------------------------------------------- #
# FLATNOTEBOOK Widget wxPython IMPLEMENTATION
#
# Original C++ Code From Eran. You Can Find It At:
#
# http://wxforum.shadonet.com/viewtopic.php?t=5761&start=0
#
# License: wxWidgets license
#
#
# Python Code By:
#
# Andrea Gavana, @ 02 Oct 2006
# Latest Revision: 26 Oct 2011, 21.00 GMT
#
#
# 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
# --------------------------------------------------------------------------- #

"""
L{FlatNotebook} is a full, generic and owner-drawn implementation of `wx.Notebook`.

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

L{FlatNotebook} is a full implementation of the `wx.Notebook`, and designed to be
a drop-in replacement for `wx.Notebook`. The API functions are similar so one can
expect the function to behave in the same way.

Some features:

- The buttons are highlighted a la Firefox style;
- The scrolling is done for bulks of tabs (so, the scrolling is faster and better);
- The buttons area is never overdrawn by tabs (unlike many other implementations I saw);
- It is a generic control;
- Currently there are 6 different styles - VC8, VC 71, Standard, Fancy, Firefox 2 and Ribbon;
- Mouse middle click can be used to close tabs;
- A function to add right click menu for tabs (simple as L{SetRightClickMenu});
- All styles has bottom style as well (they can be drawn in the bottom of screen);
- An option to hide 'X' button or navigation buttons (separately);
- Gradient colouring of the selected tabs and border;
- Support for drag 'n' drop of tabs, both in the same notebook or to another notebook;
- Possibility to have closing button on the active tab directly;
- Support for disabled tabs;
- Colours for active/inactive tabs, and captions;
- Background of tab area can be painted in gradient (VC8 style only);
- Colourful tabs - a random gentle colour is generated for each new tab (very cool, VC8 style only);
- Support for showing pages in "column/row mode", which means that all the pages will be
  shown in "tile" mode while the tabs are hidden;
- Possibility to add a custom panel to show a logo or HTML documentation or
  whatever you like when there are no pages left in L{FlatNotebook};
- Try setting the tab area colour for the Ribbon Style.

And much more.

Usage
=====

Usage example::

    import wx
    import wx.lib.agw.flatnotebook as fnb

    class MyFrame(wx.Frame):

        def __init__(self, parent):

            wx.Frame.__init(self, parent, -1, "FlatNotebook Demo")

            panel = wx.Panel(self)

            notebook = fnb.FlatNotebook(panel, -1)

            for i in xrange(3):
                caption = "Page %d"%(i+1)
                notebook.AddPage(self.CreatePage(notebook, caption), caption)

            sizer = wx.BoxSizer(wx.VERTICAL)
            sizer.Add(notebook, 1, wx.ALL|wx.EXPAND, 5)
            panel.SetSizer(sizer)

        def CreatePage(self, notebook, caption):
            '''
            Creates a simple `wx.Panel` containing a `wx.TextCtrl`.

            :param `notebook`: an instance of `FlatNotebook`;
            :param `caption`: a simple label.
            '''

            p = wx.Panel(notebook)
            wx.StaticText(p, -1, caption, (20,20))
            wx.TextCtrl(p, -1, "", (20,40), (150,-1))
            return p

    # our normal wxApp-derived class, as usual

    app = wx.PySimpleApp()

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

    app.MainLoop()

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

This class supports the following window styles:

================================ =========== ==================================================
Window Styles                    Hex Value   Description
================================ =========== ==================================================
``FNB_VC71``                             0x1 Use Visual Studio 2003 (VC7.1) style for tabs.
``FNB_FANCY_TABS``                       0x2 Use fancy style - square tabs filled with gradient colouring.
``FNB_TABS_BORDER_SIMPLE``               0x4 Draw thin border around the page.
``FNB_NO_X_BUTTON``                      0x8 Do not display the 'X' button.
``FNB_NO_NAV_BUTTONS``                  0x10 Do not display the right/left arrows.
``FNB_MOUSE_MIDDLE_CLOSES_TABS``        0x20 Use the mouse middle button for cloing tabs.
``FNB_BOTTOM``                          0x40 Place tabs at bottom - the default is to place them at top.
``FNB_NODRAG``                          0x80 Disable dragging of tabs.
``FNB_VC8``                            0x100 Use Visual Studio 2005 (VC8) style for tabs.
``FNB_X_ON_TAB``                       0x200 Place 'X' close button on the active tab.
``FNB_BACKGROUND_GRADIENT``            0x400 Use gradients to paint the tabs background.
``FNB_COLOURFUL_TABS``                 0x800 Use colourful tabs (VC8 style only).
``FNB_DCLICK_CLOSES_TABS``            0x1000 Style to close tab using double click.
``FNB_SMART_TABS``                    0x2000 Use `Smart Tabbing`, like ``Alt`` + ``Tab`` on Windows.
``FNB_DROPDOWN_TABS_LIST``            0x4000 Use a dropdown menu on the left in place of the arrows.
``FNB_ALLOW_FOREIGN_DND``             0x8000 Allows drag 'n' drop operations between different L{FlatNotebook}.
``FNB_HIDE_ON_SINGLE_TAB``           0x10000 Hides the Page Container when there is one or fewer tabs.
``FNB_DEFAULT_STYLE``                0x10020 L{FlatNotebook} default style.
``FNB_FF2``                          0x20000 Use Firefox 2 style for tabs.
``FNB_NO_TAB_FOCUS``                 0x40000 Does not allow tabs to have focus.
``FNB_RIBBON_TABS``                  0x80000 Use the Ribbon Tabs style
``FNB_HIDE_TABS``                   0x100000 Hides the Page Container allowing only keyboard navigation
``FNB_NAV_BUTTONS_WHEN_NEEDED``     0x200000 Hides the navigation left/right arrows if all tabs fit
================================ =========== ==================================================

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

This class processes the following events:

========================================= ==================================================
Event Name                                Description
========================================= ==================================================
``EVT_FLATNOTEBOOK_PAGE_CHANGED``         Notify client objects when the active page in L{FlatNotebook} has changed.
``EVT_FLATNOTEBOOK_PAGE_CHANGING``        Notify client objects when the active page in L{FlatNotebook} is about to change.
``EVT_FLATNOTEBOOK_PAGE_CLOSED``          Notify client objects when a page in L{FlatNotebook} has been closed.
``EVT_FLATNOTEBOOK_PAGE_CLOSING``         Notify client objects when a page in L{FlatNotebook} is closing.
``EVT_FLATNOTEBOOK_PAGE_CONTEXT_MENU``    Notify client objects when a pop-up menu should appear next to a tab.
``EVT_FLATNOTEBOOK_PAGE_DROPPED``         Notify client objects when a tab has been dropped and re-arranged (on the *same* notebook)
``EVT_FLATNOTEBOOK_PAGE_DROPPED_FOREIGN`` Notify client objects when a tab has been dropped and re-arranged (from a foreign notebook)
========================================= ==================================================

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

L{FlatNotebook} is distributed under the wxPython license.

Latest Revision: Andrea Gavana @ 26 Oct 2011, 21.00 GMT

Version 3.2
"""

__docformat__ = "epytext"

#----------------------------------------------------------------------
# Beginning Of FLATNOTEBOOK wxPython Code
#----------------------------------------------------------------------

import wx
import random
import math
import weakref
import cPickle

# Used on OSX to get access to carbon api constants
if wx.Platform == '__WXMAC__':
    import Carbon.Appearance

# Check for the new method in 2.7 (not present in 2.6.3.3)
if wx.VERSION_STRING < "2.7":
    wx.Rect.Contains = lambda self, point: wx.Rect.Inside(self, point)

FNB_HEIGHT_SPACER = 10

# Use Visual Studio 2003 (VC7.1) style for tabs
FNB_VC71 = 1
"""Use Visual Studio 2003 (VC7.1) style for tabs"""

# Use fancy style - square tabs filled with gradient colouring
FNB_FANCY_TABS = 2
"""Use fancy style - square tabs filled with gradient colouring"""

# Draw thin border around the page
FNB_TABS_BORDER_SIMPLE = 4
"""Draw thin border around the page"""

# Do not display the 'X' button
FNB_NO_X_BUTTON = 8
"""Do not display the 'X' button"""

# Do not display the Right / Left arrows
FNB_NO_NAV_BUTTONS = 16
"""Do not display the right/left arrows"""

# Use the mouse middle button for cloing tabs
FNB_MOUSE_MIDDLE_CLOSES_TABS = 32
"""Use the mouse middle button for cloing tabs"""

# Place tabs at bottom - the default is to place them
# at top
FNB_BOTTOM = 64
"""Place tabs at bottom - the default is to place them at top"""

# Disable dragging of tabs
FNB_NODRAG = 128
"""Disable dragging of tabs"""

# Use Visual Studio 2005 (VC8) style for tabs
FNB_VC8 = 256
"""Use Visual Studio 2005 (VC8) style for tabs"""

# Firefox 2 tabs style
FNB_FF2 = 131072
"""Use Firefox 2 style for tabs"""

# Place 'X' on a tab
FNB_X_ON_TAB = 512
"""Place 'X' close button on the active tab"""

FNB_BACKGROUND_GRADIENT = 1024
"""Use gradients to paint the tabs background"""

FNB_COLOURFUL_TABS = 2048
"""Use colourful tabs (VC8 style only)"""

# Style to close tab using double click - styles 1024, 2048 are reserved
FNB_DCLICK_CLOSES_TABS = 4096
"""Style to close tab using double click"""

FNB_SMART_TABS = 8192
"""Use `Smart Tabbing`, like ``Alt`` + ``Tab`` on Windows"""

FNB_DROPDOWN_TABS_LIST = 16384
"""Use a dropdown menu on the left in place of the arrows"""

FNB_ALLOW_FOREIGN_DND = 32768
"""Allows drag and drop operations between different L{FlatNotebook}"""

FNB_HIDE_ON_SINGLE_TAB = 65536
"""Hides the Page Container when there is one or fewer tabs"""

FNB_NO_TAB_FOCUS = 262144
""" Does not allow tabs to have focus"""

FNB_RIBBON_TABS = 0x80000
"""Use Ribbon style for tabs"""

FNB_HIDE_TABS = 0x100000
"""Hides the tabs allowing only keyboard navigation between pages"""

FNB_NAV_BUTTONS_WHEN_NEEDED = 0x200000
""" Hides the navigation left/right arrows if all tabs fit. """

VERTICAL_BORDER_PADDING = 4

# Button size is a 16x16 xpm bitmap
BUTTON_SPACE = 16
"""Button size is a 16x16 xpm bitmap"""

VC8_SHAPE_LEN = 16

MASK_COLOUR  = wx.Colour(0, 128, 128)
"""Mask colour for the arrow bitmaps"""

# Button status
FNB_BTN_PRESSED = 2
"""Navigation button is pressed"""
FNB_BTN_HOVER = 1
"""Navigation button is hovered"""
FNB_BTN_NONE = 0
"""No navigation"""

# Hit Test results
FNB_TAB = 1             # On a tab
"""Indicates mouse coordinates inside a tab"""
FNB_X = 2               # On the X button
"""Indicates mouse coordinates inside the X region"""
FNB_TAB_X = 3           # On the 'X' button (tab's X button)
"""Indicates mouse coordinates inside the X region in a tab"""
FNB_LEFT_ARROW = 4      # On the rotate left arrow button
"""Indicates mouse coordinates inside the left arrow region"""
FNB_RIGHT_ARROW = 5     # On the rotate right arrow button
"""Indicates mouse coordinates inside the right arrow region"""
FNB_DROP_DOWN_ARROW = 6 # On the drop down arrow button
"""Indicates mouse coordinates inside the drop down arrow region"""
FNB_NOWHERE = 0         # Anywhere else
"""Indicates mouse coordinates not on any tab of the notebook"""

FNB_DEFAULT_STYLE = FNB_MOUSE_MIDDLE_CLOSES_TABS | FNB_HIDE_ON_SINGLE_TAB
"""L{FlatNotebook} default style"""

# FlatNotebook Events:
# wxEVT_FLATNOTEBOOK_PAGE_CHANGED: Event Fired When You Switch Page;
# wxEVT_FLATNOTEBOOK_PAGE_CHANGING: Event Fired When You Are About To Switch
# Pages, But You Can Still "Veto" The Page Changing By Avoiding To Call
# event.Skip() In Your Event Handler;
# wxEVT_FLATNOTEBOOK_PAGE_CLOSING: Event Fired When A Page Is Closing, But
# You Can Still "Veto" The Page Changing By Avoiding To Call event.Skip()
# In Your Event Handler;
# wxEVT_FLATNOTEBOOK_PAGE_CLOSED: Event Fired When A Page Is Closed.
# wxEVT_FLATNOTEBOOK_PAGE_CONTEXT_MENU: Event Fired When A Menu Pops-up In A Tab.
# wxEVT_FLATNOTEBOOK_PAGE_DROPPED: Event Fired When A Tab Is Dropped On The Same Notebook

wxEVT_FLATNOTEBOOK_PAGE_CHANGED = wx.wxEVT_COMMAND_NOTEBOOK_PAGE_CHANGED
wxEVT_FLATNOTEBOOK_PAGE_CHANGING = wx.wxEVT_COMMAND_NOTEBOOK_PAGE_CHANGING
wxEVT_FLATNOTEBOOK_PAGE_CLOSING = wx.NewEventType()
wxEVT_FLATNOTEBOOK_PAGE_CLOSED = wx.NewEventType()
wxEVT_FLATNOTEBOOK_PAGE_CONTEXT_MENU = wx.NewEventType()
wxEVT_FLATNOTEBOOK_PAGE_DROPPED = wx.NewEventType()
wxEVT_FLATNOTEBOOK_PAGE_DROPPED_FOREIGN = wx.NewEventType()

#-----------------------------------#
#        FlatNotebookEvent
#-----------------------------------#

EVT_FLATNOTEBOOK_PAGE_CHANGED = wx.EVT_NOTEBOOK_PAGE_CHANGED
""" Notify client objects when the active page in L{FlatNotebook} has changed."""
EVT_FLATNOTEBOOK_PAGE_CHANGING = wx.EVT_NOTEBOOK_PAGE_CHANGING
""" Notify client objects when the active page in L{FlatNotebook} is about to change."""
EVT_FLATNOTEBOOK_PAGE_CLOSING = wx.PyEventBinder(wxEVT_FLATNOTEBOOK_PAGE_CLOSING, 1)
""" Notify client objects when a page in L{FlatNotebook} is closing."""
EVT_FLATNOTEBOOK_PAGE_CLOSED = wx.PyEventBinder(wxEVT_FLATNOTEBOOK_PAGE_CLOSED, 1)
""" Notify client objects when a page in L{FlatNotebook} has been closed."""
EVT_FLATNOTEBOOK_PAGE_CONTEXT_MENU = wx.PyEventBinder(wxEVT_FLATNOTEBOOK_PAGE_CONTEXT_MENU, 1)
""" Notify client objects when a pop-up menu should appear next to a tab."""
EVT_FLATNOTEBOOK_PAGE_DROPPED = wx.PyEventBinder(wxEVT_FLATNOTEBOOK_PAGE_DROPPED, 1)
""" Notify client objects when a tab has been dropped and re-arranged (on the *same* notebook)."""
EVT_FLATNOTEBOOK_PAGE_DROPPED_FOREIGN = wx.PyEventBinder(wxEVT_FLATNOTEBOOK_PAGE_DROPPED_FOREIGN, 1)
""" Notify client objects when a tab has been dropped and re-arranged (from a foreign notebook)."""

# Some icons in XPM format

left_arrow_disabled_xpm = [
    "    16    16        8            1",
    "` c #008080",
    ". c #555555",
    "# c #000000",
    "a c #000000",
    "b c #000000",
    "c c #000000",
    "d c #000000",
    "e c #000000",
    "````````````````",
    "````````````````",
    "````````````````",
    "````````.```````",
    "```````..```````",
    "``````.`.```````",
    "`````.``.```````",
    "````.```.```````",
    "`````.``.```````",
    "``````.`.```````",
    "```````..```````",
    "````````.```````",
    "````````````````",
    "````````````````",
    "````````````````",
    "````````````````"
    ]

x_button_pressed_xpm = [
    "    16    16        8            1",
    "` c #008080",
    ". c #4766e0",
    "# c #9e9ede",
    "a c #000000",
    "b c #000000",
    "c c #000000",
    "d c #000000",
    "e c #000000",
    "````````````````",
    "`..............`",
    "`.############.`",
    "`.############.`",
    "`.############.`",
    "`.###aa####aa#.`",
    "`.####aa##aa##.`",
    "`.#####aaaa###.`",
    "`.######aa####.`",
    "`.#####aaaa###.`",
    "`.####aa##aa##.`",
    "`.###aa####aa#.`",
    "`.############.`",
    "`..............`",
    "````````````````",
    "````````````````"
    ]

left_arrow_xpm = [
    "    16    16        8            1",
    "` c #008080",
    ". c #555555",
    "# c #000000",
    "a c #000000",
    "b c #000000",
    "c c #000000",
    "d c #000000",
    "e c #000000",
    "````````````````",
    "````````````````",
    "````````````````",
    "````````.```````",
    "```````..```````",
    "``````...```````",
    "`````....```````",
    "````.....```````",
    "`````....```````",
    "``````...```````",
    "```````..```````",
    "````````.```````",
    "````````````````",
    "````````````````",
    "````````````````",
    "````````````````"
    ]

x_button_hilite_xpm = [
    "    16    16        8            1",
    "` c #008080",
    ". c #4766e0",
    "# c #c9dafb",
    "a c #000000",
    "b c #000000",
    "c c #000000",
    "d c #000000",
    "e c #000000",
    "````````````````",
    "`..............`",
    "`.############.`",
    "`.############.`",
    "`.##aa####aa##.`",
    "`.###aa##aa###.`",
    "`.####aaaa####.`",
    "`.#####aa#####.`",
    "`.####aaaa####.`",
    "`.###aa##aa###.`",
    "`.##aa####aa##.`",
    "`.############.`",
    "`.############.`",
    "`..............`",
    "````````````````",
    "````````````````"
    ]

x_button_xpm = [
    "    16    16        8            1",
    "` c #008080",
    ". c #555555",
    "# c #000000",
    "a c #000000",
    "b c #000000",
    "c c #000000",
    "d c #000000",
    "e c #000000",
    "````````````````",
    "````````````````",
    "````````````````",
    "````````````````",
    "````..````..````",
    "`````..``..`````",
    "``````....``````",
    "```````..```````",
    "``````....``````",
    "`````..``..`````",
    "````..````..````",
    "````````````````",
    "````````````````",
    "````````````````",
    "````````````````",
    "````````````````"
    ]

left_arrow_pressed_xpm = [
    "    16    16        8            1",
    "` c #008080",
    ". c #4766e0",
    "# c #9e9ede",
    "a c #000000",
    "b c #000000",
    "c c #000000",
    "d c #000000",
    "e c #000000",
    "````````````````",
    "`..............`",
    "`.############.`",
    "`.############.`",
    "`.#######a####.`",
    "`.######aa####.`",
    "`.#####aaa####.`",
    "`.####aaaa####.`",
    "`.###aaaaa####.`",
    "`.####aaaa####.`",
    "`.#####aaa####.`",
    "`.######aa####.`",
    "`.#######a####.`",
    "`..............`",
    "````````````````",
    "````````````````"
    ]

left_arrow_hilite_xpm = [
    "    16    16        8            1",
    "` c #008080",
    ". c #4766e0",
    "# c #c9dafb",
    "a c #000000",
    "b c #000000",
    "c c #000000",
    "d c #000000",
    "e c #000000",
    "````````````````",
    "`..............`",
    "`.############.`",
    "`.######a#####.`",
    "`.#####aa#####.`",
    "`.####aaa#####.`",
    "`.###aaaa#####.`",
    "`.##aaaaa#####.`",
    "`.###aaaa#####.`",
    "`.####aaa#####.`",
    "`.#####aa#####.`",
    "`.######a#####.`",
    "`.############.`",
    "`..............`",
    "````````````````",
    "````````````````"
    ]

right_arrow_disabled_xpm = [
    "    16    16        8            1",
    "` c #008080",
    ". c #555555",
    "# c #000000",
    "a c #000000",
    "b c #000000",
    "c c #000000",
    "d c #000000",
    "e c #000000",
    "````````````````",
    "````````````````",
    "````````````````",
    "```````.````````",
    "```````..```````",
    "```````.`.``````",
    "```````.``.`````",
    "```````.```.````",
    "```````.``.`````",
    "```````.`.``````",
    "```````..```````",
    "```````.````````",
    "````````````````",
    "````````````````",
    "````````````````",
    "````````````````"
    ]

right_arrow_hilite_xpm = [
    "    16    16        8            1",
    "` c #008080",
    ". c #4766e0",
    "# c #c9dafb",
    "a c #000000",
    "b c #000000",
    "c c #000000",
    "d c #000000",
    "e c #000000",
    "````````````````",
    "`..............`",
    "`.############.`",
    "`.####a#######.`",
    "`.####aa######.`",
    "`.####aaa#####.`",
    "`.####aaaa####.`",
    "`.####aaaaa###.`",
    "`.####aaaa####.`",
    "`.####aaa#####.`",
    "`.####aa######.`",
    "`.####a#######.`",
    "`.############.`",
    "`..............`",
    "````````````````",
    "````````````````"
    ]

right_arrow_pressed_xpm = [
    "    16    16        8            1",
    "` c #008080",
    ". c #4766e0",
    "# c #9e9ede",
    "a c #000000",
    "b c #000000",
    "c c #000000",
    "d c #000000",
    "e c #000000",
    "````````````````",
    "`..............`",
    "`.############.`",
    "`.############.`",
    "`.#####a######.`",
    "`.#####aa#####.`",
    "`.#####aaa####.`",
    "`.#####aaaa###.`",
    "`.#####aaaaa##.`",
    "`.#####aaaa###.`",
    "`.#####aaa####.`",
    "`.#####aa#####.`",
    "`.#####a######.`",
    "`..............`",
    "````````````````",
    "````````````````"
    ]

right_arrow_xpm = [
    "    16    16        8            1",
    "` c #008080",
    ". c #555555",
    "# c #000000",
    "a c #000000",
    "b c #000000",
    "c c #000000",
    "d c #000000",
    "e c #000000",
    "````````````````",
    "````````````````",
    "````````````````",
    "```````.````````",
    "```````..```````",
    "```````...``````",
    "```````....`````",
    "```````.....````",
    "```````....`````",
    "```````...``````",
    "```````..```````",
    "```````.````````",
    "````````````````",
    "````````````````",
    "````````````````",
    "````````````````"
    ]

down_arrow_hilite_xpm = [
    "    16    16        8            1",
    "` c #008080",
    ". c #4766e0",
    "# c #c9dafb",
    "a c #000000",
    "b c #000000",
    "c c #000000",
    "d c #000000",
    "e c #000000",
    "````````````````",
    "``.............`",
    "``.###########.`",
    "``.###########.`",
    "``.###########.`",
    "``.#aaaaaaaaa#.`",
    "``.##aaaaaaa##.`",
    "``.###aaaaa###.`",
    "``.####aaa####.`",
    "``.#####a#####.`",
    "``.###########.`",
    "``.###########.`",
    "``.###########.`",
    "``.............`",
    "````````````````",
    "````````````````"
    ]

down_arrow_pressed_xpm = [
    "    16    16        8            1",
    "` c #008080",
    ". c #4766e0",
    "# c #9e9ede",
    "a c #000000",
    "b c #000000",
    "c c #000000",
    "d c #000000",
    "e c #000000",
    "````````````````",
    "``.............`",
    "``.###########.`",
    "``.###########.`",
    "``.###########.`",
    "``.###########.`",
    "``.###########.`",
    "``.#aaaaaaaaa#.`",
    "``.##aaaaaaa##.`",
    "``.###aaaaa###.`",
    "``.####aaa####.`",
    "``.#####a#####.`",
    "``.###########.`",
    "``.............`",
    "````````````````",
    "````````````````"
    ]

down_arrow_xpm = [
    "    16    16        8            1",
    "` c #008080",
    ". c #000000",
    "# c #000000",
    "a c #000000",
    "b c #000000",
    "c c #000000",
    "d c #000000",
    "e c #000000",
    "````````````````",
    "````````````````",
    "````````````````",
    "````````````````",
    "````````````````",
    "````````````````",
    "````.........```",
    "`````.......````",
    "``````.....`````",
    "```````...``````",
    "````````.```````",
    "````````````````",
    "````````````````",
    "````````````````",
    "````````````````",
    "````````````````"
    ]

#----------------------------------------------------------------------
from wx.lib.embeddedimage import PyEmbeddedImage

Mondrian = PyEmbeddedImage(
    "iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAAABHNCSVQICAgIfAhkiAAAAHFJ"
    "REFUWIXt1jsKgDAQRdF7xY25cpcWC60kioI6Fm/ahHBCMh+BRmGMnAgEWnvPpzK8dvrFCCCA"
    "coD8og4c5Lr6WB3Q3l1TBwLYPuF3YS1gn1HphgEEEABcKERrGy0E3B0HFJg7C1N/f/kTBBBA"
    "+Vi+AMkgFEvBPD17AAAAAElFTkSuQmCC")

#----------------------------------------------------------------------

[docs]def LightColour(colour, percent):
    """
    Brighten the input colour by a percentage.

    :param `colour`: a valid `wx.Colour` instance;
    :param `percent`: the percentage by which the input colour should be brightened.
    """

    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)

[docs]def FormatColour(colour):
    """
    Convert the input `colour` into a valid `wx.Colour` instance, using whatever typemap
    accepted by wxWidgets/wxPython.

    :param `colour`: can be an instance of `wx.Colour`, a 3 or 4 integer tuple, a hex
     string, a string representing the colour name or ``None``.

    :returns: a valid instance of `wx.Colour` or ``None`` if the input `colour` was ``None``
     in the first place.
    """

    if isinstance(colour, (list, tuple)):
        colour = wx.Colour(*colour)
    elif isinstance(colour, basestring):
        colour = wx.NamedColour(colour)

    return colour

[docs]def RandomColour():
    """ Creates a random colour. """

    r = random.randint(0, 255) # Random value betweem 0-255
    g = random.randint(0, 255) # Random value betweem 0-255
    b = random.randint(0, 255) # Random value betweem 0-255

    return wx.Colour(r, g, b)

[docs]def PaintStraightGradientBox(dc, rect, startColour, endColour, vertical=True):
    """
    Draws a gradient coloured box from `startColour` to `endColour`.

    :param `dc`: an instance of `wx.DC`;
    :param `rect`: the rectangle to fill with the gradient shading;
    :param `startColour`: the first colour in the gradient shading;
    :param `endColour`: the last colour in the gradient shading;
    :param `vertical`: ``True`` if the gradient shading is north to south, ``False``
     if it is east to west.
    """

    rd = endColour.Red() - startColour.Red()
    gd = endColour.Green() - startColour.Green()
    bd = endColour.Blue() - startColour.Blue()

    # Save the current pen and brush
    savedPen = dc.GetPen()
    savedBrush = dc.GetBrush()

    if vertical:
        high = rect.GetHeight()-1
    else:
        high = rect.GetWidth()-1

    if high < 1:
        return

    for i in xrange(high+1):

        r = startColour.Red() + ((i*rd*100)/high)/100
        g = startColour.Green() + ((i*gd*100)/high)/100
        b = startColour.Blue() + ((i*bd*100)/high)/100

        p = wx.Pen(wx.Colour(r, g, b))
        dc.SetPen(p)

        if vertical:
            dc.DrawLine(rect.x, rect.y+i, rect.x+rect.width, rect.y+i)
        else:
            dc.DrawLine(rect.x+i, rect.y, rect.x+i, rect.y+rect.height)

    # Restore the pen and brush
    dc.SetPen(savedPen)
    dc.SetBrush(savedBrush)

[docs]def AdjustColour(colour, percent, alpha=wx.ALPHA_OPAQUE):
    """
    Brighten/darken input colour by `percent` and adjust `alpha` channel if needed.

    :param `colour`: colour object to adjust, an instance of `wx.Colour`;
    :param `percent`: percent to adjust ``+`` (brighten) or ``-`` (darken);
    :param `alpha`: amount to adjust the alpha channel.

    :return: The modified colour.

    """

    radj, gadj, badj = [int(val * (abs(percent) / 100.)) for val in colour.Get()]

    if percent < 0:
        radj, gadj, badj = [val * -1 for val in [radj, gadj, badj]]
    else:
        radj, gadj, badj = [val or 255 for val in [radj, gadj, badj]]

    red = min(colour.Red() + radj, 255)
    green = min(colour.Green() + gadj, 255)
    blue = min(colour.Blue() + badj, 255)
    return wx.Colour(red, green, blue, alpha)

if wx.VERSION_STRING < "2.8.9.2":
    adjust_colour = AdjustColour
else:
    from wx.lib.colourutils import AdjustColour as adjust_colour

# -----------------------------------------------------------------------------
# Util functions
# -----------------------------------------------------------------------------

[docs]def DrawButton(dc, rect, focus, upperTabs):
    """
    Draws a L{FlatNotebook} tab.

    :param `dc`: an instance of `wx.DC`;
    :param `rect`: the tab's client rectangle;
    :param `focus`: ``True`` if the tab has focus, ``False`` otherwise;
    :param `upperTabs`: ``True`` if the tabs are at the top, ``False`` if they are
     at the bottom.
    """

    # Define the rounded rectangle base on the given rect
    # we need an array of 9 points for it
    regPts = [wx.Point() for indx in xrange(9)]

    if focus:
        if upperTabs:
            leftPt = wx.Point(rect.x, rect.y + (rect.height / 10)*8)
            rightPt = wx.Point(rect.x + rect.width - 2, rect.y + (rect.height / 10)*8)
        else:
            leftPt = wx.Point(rect.x, rect.y + (rect.height / 10)*5)
            rightPt = wx.Point(rect.x + rect.width - 2, rect.y + (rect.height / 10)*5)
    else:
        leftPt = wx.Point(rect.x, rect.y + (rect.height / 2))
        rightPt = wx.Point(rect.x + rect.width - 2, rect.y + (rect.height / 2))

    # Define the top region
    top = wx.RectPP(rect.GetTopLeft(), rightPt)
    bottom = wx.RectPP(leftPt, rect.GetBottomRight())

    topStartColour = wx.WHITE

    if not focus:
        topStartColour = LightColour(wx.SystemSettings_GetColour(wx.SYS_COLOUR_3DFACE), 50)

    topEndColour = wx.SystemSettings_GetColour(wx.SYS_COLOUR_3DFACE)
    bottomStartColour = topEndColour
    bottomEndColour = topEndColour

    # Incase we use bottom tabs, switch the colours
    if upperTabs:
        if focus:
            PaintStraightGradientBox(dc, top, topStartColour, topEndColour)
            PaintStraightGradientBox(dc, bottom, bottomStartColour, bottomEndColour)
        else:
            PaintStraightGradientBox(dc, top, topEndColour , topStartColour)
            PaintStraightGradientBox(dc, bottom, bottomStartColour, bottomEndColour)

    else:
        if focus:
            PaintStraightGradientBox(dc, bottom, topEndColour, bottomEndColour)
            PaintStraightGradientBox(dc, top,topStartColour,  topStartColour)
        else:
            PaintStraightGradientBox(dc, bottom, bottomStartColour, bottomEndColour)
            PaintStraightGradientBox(dc, top, topEndColour, topStartColour)

    dc.SetBrush(wx.TRANSPARENT_BRUSH)

# ---------------------------------------------------------------------------- #
# Class FNBDropSource
# Gives Some Custom UI Feedback during the DnD Operations
# ---------------------------------------------------------------------------- #

[docs]class FNBDropSource(wx.DropSource):
    """
    Give some custom UI feedback during the drag and drop operation in this
    function. It is called on each mouse move, so your implementation must
    not be too slow.
    """

[docs]    def __init__(self, win):
        """
        Default class constructor.
        Used internally.

        :param `win`: the source window for which we wish to provide UI feedback
         during drag and drop operations.
        """

        wx.DropSource.__init__(self, win)
        self._win = win

[docs]    def GiveFeedback(self, effect):
        """
        You may give some custom UI feedback during the drag and drop operation
        in this function. It is called on each mouse move, so your implementation
        must not be too slow.

        :param `effect`: the effect to implement. One of ``wx.DragCopy``, ``wx.DragMove``,
         ``wx.DragLink`` and ``wx.DragNone``.

        :return: Return ``False`` if you want default feedback, or ``True`` if you
         implement your own feedback. The return values is ignored under GTK.

        :note: To show your own custom drag and drop UI feedback, you must override
         this method.
        """

        self._win.DrawDragHint()
        return False

# ---------------------------------------------------------------------------- #
# Class FNBDragInfo
# Stores All The Information To Allow Drag And Drop Between Different
# FlatNotebooks.
# ---------------------------------------------------------------------------- #

[docs]class FNBDragInfo(object):
    """
    Stores all the information to allow drag and drop between different
    L{FlatNotebook} instances.
    """

    _map = weakref.WeakValueDictionary()

[docs]    def __init__(self, container, pageindex):
        """
        Default class constructor.

        :param `container`: the drag and drop container, a page in L{FlatNotebook};
        :param `pageindex`: the index of the tab that is actually being dragged.
        """

        self._id = id(container)
        FNBDragInfo._map[self._id] = container
        self._pageindex = pageindex

[docs]    def GetContainer(self):
        """ Returns the L{FlatNotebook} page (usually a panel). """

        return FNBDragInfo._map.get(self._id, None)

[docs]    def GetPageIndex(self):
        """ Returns the page index associated with a page. """

        return self._pageindex

# ---------------------------------------------------------------------------- #
# Class FNBDropTarget
# Simply Used To Handle The OnDrop() Method When Dragging And Dropping Between
# Different FlatNotebooks.
# ---------------------------------------------------------------------------- #

[docs]class FNBDropTarget(wx.DropTarget):
    """
    Class used to handle the L{FlatNotebook.OnDropTarget} method when dragging and
    dropping between different L{FlatNotebook} instances.
    """

[docs]    def __init__(self, parent):
        """
        Default class constructor.

        :param `parent`: the window handling the drag and drop, an instance of
         L{FlatNotebook}.
        """

        wx.DropTarget.__init__(self)

        self._parent = parent
        self._dataobject = wx.CustomDataObject(wx.CustomDataFormat("FlatNotebook"))
        self.SetDataObject(self._dataobject)

[docs]    def OnData(self, x, y, dragres):
        """
        Called after `OnDrop` returns ``True``.

        By default this will usually call `GetData` and will return the suggested default value `dragres`.

        :param `x`: the current x position of the mouse while dragging and dropping;
        :param `y`: the current y position of the mouse while dragging and dropping;
        :param `dragres`: an optional default return value.
        """

        if not self.GetData():
            return wx.DragNone

        draginfo = self._dataobject.GetData()
        drginfo = cPickle.loads(draginfo)

        return self._parent.OnDropTarget(x, y, drginfo.GetPageIndex(), drginfo.GetContainer())

# ---------------------------------------------------------------------------- #
# Class PageInfo
# Contains parameters for every FlatNotebook page
# ---------------------------------------------------------------------------- #

[docs]class PageInfo(object):
    """
    This class holds all the information (caption, image, etc...) belonging to a
    single tab in L{FlatNotebook}.
    """

[docs]    def __init__(self, caption="", imageindex=-1, tabangle=0, enabled=True):
        """
        Default Class Constructor.

        :param `caption`: the tab caption;
        :param `imageindex`: the tab image index based on the assigned (set)
         `wx.ImageList` (if any);
        :param `tabangle`: the tab angle (only on standard tabs, from 0 to 15
         degrees);
        :param `enabled`: sets the tab as enabled or disabled.
        """

        self._strCaption = caption
        self._TabAngle = tabangle
        self._ImageIndex = imageindex
        self._bEnabled = enabled
        self._pos = wx.Point(-1, -1)
        self._size = wx.Size(-1, -1)
        self._region = wx.Region()
        self._xRect = wx.Rect()
        self._colour = None
        self._hasFocus = False
        self._pageTextColour = None

[docs]    def SetCaption(self, value):
        """
        Sets the tab caption.

        :param `value`: the new tab caption string.
        """

        self._strCaption = value

[docs]    def GetCaption(self):
        """ Returns the tab caption. """

        return self._strCaption

[docs]    def SetPosition(self, value):
        """
        Sets the tab position.

        :param `value`: an instance of `wx.Point`.
        """

        self._pos = value

[docs]    def GetPosition(self):
        """ Returns the tab position. """

        return self._pos

[docs]    def SetSize(self, value):
        """
        Sets the tab size.

        :param `value`: an instance of `wx.Size`.
        """

        self._size = value

[docs]    def GetSize(self):
        """ Returns the tab size. """

        return self._size

[docs]    def SetTabAngle(self, value):
        """
        Sets the tab header angle.

        :param `value`: the tab header angle (0 <= value <= 15 degrees).
        """

        self._TabAngle = min(45, value)

[docs]    def GetTabAngle(self):
        """ Returns the tab angle. """

        return self._TabAngle

[docs]    def SetImageIndex(self, value):
        """
        Sets the tab image index.

        :param `value`: an index within the L{FlatNotebook} image list specifying
         the image to use for this tab.
        """

        self._ImageIndex = value

[docs]    def GetImageIndex(self):
        """ Returns the tab image index. """

        return self._ImageIndex

[docs]    def GetPageTextColour(self):
        """
        Returns the tab text colour if it has been set previously, or ``None``
        otherwise.
        """

        return self._pageTextColour

[docs]    def SetPageTextColour(self, colour):
        """
        Sets the tab text colour for this tab.

        :param `colour`: an instance of `wx.Colour`. You can pass ``None`` or
         `wx.NullColour` to return to the default page text colour.
        """

        colour = FormatColour(colour)

        if colour is None or not colour.IsOk():
            self._pageTextColour = None
        else:
            self._pageTextColour = colour

[docs]    def GetEnabled(self):
        """ Returns whether the tab is enabled or not. """

        return self._bEnabled

[docs]    def EnableTab(self, enabled):
        """
        Sets the tab enabled or disabled.

        :param `enabled`: ``True`` to enable a tab, ``False`` to disable it.
        """

        self._bEnabled = enabled

[docs]    def SetRegion(self, points=[]):
        """
        Sets the tab region.

        :param `points`: a Python list of `wx.Point`
        """

        self._region = wx.RegionFromPoints(points)

[docs]    def GetRegion(self):
        """ Returns the tab region. """

        return self._region

[docs]    def SetXRect(self, xrect):
        """
        Sets the button 'X' area rect.

        :param `xrect`: an instance of `wx.Rect`, specifying the client rectangle
         of the 'X' button.
        """

        self._xRect = xrect

[docs]    def GetXRect(self):
        """ Returns the button 'X' area rect. """

        return self._xRect

[docs]    def GetColour(self):
        """ Returns the tab colour. """

        return self._colour

[docs]    def SetColour(self, colour):
        """
        Sets the tab colour.

        :param `colour`: a valid `wx.Colour` object or any typemap supported by wxWidgets/wxPython
         to generate a colour (i.e., a hex string, a colour name, a 3 or 4 integer tuple).
        """

        self._colour = FormatColour(colour)

# ---------------------------------------------------------------------------- #
# Class FlatNotebookEvent
# ---------------------------------------------------------------------------- #

[docs]class FlatNotebookEvent(wx.PyCommandEvent):
    """
    This events will be sent when a ``EVT_FLATNOTEBOOK_PAGE_CHANGED``,
    ``EVT_FLATNOTEBOOK_PAGE_CHANGING``, ``EVT_FLATNOTEBOOK_PAGE_CLOSING``,
    ``EVT_FLATNOTEBOOK_PAGE_CLOSED`` and ``EVT_FLATNOTEBOOK_PAGE_CONTEXT_MENU`` is
    mapped in the parent.
    """

[docs]    def __init__(self, eventType, eventId=1, nSel=-1, nOldSel=-1):
        """
        Default class constructor.

        :param `eventType`: the event type;
        :param `eventId`: the event identifier;
        :param `nSel`: the current selection;
        :param `nOldSel`: the old selection.
        """

        wx.PyCommandEvent.__init__(self, eventType, eventId)
        self._eventType = eventType

        self.notify = wx.NotifyEvent(eventType, eventId)

[docs]    def GetNotifyEvent(self):
        """ Returns the actual `wx.NotifyEvent`. """

        return self.notify

[docs]    def IsAllowed(self):
        """
        Returns ``True`` if the change is allowed (L{Veto} hasn't been called) or
        ``False`` otherwise (if it was).
        """

        return self.notify.IsAllowed()

[docs]    def Veto(self):
        """
        Prevents the change announced by this event from happening.

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

        self.notify.Veto()

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

        self.notify.Allow()

[docs]    def SetSelection(self, nSel):
        """
        Sets the event selection.

        :param `nSel`: an integer specifying the new selection.
        """

        self._selection = nSel

[docs]    def SetOldSelection(self, nOldSel):
        """
        Sets the id of the page selected before the change.

        :param `nOldSel`: an integer specifying the old selection.
        """

        self._oldselection = nOldSel

[docs]    def GetSelection(self):
        """ Returns the currently selected page, or -1 if none was selected. """

        return self._selection

[docs]    def GetOldSelection(self):
        """ Returns the page that was selected before the change, -1 if none was selected. """

        return self._oldselection

# ---------------------------------------------------------------------------- #
# Class TabNavigatorWindow
# ---------------------------------------------------------------------------- #

[docs]class FlatNotebookDragEvent(FlatNotebookEvent):
    """
    This event will be sent when a ``EVT_FLATNOTEBOOK_PAGE_DRAGGED_FOREIGN`` is
    mapped in the parent.
    """

[docs]    def __init__(self, eventType, eventId=1, nSel=-1, nOldSel=-1):
        """
        Default class constructor.

        :param `eventType`: the event type;
        :param `eventId`: the event identifier;
        :param `nSel`: the current selection;
        :param `nOldSel`: the old selection.
        """

        wx.PyCommandEvent.__init__(self, eventType, eventId)
        self._eventType = eventType

        self.notify = wx.NotifyEvent(eventType, eventId)
        self._oldnotebook = -1
        self._newnotebook = -1

[docs]    def GetNotebook(self):
        """ Returns the new notebook. """

        return self._newnotebook

[docs]    def GetOldNotebook(self):
        """ Returns the old notebook. """

        return self._oldnotebook

[docs]    def SetNotebook(self, notebook):
        """
        Sets the new notebook.

        :param `notebook`: an instance of L{FlatNotebook}.
        """

        self._newnotebook = notebook

[docs]    def SetOldNotebook(self, old):
        """
        Sets the old notebook.

        :param `notebook`: an instance of L{FlatNotebook}.
        """

        self._oldnotebook = old

# ---------------------------------------------------------------------------- #
# Class TabNavigatorWindow
# ---------------------------------------------------------------------------- #

[docs]class TabNavigatorWindow(wx.Dialog):
    """
    This class is used to create a modal dialog that enables `Smart Tabbing`,
    similar to what you would get by hitting ``Alt`` + ``Tab`` on Windows.
    """

[docs]    def __init__(self, parent=None, icon=None):
        """
        Default class constructor.
        Used internally.

        :param `parent`: the L{TabNavigatorWindow} parent window;
        :param `icon`: a valid `wx.Bitmap` object representing the icon to be displayed
         in the L{TabNavigatorWindow}.
        """

        wx.Dialog.__init__(self, parent, wx.ID_ANY, "", style=0)

        self._selectedItem = -1
        self._indexMap = []

        if icon is None:
            self._bmp = Mondrian.GetBitmap()
        else:
            self._bmp = icon

        sz = wx.BoxSizer(wx.VERTICAL)

        self._listBox = wx.ListBox(self, wx.ID_ANY, wx.DefaultPosition, wx.Size(200, 150), [], wx.LB_SINGLE | wx.NO_BORDER)

        mem_dc = wx.MemoryDC()
        mem_dc.SelectObject(wx.EmptyBitmap(1,1))
        font = wx.SystemSettings_GetFont(wx.SYS_DEFAULT_GUI_FONT)
        font.SetWeight(wx.BOLD)
        mem_dc.SetFont(font)

        panelHeight = mem_dc.GetCharHeight()
        panelHeight += 4 # Place a spacer of 2 pixels

        # Out signpost bitmap is 24 pixels
        if panelHeight < 24:
            panelHeight = 24

        self._panel = wx.Panel(self, wx.ID_ANY, wx.DefaultPosition, wx.Size(200, panelHeight))

        sz.Add(self._panel)
        sz.Add(self._listBox, 1, wx.EXPAND)

        self.SetSizer(sz)

        # Connect events to the list box
        self._listBox.Bind(wx.EVT_KEY_UP, self.OnKeyUp)
        self._listBox.Bind(wx.EVT_NAVIGATION_KEY, self.OnNavigationKey)
        self._listBox.Bind(wx.EVT_LISTBOX_DCLICK, self.OnItemSelected)

        # Connect paint event to the panel
        self._panel.Bind(wx.EVT_PAINT, self.OnPanelPaint)
        self._panel.Bind(wx.EVT_ERASE_BACKGROUND, self.OnPanelEraseBg)

        self.SetBackgroundColour(wx.SystemSettings_GetColour(wx.SYS_COLOUR_3DFACE))
        self._listBox.SetBackgroundColour(wx.SystemSettings_GetColour(wx.SYS_COLOUR_3DFACE))
        self.PopulateListControl(parent)

        self.GetSizer().Fit(self)
        self.GetSizer().SetSizeHints(self)
        self.GetSizer().Layout()
        self.Centre()

        # Set focus on the list box to avoid having to click on it to change
        # the tab selection under GTK.
        self._listBox.SetFocus()

[docs]    def OnKeyUp(self, event):
        """
        Handles the ``wx.EVT_KEY_UP`` for the L{TabNavigatorWindow}.

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

        if event.GetKeyCode() == wx.WXK_CONTROL:
            self.CloseDialog()

[docs]    def OnNavigationKey(self, event):
        """
        Handles the ``wx.EVT_NAVIGATION_KEY`` for the L{TabNavigatorWindow}.

        :param `event`: a `wx.NavigationKeyEvent` event to be processed.
        """

        selected = self._listBox.GetSelection()
        bk = self.GetParent()
        maxItems = bk.GetPageCount()

        if event.GetDirection():

            # Select next page
            if selected == maxItems - 1:
                itemToSelect = 0
            else:
                itemToSelect = selected + 1

        else:

            # Previous page
            if selected == 0:
                itemToSelect = maxItems - 1
            else:
                itemToSelect = selected - 1

        self._listBox.SetSelection(itemToSelect)

[docs]    def PopulateListControl(self, book):
        """
        Populates the L{TabNavigatorWindow} listbox with a list of tabs.

        :param `book`: an instance of L{FlatNotebook} containing the tabs to be
         displayed in the listbox.
        """

        selection = book.GetSelection()
        count = book.GetPageCount()

        self._listBox.Append(book.GetPageText(selection))
        self._indexMap.append(selection)

        prevSel = book.GetPreviousSelection()

        if prevSel != wx.NOT_FOUND:

            # Insert the previous selection as second entry
            self._listBox.Append(book.GetPageText(prevSel))
            self._indexMap.append(prevSel)

        for c in xrange(count):

            # Skip selected page
            if c == selection:
                continue

            # Skip previous selected page as well
            if c == prevSel:
                continue

            self._listBox.Append(book.GetPageText(c))
            self._indexMap.append(c)

        # Select the next entry after the current selection
        self._listBox.SetSelection(0)
        dummy = wx.NavigationKeyEvent()
        dummy.SetDirection(True)
        self.OnNavigationKey(dummy)

[docs]    def OnItemSelected(self, event):
        """
        Handles the ``wx.EVT_LISTBOX_DCLICK`` for the L{TabNavigatorWindow}.

        :param `event`: a `wx.ListEvent` event to be processed.
        """

        self.CloseDialog()

[docs]    def CloseDialog(self):
        """
        Closes the L{TabNavigatorWindow} dialog, setting the new selection in
        L{FlatNotebook}.
        """

        bk = self.GetParent()
        self._selectedItem = self._listBox.GetSelection()
        iter = self._indexMap[self._selectedItem]
        bk._pages.FireEvent(iter)
        self.EndModal(wx.ID_OK)

[docs]    def OnPanelPaint(self, event):
        """
        Handles the ``wx.EVT_PAINT`` for the L{TabNavigatorWindow} top panel.

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

        dc = wx.PaintDC(self._panel)
        rect = self._panel.GetClientRect()

        bmp = wx.EmptyBitmap(rect.width, rect.height)

        mem_dc = wx.MemoryDC()
        mem_dc.SelectObject(bmp)

        endColour = wx.SystemSettings_GetColour(wx.SYS_COLOUR_BTNSHADOW)
        startColour = LightColour(endColour, 50)
        PaintStraightGradientBox(mem_dc, rect, startColour, endColour)

        # Draw the caption title and place the bitmap
        # get the bitmap optimal position, and draw it
        bmpPt, txtPt = wx.Point(), wx.Point()
        bmpPt.y = (rect.height - self._bmp.GetHeight())/2
        bmpPt.x = 3
        mem_dc.DrawBitmap(self._bmp, bmpPt.x, bmpPt.y, True)

        # get the text position, and draw it
        font = wx.SystemSettings_GetFont(wx.SYS_DEFAULT_GUI_FONT)
        font.SetWeight(wx.BOLD)
        mem_dc.SetFont(font)
        fontHeight = mem_dc.GetCharHeight()

        txtPt.x = bmpPt.x + self._bmp.GetWidth() + 4
        txtPt.y = (rect.height - fontHeight)/2
        mem_dc.SetTextForeground(wx.WHITE)
        mem_dc.DrawText("Opened tabs:", txtPt.x, txtPt.y)
        mem_dc.SelectObject(wx.NullBitmap)

        dc.DrawBitmap(bmp, 0, 0)

[docs]    def OnPanelEraseBg(self, event):
        """
        Handles the ``wx.EVT_ERASE_BACKGROUND`` for the L{TabNavigatorWindow} top panel.

        :param `event`: a `wx.EraseEvent` event to be processed.

        :note: This method is intentionally empty to reduce flicker.
        """

        pass

# ---------------------------------------------------------------------------- #
# Class FNBRenderer
# ---------------------------------------------------------------------------- #

[docs]class FNBRenderer(object):
    """
    Parent class for the 6 renderers defined: `Standard`, `VC71`, `Fancy`, `Firefox 2`,
    `VC8` and `Ribbon`. This class implements the common methods of all 6 renderers.
    """

[docs]    def __init__(self):
        """ Default class constructor. """

        self._tabHeight = None

        if wx.Platform == "__WXMAC__":
            # Get proper highlight colour for focus rectangle from the
            # current Mac theme.  kThemeBrushFocusHighlight is
            # available on Mac OS 8.5 and higher
            if hasattr(wx, 'MacThemeColour'):
                c = wx.MacThemeColour(Carbon.Appearance.kThemeBrushFocusHighlight)
            else:
                brush = wx.Brush(wx.BLACK)
                brush.MacSetTheme(Carbon.Appearance.kThemeBrushFocusHighlight)
                c = brush.GetColour()
            self._focusPen = wx.Pen(c, 2, wx.SOLID)
        else:
            self._focusPen = wx.Pen(wx.BLACK, 1, wx.USER_DASH)
            self._focusPen.SetDashes([1, 1])
            self._focusPen.SetCap(wx.CAP_BUTT)

[docs]    def GetLeftButtonPos(self, pageContainer):
        """
        Returns the left button position in the navigation area.

        :param `pageContainer`: an instance of L{FlatNotebook}.
        """

        pc = pageContainer
        agwStyle = pc.GetParent().GetAGWWindowStyleFlag()
        rect = pc.GetClientRect()
        clientWidth = rect.width

        if agwStyle & FNB_NO_X_BUTTON:
            return clientWidth - 38
        else:
            return clientWidth - 54

[docs]    def GetRightButtonPos(self, pageContainer):
        """
        Returns the right button position in the navigation area.

        :param `pageContainer`: an instance of L{FlatNotebook}.
        """

        pc = pageContainer
        agwStyle = pc.GetParent().GetAGWWindowStyleFlag()
        rect = pc.GetClientRect()
        clientWidth = rect.width

        if agwStyle & FNB_NO_X_BUTTON:
            return clientWidth - 22
        else:
            return clientWidth - 38

[docs]    def GetDropArrowButtonPos(self, pageContainer):
        """
        Returns the drop down button position in the navigation area.

        :param `pageContainer`: an instance of L{FlatNotebook}.
        """

        return self.GetRightButtonPos(pageContainer)

[docs]    def GetXPos(self, pageContainer):
        """
        Returns the 'X' button position in the navigation area.

        :param `pageContainer`: an instance of L{FlatNotebook}.
        """

        pc = pageContainer
        agwStyle = pc.GetParent().GetAGWWindowStyleFlag()
        rect = pc.GetClientRect()
        clientWidth = rect.width

        if agwStyle & FNB_NO_X_BUTTON:
            return clientWidth
        else:
            return clientWidth - 22

[docs]    def GetButtonsAreaLength(self, pageContainer):
        """
        Returns the navigation area width.

        :param `pageContainer`: an instance of L{FlatNotebook}.
        """

        pc = pageContainer
        agwStyle = pc.GetParent().GetAGWWindowStyleFlag()

        # ''
        if agwStyle & FNB_NO_NAV_BUTTONS and agwStyle & FNB_NO_X_BUTTON and not agwStyle & FNB_DROPDOWN_TABS_LIST:
            return 0

        # 'x'
        elif agwStyle & FNB_NO_NAV_BUTTONS and not agwStyle & FNB_NO_X_BUTTON and not agwStyle & FNB_DROPDOWN_TABS_LIST:
            return 22

        # '<>'
        if not agwStyle & FNB_NO_NAV_BUTTONS and agwStyle & FNB_NO_X_BUTTON and not agwStyle & FNB_DROPDOWN_TABS_LIST:
            return 53 - 16

        # 'vx'
        if agwStyle & FNB_DROPDOWN_TABS_LIST and not agwStyle & FNB_NO_X_BUTTON:
            return 22 + 16

        # 'v'
        if agwStyle & FNB_DROPDOWN_TABS_LIST and agwStyle & FNB_NO_X_BUTTON:
            return 22

        # '<>x'
        return 53

[docs]    def DrawArrowAccordingToState(self, dc, pc, rect):
        """
        Draws the left and right scrolling arrows.

        :param `dc`: an instance of `wx.DC`;
        :param `pc`: an instance of L{FlatNotebook};
        :param `rect`: the client rectangle containing the scrolling arrows.
        """

        lightFactor = (pc.HasAGWFlag(FNB_BACKGROUND_GRADIENT) and [70] or [0])[0]
        PaintStraightGradientBox(dc, rect, pc._tabAreaColour, LightColour(pc._tabAreaColour, lightFactor))

[docs]    def DrawLeftArrow(self, pageContainer, dc):
        """
        Draws the left navigation arrow.

        :param `pageContainer`: an instance of L{FlatNotebook};
        :param `dc`: an instance of `wx.DC`.
        """

        pc = pageContainer

        agwStyle = pc.GetParent().GetAGWWindowStyleFlag()
        if agwStyle & FNB_NO_NAV_BUTTONS:
            return

        # Make sure that there are pages in the container
        if not pc._pagesInfoVec:
            return

        if agwStyle & FNB_NAV_BUTTONS_WHEN_NEEDED:
            if pc._pagesInfoVec[-1].GetPosition() != wx.Point(-1, -1) and pc._nFrom == 0:
                return

        # Set the bitmap according to the button status
        if pc._nLeftButtonStatus == FNB_BTN_HOVER:
            arrowBmp = wx.BitmapFromXPMData(left_arrow_hilite_xpm)
        elif pc._nLeftButtonStatus == FNB_BTN_PRESSED:
            arrowBmp = wx.BitmapFromXPMData(left_arrow_pressed_xpm)
        else:
            arrowBmp = wx.BitmapFromXPMData(left_arrow_xpm)

        if pc._nFrom == 0:
            # Handle disabled arrow
            arrowBmp = wx.BitmapFromXPMData(left_arrow_disabled_xpm)

        arrowBmp.SetMask(wx.Mask(arrowBmp, MASK_COLOUR))

        # Erase old bitmap
        posx = self.GetLeftButtonPos(pc)
        self.DrawArrowAccordingToState(dc, pc, wx.Rect(posx, 6, 16, 14))

        # Draw the new bitmap
        dc.DrawBitmap(arrowBmp, posx, 6, True)

[docs]    def DrawRightArrow(self, pageContainer, dc):
        """
        Draws the right navigation arrow.

        :param `pageContainer`: an instance of L{FlatNotebook};
        :param `dc`: an instance of `wx.DC`.
        """

        pc = pageContainer

        agwStyle = pc.GetParent().GetAGWWindowStyleFlag()
        if agwStyle & FNB_NO_NAV_BUTTONS:
            return

        # Make sure that there are pages in the container
        if not pc._pagesInfoVec:
            return

        if agwStyle & FNB_NAV_BUTTONS_WHEN_NEEDED:
            if pc._pagesInfoVec[-1].GetPosition() != wx.Point(-1, -1) and pc._nFrom == 0:
                return

        # Set the bitmap according to the button status
        if pc._nRightButtonStatus == FNB_BTN_HOVER:
            arrowBmp = wx.BitmapFromXPMData(right_arrow_hilite_xpm)
        elif pc._nRightButtonStatus == FNB_BTN_PRESSED:
            arrowBmp = wx.BitmapFromXPMData(right_arrow_pressed_xpm)
        else:
            arrowBmp = wx.BitmapFromXPMData(right_arrow_xpm)

        # Check if the right most tab is visible, if it is
        # don't rotate right anymore
        if pc._pagesInfoVec[-1].GetPosition() != wx.Point(-1, -1):
            arrowBmp = wx.BitmapFromXPMData(right_arrow_disabled_xpm)

        arrowBmp.SetMask(wx.Mask(arrowBmp, MASK_COLOUR))

        # erase old bitmap
        posx = self.GetRightButtonPos(pc)
        self.DrawArrowAccordingToState(dc, pc, wx.Rect(posx, 6, 16, 14))

        # Draw the new bitmap
        dc.DrawBitmap(arrowBmp, posx, 6, True)

[docs]    def DrawDropDownArrow(self, pageContainer, dc):
        """
        Draws the drop-down arrow in the navigation area.

        :param `pageContainer`: an instance of L{FlatNotebook};
        :param `dc`: an instance of `wx.DC`.
        """

        pc = pageContainer

        # Check if this style is enabled
        agwStyle = pc.GetParent().GetAGWWindowStyleFlag()
        if not agwStyle & FNB_DROPDOWN_TABS_LIST:
            return

        # Make sure that there are pages in the container
        if not pc._pagesInfoVec:
            return

        if pc._nArrowDownButtonStatus == FNB_BTN_HOVER:
            downBmp = wx.BitmapFromXPMData(down_arrow_hilite_xpm)
        elif pc._nArrowDownButtonStatus == FNB_BTN_PRESSED:
            downBmp = wx.BitmapFromXPMData(down_arrow_pressed_xpm)
        else:
            downBmp = wx.BitmapFromXPMData(down_arrow_xpm)

        downBmp.SetMask(wx.Mask(downBmp, MASK_COLOUR))

        # erase old bitmap
        posx = self.GetDropArrowButtonPos(pc)
        self.DrawArrowAccordingToState(dc, pc, wx.Rect(posx, 6, 16, 14))

        # Draw the new bitmap
        dc.DrawBitmap(downBmp, posx, 6, True)

[docs]    def DrawX(self, pageContainer, dc):
        """
        Draw the 'X' navigation button in the navigation area.

        :param `pageContainer`: an instance of L{FlatNotebook};
        :param `dc`: an instance of `wx.DC`.
        """

        pc = pageContainer

        # Check if this style is enabled
        agwStyle = pc.GetParent().GetAGWWindowStyleFlag()
        if agwStyle & FNB_NO_X_BUTTON:
            return

        # Make sure that there are pages in the container
        if not pc._pagesInfoVec:
            return

        # Set the bitmap according to the button status
        if pc._nXButtonStatus == FNB_BTN_HOVER:
            xbmp = wx.BitmapFromXPMData(x_button_hilite_xpm)
        elif pc._nXButtonStatus == FNB_BTN_PRESSED:
            xbmp = wx.BitmapFromXPMData(x_button_pressed_xpm)
        else:
            xbmp = wx.BitmapFromXPMData(x_button_xpm)

        xbmp.SetMask(wx.Mask(xbmp, MASK_COLOUR))

        # erase old bitmap
        posx = self.GetXPos(pc)
        self.DrawArrowAccordingToState(dc, pc, wx.Rect(posx, 6, 16, 14))

        # Draw the new bitmap
        dc.DrawBitmap(xbmp, posx, 6, True)

[docs]    def DrawTabX(self, pageContainer, dc, rect, tabIdx, btnStatus):
        """
        Draws the 'X' in the selected tab.

        :param `pageContainer`: an instance of L{FlatNotebook};
        :param `dc`: an instance of `wx.DC`;
        :param `rect`: the current tab client rectangle;
        :param `tabIdx`: the index of the current tab;
        :param `btnStatus`: the status of the 'X' button in the current tab.
        """

        pc = pageContainer
        if not pc.HasAGWFlag(FNB_X_ON_TAB):
            return

        # We draw the 'x' on the active tab only
        if tabIdx != pc.GetSelection() or tabIdx < 0:
            return

        # Set the bitmap according to the button status

        if btnStatus == FNB_BTN_HOVER:
            xBmp = wx.BitmapFromXPMData(x_button_hilite_xpm)
        elif btnStatus == FNB_BTN_PRESSED:
            xBmp = wx.BitmapFromXPMData(x_button_pressed_xpm)
        else:
            xBmp = wx.BitmapFromXPMData(x_button_xpm)

        # Set the masking
        xBmp.SetMask(wx.Mask(xBmp, MASK_COLOUR))

        # Draw the new bitmap
        dc.DrawBitmap(xBmp, rect.x, rect.y, True)

        # Update the vector
        rr = wx.Rect(rect.x, rect.y, 14, 13)
        pc._pagesInfoVec[tabIdx].SetXRect(rr)

[docs]    def DrawTabsLine(self, pageContainer, dc, selTabX1=-1, selTabX2=-1):
        """
        Draws a line over the tabs.

        :param `pageContainer`: an instance of L{FlatNotebook};
        :param `dc`: an instance of `wx.DC`;
        :param `selTabX1`: first x coordinate of the tab line;
        :param `selTabX2`: second x coordinate of the tab line.
        """

        pc = pageContainer

        clntRect = pc.GetClientRect()
        clientRect3 = wx.Rect(0, 0, clntRect.width, clntRect.height)

        if pc.HasAGWFlag(FNB_FF2):
            if not pc.HasAGWFlag(FNB_BOTTOM):
                fillColour = wx.SystemSettings_GetColour(wx.SYS_COLOUR_3DFACE)
            else:
                fillColour = wx.WHITE

            dc.SetPen(wx.Pen(fillColour))

            if pc.HasAGWFlag(FNB_BOTTOM):

                dc.DrawLine(1, 0, clntRect.width-1, 0)
                dc.DrawLine(1, 1, clntRect.width-1, 1)

                dc.SetPen(wx.Pen(wx.SystemSettings_GetColour(wx.SYS_COLOUR_BTNSHADOW)))
                dc.DrawLine(1, 2, clntRect.width-1, 2)

                dc.SetPen(wx.Pen(fillColour))
                dc.DrawLine(selTabX1 + 2, 2, selTabX2 - 1, 2)

            else:

                dc.DrawLine(1, clntRect.height, clntRect.width-1, clntRect.height)
                dc.DrawLine(1, clntRect.height-1, clntRect.width-1, clntRect.height-1)

                dc.SetPen(wx.Pen(wx.SystemSettings_GetColour(wx.SYS_COLOUR_BTNSHADOW)))
                dc.DrawLine(1, clntRect.height-2, clntRect.width-1, clntRect.height-2)

                dc.SetPen(wx.Pen(wx.SystemSettings_GetColour(wx.SYS_COLOUR_3DFACE)))
                dc.DrawLine(selTabX1 + 2, clntRect.height-2, selTabX2-1, clntRect.height-2)

        else:

            if pc.HasAGWFlag(FNB_BOTTOM):

                clientRect = wx.Rect(0, 2, clntRect.width, clntRect.height - 2)
                clientRect2 = wx.Rect(0, 1, clntRect.width, clntRect.height - 1)

            else:

                clientRect = wx.Rect(0, 0, clntRect.width, clntRect.height - 2)
                clientRect2 = wx.Rect(0, 0, clntRect.width, clntRect.height - 1)

            dc.SetBrush(wx.TRANSPARENT_BRUSH)
            dc.SetPen(wx.Pen(pc.GetSingleLineBorderColour()))
            dc.DrawRectangleRect(clientRect2)
            dc.DrawRectangleRect(clientRect3)

            dc.SetPen(wx.Pen(wx.SystemSettings_GetColour(wx.SYS_COLOUR_BTNSHADOW)))
            dc.DrawRectangleRect(clientRect)

            if not pc.HasAGWFlag(FNB_TABS_BORDER_SIMPLE):

                dc.SetPen(wx.Pen((pc.HasAGWFlag(FNB_VC71) and [wx.Colour(247, 243, 233)] or [pc._tabAreaColour])[0]))
                dc.DrawLine(0, 0, 0, clientRect.height+1)

                if pc.HasAGWFlag(FNB_BOTTOM):

                    dc.DrawLine(0, clientRect.height+1, clientRect.width, clientRect.height+1)

                else:

                    dc.DrawLine(0, 0, clientRect.width, 0)

                dc.DrawLine(clientRect.width - 1, 0, clientRect.width - 1, clientRect.height+1)

[docs]    def CalcTabWidth(self, pageContainer, tabIdx, tabHeight):
        """
        Calculates the width of the input tab.

        :param `pageContainer`: an instance of L{FlatNotebook};
        :param `tabIdx`: the index of the input tab;
        :param `tabHeight`: the height of the tab.
        """

        pc = pageContainer
        dc = wx.MemoryDC()
        dc.SelectObject(wx.EmptyBitmap(1,1))

        boldFont = wx.SystemSettings_GetFont(wx.SYS_DEFAULT_GUI_FONT)
        boldFont.SetWeight(wx.FONTWEIGHT_BOLD)

        if pc.IsDefaultTabs():
            shapePoints = int(tabHeight*math.tan(float(pc._pagesInfoVec[tabIdx].GetTabAngle())/180.0*math.pi))

        # Calculate the text length using the bold font, so when selecting a tab
        # its width will not change
        dc.SetFont(boldFont)
        width, pom = dc.GetTextExtent(pc.GetPageText(tabIdx))

        # Set a minimum size to a tab
        if width < 20:
            width = 20

        tabWidth = 2*pc._pParent.GetPadding() + width

        # Style to add a small 'x' button on the top right
        # of the tab
        if pc.HasAGWFlag(FNB_X_ON_TAB) and tabIdx == pc.GetSelection():
            # The xpm image that contains the 'x' button is 9 pixels
            spacer = 9
            if pc.HasAGWFlag(FNB_VC8):
                spacer = 4

            tabWidth += pc._pParent.GetPadding() + spacer

        if pc.IsDefaultTabs():
            # Default style
            tabWidth += 2*shapePoints

        hasImage = pc._ImageList != None and pc._pagesInfoVec[tabIdx].GetImageIndex() != -1

        # For VC71 style, we only add the icon size (16 pixels)
        if hasImage:

            if not pc.IsDefaultTabs():
                tabWidth += 16 + pc._pParent.GetPadding()
            else:
                # Default style
                tabWidth += 16 + pc._pParent.GetPadding() + shapePoints/2

        return tabWidth

[docs]    def CalcTabHeight(self, pageContainer):
        """
        Calculates the height of the input tab.

        :param `pageContainer`: an instance of L{FlatNotebook}.
        """

        if self._tabHeight:
            return self._tabHeight

        pc = pageContainer
        dc = wx.MemoryDC()
        dc.SelectObject(wx.EmptyBitmap(1,1))

        # For GTK it seems that we must do this steps in order
        # for the tabs will get the proper height on initialization
        # on MSW, preforming these steps yields wierd results
        normalFont = wx.SystemSettings_GetFont(wx.SYS_DEFAULT_GUI_FONT)
        boldFont = normalFont

        if "__WXGTK__" in wx.PlatformInfo:
            boldFont.SetWeight(wx.FONTWEIGHT_BOLD)
            dc.SetFont(boldFont)

        height = dc.GetCharHeight()

        tabHeight = height + FNB_HEIGHT_SPACER # We use 8 pixels as padding
        if "__WXGTK__" in wx.PlatformInfo:
            # On GTK the tabs are should be larger
            tabHeight += 6

        self._tabHeight = tabHeight

        return tabHeight

[docs]    def DrawTabs(self, pageContainer, dc):
        """
        Actually draws the tabs in L{FlatNotebook}.

        :param `pageContainer`: an instance of L{FlatNotebook};
        :param `dc`: an instance of `wx.DC`.
        """

        pc = pageContainer
        if "__WXMAC__" in wx.PlatformInfo:
            # Works well on MSW & GTK, however this lines should be skipped on MAC
            if not pc._pagesInfoVec or pc._nFrom >= len(pc._pagesInfoVec):
                pc.Hide()
                return

        # Get the text hight
        tabHeight = self.CalcTabHeight(pageContainer)
        agwStyle = pc.GetParent().GetAGWWindowStyleFlag()

        # Calculate the number of rows required for drawing the tabs
        rect = pc.GetClientRect()
        clientWidth = rect.width

        # Set the maximum client size
        pc.SetSizeHints(self.GetButtonsAreaLength(pc), tabHeight)
        borderPen = wx.Pen(wx.SystemSettings_GetColour(wx.SYS_COLOUR_BTNSHADOW))

        if agwStyle & FNB_VC71:
            backBrush = wx.Brush(wx.Colour(247, 243, 233))
        else:
            backBrush = wx.Brush(pc._tabAreaColour)

        noselBrush = wx.Brush(wx.SystemSettings_GetColour(wx.SYS_COLOUR_BTNFACE))
        selBrush = wx.Brush(pc._activeTabColour)

        size = pc.GetSize()

        # Background
        dc.SetTextBackground((agwStyle & FNB_VC71 and [wx.Colour(247, 243, 233)] or [pc.GetBackgroundColour()])[0])
        dc.SetTextForeground(pc._activeTextColour)
        dc.SetBrush(backBrush)

        # If border style is set, set the pen to be border pen
        if pc.HasAGWFlag(FNB_TABS_BORDER_SIMPLE):
            dc.SetPen(borderPen)
        else:
            colr = (pc.HasAGWFlag(FNB_VC71) and [wx.Colour(247, 243, 233)] or [pc.GetBackgroundColour()])[0]
            dc.SetPen(wx.Pen(colr))

        if pc.HasAGWFlag(FNB_FF2):
            lightFactor = (pc.HasAGWFlag(FNB_BACKGROUND_GRADIENT) and [70] or [0])[0]
            PaintStraightGradientBox(dc, pc.GetClientRect(), pc._tabAreaColour, LightColour(pc._tabAreaColour, lightFactor))
            dc.SetBrush(wx.TRANSPARENT_BRUSH)

        dc.DrawRectangle(0, 0, size.x, size.y)

        # We always draw the bottom/upper line of the tabs
        # regradless the style
        dc.SetPen(borderPen)

        if not pc.HasAGWFlag(FNB_FF2):
            self.DrawTabsLine(pc, dc)

        # Restore the pen
        dc.SetPen(borderPen)

        if pc.HasAGWFlag(FNB_VC71):

            greyLineYVal  = (pc.HasAGWFlag(FNB_BOTTOM) and [0] or [size.y - 2])[0]
            whiteLineYVal = (pc.HasAGWFlag(FNB_BOTTOM) and [3] or [size.y - 3])[0]

            pen = wx.Pen(wx.SystemSettings_GetColour(wx.SYS_COLOUR_3DFACE))
            dc.SetPen(pen)

            # Draw thik grey line between the windows area and
            # the tab area
            for num in xrange(3):
                dc.DrawLine(0, greyLineYVal + num, size.x, greyLineYVal + num)

            wbPen = (pc.HasAGWFlag(FNB_BOTTOM) and [wx.BLACK_PEN] or [wx.WHITE_PEN])[0]
            dc.SetPen(wbPen)
            dc.DrawLine(1, whiteLineYVal, size.x - 1, whiteLineYVal)

            # Restore the pen
            dc.SetPen(borderPen)

        # Draw labels
        normalFont = wx.SystemSettings_GetFont(wx.SYS_DEFAULT_GUI_FONT)
        boldFont = wx.SystemSettings_GetFont(wx.SYS_DEFAULT_GUI_FONT)
        boldFont.SetWeight(wx.FONTWEIGHT_BOLD)
        dc.SetFont(boldFont)

        posx = pc._pParent.GetPadding()

        # Update all the tabs from 0 to 'pc._nFrom' to be non visible
        for i in xrange(pc._nFrom):

            pc._pagesInfoVec[i].SetPosition(wx.Point(-1, -1))
            pc._pagesInfoVec[i].GetRegion().Clear()

        count = pc._nFrom

        #----------------------------------------------------------
        # Go over and draw the visible tabs
        #----------------------------------------------------------
        x1 = x2 = -1
        for i in xrange(pc._nFrom, len(pc._pagesInfoVec)):

            dc.SetPen(borderPen)

            if not pc.HasAGWFlag(FNB_FF2):
                dc.SetBrush((i==pc.GetSelection() and [selBrush] or [noselBrush])[0])

            # Now set the font to the correct font
            dc.SetFont((i==pc.GetSelection() and [boldFont] or [normalFont])[0])

            # Add the padding to the tab width
            # Tab width:
            # +-----------------------------------------------------------+
            # | PADDING | IMG | IMG_PADDING | TEXT | PADDING | x |PADDING |
            # +-----------------------------------------------------------+
            tabWidth = self.CalcTabWidth(pageContainer, i, tabHeight)

            # Check if we can draw more
            if posx + tabWidth + self.GetButtonsAreaLength(pc) >= clientWidth:
                break

            count = count + 1

            # By default we clean the tab region
            pc._pagesInfoVec[i].GetRegion().Clear()

            # Clean the 'x' buttn on the tab.
            # A 'Clean' rectangle, is a rectangle with width or height
            # with values lower than or equal to 0
            pc._pagesInfoVec[i].GetXRect().SetSize(wx.Size(-1, -1))

            # Draw the tab (border, text, image & 'x' on tab)
            self.DrawTab(pc, dc, posx, i, tabWidth, tabHeight, pc._nTabXButtonStatus)

            if pc.GetSelection() == i:
                x1 = posx
                x2 = posx + tabWidth + 2

            # Restore the text forground
            dc.SetTextForeground(pc._activeTextColour)

            # Update the tab position & size
            posy = (pc.HasAGWFlag(FNB_BOTTOM) and [0] or [VERTICAL_BORDER_PADDING])[0]

            pc._pagesInfoVec[i].SetPosition(wx.Point(posx, posy))
            pc._pagesInfoVec[i].SetSize(wx.Size(tabWidth, tabHeight))
            self.DrawFocusRectangle(dc, pc, pc._pagesInfoVec[i])

            posx += tabWidth

        # Update all tabs that can not fit into the screen as non-visible
        for i in xrange(count, len(pc._pagesInfoVec)):
            pc._pagesInfoVec[i].SetPosition(wx.Point(-1, -1))
            pc._pagesInfoVec[i].GetRegion().Clear()

        # Draw the left/right/close buttons
        # Left arrow
        self.DrawLeftArrow(pc, dc)
        self.DrawRightArrow(pc, dc)
        self.DrawX(pc, dc)
        self.DrawDropDownArrow(pc, dc)

        if pc.HasAGWFlag(FNB_FF2):
            self.DrawTabsLine(pc, dc, x1, x2)

[docs]    def DrawFocusRectangle(self, dc, pageContainer, page):
        """
        Draws a focus rectangle like the native `wx.Notebook`.

        :param `dc`: an instance of `wx.DC`;
        :param `pageContainer`: an instance of L{FlatNotebook};
        :param `page`: an instance of L{PageInfo}, representing a page in the notebook.
        """

        if not page._hasFocus:
            return

        tabPos = wx.Point(*page.GetPosition())
        if pageContainer.GetParent().GetAGWWindowStyleFlag() & FNB_VC8:
            vc8ShapeLen = self.CalcTabHeight(pageContainer) - VERTICAL_BORDER_PADDING - 2
            tabPos.x += vc8ShapeLen

        rect = wx.RectPS(tabPos, page.GetSize())
        rect = wx.Rect(rect.x+2, rect.y+2, rect.width-4, rect.height-8)

        if wx.Platform == '__WXMAC__':
            rect.SetWidth(rect.GetWidth() + 1)

        dc.SetBrush(wx.TRANSPARENT_BRUSH)
        dc.SetPen(self._focusPen)
        dc.DrawRoundedRectangleRect(rect, 2)

[docs]    def DrawDragHint(self, pc, tabIdx):
        """
        Draws tab drag hint, the default implementation is to do nothing.
        You can override this function to provide a nice feedback to user.

        :param `pc`: an instance of L{FlatNotebook};
        :param `tabIdx`: the index of the tab we are dragging.

        :note: To show your own custom drag and drop UI feedback, you must override
         this method in your derived class.
        """

        pass

[docs]    def NumberTabsCanFit(self, pageContainer, fr=-1):
        """
        Calculates the number of tabs that can fit on the available space on screen.

        :param `pageContainer`: an instance of L{FlatNotebook};
        :param `fr`: the current first visible tab.
        """

        pc = pageContainer

        rect = pc.GetClientRect()
        clientWidth = rect.width

        vTabInfo = []

        tabHeight = self.CalcTabHeight(pageContainer)

        # The drawing starts from posx
        posx = pc._pParent.GetPadding()

        if fr < 0:
            fr = pc._nFrom

        for i in xrange(fr, len(pc._pagesInfoVec)):

            tabWidth = self.CalcTabWidth(pageContainer, i, tabHeight)
            if posx + tabWidth + self.GetButtonsAreaLength(pc) >= clientWidth:
                break;

            # Add a result to the returned vector
            tabRect = wx.Rect(posx, VERTICAL_BORDER_PADDING, tabWidth , tabHeight)
            vTabInfo.append(tabRect)

            # Advance posx
            posx += tabWidth + FNB_HEIGHT_SPACER

        return vTabInfo

# ---------------------------------------------------------------------------- #
# Class FNBRendererMgr
# A manager that handles all the renderers defined below and calls the
# appropriate one when drawing is needed
# ---------------------------------------------------------------------------- #

[docs]class FNBRendererMgr(object):
    """
    This class represents a manager that handles all the 6 renderers defined
    and calls the appropriate one when drawing is needed.
    """

[docs]    def __init__(self):
        """ Default class constructor. """

        # register renderers

        self._renderers = {}
        self._renderers.update({-1: FNBRendererDefault()})
        self._renderers.update({FNB_VC71: FNBRendererVC71()})
        self._renderers.update({FNB_FANCY_TABS: FNBRendererFancy()})
        self._renderers.update({FNB_VC8: FNBRendererVC8()})
        self._renderers.update({FNB_RIBBON_TABS: FNBRendererRibbonTabs()})
        self._renderers.update({FNB_FF2: FNBRendererFirefox2()})

[docs]    def GetRenderer(self, style):
        """
        Returns the current renderer based on the style selected.

        :param `style`: represents one of the 6 implemented styles for L{FlatNotebook},
         namely one of these bits:

         ===================== ========= ======================
         Tabs style            Hex Value Description
         ===================== ========= ======================
         ``FNB_VC71``                0x1 Use Visual Studio 2003 (VC7.1) style for tabs
         ``FNB_FANCY_TABS``          0x2 Use fancy style - square tabs filled with gradient colouring
         ``FNB_VC8``               0x100 Use Visual Studio 2005 (VC8) style for tabs
         ``FNB_FF2``             0x20000 Use Firefox 2 style for tabs
         ``FNB_RIBBON_TABS``     0x80000 Use the Ribbon Tabs style to render the tabs
         ===================== ========= ======================

        """

        if style & FNB_VC71:
            return self._renderers[FNB_VC71]

        if style & FNB_FANCY_TABS:
            return self._renderers[FNB_FANCY_TABS]

        if style & FNB_VC8:
            return self._renderers[FNB_VC8]

        if style & FNB_FF2:
            return self._renderers[FNB_FF2]

        if style & FNB_RIBBON_TABS:
            return self._renderers[FNB_RIBBON_TABS]

        # the default is to return the default renderer
        return self._renderers[-1]

#------------------------------------------
# Default renderer
#------------------------------------------

[docs]class FNBRendererDefault(FNBRenderer):
    """
    This class handles the drawing of tabs using the standard renderer.
    """

[docs]    def __init__(self):
        """ Default class constructor. """

        FNBRenderer.__init__(self)

[docs]    def DrawTab(self, pageContainer, dc, posx, tabIdx, tabWidth, tabHeight, btnStatus):
        """
        Draws a tab using the `Standard` style.

        :param `pageContainer`: an instance of L{FlatNotebook};
        :param `dc`: an instance of `wx.DC`;
        :param `posx`: the x position of the tab;
        :param `tabIdx`: the index of the tab;
        :param `tabWidth`: the tab's width;
        :param `tabHeight`: the tab's height;
        :param `btnStatus`: the status of the 'X' button inside this tab.
        """

        # Default style
        borderPen = wx.Pen(wx.SystemSettings_GetColour(wx.SYS_COLOUR_BTNSHADOW))
        pc = pageContainer

        tabPoints = [wx.Point() for ii in xrange(7)]
        tabPoints[0].x = posx
        tabPoints[0].y = (pc.HasAGWFlag(FNB_BOTTOM) and [2] or [tabHeight - 2])[0]

        tabPoints[1].x = int(posx+(tabHeight-2)*math.tan(float(pc._pagesInfoVec[tabIdx].GetTabAngle())/180.0*math.pi))
        tabPoints[1].y = (pc.HasAGWFlag(FNB_BOTTOM) and [tabHeight - (VERTICAL_BORDER_PADDING+2)] or [(VERTICAL_BORDER_PADDING+2)])[0]

        tabPoints[2].x = tabPoints[1].x+2
        tabPoints[2].y = (pc.HasAGWFlag(FNB_BOTTOM) and [tabHeight - VERTICAL_BORDER_PADDING] or [VERTICAL_BORDER_PADDING])[0]

        tabPoints[3].x = int(posx+tabWidth-(tabHeight-2)*math.tan(float(pc._pagesInfoVec[tabIdx].GetTabAngle())/180.0*math.pi))-2
        tabPoints[3].y = (pc.HasAGWFlag(FNB_BOTTOM) and [tabHeight - VERTICAL_BORDER_PADDING] or [VERTICAL_BORDER_PADDING])[0]

        tabPoints[4].x = tabPoints[3].x+2
        tabPoints[4].y = (pc.HasAGWFlag(FNB_BOTTOM) and [tabHeight - (VERTICAL_BORDER_PADDING+2)] or [(VERTICAL_BORDER_PADDING+2)])[0]

        tabPoints[5].x = int(tabPoints[4].x+(tabHeight-2)*math.tan(float(pc._pagesInfoVec[tabIdx].GetTabAngle())/180.0*math.pi))
        tabPoints[5].y = (pc.HasAGWFlag(FNB_BOTTOM) and [2] or [tabHeight - 2])[0]

        tabPoints[6].x = tabPoints[0].x
        tabPoints[6].y = tabPoints[0].y

        if tabIdx == pc.GetSelection():

            # Draw the tab as rounded rectangle
            dc.DrawPolygon(tabPoints)

        else:

            if tabIdx != pc.GetSelection() - 1:

                # Draw a vertical line to the right of the text
                pt1x = tabPoints[5].x
                pt1y = (pc.HasAGWFlag(FNB_BOTTOM) and [4] or [tabHeight - 6])[0]
                pt2x = tabPoints[5].x
                pt2y = (pc.HasAGWFlag(FNB_BOTTOM) and [tabHeight - 4] or [4])[0]
                dc.DrawLine(pt1x, pt1y, pt2x, pt2y)

        if tabIdx == pc.GetSelection():

            savePen = dc.GetPen()
            whitePen = wx.Pen(wx.WHITE)
            whitePen.SetWidth(1)
            dc.SetPen(whitePen)

            secPt = wx.Point(tabPoints[5].x + 1, tabPoints[5].y)
            dc.DrawLine(tabPoints[0].x, tabPoints[0].y, secPt.x, secPt.y)

            # Restore the pen
            dc.SetPen(savePen)

        # -----------------------------------
        # Text and image drawing
        # -----------------------------------

        # Text drawing offset from the left border of the
        # rectangle

        # The width of the images are 16 pixels
        padding = pc.GetParent().GetPadding()
        shapePoints = int(tabHeight*math.tan(float(pc._pagesInfoVec[tabIdx].GetTabAngle())/180.0*math.pi))
        hasImage = pc._pagesInfoVec[tabIdx].GetImageIndex() != -1
        imageYCoord = (pc.HasAGWFlag(FNB_BOTTOM) and [6] or [8])[0]

        if hasImage:
            textOffset = 2*pc._pParent._nPadding + 16 + shapePoints/2
        else:
            textOffset = pc._pParent._nPadding + shapePoints/2

        textOffset += 2

        if tabIdx != pc.GetSelection():

            # Set the text background to be like the vertical lines
            dc.SetTextForeground(pc._pParent.GetNonActiveTabTextColour())

        if hasImage:

            imageXOffset = textOffset - 16 - padding
            pc._ImageList.Draw(pc._pagesInfoVec[tabIdx].GetImageIndex(), dc,
                                     posx + imageXOffset, imageYCoord,
                                     wx.IMAGELIST_DRAW_TRANSPARENT, True)

        pageTextColour = pc._pParent.GetPageTextColour(tabIdx)
        if pageTextColour is not None:
            dc.SetTextForeground(pageTextColour)

        dc.DrawText(pc.GetPageText(tabIdx), posx + textOffset, imageYCoord)

        # draw 'x' on tab (if enabled)
        if pc.HasAGWFlag(FNB_X_ON_TAB) and tabIdx == pc.GetSelection():

            textWidth, textHeight = dc.GetTextExtent(pc.GetPageText(tabIdx))
            tabCloseButtonXCoord = posx + textOffset + textWidth + 1

            # take a bitmap from the position of the 'x' button (the x on tab button)
            # this bitmap will be used later to delete old buttons
            tabCloseButtonYCoord = imageYCoord
            x_rect = wx.Rect(tabCloseButtonXCoord, tabCloseButtonYCoord, 16, 16)

            # Draw the tab
            self.DrawTabX(pc, dc, x_rect, tabIdx, btnStatus)

#------------------------------------------
# Firefox2 renderer
#------------------------------------------

[docs]class FNBRendererFirefox2(FNBRenderer):
    """
    This class handles the drawing of tabs using the `Firefox 2` renderer.
    """

[docs]    def __init__(self):
        """ Default class constructor. """

        FNBRenderer.__init__(self)

[docs]    def DrawTab(self, pageContainer, dc, posx, tabIdx, tabWidth, tabHeight, btnStatus):
        """
        Draws a tab using the `Firefox 2` style.

        :param `pageContainer`: an instance of L{FlatNotebook};
        :param `dc`: an instance of `wx.DC`;
        :param `posx`: the x position of the tab;
        :param `tabIdx`: the index of the tab;
        :param `tabWidth`: the tab's width;
        :param `tabHeight`: the tab's height;
        :param `btnStatus`: the status of the 'X' button inside this tab.
        """

        borderPen = wx.Pen(wx.SystemSettings_GetColour(wx.SYS_COLOUR_BTNSHADOW))
        pc = pageContainer

        tabPoints = [wx.Point() for indx in xrange(7)]
        tabPoints[0].x = posx + 2
        tabPoints[0].y = (pc.HasAGWFlag(FNB_BOTTOM) and [2] or [tabHeight - 2])[0]

        tabPoints[1].x = tabPoints[0].x
        tabPoints[1].y = (pc.HasAGWFlag(FNB_BOTTOM) and [tabHeight - (VERTICAL_BORDER_PADDING+2)] or [(VERTICAL_BORDER_PADDING+2)])[0]

        tabPoints[2].x = tabPoints[1].x+2
        tabPoints[2].y = (pc.HasAGWFlag(FNB_BOTTOM) and [tabHeight - VERTICAL_BORDER_PADDING] or [VERTICAL_BORDER_PADDING])[0]

        tabPoints[3].x = posx + tabWidth - 2
        tabPoints[3].y = (pc.HasAGWFlag(FNB_BOTTOM) and [tabHeight - VERTICAL_BORDER_PADDING] or [VERTICAL_BORDER_PADDING])[0]

        tabPoints[4].x = tabPoints[3].x + 2
        tabPoints[4].y = (pc.HasAGWFlag(FNB_BOTTOM) and [tabHeight - (VERTICAL_BORDER_PADDING+2)] or [(VERTICAL_BORDER_PADDING+2)])[0]

        tabPoints[5].x = tabPoints[4].x
        tabPoints[5].y = (pc.HasAGWFlag(FNB_BOTTOM) and [2] or [tabHeight - 2])[0]

        tabPoints[6].x = tabPoints[0].x
        tabPoints[6].y = tabPoints[0].y

        #------------------------------------
        # Paint the tab with gradient
        #------------------------------------
        rr = wx.RectPP(tabPoints[2], tabPoints[5])
        DrawButton(dc, rr, pc.GetSelection() == tabIdx , not pc.HasAGWFlag(FNB_BOTTOM))

        dc.SetBrush(wx.TRANSPARENT_BRUSH)
        dc.SetPen(borderPen)

        # Draw the tab as rounded rectangle
        dc.DrawPolygon(tabPoints)

        # -----------------------------------
        # Text and image drawing
        # -----------------------------------

        # The width of the images are 16 pixels
        padding = pc.GetParent().GetPadding()
        shapePoints = int(tabHeight*math.tan(float(pc._pagesInfoVec[tabIdx].GetTabAngle())/180.0*math.pi))
        hasImage = pc._pagesInfoVec[tabIdx].GetImageIndex() != -1
        imageYCoord = (pc.HasAGWFlag(FNB_BOTTOM) and [6] or [8])[0]

        if hasImage:
            textOffset = 2*padding + 16 + shapePoints/2
        else:
            textOffset = padding + shapePoints/2

        textOffset += 2

        if tabIdx != pc.GetSelection():

            # Set the text background to be like the vertical lines
            dc.SetTextForeground(pc._pParent.GetNonActiveTabTextColour())

        if hasImage:
            imageXOffset = textOffset - 16 - padding
            pc._ImageList.Draw(pc._pagesInfoVec[tabIdx].GetImageIndex(), dc,
                               posx + imageXOffset, imageYCoord,
                               wx.IMAGELIST_DRAW_TRANSPARENT, True)

        pageTextColour = pc._pParent.GetPageTextColour(tabIdx)
        if pageTextColour is not None:
            dc.SetTextForeground(pageTextColour)

        dc.DrawText(pc.GetPageText(tabIdx), posx + textOffset, imageYCoord)

        # draw 'x' on tab (if enabled)
        if pc.HasAGWFlag(FNB_X_ON_TAB) and tabIdx == pc.GetSelection():

            textWidth, textHeight = dc.GetTextExtent(pc.GetPageText(tabIdx))
            tabCloseButtonXCoord = posx + textOffset + textWidth + 1

            # take a bitmap from the position of the 'x' button (the x on tab button)
            # this bitmap will be used later to delete old buttons
            tabCloseButtonYCoord = imageYCoord
            x_rect = wx.Rect(tabCloseButtonXCoord, tabCloseButtonYCoord, 16, 16)

            # Draw the tab
            self.DrawTabX(pc, dc, x_rect, tabIdx, btnStatus)

#------------------------------------------------------------------
# Visual studio 7.1
#------------------------------------------------------------------

[docs]class FNBRendererVC71(FNBRenderer):
    """
    This class handles the drawing of tabs using the `VC71` renderer.
    """

[docs]    def __init__(self):
        """ Default class constructor. """

        FNBRenderer.__init__(self)

[docs]    def DrawTab(self, pageContainer, dc, posx, tabIdx, tabWidth, tabHeight, btnStatus):
        """
        Draws a tab using the `VC71` style.

        :param `pageContainer`: an instance of L{FlatNotebook};
        :param `dc`: an instance of `wx.DC`;
        :param `posx`: the x position of the tab;
        :param `tabIdx`: the index of the tab;
        :param `tabWidth`: the tab's width;
        :param `tabHeight`: the tab's height;
        :param `btnStatus`: the status of the 'X' button inside this tab.
        """

        # Visual studio 7.1 style
        borderPen = wx.Pen(wx.SystemSettings_GetColour(wx.SYS_COLOUR_BTNSHADOW))
        pc = pageContainer

        dc.SetPen((tabIdx == pc.GetSelection() and [wx.Pen(wx.SystemSettings_GetColour(wx.SYS_COLOUR_3DFACE))] or [borderPen])[0])
        dc.SetBrush((tabIdx == pc.GetSelection() and [wx.Brush(wx.SystemSettings_GetColour(wx.SYS_COLOUR_3DFACE))] or [wx.Brush(wx.Colour(247, 243, 233))])[0])

        if tabIdx == pc.GetSelection():

            posy = (pc.HasAGWFlag(FNB_BOTTOM) and [0] or [VERTICAL_BORDER_PADDING])[0]
            tabH = (pc.HasAGWFlag(FNB_BOTTOM) and [tabHeight - 5] or [tabHeight - 3])[0]
            dc.DrawRectangle(posx, posy, tabWidth, tabH)

            # Draw a black line on the left side of the
            # rectangle
            dc.SetPen(wx.BLACK_PEN)

            blackLineY1 = VERTICAL_BORDER_PADDING
            blackLineY2 = tabH
            dc.DrawLine(posx + tabWidth, blackLineY1, posx + tabWidth, blackLineY2)

            # To give the tab more 3D look we do the following
            # Incase the tab is on top,
            # Draw a thik white line on topof the rectangle
            # Otherwise, draw a thin (1 pixel) black line at the bottom

            pen = wx.Pen((pc.HasAGWFlag(FNB_BOTTOM) and [wx.BLACK] or [wx.WHITE])[0])
            dc.SetPen(pen)
            whiteLinePosY = (pc.HasAGWFlag(FNB_BOTTOM) and [blackLineY2] or [VERTICAL_BORDER_PADDING ])[0]
            dc.DrawLine(posx , whiteLinePosY, posx + tabWidth + 1, whiteLinePosY)

            # Draw a white vertical line to the left of the tab
            dc.SetPen(wx.WHITE_PEN)
            if not pc.HasAGWFlag(FNB_BOTTOM):
                blackLineY2 += 1

            dc.DrawLine(posx, blackLineY1, posx, blackLineY2)

        else:

            # We dont draw a rectangle for non selected tabs, but only
            # vertical line on the left

            blackLineY1 = (pc.HasAGWFlag(FNB_BOTTOM) and [VERTICAL_BORDER_PADDING + 2] or [VERTICAL_BORDER_PADDING + 1])[0]
            blackLineY2 = pc.GetSize().y - 5
            dc.DrawLine(posx + tabWidth, blackLineY1, posx + tabWidth, blackLineY2)

        # -----------------------------------
        # Text and image drawing
        # -----------------------------------

        # Text drawing offset from the left border of the
        # rectangle

        # The width of the images are 16 pixels
        padding = pc.GetParent().GetPadding()
        hasImage = pc._pagesInfoVec[tabIdx].GetImageIndex() != -1
        imageYCoord = (pc.HasAGWFlag(FNB_BOTTOM) and [5] or [8])[0]

        if hasImage:
            textOffset = 2*pc._pParent._nPadding + 16
        else:
            textOffset = pc._pParent._nPadding

        if tabIdx != pc.GetSelection():

            # Set the text background to be like the vertical lines
            dc.SetTextForeground(pc._pParent.GetNonActiveTabTextColour())

        if hasImage:

            imageXOffset = textOffset - 16 - padding
            pc._ImageList.Draw(pc._pagesInfoVec[tabIdx].GetImageIndex(), dc,
                                     posx + imageXOffset, imageYCoord,
                                     wx.IMAGELIST_DRAW_TRANSPARENT, True)

        pageTextColour = pc._pParent.GetPageTextColour(tabIdx)
        if pageTextColour is not None:
            dc.SetTextForeground(pageTextColour)

        dc.DrawText(pc.GetPageText(tabIdx), posx + textOffset, imageYCoord)

        # draw 'x' on tab (if enabled)
        if pc.HasAGWFlag(FNB_X_ON_TAB) and tabIdx == pc.GetSelection():

            textWidth, textHeight = dc.GetTextExtent(pc.GetPageText(tabIdx))
            tabCloseButtonXCoord = posx + textOffset + textWidth + 1

            # take a bitmap from the position of the 'x' button (the x on tab button)
            # this bitmap will be used later to delete old buttons
            tabCloseButtonYCoord = imageYCoord
            x_rect = wx.Rect(tabCloseButtonXCoord, tabCloseButtonYCoord, 16, 16)

            # Draw the tab
            self.DrawTabX(pc, dc, x_rect, tabIdx, btnStatus)

#------------------------------------------------------------------
# Fancy style
#------------------------------------------------------------------

[docs]class FNBRendererFancy(FNBRenderer):
    """
    This class handles the drawing of tabs using the `Fancy` renderer.
    """

[docs]    def __init__(self):
        """ Default class constructor. """

        FNBRenderer.__init__(self)

[docs]    def DrawTab(self, pageContainer, dc, posx, tabIdx, tabWidth, tabHeight, btnStatus):
        """
        Draws a tab using the `Fancy` style, similar to the `VC71` one but with gradients.

        :param `pageContainer`: an instance of L{FlatNotebook};
        :param `dc`: an instance of `wx.DC`;
        :param `posx`: the x position of the tab;
        :param `tabIdx`: the index of the tab;
        :param `tabWidth`: the tab's width;
        :param `tabHeight`: the tab's height;
        :param `btnStatus`: the status of the 'X' button inside this tab.
        """

        # Fancy tabs - like with VC71 but with the following differences:
        # - The Selected tab is coloured with gradient colour
        borderPen = wx.Pen(wx.SystemSettings_GetColour(wx.SYS_COLOUR_BTNSHADOW))
        pc = pageContainer

        pen = (tabIdx == pc.GetSelection() and [wx.Pen(pc._pParent.GetBorderColour())] or [wx.Pen(wx.SystemSettings_GetColour(wx.SYS_COLOUR_3DFACE))])[0]

        if tabIdx == pc.GetSelection():

            posy = (pc.HasAGWFlag(FNB_BOTTOM) and [2] or [VERTICAL_BORDER_PADDING])[0]
            th = tabHeight - 5

            rect = wx.Rect(posx, posy, tabWidth, th)

            col2 = (pc.HasAGWFlag(FNB_BOTTOM) and [pc._pParent.GetGradientColourTo()] or [pc._pParent.GetGradientColourFrom()])[0]
            col1 = (pc.HasAGWFlag(FNB_BOTTOM) and [pc._pParent.GetGradientColourFrom()] or [pc._pParent.GetGradientColourTo()])[0]

            PaintStraightGradientBox(dc, rect, col1, col2)
            dc.SetBrush(wx.TRANSPARENT_BRUSH)
            dc.SetPen(pen)
            dc.DrawRectangleRect(rect)

            # erase the bottom/top line of the rectangle
            dc.SetPen(wx.Pen(pc._pParent.GetGradientColourFrom()))
            if pc.HasAGWFlag(FNB_BOTTOM):
                dc.DrawLine(rect.x, 2, rect.x + rect.width, 2)
            else:
                dc.DrawLine(rect.x, rect.y + rect.height - 1, rect.x + rect.width, rect.y + rect.height - 1)

        else:

            # We dont draw a rectangle for non selected tabs, but only
            # vertical line on the left
            dc.SetPen(borderPen)
            dc.DrawLine(posx + tabWidth, VERTICAL_BORDER_PADDING + 3, posx + tabWidth, tabHeight - 4)

        # -----------------------------------
        # Text and image drawing
        # -----------------------------------

        # Text drawing offset from the left border of the
        # rectangle

        # The width of the images are 16 pixels
        padding = pc.GetParent().GetPadding()
        hasImage = pc._pagesInfoVec[tabIdx].GetImageIndex() != -1
        imageYCoord = (pc.HasAGWFlag(FNB_BOTTOM) and [6] or [8])[0]

        if hasImage:
            textOffset = 2*pc._pParent._nPadding + 16
        else:
            textOffset = pc._pParent._nPadding

        textOffset += 2

        if tabIdx != pc.GetSelection():

            # Set the text background to be like the vertical lines
            dc.SetTextForeground(pc._pParent.GetNonActiveTabTextColour())

        if hasImage:

            imageXOffset = textOffset - 16 - padding
            pc._ImageList.Draw(pc._pagesInfoVec[tabIdx].GetImageIndex(), dc,
                                     posx + imageXOffset, imageYCoord,
                                     wx.IMAGELIST_DRAW_TRANSPARENT, True)

        pageTextColour = pc._pParent.GetPageTextColour(tabIdx)
        if pageTextColour is not None:
            dc.SetTextForeground(pageTextColour)

        dc.DrawText(pc.GetPageText(tabIdx), posx + textOffset, imageYCoord)

        # draw 'x' on tab (if enabled)
        if pc.HasAGWFlag(FNB_X_ON_TAB) and tabIdx == pc.GetSelection():

            textWidth, textHeight = dc.GetTextExtent(pc.GetPageText(tabIdx))
            tabCloseButtonXCoord = posx + textOffset + textWidth + 1

            # take a bitmap from the position of the 'x' button (the x on tab button)
            # this bitmap will be used later to delete old buttons
            tabCloseButtonYCoord = imageYCoord
            x_rect = wx.Rect(tabCloseButtonXCoord, tabCloseButtonYCoord, 16, 16)

            # Draw the tab
            self.DrawTabX(pc, dc, x_rect, tabIdx, btnStatus)

#------------------------------------------------------------------
# Visual studio 2005 (VS8)
#------------------------------------------------------------------

[docs]class FNBRendererVC8(FNBRenderer):
    """
    This class handles the drawing of tabs using the `VC8` renderer.
    """

[docs]    def __init__(self):
        """ Default class constructor. """

        FNBRenderer.__init__(self)
        self._first = True
        self._factor = 1

[docs]    def DrawTabs(self, pageContainer, dc):
        """
        Draws all the tabs using `VC8` style.

        :param `pageContainer`: an instance of L{FlatNotebook};
        :param `dc`: an instance of `wx.DC`.
        """

        pc = pageContainer

        if "__WXMAC__" in wx.PlatformInfo:
            # Works well on MSW & GTK, however this lines should be skipped on MAC
            if not pc._pagesInfoVec or pc._nFrom >= len(pc._pagesInfoVec):
                pc.Hide()
                return

        # Get the text hight
        tabHeight = self.CalcTabHeight(pageContainer)

        # Set the font for measuring the tab height
        normalFont = wx.SystemSettings_GetFont(wx.SYS_DEFAULT_GUI_FONT)
        boldFont = wx.SystemSettings_GetFont(wx.SYS_DEFAULT_GUI_FONT)
        boldFont.SetWeight(wx.FONTWEIGHT_BOLD)

        # Calculate the number of rows required for drawing the tabs
        rect = pc.GetClientRect()

        # Set the maximum client size
        pc.SetSizeHints(self.GetButtonsAreaLength(pc), tabHeight)
        borderPen = wx.Pen(wx.SystemSettings_GetColour(wx.SYS_COLOUR_BTNSHADOW))

        # Create brushes
        backBrush = wx.Brush(pc._tabAreaColour)
        noselBrush = wx.Brush(wx.SystemSettings_GetColour(wx.SYS_COLOUR_BTNFACE))
        selBrush = wx.Brush(pc._activeTabColour)
        size = pc.GetSize()

        # Background
        dc.SetTextBackground(pc.GetBackgroundColour())
        dc.SetTextForeground(pc._activeTextColour)

        # If border style is set, set the pen to be border pen
        if pc.HasAGWFlag(FNB_TABS_BORDER_SIMPLE):
            dc.SetPen(borderPen)
        else:
            dc.SetPen(wx.TRANSPARENT_PEN)

        lightFactor = (pc.HasAGWFlag(FNB_BACKGROUND_GRADIENT) and [70] or [0])[0]

        # For VC8 style, we colour the tab area in gradient colouring
        lightcolour = LightColour(pc._tabAreaColour, lightFactor)
        PaintStraightGradientBox(dc, pc.GetClientRect(), pc._tabAreaColour, lightcolour)

        dc.SetBrush(wx.TRANSPARENT_BRUSH)
        dc.DrawRectangle(0, 0, size.x, size.y)

        # We always draw the bottom/upper line of the tabs
        # regradless the style
        dc.SetPen(borderPen)
        self.DrawTabsLine(pc, dc)

        # Restore the pen
        dc.SetPen(borderPen)

        # Draw labels
        dc.SetFont(boldFont)

        # Update all the tabs from 0 to 'pc.self._nFrom' to be non visible
        for i in xrange(pc._nFrom):

            pc._pagesInfoVec[i].SetPosition(wx.Point(-1, -1))
            pc._pagesInfoVec[i].GetRegion().Clear()

        # Draw the visible tabs, in VC8 style, we draw them from right to left
        vTabsInfo = self.NumberTabsCanFit(pc)

        activeTabPosx = 0
        activeTabWidth = 0
        activeTabHeight = 0

        for cur in xrange(len(vTabsInfo)-1, -1, -1):

            # 'i' points to the index of the currently drawn tab
            # in pc.GetPageInfoVector() vector
            i = pc._nFrom + cur
            dc.SetPen(borderPen)
            dc.SetBrush((i==pc.GetSelection() and [selBrush] or [noselBrush])[0])

            # Now set the font to the correct font
            dc.SetFont((i==pc.GetSelection() and [boldFont] or [normalFont])[0])

            # Add the padding to the tab width
            # Tab width:
            # +-----------------------------------------------------------+
            # | PADDING | IMG | IMG_PADDING | TEXT | PADDING | x |PADDING |
            # +-----------------------------------------------------------+

            tabWidth = self.CalcTabWidth(pageContainer, i, tabHeight)
            posx = vTabsInfo[cur].x

            # By default we clean the tab region
            # incase we use the VC8 style which requires
            # the region, it will be filled by the function
            # drawVc8Tab
            pc._pagesInfoVec[i].GetRegion().Clear()

            # Clean the 'x' buttn on the tab
            # 'Clean' rectanlge is a rectangle with width or height
            # with values lower than or equal to 0
            pc._pagesInfoVec[i].GetXRect().SetSize(wx.Size(-1, -1))

            # Draw the tab
            # Incase we are drawing the active tab
            # we need to redraw so it will appear on top
            # of all other tabs

            # when using the vc8 style, we keep the position of the active tab so we will draw it again later
            if i == pc.GetSelection() and pc.HasAGWFlag(FNB_VC8):

                activeTabPosx = posx
                activeTabWidth = tabWidth
                activeTabHeight = tabHeight

            else:

                self.DrawTab(pc, dc, posx, i, tabWidth, tabHeight, pc._nTabXButtonStatus)

            # Restore the text forground
            dc.SetTextForeground(pc._activeTextColour)

            # Update the tab position & size
            pc._pagesInfoVec[i].SetPosition(wx.Point(posx, VERTICAL_BORDER_PADDING))
            pc._pagesInfoVec[i].SetSize(wx.Size(tabWidth, tabHeight))

        # Incase we are in VC8 style, redraw the active tab (incase it is visible)
        if pc.GetSelection() >= pc._nFrom and pc.GetSelection() < pc._nFrom + len(vTabsInfo):

            self.DrawTab(pc, dc, activeTabPosx, pc.GetSelection(), activeTabWidth, activeTabHeight, pc._nTabXButtonStatus)

        # Update all tabs that can not fit into the screen as non-visible
        for xx in xrange(pc._nFrom + len(vTabsInfo), len(pc._pagesInfoVec)):

            pc._pagesInfoVec[xx].SetPosition(wx.Point(-1, -1))
            pc._pagesInfoVec[xx].GetRegion().Clear()

        # Draw the left/right/close buttons
        # Left arrow
        self.DrawLeftArrow(pc, dc)
        self.DrawRightArrow(pc, dc)
        self.DrawX(pc, dc)
        self.DrawDropDownArrow(pc, dc)

[docs]    def DrawTab(self, pageContainer, dc, posx, tabIdx, tabWidth, tabHeight, btnStatus):
        """
        Draws a tab using the `VC8` style.

        :param `pageContainer`: an instance of L{FlatNotebook};
        :param `dc`: an instance of `wx.DC`;
        :param `posx`: the x position of the tab;
        :param `tabIdx`: the index of the tab;
        :param `tabWidth`: the tab's width;
        :param `tabHeight`: the tab's height;
        :param `btnStatus`: the status of the 'X' button inside this tab.
        """

        pc = pageContainer
        borderPen = wx.Pen(pc._pParent.GetBorderColour())
        tabPoints = [wx.Point() for ii in xrange(8)]

        # If we draw the first tab or the active tab,
        # we draw a full tab, else we draw a truncated tab
        #
        #             X(2)                  X(3)
        #        X(1)                            X(4)
        #
        #                                           X(5)
        #
        # X(0),(7)                                  X(6)
        #
        #

        tabPoints[0].x = (pc.HasAGWFlag(FNB_BOTTOM) and [posx] or [posx+self._factor])[0]
        tabPoints[0].y = (pc.HasAGWFlag(FNB_BOTTOM) and [2] or [tabHeight - 3])[0]

        tabPoints[1].x = tabPoints[0].x + tabHeight - VERTICAL_BORDER_PADDING - 3 - self._factor
        tabPoints[1].y = (pc.HasAGWFlag(FNB_BOTTOM) and [tabHeight - (VERTICAL_BORDER_PADDING+2)] or [(VERTICAL_BORDER_PADDING+2)])[0]

        tabPoints[2].x = tabPoints[1].x + 4
        tabPoints[2].y = (pc.HasAGWFlag(FNB_BOTTOM) and [tabHeight - VERTICAL_BORDER_PADDING] or [VERTICAL_BORDER_PADDING])[0]

        tabPoints[3].x = tabPoints[2].x + tabWidth - 2
        tabPoints[3].y = (pc.HasAGWFlag(FNB_BOTTOM) and [tabHeight - VERTICAL_BORDER_PADDING] or [VERTICAL_BORDER_PADDING])[0]

        tabPoints[4].x = tabPoints[3].x + 1
        tabPoints[4].y = (pc.HasAGWFlag(FNB_BOTTOM) and [tabPoints[3].y - 1] or [tabPoints[3].y + 1])[0]

        tabPoints[5].x = tabPoints[4].x + 1
        tabPoints[5].y = (pc.HasAGWFlag(FNB_BOTTOM) and [(tabPoints[4].y - 1)] or [tabPoints[4].y + 1])[0]

        tabPoints[6].x = tabPoints[2].x + tabWidth
        tabPoints[6].y = tabPoints[0].y

        tabPoints[7].x = tabPoints[0].x
        tabPoints[7].y = tabPoints[0].y

        pc._pagesInfoVec[tabIdx].SetRegion(tabPoints)

        # Draw the polygon
        br = dc.GetBrush()
        dc.SetBrush(wx.Brush((tabIdx == pc.GetSelection() and [pc._activeTabColour] or [pc._colourTo])[0]))
        dc.SetPen(wx.Pen((tabIdx == pc.GetSelection() and [wx.SystemSettings_GetColour(wx.SYS_COLOUR_BTNSHADOW)] or [pc._colourBorder])[0]))
        dc.DrawPolygon(tabPoints)

        # Restore the brush
        dc.SetBrush(br)
        rect = pc.GetClientRect()

        if tabIdx != pc.GetSelection() and not pc.HasAGWFlag(FNB_BOTTOM):

            # Top default tabs
            dc.SetPen(wx.Pen(pc._pParent.GetBorderColour()))
            lineY = rect.height
            curPen = dc.GetPen()
            curPen.SetWidth(1)
            dc.SetPen(curPen)
            dc.DrawLine(posx, lineY, posx+rect.width, lineY)

        # Incase we are drawing the selected tab, we draw the border of it as well
        # but without the bottom (upper line incase of wxBOTTOM)
        if tabIdx == pc.GetSelection():

            borderPen = wx.Pen(wx.SystemSettings_GetColour(wx.SYS_COLOUR_BTNSHADOW))
            dc.SetPen(borderPen)
            dc.SetBrush(wx.TRANSPARENT_BRUSH)
            dc.DrawPolygon(tabPoints)

            # Delete the bottom line (or the upper one, incase we use wxBOTTOM)
            dc.SetPen(wx.WHITE_PEN)
            dc.DrawLine(tabPoints[0].x, tabPoints[0].y, tabPoints[6].x, tabPoints[6].y)

        self.FillVC8GradientColour(pc, dc, tabPoints, tabIdx == pc.GetSelection(), tabIdx)

        # Draw a thin line to the right of the non-selected tab
        if tabIdx != pc.GetSelection():

            dc.SetPen(wx.Pen(wx.SystemSettings_GetColour(wx.SYS_COLOUR_3DFACE)))
            dc.DrawLine(tabPoints[4].x-1, tabPoints[4].y, tabPoints[5].x-1, tabPoints[5].y)
            dc.DrawLine(tabPoints[5].x-1, tabPoints[5].y, tabPoints[6].x-1, tabPoints[6].y)

        # Text drawing offset from the left border of the
        # rectangle

        # The width of the images are 16 pixels
        vc8ShapeLen = tabHeight - VERTICAL_BORDER_PADDING - 2
        if pc.TabHasImage(tabIdx):
            textOffset = 2*pc._pParent.GetPadding() + 16 + vc8ShapeLen
        else:
            textOffset = pc._pParent.GetPadding() + vc8ShapeLen

        # Draw the image for the tab if any
        imageYCoord = (pc.HasAGWFlag(FNB_BOTTOM) and [6] or [8])[0]

        if pc.TabHasImage(tabIdx):

            imageXOffset = textOffset - 16 - pc._pParent.GetPadding()
            pc._ImageList.Draw(pc._pagesInfoVec[tabIdx].GetImageIndex(), dc,
                                     posx + imageXOffset, imageYCoord,
                                     wx.IMAGELIST_DRAW_TRANSPARENT, True)

        boldFont = wx.SystemSettings_GetFont(wx.SYS_DEFAULT_GUI_FONT)

        # if selected tab, draw text in bold
        if tabIdx == pc.GetSelection():
            boldFont.SetWeight(wx.FONTWEIGHT_BOLD)

        dc.SetFont(boldFont)

        pageTextColour = pc._pParent.GetPageTextColour(tabIdx)
        if pageTextColour is not None:
            dc.SetTextForeground(pageTextColour)

        dc.DrawText(pc.GetPageText(tabIdx), posx + textOffset, imageYCoord)

        # draw 'x' on tab (if enabled)
        if pc.HasAGWFlag(FNB_X_ON_TAB) and tabIdx == pc.GetSelection():

            textWidth, textHeight = dc.GetTextExtent(pc.GetPageText(tabIdx))
            tabCloseButtonXCoord = posx + textOffset + textWidth + 1

            # take a bitmap from the position of the 'x' button (the x on tab button)
            # this bitmap will be used later to delete old buttons
            tabCloseButtonYCoord = imageYCoord
            x_rect = wx.Rect(tabCloseButtonXCoord, tabCloseButtonYCoord, 16, 16)
            # Draw the tab
            self.DrawTabX(pc, dc, x_rect, tabIdx, btnStatus)

        self.DrawFocusRectangle(dc, pc, pc._pagesInfoVec[tabIdx])

[docs]    def FillVC8GradientColour(self, pageContainer, dc, tabPoints, bSelectedTab, tabIdx):
        """
        Fills a tab with a gradient shading.

        :param `pageContainer`: an instance of L{FlatNotebook};
        :param `dc`: an instance of `wx.DC`;
        :param `tabPoints`: a Python list of `wx.Point` representing the tab outline;
        :param `bSelectedTab`: ``True`` if the tab is selected, ``False`` otherwise;
        :param `tabIdx`: the index of the tab;
        """

        # calculate gradient coefficients
        pc = pageContainer

        if self._first:
            self._first = False
            pc._colourTo   = LightColour(wx.SystemSettings_GetColour(wx.SYS_COLOUR_3DFACE), 0)
            pc._colourFrom = LightColour(wx.SystemSettings_GetColour(wx.SYS_COLOUR_3DFACE), 60)

        col2 = pc._pParent.GetGradientColourTo()
        col1 = pc._pParent.GetGradientColourFrom()

        # If colourful tabs style is set, override the tab colour
        if pc.HasAGWFlag(FNB_COLOURFUL_TABS):

            if not pc._pagesInfoVec[tabIdx].GetColour():

                # First time, generate colour, and keep it in the vector
                tabColour = RandomColour()
                pc._pagesInfoVec[tabIdx].SetColour(tabColour)

            if pc.HasAGWFlag(FNB_BOTTOM):

                col2 = LightColour(pc._pagesInfoVec[tabIdx].GetColour(), 50)
                col1 = LightColour(pc._pagesInfoVec[tabIdx].GetColour(), 80)

            else:

                col1 = LightColour(pc._pagesInfoVec[tabIdx].GetColour(), 50)
                col2 = LightColour(pc._pagesInfoVec[tabIdx].GetColour(), 80)

        size = abs(tabPoints[2].y - tabPoints[0].y) - 1

        rf, gf, bf = 0, 0, 0
        rstep = float(col2.Red() - col1.Red())/float(size)
        gstep = float(col2.Green() - col1.Green())/float(size)
        bstep = float(col2.Blue() - col1.Blue())/float(size)

        y = tabPoints[0].y

        # If we are drawing the selected tab, we need also to draw a line
        # from 0.tabPoints[0].x and tabPoints[6].x . end, we achieve this
        # by drawing the rectangle with transparent brush
        # the line under the selected tab will be deleted by the drwaing loop
        if bSelectedTab:
            self.DrawTabsLine(pc, dc)

        while 1:

            if pc.HasAGWFlag(FNB_BOTTOM):

                if y > tabPoints[0].y + size:
                    break

            else:

                if y < tabPoints[0].y - size:
                    break

            currCol = wx.Colour(col1.Red() + rf, col1.Green() + gf, col1.Blue() + bf)

            dc.SetPen((bSelectedTab and [wx.Pen(pc._activeTabColour)] or [wx.Pen(currCol)])[0])
            startX = self.GetStartX(tabPoints, y, pc.GetParent().GetAGWWindowStyleFlag())
            endX = self.GetEndX(tabPoints, y, pc.GetParent().GetAGWWindowStyleFlag())
            dc.DrawLine(startX, y, endX, y)

            # Draw the border using the 'edge' point
            dc.SetPen(wx.Pen((bSelectedTab and [wx.SystemSettings_GetColour(wx.SYS_COLOUR_BTNSHADOW)] or [pc._colourBorder])[0]))

            dc.DrawPoint(startX, y)
            dc.DrawPoint(endX, y)

            # Progress the colour
            rf += rstep
            gf += gstep
            bf += bstep

            if pc.HasAGWFlag(FNB_BOTTOM):
                y = y + 1
            else:
                y = y - 1

[docs]    def GetStartX(self, tabPoints, y, style):
        """
        Returns the `x` start position of a tab.

        :param `tabPoints`: a Python list of `wx.Point` representing the tab outline;
        :param `y`: the y start position of the tab;
        :param `style`: can be ``FNB_BOTTOM`` or the default (tabs at top).
        """

        x1, x2, y1, y2 = 0.0, 0.0, 0.0, 0.0

        # We check the 3 points to the left

        bBottomStyle = (style & FNB_BOTTOM and [True] or [False])[0]
        match = False

        if bBottomStyle:

            for i in xrange(3):

                if y >= tabPoints[i].y and y < tabPoints[i+1].y:

                    x1 = tabPoints[i].x
                    x2 = tabPoints[i+1].x
                    y1 = tabPoints[i].y
                    y2 = tabPoints[i+1].y
                    match = True
                    break

        else:

            for i in xrange(3):

                if y <= tabPoints[i].y and y > tabPoints[i+1].y:

                    x1 = tabPoints[i].x
                    x2 = tabPoints[i+1].x
                    y1 = tabPoints[i].y
                    y2 = tabPoints[i+1].y
                    match = True
                    break

        if not match:
            return tabPoints[2].x

        # According to the equation y = ax + b => x = (y-b)/a
        # We know the first 2 points

        x1, x2, y1, y2 = map(float, (x1, x2, y1, y2))

        if abs(x2 - x1) < 1e-6:
            return x2
        else:
            a = (y2 - y1)/(x2 - x1)

        b = y1 - ((y2 - y1)/(x2 - x1))*x1

        if a == 0:
            return int(x1)

        x = (y - b)/a

        return int(x)

[docs]    def GetEndX(self, tabPoints, y, style):
        """
        Returns the `x` end position of a tab.

        :param `tabPoints`: a Python list of `wx.Point` representing the tab outline;
        :param `y`: the y end position of the tab;
        :param `style`: can be ``FNB_BOTTOM`` or the default (tabs at top).
        """

        x1, x2, y1, y2 = 0.0, 0.0, 0.0, 0.0

        # We check the 3 points to the left
        bBottomStyle = (style & FNB_BOTTOM and [True] or [False])[0]
        match = False

        if bBottomStyle:

            for i in xrange(7, 3, -1):

                if y >= tabPoints[i].y and y < tabPoints[i-1].y:

                    x1 = tabPoints[i].x
                    x2 = tabPoints[i-1].x
                    y1 = tabPoints[i].y
                    y2 = tabPoints[i-1].y
                    match = True
                    break

        else:

            for i in xrange(7, 3, -1):

                if y <= tabPoints[i].y and y > tabPoints[i-1].y:

                    x1 = tabPoints[i].x
                    x2 = tabPoints[i-1].x
                    y1 = tabPoints[i].y
                    y2 = tabPoints[i-1].y
                    match = True
                    break

        if not match:
            return tabPoints[3].x

        # According to the equation y = ax + b => x = (y-b)/a
        # We know the first 2 points

        # Vertical line
        if x1 == x2:
            return int(x1)

        a = (y2 - y1)/(x2 - x1)
        b = y1 - ((y2 - y1)/(x2 - x1))*x1

        if a == 0:
            return int(x1)

        x = (y - b)/a

        return int(x)

[docs]    def NumberTabsCanFit(self, pageContainer, fr=-1):
        """
        Calculates the number of tabs that can fit on the available space on screen.

        :param `pageContainer`: an instance of L{FlatNotebook};
        :param `fr`: the current first visible tab.
        """

        pc = pageContainer

        rect = pc.GetClientRect()
        clientWidth = rect.width

        # Empty results
        vTabInfo = []
        tabHeight = self.CalcTabHeight(pageContainer)

        # The drawing starts from posx
        posx = pc._pParent.GetPadding()

        if fr < 0:
            fr = pc._nFrom

        for i in xrange(fr, len(pc._pagesInfoVec)):

            vc8glitch = tabHeight + FNB_HEIGHT_SPACER
            tabWidth = self.CalcTabWidth(pageContainer, i, tabHeight)

            if posx + tabWidth + vc8glitch + self.GetButtonsAreaLength(pc) >= clientWidth:
                break

            # Add a result to the returned vector
            tabRect = wx.Rect(posx, VERTICAL_BORDER_PADDING, tabWidth, tabHeight)
            vTabInfo.append(tabRect)

            # Advance posx
            posx += tabWidth + FNB_HEIGHT_SPACER

        return vTabInfo

#------------------------------------------------------------------
# Ribbon Tabs style
#------------------------------------------------------------------

[docs]class FNBRendererRibbonTabs(FNBRenderer):
    """
    This class handles the drawing of tabs using the `Ribbon Tabs` renderer.
    """

[docs]    def __init__(self):
        """ Default class constructor. """

        FNBRenderer.__init__(self)
        self._first = True
        self._factor = 1

    # definte this because we don't want to use the bold font

[docs]    def CalcTabWidth(self, pageContainer, tabIdx, tabHeight):
        """
        Calculates the width of the input tab.

        :param `pageContainer`: an instance of L{FlatNotebook};
        :param `tabIdx`: the index of the input tab;
        :param `tabHeight`: the height of the tab.
        """

        pc = pageContainer
        dc = wx.MemoryDC()
        dc.SelectObject(wx.EmptyBitmap(1,1))

        font = wx.SystemSettings_GetFont(wx.SYS_DEFAULT_GUI_FONT)

        if pc.IsDefaultTabs():
            shapePoints = int(tabHeight*math.tan(float(pc._pagesInfoVec[tabIdx].GetTabAngle())/180.0*math.pi))

        dc.SetFont(font)
        width, pom = dc.GetTextExtent(pc.GetPageText(tabIdx))

        # Set a minimum size to a tab
        if width < 20:
            width = 20

        tabWidth = 2*pc._pParent.GetPadding() + width

        # Style to add a small 'x' button on the top right
        # of the tab
        if pc.HasAGWFlag(FNB_X_ON_TAB) and tabIdx == pc.GetSelection():
            # The xpm image that contains the 'x' button is 9 pixels
            spacer = 9
            if pc.HasAGWFlag(FNB_VC8):
                spacer = 4

            tabWidth += pc._pParent.GetPadding() + spacer

        if pc.IsDefaultTabs():
            # Default style
            tabWidth += 2*shapePoints

        hasImage = pc._ImageList != None and pc._pagesInfoVec[tabIdx].GetImageIndex() != -1

        # For VC71 style, we only add the icon size (16 pixels)
        if hasImage:

            if not pc.IsDefaultTabs():
                tabWidth += 16 + pc._pParent.GetPadding()
            else:
                # Default style
                tabWidth += 16 + pc._pParent.GetPadding() + shapePoints/2

        return tabWidth

[docs]    def DrawTab(self, pageContainer, dc, posx, tabIdx, tabWidth, tabHeight, btnStatus):
        """
        Draws a tab using the `Ribbon Tabs` style.

        :param `pageContainer`: an instance of L{FlatNotebook};
        :param `dc`: an instance of `wx.DC`;
        :param `posx`: the x position of the tab;
        :param `tabIdx`: the index of the tab;
        :param `tabWidth`: the tab's width;
        :param `tabHeight`: the tab's height;
        :param `btnStatus`: the status of the 'X' button inside this tab.
        """

        pc = pageContainer

        gc = wx.GraphicsContext.Create(dc)
        gc.SetPen(dc.GetPen())
        gc.SetBrush(dc.GetBrush())

        spacer = math.ceil(float(FNB_HEIGHT_SPACER)/2/2)
        gc.DrawRoundedRectangle(posx+1,spacer,tabWidth-1,tabHeight-spacer*2,5)

        if tabIdx == pc.GetSelection():
            pass
        else:
            if tabIdx != pc.GetSelection() - 1:
                pass

        # -----------------------------------
        # Text and image drawing
        # -----------------------------------

        # Text drawing offset from the left border of the
        # rectangle

        # The width of the images are 16 pixels
        padding = pc.GetParent().GetPadding()
        hasImage = pc._pagesInfoVec[tabIdx].GetImageIndex() != -1
        imageYCoord = FNB_HEIGHT_SPACER/2

        if hasImage:
            textOffset = 2*pc._pParent._nPadding + 16
        else:
            textOffset = pc._pParent._nPadding

        textOffset += 2

        if tabIdx != pc.GetSelection():

            # Set the text background to be like the vertical lines
            dc.SetTextForeground(pc._pParent.GetNonActiveTabTextColour())

        if hasImage:

            imageXOffset = textOffset - 16 - padding
            pc._ImageList.Draw(pc._pagesInfoVec[tabIdx].GetImageIndex(), dc,
                                     posx + imageXOffset, imageYCoord,
                                     wx.IMAGELIST_DRAW_TRANSPARENT, True)

        pageTextColour = pc._pParent.GetPageTextColour(tabIdx)
        if pageTextColour is not None:
            dc.SetTextForeground(pageTextColour)

        dc.DrawText(pc.GetPageText(tabIdx), posx + textOffset, imageYCoord)

        # draw 'x' on tab (if enabled)
        if pc.HasAGWFlag(FNB_X_ON_TAB) and tabIdx == pc.GetSelection():

            textWidth, textHeight = dc.GetTextExtent(pc.GetPageText(tabIdx))
            tabCloseButtonXCoord = posx + textOffset + textWidth + 1

            # take a bitmap from the position of the 'x' button (the x on tab button)
            # this bitmap will be used later to delete old buttons
            tabCloseButtonYCoord = imageYCoord
            x_rect = wx.Rect(tabCloseButtonXCoord, tabCloseButtonYCoord, 16, 16)

            # Draw the tab
            self.DrawTabX(pc, dc, x_rect, tabIdx, btnStatus)

[docs]    def DrawTabs(self, pageContainer, dc):
        """
        Actually draws the tabs in L{FlatNotebook}.

        :param `pageContainer`: an instance of L{FlatNotebook};
        :param `dc`: an instance of `wx.DC`.
        """

        pc = pageContainer
        #style = pc.GetParent().GetWindowStyleFlag()

        if "__WXMAC__" in wx.PlatformInfo:
            # Works well on MSW & GTK, however this lines should be skipped on MAC
            if not pc._pagesInfoVec or pc._nFrom >= len(pc._pagesInfoVec):
                pc.Hide()
                return

        # Get the text height
        tabHeight = self.CalcTabHeight(pageContainer)

        # Calculate the number of rows required for drawing the tabs
        rect = pc.GetClientRect()
        clientWidth = rect.width

        # Set the maximum client size
        pc.SetSizeHints(self.GetButtonsAreaLength(pc), tabHeight)

        size = pc.GetSize()

        # Background
        dc.SetTextBackground(pc.GetBackgroundColour())
        dc.SetTextForeground(pc._activeTextColour)

        borderPen = wx.Pen(wx.SystemSettings_GetColour(wx.SYS_COLOUR_BTNSHADOW))
        backBrush = wx.Brush(pc._tabAreaColour)

        # If border style is set, set the pen to be border pen
        if pc.HasAGWFlag(FNB_TABS_BORDER_SIMPLE):
            dc.SetPen(borderPen)
        else:
            dc.SetPen(wx.Pen(pc._tabAreaColour))

        dc.SetBrush(backBrush)
        dc.DrawRectangle(0, 0, size.x, size.y)

        # Draw labels
        font = wx.SystemSettings_GetFont(wx.SYS_DEFAULT_GUI_FONT)
        dc.SetFont(font)

        posx = pc._pParent.GetPadding()

        # Update all the tabs from 0 to 'pc._nFrom' to be non visible
        for i in xrange(pc._nFrom):
            pc._pagesInfoVec[i].SetPosition(wx.Point(-1, -1))

        count = pc._nFrom

        #----------------------------------------------------------
        # Go over and draw the visible tabs
        #----------------------------------------------------------
        selPen = wx.Pen(adjust_colour(pc._tabAreaColour, -20))
        noselPen = wx.Pen(pc._tabAreaColour)
        noselBrush = wx.Brush(pc._tabAreaColour)
        selBrush = wx.Brush(LightColour(pc._tabAreaColour,60))

        for i in xrange(pc._nFrom, len(pc._pagesInfoVec)):

            # This style highlights the selected tab and the tab the mouse is over
            highlight = (i==pc.GetSelection()) or pc.IsMouseHovering(i)
            dc.SetPen((highlight and [selPen] or [noselPen])[0])
            dc.SetBrush((highlight and [selBrush] or [noselBrush])[0])

            # Add the padding to the tab width
            # Tab width:
            # +-----------------------------------------------------------+
            # | PADDING | IMG | IMG_PADDING | TEXT | PADDING | x |PADDING |
            # +-----------------------------------------------------------+
            tabWidth = self.CalcTabWidth(pageContainer, i, tabHeight)

            # Check if we can draw more
            if posx + tabWidth + self.GetButtonsAreaLength(pc) >= clientWidth:
                break

            count = count + 1

            # By default we clean the tab region
            #pc._pagesInfoVec[i].GetRegion().Clear()

            # Clean the 'x' buttn on the tab.
            # A 'Clean' rectangle, is a rectangle with width or height
            # with values lower than or equal to 0
            pc._pagesInfoVec[i].GetXRect().SetSize(wx.Size(-1, -1))

            # Draw the tab (border, text, image & 'x' on tab)
            self.DrawTab(pc, dc, posx, i, tabWidth, tabHeight, pc._nTabXButtonStatus)

            # Restore the text forground
            dc.SetTextForeground(pc._activeTextColour)

            # Update the tab position & size
            posy = (pc.HasAGWFlag(FNB_BOTTOM) and [0] or [VERTICAL_BORDER_PADDING])[0]

            pc._pagesInfoVec[i].SetPosition(wx.Point(posx, posy))
            pc._pagesInfoVec[i].SetSize(wx.Size(tabWidth, tabHeight))

            posx += tabWidth

        # Update all tabs that can not fit into the screen as non-visible
        for i in xrange(count, len(pc._pagesInfoVec)):
            pc._pagesInfoVec[i].SetPosition(wx.Point(-1, -1))
            pc._pagesInfoVec[i].GetRegion().Clear()

        # Draw the left/right/close buttons
        # Left arrow
        self.DrawLeftArrow(pc, dc)
        self.DrawRightArrow(pc, dc)
        self.DrawX(pc, dc)
        self.DrawDropDownArrow(pc, dc)

# ---------------------------------------------------------------------------- #
# Class FlatNotebook
# ---------------------------------------------------------------------------- #

[docs]class FlatNotebook(wx.PyPanel):
    """
    The L{FlatNotebook} is a full implementation of the `wx.Notebook`, and designed to be
    a drop-in replacement for `wx.Notebook`. The API functions are similar so one can
    expect the function to behave in the same way.
    """

[docs]    def __init__(self, parent, id=wx.ID_ANY, pos=wx.DefaultPosition, size=wx.DefaultSize,
                 style=0, agwStyle=0, name="FlatNotebook"):
        """
        Default class constructor.

        :param `parent`: the L{FlatNotebook} parent;
        :param `id`: an identifier for the control: a value of -1 is taken to mean a default;
        :param `pos`: the control position. A value of (-1, -1) indicates a default position,
         chosen by either the windowing system or wxPython, depending on platform;
        :param `size`: the control size. A value of (-1, -1) indicates a default size,
         chosen by either the windowing system or wxPython, depending on platform;
        :param `style`: the underlying `wx.PyPanel` window style;
        :param `agwStyle`: the AGW-specific window style. This can be a combination of the
         following bits:

         ================================ =========== ==================================================
         Window Styles                    Hex Value   Description
         ================================ =========== ==================================================
         ``FNB_VC71``                             0x1 Use Visual Studio 2003 (VC7.1) style for tabs.
         ``FNB_FANCY_TABS``                       0x2 Use fancy style - square tabs filled with gradient colouring.
         ``FNB_TABS_BORDER_SIMPLE``               0x4 Draw thin border around the page.
         ``FNB_NO_X_BUTTON``                      0x8 Do not display the 'X' button.
         ``FNB_NO_NAV_BUTTONS``                  0x10 Do not display the right/left arrows.
         ``FNB_MOUSE_MIDDLE_CLOSES_TABS``        0x20 Use the mouse middle button for cloing tabs.
         ``FNB_BOTTOM``                          0x40 Place tabs at bottom - the default is to place them at top.
         ``FNB_NODRAG``                          0x80 Disable dragging of tabs.
         ``FNB_VC8``                            0x100 Use Visual Studio 2005 (VC8) style for tabs.
         ``FNB_X_ON_TAB``                       0x200 Place 'X' close button on the active tab.
         ``FNB_BACKGROUND_GRADIENT``            0x400 Use gradients to paint the tabs background.
         ``FNB_COLOURFUL_TABS``                 0x800 Use colourful tabs (VC8 style only).
         ``FNB_DCLICK_CLOSES_TABS``            0x1000 Style to close tab using double click.
         ``FNB_SMART_TABS``                    0x2000 Use `Smart Tabbing`, like ``Alt`` + ``Tab`` on Windows.
         ``FNB_DROPDOWN_TABS_LIST``            0x4000 Use a dropdown menu on the left in place of the arrows.
         ``FNB_ALLOW_FOREIGN_DND``             0x8000 Allows drag 'n' drop operations between different L{FlatNotebook}.
         ``FNB_HIDE_ON_SINGLE_TAB``           0x10000 Hides the Page Container when there is one or fewer tabs.
         ``FNB_DEFAULT_STYLE``                0x10020 L{FlatNotebook} default style.
         ``FNB_FF2``                          0x20000 Use Firefox 2 style for tabs.
         ``FNB_NO_TAB_FOCUS``                 0x40000 Does not allow tabs to have focus.
         ``FNB_RIBBON_TABS``                  0x80000 Use the Ribbon Tabs style.
         ``FNB_HIDE_TABS``                   0x100000 Hides the Page Container allowing only keyboard navigation
         ``FNB_NAV_BUTTONS_WHEN_NEEDED``     0x200000 Hides the navigation left/right arrows if all tabs fit
         ================================ =========== ==================================================

        :param `name`: the window name.
        """

        self._bForceSelection = False
        self._nPadding = 6
        self._nFrom = 0
        style |= wx.TAB_TRAVERSAL
        self._pages = None
        self._windows = []
        self._popupWin = None
        self._naviIcon = None
        self._agwStyle = agwStyle
        self._orientation = None
        self._customPanel = None

        wx.PyPanel.__init__(self, parent, id, pos, size, style)
        attr = self.GetDefaultAttributes()
        self.SetOwnForegroundColour(attr.colFg)
        self.SetOwnBackgroundColour(attr.colBg)

        self._pages = PageContainer(self, wx.ID_ANY, wx.DefaultPosition, wx.DefaultSize, style)

        self.Bind(wx.EVT_NAVIGATION_KEY, self.OnNavigationKey)

        self.Init()

[docs]    def Init(self):
        """ Initializes all the class attributes. """

        self._pages._colourBorder = wx.SystemSettings_GetColour(wx.SYS_COLOUR_BTNSHADOW)

        self._mainSizer = wx.BoxSizer(wx.VERTICAL)
        self.SetSizer(self._mainSizer)

        # The child panels will inherit this bg colour, so leave it at the default value
        #self.SetBackgroundColour(wx.SystemSettings_GetColour(wx.SYS_COLOUR_APPWORKSPACE))

        # Set default page height
        dc = wx.ClientDC(self)

        if "__WXGTK__" in wx.PlatformInfo:
            # For GTK it seems that we must do this steps in order
            # for the tabs will get the proper height on initialization
            # on MSW, preforming these steps yields wierd results
            boldFont = wx.SystemSettings_GetFont(wx.SYS_DEFAULT_GUI_FONT)
            boldFont.SetWeight(wx.FONTWEIGHT_BOLD)
            dc.SetFont(boldFont)

        height = dc.GetCharHeight()

        tabHeight = height + FNB_HEIGHT_SPACER         # We use 8 pixels as padding

        if "__WXGTK__" in wx.PlatformInfo:
            tabHeight += 6

        self._pages.SetSizeHints(-1, tabHeight)
        # Add the tab container to the sizer
        self._mainSizer.Insert(0, self._pages, 0, wx.EXPAND)
        self._mainSizer.Layout()

        self._pages._nFrom = self._nFrom
        self._pDropTarget = FNBDropTarget(self)
        self.SetDropTarget(self._pDropTarget)

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

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

        if not self._windows:
            # Something is better than nothing... no pages!
            return wx.Size(20, 20)

        maxWidth = maxHeight = 0
        tabHeight = self.GetPageBestSize().height

        for win in self._windows:
            # Loop over all the windows to get their best size
            width, height = win.GetBestSize()
            maxWidth, maxHeight = max(maxWidth, width), max(maxHeight, height)

        return wx.Size(maxWidth, maxHeight+tabHeight)

[docs]    def Tile(self, orient=None):
        """
        Shows pages in column/row mode (one panel after the other in columns/rows).

        :param `orient`: this parameter represents the orientation of the stacked
         panels. Pass ``wx.VERTICAL`` to get vertically stacked panels, ``wx.HORIZONTAL``
         to get horizontally stacked panels or ``None`` to return to the default
         L{FlatNotebook} behaviour with tabs.
        """

        self.Freeze()
        self._orientation = orient

        self._mainSizer.Detach(self._pages)
        for win in self._windows:
            self._mainSizer.Detach(win)

##        self._mainSizer.Destroy()

        if orient is not None:
            self._mainSizer = wx.BoxSizer(orient)
            self._mainSizer.Add(self._pages)

            for win in self._windows:
                self._mainSizer.Add(win, 1, wx.EXPAND | wx.ALL, 2)
                win.Show()

        else:

            self._mainSizer = wx.BoxSizer(wx.VERTICAL)
            # Add the tab container to the sizer
            self._mainSizer.Insert(0, self._pages, 0, wx.EXPAND)

            curr = self._pages.GetSelection()
            for indx, win in enumerate(self._windows):
                if indx == curr:
                    if self.GetAGWWindowStyleFlag() & FNB_BOTTOM:
                        self._mainSizer.Insert(0, win, 1, wx.EXPAND)
                    else:
                        # We leave a space of 1 pixel around the window
                        self._mainSizer.Add(win, 1, wx.EXPAND)
                    win.Show()

                else:
                    win.Hide()

        self.SetSizer(self._mainSizer)

        self._mainSizer.Layout()
        self.Layout()

        if orient is None:
            self.SetSelection(self._pages._iActivePage)
            self._pages._ReShow()

        self.Thaw()

[docs]    def GetTileOrientation(self):
        """
        Returns the orientation when on tiling mode. This method can return
        ``wx.VERTICAL`` when the panels are vertically stacked, ``wx.HORIZONTAL``
        when they are horizontally stacked panels or ``None`` when there is no
        stacking and L{FlatNotebook} behaves like a normal notebook.
        """

        return self._orientation

[docs]    def SetCustomPage(self, panel):
        """
        Sets a custom panel to show when there are no pages left in L{FlatNotebook}.

        :param `panel`: any subclass of `wx.Window` will do, as long as it is suitable
         to be used as a notebook page. Examples include `wx.Panel`, `wx.ScrolledWindow`,
         and so on.
        """

        self.Freeze()

        if panel is None:
            if self._customPanel is not None:
                self._mainSizer.Detach(self._customPanel)
                self._customPanel.Show(False)

        else:
            if self._customPanel is not None:
                self._mainSizer.Detach(self._customPanel)
                self._customPanel.Show(False)
                self._customPanel.Destroy()

        self._customPanel = panel
        self.ShowCustomPage(True)

        self._pages._ReShow()
        self._mainSizer.Layout()
        self.Thaw()

[docs]    def GetCustomPage(self):
        """ Returns a custom panel to show when there are no pages left in L{FlatNotebook}. """

        return self._customPanel

[docs]    def ShowCustomPage(self, show=True):
        """ Hides the custom panel which is shown when there are no pages left in L{FlatNotebook}. """

        if self._customPanel is None:
            return

        self.Freeze()
        self._customPanel.Show(False)

        if show:
            if self.GetPageCount() == 0:
                self._mainSizer.Add(self._customPanel, 1, wx.EXPAND | wx.ALL, 2)
                self._customPanel.Show(True)
        else:
            if self._customPanel.GetContainingSizer() is not None:
                self._mainSizer.Detach(self._customPanel)

        self._mainSizer.Layout()
        self.Thaw()

[docs]    def SetActiveTabTextColour(self, textColour):
        """
        Sets the text colour for the active tab.

        :param `textColour`: a valid `wx.Colour` object or any typemap supported by wxWidgets/wxPython
         to generate a colour (i.e., a hex string, a colour name, a 3 or 4 integer tuple).
        """

        self._pages._activeTextColour = FormatColour(textColour)

[docs]    def OnDropTarget(self, x, y, nTabPage, wnd_oldContainer):
        """
        Handles the drop action from a drag and drop operation.

        :param `x`: the x position of the drop action;
        :param `y`: the y position of the drop action;
        :param `nTabPage`: the index of the tab being dropped;
        :param `wnd_oldContainer`: the L{FlatNotebook} to which the dropped tab previously
         belonged to.
        """

        return self._pages.OnDropTarget(x, y, nTabPage, wnd_oldContainer)

[docs]    def GetPreviousSelection(self):
        """ Returns the previous selection. """

        return self._pages._iPreviousActivePage

[docs]    def AddPage(self, page, text, select=False, imageId=-1):
        """
        Adds a page to the L{FlatNotebook}.

        :param `page`: specifies the new page;
        :param `text`: specifies the text for the new page;
        :param `select`: specifies whether the page should be selected;
        :param `imageId`: specifies the optional image index for the new page.

        :return: ``True`` if successful, ``False`` otherwise.
        """

        # sanity check
        if not page:
            return False

        min_size = page.GetMinSize()
        if not min_size.IsFullySpecified():
            page.SetMinSize((1, 1))

        self.ShowCustomPage(False)

        # reparent the window to us
        page.Reparent(self)

        # Add tab
        bSelected = select or len(self._windows) == 0

        if bSelected:

            bSelected = False

            # Check for selection and send events
            oldSelection = self._pages._iActivePage
            tabIdx = len(self._windows)

            event = FlatNotebookEvent(wxEVT_FLATNOTEBOOK_PAGE_CHANGING, self.GetId())
            event.SetSelection(tabIdx)
            event.SetOldSelection(oldSelection)
            event.SetEventObject(self)

            if not self.GetEventHandler().ProcessEvent(event) or event.IsAllowed() or len(self._windows) == 0:
                bSelected = True

        curSel = self._pages.GetSelection()

        if not self._pages.IsShown():
            self._pages.Show()

        self._pages.AddPage(text, bSelected, imageId)
        self._windows.append(page)

        self.Freeze()

        # Check if a new selection was made
        if bSelected:

            if curSel >= 0:

                # Remove the window from the main sizer
                self._mainSizer.Detach(self._windows[curSel])
                self._windows[curSel].Hide()

            if self.GetAGWWindowStyleFlag() & FNB_BOTTOM:

                self._mainSizer.Insert(0, page, 1, wx.EXPAND)

            else:

                # We leave a space of 1 pixel around the window
                self._mainSizer.Add(page, 1, wx.EXPAND)

            # Fire a wxEVT_FLATNOTEBOOK_PAGE_CHANGED event
            event.SetEventType(wxEVT_FLATNOTEBOOK_PAGE_CHANGED)
            event.SetOldSelection(oldSelection)
            self.GetEventHandler().ProcessEvent(event)

        else:

            # Hide the page
            page.Hide()

        self.Tile(self._orientation)
        self.Thaw()
        self._mainSizer.Layout()
        self.Refresh()

        return True

[docs]    def SetImageList(self, imageList):
        """
        Sets the image list for the page control.

        :param `imageList`: an instance of `wx.ImageList`.
        """

        self._pages.SetImageList(imageList)

[docs]    def AssignImageList(self, imageList):
        """
        Assigns the image list for the page control.

        :param `imageList`: an instance of `wx.ImageList`.
        """

        self._pages.AssignImageList(imageList)

[docs]    def GetImageList(self):
        """ Returns the associated image list. """

        return self._pages.GetImageList()

[docs]    def InsertPage(self, indx, page, text, select=True, imageId=-1):
        """
        Inserts a new page at the specified position.

        :param `indx`: specifies the position of the new page;
        :param `page`: specifies the new page;
        :param `text`: specifies the text for the new page;
        :param `select`: specifies whether the page should be selected;
        :param `imageId`: specifies the optional image index for the new page.

        :return: ``True`` if successful, ``False`` otherwise.
        """

        # sanity check
        if not page:
            return False

        self.ShowCustomPage(False)

        # reparent the window to us
        page.Reparent(self)

        if not self._windows:

            self.AddPage(page, text, select, imageId)
            return True

        # Insert tab
        bSelected = select or not self._windows
        curSel = self._pages.GetSelection()

        indx = max(0, min(indx, len(self._windows)))

        if indx <= len(self._windows):

            self._windows.insert(indx, page)

        else:

            self._windows.append(page)

        if bSelected:

            bSelected = False

            # Check for selection and send events
            oldSelection = self._pages._iActivePage

            event = FlatNotebookEvent(wxEVT_FLATNOTEBOOK_PAGE_CHANGING, self.GetId())
            event.SetSelection(indx)
            event.SetOldSelection(oldSelection)
            event.SetEventObject(self)

            if not self.GetEventHandler().ProcessEvent(event) or event.IsAllowed() or len(self._windows) == 0:
                bSelected = True

        self._pages.InsertPage(indx, text, bSelected, imageId)

        if indx <= curSel:
            curSel = curSel + 1

        self.Freeze()

        # Check if a new selection was made
        if bSelected:

            if curSel >= 0:

                # Remove the window from the main sizer
                self._mainSizer.Detach(self._windows[curSel])
                self._windows[curSel].Hide()

            self._pages.SetSelection(indx)

            # Fire a wxEVT_FLATNOTEBOOK_PAGE_CHANGED event
            event.SetEventType(wxEVT_FLATNOTEBOOK_PAGE_CHANGED)
            event.SetOldSelection(oldSelection)
            self.GetEventHandler().ProcessEvent(event)

        else:

            # Hide the page
            page.Hide()

        self.Tile(self._orientation)
        self.Thaw()
        self._mainSizer.Layout()
        self.Refresh()

        return True

[docs]    def SetSelection(self, page):
        """
        Sets the selection for the given page.

        :param `page`: an integer specifying the new selected page.

        :note: The call to this function **does not** generate the page changing events.
        """

        if page >= len(self._windows) or not self._windows:
            return

        # Support for disabed tabs
        if not self._pages.GetEnabled(page) and len(self._windows) > 1 and not self._bForceSelection:
            return

        if self._orientation is not None:
            return

        curSel = self._pages.GetSelection()

        # program allows the page change
        self.Freeze()
        if curSel >= 0:

            # Remove the window from the main sizer
            self._mainSizer.Detach(self._windows[curSel])
            self._windows[curSel].Hide()

        if self.GetAGWWindowStyleFlag() & FNB_BOTTOM:

            self._mainSizer.Insert(0, self._windows[page], 1, wx.EXPAND)

        else:

            # We leave a space of 1 pixel around the window
            self._mainSizer.Add(self._windows[page], 1, wx.EXPAND)

        self._windows[page].Show()
        self.Thaw()

        self._mainSizer.Layout()

        if page != self._pages._iActivePage:
            # there is a real page changing
            self._pages._iPreviousActivePage = self._pages._iActivePage

        self._pages._iActivePage = page
        self._pages.DoSetSelection(page)

[docs]    def DeletePage(self, page):
        """
        Deletes the specified page, and the associated window.

        :param `page`: an integer specifying the new selected page.

        :note: The call to this function generates the page changing events.
        """

        if page >= len(self._windows) or page < 0:
            return

        # Fire a closing event
        event = FlatNotebookEvent(wxEVT_FLATNOTEBOOK_PAGE_CLOSING, self.GetId())
        event.SetSelection(page)
        event.SetEventObject(self)
        self.GetEventHandler().ProcessEvent(event)

        # The event handler allows it?
        if not event.IsAllowed():
            return

        self.Freeze()

        # Delete the requested page
        pageRemoved = self._windows[page]

        # If the page is the current window, remove it from the sizer
        # as well
        if page == self._pages.GetSelection():
            self._mainSizer.Detach(pageRemoved)

        # Remove it from the array as well
        self._windows.pop(page)

        # Now we can destroy it in wxWidgets use Destroy instead of delete
        pageRemoved.Destroy()

        self.Thaw()

        self._pages.DoDeletePage(page)

        self.Tile(self._orientation)
        self.ShowCustomPage(True)

        self.Refresh()
        self.Update()

        # Fire a closed event
        closedEvent = FlatNotebookEvent(wxEVT_FLATNOTEBOOK_PAGE_CLOSED, self.GetId())
        closedEvent.SetSelection(page)
        closedEvent.SetEventObject(self)
        self.GetEventHandler().ProcessEvent(closedEvent)

[docs]    def DeleteAllPages(self):
        """ Deletes all the pages in the L{FlatNotebook}. """

        if not self._windows:
            return False

        self.Freeze()

        for page in self._windows:
            page.Destroy()

        self._windows = []
        self.Thaw()

        # Clear the container of the tabs as well
        self._pages.DeleteAllPages()
        self.ShowCustomPage(True)

        return True

[docs]    def GetCurrentPage(self):
        """ Returns the currently selected notebook page or ``None`` if none is selected. """

        sel = self._pages.GetSelection()
        if sel < 0 or sel >= len(self._windows):
            return None

        return self._windows[sel]

[docs]    def GetPage(self, page):
        """ Returns the window at the given page position, or ``None``. """

        if page >= len(self._windows):
            return None

        return self._windows[page]

[docs]    def GetPageIndex(self, win):
        """
        Returns the index at which the window is found.

        :param `win`: an instance of `wx.Window`.
        """

        try:
            return self._windows.index(win)
        except:
            return -1

[docs]    def GetSelection(self):
        """ Returns the currently selected page, or -1 if none was selected. """

        return self._pages.GetSelection()

[docs]    def AdvanceSelection(self, forward=True):
        """
        Cycles through the tabs.

        :param `forward`: if ``True``, the selection is advanced in ascending order
         (to the right), otherwise the selection is advanced in descending order.

        :note: The call to this function generates the page changing events.
        """

        self._pages.AdvanceSelection(forward)

[docs]    def GetPageCount(self):
        """ Returns the number of pages in the L{FlatNotebook} control. """

        return self._pages.GetPageCount()

[docs]    def SetNavigatorIcon(self, bmp):
        """
        Set the icon used by the L{TabNavigatorWindow}.

        :param `bmp`: a valid `wx.Bitmap` object.
        """

        if isinstance(bmp, wx.Bitmap) and bmp.IsOk():
            # Make sure image is proper size
            if bmp.GetSize() != (16, 16):
                img = bmp.ConvertToImage()
                img.Rescale(16, 16, wx.IMAGE_QUALITY_HIGH)
                bmp = wx.BitmapFromImage(img)
            self._naviIcon = bmp
        else:
            raise TypeError("SetNavigatorIcon requires a valid bitmap")

[docs]    def OnNavigationKey(self, event):
        """
        Handles the ``wx.EVT_NAVIGATION_KEY`` event for L{FlatNotebook}.

        :param `event`: a `wx.NavigationKeyEvent` event to be processed.
        """

        if event.IsWindowChange():
            if len(self._windows) == 0:
                return
            # change pages
            if self.HasAGWFlag(FNB_SMART_TABS):
                if not self._popupWin:
                    self._popupWin = TabNavigatorWindow(self, self._naviIcon)
                    self._popupWin.SetReturnCode(wx.ID_OK)
                    self._popupWin.ShowModal()
                    self._popupWin.Destroy()
                    self._popupWin = None
                else:
                    # a dialog is already opened
                    self._popupWin.OnNavigationKey(event)
                    return
            else:
                # change pages
                self.AdvanceSelection(event.GetDirection())

        else:
            event.Skip()

[docs]    def GetPageShapeAngle(self, page_index):
        """
        Returns the angle associated to a tab.

        :param `page_index`: the index of the tab for which we wish to get the shape angle.
        """

        if page_index < 0 or page_index >= len(self._pages._pagesInfoVec):
            return None, False

        result = self._pages._pagesInfoVec[page_index].GetTabAngle()
        return result, True

[docs]    def SetPageShapeAngle(self, page_index, angle):
        """
        Sets the angle associated to a tab.

        :param `page_index`: the index of the tab for which we wish to get the shape angle;
        :param `angle`: the new shape angle for the tab (must be less than 15 degrees).
        """

        if page_index < 0 or page_index >= len(self._pages._pagesInfoVec):
            return

        if angle > 15:
            return

        self._pages._pagesInfoVec[page_index].SetTabAngle(angle)

[docs]    def SetAllPagesShapeAngle(self, angle):
        """
        Sets the angle associated to all the tab.

        :param `angle`: the new shape angle for the tab (must be less than 15 degrees).
        """

        if angle > 15:
            return

        for ii in xrange(len(self._pages._pagesInfoVec)):
            self._pages._pagesInfoVec[ii].SetTabAngle(angle)

        self.Refresh()

[docs]    def GetPageBestSize(self):
        """ Return the page best size. """

        return self._pages.GetClientSize()

[docs]    def SetPageText(self, page, text):
        """
        Sets the text for the given page.

        :param `page`: an integer specifying the page index;
        :param `text`: the new tab label.
        """

        bVal = self._pages.SetPageText(page, text)
        self._pages.Refresh()

        return bVal

[docs]    def SetPadding(self, padding):
        """
        Sets the amount of space around each page's icon and label, in pixels.

        :param `padding`: the amount of space around each page's icon and label,
         in pixels.

        :note: Only the horizontal padding is considered.
        """

        self._nPadding = padding.GetWidth()

[docs]    def GetTabArea(self):
        """ Returns the associated page. """

        return self._pages

[docs]    def GetPadding(self):
        """ Returns the amount of space around each page's icon and label, in pixels. """

        return self._nPadding

[docs]    def SetAGWWindowStyleFlag(self, agwStyle):
        """
        Sets the L{FlatNotebook} window style flags.

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

         ================================ =========== ==================================================
         Window Styles                    Hex Value   Description
         ================================ =========== ==================================================
         ``FNB_VC71``                             0x1 Use Visual Studio 2003 (VC7.1) style for tabs.
         ``FNB_FANCY_TABS``                       0x2 Use fancy style - square tabs filled with gradient colouring.
         ``FNB_TABS_BORDER_SIMPLE``               0x4 Draw thin border around the page.
         ``FNB_NO_X_BUTTON``                      0x8 Do not display the 'X' button.
         ``FNB_NO_NAV_BUTTONS``                  0x10 Do not display the right/left arrows.
         ``FNB_MOUSE_MIDDLE_CLOSES_TABS``        0x20 Use the mouse middle button for cloing tabs.
         ``FNB_BOTTOM``                          0x40 Place tabs at bottom - the default is to place them at top.
         ``FNB_NODRAG``                          0x80 Disable dragging of tabs.
         ``FNB_VC8``                            0x100 Use Visual Studio 2005 (VC8) style for tabs.
         ``FNB_X_ON_TAB``                       0x200 Place 'X' close button on the active tab.
         ``FNB_BACKGROUND_GRADIENT``            0x400 Use gradients to paint the tabs background.
         ``FNB_COLOURFUL_TABS``                 0x800 Use colourful tabs (VC8 style only).
         ``FNB_DCLICK_CLOSES_TABS``            0x1000 Style to close tab using double click.
         ``FNB_SMART_TABS``                    0x2000 Use `Smart Tabbing`, like ``Alt`` + ``Tab`` on Windows.
         ``FNB_DROPDOWN_TABS_LIST``            0x4000 Use a dropdown menu on the left in place of the arrows.
         ``FNB_ALLOW_FOREIGN_DND``             0x8000 Allows drag 'n' drop operations between different L{FlatNotebook}.
         ``FNB_HIDE_ON_SINGLE_TAB``           0x10000 Hides the Page Container when there is one or fewer tabs.
         ``FNB_DEFAULT_STYLE``                0x10020 L{FlatNotebook} default style.
         ``FNB_FF2``                          0x20000 Use Firefox 2 style for tabs.
         ``FNB_NO_TAB_FOCUS``                 0x40000 Does not allow tabs to have focus.
         ``FNB_RIBBON_TABS``                  0x80000 Use the Ribbon Tabs style.
         ``FNB_HIDE_TABS``                   0x100000 Hides the Page Container allowing only keyboard navigation
         ``FNB_NAV_BUTTONS_WHEN_NEEDED``     0x200000 Hides the navigation left/right arrows if all tabs fit
         ================================ =========== ==================================================

        """

        oldStyle = self._agwStyle
        self._agwStyle = agwStyle
        renderer = self._pages._mgr.GetRenderer(agwStyle)
        renderer._tabHeight = None

        if self._pages:
            # For changing the tab position (i.e. placing them top/bottom)
            # refreshing the tab container is not enough
            self.SetSelection(self._pages._iActivePage)

        # If we just hid the tabs we must Refresh()
        if (not (oldStyle & FNB_HIDE_TABS) and agwStyle & FNB_HIDE_TABS) or \
           (not (oldStyle & FNB_HIDE_ON_SINGLE_TAB) and agwStyle & FNB_HIDE_ON_SINGLE_TAB):
            self.Refresh()

        if (oldStyle & FNB_HIDE_TABS and not (agwStyle & FNB_HIDE_TABS)) or \
           (oldStyle & FNB_HIDE_ON_SINGLE_TAB and not self.HasAGWFlag(FNB_HIDE_ON_SINGLE_TAB)):
            #For Redrawing the Tabs once you remove the Hide tyle
            self._pages._ReShow()

[docs]    def GetAGWWindowStyleFlag(self):
        """
        Returns the L{FlatNotebook} window style.

        :see: L{SetAGWWindowStyleFlag} for a list of valid window styles.
        """

        return self._agwStyle

[docs]    def HasAGWFlag(self, flag):
        """
        Returns whether a flag is present in the L{FlatNotebook} style.

        :param `flag`: one of the possible L{FlatNotebook} window styles.

        :see: L{SetAGWWindowStyleFlag} for a list of possible window style flags.
        """

        agwStyle = self.GetAGWWindowStyleFlag()
        res = (agwStyle & flag and [True] or [False])[0]
        return res

[docs]    def HideTabs(self):
        """ Hides the tabs. """

        agwStyle = self.GetAGWWindowStyleFlag()
        agwStyle |= FNB_HIDE_TABS
        self.SetAGWWindowStyleFlag(agwStyle)

[docs]    def ShowTabs(self):
        """ Shows the tabs if hidden previously. """

        agwStyle = self.GetAGWWindowStyleFlag()
        agwStyle &= ~FNB_HIDE_TABS
        self.SetAGWWindowStyleFlag(agwStyle)

[docs]    def RemovePage(self, page):
        """
        Deletes the specified page, without deleting the associated window.

        :param `page`: an integer specifying the page index.
        """

        if page >= len(self._windows):
            return False

        # Fire a closing event
        event = FlatNotebookEvent(wxEVT_FLATNOTEBOOK_PAGE_CLOSING, self.GetId())
        event.SetSelection(page)
        event.SetEventObject(self)
        self.GetEventHandler().ProcessEvent(event)

        # The event handler allows it?
        if not event.IsAllowed():
            return False

        self.Freeze()

        # Remove the requested page
        pageRemoved = self._windows[page]

        # If the page is the current window, remove it from the sizer
        # as well
        if page == self._pages.GetSelection():
            self._mainSizer.Detach(pageRemoved)

        # Remove it from the array as well
        self._windows.pop(page)

        self.Tile(self._orientation)
        self.ShowCustomPage(True)

        self.Thaw()

        self._pages.DoDeletePage(page)

        return True

[docs]    def SetRightClickMenu(self, menu):
        """
        Sets the popup menu associated to a right click on a tab.

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

        self._pages._pRightClickMenu = menu

[docs]    def GetPageText(self, page):
        """
        Returns the string for the given page.

        :param `page`: an integer specifying the page index.
        """

        return self._pages.GetPageText(page)

[docs]    def SetGradientColours(self, fr, to, border):
        """
        Sets the gradient colours for the tab.

        :param `fr`: the first gradient colour, an instance of `wx.Colour`;
        :param `to`: the second gradient colour, an instance of `wx.Colour`;
        :param `border`: the border colour, an instance of `wx.Colour`.
        """

        self._pages._colourFrom = fr
        self._pages._colourTo   = to
        self._pages._colourBorder = border

[docs]    def SetGradientColourFrom(self, fr):
        """
        Sets the starting colour for the gradient.

        :param `fr`: the first gradient colour, an instance of `wx.Colour`.
        """

        self._pages._colourFrom = fr

[docs]    def SetGradientColourTo(self, to):
        """
        Sets the ending colour for the gradient.

        :param `to`: the second gradient colour, an instance of `wx.Colour`;
        """

        self._pages._colourTo = to

[docs]    def SetGradientColourBorder(self, border):
        """
        Sets the tab border colour.

        :param `border`: the border colour, an instance of `wx.Colour`.
        """

        self._pages._colourBorder = border

[docs]    def GetGradientColourFrom(self):
        """ Gets first gradient colour. """

        return self._pages._colourFrom

[docs]    def GetGradientColourTo(self):
        """ Gets second gradient colour. """

        return self._pages._colourTo

[docs]    def GetGradientColourBorder(self):
        """ Gets the tab border colour. """

        return self._pages._colourBorder

[docs]    def GetBorderColour(self):
        """ Returns the border colour. """

        return self._pages._colourBorder

[docs]    def GetActiveTabTextColour(self):
        """ Get the active tab text colour. """

        return self._pages._activeTextColour

[docs]    def SetPageImage(self, page, image):
        """
        Sets the image index for the given page.

        :param `page`: an integer specifying the page index;
        :param `image`: an index into the image list which was set with L{SetImageList}.
        """

        self._pages.SetPageImage(page, image)

[docs]    def GetPageImage(self, page):
        """
        Returns the image index for the given page.

        :param `page`: an integer specifying the page index.
        """

        return self._pages.GetPageImage(page)

[docs]    def GetEnabled(self, page):
        """
        Returns whether a tab is enabled or not.

        :param `page`: an integer specifying the page index.
        """

        return self._pages.GetEnabled(page)

[docs]    def EnableTab(self, page, enabled=True):
        """
        Enables or disables a tab.

        :param `page`: an integer specifying the page index;
        :param `enabled`: ``True`` to enable a tab, ``False`` to disable it.
        """

        if page >= len(self._windows):
            return

        self._windows[page].Enable(enabled)
        self._pages.EnableTab(page, enabled)

[docs]    def GetNonActiveTabTextColour(self):
        """ Returns the non active tabs text colour. """

        return self._pages._nonActiveTextColour

[docs]    def SetNonActiveTabTextColour(self, colour):
        """
        Sets the non active tabs text colour.

        :param `colour`: a valid `wx.Colour` object or any typemap supported by wxWidgets/wxPython
         to generate a colour (i.e., a hex string, a colour name, a 3 or 4 integer tuple).
        """

        self._pages._nonActiveTextColour = FormatColour(colour)

[docs]    def GetPageTextColour(self, page):
        """
        Returns the tab text colour if it has been set previously, or ``None`` otherwise.

        :param `page`: an integer specifying the page index.
        """

        return self._pages.GetPageTextColour(page)

[docs]    def SetPageTextColour(self, page, colour):
        """
        Sets the tab text colour individually.

        :param `page`: an integer specifying the page index;
        :param `colour`: a valid `wx.Colour` object or any typemap supported by wxWidgets/wxPython
         to generate a colour (i.e., a hex string, a colour name, a 3 or 4 integer tuple). You can
         pass ``None`` or `wx.NullColour` to return to the default page text colour.
        """

        self._pages.SetPageTextColour(page, colour)

[docs]    def SetTabAreaColour(self, colour):
        """
        Sets the area behind the tabs colour.

        :param `colour`: a valid `wx.Colour` object or any typemap supported by wxWidgets/wxPython
         to generate a colour (i.e., a hex string, a colour name, a 3 or 4 integer tuple).
        """

        self._pages._tabAreaColour = FormatColour(colour)

[docs]    def GetTabAreaColour(self):
        """ Returns the area behind the tabs colour. """

        return self._pages._tabAreaColour

[docs]    def SetActiveTabColour(self, colour):
        """
        Sets the active tab colour.

        :param `colour`: a valid `wx.Colour` object or any typemap supported by wxWidgets/wxPython
         to generate a colour (i.e., a hex string, a colour name, a 3 or 4 integer tuple).
        """

        self._pages._activeTabColour = FormatColour(colour)

[docs]    def GetActiveTabColour(self):
        """ Returns the active tab colour. """

        return self._pages._activeTabColour

[docs]    def EnsureVisible(self, page):
       """
       Ensures that a tab is visible.

       :param `page`: an integer specifying the page index.
       """

       self._pages.DoSetSelection(page)

# ---------------------------------------------------------------------------- #
# Class PageContainer
# Acts as a container for the pages you add to FlatNotebook
# ---------------------------------------------------------------------------- #

[docs]class PageContainer(wx.PyPanel):
    """
    This class acts as a container for the pages you add to L{FlatNotebook}.
    """

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

        Used internally, do not call it in your code!

        :param `parent`: the L{PageContainer} parent;
        :param `id`: an identifier for the control: a value of -1 is taken to mean a default;
        :param `pos`: the control position. A value of (-1, -1) indicates a default position,
         chosen by either the windowing system or wxPython, depending on platform;
        :param `size`: the control size. A value of (-1, -1) indicates a default size,
         chosen by either the windowing system or wxPython, depending on platform;
        :param `style`: the window style.
        """

        self._ImageList = None
        self._iActivePage = -1
        self._pDropTarget = None
        self._nLeftClickZone = FNB_NOWHERE
        self._iPreviousActivePage = -1

        self._pRightClickMenu = None
        self._nXButtonStatus = FNB_BTN_NONE
        self._nArrowDownButtonStatus = FNB_BTN_NONE
        self._pParent = parent
        self._nRightButtonStatus = FNB_BTN_NONE
        self._nLeftButtonStatus = FNB_BTN_NONE
        self._nTabXButtonStatus = FNB_BTN_NONE

        self._nHoveringOverTabIndex = -1
        self._nHoveringOverLastTabIndex = -1

        self._setCursor = False

        self._pagesInfoVec = []

        self._colourTo = wx.SystemSettings_GetColour(wx.SYS_COLOUR_ACTIVECAPTION)
        self._colourFrom = wx.WHITE
        self._activeTabColour = wx.WHITE
        self._activeTextColour = wx.SystemSettings_GetColour(wx.SYS_COLOUR_BTNTEXT)
        self._nonActiveTextColour = wx.SystemSettings_GetColour(wx.SYS_COLOUR_BTNTEXT)
        self._tabAreaColour = wx.SystemSettings_GetColour(wx.SYS_COLOUR_BTNFACE)

        self._nFrom = 0
        self._isdragging = False

        # Set default page height, this is done according to the system font
        memDc = wx.MemoryDC()
        memDc.SelectObject(wx.EmptyBitmap(1,1))

        if "__WXGTK__" in wx.PlatformInfo:
            boldFont = wx.SystemSettings_GetFont(wx.SYS_DEFAULT_GUI_FONT)
            boldFont.SetWeight(wx.BOLD)
            memDc.SetFont(boldFont)

        height = memDc.GetCharHeight()
        tabHeight = height + FNB_HEIGHT_SPACER # We use 10 pixels as padding

        wx.PyPanel.__init__(self, parent, id, pos, wx.Size(size.x, tabHeight),
                            style|wx.NO_BORDER|wx.NO_FULL_REPAINT_ON_RESIZE|wx.WANTS_CHARS)

        attr = self.GetDefaultAttributes()
        self.SetOwnForegroundColour(attr.colFg)
        self.SetOwnBackgroundColour(attr.colBg)

        self._pDropTarget = FNBDropTarget(self)
        self.SetDropTarget(self._pDropTarget)
        self._mgr = FNBRendererMgr()

        self.Bind(wx.EVT_PAINT, self.OnPaint)
        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_RIGHT_DOWN, self.OnRightDown)
        self.Bind(wx.EVT_MIDDLE_DOWN, self.OnMiddleDown)
        self.Bind(wx.EVT_MOTION, self.OnMouseMove)
        self.Bind(wx.EVT_MOUSEWHEEL, self.OnMouseWheel)
        self.Bind(wx.EVT_ERASE_BACKGROUND, self.OnEraseBackground)
        self.Bind(wx.EVT_LEAVE_WINDOW, self.OnMouseLeave)
        self.Bind(wx.EVT_ENTER_WINDOW, self.OnMouseEnterWindow)
        self.Bind(wx.EVT_LEFT_DCLICK, self.OnLeftDClick)
        self.Bind(wx.EVT_SET_FOCUS, self.OnSetFocus)
        self.Bind(wx.EVT_KILL_FOCUS, self.OnKillFocus)
        self.Bind(wx.EVT_KEY_DOWN, self.OnKeyDown)

[docs]    def OnEraseBackground(self, event):
        """
        Handles the ``wx.EVT_ERASE_BACKGROUND`` event for L{PageContainer}.

        :param `event`: a `wx.EraseEvent` event to be processed.

        :note: This method is intentionally empty to reduce flicker.
        """

        pass

    def _ReShow(self):
        """
        Handles the redraw of the tabs when the ``FNB_HIDE_ON_SINGLE_TAB`` has been removed.
        """

        self.Show()
        self.GetParent()._mainSizer.Layout()
        self.Refresh()

[docs]    def OnPaint(self, event):
        """
        Handles the ``wx.EVT_PAINT`` event for L{PageContainer}.

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

        dc = wx.BufferedPaintDC(self)
        parent = self.GetParent()

        renderer = self._mgr.GetRenderer(parent.GetAGWWindowStyleFlag())
        renderer.DrawTabs(self, dc)

        if self.HasAGWFlag(FNB_HIDE_ON_SINGLE_TAB) and len(self._pagesInfoVec) <= 1 or \
           self.HasAGWFlag(FNB_HIDE_TABS) or parent._orientation or \
           (parent._customPanel and len(self._pagesInfoVec) == 0):
            self.Hide()
            self.GetParent()._mainSizer.Layout()
            self.Refresh()

[docs]    def AddPage(self, caption, selected=False, imgindex=-1):
        """
        Adds a page to the L{PageContainer}.

        :param `page`: specifies the new page;
        :param `text`: specifies the text for the new page;
        :param `select`: specifies whether the page should be selected;
        :param `imageId`: specifies the optional image index for the new page.
        """

        if selected:

            self._iPreviousActivePage = self._iActivePage
            self._iActivePage = len(self._pagesInfoVec)

        # Create page info and add it to the vector
        pageInfo = PageInfo(caption, imgindex)
        self._pagesInfoVec.append(pageInfo)
        self.Refresh()

[docs]    def InsertPage(self, indx, text, selected=True, imgindex=-1):
        """
        Inserts a new page at the specified position.

        :param `indx`: specifies the position of the new page;
        :param `page`: specifies the new page;
        :param `text`: specifies the text for the new page;
        :param `select`: specifies whether the page should be selected;
        :param `imageId`: specifies the optional image index for the new page.
        """

        if selected:

            self._iPreviousActivePage = self._iActivePage
            self._iActivePage = len(self._pagesInfoVec)

        self._pagesInfoVec.insert(indx, PageInfo(text, imgindex))

        self.Refresh()
        return True

[docs]    def OnSize(self, event):
        """
        Handles the ``wx.EVT_SIZE`` event for L{PageContainer}.

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

        # When resizing the control, try to fit to screen as many tabs as we can
        agwStyle = self.GetParent().GetAGWWindowStyleFlag()
        renderer = self._mgr.GetRenderer(agwStyle)

        fr = 0
        page = self.GetSelection()

        for fr in xrange(self._nFrom):
            vTabInfo = renderer.NumberTabsCanFit(self, fr)
            if page - fr >= len(vTabInfo):
                continue
            break

        self._nFrom = fr

        self.Refresh() # Call on paint
        event.Skip()

[docs]    def OnMiddleDown(self, event):
        """
        Handles the ``wx.EVT_MIDDLE_DOWN`` event for L{PageContainer}.

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

        # Test if this style is enabled
        agwStyle = self.GetParent().GetAGWWindowStyleFlag()

        if not agwStyle & FNB_MOUSE_MIDDLE_CLOSES_TABS:
            return

        where, tabIdx = self.HitTest(event.GetPosition())

        if where == FNB_TAB:
            self.DeletePage(tabIdx)

        event.Skip()

[docs]    def OnMouseWheel(self, event):
        """
        Handles the ``wx.EVT_MOUSEWHEEL`` event for L{PageContainer}.

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

        rotation = event.GetWheelRotation()
        delta = event.GetWheelDelta()
        steps = int(rotation/delta)

        for tab in xrange(abs(steps)):
            if steps > 0:
                before = self._nLeftButtonStatus
                self._nLeftButtonStatus = FNB_BTN_PRESSED
                self.RotateLeft()
                self._nLeftButtonStatus = before
            else:
                before = self._nRightButtonStatus
                self._nRightButtonStatus = FNB_BTN_PRESSED
                self.RotateRight()
                self._nRightButtonStatus = before

        event.Skip()

[docs]    def OnRightDown(self, event):
        """
        Handles the ``wx.EVT_RIGHT_DOWN`` event for L{PageContainer}.

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

        where, tabIdx = self.HitTest(event.GetPosition())

        if where in [FNB_TAB, FNB_TAB_X]:

            if self._pagesInfoVec[tabIdx].GetEnabled():
                # This shouldn't really change the selection, so it's commented out
                # Fire events and eventually (if allowed) change selection
                # self.FireEvent(tabIdx)

                # send a message to popup a custom menu
                event = FlatNotebookEvent(wxEVT_FLATNOTEBOOK_PAGE_CONTEXT_MENU, self.GetParent().GetId())
                event.SetSelection(tabIdx)
                event.SetOldSelection(self._iActivePage)
                event.SetEventObject(self.GetParent())
                self.GetParent().GetEventHandler().ProcessEvent(event)

                if self._pRightClickMenu:
                    self.PopupMenu(self._pRightClickMenu)

        event.Skip()

[docs]    def OnLeftDown(self, event):
        """
        Handles the ``wx.EVT_LEFT_DOWN`` event for L{PageContainer}.

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

        # Reset buttons status
        self._nXButtonStatus     = FNB_BTN_NONE
        self._nLeftButtonStatus  = FNB_BTN_NONE
        self._nRightButtonStatus = FNB_BTN_NONE
        self._nTabXButtonStatus  = FNB_BTN_NONE
        self._nArrowDownButtonStatus = FNB_BTN_NONE

        self._nLeftClickZone, tabIdx = self.HitTest(event.GetPosition())

        if self._nLeftClickZone == FNB_DROP_DOWN_ARROW:
            self._nArrowDownButtonStatus = FNB_BTN_PRESSED
            self.Refresh()
        elif self._nLeftClickZone == FNB_LEFT_ARROW:
            self._nLeftButtonStatus = FNB_BTN_PRESSED
            self.Refresh()
        elif self._nLeftClickZone == FNB_RIGHT_ARROW:
            self._nRightButtonStatus = FNB_BTN_PRESSED
            self.Refresh()
        elif self._nLeftClickZone == FNB_X:
            self._nXButtonStatus = FNB_BTN_PRESSED
            self.Refresh()
        elif self._nLeftClickZone == FNB_TAB_X:
            self._nTabXButtonStatus = FNB_BTN_PRESSED
            self.Refresh()

        elif self._nLeftClickZone == FNB_TAB:

            if self._iActivePage != tabIdx:

                # In case the tab is disabled, we dont allow to choose it
                if len(self._pagesInfoVec) > tabIdx and \
                   self._pagesInfoVec[tabIdx].GetEnabled():
                    self.FireEvent(tabIdx)

[docs]    def RotateLeft(self):
        """ Scrolls tabs to the left by bulk of 5 tabs. """

        if self._nFrom == 0:
            return

        # Make sure that the button was pressed before
        if self._nLeftButtonStatus != FNB_BTN_PRESSED:
            return

        self._nLeftButtonStatus = FNB_BTN_HOVER

        # We scroll left with bulks of 5
        scrollLeft = self.GetNumTabsCanScrollLeft()

        self._nFrom -= scrollLeft
        if self._nFrom < 0:
            self._nFrom = 0

        self.Refresh()

[docs]    def RotateRight(self):
        """ Scrolls tabs to the right by bulk of 5 tabs. """

        if self._nFrom >= len(self._pagesInfoVec) - 1:
            return

        # Make sure that the button was pressed before
        if self._nRightButtonStatus != FNB_BTN_PRESSED:
            return

        self._nRightButtonStatus = FNB_BTN_HOVER

        # Check if the right most tab is visible, if it is
        # don't rotate right anymore
        if self._pagesInfoVec[len(self._pagesInfoVec)-1].GetPosition() != wx.Point(-1, -1):
            return

        self._nFrom += 1
        self.Refresh()

[docs]    def OnLeftUp(self, event):
        """
        Handles the ``wx.EVT_LEFT_UP`` event for L{PageContainer}.

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

        # forget the zone that was initially clicked
        self._nLeftClickZone = FNB_NOWHERE

        where, tabIdx = self.HitTest(event.GetPosition())

        if not self.HasAGWFlag(FNB_NO_TAB_FOCUS):
            # Make sure selected tab has focus
            self.SetFocus()

        if where == FNB_LEFT_ARROW:
            self.RotateLeft()

        elif where == FNB_RIGHT_ARROW:
            self.RotateRight()

        elif where == FNB_X:

            # Make sure that the button was pressed before
            if self._nXButtonStatus != FNB_BTN_PRESSED:
                return

            self._nXButtonStatus = FNB_BTN_HOVER

            self.DeletePage(self._iActivePage)

        elif where == FNB_TAB_X:

            # Make sure that the button was pressed before
            if self._nTabXButtonStatus != FNB_BTN_PRESSED:
                return

            self._nTabXButtonStatus = FNB_BTN_HOVER

            self.DeletePage(self._iActivePage)

        elif where == FNB_DROP_DOWN_ARROW:

            # Make sure that the button was pressed before
            if self._nArrowDownButtonStatus != FNB_BTN_PRESSED:
                return

            self._nArrowDownButtonStatus = FNB_BTN_NONE

            # Refresh the button status
            renderer = self._mgr.GetRenderer(self.GetParent().GetAGWWindowStyleFlag())
            dc = wx.ClientDC(self)
            renderer.DrawDropDownArrow(self, dc)

            self.PopupTabsMenu()

        event.Skip()

[docs]    def HitTest(self, pt):
        """
        HitTest method for L{PageContainer}.

        :param `pt`: an instance of `wx.Point`, to test for hits.

        :return: The hit test flag (if any) and the hit page index (if any). The return
         value can be one of the following bits:

         ========================= ======= =================================
         HitTest Flag               Value  Description
         ========================= ======= =================================
         ``FNB_NOWHERE``                 0 Indicates mouse coordinates not on any tab of the notebook
         ``FNB_TAB``                     1 Indicates mouse coordinates inside a tab
         ``FNB_X``                       2 Indicates mouse coordinates inside the 'X' button region
         ``FNB_TAB_X``                   3 Indicates mouse coordinates inside the 'X' region in a tab
         ``FNB_LEFT_ARROW``              4 Indicates mouse coordinates inside the left arrow region
         ``FNB_RIGHT_ARROW``             5 Indicates mouse coordinates inside the right arrow region
         ``FNB_DROP_DOWN_ARROW``         6 Indicates mouse coordinates inside the drop down arrow region
         ========================= ======= =================================

        """

        agwStyle = self.GetParent().GetAGWWindowStyleFlag()
        render = self._mgr.GetRenderer(agwStyle)

        fullrect = self.GetClientRect()
        btnLeftPos = render.GetLeftButtonPos(self)
        btnRightPos = render.GetRightButtonPos(self)
        btnXPos = render.GetXPos(self)

        tabIdx = -1

        if len(self._pagesInfoVec) == 0:
            return FNB_NOWHERE, tabIdx

        rect = wx.Rect(btnXPos, 8, 16, 16)
        if rect.Contains(pt):
            return (agwStyle & FNB_NO_X_BUTTON and [FNB_NOWHERE] or [FNB_X])[0], tabIdx

        rect = wx.Rect(btnRightPos, 8, 16, 16)
        if agwStyle & FNB_DROPDOWN_TABS_LIST:
            rect = wx.Rect(render.GetDropArrowButtonPos(self), 8, 16, 16)
            if rect.Contains(pt):
                return FNB_DROP_DOWN_ARROW, tabIdx

        if rect.Contains(pt):
            return (agwStyle & FNB_NO_NAV_BUTTONS and [FNB_NOWHERE] or [FNB_RIGHT_ARROW])[0], tabIdx

        rect = wx.Rect(btnLeftPos, 8, 16, 16)
        if rect.Contains(pt):
            return (agwStyle & FNB_NO_NAV_BUTTONS and [FNB_NOWHERE] or [FNB_LEFT_ARROW])[0], tabIdx

        # Test whether a left click was made on a tab
        bFoundMatch = False

        for cur in xrange(self._nFrom, len(self._pagesInfoVec)):

            pgInfo = self._pagesInfoVec[cur]

            if pgInfo.GetPosition() == wx.Point(-1, -1):
                continue

            if agwStyle & FNB_X_ON_TAB and cur == self.GetSelection():
                # 'x' button exists on a tab
                if self._pagesInfoVec[cur].GetXRect().Contains(pt):
                    return FNB_TAB_X, cur

            if agwStyle & FNB_VC8:

                if self._pagesInfoVec[cur].GetRegion().Contains(pt.x, pt.y):
                    if bFoundMatch or cur == self.GetSelection():
                        return FNB_TAB, cur

                    tabIdx = cur
                    bFoundMatch = True

            else:

                tabRect = wx.Rect(pgInfo.GetPosition().x, pgInfo.GetPosition().y,
                                  pgInfo.GetSize().x, pgInfo.GetSize().y)

                if tabRect.Contains(pt):
                    # We have a match
                    return FNB_TAB, cur

        if bFoundMatch:
            return FNB_TAB, tabIdx

        if self._isdragging:
            # We are doing DND, so check also the region outside the tabs
            # try before the first tab
            pgInfo = self._pagesInfoVec[0]
            tabRect = wx.Rect(0, pgInfo.GetPosition().y, pgInfo.GetPosition().x, self.GetParent().GetSize().y)
            if tabRect.Contains(pt):
                return FNB_TAB, 0

            # try after the last tab
            pgInfo = self._pagesInfoVec[-1]
            startpos = pgInfo.GetPosition().x+pgInfo.GetSize().x
            tabRect = wx.Rect(startpos, pgInfo.GetPosition().y, fullrect.width-startpos, self.GetParent().GetSize().y)

            if tabRect.Contains(pt):
                return FNB_TAB, len(self._pagesInfoVec)

        # Default
        return FNB_NOWHERE, -1

[docs]    def SetSelection(self, page):
        """
        Sets the selected page.

        :param `page`: an integer specifying the page index.
        """

        book = self.GetParent()
        FlatNotebook.SetSelection(book, page)

##        self.DoSetSelection(page)

[docs]    def DoSetSelection(self, page):
        """
        Does the actual selection of a page.

        :param `page`: an integer specifying the page index.
        """

        if page < len(self._pagesInfoVec):
            #! fix for tabfocus
            da_page = self._pParent.GetPage(page)

            if da_page != None:
                da_page.SetFocus()

        if not self.IsTabVisible(page):
            # Try to remove one tab from start and try again

            if not self.CanFitToScreen(page):

                if self._nFrom > page:
                    self._nFrom = page
                else:
                    while self._nFrom < page:
                        self._nFrom += 1
                        if self.CanFitToScreen(page):
                            break

        self.Refresh()

[docs]    def DeletePage(self, page):
        """
        Delete the specified page from L{PageContainer}.

        :param `page`: an integer specifying the page index.
        """

        book = self.GetParent()
        book.DeletePage(page)
        book.Refresh()

[docs]    def IsMouseHovering(self, page):
        """
        Returns whether or not the mouse is hovering over this page's tab

        :param `page`: an integer specifying the page index.
        """
        return page == self._nHoveringOverTabIndex

[docs]    def IsTabVisible(self, page):
        """
        Returns whether a tab is visible or not.

        :param `page`: an integer specifying the page index.
        """

        iLastVisiblePage = self.GetLastVisibleTab()
        return page <= iLastVisiblePage and page >= self._nFrom

[docs]    def DoDeletePage(self, page):
        """
        Does the actual page deletion.

        :param `page`: an integer specifying the page index.
        """

        # Remove the page from the vector
        book = self.GetParent()
        self._pagesInfoVec.pop(page)

        # Thanks to Yiaanis AKA Mandrav
        if self._iActivePage >= page:
            self._iActivePage = self._iActivePage - 1
            self._iPreviousActivePage = -1

        # The delete page was the last first on the array,
        # but the book still has more pages, so we set the
        # active page to be the first one (0)
        if self._iActivePage < 0 and len(self._pagesInfoVec) > 0:
            self._iActivePage = 0
            self._iPreviousActivePage = -1

        # Refresh the tabs
        if self._iActivePage >= 0:

            book._bForceSelection = True

            # Check for selection and send event
            event = FlatNotebookEvent(wxEVT_FLATNOTEBOOK_PAGE_CHANGING, self.GetParent().GetId())
            event.SetSelection(self._iActivePage)
            event.SetOldSelection(self._iPreviousActivePage)
            event.SetEventObject(self.GetParent())
            self.GetParent().GetEventHandler().ProcessEvent(event)

            book.SetSelection(self._iActivePage)
            book._bForceSelection = False

            # Fire a wxEVT_FLATNOTEBOOK_PAGE_CHANGED event
            event.SetEventType(wxEVT_FLATNOTEBOOK_PAGE_CHANGED)
            event.SetOldSelection(self._iPreviousActivePage)
            self.GetParent().GetEventHandler().ProcessEvent(event)

        #if not self._pagesInfoVec:
        #    # Erase the page container drawings
        #    dc = wx.ClientDC(self)
        #    dc.Clear()

[docs]    def DeleteAllPages(self):
        """ Deletes all the pages in the L{PageContainer}. """

        self._iActivePage = -1
        self._iPreviousActivePage = -1
        self._nFrom = 0
        self._pagesInfoVec = []

        # Erase the page container drawings
        dc = wx.ClientDC(self)
        dc.Clear()

[docs]    def OnMouseMove(self, event):
        """
        Handles the ``wx.EVT_MOTION`` event for L{PageContainer}.

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

        if self._pagesInfoVec and self.IsShown():

            xButtonStatus = self._nXButtonStatus
            xTabButtonStatus = self._nTabXButtonStatus
            rightButtonStatus = self._nRightButtonStatus
            leftButtonStatus = self._nLeftButtonStatus
            dropDownButtonStatus = self._nArrowDownButtonStatus

            agwStyle = self.GetParent().GetAGWWindowStyleFlag()

            self._nXButtonStatus = FNB_BTN_NONE
            self._nRightButtonStatus = FNB_BTN_NONE
            self._nLeftButtonStatus = FNB_BTN_NONE
            self._nTabXButtonStatus = FNB_BTN_NONE
            self._nArrowDownButtonStatus = FNB_BTN_NONE
            bRedrawTabs = False
            self._nHoveringOverTabIndex = -1

            where, tabIdx = self.HitTest(event.GetPosition())

            if where == FNB_X:
                if event.LeftIsDown():

                    self._nXButtonStatus = (self._nLeftClickZone==FNB_X and [FNB_BTN_PRESSED] or [FNB_BTN_NONE])[0]

                else:

                    self._nXButtonStatus = FNB_BTN_HOVER

            elif where == FNB_DROP_DOWN_ARROW:
                if event.LeftIsDown():

                    self._nArrowDownButtonStatus = (self._nLeftClickZone==FNB_DROP_DOWN_ARROW and [FNB_BTN_PRESSED] or [FNB_BTN_NONE])[0]

                else:

                    self._nArrowDownButtonStatus = FNB_BTN_HOVER

            elif where == FNB_TAB_X:
                if event.LeftIsDown():

                    self._nTabXButtonStatus = (self._nLeftClickZone==FNB_TAB_X and [FNB_BTN_PRESSED] or [FNB_BTN_NONE])[0]

                else:

                    self._nTabXButtonStatus = FNB_BTN_HOVER

            elif where == FNB_RIGHT_ARROW:
                if event.LeftIsDown():

                    self._nRightButtonStatus = (self._nLeftClickZone==FNB_RIGHT_ARROW and [FNB_BTN_PRESSED] or [FNB_BTN_NONE])[0]

                else:

                    self._nRightButtonStatus = FNB_BTN_HOVER

            elif where == FNB_LEFT_ARROW:
                if event.LeftIsDown():

                    self._nLeftButtonStatus = (self._nLeftClickZone==FNB_LEFT_ARROW and [FNB_BTN_PRESSED] or [FNB_BTN_NONE])[0]

                else:

                    self._nLeftButtonStatus = FNB_BTN_HOVER

            elif where == FNB_TAB:
                # Call virtual method for showing tooltip
                self.ShowTabTooltip(tabIdx)

                if not self.GetEnabled(tabIdx):
                    # Set the cursor to be 'No-entry'
                    wx.SetCursor(wx.StockCursor(wx.CURSOR_NO_ENTRY))
                    self._setCursor = True
                else:
                    self._nHoveringOverTabIndex = tabIdx
                    if self._setCursor:
                        wx.SetCursor(wx.StockCursor(wx.CURSOR_ARROW))
                        self._setCursor = False

                # Support for drag and drop
                if event.Dragging() and not (agwStyle & FNB_NODRAG):

                    self._isdragging = True
                    draginfo = FNBDragInfo(self, tabIdx)
                    drginfo = cPickle.dumps(draginfo)
                    dataobject = wx.CustomDataObject(wx.CustomDataFormat("FlatNotebook"))
                    dataobject.SetData(drginfo)
                    dragSource = FNBDropSource(self)
                    dragSource.SetData(dataobject)
                    dragSource.DoDragDrop(wx.Drag_DefaultMove)

            if self._nHoveringOverTabIndex != self._nHoveringOverLastTabIndex:
                self._nHoveringOverLastTabIndex = self._nHoveringOverTabIndex
                if self._nHoveringOverTabIndex >= 0:
                    bRedrawTabs = True

            bRedrawX = self._nXButtonStatus != xButtonStatus
            bRedrawRight = self._nRightButtonStatus != rightButtonStatus
            bRedrawLeft = self._nLeftButtonStatus != leftButtonStatus
            bRedrawTabX = self._nTabXButtonStatus != xTabButtonStatus
            bRedrawDropArrow = self._nArrowDownButtonStatus != dropDownButtonStatus

            render = self._mgr.GetRenderer(agwStyle)

            if (bRedrawX or bRedrawRight or bRedrawLeft or bRedrawTabX or bRedrawDropArrow or bRedrawTabs):

                dc = wx.ClientDC(self)

                if bRedrawX:

                    render.DrawX(self, dc)

                if bRedrawLeft:

                    render.DrawLeftArrow(self, dc)

                if bRedrawRight:

                    render.DrawRightArrow(self, dc)

                if bRedrawTabX or bRedrawTabs:

                    self.Refresh()

                if bRedrawDropArrow:

                    render.DrawDropDownArrow(self, dc)

        event.Skip()

[docs]    def GetLastVisibleTab(self):
        """ Returns the last visible tab in the tab area. """

        if self._nFrom < 0:
            return -1

        ii = 0

        for ii in xrange(self._nFrom, len(self._pagesInfoVec)):

            if self._pagesInfoVec[ii].GetPosition() == wx.Point(-1, -1):
                break

        return ii-1

[docs]    def GetNumTabsCanScrollLeft(self):
        """ Returns the number of tabs than can be scrolled left. """

        if self._nFrom - 1 >= 0:
            return 1

        return 0

[docs]    def IsDefaultTabs(self):
        """ Returns whether a tab has a default style. """

        agwStyle = self.GetParent().GetAGWWindowStyleFlag()
        res = (agwStyle & FNB_VC71) or (agwStyle & FNB_FANCY_TABS) or (agwStyle & FNB_VC8)
        return not res

[docs]    def AdvanceSelection(self, forward=True):
        """
        Cycles through the tabs.

        :param `forward`: if ``True``, the selection is advanced in ascending order
         (to the right), otherwise the selection is advanced in descending order.

        :note: The call to this function generates the page changing events.
        """

        nSel = self.GetSelection()

        if nSel < 0:
            return

        nMax = self.GetPageCount() - 1

        if forward:
            newSelection = (nSel == nMax and [0] or [nSel + 1])[0]
        else:
            newSelection = (nSel == 0 and [nMax] or [nSel - 1])[0]

        if not self._pagesInfoVec[newSelection].GetEnabled():
            return

        self.FireEvent(newSelection)

[docs]    def OnMouseLeave(self, event):
        """
        Handles the ``wx.EVT_LEAVE_WINDOW`` event for L{PageContainer}.

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

        self._nLeftButtonStatus = FNB_BTN_NONE
        self._nXButtonStatus = FNB_BTN_NONE
        self._nRightButtonStatus = FNB_BTN_NONE
        self._nTabXButtonStatus = FNB_BTN_NONE
        self._nArrowDownButtonStatus = FNB_BTN_NONE
        self._nHoveringOverTabIndex = -1
        self._nHoveringOverLastTabIndex = -1

        self.Refresh()
        selection = self.GetSelection()

        if selection == -1:
            event.Skip()
            return

        if not self.IsTabVisible(selection):
            if selection == len(self._pagesInfoVec) - 1:
                if not self.CanFitToScreen(selection):
                    event.Skip()
                    return
            else:
                event.Skip()
                return

        agwStyle = self.GetParent().GetAGWWindowStyleFlag()
        render = self._mgr.GetRenderer(agwStyle)
        dc = wx.ClientDC(self)
        render.DrawTabX(self, dc, self._pagesInfoVec[selection].GetXRect(), selection, self._nTabXButtonStatus)
        if not agwStyle & FNB_RIBBON_TABS:
            render.DrawFocusRectangle(dc, self, self._pagesInfoVec[selection])

        event.Skip()

[docs]    def OnMouseEnterWindow(self, event):
        """
        Handles the ``wx.EVT_ENTER_WINDOW`` event for L{PageContainer}.

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

        self._nLeftButtonStatus = FNB_BTN_NONE
        self._nXButtonStatus = FNB_BTN_NONE
        self._nRightButtonStatus = FNB_BTN_NONE
        self._nLeftClickZone = FNB_BTN_NONE
        self._nArrowDownButtonStatus = FNB_BTN_NONE

        event.Skip()

[docs]    def ShowTabTooltip(self, tabIdx):
        """
        Shows a tab tooltip.

        :param `tabIdx`: an integer specifying the page index.
        """

        pWindow = self._pParent.GetPage(tabIdx)

        if pWindow:
            pToolTip = pWindow.GetToolTip()
            if pToolTip and pToolTip.GetWindow() == pWindow:
                self.SetToolTipString(pToolTip.GetTip())

[docs]    def SetPageImage(self, page, image):
        """
        Sets the image index for the given page.

        :param `page`: an integer specifying the page index;
        :param `image`: an index into the image list which was set with L{SetImageList}.
        """

        if page < len(self._pagesInfoVec):
            self._pagesInfoVec[page].SetImageIndex(image)
            self.Refresh()

[docs]    def GetPageImage(self, page):
        """
        Returns the image index associated to a page.

        :param `page`: an integer specifying the page index.
        """

        if page < len(self._pagesInfoVec):
            return self._pagesInfoVec[page].GetImageIndex()

        return -1

[docs]    def GetPageTextColour(self, page):
        """
        Returns the tab text colour if it has been set previously, or ``None`` otherwise.

        :param `page`: an integer specifying the page index.
        """

        if page < len(self._pagesInfoVec):
            return self._pagesInfoVec[page].GetPageTextColour()

        return None

[docs]    def SetPageTextColour(self, page, colour):
        """
        Sets the tab text colour individually.

        :param `page`: an integer specifying the page index;
        :param `colour`: a valid `wx.Colour` object or any typemap supported by wxWidgets/wxPython
         to generate a colour (i.e., a hex string, a colour name, a 3 or 4 integer tuple). You can
         pass ``None`` or `wx.NullColour` to return to the default page text colour.
        """

        if page < len(self._pagesInfoVec):
            self._pagesInfoVec[page].SetPageTextColour(colour)
            self.Refresh()

[docs]    def OnDropTarget(self, x, y, nTabPage, wnd_oldContainer):
        """
        Handles the drop action from a drag and drop operation.

        :param `x`: the x position of the drop action;
        :param `y`: the y position of the drop action;
        :param `nTabPage`: the index of the tab being dropped;
        :param `wnd_oldContainer`: the L{FlatNotebook} to which the dropped tab previously
         belonged to.
        """

        # Disable drag'n'drop for disabled tab
        if len(wnd_oldContainer._pagesInfoVec) > nTabPage and \
           not wnd_oldContainer._pagesInfoVec[nTabPage].GetEnabled():
            return wx.DragCancel

        self._isdragging = True
        oldContainer = wnd_oldContainer
        nIndex = -1

        where, nIndex = self.HitTest(wx.Point(x, y))

        oldNotebook = oldContainer.GetParent()
        newNotebook = self.GetParent()

        if oldNotebook == newNotebook:

            if nTabPage >= 0:

                if where == FNB_TAB:
                    self.MoveTabPage(nTabPage, nIndex)

                event = FlatNotebookEvent(wxEVT_FLATNOTEBOOK_PAGE_DROPPED, self.GetParent().GetId())
                event.SetSelection(nIndex)
                event.SetOldSelection(nTabPage)
                event.SetEventObject(self.GetParent())
                self.GetParent().GetEventHandler().ProcessEvent(event)

        elif self.GetParent().GetAGWWindowStyleFlag() & FNB_ALLOW_FOREIGN_DND:

            if wx.Platform in ["__WXMSW__", "__WXGTK__", "__WXMAC__"]:
                if nTabPage >= 0:

                    window = oldNotebook.GetPage(nTabPage)

                    if window:
                        where, nIndex = newNotebook._pages.HitTest(wx.Point(x, y))
                        caption = oldContainer.GetPageText(nTabPage)
                        imageindex = oldContainer.GetPageImage(nTabPage)
                        oldNotebook.RemovePage(nTabPage)
                        window.Reparent(newNotebook)

                        if imageindex >= 0:

                            bmp = oldNotebook.GetImageList().GetBitmap(imageindex)
                            newImageList = newNotebook.GetImageList()

                            if not newImageList:
                                xbmp, ybmp = bmp.GetWidth(), bmp.GetHeight()
                                newImageList = wx.ImageList(xbmp, ybmp)
                                imageindex = 0
                            else:
                                imageindex = newImageList.GetImageCount()

                            newImageList.Add(bmp)
                            newNotebook.SetImageList(newImageList)

                        newNotebook.InsertPage(nIndex, window, caption, True, imageindex)

                    event = FlatNotebookDragEvent(wxEVT_FLATNOTEBOOK_PAGE_DROPPED_FOREIGN, self.GetParent().GetId())
                    event.SetSelection(nIndex)
                    event.SetOldSelection(nTabPage)
                    event.SetNotebook(newNotebook)
                    event.SetOldNotebook(oldNotebook)
                    event.SetEventObject(self.GetParent())
                    self.GetParent().GetEventHandler().ProcessEvent(event)

        self._isdragging = False

        return wx.DragMove

[docs]    def MoveTabPage(self, nMove, nMoveTo):
        """
        Moves a tab inside the same L{FlatNotebook}.

        :param `nMove`: the start index of the moved tab;
        :param `nMoveTo`: the destination index of the moved tab.
        """

        if nMove == nMoveTo:
            return

        elif nMoveTo < len(self._pParent._windows):
            nMoveTo = nMoveTo + 1

        self._pParent.Freeze()

        # Remove the window from the main sizer
        nCurSel = self._pParent._pages.GetSelection()
        self._pParent._mainSizer.Detach(self._pParent._windows[nCurSel])
        self._pParent._windows[nCurSel].Hide()

        pWindow = self._pParent._windows[nMove]
        self._pParent._windows.pop(nMove)
        self._pParent._windows.insert(nMoveTo-1, pWindow)

        pgInfo = self._pagesInfoVec[nMove]

        self._pagesInfoVec.pop(nMove)
        self._pagesInfoVec.insert(nMoveTo - 1, pgInfo)

        # Add the page according to the style
        pSizer = self._pParent._mainSizer
        agwStyle = self.GetParent().GetAGWWindowStyleFlag()

        if agwStyle & FNB_BOTTOM:

            pSizer.Insert(0, pWindow, 1, wx.EXPAND)

        else:

            # We leave a space of 1 pixel around the window
            pSizer.Add(pWindow, 1, wx.EXPAND)

        pWindow.Show()

        pSizer.Layout()
        self._iActivePage = nMoveTo - 1
        self._iPreviousActivePage = -1
        self.DoSetSelection(self._iActivePage)
        self.Refresh()
        self._pParent.Thaw()

[docs]    def CanFitToScreen(self, page):
        """
        Returns wheter a tab can fit in the left space in the screen or not.

        :param `page`: an integer specifying the page index.
        """

        # Incase the from is greater than page,
        # we need to reset the self._nFrom, so in order
        # to force the caller to do so, we return false
        if self._nFrom > page:
            return False

        agwStyle = self.GetParent().GetAGWWindowStyleFlag()
        render = self._mgr.GetRenderer(agwStyle)

        vTabInfo = render.NumberTabsCanFit(self)

        if page - self._nFrom >= len(vTabInfo):
            return False

        return True

[docs]    def GetNumOfVisibleTabs(self):
        """ Returns the number of visible tabs. """

        count = 0
        for ii in xrange(self._nFrom, len(self._pagesInfoVec)):
            if self._pagesInfoVec[ii].GetPosition() == wx.Point(-1, -1):
                break
            count = count + 1

        return count

[docs]    def GetEnabled(self, page):
        """
        Returns whether a tab is enabled or not.

        :param `page`: an integer specifying the page index.
        """

        if page >= len(self._pagesInfoVec):
            return True # Seems strange, but this is the default

        return self._pagesInfoVec[page].GetEnabled()

[docs]    def EnableTab(self, page, enabled=True):
        """
        Enables or disables a tab.

        :param `page`: an integer specifying the page index;
        :param `enabled`: ``True`` to enable a tab, ``False`` to disable it.
        """

        if page >= len(self._pagesInfoVec):
            return

        self._pagesInfoVec[page].EnableTab(enabled)

[docs]    def GetSingleLineBorderColour(self):
        """ Returns the colour for the single line border. """

        if self.HasAGWFlag(FNB_FANCY_TABS):
            return self._colourFrom

        return wx.WHITE

[docs]    def HasAGWFlag(self, flag):
        """
        Returns whether a flag is present in the L{FlatNotebook} style.

        :param `flag`: one of the possible L{FlatNotebook} window styles.

        :see: L{FlatNotebook.SetAGWWindowStyleFlag} for a list of possible window
         style flags.
        """

        agwStyle = self.GetParent().GetAGWWindowStyleFlag()
        res = (agwStyle & flag and [True] or [False])[0]
        return res

[docs]    def ClearAGWFlag(self, flag):
        """
        Deletes a flag from the L{FlatNotebook} style.

        :param `flag`: one of the possible L{FlatNotebook} window styles.

        :see: L{FlatNotebook.SetAGWWindowStyleFlag} for a list of possible window
         style flags.
        """

        parent = self.GetParent()
        agwStyle = parent.GetAGWWindowStyleFlag()
        agwStyle &= ~flag
        parent.SetAGWWindowStyleFlag(agwStyle)

[docs]    def SetAGWWindowStyleFlag(self, agwStyle):
        """
        Sets the L{FlatNotebook} window style.

        :param `agwStyle`: the new L{FlatNotebook} window style.

        :see: The L{FlatNotebook.__init__} method for the `agwStyle` parameter description.
        """

        self.GetParent().SetAGWWindowStyleFlag(agwStyle)

[docs]    def GetAGWWindowStyleFlag(self):
        """
        Returns the L{FlatNotebook} window style.

        :see: The L{FlatNotebook.__init__} method for the `agwStyle` parameter description.
        """

        return self.GetParent().GetAGWWindowStyleFlag()

[docs]    def TabHasImage(self, tabIdx):
        """
        Returns whether a tab has an associated image index or not.

        :param `tabIdx`: an integer specifying the page index.
        """

        if self._ImageList:
            return self._pagesInfoVec[tabIdx].GetImageIndex() != -1

        return False

[docs]    def OnLeftDClick(self, event):
        """
        Handles the ``wx.EVT_LEFT_DCLICK`` event for L{PageContainer}.

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

        where, tabIdx = self.HitTest(event.GetPosition())

        if where == FNB_RIGHT_ARROW:
            self._nRightButtonStatus = FNB_BTN_PRESSED
            self.RotateRight()

        elif where == FNB_LEFT_ARROW:
            self._nLeftButtonStatus = FNB_BTN_PRESSED
            self.RotateLeft()

        elif self.HasAGWFlag(FNB_DCLICK_CLOSES_TABS):

            if where == FNB_TAB:
                self.DeletePage(tabIdx)

        else:

            event.Skip()

[docs]    def OnSetFocus(self, event):
        """
        Handles the ``wx.EVT_SET_FOCUS`` event for L{PageContainer}.

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

        if self._iActivePage < 0:
            event.Skip()
            return

        self.SetFocusedPage(self._iActivePage)

[docs]    def OnKillFocus(self, event):
        """
        Handles the ``wx.EVT_KILL_FOCUS`` event for L{PageContainer}.

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

        self.SetFocusedPage()

[docs]    def OnKeyDown(self, event):
        """
        Handles the ``wx.EVT_KEY_DOWN`` event for L{PageContainer}.

        :param `event`: a `wx.KeyEvent` event to be processed.

        :note: When the L{PageContainer} has the focus tabs can be changed with
         the left/right arrow keys.
        """

        key = event.GetKeyCode()
        if key == wx.WXK_LEFT:
            self.GetParent().AdvanceSelection(False)
            self.SetFocus()
        elif key == wx.WXK_RIGHT:
            self.GetParent().AdvanceSelection(True)
            self.SetFocus()
        elif key == wx.WXK_TAB and not event.ControlDown():
            flags = 0
            if not event.ShiftDown(): flags |= wx.NavigationKeyEvent.IsForward
            if event.CmdDown():       flags |= wx.NavigationKeyEvent.WinChange
            self.Navigate(flags)
        else:
            event.Skip()

[docs]    def SetFocusedPage(self, pageIndex=-1):
        """
        Sets/Unsets the focus on the appropriate page.

        :param `pageIndex`: an integer specifying the page index. If `pageIndex`
         is defaulted to -1, we have lost focus and no focus indicator is drawn.
        """

        for indx, page in enumerate(self._pagesInfoVec):
            if indx == pageIndex:
                page._hasFocus = True
            else:
                page._hasFocus = False

        self.Refresh()

[docs]    def PopupTabsMenu(self):
        """ Pops up the menu activated with the drop down arrow in the navigation area. """

        popupMenu = wx.Menu()

        for i in xrange(len(self._pagesInfoVec)):
            pi = self._pagesInfoVec[i]
            item = wx.MenuItem(popupMenu, i+1, pi.GetCaption(), pi.GetCaption(), wx.ITEM_NORMAL)
            self.Bind(wx.EVT_MENU, self.OnTabMenuSelection, item)

            # There is an alignment problem with wx2.6.3 & Menus so only use
            # images for versions above 2.6.3
            if wx.VERSION > (2, 6, 3, 0) and self.TabHasImage(i):
                item.SetBitmap(self.GetImageList().GetBitmap(pi.GetImageIndex()))

            popupMenu.AppendItem(item)
            item.Enable(pi.GetEnabled())

        self.PopupMenu(popupMenu)

[docs]    def OnTabMenuSelection(self, event):
        """
        Handles the ``wx.EVT_MENU`` event for L{PageContainer}.

        :param `event`: a `wx.MenuEvent` event to be processed.
        """

        selection = event.GetId() - 1
        self.FireEvent(selection)

[docs]    def FireEvent(self, selection):
        """
        Fires the ``EVT_FLATNOTEBOOK_PAGE_CHANGING`` and ``EVT_FLATNOTEBOOK_PAGE_CHANGED``
        events called from other methods (from menu selection or `Smart Tabbing`).

        This is an utility function.

        :param `selection`: the new selection inside L{FlatNotebook}.
        """

        if selection == self._iActivePage:
            # No events for the same selection
            return

        oldSelection = self._iActivePage

        event = FlatNotebookEvent(wxEVT_FLATNOTEBOOK_PAGE_CHANGING, self.GetParent().GetId())
        event.SetSelection(selection)
        event.SetOldSelection(oldSelection)
        event.SetEventObject(self.GetParent())

        if not self.GetParent().GetEventHandler().ProcessEvent(event) or event.IsAllowed():

            self.SetSelection(selection)

            # Fire a wxEVT_FLATNOTEBOOK_PAGE_CHANGED event
            event.SetEventType(wxEVT_FLATNOTEBOOK_PAGE_CHANGED)
            event.SetOldSelection(oldSelection)
            self.GetParent().GetEventHandler().ProcessEvent(event)
            if not self.HasAGWFlag(FNB_NO_TAB_FOCUS):
                self.SetFocus()

[docs]    def SetImageList(self, imglist):
        """
        Sets the image list for the L{PageContainer}.

        :param `imageList`: an instance of `wx.ImageList`.
        """

        self._ImageList = imglist

[docs]    def AssignImageList(self, imglist):
        """
        Assigns the image list for the L{PageContainer}.

        :param `imageList`: an instance of `wx.ImageList`.
        """

        self._ImageList = imglist

[docs]    def GetImageList(self):
        """ Returns the image list for the page control. """

        return self._ImageList

[docs]    def GetSelection(self):
        """ Returns the current selected page. """

        return self._iActivePage

[docs]    def GetPageCount(self):
        """ Returns the number of tabs in the L{FlatNotebook} control. """

        return len(self._pagesInfoVec)

[docs]    def GetPageText(self, page):
        """
        Returns the tab caption of the page.

        :param `page`: an integer specifying the page index.
        """

        if page < len(self._pagesInfoVec):
            return self._pagesInfoVec[page].GetCaption()
        else:
            return u''

[docs]    def SetPageText(self, page, text):
        """
        Sets the tab caption of the page.

        :param `page`: an integer specifying the page index;
        :param `text`: the new tab label.
        """

        if page < len(self._pagesInfoVec):
            self._pagesInfoVec[page].SetCaption(text)
            return True
        else:
            return False

[docs]    def DrawDragHint(self):
        """ Draws small arrow at the place that the tab will be placed. """

        # get the index of tab that will be replaced with the dragged tab
        pt = wx.GetMousePosition()
        client_pt = self.ScreenToClient(pt)
        where, tabIdx = self.HitTest(client_pt)
        self._mgr.GetRenderer(self.GetParent().GetAGWWindowStyleFlag()).DrawDragHint(self, tabIdx)

# ---------------------------------------------------------------------------- #
# Class FlatNotebookCompatible
# This class is more compatible with the wx.Notebook API.
# ---------------------------------------------------------------------------- #

[docs]class FlatNotebookCompatible(FlatNotebook):
    """
    This class is more compatible with the `wx.Notebook` API, especially regarding
    page changing events. Use the L{FlatNotebookCompatible.SetSelection} method if you wish to send page
    changing events, or L{FlatNotebookCompatible.ChangeSelection} otherwise.
    """

[docs]    def __init__(self, parent, id=wx.ID_ANY, pos=wx.DefaultPosition, size=wx.DefaultSize,
                 style=0, agwStyle=0, name="FlatNotebook"):
        """
        Default class constructor.

        :param `parent`: the L{FlatNotebook} parent;
        :param `id`: an identifier for the control: a value of -1 is taken to mean a default;
        :param `pos`: the control position. A value of (-1, -1) indicates a default position,
         chosen by either the windowing system or wxPython, depending on platform;
        :param `size`: the control size. A value of (-1, -1) indicates a default size,
         chosen by either the windowing system or wxPython, depending on platform;
        :param `style`: the underlying `wx.PyPanel` window style;
        :param `agwStyle`: the AGW-specific window style. This can be a combination of the
         following bits:

         ================================ =========== ==================================================
         Window Styles                    Hex Value   Description
         ================================ =========== ==================================================
         ``FNB_VC71``                             0x1 Use Visual Studio 2003 (VC7.1) style for tabs.
         ``FNB_FANCY_TABS``                       0x2 Use fancy style - square tabs filled with gradient colouring.
         ``FNB_TABS_BORDER_SIMPLE``               0x4 Draw thin border around the page.
         ``FNB_NO_X_BUTTON``                      0x8 Do not display the 'X' button.
         ``FNB_NO_NAV_BUTTONS``                  0x10 Do not display the right/left arrows.
         ``FNB_MOUSE_MIDDLE_CLOSES_TABS``        0x20 Use the mouse middle button for cloing tabs.
         ``FNB_BOTTOM``                          0x40 Place tabs at bottom - the default is to place them at top.
         ``FNB_NODRAG``                          0x80 Disable dragging of tabs.
         ``FNB_VC8``                            0x100 Use Visual Studio 2005 (VC8) style for tabs.
         ``FNB_X_ON_TAB``                       0x200 Place 'X' close button on the active tab.
         ``FNB_BACKGROUND_GRADIENT``            0x400 Use gradients to paint the tabs background.
         ``FNB_COLOURFUL_TABS``                 0x800 Use colourful tabs (VC8 style only).
         ``FNB_DCLICK_CLOSES_TABS``            0x1000 Style to close tab using double click.
         ``FNB_SMART_TABS``                    0x2000 Use `Smart Tabbing`, like ``Alt`` + ``Tab`` on Windows.
         ``FNB_DROPDOWN_TABS_LIST``            0x4000 Use a dropdown menu on the left in place of the arrows.
         ``FNB_ALLOW_FOREIGN_DND``             0x8000 Allows drag 'n' drop operations between different L{FlatNotebook}.
         ``FNB_HIDE_ON_SINGLE_TAB``           0x10000 Hides the Page Container when there is one or fewer tabs.
         ``FNB_DEFAULT_STYLE``                0x10020 L{FlatNotebook} default style.
         ``FNB_FF2``                          0x20000 Use Firefox 2 style for tabs.
         ``FNB_NO_TAB_FOCUS``                 0x40000 Does not allow tabs to have focus.
         ``FNB_RIBBON_TABS``                  0x80000 Use the Ribbon Tabs style.
         ``FNB_HIDE_TABS``                   0x100000 Hides the Page Container allowing only keyboard navigation
         ``FNB_NAV_BUTTONS_WHEN_NEEDED``     0x200000 Hides the navigation left/right arrows if all tabs fit
         ================================ =========== ==================================================

        :param `name`: the window name.
        """

        FlatNotebook.__init__(self, parent, id, pos, size, style, agwStyle, name)

[docs]    def SetSelection(self, page):
        """
        Sets the selection for the given page.

        :param `page`: an integer specifying the new selected page.

        :note: The call to this function **generates** the page changing events.
        """

        if page >= len(self._windows) or not self._windows:
            return

        # Support for disabed tabs
        if not self._pages.GetEnabled(page) and len(self._windows) > 1 and not self._bForceSelection:
            return

        self._pages.FireEvent(page)

[docs]    def ChangeSelection(self, page):
        """
        Sets the selection for the given page.

        :param `page`: an integer specifying the new selected page.

        :note: The call to this function **does not** generate the page changing events.
        """

        FlatNotebook.SetSelection(self, page)

Navigation

  • index
  • modules |
  • Home |
  • Gallery |
  • Contents»
  • Module code »
  • flatnotebook


floatspin

  • modules |
  • Home |
  • Gallery |
  • Contents»
  • Module code »
  • floatspin

Source code for floatspin

# --------------------------------------------------------------------------- #
# FLOATSPIN Control wxPython IMPLEMENTATION
# Python Code By:
#
# Andrea Gavana, @ 16 Nov 2005
# Latest Revision: 17 Aug 2011, 15.00 GMT
#
#
# TODO List/Caveats
#
# 1. Ay Idea?
#
# 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
# --------------------------------------------------------------------------- #

"""
L{FloatSpin} implements a floating point `wx.SpinCtrl`.

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

L{FloatSpin} implements a floating point `wx.SpinCtrl`. It is built using a custom
`wx.PyControl`, composed by a `wx.TextCtrl` and a `wx.SpinButton`. In order to
correctly handle floating points numbers without rounding errors or non-exact
floating point representations, L{FloatSpin} uses the great L{FixedPoint} class
from Tim Peters.

What you can do:

- Set the number of representative digits for your floating point numbers;
- Set the floating point format (``%f``, ``%F``, ``%e``, ``%E``, ``%g``, ``%G``);
- Set the increment of every ``EVT_FLOATSPIN`` event;
- Set minimum, maximum values for L{FloatSpin} as well as its range;
- Change font and colour for the underline `wx.TextCtrl`.

Usage
=====

Usage example::

    import wx
    import wx.lib.agw.floatspin as FS

    class MyFrame(wx.Frame):

        def __init__(self, parent):

            wx.Frame.__init__(self, parent, -1, "FloatSpin Demo")

            panel = wx.Panel(self)

            floatspin = FS.FloatSpin(panel, -1, pos=(50, 50), min_val=0, max_val=1,
                                     increment=0.01, value=0.1, agwStyle=FS.FS_LEFT)
            floatspin.SetFormat("%f")
            floatspin.SetDigits(2)

    # our normal wxApp-derived class, as usual

    app = wx.PySimpleApp()

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

    app.MainLoop()

Events
======

L{FloatSpin} catches 3 different types of events:

1) Spin events: events generated by spinning up/down the spinbutton;
2) Char events: playing with up/down arrows of the keyboard increase/decrease
   the value of L{FloatSpin};
3) Mouse wheel event: using the wheel will change the value of L{FloatSpin}.

In addition, there are some other functionalities:

- It remembers the initial value as a default value, call L{SetToDefaultValue}, or
  press ``Esc`` to return to it;
- ``Shift`` + arrow = 2 * increment        (or ``Shift`` + mouse wheel);
- ``Ctrl``  + arrow = 10 * increment       (or ``Ctrl`` + mouse wheel);
- ``Alt``   + arrow = 100 * increment      (or ``Alt`` + mouse wheel);
- Combinations of ``Shift``, ``Ctrl``, ``Alt`` increment the L{FloatSpin} value by the
  product of the factors;
- ``PgUp`` & ``PgDn`` = 10 * increment * the product of the ``Shift``, ``Ctrl``, ``Alt``
  factors;
- ``Space`` sets the control's value to it's last valid state.

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

This class supports the following window styles:

=============== =========== ==================================================
Window Styles   Hex Value   Description
=============== =========== ==================================================
``FS_READONLY``         0x1 Sets L{FloatSpin} as read-only control.
``FS_LEFT``             0x2 Horizontally align the underlying `wx.TextCtrl` on the left.
``FS_CENTRE``           0x4 Horizontally align the underlying `wx.TextCtrl` on center.
``FS_RIGHT``            0x8 Horizontally align the underlying `wx.TextCtrl` on the right.
=============== =========== ==================================================

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

This class processes the following events:

================= ==================================================
Event Name        Description
================= ==================================================
``EVT_FLOATSPIN`` Emitted when the user changes the value of L{FloatSpin}, either with the mouse or with the keyboard.
================= ==================================================

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

L{FloatSpin} control is distributed under the wxPython license.

Latest revision: Andrea Gavana @ 17 Aug 2011, 15.00 GMT

Version 0.9

Backward Incompatibilities
==========================

Modifications to allow `min_val` or `max_val` to be ``None`` done by:

James Bigler,
SCI Institute, University of Utah,
March 14, 2007

:note: Note that the changes I made will break backward compatibility,
 because I changed the contructor's parameters from `min` / `max` to
 `min_val` / `max_val` to be consistent with the other functions and to
 eliminate any potential confusion with the built in `min` and `max`
 functions.

You specify open ranges like this (you can equally do this in the
constructor)::

    SetRange(min_val=1, max_val=None)     # [1,  ]
    SetRange(min_val=None, max_val=0)     # [ , 0]

or no range::

    SetRange(min_val=None, max_val=None)  # [ , ]

"""

#----------------------------------------------------------------------
# Beginning Of FLOATSPIN wxPython Code
#----------------------------------------------------------------------

import wx
import locale
from math import ceil, floor

# Set The Styles For The Underline wx.TextCtrl
FS_READONLY = 1
""" Sets L{FloatSpin} as read-only control. """
FS_LEFT = 2
""" Horizontally align the underlying `wx.TextCtrl` on the left. """
FS_CENTRE = 4
""" Horizontally align the underlying `wx.TextCtrl` on center. """
FS_RIGHT = 8
""" Horizontally align the underlying `wx.TextCtrl` on the right. """

# Define The FloatSpin Event
wxEVT_FLOATSPIN = wx.NewEventType()

#-----------------------------------#
#        FloatSpinEvent
#-----------------------------------#

EVT_FLOATSPIN = wx.PyEventBinder(wxEVT_FLOATSPIN, 1)
""" Emitted when the user changes the value of L{FloatSpin}, either with the mouse or""" \
""" with the keyboard. """

# ---------------------------------------------------------------------------- #
# Class FloatSpinEvent
# ---------------------------------------------------------------------------- #

[docs]class FloatSpinEvent(wx.PyCommandEvent):
    """ This event will be sent when a ``EVT_FLOATSPIN`` event is mapped in the parent. """

[docs]    def __init__(self, eventType, eventId=1, nSel=-1, nOldSel=-1):
        """
        Default class constructor.

        :param `eventType`: the event type;
        :param `eventId`: the event identifier;
        :param `nSel`: the current selection;
        :param `nOldSel`: the old selection.
        """

        wx.PyCommandEvent.__init__(self, eventType, eventId)
        self._eventType = eventType

[docs]    def SetPosition(self, pos):
        """
        Sets event position.

        :param `pos`: an integer specyfing the event position.
        """

        self._position = pos

[docs]    def GetPosition(self):
        """ Returns event position. """

        return self._position

#----------------------------------------------------------------------------
# FloatTextCtrl
#----------------------------------------------------------------------------

[docs]class FloatTextCtrl(wx.TextCtrl):
    """
    A class which holds a `wx.TextCtrl`, one of the two building blocks
    of L{FloatSpin}.
    """

[docs]    def __init__(self, parent, id=wx.ID_ANY, value="", pos=wx.DefaultPosition,
                 size=wx.DefaultSize, style=wx.TE_NOHIDESEL | wx.TE_PROCESS_ENTER,
                 validator=wx.DefaultValidator,
                 name=wx.TextCtrlNameStr):
        """
        Default class constructor.
        Used internally. Do not call directly this class in your code!

        :param `parent`: the L{FloatTextCtrl} parent;
        :param `id`: an identifier for the control: a value of -1 is taken to mean a default;
        :param `value`: default text value;
        :param `pos`: the control position. A value of (-1, -1) indicates a default position,
         chosen by either the windowing system or wxPython, depending on platform;
        :param `size`: the control size. A value of (-1, -1) indicates a default size,
         chosen by either the windowing system or wxPython, depending on platform;
        :param `style`: the window style;
        :param `validator`: the window validator;
        :param `name`: the window name.

        """

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

        self._parent = parent
        self.Bind(wx.EVT_WINDOW_DESTROY, self.OnDestroy)
        self.Bind(wx.EVT_CHAR, self.OnChar)
        self.Bind(wx.EVT_KILL_FOCUS, self.OnKillFocus)

[docs]    def OnDestroy(self, event):
        """
        Handles the ``wx.EVT_WINDOW_DESTROY`` event for L{FloatTextCtrl}.

        :param `event`: a `wx.WindowDestroyEvent` event to be processed.

        :note: This method tries to correctly handle the control destruction under MSW.
        """

        if self._parent:
            self._parent._textctrl = None
            self._parent = None

[docs]    def OnChar(self, event):
        """
        Handles the ``wx.EVT_CHAR`` event for L{FloatTextCtrl}.

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

        if self._parent:
            self._parent.OnChar(event)

[docs]    def OnKillFocus(self, event):
        """
        Handles the ``wx.EVT_KILL_FOCUS`` event for L{FloatTextCtrl}.

        :param `event`: a `wx.FocusEvent` event to be processed.

        :note: This method synchronizes the `wx.SpinButton` and the `wx.TextCtrl`
         when focus is lost.
         """

        if self._parent:
            self._parent.SyncSpinToText(True)

        event.Skip()

#---------------------------------------------------------------------------- #
# FloatSpin
# This Is The Main Class Implementation
# ---------------------------------------------------------------------------- #

[docs]class FloatSpin(wx.PyControl):
    """
    L{FloatSpin} implements a floating point `wx.SpinCtrl`. It is built using a custom
    `wx.PyControl`, composed by a `wx.TextCtrl` and a `wx.SpinButton`. In order to
    correctly handle floating points numbers without rounding errors or non-exact
    floating point representations, L{FloatSpin} uses the great L{FixedPoint} class
    from Tim Peters.
    """

[docs]    def __init__(self, parent, id=wx.ID_ANY, pos=wx.DefaultPosition,
                 size=(95,-1), style=0, value=0.0, min_val=None, max_val=None,
                 increment=1.0, digits=-1, agwStyle=FS_LEFT,
                 name="FloatSpin"):
        """
        Default class constructor.

        :param `parent`: the L{FloatSpin} parent;
        :param `id`: an identifier for the control: a value of -1 is taken to mean a default;
        :param `pos`: the control position. A value of (-1, -1) indicates a default position,
         chosen by either the windowing system or wxPython, depending on platform;
        :param `size`: the control size. A value of (-1, -1) indicates a default size,
         chosen by either the windowing system or wxPython, depending on platform;
        :param `style`: the window style;
        :param `value`: is the current value for L{FloatSpin};
        :param `min_val`: the minimum value, ignored if ``None``;
        :param `max_val`: the maximum value, ignored if ``None``;
        :param `increment`: the increment for every L{FloatSpinEvent} event;
        :param `digits`: number of representative digits for your floating point numbers;
        :param `agwStyle`: one of the following bits:

         =============== =========== ==================================================
         Window Styles   Hex Value   Description
         =============== =========== ==================================================
         ``FS_READONLY``         0x1 Sets L{FloatSpin} as read-only control.
         ``FS_LEFT``             0x2 Horizontally align the underlying `wx.TextCtrl` on the left.
         ``FS_CENTRE``           0x4 Horizontally align the underlying `wx.TextCtrl` on center.
         ``FS_RIGHT``            0x8 Horizontally align the underlying `wx.TextCtrl` on the right.
         =============== =========== ==================================================

        :param `name`: the window name.

        """

        wx.PyControl.__init__(self, parent, id, pos, size, style|wx.NO_BORDER|
                              wx.NO_FULL_REPAINT_ON_RESIZE | wx.CLIP_CHILDREN,
                              wx.DefaultValidator, name)

        # Don't call SetRange here, because it will try to modify
        # self._value whose value doesn't exist yet.
        self.SetRangeDontClampValue(min_val, max_val)
        self._value = self.ClampValue(FixedPoint(str(value), 20))
        self._defaultvalue = self._value
        self._increment = FixedPoint(str(increment), 20)
        self._spinmodifier = FixedPoint(str(1.0), 20)
        self._digits = digits
        self._snapticks = False
        self._spinbutton = None
        self._textctrl = None
        self._spinctrl_bestsize = wx.Size(-999, -999)

        # start Philip Semanchuk addition
        # The textbox & spin button are drawn slightly differently
        # depending on the platform. The difference is most pronounced
        # under OS X.
        if "__WXMAC__" in wx.PlatformInfo:
            self._gap = 8
            self._spin_top = 3
            self._text_left = 4
            self._text_top = 4
        elif "__WXMSW__" in wx.PlatformInfo:
            self._gap = 1
            self._spin_top = 0
            self._text_left = 0
            self._text_top = 0
        else:
            # GTK
            self._gap = -1
            self._spin_top = 0
            self._text_left = 0
            self._text_top = 0
        # end Philip Semanchuk addition

        self.SetLabel(name)
        # start Philip Semanchuk change
        # Set the background color to match that of the parent. wxMac supports
        # transparency, and that gives the best results on that platform.
        # Other platforms ignore wx.ALPHA_TRANSPARENT.
        colour = parent.GetBackgroundColour()
        colour.Set(colour.Red(), colour.Green(), colour.Blue(),
                   wx.ALPHA_TRANSPARENT)
        self.SetBackgroundColour(colour)
        # end Philip Semanchuk change
        self.SetForegroundColour(parent.GetForegroundColour())

        width = size[0]
        height = size[1]
        best_size = self.DoGetBestSize()

        if width == -1:
            width = best_size.GetWidth()
        if height == -1:
            height = best_size.GetHeight()

        self._validkeycode = [43, 44, 45, 46, 69, 101, 127, 314]
        self._validkeycode.extend(range(48, 58))
        self._validkeycode.extend([wx.WXK_RETURN, wx.WXK_TAB, wx.WXK_BACK,
                                   wx.WXK_LEFT, wx.WXK_RIGHT])

        self._spinbutton = wx.SpinButton(self, wx.ID_ANY, wx.DefaultPosition,
                                         size=(-1, height),
                                         style=wx.SP_ARROW_KEYS | wx.SP_VERTICAL |
                                         wx.SP_WRAP)

        txtstyle = wx.TE_NOHIDESEL | wx.TE_PROCESS_ENTER

        if agwStyle & FS_RIGHT:
            txtstyle = txtstyle | wx.TE_RIGHT
        elif agwStyle & FS_CENTRE:
            txtstyle = txtstyle | wx.TE_CENTER

        if agwStyle & FS_READONLY:
            txtstyle = txtstyle | wx.TE_READONLY

        self._textctrl = FloatTextCtrl(self, wx.ID_ANY, str(self._value),
                                       wx.DefaultPosition,
                                       (width-self._spinbutton.GetSize().GetWidth(), height),
                                       txtstyle)

        # start Philip Semanchuk addition
        # Setting the textctrl's size in the ctor also sets its min size.
        # But the textctrl is entirely controlled by the parent floatspin
        # control and should accept whatever size its parent dictates, so
        # here we tell it to forget its min size.
        self._textctrl.SetMinSize(wx.DefaultSize)
        # Setting the spin buttons's size in the ctor also sets its min size.
        # Under OS X that results in a rendering artifact because spin buttons
        # are a little shorter than textboxes.
        # Setting the min size to the default allows OS X to draw the spin
        # button correctly. However, Windows and KDE take the call to
        # SetMinSize() as a cue to size the spin button taller than the
        # textbox, so we avoid the call there.
        if "__WXMAC__" in wx.PlatformInfo:
            self._spinbutton.SetMinSize(wx.DefaultSize)
        # end Philip Semanchuk addition

        self._mainsizer = wx.BoxSizer(wx.HORIZONTAL)
        # Ensure the spin button is shown, and the text widget takes
        # all remaining free space
        self._mainsizer.Add(self._textctrl, 1)
        self._mainsizer.Add(self._spinbutton, 0)
        self.SetSizer(self._mainsizer)
        self._mainsizer.Layout()

        self.SetFormat()
        self.SetDigits(digits)

        # set the value here without generating an event

        decimal = locale.localeconv()["decimal_point"]
        strs = ("%100." + str(self._digits) + self._textformat[1])%self._value
        strs = strs.replace(".", decimal)

        strs = strs.strip()
        strs = self.ReplaceDoubleZero(strs)

        self._textctrl.SetValue(strs)

        if not (agwStyle & FS_READONLY):
            self.Bind(wx.EVT_SPIN_UP, self.OnSpinUp)
            self.Bind(wx.EVT_SPIN_DOWN, self.OnSpinDown)
            self._spinbutton.Bind(wx.EVT_LEFT_DOWN, self.OnSpinMouseDown)

        self._textctrl.Bind(wx.EVT_TEXT_ENTER, self.OnTextEnter)
        self._textctrl.Bind(wx.EVT_MOUSEWHEEL, self.OnMouseWheel)
        self._spinbutton.Bind(wx.EVT_MOUSEWHEEL, self.OnMouseWheel)

        self.Bind(wx.EVT_SET_FOCUS, self.OnFocus)
        self.Bind(wx.EVT_KILL_FOCUS, self.OnKillFocus)
        self.Bind(wx.EVT_SIZE, self.OnSize)

        # start Philip Semanchuk move
        self.SetBestSize((width, height))
        # end Philip Semanchuk move

[docs]    def OnDestroy(self, event):
        """
        Handles the ``wx.EVT_WINDOW_DESTROY`` event for L{FloatSpin}.

        :param `event`: a `wx.WindowDestroyEvent` event to be processed.

        :note: This method tries to correctly handle the control destruction under MSW.
        """

        # Null This Since MSW Sends KILL_FOCUS On Deletion
        if self._textctrl:
            self._textctrl._parent = None
            self._textctrl.Destroy()
            self._textctrl = None

        self._spinbutton.Destroy()
        self._spinbutton = None

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

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

        if self._spinctrl_bestsize.x == -999:

            spin = wx.SpinCtrl(self, -1)
            self._spinctrl_bestsize = spin.GetBestSize()

            # oops something went wrong, set to reasonable value
            if self._spinctrl_bestsize.GetWidth() < 20:
                self._spinctrl_bestsize.SetWidth(95)
            if self._spinctrl_bestsize.GetHeight() < 10:
                self._spinctrl_bestsize.SetHeight(22)

            spin.Destroy()

        return self._spinctrl_bestsize

[docs]    def DoSendEvent(self):
        """ Send the event to the parent. """

        event = wx.CommandEvent(wx.wxEVT_COMMAND_SPINCTRL_UPDATED, self.GetId())
        event.SetEventObject(self)
        event.SetInt(int(self._value + 0.5))

        if self._textctrl:
            event.SetString(self._textctrl.GetValue())

        self.GetEventHandler().ProcessEvent(event)

        eventOut = FloatSpinEvent(wxEVT_FLOATSPIN, self.GetId())
        eventOut.SetPosition(int(self._value + 0.5))
        eventOut.SetEventObject(self)
        self.GetEventHandler().ProcessEvent(eventOut)

[docs]    def OnSpinMouseDown(self, event):
        """
        Handles the ``wx.EVT_LEFT_DOWN`` event for L{FloatSpin}.

        :param `event`: a `wx.MouseEvent` event to be processed.

        :note: This method works on the underlying `wx.SpinButton`.
        """

        modifier = FixedPoint(str(1.0), 20)
        if event.ShiftDown():
            modifier = modifier*2.0
        if event.ControlDown():
            modifier = modifier*10.0
        if event.AltDown():
            modifier = modifier*100.0

        self._spinmodifier = modifier

        event.Skip()

[docs]    def OnSpinUp(self, event):
        """
        Handles the ``wx.EVT_SPIN_UP`` event for L{FloatSpin}.

        :param `event`: a `wx.SpinEvent` event to be processed.
        """

        if self._textctrl and self._textctrl.IsModified():
            self.SyncSpinToText(False)

        if self.InRange(self._value + self._increment*self._spinmodifier):

            self._value = self._value + self._increment*self._spinmodifier
            self.SetValue(self._value)
            self.DoSendEvent()

[docs]    def OnSpinDown(self, event):
        """
        Handles the ``wx.EVT_SPIN_DOWN`` event for L{FloatSpin}.

        :param `event`: a `wx.SpinEvent` event to be processed.
        """

        if self._textctrl and self._textctrl.IsModified():
            self.SyncSpinToText(False)

        if self.InRange(self._value - self._increment*self._spinmodifier):

            self._value = self._value - self._increment*self._spinmodifier
            self.SetValue(self._value)
            self.DoSendEvent()

[docs]    def OnTextEnter(self, event):
        """
        Handles the ``wx.EVT_TEXT_ENTER`` event for L{FloatSpin}.

        :param `event`: a `wx.KeyEvent` event to be processed.

        :note: This method works on the underlying `wx.TextCtrl`.
        """

        self.SyncSpinToText(True)
        event.Skip()

[docs]    def OnChar(self, event):
        """
        Handles the ``wx.EVT_CHAR`` event for L{FloatSpin}.

        :param `event`: a `wx.KeyEvent` event to be processed.

        :note: This method works on the underlying `wx.TextCtrl`.
        """

        modifier = FixedPoint(str(1.0), 20)
        if event.ShiftDown():
            modifier = modifier*2.0
        if event.ControlDown():
            modifier = modifier*10.0
        if event.AltDown():
            modifier = modifier*100.0

        keycode = event.GetKeyCode()

        if keycode == wx.WXK_UP:

            if self._textctrl and self._textctrl.IsModified():
                self.SyncSpinToText(False)

            self.SetValue(self._value + self._increment*modifier)
            self.DoSendEvent()

        elif keycode == wx.WXK_DOWN:

            if self._textctrl and self._textctrl.IsModified():
                self.SyncSpinToText(False)

            self.SetValue(self._value - self._increment*modifier)
            self.DoSendEvent()

        elif keycode == wx.WXK_PRIOR:

            if self._textctrl and self._textctrl.IsModified():
                self.SyncSpinToText(False)

            self.SetValue(self._value + 10.0*self._increment*modifier)
            self.DoSendEvent()

        elif keycode == wx.WXK_NEXT:

            if self._textctrl and self._textctrl.IsModified():
                self.SyncSpinToText(False)

            self.SetValue(self._value - 10.0*self._increment*modifier)
            self.DoSendEvent()

        elif keycode == wx.WXK_SPACE:

            self.SetValue(self._value)
            event.Skip(False)

        elif keycode == wx.WXK_ESCAPE:

            self.SetToDefaultValue()
            self.DoSendEvent()

        elif keycode == wx.WXK_TAB:

            new_event = wx.NavigationKeyEvent()
            new_event.SetEventObject(self.GetParent())
            new_event.SetDirection(not event.ShiftDown())
            # CTRL-TAB changes the (parent) window, i.e. switch notebook page
            new_event.SetWindowChange(event.ControlDown())
            new_event.SetCurrentFocus(self)
            self.GetParent().GetEventHandler().ProcessEvent(new_event)

        else:
            if keycode not in self._validkeycode:
                return

            event.Skip()

[docs]    def OnMouseWheel(self, event):
        """
        Handles the ``wx.EVT_MOUSEWHEEL`` event for L{FloatSpin}.

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

        modifier = FixedPoint(str(1.0), 20)
        if event.ShiftDown():
            modifier = modifier*2.0
        if event.ControlDown():
            modifier = modifier*10.0
        if event.AltDown():
            modifier = modifier*100.0

        if self._textctrl and self._textctrl.IsModified():
            self.SyncSpinToText(False)

        if event.GetWheelRotation() > 0:
            self.SetValue(self._value + self._increment*modifier)
            self.DoSendEvent()

        else:

            self.SetValue(self._value - self._increment*modifier)
            self.DoSendEvent()

[docs]    def OnSize(self, event):
        """
        Handles the ``wx.EVT_SIZE`` event for L{FloatSpin}.

        :param `event`: a `wx.SizeEvent` event to be processed.

        :note: This method resizes the text control and reposition the spin button when
         resized.
        """
        # start Philip Semanchuk addition
        event_width = event.GetSize().width

        self._textctrl.SetPosition((self._text_left, self._text_top))

        text_width, text_height = self._textctrl.GetSizeTuple()

        spin_width, _ = self._spinbutton.GetSizeTuple()

        text_width = event_width - (spin_width + self._gap + self._text_left)

        self._textctrl.SetSize(wx.Size(text_width, text_height))

        # The spin button is always snug against the right edge of the
        # control.
        self._spinbutton.SetPosition((event_width - spin_width, self._spin_top))

        event.Skip()
        # end Philip Semanchuk addition

[docs]    def ReplaceDoubleZero(self, strs):
        """
        Replaces the (somewhat) python ugly `+e000` with `+e00`.

        :param `strs`: a string (possibly) containing a `+e00` substring.
        """

        if self._textformat not in ["%g", "%e", "%E", "%G"]:
            return strs

        if strs.find("e+00") >= 0:
            strs = strs.replace("e+00", "e+0")
        elif strs.find("e-00") >= 0:
            strs = strs.replace("e-00", "e-0")
        elif strs.find("E+00") >= 0:
            strs = strs.replace("E+00", "E+0")
        elif strs.find("E-00") >= 0:
            strs = strs.replace("E-00", "E-0")

        return strs

[docs]    def SetValue(self, value):
        """
        Sets the L{FloatSpin} value.

        :param `value`: the new value.
        """
        if not self._textctrl or not self.InRange(value):
            return

        if self._snapticks and self._increment != 0.0:

            finite, snap_value = self.IsFinite(value)

            if not finite: # FIXME What To Do About A Failure?

                if (snap_value - floor(snap_value) < ceil(snap_value) - snap_value):
                    value = self._defaultvalue + floor(snap_value)*self._increment
                else:
                    value = self._defaultvalue + ceil(snap_value)*self._increment

        decimal = locale.localeconv()["decimal_point"]
        strs = ("%100." + str(self._digits) + self._textformat[1])%value
        strs = strs.replace(".", decimal)
        strs = strs.strip()
        strs = self.ReplaceDoubleZero(strs)

        if value != self._value or strs != self._textctrl.GetValue():

            self._textctrl.SetValue(strs)
            self._textctrl.DiscardEdits()
            self._value = value

[docs]    def GetValue(self):
        """ Returns the L{FloatSpin} value. """

        return float(self._value)

[docs]    def SetRangeDontClampValue(self, min_val, max_val):
        """
        Sets the allowed range.

        :param `min_val`: the minimum value for L{FloatSpin}. If it is ``None`` it is
         ignored;
        :param `max_val`: the maximum value for L{FloatSpin}. If it is ``None`` it is
         ignored.

        :note: This method doesn't modify the current value.
        """

        if (min_val != None):
            self._min = FixedPoint(str(min_val), 20)
        else:
            self._min = None
        if (max_val != None):
            self._max = FixedPoint(str(max_val), 20)
        else:
            self._max = None

[docs]    def SetRange(self, min_val, max_val):
        """
        Sets the allowed range.

        :param `min_val`: the minimum value for L{FloatSpin}. If it is ``None`` it is
         ignored;
        :param `max_val`: the maximum value for L{FloatSpin}. If it is ``None`` it is
         ignored.

        :note: This method doesn't modify the current value.

        :note: You specify open ranges like this (you can equally do this in the
         constructor)::

             SetRange(min_val=1, max_val=None)
             SetRange(min_val=None, max_val=0)

         or no range::

             SetRange(min_val=None, max_val=None)

        """

        self.SetRangeDontClampValue(min_val, max_val)

        value = self.ClampValue(self._value)
        if (value != self._value):
            self.SetValue(value)

[docs]    def ClampValue(self, var):
        """
        Clamps `var` between `_min` and `_max` depending if the range has
        been specified.

        :param `var`: the value to be clamped.

        :return: A clamped copy of `var`.
        """

        if (self._min != None):
            if (var < self._min):
                var = self._min
                return var

        if (self._max != None):
            if (var > self._max):
                var = self._max

        return var

[docs]    def SetIncrement(self, increment):
        """
        Sets the increment for every ``EVT_FLOATSPIN`` event.

        :param `increment`: a floating point number specifying the L{FloatSpin} increment.
        """

        if increment < 1./10.0**self._digits:
            raise Exception("\nERROR: Increment Should Be Greater Or Equal To 1/(10**digits).")

        self._increment = FixedPoint(str(increment), 20)
        self.SetValue(self._value)

[docs]    def GetIncrement(self):
        """ Returns the increment for every ``EVT_FLOATSPIN`` event. """

        return self._increment

[docs]    def SetDigits(self, digits=-1):
        """
        Sets the number of digits to show.

        :param `digits`: the number of digits to show. If `digits` < 0, L{FloatSpin}
         tries to calculate the best number of digits based on input values passed
         in the constructor.
        """

        if digits < 0:
            incr = str(self._increment)
            if incr.find(".") < 0:
                digits = 0
            else:
                digits = len(incr[incr.find(".")+1:])

        self._digits = digits

        self.SetValue(self._value)

[docs]    def GetDigits(self):
        """ Returns the number of digits shown. """

        return self._digits

[docs]    def SetFormat(self, fmt="%f"):
        """
        Set the string format to use.

        :param `fmt`: the new string format to use. One of the following strings:

         ====== =================================
         Format Description
         ====== =================================
         'e'    Floating point exponential format (lowercase)
         'E'    Floating point exponential format (uppercase)
         'f'    Floating point decimal format
         'F'    Floating point decimal format
         'g'    Floating point format. Uses lowercase exponential format if exponent is less than -4 or not less than precision, decimal format otherwise
         'G'    Floating point format. Uses uppercase exponential format if exponent is less than -4 or not less than precision, decimal format otherwise
         ====== =================================

        """

        if fmt not in ["%f", "%g", "%e", "%E", "%F", "%G"]:
            raise Exception('\nERROR: Bad Float Number Format: ' + repr(fmt) + '. It Should Be ' \
                            'One Of "%f", "%g", "%e", "%E", "%F", "%G"')

        self._textformat = fmt

        if self._digits < 0:
            self.SetDigits()

        self.SetValue(self._value)

[docs]    def GetFormat(self):
        """
        Returns the string format in use.

        :see: L{SetFormat} for a list of valid string formats.
        """

        return self._textformat

[docs]    def SetDefaultValue(self, defaultvalue):
        """
        Sets the L{FloatSpin} default value.

        :param `defaultvalue`: a floating point value representing the new default
         value for L{FloatSpin}.
        """

        if self.InRange(defaultvalue):
            self._defaultvalue = FixedPoint(str(defaultvalue), 20)

[docs]    def GetDefaultValue(self):
        """ Returns the L{FloatSpin} default value. """

        return self._defaultvalue

[docs]    def IsDefaultValue(self):
        """ Returns whether the current value is the default value or not. """

        return self._value == self._defaultvalue

[docs]    def SetToDefaultValue(self):
        """ Sets L{FloatSpin} value to its default value. """

        self.SetValue(self._defaultvalue)

[docs]    def SetSnapToTicks(self, forceticks=True):
        """
        Force the value to always be divisible by the increment. Initially ``False``.

        :param `forceticks`: ``True`` to force the snap to ticks option, ``False`` otherwise.

        :note: This uses the default value as the basis, you will get strange results
         for very large differences between the current value and default value
         when the increment is very small.
        """

        if self._snapticks != forceticks:

            self._snapticks = forceticks
            self.SetValue(self._value)

[docs]    def GetSnapToTicks(self):
        """ Returns whether the snap to ticks option is active or not. """

        return self._snapticks

[docs]    def OnFocus(self, event):
        """
        Handles the ``wx.EVT_SET_FOCUS`` event for L{FloatSpin}.

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

        if self._textctrl:
            self._textctrl.SetFocus()

        event.Skip()

[docs]    def OnKillFocus(self, event):
        """
        Handles the ``wx.EVT_KILL_FOCUS`` event for L{FloatSpin}.

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

        self.SyncSpinToText(True)
        event.Skip()

[docs]    def SyncSpinToText(self, send_event=True, force_valid=True):
        """
        Synchronize the underlying `wx.TextCtrl` with `wx.SpinButton`.

        :param `send_event`: ``True`` to send a ``EVT_FLOATSPIN`` event, ``False``
         otherwise;
        :param `force_valid`: ``True`` to force a valid value (i.e. inside the
         provided range), ``False`` otherwise.
        """

        if not self._textctrl:
            return

        curr = self._textctrl.GetValue()
        curr = curr.strip()
        decimal = locale.localeconv()["decimal_point"]
        curr = curr.replace(decimal, ".")

        if curr:
            try:
                curro = float(curr)
                curr = FixedPoint(curr, 20)
            except:
                self.SetValue(self._value)
                return

            if force_valid or not self.HasRange() or self.InRange(curr):

                if force_valid and self.HasRange():

                    curr = self.ClampValue(curr)

                if self._value != curr:
                    self.SetValue(curr)

                    if send_event:
                        self.DoSendEvent()

        elif force_valid:

            # textctrl is out of sync, discard and reset
            self.SetValue(self.GetValue())

[docs]    def SetFont(self, font=None):
        """
        Sets the underlying `wx.TextCtrl` font.

        :param `font`: a valid instance of `wx.Font`.
        """

        if font is None:
            font = wx.SystemSettings_GetFont(wx.SYS_DEFAULT_GUI_FONT)

        if not self._textctrl:
            return False

        return self._textctrl.SetFont(font)

[docs]    def GetFont(self):
        """ Returns the underlying `wx.TextCtrl` font. """

        if not self._textctrl:
            return self.GetFont()

        return self._textctrl.GetFont()

[docs]    def GetMin(self):
        """
        Returns the minimum value for L{FloatSpin}. It can be a
        number or ``None`` if no minimum is present.
        """

        return self._min

[docs]    def GetMax(self):
        """
        Returns the maximum value for L{FloatSpin}. It can be a
        number or ``None`` if no minimum is present.
        """

        return self._max

[docs]    def HasRange(self):
        """ Returns whether L{FloatSpin} range has been set or not. """

        return (self._min != None) or (self._max != None)

[docs]    def InRange(self, value):
        """
        Returns whether a value is inside L{FloatSpin} range.

        :param `value`: the value to test.
        """

        if (not self.HasRange()):
            return True
        if (self._min != None):
            if (value < self._min):
                return False
        if (self._max != None):
            if (value > self._max):
                return False
        return True

[docs]    def GetTextCtrl(self):
        """ Returns the underlying `wx.TextCtrl`. """

        return self._textctrl

[docs]    def IsFinite(self, value):
        """
        Tries to determine if a value is finite or infinite/NaN.

        :param `value`: the value to test.
        """

        try:
            snap_value = (value - self._defaultvalue)/self._increment
            finite = True
        except:
            finite = False
            snap_value = None

        return finite, snap_value

# Class FixedPoint, version 0.0.4.
# Released to the public domain 28-Mar-2001,
# by Tim Peters (tim.one@home.com).

# Provided as-is; use at your own risk; no warranty; no promises; enjoy!

# 28-Mar-01 ver 0.0,4
#     Use repr() instead of str() inside __str__, because str(long) changed
#     since this was first written (used to produce trailing "L", doesn't
#     now).
#
# 09-May-99 ver 0,0,3
#     Repaired __sub__(FixedPoint, string); was blowing up.
#     Much more careful conversion of float (now best possible).
#     Implemented exact % and divmod.
#
# 14-Oct-98 ver 0,0,2
#     Added int, long, frac.  Beefed up docs.  Removed DECIMAL_POINT
#     and MINUS_SIGN globals to discourage bloating this class instead
#     of writing formatting wrapper classes (or subclasses)
#
# 11-Oct-98 ver 0,0,1
#     posted to c.l.py

__version__ = 0, 0, 4

# The default value for the number of decimal digits carried after the
# decimal point.  This only has effect at compile-time.
DEFAULT_PRECISION = 2

[docs]class FixedPoint(object):
    """
    FixedPoint objects support decimal arithmetic with a fixed number of
    digits (called the object's precision) after the decimal point.  The
    number of digits before the decimal point is variable & unbounded.

    The precision is user-settable on a per-object basis when a FixedPoint
    is constructed, and may vary across FixedPoint objects.  The precision
    may also be changed after construction via `FixedPoint.set_precision(p)`.
    Note that if the precision of a FixedPoint is reduced via L{FixedPoint.set_precision},
    information may be lost to rounding.

    Example::

        >>> x = FixedPoint("5.55")  # precision defaults to 2
        >>> print x
        5.55
        >>> x.set_precision(1)      # round to one fraction digit
        >>> print x
        5.6
        >>> print FixedPoint("5.55", 1)  # same thing setting to 1 in constructor
        5.6
        >>> repr(x) #  returns constructor string that reproduces object exactly
        "FixedPoint('5.6', 1)"
        >>>

    When L{FixedPoint} objects of different precision are combined via + - * /,
    the result is computed to the larger of the inputs' precisions, which also
    becomes the precision of the resulting L{FixedPoint} object. Example::

        >>> print FixedPoint("3.42") + FixedPoint("100.005", 3)
        103.425
        >>>

    When a L{FixedPoint} is combined with other numeric types (ints, floats,
    strings representing a number) via + - * /, then similarly the computation
    is carried out using -- and the result inherits -- the L{FixedPoint}'s
    precision. Example::

        >>> print FixedPoint(1) / 7
        0.14
        >>> print FixedPoint(1, 30) / 7
        0.142857142857142857142857142857
        >>>

    The string produced by `str(x)` (implictly invoked by `print`) always
    contains at least one digit before the decimal point, followed by a
    decimal point, followed by exactly `x.get_precision()` digits.  If `x` is
    negative, `str(x)[0] == "-"`.

    The L{FixedPoint} constructor can be passed an int, long, string, float,
    L{FixedPoint}, or any object convertible to a float via `float()` or to a
    long via `long()`. Passing a precision is optional; if specified, the
    precision must be a non-negative int. There is no inherent limit on
    the size of the precision, but if very very large you'll probably run
    out of memory.

    Note that conversion of floats to L{FixedPoint} can be surprising, and
    should be avoided whenever possible. Conversion from string is exact
    (up to final rounding to the requested precision), so is greatly
    preferred. Example::

        >>> print FixedPoint(1.1e30)
        1099999999999999993725589651456.00
        >>> print FixedPoint("1.1e30")
        1100000000000000000000000000000.00
        >>>

    """

    # the exact value is self.n / 10**self.p;
    # self.n is a long; self.p is an int

[docs]    def __init__(self, value=0, precision=DEFAULT_PRECISION):
        """
        Default class constructor.

        :param `value`: the initial value;
        :param `precision`: must be an int >= 0, and defaults to ``DEFAULT_PRECISION``.
        """

        self.n = self.p = 0
        self.set_precision(precision)
        p = self.p

        if isinstance(value, type("42.3e5")):
            n, exp = _string2exact(value)
            # exact value is n*10**exp = n*10**(exp+p)/10**p
            effective_exp = exp + p
            if effective_exp > 0:
                n = n * _tento(effective_exp)
            elif effective_exp < 0:
                n = _roundquotient(n, _tento(-effective_exp))
            self.n = n
            return

        if isinstance(value, type(42)) or isinstance(value, type(42L)):
            self.n = long(value) * _tento(p)
            return

        if isinstance(value, FixedPoint):
            temp = value.copy()
            temp.set_precision(p)
            self.n, self.p = temp.n, temp.p
            return

        if isinstance(value, type(42.0)):
            # XXX ignoring infinities and NaNs and overflows for now
            import math
            f, e = math.frexp(abs(value))
            assert f == 0 or 0.5 <= f < 1.0
            # |value| = f * 2**e exactly

            # Suck up CHUNK bits at a time; 28 is enough so that we suck
            # up all bits in 2 iterations for all known binary double-
            # precision formats, and small enough to fit in an int.
            CHUNK = 28
            top = 0L
            # invariant: |value| = (top + f) * 2**e exactly
            while f:
                f = math.ldexp(f, CHUNK)
                digit = int(f)
                assert digit >> CHUNK == 0
                top = (top << CHUNK) | digit
                f = f - digit
                assert 0.0 <= f < 1.0
                e = e - CHUNK

            # now |value| = top * 2**e exactly
            # want n such that n / 10**p = top * 2**e, or
            # n = top * 10**p * 2**e
            top = top * _tento(p)
            if e >= 0:
                n = top << e
            else:
                n = _roundquotient(top, 1L << -e)
            if value < 0:
                n = -n
            self.n = n
            return

        if isinstance(value, type(42-42j)):
            raise TypeError("can't convert complex to FixedPoint: " +
                            `value`)

        # can we coerce to a float?
        yes = 1
        try:
            asfloat = float(value)
        except:
            yes = 0
        if yes:
            self.__init__(asfloat, p)
            return

        # similarly for long
        yes = 1
        try:
            aslong = long(value)
        except:
            yes = 0
        if yes:
            self.__init__(aslong, p)
            return

        raise TypeError("can't convert to FixedPoint: " + `value`)

[docs]    def get_precision(self):
        """
        Return the precision of this L{FixedPoint}.

        :note: The precision is the number of decimal digits carried after
         the decimal point, and is an int >= 0.
        """

        return self.p

[docs]    def set_precision(self, precision=DEFAULT_PRECISION):
        """
        Change the precision carried by this L{FixedPoint} to `precision`.

        :param `precision`: must be an int >= 0, and defaults to
         ``DEFAULT_PRECISION``.

        :note: If `precision` is less than this FixedPoint's current precision,
         information may be lost to rounding.
        """

        try:
            p = int(precision)
        except:
            raise TypeError("precision not convertable to int: " +
                            `precision`)
        if p < 0:
            raise ValueError("precision must be >= 0: " + `precision`)

        if p > self.p:
            self.n = self.n * _tento(p - self.p)
        elif p < self.p:
            self.n = _roundquotient(self.n, _tento(self.p - p))
        self.p = p

    def __str__(self):

        n, p = self.n, self.p
        i, f = divmod(abs(n), _tento(p))
        if p:
            frac = repr(f)[:-1]
            frac = "0" * (p - len(frac)) + frac
        else:
            frac = ""
        return "-"[:n<0] + \
               repr(i)[:-1] + \
               "." + frac

    def __repr__(self):

        return "FixedPoint" + `(str(self), self.p)`

[docs]    def copy(self):
        """ Create a copy of the current L{FixedPoint}. """

        return _mkFP(self.n, self.p)

    __copy__ = __deepcopy__ = copy

    def __cmp__(self, other):

        if (other == None):
            return 1
        xn, yn, p = _norm(self, other)
        return cmp(xn, yn)

    def __hash__(self):
        # caution!  == values must have equal hashes, and a FixedPoint
        # is essentially a rational in unnormalized form.  There's
        # really no choice here but to normalize it, so hash is
        # potentially expensive.
        n, p = self.__reduce()

        # Obscurity: if the value is an exact integer, p will be 0 now,
        # so the hash expression reduces to hash(n).  So FixedPoints
        # that happen to be exact integers hash to the same things as
        # their int or long equivalents.  This is Good.  But if a
        # FixedPoint happens to have a value exactly representable as
        # a float, their hashes may differ.  This is a teensy bit Bad.
        return hash(n) ^ hash(p)

    def __nonzero__(self):
        return self.n != 0

    def __neg__(self):
        return _mkFP(-self.n, self.p)

    def __abs__(self):
        if self.n >= 0:
            return self.copy()
        else:
            return -self

    def __add__(self, other):
        n1, n2, p = _norm(self, other)
        # n1/10**p + n2/10**p = (n1+n2)/10**p
        return _mkFP(n1 + n2, p)

    __radd__ = __add__

    def __sub__(self, other):
        if not isinstance(other, FixedPoint):
            other = FixedPoint(other, self.p)
        return self.__add__(-other)

    def __rsub__(self, other):
        return (-self) + other

    def __mul__(self, other):
        n1, n2, p = _norm(self, other)
        # n1/10**p * n2/10**p = (n1*n2/10**p)/10**p
        return _mkFP(_roundquotient(n1 * n2, _tento(p)), p)

    __rmul__ = __mul__

    def __div__(self, other):
        n1, n2, p = _norm(self, other)
        if n2 == 0:
            raise ZeroDivisionError("FixedPoint division")
        if n2 < 0:
            n1, n2 = -n1, -n2
        # n1/10**p / (n2/10**p) = n1/n2 = (n1*10**p/n2)/10**p
        return _mkFP(_roundquotient(n1 * _tento(p), n2), p)

    def __rdiv__(self, other):
        n1, n2, p = _norm(self, other)
        return _mkFP(n2, p) / self

    def __divmod__(self, other):
        n1, n2, p = _norm(self, other)
        if n2 == 0:
            raise ZeroDivisionError("FixedPoint modulo")
        # floor((n1/10**p)/(n2*10**p)) = floor(n1/n2)
        q = n1 / n2
        # n1/10**p - q * n2/10**p = (n1 - q * n2)/10**p
        return q, _mkFP(n1 - q * n2, p)

    def __rdivmod__(self, other):
        n1, n2, p = _norm(self, other)
        return divmod(_mkFP(n2, p), self)

    def __mod__(self, other):
        return self.__divmod__(other)[1]

    def __rmod__(self, other):
        n1, n2, p = _norm(self, other)
        return _mkFP(n2, p).__mod__(self)

    # caution! float can lose precision
    def __float__(self):
        n, p = self.__reduce()
        return float(n) / float(_tento(p))

    # XXX should this round instead?
    # XXX note e.g. long(-1.9) == -1L and long(1.9) == 1L in Python
    # XXX note that __int__ inherits whatever __long__ does,
    # XXX and .frac() is affected too
    def __long__(self):
        answer = abs(self.n) / _tento(self.p)
        if self.n < 0:
            answer = -answer
        return answer

    def __int__(self):
        return int(self.__long__())

[docs]    def frac(self):
        """
        Returns fractional portion as a L{FixedPoint}.

        :note: In L{FixedPoint},

         this equality holds true::

                x = x.frac() + long(x)

        """
        return self - long(self)

    # return n, p s.t. self == n/10**p and n % 10 != 0

    def __reduce(self):
        n, p = self.n, self.p
        if n == 0:
            p = 0
        while p and n % 10 == 0:
            p = p - 1
            n = n / 10
        return n, p

# return 10L**n

[docs]def _tento(n, cache={}):
    try:
        return cache[n]
    except KeyError:
        answer = cache[n] = 10L ** n
        return answer

# return xn, yn, p s.t.
# p = max(x.p, y.p)
# x = xn / 10**p
# y = yn / 10**p
#
# x must be FixedPoint to begin with; if y is not FixedPoint,
# it inherits its precision from x.
#
# Note that this is called a lot, so default-arg tricks are helpful.

[docs]def _norm(x, y, isinstance=isinstance, FixedPoint=FixedPoint,
                _tento=_tento):
    assert isinstance(x, FixedPoint)
    if not isinstance(y, FixedPoint):
        y = FixedPoint(y, x.p)
    xn, yn = x.n, y.n
    xp, yp = x.p, y.p
    if xp > yp:
        yn = yn * _tento(xp - yp)
        p = xp
    elif xp < yp:
        xn = xn * _tento(yp - xp)
        p = yp
    else:
        p = xp  # same as yp
    return xn, yn, p

[docs]def _mkFP(n, p, FixedPoint=FixedPoint):
    f = FixedPoint()
    f.n = n
    f.p = p
    return f

# divide x by y, rounding to int via nearest-even
# y must be > 0
# XXX which rounding modes are useful?

[docs]def _roundquotient(x, y):
    assert y > 0
    n, leftover = divmod(x, y)
    c = cmp(leftover << 1, y)
    # c < 0 <-> leftover < y/2, etc
    if c > 0 or (c == 0 and (n & 1) == 1):
        n = n + 1
    return n

# crud for parsing strings

import re

# There's an optional sign at the start, and an optional exponent
# at the end.  The exponent has an optional sign and at least one
# digit.  In between, must have either at least one digit followed
# by an optional fraction, or a decimal point followed by at least
# one digit.  Yuck.

_parser = re.compile(r"""
    \s*
    (?P<sign>[-+])?
    (
        (?P<int>\d+) (\. (?P<frac>\d*))?
    |
        \. (?P<onlyfrac>\d+)
    )
    ([eE](?P<exp>[-+]? \d+))?
    \s* $
""", re.VERBOSE).match

del re

# return n, p s.t. float string value == n * 10**p exactly

[docs]def _string2exact(s):
    m = _parser(s)
    if m is None:
        raise ValueError("can't parse as number: " + `s`)

    exp = m.group('exp')
    if exp is None:
        exp = 0
    else:
        exp = int(exp)

    intpart = m.group('int')
    if intpart is None:
        intpart = "0"
        fracpart = m.group('onlyfrac')
    else:
        fracpart = m.group('frac')
        if fracpart is None or fracpart == "":
            fracpart = "0"
    assert intpart
    assert fracpart

    i, f = long(intpart), long(fracpart)
    nfrac = len(fracpart)
    i = i * _tento(nfrac) + f
    exp = exp - nfrac

    if m.group('sign') == "-":
        i = -i

    return i, exp

Navigation

  • index
  • modules |
  • Home |
  • Gallery |
  • Contents»
  • Module code »
  • floatspin


fmcustomizedlg

  • modules |
  • Home |
  • Gallery |
  • Contents»
  • Module code »
  • fmcustomizedlg

Source code for fmcustomizedlg

"""
This module contains a custom dialog class used to personalize the appearance of a
L{FlatMenu} on the fly, allowing also the user of your application to do the same.
"""

import wx
from UserDict import UserDict

from artmanager import ArtManager
from fmresources import *
from labelbook import LabelBook

_ = wx.GetTranslation

# ---------------------------------------------------------------------------- #
# Class OrderedDict
# ---------------------------------------------------------------------------- #

class OrderedDict(UserDict):
    """
    An ordered dictionary implementation.
    """

    def __init__(self, dict = None):
        self._keys = []
        UserDict.__init__(self, dict)

    def __delitem__(self, key):
        UserDict.__delitem__(self, key)
        self._keys.remove(key)

    def __setitem__(self, key, item):
        UserDict.__setitem__(self, key, item)
        if key not in self._keys: self._keys.append(key)

    def clear(self):
        UserDict.clear(self)
        self._keys = []

    def copy(self):
        dict = UserDict.copy(self)
        dict._keys = self._keys[:]
        return dict

    def items(self):
        return zip(self._keys, self.values())

    def keys(self):
        return self._keys

    def popitem(self):
        try:
            key = self._keys[-1]
        except IndexError:
            raise KeyError('dictionary is empty')

        val = self[key]
        del self[key]

        return (key, val)

    def setdefault(self, key, failobj = None):
        UserDict.setdefault(self, key, failobj)
        if key not in self._keys: self._keys.append(key)

    def update(self, dict):
        UserDict.update(self, dict)
        for key in dict.keys():
            if key not in self._keys: self._keys.append(key)

    def values(self):
        return map(self.get, self._keys)

# ---------------------------------------------------------------------------- #
# Class FMTitlePanel
# ---------------------------------------------------------------------------- #

[docs]class FMTitlePanel(wx.Panel):
    """
    Helper class to draw gradient shadings on the dialog.
    """

[docs]    def __init__(self, parent, title):
        """
        Default class constructor.

        :param `parent`: the L{FMTitlePanel} parent;
        :param `title`: the string to use as a dialog title.
        """

        wx.Panel.__init__(self, parent)
        self._title = title

        # Set the panel size
        dc = wx.MemoryDC()
        dc.SelectObject(wx.EmptyBitmap(1, 1))
        dc.SetFont(wx.SystemSettings_GetFont( wx.SYS_DEFAULT_GUI_FONT ))

        ww, hh = dc.GetTextExtent("Tp")
        dc.SelectObject(wx.NullBitmap)

        # Set minimum panel size
        if ww < 250:
            ww = 250

        self.SetSize(wx.Size(ww, hh + 10))

        self.Bind(wx.EVT_PAINT, self.OnPaint)
        self.Bind(wx.EVT_ERASE_BACKGROUND, self.OnEraseBackground)

[docs]    def OnEraseBackground(self, event):
        """
        Handles the ``wx.EVT_ERASE_BACKGROUND`` event for L{FMTitlePanel}.

        :param `event`: a `wx.EraseEvent` event to be processed.

        :note: This method is intentionally empty to reduce flicker.
        """

        pass

[docs]    def OnPaint(self, event):
        """
        Handles the ``wx.EVT_PAINT`` event for L{FMTitlePanel}.

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

        dc = wx.BufferedPaintDC(self)

        # Draw the background
        colour1 = wx.SystemSettings_GetColour(wx.SYS_COLOUR_3DFACE)
        colour2 = ArtManager.Get().LightColour(colour1, 70)
        ArtManager.Get().PaintStraightGradientBox(dc, self.GetClientRect(), colour1, colour2, False)

        # Draw the text
        font = wx.SystemSettings_GetFont(wx.SYS_DEFAULT_GUI_FONT)
        font.SetWeight(wx.BOLD)
        dc.SetFont(font)
        dc.SetTextForeground(wx.BLACK)
        dc.DrawText(self._title, 5, 5)

# ---------------------------------------------------------------------------- #
# Class FMCustomizeDlg
# ---------------------------------------------------------------------------- #

[docs]class FMCustomizeDlg(wx.Dialog):
    """
    Class used to customize the appearance of L{FlatMenu} and L{FlatMenuBar}.
    """

[docs]    def __init__(self, parent=None):
        """
        Default class constructor.

        :param `parent`: the L{FMCustomizeDlg} parent window.
        """

        self._book = None

        if not parent:
            wx.Dialog.__init__(self)
            return

        wx.Dialog.__init__(self, parent, wx.ID_ANY, _("Customize"), wx.DefaultPosition,
                           wx.DefaultSize, wx.DEFAULT_DIALOG_STYLE)

        self._visibleMenus = OrderedDict()
        self._hiddenMenus = OrderedDict()

        self.CreateDialog()
        self.ConnectEvents()
        self.GetSizer().Fit(self)
        self.GetSizer().SetSizeHints(self)
        self.GetSizer().Layout()
        self.Centre()

[docs]    def CreateDialog(self):
        """ Actually creates the dialog. """

        sz = wx.BoxSizer(wx.VERTICAL)
        self.SetSizer(sz)

        # Create the main book and add some pages into it
        style = INB_NO_RESIZE | INB_LEFT | INB_DRAW_SHADOW | INB_BORDER
        self._book = LabelBook(self, wx.ID_ANY, wx.DefaultPosition, wx.DefaultSize, style)
        sz.Add(self._book, 1, wx.EXPAND)

        self._book.SetColour(INB_TAB_AREA_BACKGROUND_COLOUR, ArtManager.Get().GetMenuFaceColour())

        colour = wx.SystemSettings_GetColour(wx.SYS_COLOUR_3DFACE)
        self._book.SetColour(INB_ACTIVE_TAB_COLOUR, colour)

        self.created = False
        self.Initialise()
        hsizer = wx.BoxSizer(wx.HORIZONTAL)

        # add a separator between the book & the buttons area
        hsizer.Add(wx.Button(self, wx.ID_OK, _("&Close")), 0, wx.EXPAND | wx.ALIGN_RIGHT)
        sz.Add(wx.StaticLine(self), 0, wx.EXPAND | wx.TOP | wx.BOTTOM, 3)
        sz.Add(hsizer, 0, wx.ALIGN_RIGHT | wx.ALL, 2)

[docs]    def Initialise(self):
        """ Initialzes the L{LabelBook} pages. """

        self._book.DeleteAllPages()
        self._book.AddPage(self.CreateMenusPage(), _("Menus"), True)
        self._book.AddPage(self.CreateOptionsPage(), _("Options"), False)

[docs]    def CloseDialog(self):
        """ Closes the dialog. """

        self.EndModal(wx.ID_OK)

[docs]    def ConnectEvents(self):
        """ Does nothing at the moment. """

        pass

[docs]    def CreateMenusPage(self):
        """ Creates the L{LabelBook} pages with L{FlatMenu} information. """

        menus = wx.Panel(self._book, wx.ID_ANY, wx.DefaultPosition, wx.Size(300, 300))
        sz = wx.BoxSizer(wx.VERTICAL)
        menus.SetSizer(sz)

        choices = []

        mb = self.GetParent()

        if not self.created:
            self.order = []

        # Add all the menu items that are currently visible to the list
        for i in xrange(len(mb._items)):

            dummy, lableOnly = ArtManager.Get().GetAccelIndex(mb._items[i].GetTitle())
            choices.append(lableOnly)

            # Add the menu to the visible menus map
            self._visibleMenus.update({lableOnly: mb._items[i].GetMenu()})
            if not self.created:
                self.order.append(lableOnly)

        # Add all hidden menus to the menu bar

        for key in self._hiddenMenus.keys():
            choices.append(key)

        if self.created:
            visible = OrderedDict()
            hidden = OrderedDict()
            for items in self.order:
                if items in self._visibleMenus:
                    visible[items] = self._visibleMenus[items]
                elif items in self._hiddenMenus:
                    hidden[items] = self._hiddenMenus[items]

            self._visibleMenus = visible
            self._hiddenMenus = hidden

        self._menuListId = wx.NewId()
        self._checkListMenus = wx.CheckListBox(menus, self._menuListId, pos=wx.DefaultPosition, size=wx.Size(250, 250),
                                               choices=self.order, style=wx.BORDER_SIMPLE)
        self._checkListMenus.Bind(wx.EVT_CHECKLISTBOX, self.OnMenuChecked)

        # check all visible items
        for indx, item in enumerate(self.order):
            if item in self._visibleMenus:
                self._checkListMenus.Check(indx)

        # Add title panel
        title = FMTitlePanel(menus, _("Select Menu To Add/Remove:"))
        sz.Add(title, 0, wx.EXPAND | wx.ALL, 2)
        sz.Add(self._checkListMenus, 1, wx.EXPAND | wx.TOP | wx.RIGHT | wx.LEFT, 2)

        self.created = True

        return menus

[docs]    def CreateShortcutsPage(self):
        """ Creates the L{LabelBook} shorcuts page. """

        shorcuts = wx.Panel(self._book, wx.ID_ANY, wx.DefaultPosition, wx.Size(300, 300))
        return shorcuts

[docs]    def CreateOptionsPage(self):
        """ Creates the L{LabelBook} option page which holds the L{FlatMenu} styles. """

        options = wx.Panel(self._book, wx.ID_ANY, wx.DefaultPosition, wx.Size(300, 300))

        # Create some options here
        vsizer = wx.BoxSizer(wx.VERTICAL)
        options.SetSizer(vsizer)

        #-----------------------------------------------------------
        # options page layout
        # - Menu Style: Default or 2007 (radio group)
        #
        # - Default Style Settings:     (static box)
        #     + Draw vertical gradient  (check box)
        #     + Draw border             (check box)
        #     + Drop toolbar shadow     (check box)
        #
        # - Colour Scheme                   (static box)
        #     + Menu bar background colour  (combo button)
        #-----------------------------------------------------------

        self._menuStyleID = wx.NewId()
        choices =  [_("Default Style"), _("Metallic")]
        self._menuStyle = wx.RadioBox(options, self._menuStyleID, _("Menu bar style"),
                                      wx.DefaultPosition, wx.DefaultSize, choices)

        # update the selection
        theme = ArtManager.Get().GetMenuTheme()

        if theme == Style2007:
            self._menuStyle.SetSelection(1)
        else:
            self._menuStyle.SetSelection(0)

        # connect event to the control
        self._menuStyle.Bind(wx.EVT_RADIOBOX, self.OnChangeStyle)

        vsizer.Add(self._menuStyle, 0, wx.EXPAND | wx.ALL, 5)

        self._sbStyle = wx.StaticBoxSizer(wx.StaticBox(options, -1, _("Default style settings")), wx.VERTICAL)
        self._drawVertGradID = wx.NewId()
        self._verticalGradient = wx.CheckBox(options, self._drawVertGradID, _("Draw vertical gradient"))
        self._verticalGradient.Bind(wx.EVT_CHECKBOX, self.OnChangeStyle)
        self._sbStyle.Add(self._verticalGradient, 0, wx.EXPAND | wx.ALL, 3)
        self._verticalGradient.SetValue(ArtManager.Get().GetMBVerticalGradient())

        self._drawBorderID = wx.NewId()
        self._drawBorder = wx.CheckBox(options, self._drawBorderID, _("Draw border around menu bar"))
        self._drawBorder.Bind(wx.EVT_CHECKBOX, self.OnChangeStyle)
        self._sbStyle.Add(self._drawBorder, 0, wx.EXPAND | wx.ALL, 3)
        self._drawBorder.SetValue(ArtManager.Get().GetMenuBarBorder())

        self._shadowUnderTBID = wx.NewId()
        self._shadowUnderTB =  wx.CheckBox(options, self._shadowUnderTBID, _("Toolbar float over menu bar"))
        self._shadowUnderTB.Bind(wx.EVT_CHECKBOX, self.OnChangeStyle)
        self._sbStyle.Add(self._shadowUnderTB, 0, wx.EXPAND | wx.ALL, 3)
        self._shadowUnderTB.SetValue(ArtManager.Get().GetRaiseToolbar())

        vsizer.Add(self._sbStyle, 0, wx.EXPAND | wx.ALL, 5)

        # Misc
        sb = wx.StaticBoxSizer(wx.StaticBox(options, -1, _("Colour Scheme")), wx.VERTICAL)
        self._colourID = wx.NewId()

        colourChoices = ArtManager.Get().GetColourSchemes()
        colourChoices.sort()

        self._colour = wx.ComboBox(options, self._colourID, ArtManager.Get().GetMenuBarColourScheme(), choices=colourChoices,
                                   style=wx.CB_DROPDOWN | wx.CB_READONLY)
        sb.Add(self._colour, 0, wx.EXPAND)
        vsizer.Add(sb, 0, wx.EXPAND | wx.ALL, 5)
        self._colour.Bind(wx.EVT_COMBOBOX, self.OnChangeStyle)

        # update the dialog by sending all possible events to us
        event = wx.CommandEvent(wx.wxEVT_COMMAND_RADIOBOX_SELECTED, self._menuStyleID)
        event.SetEventObject(self)
        event.SetInt(self._menuStyle.GetSelection())
        self._menuStyle.ProcessEvent(event)

        event.SetEventType(wx.wxEVT_COMMAND_CHECKBOX_CLICKED)
        event.SetId(self._drawVertGradID)
        event.SetInt(ArtManager.Get().GetMBVerticalGradient())
        self._verticalGradient.ProcessEvent(event)

        event.SetEventType(wx.wxEVT_COMMAND_CHECKBOX_CLICKED)
        event.SetId(self._shadowUnderTBID)
        event.SetInt(ArtManager.Get().GetRaiseToolbar())
        self._shadowUnderTB.ProcessEvent(event)

        event.SetEventType(wx.wxEVT_COMMAND_CHECKBOX_CLICKED)
        event.SetId(self._drawBorderID)
        event.SetInt(ArtManager.Get().GetMenuBarBorder())
        self._drawBorder.ProcessEvent(event)

        event.SetEventType(wx.wxEVT_COMMAND_COMBOBOX_SELECTED)
        event.SetId(self._colourID)
        self._colour.ProcessEvent(event)

        return options

[docs]    def OnMenuChecked(self, event):
        """
        Handles the ``wx.EVT_CHECKBOX`` event for L{FMCustomizeDlg}.

        :param `event`: a `wx.CommandEvent` event to be processed.

        :note: This method handles the L{FlatMenu} menus visibility.
        """

        id = event.GetInt()
        checked = self._checkListMenus.IsChecked(id)
        menuName = self._checkListMenus.GetString(id)
        menu = None
        mb = self.GetParent()

        if checked:

            # remove the item from the hidden map
            if self._hiddenMenus.has_key(menuName):
                menu = self._hiddenMenus.pop(menuName)

            # add it to the visible map
            if menu:
                self._visibleMenus.update({menuName: menu})

            indx = self._checkListMenus.GetItems().index(menuName)
            # update the menubar
            mb.Insert(indx, menu, menu._menuBarFullTitle)
            mb.Refresh()

        else:

            # remove the item from the visible items
            if self._visibleMenus.has_key(menuName):
                menu = self._visibleMenus.pop(menuName)

            # add it to the hidden map
            if menu:
                self._hiddenMenus.update({menuName: menu})

            # update the menubar
            pos = mb.FindMenu(menuName)
            if pos != wx.NOT_FOUND:
                mb.Remove(pos)

            mb.Refresh()

        if self.created:
            visible = OrderedDict()
            hidden = OrderedDict()
            for items in self.order:
                if items in self._visibleMenus:
                    visible[items] = self._visibleMenus[items]
                elif items in self._hiddenMenus:
                    hidden[items] = self._hiddenMenus[items]

            self._visibleMenus = visible
            self._hiddenMenus = hidden

[docs]    def OnChangeStyle(self, event):
        """
        Handles the ``wx.EVT_CHECKBOX`` event for L{FMCustomizeDlg}.

        :param `event`: a `wx.CommandEvent` event to be processed.

        :note: This method handles the L{FlatMenu} styles.
        """

        mb = self.GetParent()

        if event.GetId() == self._menuStyleID:

            if event.GetSelection() == 0:

                # Default style
                ArtManager.Get().SetMenuTheme(StyleXP)
                self._drawBorder.Enable()
                self._verticalGradient.Enable()
                mb.Refresh()

            else:

                ArtManager.Get().SetMenuTheme(Style2007)
                self._drawBorder.Enable(False)
                self._verticalGradient.Enable(False)
                mb.Refresh()

            return

        if event.GetId() == self._drawBorderID:

            ArtManager.Get().DrawMenuBarBorder(event.IsChecked())
            mb.Refresh()
            return

        if event.GetId() == self._drawVertGradID:

            ArtManager.Get().SetMBVerticalGradient(event.IsChecked())
            mb.Refresh()
            return

        if event.GetId() == self._colourID:

            selection = _("Default")
            sel = self._colour.GetSelection()
            if sel != wx.NOT_FOUND:
                # select new colour scheme
                selection = self._colour.GetStringSelection()

            ArtManager.Get().SetMenuBarColour(selection)
            mb.Refresh()
            return

        if event.GetId() == self._shadowUnderTBID:
            ArtManager.Get().SetRaiseToolbar(event.IsChecked())
            mb.Refresh()
            return

Navigation

  • index
  • modules |
  • Home |
  • Gallery |
  • Contents»
  • Module code »
  • fmcustomizedlg


foldpanelbar

  • modules |
  • Home |
  • Gallery |
  • Contents»
  • Module code »
  • foldpanelbar

Source code for foldpanelbar

# --------------------------------------------------------------------------- #
# FOLDPANELBAR wxPython IMPLEMENTATION
# Ported From Jorgen Bodde & Julian Smart (Extended Demo) C++ Code By:
#
# Andrea Gavana, @ 23 Mar 2005
# Latest Revision: 17 Sep 2011, 23.00 GMT
#
#
# TODO List
#
# All The C++ TODOs Are Still Alive. I Am Not Able to Read Jorges's Mind
# So I Don't Really Know What Will Be The New Features/Additions He Will
# Make On His Code. At The Moment They Are:
#
# 1. OnPaint Function In CaptionBar Class:
# TODO: Maybe First A Memory Dc Should Draw All, And Then Paint It On The
# Caption. This Way A Flickering Arrow During Resize Is Not Visible.
#
# 2. OnChar Function In CaptionBar Class:
# TODO: This Is Easy To Do But I Don't Have Any Useful Idea On Which Kind
# Of Features To Add. Does Anyone Have An Intelligent Idea?
#
# 3. AddFoldPanelWindow Function In FoldPanelBar Class:
# TODO: Take Old And New Heights, And If Difference, Reposition All The
# Lower Panels. This Is Because The User Can Add New wxWindow Controls
# Somewhere In Between When Other Panels Are Already Present.
# Don't Know What It Means. Probably Is My Poor English...
#
# 4. OnSizePanel Function In FoldPanelBar Class:
# TODO: A Smart Way To Check Wether The Old - New Width Of The
# Panel Changed, If So No Need To Resize The Fold Panel Items
#
#
# DONE List:
#
# 1. Implemented Styles Like FPB_SINGLE_FOLD and FPB_EXCLUSIVE_FOLD
# Thanks To E. A. Tacao For His Nice Suggestions.
#
# 2. Added Some Maquillage To FoldPanelBar: When The Mouse Enters The Icon
# Region, It Is Changed To wx.CURSOR_HAND.
#
#
# For The Original TODO List From Jorgen, Please Refer To:
# http://www.solidsteel.nl/jorg/components/foldpanel/wxFoldPanelBar.php#todo_list
#
#
#
# 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
# --------------------------------------------------------------------------- #

"""
L{FoldPanelBar} is a control that contains multiple panels, which can be expanded
or collapsed.

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

The L{FoldPanelBar} is a control that contains multiple panels (of type
L{FoldPanelItem}) that can be expanded or collapsed. The captionbar of
the L{FoldPanelBar} can be customized by setting it to a horizontal gradient
style, vertical gradient style, a single colour, a rectangle or filled
rectangle. The `FoldPanel` items can be collapsed in place or to the
bottom of the control. `wx.Window` derived controls can be added
dynamically, and separated by separator lines.

How does it work
----------------

The internals of the L{FoldPanelBar} is a list of L{FoldPanelItem} objects. Through
the reference of `FoldPanel` these panels can be controlled by adding new controls
to a FoldPanel or adding new FoldPanels to the L{FoldPanelBar}.

The L{CaptionBar} fires events to the parent (container of all panel items) when a
sub-panel needs resizing (either folding or expanding). The fold or expand process
is simply a resize of the panel so it looks like all controls on it are gone. All
controls are still child of the `FoldPanel` they are located on. If they don't
handle the event (and they won't) then the owner of the L{FoldPanelBar} gets the
events.

This is what you need to handle the controls. There isn't much to it just
a lot of calculations to see what panel belongs where. There are no sizers
involved in the panels, everything is purely x-y positioning.

What can it do and what not?
----------------------------

a) What it can do:

   * Run-time addition of panels (no deletion just yet);
   * Run time addition of controls to the panel (it will be resized accordingly);
   * Creating panels in collapsed mode or expanded mode;
   * Various modes of caption behaviour and filling to make it more appealing;
   * Panels can be folded and collapsed (or all of them) to allow more space.

b) What it cannot do:

   * Selection of a panel like in a listctrl;
   * Dragging and dropping the panels;
   * Re-ordering the panels (not yet).

Usage
=====

Usage example::

    import wx
    import wx.lib.agw.foldpanelbar as fpb

    class MyFrame(wx.Frame):

        def __init__(self, parent):

            wx.Frame.__init__(self, parent, -1, "FoldPanelBar Demo")

            text_ctrl = wx.TextCtrl(self, -1, size=(400, 100), style=wx.TE_MULTILINE)

            panel_bar = fpb.FoldPanelBar(self, -1, agwStyle=fpb.FPB_HORIZONTAL|fpb.FPB_DEFAULT_STYLE)

            fold_panel = panel_bar.AddFoldPanel("Thing")
            thing = wx.TextCtrl(fold_panel, -1, size=(400, -1), style=wx.TE_MULTILINE)

            panel_bar.AddFoldPanelWindow(fold_panel, thing)

            main_sizer = wx.BoxSizer(wx.HORIZONTAL)
            main_sizer.Add(text_ctrl, 1, wx.EXPAND)
            main_sizer.Add(panel_bar, 0, wx.EXPAND)
            self.SetSizer(main_sizer)

    # our normal wxApp-derived class, as usual

    app = wx.PySimpleApp()

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

    app.MainLoop()

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

L{FoldPanelBar} is supported on the following platforms:
  * Windows (Verified on Windows XP, 2000)
  * Linux/Unix (GTK2) (Thanks to Toni Brkic and Robin Dunn)
  * Mac OSX (Thanks to Robin Dunn for the L{CaptionBar} size patch)

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

This class supports the following window styles:

========================== =========== ==================================================
Window Styles              Hex Value   Description
========================== =========== ==================================================
``FPB_SINGLE_FOLD``                0x1 Single fold forces other panels to close when they are open, and only opens the current panel. This will allow the open panel to gain the full size left in the client area.
``FPB_COLLAPSE_TO_BOTTOM``         0x2 All panels are stacked to the bottom. When they are expanded again they show up at the top.
``FPB_EXCLUSIVE_FOLD``             0x4 ``FPB_SINGLE_FOLD`` style plus the panels will be stacked at the bottom.
``FPB_HORIZONTAL``                 0x8 L{FoldPanelBar} will be horizontal.
``FPB_VERTICAL``                  0x10 L{FoldPanelBar} will be vertical.
========================== =========== ==================================================

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

This class processes the following events:

================== ==================================================
Event Name         Description
================== ==================================================
``EVT_CAPTIONBAR`` The user has pressed the caption bar: L{FoldPanelBar} will either expand or collapse the underlying panel.
================== ==================================================

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

L{FoldPanelBar} is distributed under the wxPython license.

Latest Revision: Andrea Gavana @ 17 Sep 2011, 23.00 GMT

Version 0.5

"""

import wx

#----------------------------------------------------------------------
# Collapsed And Expanded Bitmap Images
# Created With img2py.py
#----------------------------------------------------------------------
from wx.lib.embeddedimage import PyEmbeddedImage

CollapsedIcon = PyEmbeddedImage(
    "iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAABHNCSVQICAgIfAhkiAAAADdJ"
    "REFUOI1jZGRiZqAEMFGke/Ab8P/f3/8D5wKY7YRcQRsXoNuKzxXUdwEu23CJU+wCxtG8wAAA"
    "mvUb+vltJD8AAAAASUVORK5CYII=")

ExpandedIcon = PyEmbeddedImage(
    "iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAABHNCSVQICAgIfAhkiAAAAEJJ"
    "REFUOI1jZGRiZqAEMFGke1AYwIIu8P/f3/+4FDMyMTNS3QUYBmCzBZ84bQIR3TZcttPOBci2"
    "4rOdKi5gHM0LDACevARXGc9htQAAAABJRU5ErkJggg==")

#----------------------------------------------------------------------
# FOLDPANELBAR Starts Here
#----------------------------------------------------------------------

# CAPTIONBAR STYLES
#
#- CAPTIONBAR_GRADIENT_V: Draws a vertical gradient from top to bottom
#- CAPTIONBAR_GRADIENT_H: Draws a horizontal gradient from left to right
#- CAPTIONBAR_SINGLE: Draws a single filled rectangle to draw the caption
#- CAPTIONBAR_RECTANGLE: Draws a single colour with a rectangle around the caption
#- CAPTIONBAR_FILLED_RECTANGLE: Draws a filled rectangle and a border around it

CAPTIONBAR_NOSTYLE            = 0
CAPTIONBAR_GRADIENT_V         = 1
CAPTIONBAR_GRADIENT_H         = 2
CAPTIONBAR_SINGLE             = 3
CAPTIONBAR_RECTANGLE          = 4
CAPTIONBAR_FILLED_RECTANGLE   = 5

FPB_EXTRA_X = 10
FPB_EXTRA_Y = 4

# pixels of the bmp to be aligned from the right filled with space
FPB_BMP_RIGHTSPACE = 2

# Now supported! Single fold forces
# other panels to close when they are open, and only opens the current panel.
# This will allow the open panel to gain the full size left in the client area
FPB_SINGLE_FOLD = 0x0001
""" Single fold forces other panels to close when they are open, and only opens""" \
""" the current panel. This will allow the open panel to gain the full size left""" \
""" in the client area."""

# All panels are stacked to the bottom. When they are expanded again they
# show up at the top
FPB_COLLAPSE_TO_BOTTOM = 0x0002
""" All panels are stacked to the bottom. When they are expanded again they show""" \
""" up at the top. """

# Now supported! Single fold plus panels
# will be stacked at the bottom
FPB_EXCLUSIVE_FOLD = 0x0004
""" ``FPB_SINGLE_FOLD`` style plus the panels will be stacked at the bottom. """

# Orientation Flag
FPB_HORIZONTAL = 0x0008
""" L{FoldPanelBar} will be horizontal. """
FPB_VERTICAL = 0x0010
""" L{FoldPanelBar} will be vertical. """

# FoldPanelItem default settings
FPB_ALIGN_LEFT = 0
FPB_ALIGN_WIDTH = 1

FPB_DEFAULT_LEFTSPACING = 5
FPB_DEFAULT_RIGHTSPACING = 10
FPB_DEFAULT_SPACING = 8

FPB_DEFAULT_LEFTLINESPACING = 2
FPB_DEFAULT_RIGHTLINESPACING = 2

# ------------------------------------------------------------------------------ #
# class CaptionBarStyle
# ------------------------------------------------------------------------------ #

[docs]class CaptionBarStyle(object):
    """
    This class encapsulates the styles you wish to set for the
    L{CaptionBar} (this is the part of the `FoldPanel` where the caption
    is displayed). It can either be applied at creation time be
    reapplied when styles need to be changed.

    At construction time, all styles are set to their default
    transparency.  This means none of the styles will be applied to
    the L{CaptionBar} in question, meaning it will be created using the
    default internals. When setting i.e the colour, font or panel
    style, these styles become active to be used.
    """

[docs]    def __init__(self):
        """ Default constructor for this class. """

        self.ResetDefaults()

[docs]    def ResetDefaults(self):
        """ Resets default L{CaptionBarStyle}. """
        self._firstColourUsed = False
        self._secondColourUsed = False
        self._textColourUsed = False
        self._captionFontUsed = False
        self._captionStyleUsed = False
        self._captionStyle = CAPTIONBAR_GRADIENT_V

    # ------- CaptionBar Font -------

[docs]    def SetCaptionFont(self, font):
        """
        Sets font for the caption bar.

        :param `font`: a valid `wx.Font` object.

        :note: If this is not set, the font property is undefined and will not be used.
         Use L{CaptionFontUsed} to check if this style is used.
        """

        self._captionFont = font
        self._captionFontUsed = True

[docs]    def CaptionFontUsed(self):
        """ Checks if the caption bar font is set. """

        return self._captionFontUsed

[docs]    def GetCaptionFont(self):
        """
        Returns the font for the caption bar.

        :note: Please be warned this will result in an assertion failure when
         this property is not previously set.

        :see: L{SetCaptionFont}, L{CaptionFontUsed}
        """

        return self._captionFont

    # ------- First Colour -------

[docs]    def SetFirstColour(self, colour):
        """
        Sets first colour for the caption bar.

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

        :note: If this is not set, the colour property is undefined and will not be used.
         Use L{FirstColourUsed} to check if this style is used.
        """

        self._firstColour = colour
        self._firstColourUsed = True

[docs]    def FirstColourUsed(self):
        """ Checks if the first colour of the caption bar is set."""

        return self._firstColourUsed

[docs]    def GetFirstColour(self):
        """
        Returns the first colour for the caption bar.

        :note: Please be warned this will result in an assertion failure when
         this property is not previously set.

        :see: L{SetFirstColour}, L{FirstColourUsed}
        """

        return self._firstColour

    # ------- Second Colour -------

[docs]    def SetSecondColour(self, colour):
        """
        Sets second colour for the caption bar.

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

        :note: If this is not set, the colour property is undefined and will not be used.
         Use L{SecondColourUsed} to check if this style is used.
        """

        self._secondColour = colour
        self._secondColourUsed = True

[docs]    def SecondColourUsed(self):
        """ Checks if the second colour of the caption bar is set."""

        return self._secondColourUsed

[docs]    def GetSecondColour(self):
        """
        Returns the second colour for the caption bar.

        :note: Please be warned this will result in an assertion failure when
         this property is not previously set.

        :see: L{SetSecondColour}, L{SecondColourUsed}
        """

        return self._secondColour

    # ------- Caption Text Colour -------

[docs]    def SetCaptionColour(self, colour):
        """
        Sets caption colour for the caption bar.

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

        :note: If this is not set, the colour property is undefined and will not be used.
         Use L{CaptionColourUsed} to check if this style is used.
        """

        self._textColour = colour
        self._textColourUsed = True

[docs]    def CaptionColourUsed(self):
        """ Checks if the caption colour of the caption bar is set."""

        return self._textColourUsed

[docs]    def GetCaptionColour(self):
        """
        Returns the caption colour for the caption bar.

        :note: Please be warned this will result in an assertion failure
         when this property is not previously set.

        :see: L{SetCaptionColour}, L{CaptionColourUsed}
        """

        return self._textColour

    # ------- CaptionStyle  -------

[docs]    def SetCaptionStyle(self, style):
        """
        Sets caption style for the caption bar.

        :param `style`: can be one of the following bits:

         =============================== ======= =============================
         Caption Style                    Value  Description
         =============================== ======= =============================
         ``CAPTIONBAR_GRADIENT_V``             1 Draws a vertical gradient from top to bottom
         ``CAPTIONBAR_GRADIENT_H``             2 Draws a horizontal gradient from left to right
         ``CAPTIONBAR_SINGLE``                 3 Draws a single filled rectangle to draw the caption
         ``CAPTIONBAR_RECTANGLE``              4 Draws a single colour with a rectangle around the caption
         ``CAPTIONBAR_FILLED_RECTANGLE``       5 Draws a filled rectangle and a border around it
         =============================== ======= =============================

        :note: If this is not set, the property is undefined and will not be used.
         Use L{CaptionStyleUsed} to check if this style is used.
        """

        self._captionStyle = style
        self._captionStyleUsed = True

[docs]    def CaptionStyleUsed(self):
        """ Checks if the caption style of the caption bar is set."""

        return self._captionStyleUsed

[docs]    def GetCaptionStyle(self):
        """
        Returns the caption style for the caption bar.

        :note: Please be warned this will result in an assertion failure
         when this property is not previously set.

        :see: L{SetCaptionStyle}, L{CaptionStyleUsed}
        """

        return self._captionStyle

#-----------------------------------#
#        CaptionBarEvent
#-----------------------------------#

wxEVT_CAPTIONBAR = wx.NewEventType()
EVT_CAPTIONBAR = wx.PyEventBinder(wxEVT_CAPTIONBAR, 0)
""" The user has pressed the caption bar: L{FoldPanelBar} will either expand or""" \
""" collapse the underlying panel. """

# Define Empty CaptionBar Style
EmptyCaptionBarStyle = CaptionBarStyle()

# ---------------------------------------------------------------------------- #
# class CaptionBarEvent
# ---------------------------------------------------------------------------- #

[docs]class CaptionBarEvent(wx.PyCommandEvent):
    """
    This event will be sent when a ``EVT_CAPTIONBAR`` is mapped in the parent.
    It is to notify the parent that the bar is now in collapsed or expanded
    state. The parent should re-arrange the associated windows accordingly
    """

[docs]    def __init__(self, evtType):
        """
        Default class constructor.

        :param `evtType`: the event type.
        """

        wx.PyCommandEvent.__init__(self, evtType)

[docs]    def GetFoldStatus(self):
        """
        Returns whether the bar is expanded or collapsed. ``True`` means
        expanded.
        """

        return not self._bar.IsCollapsed()

[docs]    def GetBar(self):
        """ Returns the selected L{CaptionBar}. """

        return self._bar

[docs]    def SetTag(self, tag):
        """
        Assigns a tag to the selected L{CaptionBar}.

        :param `tag`: an instance of L{FoldPanelBar}.
        """

        self._tag = tag

[docs]    def GetTag(self):
        """ Returns the tag assigned to the selected L{CaptionBar}. """

        return self._tag

[docs]    def SetBar(self, bar):
        """
        Sets the bar associated with this event.

        :param `bar`: an instance of L{CaptionBar}.

        :note: Should not be used by any other than the originator of the event.
        """

        self._bar = bar

# -------------------------------------------------------------------------------- #
# class CaptionBar
# -------------------------------------------------------------------------------- #

[docs]class CaptionBar(wx.Window):
    """
    This class is a graphical caption component that consists of a
    caption and a clickable arrow.

    The L{CaptionBar} fires an event ``EVT_CAPTIONBAR`` which is a
    L{CaptionBarEvent}. This event can be caught and the parent window
    can act upon the collapsed or expanded state of the bar (which is
    actually just the icon which changed). The parent panel can
    reduce size or expand again.
    """

[docs]    def __init__(self, parent, id, pos, size, caption="",
                 foldIcons=None, cbstyle=None,
                 rightIndent=FPB_BMP_RIGHTSPACE,
                 iconWidth=16, iconHeight=16, collapsed=False):
        """
        Default class constructor.

        :param `parent`: the L{CaptionBar} parent window;
        :param `id`: an identifier for the control: a value of -1 is taken to mean a default;
        :param `pos`: the control position. A value of (-1, -1) indicates a default position,
         chosen by either the windowing system or wxPython, depending on platform;
        :param `size`: the control size. A value of (-1, -1) indicates a default size,
         chosen by either the windowing system or wxPython, depending on platform;
        :param `caption`: the string to be displayed in L{CaptionBar};
        :param `foldIcons`: an instance of `wx.ImageList` containing the icons to display
         next to the caption text;
        :param `cbstyle`: the L{CaptionBar} window style. Must be an instance of
         L{CaptionBarStyle};
        :param `rightIndent`: number of pixels of the bmp to be aligned from the right filled
         with space;
        :param `iconWidth`: the L{CaptionBar} icon width;
        :param `iconHeight`: the L{CaptionBar} icon height;
        :param `collapsed`: ``True`` if the L{CaptionBar} should start in the collapsed state,
         ``False`` otherwise.
        """

        wx.Window.__init__(self, parent, wx.ID_ANY, pos=pos,
                           size=(20,20), style=wx.NO_BORDER)

        self._controlCreated = False
        self._collapsed = collapsed
        self.ApplyCaptionStyle(cbstyle, True)

        if foldIcons is None:
            foldIcons = wx.ImageList(16, 16)

            bmp = ExpandedIcon.GetBitmap()
            foldIcons.Add(bmp)
            bmp = CollapsedIcon.GetBitmap()
            foldIcons.Add(bmp)

        # set initial size
        if foldIcons:
            assert foldIcons.GetImageCount() > 1
            iconWidth, iconHeight = foldIcons.GetSize(0)

        self._caption = caption
        self._foldIcons = foldIcons
        self._style = cbstyle
        self._rightIndent = rightIndent
        self._iconWidth = iconWidth
        self._iconHeight = iconHeight
        self._oldSize = wx.Size(20,20)

        self._controlCreated = True

        self.Bind(wx.EVT_PAINT, self.OnPaint)
        self.Bind(wx.EVT_SIZE, self.OnSize)
        self.Bind(wx.EVT_MOUSE_EVENTS, self.OnMouseEvent)
        self.Bind(wx.EVT_CHAR, self.OnChar)

[docs]    def ApplyCaptionStyle(self, cbstyle=None, applyDefault=True):
        """
        Applies the style defined in `cbstyle` to the L{CaptionBar}.

        :param `cbstyle`: an instance of L{CaptionBarStyle};
        :param `applyDefault`: if ``True``, the colours used in the L{CaptionBarStyle}
         will be reset to their default values.
        """

        if cbstyle is None:
            cbstyle = EmptyCaptionBarStyle

        newstyle = cbstyle

        if applyDefault:

            # get first colour from style or make it default
            if not newstyle.FirstColourUsed():
                newstyle.SetFirstColour(wx.WHITE)

            # get second colour from style or make it default
            if not newstyle.SecondColourUsed():
                # make the second colour slightly darker then the background
                colour = self.GetParent().GetBackgroundColour()
                r, g, b = int(colour.Red()), int(colour.Green()), int(colour.Blue())
                colour = ((r >> 1) + 20, (g >> 1) + 20, (b >> 1) + 20)
                newstyle.SetSecondColour(wx.Colour(colour[0], colour[1], colour[2]))

            # get text colour
            if not newstyle.CaptionColourUsed():
                newstyle.SetCaptionColour(wx.BLACK)

            # get font colour
            if not newstyle.CaptionFontUsed():
                newstyle.SetCaptionFont(self.GetParent().GetFont())

            # apply caption style
            if not newstyle.CaptionStyleUsed():
                newstyle.SetCaptionStyle(CAPTIONBAR_GRADIENT_V)

        self._style = newstyle

[docs]    def SetCaptionStyle(self, cbstyle=None, applyDefault=True):
        """
        Sets L{CaptionBar} styles with L{CaptionBarStyle} class.

        :param `cbstyle`: an instance of L{CaptionBarStyle};
        :param `applyDefault`: if ``True``, the colours used in the L{CaptionBarStyle}
         will be reset to their default values.

        :note: All styles that are actually set, are applied. If you set `applyDefault`
         to ``True``, all other (not defined) styles will be set to default. If it is
         ``False``, the styles which are not set in the L{CaptionBarStyle} will be ignored.
        """

        if cbstyle is None:
            cbstyle = EmptyCaptionBarStyle

        self.ApplyCaptionStyle(cbstyle, applyDefault)
        self.Refresh()

[docs]    def GetCaptionStyle(self):
        """
        Returns the current style of the captionbar in a L{CaptionBarStyle} class.

        :note: This can be used to change and set back the changes.
        """

        return self._style

[docs]    def IsCollapsed(self):
        """ Returns wether the status of the bar is expanded or collapsed. """

        return self._collapsed

[docs]    def SetRightIndent(self, pixels):
        """
        Sets the amount of pixels on the right from which the bitmap
        is trailing.

        :param `pixels`: the number of pixels on the right from which the bitmap
         is trailing. If this is 0, it will be drawn all the way to the right,
         default is equal to ``FPB_BMP_RIGHTSPACE``. Assign this before
         assigning an image list to prevent a redraw.
        """

        assert pixels >= 0
        self._rightIndent = pixels
        if self._foldIcons:
            self.Refresh()

[docs]    def Collapse(self):
        """
        This sets the internal state/representation to collapsed.

        :note: This does not trigger a L{CaptionBarEvent} to be sent to the
         parent.
        """

        self._collapsed = True
        self.RedrawIconBitmap()

[docs]    def Expand(self):
        """
        This sets the internal state/representation to expanded.

        :note: This does not trigger a L{CaptionBarEvent} to be sent to the
         parent.
        """

        self._collapsed = False
        self.RedrawIconBitmap()

[docs]    def SetBoldFont(self):
        """ Sets the L{CaptionBar} font weight to bold."""

        self.GetFont().SetWeight(wx.BOLD)

[docs]    def SetNormalFont(self):
        """ Sets the L{CaptionBar} font weight to normal."""

        self.GetFont().SetWeight(wx.NORMAL)

[docs]    def IsVertical(self):
        """
        Returns wether the L{CaptionBar} has a default orientation or not.
        Default is vertical.
        """

        fld = self.GetParent().GetGrandParent()
        if isinstance(fld, FoldPanelBar):
            return self.GetParent().GetGrandParent().IsVertical()
        else:
            raise Exception("ERROR: Wrong Parent " + repr(fld))

[docs]    def OnPaint(self, event):
        """
        Handles the ``wx.EVT_PAINT`` event for L{CaptionBar}.

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

        if not self._controlCreated:
            event.Skip()
            return

        dc = wx.PaintDC(self)
        wndRect = self.GetRect()
        vertical = self.IsVertical()

        # TODO: Maybe first a memory DC should draw all, and then paint it on
        # the caption. This way a flickering arrow during resize is not visible

        self.FillCaptionBackground(dc)
        dc.SetFont(self._style.GetCaptionFont())
        dc.SetTextForeground(self._style.GetCaptionColour())

        if vertical:
            dc.DrawText(self._caption, 4, FPB_EXTRA_Y/2)
        else:
            dc.DrawRotatedText(self._caption, FPB_EXTRA_Y/2,
                               wndRect.GetBottom() - 4, 90)

        # draw small icon, either collapsed or expanded
        # based on the state of the bar. If we have any bmp's

        if self._foldIcons:

            index = self._collapsed

            if vertical:
                drw = wndRect.GetRight() - self._iconWidth - self._rightIndent
                self._foldIcons.Draw(index, dc, drw,
                                     (wndRect.GetHeight() - self._iconHeight)/2,
                                     wx.IMAGELIST_DRAW_TRANSPARENT)
            else:
                self._foldIcons.Draw(index, dc,
                                     (wndRect.GetWidth() - self._iconWidth)/2,
                                     self._rightIndent, wx.IMAGELIST_DRAW_TRANSPARENT)

##        event.Skip()

[docs]    def FillCaptionBackground(self, dc):
        """
        Fills the background of the caption with either a gradient or
        a solid colour.

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

        style = self._style.GetCaptionStyle()

        if style == CAPTIONBAR_GRADIENT_V:
            if self.IsVertical():
                self.DrawVerticalGradient(dc, self.GetRect())
            else:
                self.DrawHorizontalGradient(dc, self.GetRect())

        elif style == CAPTIONBAR_GRADIENT_H:
            if self.IsVertical():
                self.DrawHorizontalGradient(dc, self.GetRect())
            else:
                self.DrawVerticalGradient(dc, self.GetRect())

        elif style == CAPTIONBAR_SINGLE:
            self.DrawSingleColour(dc, self.GetRect())
        elif style == CAPTIONBAR_RECTANGLE or style == CAPTIONBAR_FILLED_RECTANGLE:
            self.DrawSingleRectangle(dc, self.GetRect())
        else:
            raise Exception("STYLE Error: Undefined Style Selected: " + repr(style))

[docs]    def OnMouseEvent(self, event):
        """
        Handles the ``wx.EVT_MOUSE_EVENTS`` event for L{CaptionBar}.

        :param `event`: a `wx.MouseEvent` event to be processed.

        :note: This method catches the mouse click-double click. If clicked on
         the arrow (single) or double on the caption we change state and an event
         must be fired to let this panel collapse or expand.
        """

        send_event = False
        vertical = self.IsVertical()

        if event.LeftDown() and self._foldIcons:

            pt = event.GetPosition()
            rect = self.GetRect()

            drw = (rect.GetWidth() - self._iconWidth - self._rightIndent)
            if vertical and pt.x > drw or not vertical and \
               pt.y < (self._iconHeight + self._rightIndent):
                send_event = True

        elif event.LeftDClick():
            self.SetCursor(wx.StockCursor(wx.CURSOR_ARROW))
            send_event = True

        elif event.Entering() and self._foldIcons:
            pt = event.GetPosition()
            rect = self.GetRect()

            drw = (rect.GetWidth() - self._iconWidth - self._rightIndent)
            if vertical and pt.x > drw or not vertical and \
               pt.y < (self._iconHeight + self._rightIndent):
                self.SetCursor(wx.StockCursor(wx.CURSOR_HAND))
            else:
                self.SetCursor(wx.StockCursor(wx.CURSOR_ARROW))

        elif event.Leaving():
            self.SetCursor(wx.StockCursor(wx.CURSOR_ARROW))

        elif event.Moving():
            pt = event.GetPosition()
            rect = self.GetRect()

            drw = (rect.GetWidth() - self._iconWidth - self._rightIndent)
            if vertical and pt.x > drw or not vertical and \
               pt.y < (self._iconHeight + self._rightIndent):
                self.SetCursor(wx.StockCursor(wx.CURSOR_HAND))
            else:
                self.SetCursor(wx.StockCursor(wx.CURSOR_ARROW))

        # send the collapse, expand event to the parent

        if send_event:
            event = CaptionBarEvent(wxEVT_CAPTIONBAR)
            event.SetId(self.GetId())
            event.SetEventObject(self)
            event.SetBar(self)
            self.GetEventHandler().ProcessEvent(event)

[docs]    def OnChar(self, event):
        """
        Handles the ``wx.EVT_CHAR`` event for L{CaptionBar}.

        :param `event`: a `wx.KeyEvent` event to be processed.

        :note: This method currently does nothing.
        """

        # TODO: Anything here?
        event.Skip()

[docs]    def DoGetBestSize(self):
        """
        Returns the best size for this panel, based upon the font
        assigned to this window, and the caption string.

        :note: Overridden from `wx.Window`.
        """

        if self.IsVertical():
            x, y = self.GetTextExtent(self._caption)
        else:
            y, x = self.GetTextExtent(self._caption)

        if x < self._iconWidth:
            x = self._iconWidth

        if y < self._iconHeight:
            y = self._iconHeight

        # TODO: The extra FPB_EXTRA_X constants should be adjustable as well

        return wx.Size(x + FPB_EXTRA_X, y + FPB_EXTRA_Y)

[docs]    def DrawVerticalGradient(self, dc, rect):
        """
        Gradient fill from colour 1 to colour 2 from top to bottom.

        :param `dc`: an instance of `wx.DC`;
        :param `rect`: the L{CaptionBar} client rectangle.
        """

        if  rect.height < 1 or rect.width < 1:
            return

        dc.SetPen(wx.TRANSPARENT_PEN)

        # calculate gradient coefficients
        col2 = self._style.GetSecondColour()
        col1 = self._style.GetFirstColour()

        r1, g1, b1 = int(col1.Red()), int(col1.Green()), int(col1.Blue())
        r2, g2, b2 = int(col2.Red()), int(col2.Green()), int(col2.Blue())

        flrect = float(rect.height)

        rstep = float((r2 - r1)) / flrect
        gstep = float((g2 - g1)) / flrect
        bstep = float((b2 - b1)) / flrect

        rf, gf, bf = 0, 0, 0

        for y in range(rect.y, rect.y + rect.height):
            currCol = (r1 + rf, g1 + gf, b1 + bf)

            dc.SetBrush(wx.Brush(currCol, wx.SOLID))
            dc.DrawRectangle(rect.x, rect.y + (y - rect.y), rect.width, rect.height)
            rf = rf + rstep
            gf = gf + gstep
            bf = bf + bstep

[docs]    def DrawHorizontalGradient(self, dc, rect):
        """
        Gradient fill from colour 1 to colour 2 from left to right.

        :param `dc`: an instance of `wx.DC`;
        :param `rect`: the L{CaptionBar} client rectangle.
        """

        if rect.height < 1 or rect.width < 1:
            return

        dc.SetPen(wx.TRANSPARENT_PEN)

        # calculate gradient coefficients
        col2 = self._style.GetSecondColour()
        col1 = self._style.GetFirstColour()

        r1, g1, b1 = int(col1.Red()), int(col1.Green()), int(col1.Blue())
        r2, g2, b2 = int(col2.Red()), int(col2.Green()), int(col2.Blue())

        flrect = float(rect.width)

        rstep = float((r2 - r1)) / flrect
        gstep = float((g2 - g1)) / flrect
        bstep = float((b2 - b1)) / flrect

        rf, gf, bf = 0, 0, 0

        for x in range(rect.x, rect.x + rect.width):
            currCol = (r1 + rf, g1 + gf, b1 + bf)

            dc.SetBrush(wx.Brush(currCol, wx.SOLID))
            dc.DrawRectangle(rect.x + (x - rect.x), rect.y, 1, rect.height)
            rf = rf + rstep
            gf = gf + gstep
            bf = bf + bstep

[docs]    def DrawSingleColour(self, dc, rect):
        """
        Single colour fill for L{CaptionBar}.

        :param `dc`: an instance of `wx.DC`;
        :param `rect`: the L{CaptionBar} client rectangle.
        """

        if rect.height < 1 or rect.width < 1:
            return

        dc.SetPen(wx.TRANSPARENT_PEN)

        # draw simple rectangle
        dc.SetBrush(wx.Brush(self._style.GetFirstColour(), wx.SOLID))
        dc.DrawRectangle(rect.x, rect.y, rect.width, rect.height)

[docs]    def DrawSingleRectangle(self, dc, rect):
        """
        Single rectangle for L{CaptionBar}.

        :param `dc`: an instance of `wx.DC`;
        :param `rect`: the L{CaptionBar} client rectangle.
        """

        if rect.height < 2 or rect.width < 1:
            return

        # single frame, set up internal fill colour

        if self._style.GetCaptionStyle() == CAPTIONBAR_RECTANGLE:
            colour = self.GetParent().GetBackgroundColour()
            br = wx.Brush(colour, wx.SOLID)
        else:
            colour = self._style.GetFirstColour()
            br = wx.Brush(colour, wx.SOLID)

        # setup the pen frame

        pen = wx.Pen(self._style.GetSecondColour())
        dc.SetPen(pen)
        dc.SetBrush(br)
        dc.DrawRectangle(rect.x, rect.y, rect.width, rect.height - 1)

        bgpen = wx.Pen(self.GetParent().GetBackgroundColour())
        dc.SetPen(bgpen)
        dc.DrawLine(rect.x, rect.y + rect.height - 1, rect.x + rect.width,
                    rect.y + rect.height - 1)

[docs]    def OnSize(self, event):
        """
        Handles the ``wx.EVT_SIZE`` event for L{CaptionBar}.

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

        if not self._controlCreated:
            event.Skip()
            return

        size = event.GetSize()

        if self._foldIcons:

            # What I am doing here is simply invalidating the part of the window
            # exposed. So when I make a rect with as width the newly exposed part,
            # and the x,y of the old window size origin, I don't need a bitmap
            # calculation in it, or do I ? The bitmap needs redrawing anyway.
            # Leave it like this until I figured it out.

            # set rect to redraw as old bitmap area which is entitled to redraw

            rect = wx.Rect(size.GetWidth() - self._iconWidth - self._rightIndent, 0,
                           self._iconWidth + self._rightIndent,
                           self._iconWidth + self._rightIndent)

            # adjust rectangle when more is slided so we need to redraw all
            # the old stuff but not all (ugly flickering)

            diffX = size.GetWidth() - self._oldSize.GetWidth()

            if diffX > 1:

                # adjust the rect with all the crap to redraw

                rect.SetWidth(rect.GetWidth() + diffX + 10)
                rect.SetX(rect.GetX() - diffX - 10)

            self.RefreshRect(rect)

        else:

            rect = self.GetRect()
            self.RefreshRect(rect)

        self._oldSize = size

[docs]    def RedrawIconBitmap(self):
        """ Redraws the icons (if they exists). """

        if self._foldIcons:

            # invalidate the bitmap area and force a redraw

            rect = self.GetRect()

            rect.SetX(rect.GetWidth() - self._iconWidth - self._rightIndent)
            rect.SetWidth(self._iconWidth + self._rightIndent)
            self.RefreshRect(rect)

# ---------------------------------------------------------------------------------- #
# class FoldPanelBar
# ---------------------------------------------------------------------------------- #

[docs]class FoldPanelBar(wx.Panel):
    """
    The L{FoldPanelBar} is a class which can maintain a list of
    collapsible panels. Once a panel is collapsed, only it's caption
    bar is visible to the user. This will provide more space for the
    other panels, or allow the user to close panels which are not used
    often to get the most out of the work area.

    This control is easy to use. Simply create it as a child for a
    panel or sash window, and populate panels with
    L{FoldPanelBar.AddFoldPanel}. Then use the L{FoldPanelBar.AddFoldPanelWindow} to add
    `wx.Window` derived controls to the current fold panel. Use
    L{FoldPanelBar.AddFoldPanelSeparator} to put separators between the groups of
    controls that need a visual separator to group them
    together. After all is constructed, the user can fold the panels
    by double clicking on the bar or single click on the arrow, which
    will indicate the collapsed or expanded state.
    """

[docs]    def __init__(self, parent, id=-1, pos=wx.DefaultPosition, size=wx.DefaultSize,
                 style=wx.TAB_TRAVERSAL|wx.NO_BORDER, agwStyle=0):
        """
        Default class constructor.

        :param `parent`: the L{FoldPanelBar} parent window;
        :param `id`: an identifier for the control: a value of -1 is taken to mean a default;
        :param `pos`: the control position. A value of (-1, -1) indicates a default position,
         chosen by either the windowing system or wxPython, depending on platform;
        :param `size`: the control size. A value of (-1, -1) indicates a default size,
         chosen by either the windowing system or wxPython, depending on platform;
        :param `style`: the underlying `wx.Panel` window style;
        :param `agwStyle`: the AGW-specific L{FoldPanelBar} window style. It can be one of the
         following bits:

         ========================== =========== ==================================================
         Window Styles              Hex Value   Description
         ========================== =========== ==================================================
         ``FPB_SINGLE_FOLD``                0x1 Single fold forces other panels to close when they are open, and only opens the current panel. This will allow the open panel to gain the full size left in the client area.
         ``FPB_COLLAPSE_TO_BOTTOM``         0x2 All panels are stacked to the bottom. When they are expanded again they show up at the top.
         ``FPB_EXCLUSIVE_FOLD``             0x4 ``FPB_SINGLE_FOLD`` style plus the panels will be stacked at the bottom.
         ``FPB_HORIZONTAL``                 0x4 L{FoldPanelBar} will be horizontal.
         ``FPB_VERTICAL``                   0x8 L{FoldPanelBar} will be vertical.
         ========================== =========== ==================================================
        """

        self._controlCreated = False

        # make sure there is any orientation
        if not agwStyle & (FPB_HORIZONTAL | FPB_VERTICAL):
            agwStyle = agwStyle | FPB_VERTICAL

        if agwStyle & FPB_HORIZONTAL:
            self._isVertical = False
        else:
            self._isVertical = True

        self._agwStyle = agwStyle

        # create the panel (duh!). This causes a size event, which we are going
        # to skip when we are not initialised

        wx.Panel.__init__(self, parent, id, pos, size, style)

        # the fold panel area

        self._foldPanel = wx.Panel(self, wx.ID_ANY, pos, size,
                                   wx.NO_BORDER | wx.TAB_TRAVERSAL)

        self._controlCreated = True
        self._panels = []

        self.Bind(EVT_CAPTIONBAR, self.OnPressCaption)
        self.Bind(wx.EVT_SIZE, self.OnSizePanel)

[docs]    def AddFoldPanel(self, caption="", collapsed=False, foldIcons=None, cbstyle=None):
        """
        Adds a fold panel to the list of panels.

        :param `caption`: the caption to be displayed in the associated L{CaptionBar};
        :param `collapsed`: if set to ``True``, the panel is collapsed initially;
        :param `foldIcons`: an instance of `wx.ImageList` containing the icons to display
         next to the caption text;
        :param `cbstyle`: an instance of L{CaptionBarStyle}.

        :note: The FoldPanel item which is returned, can be used as a reference to perform
         actions upon the fold panel like collapsing it, expanding it, or deleting it
         from the list. Use this foldpanel to add windows to it.

        :see: L{AddFoldPanelWindow} and L{AddFoldPanelSeparator} to see how to add
         items derived from `wx.Window` to the panels.
        """

        if cbstyle is None:
            cbstyle = EmptyCaptionBarStyle

        # create a fold panel item, which is first only the caption.
        # the user can now add a panel area which will be folded in
        # when pressed.

        if foldIcons is None:
            foldIcons = wx.ImageList(16, 16)

            bmp = ExpandedIcon.GetBitmap()
            foldIcons.Add(bmp)
            bmp = CollapsedIcon.GetBitmap()
            foldIcons.Add(bmp)

        item = FoldPanelItem(self._foldPanel, -1, caption=caption,
                             foldIcons=foldIcons,
                             collapsed=collapsed, cbstyle=cbstyle)

        pos = 0
        if len(self._panels) > 0:
            pos = self._panels[-1].GetItemPos() + self._panels[-1].GetPanelLength()

        item.Reposition(pos)
        self._panels.append(item)

        return item

[docs]    def AddFoldPanelWindow(self, panel, window, flags=FPB_ALIGN_WIDTH,
                           spacing=FPB_DEFAULT_SPACING,
                           leftSpacing=FPB_DEFAULT_LEFTLINESPACING,
                           rightSpacing=FPB_DEFAULT_RIGHTLINESPACING):
        """
        Adds a `wx.Window` derived instance to the referenced fold panel.

        :param `panel`: an instance of L{FoldPanelItem};
        :param `window`: the window we wish to add to the fold panel, an instance
         of `wx.Window`;
        :param `flags`: can be one of the following bits:

         ====================== ======= ====================================
         Align Flag              Value  Description
         ====================== ======= ====================================
         ``FPB_ALIGN_WIDTH``          1 The `wx.Window` to be added will be aligned to fit the width of the FoldPanel when it is resized. Very handy for sizer items, buttons and text boxes.
         ``FPB_ALIGN_LEFT``           0 Aligns left instead of fitting the width of the child window to be added. Use either this one or ``FPB_ALIGN_WIDTH``.
         ====================== ======= ====================================

        :param `spacing`: the `wx.Window` to be added can be slightly indented from
         left and right so it is more visibly placed in the fold panel. Use `spacing` > 0
         to give the control an y offset from the previous `wx.Window` added;
        :param `leftSpacing`: give the `wx.Window` added a slight indent from the left;
        :param `rightSpacing`: give the `wx.Window` added a slight indent from the right;

        :note: Make the window be a child of the fold panel!

         The following example adds a FoldPanel to the L{FoldPanelBar} and
         adds two `wx.Window` derived controls to the FoldPanel::

               # Create the FoldPanelBar
               m_pnl = FoldPanelBar(self, wx.ID_ANY, wx.DefaultPosition, wx.DefaultSize, agwStyle=0x2)

               # Add a foldpanel to the control. "Test me" is the caption and it is
               # initially not collapsed.
               item = m_pnl.AddFoldPanel("Test me", False)

               # Now add a button to the fold panel. Mind that the button should be
               # made child of the FoldPanel and not of the main form.
               m_pnl.AddFoldPanelWindow(item, wx.Button(item, ID_COLLAPSEME, "Collapse Me"))

               # Add a separator between the two controls. This is purely a visual
               # line that can have a certain colour and also the indents and width
               # aligning like a control.
               m_pnl.AddFoldPanelSeparator(item)

               # Now add a text ctrl. Also very easy. Align this on width so that
               # when the control gets wider the text control also sizes along.
               m_pnl.AddFoldPanelWindow(item, wx.TextCtrl(item, wx.ID_ANY, "Comment"), FPB_ALIGN_WIDTH, FPB_DEFAULT_SPACING, 20)

        """

        try:
            item = self._panels.index(panel)
        except:
            raise Exception("ERROR: Invalid Panel Passed To AddFoldPanelWindow: " + repr(panel))

        panel.AddWindow(window, flags, spacing, leftSpacing, rightSpacing)

        # TODO: Take old and new height, and if difference, reposition all the lower
        # panels this is because the user can add new wxWindow controls somewhere in
        # between when other panels are already present.

        return 0

[docs]    def AddFoldPanelSeparator(self, panel, colour=wx.BLACK,
                              spacing=FPB_DEFAULT_SPACING,
                              leftSpacing=FPB_DEFAULT_LEFTLINESPACING,
                              rightSpacing=FPB_DEFAULT_RIGHTLINESPACING):
        """
        Adds a separator line to the current fold panel.

        The separator is a simple line which is drawn and is no real
        component. It can be used to separate groups of controls
        which belong to each other.

        :param `colour`: the separator colour, an instance of `wx.Colour`;
        :param `spacing`: the separator to be added can be slightly indented from
         left and right so it is more visibly placed in the fold panel. Use `spacing` > 0
         to give the control an y offset from the previous `wx.Window` added;
        :param `leftSpacing`: give the added separator a slight indent from the left;
        :param `rightSpacing`: give the added separator a slight indent from the right.
        """

        try:
            item = self._panels.index(panel)
        except:
            raise Exception("ERROR: Invalid Panel Passed To AddFoldPanelSeparator: " + repr(panel))

        panel.AddSeparator(colour, spacing, leftSpacing, rightSpacing)
        return 0

[docs]    def OnSizePanel(self, event):
        """
        Handles the ``wx.EVT_SIZE`` event for L{FoldPanelBar}.

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

        # skip all stuff when we are not initialised yet

        if not self._controlCreated:
            event.Skip()
            return

        foldrect = self.GetRect()

        # fold panel itself. If too little space,
        # don't show it

        foldrect.SetX(0)
        foldrect.SetY(0)

        self._foldPanel.SetSize(foldrect[2:])

        if self._agwStyle & FPB_COLLAPSE_TO_BOTTOM or self._agwStyle & FPB_EXCLUSIVE_FOLD:
            rect = self.RepositionCollapsedToBottom()
            vertical = self.IsVertical()
            if vertical and rect.GetHeight() > 0 or not vertical and rect.GetWidth() > 0:
                self.RefreshRect(rect)

        # TODO: A smart way to check wether the old - new width of the
        # panel changed, if so no need to resize the fold panel items

        self.RedisplayFoldPanelItems()

[docs]    def OnPressCaption(self, event):
        """
        Handles the ``wx.EVT_CAPTIONBAR`` event for L{CaptionBar}.

        :param `event`: a L{CaptionBarEvent} event to be processed.
        """

        # act upon the folding or expanding status of the bar
        # to expand or collapse the panel(s)

        if event.GetFoldStatus():
            self.Collapse(event.GetTag())
        else:
            self.Expand(event.GetTag())

[docs]    def RefreshPanelsFrom(self, item):
        """
        Refreshes all the panels from given one down to last one.

        :param `item`: the first L{FoldPanelItem} to be refreshed.
        """

        try:
            i = self._panels.index(item)
        except:
            raise Exception("ERROR: Invalid Panel Passed To RefreshPanelsFrom: " + repr(item))

        self.Freeze()

        # if collapse to bottom is on, the panels that are not expanded
        # should be drawn at the bottom. All panels that are expanded
        # are drawn on top. The last expanded panel gets all the extra space

        if self._agwStyle & FPB_COLLAPSE_TO_BOTTOM or self._agwStyle & FPB_EXCLUSIVE_FOLD:

            offset = 0

            for panels in self._panels:

                if panels.IsExpanded():
                    offset = offset + panels.Reposition(offset)

            # put all non collapsed panels at the bottom where there is space,
            # else put them right behind the expanded ones

            self.RepositionCollapsedToBottom()

        else:

            pos = self._panels[i].GetItemPos() + self._panels[i].GetPanelLength()
            for j in range(i+1, len(self._panels)):
                pos = pos + self._panels[j].Reposition(pos)

        self.Thaw()

[docs]    def RedisplayFoldPanelItems(self):
        """ Resizes the fold panels so they match the width. """

        # resize them all. No need to reposition
        for panels in self._panels:
            panels.ResizePanel()
            panels.Refresh()

[docs]    def RepositionCollapsedToBottom(self):
        """
        Repositions all the collapsed panels to the bottom.

        When it is not possible to align them to the bottom, stick them behind
        the visible panels.
        """

        value = wx.Rect(0,0,0,0)
        vertical = self.IsVertical()

        # determine wether the number of panels left
        # times the size of their captions is enough
        # to be placed in the left over space

        expanded = 0
        collapsed = 0
        collapsed, expanded, values = self.GetPanelsLength(collapsed, expanded)

        # if no room stick them behind the normal ones, else
        # at the bottom

        if (vertical and [self.GetSize().GetHeight()] or \
            [self.GetSize().GetWidth()])[0] - expanded - collapsed < 0:
            offset = expanded
        else:

            # value is the region which is left unpainted
            # I will send it back as 'slack' so it does not need to
            # be recalculated.

            value.SetHeight(self.GetSize().GetHeight())
            value.SetWidth(self.GetSize().GetWidth())

            if vertical:
                value.SetY(expanded)
                value.SetHeight(value.GetHeight() - expanded)
            else:
                value.SetX(expanded)
                value.SetWidth(value.GetWidth() - expanded)

            offset = (vertical and [self.GetSize().GetHeight()] or \
                      [self.GetSize().GetWidth()])[0] - collapsed

        # go reposition

        for panels in self._panels:
            if not panels.IsExpanded():
                offset = offset + panels.Reposition(offset)

        return value

[docs]    def GetPanelsLength(self, collapsed, expanded):
        """
        Returns the length of the panels that are expanded and
        collapsed.

        :param `collapsed`: the current value of the collapsed panels;
        :param `expanded`: the current value of the expanded panels.

        :note: This is useful to determine quickly what size is used to display,
         and what is left at the bottom (right) to align the collapsed panels.
        """

        value = 0

        # assumed here that all the panels that are expanded
        # are positioned after each other from 0,0 to end.

        for j in range(0, len(self._panels)):
            offset = self._panels[j].GetPanelLength()
            value = value + offset
            if self._panels[j].IsExpanded():
                expanded = expanded + offset
            else:
                collapsed = collapsed + offset

        return collapsed, expanded, value

[docs]    def Collapse(self, foldpanel):
        """
        Collapses the given fold panel reference, and updates the foldpanel bar.

        :param `foldpanel`: an instance of L{FoldPanelItem}.

        :note: With the ``FPB_COLLAPSE_TO_BOTTOM`` style set, all collapsed captions
         are put at the bottom of the control. In the normal mode, they stay where
         they are.
        """

        try:
            item = self._panels.index(foldpanel)
        except:
            raise Exception("ERROR: Invalid Panel Passed To Collapse: " + repr(foldpanel))

        foldpanel.Collapse()
        self.RefreshPanelsFrom(foldpanel)

[docs]    def Expand(self, foldpanel):
        """
        Expands the given fold panel reference, and updates the foldpanel bar.

        :param `foldpanel`: an instance of L{FoldPanelItem}.

        :note: With the ``FPB_COLLAPSE_TO_BOTTOM`` style set, they will be removed
         from the bottom and the order where the panel originally was placed is
         restored.
        """

        fpbextrastyle = 0

        if self._agwStyle & FPB_SINGLE_FOLD or self._agwStyle & FPB_EXCLUSIVE_FOLD:
            fpbextrastyle = 1
            for panel in self._panels:
                panel.Collapse()

        foldpanel.Expand()

        if fpbextrastyle:
            if self._agwStyle & FPB_EXCLUSIVE_FOLD:
                self.RepositionCollapsedToBottom()
            self.RefreshPanelsFrom(self._panels[0])
        else:
            self.RefreshPanelsFrom(foldpanel)

[docs]    def ApplyCaptionStyle(self, foldpanel, cbstyle):
        """
        Sets the style of the caption bar (L{CaptionBar}) of the fold panel.

        :param `foldpanel`: an instance of L{FoldPanelItem};
        :param `cbstyle`: an instance of L{CaptionBarStyle}.

        :note:

         The changes are applied immediately. All styles not set in the
         L{CaptionBarStyle} class are not applied. Use the L{CaptionBar} reference
         to indicate what captionbar you want to apply the style to. To apply one
         style to all L{CaptionBar} items, use L{ApplyCaptionStyleAll}.
        """

        foldpanel.ApplyCaptionStyle(cbstyle)

[docs]    def ApplyCaptionStyleAll(self, cbstyle):
        """
        Sets the style of all the caption bars of the fold panel.
        The changes are applied immediately.

        :param `cbstyle`: an instance of L{CaptionBarStyle}.
        """

        for panels in self._panels:
            self.ApplyCaptionStyle(panels, cbstyle)

[docs]    def GetCaptionStyle(self, foldpanel):
        """
        Returns the currently used caption style for the fold panel.

        It is returned as a L{CaptionBarStyle} class. After modifying it, it can
        be set again.

        :param `foldpanel`: an instance of L{FoldPanelItem}.
        """

        return foldpanel.GetCaptionStyle()

[docs]    def IsVertical(self):
        """
        Returns whether the L{CaptionBar} has default orientation or not.
        Default is vertical.
        """

        return self._isVertical

[docs]    def GetFoldPanel(self, item):
        """
        Returns the panel associated with the index `item`.

        :param `item`: an integer representing the L{FoldPanelItem} in the list of
         panels in this L{FoldPanelBar}.
        """

        try:
            ind = self._panels[item]
            return self._panels[item]
        except:
            raise Exception("ERROR: List Index Out Of Range Or Bad Item Passed: " + repr(item) + \
                            ". Item Should Be An Integer Between " + repr(0) + " And " + \
                            repr(len(self._panels)))

[docs]    def GetCount(self):
        """ Returns the number of panels in the L{FoldPanelBar}. """

        try:
            return len(self._panels)
        except:
            raise Exception("ERROR: No Panels Have Been Added To FoldPanelBar")

# --------------------------------------------------------------------------------- #
# class FoldPanelItem
# --------------------------------------------------------------------------------- #

[docs]class FoldPanelItem(wx.Panel):
    """
    This class is a child sibling of the L{FoldPanelBar} class. It will
    contain a L{CaptionBar} class for receiving of events, and a the
    rest of the area can be populated by a `wx.Panel` derived class.
    """

[docs]    def __init__(self, parent, id=wx.ID_ANY, caption="", foldIcons=None,
                 collapsed=False, cbstyle=None):
        """
        Default class constructor.

        :param `parent`: the L{FoldPanelItem} parent window;
        :param `id`: an identifier for the control: a value of -1 is taken to mean a default;
        :param `caption`: the string to be displayed in L{CaptionBar};
        :param `foldIcons`: an instance of `wx.ImageList` containing the icons to display
         next to the caption text;
        :param `collapsed`: ``True`` if the L{CaptionBar} should start in the collapsed state,
         ``False`` otherwise;
        :param `cbstyle`: the L{CaptionBar} window style. Must be an instance of
         L{CaptionBarStyle}.
        """

        wx.Panel.__init__(self, parent, id, wx.Point(0,0), style=wx.CLIP_CHILDREN)
        self._controlCreated = False
        self._UserSize = 0
        self._PanelSize = 0
        self._LastInsertPos = 0
        self._itemPos = 0
        self._userSized = False

        if foldIcons is None:
            foldIcons = wx.ImageList(16, 16)

            bmp = ExpandedIcon.GetBitmap()
            foldIcons.Add(bmp)
            bmp = CollapsedIcon.GetBitmap()
            foldIcons.Add(bmp)

        self._foldIcons = foldIcons
        if cbstyle is None:
            cbstyle = EmptyCaptionBarStyle

        # create the caption bar, in collapsed or expanded state

        self._captionBar = CaptionBar(self, wx.ID_ANY, wx.Point(0,0),
                                      size=wx.DefaultSize, caption=caption,
                                      foldIcons=foldIcons, cbstyle=cbstyle)

        if collapsed:
            self._captionBar.Collapse()

        self._controlCreated = True

        # make initial size for component, if collapsed, the
        # size is determined on the panel height and won't change

        size = self._captionBar.GetSize()

        self._PanelSize = (self.IsVertical() and [size.GetHeight()] or \
                           [size.GetWidth()])[0]

        self._LastInsertPos = self._PanelSize
        self._items = []

        self.Bind(EVT_CAPTIONBAR, self.OnPressCaption)
        self.Bind(wx.EVT_PAINT, self.OnPaint)

[docs]    def AddWindow(self, window, flags=FPB_ALIGN_WIDTH, spacing=FPB_DEFAULT_SPACING,
                  leftSpacing=FPB_DEFAULT_LEFTLINESPACING,
                  rightSpacing=FPB_DEFAULT_RIGHTLINESPACING):
        """
        Adds a window item to the list of items on this panel.

        :param `window`: an instance of `wx.Window`;
        :param `flags`: can be one of the following bits:

         ====================== ======= ====================================
         Align Flag              Value  Description
         ====================== ======= ====================================
         ``FPB_ALIGN_WIDTH``          1 The `wx.Window` to be added will be aligned to fit the width of the FoldPanel when it is resized. Very handy for sizer items, buttons and text boxes.
         ``FPB_ALIGN_LEFT``           0 Aligns left instead of fitting the width of the child window to be added. Use either this one or ``FPB_ALIGN_WIDTH``.
         ====================== ======= ====================================

        :param `spacing`: reserves a number of pixels before the window element;
        :param `leftSpacing`: an indent, in pixels;
        :param `rightSpacing`: a right spacing, only relevant when the style
         ``FPB_ALIGN_WIDTH`` is chosen.
        """

        wi = FoldWindowItem(self, window, Type="WINDOW", flags=flags, spacing=spacing,
                            leftSpacing=leftSpacing, rightSpacing=rightSpacing)

        self._items.append(wi)

        vertical = self.IsVertical()

        self._spacing = spacing
        self._leftSpacing = leftSpacing
        self._rightSpacing = rightSpacing

        xpos = (vertical and [leftSpacing] or [self._LastInsertPos + spacing])[0]
        ypos = (vertical and [self._LastInsertPos + spacing] or [leftSpacing])[0]

        window.SetDimensions(xpos, ypos, -1, -1, wx.SIZE_USE_EXISTING)

        self._LastInsertPos = self._LastInsertPos + wi.GetWindowLength(vertical)
        self.ResizePanel()

[docs]    def AddSeparator(self, colour=wx.BLACK, spacing=FPB_DEFAULT_SPACING,
                     leftSpacing=FPB_DEFAULT_LEFTSPACING,
                     rightSpacing=FPB_DEFAULT_RIGHTSPACING):
        """
        Adds a separator item to the list of items on this panel.

        :param `colour`: the separator colour, an instance of `wx.Colour`;
        :param `spacing`: the separator to be added can be slightly indented from
         left and right so it is more visibly placed in the fold panel. Use `spacing` > 0
         to give the control an y offset from the previous `wx.Window` added;
        :param `leftSpacing`: give the added separator a slight indent from the left;
        :param `rightSpacing`: give the added separator a slight indent from the right.
        """

        wi = FoldWindowItem(self, window=None, Type="SEPARATOR",
                            flags=FPB_ALIGN_WIDTH, y=self._LastInsertPos,
                            colour=colour, spacing=spacing, leftSpacing=leftSpacing,
                            rightSpacing=rightSpacing)

        self._items.append(wi)
        self._LastInsertPos = self._LastInsertPos + \
                              wi.GetWindowLength(self.IsVertical())

        self.ResizePanel()

[docs]    def Reposition(self, pos):
        """
        Repositions this L{FoldPanelItem} and reports the length occupied
        for the next L{FoldPanelItem} in the list.

        :param `pos`: the new item position.
        """

        # NOTE: Call Resize before Reposition when an item is added, because the new
        # size needed will be calculated by Resize. Of course the relative position
        # of the controls have to be correct in respect to the caption bar

        self.Freeze()

        vertical = self.IsVertical()
        xpos = (vertical and [-1] or [pos])[0]
        ypos = (vertical and [pos] or [-1])[0]

        self.SetDimensions(xpos, ypos, -1, -1, wx.SIZE_USE_EXISTING)
        self._itemPos = pos

        self.Thaw()

        return self.GetPanelLength()

[docs]    def OnPressCaption(self, event):
        """
        Handles the ``wx.EVT_CAPTIONBAR`` event for L{FoldPanelItem}.

        :param `event`: a L{CaptionBarEvent} event to be processed.
        """

        # tell the upper container we are responsible
        # for this event, so it can fold the panel item
        # and do a refresh

        event.SetTag(self)
        event.Skip()

[docs]    def ResizePanel(self):
        """ Resizes the panel. """

        # prevent unnecessary updates by blocking repaints for a sec

        self.Freeze()

        vertical = self.IsVertical()
        # force this panel to take the width of the parent panel and the y of the
        # user or calculated width (which will be recalculated by the contents here)

        if self._captionBar.IsCollapsed():
            size = self._captionBar.GetSize()
            self._PanelSize = (vertical and [size.GetHeight()] or [size.GetWidth()])[0]
        else:
            size = self.GetBestSize()
            self._PanelSize = (vertical and [size.GetHeight()] or [size.GetWidth()])[0]

            if self._UserSize:
                if vertical:
                    size.SetHeight(self._UserSize)
                else:
                    size.SetWidth(self._UserSize)

        pnlsize = self.GetParent().GetSize()

        if vertical:
            size.SetWidth(pnlsize.GetWidth())
        else:
            size.SetHeight(pnlsize.GetHeight())

        # resize caption bar
        xsize = (vertical and [size.GetWidth()] or [-1])[0]
        ysize = (vertical and [-1] or [size.GetHeight()])[0]

        self._captionBar.SetSize((xsize, ysize))

        # resize the panel
        self.SetSize(size)

        # go by all the controls and call Layout

        for items in self._items:
            items.ResizeItem((vertical and [size.GetWidth()] or \
                              [size.GetHeight()])[0], vertical)

        self.Thaw()

[docs]    def OnPaint(self, event):
        """
        Handles the ``wx.EVT_PAINT`` event for L{FoldPanelItem}.

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

        # draw all the items that are lines

        dc = wx.PaintDC(self)
        vertical = self.IsVertical()

        for item in self._items:

            if item.GetType() == "SEPARATOR":
                pen = wx.Pen(item.GetLineColour(), 1, wx.SOLID)
                dc.SetPen(pen)
                a = item.GetLeftSpacing()
                b = item.GetLineY() + item.GetSpacing()
                c = item.GetLineLength()
                d = a + c

                if vertical:
                    dc.DrawLine(a, b, d, b)
                else:
                    dc.DrawLine(b, a, b, d)

        event.Skip()

[docs]    def IsVertical(self):
        """
        Returns whether the L{CaptionBar} has default orientation or not.
        Default is vertical.
        """

        # grandparent of FoldPanelItem is FoldPanelBar
        # default is vertical

        if isinstance(self.GetGrandParent(), FoldPanelBar):
            return self.GetGrandParent().IsVertical()
        else:
            raise Exception("ERROR: Wrong Parent " + repr(self.GetGrandParent()))

[docs]    def IsExpanded(self):
        """
        Returns expanded or collapsed status.  If the panel is
        expanded, ``True`` is returned.
        """

        return not self._captionBar.IsCollapsed()

[docs]    def GetItemPos(self):
        """ Returns item's position. """

        return self._itemPos

[docs]    def Collapse(self):
        """
        Internal method.

        This should not be called by the user, because it doesn't trigger the
        parent  to tell it that we are collapsed or expanded, it only changes
        visual state.
        """

        self._captionBar.Collapse()
        self.ResizePanel()

[docs]    def Expand(self):
        """
        Internal method.

        This should not be called by the user, because it doesn't trigger the
        parent to tell it that we are collapsed or expanded, it only changes
        visual state.
        """

        self._captionBar.Expand()
        self.ResizePanel()

[docs]    def GetPanelLength(self):
        """ Returns size of panel. """

        if self._captionBar.IsCollapsed():
            return self.GetCaptionLength()
        elif self._userSized:
            return self._UserSize

        return self._PanelSize

[docs]    def GetCaptionLength(self):
        """ Returns height of caption only. This is for folding calculation purposes. """

        size = self._captionBar.GetSize()
        return (self.IsVertical() and [size.GetHeight()] or [size.GetWidth()])[0]

[docs]    def ApplyCaptionStyle(self, cbstyle):
        """ Applies the style defined in `cbstyle` to the L{CaptionBar}."""

        self._captionBar.SetCaptionStyle(cbstyle)

[docs]    def GetCaptionStyle(self):
        """
        Returns the current style of the captionbar in a L{CaptionBarStyle} class.

        This can be used to change and set back the changes.
        """

        return self._captionBar.GetCaptionStyle()

# ----------------------------------------------------------------------------------- #
# class FoldWindowItem
# ----------------------------------------------------------------------------------- #

[docs]class FoldWindowItem(object):
    """
    This class is a child sibling of the L{FoldPanelItem} class. It
    will contain `wx.Window` that can be either a separator (a coloured
    line simulated by a `wx.Window`) or a wxPython controls (such as a
    `wx.Button`, a `wx.ListCtrl` etc...).
    """

[docs]    def __init__(self, parent, window=None, **kw):
        """
        Default class constructor

        :param `parent`: the L{FoldWindowItem} parent;
        :param `window`: the window contained in this item.

        :keyword `Type`: can be "WINDOW" or "SEPARATOR";
        :keyword `lineColour`: the separator colour (meaningful for separators only);
        :keyword `y`: the separator y position (meaningful for separators only);
        :keyword `flags`: the alignment flags;
        :keyword `spacing`: reserves a number of pixels before the window/separator element;
        :keyword `leftSpacing`: an indent, in pixels;
        :keyword `rightSpacing`: a right spacing, only relevant when the style
         ``FPB_ALIGN_WIDTH`` is chosen.

        :see: L{FoldPanelBar.AddFoldPanelWindow} for a list of valid alignment flags.
        """

        if not kw.has_key("Type"):
            raise Exception('ERROR: Missing Window Type Information. This Should Be "WINDOW" Or "SEPARATOR"')

        if kw.get("Type") == "WINDOW":
            # Window constructor. This initialises the class as a wx.Window Type

            if kw.has_key("flags"):
                self._flags = kw.get("flags")
            else:
                self._flags = FPB_ALIGN_WIDTH
            if kw.has_key("spacing"):
                self._spacing = kw.get("spacing")
            else:
                self._spacing = FPB_DEFAULT_SPACING
            if kw.has_key("leftSpacing"):
                self._leftSpacing = kw.get("leftSpacing")
            else:
                self._leftSpacing = FPB_DEFAULT_LEFTSPACING
            if kw.has_key("rightSpacing"):
                self._rightSpacing = kw.get("rightSpacing")
            else:
                self._rightSpacing = FPB_DEFAULT_RIGHTSPACING

            self._lineY = 0
            self._sepLineColour = None
            self._wnd = window

        elif kw.get("Type") == "SEPARATOR":
            # separator constructor. This initialises the class as a separator type

            if kw.has_key("y"):
                self._lineY = kw.get("y")
            else:
                raise Exception("ERROR: Undefined Y Position For The Separator")
            if kw.has_key("lineColour"):
                self._sepLineColour = kw.get("lineColour")
            else:
                self._sepLineColour = wx.BLACK
            if kw.has_key("flags"):
                self._flags = kw.get("flags")
            else:
                self._flags = FPB_ALIGN_WIDTH
            if kw.has_key("spacing"):
                self._spacing = kw.get("spacing")
            else:
                self._spacing = FPB_DEFAULT_SPACING
            if kw.has_key("leftSpacing"):
                self._leftSpacing = kw.get("leftSpacing")
            else:
                self._leftSpacing = FPB_DEFAULT_LEFTSPACING
            if kw.has_key("rightSpacing"):
                self._rightSpacing = kw.get("rightSpacing")
            else:
                self._rightSpacing = FPB_DEFAULT_RIGHTSPACING

            self._wnd = window

        else:
            raise Exception("ERROR: Undefined Window Type Selected: " + repr(kw.get("Type")))

        self._type = kw.get("Type")
        self._lineLength = 0

[docs]    def GetType(self):
        """ Returns the L{FoldWindowItem} type. """

        return self._type

[docs]    def GetLineY(self):
        """ Returns the y position of the separator. """

        return self._lineY

[docs]    def GetLineLength(self):
        """ Returns the separator line length. """

        return self._lineLength

[docs]    def GetLineColour(self):
        """ Returns the separator line colour. """

        return self._sepLineColour

[docs]    def GetLeftSpacing(self):
        """ Returns the left indent of L{FoldWindowItem}. """

        return self._leftSpacing

[docs]    def GetRightSpacing(self):
        """ Returns the right indent of L{FoldWindowItem}. """

        return self._rightSpacing

[docs]    def GetSpacing(self):
        """ Returns the spacing of L{FoldWindowItem}. """

        return self._spacing

[docs]    def GetWindowLength(self, vertical=True):
        """
        Returns space needed by the window if type is L{FoldWindowItem}
        "WINDOW" and returns the total size plus the extra spacing.

        :param `vertical`: ``True`` if the parent L{FoldPanelBar} is in vertical
         mode.
        """

        value = 0
        if self._type == "WINDOW":
            size = self._wnd.GetSize()
            value = (vertical and [size.GetHeight()] or [size.GetWidth()])[0] + \
                    self._spacing

        elif self._type == "SEPARATOR":
            value = 1 + self._spacing

        return value

[docs]    def ResizeItem(self, size, vertical=True):
        """
        Resizes the element, whatever it is.

        A separator or line will be always aligned by width or height
        depending on orientation of the whole panel.

        :param `size`: the maximum size available for the L{FoldWindowItem};
        :param `vertical`: ``True`` if the parent L{FoldPanelBar} is in vertical
         mode.
        """

        if self._flags & FPB_ALIGN_WIDTH:
            # align by taking full width
            mySize = size - self._leftSpacing - self._rightSpacing

            if mySize < 0:
                mySize = 10  # can't have negative width

            if self._type == "SEPARATOR":
                self._lineLength = mySize
            else:
                xsize = (vertical and [mySize] or [-1])[0]
                ysize = (vertical and [-1] or [mySize])[0]

                self._wnd.SetSize((xsize, ysize))

Navigation

  • index
  • modules |
  • Home |
  • Gallery |
  • Contents»
  • Module code »
  • foldpanelbar


fourwaysplitter

  • modules |
  • Home |
  • Gallery |
  • Contents»
  • Module code »
  • fourwaysplitter

Source code for fourwaysplitter

# --------------------------------------------------------------------------------- #
# FOURWAYSPLITTER wxPython IMPLEMENTATION
#
# Andrea Gavana, @ 03 Nov 2006
# Latest Revision: 17 Aug 2011, 15.00 GMT
#
#
# TODO List
#
# 1. Any idea?
#
# For All Kind Of Problems, Requests Of Enhancements And Bug Reports, Please
# Write To Me At:
#
# andrea.gavana@maerskoil.com
# andrea.gavana@gmail.com
#
# Or, Obviously, To The wxPython Mailing List!!!
#
#
# End Of Comments
# --------------------------------------------------------------------------------- #

"""
L{FourWaySplitter} is a layout manager which manages 4 children like 4 panes in a
window.

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

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

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

The main characteristics of L{FourWaySplitter} are:

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

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

Usage
=====

Usage example::

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

    class MyFrame(wx.Frame):

        def __init__(self, parent):

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

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

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

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

                splitter.AppendWindow(panel)

    # our normal wxApp-derived class, as usual

    app = wx.PySimpleApp()

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

    app.MainLoop()

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

L{FourWaySplitter} has been tested on the following platforms:
  * Windows (Windows XP);
  * Linux Ubuntu (Dapper 6.06)

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

This class supports the following window styles:

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

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

This class processes the following events:

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

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

L{FourWaySplitter} is distributed under the wxPython license.

Latest Revision: Andrea Gavana @ 17 Aug 2011, 15.00 GMT

Version 0.4

"""

__docformat__ = "epytext"

import wx

_RENDER_VER = (2,6,1,1)

# Tolerance for mouse shape and sizing
_TOLERANCE = 5

# Modes
NOWHERE = 0
FLAG_CHANGED = 1
FLAG_PRESSED = 2

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

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

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

[docs]class FourWaySplitterEvent(wx.PyCommandEvent):
    """
    This event class is almost the same as `wx.SplitterEvent` except
    it adds an accessor for the sash index that is being changed.  The
    same event type IDs and event binders are used as with
    `wx.SplitterEvent`.
    """

[docs]    def __init__(self, evtType=wx.wxEVT_NULL, splitter=None):
        """
        Default class constructor.

        :param `evtType`: the event type;
        :param `splitter`: the associated L{FourWaySplitter} window.
        """

        wx.PyCommandEvent.__init__(self, evtType)

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

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

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

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

        self.sashIdx = idx

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

        :param `pos`: the new sash position.

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

        self.sashPos = pos

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

        return self.sashIdx

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

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

        return self.sashPos

    # methods from wx.NotifyEvent

[docs]    def Veto(self):
        """
        Prevents the change announced by this event from happening.

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

        self.isAllowed = False

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

        self.isAllowed = True

[docs]    def IsAllowed(self):
        """
        Returns ``True`` if the change is allowed (L{Veto} hasn't been called) or
        ``False`` otherwise (if it was).
        """

        return self.isAllowed

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

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

    :note: These things are not yet supported:

     * Minimum pane size (minimum of what? Width? Height?);
     * Using negative sash positions to indicate a position offset from the end;
     * User controlled unsplitting with double clicks on the sash (but supported via the L{FourWaySplitter.SetExpanded} method);
     * Sash gravity.

    """

[docs]    def __init__(self, parent, id=wx.ID_ANY, pos=wx.DefaultPosition,
                 size=wx.DefaultSize, style=0, agwStyle=0, name="FourWaySplitter"):
        """
        Default class constructor.

        :param `parent`: parent window. Must not be ``None``;
        :param `id`: window identifier. A value of -1 indicates a default value;
        :param `pos`: the control position. A value of (-1, -1) indicates a default position,
         chosen by either the windowing system or wxPython, depending on platform;
        :param `size`: the control size. A value of (-1, -1) indicates a default size,
         chosen by either the windowing system or wxPython, depending on platform;
        :param `style`: the underlying `wx.PyPanel` window style;
        :param `agwStyle`: the AGW-specific window style. It can be a combination of the
         following bits:

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

        :param `name`: the window name.
        """

        # always turn on tab traversal
        style |= wx.TAB_TRAVERSAL

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

        self._agwStyle = agwStyle

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

        self._windows = []

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

        self._sashTrackerPen = wx.Pen(wx.BLACK, 2, wx.SOLID)

        self._sashCursorWE = wx.StockCursor(wx.CURSOR_SIZEWE)
        self._sashCursorNS = wx.StockCursor(wx.CURSOR_SIZENS)
        self._sashCursorSIZING = wx.StockCursor(wx.CURSOR_SIZING)

        self.Bind(wx.EVT_PAINT, self.OnPaint)
        self.Bind(wx.EVT_MOTION, self.OnMotion)
        self.Bind(wx.EVT_SIZE, self.OnSize)
        self.Bind(wx.EVT_LEFT_DOWN, self.OnLeftDown)
        self.Bind(wx.EVT_LEFT_UP, self.OnLeftUp)
        self.Bind(wx.EVT_LEAVE_WINDOW, self.OnLeaveWindow)
        self.Bind(wx.EVT_ENTER_WINDOW, self.OnEnterWindow)

[docs]    def SetAGWWindowStyleFlag(self, agwStyle):
        """
        Sets the L{FourWaySplitter} window style flags.

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

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

        self._agwStyle = agwStyle
        self.Refresh()

[docs]    def GetAGWWindowStyleFlag(self):
        """
        Returns the L{FourWaySplitter} window style.

        :see: L{SetAGWWindowStyleFlag} for a list of possible window styles.
        """

        return self._agwStyle

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

        :param `window`: an instance of `wx.Window`.
        """

        self.InsertWindow(len(self._windows), window)

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

        :param `idx`: the index at which the window will be inserted;
        :param `window`: an instance of `wx.Window`;
        :param `sashPos`: the sash position after the window insertion.
        """

        assert window not in self._windows, "A window can only be in the splitter once!"

        self._windows.insert(idx, window)

        self._SizeWindows()

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

        :param `window`: an instance of `wx.Window`.
        """

        assert window in self._windows, "Unknown window!"

        idx = self._windows.index(window)
        del self._windows[idx]

        self._SizeWindows()

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

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

        assert oldWindow in self._windows, "Unknown window!"

        idx = self._windows.index(oldWindow)
        self._windows[idx] = newWindow

        self._SizeWindows()

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

        :param `window1`: an instance of `wx.Window`;
        :param `window2`: another instance of `wx.Window`.
        """

        assert window1 in self._windows, "Unknown window!"
        assert window2 in self._windows, "Unknown window!"

        idx1 = self._windows.index(window1)
        idx2 = self._windows.index(window2)
        self._windows[idx1] = window2
        self._windows[idx2] = window1

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

        self._SizeWindows()

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

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

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

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

        return None

    # Get top left child

[docs]    def GetTopLeft(self):
        """ Returns the top left window (window index: 0). """

        return self.GetWindow(0)

    # Get top right child

[docs]    def GetTopRight(self):
        """ Returns the top right window (window index: 1). """

        return self.GetWindow(1)

    # Get bottom left child

[docs]    def GetBottomLeft(self):
        """ Returns the bottom left window (window index: 2). """

        return self.GetWindow(2)

    # Get bottom right child

[docs]    def GetBottomRight(self):
        """ Returns the bottom right window (window index: 3). """

        return self.GetWindow(3)

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

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

        if not self._windows:
            # something is better than nothing...
            return wx.Size(10, 10)

        width = height = 0
        border = self._GetBorderSize()

        tl = self.GetTopLeft()
        tr = self.GetTopRight()
        bl = self.GetBottomLeft()
        br = self.GetBottomRight()

        for win in self._windows:
            w, h = win.GetEffectiveMinSize()
            width += w
            height += h

        if tl and tr:
          width += self._GetSashSize()

        if bl and br:
          height += self._GetSashSize()

        return wx.Size(width+2*border, height+2*border)

    # Recompute layout

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

        :see: L{SetHSplit} and L{SetVSplit} for more information about split fractions.
        """

        win0 = self.GetTopLeft()
        win1 = self.GetTopRight()
        win2 = self.GetBottomLeft()
        win3 = self.GetBottomRight()

        width, height = self.GetSize()
        barSize = self._GetSashSize()
        border = self._GetBorderSize()

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

        else:

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

    # Determine split mode

[docs]    def GetMode(self, pt):
        """
        Determines the split mode for L{FourWaySplitter}.

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

        :return: One of the following 3 split modes:

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

        """

        barSize = self._GetSashSize()
        flag = wx.BOTH

        if pt.x < self._splitx - _TOLERANCE:
            flag &= ~wx.VERTICAL

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

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

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

        return flag

    # Move the split intelligently

[docs]    def MoveSplit(self, x, y):
        """
        Moves the split accordingly to user action.

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

        width, height = self.GetSize()
        barSize = self._GetSashSize()

        if x < 0: x = 0
        if y < 0: y = 0
        if x > width - barSize: x = width - barSize
        if y > height - barSize: y = height - barSize

        self._splitx = x
        self._splity = y

    # Adjust layout

[docs]    def AdjustLayout(self):
        """
        Adjust layout of L{FourWaySplitter}. Mainly used to recalculate the
        correct values for split fractions.
        """

        width, height = self.GetSize()
        barSize = self._GetSashSize()
        border = self._GetBorderSize()

        self._fhor = (width > barSize and \
                      [(10000*self._splitx+(width-barSize-1))/(width-barSize)] \
                      or [0])[0]

        self._fver = (height > barSize and \
                      [(10000*self._splity+(height-barSize-1))/(height-barSize)] \
                      or [0])[0]

        self._SizeWindows()

    # Button being pressed

[docs]    def OnLeftDown(self, event):
        """
        Handles the ``wx.EVT_LEFT_DOWN`` event for L{FourWaySplitter}.

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

        if not self.IsEnabled():
            return

        pt = event.GetPosition()
        self.CaptureMouse()
        self._mode = self.GetMode(pt)

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

            self._flags |= FLAG_PRESSED

    # Button being released

[docs]    def OnLeftUp(self, event):
        """
        Handles the ``wx.EVT_LEFT_UP`` event for L{FourWaySplitter}.

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

        if not self.IsEnabled():
            return

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

        flgs = self._flags

        self._flags &= ~FLAG_CHANGED
        self._flags &= ~FLAG_PRESSED

        if flgs & FLAG_PRESSED:

            if not self.GetAGWWindowStyleFlag() & wx.SP_LIVE_UPDATE:
                self.DrawTrackSplitter(self._splitx, self._splity)
                self.DrawSplitter(wx.ClientDC(self))
                self.AdjustLayout()

            if flgs & FLAG_CHANGED:
                event = FourWaySplitterEvent(wx.wxEVT_COMMAND_SPLITTER_SASH_POS_CHANGED, self)
                event.SetSashIdx(self._mode)
                event.SetSashPosition(wx.Point(self._splitx, self._splity))
                self.GetEventHandler().ProcessEvent(event)

        self._mode = NOWHERE

[docs]    def OnLeaveWindow(self, event):
        """
        Handles the ``wx.EVT_LEAVE_WINDOW`` event for L{FourWaySplitter}.

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

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

[docs]    def OnEnterWindow(self, event):
        """
        Handles the ``wx.EVT_ENTER_WINDOW`` event for L{FourWaySplitter}.

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

        self._RedrawIfHotSensitive(True)

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

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

        if not wx.VERSION >= _RENDER_VER:
            return

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

[docs]    def OnMotion(self, event):
        """
        Handles the ``wx.EVT_MOTION`` event for L{FourWaySplitter}.

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

        if self.HasFlag(wx.SP_NOSASH):
            return

        pt = event.GetPosition()

        # Moving split
        if self._flags & FLAG_PRESSED:

            oldsplitx = self._splitx
            oldsplity = self._splity

            if self._mode == wx.BOTH:
                self.MoveSplit(pt.x - self._offx, pt.y - self._offy)

            elif self._mode == wx.VERTICAL:
                self.MoveSplit(pt.x - self._offx, self._splity)

            elif self._mode == wx.HORIZONTAL:
                self.MoveSplit(self._splitx, pt.y - self._offy)

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

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

                self._flags |= FLAG_CHANGED

        # Change cursor based on position
        ff = self.GetMode(pt)

        if ff == wx.BOTH:
            self.SetCursor(self._sashCursorSIZING)

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

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

        else:
            self.SetCursor(wx.STANDARD_CURSOR)

        event.Skip()

[docs]    def OnPaint(self, event):
        """
        Handles the ``wx.EVT_PAINT`` event for L{FourWaySplitter}.

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

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

[docs]    def OnSize(self, event):
        """
        Handles the ``wx.EVT_SIZE`` event for L{FourWaySplitter}.

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

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

        self._SizeWindows()

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

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

        # send the event
        event = FourWaySplitterEvent(wx.wxEVT_COMMAND_SPLITTER_SASH_POS_CHANGING, self)
        event.SetSashIdx(self._mode)
        event.SetSashPosition(pt)

        if self.GetEventHandler().ProcessEvent(event) and not event.IsAllowed():
            # the event handler vetoed the change or missing event.Skip()
            return False
        else:
            # or it might have changed the value
            return True

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

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

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

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

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

    # Draw the horizontal split

[docs]    def DrawSplitter(self, dc):
        """
        Actually draws the sashes.

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

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

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

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

        flag = 0
        if self._isHot:
            flag = wx.CONTROL_CURRENT

        width, height = self.GetSize()

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

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

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

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

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

        # Draw a line to represent the dragging sash, for when not
        # doing live updates
        w, h = self.GetClientSize()
        dc = wx.ScreenDC()

        dc.SetLogicalFunction(wx.INVERT)
        dc.SetPen(self._sashTrackerPen)
        dc.SetBrush(wx.TRANSPARENT_BRUSH)

        if self._mode == wx.VERTICAL:
            x1 = x
            y1 = 2
            x2 = x
            y2 = h-2
            if x1 > w:
                x1 = w
                x2 = w
            elif x1 < 0:
                x1 = 0
                x2 = 0

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

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

        elif self._mode == wx.HORIZONTAL:

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

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

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

        elif self._mode == wx.BOTH:

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

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

            dc.DrawLine(x1, y1, x2, y2)

            x1 = x
            x2 = x
            y1 = 2
            y2 = h-2

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

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

    # Change horizontal split [fraction*10000]

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

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

            fourSplitter.SetHSplit(3500)

        """

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

    # Change vertical split [fraction*10000]

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

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

            fourSplitter.SetVSplit(3500)

        """

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

    # Expand one or all of the four panes

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

        :param `expanded`: an integer >= 0 to expand a window to fill the whole
         client size, or an integer < 0 to return to the four-window view.
        """

        if expanded >= 4:
            raise Exception("ERROR: SetExpanded: index out of range: %d"%expanded)

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

Navigation

  • index
  • modules |
  • Home |
  • Gallery |
  • Contents»
  • Module code »
  • fourwaysplitter


genericmessagedialog

  • modules |
  • Home |
  • Gallery |
  • Contents»
  • Module code »
  • genericmessagedialog

Source code for genericmessagedialog

# --------------------------------------------------------------------------------- #
# GENERICMESSAGEDIALOG wxPython IMPLEMENTATION
#
# Andrea Gavana, @ 07 October 2008
# Latest Revision: 29 Feb 2012, 21.00 GMT
#
#
# TODO List
#
# 1) ?
#
#
# 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
# --------------------------------------------------------------------------------- #

"""
This class is a possible, fancy replacement for `wx.MessageDialog`.

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

This class represents a dialog that shows a single or multi-line message,
with a choice of ``OK``, ``Yes``, ``No``, ``Cancel`` and ``Help`` buttons. It is a possible
replacement for the standard `wx.MessageDialog`, with these extra functionalities:

* Possibility to modify the dialog position;
* Custom themed generic bitmap & text buttons;
* Support for normal and extended message (in different fonts);
* Custom labels for the ``OK``, ``Yes``, ``No``, ``Cancel`` and ``Help`` buttons;
* Custom icons for the ``OK``, ``Yes``, ``No``, ``Cancel`` and ``Help`` buttons;
* Possibility to set an icon to the dialog;
* More visibility to the button getting the focus;
* Support for Aqua buttons or Gradient buttons instead of themed ones (see L{AquaButton}
  and L{GradientButton});
* Possibility to automatically wrap long lines of text;
* Good old Python code :-D .

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

Usage
=====

Usage example::

    import wx
    import wx.lib.agw.genericmessagedialog as GMD

    # Our normal wxApp-derived class, as usual
    app = wx.App(0)

    main_message = "Hello world! I am the main message."

    dlg = GMD.GenericMessageDialog(None, main_message, "A Nice Message Box",
                                   agwStyle=wx.ICON_INFORMATION|wx.OK)

    dlg.ShowModal()
    dlg.Destroy()

    app.MainLoop()

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

L{GenericMessageDialog} has been tested on the following platforms:
  * Windows (Windows XP).

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

This class supports the following window styles:

=========================== =========== ==================================================
Window Styles               Hex Value   Description
=========================== =========== ==================================================
``GMD_USE_AQUABUTTONS``            0x20 Uses `wx.lib.agw.aquabutton` buttons instead of generic buttons.
``GMD_USE_GRADIENTBUTTONS``        0x40 Uses `wx.lib.agw.gradientbutton` buttons instead of generic buttons.
=========================== =========== ==================================================

The styles above are mutually exclusive. The style chosen above can be combined with a
bitlist containing flags chosen from the following:

=========================== =========== ==================================================
Window Styles               Hex Value   Description
=========================== =========== ==================================================
``wx.OK``                           0x4 Shows an ``OK`` button.
``wx.CANCEL``                      0x10 Shows a ``Cancel`` button.
``wx.YES_NO``                       0xA Show ``Yes`` and ``No`` buttons.
``wx.YES_DEFAULT``                  0x0 Used with ``wx.YES_NO``, makes ``Yes`` button the default - which is the default behaviour.
``wx.NO_DEFAULT``                  0x80 Used with ``wx.YES_NO``, makes ``No`` button the default.
``wx.ICON_EXCLAMATION``           0x100 Shows an exclamation mark icon.
``wx.ICON_HAND``                  0x200 Shows an error icon.
``wx.ICON_ERROR``                 0x200 Shows an error icon - the same as ``wx.ICON_HAND``.
``wx.ICON_QUESTION``              0x400 Shows a question mark icon.
``wx.ICON_INFORMATION``           0x800 Shows an information icon.
=========================== =========== ==================================================

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

`No custom events are available for this class.`

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

L{GenericMessageDialog} is distributed under the wxPython license.

Latest Revision: Andrea Gavana @ 29 Feb 2012, 21.00 GMT

Version 0.7

"""

import wx
import wx.lib.wordwrap as wordwrap

import wx.lib.buttons as buttons
from wx.lib.embeddedimage import PyEmbeddedImage

# To use AquaButtons or GradientButtons instead of wx.lib.buttons
import aquabutton as AB
import gradientbutton as GB

# GenericMessageDialog styles
GMD_USE_AQUABUTTONS = 32
""" Uses `wx.lib.agw.aquabutton` buttons instead of generic buttons. """
GMD_USE_GRADIENTBUTTONS = 64
""" Uses `wx.lib.agw.gradientbutton` buttons instead of generic buttons. """

# Avoid 2.9 errors
BUTTON_SIZER_FLAGS = wx.OK | wx.CANCEL | wx.YES | wx.NO | wx.HELP | wx.NO_DEFAULT

_ = wx.GetTranslation

_cancel = PyEmbeddedImage(
    "iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAABHNCSVQICAgIfAhkiAAAA1dJ"
    "REFUOI11019oEwccB/Dv3eUuyZ2XpfljsmJ7JY01KZYWty6bdMwnp1X34JNS5sPAsmYruOnL"
    "3kTGcPg6Bdkexqql4EPdBuKbVG0xLmpoWjbW0D+S1Jg24RJzuSR3l58PtpsI/l5/fB5+3x9f"
    "AEDc7VauhMP3prq7q9+1t5/AW+aiLB+ZDocrU6HQk4tAFAC4s8Gg0uVyXTsZiw190Nsr6JnM"
    "kZAkrd6rVtOv4wuyfLS/rW3y6Oioq2tgILiRyXy4v1yexU979yaKIyNEiQRRsUjG2Bjddrtr"
    "532+k9v4B1kevu33l+vnzhFtbBAtL9OLS5douq9v0eZ1OPo8Xi8gSUClAls8jk+qVad148bP"
    "33s8TcY0K32mOTV07JhsP3UKKJUAy8IORYF3584erodopaGqh7qzWYEJBgGGgW3fPrQ/eyY0"
    "5uePewzjxIGDB0U5HgcsC1BV0MOH+GtiojF/9+433P1qNd1pGCvs5uawUijwbDAIWBZsAwPw"
    "5nJsRyBgc8fjYLZwK5lE6uZN88Hc3LdfmeYVDgDu12oLXUSrxvPnw8r6uo3z+cAQwRGJQOzv"
    "B0sEKhZhJRJI3rplJlKpM+OWdRkAuO2gZnQ93UO02CgUjr9bLHKCzweGZcGYJqhchp5I4NGd"
    "O9bjpaUvxol+2Xa211/FAKolSa0XySSq+TzYYBAAYGkaUKnA5LgWA6hvmP//PKgokx9tbspq"
    "Pg8NgL61c0gSJL8f73R04O9KRV9Mp0+PtlrX/zvhgigO749GJ4dKJVc9l0MTgAVAZBg4BQEk"
    "SeCcTjAAOhWF5/3+w7FsdvkPogXuR7f7s/d6eycPqKqrubKC+hZ28DxydnurzHFWwG5niefB"
    "CALYVgu7wmGe2toOfby2lrVFIpFrn9brcmNpCU0ALIAdooiMw9FI1etfkmGUbaY5EXY4JIth"
    "YAIw1tcxODgoEcddZeua9rQqCGB5HgwA0e3GmsdjPtH1s1/Xar+ON5vTi6p6+qmm6U5JAksE"
    "VhBQbzahl0p57n1Nm9kQxVhXINAucxzSLpeZLBTOxHX98nbAfxItxMrlVV4UD+/q7OTJ58Pc"
    "7Ow/uVTq81c1FYTo76HQo5k9expXnc6xt9X5OsuOPIhGtZndu//9DYgBwEt1gHq0YITgmAAA"
    "AABJRU5ErkJggg==")

#----------------------------------------------------------------------
_error = PyEmbeddedImage(
    "iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAAABHNCSVQICAgIfAhkiAAACY9J"
    "REFUWIWVl1tsXMd9xn8zc87ZXe4ud5dc0qRIWRIp0pJtVRFr15ZFA7kURJsADWwgQJvYSRAg"
    "gtGg6JvzIpi1nctDU8ZpYqFogMaBm5cETg0DjoM0hl0lRiJaVmxKFiRSsnWxTIqXJbncy7nM"
    "pQ+7lGTLl3YOPpxz5szM9/0vM2dG8DHlCz//ufrisWN/WQrD2zNCOM/3UZ6HVArZbmMBaxIS"
    "bdFJQqQUlUxm+v5vfesVhHAfNb74SPbJSfnLixe/uOe22/65u9R1k2xGTqoWuRASIQTgWpez"
    "WGuwRuPyeTE/d+7tmbfP/cPfPv30rz6KQn3oF+fEf/74xw/sLpW+Pzw80puTKZFWGZHyciJQ"
    "WeGrDuGrjPC9tPC9QAReIFK+L9KpQKQ9T+Qy6RKLi/feMzo6++zJk3P/Pw84J/79859/cKyv"
    "719uu/32crrZBA3IAIQPUoGQ7d4OhAU0CAPOgnMQBNSM4eTx4xeOr69/4xvPPff8/80Dk5Ny"
    "6tvffmBvV9fUntHRcsfqKjSboJMWTAI6Bh21EbYRQRJDkoDW0GwSWEtnuVxMFhcP3NrXN/vb"
    "8+dv8MT7BYh/ajYf2NfVNXXHzp3lfKUCjQYYA0a3BCRRC1eJw3Zdmzy+7t5okDKGzu7uYrS0"
    "dO9woTB7ZH5+7sMEiH8cGXnwznLP1F0jI+Xsygo0mwhj0GHIhStXCKwlcK5NFr+XtE28vrbG"
    "wtISeSlBa3QYooyh2N1daCwujven03PTlcrcewVMTsoHT5164O7u7ql7du8qpysVTBiCMego"
    "4vdXrnBqyxbmFxYY0LolYpP0OvLK6iovVauc6+ykfukSvUFAojVxGCKtpau7u1i7fPlAJ8ye"
    "bDTmNgWIu44d+9KBcvn7n9m9u5xaW8OEIc4YkjjmaKVC7qtf5bOHDuEGBnj9xRfpjyIC53Bx"
    "jEuSFvnaGr93jn2Tk9zzta9xfnWVy9PTlDyPxBjCtojunp7i0uLivc7a2QtxPKfu2blz4jO3"
    "3PLkJ/v7bwrW1tBtch3HvF6vU/r617n7y19GKkXPjh2YgQH+9NJLlNsDWq1Z2djgj6kUeycn"
    "2T42hlSKwbExLlarXJ6eJi8lsdaEYQjO0d/fX4izuTtDJV9RA573N/vLPfeX6nURhiHGGKzW"
    "rFpL4aGHuPMrX0Gqa6nSs2MHdnCQN15+mVKjQbXZ5LV8nk889hjbx8auttsUsVSvE504gdOa"
    "sC1CWsvy+nr2xPz8Ec/V62J9/l2WMhkC50gDaSFIpdNsLRSQUvL+suvTn0YIwR8OHULkctzx"
    "+OPcfB35ZvGUYkehwDtxTMNaYudIANtooFdWCIzBywCJtSzGMSlrSQtBBkiFIc3vfAftHIP3"
    "3QfivWvWLZ/6FP73vkfQ0cHg3r03kDutefenP+Xi4cPEUUQiBIlzJM5hAWUMAeD5QGgsl0lI"
    "W0sGriK9tET90Ucx1nLz/ffjoLXKtWYtO+7eDzisMddNZgHGcPknP+GtH/yAKAxJgBCIgNA5"
    "tJRo51CAJ4GmNSw7S4e15IFcGxqwKyscn5zEGcOW++7DGINzH/yDE0KicLz71FOcm5oialse"
    "OkcNaLQRS4m2tiUAILSWVWsx7UpJa34qQArB6vIyxx95hLBep2tiAj+bvc4T1yxPNjaoPPMM"
    "53/0I8IwJBGC2DlC52g6RwOoAaGU+O3+ngWiMGS1Vms1EoJOIWgIQVMIckKQFYJGvU7l6acZ"
    "37OH4tatN3hBSMniuXMc/dnP8FZWcFISW0tsDA3nqDtHzTnWraWhFP2ZDAbwonZcs3GMby0S"
    "SIA64NrPTaB7bIy7vvlNMjfdRLPZ/MAQdA4Nsevhh/njI49gZ2db/duW19vW14HY94k6OjCA"
    "6g2C/f2eNxGEoeh0jgJQaOdAFvCBwr59HHj0UbpGR0miGKMNRhu01hitr70nmvyWLeR27uTy"
    "iROYlZXWbqltzGZo00rhpdP6otbPqqJS+7cGwUQpDEXeOTqBPJAXggDIfmIvf3HoEKXhYZIo"
    "whiNMRptNLlcDikljXrjWn2SkO3vJzs8zMKbb+KtrpKSkhS01hggoxRhOq3nouhZlfa8/UN+"
    "MLElDEUW6JCypVAp5J4/Y+/DD1McGiKJIrTWbRg6s1miF17ALS7ibdtGrV7HbH5PEjr6+sgM"
    "DbF8+jTpjQ0CKfGlJAA6lGIxCPTpJHlW5YvFu/f2909sqVaFBwS+TyAl+d5exh5/DH/bNuIw"
    "arvcoI2h1NkJL/yKt777Xaq/+x09IyOwbRu1jdrVcCRJQn5ggMGhIeqvvIK0FiUlnpQEqRTL"
    "ff16No7/S/WWy5JU6pNbhOgqak0gJSnPwzeGcrFIcWyMtXoDnSQYoykXS2R/+98sTE2RiiL8"
    "MCScnqZnZIRk61aq1SpGGxCCvlRA8otf0Dx9GqUUSkqU77NQKHAqnXqjLsS/qdX19Usrtdpc"
    "XYjxkWKxWLSWQCkyQpCcOEHBWrJ3/DmrjQY9pRI9R/6H9SeeIIgi0kqRUQo/DNHHjtEzOko4"
    "MEAjjNiW7cA++SSV558nUApfSqTvM9/ZyW/WN2ZOriw/dHF5+Q0FECbJWef7ZzacGx8pFou9"
    "xtAhBB1SYt58kxIwOD5O55Ej1H/4Q/w4JuV5pJRqwfNQYYh77TV6d+2ib/s25OHD1H/9awLP"
    "u0p+KZ/nN9XqzAWdHLxYr0/D+3bFu8vlv77V8w7/XaGwfXuthuccHuBLScfgIHZxERFFKCEQ"
    "7c6bAzjAWovI5aBYJHznHQyt5TwSkhMdGX65ujpzztqDM5XK0U3O92xKlxuNs34ud2ZB6/Fd"
    "hUKx39rWFFIKr1olgKuWB9djM8OVQmmNrNXw2jGXnsfJXJZn1tZmLkh58PXl5aPXc96wLb9S"
    "q531CoUz58NwfFexWNzqXCsxlSKtFCkpW+9S4rcF+O0YX3/32gn3aibDU5XKzLued/DV+fmj"
    "7+f7wJPRlWr1LF1ds6cajQO3lkrFHdAiVgrP81pnQ99Heh6iDdk+L6pNcs/j5VSKf11enrmS"
    "Th989dKlG8g/VADA8vr6WVsqnTler4/v7u4u3uz7CM+DILgG3wffx/k+eB7O87Ceh0mleMH3"
    "eXxhYWY5nz8489ZbH0gOH3c4BYaHh/9qrLf3iX1Cbk/XNlyXEBSAjBAEQuAB2jlioOEcVedI"
    "iiXxYqN+8rWVlb+fe/vt6Y8a/2MFOOfE5yYm9lbm50eDOKZHKTqVIqcUGVouNEBsDDVg3Rhk"
    "Pu+yfX0z//Hcc2c+bvz/BZALwYu3Z1YVAAAAAElFTkSuQmCC")

#----------------------------------------------------------------------
_help = PyEmbeddedImage(
    "iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAABHNCSVQICAgIfAhkiAAAAtxJ"
    "REFUOI2lk81LFHEYx5+ZndnWnV0bt8z2TYKpxYsdwpBWA62w2rxIdOgmdPAvCOnqMSiig2SB"
    "lVmeAhEsJt02SNdcXZXC1HYT3SRWXLd1HHdmduf3ezqUgrjQoef08MDzeZ7v8wLwn8aUCn69"
    "fNntWl9vsrrdR4pra2lDEN5Xf/qU/ScgMjR09PTjxw/sLS03+YYGFmw2QF0Hc2KisJXL9Sxf"
    "uNAZDAa1koBIJHJcFMUxKZOR+EwGVhHBQIQT5eVgzedBb26GX6o6kc1mL9XV1eV389hdxzU+"
    "/tzpdErfnU6IiaIunD+/6Gm5MhkXhLEvXm+6QAiUT02d87W1PTygY76pqT4jipjq6EBZlrfz"
    "eW1S1/U5TdPnVFWLxuOzTz7L8s5GfT2mRZEkPB7/vg7sq6vXiKLAyswMSNKpJUIIFosUCSEM"
    "pdQhSVJdQlXDRlUVmIrCWnO5q7sADgCAFgp+k1LQ/X4wjAKqO1qOs7B2lmVtCMBQgmYqlVo+"
    "K0mAlAItFj37OqAMkzMBwC8IIMvvOGISq6YZRUXVthQlvzX6fnSnoqJiAbNZMAHAtFi29wEM"
    "QYgQAODDYQj4jqfu37+3MTYeLZuNz1r7XjyHvme9ou3QoY5iNArkT8GP+4Y43dPDL9rtiW+h"
    "EC7FYnRhYeFee3t7sLa29szw8HAg/ObNYGsohK+fPsXk9etRRNxb/54T6+0NHm5oCPMcZyt2"
    "dQEbCCBbVbXDpNMOY2AANi9ehLsrK+Dz+e52d3d3lrzE6enpRlc8/pKV5WpEBCQEkFJASqGw"
    "ubn4qrn5dmxm5lFlZWV/f3//HYZh8MAvDLW22k86HDfsktTEWK3H6Pb2T3V+fvRHIjEYSiYN"
    "j8cTqKmp+WCxWG6NjIy8LfVMjNvtLlMUxWGapgMRbYhoRUT+79AJAHA8z6e8Xu8mVwKAjY2N"
    "RiwWo6qqaqZpcoQQy65clmUJx3Gmy+Uykslk4TdmSW8/+y1ZpAAAAABJRU5ErkJggg==")

#----------------------------------------------------------------------
_information = PyEmbeddedImage(
    "iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAAABHNCSVQICAgIfAhkiAAACINJ"
    "REFUWIWll1uMXVUZgL+19u1c9rnPzJmZzkzb6YVSgdK7gEorWCoID0QeNWJ8gxf0RaKJMcbE"
    "F19UQkwUiG/6QEJ8oEBoxdhqsRdAqEUovcxMO9Nz5pwz57bPvi4fzp7p6bRIiX/yZ+/s7P//"
    "v/Vf1l5b8PlEh4eGdX1qwsilR/WEkSeEwA+X/KXWlSC4NAvVKpz0b9WhuLXXDg7nJ++8Z2j9"
    "2gNj60Z3jI0VJ4uFTDaVMgwUdLqeX6u1W1fmFmcuX5g/dfX87OvtK+8eg0OV/xPgYLY0vf0b"
    "63fc+b1tOzft3r51wl43niOfNjF0DRlbRwr8IKTRdvlkrsHpf8103jn50dvnT5/9fePSyT/D"
    "oebnBrDtJ7dO7N37w737dz7+lb2b0lMjWQwpiCJQ6lOcCZASgkhxYb7B4WMfdt4+fOrlS6dP"
    "/MJrv3jmZjbazfzkyk/t2/r1A7959Jtfffj+3ZvNjJWk5wkcD1wf3AC8m6jrQ88DzxfYySSb"
    "p8fMwprRba3I3NOqjPzH6564+JkA+aGnv3zHwweef/ix++/eMF6m51wL7AXg+XEgH8IIghC6"
    "3vXPXa8P4vuSkVKe4Ynymrqn724ulD5YDXEdQMb81uYtjx58bt/BfTuGs0Va7b6jQcduHGhy"
    "GPZsho3j/TrOVKHTi4PH7zseOC7YyTSFsaGRxW60tXs+ddQL36veBOB+e3r/Iz/bc2D/Y8O5"
    "IZrNCNdTuL6KIRQ9T9H1oJSFR/YIhrJgJ2BNCa424NwVhRsH7nngeH2bjqtIJlJYeXtNdcmx"
    "G7ONN2HGA9CXw49uvO+hDbu2P5G3s1QrTVQEQggQAoFAiH6XKSXITxnYCWsFXUoYzQe0Oy6g"
    "4ia98TqULzK9c9vjjdnZV+szx/44APBgbmzbnU8Oj49la5Umfs9HCEk/vkQIsaJKwXw1gR+Y"
    "GPq1IVpY7NFsthAClOoHVSiUUqD6V6lJyhPjmfLWLd+pzxx4A16v6QAjU3fvLq1bd5/X9enU"
    "mqhIIaVASIkUEiEFMgYAwYkzHTaMwle259A1wZnzXV47XqHV6m+AimtBo0ihVBRDKYyURXFy"
    "6t7C6F176vOvH9IBWdiw7kEjnc1X5iv0Wm2klCsqhByA6Zek2YLfvtzk1WMJTEMys9Cj3Q3j"
    "1bMSrK8RUaSIoogoitDaOpZtZ7NrJx6oz/O6DgfyyeHRXY7jU1+4Sui6aJoWA2hIKWIQsVIO"
    "BBi6RrvdWtmUPD+K6x2nP151FCkiFaGiiDCMQECyWMIqDu2CBwq6bU+W9UxuammpQ6NWR4VB"
    "H0DT0KRcKYOUfQCAcinF9799O2tGUigFjhvw/J/OcvpsFSnEtZUrhYpXPqi+ZqDbmUnbnirr"
    "meHikLCMXHepi+M4CKXQtOXVywHtA0QKRgo59u0qk0qsDBFH3p7l7+/MoUlWMrBc/+XAYRgR"
    "RSGi65BMJXNWbqisi1QiH7k9q335DJ3qHHqihG7ZaJpxfS/EjRgpCIJg9QZKFIZ4nosmxXXN"
    "N1j/ZQjZc0nYKZOEldGFkCFCqaA5gzN3BKVl0FKj6MkR9EShD6Mn0HQDKTUiJfADH1Z9kIIw"
    "xHU9NE2gouUJCInCkDD0CQOX0GsT9GooL4ud2anQDaV7ftBASldL5kEaKL9N0J4lcBZBSyH0"
    "NEJPI40UUk+iMGg3zP6oDUiv22apfhVNKFTkE4UeUdAjCrpEfgcVtFBeE8I2CeMLQOiJyFvS"
    "e61GFUHdygyXNTNHpDqgJUD266siD+VDFPoguhBJ3E6pv8EMiOs06dUug6boG3h9VW5874IK"
    "EZqFaY+ghF53O+0F2bp8bj7we58kC2MY6TLIBEhr4GqBNEHoIDSIJ+EGURGwrP1tGyFjO6Pv"
    "Q7PQrDyJwgRKRRdaly8sSDjUdBq144l8kWRxHRip/ssrEKs1BlotQh+wM29i01czO0ayNI7X"
    "aR2HV5YkQH1u9rBuaZXM+BbM1BAI8zqjFdWWoT4N4GbZi1WYSDODPbIJPZle7FxdeBNQEqBy"
    "/K+nndbi4cLUNOmRzQg9FUOsBknE/WFww2lO6gOAgzbXspnITZCbvA2/1/lL9cS5UwBxQd/o"
    "VM99+IKR0iql6btJFiZiwwHVLIRmgKYhpLzhMCmkAKkhNB20ATthgjAw0iXyU3dg5TPVxtyl"
    "38ELrQEAuHLk8FuN+QsvldaOR8X1OzAzw/3miTMhpN7fioVEIYhWTYFS/ROpiL8hyLjxpIGW"
    "yJJbs4Xi+umoXVv4Q+WtN44s2w2ciD4Ou9H0v7OTI7fnxtZvCgMTz3EIwwghtdixxLIspGZh"
    "p5NU6i4fX2ryztkqrxz5hMVGb+UjJIRAIdCtFPnxacq3byEIm6/NnTj1o6DyYm0lc6t7yf7S"
    "z7duuue+5zRjZN/CR7PUZ87hNGsIFKlUimw2S9q2SSaTJEwThCAIAhynR7fbpdVq0mq1CMMI"
    "I2WTLU8yvGGSUDWOXjx14qnu0WffHYx3w6nYu3S40k5s+mdmNLe2MDG5wUoNSSk0TEMjZ9vk"
    "83kKhQKFfIFMNks63YcxTRNdjzNlWFi5IUrrN1HaOB56fuXVmXdPPdP927Pv3TA8qx8sS/Le"
    "n4yv2bH96eLo+u8KL1mm7WCFLildkE4kSKdSWKaFkALfD3B6Dh3HoesFOGh4CZNA967WFy+9"
    "dPXU+79y/vHjuZvF+d+/ZlufMEvbD9w7tm7jk7nC6NcKCXu0kEiIgmWQTZqkTAMpBD0/oNnz"
    "qDku1a6jat3WQq02/2bl4sUXFk+cPsrHv3Y/LcSt/Zx+8ZlkdsOWO4pTU/vz+eLefCY7nUmm"
    "iglTSwL0/NBZ6nZrS83muaV67XjtyuxbzQ9m3+fkT7uf5foW/44H5K4fpLltsmTkckVlmDmA"
    "oNdr0G7V+XBmkfd+2fk87v4LLAgo84Gt5eYAAAAASUVORK5CYII=")

#----------------------------------------------------------------------
_no = PyEmbeddedImage(
    "iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAABHNCSVQICAgIfAhkiAAAAelJ"
    "REFUOI21ksFL03EYxj/fX1tuWEtxW0ZulbbpKYutIYM6CIFEimh2CUFIKKhLpxCKSPwDunSI"
    "IOgQSh48dq5DB9EiVik/NaHBYrRm5HTG2u/pMAsTiRb0nJ735X0e3vfhhf+FC4dpT/WioWY6"
    "/8ngfT8reoXsXtYBd1XigTDnc/frJeW18iigoSOMAOavxEehZm4QOYXHymRmVV6b1PIlFPFy"
    "cKf5Xdsb9gD3gtdisdlcn3n+LEXm017inRniSx+iD5eY2D5vbS2uNBP8coDLnuRd46kpUiqV"
    "8O0p4YqNETrOudONxP9ocP0Y0y13uoAyTU0W+fxXmkIWsEF4pIsHSZ4CNTsa3G4n4TvjPkTd"
    "MPARv3+VbDZHJLIBpGFfD3Vn3Q1XW+lnS6A/iZnrw2mb7AYruRmNmJ7+TCJRC2wAa+DMsHDx"
    "BdEJGoD8rw2W+7gRvuUCyw8sAPMUCm8ZH39NNpsC5gEbLC+hmy6enGLst/PfDSKpVdJJSR2S"
    "OjQ1dUKRSESjo1FJbZJaJIUlBWQPIyAAwJseZuQYSQFJ+yU1SmpUWUHZi34Vv9VL8kmqleSR"
    "tFsSetnNIuB2GbDtQcWMexWMwRgLpM3dHNKOU6FykASq1OvfSQNes3mL31vdv5tiJdl8FZqd"
    "8QO3F9ZRFEVpTAAAAABJRU5ErkJggg==")

#----------------------------------------------------------------------
_ok = PyEmbeddedImage(
    "iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAABHNCSVQICAgIfAhkiAAAAjdJ"
    "REFUOI2tksFLk3Ecxp+97975vmuve1dWuiUTNIy1JlsLpkZG0aXLbv0B0aVDUMfVQTp0jJpF"
    "EHl5LxUZgZcuQjAID4KUyWwyEU3d9m7O5d733dze97dfB1siJSn1nJ/P5+ELX+Afwx6YuAMB"
    "AVgwjcaBBdIovP2eyKMLPYNdM+7kNKZA9i3gR+ENCeF4Hx+8VigVBgrKWrXKGp/2JeCfwhsW"
    "Q/HTQiCaVTOYUiZtDuoMQqefrc1S9+uOEGNSRzqd+4j72/c1l4OOQNwn+aOFWg5TdBJEIKbH"
    "dI9zHLMt6H3lHrjScfU5x3DSmOXNrVUUxwFQ6S3vDdh9cZ/zTHSz8R0pMguGMKaRMuX5peQ9"
    "ZULPW8+PnB286L78zH/M76/DwCYtjSTefaAOQZjpEDofn5J8UR0qViqLoCpLql+IXFzS72IC"
    "eQCwssR2NFfOtNXsFZx09SLkDnfSlsYTluUy7a3Hz6mWMrLGKswiJaV0WS6Uyr9gAGC7It0L"
    "WrWYm99K9VdcqugSD8Pd6nG6RNeJCq9ZstwqNL1CMl/z8npdiRkPd2AAYJcTy41FcSVZt+lK"
    "na9FaLspCg4ehDew3qJgs6qStUxerhItlr+h74KB5iPNgVZuGkm6QpQWmy3i8AoiY7dA1XTy"
    "LZuVGYHGZi8t/gbvCABgDFS7vpVEgSgS29bv5CR7XtmQjxxyxt77En+Edwt+Svpua3MbRT5T"
    "a9QXPGL7gxc9L/eE98wwHWaG6JD1783/kB9qTvueLt8LjwAAAABJRU5ErkJggg==")

#----------------------------------------------------------------------
_question = PyEmbeddedImage(
    "iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAAABHNCSVQICAgIfAhkiAAAB/pJ"
    "REFUWIXFl3tsVuUdxz/PubyXvu3b2hugKAobaYHJpYZLghMdEzsnbKhxGidzuMVkExedG9ni"
    "0Jm4kGWpIsmyyz9go1lkGzC5KAFLkSJQuUwYtEBx3Au0pX1p3/c9z+W3PwoJoiCgyb7J8885"
    "v/P7fM5znjx5DnyBFBUVlZWXlw/6Ij2uKcOHD6n60x//vGrVilWdq1e907N4UX1jVVXVuGvp"
    "pa72gdLS0huWL3v7o492HSjZ2NRlAO6aMiAYOWpY78yZM8YdPXp039X086+meOrUqdMXLlz4"
    "zrr3Wq873p7mhsE3+el0md/S2svJ9mOxF194ZvaJEyeOtbS07LjSnlcyA/6AAQPK5s6dWzdp"
    "wqRH/rl8q43Fh/nxeICODFo7nHP09OQpK+0xP3z8rmDNmrUrfzn3uSe7urqOAQ6QKxVQgNTU"
    "1IwfWDFwaM1tNbcPrxo+prJi4KSW1g7VdjDnSkoqvTD00VpjjMNoizYO64SengjoddO+Ocyb"
    "OP4W/nvo4JZNH2z9d0PDhvVtbfsO7N27d9PnzsD8+b9/vfaeex89fPgYx46fYs/eTpPLJVR5"
    "+fV+SUmMbDbCWosx/UNrhzUOYy1agwicOp1FXMaMHVuppt39NW/EiGEqlUrw2msLV86Z89S9"
    "lxSYN29e7L5vfye/fMUOp6hU8XiI7wcqFlMYY9Da0NeXQxtDqiAkXZRAedDdneXY8QzZrCEM"
    "AowRtFGcPRthjRHnYML4cnn++fu9Z599pqyurq7zPDO4UCCVSpVGUYQzcSoqi5XWEc5Z8nmL"
    "tZZ8LuLWW6/nG3dWU1qWAsA5i9aankwfS5fupKFhP54f4izEYgrrh0qc4uNDvSgFQ4cOvRn4"
    "bAHP89LOWfr6tDNGe8YYnHM4ZzFGE+mI6feNxvc8+vpyWOvOrQWLMYYZM0ZSXByydNkewANR"
    "IOBEYXT/ZBcXF5ddyPyEQEVFRVopD21UoCOLsRbnLNYZrDUYo9Ha4MVDtDZ0dHSTSMRwzpLN"
    "5ejry3LjjUl279qHMUlQAZ7n43khAwekFEAyTMYvKSAiAoJzoI3BGIOcEzBGY4zmzJkM9fXv"
    "0rD+PxxoO4E1lhdffJgxo4eQyZwln89SVhZy8GCOWCyO8gTPU+TzWkRQVll1SYGurq6z4sA6"
    "64yxnjEWaw0ipv8ts3lqv/Vb2k924XsQBAqtLe+8u52acUPIZDJEUYRSGsFx4RYQhB5KQS6X"
    "y19SoLe3t8fzPQJPMMahtUWk/ztv2dLCkSMncC4iHvMRsYAjn88xacJwTrSfJpPpxRjN4SNd"
    "BEEJguAJIEIyESBAd3d3xyUF2tvbO33PI10cqEhbnHN0nzlLw/pdRFEWpRRKeThncQ5y+Twz"
    "ZkxkxMgBnDzVhTjD1q0HyPZ5JBICCA7BA4oKQ9XV0cnx48c/vpD5qY1o2dLlLdt2ZIZ39xRw"
    "9PBJPtx+EBGNOI11EWIjHIZ8NsfPf3EfEyfczKlTHVhraG09yoIFTRQVVeJ5MTw/hu+HOOvz"
    "yCOjZMqUis47p3y9/EKed7HA2nXrlg25qYgjR7rZvvM4nhcDAkQCxAUIAVEeam4bzqSJQ2hv"
    "P40xmra2k7z66vsUpCpx0l+P+IgE9PU5xowZojZ/sHnrxbxPCTQ1vb+iumoQ27YdEoj1QyWG"
    "SIgQIi5GX59i2rRRdHZ2o41m9+4jzJ/fQCw+4BP1TmKIBCiFfPUrxSxZsuSvnyvQ3Ny8MQjs"
    "qZEjCqyOgnNNYogkwCUQEiiVZNCgJLlcDoXjrbd2k0hcjyKOcwlE4ojEQWJEkU9VValLxG3U"
    "2rrnvYt5wcUXAPdh87amBx6omr59+x7xvLgS8RHRODxEfHwfPmw+QSKp0caSySRQqgARDwhB"
    "QkQCnIREkWX242Np3NC0paenp/uKBJb8Y9kbb77x+owFC9pcR0eoxBmcBCAhTgzJZJy6Vw7g"
    "+xZnHcUlpQR+gKgQz/MRF+JUgCc+lRW4CRNv9J988nd/A+zFsEseSBoaGg9t2do1eP780yqZ"
    "FKxziNU4sfT2ambNGkhNTYIo8nj55f1ksyGe56GUj+cF+L5PNgs//Um5TJxYkK+tvbvwswQ+"
    "tQbO5+mnn3rsR09MUoMGZazWBYhL4iSFMSnuuGMQ06cXUF6epKbmBub9ppoz3QqRQsSlcK4A"
    "rQsoLTPuwQduUS+99MITnwW/rMDOnTs3rF69bl394nuUsUYghXOFOFeEUiFF6RTXXVdKuihN"
    "KuVjdKz/vhQikkJrJXV/GCVNm7Zsa2pqeutSnMsdSqWxcf3GuXOf+7HndQZr1igViyWBkH2t"
    "AWFoGDw4xv59Xfzq1/sRNwRIoFSc3l6fx76PTJ5c5s+Z89R3z5w5c+gynMunurr6dmu1zJ5d"
    "H8UTDVJSsl7S6fWSSjVKLLZa4vFVUljUKEXpRikuaZREslFmznzTtLbskvHjJz18zeAL89BD"
    "Dz8n4uQHj79tlGqSVOEOSRVuk1Thzv6R2i6FhdtFeVtl+ox/2b17d8msWbNf+VLg53PX1KlP"
    "iHNSV7dSQ7Mkk22SSLRKItEqyYIDArvkZ8/8Xe9r3S0PPvjQy18q/HwmT77je21t+zs3NO6W"
    "cTXrDbQ6OOCqqzfaRYsapLn5Az11au3T58qv+q/ripJOp0sXL67f2d3dJWvWbHEr3t7k9rW2"
    "SH39m0cqKiqGXW2/a7YcPXrso7W1tfd7HsHatQ0rN29u+gtgrrXf/y3/A9AbS5RB5/OZAAAA"
    "AElFTkSuQmCC")

#----------------------------------------------------------------------
_reassign = PyEmbeddedImage(
    "iVBORw0KGgoAAAANSUhEUgAAAAwAAAAMCAYAAABWdVznAAAABHNCSVQICAgIfAhkiAAAAcRJ"
    "REFUKJGdj01Ik3Ecxz///565KcvkcUwedtiWRFRUprTAxxZLq0MRzBy5IIoShF5cp6BLBF16"
    "oU4RnQK7BC2WtEOLGLJkvdGbBzOFEqpLRXhYbZLu+XWwt3Mf+B4/H/gqFlkOnAU+AGFgDlgJ"
    "zABBIC0ij5RSAoDH485lr52SocHdMv7giqR6e2SyeFn2JLrlWf6SWIHGj4VCoRXAAGhb17Yz"
    "urFTFnSTevn4KYnePqamp0j17+Xzl3esWdseFJFlwFsDQGmD4KrtyvzkZf/h05w/18GOXScw"
    "dA2UG9/tNwALADqTySQrlW/kcncYyd5ia3w9kZYaN65fpVwu43Y5gKCUUgA6mUzePHRwQIpj"
    "BZY2NXD0eBq7qwNrySxjo/eo1Ry01vzGABhKDyjmRsCoh9nvUP2KUZnm7pMJujZv41f8r5A+"
    "sk9ejWaVUddAIh4httrF5HuLwWMnsawWHMf5I+hSqWQXSzPqwvBzuvvPcHF4gvuvG1nReYBw"
    "OML8/A9EBBERAMO27YexWIzohnY8dS7GX/TRuilFfEsP1WoFr7cen8+H/vcIUAmFQmKappim"
    "Kc3NfvH7FxcIBASQfD4f5X/4CVPZn52VDH4mAAAAAElFTkSuQmCC")

#----------------------------------------------------------------------
_warning = PyEmbeddedImage(
    "iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAAABHNCSVQICAgIfAhkiAAABohJ"
    "REFUWIXVlktsHVcZx3/nzJyZ+7RvYjs3Jtj12773xokfcV4VCgopArUisEhb8ahIg9ImAYnn"
    "glVggRCgbtghVqxYVCwQokh0gSDQNhJSC4iIUpREbWM7iePHffnOnJlzWMy1Y9RWTdxmwZGO"
    "ZjQ65zu/7/t/33cG/l/HTx4pZv/0s/OHfvXdR/ceA3e7duR2Ns2CGhrpuVgeUi/uL2V+f+pT"
    "hSe2C+BsZ9NXZ51jhz4x+8PBoVSh0KHyrfV4gP/M/+61GtX7tXXfEXgMMmNTE+eGxnu7CBpI"
    "GzC+r3/64HTX5+/X1rYAjh5KnxidKX86q1rYYB3COsUeJSZnBp++8BHGHijAWegcnqpc6H9o"
    "Ry5er2MjDVGIiGqMT+4Zm5zp/jIgHhjA4MOFk2NT48dUvEYUaEygsUEAQYOenYK9s4Nf/OYI"
    "Uw8E4MwuiiPTlWeLxYwfNKtEOiTWAUaHELagtcxEpdg3Xuo+y32U5T1XwRNz3WcOHj/8dE4u"
    "S6PXEXEIUQtpQoSNEEaTyfoE1h/ouDH/0ivLvPmhAXylyODBE3PPTUwUinH9NjaKMG4ekxtE"
    "qx6ErqFMDUxIrqsnc3Oxml56vfnC2xB9KACPH+79xpETs6fS8U1MFGBNROHo19jxse+QnjiJ"
    "DKsw/zLCaNIZRSSyA2sLC6++cod/v5/t982BC0NMlmfLT3XnQ0zQQBiNiCOkmwEhEdIBN02s"
    "Y2yooX6T0nguN1HadeEUdH5QAGek1PfMeLl3gPpionWsIY7Ams1FcWyIwgijI1hv0qlvMF3J"
    "fXywzGc/EMDXxzhcmpl4vODXsbqFsBqMBhshuAtgYoMONXGzhVlagRvXKPeG/uho4dypHnZv"
    "C+AYpEYrwxfGRnf20LidHBprpIlxrIatAFGEXq0TLq5g1lrQMuSiFWYq+bnh3fLJbQEcqTgn"
    "StODj+WdVWwcIG2IayOU0CipkdjNtbbRwKw0sdpgaavTaFDq1XJ8NH/2qR6G7wvgC9AxPDl0"
    "fmQglxfrK7hEKJFMT2o8GSHF3Qg4GBwJUm7pwwbS0SoHKtlS3x7nNO/Rot8VYOBA6mRlsu94"
    "Xqzg2BAldfvwCF9ovGYNGbY21ytH4LvgSBAimQCEmtHdEaWx3JdO72HfPQGc2UVxrNR/fqhP"
    "+VLXUCJGiRhPRCjdQC0v4a8u4zSWIA4gauFEa6Q9UC5I0fa1DeHHDQ6Us/39u9Uz7/bn9I4P"
    "Dw3nn5zcW5zLsopE44oIGbeQa6vIejUR2AMu/xjz+vNgLfLOvxDpJOzYtltCJBBRxPCukPJI"
    "9tTNW6u//ONbXNp63v90wnP9DM0dGnhuZm+u6JkGrtC4jTXkyi1kq5Hg+i54LutWUevcT2AV"
    "snYVVwGuTCwKwBFJUkiJlIZ0Pp25vhBkuoX57ZXq3Ra9NQJicCh/erJSKGeoI3UDuXob2ayC"
    "YyHlglLgKqzjIQ5dZOfss9g4RF+6CFd+nkQn0qDbZbqhR2wY6AqpjKYfXbxT+yTw63dE4Ntl"
    "puZm9/xo34jX6awu4txZQOomQgnwPfB9SKXBTyOyXbgz5xG5jyKki2vWYOESOE57bkl4mWSl"
    "wJDLKu/qQtTV55jf/G2N1ibAWVDj09mLR/ZmjnfU3sZZW8YRBuEBvoJUClIZ8LOQyoLyQWWg"
    "MAbBMlx9HpoL4Kh2LbYBrAGx0S8sHVlLdV323ViMrl2+w6ubAJ/Zz7HJPr43mq6mVdRCKZBe"
    "W28/1fY8C6kcpPLJXF+Apb/C/B+gfh1cD5x2GQjaBxswBqwFC0IaOjI41+bNnqKxL/yjRtX5"
    "1j6yo7vFD6Z649mOlEGpxJG7oU+BnwE/B34e/A7wO5N3YUFacFPtTRve28R7a5KLK443v+VS"
    "hmYoelea7s0/L8R/ccdmKuWZPh7e2fwnbltC4QBKJoXt+eC1I5DugFRnAqBy4PpJkhkNugGB"
    "l+gvLBDBxuVl2hDWgrUc3VcQdnjuc7fc137hukJkTL7bW1rxcdZDXF/ieBIReBCkEE0FnpPU"
    "vq9BtUA54MZtnRIAG7UgamJDjQ0NhBIbKgh9RGiwYYA1CYSXd8jms109O7Od7uIb16+8tLb0"
    "07Aqh3TdxtIxsSuMkdIY6bSMFCsGgZHILX1z4yVJNmNs+2kSyQ0YDAbkjpTp7PDIxQYHkNZa"
    "4eYbznxw6fJbbywtii0WN6za93huZ4izszhHckmyZwPESjei+iai/neC79/DP+MDH/8FsY6a"
    "7HCEfEAAAAAASUVORK5CYII=")

#----------------------------------------------------------------------
_yes = PyEmbeddedImage(
    "iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAABHNCSVQICAgIfAhkiAAAAjdJ"
    "REFUOI2tksFLk3Ecxp+97975vmuve1dWuiUTNIy1JlsLpkZG0aXLbv0B0aVDUMfVQTp0jJpF"
    "EHl5LxUZgZcuQjAID4KUyWwyEU3d9m7O5d733dze97dfB1siJSn1nJ/P5+ELX+Afwx6YuAMB"
    "AVgwjcaBBdIovP2eyKMLPYNdM+7kNKZA9i3gR+ENCeF4Hx+8VigVBgrKWrXKGp/2JeCfwhsW"
    "Q/HTQiCaVTOYUiZtDuoMQqefrc1S9+uOEGNSRzqd+4j72/c1l4OOQNwn+aOFWg5TdBJEIKbH"
    "dI9zHLMt6H3lHrjScfU5x3DSmOXNrVUUxwFQ6S3vDdh9cZ/zTHSz8R0pMguGMKaRMuX5peQ9"
    "ZULPW8+PnB286L78zH/M76/DwCYtjSTefaAOQZjpEDofn5J8UR0qViqLoCpLql+IXFzS72IC"
    "eQCwssR2NFfOtNXsFZx09SLkDnfSlsYTluUy7a3Hz6mWMrLGKswiJaV0WS6Uyr9gAGC7It0L"
    "WrWYm99K9VdcqugSD8Pd6nG6RNeJCq9ZstwqNL1CMl/z8npdiRkPd2AAYJcTy41FcSVZt+lK"
    "na9FaLspCg4ehDew3qJgs6qStUxerhItlr+h74KB5iPNgVZuGkm6QpQWmy3i8AoiY7dA1XTy"
    "LZuVGYHGZi8t/gbvCABgDFS7vpVEgSgS29bv5CR7XtmQjxxyxt77En+Edwt+Svpua3MbRT5T"
    "a9QXPGL7gxc9L/eE98wwHWaG6JD1783/kB9qTvueLt8LjwAAAABJRU5ErkJggg==")

[docs]class StdDialogButtonSizer(wx.BoxSizer):
    """ wxWidgets standard dialog button sizer. """

[docs]    def __init__(self):
        """ Default class constructor. """

        wx.BoxSizer.__init__(self, wx.HORIZONTAL)

        self._buttonAffirmative = None
        self._buttonApply = None
        self._buttonNegative = None
        self._buttonCancel = None
        self._buttonHelp = None

[docs]    def AddButton(self, mybutton):
        """
        Add a button to the sizer.

        :param `mybutton`: the button to add.
        """

        buttonId = mybutton.GetId()

        if buttonId in [wx.ID_OK, wx.ID_YES, wx.ID_SAVE]:
            self._buttonAffirmative = mybutton

        elif buttonId == wx.ID_APPLY:
            self._buttonApply = mybutton
        elif buttonId == wx.ID_NO:
            self._buttonNegative = mybutton
        elif buttonId in [wx.ID_CANCEL, wx.ID_CLOSE]:
            self._buttonCancel = mybutton
        elif buttonId in [wx.ID_HELP, wx.ID_CONTEXT_HELP]:
            self._buttonHelp = mybutton

[docs]    def SetAffirmativeButton(self, button):
        """
        Sets the affirmative button.

        :param `button`: the button to set as affirmative one.
        """

        self._buttonAffirmative = button

[docs]    def SetNegativeButton(self, button):
        """
        Sets the negative button.

        :param `button`: the button to set as negative one.
        """

        self._buttonNegative = button

[docs]    def SetCancelButton(self, button):
        """
        Sets the cancel button.

        :param `button`: the button to set as cancel one.
        """

        self._buttonCancel = button

[docs]    def Realize(self):
        """ Realizes the sizer depending on the platform. """

        if wx.Platform == "__WXMAC__":

            self.Add((0, 0), 0, wx.LEFT, 6)
            if self._buttonHelp:
                self.Add(self._buttonHelp, 0, wx.ALIGN_CENTRE | wx.LEFT | wx.RIGHT, 6)

            if self._buttonNegative:
                # HIG POLICE BULLETIN - destructive buttons need extra padding
                # 24 pixels on either side
                self.Add(self._buttonNegative, 0, wx.ALIGN_CENTRE | wx.LEFT | wx.RIGHT, 12)

            # extra whitespace between help/negative and cancel/ok buttons
            self.Add((0, 0), 1, wx.EXPAND, 0)

            if self._buttonCancel:
                self.Add(self._buttonCancel, 0, wx.ALIGN_CENTRE | wx.LEFT | wx.RIGHT, 6)
                # Cancel or help should be default
                # self._buttonCancel.SetDefaultButton()

            # Ugh, Mac doesn't really have apply dialogs, so I'll just
            # figure the best place is between Cancel and OK
            if self._buttonApply:
                self.Add(self._buttonApply, 0, wx.ALIGN_CENTRE | wx.LEFT | wx.RIGHT, 6)

            if self._buttonAffirmative:
                self.Add(self._buttonAffirmative, 0, wx.ALIGN_CENTRE | wx.LEFT, 6)
                if self._buttonAffirmative.GetId() == wx.ID_SAVE:
                    # these buttons have set labels under Mac so we should use them
                    self._buttonAffirmative.SetLabel(_("Save"))
                    if self._buttonNegative:
                        self._buttonNegative.SetLabel(_("Don't Save"))

            # Extra space around and at the right
            self.Add((12, 24))

        elif wx.Platform == "__WXGTK__":

            self.Add((0, 0), 0, wx.LEFT, 9)
            if self._buttonHelp:
                self.Add(self._buttonHelp, 0, wx.ALIGN_CENTRE | wx.LEFT | wx.RIGHT, 3)

            # extra whitespace between help and cancel/ok buttons
            self.Add((0, 0), 1, wx.EXPAND, 0)

            if self._buttonNegative:
                self.Add(self._buttonNegative, 0, wx.ALIGN_CENTRE | wx.LEFT | wx.RIGHT, 3)

            # according to HIG, in explicit apply windows the order is:
            # [ Help                     Apply   Cancel   OK ]
            if self._buttonApply:
                self.Add(self._buttonApply, 0, wx.ALIGN_CENTRE | wx.LEFT | wx.RIGHT, 3)

            if self._buttonCancel:
                self.Add(self._buttonCancel, 0, wx.ALIGN_CENTRE | wx.LEFT | wx.RIGHT, 3)
                # Cancel or help should be default
                # self._buttonCancel.SetDefaultButton()

            if self._buttonAffirmative:
                self.Add(self._buttonAffirmative, 0, wx.ALIGN_CENTRE | wx.LEFT, 6)

        elif wx.Platform == "__WXMSW__":
            # Windows
            # center-justify buttons
            self.Add((0, 0), 1, wx.EXPAND, 0)

            if self._buttonAffirmative:
                self.Add(self._buttonAffirmative, 0, wx.ALIGN_CENTRE | wx.LEFT | wx.RIGHT, self._buttonAffirmative.ConvertDialogSizeToPixels(wx.Size(2, 0)).x)

            if self._buttonNegative:
                self.Add(self._buttonNegative, 0, wx.ALIGN_CENTRE | wx.LEFT | wx.RIGHT, self._buttonNegative.ConvertDialogSizeToPixels(wx.Size(2, 0)).x)

            if self._buttonCancel:
                self.Add(self._buttonCancel, 0, wx.ALIGN_CENTRE | wx.LEFT | wx.RIGHT, self._buttonCancel.ConvertDialogSizeToPixels(wx.Size(2, 0)).x)

            if self._buttonApply:
                self.Add(self._buttonApply, 0, wx.ALIGN_CENTRE | wx.LEFT | wx.RIGHT, self._buttonApply.ConvertDialogSizeToPixels(wx.Size(2, 0)).x)

            if self._buttonHelp:
                self.Add(self._buttonHelp, 0, wx.ALIGN_CENTRE | wx.LEFT | wx.RIGHT, self._buttonHelp.ConvertDialogSizeToPixels(wx.Size(2, 0)).x)

            self.Add((0, 0), 1, wx.EXPAND, 0)

        else:
            # GTK+1 and any other platform

            if self._buttonHelp:
                self.Add(self._buttonHelp, 0, wx.ALIGN_CENTRE | wx.LEFT | wx.RIGHT, self._buttonHelp.ConvertDialogSizeToPixels(wx.Size(4, 0)).x)

            # extra whitespace between help and cancel/ok buttons
            self.Add((0, 0), 1, wx.EXPAND, 0)

            if self._buttonApply:
                self.Add(self._buttonApply, 0, wx.ALIGN_CENTRE | wx.LEFT | wx.RIGHT, self._buttonApply.ConvertDialogSizeToPixels(wx.Size(4, 0)).x)

            if self._buttonAffirmative:
                self.Add(self._buttonAffirmative, 0, wx.ALIGN_CENTRE | wx.LEFT | wx.RIGHT, self._buttonAffirmative.ConvertDialogSizeToPixels(wx.Size(4, 0)).x)

            if self._buttonNegative:
                self.Add(self._buttonNegative, 0, wx.ALIGN_CENTRE | wx.LEFT | wx.RIGHT, self._buttonNegative.ConvertDialogSizeToPixels(wx.Size(4, 0)).x)

            if self._buttonCancel:
                self.Add(self._buttonCancel, 0, wx.ALIGN_CENTRE | wx.LEFT | wx.RIGHT, self._buttonCancel.ConvertDialogSizeToPixels(wx.Size(4, 0)).x)
                # Cancel or help should be default
                # self._buttonCancel.SetDefaultButton()

[docs]class GenericMessageDialog(wx.Dialog):
    """
    Main class implementation, L{GenericMessageDialog} is a possible replacement
    for the standard `wx.MessageDialog`.
    """

[docs]    def __init__(self, parent, message, caption, agwStyle,
                 pos=wx.DefaultPosition, size=wx.DefaultSize,
                 style=wx.DEFAULT_DIALOG_STYLE|wx.WANTS_CHARS,
                 wrap=-1):
        """
        Default class constructor. Use L{ShowModal} to show the dialog.

        :param `parent`: the L{GenericMessageDialog} parent (if any);
        :param `message`: the message in the main body of the dialog;
        :param `caption`: the dialog title;
        :param `agwStyle`: the AGW-specific dialog style; it can be one of the
         following bits:

         =========================== =========== ==================================================
         Window Styles               Hex Value   Description
         =========================== =========== ==================================================
         0                                     0 Uses normal generic buttons
         ``GMD_USE_AQUABUTTONS``            0x20 Uses L{AquaButton} buttons instead of generic buttons.
         ``GMD_USE_GRADIENTBUTTONS``        0x40 Uses L{GradientButton} buttons instead of generic buttons.
         =========================== =========== ==================================================

         The styles above are mutually exclusive. The style chosen above can be combined with a
         bitlist containing flags chosen from the following:

         =========================== =========== ==================================================
         Window Styles               Hex Value   Description
         =========================== =========== ==================================================
         ``wx.OK``                           0x4 Shows an ``OK`` button.
         ``wx.CANCEL``                      0x10 Shows a ``Cancel`` button.
         ``wx.YES_NO``                       0xA Show ``Yes`` and ``No`` buttons.
         ``wx.YES_DEFAULT``                  0x0 Used with ``wx.YES_NO``, makes ``Yes`` button the default - which is the default behaviour.
         ``wx.NO_DEFAULT``                  0x80 Used with ``wx.YES_NO``, makes ``No`` button the default.
         ``wx.ICON_EXCLAMATION``           0x100 Shows an exclamation mark icon.
         ``wx.ICON_HAND``                  0x200 Shows an error icon.
         ``wx.ICON_ERROR``                 0x200 Shows an error icon - the same as ``wx.ICON_HAND``.
         ``wx.ICON_QUESTION``              0x400 Shows a question mark icon.
         ``wx.ICON_INFORMATION``           0x800 Shows an information icon.
         =========================== =========== ==================================================

        :param `pos`: the dialog position on screen;
        :param `size`: the dialog size;
        :param `style`: the underlying `wx.Dialog` style;
        :param `wrap`: if set greater than zero, wraps the string in `message` so that
         every line is at most `wrap` pixels long.

        :note: Notice that not all styles are compatible: only one of ``wx.OK`` and ``wx.YES_NO`` may be
         specified (and one of them must be specified) and at most one default button style can be used
         and it is only valid if the corresponding button is shown in the message box.
        """

        wx.Dialog.__init__(self, parent, wx.ID_ANY, caption, pos, size, style)

        self._message = message
        self._agwStyle = agwStyle
        self._wrap = wrap

        # The extended message placeholder
        self._extendedMessage = ''

        # Labels for the buttons, initially empty meaning that the defaults should
        # be used, use GetYes/No/OK/CancelLabel() to access them
        self._yes = self._no = self._ok = self._cancel = self._help = ''

        # Icons for the buttons, initially empty meaning that the defaults should
        # be used, use GetYes/No/OK/CancelBitmap() to access them
        self._yesBitmap = self._noBitmap = self._okBitmap = self._cancelBitmap = self._helpBitmap = None

        self._created = False

[docs]    def CreateMessageDialog(self):
        """ Actually creates the L{GenericMessageDialog}, just before showing it on screen. """

        message = self.GetMessage()

        topsizer = wx.BoxSizer(wx.VERTICAL)
        icon_text = wx.BoxSizer(wx.HORIZONTAL)

        case = self._agwStyle & wx.ICON_MASK

        if case == wx.ICON_ERROR:
            bitmap = _error

        elif case == wx.ICON_INFORMATION:
            bitmap = _information

        elif case == wx.ICON_WARNING:
            bitmap = _warning

        elif case == wx.ICON_QUESTION:
            bitmap = _question

        # Populate the sizers...
        icon = wx.StaticBitmap(self, -1, bitmap.GetBitmap())
        icon_text.Add(icon, 0, wx.ALIGN_CENTER_HORIZONTAL)

        textsizer = wx.BoxSizer(wx.VERTICAL)

        # We want to show the main message in a different font to make it stand
        # out if the extended message is used as well. This looks better and is
        # more consistent with the native dialogs under MSW and GTK.

        if self._extendedMessage.strip():
            boldFont = self.GetFont().Larger().MakeBold()
            if self._wrap > 0:
                message = self.WrapMessage(message, self._wrap, boldFont)

            msgSizer = self.CreateTextSizer(message)

            for index in xrange(len(msgSizer.GetChildren())):
                msgSizer.GetItem(index).GetWindow().SetFont(boldFont)

            textsizer.AddF(msgSizer, wx.SizerFlags().Border(wx.BOTTOM, 20))
            lowerMessage = self.GetExtendedMessage()

        else: # no extended message

            lowerMessage = message

        if self._wrap > 0:
            lowerMessage = self.WrapMessage(lowerMessage, self._wrap)

        textsizer.Add(self.CreateTextSizer(lowerMessage))

        icon_text.Add(textsizer, 1, wx.ALIGN_CENTER | wx.LEFT, 10)
        topsizer.Add(icon_text, 1, wx.EXPAND | wx.LEFT | wx.RIGHT | wx.TOP, 10)

        center_flag = wx.EXPAND
        if self._agwStyle & wx.YES_NO:
            center_flag |= wx.ALIGN_CENTRE

        sizerBtn = self.CreateSeparatedButtonSizer(self._agwStyle & BUTTON_SIZER_FLAGS)
        if sizerBtn:
            topsizer.Add(sizerBtn, 0, center_flag | wx.ALL, 10)

        self.SetAutoLayout(True)
        self.SetSizer(topsizer)

        topsizer.SetSizeHints(self)
        topsizer.Fit(self)
        size = self.GetSize()

        if size.x < size.y*3/2:
            size.x = size.y*3/2
            self.SetSize(size)

        self.Layout()
        self.Centre(wx.BOTH | wx.CENTER_FRAME)

        self.Bind(wx.EVT_BUTTON, self.OnYes, id=wx.ID_YES)
        self.Bind(wx.EVT_BUTTON, self.OnOk, id=wx.ID_OK)
        self.Bind(wx.EVT_BUTTON, self.OnNo, id=wx.ID_NO)
        self.Bind(wx.EVT_BUTTON, self.OnCancel, id=wx.ID_CANCEL)
        self.Bind(wx.EVT_BUTTON, self.OnHelp, id=wx.ID_HELP)

        for child in self.GetChildren():
            if isinstance(child, wx.lib.buttons.ThemedGenBitmapTextButton) or \
               isinstance(child, AB.AquaButton) or isinstance(child, GB.GradientButton):
                # Handles the key down for the buttons...
                child.Bind(wx.EVT_KEY_DOWN, self.OnKeyDown)
                if isinstance(child, wx.lib.buttons.ThemedGenBitmapTextButton):
                    child.SetUseFocusIndicator(False)

        self.Bind(wx.EVT_NAVIGATION_KEY, self.OnNavigation)
        self.SwitchFocus()

[docs]    def EndDialog(self, rc):
        """
        Ends the L{GenericMessageDialog} life. This will be done differently depending on
        the dialog modal/non-modal behaviour.

        :param `rc`: one of the ``wx.ID_YES``, ``wx.ID_NO``, ``wx.ID_OK``, ``wx.ID_CANCEL`` constants.

        :note: the `rc` parameter is unused if the dialog is not modal.
        """

        if self.IsModal():
            self.EndModal(rc)
        else:
            self.Hide()

[docs]    def OnYes(self, event):
        """ L{GenericMessageDialog} had received a ``wx.ID_YES`` answer. """

        self.EndDialog(wx.ID_YES)

[docs]    def OnOk(self, event):
        """ L{GenericMessageDialog} had received a ``wx.ID_OK`` answer. """

        self.EndDialog(wx.ID_OK)

[docs]    def OnNo(self, event):
        """ L{GenericMessageDialog} had received a ``wx.ID_NO`` answer. """

        self.EndDialog(wx.ID_NO)

[docs]    def OnCancel(self, event):
        """ L{GenericMessageDialog} had received a ``wx.ID_CANCEL`` answer. """

        # Allow cancellation via ESC/Close button except if
        # only YES and NO are specified.

        if self._agwStyle & wx.YES_NO != wx.YES_NO or self._agwStyle & wx.CANCEL:
            self.EndDialog(wx.ID_CANCEL)

[docs]    def OnHelp(self, event):
        """ L{GenericMessageDialog} had received a ``wx.ID_HELP`` answer. """

        self.EndDialog(wx.ID_HELP)

[docs]    def OnKeyDown(self, event):
        """
        Handles the ``wx.EVT_KEY_DOWN`` event for L{GenericMessageDialog}.

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

        key = event.GetKeyCode()
        if key == wx.WXK_ESCAPE:
            self.OnCancel(None)

        ids = []
        for child in self.GetChildren():
            if isinstance(child, wx.lib.buttons.ThemedGenBitmapTextButton) or \
               isinstance(child, AB.AquaButton) or isinstance(child, GB.GradientButton):
                ids.append(child.GetId())

        if key in [ord("y"), ord("Y")] and wx.ID_YES in ids:
            self.OnYes(None)
        elif key in [ord("n"), ord("N")] and wx.ID_NO in ids:
            self.OnNo(None)
        elif key in [ord("c"), ord("C")] and wx.ID_CANCEL in ids:
            self.OnCancel(None)
        elif key in [ord("o"), ord("O")] and wx.ID_OK in ids:
            self.OnOk(None)
        elif key in [ord("h"), ord("H")] and wx.ID_HELP in ids:
            self.OnHelp(None)

        event.Skip()

[docs]    def OnNavigation(self, event):
        """
        Handles the ``wx.EVT_NAVIGATION_KEY`` event for L{GenericMessageDialog}.

        :param `event`: a `wx.NavigationKeyEvent` event to be processed.
        """

        # Switch the focus between buttons...
        if wx.GetKeyState(wx.WXK_LEFT) or wx.GetKeyState(wx.WXK_RIGHT) or \
           wx.GetKeyState(wx.WXK_DOWN) or wx.GetKeyState(wx.WXK_UP) or \
           wx.GetKeyState(wx.WXK_NUMPAD_LEFT) or wx.GetKeyState(wx.WXK_NUMPAD_RIGHT) or \
           wx.GetKeyState(wx.WXK_NUMPAD_DOWN) or wx.GetKeyState(wx.WXK_NUMPAD_UP) or \
           event.IsFromTab():
            event.Skip()
            wx.CallAfter(self.SwitchFocus)
            return

        button = wx.Window.FindFocus()
        buttonId = button.GetId()
        self.EndDialog(buttonId)

[docs]    def SwitchFocus(self):
        """ Switch focus between buttons. """

        current = wx.Window.FindFocus()
        font = self.GetFont()
        boldFont = wx.Font(font.GetPointSize(), font.GetFamily(), font.GetStyle(), wx.BOLD,
                           font.GetUnderlined(), font.GetFaceName())

        for child in self.GetChildren():
            if isinstance(child, wx.lib.buttons.ThemedGenBitmapTextButton) or \
               isinstance(child, AB.AquaButton) or isinstance(child, GB.GradientButton):
                if child == current:
                    # Set a bold font for the current focused button
                    child.SetFont(boldFont)
                else:
                    # Restore the other buttons...
                    child.SetFont(font)
                child.Refresh()

[docs]    def CreateButtonSizer(self, flags):
        """
        Creates a sizer with standard buttons.

        :param `flags`: a bit list of the following flags:

         ================= ========= ==========================
         Flags             Hex Value Description
         ================= ========= ==========================
         ``wx.YES``              0x2 Show a ``Yes`` button
         ``wx.OK``               0x4 Show an ``OK`` button
         ``wx.NO``               0x8 Show a ``No`` button
         ``wx.CANCEL``          0x10 Show a ``Cancel`` button
         ``wx.NO_DEFAULT``      0x80 Used with ``wx.YES`` and ``wx.NO``, makes ``No`` button the default
         ``wx.HELP``          0x8000 Show a ``Help`` button
         ================= ========= ==========================

        :note: The sizer lays out the buttons in a manner appropriate to the platform.
        """

        sizer = self.CreateStdDialogButtonSizer(flags)

        return sizer

[docs]    def CreateSeparatedButtonSizer(self, flags):
        """
        Creates a sizer with standard buttons using L{CreateButtonSizer} separated
        from the rest of the dialog contents by a horizontal `wx.StaticLine`.

        :param `flags`: the button sizer flags.

        :see: L{CreateButtonSizer} for a list of valid flags.
        """

        sizer = self.CreateButtonSizer(flags)

        # Mac Human Interface Guidelines recommend not to use static lines as
        # grouping elements
        if wx.Platform != "__WXMAC__":
            topsizer = wx.BoxSizer(wx.VERTICAL)
            topsizer.AddF(wx.StaticLine(self), wx.SizerFlags().Expand().DoubleBorder(wx.BOTTOM))
            topsizer.AddF(sizer, wx.SizerFlags().Expand())
            sizer = topsizer

        return sizer

[docs]    def CreateStdDialogButtonSizer(self, flags):
        """
        Creates a L{StdDialogButtonSizer} with standard buttons.

        :param `flags`: the button sizer flags.

        :see: L{CreateButtonSizer} for a list of valid flags.

        :note: The sizer lays out the buttons in a manner appropriate to the platform.
        """

        sizer = StdDialogButtonSizer()
        no = yes = ok = None
        if flags & wx.OK:
            # Remove unwanted flags...
            flags &= ~(wx.YES | wx.NO | wx.NO_DEFAULT)

        if self._agwStyle & GMD_USE_AQUABUTTONS:
            klass = AB.AquaButton
        elif self._agwStyle & GMD_USE_GRADIENTBUTTONS:
            klass = GB.GradientButton
        else:
            klass = buttons.ThemedGenBitmapTextButton

        if flags & wx.OK:
            ok = klass(self, wx.ID_OK, self.GetCustomOKBitmap(), self.GetCustomOKLabel())
            sizer.AddButton(ok)

        if flags & wx.CANCEL:
            cancel = klass(self, wx.ID_CANCEL, self.GetCustomCancelBitmap(), self.GetCustomCancelLabel())
            sizer.AddButton(cancel)

        if flags & wx.YES:
            yes = klass(self, wx.ID_YES, self.GetCustomYesBitmap(), self.GetCustomYesLabel())
            sizer.AddButton(yes)

        if flags & wx.NO:
            no = klass(self, wx.ID_NO, self.GetCustomNoBitmap(), self.GetCustomNoLabel())
            sizer.AddButton(no)

        if flags & wx.HELP:
            help = klass(self, wx.ID_HELP, self.GetCustomHelpBitmap(), self.GetCustomHelpLabel())
            sizer.AddButton(help)

        if flags & wx.NO_DEFAULT:
            if no:
                no.SetDefault()
                no.SetFocus()
        else:
            if ok:
                ok.SetDefault()
                ok.SetFocus()
            elif yes:
                yes.SetDefault()
                yes.SetFocus()

        if flags & wx.OK:
            self.SetAffirmativeId(wx.ID_OK)
        elif flags & wx.YES:
            self.SetAffirmativeId(wx.ID_YES)

        sizer.Realize()

        return sizer

[docs]    def GetDefaultYesLabel(self):
        """
        Returns the default label for the ``Yes`` button.

        :note: this method may be overridden to provide different defaults for the
         default button labels.

        .. versionadded:: 0.9.3
        """

        return _("Yes")

[docs]    def GetDefaultNoLabel(self):
        """
        Returns the default label for the ``No`` button.

        :note: this method may be overridden to provide different defaults for the
         default button labels.

        .. versionadded:: 0.9.3
        """

        return _("No")

[docs]    def GetDefaultOKLabel(self):
        """
        Returns the default label for the ``OK`` button.

        :note: this method may be overridden to provide different defaults for the
         default button labels.

        .. versionadded:: 0.9.3
        """

        return _("OK")

[docs]    def GetDefaultCancelLabel(self):
        """
        Returns the default label for the ``Cancel`` button.

        :note: this method may be overridden to provide different defaults for the
         default button labels.

        .. versionadded:: 0.9.3
        """

        return _("Cancel")

[docs]    def GetDefaultHelpLabel(self):
        """
        Returns the default label for the ``Help`` button.

        :note: this method may be overridden to provide different defaults for the
         default button labels.

        .. versionadded:: 0.9.3
        """

        return _("Help")

[docs]    def GetCustomOKLabel(self):
        """
        If a custom label has been used for the ``OK`` button, this method will return
        it as a string. Otherwise, the default one (as defined in L{GetDefaultOKLabel})
        is returned.

        .. versionadded:: 0.9.3
        """

        return (self._ok and [self._ok] or [self.GetDefaultOKLabel()])[0]

[docs]    def GetCustomYesLabel(self):
        """
        If a custom label has been used for the ``Yes`` button, this method will return
        it as a string. Otherwise, the default one (as defined in L{GetDefaultYesLabel})
        is returned.

        .. versionadded:: 0.9.3
        """

        return (self._yes and [self._yes] or [self.GetDefaultYesLabel()])[0]

[docs]    def GetCustomNoLabel(self):
        """
        If a custom label has been used for the ``No`` button, this method will return
        it as a string. Otherwise, the default one (as defined in L{GetDefaultNoLabel})
        is returned.

        .. versionadded:: 0.9.3
        """

        return (self._no and [self._no] or [self.GetDefaultNoLabel()])[0]

[docs]    def GetCustomCancelLabel(self):
        """
        If a custom label has been used for the ``Cancel`` button, this method will return
        it as a string. Otherwise, the default one (as defined in L{GetDefaultCancelLabel})
        is returned.

        .. versionadded:: 0.9.3
        """

        return (self._cancel and [self._cancel] or [self.GetDefaultCancelLabel()])[0]

[docs]    def GetCustomHelpLabel(self):
        """
        If a custom label has been used for the ``Help`` button, this method will return
        it as a string. Otherwise, the default one (as defined in L{GetDefaultHelpLabel})
        is returned.

        .. versionadded:: 0.9.3
        """

        return (self._help and [self._help] or [self.GetDefaultHelpLabel()])[0]

    # Customization of the message box buttons

[docs]    def SetYesNoLabels(self, yes, no):
        """
        Overrides the default labels of the ``Yes`` and ``No`` buttons.

        :param `yes`: the new label for the ``Yes`` button;
        :param `no`: the new label for the ``No`` button.

        Typically, if the function was used successfully, the main dialog message may need to be changed, e.g.::

            main_message = "Hello world! I am the main message."

            dlg = GenericMessageDialog(None, main_message, "A Nice Message Box",
                                       agwStyle=wx.ICON_INFORMATION|wx.OK)

            if dlg.SetYesNoLabels(_("&Quit"), _("&Don't quit")):
                dlg.SetMessage(_("What do you want to do?"))

            else: # buttons have standard "Yes"/"No" values, so rephrase the question
                dlg.SetMessage(_("Do you really want to quit?"))

        .. versionadded:: 0.9.3
        """

        self._yes, self._no = yes, no
        return True

[docs]    def SetYesNoCancelLabels(self, yes, no, cancel):
        """
        Overrides the default labels of the ``Yes`` and ``No`` buttons.

        :param `yes`: the new label for the ``Yes`` button;
        :param `no`: the new label for the ``No`` button;
        :param `cancel`: the new label for the ``Cancel`` button.

        :see: The remarks in the L{SetYesNoLabels} documentation.

        .. versionadded:: 0.9.3
        """

        self._yes, self._no, self._cancel = yes, no, cancel
        return True

[docs]    def SetOKLabel(self, ok):
        """
        Overrides the default label of the ``OK`` button.

        :param `ok`: the new label for the ``OK`` button.

        :see: The remarks in the L{SetYesNoLabels} documentation.

        .. versionadded:: 0.9.3
        """

        self._ok = ok
        return True

[docs]    def SetOKCancelLabels(self, ok, cancel):
        """
        Overrides the default labels of the ``OK`` and ``Cancel`` buttons.

        :param `ok`: the new label for the ``OK`` button;
        :param `cancel`: the new label for the ``Cancel`` button.

        :see: The remarks in the L{SetYesNoLabels} documentation.

        .. versionadded:: 0.9.3
        """

        self._ok, self._cancel = ok, cancel
        return True

[docs]    def SetHelpLabel(self, help):
        """
        Overrides the default label of the ``Help`` button.

        :param `help`: the new label for the ``Help`` button.

        :see: The remarks in the L{SetYesNoLabels} documentation.

        .. versionadded:: 0.9.3
        """

        self._help = help
        return True

    # Test if any custom labels were set

[docs]    def HasCustomLabels(self):
        """
        Returns ``True`` if any of the buttons have a non-default label.

        .. versionadded:: 0.9.3
        """

        for label in [self._ok, self._no, self._yes, self._cancel, self._help]:
            if label.strip():
                return True

        return False

[docs]    def GetDefaultYesBitmap(self):
        """
        Returns the default icon for the ``Yes`` button.

        :note: this method may be overridden to provide different defaults for the
         default button icons.

        .. versionadded:: 0.9.3
        """

        return _yes.GetBitmap()

[docs]    def GetDefaultNoBitmap(self):
        """
        Returns the default icon for the ``No`` button.

        :note: this method may be overridden to provide different defaults for the
         default button icons.

        .. versionadded:: 0.9.3
        """

        return _no.GetBitmap()

[docs]    def GetDefaultOKBitmap(self):
        """
        Returns the default icon for the ``OK`` button.

        :note: this method may be overridden to provide different defaults for the
         default button icons.

        .. versionadded:: 0.9.3
        """

        return _ok.GetBitmap()

[docs]    def GetDefaultCancelBitmap(self):
        """
        Returns the default icon for the ``Cancel`` button.

        :note: this method may be overridden to provide different defaults for the
         default button icons.

        .. versionadded:: 0.9.3
        """

        return _cancel.GetBitmap()

[docs]    def GetDefaultHelpBitmap(self):
        """
        Returns the default icon for the ``Help`` button.

        :note: this method may be overridden to provide different defaults for the
         default button icons.

        .. versionadded:: 0.9.3
        """

        return _help.GetBitmap()

[docs]    def GetCustomOKBitmap(self):
        """
        If a custom icon has been used for the ``OK`` button, this method will return
        it as an instance of `wx.Bitmap`. Otherwise, the default one (as defined in
        L{GetDefaultOKBitmap}) is returned.

        .. versionadded:: 0.9.3
        """

        return (self._okBitmap and [self._okBitmap] or [self.GetDefaultOKBitmap()])[0]

[docs]    def GetCustomYesBitmap(self):
        """
        If a custom icon has been used for the ``Yes`` button, this method will return
        it as an instance of `wx.Bitmap`. Otherwise, the default one (as defined in
        L{GetDefaultYesBitmap}) is returned.

        .. versionadded:: 0.9.3
        """

        return (self._yesBitmap and [self._yesBitmap] or [self.GetDefaultYesBitmap()])[0]

[docs]    def GetCustomNoBitmap(self):
        """
        If a custom icon has been used for the ``No`` button, this method will return
        it as an instance of `wx.Bitmap`. Otherwise, the default one (as defined in
        L{GetDefaultNoBitmap}) is returned.

        .. versionadded:: 0.9.3
        """

        return (self._noBitmap and [self._noBitmap] or [self.GetDefaultNoBitmap()])[0]

[docs]    def GetCustomCancelBitmap(self):
        """
        If a custom icon been used for the ``Cancel`` button, this method will return
        it as an instance of `wx.Bitmap`. Otherwise, the default one (as defined in
        L{GetDefaultCancelBitmap}) is returned.

        .. versionadded:: 0.9.3
        """

        return (self._cancelBitmap and [self._cancelBitmap] or [self.GetDefaultCancelBitmap()])[0]

[docs]    def GetCustomHelpBitmap(self):
        """
        If a custom icon has been used for the ``Help`` button, this method will return
        it as an instance of `wx.Bitmap`. Otherwise, the default one (as defined in
        L{GetDefaultHelpBitmap}) is returned.

        .. versionadded:: 0.9.3
        """

        return (self._helpBitmap and [self._helpBitmap] or [self.GetDefaultHelpBitmap()])[0]

    # Customization of the message box buttons icons

[docs]    def SetYesNoBitmaps(self, yesBitmap, noBitmap):
        """
        Overrides the default icons of the ``Yes`` and ``No`` buttons.

        :param `yesBitmap`: the new icon for the ``Yes`` button, an instance of `wx.Bitmap`;
        :param `noBitmap`: the new icon for the ``No`` button, an instance of `wx.Bitmap`.

        .. versionadded:: 0.9.3
        """

        self._yesBitmap, self._noBitmap = yesBitmap, noBitmap
        return True

[docs]    def SetYesNoCancelBitmaps(self, yesBitmap, noBitmap, cancelBitmap):
        """
        Overrides the default icons of the ``Yes`` and ``No`` buttons.

        :param `yesBitmap`: the new icon for the ``Yes`` button, an instance of `wx.Bitmap`;
        :param `noBitmap`: the new icon for the ``No`` button, an instance of `wx.Bitmap`;
        :param `cancelBitmap`: the new icon for the ``Cancel`` button, an instance of `wx.Bitmap`.

        .. versionadded:: 0.9.3
        """

        self._yesBitmap, self._noBitmap, self._cancelBitmap = yesBitmap, noBitmap, cancelBitmap
        return True

[docs]    def SetOKBitmap(self, okBitmap):
        """
        Overrides the default icon of the ``OK`` button.

        :param `yesBitmap`: the new icon for the ``OK`` button, an instance of `wx.Bitmap`;

        .. versionadded:: 0.9.3
        """

        self._okBitmap = okBitmap
        return True

[docs]    def SetOKCancelBitmaps(self, okBitmap, cancelBitmap):
        """
        Overrides the default icons of the ``OK`` and ``Cancel`` buttons.

        :param `okBitmap`: the new icon for the ``OK`` button, an instance of `wx.Bitmap`;
        :param `cancelBitmap`: the new icon for the ``Cancel`` button, an instance of `wx.Bitmap`.

        .. versionadded:: 0.9.3
        """

        self._okBitmap, self._cancelBitmap = okBitmap, cancelBitmap
        return True

[docs]    def SetHelpBitmap(self, helpBitmap):
        """
        Overrides the default icon of the ``Help`` button.

        :param `helpBitmap`: the new icon for the ``Help`` button, an instance of `wx.Bitmap`.

        .. versionadded:: 0.9.3
        """

        self._helpBitmap = helpBitmap
        return True

    # Test if any custom icons were set

[docs]    def HasCustomBitmaps(self):
        """
        Returns ``True`` if any of the buttons have a non-default icons.

        .. versionadded:: 0.9.3
        """

        for icon in [self._okBitmap, self._noBitmap, self._yesBitmap,
                     self._cancelBitmap, self._helpBitmap]:
            if icon is not None:
                return True

        return False

[docs]    def WrapMessage(self, message, wrap, font=None):
        """
        Wraps the input message to multi lines so that the resulting new message
        is at most `wrap` pixels wide.

        :param `message`: the original input message;
        :param `wrap`: wraps the string in `message` so that every line is at most
         `wrap` pixels long;
        :param `font`: if not ``None``, it should be an instance of `wx.Font` to be
         used to measure and then wrap the input `message`.

        :return: a new message wrapped at maximum `wrap` pixels wide.

        :todo: Estabilish if wrapping all messages by default is a better idea than
         provide a keyword parameter to L{GenericMessageDialog}. A default maximum
         line width might be the wxMac one, at 360 pixels.
        """

        dc = wx.ClientDC(self)

        if font is None:
            dc.SetFont(self.GetFont())
        else:
            dc.SetFont(font)

        newMessage = wordwrap.wordwrap(message, wrap, dc, False)
        return newMessage

[docs]    def ShowModal(self):
        """
        Shows the dialog, returning one of ``wx.ID_OK``, ``wx.ID_CANCEL``, ``wx.ID_YES``,
        ``wx.ID_NO`` or ``wx.ID_HELP``.

        :note: Notice that this method returns the identifier of the button which was
         clicked unlike the `wx.MessageBox()` function.

        :note: Reimplemented from `wx.Dialog`.
        """

        if not self._created:

            self._created = True
            self.CreateMessageDialog()

        return wx.Dialog.ShowModal(self)

[docs]    def GetCaption(self):
        """
        Returns the main caption (the title) for L{GenericMessageDialog}.

        .. versionadded:: 0.9.3
        """

        return self.GetTitle()

[docs]    def SetMessage(self, message):
        """
        Sets the message shown by the dialog.

        :param `message`: a string representing the main L{GenericMessageDialog} message.

        .. versionadded:: 0.9.3
        """

        self._message = message

[docs]    def GetMessage(self):
        """
        Returns a string representing the main L{GenericMessageDialog} message.

        .. versionadded:: 0.9.3
        """

        return self._message

[docs]    def SetExtendedMessage(self, extendedMessage):
        """
        Sets the extended message for the dialog: this message is usually an extension of the
        short message specified in the constructor or set with L{SetMessage}.

        If it is set, the main message appears highlighted and this message appears beneath
        it in normal font.

        :param `extendedMessage`: a string representing the extended L{GenericMessageDialog} message.

        .. versionadded:: 0.9.3
        """

        self._extendedMessage = extendedMessage

[docs]    def GetExtendedMessage(self):
        """
        Returns a string representing the extended L{GenericMessageDialog} message.

        .. versionadded:: 0.9.3
        """

        return self._extendedMessage

[docs]    def GetMessageDialogStyle(self):
        """
        Returns the AGW-specific window style for L{GenericMessageDialog}.

        .. versionadded:: 0.9.3
        """

        return self._agwStyle

    # To combine the separate main and extended messages in a single string

[docs]    def GetFullMessage(self):
        """
        Returns a string representing the combination of the main L{GenericMessageDialog}
        message and the extended message, separated by an empty line.

        .. versionadded:: 0.9.3
        """

        msg = self._message
        if self._extendedMessage.strip():
            msg += '\n\n' + self._extendedMessage

        return msg

Navigation

  • index
  • modules |
  • Home |
  • Gallery |
  • Contents»
  • Module code »
  • genericmessagedialog


gradientbutton

  • modules |
  • Home |
  • Gallery |
  • Contents»
  • Module code »
  • gradientbutton

Source code for gradientbutton

# --------------------------------------------------------------------------------- #
# GRADIENTBUTTON wxPython IMPLEMENTATION
#
# Andrea Gavana, @ 07 October 2008
# Latest Revision: 09 Feb 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
# --------------------------------------------------------------------------------- #

"""
L{GradientButton} is another custom-drawn button class which mimics Windows CE mobile
gradient buttons.

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

L{GradientButton} is another custom-drawn button class which mimics Windows CE mobile
gradient buttons, using a tri-vertex blended gradient plus some ClearType bold
font (best effect with Tahoma Bold). L{GradientButton} supports:

* Triple blended gradient background, with customizable colours;
* Custom colours for the "pressed" state;
* Rounded-corners buttons;
* Text-only or image+text buttons.

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

Usage
=====

Usage example::

    import wx
    import wx.lib.agw.gradientbutton as GB

    class MyFrame(wx.Frame):

        def __init__(self, parent):

            wx.Frame.__init__(self, parent, -1, "GradientButton Demo")

            panel = wx.Panel(self, -1)

            # One button without bitmap
            button_1 = GB.GradientButton(panel, -1, None, "Hello World", (100, 50))

            # One button with bitmap
            my_bitmap = wx.Bitmap("my_bitmap.png", wx.BITMAP_TYPE_PNG)
            button_2 = GB.GradientButton(panel, -1, my_bitmap, "GradientButton", (100, 150))

    # our normal wxApp-derived class, as usual

    app = wx.PySimpleApp()

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

    app.MainLoop()

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

L{GradientButton} has been tested on the following platforms:
  * Windows (Windows XP).

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 `wx.wxEVT_COMMAND_BUTTON_CLICKED` event, when the button is clicked.
================= ==================================================

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

L{GradientButton} is distributed under the wxPython license.

Latest Revision: Andrea Gavana @ 09 Feb 2012, 21.00 GMT

Version 0.3

"""

import wx

HOVER = 1
CLICK = 2

[docs]class GradientButtonEvent(wx.PyCommandEvent):
    """ Event sent from L{GradientButton} when the button is activated. """

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

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

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

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

        :param `btn`: the button object, an instance of L{GradientButton}.
        """

        self.theButton = btn

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

        return self.theButton

[docs]class GradientButton(wx.PyControl):
    """ This is the main class implementation of L{GradientButton}. """

[docs]    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="gradientbutton"):
        """
        Default class constructor.

        :param `parent`: the L{GradientButton} parent;
        :param `id`: window identifier. A value of -1 indicates a default value;
        :param `bitmap`: the button bitmap (if any);
        :param `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;
        :param `size`: the control size. A value of (-1, -1) indicates a default size,
         chosen by either the windowing system or wxPython, depending on platform;
        :param `style`: the button style (unused);
        :param `validator`: the validator associated to the button;
        :param `name`: the button name.
        """

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

        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_LEFT_DCLICK, self.OnLeftDown)

        self._mouseAction = None
        self._bitmap = bitmap
        self._hasFocus = False

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

        self.SetBaseColours()

[docs]    def SetBaseColours(self, startcolour=wx.BLACK, foregroundcolour=wx.WHITE):
        """Sets the bottom, top, pressed and foreground colour

        :param startcolour: based colour to be used for bottom, top and pressed
        :param foregroundcolour: colour used for the text

        """
        self._bottomStartColour = startcolour
        rgba = self._bottomStartColour.Red(), self._bottomStartColour.Green(), \
               self._bottomStartColour.Blue(), self._bottomStartColour.Alpha()
        self._bottomEndColour = self.LightColour(self._bottomStartColour, 20)
        self._topStartColour = self.LightColour(self._bottomStartColour, 40)
        self._topEndColour = self.LightColour(self._bottomStartColour, 25)
        self._pressedTopColour = self.LightColour(self._bottomStartColour, 20)
        self._pressedBottomColour = wx.Colour(*rgba)
        self.SetForegroundColour(foregroundcolour)

[docs]    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;
        :param `percent`: determines how light the colour will be. `percent` = 100
         returns white, `percent` = 0 returns `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)

[docs]    def OnSize(self, event):
        """
        Handles the ``wx.EVT_SIZE`` event for L{GradientButton}.

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

        event.Skip()
        self.Refresh()

[docs]    def OnLeftDown(self, event):
        """
        Handles the ``wx.EVT_LEFT_DOWN`` event for L{GradientButton}.

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

        if not self.IsEnabled():
            return

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

[docs]    def OnLeftUp(self, event):
        """
        Handles the ``wx.EVT_LEFT_UP`` event for L{GradientButton}.

        :param `event`: a `wx.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()

[docs]    def OnMouseEnter(self, event):
        """
        Handles the ``wx.EVT_ENTER_WINDOW`` event for L{GradientButton}.

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

        if not self.IsEnabled():
            return

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

[docs]    def OnMouseLeave(self, event):
        """
        Handles the ``wx.EVT_LEAVE_WINDOW`` event for L{GradientButton}.

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

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

[docs]    def OnGainFocus(self, event):
        """
        Handles the ``wx.EVT_SET_FOCUS`` event for L{GradientButton}.

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

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

[docs]    def OnLoseFocus(self, event):
        """
        Handles the ``wx.EVT_KILL_FOCUS`` event for L{GradientButton}.

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

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

[docs]    def OnKeyDown(self, event):
        """
        Handles the ``wx.EVT_KEY_DOWN`` event for L{GradientButton}.

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

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

[docs]    def OnKeyUp(self, event):
        """
        Handles the ``wx.EVT_KEY_UP`` event for L{GradientButton}.

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

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

[docs]    def OnPaint(self, event):
        """
        Handles the ``wx.EVT_PAINT`` event for L{GradientButton}.

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

        dc = wx.BufferedPaintDC(self)
        gc = wx.GraphicsContext.Create(dc)
        dc.SetBackground(wx.Brush(self.GetParent().GetBackgroundColour()))
        dc.Clear()

        clientRect = self.GetClientRect()
        gradientRect = wx.Rect(*clientRect)
        capture = wx.Window.GetCapture()

        x, y, width, height = clientRect

        gradientRect.SetHeight(gradientRect.GetHeight()/2 + ((capture==self and [1] or [0])[0]))
        if capture != self:
            if self._mouseAction == HOVER:
                topStart, topEnd = self.LightColour(self._topStartColour, 10), self.LightColour(self._topEndColour, 10)
            else:
                topStart, topEnd = self._topStartColour, self._topEndColour

            rc1 = wx.Rect(x, y, width, height/2)
            path1 = self.GetPath(gc, rc1, 8)
            br1 = gc.CreateLinearGradientBrush(x, y, x, y+height/2, topStart, topEnd)
            gc.SetBrush(br1)
            gc.FillPath(path1) #draw main

            path4 = gc.CreatePath()
            path4.AddRectangle(x, y+height/2-8, width, 8)
            path4.CloseSubpath()
            gc.SetBrush(br1)
            gc.FillPath(path4)

        else:

            rc1 = wx.Rect(x, y, width, height)
            path1 = self.GetPath(gc, rc1, 8)
            gc.SetPen(wx.Pen(self._pressedTopColour))
            gc.SetBrush(wx.Brush(self._pressedTopColour))
            gc.FillPath(path1)

        gradientRect.Offset((0, gradientRect.GetHeight()))

        if capture != self:

            if self._mouseAction == HOVER:
                bottomStart, bottomEnd = self.LightColour(self._bottomStartColour, 10), self.LightColour(self._bottomEndColour, 10)
            else:
                bottomStart, bottomEnd = self._bottomStartColour, self._bottomEndColour

            rc3 = wx.Rect(x, y+height/2, width, height/2)
            path3 = self.GetPath(gc, rc3, 8)
            br3 = gc.CreateLinearGradientBrush(x, y+height/2, x, y+height, bottomStart, bottomEnd)
            gc.SetBrush(br3)
            gc.FillPath(path3) #draw main

            path4 = gc.CreatePath()
            path4.AddRectangle(x, y+height/2, width, 8)
            path4.CloseSubpath()
            gc.SetBrush(br3)
            gc.FillPath(path4)

            shadowOffset = 0
        else:

            rc2 = wx.Rect(x+1, gradientRect.height/2, gradientRect.width, gradientRect.height)
            path2 = self.GetPath(gc, rc2, 8)
            gc.SetPen(wx.Pen(self._pressedBottomColour))
            gc.SetBrush(wx.Brush(self._pressedBottomColour))
            gc.FillPath(path2)
            shadowOffset = 1

        font = gc.CreateFont(self.GetFont(), self.GetForegroundColour())
        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+shadowOffset      # adjust for bitmap and text to centre
        if self._bitmap:
            pos_y =  (height-bh)/2+shadowOffset
            gc.DrawBitmap(self._bitmap, pos_x, pos_y, bw, bh) # draw bitmap if available
            pos_x = pos_x + 2   # extra spacing from bitmap

        gc.DrawText(label, pos_x + bw + shadowOffset, (height-th)/2+shadowOffset)

[docs]    def GetPath(self, gc, rc, r):
        """
        Returns a rounded `wx.GraphicsPath` rectangle.

        :param `gc`: an instance of `wx.GraphicsContext`;
        :param `rc`: a client rectangle;
        :param `r`: the radious of the rounded part of the rectangle.
        """

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

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

        :param `size`: an instance of `wx.Size`.
        """

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

    SetBestSize = SetInitialSize

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

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

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

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

        return wx.Button.GetClassDefaultAttributes()

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

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

        return False

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

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

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

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

[docs]    def SetTopStartColour(self, colour):
        """
        Sets the top start colour for the gradient shading.

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

        self._topStartColour = colour
        self.Refresh()

[docs]    def GetTopStartColour(self):
        """ Returns the top start colour for the gradient shading. """

        return self._topStartColour

[docs]    def SetTopEndColour(self, colour):
        """
        Sets the top end colour for the gradient shading.

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

        self._topEndColour = colour
        self.Refresh()

[docs]    def GetTopEndColour(self):
        """ Returns the top end colour for the gradient shading. """

        return self._topEndColour

[docs]    def SetBottomStartColour(self, colour):
        """
        Sets the top bottom colour for the gradient shading.

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

        self._bottomStartColour = colour
        self.Refresh()

[docs]    def GetBottomStartColour(self):
        """ Returns the bottom start colour for the gradient shading. """

        return self._bottomStartColour

[docs]    def SetBottomEndColour(self, colour):
        """
        Sets the bottom end colour for the gradient shading.

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

        self._bottomEndColour = colour
        self.Refresh()

[docs]    def GetBottomEndColour(self):
        """ Returns the bottom end colour for the gradient shading. """

        return self._bottomEndColour

[docs]    def SetPressedTopColour(self, colour):
        """
        Sets the pressed top start colour for the gradient shading.

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

        self._pressedTopColour = colour
        self.Refresh()

[docs]    def GetPressedTopColour(self):
        """ Returns the pressed top start colour for the gradient shading. """

        return self._pressedTopColour

[docs]    def SetPressedBottomColour(self, colour):
        """
        Sets the pressed bottom start colour for the gradient shading.

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

        self._pressedBottomColour = colour
        self.Refresh()

[docs]    def GetPressedBottomColour(self):
        """ Returns the pressed bottom start colour for the gradient shading. """

        return self._pressedBottomColour

[docs]    def SetForegroundColour(self, colour):
        """
        Sets the L{GradientButton} foreground (text) colour.

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

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

        wx.PyControl.SetForegroundColour(self, colour)
        self.Refresh()

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

        :note: Overridden from `wx.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 = 15
        if self._bitmap:
            bmpWidth, bmpHeight = self._bitmap.GetWidth()+10, self._bitmap.GetHeight()
            retWidth += bmpWidth
            retHeight = max(bmpHeight, retHeight)
            constant = 15

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

[docs]    def SetDefault(self):
        """ Sets the default button. """

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

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

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

Navigation

  • index
  • modules |
  • Home |
  • Gallery |
  • Contents»
  • Module code »
  • gradientbutton


hyperlink

  • modules |
  • Home |
  • Gallery |
  • Contents»
  • Module code »
  • hyperlink

Source code for hyperlink

# --------------------------------------------------------------------------- #
# HYPERLINKSCTRL wxPython IMPLEMENTATION
# Ported From Angelo Mandato C++ Code By:
#
# Andrea Gavana, @ 27 Mar 2005
# Latest Revision: 17 Aug 2011, 15.00 GMT
#
#
# Original Web Site (For The C++ Code):
#
# http://www.spaceblue.com/codedetail.php?CodeID=7
#
#
# Thanks to E. A. Tacao for his nice suggestions and improvements of the code.
#
# 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
# --------------------------------------------------------------------------- #

"""
L{HyperLinkCtrl} is a control for wxPython that acts like a hyper link
in a typical browser.

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

L{HyperLinkCtrl} is a control for wxPython that acts like a hyper link
in a typical browser. Latest features include the ability to capture
your own left, middle, and right click events to perform your own
custom event handling and ability to open link in a new or current
browser window.

Special thanks to Robin Dunn for the event binder for the 3 mouse buttons.

Usage
=====

Usage example::

    import wx
    import wx.lib.agw.hyperlink as hl

    class MyFrame(wx.Frame):

        def __init__(self, parent):

            wx.Frame.__init__(self, parent, -1, "HyperLink Demo")

            panel = wx.Panel(self, -1)

            # Default Web links:
            hyper1 = hl.HyperLinkCtrl(panel, -1, "wxPython Main Page", pos=(100, 100),
                                      URL="http://www.wxpython.org/")

            # Web link with underline rollovers, opens in same window
            hyper2 = hl.HyperLinkCtrl(panel, -1, "My Home Page", pos=(100, 150),
                                      URL="http://xoomer.virgilio.it/infinity77/")

            hyper2.AutoBrowse(False)
            hyper2.SetColours("BLUE", "BLUE", "BLUE")
            hyper2.EnableRollover(True)
            hyper2.SetUnderlines(False, False, True)
            hyper2.SetBold(True)
            hyper2.OpenInSameWindow(True)
            hyper2.SetToolTip(wx.ToolTip("Hello World!"))
            hyper2.UpdateLink()

    # our normal wxApp-derived class, as usual

    app = wx.PySimpleApp()

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

    app.MainLoop()

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

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

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

This class processes the following events:

======================== ==================================================
Event Name               Description
======================== ==================================================
``EVT_HYPERLINK_LEFT``   Responds to a left mouse button event. Sent when the left mouse button is clicked, but only if `AutoBrowse` is set to ``False``.
``EVT_HYPERLINK_MIDDLE`` Responds to a middle mouse button event. Sent when the middle mouse button is clicked.
``EVT_HYPERLINK_RIGHT``  Handles a right mouse button event. Sent when the right mouse button is clicked, but only if `DoPopup` is set to ``False``.
======================== ==================================================

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

L{HyperLinkCtrl} is distributed under the wxPython license.

Latest Revision: Andrea Gavana @ 17 Aug 2011, 15.00 GMT

Version 0.6

"""

import wx
from wx.lib.stattext import GenStaticText as StaticText

# Import the useful webbrowser module for platform-independent results
import webbrowser

# Set no delay time to open the web page
webbrowser.PROCESS_CREATION_DELAY = 0

# To show a popup that copies the hyperlinks on the clipboard
wxHYPERLINKS_POPUP_COPY = 1000

#-----------------------------------#
#        HyperLinksEvents
#-----------------------------------#

# wxEVT_HYPERLINK_LEFT: Respond To A Left Mouse Button Event
# wxEVT_HYPERLINK_MIDDLE: Respond To A Middle Mouse Button Event
# wxEVT_HYPERLINK_RIGHT: Respond To A Right Mouse Button Event

wxEVT_HYPERLINK_LEFT = wx.NewEventType()
wxEVT_HYPERLINK_MIDDLE = wx.NewEventType()
wxEVT_HYPERLINK_RIGHT = wx.NewEventType()

EVT_HYPERLINK_LEFT = wx.PyEventBinder(wxEVT_HYPERLINK_LEFT, 1)
""" Responds to a left mouse button event. Sent when the left mouse button is""" \
""" clicked, but only if `AutoBrowse` is set to ``False``. """
EVT_HYPERLINK_MIDDLE = wx.PyEventBinder(wxEVT_HYPERLINK_MIDDLE, 1)
""" Responds to a middle mouse button event. Sent when the middle mouse button is clicked. """
EVT_HYPERLINK_RIGHT = wx.PyEventBinder(wxEVT_HYPERLINK_RIGHT, 1)
""" Handles a right mouse button event. Sent when the right mouse button is""" \
""" clicked, but only if `DoPopup` is set to ``False``. """

# ------------------------------------------------------------
# This class implements the event listener for the hyperlinks
# ------------------------------------------------------------

[docs]class HyperLinkEvent(wx.PyCommandEvent):
    """
    Event object sent in response to clicking on a L{HyperLinkCtrl}.
    """

[docs]    def __init__(self, eventType, eventId):
        """
        Default Class Constructor.

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

        wx.PyCommandEvent.__init__(self, eventType, eventId)
        self._eventType = eventType

[docs]    def SetPosition(self, pos):
        """
        Sets the event position.

        :param `pos`: an instance of `wx.Point`.
        """

        self._pos = pos

[docs]    def GetPosition(self):
        """ Returns the event position. """

        return self._pos

# -------------------------------------------------
# This is the main HyperLinkCtrl implementation
# it user the StatiText from wx.lib.stattext
# because of its "quasi-dynamic" behavior
# -------------------------------------------------

[docs]class HyperLinkCtrl(StaticText):
    """
    L{HyperLinkCtrl} is a control for wxPython that acts like a hyper
    link in a typical browser. Latest features include the ability to
    capture your own left, middle, and right click events to perform
    your own custom event handling and ability to open link in a new
    or current browser window.
    """

[docs]    def __init__(self, parent, id=-1, label="", pos=wx.DefaultPosition,
                 size=wx.DefaultSize, style=0, name="staticText", URL=""):
        """
        Default class constructor.

        :param `parent`: the window parent. Must not be ``None``;
        :param `id`: window identifier. A value of -1 indicates a default value;
        :param `label`: the control 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;
        :param `size`: the control size. A value of (-1, -1) indicates a default size,
         chosen by either the windowing system or wxPython, depending on platform;
        :param `style`: the window style;
        :param `name`: the window name;
        :param `URL`: a string specifying the url link to navigate to.

        :note: Pass URL="" to use the label as the url link to navigate to.
        """

        StaticText.__init__(self, parent, id, label, pos, size,
                            style, name)

        if URL.strip() == "":
            self._URL = label
        else:
            self._URL = URL

        # Set Tooltip
        self.SetToolTip(wx.ToolTip(self._URL))

        # Set default properties
        # default: True
        self.ReportErrors()

        # default: True, True, True
        self.SetUnderlines()

        # default: blue, violet, blue
        self.SetColours()

        # default: False
        self.SetVisited()

        # default: False
        self.EnableRollover()

        # default: False
        self.SetBold()

        # default: wx.CURSOR_HAND
        self.SetLinkCursor()

        # default True
        self.AutoBrowse()

        # default True
        self.DoPopup()

        # default False
        self.OpenInSameWindow()

        # Set control properties and refresh
        self.UpdateLink(True)

        self.Bind(wx.EVT_MOUSE_EVENTS, self.OnMouseEvent)
        self.Bind(wx.EVT_MOTION, self.OnMouseEvent)

[docs]    def GotoURL(self, URL, ReportErrors=True, NotSameWinIfPossible=False):
        """
        Goto the specified URL.

        :param `URL`: the url link we wish to navigate;
        :param `ReportErrors`: Use ``True`` to display error dialog if an error
         occurrs navigating to the URL;
        :param `NotSameWinIfPossible`: Use ``True`` to attempt to open the URL
         in new browser window.
        """

        logOff = wx.LogNull()

        try:
            webbrowser.open(URL, new=NotSameWinIfPossible)
            self.SetVisited(True)
            self.UpdateLink(True)

            return True

        except:
            self.DisplayError("Unable To Launch Browser.", ReportErrors)
            return False

[docs]    def OnMouseEvent(self, event):
        """
        Handles the ``wx.EVT_MOUSE_EVENTS`` events for L{HyperLinkCtrl}.

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

        if event.Moving():
            # Mouse Is Moving On The StaticText
            # Set The Hand Cursor On The Link
            self.SetCursor(self._CursorHand)

            if self._EnableRollover:
                fontTemp = self.GetFont()
                fontTemp.SetUnderlined(self._RolloverUnderline)
                if self._Bold:
                    fontTemp.SetWeight(wx.BOLD)

                needRefresh = False

                if self.GetFont() != fontTemp:
                    self.SetFont(fontTemp)
                    needRefresh = True

                if self.GetForegroundColour() != self._LinkRolloverColour:
                    self.SetForegroundColour(self._LinkRolloverColour)
                    needRefresh = True

                if needRefresh:
                    self.Refresh()

        else:
            # Restore The Original Cursor
            self.SetCursor(wx.NullCursor)
            if self._EnableRollover:
                self.UpdateLink(True)

            if event.LeftUp():
                # Left Button Was Pressed
                if self._AutoBrowse:
                    self.GotoURL(self._URL, self._ReportErrors,
                                 self._NotSameWinIfPossible)

                else:
                    eventOut = HyperLinkEvent(wxEVT_HYPERLINK_LEFT, self.GetId())
                    eventOut.SetEventObject(self)
                    eventOut.SetPosition(event.GetPosition())
                    self.GetEventHandler().ProcessEvent(eventOut)

                self.SetVisited(True)

            elif event.RightUp():
                # Right Button Was Pressed
                if self._DoPopup:
                    # Popups A Menu With The "Copy HyperLynks" Feature
                    menuPopUp = wx.Menu("", wx.MENU_TEAROFF)
                    menuPopUp.Append(wxHYPERLINKS_POPUP_COPY, "Copy HyperLink")
                    self.Bind(wx.EVT_MENU, self.OnPopUpCopy, id=wxHYPERLINKS_POPUP_COPY)
                    self.PopupMenu(menuPopUp, wx.Point(event.X, event.Y))
                    menuPopUp.Destroy()
                    self.Unbind(wx.EVT_MENU, id=wxHYPERLINKS_POPUP_COPY)

                else:
                    eventOut = HyperLinkEvent(wxEVT_HYPERLINK_RIGHT, self.GetId())
                    eventOut.SetEventObject(self)
                    eventOut.SetPosition(event.GetPosition())
                    self.GetEventHandler().ProcessEvent(eventOut)

            elif event.MiddleUp():
                # Middle Button Was Pressed
                eventOut = HyperLinkEvent(wxEVT_HYPERLINK_MIDDLE, self.GetId())
                eventOut.SetEventObject(self)
                eventOut.SetPosition(event.GetPosition())
                self.GetEventHandler().ProcessEvent(eventOut)

        event.Skip()

[docs]    def OnPopUpCopy(self, event):
        """
        Handles the ``wx.EVT_MENU`` event for L{HyperLinkCtrl}.

        :param `event`: a `wx.MenuEvent` event to be processed.

        :note: This method copies the data from the L{HyperLinkCtrl} to the clipboard.
        """

        wx.TheClipboard.UsePrimarySelection(False)
        if not wx.TheClipboard.Open():
            return
        data = wx.TextDataObject(self._URL)
        wx.TheClipboard.SetData(data)
        wx.TheClipboard.Close()

[docs]    def UpdateLink(self, OnRefresh=True):
        """
        Updates the link, changing text properties if:

        - User specific setting;
        - Link visited;
        - New link;

        :param `OnRefresh`: ``True`` to refresh the control, ``False`` otherwise.

        """

        fontTemp = self.GetFont()

        if self._Visited:
            self.SetForegroundColour(self._VisitedColour)
            fontTemp.SetUnderlined(self._VisitedUnderline)

        else:

            self.SetForegroundColour(self._LinkColour)
            fontTemp.SetUnderlined(self._LinkUnderline)

        if self._Bold:
            fontTemp.SetWeight(wx.BOLD)

        if self.GetFont() != fontTemp:
            self.SetFont(fontTemp)

        self.Refresh(OnRefresh)

[docs]    def DisplayError(self, ErrorMessage, ReportErrors=True):
        """
        Displays an error message (according to the `ReportErrors` parameter) in a
        `wx.MessageBox`.

        :param `ErrorMessage`: a string representing the error to display;
        :param `ReportErrors`: ``True`` to display error dialog if an error occurrs
         navigating to the URL.
        """

        if ReportErrors:
            wx.MessageBox(ErrorMessage, "HyperLinks Error", wx.OK | wx.CENTRE | wx.ICON_ERROR)

[docs]    def SetColours(self, link=wx.Colour(0, 0, 255), visited=wx.Colour(79, 47, 79),
                   rollover=wx.Colour(0, 0, 255)):
        """
        Sets the colours for the link, the visited link and the mouse rollover.

        - Visited link: VIOLET
        - Rollover: BLUE

        :param `link`: a valid `wx.Colour` to use as text foreground for new links
         (default=RED);
        :param `visited`: a valid `wx.Colour` to use as text foreground for visited
         links (default=VIOLET);
        :param `rollover`: a valid `wx.Colour` to use as text foreground for links
         rollovers (default=BLUE).
        """

        self._LinkColour = link
        self._VisitedColour = visited
        self._LinkRolloverColour = rollover

[docs]    def GetColours(self):
        """
        Gets the colours for the link, the visited link and the mouse
        rollover.
        """

        return self._LinkColour, self._VisitedColour, self._LinkRolloverColour

[docs]    def SetUnderlines(self, link=True, visited=True, rollover=True):
        """
        Sets whether the text should be underlined or not for new links, visited
        links and rollovers.

        :param `link`: ``True`` to set the text of new links as underlined, ``False``
         otherwise;
        :param `visited`: ``True`` to set the text of visited links as underlined,
         ``False`` otherwise;
        :param `rollover`: ``True`` to set the text of rollovers as underlined,
         ``False`` otherwise.
        """

        self._LinkUnderline = link
        self._RolloverUnderline = rollover
        self._VisitedUnderline = visited

[docs]    def GetUnderlines(self):
        """
        Returns if link is underlined, if the mouse rollover is
        underlined and if the visited link is underlined.
        """

        return self._LinkUnderline, self._RolloverUnderline, self._VisitedUnderline

[docs]    def SetLinkCursor(self, cur=wx.CURSOR_HAND):
        """
        Sets link cursor properties.

        :param `cur`: an integer representing a `wx.StockCursor` constant.
        """

        self._CursorHand = wx.StockCursor(cur)

[docs]    def GetLinkCursor(self):
        """ Gets the link cursor. """

        return self._CursorHand

[docs]    def SetVisited(self, Visited=False):
        """
        Sets a link as visited.

        :param `Visited`: ``True`` to set a link as visited, ``False`` otherwise.
        """

        self._Visited = Visited

[docs]    def GetVisited(self):
        """ Returns whether a link has been visited or not. """

        return self._Visited

[docs]    def SetBold(self, Bold=False):
        """
        Sets the L{HyperLinkCtrl} label in bold text.

        :param `Bold`: ``True`` to set the L{HyperLinkCtrl} label as bold, ``False``
         otherwise.
        """

        self._Bold = Bold

[docs]    def GetBold(self):
        """ Returns whether the L{HyperLinkCtrl} has text in bold or not. """

        return self._Bold

[docs]    def SetURL(self, URL):
        """
        Sets the L{HyperLinkCtrl} text to the specified URL.

        :param `URL`: the new URL associated with L{HyperLinkCtrl}.
        """

        self._URL = URL

[docs]    def GetURL(self):
        """ Retrieve the URL associated to the L{HyperLinkCtrl}. """

        return self._URL

[docs]    def OpenInSameWindow(self, NotSameWinIfPossible=False):
        """
        Open multiple URL in the same window (if possible).

        :param `NotSameWinIfPossible`: ``True`` to open an hyperlink in a new browser
         window, ``False`` to use an existing browser window.
        """

        self._NotSameWinIfPossible = NotSameWinIfPossible

[docs]    def EnableRollover(self, EnableRollover=False):
        """
        Enable/disable rollover.

        :param `EnableRollover`: ``True`` to enable text effects during rollover,
         ``False`` to disable them.
        """

        self._EnableRollover = EnableRollover

[docs]    def ReportErrors(self, ReportErrors=True):
        """
        Set whether to report browser errors or not.

        :param `ReportErrors`: Use ``True`` to display error dialog if an error
         occurrs navigating to the URL;
        """

        self._ReportErrors = ReportErrors

[docs]    def AutoBrowse(self, AutoBrowse=True):
        """
        Automatically browse to URL when clicked.

        :param `AutoBrowse`: ``True`` to automatically browse to an URL when clicked,
         ``False`` otherwise.

        :note: Set `AutoBrowse` to ``False`` to receive ``EVT_HYPERLINK_LEFT`` events.
        """

        self._AutoBrowse = AutoBrowse

[docs]    def DoPopup(self, DoPopup=True):
        """
        Sets whether to show popup menu on right click or not.

        :param `DoPopup`: ``True`` to show a popup menu on right click, ``False`` otherwise.
        """

        self._DoPopup = DoPopup

Navigation

  • index
  • modules |
  • Home |
  • Gallery |
  • Contents»
  • Module code »
  • hyperlink


hypertreelist

  • modules |
  • Home |
  • Gallery |
  • Contents»
  • Module code »
  • hypertreelist

Source code for hypertreelist

# --------------------------------------------------------------------------------- #
# HYPERTREELIST wxPython IMPLEMENTATION
# Inspired By And Heavily Based On wx.gizmos.TreeListCtrl.
#
# Andrea Gavana, @ 08 May 2006
# Latest Revision: 03 Mar 2012, 21.00 GMT
#
#
# TODO List
#
# Almost All The Features Of wx.gizmos.TreeListCtrl Are Available, And There Is
# Practically No Limit In What Could Be Added To This Class. The First Things
# That Comes To My Mind Are:
#
# 1. Add Support For 3-State CheckBoxes (Is That Really Useful?).
#
# 2. Try To Implement A More Flicker-Free Background Image In Cases Like
#    Centered Or Stretched Image (Now HyperTreeList Supports Only Tiled
#    Background Images).
#
# 3. Try To Mimic Windows wx.TreeCtrl Expanding/Collapsing behaviour: HyperTreeList
#    Suddenly Expands/Collapses The Nodes On Mouse Click While The Native Control
#    Has Some Kind Of "Smooth" Expanding/Collapsing, Like A Wave. I Don't Even
#    Know Where To Start To Do That.
#
# 4. Speed Up General OnPaint Things? I Have No Idea, Here HyperTreeList Is Quite
#    Fast, But We Should See On Slower Machines.
#
#
# 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
# --------------------------------------------------------------------------------- #

"""
L{HyperTreeList} is a class that mimics the behaviour of `wx.gizmos.TreeListCtrl`, with
some more functionalities.

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

L{HyperTreeList} is a class that mimics the behaviour of `wx.gizmos.TreeListCtrl`, with
almost the same base functionalities plus some more enhancements. This class does
not rely on the native control, as it is a full owner-drawn tree-list control.

L{HyperTreeList} is somewhat an hybrid between L{CustomTreeCtrl} and `wx.gizmos.TreeListCtrl`.

In addition to the standard `wx.gizmos.TreeListCtrl` behaviour this class supports:

* CheckBox-type items: checkboxes are easy to handle, just selected or unselected
  state with no particular issues in handling the item's children;
* Added support for 3-state value checkbox items;
* RadioButton-type items: since I elected to put radiobuttons in L{CustomTreeCtrl}, I
  needed some way to handle them, that made sense. So, I used the following approach:

  - All peer-nodes that are radiobuttons will be mutually exclusive. In other words,
    only one of a set of radiobuttons that share a common parent can be checked at
    once. If a radiobutton node becomes checked, then all of its peer radiobuttons
    must be unchecked.
  - If a radiobutton node becomes unchecked, then all of its child nodes will become
    inactive.

* Hyperlink-type items: they look like an hyperlink, with the proper mouse cursor on
  hovering;
* Multiline text items;
* Enabling/disabling items (together with their plain or grayed out icons);
* Whatever non-toplevel widget can be attached next to a tree item;
* Whatever non-toplevel widget can be attached next to a list item;
* Column headers are fully customizable in terms of icons, colour, font, alignment etc...;
* Default selection style, gradient (horizontal/vertical) selection style and Windows
  Vista selection style;
* Customized drag and drop images built on the fly;
* Setting the L{HyperTreeList} item buttons to a personalized imagelist;
* Setting the L{HyperTreeList} check/radio item icons to a personalized imagelist;
* Changing the style of the lines that connect the items (in terms of `wx.Pen` styles);
* Using an image as a L{HyperTreeList} background (currently only in "tile" mode);
* Ellipsization of long items when the horizontal space is low, via the ``TR_ELLIPSIZE_LONG_ITEMS``
  style (`New in version 0.9.3`).

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

Base Functionalities
====================

L{HyperTreeList} supports all the `wx.gizmos.TreeListCtrl` styles, except:

- ``TR_EXTENDED``: supports for this style is on the todo list (Am I sure of this?).

Plus it has 3 more styles to handle checkbox-type items:

- ``TR_AUTO_CHECK_CHILD``: automatically checks/unchecks the item children;
- ``TR_AUTO_CHECK_PARENT``: automatically checks/unchecks the item parent;
- ``TR_AUTO_TOGGLE_CHILD``: automatically toggles the item children.

And a style useful to hide the TreeListCtrl header:

- ``TR_NO_HEADER``: hides the L{HyperTreeList} header.

And a style related to long items (with a lot of text in them), which can be
ellipsized:

- ``TR_ELLIPSIZE_LONG_ITEMS``: ellipsizes long items when the horizontal space for
  L{HyperTreeList} is low (`New in version 0.9.3`).

All the methods available in `wx.gizmos.TreeListCtrl` are also available in L{HyperTreeList}.

Usage
=====

Usage example::

    import wx
    import wx.lib.agw.hypertreelist as HTL

    class MyFrame(wx.Frame):

        def __init__(self, parent):

            wx.Frame.__init__(self, parent, -1, "HyperTreeList Demo")

            tree_list = HTL.HyperTreeList(self)

            tree_list.AddColumn("First column")

            root = tree_list.AddRoot("Root", ct_type=1)

            parent = tree_list.AppendItem(root, "First child", ct_type=1)
            child = tree_list.AppendItem(parent, "First Grandchild", ct_type=1)

            tree_list.AppendItem(root, "Second child", ct_type=1)

    # our normal wxApp-derived class, as usual

    app = wx.PySimpleApp()

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

    app.MainLoop()

Events
======

All the events supported by `wx.gizmos.TreeListCtrl` are also available in L{HyperTreeList},
with a few exceptions:

- ``EVT_TREE_GET_INFO`` (don't know what this means);
- ``EVT_TREE_SET_INFO`` (don't know what this means);
- ``EVT_TREE_ITEM_MIDDLE_CLICK`` (not implemented, but easy to add);
- ``EVT_TREE_STATE_IMAGE_CLICK`` (no need for that, look at the checking events below).

Plus, L{HyperTreeList} supports the events related to the checkbutton-type items:

- ``EVT_TREE_ITEM_CHECKING``: an item is being checked;
- ``EVT_TREE_ITEM_CHECKED``: an item has been checked.

And to hyperlink-type items:

- ``EVT_TREE_ITEM_HYPERLINK``: an hyperlink item has been clicked (this event is sent
  after the ``EVT_TREE_SEL_CHANGED`` event).

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

L{HyperTreeList} has been tested on the following platforms:
  * Windows (Windows XP);

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

This class supports the following window styles:

============================== =========== ==================================================
Window Styles                  Hex Value   Description
============================== =========== ==================================================
``TR_NO_BUTTONS``                      0x0 For convenience to document that no buttons are to be drawn.
``TR_SINGLE``                          0x0 For convenience to document that only one item may be selected at a time. Selecting another item causes the current selection, if any, to be deselected. This is the default.
``TR_HAS_BUTTONS``                     0x1 Use this style to show + and - buttons to the left of parent items.
``TR_NO_LINES``                        0x4 Use this style to hide vertical level connectors.
``TR_LINES_AT_ROOT``                   0x8 Use this style to show lines between root nodes. Only applicable if ``TR_HIDE_ROOT`` is set and ``TR_NO_LINES`` is not set.
``TR_DEFAULT_STYLE``                   0x9 The set of flags that are closest to the defaults for the native control for a particular toolkit.
``TR_TWIST_BUTTONS``                  0x10 Use old Mac-twist style buttons.
``TR_MULTIPLE``                       0x20 Use this style to allow a range of items to be selected. If a second range is selected, the current range, if any, is deselected.
``TR_EXTENDED``                       0x40 Use this style to allow disjoint items to be selected. (Only partially implemented; may not work in all cases).
``TR_HAS_VARIABLE_ROW_HEIGHT``        0x80 Use this style to cause row heights to be just big enough to fit the content. If not set, all rows use the largest row height. The default is that this flag is unset.
``TR_EDIT_LABELS``                   0x200 Use this style if you wish the user to be able to edit labels in the tree control.
``TR_ROW_LINES``                     0x400 Use this style to draw a contrasting border between displayed rows.
``TR_HIDE_ROOT``                     0x800 Use this style to suppress the display of the root node, effectively causing the first-level nodes to appear as a series of root nodes.
``TR_COLUMN_LINES``                 0x1000 Use this style to draw a contrasting border between displayed columns.
``TR_FULL_ROW_HIGHLIGHT``           0x2000 Use this style to have the background colour and the selection highlight extend  over the entire horizontal row of the tree control window.
``TR_AUTO_CHECK_CHILD``             0x4000 Only meaningful foe checkbox-type items: when a parent item is checked/unchecked its children are checked/unchecked as well.
``TR_AUTO_TOGGLE_CHILD``            0x8000 Only meaningful foe checkbox-type items: when a parent item is checked/unchecked its children are toggled accordingly.
``TR_AUTO_CHECK_PARENT``           0x10000 Only meaningful foe checkbox-type items: when a child item is checked/unchecked its parent item is checked/unchecked as well.
``TR_ALIGN_WINDOWS``               0x20000 Flag used to align windows (in items with windows) at the same horizontal position.
``TR_NO_HEADER``                   0x40000 Use this style to hide the columns header.
``TR_ELLIPSIZE_LONG_ITEMS``        0x80000 Flag used to ellipsize long items when the horizontal space for L{HyperTreeList} columns is low.
``TR_VIRTUAL``                    0x100000 L{HyperTreeList} will have virtual behaviour.
============================== =========== ==================================================

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

This class processes the following events:

============================== ==================================================
Event Name                     Description
============================== ==================================================
``EVT_LIST_COL_BEGIN_DRAG``    The user started resizing a column - can be vetoed.
``EVT_LIST_COL_CLICK``         A column has been left-clicked.
``EVT_LIST_COL_DRAGGING``      The divider between columns is being dragged.
``EVT_LIST_COL_END_DRAG``      A column has been resized by the user.
``EVT_LIST_COL_RIGHT_CLICK``   A column has been right-clicked.
``EVT_TREE_BEGIN_DRAG``        Begin dragging with the left mouse button.
``EVT_TREE_BEGIN_LABEL_EDIT``  Begin editing a label. This can be prevented by calling L{TreeEvent.Veto}.
``EVT_TREE_BEGIN_RDRAG``       Begin dragging with the right mouse button.
``EVT_TREE_DELETE_ITEM``       Delete an item.
``EVT_TREE_END_DRAG``          End dragging with the left or right mouse button.
``EVT_TREE_END_LABEL_EDIT``    End editing a label. This can be prevented by calling L{TreeEvent.Veto}.
``EVT_TREE_GET_INFO``          Request information from the application (not implemented in L{HyperTreeList}).
``EVT_TREE_ITEM_ACTIVATED``    The item has been activated, i.e. chosen by double clicking it with mouse or from keyboard.
``EVT_TREE_ITEM_CHECKED``      A checkbox or radiobox type item has been checked.
``EVT_TREE_ITEM_CHECKING``     A checkbox or radiobox type item is being checked.
``EVT_TREE_ITEM_COLLAPSED``    The item has been collapsed.
``EVT_TREE_ITEM_COLLAPSING``   The item is being collapsed. This can be prevented by calling L{TreeEvent.Veto}.
``EVT_TREE_ITEM_EXPANDED``     The item has been expanded.s
``EVT_TREE_ITEM_EXPANDING``    The item is being expanded. This can be prevented by calling L{TreeEvent.Veto}.
``EVT_TREE_ITEM_GETTOOLTIP``   The opportunity to set the item tooltip is being given to the application (call L{TreeEvent.SetToolTip}).
``EVT_TREE_ITEM_HYPERLINK``    An hyperlink type item has been clicked.
``EVT_TREE_ITEM_MENU``         The context menu for the selected item has been requested, either by a right click or by using the menu key.
``EVT_TREE_ITEM_MIDDLE_CLICK`` The user has clicked the item with the middle mouse button (not implemented in L{HyperTreeList}).
``EVT_TREE_ITEM_RIGHT_CLICK``  The user has clicked the item with the right mouse button.
``EVT_TREE_KEY_DOWN``          A key has been pressed.
``EVT_TREE_SEL_CHANGED``       Selection has changed.
``EVT_TREE_SEL_CHANGING``      Selection is changing. This can be prevented by calling L{TreeEvent.Veto}.
``EVT_TREE_SET_INFO``          Information is being supplied to the application (not implemented in L{HyperTreeList}).
``EVT_TREE_STATE_IMAGE_CLICK`` The state image has been clicked (not implemented in L{HyperTreeList}).
============================== ==================================================

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

L{HyperTreeList} is distributed under the wxPython license.

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

Version 1.3

"""

import wx
import wx.gizmos

from customtreectrl import CustomTreeCtrl
from customtreectrl import DragImage, TreeEvent, GenericTreeItem, ChopText
from customtreectrl import TreeEditTimer as TreeListEditTimer
from customtreectrl import EVT_TREE_ITEM_CHECKING, EVT_TREE_ITEM_CHECKED, EVT_TREE_ITEM_HYPERLINK

# Version Info
__version__ = "1.3"

# --------------------------------------------------------------------------
# Constants
# --------------------------------------------------------------------------

_NO_IMAGE = -1

_DEFAULT_COL_WIDTH = 100
_LINEHEIGHT = 10
_LINEATROOT = 5
_MARGIN = 2
_MININDENT = 16
_BTNWIDTH = 9
_BTNHEIGHT = 9
_EXTRA_WIDTH = 4
_EXTRA_HEIGHT = 4

_MAX_WIDTH = 30000  # pixels; used by OnPaint to redraw only exposed items

_DRAG_TIMER_TICKS = 250   # minimum drag wait time in ms
_FIND_TIMER_TICKS = 500   # minimum find wait time in ms
_EDIT_TIMER_TICKS = 250 # minimum edit wait time in ms

# --------------------------------------------------------------------------
# Additional HitTest style
# --------------------------------------------------------------------------
TREE_HITTEST_ONITEMCHECKICON  = 0x4000

# HyperTreeList styles
TR_NO_BUTTONS = wx.TR_NO_BUTTONS                               # for convenience
""" For convenience to document that no buttons are to be drawn. """
TR_HAS_BUTTONS = wx.TR_HAS_BUTTONS                             # draw collapsed/expanded btns
""" Use this style to show + and - buttons to the left of parent items. """
TR_NO_LINES = wx.TR_NO_LINES                                   # don't draw lines at all
""" Use this style to hide vertical level connectors. """
TR_LINES_AT_ROOT = wx.TR_LINES_AT_ROOT                         # connect top-level nodes
""" Use this style to show lines between root nodes. Only applicable if ``TR_HIDE_ROOT`` is""" \
""" set and ``TR_NO_LINES`` is not set. """
TR_TWIST_BUTTONS = wx.TR_TWIST_BUTTONS                         # still used by wxTreeListCtrl
""" Use old Mac-twist style buttons. """
TR_SINGLE = wx.TR_SINGLE                                       # for convenience
""" For convenience to document that only one item may be selected at a time. Selecting another""" \
""" item causes the current selection, if any, to be deselected. This is the default. """
TR_MULTIPLE = wx.TR_MULTIPLE                                   # can select multiple items
""" Use this style to allow a range of items to be selected. If a second range is selected,""" \
""" the current range, if any, is deselected. """
TR_EXTENDED = wx.TR_EXTENDED                                   # TODO: allow extended selection
""" Use this style to allow disjoint items to be selected. (Only partially implemented;""" \
""" may not work in all cases). """
TR_HAS_VARIABLE_ROW_HEIGHT = wx.TR_HAS_VARIABLE_ROW_HEIGHT     # what it says
""" Use this style to cause row heights to be just big enough to fit the content.""" \
""" If not set, all rows use the largest row height. The default is that this flag is unset. """
TR_EDIT_LABELS = wx.TR_EDIT_LABELS                             # can edit item labels
""" Use this style if you wish the user to be able to edit labels in the tree control. """
TR_ROW_LINES = wx.TR_ROW_LINES                                 # put border around items
""" Use this style to draw a contrasting border between displayed rows. """
TR_HIDE_ROOT = wx.TR_HIDE_ROOT                                 # don't display root node
""" Use this style to suppress the display of the root node, effectively causing the""" \
""" first-level nodes to appear as a series of root nodes. """
TR_FULL_ROW_HIGHLIGHT = wx.TR_FULL_ROW_HIGHLIGHT               # highlight full horz space
""" Use this style to have the background colour and the selection highlight extend """ \
""" over the entire horizontal row of the tree control window. """

TR_AUTO_CHECK_CHILD = 0x04000                                  # only meaningful for checkboxes
""" Only meaningful foe checkbox-type items: when a parent item is checked/unchecked""" \
""" its children are checked/unchecked as well. """
TR_AUTO_TOGGLE_CHILD = 0x08000                                 # only meaningful for checkboxes
""" Only meaningful foe checkbox-type items: when a parent item is checked/unchecked""" \
""" its children are toggled accordingly. """
TR_AUTO_CHECK_PARENT = 0x10000                                 # only meaningful for checkboxes
""" Only meaningful foe checkbox-type items: when a child item is checked/unchecked""" \
""" its parent item is checked/unchecked as well. """
TR_ALIGN_WINDOWS = 0x20000                                     # to align windows horizontally for items at the same level
""" Flag used to align windows (in items with windows) at the same horizontal position. """
TR_ELLIPSIZE_LONG_ITEMS = 0x80000                              # to ellipsize long items when horizontal space is low
""" Flag used to ellipsize long items when the horizontal space for L{HyperTreeList} columns is low."""
TR_VIRTUAL = 0x100000
""" L{HyperTreeList} will have virtual behaviour. """

# --------------------------------------------------------------------------
# Additional HyperTreeList style to hide the header
# --------------------------------------------------------------------------
TR_NO_HEADER = 0x40000
""" Use this style to hide the columns header. """
# --------------------------------------------------------------------------

[docs]def IsBufferingSupported():
    """
    Utility function which checks if a platform handles correctly double
    buffering for the header. Currently returns ``False`` for all platforms
    except Windows XP.
    """

    if wx.Platform != "__WXMSW__":
        return False

    if wx.App.GetComCtl32Version() >= 600:
        if wx.GetOsVersion()[1] > 5:
            # Windows Vista
            return False

        return True

    return False

[docs]class TreeListColumnInfo(object):
    """
    Class used to store information (width, alignment flags, colours, etc...) about a
    L{HyperTreeList} column header.
    """

[docs]    def __init__(self, input="", width=_DEFAULT_COL_WIDTH, flag=wx.ALIGN_LEFT,
                 image=-1, shown=True, colour=None, edit=False):
        """
        Default class constructor.

        :param `input`: can be a string (representing the column header text) or
         another instance of L{TreeListColumnInfo}. In the latter case, all the
         other input parameters are not used;
        :param `width`: the column width in pixels;
        :param `flag`: the column alignment flag, one of ``wx.ALIGN_LEFT``,
         ``wx.ALIGN_RIGHT``, ``wx.ALIGN_CENTER``;
        :param `image`: an index within the normal image list assigned to
         L{HyperTreeList} specifying the image to use for the column;
        :param `shown`: ``True`` to show the column, ``False`` to hide it;
        :param `colour`: a valid `wx.Colour`, representing the text foreground colour
         for the column;
        :param `edit`: ``True`` to set the column as editable, ``False`` otherwise.
        """

        if isinstance(input, basestring):
            self._text = input
            self._width = width
            self._flag = flag
            self._image = image
            self._selected_image = -1
            self._shown = shown
            self._edit = edit
            self._font = wx.SystemSettings_GetFont(wx.SYS_DEFAULT_GUI_FONT)
            if colour is None:
                self._colour = wx.SystemSettings_GetColour(wx.SYS_COLOUR_WINDOWTEXT)
            else:
                self._colour = colour

        else:

            self._text = input._text
            self._width = input._width
            self._flag = input._flag
            self._image = input._image
            self._selected_image = input._selected_image
            self._shown = input._shown
            self._edit = input._edit
            self._colour = input._colour
            self._font = input._font

    # get/set

[docs]    def GetText(self):
        """ Returns the column header label. """

        return self._text

[docs]    def SetText(self, text):
        """
        Sets the column header label.

        :param `text`: the new column header text.
        """

        self._text = text
        return self

[docs]    def GetWidth(self):
        """ Returns the column header width in pixels. """

        return self._width

[docs]    def SetWidth(self, width):
        """
        Sets the column header width.

        :param `width`: the column header width, in pixels.
        """

        self._width = width
        return self

[docs]    def GetAlignment(self):
        """ Returns the column text alignment. """

        return self._flag

[docs]    def SetAlignment(self, flag):
        """
        Sets the column text alignment.

        :param `flag`: the alignment flag, one of ``wx.ALIGN_LEFT``, ``wx.ALIGN_RIGHT``,
         ``wx.ALIGN_CENTER``.
        """

        self._flag = flag
        return self

[docs]    def GetColour(self):
        """ Returns the column text colour. """

        return self._colour

[docs]    def SetColour(self, colour):
        """
        Sets the column text colour.

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

        self._colour = colour
        return self

[docs]    def GetImage(self):
        """ Returns the column image index. """

        return self._image

[docs]    def SetImage(self, image):
        """
        Sets the column image index.

        :param `image`: an index within the normal image list assigned to
         L{HyperTreeList} specifying the image to use for the column.
        """

        self._image = image
        return self

[docs]    def GetSelectedImage(self):
        """ Returns the column image index in the selected state. """

        return self._selected_image

[docs]    def SetSelectedImage(self, image):
        """
        Sets the column image index in the selected state.

        :param `image`: an index within the normal image list assigned to
         L{HyperTreeList} specifying the image to use for the column when in
         selected state.
        """

        self._selected_image = image
        return self

[docs]    def IsEditable(self):
        """ Returns ``True`` if the column is editable, ``False`` otherwise. """

        return self._edit

[docs]    def SetEditable(self, edit):
        """
        Sets the column as editable or non-editable.

        :param `edit`: ``True`` if the column should be editable, ``False`` otherwise.
        """

        self._edit = edit
        return self

[docs]    def IsShown(self):
        """ Returns ``True`` if the column is shown, ``False`` if it is hidden. """

        return self._shown

[docs]    def SetShown(self, shown):
        """
        Sets the column as shown or hidden.

        :param `shown`: ``True`` if the column should be shown, ``False`` if it
         should be hidden.
        """

        self._shown = shown
        return self

[docs]    def SetFont(self, font):
        """
        Sets the column text font.

        :param `font`: a valid `wx.Font` object.
        """

        self._font = font
        return self

[docs]    def GetFont(self):
        """ Returns the column text font. """

        return self._font

#-----------------------------------------------------------------------------
#  TreeListHeaderWindow (internal)
#-----------------------------------------------------------------------------

[docs]class TreeListHeaderWindow(wx.Window):
    """ A window which holds the header of L{HyperTreeList}. """

[docs]    def __init__(self, parent, id=wx.ID_ANY, owner=None, pos=wx.DefaultPosition,
                 size=wx.DefaultSize, style=0, name="wxtreelistctrlcolumntitles"):
        """
        Default class constructor.

        :param `parent`: the window parent. Must not be ``None``;
        :param `id`: window identifier. A value of -1 indicates a default value;
        :param `owner`: the window owner, in this case an instance of L{TreeListMainWindow};
        :param `pos`: the control position. A value of (-1, -1) indicates a default position,
         chosen by either the windowing system or wxPython, depending on platform;
        :param `size`: the control size. A value of (-1, -1) indicates a default size,
         chosen by either the windowing system or wxPython, depending on platform;
        :param `style`: the window style;
        :param `name`: the window name.
        """

        wx.Window.__init__(self, parent, id, pos, size, style, name=name)

        self._owner = owner
        self._currentCursor = wx.StockCursor(wx.CURSOR_DEFAULT)
        self._resizeCursor = wx.StockCursor(wx.CURSOR_SIZEWE)
        self._isDragging = False
        self._dirty = False
        self._total_col_width = 0
        self._hotTrackCol = -1
        self._columns = []
        self._headerCustomRenderer = None

        self.Bind(wx.EVT_PAINT, self.OnPaint)
        self.Bind(wx.EVT_MOUSE_EVENTS, self.OnMouse)
        self.Bind(wx.EVT_SET_FOCUS, self.OnSetFocus)

        self.SetBackgroundStyle(wx.BG_STYLE_CUSTOM)

[docs]    def SetBuffered(self, buffered):
        """
        Sets/unsets the double buffering for the header.

        :param `buffered`: ``True`` to use double-buffering, ``False`` otherwise.

        :note: Currently we are using double-buffering only on Windows XP.
        """

        self._buffered = buffered

    # total width of all columns

[docs]    def GetWidth(self):
        """ Returns the total width of all columns. """

        return self._total_col_width

    # column manipulation

[docs]    def GetColumnCount(self):
        """ Returns the total number of columns. """

        return len(self._columns)

    # column information manipulation

[docs]    def GetColumn(self, column):
        """
        Returns a column item, an instance of L{TreeListItem}.

        :param `column`: an integer specifying the column index.
        """

        if column < 0 or column >= self.GetColumnCount():
            raise Exception("Invalid column")

        return self._columns[column]

[docs]    def GetColumnText(self, column):
        """
        Returns the column text label.

        :param `column`: an integer specifying the column index.
        """

        if column < 0 or column >= self.GetColumnCount():
            raise Exception("Invalid column")

        return self._columns[column].GetText()

[docs]    def SetColumnText(self, column, text):
        """
        Sets the column text label.

        :param `column`: an integer specifying the column index;
        :param `text`: the new column label.
        """

        if column < 0 or column >= self.GetColumnCount():
            raise Exception("Invalid column")

        return self._columns[column].SetText(text)

[docs]    def GetColumnAlignment(self, column):
        """
        Returns the column text alignment.

        :param `column`: an integer specifying the column index.
        """

        if column < 0 or column >= self.GetColumnCount():
            raise Exception("Invalid column")

        return self._columns[column].GetAlignment()

[docs]    def SetColumnAlignment(self, column, flag):
        """
        Sets the column text alignment.

        :param `column`: an integer specifying the column index;
        :param `flag`: the new text alignment flag.

        :see: L{TreeListColumnInfo.SetAlignment} for a list of valid alignment
         flags.
        """

        if column < 0 or column >= self.GetColumnCount():
            raise Exception("Invalid column")

        return self._columns[column].SetAlignment(flag)

[docs]    def GetColumnWidth(self, column):
        """
        Returns the column width, in pixels.

        :param `column`: an integer specifying the column index.
        """

        if column < 0 or column >= self.GetColumnCount():
            raise Exception("Invalid column")

        return self._columns[column].GetWidth()

[docs]    def GetColumnColour(self, column):
        """
        Returns the column text colour.

        :param `column`: an integer specifying the column index.
        """

        if column < 0 or column >= self.GetColumnCount():
            raise Exception("Invalid column")

        return self._columns[column].GetColour()

[docs]    def SetColumnColour(self, column, colour):
        """
        Sets the column text colour.

        :param `column`: an integer specifying the column index;
        :param `colour`: a valid `wx.Colour` object.
        """

        if column < 0 or column >= self.GetColumnCount():
            raise Exception("Invalid column")

        return self._columns[column].SetColour(colour)

[docs]    def IsColumnEditable(self, column):
        """
        Returns ``True`` if the column is editable, ``False`` otherwise.

        :param `column`: an integer specifying the column index.
        """

        if column < 0 or column >= self.GetColumnCount():
            raise Exception("Invalid column")

        return self._columns[column].IsEditable()

[docs]    def IsColumnShown(self, column):
        """
        Returns ``True`` if the column is shown, ``False`` if it is hidden.

        :param `column`: an integer specifying the column index.
        """

        if column < 0 or column >= self.GetColumnCount():
            raise Exception("Invalid column")

        return self._columns[column].IsShown()

    # shift the DC origin to match the position of the main window horz
    # scrollbar: this allows us to always use logical coords

[docs]    def AdjustDC(self, dc):
        """
        Shifts the `wx.DC` origin to match the position of the main window horizontal
        scrollbar: this allows us to always use logical coordinates.

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

        xpix, dummy = self._owner.GetScrollPixelsPerUnit()
        x, dummy = self._owner.GetViewStart()

        # account for the horz scrollbar offset
        dc.SetDeviceOrigin(-x * xpix, 0)

[docs]    def OnPaint(self, event):
        """
        Handles the ``wx.EVT_PAINT`` event for L{TreeListHeaderWindow}.

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

        if self._buffered:
            dc = wx.BufferedPaintDC(self)
        else:
            dc = wx.PaintDC(self)

        self.AdjustDC(dc)

        x = 0

        # width and height of the entire header window
        w, h = self.GetClientSize()
        w, dummy = self._owner.CalcUnscrolledPosition(w, 0)
        dc.SetBackgroundMode(wx.TRANSPARENT)

        numColumns = self.GetColumnCount()

        for i in xrange(numColumns):

            if x >= w:
                break

            if not self.IsColumnShown(i):
                continue # do next column if not shown

            params = wx.HeaderButtonParams()

            column = self.GetColumn(i)
            params.m_labelColour = column.GetColour()
            params.m_labelFont = column.GetFont()

            wCol = column.GetWidth()
            flags = 0
            rect = wx.Rect(x, 0, wCol, h)
            x += wCol

            if i == self._hotTrackCol:
                flags |= wx.CONTROL_CURRENT

            params.m_labelText = column.GetText()
            params.m_labelAlignment = column.GetAlignment()

            image = column.GetImage()
            imageList = self._owner.GetImageList()

            if image != -1 and imageList:
                params.m_labelBitmap = imageList.GetBitmap(image)

            if self._headerCustomRenderer != None:
               self._headerCustomRenderer.DrawHeaderButton(dc, rect, flags, params)
            else:
                wx.RendererNative.Get().DrawHeaderButton(self, dc, rect, flags,
                                                         wx.HDR_SORT_ICON_NONE, params)

        # Fill up any unused space to the right of the columns
        if x < w:
            rect = wx.Rect(x, 0, w-x, h)
            if self._headerCustomRenderer != None:
               self._headerCustomRenderer.DrawHeaderButton(dc, rect)
            else:
                wx.RendererNative.Get().DrawHeaderButton(self, dc, rect)

[docs]    def DrawCurrent(self):
        """ Draws the column resize line on a `wx.ScreenDC`. """

        x1, y1 = self._currentX, 0
        x1, y1 = self.ClientToScreen((x1, y1))
        x2 = self._currentX-1
        if wx.Platform == "__WXMSW__":
            x2 += 1 # but why ????

        y2 = 0
        dummy, y2 = self._owner.GetClientSize()
        x2, y2 = self._owner.ClientToScreen((x2, y2))

        dc = wx.ScreenDC()
        dc.SetLogicalFunction(wx.INVERT)
        dc.SetPen(wx.Pen(wx.BLACK, 2, wx.SOLID))
        dc.SetBrush(wx.TRANSPARENT_BRUSH)

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

[docs]    def SetCustomRenderer(self, renderer=None):
        """
        Associate a custom renderer with the header - all columns will use it

        :param `renderer`: a class able to correctly render header buttons

        :note: the renderer class **must** implement the method `DrawHeaderButton`
        """

        self._headerCustomRenderer = renderer

[docs]    def XToCol(self, x):
        """
        Returns the column that corresponds to the logical input `x` coordinate.

        :param `x`: the `x` position to evaluate.

        :return: The column that corresponds to the logical input `x` coordinate,
         or ``wx.NOT_FOUND`` if there is no column at the `x` position.
        """

        colLeft = 0
        numColumns = self.GetColumnCount()
        for col in xrange(numColumns):

            if not self.IsColumnShown(col):
                continue

            column = self.GetColumn(col)

            if x < (colLeft + column.GetWidth()):
                 return col

            colLeft += column.GetWidth()

        return wx.NOT_FOUND

[docs]    def RefreshColLabel(self, col):
        """
        Redraws the column.

        :param `col`: the index of the column to redraw.
        """

        if col >= self.GetColumnCount():
            return

        x = idx = width = 0
        while idx <= col:

            if not self.IsColumnShown(idx):
                idx += 1
                continue

            column = self.GetColumn(idx)
            x += width
            width = column.GetWidth()
            idx += 1

        x, dummy = self._owner.CalcScrolledPosition(x, 0)
        self.RefreshRect(wx.Rect(x, 0, width, self.GetSize().GetHeight()))

[docs]    def OnMouse(self, event):
        """
        Handles the ``wx.EVT_MOUSE_EVENTS`` event for L{TreeListHeaderWindow}.

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

        # we want to work with logical coords
        x, dummy = self._owner.CalcUnscrolledPosition(event.GetX(), 0)
        y = event.GetY()

        if event.Moving():

            col = self.XToCol(x)
            if col != self._hotTrackCol:

                # Refresh the col header so it will be painted with hot tracking
                # (if supported by the native renderer.)
                self.RefreshColLabel(col)

                # Also refresh the old hot header
                if self._hotTrackCol >= 0:
                    self.RefreshColLabel(self._hotTrackCol)

                self._hotTrackCol = col

        if event.Leaving() and self._hotTrackCol >= 0:

            # Leaving the window so clear any hot tracking indicator that may be present
            self.RefreshColLabel(self._hotTrackCol)
            self._hotTrackCol = -1

        if self._isDragging:

            self.SendListEvent(wx.wxEVT_COMMAND_LIST_COL_DRAGGING, event.GetPosition())

            # we don't draw the line beyond our window, but we allow dragging it
            # there
            w, dummy = self.GetClientSize()
            w, dummy = self._owner.CalcUnscrolledPosition(w, 0)
            w -= 6

            # erase the line if it was drawn
            if self._currentX < w:
                self.DrawCurrent()

            if event.ButtonUp():
                self._isDragging = False
                if self.HasCapture():
                    self.ReleaseMouse()
                self._dirty = True
                self.SetColumnWidth(self._column, self._currentX - self._minX)
                self.Refresh()
                self.SendListEvent(wx.wxEVT_COMMAND_LIST_COL_END_DRAG, event.GetPosition())
            else:
                self._currentX = max(self._minX + 7, x)

                # draw in the new location
                if self._currentX < w:
                    self.DrawCurrent()

        else: # not dragging

            self._minX = 0
            hit_border = False

            # end of the current column
            xpos = 0

            # find the column where this event occured
            countCol = self.GetColumnCount()

            for column in xrange(countCol):

                if not self.IsColumnShown(column):
                    continue # do next if not shown

                xpos += self.GetColumnWidth(column)
                self._column = column
                if abs (x-xpos) < 3 and y < 22:
                    # near the column border
                    hit_border = True
                    break

                if x < xpos:
                    # inside the column
                    break

                self._minX = xpos

            if event.LeftDown() or event.RightUp():
                if hit_border and event.LeftDown():
                    self._isDragging = True
                    self.CaptureMouse()
                    self._currentX = x
                    self.DrawCurrent()
                    self.SendListEvent(wx.wxEVT_COMMAND_LIST_COL_BEGIN_DRAG, event.GetPosition())
                else: # click on a column
                    evt = (event.LeftDown() and [wx.wxEVT_COMMAND_LIST_COL_CLICK] or [wx.wxEVT_COMMAND_LIST_COL_RIGHT_CLICK])[0]
                    self.SendListEvent(evt, event.GetPosition())

            elif event.LeftDClick() and hit_border:
                self.SetColumnWidth(self._column, self._owner.GetBestColumnWidth(self._column))
                self.Refresh()

            elif event.Moving():

                if hit_border:
                    setCursor = self._currentCursor == wx.STANDARD_CURSOR
                    self._currentCursor = self._resizeCursor
                else:
                    setCursor = self._currentCursor != wx.STANDARD_CURSOR
                    self._currentCursor = wx.STANDARD_CURSOR

                if setCursor:
                    self.SetCursor(self._currentCursor)

[docs]    def OnSetFocus(self, event):
        """
        Handles the ``wx.EVT_SET_FOCUS`` event for L{TreeListHeaderWindow}.

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

        self._owner.SetFocus()

[docs]    def SendListEvent(self, evtType, pos):
        """
        Sends a `wx.ListEvent` for the parent window.

        :param `evtType`: the event type;
        :param `pos`: an instance of `wx.Point`.
        """

        parent = self.GetParent()
        le = wx.ListEvent(evtType, parent.GetId())
        le.SetEventObject(parent)
        le.m_pointDrag = pos

        # the position should be relative to the parent window, not
        # this one for compatibility with MSW and common sense: the
        # user code doesn't know anything at all about this header
        # window, so why should it get positions relative to it?
        le.m_pointDrag.y -= self.GetSize().y
        le.m_col = self._column
        parent.GetEventHandler().ProcessEvent(le)

[docs]    def AddColumnInfo(self, colInfo):
        """
        Appends a column to the L{TreeListHeaderWindow}.

        :param `colInfo`: an instance of L{TreeListColumnInfo}.
        """

        self._columns.append(colInfo)
        self._total_col_width += colInfo.GetWidth()
        self._owner.AdjustMyScrollbars()
        self._owner._dirty = True

[docs]    def AddColumn(self, text, width=_DEFAULT_COL_WIDTH, flag=wx.ALIGN_LEFT,
                  image=-1, shown=True, colour=None, edit=False):
        """
        Appends a column to the L{TreeListHeaderWindow}.

        :param `text`: the column text label;
        :param `width`: the column width in pixels;
        :param `flag`: the column alignment flag, one of ``wx.ALIGN_LEFT``,
         ``wx.ALIGN_RIGHT``, ``wx.ALIGN_CENTER``;
        :param `image`: an index within the normal image list assigned to
         L{HyperTreeList} specifying the image to use for the column;
        :param `shown`: ``True`` to show the column, ``False`` to hide it;
        :param `colour`: a valid `wx.Colour`, representing the text foreground colour
         for the column;
        :param `edit`: ``True`` to set the column as editable, ``False`` otherwise.
        """

        colInfo = TreeListColumnInfo(text, width, flag, image, shown, colour, edit)
        self.AddColumnInfo(colInfo)

[docs]    def SetColumnWidth(self, column, width):
        """
        Sets the column width, in pixels.

        :param `column`: an integer specifying the column index;
        :param `width`: the new width for the column, in pixels.
        """

        if column < 0 or column >= self.GetColumnCount():
            raise Exception("Invalid column")

        self._total_col_width -= self._columns[column].GetWidth()
        self._columns[column].SetWidth(width)
        self._total_col_width += width
        self._owner.AdjustMyScrollbars()
        self._owner._dirty = True

[docs]    def InsertColumnInfo(self, before, colInfo):
        """
        Inserts a column to the L{TreeListHeaderWindow} at the position specified
        by `before`.

        :param `before`: the index at which we wish to insert the new column;
        :param `colInfo`: an instance of L{TreeListColumnInfo}.
        """

        if before < 0 or before >= self.GetColumnCount():
            raise Exception("Invalid column")

        self._columns.insert(before, colInfo)
        self._total_col_width += colInfo.GetWidth()
        self._owner.AdjustMyScrollbars()
        self._owner._dirty = True

[docs]    def InsertColumn(self, before, text, width=_DEFAULT_COL_WIDTH,
                     flag=wx.ALIGN_LEFT, image=-1, shown=True, colour=None,
                     edit=False):
        """
        Inserts a column to the L{TreeListHeaderWindow} at the position specified
        by `before`.

        :param `before`: the index at which we wish to insert the new column;
        :param `text`: the column text label;
        :param `width`: the column width in pixels;
        :param `flag`: the column alignment flag, one of ``wx.ALIGN_LEFT``,
         ``wx.ALIGN_RIGHT``, ``wx.ALIGN_CENTER``;
        :param `image`: an index within the normal image list assigned to
         L{HyperTreeList} specifying the image to use for the column;
        :param `shown`: ``True`` to show the column, ``False`` to hide it;
        :param `colour`: a valid `wx.Colour`, representing the text foreground colour
         for the column;
        :param `edit`: ``True`` to set the column as editable, ``False`` otherwise.
        """

        colInfo = TreeListColumnInfo(text, width, flag, image, shown, colour,
                                     edit)
        self.InsertColumnInfo(before, colInfo)

[docs]    def RemoveColumn(self, column):
        """
        Removes a column from the L{TreeListHeaderWindow}.

        :param `column`: an integer specifying the column index.
        """

        if column < 0 or column >= self.GetColumnCount():
            raise Exception("Invalid column")

        self._total_col_width -= self._columns[column].GetWidth()
        self._columns.pop(column)
        self._owner.AdjustMyScrollbars()
        self._owner._dirty = True

[docs]    def SetColumn(self, column, info):
        """
        Sets a column using an instance of L{TreeListColumnInfo}.

        :param `column`: an integer specifying the column index;
        :param `info`: an instance of L{TreeListColumnInfo}.
        """

        if column < 0 or column >= self.GetColumnCount():
            raise Exception("Invalid column")

        w = self._columns[column].GetWidth()
        self._columns[column] = info

        if w != info.GetWidth():
            self._total_col_width += info.GetWidth() - w
            self._owner.AdjustMyScrollbars()

        self._owner._dirty = True

# ---------------------------------------------------------------------------
# TreeListItem
# ---------------------------------------------------------------------------

[docs]class TreeListItem(GenericTreeItem):
    """
    This class holds all the information and methods for every single item in
    L{HyperTreeList}.

    :note: Subclassed from L{customtreectrl.GenericTreeItem}.
    """

[docs]    def __init__(self, mainWin, parent, text=[], ct_type=0, wnd=None, image=-1, selImage=-1, data=None):
        """
        Default class constructor.
        For internal use: do not call it in your code!

        :param `mainWin`: the main L{HyperTreeList} window, in this case an instance
         of L{TreeListMainWindow};
        :param `parent`: the tree item parent (may be ``None`` for root items);
        :param `text`: the tree item text;
        :param `ct_type`: the tree item kind. May be one of the following integers:

         =============== ==========================
         `ct_type` Value Description
         =============== ==========================
                0        A normal item
                1        A checkbox-like item
                2        A radiobutton-type item
         =============== ==========================

        :param `wnd`: if not ``None``, a non-toplevel window to be displayed next to
         the item;
        :param `image`: an index within the normal image list specifying the image to
         use for the item in unselected state;
        :param `selImage`: an index within the normal image list specifying the image to
         use for the item in selected state; if `image` > -1 and `selImage` is -1, the
         same image is used for both selected and unselected items;
        :param `data`: associate the given Python object `data` with the item.

        :note: Regarding radiobutton-type items (with `ct_type` = 2), the following
         approach is used:

         - All peer-nodes that are radiobuttons will be mutually exclusive. In other words,
           only one of a set of radiobuttons that share a common parent can be checked at
           once. If a radiobutton node becomes checked, then all of its peer radiobuttons
           must be unchecked.
         - If a radiobutton node becomes unchecked, then all of its child nodes will become
           inactive.
        """

        self._col_images = []
        self._owner = mainWin

        # We don't know the height here yet.
        self._text_x = 0

        GenericTreeItem.__init__(self, parent, text, ct_type, wnd, image, selImage, data)

        self._wnd = [None]             # are we holding a window?
        self._hidden = False

        if wnd:
            self.SetWindow(wnd)

[docs]    def IsHidden(self):
        """ Returns whether the item is hidden or not. """

        return self._hidden

[docs]    def Hide(self, hide):
        """
        Hides/shows the L{TreeListItem}.

        :param `hide`: ``True`` to hide the item, ``False`` to show it.
        """

        self._hidden = hide

[docs]    def DeleteChildren(self, tree):
        """
        Deletes the item children.

        :param `tree`: the main L{TreeListMainWindow} instance.
        """

        for child in self._children:
            if tree:
                tree.SendDeleteEvent(child)

            child.DeleteChildren(tree)

            if child == tree._selectItem:
                tree._selectItem = None

            # We have to destroy the associated window
            for wnd in child._wnd:
                if wnd:
                    wnd.Hide()
                    wnd.Destroy()

            child._wnd = []

            if child in tree._itemWithWindow:
                tree._itemWithWindow.remove(child)

            del child

        self._children = []

[docs]    def HitTest(self, point, theCtrl, flags, column, level):
        """
        HitTest method for an item. Called from the main window HitTest.

        :param `point`: the point to test for the hit (an instance of `wx.Point`);
        :param `theCtrl`: the main L{TreeListMainWindow} tree;
        :param `flags`: a bitlist of hit locations;
        :param `column`: an integer specifying the column index;
        :param `level`: the item's level inside the tree hierarchy.

        :see: L{TreeListMainWindow.HitTest} method for the flags explanation.
        """

        # for a hidden root node, don't evaluate it, but do evaluate children
        if not theCtrl.HasAGWFlag(wx.TR_HIDE_ROOT) or level > 0:

            # reset any previous hit infos
            flags = 0
            column = -1
            header_win = theCtrl._owner.GetHeaderWindow()

            # check for right of all columns (outside)
            if point.x > header_win.GetWidth():
                return None, flags, wx.NOT_FOUND

            # evaluate if y-pos is okay
            h = theCtrl.GetLineHeight(self)

            if point.y >= self._y and point.y <= self._y + h:

                maincol = theCtrl.GetMainColumn()

                # check for above/below middle
                y_mid = self._y + h/2
                if point.y < y_mid:
                    flags |= wx.TREE_HITTEST_ONITEMUPPERPART
                else:
                    flags |= wx.TREE_HITTEST_ONITEMLOWERPART

                # check for button hit
                if self.HasPlus() and theCtrl.HasButtons():
                    bntX = self._x - theCtrl._btnWidth2
                    bntY = y_mid - theCtrl._btnHeight2
                    if ((point.x >= bntX) and (point.x <= (bntX + theCtrl._btnWidth)) and
                        (point.y >= bntY) and (point.y <= (bntY + theCtrl._btnHeight))):
                        flags |= wx.TREE_HITTEST_ONITEMBUTTON
                        column = maincol
                        return self, flags, column

                # check for hit on the check icons
                if self.GetType() != 0:
                    imageWidth = 0
                    numberOfMargins = 1
                    if self.GetCurrentImage() != _NO_IMAGE:
                        imageWidth = theCtrl._imgWidth
                        numberOfMargins += 1
                    chkX = self._text_x - imageWidth - numberOfMargins*_MARGIN - theCtrl._checkWidth
                    chkY = y_mid - theCtrl._checkHeight2
                    if ((point.x >= chkX) and (point.x <= (chkX + theCtrl._checkWidth)) and
                        (point.y >= chkY) and (point.y <= (chkY + theCtrl._checkHeight))):
                        flags |= TREE_HITTEST_ONITEMCHECKICON
                        return self, flags, maincol

                # check for image hit
                if self.GetCurrentImage() != _NO_IMAGE:
                    imgX = self._text_x - theCtrl._imgWidth - _MARGIN
                    imgY = y_mid - theCtrl._imgHeight2
                    if ((point.x >= imgX) and (point.x <= (imgX + theCtrl._imgWidth)) and
                        (point.y >= imgY) and (point.y <= (imgY + theCtrl._imgHeight))):
                        flags |= wx.TREE_HITTEST_ONITEMICON
                        column = maincol
                        return self, flags, column

                # check for label hit
                if ((point.x >= self._text_x) and (point.x <= (self._text_x + self._width))):
                    flags |= wx.TREE_HITTEST_ONITEMLABEL
                    column = maincol
                    return self, flags, column

                # check for indent hit after button and image hit
                if point.x < self._x:
                    flags |= wx.TREE_HITTEST_ONITEMINDENT
                    column = -1 # considered not belonging to main column
                    return self, flags, column

                # check for right of label
                end = 0
                for i in xrange(maincol):
                    end += header_win.GetColumnWidth(i)
                    if ((point.x > (self._text_x + self._width)) and (point.x <= end)):
                        flags |= wx.TREE_HITTEST_ONITEMRIGHT
                        column = -1 # considered not belonging to main column
                        return self, flags, column

                # else check for each column except main
                x = 0
                for j in xrange(theCtrl.GetColumnCount()):
                    if not header_win.IsColumnShown(j):
                        continue
                    w = header_win.GetColumnWidth(j)
                    if ((j != maincol) and (point.x >= x and point.x < x+w)):
                        flags |= wx.TREE_HITTEST_ONITEMCOLUMN
                        column = j
                        return self, flags, column

                    x += w

                # no special flag or column found
                return self, flags, column

            # if children not expanded, return no item
            if not self.IsExpanded():
                return None, flags, wx.NOT_FOUND

        # in any case evaluate children
        for child in self._children:
            hit, flags, column = child.HitTest(point, theCtrl, flags, column, level+1)
            if hit:
                return hit, flags, column

        # not found
        return None, flags, wx.NOT_FOUND

[docs]    def GetText(self, column=None):
        """
        Returns the item text label.

        :param `column`: if not ``None``, an integer specifying the column index.
         If it is ``None``, the main column index is used.
        """

        column = (column is not None and [column] or [self._owner.GetMainColumn()])[0]

        if len(self._text) > 0:
            if self._owner.IsVirtual():
                return self._owner.GetItemText(self._data, column)
            else:
                return self._text[column]

        return ""

[docs]    def GetImage(self, which=wx.TreeItemIcon_Normal, column=None):
        """
        Returns the item image for a particular item state.

        :param `which`: can be one of the following bits:

         ================================= ========================
         Item State                        Description
         ================================= ========================
         ``TreeItemIcon_Normal``           To get the normal item image
         ``TreeItemIcon_Selected``         To get the selected item image (i.e. the image which is shown when the item is currently selected)
         ``TreeItemIcon_Expanded``         To get the expanded image (this only makes sense for items which have children - then this image is shown when the item is expanded and the normal image is shown when it is collapsed)
         ``TreeItemIcon_SelectedExpanded`` To get the selected expanded image (which is shown when an expanded item is currently selected)
         ================================= ========================

        :param `column`: if not ``None``, an integer specifying the column index.
         If it is ``None``, the main column index is used.
        """

        column = (column is not None and [column] or [self._owner.GetMainColumn()])[0]

        if column == self._owner.GetMainColumn():
            return self._images[which]

        if column < len(self._col_images):
            return self._col_images[column]

        return _NO_IMAGE

[docs]    def GetCurrentImage(self, column=None):
        """
        Returns the current item image.

        :param `column`: if not ``None``, an integer specifying the column index.
         If it is ``None``, the main column index is used.
        """

        column = (column is not None and [column] or [self._owner.GetMainColumn()])[0]

        if column != self._owner.GetMainColumn():
            return self.GetImage(column=column)

        image = GenericTreeItem.GetCurrentImage(self)
        return image

[docs]    def SetText(self, column, text):
        """
        Sets the item text label.

        :param `column`: if not ``None``, an integer specifying the column index.
         If it is ``None``, the main column index is used;
        :param `text`: a string specifying the new item label.
        """

        column = (column is not None and [column] or [self._owner.GetMainColumn()])[0]

        if column < len(self._text):
            self._text[column] = text
        elif column < self._owner.GetColumnCount():
            self._text.extend([""] * (column - len(self._text) + 1))
            self._text[column] = text

[docs]    def SetImage(self, column, image, which):
        """
        Sets the item image for a particular item state.

        :param `column`: if not ``None``, an integer specifying the column index.
         If it is ``None``, the main column index is used;
        :param `image`: an index within the normal image list specifying the image to use;
        :param `which`: the item state.

        :see: L{GetImage} for a list of valid item states.
        """

        column = (column is not None and [column] or [self._owner.GetMainColumn()])[0]

        if column == self._owner.GetMainColumn():
            self._images[which] = image
        elif column < len(self._col_images):
            self._col_images[column] = image
        elif column < self._owner.GetColumnCount():
            self._col_images.extend([_NO_IMAGE] * (column - len(self._col_images) + 1))
            self._col_images[column] = image

[docs]    def GetTextX(self):
        """ Returns the `x` position of the item text. """

        return self._text_x

[docs]    def SetTextX(self, text_x):
        """
        Sets the `x` position of the item text.

        :param `text_x`: the `x` position of the item text.
        """

        self._text_x = text_x

[docs]    def SetWindow(self, wnd, column=None):
        """
        Sets the window associated to the item.

        :param `wnd`: a non-toplevel window to be displayed next to the item;
        :param `column`: if not ``None``, an integer specifying the column index.
         If it is ``None``, the main column index is used.
        """

        column = (column is not None and [column] or [self._owner.GetMainColumn()])[0]

        if type(self._wnd) != type([]):
            self._wnd = [self._wnd]

        if column < len(self._wnd):
            self._wnd[column] = wnd
        elif column < self._owner.GetColumnCount():
            self._wnd.extend([None] * (column - len(self._wnd) + 1))
            self._wnd[column] = wnd

        if self not in self._owner._itemWithWindow:
            self._owner._itemWithWindow.append(self)

        # We have to bind the wx.EVT_SET_FOCUS for the associated window
        # No other solution to handle the focus changing from an item in
        # HyperTreeList and the window associated to an item
        # Do better strategies exist?
        wnd.Bind(wx.EVT_SET_FOCUS, self.OnSetFocus)

        # We don't show the window if the item is collapsed
        if self._isCollapsed:
            wnd.Show(False)

        # The window is enabled only if the item is enabled
        wnd.Enable(self._enabled)

[docs]    def OnSetFocus(self, event):
        """
        Handles the ``wx.EVT_SET_FOCUS`` event for a window associated to an item.

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

        treectrl = self._owner
        select = treectrl.GetSelection()

        # If the window is associated to an item that currently is selected
        # (has focus) we don't kill the focus. Otherwise we do it.
        if select != self:
            treectrl._hasFocus = False
        else:
            treectrl._hasFocus = True

        event.Skip()

[docs]    def GetWindow(self, column=None):
        """
        Returns the window associated to the item.

        :param `column`: if not ``None``, an integer specifying the column index.
         If it is ``None``, the main column index is used.
        """

        column = (column is not None and [column] or [self._owner.GetMainColumn()])[0]

        if column >= len(self._wnd):
            return None

        return self._wnd[column]

[docs]    def DeleteWindow(self, column=None):
        """
        Deletes the window associated to the item (if any).

        :param `column`: if not ``None``, an integer specifying the column index.
         If it is ``None``, the main column index is used.
        """

        column = (column is not None and [column] or [self._owner.GetMainColumn()])[0]

        if column >= len(self._wnd):
            return

        if self._wnd[column]:
            self._wnd[column].Destroy()
            self._wnd[column] = None

[docs]    def GetWindowEnabled(self, column=None):
        """
        Returns whether the window associated with an item is enabled or not.

        :param `column`: if not ``None``, an integer specifying the column index.
         If it is ``None``, the main column index is used.
        """

        column = (column is not None and [column] or [self._owner.GetMainColumn()])[0]

        if not self._wnd[column]:
            raise Exception("\nERROR: This Item Has No Window Associated At Column %s"%column)

        return self._wnd[column].IsEnabled()

[docs]    def SetWindowEnabled(self, enable=True, column=None):
        """
        Sets whether the window associated with an item is enabled or not.

        :param `enable`: ``True`` to enable the associated window, ``False`` to disable it;
        :param `column`: if not ``None``, an integer specifying the column index.
         If it is ``None``, the main column index is used.
        """

        column = (column is not None and [column] or [self._owner.GetMainColumn()])[0]

        if not self._wnd[column]:
            raise Exception("\nERROR: This Item Has No Window Associated At Column %s"%column)

        self._wnd[column].Enable(enable)

[docs]    def GetWindowSize(self, column=None):
        """
        Returns the associated window size.

        :param `column`: if not ``None``, an integer specifying the column index.
         If it is ``None``, the main column index is used.
        """

        column = (column is not None and [column] or [self._owner.GetMainColumn()])[0]

        if not self._wnd[column]:
            raise Exception("\nERROR: This Item Has No Window Associated At Column %s"%column)

        return self._wnd[column].GetSize()

#-----------------------------------------------------------------------------
# EditTextCtrl (internal)
#-----------------------------------------------------------------------------

[docs]class EditCtrl(object):
    """
    Base class for controls used for in-place edit.
    """

[docs]    def __init__(self, parent, id=wx.ID_ANY, item=None, column=None, owner=None,
                 value="", pos=wx.DefaultPosition, size=wx.DefaultSize, style=0,
                 validator=wx.DefaultValidator, name="editctrl", **kwargs):
        """
        Default class constructor.

        :param `parent`: the window parent. Must not be ``None``;
        :param `id`: window identifier. A value of -1 indicates a default value;
        :param `item`: an instance of L{TreeListItem};
        :param `column`: if not ``None``, an integer specifying the column index.
         If it is ``None``, the main column index is used;
        :param `owner`: the window owner, in this case an instance of L{TreeListMainWindow};
        :param `value`: the initial value in the control;
        :param `pos`: the control position. A value of (-1, -1) indicates a default position,
         chosen by either the windowing system or wxPython, depending on platform;
        :param `size`: the control size. A value of (-1, -1) indicates a default size,
         chosen by either the windowing system or wxPython, depending on platform;
        :param `style`: the window style;
        :param `validator`: the window validator;
        :param `name`: the window name.
        """
        self._owner = owner
        self._startValue = value
        self._itemEdited = item
        self._finished = False

        column = (column is not None and [column] or [self._owner.GetMainColumn()])[0]

        self._column = column

        w = self._itemEdited.GetWidth()
        h = self._itemEdited.GetHeight()

        wnd = self._itemEdited.GetWindow(column)
        if wnd:
            w = w - self._itemEdited.GetWindowSize(column)[0]
            h = 0

        x = item.GetX()

        if column > 0:
            x = 0

        for i in xrange(column):
            if not self._owner.GetParent()._header_win.IsColumnShown(i):
                continue # do next column if not shown

            col = self._owner.GetParent()._header_win.GetColumn(i)
            wCol = col.GetWidth()
            x += wCol

        x, y = self._owner.CalcScrolledPosition(x+2, item.GetY())

        image_w = image_h = wcheck = hcheck = 0
        image = item.GetCurrentImage(column)

        if image != _NO_IMAGE:

            if self._owner._imageListNormal:
                image_w, image_h = self._owner._imageListNormal.GetSize(image)
                image_w += 2*_MARGIN

            else:

                raise Exception("\n ERROR: You Must Create An Image List To Use Images!")

        if column > 0:
            checkimage = item.GetCurrentCheckedImage()
            if checkimage is not None:
                wcheck, hcheck = self._owner._imageListCheck.GetSize(checkimage)
                wcheck += 2*_MARGIN

        if wnd:
            h = max(hcheck, image_h)
            dc = wx.ClientDC(self._owner)
            h = max(h, dc.GetTextExtent("Aq")[1])
            h = h + 2

        # FIXME: what are all these hardcoded 4, 8 and 11s really?
        x += image_w + wcheck
        w -= image_w + 2*_MARGIN + wcheck

        super(EditCtrl, self).__init__(parent, id, value, wx.Point(x,y),
                                       wx.Size(w+15, h),
                                       style=style|wx.SIMPLE_BORDER,
                                       name=name, **kwargs)

        if wx.Platform == "__WXMAC__":
            self.SetFont(owner.GetFont())
            bs = self.GetBestSize()
            self.SetSize((-1, bs.height))

        self.Bind(wx.EVT_KILL_FOCUS, self.OnKillFocus)

[docs]    def item(self):
        """Returns the item currently edited."""

        return self._itemEdited

[docs]    def column(self):
        """Returns the column currently edited."""

        return self._column

[docs]    def StopEditing(self):
        """Suddenly stops the editing."""

        self._owner.OnCancelEdit()
        self.Finish()

[docs]    def Finish(self):
        """Finish editing."""

        if not self._finished:

            self._finished = True
            self._owner.SetFocusIgnoringChildren()
            self._owner.ResetEditControl()

[docs]    def AcceptChanges(self):
        """Accepts/refuses the changes made by the user."""

        value = self.GetValue()

        if value == self._startValue:
            # nothing changed, always accept
            # when an item remains unchanged, the owner
            # needs to be notified that the user decided
            # not to change the tree item label, and that
            # the edit has been cancelled
            self._owner.OnCancelEdit()
            return True
        else:
            return self._owner.OnAcceptEdit(value)

[docs]    def OnKillFocus(self, event):
        """
        Handles the ``wx.EVT_KILL_FOCUS`` event for L{EditCtrl}

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

        # We must let the native control handle focus, too, otherwise
        # it could have problems with the cursor (e.g., in wxGTK).
        event.Skip()

[docs]class EditTextCtrl(EditCtrl, wx.TextCtrl):
    """
    Text control used for in-place edit.
    """

[docs]    def __init__(self, parent, id=wx.ID_ANY, item=None, column=None, owner=None,
                 value="", pos=wx.DefaultPosition, size=wx.DefaultSize, style=0,
                 validator=wx.DefaultValidator, name="edittextctrl", **kwargs):
        """
        Default class constructor.
        For internal use: do not call it in your code!

        :param `parent`: the window parent. Must not be ``None``;
        :param `id`: window identifier. A value of -1 indicates a default value;
        :param `item`: an instance of L{TreeListItem};
        :param `column`: if not ``None``, an integer specifying the column index.
         If it is ``None``, the main column index is used;
        :param `owner`: the window owner, in this case an instance of L{TreeListMainWindow};
        :param `value`: the initial value in the text control;
        :param `pos`: the control position. A value of (-1, -1) indicates a default position,
         chosen by either the windowing system or wxPython, depending on platform;
        :param `size`: the control size. A value of (-1, -1) indicates a default size,
         chosen by either the windowing system or wxPython, depending on platform;
        :param `style`: the window style;
        :param `validator`: the window validator;
        :param `name`: the window name.
        """

        super(EditTextCtrl, self).__init__(parent, id, item, column, owner,
                                           value, pos, size, style, validator,
                                           name, **kwargs)
        self.SelectAll()

        self.Bind(wx.EVT_CHAR, self.OnChar)
        self.Bind(wx.EVT_KEY_UP, self.OnKeyUp)

[docs]    def OnChar(self, event):
        """
        Handles the ``wx.EVT_CHAR`` event for L{EditTextCtrl}.

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

        keycode = event.GetKeyCode()

        if keycode in [wx.WXK_RETURN, wx.WXK_NUMPAD_ENTER] and not event.ShiftDown():
            # Notify the owner about the changes
            self.AcceptChanges()
            # Even if vetoed, close the control (consistent with MSW)
            wx.CallAfter(self.Finish)

        elif keycode == wx.WXK_ESCAPE:
            self.StopEditing()

        else:
            event.Skip()

[docs]    def OnKeyUp(self, event):
        """
        Handles the ``wx.EVT_KEY_UP`` event for L{EditTextCtrl}.

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

        if not self._finished:

            # auto-grow the textctrl:
            parentSize = self._owner.GetSize()
            myPos = self.GetPosition()
            mySize = self.GetSize()

            sx, sy = self.GetTextExtent(self.GetValue() + "M")
            if myPos.x + sx > parentSize.x:
                sx = parentSize.x - myPos.x
            if mySize.x > sx:
                sx = mySize.x

            self.SetSize((sx, -1))

        event.Skip()

# ---------------------------------------------------------------------------
# TreeListMainWindow implementation
# ---------------------------------------------------------------------------

[docs]class TreeListMainWindow(CustomTreeCtrl):
    """
    This class represents the main window (and thus the main column) in L{HyperTreeList}.

    :note: This is a subclass of L{CustomTreeCtrl}.
    """

[docs]    def __init__(self, parent, id=wx.ID_ANY, pos=wx.DefaultPosition, size=wx.DefaultSize,
                 style=0, agwStyle=wx.TR_DEFAULT_STYLE, validator=wx.DefaultValidator,
                 name="wxtreelistmainwindow"):
        """
        Default class constructor.

        :param `parent`: parent window. Must not be ``None``;
        :param `id`: window identifier. A value of -1 indicates a default value;
        :param `pos`: the control position. A value of (-1, -1) indicates a default position,
         chosen by either the windowing system or wxPython, depending on platform;
        :param `size`: the control size. A value of (-1, -1) indicates a default size,
         chosen by either the windowing system or wxPython, depending on platform;
        :param `style`: the underlying `wx.PyScrolledWindow` style;
        :param `agwStyle`: the AGW-specific L{TreeListMainWindow} window style. This can be a
         combination of the following bits:

         ============================== =========== ==================================================
         Window Styles                  Hex Value   Description
         ============================== =========== ==================================================
         ``TR_NO_BUTTONS``                      0x0 For convenience to document that no buttons are to be drawn.
         ``TR_SINGLE``                          0x0 For convenience to document that only one item may be selected at a time. Selecting another item causes the current selection, if any, to be deselected. This is the default.
         ``TR_HAS_BUTTONS``                     0x1 Use this style to show + and - buttons to the left of parent items.
         ``TR_NO_LINES``                        0x4 Use this style to hide vertical level connectors.
         ``TR_LINES_AT_ROOT``                   0x8 Use this style to show lines between root nodes. Only applicable if ``TR_HIDE_ROOT`` is set and ``TR_NO_LINES`` is not set.
         ``TR_DEFAULT_STYLE``                   0x9 The set of flags that are closest to the defaults for the native control for a particular toolkit.
         ``TR_TWIST_BUTTONS``                  0x10 Use old Mac-twist style buttons.
         ``TR_MULTIPLE``                       0x20 Use this style to allow a range of items to be selected. If a second range is selected, the current range, if any, is deselected.
         ``TR_EXTENDED``                       0x40 Use this style to allow disjoint items to be selected. (Only partially implemented; may not work in all cases).
         ``TR_HAS_VARIABLE_ROW_HEIGHT``        0x80 Use this style to cause row heights to be just big enough to fit the content. If not set, all rows use the largest row height. The default is that this flag is unset.
         ``TR_EDIT_LABELS``                   0x200 Use this style if you wish the user to be able to edit labels in the tree control.
         ``TR_ROW_LINES``                     0x400 Use this style to draw a contrasting border between displayed rows.
         ``TR_HIDE_ROOT``                     0x800 Use this style to suppress the display of the root node, effectively causing the first-level nodes to appear as a series of root nodes.
         ``TR_FULL_ROW_HIGHLIGHT``           0x2000 Use this style to have the background colour and the selection highlight extend  over the entire horizontal row of the tree control window.
         ``TR_AUTO_CHECK_CHILD``             0x4000 Only meaningful foe checkbox-type items: when a parent item is checked/unchecked its children are checked/unchecked as well.
         ``TR_AUTO_TOGGLE_CHILD``            0x8000 Only meaningful foe checkbox-type items: when a parent item is checked/unchecked its children are toggled accordingly.
         ``TR_AUTO_CHECK_PARENT``           0x10000 Only meaningful foe checkbox-type items: when a child item is checked/unchecked its parent item is checked/unchecked as well.
         ``TR_ALIGN_WINDOWS``               0x20000 Flag used to align windows (in items with windows) at the same horizontal position.
         ``TR_NO_HEADER``                   0x40000 Use this style to hide the columns header.
         ``TR_ELLIPSIZE_LONG_ITEMS``        0x80000 Flag used to ellipsize long items when the horizontal space for L{CustomTreeCtrl} is low.
         ``TR_VIRTUAL``                    0x100000 L{HyperTreeList} will have virtual behaviour.
         ============================== =========== ==================================================

        :param `validator`: window validator;
        :param `name`: window name.
        """

        self._buffered = False

        CustomTreeCtrl.__init__(self, parent, id, pos, size, style, agwStyle, validator, name)

        self._shiftItem = None
        self._editItem = None
        self._selectItem = None

        self._curColumn = -1 # no current column
        self._owner = parent
        self._main_column = 0
        self._dragItem = None

        self._imgWidth = self._imgWidth2 = 0
        self._imgHeight = self._imgHeight2 = 0
        self._btnWidth = self._btnWidth2 = 0
        self._btnHeight = self._btnHeight2 = 0
        self._checkWidth = self._checkWidth2 = 0
        self._checkHeight = self._checkHeight2 = 0
        self._agwStyle = agwStyle
        self._current = None

        # TextCtrl initial settings for editable items
        self._editTimer = TreeListEditTimer(self)
        self._left_down_selection = False

        self._dragTimer = wx.Timer(self)
        self._findTimer = wx.Timer(self)

        self.Bind(wx.EVT_PAINT, self.OnPaint)
        self.Bind(wx.EVT_MOUSE_EVENTS, self.OnMouse)
        self.Bind(wx.EVT_SCROLLWIN, self.OnScroll)

        # Sets the focus to ourselves: this is useful if you have items
        # with associated widgets.
        self.SetFocus()
        self.SetBackgroundStyle(wx.BG_STYLE_CUSTOM)

[docs]    def SetBuffered(self, buffered):
        """
        Sets/unsets the double buffering for the main window.

        :param `buffered`: ``True`` to use double-buffering, ``False`` otherwise.

        :note: Currently we are using double-buffering only on Windows XP.
        """

        self._buffered = buffered
        if buffered:
            self.SetBackgroundStyle(wx.BG_STYLE_CUSTOM)
        else:
            self.SetBackgroundStyle(wx.BG_STYLE_SYSTEM)

[docs]    def IsVirtual(self):
        """ Returns ``True`` if L{TreeListMainWindow} has the ``TR_VIRTUAL`` flag set. """

        return self.HasAGWFlag(TR_VIRTUAL)

#-----------------------------------------------------------------------------
# functions to work with tree items
#-----------------------------------------------------------------------------

[docs]    def GetItemImage(self, item, column=None, which=wx.TreeItemIcon_Normal):
        """
        Returns the item image.

        :param `item`: an instance of L{TreeListItem};
        :param `column`: if not ``None``, an integer specifying the column index.
         If it is ``None``, the main column index is used;
        :param `which`: can be one of the following bits:

         ================================= ========================
         Item State                        Description
         ================================= ========================
         ``TreeItemIcon_Normal``           To get the normal item image
         ``TreeItemIcon_Selected``         To get the selected item image (i.e. the image which is shown when the item is currently selected)
         ``TreeItemIcon_Expanded``         To get the expanded image (this only makes sense for items which have children - then this image is shown when the item is expanded and the normal image is shown when it is collapsed)
         ``TreeItemIcon_SelectedExpanded`` To get the selected expanded image (which is shown when an expanded item is currently selected)
         ================================= ========================
        """

        column = (column is not None and [column] or [self._main_column])[0]

        if column < 0:
            return _NO_IMAGE

        return item.GetImage(which, column)

[docs]    def SetItemImage(self, item, image, column=None, which=wx.TreeItemIcon_Normal):
        """
        Sets the item image for a particular item state.

        :param `item`: an instance of L{TreeListItem};
        :param `image`: an index within the normal image list specifying the image to use;
        :param `column`: if not ``None``, an integer specifying the column index.
         If it is ``None``, the main column index is used;
        :param `which`: the item state.

        :see: L{GetItemImage} for a list of valid item states.
        """

        column = (column is not None and [column] or [self._main_column])[0]

        if column < 0:
            return

        item.SetImage(column, image, which)
        dc = wx.ClientDC(self)
        self.CalculateSize(item, dc)
        self.RefreshLine(item)

[docs]    def GetItemWindowEnabled(self, item, column=None):
        """
        Returns whether the window associated with an item is enabled or not.

        :param `item`: an instance of L{TreeListItem};
        :param `column`: if not ``None``, an integer specifying the column index.
         If it is ``None``, the main column index is used.
        """

        return item.GetWindowEnabled(column)

[docs]    def GetItemWindow(self, item, column=None):
        """
        Returns the window associated with an item.

        :param `item`: an instance of L{TreeListItem};
        :param `column`: if not ``None``, an integer specifying the column index.
         If it is ``None``, the main column index is used.
        """

        return item.GetWindow(column)

[docs]    def SetItemWindow(self, item, window, column=None):
        """
        Sets the window associated to an item.

        :param `item`: an instance of L{TreeListItem};
        :param `wnd`: a non-toplevel window to be displayed next to the item;
        :param `column`: if not ``None``, an integer specifying the column index.
         If it is ``None``, the main column index is used.

        :note: The window parent should not be the L{HyperTreeList} itself, but actually
         an instance of L{TreeListMainWindow}. The current solution here is to reparent
         the window to this class.
        """

        # Reparent the window to ourselves
        if window.GetParent() != self:
            window.Reparent(self)

        item.SetWindow(window, column)
        if window:
            self._hasWindows = True

[docs]    def SetItemWindowEnabled(self, item, enable=True, column=None):
        """
        Sets whether the window associated with an item is enabled or not.

        :param `item`: an instance of L{TreeListItem};
        :param `enable`: ``True`` to enable the associated window, ``False`` to disable it;
        :param `column`: if not ``None``, an integer specifying the column index.
         If it is ``None``, the main column index is used.
        """

        item.SetWindowEnabled(enable, column)

# ----------------------------------------------------------------------------
# navigation
# ----------------------------------------------------------------------------

[docs]    def IsItemVisible(self, item):
        """
        Returns whether the item is visible or not.

        :param `item`: an instance of L{TreeListItem};
        """

        # An item is only visible if it's not a descendant of a collapsed item
        parent = item.GetParent()

        while parent:

            if not parent.IsExpanded():
                return False

            parent = parent.GetParent()

        startX, startY = self.GetViewStart()
        clientSize = self.GetClientSize()

        rect = self.GetBoundingRect(item)

        if not rect:
            return False
        if rect.GetWidth() == 0 or rect.GetHeight() == 0:
            return False
        if rect.GetBottom() < 0 or rect.GetTop() > clientSize.y:
            return False
        if rect.GetRight() < 0 or rect.GetLeft() > clientSize.x:
            return False

        return True

[docs]    def GetPrevChild(self, item, cookie):
        """
        Returns the previous child of an item.

        :param `item`: an instance of L{TreeListItem};
        :param `cookie`: a parameter which is opaque for the application but is necessary
         for the library to make these functions reentrant (i.e. allow more than one
         enumeration on one and the same object simultaneously).

        :note: This method returns ``None`` if there are no further siblings.
        """

        children = item.GetChildren()

        if cookie >= 0:
            return children[cookie], cookie-1
        else:
            # there are no more of them
            return None, cookie

[docs]    def GetFirstExpandedItem(self):
        """ Returns the first item which is in the expanded state. """

        return self.GetNextExpanded(self.GetRootItem())

[docs]    def GetNextExpanded(self, item):
        """
        Returns the next expanded item after the input one.

        :param `item`: an instance of L{TreeListItem}.
        """

        return CustomTreeCtrl.GetNextExpanded(self, item)

[docs]    def GetPrevExpanded(self, item):
        """
        Returns the previous expanded item before the input one.

        :param `item`: an instance of L{TreeListItem}.
        """

        return CustomTreeCtrl.GetPrevExpanded(self, item)

[docs]    def GetFirstVisibleItem(self):
        """ Returns the first visible item. """

        return self.GetNextVisible(self.GetRootItem())

[docs]    def GetPrevVisible(self, item):
        """
        Returns the previous visible item before the input one.

        :param `item`: an instance of L{TreeListItem}.
        """

        i = self.GetPrev(item)
        while i:
            if self.IsItemVisible(i):
                return i
            i = self.GetPrev(i)

        return None

# ----------------------------------------------------------------------------
# operations
# ----------------------------------------------------------------------------

[docs]    def DoInsertItem(self, parent, previous, text, ct_type=0, wnd=None, image=-1, selImage=-1, data=None):
        """
        Actually inserts an item in the tree.

        :param `parentId`: an instance of L{TreeListItem} representing the
         item's parent;
        :param `previous`: the index at which we should insert the item;
        :param `text`: the item text label;
        :param `ct_type`: the item type (see L{CustomTreeCtrl.SetItemType} for a list of valid
         item types);
        :param `wnd`: if not ``None``, a non-toplevel window to show next to the item;
        :param `image`: an index within the normal image list specifying the image to
         use for the item in unselected state;
        :param `selImage`: an index within the normal image list specifying the image to
         use for the item in selected state; if `image` > -1 and `selImage` is -1, the
         same image is used for both selected and unselected items;
        :param `data`: associate the given Python object `data` with the item.
        """

        self._dirty = True # do this first so stuff below doesn't cause flicker
        arr = [""]*self.GetColumnCount()
        arr[self._main_column] = text

        if not parent:
            # should we give a warning here?
            return self.AddRoot(text, ct_type, wnd, image, selImage, data)

        self._dirty = True     # do this first so stuff below doesn't cause flicker

        item = TreeListItem(self, parent, arr, ct_type, wnd, image, selImage, data)

        if wnd is not None:
            self._hasWindows = True
            self._itemWithWindow.append(item)

        parent.Insert(item, previous)

        return item

[docs]    def AddRoot(self, text, ct_type=0, wnd=None, image=-1, selImage=-1, data=None):
        """
        Adds a root item to the L{TreeListMainWindow}.

        :param `text`: the item text label;
        :param `ct_type`: the item type (see L{CustomTreeCtrl.SetItemType} for a list of valid
         item types);
        :param `wnd`: if not ``None``, a non-toplevel window to show next to the item;
        :param `image`: an index within the normal image list specifying the image to
         use for the item in unselected state;
        :param `selImage`: an index within the normal image list specifying the image to
         use for the item in selected state; if `image` > -1 and `selImage` is -1, the
         same image is used for both selected and unselected items;
        :param `data`: associate the given Python object `data` with the item.

        :warning: only one root is allowed to exist in any given instance of L{TreeListMainWindow}.
        """

        if self._anchor:
            raise Exception("\nERROR: Tree Can Have Only One Root")

        if wnd is not None and not (self._agwStyle & wx.TR_HAS_VARIABLE_ROW_HEIGHT):
            raise Exception("\nERROR: In Order To Append/Insert Controls You Have To Use The Style TR_HAS_VARIABLE_ROW_HEIGHT")

        if text.find("\n") >= 0 and not (self._agwStyle & wx.TR_HAS_VARIABLE_ROW_HEIGHT):
            raise Exception("\nERROR: In Order To Append/Insert A MultiLine Text You Have To Use The Style TR_HAS_VARIABLE_ROW_HEIGHT")

        if ct_type < 0 or ct_type > 2:
            raise Exception("\nERROR: Item Type Should Be 0 (Normal), 1 (CheckBox) or 2 (RadioButton). ")

        self._dirty = True     # do this first so stuff below doesn't cause flicker
        arr = [""]*self.GetColumnCount()
        arr[self._main_column] = text
        self._anchor = TreeListItem(self, None, arr, ct_type, wnd, image, selImage, data)

        if wnd is not None:
            self._hasWindows = True
            self._itemWithWindow.append(self._anchor)

        if self.HasAGWFlag(wx.TR_HIDE_ROOT):
            # if root is hidden, make sure we can navigate
            # into children
            self._anchor.SetHasPlus()
            self._anchor.Expand()
            self.CalculatePositions()

        if not self.HasAGWFlag(wx.TR_MULTIPLE):
            self._current = self._key_current = self._selectItem = self._anchor
            self._current.SetHilight(True)

        return self._anchor

[docs]    def Delete(self, item):
        """
        Deletes an item.

        :param `item`: an instance of L{TreeListItem}.
        """

        if not item:
            raise Exception("\nERROR: Invalid Tree Item. ")

        self._dirty = True     # do this first so stuff below doesn't cause flicker

        if self._editCtrl != None and self.IsDescendantOf(item, self._editCtrl.item()):
            # can't delete the item being edited, cancel editing it first
            self._editCtrl.StopEditing()

        # don't stay with invalid self._shiftItem or we will crash in the next call to OnChar()
        changeKeyCurrent = False
        itemKey = self._shiftItem

        while itemKey:
            if itemKey == item:  # self._shiftItem is a descendant of the item being deleted
                changeKeyCurrent = True
                break

            itemKey = itemKey.GetParent()

        parent = item.GetParent()
        if parent:
            parent.GetChildren().remove(item)  # remove by value

        if changeKeyCurrent:
            self._shiftItem = parent

        self.SendDeleteEvent(item)
        if self._selectItem == item:
            self._selectItem = None

        # Remove the item with window
        if item in self._itemWithWindow:
            for wnd in item._wnd:
                if wnd:
                    wnd.Hide()
                    wnd.Destroy()

            item._wnd = []
            self._itemWithWindow.remove(item)

        item.DeleteChildren(self)
        del item

    # Don't leave edit or selection on a child which is about to disappear

[docs]    def ChildrenClosing(self, item):
        """
        We are about to destroy the item's children.

        :param `item`: an instance of L{TreeListItem}.
        """

        if self._editCtrl != None and item != self._editCtrl.item() and self.IsDescendantOf(item, self._editCtrl.item()):
            self._editCtrl.StopEditing()

        if self.IsDescendantOf(item, self._selectItem):
            self._selectItem = item

        if item != self._current and self.IsDescendantOf(item, self._current):
            self._current.SetHilight(False)
            self._current = None

[docs]    def DeleteRoot(self):
        """
        Removes the tree root item (and subsequently all the items in
        L{TreeListMainWindow}.
        """

        if self._anchor:

            self._dirty = True
            self.SendDeleteEvent(self._anchor)
            self._current = None
            self._selectItem = None
            self._anchor.DeleteChildren(self)
            del self._anchor
            self._anchor = None

[docs]    def DeleteAllItems(self):
        """ Delete all items in the L{TreeListMainWindow}. """

        self.DeleteRoot()

[docs]    def HideWindows(self):
        """ Hides the windows associated to the items. Used internally. """

        for child in self._itemWithWindow:
            if not self.IsItemVisible(child):
                for column in xrange(self.GetColumnCount()):
                    wnd = child.GetWindow(column)
                    if wnd and wnd.IsShown():
                        wnd.Hide()

[docs]    def EnableItem(self, item, enable=True, torefresh=True):
        """
        Enables/disables an item.

        :param `item`: an instance of L{TreeListItem};
        :param `enable`: ``True`` to enable the item, ``False`` otherwise;
        :param `torefresh`: whether to redraw the item or not.
        """

        if item.IsEnabled() == enable:
            return

        if not enable and item.IsSelected():
            self.DoSelectItem(item, not self.HasAGWFlag(wx.TR_MULTIPLE))

        item.Enable(enable)

        for column in xrange(self.GetColumnCount()):
            wnd = item.GetWindow(column)

            # Handles the eventual window associated to the item
            if wnd:
                wnd.Enable(enable)

        if torefresh:
            # We have to refresh the item line
            dc = wx.ClientDC(self)
            self.CalculateSize(item, dc)
            self.RefreshLine(item)

[docs]    def IsItemEnabled(self, item):
        """
        Returns whether an item is enabled or disabled.

        :param `item`: an instance of L{TreeListItem}.
        """

        return item.IsEnabled()

[docs]    def GetCurrentItem(self):
        """ Returns the current item. """

        return self._current

[docs]    def GetColumnCount(self):
        """ Returns the total number of columns. """

        return self._owner.GetHeaderWindow().GetColumnCount()

[docs]    def SetMainColumn(self, column):
        """
        Sets the L{HyperTreeList} main column (i.e. the position of the underlying
        L{CustomTreeCtrl}.

        :param `column`: if not ``None``, an integer specifying the column index.
         If it is ``None``, the main column index is used.
        """

        if column >= 0 and column < self.GetColumnCount():
            self._main_column = column

[docs]    def GetMainColumn(self):
        """
        Returns the L{HyperTreeList} main column (i.e. the position of the underlying
        L{CustomTreeCtrl}.
        """

        return self._main_column

[docs]    def ScrollTo(self, item):
        """
        Scrolls the specified item into view.

        :param `item`: an instance of L{TreeListItem}.
        """

        # ensure that the position of the item it calculated in any case
        if self._dirty:
            self.CalculatePositions()

        # now scroll to the item
        xUnit, yUnit = self.GetScrollPixelsPerUnit()
        start_x, start_y = self.GetViewStart()
        start_y *= yUnit
        client_w, client_h = self.GetClientSize ()

        x, y = self._anchor.GetSize (0, 0, self)
        x = self._owner.GetHeaderWindow().GetWidth()
        y += yUnit + 2 # one more scrollbar unit + 2 pixels
        x_pos = self.GetScrollPos(wx.HORIZONTAL)

        if item._y < start_y+3:
            # going down, item should appear at top
            self.SetScrollbars(xUnit, yUnit, (xUnit and [x/xUnit] or [0])[0], (yUnit and [y/yUnit] or [0])[0],
                               x_pos, (yUnit and [item._y/yUnit] or [0])[0])

        elif item._y+self.GetLineHeight(item) > start_y+client_h:
            # going up, item should appear at bottom
            item._y += yUnit + 2
            self.SetScrollbars(xUnit, yUnit, (xUnit and [x/xUnit] or [0])[0], (yUnit and [y/yUnit] or [0])[0],
                               x_pos, (yUnit and [(item._y+self.GetLineHeight(item)-client_h)/yUnit] or [0])[0])

[docs]    def SetDragItem(self, item):
        """
        Sets the specified item as member of a current drag and drop operation.

        :param `item`: an instance of L{TreeListItem}.
        """

        prevItem = self._dragItem
        self._dragItem = item
        if prevItem:
            self.RefreshLine(prevItem)
        if self._dragItem:
            self.RefreshLine(self._dragItem)

# ----------------------------------------------------------------------------
# helpers
# ----------------------------------------------------------------------------

[docs]    def AdjustMyScrollbars(self):
        """ Internal method used to adjust the `wx.PyScrolledWindow` scrollbars. """

        if self._anchor:
            xUnit, yUnit = self.GetScrollPixelsPerUnit()
            if xUnit == 0:
                xUnit = self.GetCharWidth()
            if yUnit == 0:
                yUnit = self._lineHeight

            x, y = self._anchor.GetSize(0, 0, self)
            y += yUnit + 2 # one more scrollbar unit + 2 pixels
            x_pos = self.GetScrollPos(wx.HORIZONTAL)
            y_pos = self.GetScrollPos(wx.VERTICAL)
            x = self._owner.GetHeaderWindow().GetWidth() + 2
            if x < self.GetClientSize().GetWidth():
                x_pos = 0

            self.SetScrollbars(xUnit, yUnit, x/xUnit, y/yUnit, x_pos, y_pos)
        else:
            self.SetScrollbars(0, 0, 0, 0)

[docs]    def PaintItem(self, item, dc):
        """
        Actually draws an item.

        :param `item`: an instance of L{TreeListItem};
        :param `dc`: an instance of `wx.DC`.
        """

        def _paintText(text, textrect, alignment):
            """
            Sub-function to draw multi-lines text label aligned correctly.

            :param `text`: the item text label (possibly multiline);
            :param `textrect`: the label client rectangle;
            :param `alignment`: the alignment for the text label, one of ``wx.ALIGN_LEFT``,
             ``wx.ALIGN_RIGHT``, ``wx.ALIGN_CENTER``.
            """

            txt = text.splitlines()
            if alignment != wx.ALIGN_LEFT and len(txt):
                yorigin = textrect.Y
                for t in txt:
                    w, h = dc.GetTextExtent(t)
                    plus = textrect.Width - w
                    if alignment == wx.ALIGN_CENTER:
                        plus /= 2
                    dc.DrawLabel(t, wx.Rect(textrect.X + plus, yorigin, w, yorigin+h))
                    yorigin += h
                return
            dc.DrawLabel(text, textrect)

        attr = item.GetAttributes()

        if attr and attr.HasFont():
            dc.SetFont(attr.GetFont())
        elif item.IsBold():
            dc.SetFont(self._boldFont)
        if item.IsHyperText():
            dc.SetFont(self.GetHyperTextFont())
            if item.GetVisited():
                dc.SetTextForeground(self.GetHyperTextVisitedColour())
            else:
                dc.SetTextForeground(self.GetHyperTextNewColour())

        colText = wx.Colour(*dc.GetTextForeground())

        if item.IsSelected():
            if (wx.Platform == "__WXMAC__" and self._hasFocus):
                colTextHilight = wx.SystemSettings_GetColour(wx.SYS_COLOUR_HIGHLIGHTTEXT)
            else:
                colTextHilight = wx.SystemSettings_GetColour(wx.SYS_COLOUR_HIGHLIGHTTEXT)

        else:
            attr = item.GetAttributes()
            if attr and attr.HasTextColour():
                colText = attr.GetTextColour()

        if self._vistaselection:
            colText = colTextHilight = wx.BLACK

        total_w = self._owner.GetHeaderWindow().GetWidth()
        total_h = self.GetLineHeight(item)
        off_h = (self.HasAGWFlag(wx.TR_ROW_LINES) and [1] or [0])[0]
        off_w = (self.HasAGWFlag(wx.TR_COLUMN_LINES) and [1] or [0])[0]
##        clipper = wx.DCClipper(dc, 0, item.GetY(), total_w, total_h) # only within line

        text_w, text_h, dummy = dc.GetMultiLineTextExtent(item.GetText(self.GetMainColumn()))

        drawItemBackground = False
        # determine background and show it
        if attr and attr.HasBackgroundColour():
            colBg = attr.GetBackgroundColour()
            drawItemBackground = True
        else:
            colBg = self._backgroundColour

        dc.SetBrush(wx.Brush(colBg, wx.SOLID))
        dc.SetPen(wx.TRANSPARENT_PEN)

        if self.HasAGWFlag(wx.TR_FULL_ROW_HIGHLIGHT):

            itemrect = wx.Rect(0, item.GetY() + off_h, total_w-1, total_h - off_h)

            if item == self._dragItem:
                dc.SetBrush(self._hilightBrush)
                if wx.Platform == "__WXMAC__":
                    dc.SetPen((item == self._dragItem) and [wx.BLACK_PEN] or [wx.TRANSPARENT_PEN])[0]

                dc.SetTextForeground(colTextHilight)

            elif item.IsSelected():

                wnd = item.GetWindow(self._main_column)
                wndx = 0
                if wnd:
                    wndx, wndy = item.GetWindowSize(self._main_column)

                itemrect = wx.Rect(0, item.GetY() + off_h, total_w-1, total_h - off_h)

                if self._usegradients:
                    if self._gradientstyle == 0:   # Horizontal
                        self.DrawHorizontalGradient(dc, itemrect, self._hasFocus)
                    else:                          # Vertical
                        self.DrawVerticalGradient(dc, itemrect, self._hasFocus)
                elif self._vistaselection:
                    self.DrawVistaRectangle(dc, itemrect, self._hasFocus)
                else:
                    if wx.Platform in ["__WXGTK2__", "__WXMAC__"]:
                        flags = wx.CONTROL_SELECTED
                        if self._hasFocus: flags = flags | wx.CONTROL_FOCUSED
                        wx.RendererNative.Get().DrawItemSelectionRect(self._owner, dc, itemrect, flags)
                    else:
                        dc.SetBrush((self._hasFocus and [self._hilightBrush] or [self._hilightUnfocusedBrush])[0])
                        dc.SetPen((self._hasFocus and [self._borderPen] or [wx.TRANSPARENT_PEN])[0])
                        dc.DrawRectangleRect(itemrect)

                dc.SetTextForeground(colTextHilight)

            # On GTK+ 2, drawing a 'normal' background is wrong for themes that
            # don't allow backgrounds to be customized. Not drawing the background,
            # except for custom item backgrounds, works for both kinds of theme.
            elif drawItemBackground:

                itemrect = wx.Rect(0, item.GetY() + off_h, total_w-1, total_h - off_h)
                dc.SetBrush(wx.Brush(colBg, wx.SOLID))
                dc.DrawRectangleRect(itemrect)
                dc.SetTextForeground(colText)

            else:
                dc.SetTextForeground(colText)

        else:

            dc.SetTextForeground(colText)

        text_extraH = (total_h > text_h and [(total_h - text_h)/2] or [0])[0]
        img_extraH = (total_h > self._imgHeight and [(total_h-self._imgHeight)/2] or [0])[0]
        x_colstart = 0

        for i in xrange(self.GetColumnCount()):
            if not self._owner.GetHeaderWindow().IsColumnShown(i):
                continue

            col_w = self._owner.GetHeaderWindow().GetColumnWidth(i)
            dc.SetClippingRegion(x_colstart, item.GetY(), col_w, total_h) # only within column

            image = _NO_IMAGE
            x = image_w = wcheck = hcheck = 0

            if i == self.GetMainColumn():
                x = item.GetX() + _MARGIN
                if self.HasButtons():
                    x += (self._btnWidth-self._btnWidth2) + _LINEATROOT
                else:
                    x -= self._indent/2

                if self._imageListNormal:
                    image = item.GetCurrentImage(i)

                if item.GetType() != 0 and self._imageListCheck:
                    checkimage = item.GetCurrentCheckedImage()
                    wcheck, hcheck = self._imageListCheck.GetSize(item.GetType())
                else:
                    wcheck, hcheck = 0, 0

            else:
                x = x_colstart + _MARGIN
                image = item.GetImage(column=i)

            if image != _NO_IMAGE:
                image_w = self._imgWidth + _MARGIN

            # honor text alignment
            text = item.GetText(i)
            alignment = self._owner.GetHeaderWindow().GetColumn(i).GetAlignment()

            text_w, dummy, dummy = dc.GetMultiLineTextExtent(text)

            if alignment == wx.ALIGN_RIGHT:
                w = col_w - (image_w + wcheck + text_w + off_w + _MARGIN + 1)
                x += (w > 0 and [w] or [0])[0]

            elif alignment == wx.ALIGN_CENTER:
                w = (col_w - (image_w + wcheck + text_w + off_w + _MARGIN))/2
                x += (w > 0 and [w] or [0])[0]
            else:
                if image_w == 0 and wcheck:
                    x += 2*_MARGIN

            text_x = x + image_w + wcheck + 1

            if i == self.GetMainColumn():
                item.SetTextX(text_x)

            if not self.HasAGWFlag(wx.TR_FULL_ROW_HIGHLIGHT):
                dc.SetBrush((self._hasFocus and [self._hilightBrush] or [self._hilightUnfocusedBrush])[0])
                dc.SetPen((self._hasFocus and [self._borderPen] or [wx.TRANSPARENT_PEN])[0])
                if i == self.GetMainColumn():
                    if item == self._dragItem:
                        if wx.Platform == "__WXMAC__":  # don't draw rect outline if we already have the background colour
                            dc.SetPen((item == self._dragItem and [wx.BLACK_PEN] or [wx.TRANSPARENT_PEN])[0])

                        dc.SetTextForeground(colTextHilight)

                    elif item.IsSelected():

                        itemrect = wx.Rect(text_x-2, item.GetY() + off_h, text_w+2*_MARGIN, total_h - off_h)

                        if self._usegradients:
                            if self._gradientstyle == 0:   # Horizontal
                                self.DrawHorizontalGradient(dc, itemrect, self._hasFocus)
                            else:                          # Vertical
                                self.DrawVerticalGradient(dc, itemrect, self._hasFocus)
                        elif self._vistaselection:
                            self.DrawVistaRectangle(dc, itemrect, self._hasFocus)
                        else:
                            if wx.Platform in ["__WXGTK2__", "__WXMAC__"]:
                                flags = wx.CONTROL_SELECTED
                                if self._hasFocus: flags = flags | wx.CONTROL_FOCUSED
                                wx.RendererNative.Get().DrawItemSelectionRect(self._owner, dc, itemrect, flags)
                            else:
                                dc.DrawRectangleRect(itemrect)

                        dc.SetTextForeground(colTextHilight)

                    elif item == self._current:
                        dc.SetPen((self._hasFocus and [wx.BLACK_PEN] or [wx.TRANSPARENT_PEN])[0])

                    # On GTK+ 2, drawing a 'normal' background is wrong for themes that
                    # don't allow backgrounds to be customized. Not drawing the background,
                    # except for custom item backgrounds, works for both kinds of theme.
                    elif drawItemBackground:

                        itemrect = wx.Rect(text_x-2, item.GetY() + off_h, text_w+2*_MARGIN, total_h - off_h)
                        dc.SetBrush(wx.Brush(colBg, wx.SOLID))
                        dc.DrawRectangleRect(itemrect)

                    else:
                        dc.SetTextForeground(colText)

                else:
                    dc.SetTextForeground(colText)

            if self.HasAGWFlag(wx.TR_COLUMN_LINES):  # vertical lines between columns
                pen = wx.Pen(wx.SystemSettings_GetColour(wx.SYS_COLOUR_3DLIGHT), 1, wx.SOLID)
                dc.SetPen((self.GetBackgroundColour() == wx.WHITE and [pen] or [wx.WHITE_PEN])[0])
                dc.DrawLine(x_colstart+col_w-1, item.GetY(), x_colstart+col_w-1, item.GetY()+total_h)

            dc.SetBackgroundMode(wx.TRANSPARENT)

            if image != _NO_IMAGE:
                y = item.GetY() + img_extraH
                if wcheck:
                    x += wcheck

                if item.IsEnabled():
                    imglist = self._imageListNormal
                else:
                    imglist = self._grayedImageList

                imglist.Draw(image, dc, x, y, wx.IMAGELIST_DRAW_TRANSPARENT)

            if wcheck:
                if item.IsEnabled():
                    imglist = self._imageListCheck
                else:
                    imglist = self._grayedCheckList

                if self.HasButtons():  # should the item show a button?
                    btnWidth = self._btnWidth
                else:
                    btnWidth = -self._btnWidth

                imglist.Draw(checkimage, dc,
                             item.GetX() + btnWidth + _MARGIN,
                             item.GetY() + ((total_h > hcheck) and [(total_h-hcheck)/2] or [0])[0]+1,
                             wx.IMAGELIST_DRAW_TRANSPARENT)

            text_w, text_h, dummy = dc.GetMultiLineTextExtent(text)
            text_extraH = (total_h > text_h and [(total_h - text_h)/2] or [0])[0]
            text_y = item.GetY() + text_extraH
            textrect = wx.Rect(text_x, text_y, text_w, text_h)

            if self.HasAGWFlag(TR_ELLIPSIZE_LONG_ITEMS):
                if i == self.GetMainColumn():
                    maxsize = col_w - text_x - _MARGIN
                else:
                    maxsize = col_w - (wcheck + image_w + _MARGIN)

                text = ChopText(dc, text, maxsize)

            if not item.IsEnabled():
                foreground = dc.GetTextForeground()
                dc.SetTextForeground(self._disabledColour)
                _paintText(text, textrect, alignment)
                dc.SetTextForeground(foreground)
            else:
                if wx.Platform == "__WXMAC__" and item.IsSelected() and self._hasFocus:
                    dc.SetTextForeground(wx.WHITE)
                _paintText(text, textrect, alignment)

            wnd = item.GetWindow(i)
            if wnd:
                if text_w == 0:
                    wndx = text_x
                else:
                    wndx = text_x + text_w + 2*_MARGIN
                xa, ya = self.CalcScrolledPosition((0, item.GetY()))
                wndx += xa
                if item.GetHeight() > item.GetWindowSize(i)[1]:
                    ya += (item.GetHeight() - item.GetWindowSize(i)[1])/2

                if not wnd.IsShown():
                    wnd.Show()
                if wnd.GetPosition() != (wndx, ya):
                    wnd.SetPosition((wndx, ya))

            x_colstart += col_w
            dc.DestroyClippingRegion()

        # restore normal font
        dc.SetFont(self._normalFont)

    # Now y stands for the top of the item, whereas it used to stand for middle !

[docs]    def PaintLevel(self, item, dc, level, y, x_maincol):
        """
        Paint a level in the hierarchy of L{TreeListMainWindow}.

        :param `item`: an instance of L{TreeListItem};
        :param `dc`: an instance of `wx.DC`;
        :param `level`: the item level in the tree hierarchy;
        :param `y`: the current vertical position in the `wx.PyScrolledWindow`;
        :param `x_maincol`: the horizontal position of the main column.
        """

        if item.IsHidden():
            return y, x_maincol

        # Handle hide root (only level 0)
        if self.HasAGWFlag(wx.TR_HIDE_ROOT) and level == 0:
            for child in item.GetChildren():
                y, x_maincol = self.PaintLevel(child, dc, 1, y, x_maincol)

            # end after expanding root
            return y, x_maincol

        # calculate position of vertical lines
        x = x_maincol + _MARGIN # start of column

        if self.HasAGWFlag(wx.TR_LINES_AT_ROOT):
            x += _LINEATROOT # space for lines at root

        if self.HasButtons():
            x += (self._btnWidth-self._btnWidth2) # half button space
        else:
            x += (self._indent-self._indent/2)

        if self.HasAGWFlag(wx.TR_HIDE_ROOT):
            x += self._indent*(level-1) # indent but not level 1
        else:
            x += self._indent*level # indent according to level

        # set position of vertical line
        item.SetX(x)
        item.SetY(y)

        h = self.GetLineHeight(item)
        y_top = y
        y_mid = y_top + (h/2)
        y += h

        exposed_x = dc.LogicalToDeviceX(0)
        exposed_y = dc.LogicalToDeviceY(y_top)

        # horizontal lines between rows?
        draw_row_lines = self.HasAGWFlag(wx.TR_ROW_LINES)

        if self.IsExposed(exposed_x, exposed_y, _MAX_WIDTH, h + draw_row_lines):
            if draw_row_lines:
                total_width = self._owner.GetHeaderWindow().GetWidth()
                # if the background colour is white, choose a
                # contrasting colour for the lines
                pen = wx.Pen(wx.SystemSettings_GetColour(wx.SYS_COLOUR_3DLIGHT), 1, wx.SOLID)
                dc.SetPen((self.GetBackgroundColour() == wx.WHITE and [pen] or [wx.WHITE_PEN])[0])
                dc.DrawLine(0, y_top, total_width, y_top)
                dc.DrawLine(0, y_top+h, total_width, y_top+h)

            # draw item
            self.PaintItem(item, dc)

            # restore DC objects
            dc.SetBrush(wx.WHITE_BRUSH)
            dc.SetPen(self._dottedPen)

            # clip to the column width
            clip_width = self._owner.GetHeaderWindow().GetColumn(self._main_column).GetWidth()
##            clipper = wx.DCClipper(dc, x_maincol, y_top, clip_width, 10000)

            if not self.HasAGWFlag(wx.TR_NO_LINES):  # connection lines

                # draw the horizontal line here
                dc.SetPen(self._dottedPen)
                x2 = x - self._indent
                if x2 < (x_maincol + _MARGIN):
                    x2 = x_maincol + _MARGIN
                x3 = x + (self._btnWidth-self._btnWidth2)
                if self.HasButtons():
                    if item.HasPlus():
                        dc.DrawLine(x2, y_mid, x - self._btnWidth2, y_mid)
                        dc.DrawLine(x3, y_mid, x3 + _LINEATROOT, y_mid)
                    else:
                        dc.DrawLine(x2, y_mid, x3 + _LINEATROOT, y_mid)
                else:
                    dc.DrawLine(x2, y_mid, x - self._indent/2, y_mid)

            if item.HasPlus() and self.HasButtons():  # should the item show a button?

                if self._imageListButtons:

                    # draw the image button here
                    image = wx.TreeItemIcon_Normal
                    if item.IsExpanded():
                        image = wx.TreeItemIcon_Expanded
                    if item.IsSelected():
                        image += wx.TreeItemIcon_Selected - wx.TreeItemIcon_Normal
                    xx = x - self._btnWidth2 + _MARGIN
                    yy = y_mid - self._btnHeight2
                    dc.SetClippingRegion(xx, yy, self._btnWidth, self._btnHeight)
                    self._imageListButtons.Draw(image, dc, xx, yy, wx.IMAGELIST_DRAW_TRANSPARENT)
                    dc.DestroyClippingRegion()

                elif self.HasAGWFlag(wx.TR_TWIST_BUTTONS):

                    # draw the twisty button here
                    dc.SetPen(wx.BLACK_PEN)
                    dc.SetBrush(self._hilightBrush)
                    button = [wx.Point() for j in xrange(3)]
                    if item.IsExpanded():
                        button[0].x = x - (self._btnWidth2+1)
                        button[0].y = y_mid - (self._btnHeight/3)
                        button[1].x = x + (self._btnWidth2+1)
                        button[1].y = button[0].y
                        button[2].x = x
                        button[2].y = button[0].y + (self._btnHeight2+1)
                    else:
                        button[0].x = x - (self._btnWidth/3)
                        button[0].y = y_mid - (self._btnHeight2+1)
                        button[1].x = button[0].x
                        button[1].y = y_mid + (self._btnHeight2+1)
                        button[2].x = button[0].x + (self._btnWidth2+1)
                        button[2].y = y_mid

                    dc.SetClippingRegion(x_maincol + _MARGIN, y_top, clip_width, h)
                    dc.DrawPolygon(button)
                    dc.DestroyClippingRegion()

                else: # if (HasAGWFlag(wxTR_HAS_BUTTONS))

                    rect = wx.Rect(x-self._btnWidth2, y_mid-self._btnHeight2, self._btnWidth, self._btnHeight)
                    flag = (item.IsExpanded() and [wx.CONTROL_EXPANDED] or [0])[0]
                    wx.RendererNative.GetDefault().DrawTreeItemButton(self, dc, rect, flag)

        # restore DC objects
        dc.SetBrush(wx.WHITE_BRUSH)
        dc.SetPen(self._dottedPen)
        dc.SetTextForeground(wx.BLACK)

        if item.IsExpanded():

            # process lower levels
            if self._imgWidth > 0:
                oldY = y_mid + self._imgHeight2
            else:
                oldY = y_mid + h/2

            for child in item.GetChildren():

                y, x_maincol = self.PaintLevel(child, dc, level+1, y, x_maincol)

                # draw vertical line
                if not self.HasAGWFlag(wx.TR_NO_LINES):
                    Y1 = child.GetY() + child.GetHeight()/2
                    dc.DrawLine(x, oldY, x, Y1)

        return y, x_maincol

# ----------------------------------------------------------------------------
# wxWindows callbacks
# ----------------------------------------------------------------------------

[docs]    def OnEraseBackground(self, event):
        """
        Handles the ``wx.EVT_ERASE_BACKGROUND`` event for L{TreeListMainWindow}.

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

        # do not paint the background separately in buffered mode.
        if not self._buffered:
            CustomTreeCtrl.OnEraseBackground(self, event)

[docs]    def OnPaint(self, event):
        """
        Handles the ``wx.EVT_PAINT`` event for L{TreeListMainWindow}.

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

        if self._buffered:

            # paint the background
            dc = wx.BufferedPaintDC(self)
            rect = self.GetUpdateRegion().GetBox()
            dc.SetClippingRect(rect)
            dc.SetBackground(wx.Brush(self.GetBackgroundColour()))
            if self._backgroundImage:
                self.TileBackground(dc)
            else:
                dc.Clear()

        else:
            dc = wx.PaintDC(self)

        self.PrepareDC(dc)

        if not self._anchor or self.GetColumnCount() <= 0:
            return

        # calculate button size
        if self._imageListButtons:
            self._btnWidth, self._btnHeight = self._imageListButtons.GetSize(0)
        elif self.HasButtons():
            self._btnWidth = _BTNWIDTH
            self._btnHeight = _BTNHEIGHT

        self._btnWidth2 = self._btnWidth/2
        self._btnHeight2 = self._btnHeight/2

        # calculate image size
        if self._imageListNormal:
            self._imgWidth, self._imgHeight = self._imageListNormal.GetSize(0)

        self._imgWidth2 = self._imgWidth/2
        self._imgHeight2 = self._imgHeight/2

        if self._imageListCheck:
            self._checkWidth, self._checkHeight = self._imageListCheck.GetSize(0)

        self._checkWidth2 = self._checkWidth/2
        self._checkHeight2 = self._checkHeight/2

        # calculate indent size
        if self._imageListButtons:
            self._indent = max(_MININDENT, self._btnWidth + _MARGIN)
        elif self.HasButtons():
            self._indent = max(_MININDENT, self._btnWidth + _LINEATROOT)

        # set default values
        dc.SetFont(self._normalFont)
        dc.SetPen(self._dottedPen)

        # calculate column start and paint
        x_maincol = 0
        for i in xrange(self.GetMainColumn()):
            if not self._owner.GetHeaderWindow().IsColumnShown(i):
                continue
            x_maincol += self._owner.GetHeaderWindow().GetColumnWidth(i)

        y, x_maincol = self.PaintLevel(self._anchor, dc, 0, 0, x_maincol)

[docs]    def HitTest(self, point, flags=0):
        """
        Calculates which (if any) item is under the given point, returning the tree item
        at this point plus extra information flags plus the item's column.

        :param `point`: an instance of `wx.Point`, a point to test for hits;
        :param `flags`: a bitlist of the following values:

         ================================== =============== =================================
         HitTest Flags                      Hex Value       Description
         ================================== =============== =================================
         ``TREE_HITTEST_ABOVE``                         0x1 Above the client area
         ``TREE_HITTEST_BELOW``                         0x2 Below the client area
         ``TREE_HITTEST_NOWHERE``                       0x4 No item has been hit
         ``TREE_HITTEST_ONITEMBUTTON``                  0x8 On the button associated to an item
         ``TREE_HITTEST_ONITEMICON``                   0x10 On the icon associated to an item
         ``TREE_HITTEST_ONITEMINDENT``                 0x20 On the indent associated to an item
         ``TREE_HITTEST_ONITEMLABEL``                  0x40 On the label (string) associated to an item
         ``TREE_HITTEST_ONITEM``                       0x50 Anywhere on the item
         ``TREE_HITTEST_ONITEMRIGHT``                  0x80 On the right of the label associated to an item
         ``TREE_HITTEST_TOLEFT``                      0x200 On the left of the client area
         ``TREE_HITTEST_TORIGHT``                     0x400 On the right of the client area
         ``TREE_HITTEST_ONITEMUPPERPART``             0x800 On the upper part (first half) of the item
         ``TREE_HITTEST_ONITEMLOWERPART``            0x1000 On the lower part (second half) of the item
         ``TREE_HITTEST_ONITEMCHECKICON``            0x2000 On the check/radio icon, if present
         ================================== =============== =================================

        :return: the item (if any, ``None`` otherwise), the `flags` and the column are always
         returned as a tuple.
        """

        w, h = self.GetSize()
        column = -1

        if not isinstance(point, wx.Point):
            point = wx.Point(*point)

        if point.x < 0:
            flags |= wx.TREE_HITTEST_TOLEFT
        if point.x > w:
            flags |= wx.TREE_HITTEST_TORIGHT
        if point.y < 0:
            flags |= wx.TREE_HITTEST_ABOVE
        if point.y > h:
            flags |= wx.TREE_HITTEST_BELOW
        if flags:
            return None, flags, column

        if not self._anchor:
            flags = wx.TREE_HITTEST_NOWHERE
            column = -1
            return None, flags, column

        hit, flags, column = self._anchor.HitTest(self.CalcUnscrolledPosition(point), self, flags, column, 0)
        if not hit:
            flags = wx.TREE_HITTEST_NOWHERE
            column = -1
            return None, flags, column

        return hit, flags, column

[docs]    def EditLabel(self, item, column=None):
        """
        Starts editing an item label.

        :param `item`: an instance of L{TreeListItem};
        :param `column`: if not ``None``, an integer specifying the column index.
         If it is ``None``, the main column index is used.
        """

        if not item:
            return

        column = (column is not None and [column] or [self._main_column])[0]

        if column < 0 or column >= self.GetColumnCount():
            return

        self._curColumn = column
        self._editItem = item

        te = TreeEvent(wx.wxEVT_COMMAND_TREE_BEGIN_LABEL_EDIT, self._owner.GetId())
        te.SetItem(self._editItem)
        te.SetInt(column)
        te.SetEventObject(self._owner)
        self._owner.GetEventHandler().ProcessEvent(te)

        if not te.IsAllowed():
            return

        # ensure that the position of the item it calculated in any case
        if self._dirty:
            self.CalculatePositions()

        if self._editCtrl != None and (item != self._editCtrl.item() or column != self._editCtrl.column()):
            self._editCtrl.StopEditing()

        self._editCtrl = self._owner.CreateEditCtrl(item, column)
        self._editCtrl.SetFocus()

[docs]    def OnEditTimer(self):
        """ The timer for editing has expired. Start editing. """

        self.EditLabel(self._current, self._curColumn)

[docs]    def OnAcceptEdit(self, value):
        """
        Called by L{EditTextCtrl}, to accept the changes and to send the
        ``EVT_TREE_END_LABEL_EDIT`` event.

        :param `value`: the new value of the item label.
        """

        # TODO if the validator fails this causes a crash
        le = TreeEvent(wx.wxEVT_COMMAND_TREE_END_LABEL_EDIT, self._owner.GetId())
        le.SetItem(self._editItem)
        le.SetEventObject(self._owner)
        le.SetLabel(value)
        le.SetInt(self._curColumn if self._curColumn >= 0 else 0)
        le._editCancelled = False
        self._owner.GetEventHandler().ProcessEvent(le)

        if not le.IsAllowed():
            return

        if self._curColumn == -1:
            self._curColumn = 0

        self.SetItemText(self._editItem, unicode(value), self._curColumn)

[docs]    def OnCancelEdit(self):
        """
        Called by L{EditCtrl}, to cancel the changes and to send the
        ``EVT_TREE_END_LABEL_EDIT`` event.
        """

        # let owner know that the edit was cancelled
        le = TreeEvent(wx.wxEVT_COMMAND_TREE_END_LABEL_EDIT, self._owner.GetId())
        le.SetItem(self._editItem)
        le.SetEventObject(self._owner)
        le.SetLabel("")
        le._editCancelled = True

        self._owner.GetEventHandler().ProcessEvent(le)

[docs]    def OnMouse(self, event):
        """
        Handles the ``wx.EVT_MOUSE_EVENTS`` event for L{TreeListMainWindow}.

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

        if not self._anchor:
            return

        # we process left mouse up event (enables in-place edit), right down
        # (pass to the user code), left dbl click (activate item) and
        # dragging/moving events for items drag-and-drop
        if not (event.LeftDown() or event.LeftUp() or event.RightDown() or \
                event.RightUp() or event.LeftDClick() or event.Dragging() or \
                event.GetWheelRotation() != 0 or event.Moving()):
            self._owner.GetEventHandler().ProcessEvent(event)
            return

        # set focus if window clicked
        if event.LeftDown() or event.RightDown():
            self._hasFocus = True
            self.SetFocusIgnoringChildren()

        # determine event
        p = wx.Point(event.GetX(), event.GetY())
        flags = 0
        item, flags, column = self._anchor.HitTest(self.CalcUnscrolledPosition(p), self, flags, self._curColumn, 0)

        underMouse = item
        underMouseChanged = underMouse != self._underMouse

        if underMouse and (flags & wx.TREE_HITTEST_ONITEM) and not event.LeftIsDown() and \
           not self._isDragging and (not self._editTimer or not self._editTimer.IsRunning()):
            underMouse = underMouse
        else:
            underMouse = None

        if underMouse != self._underMouse:
            if self._underMouse:
                # unhighlight old item
                self._underMouse = None

            self._underMouse = underMouse

        # Determines what item we are hovering over and need a tooltip for
        hoverItem = item

        if (event.LeftDown() or event.LeftUp() or event.RightDown() or \
            event.RightUp() or event.LeftDClick() or event.Dragging()):
            if self._editCtrl != None and (item != self._editCtrl.item() or column != self._editCtrl.column()):
                self._editCtrl.StopEditing()

        # We do not want a tooltip if we are dragging, or if the edit timer is running
        if underMouseChanged and not self._isDragging and (not self._editTimer or not self._editTimer.IsRunning()):

            if hoverItem is not None:
                # Ask the tree control what tooltip (if any) should be shown
                hevent = TreeEvent(wx.wxEVT_COMMAND_TREE_ITEM_GETTOOLTIP, self.GetId())
                hevent.SetItem(hoverItem)
                hevent.SetEventObject(self)

                if self.GetEventHandler().ProcessEvent(hevent) and hevent.IsAllowed():
                    self.SetToolTip(hevent._label)

                if hoverItem.IsHyperText() and (flags & wx.TREE_HITTEST_ONITEMLABEL) and hoverItem.IsEnabled():
                    self.SetCursor(wx.StockCursor(wx.CURSOR_HAND))
                    self._isonhyperlink = True
                else:
                    if self._isonhyperlink:
                        self.SetCursor(wx.StockCursor(wx.CURSOR_ARROW))
                        self._isonhyperlink = False

        # we only process dragging here
        if event.Dragging():

            if self._isDragging:
                if not self._dragImage:
                    # Create the custom draw image from the icons and the text of the item
                    self._dragImage = DragImage(self, self._current or item)
                    self._dragImage.BeginDrag(wx.Point(0,0), self)
                    self._dragImage.Show()

                self._dragImage.Move(p)

                if self._countDrag == 0 and item:
                    self._oldItem = self._current
                    self._oldSelection = self._current

                if item != self._dropTarget:

                    # unhighlight the previous drop target
                    if self._dropTarget:
                        self._dropTarget.SetHilight(False)
                        self.RefreshLine(self._dropTarget)
                    if item:
                        item.SetHilight(True)
                        self.RefreshLine(item)
                        self._countDrag = self._countDrag + 1
                    self._dropTarget = item

                    self.Update()

                if self._countDrag >= 3 and self._oldItem is not None:
                    # Here I am trying to avoid ugly repainting problems... hope it works
                    self.RefreshLine(self._oldItem)
                    self._countDrag = 0

                return # nothing to do, already done

            if item == None:
                return # we need an item to dragging

            # determine drag start
            if self._dragCount == 0:
                self._dragTimer.Start(_DRAG_TIMER_TICKS, wx.TIMER_ONE_SHOT)

            self._dragCount += 1
            if self._dragCount < 3:
                return # minimum drag 3 pixel
            if self._dragTimer.IsRunning():
                return

            # we're going to drag
            self._dragCount = 0

            # send drag start event
            command = (event.LeftIsDown() and [wx.wxEVT_COMMAND_TREE_BEGIN_DRAG] or [wx.wxEVT_COMMAND_TREE_BEGIN_RDRAG])[0]
            nevent = TreeEvent(command, self._owner.GetId())
            nevent.SetEventObject(self._owner)
            nevent.SetItem(self._current) # the dragged item
            nevent.SetPoint(p)
            nevent.Veto()         # dragging must be explicit allowed!

            if self.GetEventHandler().ProcessEvent(nevent) and nevent.IsAllowed():

                # we're going to drag this item
                self._isDragging = True
                self.CaptureMouse()
                self.RefreshSelected()

                # in a single selection control, hide the selection temporarily
                if not (self._agwStyle & wx.TR_MULTIPLE):
                    if self._oldSelection:

                        self._oldSelection.SetHilight(False)
                        self.RefreshLine(self._oldSelection)
                else:
                    selections = self.GetSelections()
                    if len(selections) == 1:
                        self._oldSelection = selections[0]
                        self._oldSelection.SetHilight(False)
                        self.RefreshLine(self._oldSelection)

        elif self._isDragging:  # any other event but not event.Dragging()

            # end dragging
            self._dragCount = 0
            self._isDragging = False
            if self.HasCapture():
                self.ReleaseMouse()
            self.RefreshSelected()

            # send drag end event event
            nevent = TreeEvent(wx.wxEVT_COMMAND_TREE_END_DRAG, self._owner.GetId())
            nevent.SetEventObject(self._owner)
            nevent.SetItem(item) # the item the drag is started
            nevent.SetPoint(p)
            self._owner.GetEventHandler().ProcessEvent(nevent)

            if self._dragImage:
                self._dragImage.EndDrag()

            if self._dropTarget:
                self._dropTarget.SetHilight(False)
                self.RefreshLine(self._dropTarget)

            if self._oldSelection:
                self._oldSelection.SetHilight(True)
                self.RefreshLine(self._oldSelection)
                self._oldSelection = None

            self._isDragging = False
            self._dropTarget = None
            if self._dragImage:
                self._dragImage = None

            self.Refresh()

        elif self._dragCount > 0:  # just in case dragging is initiated

            # end dragging
            self._dragCount = 0

        # we process only the messages which happen on tree items
        if (item == None or not self.IsItemEnabled(item)) and not event.GetWheelRotation():
            self._owner.GetEventHandler().ProcessEvent(event)
            return

        # remember item at shift down
        if event.ShiftDown():
            if not self._shiftItem:
                self._shiftItem = self._current
        else:
            self._shiftItem = None

        if event.RightUp():

            self.SetFocus()
            nevent = TreeEvent(wx.wxEVT_COMMAND_TREE_ITEM_RIGHT_CLICK, self._owner.GetId())
            nevent.SetEventObject(self._owner)
            nevent.SetItem(item) # the item clicked
            nevent.SetInt(self._curColumn) # the column clicked
            nevent.SetPoint(p)
            self._owner.GetEventHandler().ProcessEvent(nevent)

        elif event.LeftUp():

            if self._lastOnSame:
                if item == self._current and self._curColumn != -1 and \
                   self._owner.GetHeaderWindow().IsColumnEditable(self._curColumn) and \
                   flags & (wx.TREE_HITTEST_ONITEMLABEL | wx.TREE_HITTEST_ONITEMCOLUMN):
                    self._editTimer.Start(_EDIT_TIMER_TICKS, wx.TIMER_ONE_SHOT)

                self._lastOnSame = False

            if (((flags & wx.TREE_HITTEST_ONITEMBUTTON) or (flags & wx.TREE_HITTEST_ONITEMICON)) and \
                self.HasButtons() and item.HasPlus()):

                # only toggle the item for a single click, double click on
                # the button doesn't do anything (it toggles the item twice)
                if event.LeftDown():
                    self.Toggle(item)

                # don't select the item if the button was clicked
                return

            # determine the selection if not done by left down
            if not self._left_down_selection:
                unselect_others = not ((event.ShiftDown() or event.CmdDown()) and self.HasAGWFlag(wx.TR_MULTIPLE))
                self.DoSelectItem(item, unselect_others, event.ShiftDown())
                self.EnsureVisible (item)
                self._current = self._key_current = item # make the new item the current item
            else:
                self._left_down_selection = False

        elif event.LeftDown() or event.RightDown() or event.LeftDClick():

            if column >= 0:
                self._curColumn = column

            if event.LeftDown() or event.RightDown():
                self.SetFocus()
                self._lastOnSame = item == self._current

            if (((flags & wx.TREE_HITTEST_ONITEMBUTTON) or (flags & wx.TREE_HITTEST_ONITEMICON)) and \
                self.HasButtons() and item.HasPlus()):

                # only toggle the item for a single click, double click on
                # the button doesn't do anything (it toggles the item twice)
                if event.LeftDown():
                    self.Toggle(item)

                # don't select the item if the button was clicked
                return

            if flags & TREE_HITTEST_ONITEMCHECKICON and event.LeftDown():
                if item.GetType() > 0:
                    if self.IsItem3State(item):
                        checked = self.GetItem3StateValue(item)
                        checked = (checked+1)%3
                    else:
                        checked = not self.IsItemChecked(item)

                    self.CheckItem(item, checked)
                    return

            # determine the selection if the current item is not selected
            if not item.IsSelected():
                unselect_others = not ((event.ShiftDown() or event.CmdDown()) and self.HasAGWFlag(wx.TR_MULTIPLE))
                self.DoSelectItem(item, unselect_others, event.ShiftDown())
                self.EnsureVisible(item)
                self._current = self._key_current = item # make the new item the current item
                self._left_down_selection = True

            # For some reason, Windows isn't recognizing a left double-click,
            # so we need to simulate it here.  Allow 200 milliseconds for now.
            if event.LeftDClick():

                # double clicking should not start editing the item label
                self._editTimer.Stop()
                self._lastOnSame = False

                # send activate event first
                nevent = TreeEvent(wx.wxEVT_COMMAND_TREE_ITEM_ACTIVATED, self._owner.GetId())
                nevent.SetEventObject(self._owner)
                nevent.SetItem(item) # the item clicked
                nevent.SetInt(self._curColumn) # the column clicked
                nevent.SetPoint(p)
                if not self._owner.GetEventHandler().ProcessEvent(nevent):

                    # if the user code didn't process the activate event,
                    # handle it ourselves by toggling the item when it is
                    # double clicked
                    if item.HasPlus():
                        self.Toggle(item)

        else: # any other event skip just in case

            event.Skip()

[docs]    def OnScroll(self, event):
        """
        Handles the ``wx.EVT_SCROLLWIN`` event for L{TreeListMainWindow}.

        :param `event`: a `wx.ScrollEvent` event to be processed.
        """

        def _updateHeaderWindow(header):
            header.Refresh()
            header.Update()

        # Update the header window after this scroll event has fully finished
        # processing, and the scoll action is complete.
        if event.GetOrientation() == wx.HORIZONTAL:
            wx.CallAfter(_updateHeaderWindow, self._owner.GetHeaderWindow())
        event.Skip()

[docs]    def CalculateSize(self, item, dc):
        """
        Calculates overall position and size of an item.

        :param `item`: an instance of L{TreeListItem};
        :param `dc`: an instance of `wx.DC`.
        """

        attr = item.GetAttributes()

        if attr and attr.HasFont():
            dc.SetFont(attr.GetFont())
        elif item.IsBold():
            dc.SetFont(self._boldFont)
        else:
            dc.SetFont(self._normalFont)

        text_w = text_h = wnd_w = wnd_h = 0
        for column in xrange(self.GetColumnCount()):
            w, h, dummy = dc.GetMultiLineTextExtent(item.GetText(column))
            text_w, text_h = max(w, text_w), max(h, text_h)

            wnd = item.GetWindow(column)
            if wnd:
                wnd_h = max(wnd_h, item.GetWindowSize(column)[1])
                if column == self._main_column:
                    wnd_w = item.GetWindowSize(column)[0]

        text_w, dummy, dummy = dc.GetMultiLineTextExtent(item.GetText(self._main_column))
        text_h+=2

        # restore normal font
        dc.SetFont(self._normalFont)

        image_w, image_h = 0, 0
        image = item.GetCurrentImage()

        if image != _NO_IMAGE:

            if self._imageListNormal:

                image_w, image_h = self._imageListNormal.GetSize(image)
                image_w += 2*_MARGIN

        total_h = ((image_h > text_h) and [image_h] or [text_h])[0]

        checkimage = item.GetCurrentCheckedImage()
        if checkimage is not None:
            wcheck, hcheck = self._imageListCheck.GetSize(checkimage)
            wcheck += 2*_MARGIN
        else:
            wcheck = 0

        if total_h < 30:
            total_h += 2            # at least 2 pixels
        else:
            total_h += total_h/10   # otherwise 10% extra spacing

        if total_h > self._lineHeight:
            self._lineHeight = max(total_h, wnd_h+2)

        item.SetWidth(image_w+text_w+wcheck+2+wnd_w)
        item.SetHeight(max(total_h, wnd_h+2))

[docs]    def CalculateLevel(self, item, dc, level, y, x_colstart):
        """
        Calculates the level of an item inside the tree hierarchy.

        :param `item`: an instance of L{TreeListItem};
        :param `dc`: an instance of `wx.DC`;
        :param `level`: the item level in the tree hierarchy;
        :param `y`: the current vertical position inside the `wx.PyScrolledWindow`;
        :param `x_colstart`: the x coordinate at which the item's column starts.
        """

        # calculate position of vertical lines
        x = x_colstart + _MARGIN # start of column
        if self.HasAGWFlag(wx.TR_LINES_AT_ROOT):
            x += _LINEATROOT # space for lines at root
        if self.HasButtons():
            x += (self._btnWidth-self._btnWidth2) # half button space
        else:
            x += (self._indent-self._indent/2)

        if self.HasAGWFlag(wx.TR_HIDE_ROOT):
            x += self._indent * (level-1) # indent but not level 1
        else:
            x += self._indent * level # indent according to level

        # a hidden root is not evaluated, but its children are always
        if self.HasAGWFlag(wx.TR_HIDE_ROOT) and (level == 0):
            # a hidden root is not evaluated, but its
            # children are always calculated
            children = item.GetChildren()
            count = len(children)
            level = level + 1
            for n in xrange(count):
                y = self.CalculateLevel(children[n], dc, level, y, x_colstart)  # recurse

            return y

        self.CalculateSize(item, dc)

        # set its position
        item.SetX(x)
        item.SetY(y)
        y += self.GetLineHeight(item)

        if not item.IsExpanded():
            # we don't need to calculate collapsed branches
            return y

        children = item.GetChildren()
        count = len(children)
        level = level + 1
        for n in xrange(count):
            y = self.CalculateLevel(children[n], dc, level, y, x_colstart)  # recurse

        return y

[docs]    def CalculatePositions(self):
        """ Recalculates all the items positions. """

        if not self._anchor:
            return

        dc = wx.ClientDC(self)
        self.PrepareDC(dc)

        dc.SetFont(self._normalFont)
        dc.SetPen(self._dottedPen)

        y, x_colstart = 2, 0
        for i in xrange(self.GetMainColumn()):
            if not self._owner.GetHeaderWindow().IsColumnShown(i):
                continue
            x_colstart += self._owner.GetHeaderWindow().GetColumnWidth(i)

        self.CalculateLevel(self._anchor, dc, 0, y, x_colstart) # start recursion

[docs]    def SetItemText(self, item, text, column=None):
        """
        Sets the item text label.

        :param `item`: an instance of L{TreeListItem};
        :param `text`: a string specifying the new item label;
        :param `column`: if not ``None``, an integer specifying the column index.
         If it is ``None``, the main column index is used.
        """

        dc = wx.ClientDC(self)
        item.SetText(column, text)
        self.CalculateSize(item, dc)
        self.RefreshLine(item)

[docs]    def GetItemText(self, item, column=None):
        """
        Returns the item text label.

        :param `item`: an instance of L{TreeListItem};
        :param `column`: if not ``None``, an integer specifying the column index.
         If it is ``None``, the main column index is used.
        """

        if self.IsVirtual():
            return self._owner.OnGetItemText(item, column)
        else:
            return item.GetText(column)

[docs]    def GetItemWidth(self, item, column):
        """
        Returns the item width.

        :param `item`: an instance of L{TreeListItem};
        :param `column`: an integer specifying the column index.
        """

        if not item:
            return 0

        # determine item width
        font = self.GetItemFont(item)
        if not font.IsOk():
            if item.IsBold():
                font = self._boldFont
            elif item.IsItalic():
                font = self._italicFont
            elif item.IsHyperText():
                font = self.GetHyperTextFont()
            else:
                font = self._normalFont

        dc = wx.ClientDC(self)
        dc.SetFont(font)
        w, h, dummy = dc.GetMultiLineTextExtent(item.GetText(column))
        w += 2*_MARGIN

        # calculate width
        width = w + 2*_MARGIN
        if column == self.GetMainColumn():
            width += _MARGIN
            if self.HasAGWFlag(wx.TR_LINES_AT_ROOT):
                width += _LINEATROOT
            if self.HasButtons():
                width += self._btnWidth + _LINEATROOT
            if item.GetCurrentImage() != _NO_IMAGE:
                width += self._imgWidth

            # count indent level
            level = 0
            parent = item.GetParent()
            root = self.GetRootItem()
            while (parent and (not self.HasAGWFlag(wx.TR_HIDE_ROOT) or (parent != root))):
                level += 1
                parent = parent.GetParent()

            if level:
                width += level*self.GetIndent()

        wnd = item.GetWindow(column)
        if wnd:
            width += wnd.GetSize()[0] + 2*_MARGIN

        return width

[docs]    def GetBestColumnWidth(self, column, parent=None):
        """
        Returns the best column's width based on the items width in this column.

        :param `column`: an integer specifying the column index;
        :param `parent`: an instance of L{TreeListItem}.
        """

        maxWidth, h = self.GetClientSize()
        width = 0

        if maxWidth < 5:
            # Not shown on screen
            maxWidth = 1000

        # get root if on item
        if not parent:
            parent = self.GetRootItem()

        # add root width
        if not self.HasAGWFlag(wx.TR_HIDE_ROOT):
            w = self.GetItemWidth(parent, column)
            if width < w:
                width = w
            if width > maxWidth:
                return maxWidth

        item, cookie = self.GetFirstChild(parent)
        while item:
            w = self.GetItemWidth(item, column)
            if width < w:
                width = w
            if width > maxWidth:
                return maxWidth

            # check the children of this item
            if item.IsExpanded():
                w = self.GetBestColumnWidth(column, item)
                if width < w:
                    width = w
                if width > maxWidth:
                    return maxWidth

            # next sibling
            item, cookie = self.GetNextChild(parent, cookie)

        return max(10, width) # Prevent zero column width

[docs]    def HideItem(self, item, hide=True):
        """
        Hides/shows an item.

        :param `item`: an instance of L{TreeListItem};
        :param `hide`: ``True`` to hide the item, ``False`` to show it.
        """

        item.Hide(hide)
        self.Refresh()

#----------------------------------------------------------------------------
# TreeListCtrl - the multicolumn tree control
#----------------------------------------------------------------------------

_methods = ["GetIndent", "SetIndent", "GetSpacing", "SetSpacing", "GetImageList", "GetStateImageList",
            "GetButtonsImageList", "AssignImageList", "AssignStateImageList", "AssignButtonsImageList",
            "SetImageList", "SetButtonsImageList", "SetStateImageList",
            "GetItemText", "GetItemImage", "GetItemPyData", "GetPyData", "GetItemTextColour",
            "GetItemBackgroundColour", "GetItemFont", "SetItemText", "SetItemImage", "SetItemPyData", "SetPyData",
            "SetItemHasChildren", "SetItemBackgroundColour", "SetItemFont", "IsItemVisible", "HasChildren",
            "IsExpanded", "IsSelected", "IsBold", "GetChildrenCount", "GetRootItem", "GetSelection", "GetSelections",
            "GetItemParent", "GetFirstChild", "GetNextChild", "GetPrevChild", "GetLastChild", "GetNextSibling",
            "GetPrevSibling", "GetNext", "GetFirstExpandedItem", "GetNextExpanded", "GetPrevExpanded",
            "GetFirstVisibleItem", "GetNextVisible", "GetPrevVisible", "AddRoot", "PrependItem", "InsertItem",
            "AppendItem", "Delete", "DeleteChildren", "DeleteRoot", "Expand", "ExpandAll", "ExpandAllChildren",
            "Collapse", "CollapseAndReset", "Toggle", "Unselect", "UnselectAll", "SelectItem", "SelectAll",
            "EnsureVisible", "ScrollTo", "HitTest", "GetBoundingRect", "EditLabel", "FindItem", "SelectAllChildren",
            "SetDragItem", "GetColumnCount", "SetMainColumn", "GetHyperTextFont", "SetHyperTextFont",
            "SetHyperTextVisitedColour", "GetHyperTextVisitedColour", "SetHyperTextNewColour", "GetHyperTextNewColour",
            "SetItemVisited", "GetItemVisited", "SetHilightFocusColour", "GetHilightFocusColour", "SetHilightNonFocusColour",
            "GetHilightNonFocusColour", "SetFirstGradientColour", "GetFirstGradientColour", "SetSecondGradientColour",
            "GetSecondGradientColour", "EnableSelectionGradient", "SetGradientStyle", "GetGradientStyle",
            "EnableSelectionVista", "SetBorderPen", "GetBorderPen", "SetConnectionPen", "GetConnectionPen",
            "SetBackgroundImage", "GetBackgroundImage", "SetImageListCheck", "GetImageListCheck", "EnableChildren",
            "EnableItem", "IsItemEnabled", "GetDisabledColour", "SetDisabledColour", "IsItemChecked",
            "UnCheckRadioParent", "CheckItem", "CheckItem2", "AutoToggleChild", "AutoCheckChild", "AutoCheckParent",
            "CheckChilds", "CheckSameLevel", "GetItemWindowEnabled", "SetItemWindowEnabled", "GetItemType",
            "IsDescendantOf", "SetItemHyperText", "IsItemHyperText", "SetItemBold", "SetItemDropHighlight", "SetItemItalic",
            "GetEditControl", "ShouldInheritColours", "GetItemWindow", "SetItemWindow", "SetItemTextColour", "HideItem",
            "DeleteAllItems", "ItemHasChildren", "ToggleItemSelection", "SetItemType", "GetCurrentItem",
            "SetItem3State", "SetItem3StateValue", "GetItem3StateValue", "IsItem3State", "GetPrev"]

[docs]class HyperTreeList(wx.PyControl):
    """
    L{HyperTreeList} is a class that mimics the behaviour of `wx.gizmos.TreeListCtrl`, with
    almost the same base functionalities plus some more enhancements. This class does
    not rely on the native control, as it is a full owner-drawn tree-list control.
    """

[docs]    def __init__(self, parent, id=wx.ID_ANY, pos=wx.DefaultPosition, size=wx.DefaultSize,
                 style=0, agwStyle=wx.TR_DEFAULT_STYLE, validator=wx.DefaultValidator,
                 name="HyperTreeList"):
        """
        Default class constructor.

        :param `parent`: parent window. Must not be ``None``;
        :param `id`: window identifier. A value of -1 indicates a default value;
        :param `pos`: the control position. A value of (-1, -1) indicates a default position,
         chosen by either the windowing system or wxPython, depending on platform;
        :param `size`: the control size. A value of (-1, -1) indicates a default size,
         chosen by either the windowing system or wxPython, depending on platform;
        :param `style`: the underlying `wx.PyScrolledWindow` style;
        :param `agwStyle`: the AGW-specific L{HyperTreeList} window style. This can be a combination
         of the following bits:

         ============================== =========== ==================================================
         Window Styles                  Hex Value   Description
         ============================== =========== ==================================================
         ``TR_NO_BUTTONS``                      0x0 For convenience to document that no buttons are to be drawn.
         ``TR_SINGLE``                          0x0 For convenience to document that only one item may be selected at a time. Selecting another item causes the current selection, if any, to be deselected. This is the default.
         ``TR_HAS_BUTTONS``                     0x1 Use this style to show + and - buttons to the left of parent items.
         ``TR_NO_LINES``                        0x4 Use this style to hide vertical level connectors.
         ``TR_LINES_AT_ROOT``                   0x8 Use this style to show lines between root nodes. Only applicable if ``TR_HIDE_ROOT`` is set and ``TR_NO_LINES`` is not set.
         ``TR_DEFAULT_STYLE``                   0x9 The set of flags that are closest to the defaults for the native control for a particular toolkit.
         ``TR_TWIST_BUTTONS``                  0x10 Use old Mac-twist style buttons.
         ``TR_MULTIPLE``                       0x20 Use this style to allow a range of items to be selected. If a second range is selected, the current range, if any, is deselected.
         ``TR_EXTENDED``                       0x40 Use this style to allow disjoint items to be selected. (Only partially implemented; may not work in all cases).
         ``TR_HAS_VARIABLE_ROW_HEIGHT``        0x80 Use this style to cause row heights to be just big enough to fit the content. If not set, all rows use the largest row height. The default is that this flag is unset.
         ``TR_EDIT_LABELS``                   0x200 Use this style if you wish the user to be able to edit labels in the tree control.
         ``TR_ROW_LINES``                     0x400 Use this style to draw a contrasting border between displayed rows.
         ``TR_HIDE_ROOT``                     0x800 Use this style to suppress the display of the root node, effectively causing the first-level nodes to appear as a series of root nodes.
         ``TR_COLUMN_LINES``                 0x1000 Use this style to draw a contrasting border between displayed columns.
         ``TR_FULL_ROW_HIGHLIGHT``           0x2000 Use this style to have the background colour and the selection highlight extend  over the entire horizontal row of the tree control window.
         ``TR_AUTO_CHECK_CHILD``             0x4000 Only meaningful foe checkbox-type items: when a parent item is checked/unchecked its children are checked/unchecked as well.
         ``TR_AUTO_TOGGLE_CHILD``            0x8000 Only meaningful foe checkbox-type items: when a parent item is checked/unchecked its children are toggled accordingly.
         ``TR_AUTO_CHECK_PARENT``           0x10000 Only meaningful foe checkbox-type items: when a child item is checked/unchecked its parent item is checked/unchecked as well.
         ``TR_ALIGN_WINDOWS``               0x20000 Flag used to align windows (in items with windows) at the same horizontal position.
         ``TR_NO_HEADER``                   0x40000 Use this style to hide the columns header.
         ``TR_ELLIPSIZE_LONG_ITEMS``        0x80000 Flag used to ellipsize long items when the horizontal space for L{CustomTreeCtrl} is low.
         ``TR_VIRTUAL``                    0x100000 L{HyperTreeList} will have virtual behaviour.
         ============================== =========== ==================================================

        :param `validator`: window validator;
        :param `name`: window name.
        """

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

        self._header_win = None
        self._main_win = None
        self._headerHeight = 0
        self._attr_set = False

        main_style = style & ~(wx.SIMPLE_BORDER|wx.SUNKEN_BORDER|wx.DOUBLE_BORDER|
                               wx.RAISED_BORDER|wx.STATIC_BORDER)

        self._agwStyle = agwStyle

        self._main_win = TreeListMainWindow(self, -1, wx.Point(0, 0), size, main_style, agwStyle, validator)
        self._main_win._buffered = False

        self._header_win = TreeListHeaderWindow(self, -1, self._main_win, wx.Point(0, 0),
                                                wx.DefaultSize, wx.TAB_TRAVERSAL)
        self._header_win._buffered = False

        self.CalculateAndSetHeaderHeight()
        self.Bind(wx.EVT_SIZE, self.OnSize)

        self.SetBuffered(IsBufferingSupported())
        self._main_win.SetAGWWindowStyleFlag(agwStyle)

[docs]    def SetBuffered(self, buffered):
        """
        Sets/unsets the double buffering for the header and the main window.

        :param `buffered`: ``True`` to use double-buffering, ``False`` otherwise.

        :note: Currently we are using double-buffering only on Windows XP.
        """

        self._main_win.SetBuffered(buffered)
        self._header_win.SetBuffered(buffered)

[docs]    def CalculateAndSetHeaderHeight(self):
        """ Calculates the best header height and stores it. """

        if self._header_win:
            h = wx.RendererNative.Get().GetHeaderButtonHeight(self._header_win)
            # only update if changed
            if h != self._headerHeight:
                self._headerHeight = h
                self.DoHeaderLayout()

[docs]    def DoHeaderLayout(self):
        """ Layouts the header control. """

        w, h = self.GetClientSize()
        has_header = self._agwStyle & TR_NO_HEADER == 0

        if self._header_win and has_header:
            self._header_win.SetDimensions(0, 0, w, self._headerHeight)
            self._header_win.Refresh()
        else:
            self._header_win.SetDimensions(0, 0, 0, 0)

        if self._main_win and has_header:
            self._main_win.SetDimensions(0, self._headerHeight + 1, w, h - self._headerHeight - 1)
        else:
            self._main_win.SetDimensions(0, 0, w, h)

[docs]    def OnSize(self, event):
        """
        Handles the ``wx.EVT_SIZE`` event for L{HyperTreeList}.

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

        self.DoHeaderLayout()

[docs]    def SetFont(self, font):
        """
        Sets the default font for the header window and the main window.

        :param `font`: a valid `wx.Font` object.
        """

        if self._header_win:
            self._header_win.SetFont(font)
            self.CalculateAndSetHeaderHeight()
            self._header_win.Refresh()

        if self._main_win:
            return self._main_win.SetFont(font)
        else:
            return False

[docs]    def SetHeaderFont(self, font):
        """
        Sets the default font for the header window..

        :param `font`: a valid `wx.Font` object.
        """

        if not self._header_win:
            return

        for column in xrange(self.GetColumnCount()):
            self._header_win.SetColumn(column, self.GetColumn(column).SetFont(font))

        self._header_win.Refresh()

[docs]    def SetHeaderCustomRenderer(self, renderer=None):
        """
        Associate a custom renderer with the header - all columns will use it

        :param `renderer`: a class able to correctly render header buttons

        :note: the renderer class **must** implement the method `DrawHeaderButton`
        """

        self._header_win.SetCustomRenderer(renderer)

[docs]    def SetAGWWindowStyleFlag(self, agwStyle):
        """
        Sets the window style for L{HyperTreeList}.

        :param `agwStyle`: can be a combination of the following bits:

         ============================== =========== ==================================================
         Window Styles                  Hex Value   Description
         ============================== =========== ==================================================
         ``TR_NO_BUTTONS``                      0x0 For convenience to document that no buttons are to be drawn.
         ``TR_SINGLE``                          0x0 For convenience to document that only one item may be selected at a time. Selecting another item causes the current selection, if any, to be deselected. This is the default.
         ``TR_HAS_BUTTONS``                     0x1 Use this style to show + and - buttons to the left of parent items.
         ``TR_NO_LINES``                        0x4 Use this style to hide vertical level connectors.
         ``TR_LINES_AT_ROOT``                   0x8 Use this style to show lines between root nodes. Only applicable if ``TR_HIDE_ROOT`` is set and ``TR_NO_LINES`` is not set.
         ``TR_DEFAULT_STYLE``                   0x9 The set of flags that are closest to the defaults for the native control for a particular toolkit.
         ``TR_TWIST_BUTTONS``                  0x10 Use old Mac-twist style buttons.
         ``TR_MULTIPLE``                       0x20 Use this style to allow a range of items to be selected. If a second range is selected, the current range, if any, is deselected.
         ``TR_EXTENDED``                       0x40 Use this style to allow disjoint items to be selected. (Only partially implemented; may not work in all cases).
         ``TR_HAS_VARIABLE_ROW_HEIGHT``        0x80 Use this style to cause row heights to be just big enough to fit the content. If not set, all rows use the largest row height. The default is that this flag is unset.
         ``TR_EDIT_LABELS``                   0x200 Use this style if you wish the user to be able to edit labels in the tree control.
         ``TR_ROW_LINES``                     0x400 Use this style to draw a contrasting border between displayed rows.
         ``TR_HIDE_ROOT``                     0x800 Use this style to suppress the display of the root node, effectively causing the first-level nodes to appear as a series of root nodes.
         ``TR_COLUMN_LINES``                 0x1000 Use this style to draw a contrasting border between displayed columns.
         ``TR_FULL_ROW_HIGHLIGHT``           0x2000 Use this style to have the background colour and the selection highlight extend  over the entire horizontal row of the tree control window.
         ``TR_AUTO_CHECK_CHILD``             0x4000 Only meaningful foe checkbox-type items: when a parent item is checked/unchecked its children are checked/unchecked as well.
         ``TR_AUTO_TOGGLE_CHILD``            0x8000 Only meaningful foe checkbox-type items: when a parent item is checked/unchecked its children are toggled accordingly.
         ``TR_AUTO_CHECK_PARENT``           0x10000 Only meaningful foe checkbox-type items: when a child item is checked/unchecked its parent item is checked/unchecked as well.
         ``TR_ALIGN_WINDOWS``               0x20000 Flag used to align windows (in items with windows) at the same horizontal position.
         ``TR_NO_HEADER``                   0x40000 Use this style to hide the columns header.
         ``TR_ELLIPSIZE_LONG_ITEMS``        0x80000 Flag used to ellipsize long items when the horizontal space for L{CustomTreeCtrl} is low.
         ``TR_VIRTUAL``                    0x100000 L{HyperTreeList} will have virtual behaviour.
         ============================== =========== ==================================================

        :note: Please note that some styles cannot be changed after the window creation
         and that `Refresh()` might need to be be called after changing the others for
         the change to take place immediately.
        """

        if self._main_win:
            self._main_win.SetAGWWindowStyleFlag(agwStyle)

        tmp = self._agwStyle
        self._agwStyle = agwStyle
        if abs(agwStyle - tmp) & TR_NO_HEADER:
            self.DoHeaderLayout()

[docs]    def GetAGWWindowStyleFlag(self):
        """
        Returns the L{HyperTreeList} window style flag.

        :see: L{SetAGWWindowStyleFlag} for a list of valid window styles.
        """

        agwStyle = self._agwStyle
        if self._main_win:
            agwStyle |= self._main_win.GetAGWWindowStyleFlag()

        return agwStyle

[docs]    def HasAGWFlag(self, flag):
        """
        Returns whether a flag is present in the L{HyperTreeList} style.

        :param `flag`: one of the possible L{HyperTreeList} window styles.

        :see: L{SetAGWWindowStyleFlag} for a list of possible window style flags.
        """

        agwStyle = self.GetAGWWindowStyleFlag()
        res = (agwStyle & flag and [True] or [False])[0]
        return res

[docs]    def SetBackgroundColour(self, colour):
        """
        Changes the background colour of L{HyperTreeList}.

        :param `colour`: the colour to be used as the background colour, pass
         `wx.NullColour` to reset to the default colour.

        :note: The background colour is usually painted by the default `wx.EraseEvent`
         event handler function under Windows and automatically under GTK.

        :note: Setting the background colour does not cause an immediate refresh, so
         you may wish to call `wx.Window.ClearBackground` or `wx.Window.Refresh` after
         calling this function.

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

        if not self._main_win:
            return False

        return self._main_win.SetBackgroundColour(colour)

[docs]    def SetForegroundColour(self, colour):
        """
        Changes the foreground colour of L{HyperTreeList}.

        :param `colour`: the colour to be used as the foreground colour, pass
         `wx.NullColour` to reset to the default colour.

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

        if not self._main_win:
            return False

        return self._main_win.SetForegroundColour(colour)

[docs]    def SetColumnWidth(self, column, width):
        """
        Sets the column width, in pixels.

        :param `column`: an integer specifying the column index;
        :param `width`: the new column width, in pixels.
        """

        if width == wx.LIST_AUTOSIZE_USEHEADER:

            font = self._header_win.GetFont()
            dc = wx.ClientDC(self._header_win)
            width, dummy, dummy = dc.GetMultiLineTextExtent(self._header_win.GetColumnText(column))
            # Search TreeListHeaderWindow.OnPaint to understand this:
            width += 2*_EXTRA_WIDTH + _MARGIN

        elif width == wx.LIST_AUTOSIZE:

            width = self._main_win.GetBestColumnWidth(column)

        self._header_win.SetColumnWidth(column, width)
        self._header_win.Refresh()

[docs]    def GetColumnWidth(self, column):
        """
        Returns the column width, in pixels.

        :param `column`: an integer specifying the column index.
        """

        return self._header_win.GetColumnWidth(column)

[docs]    def SetColumnText(self, column, text):
        """
        Sets the column text label.

        :param `column`: an integer specifying the column index;
        :param `text`: the new column label.
        """

        self._header_win.SetColumnText(column, text)
        self._header_win.Refresh()

[docs]    def GetColumnText(self, column):
        """
        Returns the column text label.

        :param `column`: an integer specifying the column index.
        """

        return self._header_win.GetColumnText(column)

[docs]    def AddColumn(self, text, width=_DEFAULT_COL_WIDTH, flag=wx.ALIGN_LEFT,
                  image=-1, shown=True, colour=None, edit=False):
        """
        Appends a column to the L{HyperTreeList}.

        :param `text`: the column text label;
        :param `width`: the column width in pixels;
        :param `flag`: the column alignment flag, one of ``wx.ALIGN_LEFT``,
         ``wx.ALIGN_RIGHT``, ``wx.ALIGN_CENTER``;
        :param `image`: an index within the normal image list assigned to
         L{HyperTreeList} specifying the image to use for the column;
        :param `shown`: ``True`` to show the column, ``False`` to hide it;
        :param `colour`: a valid `wx.Colour`, representing the text foreground colour
         for the column;
        :param `edit`: ``True`` to set the column as editable, ``False`` otherwise.
        """

        self._header_win.AddColumn(text, width, flag, image, shown, colour, edit)
        self.DoHeaderLayout()

[docs]    def AddColumnInfo(self, colInfo):
        """
        Appends a column to the L{HyperTreeList}.

        :param `colInfo`: an instance of L{TreeListColumnInfo}.
        """

        self._header_win.AddColumnInfo(colInfo)
        self.DoHeaderLayout()

[docs]    def InsertColumnInfo(self, before, colInfo):
        """
        Inserts a column to the L{HyperTreeList} at the position specified
        by `before`.

        :param `before`: the index at which we wish to insert the new column;
        :param `colInfo`: an instance of L{TreeListColumnInfo}.
        """

        self._header_win.InsertColumnInfo(before, colInfo)
        self._header_win.Refresh()

[docs]    def InsertColumn(self, before, text, width=_DEFAULT_COL_WIDTH,
                     flag=wx.ALIGN_LEFT, image=-1, shown=True, colour=None,
                     edit=False):
        """
        Inserts a column to the L{HyperTreeList} at the position specified
        by `before`.

        :param `before`: the index at which we wish to insert the new column;
        :param `text`: the column text label;
        :param `width`: the column width in pixels;
        :param `flag`: the column alignment flag, one of ``wx.ALIGN_LEFT``,
         ``wx.ALIGN_RIGHT``, ``wx.ALIGN_CENTER``;
        :param `image`: an index within the normal image list assigned to
         L{HyperTreeList} specifying the image to use for the column;
        :param `shown`: ``True`` to show the column, ``False`` to hide it;
        :param `colour`: a valid `wx.Colour`, representing the text foreground colour
         for the column;
        :param `edit`: ``True`` to set the column as editable, ``False`` otherwise.
        """

        self._header_win.InsertColumn(before, text, width, flag, image,
                                      shown, colour, edit)
        self._header_win.Refresh()

[docs]    def RemoveColumn(self, column):
        """
        Removes a column from the L{HyperTreeList}.

        :param `column`: an integer specifying the column index.
        """

        self._header_win.RemoveColumn(column)
        self._header_win.Refresh()

[docs]    def SetColumn(self, column, colInfo):
        """
        Sets a column using an instance of L{TreeListColumnInfo}.

        :param `column`: an integer specifying the column index;
        :param `info`: an instance of L{TreeListColumnInfo}.
        """

        self._header_win.SetColumn(column, colInfo)
        self._header_win.Refresh()

[docs]    def GetColumn(self, column):
        """
        Returns an instance of L{TreeListColumnInfo} containing column information.

        :param `column`: an integer specifying the column index.
        """

        return self._header_win.GetColumn(column)

[docs]    def SetColumnImage(self, column, image):
        """
        Sets an image on the specified column.

        :param `column`: an integer specifying the column index.
        :param `image`: an index within the normal image list assigned to
         L{HyperTreeList} specifying the image to use for the column.
        """

        self._header_win.SetColumn(column, self.GetColumn(column).SetImage(image))
        self._header_win.Refresh()

[docs]    def GetColumnImage(self, column):
        """
        Returns the image assigned to the specified column.

        :param `column`: an integer specifying the column index.
        """

        return self._header_win.GetColumn(column).GetImage()

[docs]    def SetColumnEditable(self, column, edit):
        """
        Sets the column as editable or non-editable.

        :param `column`: an integer specifying the column index;
        :param `edit`: ``True`` if the column should be editable, ``False`` otherwise.
        """

        self._header_win.SetColumn(column, self.GetColumn(column).SetEditable(edit))

[docs]    def SetColumnShown(self, column, shown):
        """
        Sets the column as shown or hidden.

        :param `column`: an integer specifying the column index;
        :param `shown`: ``True`` if the column should be shown, ``False`` if it
         should be hidden.
        """

        if self._main_win.GetMainColumn() == column:
            shown = True # Main column cannot be hidden

        self.SetColumn(column, self.GetColumn(column).SetShown(shown))

[docs]    def IsColumnEditable(self, column):
        """
        Returns ``True`` if the column is editable, ``False`` otherwise.

        :param `column`: an integer specifying the column index.
        """

        return self._header_win.GetColumn(column).IsEditable()

[docs]    def IsColumnShown(self, column):
        """
        Returns ``True`` if the column is shown, ``False`` otherwise.

        :param `column`: an integer specifying the column index.
        """

        return self._header_win.GetColumn(column).IsShown()

[docs]    def SetColumnAlignment(self, column, flag):
        """
        Sets the column text alignment.

        :param `column`: an integer specifying the column index;
        :param `flag`: the alignment flag, one of ``wx.ALIGN_LEFT``, ``wx.ALIGN_RIGHT``,
         ``wx.ALIGN_CENTER``.
        """

        self._header_win.SetColumn(column, self.GetColumn(column).SetAlignment(flag))
        self._header_win.Refresh()

[docs]    def GetColumnAlignment(self, column):
        """
        Returns the column text alignment.

        :param `column`: an integer specifying the column index.
        """

        return self._header_win.GetColumn(column).GetAlignment()

[docs]    def SetColumnColour(self, column, colour):
        """
        Sets the column text colour.

        :param `column`: an integer specifying the column index;
        :param `colour`: a valid `wx.Colour` object.
        """

        self._header_win.SetColumn(column, self.GetColumn(column).SetColour(colour))
        self._header_win.Refresh()

[docs]    def GetColumnColour(self, column):
        """
        Returns the column text colour.

        :param `column`: an integer specifying the column index.
        """

        return self._header_win.GetColumn(column).GetColour()

[docs]    def SetColumnFont(self, column, font):
        """
        Sets the column text font.

        :param `column`: an integer specifying the column index;
        :param `font`: a valid `wx.Font` object.
        """

        self._header_win.SetColumn(column, self.GetColumn(column).SetFont(font))
        self._header_win.Refresh()

[docs]    def GetColumnFont(self, column):
        """
        Returns the column text font.

        :param `column`: an integer specifying the column index.
        """

        return self._header_win.GetColumn(column).GetFont()

[docs]    def Refresh(self, erase=True, rect=None):
        """
        Causes this window, and all of its children recursively (except under wxGTK1
        where this is not implemented), to be repainted.

        :param `erase`: If ``True``, the background will be erased;
        :param `rect`: If not ``None``, only the given rectangle will be treated as damaged.

        :note: Note that repainting doesn't happen immediately but only during the next
         event loop iteration, if you need to update the window immediately you should
         use `Update` instead.

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

        self._main_win.Refresh(erase, rect)
        self._header_win.Refresh(erase, rect)

[docs]    def SetFocus(self):
        """ This sets the window to receive keyboard input. """

        self._main_win.SetFocus()

[docs]    def GetHeaderWindow(self):
        """ Returns the header window, an instance of L{TreeListHeaderWindow}. """

        return self._header_win

[docs]    def GetMainWindow(self):
        """ Returns the main window, an instance of L{TreeListMainWindow}. """

        return self._main_win

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

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

        # something is better than nothing...
        return wx.Size(200, 200) # but it should be specified values! FIXME

[docs]    def OnGetItemText(self, item, column):
        """
        This function **must** be overloaded in the derived class for a control
        with ``TR_VIRTUAL`` style. It should return the string containing the
        text of the given column for the specified item.

        :param `item`: an instance of L{TreeListItem};
        :param `column`: an integer specifying the column index.
        """

        return ""

[docs]    def SortChildren(self, item):
        """
        Sorts the children of the given item using L{OnCompareItems} method of L{HyperTreeList}.
        You should override that method to change the sort order (the default is ascending
        case-sensitive alphabetical order).

        :param `item`: an instance of L{TreeListItem};
        """

        if not self._attr_set:
            setattr(self._main_win, "OnCompareItems", self.OnCompareItems)
            self._attr_set = True

        self._main_win.SortChildren(item)

[docs]    def OnCompareItems(self, item1, item2):
        """
        Returns whether 2 items have the same text.

        Override this function in the derived class to change the sort order of the items
        in the L{HyperTreeList}. The function should return a negative, zero or positive
        value if the first item is less than, equal to or greater than the second one.

        :param `item1`: an instance of L{TreeListItem};
        :param `item2`: another instance of L{TreeListItem}.

        :note: The base class version compares items alphabetically.
        """

        # do the comparison here, and not delegate to self._main_win, in order
        # to let the user override it

        return self.GetItemText(item1) == self.GetItemText(item2)

[docs]    def CreateEditCtrl(self, item, column):
        """
        Create an edit control for editing a label of an item. By default, this
        returns a text control.

        Override this function in the derived class to return a different type
        of control.

        :param `item`: an instance of L{TreeListItem};
        :param `column`: an integer specifying the column index.
        """

        return EditTextCtrl(self.GetMainWindow(), -1, item, column,
                            self.GetMainWindow(), item.GetText(column),
                            style=self.GetTextCtrlStyle(column))

[docs]    def GetTextCtrlStyle(self, column):
        """
        Return the style to use for the text control that is used to edit
        labels of items.

        Override this function in the derived class to support a different
        style, e.g. ``wx.TE_MULTILINE``.

        :param `column`: an integer specifying the column index.
        """

        return self.GetTextCtrlAlignmentStyle(column) | wx.TE_PROCESS_ENTER

[docs]    def GetTextCtrlAlignmentStyle(self, column):
        """
        Return the alignment style to use for the text control that is used
        to edit labels of items. The alignment style is derived from the
        column alignment.

        :param `column`: an integer specifying the column index.
        """

        header_win = self.GetHeaderWindow()
        alignment = header_win.GetColumnAlignment(column)
        return {wx.ALIGN_LEFT: wx.TE_LEFT,
                wx.ALIGN_RIGHT: wx.TE_RIGHT,
                wx.ALIGN_CENTER: wx.TE_CENTER}[alignment]

[docs]    def GetClassDefaultAttributes(self):
        """
        Returns the default font and colours which are used by the control. This is
        useful if you want to use the same font or colour in your own control as in
        a standard control -- which is a much better idea than hard coding specific
        colours or fonts which might look completely out of place on the users system,
        especially if it uses themes.

        This static method is "overridden'' in many derived classes and so calling,
        for example, `wx.Button.GetClassDefaultAttributes()` will typically return the
        values appropriate for a button which will be normally different from those
        returned by, say, `wx.ListCtrl.GetClassDefaultAttributes()`.

        :note: The `wx.VisualAttributes` structure has at least the fields `font`,
         `colFg` and `colBg`. All of them may be invalid if it was not possible to
         determine the default control appearance or, especially for the background
         colour, if the field doesn't make sense as is the case for `colBg` for the
         controls with themed background.
        """

        attr = wx.VisualAttributes()
        attr.colFg = wx.SystemSettings_GetColour(wx.SYS_COLOUR_WINDOWTEXT)
        attr.colBg = wx.SystemSettings_GetColour(wx.SYS_COLOUR_LISTBOX)
        attr.font  = wx.SystemSettings_GetFont(wx.SYS_DEFAULT_GUI_FONT)
        return attr

    GetClassDefaultAttributes = classmethod(GetClassDefaultAttributes)

[docs]def create_delegator_for(method):
    """
    Creates a method that forwards calls to `self._main_win` (an instance of L{TreeListMainWindow}).

    :param `method`: one method inside the L{TreeListMainWindow} local scope.
    """

    def delegate(self, *args, **kwargs):
        return getattr(self._main_win, method)(*args, **kwargs)
    return delegate

# Create methods that delegate to self._main_win. This approach allows for
# overriding these methods in possible subclasses of HyperTreeList

for method in _methods:
    setattr(HyperTreeList, method, create_delegator_for(method))

Navigation

  • index
  • modules |
  • Home |
  • Gallery |
  • Contents»
  • Module code »
  • hypertreelist


Overview: module code

  • modules |
  • Home |
  • Gallery |
  • Contents»
  • Overview: module code

All modules for which code is available

  • advancedsplash
  • aquabutton
  • artmanager
  • aui.aui_switcherdialog
  • aui.aui_utilities
  • aui.auibar
  • aui.auibook
  • aui.dockart
  • aui.framemanager
  • aui.tabart
  • balloontip
  • buttonpanel
  • cubecolourdialog
  • customtreectrl
  • flatmenu
  • flatnotebook
  • floatspin
  • fmcustomizedlg
  • foldpanelbar
  • fourwaysplitter
  • genericmessagedialog
  • gradientbutton
  • hyperlink
  • hypertreelist
  • infobar
  • knobctrl
  • labelbook
  • multidirdialog
  • peakmeter
  • persist.persist_handlers
  • persist.persistencemanager
  • piectrl
  • pybusyinfo
  • pycollapsiblepane
  • pygauge
  • pyprogress
  • ribbon.art_aui
  • ribbon.art_internal
  • ribbon.art_msw
  • ribbon.bar
  • ribbon.buttonbar
  • ribbon.control
  • ribbon.gallery
  • ribbon.page
  • ribbon.panel
  • ribbon.toolbar
  • rulerctrl
  • shapedbutton
  • shortcuteditor
  • speedmeter
  • supertooltip
  • thumbnailctrl
  • toasterbox
  • ultimatelistctrl
  • xlsgrid
  • zoombar

Navigation

  • index
  • modules |
  • Home |
  • Gallery |
  • Overview: module code


infobar

  • modules |
  • Home |
  • Gallery |
  • Contents»
  • Module code »
  • infobar

Source code for infobar

# --------------------------------------------------------------------------- #
# INFOBAR Control wxPython IMPLEMENTATION
# Inspired By And Heavily Based On wxInfoBar.
#
# Python Code By:
#
# Andrea Gavana, @ 12 March 2012
# Latest Revision: 12 Mar 2012, 21.00 GMT
#
#
# TODO List/Caveats
#
# 1. ?
#
#
# 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
# --------------------------------------------------------------------------- #

"""
An info bar is a transient window shown at top or bottom of its parent window to display
non-critical information to the user.

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

An info bar is a transient window shown at top or bottom of its parent window to display
non-critical information to the user.

:note:

    The Python implementation of L{InfoBar} is a direct translation of the generic C++
    implementation of `wx.InfoBar`.

This class provides another way to show messages to the user, intermediate between message
boxes and status bar messages. The message boxes are modal and thus interrupt the users work
flow and should be used sparingly for this reason. However status bar messages are often
too easy not to notice at all. An info bar provides a way to present the messages which has
a much higher chance to be noticed by the user but without being annoying.

Info bar may show an icon (on the left), text message and, optionally, buttons allowing the
user to react to the information presented. It always has a close button at the right allowing
the user to dismiss it so it isn't necessary to provide a button just to close it.

L{InfoBar} calls its parent `Layout()` method (if its parent is **not** managed by L{AuiManager}
or `wx.aui.AuiManager`) and assumes that it will change the parent layout appropriately depending
on whether the info bar itself is shown or hidden. Usually this is achieved by simply using a
sizer for the parent window layout and adding wxInfoBar to this sizer as one of the items.
Considering the usual placement of the info bars, normally this sizer should be a vertical
`wx.BoxSizer` and the bar its first or last element.

Base Functionalities
====================

L{InfoBar} supports all the `wx.InfoBar` generic implementation functionalities, and in addition
it using L{AddButton} it is possible to add a button with a bitmap (and not only a plain `wx.Button`).

For example::

    info = InfoBar(parent)
    bitmap = wx.Bitmap('nice_bitmap.png', wx.BITMAP_TYPE_PNG)

    info.AddButton(wx.NewId(), 'New Button', bitmap)

Usage
=====

The simplest possible example of using this class would be::

    import wx
    import wx.lib.agw.infobar as IB

    class MyFrame(wx.Frame):

        def __init__(self, parent):

            wx.Frame.__init__(self, parent, -1, 'InfoBar Demo')

            self._infoBar = IB.InfoBar(self)

            sizer = wx.BoxSizer(wx.VERTICAL)
            sizer.AddF(self._infoBar, wx.SizerFlags().Expand())

            panel = wx.Panel(self)
            sizer.Add(panel, 1, wx.EXPAND)

            # ... Add other frame controls to the sizer ...
            self.SetSizer(sizer)

            wx.CallLater(2000, self.SomeMethod)

        def SomeMethod(self):

            self._infoBar.ShowMessage("Something happened", wx.ICON_INFORMATION)

    # our normal wxApp-derived class, as usual

    app = wx.PySimpleApp()

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

    app.MainLoop()

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

L{InfoBar} has been tested on the following platforms:
  * Windows (Vista/7).

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 `wx.wxEVT_COMMAND_BUTTON_CLICKED` event, when the button is clicked.
================= ==================================================

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

L{InfoBar} control is distributed under the wxPython license.

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

Version 0.1

"""

# Version Info
__version__ = "0.1"

# Start the imports
import wx

# These two are needed only to check if the InfoBar parent
# is managed by PyAUI or wx.aui, in which case the handling
# of the showing/dismissing is done a bit differently
import wx.aui
import aui.framemanager as framemanager

# Get the translation function
_ = wx.GetTranslation

# Determine the placement of the bar from its position in the containing
# sizer
BarPlacement_Unknown = 0
""" Unknown L{InfoBar} placement (not good). """
BarPlacement_Top     = 1
""" L{InfoBar} is placed at the top of its parent. """
BarPlacement_Bottom  = 2
""" L{InfoBar} is placed at the bottom of its parent. """

# This dictionary is here because wx.ArtProvider.GetMessageBoxIconId(flags)
# doesn't do what I think it should do in wxPython
FLAGS2ART = {wx.ICON_NONE        : wx.ART_MISSING_IMAGE,
             wx.ICON_INFORMATION : wx.ART_INFORMATION,
             wx.ICON_QUESTION    : wx.ART_QUESTION,
             wx.ICON_WARNING     : wx.ART_WARNING,
             wx.ICON_ERROR       : wx.ART_ERROR
             }

# ----------------------------------------------------------------------------
# Local helpers
# ----------------------------------------------------------------------------

[docs]def GetCloseButtonBitmap(win, size, colBg, flags=0):
    """
    For platforms supporting it (namely wxMSW and wxMAC), this method uses `wx.RendererNative`
    to draw a natively-looking close button on the L{InfoBar} itself.

    :param `win`: the window in which we wish to draw the close button (an instance of
     L{InfoBar});
    :param tuple `size`: the close button size, a tuple of `(width, height)` dimensions in pixels;
    :param `colBg`: the background colour of the parent window, an instance of `wx.Colour`;
    :param integer `flags`: may have the ``wx.CONTROL_PRESSED``, ``wx.CONTROL_CURRENT`` or
     ``wx.CONTROL_ISDEFAULT`` bit set.
    """

    bmp = wx.EmptyBitmap(*size)
    dc = wx.MemoryDC()
    dc.SelectObject(bmp)
    dc.SetBackground(wx.Brush(colBg))
    dc.Clear()

    wx.RendererNative.Get().DrawTitleBarBitmap(win, dc, wx.RectS(size), wx.TITLEBAR_BUTTON_CLOSE, flags)
    dc.SelectObject(wx.NullBitmap)

    return bmp

# ============================================================================
# Implementation
# ============================================================================

[docs]class InfoBar(wx.PyControl):
    """
    An info bar is a transient window shown at top or bottom of its parent window to display
    non-critical information to the user.

    This is the main class implementation, plainly translated from C++.
    """

[docs]    def __init__(self, parent, id=wx.ID_ANY, pos=wx.DefaultPosition, size=wx.DefaultSize,
                 style=0, name='InfoBar'):
        """
        Default class constructor.

        :param `parent`: parent window. Must not be ``None``;
        :param integer `id`: window identifier. A value of -1 indicates a default value;
        :param `pos`: the control position. A value of (-1, -1) indicates a default position,
         chosen by either the windowing system or wxPython, depending on platform;
        :type `pos`: tuple or `wx.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 `wx.Size`
        :param integer `style`: the L{InfoBar} style (unused at present);
        :param string `name`: the control name.
        """

        wx.PyControl.__init__(self, parent, id, pos, size, style|wx.BORDER_NONE, name=name)

        self.SetInitialSize(size)
        self.Init()

        # calling Hide() before Create() ensures that we're created initially
        # hidden
        self.Hide()

        # use special, easy to notice, colours
        colBg = wx.SystemSettings.GetColour(wx.SYS_COLOUR_INFOBK)
        self.SetBackgroundColour(colBg)
        self.SetOwnForegroundColour(wx.SystemSettings.GetColour(wx.SYS_COLOUR_INFOTEXT))

        # create the controls: icon,text and the button to dismiss the
        # message.

        # the icon is not shown unless it's assigned a valid bitmap
        self._icon = wx.StaticBitmap(self, wx.ID_ANY, wx.NullBitmap)
        self._text = wx.StaticText(self, wx.ID_ANY, "")

        if wx.Platform == '__WXGTK__':
            bmp = wx.ArtProvider.GetBitmap(wx.ART_CLOSE, wx.ART_BUTTON)
        else:
            # THIS CRASHES PYTHON ALTOGETHER!!
            # sizeBmp = wx.ArtProvider.GetSizeHint(wx.ART_BUTTON)
            sizeBmp = (16, 16)
            bmp = GetCloseButtonBitmap(self, sizeBmp, colBg)

        self._button = wx.BitmapButton(self, wx.ID_ANY, bmp, style=wx.BORDER_NONE)

        if wx.Platform != '__WXGTK__':
            self._button.SetBitmapPressed(GetCloseButtonBitmap(self, sizeBmp, colBg, wx.CONTROL_PRESSED))
            self._button.SetBitmapCurrent(GetCloseButtonBitmap(self, sizeBmp, colBg, wx.CONTROL_CURRENT))

        self._button.SetBackgroundColour(colBg)
        self._button.SetToolTipString(_("Hide this notification message."))

        # center the text inside the sizer with an icon to the left of it and a
        # button at the very right
        #
        # NB: AddButton() relies on the button being the last control in the sizer
        #     and being preceded by a spacer
        sizer = wx.BoxSizer(wx.HORIZONTAL)
        sizer.AddF(self._icon, wx.SizerFlags().Centre().Border())
        sizer.AddF(self._text, wx.SizerFlags().Centre())
        sizer.AddStretchSpacer()
        sizer.AddF(self._button, wx.SizerFlags().Centre().Border())
        self.SetSizer(sizer)

        self.Bind(wx.EVT_BUTTON, self.OnButton)

[docs]    def Init(self):
        """ Common initialization code. """

        self._icon = None
        self._text = None
        self._button = None
        self._showEffect = wx.SHOW_EFFECT_MAX
        self._hideEffect = wx.SHOW_EFFECT_MAX

        # use default effect duration
        self._effectDuration = 0

[docs]    def SetFont(self, font):
        """
        Overridden base class methods changes the font of the text message.

        L{InfoBar} overrides this method to use the font passed to it for its text
        message part. By default a larger and bold version of the standard font is used.

        :param `font`: a valid instance of `wx.Font`.

        :note: Reimplemented from `wx.Window`.
        """

        if not wx.PyControl.SetFont(self, font):
            return False

        # check that we're not called before Create()
        if self._text:
            self._text.SetFont(font)

        return True

[docs]    def GetBarPlacement(self):
        """
        Determines the placement of the bar from its position in the containing
        sizer.

        :return: One of these integer bits:

         ========================== =========== ==================================================
         Placement Flag             Hex Value   Description
         ========================== =========== ==================================================
         ``BarPlacement_Unknown``           0x0 Unknown placement of L{InfoBar} (not good).
         ``BarPlacement_Top``               0x1 L{InfoBar} is placed at the top of its parent.
         ``BarPlacement_Bottom``            0x2 L{InfoBar} is placed at the bottom of its parent.
         ========================== =========== ==================================================

        """

        sizer = self.GetContainingSizer()

        if not sizer:
            return BarPlacement_Unknown

        siblings = sizer.GetChildren()

        if siblings[0].GetWindow() == self:
            return BarPlacement_Top
        elif siblings[-1].GetWindow()== self:
            return BarPlacement_Bottom
        else:
            return BarPlacement_Unknown

[docs]    def GetShowEffect(self):
        """
        Return the effect currently used for showing the bar.

        :return: One of the following integer bits:

         ================================== =========== ==================================================
         `ShowEffect` Flag                  Hex Value   Description
         ================================== =========== ==================================================
         ``wx.SHOW_EFFECT_NONE``                    0x0 No effect, equivalent to normal `Show()` or `Hide()` call.
         ``wx.SHOW_EFFECT_SLIDE_TO_TOP``            0x7 Slide the L{InfoBar} window to the top.
         ``wx.SHOW_EFFECT_SLIDE_TO_BOTTOM``         0x8 Slide the L{InfoBar} window to the bottom.
         ================================== =========== ==================================================

        """

        if self._showEffect != wx.SHOW_EFFECT_MAX:
            return self._showEffect

        placement = self.GetBarPlacement()

        if placement == BarPlacement_Top:
            return wx.SHOW_EFFECT_SLIDE_TO_BOTTOM

        elif placement == BarPlacement_Bottom:
            return wx.SHOW_EFFECT_SLIDE_TO_TOP

        elif placement == BarPlacement_Unknown:
            return wx.SHOW_EFFECT_NONE

        else:
            raise Exception("unknown info bar placement")

[docs]    def GetHideEffect(self):
        """
        Return the effect currently used for hiding the bar.

        :return: One of the following integer bits:

         ================================== =========== ==================================================
         `ShowEffect` Flag                  Hex Value   Description
         ================================== =========== ==================================================
         ``wx.SHOW_EFFECT_NONE``                    0x0 No effect, equivalent to normal `Show()` or `Hide()` call.
         ``wx.SHOW_EFFECT_SLIDE_TO_TOP``            0x7 Slide the L{InfoBar} window to the top.
         ``wx.SHOW_EFFECT_SLIDE_TO_BOTTOM``         0x8 Slide the L{InfoBar} window to the bottom.
         ================================== =========== ==================================================

        """

        if self._hideEffect != wx.SHOW_EFFECT_MAX:
            return self._hideEffect

        placement = self.GetBarPlacement()

        if placement == BarPlacement_Top:
            return wx.SHOW_EFFECT_SLIDE_TO_TOP

        elif placement == BarPlacement_Bottom:
            return wx.SHOW_EFFECT_SLIDE_TO_BOTTOM

        elif placement == BarPlacement_Unknown:
            return wx.SHOW_EFFECT_NONE

        else:
            raise Exception("unknown info bar placement")

[docs]    def GetDefaultBorder(self):
        """ Returns the default border style for L{InfoBar}. """

        return wx.BORDER_NONE

[docs]    def UpdateParent(self):
        """
        Updates the parent layout appearance, but only if this L{InfoBar} parent is **not** managed
        by L{AuiManager} or `wx.aui.AuiManager`.
        """

        parent = self.GetParent()
        parent.Layout()

[docs]    def DoHide(self):
        """ Hides this L{InfoBar} with whatever hiding effect has been chosen. """

        self.HideWithEffect(self.GetHideEffect(), self.GetEffectDuration())

        handler = self.GetParent().GetEventHandler()
        managers = (framemanager.AuiManager, wx.aui.AuiManager)

        if not isinstance(handler, managers):
            self.UpdateParent()
        else:
            pane = handler.GetPane(self)
            pane.Show(False)
            handler.Update()

[docs]    def DoShow(self):
        """ Shows this L{InfoBar} with whatever showing effect has been chosen. """

        # re-layout the parent first so that the window expands into an already
        # unoccupied by the other controls area: for this we need to change our
        # internal visibility flag to force Layout() to take us into account(an
        # alternative solution to this hack would be to temporarily set
        # wx.RESERVE_SPACE_EVEN_IF_HIDDEN flag but it's not really better)

        # just change the internal flag indicating that the window is visible,
        # without really showing it
        self.GetParent().Freeze()

        wx.PyControl.Show(self)

        # adjust the parent layout to account for us
        self.UpdateParent()

        # reset the flag back before really showing the window or it wouldn't be
        # shown at all because it would believe itself already visible
        wx.PyControl.Show(self, False)
        self.GetParent().Thaw()

        # finally do really show the window.
        self.ShowWithEffect(self.GetShowEffect(), self.GetEffectDuration())

        handler = self.GetParent().GetEventHandler()
        managers = (framemanager.AuiManager, wx.aui.AuiManager)

        if isinstance(handler, managers):
            pane = handler.GetPane(self)
            pane.Show(True)
            handler.Update()

[docs]    def ShowMessage(self, msg, flags=wx.ICON_INFORMATION):
        """
        Show a message in the bar.

        If the bar is currently hidden, it will be shown. Otherwise its message will be updated in place.

        :param string `msg`: the text of the message;
        :param integer `flags`: one of ``wx.ICON_NONE``, ``wx.ICON_INFORMATION`` (default), ``wx.ICON_QUESTION``,
         ``wx.ICON_WARNING`` or ``wx.ICON_ERROR`` values.

         :note: These flags have the same meaning as in `wx.MessageDialog` for the generic version, i.e.
          show (or not, in case of ``wx.ICON_NONE``) the corresponding icon in the bar but can be interpreted
          by the native versions. For example, the GTK+ native implementation doesn't show icons at all but
          uses this parameter to select the appropriate background colour for the notification.
        """

        # first update the controls
        icon = flags & wx.ICON_MASK

        if not icon or icon == wx.ICON_NONE:
            self._icon.Hide()

        else: # do show an icon
            self._icon.SetBitmap(wx.ArtProvider.GetBitmap(FLAGS2ART[flags], wx.ART_BUTTON))
            self._icon.Show()

        # notice the use of EscapeMnemonics() to ensure that "&" come through
        # correctly
        self._text.SetLabel(wx.PyControl.EscapeMnemonics(msg))

        # then show this entire window if not done yet
        if not self.IsShown():
            self.DoShow()
        else: # we're already shown
            # just update the layout to correspond to the new message
            self.Layout()

[docs]    def Dismiss(self):
        """
        Hides the L{InfoBar} window.

        This method hides the window and lays out the parent window to account for
        its disappearance (unlike a simple `Hide()`), but only if this L{InfoBar}
        parent is **not** managed by L{AuiManager} or `wx.aui.AuiManager`.
        """

        self.DoHide()

[docs]    def AddButton(self, btnid, label, bitmap=wx.NullBitmap):
        """
        Adds a button to be shown in the info bar.

        The button added by this method will be shown to the right of the text (in LTR layout),
        with each successive button being added to the right of the previous one. If any buttons
        are added to the info bar using this method, the default `Close` button is not shown
        as it is assumed that the extra buttons already allow the user to close it.

        Clicking the button will generate a normal ``wx.wxEVT_COMMAND_BUTTON_CLICKED`` event which
        can be handled as usual. The default handler in L{InfoBar} itself closes the window
        whenever a button in it is clicked so if you wish the info bar to be hidden when the button
        is clicked, simply call `event.Skip()` in the button handler to let the base class handler
        do it (calling L{Dismiss} explicitly works too, of course). On the other hand, if you don't
        skip the event, the info bar will remain opened so make sure to do it for at least some
        buttons to allow the user to close it.

        :param integer `btnid`: id of the button. It will be used in the button message clicking
         this button will generate;
        :param string `label`: the label of the button. It may only be empty if `btnid` is one of
         the stock ids in which case the corresponding stock label will be used;
        :param `bitmap`: if not equal to `wx.NullBitmap`, a valid `wx.Bitmap` image to show beside
         the button text.

        :note:

             Notice that the generic L{InfoBar} implementation handles the button events itself
             and so they are not propagated to the info bar parent and you need to either inherit from
             L{InfoBar} and handle them in your derived class or use `self.Bind(...)` to handle the
             button events in the parent frame.

        """

        sizer = self.GetSizer()

        if not sizer:
            raise Exception("must be created first")

        # user-added buttons replace the standard close button so remove it if we
        # hadn't done it yet
        if sizer.Detach(self._button):
            self._button.Hide()

        button = wx.Button(self, btnid, label)

        if bitmap.IsOk():
            # Add the bitmap to the button
            button.SetBitmap(bitmap, wx.LEFT)
            button.SetBitmapMargins((2, 2)) # default is 4 but that seems too big to me.

        if wx.Platform == '__WXMAC__':
            # smaller buttons look better in the(narrow)info bar under OS X
            button.SetWindowVariant(wx.WINDOW_VARIANT_SMALL)

        sizer.AddF(button, wx.SizerFlags().Centre().DoubleBorder())

        if self.IsShown():
            self.UpdateParent()

[docs]    def RemoveButton(self, btnid):
        """
        Remove a button previously added by L{AddButton}.

        :param integer `btnid`: id of the button to remove. If more than one button with the
         same id is used in the L{InfoBar} (which is in any case not recommended), the last,
         i.e. most recently added, button with this `id` is removed.
        """

        sizer = self.GetSizer()

        if not sizer:
            raise Exception("must be created first")

        # iterate over the sizer items in reverse order to find the last added
        # button with this id(ids of all buttons should be unique anyhow but if
        # they are repeated removing the last added one probably makes more sense)
        items = sizer.GetChildren()

        for item in items[::-1]:
            # if we reached the spacer separating the buttons from the text
            # preceding them without finding our button,it must mean it's not
            # there at all
            if item.IsSpacer():
                raise Exception("button with id %d not found"%btnid)

            # check if we found our button
            if item.GetWindow().GetId() == btnid:
                sizer.Detach(item)
                item.GetWindow().Destroy()
                break

        # check if there are any custom buttons left
        if sizer.GetChildren()[-1].IsSpacer():
            # if the last item is the spacer,none are left so restore the
            # standard close button
            sizer.Add(self._button, wx.SizerFlags().Centre().DoubleBorder())
            self._button.Show()

[docs]    def OnButton(self, event):
        """
        Default event handler for the `Close` button in L{InfoBar}.

        :param `event`: a `wx.CommandEvent` to be processed.

        :note:

             Notice that the generic L{InfoBar} implementation handles the button events itself
             and so they are not propagated to the info bar parent and you need to either inherit from
             L{InfoBar} and handle them in your derived class or use `self.Bind(...)` to handle the
             button events in the parent frame.
        """

        self.DoHide()

[docs]    def SetShowHideEffects(self, showEffect, hideEffect):
        """
        Set the effects to use when showing and hiding the bar.

        Either or both of the parameters can be set to ``wx.SHOW_EFFECT_NONE`` to disable using
        effects entirely.

        By default, the info bar uses ``wx.SHOW_EFFECT_SLIDE_TO_BOTTOM`` effect for showing itself
        and ``wx.SHOW_EFFECT_SLIDE_TO_TOP`` for hiding if it is the first element of the containing
        sizer and reverse effects if it's the last one. If it is neither the first nor the last element,
        no effect is used to avoid the use of an inappropriate one and this function must be called
        if an effect is desired.

        :param integer `showEffect`: the effect to use when showing the bar;
        :param integer `hideEffect`: the effect to use when hiding the bar.

        The `showEffect` and `hideEffect` parameters can take one of the following bit:

        ==================================== ===========================================================
        `ShowEffect` Flag                    Description
        ==================================== ===========================================================
        ``SHOW_EFFECT_NONE``                 No effect, equivalent to normal `Show()` or `Hide()` call.
        ``SHOW_EFFECT_ROLL_TO_LEFT``         Roll window to the left.
        ``SHOW_EFFECT_ROLL_TO_RIGHT``        Roll window to the right.
        ``SHOW_EFFECT_ROLL_TO_TOP``          Roll window to the top.
        ``SHOW_EFFECT_ROLL_TO_BOTTOM``       Roll window to the bottom.
        ``SHOW_EFFECT_SLIDE_TO_LEFT``        Slide window to the left.
        ``SHOW_EFFECT_SLIDE_TO_RIGHT``       Slide window to the right.
        ``SHOW_EFFECT_SLIDE_TO_TOP``         Slide window to the top.
        ``SHOW_EFFECT_SLIDE_TO_BOTTOM``      Slide window to the bottom.
        ``SHOW_EFFECT_BLEND``                Fade in or out effect.
        ``SHOW_EFFECT_EXPAND``               Expanding or collapsing effect.
        ==================================== ===========================================================

        """

        self._showEffect = showEffect
        self._hideEffect = hideEffect

[docs]    def SetEffectDuration(self, duration):
        """
        Sets the duration of the animation used when showing or hiding the bar.

        By default, 500ms duration is used.

        :param integer `duration`: duration of the animation, in milliseconds.
        """

        self._effectDuration = duration

[docs]    def GetEffectDuration(self):
        """ Return the effect animation duration currently used, in milliseconds. """

        return self._effectDuration

Navigation

  • index
  • modules |
  • Home |
  • Gallery |
  • Contents»
  • Module code »
  • infobar


knobctrl

  • modules |
  • Home |
  • Gallery |
  • Contents»
  • Module code »
  • knobctrl

Source code for knobctrl

# --------------------------------------------------------------------------------- #
# KNOBCTRL wxPython IMPLEMENTATION
#
# Andrea Gavana, @ 03 Nov 2006
# Latest Revision: 17 Aug 2011, 15.00 GMT
#
#
# TODO List
#
# 1. Any idea?
#
# For All Kind Of Problems, Requests Of Enhancements And Bug Reports, Please
# Write To Me At:
#
# andrea.gavana@maerskoil.com
# andrea.gavana@gmail.com
#
# Or, Obviously, To The wxPython Mailing List!!!
#
#
# End Of Comments
# --------------------------------------------------------------------------------- #

"""
L{KnobCtrl} lets the user select a numerical value by rotating it.

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

L{KnobCtrl} lets the user select a numerical value by rotating it. It works like a
scrollbar: just set the ticks range property and read the value property in the
associated ``EVT_KC_ANGLE_CHANGING``/``EVT_KC_ANGLE_CHANGED`` events. Simple but
effective.

It can be easily used if you want to simulate the volume knob of a music player
or similar functionalities.

Usage
=====

Usage example::

    import wx
    import wx.lib.agw.knobctrl as KC

    class MyFrame(wx.Frame):

        def __init__(self, parent):

            wx.Frame.__init__(self, parent, -1, "KnobCtrl Demo")

            panel = wx.Panel(self)

            knob1 = KC.KnobCtrl(panel, -1, size=(100, 100))
            knob2 = KC.KnobCtrl(panel, -1, size=(100, 100))

            knob1.SetTags(range(0, 151, 10))
            knob1.SetAngularRange(-45, 225)
            knob1.SetValue(45)

            knob2.SetTags(range(0, 151, 10))
            knob2.SetAngularRange(0, 270)
            knob2.SetValue(100)

            main_sizer = wx.BoxSizer(wx.VERTICAL)
            main_sizer.Add(knob1, 0, wx.EXPAND|wx.ALL, 20)
            main_sizer.Add(knob2, 0, wx.EXPAND|wx.ALL, 20)

            panel.SetSizer(main_sizer)
            main_sizer.Layout()

    # our normal wxApp-derived class, as usual

    app = wx.PySimpleApp()

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

    app.MainLoop()

Events
======

L{KnobCtrl} implements two events that can be intercepted by the user:

- ``EVT_KC_ANGLE_CHANGING``;
- ``EVT_KC_ANGLE_CHANGED``.

The first one can be "vetoed" by eliminating the `event.Skip()` at the end of the
event handler.

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

L{KnobCtrl} has been tested on the following platforms:
  * Windows (Windows XP);
  * Linux Ubuntu (Dapper 6.06)

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

This class supports the following window styles:

================== =========== ==================================================
Window Styles      Hex Value   Description
================== =========== ==================================================
``KC_BUFFERED_DC``         0x1 Flag to use double buffering (recommendeded = 1).
================== =========== ==================================================

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

This class processes the following events:

========================= ==================================================
Event Name                Description
========================= ==================================================
``EVT_KC_ANGLE_CHANGED``  Notify the client that the knob has changed its value.
``EVT_KC_ANGLE_CHANGING`` Notify the client that the knob is changing its value.
========================= ==================================================

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

L{KnobCtrl} is distributed under the wxPython license.

Latest Revision: Andrea Gavana @ 17 Aug 2011, 15.00 GMT

Version 0.3

"""

__docformat__ = "epytext"

import wx
import math

# Flag to use double buffering (recommendeded = 1)
KC_BUFFERED_DC = 1
"""Flag to use double buffering (recommendeded = 1)"""

# Events
wxEVT_KC_ANGLE_CHANGING = wx.NewEventType()
wxEVT_KC_ANGLE_CHANGED = wx.NewEventType()

EVT_KC_ANGLE_CHANGING = wx.PyEventBinder(wxEVT_KC_ANGLE_CHANGING, 1)
""" Notify the client that the knob is changing its value."""
EVT_KC_ANGLE_CHANGED = wx.PyEventBinder(wxEVT_KC_ANGLE_CHANGED, 1)
""" Notify the client that the knob has changed its value."""

# ---------------------------------------------------------------------------- #
# Class KnobCtrlEvent
# ---------------------------------------------------------------------------- #

[docs]class KnobCtrlEvent(wx.PyCommandEvent):
    """
    Represent details of the events that the L{KnobCtrl} object sends.
    """

[docs]    def __init__(self, eventType, eventId=1):
        """
        Default class constructor.
        For internal use: do not call it in your code!

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

        wx.PyCommandEvent.__init__(self, eventType, eventId)

[docs]    def SetOldValue(self, oldValue):
        """
        Sets the old L{KnobCtrl} value for this event.

        :param `oldValue`: an integer representing the old value.
        """

        self._oldValue = oldValue

[docs]    def GetOldValue(self):
        """ Returns the old L{KnobCtrl} value for this event. """

        return self._oldValue

[docs]    def SetValue(self, value):
        """
        Sets the new L{KnobCtrl} value for this event.

        :param `value`: an integer representing the new value.
        """

        self._value = value

[docs]    def GetValue(self):
        """ Returns the new L{KnobCtrl} value for this event. """

        return self._value

#----------------------------------------------------------------------
# BUFFERENDWINDOW Class
# This Class Has Been Taken From The wxPython Wiki, And Slightly
# Adapted To Fill My Needs. See:
#
# http://wiki.wxpython.org/index.cgi/DoubleBufferedDrawing
#
# For More Info About DC And Double Buffered Drawing.
#----------------------------------------------------------------------

[docs]class BufferedWindow(wx.Window):
    """
    A Buffered window class.

    To use it, subclass it and define a `Draw(dc)` method that takes a `dc`
    to draw to. In that method, put the code needed to draw the picture
    you want. The window will automatically be double buffered, and the
    screen will be automatically updated when a Paint event is received.

    When the drawing needs to change, you app needs to call the
    L{BufferedWindow.UpdateDrawing} method. Since the drawing is stored in a bitmap, you
    can also save the drawing to file by calling the
    `SaveToFile(self, file_name, file_type)` method.
    """

[docs]    def __init__(self, parent, id=wx.ID_ANY, pos=wx.DefaultPosition, size=wx.DefaultSize,
                 style=wx.NO_FULL_REPAINT_ON_RESIZE, agwStyle=KC_BUFFERED_DC):
        """
        Default class constructor.

        :param `parent`: parent window. Must not be ``None``;
        :param `id`: window identifier. A value of -1 indicates a default value;
        :param `pos`: the control position. A value of (-1, -1) indicates a default position,
         chosen by either the windowing system or wxPython, depending on platform;
        :param `size`: the control size. A value of (-1, -1) indicates a default size,
         chosen by either the windowing system or wxPython, depending on platform;
        :param `style`: the window style;
        :param `agwStyle`: if set to ``KC_BUFFERED_DC``, double-buffering will
         be used.
        """

        wx.Window.__init__(self, parent, id, pos, size, style)

        self.Bind(wx.EVT_PAINT, self.OnPaint)
        self.Bind(wx.EVT_SIZE, self.OnSize)
        self.Bind(wx.EVT_ERASE_BACKGROUND, lambda x: None)

        # OnSize called to make sure the buffer is initialized.
        # This might result in OnSize getting called twice on some
        # platforms at initialization, but little harm done.
        self.OnSize(None)

[docs]    def Draw(self, dc):
        """
        This method should be overridden when sub-classed.

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

        pass

[docs]    def OnPaint(self, event):
        """
        Handles the ``wx.EVT_PAINT`` event for L{BufferedWindow}.

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

        # All that is needed here is to draw the buffer to screen
        if self._agwStyle == KC_BUFFERED_DC:
            dc = wx.BufferedPaintDC(self, self._Buffer)
        else:
            dc = wx.PaintDC(self)
            dc.DrawBitmap(self._Buffer,0,0)

[docs]    def OnSize(self,event):
        """
        Handles the ``wx.EVT_SIZE`` event for L{BufferedWindow}.

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

        # The Buffer init is done here, to make sure the buffer is always
        # the same size as the Window
        self.Width, self.Height = self.GetClientSizeTuple()

        # Make new off screen bitmap: this bitmap will always have the
        # current drawing in it, so it can be used to save the image to
        # a file, or whatever.

        # This seems required on MacOS, it doesn't like wx.EmptyBitmap with
        # size = (0, 0)
        # Thanks to Gerard Grazzini

        if "__WXMAC__" in wx.Platform:
            if self.Width == 0:
                self.Width = 1
            if self.Height == 0:
                self.Height = 1

        self._Buffer = wx.EmptyBitmap(self.Width, self.Height)

        memory = wx.MemoryDC()
        memory.SelectObject(self._Buffer)
        memory.SetBackground(wx.Brush(self.GetBackgroundColour()))
        memory.SetPen(wx.TRANSPARENT_PEN)
        memory.Clear()

        minradius = min(0.9*self.Width/2, 0.9*self.Height/2)
        memory.DrawCircle(self.Width/2, self.Height/2, minradius)
        memory.SelectObject(wx.NullBitmap)
        self._region = wx.RegionFromBitmapColour(self._Buffer, self.GetBackgroundColour())
        self._minradius = minradius

        self.UpdateDrawing()

[docs]    def UpdateDrawing(self):
        """
        This would get called if the drawing needed to change, for whatever reason.

        The idea here is that the drawing is based on some data generated
        elsewhere in the system. If that data changes, the drawing needs to
        be updated.
        """

        if self._agwStyle == KC_BUFFERED_DC:
            dc = wx.BufferedDC(wx.ClientDC(self), self._Buffer)
            self.Draw(dc)
        else:
            # update the buffer
            dc = wx.MemoryDC()
            dc.SelectObject(self._Buffer)

            self.Draw(dc)
            # update the screen
            wx.ClientDC(self).Blit(0, 0, self.Width, self.Height, dc, 0, 0)

# ---------------------------------------------------------------------------- #
# Class KnobCtrl
# ---------------------------------------------------------------------------- #

[docs]class KnobCtrl(BufferedWindow):
    """
    This class can be used to simulate a knob volume control often found in
    PC music players.
    """

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

        :param `parent`: parent window. Must not be ``None``;
        :param `id`: window identifier. A value of -1 indicates a default value;
        :param `pos`: the control position. A value of (-1, -1) indicates a default position,
         chosen by either the windowing system or wxPython, depending on platform;
        :param `size`: the control size. A value of (-1, -1) indicates a default size,
         chosen by either the windowing system or wxPython, depending on platform;
        :param `style`: the window style;
        :param `agwStyle`: if set to ``KC_BUFFERED_DC``, double-buffering will
         be used.
        """

        self._agwStyle = agwStyle
        self._knobcolour = wx.SystemSettings_GetColour(wx.SYS_COLOUR_3DFACE)

        self._startcolour = wx.WHITE
        self._endcolour = wx.Colour(170, 170, 150)
        self._tagscolour = wx.BLACK
        self._boundingcolour = wx.WHITE
        self._tags = []
        self._anglestart = -45
        self._angleend = 180
        self._state = 0
        self._minvalue = 0
        self._maxvalue = 100
        self._old_ang = 0
        self._trackposition = 0
        self._knobradius = 4

        BufferedWindow.__init__(self, parent, id, pos, size,
                                style=wx.NO_FULL_REPAINT_ON_RESIZE,
                                agwStyle=agwStyle)

        self.Bind(wx.EVT_MOUSE_EVENTS, self.OnMouseEvents)
        self.SetValue(self._trackposition)

[docs]    def OnMouseEvents(self, event):
        """
        Handles the ``wx.EVT_MOUSE_EVENTS`` event for L{KnobCtrl}.

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

        if self._state == 0 and event.Entering():
            self._state = 1
        elif self._state >= 1 and event.Leaving():
            self._state = 0
        elif self._state == 1 and event.LeftDown():
            self._state = 2
            self._mousePosition = event.GetPosition()
            self.SetTrackPosition()
        elif self._state == 2 and event.LeftIsDown():
            self._mousePosition = event.GetPosition()
            self.SetTrackPosition()
        elif self._state == 2 and event.LeftUp():
            self._state = 1

[docs]    def SetTags(self, tags):
        """
        Sets the tags for L{KnobCtrl}.

        :param `tags`: a list of integers ranging from `minvalue` to `maxvalue`.
        """

        self._tags = tags
        if min(tags) < self._minvalue:
            self._minvalue = min(tags)

        if max(tags) > self._maxvalue:
            self._maxvalue = max(tags)

        self.OnSize(None)

[docs]    def GetMinValue(self):
        """ Returns the minimum value for L{KnobCtrl}. """

        return self._minvalue

[docs]    def GetMaxValue(self):
        """ Returns the maximum value for L{KnobCtrl}. """

        return self._maxvalue

[docs]    def GetKnobRadius(self):
        """ Returns the knob radius, in pixels. """

        return self._knobradius

[docs]    def SetKnobRadius(self, radius):
        """
        Sets the knob radius.

        :param `radius`: the knob radius, in pixels.
        """

        if radius <= 0:
            return

        self._knobradius = radius
        self.UpdateDrawing()

[docs]    def GetTags(self):
        """ Returns the L{KnobCtrl} tags. """

        return self._tags

[docs]    def SetTagsColour(self, colour):
        """
        Sets the tags colour.

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

        self._tagscolour = colour
        self.UpdateDrawing()

[docs]    def GetTagsColour(self):
        """ Returns the tags colour. """

        return self._tagscolour

[docs]    def SetBoundingColour(self, colour):
        """
        Sets the bounding circle colour.

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

        self._boundingcolour = colour
        self.UpdateDrawing()

[docs]    def GetBoundingColour(self):
        """ Returns the bounding circle colour. """

        return self._boundingcolour

[docs]    def SetFirstGradientColour(self, colour):
        """
        Sets the first gradient colour for shading.

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

        self._startcolour = colour
        self.UpdateDrawing()

[docs]    def GetFirstGradientColour(self):
        """ Returns the first gradient colour for shading. """

        return self._startcolour

[docs]    def SetSecondGradientColour(self, colour):
        """
        Sets the second gradient colour for shading.

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

        self._endcolour = colour
        self.UpdateDrawing()

[docs]    def GetSecondGradientColour(self):
        """ Returns the second gradient colour for shading. """

        return self._endcolour

[docs]    def SetAngularRange(self, start, end):
        """
        Sets the angular range for L{KnobCtrl}.

        :param `start`: the starting angle, in degrees, clockwise;
        :param `start`: the ending angle, in degrees, clockwise.
        """

        self._anglestart = start
        self._angleend = end
        self.UpdateDrawing()

[docs]    def GetAngularRange(self):
        """
        Returns the angular range for L{KnobCtrl} as a tuple. The `start` and `end`
        angles in the returned tuple are given in degrees, clockwise.
        """

        return self._anglestart, self._angleend

[docs]    def Draw(self, dc):
        """
        Draws everything on the empty bitmap.
        Here all the chosen styles are applied.

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

        size  = self.GetClientSize()

        if size.x < 21 or size.y < 21:
            return

        dc.SetClippingRegionAsRegion(self._region)
        self.DrawDiagonalGradient(dc, size)
        self.DrawInsetCircle(dc, self._knobcolour)
        dc.DestroyClippingRegion()
        self.DrawBoundingCircle(dc, size)

        if self._tags:
            self.DrawTags(dc, size)

[docs]    def DrawTags(self, dc, size):
        """
        Draws the tags.

        :param `dc`: an instance of `wx.DC`;
        :param `size`: the control size.
        """

        deltarange = abs(self._tags[-1] - self._tags[0])
        deltaangle = self._angleend - self._anglestart

        width = size.x
        height = size.y

        xshift = 0
        yshift = 0

        if width > height:
            xshift = width - height
        elif width < height:
            yshift = height - width

        coeff = float(deltaangle)/float(deltarange)

        dcPen = wx.Pen(self._tagscolour, 1)

        for tags in self._tags:

            if tags == self._tags[0] or tags == self._tags[-1]:
                # draw first and last tags bigger
                dcPen.SetWidth(2)
                tagLen = 8
            else:
                dcPen.SetWidth(1)
                tagLen = 6

            dc.SetPen(dcPen)

            tg = tags - self._tags[0]
            angle = tg*coeff + self._anglestart
            angle = angle*math.pi/180.0

            sxi = math.cos(angle)*(width - xshift + tagLen - 6)/2.0
            syi = math.sin(angle)*(height - yshift + tagLen - 6)/2.0

            dxi = math.cos(angle)*((width - xshift + tagLen - 6)/2.0 - tagLen)
            dyi = math.sin(angle)*((height - yshift + tagLen - 6)/2.0 - tagLen)

            dc.DrawLine(width/2 - sxi, height/2 - syi,
                        width/2 - dxi, height/2 - dyi)

[docs]    def DrawDiagonalGradient(self, dc, size):
        """
        Draw a shading of diagonal gradient to L{KnobCtrl}.

        :param `dc`: an instance of `wx.DC`;
        :param `size`: the control size.
        """

        col1 = self._startcolour
        col2 = self._endcolour

        r1, g1, b1 = int(col1.Red()), int(col1.Green()), int(col1.Blue())
        r2, g2, b2 = int(col2.Red()), int(col2.Green()), int(col2.Blue())

        maxsize = max(size.x, size.y)

        flrect = maxsize

        rstep = float((r2 - r1)) / flrect
        gstep = float((g2 - g1)) / flrect
        bstep = float((b2 - b1)) / flrect

        rf, gf, bf = 0, 0, 0
        dc.SetBrush(wx.TRANSPARENT_BRUSH)

        for ii in xrange(0, maxsize, 2):
            currCol = (r1 + rf, g1 + gf, b1 + bf)
            dc.SetPen(wx.Pen(currCol, 2))
            dc.DrawLine(0, ii+2, ii+2, 0)
            rf = rf + rstep
            gf = gf + gstep
            bf = bf + bstep

        for ii in xrange(0, maxsize, 2):
            currCol = (r1 + rf, g1 + gf, b1 + bf)
            dc.SetPen(wx.Pen(currCol, 2))
            dc.DrawLine(ii+2, maxsize, maxsize, ii+2)
            rf = rf + rstep
            gf = gf + gstep
            bf = bf + bstep

[docs]    def OffsetColour(self, colour, offset):
        """
        Changes the input colour by the `offset` value. Used internally.

        :param `colour`: a valid `wx.Colour` object;
        :param `offset`: an integer value for offsetting the input colour.
        """

        byRed = 0
        byGreen = 0
        byBlue = 0
        offsetR = offset
        offsetG = offset
        offsetB = offset

        if offset < -255 or offset> 255:
            return colour

        # Get RGB components of specified colour
        byRed = colour.Red()
        byGreen = colour.Green()
        byBlue = colour.Blue()

        # Calculate max. allowed real offset
        if offset > 0:

            if byRed + offset > 255:
                offsetR = 255 - byRed
            if byGreen + offset > 255:
                offsetG = 255 - byGreen
            if byBlue + offset > 255:
                offsetB = 255 - byBlue

            offset = min(min(offsetR, offsetG), offsetB)

        else:

            if byRed + offset < 0:
                offsetR = -byRed
            if byGreen + offset < 0:
                offsetG = -byGreen
            if byBlue + offset < 0:
                offsetB = -byBlue

            offset = max(max(offsetR, offsetG), offsetB)

        c1 = wx.Colour(byRed + offset, byGreen + offset, byBlue + offset)

        return c1

[docs]    def DrawInsetCircle(self, dc, pencolour):
        """
        Draws the small knob.

        :param `dc`: an instance of `wx.DC`;
        :param `pencolour`: the colour to use for drawing the inset circle.
        """

        self._knobcenter = self.CircleCoords(self._minradius*0.8, self.GetTrackPosition(),
                                             self.Width/2, self.Height/2)

        cx, cy = self._knobcenter
        r = self._knobradius

        p1 = wx.Pen(self.OffsetColour(pencolour, -70), 2)
        p2 = wx.Pen(self.OffsetColour(pencolour, 10), 1)

        pt1 = wx.Point(cx-r*math.sqrt(2)/2, cy+r*math.sqrt(2)/2)
        pt2 = wx.Point(cx+r*math.sqrt(2)/2, cy-r*math.sqrt(2)/2)

        dc.SetPen(p2)
        dc.DrawArcPoint(pt1, pt2, (cx, cy))
        dc.SetPen(p1)
        dc.DrawArcPoint(pt2, pt1, (cx, cy))

[docs]    def DrawBoundingCircle(self, dc, size):
        """
        Draws the L{KnobCtrl} bounding circle.

        :param `dc`: an instance of `wx.DC`;
        :param `size`: the control size.
        """

        radius = 0.9*min(size.x, size.y)/2
        dc.SetBrush(wx.TRANSPARENT_BRUSH)
        dc.SetPen(wx.Pen(self._boundingcolour))
        dc.DrawCircle(self.Width/2, self.Height/2, radius)

[docs]    def CircleCoords(self, radius, angle, centerX, centerY):
        """
        Converts the input values into logical `x` and `y` coordinates.

        :param `radius`: the L{KnobCtrl} radius;
        :param `angle`: the angular position of the mouse;
        :param `centerX`: the `x` position of the L{KnobCtrl} center;
        :param `centerX`: the `y` position of the L{KnobCtrl} center.
        """

        x = radius*math.cos(angle) + centerX
        y = radius*math.sin(angle) + centerY

        return x, y

[docs]    def SetTrackPosition(self):
        """ Used internally. """

        width, height = self.GetSize()

        x = self._mousePosition.x
        y = self._mousePosition.y

        ang = self.GetAngleFromCoord(x, y)
        val = ang*180.0/math.pi

        deltarange = self._maxvalue - self._minvalue
        deltaangle = self._angleend - self._anglestart

        coeff = float(deltaangle)/float(deltarange)

        if self._anglestart < 0 and val >= 360.0 + self._anglestart:
            scaledval = (val  - (360.0 + self._anglestart))/coeff
        else:
            scaledval = (val  - self._anglestart)/coeff

        if scaledval > self._maxvalue or scaledval < self._minvalue:
            ang = self._old_ang
        else:
            event = KnobCtrlEvent(wxEVT_KC_ANGLE_CHANGING, self.GetId())
            event.SetEventObject(self)
            event.SetOldValue(self.GetValue())
            event.SetValue(int(round(scaledval)))

            if self.GetEventHandler().ProcessEvent(event):
                # the caller didn't use event.Skip()
                return

            self.SetValue(scaledval)
            event.SetEventType(wxEVT_KC_ANGLE_CHANGED)
            event.SetOldValue(scaledval)
            self.GetEventHandler().ProcessEvent(event)

        self._old_ang = ang

[docs]    def SetValue(self, val):
        """
        Sets programmatically the value of L{KnobCtrl}.

        :param `val`: an integer specifying the new L{KnobCtrl} value.

        :note: This method does not send a L{KnobCtrlEvent}.
        """

        if val < self._minvalue or val > self._maxvalue:
            return

        width, height = self.GetSize()

        deltarange = self._maxvalue - self._minvalue
        deltaangle = self._angleend - self._anglestart

        coeff = float(deltaangle)/float(deltarange)

        ang = 360.0 + val*coeff + self._anglestart

        ang = ang*math.pi/180.0
        self._old_ang = ang

        self._trackposition = int(round(val))
        self.UpdateDrawing()

[docs]    def GetValue(self):
        """ Returns the value of L{KnobCtrl}. """

        return self._trackposition

[docs]    def GetTrackPosition(self):
        """ Used internally. """

        return self._old_ang - math.pi

[docs]    def GetAngleFromCoord(self, cx, cy):
        """
        Returns the angular position based on the input logical coordinates.
        Used internally.

        :param `cx`: the `x` logical position;
        :param `cy`: the `y` logical position.
        """

        width, height = self.GetSize()

        ang = 0
        y = (height/2 - float(cy))/(height/2)
        x = (float(cx) - width/2)/(height/2)

        ang = ang - math.atan2(-y, -x)

        if ang < 0:
            ang = ang + 2.0*math.pi

        return  ang

Navigation

  • index
  • modules |
  • Home |
  • Gallery |
  • Contents»
  • Module code »
  • knobctrl


labelbook

  • modules |
  • Home |
  • Gallery |
  • Contents»
  • Module code »
  • labelbook

Source code for labelbook

# --------------------------------------------------------------------------- #
# LABELBOOK And FLATIMAGEBOOK Widgets wxPython IMPLEMENTATION
#
# Original C++ Code From Eran, embedded in the FlatMenu source code
#
#
# License: wxWidgets license
#
#
# Python Code By:
#
# Andrea Gavana, @ 03 Nov 2006
# Latest Revision: 07 Dec 2011, 21.00 GMT
#
#
# 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!!!
#
# TODO:
# LabelBook - Support IMB_SHOW_ONLY_IMAGES
# LabelBook - An option to only draw the border
#             between the controls and the pages so the background
#             colour can flow into the window background
#
#
#
# End Of Comments
# --------------------------------------------------------------------------- #

"""
L{LabelBook} and L{FlatImageBook} are a quasi-full generic and owner-drawn
implementations of `wx.Notebook`.

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

L{LabelBook} and L{FlatImageBook} are quasi-full implementations of the `wx.Notebook`,
and designed to be a drop-in replacement for `wx.Notebook`. The API functions are
similar so one can expect the function to behave in the same way.
L{LabelBook} anf L{FlatImageBook} share their appearance with `wx.Toolbook` and
`wx.Listbook`, while having more options for custom drawings, label positioning,
mouse pointing and so on. Moreover, they retain also some visual characteristics
of the Outlook address book.

Some features:

- They are generic controls;
- Supports for left, right, top (L{FlatImageBook} only), bottom (L{FlatImageBook}
  only) book styles;
- Possibility to draw images only, text only or both (L{FlatImageBook} only);
- Support for a "pin-button", that allows the user to shrink/expand the book
  tab area;
- Shadows behind tabs (L{LabelBook} only);
- Gradient shading of the tab area (L{LabelBook} only);
- Web-like mouse pointing on tabs style (L{LabelBook} only);
- Many customizable colours (tab area, active tab text, tab borders, active
  tab, highlight) - L{LabelBook} only.

And much more. See the demo for a quasi-complete review of all the functionalities
of L{LabelBook} and L{FlatImageBook}.

Usage
=====

Usage example::

    import wx
    import wx.lib.agw.labelbook as LB

    class MyFrame(wx.Frame):

        def __init__(self, parent):

            wx.Frame.__init__(self, parent, -1, "LabelBook Demo")

            # Possible values for Tab placement are INB_TOP, INB_BOTTOM, INB_RIGHT, INB_LEFT

            notebook = LB.LabelBook(self, -1, agwStyle=LB.INB_FIT_LABELTEXT|LB.INB_LEFT|LB.INB_DRAW_SHADOW|LB.INB_GRADIENT_BACKGROUND)

            pane1 = wx.Panel(notebook)
            pane2 = wx.Panel(notebook)

            imagelist = wx.ImageList(32, 32)
            imagelist.Add(wx.Bitmap("my_bitmap.png", wx.BITMAP_TYPE_PNG))
            notebook.AssignImageList(imagelist)

            notebook.AddPage(pane_1, "Tab1", 1, 0)
            notebook.AddPage(pane_2, "Tab2", 0, 0)

    # our normal wxApp-derived class, as usual

    app = wx.PySimpleApp()

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

    app.MainLoop()

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

L{LabelBook} and L{FlatImageBook} have been tested on the following platforms:
  * Windows (Windows XP);
  * Linux Ubuntu (Dapper 6.06)

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

This class supports the following window styles:

=========================== =========== ==================================================
Window Styles               Hex Value   Description
=========================== =========== ==================================================
``INB_BOTTOM``                      0x1 Place labels below the page area. Available only for L{FlatImageBook}.
``INB_LEFT``                        0x2 Place labels on the left side. Available only for L{FlatImageBook}.
``INB_RIGHT``                       0x4 Place labels on the right side.
``INB_TOP``                         0x8 Place labels above the page area.
``INB_BORDER``                     0x10 Draws a border around L{LabelBook} or L{FlatImageBook}.
``INB_SHOW_ONLY_TEXT``             0x20 Shows only text labels and no images. Available only for L{LabelBook}.
``INB_SHOW_ONLY_IMAGES``           0x40 Shows only tab images and no label texts. Available only for L{LabelBook}.
``INB_FIT_BUTTON``                 0x80 Displays a pin button to show/hide the book control.
``INB_DRAW_SHADOW``               0x100 Draw shadows below the book tabs. Available only for L{LabelBook}.
``INB_USE_PIN_BUTTON``            0x200 Displays a pin button to show/hide the book control.
``INB_GRADIENT_BACKGROUND``       0x400 Draws a gradient shading on the tabs background. Available only for L{LabelBook}.
``INB_WEB_HILITE``                0x800 On mouse hovering, tabs behave like html hyperlinks. Available only for L{LabelBook}.
``INB_NO_RESIZE``                0x1000 Don't allow resizing of the tab area.
``INB_FIT_LABELTEXT``            0x2000 Will fit the tab area to the longest text (or text+image if you have images) in all the tabs.
``INB_BOLD_TAB_SELECTION``       0x4000 Show the selected tab text using a bold font.
=========================== =========== ==================================================

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

This class processes the following events:

=================================== ==================================================
Event Name                          Description
=================================== ==================================================
``EVT_IMAGENOTEBOOK_PAGE_CHANGED``  Notify client objects when the active page in L{FlatImageBook} or L{LabelBook} has changed.
``EVT_IMAGENOTEBOOK_PAGE_CHANGING`` Notify client objects when the active page in L{FlatImageBook} or L{LabelBook} is about to change.
``EVT_IMAGENOTEBOOK_PAGE_CLOSED``   Notify client objects when a page in L{FlatImageBook} or L{LabelBook} has been closed.
``EVT_IMAGENOTEBOOK_PAGE_CLOSING``  Notify client objects when a page in L{FlatImageBook} or L{LabelBook} is closing.
=================================== ==================================================

TODOs
=====

- L{LabelBook}: support ``IMB_SHOW_ONLY_IMAGES``;
- L{LabelBook}: an option to only draw the border between the controls and the pages so the background
  colour can flow into the window background.

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

L{LabelBook} and L{FlatImageBook} are distributed under the wxPython license.

Latest Revision: Andrea Gavana @ 07 Dec 2011, 21.00 GMT

Version 0.6.

"""

__docformat__ = "epytext"
__version__ = "0.6"

#----------------------------------------------------------------------
# Beginning Of IMAGENOTEBOOK wxPython Code
#----------------------------------------------------------------------

import wx

from artmanager import ArtManager, DCSaver
from fmresources import *

# Check for the new method in 2.7 (not present in 2.6.3.3)
if wx.VERSION_STRING < "2.7":
    wx.Rect.Contains = lambda self, point: wx.Rect.Inside(self, point)

# FlatImageBook and LabelBook styles
INB_BOTTOM = 1
""" Place labels below the page area. Available only for L{FlatImageBook}."""
INB_LEFT = 2
""" Place labels on the left side. Available only for L{FlatImageBook}."""
INB_RIGHT = 4
""" Place labels on the right side. """
INB_TOP = 8
""" Place labels above the page area. """
INB_BORDER = 16
""" Draws a border around L{LabelBook} or L{FlatImageBook}. """
INB_SHOW_ONLY_TEXT = 32
""" Shows only text labels and no images. Available only for L{LabelBook}."""
INB_SHOW_ONLY_IMAGES = 64
""" Shows only tab images and no label texts. Available only for L{LabelBook}."""
INB_FIT_BUTTON = 128
""" Displays a pin button to show/hide the book control. """
INB_DRAW_SHADOW = 256
""" Draw shadows below the book tabs. Available only for L{LabelBook}."""
INB_USE_PIN_BUTTON = 512
""" Displays a pin button to show/hide the book control. """
INB_GRADIENT_BACKGROUND = 1024
""" Draws a gradient shading on the tabs background. Available only for L{LabelBook}."""
INB_WEB_HILITE = 2048
""" On mouse hovering, tabs behave like html hyperlinks. Available only for L{LabelBook}."""
INB_NO_RESIZE = 4096
""" Don't allow resizing of the tab area. """
INB_FIT_LABELTEXT = 8192
""" Will fit the tab area to the longest text (or text+image if you have images) in all the tabs. """
INB_BOLD_TAB_SELECTION = 16384
""" Show the selected tab text using a bold font. """

wxEVT_IMAGENOTEBOOK_PAGE_CHANGED = wx.wxEVT_COMMAND_NOTEBOOK_PAGE_CHANGED
wxEVT_IMAGENOTEBOOK_PAGE_CHANGING = wx.wxEVT_COMMAND_NOTEBOOK_PAGE_CHANGING
wxEVT_IMAGENOTEBOOK_PAGE_CLOSING = wx.NewEventType()
wxEVT_IMAGENOTEBOOK_PAGE_CLOSED = wx.NewEventType()

#-----------------------------------#
#        ImageNotebookEvent
#-----------------------------------#

EVT_IMAGENOTEBOOK_PAGE_CHANGED = wx.EVT_NOTEBOOK_PAGE_CHANGED
""" Notify client objects when the active page in L{FlatImageBook} or L{LabelBook} has changed. """
EVT_IMAGENOTEBOOK_PAGE_CHANGING = wx.EVT_NOTEBOOK_PAGE_CHANGING
""" Notify client objects when the active page in L{FlatImageBook} or L{LabelBook} is about to change. """
EVT_IMAGENOTEBOOK_PAGE_CLOSING = wx.PyEventBinder(wxEVT_IMAGENOTEBOOK_PAGE_CLOSING, 1)
""" Notify client objects when a page in L{FlatImageBook} or L{LabelBook} is closing. """
EVT_IMAGENOTEBOOK_PAGE_CLOSED = wx.PyEventBinder(wxEVT_IMAGENOTEBOOK_PAGE_CLOSED, 1)
""" Notify client objects when a page in L{FlatImageBook} or L{LabelBook} has been closed. """

# ---------------------------------------------------------------------------- #
# Class ImageNotebookEvent
# ---------------------------------------------------------------------------- #

[docs]class ImageNotebookEvent(wx.PyCommandEvent):
    """
    This events will be sent when a ``EVT_IMAGENOTEBOOK_PAGE_CHANGED``,
    ``EVT_IMAGENOTEBOOK_PAGE_CHANGING``, ``EVT_IMAGENOTEBOOK_PAGE_CLOSING``,
    ``EVT_IMAGENOTEBOOK_PAGE_CLOSED`` is mapped in the parent.
    """

[docs]    def __init__(self, eventType, eventId=1, sel=-1, oldsel=-1):
        """
        Default class constructor.

        :param `eventType`: the event type;
        :param `eventId`: the event identifier;
        :param `sel`: the current selection;
        :param `oldsel`: the old selection.
        """

        wx.PyCommandEvent.__init__(self, eventType, eventId)
        self._eventType = eventType
        self._sel = sel
        self._oldsel = oldsel
        self._allowed = True

[docs]    def SetSelection(self, s):
        """
        Sets the event selection.

        :param `s`: an integer specifying the new selection.
        """

        self._sel = s

[docs]    def SetOldSelection(self, s):
        """
        Sets the event old selection.

        :param `s`: an integer specifying the old selection.
        """

        self._oldsel = s

[docs]    def GetSelection(self):
        """ Returns the event selection. """

        return self._sel

[docs]    def GetOldSelection(self):
        """ Returns the old event selection. """

        return self._oldsel

[docs]    def Veto(self):
        """
        Prevents the change announced by this event from happening.

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

        self._allowed = False

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

        self._allowed = True

[docs]    def IsAllowed(self):
        """
        Returns ``True`` if the change is allowed (L{Veto} hasn't been called) or
        ``False`` otherwise (if it was).
        """

        return self._allowed

# ---------------------------------------------------------------------------- #
# Class ImageInfo
# ---------------------------------------------------------------------------- #

[docs]class ImageInfo(object):
    """
    This class holds all the information (caption, image, etc...) belonging to a
    single tab in L{LabelBook}.
    """

[docs]    def __init__(self, strCaption="", imageIndex=-1, enabled=True):
        """
        Default class constructor.

        :param `strCaption`: the tab caption;
        :param `imageIndex`: the tab image index based on the assigned (set)
         `wx.ImageList` (if any);
        :param `enabled`: sets the tab as enabled or disabled.
        """

        self._pos = wx.Point()
        self._size = wx.Size()
        self._strCaption = strCaption
        self._ImageIndex = imageIndex
        self._captionRect = wx.Rect()
        self._bEnabled = enabled

[docs]    def SetCaption(self, value):
        """
        Sets the tab caption.

        :param `value`: the new tab caption.
        """

        self._strCaption = value

[docs]    def GetCaption(self):
        """ Returns the tab caption. """

        return self._strCaption

[docs]    def SetPosition(self, value):
        """
        Sets the tab position.

        :param `value`: the new tab position, an instance of `wx.Point`.
        """

        self._pos = value

[docs]    def GetPosition(self):
        """ Returns the tab position. """

        return self._pos

[docs]    def SetSize(self, value):
        """
        Sets the tab size.

        :param `value`:  the new tab size, an instance of `wx.Size`.
        """

        self._size = value

[docs]    def GetSize(self):
        """ Returns the tab size. """

        return self._size

[docs]    def SetImageIndex(self, value):
        """
        Sets the tab image index.

        :param `value`: an index into the image list..
        """

        self._ImageIndex = value

[docs]    def GetImageIndex(self):
        """ Returns the tab image index. """

        return self._ImageIndex

[docs]    def SetTextRect(self, rect):
        """
        Sets the client rectangle available for the tab text.

        :param `rect`: the tab text client rectangle, an instance of `wx.Rect`.
        """

        self._captionRect = rect

[docs]    def GetTextRect(self):
        """ Returns the client rectangle available for the tab text. """

        return self._captionRect

[docs]    def GetEnabled(self):
        """ Returns whether the tab is enabled or not. """

        return self._bEnabled

[docs]    def EnableTab(self, enabled):
        """
        Sets the tab enabled or disabled.

        :param `enabled`: ``True`` to enable a tab, ``False`` to disable it.
        """

        self._bEnabled = enabled

# ---------------------------------------------------------------------------- #
# Class ImageContainerBase
# ---------------------------------------------------------------------------- #

[docs]class ImageContainerBase(wx.Panel):
    """
    Base class for L{FlatImageBook} image container.
    """

[docs]    def __init__(self, parent, id=wx.ID_ANY, pos=wx.DefaultPosition, size=wx.DefaultSize,
                 style=0, agwStyle=0, name="ImageContainerBase"):
        """
        Default class constructor.

        :param `parent`: parent window. Must not be ``None``;
        :param `id`: window identifier. A value of -1 indicates a default value;
        :param `pos`: the control position. A value of (-1, -1) indicates a default position,
         chosen by either the windowing system or wxPython, depending on platform;
        :param `size`: the control size. A value of (-1, -1) indicates a default size,
         chosen by either the windowing system or wxPython, depending on platform;
        :param `style`: the underlying `wx.Panel` window style;
        :param `agwStyle`: the AGW-specific window style. This can be a combination of the
         following bits:

         =========================== =========== ==================================================
         Window Styles               Hex Value   Description
         =========================== =========== ==================================================
         ``INB_BOTTOM``                      0x1 Place labels below the page area. Available only for L{FlatImageBook}.
         ``INB_LEFT``                        0x2 Place labels on the left side. Available only for L{FlatImageBook}.
         ``INB_RIGHT``                       0x4 Place labels on the right side.
         ``INB_TOP``                         0x8 Place labels above the page area.
         ``INB_BORDER``                     0x10 Draws a border around L{LabelBook} or L{FlatImageBook}.
         ``INB_SHOW_ONLY_TEXT``             0x20 Shows only text labels and no images. Available only for L{LabelBook}.
         ``INB_SHOW_ONLY_IMAGES``           0x40 Shows only tab images and no label texts. Available only for L{LabelBook}.
         ``INB_FIT_BUTTON``                 0x80 Displays a pin button to show/hide the book control.
         ``INB_DRAW_SHADOW``               0x100 Draw shadows below the book tabs. Available only for L{LabelBook}.
         ``INB_USE_PIN_BUTTON``            0x200 Displays a pin button to show/hide the book control.
         ``INB_GRADIENT_BACKGROUND``       0x400 Draws a gradient shading on the tabs background. Available only for L{LabelBook}.
         ``INB_WEB_HILITE``                0x800 On mouse hovering, tabs behave like html hyperlinks. Available only for L{LabelBook}.
         ``INB_NO_RESIZE``                0x1000 Don't allow resizing of the tab area.
         ``INB_FIT_LABELTEXT``            0x2000 Will fit the tab area to the longest text (or text+image if you have images) in all the tabs.
         ``INB_BOLD_TAB_SELECTION``       0x4000 Show the selected tab text using a bold font.
         =========================== =========== ==================================================

        :param `name`: the window name.
        """

        self._nIndex = -1
        self._nImgSize = 16
        self._ImageList = None
        self._nHoveredImgIdx = -1
        self._bCollapsed = False
        self._tabAreaSize = (-1, -1)
        self._nPinButtonStatus = INB_PIN_NONE
        self._pagesInfoVec = []
        self._pinBtnRect = wx.Rect()

        wx.Panel.__init__(self, parent, id, pos, size, style | wx.NO_BORDER | wx.NO_FULL_REPAINT_ON_RESIZE, name)

[docs]    def HasAGWFlag(self, flag):
        """
        Tests for existance of flag in the style.

        :param `flag`: a window style. This can be a combination of the following bits:

         =========================== =========== ==================================================
         Window Styles               Hex Value   Description
         =========================== =========== ==================================================
         ``INB_BOTTOM``                      0x1 Place labels below the page area. Available only for L{FlatImageBook}.
         ``INB_LEFT``                        0x2 Place labels on the left side. Available only for L{FlatImageBook}.
         ``INB_RIGHT``                       0x4 Place labels on the right side.
         ``INB_TOP``                         0x8 Place labels above the page area.
         ``INB_BORDER``                     0x10 Draws a border around L{LabelBook} or L{FlatImageBook}.
         ``INB_SHOW_ONLY_TEXT``             0x20 Shows only text labels and no images. Available only for L{LabelBook}.
         ``INB_SHOW_ONLY_IMAGES``           0x40 Shows only tab images and no label texts. Available only for L{LabelBook}.
         ``INB_FIT_BUTTON``                 0x80 Displays a pin button to show/hide the book control.
         ``INB_DRAW_SHADOW``               0x100 Draw shadows below the book tabs. Available only for L{LabelBook}.
         ``INB_USE_PIN_BUTTON``            0x200 Displays a pin button to show/hide the book control.
         ``INB_GRADIENT_BACKGROUND``       0x400 Draws a gradient shading on the tabs background. Available only for L{LabelBook}.
         ``INB_WEB_HILITE``                0x800 On mouse hovering, tabs behave like html hyperlinks. Available only for L{LabelBook}.
         ``INB_NO_RESIZE``                0x1000 Don't allow resizing of the tab area.
         ``INB_FIT_LABELTEXT``            0x2000 Will fit the tab area to the longest text (or text+image if you have images) in all the tabs.
         ``INB_BOLD_TAB_SELECTION``       0x4000 Show the selected tab text using a bold font.
         =========================== =========== ==================================================
        """

        style = self.GetParent().GetAGWWindowStyleFlag()
        res = (style & flag and [True] or [False])[0]
        return res

[docs]    def ClearFlag(self, flag):
        """
        Removes flag from the style.

        :param `flag`: a window style flag.

        :see: L{HasAGWFlag} for a list of possible window style flags.
        """

        parent = self.GetParent()
        agwStyle = parent.GetAGWWindowStyleFlag()
        agwStyle &= ~(flag)
        parent.SetAGWWindowStyleFlag(agwStyle)

[docs]    def AssignImageList(self, imglist):
        """
        Assigns an image list to the L{ImageContainerBase}.

        :param `imglist`: an instance of `wx.ImageList`.
        """

        if imglist and imglist.GetImageCount() != 0:
            self._nImgSize = imglist.GetBitmap(0).GetHeight()

        self._ImageList = imglist
        parent = self.GetParent()
        agwStyle = parent.GetAGWWindowStyleFlag()
        parent.SetAGWWindowStyleFlag(agwStyle)

[docs]    def GetImageList(self):
        """ Return the image list for L{ImageContainerBase}. """

        return self._ImageList

[docs]    def GetImageSize(self):
        """ Returns the image size inside the L{ImageContainerBase} image list. """

        return self._nImgSize

[docs]    def FixTextSize(self, dc, text, maxWidth):
        """
        Fixes the text, to fit `maxWidth` value. If the text length exceeds
        `maxWidth` value this function truncates it and appends two dots at
        the end. ("Long Long Long Text" might become "Long Long...").

        :param `dc`: an instance of `wx.DC`;
        :param `text`: the text to fix/truncate;
        :param `maxWidth`: the maximum allowed width for the text, in pixels.
        """

        return ArtManager.Get().TruncateText(dc, text, maxWidth)

[docs]    def CanDoBottomStyle(self):
        """
        Allows the parent to examine the children type. Some implementation
        (such as L{LabelBook}), does not support top/bottom images, only left/right.
        """

        return False

[docs]    def AddPage(self, caption, selected=False, imgIdx=-1):
        """
        Adds a page to the container.

        :param `caption`: specifies the text for the new tab;
        :param `selected`: specifies whether the page should be selected;
        :param `imgIdx`: specifies the optional image index for the new tab.
        """

        self._pagesInfoVec.append(ImageInfo(caption, imgIdx))
        if selected or len(self._pagesInfoVec) == 1:
            self._nIndex = len(self._pagesInfoVec)-1

        self.Refresh()

[docs]    def InsertPage(self, page_idx, caption, selected=False, imgIdx=-1):
        """
        Inserts a page into the container at the specified position.

        :param `page_idx`: specifies the position for the new tab;
        :param `caption`: specifies the text for the new tab;
        :param `selected`: specifies whether the page should be selected;
        :param `imgIdx`: specifies the optional image index for the new tab.
        """

        self._pagesInfoVec.insert(page_idx, ImageInfo(caption, imgIdx))
        if selected or len(self._pagesInfoVec) == 1:
            self._nIndex = len(self._pagesInfoVec)-1

        self.Refresh()

[docs]    def SetPageImage(self, page, imgIdx):
        """
        Sets the image for the given page.

        :param `page`: the index of the tab;
        :param `imgIdx`: specifies the optional image index for the tab.
        """

        imgInfo = self._pagesInfoVec[page]
        imgInfo.SetImageIndex(imgIdx)

[docs]    def SetPageText(self, page, text):
        """
        Sets the tab caption for the given page.

        :param `page`: the index of the tab;
        :param `text`: the new tab caption.
        """

        imgInfo = self._pagesInfoVec[page]
        imgInfo.SetCaption(text)

[docs]    def GetPageImage(self, page):
        """
        Returns the image index for the given page.

        :param `page`: the index of the tab.
        """

        imgInfo = self._pagesInfoVec[page]
        return imgInfo.GetImageIndex()

[docs]    def GetPageText(self, page):
        """
        Returns the tab caption for the given page.

        :param `page`: the index of the tab.
        """

        imgInfo = self._pagesInfoVec[page]
        return imgInfo.GetCaption()

[docs]    def GetEnabled(self, page):
        """
        Returns whether a tab is enabled or not.

        :param `page`: an integer specifying the page index.
        """

        if page >= len(self._pagesInfoVec):
            return True # Adding a page - enabled by default

        imgInfo = self._pagesInfoVec[page]
        return imgInfo.GetEnabled()

[docs]    def EnableTab(self, page, enabled=True):
        """
        Enables or disables a tab.

        :param `page`: an integer specifying the page index;
        :param `enabled`: ``True`` to enable a tab, ``False`` to disable it.
        """

        if page >= len(self._pagesInfoVec):
            return

        imgInfo = self._pagesInfoVec[page]
        imgInfo.EnableTab(enabled)

[docs]    def ClearAll(self):
        """ Deletes all the pages in the container. """

        self._pagesInfoVec = []
        self._nIndex = wx.NOT_FOUND

[docs]    def DoDeletePage(self, page):
        """
        Does the actual page deletion.

        :param `page`: the index of the tab.
        """

        # Remove the page from the vector
        book = self.GetParent()
        self._pagesInfoVec.pop(page)

        if self._nIndex >= page:
            self._nIndex = self._nIndex - 1

        # The delete page was the last first on the array,
        # but the book still has more pages, so we set the
        # active page to be the first one (0)
        if self._nIndex < 0 and len(self._pagesInfoVec) > 0:
            self._nIndex = 0

        # Refresh the tabs
        if self._nIndex >= 0:

            book._bForceSelection = True
            book.SetSelection(self._nIndex)
            book._bForceSelection = False

        if not self._pagesInfoVec:
            # Erase the page container drawings
            dc = wx.ClientDC(self)
            dc.Clear()

[docs]    def OnSize(self, event):
        """
        Handles the ``wx.EVT_SIZE`` event for L{ImageContainerBase}.

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

        self.Refresh() # Call on paint
        event.Skip()

[docs]    def OnEraseBackground(self, event):
        """
        Handles the ``wx.EVT_ERASE_BACKGROUND`` event for L{ImageContainerBase}.

        :param `event`: a `wx.EraseEvent` event to be processed.

        :note: This method is intentionally empty to reduce flicker.
        """

        pass

[docs]    def HitTest(self, pt):
        """
        Returns the index of the tab at the specified position or ``wx.NOT_FOUND``
        if ``None``, plus the flag style of L{HitTest}.

        :param `pt`: an instance of `wx.Point`, to test for hits.

        :return: The index of the tab at the specified position plus the hit test
         flag, which can be one of the following bits:

         ====================== ======= ================================
         HitTest Flags           Value  Description
         ====================== ======= ================================
         ``IMG_OVER_IMG``             0 The mouse is over the tab icon
         ``IMG_OVER_PIN``             1 The mouse is over the pin button
         ``IMG_OVER_EW_BORDER``       2 The mouse is over the east-west book border
         ``IMG_NONE``                 3 Nowhere
         ====================== ======= ================================

        """

        style = self.GetParent().GetAGWWindowStyleFlag()

        if style & INB_USE_PIN_BUTTON:
            if self._pinBtnRect.Contains(pt):
                return -1, IMG_OVER_PIN

        for i in xrange(len(self._pagesInfoVec)):

            if self._pagesInfoVec[i].GetPosition() == wx.Point(-1, -1):
                break

            # For Web Hover style, we test the TextRect
            if not self.HasAGWFlag(INB_WEB_HILITE):
                buttonRect = wx.RectPS(self._pagesInfoVec[i].GetPosition(), self._pagesInfoVec[i].GetSize())
            else:
                buttonRect = self._pagesInfoVec[i].GetTextRect()

            if buttonRect.Contains(pt):
                return i, IMG_OVER_IMG

        if self.PointOnSash(pt):
            return -1, IMG_OVER_EW_BORDER
        else:
            return -1, IMG_NONE

[docs]    def PointOnSash(self, pt):
        """
        Tests whether pt is located on the sash.

        :param `pt`: an instance of `wx.Point`, to test for hits.
        """

        # Check if we are on a the sash border
        cltRect = self.GetClientRect()

        if self.HasAGWFlag(INB_LEFT) or self.HasAGWFlag(INB_TOP):
            if pt.x > cltRect.x + cltRect.width - 4:
                return True

        else:
            if pt.x < 4:
                return True

        return False

[docs]    def OnMouseLeftDown(self, event):
        """
        Handles the ``wx.EVT_LEFT_DOWN`` event for L{ImageContainerBase}.

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

        newSelection = -1
        event.Skip()

        # Support for collapse/expand
        style = self.GetParent().GetAGWWindowStyleFlag()
        if style & INB_USE_PIN_BUTTON:

            if self._pinBtnRect.Contains(event.GetPosition()):

                self._nPinButtonStatus = INB_PIN_PRESSED
                dc = wx.ClientDC(self)
                self.DrawPin(dc, self._pinBtnRect, not self._bCollapsed)
                return

        # Incase panel is collapsed, there is nothing
        # to check
        if self._bCollapsed:
            return

        tabIdx, where = self.HitTest(event.GetPosition())

        if where == IMG_OVER_IMG:
            self._nHoveredImgIdx = -1

        if tabIdx == -1:
            return

        self.GetParent().SetSelection(tabIdx)

[docs]    def OnMouseLeaveWindow(self, event):
        """
        Handles the ``wx.EVT_LEAVE_WINDOW`` event for L{ImageContainerBase}.

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

        bRepaint = self._nHoveredImgIdx != -1
        self._nHoveredImgIdx = -1

        # Make sure the pin button status is NONE
        # incase we were in pin button style
        style = self.GetParent().GetAGWWindowStyleFlag()

        if style & INB_USE_PIN_BUTTON:

            self._nPinButtonStatus = INB_PIN_NONE
            dc = wx.ClientDC(self)
            self.DrawPin(dc, self._pinBtnRect, not self._bCollapsed)

        # Restore cursor
        wx.SetCursor(wx.StockCursor(wx.CURSOR_ARROW))

        if bRepaint:
            self.Refresh()

[docs]    def OnMouseLeftUp(self, event):
        """
        Handles the ``wx.EVT_LEFT_UP`` event for L{ImageContainerBase}.

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

        style = self.GetParent().GetAGWWindowStyleFlag()

        if style & INB_USE_PIN_BUTTON:

            bIsLabelContainer = not self.CanDoBottomStyle()

            if self._pinBtnRect.Contains(event.GetPosition()):

                self._nPinButtonStatus = INB_PIN_NONE
                self._bCollapsed = not self._bCollapsed

                if self._bCollapsed:

                    # Save the current tab area width
                    self._tabAreaSize = self.GetSize()

                    if bIsLabelContainer:

                        self.SetSizeHints(20, self._tabAreaSize.y)

                    else:

                        if style & INB_BOTTOM or style & INB_TOP:
                            self.SetSizeHints(self._tabAreaSize.x, 20)
                        else:
                            self.SetSizeHints(20, self._tabAreaSize.y)

                else:

                    if bIsLabelContainer:

                        self.SetSizeHints(self._tabAreaSize.x, -1)

                    else:

                        # Restore the tab area size
                        if style & INB_BOTTOM or style & INB_TOP:
                            self.SetSizeHints(-1, self._tabAreaSize.y)
                        else:
                            self.SetSizeHints(self._tabAreaSize.x, -1)

                self.GetParent().GetSizer().Layout()
                self.Refresh()
                return

[docs]    def OnMouseMove(self, event):
        """
        Handles the ``wx.EVT_MOTION`` event for L{ImageContainerBase}.

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

        style = self.GetParent().GetAGWWindowStyleFlag()
        if style & INB_USE_PIN_BUTTON:

            # Check to see if we are in the pin button rect
            if not self._pinBtnRect.Contains(event.GetPosition()) and self._nPinButtonStatus == INB_PIN_PRESSED:

                self._nPinButtonStatus = INB_PIN_NONE
                dc = wx.ClientDC(self)
                self.DrawPin(dc, self._pinBtnRect, not self._bCollapsed)

        imgIdx, where = self.HitTest(event.GetPosition())

        # Allow hovering unless over current tab or tab is disabled
        self._nHoveredImgIdx = -1

        if imgIdx < len(self._pagesInfoVec) and self.GetEnabled(imgIdx) and imgIdx != self._nIndex:
            self._nHoveredImgIdx = imgIdx

        if not self._bCollapsed:

            if self._nHoveredImgIdx >= 0 and self.HasAGWFlag(INB_WEB_HILITE):

                # Change the cursor to be Hand if we have the Web hover style set
                wx.SetCursor(wx.StockCursor(wx.CURSOR_HAND))

            elif not self.PointOnSash(event.GetPosition()):

                # Restore the cursor if we are not currently hovering the sash
                wx.SetCursor(wx.StockCursor(wx.CURSOR_ARROW))

        self.Refresh()

[docs]    def DrawPin(self, dc, rect, downPin):
        """
        Draw a pin button, that allows collapsing of the image panel.

        :param `dc`: an instance of `wx.DC`;
        :param `rect`: the pin button client rectangle;
        :param `downPin`: ``True`` if the pin button is facing downwards, ``False``
         if it is facing leftwards.
        """

        # Set the bitmap according to the button status

        if downPin:
            pinBmp = wx.BitmapFromXPMData(pin_down_xpm)
        else:
            pinBmp = wx.BitmapFromXPMData(pin_left_xpm)

        xx = rect.x + 2

        if self._nPinButtonStatus in [INB_PIN_HOVER, INB_PIN_NONE]:

            dc.SetBrush(wx.TRANSPARENT_BRUSH)
            dc.SetPen(wx.BLACK_PEN)
            dc.DrawRectangle(xx, rect.y, 16, 16)

            # Draw upper and left border with grey colour
            dc.SetPen(wx.WHITE_PEN)
            dc.DrawLine(xx, rect.y, xx + 16, rect.y)
            dc.DrawLine(xx, rect.y, xx, rect.y + 16)

        elif self._nPinButtonStatus == INB_PIN_PRESSED:

            dc.SetBrush(wx.TRANSPARENT_BRUSH)
            dc.SetPen(wx.Pen(wx.NamedColour("LIGHT GREY")))
            dc.DrawRectangle(xx, rect.y, 16, 16)

            # Draw upper and left border with grey colour
            dc.SetPen(wx.BLACK_PEN)
            dc.DrawLine(xx, rect.y, xx + 16, rect.y)
            dc.DrawLine(xx, rect.y, xx, rect.y + 16)

        # Set the masking
        pinBmp.SetMask(wx.Mask(pinBmp, wx.WHITE))

        # Draw the new bitmap
        dc.DrawBitmap(pinBmp, xx, rect.y, True)

        # Save the pin rect
        self._pinBtnRect = rect

# ---------------------------------------------------------------------------- #
# Class ImageContainer
# ---------------------------------------------------------------------------- #

[docs]class ImageContainer(ImageContainerBase):
    """
    Base class for L{FlatImageBook} image container.
    """

[docs]    def __init__(self, parent, id=wx.ID_ANY, pos=wx.DefaultPosition, size=wx.DefaultSize,
                 style=0, agwStyle=0, name="ImageContainer"):
        """
        Default class constructor.

        :param `parent`: parent window. Must not be ``None``;
        :param `id`: window identifier. A value of -1 indicates a default value;
        :param `pos`: the control position. A value of (-1, -1) indicates a default position,
         chosen by either the windowing system or wxPython, depending on platform;
        :param `size`: the control size. A value of (-1, -1) indicates a default size,
         chosen by either the windowing system or wxPython, depending on platform;
        :param `style`: the underlying `wx.Panel` window style;
        :param `agwStyle`: the AGW-specific window style. This can be a combination of the
         following bits:

         =========================== =========== ==================================================
         Window Styles               Hex Value   Description
         =========================== =========== ==================================================
         ``INB_BOTTOM``                      0x1 Place labels below the page area. Available only for L{FlatImageBook}.
         ``INB_LEFT``                        0x2 Place labels on the left side. Available only for L{FlatImageBook}.
         ``INB_RIGHT``                       0x4 Place labels on the right side.
         ``INB_TOP``                         0x8 Place labels above the page area.
         ``INB_BORDER``                     0x10 Draws a border around L{LabelBook} or L{FlatImageBook}.
         ``INB_SHOW_ONLY_TEXT``             0x20 Shows only text labels and no images. Available only for L{LabelBook}.
         ``INB_SHOW_ONLY_IMAGES``           0x40 Shows only tab images and no label texts. Available only for L{LabelBook}.
         ``INB_FIT_BUTTON``                 0x80 Displays a pin button to show/hide the book control.
         ``INB_DRAW_SHADOW``               0x100 Draw shadows below the book tabs. Available only for L{LabelBook}.
         ``INB_USE_PIN_BUTTON``            0x200 Displays a pin button to show/hide the book control.
         ``INB_GRADIENT_BACKGROUND``       0x400 Draws a gradient shading on the tabs background. Available only for L{LabelBook}.
         ``INB_WEB_HILITE``                0x800 On mouse hovering, tabs behave like html hyperlinks. Available only for L{LabelBook}.
         ``INB_NO_RESIZE``                0x1000 Don't allow resizing of the tab area.
         ``INB_FIT_LABELTEXT``            0x2000 Will fit the tab area to the longest text (or text+image if you have images) in all the tabs.
         ``INB_BOLD_TAB_SELECTION``       0x4000 Show the selected tab text using a bold font.
         =========================== =========== ==================================================

        :param `name`: the window name.
        """

        ImageContainerBase.__init__(self, parent, id, pos, size, style, agwStyle, name)

        self.Bind(wx.EVT_PAINT, self.OnPaint)
        self.Bind(wx.EVT_SIZE, self.OnSize)
        self.Bind(wx.EVT_LEFT_DOWN, self.OnMouseLeftDown)
        self.Bind(wx.EVT_LEFT_UP, self.OnMouseLeftUp)
        self.Bind(wx.EVT_ERASE_BACKGROUND, self.OnEraseBackground)
        self.Bind(wx.EVT_MOTION, self.OnMouseMove)
        self.Bind(wx.EVT_LEAVE_WINDOW, self.OnMouseLeaveWindow)

[docs]    def OnSize(self, event):
        """
        Handles the ``wx.EVT_SIZE`` event for L{ImageContainer}.

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

        ImageContainerBase.OnSize(self, event)
        event.Skip()

[docs]    def OnMouseLeftDown(self, event):
        """
        Handles the ``wx.EVT_LEFT_DOWN`` event for L{ImageContainer}.

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

        ImageContainerBase.OnMouseLeftDown(self, event)
        event.Skip()

[docs]    def OnMouseLeftUp(self, event):
        """
        Handles the ``wx.EVT_LEFT_UP`` event for L{ImageContainer}.

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

        ImageContainerBase.OnMouseLeftUp(self, event)
        event.Skip()

[docs]    def OnEraseBackground(self, event):
        """
        Handles the ``wx.EVT_ERASE_BACKGROUND`` event for L{ImageContainer}.

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

        ImageContainerBase.OnEraseBackground(self, event)

[docs]    def OnMouseMove(self, event):
        """
        Handles the ``wx.EVT_MOTION`` event for L{ImageContainer}.

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

        ImageContainerBase.OnMouseMove(self, event)
        event.Skip()

[docs]    def OnMouseLeaveWindow(self, event):
        """
        Handles the ``wx.EVT_LEAVE_WINDOW`` event for L{ImageContainer}.

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

        ImageContainerBase.OnMouseLeaveWindow(self, event)
        event.Skip()

[docs]    def CanDoBottomStyle(self):
        """
        Allows the parent to examine the children type. Some implementation
        (such as L{LabelBook}), does not support top/bottom images, only left/right.
        """

        return True

[docs]    def OnPaint(self, event):
        """
        Handles the ``wx.EVT_PAINT`` event for L{ImageContainer}.

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

        dc = wx.BufferedPaintDC(self)
        style = self.GetParent().GetAGWWindowStyleFlag()

        backBrush = wx.WHITE_BRUSH
        if style & INB_BORDER:
            borderPen = wx.Pen(wx.SystemSettings_GetColour(wx.SYS_COLOUR_3DSHADOW))
        else:
            borderPen = wx.TRANSPARENT_PEN

        size = self.GetSize()

        # Background
        dc.SetBrush(backBrush)

        borderPen.SetWidth(1)
        dc.SetPen(borderPen)
        dc.DrawRectangle(0, 0, size.x, size.y)
        bUsePin = (style & INB_USE_PIN_BUTTON and [True] or [False])[0]

        if bUsePin:

            # Draw the pin button
            clientRect = self.GetClientRect()
            pinRect = wx.Rect(clientRect.GetX() + clientRect.GetWidth() - 20, 2, 20, 20)
            self.DrawPin(dc, pinRect, not self._bCollapsed)

            if self._bCollapsed:
                return

        borderPen = wx.BLACK_PEN
        borderPen.SetWidth(1)
        dc.SetPen(borderPen)
        dc.DrawLine(0, size.y, size.x, size.y)
        dc.DrawPoint(0, size.y)

        clientSize = 0
        bUseYcoord = (style & INB_RIGHT or style & INB_LEFT)

        if bUseYcoord:
            clientSize = size.GetHeight()
        else:
            clientSize = size.GetWidth()

        # We reserver 20 pixels for the 'pin' button

        # The drawing of the images start position. This is
        # depenedent of the style, especially when Pin button
        # style is requested

        if bUsePin:
            if style & INB_TOP or style & INB_BOTTOM:
                pos = (style & INB_BORDER and [0] or [1])[0]
            else:
                pos = (style & INB_BORDER and [20] or [21])[0]
        else:
            pos = (style & INB_BORDER and [0] or [1])[0]

        nPadding = 4    # Pad text with 2 pixels on the left and right
        nTextPaddingLeft = 2

        count = 0
        normalFont = wx.SystemSettings_GetFont(wx.SYS_DEFAULT_GUI_FONT)
        boldFont = wx.SystemSettings_GetFont(wx.SYS_DEFAULT_GUI_FONT)
        boldFont.SetWeight(wx.BOLD)

        for i in xrange(len(self._pagesInfoVec)):

            count = count + 1

            # incase the 'fit button' style is applied, we set the rectangle width to the
            # text width plus padding
            # Incase the style IS applied, but the style is either LEFT or RIGHT
            # we ignore it
            dc.SetFont(normalFont)

            if style & INB_BOLD_TAB_SELECTION and self._nIndex == i:
                dc.SetFont(boldFont)

            textWidth, textHeight = dc.GetTextExtent(self._pagesInfoVec[i].GetCaption())

            # Default values for the surronounding rectangle
            # around a button
            rectWidth = self._nImgSize * 2  # To avoid the recangle to 'touch' the borders
            rectHeight = self._nImgSize * 2

            # Incase the style requires non-fixed button (fit to text)
            # recalc the rectangle width
            if style & INB_FIT_BUTTON and \
               not ((style & INB_LEFT) or (style & INB_RIGHT)) and \
               not self._pagesInfoVec[i].GetCaption() == "" and \
               not (style & INB_SHOW_ONLY_IMAGES):

                rectWidth = ((textWidth + nPadding * 2) > rectWidth and [nPadding * 2 + textWidth] or [rectWidth])[0]

                # Make the width an even number
                if rectWidth % 2 != 0:
                    rectWidth += 1

            # Check that we have enough space to draw the button
            # If Pin button is used, consider its space as well (applicable for top/botton style)
            # since in the left/right, its size is already considered in 'pos'
            pinBtnSize = (bUsePin and [20] or [0])[0]

            if pos + rectWidth + pinBtnSize > clientSize:
                break

            # Calculate the button rectangle
            modRectWidth = ((style & INB_LEFT or style & INB_RIGHT) and [rectWidth - 2] or [rectWidth])[0]
            modRectHeight = ((style & INB_LEFT or style & INB_RIGHT) and [rectHeight] or [rectHeight - 2])[0]

            if bUseYcoord:
                buttonRect = wx.Rect(1, pos, modRectWidth, modRectHeight)
            else:
                buttonRect = wx.Rect(pos , 1, modRectWidth, modRectHeight)

            # Check if we need to draw a rectangle around the button
            if self._nIndex == i:

                # Set the colours
                penColour = wx.SystemSettings_GetColour(wx.SYS_COLOUR_ACTIVECAPTION)
                brushColour = ArtManager.Get().LightColour(wx.SystemSettings_GetColour(wx.SYS_COLOUR_ACTIVECAPTION), 75)

                dc.SetPen(wx.Pen(penColour))
                dc.SetBrush(wx.Brush(brushColour))

                # Fix the surrounding of the rect if border is set
                if style & INB_BORDER:

                    if style & INB_TOP or style & INB_BOTTOM:
                        buttonRect = wx.Rect(buttonRect.x + 1, buttonRect.y, buttonRect.width - 1, buttonRect.height)
                    else:
                        buttonRect = wx.Rect(buttonRect.x, buttonRect.y + 1, buttonRect.width, buttonRect.height - 1)

                dc.DrawRectangleRect(buttonRect)

            if self._nHoveredImgIdx == i:

                # Set the colours
                penColour = wx.SystemSettings_GetColour(wx.SYS_COLOUR_ACTIVECAPTION)
                brushColour = ArtManager.Get().LightColour(wx.SystemSettings_GetColour(wx.SYS_COLOUR_ACTIVECAPTION), 90)

                dc.SetPen(wx.Pen(penColour))
                dc.SetBrush(wx.Brush(brushColour))

                # Fix the surrounding of the rect if border is set
                if style & INB_BORDER:

                    if style & INB_TOP or style & INB_BOTTOM:
                        buttonRect = wx.Rect(buttonRect.x + 1, buttonRect.y, buttonRect.width - 1, buttonRect.height)
                    else:
                        buttonRect = wx.Rect(buttonRect.x, buttonRect.y + 1, buttonRect.width, buttonRect.height - 1)

                dc.DrawRectangleRect(buttonRect)

            if bUseYcoord:
                rect = wx.Rect(0, pos, rectWidth, rectWidth)
            else:
                rect = wx.Rect(pos, 0, rectWidth, rectWidth)

            # Incase user set both flags:
            # INB_SHOW_ONLY_TEXT and INB_SHOW_ONLY_IMAGES
            # We override them to display both

            if style & INB_SHOW_ONLY_TEXT and style & INB_SHOW_ONLY_IMAGES:

                style ^= INB_SHOW_ONLY_TEXT
                style ^= INB_SHOW_ONLY_IMAGES
                self.GetParent().SetAGWWindowStyleFlag(style)

            # Draw the caption and text
            imgTopPadding = 10
            if not style & INB_SHOW_ONLY_TEXT and self._pagesInfoVec[i].GetImageIndex() != -1:

                if bUseYcoord:

                    imgXcoord = self._nImgSize / 2
                    imgYcoord = (style & INB_SHOW_ONLY_IMAGES and [pos + self._nImgSize / 2] or [pos + imgTopPadding])[0]

                else:

                    imgXcoord = pos + (rectWidth / 2) - (self._nImgSize / 2)
                    imgYcoord = (style & INB_SHOW_ONLY_IMAGES and [self._nImgSize / 2] or [imgTopPadding])[0]

                self._ImageList.Draw(self._pagesInfoVec[i].GetImageIndex(), dc,
                                     imgXcoord, imgYcoord,
                                     wx.IMAGELIST_DRAW_TRANSPARENT, True)

            # Draw the text
            if not style & INB_SHOW_ONLY_IMAGES and not self._pagesInfoVec[i].GetCaption() == "":

                if style & INB_BOLD_TAB_SELECTION and self._nIndex == i:
                    dc.SetFont(boldFont)
                else:
                    dc.SetFont(normalFont)

                # Check if the text can fit the size of the rectangle,
                # if not truncate it
                fixedText = self._pagesInfoVec[i].GetCaption()
                if not style & INB_FIT_BUTTON or (style & INB_LEFT or (style & INB_RIGHT)):

                    fixedText = self.FixTextSize(dc, self._pagesInfoVec[i].GetCaption(), self._nImgSize *2 - 4)

                    # Update the length of the text
                    textWidth, textHeight = dc.GetTextExtent(fixedText)

                if bUseYcoord:

                    textOffsetX = ((rectWidth - textWidth) / 2 )
                    textOffsetY = (not style & INB_SHOW_ONLY_TEXT  and [pos + self._nImgSize  + imgTopPadding + 3] or \
                                       [pos + ((self._nImgSize * 2 - textHeight) / 2 )])[0]

                else:

                    textOffsetX = (rectWidth - textWidth) / 2  + pos + nTextPaddingLeft
                    textOffsetY = (not style & INB_SHOW_ONLY_TEXT and [self._nImgSize + imgTopPadding + 3] or \
                                       [((self._nImgSize * 2 - textHeight) / 2 )])[0]

                dc.SetTextForeground(wx.SystemSettings_GetColour(wx.SYS_COLOUR_WINDOWTEXT))
                dc.DrawText(fixedText, textOffsetX, textOffsetY)

            # Update the page info
            self._pagesInfoVec[i].SetPosition(buttonRect.GetPosition())
            self._pagesInfoVec[i].SetSize(buttonRect.GetSize())

            pos += rectWidth

        # Update all buttons that can not fit into the screen as non-visible
        for ii in xrange(count, len(self._pagesInfoVec)):
            self._pagesInfoVec[ii].SetPosition(wx.Point(-1, -1))

        # Draw the pin button
        if bUsePin:

            clientRect = self.GetClientRect()
            pinRect = wx.Rect(clientRect.GetX() + clientRect.GetWidth() - 20, 2, 20, 20)
            self.DrawPin(dc, pinRect, not self._bCollapsed)

# ---------------------------------------------------------------------------- #
# Class LabelContainer
# ---------------------------------------------------------------------------- #

[docs]class LabelContainer(ImageContainerBase):
    """ Base class for L{LabelBook}. """

[docs]    def __init__(self, parent, id=wx.ID_ANY, pos=wx.DefaultPosition, size=wx.DefaultSize,
                 style=0, agwStyle=0, name="LabelContainer"):
        """
        Default class constructor.

        :param `parent`: parent window. Must not be ``None``;
        :param `id`: window identifier. A value of -1 indicates a default value;
        :param `pos`: the control position. A value of (-1, -1) indicates a default position,
         chosen by either the windowing system or wxPython, depending on platform;
        :param `size`: the control size. A value of (-1, -1) indicates a default size,
         chosen by either the windowing system or wxPython, depending on platform;
        :param `style`: the underlying `wx.Panel` window style;
        :param `agwStyle`: the AGW-specific window style. This can be a combination of the
         following bits:

         =========================== =========== ==================================================
         Window Styles               Hex Value   Description
         =========================== =========== ==================================================
         ``INB_BOTTOM``                      0x1 Place labels below the page area. Available only for L{FlatImageBook}.
         ``INB_LEFT``                        0x2 Place labels on the left side. Available only for L{FlatImageBook}.
         ``INB_RIGHT``                       0x4 Place labels on the right side.
         ``INB_TOP``                         0x8 Place labels above the page area.
         ``INB_BORDER``                     0x10 Draws a border around L{LabelBook} or L{FlatImageBook}.
         ``INB_SHOW_ONLY_TEXT``             0x20 Shows only text labels and no images. Available only for L{LabelBook}.
         ``INB_SHOW_ONLY_IMAGES``           0x40 Shows only tab images and no label texts. Available only for L{LabelBook}.
         ``INB_FIT_BUTTON``                 0x80 Displays a pin button to show/hide the book control.
         ``INB_DRAW_SHADOW``               0x100 Draw shadows below the book tabs. Available only for L{LabelBook}.
         ``INB_USE_PIN_BUTTON``            0x200 Displays a pin button to show/hide the book control.
         ``INB_GRADIENT_BACKGROUND``       0x400 Draws a gradient shading on the tabs background. Available only for L{LabelBook}.
         ``INB_WEB_HILITE``                0x800 On mouse hovering, tabs behave like html hyperlinks. Available only for L{LabelBook}.
         ``INB_NO_RESIZE``                0x1000 Don't allow resizing of the tab area.
         ``INB_FIT_LABELTEXT``            0x2000 Will fit the tab area to the longest text (or text+image if you have images) in all the tabs.
         ``INB_BOLD_TAB_SELECTION``       0x4000 Show the selected tab text using a bold font.
         =========================== =========== ==================================================

        :param `name`: the window name.
        """

        ImageContainerBase.__init__(self, parent, id, pos, size, style, agwStyle, name)
        self._nTabAreaWidth = 100
        self._oldCursor = wx.NullCursor
        self._coloursMap = {}
        self._skin = wx.NullBitmap
        self._sashRect = wx.Rect()

        self.Bind(wx.EVT_PAINT, self.OnPaint)
        self.Bind(wx.EVT_SIZE, self.OnSize)
        self.Bind(wx.EVT_LEFT_DOWN, self.OnMouseLeftDown)
        self.Bind(wx.EVT_LEFT_UP, self.OnMouseLeftUp)
        self.Bind(wx.EVT_MOTION, self.OnMouseMove)
        self.Bind(wx.EVT_LEAVE_WINDOW, self.OnMouseLeaveWindow)
        self.Bind(wx.EVT_ERASE_BACKGROUND, self.OnEraseBackground)

[docs]    def OnSize(self, event):
        """
        Handles the ``wx.EVT_SIZE`` event for L{LabelContainer}.

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

        ImageContainerBase.OnSize(self, event)
        event.Skip()

[docs]    def OnEraseBackground(self, event):
        """
        Handles the ``wx.EVT_ERASE_BACKGROUND`` event for L{LabelContainer}.

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

        ImageContainerBase.OnEraseBackground(self, event)

[docs]    def GetTabAreaWidth(self):
        """ Returns the width of the tab area. """

        return self._nTabAreaWidth

[docs]    def SetTabAreaWidth(self, width):
        """
        Sets the width of the tab area.

        :param `width`: the width of the tab area, in pixels.
        """

        self._nTabAreaWidth = width

[docs]    def CanDoBottomStyle(self):
        """
        Allows the parent to examine the children type. Some implementation
        (such as L{LabelBook}), does not support top/bottom images, only left/right.
        """

        return False

[docs]    def SetBackgroundBitmap(self, bmp):
        """
        Sets the background bitmap for the control.

        :param `bmp`: a valid `wx.Bitmap` object.
        """

        self._skin = bmp

[docs]    def OnPaint(self, event):
        """
        Handles the ``wx.EVT_PAINT`` event for L{LabelContainer}.

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

        style = self.GetParent().GetAGWWindowStyleFlag()

        dc = wx.BufferedPaintDC(self)
        backBrush = wx.Brush(self._coloursMap[INB_TAB_AREA_BACKGROUND_COLOUR])
        if self.HasAGWFlag(INB_BORDER):
            borderPen = wx.Pen(self._coloursMap[INB_TABS_BORDER_COLOUR])
        else:
            borderPen = wx.TRANSPARENT_PEN

        size = self.GetSize()

        # Set the pen & brush
        dc.SetBrush(backBrush)
        dc.SetPen(borderPen)

        # Incase user set both flags, we override them to display both
        # INB_SHOW_ONLY_TEXT and INB_SHOW_ONLY_IMAGES
        if style & INB_SHOW_ONLY_TEXT and style & INB_SHOW_ONLY_IMAGES:

            style ^= INB_SHOW_ONLY_TEXT
            style ^= INB_SHOW_ONLY_IMAGES
            self.GetParent().SetAGWWindowStyleFlag(style)

        if self.HasAGWFlag(INB_GRADIENT_BACKGROUND) and not self._skin.Ok():

            # Draw graident in the background area
            startColour = self._coloursMap[INB_TAB_AREA_BACKGROUND_COLOUR]
            endColour   = ArtManager.Get().LightColour(self._coloursMap[INB_TAB_AREA_BACKGROUND_COLOUR], 50)
            ArtManager.Get().PaintStraightGradientBox(dc, wx.Rect(0, 0, size.x / 2, size.y), startColour, endColour, False)
            ArtManager.Get().PaintStraightGradientBox(dc, wx.Rect(size.x / 2, 0, size.x / 2, size.y), endColour, startColour, False)

        else:

            # Draw the border and background
            if self._skin.Ok():

                dc.SetBrush(wx.TRANSPARENT_BRUSH)
                self.DrawBackgroundBitmap(dc)

            dc.DrawRectangleRect(wx.Rect(0, 0, size.x, size.y))

        # Draw border
        if self.HasAGWFlag(INB_BORDER) and self.HasAGWFlag(INB_GRADIENT_BACKGROUND):

            # Just draw the border with transparent brush
            dc.SetBrush(wx.TRANSPARENT_BRUSH)
            dc.DrawRectangleRect(wx.Rect(0, 0, size.x, size.y))

        bUsePin = (self.HasAGWFlag(INB_USE_PIN_BUTTON) and [True] or [False])[0]

        if bUsePin:

            # Draw the pin button
            clientRect = self.GetClientRect()
            pinRect = wx.Rect(clientRect.GetX() + clientRect.GetWidth() - 20, 2, 20, 20)
            self.DrawPin(dc, pinRect, not self._bCollapsed)

            if self._bCollapsed:
                return

        dc.SetPen(wx.BLACK_PEN)
        self.SetSizeHints(self._nTabAreaWidth, -1)

        # We reserve 20 pixels for the pin button
        posy = 20
        count = 0

        for i in xrange(len(self._pagesInfoVec)):
            count = count+1
            # Default values for the surronounding rectangle
            # around a button
            rectWidth = self._nTabAreaWidth

            if self.HasAGWFlag(INB_SHOW_ONLY_TEXT):
                font = wx.SystemSettings_GetFont(wx.SYS_DEFAULT_GUI_FONT)
                font.SetPointSize(font.GetPointSize() * self.GetParent().GetFontSizeMultiple())

                if self.GetParent().GetFontBold():
                    font.SetWeight(wx.FONTWEIGHT_BOLD)
                elif self.HasAGWFlag(INB_BOLD_TAB_SELECTION) and self._nIndex == i:
                    font.SetWeight(wx.FONTWEIGHT_BOLD)

                dc.SetFont(font)
                w, h = dc.GetTextExtent(self._pagesInfoVec[i].GetCaption())
                rectHeight = h * 2
            else:
                rectHeight = self._nImgSize * 2

            # Check that we have enough space to draw the button
            if posy + rectHeight > size.GetHeight():
                break

            # Calculate the button rectangle
            posx = 0

            buttonRect = wx.Rect(posx, posy, rectWidth, rectHeight)
            indx = self._pagesInfoVec[i].GetImageIndex()

            if indx == -1:
                bmp = wx.NullBitmap
            else:
                bmp = self._ImageList.GetBitmap(indx)

            self.DrawLabel(dc, buttonRect, self._pagesInfoVec[i].GetCaption(), bmp,
                           self._pagesInfoVec[i], self.HasAGWFlag(INB_LEFT) or self.HasAGWFlag(INB_TOP),
                           i, self._nIndex == i, self._nHoveredImgIdx == i)

            posy += rectHeight

        # Update all buttons that can not fit into the screen as non-visible
        for ii in xrange(count, len(self._pagesInfoVec)):
            self._pagesInfoVec[i].SetPosition(wx.Point(-1, -1))

        if bUsePin:

            clientRect = self.GetClientRect()
            pinRect = wx.Rect(clientRect.GetX() + clientRect.GetWidth() - 20, 2, 20, 20)
            self.DrawPin(dc, pinRect, not self._bCollapsed)

[docs]    def DrawBackgroundBitmap(self, dc):
        """
        Draws a bitmap as the background of the control.

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

        clientRect = self.GetClientRect()
        width = clientRect.GetWidth()
        height = clientRect.GetHeight()
        coveredY = coveredX = 0
        xstep = self._skin.GetWidth()
        ystep = self._skin.GetHeight()
        bmpRect = wx.Rect(0, 0, xstep, ystep)
        if bmpRect != clientRect:

            mem_dc = wx.MemoryDC()
            bmp = wx.EmptyBitmap(width, height)
            mem_dc.SelectObject(bmp)

            while coveredY < height:

                while coveredX < width:

                    mem_dc.DrawBitmap(self._skin, coveredX, coveredY, True)
                    coveredX += xstep

                coveredX = 0
                coveredY += ystep

            mem_dc.SelectObject(wx.NullBitmap)
            #self._skin = bmp
            dc.DrawBitmap(bmp, 0, 0)

        else:

            dc.DrawBitmap(self._skin, 0, 0)

[docs]    def OnMouseLeftUp(self, event):
        """
        Handles the ``wx.EVT_LEFT_UP`` event for L{LabelContainer}.

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

        if self.HasAGWFlag(INB_NO_RESIZE):

            ImageContainerBase.OnMouseLeftUp(self, event)
            return

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

        # Sash was being dragged?
        if not self._sashRect.IsEmpty():

            # Remove sash
            ArtManager.Get().DrawDragSash(self._sashRect)
            self.Resize(event)

            self._sashRect = wx.Rect()
            return

        self._sashRect = wx.Rect()

        # Restore cursor
        if self._oldCursor.Ok():

            wx.SetCursor(self._oldCursor)
            self._oldCursor = wx.NullCursor

        ImageContainerBase.OnMouseLeftUp(self, event)

[docs]    def Resize(self, event):
        """
        Actually resizes the tab area.

        :param `event`: an instance of `wx.SizeEvent`.
        """

        # Resize our size
        self._tabAreaSize = self.GetSize()
        newWidth = self._tabAreaSize.x
        x = event.GetX()

        if self.HasAGWFlag(INB_BOTTOM) or self.HasAGWFlag(INB_RIGHT):

            newWidth -= event.GetX()

        else:

            newWidth = x

        if newWidth < 100: # Dont allow width to be lower than that
            newWidth = 100

        self.SetSizeHints(newWidth, self._tabAreaSize.y)

        # Update the tab new area width
        self._nTabAreaWidth = newWidth
        self.GetParent().Freeze()
        self.GetParent().GetSizer().Layout()
        self.GetParent().Thaw()

[docs]    def OnMouseMove(self, event):
        """
        Handles the ``wx.EVT_MOTION`` event for L{LabelContainer}.

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

        if self.HasAGWFlag(INB_NO_RESIZE):

            ImageContainerBase.OnMouseMove(self, event)
            return

        # Remove old sash
        if not self._sashRect.IsEmpty():
            ArtManager.Get().DrawDragSash(self._sashRect)

        if event.LeftIsDown():

            if not self._sashRect.IsEmpty():

                # Progress sash, and redraw it
                clientRect = self.GetClientRect()
                pt = self.ClientToScreen(wx.Point(event.GetX(), 0))
                self._sashRect = wx.RectPS(pt, wx.Size(4, clientRect.height))
                ArtManager.Get().DrawDragSash(self._sashRect)

            else:

                # Sash is not being dragged
                if self._oldCursor.Ok():
                    wx.SetCursor(self._oldCursor)
                    self._oldCursor = wx.NullCursor

        else:

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

            if self.PointOnSash(event.GetPosition()):

                # Change cursor to EW cursor
                self._oldCursor = self.GetCursor()
                wx.SetCursor(wx.StockCursor(wx.CURSOR_SIZEWE))

            elif self._oldCursor.Ok():

                wx.SetCursor(self._oldCursor)
                self._oldCursor = wx.NullCursor

            self._sashRect = wx.Rect()
            ImageContainerBase.OnMouseMove(self, event)

[docs]    def OnMouseLeftDown(self, event):
        """
        Handles the ``wx.EVT_LEFT_DOWN`` event for L{LabelContainer}.

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

        if self.HasAGWFlag(INB_NO_RESIZE):

            ImageContainerBase.OnMouseLeftDown(self, event)
            return

        imgIdx, where = self.HitTest(event.GetPosition())

        if IMG_OVER_EW_BORDER == where and not self._bCollapsed:

            # We are over the sash
            if not self._sashRect.IsEmpty():
                ArtManager.Get().DrawDragSash(self._sashRect)
            else:
                # first time, begin drawing sash
                self.CaptureMouse()

                # Change mouse cursor
                self._oldCursor = self.GetCursor()
                wx.SetCursor(wx.StockCursor(wx.CURSOR_SIZEWE))

            clientRect = self.GetClientRect()
            pt = self.ClientToScreen(wx.Point(event.GetX(), 0))
            self._sashRect = wx.RectPS(pt, wx.Size(4, clientRect.height))

            ArtManager.Get().DrawDragSash(self._sashRect)

        else:
            ImageContainerBase.OnMouseLeftDown(self, event)

[docs]    def OnMouseLeaveWindow(self, event):
        """
        Handles the ``wx.EVT_LEAVE_WINDOW`` event for L{LabelContainer}.

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

        if self.HasAGWFlag(INB_NO_RESIZE):

            ImageContainerBase.OnMouseLeaveWindow(self, event)
            return

        # If Sash is being dragged, ignore this event
        if not self.HasCapture():
            ImageContainerBase.OnMouseLeaveWindow(self, event)

[docs]    def DrawRegularHover(self, dc, rect):
        """
        Draws a rounded rectangle around the current tab.

        :param `dc`: an instance of `wx.DC`;
        :param `rect`: the current tab client rectangle.
        """

        # The hovered tab with default border
        dc.SetBrush(wx.TRANSPARENT_BRUSH)
        dc.SetPen(wx.Pen(wx.WHITE))

        # We draw CCW
        if self.HasAGWFlag(INB_RIGHT) or self.HasAGWFlag(INB_TOP):

            # Right images
            # Upper line
            dc.DrawLine(rect.x + 1, rect.y, rect.x + rect.width, rect.y)

            # Right line (white)
            dc.DrawLine(rect.x + rect.width, rect.y, rect.x + rect.width, rect.y + rect.height)

            # Bottom diagnol - we change pen
            dc.SetPen(wx.Pen(self._coloursMap[INB_TABS_BORDER_COLOUR]))

            # Bottom line
            dc.DrawLine(rect.x + rect.width, rect.y + rect.height, rect.x, rect.y + rect.height)

        else:

            # Left images
            # Upper line white
            dc.DrawLine(rect.x, rect.y, rect.x + rect.width - 1, rect.y)

            # Left line
            dc.DrawLine(rect.x, rect.y, rect.x, rect.y + rect.height)

            # Bottom diagnol, we change the pen
            dc.SetPen(wx.Pen(self._coloursMap[INB_TABS_BORDER_COLOUR]))

            # Bottom line
            dc.DrawLine(rect.x, rect.y + rect.height, rect.x + rect.width, rect.y + rect.height)

[docs]    def DrawWebHover(self, dc, caption, xCoord, yCoord, selected):
        """
        Draws a web style hover effect (cursor set to hand & text is underlined).

        :param `dc`: an instance of `wx.DC`;
        :param `caption`: the tab caption text;
        :param `xCoord`: the x position of the tab caption;
        :param `yCoord`: the y position of the tab caption;
        :param `selected`: ``True`` if the tab is selected, ``False`` otherwise.
        """

        # Redraw the text with underlined font
        underLinedFont = wx.SystemSettings_GetFont(wx.SYS_DEFAULT_GUI_FONT)
        underLinedFont.SetPointSize(underLinedFont.GetPointSize() * self.GetParent().GetFontSizeMultiple())
        if self.GetParent().GetFontBold():
            underLinedFont.SetWeight(wx.FONTWEIGHT_BOLD)
        elif self.HasAGWFlag(INB_BOLD_TAB_SELECTION) and selected:
            underLinedFont.SetWeight(wx.FONTWEIGHT_BOLD)

        underLinedFont.SetUnderlined(True)
        dc.SetFont(underLinedFont)
        dc.DrawText(caption, xCoord, yCoord)

[docs]    def SetColour(self, which, colour):
        """
        Sets a colour for a parameter.

        :param `which`: can be one of the following parameters:

         ================================== ======= ==================================
         Colour Key                          Value  Description
         ================================== ======= ==================================
         ``INB_TAB_AREA_BACKGROUND_COLOUR``     100 The tab area background colour
         ``INB_ACTIVE_TAB_COLOUR``              101 The active tab background colour
         ``INB_TABS_BORDER_COLOUR``             102 The tabs border colour
         ``INB_TEXT_COLOUR``                    103 The tab caption text colour
         ``INB_ACTIVE_TEXT_COLOUR``             104 The active tab caption text colour
         ``INB_HILITE_TAB_COLOUR``              105 The tab caption highlight text colour
         ================================== ======= ==================================

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

        self._coloursMap[which] = colour

[docs]    def GetColour(self, which):
        """
        Returns a colour for a parameter.

        :param `which`: the colour key.

        :see: L{SetColour} for a list of valid colour keys.
        """

        if not self._coloursMap.has_key(which):
            return wx.Colour()

        return self._coloursMap[which]

[docs]    def InitializeColours(self):
        """ Initializes the colours map to be used for this control. """

        # Initialize map colours
        self._coloursMap.update({INB_TAB_AREA_BACKGROUND_COLOUR: ArtManager.Get().LightColour(ArtManager.Get().FrameColour(), 50)})
        self._coloursMap.update({INB_ACTIVE_TAB_COLOUR: ArtManager.Get().GetMenuFaceColour()})
        self._coloursMap.update({INB_TABS_BORDER_COLOUR: wx.SystemSettings_GetColour(wx.SYS_COLOUR_3DSHADOW)})
        self._coloursMap.update({INB_HILITE_TAB_COLOUR: wx.NamedColour("LIGHT BLUE")})
        self._coloursMap.update({INB_TEXT_COLOUR: wx.WHITE})
        self._coloursMap.update({INB_ACTIVE_TEXT_COLOUR: wx.BLACK})

        # dont allow bright colour one on the other
        if not ArtManager.Get().IsDark(self._coloursMap[INB_TAB_AREA_BACKGROUND_COLOUR]) and \
           not ArtManager.Get().IsDark(self._coloursMap[INB_TEXT_COLOUR]):

            self._coloursMap[INB_TEXT_COLOUR] = ArtManager.Get().DarkColour(self._coloursMap[INB_TEXT_COLOUR], 100)

[docs]    def DrawLabel(self, dc, rect, text, bmp, imgInfo, orientationLeft, imgIdx, selected, hover):
        """
        Draws a label using the specified dc.

        :param `dc`: an instance of `wx.DC`;
        :param `rect`: the text client rectangle;
        :param `text`: the actual text string;
        :param `bmp`: a bitmap to be drawn next to the text;
        :param `imgInfo`: an instance of L{ImageInfo};
        :param `orientationLeft`: ``True`` if the book has the ``INB_RIGHT`` or ``INB_LEFT``
         style set;
        :param `imgIdx`: the tab image index;
        :param `selected`: ``True`` if the tab is selected, ``False`` otherwise;
        :param `hover`: ``True`` if the tab is being hovered with the mouse, ``False`` otherwise.
        """

        dcsaver = DCSaver(dc)
        nPadding = 6

        if orientationLeft:

            rect.x += nPadding
            rect.width -= nPadding

        else:

            rect.width -= nPadding

        textRect = wx.Rect(*rect)
        imgRect = wx.Rect(*rect)

        font = wx.SystemSettings_GetFont(wx.SYS_DEFAULT_GUI_FONT)
        font.SetPointSize(font.GetPointSize() * self.GetParent().GetFontSizeMultiple())

        if self.GetParent().GetFontBold():
            font.SetWeight(wx.FONTWEIGHT_BOLD)
        elif self.HasAGWFlag(INB_BOLD_TAB_SELECTION) and selected:
            font.SetWeight(wx.FONTWEIGHT_BOLD)

        dc.SetFont(font)

        # First we define the rectangle for the text
        w, h = dc.GetTextExtent(text)

        #-------------------------------------------------------------------------
        # Label layout:
        # [ nPadding | Image | nPadding | Text | nPadding ]
        #-------------------------------------------------------------------------

        # Text bounding rectangle
        textRect.x += nPadding
        textRect.y = rect.y + (rect.height - h)/2
        textRect.width = rect.width - 2 * nPadding

        if bmp.Ok() and not self.HasAGWFlag(INB_SHOW_ONLY_TEXT):
            textRect.x += (bmp.GetWidth() + nPadding)
            textRect.width -= (bmp.GetWidth() + nPadding)

        textRect.height = h

        # Truncate text if needed
        caption = ArtManager.Get().TruncateText(dc, text, textRect.width)

        # Image bounding rectangle
        if bmp.Ok() and not self.HasAGWFlag(INB_SHOW_ONLY_TEXT):

            imgRect.x += nPadding
            imgRect.width = bmp.GetWidth()
            imgRect.y = rect.y + (rect.height - bmp.GetHeight())/2
            imgRect.height = bmp.GetHeight()

        # Draw bounding rectangle
        if selected:

            # First we colour the tab
            dc.SetBrush(wx.Brush(self._coloursMap[INB_ACTIVE_TAB_COLOUR]))

            if self.HasAGWFlag(INB_BORDER):
                dc.SetPen(wx.Pen(self._coloursMap[INB_TABS_BORDER_COLOUR]))
            else:
                dc.SetPen(wx.Pen(self._coloursMap[INB_ACTIVE_TAB_COLOUR]))

            labelRect = wx.Rect(*rect)

            if orientationLeft:
                labelRect.width += 3
            else:
                labelRect.width += 3
                labelRect.x -= 3

            dc.DrawRoundedRectangleRect(labelRect, 3)

            if not orientationLeft and self.HasAGWFlag(INB_DRAW_SHADOW):
                dc.SetPen(wx.BLACK_PEN)
                dc.DrawPoint(labelRect.x + labelRect.width - 1, labelRect.y + labelRect.height - 1)

        # Draw the text & bitmap
        if caption != "":

            if selected:
                dc.SetTextForeground(self._coloursMap[INB_ACTIVE_TEXT_COLOUR])
            else:
                dc.SetTextForeground(self._coloursMap[INB_TEXT_COLOUR])

            dc.DrawText(caption, textRect.x, textRect.y)
            imgInfo.SetTextRect(textRect)

        else:

            imgInfo.SetTextRect(wx.Rect())

        if bmp.Ok() and not self.HasAGWFlag(INB_SHOW_ONLY_TEXT):
            dc.DrawBitmap(bmp, imgRect.x, imgRect.y, True)

        # Drop shadow
        if self.HasAGWFlag(INB_DRAW_SHADOW) and selected:

            sstyle = 0
            if orientationLeft:
                sstyle = BottomShadow
            else:
                sstyle = BottomShadowFull | RightShadow

            if self.HasAGWFlag(INB_WEB_HILITE):

                # Always drop shadow for this style
                ArtManager.Get().DrawBitmapShadow(dc, rect, sstyle)

            else:

                if imgIdx+1 != self._nHoveredImgIdx:
                    ArtManager.Get().DrawBitmapShadow(dc, rect, sstyle)

        # Draw hover effect
        if hover:

            if self.HasAGWFlag(INB_WEB_HILITE) and caption != "":
                self.DrawWebHover(dc, caption, textRect.x, textRect.y, selected)
            else:
                self.DrawRegularHover(dc, rect)

        # Update the page information bout position and size
        imgInfo.SetPosition(rect.GetPosition())
        imgInfo.SetSize(rect.GetSize())

# ---------------------------------------------------------------------------- #
# Class FlatBookBase
# ---------------------------------------------------------------------------- #

[docs]class FlatBookBase(wx.Panel):
    """ Base class for the containing window for L{LabelBook} and L{FlatImageBook}. """

[docs]    def __init__(self, parent, id=wx.ID_ANY, pos=wx.DefaultPosition, size=wx.DefaultSize,
                 style=0, agwStyle=0, name="FlatBookBase"):
        """
        Default class constructor.

        :param `parent`: parent window. Must not be ``None``;
        :param `id`: window identifier. A value of -1 indicates a default value;
        :param `pos`: the control position. A value of (-1, -1) indicates a default position,
         chosen by either the windowing system or wxPython, depending on platform;
        :param `size`: the control size. A value of (-1, -1) indicates a default size,
         chosen by either the windowing system or wxPython, depending on platform;
        :param `style`: the underlying `wx.Panel` window style;
        :param `agwStyle`: the AGW-specific window style. This can be a combination of the
         following bits:

         =========================== =========== ==================================================
         Window Styles               Hex Value   Description
         =========================== =========== ==================================================
         ``INB_BOTTOM``                      0x1 Place labels below the page area. Available only for L{FlatImageBook}.
         ``INB_LEFT``                        0x2 Place labels on the left side. Available only for L{FlatImageBook}.
         ``INB_RIGHT``                       0x4 Place labels on the right side.
         ``INB_TOP``                         0x8 Place labels above the page area.
         ``INB_BORDER``                     0x10 Draws a border around L{LabelBook} or L{FlatImageBook}.
         ``INB_SHOW_ONLY_TEXT``             0x20 Shows only text labels and no images. Available only for L{LabelBook}.
         ``INB_SHOW_ONLY_IMAGES``           0x40 Shows only tab images and no label texts. Available only for L{LabelBook}.
         ``INB_FIT_BUTTON``                 0x80 Displays a pin button to show/hide the book control.
         ``INB_DRAW_SHADOW``               0x100 Draw shadows below the book tabs. Available only for L{LabelBook}.
         ``INB_USE_PIN_BUTTON``            0x200 Displays a pin button to show/hide the book control.
         ``INB_GRADIENT_BACKGROUND``       0x400 Draws a gradient shading on the tabs background. Available only for L{LabelBook}.
         ``INB_WEB_HILITE``                0x800 On mouse hovering, tabs behave like html hyperlinks. Available only for L{LabelBook}.
         ``INB_NO_RESIZE``                0x1000 Don't allow resizing of the tab area.
         ``INB_FIT_LABELTEXT``            0x2000 Will fit the tab area to the longest text (or text+image if you have images) in all the tabs.
         ``INB_BOLD_TAB_SELECTION``       0x4000 Show the selected tab text using a bold font.
         =========================== =========== ==================================================

        :param `name`: the window name.
        """

        self._pages = None
        self._bInitializing = True
        self._pages = None
        self._bForceSelection = False
        self._windows = []
        self._fontSizeMultiple = 1.0
        self._fontBold = False

        style |= wx.TAB_TRAVERSAL
        self._agwStyle = agwStyle

        wx.Panel.__init__(self, parent, id, pos, size, style, name)
        self._bInitializing = False

        self.Bind(wx.EVT_NAVIGATION_KEY, self.OnNavigationKey)

[docs]    def SetAGWWindowStyleFlag(self, agwStyle):
        """
        Sets the window style.

        :param `agwStyle`: can be a combination of the following bits:

         =========================== =========== ==================================================
         Window Styles               Hex Value   Description
         =========================== =========== ==================================================
         ``INB_BOTTOM``                      0x1 Place labels below the page area. Available only for L{FlatImageBook}.
         ``INB_LEFT``                        0x2 Place labels on the left side. Available only for L{FlatImageBook}.
         ``INB_RIGHT``                       0x4 Place labels on the right side.
         ``INB_TOP``                         0x8 Place labels above the page area.
         ``INB_BORDER``                     0x10 Draws a border around L{LabelBook} or L{FlatImageBook}.
         ``INB_SHOW_ONLY_TEXT``             0x20 Shows only text labels and no images. Available only for L{LabelBook}.
         ``INB_SHOW_ONLY_IMAGES``           0x40 Shows only tab images and no label texts. Available only for L{LabelBook}.
         ``INB_FIT_BUTTON``                 0x80 Displays a pin button to show/hide the book control.
         ``INB_DRAW_SHADOW``               0x100 Draw shadows below the book tabs. Available only for L{LabelBook}.
         ``INB_USE_PIN_BUTTON``            0x200 Displays a pin button to show/hide the book control.
         ``INB_GRADIENT_BACKGROUND``       0x400 Draws a gradient shading on the tabs background. Available only for L{LabelBook}.
         ``INB_WEB_HILITE``                0x800 On mouse hovering, tabs behave like html hyperlinks. Available only for L{LabelBook}.
         ``INB_NO_RESIZE``                0x1000 Don't allow resizing of the tab area.
         ``INB_FIT_LABELTEXT``            0x2000 Will fit the tab area to the longest text (or text+image if you have images) in all the tabs.
         ``INB_BOLD_TAB_SELECTION``       0x4000 Show the selected tab text using a bold font.
         =========================== =========== ==================================================

        """

        self._agwStyle = agwStyle

        # Check that we are not in initialization process
        if self._bInitializing:
            return

        if not self._pages:
            return

        # Detach the windows attached to the sizer
        if self.GetSelection() >= 0:
            self._mainSizer.Detach(self._windows[self.GetSelection()])

        self._mainSizer.Detach(self._pages)

        if isinstance(self, LabelBook):
            self._mainSizer = wx.BoxSizer(wx.HORIZONTAL)
        else:
            if agwStyle & INB_LEFT or agwStyle & INB_RIGHT:
                self._mainSizer = wx.BoxSizer(wx.HORIZONTAL)
            else:
                self._mainSizer = wx.BoxSizer(wx.VERTICAL)

        self.SetSizer(self._mainSizer)

        # Add the tab container and the separator
        self._mainSizer.Add(self._pages, 0, wx.EXPAND)

        if isinstance(self, FlatImageBook):
            if agwStyle & INB_LEFT or agwStyle & INB_RIGHT:
                self._pages.SetSizeHints(self._pages._nImgSize * 2, -1)
            else:
                self._pages.SetSizeHints(-1, self._pages._nImgSize * 2)

        # Attach the windows back to the sizer to the sizer
        if self.GetSelection() >= 0:
            self.DoSetSelection(self._windows[self.GetSelection()])

        if agwStyle & INB_FIT_LABELTEXT:
            self.ResizeTabArea()

        self._mainSizer.Layout()
        dummy = wx.SizeEvent()
        wx.PostEvent(self, dummy)
        self._pages.Refresh()

[docs]    def GetAGWWindowStyleFlag(self):
        """
        Returns the L{FlatBookBase} window style.

        :see: L{SetAGWWindowStyleFlag} for a list of possible window style flags.
        """

        return self._agwStyle

[docs]    def HasAGWFlag(self, flag):
        """
        Returns whether a flag is present in the L{FlatBookBase} style.

        :param `flag`: one of the possible L{FlatBookBase} window styles.

        :see: L{SetAGWWindowStyleFlag} for a list of possible window style flags.
        """

        agwStyle = self.GetAGWWindowStyleFlag()
        res = (agwStyle & flag and [True] or [False])[0]
        return res

[docs]    def AddPage(self, page, text, select=False, imageId=-1):
        """
        Adds a page to the book.

        :param `page`: specifies the new page;
        :param `text`: specifies the text for the new page;
        :param `select`: specifies whether the page should be selected;
        :param `imageId`: specifies the optional image index for the new page.

        :note: The call to this function generates the page changing events.
        """

        if not page:
            return

        page.Reparent(self)

        self._windows.append(page)

        if select or len(self._windows) == 1:
            self.SetSelection(len(self._windows)-1)
        else:
            page.Hide()

        self._pages.AddPage(text, select, imageId)
        self.ResizeTabArea()
        self.Refresh()

[docs]    def InsertPage(self, page_idx, page, text, select=False, imageId=-1):
        """
        Inserts a page into the book at the specified position.

        :param `page_idx`: specifies the position for the new page;
        :param `page`: specifies the new page;
        :param `text`: specifies the text for the new page;
        :param `select`: specifies whether the page should be selected;
        :param `imageId`: specifies the optional image index for the new page.

        :note: The call to this function generates the page changing events.
        """

        if not page:
            return

        page.Reparent(self)

        self._windows.insert(page_idx, page)

        if select or len(self._windows) == 1:
            self.SetSelection(page_idx)
        else:
            page.Hide()

        self._pages.InsertPage(page_idx, text, select, imageId)
        self.ResizeTabArea()
        self.Refresh()

[docs]    def DeletePage(self, page):
        """
        Deletes the specified page, and the associated window.

        :param `page`: an integer specifying the page to be deleted.

        :note: The call to this function generates the page changing events.
        """

        if page >= len(self._windows) or page < 0:
            return

        # Fire a closing event
        event = ImageNotebookEvent(wxEVT_IMAGENOTEBOOK_PAGE_CLOSING, self.GetId())
        event.SetSelection(page)
        event.SetEventObject(self)
        self.GetEventHandler().ProcessEvent(event)

        # The event handler allows it?
        if not event.IsAllowed():
            return False

        self.Freeze()

        # Delete the requested page
        pageRemoved = self._windows[page]

        # If the page is the current window, remove it from the sizer
        # as well
        if page == self.GetSelection():
            self._mainSizer.Detach(pageRemoved)

        # Remove it from the array as well
        self._windows.pop(page)

        # Now we can destroy it in wxWidgets use Destroy instead of delete
        pageRemoved.Destroy()
        self._mainSizer.Layout()

        self._pages.DoDeletePage(page)
        self.ResizeTabArea()
        self.Thaw()

        # Fire a closed event
        closedEvent = ImageNotebookEvent(wxEVT_IMAGENOTEBOOK_PAGE_CLOSED, self.GetId())
        closedEvent.SetSelection(page)
        closedEvent.SetEventObject(self)
        self.GetEventHandler().ProcessEvent(closedEvent)

[docs]    def RemovePage(self, page):
        """
        Deletes the specified page, without deleting the associated window.

        :param `page`: an integer specifying the page to be removed.

        :note: The call to this function generates the page changing events.
        """

        if page >= len(self._windows):
            return False

        # Fire a closing event
        event = ImageNotebookEvent(wxEVT_IMAGENOTEBOOK_PAGE_CLOSING, self.GetId())
        event.SetSelection(page)
        event.SetEventObject(self)
        self.GetEventHandler().ProcessEvent(event)

        # The event handler allows it?
        if not event.IsAllowed():
            return False

        self.Freeze()

        # Remove the requested page
        pageRemoved = self._windows[page]

        # If the page is the current window, remove it from the sizer
        # as well
        if page == self.GetSelection():
            self._mainSizer.Detach(pageRemoved)

        # Remove it from the array as well
        self._windows.pop(page)
        self._mainSizer.Layout()
        self.ResizeTabArea()
        self.Thaw()

        self._pages.DoDeletePage(page)

        # Fire a closed event
        closedEvent = ImageNotebookEvent(wxEVT_IMAGENOTEBOOK_PAGE_CLOSED, self.GetId())
        closedEvent.SetSelection(page)
        closedEvent.SetEventObject(self)
        self.GetEventHandler().ProcessEvent(closedEvent)

        return True

[docs]    def ResizeTabArea(self):
        """ Resizes the tab area if the control has the ``INB_FIT_LABELTEXT`` style set. """

        agwStyle = self.GetAGWWindowStyleFlag()

        if agwStyle & INB_FIT_LABELTEXT == 0:
            return

        if agwStyle & INB_LEFT or agwStyle & INB_RIGHT:
            dc = wx.MemoryDC()
            dc.SelectObject(wx.EmptyBitmap(1, 1))
            font = wx.SystemSettings_GetFont(wx.SYS_DEFAULT_GUI_FONT)
            font.SetPointSize(font.GetPointSize()*self._fontSizeMultiple)
            if self.GetFontBold() or agwStyle & INB_BOLD_TAB_SELECTION:
                font.SetWeight(wx.FONTWEIGHT_BOLD)
            dc.SetFont(font)
            maxW = 0

            for page in xrange(self.GetPageCount()):
                caption = self._pages.GetPageText(page)
                w, h = dc.GetTextExtent(caption)
                maxW = max(maxW, w)

            maxW += 24 #TODO this is 6*4 6 is nPadding from drawlabel

            if not agwStyle & INB_SHOW_ONLY_TEXT:
                maxW += self._pages._nImgSize * 2

            maxW = max(maxW, 100)
            self._pages.SetSizeHints(maxW, -1)
            self._pages._nTabAreaWidth = maxW

[docs]    def DeleteAllPages(self):
        """ Deletes all the pages in the book. """

        if not self._windows:
            return

        self.Freeze()

        for win in self._windows:
            win.Destroy()

        self._windows = []
        self.Thaw()

        # remove old selection
        self._pages.ClearAll()
        self._pages.Refresh()

[docs]    def SetSelection(self, page):
        """
        Changes the selection from currently visible/selected page to the page
        given by page.

        :param `page`: an integer specifying the page to be selected.

        :note: The call to this function generates the page changing events.
        """

        if page >= len(self._windows):
            return

        if not self.GetEnabled(page):
            return

        if page == self.GetSelection() and not self._bForceSelection:
            return

        oldSelection = self.GetSelection()

        # Generate an event that indicates that an image is about to be selected
        event = ImageNotebookEvent(wxEVT_IMAGENOTEBOOK_PAGE_CHANGING, self.GetId())
        event.SetSelection(page)
        event.SetOldSelection(oldSelection)
        event.SetEventObject(self)
        self.GetEventHandler().ProcessEvent(event)

        # The event handler allows it?
        if not event.IsAllowed() and not self._bForceSelection:
            return

        self.DoSetSelection(self._windows[page])
        # Now we can update the new selection
        self._pages._nIndex = page

        # Refresh calls the OnPaint of this class
        self._pages.Refresh()

        # Generate an event that indicates that an image was selected
        eventChanged = ImageNotebookEvent(wxEVT_IMAGENOTEBOOK_PAGE_CHANGED, self.GetId())
        eventChanged.SetEventObject(self)
        eventChanged.SetOldSelection(oldSelection)
        eventChanged.SetSelection(page)
        self.GetEventHandler().ProcessEvent(eventChanged)

[docs]    def AssignImageList(self, imglist):
        """
        Assigns an image list to the control.

        :param `imglist`: an instance of `wx.ImageList`.
        """

        self._pages.AssignImageList(imglist)

        # Force change
        self.SetAGWWindowStyleFlag(self.GetAGWWindowStyleFlag())

[docs]    def GetSelection(self):
        """ Returns the current selection. """

        if self._pages:
            return self._pages._nIndex
        else:
            return -1

[docs]    def DoSetSelection(self, window):
        """
        Select the window by the provided pointer.

        :param `window`: an instance of `wx.Window`.
        """

        curSel = self.GetSelection()
        agwStyle = self.GetAGWWindowStyleFlag()
        # Replace the window in the sizer
        self.Freeze()

        # Check if a new selection was made
        bInsertFirst = (agwStyle & INB_BOTTOM or agwStyle & INB_RIGHT)

        if curSel >= 0:

            # Remove the window from the main sizer
            self._mainSizer.Detach(self._windows[curSel])
            self._windows[curSel].Hide()

        if bInsertFirst:
            self._mainSizer.Insert(0, window, 1, wx.EXPAND)
        else:
            self._mainSizer.Add(window, 1, wx.EXPAND)

        window.Show()
        self._mainSizer.Layout()
        self.Thaw()

[docs]    def GetImageList(self):
        """ Returns the associated image list. """

        return self._pages.GetImageList()

[docs]    def GetPageCount(self):
        """ Returns the number of pages in the book. """

        return len(self._windows)

[docs]    def GetFontBold(self):
        """ Gets the font bold status. """

        return self._fontBold

[docs]    def SetFontBold(self, bold):
        """
        Sets whether the page captions are bold or not.

        :param `bold`: ``True`` or ``False``.
        """

        self._fontBold = bold

[docs]    def GetFontSizeMultiple(self):
        """ Gets the font size multiple for the page captions. """

        return self._fontSizeMultiple

[docs]    def SetFontSizeMultiple(self, multiple):
        """
        Sets the font size multiple for the page captions.

        :param `multiple`: The multiple to be applied to the system font to get the our font size.
        """

        self._fontSizeMultiple = multiple

[docs]    def SetPageImage(self, page, imageId):
        """
        Sets the image index for the given page.

        :param `page`: an integer specifying the page index;
        :param `image`: an index into the image list.
        """

        self._pages.SetPageImage(page, imageId)
        self._pages.Refresh()

[docs]    def SetPageText(self, page, text):
        """
        Sets the text for the given page.

        :param `page`: an integer specifying the page index;
        :param `text`: the new tab label.
        """

        self._pages.SetPageText(page, text)
        self._pages.Refresh()

[docs]    def GetPageText(self, page):
        """
        Returns the text for the given page.

        :param `page`: an integer specifying the page index.
        """

        return self._pages.GetPageText(page)

[docs]    def GetPageImage(self, page):
        """
        Returns the image index for the given page.

        :param `page`: an integer specifying the page index.
        """

        return self._pages.GetPageImage(page)

[docs]    def GetEnabled(self, page):
        """
        Returns whether a tab is enabled or not.

        :param `page`: an integer specifying the page index.
        """

        return self._pages.GetEnabled(page)

[docs]    def EnableTab(self, page, enabled=True):
        """
        Enables or disables a tab.

        :param `page`: an integer specifying the page index;
        :param `enabled`: ``True`` to enable a tab, ``False`` to disable it.
        """

        if page >= len(self._windows):
            return

        self._windows[page].Enable(enabled)
        self._pages.EnableTab(page, enabled)

[docs]    def GetPage(self, page):
        """
        Returns the window at the given page position.

        :param `page`: an integer specifying the page to be returned.
        """

        if page >= len(self._windows):
            return

        return self._windows[page]

[docs]    def GetCurrentPage(self):
        """ Returns the currently selected notebook page or ``None``. """

        if self.GetSelection() < 0:
            return

        return self.GetPage(self.GetSelection())

[docs]    def OnNavigationKey(self, event):
        """
        Handles the ``wx.EVT_NAVIGATION_KEY`` event for L{FlatBookBase}.

        :param `event`: a `wx.NavigationKeyEvent` event to be processed.
        """

        if event.IsWindowChange():
            if self.GetPageCount() == 0:
                return

            # change pages
            self.AdvanceSelection(event.GetDirection())

        else:
            event.Skip()

[docs]    def AdvanceSelection(self, forward=True):
        """
        Cycles through the tabs.

        :param `forward`: if ``True``, the selection is advanced in ascending order
         (to the right), otherwise the selection is advanced in descending order.

        :note: The call to this function generates the page changing events.
        """

        nSel = self.GetSelection()

        if nSel < 0:
            return

        nMax = self.GetPageCount() - 1

        if forward:
            newSelection = (nSel == nMax and [0] or [nSel + 1])[0]
        else:
            newSelection = (nSel == 0 and [nMax] or [nSel - 1])[0]

        self.SetSelection(newSelection)

[docs]    def ChangeSelection(self, page):
        """
        Changes the selection for the given page, returning the previous selection.

        :param `page`: an integer specifying the page to be selected.

        :note: The call to this function does not generate the page changing events.
        """

        if page < 0 or page >= self.GetPageCount():
            return

        oldPage = self.GetSelection()
        self.DoSetSelection(page)

        return oldPage

    CurrentPage = property(GetCurrentPage, doc="See `GetCurrentPage`")
    Page = property(GetPage, doc="See `GetPage`")
    PageCount = property(GetPageCount, doc="See `GetPageCount`")
    PageImage = property(GetPageImage, SetPageImage, doc="See `GetPageImage, SetPageImage`")
    PageText = property(GetPageText, SetPageText, doc="See `GetPageText, SetPageText`")
    Selection = property(GetSelection, SetSelection, doc="See `GetSelection, SetSelection`")

# ---------------------------------------------------------------------------- #
# Class FlatImageBook
# ---------------------------------------------------------------------------- #

[docs]class FlatImageBook(FlatBookBase):
    """
    Default implementation of the image book, it is like a `wx.Notebook`, except that
    images are used to control the different pages. This container is usually used
    for configuration dialogs etc.

    :note: Currently, this control works properly for images of size 32x32 and bigger.
    """

[docs]    def __init__(self, parent, id=wx.ID_ANY, pos=wx.DefaultPosition, size=wx.DefaultSize,
                 style=0, agwStyle=0, name="FlatImageBook"):
        """
        Default class constructor.

        :param `parent`: parent window. Must not be ``None``;
        :param `id`: window identifier. A value of -1 indicates a default value;
        :param `pos`: the control position. A value of (-1, -1) indicates a default position,
         chosen by either the windowing system or wxPython, depending on platform;
        :param `size`: the control size. A value of (-1, -1) indicates a default size,
         chosen by either the windowing system or wxPython, depending on platform;
        :param `style`: the underlying `wx.Panel` window style;
        :param `agwStyle`: the AGW-specific window style. This can be a combination of the
         following bits:

         =========================== =========== ==================================================
         Window Styles               Hex Value   Description
         =========================== =========== ==================================================
         ``INB_BOTTOM``                      0x1 Place labels below the page area. Available only for L{FlatImageBook}.
         ``INB_LEFT``                        0x2 Place labels on the left side. Available only for L{FlatImageBook}.
         ``INB_RIGHT``                       0x4 Place labels on the right side.
         ``INB_TOP``                         0x8 Place labels above the page area.
         ``INB_BORDER``                     0x10 Draws a border around L{LabelBook} or L{FlatImageBook}.
         ``INB_SHOW_ONLY_TEXT``             0x20 Shows only text labels and no images. Available only for L{LabelBook}.
         ``INB_SHOW_ONLY_IMAGES``           0x40 Shows only tab images and no label texts. Available only for L{LabelBook}.
         ``INB_FIT_BUTTON``                 0x80 Displays a pin button to show/hide the book control.
         ``INB_DRAW_SHADOW``               0x100 Draw shadows below the book tabs. Available only for L{LabelBook}.
         ``INB_USE_PIN_BUTTON``            0x200 Displays a pin button to show/hide the book control.
         ``INB_GRADIENT_BACKGROUND``       0x400 Draws a gradient shading on the tabs background. Available only for L{LabelBook}.
         ``INB_WEB_HILITE``                0x800 On mouse hovering, tabs behave like html hyperlinks. Available only for L{LabelBook}.
         ``INB_NO_RESIZE``                0x1000 Don't allow resizing of the tab area.
         ``INB_FIT_LABELTEXT``            0x2000 Will fit the tab area to the longest text (or text+image if you have images) in all the tabs.
         ``INB_BOLD_TAB_SELECTION``       0x4000 Show the selected tab text using a bold font.
         =========================== =========== ==================================================

        :param `name`: the window name.
        """

        FlatBookBase.__init__(self, parent, id, pos, size, style, agwStyle, name)

        self._pages = self.CreateImageContainer()

        if agwStyle & INB_LEFT or agwStyle & INB_RIGHT:
            self._mainSizer = wx.BoxSizer(wx.HORIZONTAL)
        else:
            self._mainSizer = wx.BoxSizer(wx.VERTICAL)

        self.SetSizer(self._mainSizer)

        # Add the tab container to the sizer
        self._mainSizer.Add(self._pages, 0, wx.EXPAND)

        if agwStyle & INB_LEFT or agwStyle & INB_RIGHT:
            self._pages.SetSizeHints(self._pages.GetImageSize() * 2, -1)
        else:
            self._pages.SetSizeHints(-1, self._pages.GetImageSize() * 2)

        self._mainSizer.Layout()

[docs]    def CreateImageContainer(self):
        """ Creates the image container class for L{FlatImageBook}. """

        return ImageContainer(self, wx.ID_ANY, agwStyle=self.GetAGWWindowStyleFlag())

# ---------------------------------------------------------------------------- #
# Class LabelBook
# ---------------------------------------------------------------------------- #

[docs]class LabelBook(FlatBookBase):
    """
    An implementation of a notebook control - except that instead of having
    tabs to show labels, it labels to the right or left (arranged horizontally).
    """

[docs]    def __init__(self, parent, id=wx.ID_ANY, pos=wx.DefaultPosition, size=wx.DefaultSize,
                 style=0, agwStyle=0, name="LabelBook"):
        """
        Default class constructor.

        :param `parent`: parent window. Must not be ``None``;
        :param `id`: window identifier. A value of -1 indicates a default value;
        :param `pos`: the control position. A value of (-1, -1) indicates a default position,
         chosen by either the windowing system or wxPython, depending on platform;
        :param `size`: the control size. A value of (-1, -1) indicates a default size,
         chosen by either the windowing system or wxPython, depending on platform;
        :param `style`: the underlying `wx.Panel` window style;
        :param `agwStyle`: the AGW-specific window style. This can be a combination of the
         following bits:

         =========================== =========== ==================================================
         Window Styles               Hex Value   Description
         =========================== =========== ==================================================
         ``INB_BOTTOM``                      0x1 Place labels below the page area. Available only for L{FlatImageBook}.
         ``INB_LEFT``                        0x2 Place labels on the left side. Available only for L{FlatImageBook}.
         ``INB_RIGHT``                       0x4 Place labels on the right side.
         ``INB_TOP``                         0x8 Place labels above the page area.
         ``INB_BORDER``                     0x10 Draws a border around L{LabelBook} or L{FlatImageBook}.
         ``INB_SHOW_ONLY_TEXT``             0x20 Shows only text labels and no images. Available only for L{LabelBook}.
         ``INB_SHOW_ONLY_IMAGES``           0x40 Shows only tab images and no label texts. Available only for L{LabelBook}.
         ``INB_FIT_BUTTON``                 0x80 Displays a pin button to show/hide the book control.
         ``INB_DRAW_SHADOW``               0x100 Draw shadows below the book tabs. Available only for L{LabelBook}.
         ``INB_USE_PIN_BUTTON``            0x200 Displays a pin button to show/hide the book control.
         ``INB_GRADIENT_BACKGROUND``       0x400 Draws a gradient shading on the tabs background. Available only for L{LabelBook}.
         ``INB_WEB_HILITE``                0x800 On mouse hovering, tabs behave like html hyperlinks. Available only for L{LabelBook}.
         ``INB_NO_RESIZE``                0x1000 Don't allow resizing of the tab area.
         ``INB_FIT_LABELTEXT``            0x2000 Will fit the tab area to the longest text (or text+image if you have images) in all the tabs.
         ``INB_BOLD_TAB_SELECTION``       0x4000 Show the selected tab text using a bold font.
         =========================== =========== ==================================================

        :param `name`: the window name.
        """

        FlatBookBase.__init__(self, parent, id, pos, size, style, agwStyle, name)

        self._pages = self.CreateImageContainer()

        # Label book specific initialization
        self._mainSizer = wx.BoxSizer(wx.HORIZONTAL)
        self.SetSizer(self._mainSizer)

        # Add the tab container to the sizer
        self._mainSizer.Add(self._pages, 0, wx.EXPAND)
        self._pages.SetSizeHints(self._pages.GetTabAreaWidth(), -1)

        # Initialize the colours maps
        self._pages.InitializeColours()

        self.Bind(wx.EVT_SIZE, self.OnSize)

[docs]    def CreateImageContainer(self):
        """ Creates the image container (LabelContainer) class for L{FlatImageBook}. """

        return LabelContainer(self, wx.ID_ANY, agwStyle=self.GetAGWWindowStyleFlag())

[docs]    def SetColour(self, which, colour):
        """
        Sets the colour for the specified parameter.

        :param `which`: the colour key;
        :param `colour`: a valid `wx.Colour` instance.

        :see: L{LabelContainer.SetColour} for a list of valid colour keys.
        """

        self._pages.SetColour(which, colour)

[docs]    def GetColour(self, which):
        """
        Returns the colour for the specified parameter.

        :param `which`: the colour key.

        :see: L{LabelContainer.SetColour} for a list of valid colour keys.
        """

        return self._pages.GetColour(which)

[docs]    def OnSize(self, event):
        """
        Handles the ``wx.EVT_SIZE`` event for L{LabelBook}.

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

        self._pages.Refresh()
        event.Skip()

Navigation

  • index
  • modules |
  • Home |
  • Gallery |
  • Contents»
  • Module code »
  • labelbook


multidirdialog

  • modules |
  • Home |
  • Gallery |
  • Contents»
  • Module code »
  • multidirdialog

Source code for multidirdialog

# --------------------------------------------------------------------------------- #
# MULTIDIRDIALOG wxPython IMPLEMENTATION
#
# Andrea Gavana, @ 07 October 2008
# Latest Revision: 17 Aug 2011, 15.00 GMT
#
#
# TODO List
#
# 1) Implement an meaningful action for the "Make New Folder" button, but this
#    requires a strong integration with Explorer, at least on Windows;
#
# 2) Be more user-friendly with special folders as the Desktop, My Documents etc...
#
#
# 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
# --------------------------------------------------------------------------------- #

"""
This class represents a possible replacement for `wx.DirDialog`, with the additional
ability of selecting multiple folders at once.

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

This class represents a possible replacement for `wx.DirDialog`, with the additional
ability of selecting multiple folders at once. It may be useful when you wish to
present to the user a directory browser which allows multiple folder selections.
L{MultiDirDialog} sports the following features:

* Ability to select a single or mutliple folders, depending on the style passed;
* More colourful and eye-catching buttons;
* Good old Python code :-D .

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

Usage
=====

Usage example::

    import os
    import wx

    import wx.lib.agw.multidirdialog as MDD

    # Our normal wxApp-derived class, as usual
    app = wx.App(0)

    dlg = MDD.MultiDirDialog(None, title="Custom MultiDirDialog", defaultPath=os.getcwd(),
                             agwStyle=MDD.DD_MULTIPLE|MDD.DD_DIR_MUST_EXIST)

    if dlg.ShowModal() != wx.ID_OK:
        print "You Cancelled The Dialog!"
        dlg.Destroy()
        return

    paths = dlg.GetPaths()
    for indx, path in enumerate(paths):
        print "Path %d: %s"%(indx+1, path)

    dlg.Destroy()

    app.MainLoop()

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

L{MultiDirDialog} has been tested on the following platforms:
  * Windows (Windows XP).

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

This class supports the following window styles:

===================== =========== ==================================================
Window Styles         Hex Value   Description
===================== =========== ==================================================
``DD_NEW_DIR_BUTTON``       0x000 Enable/disable the "Make new folder" button
``DD_DIR_MUST_EXIST``       0x200 The dialog will allow the user to choose only an existing folder. When this style is not given, a "Create new directory" button is added to the dialog (on Windows) or some other way is provided to the user to type the name of a new folder.
``DD_MULTIPLE``             0x400 Allows the selection of multiple folders.
===================== =========== ==================================================

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

`No custom events are available for this class.`

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

L{MultiDirDialog} is distributed under the wxPython license.

Latest Revision: Andrea Gavana @ 17 Aug 2011, 15.00 GMT

Version 0.3

"""

import os
import wx
import wx.lib.buttons as buttons

from wx.lib.embeddedimage import PyEmbeddedImage

# MultiDirDialog styles
DD_MULTIPLE = 1024
""" Allows the selection of multiple folders. """
DD_DEFAULT_STYLE = wx.DD_DEFAULT_STYLE
""" Equivalent to a combination of ``wx.DEFAULT_DIALOG_STYLE`` and ``wx.RESIZE_BORDER``. """
DD_DIR_MUST_EXIST = wx.DD_DIR_MUST_EXIST
""" The dialog will allow the user to choose only an existing folder. When this style""" \
""" is not given, a "Create new directory" button is added to the dialog (on Windows)""" \
""" or some other way is provided to the user to type the name of a new folder. """
DD_NEW_DIR_BUTTON = wx.DD_NEW_DIR_BUTTON

_ = wx.GetTranslation

_cancel = PyEmbeddedImage(
    "iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAABHNCSVQICAgIfAhkiAAAA1dJ"
    "REFUOI11019oEwccB/Dv3eUuyZ2XpfljsmJ7JY01KZYWty6bdMwnp1X34JNS5sPAsmYruOnL"
    "3kTGcPg6Bdkexqql4EPdBuKbVG0xLmpoWjbW0D+S1Jg24RJzuSR3l58PtpsI/l5/fB5+3x9f"
    "AEDc7VauhMP3prq7q9+1t5/AW+aiLB+ZDocrU6HQk4tAFAC4s8Gg0uVyXTsZiw190Nsr6JnM"
    "kZAkrd6rVtOv4wuyfLS/rW3y6Oioq2tgILiRyXy4v1yexU979yaKIyNEiQRRsUjG2Bjddrtr"
    "532+k9v4B1kevu33l+vnzhFtbBAtL9OLS5douq9v0eZ1OPo8Xi8gSUClAls8jk+qVad148bP"
    "33s8TcY0K32mOTV07JhsP3UKKJUAy8IORYF3584erodopaGqh7qzWYEJBgGGgW3fPrQ/eyY0"
    "5uePewzjxIGDB0U5HgcsC1BV0MOH+GtiojF/9+433P1qNd1pGCvs5uawUijwbDAIWBZsAwPw"
    "5nJsRyBgc8fjYLZwK5lE6uZN88Hc3LdfmeYVDgDu12oLXUSrxvPnw8r6uo3z+cAQwRGJQOzv"
    "B0sEKhZhJRJI3rplJlKpM+OWdRkAuO2gZnQ93UO02CgUjr9bLHKCzweGZcGYJqhchp5I4NGd"
    "O9bjpaUvxol+2Xa211/FAKolSa0XySSq+TzYYBAAYGkaUKnA5LgWA6hvmP//PKgokx9tbspq"
    "Pg8NgL61c0gSJL8f73R04O9KRV9Mp0+PtlrX/zvhgigO749GJ4dKJVc9l0MTgAVAZBg4BQEk"
    "SeCcTjAAOhWF5/3+w7FsdvkPogXuR7f7s/d6eycPqKqrubKC+hZ28DxydnurzHFWwG5niefB"
    "CALYVgu7wmGe2toOfby2lrVFIpFrn9brcmNpCU0ALIAdooiMw9FI1etfkmGUbaY5EXY4JIth"
    "YAIw1tcxODgoEcddZeua9rQqCGB5HgwA0e3GmsdjPtH1s1/Xar+ON5vTi6p6+qmm6U5JAksE"
    "VhBQbzahl0p57n1Nm9kQxVhXINAucxzSLpeZLBTOxHX98nbAfxItxMrlVV4UD+/q7OTJ58Pc"
    "7Ow/uVTq81c1FYTo76HQo5k9expXnc6xt9X5OsuOPIhGtZndu//9DYgBwEt1gHq0YITgmAAA"
    "AABJRU5ErkJggg==")

#----------------------------------------------------------------------
_ok = PyEmbeddedImage(
    "iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAABHNCSVQICAgIfAhkiAAAAjdJ"
    "REFUOI2tksFLk3Ecxp+97975vmuve1dWuiUTNIy1JlsLpkZG0aXLbv0B0aVDUMfVQTp0jJpF"
    "EHl5LxUZgZcuQjAID4KUyWwyEU3d9m7O5d733dze97dfB1siJSn1nJ/P5+ELX+Afwx6YuAMB"
    "AVgwjcaBBdIovP2eyKMLPYNdM+7kNKZA9i3gR+ENCeF4Hx+8VigVBgrKWrXKGp/2JeCfwhsW"
    "Q/HTQiCaVTOYUiZtDuoMQqefrc1S9+uOEGNSRzqd+4j72/c1l4OOQNwn+aOFWg5TdBJEIKbH"
    "dI9zHLMt6H3lHrjScfU5x3DSmOXNrVUUxwFQ6S3vDdh9cZ/zTHSz8R0pMguGMKaRMuX5peQ9"
    "ZULPW8+PnB286L78zH/M76/DwCYtjSTefaAOQZjpEDofn5J8UR0qViqLoCpLql+IXFzS72IC"
    "eQCwssR2NFfOtNXsFZx09SLkDnfSlsYTluUy7a3Hz6mWMrLGKswiJaV0WS6Uyr9gAGC7It0L"
    "WrWYm99K9VdcqugSD8Pd6nG6RNeJCq9ZstwqNL1CMl/z8npdiRkPd2AAYJcTy41FcSVZt+lK"
    "na9FaLspCg4ehDew3qJgs6qStUxerhItlr+h74KB5iPNgVZuGkm6QpQWmy3i8AoiY7dA1XTy"
    "LZuVGYHGZi8t/gbvCABgDFS7vpVEgSgS29bv5CR7XtmQjxxyxt77En+Edwt+Svpua3MbRT5T"
    "a9QXPGL7gxc9L/eE98wwHWaG6JD1783/kB9qTvueLt8LjwAAAABJRU5ErkJggg==")

#----------------------------------------------------------------------
_cdrom = PyEmbeddedImage(
    "iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAABHNCSVQICAgIfAhkiAAAArRJ"
    "REFUOI11kc9rm3Ucx1/f5/eTLV2aJ2vqVseGWzeYDAbCCq2THQqiuB3mP+DBQ3ss3rysILLb"
    "2I5FhKHkNFmFHkrFoVDQDautI02ZWqGJ7WzWEkzy/M73u1NKbNj79Dl8Xi8+P+BQhoeHj09N"
    "Td1aWlr6s1qtNjY3N/dLpdIvExMTHwPG4f7/ZWRk5M35+fmnqidSSqWUUlEUqdnZ2W+B3Kv4"
    "wbm5uaeNRkO1220VRZEKw1D5vq/CMDwQTk9PfwVoffTk5ORMpVJR5XJZ1Wo1FYahCoJAtVot"
    "laapSpJEBUGgNjY2VLFYvNblDkzj4+PvJ0kCgJSSvb09tv7eiuv/1tMgDGg2m+zu7mKaJmNj"
    "Yx90uYOj5PP5k2ma4jgOuqbT/K/JvYd3n4+eOu9cH7s+lMiE/f19hBAUCoUzfYIkSYJ8Po+u"
    "69i2TZIk3Hz3w1MqUtT36iRpgu/7ZDIZfN+P+1ZYXV39bWBgANd1OZo9ilfwuDB0gYunL+K4"
    "Dq1WCyEEcRyztra22idYWFj4srxW9j3PQ0pJo9EADWzHxvM8juWO4doZln9c3llfX/+my+nd"
    "IgzDrUpceeftS1ffcHSX+os6Ukosy8I0THJHBnn87Cduf/H5/dZO++s+AcA/V2sfbYa/nmFb"
    "QwYamjJACWrbVVY2HvMDiyxXnvzMXyz2HRGw8ifJ+6N/sNi+QzE4jbd9Auu5g3Jh6OxrjGZP"
    "4HgUgh6oV2B++tZngxOXr2AbBpZpYGomujIR0kTFOqmQ/P56NVfiQb8gm80640fey9nPLKI4"
    "IkKhAKk6CDocHyqQcVyuFK8NlnhgAOnhCag36k6pdJ92u43ruliWhRACgWDmkxl27G2anVam"
    "93uih9dv3Lh569y5s5fjuCMNQ6BpIIROp9NB13XQ0R599+j7lZUnd7rQS0kMSYjIJmZ4AAAA"
    "AElFTkSuQmCC")

#----------------------------------------------------------------------
_computer = PyEmbeddedImage(
    "iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAABHNCSVQICAgIfAhkiAAAAshJ"
    "REFUOI1dk91PXGUQxn/ve979YkHXmhZ325oUa9Wlxg9q8caoCRde9Hb/Bv4KQ8J/AXdceFF6"
    "YYJXNCYWE0xITAxt1cjXKpiYsnQpH3v2sOfMTC8WAZ2rmWSeZ56ZJ+MAzKwEXIHEQ5ELYedp"
    "QpKcV8Vise2cOwwAnU63sdFsTx0cnpiJoipkqkiaIaa0Wh2etQ4tyxRVo1xy0eefXf0G+DoA"
    "ZJlea/7VGRksF1B1iICIQwUyEb79boMfl/8khDy4wLVamdF3X33LzHwAUJQ47k82U1QVkX7e"
    "3u+y2XyB9w7THkZGlnkUNYDw705HHeXgqIdZH6wqmCq/r7XZPzBCroRKSvDKrZsVIt/HnREc"
    "x8bRcYaZoCKICCIZf2wcY65IFAIQeOdWhfdH30D1PwSeuOvYfS5wqkBEiOMeu3t6Oj2jXC4x"
    "+l6NblfO7Al9OMSJp9V2YJwe0XhxIPSyHFEAH2Vcvz5AL4vY2z85RV1YodM1dp8bDodI34nj"
    "Y4+LSkQuUCwYUcjz9z8ppYLiLipQlLiT0NpLCCEHOFQDIuCDxzRgTtnd6zt1+RL4KLqgQDP9"
    "6oscI28mmPVwPiKKgoUw4CLvyLLURFKX9nqc9E4oBCUfsnMbvfff3/lgoHK50vLLPy3zbLcV"
    "jdy48eHdjz75slAouidPnj7+7denj1wUpXc+HrPq1ZqrDlcfOec0AFQqlZ8bjcYvW1tbgyJy"
    "d3x8/F6pOHBlsPyKS9MeWZq+liS9oZWVlYcP7j/4YWJiYn92djY9e4xGoxEBQ8Db09PTC5ub"
    "m7a+vmZLS0u2uLhoq6urtr29bXNzc4+HhoY+BS6NjY3lgLNjMj8/Hy0sLBTb7fbtarV6r16v"
    "387n86+LiHfOHTabzfW1tbWHuVxueXh4uDMzM5M55+yM4GJMTU35OI7LOzs7AyLiarVaUq/X"
    "O5OTk+n/e18CKWqFGqiV9Q4AAAAASUVORK5CYII=")

#----------------------------------------------------------------------
_folder_close = PyEmbeddedImage(
    "iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAABHNCSVQICAgIfAhkiAAAAcBJ"
    "REFUOI2Nk0FrE1EQx3+zL7vbmFKRQkE/gyfpISL4WYJHsQfPvXkQe6go+AnEi6dcBBEkhYgS"
    "oQfFeqo0VJRobaspm2R339sdD9u0IclC/zAwzLz5zbzhPeFUnU5HuYDq9brMBB+/+KQXVavV"
    "+jBZWxk79zffl3Z9dO8GQbCAiAAEM4DvvyI21m4SpyCiaK6ogqqiwN2nWzxbu0W1WpuBn00w"
    "ih3H/YwkcbgMnFOcU5K0yKdJTLVawzk3H3D8z9GPHKqKy3QGYK0Fiqkm5Y2do77l3ec+mQhD"
    "q+eWFgXjzr1ebzgXgBG2u0O+7A/JRYhzCjttqJrTbDb3G43G7blXyEQIlkI+dmNiPK5dqeBE"
    "sJoXO7CGdru9VbrEXDzCyyEisPPH8XOgrCwaFgysXl/lwcttLqWjmUd0BnCeh78UYgQQiJxy"
    "cpJj8gxcUZdbVw5Q47FYM1REESBTSJ0htYZkVCxChXKAXxGWq4bAnAPiDAbWMPCFEbD7bfew"
    "FPD34Hfa3TuKlmth4PsVycWTQYoeDp39EXnpVVh522pvTgPGI4V3Nt7E08lJvXr+ZP3g6+uH"
    "ZYB5EsCn+DwhEAHJ9KH/LOgEF+oT+k8AAAAASUVORK5CYII=")

#----------------------------------------------------------------------
_folder_open = PyEmbeddedImage(
    "iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAABHNCSVQICAgIfAhkiAAAAvdJ"
    "REFUOI1tU01o23UYft7/75ekqXVJWsO6HaZWzDyIih4UCkJBGIroUATxWPEyLx6EDZzz5Dzr"
    "xB3FkygoCA7ZR0A3g60zWdutbrZLTNOvJI1pmvyT/8fv4/WQFFzwgZf36zm8HzyEeyEAEAAD"
    "gAexM/B6iEsDAwak4eZwzXk48/gTr7w5+04qlUoMkwEgnnnyuekPz372xbGXjr8GAKPp9OSL"
    "L796/PQnn57/5Y/lv9q+tp3A8KEHM48BqcT4o888CwA49taJ04vFeqPta22s5Wtz+cL5r77/"
    "YW3HdY213Pa1Xd5w+WK+Yr/NremzX17MLZVqrQu5m/MEgM6c+yb70btvzLR6RlmtEInGhKvg"
    "lDcb2Nr1jR+yTSbvc6YeGHGOpOMYjZAlInEhm7sm3/7g8+/em319ZqPR061OV5Z3Amq4yhoW"
    "eiI1JqYOJZ3JiTFxIMasNEMb0FbHU2OjI6LWaAdyYXHpTk8T1qpN+unmHo4emUT64LhzOCGd"
    "iNM/T3VPoWZCsk6Eo8KBUobageev77Q6cnE++2O+2DwVeBCuZ3g8GYfraax4/a9FRP8ZQgDM"
    "ISJSQAeKtN/tblabDal3ioW529XVp6fSmZqr+M62j0AzAYAjJKKOQlT2J2FmRIQBQE6n6QWl"
    "zXpTAvAvfX3u16MnP85U29r+vNIT9a5BIi4BADEBjEQIsQgBzBBEDCK5sFT5Z+VWZUsCwFpp"
    "9cr2bm+27QGtPUZUAnuDFYwBg4jAzIBmrZQlZlHZ5UTY9RwJAI3SQm61VPZk9P54CHCfvA/D"
    "VimjtCUCRGiYAKJY2Eg6brEuARD83crq8o1C9KEXpgOC0caQ0YqtNk5oyQGYwm6LwvpK26tc"
    "z7ul61ld//MytHdDDgSky7fmsgcPPz/t6Q4TWABA0Nwgv3Z7y/v7t5y/XrikGsWrAO4CsPvz"
    "yf1k++7vl+mp2hkVdE2wkV/2y/NXe+uFK/Ba8wDqw8IaePvf4gE58cj7ELEZAKP/o859qd+D"
    "fwFu65tDy5tMTAAAAABJRU5ErkJggg==")

#----------------------------------------------------------------------
_hd = PyEmbeddedImage(
    "iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAABHNCSVQICAgIfAhkiAAAAxlJ"
    "REFUOI11ks1vG1UUxc+b98YzyfM4gxzSpHHttCFRbQto7YQgxRKIRRYIZRepEkQVzYJ/gAUi"
    "i/wlSLBhFSEWZMUiQkLCSmUk0o6rNiExcvNRR/Z0xh6P5/OxqFwlfNzVWZz7u0dXh+B/Zn19"
    "Pd1qtQpxHBeiKCoKId4aHR39dGdnx7zsY0Oxurq6FIbhZ4yxwgeVcnHuVuaarmvwPB/nL9r4"
    "/Y+neHrQ+BLA5mUAHYp8Pr8uSdLXD+7fu/nRh5XktckpKOoIONcwNzeP998r483x8bvKSPKb"
    "/f19Z7gnDYUsyz+nUiksLi4ioWqIBcFfBw/R/LOK1nkTCVVDpVJJLpbvfPWfCQzDON/e3v7k"
    "9szk9Z7VwUuzA4WnoaXS6LQ7CAYD2C/bODlr3c3O3Pq2Vqt1ryQghKDb7X7XPG9BH5/ExNQN"
    "DPo9nJ2+wMxsEfr4JPhYGkEYqrIsb/4rAQBwzp+HUfRF5no6MX1jFlOZmxAihtVuYpSnYDyq"
    "QdUm0O323i2Xy99Xq1XzCiCZTPqcp/K247192jxA4DmI4wDPT88xMZXF7NxtPDaeIZfLUdd1"
    "39jd3f2RXAYIIcjS0tLHy8vLP42NjUGWZTDGIEkS4jiGruuglIIQAtd1o5OTk3fYZQAhRGia"
    "Vi0Wi0/m5+fzhFzhAwBc14VlWbAsi5qmeZ/901AqlazDw8MfSqXSZiKRgOM4sG0bpmmi0+mg"
    "3++DUtpWFOWR53m/vT6xtbUl1et1cnR0JDUajTsrKyu/+L4/4nleGIZhw/O8x0EQPLQs69fj"
    "4+Mnuq73NjY2PLK2tkYNw6CmaTLP85jv+wnf99O5XO7zKIrMs7OzZ77vdwkhPiHEppSaiqLY"
    "09PTjmEYASkUCgnbtqnruiwIAjkMQyWKIkUIoQohZACyEIK+ehEJCCEOY8zmnPey2azHisVi"
    "ZBjGq15LkqCURmEY+nEc94UQVAgxLJuQJClkjAWqqvrpdDqo1WohrdfrotVqxbZtR47jRJzz"
    "kDEWaJrmqao64Jy7nHNX1/V+JpNxFxYWBnt7e/7FxUUEAH8DenV0NY9j5foAAAAASUVORK5C"
    "YII=")

#----------------------------------------------------------------------
_new = PyEmbeddedImage(
    "iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAABHNCSVQICAgIfAhkiAAAAqpJ"
    "REFUOI1t0c1rXGUUx/Hvc+/czGtmEk1NTCYWY1BERAJVRMW4cCEIunHTnYjgQrduRHDTrX+F"
    "u+ZvEF2IRVCRRkpt1VSTmqQ1rzNz733uc855XDSRkfHsz+ec3zmO/6mrVz9vPjHTm52e6c23"
    "mq2lmpPFVE/6qrYUcXMON+2y7NP5Zy9/Wxtv/Gx9vXb5ynsfLczPvZnV0kfT+uycq6WdmO/V"
    "82GaNtsPucx5NAyqoDYD8B+gc2m53mk13pluZy9DgptK8b5kZ/sPkqzH4xdmiMUeopJU4jKA"
    "ZBwYDo4j0cRUiDESo3B8uMfmjV85Hea4GIgmqIRExJoTwGFd1LBgKpgZJp4qP6YoSqIJ0c4A"
    "DS5xNjURwfv7Fk28acC5Gi6MsGqIqUA0iIKZYKYuOEsngKOjFZMgXlVIkgBSIOIxOwMsoBIQ"
    "FSwGNxFhY2MjqkpQC2jwiB+gUiEqBA1UVYlIhYgSQmBiAwAViaqCaSCGHJGKO+6EnYMf+ObH"
    "67zYW2C50aXSB701wAEZ0HzjlbWLVfArKlOgHvTBNO1FwsIBh6OK1aLNQtImRmmdAy2gD3Sf"
    "ear/em/+ybWg+0g+4Pt7f7IzOkVmhXovoJmwuXeXraMDsE7jHPBAClwog8yS9ZJQ3qUoCm76"
    "Q/J+TqsraDPH0iF3yl2G96B2uvxvBDmL8fAoL6crVVxZEipBNDCo/qYq95HkmMoLeQVVaNKN"
    "uPEjeqCd+9C9+VfOonkyNS5al/Yu3J4qOJ3bJamarBw8x5R0bt0oTr4eB7aAzbIIa8lop4hp"
    "WSPJ9p+fX71tMf3p59+3Xy1j+kISUh5L+5tvP73+Qf+196+NAwp8d+u37ft+/5evWquLmrSa"
    "17uN/vbSpbfylz5Z+bg7eoQsNtIv/daVD9/94tr52/8BSS2agPSymFoAAAAASUVORK5CYII=")

#----------------------------------------------------------------------
_removable = PyEmbeddedImage(
    "iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAABHNCSVQICAgIfAhkiAAAAldJ"
    "REFUOI2lkbFOXFcQhr+Zc+7uXRZvFi2GOFHiSInA7CLFCnaRCokij0DjyElFh9K6sfwQeQEX"
    "rngAvwBNsCyniNCChCKFSCYOkWADd/fuvfeccUEgrCU3yS+NNNN88/8z8D8l14d+v38jTdv3"
    "fD3tqEpdRJxE1AzDYYCFoswGg8HL5eXPDwH8dYBzzR8/aM9855x778ZQC2TZ+TEwB6ATAK8r"
    "SZLgvefP316SZed47zl902fw+hXOOZxTfKKzz5//1Jpw8OSJaZIcfyFykeqPw1+QX7f5aOEb"
    "pP+Iqv4p1YdfUlUF3omUbtwB/r5ysLa2cztNG+nl3P36W5qzPaZ2HzL67BH15ceMxxnjYkiM"
    "FXOt5mSEznxn0aliZoSqRFXofNzjIHnA9M0F1HvG4yFVOQag0UhnJiIkkixEixTFiBgqQqg4"
    "G/xFdfY7+eicNG0g6nBaQ6SiVivmJgDiZKEsc8CIoSLGQNqc4cbS9zSmpvEuQZ1D1CFS4BJ/"
    "cwJQFKPFIRGwC6Aq6mp0Zm9hplQR1AzRSFUFLFhnAvBi5+e7z549Jc9zzGzy+WYYsHinS7N7"
    "wnyyxNIn9+evAKurqx5ke3Pzh68smkRMMDCLglz2iHOJjeKJNXw7HB0dvwCQlZWV5ODgoFkU"
    "RTOE0DSzGpCYmf9ngQfUzFREKqAQkaH3/qTb7b5xGxsb7O3tWVmWAPGyRCQApYgUIpKLyFBV"
    "z1X1zHs/aLfbp/v7+4X8G9NkfX1dd3d3XZZlmue5izFKjFFU1er1emi1WqHX64Wtra0oIu8c"
    "6j/qLUda/yKP2243AAAAAElFTkSuQmCC")

#----------------------------------------------------------------------

[docs]class MultiDirDialog(wx.Dialog):
    """
    A different implementation of `wx.DirDialog` which allows multiple
    folders to be selected at once.
    """

[docs]    def __init__(self, parent, message=_("Choose one or more folders:"), title=_("Browse For Folders"),
                 defaultPath="", style=wx.DD_DEFAULT_STYLE, agwStyle=DD_MULTIPLE, pos=wx.DefaultPosition,
                 size=wx.DefaultSize, name="multidirdialog"):
        """
        Default class constructor.

        :param `parent`: the dialog parent widget;
        :param `message`: the message to show on the dialog;
        :param `title`: the dialog title;
        :param `defaultPath`: the default path, or the empty string;
        :param `style`: the underlying `wx.Dialog` window style;
        :param `agwStyle`: the AGW-specific dialog style; this can be a combination of the
         following bits:

         ===================== =========== ==================================================
         Window Styles         Hex Value   Description
         ===================== =========== ==================================================
         ``DD_NEW_DIR_BUTTON``       0x000 Enable/disable the "Make new folder" button
         ``DD_DIR_MUST_EXIST``       0x200 The dialog will allow the user to choose only an existing folder. When this style is not given, a "Create new directory" button is added to the dialog (on Windows) or some other way is provided to the user to type the name of a new folder.
         ``DD_MULTIPLE``             0x400 Allows the selection of multiple folders.
         ===================== =========== ==================================================

        :param `pos`: the dialog position;
        :param `size`: the dialog size;
        :param `name`: the dialog name.
        """

        wx.Dialog.__init__(self, parent, pos=pos, size=size, style=wx.DEFAULT_DIALOG_STYLE|wx.RESIZE_BORDER, name=name)

        self.agwStyle = agwStyle

        self.dirCtrl = wx.GenericDirCtrl(self, size=(300, 300), style=wx.DIRCTRL_3D_INTERNAL|wx.DIRCTRL_DIR_ONLY)
        self.folderText = wx.TextCtrl(self, -1, defaultPath, style=wx.TE_PROCESS_ENTER)
        self.CreateButtons()

        self.SetProperties(title)
        # Setup the layout and frame properties
        self.SetupDirCtrl(defaultPath)
        self.LayoutItems(message)
        self.BindEvents()

        if parent and pos == wx.DefaultPosition:
            self.CenterOnParent()

[docs]    def SetupDirCtrl(self, defaultPath):
        """
        Setup the internal `wx.GenericDirCtrl` (icons, labels, etc...).

        :param `defaultPath`: the default path for L{MultiDirDialog}, can be an
         empty string.
        """

        il = wx.ImageList(16, 16)

        # Add images to list. You need to keep the same order in order for
        # this to work!

        # closed folder:
        il.Add(_folder_close.GetBitmap())

        # open folder:
        il.Add(_folder_open.GetBitmap())

        # root of filesystem (linux):
        il.Add(_computer.GetBitmap())

        # drive letter (windows):
        il.Add(_hd.GetBitmap())

        # cdrom drive:
        il.Add(_cdrom.GetBitmap())

        # removable drive on win98:
        il.Add(_removable.GetBitmap())

        # removable drive (floppy, flash, etc):
        il.Add(_removable.GetBitmap())

        # assign image list:
        treeCtrl = self.dirCtrl.GetTreeCtrl()
        treeCtrl.AssignImageList(il)

        if self.agwStyle & DD_MULTIPLE:
            treeCtrl.SetWindowStyle(treeCtrl.GetWindowStyle() | wx.TR_MULTIPLE)

        if not defaultPath.strip():
            return

        # Set the wx.GenericDirCtrl default path
        self.dirCtrl.ExpandPath(defaultPath)
        self.dirCtrl.SetDefaultPath(defaultPath)
        self.dirCtrl.SetPath(defaultPath)

        self.folderText.SetValue(treeCtrl.GetItemText(treeCtrl.GetSelections()[0]))

[docs]    def SetProperties(self, title):
        """
        Sets few properties for the dialog.

        :param `title`: the dialog title.
        """

        self.SetTitle(title)
        self.okButton.SetDefault()

        if self.agwStyle & wx.DD_DIR_MUST_EXIST:
            self.newButton.Enable(False)

[docs]    def LayoutItems(self, message):
        """ Layout the widgets using sizers. """

        mainSizer = wx.BoxSizer(wx.VERTICAL)
        textSizer = wx.BoxSizer(wx.HORIZONTAL)
        bottomSizer = wx.BoxSizer(wx.HORIZONTAL)

        staticText = wx.StaticText(self, -1, message)
        f = staticText.GetFont()
        f.SetWeight(wx.BOLD)
        staticText.SetFont(f)

        # Add the main wx.GenericDirCtrl
        mainSizer.Add(staticText, 0, wx.EXPAND|wx.ALL, 10)
        mainSizer.Add(self.dirCtrl, 1, wx.EXPAND|wx.ALL, 10)

        label = wx.StaticText(self, -1, _("Folder:"))
        textSizer.Add(label, 0, wx.LEFT|wx.RIGHT|wx.ALIGN_CENTER_VERTICAL, 10)
        textSizer.Add(self.folderText, 1, wx.RIGHT|wx.EXPAND|wx.ALIGN_CENTER_VERTICAL, 10)
        mainSizer.Add(textSizer, 0, wx.EXPAND|wx.BOTTOM, 10)

        # Add the fancy buttons
        bottomSizer.Add(self.newButton, 0, wx.ALL, 10)
        bottomSizer.Add((0, 0), 1, wx.EXPAND)
        bottomSizer.Add(self.okButton, 0, wx.TOP|wx.BOTTOM, 10)
        bottomSizer.Add(self.cancelButton, 0, wx.TOP|wx.BOTTOM|wx.RIGHT, 10)
        mainSizer.Add(bottomSizer, 0, wx.EXPAND)

        # Layout the dialog
        self.SetSizer(mainSizer)
        mainSizer.Layout()
        mainSizer.Fit(self)
        mainSizer.SetSizeHints(self)

[docs]    def GetPaths(self):
        """ Returns the folders selected by the user, or the default path. """

        # Retrieve the tree control and the selections the
        # user has made
        treeCtrl = self.dirCtrl.GetTreeCtrl()
        selections = treeCtrl.GetSelections()

        folders = []

        # Loop recursively over the selected folder and its sub-direcories
        for select in selections:
            itemText = treeCtrl.GetItemText(select)
            # Recurse on it.
            folder = self.RecurseTopDir(treeCtrl, select, itemText)
            folders.append(os.path.normpath(folder))

        return folders

[docs]    def RecurseTopDir(self, treeCtrl, item, itemText):
        """
        Recurse a directory tree to include the parent-folder.

        :param `treeCtrl`: the tree control associated with teh internal `wx.GenericDirCtrl`;
        :param `item`: the selected tree control item;
        :param `itemText`: the selected tree control item text.
        """

        # Get the item parent
        parent = treeCtrl.GetItemParent(item)
        if parent != treeCtrl.GetRootItem():
            # Not the root item, recurse again on it
            itemText = treeCtrl.GetItemText(parent) + "/" + itemText
            itemText = self.RecurseTopDir(treeCtrl, parent, itemText)

        return itemText

[docs]    def BindEvents(self):
        """ Binds the events to specific methods. """

        self.Bind(wx.EVT_BUTTON, self.OnOk, self.okButton)
        self.Bind(wx.EVT_BUTTON, self.OnCancel, self.cancelButton)
        self.Bind(wx.EVT_CLOSE, self.OnClose)
        self.Bind(wx.EVT_CHAR_HOOK, self.OnKeyUp)
        self.dirCtrl.GetTreeCtrl().Bind(wx.EVT_TREE_SEL_CHANGED, self.OnSelChanged)

[docs]    def CreateButtons(self):
        """ Creates the ``OK``, ``Cancel`` and ``Make New Folder`` bitmap buttons. """

        # Build a couple of fancy buttons
        self.newButton = buttons.ThemedGenBitmapTextButton(self, wx.ID_NEW, _new.GetBitmap(),
                                                           _("Make New Folder"), size=(-1, 28))
        self.okButton = buttons.ThemedGenBitmapTextButton(self, wx.ID_OK, _ok.GetBitmap(),
                                                          _("OK"), size=(-1, 28))
        self.cancelButton = buttons.ThemedGenBitmapTextButton(self, wx.ID_CANCEL, _cancel.GetBitmap(),
                                                              _("Cancel"), size=(-1, 28))

[docs]    def OnOk(self, event):
        """
        Handles the ``wx.EVT_BUTTON`` event for the dialog.

        :param `event`: a `wx.CommandEvent` event to be processed.

        :note: This method handles the ``OK`` button press.
        """

        self.EndModal(wx.ID_OK)

[docs]    def OnCancel(self, event):
        """
        Handles the ``wx.EVT_BUTTON`` event for the dialog.

        :param `event`: a `wx.CommandEvent` event to be processed.

        :note: This method handles the ``Cancel`` button press.
        """

        self.OnClose(event)

[docs]    def OnClose(self, event):
        """
        Handles the ``wx.EVT_CLOSE`` event for the dialog.

        :param `event`: a `wx.CloseEvent` event to be processed.
        """

        self.EndModal(wx.ID_CANCEL)

[docs]    def OnKeyUp(self, event):
        """
        Handles the ``wx.EVT_CHAR_HOOK`` event for the dialog.

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

        if event.GetKeyCode() == wx.WXK_ESCAPE:
            # Close the dialog, no action
            self.OnClose(event)
        elif event.GetKeyCode() in [wx.WXK_RETURN, wx.WXK_NUMPAD_ENTER]:
            # Close the dialog, the user wants to continue
            self.OnOk(event)

        event.Skip()

[docs]    def OnSelChanged(self, event):
        """
        Handles the ``wx.EVT_TREE_SEL_CHANGED`` event for the tree control associated
        with L{MultiDirDialog}.

        :param `event`: a `wx.TreeEvent` event to be processed.
        """

        if self.IsBeingDeleted():
            # We are being destroyed...
            event.Skip()
            return

        item = event.GetItem()
        if not item.IsOk():
            # Bad item?
            event.Skip()
            return

        treeCtrl = self.dirCtrl.GetTreeCtrl()
        text = treeCtrl.GetItemText(item)
        # Set the item name into the text control
        self.folderText.SetValue(text)
        self.folderText.Refresh()

        event.Skip()

Navigation

  • index
  • modules |
  • Home |
  • Gallery |
  • Contents»
  • Module code »
  • multidirdialog


peakmeter

  • modules |
  • Home |
  • Gallery |
  • Contents»
  • Module code »
  • peakmeter

Source code for peakmeter

# --------------------------------------------------------------------------------- #
# PEAKMETERCTRL wxPython IMPLEMENTATION
#
# Andrea Gavana, @ 07 October 2008
# Latest Revision: 17 Aug 2011, 15.00 GMT
#
#
# TODO List
#
# 1) Falloff effect for vertical bands;
#
# 2) Possibly some nicer drawing of bands and leds (using GraphicsContext).
#
#
# 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
# --------------------------------------------------------------------------------- #

"""
L{PeakMeterCtrl} mimics the behaviour of equalizers that are usually found in stereos
and MP3 players.

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

L{PeakMeterCtrl} mimics the behaviour of equalizers that are usually found in stereos
and MP3 players. This widgets supports:

* Vertical and horizontal led bands;
* Settings number of bands and leds per band;
* Possibility to change the colour for low/medium/high band frequencies;
* Falloff effects;
* Showing a background grid for the bands.

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

Usage
=====

Usage example::

    import wx
    import random

    import wx.lib.agw.peakmeter as PM

    class MyFrame(wx.Frame):

        def __init__(self, parent):

            wx.Frame.__init__(self, parent, -1, "PeakMeterCtrl Demo")

            panel = wx.Panel(self)

            # Initialize Peak Meter control 1
            self.vertPeak = PM.PeakMeterCtrl(panel, -1, style=wx.SIMPLE_BORDER, agwStyle=PM.PM_VERTICAL)
            # Initialize Peak Meter control 2
            self.horzPeak = PM.PeakMeterCtrl(panel, -1, style=wx.SUNKEN_BORDER, agwStyle=PM.PM_HORIZONTAL)

            self.vertPeak.SetMeterBands(10, 15)
            self.horzPeak.SetMeterBands(10, 15)

            # Layout the two PeakMeterCtrl
            mainSizer = wx.BoxSizer(wx.HORIZONTAL)
            mainSizer.Add(self.vertPeak, 0, wx.EXPAND|wx.ALL, 15)
            mainSizer.Add(self.horzPeak, 0, wx.EXPAND|wx.ALL, 15)

            panel.SetSizer(mainSizer)
            mainSizer.Layout()

            self.timer = wx.Timer(self)
            self.Bind(wx.EVT_TIMER, self.OnTimer)

            wx.CallLater(500, self.Start)

        def Start(self):
            ''' Starts the PeakMeterCtrl. '''

            self.timer.Start(1000/2)            # 2 fps

            self.vertPeak.Start(1000/18)        # 18 fps
            self.horzPeak.Start(1000/20)        # 20 fps

        def OnTimer(self, event):
            '''
            Handles the ``wx.EVT_TIMER`` event for L{PeakMeterCtrl}.

            :param `event`: a `wx.TimerEvent` event to be processed.
            '''

            # Generate 15 random number and set them as data for the meter
            nElements = 15
            arrayData = []

            for i in xrange(nElements):
                nRandom = random.randint(0, 100)
                arrayData.append(nRandom)

            self.vertPeak.SetData(arrayData, 0, nElements)
            self.horzPeak.SetData(arrayData, 0, nElements)

    # our normal wxApp-derived class, as usual

    app = wx.PySimpleApp()

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

    app.MainLoop()

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

L{PeakMeterCtrl} has been tested on the following platforms:
  * Windows (Windows XP).

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

This class supports the following window styles:

================= =========== ==================================================
Window Styles     Hex Value   Description
================= =========== ==================================================
``PM_HORIZONTAL``         0x0 Shows horizontal bands in L{PeakMeterCtrl}.
``PM_VERTICAL``           0x1 Shows vertical bands in L{PeakMeterCtrl}.
================= =========== ==================================================

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

`No custom events are available for this class.`

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

L{PeakMeterCtrl} is distributed under the wxPython license.

Latest Revision: Andrea Gavana @ 17 Aug 2011, 15.00 GMT

Version 0.3

"""

import wx

# Horizontal or vertical PeakMeterCtrl
PM_HORIZONTAL = 0
""" Shows horizontal bands in L{PeakMeterCtrl}. """
PM_VERTICAL = 1
""" Shows vertical bands in L{PeakMeterCtrl}. """

# Some useful constants...
BAND_DEFAULT = 8
LEDS_DEFAULT = 8
BAND_PERCENT = 10       # 10% of Max Range (Auto Decrease)
GRID_INCREASEBY = 15    # Increase Grid colour based on Background colour
FALL_INCREASEBY = 60    # Increase Falloff colour based on Background
DEFAULT_SPEED = 10

[docs]def InRange(val, valMin, valMax):
    """
    Returns whether the value `val` is between `valMin` and `valMax`.

    :param `val`: the value to test;
    :param `valMin`: the minimum range value;
    :param `valMax`: the maximum range value.
    """

    return val >= valMin and val <= valMax

[docs]def LightenColour(crColour, byIncreaseVal):
    """
    Lightens a colour.

    :param `crColour`: a valid `wx.Colour` object;
    :param `byIncreaseVal`: an integer specifying the amount for which the input
     colour should be brightened.
    """

    byRed = crColour.Red()
    byGreen = crColour.Green()
    byBlue = crColour.Blue()

    byRed = (byRed + byIncreaseVal <= 255 and [byRed + byIncreaseVal] or [255])[0]
    byGreen = (byGreen + byIncreaseVal <= 255 and [byGreen + byIncreaseVal] or [255])[0]
    byBlue = (byBlue + byIncreaseVal <= 255 and [byBlue + byIncreaseVal] or [255])[0]

    return wx.Colour(byRed, byGreen, byBlue)

[docs]def DarkenColour(crColour, byReduceVal):
    """
    Darkens a colour.

    :param `crColour`: a valid `wx.Colour` object;
    :param `byReduceVal`: an integer specifying the amount for which the input
     colour should be darkened.
    """

    byRed = crColour.Red()
    byGreen = crColour.Green()
    byBlue = crColour.Blue()

    byRed = (byRed >= byReduceVal and [byRed - byReduceVal] or [0])[0]
    byGreen = (byGreen >= byReduceVal and [byGreen - byReduceVal] or [0])[0]
    byBlue = (byBlue >= byReduceVal and [byBlue - byReduceVal] or [0])[0]

    return wx.Colour(byRed, byGreen, byBlue)

[docs]class PeakMeterData(object):
    """ A simple class which holds data for our L{PeakMeterCtrl}. """

[docs]    def __init__(self, value=0, falloff=0, peak=0):
        """
        Default class constructor.

        :param `value`: the current L{PeakMeterCtrl} value;
        :param `falloff`: the falloff effect. ``True`` to enable it, ``False`` to
         disable it;
        :param `peak`: the peak value.
        """

        self._value = value
        self._falloff = falloff
        self._peak = peak

[docs]    def IsEqual(self, pm):
        """
        Returns whether 2 instances of L{PeakMeterData} are the same.

        :param `pm`: another instance of L{PeakMeterData}.
        """

        return self._value == pm._value

[docs]    def IsGreater(self, pm):
        """
        Returns whether one L{PeakMeterData} is greater than another.

        :param `pm`: another instance of L{PeakMeterData}.
        """

        return self._value > pm._value

[docs]    def IsLower(self, pm):
        """
        Returns whether one L{PeakMeterData} is smaller than another.

        :param `pm`: another instance of L{PeakMeterData}.
        """

        return self._value < pm._value

[docs]class PeakMeterCtrl(wx.PyControl):
    """ The main L{PeakMeterCtrl} implementation. """

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

        :param parent: the L{PeakMeterCtrl} parent. Must not be ``None``
        :param `id`: window identifier. A value of -1 indicates a default value;
        :param `pos`: the control position. A value of (-1, -1) indicates a default position,
         chosen by either the windowing system or wxPython, depending on platform;
        :param `size`: the control size. A value of (-1, -1) indicates a default size,
         chosen by either the windowing system or wxPython, depending on platform;
        :param `style`: the underlying `wx.PyControl` window style;
        :param `agwStyle`: the AGW-specific window style, which can be one of the following bits:

         ================= =========== ==================================================
         Window Styles     Hex Value   Description
         ================= =========== ==================================================
         ``PM_HORIZONTAL``         0x0 Shows horizontal bands in L{PeakMeterCtrl}.
         ``PM_VERTICAL``           0x1 Shows vertical bands in L{PeakMeterCtrl}.
         ================= =========== ==================================================

        """

        wx.PyControl.__init__(self, parent, id, pos, size, style)
        self.SetBackgroundStyle(wx.BG_STYLE_CUSTOM)

        self._agwStyle = agwStyle
        # Initializes all data
        self.InitData()

        self.Bind(wx.EVT_PAINT, self.OnPaint)
        self.Bind(wx.EVT_SIZE, self.OnSize)
        self.Bind(wx.EVT_ERASE_BACKGROUND, self.OnEraseBackground)
        self.Bind(wx.EVT_TIMER, self.OnTimer)

[docs]    def InitData(self):
        """ Initializes the control. """

        colLime = wx.Colour(0, 255, 0)
        colRed = wx.Colour(255, 0, 0)
        colYellow = wx.Colour(255, 255, 0)

        self._showGrid = False
        self._showFalloff = True
        self._delay = 10
        self._minValue = 60         # Min Range 0-60
        self._medValue = 80         # Med Range 60-80
        self._maxValue = 100        # Max Range 80-100
        self._numBands = BAND_DEFAULT
        self._ledBands = LEDS_DEFAULT
        self._clrBackground = self.GetBackgroundColour()
        self._clrNormal = colLime
        self._clrMedium = colYellow
        self._clrHigh = colRed
        self._speed = DEFAULT_SPEED
        self._timer = wx.Timer(self)

        # clear vector data
        self._meterData = []

[docs]    def SetAGWWindowStyleFlag(self, agwStyle):
        """
        Sets the L{PeakMeterCtrl} window style flags.

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

         ================= =========== ==================================================
         Window Styles     Hex Value   Description
         ================= =========== ==================================================
         ``PM_HORIZONTAL``         0x0 Shows horizontal bands in L{PeakMeterCtrl}.
         ``PM_VERTICAL``           0x1 Shows vertical bands in L{PeakMeterCtrl}.
         ================= =========== ==================================================

        """

        self._agwStyle = agwStyle
        self.Refresh()

[docs]    def GetAGWWindowStyleFlag(self):
        """
        Returns the L{PeakMeterCtrl} window style.

        :see: L{SetAGWWindowStyleFlag} for a list of possible window style flags.
        """

        return self._agwStyle

[docs]    def ResetControl(self):
        """ Resets the L{PeakMeterCtrl}. """

        # Initialize vector
        for i in xrange(self._numBands):
            pm = PeakMeterData(self._maxValue, self._maxValue, self._speed)
            self._meterData.append(pm)

        self.Refresh()

[docs]    def SetBackgroundColour(self, colourBgnd):
        """
        Changes the background colour of L{PeakMeterCtrl}.

        :param `colourBgnd`: the colour to be used as the background colour, pass
         `wx.NullColour` to reset to the default colour.

        :note: The background colour is usually painted by the default `wx.EraseEvent`
         event handler function under Windows and automatically under GTK.

        :note: Setting the background colour does not cause an immediate refresh, so
         you may wish to call `wx.Window.ClearBackground` or `wx.Window.Refresh` after
         calling this function.

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

        wx.PyControl.SetBackgroundColour(self, colourBgnd)
        self._clrBackground = colourBgnd
        self.Refresh()

[docs]    def SetBandsColour(self, colourNormal, colourMedium, colourHigh):
        """
        Set bands colour for L{PeakMeterCtrl}.

        :param `colourNormal`: the colour for normal (low) bands, a valid `wx.Colour`
         object;
        :param `colourMedium`: the colour for medium bands, a valid `wx.Colour`
         object;
        :param `colourHigh`: the colour for high bands, a valid `wx.Colour`
         object.
        """

        self._clrNormal = colourNormal
        self._clrMedium = colourMedium
        self._clrHigh   = colourHigh

        self.Refresh()

[docs]    def SetMeterBands(self, numBands, ledBands):
        """
        Set number of vertical or horizontal bands to display.

        :param `numBands`: number of bands to display (either vertical or horizontal);
        :param `ledBands`: the number of leds per band.

        :note: You can obtain a smooth effect by setting `nHorz` or `nVert` to "1", these
         cannot be 0.
        """

        assert (numBands > 0 and ledBands > 0)

        self._numBands = numBands
        self._ledBands = ledBands

        # Reset vector
        self.ResetControl()

[docs]    def SetRangeValue(self, minVal, medVal, maxVal):
        """
        Sets the ranges for low, medium and high bands.

        :param `minVal`: the value for low bands;
        :param `medVal`: the value for medium bands;
        :param `maxVal`: the value for high bands.

        :note: The conditions to be satisfied are:

         Min: [0 - nMin[,  Med: [nMin - nMed[,  Max: [nMed - nMax]

        """

        assert (maxVal > medVal and medVal > minVal and minVal > 0)

        self._minValue = minVal
        self._medValue = medVal
        self._maxValue = maxVal

[docs]    def GetRangeValue(self):
        """ Get range value of L{PeakMeterCtrl}. """

        return self._minValue, self._medValue, self._maxValue

[docs]    def SetFalloffDelay(self, speed):
        """
        Set peak value speed before falling off.

        :param `speed`: the speed at which the falloff happens.
        """

        self._speed = speed

[docs]    def SetFalloffEffect(self, falloffEffect):
        """
        Set falloff effect flag.

        :param `falloffEffect`: ``True`` to enable the falloff effect, ``False``
         to disable it.
        """

        if self._showFalloff != falloffEffect:

            self._showFalloff = falloffEffect
            self.Refresh()

[docs]    def GetFalloffEffect(self):
        """ Returns the falloff effect flag. """

        return self._showFalloff

[docs]    def ShowGrid(self, showGrid):
        """
        Request to have gridlines visible or not.

        :param `showGrid`: ``True`` to show grid lines, ``False`` otherwise.
        """

        if self._showGrid != showGrid:

            self._showGrid = showGrid
            self.Refresh()

[docs]    def IsGridVisible(self):
        """ Returns if gridlines are visible. """

        return self._showGrid

[docs]    def SetData(self, arrayValue, offset, size):
        """
        Change data value. Use this function to change only
        a set of values. All bands can be changed or only 1 band,
        depending on the application.

        :param `arrayValue`: a Python list containing the L{PeakMeterData} values;
        :param `offset`: the (optional) offset where to start applying the new data;
        :param `size`: the size of the input data.
        """

        assert (offset >= 0 and arrayValue != [])

        isRunning = self.IsStarted()

        # Stop timer if Animation is active
        if isRunning:
            self.Stop()

        maxSize = offset + size

        for i in xrange(offset, maxSize):

            if i < len(self._meterData):

                pm = self._meterData[i]
                pm._value = arrayValue[i]

                if pm._falloff < pm._value:

                    pm._falloff = pm._value
                    pm._peak = self._speed

                self._meterData[i] = pm

        # Auto-restart
        if isRunning:
            return self.Start(self._delay)

        self.Refresh()

        return True

[docs]    def IsStarted(self):
        """ Check if animation is active. """

        return self._timer.IsRunning()

[docs]    def Start(self, delay):
        """
        Start the timer and animation effect.

        :param `delay`: the animation effect delay, in milliseconds.
        """

        if not self.IsStarted():
            self._delay = delay
            self._timer.Start(self._delay)
        else:
            return False

        return True

[docs]    def Stop(self):
        """ Stop the timer and animation effect. """

        if self.IsStarted():
            self._timer.Stop()
            return True

        return False

[docs]    def DoTimerProcessing(self):
        """ L{PeakMeterCtrl} animation, does the ``wx.EVT_TIMER`` processing. """

        self.Refresh()

        decValue  = self._maxValue/self._ledBands
        noChange = True

        for pm in self._meterData:

            if pm._value > 0:

                pm._value -= (self._ledBands > 1 and [decValue] or [self._maxValue*BAND_PERCENT/100])[0]
                if pm._value < 0:
                    pm._value = 0

                noChange = False

            if pm._peak > 0:

                pm._peak -= 1
                noChange = False

            if pm._peak == 0 and pm._falloff > 0:

                pm._falloff -= (self._ledBands > 1 and [decValue >> 1] or [5])[0]
                if pm._falloff < 0:
                    pm._falloff = 0

                noChange = False

        if noChange: # Stop timer if no more data

            self.Stop()

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

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

        # something is better than nothing...
        return wx.Size(200, 150)

[docs]    def OnPaint(self, event):
        """
        Handles the ``wx.EVT_PAINT`` event for L{PeakMeterCtrl}.

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

        dc = wx.AutoBufferedPaintDC(self)
        self._clrBackground = self.GetBackgroundColour()
        dc.SetBackground(wx.Brush(self._clrBackground))
        dc.Clear()
        rc = self.GetClientRect()

        pen = wx.Pen(self._clrBackground)
        dc.SetPen(pen)

        if self.GetAGWWindowStyleFlag() & PM_VERTICAL:
            self.DrawVertBand(dc, rc)
        else:
            self.DrawHorzBand(dc, rc)

[docs]    def OnEraseBackground(self, event):
        """
        Handles the ``wx.EVT_ERASE_BACKGROUND`` event for L{PeakMeterCtrl}.

        :param `event`: a `wx.EraseEvent` event to be processed.

        :note: This method is intentionally empty to reduce flicker.
        """

        # This is intentionally empty, to reduce flicker
        pass

[docs]    def OnSize(self, event):
        """
        Handles the ``wx.EVT_SIZE`` event for L{PeakMeterCtrl}.

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

        self.Refresh()
        event.Skip()

[docs]    def OnTimer(self, event):
        """
        Handles the ``wx.EVT_TIMER`` event for L{PeakMeterCtrl}.

        :param `event`: a `wx.TimerEvent` event to be processed.
        """

        self.DoTimerProcessing()

[docs]    def DrawHorzBand(self, dc, rect):
        """
        Draws horizontal bands.

        :param `dc`: an instance of `wx.DC`;
        :param `rect`: the horizontal bands client rectangle.

        :todo: Implement falloff effect for horizontal bands.
        """

        horzBands = (self._ledBands > 1 and [self._ledBands] or [self._maxValue*BAND_PERCENT/100])[0]
        minHorzLimit = self._minValue*horzBands/self._maxValue
        medHorzLimit = self._medValue*horzBands/self._maxValue
        maxHorzLimit = horzBands

        size = wx.Size(rect.width/horzBands, rect.height/self._numBands)
        rectBand = wx.RectPS(rect.GetTopLeft(), size)

        # Draw band from top
        rectBand.OffsetXY(0, rect.height-size.y*self._numBands)
        xDecal = (self._ledBands > 1 and [1] or [0])[0]
        yDecal = (self._numBands > 1 and [1] or [0])[0]

        for vert in xrange(self._numBands):

            self._value = self._meterData[vert]._value
            horzLimit = self._value*horzBands/self._maxValue

            for horz in xrange(horzBands):

                rectBand.Deflate(0, yDecal)

                # Find colour based on range value
                colourRect = self._clrBackground
                if self._showGrid:
                    colourRect = DarkenColour(self._clrBackground, GRID_INCREASEBY)

                if self._showGrid and (horz == minHorzLimit or horz == (horzBands-1)):

                    points = [wx.Point() for i in xrange(2)]
                    points[0].x = rectBand.GetTopLeft().x + (rectBand.width >> 1)
                    points[0].y = rectBand.GetTopLeft().y - yDecal
                    points[1].x = points[0].x
                    points[1].y = rectBand.GetBottomRight().y + yDecal
                    dc.DrawLinePoint(points[0], points[1])

                if horz < horzLimit:

                    if InRange(horz, 0, minHorzLimit-1):
                        colourRect = self._clrNormal
                    elif InRange(horz, minHorzLimit, medHorzLimit-1):
                        colourRect = self._clrMedium
                    elif InRange(horz, medHorzLimit, maxHorzLimit):
                        colourRect = self._clrHigh

                dc.SetBrush(wx.Brush(colourRect))
                dc.DrawRectangleRect(rectBand)

                rectBand.Inflate(0, yDecal)
                rectBand.OffsetXY(size.x, 0)

            # Move to Next Vertical band
            rectBand.OffsetXY(-size.x*horzBands, size.y)

[docs]    def DrawVertBand(self, dc, rect):
        """
        Draws vertical bands.

        :param `dc`: an instance of `wx.DC`;
        :param `rect`: the vertical bands client rectangle.
        """

        vertBands = (self._ledBands > 1 and [self._ledBands] or [self._maxValue*BAND_PERCENT/100])[0]
        minVertLimit = self._minValue*vertBands/self._maxValue
        medVertLimit = self._medValue*vertBands/self._maxValue
        maxVertLimit = vertBands

        size = wx.Size(rect.width/self._numBands, rect.height/vertBands)
        rectBand = wx.RectPS(rect.GetTopLeft(), size)

        # Draw band from bottom
        rectBand.OffsetXY(0, rect.bottom-size.y)
        xDecal = (self._numBands > 1 and [1] or [0])[0]
        yDecal = (self._ledBands > 1 and [1] or [0])[0]

        for horz in xrange(self._numBands):

            self._value = self._meterData[horz]._value
            vertLimit = self._value*vertBands/self._maxValue
            rectPrev = wx.Rect(*rectBand)

            for vert in xrange(vertBands):

                rectBand.Deflate(xDecal, 0)

                # Find colour based on range value
                colourRect = self._clrBackground
                if self._showGrid:
                    colourRect = DarkenColour(self._clrBackground, GRID_INCREASEBY)

                # Draw grid line (level) bar
                if self._showGrid and (vert == minVertLimit or vert == (vertBands-1)):

                    points = [wx.Point() for i in xrange(2)]
                    points[0].x = rectBand.GetTopLeft().x - xDecal
                    points[0].y = rectBand.GetTopLeft().y + (rectBand.height >> 1)
                    points[1].x = rectBand.GetBottomRight().x + xDecal
                    points[1].y = points[0].y
                    dc.DrawLinePoint(points[0], points[1])

                if vert < vertLimit:

                    if InRange(vert, 0, minVertLimit-1):
                        colourRect = self._clrNormal
                    elif InRange(vert, minVertLimit, medVertLimit-1):
                        colourRect = self._clrMedium
                    elif InRange(vert, medVertLimit, maxVertLimit):
                        colourRect = self._clrHigh

                dc.SetBrush(wx.Brush(colourRect))
                dc.DrawRectangleRect(rectBand)

                rectBand.Inflate(xDecal, 0)
                rectBand.OffsetXY(0, -size.y)

            # Draw falloff effect
            if self._showFalloff:

                oldPen = dc.GetPen()
                pen = wx.Pen(DarkenColour(self._clrBackground, FALL_INCREASEBY))
                maxHeight = size.y*vertBands
                points = [wx.Point() for i in xrange(2)]
                points[0].x = rectPrev.GetTopLeft().x + xDecal
                points[0].y = rectPrev.GetBottomRight().y - self._meterData[horz]._falloff*maxHeight/self._maxValue
                points[1].x = rectPrev.GetBottomRight().x - xDecal
                points[1].y = points[0].y
                dc.SetPen(pen)
                dc.DrawLinePoint(points[0], points[1])
                dc.SetPen(oldPen)

            # Move to Next Horizontal band
            rectBand.OffsetXY(size.x, size.y*vertBands)

Navigation

  • index
  • modules |
  • Home |
  • Gallery |
  • Contents»
  • Module code »
  • peakmeter


piectrl

  • modules |
  • Home |
  • Gallery |
  • Contents»
  • Module code »
  • piectrl

Source code for piectrl

# --------------------------------------------------------------------------- #
# PIECTRL Control wxPython IMPLEMENTATION
# Python Code By:
#
# Andrea Gavana, @ 31 Oct 2005
# Latest Revision: 17 Aug 2011, 15.00 GMT
#
#
# TODO List/Caveats
#
# 1. Maybe Integrate The Very Nice PyOpenGL Implementation Of A PieChart Coded
#    By Will McGugan?
#
# 2. Not Tested On Other Platforms, Only On Windows 2000/XP, With Python 2.4.1
#    And wxPython 2.6.1.0
#
# 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
# --------------------------------------------------------------------------- #

"""
L{PieCtrl} and L{ProgressPie} are simple classes that reproduce the behavior of a pie
chart.

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

L{PieCtrl} and L{ProgressPie} are simple classes that reproduce the behavior of a pie
chart. They use only pure wxPython classes/methods, without external dependencies.
L{PieCtrl} is somewhat a "static" control, that you may create in order to display
a simple pie chart on a `wx.Panel` or similar. L{ProgressPie} tries to emulate the
behavior of `wx.ProgressDialog`, but using a pie chart instead of a gauge.

Usage
=====

Usage example::

    import wx
    import wx.lib.agw.piectrl as PC

    class MyFrame(wx.Frame):

        def __init__(self, parent):

            wx.Frame.__init__(self, parent, -1, "PieCtrl Demo")

            panel = wx.Panel(self)

            # create a simple PieCtrl with 3 sectors
            mypie = PC.PieCtrl(panel, -1, wx.DefaultPosition, wx.Size(180,270))

            part = PC.PiePart()

            part.SetLabel("Label 1")
            part.SetValue(300)
            part.SetColour(wx.Colour(200, 50, 50))
            mypie._series.append(part)

            part = PC.PiePart()

            part.SetLabel("Label 2")
            part.SetValue(200)
            part.SetColour(wx.Colour(50, 200, 50))
            mypie._series.append(part)

            part = PC.PiePart()

            part.SetLabel("helloworld label 3")
            part.SetValue(50)
            part.SetColour(wx.Colour(50, 50, 200))
            mypie._series.append(part)

            # create a ProgressPie
            progress_pie = PC.ProgressPie(panel, 100, 50, -1, wx.DefaultPosition,
                                          wx.Size(180, 200), wx.SIMPLE_BORDER)

            progress_pie.SetBackColour(wx.Colour(150, 200, 255))
            progress_pie.SetFilledcolour(wx.Colour(255, 0, 0))
            progress_pie.SetUnfilledColour(wx.WHITE)
            progress_pie.SetHeight(20)

            main_sizer = wx.BoxSizer(wx.HORIZONTAL)

            main_sizer.Add(mypie, 1, wx.EXPAND | wx.ALL, 5)
            main_sizer.Add(progress_pie, 1, wx.EXPAND | wx.ALL, 5)

            panel.SetSizer(main_sizer)
            main_sizer.Layout()

    # our normal wxApp-derived class, as usual

    app = wx.PySimpleApp()

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

    app.MainLoop()

Methods and Settings
====================

With L{PieCtrl} you can:

- Create a L{PieCtrl} with different sectors;
- Set the sector values, colours and labels;
- Assign a legend to the L{PieCtrl};
- Use an image as the L{PieCtrl} background;
- Change the vertical rotation (perspective) of the L{PieCtrl};
- Show/hide the segment edges.

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

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

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

`No custom events are available for this class.`

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

L{PieCtrl} is distributed under the wxPython license.

Latest revision: Andrea Gavana @ 17 Aug 2011, 15.00 GMT

Version 0.2

"""

#----------------------------------------------------------------------
# Beginning Of PIECTRL wxPython Code
#----------------------------------------------------------------------

import wx

from math import pi, sin, cos

#----------------------------------------------------------------------
# Class PieCtrlLegend
# This Class Handles The Legend For The Classic PieCtrl.
#----------------------------------------------------------------------

[docs]class PieCtrlLegend(wx.Window):
    """
    This class displays a legend window for the classic L{PieCtrl}.
    """

[docs]    def __init__(self, parent, title, id=wx.ID_ANY, pos=wx.DefaultPosition,
                 size=wx.DefaultSize, style=0):
        """
        Default class constructor.

        :param `parent`: the L{PieCtrlLegend} parent;
        :param `title`: the legend title;
        :param `id`: window identifier. A value of -1 indicates a default value;
        :param `pos`: the control position. A value of (-1, -1) indicates a default position,
         chosen by either the windowing system or wxPython, depending on platform;
        :param `size`: the control size. A value of (-1, -1) indicates a default size,
         chosen by either the windowing system or wxPython, depending on platform;
        :param `style`: the window style (unused).
        """

        wx.Window.__init__(self, parent, id, pos, size, style)

        self._title = title
        self._istransparent = False
        self._horborder = 5
        self._verborder = 5
        self._titlecolour = wx.Colour(0, 0, 127)
        self._labelcolour = wx.BLACK
        self._backcolour = wx.Colour(255, 255, 0)
        self._backgroundDC = wx.MemoryDC()
        self._parent = parent

        self.Bind(wx.EVT_ERASE_BACKGROUND, lambda x: None)
        self.Bind(wx.EVT_PAINT, self.OnPaint)

[docs]    def SetTransparent(self, value=False):
        """
        Toggles the legend transparency (visibility).

        :param `value`: ``True`` to set the legend as transparent, ``False`` otherwise.
        """

        self._istransparent = value
        self.Refresh()

[docs]    def RecreateBackground(self, parentdc):
        """
        Recreates the legend background.

        :param `parentdc`: an instance of `wx.DC`.
        """

        w, h = self.GetSize()
        self._background = wx.EmptyBitmap(w, h)
        self._backgroundDC.SelectObject(self._background)

        if self.IsTransparent():

            self._backgroundDC.Blit(0, 0, w, h, parentdc, self.GetPosition().x,
                                    self.GetPosition().y)

        else:

            self._backgroundDC.SetBackground(wx.Brush(self._backcolour))
            self._backgroundDC.Clear()

        self.Refresh()

[docs]    def SetHorizontalBorder(self, value):
        """
        Sets the legend's horizontal border.

        :param `value`: the horizontal border thickness, in pixels.
        """

        self._horborder = value
        self.Refresh()

[docs]    def GetHorizontalBorder(self):
        """ Returns the legend's horizontal border, in pixels. """

        return self._horborder

[docs]    def SetVerticalBorder(self, value):
        """
        Sets the legend's vertical border.

        :param `value`: the horizontal border thickness, in pixels.
        """

        self._verborder = value
        self.Refresh()

[docs]    def GetVerticalBorder(self):
        """ Returns the legend's vertical border, in pixels. """

        return self._verborder

[docs]    def SetLabelColour(self, colour):
        """
        Sets the legend label colour.

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

        self._labelcolour = colour
        self.Refresh()

[docs]    def GetLabelColour(self):
        """ Returns the legend label colour. """

        return self._labelcolour

[docs]    def SetLabelFont(self, font):
        """
        Sets the legend label font.

        :param `font`: a valid `wx.Font` object.
        """

        self._labelfont = font
        self.Refresh()

[docs]    def GetLabelFont(self):
        """ Returns the legend label font. """

        return self._labelfont

[docs]    def SetBackColour(self, colour):
        """
        Sets the legend background colour.

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

        self._backcolour = colour
        self.Refresh()

[docs]    def GetBackColour(self):
        """ Returns the legend background colour. """

        return self._backcolour

[docs]    def IsTransparent(self):
        """ Returns whether the legend background is transparent or not. """

        return self._istransparent

[docs]    def OnPaint(self, event):
        """
        Handles the ``wx.EVT_PAINT`` event for L{PieCtrlLegend}.

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

        pdc = wx.PaintDC(self)

        w, h = self.GetSize()
        bmp = wx.EmptyBitmap(w, h)
        mdc = wx.MemoryDC()
        mdc.SelectObject(bmp)

        if self.IsTransparent():

            parentdc = wx.ClientDC(self.GetParent())
            mdc.Blit(0, 0, w, h, self._backgroundDC, 0, 0)

        else:

            mdc.SetBackground(wx.Brush(self._backcolour))
            mdc.Clear()

        dy = self._verborder
        mdc.SetFont(self._labelfont)
        mdc.SetTextForeground(self._labelcolour)
        maxwidth = 0

        for ii in xrange(len(self._parent._series)):

            tw, th = mdc.GetTextExtent(self._parent._series[ii].GetLabel())
            mdc.SetBrush(wx.Brush(self._parent._series[ii].GetColour()))
            mdc.DrawCircle(self._horborder+5, dy+th/2, 5)
            mdc.DrawText(self._parent._series[ii].GetLabel(), self._horborder+15, dy)
            dy = dy + th + 3
            maxwidth = max(maxwidth, int(2*self._horborder+tw+15))

        dy = dy + self._verborder
        if w != maxwidth or h != dy:
            self.SetSize((maxwidth, dy))

        pdc.Blit(0, 0, w, h, mdc, 0, 0)

#----------------------------------------------------------------------
# Class PiePart
# This Class Handles The Legend Segments Properties, Such As Value,
# Colour And Label.
#----------------------------------------------------------------------

[docs]class PiePart(object):
    """
    This class handles the legend segments properties, such as value,
    colour and label.
    """

[docs]    def __init__(self, value=0, colour=wx.BLACK, label=""):
        """
        Default class constructor.

        :param `value`: the pie part value;
        :param `colour`: the pie part colour;
        :param `label`: the pie part text label.
        """

        self._value = value
        self._colour = colour
        self._label = label

[docs]    def SetValue(self, value):
        """
        Sets the segment absolute value.

        :param `value`: a floating point number representing the L{PiePart} value.
        """

        self._value = value

[docs]    def GetValue(self):
        """ Returns the segment absolute value. """

        return self._value

[docs]    def SetColour(self, colour):
        """
        Sets the segment colour.

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

        self._colour = colour

[docs]    def GetColour(self):
        """ Returns the segment colour. """

        return self._colour

[docs]    def SetLabel(self, label):
        """
        Sets the segment label.

        :param `label`: the pie part text label.
        """

        self._label = label

[docs]    def GetLabel(self):
        """ Returns the segment label. """

        return self._label

#----------------------------------------------------------------------
# Class PieCtrl
# This Is The Main PieCtrl Implementation, Used Also By ProgressPie.
#----------------------------------------------------------------------

[docs]class PieCtrl(wx.Window):
    """
    L{PieCtrl} is somewhat a "static" control, that you may create in order to display
    a simple pie chart on a `wx.Panel` or similar.
    """

[docs]    def __init__(self, parent, id=wx.ID_ANY, pos=wx.DefaultPosition,
                 size=wx.DefaultSize, style=0, name="PieCtrl"):
        """
        Default class constructor.

        :param `parent`: the L{PieCtrl} parent. Must not be ``None``;
        :param `id`: window identifier. A value of -1 indicates a default value;
        :param `pos`: the control position. A value of (-1, -1) indicates a default position,
         chosen by either the windowing system or wxPython, depending on platform;
        :param `size`: the control size. A value of (-1, -1) indicates a default size,
         chosen by either the windowing system or wxPython, depending on platform;
        :param `style`: the window style (unused);
        :param `name`: the window name.
        """

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

        self._angle = pi/12
        self._rotationangle = 0
        self._height = 10
        self._background = wx.NullBitmap
        self._canvasbitmap = wx.EmptyBitmap(1, 1)
        self._canvasDC = wx.MemoryDC()
        self._backcolour = wx.WHITE
        self._showedges = True
        self._series = []

        self.Bind(wx.EVT_ERASE_BACKGROUND, lambda x: None)
        self.Bind(wx.EVT_SIZE, self.OnSize)
        self.Bind(wx.EVT_PAINT, self.OnPaint)

        self.RecreateCanvas()
        self._legend = PieCtrlLegend(self, "PieCtrl", -1, wx.Point(10,10), wx.Size(100,75))

[docs]    def SetBackground(self, bmp):
        """
        Sets the L{PieCtrl} background image.

        :param `bmp`: a valid `wx.Bitmap` object.
        """

        self._background = bmp
        self.Refresh()

[docs]    def GetBackground(self):
        """ Returns the L{PieCtrl} background image. """

        return self._background

[docs]    def OnSize(self, event):
        """
        Handles the ``wx.EVT_SIZE`` event for L{PieCtrl}.

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

        self.RecreateCanvas()
        self.Refresh()
        event.Skip()

[docs]    def RecreateCanvas(self):
        """ Recreates the L{PieCtrl} container (canvas). """

        self._canvasbitmap = wx.EmptyBitmap(self.GetSize().GetWidth(),
                                            self.GetSize().GetHeight())
        self._canvasDC.SelectObject(self._canvasbitmap)

[docs]    def GetPartAngles(self):
        """ Returns the angles associated to all segments. """

        angles = []
        total = 0.0

        for ii in xrange(len(self._series)):
            total = total + self._series[ii].GetValue()

        current = 0.0
        angles.append(current)

        for ii in xrange(len(self._series)):

            current = current + self._series[ii].GetValue()
            angles.append(360.0*current/total)

        return angles

[docs]    def SetAngle(self, angle):
        """
        Sets the orientation angle for L{PieCtrl}.

        :param `angle`: the orientation angle for L{PieCtrl}, in radians.
        """

        if angle < 0:
            angle = 0
        if angle > pi/2:
            angle = pi/2

        self._angle = angle
        self.Refresh()

[docs]    def GetAngle(self):
        """ Returns the orientation angle for L{PieCtrl}, in radians. """

        return self._angle

[docs]    def SetRotationAngle(self, angle):
        """
        Sets the angle at which the first sector starts.

        :param `angle`: the first sector angle, in radians.
        """

        if angle < 0:
            angle = 0
        if angle > 2*pi:
            angle = 2*pi

        self._rotationangle = angle
        self.Refresh()

[docs]    def GetRotationAngle(self):
        """ Returns the angle at which the first sector starts, in radians. """

        return self._rotationangle

[docs]    def SetShowEdges(self, value=True):
        """
        Sets whether the L{PieCtrl} edges are visible or not.

        :param `value`: ``True`` to show the edges, ``False`` to hide them.
        """

        self._showedges = value
        self.Refresh()

[docs]    def GetShowEdges(self):
        """ Returns whether the L{PieCtrl} edges are visible or not. """

        return self._showedges

[docs]    def SetBackColour(self, colour):
        """
        Sets the L{PieCtrl} background colour.

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

        self._backcolour = colour
        self.Refresh()

[docs]    def GetBackColour(self):
        """ Returns the L{PieCtrl} background colour. """

        return self._backcolour

[docs]    def SetHeight(self, value):
        """
        Sets the height (in pixels) of the L{PieCtrl}.

        :param `value`: the new height of the widget, in pixels.
        """

        self._height = value

[docs]    def GetHeight(self):
        """ Returns the height (in pixels) of the L{PieCtrl}. """

        return self._height

[docs]    def GetLegend(self):
        """ Returns the L{PieCtrl} legend. """

        return self._legend

[docs]    def DrawParts(self, dc, cx, cy, w, h):
        """
        Draws the L{PieCtrl} external edges.

        :param `dc`: an instance of `wx.DC`;
        :param `cx`: the part `x` coordinate;
        :param `cy`: the part `y` coordinate;
        :param `w`: the control's width;
        :param `h`: the control's height.
        """

        angles = self.GetPartAngles()
        oldpen = dc.GetPen()

        if self._showedges:
            dc.SetPen(wx.BLACK_PEN)

        for ii in xrange(len(angles)):

            if ii > 0:

                if not self._showedges:
                    dc.SetPen(wx.Pen(self._series[ii-1].GetColour()))

                dc.SetBrush(wx.Brush(self._series[ii-1].GetColour()))

                if angles[ii-1] != angles[ii]:
                    dc.DrawEllipticArc(0, int((1-sin(self._angle))*(h/2)+cy), w,
                                       int(h*sin(self._angle)),
                                       angles[ii-1]+self._rotationangle/pi*180,
                                       angles[ii]+self._rotationangle/pi*180)

        if len(self._series) == 1:

            dc.SetBrush(wx.Brush(self._series[0].GetColour()))
            dc.DrawEllipticArc(0, int((1-sin(self._angle))*(h/2)+cy), w,
                               int(h*sin(self._angle)), 0, 360)

        dc.SetPen(oldpen)

[docs]    def Draw(self, pdc):
        """
        Draws all the sectors of L{PieCtrl}.

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

        w, h = self.GetSize()

        self._canvasDC.BeginDrawing()
        self._canvasDC.SetBackground(wx.WHITE_BRUSH)
        self._canvasDC.Clear()

        if self._background != wx.NullBitmap:

            for ii in xrange(0, w, self._background.GetWidth()):

                for jj in xrange(0, h, self._background.GetHeight()):

                    self._canvasDC.DrawBitmap(self._background, ii, jj)

        else:

            self._canvasDC.SetBackground(wx.Brush(self._backcolour))
            self._canvasDC.Clear()

        if len(self._series) > 0:

            if self._angle <= pi/2:
                self.DrawParts(self._canvasDC, 0, int(self._height*cos(self._angle)), w, h)
            else:
                self.DrawParts(self._canvasDC, 0, 0, w, h)

            points = [[0, 0]]*4
            triangle = [[0, 0]]*3
            self._canvasDC.SetPen(wx.Pen(wx.BLACK))
            angles = self.GetPartAngles()
            angleindex = 0
            self._canvasDC.SetBrush(wx.Brush(wx.Colour(self._series[angleindex].GetColour().Red(),
                                                       self._series[angleindex].GetColour().Green(),
                                                       self._series[angleindex].GetColour().Blue())))
            changeangle = False
            x = 0.0

            while x <= 2*pi:

                changeangle = False

                if angleindex < len(angles):

                    if x/pi*180.0 >= angles[angleindex+1]:

                        changeangle = True
                        x = angles[angleindex+1]*pi/180.0

                points[0] = points[1]
                px = int(w/2*(1+cos(x+self._rotationangle)))
                py = int(h/2-sin(self._angle)*h/2*sin(x+self._rotationangle)-1)
                points[1] = [px, py]
                triangle[0] = [w / 2, h / 2]
                triangle[1] = points[0]
                triangle[2] = points[1]

                if x > 0:

                    self._canvasDC.SetBrush(wx.Brush(self._series[angleindex].GetColour()))
                    oldPen = self._canvasDC.GetPen()
                    self._canvasDC.SetPen(wx.Pen(self._series[angleindex].GetColour()))
                    self._canvasDC.DrawPolygon([wx.Point(pts[0], pts[1]) for pts in triangle])
                    self._canvasDC.SetPen(oldPen)

                if changeangle:

                    angleindex = angleindex + 1

                x = x + 0.05

            x = 2*pi
            points[0] = points[1]
            px = int(w/2 * (1+cos(x+self._rotationangle)))
            py = int(h/2-sin(self._angle)*h/2*sin(x+self._rotationangle)-1)
            points[1] = [px, py]
            triangle[0] = [w / 2, h / 2]
            triangle[1] = points[0]
            triangle[2] = points[1]

            self._canvasDC.SetBrush(wx.Brush(self._series[angleindex].GetColour()))
            oldPen = self._canvasDC.GetPen()
            self._canvasDC.SetPen(wx.Pen(self._series[angleindex].GetColour()))
            self._canvasDC.DrawPolygon([wx.Point(pts[0], pts[1]) for pts in triangle])

            self._canvasDC.SetPen(oldPen)
            angleindex = 0

            x = 0.0

            while x <= 2*pi:

                changeangle = False
                if angleindex < len(angles):

                    if x/pi*180 >= angles[angleindex+1]:

                        changeangle = True
                        x = angles[angleindex+1]*pi/180

                points[0] = points[1]
                points[3] = points[2]
                px = int(w/2 * (1+cos(x+self._rotationangle)))
                py = int(h/2-sin(self._angle)*h/2*sin(x+self._rotationangle)-1)
                points[1] = [px, py]
                points[2] = [px, int(py+self._height*cos(self._angle))]

                if w > 0:

                    curColour = wx.Colour(self._series[angleindex].GetColour().Red()*(1.0-float(px)/w),
                                          self._series[angleindex].GetColour().Green()*(1.0-float(px)/w),
                                          self._series[angleindex].GetColour().Blue()*(1.0-float(px)/w))

                    if not self._showedges:
                        self._canvasDC.SetPen(wx.Pen(curColour))

                    self._canvasDC.SetBrush(wx.Brush(curColour))

                if sin(x+self._rotationangle) < 0 and sin(x-0.05+self._rotationangle) <= 0 and x > 0:
                    self._canvasDC.DrawPolygon([wx.Point(pts[0], pts[1]) for pts in points])

                if changeangle:

                    angleindex = angleindex + 1

                x = x + 0.05

            x = 2*pi
            points[0] = points[1]
            points[3] = points[2]
            px = int(w/2 * (1+cos(x+self._rotationangle)))
            py = int(h/2-sin(self._angle)*h/2*sin(x+self._rotationangle)-1)
            points[1] = [px, py]
            points[2] = [px, int(py+self._height*cos(self._angle))]

            if w > 0:

                curColour = wx.Colour(self._series[angleindex].GetColour().Red()*(1.0-float(px)/w),
                                          self._series[angleindex].GetColour().Green()*(1.0-float(px)/w),
                                          self._series[angleindex].GetColour().Blue()*(1.0-float(px)/w))

                if not self._showedges:
                    self._canvasDC.SetPen(wx.Pen(curColour))

                self._canvasDC.SetBrush(wx.Brush(curColour))

            if sin(x+self._rotationangle) < 0 and sin(x-0.05+self._rotationangle) <= 0:
                self._canvasDC.DrawPolygon([wx.Point(pts[0], pts[1]) for pts in points])

            if self._angle <= pi/2:
                self.DrawParts(self._canvasDC, 0, 0, w, h)
            else:
                self.DrawParts(self._canvasDC, 0, int(self._height*cos(self._angle)), w, h)

        self._canvasDC.EndDrawing()

        pdc.Blit(0, 0, w, h, self._canvasDC, 0, 0)
        self._legend.RecreateBackground(self._canvasDC)

[docs]    def OnPaint(self, event):
        """
        Handles the ``wx.EVT_PAINT`` event for L{PieCtrl}.

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

        pdc = wx.PaintDC(self)
        self.Draw(pdc)

#----------------------------------------------------------------------
# Class ProgressPie
# This Is The Main ProgressPie Implementation. Is Is A Subclassing Of
# PieCtrl, With 2 Sectors.
#----------------------------------------------------------------------

[docs]class ProgressPie(PieCtrl):
    """
    L{ProgressPie} tries to emulate the behavior of `wx.ProgressDialog`, but
    using a pie chart instead of a gauge.
    """

[docs]    def __init__(self, parent, maxvalue, value, id=wx.ID_ANY,
                 pos=wx.DefaultPosition, size=wx.DefaultSize, style=0):
        """
        Default class constructor.

        :param `parent`: the L{PieCtrl} parent. Must not be ``None``;
        :param `id`: window identifier. A value of -1 indicates a default value;
        :param `pos`: the control position. A value of (-1, -1) indicates a default position,
         chosen by either the windowing system or wxPython, depending on platform;
        :param `size`: the control size. A value of (-1, -1) indicates a default size,
         chosen by either the windowing system or wxPython, depending on platform;
        :param `style`: the window style (unused);
        :param `name`: the window name.
        """

        PieCtrl.__init__(self, parent, id, pos, size, style)

        self._maxvalue = maxvalue
        self._value = value
        self.GetLegend().Hide()

        self._filledcolour = wx.Colour(0, 0, 127)
        self._unfilledcolour = wx.WHITE
        part = PiePart()
        part.SetColour(self._filledcolour)
        a = min(float(value), maxvalue)
        part.SetValue(max(a, 0.0))
        self._series.append(part)
        part = PiePart()
        part.SetColour(self._unfilledcolour)
        part.SetValue(max(0.0, maxvalue-part.GetValue()))
        self._series.append(part)

[docs]    def SetValue(self, value):
        """
        Sets the L{ProgressPie} value.

        :param `value`: a floating point number representing the new value.
        """

        self._value = min(value, self._maxvalue)
        self._series[0].SetValue(max(self._value, 0.0))
        self._series[1].SetValue(max(self._maxvalue-self._value, 0.0))
        self.Refresh()

[docs]    def GetValue(self):
        """ Returns the L{ProgressPie} value. """

        return self._value

[docs]    def SetMaxValue(self, value):
        """
        Sets the L{ProgressPie} maximum value.

        :param `value`: a floating point number representing the maximum value.
        """

        self._maxvalue = value
        self._value = min(self._value, self._maxvalue)
        self._series[0].SetValue(max(self._value, 0.0))
        self._series[1].SetValue(max(self._maxvalue-self._value, 0.0))
        self.Refresh()

[docs]    def GetMaxValue(self):
        """ Returns the L{ProgressPie}  maximum value. """

        return self._maxvalue

[docs]    def SetFilledColour(self, colour):
        """
        Sets the colour that progressively fills the L{ProgressPie} .

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

        self._filledcolour = colour
        self._series[0].SetColour(self._filledcolour)
        self.Refresh()

[docs]    def SetUnfilledColour(self, colour):
        """
        Sets the colour that is filled.

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

        self._unfilledcolour= colour
        self._series[1].SetColour(self._unfilledcolour)
        self.Refresh()

[docs]    def GetFilledColour(self):
        """ Returns the colour that progressively fills the L{ProgressPie}. """

        return self._filledcolour

[docs]    def GetUnfilledColour(self):
        """ Returns the colour that is filled. """

        return self._unfilledcolour

Navigation

  • index
  • modules |
  • Home |
  • Gallery |
  • Contents»
  • Module code »
  • piectrl


pybusyinfo

  • modules |
  • Home |
  • Gallery |
  • Contents»
  • Module code »
  • pybusyinfo

Source code for pybusyinfo

"""
L{PyBusyInfo} constructs a busy info window and displays a message in it.

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

L{PyBusyInfo} constructs a busy info window and displays a message in it.

This class makes it easy to tell your user that the program is temporarily busy.
Just create a L{PyBusyInfo} object, and within the current scope, a message window
will be shown.

For example::

    busy = PyBusyInfo("Please wait, working...")

    for i in xrange(10000):
        DoACalculation()

    del busy

It works by creating a window in the constructor, and deleting it in the destructor.
You may also want to call `wx.Yield()` to refresh the window periodically (in case
it had been obscured by other windows, for example).

Usage
=====

Usage example::

    import wx
    import wx.lib.agw.pybusyinfo as PBI

    class MyFrame(wx.Frame):

        def __init__(self, parent):

            wx.Frame.__init__(self, parent, -1, "PyBusyInfo Demo")

            panel = wx.Panel(self)

            b = wx.Button(panel, -1, "Test PyBusyInfo ", (50,50))
            self.Bind(wx.EVT_BUTTON, self.OnButton, b)

        def OnButton(self, event):

            message = "Please wait 5 seconds, working..."
            busy = PBI.PyBusyInfo(message, parent=self, title="Really Busy")

            wx.Yield()

            for indx in xrange(5):
                wx.MilliSleep(1000)

            del busy

    # our normal wxApp-derived class, as usual

    app = wx.PySimpleApp()

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

    app.MainLoop()

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

L{PyBusyInfo} has been tested on the following platforms:
  * Windows (Windows XP).

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

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

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

`No custom events are available for this class.`

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

L{PyBusyInfo} is distributed under the wxPython license.

Latest Revision: Andrea Gavana @ 17 Aug 2011, 15.00 GMT

Version 0.1

"""

import wx

_ = wx.GetTranslation

[docs]class PyInfoFrame(wx.Frame):
    """ Base class for L{PyBusyInfo}. """

[docs]    def __init__(self, parent, message, title, icon):
        """
        Default class constructor.

        :param `parent`: the frame parent;
        :param `message`: the message to display in the L{PyBusyInfo};
        :param `title`: the main L{PyBusyInfo} title;
        :param `icon`: an icon to draw as the frame icon, an instance of `wx.Bitmap`.
        """

        wx.Frame.__init__(self, parent, wx.ID_ANY, title, wx.DefaultPosition,
                          wx.DefaultSize, wx.NO_BORDER|wx.FRAME_TOOL_WINDOW|wx.FRAME_SHAPED|wx.STAY_ON_TOP)

        panel = wx.Panel(self)
        panel.SetCursor(wx.HOURGLASS_CURSOR)

        self._message = message
        self._title = title
        self._icon = icon

        dc = wx.ClientDC(self)
        textWidth, textHeight, dummy = dc.GetMultiLineTextExtent(self._message)
        sizeText = wx.Size(textWidth, textHeight)

        self.SetClientSize((max(sizeText.x, 340) + 60, max(sizeText.y, 40) + 60))
        # need to size the panel correctly first so that text.Centre() works
        panel.SetSize(self.GetClientSize())

        # Bind the events to draw ourselves
        panel.Bind(wx.EVT_PAINT, self.OnPaint)
        panel.Bind(wx.EVT_ERASE_BACKGROUND, self.OnErase)

        self.Centre(wx.BOTH)

        # Create a non-rectangular region to set the frame shape
        size = self.GetSize()
        bmp = wx.EmptyBitmap(size.x, size.y)
        dc = wx.BufferedDC(None, bmp)
        dc.SetBackground(wx.Brush(wx.Colour(0, 0, 0), wx.SOLID))
        dc.Clear()
        dc.SetPen(wx.Pen(wx.Colour(0, 0, 0), 1))
        dc.DrawRoundedRectangle(0, 0, size.x, size.y, 12)
        r = wx.RegionFromBitmapColour(bmp, wx.Colour(0, 0, 0))
        # Store the non-rectangular region
        self.reg = r

        if wx.Platform == "__WXGTK__":
            self.Bind(wx.EVT_WINDOW_CREATE, self.SetBusyShape)
        else:
            self.SetBusyShape()

        # Add a custom bitmap at the top (if any)

[docs]    def SetBusyShape(self, event=None):
        """
        Sets L{PyInfoFrame} shape using the region created from the bitmap.

        :param `event`: a `wx.WindowCreateEvent` event (GTK only, as GTK supports setting
         the window shape only during window creation).
        """

        self.SetShape(self.reg)
        if event:
            # GTK only
            event.Skip()

[docs]    def OnPaint(self, event):
        """
        Handles the ``wx.EVT_PAINT`` event for L{PyInfoFrame}.

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

        panel = event.GetEventObject()

        dc = wx.BufferedPaintDC(panel)
        dc.Clear()

        # Fill the background with a gradient shading
        startColour = wx.SystemSettings_GetColour(wx.SYS_COLOUR_ACTIVECAPTION)
        endColour = wx.WHITE

        rect = panel.GetRect()
        dc.GradientFillLinear(rect, startColour, endColour, wx.SOUTH)

        # Draw the label
        font = wx.SystemSettings_GetFont(wx.SYS_DEFAULT_GUI_FONT)
        dc.SetFont(font)

        # Draw the message
        rect2 = wx.Rect(*rect)
        rect2.height += 20
        dc.DrawLabel(self._message, rect2, alignment=wx.ALIGN_CENTER|wx.ALIGN_CENTER)

        # Draw the top title
        font.SetWeight(wx.BOLD)
        dc.SetFont(font)
        dc.SetPen(wx.Pen(wx.SystemSettings_GetColour(wx.SYS_COLOUR_CAPTIONTEXT)))
        dc.SetTextForeground(wx.SystemSettings_GetColour(wx.SYS_COLOUR_CAPTIONTEXT))

        if self._icon.IsOk():
            iconWidth, iconHeight = self._icon.GetWidth(), self._icon.GetHeight()
            dummy, textHeight = dc.GetTextExtent(self._title)
            textXPos, textYPos = iconWidth + 10, (iconHeight-textHeight)/2
            dc.DrawBitmap(self._icon, 5, 5, True)
        else:
            textXPos, textYPos = 5, 0

        dc.DrawText(self._title, textXPos, textYPos+5)
        dc.DrawLine(5, 25, rect.width-5, 25)

        size = self.GetSize()
        dc.SetPen(wx.Pen(startColour, 1))
        dc.SetBrush(wx.TRANSPARENT_BRUSH)
        dc.DrawRoundedRectangle(0, 0, size.x, size.y-1, 12)

[docs]    def OnErase(self, event):
        """
        Handles the ``wx.EVT_ERASE_BACKGROUND`` event for L{PyInfoFrame}.

        :param `event`: a `wx.EraseEvent` event to be processed.

        :note: This method is intentionally empty to reduce flicker.
        """

        # This is empty on purpose, to avoid flickering
        pass

# -------------------------------------------------------------------- #
# The actual PyBusyInfo implementation
# -------------------------------------------------------------------- #

[docs]class PyBusyInfo(object):
    """
    Constructs a busy info window as child of parent and displays a message in it.
    """

[docs]    def __init__(self, message, parent=None, title=_("Busy"), icon=wx.NullBitmap):
        """
        Default class constructor.

        :param `parent`: the L{PyBusyInfo} parent;
        :param `message`: the message to display in the L{PyBusyInfo};
        :param `title`: the main L{PyBusyInfo} title;
        :param `icon`: an icon to draw as the frame icon, an instance of `wx.Bitmap`.

        :note: If `parent` is not ``None`` you must ensure that it is not closed
         while the busy info is shown.
        """

        self._infoFrame = PyInfoFrame(parent, message, title, icon)

        if parent and parent.HasFlag(wx.STAY_ON_TOP):
            # we must have this flag to be in front of our parent if it has it
            self._infoFrame.SetWindowStyleFlag(wx.STAY_ON_TOP)

        self._infoFrame.Show(True)
        self._infoFrame.Refresh()
        self._infoFrame.Update()

    def __del__(self):
        """ Overloaded method, for compatibility with wxWidgets. """

        self._infoFrame.Show(False)
        self._infoFrame.Destroy()

Navigation

  • index
  • modules |
  • Home |
  • Gallery |
  • Contents»
  • Module code »
  • pybusyinfo


pycollapsiblepane

  • modules |
  • Home |
  • Gallery |
  • Contents»
  • Module code »
  • pycollapsiblepane

Source code for pycollapsiblepane

# --------------------------------------------------------------------------------- #
# PYCOLLAPSIBLEPANE wxPython IMPLEMENTATION
# Generic Implementation Based On wx.CollapsiblePane.
#
# Andrea Gavana, @ 09 Aug 2007
# Latest Revision: 17 Aug 2011, 15.00 GMT
#
#
# For All Kind Of Problems, Requests Of Enhancements And Bug Reports, Please
# Write To Me At:
#
# andrea.gavana@maerskoil.com
# andrea.gavana@gmail.com
#
# Or, Obviously, To The wxPython Mailing List!!!
#
#
# End Of Comments
# --------------------------------------------------------------------------------- #

"""
L{PyCollapsiblePane} is a container with an embedded button-like control which
can be used by the user to collapse or expand the pane's contents.

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

A collapsible pane is a container with an embedded button-like control which
can be used by the user to collapse or expand the pane's contents.
Once constructed you should use the L{GetPane} function to access the pane and
add your controls inside it (i.e. use the window returned from L{GetPane} as the
parent for the controls which must go in the pane, **not** the L{PyCollapsiblePane}
itself!).

:note: Note that because of its nature of control which can dynamically (and drastically)
 change its size at run-time under user-input, when putting L{PyCollapsiblePane}
 inside a `wx.Sizer` you should be careful to add it with a proportion value of zero;
 this is because otherwise all other windows with non-null proportion values would
 automatically get resized each time the user expands or collapse the pane window
 resulting usually in a weird, flickering effect.

Usage
=====

Usage example::

    import wx
    import wx.lib.agw.pycollapsiblepane as PCP

    class MyFrame(wx.Frame):

        def __init__(self, parent):

            wx.Frame.__init__(self, parent, -1, "PyCollapsiblePane Demo")

            panel = wx.Panel(self)

            title = wx.StaticText(panel, label="PyCollapsiblePane")
            title.SetFont(wx.Font(18, wx.SWISS, wx.NORMAL, wx.BOLD))
            title.SetForegroundColour("blue")

            self.cp = cp = PCP.PyCollapsiblePane(panel, label=label1,
                                                 style=wx.CP_DEFAULT_STYLE|wx.CP_NO_TLW_RESIZE)

            self.MakePaneContent(cp.GetPane())

            sizer = wx.BoxSizer(wx.VERTICAL)
            sizer.Add(title, 0, wx.ALL, 25)
            sizer.Add(cp, 0, wx.RIGHT|wx.LEFT|wx.EXPAND, 25)

            panel.SetSizer(sizer)
            sizer.Layout()

        def MakePaneContent(self, pane):
            ''' Just makes a few controls to put on `PyCollapsiblePane`. '''

            nameLbl = wx.StaticText(pane, -1, "Name:")
            name = wx.TextCtrl(pane, -1, "");

            addrLbl = wx.StaticText(pane, -1, "Address:")
            addr1 = wx.TextCtrl(pane, -1, "");
            addr2 = wx.TextCtrl(pane, -1, "");

            cstLbl = wx.StaticText(pane, -1, "City, State, Zip:")
            city  = wx.TextCtrl(pane, -1, "", size=(150,-1));
            state = wx.TextCtrl(pane, -1, "", size=(50,-1));
            zip   = wx.TextCtrl(pane, -1, "", size=(70,-1));

            addrSizer = wx.FlexGridSizer(cols=2, hgap=5, vgap=5)
            addrSizer.AddGrowableCol(1)
            addrSizer.Add(nameLbl, 0,
                          wx.ALIGN_RIGHT|wx.ALIGN_CENTER_VERTICAL)
            addrSizer.Add(name, 0, wx.EXPAND)
            addrSizer.Add(addrLbl, 0,
                          wx.ALIGN_RIGHT|wx.ALIGN_CENTER_VERTICAL)
            addrSizer.Add(addr1, 0, wx.EXPAND)
            addrSizer.Add((5,5))
            addrSizer.Add(addr2, 0, wx.EXPAND)

            addrSizer.Add(cstLbl, 0,
                          wx.ALIGN_RIGHT|wx.ALIGN_CENTER_VERTICAL)

            cstSizer = wx.BoxSizer(wx.HORIZONTAL)
            cstSizer.Add(city, 1)
            cstSizer.Add(state, 0, wx.LEFT|wx.RIGHT, 5)
            cstSizer.Add(zip)
            addrSizer.Add(cstSizer, 0, wx.EXPAND)

            border = wx.BoxSizer()
            border.Add(addrSizer, 1, wx.EXPAND|wx.ALL, 5)
            pane.SetSizer(border)

    # our normal wxApp-derived class, as usual

    app = wx.PySimpleApp()

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

    app.MainLoop()

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

This class supports the following window styles:

==================== =========== ==================================================
Window Styles        Hex Value   Description
==================== =========== ==================================================
``CP_NO_TLW_RESIZE``         0x2 By default L{PyCollapsiblePane} resizes the top level window containing it when its own size changes. This allows to easily implement dialogs containing an optionally shown part, for example, and so is the default behaviour but can be inconvenient in some specific cases -- use this flag to disable this automatic parent resizing then.
``CP_GTK_EXPANDER``          0x4 Uses a GTK expander instead of a button.
``CP_USE_STATICBOX``         0x8 Uses a `wx.StaticBox` around L{PyCollapsiblePane}.
``CP_LINE_ABOVE``           0x10 Draws a line above L{PyCollapsiblePane}.
==================== =========== ==================================================

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

This class processes the following events:

=============================== ==================================================
Event Name                      Description
=============================== ==================================================
``EVT_COLLAPSIBLEPANE_CHANGED`` The user showed or hid the collapsible pane.
=============================== ==================================================

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

L{PyCollapsiblePane} is distributed under the wxPython license.

Latest Revision: Andrea Gavana @ 17 Aug 2011, 15.00 GMT

Version 0.4

"""

import wx

CP_GTK_EXPANDER = 4
""" Uses a GTK expander instead of a button. """
CP_USE_STATICBOX = 8
""" Uses a `wx.StaticBox` around L{PyCollapsiblePane}. """
CP_LINE_ABOVE = 16
""" Draws a line above L{PyCollapsiblePane}. """
CP_DEFAULT_STYLE = wx.CP_DEFAULT_STYLE
""" The default style. It includes ``wx.TAB_TRAVERSAL`` and ``wx.BORDER_NONE``. """
CP_NO_TLW_RESIZE = wx.CP_NO_TLW_RESIZE
""" By default L{PyCollapsiblePane} resizes the top level window containing it when its""" \
""" own size changes. This allows to easily implement dialogs containing an optionally""" \
""" shown part, for example, and so is the default behaviour but can be inconvenient""" \
""" in some specific cases -- use this flag to disable this automatic parent resizing then. """

# inject into the wx namespace with the other CP_* constants
wx.CP_GTK_EXPANDER = CP_GTK_EXPANDER
wx.CP_USE_STATICBOX = CP_USE_STATICBOX
wx.CP_LINE_ABOVE = CP_LINE_ABOVE

# PyCollapsiblePane events
EVT_COLLAPSIBLEPANE_CHANGED = wx.EVT_COLLAPSIBLEPANE_CHANGED
""" The user showed or hid the collapsible pane. """

#-----------------------------------------------------------------------------
# 2.9 deprecates SetSpacer, so we'll use AssignSpacer and monkey-patch 2.8 so
# it works there too

if wx.VERSION < (2, 9):
    wx.SizerItem.AssignSpacer = wx.SizerItem.SetSpacer

#-----------------------------------------------------------------------------
# GTKExpander widget
#-----------------------------------------------------------------------------

[docs]class GTKExpander(wx.PyControl):
    """
    A L{GTKExpander} allows the user to hide or show its child by clicking on an expander
    triangle.
    """

[docs]    def __init__(self, parent, id=wx.ID_ANY, label="", pos=wx.DefaultPosition,
                 size=wx.DefaultSize, style=wx.NO_BORDER):
        """
        Default class constructor.

        :param `parent`: the L{GTKExpander} parent. Must not be ``None``;
        :param `id`: window identifier. A value of -1 indicates a default value;
        :param `label`: the expander 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;
        :param `size`: the control size. A value of (-1, -1) indicates a default size,
         chosen by either the windowing system or wxPython, depending on platform;
        :param `style`: the expander style.
        """

        wx.PyControl.__init__(self, parent, id, pos, size, style)
        self.SetLabel(label)

        self.SetBackgroundStyle(wx.BG_STYLE_CUSTOM)
        self._parent = parent

        self.Bind(wx.EVT_SIZE, self.OnSize)

[docs]    def OnDrawGTKExpander(self, dc):
        """
        Draws the L{GTKExpander} triangle.

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

        size = self.GetSize()
        label = self._parent.GetBtnLabel()
        triangleWidth, triangleHeight = self._parent.GetExpanderDimensions()
        textWidth, textHeight, descent, externalLeading = dc.GetFullTextExtent(label, self.GetFont())

        dc.SetBrush(wx.BLACK_BRUSH)
        dc.SetPen(wx.BLACK_PEN)

        if self._parent.IsCollapsed():
            startX, startY = triangleWidth/2, size.y - triangleHeight - 1 - descent
            pt1 = wx.Point(startX, startY)
            pt2 = wx.Point(startX, size.y - 1 - descent)
            pt3 = wx.Point(startX+triangleWidth, size.y-triangleHeight/2 - 1 - descent)
        else:

            startX, startY = 0, size.y - triangleWidth - descent - 1
            pt1 = wx.Point(startX, startY)
            pt2 = wx.Point(startX+triangleHeight, startY)
            pt3 = wx.Point(startX+triangleHeight/2, size.y - descent - 1)

        dc.DrawPolygon([pt1, pt2, pt3])

[docs]    def OnDrawGTKText(self, dc):
        """
        Draws the L{GTKExpander} text label.

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

        size = self.GetSize()
        label = self._parent.GetBtnLabel()
        triangleWidth, triangleHeight = self._parent.GetExpanderDimensions()
        textWidth, textHeight, descent, externalLeading = dc.GetFullTextExtent(label, self.GetFont())
        dc.SetFont(self.GetFont())

        startX, startY = 2*triangleHeight+1, size.y - textHeight
        dc.DrawText(label, startX, startY)

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

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

        triangleWidth, triangleHeight = self._parent.GetExpanderDimensions()
        label = self._parent.GetBtnLabel()
        dc = wx.ClientDC(self)
        textWidth, textHeight, descent, externalLeading = dc.GetFullTextExtent(label, self.GetFont())

        maxHeight = max(textHeight+descent, triangleHeight)
        maxWidth = 2*triangleHeight+1 + textWidth

        return wx.Size(maxWidth, maxHeight)

[docs]    def OnSize(self, event):
        """
        Handles the ``wx.EVT_SIZE`` event for L{GTKExpander}.

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

        self.Refresh()

#-----------------------------------------------------------------------------
# PyCollapsiblePane
#-----------------------------------------------------------------------------

[docs]class PyCollapsiblePane(wx.PyPanel):
    """
    L{PyCollapsiblePane} is a container with an embedded button-like control which
    can be used by the user to collapse or expand the pane's contents.
    """

[docs]    def __init__(self, parent, id=wx.ID_ANY, label="", pos=wx.DefaultPosition,
                 size=wx.DefaultSize, style=0, agwStyle=wx.CP_DEFAULT_STYLE,
                 validator=wx.DefaultValidator, name="PyCollapsiblePane"):
        """
        Default class constructor.

        :param `parent`: the L{PyCollapsiblePane} parent. Must not be ``None``;
        :param `id`: window identifier. A value of -1 indicates a default value;
        :param `label`: The initial label shown in the button which allows the
         user to expand or collapse the pane window.
        :param `pos`: the control position. A value of (-1, -1) indicates a default position,
         chosen by either the windowing system or wxPython, depending on platform;
        :param `size`: the control size. A value of (-1, -1) indicates a default size,
         chosen by either the windowing system or wxPython, depending on platform;
        :param `style`: the underlying `wx.PyPanel` window style;
        :param `agwStyle`: the AGW-specifi window style. This can be a combination of the
         following bits:

         ==================== =========== ==================================================
         Window Styles        Hex Value   Description
         ==================== =========== ==================================================
         ``CP_NO_TLW_RESIZE``         0x2 By default L{PyCollapsiblePane} resizes the top level window containing it when its own size changes. This allows to easily implement dialogs containing an optionally shown part, for example, and so is the default behaviour but can be inconvenient in some specific cases -- use this flag to disable this automatic parent resizing then.
         ``CP_GTK_EXPANDER``          0x4 Uses a GTK expander instead of a button.
         ``CP_USE_STATICBOX``         0x8 Uses a `wx.StaticBox` around L{PyCollapsiblePane}.
         ``CP_LINE_ABOVE``           0x10 Draws a line above L{PyCollapsiblePane}.
         ==================== =========== ==================================================

        :param `validator`: the validator associated to the L{PyCollapsiblePane};
        :param `name`: the widget name.

        """

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

        self._pButton = self._pStaticLine = self._pPane = self._sz = None
        self._strLabel = label
        self._bCollapsed = True
        self._agwStyle = agwStyle

        self._pPane = wx.Panel(self, style=wx.TAB_TRAVERSAL|wx.NO_BORDER)
        self._pPane.Hide()

        if self.HasAGWFlag(CP_USE_STATICBOX):
            # Use a StaticBox instead of a StaticLine, and the button's
            # position will be handled separately so don't put it in the sizer
            self._pStaticBox = wx.StaticBox(self)
            self.SetButton(wx.Button(self, wx.ID_ANY, self.GetLabel(), style=wx.BU_EXACTFIT))
            self._sz = wx.BoxSizer(wx.VERTICAL)
            self._sz.Add((1,1))  # spacer, size will be reset later
            self._contentSizer = wx.StaticBoxSizer(self._pStaticBox, wx.VERTICAL)
            self._contentSizer.Add((1,1))  # spacer, size will be reset later
            self._contentSizer.Add(self._pPane, 1, wx.EXPAND)
            self._sz.Add(self._contentSizer, 1, wx.EXPAND)

            if self.HasAGWFlag(CP_USE_STATICBOX) and 'wxMSW' in wx.PlatformInfo:
                # This hack is needed on Windows because wxMSW clears the
                # CLIP_SIBLINGS style from all sibling controls that overlap the
                # static box, so the box ends up overdrawing the button since we
                # have the button overlapping the box. This hack will ensure that
                # the button is refreshed after every time that the box is drawn.
                # This adds a little flicker but it is not too bad compared to
                # others.
                def paint(evt):
                    def updateBtn():
                        if self and self._pButton:
                            self._pButton.Refresh()
                            self._pButton.Update()
                    wx.CallAfter(updateBtn)
                    evt.Skip()
                self._pStaticBox.Bind(wx.EVT_PAINT, paint)

        elif self.HasAGWFlag(CP_GTK_EXPANDER):
            self._sz = wx.BoxSizer(wx.HORIZONTAL)
            self.SetExpanderDimensions(3, 6)
            self.SetButton(GTKExpander(self, wx.ID_ANY, self.GetLabel()))
            self._sz.Add(self._pButton, 0, wx.LEFT|wx.TOP|wx.BOTTOM, self.GetBorder())

            self._pButton.Bind(wx.EVT_PAINT, self.OnDrawGTKStyle)
            self._pButton.Bind(wx.EVT_LEFT_DOWN, self.OnButton)
            if wx.Platform == "__WXMSW__":
                self._pButton.Bind(wx.EVT_LEFT_DCLICK, self.OnButton)

        else:
            # create children and lay them out using a wx.BoxSizer
            # (so that we automatically get RTL features)
            self.SetButton(wx.Button(self, wx.ID_ANY, self.GetLabel(), style=wx.BU_EXACTFIT))
            self._pStaticLine = wx.StaticLine(self, wx.ID_ANY)

            if self.HasAGWFlag(CP_LINE_ABOVE):
                # put the static line above the button
                self._sz = wx.BoxSizer(wx.VERTICAL)
                self._sz.Add(self._pStaticLine, 0, wx.ALL|wx.GROW, self.GetBorder())
                self._sz.Add(self._pButton, 0, wx.LEFT|wx.RIGHT|wx.BOTTOM, self.GetBorder())
            else:
                # arrange the static line and the button horizontally
                self._sz = wx.BoxSizer(wx.HORIZONTAL)
                self._sz.Add(self._pButton, 0, wx.LEFT|wx.TOP|wx.BOTTOM, self.GetBorder())
                self._sz.Add(self._pStaticLine, 1, wx.ALIGN_CENTER|wx.LEFT|wx.RIGHT, self.GetBorder())

        self.Bind(wx.EVT_SIZE, self.OnSize)

[docs]    def SetAGWWindowStyleFlag(self, agwStyle):
        """
        Sets the L{PyCollapsiblePane} window style flags.

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

         ==================== =========== ==================================================
         Window Styles        Hex Value   Description
         ==================== =========== ==================================================
         ``CP_NO_TLW_RESIZE``         0x2 By default L{PyCollapsiblePane} resizes the top level window containing it when its own size changes. This allows to easily implement dialogs containing an optionally shown part, for example, and so is the default behaviour but can be inconvenient in some specific cases -- use this flag to disable this automatic parent resizing then.
         ``CP_GTK_EXPANDER``          0x4 Uses a GTK expander instead of a button.
         ``CP_USE_STATICBOX``         0x8 Uses a `wx.StaticBox` around L{PyCollapsiblePane}.
         ``CP_LINE_ABOVE``           0x10 Draws a line above L{PyCollapsiblePane}.
         ==================== =========== ==================================================

        """

        self._agwStyle = agwStyle
        self.Layout()
        self.Refresh()

[docs]    def GetAGWWindowStyleFlag(self):
        """
        Returns the L{PyCollapsiblePane} window style.

        :see: L{SetAGWWindowStyleFlag} for a list of possible window style flags.
        """

        return self._agwStyle

[docs]    def HasAGWFlag(self, flag):
        """
        Returns whether a flag is present in the L{PyCollapsiblePane} style.

        :param `flag`: one of the possible L{PyCollapsiblePane} window styles.

        :see: L{SetAGWWindowStyleFlag} for a list of possible window style flags.
        """

        agwStyle = self.GetAGWWindowStyleFlag()
        res = (agwStyle & flag and [True] or [False])[0]
        return res

[docs]    def GetBtnLabel(self):
        """ Returns the button label. """

        if self.GetAGWWindowStyleFlag() & CP_GTK_EXPANDER:
            return self.GetLabel()

        return self.GetLabel() + (self.IsCollapsed() and [" >>"] or [" <<"])[0]

[docs]    def OnStateChange(self, sz):
        """
        Handles the status changes (collapsing/expanding).

        :param `sz`: an instance of `wx.Size`.
        """

        # minimal size has priority over the best size so set here our min size
        self.SetMinSize(sz)
        self.SetSize(sz)

        if self.HasAGWFlag(wx.CP_NO_TLW_RESIZE):
            # the user asked to explicitely handle the resizing itself...
            return

        # NB: the following block of code has been accurately designed to
        #     as much flicker-free as possible be careful when modifying it!

        top = wx.GetTopLevelParent(self)
        if top:
            # NB: don't Layout() the 'top' window as its size has not been correctly
            #     updated yet and we don't want to do an initial Layout() with the old
            #     size immediately followed by a SetClientSize/Fit call for the new
            #     size that would provoke flickering!

            if top.GetSizer():
                if (wx.Platform == "__WXGTK__" and self.IsCollapsed()) or wx.Platform != "__WXGTK__":
                # FIXME: the SetSizeHints() call would be required also for GTK+ for
                #        the expanded.collapsed transition. Unfortunately if we
                #        enable this line, then the GTK+ top window won't always be
                #        resized by the SetClientSize() call below! As a side effect
                #        of this dirty fix, the minimal size for the pane window is
                #        not set in GTK+ and the user can hide it shrinking the "top"
                #        window...

                    top.GetSizer().SetSizeHints(top)

            # we shouldn't attempt to resize a maximized window, whatever happens
            if not top.IsMaximized():

                if self.IsCollapsed():
                    # expanded . collapsed transition
                    if top.GetSizer():
                        # we have just set the size hints...
                        sz = top.GetSizer().CalcMin()

                        # use SetClientSize() and not SetSize() otherwise the size for
                        # e.g. a wxFrame with a menubar wouldn't be correctly set
                        top.SetClientSize(sz)

                    else:

                        top.Layout()

                else:

                    # collapsed . expanded transition

                    # force our parent to "fit", i.e. expand so that it can honour
                    # our minimal size
                    top.Fit()

[docs]    def Collapse(self, collapse=True):
        """
        Collapses or expands the pane window.

        :param `collapse`: ``True`` to collapse the pane window, ``False`` to expand it.
        """

        # optimization
        if self.IsCollapsed() == collapse:
            return

        self.Freeze()

        # update our state
        self._pPane.Show(not collapse)
        self._bCollapsed = collapse
        self.Thaw()

        # update button label
        # NB: this must be done after updating our "state"
        self._pButton.SetLabel(self.GetBtnLabel())

        self.OnStateChange(self.GetBestSize())

[docs]    def Expand(self):
        """ Same as L{Collapse} (False). """

        self.Collapse(False)

[docs]    def IsCollapsed(self):
        """ Returns ``True`` if the pane window is currently hidden. """

        return self._bCollapsed

[docs]    def IsExpanded(self):
        """ Returns ``True`` if the pane window is currently shown. """

        return not self.IsCollapsed()

[docs]    def GetPane(self):
        """
        Returns a reference to the pane window. Use the returned `wx.Window` as
        the parent of widgets to make them part of the collapsible area.
        """

        return self._pPane

[docs]    def SetLabel(self, label):
        """
        Sets the button label.

        :param `label`: the new button label.

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

        self._strLabel =  label
        self._pButton.SetLabel(self.GetBtnLabel())
        self._pButton.SetInitialSize()
        self._pButton.Refresh()

        self.Layout()

[docs]    def GetLabel(self):
        """
        Returns the button label.

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

        return self._strLabel

[docs]    def SetButtonFont(self, font):
        """
        Sets the button font.

        :param `font`: a valid `wx.Font` object.
        """

        self._pButton.SetFont(font)
        self.Layout()

[docs]    def GetButtonFont(self):
        """ Returns the button font. """

        return self._pButton.GetFont()

[docs]    def GetBorder(self):
        """ Returns the L{PyCollapsiblePane} border in pixels (platform dependent). """

        if wx.Platform == "__WXMAC__":
            return 6
        elif wx.Platform == "__WXGTK__":
            return 3
        elif wx.Platform == "__WXMSW__":
            return self._pButton.ConvertDialogSizeToPixels(wx.Size(2, 0)).x
        else:
            return 5

[docs]    def SetExpanderDimensions(self, width, height):
        """
        Sets the expander width and height.

        :param `width`: an integer specifying the expander width in pixels;
        :param `height`: an integer specifying the expander height in pixels.
        """

        self._expanderDimensions = width, height
        if self._sz:
            self._sz.Layout()
        if self._pButton:
            self._pButton.Refresh()

[docs]    def GetExpanderDimensions(self):
        """
        Returns the expander dimensions, a tuple of integers representing the
        width and height of the expander, in pixels.
        """

        return self._expanderDimensions

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

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

        if self.HasAGWFlag(CP_USE_STATICBOX):
            # In this case the button is not in the sizer, and the static box
            # is not shown when not expanded, so use the size of the button as
            # our stating point. But first we'll make sure that it is it's
            # best size.
            sz = self._pButton.GetBestSize()
            self._pButton.SetSize(sz)
            bdr = self.GetBorder()
            sz += (2*bdr, 2*bdr)

            if self.IsExpanded():
                # Reset the spacer sizes to be based on the button size
                adjustment = 0
                if 'wxMac' not in wx.PlatformInfo:
                    adjustment = -3
                self._sz.Children[0].AssignSpacer((1, sz.height/2 + adjustment))
                self._contentSizer.Children[0].AssignSpacer((1, sz.height/2))

                ssz = self._sz.GetMinSize()
                sz.width = max(sz.width, ssz.width)
                sz.height = max(sz.height, ssz.height)

        else:
            # do not use GetSize() but rather GetMinSize() since it calculates
            # the required space of the sizer
            sz = self._sz.GetMinSize()

            # when expanded, we need more space
            if self.IsExpanded():
                pbs = self._pPane.GetBestSize()
                sz.width = max(sz.GetWidth(), pbs.x)
                sz.height = sz.y + self.GetBorder() + pbs.y

        return sz

[docs]    def Layout(self):
        """ Layout the L{PyCollapsiblePane}. """

        if not self._pButton or not self._pPane or not self._sz:
            return False     # we need to complete the creation first!

        oursz = self.GetSize()

        if self.HasAGWFlag(CP_USE_STATICBOX):
            bdr = self.GetBorder()
            self._pButton.SetPosition((bdr, bdr))

            if self.IsExpanded():
                self._pPane.Show()
                self._pPane.Layout()
                self._pStaticBox.Show()
                self._pStaticBox.Lower()
                self._pButton.Raise()
                self._sz.SetDimension(0, 0, oursz.width, oursz.height)
                self._sz.Layout()
            else:
                if hasattr(self, '_pStaticBox'):
                    self._pStaticBox.Hide()

        else:
            # move & resize the button and the static line
            self._sz.SetDimension(0, 0, oursz.GetWidth(), self._sz.GetMinSize().GetHeight())
            self._sz.Layout()

            if self.IsExpanded():

                # move & resize the container window
                yoffset = self._sz.GetSize().GetHeight() + self.GetBorder()
                self._pPane.SetDimensions(0, yoffset, oursz.x, oursz.y - yoffset)

                # this is very important to make the pane window layout show correctly
                self._pPane.Show()
                self._pPane.Layout()

        return True

[docs]    def SetButton(self, button):
        """
        Assign a new button to L{PyCollapsiblePane}.

        :param `button`: can be the standard `wx.Button` or any of the generic
         implementations which live in `wx.lib.buttons`.
        """

        if self._pButton:
            if not self.HasAGWFlag(CP_USE_STATICBOX):
                self._sz.Replace(self._pButton, button)
            self.Unbind(wx.EVT_BUTTON, self._pButton)
            self._pButton.Destroy()

        self._pButton = button
        self.SetLabel(button.GetLabel())
        self.Bind(wx.EVT_BUTTON, self.OnButton, self._pButton)

        if self._pPane:
            self._pButton.MoveBeforeInTabOrder(self._pPane)
        self.Layout()

[docs]    def GetButton(self):
        """ Returns the button associated with L{PyCollapsiblePane}. """

        return self._pButton

#-----------------------------------------------------------------------------
# PyCollapsiblePane - event handlers
#-----------------------------------------------------------------------------

[docs]    def OnButton(self, event):
        """
        Handles the ``wx.EVT_BUTTON`` event for L{PyCollapsiblePane}.

        :param `event`: a `wx.CommandEvent` event to be processed.
        """

        if event.GetEventObject() != self._pButton:
            event.Skip()
            return

        self.Collapse(not self.IsCollapsed())

        # this change was generated by the user - send the event
        ev = wx.CollapsiblePaneEvent(self, self.GetId(), self.IsCollapsed())
        self.GetEventHandler().ProcessEvent(ev)

[docs]    def OnSize(self, event):
        """
        Handles the ``wx.EVT_SIZE`` event for L{PyCollapsiblePane}.

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

        self.Layout()

[docs]    def OnDrawGTKStyle(self, event):
        """
        Handles the ``wx.EVT_PAINT`` event for L{PyCollapsiblePane}.

        :param `event`: a `wx.PaintEvent` event to be processed.

        :note: This is a drawing routine to paint the GTK-style expander.
        """

        dc = wx.AutoBufferedPaintDC(self._pButton)
        dc.SetBackground(wx.Brush(self.GetBackgroundColour()))
        dc.Clear()

        self.OnDrawGTKExpander(dc)
        self.OnDrawGTKText(dc)

[docs]    def OnDrawGTKExpander(self, dc):
        """
        Overridable method to draw the GTK-style expander.

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

        self._pButton.OnDrawGTKExpander(dc)

[docs]    def OnDrawGTKText(self, dc):
        """
        Overridable method to draw the L{PyCollapsiblePane} text in the expander.

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

        self._pButton.OnDrawGTKText(dc)

Navigation

  • index
  • modules |
  • Home |
  • Gallery |
  • Contents»
  • Module code »
  • pycollapsiblepane


pygauge

  • modules |
  • Home |
  • Gallery |
  • Contents»
  • Module code »
  • pygauge

Source code for pygauge

# --------------------------------------------------------------------------------- #
# PYGAUGE wxPython IMPLEMENTATION
#
# Mark Reed, @ 28 Jul 2010
# Latest Revision: 17 Aug 2011, 15.00 GMT
#
# TODO List
#
# 1. Indeterminate mode (see wx.Gauge)
# 2. Vertical bar
# 3. Bitmap support (bar, background)
# 4. UpdateFunction - Pass a function to PyGauge which will be called every X
#    milliseconds and the value will be updated to the returned value.
# 5. Currently the full gradient is drawn from 0 to value. Perhaps the gradient
#    should be drawn from 0 to range and clipped at 0 to value.
# 6. Add a label?
#
# For All Kind Of Problems, Requests Of Enhancements And Bug Reports, Please
# Write To The:
#
# wxPython Mailing List!!!
#
# End Of Comments
# --------------------------------------------------------------------------------- #

"""
L{PyGauge} is a generic `wx.Gauge` implementation.

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

L{PyGauge} supports the determinate mode functions as `wx.Gauge` and adds an L{Update} function
which takes a value and a time parameter. The `value` is added to the current value over
a period of `time` milliseconds.

Usage
=====

Usage example::

    import wx
    import wx.lib.agw.pygauge as PG

    class MyFrame(wx.Frame):

        def __init__(self, parent):

            wx.Frame.__init__(self, parent, -1, "PyGauge Demo")

            panel = wx.Panel(self)

            gauge1 = PG.PyGauge(panel, -1, size=(100, 25), style=wx.GA_HORIZONTAL)
            gauge1.SetValue(80)
            gauge1.SetBackgroundColour(wx.WHITE)
            gauge1.SetBorderColor(wx.BLACK)

            gauge2 = PG.PyGauge(panel, -1, size=(100, 25), style=wx.GA_HORIZONTAL)
            gauge2.SetValue([20, 80])
            gauge2.SetBarColor([wx.Colour(162, 255, 178), wx.Colour(159, 176, 255)])
            gauge2.SetBackgroundColour(wx.WHITE)
            gauge2.SetBorderColor(wx.BLACK)
            gauge2.SetBorderPadding(2)
            gauge2.Update([30, 0], 2000)

            gauge3 = PG.PyGauge(panel, -1, size=(100, 25), style=wx.GA_HORIZONTAL)
            gauge3.SetValue(50)
            gauge3.SetBarColor(wx.GREEN)
            gauge3.SetBackgroundColour(wx.WHITE)
            gauge3.SetBorderColor(wx.BLACK)

            sizer = wx.BoxSizer(wx.VERTICAL)
            sizer.Add(gauge1, 0, wx.ALIGN_CENTER_VERTICAL|wx.ALL, 20)
            sizer.Add(gauge2, 0, wx.ALIGN_CENTER_VERTICAL|wx.ALL, 20)
            sizer.Add(gauge3, 0, wx.ALIGN_CENTER_VERTICAL|wx.ALL, 20)

            panel.SetSizer(sizer)
            sizer.Layout()

    # our normal wxApp-derived class, as usual

    app = wx.PySimpleApp()

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

    app.MainLoop()

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

L{PyGauge} has been tested on the following platforms:
  * Windows (Windows XP);

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

L{PyGauge} is distributed under the wxPython license.

L{PyGauge} has been kindly contributed to the AGW library by Mark Reed.

Latest Revision: Andrea Gavana @ 17 Aug 2011, 15.00 GMT

Version 0.1

"""

import wx
import copy

[docs]class PyGauge(wx.PyWindow):
    """
    This class provides a visual alternative for `wx.Gauge`. It currently
    only support determinate mode (see L{PyGauge.SetValue} and L{PyGauge.SetRange})
    """

[docs]    def __init__(self, parent, id=wx.ID_ANY, range=100, pos=wx.DefaultPosition,
                 size=(-1,30), style=0):
        """
        Default class constructor.

        :param `parent`: parent window. Must not be ``None``;
        :param `id`: window identifier. A value of -1 indicates a default value;
        :param `pos`: the control position. A value of (-1, -1) indicates a default position,
         chosen by either the windowing system or wxPython, depending on platform;
        :param `size`: the control size. A value of (-1, -1) indicates a default size,
         chosen by either the windowing system or wxPython, depending on platform;
        :param `style`: the underlying `wx.PyWindow` window style.
        """

        wx.PyWindow.__init__(self, parent, id, pos, size, style)

        self._size = size

        self._border_colour = None
        self._barColour    = self._barColourSorted   = [wx.Colour(212,228,255)]
        self._barGradient  = self._barGradientSorted = None

        self._border_padding = 0
        self._range = range
        self._value = [0]
        self._valueSorted = [0]

        self._timerId = wx.NewId()
        self._timer = None

        self.Bind(wx.EVT_PAINT, self.OnPaint)
        self.Bind(wx.EVT_ERASE_BACKGROUND, self.OnEraseBackground)
        self.Bind(wx.EVT_TIMER, self.OnTimer)

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

        :note: Overridden from `wx.PyWindow`.
        """

        return wx.Size(self._size[0], self._size[1])

[docs]    def GetBorderColour(self):
        """ Returns the L{PyGauge} border colour. """

        return self._border_colour

[docs]    def SetBorderColour(self, colour):
        """
        Sets the L{PyGauge} border colour.

        :param `colour`: an instance of `wx.Colour`.
        """

        self._border_colour = colour

    SetBorderColor = SetBorderColour
    GetBorderColor = GetBorderColour

[docs]    def GetBarColour(self):
        """ Returns the L{PyGauge} main bar colour. """

        return self._barColour[0]

[docs]    def SetBarColour(self, colour):
        """
        Sets the L{PyGauge} main bar colour.

        :param `colour`: an instance of `wx.Colour`.
        """

        if type(colour) != type([]):
            self._barColour = [colour]
        else:
            self._barColour = list(colour)

        self.SortForDisplay()

    SetBarColor = SetBarColour
    GetBarColor = GetBarColour

[docs]    def GetBarGradient(self):
        """ Returns a tuple containing the gradient start and end colours. """

        if self._barGradient == None:
            return None

        return self._barGradient[0]

[docs]    def SetBarGradient(self, gradient):
        """
        Sets the bar gradient.

        :param `gradient`: a tuple containing the gradient start and end colours.

        :note: This overrides the bar colour previously set with L{SetBarColour}.
        """

        if type(gradient) != type([]):
            self._barGradient = [gradient]
        else:
            self._barGradient = list(gradient)

        self.SortForDisplay()

[docs]    def GetBorderPadding(self):
        """ Gets the border padding. """

        return self._border_padding

[docs]    def SetBorderPadding(self, padding):
        """
        Sets the border padding.

        :param `padding`: pixels between the border and the progress bar.
        """

        self._border_padding = padding

[docs]    def GetRange(self):
        """ Returns the maximum value of the gauge. """

        return self._range

[docs]    def SetRange(self, range):
        """
        Sets the range of the gauge. The gauge length is its
        value as a proportion of the range.

        :param `range`: The maximum value of the gauge.
        """

        if range <= 0:
            raise Exception("ERROR:\n Gauge range must be greater than 0.")

        self._range = range

[docs]    def GetValue(self):
        """ Returns the current position of the gauge. """

        return self._value[0]

[docs]    def SetValue(self, value):
        """
        Sets the current position of the gauge.

        :param `value`: an integer specifying the current position of the gauge.
        """

        if type(value) != type([]):
            self._value = [value]
        else:
            self._value = list(value)

        self.SortForDisplay()

        for v in self._value:
            if v < 0 or v > self._range:
                raise Exception("ERROR:\n Gauge value must be between 0 and its range.")

[docs]    def OnEraseBackground(self, event):
        """
        Handles the ``wx.EVT_ERASE_BACKGROUND`` event for L{PyGauge}.

        :param `event`: a `wx.EraseEvent` event to be processed.

        :note: This method is intentionally empty to reduce flicker.
        """

        pass

[docs]    def OnPaint(self, event):
        """
        Handles the ``wx.EVT_PAINT`` event for L{PyGauge}.

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

        dc = wx.BufferedPaintDC(self)
        rect = self.GetClientRect()

        dc.SetBackground(wx.Brush(self.GetBackgroundColour()))
        dc.Clear()
        colour = self.GetBackgroundColour()
        dc.SetBrush(wx.Brush(colour))
        dc.SetPen(wx.Pen(colour))
        dc.DrawRectangleRect(rect)

        if self._border_colour:
            dc.SetPen(wx.Pen(self.GetBorderColour()))
            dc.DrawRectangleRect(rect)
            pad = 1 + self.GetBorderPadding()
            rect.Deflate(pad,pad)

        if self.GetBarGradient():
            for i, gradient in enumerate(self._barGradientSorted):
                c1,c2 = gradient
                w = rect.width * (float(self._valueSorted[i]) / self._range)
                r = copy.copy(rect)
                r.width = w
                dc.GradientFillLinear(r, c1, c2, wx.EAST)
        else:
            for i, colour in enumerate(self._barColourSorted):
                dc.SetBrush(wx.Brush(colour))
                dc.SetPen(wx.Pen(colour))
                w = rect.width * (float(self._valueSorted[i]) / self._range)
                r = copy.copy(rect)
                r.width = w
                dc.DrawRectangleRect(r)

[docs]    def OnTimer(self,event):
        """
        Handles the ``wx.EVT_TIMER`` event for L{PyGauge}.

        :param `event`: a `wx.TimerEvent` event to be processed.
        """

        if self._timerId == event.GetId():
            stop_timer = True
            for i, v in enumerate(self._value):
                self._value[i] += self._update_step[i]

                if self._update_step[i] > 0:
                    if self._value[i] > self._update_value[i]:
                        self._value[i] = self._update_value[i]
                    else: stop_timer = False
                else:
                    if self._value[i] < self._update_value[i]:
                        self._value[i] = self._update_value[i]
                    else: stop_timer = False

            if stop_timer:
                self._timer.Stop()

            self.SortForDisplay()

            self.Refresh()

[docs]    def Update(self, value, time=0):
        """
        Update the gauge by adding `value` to it over `time` milliseconds. The `time` parameter
        **must** be a multiple of 50 milliseconds.

        :param `value`: The value to be added to the gauge;
        :param `time`: The length of time in milliseconds that it will take to move the gauge.
        """

        if type(value) != type([]):
            value = [value]

        if len(value) != len(self._value):
            raise Exception("ERROR:\n len(value) != len(self.GetValue())")

        self._update_value = []
        self._update_step  = []
        for i, v in enumerate(self._value):
            if value[i]+v <= 0 or value[i]+v > self._range:
                raise Exception("ERROR:\n Gauge value must be between 0 and its range. ")

            self._update_value.append(value[i] + v)
            self._update_step.append(float(value[i])/(time/50))

        #print self._update_

        if not self._timer:
            self._timer = wx.Timer(self, self._timerId)

        self._timer.Start(100)

[docs]    def SortForDisplay(self):
        """ Internal method which sorts things so we draw the longest bar first. """

        if self.GetBarGradient():
            tmp = sorted(zip(self._value,self._barGradient)); tmp.reverse()
            a,b = zip(*tmp)
            self._valueSorted       = list(a)
            self._barGradientSorted = list(b)
        else:
            tmp = sorted(zip(self._value,self._barColour)); tmp.reverse()
            a,b = zip(*tmp)
            self._valueSorted     = list(a)
            self._barColourSorted = list(b)

Navigation

  • index
  • modules |
  • Home |
  • Gallery |
  • Contents»
  • Module code »
  • pygauge


pyprogress

  • modules |
  • Home |
  • Gallery |
  • Contents»
  • Module code »
  • pyprogress

Source code for pyprogress

# --------------------------------------------------------------------------------- #
# PYPROGRESS wxPython IMPLEMENTATION
#
# Andrea Gavana, @ 03 Nov 2006
# Latest Revision: 17 Aug 2011, 15.00 GMT
#
#
# TODO List
#
# 1. Do we support all the styles of wx.ProgressDialog in indeterminated mode?
#
# 2. Other ideas?
#
#
# For All Kind Of Problems, Requests Of Enhancements And Bug Reports, Please
# Write To Me At:
#
# andrea.gavana@maerskoil.com
# andrea.gavana@gmail.com
#
# Or, Obviously, To The wxPython Mailing List!!!
#
#
# End Of Comments
# --------------------------------------------------------------------------------- #

"""
L{PyProgress} is similar to `wx.ProgressDialog` in indeterminated mode, but with a
different gauge appearance and a different spinning behavior.

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

L{PyProgress} is similar to `wx.ProgressDialog` in indeterminated mode, but with a
different gauge appearance and a different spinning behavior. The moving gauge
can be drawn with a single solid colour or with a shading gradient foreground.
The gauge background colour is user customizable.

The bar does not move always from the beginning to the end as in `wx.ProgressDialog`
in indeterminated mode, but spins cyclically forward and backward.

Other options include:

- Possibility to change the proportion between the spinning bar and the
  entire gauge, so that the bar can be longer or shorter (the default is 20%);
- Modifying the number of steps the spinning bar performs before a forward
  (or backward) loop reverses.

L{PyProgress} can optionally display a ``Cancel`` button, and a `wx.StaticText` which
outputs the elapsed time from the starting of the process.

Usage
=====

Usage example::

    import wx
    import wx.lib.agw.pyprogress as PP

    # Our normal wxApp-derived class, as usual
    app = wx.App(0)

    dlg = PP.PyProgress(None, -1, "PyProgress Example",
                        "An Informative Message",
                        agwStyle=wx.PD_APP_MODAL|wx.PD_ELAPSED_TIME)

    dlg.SetGaugeProportion(0.2)
    dlg.SetGaugeSteps(50)
    dlg.SetGaugeBackground(wx.WHITE)
    dlg.SetFirstGradientColour(wx.WHITE)
    dlg.SetSecondGradientColour(wx.BLUE)

    max = 400
    keepGoing = True
    count = 0

    while keepGoing and count < max:
        count += 1
        wx.MilliSleep(30)

        if count >= max / 2:
            keepGoing = dlg.UpdatePulse("Half-time!")
        else:
            keepGoing = dlg.UpdatePulse()

    dlg.Destroy()

    app.MainLoop()

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

L{PyProgress} has been tested on the following platforms:
  * Windows (Windows XP);
  * Linux Ubuntu (Dapper 6.06)

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

This class supports the following window styles:

=================== =========== ==================================================
Window Styles       Hex Value   Description
=================== =========== ==================================================
``PD_CAN_ABORT``            0x1 This flag tells the dialog that it should have a ``Cancel`` button which the user may press. If this happens, the next call to `Update` will return ``False``.
``PD_APP_MODAL``            0x2 Make the progress dialog modal. If this flag is not given, it is only 'locally' modal - that is the input to the parent window is disabled, but not to the other ones.
``PD_AUTO_HIDE``            0x4 Causes the progress dialog to disappear from screen as soon as the maximum value of the progress meter has been reached.
``PD_ELAPSED_TIME``         0x8 This flag tells the dialog that it should show elapsed time (since creating the dialog).
=================== =========== ==================================================

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

`No custom events are available for this class.`

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

L{PyProgress} is distributed under the wxPython license.

Latest Revision: Andrea Gavana @ 17 Aug 2011, 15.00 GMT

Version 0.4

"""

__docformat__ = "epytext"

import wx

# Some constants, taken straight from wx.ProgressDialog
Uncancelable = -1
Canceled = 0
Continue = 1
Finished = 2

# Margins between gauge and text/button
LAYOUT_MARGIN = 8

# PyProgress styles
PD_CAN_ABORT = wx.PD_CAN_ABORT
""" This flag tells the dialog that it should have a "Cancel" button which the user""" \
""" may press. If this happens, the next call to `Update()` will return ``False``. """
PD_APP_MODAL = wx.PD_APP_MODAL
""" Make the progress dialog modal. If this flag is not given, it is only 'locally'"""\
""" modal - that is the input to the parent window is disabled, but not to the other ones. """
PD_AUTO_HIDE = wx.PD_AUTO_HIDE
""" Causes the progress dialog to disappear from screen as soon as the maximum""" \
""" value of the progress meter has been reached. """
PD_ELAPSED_TIME = wx.PD_ELAPSED_TIME
""" This flag tells the dialog that it should show elapsed time (since creating the dialog). """

# ---------------------------------------------------------------------------- #
# Class ProgressGauge
# ---------------------------------------------------------------------------- #

[docs]class ProgressGauge(wx.PyWindow):
    """ This class provides a visual alternative for `wx.Gauge`."""

[docs]    def __init__(self, parent, id=wx.ID_ANY, pos=wx.DefaultPosition,
                 size=(-1,30)):
        """
        Default class constructor.

        :param `parent`: parent window. Must not be ``None``;
        :param `id`: window identifier. A value of -1 indicates a default value;
        :param `pos`: the control position. A value of (-1, -1) indicates a default position,
         chosen by either the windowing system or wxPython, depending on platform;
        :param `size`: the control size. A value of (-1, -1) indicates a default size,
         chosen by either the windowing system or wxPython, depending on platform.
        """

        wx.PyWindow.__init__(self, parent, id, pos, size, style=wx.SUNKEN_BORDER)

        self._value = 0
        self._steps = 50
        self._pos = 0
        self._current = 0
        self._gaugeproportion = 0.2
        self._firstGradient = wx.WHITE
        self._secondGradient = wx.BLUE
        self._background = wx.Brush(wx.WHITE, wx.SOLID)

        self.Bind(wx.EVT_PAINT, self.OnPaint)
        self.Bind(wx.EVT_ERASE_BACKGROUND, self.OnEraseBackground)

[docs]    def GetFirstGradientColour(self):
        """ Returns the first gradient colour. """

        return self._firstGradient

[docs]    def SetFirstGradientColour(self, colour):
        """
        Sets the first gradient colour.

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

        if not isinstance(colour, wx.Colour):
            colour = wx.NamedColour(colour)

        self._firstGradient = colour
        self.Refresh()

[docs]    def GetSecondGradientColour(self):
        """ Returns the second gradient colour. """

        return self._secondGradient

[docs]    def SetSecondGradientColour(self, colour):
        """
        Sets the second gradient colour.

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

        if not isinstance(colour, wx.Colour):
            colour = wx.NamedColour(colour)

        self._secondGradient = colour
        self.Refresh()

[docs]    def GetGaugeBackground(self):
        """ Returns the gauge background colour. """

        return self._background

[docs]    def SetGaugeBackground(self, colour):
        """
        Sets the gauge background colour.

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

        if not isinstance(colour, wx.Colour):
            colour = wx.NamedColour(colour)

        self._background = wx.Brush(colour, wx.SOLID)

[docs]    def SetGaugeSteps(self, steps):
        """
        Sets the number of steps the gauge performs before switching from
        forward to backward (or vice-versa) movement.

        :param `steps`: the number of steps the gauge performs before switching from
         forward to backward (or vice-versa) movement.
        """

        if steps <= 0:
            raise Exception("ERROR:\n Gauge steps must be greater than zero. ")

        if steps != self._steps:
            self._steps = steps

[docs]    def GetGaugeSteps(self):
        """
        Returns the number of steps the gauge performs before switching from
        forward to backward (or vice-versa) movement.
        """

        return self._steps

[docs]    def GetGaugeProportion(self):
        """
        Returns the relative proportion between the sliding bar and the
        whole gauge.
        """

        return self._gaugeproportion

[docs]    def SetGaugeProportion(self, proportion):
        """
        Sets the relative proportion between the sliding bar and the
        whole gauge.

        :param `proportion`: a floating point number representing the relative
         proportion between the sliding bar and the whole gauge.
        """

        if proportion <= 0 or proportion >= 1:
            raise Exception("ERROR:\n Gauge proportion must be between 0 and 1. ")

        if proportion != self._gaugeproportion:
            self._gaugeproportion = proportion

[docs]    def OnEraseBackground(self, event):
        """
        Handles the ``wx.EVT_ERASE_BACKGROUND`` event for L{ProgressGauge}.

        :param `event`: a `wx.EraseEvent` event to be processed.

        :note: This method is intentionally empty to reduce flicker.
        """

        pass

[docs]    def OnPaint(self, event):
        """
        Handles the ``wx.EVT_PAINT`` event for L{ProgressGauge}.

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

        dc = wx.BufferedPaintDC(self)
        dc.SetBackground(self._background)

        dc.Clear()

        xsize, ysize = self.GetClientSize()
        interval = xsize/float(self._steps)

        self._pos = interval*self._value

        status = self._current/(self._steps - int(self._gaugeproportion*xsize)/int(interval))

        if status%2 == 0:
            increment = 1
        else:
            increment = -1

        self._value = self._value + increment
        self._current = self._current + 1
        self.DrawProgress(dc, xsize, ysize, increment)

[docs]    def DrawProgress(self, dc, xsize, ysize, increment):
        """
        Actually draws the sliding bar.

        :param `dc`: an instance of `wx.DC`;
        :param `xsize`: the width of the whole progress bar;
        :param `ysize`: the height of the whole progress bar;
        :param `increment`: a positive value if we are spinning from left to right,
         a negative one if we are spinning from right to left.
        """

        if increment > 0:
            col1 = self.GetFirstGradientColour()
            col2 = self.GetSecondGradientColour()
        else:
            col1 = self.GetSecondGradientColour()
            col2 = self.GetFirstGradientColour()

        interval = self._gaugeproportion*xsize

        r1, g1, b1 = int(col1.Red()), int(col1.Green()), int(col1.Blue())
        r2, g2, b2 = int(col2.Red()), int(col2.Green()), int(col2.Blue())

        rstep = float((r2 - r1)) / interval
        gstep = float((g2 - g1)) / interval
        bstep = float((b2 - b1)) / interval

        rf, gf, bf = 0, 0, 0
        dc.SetBrush(wx.TRANSPARENT_BRUSH)

        for ii in xrange(int(self._pos), int(self._pos+interval)):
            currCol = (r1 + rf, g1 + gf, b1 + bf)
            dc.SetPen(wx.Pen(currCol, 2))
            dc.DrawLine(ii, 1, ii, ysize-2)
            rf = rf + rstep
            gf = gf + gstep
            bf = bf + bstep

[docs]    def Update(self):
        """ Updates the gauge with a new value. """

        self.Refresh()

# ---------------------------------------------------------------------------- #
# Class PyProgress
# ---------------------------------------------------------------------------- #

[docs]class PyProgress(wx.Dialog):
    """
    L{PyProgress} is similar to `wx.ProgressDialog` in indeterminated mode, but with a
    different gauge appearance and a different spinning behavior. The moving gauge
    can be drawn with a single solid colour or with a shading gradient foreground.
    The gauge background colour is user customizable.
    The bar does not move always from the beginning to the end as in `wx.ProgressDialog`
    in indeterminated mode, but spins cyclically forward and backward.
    """

[docs]    def __init__(self, parent=None, id=-1, title="", message="",
                 agwStyle=wx.PD_APP_MODAL|wx.PD_AUTO_HIDE):
        """
        Default class constructor.

        :param `parent`: parent window;
        :param `id`: window identifier. A value of -1 indicates a default value;
        :param `title`: dialog title to show in titlebar;
        :param `message`: message displayed above the progress bar;
        :param `style`: the dialog style. This can be a combination of the following bits:

         =================== =========== ==================================================
         Window Styles       Hex Value   Description
         =================== =========== ==================================================
         ``PD_CAN_ABORT``            0x1 This flag tells the dialog that it should have a ``Cancel`` button which the user may press. If this happens, the next call to `UpdatePulse` will return ``False``.
         ``PD_APP_MODAL``            0x2 Make the progress dialog modal. If this flag is not given, it is only 'locally' modal - that is the input to the parent window is disabled, but not to the other ones.
         ``PD_AUTO_HIDE``            0x4 Causes the progress dialog to disappear from screen as soon as the maximum value of the progress meter has been reached.
         ``PD_ELAPSED_TIME``         0x8 This flag tells the dialog that it should show elapsed time (since creating the dialog).
         =================== =========== ==================================================

        """

        wx.Dialog.__init__(self, parent, id, title)

        self._delay = 3
        self._hasAbortButton = False

        # we may disappear at any moment, let the others know about it
        self.SetExtraStyle(self.GetExtraStyle()|wx.WS_EX_TRANSIENT)

        self._hasAbortButton = (agwStyle & wx.PD_CAN_ABORT)

        if wx.Platform == "__WXMSW__":
            # we have to remove the "Close" button from the title bar then as it is
            # confusing to have it - it doesn't work anyhow
            # FIXME: should probably have a (extended?) window style for this
            if not self._hasAbortButton:
                self.EnableClose(False)

        self._state = (self._hasAbortButton and [Continue] or [Uncancelable])[0]
        self._parentTop = wx.GetTopLevelParent(parent)

        dc = wx.ClientDC(self)
        dc.SetFont(wx.SystemSettings_GetFont(wx.SYS_DEFAULT_GUI_FONT))
        widthText, dummy = dc.GetTextExtent(message)

        sizer = wx.BoxSizer(wx.VERTICAL)

        self._msg = wx.StaticText(self, wx.ID_ANY, message)
        sizer.Add(self._msg, 0, wx.LEFT|wx.TOP, 2*LAYOUT_MARGIN)

        sizeDlg = wx.Size()
        sizeLabel = self._msg.GetSize()
        sizeDlg.y = 2*LAYOUT_MARGIN + sizeLabel.y

        self._gauge = ProgressGauge(self, -1)

        sizer.Add(self._gauge, 0, wx.LEFT|wx.RIGHT|wx.TOP|wx.EXPAND, 2*LAYOUT_MARGIN)

        sizeGauge = self._gauge.GetSize()
        sizeDlg.y += 2*LAYOUT_MARGIN + sizeGauge.y

        # create the estimated/remaining/total time zones if requested
        self._elapsed = None
        self._display_estimated = self._last_timeupdate = self._break = 0
        self._ctdelay = 0

        label = None

        nTimeLabels = 0

        if agwStyle & wx.PD_ELAPSED_TIME:

            nTimeLabels += 1
            self._elapsed = self.CreateLabel("Elapsed time : ", sizer)

        if nTimeLabels > 0:

            label = wx.StaticText(self, -1, "")
            # set it to the current time
            self._timeStart = wx.GetCurrentTime()
            sizeDlg.y += nTimeLabels*(label.GetSize().y + LAYOUT_MARGIN)
            label.Destroy()

        sizeDlgModified = False

        if wx.Platform == "__WXMSW__":
            sizerFlags = wx.ALIGN_RIGHT|wx.ALL
        else:
            sizerFlags = wx.ALIGN_CENTER_HORIZONTAL|wx.BOTTOM|wx.TOP

        if self._hasAbortButton:
            buttonSizer = wx.BoxSizer(wx.HORIZONTAL)

            self._btnAbort = wx.Button(self, -1, "Cancel")
            self._btnAbort.Bind(wx.EVT_BUTTON, self.OnCancel)

            # Windows dialogs usually have buttons in the lower right corner
            buttonSizer.Add(self._btnAbort, 0, sizerFlags, LAYOUT_MARGIN)

            if not sizeDlgModified:
                sizeDlg.y += 2*LAYOUT_MARGIN + wx.Button.GetDefaultSize().y

        if self._hasAbortButton:
            sizer.Add(buttonSizer, 0, sizerFlags, LAYOUT_MARGIN )

        self.Bind(wx.EVT_CLOSE, self.OnClose)
        self.Bind(wx.EVT_WINDOW_DESTROY, self.OnDestroy)

        self._agwStyle = agwStyle

        self.SetSizerAndFit(sizer)

        sizeDlg.y += 2*LAYOUT_MARGIN

        # try to make the dialog not square but rectangular of reasonable width
        sizeDlg.x = max(widthText, 4*sizeDlg.y/3)
        sizeDlg.x *= 3
        sizeDlg.x /= 2
        self.SetClientSize(sizeDlg)

        self.Centre(wx.CENTER_FRAME|wx.BOTH)

        if agwStyle & wx.PD_APP_MODAL:
            self._winDisabler = wx.WindowDisabler(self)
        else:
            if self._parentTop:
                self._parentTop.Disable()
            self._winDisabler = None

        self.ShowDialog()
        self.Enable()

        # this one can be initialized even if the others are unknown for now
        # NB: do it after calling Layout() to keep the labels correctly aligned
        if self._elapsed:
            self.SetTimeLabel(0, self._elapsed)

        if not wx.EventLoop().GetActive():
            self.evtloop = wx.EventLoop()
            wx.EventLoop.SetActive(self.evtloop)

        self.Update()

[docs]    def CreateLabel(self, text, sizer):
        """
        Creates the `wx.StaticText` that holds the elapsed time label.

        :param `text`: the dialog message to be displayed above the gauge;
        :param `sizer`: the main `wx.BoxSizer` for L{PyProgress}.
        """

        locsizer = wx.BoxSizer(wx.HORIZONTAL)
        dummy = wx.StaticText(self, wx.ID_ANY, text)
        label = wx.StaticText(self, wx.ID_ANY, "unknown")

        if wx.Platform in ["__WXMSW__", "__WXMAC__"]:
            # label and time centered in one row
            locsizer.Add(dummy, 1, wx.ALIGN_LEFT)
            locsizer.Add(label, 1, wx.ALIGN_LEFT|wx.LEFT, LAYOUT_MARGIN)
            sizer.Add(locsizer, 0, wx.ALIGN_CENTER_HORIZONTAL|wx.TOP, LAYOUT_MARGIN)
        else:
            # label and time to the right in one row
            sizer.Add(locsizer, 0, wx.ALIGN_RIGHT|wx.RIGHT|wx.TOP, LAYOUT_MARGIN)
            locsizer.Add(dummy)
            locsizer.Add(label, 0, wx.LEFT, LAYOUT_MARGIN)

        return label

    # ----------------------------------------------------------------------------
    # wxProgressDialog operations
    # ----------------------------------------------------------------------------

[docs]    def UpdatePulse(self, newmsg=""):
        """
        Updates the dialog, setting the progress bar to the new value and, if given
        changes the message above it. Returns ``True`` unless the ``Cancel`` button
        has been pressed.

        If ``False`` is returned, the application can either immediately destroy the
        dialog or ask the user for the confirmation.

        :param `newmsg`: The new messages for the progress dialog text, if it is
         empty (which is the default) the message is not changed.
        """

        self._gauge.Update()

        if newmsg and newmsg != self._msg.GetLabel():
            self._msg.SetLabel(newmsg)
            wx.YieldIfNeeded()

        if self._elapsed:
            elapsed = wx.GetCurrentTime() - self._timeStart
            if self._last_timeupdate < elapsed:
                self._last_timeupdate = elapsed

            self.SetTimeLabel(elapsed, self._elapsed)

        if self._state == Finished:

            if not self._agwStyle & wx.PD_AUTO_HIDE:

                self.EnableClose()

                if newmsg == "":
                    # also provide the finishing message if the application didn't
                    self._msg.SetLabel("Done.")

                wx.YieldIfNeeded()
                self.ShowModal()
                return False

            else:
                # reenable other windows before hiding this one because otherwise
                # Windows wouldn't give the focus back to the window which had
                # been previously focused because it would still be disabled
                self.ReenableOtherWindows()
                self.Hide()

        # we have to yield because not only we want to update the display but
        # also to process the clicks on the cancel and skip buttons
        wx.YieldIfNeeded()

        return self._state != Canceled

[docs]    def GetFirstGradientColour(self):
        """ Returns the gauge first gradient colour. """

        return self._gauge.GetFirstGradientColour()

[docs]    def SetFirstGradientColour(self, colour):
        """
        Sets the gauge first gradient colour.

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

        self._gauge.SetFirstGradientColour(colour)

[docs]    def GetSecondGradientColour(self):
        """ Returns the gauge second gradient colour. """

        return self._gauge.GetSecondGradientColour()

[docs]    def SetSecondGradientColour(self, colour):
        """
        Sets the gauge second gradient colour.

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

        self._gauge.SetSecondGradientColour(colour)

[docs]    def GetGaugeBackground(self):
        """ Returns the gauge background colour. """

        return self._gauge.GetGaugeBackground()

[docs]    def SetGaugeBackground(self, colour):
        """
        Sets the gauge background colour.

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

        self._gauge.SetGaugeBackground(colour)

[docs]    def SetGaugeSteps(self, steps):
        """
        Sets the number of steps the gauge performs before switching from
        forward to backward (or vice-versa) movement.

        :param `steps`: the number of steps the gauge performs before switching from
         forward to backward (or vice-versa) movement.
        """

        self._gauge.SetGaugeSteps(steps)

[docs]    def GetGaugeSteps(self):
        """
        Returns the number of steps the gauge performs before switching from
        forward to backward (or vice-versa) movement.
        """

        return self._gauge.GetGaugeSteps()

[docs]    def GetGaugeProportion(self):
        """
        Returns the relative proportion between the sliding bar and the
        whole gauge.
        """

        return self._gauge.GetGaugeProportion()

[docs]    def SetGaugeProportion(self, proportion):
        """
        Sets the relative proportion between the sliding bar and the
        whole gauge.

        :param `proportion`: a floating point number representing the relative
         proportion between the sliding bar and the whole gauge.
        """

        self._gauge.SetGaugeProportion(proportion)

[docs]    def ShowDialog(self, show=True):
        """
        Show the dialog.

        :param `show`: ``True`` to show the dialog and re-enable all the other windows,
         ``False`` otherwise.
        """

        # reenable other windows before hiding this one because otherwise
        # Windows wouldn't give the focus back to the window which had
        # been previously focused because it would still be disabled
        if not show:
            self.ReenableOtherWindows()

        return self.Show()

    # ----------------------------------------------------------------------------
    # event handlers
    # ----------------------------------------------------------------------------

[docs]    def OnCancel(self, event):
        """
        Handles the ``wx.EVT_BUTTON`` event for the dialog.

        :param `event`: a `wx.CommandEvent` event to be processed.

        :note: This method handles the ``Cancel`` button press.
        """

        if self._state == Finished:

            # this means that the count down is already finished and we're being
            # shown as a modal dialog - so just let the default handler do the job
            event.Skip()

        else:

            # request to cancel was received, the next time Update() is called we
            # will handle it
            self._state = Canceled

            # update the buttons state immediately so that the user knows that the
            # request has been noticed
            self.DisableAbort()

            # save the time when the dialog was stopped
            self._timeStop = wx.GetCurrentTime()

        self.ReenableOtherWindows()

[docs]    def OnDestroy(self, event):
        """
        Handles the ``wx.EVT_WINDOW_DESTROY`` event for L{PyProgress}.

        :param `event`: a `wx.WindowDestroyEvent` event to be processed.
        """

        self.ReenableOtherWindows()
        event.Skip()

[docs]    def OnClose(self, event):
        """
        Handles the ``wx.EVT_CLOSE`` event for L{PyProgress}.

        :param `event`: a `wx.CloseEvent` event to be processed.
        """

        if self._state == Uncancelable:

            # can't close this dialog
            event.Veto()

        elif self._state == Finished:

            # let the default handler close the window as we already terminated
            self.Hide()
            event.Skip()

        else:

            # next Update() will notice it
            self._state = Canceled
            self.DisableAbort()

            self._timeStop = wx.GetCurrentTime()

[docs]    def ReenableOtherWindows(self):
        """ Re-enables the other windows if using `wx.WindowDisabler`. """

        if self._agwStyle & wx.PD_APP_MODAL:
            if hasattr(self, "_winDisabler"):
                del self._winDisabler

        else:

            if self._parentTop:
                self._parentTop.Enable()

[docs]    def SetTimeLabel(self, val, label=None):
        """
        Sets the elapsed time label.

        :param `val`: the elapsed time since the dialog was shown, in seconds;
        :param `label`: the new message to display in the elapsed time text.
        """

        if label:

            hours = val/3600
            minutes = (val%3600)/60
            seconds = val%60
            strs = ("%lu:%02lu:%02lu")%(hours, minutes, seconds)

            if strs != label.GetLabel():
                label.SetLabel(strs)

[docs]    def EnableAbort(self, enable=True):
        """
        Enables or disables the ``Cancel`` button.

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

        if self._hasAbortButton:
            if self._btnAbort:
                self._btnAbort.Enable(enable)

[docs]    def EnableClose(self, enable=True):
        """
        Enables or disables the ``Close`` button.

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

        if self._hasAbortButton:
            if self._btnAbort:
                self._btnAbort.Enable(enable)
                self._btnAbort.SetLabel("Close")
                self._btnAbort.Bind(wx.EVT_BUTTON, self.OnClose)

[docs]    def DisableAbort(self):
        """ Disables the ``Cancel`` button. """

        self.EnableAbort(False)

Navigation

  • index
  • modules |
  • Home |
  • Gallery |
  • Contents»
  • Module code »
  • pyprogress


rulerctrl

  • modules |
  • Home |
  • Gallery |
  • Contents»
  • Module code »
  • rulerctrl

Source code for rulerctrl

# --------------------------------------------------------------------------------- #
# RULERCTRL wxPython IMPLEMENTATION
#
# Andrea Gavana, @ 03 Nov 2006
# Latest Revision: 17 Aug 2011, 15.00 GMT
#
#
# TODO List
#
# 1. Any idea?
#
# For All Kind Of Problems, Requests Of Enhancements And Bug Reports, Please
# Write To Me At:
#
# andrea.gavana@maerskoil.com
# andrea.gavana@gmail.com
#
# Or, Obviously, To The wxPython Mailing List!!!
#
#
# End Of Comments
# --------------------------------------------------------------------------------- #

"""
L{RulerCtrl} implements a ruler window that can be placed on top, bottom, left or right
to any wxPython widget.

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

L{RulerCtrl} implements a ruler window that can be placed on top, bottom, left or right
to any wxPython widget. It is somewhat similar to the rulers you can find in text
editors software, though not so powerful.

L{RulerCtrl} has the following characteristics:

- Can be horizontal or vertical;
- 4 built-in formats: integer, real, time and linearDB formats;
- Units (as ``cm``, ``dB``, ``inches``) can be displayed together with the label values;
- Possibility to add a number of "paragraph indicators", small arrows that point at
  the current indicator position;
- Customizable background colour, tick colour, label colour;
- Possibility to flip the ruler (i.e. changing the tick alignment);
- Changing individually the indicator colour (requires PIL at the moment);
- Different window borders are supported (``wx.STATIC_BORDER``, ``wx.SUNKEN_BORDER``,
  ``wx.DOUBLE_BORDER``, ``wx.NO_BORDER``, ``wx.RAISED_BORDER``, ``wx.SIMPLE_BORDER``);
- Logarithmic scale available;
- Possibility to draw a thin line over a selected window when moving an indicator,
  which emulates the text editors software.

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

Usage
=====

Usage example::

    import wx
    import wx.lib.agw.rulerctrl as RC

    class MyFrame(wx.Frame):

        def __init__(self, parent):

            wx.Frame.__init__(self, parent, -1, "RulerCtrl Demo")

            panel = wx.Panel(self)

            text = wx.TextCtrl(panel, -1, "Hello World! wxPython rules", style=wx.TE_MULTILINE)

            ruler1 = RC.RulerCtrl(panel, -1, orient=wx.HORIZONTAL, style=wx.SUNKEN_BORDER)
            ruler2 = RC.RulerCtrl(panel, -1, orient=wx.VERTICAL, style=wx.SUNKEN_BORDER)

            mainsizer = wx.BoxSizer(wx.HORIZONTAL)
            leftsizer = wx.BoxSizer(wx.VERTICAL)
            bottomleftsizer = wx.BoxSizer(wx.HORIZONTAL)
            topsizer = wx.BoxSizer(wx.HORIZONTAL)

            leftsizer.Add((20, 20), 0, wx.ADJUST_MINSIZE, 0)
            topsizer.Add((39, 0), 0, wx.ADJUST_MINSIZE, 0)
            topsizer.Add(ruler1, 1, wx.EXPAND, 0)
            leftsizer.Add(topsizer, 0, wx.EXPAND, 0)

            bottomleftsizer.Add((10, 0))
            bottomleftsizer.Add(ruler2, 0, wx.EXPAND, 0)
            bottomleftsizer.Add(text, 1, wx.EXPAND, 0)
            leftsizer.Add(bottomleftsizer, 1, wx.EXPAND, 0)
            mainsizer.Add(leftsizer, 3, wx.EXPAND, 0)

            panel.SetSizer(mainsizer)

    # our normal wxApp-derived class, as usual

    app = wx.PySimpleApp()

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

    app.MainLoop()

Events
======

L{RulerCtrl} implements the following events related to indicators:

- ``EVT_INDICATOR_CHANGING``: the user is about to change the position of one indicator;
- ``EVT_INDICATOR_CHANGED``: the user has changed the position of one indicator.

Supported Platforms
===================

L{RulerCtrl} has been tested on the following platforms:
  * Windows (Windows XP);
  * Linux Ubuntu (Dapper 6.06)

Window Styles
=============

`No particular window styles are available for this class.`

Events Processing
=================

This class processes the following events:

========================== ==================================================
Event Name                 Description
========================== ==================================================
``EVT_INDICATOR_CHANGED``  The user has changed the indicator value.
``EVT_INDICATOR_CHANGING`` The user is about to change the indicator value.
========================== ==================================================

License And Version
===================

L{RulerCtrl} is distributed under the wxPython license.

Latest Revision: Andrea Gavana @ 17 Aug 2011, 15.00 GMT

Version 0.3

"""

__docformat__ = "epytext"

import wx
import math
import cStringIO, zlib

# Try to import PIL, if possible.
# This is used only to change the colour for an indicator arrow.
_hasPIL = False
try:
    import Image
    _hasPIL = True
except:
    pass

# Built-in formats
IntFormat = 1
""" Integer format. """
RealFormat = 2
""" Real format. """
TimeFormat = 3
""" Time format. """
LinearDBFormat = 4
""" Linear DB format. """
HHMMSS_Format = 5
""" HHMMSS format. """

# Events
wxEVT_INDICATOR_CHANGING = wx.NewEventType()
wxEVT_INDICATOR_CHANGED = wx.NewEventType()

EVT_INDICATOR_CHANGING = wx.PyEventBinder(wxEVT_INDICATOR_CHANGING, 2)
""" The user is about to change the indicator value. """
EVT_INDICATOR_CHANGED = wx.PyEventBinder(wxEVT_INDICATOR_CHANGED, 2)
""" The user has changed the indicator value. """

# Some accessor functions
#----------------------------------------------------------------------

[docs]def GetIndicatorData():
    """ Returns the image indicator as a decompressed stream of characters. """

    return zlib.decompress(
'x\xda\x01x\x01\x87\xfe\x89PNG\r\n\x1a\n\x00\x00\x00\rIHDR\x00\x00\x00\n\x00\
\x00\x00\n\x08\x06\x00\x00\x00\x8d2\xcf\xbd\x00\x00\x00\x04sBIT\x08\x08\x08\
\x08|\x08d\x88\x00\x00\x01/IDAT\x18\x95m\xceO(\x83q\x1c\xc7\xf1\xf7\xef\xf9\
\xcd\xf6D6\xca\x1c\xc8\x9f\x14\'J-\xc4A9(9(-\xe5 \xed\xe4\xe2\xe2\xb2\x928\
\xb9\xec\xc2\x01\x17.\x0e\xe4\xe6B\xed\xb2\x1c\xdc$5\x97\xf9S\xb3\x14+\x0eO\
\xdb\xccZ\x9e\xfd\xf9\xba\x98E{\x1d\xbf\xbd\xfb\xf4U\x00\x18\x9d\xc3\xad\x1d\
\xa1+\xa7S\x15\xf8\xa1\xb5i\xbc\xc4\xd7\x0f\xca\xc5\xd82U3[\x97\xb1\x82\xc4S\
"\x89\xb4\xc8SZ\xc4\xb2E\xfa\x06CR)\x1c\x00\xb8\x8cb"-|\x94@\x01\x0e\r\xee&\
\xf8\x12\xc5\xdf\xd0\xd4\xf2\xf6i\x90/\x82\xe9\x82\xdb\xe72\xa7\xe7%\x92\x99\
\xdfA\xb4j\x9b]\xa5\xaek\xbag|\xaa\xdd\xca)\xceb\x10\xbe\x87\xacm VT\xd0N\
\x0f\xf9\xd7\x94\xd6\xde\xb1\xdd\xf9\xcdm_\x83\xdb\x81\x95W\x88\x02\xad\x159\
\x01\xcc!U2}\xa3$\x0f\x1dZR\xd1\xfd\xbb\x9b\xc7\x89\xc99\x7f\xb7\xb7\xd1\x00\
\xc0.B\xbe\xac\xc8\xbe?P\x8e\x8c\x1ccg\x02\xd5\x1f\x9a\x07\xf6\x82a[6.D\xfc\
\'"\x9e\xc0\xb5\xa0\xeb\xd7\xa8\xc9\xdd\xbf\xb3pdI\xefRD\xc0\x08\xd6\x8e*\\-\
+\xa0\x17\xff\x9f\xbf\x01{\xb5t\x9e\x99]a\x97\x00\x00\x00\x00IEND\xaeB`\x82G\
\xbf\xa8>' )

[docs]def GetIndicatorBitmap():
    """ Returns the image indicator as a `wx.Bitmap`. """

    return wx.BitmapFromImage(GetIndicatorImage())

[docs]def GetIndicatorImage():
    """ Returns the image indicator as a `wx.Image`. """

    stream = cStringIO.StringIO(GetIndicatorData())
    return wx.ImageFromStream(stream)

[docs]def MakePalette(tr, tg, tb):
    """
    Creates a palette to be applied on an image based on input colour.

    :param `tr`: the red intensity of the input colour;
    :param `tg`: the green intensity of the input colour;
    :param `tb`: the blue intensity of the input colour.
    """

    l = []
    for i in range(255):
        l.extend([tr*i / 255, tg*i / 255, tb*i / 255])

    return l

[docs]def ConvertWXToPIL(bmp):
    """
    Converts a `wx.Image` into a PIL image.

    :param `bmp`: an instance of `wx.Image`.

    :note: Requires PIL (Python Imaging Library), which can be downloaded from
     http://www.pythonware.com/products/pil/
    """

    width = bmp.GetWidth()
    height = bmp.GetHeight()
    img = Image.fromstring("RGBA", (width, height), bmp.GetData())

    return img

[docs]def ConvertPILToWX(pil, alpha=True):
    """
    Converts a PIL image into a `wx.Image`.

    :param `pil`: a PIL image;
    :param `alpha`: ``True`` if the image contains alpha transparency, ``False``
     otherwise.

    :note: Requires PIL (Python Imaging Library), which can be downloaded from
     http://www.pythonware.com/products/pil/
    """

    if alpha:
        image = apply(wx.EmptyImage, pil.size)
        image.SetData(pil.convert("RGB").tostring())
        image.SetAlphaData(pil.convert("RGBA").tostring()[3::4])
    else:
        image = wx.EmptyImage(pil.size[0], pil.size[1])
        new_image = pil.convert('RGB')
        data = new_image.tostring()
        image.SetData(data)

    return image

# ---------------------------------------------------------------------------- #
# Class RulerCtrlEvent
# ---------------------------------------------------------------------------- #

[docs]class RulerCtrlEvent(wx.PyCommandEvent):
    """
    Represent details of the events that the L{RulerCtrl} object sends.
    """

[docs]    def __init__(self, eventType, eventId=1):
        """
        Default class constructor.

        :param `eventType`: the event type;
        :param `eventId`: the event identifier.
        """

        wx.PyCommandEvent.__init__(self, eventType, eventId)

[docs]    def SetValue(self, value):
        """
        Sets the event value.

        :param `value`: the new indicator position.
        """

        self._value = value

[docs]    def GetValue(self):
        """ Returns the event value. """

        return self._value

[docs]    def SetOldValue(self, oldValue):
        """
        Sets the event old value.

        :param `value`: the old indicator position.
        """

        self._oldValue = oldValue

[docs]    def GetOldValue(self):
        """ Returns the event old value. """

        return self._oldValue

# ---------------------------------------------------------------------------- #
# Class Label
# ---------------------------------------------------------------------------- #

[docs]class Label(object):
    """
    Auxilary class. Just holds information about a label in L{RulerCtrl}.
    """

[docs]    def __init__(self, pos=-1, lx=-1, ly=-1, text=""):
        """
        Default class constructor.

        :param `pos`: the indicator position;
        :param `lx`: the indicator `x` coordinate;
        :param `ly`: the indicator `y` coordinate;
        :param `text`: the label text.
        """

        self.pos = pos
        self.lx = lx
        self.ly = ly
        self.text = text

# ---------------------------------------------------------------------------- #
# Class Indicator
# ---------------------------------------------------------------------------- #

[docs]class Indicator(object):
    """
    This class holds all the information about a single indicator inside L{RulerCtrl}.

    You should not call this class directly. Use::

        ruler.AddIndicator(id, value)

    to add an indicator to your L{RulerCtrl}.
    """

[docs]    def __init__(self, parent, id=wx.ID_ANY, value=0):
        """
        Default class constructor.

        :param `parent`: the parent window, an instance of L{RulerCtrl};
        :param `id`: the indicator identifier;
        :param `value`: the initial value of the indicator.
        """

        self._parent = parent
        if id == wx.ID_ANY:
            id = wx.NewId()

        self._id = id
        self._colour = None

        self.RotateImage(GetIndicatorImage())
        self.SetValue(value)

[docs]    def GetPosition(self):
        """ Returns the position at which we should draw the indicator bitmap. """

        orient = self._parent._orientation
        flip = self._parent._flip
        left, top, right, bottom = self._parent.GetBounds()
        minval = self._parent._min
        maxval = self._parent._max

        value = self._value

        if self._parent._log:
            value = math.log10(value)
            maxval = math.log10(maxval)
            minval = math.log10(minval)

        pos = float(value-minval)/abs(maxval - minval)

        if orient == wx.HORIZONTAL:
            xpos = int(pos*right) - self._img.GetWidth()/2
            if flip:
                ypos = top
            else:
                ypos = bottom - self._img.GetHeight()
        else:
            ypos = int(pos*bottom) - self._img.GetHeight()/2
            if flip:
                xpos = left
            else:
                xpos = right - self._img.GetWidth()

        return xpos, ypos

[docs]    def GetImageSize(self):
        """ Returns the indicator bitmap size. """

        return self._img.GetWidth(), self._img.GetHeight()

[docs]    def GetRect(self):
        """ Returns the indicator client rectangle. """

        return self._rect

[docs]    def RotateImage(self, img=None):
        """
        Rotates the default indicator bitmap.

        :param `img`: if not ``None``, the indicator image.
        """

        if img is None:
            img = GetIndicatorImage()

        orient = self._parent._orientation
        flip = self._parent._flip
        left, top, right, bottom = self._parent.GetBounds()

        if orient == wx.HORIZONTAL:
            if flip:
                img = img.Rotate(math.pi, (5, 5), True)
        else:
            if flip:
                img = img.Rotate(-math.pi/2, (5, 5), True)
            else:
                img = img.Rotate(math.pi/2, (5, 5), True)

        self._img = img

[docs]    def SetValue(self, value):
        """
        Sets the indicator value.

        :param `value`: the new indicator value.
        """

        if value < self._parent._min:
            value = self._parent._min
        if value > self._parent._max:
            value = self._parent._max

        self._value = value
        self._rect = wx.Rect()

        self._parent.Refresh()

[docs]    def GetValue(self):
        """ Returns the indicator value. """

        return self._value

[docs]    def Draw(self, dc):
        """
        Actually draws the indicator.

        :param `dc`: an instance of `wx.DC`.
        """

        xpos, ypos = self.GetPosition()
        bmp = wx.BitmapFromImage(self._img)
        dc.DrawBitmap(bmp, xpos, ypos, True)
        self._rect = wx.Rect(xpos, ypos, self._img.GetWidth(), self._img.GetHeight())

[docs]    def GetId(self):
        """ Returns the indicator id. """

        return self._id

[docs]    def SetColour(self, colour):
        """
        Sets the indicator colour.

        :param `colour`: the new indicator colour, an instance of `wx.Colour`.

        :note: Requires PIL (Python Imaging Library), which can be downloaded from
         http://www.pythonware.com/products/pil/
        """

        if not _hasPIL:
            return

        palette = colour.Red(), colour.Green(), colour.Blue()

        img = ConvertWXToPIL(GetIndicatorBitmap())
        l = MakePalette(*palette)
        # The Palette Can Be Applied Only To "L" And "P" Images, Not "RGBA"
        img = img.convert("L")
        # Apply The New Palette
        img.putpalette(l)
        # Convert The Image Back To RGBA
        img = img.convert("RGBA")
        img = ConvertPILToWX(img)
        self.RotateImage(img)

        self._parent.Refresh()

# ---------------------------------------------------------------------------- #
# Class RulerCtrl
# ---------------------------------------------------------------------------- #

[docs]class RulerCtrl(wx.PyPanel):
    """
    L{RulerCtrl} implements a ruler window that can be placed on top, bottom, left or right
    to any wxPython widget. It is somewhat similar to the rulers you can find in text
    editors software, though not so powerful.
    """

[docs]    def __init__(self, parent, id=-1, pos=wx.DefaultPosition, size=wx.DefaultSize,
                 style=wx.STATIC_BORDER, orient=wx.HORIZONTAL):
        """
        Default class constructor.

        :param `parent`: parent window. Must not be ``None``;
        :param `id`: window identifier. A value of -1 indicates a default value;
        :param `pos`: the control position. A value of (-1, -1) indicates a default position,
         chosen by either the windowing system or wxPython, depending on platform;
        :param `size`: the control size. A value of (-1, -1) indicates a default size,
         chosen by either the windowing system or wxPython, depending on platform;
        :param `style`: the window style;
        :param `orient`: sets the orientation of the L{RulerCtrl}, and can be either
         ``wx.HORIZONTAL`` of ``wx.VERTICAL``.
        """

        wx.PyPanel.__init__(self, parent, id, pos, size, style)

        self.SetBackgroundStyle(wx.BG_STYLE_CUSTOM)
        width, height = size

        self._min = 0.0
        self._max = 10.0
        self._orientation = orient
        self._spacing = 5
        self._hassetspacing = False
        self._format = RealFormat
        self._flip = False
        self._log = False
        self._labeledges = False
        self._units = ""

        self._drawingparent = None
        self._drawingpen = wx.Pen(wx.BLACK, 2)

        self._left = -1
        self._top = -1
        self._right = -1
        self._bottom = -1

        self._major = 1
        self._minor = 1

        self._indicators = []
        self._currentIndicator = None

        fontsize = 10
        if wx.Platform == "__WXMSW__":
            fontsize = 8

        self._minorfont = wx.Font(fontsize, wx.SWISS, wx.NORMAL, wx.NORMAL)
        self._majorfont = wx.Font(fontsize, wx.SWISS, wx.NORMAL, wx.BOLD)

        if wx.Platform == "__WXMAC__":
            self._minorfont.SetNoAntiAliasing(True)
            self._majorfont.SetNoAntiAliasing(True)

        self._bits = []
        self._userbits = []
        self._userbitlen = 0
        self._tickmajor = True
        self._tickminor = True
        self._timeformat = IntFormat
        self._labelmajor = True
        self._labelminor = True
        self._tickpen = wx.Pen(wx.BLACK)
        self._textcolour = wx.BLACK
        self._background = wx.WHITE

        self._valid = False
        self._state = 0

        self._style = style
        self._orientation = orient
        wbound, hbound = self.CheckStyle()

        if orient & wx.VERTICAL:
            self.SetBestSize((28, height))
        else:
            self.SetBestSize((width, 28))

        self.SetBounds(0, 0, wbound, hbound)

        self.Bind(wx.EVT_SIZE, self.OnSize)
        self.Bind(wx.EVT_PAINT, self.OnPaint)
        self.Bind(wx.EVT_ERASE_BACKGROUND, self.OnEraseBackground)
        self.Bind(wx.EVT_MOUSE_EVENTS, self.OnMouseEvents)
        self.Bind(wx.EVT_MOUSE_CAPTURE_LOST, lambda evt: True)

[docs]    def OnMouseEvents(self, event):
        """
        Handles the ``wx.EVT_MOUSE_EVENTS`` event for L{RulerCtrl}.

        :param `event`: a `wx.MouseEvent` event to be processed.
        """

        if not self._indicators:
            event.Skip()
            return

        mousePos = event.GetPosition()

        if event.LeftDown():
            self.CaptureMouse()
            self.GetIndicator(mousePos)
            self._mousePosition = mousePos
            self.SetIndicatorValue(sendEvent=False)
        elif event.Dragging() and self._currentIndicator:
            self._mousePosition = mousePos
            self.SetIndicatorValue()
        elif event.LeftUp():
            if self.HasCapture():
                self.ReleaseMouse()
            self.SetIndicatorValue(sendEvent=False)
            if self._drawingparent:
                self._drawingparent.Refresh()
            self._currentIndicator = None
        #else:
        #    self._currentIndicator = None

        event.Skip()

[docs]    def OnPaint(self, event):
        """
        Handles the ``wx.EVT_PAINT`` event for L{RulerCtrl}.

        :param `event`: a `wx.PaintEvent` event to be processed.
        """

        dc = wx.BufferedPaintDC(self)
        dc.SetBackground(wx.Brush(self._background))
        dc.Clear()
        self.Draw(dc)

[docs]    def OnSize(self, event):
        """
        Handles the ``wx.EVT_SIZE`` event for L{RulerCtrl}.

        :param `event`: a `wx.SizeEvent` event to be processed.
        """

        width, height = self.CheckStyle()
        self.SetBounds(0, 0, width, height)

        self.Invalidate()
        event.Skip()

[docs]    def OnEraseBackground(self, event):
        """
        Handles the ``wx.EVT_ERASE_BACKGROUND`` event for L{RulerCtrl}.

        :param `event`: a `wx.EraseEvent` event to be processed.

        :note: This method is intentionally empty to reduce flicker.
        """

        pass

[docs]    def SetIndicatorValue(self, sendEvent=True):
        """
        Sets the indicator value.

        :param `sendEvent`: ``True`` to send a L{RulerCtrlEvent}, ``False`` otherwise.
        """

        if self._currentIndicator is None:
            return

        left, top, right, bottom = self.GetBounds()

        x = self._mousePosition.x
        y = self._mousePosition.y

        maxvalue = self._max
        minvalue = self._min

        if self._log:
            minvalue = math.log10(minvalue)
            maxvalue = math.log10(maxvalue)

        deltarange = abs(self._max - self._min)

        if self._orientation == wx.HORIZONTAL:  # only x moves
            value = deltarange*float(x)/(right - left)
        else:
            value = deltarange*float(y)/(bottom - top)

        value += minvalue

        if self._log:
            value = 10**value

        if value < self._min or value > self._max:
            return

        self.DrawOnParent(self._currentIndicator)

        if sendEvent:
            event = RulerCtrlEvent(wxEVT_INDICATOR_CHANGING, self._currentIndicator.GetId())
            event.SetOldValue(self._currentIndicator.GetValue())

            event.SetValue(value)
            event.SetEventObject(self)

            if self.GetEventHandler().ProcessEvent(event):
                self.DrawOnParent(self._currentIndicator)
                return

            self._currentIndicator.SetValue(value)

        if sendEvent:
            event.SetEventType(wxEVT_INDICATOR_CHANGED)
            event.SetOldValue(value)
            self.GetEventHandler().ProcessEvent(event)
            self.DrawOnParent(self._currentIndicator)

        self.Refresh()

[docs]    def GetIndicator(self, mousePos):
        """
        Returns the indicator located at the mouse position `mousePos` (if any).

        :param `mousePos`: the mouse position, an instance of `wx.Point`.
        """

        for indicator in self._indicators:
            if indicator.GetRect().Contains(mousePos):
                self._currentIndicator = indicator
                break

[docs]    def CheckStyle(self):
        """ Adjust the L{RulerCtrl} style accordingly to borders, units, etc..."""

        width, height = self.GetSize()

        if self._orientation & wx.HORIZONTAL:
            if self._style & wx.NO_BORDER:
                hbound = 28
                wbound = width-1
            elif self._style & wx.SIMPLE_BORDER:
                hbound = 27
                wbound = width-1
            elif self._style & wx.STATIC_BORDER:
                hbound = 26
                wbound = width-3
            elif self._style & wx.SUNKEN_BORDER:
                hbound = 24
                wbound = width-5
            elif self._style & wx.RAISED_BORDER:
                hbound = 22
                wbound = width-7
            elif self._style & wx.DOUBLE_BORDER:
                hbound = 22
                wbound = width-7
        else:
            if self._style & wx.NO_BORDER:
                wbound = 28
                hbound = height-1
            elif self._style & wx.SIMPLE_BORDER:
                wbound = 27
                hbound = height-1
            elif self._style & wx.STATIC_BORDER:
                wbound = 26
                hbound = height-3
            elif self._style & wx.SUNKEN_BORDER:
                wbound = 24
                hbound = height-5
            elif self._style & wx.RAISED_BORDER:
                wbound = 22
                hbound = height-7
            elif self._style & wx.DOUBLE_BORDER:
                wbound = 22
                hbound = height-7

        minText = self.LabelString(self._min, major=True)
        maxText = self.LabelString(self._max, major=True)

        dc = wx.ClientDC(self)
        minWidth, minHeight = dc.GetTextExtent(minText)
        maxWidth, maxHeight = dc.GetTextExtent(maxText)

        maxWidth = max(maxWidth, minWidth)
        maxHeight = max(maxHeight, minHeight)

        if self._orientation == wx.HORIZONTAL:
            if maxHeight + 4 > hbound:
                hbound = maxHeight
                self.SetBestSize((-1, maxHeight + 4))
                if self.GetContainingSizer():
                    self.GetContainingSizer().Layout()
        else:
            if maxWidth + 4 > wbound:
                wbound = maxWidth
                self.SetBestSize((maxWidth + 4, -1))
                if self.GetContainingSizer():
                    self.GetContainingSizer().Layout()

        return wbound, hbound

[docs]    def TickMajor(self, tick=True):
        """
        Sets whether the major ticks should be ticked or not.

        :param `tick`: ``True`` to show major ticks, ``False`` otherwise.
        """

        if self._tickmajor != tick:
            self._tickmajor = tick
            self.Invalidate()

[docs]    def TickMinor(self, tick=True):
        """
        Sets whether the minor ticks should be ticked or not.

        :param `tick`: ``True`` to show minor ticks, ``False`` otherwise.
        """

        if self._tickminor != tick:
            self._tickminor = tick
            self.Invalidate()

[docs]    def LabelMinor(self, label=True):
        """
        Sets whether the minor ticks should be labeled or not.

        :param `label`: ``True`` to label minor ticks, ``False`` otherwise.
        """

        if self._labelminor != label:
            self._labelminor = label
            self.Invalidate()

[docs]    def LabelMajor(self, label=True):
        """
        Sets whether the major ticks should be labeled or not.

        :param `label`: ``True`` to label major ticks, ``False`` otherwise.
        """

        if self._labelmajor != label:
            self._labelmajor = label
            self.Invalidate()

[docs]    def GetTimeFormat(self):
        """ Returns the time format. """

        return self._timeformat

[docs]    def SetTimeFormat(self, format=TimeFormat):
        """
        Sets the time format.

        :param `format`: the format used to display time values.
        """

        if self._timeformat != format:
            self._timeformat = format
            self.Invalidate()

[docs]    def SetFormat(self, format):
        """
        Sets the format for L{RulerCtrl}.

        :param `format`: the format used to display values in L{RulerCtrl}. This can be
         one of the following bits:

         ====================== ======= ==============================
         Format                  Value  Description
         ====================== ======= ==============================
         ``IntFormat``                1 Integer format
         ``RealFormat``               2 Real format
         ``TimeFormat``               3 Time format
         ``LinearDBFormat``           4 Linear DB format
         ``HHMMSS_Format``            5 HHMMSS format
         ====================== ======= ==============================
         """

        if self._format != format:
            self._format = format
            self.Invalidate()

[docs]    def GetFormat(self):
        """
        Returns the format used to display values in L{RulerCtrl}.

        :see: L{SetFormat} for a list of possible formats.
        """

        return self._format

[docs]    def SetLog(self, log=True):
        """
        Sets whether L{RulerCtrl} should have a logarithmic scale or not.

        :param `log`: ``True`` to use a logarithmic scake, ``False`` to use a
         linear one.
        """

        if self._log != log:
            self._log = log
            self.Invalidate()

[docs]    def SetUnits(self, units):
        """
        Sets the units that should be displayed beside the labels.

        :param `units`: the units that should be displayed beside the labels.
        """

        # Specify the name of the units (like "dB") if you
        # want numbers like "1.6" formatted as "1.6 dB".

        if self._units != units:
            self._units = units
            self.Invalidate()

[docs]    def SetBackgroundColour(self, colour):
        """
        Sets the L{RulerCtrl} background colour.

        :param `colour`: an instance of `wx.Colour`.

        :note: Overridden from `wx.PyPanel`.
        """

        self._background = colour
        wx.PyPanel.SetBackgroundColour(self, colour)
        self.Refresh()

[docs]    def SetOrientation(self, orient=None):
        """
        Sets the L{RulerCtrl} orientation.

        :param `orient`: can be ``wx.HORIZONTAL`` or ``wx.VERTICAL``.
        """

        if orient is None:
            orient = wx.HORIZONTAL

        if self._orientation != orient:
            self._orientation = orient

            if self._orientation == wx.VERTICAL and not self._hassetspacing:
                self._spacing = 2

            self.Invalidate()

[docs]    def SetRange(self, minVal, maxVal):
        """
        Sets the L{RulerCtrl} range.

        :param `minVal`: the minimum value of L{RulerCtrl};
        :param `maxVal`: the maximum value of L{RulerCtrl}.
        """

        # For a horizontal ruler,
        # minVal is the value in the center of pixel "left",
        # maxVal is the value in the center of pixel "right".

        if self._min != minVal or self._max != maxVal:
            self._min = minVal
            self._max = maxVal
            self.Invalidate()

[docs]    def SetSpacing(self, spacing):
        """
        Sets the L{RulerCtrl} spacing between labels.

        :param `spacing`: the spacing between labels, in pixels.
        """

        self._hassetspacing = True

        if self._spacing != spacing:
            self._spacing = spacing
            self.Invalidate()

[docs]    def SetLabelEdges(self, labelEdges=True):
        """
        Sets whether the edge values should always be displayed or not.

        :param `labelEdges`: ``True`` to always display edge labels, ``False`` otherwise/
        """

        # If this is True, the edges of the ruler will always
        # receive a label.  If not, the nearest round number is
        # labeled (which may or may not be the edge).

        if self._labeledges != labelEdges:
            self._labeledges = labelEdges
            self.Invalidate()

[docs]    def SetFlip(self, flip=True):
        """
        Sets whether the orientation of the tick marks should be reversed.

        :param `flip`: ``True`` to reverse the orientation of the tick marks, ``False``
         otherwise.
        """

        # If this is True, the orientation of the tick marks
        # is reversed from the default eg. above the line
        # instead of below

        if self._flip != flip:
            self._flip = flip
            self.Invalidate()
            for indicator in self._indicators:
                indicator.RotateImage()

[docs]    def SetFonts(self, minorFont, majorFont):
        """
        Sets the fonts for minor and major tick labels.

        :param `minorFont`: the font used to draw minor ticks, a valid `wx.Font` object;
        :param `majorFont`: the font used to draw major ticks, a valid `wx.Font` object.
        """

        self._minorfont = minorFont
        self._majorfont = majorFont

        if wx.Platform == "__WXMAC__":
            self._minorfont.SetNoAntiAliasing(True)
            self._majorfont.SetNoAntiAliasing(True)

        self.Invalidate()

[docs]    def SetTickPenColour(self, colour=wx.BLACK):
        """
        Sets the pen colour to draw the ticks.

        :param `colour`: a valid `wx.Colour` object.
        """

        self._tickpen = wx.Pen(colour)
        self.Refresh()

[docs]    def SetLabelColour(self, colour=wx.BLACK):
        """
        Sets the labels colour.

        :param `colour`: a valid `wx.Colour` object.
        """

        self._textcolour = colour
        self.Refresh()

[docs]    def OfflimitsPixels(self, start, end):
        """ Used internally. """

        if not self._userbits:
            if self._orientation == wx.HORIZONTAL:
                self._length = self._right-self._left
            else:
                self._length = self._bottom-self._top

            self._userbits = [0]*self._length
            self._userbitlen  = self._length+1

        if end < start:
            i = end
            end = start
            start = i

        if start < 0:
            start = 0
        if end > self._length:
            end = self._length

        for ii in xrange(start, end+1):
            self._userbits[ii] = 1

[docs]    def SetBounds(self, left, top, right, bottom):
        """
        Sets the bounds for L{RulerCtrl} (its client rectangle).

        :param `left`: the left corner of the client rectangle;
        :param `top`: the top corner of the client rectangle;
        :param `right`: the right corner of the client rectangle;
        :param `bottom`: the bottom corner of the client rectangle.
        """

        if self._left != left or self._top != top or self._right != right or \
           self._bottom != bottom:

            self._left = left
            self._top = top
            self._right = right
            self._bottom = bottom

            self.Invalidate()

[docs]    def GetBounds(self):
        """ Returns the L{RulerCtrl} bounds (its client rectangle). """

        return self._left, self._top, self._right, self._bottom

[docs]    def AddIndicator(self, id, value):
        """
        Adds an indicator to L{RulerCtrl}. You should pass a unique `id` and a starting
        `value` for the indicator.

        :param `id`: the indicator identifier;
        :param `value`: the indicator initial value.
        """

        self._indicators.append(Indicator(self, id, value))
        self.Refresh()

[docs]    def SetIndicatorColour(self, id, colour=None):
        """
        Sets the indicator colour.

        :param `id`: the indicator identifier;
        :param `colour`: a valid `wx.Colour` object.

        :note: This method requires PIL to change the image palette.
        """

        if not _hasPIL:
            return

        if colour is None:
            colour = wx.WHITE

        for indicator in self._indicators:
            if indicator.GetId() == id:
                indicator.SetColour(colour)
                break

[docs]    def Invalidate(self):
        """ Invalidates the ticks calculations. """

        self._valid = False

        if self._orientation == wx.HORIZONTAL:
            self._length = self._right - self._left
        else:
            self._length = self._bottom - self._top

        self._majorlabels = []
        self._minorlabels = []
        self._bits = []
        self._userbits = []
        self._userbitlen = 0
        self.Refresh()

[docs]    def FindLinearTickSizes(self, UPP):
        """ Used internally. """

        # Given the dimensions of the ruler, the range of values it
        # has to display, and the format (i.e. Int, Real, Time),
        # figure out how many units are in one Minor tick, and
        # in one Major tick.
        #
        # The goal is to always put tick marks on nice round numbers
        # that are easy for humans to grok.  This is the most tricky
        # with time.

        # As a heuristic, we want at least 16 pixels
        # between each minor tick
        units = 16.0*abs(UPP)

        self._digits = 0

        if self._format == LinearDBFormat:

            if units < 0.1:
                self._minor = 0.1
                self._major = 0.5
                return

            if units < 1.0:
                self._minor = 1.0
                self._major = 6.0
                return

            self._minor = 3.0
            self._major = 12.0
            return

        elif self._format == IntFormat:

            d = 1.0
            while 1:
                if units < d:
                    self._minor = d
                    self._major = d*5.0
                    return

                d = d*5.0
                if units < d:
                    self._minor = d
                    self._major = d*2.0
                    return

                d = 2.0*d

        elif self._format == TimeFormat:

            if units > 0.5:
                if units < 1.0:  # 1 sec
                    self._minor = 1.0
                    self._major = 5.0
                    return

                if units < 5.0:  # 5 sec
                    self._minor = 5.0
                    self._major = 15.0
                    return

                if units < 10.0:
                    self._minor = 10.0
                    self._major = 30.0
                    return

                if units < 15.0:
                    self._minor = 15.0
                    self._major = 60.0
                    return

                if units < 30.0:
                    self._minor = 30.0
                    self._major = 60.0
                    return

                if units < 60.0:  # 1 min
                    self._minor = 60.0
                    self._major = 300.0
                    return

                if units < 300.0:  # 5 min
                    self._minor = 300.0
                    self._major = 900.0
                    return

                if units < 600.0:  # 10 min
                    self._minor = 600.0
                    self._major = 1800.0
                    return

                if units < 900.0:  # 15 min
                    self._minor = 900.0
                    self._major = 3600.0
                    return

                if units < 1800.0:  # 30 min
                    self._minor = 1800.0
                    self._major = 3600.0
                    return

                if units < 3600.0:  # 1 hr
                    self._minor = 3600.0
                    self._major = 6*3600.0
                    return

                if units < 6*3600.0:  # 6 hrs
                    self._minor = 6*3600.0
                    self._major = 24*3600.0
                    return

                if units < 24*3600.0:  # 1 day
                    self._minor = 24*3600.0
                    self._major = 7*24*3600.0
                    return

                self._minor = 24.0*7.0*3600.0 # 1 week
                self._major = 24.0*7.0*3600.0

        # Otherwise fall through to RealFormat
        # (fractions of a second should be dealt with
        # the same way as for RealFormat)

        elif self._format == RealFormat:

            d = 0.000001
            self._digits = 6

            while 1:
                if units < d:
                    self._minor = d
                    self._major = d*5.0
                    return

                d = d*5.0
                if units < d:
                    self._minor = d
                    self._major = d*2.0
                    return

                d = d*2.0
                self._digits = self._digits - 1

[docs]    def LabelString(self, d, major=None):
        """ Used internally. """

        # Given a value, turn it into a string according
        # to the current ruler format.  The number of digits of
        # accuracy depends on the resolution of the ruler,
        # i.e. how far zoomed in or out you are.

        s = ""

        if d < 0.0 and d + self._minor > 0.0:
            d = 0.0

        if self._format == IntFormat:
            s = "%d"%int(math.floor(d+0.5))

        elif self._format == LinearDBFormat:
            if self._minor >= 1.0:
                s = "%d"%int(math.floor(d+0.5))
            else:
                s = "%0.1f"%d

        elif self._format == RealFormat:
            if self._minor >= 1.0:
                s = "%d"%int(math.floor(d+0.5))
            else:
                s = (("%." + str(self._digits) + "f")%d).strip()

        elif self._format == TimeFormat:
            if major:
                if d < 0:
                    s = "-"
                    d = -d

                if self.GetTimeFormat() == HHMMSS_Format:

                    secs = int(d + 0.5)
                    if self._minor >= 1.0:
                        s = ("%d:%02d:%02d")%(secs/3600, (secs/60)%60, secs%60)

                    else:
                        t1 = ("%d:%02d:")%(secs/3600, (secs/60)%60)
                        format = "%" + "%0d.%dlf"%(self._digits+3, self._digits)
                        t2 = format%(d%60.0)
                        s = s + t1 + t2

                else:

                    if self._minor >= 3600.0:
                        hrs = int(d/3600.0 + 0.5)
                        h = "%d:00:00"%hrs
                        s = s + h

                    elif self._minor >= 60.0:
                        minutes = int(d/60.0 + 0.5)
                        if minutes >= 60:
                            m = "%d:%02d:00"%(minutes/60, minutes%60)
                        else:
                            m = "%d:00"%minutes

                        s = s + m

                    elif self._minor >= 1.0:
                        secs = int(d + 0.5)
                        if secs >= 3600:
                            t = "%d:%02d:%02d"%(secs/3600, (secs/60)%60, secs%60)
                        elif secs >= 60:
                            t = "%d:%02d"%(secs/60, secs%60)
                        else:
                            t = "%d"%secs

                        s = s + t

                    else:
                        secs = int(d)
                        if secs >= 3600:
                            t1 = "%d:%02d:"%(secs/3600, (secs/60)%60)
                        elif secs >= 60:
                            t1 = "%d:"%(secs/60)

                        if secs >= 60:
                            format = "%%0%d.%dlf"%(self._digits+3, self._digits)
                        else:
                            format = "%%%d.%dlf"%(self._digits+3, self._digits)

                        t2 = format%(d%60.0)

                        s = s + t1 + t2

        if self._units != "":
            s = s + " " + self._units

        return s

[docs]    def Tick(self, dc, pos, d, major):
        """
        Ticks a particular position.

        :param `dc`: an instance of `wx.DC`;
        :param `pos`: the label position;
        :param `d`: the current label value;
        :param `major`: ``True`` if it is a major ticks, ``False`` if it is a minor one.
        """

        if major:
            label = Label()
            self._majorlabels.append(label)
        else:
            label = Label()
            self._minorlabels.append(label)

        label.pos = pos
        label.lx = self._left - 2000 # don't display
        label.ly = self._top - 2000  # don't display
        label.text = ""

        dc.SetFont((major and [self._majorfont] or [self._minorfont])[0])

        l = self.LabelString(d, major)
        strw, strh = dc.GetTextExtent(l)

        if self._orientation == wx.HORIZONTAL:
            strlen = strw
            strpos = pos - strw/2
            if strpos < 0:
                strpos = 0
            if strpos + strw >= self._length:
                strpos = self._length - strw
            strleft = self._left + strpos
            if self._flip:
                strtop = self._top + 4
                self._maxheight = max(self._maxheight, 4 + strh)
            else:
                strtop = self._bottom - strh - 6
                self._maxheight = max(self._maxheight, strh + 6)

        else:
            strlen = strh
            strpos = pos - strh/2
            if strpos < 0:
                strpos = 0
            if strpos + strh >= self._length:
                strpos = self._length - strh
            strtop = self._top + strpos
            if self._flip:
                strleft = self._left + 5
                self._maxwidth = max(self._maxwidth, 5 + strw)
            else:
                strleft = self._right - strw - 6
                self._maxwidth = max(self._maxwidth, strw + 6)

        # See if any of the pixels we need to draw this
        # label is already covered

        if major and self._labelmajor or not major and self._labelminor:
            for ii in xrange(strlen):
                if self._bits[strpos+ii]:
                    return

        # If not, position the label and give it text

        label.lx = strleft
        label.ly = strtop
        label.text = l

        if major:
            if self._tickmajor and not self._labelmajor:
                label.text = ""
            self._majorlabels[-1] = label

        else:
            if self._tickminor and not self._labelminor:
                label.text = ""
            label.text = label.text.replace(self._units, "")
            self._minorlabels[-1] = label

        # And mark these pixels, plus some surrounding
        # ones (the spacing between labels), as covered

        if (not major and self._labelminor) or (major and self._labelmajor):

            leftmargin = self._spacing

            if strpos < leftmargin:
                leftmargin = strpos

            strpos = strpos - leftmargin
            strlen = strlen + leftmargin

            rightmargin = self._spacing

            if strpos + strlen > self._length - self._spacing:
                rightmargin = self._length - strpos - strlen

            strlen = strlen + rightmargin

            for ii in xrange(strlen):
                self._bits[strpos+ii] = 1

[docs]    def Update(self, dc):
        """
        Updates all the ticks calculations.

        :param `dc`: an instance of `wx.DC`.
        """

        # This gets called when something has been changed
        # (i.e. we've been invalidated).  Recompute all
        # tick positions.

        if self._orientation == wx.HORIZONTAL:
            self._maxwidth = self._length
            self._maxheight = 0
        else:
            self._maxwidth = 0
            self._maxheight = self._length

        self._bits = [0]*(self._length+1)
        self._middlepos = []

        if self._userbits:
            for ii in xrange(self._length):
                self._bits[ii] = self._userbits[ii]
        else:
            for ii in xrange(self._length):
                self._bits[ii] = 0

        if not self._log:

            UPP = (self._max - self._min)/float(self._length)  # Units per pixel

            self.FindLinearTickSizes(UPP)

            # Left and Right Edges
            if self._labeledges:
                self.Tick(dc, 0, self._min, True)
                self.Tick(dc, self._length, self._max, True)

            # Zero (if it's in the middle somewhere)
            if self._min*self._max < 0.0:
                mid = int(self._length*(self._min/(self._min-self._max)) + 0.5)
                self.Tick(dc, mid, 0.0, True)

            sg = ((UPP > 0.0) and [1.0] or [-1.0])[0]

            # Major ticks
            d = self._min - UPP/2
            lastd = d
            majorint = int(math.floor(sg*d/self._major))
            ii = -1

            while ii <= self._length:
                ii = ii + 1
                lastd = d
                d = d + UPP

                if int(math.floor(sg*d/self._major)) > majorint:
                    majorint = int(math.floor(sg*d/self._major))
                    self.Tick(dc, ii, sg*majorint*self._major, True)

            # Minor ticks
            d = self._min - UPP/2
            lastd = d
            minorint = int(math.floor(sg*d/self._minor))
            ii = -1

            while ii <= self._length:
                ii = ii + 1
                lastd = d
                d = d + UPP

                if int(math.floor(sg*d/self._minor)) > minorint:
                    minorint = int(math.floor(sg*d/self._minor))
                    self.Tick(dc, ii, sg*minorint*self._minor, False)

            # Left and Right Edges
            if self._labeledges:
                self.Tick(dc, 0, self._min, True)
                self.Tick(dc, self._length, self._max, True)

        else:
            # log case

            lolog = math.log10(self._min)
            hilog = math.log10(self._max)
            scale = self._length/(hilog - lolog)
            lodecade = int(math.floor(lolog))
            hidecade = int(math.ceil(hilog))

            # Left and Right Edges
            if self._labeledges:
                self.Tick(dc, 0, self._min, True)
                self.Tick(dc, self._length, self._max, True)

            startdecade = 10.0**lodecade

            # Major ticks are the decades
            decade = startdecade
            for ii in xrange(lodecade, hidecade):
                if ii != lodecade:
                    val = decade
                    if val > self._min and val < self._max:
                        pos = int(((math.log10(val) - lolog)*scale)+0.5)
                        self.Tick(dc, pos, val, True)

                decade = decade*10.0

            # Minor ticks are multiples of decades
            decade = startdecade

            for ii in xrange(lodecade, hidecade):
                for jj in xrange(2, 10):
                    val = decade*jj
                    if val >= self._min and val < self._max:
                        pos = int(((math.log10(val) - lolog)*scale)+0.5)
                        self.Tick(dc, pos, val, False)

                decade = decade*10.0

        self._valid = True

[docs]    def Draw(self, dc):
        """
        Actually draws the whole L{RulerCtrl}.

        :param `dc`: an instance of `wx.DC`.
        """

        if not self._valid:
            self.Update(dc)

        dc.SetBrush(wx.Brush(self._background))
        dc.SetPen(self._tickpen)
        dc.SetTextForeground(self._textcolour)

        dc.DrawRectangleRect(self.GetClientRect())

        if self._orientation == wx.HORIZONTAL:
            if self._flip:
                dc.DrawLine(self._left, self._top, self._right+1, self._top)
            else:
                dc.DrawLine(self._left, self._bottom-1, self._right+1, self._bottom-1)

        else:
            if self._flip:
                dc.DrawLine(self._left, self._top, self._left, self._bottom+1)
            else:
                dc.DrawLine(self._right-1, self._top, self._right-1, self._bottom+1)

        dc.SetFont(self._majorfont)

        for label in self._majorlabels:
            pos = label.pos

            if self._orientation == wx.HORIZONTAL:
                if self._flip:
                    dc.DrawLine(self._left + pos, self._top,
                                self._left + pos, self._top + 5)
                else:
                    dc.DrawLine(self._left + pos, self._bottom - 5,
                                self._left + pos, self._bottom)

            else:
                if self._flip:
                    dc.DrawLine(self._left, self._top + pos,
                                self._left + 5, self._top + pos)
                else:
                    dc.DrawLine(self._right - 5, self._top + pos,
                                self._right, self._top + pos)

            if label.text != "":
                dc.DrawText(label.text, label.lx, label.ly)

        dc.SetFont(self._minorfont)

        for label in self._minorlabels:
            pos = label.pos

            if self._orientation == wx.HORIZONTAL:
                if self._flip:
                    dc.DrawLine(self._left + pos, self._top,
                                self._left + pos, self._top + 3)
                else:
                    dc.DrawLine(self._left + pos, self._bottom - 3,
                                self._left + pos, self._bottom)

            else:
                if self._flip:
                    dc.DrawLine(self._left, self._top + pos,
                                self._left + 3, self._top + pos)
                else:
                    dc.DrawLine(self._right - 3, self._top + pos,
                                self._right, self._top + pos)

            if label.text != "":
                dc.DrawText(label.text, label.lx, label.ly)

        for indicator in self._indicators:
            indicator.Draw(dc)

[docs]    def SetDrawingParent(self, dparent):
        """
        Sets the window to which L{RulerCtrl} draws a thin line over.

        :param `dparent`: an instance of `wx.Window`, representing the window to
         which L{RulerCtrl} draws a thin line over.
        """

        self._drawingparent = dparent

[docs]    def GetDrawingParent(self):
        """ Returns the window to which L{RulerCtrl} draws a thin line over. """

        return self._drawingparent

[docs]    def DrawOnParent(self, indicator):
        """
        Actually draws the thin line over the drawing parent window.

        :param `indicator`: the current indicator, an instance of L{Indicator}.

        :note: This method is currently not available on wxMac as it uses `wx.ScreenDC`.
        """

        if not self._drawingparent:
            return

        xpos, ypos = indicator.GetPosition()
        parentrect = self._drawingparent.GetClientRect()

        dc = wx.ScreenDC()
        dc.SetLogicalFunction(wx.INVERT)
        dc.SetPen(self._drawingpen)
        dc.SetBrush(wx.TRANSPARENT_BRUSH)

        imgx, imgy = indicator.GetImageSize()

        if self._orientation == wx.HORIZONTAL:

            x1 = xpos+ imgx/2
            y1 = parentrect.y
            x2 = x1
            y2 = parentrect.height
            x1, y1 = self._drawingparent.ClientToScreenXY(x1, y1)
            x2, y2 = self._drawingparent.ClientToScreenXY(x2, y2)

        elif self._orientation == wx.VERTICAL:

            x1 = parentrect.x
            y1 = ypos + imgy/2
            x2 = parentrect.width
            y2 = y1

            x1, y1 = self._drawingparent.ClientToScreenXY(x1, y1)
            x2, y2 = self._drawingparent.ClientToScreenXY(x2, y2)

        dc.DrawLine(x1, y1, x2, y2)
        dc.SetLogicalFunction(wx.COPY)

Navigation

  • index
  • modules |
  • Home |
  • Gallery |
  • Contents»
  • Module code »
  • rulerctrl


shapedbutton

  • modules |
  • Home |
  • Gallery |
  • Contents»
  • Module code »
  • shapedbutton

Source code for shapedbutton

# --------------------------------------------------------------------------- #
# SHAPEDBUTTON Control wxPython IMPLEMENTATION
# Python Code By:
#
# Andrea Gavana, @ 18 Oct 2005
# Latest Revision: 16 Jan 2012, 20.00 GMT
#
#
# TODO List/Caveats
#
# 1. Elliptic Buttons May Be Handled Better, In My Opinion. They Look Nice
#    But They Are Somewhat More Difficult To Handle When Using Sizers.
#    This Is Probably Due To Some Lack In My Implementation;
#
# 2. I Am Unable To Translate The 2 Files "UpButton.png" And "DownButton.png"
#    Using "img2py" (Under wx.tools) Or With PIL In Order To Embed Them In
#    A Python File. Every Translation I Made, Did Not Preserve The Alpha
#    Channel So I Ended Up With Round Buttons Inside Black Squares. Does
#    Anyone Have A Suggestion Here?
#
# 3. Creating *A Lot* Of ShapedButtons May Require Some Time. In The Demo,
#    I Create 23 Buttons In About 0.4 Seconds On Windows XP, 3 GHz 1 GB RAM.
#
# 4. Creating Buttons With Size Greater Than wx.Size(200, 200) May Display
#    Buttons With Clearly Evident Pixel Edges. This Is Due To The Size Of The
#    Image Files I Load During Initialization. If This Is Not Satisfactory,
#    Please Let Me Know And I Will Upload Bigger Files.
#
# 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
# --------------------------------------------------------------------------- #

"""
`ShapedButton` tries to fill the lack of "custom shaped" controls in wxPython
and it can be used to build round or elliptic-shaped buttons.

Description
===========

`ShapedButton` tries to fill the lack of "custom shaped" controls in wxPython
(that depends on the same lack in wxWidgets). It can be used to build round
buttons or elliptic buttons.

I have stolen some code from `wx.lib.buttons` in order to recreate the same
classes (`GenButton`, `GenBitmapButton`, `GenBitmapTextButton`, `GenToggleButton`,
`GenBitmapToggleButton`, `GenBitmapTextToggleButton`). Here you have the same
classes (with "Gen" replaced by "S"), with the same event handling, but they
are rounded/elliptical buttons.

`ShapedButton` is based on a `wx.Window`, in which 2 images are drawn depending
on the button state (pressed or not pressed). The 2 images have been stolen
from Audacity (written with wxWidgets) and rearranged/reshaped/restyled
using adobe PhotoShop.
Changing the button colour in runtime was more difficult, but using some
intelligent instruction from the PIL library it can be done.

`ShapedButton` reacts on mouse events *only* if the mouse event occurred inside
the circle/ellipse, even if `ShapedButton` is built on a rectangular window.
This behavior is a lot different with respect to Audacity round buttons.

Usage
=====

Usage example::

    import wx
    import wx.lib.agw.shapedbutton as SB

    class MyFrame(wx.Frame):

        def __init__(self, parent):

            wx.Frame.__init__(self, parent, -1, "ShapedButton Demo")

            panel = wx.Panel(self)

            # Create 2 bitmaps for the button
            upbmp = wx.Bitmap("play.png", wx.BITMAP_TYPE_PNG)
            disbmp = wx.Bitmap("playdisabled.png", wx.BITMAP_TYPE_PNG)

            play = SB.SBitmapToggleButton(panel, -1, upbmp, (100, 50))
            play.SetUseFocusIndicator(False)
            play.SetBitmapDisabled(disbmp)

    # our normal wxApp-derived class, as usual

    app = wx.PySimpleApp()

    frame = MyFrame(None)
    app.SetTopWindow(frame)
    frame.Show()

    app.MainLoop()

The `ShapedButton` construction and usage is quite similar to the `wx.lib.buttons`
implementation.

Methods and Settings
====================

With `ShapedButton` you can:

- Create rounded/elliptical buttons/togglebuttons;
- Set images for the enabled/disabled/focused/selected state of the button;
- Draw the focus indicator (or disable it);
- Set label colour and font;
- Apply a rotation to the `ShapedButton` label;
- Change `ShapedButton` shape and text orientation in runtime.

:note: `ShapedButton` **requires** PIL (Python Imaging Library) library to be installed,
 which can be downloaded from http://www.pythonware.com/products/pil/ .

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 `wx.wxEVT_COMMAND_BUTTON_CLICKED` event, when the button is clicked.
================= ==================================================

License And Version
===================

`ShapedButton` is distributed under the wxPython license.

Latest revision: Andrea Gavana @ 16 Jan 2012, 20.00 GMT

Version 0.4

"""

#----------------------------------------------------------------------
# Beginning Of SHAPEDBUTTON wxPython Code
#----------------------------------------------------------------------

import wx

# First Check If PIL Is Installed Properly
try:

    import PIL.Image as Image

except ImportError:

    errstr = ("\nShapedButton *Requires* PIL (Python Imaging Library).\n"
             "You Can Get It At:\n\n"
             "http://www.pythonware.com/products/pil/\n\n"
             "ShapedButton Can Not Continue. Exiting...\n")

    raise Exception(errstr)

import os

folder = os.path.split(__file__)[0]

# Import Some Stuff For The Annoying Ellipsis... ;-)
from math import sin, cos, pi

#-----------------------------------------------------------------------------
# PATH & FILE FILLING FUNCTION (OS INDEPENDENT)
# This Is Required To Load The Pressed And Non-Pressed Images From The
# "images" Directory.
#-----------------------------------------------------------------------------

[docs]def opj(path):
    """
    Convert paths to the platform-specific separator.

    :param `path`: the path to convert.
    """

    strs = apply(os.path.join, tuple(path.split('/')))
    # HACK: on Linux, a leading / gets lost...
    if path.startswith('/'):
        strs = '/' + strs

    return strs

#-----------------------------------------------------------------------------

#----------------------------------------------------------------------
# Class SButtonEvent
# Code Stolen From wx.lib.buttons. This Class Handles All The Button
# And ToggleButton Events.
#----------------------------------------------------------------------

[docs]class SButtonEvent(wx.PyCommandEvent):
    """ Event sent from the generic buttons when the button is activated. """

[docs]    def __init__(self, eventType, eventId):
        """
        Default class constructor.

        :param `eventType`: the event type;
        :param `eventId`: the event identifier.
        """

        wx.PyCommandEvent.__init__(self, eventType, eventId)
        self.isDown = False
        self.theButton = None

[docs]    def SetIsDown(self, isDown):
        """
        Sets the button event as pressed.

        :param `isDown`: ``True`` to set the event as "pressed", ``False`` otherwise.
        """

        self.isDown = isDown

[docs]    def GetIsDown(self):
        """ Returns ``True`` if the button event is "pressed". """

        return self.isDown

[docs]    def SetButtonObj(self, btn):
        """
        Sets the event object for the event.

        :param `btn`: the button object.
        """

        self.theButton = btn

[docs]    def GetButtonObj(self):
        """ Returns the object associated with this event. """

        return self.theButton

#----------------------------------------------------------------------
# SBUTTON Class
# This Is The Main Class Implementation. See __init__() Method For
# Details. All The Other Button Types Depend On This Class For Event
# Handling And Property Settings.
#----------------------------------------------------------------------

[docs]class SButton(wx.Window):
    """ This is the main implementation of `ShapedButton`. """

    _labeldelta = 1

[docs]    def __init__(self, parent, id=wx.ID_ANY, label="", pos=wx.DefaultPosition,
                 size=wx.DefaultSize):
        """
        Default class constructor.

        :param `parent`: the L{SButton} parent. Must not be ``None``;
        :param `id`: window identifier. A value of -1 indicates a default value;
        :param `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;
        :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.
        """

        wx.Window.__init__(self, parent, id, pos, size)

        if label is None:
            label = ""

        self._enabled = True
        self._isup = True
        self._hasfocus = False
        self._usefocusind = True

        # Initialize Button Properties
        self.SetButtonColour()
        self.SetLabel(label)
        self.SetLabelColour()
        self.InitColours()
        self.SetAngleOfRotation()
        self.SetEllipseAxis()

        if size == wx.DefaultSize:
            self.SetInitialSize(self.DoGetBestSize())

        # Event Binding
        self.Bind(wx.EVT_LEFT_DOWN, self.OnLeftDown)
        self.Bind(wx.EVT_LEFT_UP, self.OnLeftUp)

        if wx.Platform == '__WXMSW__':
            self.Bind(wx.EVT_LEFT_DCLICK, self.OnLeftDown)

        self.Bind(wx.EVT_MOTION, self.OnMotion)
        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_SIZE, self.OnSize)
        self.Bind(wx.EVT_ERASE_BACKGROUND, lambda x: None)
        self.Bind(wx.EVT_PAINT, self.OnPaint)

[docs]    def SetButtonColour(self, colour=None):
        """
        Sets the button colour, for all button states.

        :param `colour`: an instance of `wx.Colour`.

        :note: The original button images are greyscale with a lot of pixels with
         different colours. Changing smoothly the button colour in order to
         give the same 3D effect can be efficiently done only with PIL.
        """

        if colour is None:
            colour = wx.WHITE

        palette = colour.Red(), colour.Green(), colour.Blue()

        self._buttoncolour = colour

        self._mainbuttondown = DownButton.GetImage()
        self._mainbuttonup = UpButton.GetImage()

[docs]    def GetButtonColour(self):
        """ Returns the button colour. """

        return self._buttoncolour

[docs]    def SetLabelColour(self, colour=None):
        """
        Sets the button label colour.

        :param `colour`: an instance of `wx.Colour`.
        """

        if colour is None:
            colour = wx.BLACK

        self._labelcolour = colour

[docs]    def GetLabelColour(self):
        """ Returns the button label colour. """

        return self._labelcolour

[docs]    def SetLabel(self, label=None):
        """
        Sets the button label.

        :param `label`: the new button label.
        """

        if label is None:
            label = ""

        self._buttonlabel = label

[docs]    def GetLabel(self):
        """ Returns the button label. """

        return self._buttonlabel

[docs]    def SetBestSize(self, size=None):
        """
        Given the current font settings, calculate and set a good size.

        :param `size`: if not ``None``, an instance of `wx.Size` to pass to
         `SetInitialSize`.
        """

        if size is None:
            size = wx.DefaultSize

        self.SetInitialSize(size)

[docs]    def DoGetBestSize(self):
        """
        Overridden base class virtual. Determines the best size of the button
        based on the label size.

        :note: Overridden from `wx.Window`.
        """

        w, h, usemin = self._GetLabelSize()
        defsize = wx.Button.GetDefaultSize()
        width = 12 + w

        if usemin and width < defsize.width:
           width = defsize.width

        height = 11 + h

        if usemin and height < defsize.height:
            height = defsize.height

        return (width, height)

[docs]    def AcceptsFocus(self):
        """
        Can this window be given focus by mouse click?

        :note: Overridden from `wx.Window`.
        """

        return self.IsShown() and self.IsEnabled()

[docs]    def ShouldInheritColours(self):
        """
        Overridden base class virtual. Buttons usually do not inherit
        parent's colours.
        """

        return False

[docs]    def Enable(self, enable=True):
        """
        Enables/disables the button.

        :param `enable`: ``True`` to enable the button, ``False`` to disable it.

        :note: Overridden from `wx.Window`.
        """

        self._enabled = enable
        self.Refresh()

[docs]    def IsEnabled(self):
        """ Returns wheter the button is enabled or not. """

        return self._enabled

[docs]    def SetUseFocusIndicator(self, flag):
        """
        Specifies if a focus indicator (dotted line) should be used.

        :param `flag`: ``True`` to use the focus indicator, ``False`` otherwise.
        """

        self._usefocusind = flag

[docs]    def GetUseFocusIndicator(self):
        """ Returns focus indicator flag. """

        return self._usefocusind

[docs]    def InitColours(self):
        """
        Calculates a new set of focus indicator colour and indicator pen
        based on button colour and label colour.
        """

        textclr = self.GetLabelColour()
        faceclr = self.GetButtonColour()

        r, g, b = faceclr.Get()
        hr, hg, hb = min(255,r+64), min(255,g+64), min(255,b+64)
        self._focusclr = wx.Colour(hr, hg, hb)

        if wx.Platform == "__WXMAC__":
            self._focusindpen = wx.Pen(textclr, 1, wx.SOLID)
        else:
            self._focusindpen = wx.Pen(textclr, 1, wx.USER_DASH)
            self._focusindpen.SetDashes([1,1])
            self._focusindpen.SetCap(wx.CAP_BUTT)

[docs]    def SetDefault(self):
        """ Sets the button as default item. """

        self.GetParent().SetDefaultItem(self)

    def _GetLabelSize(self):
        """ Used internally """

        w, h = self.GetTextExtent(self.GetLabel())
        return w, h, True

[docs]    def Notify(self):
        """ Notifies an event and let it be processed. """

        evt = SButtonEvent(wx.wxEVT_COMMAND_BUTTON_CLICKED, self.GetId())
        evt.SetIsDown(not self._isup)
        evt.SetButtonObj(self)
        evt.SetEventObject(self)
        self.GetEventHandler().ProcessEvent(evt)

[docs]    def DrawMainButton(self, dc, width, height):
        """
        Draws the main button, in whichever state it is.

        :param `dc`: an instance of `wx.DC`;
        :param `width`: the button width;
        :param `height`: the button height.
        """

        w = min(width, height)

        if w <= 2:
            return

        position = self.GetPosition()

        main, secondary = self.GetEllipseAxis()
        xc = width/2
        yc = height/2

        if abs(main - secondary) < 1e-6:
            # In This Case The Button Is A Circle
            if self._isup:
                img = self._mainbuttonup.Scale(w, w)
            else:
                img = self._mainbuttondown.Scale(w, w)
        else:
            # In This Case The Button Is An Ellipse... Some Math To Do
            rect = self.GetRect()

            if main > secondary:
                # This Is An Ellipse With Main Axis Aligned With X Axis
                rect2 = w
                rect3 = w*secondary/main

            else:
                # This Is An Ellipse With Main Axis Aligned With Y Axis
                rect3 = w
                rect2 = w*main/secondary

            if self._isup:
                img = self._mainbuttonup.Scale(rect2, rect3)
            else:
                img = self._mainbuttondown.Scale(rect2, rect3)

        bmp = img.ConvertToBitmap()

        if abs(main - secondary) < 1e-6:
            if height > width:
                xpos = 0
                ypos = (height - width)/2
            else:
                xpos = (width - height)/2
                ypos = 0
        else:
            if height > width:
                if main > secondary:
                    xpos = 0
                    ypos = (height - rect3)/2
                else:
                    xpos = (width - rect2)/2
                    ypos = (height - rect3)/2
            else:
                if main > secondary:
                    xpos = (width - rect2)/2
                    ypos = (height - rect3)/2
                else:
                    xpos = (width - rect2)/2
                    ypos = 0

        # Draw Finally The Bitmap
        dc.DrawBitmap(bmp, xpos, ypos, True)

        # Store Bitmap Position And Size To Draw An Elliptical Focus Indicator
        self._xpos = xpos
        self._ypos = ypos
        self._imgx = img.GetWidth()
        self._imgy = img.GetHeight()

[docs]    def DrawLabel(self, dc, width, height, dw=0, dh=0):
        """
        Draws the label on the button.

        :param `dc`: an instance of `wx.DC`;
        :param `width`: the button width;
        :param `height`: the button height;
        :param `dw`: width differential, to show a 3D effect;
        :param `dh`: height differential, to show a 3D effect.
        """

        dc.SetFont(self.GetFont())

        if self.IsEnabled():
            dc.SetTextForeground(self.GetLabelColour())
        else:
            dc.SetTextForeground(wx.SystemSettings.GetColour(wx.SYS_COLOUR_GRAYTEXT))

        label = self.GetLabel()
        tw, th = dc.GetTextExtent(label)

        w = min(width, height)

        # labeldelta Is Used To Give The Impression Of A "3D" Click
        if not self._isup:
            dw = dh = self._labeldelta

        angle = self.GetAngleOfRotation()*pi/180.0

        # Check If There Is Any Rotation Chosen By The User
        if angle == 0:
            dc.DrawText(label, (width-tw)/2+dw, (height-th)/2+dh)
        else:
            xc, yc = (width/2, height/2)

            xp = xc - (tw/2)* cos(angle) - (th/2)*sin(angle)
            yp = yc + (tw/2)*sin(angle) - (th/2)*cos(angle)

            dc.DrawRotatedText(label, xp + dw, yp + dh , angle*180/pi)

[docs]    def DrawFocusIndicator(self, dc, width, height):
        """
        Draws the focus indicator. This is a circle/ellipse inside the button
        drawn with a dotted-style pen, to let the user know which button has
        the focus.

        :param `dc`: an instance of `wx.DC`;
        :param `width`: the button width;
        :param `height`: the button height.
        """

        self._focusindpen.SetColour(self._focusclr)
        dc.SetLogicalFunction(wx.INVERT)
        dc.SetPen(self._focusindpen)
        dc.SetBrush(wx.TRANSPARENT_BRUSH)

        main, secondary = self.GetEllipseAxis()

        if abs(main - secondary) < 1e-6:
            # Ah, That Is A Round Button
            if height > width:
                dc.DrawCircle(width/2, height/2, width/2-4)
            else:
                dc.DrawCircle(width/2, height/2, height/2-4)
        else:
            # This Is An Ellipse
            if hasattr(self, "_xpos"):
                dc.DrawEllipse(self._xpos + 2, self._ypos + 2, self._imgx - 4, self._imgy - 4)

        dc.SetLogicalFunction(wx.COPY)

[docs]    def OnSize(self, event):
        """
        Handles the ``wx.EVT_SIZE`` event for L{SButton}.

        :param `event`: a `wx.SizeEvent` event to be processed.
        """

        self.Refresh()
        event.Skip()

[docs]    def OnPaint(self, event):
        """
        Handles the ``wx.EVT_PAINT`` event for L{SButton}.

        :param `event`: a `wx.PaintEvent` event to be processed.
        """

        (width, height) = self.GetClientSizeTuple()

        # Use A Double Buffered DC (Good Speed Up)
        dc = wx.BufferedPaintDC(self)

        # The DC Background *Must* Be The Same As The Parent Background Colour,
        # In Order To Hide The Fact That Our "Shaped" Button Is Still Constructed
        # Over A Rectangular Window
        brush = wx.Brush(self.GetParent().GetBackgroundColour(), wx.SOLID)

        dc.SetBackground(brush)
        dc.Clear()

        self.DrawMainButton(dc, width, height)
        self.DrawLabel(dc, width, height)

        if self._hasfocus and self._usefocusind:
            self.DrawFocusIndicator(dc, width, height)

[docs]    def IsOutside(self, x, y):
        """
        Checks if a mouse events occurred inside the circle/ellipse or not.

        :param `x`: the mouse x position;
        :param `y`: the mouse y position.
        """

        (width, height) = self.GetClientSizeTuple()
        diam = min(width, height)
        xc, yc = (width/2, height/2)

        main, secondary = self.GetEllipseAxis()

        if abs(main - secondary) < 1e-6:
            # This Is A Circle
            if ((x - xc)**2.0 + (y - yc)**2.0) > (diam/2.0)**2.0:
                return True
        else:
            # This Is An Ellipse
            mn = max(main, secondary)
            main = self._imgx/2.0
            secondary = self._imgy/2.0
            if (((x-xc)/main)**2.0 + ((y-yc)/secondary)**2.0) > 1:
                return True

        return False

[docs]    def OnLeftDown(self, event):
        """
        Handles the ``wx.EVT_LEFT_DOWN`` event for L{SButton}.

        :param `event`: a `wx.MouseEvent` event to be processed.
        """

        if not self.IsEnabled():
            return

        x, y = (event.GetX(), event.GetY())

        if self.IsOutside(x,y):
            return

        self._isup = False

        if not self.HasCapture():
            self.CaptureMouse()

        self.SetFocus()

        self.Refresh()
        event.Skip()

[docs]    def OnLeftUp(self, event):
        """
        Handles the ``wx.EVT_LEFT_UP`` event for L{SButton}.

        :param `event`: a `wx.MouseEvent` event to be processed.
        """

        if not self.IsEnabled() or not self.HasCapture():
            return

        if self.HasCapture():
            self.ReleaseMouse()

            if not self._isup:
                self.Notify()

            self._isup = True
            self.Refresh()
            event.Skip()

[docs]    def OnMotion(self, event):
        """
        Handles the ``wx.EVT_MOTION`` event for L{SButton}.

        :param `event`: a `wx.MouseEvent` event to be processed.
        """

        if not self.IsEnabled() or not self.HasCapture():
            return

        if event.LeftIsDown() and self.HasCapture():
            x, y = event.GetPositionTuple()

            if self._isup and not self.IsOutside(x, y):
                self._isup = False
                self.Refresh()
                return

            if not self._isup and self.IsOutside(x,y):
                self._isup = True
                self.Refresh()
                return

        event.Skip()

[docs]    def OnGainFocus(self, event):
        """
        Handles the ``wx.EVT_SET_FOCUS`` event for L{SButton}.

        :param `event`: a `wx.FocusEvent` event to be processed.
        """

        self._hasfocus = True
        dc = wx.ClientDC(self)
        w, h = self.GetClientSizeTuple()

        if self._usefocusind:
            self.DrawFocusIndicator(dc, w, h)

[docs]    def OnLoseFocus(self, event):
        """
        Handles the ``wx.EVT_KILL_FOCUS`` event for L{SButton}.

        :param `event`: a `wx.FocusEvent` event to be processed.
        """

        self._hasfocus = False
        dc = wx.ClientDC(self)
        w, h = self.GetClientSizeTuple()

        if self._usefocusind:
            self.DrawFocusIndicator(dc, w, h)

        self.Refresh()

[docs]    def OnKeyDown(self, event):
        """
        Handles the ``wx.EVT_KEY_DOWN`` event for L{SButton}.

        :param `event`: a `wx.KeyEvent` event to be processed.
        """

        if self._hasfocus and event.GetKeyCode() == ord(" "):

            self._isup = False
            self.Refresh()

        event.Skip()

[docs]    def OnKeyUp(self, event):
        """
        Handles the ``wx.EVT_KEY_UP`` event for L{SButton}.

        :param `event`: a `wx.KeyEvent` event to be processed.
        """

        if self._hasfocus and event.GetKeyCode() == ord(" "):

            self._isup = True
            self.Notify()
            self.Refresh()

        event.Skip()

[docs]    def MakePalette(self, tr, tg, tb):
        """
        Creates a palette to be applied on an image based on input colour.

        :param `tr`: the red intensity of the input colour;
        :param `tg`: the green intensity of the input colour;
        :param `tb`: the blue intensity of the input colour.
        """

        l = []
        for i in range(255):
            l.extend([tr*i / 255, tg*i / 255, tb*i / 255])

        return l

[docs]    def ConvertWXToPIL(self, bmp):
        """
        Converts a `wx.Image` into a PIL image.

        :param `bmp`: an instance of `wx.Image`.
        """

        width = bmp.GetWidth()
        height = bmp.GetHeight()
        img = Image.fromstring("RGBA", (width, height), bmp.GetData())

        return img

[docs]    def ConvertPILToWX(self, pil, alpha=True):
        """
        Converts a PIL image into a `wx.Image`.

        :param `pil`: a PIL image;
        :param `alpha`: ``True`` if the image contains alpha transparency, ``False``
         otherwise.
        """

        if alpha:
            image = apply(wx.EmptyImage, pil.size)
            image.SetData(pil.convert("RGB").tostring())
            image.SetAlphaData(pil.convert("RGBA").tostring()[3::4])
        else:
            image = wx.EmptyImage(pil.size[0], pil.size[1])
            new_image = pil.convert('RGB')
            data = new_image.tostring()
            image.SetData(data)

        return image

[docs]    def SetAngleOfRotation(self, angle=None):
        """
        Sets angle of button label rotation.

        :param `angle`: the label rotation, in degrees.
        """

        if angle is None:
            angle = 0

        self._rotation = angle*pi/180

[docs]    def GetAngleOfRotation(self):
        """ Returns angle of button label rotation, in degrees. """

        return self._rotation*180.0/pi

[docs]    def SetEllipseAxis(self, main=None, secondary=None):
        """
        Sets the ellipse axis. What it is important is not their absolute values
        but their ratio.

        :param `main`: a floating point number representing the absolute dimension
         of the main ellipse axis;
        :param `secondary`: a floating point number representing the absolute dimension
         of the secondary ellipse axis.
        """

        if main is None:
            main = 1.0
            secondary = 1.0

        self._ellipseaxis = (main, secondary)

[docs]    def GetEllipseAxis(self):
        """ Returns the ellipse axes. """

        return self._ellipseaxis

#----------------------------------------------------------------------
# SBITMAPBUTTON Class
# It Is Derived From SButton, And It Is A Class Useful To Draw A
# ShapedButton With An Image In The Middle. The Button Can Have 4
# Different Bitmaps Assigned To Its Different States (Pressed, Non
# Pressed, With Focus, Disabled).
#----------------------------------------------------------------------

[docs]class SBitmapButton(SButton):
    """
    Subclass of L{SButton} which displays a bitmap, acting like a
    `wx.BitmapButton`.
    """

[docs]    def __init__(self, parent, id, bitmap, pos=wx.DefaultPosition, size=wx.DefaultSize):
        """
        Default class constructor.

        :param `parent`: the L{SBitmapButton} parent. Must not be ``None``;
        :param `id`: window identifier. A value of -1 indicates a default value;
        :param `bitmap`: the button bitmap (if any);
        :param `pos`: the control position. A value of (-1, -1) indicates a default position,
         chosen by either the windowing system or wxPython, depending on platform;
        :param `size`: the control size. A value of (-1, -1) indicates a default size,
         chosen by either the windowing system or wxPython, depending on platform.
        """

        self._bmpdisabled = None
        self._bmpfocus = None
        self._bmpselected = None

        self.SetBitmapLabel(bitmap)

        SButton.__init__(self, parent, id, "", pos, size)

[docs]    def GetBitmapLabel(self):
        """ Returns the bitmap associated with the button in the normal state. """

        return self._bmplabel

[docs]    def GetBitmapDisabled(self):
        """ Returns the bitmap displayed when the button is disabled. """

        return self._bmpdisabled

[docs]    def GetBitmapFocus(self):
        """ Returns the bitmap displayed when the button has the focus. """

        return self._bmpfocus

[docs]    def GetBitmapSelected(self):
        """ Returns the bitmap displayed when the button is selected (pressed). """

        return self._bmpselected

[docs]    def SetBitmapDisabled(self, bitmap):
        """
        Sets the bitmap to display when the button is disabled.

        :param `bitmap`: a valid `wx.Bitmap` object.
        """

        self._bmpdisabled = bitmap

[docs]    def SetBitmapFocus(self, bitmap):
        """
        Sets the bitmap to display when the button has the focus.

        :param `bitmap`: a valid `wx.Bitmap` object.
        """

        self._bmpfocus = bitmap
        self.SetUseFocusIndicator(False)

[docs]    def SetBitmapSelected(self, bitmap):
        """
        Sets the bitmap to display when the button is selected (pressed).

        :param `bitmap`: a valid `wx.Bitmap` object.
        """

        self._bmpselected = bitmap

[docs]    def SetBitmapLabel(self, bitmap, createothers=True):
        """
        Sets the bitmap to display normally. This is the only one that is
        required.

        :param `bitmap`: a valid `wx.Bitmap` object;
        :param `createothers`: if set to ``True``, then the other bitmaps will be
         generated on the fly. Currently, only the disabled bitmap is generated.
        """

        self._bmplabel = bitmap

        if bitmap is not None and createothers:
            dis_bitmap = wx.BitmapFromImage(bitmap.ConvertToImage().ConvertToGreyscale())
            self.SetBitmapDisabled(dis_bitmap)

    def _GetLabelSize(self):
        """ Used internally. """

        if not self._bmplabel:
            return -1, -1, False

        return self._bmplabel.GetWidth() + 2, self._bmplabel.GetHeight() + 2, False

[docs]    def DrawLabel(self, dc, width, height, dw=0, dh=0):
        """
        Draws the bitmap in the middle of the button.

        :param `dc`: an instance of `wx.DC`;
        :param `width`: the button width;
        :param `height`: the button height;
        :param `dw`: width differential, to show a 3D effect;
        :param `dh`: height differential, to show a 3D effect.
        """

        bmp = self._bmplabel

        if self._bmpdisabled and not self.IsEnabled():
            bmp = self._bmpdisabled

        if self._bmpfocus and self._hasfocus:
            bmp = self._bmpfocus

        if self._bmpselected and not self._isup:
            bmp = self._bmpselected

        bw, bh = bmp.GetWidth(), bmp.GetHeight()

        if not self._isup:
            dw = dh = self._labeldelta

        hasMask = bmp.GetMask() != None
        dc.DrawBitmap(bmp, (width - bw)/2 + dw, (height - bh)/2 + dh, hasMask)

#----------------------------------------------------------------------
# SBITMAPTEXTBUTTON Class
# It Is Derived From SButton, And It Is A Class Useful To Draw A
# ShapedButton With An Image And Some Text Ceneterd In The Middle.
# The Button Can Have 4 Different Bitmaps Assigned To Its Different
# States (Pressed, Non Pressed, With Focus, Disabled).
#----------------------------------------------------------------------

[docs]class SBitmapTextButton(SBitmapButton):
    """
    Subclass of L{SButton} which displays a bitmap and a label.
    """

[docs]    def __init__(self, parent, id, bitmap, label,
                 pos=wx.DefaultPosition, size=wx.DefaultSize):
        """
        Default class constructor.

        :param `parent`: the L{SBitmapTextButton} parent. Must not be ``None``;
        :param `id`: window identifier. A value of -1 indicates a default value;
        :param `bitmap`: the button bitmap (if any);
        :param `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;
        :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.
        """

        SBitmapButton.__init__(self, parent, id, bitmap, pos, size)
        self.SetLabel(label)

    def _GetLabelSize(self):
        """ Used internally. """

        w, h = self.GetTextExtent(self.GetLabel())

        if not self._bmplabel:
            return w, h, True       # if there isn't a bitmap use the size of the text

        w_bmp = self._bmplabel.GetWidth() + 2
        h_bmp = self._bmplabel.GetHeight() + 2
        width = w + w_bmp

        if h_bmp > h:
            height = h_bmp
        else:
            height = h

        return width, height, True

[docs]    def DrawLabel(self, dc, width, height, dw=0, dh=0):
        """
        Draws the bitmap and the text label.

        :param `dc`: an instance of `wx.DC`;
        :param `width`: the button width;
        :param `height`: the button height;
        :param `dw`: width differential, to show a 3D effect;
        :param `dh`: height differential, to show a 3D effect.
        """

        bmp = self._bmplabel

        if bmp != None:     # if the bitmap is used

            if self._bmpdisabled and not self.IsEnabled():
                bmp = self._bmpdisabled

            if self._bmpfocus and self._hasfocus:
                bmp = self._bmpfocus

            if self._bmpselected and not self._isup:
                bmp = self._bmpselected

            bw, bh = bmp.GetWidth(), bmp.GetHeight()

            if not self._isup:
                dw = dh = self._labeldelta

            hasMask = bmp.GetMask() != None

        else:

            bw = bh = 0     # no bitmap -> size is zero

        dc.SetFont(self.GetFont())

        if self.IsEnabled():
            dc.SetTextForeground(self.GetLabelColour())
        else:
            dc.SetTextForeground(wx.SystemSettings.GetColour(wx.SYS_COLOUR_GRAYTEXT))

        label = self.GetLabel()
        tw, th = dc.GetTextExtent(label)  # size of text

        if not self._isup:
            dw = dh = self._labeldelta

        w = min(width, height)

        pos_x = (width - bw - tw)/2 + dw      # adjust for bitmap and text to centre

        rotangle = self.GetAngleOfRotation()*pi/180.0

        if bmp != None:
            if rotangle < 1.0/180.0:
                dc.DrawBitmap(bmp, pos_x, (height - bh)/2 + dh, hasMask) # draw bitmap if available
                pos_x = pos_x + 4   # extra spacing from bitmap
            else:
                pass

        if rotangle < 1.0/180.0:
            dc.DrawText(label, pos_x + dw + bw, (height-th)/2+dh)      # draw the text
        else:
            xc, yc = (width/2, height/2)
            xp = xc - (tw/2)* cos(rotangle) - (th/2)*sin(rotangle)
            yp = yc + (tw/2)*sin(rotangle) - (th/2)*cos(rotangle)
            dc.DrawRotatedText(label, xp, yp , rotangle*180.0/pi)

#----------------------------------------------------------------------
# __STOGGLEMIXIN Class
# A Mixin That Allows To Transform Any Of SButton, SBitmapButton And
# SBitmapTextButton In The Corresponding ToggleButtons.
#----------------------------------------------------------------------

[docs]class __SToggleMixin(object):
    """
    A mixin that allows to transform any of L{SButton}, L{SBitmapButton} and
    L{SBitmapTextButton} in the corresponding toggle buttons.
    """

[docs]    def SetToggle(self, flag):
        """
        Sets the button as toggled/not toggled.

        :param `flag`: ``True`` to set the button as toggled, ``False`` otherwise.
        """

        self._isup = not flag
        self.Refresh()

    SetValue = SetToggle

[docs]    def GetToggle(self):
        """ Returns the toggled state of a button. """

        return not self._isup

    GetValue = GetToggle

[docs]    def OnLeftDown(self, event):
        """
        Handles the ``wx.EVT_LEFT_DOWN`` event for the button.

        :param `event`: a `wx.MouseEvent` event to be processed.
        """

        if not self.IsEnabled():
            return

        x, y = (event.GetX(), event.GetY())

        if self.IsOutside(x,y):
            return

        self._saveup = self._isup
        self._isup = not self._isup

        if not self.HasCapture():
            self.CaptureMouse()

        self.SetFocus()
        self.Refresh()

[docs]    def OnLeftUp(self, event):
        """
        Handles the ``wx.EVT_LEFT_UP`` event for the button.

        :param `event`: a `wx.MouseEvent` event to be processed.
        """

        if not self.IsEnabled() or not self.HasCapture():
            return

        if self.HasCapture():
            if self._isup != self._saveup:
                self.Notify()

            self.ReleaseMouse()
            self.Refresh()

[docs]    def OnKeyDown(self, event):
        """
        Handles the ``wx.EVT_KEY_DOWN`` event for the button.

        :param `event`: a `wx.KeyEvent` event to be processed.
        """

        event.Skip()

[docs]    def OnMotion(self, event):
        """
        Handles the ``wx.EVT_MOTION`` event for the button.

        :param `event`: a `wx.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 not self.IsOutside(x, y):
                self._isup = not self._saveup
                self.Refresh()
                return

            if self.IsOutside(x,y):
                self._isup = self._saveup
                self.Refresh()
                return

        event.Skip()

[docs]    def OnKeyUp(self, event):
        """
        Handles the ``wx.EVT_KEY_UP`` event for the button.

        :param `event`: a `wx.KeyEvent` event to be processed.
        """

        if self._hasfocus and event.GetKeyCode() == ord(" "):

            self._isup = not self._isup
            self.Notify()
            self.Refresh()

        event.Skip()

#----------------------------------------------------------------------
# STOGGLEBUTTON Class
#----------------------------------------------------------------------

[docs]class SToggleButton(__SToggleMixin, SButton):
    """ A `ShapedButton` toggle button. """
    pass

#----------------------------------------------------------------------
# SBITMAPTOGGLEBUTTON Class
#----------------------------------------------------------------------

[docs]class SBitmapToggleButton(__SToggleMixin, SBitmapButton):
    """ A `ShapedButton` toggle bitmap button. """
    pass

#----------------------------------------------------------------------
# SBITMAPTEXTTOGGLEBUTTON Class
#----------------------------------------------------------------------

[docs]class SBitmapTextToggleButton(__SToggleMixin, SBitmapTextButton):
    """ A `ShapedButton` toggle bitmap button with a text label. """
    pass

#----------------------------------------------------------------------

from wx.lib.embeddedimage import PyEmbeddedImage

UpButton = PyEmbeddedImage(
    "iVBORw0KGgoAAAANSUhEUgAAAMgAAADICAMAAACahl6sAAAACXBIWXMAAA7DAAAOwwHHb6hk"
    "AAAABGdBTUEAALGOfPtRkwAAACBjSFJNAAB6JQAAgIMAAPn/AACA6QAAdTAAAOpgAAA6mAAA"
    "F2+SX8VGAAADAFBMVEX//////8z//5n//2b//zP//wD/zP//zMz/zJn/zGb/zDP/zAD/mf//"
    "mcz/mZn/mWb/mTP/mQD/Zv//Zsz/Zpn/Zmb/ZjP/ZgD/M///M8z/M5n/M2b/MzP/MwD/AP//"
    "AMz/AJn/AGb/ADP/AADM///M/8zM/5nM/2bM/zPM/wDMzP/MzMzMzJnMzGbMzDPMzADMmf/M"
    "mczMmZnMmWbMmTPMmQDMZv/MZszMZpnMZmbMZjPMZgDMM//MM8zMM5nMM2bMMzPMMwDMAP/M"
    "AMzMAJnMAGbMADPMAACZ//+Z/8yZ/5mZ/2aZ/zOZ/wCZzP+ZzMyZzJmZzGaZzDOZzACZmf+Z"
    "mcyZmZmZmWaZmTOZmQCZZv+ZZsyZZpmZZmaZZjOZZgCZM/+ZM8yZM5mZM2aZMzOZMwCZAP+Z"
    "AMyZAJmZAGaZADOZAABm//9m/8xm/5lm/2Zm/zNm/wBmzP9mzMxmzJlmzGZmzDNmzABmmf9m"
    "mcxmmZlmmWZmmTNmmQBmZv9mZsxmZplmZmZmZjNmZgBmM/9mM8xmM5lmM2ZmMzNmMwBmAP9m"
    "AMxmAJlmAGZmADNmAAAz//8z/8wz/5kz/2Yz/zMz/wAzzP8zzMwzzJkzzGYzzDMzzAAzmf8z"
    "mcwzmZkzmWYzmTMzmQAzZv8zZswzZpkzZmYzZjMzZgAzM/8zM8wzM5kzM2YzMzMzMwAzAP8z"
    "AMwzAJkzAGYzADMzAAAA//8A/8wA/5kA/2YA/zMA/wAAzP8AzMwAzJkAzGYAzDMAzAAAmf8A"
    "mcwAmZkAmWYAmTMAmQAAZv8AZswAZpkAZmYAZjMAZgAAM/8AM8wAM5kAM2YAMzMAMwAAAP8A"
    "AMwAAJkAAGYAADMAAADU1NTT09PS0tLR0dHQ0NDNzc3Ly8vKysrJycnIyMjHx8fGxsbFxcXC"
    "wsLBwcH39/f09PTw8PDs7Ozo6Ojj4+Pe3t7Z2dnX19fV1dXOzs7ExMTDw8O+vr66urq1tbWw"
    "sLCsrKyoqKikpKSgoKCcnJyUlJSPj4////+2FWUJAAABAHRSTlP/////////////////////"
    "////////////////////////////////////////////////////////////////////////"
    "////////////////////////////////////////////////////////////////////////"
    "////////////////////////////////////////////////////////////////////////"
    "////////////////////////////////////////////////////////////////////////"
    "//////////////////////////////8AU/cHJQAAIcNJREFUeNpi+D9MAEAAMQwXjwAE0LDx"
    "CEAA0cIjL9+8wwreA8GHGzdvvn1FA0sBAoj6HsHhCySP3Lx54y3VrQUIIGp6BOHkt2/fAgkQ"
    "BWKBIIpvQB76cPPmrVtUtBwggBio6o232AHYT9g8cvs21awHCCCqeOQV2LFg8AYI4Yw3EIDq"
    "KUTUfPhw48ONGzdvvaaGGwACiAoeeQF14hv8AN03sJgB+uTWS8pdARBAlHoE2QuvXwMROgAK"
    "Y/UNIqWBY4XiRAYQQJR55DVKVLzGBbDEDCL/gzwCipVbbyhyCkAAUeARhnfIkQEFr5AAVr9g"
    "ZBZY8gLGyh0KXAMQQAwUJyp4enqFCRD+wOsTSO0CKsTukO0cgAAi0yMvoXEBcj/UBy/BAKdP"
    "wKohHkHzDKSeBCYvkFfu3CGz2gcIIAayYwPuESRvQHyC8A5q0nqNvTBG88gd8mIFIIAYyPIG"
    "PF9APIHwBlqkvMYaI2jZHV4Mg3L87Tu373z8SIajAAKIgazoQIqNl+jg1UusKes1IotAPPMO"
    "pUKBe+Q2KFLI8AlAAJHqkVeQDA72BLLzX2CLEWw5nVCMgD1y5+NdUgtjgAAi0SMMkNhAigug"
    "D168ePHyBdwr8Bh5/QqSpJA88vYNlsYKvO2F4pG7JLoMIIAYSM8d0KwB9sQLKECKEeQkhdZI"
    "eYPWknyH3FRB9gfII9raJDkNIIAYSKvHkWID5PQXCIDFH8hewNLcIugR7XckOA4ggBhIiw54"
    "3niBCtB8Ac/bb1Gd/w49f+DwyEeIR0iJFIAAIt4jqJkDiz+QMjiW5jtKF+sthjdu3ECOD6A/"
    "IB4h3icAAcRAWu5A8sbz58+RvPEKFhuoTUMC4D0MQFvASP6AeoRorwAEEJEeeQHxCKysAnsD"
    "2SOocYElAeH1CKTshXrjzkeEJ0CAyCYLQAAxEJ2skHPH8+cIj4C9AfUDSsEKdiEo0dy4AaE/"
    "gGkogPoAzPhwA8Uj2nfvaWvfA3niHhDcv0+UEwECiCiPvHqDiI4XSB55DvHIKzSPvEM0ocBO"
    "vHnzBrgpdQNMQwGSnyCKbsELLIgHYOD+faKGXAACiIHIShASHy+wRser17BGFCLBQPpKt3EA"
    "oBTMUx8gnrx5E9o4+Qj1yH0YeAAERLgSIIAYiKs9MP2BiA00f0Dj4RY0oeAAt2/dhIAbN2AN"
    "X6hH7mqDfAHxyEMgAHmEiEgBCCAGwtkclj+QPAH2BixzQJMUpNcKchKiJrh3TxsFQAqju3c/"
    "fgR6BR45EIDqkfsPHiKB+/cJDk8ABBADUf6A5o7nyB4BF7pgf8DiAlip3UJUaCDnAMMSCdy7"
    "D0ky9+4BvQKPGpBnQMQduEdA+iAeeAQEEI/cJ1R4AQQQAxHFLjA+sPkDmqjgjXFg3YyICUji"
    "Rg5VkKdgHtHW/ggFEM8gkhxQ9z1wdDyCAVjyIuATgABiIMYfryGlFcwTkOwB8gckb0C8cQOY"
    "Xe/AvQHyxSMUAHTOQ0iyv/8AnMjA4ONHlKzzEeaRR48eP0b1yAP8qQsggPB65DW82EWKjhdI"
    "qQocG5BRkNug0LwHThQgRzx58gSEkQDIYZDUAk4qkMR2T/se2DcwcBfZIzB9MC/hbUMCBBAD"
    "3nIX5BFocYWZzaGxASpqQd74CMwVD+4/hHrk0yc8HnkEKVaJ8cinT48hAOQTfI4FCCAG/PU5"
    "tNh9jpw9oKUVJHe8f38T4gvte5DU9BjkgE9A8OQJukfArnkM9RA010ByDCyh3dWG1iHg4AAa"
    "8xkIIGaBteFxLEAAMeDr1cKrDzSPIOXy9+9h/rhPkkdAAQz3yD3cHnn69CnQLzCP4KlOAAKI"
    "AV97F8MbKMkKlMeBjW+IJx4+gqakT6BgfAq2/xM6ePzkMTJ49BCUo6ClGbyuQfbI56fPnj2D"
    "+AUUMkAtOJ0LEEA4PfICVn+gegQRHeDYAFZ+4LgA+wPsWFBiwOWRJ+geQSqWtWGeQfHIM4hH"
    "QMZBPIKzEAYIIAa83UGUYhepEgTX5MCyClRSgS0FpieoH6DegHgFDaB45BEsqwC9Am0fwuME"
    "JUYg4CkkTh7hihOAAMLjEfSM/gI1PkDV+B1gSQUupUBpCskL2AEuj8AiBb9HID7B6RGAAGLA"
    "X2Chxwc8e7z/cOs2MG8CMzg4c4M98QyREEj1CNAruD3yBQQgfgEZgd3FAAHEgCdhoWQQFH+A"
    "Cl1gBwiYOSB5A+gNmEfw+AWnRxAlMdg3cI88+fQU5g+YV0D1E1YnAwQQVo+ABz9eofkD5BFY"
    "sgL2HoCp6j44b4DLKaAznxHwCCjzI3kCpS0FihOYR2ANHFD5Ac7tX74geQVoypMb2NwMEEAM"
    "OHu2mAkLXpuD6g5QfEDyBtgjz5AAdm8g53UMj8D9Au9MgUsQsMFfkH0CLr6wuRkggBjwllio"
    "6QoaH8BkBWqkP3gEyRuQaoOwR5BLX2I9Ak5bED98/QpPX5+x+QQggBiwNrHQa3R4eQXyx4fb"
    "d7TB0YGoNJ49I+wRUCsSzSOPH6FkFEgjF+SfB+BWAqiR8Bnska8g8AXmlc+fsLgaIIAYsI63"
    "o3sEls9B+eMGMJvfv/8I4g+QC9H9gdUj4PgAtyMf48rwcI88gETKw8fApAtMW19APoB4BZq8"
    "Pj/BbKsABBADrhLrFaJ/jpQ/gOXuzdsf74IKXWgex4gPXB55/BjSniXSI+AW8COIR2BxAvUL"
    "0COYJRdAAGF6BNE0gXgEPNQOi4/3wNocWFxBK/KnNPfI40+QtAX3CMgrwMSFmUsAAogBd9v9"
    "BaLgBfcGgc0ScDUIbK+DyiqwD2jqEUil+BTJI9++QT2CWXIBBBADrqrwJUpGh+Tzd8Dq4yMo"
    "m3/+jCVrPMPlIVjRCy6qnyCXWQ9RAepYBdgnT4CJC+yRb0BPgDAkToCFMJrDAQIIq0dQcjrI"
    "I+BuLTB/3LoDbJU8fIzcJCHKI5CiF8MjDwl65CGoiAf7AxQdYACLEzSHAwQQA9a2InLKghVY"
    "4PrjHtAbj2G5g9YeAVUmoNz47BnQFzB/fIPk+GdP0XwCEEAMGOsA4IOKSCUWOKND8gcwPsCx"
    "QSePgGpFUHZHipFvXyG1CerqKIAAYsCaQxAl1gt4RfgB2IkCtdmffCIlNhAeQfR4cXrkPjp4"
    "+ADURQB5BOKP70DwDVJ2AbMJitMBAogBayPrJWwiB17yAitCYEa/B27JkeMReC8euWZHi44H"
    "GB55gOSRrzCPfIPm96coTgcIIAa8/ngBa2EBMwgwn2s/fAwdECDTI2hNFCI8Ago5kG3QKPmG"
    "5JNnKD4BCCAGtHEs2PDoC/hIA7jAen/j9kdg8xpcYIGrD9I8AvEKcR5BnlIAV4vAwh7ska/Q"
    "GPkOK7ueIjseIIAYcDROYJNqkBwC7NcCK/QH9x+R5RF4dgd55AmWihApg8B6JDAfgTzy6RPM"
    "I9AYgRXCyFECEEAMOAYcENM4kKYJsIEFSrFP0LoeRHsGtWbHEhsP4IOo2tr3kLwE9AnYI1/g"
    "eeQ7rBB+hpzdAQKIAXVGB9q/RfgD2nS/dUcb2B8EV0/098gTYC5BLre+QwphoE/eI1wPEEAM"
    "2AZO4D6BNLFAJdZHkEceQ3vR1PbIA3SPwABkzOwxMJdAWinf4QCcuJ49Q7geIIAYUFYvoXgE"
    "HCHgEusDqIcO6tgS0zDBUiE+RXRzQQM6qBkd4Yn7yHOg9xADKjCPfEXxyLdvX5B9AhBADBhZ"
    "Hckj4KIXNDAKGmqHeuQZGR7B1l/HVuyiegLqEWAj9RHMI0Cf/EB4BcUjAAHEgJmyXiKVWJAq"
    "BNg0gRS9pMQHZhOFfI8Aszty2vrxA5K4gGJw5wMEEAPy5BTKghlowoLmdKBHnjz5/OwZeR5B"
    "GpAnyyNPYM0UkCfAAJpLvsDHggECCO6Rd2gegUcIsAr5CGpSPyalwEKtEKEtLewNRiRfaGMB"
    "QK8A7X4CLYC/w3wCihhwEQxzP0AAMSAv8UPyCLwqBHoE2EdHH4klwyPYW74o0YHTI/AYQY6S"
    "7+CCC7ZkECCAGOCbJhCrTV7CIwTSK7yrDR0sGzCPPHr8FN0jsMQFixKAAIJ75C3SshnI8itI"
    "oxeUQ+6BapDPT2nikfvEeOThI8iwENQjP2EeAeV3qAcAAogBo68OA6+hHrkN9gh4sIEEr6A2"
    "tRDTgDBfPHoAy+dITSttrOAeqIMFHk2BeuQnEIB8guIRgABC8cgr5DWvSOOK90Ctd3CnkKzi"
    "F1wAo3kEPqqIUQdi9wh4NAUeIzCPgHqLUA8ABBADvMxCXY8M8gh4eg1YGd67D6oKn1HoEbTR"
    "E1iFTtgj4CUdj8GjKV+/wmLkJyyXwDIJQADBPQJelIy8mhpSh4Da7/cHgUfAQ3XIHvmJ5hGA"
    "AGJAVCJIWQS0eAnSyrp5CzR/AOuFkFuzo/XVHyGVVjg9gJiyBmUihEe+wzzyE8UnAAEE9Qgk"
    "RuAp6xWsdQIbWSSpDiHJI/dJ9Mg3mEd+gj0CL4ABAgjhkTcoMQLMIW9AleGdO/fAWY0Sj6As"
    "wyDTI6DRG0jHHeyRX79+QRMXzCMAAYSatF6hZXXwFMLDweGRxxCPQDMJ0CO/UDwCEEDIHkEq"
    "s2BzhaApBNCg+OfPz8gF0LkRij3y6MnTZ7AY+QUGP8FFMLQmAQggBpR6/RU8h0CbJ3dAzRNg"
    "M5qcCEFMkH9GHplDH/rB5pG7yACyjA3YcAR7BJLboR75jvAIQAAxQPYJw2Lk1UuklXGw5snj"
    "x5R6BBonZHoE1gT+DKsSYTECye5fwHuZAAKIATmvvwIvDH85hDzyA55JAAII5JFX72DdXPhW"
    "HMiygA/gWh3UYIQvziA1o8PXK0AXnj0CDU2DpjvvIVWG2shr4e8irURD+AU0CPEJWLeDPAJK"
    "Wb9//4Z75AuoKQ8QQAyQHehYPAJapgGdZhscHnkE8wgsRsBpC+QRUNoCCCAGSMpC8chr2Lzn"
    "jY/alHoEufhFNBbRa3TklPQRC7gLXmYB8shXaIz8+g3LJF8hLWCAAMLpEXB1ODg9Ao6R3zCf"
    "QD0CEEDIHoF5Bb7C4TYoSkFOgM9EP0VxJEkZHeERuCfgKQfqAbhHIIugYUtpgWIghzx8As7t"
    "sBgB+QSWtoCeAAggLB55jeQRUAOaSh5BrgjRPIIRE+geAY+iQosteIz8hlQlUI8ABBCKR14h"
    "e+Q9uPAFjfNR5BGUWh2xxow0j9wFj0eBGykoMYLkEYAAwowR2HJ3SN9wMHrkB6T4BZfAcI8A"
    "BBBmjMBS1gesHsEF0DM6PGHBhq0fIryhrY3sEVgxi3uLBkgePUZ+//7zBxQn8NYWQABBPPIO"
    "ESOv4WXWDaBHwEPIyKUWsR6B1SDwvjrS4kWwR1BigpBHwFsYwJn9GzxGEB75+hXoCYAAgnkE"
    "2oyH7zECNuEp9Ah07hDJIzBvoJa4KPsWcHrlHtQj0KQF9MYfsE9+/oB6BCCAUDzyGr51DZi0"
    "BrVHwD4BF8AwjwAEEGrSeo3Y9UWER55B1g3g8Aik4IUva0dZE4te76FsWoICBBvJI8+QY+Q3"
    "cowABBAss79FOoACusAM7BHQxNeTJ9gzO3oNjuyRzzg8AtmWh15zE/YIsCKBeOQrOLNDkxZS"
    "jAAEECJpwc7SeANdv/+BZI9gX+2A4g1oqsK7jQyPR56ieAQlRgACCOqRd0hngkD3hQxij/zC"
    "EiMAAYQcI8h7VHF6BGnxO3jFJ6618NAlG+j5A9GWIsUjoH0dD+B55Ce2UgsggJBiBHpiDkke"
    "eQZy8NPPWJb0w/IHcm1+D7Z1j5A/kD0E2UkGrEgQHgHXIpAogXsEIIBIjBHIWgykWAA5Fus2"
    "C1iyQktUcG+gOBgtMnB75AvCI2FhoCiBewQggFBjBHHGxCD2yA+sHgEIIJRSiwiPQOZsoB6B"
    "bBpC8QjKTiRQ/niA2EX1Eb4jlAoeCYN55DvEIwABhFxqgRMX3CM3buL2CHTaB80j2LZUITwC"
    "y+TYNiET45F7D558/gLzyB+ER6AxAhBAqDECLXwhHXaQR+6hegQ8OwDdaPEZXsIic5BXwiI3"
    "S+5+RHcs0QDFI9+gHgkDeQS51AIIIAb46XFIHnk7uD3yC5tHAAII5JH379EyCcIj0LYWbP8U"
    "pJcE3RaGyBJI6+MeIQ3xwuYI4ZkcvsGYLI/AxrWwewQggLB6BLp4HNyxgux1efIZaYXlpyeI"
    "XA1eKPMJfTMq8oAi1CPwndJI275vI9PIAHN/OCizY/cINLMDBBA2jyDnkfvQzaawBjksMp5A"
    "Vy09hq1eQp3qROlGwQtdbG7GCjA9AgrSz8/QPIJcagEEEMgjHz6AG/JvkU/GweqRxzg8gjb9"
    "QSuPPH2GUmihegQggEAeuXHjPSJGIGcsImLkATaPwNIUcnJCzhtIc+hoGf0WmR4BOQSvRwAC"
    "COYRpBh5gxwj4GHwx5B2E8wjSKXTE/SNRrBMjt0joEMrbkKObYKd+QDn4/YISCvII5AZK5hH"
    "/qJ6BCCAEB55+xblFEWwR+5CVoI8eoxR12FLUihrAWDL+rTvIkUIzPmEPILsIUgzHlR8QmZ1"
    "f/78/RvkjbC/KB4BCCAkj6AeVzR4PfIL6pEwlNYvQACBPPL2xof372Dn42GNkUeYrQ80jzxE"
    "XwsA750jGia3iPYITAzmkbughVZPEFkE6BEggHsEdL4QQACBJ3pgHsEWIw9I98hDengEkrQg"
    "HgFtHQMIIPDU201QAYx2GBnYIx+hS1oePcaanLAUubB0BWu4IycrVIdiA+gegXgGWPiCVoyB"
    "Gyg/gLUIMKuDIgSYtKADdCA/AAQQ2CNv0TwC2XM/+DzyFegRYIcdVPZCkhbEI/dAfgAIIMj0"
    "9I0b75DOHX4HPXXmNvhAovv3ifUIYq8XbNgH4pHb6B65CT0uiDiPgEa1QEvfnsJSFihhgWME"
    "OmQK9gJAAEE8chNaACMfKwXxCOTcGFiVh1ZCAfmwA2VQd6whJqM+whu8EAfCPQIHN5EOEUKu"
    "Z9A98ukpqBaBlllggOIRgACCeOTWzffwo6wRx9feAh+4AszvuDyCc9UrYkrtI1LLHZGkcHkE"
    "S+YHZ3XQoprPsIEHSA75C2o0QtqMYC8ABBCyR6Bn3Q1Kj4DXPcA8AsnrYdDReIhHAAII4pHb"
    "N99DowQ5Rm7eAp8+Q5RHkFa430ee+CfPI0ieAWf1Bw+gUwo/4P6AeAQRIwABhOoRlPPhPtyE"
    "nT/z4BHK2UoYu3EePMBYIwOZHQd105EPB8PmETSAnv3BHrkPWpwJKXxhKQvskZ8/v8M8AhBA"
    "0KWAtz68Rz/mDnQiECi7Yx4Shc0j97F4BOUcrdtopS5ejyB8BDpY6R6sLwIss+ARAvLIL6BH"
    "oP74DxBACI+8H7QeAc26QZrwP9E9Ak9Z/wECCLZc9gb4mD5Uj3wArTu7izgoi2KP3CLdI6Dj"
    "f0FbosANRmAl8geRRUDVIdAjUA8ABBDCIx/QPPIe6hHIli3YeVk4PQJfhww9mRCllQXxyG28"
    "MQIVRDqXDnIMHGj3PKydBa7V//799w9cH0Jmp6EeAAggmEduQqLkPeoxkLfAKfQ+7OwCLB55"
    "gLwQGb3o/Yg+AnQLe8GFnMuRPAECYI88fPIJNDQHap6A4+MftIGClLL+AwQQzCPA2hYeJ6ge"
    "gewPGhiPQMZPgA1fWDsLWqv/gzQZkT0CEEAwj7wGtRs+YPHIHegio4HxCHiKB7ya8Ru0efIX"
    "krJA9Tp4AR3s9AeAAIJvhIF6BHFMKugkSJhH7mH1COIwAGj/4x6isYh8vhzpHrmF5BHQgnb4"
    "dMIfcA4B+gTuEZj7AQII7pGXt24Am46oHgHXq5BFRg8wt2yjbq1FWdGHPOmMfh4j3uoQ6ido"
    "pQ46ZQk2MPcdXBn++QuPEXB//Tt8LzhAACE2i4Fs+PAByRvQenUAPQLOIeDKEN41BOcPcBaB"
    "eATufIAAQvPIDZRjUgfaI5BxObS++r9/GE14EAAIICSPgK1A8QjFSQsph5DgkZtIHrn/4PEn"
    "xKwIPGHBPPIV7nyAAELa4opixU1Uj4D3Bz1APgsTzSOoa14hKxswJmpvY+vlYsn04FEHcB1y"
    "7yGkQwXpq8NyOqzBiBQh/wECCMkjb2C2wAIFfkzqXWhNQiePwIZPgBHyALRJ4StyDoF4BNqn"
    "QrqtCCCAkLeBI/erERNiA+URyJzIk2dIs1Rgb0DKXtDCeOQI+Q8QQNg8ApuuRHgEujMbejTG"
    "A4wDM5A6U9DGIopH0FrAmL7B9AhkcufBY8hUAqwf8g85Qn4g5ZD//wECCOW0AcgwMyI2oCUP"
    "4nRqSKMLwyMYK1/Rl8qgD8Pj9QikAgGdjX3vwWPQpj3QeiDwkAMiQiApC9nxAAGEcnjFR5TJ"
    "YvhCaGSP3Id2T/B5BHPNDwkegd4MA56jevDo0xfYwDU8Qv7B+4bIEfIfIIBQjxOB+OQOymH6"
    "8PMssXoEY58XhR4BV16QLvZ9YFsRntHh3vgHrUNQc8j//wABRIZH7mN4BDOfgzyBaGlh8Qjm"
    "wANafNwFpqtPT8HbE8ATCQiPhGFUhiAAEECoHnmFurQTiyfg+QTLhjXkpa8YGR2nR9CrEHj+"
    "gC3qB/cLkfwB6at//4Z6QwlAAKEdgvQRzSNIp7fTxSO34Kua7kHbWN9gjUUMj6C6HCCA0I+l"
    "+oh0OLU2Yhct7T0CHf25A11mBl/SD+mnI+cQzDoEBAACCJdHPiJ5BOMgHMiR4/dx78Mh2SOw"
    "MTnQXUOgMIQMkaI1TVAqdXSPAAQQxtFt0PXcd7WxnJeOs5GI6hFEoYVtwQxamYXaRQerBk2K"
    "f0LsTPgdhih54c13dH/8BwggzMP0IO5AHDaONMhOO48gJqfAM7jgcSzINiR4mxeWsMAR8h3D"
    "2QABhMUjd1E8gjwqSmCPF2UeuQM9Ol8bMtiAWHONHB+w8V6MCPkPEEBYjjeEegR6EDLaIAPS"
    "FAjGpmdUj9wh0iOwDsNteBnzCFaB/ICOLP5D8gikxMI8lxUggLAdponYxgiadUOMMKKMV9+7"
    "By/N7uGs1WHewLLkAbtHwIetQ3flwjuF/9Bz+ncsrgYIIGyHsqJ6BPVMffTBd/weuXOHoEdg"
    "s7fQchc00fcZsSnsdxhKhIBnDX9gSVj//wMEENZjclE88vgxxuo+KnsEceUTaFUVYkvYb8gU"
    "wj+UEgtplBQFAAQQVo+8gx8Sg1gb9Amydw1+SwJyvifHI7cQMyCwy8RA8yCgmSl4/kDK6OA2"
    "FmS09/sDbG4GCCDsR0kjTj0HH+j8CXbI+JMnj6B7KJDzPMGWL0aFCOKjRgh0hOMxJFl9A+/a"
    "AY9iIWUQcImFI0L+AwQQjsO9YUc6o3jkE3wP9EPI0fWUeOQ2fAIXkjkgu6DAhx1Bu7ZIFSEi"
    "YX3H4Y//AAGE67h1VI9Ajrx+irjoALbukiKP3ILHBviAioefwIv4vyIlK4wCC1d8/P8PEEC4"
    "PHIfzSOwjSGwFZqw9IXNI1hHHrCs+kFawa8N3ooLPcPlB9JgHIo/fuIosUAAIIBwXknwCna6"
    "IJJHYFvZIIeDQCd4EPsQULYbYQ6hIHkIedkypBEBqs1hh+r8xOYPaA2C85pEgADCfUkE7OhK"
    "8ImG4PPb0XYXwjd6IjwCm829i3YJDzaPwLs94PmXx+D14pBzT37BVjcg1ejQhPUdp3MBAgjP"
    "tR1vUT3yBePYc6hvwK0w1ObKXcLbRO6ANuDCLk158gmSqr5BvIESHdBRE/B84U3crgUIIHwX"
    "qUCP2CbkkYcPHiDvECHdI4/hhe53aLGL7A/48A/u/AECAAGE97YYuE+QPfIV5pmnzz6DffMI"
    "tLQG+QQd5Fndj2h77D9CW7iQQT/QQWog0+HHsmHxxl9YfKCOY6EDgADCe9nQW1jaeop8Dv1X"
    "+P0AkLs0oDeJoHpEm4BHYMd7Qq4dgJ7c8gOy6egvarkLrwjx3rMNEED4r396CfYI9LQz1MPC"
    "vyLd3PD08xPIlRqImNG+h3r1HOo1dNCblT5BDlP/ijiS4jdqdKDEB/5r3AECiMCFXK/AJ+5i"
    "9QjMM89AaQy6vhmxAO0+zi4y9BRf6PGuiAPZfkL3tyBnc0i5CzmkgsB19AABROiKtFcPERdo"
    "QDzyDQy/Ih+t/wyxnwferHyA1E9G6SxDDiP+hBIb3yHe+I3uDXC7hJj4+P8fIIAIXlr3EhTG"
    "jyFH1UKjBH7K9jdErCBOE0C6swoLgLYVYLdYQI+M/QFfJ46azcMgWw0Jx8f//wABRPgawbcP"
    "IZ0SqN1IB59Dj3FHzf6Yp2CjAHhRDj+/F5yowN5AzuSwZAU9juY2QWcCBBAxVyaCeyVPYCka"
    "2R9wv6B4Bt6SwQKewiMW2RvQ1e5///1F8wc0fxDhSoAAIuqqzbfQVI3shm+gA4S/w49A/4Za"
    "mH3BdnDCly/IiRNy4iLk+Abomh+UVAXb54K3PkcAgAAi7vLTh5BbOuDZE3rONtwj0JOEkX2C"
    "4RlobQoPBuj5fjCPoFYefyEr339hHYvDCgACiMjraF9BbqqCHBeOODAcfmQt7KhqlOSGARDa"
    "kP0AXYEF9wWkTQI79eQbkdeCAwQQsRcEI100g8UjsKOEkbzz9RumHyB6fkBOWoQe3PAHtq4a"
    "qcyFeQR8fhaRDgQIIOKvbIYcAwqtwr4i++QHGKJEz3fUAuE7TC3cD6BaA7Kd5S960yoMsi36"
    "J/jcVaKdBxBAJFyi/Qjhka/QvA51G8gjP9Di5zs6gJ6lCvEGzB+QxeF/kapAcNvqN+yoPOJd"
    "BxBApFxrfgN8zwVG6vpBGPyEHUkI8QJ0jxRkkeU/aKH79y+syP0Fi44HJDgOIIBIu2getAkU"
    "uTZB9wfkHEgQjeR4mA9+wX0B8QfUIyj+QNQdxOcOCAAIINI88p/hyZPPn5EbK3Cf/EQFv0AQ"
    "Dn5Dj8j5DfMDNElB4uMv3BPgEhfStvpGossAAohE5f/fPv70Ca12/vEd7hOQ85HCH+x8mB+A"
    "vvgNjwpYbCAAuKQCZw5IYfWBRIcBBBCpHoGkL/AwF6LtivAJcixAUxH0VAOUmEDyB3jbF7T6"
    "gzQQYXt0SAMAAUSGR/6De4xPUS4FgfoEkZx+wz3yB8Uj4M1Rf5E8A/MGOIuD8zipuQMCAAKI"
    "HI9AMv0XRHPlO1I9hxwhGB6BhD/CA2GQjAE7vQxyqvI3spwEEEDkeeT/68+fUdriKBU2wiPI"
    "XglD+CQsDO6PMMg5Lb+gp8US3yRBBwABRKZHgAB25yJynYIovpD8ghIvcACVg5xSCEtS5GQO"
    "KAAIIPI98p8BmrzgNT2KV5ALXah3fv9G8gHEDxBfQK8YILnIRQYAAUSBVtCMEOKWP6S2OXKs"
    "IMcMqg+gyQnhi1sUOQUggCjzyP//z56h9ZZQEhhycYwKYIco/4Alqm8UOgQggCj1CKivgiWz"
    "fEdqtGABiGsFIM3k15S7AiCAqOCR///fQHqAX7H0ubA1IVH6MEAtb6nhBoAAoopHoKXYl2fw"
    "zI8xRIHomKD2jqlmPUAAUc8joPzy7BnqfZLfcACYPBUtBwgganoEAu48RR0xwQq0qW4tQABR"
    "3yPALHMbv0fuvqWBpQABRAuPDAgACKBh4xGAABo2HgEIMABb8EQbIiGeqQAAAABJRU5ErkJg"
    "gg==")

#----------------------------------------------------------------------
DownButton = PyEmbeddedImage(
    "iVBORw0KGgoAAAANSUhEUgAAAMgAAADICAMAAACahl6sAAAACXBIWXMAAA7DAAAOwwHHb6hk"
    "AAAABGdBTUEAALGOfPtRkwAAACBjSFJNAAB6JQAAgIMAAPn/AACA6QAAdTAAAOpgAAA6mAAA"
    "F2+SX8VGAAADAFBMVEX//////8z//5n//2b//zP//wD/zP//zMz/zJn/zGb/zDP/zAD/mf//"
    "mcz/mZn/mWb/mTP/mQD/Zv//Zsz/Zpn/Zmb/ZjP/ZgD/M///M8z/M5n/M2b/MzP/MwD/AP//"
    "AMz/AJn/AGb/ADP/AADM///M/8zM/5nM/2bM/zPM/wDMzP/MzMzMzJnMzGbMzDPMzADMmf/M"
    "mczMmZnMmWbMmTPMmQDMZv/MZszMZpnMZmbMZjPMZgDMM//MM8zMM5nMM2bMMzPMMwDMAP/M"
    "AMzMAJnMAGbMADPMAACZ//+Z/8yZ/5mZ/2aZ/zOZ/wCZzP+ZzMyZzJmZzGaZzDOZzACZmf+Z"
    "mcyZmZmZmWaZmTOZmQCZZv+ZZsyZZpmZZmaZZjOZZgCZM/+ZM8yZM5mZM2aZMzOZMwCZAP+Z"
    "AMyZAJmZAGaZADOZAABm//9m/8xm/5lm/2Zm/zNm/wBmzP9mzMxmzJlmzGZmzDNmzABmmf9m"
    "mcxmmZlmmWZmmTNmmQBmZv9mZsxmZplmZmZmZjNmZgBmM/9mM8xmM5lmM2ZmMzNmMwBmAP9m"
    "AMxmAJlmAGZmADNmAAAz//8z/8wz/5kz/2Yz/zMz/wAzzP8zzMwzzJkzzGYzzDMzzAAzmf8z"
    "mcwzmZkzmWYzmTMzmQAzZv8zZswzZpkzZmYzZjMzZgAzM/8zM8wzM5kzM2YzMzMzMwAzAP8z"
    "AMwzAJkzAGYzADMzAAAA//8A/8wA/5kA/2YA/zMA/wAAzP8AzMwAzJkAzGYAzDMAzAAAmf8A"
    "mcwAmZkAmWYAmTMAmQAAZv8AZswAZpkAZmYAZjMAZgAAM/8AM8wAM5kAM2YAMzMAMwAAAP8A"
    "AMwAAJkAAGYAADMAAADV1dXU1NTT09PS0tLR0dHQ0NDOzs7Nzc3Ly8vKysrJycnIyMjGxsbD"
    "w8PCwsL39/f09PTx8fHu7u7p6enk5OTf39/Z2dnW1tbPz8/Hx8fExMS/v7+7u7u3t7e0tLSw"
    "sLCtra2pqamlpaWhoaGdnZ2Tk5OPj4////+ZlMjzAAABAHRSTlP/////////////////////"
    "////////////////////////////////////////////////////////////////////////"
    "////////////////////////////////////////////////////////////////////////"
    "////////////////////////////////////////////////////////////////////////"
    "////////////////////////////////////////////////////////////////////////"
    "//////////////////////////////8AU/cHJQAAIMRJREFUeNpi+D9MAEAAMQwXjwAE0LDx"
    "CEAA0cIjb+9/wQE+g8GdNzSwFCCAqO8R7S+4AcQjz549+0B1awECiJoeAbr0KwR8QwNQ4a9f"
    "viK8A/IPFS0HCCAG6nvjGy4A8Qsibp5R0ysAAUQVj7yFeeA7CPzADr5DANRHyL6hSpYBCCAq"
    "eOQ1NBJgfviJDSB7B9Mvryl3BUAAUeoRkCcgPgA59xcY/IYBKPcXlPEL4Smwb6ApjTr5BSCA"
    "KPPI7a+QqEDyxm/sAMUrkJhBRAzEJ+8ocgpAAFHgEQZIbEAiA+aFP1gAmm+Q/PIdyStAvzyl"
    "wDUAAcRAYaKCxQXcD2FQgN0zEJ/8gmYaSLRACmWwTz59Its5AAFEpkfewjwBiQhkH2AArL4B"
    "e+Yn3C9wrzz9RGbGBwgg8jwCLmrh/vjzG+6Pv38x/QH3ye8/6EkMFiuIbP/06acnZDkJIIAY"
    "yEtU4OgA+QIRFX+hANU3KMkLwyPwAgwSJ1/AcUKeVwACiIF8f/z8hUhSf+EewZmuUPMJwiff"
    "kYtisFc+PSHDJwABRKpH3oN9AU5TUE/8hccFqk9gSQqpCEb4AZhHEEUxwi/w4uvTk7ckOgwg"
    "gBhILXLBsQFJVMgJCs0bEF/AowAlIqBegBbDP38gl8RfYXn+yRMSXQYQQAykZnJQdPxE9cY/"
    "NH8g/IDi8p+/sLZdfqK0XJCS10eSnAYQQKR45AHUH6BkhYiMf3CfhCF7A7VVgtrgggHUNhi4"
    "wQZtf4Gi5Mnj9yQ4DiCAGEiKDkgWB3kD4oV/QAAkkOMCWk0g3P0dJ0BvGyO3WUDZ5OPHx8S7"
    "DiCAiPcIuAqEFLngDP4PCv6iegPqD2TngZ0IcymssY/mG1gTH1Z4gTP8ExJ8AhBADERHByyT"
    "QxPVP2SPQLwB8gRSM+o7om+I6Dti6XvBOipoLWJQgwWYvIjNKQABRKRH3kBzx29o7viH7A+E"
    "N34h1QxInQ40gOad78jRhewRcJx8JLLJAhBADMQmqx9IeRzNG6AkBU5OP38gJw945xwToHoK"
    "s3ePVJ98fPyIKCcCBBBRHrkJblhBklUYkjdAHgHFBjQygHEBb2wgjZigAQzvYHoFphvqEaLq"
    "RoAAIsIjDLBk9Qc1OqCJCpIzIG0mtM44sN0EA6D0DgKfPoF4yB5CpDZknyB55PHDh0S4EiCA"
    "CCu5Ayp24f74h5bJQakKxRufEZ749AnmfBj4+BHmmWdP4V4BewSRyBCtLkh18vHjo0dERApA"
    "ABH0yGtoskLzBiRRQWMD6At44wKcRUHWP34MdMCjx1Dw6NFDMICIIHkI4h+UYgAx+gWu4Z8A"
    "dT98RcidAAFEyCOvv4JrD1CTBCNZwWMD0rSApgWgHz5CHf7gIRw8eKCt/QAI4J75CE9qsGQG"
    "jhiwP5A9AiqCifEJQAAxEPIHuDaH+AM5PqB5HJKooNnzKahdAcycIGeDgPb9+/e1oeA+lA3x"
    "DCyqQDHzCZ5jMIdXIb2Tj2AzCfgEIIAYCPkDXO6CmogYhS4oWaGkKpAvQIEHCn2Qw+/fQwUw"
    "b4Hj5REk4YG9AvcLFq88hcQJMHBe4nUqQADh9cjtb5DaHCV/QH0Bjo1vUF+AG6tAy8Bhf+/D"
    "h7tYwYcPSB56AE9o0BwDjhp4/v8ML75B8Qz2iDbeHA8QQAx4Ox+g/AFuW6FkD2juAGcOaPcU"
    "6A9QTECiAe6ROwgA8woIgLxyHx43sHhB9clnRCEO8shHcDbD51iAAGLA274CxQd6sgLXHeCy"
    "ChQfkAwJSsTALAHyA9gbd7ACRLyAE959aLQ8APkFmA+eIOeXz5+RYwRUBIMyHh7HAgQQA/76"
    "HJQ/UMpdSFUOzh3gsgpS1kP9AQlwiEduAwEO34CTGNgrD6A+eQgrxz49hZfI6B4BlSF4EhdA"
    "ADHgaV/B4wMlf0Cyx/fvsMwBzhv3kSPiNgzgiBdEXrkPjxpwZnkMTWEIvzxD9cgDbZzOBQgg"
    "BtztXUj9gdJmh5ZW4OiAduQ+QiMD5I3bIE+A8K1bt+AeuY3qr9tYvAJOYw8fPn70+COibgH5"
    "5RmGR3AWwgABxIAnf0Drc5RS9w80WX0Fd36ePIHljbsQN0OcfQvqETSAGScwz8CzPbAyRYoV"
    "aGMNVDvBPKKNK04AAogBd8ICtq8w88fv3z/h/ngKzOQPH0CLqTsIP9zC6RFISYbNIyCvQD0C"
    "9gqkcQlvbhL2CEAA4fAIJF39Rs0f8GQFzh6g3IFIVLehLqfEI+DyC1pPPoG1YD6hewSHTwAC"
    "iAFnR+rXL5QKBNpIBPsDVOg+BRW52veheQPug5sgQIZHoMnrEaTKh9UsiGYz3CNA1VidDBBA"
    "WD3yECmjY40PUO4AZg5tSN4AxwTQ9TeRPIKIHjSPwCpGFI+APXMftVn5Edkv4Kb0Q2jTB+uM"
    "EEAAMeAYaQB5BDNhgfIHqFECKq1AbUJ4soL6AArI8sh9FI+gRspHhEdAWrC5GSCAGHDUIKCM"
    "jlzugvseP0FNRFChCMod4MwBzhuguLhJBY8g2soPYG0XKEDzCDafAAQQA9auLaRGR4kPcN8D"
    "lK6AzfVPjx6BcscdaJUBcvsNIMDvEUQjBbdHkDI+oq2PxSNYXA0QQAzYWibf0Uos5PzxGZKs"
    "7t2DJ6pbEG+geQSt9AJ7A5rREQC1kY/iGVgqewjrZz4CFfWwngHm1DxAADHgLrHgHoHWHxB/"
    "AIvdx6D4+HAXXlRh88gtDI8gSiyiPAKNFrhHwDGC6OJgOBsggDA98h0to8PKK2j++AT0hjYi"
    "WdHQI7BOC9xDeD0CEEAYHvkKGmv4jc0j0Ph49PA+MFkBqw6QD2jrEaTOMaTfD/fIB4zlRQAB"
    "xIC15AV10VEqQmAGAeePT6Dy6sMHSNWBWlRhAuSMjuhoIVeH2DI6LgCqDe/d/wDrK6D7BCCA"
    "MD2C1saCNhR/gJvtkPwBKnbhtTjVPQJLTsiegMmBm3XYPQIQQAwYEYJaYkEL3h+gZvuzp48f"
    "AePjLqxgpY9HYKMYaN3ou2g+AQggBrT1SmCPICIEWCeC+ufQgvcTqHV1F+aRm/TxCCRLwPR8"
    "+ADrvn1A7ZoABBADZtH7+88fhDf+ghvuYH8A+wWg+hzctoJn8Zuw2hDKhtCYDWBEpx0tj9/D"
    "VVIhxwbcI0j90Lt3UZwOEEAMmN1bpN4UrAcC6p5DK0KER27g8wjWbhVsIIUWHgEIIAbUovc7"
    "aFQR4Q/IQAMoo3/+DOrUgrqCsMYHvT0CH9dAJFdktwMEEANKI+v7D2SPwFq830EZ/Rmocw5q"
    "mMAqCBp55AEyQPIIbKQMXg0DTUR2PEAAMWCOYyEnLFBGB5dYT8G9c1D/A+ILRDUI9QQyG1Yj"
    "3kZt+0LyKJo/wIN1yB6BVH2I0WO4PyBDF7eR6to7SI4HCCBsHoE236FVOmjEBFyjQzpStxGl"
    "FYpHYHykyv3mLbRyC5y0sXkEpfkO9QiIBqcuiEfgIzI4PAIQQAyoI71Iray/0D7IN3CJ9fER"
    "pCN1h0iPoDTnyfbIA2SPYJT6t24jNYIBAogBtTJEamWBPQKpCr8Am4qgQbh7d+8gN0zo7RFE"
    "zwdq561bCNcDBBAD8uollI46KGGBRqpBTRNgifUA2FT8gPAHiuPRPYAIMrS+IcQjiCFT1DHg"
    "Bw8Q00JwH92HjMRCcjnMvvdAAPbIbbjzAQKIAaW5CBoihfgDOsb7E1r0gsevQHX6rZvEewSj"
    "Zgd5hSiPIE90ARM01CMQ295j9whAADGgDMkhWieIzhS4afIAUhUi0hW5HrlLoUfeIwFQ8Qh3"
    "PkAAMSAmPb/B50Kgy0sgHgH20UFDP/dBVeHNQeURkE/gDS6AAGJA6YjAptKho7zg3u3nZ8Cm"
    "yX1wZ+r2zZsEPQJlwyotcMUFrgthnSrwJArqMNAD1J4gEgCXwCAdoLyO8MY7EAAnL3iUAAQQ"
    "A7zd+/07Yk0AzCPfIW2sx5ASC1uDF8UfSBzkLiLK4PUHLDU6Po88gLR/7+LyCGypCkAAwTzy"
    "5Su0ZxgGS1h/oK1eoD8egUqOO7ep4pF7pHoE0sHF4hGwV+C5BCCAGFCmEf4gLRaFdW9BvXTI"
    "YNwg8cg7BADGCcwjAAGE5JGfSCv84K1eUB0CbCwCPXIbI6Oje+QGmkduIvVKwM2su9jG5Qh4"
    "5OGDh2CPAH1y8waaP5A9AhBAGB6BLYiD1iFfwHUIMECI9Qiemh0xcII8UoLkCUyPgL1yHzTo"
    "APII2Cc4PAIQQFCPfIGNv4eh5JAv0FYWpIVAVY9oYxu7wuIRcMF1HzwgCOw5oHgD7JWb0DoR"
    "IIAQHvmJWOYHnwkBeeTxQ8g476DzyFsUjwAEEAO0zEKMnsDWZwD7IV8hleF96DjvLSweQfYA"
    "No/cQp47BNUhmLNU0LYVzOGP0QB4hh1UlyA8AvbC27dg6ga05QgQQHCP/ED1yK9fkMrw0xPE"
    "gDWucRNSPIIx3Qavw4nxCHIOgXrkPdQjAAHEgFSLILIIZKwXPHLyGBStd2jvkYdY/IBY6gVM"
    "FUgeeQvyBRiA0hbEIwABxABtwiNG4BGD1sBa/dPHR/dAzfdB5hG4P4A+gXoEIICQPQJb7w4b"
    "AgJ2qIC1+r170CE5DMejd64w2l3o8yMf0DtTyHn8MU4AHodHeOQtMgBmkptgLwAEEGaMQBZc"
    "QponcI/cun0Tt0ewdhexllqwihBzyuAR0R55i90jAAEE9oj2V+gII9Qjf2DNk6fQ5glmsqLY"
    "I+i1+WNyY+T9DfBSG4AAYoCVvlCPQBa5w9tZ8ObJ4PEIeoy8fw/OJAABBPLIW3Dp+xvukT/I"
    "XVxt1PbiLbTJT6weuQGfAbqJaGtBV2ppQxYHaD9E8gg+X0BmD0FDH8DgxPQIuNwC9a4AAgjk"
    "kfvQagTNI6AuFcwjt28htWixVYqoNT2qR+7APIKeyR/AKsLHBMAj8EIqYPsXu0dAaQsggBjA"
    "G7i/ocYIuPAFLZsBDZ7cvYuY9rxFcF4Eq0dgjXik5ZlEFLsoiQu06uXObSweAWX3G0BPAAQQ"
    "wiNIMQJtMD4bSh4BCCAsMfIHPnoCbjDexVjChJxXiPUIYi0j1COPEEtmHxPjEaBP7iJ55A0Q"
    "oHgEIIAwY+QP2CPg6hDa8kX2yE20vEJ4zgoxwXPvPmKRGaKRi83hH8GruSH0RyweAXnizds3"
    "8HIL6AmAAMKMkT+IOcNPj6jmEdS1pYTqQEIeAUcINE6gHgEIICwx8hvWhB+0HgH64A3cK1CP"
    "AAQQlhj5DW3Cg/oiMI/cQvYInE3IM7Chh7uwkSz4gnIsHvkIBY+hK2c/IglgeOQNhkcAAgji"
    "EaQK8Q9s+QxoTgQywnjnDmKdD7JHcJZk8AVo0KoQuvpaGxYbWKLjI7K7Hz9B9ghY7CHMI8gp"
    "C9kjAAGEyyPg6hCLR5BpfB5BDKBAWr3Ia0mxZXLEKrOPH1HZaB6BxchrIIB4BOgVoCcAAgjT"
    "I78Ht0dQUxbQJ6AOCtATAAGE6pE/UI9A1gcAPaKN7hEYuIW2cAbDAyD6DswjiGQF8gCqR2CO"
    "fYILfAQvYAZ55A5KjAAxNG2BPAIQQMgeAUXJHzSPgGZFsHkE1tWCiWLGBKQ3BfcI0t4E1E1L"
    "ODyCIgL0CKhqvnPzBsgjb1BzOyRpAQQQwiO/oMdPwJf8IXnkDpbFr6gewbrWF6VpgrZMEWdM"
    "QHeYwdYxf8LiETB4jcjtII8ABBBajAwhj7xB9QhAAFEUI7B6Atd6eFgbCzwHAsnmiCIVPfkg"
    "9ilC1l5Dl8hj8chbSKEFiROYRwACCC2zk+IR6KYEnLLQuhA61gDfu4MUER+RowC2ghzJI5+g"
    "HvkI9chtpBh5/RpSAMPyCEAAIccIkke+E+URzJ0VWJMVuGeLsgMRJQ6eQrZeQjyBtIsUwsXq"
    "kddQAIwUWIwABBBGjPwmIUYGzCNwn7yGxwhAACHFyC9YHvlFcYwgFtDcgxW88GSFlIpg/kD3"
    "yFO4BIEYQUpaAAGEkdnBu1bBY1rPnnzE9Ai6u7FHCGLi8z4Oj3zC45GnxHsEESMAAQT1CGSA"
    "DuQVcj2CbR8V0sL9RyiJCppqPuHyCBIbxSOwJgoiQuAeAQggbB75ORQ9AhBAII98/gwdjQed"
    "ZwTeY4/dI3eQdrUhOxtl/T582SI0k8N3T6F7A5QXYA7G8AjSRni4R+7dufX+/Vu0lAX3CEAA"
    "MUDP84MesPEb6pHvSB75cAdthyTWnXl3kddYIwaqYQNwKHkDOeSfIgEUDtoeK6BHbt9CixBk"
    "jwAEECxGQEucYEfj/ER45AF4OT98oSvCR1g24mLM2GImq09YnYofQD3y4P6HWzch9fprZI+8"
    "gXoEIICQPAKPkcHtEeRaBKnUAgggqEe+wGLkF9wjoGk38OADTo98gK6ZRF+vj7xiFCV/oOwu"
    "JMUj4G2CH24hF76vwAgRIwABhMUjP2E1+yfogswPSB5BiwSsGw/g44na0I1fSPGB1yNwSWRF"
    "T2AeuYvskVdAgBIjAAGE6pFfkLwO37oDWgtP2CP3sGzAh+8mRs7oT6EnipDiEfDZC2B33L0J"
    "7h++gXoD4hNIXxfoCYAAwoiRX4gYGZQegWSRV0gxAvEIQACBPHLn2ecv0JOaoCcYQTdNfgJ1"
    "lRGrVUnyyEMkb1DBI8C8Cumxv8ESI6DFpgABBPLIm2dfMD3yBbdHkDP5PSwAl0eekuWRT6ge"
    "AfvkFWqMgCZ6AAIIPPX2DFz+Qj3yE3zQCXQbK2xf0weMUgrP5iLYtAHk2JCP8O4T3CPIAOED"
    "JB9ieuQ+0CNo/nj1ClIhglPWf4AAAnvk7ufPEI/8hMUIaP/n4PLIvbu336P54xU0RsCToQAB"
    "BJmeBnrkK+REGsiZg9+huR101II2ikfQAYZHkOsPJI+A2lXkeATU2AdNvYHmQt9hegQcI2Av"
    "AAQQzCNfvsKOwvwJPZfiC3yH9L3797DGBEGPPIZ5BKlNhc8jOKp1kEc+YPfIa7hHAAII2SPg"
    "XIIcI89AZoAWrN7D6wH0xQyoAz/QI1xweQSrp1DbvqDp6Q/AXhWiFnkJBLBCC+oRgACCeOQZ"
    "uCb5Djs8GeGRj4PCI8D2xd07wHod2R/oHgEIIKhHnkGj5AfsWE7w0S3PoI2D+7CNWjg8grEh"
    "B3wQBekeeYbLI9rad27ffA9LWC/hHoEMYoO9ABBAlHgEfjwQ+mIGkEegm54hcx3U8MgNLB5B"
    "yiMAAQRdCgjyCDS7w058BZ/rACz7IEvxsJxphH2h6APUjI44SYsYj2CkM2iDEeiRW4jCF+oP"
    "lLz+HyCAEB75Aj4X88cPZI88HSQeuX8fmLIgHnmF7BFEFvkPEECw5bIgj0AS1w+oR75CD6IB"
    "reqGbIMaKI+AGq6QBiMiYSE8AvUAQADh8QikSwLxiDYuj2hj2awGzSHwgV7MniEpHgFvO/8A"
    "iRA8HgEIILhHwD5BeOQ7xCNPwR55AN20hWf3oDZmfFDBI+BDwkDNkztoOeQluD58g+QRgACC"
    "eeQZ+Ag46PHpMI98gXjk4UB6BLSN88PtW+8wIwTiEdjZIgABBPPIG/A5YwiPQM7eBXd3YQeS"
    "EOURlKnnj4gWI3keAWd1bfC8CKo/ECkLthMGIIDgG2HAUYIUI7DzgcAtHUyPwHZoY/MIyqwU"
    "YtqDZI+Ahx2ALYu74MoQ3SOvUVLWf4AAQmxNguQScBEMPdkZfGDTp4/Q48zwnwUAW7eEOu0M"
    "bTCS4xFYwnpw/wNG0QuNEZA/XsDcDxBAiM1izz5//gK98gFybO3Xr9DzzMBV0gB4BJKw7n0A"
    "LZwD9dVfIXvkNUqZ9f8/QAAheQSR32FnbYPPAhtIjwCLXnCH6h1SifUC7BHYUBDc+QABhOIR"
    "SDsFcd8Jske0CXsEc0UDondIokeg0z2gEV+sHnkFHp1D9ghAACFtcX0GyyWwc4TB52E+gzWk"
    "0eMEc9Ur+loyyMwtWTU7eKAespcI3g8B++MFEMCyCLI//gMEEJJH3kF8AjkTGXZNAGiNEOQM"
    "RnI9QkozHqnAgjZOPsDGF8EeefEC4hFYgxHpdGaAAELeBv4MESdIHoE0E0Art+jnEcisHCiH"
    "3EZp9aJ7BMnxAAGE7JGnzyBHvH5F9chTqEe0cZ6ZAc7lmB5BrCkhzSOweV3QmTi3biJ55AWy"
    "R96gegQggFBOG3gKOUcU5hPoOaXgsxjBuQTppBL0dfoYay3h055A+hPWkThCCQuUQ+5Cpz/B"
    "Aw5wj8CaJ8iOBwgglMMrPqEkrq8wj0BOpkY9coVQskI5eY1Ej4C9Ackh8GFSNH+8Qo+Q/wAB"
    "hHqcyNOnz6BxAj/vHXqsJCUe+USGR0BLzZBKrNcvX+JNWP//AwQQqkc+fYJWi9T1yFMSPPIU"
    "mJIhxcsDRIkFL3lxewQggFA98voT7PxgxHVmEI8AI/oh5EQl2JFEaBu3sS4axTfdht0Xz6Dr"
    "gUAZ/Q64bYIoeZ8/RymyUA8yBgggtEOQnmD1CPToVeRjV2jkEViBBa0KIbO40AzyHMkjqJUh"
    "CAAEEPqxVJ+gGR7lQGfIwcTwoyvBB9yS4pFP2DyDuwIBzaqDlvTDRt8hNchzsEdwJKz//wEC"
    "CN0jT548hfkEcZg9uNyCHJgOO4gM0UiE7KfFtukAZW6dCI8Aswd0rBcUH6A5XGgbC5RBniN5"
    "5A0WjwAEEMbRbcBSHzVOYAfRQ/fRoR1zh2+tPsqSpk9ofsDwzFNY9gANQEG2WEBXB7yEZJDn"
    "0LIXa4T8BwggzMP0sHrkGXiW4jGtPIK8Tgs8/APehgRac/0aJWGBPPL6FShCMJwNEECYHgFV"
    "xMinuNPRI5CzPsFzIe+Rpqcg3sCbQ/7/BwggTI+8hZ8Wjri04hn8ugaERyC7ox7i2M+CvoL0"
    "EwGPgIoEyBQC+HC4m+9QmopQf8ByCEqzFwoAAgjbYZqgxPUMfoEDFo+gHDqIiBvUMQdUb3zC"
    "mPBE9wi04Y6oP2AFFpYSC4urAQII26GskKUW8KPosXoEtc2IzSN4khW6R57COyCPtCH1B7QC"
    "weURLI4GCCCsx+SC55KRTz3H7hFtIj3yCY9HkNbNgFvYHz6AeiDQtTPQLggig0DXNWFzM0AA"
    "YfXIDdgCGMzT22EtLuSDWQh65CkRHvkIObb97t1bN2FbEmBdKUQGgXgE62WpAAGE/ShpUIHz"
    "CXFDACTyYefpa6N3rMDnjKLld2SPPMXpEfhlK+CNFfeRNk1C59hgBRahhPX/P0AA4TjcGxyk"
    "sDiBpuInsMsacJ1mi73oxbdGCzLGAElWkNNwbkI37UAqdLg/niOVWNhdDBBAuI5bhywWQ8mO"
    "NPAI/Jzoh5ATOUH9QXh5RUp8/P8PEEA4PfIIlDygZ+rDp/OAHnmEOpzyAFqnYHoEW+sXNlYH"
    "W4wJ8Qd4lBx0NtFNRDWINT7weQQggHBeSfAKtLMAyRmwqftH8GtS7t+7j76gCZtX0G9OAnvg"
    "EyJvQEZogLU5YgfVa2hDEV6jv8Ac60UHAAGE+5KIhw/h909Ai3kMj0BH5RG9RGyNlE9IAHkt"
    "OSw2wPeWQOID7g/kcpeo+Pj/HyCA8Fzb8fYh0pH6iOPbUT2Cuk0S9xYwjH1HkCuJoLd9IMUG"
    "0ggWvKEI9wae69IAAgjfRSpoHvkI8wjsJGT47S4oHoF5Bst5/E8QQ0SwkwPAdxogzg6ArFdE"
    "TVa4+yDIACCA8N4Wg7JzBdx+ghy38gB65iDS+iD0zXmwiwU+YomJjx8ht0NpQ7xx+xasSfIG"
    "rZkIbyhC/YHPsQABhPeyobfw+yeQXQD2CHjtFspqofso+z7hHsECYFcr3YdGB2JPNLwaRPMI"
    "wYT1/z9AAOG//unVI+T9j6geQb1PCLatGFtj8hHm2V/a0BOIb99E2+yJHB+o+QN3gQUGAAFE"
    "4EKuVw/R+k7QM8jA7riL9coaZM88xHbMH3jKHnYkBux8ENiy5JeY6Qo6WYjfH/8BAojQFWmv"
    "cJ7TdxdlMw/y+mzktdios0FIJ3qCjsO48R4lOiBTa+jx8Qqyue0lAYcCBBDBS+teoaZ7SKMR"
    "cUwq5kYl5L3r6AB2hPJdZG+g+OMFotkOndF5/ZqI+Pj/HyCACF8j+Bb5hNGH6B7B3KAP2dKH"
    "9WoxxHmkkNOMEDn8NWyiE7nVjpQ/CN+3CRBAxFyZ+AAVIHvkFvaDK7Dd/ATbTHoDdpDc27co"
    "mRw2vIvwB3yJ8lsiXAkQQERdtfkWMYANLnHug0reO/AjnmDnvULP5YQf/YK+QRz5KDw0TyCP"
    "UsOHqokqdmEAIICIu/wUNb9CVs+CPXIT+eBaZK8gvIM4iAfVG6geeYnqEVh0vCZQnyMAQAAR"
    "eR3tK6QuCIZH3qOfA4k42BJVHHEqyxuEJ2Cp6iXCE4g1MxiD7jgBQAARe0Ew0sUA9xC3uSE8"
    "8o4IgPAFPDLgyeolcmzAcweukQYsACCAiL+yGeqRe7CLq2Bnx2PGB/RQNchhd2hH5MA21b9G"
    "TlOovoAtu3xDdLICAYAAIuES7fvIZ+mjeQRxduJbzNN90FIUYo8UfG0Jki9evkLkjjck3DYP"
    "EECkXGv+jpBHwDGB1QPIm+mhnkBe64Pii1ew2MA+7oMDAAQQaRfNwzxyF0eMYIkAlPMAXr9B"
    "eALJHyiryeDbC9+S5DSAACLNI/8Z7kHa79ADLWAeeYd2fCIsFtCONUDxBaZHYP4AJ6q3JLoM"
    "IIBIVP7/DbRHdQdyjjuqR3AmKKSNg69eY/cI0iYdcHS8JtFhAAFEqkcg6QveCkfxyDvs5ROK"
    "N5DiA+yRV8h7KGAl7tt3pLsKIIDI8Mh/XB7BWkIhe+M1si/QAKzEJT13QABAAJHjEaBXwB5B"
    "tLKwxsgbjBh5hRohyFHx+vUbSrzx/z9AAJHnkf+vkDxyg0CMoOYQHJHx+g0sWb0kz0UAAUSm"
    "R0C7F+F3HbxHbw2iHR31GjV5gTMK6g5oxIlyZDsHIIDI98h/BmgzHrldi80foLB+jQu8eY3s"
    "DQpcAxBAFGgFFcaIrhL6SbzYanM0P6BEBekFLioACCDKPPL/P7QFjFkpolbp8DT2BtUTSEfi"
    "UegQgACi1CNA8BJWDKMnrzcQ/Aarp5Aj490Lyl0BEEBU8Mj//69vofVk35IAIFttKQYAAUQV"
    "j0ASGTzjox/B/fYdZqMYctI4xQkKAQACiHoe+f8fOtSAWiBD+ihvMbuLVPXG//8AAURNj0CH"
    "XCCjKzh78hBvUN1agACivkeAWeYtfo+8fUUDSwECiBYeGRAAEEDDxiMAATRsPAIQYAAZi6PF"
    "fdLmvAAAAABJRU5ErkJggg==")

Navigation

  • index
  • modules |
  • Home |
  • Gallery |
  • Contents»
  • Module code »
  • shapedbutton


shortcuteditor

  • modules |
  • Home |
  • Gallery |
  • Contents»
  • Module code »
  • shortcuteditor

Source code for shortcuteditor

# --------------------------------------------------------------------------------- #
# SHORTCUTEDITOR wxPython IMPLEMENTATION
# Inspired By the GIMP Shortcut Editor.
#
# Andrea Gavana, @ 05 March 2012
# Latest Revision: 06 Mar 2012, 21.00 GMT
#
#
# TODO List
#
# 1. Check the various IDs in the KEYMAP dictionary to try and understand if all
#    the possible shortcut combinations can be handled.
#
# 2. Verify that the current shortcut handling is working as advertised.
#
#
# For All Kind Of Problems, Requests Of Enhancements And Bug Reports, Please
# Write To Me At:
#
# andrea.gavana@maerskoil.com
# andrea.gavana@gmail.com
#
# Or, Obviously, To The wxPython Mailing List!!!
#
#
# End Of Comments
# --------------------------------------------------------------------------------- #

"""
L{ShortcutEditor} is a widget that allows the user to customize and change keyboard
shortcuts via a dialog. It can be used to edit `wx.MenuItem` shortcuts or accelerators
defined in a `wx.AcceleratorTable`.

:note:

    L{ShortcutEditor} **requires** the minimum AGW version 0.9.3 or the current
    SVN, for the various enhancements made to the L{HyperTreeList} and L{GenericMessageDialog}
    widgets.

Description
===========

L{ShortcutEditor} is a widget that allows the user to customize and change keyboard
shortcuts via a dialog. It can be used to edit `wx.MenuItem` shortcuts or accelerators
defined in a `wx.AcceleratorTable`.

The interface itself is very much inpired by the GIMP shortcut editor:

http://graphicssoft.about.com/od/gimptutorials/tp/keyboard-shortcut-editor.htm

There are very few minor UI differences between L{ShortcutEditor} and the GIMP one,
although the behaviour should be pretty much equivalent.

Various features:

* Shortcuts are listed in a tree-like structure, pretty much reflecting a menu
  hierarchy (as most of the time L{ShortcutEditor} is used to edit `wx.MenuItem`
  shortcuts);
* Accelerators defined via `wx.AcceleratorTable` are handled in a similar way;
* Support for I18N;
* Ability to restore default shortcuts/accelerators via a UI button;
* Possibility to send back the new/updated shortcuts to the original `wx.MenuBar` or
  the original `wx.AcceleratorTable`;
* Filters on the shortcuts label (case-insensitive);
* Basic help window with instructions (customizable via L{SetHTMLHelpFile}), via
  the ``Help`` button.

And a lot more. Check the demo for an almost complete review of the functionalities.

UI Interactions
===============

1. In the L{ShortcutEditor} dialog you can open sub-sections by clicking the small box
   with a + sign in it next to each section name. In the screen grab, you can see I've
   opened the *Options* sub-section as I'm going to add a keyboard shortcut to the
   *OptionsItem 1* item.

   .. figure:: _static/ShortcutEditor_1_thumb.png
      :alt: Open Subsections
      :figclass: floatcenter
      :target: _static/ShortcutEditor_1.png

      **Figure 1**

2. Now you need to scroll to the tool or command that you want to edit and click on it
   to select it. When selected, the text for that tool in the *Shortcut* column changes
   to read 'New accelerator...' and you can press the key or combination of keys you
   want to assign as a shortcut.

   .. figure:: _static/ShortcutEditor_2_thumb.png
      :alt: Assign Shortcut
      :figclass: floatcenter
      :target: _static/ShortcutEditor_2.png

      **Figure 2**

3. I've changed the *OptionsItem 1*'s keyboard shortcut to ``Shift+Ctrl+F`` by pressing
   the ``Shift``, ``Ctrl`` and ``F`` keys simultaneously. If you want to remove a keyboard
   shortcut from any tool or command, just click on it to select it and then when the
   'New accelerator...' text displays, press the backspace key and the text will change
   to 'Disabled'.

   Once you're happy that your keyboard shortcuts are set up as you wish, simply click
   the ``OK`` button.

   .. figure:: _static/ShortcutEditor_3_thumb.png
      :alt: Remove/Save Shortcuts
      :figclass: floatcenter
      :target: _static/ShortcutEditor_3.png

      **Figure 3**

4. If you thought my choice of ``Shift+Ctrl+F`` was an odd selection, I chose it because
   it was a keyboard combination that hadn't already been assigned to any tool or command.
   If you try to assign a keyboard shortcut that is already in use, an alert will open
   telling you what the shortcut is currently being used for. If you want to keep the
   original shortcut, just click the ``Cancel`` button, otherwise click ``Reassign shortcut``
   to make the shortcut apply to your new selection.

   .. figure:: _static/ShortcutEditor_4_thumb.png
      :alt: Reassigning Shortcuts
      :figclass: floatcenter
      :target: _static/ShortcutEditor_4.png

      **Figure 4**

Base Functionalities
====================

There are basically three ways to populate the L{ShortcutEditor} dialog, depending on
your needs. These approaches can be combined if needed.

1) Use the L{FromMenuBar} method: if you need to give your user the ability to edit
   the various `wx.MenuItem` shortcuts in your application, you can create L{ShortcutEditor}
   in this way::

        # Build your wx.MenuBar first!!!
        # "self" is an instance of wx.TopLevelWindow

        dlg = ShortcutEditor(self)
        dlg.FromMenuBar(self)

        # Here the user will make all the various modifications
        # to the shortcuts

        if dlg.ShowModal() == wx.ID_OK:
            # Changes accepted, send back the new shortcuts to
            # the TLW wx.MenuBar
            dlg.ToMenuBar(self)

        dlg.Destroy()

2) Use the L{FromAcceleratorTable} method: if you need to give your user the ability to edit
   the various accelerators you set via `wx.AcceleratorTable` in your application, you can
   create L{ShortcutEditor} in this way::

        # Build your wx.AcceleratorTable first!!!
        # "accelTable" is a list of tuples (4 elements per tuple)

        accelTable = []

        # Every tuple is defined in this way:

        for label, flags, keyCode, cmdID in my_accelerators:
            # label:   the string used to show the accelerator into the ShortcutEditor dialog
            # flags:   a bitmask of wx.ACCEL_ALT, wx.ACCEL_SHIFT, wx.ACCEL_CTRL, wx.ACCEL_CMD,
            #          or wx.ACCEL_NORMAL used to specify which modifier keys are held down
            # keyCode: the keycode to be detected (i.e., ord('b'), wx.WXK_F10, etc...)
            # cmdID:   the menu or control command ID to use for the accelerator event.

            accel_tuple = (label, flags, keyCode, cmdID)
            accelTable.append(accel_tuple)

        dlg = ShortcutEditor(self)
        dlg.FromAcceleratorTable(accelTable)

        # Here the user will make all the various modifications
        # to the shortcuts

        if dlg.ShowModal() == wx.ID_OK:
            # Changes accepted, send back the new shortcuts to
            # the window with the wx.AcceleratorTable:
            dlg.ToAcceleratorTable(self)

        dlg.Destroy()

3) Build your own hierarchy of shortcuts using L{GetShortcutManager}::

        dlg = ShortcutEditor(self)
        manager = dlg.GetShortcutManager()

        for label, accelerator, bitmap, help, cmdID in my_list:
            shortcut = Shortcut(label, accelerator, bitmap, help, accelId=cmdID)
            manager.AppendItem(shortcut)

        dlg.ShowModal()
        dlg.Destroy()

Usage
=====

Usage example::

    import wx
    import wx.lib.agw.shortcuteditor as SE

    class MyFrame(wx.Frame):

        def __init__(self, parent):

            wx.Frame.__init(self, parent, -1, "ShortcutEditor Demo")

            bar = wx.MenuBar()
            menu = wx.Menu()

            menu.Append(101, "&Mercury", "This the text in the Statusbar")
            menu.Append(102, "&Venus", "")
            menu.Append(103, "&Earth", "You may select Earth too")
            menu.AppendSeparator()
            menu.Append(104, "&Close", "Close this frame")

            bar.Append(menu, 'File')
            self.SetMenuBar(bar)

            dlg = SE.ShortcutEditor(self)
            dlg.FromMenuBar(self)

            if dlg.ShowModal() == wx.ID_OK:
                # Changes accepted, send back the new shortcuts to the TLW wx.MenuBar
                dlg.ToMenuBar(self)

            dlg.Destroy()

    # our normal wxApp-derived class, as usual

    app = wx.PySimpleApp()

    frame = MyFrame(None)
    app.SetTopWindow(frame)
    frame.Show()

    app.MainLoop()

Window Styles
=============

`No particular window styles are available for this class.`

Events Processing
=================

This class processes the following events:

========================= ==================================================
Event Name                Description
========================= ==================================================
``EVT_SHORTCUT_CHANGING`` Event emitted when the user is about to change a shortcut.
``EVT_SHORTCUT_CHANGED``  Event emitted when the user has changed a shortcut.
========================= ==================================================

Supported Platforms
===================

L{ShortcutEditor} has been tested on the following platforms:
  * Windows (Windows Vista/7);

License And Version
===================

L{ShortcutEditor} is distributed under the wxPython license.

Latest Revision: Andrea Gavana @ 06 Mar 2012, 21.00 GMT

Version 0.1

.. versionadded:: 0.9.3

"""

# Version Info
__version__ = "0.1"

import wx
import os
import sys

import wx.html

import wx.lib.buttons as buttons
from wx.lib.embeddedimage import PyEmbeddedImage
from wx.lib.mixins import treemixin

# AGW stuff
import hypertreelist as HTL
import genericmessagedialog as GMD

# add support for I18N
_ = wx.GetTranslation

try:
    dirName = os.path.dirname(os.path.abspath(__file__))
except:
    dirName = os.path.dirname(os.path.abspath(sys.argv[0]))

# ----------------------------------------------------------------------------
# Constants
# ----------------------------------------------------------------------------

DATA_DIR = os.path.join(dirName, 'data')

# These commented out things need to be taken into account somehow, but I
# have no idea how to treat them and even if they could be valid accelerators

KEYMAP = {
    wx.WXK_BACK : 'Back',
    wx.WXK_TAB : 'Tab',
    wx.WXK_RETURN : 'Enter',
    wx.WXK_ESCAPE : 'Esc',
    wx.WXK_SPACE : 'Space',
    wx.WXK_DELETE : 'Delete',
    wx.WXK_START : 'Start',
    wx.WXK_CANCEL : 'Cancel',
    wx.WXK_CLEAR : 'Clear',
    wx.WXK_MENU : 'Menu',
    wx.WXK_PAUSE : 'Pause',
    wx.WXK_CAPITAL : 'Capital',

    wx.WXK_END : 'End',
    wx.WXK_HOME : 'Home',
    wx.WXK_LEFT : 'Left',
    wx.WXK_UP : 'Up',
    wx.WXK_RIGHT : 'Right',
    wx.WXK_DOWN : 'Down',
    wx.WXK_SELECT : 'Select',
    wx.WXK_PRINT : 'Print',
    wx.WXK_EXECUTE : 'Execute',
    wx.WXK_SNAPSHOT : 'Snapshot',
    wx.WXK_INSERT : 'Insert',
    wx.WXK_HELP : 'Help',
#    wx.WXK_NUMPAD0 : 'WXK_NUMPAD0',
#    wx.WXK_NUMPAD1 : 'WXK_NUMPAD1',
#    wx.WXK_NUMPAD2 : 'WXK_NUMPAD2',
#    wx.WXK_NUMPAD3 : 'WXK_NUMPAD3',
#    wx.WXK_NUMPAD4 : 'WXK_NUMPAD4',
#    wx.WXK_NUMPAD5 : 'WXK_NUMPAD5',
#    wx.WXK_NUMPAD6 : 'WXK_NUMPAD6',
#    wx.WXK_NUMPAD7 : 'WXK_NUMPAD7',
#    wx.WXK_NUMPAD8 : 'WXK_NUMPAD8',
#    wx.WXK_NUMPAD9 : 'WXK_NUMPAD9',
    wx.WXK_MULTIPLY : '*',
    wx.WXK_ADD : '+',
#    wx.WXK_SEPARATOR : 'WXK_SEPARATOR',
    wx.WXK_SUBTRACT : '-',
    wx.WXK_DECIMAL : '.',
    wx.WXK_DIVIDE : '/',
    wx.WXK_F1 : 'F1',
    wx.WXK_F2 : 'F2',
    wx.WXK_F3 : 'F3',
    wx.WXK_F4 : 'F4',
    wx.WXK_F5 : 'F5',
    wx.WXK_F6 : 'F6',
    wx.WXK_F7 : 'F7',
    wx.WXK_F8 : 'F8',
    wx.WXK_F9 : 'F9',
    wx.WXK_F10 : 'F10',
    wx.WXK_F11 : 'F11',
    wx.WXK_F12 : 'F12',
    wx.WXK_F13 : 'F13',
    wx.WXK_F14 : 'F14',
    wx.WXK_F15 : 'F15',
    wx.WXK_F16 : 'F16',
    wx.WXK_F17 : 'F17',
    wx.WXK_F18 : 'F18',
    wx.WXK_F19 : 'F19',
    wx.WXK_F20 : 'F20',
    wx.WXK_F21 : 'F21',
    wx.WXK_F22 : 'F22',
    wx.WXK_F23 : 'F23',
    wx.WXK_F24 : 'F24',
    wx.WXK_NUMLOCK : 'NumLock',
    wx.WXK_SCROLL : 'Scroll',
    wx.WXK_PAGEUP : 'PgUp',
    wx.WXK_PAGEDOWN : 'PgDn',
#    wx.WXK_NUMPAD_SPACE : 'WXK_NUMPAD_SPACE',
#    wx.WXK_NUMPAD_TAB : 'WXK_NUMPAD_TAB',
#    wx.WXK_NUMPAD_ENTER : 'WXK_NUMPAD_ENTER',
#    wx.WXK_NUMPAD_F1 : 'WXK_NUMPAD_F1',
#    wx.WXK_NUMPAD_F2 : 'WXK_NUMPAD_F2',
#    wx.WXK_NUMPAD_F3 : 'WXK_NUMPAD_F3',
#    wx.WXK_NUMPAD_F4 : 'WXK_NUMPAD_F4',
#    wx.WXK_NUMPAD_HOME : 'WXK_NUMPAD_HOME',
#    wx.WXK_NUMPAD_LEFT : 'WXK_NUMPAD_LEFT',
#    wx.WXK_NUMPAD_UP : 'WXK_NUMPAD_UP',
#    wx.WXK_NUMPAD_RIGHT : 'WXK_NUMPAD_RIGHT',
#    wx.WXK_NUMPAD_DOWN : 'WXK_NUMPAD_DOWN',
#    wx.WXK_NUMPAD_PRIOR : 'WXK_NUMPAD_PRIOR',
#    wx.WXK_NUMPAD_PAGEUP : 'WXK_NUMPAD_PAGEUP',
#    wx.WXK_NUMPAD_NEXT : 'WXK_NUMPAD_NEXT',
#    wx.WXK_NUMPAD_PAGEDOWN : 'WXK_NUMPAD_PAGEDOWN',
#    wx.WXK_NUMPAD_END : 'WXK_NUMPAD_END',
#    wx.WXK_NUMPAD_BEGIN : 'WXK_NUMPAD_BEGIN',
#    wx.WXK_NUMPAD_INSERT : 'WXK_NUMPAD_INSERT',
#    wx.WXK_NUMPAD_DELETE : 'WXK_NUMPAD_DELETE',
#    wx.WXK_NUMPAD_EQUAL : 'WXK_NUMPAD_EQUAL',
#    wx.WXK_NUMPAD_MULTIPLY : 'WXK_NUMPAD_MULTIPLY',
#    wx.WXK_NUMPAD_ADD : 'WXK_NUMPAD_ADD',
#    wx.WXK_NUMPAD_SEPARATOR : 'WXK_NUMPAD_SEPARATOR',
#    wx.WXK_NUMPAD_SUBTRACT : 'WXK_NUMPAD_SUBTRACT',
#    wx.WXK_NUMPAD_DECIMAL : 'WXK_NUMPAD_DECIMAL',
#    wx.WXK_NUMPAD_DIVIDE : 'WXK_NUMPAD_DIVIDE',
#
#    wx.WXK_WINDOWS_LEFT : 'WXK_WINDOWS_LEFT',
#    wx.WXK_WINDOWS_RIGHT : 'WXK_WINDOWS_RIGHT',
#    wx.WXK_WINDOWS_MENU : 'WXK_WINDOWS_MENU',

#    wx.WXK_SPECIAL1 : 'WXK_SPECIAL1',
#    wx.WXK_SPECIAL2 : 'WXK_SPECIAL2',
#    wx.WXK_SPECIAL3 : 'WXK_SPECIAL3',
#    wx.WXK_SPECIAL4 : 'WXK_SPECIAL4',
#    wx.WXK_SPECIAL5 : 'WXK_SPECIAL5',
#    wx.WXK_SPECIAL6 : 'WXK_SPECIAL6',
#    wx.WXK_SPECIAL7 : 'WXK_SPECIAL7',
#    wx.WXK_SPECIAL8 : 'WXK_SPECIAL8',
#    wx.WXK_SPECIAL9 : 'WXK_SPECIAL9',
#    wx.WXK_SPECIAL10 : 'WXK_SPECIAL10',
#    wx.WXK_SPECIAL11 : 'WXK_SPECIAL11',
#    wx.WXK_SPECIAL12 : 'WXK_SPECIAL12',
#    wx.WXK_SPECIAL13 : 'WXK_SPECIAL13',
#    wx.WXK_SPECIAL14 : 'WXK_SPECIAL14',
#    wx.WXK_SPECIAL15 : 'WXK_SPECIAL15',
#    wx.WXK_SPECIAL16 : 'WXK_SPECIAL16',
#    wx.WXK_SPECIAL17 : 'WXK_SPECIAL17',
#    wx.WXK_SPECIAL18 : 'WXK_SPECIAL18',
#    wx.WXK_SPECIAL19 : 'WXK_SPECIAL19',
#    wx.WXK_SPECIAL2 : 'WXK_SPECIAL2',
}

# Define a dictionary to hold the correspondence between wx.ACCEL_* and
# human-readable names
ACCELERATORS = {wx.ACCEL_ALT   : 'Alt',
                wx.ACCEL_CTRL  : 'Ctrl',
                wx.ACCEL_NORMAL: '',
                wx.ACCEL_SHIFT : 'Shift'}

# Define a dictionary to hold the correspondence between wx.MOD_* and
# human-readable names (platform dependent)
if wx.Platform == '__WXMAC__':
    MODIFIERS = [(wx.MOD_CONTROL, 'Cmd'), (wx.MOD_ALT, 'Alt'), (wx.MOD_SHIFT, 'Shift'), (wx.MOD_META, 'Meta')]
else:
    MODIFIERS = [(wx.MOD_CONTROL, 'Ctrl'), (wx.MOD_ALT, 'Alt'), (wx.MOD_SHIFT, 'Shift'), (wx.MOD_WIN, 'Win')]

# Define a couple of standard, default accelerators
NEW_ACCEL_STRING = _('New accelerator...')
DISABLED_STRING = _('Disabled')

# Events handled by ShortcutEditor
wxEVT_SHORTCUT_CHANGING = wx.NewEventType()
wxEVT_SHORTCUT_CHANGED = wx.NewEventType()

EVT_SHORTCUT_CHANGING = wx.PyEventBinder(wxEVT_SHORTCUT_CHANGING, 1)
""" Event emitted when the user is about to change a shortcut. """
EVT_SHORTCUT_CHANGED = wx.PyEventBinder(wxEVT_SHORTCUT_CHANGED, 1)
""" Event emitted when the user has changed a shortcut. """

# Standard images for all the buttons we use in the dialog
#----------------------------------------------------------------------
_cancel = PyEmbeddedImage(
    "iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAABGdBTUEAAK/INwWK6QAAABl0"
    "RVh0U29mdHdhcmUAQWRvYmUgSW1hZ2VSZWFkeXHJZTwAAAQQSURBVHjaAEEAvv8BXTIyAAL9"
    "/UEy6Oip+fn5BqAAAHX1/f2bBP7+ACMDAwA4BQUAB/z8AAH6+hQhCQm7FAsLKpPm5qfh/f1g"
    "4QAAAAIAQQC+/wMtGBhBLufnr1w5ORI1JycI+traR9QBAev4/v7NFQICABsDAwAB/PwUFwAA"
    "vDdJSTA0X18DIujoL9Lm5iLZAACyAgBBAL7/A2ADA8xhKSkREoaGAAQ9PQAm398DAeDgRtP/"
    "/+gKAgLOHQEBDBr//782NDQwIGpqAP84OAAgFBQBKOXlLr3n5wcCAEEAvv8E9fn5CAcBAQD5"
    "3NwA+A8PAA5aWgBY+PgG/cjIlMcCAhUUAQFSMScnMB1VVQD/AAAA99HRAAj4+AAFBQUBAf//"
    "NAKI+TEf36uvT5546N+4wczMxcXwE2gYu6Qkg8T79yxCb986KUtKSiu7ujKwAA3/9ewZA/fN"
    "mwxX1q5lyD979sXZ//9LAAKImZeL69w5oJ//v37tqvP4MQsj0IA/wEBjBWrg+fmTUVRZmYGD"
    "lxesmePpU4Zbx44xFF269OLQ379xQAftBgggZgFOToYvf/+ePcPA8ILl0yc35RcvWP79+sXA"
    "9PMnAxc3NwML0LA/L14w/H79muHarVsM5TduvDj6928UUPNeIGYACCBmbXFxBkFgVPEwM597"
    "xcn5W/DXLxexp08Zf338yPDn/XuGX0CNPz5/ZvgGNLD93r13R37/DhBkYDjMA9QMChOAAGLR"
    "FBEBpQOG/3/+8Mn+/Bmi8OkT40eg5ncfPjB8BXqHhZ2dgRvoHVFRUQYvMTHuN48fa/xgYDjG"
    "C9R8H4gBAohZDxhgP///55H68eOg34sXxmJAze+BEh/+/2f4DqT/sLAwsAK9ycbGxmAhJcUi"
    "yczscfrDh9dAQ85+BcoDBBCztoyMpMz37/vCnjwxkAY69QNQ8BsQswI18EtIMHACaRBgBbqE"
    "CYiNZGRYRP//d738/v3rF0BDAAKI2U9A4EjMw4f6il+/MnwEKvwJxCBNT4SFGab/+PGem42N"
    "WY+bm/kvMFWyAMWZga4xVVBgkfj3z23f27cPAQKISebzZ21toOa/QI3/gJgfGKCPgZq7v317"
    "sfPdO7+Fr19nnv/585cIUCMTKMEBY4UFmF7M5eTYBJmZkwACiPk1F5cCPyengTYwzlmBtpwG"
    "aq7//v3F+Y8fo9gYGQ+xMzCcv/7ly0sxFhY3HSEhFkFgmvgEjJ2ms2d/7Pz6dSpAADHIAkNX"
    "R1x80SoxsX+bxMX/6/HzPwc6xBnkbw6gjWpAF6kDaUNGxoxFSko/7lpY/E/n5//ByMBQAlID"
    "EEAMqmJiDNJAWxX4+dsluLh2A8XcGKAAZoA+MEdqAvn6jIwx+iwse5kZGAphagACDAAeLHBa"
    "S9SUbwAAAABJRU5ErkJggg==")

#----------------------------------------------------------------------
_clear = PyEmbeddedImage(
    "iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAABmJLR0QA/wD/AP+gvaeTAAAA"
    "B3RJTUUH1wYeFCULmGdR+AAAAnpJREFUOI2V0ktIVFEcBvDv3jveufO4jk46ZVlGNUGRLTIp"
    "K8OCoAdBIM2ioo2LCKFsI7QJCQoiiJ60nCDBTbUpsJSh0cxw42DImA2j1vhImXFmvPM493VO"
    "izDS6WFn/X0/+H8cDv/xHpyzXuYs/FVdVT2iVbre/CTXxq+0fP+M9ZLNId/YVd+4+tTZFo5o"
    "rBUAVgQ8PI9VsOBmTf1JR3+wE18igyCcHAUAy0oAysSLFeuqBJFMoW7nerwZ+JzLGFLLP4FP"
    "70r7KOOeBzqMZpeYl+KxEPqiYlbVhHt3XnwN/PUEf5tfMg3Lfrmk+tYhn3VNWXUeUYXXFogQ"
    "GhNi1xZzwp+AxiN7H01EjtaoxCt4KmvhLMvA6priqzaTjrxFDQSDYADALS+Ov4WkWzxPDWY7"
    "np4/IY0Ob+RHQgrc5QnsafgIQx+CrqH1WJNyuwCI9DrLqeAI2GXvlrVVp22MmdDyMYyPJvDM"
    "TxEJ21HXMNBeXjvU5PNBWwJEu0tdpk18L5ft9pa4a0ShSIapzUGZHwEvZKCTafR2ZzXOmfP4"
    "LiTTiz0eAGL9lTbDLnY53dWbZNd2MZuegKnHoeYnkVuIQVdnoKszcDhTBVvxAJCj2iuH7N3h"
    "kLfapsdewlFcAY1MITU7AmokoaSmAVDoKoDkbwBK1cOi6LZPjLbD6fJCV2cQDfeAZGdBzSSS"
    "CQrGAMPgeJBkvgAAuIZvk0HoGiBKEsKhTj0VT4IaC+AFA/E5DprKATzSvrYf4y0Bth1M9RDT"
    "soHSosfhwdcsq5AiajBqmgbyhEdGARJxRnmOdS/foOAfAECXv9hrmuwuIeyApqL4Z5jn9vmu"
    "KB9+zX4H1k8cy/juDWsAAAAASUVORK5CYII=")

#----------------------------------------------------------------------
_default = PyEmbeddedImage(
    "iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAABHNCSVQICAgIfAhkiAAAAAlw"
    "SFlzAAAK8AAACvABQqw0mAAAACV0RVh0U29mdHdhcmUATWFjcm9tZWRpYSBGaXJld29ya3Mg"
    "TVggMjAwNId2rM8AAAAWdEVYdENyZWF0aW9uIFRpbWUAMDIvMTEvMDeS+i0/AAACvklEQVR4"
    "nKWSXUjVdxjHP7/f/+W8qdPqj5rRPAsryDM2FIRBjEQotjuHsV2NCIPqoqju6iqnuYu9ZKtw"
    "N7mKujGqDXQ3o9UQEsl8mYl1OGp5lDRt5+h5+Z/j///rIgVfops98MDDw/N8+D4vQinF/zG5"
    "NtHU2LDn8qWL1StS1q329khj43dPZ1/P578X8Mfvdw/W1Oy9Mzo21l5bW1vjy/XKCy0tZ4LB"
    "YHBudq6s/uC3x9YCdADchIUMzHR13du/9cOyvEgkAspp7uvpMzs7/wz9dP5nno2GldBFIWAA"
    "2dUKhMoODju1wZ11u65fu0o0GnW2lIbse38/CMXiMR739rF722fcbrr5iZ1JhFYqEG+XOCR+"
    "aStr/W/erNfFDAG/oYpzXtrXrh7x9j4b52T5VxyvPMHAZA+bzlZt3Fxgza0egV0qmcy+TsRB"
    "ahYTzxFf11327jtXxmSsku0l20hfuE9qmnSgwFp1tqUl9oFAahKkAE1X2Il5csxpthdPwNg/"
    "QAqh68IF8Q5AaY6hu7arKaQXhAZCGiB1cAS4BkJqCEN6AmQ3rb8CnhJpZ/qHHjrkF9r4/Dmg"
    "ZcFYAkhBMp3GNfMepTHC5nqAb2TqZWJrMu4wM5lkYTHKSO4gRVUpKC1CMwMMd00ytUNMV4H7"
    "DgWQXURJAZqhkcnAq5EIsdlpjKJxuiMbyA7v58nGoY/vHD5QveWDwti55ubHgLv8SNLjdV3d"
    "cFhcANcRxFIJpN+DtpDgxWiaT/MsOu9fKentCv+lS42Ojo6m/oGB08uv/NGhA/qjyqr5b8pD"
    "dnd+QZxcv4lKJzGERkxPcjLRwr/OKHbaxvR4lGVZDwFQSi15dDk2w2MTX6Qe/Ppj+PsvpzIN"
    "5W5zdZ5Cw/X5fcmKiorrbW2/7VjuWwFY73GlyrP9N9pbT9WNf16z94emxoaja2veALFzTWMO"
    "z/GRAAAAAElFTkSuQmCC")

#----------------------------------------------------------------------
_help = PyEmbeddedImage(
    "iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAC+ElEQVR4nGWTP2xbVRjFf9+9"
    "9/01TgwJCQkMbkMKqCkEKGoXBpiQEqkpZUL8y8BeRqYwMMBQRMWMGtQgJCSKYWCohARIVCCo"
    "MJUgLbSipVERTuzYcexn+713L4OlirafdLZzznC+c4TbbnZxrSTIEkoeQ9S8iICob0WkevHM"
    "C5Xb+XKLeOH08WIxXnloZqoUhSFRFDHIcmr1XerNDts7navWuTfWPz1SucNgduH0qfm58mt7"
    "y/ezfq1LrZmR2SHFaAg9QTtLo1WnnybLv3+yuHrTYHZh7a1DT8ysFEfH+eVyh73TEa8vTvL0"
    "o0WsdXzz6w6nzm5x5cYALdDtNMgG3aO/ffxcRWYX18pTE6W/Dj7+CN9daDM17lN5+2GsteS5"
    "w1qLc44b9ZSXTlxHRHDOkrRqTWvzPXp837GVw0/OHl7fyOiljt2eJQ4U9VbGiTM1HLBn0iP2"
    "hR8v92n1QGmNaB3m6eCS8QNvSZmI7XYXRECED76skTshs6C18OyBGOccm7uOTjrMLNQRottH"
    "zOhIoVxrpsM0BPqpo9vJEa15YMLnzWNjWGs590efRg/8yABQUJB0dclYB71BjnWwvZORI3i+"
    "RnuKd16ZIA6EK/9mnPy6QxB7KDV8XDFw1BsGM0hzBMfmdooTwfgKZRQLB+9iZtJgrePD7xNS"
    "ZQgChdIKgJGCRZRGdZJBpd1OsM4hSlB6iKl7DM45nHNc2nQEoSGIPMLYY2TEIwxAtKkaRH3R"
    "au8uFcNRulZQaojKzwn7pn22EjC+xgs0fuhhfE15DP5cbyFKf6Qufvb8atJPqpHOMQKIIEo4"
    "+lTMoRmfhTmfuWmD9jReqJm+10ORs/FPv3L+/QNVBeBwy4O01QzE3uz2hesp3QFs7MDfTYdR"
    "cN+oUPIyzv3QqIrSy7dsYf+LX82jzOe5GS3rsEgcGeKCR6FouLvkMVYybDV6XNtIqoNMnvnp"
    "3Qebd6xx7uWzJZQ6Ltp71XhBOS7EhJEhzS27SV4VbU6ef2//6v81/wH6bjI8fK9HXAAAAABJ"
    "RU5ErkJggg==")

#----------------------------------------------------------------------
_info = PyEmbeddedImage(
    "iVBORw0KGgoAAAANSUhEUgAAAEAAAABACAYAAACqaXHeAAAABGdBTUEAALGPC/xhBQAAAAFz"
    "UkdCAK7OHOkAAAAgY0hSTQAAeiYAAICEAAD6AAAAgOgAAHUwAADqYAAAOpgAABdwnLpRPAAA"
    "AAZiS0dEAP8A/wD/oL2nkwAAAAlwSFlzAAAN1gAADdYBkG95nAAAEURJREFUeNrtmmlsXNd1"
    "x//n3Hvfm53kcEiKpERSmy3LdmwlSrwVcZM4qdE6CVB0M4p8CBL0S9ECTb61/dD0cxq3KPKp"
    "SIK2aZAWbeo2cd0kcJp4ixfZlmxHu0RJXGaG23D2mffevacf3oxEs/JObWgecPguhrPc87tn"
    "uefcB/zy+uX1//qiq/2DrDT56cFsZmhyfPLme3ea7MB+ERkDABLUIpazpfOHTzUWTi+210or"
    "UdAOIHLjA/DSg35h6rZbd33k0w8PbtvzK6lsfkcilR0wmn3FUADBibjIIeoGnVanWV9uri6c"
    "WJp95dHZFx/7YW3lQlFsJDccAGV8tW3fPQf3P/CFL+VHpu/PZtKFoTSCiSETDWWMJH0FrQgE"
    "wDkgsA7NjqXyesDlmvNrLRvVKiuzpZPPf/fYk9/5u/XFU0VAbgwA2cLU8J2//odfnth3z+cH"
    "c6mRnSOmPTXiR+mEEgDodCOptQIbRBYAQTEhnTCcSRo2msla0FojpFOljlesOLW2XHz16E++"
    "9ZWzhx573Iad6LoGMLb3I3s/9Jk/eWRk+95PzRRUcPNkMkz5LGu1jl2qtqN2N5LIOondWwAQ"
    "iAAmgmIizyjKJj0ez6e17yleqgb82oVOsrTaqp89/uQjrz729a91VhZa79tCr4Ty4zfdfetd"
    "v/Pn3xzfPvPRO6a81t6JVNRod+2ZxWqwtN6yndAKBDCaKelrTicMp3zDvlGsmMgJEFmHZieS"
    "1XrbtruRjA4kaKrghw7iIzNz/8Do7oHl2SPPhu16cF0BGLv57l13/faffXPb+PiHP7Qz0RwZ"
    "MO78Ui0srjajMHJQipFLeWrP5KB/5+6x1G07C4l9U/nETTvy/p7JIX96LOeNDqa0E0EYOTgn"
    "0gmsVBpd6xtFM2MpYbHoqNG7/PHdpnT6hWdctxVdFwBSQ+MDdz/8F1+fmJz5xIEZv5lLaXum"
    "WA1rza5jZiSMon1T+cS9t06m927P+/lcQqcShhOeZt8oTnhaZZKeKgwkzdRozisMpHSzE7pO"
    "aMU5Qb0VOAFkejQNEYs2Dd+lWC8unXnpZRF3bQGw9ujAQ3/8pelb7vni7VOmU8iZaLZUDZud"
    "0GnFlPAUH7x5PHXHntFUJmlU7PEAxQmAKBb0RSumwbSvtuXTptEOXasbOgBodkJhAk2NpNHs"
    "RF6YmDxYWTzxZHNtoXhNAYztv3f/Bz75xa/uHktmdo35wcJyPaq3A2c0k1ZMt82MJD6waySl"
    "mIkAYgIRgZggsfa0SWI4CU/zcC6pl9dbthtZIRC1upFL+prGh3xXrkmBMxP50olnHrdhJ3zX"
    "C7cVymsvqfbf+3t/NJTL7tg5ajrrza6ttgKrFZNiQjbl8U3bhxJKUV8/EJEwkRCod21mQEQg"
    "ECCDaV/tnRzyPK3Y9L6jvN6yvseyf0eqnZ/c82sjuz9813uy3K0AMDhx01R++75Pbc9z4Bty"
    "K9V2xARSTKSYaTib1OmkYQLAhFjxWLsYBt5EqJcdiTA+nDaphCGlFBnFZK2TtXrH7igko+Fc"
    "MjP94c9+3qQG/GsCYPrOBx/M5gYmxwZUUG12bRhZKGYoxVCKKJ3UrJkvLm0v5fc3IfRmV58B"
    "IDBKkacVa0VQKnarRjtwxCI7xxLdbGHH/Zn8jumrDkD7KTM4sffBXJJUwpCrtQLHTBgbSpk7"
    "d40mh7IJ1QmsOBHwhtXu692zBiGiTdK3lPiKrANRHBy1YlKKSQRodyO3vZCMMun0SG5s9/6r"
    "DiCRzedTgyO7R7IcQODCyEkhl9R33TKe2j89nLh950iiGzlpdkJHGzTnS0pfCgtvkEuGQACW"
    "qq3IySUAcXxhanZCl/SVy6aMGd518D5Whq4ygOGCn8wUsgm2nTASZqJbpoYTAylfCYDBtK8V"
    "Ec4Wq0EYCTiO8D3FL6v5JYljBurtwC5V2pHmvuLUczGCdQImSCapJDEw9hGdyKTflQW/XwB+"
    "aiivWKU8w64TBJLyDRcGkqqf4JkIWhEtrbeiM8X17t7JId83iqxzsFbIOkEYOXJOAAI0E7Rm"
    "0YqhmNBoh/ZMsRZEzolWHKcFAICDCMOJCAjIJbVjZQqsdApA46oBKMzckTeerxWj60SQ9DX7"
    "RnOv0iLrnAgApZjmlxtRcaXJg2nfHx5Isqf5YhHUt1sB4JxQvRXgxeMlFNeabmZigIdzSdGK"
    "BGBAABGBUgSx8efSSe0ASYjAu6oWIAKIk55zA1oxmC/Gd1QaXWudoNYI1Msnyv65Ys0MZnz5"
    "+IemwoP7tslwLsEJL07uIoJOYGW90XXF9ZbMrTTU8XOr6qUT5eTIUMo+cHC6M5DxrAjBCce/"
    "Lf3QEkN510H8/QJYOXd4pXv3p0PrMmyUosg6RNaJpxUHkXXl9VbUCSz96PlzqXY34vsPbA/2"
    "7sjbwawvzW5I3TVLWjGYiACBE4h1grF8Cg/dt9t+9M7t9NKxkvrpK3NeJ4h4WCWccwInBCcE"
    "JSTMTJVaV0eRXYdI66oGwXZ1qdRutdebXaeyKY+7oZXF1UbUaAf21EIlaLZDlzAKzITxQtoe"
    "uHksLAwkxTeKFDP1rKVXF8S9AKPjCG8001A2Ia1uxNmU5wqDSWEiYu4JEXyjCACXKm1urRef"
    "jrqN9asKoLG2XKouV87MLbd9o5iNYpycr3RfPFlqlyutiAhIeBp7tg9GpdWWarZDVipWVCuC"
    "ZiajYmWNVrGo+DWtmMLI8blilffuGHK5lC/UzwA9WNmUp1arHV1arTdLp5561IYdd1UBhO3V"
    "ZmXh0L8urHRso21VLu0pARBGTojjLMBMdNNUPrLOobzWVIqZlGKoXlrTvYKpB5D7rxnFtF7v"
    "cK0V0L7pYesZpr4FEBP5RpPRig+dXEmsluaeq51/9eVrsBUWzB15/NHV5fLJEwuNRNI3nPQU"
    "9dpbFze1+VxCRgZTbq5cV0CvTlCx6J4FaH0Jho4h0bFzq0oxY7yQFgKBOc4aigkDaY/nyg1z"
    "6sJao/jaDx/p1paq16QWqJfPLq6eee4bp+ZrslYL1GDGV0oxEai3/SX4RuGh+3Z377l9IlKK"
    "er2/nhUwo2cBF91BK0ZkHZ24UOGd4wNuMONLXD7HRFO+YetEPf1aySufP/r95RNP/uyaVYPi"
    "LGaf/7d/WinNv/LK6UqSQJz2NfdLun4NNJZPSWEg6WIwREwU7+p6VvAGC1BM9WZAzU6IAzeN"
    "Os+oi30CrZjSvubDp5a9sxfKS4uv/OcjUbvWumYAAKC+Mr+yePTpr51ZqLYvLDd1JumxUUz9"
    "GE8Xd3AbisJeFzgGcSnwcZwdaK5co1zKw46xXK9tHP9J+4Ya7ZCfP1pWK+ePfKs69+rh99zJ"
    "2rqOoGD+5e89vjp/8qmXTqwmuqGllN8vTKg//0t3emO9TwRw7BJgAqxzmFuu08xEbP6Id8qk"
    "FJFnmA6dKJuF4vJ8+bXH/8FFXXsdAADC1npj4dX/+tpcaX19tlhXSU+RVtxbe+lZQO8u8S6y"
    "v60VAZwTOBf/v9WJYK3g1p3DYjSj/1ZPM1qdiI6cXuHK/Ov/0iifPvm+eplb3RZfPf38s5XS"
    "mWePnFlLtANLnmF6g7L9YV9pEXEiYp2TyMbinEil3kEmaTA6lHZO5OI212im0mqTyyu1xurJ"
    "p77voq67rgCEnXq7eOGFb8wv11pL623u7dR6Cl8U6SkOJwJrBZEVCa2LJbSyVmujMJh0SV/D"
    "ORGR2HREgOMX1nS9Wi2210qn33c3+0qcDFWPPvPz6kp5dnaxZkTiQCeCWGnXM3URWCdirUjU"
    "X/3IShRZ6YQWAGR8OCNMJP33EwFBaDFbrKtOrXQobC8vX5cAgvrKcnN17tCJuXXT6oQwmhGv"
    "NuCciHMi1vXM3jmJrEjUX33rpBNEkkwYSSeNs86JlfgzRjHKay1eXK51188f+p57D23wqwLA"
    "2dCtnH72u6WVau18ua7i4obgnBPrBHEzxJG1lmxkKYoihFFEYWQRRlYi6ySbNI6IJLJOrHVg"
    "JkRW6H9envNWloqv1+YOP7slx/dX6nQ46jSWspN33tty/s07x3NhNuWxiFOQ0EBCj8lqgtMg"
    "pyCxiDglzjLEKSYhK46cgyiO9wpPHVkwT75yobnw0r9/uXrh8KHrGoANWkHUbZ1yA3s+Ue9I"
    "YfuwUYNp5Xs6roIvnXzEuwEBSAQkkN7uQFizsFFQrU7IP35xXv3o+XPB3MuPf6X82mPfFhe5"
    "6xoAALQr8wsS1E4hO/rJ08VwwGimgbRHCd/A0xpGKxjF0IqhFaHfB2SOW02NVkhHTq/S9352"
    "ls+cP+NWj/3gL88+/4O/lqgdbtUc9ZUEAHFwxZ/+/Pf3lOZnzcPbfvxCHU8eyWGikMauiSxG"
    "B5PwPYX4qJQQWUE7iLC43MK5UgPltQaCoIYPzhTxwMEn+G9e/9n8L6Io2MopXlkAABKe8I70"
    "Gfqtj/8Ui61pvHB6BM+d2oZnD2cQWg9ONAT9I2IHpgi+7mJiqIaH7y7hjulV7MhXUDp5LBQb"
    "VbZ6flccwIP34TdG89jv6RB3zNRx23SI3713FtWWRr3toR0oRI5BEBjtkPYiZFMBcskQKS9C"
    "t93EhZPHcfJY6eixs3jxhgJgNOjW3fjk0OhIMpUdgJUcOPMFZDMtZFv/Adhz+L+PKVHc7QXi"
    "xqdjOCsw2hUyaYwAKG/lHPlKAiBACGgFnTbCIADcGlzrUbjuIThbgXUMJ5uFIBdPEAV+Oo3t"
    "e2/BcD4xOT2OA1s9xysKIIiA/34O3yoX10qzrx9Gp1UH7FkgOAyRxjt4RC0uJINuG9bayDrU"
    "brgYUKtDiBTlx8bhJQugzB+A9BRc8zuQ7iGQ4OIh+GVTaaOGuRNHUV4Ojx2b3foYcEUtQCvg"
    "M/fjc+PbR8YKE5NgMwryPwgye0D+PSDSb/vMpwBQxsD3kc6kkLmhABABvockENf+sCuQ7kuQ"
    "8Cyk+yxE7Nu6QSqbw/S+2zA85O+cmcDBGwpAGAFPvIh/XCouL184fhRRUIE0/x6u9lUgOHyJ"
    "0luagMBGIax1zkZo31AAAKDaQMU5BIl0CqwHQZnPg3NfBrwPbuiLvZX+gspSGZ1O2O4EWLmh"
    "ABgNPPRRfG5sfHhydMc02IyAvAMgsxvk3/2OYgARYWxqBoP5XO5T9+AzRm/tnK9UFugncqUZ"
    "Y0prECnArQDdQxC9C9J95h3FgPhQIX7AymiME5AEEAJw6Hdb4/E1rwap9326J8Y5MAHujt3t"
    "BxTZpPEUEL4K6T4F2LlLz8dsMnmIwFmLsNtBbWUZ86eOYqW8Xvn2Y/jq8XM42/v+/m9xT+i9"
    "TnqrFOcN94tjz8B89mP4zYcfxJcmtvkzyZSvtfGgjA9WCswKrFTcLLUW1kZwNkIUdBF0u9Jo"
    "dLqLZTf7zz/E3z7+NB7rhuhuWHXbu28cb3xNrjSAvqJqE4Q3AGGGntqGmdv34OB9B/CrU+P6"
    "rnSKRn0DKJberjd+4CFyhFaHUKnaC8fPhj958XW8fOoCji2tYdEJQgBRT+wGcW8ytm8HgbZI"
    "+c0gNooB4PVdw9NIj20b+NiuPdN/OjmWTQ1mfRARBIB1jEotwGK5Fpw6ee6vlsuVnzhB0FMk"
    "7EmwQTaDeNcQ1Ps0fX4b6QPoQ0hYB11vhKuBTQw2w/SeastTzSCJasPD4nKIxaW2XVhYe6Jc"
    "XHrCidhNmUouE/zkLQSbxlsO4L2JSNRs1H8RheGqE8k3Wx1Vqze61Wp1YalU/Nfl0uKjztn1"
    "3gqHmyTaIO4tRDaMr0oMuKz/b84MG+4KgNLG5I3xCgAoDINKFIbVDWZrNykcbri/le+7qxED"
    "NrvCm2aCy7jFxjtdxqJk02raNxm/VQa4Klngci6xWXG6zHizW2yey2b/lU1mLW9j/ld1H/BO"
    "4sObKY93AUDeJPi9o5W+2gDe6rc2mzzeBgAuE9W37PpfnmQMHSrQKjcAAAAASUVORK5CYII=")

#----------------------------------------------------------------------
_ok = PyEmbeddedImage(
    "iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAABGdBTUEAANkE3LLaAgAAAjpJ"
    "REFUeJy90k1IkwEcx/Hvs2evMt1KJ741Wy0zexMy0US6WHSKgii8pAUZKUEFubSgkjKRQgT1"
    "kL0hZNChMpJCi/RQGQll0sBE09wWw5c2c5rbs+fptIgutQ59758//8MP/nNCcsWSm5ajS+8C"
    "6qh1con5So+3W3ni6lTiS81XAe1f45QDsXV3JloVT2BC8c57lGZng6LZJVz8+Ub8fpVD0Mri"
    "1DVqf8dpZYYLZ6pOOjJi1jDqHyIoS7xwdyMbla1qANNO7fHDx0rrZPV3WufbpOl26iM4/Yju"
    "XEXlwdNWvZ3xuY9IssKDT23c6+0l3McjUVfEoe2Vm5vyEwuJ1yVgyRO3jflHfIFBXtvK1dUl"
    "jt016ZpM/MFJZiUfTyfbed7/Ct9t6hmiRkzeR2Moddo6G5xBJYZJjEkiMUcoIvtrzo7iLeUp"
    "Ohu+oJcpycPA3DPefXiP6zoN0gAOQBYRyLRslAqmtS7coSF8iguNQVFZs0yrtYIGb2iE0eBb"
    "3OFBvMMzOBuk2oV+qgAZQFz8zMvwPGkrc3XZQlyIb4KfsNqPUYhFL6pRqWQMOjULEwJ9l3yX"
    "Z/uojmAAEQgFhukKLsq2rLyE9XqTiiTtMuwxWaQb7Cw3ZjDjCtBx1tk41SNX/oojBwBCfidd"
    "QUlalVtgX5tqsmHVrWCdKZfxL2M0nXrY4nksnQDCf9pL3IZy/f1m917ljXxD6fCeV+zF2ugW"
    "B5gLHcbOFtceZVOZ4RagjwZHSrLkUwHE/guOqh90ld9+870vDgAAAABJRU5ErkJggg==")

#----------------------------------------------------------------------
_reassign = PyEmbeddedImage(
    "iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAAGXRFWHRTb2Z0d2FyZQBBZG9i"
    "ZSBJbWFnZVJlYWR5ccllPAAAAsZJREFUeNqck1lIVGEUx393thaXCm0qtdJrm4FlONGkWESb"
    "tthDUA9F9dDyFhTRghI9WJpgPgSBD/UWQRvZrg6CSFk5FuJDD+nYTFCmmaDV2Cz3dr7LBEIv"
    "0oE/937nfP/DOed/Pm1XPZMyU2AYNBom5TYNzWYDTXw2KyhRCVjff4iJWDwOv2OU1+5tYDyK"
    "qc7qui1u8EACpnJGYtyVsxVQUP8Zs3QzHMH8JfDq0Nl3jIrycyqZKRWhldZiXt1XQSQeo6PP"
    "j/9jP6HhgKbKm5+mmx5dx5tbKFVoAged/VXYpe7Zyfu45ruJQ93sDF4kHAXvovOkp6zmec9t"
    "q5kdBfvJmeugI3AeK6Mq2SGQBCPhkHW2L97IoXchZqYmwc9oG0vmFZAydSHBbwE2r9LpDF0i"
    "OAhdfeAUonuWkH/o3HvVTdNpPPZeH74+Hzdc+ZTNSGbGOG/IdS9jqtPNrVfXZdzwoptg40k2"
    "TVnF0bSZTlreDtN8Bk95PV12kXFo6Va+PDtDiy2fw0nTscftPeS4c0hx5fL4dW+ktZL1O+vo"
    "joYpDQ4ZWU2KfIUu1ZZNNdt4wmRzNfcPbNzuGh7RCQxA/+gTFmT8ZE9JkUtidx6elJtOvHUH"
    "G9hUjf+vWjYjTuuWGs3cXVK8OCtzjOKiAP2SIPgVPofbUb7t3uV5G6o0c+1KGfiQyLhHZIwm"
    "ZCy7jHn8QB7x2DSGwm8JfYIvId2a8NzMANlZkOpaRMwYs6Qc+z2AbCJuh8j4SGRU+zhivCcm"
    "9QQ/w8sOBpsrA9tUgi0XeSJDnKNn92IkFktLyPg9IaNWWoVfc1GoVjYe5nXLBY7IYHuwZkN+"
    "WQ2twktX5OI1IHvFyIDO07YAzWfxqPVYIkhJrP6okD9MfAuSZAVqfGLSrn9diYu29gjPEzJq"
    "k32NysZHaXUmseHxKTzC6+I/LFdQONHxR4ABANuzKntCBWfVAAAAAElFTkSuQmCC")

#----------------------------------------------------------------------

_html_back = PyEmbeddedImage(
    "iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAAABGdBTUEAAK/INwWK6QAAABl0"
    "RVh0U29mdHdhcmUAQWRvYmUgSW1hZ2VSZWFkeXHJZTwAAAavSURBVHjaYvz//z/DQAKAAGJi"
    "GGAAEEAD7gCAAGJBF2Bk7IM6jRGIgTQzkGZG5wMxI0g3mNZh+PGnmoGbhZWBhSkXKPocbth/"
    "qBd5mSFqQUJn0lDsAwgg0kMAlmQYGdgYvv3OZPr2e3dgoFqEsqJAIMOvf9YMf4EKQPgPVCE3"
    "M8QROABAAJHuAJBH/v1XZnj/c620NO+0hbO9JNbN8WIQFmBnYPgNtPkf1AEgddxMEBoPAAgg"
    "FhItZ2T48Tea4d+/1thEXbm6SgsGFQV+hr9//zH8+vUXET6gKAJZzoQUYjgAQAAR7wBGRh6G"
    "Tz87BES5sjo67BjTE3XBpv/5/QfVDlBa4QD5nBFiOYEQAAggFuKCnEGN4du3OYamUrbTp7sx"
    "mBtLAA3/y/D6838GHrb/DMzMYFv+AS3/y8AODXYiixeAAGIhaPnvvx6MDH+nxyYbKvR02DGI"
    "inAy/Ab6evk1RobHn5gYik1/M/z/x8jw/dsfJoavv52Awc4B1McBzz2MUJqViYmBk+UskHUJ"
    "2QqAAGIhYHksUP/Mtk5HzrISU3Dovvn6h2H6OWaG/Q8ZGSwlfjMw/vvLwMjMwqCnKcLEyciY"
    "x8rNnAdPB8wQg5hZGYGx95vh5vMvt4ECasjWAAQQC07L//6J5uBknD1hoht7eqoeOISvv/7P"
    "MOUMM8Ojj4wMXMDQZvz7lwFUkv8H0gt6HYA57z9S2IMkgJkCmCM42VkYjlx5wxCav0sc3SqA"
    "AMLugP//XFlYGKdPnebBnpSgAzbs8MP/DLMuMAF9wsjAyfyH4dOPX8Co+Mvw5y8TEAMdAwyq"
    "/wwgC/8BMwmQ/vcPaAwwkQL5jH9ZGNiY/4Ni4ze6VQABhM0BssCwn1BX78ALsfwfw9ZbjAxz"
    "LjCDo5MD6PPfP/8wMP39w3Dr5R+Gks1/GP78ATrk1x9goAHZv3+Dc8ZfIP785ReDixY3Q5aH"
    "ONhh2Oo9gADC4oBfma6uKlqlJWZg3r77DAxzLgLjEZi4mYHx/fPXb4a/QPwfaNlHYLw+f/0L"
    "bPFvIPsPVO43CAP57z/9YFARYYJnCmw5EiCAsDiAMTA2VoeBg4OZ4dqrvwzzLjKDNTIBs92v"
    "XxBLYPgf0Lcs//8AAwlYFgAxA5T9D0Qz/GFgBdJM//8x/AVFx///WHMmQABhcwAbOzs4+TJ8"
    "/fWf4TvIXGBw/wYF769fSA6ABvcvSJCD2UBf//6NcCAoJEChAw97LEEAEEBY6oJ/O9atuwku"
    "Xk2l/zOEqf5i+PztD8Ovn7+gFiHwb6Ajvn//DcS/oPg3Ev83sOz6BdT3G54gsQUBQABhcQDr"
    "tJUrrz2ZM/cK0MWsDMHqfxlC1IDx/fU3w48fv8GJC+T738DQALqCgYf1LxD/A+L/DLxs/xh4"
    "gWxetv9gzM/BwMAOrIaB9uMEAAGELQquAmO8qrR0/wI5OT4mTw8FhjiDr8CijYlhzrHfDD+B"
    "IcEKTA9fvv5i0JdiZqjyEgPmAmDWA8Ux0JegkINkxX9gNsgB3378AacBRixRABBAOAoi5sWf"
    "P/2Uio/f0jF/gTeDt6c8Q7TBPwYBVnaG3j3fGd5+/AlM7X8YmP8zMkjyMwPrAjZgomUFp3Ww"
    "Q6COAcX9L5AjWJkZ2N//Bkkzo1sFEEC4i2Im1s7Xr76zRkdtapw+y50pMlSVwRtYAYpy8TG0"
    "bXnDcPzmd4afEsBE+usfAzcPG0NV33mGOw8+MrBwAI1kBDqAEdqCAlKsbEwMrz78YPj8+993"
    "dGsAAogFZ6sHFFysLC0fP/x+kZywvff69bd8ZSWGDBaq3Ax9Yf8Zujb/Y3gDCglwqfefYcue"
    "h/9un3+5DJgYzgP1sqNURiBbWJhZgc22U+hWAQQQC8HmFwfLnO9//t9trj8y5/z5l0oT+u0Y"
    "VGV5GBoCGRhuPPvO8Os3JIVzcQNTHzfragYulk3gWgvdAUzYGwYAAcREVBuQhXE/Aw+H45YN"
    "d7a4eW1k2HHoJYOkFB+DvgI3uCL69/8fxKz/QKt+487z2ABAADGR0Bx7xMDPHnrvzoe6oPAt"
    "Xxs6zzL8+s/MICTICY4GFAf//E9UawgEAAKIeAdAatofwDhu/vmPwaO16eQF/+gdDFdufWYQ"
    "F+EG1xVwK0EO+v4PVI8RbB0BBBB5HRMWpiMM/GxO58687PMK2/qjqPkkMK8D62VmRhZIxcEA"
    "KX6//SMYEgABxIjeNySqYwJjgzob//87M/z+V8PIw8L0n4kxGSh6B6NjAmohs0D0oXdMAAKI"
    "caA7pwABNOB9Q4AAGnAHAAQYABaU9vBbRzekAAAAAElFTkSuQmCC")

#----------------------------------------------------------------------
_html_forward = PyEmbeddedImage(
    "iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAAABGdBTUEAAK/INwWK6QAAABl0"
    "RVh0U29mdHdhcmUAQWRvYmUgSW1hZ2VSZWFkeXHJZTwAAAbWSURBVHjaYvz//z/DQAKAAGJi"
    "GGAAEEAD7gCAAGJBF2A0mQVlAPGPfwwMv/9D2HAFDHwMf/9PZfjyR5CBnaWZ4f//kwx/geL/"
    "gOqAyoFyDHD+XySxfxCx/78KUewDCCDcIQBKGqxAm9FV/P6nK8zHHuPqrODN/PvvHobvf6qB"
    "ouzkhgBAAOGPAmagAziYUcX+/mfiYGJkmNHuyLB6jjePoix/C8P7H7uAIaFLjgMAAgi/A/5D"
    "VXCgKvsDDNI/v/8xBLorMezbEMwQm6hnx/jlz25gaBQApdlIcQBAABGXCBmBIcHKhOY2cKQy"
    "KEjzMCyY6Mowa5qbuIggRz/D518LgelElFgHAAQQcQ74D02ULODU+B2SFoEJCpjYnn8EEkBG"
    "SrQ2w54tIQzG5pIRDG+/bwcmOG1ijAYIIBYsYqoMP//aMPwBJllGBkgpBfLsHyDz//8/DN/+"
    "aPzhYGUAFWCMjP8Y5l9iYpDiZWCI1PnDoK8lwrBrfTBDec0h4znTL+wB5pJ8BhamVfgcABBA"
    "LFh8u1pJhldfkJsNmN7+Qzz/D5q1gNTv738ZRPnYGdhYmBj+//vH8AuYTRdfYWV4+JGRIcXw"
    "L4O0ABvDrMmuDEqKAhK1VYdW/P3zX4iBlXkGAwP2EhcggDDLgb//lDpLzBm8rKQYvn7/A8wI"
    "jAyMTEyQogCUFoAsZmDEsQNzyM8fv4Ehw8TAARQ//ZyF4elnZoY8078MOuIMDJXFpgwS4lyM"
    "mem7J//89YedgZl5IjYHAAQQtjTwix3ou38/fwN9+4vhN9CS30D2319/GP79AQbDXwj9/ecf"
    "hr/AqPnz5w/Dn5+/GLiY/jC8+sbA0HaMmeHgfUZwcCXGaDNMmeLCws7C2Mfw+68fNgcABBC2"
    "NAA09C/Q5/8Zdl34wLDsxEcGbk5WBlY2VgZmVhYghtCsrMwMLGwsQEuZGZiBOe/Xr98MbMAM"
    "+PMPC8OEM0wMX4DZ1FvtH0NKog7Dly+/mArzdk9lYGa7DjT+NrJdAAHEgjPnAfHL978YTt36"
    "yMDLA4xzdjYGFnaIQ1hY2cCWswDZXMAEycbByPDnFySNsAHLREYmFobZF5iA6e8fg7vKf4bc"
    "LEOGzZvuyOzb8yAHqCof2R6AAMKaDf8BE98/UMIDJn9WIAYmRwYWYFZj+fcHin/D2f9AUQD0"
    "PQyDoosJJAc0eR4wh1x79Q8Y/YwMWdmGIG85otsFEEA4Q+Df/3/A6P4DNPAnw282RqQCAZQb"
    "EWn6P3JhAW1bgPIOCzA6vv1lYfj8EyLGzQ0qIBkxSkmAAGLBXfiAiltgYvv2m4EV6B1Q+mMB"
    "hgorMOExQ9l/gGwOROaAF5ogKz//YmKI1PvHYC4JEV+8+AoodZ1BtwYggPCEwH9gNfCfgYv5"
    "HwM7MC5ZgZgZRDMCowJoCwsjMI4ZQFHAyPCbEVpi/YfUwsBAYwjRY2KI1QFWZCycDBs332NY"
    "tvj6F2CwzEC3ByCAWHAVvZ+//WFwNxJisNISAFrMyMDEwszABKKBZQIzEINoUMj07P7AcO7J"
    "LwY+oM+/g0pLYLDEmrIyJBoDywpODoaDRx4zpKbtAJlay8DEeATdKoAAwuIARmZ2NiYGIQFO"
    "Bk5gCmdnA1oMCldQgQRqHgAtBjF+AsuB37/+AhPoP3A6+Qh0NScnG0O+HTdDqBEbAycvJ8OJ"
    "0y8YoqO3Mrx+8WUaAwfbBHDwoAGAAMJwwH9mhi89S64KrN7Lw/D7DyJRMf5jBIfvn1//GIR5"
    "2BhKU3UZQOnqBzDVv/v0i0FXHijmxcvgqMEBtnzzjgcMSUk7Gd68+DaJgYu9BJxAmRkxHAAQ"
    "QCxYqt7kg8eeOQOD8i+8KfYXXhkBU+VfWWEhzvjUCHUGHhF2hq/ffjG4AC2t8hdm0JDhYmBk"
    "52DomXKBoa766O/v3/+0MfCyNgL14mx6AwQQtjSwC9gK2gUKCkSKhDoAFIRMzMYsPKzxoGQH"
    "LOMZkh2EGXTlOBmkxHkYPn7/z1BavJ9h4dwrbxk4WDIZOFlWMxBo9QMEEAtJ7SdIUucCB8o/"
    "SGFlpsLFICjCw3D64juGvPIjDOeOPTvPwM+WBFR7AdwYJQAAAog4B8BatshCQMt5uYHamVkZ"
    "Jsy+ztDWc/rPxzc/FjEIsFcB1b8kxnIQAAgg/A5ghMX/PwxhEWFOhudvfjPkNRxm2Lf9wTNg"
    "cOcx8LGtBVtMQmcLIIDwOwBcqqCZBsyT/4DlQe/cKwxr19358/LZlw0MvGxlQFfdBzuWRAAQ"
    "QCx44/sHFq+wMt1+9fHn8Wmzr/ADi8NuBl72pcAE+htbHicGAAQQ40B3TgECaMD7hgABNOAO"
    "AAgwANtDcqAqYx6xAAAAAElFTkSuQmCC")

#----------------------------------------------------------------------
_html_home = PyEmbeddedImage(
    "iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAAABGdBTUEAAK/INwWK6QAAABl0"
    "RVh0U29mdHdhcmUAQWRvYmUgSW1hZ2VSZWFkeXHJZTwAAAmrSURBVHjaYvz//z/DQAKAAGJi"
    "GGAAEECMDH5SqCL/oe76ywiWZvjHiJD7xwzEULnf/w0Yfv3tY/jPyMPAzFLOwMq2n+EfNDRB"
    "NCMjBP9HNhjqX1CogzAjEwNAAJEXAj+++7Ax/N/QlV/pOLu205Sfk2sVw5fP8eQYBRBALGh8"
    "biD2hdL/gBjoZYYrQHwCEmFAH335ksnLJ9QztbCFK9Y9ECwsJSImktZWNf/p40fyDDz8bUDv"
    "/SHWAQABxMygzovMlwSG0lZg8IQBg8cfSPsBw+kPMCa2AuXYGT5+7FFX1Gxe2TyT1dfKieHb"
    "vy8MP/5+Y9CRV2dws7RjPHP7uuOze3dUGNjYDwCD/zs4CtBiHJXLyAAQQMwMmkDPMv6HYT6g"
    "cAKQwQtTAMS7GP79ucjw6eMCD1uvxGV10xn0lTUY3v15xTD9eQPDng8bGFTZ9BhUxVQYAh3d"
    "GJ69f6N7+fI5awYW1pMMzMyvGf7jdwBAAAEdwAMRh2B+IE4Fsnjh6v/8+cDw80dMgl+C19yy"
    "CQwSgiIMj3/dZZj2vJ7h0pczDK9/vmA4//k4gzSzIoOygAqDn70rw49//+ROXTjt8u/vvwsM"
    "LCyP8DkAIICYGbS5kEOAHxh/qUB1vKAUCrQYyPyn3pRcq9ib2sDAwcrGcOHrMYYpz2sZHv+4"
    "x8DByMXA9J+N4c2vVwyHP+wGahJg0ODRYXA1t2YQExUTOXDqeMDv71+fAUPjEi4HAAQQM4MW"
    "F7IQMAQYgQ5g4mX49plBkE+QYV7xdIZs7wRwbOz+uJph7ssOhs+/PzGw/Odg+PPvL8NvIGb8"
    "z8TwDZgWDr7bxfD91zcGI25LBjMdPQZDbR3OPaeOB319/46RgZ3jEAMDaoSADAUIIGYGQxZ4"
    "+AMTIDBB/E9j+PKeV1VGlWF55SIGbxNnhr/ARL3m3QyGNW9mA9lAZf9YwJb/+fuX4e+/f2D6"
    "P7C8+P+fkeHUx6MMj789ZNDjNAGmFU0GVwsbhtPXLzk8f3hfhoGNYz/Q0l/IDgAIIGYGI6AD"
    "GP9BMtz//7JAy1OsDZy5lpTOZzBR0Wf4+vcTw5zXbQy7368FBzfDf2a45WAMdcBfsGP+A41i"
    "Zjj38RTDxU/nGXTZjRm0ZNUZPG0cGO6+fG5089plfWB0HGdgYvoAKYgYGQACiJlBnx1oKND3"
    "f/9qAYN9boRrgvrigtkM8qIykMT2so7h/JejDGzAwPkHtABm+W+opb+BBsFCAiwG5LMAVd/+"
    "cpPhyLsDDApMygx64noMAY6uDB9+/VA9ff6MOzAizjMwMT8GOQAggCAO+PHNA2j6ivroJp0J"
    "iR0MPOzcDNe/n2WY9qqO4dGPOwxsjNxgn4KD+88fYLz/A1uO7Hs4G0qzAIuN59+fMWx/uYVB"
    "8L8Igw6vNoOvvRODsJCwyP7TR0P/fP/+BFh8XwIIIGYGHYZQCT7xhZNTJ4sXeGUDCztI6fzr"
    "/0+G179eMDz4cZfh/18msM9hFoEtgWK45WD8HxEdQPz9z08GEwFLBh8xfwbO/1wMf3/9YbAz"
    "MWPQVdVkP3nlos+HT5/eAwQQC+P/P01N0a0CCXYx8CoDlCSl2RQZlFh1GPb83cTADDT46+9v"
    "wCD+A/cpPArAFkOj5Q9M7C8DKzAEfgIdoMGlyWAhYsXwg/EH2OCfP34y+Ns5geo4tqjyvDKA"
    "AGL5z8JycNa+WRrbzm4GG/Drx2+GCNsQhiTHBAZOYD4HGSLOIsbgJxoHTIQsQMN/gy0BpQdQ"
    "ovv3HxIKEBrIB3qBGQjXP1/DcPrbWaAZ3KBCnGH/qRMME1bOAUY9KwMLEzPD20+fGX4yMZwG"
    "CCAWoEjFmTvHd535Awyj3wzfGL4y+EiJSiaCHcDMDXYUD4sAQ6RoBrDWZYLkFrw1Jaj0ZGA4"
    "++4Mw6Hfpxn4WIBlGzCjnbxxnmHXno1bGNi55jMws3EyMLMCg4nrIEAAgQqBD8D8uY6BDWjy"
    "X2B2ZPrG8vn3t0SQWSDXg3z98+8vhp//gXXLL2aG1SfWM3wEFlJMTCyQ+PoPKeH+A/WysbAx"
    "BFh4MgiyCYDjHyQnwCoEpl9+eg8s4Dn3M3DwrWMA5hKw4F8GBoAAQlTHsKYZM8PXj9/eAeuf"
    "/wzcwAIR5IA/wGBnZmZm+PjlC0P5wuqfL57e38bAxvkemH1ZIA0WYI356y8XMyefl5WmKZ+Y"
    "hAiQ+xuYDpgYRNiEwRa9//IBZPYXYIIChhAQ/4ckdoAAQjgAVhgxMbz58vUjw8/fvxg4mbjA"
    "raBfwMT3Hxi/oCKXi5PrCwM3VzEDM+d9cPkBw8x/Rbi4uQ0ZGRj5/oPLhD/AEOQBOkCU4d+v"
    "fwwfgGYCwTuwPazAwvA3O7h1BRBATJBS+D8CMzF8+PT90++vv78C0wAXMLA4wCn+Pyy8mcBl"
    "MRMD639EEQ4KvX+/mcH6wSr/g8sLbiAUYBUA6v/N8OUrOATegj3JAgwStp9ghwAEILIMVgCG"
    "QRga3GGTUfb/H9lBy5DutkQPu0t8wYhaNf61NIK+7jli4Nwaml3pRqlPiAI1QlCEaWP6Oa+C"
    "ort891irVXRz7HYgmIcnpsz1fAt12QThLz4BxASOIGTMxPjt/Y93H958ecPAAswyPEyCwJzw"
    "G1GRMUJDAUSD4hOYPsDBCvMIVB0ou3IALedi5QQm2k8M779/BMY/w2eIWqh6oFqAAGICN9+Q"
    "MdP/P79//fz06vMrsIE8THzgwuYf0GugPsR/uGX/EY6BYZAcOD3/B5cNnCycDFwsXAxvPr1l"
    "eP/t00dgSv6GEtpADBBALOCGJioAppD/H958fQvmgNLA59+fGUAJC6wD3EyDWo7cxoCkH0hK"
    "ATrg29/vDHzAKAQ54vWndwyfv3/+AHTAT0hbFwEAAoiFAaNhDqyvGf+/fvvlNZinAixK3/x4"
    "DbQHVN//gzSWURzwH5GLGEGpBFQ0/2Ew4DVgEAXlAKDI2y9Az/z79ZGBhf03epsEIIBYwEGH"
    "CkC2vPz84zOYEyuXxBAjlwhMDyzACuoPsOBkhFjGBPUJPASB2RQozgEs5FjYWRgmW0wChwQT"
    "BxPD5x9fQOkLGAIMv+AOhgKAAGJhwNZyZmJ4dPnZZQYQBid4IASW9sAC4h3Dz3/A4pAJqb0N"
    "YzGB1PxnuvniDlDNTwYmYO8JlG4ef3vJcP7+JZCZTxmYGX+j+xYggBgZMhmxlehqLAwss0RY"
    "hbWAZvyG5D5GUDXM8u7np/dA2gPo3QeQsp8dFgKijIxMm4RYuFSBJeDPf/8h3Tqg41nf//jx"
    "6Off/7lAU46jWwQQQIwD3TsGCKAB7x0DBBgAIYJYB6/AsBcAAAAASUVORK5CYII=")

#----------------------------------------------------------------------
_html_print = PyEmbeddedImage(
    "iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAAAGXRFWHRTb2Z0d2FyZQBBZG9i"
    "ZSBJbWFnZVJlYWR5ccllPAAABwhJREFUeJytl99vVMcVxz9n7tx7d732esHYxmBTfgVRQmg3"
    "OBH9IRGgjUBqoBKoapDIQ9NW4qH0oVL/hPahfegD6kvCcyM1b6nUNhJS0kpNSgW0VUQsEpvy"
    "yxCDbdZe7957585MH3bXNhRcQBzp7OydOXe+59ecc0eOHfsRK5FzbtOOHdt+v3nzhl7nnHuU"
    "3OnTv9oGcPHiRQCq1SqP8yyvvfbGigrkuR09deoHfz94cL9aSa5arS5u/rhUrVbRIrKikIhY"
    "Y6wB4odLeMA/MTi0vNG2amUlHk2uzRZIn2oHtbSBRymNiDyUHw7uF5WoVvc8MXi1WkXn+TTe"
    "e7wXoqibMCzj/RKg9w8LvV8G3vn/dKRBEAFrDc3mXZwzFItDiLCoWBAED4DbBxRwT50DeulR"
    "UEqTZfPkuWX16k2IBEC2LAT3gy4PwdPS//hXqYA0rVGr/Yf5+RuAaSgVtn3slrG/77lzrp+E"
    "qtXqcg8skUhAltURqessM99RSoVLCiyP/zPJgRZ573HO4j3rjMl2WRus7+oq7t21a8cJrTti"
    "HcBnnAPee+WcO1YuV04MD4/s3rp1W19//9poeHgdE+MTOJO0X5E2YGeEZ+IB793Pjxw5+stX"
    "XjlAX18/hUIMCKFWnPvHBRI9yMD1BUzeRPBYZxHpALc88ObRA09Xio0xz+3c+cLPjh8/0U7A"
    "JknSIAg0SSNBFbvoHtnKzEKOtCMmEiIC0j7CatmGT9yMDh06+NOTJ3/ym/37v029Po+I4D1E"
    "Ucjs9B3+eO5TvnHwIHgB33J1IKCkZXtiweRggMx6jAPrQMKAz879jT2DEeXeARpJwke1T+mh"
    "i73DX+GTsX/x9pnTv9alUmnnyMgI3ju0Xio4QaBI04Ssdz2XZhU4hxYQgbqB6RRqiWc+B+Pa"
    "unnfygYBJxDYNXxd1+kqhixkDTJnWVdZQxDC2qEhyuXeL+uenvJzfX19iLRAQbDWkTUT6onh"
    "C7WKuTpEXriTwOVZuNnwJA6Ub4Wgjbn4i0AOhHM9HM3n2RAJfb1lvlf5Jg6LE0df32oGBgaH"
    "daVSWdvT041SglKKLMtpNlPiAGqpZ9oVUXX4523h0jTUc1qy/6eBOgHVKHBlNmd0a0DmwOMQ"
    "hEAp4riLSqW3or2X0txck8HBIkoJ1lq0VsSh4m7dMFMv8vEETN6jlW3ymMVXwCUlJmYErVs5"
    "1TESIMtynJNQp6nhwoXPGBhYRV9fD+VyF4VCTKngmLhX4A8fl8gSIGx7WJYA7qMHy4IH0ojx"
    "VRXiOMCokCTJmJurc+dOjXv3mtTrCVopZQCmpmpMTc0ShiHd3QUG+0tsW9vLD7+6wJyNuJdq"
    "ZptCrelpGDBWcO1TIUCkoRhCTwyru6ASWypBxsvruxm/do+pu3Xq9YQ0NXjviaIYEXJtrZkN"
    "w2BToVAgz3O89zSbGTdvwfpCysnna+goJohClI4QETInbQWWzI8DiALfKul5js0z8jSlkcLN"
    "W5bMZAAUixEiCqUCnLN1nabJTaX8i8ViAWMMWmvm5mb54IP3McZgbatHdGqACCgRlOqU5HbS"
    "OXDed8RABFEKHQQoJYyOfo21a4cxxhAEAcZkZFlzRue5ueq9oViM0VqI4wJTU9f48MM/kSQJ"
    "pVIXQaDx/gnqfbtKWmtpNpuAY8uWzWzduo0kaaJ1RK3WoNGo39J5nl/JsialUpEkgTiOMCah"
    "u7uboaEhXn/9OKtWrSbPzeMrAARBQJIkvPPO75icnMRaQxxrICaOY6anE7Isvarz3Jy/e/eL"
    "rLu7EGndenFwcIBXXz1EFBV56aVRjLFY22q9znla1xOP9w7nWm5vtfNWY3IOnPNs2dLLgQMH"
    "mZy8yebNGykUQsJQUSgUqdVmybL0ogbOX7586d+HDx8ZrVTKGJPz4ou7KZcHCMOA9euHMcYu"
    "AjjnlgG69lyH7eJanlvK5RL79n2LiYnb7N69nYWFBkEQoFTA2NgnV73nL8Ho6Gg2Pz83myTJ"
    "Xq3jYpYZtbDQYGxsgtHR7QSBxlqLtXYR0FqHc7Y9dtguKtjhLDP09/dy6dLn7XxYYGpqyn70"
    "0V9nzp8/94sgCM5qEUEp9e7Zs3++eP78uRfCMFpnrd51+PB33+jpKRWbzbRtLcu84Bc9sHyu"
    "M+99az5Nc6yFkZEB/9Zbb7+rVPMDa93t6em7Y1EUXRKRpU+yMNTjWsfjMzOzRNHA97dv3/xm"
    "63j5+9ztPQ8Au4coxOL8zMw8GzYMSRh2f3779s3f9vevIQzDxS9t3Ro91sbcuZOTplHXyy8/"
    "f2rjxmENUCoVHpnprXizeESXj8vXCgXNvn17fnzmzJUzN24sjMexJo5b3USnadi2KgAsWsvq"
    "ZrNefu+9969Za91K98aV77VLiyLI9euTYaEQfslaN57nIZ129l9hzBKSSHX0vAAAAABJRU5E"
    "rkJggg==")

#----------------------------------------------------------------------
_html_reload = PyEmbeddedImage(
    "iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAAABGdBTUEAAK/INwWK6QAAABl0"
    "RVh0U29mdHdhcmUAQWRvYmUgSW1hZ2VSZWFkeXHJZTwAAAlZSURBVHjabIvBCYBAEAOT027t"
    "xI/VWJA/i9DkonsfwYEhw8LSNh64EP/kroxbZKnRXzaIJ+62QpMj0qVm4BqN+vN+vNsFEBMD"
    "JeAfIxJm0mf486+D4fvXtUDjlYg1AiCAKHMAAzRkQCH048evONtYhjiHpECGL5+PMPz9E0uM"
    "doAAotwBoCD9Dwzi3//+KosoMizMmsswMXWWJAcjywKGH1/7GRgZ2fDpBgggFiJtEWH4/0+T"
    "4c9/VYa/DNxAH/9j+A+NAnAIMP5m+MGg+PP7b4ZPjI8YorztGcyV9zPFTUwquPXgqjYDpzAo"
    "NF5iMxgggPA74B+DIsOv//lA2pWHm19dVliWmZuVFxLksDTwH5IGfnz7yaAkpMrwluE5w+rf"
    "3Qx+GvkMB1t3MoS2x7oeuXhoIwOnYABQxwt0KwACiBFrLmBkYGP4zVAG9G2lm7YHV5ZtNoOJ"
    "ihEDOycjw1+gZ7EmBSBkYmRiuPLnGMPen4vBhrjxRTDof/dlCG6KZ9h3Zu8JBk4hL4b//98j"
    "5wKAAMLmAE5gcM6SEZKNmRE1g8FOz4rh1I+dDBe+H2X48Oc1w+//v8HW4UoPf///Abr7L1jN"
    "9/9fGOx4fBkcGWIYvCtjGM7dvtLEwMpeD3bAtgdgHQABhB4FzECfz1cSVw7fmbOT4R3/Q4by"
    "h9EMH36/ZvgHdOgfIMRpNxSwMXEwcDJxgh3z5e83hqM/DjIEKqczaMnpMJy7ekGFgZkdRT1A"
    "ALGgpOY//yNFOEXC1yavY7jOcpJhyo1WBmYmFoZ///4yyHEqMejxmjKIsUowIBIBamb4++c/"
    "w9XPFxkufjnF8PPvdwZpDjmGasVJDDNXrmJYtnP5FwZOnuno2gACCDkEhIG+r2sMbGZgFfzL"
    "0H6lloEJaCoT41+GLPlSBjtOL4aL964xPP/wAiQKDQlotAET4u8/vxksFSwYuPgEGFY9XcLg"
    "IOTO0KE4nWHx+i0MBTMrfwB9ngRUfwTdAQABhHDAn/+eEgISKt46XgzVN/MY3n79DLagQbWD"
    "QeOLKUPA9BCG03dPvmD48/cOpChmYmT4zwwJjH+M/xi+/NApiqgTNPVUZPAWDmcolW5iaF8w"
    "k6Fn9cQvDGzc6QxMzKvh8fcXUfwABBDCAT8ZnJ11XRjv/r7FsPHhNnBiC5EOYTD4Z83gPNGZ"
    "4fnrJwsZOHiLGZj+v4XEAFLZDqLZmbf/Yfzj4SsWyKD5w5QhuauEYceJbfcZOAXSgJbvAVv+"
    "H6r2H8IBAAHEgpSPdC0VrRh+/vnBYM1nDwx6ZoZs+QKGlYdWgCw/DgzbFKBlwFQITOEsQIN+"
    "MUJiAGTYP1aQFCMLIwvD5qP7GQpm1TK8fPV8MwOPcDYw2z0GBxO0vEAHAAGEcAAjo8zjj08Y"
    "lN+pMOTwFUFS8YtfDLtu7AN6lnUHMMj/MDACfcH6H2IQB9DQ30DLv3BCkz8Pw9KDmxj61899"
    "9x9UKXHzdTMw/0ZY/B97bQsQQIhyIIX9HPM/JgWmf8C8BilewcXsn79MHMAipgxo+QwG1t+Q"
    "sP/HJAmknwHd+J/hnQDMqD0Mv/7yMTCxZDAw/z/HwAgOZ05oGoGGFDzt/Pm/7+YPkC6AAEKK"
    "Akbrv//+s/wFlfL//kPSC4gGBg0Qf2dg/gsKFHGGv//6gW6QBXJswWoQPstiYGZ5BqS/AC0H"
    "qfUEql3I8P3nH6DF/+AOYGRhYWDjBEYLgzFIE0AAIWfD7wzAohQY+ZAE9h9KM/+BZrdfnkDD"
    "enl4xDS//vh5CF4egYIZ1OD4z3QLGqYQ9b9+i8iLyQpPymoHFkxcDKCAZmT5z3DuzlWG6um9"
    "8FQIEEAsOCIGgln+gAKAi+H79zo2Zo6y1th+RkYmVoaS2YXAtMABzLrAUg3kW2DyAAczI6zV"
    "BMyeXz/aOmpaM/hZ2jLs+r8EmKt+MFgyuTLwsFsy/P3x+z3MKoAAwu4AJnhJJ8vw5dscdUkt"
    "txlpsxgctK0ZZu5ZALQYGDdAh4DTCpZqieHbl2wuTv7oLP8UhgM/NzCsfjMLWEf8Y1CSNmA4"
    "fvEeMMv/fghTDRBACAdgtPP+mzJ8/rHE2yxAbWHmfIbLrPsYzv/Zz/DvF1Dq818tBo4vK4EO"
    "YIImLFhC+wesLpWlhaWNJxX0M0hrsDO0PpnH8O8vG4MIsAiX/KfOsGrvJGC0sR+F2QIQQMiJ"
    "EMnu/7oM335sjHVMlpyWOoFh7ceZDCsfzmQok+9mcFJ3YKiObxJlYeEIgzdSofgfMAUrSioy"
    "2BuZMfwWec3QfC8fWIN+ZPjx7ztDnFQRw8njtxlOXzz3CVivr4dZBRBALFgqFRlgsbo2zS1H"
    "sj+xg6H3cSXD4Xe7gbUcJ8OpV8cZbIR4GHxDbRDBjRxzwDTw5tdzhoUfWxkuXD3NAMrRP//+"
    "ZPCTiGAw+uPBYD01AlixMcwFqrwA0wMQQIhyIIEbmnq/TzZTss7ZUbWBofF+PsPJD4cZ+FkE"
    "wHI/gT75+e8HohLC2iz5D66sQJAFWJNGyCQwRAvmMcTXljOs37vjFAM3jwsoEv8fh7gBIIBQ"
    "0wBE6P3nr58Yvn76ziDAIAoMjO/AopwdmBmAQQxMSH+BDVBGfI1MYOLkZeZlMBI0ZYiWTmb4"
    "85yXwb02leH4aaCNvPwRQPd9RlYPEECYaYCZo/v6g8v2CdMz7JZlzGNg+cfJMPfRVHC7IEIs"
    "nsFbJJDhN7BZxoie8oEiIEeyMbIz8PzjY/j0+hfD9BnbGZZuW8vw/hMwwfIKFADVYbQJAQII"
    "Mw38//+ZgZM/fO+5HVsDeiKMFqbPYhCWF2WoulHKIMEqxfD25k+GCVumMrCxciP1lBghDgDm"
    "hu8/fzM8ev2S4f7zp+//fft6Bljq9TNwcG7H1ZQCCCBEGojlQ3gG3K1ilWP4/HmBhqyu4+zE"
    "KQyP+W4Cs/9vhoenPjPUzqp4zMDOuwiRDZlhPSQmIPsHAxPbQ2A5cRqY2K6gFdcIf56ApAGA"
    "AMLdLP///xEwJLxuPL7V59YWlNkUWs2Q7h7JMIV1CbDu573LwMFdA7EYuRxgRLDBFv/Hk2Ah"
    "ACCACHRMgOUnO0/W91//LpTOr2k9//CKiCCPENBMViZwwxdc7v9Hy46ELUUGAAFERM8IaCAz"
    "yywGDpbDy3avncjIyuXKwMrFimEvmQAggIjsmoFsYrrOwMHl/f8vcyWwWaUI9SbFTgAIMAAF"
    "XnDxjsZXyQAAAABJRU5ErkJggg==")

#----------------------------------------------------------------------

[docs]def FontFromFont(font):
    """
    Creates a copy of the input `font`.

    :param `font`: an instance of `wx.Font`.
    """

    new_font = wx.Font(font.GetPointSize(), font.GetFamily(), font.GetStyle(),
                       font.GetWeight(), font.GetUnderlined(),
                       font.GetFaceName(), font.GetEncoding())

    return new_font

# ----------------------------------------------------------------------------
# HTMLHelpWindow is a frame containing the HTML help page for ShortcutEditor
# ----------------------------------------------------------------------------

[docs]class HTMLHelpWindow(wx.Frame):
    """
    A simple `wx.Frame` container for the basic help provided to L{ShortcutEditor}.
    The help page is actually straightly derived from:

    http://graphicssoft.about.com/od/gimptutorials/tp/keyboard-shortcut-editor.htm
    """

[docs]    def __init__(self, parent, htmlFile):
        """
        Default class constructor.

        :param `parent`: an instance of L{ShortcutEditor};
        :param string `htmlFile`: a valid HTML file containing either the default help
         or your particular definition of help.
        """

        wx.Frame.__init__(self, parent, title=_('Configure Keyboard Shortcuts Help'))

        self.htmlFile = htmlFile

        toolbar = self.CreateToolBar(wx.TB_HORIZONTAL|wx.TB_FLAT|wx.TB_TEXT|wx.TB_3DBUTTONS)
        self.BuildToolBar(toolbar)

        self.html = wx.html.HtmlWindow(self, style=wx.SUNKEN_BORDER)
        self.printer = wx.html.HtmlEasyPrinting()

        box = wx.BoxSizer(wx.VERTICAL)
        box.Add(self.html, 1, wx.EXPAND)

        self.SetSizer(box)
        self.SetAutoLayout(True)

        self.SetIcon(parent.GetIcon())
        self.CreateStatusBar()

        xvideo = wx.SystemSettings.GetMetric(wx.SYS_SCREEN_X)
        yvideo = wx.SystemSettings.GetMetric(wx.SYS_SCREEN_Y)

        self.SetSize((xvideo/2, yvideo/2))

        self.html.LoadFile(self.htmlFile)
        self.Show()

[docs]    def BuildToolBar(self, toolbar):
        """
        Creates a toolbar for L{HTMLHelpWindow} containing the standard browsing
        buttons like `Back`, `Forward`, `Home`, `Refresh` and `Print`.

        :param `toolbar`: an instance of `wx.ToolBar`.
        """

        w, h = _html_reload.GetBitmap().GetWidth(), _html_reload.GetBitmap().GetHeight()
        toolbar.SetToolBitmapSize((w, h))

        toolbar.AddLabelTool(wx.ID_BACKWARD, _('Back'), _html_back.GetBitmap(), shortHelp=_('Back'),
                             longHelp=_('Go to the previous page'))

        toolbar.AddLabelTool(wx.ID_FORWARD, _('Forward'), _html_forward.GetBitmap(), shortHelp=_('Forward'),
                             longHelp=_('Go to the next page'))

        toolbar.AddSeparator()

        toolbar.AddLabelTool(wx.ID_HOME, _('Home'), _html_home.GetBitmap(), shortHelp=_('Home Page'),
                             longHelp=_('Go to the home page'))

        toolbar.AddLabelTool(wx.ID_REFRESH, _('Refresh'), _html_reload.GetBitmap(), shortHelp=_('Refresh'),
                             longHelp=_('Refresh the current page'))

        toolbar.AddSeparator()
        toolbar.AddStretchableSpace()

        toolbar.AddLabelTool(wx.ID_PRINT, _('Print'), _html_print.GetBitmap(), shortHelp=_('Print'),
                             longHelp=_('Print the current page'))

        toolbar.Realize()

        self.Bind(wx.EVT_TOOL, self.OnHTMLToolbar)
        self.Bind(wx.EVT_UPDATE_UI, self.OnUpdateUI)
        self.Bind(wx.EVT_CLOSE, self.OnClose)

[docs]    def OnHTMLToolbar(self, event):
        """
        Handles all the ``wx.EVT_TOOL`` events for L{HTMLHelpWindow}.

        :param `event`: an instance of `wx.CommandEvent`.
        """

        evId = event.GetId()

        if evId == wx.ID_BACKWARD:
            self.html.HistoryBack()
        elif evId == wx.ID_FORWARD:
            self.html.HistoryForward()
        elif evId == wx.ID_HOME:
            self.html.LoadFile(self.htmlFile)
        elif evId == wx.ID_REFRESH:
            self.html.LoadPage(self.html.GetOpenedPage())
        elif evId == wx.ID_PRINT:
            self.printer.GetPrintData().SetPaperId(wx.PAPER_LETTER)
            self.printer.PrintFile(self.html.GetOpenedPage())
        else:
            raise Exception('Invalid toolbar item in HTMLHelpWindow')

[docs]    def OnUpdateUI(self, event):
        """
        Handles all the ``wx.EVT_UPDATE_UI`` events for L{HTMLHelpWindow}.

        :param `event`: an instance of `wx.UpdateUIEvent`.
        """

        evId = event.GetId()

        if evId == wx.ID_BACKWARD:
            event.Enable(self.html.HistoryCanBack())
        elif evId == wx.ID_FORWARD:
            event.Enable(self.html.HistoryCanForward())
        else:
            event.Skip()

[docs]    def OnClose(self, event):
        """
        Handles the ``wx.EVT_CLOSE`` event for L{HTMLHelpWindow}.

        :param `event`: an instance of `wx.CloseEvent`.
        """

        parent = self.GetParent()
        self.Destroy()

        parent.htmlWindow = None
        event.Skip()

# ----------------------------------------------------------------------------
# ShortcutEvent is a special subclassing of wx.PyCommandEvent
# ----------------------------------------------------------------------------

[docs]class ShortcutEvent(wx.PyCommandEvent):
    """
    L{ShortcutEvent} is a special subclassing of `wx.PyCommandEvent`.

    This event gets emitted when the user is about to change a shortcut (via ``EVT_SHORTCUT_CHANGING``)
    and when the user has changed a shortcut (via ``EVT_SHORTCUT_CHANGED``).
    """

[docs]    def __init__(self, evtType, evtId, **kwargs):
        """
        Default class constructor.
        For internal use: do not call it in your code!

        :param integer `evtType`: the event type;
        :param integer `evtId`: the event identifier.
        """

        wx.PyCommandEvent.__init__(self, evtType, evtId, **kwargs)

[docs]    def GetAccelerator(self):
        """
        Gets the shortcut string for which the operation was performed for ``EVT_SHORTCUT_CHANGED``
        and ``EVT_SHORTCUT_CHANGING`` events.

        :return: A string representing the new shortcut string (accelerator).
        """

        return self.accelerator

[docs]    def SetAccelerator(self, accelerator):
        """
        Sets the shortcut string for which the operation was performed for ``EVT_SHORTCUT_CHANGED``
        and ``EVT_SHORTCUT_CHANGING`` events.

        :param string `accelerator`: a string representing the new shortcut string (accelerator).
        """

        self.accelerator = accelerator

[docs]    def GetOldAccelerator(self):
        """
        Returns the previous shortcut string for ``EVT_SHORTCUT_CHANGED`` and
        ``EVT_SHORTCUT_CHANGING`` events.

        :return: A string representing the old shortcut string (accelerator).
        """

        return self.oldAccelerator

[docs]    def SetOldAccelerator(self, accelerator):
        """
        Sets the previous shortcut string for ``EVT_SHORTCUT_CHANGED`` and
        ``EVT_SHORTCUT_CHANGING`` events.

        :param string `accelerator`: a string representing the old shortcut string (accelerator).
        """

        self.oldAccelerator = accelerator

[docs]    def SetShortcut(self, shortcut):
        """
        Sets the shortcut class used for ``EVT_SHORTCUT_CHANGED`` and
        ``EVT_SHORTCUT_CHANGING`` events.

        :param `shortcut`: an instance of L{Shortcut}.
        """

        self.shortcut = shortcut
        self.accelerator = shortcut.accelerator

[docs]    def GetShortcut(self):
        """
        Returns the shortcut class used for ``EVT_SHORTCUT_CHANGED`` and
        ``EVT_SHORTCUT_CHANGING`` events.

        :return: An instance of L{Shortcut}.
        """

        return self.shortcut

# ----------------------------------------------------------------------------
# Shortcut is a class containing the details for a shortcut, whether from
# a menu item, an accelerator or a user-defined shortcut. It behaves like
# a tree, with children and parents.
# ----------------------------------------------------------------------------

[docs]class Shortcut(object):
    """
    L{Shortcut} is a class containing the details for a shortcut, whether from
    a menu item, an accelerator or a user-defined shortcut. It behaves like
    a tree, with children and parents.
    """

[docs]    def __init__(self, label='', accelerator='', bitmap=wx.NullBitmap, help='',
                 menuItem=None, accelId=None):
        """
        Default class constructor.

        :param string `label`: the shortcut label string;
        :param string `accelerator`: the shortcut accelerator string;
        :param `bitmap`: an instance of `wx.Bitmap`, to display along the shortcut `label`
         in the interface tree;
        :param string `help`: the help string for this shortcut, to display in the interface tree;
        :param `menuItem`: if this L{Shortcut} is derived from a `wx.MenuItem`, the `wx.MenuItem`
         to which it should be associated;
        :param integer `accelId`: if this L{Shortcut} is derived from an accelerator in a `wx.AcceleratorTable`
         or from a custom, developer-defined shortcut, it represents the ID it is associated with.
        """

        self.label = label
        self.accelerator = accelerator
        self.bitmap = bitmap
        self.help = help
        self.menuItem = menuItem
        self.accelId = accelId

        self.parent = None
        self.topMenu = False
        self.imageIndex = -1
        self.changed = False
        self.shown = True
        self.position = None

        self.originalAccelerator = accelerator
        self.children = []

[docs]    def AppendItem(self, item):
        """
        Appends a L{Shortcut} item as a last child of its parent.

        :param `item`: an instance of L{Shortcut}.
        """

        item.parent = self
        self.children.append(item)

[docs]    def GetAccelerator(self):
        """ Returns the string accelerator associated with this shortcut. """

        return self.accelerator

[docs]    def SetAccelerator(self, accelerator):
        """
        Sets the string accelerator associated with this shortcut.

        :param string `accelerator`: a string representing the shortcut string (accelerator).
        """

        self.accelerator = accelerator
        self.changed = False

        if self.originalAccelerator != accelerator:
            self.changed = True

[docs]    def HasChanged(self):
        """
        Returns ``True`` if the current accelerator associated with this L{Shortcut} is
        different from the original one, ``False`` otherwise.
        """

        return self.changed

[docs]    def GetBitmap(self):
        """
        Returns the bitmap associated with this L{Shortcut}.

        :note: You should always check if the returned bitmap is a valid one or not::

            bitmap = shortcut.GetBitmap()
            if bitmap.IsOk():
                DoSomething()

         as the default bitmap associated with a L{Shortcut} is `wx.NullBitmap`.
        """

        return self.bitmap

[docs]    def SetBitmap(self, bitmap):
        """
        Sets the bitmap associated with this L{Shortcut}.

        :param `bitmap`: an instance of `wx.Bitmap` (can be invalid, i.e., `wx.NullBitmap`).
        """

        self.bitmap = bitmap

[docs]    def GetLabel(self):
        """ Returns the string label associated with this shortcut. """

        return self.label

[docs]    def IsTop(self):
        """
        Returns ``True`` if this L{Shortcut} is associated with a top-level `wx.Menu`,
        (i.e., in the top `wx.MenuBar` level), ``False`` otherwise.
        """

        return self.topMenu

[docs]    def GetFirstChild(self, item):
        """
        Returns this L{Shortcut}'s first child and an integer value 'cookie'.
        Call L{GetNextChild} for the next child using this very 'cookie' return
        value as an input.

        :param `item`: an instance of L{Shortcut}.

        :return: A tuple with the first value being an instance of L{Shortcut} or ``None`` if there are no
         further children, and as second value an integer parameter 'cookie'.

        :note: This method returns ``None`` if there are no further children.
        """

        cookie = 0
        return self.GetNextChild(item, cookie)

[docs]    def GetNextChild(self, item, cookie):
        """
        Returns this L{Shortcut}'s next child.

        :param `item`: an instance of L{Shortcut};
        :param integer `cookie`: a parameter which is opaque for the application but is necessary
         for the library to make this function reentrant (i.e. allow more than one
         enumeration on one and the same object simultaneously).

        :return: A tuple with the first value being an instance of L{Shortcut} or ``None`` if there are no
         further children, and as second value an integer parameter 'cookie'.

        :note: This method returns ``None`` if there are no further children.
        """

        children = item.children
        if cookie < len(children):
            return children[cookie], cookie + 1

        return None, cookie

[docs]    def GetImageIndex(self):
        """ Returns an integer index to be used in the L{ListShortcut} own `wx.ImageList`. """

        return self.imageIndex

[docs]    def CheckAccelerator(self, item, shortcut, accelerator):
        """
        Checks if a shortcut string entered by the user has already been taken by another entry
        in the L{Shortcut} hierarchy.

        :param `item`: an instance of L{Shortcut};
        :param `shortcut`: another instance of L{Shortcut}, to compare with the previous `item`;
        :param string `accelerator`: the user-edited accelerator string to check.

        :return: An instance of L{Shortcut} if the shortcut string entered by the user conflicts
         with an existing one, ``None`` otherwise.
        """

        child, cookie = self.GetFirstChild(item)

        while child:
            existingAccel = child.accelerator.lower().split('+')
            existingAccel.sort()

            if existingAccel == accelerator and shortcut != child:
                return child

            conflict = self.CheckAccelerator(child, shortcut, accelerator)

            if conflict:
                return conflict

            child, cookie = self.GetNextChild(item, cookie)

        return None

[docs]    def Match(self, filter=u'', item=None):
        """
        Matches this L{Shortcut} label string against the `filter` input variable.

        :param string `filter`: a string to match;
        :param `item`: an instance of L{Shortcut}: its label string is compared with
         the `filter` string to look for a match.

        :return: An instance of L{Shortcut} if the `filter` string is contained in
         the `item` lable, ``None`` otherwise.

        :note: The string-matching is case-insensitive.
        """

        if item is None:
            item = self

        child, cookie = self.GetFirstChild(item)

        while child:

            if filter in child.label.lower():
                self.ShowHierarchy(child)

            self.Match(filter, child)
            child, cookie = self.GetNextChild(item, cookie)

[docs]    def ShowHierarchy(self, item):
        """
        Set the status of this L{Shortcut} ans its parent as `shown` in the
        L{ListShortcut} tree hierarchy.

        :param `item`: an instance of L{Shortcut}.
        """

        item.shown = True
        parent = item.parent

        while parent:
            parent.shown = True
            parent = parent.parent

[docs]    def ResetVisibility(self, item=None):
        """
        Set the status of this L{Shortcut} and its parent as `hidden` in the
        L{ListShortcut} tree hierarchy.

        :param `item`: an instance of L{Shortcut}, used only to make this function reentrant
         (i.e. allow more than one enumeration on one and the same object simultaneously).
        """

        if item is None:
            item = self

        child, cookie = self.GetFirstChild(item)

        while child:
            child.shown = False
            item.shown = False
            self.ResetVisibility(child)
            child, cookie = self.GetNextChild(item, cookie)

[docs]    def Get(self, label, item=None):
        """
        Returns an instance of L{Shortcut} whose label matches the input `label` string.

        :param string `label`: the string label to compare against this L{Shortcut} label;
        :param `item`: an instance of L{Shortcut}, used only to make this function reentrant
         (i.e. allow more than one enumeration on one and the same object simultaneously).

        :return: An instance of L{Shortcut} or ``None`` if no match was found.
        """

        if item is None:
            item = self

        child, cookie = self.GetFirstChild(item)
        retChild = None

        while child:
            if child.label.lower() == label.lower():
                return child

            retChild = self.Get(label, child)
            child, cookie = self.GetNextChild(item, cookie)

        return retChild

[docs]    def GetById(self, id, item=None):
        """
        Returns an instance of L{Shortcut} whose ID matches the input `id`.

        :param integer `id`: an integer ID to compare against this L{Shortcut} id;
        :param `item`: an instance of L{Shortcut}, used only to make this function reentrant
         (i.e. allow more than one enumeration on one and the same object simultaneously).

        :return: An instance of L{Shortcut} or ``None`` if no match was found.
        """

        if item is None:
            item = self

        child, cookie = self.GetFirstChild(item)
        retChild = None

        while child:
            if child.menuItem and child.menuItem.GetId() == id:
                return child
            elif child.accelId == id:
                return child

            retChild = self.GetById(id, child)
            child, cookie = self.GetNextChild(item, cookie)

        return retChild

[docs]    def GetId(self):
        """ Returns this L{Shortcut} ID. """

        if self.menuItem is not None:
            if isinstance(self.menuItem, wx.Menu):
                return 1
            return self.menuItem.GetId()

        return self.accelId

[docs]    def RestoreDefaults(self, item=None):
        """
        Restore the original shortcut string for this L{Shortcut}.

        :param `item`: an instance of L{Shortcut}, used only to make this function reentrant
         (i.e. allow more than one enumeration on one and the same object simultaneously).
        """

        if item is None:
            item = self

        child, cookie = self.GetFirstChild(item)

        while child:
            child.accelerator = child.originalAccelerator
            child.changed = False
            self.RestoreDefaults(child)
            child, cookie = self.GetNextChild(item, cookie)

[docs]    def FromMenuItem(self):
        """
        Constructs this L{Shortcut} starting from a `wx.Menu` or `wx.MenuItem`.

        The attributes needed to properly construct a L{Shortcut} are the label,
        the accelerator string, the help string (optional) and the bitmap associated
        with it (optional).
        """

        if self.menuItem is None:
            return

        menuItem = self.menuItem

        if isinstance(menuItem, wx.Menu):
            label = menuItem.GetTitle()
            accelerator = DISABLED_STRING
            help = ''
            bitmap = wx.NullBitmap
        else:
            label = menuItem.GetItemLabelText()
            accelerator = menuItem.GetItemLabel()

            if '\t' in accelerator:
                accelerator = accelerator[accelerator.index('\t')+1:]
            else:
                accelerator = DISABLED_STRING

            help = menuItem.GetHelp()
            bitmap = menuItem.GetBitmap()

        self.label = label
        self.accelerator = accelerator
        self.help = help
        self.bitmap = bitmap

        self.originalAccelerator = accelerator

[docs]    def ToMenuItem(self, menuBar):
        """
        Dumps this L{Shortcut} into a `wx.Menu` or `wx.MenuItem`.

        The attributes needed to properly dump a L{Shortcut} into a `wx.Menu` or `wx.MenuBar`
        are the label and the accelerator string.

        :param `menuBar`: an instance of `wx.MenuBar`.
        """

        if self.menuItem is None or not self.changed:
            return

        menuItem = self.menuItem

        if isinstance(menuItem, wx.Menu):

            if self.accelerator == DISABLED_STRING:
                label = self.label
            else:
                label = '%s\t%s'%(self.label, self.accelerator)

            menuBar.SetMenuLabel(menuItem.position, label)

        else:

            label = menuItem.GetItemLabel()
            if '\t' in label:
                label = label[0:label.index('\t')]

            if self.accelerator != DISABLED_STRING:
                label = '%s\t%s'%(label, self.accelerator)

            menuBar.SetLabel(menuItem.GetId(), label)

[docs]    def ToAcceleratorItem(self, table):
        """
        Dumps this L{Shortcut} into a tuple of 3 elements:

        * **flags**: a bitmask of ``wx.ACCEL_ALT``, ``wx.ACCEL_SHIFT``, ``wx.ACCEL_CTRL``, ``wx.ACCEL_CMD``
          or ``wx.ACCEL_NORMAL`` used to specify which modifier keys are held down;
        * **keyCode**: the keycode to be detected (i.e., ord('b'), wx.WXK_F10, etc...);
        * **cmdID**: the menu or control command ID to use for the accelerator event.

        :param `table`: a list of tuples, with the above specifications.
        """

        if self.menuItem is not None or not self.changed:
            return

        if self.GetId() is None:
            return

        accelerator = self.accelerator
        accelId = self.accelId

        split = accelerator.split('+')
        modifiers, keyCode = split[0:-1], split[-1]

        inv_Accel = dict(zip(ACCELERATORS.values(), ACCELERATORS.keys()))
        inv_KeyMap = dict(zip(KEYMAP.values(), KEYMAP.keys()))

        base = wx.ACCEL_NORMAL

        for mod in modifiers:
            base |= inv_Accel[mod]

        if keyCode in inv_KeyMap:
            keyCode = inv_KeyMap[keyCode]
        else:
            keyCode = ord(keyCode)

        accelItem = (base, keyCode, accelId)
        table.append(accelItem)

# ----------------------------------------------------------------------------
# ConflictDialog is a subclass of GenericMessageDialog, customized to look
# like the GIMP conflict dialog.
# ----------------------------------------------------------------------------

[docs]class ConflictDialog(GMD.GenericMessageDialog):
    """
    L{ConflictDialog} is a subclass of L{GenericMessageDialog}, customized to look
    like the GIMP conflict dialog. This class is used to resolve shortcut
    conflicts when the user assigns a shortcut that is already taken by another
    entry in the shortcut list.
    """

[docs]    def __init__(self, parent, conflict):
        """
        Default class constructor.

        :param `parent`: an instance of L{ShortcutEditor};
        :param `conflict`: an instance of L{Shortcut}, representing the conflicting
         shortcut.
        """

        transDict = dict(shortcut=conflict.accelerator, item=conflict.label, group=conflict.parent.label)
        message = _('Shortcut "%(shortcut)s" is already taken by\n"%(item)s" from the "%(group)s" group. ')%transDict

        transDict = dict(item=conflict.label)
        extendedMessage = _('Reassigning the shortcut will cause it to be removed from \n"%(item)s". ')%transDict

        GMD.GenericMessageDialog.__init__(self, parent, message, _('Conflicting Shortcuts'),
                                          wx.OK|wx.CANCEL|wx.ICON_EXCLAMATION)

        self.SetOKLabel(_('Reassing shortcut '))
        self.SetOKBitmap(_reassign.GetBitmap())

        self.SetExtendedMessage(extendedMessage + '\n')
        self.SetIcon(parent.GetParent().GetIcon())

# ----------------------------------------------------------------------------
# ListShortcut is a subclass of HyperTreeList, customized to look
# like the GIMP main shortcut list.
# ----------------------------------------------------------------------------

[docs]class ListShortcut(HTL.HyperTreeList, treemixin.ExpansionState):
    """
    L{ListShortcut} is a subclass of L{HyperTreeList}, customized to look
    like the GIMP main shortcut list. This class is used to display the
    shortcut label (with an optional bitmap next to it), its accelerator and
    the help string associated with it (if present).

    This information is displayed in 3 columns inside L{ListShortcut}.
    """

[docs]    def __init__(self, parent):
        """
        Default class constructor.

        :param `parent`: an instance of L{ShortcutEditor}.
        """

        HTL.HyperTreeList.__init__(self, parent, style=wx.BORDER_THEME,
                                   agwStyle=wx.TR_DEFAULT_STYLE|wx.TR_HIDE_ROOT|
                                   wx.TR_FULL_ROW_HIGHLIGHT|HTL.TR_ELLIPSIZE_LONG_ITEMS)

        self.SetBackgroundColour(wx.WHITE)

        self.AddColumn(_('Action'))
        self.AddColumn(_('Shortcut'))
        self.AddColumn(_('Help Label'))
        self.SetMainColumn(0) # the one with the tree in it...

        self.AddRoot('')
        self.CalculateOffset()

        self.selectedItem = None
        self.hookBound = False
        self.filter = u''
        self.expansionState = []

        self.Bind(wx.EVT_TREE_SEL_CHANGED, self.OnSelChanged)
        self.Bind(wx.EVT_TREE_ITEM_EXPANDED, self.OnExpandCollapse)
        self.Bind(wx.EVT_TREE_ITEM_COLLAPSED, self.OnExpandCollapse)

        mainWindow = self.GetMainWindow()
        mainWindow.Bind(wx.EVT_LEFT_DOWN, self.OnLeftDown)
        mainWindow.Bind(wx.EVT_KILL_FOCUS, self.OnKillFocus)

[docs]    def CalculateOffset(self):
        """
        Calculates an offset (in pixels) so that the L{Shortcut} items without
        a bitmap look parallel to the ones with a bitmap.
        """

        dc = wx.MemoryDC()
        dc.SelectObject(wx.EmptyBitmap(20, 20))
        dc.SetFont(self.GetFont())

        space = 0
        text = ''

        while space < 15:
            space, dummy = dc.GetTextExtent(text)
            text += ' '

        dc.SelectObject(wx.NullBitmap)
        self.offset = text

        boldFont = FontFromFont(self.GetFont())
        boldFont.SetWeight(wx.BOLD)

        self.boldFont = boldFont

[docs]    def Populate(self, item=None, shortcut=None):
        """
        Recursively populates the L{ListShortcut} with information from the L{Shortcut} tree.

        :param `item`: an instance of L{GenericTreeItem}. If ``None``, it is defaulted to
         the L{ListShortcut} root item to make this function reentrant (i.e. allow more than one
         enumeration on one and the same object simultaneously);
        :param `shortcut`: an instance of L{Shortcut}. If ``None``, it is defaulted to
         `self.manager` to make this function reentrant (i.e. allow more than one
         enumeration on one and the same object simultaneously).
        """

        if shortcut is None:
            shortcut = self.manager
            item = self.GetRootItem()

        for child in shortcut.children:

            if not child.shown:
                continue

            image = child.GetImageIndex()
            label = child.label

            if image < 0:
                if not child.IsTop():
                    label = self.offset + label

                newItem = self.AppendItem(item, label, data=child)
            else:
                newItem = self.AppendItem(item, label, image=image, data=child)

            if child.IsTop():
                self.SetItemFont(newItem, self.boldFont)

            self.SetItemText(newItem, child.accelerator, 1)
            self.SetItemText(newItem, child.help, 2)

            colour = (child.HasChanged() and [wx.RED] or [wx.BLACK])[0]
            self.SetItemTextColour(newItem, colour)

            self.Populate(newItem, child)

[docs]    def MakeImageList(self):
        """ Builds the L{ListShortcut} image list based on the bitmaps in the L{Shortcut} hierarchy. """

        self.imageList = wx.ImageList(16, 16)
        self.BuildImageList()
        self.AssignImageList(self.imageList)

[docs]    def BuildImageList(self, shortcut=None, index=None):
        """
        Recursively builds the L{ListShortcut} image list based on the bitmaps in the
        L{Shortcut} hierarchy.

        :param `shortcut`: an instance of L{Shortcut}. If ``None``, it is defaulted to
         `self.manager` to make this function reentrant (i.e. allow more than one
         enumeration on one and the same object simultaneously);
        :param integer `index`: the current image index inside the L{ListShortcut} own `wx.ImageList`.
        """

        if shortcut is None:
            shortcut = self.manager
            index = 0

        for child in shortcut.children:
            bitmap = child.GetBitmap()

            if bitmap.IsOk():
                self.imageList.Add(bitmap)
                child.imageIndex = index
                index += 1

            index = self.BuildImageList(child, index)

        return index

[docs]    def GetItemIdentity(self, item):
        """
        Return a hashable object that represents the identity of a L{ListShortcut} item.

        In this implementation this returns the item label.

        :param `item`: an instance of L{GenericTreeItem}.
        """

        return self.GetItemText(item)

[docs]    def OnSelChanged(self, event):
        """
        Handles the ``wx.EVT_TREE_SEL_CHANGED`` event for L{ListShortcut}.

        :param `event`: an instance of `wx.TreeEvent`.
        """

        selectedItem = event.GetItem()

        if selectedItem != self.selectedItem:
            if self.selectedItem is not None:
                pydata = self.GetPyData(self.selectedItem)
                self.SetItemText(self.selectedItem, pydata.accelerator, 1)
            else:
                pydata = self.GetPyData(selectedItem)
                if pydata.GetId() is not None:
                    self.SetItemText(selectedItem, NEW_ACCEL_STRING, 1)
        else:

            pydata = self.GetPyData(selectedItem)
            self.SetItemText(selectedItem, pydata.accelerator, 1)

        self.selectedItem = selectedItem
        self.ShowShortcutText(False)

[docs]    def OnExpandCollapse(self, event):
        """
        Handles the ``wx.EVT_TREE_ITEM_COLLAPSED`` / ``wx.EVT_TREE_ITEM_EXPANDED`` events for L{ListShortcut}.

        :param `event`: an instance of `wx.TreeEvent`.
        """

        event.Skip()
        self.expansionState = self.GetExpansionState()

[docs]    def OnLeftDown(self, event):
        """
        Handles the ``wx.EVT_LEFT_DOWN`` event for L{ListShortcut}.

        :param `event`: an instance of `wx.MouseEvent`.
        """

        if not self.hookBound:
            self.GetParent().Bind(wx.EVT_CHAR_HOOK, self.OnShortcut)
            self.hookBound = True

        currentItem, flags, column = self.HitTest(event.GetPosition())

        if self.selectedItem is None or not currentItem:
            event.Skip()
            return

        pydata = self.GetPyData(currentItem)

        if pydata.GetId() is None:
            event.Skip()
            return

        if self.GetItemText(currentItem, 1) != NEW_ACCEL_STRING:
            self.SetItemText(currentItem, NEW_ACCEL_STRING, 1)
        else:
            self.SetItemText(currentItem, pydata.accelerator, 1)

        event.Skip()

[docs]    def OnKillFocus(self, event):
        """
        Handles the ``wx.EVT_KILL_FOCUS`` event for L{ListShortcut}.

        :param `event`: an instance of `wx.FocusEvent`.
        """

        self.GetParent().Unbind(wx.EVT_CHAR_HOOK)
        self.hookBound = False

        self.ShowShortcutText(False)

        if self.selectedItem:
            pydata = self.GetPyData(self.selectedItem)
            self.SetItemText(self.selectedItem, pydata.accelerator, 1)

        event.Skip()

[docs]    def OnShortcut(self, event):
        """
        Handles the ``wx.EVT_CHAR_HOOK`` event for L{ShortcutEditor}, implemented in L{ListShortcut}
        as it is easier to deal with in this class.

        :param `event`: an instance of `wx.KeyEvent`.
        """

        if self.selectedItem is None:
            # How did we get here???
            event.Skip()
            return

        pydata = self.GetPyData(self.selectedItem)
        currentText = self.GetItemText(self.selectedItem, 1)

        if pydata.GetId() is None:
            # Don't allow to change labels for shortcuts without an ID
            event.Skip()
            return

        self.ShowShortcutText(True)
        textCtrl = self.GetParent().hiddenText

        keyCode = event.GetKeyCode()
        modifiers = event.GetModifiers()

        # If we press backspace with no modifers down, *and* the current text is
        # "New accelerator..." then we reset the accelerator to "Disabled"
        if keyCode == wx.WXK_BACK and modifiers == 0 and currentText in [NEW_ACCEL_STRING, DISABLED_STRING]:

            accelerator = DISABLED_STRING

            if not self.FireShortcutChanging(pydata, accelerator):
                return

            pydata.SetAccelerator(accelerator)
            self.SetItemText(self.selectedItem, pydata.accelerator, 1)

            colour = (pydata.HasChanged() and [wx.RED] or [wx.BLACK])[0]
            self.SetItemTextColour(self.selectedItem, colour)

            self.ShowShortcutText(False)
            self.FireShortcutChanged(pydata, accelerator)

            return

        newContent = ''

        for mod_int, mod_name in MODIFIERS:

            if modifiers & mod_int == 0:
                continue

            newContent += mod_name + '+'

        if newContent.strip():
            textCtrl.ChangeValue(newContent)

        accelerator = ''

        if keyCode in KEYMAP:
            accelerator = newContent + KEYMAP[keyCode]
        else:
            try:
                toChar = chr(keyCode)
                accelerator = newContent + toChar
            except ValueError:
                pass

        if accelerator:

            if not self.FireShortcutChanging(pydata, accelerator):
                return

            if self.AcceptShortcut(pydata, accelerator):

                pydata.SetAccelerator(accelerator)
                self.SetItemText(self.selectedItem, pydata.accelerator, 1)

                colour = (pydata.HasChanged() and [wx.RED] or [wx.BLACK])[0]
                self.SetItemTextColour(self.selectedItem, colour)

                self.ShowShortcutText(False)
                self.FireShortcutChanged(pydata, accelerator)

[docs]    def AcceptShortcut(self, shortcut, accelerator):
        """
        Returns ``True`` if the input `accelerator` is a valid shortcut, ``False`` otherwise.

        :param `shortcut`: an instance of L{Shortcut};
        :param string `accelerator`: the new accelerator to check.

        :note: Conflicting shortcuts are handled inside this method by presenting the user with
         a conflict dialog. At this point the user can decide to reassign an existing shortcut
         or to back away, in which case this method will return ``False``.
        """

        sortedAccel = accelerator.lower().split('+')
        sortedAccel.sort()

        conflict = self.manager.CheckAccelerator(self.manager, shortcut, sortedAccel)

        if conflict is None:
            return True

        dlg = ConflictDialog(self.GetParent(), conflict)

        if dlg.ShowModal() == wx.ID_OK:
            self.DisableShortcut(conflict)
            dlg.Destroy()
            return True

        dlg.Destroy()
        return False

[docs]    def DisableShortcut(self, conflict, item=None):
        """
        If the user decides to reassign a shortcut to another item, this method will disable
        the conflicting shortcut (by putting a "Disabled" string as its accelerator).

        :param `conflict`: an instance of L{Shortcut} to reset;
        :param `item`: an instance of L{GenericTreeItem}. If defaulted to ``None``, it is set
         to the L{ListShortcut} root item and used only to make this function reentrant
         (i.e. allow more than one enumeration on one and the same object simultaneously).
        """

        if item is None:
            item = self.GetRootItem()

        child, cookie = self.GetFirstChild(item)

        while child:
            if child.GetData() == conflict:
                conflict.SetAccelerator(DISABLED_STRING)
                self.SetItemText(child, conflict.accelerator, 1)

                colour = (conflict.HasChanged() and [wx.RED] or [wx.BLACK])[0]
                self.SetItemTextColour(child, colour)
                return

            self.DisableShortcut(conflict, child)
            child, cookie = self.GetNextChild(item, cookie)

[docs]    def FireShortcutChanging(self, shortcut, newAccel):
        """
        Fires the ``EVT_SHORTCUT_CHANGING`` event for L{ListShortcut}.

        The event propagation (and thus the shortcut renaming by the user) can be
        interrupted by *not* calling `event.Skip()` in your handler for this event.

        :param `shortcut`: an instance of L{Shortcut} that is about to be renamed;
        :param string `newAccel`: the new accelerator just entered by the user.
        """

        event = ShortcutEvent(wxEVT_SHORTCUT_CHANGING, self.GetId())
        event.SetShortcut(shortcut)
        event.oldAccelerator = shortcut.accelerator
        event.accelerator = newAccel
        event.SetEventObject(self)

        if self.GetEventHandler().ProcessEvent(event):
            # the caller didn't use event.Skip()
            return False

        return True

[docs]    def FireShortcutChanged(self, shortcut, newAccel):
        """
        Fires the ``EVT_SHORTCUT_CHANGED`` event for L{ListShortcut}.

        :param `shortcut`: an instance of L{Shortcut} that has been renamed;
        :param string `newAccel`: the new accelerator just entered by the user.
        """

        event = ShortcutEvent(wxEVT_SHORTCUT_CHANGED, self.GetId())
        event.SetShortcut(shortcut)
        event.oldAccelerator = shortcut.accelerator
        event.accelerator = newAccel
        event.SetEventObject(self)

        self.GetEventHandler().ProcessEvent(event)

        return True

[docs]    def ShowShortcutText(self, show):
        """
        Shows/Hides a `wx.TextCtrl` used to display the combination of keystrokes the user
        has entered. This `wx.TextCtrl` remains visible only for a short amount of time
        and only when some keys are down.

        :param bool `show`: ``True`` to show the `wx.TextCtrl`, ``False`` to hide it.
        """

        textCtrl = self.GetParent().hiddenText

        if show and not textCtrl.IsShown():
            textCtrl.Show()

        elif not show and textCtrl.IsShown():
            textCtrl.Hide()

[docs]    def SetFilter(self, filter=u''):
        """
        Sets the `filter` string against all the shortcuts in the L{ListShortcut} are matched.

        :param string `filter`: a string to match.
        """

        self.filter = filter

        self.manager.ResetVisibility()
        self.manager.Match(filter)
        self.RecreateTree()

[docs]    def RecreateTree(self):
        """ Recreates the entire L{ListShortcut} (columns excluded). """

        self.Freeze()
        self.DeleteAllItems()
        self.AddRoot(u'')

        self.Populate()

        if not self.expansionState:
            # Only the root item
            self.ExpandAll()
        else:
            self.SetExpansionState(self.expansionState)

        self.Thaw()

[docs]    def HasFlag(self, flag):
        """
        Overridden from `wx.Window` as a workaround on the conflicts between `treemixin` and
        L{HyperTreeList} with the ``wx.TR_HIDE_ROOT`` `agwStyle` set.

        :param integer `flag`: an integer bit flag specifying the `agwStyle` style.

        :return: ``True`` if the L{ListShortcut} has the input `flag` set, ``False`` otherwise.

        :note: Overridden from `wx.Window`.
        """

        return self.HasAGWFlag(flag)

# ----------------------------------------------------------------------------
# ShortcutEditor is a subclass of wx.Dialog, customized to look
# like the GIMP main shortcut dialog.
# ----------------------------------------------------------------------------

[docs]class ShortcutEditor(wx.Dialog):
    """
    L{ShortcutEditor} is a widget that allows the user to customize and change keyboard
    shortcuts via a dialog. It can be used to edit `wx.MenuItem` shortcuts or accelerators
    defined in a `wx.AcceleratorTable`.

    The interface itself is very much inpired by the GIMP shortcut editor:

    http://graphicssoft.about.com/od/gimptutorials/tp/keyboard-shortcut-editor.htm

    There are very few minor UI differences between L{ShortcutEditor} and the GIMP one,
    although the behaviour should be pretty much equivalent.
    """

[docs]    def __init__(self, parent):
        """
        Default class constructor.

        :param `parent`: an instance of `wx.Window`, it can also be ``None``.
        """

        wx.Dialog.__init__(self, parent, title=_('Configure Keyboard Shortcuts'),
                           style=wx.DEFAULT_DIALOG_STYLE|wx.RESIZE_BORDER)

        self.htmlFile = os.path.join(DATA_DIR, 'default_help_text.html')
        self.htmlWindow = None

        self.CreateWidgets()
        self.DoLayout()
        self.BindEvents()

        if parent is not None and isinstance(parent, wx.TopLevelWindow):
            self.SetIcon(parent.GetIcon())

        self.Init()

[docs]    def CreateWidgets(self):
        """
        Creates all the widgets needed to populate the interface, such as buttons,
        texts and, most importantly, L{ListShortcut}.
        """

        self.topStatic = wx.StaticText(self, -1, _('&Search:'))
        self.searchText = wx.TextCtrl(self, -1, '')

        clearBmp = _clear.GetBitmap()
        self.clearButton = wx.BitmapButton(self, wx.ID_CLEAR, clearBmp, style=wx.NO_BORDER)

        self.listShortcut = ListShortcut(self)
        self.hiddenText = wx.TextCtrl(self, -1, '', style=wx.BORDER_THEME)

        w, h, d, e = self.hiddenText.GetFullTextExtent('Ctrl+Shift+Alt+q+g+M', self.hiddenText.GetFont())
        self.hiddenText.SetMinSize((w, h+d-e+1))

        defaultBmp = _default.GetBitmap()
        self.defaultButton = buttons.ThemedGenBitmapTextButton(self, wx.ID_RESET, defaultBmp,
                                                               _('Restore Defaults '), size=(-1, 29))

        self.infoBitmap = wx.StaticBitmap(self, -1, _info.GetBitmap())

        message = _('To edit a shortcut key, click on the corresponding row\n' \
                    'and type a new accelerator, or press backspace to clear.')

        italicFont = wx.SystemSettings.GetFont(wx.SYS_DEFAULT_GUI_FONT)
        italicFont.SetStyle(wx.ITALIC)

        self.infoStatic = wx.StaticText(self, -1, message)
        self.infoStatic.SetFont(italicFont)

        okBmp = _ok.GetBitmap()
        cancelBmp = _cancel.GetBitmap()
        helpBmp = _help.GetBitmap()

        self.okButton = buttons.ThemedGenBitmapTextButton(self, wx.ID_OK, okBmp, _('OK'))
        self.cancelButton = buttons.ThemedGenBitmapTextButton(self, wx.ID_CANCEL, cancelBmp, _('Cancel'))
        self.helpButton = buttons.ThemedGenBitmapTextButton(self, wx.ID_HELP, helpBmp, _('Help'))

        self.okButton.SetDefault()

[docs]    def DoLayout(self):
        """ Lays out the widgets using sizers in a platform-independent way. """

        mainSizer = wx.BoxSizer(wx.VERTICAL)
        topSizer = wx.BoxSizer(wx.HORIZONTAL)

        mainSizer.Add((0, 5))
        topSizer.Add(self.topStatic, 0, wx.RIGHT|wx.ALIGN_CENTER_VERTICAL, 5)
        topSizer.Add(self.searchText, 1, wx.RIGHT, 5)
        topSizer.Add(self.clearButton, 0, wx.ALIGN_CENTER_VERTICAL)

        mainSizer.Add(topSizer, 0, wx.ALL|wx.EXPAND, 10)
        mainSizer.Add(self.listShortcut, 1, wx.EXPAND|wx.LEFT|wx.RIGHT, 10)
        mainSizer.Add((0, 5))

        hiddenSizer = wx.BoxSizer(wx.HORIZONTAL)
        hiddenSizer.Add(self.hiddenText, 0, wx.LEFT|wx.RIGHT|wx.RESERVE_SPACE_EVEN_IF_HIDDEN, 10)
        hiddenSizer.Add((1, 0), 1, wx.EXPAND)
        hiddenSizer.Add(self.defaultButton, 0, wx.EXPAND|wx.LEFT|wx.RIGHT, 10)

        mainSizer.Add(hiddenSizer, 0, wx.EXPAND|wx.BOTTOM, 5)

        centerSizer = wx.BoxSizer(wx.HORIZONTAL)
        centerSizer.Add(self.infoBitmap, 0, wx.ALIGN_CENTER_VERTICAL|wx.RIGHT, 10)
        centerSizer.Add(self.infoStatic, 1, wx.ALIGN_CENTER)

        mainSizer.Add(centerSizer, 0, wx.TOP|wx.BOTTOM|wx.RIGHT, 10)

        otherSizer = wx.BoxSizer(wx.HORIZONTAL)
        # Add the fancy buttons
        otherSizer.Add(self.okButton, 0, wx.ALL, 10)
        otherSizer.Add((0, 0), 1, wx.EXPAND)
        otherSizer.Add(self.cancelButton, 0, wx.LEFT|wx.TOP|wx.BOTTOM, 10)
        otherSizer.Add(self.helpButton, 0, wx.ALL, 10)
        mainSizer.Add(otherSizer, 0, wx.EXPAND|wx.TOP, 5)

        self.hiddenText.Hide()
        self.SetSizer(mainSizer)
        mainSizer.Layout()

[docs]    def BindEvents(self):
        """
        Binds a few events we will need to process:

        * ``wx.EVT_TEXT`` for the label filtering;
        * ``wx.EVT_BUTTON`` for clearing the filtering, for the HTML help window and
          to reset all the shortcuts to their defaults.
        """

        self.searchText.Bind(wx.EVT_TEXT, self.OnSetFilter)
        self.clearButton.Bind(wx.EVT_BUTTON, self.OnClearFilter)

        self.defaultButton.Bind(wx.EVT_BUTTON, self.OnRestoreDefaults)
        self.helpButton.Bind(wx.EVT_BUTTON, self.OnHTMLHelp)

[docs]    def Init(self):
        """ Common initialization procedures. """

        self.manager = Shortcut()
        self.listShortcut.manager = self.manager

[docs]    def FromMenuBar(self, topWindow):
        """
        Builds the entire shortcut hierarchy starting from a `wx.MenuBar`.

        :param `topWindow`: an instance of `wx.TopLevelWindow`, containing the `wx.MenuBar`
         we wish to scan.
        """

        def MenuItemSearch(menu, item):

            for menuItem in menu.GetMenuItems():
                label = menuItem.GetLabel()

                if not label:
                    # It's a separator
                    continue

                shortcutItem = Shortcut(menuItem=menuItem)
                shortcutItem.FromMenuItem()

                item.AppendItem(shortcutItem)

                subMenu = menuItem.GetSubMenu()

                if subMenu:
                    MenuItemSearch(subMenu, shortcutItem)

        position = 0

        for menu, name in topWindow.GetMenuBar().GetMenus():

            shortcutItem = Shortcut(menuItem=menu)
            shortcutItem.topMenu = True
            shortcutItem.position = position
            shortcutItem.FromMenuItem()

            position += 1
            self.manager.AppendItem(shortcutItem)
            MenuItemSearch(menu, item=shortcutItem)

[docs]    def ToMenuBar(self, topWindow):
        """
        Dumps the entire shortcut hierarchy (for shortcuts associated with a `wx.MenuItem`), into
        a `wx.MenuBar`, changing only the `wx.Menu` / `wx.MenuItem` labels (it does **not** rebuild
        the `wx.MenuBar`).

        :param `topWindow`: an instance of `wx.TopLevelWindow`, containing the `wx.MenuBar`
         we wish to repopulate.
        """

        def MenuItemSet(shortcut, menuBar):

            child, cookie = shortcut.GetFirstChild(shortcut)

            while child:
                child.ToMenuItem(menuBar)
                MenuItemSet(child, menuBar)
                child, cookie = shortcut.GetNextChild(shortcut, cookie)

        manager = self.GetShortcutManager()
        menuBar = topWindow.GetMenuBar()

        MenuItemSet(manager, menuBar)

[docs]    def FromAcceleratorTable(self, accelTable):
        """
        Builds the entire shortcut hierarchy starting from a modified version of a `wx.AcceleratorTable`.

        :param `accelTable`: a modified version of `wx.AcceleratorTable`, is a list of tuples (4 elements per tuple),
         populated like this::

            accelTable = []

            # Every tuple is defined in this way:

            for label, flags, keyCode, cmdID in my_accelerators:
                # label:   the string used to show the accelerator into the ShortcutEditor dialog
                # flags:   a bitmask of wx.ACCEL_ALT, wx.ACCEL_SHIFT, wx.ACCEL_CTRL, wx.ACCEL_CMD,
                #          or wx.ACCEL_NORMAL used to specify which modifier keys are held down
                # keyCode: the keycode to be detected (i.e., ord('b'), wx.WXK_F10, etc...)
                # cmdID:   the menu or control command ID to use for the accelerator event.

                accel_tuple = (label, flags, keyCode, cmdID)
                accelTable.append(accel_tuple)

        """

        parentShortcut = Shortcut(_('Accelerators'))

        parentShortcut.topMenu = True
        self.manager.AppendItem(parentShortcut)

        for text, modifier, accel, ids in accelTable:
            modifier = ACCELERATORS[modifier]
            if accel in KEYMAP:
                accel = KEYMAP[accel]
            else:
                accel = chr(accel)

            shortcut = (modifier and ['%s+%s'%(modifier, accel)] or [accel])[0]
            shortcutItem = Shortcut(text, shortcut, accelId=ids)
            parentShortcut.AppendItem(shortcutItem)

[docs]    def ToAcceleratorTable(self, window):
        """
        Dumps the entire shortcut hierarchy (for shortcuts associated with a `wx.AcceleratorTable`), into
        a `wx.AcceleratorTable`. This method **does** rebuild the `wx.AcceleratorTable` and sets it back
        to the input `window`.

        :param `window`: an instance of `wx.Window`, to which the new `wx.AcceleratorTable` should be set.
        """

        def AccelItemSet(shortcut, table):

            child, cookie = shortcut.GetFirstChild(shortcut)

            while child:
                child.ToAcceleratorItem(table)
                table = AccelItemSet(child, table)
                child, cookie = shortcut.GetNextChild(shortcut, cookie)

            return table

        manager = self.GetShortcutManager()
        table = AccelItemSet(manager, table=[])

        window.SetAcceleratorTable(wx.AcceleratorTable(table))

[docs]    def SetColumnWidths(self):
        """
        Sets the L{ListShortcut} columns widths to acceptable and eye-pleasing
        numbers (in pixels).
        """

        total_width = 0
        for col in xrange(self.listShortcut.GetColumnCount()):
            self.listShortcut.SetColumnWidth(col, wx.LIST_AUTOSIZE)
            width = self.listShortcut.GetColumnWidth(col)

            if col == 0:
                width += 20
            elif col == 1:
                width += 5
            else:
                width = min(width, 200)

            width = max(50, width)
            self.listShortcut.SetColumnWidth(col, width)
            total_width += width

        self.listShortcut.GetMainWindow()._lineHeight += 5
        dialogHeight = wx.SystemSettings.GetMetric(wx.SYS_SCREEN_Y)/2

        self.SetSize((total_width+60, dialogHeight))

        self.Center()

[docs]    def OnSetFilter(self, event=None):
        """
        Handles the ``wx.EVT_TEXT`` event for L{ShortcutEditor}.

        :param `event`: if not ``None``, an instance of `wx.KeyEvent`.
        """

        if event:
            event.Skip()

        filter = self.searchText.GetValue()
        filter = filter.lower().strip()

        self.listShortcut.SetFilter(filter)

[docs]    def OnClearFilter(self, event):
        """
        Handles the ``wx.EVT_BUTTON`` event for L{ShortcutEditor} when the user clears the
        label filter at the top of the user interface.

        :param `event`: an instance of `wx.CommandEvent`.
        """

        self.searchText.SetValue(u'')

[docs]    def OnRestoreDefaults(self, event):
        """
        Handles the ``wx.EVT_BUTTON`` event for L{ShortcutEditor} when the user restores the
        original shortcuts.

        :param `event`: an instance of `wx.CommandEvent`.
        """

        self.manager.RestoreDefaults()
        self.listShortcut.RecreateTree()

[docs]    def OnHTMLHelp(self, event):
        """
        Handles the ``wx.EVT_BUTTON`` event for L{ShortcutEditor} when the user presses the ``Help``
        button.

        :param `event`: an instance of `wx.CommandEvent`.

        :note: By default, this method launches a `wx.html.HtmlWindow` containing the default
         HTML help file. If you wish to load another help file, you should call L{SetHTMLHelpFile}
         with another input HTML file.
        """

        if self.htmlWindow:
            self.htmlWindow.Show()
            self.htmlWindow.Restore()
            self.htmlWindow.Raise()
            return

        self.htmlWindow = HTMLHelpWindow(self, self.htmlFile)

[docs]    def GetShortcutManager(self):
        """ Returns the root L{Shortcut} containing the whole shortcut hierarchy. """

        return self.manager

[docs]    def SetHTMLHelpFile(self, htmlFile):
        """
        Sets a new HTML help file (a valid html file) to be loaded when the user seeks
        for an explanation on how the UI works.

        :param string `htmlFile`: a valid HTML file.
        """

        if not os.path.isfile(htmlFile):
            raise Exception('Invalid HTML help file passed to ShortcutEditor')

        self.htmlFile = htmlFile

        if self.htmlWindow is not None:
            self.htmlWindow.htmlFile = htmlFile
            self.htmlWindow.LoadFile(self.htmlFile)

[docs]    def PreShow(self):
        """ Does some more common initialization before showing L{ShortcutEditor}. """

        self.listShortcut.MakeImageList()
        self.listShortcut.RecreateTree()

        self.SetColumnWidths()

[docs]    def ShowModal(self):
        """
        Shows the L{ShortcutEditor} dialog in an application-modal way.

        Program flow does not return until the dialog has been dismissed with `EndModal`.

        :return: The value set with `SetReturnCode`.

        :note: Notice that it is possible to call L{ShowModal} for a dialog which had been
         previously shown with L{Show}, this allows to make an existing modeless dialog
         modal. However L{ShowModal} can't be called twice without intervening `EndModal` calls.

        :note: Note that this function creates a temporary event loop which takes precedence
         over the application's main event loop (see `wx.EventLoopBase`) and which is
         destroyed when the dialog is dismissed. This also results in a call to
         `wx.App.ProcessPendingEvents()`.
        """

        self.PreShow()
        wx.Dialog.ShowModal(self)

[docs]    def Show(self, show=True):
        """
        Hides or shows the L{ShortcutEditor} dialog.

        The preferred way of dismissing a modal dialog is to use `EndModal`.

        :param bool `show`: if ``True``, the dialog box is shown and brought to the front,
         otherwise the box is hidden. If ``False`` and the dialog is modal, control is
         returned to the calling program.

        :note: Reimplemented from `wx.Window`.
        """

        self.PreShow()
        wx.Dialog.Show(self, show)

Navigation

  • index
  • modules |
  • Home |
  • Gallery |
  • Contents»
  • Module code »
  • shortcuteditor


speedmeter

  • modules |
  • Home |
  • Gallery |
  • Contents»
  • Module code »
  • speedmeter

Source code for speedmeter

# --------------------------------------------------------------------------- #
# SPEEDMETER Control wxPython IMPLEMENTATION
# Python Code By:
#
# Andrea Gavana, @ 25 Sep 2005
# Latest Revision: 17 Aug 2011, 15.00 GMT
#
#
# TODO List/Caveats
#
# 1. Combination Of The Two Styles:
#
#    SM_DRAW_PARTIAL_FILLER
#    SM_DRAW_SECTORS
#
#    Does Not Work Very Well. It Works Well Only In Case When The Sector Colours
#    Are The Same For All Intervals.
#
#
# Thanks To Gerard Grazzini That Has Tried The Demo On MacOS, I Corrected A
# Bug On Line 246
#
#
# 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
# --------------------------------------------------------------------------- #

"""
L{SpeedMeter} tries to reproduce the behavior of some car controls (but not only),
by creating an "angular" control (actually, circular).

Description
===========

L{SpeedMeter} tries to reproduce the behavior of some car controls (but not only),
by creating an "angular" control (actually, circular). I remember to have seen
it somewhere, and i decided to implement it in wxPython.

L{SpeedMeter} starts its construction from an empty bitmap, and it uses some
functions of the `wx.DC` class to create the rounded effects. everything is
processed in the `Draw()` method of L{SpeedMeter} class.

This implementation allows you to use either directly the `wx.PaintDC`, or the
better (for me) double buffered style with `wx.BufferedPaintDC`. the double
buffered implementation has been adapted from the wxPython wiki example:

http://wiki.wxpython.org/index.cgi/doublebuffereddrawing

Usage
=====

Usage example::

    import wx
    import wx.lib.agw.speedmeter as SM

    class MyFrame(wx.Frame):

        def __init__(self, parent):

            wx.Frame.__init__(self, parent, -1, "SpeedMeter Demo")

            speed = SM.SpeedMeter(self, agwStyle=SM.SM_DRAW_HAND|SM.SM_DRAW_SECTORS|SM.SM_DRAW_MIDDLE_TEXT|SM.SM_DRAW_SECONDARY_TICKS)

            # Set The Region Of Existence Of SpeedMeter (Always In Radians!!!!)
            speed.SetAngleRange(-pi/6, 7*pi/6)

            # Create The Intervals That Will Divide Our SpeedMeter In Sectors
            intervals = range(0, 201, 20)
            speed.SetIntervals(intervals)

            # Assign The Same Colours To All Sectors (We Simulate A Car Control For Speed)
            # Usually This Is Black
            colours = [wx.BLACK]*10
            speed.SetIntervalColours(colours)

            # Assign The Ticks: Here They Are Simply The String Equivalent Of The Intervals
            ticks = [str(interval) for interval in intervals]
            speed.SetTicks(ticks)
            # Set The Ticks/Tick Markers Colour
            speed.SetTicksColour(wx.WHITE)
            # We Want To Draw 5 Secondary Ticks Between The Principal Ticks
            speed.SetNumberOfSecondaryTicks(5)

            # Set The Font For The Ticks Markers
            speed.SetTicksFont(wx.Font(7, wx.SWISS, wx.NORMAL, wx.NORMAL))

            # Set The Text In The Center Of SpeedMeter
            speed.SetMiddleText("Km/h")
            # Assign The Colour To The Center Text
            speed.SetMiddleTextColour(wx.WHITE)
            # Assign A Font To The Center Text
            speed.SetMiddleTextFont(wx.Font(8, wx.SWISS, wx.NORMAL, wx.BOLD))

            # Set The Colour For The Hand Indicator
            speed.SetHandColour(wx.Colour(255, 50, 0))

            # Do Not Draw The External (Container) Arc. Drawing The External Arc May
            # Sometimes Create Uglier Controls. Try To Comment This Line And See It
            # For Yourself!
            speed.DrawExternalArc(False)

            # Set The Current Value For The SpeedMeter
            speed.SetSpeedValue(44)

    # our normal wxApp-derived class, as usual

    app = wx.PySimpleApp()

    frame = MyFrame(None)
    app.SetTopWindow(frame)
    frame.Show()

    app.MainLoop()

Methods and Settings
====================

L{SpeedMeter} is highly customizable, and in particular you can set:

- The start and end angle of existence for L{SpeedMeter};
- The intervals in which you divide the L{SpeedMeter} (numerical values);
- The corresponding thicks for the intervals;
- The interval colours (different intervals may have different filling colours);
- The ticks font and colour;
- The background colour (outsize the L{SpeedMeter} region);
- The external arc colour;
- The hand (arrow) colour;
- The hand's shadow colour;
- The hand's style ("arrow" or "hand");
- The partial filler colour;
- The number of secondary (intermediate) ticks;
- The direction of increasing speed ("advance" or "reverse");
- The text to be drawn in the middle and its font;
- The icon to be drawn in the middle;
- The first and second gradient colours (that fills the L{SpeedMeter} control);
- The current value.

Window Styles
=============

This class supports the following window styles:

=========================== =========== ==================================================
Window Styles               Hex Value   Description
=========================== =========== ==================================================
``SM_ROTATE_TEXT``                  0x1 Draws the ticks rotated: the ticks are rotated accordingly to the tick marks positions.
``SM_DRAW_SECTORS``                 0x2 Different intervals are painted in differend colours (every sector of the circle has its own colour).
``SM_DRAW_PARTIAL_SECTORS``         0x4 Every interval has its own colour, but only a circle corona is painted near the ticks.
``SM_DRAW_HAND``                    0x8 The hand (arrow indicator) is drawn.
``SM_DRAW_SHADOW``                 0x10 A shadow for the hand is drawn.
``SM_DRAW_PARTIAL_FILLER``         0x20 A circle corona that follows the hand position is drawn near the ticks.
``SM_DRAW_SECONDARY_TICKS``        0x40 Intermediate (smaller) ticks are drawn between principal ticks.
``SM_DRAW_MIDDLE_TEXT``            0x80 Some text is printed in the middle of the control near the center.
``SM_DRAW_MIDDLE_ICON``           0x100 An icon is drawn in the middle of the control near the center.
``SM_DRAW_GRADIENT``              0x200 A gradient of colours will fill the control.
``SM_DRAW_FANCY_TICKS``           0x400 With this style you can use xml tags to create some custom text and draw it at the ticks position. See `wx.lib.fancytext` for the tags.
=========================== =========== ==================================================

Events Processing
=================

`No custom events are available for this class.`

License And Version
===================

L{SpeedMeter} is distributed under the wxPython license.

Latest revision: Andrea Gavana @ 17 Aug 2011, 15.00 GMT

Version 0.3

"""

#----------------------------------------------------------------------
# Beginning Of SPEEDMETER wxPython Code
#----------------------------------------------------------------------

import wx
import wx.lib.colourdb
import wx.lib.fancytext as fancytext

from math import pi, sin, cos, log, sqrt, atan2

#----------------------------------------------------------------------
# DC Drawing Options
#----------------------------------------------------------------------
# SM_NORMAL_DC Uses The Normal wx.PaintDC
# SM_BUFFERED_DC Uses The Double Buffered Drawing Style

SM_NORMAL_DC = 0
SM_BUFFERED_DC = 1

#----------------------------------------------------------------------
# SpeedMeter Styles
#----------------------------------------------------------------------
# SM_ROTATE_TEXT: Draws The Ticks Rotated: The Ticks Are Rotated
#                 Accordingly To The Tick Marks Positions
# SM_DRAW_SECTORS: Different Intervals Are Painted In Differend Colours
#                  (Every Sector Of The Circle Has Its Own Colour)
# SM_DRAW_PARTIAL_SECTORS: Every Interval Has Its Own Colour, But Only
#                          A Circle Corona Is Painted Near The Ticks
# SM_DRAW_HAND: The Hand (Arrow Indicator) Is Drawn
# SM_DRAW_SHADOW: A Shadow For The Hand Is Drawn
# SM_DRAW_PARTIAL_FILLER: A Circle Corona That Follows The Hand Position
#                         Is Drawn Near The Ticks
# SM_DRAW_SECONDARY_TICKS: Intermediate (Smaller) Ticks Are Drawn Between
#                          Principal Ticks
# SM_DRAW_MIDDLE_TEXT: Some Text Is Printed In The Middle Of The Control
#                      Near The Center
# SM_DRAW_MIDDLE_ICON: An Icon Is Drawn In The Middle Of The Control Near
#                      The Center
# SM_DRAW_GRADIENT: A Gradient Of Colours Will Fill The Control
# SM_DRAW_FANCY_TICKS: With This Style You Can Use XML Tags To Create
#                      Some Custom Text And Draw It At The Ticks Position.
#                      See wx.lib.fancytext For The Tags.

SM_ROTATE_TEXT = 1
""" Draws the ticks rotated: the ticks are rotated accordingly to the tick marks positions. """
SM_DRAW_SECTORS = 2
""" Different intervals are painted in differend colours (every sector of the""" \
""" circle has its own colour). """
SM_DRAW_PARTIAL_SECTORS = 4
""" Every interval has its own colour, but only a circle corona is painted near the ticks. """
SM_DRAW_HAND = 8
""" The hand (arrow indicator) is drawn. """
SM_DRAW_SHADOW = 16
""" A shadow for the hand is drawn. """
SM_DRAW_PARTIAL_FILLER = 32
""" A circle corona that follows the hand position is drawn near the ticks. """
SM_DRAW_SECONDARY_TICKS = 64
""" Intermediate (smaller) ticks are drawn between principal ticks. """
SM_DRAW_MIDDLE_TEXT = 128
""" Some text is printed in the middle of the control near the center. """
SM_DRAW_MIDDLE_ICON = 256
""" An icon is drawn in the middle of the control near the center. """
SM_DRAW_GRADIENT = 512
""" A gradient of colours will fill the control. """
SM_DRAW_FANCY_TICKS = 1024
""" With this style you can use xml tags to create some custom text and""" \
""" draw it at the ticks position. See `wx.lib.fancytext` for the tags. """

#----------------------------------------------------------------------
# Event Binding
#----------------------------------------------------------------------
# SM_MOUSE_TRACK: The Mouse Left Click/Drag Allow You To Change The
#                 SpeedMeter Value Interactively

SM_MOUSE_TRACK = 1

fontfamily = range(70, 78)
familyname = ["default", "decorative", "roman", "script", "swiss", "modern", "teletype"]

weights = range(90, 93)
weightsname = ["normal", "light", "bold"]

styles = [90, 93, 94]
stylesname = ["normal", "italic", "slant"]

#----------------------------------------------------------------------
# BUFFERENDWINDOW Class
# This Class Has Been Taken From The wxPython Wiki, And Slightly
# Adapted To Fill My Needs. See:
#
# http://wiki.wxpython.org/index.cgi/DoubleBufferedDrawing
#
# For More Info About DC And Double Buffered Drawing.
#----------------------------------------------------------------------

[docs]class BufferedWindow(wx.Window):
    """
    A buffered window class.

    To use it, subclass it and define a `Draw(dc)` method that takes a `dc`
    to draw to. In that method, put the code needed to draw the picture
    you want. The window will automatically be double buffered, and the
    screen will be automatically updated when a Paint event is received.

    When the drawing needs to change, you app needs to call the
    L{BufferedWindow.UpdateDrawing} method. Since the drawing is stored in a bitmap, you
    can also save the drawing to file by calling the
    `SaveToFile(self, file_name, file_type)` method.
    """

[docs]    def __init__(self, parent, id=wx.ID_ANY, pos=wx.DefaultPosition, size=wx.DefaultSize,
                 style=wx.NO_FULL_REPAINT_ON_RESIZE, bufferedstyle=SM_BUFFERED_DC):
        """
        Default class constructor.

        :param `parent`: parent window. Must not be ``None``;
        :param `id`: window identifier. A value of -1 indicates a default value;
        :param `pos`: the control position. A value of (-1, -1) indicates a default position,
         chosen by either the windowing system or wxPython, depending on platform;
        :param `size`: the control size. A value of (-1, -1) indicates a default size,
         chosen by either the windowing system or wxPython, depending on platform;
        :param `style`: the window style;
        :param `bufferedstyle`: if set to ``SM_BUFFERED_DC``, double-buffering will
         be used.
        """

        wx.Window.__init__(self, parent, id, pos, size, style)

        self.Bind(wx.EVT_PAINT, self.OnPaint)
        self.Bind(wx.EVT_SIZE, self.OnSize)
        self.Bind(wx.EVT_ERASE_BACKGROUND, lambda x: None)

        # OnSize called to make sure the buffer is initialized.
        # This might result in OnSize getting called twice on some
        # platforms at initialization, but little harm done.
        self.OnSize(None)

[docs]    def Draw(self, dc):
        """
        This method should be overridden when sub-classed.

        :param `dc`: an instance of `wx.DC`.
        """

        pass

[docs]    def OnPaint(self, event):
        """
        Handles the ``wx.EVT_PAINT`` event for L{BufferedWindow}.

        :param `event`: a `wx.PaintEvent` event to be processed.
        """

        if self._bufferedstyle == SM_BUFFERED_DC:
            dc = wx.BufferedPaintDC(self, self._Buffer)
        else:
            dc = wx.PaintDC(self)
            dc.DrawBitmap(self._Buffer,0,0)

[docs]    def OnSize(self,event):
        """
        Handles the ``wx.EVT_SIZE`` event for L{BufferedWindow}.

        :param `event`: a `wx.SizeEvent` event to be processed.
        """

        self.Width, self.Height = self.GetClientSizeTuple()

        # Make new off screen bitmap: this bitmap will always have the
        # current drawing in it, so it can be used to save the image to
        # a file, or whatever.

        # This seems required on MacOS, it doesn't like wx.EmptyBitmap with
        # size = (0, 0)
        # Thanks to Gerard Grazzini

        if "__WXMAC__" in wx.Platform:
            if self.Width == 0:
                self.Width = 1
            if self.Height == 0:
                self.Height = 1

        self._Buffer = wx.EmptyBitmap(self.Width, self.Height)
        self.UpdateDrawing()

[docs]    def UpdateDrawing(self):
        """
        This would get called if the drawing needed to change, for whatever reason.

        The idea here is that the drawing is based on some data generated
        elsewhere in the system. if that data changes, the drawing needs to
        be updated.
        """

        if self._bufferedstyle == SM_BUFFERED_DC:
            dc = wx.BufferedDC(wx.ClientDC(self), self._Buffer)
            self.Draw(dc)
        else:
            # update the buffer
            dc = wx.MemoryDC()
            dc.SelectObject(self._Buffer)

            self.Draw(dc)
            # update the screen
            wx.ClientDC(self).Blit(0, 0, self.Width, self.Height, dc, 0, 0)

#----------------------------------------------------------------------
# SPEEDMETER Class
# This Is The Main Class Implementation. See __init__() Method For
# Details.
#----------------------------------------------------------------------

[docs]class SpeedMeter(BufferedWindow):
    """
    L{SpeedMeter} tries to reproduce the behavior of some car controls (but not only),
    by creating an "angular" control (actually, circular).

    This is the main class implementation.
    """

[docs]    def __init__(self, parent, id=wx.ID_ANY, pos=wx.DefaultPosition,
                 size=wx.DefaultSize, agwStyle=SM_DRAW_HAND,
                 bufferedstyle=SM_BUFFERED_DC,
                 mousestyle=0):
        """
        Default class constructor.

        :param `parent`: parent window. Must not be ``None``;
        :param `id`: window identifier. A value of -1 indicates a default value;
        :param `pos`: the control position. A value of (-1, -1) indicates a default position,
         chosen by either the windowing system or wxPython, depending on platform;
        :param `size`: the control size. A value of (-1, -1) indicates a default size,
         chosen by either the windowing system or wxPython, depending on platform;
        :param `agwStyle`: this value specifies the L{SpeedMeter} styles, and can be a
         combination of the following bits:

         =========================== =========== ==================================================
         Window Styles               Hex Value   Description
         =========================== =========== ==================================================
         ``SM_ROTATE_TEXT``                  0x1 Draws the ticks rotated: the ticks are rotated accordingly to the tick marks positions.
         ``SM_DRAW_SECTORS``                 0x2 Different intervals are painted in differend colours (every sector of the circle has its own colour).
         ``SM_DRAW_PARTIAL_SECTORS``         0x4 Every interval has its own colour, but only a circle corona is painted near the ticks.
         ``SM_DRAW_HAND``                    0x8 The hand (arrow indicator) is drawn.
         ``SM_DRAW_SHADOW``                 0x10 A shadow for the hand is drawn.
         ``SM_DRAW_PARTIAL_FILLER``         0x20 A circle corona that follows the hand position is drawn near the ticks.
         ``SM_DRAW_SECONDARY_TICKS``        0x40 Intermediate (smaller) ticks are drawn between principal ticks.
         ``SM_DRAW_MIDDLE_TEXT``            0x80 Some text is printed in the middle of the control near the center.
         ``SM_DRAW_MIDDLE_ICON``           0x100 An icon is drawn in the middle of the control near the center.
         ``SM_DRAW_GRADIENT``              0x200 A gradient of colours will fill the control.
         ``SM_DRAW_FANCY_TICKS``           0x400 With this style you can use xml tags to create some custom text and draw it at the ticks position. See `wx.lib.fancytext` for the tags.
         =========================== =========== ==================================================

        :param `bufferedstyle`: this value allows you to use the normal `wx.PaintDC` or the
         double buffered drawing options:

         =========================== =========== ==================================================
         Buffered Styles             Hex Value   Description
         =========================== =========== ==================================================
         ``SM_NORMAL_DC``                    0x0 Uses the normal `wx.PaintDC`
         ``SM_BUFFERED_DC``                  0x1 Uses the double buffered drawing style
         =========================== =========== ==================================================

        :param `mousestyle`: this value allows you to use the mouse to change the L{SpeedMeter}
         value interactively with left click/drag events. If set to ``SM_MOUSE_TRACK``, the mouse
         left click/drag allow you to change the L{SpeedMeter} value interactively.
        """

        self._agwStyle = agwStyle
        self._bufferedstyle = bufferedstyle
        self._mousestyle = mousestyle

        if self._agwStyle & SM_DRAW_SECTORS and self._agwStyle & SM_DRAW_GRADIENT:
            errstr = "\nERROR: Incompatible Options: SM_DRAW_SECTORS Can Not Be Used In "
            errstr = errstr + "Conjunction With SM_DRAW_GRADIENT."
            raise Exception(errstr)

        if self._agwStyle & SM_DRAW_PARTIAL_SECTORS and self._agwStyle & SM_DRAW_SECTORS:
            errstr = "\nERROR: Incompatible Options: SM_DRAW_SECTORS Can Not Be Used In "
            errstr = errstr + "Conjunction With SM_DRAW_PARTIAL_SECTORS."
            raise Exception(errstr)

        if self._agwStyle & SM_DRAW_PARTIAL_SECTORS and self._agwStyle & SM_DRAW_PARTIAL_FILLER:
            errstr = "\nERROR: Incompatible Options: SM_DRAW_PARTIAL_SECTORS Can Not Be Used In "
            errstr = errstr + "Conjunction With SM_DRAW_PARTIAL_FILLER."
            raise Exception(errstr)

        if self._agwStyle & SM_DRAW_FANCY_TICKS and self._agwStyle & SM_ROTATE_TEXT:
            errstr = "\nERROR: Incompatible Options: SM_DRAW_FANCY_TICKS Can Not Be Used In "
            errstr = errstr + "Conjunction With SM_ROTATE_TEXT."
            raise Exception(errstr)

        if self._agwStyle & SM_DRAW_SHADOW and self._agwStyle & SM_DRAW_HAND == 0:
            errstr = "\nERROR: Incompatible Options: SM_DRAW_SHADOW Can Be Used Only In "
            errstr = errstr + "Conjunction With SM_DRAW_HAND."
            raise Exception(errstr)

        if self._agwStyle & SM_DRAW_FANCY_TICKS:
            wx.lib.colourdb.updateColourDB()

        self.SetAngleRange()
        self.SetIntervals()
        self.SetSpeedValue()
        self.SetIntervalColours()
        self.SetArcColour()
        self.SetTicks()
        self.SetTicksFont()
        self.SetTicksColour()
        self.SetSpeedBackground()
        self.SetHandColour()
        self.SetShadowColour()
        self.SetFillerColour()
        self.SetDirection()
        self.SetNumberOfSecondaryTicks()
        self.SetMiddleText()
        self.SetMiddleTextFont()
        self.SetMiddleTextColour()
        self.SetFirstGradientColour()
        self.SetSecondGradientColour()
        self.SetHandStyle()
        self.DrawExternalArc()

        BufferedWindow.__init__(self, parent, id, pos, size,
                                style=wx.NO_FULL_REPAINT_ON_RESIZE,
                                bufferedstyle=bufferedstyle)

        if self._mousestyle & SM_MOUSE_TRACK:
            self.Bind(wx.EVT_MOUSE_EVENTS, self.OnMouseMotion)

[docs]    def Draw(self, dc):
        """
        Draws everything on the empty bitmap.
        Here all the chosen styles are applied.

        :param `dc`: an instance of `wx.DC`.
        """

        size  = self.GetClientSize()

        if size.x < 21 or size.y < 21:
            return

        new_dim = size.Get()

        if not hasattr(self, "dim"):
            self.dim = new_dim

        self.scale = min([float(new_dim[0]) / self.dim[0],
                          float(new_dim[1]) / self.dim[1]])

        # Create An Empty Bitmap
        self.faceBitmap = wx.EmptyBitmap(size.width, size.height)

        dc.BeginDrawing()

        speedbackground = self.GetSpeedBackground()
        # Set Background Of The Control
        dc.SetBackground(wx.Brush(speedbackground))
        dc.Clear()

        centerX = self.faceBitmap.GetWidth()/2
        centerY = self.faceBitmap.GetHeight()/2

        self.CenterX = centerX
        self.CenterY = centerY

        # Get The Radius Of The Sector. Set It A Bit Smaller To Correct Draw After
        radius = min(centerX, centerY) - 2

        self.Radius = radius

        # Get The Angle Of Existance Of The Sector
        anglerange = self.GetAngleRange()
        startangle = anglerange[1]
        endangle = anglerange[0]

        self.StartAngle = startangle
        self.EndAngle = endangle

        # Initialize The Colours And The Intervals - Just For Reference To The
        # Children Functions
        colours = None
        intervals = None

        if self._agwStyle & SM_DRAW_SECTORS or self._agwStyle & SM_DRAW_PARTIAL_SECTORS:
            # Get The Intervals Colours
            colours = self.GetIntervalColours()[:]

        textangles = []
        colourangles = []
        xcoords = []
        ycoords = []

        # Get The Intervals (Partial Sectors)
        intervals = self.GetIntervals()[:]

        start = min(intervals)
        end = max(intervals)
        span = end - start

        self.StartValue = start
        self.EndValue = end

        self.Span = span

        # Get The Current Value For The SpeedMeter
        currentvalue = self.GetSpeedValue()

        # Get The Direction Of The SpeedMeter
        direction = self.GetDirection()
        if direction == "Reverse":
            intervals.reverse()

            if self._agwStyle & SM_DRAW_SECTORS or self._agwStyle & SM_DRAW_PARTIAL_SECTORS:
                colours.reverse()

            currentvalue = end - currentvalue

        # This Because DrawArc Does Not Draw Last Point
        offset = 0.1*self.scale/180.0

        xstart, ystart = self.CircleCoords(radius+1, -endangle, centerX, centerY)
        xend, yend = self.CircleCoords(radius+1, -startangle-offset, centerX, centerY)

        # Calculate The Angle For The Current Value Of SpeedMeter
        accelangle = (currentvalue - start)/float(span)*(startangle-endangle) - startangle

        dc.SetPen(wx.TRANSPARENT_PEN)

        if self._agwStyle & SM_DRAW_PARTIAL_FILLER:

            # Get Some Data For The Partial Filler
            fillercolour = self.GetFillerColour()
            fillerendradius = radius - 10.0*self.scale
            fillerstartradius = radius

            if direction == "Advance":
                fillerstart = accelangle
                fillerend = -startangle
            else:
                fillerstart = -endangle
                fillerend = accelangle

            xs1, ys1 = self.CircleCoords(fillerendradius, fillerstart, centerX, centerY)
            xe1, ye1 = self.CircleCoords(fillerendradius, fillerend, centerX, centerY)
            xs2, ys2 = self.CircleCoords(fillerstartradius, fillerstart, centerX, centerY)
            xe2, ye2 = self.CircleCoords(fillerstartradius, fillerend, centerX, centerY)

            # Get The Sector In Which The Current Value Is
            intersection = self.GetIntersection(currentvalue, intervals)
            sectorradius = radius - 10*self.scale

        else:

            sectorradius = radius

        if self._agwStyle & SM_DRAW_PARTIAL_FILLER:
            # Draw The Filler (Both In "Advance" And "Reverse" Directions)

            dc.SetBrush(wx.Brush(fillercolour))
            dc.DrawArc(xs2, ys2, xe2, ye2, centerX, centerY)

            if self._agwStyle & SM_DRAW_SECTORS == 0:
                dc.SetBrush(wx.Brush(speedbackground))
                xclean1, yclean1 = self.CircleCoords(sectorradius, -endangle, centerX, centerY)
                xclean2, yclean2 = self.CircleCoords(sectorradius, -startangle-offset, centerX, centerY)
                dc.DrawArc(xclean1, yclean1, xclean2, yclean2, centerX, centerY)

        # This Is Needed To Fill The Partial Sector Correctly
        xold, yold = self.CircleCoords(radius, startangle+endangle, centerX, centerY)

        # Draw The Sectors
        for ii, interval in enumerate(intervals):

            if direction == "Advance":
                current = interval - start
            else:
                current = end - interval

            angle = (current/float(span))*(startangle-endangle) - startangle
            angletext = -((pi/2.0) + angle)*180/pi
            textangles.append(angletext)
            colourangles.append(angle)
            xtick, ytick = self.CircleCoords(radius, angle, centerX, centerY)

            # Keep The Coordinates, We Will Need Them After To Position The Ticks
            xcoords.append(xtick)
            ycoords.append(ytick)
            x = xtick
            y = ytick

            if self._agwStyle & SM_DRAW_SECTORS:
                if self._agwStyle & SM_DRAW_PARTIAL_FILLER:
                    if direction == "Advance":
                        if current > currentvalue:
                            x, y = self.CircleCoords(radius, angle, centerX, centerY)
                        else:
                            x, y = self.CircleCoords(sectorradius, angle, centerX, centerY)
                    else:
                        if current < end - currentvalue:
                            x, y = self.CircleCoords(radius, angle, centerX, centerY)
                        else:
                            x, y = self.CircleCoords(sectorradius, angle, centerX, centerY)
                else:
                    x, y = self.CircleCoords(radius, angle, centerX, centerY)

            if ii > 0:
                if self._agwStyle & SM_DRAW_PARTIAL_FILLER and ii == intersection:
                    # We Got The Interval In Which There Is The Current Value. If We Choose
                    # A "Reverse" Direction, First We Draw The Partial Sector, Next The Filler

                    dc.SetBrush(wx.Brush(speedbackground))

                    if direction == "Reverse":
                        if self._agwStyle & SM_DRAW_SECTORS:
                            dc.SetBrush(wx.Brush(colours[ii-1]))

                        dc.DrawArc(xe2, ye2, xold, yold, centerX, centerY)

                    if self._agwStyle & SM_DRAW_SECTORS:
                        dc.SetBrush(wx.Brush(colours[ii-1]))
                    else:
                        dc.SetBrush(wx.Brush(speedbackground))

                    dc.DrawArc(xs1, ys1, xe1, ye1, centerX, centerY)

                    if self._agwStyle & SM_DRAW_SECTORS:
                        dc.SetBrush(wx.Brush(colours[ii-1]))
                        # Here We Draw The Rest Of The Sector In Which The Current Value Is
                        if direction == "Advance":
                            dc.DrawArc(xs1, ys1, x, y, centerX, centerY)
                            x = xs1
                            y = ys1
                        else:
                            dc.DrawArc(xe2, ye2, x, y, centerX, centerY)

                elif self._agwStyle & SM_DRAW_SECTORS:
                    dc.SetBrush(wx.Brush(colours[ii-1]))

                    # Here We Still Use The SM_DRAW_PARTIAL_FILLER Style, But We Are Not
                    # In The Sector Where The Current Value Resides
                    if self._agwStyle & SM_DRAW_PARTIAL_FILLER and ii != intersection:
                        if direction == "Advance":
                            dc.DrawArc(x, y, xold, yold, centerX, centerY)
                        else:
                            if ii < intersection:
                                dc.DrawArc(x, y, xold, yold, centerX, centerY)

                    # This Is The Case Where No SM_DRAW_PARTIAL_FILLER Has Been Chosen
                    else:
                        dc.DrawArc(x, y, xold, yold, centerX, centerY)

            else:
                if self._agwStyle & SM_DRAW_PARTIAL_FILLER and self._agwStyle & SM_DRAW_SECTORS:
                    dc.SetBrush(wx.Brush(fillercolour))
                    dc.DrawArc(xs2, ys2, xe2, ye2, centerX, centerY)
                    x, y = self.CircleCoords(sectorradius, angle, centerX, centerY)
                    dc.SetBrush(wx.Brush(colours[ii]))
                    dc.DrawArc(xs1, ys1, xe1, ye1, centerX, centerY)
                    x = xs2
                    y = ys2

            xold = x
            yold = y

            if self._agwStyle & SM_DRAW_PARTIAL_SECTORS:

                sectorendradius = radius - 10.0*self.scale
                sectorstartradius = radius

                xps, yps = self.CircleCoords(sectorstartradius, angle, centerX, centerY)

                if ii > 0:
                    dc.SetBrush(wx.Brush(colours[ii-1]))
                    dc.DrawArc(xps, yps, xpsold, ypsold, centerX, centerY)

                xpsold = xps
                ypsold = yps

        if self._agwStyle & SM_DRAW_PARTIAL_SECTORS:

            xps1, yps1 = self.CircleCoords(sectorendradius, -endangle+2*offset, centerX, centerY)
            xps2, yps2 = self.CircleCoords(sectorendradius, -startangle-2*offset, centerX, centerY)

            dc.SetBrush(wx.Brush(speedbackground))
            dc.DrawArc(xps1, yps1, xps2, yps2, centerX, centerY)

        if self._agwStyle & SM_DRAW_GRADIENT:

            dc.SetPen(wx.TRANSPARENT_PEN)

            xcurrent, ycurrent = self.CircleCoords(radius, accelangle, centerX, centerY)

            # calculate gradient coefficients
            col2 = self.GetSecondGradientColour()
            col1 = self.GetFirstGradientColour()

            r1, g1, b1 = int(col1.Red()), int(col1.Green()), int(col1.Blue())
            r2, g2, b2 = int(col2.Red()), int(col2.Green()), int(col2.Blue())

            flrect = float(radius+self.scale)

            numsteps = 200

            rstep = float((r2 - r1)) / numsteps
            gstep = float((g2 - g1)) / numsteps
            bstep = float((b2 - b1)) / numsteps

            rf, gf, bf = 0, 0, 0

            radiusteps = flrect/numsteps
            interface = 0

            for ind in range(numsteps+1):
                currCol = (r1 + rf, g1 + gf, b1 + bf)
                dc.SetBrush(wx.Brush(currCol))

                gradradius = flrect - radiusteps*ind
                xst1, yst1 = self.CircleCoords(gradradius, -endangle, centerX, centerY)
                xen1, yen1 = self.CircleCoords(gradradius, -startangle-offset, centerX, centerY)

                if self._agwStyle & SM_DRAW_PARTIAL_FILLER:
                    if gradradius >= fillerendradius:
                        if direction == "Advance":
                            dc.DrawArc(xstart, ystart, xcurrent, ycurrent, centerX, centerY)
                        else:
                            dc.DrawArc(xcurrent, ycurrent, xend, yend, centerX, centerY)
                    else:
                        if interface == 0:
                            interface = 1
                            myradius = fillerendradius + 1
                            xint1, yint1 = self.CircleCoords(myradius, -endangle, centerX, centerY)
                            xint2, yint2 = self.CircleCoords(myradius, -startangle-offset, centerX, centerY)
                            dc.DrawArc(xint1, yint1, xint2, yint2, centerX, centerY)

                        dc.DrawArc(xst1, yst1, xen1, yen1, centerX, centerY)
                else:
                    if self._agwStyle & SM_DRAW_PARTIAL_SECTORS:
                        if gradradius <= sectorendradius:
                            if interface == 0:
                                interface = 1
                                myradius = sectorendradius + 1
                                xint1, yint1 = self.CircleCoords(myradius, -endangle, centerX, centerY)
                                xint2, yint2 = self.CircleCoords(myradius, -startangle-offset, centerX, centerY)
                                dc.DrawArc(xint1, yint1, xint2, yint2, centerX, centerY)
                            else:
                                dc.DrawArc(xst1, yst1, xen1, yen1, centerX, centerY)
                    else:
                        dc.DrawArc(xst1, yst1, xen1, yen1, centerX, centerY)

                rf = rf + rstep
                gf = gf + gstep
                bf = bf + bstep

        textheight = 0

        # Get The Ticks And The Ticks Colour
        ticks = self.GetTicks()[:]
        tickscolour = self.GetTicksColour()

        if direction == "Reverse":
            ticks.reverse()

        if self._agwStyle & SM_DRAW_SECONDARY_TICKS:
            ticknum = self.GetNumberOfSecondaryTicks()
            oldinterval = intervals[0]

        dc.SetPen(wx.Pen(tickscolour, 1))
        dc.SetBrush(wx.Brush(tickscolour))
        dc.SetTextForeground(tickscolour)

        # Get The Font For The Ticks
        tfont, fontsize = self.GetTicksFont()
        tfont = tfont[0]
        myfamily = tfont.GetFamily()

        fsize = self.scale*fontsize
        tfont.SetPointSize(int(fsize))
        tfont.SetFamily(myfamily)
        dc.SetFont(tfont)

        if self._agwStyle & SM_DRAW_FANCY_TICKS:
            facename = tfont.GetFaceName()
            ffamily = familyname[fontfamily.index(tfont.GetFamily())]
            fweight = weightsname[weights.index(tfont.GetWeight())]
            fstyle = stylesname[styles.index(tfont.GetStyle())]
            fcolour = wx.TheColourDatabase.FindName(tickscolour)

        textheight = 0

        # Draw The Ticks And The Markers (Text Ticks)
        for ii, angles in enumerate(textangles):

            strings = ticks[ii]
            if self._agwStyle & SM_DRAW_FANCY_TICKS == 0:
                width, height, dummy, dummy = dc.GetFullTextExtent(strings, tfont)
                textheight = height
            else:
                width, height, dummy = fancytext.GetFullExtent(strings, dc)
                textheight = height

            lX = dc.GetCharWidth()/2.0
            lY = dc.GetCharHeight()/2.0

            if self._agwStyle & SM_ROTATE_TEXT:
                angis = colourangles[ii] - float(width)/(2.0*radius)
                x, y = self.CircleCoords(radius-10.0*self.scale, angis, centerX, centerY)
                dc.DrawRotatedText(strings, x, y, angles)
            else:
                angis = colourangles[ii]
                if self._agwStyle & SM_DRAW_FANCY_TICKS == 0:
                    x, y = self.CircleCoords(radius-10*self.scale, angis, centerX, centerY)
                    lX = lX*len(strings)
                    x = x - lX - width*cos(angis)/2.0
                    y = y - lY - height*sin(angis)/2.0

                if self._agwStyle & SM_DRAW_FANCY_TICKS:
                    fancystr = '<font family="' + ffamily + '" size="' + str(int(fsize)) + '" weight="' + fweight + '"'
                    fancystr = fancystr + ' color="' + fcolour + '"' + ' style="' + fstyle + '"> ' + strings + ' </font>'

                    width, height, dummy = fancytext.GetFullExtent(fancystr, dc)
                    x, y = self.CircleCoords(radius-10*self.scale, angis, centerX, centerY)
                    x = x - width/2.0 - width*cos(angis)/2.0
                    y = y - height/2.0 - height*sin(angis)/2.0
                    fancytext.RenderToDC(fancystr, dc, x, y)
                else:
                    dc.DrawText(strings, x, y)

            # This Is The Small Rectangle --> Tick Mark
            rectangle = colourangles[ii] + pi/2.0

            sinrect = sin(rectangle)
            cosrect = cos(rectangle)
            x1 = xcoords[ii] - self.scale*cosrect
            y1 = ycoords[ii] - self.scale*sinrect
            x2 = x1 + 3*self.scale*cosrect
            y2 = y1 + 3*self.scale*sinrect
            x3 = x1 - 10*self.scale*sinrect
            y3 = y1 + 10*self.scale*cosrect
            x4 = x3 + 3*self.scale*cosrect
            y4 = y3 + 3*self.scale*sinrect

            points = [(x1, y1), (x2, y2), (x4, y4), (x3, y3)]

            dc.DrawPolygon(points)

            if self._agwStyle & SM_DRAW_SECONDARY_TICKS:
                if ii > 0:
                    newinterval = intervals[ii]
                    oldinterval = intervals[ii-1]

                    spacing = (newinterval - oldinterval)/float(ticknum+1)

                    for tcount in xrange(ticknum):
                        if direction == "Advance":
                            oldinterval = (oldinterval + spacing) - start
                            stint = oldinterval
                        else:
                            oldinterval = start + (oldinterval + spacing)
                            stint = end - oldinterval

                        angle = (stint/float(span))*(startangle-endangle) - startangle
                        rectangle = angle + pi/2.0
                        sinrect = sin(rectangle)
                        cosrect = cos(rectangle)
                        xt, yt = self.CircleCoords(radius, angle, centerX, centerY)
                        x1 = xt - self.scale*cosrect
                        y1 = yt - self.scale*sinrect
                        x2 = x1 + self.scale*cosrect
                        y2 = y1 + self.scale*sinrect
                        x3 = x1 - 6*self.scale*sinrect
                        y3 = y1 + 6*self.scale*cosrect
                        x4 = x3 + self.scale*cosrect
                        y4 = y3 + self.scale*sinrect

                        points = [(x1, y1), (x2, y2), (x4, y4), (x3, y3)]

                        dc.DrawPolygon(points)

                    oldinterval = newinterval

        tfont.SetPointSize(fontsize)
        tfont.SetFamily(myfamily)

        self.SetTicksFont(tfont)

        # Draw The External Arc
        dc.SetBrush(wx.TRANSPARENT_BRUSH)

        if self._drawarc:
            dc.SetPen(wx.Pen(self.GetArcColour(), 2.0))
            # If It's Not A Complete Circle, Draw The Connecting Lines And The Arc
            if abs(abs(startangle - endangle) - 2*pi) > 1.0/180.0:
                dc.DrawArc(xstart, ystart, xend, yend, centerX, centerY)
                dc.DrawLine(xstart, ystart, centerX, centerY)
                dc.DrawLine(xend, yend, centerX, centerY)
            else:
                # Draw A Circle, Is A 2*pi Extension Arc = Complete Circle
                dc.DrawCircle(centerX, centerY, radius)

        # Here We Draw The Text In The Middle, Near The Start Of The Arrow (If Present)
        # This Is Like The "Km/h" Or "mph" Text In The Cars
        if self._agwStyle & SM_DRAW_MIDDLE_TEXT:

            middlecolour = self.GetMiddleTextColour()
            middletext = self.GetMiddleText()
            middleangle = (startangle + endangle)/2.0

            middlefont, middlesize = self.GetMiddleTextFont()
            middlesize = self.scale*middlesize
            middlefont.SetPointSize(int(middlesize))
            dc.SetFont(middlefont)

            mw, mh, dummy, dummy = dc.GetFullTextExtent(middletext, middlefont)

            newx = centerX + 1.5*mw*cos(middleangle) - mw/2.0
            newy = centerY - 1.5*mh*sin(middleangle) - mh/2.0
            dc.SetTextForeground(middlecolour)
            dc.DrawText(middletext, newx, newy)

        # Here We Draw The Icon In The Middle, Near The Start Of The Arrow (If Present)
        # This Is Like The "Fuel" Icon In The Cars
        if self._agwStyle & SM_DRAW_MIDDLE_ICON:

            middleicon = self.GetMiddleIcon()
            middlewidth, middleheight = self.GetMiddleIconDimens()
            middleicon.SetWidth(middlewidth*self.scale)
            middleicon.SetHeight(middleheight*self.scale)
            middleangle = (startangle + endangle)/2.0

            mw = middleicon.GetWidth()
            mh = middleicon.GetHeight()

            newx = centerX + 1.5*mw*cos(middleangle) - mw/2.0
            newy = centerY - 1.5*mh*sin(middleangle) - mh/2.0

            dc.DrawIcon(middleicon, newx, newy)

            # Restore Icon Dimension, If Not Something Strange Happens
            middleicon.SetWidth(middlewidth)
            middleicon.SetHeight(middleheight)

        # Requested To Draw The Hand
        if self._agwStyle & SM_DRAW_HAND:

            handstyle = self.GetHandStyle()
            handcolour = self.GetHandColour()

            # Calculate The Data For The Hand
            if textheight == 0:
                maxradius = radius-10*self.scale
            else:
                maxradius = radius-5*self.scale-textheight

            xarr, yarr = self.CircleCoords(maxradius, accelangle, centerX, centerY)

            if handstyle == "Arrow":
                x1, y1 = self.CircleCoords(maxradius, accelangle - 4.0/180, centerX, centerY)
                x2, y2 = self.CircleCoords(maxradius, accelangle + 4.0/180, centerX, centerY)
                x3, y3 = self.CircleCoords(maxradius+3*(abs(xarr-x1)), accelangle, centerX, centerY)

                newx = centerX + 4*cos(accelangle)*self.scale
                newy = centerY + 4*sin(accelangle)*self.scale

            else:

                x1 = centerX + 4*self.scale*sin(accelangle)
                y1 = centerY - 4*self.scale*cos(accelangle)
                x2 = xarr
                y2 = yarr
                x3 = centerX - 4*self.scale*sin(accelangle)
                y3 = centerY + 4*self.scale*cos(accelangle)

                x4, y4 = self.CircleCoords(5*self.scale*sqrt(3), accelangle+pi, centerX, centerY)

            if self._agwStyle & SM_DRAW_SHADOW:

                if handstyle == "Arrow":
                    # Draw The Shadow
                    shadowcolour = self.GetShadowColour()
                    dc.SetPen(wx.Pen(shadowcolour, 5*log(self.scale+1)))
                    dc.SetBrush(wx.Brush(shadowcolour))
                    shadowdistance = 2.0*self.scale
                    dc.DrawLine(newx + shadowdistance, newy + shadowdistance,
                                xarr + shadowdistance, yarr + shadowdistance)

                    dc.DrawPolygon([(x1+shadowdistance, y1+shadowdistance),
                                    (x2+shadowdistance, y2+shadowdistance),
                                    (x3+shadowdistance, y3+shadowdistance)])
                else:
                    # Draw The Shadow
                    shadowcolour = self.GetShadowColour()
                    dc.SetBrush(wx.Brush(shadowcolour))
                    dc.SetPen(wx.Pen(shadowcolour, 1.0))
                    shadowdistance = 1.5*self.scale

                    dc.DrawPolygon([(x1+shadowdistance, y1+shadowdistance),
                                    (x2+shadowdistance, y2+shadowdistance),
                                    (x3+shadowdistance, y3+shadowdistance),
                                    (x4+shadowdistance, y4+shadowdistance)])

            if handstyle == "Arrow":

                dc.SetPen(wx.Pen(handcolour, 1.5))

                # Draw The Small Circle In The Center --> The Hand "Holder"
                dc.SetBrush(wx.Brush(speedbackground))
                dc.DrawCircle(centerX, centerY, 4*self.scale)

                dc.SetPen(wx.Pen(handcolour, 5*log(self.scale+1)))
                # Draw The "Hand", An Arrow
                dc.DrawLine(newx, newy, xarr, yarr)

                # Draw The Arrow Pointer
                dc.SetBrush(wx.Brush(handcolour))
                dc.DrawPolygon([(x1, y1), (x2, y2), (x3, y3)])

            else:

                # Draw The Hand Pointer
                dc.SetPen(wx.Pen(handcolour, 1.5))
                dc.SetBrush(wx.Brush(handcolour))
                dc.DrawPolygon([(x1, y1), (x2, y2), (x3, y3), (x4, y4)])

                # Draw The Small Circle In The Center --> The Hand "Holder"
                dc.SetBrush(wx.Brush(speedbackground))
                dc.DrawCircle(centerX, centerY, 4*self.scale)

        dc.EndDrawing()

[docs]    def SetIntervals(self, intervals=None):
        """
        Sets the intervals for L{SpeedMeter} (main ticks numeric values).

        :param `intervals`: a Python list of main ticks to be displayed. If defaulted
         to ``None``, the list `[0, 50, 100]` is used.
        """

        if intervals is None:
            intervals = [0, 50, 100]

        self._intervals = intervals

[docs]    def GetIntervals(self):
        """ Returns the intervals for L{SpeedMeter}, a Python list of main ticks displayed. """

        return self._intervals

[docs]    def SetSpeedValue(self, value=None):
        """
        Sets the current value for L{SpeedMeter}.

        :param `value`: a floating point number representing the current value. If defaulted
         to ``None``, the L{SpeedMeter} value will be the middle point of the control range.
        """

        if value is None:
            value = (max(self._intervals) - min(self._intervals))/2.0
        else:
            if value < min(self._intervals):
                raise Exception("\nERROR: Value Is Smaller Than Minimum Element In Points List")
                return
            elif value > max(self._intervals):
                raise Exception("\nERROR: Value Is Greater Than Maximum Element In Points List")
                return

        self._speedvalue = value
        try:
            self.UpdateDrawing()
        except:
            pass

[docs]    def GetSpeedValue(self):
        """ Returns the current value for L{SpeedMeter}. """

        return self._speedvalue

[docs]    def SetAngleRange(self, start=0, end=pi):
        """
        Sets the range of existence for L{SpeedMeter}.

        :param `start`: the starting angle, in radians;
        :param `end`: the ending angle, in radians.
        """

        self._anglerange = [start, end]

[docs]    def GetAngleRange(self):
        """
        Returns the range of existence for L{SpeedMeter}.
        The returned values are in radians.
        """

        return self._anglerange

[docs]    def SetIntervalColours(self, colours=None):
        """
        Sets the colours for the intervals.

        :param `colours`: a Python list of colours. The length of this list should be
         the same as the number of circle sectors in L{SpeedMeter}. If defaulted to ``None``,
         all the intervals will have a white colour.

        :note: Every interval (circle sector) should have a colour.
        """

        if colours is None:
            if not hasattr(self, "_anglerange"):
                errstr = "\nERROR: Impossible To Set Interval Colours,"
                errstr = errstr + " Please Define The Intervals Ranges Before."
                raise Exception(errstr)
                return

            colours = [wx.WHITE]*len(self._intervals)
        else:
            if len(colours) != len(self._intervals) - 1:
                errstr = "\nERROR: Length Of Colour List Does Not Match Length"
                errstr = errstr + " Of Intervals Ranges List."
                raise Exception(errstr)
                return

        self._intervalcolours = colours

[docs]    def GetIntervalColours(self):
        """ Returns the colours for the intervals."""

        if hasattr(self, "_intervalcolours"):
            return self._intervalcolours
        else:
            raise Exception("\nERROR: No Interval Colours Have Been Defined")

[docs]    def SetTicks(self, ticks=None):
        """
        Sets the ticks for L{SpeedMeter} intervals (main ticks string values).

        :param `ticks`: a Python list of strings, representing the ticks values.
         If defaulted to ``None``, the ticks will be taken from the interval values.
        """

        if ticks is None:
            if not hasattr(self, "_anglerange"):
                errstr = "\nERROR: Impossible To Set Interval Ticks,"
                errstr = errstr + " Please Define The Intervals Ranges Before."
                raise Exception(errstr)
                return

            ticks = []

            for values in self._intervals:
                ticks.append(str(values))

        else:
            if len(ticks) != len(self._intervals):
                errstr = "\nERROR: Length Of Ticks List Does Not Match Length"
                errstr = errstr + " Of Intervals Ranges List."
                raise Exception(errstr)
                return

        self._intervalticks = ticks

[docs]    def GetTicks(self):
        """ Returns the ticks for L{SpeedMeter} intervals (main ticks string values)."""

        if hasattr(self, "_intervalticks"):
            return self._intervalticks
        else:
            raise Exception("\nERROR: No Interval Ticks Have Been Defined")

[docs]    def SetTicksFont(self, font=None):
        """
        Sets the ticks font.

        :param `font`: a valid `wx.Font` object. If defaulted to ``None``, some standard
         font will be chosen automatically.
        """

        if font is None:
            self._originalfont = [wx.Font(10, wx.SWISS, wx.NORMAL, wx.BOLD, False)]
            self._originalsize = 10
        else:
            self._originalfont = [font]
            self._originalsize = font.GetPointSize()

[docs]    def GetTicksFont(self):
        """ Returns the ticks font."""

        return self._originalfont[:], self._originalsize

[docs]    def SetTicksColour(self, colour=None):
        """
        Sets the ticks colour.

        :param `colour`: a valid `wx.Colour` object. If defaulted to ``None``, the
         ticks colour will be set as blue.
        """

        if colour is None:
            colour = wx.BLUE

        self._tickscolour = colour

[docs]    def GetTicksColour(self):
        """ Returns the ticks colour."""

        return self._tickscolour

[docs]    def SetSpeedBackground(self, colour=None):
        """
        Sets the background colour outside the L{SpeedMeter} control.

        :param `colour`: a valid `wx.Colour` object. If defaulted to ``None``, the
         L{SpeedMeter} background will be taken from the system default.
        """

        if colour is None:
            colour = wx.SystemSettings_GetColour(0)

        self._speedbackground = colour

[docs]    def GetSpeedBackground(self):
        """ Returns the background colour outside the L{SpeedMeter} control."""

        return self._speedbackground

[docs]    def SetHandColour(self, colour=None):
        """
        Sets the hand (arrow indicator) colour.

        :param `colour`: a valid `wx.Colour` object. If defaulted to ``None``, the arrow
         indicator will be red.
        """

        if colour is None:
            colour = wx.RED

        self._handcolour = colour

[docs]    def GetHandColour(self):
        """ Returns the hand (arrow indicator) colour."""

        return self._handcolour

[docs]    def SetArcColour(self, colour=None):
        """
        Sets the external arc colour (thicker line).

        :param `colour`: a valid `wx.Colour` object. If defaulted to ``None``, the arc
         colour will be black.
        """

        if colour is None:
            colour = wx.BLACK

        self._arccolour = colour

[docs]    def GetArcColour(self):
        """ Returns the external arc colour."""

        return self._arccolour

[docs]    def SetShadowColour(self, colour=None):
        """
        Sets the hand's shadow colour.

        :param `colour`: a valid `wx.Colour` object. If defaulted to ``None``, the shadow
         colour will be light grey.
        """

        if colour is None:
            colour = wx.Colour(150, 150, 150)

        self._shadowcolour = colour

[docs]    def GetShadowColour(self):
        """ Returns the hand's shadow colour."""

        return self._shadowcolour

[docs]    def SetFillerColour(self, colour=None):
        """
        Sets the partial filler colour.

        A circle corona near the ticks will be filled with this colour, from
        the starting value to the current value of L{SpeedMeter}.

        :param `colour`: a valid `wx.Colour` object.
        """

        if colour is None:
            colour = wx.Colour(255, 150, 50)

        self._fillercolour = colour

[docs]    def GetFillerColour(self):
        """ Returns the partial filler colour."""

        return self._fillercolour

[docs]    def SetDirection(self, direction=None):
        """
        Sets the direction of advancing L{SpeedMeter} value.

        :param `direction`: specifying "advance" will move the hand in clock-wise direction
         (like normal car speed control), while using "reverse" will move it counterclock-wise
         direction. If defaulted to ``None``, then "advance" will be used.
        """

        if direction is None:
            direction = "Advance"

        if direction not in ["Advance", "Reverse"]:
            raise Exception('\nERROR: Direction Parameter Should Be One Of "Advance" Or "Reverse".')

        self._direction = direction

[docs]    def GetDirection(self):
        """ Returns the direction of advancing L{SpeedMeter} value."""

        return self._direction

[docs]    def SetNumberOfSecondaryTicks(self, ticknum=None):
        """
        Sets the number of secondary (intermediate) ticks.

        :param `ticknum`: the number of intermediate ticks. If defaulted to ``None``,
         3 ticks are used.
        """

        if ticknum is None:
            ticknum = 3

        if ticknum < 1:
            raise Exception("\nERROR: Number Of Ticks Must Be Greater Than 1.")

        self._secondaryticks = ticknum

[docs]    def GetNumberOfSecondaryTicks(self):
        """ Returns the number of secondary (intermediate) ticks. """

        return self._secondaryticks

[docs]    def SetMiddleText(self, text=None):
        """
        Sets the text to be drawn near the center of L{SpeedMeter}.

        :param `text`: the text to be drawn near the center of L{SpeedMeter}. If
         defaulted to ``None``, an empty string will be used.
        """

        if text is None:
            text = ""

        self._middletext = text

[docs]    def GetMiddleText(self):
        """ Returns the text to be drawn near the center of L{SpeedMeter}. """

        return self._middletext

[docs]    def SetMiddleTextFont(self, font=None):
        """
        Sets the font for the text in the middle.

        :param `font`: a valid `wx.Font` object. If defaulted to ``None``, some
         standard font will be generated.
        """

        if font is None:
            self._middletextfont = wx.Font(1, wx.SWISS, wx.NORMAL, wx.BOLD, False)
            self._middletextsize = 10.0
            self._middletextfont.SetPointSize(self._middletextsize)
        else:
            self._middletextfont = font
            self._middletextsize = font.GetPointSize()
            self._middletextfont.SetPointSize(self._middletextsize)

[docs]    def GetMiddleTextFont(self):
        """ Returns the font for the text in the middle."""

        return self._middletextfont, self._middletextsize

[docs]    def SetMiddleTextColour(self, colour=None):
        """
        Sets the colour for the text in the middle.

        :param `colour`: a valid `wx.Colour` object. If defaulted to ``None``, the text
         in the middle will be painted in blue.
        """

        if colour is None:
            colour = wx.BLUE

        self._middlecolour = colour

[docs]    def GetMiddleTextColour(self):
        """ Returns the colour for the text in the middle."""

        return self._middlecolour

[docs]    def SetMiddleIcon(self, icon):
        """
        Sets the icon to be drawn near the center of L{SpeedMeter}.

        :param `icon`: a valid `wx.Bitmap` object.
        """

        if icon.Ok():
            self._middleicon = icon
        else:
            raise Exception("\nERROR: Invalid Icon Passed To SpeedMeter.")

[docs]    def GetMiddleIcon(self):
        """ Returns the icon to be drawn near the center of L{SpeedMeter}. """

        return self._middleicon

[docs]    def GetMiddleIconDimens(self):
        """ Used internally. """

        return self._middleicon.GetWidth(), self._middleicon.GetHeight()

[docs]    def CircleCoords(self, radius, angle, centerX, centerY):
        """
        Converts the input values into logical x, y coordinates.

        :param `radius`: the L{SpeedMeter} radius;
        :param `angle`: the angular position of the mouse;
        :param `centerX`: the `x` position of the L{SpeedMeter} center;
        :param `centerX`: the `y` position of the L{SpeedMeter} center.
        """

        x = radius*cos(angle) + centerX
        y = radius*sin(angle) + centerY

        return x, y

[docs]    def GetIntersection(self, current, intervals):
        """ Used internally. """

        if self.GetDirection() == "Reverse":
            interval = intervals[:]
            interval.reverse()
        else:
            interval = intervals

        indexes = range(len(intervals))
        try:
            intersection = [ind for ind in indexes if interval[ind] <= current <= interval[ind+1]]
        except:
            if self.GetDirection() == "Reverse":
                intersection = [len(intervals) - 1]
            else:
                intersection = [0]

        return intersection[0]

[docs]    def SetFirstGradientColour(self, colour=None):
        """
        Sets the first gradient colour (near the ticks).

        :param `colour`: a valid `wx.Colour` object.
        """

        if colour is None:
            colour = wx.Colour(145, 220, 200)

        self._firstgradientcolour = colour

[docs]    def GetFirstGradientColour(self):
        """ Returns the first gradient colour (near the ticks). """

        return self._firstgradientcolour

[docs]    def SetSecondGradientColour(self, colour=None):
        """
        Sets the second gradient colour (near the center).

        :param `colour`: a valid `wx.Colour` object.
        """

        if colour is None:
            colour = wx.WHITE

        self._secondgradientcolour = colour

[docs]    def GetSecondGradientColour(self):
        """ Returns the first gradient colour (near the center). """

        return self._secondgradientcolour

[docs]    def SetHandStyle(self, style=None):
        """
        Sets the style for the hand (arrow indicator).

        :param `style`: by specifying "Hand", L{SpeedMeter} will draw a polygon
         that simulates the car speed control indicator. Using "Arrow" will force
         L{SpeedMeter} to draw a simple arrow. If defaulted to ``None``, "Hand" will
         be used.
         """

        if style is None:
            style = "Hand"

        if style not in ["Hand", "Arrow"]:
            raise Exception('\nERROR: Hand Style Parameter Should Be One Of "Hand" Or "Arrow".')
            return

        self._handstyle = style

[docs]    def GetHandStyle(self):
        """ Returns the style for the hand (arrow indicator)."""

        return self._handstyle

[docs]    def DrawExternalArc(self, draw=True):
        """
        Specify wheter or not you wish to draw the external (thicker) arc.

        :param `draw`: ``True`` to draw the external arc, ``False`` otherwise.
        """

        self._drawarc = draw

[docs]    def OnMouseMotion(self, event):
        """
        Handles the ``wx.EVT_MOUSE_EVENTS`` event for L{SpeedMeter}.

        :param `event`: a `wx.MouseEvent` event to be processed.

        :note: Here only left clicks/drags are involved. Should L{SpeedMeter}
         have something more?
        """

        mousex = event.GetX()
        mousey = event.GetY()

        if event.Leaving():
            return

        pos = self.GetClientSize()
        size = self.GetPosition()
        centerX = self.CenterX
        centerY = self.CenterY

        direction = self.GetDirection()

        if event.LeftIsDown():

            angle = atan2(float(mousey) - centerY, centerX - float(mousex)) + pi - self.EndAngle
            if angle >= 2*pi:
                angle = angle - 2*pi

            if direction == "Advance":
                currentvalue = (self.StartAngle - self.EndAngle - angle)*float(self.Span)/(self.StartAngle - self.EndAngle) + self.StartValue
            else:
                currentvalue = (angle)*float(self.Span)/(self.StartAngle - self.EndAngle) + self.StartValue

            if currentvalue >= self.StartValue and currentvalue <= self.EndValue:
                self.SetSpeedValue(currentvalue)

        event.Skip()

[docs]    def GetSpeedStyle(self):
        """ Returns a list of strings and a list of integers containing the styles. """

        stringstyle = []
        integerstyle = []

        if self._agwStyle & SM_ROTATE_TEXT:
            stringstyle.append("SM_ROTATE_TEXT")
            integerstyle.append(SM_ROTATE_TEXT)

        if self._agwStyle & SM_DRAW_SECTORS:
            stringstyle.append("SM_DRAW_SECTORS")
            integerstyle.append(SM_DRAW_SECTORS)

        if self._agwStyle & SM_DRAW_PARTIAL_SECTORS:
            stringstyle.append("SM_DRAW_PARTIAL_SECTORS")
            integerstyle.append(SM_DRAW_PARTIAL_SECTORS)

        if self._agwStyle & SM_DRAW_HAND:
            stringstyle.append("SM_DRAW_HAND")
            integerstyle.append(SM_DRAW_HAND)

        if self._agwStyle & SM_DRAW_SHADOW:
            stringstyle.append("SM_DRAW_SHADOW")
            integerstyle.append(SM_DRAW_SHADOW)

        if self._agwStyle & SM_DRAW_PARTIAL_FILLER:
            stringstyle.append("SM_DRAW_PARTIAL_FILLER")
            integerstyle.append(SM_DRAW_PARTIAL_FILLER)

        if self._agwStyle & SM_DRAW_SECONDARY_TICKS:
            stringstyle.append("SM_DRAW_SECONDARY_TICKS")
            integerstyle.append(SM_DRAW_SECONDARY_TICKS)

        if self._agwStyle & SM_DRAW_MIDDLE_TEXT:
            stringstyle.append("SM_DRAW_MIDDLE_TEXT")
            integerstyle.append(SM_DRAW_MIDDLE_TEXT)

        if self._agwStyle & SM_DRAW_MIDDLE_ICON:
            stringstyle.append("SM_DRAW_MIDDLE_ICON")
            integerstyle.append(SM_DRAW_MIDDLE_ICON)

        if self._agwStyle & SM_DRAW_GRADIENT:
            stringstyle.append("SM_DRAW_GRADIENT")
            integerstyle.append(SM_DRAW_GRADIENT)

        if self._agwStyle & SM_DRAW_FANCY_TICKS:
            stringstyle.append("SM_DRAW_FANCY_TICKS")
            integerstyle.append(SM_DRAW_FANCY_TICKS)

        return stringstyle, integerstyle

Navigation

  • index
  • modules |
  • Home |
  • Gallery |
  • Contents»
  • Module code »
  • speedmeter


supertooltip

  • modules |
  • Home |
  • Gallery |
  • Contents»
  • Module code »
  • supertooltip

Source code for supertooltip

# --------------------------------------------------------------------------------- #
# SUPERTOOLTIP wxPython IMPLEMENTATION
#
# Andrea Gavana, @ 07 October 2008
# Latest Revision: 14 Sep 2011, 21.00 GMT
#
#
# TODO List
#
# 1) Maybe add some more customization like multiline text
#    in the header and footer;
# 2) Check whether it's possible to use rounded corners and
#    shadows on the Mac
#
#
# 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
# --------------------------------------------------------------------------------- #

"""
L{SuperToolTip} is a class that mimics the behaviour of `wx.TipWindow` and generic tooltip
windows, although it is a custom-drawn widget.

Description
===========

L{SuperToolTip} is a class that mimics the behaviour of `wx.TipWindow` and generic tooltip
windows, although it is a custom-drawn widget.

This class supports:

* Blended triple-gradient for the tooltip background;
* Header text and header image, with possibility to set the header font indipendently;
* Footer text and footer image, with possibility to set the footer font indipendently;
* Multiline text message in the tooltip body, plus an optional image as "body image";
* Bold lines and hyperlink lines in the tooltip body;
* A wide set of predefined drawing styles for the tooltip background;
* Drawing of separator lines after the header and/or before the footer;
* Rounded corners and shadows below the tooltip window (Windows XP only);
* Fade in/fade out effects (Windows XP only);
* User-settable delays for the delay after which the tooltip appears and the delay
  after which the tooltip is destroyed.

And a lot more. Check the demo for an almost complete review of the functionalities.

Usage
=====

Usage example::

    import wx
    import wx.lib.agw.supertooltip as STT

    class MyFrame(wx.Frame):

        def __init__(self, parent):

            wx.Frame.__init__(self, parent, -1, "SuperToolTip Demo")

            panel = wx.Panel(self)
            button = wx.Button(panel, -1, "I am the SuperToolTip target", pos=(100, 50))

            tip = STT.SuperToolTip("A nice tooltip message")

            tip.SetHeader("Hello World")
            tip.SetTarget(button)
            tip.SetDrawHeaderLine(True)

            tip.ApplyStyle("Office 2007 Blue")

            tip.SetDropShadow(True)

    # our normal wxApp-derived class, as usual

    app = wx.PySimpleApp()

    frame = MyFrame(None)
    app.SetTopWindow(frame)
    frame.Show()

    app.MainLoop()

Supported Platforms
===================

L{SuperToolTip} has been tested on the following platforms:
  * Windows (Windows XP).

Window Styles
=============

`No particular window styles are available for this class.`

Events Processing
=================

`No custom events are available for this class.`

License And Version
===================

L{SuperToolTip} is distributed under the wxPython license.

Latest Revision: Andrea Gavana @ 14 Sep 2011, 21.00 GMT

Version 0.4

"""

import wx
import webbrowser

# Let's see if we can add few nice shadows to our tooltips (Windows only)
_libimported = None

if wx.Platform == "__WXMSW__":
    osVersion = wx.GetOsVersion()
    # Shadows behind menus are supported only in XP
    if osVersion[1] == 5 and osVersion[2] == 1:
        try:
            # Try Mark Hammond's win32all extensions
            import win32api
            import win32con
            import win32gui
            import winxpgui
            _libimported = "MH"
        except ImportError:
            _libimported = None
    else:
        _libimported = None

# Define a bunch of predefined colour schemes...

_colourSchemes = {"Beige": (wx.Colour(255,255,255), wx.Colour(242,242,223), wx.Colour(198,195,160), wx.Colour(0,0,0)),
                  "Blue": (wx.Colour(255,255,255), wx.Colour(202,220,246), wx.Colour(150,180,222), wx.Colour(0,0,0)),
                  "Blue 2": (wx.Colour(255,255,255), wx.Colour(228,236,248), wx.Colour(198,214,235), wx.Colour(0,0,0)),
                  "Blue 3": (wx.Colour(255,255,255), wx.Colour(213,233,243), wx.Colour(151,195,216), wx.Colour(0,0,0)),
                  "Blue 4": (wx.Colour(255,255,255), wx.Colour(227,235,255), wx.Colour(102,153,255), wx.Colour(0,0,0)),
                  "Blue Glass": (wx.Colour(182,226,253), wx.Colour(137,185,232), wx.Colour(188,244,253), wx.Colour(0,0,0)),
                  "Blue Glass 2": (wx.Colour(192,236,255), wx.Colour(147,195,242), wx.Colour(198,254,255), wx.Colour(0,0,0)),
                  "Blue Glass 3": (wx.Colour(212,255,255), wx.Colour(167,215,255), wx.Colour(218,255,255), wx.Colour(0,0,0)),
                  "Blue Inverted": (wx.Colour(117,160,222), wx.Colour(167,210,240), wx.Colour(233,243,255), wx.Colour(0,0,0)),
                  "Blue Shift": (wx.Colour(124,178,190), wx.Colour(13,122,153),  wx.Colour(0,89,116),    wx.Colour(255,255,255)),
                  "CodeProject": (wx.Colour(255,250,172), wx.Colour(255,207,157), wx.Colour(255,153,0),   wx.Colour(0,0,0)),
                  "Dark Gray": (wx.Colour(195,195,195), wx.Colour(168,168,168), wx.Colour(134,134,134), wx.Colour(255,255,255)),
                  "Deep Purple": (wx.Colour(131,128,164), wx.Colour(112,110,143), wx.Colour(90,88,117),   wx.Colour(255,255,255)),
                  "Electric Blue": (wx.Colour(224,233,255), wx.Colour(135,146,251), wx.Colour(99,109,233),  wx.Colour(0,0,0)),
                  "Firefox": (wx.Colour(255,254,207), wx.Colour(254,248,125), wx.Colour(225,119,24),  wx.Colour(0,0,0)),
                  "Gold": (wx.Colour(255,202,0),   wx.Colour(255,202,0),   wx.Colour(255,202,0),   wx.Colour(0,0,0)),
                  "Gold Shift": (wx.Colour(178,170,107), wx.Colour(202,180,32),  wx.Colour(162,139,1),   wx.Colour(255,255,255)),
                  "Gray": (wx.Colour(255,255,255), wx.Colour(228,228,228), wx.Colour(194,194,194), wx.Colour(0,0,0)),
                  "Green": (wx.Colour(234,241,223), wx.Colour(211,224,180), wx.Colour(182,200,150), wx.Colour(0,0,0)),
                  "Green Shift": (wx.Colour(129,184,129), wx.Colour(13,185,15),   wx.Colour(1,125,1), wx.Colour(255,255,255)),
                  "Light Green": (wx.Colour(174,251,171), wx.Colour(145,221,146), wx.Colour(90,176,89),   wx.Colour(0,0,0)),
                  "NASA Blue": (wx.Colour(0,91,134),    wx.Colour(0,100,150),   wx.Colour(0,105,160),   wx.Colour(255,255,255)),
                  "Office 2007 Blue": (wx.Colour(255,255,255), wx.Colour(242,246,251), wx.Colour(202,218,239), wx.Colour(76,76,76)),
                  "Orange Shift": (wx.Colour(179,120,80),  wx.Colour(183,92,19),   wx.Colour(157,73,1),    wx.Colour(255,255,255)),
                  "Outlook Green": (wx.Colour(236,242,208), wx.Colour(219,230,187), wx.Colour(195,210,155), wx.Colour(0,0,0)),
                  "Pale Green": (wx.Colour(249,255,248), wx.Colour(206,246,209), wx.Colour(148,225,155), wx.Colour(0,0,0)),
                  "Pink Blush": (wx.Colour(255,254,255), wx.Colour(255,231,242), wx.Colour(255,213,233), wx.Colour(0,0,0)),
                  "Pink Shift": (wx.Colour(202,135,188), wx.Colour(186,8,158),   wx.Colour(146,2,116),   wx.Colour(255,255,255)),
                  "Pretty Pink": (wx.Colour(255,240,249), wx.Colour(253,205,217), wx.Colour(255,150,177), wx.Colour(0,0,0)),
                  "Red": (wx.Colour(255,183,176), wx.Colour(253,157,143), wx.Colour(206,88,78),   wx.Colour(0,0,0)),
                  "Red Shift": (wx.Colour(186,102,102), wx.Colour(229,23,9),    wx.Colour(182,11,1),    wx.Colour(255,255,255)),
                  "Silver": (wx.Colour(255,255,255), wx.Colour(242,242,246), wx.Colour(212,212,224), wx.Colour(0,0,0)),
                  "Silver 2": (wx.Colour(255,255,255), wx.Colour(242,242,248), wx.Colour(222,222,228), wx.Colour(0,0,0)),
                  "Silver Glass": (wx.Colour(158,158,158), wx.Colour(255,255,255), wx.Colour(105,105,105), wx.Colour(0,0,0)),
                  "Silver Inverted": (wx.Colour(161,160,186), wx.Colour(199,201,213), wx.Colour(255,255,255), wx.Colour(0,0,0)),
                  "Silver Inverted 2": (wx.Colour(181,180,206), wx.Colour(219,221,233), wx.Colour(255,255,255), wx.Colour(0,0,0)),
                  "Soylent Green": (wx.Colour(134,211,131), wx.Colour(105,181,106), wx.Colour(50,136,49),   wx.Colour(255,255,255)),
                  "Spring Green": (wx.Colour(154,231,151), wx.Colour(125,201,126), wx.Colour(70,156,69),   wx.Colour(255,255,255)),
                  "Too Blue": (wx.Colour(255,255,255), wx.Colour(225,235,244), wx.Colour(188,209,226), wx.Colour(0,0,0)),
                  "Totally Green": (wx.Colour(190,230,160), wx.Colour(190,230,160), wx.Colour(190,230,160), wx.Colour(0,0,0)),
                  "XP Blue": (wx.Colour(119,185,236), wx.Colour(81,144,223),  wx.Colour(36,76,171),   wx.Colour(255,255,255)),
                  "Yellow": (wx.Colour(255,255,220), wx.Colour(255,231,161), wx.Colour(254,218,108), wx.Colour(0,0,0))}

[docs]def GetStyleKeys():
    """ Returns the predefined styles keywords. """

    schemes = _colourSchemes.keys()
    schemes.sort()
    return schemes

[docs]def MakeBold(font):
    """
    Makes a font bold. Utility method.

    :param `font`: the font to be made bold.
    """

    newFont = wx.Font(font.GetPointSize(), font.GetFamily(), font.GetStyle(),
                      wx.BOLD, font.GetUnderlined(), font.GetFaceName())

    return newFont

[docs]def ExtractLink(line):
    """
    Extract the link from an hyperlink line.

    :param `line`: the line of text to be processed.
    """

    line = line[4:]
    indxStart = line.find("{")
    indxEnd = line.find("}")
    hl = line[indxStart+1:indxEnd].strip()
    line = line[0:indxStart].strip()

    return line, hl

[docs]class ToolTipWindowBase(object):
    """ Base class for the different Windows and Mac implementation. """

[docs]    def __init__(self, parent, classParent):
        """
        Default class constructor.

        :param `parent`: the L{SuperToolTip} parent widget;
        :param `classParent`: the L{SuperToolTip} class object.
        """

        self._spacing = 6
        self._wasOnLink = False
        self._hyperlinkRect, self._hyperlinkWeb = [], []

        self._classParent = classParent
        self._alphaTimer = wx.Timer(self, wx.ID_ANY)

        # Bind the events
        self.Bind(wx.EVT_PAINT, self.OnPaint)
        self.Bind(wx.EVT_SIZE, self.OnSize)
        self.Bind(wx.EVT_ERASE_BACKGROUND, self.OnEraseBackground)
        self.Bind(wx.EVT_MOTION, self.OnMouseMotion)
        self.Bind(wx.EVT_TIMER, self.AlphaCycle)
        self.Bind(wx.EVT_KILL_FOCUS, self.OnDestroy)
        self.Bind(wx.EVT_LEFT_DOWN, self.OnDestroy)
        self.Bind(wx.EVT_LEFT_DCLICK, self.OnDestroy)

[docs]    def OnPaint(self, event):
        """
        Handles the ``wx.EVT_PAINT`` event for L{SuperToolTip}.

        :param `event`: a `wx.PaintEvent` event to be processed.
        """

        # Go with double buffering...
        dc = wx.BufferedPaintDC(self)

        frameRect = self.GetClientRect()
        x, y, width, height = frameRect
        # Store the rects for the hyperlink lines
        self._hyperlinkRect, self._hyperlinkWeb = [], []
        classParent = self._classParent

        # Retrieve the colours for the blended triple-gradient background
        topColour, middleColour, bottomColour = classParent.GetTopGradientColour(), \
                                                classParent.GetMiddleGradientColour(), \
                                                classParent.GetBottomGradientColour()

        # Get the user options for header, bitmaps etc...
        drawHeader, drawFooter = classParent.GetDrawHeaderLine(), classParent.GetDrawFooterLine()
        topRect = wx.Rect(frameRect.x, frameRect.y, frameRect.width, frameRect.height/2)
        bottomRect = wx.Rect(frameRect.x, frameRect.y+frameRect.height/2, frameRect.width, frameRect.height/2+1)
        # Fill the triple-gradient
        dc.GradientFillLinear(topRect, topColour, middleColour, wx.SOUTH)
        dc.GradientFillLinear(bottomRect, middleColour, bottomColour, wx.SOUTH)

        header, headerBmp = classParent.GetHeader(), classParent.GetHeaderBitmap()
        headerFont, messageFont, footerFont, hyperlinkFont = classParent.GetHeaderFont(), classParent.GetMessageFont(), \
                                                             classParent.GetFooterFont(), classParent.GetHyperlinkFont()

        xPos, yPos = self._spacing, 0
        bmpXPos = bmpYPos = 0
        bmpHeight = textHeight = bmpWidth = 0

        if headerBmp and headerBmp.IsOk():
            # We got the header bitmap
            bmpHeight, bmpWidth = headerBmp.GetHeight(), headerBmp.GetWidth()
            bmpXPos = self._spacing

        if header:
            # We got the header text
            dc.SetFont(headerFont)
            textWidth, textHeight = dc.GetTextExtent(header)

        # Calculate the header height
        height = max(textHeight, bmpHeight)
        if header:
            dc.DrawText(header, bmpXPos+bmpWidth+self._spacing, (height-textHeight+self._spacing)/2)
        if headerBmp and headerBmp.IsOk():
            dc.DrawBitmap(headerBmp, bmpXPos, (height-bmpHeight+self._spacing)/2, True)

        if header or (headerBmp and headerBmp.IsOk()):
            yPos += height
            if drawHeader:
                # Draw the separator line after the header
                dc.SetPen(wx.GREY_PEN)
                dc.DrawLine(self._spacing, yPos+self._spacing, width-self._spacing, yPos+self._spacing)

        # Get the big body image (if any)
        embeddedImage = classParent.GetBodyImage()
        bmpWidth = bmpHeight = -1
        if embeddedImage and embeddedImage.IsOk():
            bmpWidth, bmpHeight = embeddedImage.GetWidth(), embeddedImage.GetHeight()

        # A bunch of calculations to draw the main body message
        messageHeight = 0
        textSpacing = (bmpWidth > 0 and [3*self._spacing] or [2*self._spacing])[0]
        lines = classParent.GetMessage().split("\n")
        yText = yPos
        normalText = wx.SystemSettings_GetColour(wx.SYS_COLOUR_MENUTEXT)
        hyperLinkText = wx.BLUE

        for indx, line in enumerate(lines):
            # Loop over all the lines in the message
            isLink = False
            dc.SetTextForeground(normalText)
            if line.startswith("</b>"):      # is a bold line
                line = line[4:]
                font = MakeBold(messageFont)
                dc.SetFont(font)
            elif line.startswith("</l>"):    # is a link
                dc.SetFont(hyperlinkFont)
                isLink = True
                line, hl = ExtractLink(line)
                dc.SetTextForeground(hyperLinkText)
            else:
                # Is a normal line
                dc.SetFont(messageFont)

            textWidth, textHeight = dc.GetTextExtent(line)
            if textHeight == 0:
                textWidth, textHeight = dc.GetTextExtent("a")

            messageHeight += textHeight

            xText = (bmpWidth > 0 and [bmpWidth+2*self._spacing] or [self._spacing])[0]
            yText += textHeight/2+self._spacing

            dc.DrawText(line, xText, yText)
            if isLink:
                # Store the hyperlink rectangle and link
                self._hyperlinkRect.append(wx.Rect(xText, yText, textWidth, textHeight))
                self._hyperlinkWeb.append(hl)

            if indx == 0:
                messagePos = yText

        toAdd = 0
        if bmpHeight > textHeight:
            yPos += 2*self._spacing + bmpHeight
            toAdd = self._spacing
        else:
            yPos += messageHeight + 2*self._spacing

        yText = max(messageHeight, bmpHeight+2*self._spacing)
        if embeddedImage and embeddedImage.IsOk():
            # Draw the main body image
            dc.DrawBitmap(embeddedImage, self._spacing, messagePos, True)

        footer, footerBmp = classParent.GetFooter(), classParent.GetFooterBitmap()
        bmpHeight = bmpWidth = textHeight = textWidth = 0
        bmpXPos = bmpYPos = 0

        if footerBmp and footerBmp.IsOk():
            # Got the footer bitmap
            bmpHeight, bmpWidth = footerBmp.GetHeight(), footerBmp.GetWidth()
            bmpXPos = self._spacing

        if footer:
            # Got the footer text
            dc.SetFont(footerFont)
            textWidth, textHeight = dc.GetTextExtent(footer)

        if textHeight or bmpHeight:
            if drawFooter:
                # Draw the separator line before the footer
                dc.SetPen(wx.GREY_PEN)
                dc.DrawLine(self._spacing, yPos-self._spacing/2+toAdd, width-self._spacing, yPos-self._spacing/2+toAdd)

        # Draw the footer and footer bitmap (if any)
        dc.SetTextForeground(normalText)
        height = max(textHeight, bmpHeight)
        yPos += toAdd
        if footer:
            dc.DrawText(footer, bmpXPos+bmpWidth+self._spacing, yPos + (height-textHeight+self._spacing)/2)
        if footerBmp and footerBmp.IsOk():
            dc.DrawBitmap(footerBmp, bmpXPos, yPos + (height-bmpHeight+self._spacing)/2, True)

[docs]    def OnEraseBackground(self, event):
        """
        Handles the ``wx.EVT_ERASE_BACKGROUND`` event for L{SuperToolTip}.

        :param `event`: a `wx.EraseEvent` event to be processed.

        :note: This method is intentionally empty to reduce flicker.
        """

        # This is intentionally empty to reduce flicker
        pass

[docs]    def OnSize(self, event):
        """
        Handles the ``wx.EVT_SIZE`` event for L{SuperToolTip}.

        :param `event`: a `wx.SizeEvent` event to be processed.
        """

        self.Refresh()
        event.Skip()

[docs]    def OnMouseMotion(self, event):
        """
        Handles the ``wx.EVT_MOTION`` event for L{SuperToolTip}.

        :param `event`: a `wx.MouseEvent` event to be processed.
        """

        x, y = event.GetPosition()
        for rect in self._hyperlinkRect:
            if rect.Contains((x, y)):
                # We are over one hyperlink...
                self.SetCursor(wx.StockCursor(wx.CURSOR_HAND))
                self._wasOnLink = True
                return

        if self._wasOnLink:
            # Restore the normal cursor
            self._wasOnLink = False
            self.SetCursor(wx.NullCursor)

[docs]    def OnDestroy(self, event):
        """
        Handles the ``wx.EVT_LEFT_DOWN``, ``wx.EVT_LEFT_DCLICK`` and ``wx.EVT_KILL_FOCUS``
        events for L{SuperToolTip}. All these events destroy the L{SuperToolTip},
        unless the user clicked on one hyperlink.

        :param `event`: a `wx.MouseEvent` or a `wx.FocusEvent` event to be processed.
        """

        if not isinstance(event, wx.MouseEvent):
            # We haven't clicked a link
            self.Destroy()
            return

        x, y = event.GetPosition()
        for indx, rect in enumerate(self._hyperlinkRect):
            if rect.Contains((x, y)):
                # Run the webbrowser with the clicked link
                webbrowser.open_new_tab(self._hyperlinkWeb[indx])
                return

        if self._classParent.GetUseFade():
            # Fade out...
            self.StartAlpha(False)
        else:
            self.Destroy()

[docs]    def StartAlpha(self, isShow):
        """
        Start the timer which set the alpha channel for L{SuperToolTip}.

        :param `isShow`: whether L{SuperToolTip} is being shown or deleted.

        :note: This method is available only on Windows and requires Mark Hammond's
         pywin32 package.
        """

        if self._alphaTimer.IsRunning():
            return

        # Calculate starting alpha value and its step
        self.amount = (isShow and [0] or [255])[0]
        self.delta = (isShow and [5] or [-5])[0]
        # Start the timer
        self._alphaTimer.Start(30)

[docs]    def SetFont(self, font):
        """
        Sets the L{SuperToolTip} font globally.

        :param `font`: the font to set.
        """

        wx.PopupWindow.SetFont(self, font)
        self._classParent.InitFont()
        self.Invalidate()

[docs]    def Invalidate(self):
        """ Invalidate L{SuperToolTip} size and repaint it. """

        if not self._classParent.GetMessage():
            # No message yet...
            return

        self.CalculateBestSize()
        self.Refresh()

[docs]    def DropShadow(self, drop=True):
        """
        Adds a shadow under the window.

        :param `drop`: whether to drop a shadow or not.

        :note: This method is available only on Windows and requires Mark Hammond's
         pywin32 package.
        """

        if not _libimported:
            # No Mark Hammond's win32all extension
            return

        if wx.Platform != "__WXMSW__":
            # This works only on Windows XP
            return

        hwnd = self.GetHandle()

        # Create a rounded rectangle region
        size = self.GetSize()
        if drop:
            if hasattr(win32gui, "CreateRoundRectRgn"):
                rgn = win32gui.CreateRoundRectRgn(0, 0, size.x, size.y, 9, 9)
                win32gui.SetWindowRgn(hwnd, rgn, True)

        CS_DROPSHADOW = 0x00020000
        # Load the user32 library
        if not hasattr(self, "_winlib"):
            self._winlib = win32api.LoadLibrary("user32")

        csstyle = win32api.GetWindowLong(hwnd, win32con.GCL_STYLE)
        if drop:
            if csstyle & CS_DROPSHADOW:
                return
            else:
                csstyle |= CS_DROPSHADOW     #Nothing to be done
        else:
            csstyle &= ~CS_DROPSHADOW

        # Drop the shadow underneath the window
        GCL_STYLE= -26
        cstyle= win32gui.GetClassLong(hwnd, GCL_STYLE)
        if drop:
            if cstyle & CS_DROPSHADOW == 0:
                win32api.SetClassLong(hwnd, GCL_STYLE, cstyle | CS_DROPSHADOW)
        else:
            win32api.SetClassLong(hwnd, GCL_STYLE, cstyle &~ CS_DROPSHADOW)

[docs]    def AlphaCycle(self, event):
        """
        Handles the ``wx.EVT_TIMER`` event for L{SuperToolTip}.

        :param `event`: a `wx.TimerEvent` event to be processed.
        """

        # Increase (or decrease) the alpha channel
        self.amount += self.delta

        if self.amount > 255 or self.amount < 0:
            # We're done, stop the timer
            self._alphaTimer.Stop()
            if self.amount < 0:
                # Destroy the SuperToolTip, we are fading out
                self.Destroy()
            return

        # Make the SuperToolTip more or less transparent
        self.MakeWindowTransparent(self.amount)
        if not self.IsShown():
            self.Show()

[docs]    def MakeWindowTransparent(self, amount):
        """
        Makes the L{SuperToolTip} window transparent.

        :param `amount`: the alpha channel value.

        :note: This method is available only on Windows and requires Mark Hammond's
         pywin32 package.
        """

        if not _libimported:
            # No way, only Windows XP with Mark Hammond's win32all
            return

        # this API call is not in all SDKs, only the newer ones, so
        # we will runtime bind this
        if wx.Platform != "__WXMSW__":
            return

        hwnd = self.GetHandle()

        if not hasattr(self, "_winlib"):
            self._winlib = win32api.LoadLibrary("user32")

        pSetLayeredWindowAttributes = win32api.GetProcAddress(self._winlib,
                                                              "SetLayeredWindowAttributes")

        if pSetLayeredWindowAttributes == None:
            return

        exstyle = win32api.GetWindowLong(hwnd, win32con.GWL_EXSTYLE)
        if 0 == (exstyle & 0x80000):
            win32api.SetWindowLong(hwnd, win32con.GWL_EXSTYLE, exstyle | 0x80000)

        winxpgui.SetLayeredWindowAttributes(hwnd, 0, amount, 2)

[docs]    def CalculateBestSize(self):
        """ Calculates the L{SuperToolTip} window best size. """

        # See the OnPaint method for explanations...
        maxWidth = maxHeight = 0
        dc = wx.ClientDC(self)

        classParent = self._classParent
        header, headerBmp = classParent.GetHeader(), classParent.GetHeaderBitmap()

        textHeight, bmpHeight = 0, 0
        headerFont, messageFont, footerFont, hyperlinkFont = classParent.GetHeaderFont(), classParent.GetMessageFont(), \
                                                             classParent.GetFooterFont(), classParent.GetHyperlinkFont()
        if header:
            dc.SetFont(headerFont)
            textWidth, textHeight = dc.GetTextExtent(header)
            maxWidth = max(maxWidth, textWidth + 2*self._spacing)
            maxHeight += self._spacing/2
        if headerBmp and headerBmp.IsOk():
            maxWidth += headerBmp.GetWidth() + 2*self._spacing
            bmpHeight = headerBmp.GetHeight()
            if not header:
                maxHeight += self._spacing/2

        maxHeight += max(textHeight, bmpHeight)
        if textHeight or bmpHeight:
            maxHeight += self._spacing/2

        # See the OnPaint method for explanations...
        bmpWidth = bmpHeight = -1
        embeddedImage = classParent.GetBodyImage()
        if embeddedImage and embeddedImage.IsOk():
            bmpWidth, bmpHeight = embeddedImage.GetWidth(), embeddedImage.GetHeight()

        messageHeight = 0
        textSpacing = (bmpWidth and [3*self._spacing] or [2*self._spacing])[0]
        lines = classParent.GetMessage().split("\n")

        for line in lines:
            if line.startswith("</b>"):      # is a bold line
                font = MakeBold(messageFont)
                dc.SetFont(font)
                line = line[4:]
            elif line.startswith("</l>"):    # is a link
                dc.SetFont(hyperlinkFont)
                line, hl = ExtractLink(line)
            else:
                dc.SetFont(messageFont)

            textWidth, textHeight = dc.GetTextExtent(line)
            if textHeight == 0:
                textWidth, textHeight = dc.GetTextExtent("a")

            maxWidth = max(maxWidth, textWidth + textSpacing + bmpWidth)
            messageHeight += textHeight

        # See the OnPaint method for explanations...
        messageHeight = max(messageHeight, bmpHeight)
        maxHeight += messageHeight
        toAdd = 0
        if bmpHeight > textHeight:
            maxHeight += 2*self._spacing
            toAdd = self._spacing
        else:
            maxHeight += 2*self._spacing

        footer, footerBmp = classParent.GetFooter(), classParent.GetFooterBitmap()
        textHeight, bmpHeight = 0, 0

        # See the OnPaint method for explanations...
        if footer:
            dc.SetFont(footerFont)
            textWidth, textHeight = dc.GetTextExtent(footer)
            maxWidth = max(maxWidth, textWidth + 2*self._spacing)
            maxHeight += self._spacing/2

        if footerBmp and footerBmp.IsOk():
            bmpWidth, bmpHeight = footerBmp.GetWidth(), footerBmp.GetHeight()
            maxWidth = max(maxWidth, textWidth + 3*self._spacing + bmpWidth)
            if not footer:
                maxHeight += self._spacing/2

        if textHeight or bmpHeight:
            maxHeight += self._spacing/2 + max(textHeight, bmpHeight)

        maxHeight += toAdd
        self.SetSize((maxWidth, maxHeight))

[docs]    def CalculateBestPosition(self,widget):
        screen = wx.ClientDisplayRect()[2:]
        left,top = widget.ClientToScreenXY(0,0)
        right,bottom = widget.ClientToScreenXY(*widget.GetClientRect()[2:])
        size = self.GetSize()
        if right+size[0]>screen[0]:
            xpos = left-size[0]
        else:
            xpos = right
        if bottom+size[1]>screen[1]:
            ypos = top-size[1]
        else:
            ypos = bottom
        self.SetPosition((xpos,ypos))

# Handle Mac and Windows/GTK differences...

if wx.Platform == "__WXMAC__":

    class ToolTipWindow(wx.Frame, ToolTipWindowBase):
        """ Popup window that works on wxMac. """

        def __init__(self, parent, classParent):
            """
            Default class constructor.

            :param `parent`: the L{SuperToolTip} parent widget;
            :param `classParent`: the L{SuperToolTip} class object.
            """

            wx.Frame.__init__(self, parent, style=wx.NO_BORDER|wx.FRAME_FLOAT_ON_PARENT|wx.FRAME_NO_TASKBAR|wx.POPUP_WINDOW)
            # Call the base class
            ToolTipWindowBase.__init__(self, parent, classParent)

else:

[docs]    class ToolTipWindow(ToolTipWindowBase, wx.PopupWindow):
        """
        A simple `wx.PopupWindow` that holds fancy tooltips.
        Not available on Mac as `wx.PopupWindow` is not implemented there.
        """

[docs]        def __init__(self, parent, classParent):
            """
            Default class constructor.

            :param `parent`: the L{SuperToolTip} parent widget;
            :param `classParent`: the L{SuperToolTip} class object.
            """

            wx.PopupWindow.__init__(self, parent)
            # Call the base class
            ToolTipWindowBase.__init__(self, parent, classParent)

[docs]class SuperToolTip(object):
    """
    The main class for L{SuperToolTip}, which holds all the methods
    and setters/getters available to the user.
    """

[docs]    def __init__(self, message, bodyImage=wx.NullBitmap, header="", headerBmp=wx.NullBitmap,
                 footer="", footerBmp=wx.NullBitmap):
        """
        Default class constructor.

        :param `message`: the main message in L{SuperToolTip} body;
        :param `bodyImage`: the image in the L{SuperToolTip} body;
        :param `header`: the header text;
        :param `headerBmp`: the header bitmap;
        :param `footer`: the footer text;
        :param `footerBmp`: the footer bitmap.
        """

        self._superToolTip = None

        # Set all the initial options
        self.SetMessage(message)
        self.SetBodyImage(bodyImage)
        self.SetHeader(header)
        self.SetHeaderBitmap(headerBmp)
        self.SetFooter(footer)
        self.SetFooterBitmap(footerBmp)
        self._dropShadow = False
        self._useFade = False

        self._topLine = False
        self._bottomLine = False

        self.InitFont()

        # Get the running applications
        self._runningApp = wx.GetApp()
        self._runningApp.__superToolTip = True

        # Build a couple of timers...
        self._startTimer = wx.PyTimer(self.OnStartTimer)
        self._endTimer = wx.PyTimer(self.OnEndTimer)

        self.SetStartDelay()
        self.SetEndDelay()
        self.ApplyStyle("XP Blue")

[docs]    def SetTarget(self, widget):
        """
        Sets the target window for L{SuperToolTip}.

        :param `widget`: the widget to which L{SuperToolTip} is associated.
        """

        self._widget = widget

        self._widget.Bind(wx.EVT_ENTER_WINDOW, self.OnWidgetEnter)
        self._widget.Bind(wx.EVT_LEAVE_WINDOW, self.OnWidgetLeave)

[docs]    def GetTarget(self):
        """ Returns the target window for L{SuperToolTip}. """

        if not hasattr(self, "_widget"):
            raise Exception("\nError: the widget target for L{SuperToolTip} has not been set.")

        return self._widget

[docs]    def SetStartDelay(self, delay=1):
        """
        Sets the time delay (in seconds) after which the L{SuperToolTip} is created.

        :param `delay`: the delay in seconds.
        """

        self._startDelayTime = float(delay)

[docs]    def GetStartDelay(self):
        """ Returns the tim delay (in seconds) after which the L{SuperToolTip} is created."""

        return self._startDelayTime

[docs]    def SetEndDelay(self, delay=1e6):
        """
        Sets the delay time (in seconds) after which the L{SuperToolTip} is destroyed.

        :param `delay`: the delay in seconds.
        """

        self._endDelayTime = float(delay)

[docs]    def GetEndDelay(self):
        """ Returns the delay time (in seconds) after which the L{SuperToolTip} is destroyed."""

        return self._endDelayTime

[docs]    def OnWidgetEnter(self, event):
        """
        Starts the L{SuperToolTip} timer for creation, handles the ``wx.EVT_ENTER_WINDOW`` event.

        :param `event`: a `wx.MouseEvent` event to be processed.
        """

        if self._superToolTip:
            # Not yet created
            return

        if not self._runningApp.__superToolTip:
            # The running app doesn't want tooltips...
            return

        if self._startTimer.IsRunning():
            # We are already running
            event.Skip()
            return

        self._startTimer.Start(self._startDelayTime*1000)
        event.Skip()

[docs]    def OnWidgetLeave(self, event):
        """
        Handles the ``wx.EVT_LEAVE_WINDOW`` event for the target widgets.

        :param `event`: a `wx.MouseEvent` event to be processed.
        """

        pos = wx.GetMousePosition()
        realPos = self._widget.ScreenToClient(pos)
        rect = self._widget.GetClientRect()

        if rect.Contains(realPos):
            # We get fake leave events...
            event.Skip()
            return

        if self._superToolTip:
            if self.GetUseFade():
                # Fade out...
                self._superToolTip.StartAlpha(False)
            else:
                self._superToolTip.Destroy()

        self._startTimer.Stop()
        self._endTimer.Stop()

        event.Skip()

[docs]    def GetTipWindow(self):
        """ Return the TipWindow, will return None if not yet created """

        return self._superToolTip

[docs]    def OnStartTimer(self):
        """ The creation time has expired, create the L{SuperToolTip}. """

        # target widget might already be destroyed
        if not self._widget:
            self._startTimer.Stop()
            return

        tip = ToolTipWindow(self._widget, self)
        self._superToolTip = tip
        self._superToolTip.CalculateBestSize()
        self._superToolTip.CalculateBestPosition(self._widget)
        self._superToolTip.DropShadow(self.GetDropShadow())

        if self.GetUseFade():
            self._superToolTip.StartAlpha(True)
        else:
            self._superToolTip.Show()

        self._startTimer.Stop()
        self._endTimer.Start(self._endDelayTime*1000)

[docs]    def OnEndTimer(self):
        """ The show time for L{SuperToolTip} has expired, destroy the L{SuperToolTip}. """

        if self._superToolTip:
            if self.GetUseFade():
                self._superToolTip.StartAlpha(False)
            else:
                self._superToolTip.Destroy()

        self._endTimer.Stop()

[docs]    def DoShowNow(self):
        """ Create the L{SuperToolTip} immediately. """

        if self._superToolTip:
            # need to destroy it if already exists,
            # otherwise we might end up with many of them
            self._superToolTip.Destroy()

        tip = ToolTipWindow(self._widget, self)
        self._superToolTip = tip
        self._superToolTip.CalculateBestSize()
        self._superToolTip.CalculateBestPosition(self._widget)
        self._superToolTip.DropShadow(self.GetDropShadow())

        # need to stop this, otherwise we get into trouble when leaving the window
        self._startTimer.Stop()

        if self.GetUseFade():
            self._superToolTip.StartAlpha(True)
        else:
            self._superToolTip.Show()

        self._endTimer.Start(self._endDelayTime*1000)

[docs]    def OnDestroy(self, event):
        """ Handles the L{SuperToolTip} target destruction. """

        if self._superToolTip:
            # Unbind the events!
            self._widget.Unbind(wx.EVT_LEAVE_WINDOW)
            self._widget.Unbind(wx.EVT_ENTER_WINDOW)

            self._superToolTip.Destroy()
            del self._superToolTip
            self._superToolTip = None

[docs]    def SetHeaderBitmap(self, bmp):
        """
        Sets the header bitmap for L{SuperToolTip}.

        :param `bmp`: the header bitmap, a valid `wx.Bitmap` object.
        """

        self._headerBmp = bmp
        if self._superToolTip:
            self._superToolTip.Invalidate()

[docs]    def GetHeaderBitmap(self):
        """ Returns the header bitmap. """

        return self._headerBmp

[docs]    def SetHeader(self, header):
        """
        Sets the header text.

        :param `header`: the header text to display.
        """

        self._header = header
        if self._superToolTip:
            self._superToolTip.Invalidate()

[docs]    def GetHeader(self):
        """ Returns the header text. """

        return self._header

[docs]    def SetDrawHeaderLine(self, draw):
        """
        Sets whether to draw a separator line after the header or not.

        :param `draw`: ``True`` to draw a separator line after the header, ``False``
         otherwise.
        """

        self._topLine = draw
        if self._superToolTip:
            self._superToolTip.Refresh()

[docs]    def GetDrawHeaderLine(self):
        """ Returns whether the separator line after the header is drawn or not. """

        return self._topLine

[docs]    def SetBodyImage(self, bmp):
        """
        Sets the main body bitmap for L{SuperToolTip}.

        :param `bmp`: the body bitmap, a valid `wx.Bitmap` object.
        """

        self._embeddedImage = bmp
        if self._superToolTip:
            self._superToolTip.Invalidate()

[docs]    def GetBodyImage(self):
        """ Returns the main body bitmap used in L{SuperToolTip}. """

        return self._embeddedImage

[docs]    def SetDrawFooterLine(self, draw):
        """
        Sets whether to draw a separator line before the footer or not.

        :param `draw`: ``True`` to draw a separator line before the footer, ``False``
         otherwise.
        """

        self._bottomLine = draw
        if self._superToolTip:
            self._superToolTip.Refresh()

[docs]    def GetDrawFooterLine(self):
        """ Returns whether the separator line before the footer is drawn or not. """

        return self._bottomLine

[docs]    def SetFooterBitmap(self, bmp):
        """
        Sets the footer bitmap for L{SuperToolTip}.

        :param `bmp`: the footer bitmap, a valid `wx.Bitmap` object.
        """

        self._footerBmp = bmp
        if self._superToolTip:
            self._superToolTip.Invalidate()

[docs]    def GetFooterBitmap(self):
        """ Returns the footer bitmap. """

        return self._footerBmp

[docs]    def SetFooter(self, footer):
        """
        Sets the footer text.

        :param `footer`: the footer text to display.
        """

        self._footer = footer
        if self._superToolTip:
            self._superToolTip.Invalidate()

[docs]    def GetFooter(self):
        """ Returns the footer text. """

        return self._footer

[docs]    def SetMessage(self, message):
        """
        Sets the main body message for L{SuperToolTip}.

        :param `message`: the message to display in the body.
        """

        self._message = message
        if self._superToolTip:
            self._superToolTip.Invalidate()

[docs]    def GetMessage(self):
        """ Returns the main body message in L{SuperToolTip}. """

        return self._message

[docs]    def SetTopGradientColour(self, colour):
        """
        Sets the top gradient colour for L{SuperToolTip}.

        :param `colour`: the colour to use as top colour, a valid `wx.Colour` object.
        """

        self._topColour = colour
        if self._superToolTip:
            self._superToolTip.Refresh()

[docs]    def SetMiddleGradientColour(self, colour):
        """
        Sets the middle gradient colour for L{SuperToolTip}.

        :param `colour`: the colour to use as middle colour, a valid `wx.Colour` object.
        """

        self._middleColour = colour
        if self._superToolTip:
            self._superToolTip.Refresh()

[docs]    def SetBottomGradientColour(self, colour):
        """
        Sets the bottom gradient colour for L{SuperToolTip}.

        :param `colour`: the colour to use as bottom colour, a valid `wx.Colour` object.
        """

        self._bottomColour = colour
        if self._superToolTip:
            self._superToolTip.Refresh()

[docs]    def SetTextColour(self, colour):
        """
        Sets the text colour for L{SuperToolTip}.

        :param `colour`: the colour to use as text colour, a valid `wx.Colour` object.
        """

        self._textColour = colour
        if self._superToolTip:
            self._superToolTip.Refresh()

[docs]    def GetTopGradientColour(self):
        """ Returns the top gradient colour. """

        return self._topColour

[docs]    def GetMiddleGradientColour(self):
        """ Returns the middle gradient colour. """

        return self._middleColour

[docs]    def GetBottomGradientColour(self):
        """ Returns the bottom gradient colour. """

        return self._bottomColour

[docs]    def GetTextColour(self):
        """ Returns the text colour. """

        return self._textColour

    SetTopGradientColor = SetTopGradientColour
    SetMiddleGradientColor = SetMiddleGradientColour
    SetBottomGradientColor = SetBottomGradientColour
    GetTopGradientColor = GetTopGradientColour
    GetMiddleGradientColor = GetMiddleGradientColour
    GetBottomGradientColor = GetBottomGradientColour
    SetTextColor = SetTextColour
    GetTextColor = GetTextColour

[docs]    def InitFont(self):
        """ Initalizes the fonts for L{SuperToolTip}. """

        self._messageFont = wx.SystemSettings_GetFont(wx.SYS_DEFAULT_GUI_FONT)
        self._headerFont = wx.SystemSettings_GetFont(wx.SYS_DEFAULT_GUI_FONT)
        self._headerFont.SetWeight(wx.BOLD)
        self._footerFont = wx.SystemSettings_GetFont(wx.SYS_DEFAULT_GUI_FONT)
        self._footerFont.SetWeight(wx.BOLD)
        self._hyperlinkFont = wx.SystemSettings_GetFont(wx.SYS_DEFAULT_GUI_FONT)
        self._hyperlinkFont.SetWeight(wx.BOLD)
        self._hyperlinkFont.SetUnderlined(True)

[docs]    def SetMessageFont(self, font):
        """
        Sets the font for the main body message.

        :param `font`: the font to use for the main body message, a valid `wx.Font`
         object.
        """

        self._messageFont = font
        if self._superToolTip:
            self._superToolTip.Invalidate()

[docs]    def SetHeaderFont(self, font):
        """
        Sets the font for the header text.

        :param `font`: the font to use for the header text, a valid `wx.Font`
         object.
        """

        self._headerFont = font
        if self._superToolTip:
            self._superToolTip.Invalidate()

[docs]    def SetFooterFont(self, font):
        """
        Sets the font for the footer text.

        :param `font`: the font to use for the footer text, a valid `wx.Font`
         object.
        """

        self._footerFont = font
        if self._superToolTip:
            self._superToolTip.Invalidate()

[docs]    def SetHyperlinkFont(self, font):
        """
        Sets the font for the hyperlink text.

        :param `font`: the font to use for the hyperlink text, a valid `wx.Font`
         object.
        """

        self._hyperlinkFont = font
        if self._superToolTip:
            self._superToolTip.Invalidate()

[docs]    def GetMessageFont(self):
        """ Returns the font used in the main body message. """

        return self._messageFont

[docs]    def GetHeaderFont(self):
        """ Returns the font used for the header text. """

        return self._headerFont

[docs]    def GetFooterFont(self):
        """ Returns the font used for the footer text. """

        return self._footerFont

[docs]    def GetHyperlinkFont(self):
        """ Returns the font used for the hyperlink text. """

        return self._hyperlinkFont

[docs]    def SetDropShadow(self, drop):
        """
        Whether to draw a shadow below L{SuperToolTip} or not.

        :param `drop`: ``True`` to drop a shadow below the control, ``False`` otherwise.

        :note: This method is available only on Windows and requires Mark Hammond's
         pywin32 package.
        """

        self._dropShadow = drop
        if self._superToolTip:
            self._superToolTip.Invalidate()

[docs]    def GetDropShadow(self):
        """
        Returns whether a shadow below L{SuperToolTip} is drawn or not.

        :note: This method is available only on Windows and requires Mark Hammond's
         pywin32 package.
        """

        return self._dropShadow

[docs]    def SetUseFade(self, fade):
        """
        Whether to use a fade in/fade out effect or not.

        :param `fade`: ``True`` to use a fade in/fade out effect, ``False`` otherwise.

        :note: This method is available only on Windows and requires Mark Hammond's
         pywin32 package.
        """

        self._useFade = fade

[docs]    def GetUseFade(self):
        """
        Returns whether a fade in/fade out effect is used or not.

        :note: This method is available only on Windows and requires Mark Hammond's
         pywin32 package.
        """

        return self._useFade

[docs]    def ApplyStyle(self, style):
        """
        Applies none of the predefined styles.

        :param `style`: one of the predefined styles available at the
         beginning of the module.
        """

        if style not in _colourSchemes:
            raise Exception("Invalid style '%s' selected"%style)

        top, middle, bottom, text = _colourSchemes[style]
        self._topColour = top
        self._middleColour = middle
        self._bottomColour = bottom
        self._textColour = text

        if self._superToolTip:
            self._superToolTip.Refresh()

[docs]    def EnableTip(self, enable=True):
        """
        Globally (application-wide) enables/disables L{SuperToolTip}.

        :param `enable`: ``True`` to enable L{SuperToolTip} globally, ``False`` otherwise.
        """

        wx.GetApp().__superToolTip = enable
        if not enable and self._superToolTip:
            self._superToolTip.Destroy()
            self._superToolTip = None
            del self._superToolTip

Navigation

  • index
  • modules |
  • Home |
  • Gallery |
  • Contents»
  • Module code »
  • supertooltip


thumbnailctrl

  • modules |
  • Home |
  • Gallery |
  • Contents»
  • Module code »
  • thumbnailctrl

Source code for thumbnailctrl

# --------------------------------------------------------------------------- #
# THUMBNAILCTRL Control wxPython IMPLEMENTATION
# Python Code By:
#
# Andrea Gavana And Peter Damoc, @ 12 Dec 2005
# Latest Revision: 17 Aug 2011, 15.00 GMT
#
#
# TODO List/Caveats
#
# 1. Thumbnail Creation/Display May Be Somewhat Improved From The Execution
#    Speed Point Of View;
#
# 2. The Implementation For wx.HORIZONTAL Style Is Still To Be Written;
#
# 3. I Have No Idea On How To Implement Thumbnails For Audio, Video And Other Files.
#
# 4. Other Ideas?
#
#
# 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
# --------------------------------------------------------------------------- #

"""
L{ThumbnailCtrl} is a widget that can be used to display a series of images in
a "thumbnail" format.

Description
===========

L{ThumbnailCtrl} is a widget that can be used to display a series of images in
a "thumbnail" format; it mimics, for example, the windows explorer behavior
when you select the "view thumbnails" option.
Basically, by specifying a folder that contains some image files, the files
in the folder are displayed as miniature versions of the actual images in
a `wx.ScrolledWindow`.

The code is partly based on `wxVillaLib`, a wxWidgets implementation of this
control. However, L{ThumbnailCtrl} wouldn't have been so fast and complete
without the suggestions and hints from Peter Damoc. So, if he accepts the
mention, this control is his as much as mine.

Usage
=====

Usage example::

    import os

    import wx
    import wx.lib.agw.thumbnailctrl as TC

    class MyFrame(wx.Frame):

        def __init__(self, parent):

            wx.Frame.__init__(self, parent, -1, "ThumbnailCtrl Demo")

            panel = wx.Panel(self)

            sizer = wx.BoxSizer(wx.VERTICAL)

            thumbnail = TC.ThumbnailCtrl(panel, imagehandler=TC.NativeImageHandler)
            sizer.Add(thumbnail, 1, wx.EXPAND | wx.ALL, 10)

            thumbnail.ShowDir(os.getcwd())
            panel.SetSizer(sizer)

    # our normal wxApp-derived class, as usual

    app = wx.PySimpleApp()

    frame = MyFrame(None)
    app.SetTopWindow(frame)
    frame.Show()

    app.MainLoop()

Methods and Settings
====================

With L{ThumbnailCtrl} you can:

- Create different thumbnail outlines (none, images only, full, etc...);
- Highlight thumbnails on mouse hovering;
- Show/hide file names below thumbnails;
- Change thumbnail caption font;
- Zoom in/out thumbnails (done via ``Ctrl`` key + mouse wheel or with ``+`` and ``-`` chars,
  with zoom factor value customizable);
- Rotate thumbnails with these specifications:

  a) ``d`` key rotates 90 degrees clockwise;
  b) ``s`` key rotates 90 degrees counter-clockwise;
  c) ``a`` key rotates 180 degrees.

- Delete files/thumbnails (via the ``del`` key);
- Drag and drop thumbnails from L{ThumbnailCtrl} to whatever application you want;
- Use local (when at least one thumbnail is selected) or global (no need for
  thumbnail selection) popup menus;
- Show/hide a `wx.ComboBox` at the top of L{ThumbnailCtrl}: this combobox contains
  working directory information and it has history entries;
- possibility to show tooltips on thumbnails, which display file information
  (like file name, size, last modification date and thumbnail size).

:note: Using highlight thumbnails on mouse hovering may be slow on slower
 computers.

Window Styles
=============

`No particular window styles are available for this class.`

Events Processing
=================

This class processes the following events:

================================== ==================================================
Event Name                         Description
================================== ==================================================
``EVT_THUMBNAILS_CAPTION_CHANGED`` The thumbnail caption has been changed. Not used at present.
``EVT_THUMBNAILS_DCLICK``          The user has double-clicked on a thumbnail.
``EVT_THUMBNAILS_POINTED``         The mouse cursor is hovering over a thumbnail.
``EVT_THUMBNAILS_SEL_CHANGED``     The user has changed the selected thumbnail.
``EVT_THUMBNAILS_THUMB_CHANGED``   The thumbnail of an image has changed. Used internally.
================================== ==================================================

License And Version
===================

L{ThumbnailCtrl} is distributed under the wxPython license.

Latest revision: Andrea Gavana @ 17 Aug 2011, 15.00 GMT

Version 0.9

"""

#----------------------------------------------------------------------
# Beginning Of ThumbnailCtrl wxPython Code
#----------------------------------------------------------------------

import wx
import os
import time
import cStringIO
import zlib

import thread
from math import pi

from wx.lib.embeddedimage import PyEmbeddedImage

#----------------------------------------------------------------------
# Get Default Icon/Data
#----------------------------------------------------------------------

[docs]def GetMondrianData():
    """ Returns a default image placeholder as a decompressed stream of characters. """
    return \
'\x89PNG\r\n\x1a\n\x00\x00\x00\rIHDR\x00\x00\x00 \x00\x00\x00 \x08\x06\x00\
\x00\x00szz\xf4\x00\x00\x00\x04sBIT\x08\x08\x08\x08|\x08d\x88\x00\x00\x00qID\
ATX\x85\xed\xd6;\n\x800\x10E\xd1{\xc5\x8d\xb9r\x97\x16\x0b\xad$\x8a\x82:\x16\
o\xda\x84pB2\x1f\x81Fa\x8c\x9c\x08\x04Z{\xcf\xa72\xbcv\xfa\xc5\x08 \x80r\x80\
\xfc\xa2\x0e\x1c\xe4\xba\xfaX\x1d\xd0\xde]S\x07\x02\xd8>\xe1wa-`\x9fQ\xe9\
\x86\x01\x04\x10\x00\\(Dk\x1b-\x04\xdc\x1d\x07\x14\x98;\x0bS\x7f\x7f\xf9\x13\
\x04\x10@\xf9X\xbe\x00\xc9 \x14K\xc1<={\x00\x00\x00\x00IEND\xaeB`\x82'

[docs]def GetMondrianBitmap():
    """ Returns a default image placeholder as a `wx.Bitmap`. """

    return wx.BitmapFromImage(GetMondrianImage())

[docs]def GetMondrianImage():
    """ Returns a default image placeholder as a `wx.Image`. """

    stream = cStringIO.StringIO(GetMondrianData())
    return wx.ImageFromStream(stream)

#----------------------------------------------------------------------

file_broken = PyEmbeddedImage(
    "iVBORw0KGgoAAAANSUhEUgAAAEAAAABACAYAAACqaXHeAAAABGdBTUEAAK/INwWK6QAADU9J"
    "REFUeJzNWn1QE2cefja7yRI+lAKiAgKCVIqegUYMFMsM4kfvzk7nmFrnvHGcOT3bq3P/OJ1p"
    "b+zYf+r0HGxt6VVFqpYqWq9TW23RVnp6R7FXiq0UPAGhyFeQSCQJISHZ7Mf9gZuGkE02IeA9"
    "M5k3u/vuu+/z/H7v7/297y4BPzh//vxfSJIsIgjC5a/eTIPn+UnHgiDIqisIAsUwTNfmzZtf"
    "A8D7qk/5e3B0dPS6wsLCp/09MFTIbdO7ntR9vs5HRESgvr6+E0AlAD2AKZX8CsDzvEKtVsvq"
    "aKjw7LggCO7jcJQqlQoMw6gBpAIYRAgCECGxCgDPTsohEopI4n+e5xXww1MRHkry4d1Zf9fk"
    "uv90MOsCeMKfGN51pO6ZrmizKsBsWt976EjhoQ+BYMQItpSDWRNAjptPZ4xLCfl/PQTCaX2p"
    "+wNhVgSYbet7tumdRXpj1ofAbFhfqn1fmHEBHpb1AYAgAudxMy4AQRB+LReuSB/MGsETMyqA"
    "2WyG1WqVZQl/CDUZeuge0NvbKwwODk7bC7zryYFI/qF6QGNj42BnZ6dZ6rocQtNNhQNhxgQw"
    "Go24fPnyDy0tLTcFQfDpBZ7/w2198RcIMyZAW1vb+KVLlxoGBwfr7927B4Vi8qO8CfnqbCjW"
    "D4Y8MEMCCIKA77777me73d7a1tb25dDQkNXzmud/giDgdDrBsqzkuA1l7CuVSgCA0+n0y3FG"
    "BBgYGMCVK1eub926dRFN04aBgYH/el73JKRUKjE4OIi+vj5QFDWtaVG0fGRkJHiex7lz5xyn"
    "T59uBMBI9TWsAoidaW1tNTc1Nd1cv379zuzs7F91dHT8x+l0TooDnuju7h779ttvjdOdLlUq"
    "FaKjo9HV1YX9+/d379q16+QXX3xxFsAAMHU7DAgggNw1tQiCIOByuXDt2rWbK1asUOfk5KxM"
    "SUlZW19f39LX18eTJDmpbbG8cePGndra2mtDQ0NQKpUhJUPR0dHgeR6ffvqpbdeuXV+9/vrr"
    "R4eGhs4A+ArA3ZAECAXd3d24dOnSD2VlZavy8vKQmppaUFdXN2gwGO561yVJEmazGR0dHV3n"
    "z5//+NatW0MU5XebcgooikJMTAy6urqwb9++zp07d1ZfvXq1GsAn8+bNa6qsrEyGxJY4EGBT"
    "lCAIhVR0ZhgGTqcTTqcTDocDDocDgiDgm2++0Y+MjNxbuXLl7wmCQFpaWtbcuXMje3p6fly9"
    "enWyeL8gCCBJEj09PUJLS0s7z/PXWlpavigoKNhBURRYlnU/S6qMjIwEwzD47LPPbIcOHWq4"
    "cuXKPwF8D+DHF154QV1cXFxpsVjiAGwGYIUPL/ArgNFoNNbV1dmtVqvdarW6LBaLY2xszOFw"
    "OBiLxWKz2WxOs9lsHx0ddZhMJpvZbB7v7u7+effu3elZWVmJAJCUlBS1bt26nNbW1kaj0fj0"
    "I4884iYHAHfu3Lnf2dnZDWC4oaHhH08++eRWrVZLe9bxJk9RFNRqNTo6OvDhhx92Hj16tG5k"
    "ZKQBwHUAneXl5cVarfaQVqtddurUqesAUgC0BysAsWfPngOjo6ONY2NjUQzDOACMA7ADcGAi"
    "sjoBuB6U4jFTWlp6Kj4+HjzPIzExEbm5uSuPHz9+csuWLfaEhIRIl8sFgiDA8zxu3rz585Yt"
    "W3SpqanX9u7d+93GjRuv5eXlrRGvT+oQQUCtVsPhcODcuXO2w4cPi1ZvAnADgP3EiRN7NBrN"
    "ntzcXDXHcXA6nREAJF9u+BNA6OnpuQ1gGAD5gCjrUXIPFOUflAIA7siRI8Xp6ekaYOI1lVKp"
    "RGZmpqatre2QXq/v1mg0y4EJKxoMBrS1tQ2UlJQ8abPZjAD23Lhx46Pi4uI1aWlp7mEl1qdp"
    "Grdu3UJNTU1nVVVV3cjIyDUAPwJof+WVVzJ0Ol1NQUHBbxMTEyHOOoEQKOKMP/jJxoIFC/6Q"
    "mZlJidYTBAHp6emp2dnZCV1dXY0MwywnCAIkSUKv1zu7u7uNu3fvTh8aGtoE4Pj7779/ec2a"
    "NZ0ZGRlZwC9Wt9vt+Pzzz22VlZUNV69eFa3+EwDTkSNHynJyct5ZtWpVikKhgMPhgEKhkJx2"
    "gxFgSv1t27ZRUVFRFMuyZGZmZmJcXNwcpVIZT9N0tMvlWpiSklKmVConBbGkpCRq3bp1Kxsb"
    "G69v3Lhxe3p6OgRBQHt7u2Hx4sVRycnJ9Ny5czO3bdv2VHV19XvNzc2frF69+pXY2FgoFAop"
    "q3ds2rQp6plnnnkzLy9v99KlS8EwDDiOC2r5LSnAiRMnIubNm/dHkiSzaZqOIUkygabpGIqi"
    "4iiKmkuSZDRJkiqVSkWRJKmkaZqMiIhAZGQkOI5zk+c4DnFxccjOztZWVVV9+eKLLw5nZGTM"
    "YxgGzc3Ndx577LGF8fHxiI2NhU6n+111dfWZixcvnispKfmzTqebe+HCBW+rtwK4/8Ybb+Rp"
    "NJojBQUFq2JiYuB0OgH8kgqLpdiXoAVobW2NfvbZZ/cWFhbOly3ngwf6yvczMzNzWJZV9Pb2"
    "/lRUVLR2cHAQt2/fvrt9+3YtSZJQKBRYtmxZYXFx8ar6+vqrTU1NF7/++mtdZWXll0ajsQET"
    "Qa4TE3HmBY1Gsz8/P3+Oy+Vyj3dP8nK9QFKA/v5+Cn7GfzBZmiAISE5OTiwqKsq4fft2k91u"
    "X9vf3283GAyWtLS0ZNFTsrOzI0pKSsrq6+v//c477/xNr9evwMRr7ZsAhl966aUFOp3uzfz8"
    "/C2LFi3C+Pj4JMLeAsjJYiUFYFk2oIRyReA4DikpKSgqKlpZW1t7saysjOvo6NAvXbo0NjEx"
    "MZLneXAchzlz5kCj0TwVGxu7RK/Xt2Mihx8DwBw4cGBDbm5uRWFh4aNKpRJ2u30S8VCsD8hY"
    "CwRzXqouz/OIiopCVlaWtrm5+X57e/tAS0uLPicnJzEhIcE9TnmeR05OTvJzzz33a0xMtyNa"
    "rVY4fvz4a6WlpRdKSkoeFZfPYpSXIi93SyzYWWASMTmlZ/2MjIys+Pj4mI6Ojoa+vj5h/fr1"
    "xaKrikIlJyfj8ccfLwNw7NVXX43TarV/LyoqWhsXF4fx8XF3TPFF2Pv/tPIAu93ul7g/+BJD"
    "EAQsXLgwqrS0NLexsfE8RVHLFi1atNn7PpVKhdzc3OUvv/zyvg0bNvwmPz8/WeyPt8sHEkLO"
    "anZaQyCYDUmO47BgwQIsX758VW1t7bc6nU5ISkpSeuYLHMeBYRhkZWWpd+zY8afCwsJklmXB"
    "MMwUlw9EXjwOhIDL4dHRUQwMDMBms4Hn+YCuJSUKz/NQqVRYsmTJcgDzlixZsnzOnDlu1xfj"
    "AMdxoGkaqampsNvtEATBvZ8olzxBEO57whIDxsbGMD4+DrVajaioKERGRoKiKMmdXn9IT09P"
    "Li4ufiIxMVEHACzLThGW47gp54IhHwz8CiCSEt3P4XDA6XTCYrGApmnQNA2VSuUWwzvyescA"
    "l8uF+fPnK59//vm/zp8/f6FoebF98VlSBOWS99WXkATwfrhnw+JmiEKhgEKhAEmSEDM6KTEI"
    "gkBcXBwRExOTkpCQAJfLNSPkg4EsD/Algncs4Hl+ktv6+onjOS0tDTRNT1q4hJN8MCKE5AFS"
    "nQx0DQAYhkFqaqpbrJkmH5YPJMJFXqFQTBmTM0E+LB5gt9slXTpU8t4E5JKXSnsDkfV+HReU"
    "AJ6YLnlf1pNLXhAEmM1msCw7KSZ598/7PEEQ4DgOLMv6VSHQt8JhIS/HG/y5vV6vh9FohFqt"
    "ducN3r8pxCgKJpMJvb29o/hlzzI4AUSEk7yUtfyJwTAMMjMzsXjxYr/zuuf7wbt376K8vLz/"
    "7NmzlzCxpA5NgHCTl1vHFzkAPjNE774aDAaUl5f3V1RU1HAc9y9MbKr4RMA8QIr4TJP3LEU3"
    "5zjOnTtItWUwGLB//36R/CVMbKXZQhbAV2dnk7zYD3G1KI537/oURbndvqKi4hTHcV9iYvd4"
    "zB/HkFPh6ZL3JurvHIBJXuB9XfzG4MCBA/3vvvtujVzysgTwR2I65KVmAl/3iUtmlmUnDQGR"
    "/P3793H48GH9A/Ki2wckH1AAzxjgS4yZJO/dD899A7EORVEYGRlBVVWV8b333vs4GMvLEsAT"
    "oQ4Ff+Q92/YniGcMEAUQ5/ljx44Nv/XWWx9ZrdaLAJqDIR9QAO/9gHCTlxsERRFEAZRKJUwm"
    "E6qrq4cPHjx4xmq11mLi1bglGPIBBfBF8mGQFyHmACaTCSdPnhx+++23z4yOjtZi4pWZKVjy"
    "sgTwFiIU8v7GuVzyIsxmM06fPj188ODBjx5Y/nsAkl+jBoLsPECEryDl7ziQMHLJkyQJi8WC"
    "mpqa4YqKCtHtmzAN8oCM9wJKpRIRERGyyAQi6CvwyeokRcFsNqOurm64oqLijMVimZbbT2pb"
    "6gJN04TNZlNZLBYwDOOeEgNtMsqpF+y1sbEx1NbWDn/wwQdhJQ8AkmZYsWJFVEZGxtZ79+49"
    "wbIsDa/VlBQJqS0of6QD3UMQBHp7e++YTKYrCIPbe8KfHyoALACwGIAqXA8MEQImPnO7A2Ak"
    "nA3/D+/OyD/Ur3BPAAAAAElFTkSuQmCC")

[docs]def getDataSH():
    """ Return the first part of the shadow dropped behind thumbnails. """

    return zlib.decompress(
'x\xda\xeb\x0c\xf0s\xe7\xe5\x92\xe2b``\xe0\xf5\xf4p\t\x02\xd2_A\x98\x83\rHvl\
\xdc\x9c\n\xa4X\x8a\x9d<C8\x80\xa0\x86#\xa5\x83\x81\x81y\x96\xa7\x8bcH\xc5\
\x9c\xb7\xd7\xd7\xf6\x85D2\xb4^\xbc\x1b\xd0\xd0p\xa6\x85\x9d\xa1\xf1\xc0\xc7\
\x7f\xef\x8d\x98\xf89_:p]\xaew\x0c\xe9\x16[\xbc\x8bSt\xdf\x9aT\xad\xef\xcb\
\x8e\x98\xc5\xbf\xb3\x94\x9ePT\xf8\xff\xf7\xfbm\xf5\xdb\xfeZ<\x16{\xf01o[l\
\xee\xee\xbd7\xbe\x95\xdd\xde\x9d+\xbf\xfdo\xf9\xb9\xd0\x03\x8be\xb7\xc7\xe6\
Y\xcb\xbd\x8b\xdfs\xe3[\xd6\xed\xe5\x9b}\x99\xe6=:\xbd\xed\xfc\xedu|\xfcq\
\xfb\xec/K<\xf8\xfec\xd7\xdb\xdb\x87W\xec\xcf\xfd]\xb0\xcc\xf0\xc0\xe5=\xf7^\
\x1e\xf9\xfb\xe6\xe6\xce\xe9\x0c\xfb\xa7\xafPt\xbb"\xa0\x9c\xd5!hz\xa4C*\xc9\
\x85\xd7pQ\x9bD\xa0s\xcf\xa8\xf0\xa8\xf0\x00\x0b\x9fyX\x7fo\xef\xdf\xc7\xda\
\r\xcbw\xd4\xfcx\xe0\xcdk\xd8\x9e[~{\xdd\xf6\xbfw\xbe\xfd\xddS\xdc\xe0\xfec_\
\xf0\xfe\xeb\xb7\xdf\xf1\xdd\xce\xdb&\xbb\xbdv\xe7\xff\xc3\xaf\x8dy\x99\xe5\
\x9e?\xf7\xfb+\xb7\xfdnLN\xf5\xc6\xb7g\xfd\xca_\x9a\x7f?\x7f\xe0\xfe\xe3\xaa\
\xe5\x0b\xf4\xb7\xcb\xea\x97\xed\n\xb7\xbf\xff\xadh\xf9\xe3\x1d\xd5f\x7fb\
\xdf\x95Y\x15\xc6\xe7\xee\xfe\xcbz7Y\xbd\xde[\xf3y\x1f0\xd72x\xba\xfa\xb9\
\xacsJh\x02\x00\xc4i\x8dN' )

[docs]def getDataBL():
    """ Return the second part of the shadow dropped behind thumbnails. """

    return zlib.decompress(
"x\xda\xeb\x0c\xf0s\xe7\xe5\x92\xe2b``\xe0\xf5\xf4p\t\x02\xd2\xac \xcc\xc1\
\x06${\xf3\xd5\x9e\x02)\x96b'\xcf\x10\x0e \xa8\xe1H\xe9\x00\xf2\xed=]\x1cC8f\
\xea\x9e\xde\xcb\xd9` \xc2\xf0P\xdf~\xc9y\xaeu\x0f\xfe1\xdf\xcc\x14\x1482A\
\xe9\xfd\x83\x1d\xaf\x84\xac\xf8\xe6\\\x8c3\xfc\x98\xf8\xa0\xb1\xa9K\xec\x9f\
\xc4\xd1\xb4GG{\xb5\x15\x8f_|t\x8a[a\x1fWzG\xa9\xc4,\xa0Q\x0c\x9e\xae~.\xeb\
\x9c\x12\x9a\x00\x7f1,7" )

[docs]def getDataTR():
    """ Return the third part of the shadow dropped behind thumbnails. """

    return zlib.decompress(
'x\xda\xeb\x0c\xf0s\xe7\xe5\x92\xe2b``\xe0\xf5\xf4p\t\x02\xd2\xac \xcc\xc1\
\x06${\xf3\xd5\x9e\x02)\x96b\'\xcf\x10\x0e \xa8\xe1H\xe9\x00\xf2m=]\x1cC8f\
\xe6\x9e\xd9\xc8\xd9` \xc2p\x91\xbd\xaei\xeeL\x85\xdcUo\xf6\xf7\xd6\xb2\x88\
\x0bp\x9a\x89i\x16=-\x94\xe16\x93\xb9!\xb8y\xcd\t\x0f\x89\n\xe6\xb7\xfcV~6\
\x8dFo\xf5\xee\xc8\x1fOaw\xc9\x88\x0c\x16\x05\x1a\xc4\xe0\xe9\xea\xe7\xb2\
\xce)\xa1\t\x00"\xf9$\x83' )

[docs]def getShadow():
    """ Creates a shadow behind every thumbnail. """

    sh_tr = wx.ImageFromStream(cStringIO.StringIO(getDataTR())).ConvertToBitmap()
    sh_bl = wx.ImageFromStream(cStringIO.StringIO(getDataBL())).ConvertToBitmap()
    sh_sh = wx.ImageFromStream(cStringIO.StringIO(getDataSH())).Rescale(500, 500, wx.IMAGE_QUALITY_HIGH)
    return (sh_tr, sh_bl, sh_sh.ConvertToBitmap())

#-----------------------------------------------------------------------------
# PATH & FILE FILLING (OS INDEPENDENT)
#-----------------------------------------------------------------------------

[docs]def opj(path):
    """
    Convert paths to the platform-specific separator.

    :param `path`: the path to convert.
    """

    strs = apply(os.path.join, tuple(path.split('/')))
    # HACK: on Linux, a leading / gets lost...
    if path.startswith('/'):
        strs = '/' + strs

    return strs

#-----------------------------------------------------------------------------

# Different Outline On Thumb Selection:
# THUMB_OUTLINE_NONE: No Outline Drawn On Selection
# THUMB_OUTLINE_FULL: Full Outline Drawn On Selection
# THUMB_OUTLINE_RECT: Only Maximum Image Rect Outlined On Selection
# THUMB_OUTLINE_IMAGE: Only Image Rect Outlined On Selection

THUMB_OUTLINE_NONE = 0
THUMB_OUTLINE_FULL = 1
THUMB_OUTLINE_RECT = 2
THUMB_OUTLINE_IMAGE = 4

# Options For Filtering Files
THUMB_FILTER_IMAGES = 1
# THUMB_FILTER_VIDEOS = 2  Don't Know How To Create Thumbnails For Videos!!!

# ThumbnailCtrl Orientation: Not Fully Implemented Till Now
THUMB_HORIZONTAL = wx.HORIZONTAL
THUMB_VERTICAL = wx.VERTICAL

# Image File Name Extensions: Am I Missing Some Extensions Here?
extensions = [".jpeg", ".jpg", ".bmp", ".png", ".ico", ".tiff", ".ani", ".cur", ".gif",
              ".iff", ".icon", ".pcx", ".tif", ".xpm", ".xbm", ".mpeg", ".mpg", ".mov"]

# ThumbnailCtrl Events:
# wxEVT_THUMBNAILS_SEL_CHANGED: Event Fired When You Change Thumb Selection
# wxEVT_THUMBNAILS_POINTED: Event Fired When You Point A Thumb
# wxEVT_THUMBNAILS_DCLICK: Event Fired When You Double-Click A Thumb
# wxEVT_THUMBNAILS_CAPTION_CHANGED: Not Used At Present
# wxEVT_THUMBNAILS_THUMB_CHANGED: Used Internally

wxEVT_THUMBNAILS_SEL_CHANGED = wx.NewEventType()
wxEVT_THUMBNAILS_POINTED = wx.NewEventType()
wxEVT_THUMBNAILS_DCLICK = wx.NewEventType()
wxEVT_THUMBNAILS_CAPTION_CHANGED = wx.NewEventType()
wxEVT_THUMBNAILS_THUMB_CHANGED = wx.NewEventType()

#-----------------------------------#
#        ThumbnailCtrlEvent
#-----------------------------------#

EVT_THUMBNAILS_SEL_CHANGED = wx.PyEventBinder(wxEVT_THUMBNAILS_SEL_CHANGED, 1)
""" The user has changed the selected thumbnail. """
EVT_THUMBNAILS_POINTED = wx.PyEventBinder(wxEVT_THUMBNAILS_POINTED, 1)
""" The mouse cursor is hovering over a thumbnail. """
EVT_THUMBNAILS_DCLICK = wx.PyEventBinder(wxEVT_THUMBNAILS_DCLICK, 1)
""" The user has double-clicked on a thumbnail. """
EVT_THUMBNAILS_CAPTION_CHANGED = wx.PyEventBinder(wxEVT_THUMBNAILS_CAPTION_CHANGED, 1)
""" The thumbnail caption has been changed. Not used at present. """
EVT_THUMBNAILS_THUMB_CHANGED = wx.PyEventBinder(wxEVT_THUMBNAILS_THUMB_CHANGED, 1)
""" The thumbnail of an image has changed. Used internally"""

TN_USE_PIL = 0

TIME_FMT = '%d %b %Y, %H:%M:%S'

[docs]def CmpThumb(first, second):
    """
    Compares two thumbnails in terms of file names and ids.

    :param `first`: an instance of L{Thumb};
    :param `second`: another instance of L{Thumb}.
    """

    if first.GetFileName() < second.GetFileName():
        return -1
    elif first.GetFullFileName() == second.GetFullFileName():
        return first.GetId() - second.GetId()

    return 1

[docs]def SortFiles(items, sorteditems, filenames):
    """
    Sort files in alphabetical order.

    :param `sorteditems`: a list of L{Thumb} objects;
    :param `filenames`: a list of image filenames.
    """

    newfiles = []
    for item in sorteditems:
        newfiles.append(filenames[items.index(item)])

    return newfiles

# ---------------------------------------------------------------------------- #
# Class PILImageHandler, handles loading and highlighting images with PIL
# ---------------------------------------------------------------------------- #

[docs]class PILImageHandler(object):
    """
    This image handler loads and manipulates the thumbnails with the help
    of PIL (the Python Imaging Library).
    """

[docs]    def __init__(self):
        """
        Default class constructor.

        :note: If PIL is not installed, this will raise an exception. PIL
         can be downloaded from http://www.pythonware.com/products/pil/ .
        """

        try:

            import PIL.Image as Image
            import PIL.ImageEnhance as ImageEnhance

        except ImportError:

            errstr = ("\nThumbnailCtrl *requires* PIL (Python Imaging Library).\n"
                     "You can get it at:\n\n"
                     "http://www.pythonware.com/products/pil/\n\n"
                     "ThumbnailCtrl can not continue. Exiting...\n")

            raise Exception(errstr)

[docs]    def LoadThumbnail(self, filename, thumbnailsize):
        """
        Load the file and rescale it.

        :param `filename`: a file containing an image;
        :param `thumbnailsize`: the desired size of the thumbnail.
        """

        import PIL.Image as Image

        pil = Image.open(filename)
        originalsize = pil.size

        pil.thumbnail(thumbnailsize)
        img = wx.EmptyImage(pil.size[0], pil.size[1])

        img.SetData(pil.convert("RGB").tostring())

        alpha = False
        if "A" in pil.getbands():
            img.SetAlphaData(pil.convert("RGBA").tostring()[3::4])
            alpha = True

        return img, originalsize, alpha

[docs]    def HighlightImage(self, img, factor):
        """
        Adjust overall image brightness to highlight.

        :param `img`: an instance of `wx.Image`;
        :param `factor`: unused in L{PILImageHandler}.
        """

        import PIL.Image as Image
        import PIL.ImageEnhance as ImageEnhance

        pil = Image.new('RGB', (img.GetWidth(), img.GetHeight()))
        pil.fromstring(img.GetData())
        enh = ImageEnhance.Brightness(pil)
        enh = enh.enhance(1.5)
        img.SetData(enh.convert('RGB').tostring())
        return img

# ---------------------------------------------------------------------------- #
# Class NativeImageHandler, handles loading and highlighting images with wx
# ---------------------------------------------------------------------------- #

[docs]class NativeImageHandler(object):
    """
    This image handler loads and manipulates the thumbnails with the help of
    wxPython's own image related functions.
    """

[docs]    def LoadThumbnail(self, filename, thumbnailsize):
        """
        Load the file and rescale it.

        :param `filename`: a file containing an image;
        :param `thumbnailsize`: the desired size of the thumbnail.
        """

        img = wx.Image(filename)

        # Don't stop when a corrupt file is to be loaded, show Mondrian instead
        try:
            originalsize = (img.GetWidth(), img.GetHeight())
        except:
            img = file_broken.GetImage()
            originalsize = (img.GetWidth(), img.GetHeight())

        img.Rescale(min(thumbnailsize[0], originalsize[0]), min(thumbnailsize[1], originalsize[1]), wx.IMAGE_QUALITY_NORMAL)
        alpha = img.HasAlpha()

        return img, originalsize, alpha

[docs]    def HighlightImage(self, img, factor):
        """
        Adjust overall image brightness to highlight.

        :param `img`: an instance of `wx.Image`;
        :param `factor`: a floating point number representing the highlight factor.
        """

        return img.AdjustChannels(factor, factor, factor, factor)

# ---------------------------------------------------------------------------- #
# Class ThumbnailEvent
# ---------------------------------------------------------------------------- #

[docs]class ThumbnailEvent(wx.PyCommandEvent):
    """
    This class is used to send events when a thumbnail is hovered, selected,
    double-clicked or when its caption has been changed.
    """

[docs]    def __init__(self, evtType, evtId=-1):
        """
        Default class constructor.

        :param `evtType`: the event type;
        :param `evtId`: the event identifier.
        """

        wx.PyCommandEvent.__init__(self, evtType, evtId)
        self._eventType = evtType

# ---------------------------------------------------------------------------- #
# Class Thumb
# Auxiliary Class, To Handle Single Thumb Information For Every Thumb.
# Used Internally.
# ---------------------------------------------------------------------------- #

[docs]class Thumb(object):
    """
    This is an auxiliary class, to handle single thumbnail information for every thumb.

    Used internally.
    """

[docs]    def __init__(self, parent, folder, filename, caption="", size=0, lastmod=0):
        """
        Default class constructor.

        :param `parent`: the main L{ThumbnailCtrl} window;
        :param `folder`: the directory containing the images;
        :param `filename`: a file containing an image;
        :param `caption`: the thumbnail caption string;
        :param `size`: the file size;
        :param `lastmod`: the file last modification time.
        """

        self._filename = filename
        self.SetCaption(caption)
        self._id = 0
        self._dir = folder
        self._filesize = size
        self._lastmod = lastmod
        self._parent = parent
        self._captionbreaks = []
        self._bitmap = wx.EmptyBitmap(1,1)
        self._image = wx.EmptyImage(1,1)
        self._rotation = 0
        self._alpha = None

[docs]    def SetCaption(self, caption=""):
        """
        Sets the thumbnail caption.

        :param `caption`: the thumbnail caption string.
        """

        self._caption = caption
        self._captionbreaks = []

[docs]    def GetImage(self):
        """ Returns the thumbnail image. """

        return self._image

[docs]    def SetImage(self, image):
        """
        Sets the thumbnail image.

        :param `image`: a `wx.Image` object.
        """

        self._image = image

[docs]    def SetBitmap(self, bmp):
        """
        Sets the thumbnail bitmap.

        :param `bmp`: a `wx.Bitmap` object.
        """

        self._bitmap = bmp

[docs]    def GetFileName(self):
        """ Returns the file name associated with this thumbnail. """

        return self._filename

[docs]    def SetFileName(self, filename):
        """
        Sets the file name associated with this thumbnail.

        :param `filename`: the file containing the image.
        """

        self._filename = filename
        self._bitmap = wx.EmptyBitmap(1, 1)

[docs]    def GetId(self):
        """ Returns the thumbnail identifier. """

        return self._id

[docs]    def SetId(self, id=-1):
        """
        Sets the thumbnail identifier.

        :param `id`: an integer specifying the thumbnail identifier.
        """

        self._id = id

[docs]    def SetRotatedImage(self, image):
        """
        Sets the image as rotated (fast).

        :param `image`: the rotated image, an instance of `wx.Image`.
        """

        self._rotatedimage = image

[docs]    def GetRotatedImage(self):
        """ Returns a rotated image. """

        return self._rotatedimage

[docs]    def GetBitmap(self, width, height):
        """
        Returns the associated bitmap.

        :param `width`: the associated bitmap width;
        :param `height`: the associated bitmap height.
        """

        if self.GetRotation() % (2*pi) < 1e-6:
            if not self._bitmap.Ok():
                if not hasattr(self, "_threadedimage"):
                    img = GetMondrianImage()
                else:
                    img = self._threadedimage

            else:
                if not hasattr(self, "_threadedimage"):
                    img = GetMondrianImage()
                else:
                    img = self._threadedimage

        else:

            img = self.GetRotatedImage()

        if hasattr(self, "_originalsize"):
            imgwidth, imgheight = self._originalsize
        else:
            imgwidth, imgheight = (img.GetWidth(), img.GetHeight())

        if width < imgwidth or height < imgheight:
            scale = float(width)/imgwidth

            if scale > float(height)/imgheight:
                scale = float(height)/imgheight

            newW, newH = int(imgwidth*scale), int(imgheight*scale)
            if newW < 1:
                newW = 1
            if newH < 1:
                newH = 1

            img = img.Scale(newW, newH)

        bmp = img.ConvertToBitmap()

        self._image = img

        return bmp

[docs]    def GetOriginalImage(self):
        """ Returns the bitmap associated to a thumbnail, as a file name. """

        original = opj((self._dir + "/" + self._filename))

        return original

[docs]    def GetFullFileName(self):
        """ Returns the full filename of the thumbnail. """

        return self._dir + "/" + self._filename

[docs]    def GetCaption(self, line):
        """
        Returns the caption associated to a thumbnail.

        :param `line`: the caption line we wish to retrieve (useful for multilines
         caption strings).
        """

        if line + 1 >= len(self._captionbreaks):
            return ""

        strs = self._caption

        return strs

[docs]    def GetFileSize(self):
        """ Returns the file size associated to a thumbnail. """

        return self._filesize

[docs]    def GetCreationDate(self):
        """ Returns the file last modification date associated to a thumbnail. """

        return self._lastmod

[docs]    def GetOriginalSize(self):
        """ Returns a tuple containing the original image width and height, in pixels. """

        if hasattr(self, "_threadedimage"):
            img = self._threadedimage
        else:
            img = GetMondrianImage()

        if hasattr(self, "_originalsize"):
            imgwidth, imgheight = self._originalsize
        else:
            imgwidth, imgheight = (img.GetWidth(), img.GetHeight())

        return imgwidth, imgheight

[docs]    def GetCaptionLinesCount(self, width):
        """
        Returns the number of lines for the caption.

        :param `width`: the maximum width, in pixels, available for the caption text.
        """

        self.BreakCaption(width)
        return len(self._captionbreaks) - 1

[docs]    def BreakCaption(self, width):
        """
        Breaks the caption in several lines of text (if needed).

        :param `width`: the maximum width, in pixels, available for the caption text.
        """

        if len(self._captionbreaks) > 0 or width < 16:
            return

        self._captionbreaks.append(0)

        if len(self._caption) == 0:
            return

        pos = width/16
        beg = 0
        end = 0

        dc = wx.MemoryDC()
        bmp = wx.EmptyBitmap(10,10)
        dc.SelectObject(bmp)

        while 1:

            if pos >= len(self._caption):

                self._captionbreaks.append(len(self._caption))
                break

            sw, sh = dc.GetTextExtent(self._caption[beg:pos-beg])

            if  sw > width:

                if end > 0:

                    self._captionbreaks.append(end)
                    beg = end

                else:

                    self._captionbreaks.append(pos)
                    beg = pos

                pos = beg + width/16
                end = 0

            if pos < len(self._caption) and self._caption[pos] in [" ", "-", ",", ".", "_"]:
                end = pos + 1

            pos = pos + 1

        dc.SelectObject(wx.NullBitmap)

[docs]    def SetRotation(self, angle=0):
        """
        Sets the thumbnail rotation.

        :param `angle`: the thumbnail rotation, in radians.
        """

        self._rotation = angle

[docs]    def GetRotation(self):
        """ Returns the thumbnail rotation, in radians. """

        return self._rotation

# ---------------------------------------------------------------------------- #
# Class ThumbnailCtrl
# Auxiliary Class, All Useful Methods Are Defined On ScrolledThumbnail Class.
# ---------------------------------------------------------------------------- #

[docs]class ThumbnailCtrl(wx.Panel):
    """
    L{ThumbnailCtrl} is a widget that can be used to display a series of images in
    a "thumbnail" format.
    """

[docs]    def __init__(self, parent, id=wx.ID_ANY, pos=wx.DefaultPosition,
                 size=wx.DefaultSize, thumboutline=THUMB_OUTLINE_IMAGE,
                 thumbfilter=THUMB_FILTER_IMAGES, imagehandler=PILImageHandler):
        """
        Default class constructor.

        :param `parent`: parent window. Must not be ``None``;
        :param `id`: window identifier. A value of -1 indicates a default value;
        :param `pos`: the control position. A value of (-1, -1) indicates a default position,
         chosen by either the windowing system or wxPython, depending on platform;
        :param `size`: the control size. A value of (-1, -1) indicates a default size,
         chosen by either the windowing system or wxPython, depending on platform;
        :param `thumboutline`: outline style for L{ThumbnailCtrl}, which may be:

         =========================== ======= ==================================
         Outline Flag                 Value  Description
         =========================== ======= ==================================
         ``THUMB_OUTLINE_NONE``            0 No outline is drawn on selection
         ``THUMB_OUTLINE_FULL``            1 Full outline (image+caption) is drawn on selection
         ``THUMB_OUTLINE_RECT``            2 Only thumbnail bounding rectangle is drawn on selection (default)
         ``THUMB_OUTLINE_IMAGE``           4 Only image bounding rectangle is drawn.
         =========================== ======= ==================================

        :param `thumbfilter`: filter for image/video/audio files. Actually only
         ``THUMB_FILTER_IMAGES`` is implemented;
        :param `imagehandler`: can be L{PILImageHandler} if PIL is installed (faster), or
         L{NativeImageHandler} which only uses wxPython image methods.
        """

        wx.Panel.__init__(self, parent, id, pos, size)

        self._sizer = wx.BoxSizer(wx.VERTICAL)

        self._combo = wx.ComboBox(self, -1, style=wx.CB_DROPDOWN | wx.CB_READONLY)
        self._scrolled = ScrolledThumbnail(self, -1, thumboutline=thumboutline,
                                           thumbfilter=thumbfilter, imagehandler = imagehandler)

        subsizer = wx.BoxSizer(wx.HORIZONTAL)
        subsizer.Add((3, 0), 0)
        subsizer.Add(self._combo, 0, wx.EXPAND | wx.TOP, 3)
        subsizer.Add((3, 0), 0)
        self._sizer.Add(subsizer, 0, wx.EXPAND | wx.ALL, 3)
        self._sizer.Add(self._scrolled, 1, wx.EXPAND)

        self.SetSizer(self._sizer)

        self._sizer.Show(0, False)
        self._sizer.Layout()

        methods = ["GetSelectedItem", "GetPointed", "GetHighlightPointed", "SetHighlightPointed",
                   "SetThumbOutline", "GetThumbOutline", "GetPointedItem", "GetItem",
                   "GetItemCount", "GetThumbWidth", "GetThumbHeight", "GetThumbBorder",
                   "ShowFileNames", "SetPopupMenu", "GetPopupMenu", "SetGlobalPopupMenu",
                   "GetGlobalPopupMenu", "SetSelectionColour", "GetSelectionColour",
                   "EnableDragging", "SetThumbSize", "GetThumbSize", "ShowThumbs", "ShowDir",
                   "GetShowDir", "SetSelection", "GetSelection", "SetZoomFactor",
                   "GetZoomFactor", "SetCaptionFont", "GetCaptionFont", "GetItemIndex",
                   "InsertItem", "RemoveItemAt", "IsSelected", "Rotate", "ZoomIn", "ZoomOut",
                   "EnableToolTips", "GetThumbInfo", "GetOriginalImage", "SetDropShadow", "GetDropShadow"]

        for method in methods:
            setattr(self, method, getattr(self._scrolled, method))

        self._combochoices = []
        self._showcombo = False
        self._subsizer = subsizer

        self._combo.Bind(wx.EVT_COMBOBOX, self.OnComboBox)

[docs]    def ShowComboBox(self, show=True):
        """
        Shows/Hide the top folder `wx.ComboBox`.

        :param `show`: ``True`` to show the combobox, ``False`` otherwise.
        """

        if show:
            self._showcombo = True
            self._sizer.Show(0, True)
            self._sizer.Layout()
        else:
            self._showcombo = False
            self._sizer.Show(0, False)
            self._sizer.Layout()

        self._scrolled.Refresh()

[docs]    def GetShowComboBox(self):
        """ Returns whether the folder combobox is shown. """

        return self._showcombo

[docs]    def OnComboBox(self, event):
        """
        Handles the ``wx.EVT_COMBOBOX`` for the folder combobox.

        :param `event`: a `wx.CommandEvent` event to be processed.
        """

        dirs = self._combo.GetValue()

        if os.path.isdir(opj(dirs)):
            self._scrolled.ShowDir(opj(dirs))

        event.Skip()

[docs]    def RecreateComboBox(self, newdir):
        """
        Recreates the folder combobox every time a new directory is explored.

        :param `newdir`: the new folder to be explored.
        """

        newdir = newdir.strip()

        if opj(newdir) in self._combochoices:
            return

        self.Freeze()

        self._sizer.Detach(0)
        self._subsizer.Detach(1)
        self._subsizer.Destroy()
        self._combo.Destroy()

        subsizer = wx.BoxSizer(wx.HORIZONTAL)

        self._combochoices.insert(0, opj(newdir))

        self._combo = wx.ComboBox(self, -1, value=newdir, choices=self._combochoices,
                                  style=wx.CB_DROPDOWN | wx.CB_READONLY)

        subsizer.Add((3, 0), 0)
        subsizer.Add(self._combo, 1, wx.EXPAND | wx.TOP, 3)
        subsizer.Add((3, 0), 0)
        self._sizer.Insert(0, subsizer, 0, wx.EXPAND | wx.ALL, 3)

        self._subsizer = subsizer

        self._subsizer.Layout()

        if not self.GetShowComboBox():
            self._sizer.Show(0, False)

        self._sizer.Layout()

        self._combo.Bind(wx.EVT_COMBOBOX, self.OnComboBox)

        self.Thaw()

# ---------------------------------------------------------------------------- #
# Class ScrolledThumbnail
# This Is The Main Class Implementation
# ---------------------------------------------------------------------------- #

[docs]class ScrolledThumbnail(wx.ScrolledWindow):
    """ This is the main class implementation of L{ThumbnailCtrl}. """

[docs]    def __init__(self, parent, id=wx.ID_ANY, pos=wx.DefaultPosition,
                 size=wx.DefaultSize, thumboutline=THUMB_OUTLINE_IMAGE,
                 thumbfilter=THUMB_FILTER_IMAGES, imagehandler=PILImageHandler):
        """
        Default class constructor.

        :param `parent`: parent window. Must not be ``None``;
        :param `id`: window identifier. A value of -1 indicates a default value;
        :param `pos`: the control position. A value of (-1, -1) indicates a default position,
         chosen by either the windowing system or wxPython, depending on platform;
        :param `size`: the control size. A value of (-1, -1) indicates a default size,
         chosen by either the windowing system or wxPython, depending on platform;
        :param `thumboutline`: outline style for L{ScrolledThumbnail}, which may be:

         =========================== ======= ==================================
         Outline Flag                 Value  Description
         =========================== ======= ==================================
         ``THUMB_OUTLINE_NONE``            0 No outline is drawn on selection
         ``THUMB_OUTLINE_FULL``            1 Full outline (image+caption) is drawn on selection
         ``THUMB_OUTLINE_RECT``            2 Only thumbnail bounding rectangle is drawn on selection (default)
         ``THUMB_OUTLINE_IMAGE``           4 Only image bounding rectangle is drawn.
         =========================== ======= ==================================

        :param `thumbfilter`: filter for image/video/audio files. Actually only
         ``THUMB_FILTER_IMAGES`` is implemented;
        :param `imagehandler`: can be L{PILImageHandler} if PIL is installed (faster), or
         L{NativeImageHandler} which only uses wxPython image methods.
        """

        wx.ScrolledWindow.__init__(self, parent, id, pos, size)

        self.SetThumbSize(96, 80)
        self._tOutline = thumboutline
        self._filter = thumbfilter
        self._imageHandler = imagehandler()
        self._selected = -1
        self._pointed = -1
        self._labelcontrol = None
        self._pmenu = None
        self._gpmenu = None
        self._dragging = False
        self._checktext = False
        self._orient = THUMB_VERTICAL
        self._dropShadow = True

        self._tCaptionHeight = []
        self._selectedarray = []
        self._tTextHeight = 16
        self._tCaptionBorder = 8
        self._tOutlineNotSelected = True
        self._mouseeventhandled = False
        self._highlight = False
        self._zoomfactor = 1.4
        self.SetCaptionFont()
        self._items = []

        self._enabletooltip = False

        self._parent = parent

        self._selectioncolour = "#009EFF"
        self.grayPen = wx.Pen("#A2A2D2", 1, wx.SHORT_DASH)
        self.grayPen.SetJoin(wx.JOIN_MITER)
        self.SetBackgroundColour(wx.SystemSettings_GetColour(wx.SYS_COLOUR_LISTBOX))

        t, b, s = getShadow()
        self.shadow = wx.MemoryDC()
        self.shadow.SelectObject(s)

        self.ShowFileNames(True)

        self.Bind(wx.EVT_LEFT_DOWN, self.OnMouseDown)
        self.Bind(wx.EVT_LEFT_UP, self.OnMouseUp)
        self.Bind(wx.EVT_LEFT_DCLICK, self.OnMouseDClick)
        self.Bind(wx.EVT_RIGHT_DOWN, self.OnMouseDown)
        self.Bind(wx.EVT_RIGHT_UP, self.OnMouseUp)
        self.Bind(wx.EVT_MOTION, self.OnMouseMove)
        self.Bind(wx.EVT_LEAVE_WINDOW, self.OnMouseLeave)
        self.Bind(EVT_THUMBNAILS_THUMB_CHANGED, self.OnThumbChanged)
        self.Bind(wx.EVT_CHAR, self.OnChar)
        self.Bind(wx.EVT_MOUSEWHEEL, self.OnMouseWheel)

        self.Bind(wx.EVT_SIZE, self.OnResize)
        self.Bind(wx.EVT_ERASE_BACKGROUND, lambda x: None)
        self.Bind(wx.EVT_PAINT, self.OnPaint)

[docs]    def GetSelectedItem(self, index):
        """
        Returns the selected thumbnail.

        :param `index`: the thumbnail index (i.e., the selection).
        """

        return self.GetItem(self.GetSelection(index))

[docs]    def GetPointed(self):
        """ Returns the pointed thumbnail index. """

        return self._pointed

[docs]    def GetHighlightPointed(self):
        """
        Returns whether the thumbnail pointed should be highlighted or not.

        :note: Please be aware that this functionality may be slow on slower computers.
        """

        return self._highlight

[docs]    def SetHighlightPointed(self, highlight=True):
        """
        Sets whether the thumbnail pointed should be highlighted or not.

        :param `highlight`: ``True`` to enable highlight-on-point with the mouse,
         ``False`` otherwise.

        :note: Please be aware that this functionality may be slow on slower computers.
        """

        self._highlight = highlight

[docs]    def SetThumbOutline(self, outline):
        """
        Sets the thumbnail outline style on selection.

        :param `outline`: the outline to use on selection. This can be one of the following
         bits:

         =========================== ======= ==================================
         Outline Flag                 Value  Description
         =========================== ======= ==================================
         ``THUMB_OUTLINE_NONE``            0 No outline is drawn on selection
         ``THUMB_OUTLINE_FULL``            1 Full outline (image+caption) is drawn on selection
         ``THUMB_OUTLINE_RECT``            2 Only thumbnail bounding rectangle is drawn on selection (default)
         ``THUMB_OUTLINE_IMAGE``           4 Only image bounding rectangle is drawn.
         =========================== ======= ==================================

        """

        if outline not in [THUMB_OUTLINE_NONE, THUMB_OUTLINE_FULL, THUMB_OUTLINE_RECT,
                           THUMB_OUTLINE_IMAGE]:
            return

        self._tOutline = outline

[docs]    def GetThumbOutline(self):
        """
        Returns the thumbnail outline style on selection.

        :see: L{SetThumbOutline} for a list of possible return values.
        """

        return self._tOutline

[docs]    def SetDropShadow(self, drop):
        """
        Sets whether to drop a shadow behind thumbnails or not.

        :param `drop`: ``True`` to drop a shadow behind each thumbnail, ``False`` otheriwise.
        """

        self._dropShadow = drop
        self.Refresh()

[docs]    def GetDropShadow(self):
        """
        Returns whether to drop a shadow behind thumbnails or not.
        """

        return self._dropShadow

[docs]    def GetPointedItem(self):
        """ Returns the pointed thumbnail. """

        return self.GetItem(self._pointed)

[docs]    def GetItem(self, index):
        """
        Returns the item at position `index`.

        :param `index`: the thumbnail index position.
        """

        return index >= 0 and (index < len(self._items) and [self._items[index]] or [None])[0]

[docs]    def GetItemCount(self):
        """ Returns the number of thumbnails. """

        return len(self._items)

[docs]    def SortItems(self):
        """ Sorts the items accordingly to the L{CmpThumb} function. """

        self._items.sort(CmpThumb)

[docs]    def GetThumbWidth(self):
        """ Returns the thumbnail width. """

        return self._tWidth

[docs]    def GetThumbHeight(self):
        """ Returns the thumbnail height. """

        return self._tHeight

[docs]    def GetThumbBorder(self):
        """ Returns the thumbnail border. """

        return self._tBorder

[docs]    def GetCaption(self):
        """ Returns the thumbnail caption. """

        return self._caption

[docs]    def SetLabelControl(self, statictext):
        """
        Sets the thumbnail label as `wx.StaticText`.

        :param `statictext`: an instance of `wx.StaticText`.
        """

        self._labelcontrol = statictext

[docs]    def ShowFileNames(self, show=True):
        """
        Sets whether the user wants to show file names under the thumbnails or not.

        :param `show`: ``True`` to show file names under the thumbnails, ``False`` otherwise.
        """

        self._showfilenames = show
        self.Refresh()

[docs]    def SetOrientation(self, orient=THUMB_VERTICAL):
        """
        Set the L{ThumbnailCtrl} orientation (partially implemented).

        :param `orient`: one of ``THUMB_VERTICAL``, ``THUMB_HORIZONTAL``.

        :todo: Correctly implement the ``THUMB_HORIZONTAL`` orientation.
        """

        self._orient = orient

[docs]    def SetPopupMenu(self, menu):
        """
        Sets the thumbnails popup menu when at least one thumbnail is selected.

        :param `menu`: an instance of `wx.Menu`.
        """

        self._pmenu = menu

[docs]    def GetPopupMenu(self):
        """ Returns the thumbnails popup menu when at least one thumbnail is selected. """

        return self._pmenu

[docs]    def SetGlobalPopupMenu(self, gpmenu):
        """
        Sets the global thumbnails popup menu (no need of thumbnail selection).

        :param `gpmenu`: an instance of `wx.Menu`.
        """

        self._gpmenu = gpmenu

[docs]    def GetGlobalPopupMenu(self):
        """ Returns the global thumbnailss popup menu (no need of thumbnail selection). """

        return self._gpmenu

[docs]    def GetSelectionColour(self):
        """ Returns the colour used to indicate a selected thumbnail. """

        return self._selectioncolour

[docs]    def SetSelectionColour(self, colour=None):
        """
        Sets the colour used to indicate a selected thumbnail.

        :param `colour`: a valid `wx.Colour` object. If defaulted to ``None``, it
         will be taken from the system settings.
        """

        if colour is None:
            colour = wx.SystemSettings_GetColour(wx.SYS_COLOUR_HIGHLIGHT)

        self._selectioncolour = colour

[docs]    def EnableDragging(self, enable=True):
        """
        Enables/disables thumbnails drag and drop.

        :param `enable`: ``True`` to enable drag and drop, ``False`` to disable it.
        """

        self._dragging = enable

[docs]    def EnableToolTips(self, enable=True):
        """
        Globally enables/disables thumbnail file information.

        :param `enable`: ``True`` to enable thumbnail file information, ``False`` to disable it.
        """

        self._enabletooltip = enable

        if not enable and hasattr(self, "_tipwindow"):
            self._tipwindow.Enable(False)

[docs]    def GetThumbInfo(self, thumb=-1):
        """
        Returns the thumbnail information.

        :param `thumb`: the index of the thumbnail for which we are collecting information.
        """

        thumbinfo = None

        if thumb >= 0:
            thumbinfo = "Name: " + self._items[thumb].GetFileName() + "\n" \
                        "Size: " + self._items[thumb].GetFileSize() + "\n" \
                        "Modified: " + self._items[thumb].GetCreationDate() + "\n" \
                        "Dimensions: " + str(self._items[thumb].GetOriginalSize()) + "\n" \
                        "Thumb: " + str(self.GetThumbSize()[0:2])

        return thumbinfo

[docs]    def SetThumbSize(self, width, height, border=6):
        """
        Sets the thumbnail size as width, height and border.

        :param `width`: the desired thumbnail width;
        :param `height`: the desired thumbnail height;
        :param `border`: the spacing between thumbnails.
        """

        if width > 350 or height > 280:
            return

        self._tWidth = width
        self._tHeight = height
        self._tBorder = border
        self.SetScrollRate((self._tWidth + self._tBorder)/4,
                           (self._tHeight + self._tBorder)/4)
        self.SetSizeHints(self._tWidth + self._tBorder*2 + 16,
                          self._tHeight + self._tBorder*2 + 8)

[docs]    def GetThumbSize(self):
        """ Returns the thumbnail size as width, height and border. """

        return self._tWidth, self._tHeight, self._tBorder

[docs]    def Clear(self):
        """ Clears L{ThumbnailCtrl}. """

        self._items = []
        self._selected = -1
        self._selectedarray = []
        self.UpdateProp()
        self.Refresh()

[docs]    def ListDirectory(self, directory, fileExtList):
        """
        Returns list of file info objects for files of particular extensions.

        :param `directory`: the folder containing the images to thumbnail;
        :param `fileExtList`: a Python list of file extensions to consider.
        """

        fileList = [os.path.normcase(f) for f in os.listdir(directory)]
        fileList = [f for f in fileList \
                    if os.path.splitext(f)[1] in fileExtList]

        return fileList

[docs]    def ThreadImage(self, filenames):
        """
        Threaded method to load images. Used internally.

        :param `filenames`: a Python list of file names containing images.
        """

        count = 0

        while count < len(filenames):

            if not self._isrunning:
                self._isrunning = False
                thread.exit()
                return

            self.LoadImages(filenames[count], count)
            if count < 4:
                self.Refresh()
            elif count%4 == 0:
                self.Refresh()

            count = count + 1

        self._isrunning = False
        thread.exit()

[docs]    def LoadImages(self, newfile, imagecount):
        """
        Threaded method to load images. Used internally.

        :param `newfile`: a file name containing an image to thumbnail;
        :param `imagecount`: the number of images loaded until now.
        """

        if not self._isrunning:
            thread.exit()
            return

        img, originalsize, alpha = self._imageHandler.LoadThumbnail(newfile, (300, 240))
        try:
            self._items[imagecount]._threadedimage = img
            self._items[imagecount]._originalsize = originalsize
            self._items[imagecount]._bitmap = img
            self._items[imagecount]._alpha = alpha
        except:
            return

[docs]    def ShowThumbs(self, thumbs, caption):
        """
        Shows all the thumbnails.

        :param `thumbs`: should be a sequence with instances of L{Thumb};
        :param `caption`: the caption text for the current selected thumbnail.
        """

        self.SetCaption(caption)

        self._isrunning = False

        # update items
        self._items = thumbs
        myfiles = [thumb.GetFullFileName() for thumb in thumbs]

        items = self._items[:]
        self._items.sort(CmpThumb)

        newfiles = SortFiles(items, self._items, myfiles)
        self._isrunning = True

        thread.start_new_thread(self.ThreadImage, (newfiles,))
        wx.MilliSleep(20)

        self._selectedarray = []
        self.UpdateProp()
        self.Refresh()

[docs]    def ShowDir(self, folder, filter=THUMB_FILTER_IMAGES):
        """
        Shows thumbnails for a particular folder.

        :param `folder`: a directory containing the images to thumbnail;
        :param `filter`: filter images, video audio (currently implemented only for
         images).

        :todo: Find a way to create thumbnails of video, audio and other formats.
        """

        self._dir = folder
        if filter >= 0:
            self._filter = filter

        self._parent.RecreateComboBox(folder)

        # update items
        thumbs = []

        filenames = self.ListDirectory(self._dir, extensions)

        for files in filenames:

            caption = (self._showfilenames and [files] or [""])[0]
            fullfile = opj(self._dir + "/" + files)
            if not os.path.isfile(fullfile):
                continue

            stats = os.stat(fullfile)
            size = stats[6]

            if size < 1000:
                size = str(size) + " bytes"
            elif size < 1000000:
                size = str(int(round(size/1000.0))) + " Kb"
            else:
                size = str(round(size/1000000.0, 2)) + " Mb"

            lastmod = time.strftime(TIME_FMT, time.localtime(stats[8]))

            if self._filter & THUMB_FILTER_IMAGES:
                thumbs.append(Thumb(self, folder, files, caption, size, lastmod))

        return self.ShowThumbs(thumbs, caption=self._dir)

[docs]    def GetShowDir(self):
        """ Returns the working directory with images. """

        return self._dir

[docs]    def SetSelection(self, value=-1):
        """
        Sets thumbnail selection.

        :param `value`: the thumbnail index to select.
        """

        self._selected = value

        if value != -1:
            self._selectedarray = [value]
            eventOut = ThumbnailEvent(wxEVT_THUMBNAILS_SEL_CHANGED, self.GetId())
            self.GetEventHandler().ProcessEvent(eventOut)
            self.ScrollToSelected()
            self.Refresh()

[docs]    def SetZoomFactor(self, zoom=1.4):
        """
        Sets the zoom factor.

        :param `zoom`: a floating point number representing the zoom factor. Must be
         greater than or equal to 1.0.
        """

        if zoom <= 1.0:
            raise Exception("\nERROR: Zoom Factor Must Be Greater Than 1.0")

        self._zoomfactor = zoom

[docs]    def GetZoomFactor(self):
        """ Returns the zoom factor. """

        return self._zoomfactor

[docs]    def IsAudioVideo(self, fname):
        """
        Returns ``True`` if a file contains either audio or video data.
        Currently unused as L{ThumbnailCtrl} recognizes only image files.

        :param `fname`: a file name.

        :todo: Find a way to create thumbnails of video, audio and other formats.
        """

        return os.path.splitext(fname)[1].lower() in \
               [".mpg", ".mpeg", ".vob"]

[docs]    def IsVideo(self, fname):
        """
        Returns ``True`` if a file contains video data.
        Currently unused as L{ThumbnailCtrl} recognizes only image files.

        :param `fname`: a file name.

        :todo: Find a way to create thumbnails of video, audio and other formats.
        """

        return os.path.splitext(fname)[1].lower() in \
               [".m1v", ".m2v"]

[docs]    def IsAudio(self, fname):
        """
        Returns ``True`` if a file contains audio data.
        Currently unused as L{ThumbnailCtrl} recognizes only image files.

        :param `fname`: a file name.

        :todo: Find a way to create thumbnails of video, audio and other formats.
        """

        return os.path.splitext(fname)[1].lower() in \
               [".mpa", ".mp2", ".mp3", ".ac3", ".dts", ".pcm"]

[docs]    def UpdateItems(self):
        """ Updates thumbnail items. """

        selected = self._selectedarray
        selectedfname = []
        selecteditemid = []

        for ii in xrange(len(self._selectedarray)):
            selectedfname.append(self.GetSelectedItem(ii).GetFileName())
            selecteditemid.append(self.GetSelectedItem(ii).GetId())

        self.UpdateShow()

        if len(selected) > 0:
            self._selectedarray = []
            for ii in xrange(len(self._items)):
                for jj in xrange(len(selected)):
                    if self._items[ii].GetFileName() == selectedfname[jj] and \
                       self._items[ii].GetId() == selecteditemid[jj]:

                        self._selectedarray.append(ii)
                        if len(self._selectedarray) == 1:
                            self.ScrollToSelected()

            if len(self._selectedarray) > 0:
                self.Refresh()
                eventOut = ThumbnailEvent(wxEVT_THUMBNAILS_SEL_CHANGED, self.GetId())
                self.GetEventHandler().ProcessEvent(eventOut)

[docs]    def SetCaption(self, caption=""):
        """
        Sets the current caption string.

        :param `caption`: the current caption string.
        """

        self._caption = caption
        if self._labelcontrol:

            maxWidth = self._labelcontrol.GetSize().GetWidth()/8
            if len(caption) > maxWidth:
                caption = "..." + caption[len(caption) + 3 - maxWidth]

            self._labelcontrol.SetLabel(caption)

        eventOut = ThumbnailEvent(wxEVT_THUMBNAILS_CAPTION_CHANGED, self.GetId())
        self.GetEventHandler().ProcessEvent(eventOut)

[docs]    def SetCaptionFont(self, font=None):
        """
        Sets the font for all the thumbnail captions.

        :param `font`: a valid `wx.Font` object. If defaulted to ``None``, a standard
         font will be generated.
        """

        if font is None:
            font = wx.Font(8, wx.SWISS, wx.NORMAL, wx.BOLD, False)

        self._captionfont = font

[docs]    def GetCaptionFont(self):
        """ Returns the font for all the thumbnail captions. """

        return self._captionfont

[docs]    def UpdateShow(self):
        """ Updates thumbnail items. """

        self.ShowThumbs(self._items)

[docs]    def GetCaptionHeight(self, begRow, count=1):
        """
        Returns the height for the file name caption.

        :param `begRow`: the caption line at which we start measuring the height;
        :param `count`: the number of lines to measure.
        """

        capHeight = 0
        for ii in xrange(begRow, begRow + count):
            if ii < len(self._tCaptionHeight):
                capHeight = capHeight + self._tCaptionHeight[ii]

        return capHeight*self._tTextHeight

[docs]    def GetItemIndex(self, x, y):
        """
        Returns the thumbnail index at position (x, y).

        :param `x`: the mouse `x` position;
        :param `y`: the mouse `y` position.
        """

        col = (x - self._tBorder)/(self._tWidth + self._tBorder)

        if col >= self._cols:
            col = self._cols - 1

        row = -1
        y = y - self._tBorder

        while y > 0:

            row = row + 1
            y = y - (self._tHeight + self._tBorder + self.GetCaptionHeight(row))

        if row < 0:
            row = 0

        index = row*self._cols + col

        if index >= len(self._items):
            index = -1

        return index

[docs]    def UpdateProp(self, checkSize=True):
        """
        Updates L{ThumbnailCtrl} and its visible thumbnails.

        :param `checkSize`: ``True`` to update the items visibility if the window
         size has changed.
        """

        width = self.GetClientSize().GetWidth()
        self._cols = (width - self._tBorder)/(self._tWidth + self._tBorder)

        if self._cols == 0:
            self._cols = 1

        tmpvar = (len(self._items)%self._cols and [1] or [0])[0]
        self._rows = len(self._items)/self._cols + tmpvar

        self._tCaptionHeight = []

        for row in xrange(self._rows):

            capHeight = 0

            for col in xrange(self._cols):

                ii = row*self._cols + col

                if len(self._items) > ii and \
                   self._items[ii].GetCaptionLinesCount(self._tWidth - self._tCaptionBorder) > capHeight:

                    capHeight = self._items[ii].GetCaptionLinesCount(self._tWidth - self._tCaptionBorder)

            self._tCaptionHeight.append(capHeight)

        self.SetVirtualSize((self._cols*(self._tWidth + self._tBorder) + self._tBorder,
                            self._rows*(self._tHeight + self._tBorder) + \
                            self.GetCaptionHeight(0, self._rows) + self._tBorder))

        self.SetSizeHints(self._tWidth + 2*self._tBorder + 16,
                          self._tHeight + 2*self._tBorder + 8 + \
                          (self._rows and [self.GetCaptionHeight(0)] or [0])[0])

        if checkSize and width != self.GetClientSize().GetWidth():
            self.UpdateProp(False)

[docs]    def InsertItem(self, thumb, pos):
        """
        Inserts a thumbnail in the specified position.

        :param `pos`: the index at which we wish to insert the new thumbnail.
        """

        if pos < 0 or pos > len(self._items):
            self._items.append(thumb)
        else:
            self._items.insert(pos, thumb)

        self.UpdateProp()

[docs]    def RemoveItemAt(self, pos):
        """
        Removes a thumbnail at the specified position.

        :param `pos`: the index at which we wish to remove the thumbnail.
        """

        del self._items[pos]

        self.UpdateProp()

[docs]    def GetPaintRect(self):
        """ Returns the paint bounding rect for the L{OnPaint} method. """

        size = self.GetClientSize()
        paintRect = wx.Rect(0, 0, size.GetWidth(), size.GetHeight())
        paintRect.x, paintRect.y = self.GetViewStart()
        xu, yu = self.GetScrollPixelsPerUnit()
        paintRect.x = paintRect.x*xu
        paintRect.y = paintRect.y*yu

        return paintRect

[docs]    def IsSelected(self, indx):
        """
        Returns whether a thumbnail is selected or not.

        :param `indx`: the index of the thumbnail to check for selection.
        """

        return self._selectedarray.count(indx) != 0

[docs]    def GetSelection(self, selIndex=-1):
        """
        Returns the selected thumbnail.

        :param `selIndex`: if not equal to -1, the index of the selected thumbnail.
        """

        return (selIndex == -1 and [self._selected] or \
                [self._selectedarray[selIndex]])[0]

[docs]    def GetOriginalImage(self, index=None):
        """
        Returns the original image associated to a thumbnail.

        :param `index`: the index of the thumbnail. If defaulted to ``None``, the current
         selection is used.
        """

        if index is None:
            index = self.GetSelection()

        return self._items[index].GetOriginalImage()

[docs]    def ScrollToSelected(self):
        """ Scrolls the `wx.ScrolledWindow` to the selected thumbnail. """

        if self.GetSelection() == -1:
            return

        # get row
        row = self.GetSelection()/self._cols
        # calc position to scroll view

        paintRect = self.GetPaintRect()
        y1 = row*(self._tHeight + self._tBorder) + self.GetCaptionHeight(0, row)
        y2 = y1 + self._tBorder + self._tHeight + self.GetCaptionHeight(row)

        if y1 < paintRect.GetTop():
            sy = y1 # scroll top
        elif y2 > paintRect.GetBottom():
            sy = y2 - paintRect.height # scroll bottom
        else:
            return

        # scroll view
        xu, yu = self.GetScrollPixelsPerUnit()
        sy = sy/yu + (sy%yu and [1] or [0])[0] # convert sy to scroll units
        x, y = self.GetViewStart()

        self.Scroll(x,sy)

[docs]    def CalculateBestCaption(self, dc, caption, sw, width):
        """
        Calculates the best caption string to show based on the actual zoom factor.

        :param `dc`: an instance of `wx.DC`;
        :param `caption`: the original caption string;
        :param `sw`: the maximum width allowed for the caption string, in pixels;
        :param `width`: the caption string width, in pixels.
        """

        caption = caption + "..."

        while sw > width:
            caption = caption[1:]
            sw, sh = dc.GetTextExtent(caption)

        return "..." + caption[0:-3]

[docs]    def DrawThumbnail(self, bmp, thumb, index):
        """
        Draws a visible thumbnail.

        :param `bmp`: the thumbnail version of the original image;
        :param `thumb`: an instance of L{Thumb};
        :param `index`: the index of the thumbnail to draw.
        """

        dc = wx.MemoryDC()
        dc.SelectObject(bmp)
        dc.BeginDrawing()

        x = self._tBorder/2
        y = self._tBorder/2

        # background
        dc.SetPen(wx.Pen(wx.BLACK, 0, wx.TRANSPARENT))
        dc.SetBrush(wx.Brush(self.GetBackgroundColour(), wx.SOLID))
        dc.DrawRectangle(0, 0, bmp.GetWidth(), bmp.GetHeight())

        # image
        img = thumb.GetBitmap(self._tWidth, self._tHeight)
        ww = img.GetWidth()
        hh = img.GetHeight()

        if index == self.GetPointed() and self.GetHighlightPointed():
            factor = 1.5
            img = self._imageHandler.HighlightImage(img.ConvertToImage(), factor).ConvertToBitmap()

        imgRect = wx.Rect(x + (self._tWidth - img.GetWidth())/2,
                          y + (self._tHeight - img.GetHeight())/2,
                          img.GetWidth(), img.GetHeight())

        if not thumb._alpha and self._dropShadow:
            dc.Blit(imgRect.x+5, imgRect.y+5, imgRect.width, imgRect.height, self.shadow, 500-ww, 500-hh)
        dc.DrawBitmap(img, imgRect.x, imgRect.y, True)

        colour = self.GetSelectionColour()
        selected = self.IsSelected(index)

        colour = self.GetSelectionColour()

        # draw caption
        sw, sh = 0, 0
        if self._showfilenames:
            textWidth = 0
            dc.SetFont(self.GetCaptionFont())
            mycaption = thumb.GetCaption(0)
            sw, sh = dc.GetTextExtent(mycaption)

            if sw > self._tWidth:
                mycaption = self.CalculateBestCaption(dc, mycaption, sw, self._tWidth)
                sw = self._tWidth

            textWidth = sw + 8
            tx = x + (self._tWidth - textWidth)/2
            ty = y + self._tHeight

            txtcolour = "#7D7D7D"
            dc.SetTextForeground(txtcolour)

            tx = x + (self._tWidth - sw)/2
            if hh >= self._tHeight:
                ty = y + self._tHeight + (self._tTextHeight - sh)/2 + 3
            else:
                ty = y + hh + (self._tHeight-hh)/2 + (self._tTextHeight - sh)/2 + 3

            dc.DrawText(mycaption, tx, ty)

        # outline
        if self._tOutline != THUMB_OUTLINE_NONE and (self._tOutlineNotSelected or self.IsSelected(index)):

            dotrect = wx.Rect()
            dotrect.x = x - 2
            dotrect.y = y - 2
            dotrect.width = bmp.GetWidth() - self._tBorder + 4
            dotrect.height = bmp.GetHeight() - self._tBorder + 4

            dc.SetPen(wx.Pen((self.IsSelected(index) and [colour] or [wx.LIGHT_GREY])[0],
                             0, wx.SOLID))
            dc.SetBrush(wx.Brush(wx.BLACK, wx.TRANSPARENT))

            if self._tOutline == THUMB_OUTLINE_FULL or self._tOutline == THUMB_OUTLINE_RECT:

                imgRect.x = x
                imgRect.y = y
                imgRect.width = bmp.GetWidth() - self._tBorder
                imgRect.height = bmp.GetHeight() - self._tBorder

                if self._tOutline == THUMB_OUTLINE_RECT:
                    imgRect.height = self._tHeight

            dc.SetBrush(wx.TRANSPARENT_BRUSH)

            if selected:

                dc.SetPen(self.grayPen)
                dc.DrawRoundedRectangleRect(dotrect, 2)

                dc.SetPen(wx.Pen(wx.WHITE))
                dc.DrawRectangle(imgRect.x, imgRect.y,
                                 imgRect.width, imgRect.height)

                pen = wx.Pen((selected and [colour] or [wx.LIGHT_GREY])[0], 2)
                pen.SetJoin(wx.JOIN_MITER)
                dc.SetPen(pen)
                if self._tOutline == THUMB_OUTLINE_FULL:
                    dc.DrawRoundedRectangle(imgRect.x - 1, imgRect.y - 1,
                                            imgRect.width + 3, imgRect.height + 3, 2)
                else:
                    dc.DrawRectangle(imgRect.x - 1, imgRect.y - 1,
                                     imgRect.width + 3, imgRect.height + 3)
            else:
                dc.SetPen(wx.Pen(wx.LIGHT_GREY))

                dc.DrawRectangle(imgRect.x - 1, imgRect.y - 1,
                                 imgRect.width + 2, imgRect.height + 2)

        dc.EndDrawing()
        dc.SelectObject(wx.NullBitmap)

[docs]    def OnPaint(self, event):
        """
        Handles the ``wx.EVT_PAINT`` event for L{ThumbnailCtrl}.

        :param `event`: a `wx.PaintEvent` event to be processed.
        """

        paintRect = self.GetPaintRect()

        dc = wx.BufferedPaintDC(self)
        self.PrepareDC(dc)

        dc.SetPen(wx.Pen(wx.BLACK, 0, wx.TRANSPARENT))
        dc.SetBrush(wx.Brush(self.GetBackgroundColour(), wx.SOLID))

        w, h = self.GetClientSize()

        # items
        row = -1
        xwhite = self._tBorder

        for ii in xrange(len(self._items)):

            col = ii%self._cols
            if col == 0:
                row = row + 1

            xwhite = ((w - self._cols*(self._tWidth + self._tBorder)))/(self._cols+1)
            tx = xwhite + col*(self._tWidth + self._tBorder)

            ty = self._tBorder/2 + row*(self._tHeight + self._tBorder) + \
                 self.GetCaptionHeight(0, row)
            tw = self._tWidth + self._tBorder
            th = self._tHeight + self.GetCaptionHeight(row) + self._tBorder
            # visible?
            if not paintRect.Intersects(wx.Rect(tx, ty, tw, th)):
                continue

            thmb = wx.EmptyBitmap(tw, th)
            self.DrawThumbnail(thmb, self._items[ii], ii)
            dc.DrawBitmap(thmb, tx, ty)

        rect = wx.Rect(xwhite, self._tBorder/2,
                       self._cols*(self._tWidth + self._tBorder),
                       self._rows*(self._tHeight + self._tBorder) + \
                       self.GetCaptionHeight(0, self._rows))

        w = max(self.GetClientSize().GetWidth(), rect.width)
        h = max(self.GetClientSize().GetHeight(), rect.height)
        dc.DrawRectangle(0, 0, w, rect.y)
        dc.DrawRectangle(0, 0, rect.x, h)
        dc.DrawRectangle(rect.GetRight(), 0, w - rect.GetRight(), h + 50)
        dc.DrawRectangle(0, rect.GetBottom(), w, h - rect.GetBottom() + 50)

        col = len(self._items)%self._cols

        if col > 0:
            rect.x = rect.x + col*(self._tWidth + self._tBorder)
            rect.y = rect.y + (self._rows - 1)*(self._tHeight + self._tBorder) + \
                     self.GetCaptionHeight(0, self._rows - 1)
            dc.DrawRectangleRect(rect)

[docs]    def OnResize(self, event):
        """
        Handles the ``wx.EVT_SIZE`` event for L{ThumbnailCtrl}.

        :param `event`: a `wx.SizeEvent` event to be processed.
        """

        self.UpdateProp()
        self.ScrollToSelected()
        self.Refresh()

[docs]    def OnMouseDown(self, event):
        """
        Handles the ``wx.EVT_LEFT_DOWN`` and ``wx.EVT_RIGHT_DOWN`` events for L{ThumbnailCtrl}.

        :param `event`: a `wx.MouseEvent` event to be processed.
        """

        x = event.GetX()
        y = event.GetY()
        x, y = self.CalcUnscrolledPosition(x, y)
        # get item number to select
        lastselected = self._selected
        self._selected = self.GetItemIndex(x, y)

        self._mouseeventhandled = False
        update = False

        if event.ControlDown():
            if self._selected == -1:
                self._mouseeventhandled = True
            elif not self.IsSelected(self._selected):
                self._selectedarray.append(self._selected)
                update = True
                self._mouseeventhandled = True

        elif event.ShiftDown():
            if self._selected != -1:
                begindex = self._selected
                endindex = lastselected
                if lastselected < self._selected:
                    begindex = lastselected
                    endindex = self._selected
                self._selectedarray = []

                for ii in xrange(begindex, endindex+1):
                    self._selectedarray.append(ii)

                update = True

            self._selected = lastselected
            self._mouseeventhandled = True

        else:

            if self._selected == -1:
                update = len(self._selectedarray) > 0
                self._selectedarray = []
                self._mouseeventhandled = True
            elif len(self._selectedarray) <= 1:
                try:
                    update = len(self._selectedarray)== 0 or self._selectedarray[0] != self._selected
                except:
                    update = True
                self._selectedarray = []
                self._selectedarray.append(self._selected)
                self._mouseeventhandled = True

        if update:
            self.ScrollToSelected()
            self.Refresh()
            eventOut = ThumbnailEvent(wxEVT_THUMBNAILS_SEL_CHANGED, self.GetId())
            self.GetEventHandler().ProcessEvent(eventOut)

        self.SetFocus()

[docs]    def OnMouseUp(self, event):
        """
        Handles the ``wx.EVT_LEFT_UP`` and ``wx.EVT_RIGHT_UP`` events for L{ThumbnailCtrl}.

        :param `event`: a `wx.MouseEvent` event to be processed.
        """

        # get item number to select
        x = event.GetX()
        y = event.GetY()
        x, y = self.CalcUnscrolledPosition(x, y)
        lastselected = self._selected
        self._selected = self.GetItemIndex(x,y)

        if not self._mouseeventhandled:
            # set new selection
            if event.ControlDown():
                if self._selected in self._selectedarray:
                    self._selectedarray.remove(self._selected)

                self._selected = -1
            else:
                self._selectedarray = []
                self._selectedarray.append(self._selected)

            self.ScrollToSelected()
            self.Refresh()
            eventOut = ThumbnailEvent(wxEVT_THUMBNAILS_SEL_CHANGED, self.GetId())
            self.GetEventHandler().ProcessEvent(eventOut)

        # Popup menu
        if event.RightUp():
            if self._selected >= 0 and self._pmenu:
                self.PopupMenu(self._pmenu, event.GetPosition())
            elif self._selected >= 0 and not self._pmenu and self._gpmenu:
                self.PopupMenu(self._gpmenu, event.GetPosition())
            elif self._selected == -1 and self._gpmenu:
                self.PopupMenu(self._gpmenu, event.GetPosition())

        if event.ShiftDown():
            self._selected = lastselected

[docs]    def OnMouseDClick(self, event):
        """
        Handles the ``wx.EVT_LEFT_DCLICK`` event for L{ThumbnailCtrl}.

        :param `event`: a `wx.MouseEvent` event to be processed.
        """

        eventOut = ThumbnailEvent(wxEVT_THUMBNAILS_DCLICK, self.GetId())
        self.GetEventHandler().ProcessEvent(eventOut)

[docs]    def OnMouseMove(self, event):
        """
        Handles the ``wx.EVT_MOTION`` event for L{ThumbnailCtrl}.

        :param `event`: a `wx.MouseEvent` event to be processed.
        """

        # -- drag & drop --
        if self._dragging and event.Dragging() and len(self._selectedarray) > 0:

            files = wx.FileDataObject()
            for ii in xrange(len(self._selectedarray)):
                files.AddFile(opj(self.GetSelectedItem(ii).GetFullFileName()))

            source = wx.DropSource(self)
            source.SetData(files)
            source.DoDragDrop(wx.Drag_DefaultMove)

        # -- light-effect --
        x = event.GetX()
        y = event.GetY()
        x, y = self.CalcUnscrolledPosition(x, y)

        # get item number
        sel = self.GetItemIndex(x, y)

        if sel == self._pointed:
            if self._enabletooltip and sel >= 0:
                if not hasattr(self, "_tipwindow"):
                    self._tipwindow = wx.ToolTip(self.GetThumbInfo(sel))
                    self._tipwindow.SetDelay(1000)
                    self.SetToolTip(self._tipwindow)
                else:
                    self._tipwindow.SetDelay(1000)
                    self._tipwindow.SetTip(self.GetThumbInfo(sel))

            event.Skip()
            return

        if self._enabletooltip:
            if hasattr(self, "_tipwindow"):
                self._tipwindow.Enable(False)

        # update thumbnail
        self._pointed = sel

        if self._enabletooltip and sel >= 0:
            if not hasattr(self, "_tipwindow"):
                self._tipwindow = wx.ToolTip(self.GetThumbInfo(sel))
                self._tipwindow.SetDelay(1000)
                self._tipwindow.Enable(True)
                self.SetToolTip(self._tipwindow)
            else:
                self._tipwindow.SetDelay(1000)
                self._tipwindow.Enable(True)
                self._tipwindow.SetTip(self.GetThumbInfo(sel))

        self.Refresh()
        eventOut = ThumbnailEvent(wxEVT_THUMBNAILS_POINTED, self.GetId())
        self.GetEventHandler().ProcessEvent(eventOut)
        event.Skip()

[docs]    def OnMouseLeave(self, event):
        """
        Handles the ``wx.EVT_LEAVE_WINDOW`` event for L{ThumbnailCtrl}.

        :param `event`: a `wx.MouseEvent` event to be processed.
        """

        if self._pointed != -1:

            self._pointed = -1
            self.Refresh()
            eventOut = ThumbnailEvent(wxEVT_THUMBNAILS_POINTED, self.GetId())
            self.GetEventHandler().ProcessEvent(eventOut)

[docs]    def OnThumbChanged(self, event):
        """
        Handles the ``EVT_THUMBNAILS_THUMB_CHANGED`` event for L{ThumbnailCtrl}.

        :param `event`: a L{ThumbnailEvent} event to be processed.
        """

        for ii in xrange(len(self._items)):
            if self._items[ii].GetFileName() == event.GetString():

                self._items[ii].SetFilename(self._items[ii].GetFileName())
                if event.GetClientData():

                    img = wx.Image(event.GetClientData())
                    self._items[ii].SetImage(img)

        self.Refresh()

[docs]    def OnChar(self, event):
        """
        Handles the ``wx.EVT_CHAR`` event for L{ThumbnailCtrl}.

        :param `event`: a `wx.KeyEvent` event to be processed.

        :note: You have these choices:

         (1) ``d`` key rotates 90 degrees clockwise the selected thumbnails;
         (2) ``s`` key rotates 90 degrees counter-clockwise the selected thumbnails;
         (3) ``a`` key rotates 180 degrees the selected thumbnails;
         (4) ``Del`` key deletes the selected thumbnails;
         (5) ``+`` key zooms in;
         (6) ``-`` key zooms out.
        """

        if event.m_keyCode == ord("s"):
            self.Rotate()
        elif event.m_keyCode == ord("d"):
            self.Rotate(270)
        elif event.m_keyCode == ord("a"):
            self.Rotate(180)
        elif event.m_keyCode == wx.WXK_DELETE:
            self.DeleteFiles()
        elif event.m_keyCode in [wx.WXK_ADD, wx.WXK_NUMPAD_ADD]:
            self.ZoomIn()
        elif event.m_keyCode in [wx.WXK_SUBTRACT, wx.WXK_NUMPAD_SUBTRACT]:
            self.ZoomOut()

        event.Skip()

[docs]    def Rotate(self, angle=90):
        """
        Rotates the selected thumbnails by the angle specified by `angle`.

        :param `angle`: the rotation angle for the thumbnail, in degrees.
        """

        wx.BeginBusyCursor()

        count = 0
        selected = []

        for ii in xrange(len(self._items)):
            if self.IsSelected(ii):
                selected.append(self._items[ii])

        dlg = wx.ProgressDialog("Thumbnail Rotation",
                                "Rotating Thumbnail... Please Wait",
                                maximum = len(selected)+1,
                                parent=None)

        for thumb in selected:
            count = count + 1
            if TN_USE_PIL:
                newangle = thumb.GetRotation()*180/pi + angle
                fil = opj(thumb.GetFullFileName())
                pil = Image.open(fil).rotate(newangle)
                img = wx.EmptyImage(pil.size[0], pil.size[1])
                img.SetData(pil.convert('RGB').tostring())
                thumb.SetRotation(newangle*pi/180)
            else:
                img = thumb._threadedimage
                newangle = thumb.GetRotation() + angle*pi/180
                thumb.SetRotation(newangle)
                img = img.Rotate(newangle, (img.GetWidth()/2, img.GetHeight()/2), True)

            thumb.SetRotatedImage(img)
            dlg.Update(count)

        wx.EndBusyCursor()
        dlg.Destroy()

        if self.GetSelection() != -1:
            self.Refresh()

[docs]    def DeleteFiles(self):
        """
        Deletes the selected thumbnails and their associated files.

        :warning: This method deletes the original files too.
        """

        dlg = wx.MessageDialog(self, 'Are you sure you want to delete the files?',
                               'Confirmation',
                               wx.YES_NO | wx.NO_DEFAULT | wx.ICON_QUESTION)

        if dlg.ShowModal() == wx.ID_YES:
            errordelete = []
            count = 0

            dlg.Destroy()

            wx.BeginBusyCursor()

            for ii in xrange(len(self._items)):
                if self.IsSelected(ii):
                    thumb = self._items[ii]
                    files = self._items[ii].GetFullFileName()
                    filename = opj(files)
                    try:
                        os.remove(filename)
                        count = count + 1
                    except:
                        errordelete.append(files)

            wx.EndBusyCursor()

            if errordelete:
                strs = "Unable to remove the following files:\n\n"
                for fil in errordelete:
                    strs = strs + fil + "\n"
                strs = strs + "\n"
                strs = strs + "Please check your privileges and file permissions."
                dlg = wx.MessageDialog(self, strs,
                                       'Error in removing files',
                                       wx.OK | wx.ICON_ERROR)
                dlg.ShowModal()
                dlg.Destroy()

            if count:
                self.UpdateShow()

[docs]    def OnMouseWheel(self, event):
        """
        Handles the ``wx.EVT_MOUSEWHEEL`` event for L{ThumbnailCtrl}.

        :param `event`: a `wx.MouseEvent` event to be processed.

        :note: If you hold down the ``Ctrl`` key, you can zoom in/out with the mouse wheel.
        """

        if event.ControlDown():
            if event.GetWheelRotation() > 0:
                self.ZoomIn()
            else:
                self.ZoomOut()
        else:
            event.Skip()

[docs]    def ZoomOut(self):
        """ Zooms the thumbnails out. """

        w, h, b = self.GetThumbSize()

        if w < 40 or h < 40:
            return

        zoom = self.GetZoomFactor()
        neww = float(w)/zoom
        newh = float(h)/zoom

        self.SetThumbSize(int(neww), int(newh))
        self.OnResize(None)
        self._checktext = True

        self.Refresh()

[docs]    def ZoomIn(self):
        """ Zooms the thumbnails in. """

        size = self.GetClientSize()
        w, h, b = self.GetThumbSize()
        zoom = self.GetZoomFactor()

        if w*zoom + b > size.GetWidth() or h*zoom + b > size.GetHeight():
            if w*zoom + b > size.GetWidth():
                neww = size.GetWidth() - 2*self._tBorder
                newh = (float(h)/w)*neww
            else:
                newh = size.GetHeight() - 2*self._tBorder
                neww = (float(w)/h)*newh

        else:
            neww = float(w)*zoom
            newh = float(h)*zoom

        self.SetThumbSize(int(neww), int(newh))
        self.OnResize(None)
        self._checktext = True

        self.Refresh()

Navigation

  • index
  • modules |
  • Home |
  • Gallery |
  • Contents»
  • Module code »
  • thumbnailctrl


toasterbox

  • modules |
  • Home |
  • Gallery |
  • Contents»
  • Module code »
  • toasterbox

Source code for toasterbox

# --------------------------------------------------------------------------- #
# TOASTERBOX wxPython IMPLEMENTATION
# Ported And Enhanced From wxWidgets Contribution (Aj Bommarito) By:
#
# Andrea Gavana, @ 16 September 2005
# Latest Revision: 17 Aug 2011, 15.00 GMT
#
#
# TODO/Caveats List
#
# 1. Any Idea?
#
#
# 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
# --------------------------------------------------------------------------- #

"""
ToasterBox is a cross-platform widget to make the creation of MSN style "toaster"
popups easier.

Description
===========

ToasterBox is a cross-platform widget to make the creation of MSN style "toaster"
popups easier. The syntax is really easy especially if you are familiar with the
syntax of wxPython.

It has 2 main styles:

- ``TB_SIMPLE``: using this style, you will be able to specify a background image for
  ToasterBox, text properties as text colour, font and label;

- ``TB_COMPLEX``: this style will allow you to put almost any control inside a
  ToasterBox. You can add a panel in which you can put all the controls you like.

Both styles support the setting of ToasterBox position (on screen coordinates),
size, the time after which the ToasterBox is destroyed (linger), and the scroll
speed of ToasterBox.

Usage
=====

Usage example::

    import wx
    import wx.lib.agw.toasterbox as TB

    class MyFrame(wx.Frame):

        def __init__(self, parent):

            wx.Frame.__init__(self, parent, -1, "ToasterBox Demo")

            toaster = TB.ToasterBox(self, tbstyle=TB.TB_COMPLEX)
            toaster.SetPopupPauseTime(3000)

            tbpanel = toaster.GetToasterBoxWindow()
            panel = wx.Panel(tbpanel, -1)
            sizer = wx.BoxSizer(wx.VERTICAL)

            button = wx.Button(panel, wx.ID_ANY, "Simple button")
            sizer.Add(button, 0, wx.EXPAND)

            panel.SetSizer(sizer)
            toaster.AddPanel(panel)

            wx.CallLater(1000, toaster.Play)

    # our normal wxApp-derived class, as usual

    app = wx.PySimpleApp()

    frame = MyFrame(None)
    app.SetTopWindow(frame)
    frame.Show()

    app.MainLoop()

Supported Platforms
===================

ToasterBox has been tested on the following platforms:

- Windows (verified on Windows XP, 2000)
- Linux
- Mac

Window Styles
=============

This class supports the following window styles:

==================== =========== ==================================================
Window Styles        Hex Value   Description
==================== =========== ==================================================
``TB_SIMPLE``                0x1 A simple `ToasterBox`, with background image and text customization can be created.
``TB_ONTIME``                0x1 `ToasterBox` will close after a specified amount of time.
``TB_COMPLEX``               0x2 ToasterBoxes with different degree of complexity can be created. You can add as  many controls as you want, provided that you call the L{AddPanel} method and pass  to it a dummy frame and a `wx.Panel`. See the demo for details.
``TB_ONCLICK``               0x2 `ToasterBox` can be closed by clicking anywhere on the `ToasterBox` frame.
``TB_DEFAULT_STYLE``   0x2008002 Default window style for `ToasterBox`, with no caption nor close box.
``TB_CAPTION``        0x22009806 `ToasterBox` will have a caption, with the possibility to set a title for the `ToasterBox` frame, and a close box.
==================== =========== ==================================================

Events Processing
=================

`No custom events are available for this class.`

License And Version
===================

ToasterBox is distributed under the wxPython license.

Latest revision: Andrea Gavana @ 17 Aug 2011, 15.00 GMT

Version 0.3

"""

import textwrap
import wx

# Define Window List, We Use It Globally
winlist = []

TB_SIMPLE = 1
""" A simple ToasterBox, with background image and text customization can be created. """
TB_COMPLEX = 2
""" ToasterBoxes with different degree of complexity can be created. You can add as """ \
""" many controls as you want, provided that you call the AddPanel() method and pass """ \
""" to it a dummy frame and a wx.Panel. See the demo for details. """
TB_DEFAULT_STYLE = wx.SIMPLE_BORDER | wx.STAY_ON_TOP | wx.FRAME_NO_TASKBAR
""" Default window style for `ToasterBox`, with no caption nor close box. """
TB_CAPTION = TB_DEFAULT_STYLE | wx.CAPTION | wx.SYSTEM_MENU | wx.CLOSE_BOX | wx.FRAME_NO_TASKBAR
""" `ToasterBox` will have a caption, with the possibility to set a title """ \
""" for the `ToasterBox` frame, and a close box. """
TB_ONTIME = 1
""" `ToasterBox` will close after a specified amount of time. """
TB_ONCLICK = 2
""" `ToasterBox` can be closed by clicking anywhere on the `ToasterBox` frame. """

# scroll from up to down
TB_SCR_TYPE_UD = 1
# scroll from down to up
TB_SCR_TYPE_DU = 2
# fade in/out
TB_SCR_TYPE_FADE = 4

# ------------------------------------------------------------------------------ #
# Class ToasterBox
#    Main Class Implementation. It Is Basically A wx.Timer. It Creates And
#    Displays Popups And Handles The "Stacking".
# ------------------------------------------------------------------------------ #

[docs]class ToasterBox(wx.Timer):
    """
    ToasterBox is a cross-platform widget to make the creation of MSN style "toaster"
    popups easier.
    """

[docs]    def __init__(self, parent, tbstyle=TB_SIMPLE, windowstyle=TB_DEFAULT_STYLE,
                 closingstyle=TB_ONTIME, scrollType=TB_SCR_TYPE_DU):
        """
        Default class constructor.

        :param `parent`: the window parent;
        :param `tbstyle`: the L{ToasterBox} main style. Can be one of the following
         bits:

         ====================== ======= ================================
         `ToasterBox` Style      Value  Description
         ====================== ======= ================================
         ``TB_SIMPLE``              0x1 A simple L{ToasterBox}, with background image and text customization can be created
         ``TB_COMPLEX``             0x2 `ToasterBoxes` with different degree of complexity can be created. You can add as many controls as you want, provided that you call the L{AddPanel} method and pass to it a dummy frame and a `wx.Panel`.
         ====================== ======= ================================

        :param `windowstyle`: this parameter influences the visual appearance of
         L{ToasterBox}, and can be one of the following styles:

         ====================== ========== ================================
         Window Style           Hex Value  Description
         ====================== ========== ================================
         ``TB_DEFAULT_STYLE``   0x2008002  Default window style for L{ToasterBox}, with no caption nor close box.
         ``TB_CAPTION``         0x22009806 L{ToasterBox} will have a caption, with the possibility to set a title for the L{ToasterBox} frame, and a close box.
         ====================== ========== ================================

        :param `closingstyle`: the closing style for L{ToasterBox}. Can be one of the
         following bits:

         ==================== =========== ==================================================
         Closing Styles       Hex Value   Description
         ==================== =========== ==================================================
         ``TB_ONTIME``                0x1 L{ToasterBox} will close after a specified amount of time.
         ``TB_ONCLICK``               0x2 L{ToasterBox} can be closed by clicking anywhere on the L{ToasterBox} frame.
         ==================== =========== ==================================================

        :param `scrollType`: the scrolling direction for L{ToasterBox}. Can be one of the
         following bits:

         ==================== =========== ==================================================
         Scroll Styles        Hex Value   Description
         ==================== =========== ==================================================
         ``TB_SCR_TYPE_UD``           0x1 L{ToasterBox} will scroll from up to down
         ``TB_SCR_TYPE_DU``           0x2 L{ToasterBox} will scroll from down to up
         ``TB_SCR_TYPE_FADE``         0x4 L{ToasterBox} will fade in/out (without scrolling).
         ==================== =========== ==================================================

        """

        self._parent = parent
        self._sleeptime = 10
        self._pausetime = 1700
        self._popuptext = "default"
        self._popupposition = wx.Point(100,100)
        self._popuptop = wx.Point(0,0)
        self._popupsize = wx.Size(150, 170)
        self._usefocus = True
        self._originalfocus = wx.Window.FindFocus()

        self._backgroundcolour = wx.WHITE
        self._foregroundcolour = wx.BLACK
        self._textfont = wx.Font(8, wx.SWISS, wx.NORMAL, wx.NORMAL, False, "Verdana")

        self._bitmap = None

        self._tbstyle = tbstyle
        self._windowstyle = windowstyle
        self._closingstyle = closingstyle
        self._scrollType = scrollType

        self._panel = None

        self._bottomright = wx.Point(wx.GetDisplaySize().GetWidth(),
                                     wx.GetDisplaySize().GetHeight())

        if parent is not None:
            parent.Bind(wx.EVT_ICONIZE, lambda evt: [w.Hide() for w in winlist])
            self._moveTimer = wx.Timer(parent, -1)
            parent.Bind(wx.EVT_TIMER, self.OnMoveTimer, self._moveTimer)

        self._tb = ToasterBoxWindow(self._parent, self, self._tbstyle, self._windowstyle,
                                    self._closingstyle, scrollType=self._scrollType)

[docs]    def SetPopupPosition(self, pos):
        """
        Sets the L{ToasterBox} position on screen.

        :param `pos`: the widget position, an instance of `wx.Point`.
        """

        self._popupposition = pos

[docs]    def SetPopupPositionByInt(self, pos):
        """
        Sets the L{ToasterBox} position on screen, at one of the screen corners.

        :param `pos`: an integer specifying the screen corner, namely:

         ============= ========================================
         Corner Number Position
         ============= ========================================
               0       Top left screen corner
               1       Top right screen corner
               2       Bottom left screen corner
               3       Bottom right screen corner
         ============= ========================================

        """

        w, h = wx.GetDisplaySize()
        self._bottomright = wx.Point(w, h)

        # top left
        if pos == 0:
            popupposition = wx.Point(0,0)
        # top right
        elif pos == 1:
            popupposition = wx.Point(w - self._popupsize[0], 0)
        # bottom left
        elif pos == 2:
            popupposition = wx.Point(0, h - self._popupsize[1])
        # bottom right
        elif pos == 3:
            popupposition = wx.Point(self._bottomright.x - self._popupsize[0],
                                     self._bottomright.y - self._popupsize[1])

        self._bottomright = wx.Point(popupposition.x + self._popupsize[0],
                                     popupposition.y + self._popupsize[1])

        self._popupposition = popupposition

[docs]    def CenterOnParent(self, direction=wx.BOTH):
        """
        Centres the window on its parent (if any). If the L{ToasterBox} parent is ``None``,
        it calls L{CenterOnScreen}.

        :param `direction`: specifies the direction for the centering. May be ``wx.HORIZONTAL``,
         ``wx.VERTICAL`` or ``wx.BOTH``.

        :note: This methods provides for a way to center L{ToasterBox} over their parents instead of the
         entire screen. If there is no parent, then behaviour is the same as L{CenterOnScreen}.

        :see: L{CenterOnScreen}.
        """

        if not self._parent:
            self.CenterOnScreen(direction)
            return

        parent = self._parent
        screenrect = parent.GetScreenRect()
        toast_width, toast_height = self._popupsize
        x, y = screenrect.GetX(), screenrect.GetY()
        width, height = screenrect.GetWidth(), screenrect.GetHeight()

        if direction == wx.VERTICAL:
            pos = wx.Point(x, (y + (height/2) - (toast_height/2)))
        elif direction == wx.HORIZONTAL:
            pos = wx.Point((x + (width/2) - (toast_width/2)), y)
        else:
            pos = wx.Point((x + (width/2) - (toast_width/2)), (y + (height/2) - (toast_height/2)))

        tb.SetPopupPosition(pos)

    CentreOnParent = CenterOnParent

[docs]    def CenterOnScreen(self, direction=wx.BOTH):
        """
        Centres the L{ToasterBox} on screen.

        :param `direction`: specifies the direction for the centering. May be ``wx.HORIZONTAL``,
         ``wx.VERTICAL`` or ``wx.BOTH``.

        :see: L{CenterOnParent}.
        """

        screenSize = wx.GetDisplaySize()
        toast_width, toast_height = self._popupsize
        width, height = screenSize.GetWidth(), screenSize.GetHeight()

        if direction == wx.VERTICAL:
            pos = wx.Point(0, (height/2) - (toast_height/2))
        elif direction == wx.HORIZONTAL:
            pos = wx.Point((width/2) - (toast_width/2), 0)
        else:
            pos = wx.Point((width/2) - (toast_width/2), (height/2) - (toast_height/2))

        tb.SetPopupPosition(pos)

    CentreOnScreen = CenterOnScreen

[docs]    def SetPopupBackgroundColour(self, colour=None):
        """
        Sets the L{ToasterBox} background colour.

        :param `colour`: a valid `wx.Colour` object. If defaulted to ``None``, then
         the background colour will be white.

        :note: Use this method only for a L{ToasterBox} created with the ``TB_SIMPLE`` style.
        """

        if colour is None:
            colour = wx.WHITE

        if isinstance(colour, basestring):
            colour = wx.NamedColour(colour)

        self._backgroundcolour = colour
        self._tb.SetPopupBackgroundColour(self._backgroundcolour)

[docs]    def SetPopupTextColour(self, colour=None):
        """
        Sets the L{ToasterBox} foreground colour.

        :param `colour`: a valid `wx.Colour` object. If defaulted to ``None``, then
         the background colour will be black.

        :note: Use this method only for a L{ToasterBox} created with the ``TB_SIMPLE`` style.
        """

        if colour is None:
            colour = wx.BLACK

        if isinstance(colour, basestring):
            colour = wx.NamedColour(colour)

        self._foregroundcolour = colour

[docs]    def SetPopupTextFont(self, font=None):
        """
        Sets the L{ToasterBox} text font.

        :param `colour`: a valid `wx.Colour` object. If defaulted to ``None``, then
         a simple generic font will be generated.

        :note: Use this method only for a L{ToasterBox} created with the ``TB_SIMPLE`` style.
        """

        if font is None:
            font = wx.Font(8, wx.SWISS, wx.NORMAL, wx.NORMAL, False)

        self._textfont = font

[docs]    def SetPopupSize(self, size):
        """
        Sets the L{ToasterBox} size.

        :param `size`: the new control size, an instance of `wx.Size`.
        """

        self._popupsize = size

[docs]    def SetPopupPauseTime(self, pausetime):
        """
        Sets the time after which the L{ToasterBox} is destroyed (linger).

        :param `pausetime`: the delay after which the control is destroyed, in seconds.
        """

        self._pausetime = pausetime

[docs]    def SetPopupBitmap(self, bitmap=None):
        """
        Sets the L{ToasterBox} background image.

        :param `bitmap`: a valid `wx.Bitmap` object or filename. If defaulted
         to ``None``, then no background bitmap is used.

        :note: Use this method only for a L{ToasterBox} created with the ``TB_SIMPLE`` style.
        """

        if bitmap is not None:
            if isinstance(bitmap, basestring):
                bitmap = wx.Bitmap(bitmap)

        self._bitmap = bitmap

[docs]    def SetPopupScrollSpeed(self, speed):
        """
        Sets the L{ToasterBox} scroll speed.

        :param `speed`: it is the pause time (in milliseconds) for every step in the
         `ScrollUp` method.
        """

        self._sleeptime = speed

[docs]    def SetPopupText(self, text):
        """
        Sets the L{ToasterBox} text label.

        :param `text`: the widget label.

        :note: Use this method only for a L{ToasterBox} created with the ``TB_SIMPLE`` style.
        """

        self._popuptext = text

[docs]    def AddPanel(self, panel):
        """
        Adds a panel to the L{ToasterBox}.

        :param `panel`: an instance of `wx.Window`.

        :note: Use this method only for a L{ToasterBox} created with the ``TB_COMPLEX`` style.
        """

        if not self._tbstyle & TB_COMPLEX:
            raise Exception("\nERROR: Panel Can Not Be Added When Using TB_SIMPLE ToasterBox Style")

        self._panel = panel

[docs]    def Play(self):
        """ Creates the L{ToasterBoxWindow}, that does all the job. """

        # create new window
        self._tb.SetPopupSize((self._popupsize[0], self._popupsize[1]))
        self._tb.SetPopupPosition((self._popupposition[0], self._popupposition[1]))
        self._tb.SetPopupPauseTime(self._pausetime)
        self._tb.SetPopupScrollSpeed(self._sleeptime)
        self._tb.SetUseFocus(self._usefocus, self._originalfocus)

        if self._tbstyle == TB_SIMPLE:
            self._tb.SetPopupTextColour(self._foregroundcolour)
            self._tb.SetPopupBackgroundColour(self._backgroundcolour)
            self._tb.SetPopupTextFont(self._textfont)

            if self._bitmap is not None:
                self._tb.SetPopupBitmap(self._bitmap)

            self._tb.SetPopupText(self._popuptext)

        if self._tbstyle == TB_COMPLEX:
            if self._panel is not None:
                self._tb.AddPanel(self._panel)

        # clean up the list
        self.CleanList()

        # check to see if there is already a window displayed
        # by looking at the linked list
        if len(winlist) > 0:
            # there ARE other windows displayed already
            # reclac where it should display
            self.MoveAbove(self._tb)

        # shift new window on to the list
        winlist.append(self._tb)

        if not self._tb.Play():
            # if we didn't show the window properly, remove it from the list
            winlist.remove(winlist[-1])
            # delete the object too
            self._tb.Destroy()
            return

[docs]    def MoveAbove(self, tb):
        """
        If a L{ToasterBox} already exists, move the new one above the existing one.

        :param `tb`: another instance of L{ToasterBox}.
        """

        # recalc where to place this popup

        self._tb.SetPopupPosition((self._popupposition[0], self._popupposition[1] -
                                   self._popupsize[1]*len(winlist)))

[docs]    def GetToasterBoxWindow(self):
        """ Returns the L{ToasterBox} frame. """

        return self._tb

[docs]    def SetTitle(self, title):
        """
        Sets the L{ToasterBox} title if it was created with ``TB_CAPTION`` window style.

        :param `title`: the L{ToasterBox} caption title.
        """

        self._tb.SetTitle(title)

[docs]    def SetUseFocus(self, focus):
        """
        If `focus` is ``True``, Instructs L{ToasterBox} to steal the focus from the
        parent application, otherwise it returns the focus to the original owner.

        :param `focus`: ``True`` to set the focus on L{ToasterBox}, ``False`` to
         return it to the original owner.
        """

        self._usefocus = focus

[docs]    def GetUseFocus(self):
        """ Returns whether L{ToasterBox} will steal the focus from the parent application. """

        return self._usefocus

[docs]    def Notify(self):
        """ It's time to hide a L{ToasterBox}. """

        if len(winlist) == 0:
            return

        # clean the window list
        self.CleanList()

        # figure out how many blanks we have
        try:
            node = winlist[0]
        except:
            return

        if not node:
            return

        self._startPos = node.GetPosition()[1]
        self._moveTimer.Start(self._sleeptime)

[docs]    def OnMoveTimer(self, event):
        """
        Handles the ``wx.EVT_TIMER`` event for L{ToasterBox}, moving the new window
        on top of the last one created.

        :param `event`: a `wx.TimerEvent` event to be processed.
        """

        current = self._startPos
        if current >= self._popupposition[1]:
            self._moveTimer.Stop()

        # move windows to fill in blank space

        if current > self._popupposition[1]:
            current = self._popupposition[1]

        # loop through all the windows
        for j in xrange(0, len(winlist)):
            ourNewHeight = current - (j*self._popupsize[1] - 8)
            tmpTb = winlist[j]
            # reset where the object THINKS its supposed to be
            tmpTb.SetPopupPosition((self._popupposition[0], ourNewHeight))
            # actually move it
            tmpTb.SetDimensions(self._popupposition[0], ourNewHeight, tmpTb.GetSize().GetWidth(),
                                tmpTb.GetSize().GetHeight())

        self._startPos += 4

[docs]    def CleanList(self):
        """ Cleans the window list, erasing the stack of L{ToasterBox} objects. """

        if len(winlist) == 0:
            return

        node = winlist[0]
        while node:
            if not node.IsShown():
                winlist.remove(node)
                node.Close()
                try:
                    node = winlist[0]
                except:
                    node = 0
            else:
                indx = winlist.index(node)
                try:
                    node = winlist[indx+1]
                except:
                    node = 0

# ------------------------------------------------------------------------------ #
# Class ToasterBoxWindow
#    This Class Does All The Job, By Handling Background Images, Text Properties
#    And Panel Adding. Depending On The Style You Choose, ToasterBoxWindow Will
#    Behave Differently In Order To Handle Widgets Inside It.
# ------------------------------------------------------------------------------ #

[docs]class ToasterBoxWindow(wx.Frame):
    """
    This class does all the job, by handling background images, text properties
    and panel adding. Depending on the style you choose, L{ToasterBoxWindow} will
    behave differently in order to handle widgets inside it.
    """

[docs]    def __init__(self, parent, parent2, tbstyle, windowstyle, closingstyle,
                 scrollType=TB_SCR_TYPE_DU):
        """
        Default class constructor.
        Used internally. Do not call directly this class in your application!

        :param `parent`: the window parent;
        :param `parent2`: the L{ToasterBox} calling this window;
        :param `tbstyle`: the L{ToasterBoxWindow} main style. Can be one of the following
         bits:

         ====================== ======= ================================
         `ToasterBox` Style      Value  Description
         ====================== ======= ================================
         ``TB_SIMPLE``              0x1 A simple L{ToasterBox}, with background image and text customization can be created
         ``TB_COMPLEX``             0x2 `ToasterBoxes` with different degree of complexity can be created. You can add as many controls as you want, provided that you call the L{AddPanel} method and pass to it a dummy frame and a `wx.Panel`.
         ====================== ======= ================================

        :param `windowstyle`: this parameter influences the visual appearance of
         L{ToasterBoxWindow}, and can be one of the following styles:

         ====================== ========== ================================
         Window Style           Hex Value  Description
         ====================== ========== ================================
         ``TB_DEFAULT_STYLE``   0x2008002  Default window style for L{ToasterBox}, with no caption nor close box.
         ``TB_CAPTION``         0x22009806 L{ToasterBox} will have a caption, with the possibility to set a title for the L{ToasterBox} frame, and a close box.
         ====================== ========== ================================

        :param `closingstyle`: the closing style for L{ToasterBoxWindow}. Can be one of the
         following bits:

         ==================== =========== ==================================================
         Closing Styles       Hex Value   Description
         ==================== =========== ==================================================
         ``TB_ONTIME``                0x1 L{ToasterBox} will close after a specified amount of time.
         ``TB_ONCLICK``               0x2 L{ToasterBox} can be closed by clicking anywhere on the L{ToasterBox} frame.
         ==================== =========== ==================================================

        :param `scrollType`: the scrolling direction for L{ToasterBoxWindow}. Can be one of the
         following bits:

         ==================== =========== ==================================================
         Scroll Styles        Hex Value   Description
         ==================== =========== ==================================================
         ``TB_SCR_TYPE_UD``           0x1 L{ToasterBox} will scroll from up to down
         ``TB_SCR_TYPE_DU``           0x2 L{ToasterBox} will scroll from down to up
         ``TB_SCR_TYPE_FADE``         0x4 L{ToasterBox} will fade in/out (without scrolling).
         ==================== =========== ==================================================

        """

        wx.Frame.__init__(self, parent, wx.ID_ANY, "window", wx.DefaultPosition,
                         wx.DefaultSize, style=windowstyle | wx.CLIP_CHILDREN)

        self._starttime = wx.GetLocalTime()
        self._parent2 = parent2
        self._parent = parent
        self._sleeptime = 10
        self._step = 4
        self._pausetime = 1700
        self._textcolour = wx.BLACK
        self._popuptext = "Change Me!"
        # the size we want the dialog to be
        framesize = wx.Size(150, 170)
        self._count = 1
        self._tbstyle = tbstyle
        self._windowstyle = windowstyle
        self._closingstyle = closingstyle
        self._backgroundcolour = wx.WHITE

        if tbstyle == TB_COMPLEX:
            self.sizer = wx.BoxSizer(wx.VERTICAL)
        else:
            self._staticbitmap = None

        if self._windowstyle == TB_CAPTION:
            self.Bind(wx.EVT_CLOSE, self.OnClose)
            self.SetTitle("")

        if scrollType == TB_SCR_TYPE_FADE and not self.CanSetTransparent():
            import warnings
            warnings.warn("The style ``TB_SCR_TYPE_FADE`` is not supported on this platform.")
            scrollType = TB_SCR_TYPE_DU

        self._scrollType = scrollType

        if self._closingstyle & TB_ONCLICK and self._windowstyle != TB_CAPTION:
            self.Bind(wx.EVT_LEFT_DOWN, self.OnMouseDown)

        self._bottomright = wx.Point(wx.GetDisplaySize().GetWidth(),
                                     wx.GetDisplaySize().GetHeight())

        self.SetDimensions(self._bottomright.x, self._bottomright.y,
                           framesize.GetWidth(), framesize.GetHeight())

        self._scrollTimer = wx.Timer(self, -1)
        self._alphaTimer = wx.Timer(self, -1)

        self.Bind(wx.EVT_TIMER, self.OnScrollTimer, self._scrollTimer)
        self.Bind(wx.EVT_TIMER, self.AlphaCycle, self._alphaTimer)

        if not self._tbstyle & TB_COMPLEX:
            self.Bind(wx.EVT_PAINT, self.OnPaint)
            self.SetBackgroundStyle(wx.BG_STYLE_CUSTOM)

[docs]    def OnClose(self, event):
        """
        Handles the ``wx.EVT_CLOSE`` event for L{ToasterBoxWindow}.

        :param `event`: a `wx.CloseEvent` event to be processed.
        """

        self.NotifyTimer(None)
        event.Skip()

[docs]    def OnMouseDown(self, event):
        """
        Handles the ``wx.EVT_LEFT_DOWN`` event for L{ToasterBoxWindow}.

        :param `event`: a `wx.MouseEvent` event to be processed.
        """

        self.NotifyTimer(None)
        event.Skip()

[docs]    def SetPopupBitmap(self, bitmap=None):
        """
        Sets the L{ToasterBox} background image.

        :param `bitmap`: a valid `wx.Bitmap` object. If defaulted to ``None``, then
         no background bitmap is used.

        :note: Use this method only for a L{ToasterBox} created with the ``TB_SIMPLE`` style.
        """

        if bitmap is None:
            self._staticbitmap = None
        else:
            bitmap = bitmap.ConvertToImage()
            xsize, ysize = self.GetSize()
            bitmap = bitmap.Scale(xsize, ysize)
            self._staticbitmap = bitmap.ConvertToBitmap()

[docs]    def SetPopupSize(self, size):
        """
        Sets the L{ToasterBox} size.

        :param `size`: the new control size, an instance of `wx.Size`.
        """

        self.SetDimensions(self._bottomright.x, self._bottomright.y, size[0], size[1])

[docs]    def SetPopupPosition(self, pos):
        """
        Sets the L{ToasterBox} position on screen.

        :param `pos`: the widget position, an instance of `wx.Point`.
        """

        self._bottomright = wx.Point(pos[0] + self.GetSize().GetWidth(),
                                     pos[1] + self.GetSize().GetHeight())
        self._dialogtop = pos

[docs]    def SetPopupPositionByInt(self, pos):
        """
        Sets the L{ToasterBox} position on screen, at one of the screen corners.

        :param `pos`: an integer specifying the screen corner, namely:

         ============= ========================================
         Corner Number Position
         ============= ========================================
               0       Top left screen corner
               1       Top right screen corner
               2       Bottom left screen corner
               3       Bottom right screen corner
         ============= ========================================

        """

        w, h = wx.GetDisplaySize()
        self._bottomright = wx.Point(w, h)

        # top left
        if pos == 0:
            popupposition = wx.Point(0, 0)
        # top right
        elif pos == 1:
            popupposition = wx.Point(w - self._popupsize[0], 0)
        # bottom left
        elif pos == 2:
           popupposition = wx.Point(0, h - self._popupsize[1])
         # bottom right
        elif pos == 3:
            popupposition = wx.Point(self._bottomright.x - self._popupsize[0],
                                     self._bottomright.y - self._popupsize[1])

        self._bottomright = wx.Point(popupposition.x + self._popupsize[0],
                                     popupposition.y + self._popupsize[1])

        self._dialogtop = popupposition

[docs]    def SetPopupPauseTime(self, pausetime):
        """
        Sets the time after which the L{ToasterBox} is destroyed (linger).

        :param `pausetime`: the delay after which the control is destroyed, in seconds.
        """

        self._pausetime = pausetime

[docs]    def SetPopupScrollSpeed(self, speed):
        """
        Sets the L{ToasterBox} scroll speed.

        :param `speed`: it is the pause time (in milliseconds) for every step in the
         L{ScrollUp} method.
        """

        self._sleeptime = speed

[docs]    def AddPanel(self, panel):
        """
        Adds a panel to the L{ToasterBox}.

        :param `panel`: an instance of `wx.Window`.

        :note: Use this method only for a L{ToasterBox} created with the ``TB_COMPLEX`` style.
        """

        if not self._tbstyle & TB_COMPLEX:
            raise Exception("\nERROR: Panel Can Not Be Added When Using TB_SIMPLE ToasterBox Style")

        self.sizer.Add(panel, 1, wx.EXPAND)
        self.SetSizer(self.sizer)
        self.Layout()

        if self._closingstyle & TB_ONCLICK and self._windowstyle != TB_CAPTION:
            panel.Bind(wx.EVT_LEFT_DOWN, self.OnMouseDown)

[docs]    def SetPopupText(self, text):
        """
        Sets the L{ToasterBox} text label.

        :param `text`: the widget label.

        :note: Use this method only for a L{ToasterBox} created with the ``TB_SIMPLE`` style.
        """

        self._popuptext = text

[docs]    def SetPopupTextFont(self, font):
        """
        Sets the L{ToasterBox} text font.

        :param `colour`: a valid `wx.Colour` object. If defaulted to ``None``, then
         a simple generic font will be generated.

        :note: Use this method only for a L{ToasterBox} created with the ``TB_SIMPLE`` style.
        """

        self._textfont = font

[docs]    def GetPopupText(self):
        """
        Returns the L{ToasterBox} text.

        :note: Use this method only for a L{ToasterBox} created with the ``TB_SIMPLE`` style.
        """

        return self._popuptext

[docs]    def Play(self):
        """ Creates the L{ToasterBoxWindow}, that does all the job. """

        # do some checks to make sure this window is valid
        if self._bottomright.x < 1 or self._bottomright.y < 1:
            return False

        if self.GetSize().GetWidth() < 50 or self.GetSize().GetWidth() < 50:
            # toasterbox launches into a endless loop for some reason
            # when you try to make the window too small.
            return False

        self._direction = wx.UP
        self.SetupPositions()
        self.ScrollUp()
        timerid = wx.NewId()
        self.showtime = wx.Timer(self, timerid)
        self.showtime.Start(self._pausetime)
        self.Bind(wx.EVT_TIMER, self.NotifyTimer, id=timerid)

        return True

[docs]    def NotifyTimer(self, event):
        """ Hides gradually the L{ToasterBoxWindow}. """

        if self._scrollType != TB_SCR_TYPE_FADE:
            self.showtime.Stop()
            del self.showtime

        self._direction = wx.DOWN
        self.SetupPositions()

        self.ScrollDown()

[docs]    def SetPopupBackgroundColour(self, colour):
        """
        Sets the L{ToasterBox} background colour.

        :param `colour`: a valid `wx.Colour` object. If defaulted to ``None``, then
         the background colour will be white.

        :note: Use this method only for a L{ToasterBox} created with the ``TB_SIMPLE`` style.
        """

        self.SetBackgroundColour(colour)
        self._backgroundcolour = colour

[docs]    def SetPopupTextColour(self, colour):
        """
        Sets the L{ToasterBox} foreground colour.

        :param `colour`: a valid `wx.Colour` object. If defaulted to ``None``, then
         the background colour will be black.

        :note: Use this method only for a L{ToasterBox} created with the ``TB_SIMPLE`` style.
        """

        self._textcolour = colour

[docs]    def SetUseFocus(self, focus, originalfocus):
        """
        If `focus` is ``True``, Instructs L{ToasterBoxWindow} to steal the focus from the
        parent application, otherwise it returns the focus to the original owner.

        :param `focus`: ``True`` to set the focus on L{ToasterBoxWindow}, ``False`` to
         return it to the original owner;
        :param `originalfocus`: an instance of `wx.Window`, representing a pointer to
         the window which originally had the focus
        """

        self._usefocus = focus
        self._originalfocus = originalfocus

[docs]    def OnScrollTimer(self, event):
        """
        Handles the ``wx.EVT_TIMER`` event for L{ToasterBoxWindow} scrolling up/down.

        :param `event`: a `wx.TimerEvent` event to be processed.
        """

        if self._direction == wx.UP:
            self.TearUp()
        else:
            self.TearDown()

[docs]    def TearUp(self):
        """ Scrolls the L{ToasterBox} up, which means gradually showing it. """

        self._windowsize = self._windowsize + self._step
        step = self._currentStep

        if step < self._dialogtop[1]:
            step = self._dialogtop[1]

         # checking the type of the scroll (from up to down or from down to up)
        if self._scrollType == TB_SCR_TYPE_UD:
            dimY = self._dialogtop[1]
        elif self._scrollType == TB_SCR_TYPE_DU:
            dimY = step

        self.SetDimensions(self._dialogtop[0], dimY, self.GetSize().GetWidth(), self._windowsize)

        self.Refresh(False)

        self._currentStep += self._scrollStep

        if self._currentStep not in range(self._start, self._stop, self._scrollStep):
            self._scrollTimer.Stop()
            self.Update()

            if self._tbstyle == TB_SIMPLE:
                self.DrawText()

            if self._usefocus:
                self.SetFocus()
            else:
                self._originalfocus.SetFocus()

[docs]    def TearDown(self):
        """ Scrolls the L{ToasterBox} down, which means gradually hiding it. """

        self._windowsize = self._windowsize - self._step
        step = self._currentStep

        if step > self._bottomright.y:
            step = self._bottomright.y

        if self._windowsize > 0:
            # checking the type of the scroll (from up to down or from down to up)
            if self._scrollType == TB_SCR_TYPE_UD:
                dimY = self._dialogtop[1]
            elif self._scrollType == TB_SCR_TYPE_DU:
                dimY = step

            self.SetDimensions(self._dialogtop[0], dimY,
                               self.GetSize().GetWidth(), self._windowsize)

            self.Update()
            self.Refresh()

            self._currentStep += self._scrollStep

        else:
            self._scrollTimer.Stop()
            self.Hide()
            if self._parent2:
                self._parent2.Notify()

[docs]    def SetupPositions(self):
        """ Sets up the position, size and scrolling step for L{ToasterBoxWindow}. """

        if self._scrollType == TB_SCR_TYPE_FADE:
            self.SetPosition(wx.Point(*self._dialogtop))
            return

        if self._direction == wx.UP:
            # walk the Y value up in a raise motion
            self._xpos = self.GetPosition().x
            self._ypos = self._bottomright[1]
            self._windowsize = 0

            # checking the type of the scroll (from up to down or from down to up)
            if self._scrollType == TB_SCR_TYPE_UD:
                self._start = self._dialogtop[1]
                self._stop = self._ypos
                self._scrollStep = self._step
            elif self._scrollType == TB_SCR_TYPE_DU:
                self._start = self._ypos
                self._stop = self._dialogtop[1]
                self._scrollStep = -self._step

        else:

            # walk down the Y value
            self._windowsize = self.GetSize().GetHeight()

            # checking the type of the scroll (from up to down or from down to up)
            if self._scrollType == TB_SCR_TYPE_UD:
                self._start = self._bottomright.y
                self._stop = self._dialogtop[1]
                self._scrollStep = -self._step
            elif self._scrollType == TB_SCR_TYPE_DU:
                self._start = self._dialogtop[1]
                self._stop = self._bottomright.y
                self._scrollStep = self._step

        self._currentStep = self._start

[docs]    def ScrollUp(self):
        """ Scrolls the L{ToasterBox} up, which means gradually showing it. """

        if self._scrollType == TB_SCR_TYPE_FADE:
            self._amount = 0
            self._delta = 5
            self.SetSize(self.GetSize())
            self._alphaTimer.Start(self._sleeptime)
        else:
            self.Show(True)
            self._scrollTimer.Start(self._sleeptime)

[docs]    def ScrollDown(self):
        """ Scrolls the L{ToasterBox} down, which means gradually hiding it. """

        if self._scrollType == TB_SCR_TYPE_FADE:
            self._amount = 255
            self._delta = -5
            self._alphaTimer.Start(self._sleeptime)
        else:
            self._scrollTimer.Start(self._sleeptime)

[docs]    def OnPaint(self, event):
        """
        Handles the ``wx.EVT_PAINT`` event for L{ToasterBoxWindow}.

        :param `event`: a `wx.PaintEvent` event to be processed.

        :note: This event is handled and processed only if the style ``TB_SIMPLE`` is
         given to L{ToasterBox}.
        """

        dc = wx.AutoBufferedPaintDC(self)
        self.DrawText(dc)

[docs]    def DrawText(self, dc=None):
        """
        Draws the text label for a L{ToasterBox} with ``TB_SIMPLE`` style set.

        :param `dc`: an instance of `wx.DC`. If defaulted to ``None``, a `wx.ClientDC`
         will be created on the fly.
        """

        if dc is None:
            dc = wx.ClientDC(self)

        dc.SetBackground(wx.Brush(self._backgroundcolour))
        dc.Clear()

        if self._staticbitmap:
            dc.DrawBitmap(self._staticbitmap, 0, 0)
        dc.SetFont(self._textfont)
        dc.SetTextForeground(self._textcolour)

        if not hasattr(self, "text_coords"):
            self._getTextCoords(dc)
        dc.DrawTextList(*self.text_coords)

[docs]    def AlphaCycle(self, event):
        """
        Handles the ``wx.EVT_TIMER`` event for L{ToasterBoxWindow}.

        :param `event`: a `wx.TimerEvent` event to be processed.
        """

        # Increase (or decrease) the alpha channel
        self._amount += self._delta

        if self._tbstyle == TB_SIMPLE:
            self.Refresh(False)

        if self._amount > 255 or self._amount < 0:
            # We're done, stop the timer
            self._alphaTimer.Stop()

            if self._amount < 0:
                self.Hide()
                if self._parent2:
                    self._parent2.Notify()

            elif self._amount > 255:
                if self._usefocus:
                    self.SetFocus()
                else:
                    self._originalfocus.SetFocus()

            return

        # Make the ToasterBoxWindow more or less transparent
        self.MakeWindowTransparent(self._amount)
        if not self.IsShown():
            self.Show()

[docs]    def MakeWindowTransparent(self, amount):
        """
        Makes the L{ToasterBoxWindow} window transparent.

        :param `amount`: the alpha channel value.
        """

        if not self.CanSetTransparent():
            return

        self.SetTransparent(amount)

    def _getTextCoords(self, dc):
        """
        Draw the user specified text.

        :param `dc`: an instance of `wx.DC`.

        :note: Use this method only for a L{ToasterBox} created with the ``TB_SIMPLE`` style.
        """

        # border from sides and top to text (in pixels)
        border = 7
        # how much space between text lines
        textPadding = 2

        pText = self.GetPopupText()

        max_len = len(pText)

        tw, th = self._parent2._popupsize

        if self._windowstyle == TB_CAPTION:
            th = th - 20

        while 1:
            lines = textwrap.wrap(pText, max_len)

            for line in lines:
                w, h = dc.GetTextExtent(line)
                if w > tw - border * 2:
                    max_len -= 1
                    break
            else:
                break

        fh = 0
        for line in lines:
            w, h = dc.GetTextExtent(line)
            fh += h + textPadding
        y = (th - fh) / 2; coords = []

        for line in lines:
            w, h = dc.GetTextExtent(line)
            x = (tw - w) / 2
            coords.append((x, y))
            y += h + textPadding

        self.text_coords = (lines, coords)

Navigation

  • index
  • modules |
  • Home |
  • Gallery |
  • Contents»
  • Module code »
  • toasterbox


ultimatelistctrl

  • modules |
  • Home |
  • Gallery |
  • Contents»
  • Module code »
  • ultimatelistctrl

Source code for ultimatelistctrl

# --------------------------------------------------------------------------------- #
# ULTIMATELISTCTRL wxPython IMPLEMENTATION
# Inspired by and heavily based on the wxWidgets C++ generic version of wxListCtrl.
#
# Andrea Gavana, @ 08 May 2009
# Latest Revision: 09 Feb 2012, 21.00 GMT
#
#
# TODO List
#
# 1)  Subitem selection;
# 2)  Watermark? (almost, does not work very well :-( );
# 3)  Groups? (Maybe, check ObjectListView);
# 4)  Scrolling items as headers and footers;
# 5)  Alpha channel for text/background of items;
# 6)  Custom renderers for headers/footers (done);
# 7)  Fading in and out on mouse motion (a la Windows Vista Aero);
# 8)  Sub-text for headers/footers (grey text below the header/footer text);
# 9)  Fixing the columns to the left or right side of the control layout;
# 10) Skins for header and scrollbars (implemented for headers/footers).
#
#
# 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
# --------------------------------------------------------------------------------- #

"""
Description
===========

UltimateListCtrl is a class that mimics the behaviour of `wx.ListCtrl`, with almost
the same base functionalities plus some more enhancements. This class does
not rely on the native control, as it is a full owner-drawn list control.

In addition to the standard `wx.ListCtrl` behaviour this class supports:

Appearance
==========

* Multiple images for items/subitems;
* Images can be of any size and not limited to a single specific pair of `width`, `height`
  as it is the case of `wx.ImageList`. Simply use L{PyImageList} instead of `wx.ImageList`
  to add your images.
* Font, colour, background, custom renderers and formatting for items and subitems;
* Ability to add persistent data to an item using L{SetItemPyData} and L{GetItemPyData}:
  the data can be any Python object and not necessarily an integer as in `wx.ListCtrl`;
* CheckBox-type items and subitems;
* RadioButton-type items and subitems;
* Overflowing items/subitems, a la `wx.grid.Grid`, i.e. an item/subitem may overwrite neighboring
  items/subitems if its text would not normally fit in the space allotted to it;
* Hyperlink-type items and subitems: they look like an hyperlink, with the proper mouse
  cursor on hovering;
* Multiline text items and subitems;
* Variable row heights depending on the item/subitem kind/text/window;
* User defined item/subitem renderers: these renderer classes **must** implement the methods
  `DrawSubItem`, `GetLineHeight` and `GetSubItemWidth` (see the demo);
* Enabling/disabling items (together with their plain or grayed out icons);
* Whatever non-toplevel widget can be attached next to an item/subitem;
* Column headers are fully customizable in terms of icons, colour, font, alignment etc...;
* Column headers can have their own checkbox/radiobutton;
* Column footers are fully customizable in terms of icons, colour, font, alignment etc...;
* Column footers can have their own checkbox/radiobutton;
* Ability to hide/show columns;
* Default selection style, gradient (horizontal/vertical) selection style and Windows
  Vista selection style.

And a lot more. Check the demo for an almost complete review of the functionalities.

Usage
=====

Usage example::

    import sys

    import wx
    import wx.lib.agw.ultimatelistctrl as ULC

    class MyFrame(wx.Frame):

        def __init__(self):

            wx.Frame.__init__(self, parent, -1, "UltimateListCtrl Demo")

            list = ULC.UltimateListCtrl(self, wx.ID_ANY, agwStyle=wx.LC_REPORT|wx.LC_VRULES|wx.LC_HRULES|wx.LC_SINGLE_SEL)

            list.InsertColumn(0, "Column 1")
            list.InsertColumn(1, "Column 2")

            index = list.InsertStringItem(sys.maxint, "Item 1")
            list.SetStringItem(index, 1, "Sub-item 1")

            index = list.InsertStringItem(sys.maxint, "Item 2")
            list.SetStringItem(index, 1, "Sub-item 2")

            choice = wx.Choice(list, -1, choices=["one", "two"])
            index = list.InsertStringItem(sys.maxint, "A widget")

            list.SetItemWindow(index, 1, choice, expand=True)

            sizer = wx.BoxSizer(wx.VERTICAL)
            sizer.Add(list, 1, wx.EXPAND)
            self.SetSizer(sizer)

    # our normal wxApp-derived class, as usual

    app = wx.PySimpleApp()

    frame = MyFrame(None)
    app.SetTopWindow(frame)
    frame.Show()

    app.MainLoop()

Window Styles
=============

This class supports the following window styles:

===============================  =========== ====================================================================================================
Window Styles                    Hex Value   Description
===============================  =========== ====================================================================================================
``ULC_VRULES``                           0x1 Draws light vertical rules between rows in report mode.
``ULC_HRULES``                           0x2 Draws light horizontal rules between rows in report mode.
``ULC_ICON``                             0x4 Large icon view, with optional labels.
``ULC_SMALL_ICON``                       0x8 Small icon view, with optional labels.
``ULC_LIST``                            0x10 Multicolumn list view, with optional small icons. Columns are computed automatically, i.e. you don't set columns as in ``ULC_REPORT``. In other words, the list wraps, unlike a `wx.ListBox`.
``ULC_REPORT``                          0x20 Single or multicolumn report view, with optional header.
``ULC_ALIGN_TOP``                       0x40 Icons align to the top. Win32 default, Win32 only.
``ULC_ALIGN_LEFT``                      0x80 Icons align to the left.
``ULC_AUTOARRANGE``                    0x100 Icons arrange themselves. Win32 only.
``ULC_VIRTUAL``                        0x200 The application provides items text on demand. May only be used with ``ULC_REPORT``.
``ULC_EDIT_LABELS``                    0x400 Labels are editable: the application will be notified when editing starts.
``ULC_NO_HEADER``                      0x800 No header in report mode.
``ULC_NO_SORT_HEADER``                0x1000 No Docs.
``ULC_SINGLE_SEL``                    0x2000 Single selection (default is multiple).
``ULC_SORT_ASCENDING``                0x4000 Sort in ascending order. (You must still supply a comparison callback in `wx.ListCtrl.SortItems`.)
``ULC_SORT_DESCENDING``               0x8000 Sort in descending order. (You must still supply a comparison callback in `wx.ListCtrl.SortItems`.)
``ULC_TILE``                         0x10000 Each item appears as a full-sized icon with a label of one or more lines beside it (partially implemented).
``ULC_NO_HIGHLIGHT``                 0x20000 No highlight when an item is selected.
``ULC_STICKY_HIGHLIGHT``             0x40000 Items are selected by simply hovering on them, with no need to click on them.
``ULC_STICKY_NOSELEVENT``            0x80000 Don't send a selection event when using ``ULC_STICKY_HIGHLIGHT`` style.
``ULC_SEND_LEFTCLICK``              0x100000 Send a left click event when an item is selected.
``ULC_HAS_VARIABLE_ROW_HEIGHT``     0x200000 The list has variable row heights.
``ULC_AUTO_CHECK_CHILD``            0x400000 When a column header has a checkbox associated, auto-check all the subitems in that column.
``ULC_AUTO_TOGGLE_CHILD``           0x800000 When a column header has a checkbox associated, toggle all the subitems in that column.
``ULC_AUTO_CHECK_PARENT``          0x1000000 Only meaningful foe checkbox-type items: when an item is checked/unchecked its column header item is checked/unchecked as well.
``ULC_SHOW_TOOLTIPS``              0x2000000 Show tooltips for ellipsized items/subitems (text too long to be shown in the available space) containing the full item/subitem text.
``ULC_HOT_TRACKING``               0x4000000 Enable hot tracking of items on mouse motion.
``ULC_BORDER_SELECT``              0x8000000 Changes border colour whan an item is selected, instead of highlighting the item.
``ULC_TRACK_SELECT``              0x10000000 Enables hot-track selection in a list control. Hot track selection means that an item is automatically selected when the cursor remains over the item for a certain period of time. The delay is retrieved on Windows using the `win32api` call `win32gui.SystemParametersInfo(win32con.SPI_GETMOUSEHOVERTIME)`, and is defaulted to 400ms on other platforms. This style applies to all views of `UltimateListCtrl`.
``ULC_HEADER_IN_ALL_VIEWS``       0x20000000 Show column headers in all view modes.
``ULC_NO_FULL_ROW_SELECT``        0x40000000 When an item is selected, the only the item in the first column is highlighted.
``ULC_FOOTER``                    0x80000000 Show a footer too (only when header is present).
``ULC_USER_ROW_HEIGHT``          0x100000000 Allows to set a custom row height (one value for all the items, only in report mode).
===============================  =========== ====================================================================================================

Events Processing
=================

This class processes the following events:

======================================== ====================================================================================================
Event Name                               Description
======================================== ====================================================================================================
``EVT_LIST_BEGIN_DRAG``                  Begin dragging with the left mouse button.
``EVT_LIST_BEGIN_RDRAG``                 Begin dragging with the right mouse button.
``EVT_LIST_BEGIN_LABEL_EDIT``            Begin editing a label. This can be prevented by calling `Veto()`.
``EVT_LIST_END_LABEL_EDIT``              Finish editing a label. This can be prevented by calling `Veto()`.
``EVT_LIST_DELETE_ITEM``                 An item was deleted.
``EVT_LIST_DELETE_ALL_ITEMS``            All items were deleted.
``EVT_LIST_KEY_DOWN``                    A key has been pressed.
``EVT_LIST_INSERT_ITEM``                 An item has been inserted.
``EVT_LIST_COL_CLICK``                   A column (`m_col`) has been left-clicked.
``EVT_LIST_COL_RIGHT_CLICK``             A column (`m_col`) has been right-clicked.
``EVT_LIST_COL_BEGIN_DRAG``              The user started resizing a column - can be vetoed.
``EVT_LIST_COL_END_DRAG``                The user finished resizing a column.
``EVT_LIST_COL_DRAGGING``                The divider between columns is being dragged.
``EVT_LIST_ITEM_SELECTED``               The item has been selected.
``EVT_LIST_ITEM_DESELECTED``             The item has been deselected.
``EVT_LIST_ITEM_RIGHT_CLICK``            The right mouse button has been clicked on an item.
``EVT_LIST_ITEM_MIDDLE_CLICK``           The middle mouse button has been clicked on an item.
``EVT_LIST_ITEM_ACTIVATED``              The item has been activated (``ENTER`` or double click).
``EVT_LIST_ITEM_FOCUSED``                The currently focused item has changed.
``EVT_LIST_CACHE_HINT``                  Prepare cache for a virtual list control.
``EVT_LIST_ITEM_CHECKING``               An item/subitem is being checked.
``EVT_LIST_ITEM_CHECKED``                An item/subitem has been checked.
``EVT_LIST_COL_CHECKING``                A column header is being checked.
``EVT_LIST_COL_CHECKED``                 A column header has being checked.
``EVT_LIST_FOOTER_CHECKING``             A column footer is being checked.
``EVT_LIST_FOOTER_CHECKED``              A column footer has being checked.
``EVT_LIST_ITEM_HYPERLINK``              An hyperlink item has been clicked.
``EVT_LIST_FOOTER_CLICK``                The user left-clicked on a column footer.
``EVT_LIST_FOOTER_RIGHT_CLICK``          The user right-clicked on a column footer.
``EVT_LIST_ITEM_LEFT_CLICK``             Send a left-click event after an item is selected.
``EVT_LIST_END_DRAG``                    Notify an end-drag operation.
======================================== ====================================================================================================

Supported Platforms
===================

UltimateListCtrl has been tested on the following platforms:
  * Windows (Windows XP);

License And Version
===================

UltimateListCtrl is distributed under the wxPython license.

Latest Revision: Andrea Gavana @ 09 Feb 2012, 21.00 GMT

Version 0.8

"""

import wx
import math
import bisect
import types
import zlib
import cStringIO

from wx.lib.expando import ExpandoTextCtrl

# Version Info
__version__ = "0.8"

# wxPython version string
_VERSION_STRING = wx.VERSION_STRING

# ----------------------------------------------------------------------------
# UltimateListCtrl constants
# ----------------------------------------------------------------------------

# style flags
ULC_VRULES                  = wx.LC_VRULES
ULC_HRULES                  = wx.LC_HRULES

ULC_ICON                    = wx.LC_ICON
ULC_SMALL_ICON              = wx.LC_SMALL_ICON
ULC_LIST                    = wx.LC_LIST
ULC_REPORT                  = wx.LC_REPORT
ULC_TILE                    = 0x10000

ULC_ALIGN_TOP               = wx.LC_ALIGN_TOP
ULC_ALIGN_LEFT              = wx.LC_ALIGN_LEFT
ULC_AUTOARRANGE             = wx.LC_AUTOARRANGE
ULC_VIRTUAL                 = wx.LC_VIRTUAL
ULC_EDIT_LABELS             = wx.LC_EDIT_LABELS
ULC_NO_HEADER               = wx.LC_NO_HEADER
ULC_NO_SORT_HEADER          = wx.LC_NO_SORT_HEADER
ULC_SINGLE_SEL              = wx.LC_SINGLE_SEL
ULC_SORT_ASCENDING          = wx.LC_SORT_ASCENDING
ULC_SORT_DESCENDING         = wx.LC_SORT_DESCENDING

ULC_NO_HIGHLIGHT            = 0x20000
ULC_STICKY_HIGHLIGHT        = 0x40000
ULC_STICKY_NOSELEVENT       = 0x80000
ULC_SEND_LEFTCLICK          = 0x100000
ULC_HAS_VARIABLE_ROW_HEIGHT = 0x200000

ULC_AUTO_CHECK_CHILD    = 0x400000     # only meaningful for checkboxes
ULC_AUTO_TOGGLE_CHILD   = 0x800000     # only meaningful for checkboxes
ULC_AUTO_CHECK_PARENT   = 0x1000000    # only meaningful for checkboxes
ULC_SHOW_TOOLTIPS       = 0x2000000    # shows tooltips on items with ellipsis (...)
ULC_HOT_TRACKING        = 0x4000000    # enable hot tracking on mouse motion
ULC_BORDER_SELECT       = 0x8000000    # changes border colour whan an item is selected, instead of highlighting the item
ULC_TRACK_SELECT        = 0x10000000   # Enables hot-track selection in a list control. Hot track selection means that an item
                                       # is automatically selected when the cursor remains over the item for a certain period
                                       # of time. The delay is retrieved on Windows using the win32api call
                                       # win32gui.SystemParametersInfo(win32con.SPI_GETMOUSEHOVERTIME), and is defaulted to 400ms
                                       # on other platforms. This style applies to all styles of UltimateListCtrl.
ULC_HEADER_IN_ALL_VIEWS = 0x20000000   # Show column headers in all view modes
ULC_NO_FULL_ROW_SELECT  = 0x40000000   # When an item is selected, the only the item in the first column is highlighted
ULC_FOOTER              = 0x80000000   # Show a footer too (only when header is present)
ULC_USER_ROW_HEIGHT     = 0x100000000  # Allows to set a custom row height (one value for all the items, only in report mode).

ULC_MASK_TYPE  = ULC_ICON | ULC_SMALL_ICON | ULC_LIST | ULC_REPORT | ULC_TILE
ULC_MASK_ALIGN = ULC_ALIGN_TOP | ULC_ALIGN_LEFT
ULC_MASK_SORT  = ULC_SORT_ASCENDING | ULC_SORT_DESCENDING

# for compatibility only
ULC_USER_TEXT = ULC_VIRTUAL

# Omitted because
#  (a) too much detail
#  (b) not enough style flags
#  (c) not implemented anyhow in the generic version
#
# ULC_NO_SCROLL
# ULC_NO_LABEL_WRAP
# ULC_OWNERDRAW_FIXED
# ULC_SHOW_SEL_ALWAYS

# Mask flags to tell app/GUI what fields of UltimateListItem are valid
ULC_MASK_STATE         =      wx.LIST_MASK_STATE
ULC_MASK_TEXT          =      wx.LIST_MASK_TEXT
ULC_MASK_IMAGE         =      wx.LIST_MASK_IMAGE
ULC_MASK_DATA          =      wx.LIST_MASK_DATA
ULC_SET_ITEM           =      wx.LIST_SET_ITEM
ULC_MASK_WIDTH         =      wx.LIST_MASK_WIDTH
ULC_MASK_FORMAT        =      wx.LIST_MASK_FORMAT
ULC_MASK_FONTCOLOUR    =      0x0080
ULC_MASK_FONT          =      0x0100
ULC_MASK_BACKCOLOUR    =      0x0200
ULC_MASK_KIND          =      0x0400
ULC_MASK_ENABLE        =      0x0800
ULC_MASK_CHECK         =      0x1000
ULC_MASK_HYPERTEXT     =      0x2000
ULC_MASK_WINDOW        =      0x4000
ULC_MASK_PYDATA        =      0x8000
ULC_MASK_SHOWN         =      0x10000
ULC_MASK_RENDERER      =      0x20000
ULC_MASK_OVERFLOW      =      0x40000
ULC_MASK_FOOTER_TEXT   =      0x80000
ULC_MASK_FOOTER_IMAGE  =      0x100000
ULC_MASK_FOOTER_FORMAT =      0x200000
ULC_MASK_FOOTER_FONT   =      0x400000
ULC_MASK_FOOTER_CHECK  =      0x800000
ULC_MASK_FOOTER_KIND   =      0x1000000
ULC_MASK_TOOLTIP       =      0x2000000

# State flags for indicating the state of an item
ULC_STATE_DONTCARE    =   wx.LIST_STATE_DONTCARE
ULC_STATE_DROPHILITED =   wx.LIST_STATE_DROPHILITED      # MSW only
ULC_STATE_FOCUSED     =   wx.LIST_STATE_FOCUSED
ULC_STATE_SELECTED    =   wx.LIST_STATE_SELECTED
ULC_STATE_CUT         =   wx.LIST_STATE_CUT              # MSW only
ULC_STATE_DISABLED    =   wx.LIST_STATE_DISABLED         # OS2 only
ULC_STATE_FILTERED    =   wx.LIST_STATE_FILTERED         # OS2 only
ULC_STATE_INUSE       =   wx.LIST_STATE_INUSE            # OS2 only
ULC_STATE_PICKED      =   wx.LIST_STATE_PICKED           # OS2 only
ULC_STATE_SOURCE      =   wx.LIST_STATE_SOURCE           # OS2 only

# Hit test flags, used in HitTest
ULC_HITTEST_ABOVE           = wx.LIST_HITTEST_ABOVE            # Above the client area.
ULC_HITTEST_BELOW           = wx.LIST_HITTEST_BELOW            # Below the client area.
ULC_HITTEST_NOWHERE         = wx.LIST_HITTEST_NOWHERE          # In the client area but below the last item.
ULC_HITTEST_ONITEMICON      = wx.LIST_HITTEST_ONITEMICON       # On the bitmap associated with an item.
ULC_HITTEST_ONITEMLABEL     = wx.LIST_HITTEST_ONITEMLABEL      # On the label (string) associated with an item.
ULC_HITTEST_ONITEMRIGHT     = wx.LIST_HITTEST_ONITEMRIGHT      # In the area to the right of an item.
ULC_HITTEST_ONITEMSTATEICON = wx.LIST_HITTEST_ONITEMSTATEICON  # On the state icon for a tree view item that is in a user-defined state.
ULC_HITTEST_TOLEFT          = wx.LIST_HITTEST_TOLEFT           # To the left of the client area.
ULC_HITTEST_TORIGHT         = wx.LIST_HITTEST_TORIGHT          # To the right of the client area.
ULC_HITTEST_ONITEMCHECK     = 0x1000                           # On the checkbox (if any)

ULC_HITTEST_ONITEM = ULC_HITTEST_ONITEMICON | ULC_HITTEST_ONITEMLABEL | ULC_HITTEST_ONITEMSTATEICON | ULC_HITTEST_ONITEMCHECK

# Flags for GetNextItem (MSW only except ULC_NEXT_ALL)
ULC_NEXT_ABOVE = wx.LIST_NEXT_ABOVE         # Searches for an item above the specified item
ULC_NEXT_ALL   = wx.LIST_NEXT_ALL           # Searches for subsequent item by index
ULC_NEXT_BELOW = wx.LIST_NEXT_BELOW         # Searches for an item below the specified item
ULC_NEXT_LEFT  = wx.LIST_NEXT_LEFT          # Searches for an item to the left of the specified item
ULC_NEXT_RIGHT = wx.LIST_NEXT_RIGHT         # Searches for an item to the right of the specified item

# Alignment flags for Arrange (MSW only except ULC_ALIGN_LEFT)
ULC_ALIGN_DEFAULT      = wx.LIST_ALIGN_DEFAULT
ULC_ALIGN_SNAP_TO_GRID = wx.LIST_ALIGN_SNAP_TO_GRID

# Column format (MSW only except ULC_FORMAT_LEFT)
ULC_FORMAT_LEFT   = wx.LIST_FORMAT_LEFT
ULC_FORMAT_RIGHT  = wx.LIST_FORMAT_RIGHT
ULC_FORMAT_CENTRE = wx.LIST_FORMAT_CENTRE
ULC_FORMAT_CENTER = ULC_FORMAT_CENTRE

# Autosize values for SetColumnWidth
ULC_AUTOSIZE = wx.LIST_AUTOSIZE
ULC_AUTOSIZE_USEHEADER = wx.LIST_AUTOSIZE_USEHEADER      # partly supported by generic version
ULC_AUTOSIZE_FILL = -3

# Flag values for GetItemRect
ULC_RECT_BOUNDS = wx.LIST_RECT_BOUNDS
ULC_RECT_ICON   = wx.LIST_RECT_ICON
ULC_RECT_LABEL  = wx.LIST_RECT_LABEL

# Flag values for FindItem (MSW only)
ULC_FIND_UP    = wx.LIST_FIND_UP
ULC_FIND_DOWN  = wx.LIST_FIND_DOWN
ULC_FIND_LEFT  = wx.LIST_FIND_LEFT
ULC_FIND_RIGHT = wx.LIST_FIND_RIGHT

# Items/subitems rect
ULC_GETSUBITEMRECT_WHOLEITEM = wx.LIST_GETSUBITEMRECT_WHOLEITEM

# ----------------------------------------------------------------------------
# UltimateListCtrl event macros
# ----------------------------------------------------------------------------

wxEVT_COMMAND_LIST_BEGIN_DRAG = wx.wxEVT_COMMAND_LIST_BEGIN_DRAG
wxEVT_COMMAND_LIST_BEGIN_RDRAG = wx.wxEVT_COMMAND_LIST_BEGIN_RDRAG
wxEVT_COMMAND_LIST_BEGIN_LABEL_EDIT = wx.wxEVT_COMMAND_LIST_BEGIN_LABEL_EDIT
wxEVT_COMMAND_LIST_END_LABEL_EDIT = wx.wxEVT_COMMAND_LIST_END_LABEL_EDIT
wxEVT_COMMAND_LIST_DELETE_ITEM = wx.wxEVT_COMMAND_LIST_DELETE_ITEM
wxEVT_COMMAND_LIST_DELETE_ALL_ITEMS = wx.wxEVT_COMMAND_LIST_DELETE_ALL_ITEMS
wxEVT_COMMAND_LIST_ITEM_SELECTED = wx.wxEVT_COMMAND_LIST_ITEM_SELECTED
wxEVT_COMMAND_LIST_ITEM_DESELECTED = wx.wxEVT_COMMAND_LIST_ITEM_DESELECTED
wxEVT_COMMAND_LIST_KEY_DOWN = wx.wxEVT_COMMAND_LIST_KEY_DOWN
wxEVT_COMMAND_LIST_INSERT_ITEM = wx.wxEVT_COMMAND_LIST_INSERT_ITEM
wxEVT_COMMAND_LIST_COL_CLICK = wx.wxEVT_COMMAND_LIST_COL_CLICK
wxEVT_COMMAND_LIST_ITEM_RIGHT_CLICK = wx.wxEVT_COMMAND_LIST_ITEM_RIGHT_CLICK
wxEVT_COMMAND_LIST_ITEM_MIDDLE_CLICK = wx.wxEVT_COMMAND_LIST_ITEM_MIDDLE_CLICK
wxEVT_COMMAND_LIST_ITEM_ACTIVATED = wx.wxEVT_COMMAND_LIST_ITEM_ACTIVATED
wxEVT_COMMAND_LIST_CACHE_HINT = wx.wxEVT_COMMAND_LIST_CACHE_HINT
wxEVT_COMMAND_LIST_COL_RIGHT_CLICK = wx.wxEVT_COMMAND_LIST_COL_RIGHT_CLICK
wxEVT_COMMAND_LIST_COL_BEGIN_DRAG = wx.wxEVT_COMMAND_LIST_COL_BEGIN_DRAG
wxEVT_COMMAND_LIST_COL_DRAGGING = wx.wxEVT_COMMAND_LIST_COL_DRAGGING
wxEVT_COMMAND_LIST_COL_END_DRAG = wx.wxEVT_COMMAND_LIST_COL_END_DRAG
wxEVT_COMMAND_LIST_ITEM_FOCUSED = wx.wxEVT_COMMAND_LIST_ITEM_FOCUSED

wxEVT_COMMAND_LIST_FOOTER_CLICK = wx.NewEventType()
wxEVT_COMMAND_LIST_FOOTER_RIGHT_CLICK = wx.NewEventType()
wxEVT_COMMAND_LIST_FOOTER_CHECKING = wx.NewEventType()
wxEVT_COMMAND_LIST_FOOTER_CHECKED = wx.NewEventType()

wxEVT_COMMAND_LIST_ITEM_LEFT_CLICK = wx.NewEventType()
wxEVT_COMMAND_LIST_ITEM_CHECKING = wx.NewEventType()
wxEVT_COMMAND_LIST_ITEM_CHECKED = wx.NewEventType()
wxEVT_COMMAND_LIST_ITEM_HYPERLINK = wx.NewEventType()
wxEVT_COMMAND_LIST_END_DRAG = wx.NewEventType()
wxEVT_COMMAND_LIST_COL_CHECKING = wx.NewEventType()
wxEVT_COMMAND_LIST_COL_CHECKED = wx.NewEventType()

EVT_LIST_BEGIN_DRAG = wx.EVT_LIST_BEGIN_DRAG
EVT_LIST_BEGIN_RDRAG = wx.EVT_LIST_BEGIN_RDRAG
EVT_LIST_BEGIN_LABEL_EDIT = wx.EVT_LIST_BEGIN_LABEL_EDIT
EVT_LIST_END_LABEL_EDIT = wx.EVT_LIST_END_LABEL_EDIT
EVT_LIST_DELETE_ITEM = wx.EVT_LIST_DELETE_ITEM
EVT_LIST_DELETE_ALL_ITEMS = wx.EVT_LIST_DELETE_ALL_ITEMS
EVT_LIST_KEY_DOWN = wx.EVT_LIST_KEY_DOWN
EVT_LIST_INSERT_ITEM = wx.EVT_LIST_INSERT_ITEM
EVT_LIST_COL_CLICK = wx.EVT_LIST_COL_CLICK
EVT_LIST_COL_RIGHT_CLICK = wx.EVT_LIST_COL_RIGHT_CLICK
EVT_LIST_COL_BEGIN_DRAG = wx.EVT_LIST_COL_BEGIN_DRAG
EVT_LIST_COL_END_DRAG = wx.EVT_LIST_COL_END_DRAG
EVT_LIST_COL_DRAGGING = wx.EVT_LIST_COL_DRAGGING
EVT_LIST_ITEM_SELECTED = wx.EVT_LIST_ITEM_SELECTED
EVT_LIST_ITEM_DESELECTED = wx.EVT_LIST_ITEM_DESELECTED
EVT_LIST_ITEM_RIGHT_CLICK = wx.EVT_LIST_ITEM_RIGHT_CLICK
EVT_LIST_ITEM_MIDDLE_CLICK = wx.EVT_LIST_ITEM_MIDDLE_CLICK
EVT_LIST_ITEM_ACTIVATED = wx.EVT_LIST_ITEM_ACTIVATED
EVT_LIST_ITEM_FOCUSED = wx.EVT_LIST_ITEM_FOCUSED
EVT_LIST_CACHE_HINT = wx.EVT_LIST_CACHE_HINT

EVT_LIST_ITEM_LEFT_CLICK = wx.PyEventBinder(wxEVT_COMMAND_LIST_ITEM_LEFT_CLICK, 1)
EVT_LIST_ITEM_CHECKING = wx.PyEventBinder(wxEVT_COMMAND_LIST_ITEM_CHECKING, 1)
EVT_LIST_ITEM_CHECKED = wx.PyEventBinder(wxEVT_COMMAND_LIST_ITEM_CHECKED, 1)
EVT_LIST_ITEM_HYPERLINK = wx.PyEventBinder(wxEVT_COMMAND_LIST_ITEM_HYPERLINK, 1)
EVT_LIST_END_DRAG = wx.PyEventBinder(wxEVT_COMMAND_LIST_END_DRAG, 1)
EVT_LIST_COL_CHECKING = wx.PyEventBinder(wxEVT_COMMAND_LIST_COL_CHECKING, 1)
EVT_LIST_COL_CHECKED = wx.PyEventBinder(wxEVT_COMMAND_LIST_COL_CHECKED, 1)

EVT_LIST_FOOTER_CLICK = wx.PyEventBinder(wxEVT_COMMAND_LIST_FOOTER_CLICK, 1)
EVT_LIST_FOOTER_RIGHT_CLICK = wx.PyEventBinder(wxEVT_COMMAND_LIST_FOOTER_RIGHT_CLICK, 1)
EVT_LIST_FOOTER_CHECKING = wx.PyEventBinder(wxEVT_COMMAND_LIST_FOOTER_CHECKING, 1)
EVT_LIST_FOOTER_CHECKED = wx.PyEventBinder(wxEVT_COMMAND_LIST_FOOTER_CHECKED, 1)

# NOTE: If using the wxExtListBox visual attributes works everywhere then this can
# be removed, as well as the #else case below.

_USE_VISATTR = 0

# ----------------------------------------------------------------------------
# Constants
# ----------------------------------------------------------------------------

SCROLL_UNIT_X = 15
SCROLL_UNIT_Y = 15

# the spacing between the lines (in report mode)
LINE_SPACING = 0

# extra margins around the text label
EXTRA_WIDTH = 4
EXTRA_HEIGHT = 4

if wx.Platform == "__WXGTK__":
    EXTRA_HEIGHT = 6

# margin between the window and the items
EXTRA_BORDER_X = 2
EXTRA_BORDER_Y = 2

# offset for the header window
HEADER_OFFSET_X = 1
HEADER_OFFSET_Y = 1

# margin between rows of icons in [small] icon view
MARGIN_BETWEEN_ROWS = 6

# when autosizing the columns, add some slack
AUTOSIZE_COL_MARGIN = 10

# default and minimal widths for the header columns
WIDTH_COL_DEFAULT = 80
WIDTH_COL_MIN = 10

# the space between the image and the text in the report mode
IMAGE_MARGIN_IN_REPORT_MODE = 5

# the space between the image and the text in the report mode in header
HEADER_IMAGE_MARGIN_IN_REPORT_MODE = 2

# and the width of the icon, if any
MARGIN_BETWEEN_TEXT_AND_ICON = 2

# Background Image Style
_StyleTile = 0
_StyleStretch = 1

# Windows Vista Colours
_rgbSelectOuter = wx.Colour(170, 200, 245)
_rgbSelectInner = wx.Colour(230, 250, 250)
_rgbSelectTop = wx.Colour(210, 240, 250)
_rgbSelectBottom = wx.Colour(185, 215, 250)
_rgbNoFocusTop = wx.Colour(250, 250, 250)
_rgbNoFocusBottom = wx.Colour(235, 235, 235)
_rgbNoFocusOuter = wx.Colour(220, 220, 220)
_rgbNoFocusInner = wx.Colour(245, 245, 245)

# Mouse hover time for track selection
HOVER_TIME = 400
if wx.Platform == "__WXMSW__":
    try:
        import win32gui, win32con
        HOVER_TIME = win32gui.SystemParametersInfo(win32con.SPI_GETMOUSEHOVERTIME)
    except ImportError:
        pass

# For PyImageList
IL_FIXED_SIZE = 0
IL_VARIABLE_SIZE = 1

# Python integers, to make long types to work with CreateListItem
INTEGER_TYPES = [types.IntType, types.LongType]

# ----------------------------------------------------------------------------
# Functions
# ----------------------------------------------------------------------------

# Utility method

[docs]def to_list(input):
    """
    Converts the input data into a Python list.

    :param `input`: can be an integer or a Python list (in which case nothing will
     be done to `input`.
    """

    if isinstance(input, types.ListType):
        return input
    elif isinstance(input, types.IntType):
        return [input]
    else:
        raise Exception("Invalid parameter passed to `to_list`: only integers and list are accepted.")

[docs]def CheckVariableRowHeight(listCtrl, text):
    """
    Checks whether a `text` contains multiline strings and if the `listCtrl` window
    style is compatible with multiline strings.

    :param `listCtrl`: an instance of L{UltimateListCtrl};
    :param `text`: the text to analyze.
    """

    if not listCtrl.HasAGWFlag(ULC_HAS_VARIABLE_ROW_HEIGHT):
        if "\n" in text:
            raise Exception("Multiline text items are not allowed without the ULC_HAS_VARIABLE_ROW_HEIGHT style.")

[docs]def CreateListItem(itemOrId, col):
    """
    Creates a new instance of L{UltimateListItem}.

    :param `itemOrId`: can be an instance of L{UltimateListItem} or an integer;
    :param `col`: the item column.
    """

    if type(itemOrId) in INTEGER_TYPES:
        item = UltimateListItem()
        item._itemId = itemOrId
        item._col = col
    else:
        item = itemOrId

    return item

# ----------------------------------------------------------------------------

[docs]def MakeDisabledBitmap(original):
    """
    Creates a disabled-looking bitmap starting from the input one.

    :param `original`: an instance of `wx.Bitmap` to be greyed-out.
    """

    img = original.ConvertToImage()
    return wx.BitmapFromImage(img.ConvertToGreyscale())

# ----------------------------------------------------------------------------

#----------------------------------------------------------------------

[docs]def GetdragcursorData():
    """ Returns the drag and drop cursor image as a decompressed stream of characters. """

    return zlib.decompress(
"x\xda\xeb\x0c\xf0s\xe7\xe5\x92\xe2b``\xe0\xf5\xf4p\t\x02\xd2\xa2@,\xcf\xc1\
\x06$9z\xda>\x00)\xce\x02\x8f\xc8b\x06\x06na\x10fd\x985G\x02(\xd8W\xe2\x1aQ\
\xe2\x9c\x9f\x9b\x9b\x9aW\xc2\x90\xec\x11\xe4\xab\x90\x9cQ\x9a\x97\x9d\x93\
\x9a\xa7`l\xa4\x90\x99\x9e\x97_\x94\x9a\xc2\xeb\x18\xec\xec\xe9i\xa5\xa0\xa7\
W\xa5\xaa\x07\x01P:7\x1eH\xe4\xe8\xe9\xd9\x808\x11\xbc\x1e\xae\x11V\n\x06@`\
\xeehd\n\xa2-\x0c,\x8cA\xb4\x9b\t\x94o\xe2b\x08\xa2\xcd\\L\xdd@\xb4\xab\x85\
\x993\x886v\xb6p\x02\xd1\x86N\xa6\x16\x12\xf7~\xdf\x05\xbal\xa9\xa7\x8bcH\
\xc5\x9c3W9\xb9\x1a\x14\x04X/\xec\xfc\xbft\xed\x02\xa5\xf4\xc2m\xfa*<N\x17??\
\x0frqy\x9c\xd3\xb2f5\xaf\x89\x8f9Gk\xbc\x08\xa7\xbf\x06\x97\x98\x06S\xd8E\
\xbd\x9cE\xb2\x15\x9da\x89\xe2k\x0f\x9c\xb6|\x1a\xea\x14X\x1d6G\x83E\xe7\x9c\
\x1dO\xa8\xde\xb6\x84l\x15\x9eS\xcf\xc2tf\x15\xde\xf7\xb5\xb2]\xf0\x96+\xf5@\
D\x90\x1d\xef19_\xf5\xde5y\xb6+\xa7\xdeZ\xfbA\x9bu\x9f`\xffD\xafYn\xf6\x9eW\
\xeb>\xb6\x7f\x98\\U\xcb\xf5\xd5\xcb\x9a'\xe7\xf4\xd7\x0b\xba\x9e\xdb\x17E\
\xfdf\x97Z\xcb\xcc\xc0\xf0\xff?3\xc3\x92\xabN\x8arB\xc7\x8f\x03\x1d\xcc\xe0\
\xe9\xea\xe7\xb2\xce)\xa1\t\x00B7|\x00" )

[docs]def GetdragcursorBitmap():
    """ Returns the drag and drop cursor image as a `wx.Bitmap`. """

    return wx.BitmapFromImage(GetdragcursorImage())

[docs]def GetdragcursorImage():
    """ Returns the drag and drop cursor image as a `wx.Image`. """

    stream = cStringIO.StringIO(GetdragcursorData())
    return wx.ImageFromStream(stream)

#-----------------------------------------------------------------------------
#  PyImageList
#-----------------------------------------------------------------------------

[docs]class PyImageList(object):
    """
    A L{PyImageList} contains a list of images. Images can have masks for
    transparent drawing, and can be made from a variety of sources including
    bitmaps and icons.

    L{PyImageList} is used in conjunction with L{UltimateListCtrl}.

    :note: The main improvements that L{PyImageList} introduces is the removal
     of the limitation of same-size images inside the image list. If you use
     the style ``IL_VARIABLE_SIZE`` then each image can have any size (in terms
     of width and height).
    """

[docs]    def __init__(self, width, height, mask=True, initialCount=1, style=IL_VARIABLE_SIZE):
        """
        Default class constructor.

        :param `width`: the width of the images in the image list, in pixels (unused
         if you specify the ``IL_VARIABLE_SIZE`` style;
        :param `height`: the height of the images in the image list, in pixels (unused
         if you specify the ``IL_VARIABLE_SIZE`` style;
        :param `mask`: ``True`` if masks should be created for all images (unused in
         L{PyImageList});
        :param `initialCount`: the initial size of the list (unused in L{PyImageList});
        :param `style`: can be one of the following bits:

         ==================== ===== =================================
         Style Flag           Value Description
         ==================== ===== =================================
         ``IL_FIXED_SIZE``        0 All the images in L{PyImageList} have the same size (width, height)
         ``IL_VARIABLE_SIZE``     1 Each image can have any size (in terms of width and height)
         ==================== ===== =================================

        """

        self._width = width
        self._height = height
        self._mask = mask
        self._initialCount = 1
        self._style = style

        self._images = []

[docs]    def GetImageCount(self):
        """ Returns the number of images in the list. """

        return len(self._images)

[docs]    def Add(self, bitmap):
        """
        Adds a new image or images using a bitmap.

        :param `bitmap`: a valid `wx.Bitmap` object.

        :return: The new zero-based image index.

        :note: If the bitmap is wider than the images in the list and you are not using
         the ``IL_VARIABLE_SIZE`` style, then the bitmap will automatically be split
         into smaller images, each matching the dimensions of the image list.
        """

        index = len(self._images)

        # Mimic behavior of Windows ImageList_Add that automatically breaks up the added
        # bitmap into sub-images of the correct size

        if self._style & IL_FIXED_SIZE:

            if self._width > 0 and bitmap.GetWidth() > self._width and \
               bitmap.GetHeight() >= self._height:

                numImages = bitmap.GetWidth()/self._width
                for subIndex in xrange(numImages):
                    rect = wx.Rect(self._width * subIndex, 0, self._width, self._height)
                    tmpBmp = bitmap.GetSubBitmap(rect)
                    self._images.append(tmpBmp)

            else:

                self._images.append(bitmap)
        else:

            self._images.append(bitmap)

        if self._width == 0 and self._height == 0:
            self._width = bitmap.GetWidth()
            self._height = bitmap.GetHeight()

        return index

[docs]    def AddIcon(self, icon):
        """
        Adds a new image using an icon.

        :param `icon`: a valid `wx.Icon` object.

        :return: The new zero-based image index.

        :note: If the icon is wider than the images in the list and you are not using
         the ``IL_VARIABLE_SIZE`` style, then the icon will automatically be split
         into smaller images, each matching the dimensions of the image list.
        """

        return self.Add(wx.BitmapFromIcon(icon))

[docs]    def AddWithColourMask(self, bitmap, maskColour):
        """
        Adds a new image or images using a bitmap and a colour mask.

        :param `bitmap`: a valid `wx.Bitmap` object;
        :param `colour`: an instance of `wx.Colour`, a colour indicating which parts
         of the image are transparent.

        :return: The new zero-based image index.

        :note: If the bitmap is wider than the images in the list and you are not using
         the ``IL_VARIABLE_SIZE`` style, then the bitmap will automatically be split
         into smaller images, each matching the dimensions of the image list.
        """

        img = bitmap.ConvertToImage()
        img.SetMaskColour(maskColour.Red(), maskColour.Green(), maskColour.Blue())

        return self.Add(wx.BitmapFromImage(img))

[docs]    def GetBitmap(self, index):
        """
        Returns the bitmap corresponding to the given `index`, or `wx.NullBitmap`
        if the index is invalid.

        :param `index`: the bitmap index.
        """

        if index >= len(self._images):
            return wx.NullBitmap

        return self._images[index]

[docs]    def GetIcon(self, index):
        """
        Returns the icon corresponding to the given `index`, or `wx.NullIcon`
        if the index is invalid.

        :param `index`: the icon index.
        """

        if index >= len(self._images):
            return wx.NullIcon

        return wx.IconFromBitmap(self._images[index])

[docs]    def Replace(self, index, bitmap):
        """
        Replaces the existing image with the new bitmap.

        :param `index`: the index at which the image should be replaced;
        :param `bitmap`: the new bitmap to add to the image list, an instance of
         `wx.Bitmap`.
        """

        if index >= len(self._images):
            raise Exception("Wrong index in image list")

        self._images[index] = bitmap

        return True

[docs]    def ReplaceIcon(self, index, icon):
        """
        Replaces the existing image with the new icon.

        :param `index`: the index at which the image should be replaced;
        :param `icon`: the new icon to add to the image list, an instance of
         `wx.Icon`.
        """

        return self.Replace(index, wx.BitmapFromIcon(icon))

[docs]    def Remove(self, index):
        """
        Removes the image at the given position.

        :param `index`: the zero-based index of the image to be removed.
        """

        if index >= len(self._images):
            raise Exception("Wrong index in image list")

        self._images.pop(index)
        return True

[docs]    def RemoveAll(self):
        """ Removes all the images in the list. """

        self._images = []
        return True

[docs]    def GetSize(self, index):
        """
        Retrieves the size of an image in the list.

        :param `index`: the zero-based index of the image.

        :return: a tuple of `(width, height)` properties of the chosen bitmap.
        """

        if index >= len(self._images):
            raise Exception("Wrong index in image list")

        bmp = self._images[index]
        return bmp.GetWidth(), bmp.GetHeight()

[docs]    def Draw(self, index, dc, x, y, flags, solidBackground=True):
        """
        Draws a specified image onto a device context.

        :param `index`: the image index, starting from zero;
        :param `dc`: an instance of `wx.DC`;
        :param `x`: x position on the device context;
        :param `y`: y position on the device context;
        :param `flags`: how to draw the image. A bitlist of a selection of the following:

         ================================= =======================================
         Flag Paarameter                   Description
         ================================= =======================================
         ``wx.IMAGELIST_DRAW_NORMAL``      Draw the image normally
         ``wx.IMAGELIST_DRAW_TRANSPARENT`` Draw the image with transparency
         ``wx.IMAGELIST_DRAW_SELECTED``    Draw the image in selected state
         ``wx.IMAGELIST_DRAW_FOCUSED``     Draw the image in a focused state
         ================================= =======================================

        :param `solidBackground`: currently unused.
        """

        if index >= len(self._images):
            raise Exception("Wrong index in image list")

        bmp = self._images[index]
        dc.DrawBitmap(bmp, x, y, (flags & wx.IMAGELIST_DRAW_TRANSPARENT) > 0)

        return True

[docs]class SelectionStore(object):
    """
    SelectionStore is used to store the selected items in the virtual
    controls, i.e. it is well suited for storing even when the control contains
    a huge (practically infinite) number of items.

    Of course, internally it still has to store the selected items somehow (as
    an array currently) but the advantage is that it can handle the selection
    of all items (common operation) efficiently and that it could be made even
    smarter in the future (e.g. store the selections as an array of ranges +
    individual items) without changing its API.
    """

[docs]    def __init__(self):
        """ Default class constructor. """

        # the array of items whose selection state is different from default
        self._itemsSel = []
        # the default state: normally, False (i.e. off) but maybe set to true if
        # there are more selected items than non selected ones - this allows to
        # handle selection of all items efficiently
        self._defaultState = False
        # the total number of items we handle
        self._count  = 0

    # special case of SetItemCount(0)

[docs]    def Clear(self):
        """ Clears the number of selected items. """

        self._itemsSel = []
        self._count = 0
        self._defaultState = False

    # return the total number of selected items

[docs]    def GetSelectedCount(self):
        """ Return the total number of selected items. """

        return (self._defaultState and [self._count - len(self._itemsSel)] or [len(self._itemsSel)])[0]

[docs]    def IsSelected(self, item):
        """
        Returns ``True`` if the given item is selected.

        :param `item`: the item to check for selection state.
        """

        isSel = item in self._itemsSel

        # if the default state is to be selected, being in m_itemsSel means that
        # the item is not selected, so we have to inverse the logic
        return (self._defaultState and [not isSel] or [isSel])[0]

[docs]    def SelectItem(self, item, select=True):
        """
        Selects the given item.

        :param `item`: the item to select;
        :param `select`: ``True`` to select the item, ``False`` otherwise.

        :return: ``True`` if the items selection really changed.
        """

        # search for the item ourselves as like this we get the index where to
        # insert it later if needed, so we do only one search in the array instead
        # of two (adding item to a sorted array requires a search)
        index = bisect.bisect_right(self._itemsSel, item)
        isSel = index < len(self._itemsSel) and self._itemsSel[index] == item

        if select != self._defaultState:

            if item not in self._itemsSel:
                bisect.insort_right(self._itemsSel, item)
                return True

        else: # reset to default state

            if item in self._itemsSel:
                self._itemsSel.remove(item)
                return True

        return False

[docs]    def SelectRange(self, itemFrom, itemTo, select=True):
        """
        Selects a range of items.

        :param `itemFrom`: the first index of the selection range;
        :param `itemTo`: the last index of the selection range;
        :param `select`: ``True`` to select the items, ``False`` otherwise.

        :return: ``True`` and fill the `itemsChanged` array with the indices of items
         which have changed state if "few" of them did, otherwise return ``False``
         (meaning that too many items changed state to bother counting them individually).
        """

        # 100 is hardcoded but it shouldn't matter much: the important thing is
        # that we don't refresh everything when really few (e.g. 1 or 2) items
        # change state
        MANY_ITEMS = 100

        # many items (> half) changed state
        itemsChanged = []

        # are we going to have more [un]selected items than the other ones?
        if itemTo - itemFrom > self._count/2:

            if select != self._defaultState:

                # the default state now becomes the same as 'select'
                self._defaultState = select

                # so all the old selections (which had state select) shouldn't be
                # selected any more, but all the other ones should
                selOld = self._itemsSel[:]
                self._itemsSel = []

                # TODO: it should be possible to optimize the searches a bit
                #       knowing the possible range

                for item in xrange(itemFrom):
                    if item not in selOld:
                        self._itemsSel.append(item)

                for item in xrange(itemTo + 1, self._count):
                    if item not in selOld:
                        self._itemsSel.append(item)

            else: # select == self._defaultState

                # get the inclusive range of items between itemFrom and itemTo
                count = len(self._itemsSel)
                start = bisect.bisect_right(self._itemsSel, itemFrom)
                end = bisect.bisect_right(self._itemsSel, itemTo)

                if itemFrom < start:
                    start = itemFrom

                if start == count or self._itemsSel[start] < itemFrom:
                    start += 1

                if end == count or self._itemsSel[end] > itemTo:
                    end -= 1

                if start <= end:

                    # delete all of them (from end to avoid changing indices)
                    for i in xrange(end, start-1, -1):
                        if itemsChanged:
                            if len(itemsChanged) > MANY_ITEMS:
                                # stop counting (see comment below)
                                itemsChanged = []
                            else:
                                itemsChanged.append(self._itemsSel[i])

                        self._itemsSel.pop(i)
                else:
                    self._itemsSel = []

        else: # "few" items change state

            if itemsChanged:
                itemsChanged = []

            # just add the items to the selection
            for item in xrange(itemFrom, itemTo+1):
                if self.SelectItem(item, select) and itemsChanged:
                    itemsChanged.append(item)
                    if len(itemsChanged) > MANY_ITEMS:
                        # stop counting them, we'll just eat gobs of memory
                        # for nothing at all - faster to refresh everything in
                        # this case
                        itemsChanged = []

        # we set it to None if there are many items changing state
        return itemsChanged

[docs]    def OnItemDelete(self, item):
        """
        Must be called when an item is deleted.

        :param `item`: the item that is being deleted.
        """

        count = len(self._itemsSel)
        i = bisect.bisect_right(self._itemsSel, item)

        if i < count and self._itemsSel[i] == item:
            # this item itself was in m_itemsSel, remove it from there
            self._itemsSel.pop(i)

            count -= 1

        # and adjust the index of all which follow it
        while i < count:

            i += 1
            self._itemsSel[i] -= 1

[docs]    def SetItemCount(self, count):
        """
        Sets the total number of items we handle.

        :param `count`: the total number of items we handle.
        """

        # forget about all items whose indices are now invalid if the size
        # decreased
        if count < self._count:
            for i in xrange(len(self._itemsSel), 0, -1):
                if self._itemsSel[i - 1] >= count:
                    self._itemsSel.pop(i - 1)

        # remember the new number of items
        self._count = count

# ----------------------------------------------------------------------------
# UltimateListItemAttr: a structure containing the visual attributes of an item
# ----------------------------------------------------------------------------

[docs]class UltimateListItemAttr(object):
    """
    Represents the attributes (colour, font, ...) of a L{UltimateListCtrl}
    L{UltimateListItem}.
    """

[docs]    def __init__(self, colText=wx.NullColour, colBack=wx.NullColour, font=wx.NullFont,
                 enabled=True, footerColText=wx.NullColour, footerColBack=wx.NullColour,
                 footerFont=wx.NullFont):
        """
        Default class constructor.

        :param `colText`: the item text colour;
        :param `colBack`: the item background colour;
        :param `font`: the item font;
        :param `enabled`: ``True`` if the item should be enabled, ``False`` if it is disabled;
        :param `footerColText`: for footer items, the item text colour;
        :param `footerColBack`: for footer items, the item background colour;
        :param `footerFont`: for footer items, the item font.
        """

        self._colText = colText
        self._colBack = colBack
        self._font = font
        self._enabled = enabled

        self._footerColText = footerColText
        self._footerColBack = footerColBack
        self._footerFont = footerFont

    # setters

[docs]    def SetTextColour(self, colText):
        """
        Sets a new text colour.

        :param `colText`: an instance of `wx.Colour`.
        """

        self._colText = colText

[docs]    def SetBackgroundColour(self, colBack):
        """
        Sets a new background colour.

        :param `colBack`: an instance of `wx.Colour`.
        """

        self._colBack = colBack

[docs]    def SetFont(self, font):
        """
        Sets a new font for the item.

        :param `font`: an instance of `wx.Font`.
        """

        self._font = font

[docs]    def Enable(self, enable=True):
        """
        Enables or disables the item.

        :param `enable`: ``True`` to enable the item, ``False`` to disable it.
        """

        self._enabled = enable

[docs]    def SetFooterTextColour(self, colText):
        """
        Sets a new footer item text colour.

        :param `colText`: an instance of `wx.Colour`.
        """

        self._footerColText = colText

[docs]    def SetFooterBackgroundColour(self, colBack):
        """
        Sets a new footer item background colour.

        :param `colBack`: an instance of `wx.Colour`.
        """

        self._footerColBack = colBack

[docs]    def SetFooterFont(self, font):
        """
        Sets a new font for the footer item.

        :param `font`: an instance of `wx.Font`.
        """

        self._footerFont = font

    # accessors

[docs]    def HasTextColour(self):
        """ Returns ``True`` if the currently set text colour is valid. """

        return self._colText.Ok()

[docs]    def HasBackgroundColour(self):
        """ Returns ``True`` if the currently set background colour is valid. """

        return self._colBack.Ok()

[docs]    def HasFont(self):
        """ Returns ``True`` if the currently set font is valid. """

        return self._font.Ok()

[docs]    def HasFooterTextColour(self):
        """
        Returns ``True`` if the currently set text colour for the footer item
        is valid.
        """

        return self._footerColText.Ok()

[docs]    def HasFooterBackgroundColour(self):
        """
        Returns ``True`` if the currently set background colour for the footer item
        is valid.
        """

        return self._footerColBack.Ok()

[docs]    def HasFooterFont(self):
        """
        Returns ``True`` if the currently set font for the footer item
        is valid.
        """

        return self._footerFont.Ok()

    # getters

[docs]    def GetTextColour(self):
        """ Returns the currently set text colour. """

        return self._colText

[docs]    def GetBackgroundColour(self):
        """ Returns the currently set background colour. """

        return self._colBack

[docs]    def GetFont(self):
        """ Returns the currently set item font. """

        return self._font

[docs]    def GetFooterTextColour(self):
        """ Returns the currently set text colour for a footer item. """

        return self._footerColText

[docs]    def GetFooterBackgroundColour(self):
        """ Returns the currently set background colour for a footer item. """

        return self._footerColBack

[docs]    def GetFooterFont(self):
        """ Returns the currently set font for a footer item. """

        return self._footerFont

[docs]    def IsEnabled(self):
        """ Returns ``True`` if the item is enabled. """

        return self._enabled

# ----------------------------------------------------------------------------
# UltimateListItem: the item or column info, used to exchange data with UltimateListCtrl
# ----------------------------------------------------------------------------

[docs]class UltimateListItem(wx.Object):
    """ This class stores information about a L{UltimateListCtrl} item or column. """

[docs]    def __init__(self, item=None):
        """
        Default class constructor.

        :param `item`: if not ``None``, another instance of L{UltimateListItem}.
        """

        if not item:
            self.Init()
            self._attr = None
        else:
            self._mask = item._mask              # Indicates what fields are valid
            self._itemId = item._itemId          # The zero-based item position
            self._col = item._col                # Zero-based column, if in report mode
            self._state = item._state            # The state of the item
            self._stateMask = item._stateMask    # Which flags of self._state are valid (uses same flags)
            self._text = item._text              # The label/header text
            self._tooltip = item._tooltip        # The label/header tooltip text
            self._image = item._image[:]         # The zero-based indexes into an image list
            self._data = item._data              # App-defined data
            self._pyData = item._pyData          # Python-specific data
            self._format = item._format          # left, right, centre
            self._width = item._width            # width of column
            self._colour = item._colour          # item text colour
            self._font = item._font              # item font
            self._checked = item._checked        # The checking state for the item (if kind > 0)
            self._kind = item._kind              # Whether it is a normal, checkbox-like or a radiobutton-like item
            self._enabled = item._enabled        # Whether the item is enabled or not
            self._hypertext = item._hypertext    # indicates if the item is hypertext
            self._visited = item._visited        # visited state for an hypertext item
            self._wnd = item._wnd
            self._windowenabled = item._windowenabled
            self._windowsize = item._windowsize
            self._isColumnShown = item._isColumnShown
            self._customRenderer = item._customRenderer
            self._overFlow = item._overFlow
            self._footerChecked = item._footerChecked
            self._footerFormat = item._footerFormat
            self._footerImage = item._footerImage
            self._footerKind = item._footerKind
            self._footerText = item._footerText
            self._expandWin = item._expandWin
            self._attr = None

            # copy list item attributes
            if item.HasAttributes():
                self._attr = item.GetAttributes()[:]

    # resetting

[docs]    def Clear(self):
        """ Resets the item state to the default. """

        self.Init()
        self._text = ""
        self.ClearAttributes()

[docs]    def ClearAttributes(self):
        """ Deletes the item attributes if they have been stored. """

        if self._attr:
            del self._attr
            self._attr = None

    # setters

[docs]    def SetMask(self, mask):
        """
        Sets the mask of valid fields.

        :param `mask`: any combination of the following bits:

         ============================ ========= ==============================
         Mask Bits                    Hex Value Description
         ============================ ========= ==============================
         ``ULC_MASK_STATE``                 0x1 L{GetState} is valid
         ``ULC_MASK_TEXT``                  0x2 L{GetText} is valid
         ``ULC_MASK_IMAGE``                 0x4 L{GetImage} is valid
         ``ULC_MASK_DATA``                  0x8 L{GetData} is valid
         ``ULC_MASK_WIDTH``                0x20 L{GetWidth} is valid
         ``ULC_MASK_FORMAT``               0x40 L{GetFormat} is valid
         ``ULC_MASK_FONTCOLOUR``           0x80 L{GetTextColour} is valid
         ``ULC_MASK_FONT``                0x100 L{GetFont} is valid
         ``ULC_MASK_BACKCOLOUR``          0x200 L{GetBackgroundColour} is valid
         ``ULC_MASK_KIND``                0x400 L{GetKind} is valid
         ``ULC_MASK_ENABLE``              0x800 L{IsEnabled} is valid
         ``ULC_MASK_CHECK``              0x1000 L{IsChecked} is valid
         ``ULC_MASK_HYPERTEXT``          0x2000 L{IsHyperText} is valid
         ``ULC_MASK_WINDOW``             0x4000 L{GetWindow} is valid
         ``ULC_MASK_PYDATA``             0x8000 L{GetPyData} is valid
         ``ULC_MASK_SHOWN``             0x10000 L{IsShown} is valid
         ``ULC_MASK_RENDERER``          0x20000 L{GetCustomRenderer} is valid
         ``ULC_MASK_OVERFLOW``          0x40000 L{GetOverFlow} is valid
         ``ULC_MASK_FOOTER_TEXT``       0x80000 L{GetFooterText} is valid
         ``ULC_MASK_FOOTER_IMAGE``     0x100000 L{GetFooterImage} is valid
         ``ULC_MASK_FOOTER_FORMAT``    0x200000 L{GetFooterFormat} is valid
         ``ULC_MASK_FOOTER_FONT``      0x400000 L{GetFooterFont} is valid
         ``ULC_MASK_FOOTER_CHECK``     0x800000 L{IsFooterChecked} is valid
         ``ULC_MASK_FOOTER_KIND``     0x1000000 L{GetFooterKind} is valid
         ============================ ========= ==============================

        """

        self._mask = mask

[docs]    def SetId(self, id):
        """
        Sets the zero-based item position.

        :param `id`: the zero-based item position.
        """

        self._itemId = id

[docs]    def SetColumn(self, col):
        """
        Sets the zero-based column.

        :param `col`: the zero-based column.

        :note: This method is neaningful only in report mode.
        """

        self._col = col

[docs]    def SetState(self, state):
        """
        Sets the item state flags.

        :param `state`: any combination of the following bits:

         ============================ ========= ==============================
         State Bits                   Hex Value Description
         ============================ ========= ==============================
         ``ULC_STATE_DONTCARE``             0x0 Don't care what the state is
         ``ULC_STATE_DROPHILITED``          0x1 The item is highlighted to receive a drop event
         ``ULC_STATE_FOCUSED``              0x2 The item has the focus
         ``ULC_STATE_SELECTED``             0x4 The item is selected
         ``ULC_STATE_CUT``                  0x8 The item is in the cut state
         ``ULC_STATE_DISABLED``            0x10 The item is disabled
         ``ULC_STATE_FILTERED``            0x20 The item has been filtered
         ``ULC_STATE_INUSE``               0x40 The item is in use
         ``ULC_STATE_PICKED``              0x80 The item has been picked
         ``ULC_STATE_SOURCE``             0x100 The item is a drag and drop source
         ============================ ========= ==============================

        :note: The valid state flags are influenced by the value of the state mask.

        :see: L{SetStateMask}
        """

        self._mask |= ULC_MASK_STATE
        self._state = state
        self._stateMask |= state

[docs]    def SetStateMask(self, stateMask):
        """
        Sets the bitmask that is used to determine which of the state flags are
        to be set.

        :param `stateMask`: the state bitmask.

        :see: L{SetState} for a list of valid state bits.
        """

        self._stateMask = stateMask

[docs]    def SetText(self, text):
        """
        Sets the text label for the item.

        :param `text`: the text label for the item.
        """

        self._mask |= ULC_MASK_TEXT
        self._text = text

[docs]    def SetToolTip(self, text):
        """
        Sets the tooltip text for the item.

        :param `text`: the tooltip text for the item.
        """
        self._mask |= ULC_MASK_TOOLTIP
        self._tooltip = text

[docs]    def SetImage(self, image):
        """
        Sets the zero-based indexes of the images associated with the item into the
        image list.

        :param `image`: a Python list with the zero-based indexes of the images
         associated with the item into the image list.
        """

        self._mask |= ULC_MASK_IMAGE
        if image is None:
            image = []

        self._image = to_list(image)

[docs]    def SetData(self, data):
        """
        Sets client data for the item.

        :param `data`: the client data associated to the item.

        :note: Please note that client data is associated with the item and not
         with subitems.
        """

        self._mask |= ULC_MASK_DATA
        self._data = data

[docs]    def SetPyData(self, pyData):
        """
        Sets data for the item, which can be any Python object.

        :param `data`: any Python object associated to the item.

        :note: Please note that Python data is associated with the item and not
         with subitems.
        """

        self._mask |= ULC_MASK_PYDATA
        self._pyData = pyData

[docs]    def SetWidth(self, width):
        """
        Sets the column width.

        :param `width`: the column width.

        :note: This method is meaningful only for column headers in report mode.
        """

        self._mask |= ULC_MASK_WIDTH
        self._width = width

[docs]    def SetAlign(self, align):
        """
        Sets the alignment for the item.

        :param `align`: one of the following bits:

         ============================ ========= ==============================
         Alignment Bits               Hex Value Description
         ============================ ========= ==============================
         ``ULC_FORMAT_LEFT``                0x0 The item is left-aligned
         ``ULC_FORMAT_RIGHT``               0x1 The item is right-aligned
         ``ULC_FORMAT_CENTRE``              0x2 The item is centre-aligned
         ``ULC_FORMAT_CENTER``              0x2 The item is center-aligned
         ============================ ========= ==============================

        """

        self._mask |= ULC_MASK_FORMAT
        self._format = align

[docs]    def SetTextColour(self, colText):
        """
        Sets the text colour for the item.

        :param `colText`: a valid `wx.Colour` object.
        """

        self.Attributes().SetTextColour(colText)

[docs]    def SetBackgroundColour(self, colBack):
        """
        Sets the background colour for the item.

        :param `colBack`: a valid `wx.Colour` object.
        """

        self.Attributes().SetBackgroundColour(colBack)

[docs]    def SetFont(self, font):
        """
        Sets the font for the item.

        :param `font`: a valid `wx.Font` object.
        """

        self.Attributes().SetFont(font)

[docs]    def SetFooterTextColour(self, colText):
        """
        Sets the text colour for the footer item.

        :param `colText`: a valid `wx.Colour` object.
        """

        self.Attributes().SetFooterTextColour(colText)

[docs]    def SetFooterBackgroundColour(self, colBack):
        """
        Sets the background colour for the footer item.

        :param `colBack`: a valid `wx.Colour` object.
        """

        self.Attributes().SetFooterBackgroundColour(colBack)

[docs]    def SetFooterFont(self, font):
        """
        Sets the font for the footer item.

        :param `font`: a valid `wx.Font` object.
        """

        self.Attributes().SetFooterFont(font)

[docs]    def Enable(self, enable=True):
        """
        Enables or disables the item.

        :param `enable`: ``True`` to enable the item, ``False`` to disable it.
        """

        self.Attributes().Enable(enable)

    # accessors

[docs]    def GetMask(self):
        """
        Returns a bit mask indicating which fields of the structure are valid.

        :see: L{SetMask} for a list of valid bit masks.
        """

        return self._mask

[docs]    def GetId(self):
        """ Returns the zero-based item position. """

        return self._itemId

[docs]    def GetColumn(self):
        """
        Returns the zero-based column.

        :note: This method is meaningful only in report mode.
        """

        return self._col

[docs]    def GetFormat(self):
        """ Returns the header item format. """

        return self._format

[docs]    def GetState(self):
        """
        Returns a bit field representing the state of the item.

        :see: L{SetState} for a list of valid item states.
        """

        return self._state & self._stateMask

[docs]    def GetText(self):
        """ Returns the label/header text. """

        return self._text

[docs]    def GetToolTip(self):
        """ Returns the label/header tooltip. """

        return self._tooltip

[docs]    def GetImage(self):
        """
        Returns a Python list with the zero-based indexes of the images associated
        with the item into the image list.
        """

        return self._image

[docs]    def GetData(self):
        """
        Returns client data associated with the control.

        :note: Please note that client data is associated with the item and not
         with subitems.
        """

        return self._data

[docs]    def GetPyData(self):
        """
        Returns data for the item, which can be any Python object.

        :note: Please note that Python data is associated with the item and not
         with subitems.
        """

        return self._pyData

[docs]    def GetWidth(self):
        """
        Returns the column width.

        :note: This method is meaningful only for column headers in report mode.
        """

        return self._width

[docs]    def GetAlign(self):
        """
        Returns the alignment for the item.

        :see: L{SetAlign} for a list of valid alignment bits.
        """

        return self._format

[docs]    def GetAttributes(self):
        """ Returns the associated L{UltimateListItemAttr} attributes. """

        return self._attr

[docs]    def HasAttributes(self):
        """ Returns ``True`` if the item has attributes associated with it. """

        return self._attr != None

[docs]    def GetTextColour(self):
        """ Returns the text colour. """

        return (self.HasAttributes() and [self._attr.GetTextColour()] or [wx.NullColour])[0]

[docs]    def GetBackgroundColour(self):
        """ Returns the background colour. """

        return (self.HasAttributes() and [self._attr.GetBackgroundColour()] or [wx.NullColour])[0]

[docs]    def GetFont(self):
        """ Returns the item font. """

        return (self.HasAttributes() and [self._attr.GetFont()] or [wx.NullFont])[0]

[docs]    def IsEnabled(self):
        """ Returns ``True`` if the item is enabled. """

        return (self.HasAttributes() and [self._attr.IsEnabled()] or [True])[0]

    # creates self._attr if we don't have it yet

[docs]    def Attributes(self):
        """
        Returns the associated attributes if they exist, or create a new L{UltimateListItemAttr}
        structure and associate it with this item.
        """

        if not self._attr:
            self._attr = UltimateListItemAttr()

        return self._attr

[docs]    def SetKind(self, kind):
        """
        Sets the item kind.

        :param `kind`: may be one of the following integers:

         =============== ==========================
         Item Kind       Description
         =============== ==========================
                0        A normal item
                1        A checkbox-like item
                2        A radiobutton-type item
         =============== ==========================

        """

        self._mask |= ULC_MASK_KIND
        self._kind = kind

[docs]    def GetKind(self):
        """
        Returns the item kind.

        :see: L{SetKind} for a valid list of item's kind.
        """

        return self._kind

[docs]    def IsChecked(self):
        """ Returns whether the item is checked or not. """

        return self._checked

[docs]    def Check(self, checked=True):
        """
        Checks/unchecks an item.

        :param `checked`: ``True`` to check an item, ``False`` to uncheck it.

        :note: This method is meaningful only for check and radio items.
        """

        self._mask |= ULC_MASK_CHECK
        self._checked = checked

[docs]    def IsShown(self):
        """ Returns ``True`` if the item is shown, or ``False`` if it is hidden. """

        return self._isColumnShown

[docs]    def SetShown(self, shown=True):
        """
        Sets an item as shown/hidden.

        :param `shown`: ``True`` to show the item, ``False`` to hide it.
        """

        self._mask |= ULC_MASK_SHOWN
        self._isColumnShown = shown

[docs]    def SetHyperText(self, hyper=True):
        """
        Sets whether the item is hypertext or not.

        :param `hyper`: ``True`` to set hypertext behaviour, ``False`` otherwise.
        """

        self._mask |= ULC_MASK_HYPERTEXT
        self._hypertext = hyper

[docs]    def SetVisited(self, visited=True):
        """
        Sets whether an hypertext item was visited or not.

        :param `visited`: ``True`` to set a hypertext item as visited, ``False`` otherwise.
        """

        self._mask |= ULC_MASK_HYPERTEXT
        self._visited = visited

[docs]    def GetVisited(self):
        """ Returns whether an hypertext item was visited or not. """

        return self._visited

[docs]    def IsHyperText(self):
        """ Returns whether the item is hypetext or not. """

        return self._hypertext

[docs]    def SetWindow(self, wnd, expand=False):
        """
        Sets the window associated to the item.

        :param `wnd`: a non-toplevel window to be displayed next to the item;
        :param `expand`: ``True`` to expand the column where the item/subitem lives,
         so that the window will be fully visible.
        """

        self._mask |= ULC_MASK_WINDOW
        self._wnd = wnd

        listCtrl = wnd.GetParent()
        mainWin = listCtrl._mainWin

        wnd.Reparent(mainWin)

        if wnd.GetSizer():      # the window is a complex one hold by a sizer
            size = wnd.GetBestSize()
        else:                   # simple window, without sizers
            size = wnd.GetSize()

        # We have to bind the wx.EVT_SET_FOCUS for the associated window
        # No other solution to handle the focus changing from an item in
        # UltimateListCtrl and the window associated to an item
        # Do better strategies exist?
        self._wnd.Bind(wx.EVT_SET_FOCUS, self.OnSetFocus)
        self._windowsize = size

        # The window is enabled only if the item is enabled
        self._wnd.Enable(self._enabled)
        self._windowenabled = self._enabled
        self._expandWin = expand

        mainWin._hasWindows = True
        mainWin._itemWithWindow.append(self)

        # This is needed as otherwise widgets that should be invisible
        # are shown at the top left corner of ULC
        mainWin.HideWindows()
        mainWin.Refresh()

[docs]    def GetWindow(self):
        """ Returns the window associated to the item. """

        return self._wnd

[docs]    def DeleteWindow(self):
        """ Deletes the window associated to the item (if any). """

        if self._wnd:
            listCtrl = self._wnd.GetParent()
            if self in listCtrl._itemWithWindow:
                listCtrl._itemWithWindow.remove(self)
            self._wnd.Destroy()
            self._wnd = None

[docs]    def GetWindowEnabled(self):
        """ Returns whether the associated window is enabled or not. """

        if not self._wnd:
            raise Exception("\nERROR: This Item Has No Window Associated")

        return self._windowenabled

[docs]    def SetWindowEnabled(self, enable=True):
        """
        Sets whether the associated window is enabled or not.

        :param `enable`: ``True`` to enable the associated window, ``False`` to disable it.
        """

        if not self._wnd:
            raise Exception("\nERROR: This Item Has No Window Associated")

        self._windowenabled = enable
        self._wnd.Enable(enable)

[docs]    def GetWindowSize(self):
        """ Returns the associated window size. """

        return self._windowsize

[docs]    def SetCustomRenderer(self, renderer):
        """
        Associate a custom renderer to this item.

        :param `renderer`: a class able to correctly render the item.

        :note: the renderer class **must** implement the methods `DrawSubItem`,
         `GetLineHeight` and `GetSubItemWidth`.
        """

        self._mask |= ULC_MASK_RENDERER
        self._customRenderer = renderer

[docs]    def GetCustomRenderer(self):
        """ Returns the custom renderer associated with this item (if any). """

        return self._customRenderer

[docs]    def SetOverFlow(self, over=True):
        """
        Sets the item in the overflow/non overflow state.

        An item/subitem may overwrite neighboring items/subitems if its text would
        not normally fit in the space allotted to it.

        :param `over`: ``True`` to set the item in a overflow state, ``False`` otherwise.
        """

        self._mask |= ULC_MASK_OVERFLOW
        self._overFlow = over

[docs]    def GetOverFlow(self):
        """
        Returns if the item is in the overflow state.

        An item/subitem may overwrite neighboring items/subitems if its text would
        not normally fit in the space allotted to it.
        """

        return self._overFlow

[docs]    def Init(self):
        """ Initializes an empty L{UltimateListItem}. """

        self._mask = 0
        self._itemId = 0
        self._col = 0
        self._state = 0
        self._stateMask = 0
        self._image = []
        self._data = 0
        self._pyData = None
        self._text = ""
        self._tooltip = ""

        self._format = ULC_FORMAT_CENTRE
        self._width = 0

        self._colour = wx.Colour(0, 0, 0)
        self._font = wx.SystemSettings.GetFont(wx.SYS_DEFAULT_GUI_FONT)

        self._kind = 0
        self._checked = False
        self._enabled = True

        self._hypertext = False    # indicates if the item is hypertext
        self._visited = False      # visited state for an hypertext item

        self._wnd = None
        self._windowenabled = False
        self._windowsize = wx.Size()
        self._isColumnShown = True

        self._customRenderer = None
        self._overFlow = False
        self._footerChecked = False
        self._footerFormat = ULC_FORMAT_CENTRE
        self._footerImage = []
        self._footerKind = 0
        self._footerText = ""
        self._expandWin = False

[docs]    def SetFooterKind(self, kind):
        """
        Sets the footer item kind.

        :see: L{SetKind} for a list of valid items kind.
        """

        self._mask |= ULC_MASK_FOOTER_KIND
        self._footerKind = kind

[docs]    def GetFooterKind(self):
        """
        Returns the footer item kind.

        :see: L{SetKind} for a list of valid items kind.
        """

        return self._footerKind

[docs]    def IsFooterChecked(self):
        """ Returns whether the footer item is checked or not. """

        return self._footerChecked

[docs]    def CheckFooter(self, checked=True):
        """
        Checks/unchecks a footer item.

        :param `checked`: ``True`` to check an item, ``False`` to uncheck it.

        :note: This method is meaningful only for check and radio footer items.
        """

        self._mask |= ULC_MASK_FOOTER_CHECK
        self._footerChecked = checked

[docs]    def GetFooterFormat(self):
        """ Returns the footer item format. """

        return self._footerFormat

[docs]    def SetFooterFormat(self, format):
        """
        Sets the footer item format.

        :param `format`: the footer item format.
        """

        self._mask |= ULC_MASK_FOOTER_FORMAT
        self._footerFormat = format

[docs]    def GetFooterText(self):
        """ Returns the footer text. """

        return self._footerText

[docs]    def SetFooterText(self, text):
        """
        Sets the text label for the footer item.

        :param `text`: the text label for the footer item.
        """

        self._mask |= ULC_MASK_FOOTER_TEXT
        self._footerText = text

[docs]    def GetFooterImage(self):
        """
        Returns the zero-based index of the image associated with the footer item into
        the image list.
        """

        return self._footerImage

[docs]    def SetFooterImage(self, image):
        """
        Sets the zero-based index of the image associated with the footer item into the
        image list.

        :param `image`: the zero-based index of the image associated with the footer item
         into the image list.
        """

        self._mask |= ULC_MASK_FOOTER_IMAGE
        self._footerImage = to_list(image)

[docs]    def GetFooterTextColour(self):
        """ Returns the footer item text colour. """

        return (self.HasAttributes() and [self._attr.GetFooterTextColour()] or [wx.NullColour])[0]

[docs]    def GetFooterBackgroundColour(self):
        """ Returns the footer item background colour. """

        return (self.HasAttributes() and [self._attr.GetFooterBackgroundColour()] or [wx.NullColour])[0]

[docs]    def GetFooterFont(self):
        """ Returns the footer item font. """

        return (self.HasAttributes() and [self._attr.GetFooterFont()] or [wx.NullFont])[0]

[docs]    def SetFooterAlign(self, align):
        """
        Sets the alignment for the footer item.

        :see: L{SetAlign} for a list of valid alignment flags.
        """

        self._mask |= ULC_MASK_FOOTER_FORMAT
        self._footerFormat = align

[docs]    def GetFooterAlign(self):
        """
        Returns the alignment for the footer item.

        :see: L{SetAlign} for a list of valid alignment flags.
        """

        return self._footerFormat

[docs]    def OnSetFocus(self, event):
        """
        Handles the ``wx.EVT_SET_FOCUS`` event for the window associated to an item.

        :param `event`: a `wx.FocusEvent` event to be processed.
        """

        listCtrl = self._wnd.GetParent()
        select = listCtrl.GetItemState(self._itemId, ULC_STATE_SELECTED)

        # If the window is associated to an item that currently is selected
        # (has focus) we don't kill the focus. Otherwise we do it.
        if not select:
            listCtrl._hasFocus = False
        else:
            listCtrl._hasFocus = True

        listCtrl.SetFocus()

        event.Skip()

# ----------------------------------------------------------------------------
# ListEvent - the event class for the UltimateListCtrl notifications
# ----------------------------------------------------------------------------

[docs]class CommandListEvent(wx.PyCommandEvent):
    """
    A list event holds information about events associated with L{UltimateListCtrl}
    objects.
    """

[docs]    def __init__(self, commandTypeOrEvent=None, winid=0):
        """
        Default class constructor.
        For internal use: do not call it in your code!

        :param `commandTypeOrEvent`: the event type or another instance of
         `wx.PyCommandEvent`;
        :param `winid`: the event identifier.
        """

        if type(commandTypeOrEvent) == types.IntType:

            wx.PyCommandEvent.__init__(self, commandTypeOrEvent, winid)

            self.m_code = 0
            self.m_oldItemIndex = 0
            self.m_itemIndex = 0
            self.m_col = 0
            self.m_pointDrag = wx.Point()
            self.m_item = UltimateListItem()
            self.m_editCancelled = False

        else:

            wx.PyCommandEvent.__init__(self, commandTypeOrEvent.GetEventType(), commandTypeOrEvent.GetId())
            self.m_code = commandTypeOrEvent.m_code
            self.m_oldItemIndex = commandTypeOrEvent.m_oldItemIndex
            self.m_itemIndex = commandTypeOrEvent.m_itemIndex
            self.m_col = commandTypeOrEvent.m_col
            self.m_pointDrag = commandTypeOrEvent.m_pointDrag
            self.m_item = commandTypeOrEvent.m_item
            self.m_editCancelled = commandTypeOrEvent.m_editCancelled

[docs]    def GetKeyCode(self):
        """ Returns the key code if the event is a keypress event. """

        return self.m_code

[docs]    def GetIndex(self):
        """ Returns the item index. """

        return self.m_itemIndex

[docs]    def GetColumn(self):
        """
        Returns the column position: it is only used with ``COL`` events.

        For the column dragging events, it is the column to the left of the divider
        being dragged, for the column click events it may be -1 if the user clicked
        in the list control header outside any column.
        """

        return self.m_col

[docs]    def GetPoint(self):
        """ Returns the position of the mouse pointer if the event is a drag event. """

        return self.m_pointDrag

[docs]    def GetLabel(self):
        """ Returns the (new) item label for ``EVT_LIST_END_LABEL_EDIT`` event. """

        return self.m_item._text

[docs]    def GetText(self):
        """ Returns the item text. """

        return self.m_item._text

[docs]    def GetImage(self):
        """ Returns the item image. """

        return self.m_item._image

[docs]    def GetData(self):
        """ Returns the item data. """

        return self.m_item._data

[docs]    def GetMask(self):
        """ Returns the item mask. """

        return self.m_item._mask

[docs]    def GetItem(self):
        """ Returns the item itself. """

        return self.m_item

    # for wxEVT_COMMAND_LIST_CACHE_HINT only

[docs]    def GetCacheFrom(self):
        """
        Returns the first item which the list control advises us to cache.

        :note: This method is meaningful for ``EVT_LIST_CACHE_HINT`` event only.
        """

        return self.m_oldItemIndex

[docs]    def GetCacheTo(self):
        """
        Returns the last item (inclusive) which the list control advises us to cache.

        :note: This method is meaningful for ``EVT_LIST_CACHE_HINT`` event only.
        """

        return self.m_itemIndex

    # was label editing canceled? (for wxEVT_COMMAND_LIST_END_LABEL_EDIT only)

[docs]    def IsEditCancelled(self):
        """
        Returns ``True`` if it the label editing has been cancelled by the user
        (L{GetLabel} returns an empty string in this case but it doesn't allow
        the application to distinguish between really cancelling the edit and
        the admittedly rare case when the user wants to rename it to an empty
        string).

        :note: This method only makes sense for ``EVT_LIST_END_LABEL_EDIT`` messages.
        """

        return self.m_editCancelled

[docs]    def SetEditCanceled(self, editCancelled):
        """
        Sets the item editing as cancelled/not cancelled.

        :param `editCancelled`: ``True`` to set the item editing as cancelled, ``False``
         otherwise.

        :note: This method only makes sense for ``EVT_LIST_END_LABEL_EDIT`` messages.
        """

        self.m_editCancelled = editCancelled

# ----------------------------------------------------------------------------
# UltimateListEvent is a special class for all events associated with list controls
#
# NB: note that not all accessors make sense for all events, see the event
#     descriptions below
# ----------------------------------------------------------------------------

[docs]class UltimateListEvent(CommandListEvent):
    """
    A list event holds information about events associated with L{UltimateListCtrl}
    objects.
    """

[docs]    def __init__(self, commandTypeOrEvent=None, winid=0):
        """
        Default class constructor.
        For internal use: do not call it in your code!

        :param `commandTypeOrEvent`: the event type or another instance of
         `wx.PyCommandEvent`;
        :param `winid`: the event identifier.
        """

        CommandListEvent.__init__(self, commandTypeOrEvent, winid)

        if type(commandTypeOrEvent) == types.IntType:
            self.notify = wx.NotifyEvent(commandTypeOrEvent, winid)
        else:
            self.notify = wx.NotifyEvent(commandTypeOrEvent.GetEventType(), commandTypeOrEvent.GetId())

[docs]    def GetNotifyEvent(self):
        """ Returns the actual `wx.NotifyEvent`. """

        return self.notify

[docs]    def IsAllowed(self):
        """
        Returns ``True`` if the change is allowed (L{Veto} hasn't been called) or
        ``False`` otherwise (if it was).
        """

        return self.notify.IsAllowed()

[docs]    def Veto(self):
        """
        Prevents the change announced by this event from happening.

        :note: It is in general a good idea to notify the user about the reasons
         for vetoing the change because otherwise the applications behaviour (which
         just refuses to do what the user wants) might be quite surprising.
        """

        self.notify.Veto()

[docs]    def Allow(self):
        """
        This is the opposite of L{Veto}: it explicitly allows the event to be processed.
        For most events it is not necessary to call this method as the events are
        allowed anyhow but some are forbidden by default (this will be mentioned
        in the corresponding event description).
        """

        self.notify.Allow()

# ============================================================================
# private classes
# ============================================================================

#-----------------------------------------------------------------------------
#  ColWidthInfo (internal)
#-----------------------------------------------------------------------------

[docs]class ColWidthInfo(object):
    """ A simple class which holds information about L{UltimateListCtrl} columns. """

[docs]    def __init__(self, w=0, needsUpdate=True):
        """
        Default class constructor

        :param `w`: the initial width of the column;
        :param `needsUpdate`: ``True`` if the column needs refreshing, ``False``
         otherwise.
        """

        self._nMaxWidth = w
        self._bNeedsUpdate = needsUpdate

#-----------------------------------------------------------------------------
#  UltimateListItemData (internal)
#-----------------------------------------------------------------------------

[docs]class UltimateListItemData(object):
    """
    A simple class which holds information about L{UltimateListItem} visual
    attributes (client rectangles, positions, etc...).
    """

[docs]    def __init__(self, owner):
        """
        Default class constructor

        :param `owner`: an instance of L{UltimateListCtrl}.
        """

        # the list ctrl we are in
        self._owner = owner
        self.Init()

        # the item coordinates are not used in report mode, instead this pointer
        # is None and the owner window is used to retrieve the item position and
        # size

        if owner.InReportView():
            self._rect = None
        else:
            self._rect = wx.Rect()

[docs]    def SetImage(self, image):
        """
        Sets the zero-based indexes of the images associated with the item into the
        image list.

        :param `image`: a Python list with the zero-based indexes of the images
         associated with the item into the image list.
        """

        self._image = to_list(image)

[docs]    def SetData(self, data):
        """
        Sets client data for the item.

        :param `data`: the client data associated to the item.

        :note: Please note that client data is associated with the item and not
         with subitems.
        """

        self._data = data

[docs]    def HasText(self):
        """ Returns ``True`` if the item text is not the empty string. """

        return self._text != ""

[docs]    def GetText(self):
        """ Returns the item text. """

        return self._text

[docs]    def GetToolTip(self):
        """ Returns the item tooltip. """

        return self._tooltip

[docs]    def GetBackgroundColour(self):
        """ Returns the currently set background colour. """

        return self._backColour

[docs]    def GetColour(self):
        """ Returns the currently set text colour. """

        return self._colour

[docs]    def GetFont(self):
        """ Returns the currently set font. """

        return (self._hasFont and [self._font] or [wx.NullFont])[0]

[docs]    def SetText(self, text):
        """
        Sets the text label for the item.

        :param `text`: the text label for the item.
        """

        self._text = text

[docs]    def SetToolTip(self, tooltip):
        """
        Sets the tooltip for the item

        :param `tooltip`: the tooltip text
        """

        self._tooltip = tooltip

[docs]    def SetColour(self, colour):
        """
        Sets the text colour for the item.

        :param `colour`: an instance of `wx.Colour`.
        """

        if colour == wx.NullColour or colour == None:
            if self._hasColour:
                self._hasColour = False
                del self._colour
            return

        self._hasColour = True
        self._colour = colour

[docs]    def SetFont(self, font):
        """
        Sets the text font for the item.

        :param `font`: an instance of `wx.Font`.
        """

        if font == wx.NullFont:
            self._hasFont = False
            del self._font
            return

        self._hasFont = True
        self._font = font

[docs]    def SetBackgroundColour(self, colour):
        """
        Sets the background colour for the item.

        :param `colour`: an instance of `wx.Colour`.
        """

        if colour == wx.NullColour:
            self._hasBackColour = False
            del self._backColour
            return

        self._hasBackColour = True
        self._backColour = colour

    # we can't use empty string for measuring the string width/height, so
    # always return something

[docs]    def GetTextForMeasuring(self):
        """
        Returns the item text or a simple string if the item text is the
        empty string.
        """

        s = self.GetText()
        if not s.strip():
            s = 'H'

        return s

[docs]    def GetImage(self):
        """
        Returns a Python list with the zero-based indexes of the images associated
        with the item into the image list.
        """

        return self._image

[docs]    def HasImage(self):
        """ Returns ``True`` if the item has at least one image associated with it. """

        return len(self._image) > 0

[docs]    def SetKind(self, kind):
        """
        Sets the item kind.

        :param `kind`: may be one of the following integers:

         =============== ==========================
         Item Kind       Description
         =============== ==========================
                0        A normal item
                1        A checkbox-like item
                2        A radiobutton-type item
         =============== ==========================

        """

        self._kind = kind

[docs]    def GetKind(self):
        """
        Returns the item kind.

        :see: L{SetKind} for a list of valid item kinds.
        """

        return self._kind

[docs]    def IsChecked(self):
        """ Returns whether the item is checked or not. """

        return self._checked

[docs]    def Check(self, checked=True):
        """
        Checks/unchecks an item.

        :param `checked`: ``True`` to check an item, ``False`` to uncheck it.

        :note: This method is meaningful only for check and radio items.
        """

        self._checked = checked

[docs]    def SetHyperText(self, hyper=True):
        """
        Sets whether the item is hypertext or not.

        :param `hyper`: ``True`` to set hypertext behaviour, ``False`` otherwise.
        """

        self._hypertext = hyper

[docs]    def SetVisited(self, visited=True):
        """
        Sets whether an hypertext item was visited or not.

        :param `visited`: ``True`` to set a hypertext item as visited, ``False`` otherwise.
        """

        self._visited = visited

[docs]    def GetVisited(self):
        """Returns whether an hypertext item was visited or not."""

        return self._visited

[docs]    def IsHyperText(self):
        """Returns whether the item is hypetext or not."""

        return self._hypertext

[docs]    def SetWindow(self, wnd, expand=False):
        """
        Sets the window associated to the item.

        :param `wnd`: a non-toplevel window to be displayed next to the item;
        :param `expand`: ``True`` to expand the column where the item/subitem lives,
         so that the window will be fully visible.
        """

        self._mask |= ULC_MASK_WINDOW
        self._wnd = wnd

        if wnd.GetSizer():      # the window is a complex one hold by a sizer
            size = wnd.GetBestSize()
        else:                   # simple window, without sizers
            size = wnd.GetSize()

        # We have to bind the wx.EVT_SET_FOCUS for the associated window
        # No other solution to handle the focus changing from an item in
        # UltimateListCtrl and the window associated to an item
        # Do better strategies exist?
        self._windowsize = size

        # The window is enabled only if the item is enabled
        self._wnd.Enable(self._enabled)
        self._windowenabled = self._enabled
        self._expandWin = expand

[docs]    def GetWindow(self):
        """ Returns the window associated to the item. """

        return self._wnd

[docs]    def DeleteWindow(self):
        """ Deletes the window associated to the item (if any). """

        if self._wnd:
            self._wnd.Destroy()
            self._wnd = None

[docs]    def GetWindowEnabled(self):
        """ Returns whether the associated window is enabled or not. """

        if not self._wnd:
            raise Exception("\nERROR: This Item Has No Window Associated")

        return self._windowenabled

[docs]    def SetWindowEnabled(self, enable=True):
        """
        Sets whether the associated window is enabled or not.

        :param `enable`: ``True`` to enable the associated window, ``False`` to disable it.
        """

        if not self._wnd:
            raise Exception("\nERROR: This Item Has No Window Associated")

        self._windowenabled = enable
        self._wnd.Enable(enable)

[docs]    def GetWindowSize(self):
        """ Returns the associated window size. """

        return self._windowsize

[docs]    def SetAttr(self, attr):
        """
        Sets the item attributes.

        :param `attr`: an instance of L{UltimateListItemAttr}.
        """

        self._attr = attr

[docs]    def GetAttr(self):
        """ Returns the item attributes. """

        return self._attr

[docs]    def HasColour(self):
        """ Returns ``True`` if the currently set text colour is valid. """

        return self._hasColour

[docs]    def HasFont(self):
        """ Returns ``True`` if the currently set font is valid. """

        return self._hasFont

[docs]    def HasBackgroundColour(self):
        """ Returns ``True`` if the currently set background colour is valid. """

        return self._hasBackColour

[docs]    def SetCustomRenderer(self, renderer):
        """
        Associate a custom renderer to this item.

        :param `renderer`: a class able to correctly render the item.

        :note: the renderer class **must** implement the methods `DrawSubItem`,
         `GetLineHeight` and `GetSubItemWidth`.
        """

        self._mask |= ULC_MASK_RENDERER
        self._customRenderer = renderer

[docs]    def GetCustomRenderer(self):
        """ Returns the custom renderer associated with this item (if any). """

        return self._customRenderer

[docs]    def SetOverFlow(self, over=True):
        """
        Sets the item in the overflow/non overflow state.

        An item/subitem may overwrite neighboring items/subitems if its text would
        not normally fit in the space allotted to it.

        :param `over`: ``True`` to set the item in a overflow state, ``False`` otherwise.
        """

        self._mask |= ULC_MASK_OVERFLOW
        self._overFlow = over

[docs]    def GetOverFlow(self):
        """
        Returns if the item is in the overflow state.

        An item/subitem may overwrite neighboring items/subitems if its text would
        not normally fit in the space allotted to it.
        """

        return self._overFlow

[docs]    def Init(self):
        """ Initializes the item data structure. """

        # the item image or -1
        self._image = []
        # user data associated with the item
        self._data = 0
        self._pyData = None
        self._colour = wx.Colour(0, 0, 0)
        self._hasColour = False
        self._hasFont = False
        self._hasBackColour = False
        self._text = ""
        self._tooltip = ""

        # kind = 0: normal item
        # kind = 1: checkbox-type item
        self._kind = 0
        self._checked = False

        self._enabled = True

        # custom attributes or None
        self._attr = None

        self._hypertext = False
        self._visited = False

        self._wnd = None
        self._windowenabled = True
        self._windowsize = wx.Size()
        self._isColumnShown = True
        self._customRenderer = None
        self._overFlow = False
        self._expandWin = False

[docs]    def SetItem(self, info):
        """
        Sets information about the item.

        :param `info`: an instance of L{UltimateListItemData}.
        """

        if info._mask & ULC_MASK_TEXT:
            CheckVariableRowHeight(self._owner, info._text)
            self.SetText(info._text)

        if info._mask & ULC_MASK_TOOLTIP:
            self.SetToolTip(info._tooltip)

        if info._mask & ULC_MASK_KIND:
            self._kind = info._kind

        if info._mask & ULC_MASK_CHECK:
            self._checked = info._checked

        if info._mask & ULC_MASK_ENABLE:
            self._enabled = info._enabled

        if info._mask & ULC_MASK_IMAGE:
            self._image = info._image[:]

        if info._mask & ULC_MASK_DATA:
            self._data = info._data

        if info._mask & ULC_MASK_PYDATA:
            self._pyData = info._pyData

        if info._mask & ULC_MASK_HYPERTEXT:
            self._hypertext = info._hypertext
            self._visited = info._visited

        if info._mask & ULC_MASK_FONTCOLOUR:
            self.SetColour(info.GetTextColour())

        if info._mask & ULC_MASK_FONT:
            self.SetFont(info.GetFont())

        if info._mask & ULC_MASK_BACKCOLOUR:
            self.SetBackgroundColour(info.GetBackgroundColour())

        if info._mask & ULC_MASK_WINDOW:
            self._wnd = info._wnd
            self._windowenabled = info._windowenabled
            self._windowsize = info._windowsize
            self._expandWin = info._expandWin

        if info._mask & ULC_MASK_SHOWN:
            self._isColumnShown = info._isColumnShown

        if info._mask & ULC_MASK_RENDERER:
            self._customRenderer = info._customRenderer

        if info._mask & ULC_MASK_OVERFLOW:
            self._overFlow = info._overFlow

        if info.HasAttributes():

            if self._attr:
                self._attr = info.GetAttributes()
            else:
                self._attr = UltimateListItemAttr(info.GetTextColour(), info.GetBackgroundColour(),
                                                  info.GetFont(), info.IsEnabled(), info.GetFooterTextColour(),
                                                  info.GetFooterBackgroundColour(), info.GetFooterFont())

        if self._rect:

            self._rect.x = -1
            self._rect.y = -1
            self._rect.height = 0
            self._rect.width = info._width

[docs]    def SetPosition(self, x, y):
        """
        Sets the item position.

        :param `x`: the item `x` position;
        :param `y`: the item `y` position.
        """

        self._rect.x = x
        self._rect.y = y

[docs]    def SetSize(self, width, height):
        """
        Sets the item size.

        :param `width`: the item width, in pixels;
        :param `height`: the item height, in pixels.
        """

        if width != -1:
            self._rect.width = width
        if height != -1:
            self._rect.height = height

[docs]    def IsHit(self, x, y):
        """
        Returns ``True`` if the input position is inside the item client rectangle.

        :param `x`: the `x` mouse position;
        :param `y`: the `y` mouse position.
        """

        return wx.Rect(self.GetX(), self.GetY(), self.GetWidth(), self.GetHeight()).Contains((x, y))

[docs]    def GetX(self):
        """ Returns the item `x` position. """

        return self._rect.x

[docs]    def GetY(self):
        """ Returns the item `y` position. """

        return self._rect.y

[docs]    def GetWidth(self):
        """ Returns the item width, in pixels. """

        return self._rect.width

[docs]    def GetHeight(self):
        """ Returns the item height, in pixels. """

        return self._rect.height

[docs]    def GetItem(self, info):
        """
        Returns information about the item.

        :param `info`: an instance of L{UltimateListItemData}.
        """

        mask = info._mask
        if not mask:
            # by default, get everything for backwards compatibility
            mask = -1

        if mask & ULC_MASK_TEXT:
            info._text = self._text
        if mask & ULC_MASK_TOOLTIP:
            info._tooltip = self._tooltip
        if mask & ULC_MASK_IMAGE:
            info._image = self._image[:]
        if mask & ULC_MASK_DATA:
            info._data = self._data
        if mask & ULC_MASK_PYDATA:
            info._pyData = self._pyData
        if info._mask & ULC_MASK_FONT:
            info.SetFont(self.GetFont())
        if mask & ULC_MASK_KIND:
            info._kind = self._kind
        if mask & ULC_MASK_CHECK:
            info._checked = self._checked
        if mask & ULC_MASK_ENABLE:
            info._enabled = self._enabled
        if mask & ULC_MASK_HYPERTEXT:
            info._hypertext = self._hypertext
            info._visited = self._visited
        if mask & ULC_MASK_WINDOW:
            info._wnd = self._wnd
            info._windowenabled = self._windowenabled
            info._windowsize = self._windowsize
            info._expandWin = self._expandWin
        if mask & ULC_MASK_SHOWN:
            info._isColumnShown = self._isColumnShown
        if mask & ULC_MASK_RENDERER:
            info._customRenderer = self._customRenderer
        if mask & ULC_MASK_OVERFLOW:
            info._overFlow = self._overFlow

        if self._attr:

            if self._attr.HasTextColour():
                info.SetTextColour(self._attr.GetTextColour())
            if self._attr.HasBackgroundColour():
                info.SetBackgroundColour(self._attr.GetBackgroundColour())
            if self._attr.HasFont():
                info.SetFont(self._attr.GetFont())
            info.Enable(self._attr.IsEnabled())

        return info

[docs]    def IsEnabled(self):
        """ Returns ``True`` if the item is enabled, ``False`` if it is disabled. """

        return self._enabled

[docs]    def Enable(self, enable=True):
        """
        Enables or disables the item.

        :param `enable`: ``True`` to enable the item, ``False`` to disable it.
        """

        self._enabled = enable

#-----------------------------------------------------------------------------
#  UltimateListHeaderData (internal)
#-----------------------------------------------------------------------------

[docs]class UltimateListHeaderData(object):
    """
    A simple class which holds information about L{UltimateListItem} visual
    attributes for the header/footer items (client rectangles, positions, etc...).
    """

[docs]    def __init__(self, item=None):
        """
        Default class constructor.

        :param `item`: another instance of L{UltimateListHeaderData}.
        """

        self.Init()

        if item:
            self.SetItem(item)

[docs]    def HasText(self):
        """ Returns ``True`` if the currently set text colour is valid. """

        return self._text != ""

[docs]    def GetText(self):
        """ Returns the header/footer item text. """

        return self._text

[docs]    def GetToolTip(self):
        """ Returns the header/footer item tooltip. """

        return self._tooltip

[docs]    def SetText(self, text):
        """
        Sets the header/footer item text.

        :param `text`: the new header/footer text.
        """

        self._text = text

[docs]    def SetToolTip(self, tip):
        """
        Sets the header/footer item tooltip.

        :param `tip`: the new header/footer tooltip.
        """

        self._tip = tip

[docs]    def GetFont(self):
        """ Returns the header/footer item font. """

        return self._font

[docs]    def Init(self):
        """ Initializes the header/footer item. """

        self._mask = 0
        self._image = []
        self._format = 0
        self._width = 0
        self._xpos = 0
        self._ypos = 0
        self._height = 0
        self._text = ""
        self._tooltip = ""
        self._kind = 0
        self._checked = False
        self._font = wx.NullFont
        self._state = 0
        self._isColumnShown = True
        self._customRenderer = None

        self._footerImage = []
        self._footerFormat = 0
        self._footerText = ""
        self._footerKind = 0
        self._footerChecked = False
        self._footerFont = wx.NullFont

[docs]    def SetItem(self, item):
        """
        Sets information about the header/footer item.

        :param `info`: an instance of L{UltimateListHeaderData}.
        """

        self._mask = item._mask

        if self._mask & ULC_MASK_TEXT:
            self._text = item._text

        if self._mask & ULC_MASK_TOOLTIP:
            self._tooltip = item._tooltip

        if self._mask & ULC_MASK_FOOTER_TEXT:
            self._footerText = item._footerText

        if self._mask & ULC_MASK_IMAGE:
            self._image = item._image[:]

        if self._mask & ULC_MASK_FOOTER_IMAGE:
            self._footerImage = item._footerImage[:]

        if self._mask & ULC_MASK_FORMAT:
            self._format = item._format

        if self._mask & ULC_MASK_FOOTER_FORMAT:
            self._footerFormat = item._footerFormat

        if self._mask & ULC_MASK_WIDTH:
            self.SetWidth(item._width)

        if self._mask & ULC_MASK_FONT:
            self._font = item._font

        if self._mask & ULC_MASK_FOOTER_FONT:
            self._footerFont = item._footerFont

        if self._mask & ULC_MASK_FOOTER_KIND:
            self._footerKind = item._footerKind
            self._footerChecked = item._footerChecked

        if self._mask & ULC_MASK_KIND:
            self._kind = item._kind
            self._checked = item._checked

        if self._mask & ULC_MASK_CHECK:
            self._kind = item._kind
            self._checked = item._checked

        if self._mask & ULC_MASK_FOOTER_CHECK:
            self._footerKind = item._footerKind
            self._footerChecked = item._footerChecked

        if self._mask & ULC_MASK_STATE:
            self.SetState(item._state)

        if self._mask & ULC_MASK_SHOWN:
            self._isColumnShown = item._isColumnShown

        if self._mask & ULC_MASK_RENDERER:
            self._customRenderer = item._customRenderer

[docs]    def SetState(self, flag):
        """
        Sets the item state flags.

        :param `state`: any combination of the following bits:

         ============================ ========= ==============================
         State Bits                   Hex Value Description
         ============================ ========= ==============================
         ``ULC_STATE_DONTCARE``             0x0 Don't care what the state is
         ``ULC_STATE_DROPHILITED``          0x1 The item is highlighted to receive a drop event
         ``ULC_STATE_FOCUSED``              0x2 The item has the focus
         ``ULC_STATE_SELECTED``             0x4 The item is selected
         ``ULC_STATE_CUT``                  0x8 The item is in the cut state
         ``ULC_STATE_DISABLED``            0x10 The item is disabled
         ``ULC_STATE_FILTERED``            0x20 The item has been filtered
         ``ULC_STATE_INUSE``               0x40 The item is in use
         ``ULC_STATE_PICKED``              0x80 The item has been picked
         ``ULC_STATE_SOURCE``             0x100 The item is a drag and drop source
         ============================ ========= ==============================

        """

        self._state = flag

[docs]    def SetPosition(self, x, y):
        """
        Sets the header/footer item position.

        :param `x`: the item `x` position;
        :param `y`: the item `y` position.
        """

        self._xpos = x
        self._ypos = y

[docs]    def SetHeight(self, h):
        """
        Sets the header/footer item height, in pixels.

        :param `h`: an integer value representing the header/footer height.
        """

        self._height = h

[docs]    def SetWidth(self, w):
        """
        Sets the header/footer item width, in pixels.

        :param `w`: an integer value representing the header/footer width.
        """

        self._width = w

        if self._width < 0:
            self._width = WIDTH_COL_DEFAULT
        elif self._width < WIDTH_COL_MIN:
            self._width = WIDTH_COL_MIN

[docs]    def SetFormat(self, format):
        """
        Sets the header item format.

        :param `format`: the header item format.
        """

        self._format = format

[docs]    def SetFooterFormat(self, format):
        """
        Sets the footer item format.

        :param `format`: the footer item format.
        """

        self._footerFormat = format

[docs]    def HasImage(self):
        """
        Returns ``True`` if the header item has at least one image associated
        with it.
        """

        return len(self._image) > 0

[docs]    def HasFooterImage(self):
        """
        Returns ``True`` if the footer item has at least one image associated
        with it.
        """

        return len(self._footerImage) > 0

[docs]    def IsHit(self, x, y):
        """
        Returns ``True`` if the input position is inside the item client rectangle.

        :param `x`: the `x` mouse position;
        :param `y`: the `y` mouse position.
        """

        return ((x >= self._xpos) and (x <= self._xpos+self._width) and (y >= self._ypos) and (y <= self._ypos+self._height))

[docs]    def GetItem(self, item):
        """
        Returns information about the item.

        :param `item`: an instance of L{UltimateListHeaderData}.
        """

        item._mask = self._mask
        item._text = self._text
        item._tooltip = self._tooltip
        item._image = self._image[:]
        item._format = self._format
        item._width = self._width
        if self._font:
            item._font = self._font
            item.Attributes().SetFont(self._font)

        item._kind = self._kind
        item._checked = self._checked
        item._state = self._state
        item._isColumnShown = self._isColumnShown

        item._footerImage = self._footerImage
        item._footerFormat = self._footerFormat
        item._footerText = self._footerText
        item._footerKind = self._footerKind
        item._footerChecked = self._footerChecked
        item._footerFont = self._footerFont
        item._customRenderer = self._customRenderer

        return item

[docs]    def GetState(self):
        """
        Returns a bit field representing the state of the item.

        :see: L{SetState} for a list of valid item states.
        """

        return self._state

[docs]    def GetImage(self):
        """
        Returns a Python list with the zero-based indexes of the images associated
        with the header item into the image list.
        """

        return self._image

[docs]    def GetFooterImage(self):
        """
        Returns a Python list with the zero-based indexes of the images associated
        with the footer item into the image list.
        """

        return self._footerImage

[docs]    def GetWidth(self):
        """ Returns the header/footer item width, in pixels. """

        return self._width

[docs]    def GetFormat(self):
        """ Returns the header item format. """

        return self._format

[docs]    def GetFooterFormat(self):
        """ Returns the footer item format. """

        return self._footerFormat

[docs]    def SetFont(self, font):
        """
        Sets a new font for the header item.

        :param `font`: an instance of `wx.Font`.
        """

        self._font = font

[docs]    def SetFooterFont(self, font):
        """
        Sets a new font for the footer item.

        :param `font`: an instance of `wx.Font`.
        """

        self._footerFont = font

[docs]    def SetKind(self, kind):
        """
        Sets the header item kind.

        :param `kind`: may be one of the following integers:

         =============== ==========================
         Item Kind       Description
         =============== ==========================
                0        A normal item
                1        A checkbox-like item
                2        A radiobutton-type item
         =============== ==========================

        """

        self._kind = kind

[docs]    def SetFooterKind(self, kind):
        """
        Sets the footer item kind.

        :param `kind`: the footer item kind.

        :see: L{SetKind} for a list of valid item kinds.
        """

        self._footerKind = kind

[docs]    def GetKind(self):
        """
        Returns the header item kind.

        :see: L{SetKind} for a list of valid item kinds.
        """

        return self._kind

[docs]    def GetFooterKind(self):
        """
        Returns the footer item kind.

        :see: L{SetKind} for a list of valid item kinds.
        """

        return self._footerKind

[docs]    def IsChecked(self):
        """ Returns whether the header item is checked or not. """

        return self._checked

[docs]    def Check(self, checked=True):
        """
        Checks/unchecks a header item.

        :param `checked`: ``True`` to check an item, ``False`` to uncheck it.

        :note: This method is meaningful only for check and radio header items.
        """

        self._checked = checked

[docs]    def IsFooterChecked(self):
        """ Returns whether the footer item is checked or not. """

        return self._footerChecked

[docs]    def CheckFooter(self, check=True):
        """
        Checks/unchecks a footer item.

        :param `checked`: ``True`` to check an item, ``False`` to uncheck it.

        :note: This method is meaningful only for check and radio footer items.
        """

        self._footerChecked = check

[docs]    def SetCustomRenderer(self, renderer):
        """
        Associate a custom renderer to this item.

        :param `renderer`: a class able to correctly render the item.

        :note: the renderer class **must** implement the methods `DrawHeaderButton`
         and `GetForegroundColor`.
        """

        self._mask |= ULC_MASK_RENDERER
        self._customRenderer = renderer

[docs]    def GetCustomRenderer(self):
        """ Returns the custom renderer associated with this item (if any). """

        return self._customRenderer

#-----------------------------------------------------------------------------
#  GeometryInfo (internal)
#  this is not used in report view
#-----------------------------------------------------------------------------

[docs]class GeometryInfo(object):
    """
    A simple class which holds items geometries for L{UltimateListCtrl} not in
    report mode.
    """

[docs]    def __init__(self):
        """ Default class constructor. """

        # total item rect
        self._rectAll = wx.Rect()

        # label only
        self._rectLabel = wx.Rect()

        # icon only
        self._rectIcon = wx.Rect()

        # the part to be highlighted
        self._rectHighlight = wx.Rect()

        # the checkbox/radiobutton rect (if any)
        self._rectCheck = wx.Rect()

    # extend all our rects to be centered inside the one of given width

[docs]    def ExtendWidth(self, w):
        """
        Extends all our rectangles to be centered inside the one of given width.

        :param `w`: the given width.
        """

        if self._rectAll.width > w:
            raise Exception("width can only be increased")

        self._rectAll.width = w
        self._rectLabel.x = self._rectAll.x + (w - self._rectLabel.width)/2
        self._rectIcon.x = self._rectAll.x + (w - self._rectIcon.width)/2
        self._rectHighlight.x = self._rectAll.x + (w - self._rectHighlight.width)/2

#-----------------------------------------------------------------------------
#  UltimateListLineData (internal)
#-----------------------------------------------------------------------------

[docs]class UltimateListLineData(object):
    """ A simple class which holds line geometries for L{UltimateListCtrl}. """

[docs]    def __init__(self, owner):
        """
        Default class constructor.

        :param `owner`: an instance of L{UltimateListCtrl}.
        """

        # the list of subitems: only may have more than one item in report mode
        self._items = []

        # is this item selected? [NB: not used in virtual mode]
        self._highlighted = False

        # back pointer to the list ctrl
        self._owner = owner
        self._height = self._width = self._x = self._y = -1

        if self.InReportView():

            self._gi = None

        else:

            self._gi = GeometryInfo()

        if self.GetMode() in [ULC_REPORT, ULC_TILE] or self.HasMode(ULC_HEADER_IN_ALL_VIEWS):
            self.InitItems(self._owner.GetColumnCount())
        else:
            self.InitItems(1)

[docs]    def SetReportView(self, inReportView):
        """
        Sets whether L{UltimateListLineData} is in report view or not.

        :param `inReportView`: ``True`` to set L{UltimateListLineData} in report view, ``False``
         otherwise.
        """

        # we only need m_gi when we're not in report view so update as needed
        if inReportView:

            del self._gi
            self._gi = None

        else:

            self._gi = GeometryInfo()

[docs]    def GetHeight(self):
        """ Returns the line height, in pixels. """

        return self._height

[docs]    def SetHeight(self, height):
        """
        Sets the line height.

        :param `height`: the new line height.
        """

        self._height = height

[docs]    def GetWidth(self):
        """ Returns the line width. """

        return self._width

[docs]    def SetWidth(self, width):
        """
        Sets the line width.

        :param `width`: the new line width.
        """

        self._width = width

[docs]    def GetX(self):
        """ Returns the line `x` position. """

        return self._x

[docs]    def SetX(self, x):
        """
        Sets the line `x` position.

        :param `x`: the new line `x` position.
        """

        self._x = x

[docs]    def GetY(self):
        """ Returns the line `y` position. """

        return self._y

[docs]    def SetY(self, y):
        """
        Sets the line `y` position.

        :param `y`: the new line `y` position.
        """

        self._y = y

[docs]    def ResetDimensions(self):
        """ Resets the line dimensions (client rectangle). """

        self._height = self._width = self._x = self._y = -1

[docs]    def HasImage(self, col=0):
        """
        Returns ``True`` if the first item in the line has at least one image
        associated with it.
        """

        return self.GetImage(col) != []

[docs]    def HasText(self):
        """
        Returns ``True`` if the text of first item in the line is not the empty
        string.
        """

        return self.GetText(0) != ""

[docs]    def IsHighlighted(self):
        """ Returns ``True`` if the line is highlighted. """

        if self.IsVirtual():
            raise Exception("unexpected call to IsHighlighted")

        return self._highlighted

[docs]    def GetMode(self):
        """ Returns the current highlighting mode. """

        return self._owner.GetListCtrl().GetAGWWindowStyleFlag() & ULC_MASK_TYPE

[docs]    def HasMode(self, mode):
        """
        Returns ``True`` if the parent L{UltimateListCtrl} has the window
        style specified by `mode`.

        :param `mode`: the window style to check.
        """

        return self._owner.GetListCtrl().HasAGWFlag(mode)

[docs]    def InReportView(self):
        """ Returns ``True`` if the parent L{UltimateListCtrl} is in report view. """

        return self._owner.HasAGWFlag(ULC_REPORT)

[docs]    def IsVirtual(self):
        """ Returns ``True`` if the parent L{UltimateListCtrl} has the ``ULC_VIRTUAL`` style set. """

        return self._owner.IsVirtual()

[docs]    def CalculateSize(self, dc, spacing):
        """
        Calculates the line size and item positions.

        :param `dc`: an instance of `wx.DC`;
        :param `spacing`: the spacing between the items, in pixels.
        """

        item = self._items[0]
        mode = self.GetMode()

        if mode in [ULC_ICON, ULC_SMALL_ICON]:

            self._gi._rectAll.width = spacing

            s = item.GetText()

            if not s:

                lh = -1
                self._gi._rectLabel.width = 0
                self._gi._rectLabel.height = 0

            else:

                lw, lh = dc.GetTextExtent(s)
                lw += EXTRA_WIDTH
                lh += EXTRA_HEIGHT

                self._gi._rectAll.height = spacing + lh

                if lw > spacing:
                    self._gi._rectAll.width = lw

                self._gi._rectLabel.width = lw
                self._gi._rectLabel.height = lh

            if item.HasImage():

                w, h = self._owner.GetImageSize(item.GetImage())
                self._gi._rectIcon.width = w + 8
                self._gi._rectIcon.height = h + 8

                if self._gi._rectIcon.width > self._gi._rectAll.width:
                    self._gi._rectAll.width = self._gi._rectIcon.width
                if self._gi._rectIcon.height + lh > self._gi._rectAll.height - 4:
                    self._gi._rectAll.height = self._gi._rectIcon.height + lh + 4

            if item.HasText():

                self._gi._rectHighlight.width = self._gi._rectLabel.width
                self._gi._rectHighlight.height = self._gi._rectLabel.height

            else:

                self._gi._rectHighlight.width = self._gi._rectIcon.width
                self._gi._rectHighlight.height = self._gi._rectIcon.height

        elif mode == ULC_LIST:

            s = item.GetTextForMeasuring()

            lw, lh = dc.GetTextExtent(s)
            lw += EXTRA_WIDTH
            lh += EXTRA_HEIGHT

            self._gi._rectLabel.width = lw
            self._gi._rectLabel.height = lh

            self._gi._rectAll.width = lw
            self._gi._rectAll.height = lh

            if item.HasImage():

                w, h = self._owner.GetImageSize(item.GetImage())
                h += 4
                self._gi._rectIcon.width = w
                self._gi._rectIcon.height = h

                self._gi._rectAll.width += 4 + w

                if h > self._gi._rectAll.height:
                    self._gi._rectAll.height = h

            if item.GetKind() in [1, 2]:

                w, h = self._owner.GetCheckboxImageSize()
                h += 4
                self._gi._rectCheck.width = w
                self._gi._rectCheck.height = h

                self._gi._rectAll.width += 4 + w

                if h > self._gi._rectAll.height:
                    self._gi._rectAll.height = h

            self._gi._rectHighlight.width = self._gi._rectAll.width
            self._gi._rectHighlight.height = self._gi._rectAll.height

        elif mode == ULC_REPORT:
            raise Exception("unexpected call to SetSize")

        else:
            raise Exception("unknown mode")

[docs]    def SetPosition(self, x, y, spacing):
        """
        Sets the line position.

        :param `x`: the current `x` coordinate;
        :param `y`: the current `y` coordinate;
        :param `spacing`: the spacing between items, in pixels.
        """

        item = self._items[0]
        mode = self.GetMode()

        if mode in [ULC_ICON, ULC_SMALL_ICON]:

            self._gi._rectAll.x = x
            self._gi._rectAll.y = y

            if item.HasImage():

                self._gi._rectIcon.x = self._gi._rectAll.x + 4 + (self._gi._rectAll.width - self._gi._rectIcon.width)/2
                self._gi._rectIcon.y = self._gi._rectAll.y + 4

            if item.HasText():

                if self._gi._rectLabel.width > spacing:
                    self._gi._rectLabel.x = self._gi._rectAll.x + 2
                else:
                    self._gi._rectLabel.x = self._gi._rectAll.x + 2 + (spacing/2) - (self._gi._rectLabel.width/2)

                self._gi._rectLabel.y = self._gi._rectAll.y + self._gi._rectAll.height + 2 - self._gi._rectLabel.height
                self._gi._rectHighlight.x = self._gi._rectLabel.x - 2
                self._gi._rectHighlight.y = self._gi._rectLabel.y - 2

            else:

                self._gi._rectHighlight.x = self._gi._rectIcon.x - 4
                self._gi._rectHighlight.y = self._gi._rectIcon.y - 4

        elif mode == ULC_LIST:

            self._gi._rectAll.x = x
            self._gi._rectAll.y = y

            wcheck = hcheck = 0

            if item.GetKind() in [1, 2]:
                wcheck, hcheck = self._owner.GetCheckboxImageSize()
                wcheck += 2
                self._gi._rectCheck.x = self._gi._rectAll.x + 2
                self._gi._rectCheck.y = self._gi._rectAll.y + 2

            self._gi._rectHighlight.x = self._gi._rectAll.x
            self._gi._rectHighlight.y = self._gi._rectAll.y
            self._gi._rectLabel.y = self._gi._rectAll.y + 2

            if item.HasImage():

                self._gi._rectIcon.x = self._gi._rectAll.x + wcheck + 2
                self._gi._rectIcon.y = self._gi._rectAll.y + 2
                self._gi._rectLabel.x = self._gi._rectAll.x + 6 + self._gi._rectIcon.width + wcheck

            else:

                self._gi._rectLabel.x = self._gi._rectAll.x + 2 + wcheck

        elif mode == ULC_REPORT:
            raise Exception("unexpected call to SetPosition")

        else:
            raise Exception("unknown mode")

[docs]    def InitItems(self, num):
        """
        Initializes the list of items.

        :param `num`: the initial number of items to store.
        """

        for i in xrange(num):
            self._items.append(UltimateListItemData(self._owner))

[docs]    def SetItem(self, index, info):
        """
        Sets information about the item.

        :param `index`: the index of the item;
        :param `info`: an instance of L{UltimateListItem}.
        """

        item = self._items[index]
        item.SetItem(info)

[docs]    def GetItem(self, index, info):
        """
        Returns information about the item.

        :param `index`: the index of the item;
        :param `info`: an instance of L{UltimateListItem}.
        """

        item = self._items[index]
        return item.GetItem(info)

[docs]    def GetText(self, index):
        """
        Returns the item text at the position `index`.

        :param `index`: the index of the item.
        """

        item = self._items[index]
        return item.GetText()

[docs]    def SetText(self, index, s):
        """
        Sets the item text at the position `index`.

        :param `index`: the index of the item;
        :param `s`: the new item text.
        """

        item = self._items[index]
        item.SetText(s)

[docs]    def GetToolTip(self, index):
        """
        Returns the item tooltip at the position `index`.

        :param `index`: the index of the item.
        """

        item = self._items[index]
        return item.GetToolTip()

[docs]    def SetToolTip(self, index, s):
        """
        Sets the item tooltip at the position `index`.

        :param `index`: the index of the item;
        :param `s`: the new item tooltip.
        """

        item = self._items[index]
        item.SetToolTip(s)

[docs]    def SetImage(self, index, image):
        """
        Sets the zero-based indexes of the images associated with the item into the
        image list.

        :param `index`: the index of the item;
        :param `image`: a Python list with the zero-based indexes of the images
         associated with the item into the image list.
        """

        item = self._items[index]
        item.SetImage(image)

[docs]    def GetImage(self, index=0):
        """
        Returns a Python list with the zero-based indexes of the images associated
        with the item into the image list.

        :param `index`: the index of the item.
        """

        item = self._items[index]
        return item.GetImage()

[docs]    def Check(self, index, checked=True):
        """
        Checks/unchecks an item.

        :param `index`: the index of the item;
        :param `checked`: ``True`` to check an item, ``False`` to uncheck it.

        :note: This method is meaningful only for check and radio items.
        """

        item = self._items[index]
        item.Check(checked)

[docs]    def SetKind(self, index, kind=0):
        """
        Sets the item kind.

        :param `index`: the index of the item;
        :param `kind`: may be one of the following integers:

         =============== ==========================
         Item Kind       Description
         =============== ==========================
                0        A normal item
                1        A checkbox-like item
                2        A radiobutton-type item
         =============== ==========================

        """

        item = self._items[index]
        item.SetKind(kind)

[docs]    def GetKind(self, index=0):
        """
        Returns the item kind.

        :param `index`: the index of the item.

        :see: L{SetKind} for a list of valid item kinds.
        """

        item = self._items[index]
        return item.GetKind()

[docs]    def IsChecked(self, index):
        """
        Returns whether the item is checked or not.

        :param `index`: the index of the item.
        """

        item = self._items[index]
        return item.IsChecked()

[docs]    def SetColour(self, index, c):
        """
        Sets the text colour for the item.

        :param `index`: the index of the item;
        :param `c`: an instance of `wx.Colour`.
        """

        item = self._items[index]
        item.SetColour(c)

[docs]    def GetAttr(self):
        """
        Returns an instance of L{UltimateListItemAttr} associated with the first item
        in the line.
        """

        item = self._items[0]
        return item.GetAttr()

[docs]    def SetAttr(self, attr):
        """
        Sets an instance of L{UltimateListItemAttr} to the first item in the line.

        :param `attr`: an instance of L{UltimateListItemAttr}.
        """

        item = self._items[0]
        item.SetAttr(attr)

[docs]    def SetAttributes(self, dc, attr, highlighted):
        """
        Sets various attributes to the input device context.

        :param `dc`: an instance of `wx.DC`;
        :param `attr`: an instance of L{UltimateListItemAttr};
        :param `highlighted`: ``True`` if the item is highlighted, ``False`` otherwise.
        """

        listctrl = self._owner.GetParent()

        # fg colour
        # don't use foreground colour for drawing highlighted items - this might
        # make them completely invisible (and there is no way to do bit
        # arithmetics on wxColour, unfortunately)

        if not self._owner.HasAGWFlag(ULC_BORDER_SELECT) and not self._owner.HasAGWFlag(ULC_NO_FULL_ROW_SELECT):
            if highlighted:
                if wx.Platform == "__WXMAC__":
                    if self._owner.HasFocus():
                        colText = wx.WHITE
                    else:
                        colText = wx.BLACK
                else:
                    colText = wx.SystemSettings.GetColour(wx.SYS_COLOUR_HIGHLIGHTTEXT)
            else:
                if attr and attr.HasTextColour():
                    colText = attr.GetTextColour()
                else:
                    colText = listctrl.GetForegroundColour()
        elif attr and attr.HasTextColour():
            colText = attr.GetTextColour()
        else:
            colText = listctrl.GetForegroundColour()

        dc.SetTextForeground(colText)

        # font
        if attr and attr.HasFont():
            font = attr.GetFont()
        else:
            font = listctrl.GetFont()

        dc.SetFont(font)

        # bg colour
        hasBgCol = attr and attr.HasBackgroundColour()

        if highlighted or hasBgCol:
            if highlighted:
                dc.SetBrush(self._owner.GetHighlightBrush())
            else:
                dc.SetBrush(wx.Brush(attr.GetBackgroundColour(), wx.SOLID))

            dc.SetPen(wx.TRANSPARENT_PEN)

            return True

        return False

[docs]    def Draw(self, line, dc):
        """
        Draws the line on the specified device context.

        :param `line`: an instance of L{UltimateListLineData};
        :param `dc`: an instance of `wx.DC`.
        """

        item = self._items[0]
        highlighted = self.IsHighlighted()

        attr = self.GetAttr()

        useGradient, gradientStyle = self._owner._usegradients, self._owner._gradientstyle
        useVista = self._owner._vistaselection
        hasFocus = self._owner._hasFocus
        borderOnly = self._owner.HasAGWFlag(ULC_BORDER_SELECT)
        drawn = False

        if self.SetAttributes(dc, attr, highlighted):
            drawn = True

            if not borderOnly:

                if useGradient:
                    if gradientStyle == 0:
                        # horizontal gradient
                        self.DrawHorizontalGradient(dc, self._gi._rectAll, hasFocus)
                    else:
                        # vertical gradient
                        self.DrawVerticalGradient(dc, self._gi._rectAll, hasFocus)
                elif useVista:
                    # Vista selection style
                    self.DrawVistaRectangle(dc, self._gi._rectAll, hasFocus)
                else:
                    if highlighted:
                        flags = wx.CONTROL_SELECTED
                        if self._owner.HasFocus() and wx.Platform == "__WXMAC__":
                            flags |= wx.CONTROL_FOCUSED

                        wx.RendererNative.Get().DrawItemSelectionRect(self._owner, dc, self._gi._rectHighlight, flags)
                    else:
                        dc.DrawRectangleRect(self._gi._rectHighlight)

        else:

            if borderOnly:
                dc.SetBrush(wx.WHITE_BRUSH)
                dc.SetPen(wx.TRANSPARENT_PEN)
                dc.DrawRectangleRect(self._gi._rectAll)

        if item.GetKind() in [1, 2]:
            rectCheck = self._gi._rectCheck
            self._owner.DrawCheckbox(dc, rectCheck.x, rectCheck.y, item.GetKind(), item.IsChecked(), item.IsEnabled())

        if item.HasImage():
            # centre the image inside our rectangle, this looks nicer when items
            # ae aligned in a row
            rectIcon = self._gi._rectIcon
            self._owner.DrawImage(item.GetImage()[0], dc, rectIcon.x, rectIcon.y, True)

        if item.HasText():
            rectLabel = self._gi._rectLabel

            dc.SetClippingRect(rectLabel)
            dc.DrawText(item.GetText(), rectLabel.x, rectLabel.y)
            dc.DestroyClippingRegion()

        if self._owner.HasAGWFlag(ULC_HOT_TRACKING):
            if line == self._owner._newHotCurrent and not drawn:
                r = wx.Rect(*self._gi._rectAll)
                dc.SetBrush(wx.TRANSPARENT_BRUSH)
                dc.SetPen(wx.Pen(wx.NamedColour("orange")))
                dc.DrawRoundedRectangleRect(r, 3)

        if borderOnly and drawn:
            dc.SetPen(wx.Pen(wx.Colour(0, 191, 255), 2))
            dc.SetBrush(wx.TRANSPARENT_BRUSH)
            r = wx.Rect(*self._gi._rectAll)
            r.x += 1
            r.y += 1
            r.width -= 1
            r.height -= 1
            dc.DrawRoundedRectangleRect(r, 4)

[docs]    def HideItemWindow(self, item):
        """
        If the input item has a window associated with it, hide it.

        :param `item`: an instance of L{UltimateListItem}.
        """

        wnd = item.GetWindow()
        if wnd and wnd.IsShown():
            wnd.Hide()

[docs]    def DrawInReportMode(self, dc, line, rect, rectHL, highlighted, current, enabled, oldPN, oldBR):
        """
        Draws the line on the specified device context when the parent L{UltimateListCtrl}
        is in report mode.

        :param `dc`: an instance of `wx.DC`;
        :param `line`: an instance of L{UltimateListLineData};
        :param `rect`: the item client rectangle;
        :param `rectHL`: the item client rectangle when the item is highlighted;
        :param `highlighted`: ``True`` if the item is highlighted, ``False`` otherwise;
        :param `current`: ``True`` if the item is the current item;
        :param `enabled`: ``True`` if the item is enabled, ``False`` otherwise;
        :param `oldPN`: an instance of `wx.Pen`, to save and restore at the end of
         the drawing;
        :param `oldBR`: an instance of `wx.Brush`, to save and restore at the end of
         the drawing.
        """

        attr = self.GetAttr()

        useGradient, gradientStyle = self._owner._usegradients, self._owner._gradientstyle
        useVista = self._owner._vistaselection
        hasFocus = self._owner._hasFocus
        borderOnly = self._owner.HasAGWFlag(ULC_BORDER_SELECT)
        nofullRow = self._owner.HasAGWFlag(ULC_NO_FULL_ROW_SELECT)

        drawn = False
        dc.SetBrush(wx.TRANSPARENT_BRUSH)

        if nofullRow:

            x = rect.x + HEADER_OFFSET_X
            y = rect.y
            height = rect.height

            for col, item in enumerate(self._items):

                width = self._owner.GetColumnWidth(col)
                if self._owner.IsColumnShown(col):
                    paintRect = wx.Rect(x, y, self._owner.GetColumnWidth(col)-2*HEADER_OFFSET_X, rect.height)
                    break

                xOld = x
                x += width

        else:

            paintRect = wx.Rect(*rectHL)

        if self.SetAttributes(dc, attr, highlighted) and enabled:

            drawn = True

            if not borderOnly:

                if useGradient:
                    if gradientStyle == 0:
                        # horizontal gradient
                        self.DrawHorizontalGradient(dc, paintRect, hasFocus)
                    else:
                        # vertical gradient
                        self.DrawVerticalGradient(dc, paintRect, hasFocus)
                elif useVista:
                    # Vista selection style
                    self.DrawVistaRectangle(dc, paintRect, hasFocus)
                else:
                    if highlighted:
                        flags = wx.CONTROL_SELECTED
                        if hasFocus:
                            flags |= wx.CONTROL_FOCUSED
                        if current:
                            flags |= wx.CONTROL_CURRENT

                        wx.RendererNative.Get().DrawItemSelectionRect(self._owner, dc, paintRect, flags)
                    else:
                        dc.DrawRectangleRect(paintRect)

        else:

            if borderOnly:

                dc.SetBrush(wx.WHITE_BRUSH)
                dc.SetPen(wx.TRANSPARENT_PEN)
                dc.DrawRectangleRect(paintRect)

        x = rect.x + HEADER_OFFSET_X
        y = rect.y
        height = rect.height
        boldFont = wx.SystemSettings.GetFont(wx.SYS_DEFAULT_GUI_FONT)
        boldFont.SetWeight(wx.BOLD)

        for col, item in enumerate(self._items):

            if not self._owner.IsColumnShown(col):
                self.HideItemWindow(item)
                continue

            width = self._owner.GetColumnWidth(col)
            xOld = x
            x += width

            if item.GetCustomRenderer():
                customRect = wx.Rect(xOld-HEADER_OFFSET_X, rect.y, width, rect.height)
                item.GetCustomRenderer().DrawSubItem(dc, customRect, line, highlighted, enabled)
                continue

            overflow = item.GetOverFlow() and item.HasText()

            if item.GetKind() in [1, 2]:

                # We got a checkbox-type item
                ix, iy = self._owner.GetCheckboxImageSize()
                checked = item.IsChecked()
                self._owner.DrawCheckbox(dc, xOld, y + (height-iy+1)/2, item.GetKind(), checked, enabled)
                xOld += ix
                width -= ix

            if item.HasImage():

                images = item.GetImage()

                for img in images:

                    ix, iy = self._owner.GetImageSize([img])
                    self._owner.DrawImage(img, dc, xOld, y + (height-iy)/2, enabled)

                    xOld += ix
                    width -= ix

##                if images:
##                    width -= IMAGE_MARGIN_IN_REPORT_MODE - MARGIN_BETWEEN_TEXT_AND_ICON

            wnd = item.GetWindow()
            xSize = 0
            if wnd:
                xSize, ySize = item.GetWindowSize()
                wndx = xOld - HEADER_OFFSET_X + width - xSize - 3
                xa, ya = self._owner.CalcScrolledPosition((0, rect.y))
                wndx += xa
                if rect.height > ySize and not item._expandWin:
                    ya += (rect.height - ySize)/2

            itemRect = wx.Rect(xOld-2*HEADER_OFFSET_X, rect.y, width-xSize-HEADER_OFFSET_X, rect.height)
            if overflow:
                itemRect = wx.Rect(xOld-2*HEADER_OFFSET_X, rect.y, rectHL.width-xSize-HEADER_OFFSET_X, rect.height)

            dc.SetClippingRect(itemRect)

            if item.HasBackgroundColour():
                dc.SetBrush(wx.Brush(item.GetBackgroundColour()))
                dc.SetPen(wx.Pen(item.GetBackgroundColour()))
                dc.DrawRectangleRect(itemRect)
                dc.SetBrush(oldBR)
                dc.SetPen(oldPN)

            if item.HasText():

                coloured = item.HasColour()

                c = dc.GetTextForeground()
                oldTF = wx.Colour(c.Red(),c.Green(),c.Blue())
                oldFT = dc.GetFont()

                font = item.HasFont()

                if not enabled:
                    dc.SetTextForeground(self._owner.GetDisabledTextColour())
                else:
                    if coloured:
                        dc.SetTextForeground(item.GetColour())
                    elif useVista and drawn:
                        dc.SetTextForeground(wx.BLACK)

                if item.IsHyperText():
                    dc.SetFont(self._owner.GetHyperTextFont())
                    if item.GetVisited():
                        dc.SetTextForeground(self._owner.GetHyperTextVisitedColour())
                    else:
                        dc.SetTextForeground(self._owner.GetHyperTextNewColour())
                else:
                    if font:
                        dc.SetFont(item.GetFont())

                itemRect = wx.Rect(itemRect.x+MARGIN_BETWEEN_TEXT_AND_ICON, itemRect.y, itemRect.width-8, itemRect.height)
                self.DrawTextFormatted(dc, item.GetText(), line, col, itemRect, overflow)

                if coloured:
                    dc.SetTextForeground(oldTF)

                if font:
                    dc.SetFont(oldFT)

            dc.DestroyClippingRegion()

            if wnd:
                if not wnd.IsShown():
                    wnd.Show()

                if item._expandWin:
                    wRect = wx.Rect(*itemRect)
                    wRect.x += xa + 2
                    wRect.width = width - 8
                    wRect.y = ya + 2
                    wRect.height -= 4
                    if wnd.GetRect() != wRect:
                        wnd.SetRect(wRect)
                else:
                    if wnd.GetPosition() != (wndx, ya):
                        wnd.SetPosition((wndx, ya))

        if self._owner.HasAGWFlag(ULC_HOT_TRACKING):
            if line == self._owner._newHotCurrent and not drawn:
                r = wx.Rect(*paintRect)
                r.y += 1
                r.height -= 1
                dc.SetBrush(wx.TRANSPARENT_BRUSH)
                dc.SetPen(wx.Pen(wx.NamedColour("orange")))
                dc.DrawRoundedRectangleRect(r, 3)
                dc.SetPen(oldPN)

        if borderOnly and drawn:
            dc.SetPen(wx.Pen(wx.Colour(0, 191, 255), 2))
            dc.SetBrush(wx.TRANSPARENT_BRUSH)
            rect = wx.Rect(*paintRect)
            rect.y += 1
            rect.height -= 1
            dc.DrawRoundedRectangleRect(rect, 3)
            dc.SetPen(oldPN)

[docs]    def DrawTextFormatted(self, dc, text, row, col, itemRect, overflow):
        """
        Draws the item text, correctly formatted.

        :param `dc`: an instance of `wx.DC`;
        :param `text`: the item text;
        :param `row`: the line number to which this item belongs to;
        :param `col`: the column number to which this item belongs to;
        :param `itemRect`: the item client rectangle;
        :param `overflow`: ``True`` if the item should overflow into neighboring columns,
         ``False`` otherwise.
        """
        # determine if the string can fit inside the current width
        w, h, dummy = dc.GetMultiLineTextExtent(text)
        width = itemRect.width

        shortItems = self._owner._shortItems
        tuples = (row, col)

        # it can, draw it using the items alignment
        item = self._owner.GetColumn(col)
        align = item.GetAlign()

        if align == ULC_FORMAT_RIGHT:
            textAlign = wx.ALIGN_RIGHT
        elif align == ULC_FORMAT_CENTER:
            textAlign = wx.ALIGN_CENTER
        else:
            textAlign = wx.ALIGN_LEFT

        if w <= width:

            if tuples in shortItems:
                shortItems.remove(tuples)

            dc.DrawLabel(text, itemRect, textAlign|wx.ALIGN_CENTER_VERTICAL)

        else: # otherwise, truncate and add an ellipsis if possible

            if tuples not in shortItems:
                shortItems.append(tuples)

            # determine the base width
            ellipsis = "..."
            base_w, h = dc.GetTextExtent(ellipsis)

            # continue until we have enough space or only one character left

            newText = text.split("\n")
            theText = ""

            for text in newText:

                lenText = len(text)
                drawntext = text
                w, dummy = dc.GetTextExtent(text)

                while lenText > 1:

                    if w + base_w <= width:
                        break

                    w_c, h_c = dc.GetTextExtent(drawntext[-1])
                    drawntext = drawntext[0:-1]
                    lenText -= 1
                    w -= w_c

                # if still not enough space, remove ellipsis characters
                while len(ellipsis) > 0 and w + base_w > width:
                    ellipsis = ellipsis[0:-1]
                    base_w, h = dc.GetTextExtent(ellipsis)

                theText += drawntext + ellipsis + "\n"

            theText = theText.rstrip()
            # now draw the text
            dc.DrawLabel(theText, itemRect, textAlign|wx.ALIGN_CENTER_VERTICAL)

[docs]    def DrawVerticalGradient(self, dc, rect, hasfocus):
        """
        Gradient fill from colour 1 to colour 2 from top to bottom.

        :param `dc`: an instance of `wx.DC`;
        :param `rect`: the rectangle to be filled with the gradient shading;
        :param `hasfocus`: ``True`` if the main L{UltimateListCtrl} has focus, ``False``
         otherwise.
        """

        oldpen = dc.GetPen()
        oldbrush = dc.GetBrush()
        dc.SetPen(wx.TRANSPARENT_PEN)

        # calculate gradient coefficients
        if hasfocus:
            col2 = self._owner._secondcolour
            col1 = self._owner._firstcolour
        else:
            col2 = self._owner._highlightUnfocusedBrush.GetColour()
            col1 = self._owner._highlightUnfocusedBrush2.GetColour()

        r1, g1, b1 = int(col1.Red()), int(col1.Green()), int(col1.Blue())
        r2, g2, b2 = int(col2.Red()), int(col2.Green()), int(col2.Blue())

        flrect = float(rect.height)

        rstep = float((r2 - r1)) / flrect
        gstep = float((g2 - g1)) / flrect
        bstep = float((b2 - b1)) / flrect

        rf, gf, bf = 0, 0, 0

        for y in xrange(rect.y, rect.y + rect.height):
            currCol = (r1 + rf, g1 + gf, b1 + bf)
            dc.SetBrush(wx.Brush(currCol, wx.SOLID))
            dc.DrawRectangle(rect.x, y, rect.width, 1)
            rf = rf + rstep
            gf = gf + gstep
            bf = bf + bstep

        dc.SetPen(oldpen)
        dc.SetBrush(wx.TRANSPARENT_BRUSH)
        dc.DrawRectangleRect(rect)
        dc.SetBrush(oldbrush)

[docs]    def DrawHorizontalGradient(self, dc, rect, hasfocus):
        """
        Gradient fill from colour 1 to colour 2 from left to right.

        :param `dc`: an instance of `wx.DC`;
        :param `rect`: the rectangle to be filled with the gradient shading;
        :param `hasfocus`: ``True`` if the main L{UltimateListCtrl} has focus, ``False``
         otherwise.
        """

        oldpen = dc.GetPen()
        oldbrush = dc.GetBrush()
        dc.SetPen(wx.TRANSPARENT_PEN)

        # calculate gradient coefficients

        if hasfocus:
            col2 = self._owner._secondcolour
            col1 = self._owner._firstcolour
        else:
            col2 = self._owner._highlightUnfocusedBrush.GetColour()
            col1 = self._owner._highlightUnfocusedBrush2.GetColour()

        r1, g1, b1 = int(col1.Red()), int(col1.Green()), int(col1.Blue())
        r2, g2, b2 = int(col2.Red()), int(col2.Green()), int(col2.Blue())

        flrect = float(rect.width)

        rstep = float((r2 - r1)) / flrect
        gstep = float((g2 - g1)) / flrect
        bstep = float((b2 - b1)) / flrect

        rf, gf, bf = 0, 0, 0

        for x in xrange(rect.x, rect.x + rect.width):
            currCol = (int(r1 + rf), int(g1 + gf), int(b1 + bf))
            dc.SetBrush(wx.Brush(currCol, wx.SOLID))
            dc.DrawRectangle(x, rect.y, 1, rect.height)
            rf = rf + rstep
            gf = gf + gstep
            bf = bf + bstep

        dc.SetPen(oldpen)
        dc.SetBrush(wx.TRANSPARENT_BRUSH)
        dc.DrawRectangleRect(rect)
        dc.SetBrush(oldbrush)

[docs]    def DrawVistaRectangle(self, dc, rect, hasfocus):
        """
        Draws the selected item(s) with the Windows Vista style.

        :param `dc`: an instance of `wx.DC`;
        :param `rect`: the rectangle to be filled with the gradient shading;
        :param `hasfocus`: ``True`` if the main L{UltimateListCtrl} has focus, ``False``
         otherwise.
        """

        if hasfocus:

            outer = _rgbSelectOuter
            inner = _rgbSelectInner
            top = _rgbSelectTop
            bottom = _rgbSelectBottom

        else:

            outer = _rgbNoFocusOuter
            inner = _rgbNoFocusInner
            top = _rgbNoFocusTop
            bottom = _rgbNoFocusBottom

        oldpen = dc.GetPen()
        oldbrush = dc.GetBrush()

        bdrRect = wx.Rect(*rect.Get())
        filRect = wx.Rect(*rect.Get())
        filRect.Deflate(1,1)

        r1, g1, b1 = int(top.Red()), int(top.Green()), int(top.Blue())
        r2, g2, b2 = int(bottom.Red()), int(bottom.Green()), int(bottom.Blue())

        flrect = float(filRect.height)
        if flrect < 1:
            flrect = self._owner._lineHeight

        rstep = float((r2 - r1)) / flrect
        gstep = float((g2 - g1)) / flrect
        bstep = float((b2 - b1)) / flrect

        rf, gf, bf = 0, 0, 0
        dc.SetPen(wx.TRANSPARENT_PEN)

        for y in xrange(filRect.y, filRect.y + filRect.height):
            currCol = (r1 + rf, g1 + gf, b1 + bf)
            dc.SetBrush(wx.Brush(currCol, wx.SOLID))
            dc.DrawRectangle(filRect.x, y, filRect.width, 1)
            rf = rf + rstep
            gf = gf + gstep
            bf = bf + bstep

        dc.SetBrush(wx.TRANSPARENT_BRUSH)
        dc.SetPen(wx.Pen(outer))
        dc.DrawRoundedRectangleRect(bdrRect, 3)
        bdrRect.Deflate(1, 1)
        dc.SetPen(wx.Pen(inner))
        dc.DrawRoundedRectangleRect(bdrRect, 2)

        dc.SetPen(oldpen)
        dc.SetBrush(oldbrush)

[docs]    def Highlight(self, on):
        """
        Sets the current line as highlighted or not highlighted.

        :param `on`: ``True`` to set the current line as highlighted, ``False``
         otherwise.
        """

        if on == self._highlighted:
            return False

        self._highlighted = on

        return True

[docs]    def ReverseHighlight(self):
        """
        Reverses the line highlighting, switching it off if it was on and vice-versa.
        """

        self.Highlight(not self.IsHighlighted())

#-----------------------------------------------------------------------------
#  UltimateListHeaderWindow (internal)
#-----------------------------------------------------------------------------

[docs]class UltimateListHeaderWindow(wx.PyControl):
    """
    This class holds the header window for L{UltimateListCtrl}.
    """

[docs]    def __init__(self, win, id, owner, pos=wx.DefaultPosition,
                 size=wx.DefaultSize, style=0, validator=wx.DefaultValidator,
                 name="UltimateListCtrlcolumntitles", isFooter=False):
        """
        Default class constructor.

        :param `parent`: parent window. Must not be ``None``;
        :param `id`: window identifier. A value of -1 indicates a default value;
        :param `owner`: an instance of L{UltimateListCtrl};
        :param `pos`: the control position. A value of (-1, -1) indicates a default position,
         chosen by either the windowing system or wxPython, depending on platform;
        :param `size`: the control size. A value of (-1, -1) indicates a default size,
         chosen by either the windowing system or wxPython, depending on platform;
        :param `style`: the window style;
        :param `validator`: the window validator;
        :param `name`: the window name;
        :param `isFooter`: ``True`` if the L{UltimateListHeaderWindow} is in a footer
         position, ``False`` otherwise.
        """

        wx.PyControl.__init__(self, win, id, pos, size, style|wx.NO_BORDER, validator, name)

        self._isFooter = isFooter
        self._owner = owner
        self._currentCursor = wx.NullCursor
        self._resizeCursor = wx.StockCursor(wx.CURSOR_SIZEWE)
        self._isDragging = False
        self._headerHeight = None
        self._footerHeight = None

        # Custom renderer for every column
        self._headerCustomRenderer = None

        # column being resized or -1
        self._column = -1

        # divider line position in logical (unscrolled) coords
        self._currentX = 0

        # minimal position beyond which the divider line can't be dragged in
        # logical coords
        self._minX = 0

        # needs refresh
        self._dirty = False
        self._hasFont = False
        self._sendSetColumnWidth = False
        self._colToSend = -1
        self._widthToSend = 0
        self._leftDown = False
        self._enter = False
        self._currentColumn = -1

        self.Bind(wx.EVT_PAINT, self.OnPaint)
        self.Bind(wx.EVT_ERASE_BACKGROUND, lambda e: None)
        self.Bind(wx.EVT_MOUSE_EVENTS, self.OnMouse)
        self.Bind(wx.EVT_SET_FOCUS, self.OnSetFocus)
        self.Bind(wx.EVT_ENTER_WINDOW, self.OnEnterWindow)
        self.Bind(wx.EVT_LEAVE_WINDOW, self.OnLeaveWindow)

        if _USE_VISATTR:

            attr = wx.Panel.GetClassDefaultAttributes()
            self.SetOwnForegroundColour(attr.colFg)
            self.SetOwnBackgroundColour(attr.colBg)
            if not self._hasFont:
                self.SetOwnFont(attr.font)

        else:

            self.SetOwnForegroundColour(wx.SystemSettings.GetColour(wx.SYS_COLOUR_WINDOWTEXT))
            self.SetOwnBackgroundColour(wx.SystemSettings.GetColour(wx.SYS_COLOUR_BTNFACE))

            if not self._hasFont:
                self.SetOwnFont(wx.SystemSettings.GetFont(wx.SYS_DEFAULT_GUI_FONT))

[docs]    def SetCustomRenderer(self, renderer=None):
        """
        Associate a custom renderer with the header - all columns will use it

        :param `renderer`: a class able to correctly render header buttons

        :note: the renderer class **must** implement the methods `DrawHeaderButton`
          and `GetForegroundColor`.
        """

        if not self._owner.HasAGWFlag(ULC_REPORT):
            raise Exception("Custom renderers can be used on with style = ULC_REPORT")

        self._headerCustomRenderer = renderer

[docs]    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()`.
        """

        if not self._isFooter:
            if self._headerHeight is not None:
                self.GetParent()._headerHeight = self._headerHeight
                return wx.Size(200, self._headerHeight)
        else:
            if self._footerHeight is not None:
                self.GetParent()._footerHeight = self._footerHeight
                return wx.Size(200, self._footerHeight)

        w, h, d, dummy = self.GetFullTextExtent("Hg")
        maxH = self.GetTextHeight()
        nativeH = wx.RendererNative.Get().GetHeaderButtonHeight(self.GetParent())

        if not self._isFooter:
            maxH = max(max(h, maxH), nativeH)
            maxH += d
            self.GetParent()._headerHeight = maxH
        else:
            maxH = max(h, nativeH)
            maxH += d
            self.GetParent()._footerHeight = maxH

        return wx.Size(200, maxH)

[docs]    def GetWindowHeight(self):
        """ Returns the L{UltimateListHeaderWindow} height, in pixels. """

        return self.DoGetBestSize()

[docs]    def IsColumnShown(self, column):
        """
        Returns ``True`` if the input column is shown, ``False`` if it is hidden.

        :param `column`: an integer specifying the column index.
        """

        if column < 0 or column >= self._owner.GetColumnCount():
            raise Exception("Invalid column")

        return self._owner.IsColumnShown(column)

    # shift the DC origin to match the position of the main window horz
    # scrollbar: this allows us to always use logical coords

[docs]    def AdjustDC(self, dc):
        """
        Shifts the `wx.DC` origin to match the position of the main window horizontal
        scrollbar: this allows us to always use logical coordinates.

        :param `dc`: an instance of `wx.DC`.
        """

        xpix, dummy = self._owner.GetScrollPixelsPerUnit()
        x, dummy = self._owner.GetViewStart()

        # account for the horz scrollbar offset
        dc.SetDeviceOrigin(-x*xpix, 0)

[docs]    def GetTextHeight(self):
        """ Returns the column text height, in pixels. """

        maxH = 0
        numColumns = self._owner.GetColumnCount()
        dc = wx.ClientDC(self)
        for i in xrange(numColumns):

            if not self.IsColumnShown(i):
                continue

            item = self._owner.GetColumn(i)
            if item.GetFont().IsOk():
                dc.SetFont(item.GetFont())
            else:
                dc.SetFont(self.GetFont())

            wLabel, hLabel, dummy = dc.GetMultiLineTextExtent(item.GetText())
            maxH = max(maxH, hLabel)

        return maxH

[docs]    def OnPaint(self, event):
        """
        Handles the ``wx.EVT_PAINT`` event for L{UltimateListHeaderWindow}.

        :param `event`: a `wx.PaintEvent` event to be processed.
        """

        dc = wx.BufferedPaintDC(self)
        # width and height of the entire header window
        w, h = self.GetClientSize()
        w, dummy = self._owner.CalcUnscrolledPosition(w, 0)
        dc.SetBrush(wx.Brush(wx.SystemSettings.GetColour(wx.SYS_COLOUR_BTNFACE)))
        dc.SetPen(wx.TRANSPARENT_PEN)
        dc.DrawRectangle(0, -1, w, h+2)

        self.AdjustDC(dc)

        dc.SetBackgroundMode(wx.TRANSPARENT)
        dc.SetTextForeground(self.GetForegroundColour())

        x = HEADER_OFFSET_X

        numColumns = self._owner.GetColumnCount()
        item = UltimateListItem()
        renderer = wx.RendererNative.Get()
        enabled = self.GetParent().IsEnabled()
        virtual = self._owner.IsVirtual()
        isFooter = self._isFooter

        for i in xrange(numColumns):

            # Reset anything in the dc that a custom renderer might have changed
            dc.SetTextForeground(self.GetForegroundColour())

            if x >= w:
                break

            if not self.IsColumnShown(i):
                continue # do next column if not shown

            item = self._owner.GetColumn(i)
            wCol = item._width

            cw = wCol
            ch = h

            flags = 0
            if not enabled:
                flags |= wx.CONTROL_DISABLED

            # NB: The code below is not really Mac-specific, but since we are close
            # to 2.8 release and I don't have time to test on other platforms, I
            # defined this only for wxMac. If this behavior is desired on
            # other platforms, please go ahead and revise or remove the #ifdef.

            if "__WXMAC__" in wx.PlatformInfo:
                if not virtual and item._mask & ULC_MASK_STATE and item._state & ULC_STATE_SELECTED:
                    flags |= wx.CONTROL_SELECTED

            if i == 0:
               flags |= wx.CONTROL_SPECIAL # mark as first column

            if i == self._currentColumn:
                if self._leftDown:
                    flags |= wx.CONTROL_PRESSED
                else:
                    if self._enter:
                        flags |= wx.CONTROL_CURRENT

            # the width of the rect to draw: make it smaller to fit entirely
            # inside the column rect
            header_rect = wx.Rect(x-1, HEADER_OFFSET_Y-1, cw-1, ch)

            if self._headerCustomRenderer != None:
               self._headerCustomRenderer.DrawHeaderButton(dc, header_rect, flags)

               # The custom renderer will specify the color to draw the header text and buttons
               dc.SetTextForeground(self._headerCustomRenderer.GetForegroundColour())

            elif item._mask & ULC_MASK_RENDERER:
               item.GetCustomRenderer().DrawHeaderButton(dc, header_rect, flags)

               # The custom renderer will specify the color to draw the header text and buttons
               dc.SetTextForeground(item.GetCustomRenderer().GetForegroundColour())
            else:
                renderer.DrawHeaderButton(self, dc, header_rect, flags)

            # see if we have enough space for the column label
            if isFooter:
                if item.GetFooterFont().IsOk():
                    dc.SetFont(item.GetFooterFont())
                else:
                    dc.SetFont(self.GetFont())
            else:
                if item.GetFont().IsOk():
                    dc.SetFont(item.GetFont())
                else:
                    dc.SetFont(self.GetFont())

            wcheck = hcheck = 0
            kind = (isFooter and [item.GetFooterKind()] or [item.GetKind()])[0]
            checked = (isFooter and [item.IsFooterChecked()] or [item.IsChecked()])[0]

            if kind in [1, 2]:
                # We got a checkbox-type item
                ix, iy = self._owner.GetCheckboxImageSize()
                # We draw it on the left, always
                self._owner.DrawCheckbox(dc, x + HEADER_OFFSET_X, HEADER_OFFSET_Y + (h - 4 - iy)/2, kind, checked, enabled)
                wcheck += ix + HEADER_IMAGE_MARGIN_IN_REPORT_MODE
                cw -= ix + HEADER_IMAGE_MARGIN_IN_REPORT_MODE

            # for this we need the width of the text
            text = (isFooter and [item.GetFooterText()] or [item.GetText()])[0]
            wLabel, hLabel, dummy = dc.GetMultiLineTextExtent(text)
            wLabel += 2*EXTRA_WIDTH

            # and the width of the icon, if any
            image = (isFooter and [item._footerImage] or [item._image])[0]

            if image:
                imageList = self._owner._small_image_list
                if imageList:
                    for img in image:
                        if img >= 0:
                            ix, iy = imageList.GetSize(img)
                            wLabel += ix + HEADER_IMAGE_MARGIN_IN_REPORT_MODE

            else:

                imageList = None

            # ignore alignment if there is not enough space anyhow
            align = (isFooter and [item.GetFooterAlign()] or [item.GetAlign()])[0]
            align = (wLabel < cw and [align] or [ULC_FORMAT_LEFT])[0]

            if align == ULC_FORMAT_LEFT:
                xAligned = x + wcheck

            elif align == ULC_FORMAT_RIGHT:
                xAligned = x + cw - wLabel - HEADER_OFFSET_X

            elif align == ULC_FORMAT_CENTER:
                xAligned = x + wcheck + (cw - wLabel)/2

            # if we have an image, draw it on the right of the label
            if imageList:
                for indx, img in enumerate(image):
                    if img >= 0:
                        imageList.Draw(img, dc,
                                       xAligned + wLabel - (ix + HEADER_IMAGE_MARGIN_IN_REPORT_MODE)*(indx+1),
                                       HEADER_OFFSET_Y + (h - 4 - iy)/2,
                                       wx.IMAGELIST_DRAW_TRANSPARENT)

                        cw -= ix + HEADER_IMAGE_MARGIN_IN_REPORT_MODE

            # draw the text clipping it so that it doesn't overwrite the column
            # boundary
            dc.SetClippingRegion(x, HEADER_OFFSET_Y, cw, h - 4)
            self.DrawTextFormatted(dc, text, wx.Rect(xAligned+EXTRA_WIDTH, HEADER_OFFSET_Y, cw-EXTRA_WIDTH, h-4))

            x += wCol
            dc.DestroyClippingRegion()

        # Fill in what's missing to the right of the columns, otherwise we will
        # leave an unpainted area when columns are removed (and it looks better)
        if x < w:
            header_rect = wx.Rect(x, HEADER_OFFSET_Y, w - x, h)
            if self._headerCustomRenderer != None:
                # Why does the custom renderer need this adjustment??
                header_rect.x = header_rect.x - 1
                header_rect.y = header_rect.y - 1
                self._headerCustomRenderer.DrawHeaderButton(dc, header_rect, wx.CONTROL_DIRTY)
            else:
                renderer.DrawHeaderButton(self, dc, header_rect, wx.CONTROL_DIRTY) # mark as last column

[docs]    def DrawTextFormatted(self, dc, text, rect):
        """
        Draws the item text, correctly formatted.

        :param `dc`: an instance of `wx.DC`;
        :param `text`: the item text;
        :param `rect`: the item client rectangle.
        """

        # determine if the string can fit inside the current width
        w, h, dummy = dc.GetMultiLineTextExtent(text)
        width = rect.width

        if w <= width:

            dc.DrawLabel(text, rect, wx.ALIGN_CENTER_VERTICAL)

        else:

            # determine the base width
            ellipsis = "..."
            base_w, h = dc.GetTextExtent(ellipsis)

            # continue until we have enough space or only one character left

            newText = text.split("\n")
            theText = ""

            for text in newText:

                lenText = len(text)
                drawntext = text
                w, dummy = dc.GetTextExtent(text)

                while lenText > 1:

                    if w + base_w <= width:
                        break

                    w_c, h_c = dc.GetTextExtent(drawntext[-1])
                    drawntext = drawntext[0:-1]
                    lenText -= 1
                    w -= w_c

                # if still not enough space, remove ellipsis characters
                while len(ellipsis) > 0 and w + base_w > width:
                    ellipsis = ellipsis[0:-1]
                    base_w, h = dc.GetTextExtent(ellipsis)

                theText += drawntext + ellipsis + "\n"

            theText = theText.rstrip()
            dc.DrawLabel(theText, rect, wx.ALIGN_CENTER_VERTICAL)

[docs]    def OnInternalIdle(self):
        """
        This method is normally only used internally, but sometimes an application
        may need it to implement functionality that should not be disabled by an
        application defining an `OnIdle` handler in a derived class.

        This method may be used to do delayed painting, for example, and most
        implementations call `wx.Window.UpdateWindowUI` in order to send update events
        to the window in idle time.
        """

        wx.PyControl.OnInternalIdle(self)

        if self._isFooter:
            return

        if self._sendSetColumnWidth:
            self._owner.SetColumnWidth(self._colToSend, self._widthToSend)
            self._sendSetColumnWidth = False

[docs]    def DrawCurrent(self):
        """ Force the redrawing of the column window. """

        self._sendSetColumnWidth = True
        self._colToSend = self._column
        self._widthToSend = self._currentX - self._minX

[docs]    def OnMouse(self, event):
        """
        Handles the ``wx.EVT_MOUSE_EVENTS`` event for L{UltimateListHeaderWindow}.

        :param `event`: a `wx.MouseEvent` event to be processed.
        """

        # we want to work with logical coords
        x, dummy = self._owner.CalcUnscrolledPosition(event.GetX(), 0)
        y = event.GetY()

        columnX, columnY = x, y

        if self._isDragging:

            self.SendListEvent(wxEVT_COMMAND_LIST_COL_DRAGGING, event.GetPosition())

            # we don't draw the line beyond our window, but we allow dragging it
            # there

            w, dummy = self.GetClientSize()
            w, dummy = self._owner.CalcUnscrolledPosition(w, 0)
            w -= 6

            # erase the line if it was drawn
            if self._currentX < w:
                self.DrawCurrent()

            if event.ButtonUp():

                self.ReleaseMouse()
                self._isDragging = False
                self._dirty = True
                self._owner.SetColumnWidth(self._column, self._currentX - self._minX)
                self.SendListEvent(wxEVT_COMMAND_LIST_COL_END_DRAG, event.GetPosition())

            else:

                if x > self._minX + 7:
                    self._currentX = x
                else:
                    self._currentX = self._minX + 7

                # draw in the new location
                if self._currentX < w:
                    self.DrawCurrent()

        else: # not dragging

            self._minX = 0
            hit_border = False

            # end of the current column
            xpos = 0

            # find the column where this event occurred
            countCol = self._owner.GetColumnCount()
            broken = False

            for col in xrange(countCol):

                if not self.IsColumnShown(col):
                    continue

                xpos += self._owner.GetColumnWidth(col)
                self._column = col

                if abs(x-xpos) < 3 and y < 22:
                    # near the column border
                    hit_border = True
                    broken = True
                    break

                if x < xpos:
                    # inside the column
                    broken = True
                    break

                self._minX = xpos

            if not broken:
                self._column = -1

            # First check to see if we have a tooltip to display
            colItem = self._owner.GetColumn(col)
            if colItem.GetToolTip() != "":
                self.SetToolTipString(colItem.GetToolTip())
            else:
                self.SetToolTipString("")

            if event.LeftUp():
                self._leftDown = False
                self.Refresh()

            if event.LeftDown() or event.RightUp():

                if hit_border and event.LeftDown():

                    if not self._isFooter:

                        if self.SendListEvent(wxEVT_COMMAND_LIST_COL_BEGIN_DRAG,
                                              event.GetPosition()):

                            self._isDragging = True
                            self._currentX = x
                            self.CaptureMouse()
                            self.DrawCurrent()

                    #else: column resizing was vetoed by the user code

                else: # click on a column

                     # record the selected state of the columns
                    if event.LeftDown():

                        for i in xrange(self._owner.GetColumnCount()):

                            if not self.IsColumnShown(col):
                                continue

                            colItem = self._owner.GetColumn(i)
                            state = colItem.GetState()

                            if i == self._column:
                                colItem.SetState(state | ULC_STATE_SELECTED)
                                theX = x
                            else:
                                colItem.SetState(state & ~ULC_STATE_SELECTED)

                            self._leftDown = True
                            self._owner.SetColumn(i, colItem)
                            x += self._owner.GetColumnWidth(i)

                        if self.HandleColumnCheck(self._column, event.GetPosition()):
                            return

                    if not self._isFooter:
                        self.SendListEvent((event.LeftDown() and [wxEVT_COMMAND_LIST_COL_CLICK] or \
                                            [wxEVT_COMMAND_LIST_COL_RIGHT_CLICK])[0], event.GetPosition())
                    else:
                        self.SendListEvent((event.LeftDown() and [wxEVT_COMMAND_LIST_FOOTER_CLICK] or \
                                            [wxEVT_COMMAND_LIST_FOOTER_RIGHT_CLICK])[0], event.GetPosition())

                    self._leftDown = True
                    self._currentColumn = self._column

            elif event.Moving():

                setCursor = False

                if not self._isFooter:
                    if hit_border:

                        setCursor = self._currentCursor == wx.STANDARD_CURSOR
                        self._currentCursor = self._resizeCursor

                    else:

                        setCursor = self._currentCursor != wx.STANDARD_CURSOR
                        self._currentCursor = wx.STANDARD_CURSOR

                if setCursor:
                    self.SetCursor(self._currentCursor)
                else:
                    column = self.HitTestColumn(columnX, columnY)
                    self._enter = True
                    self._currentColumn = column

                    if _VERSION_STRING < "2.9":
                        leftDown = wx.GetMouseState().LeftDown()
                    else:
                        leftDown = wx.GetMouseState().LeftIsDown()

                    self._leftDown = leftDown

                    self.Refresh()

            elif event.ButtonDClick():

                self.HandleColumnCheck(self._column, event.GetPosition())

[docs]    def HandleColumnCheck(self, column, pos):
        """
        Handles the case in which a column contains a checkbox-like item.

        :param `column`: the column index;
        :param `pos`: the mouse position.
        """

        if column < 0 or column >= self._owner.GetColumnCount():
            return False

        colItem = self._owner.GetColumn(column)
        # Let's see if it is a checkbox-type item

        kind = (self._isFooter and [colItem.GetFooterKind()] or [colItem.GetKind()])[0]
        if kind not in [1, 2]:
            return False

        x = HEADER_OFFSET_X

        for i in xrange(self._owner.GetColumnCount()):

            if not self.IsColumnShown(i):
                continue

            if i == self._column:
                theX = x
                break
            x += self._owner.GetColumnWidth(i)

        parent = self.GetParent()

        w, h = self.GetClientSize()
        ix, iy = self._owner.GetCheckboxImageSize()
        rect = wx.Rect(theX + HEADER_OFFSET_X, HEADER_OFFSET_Y + (h - 4 - iy)/2, ix, iy)

        if rect.Contains(pos):
            # User clicked on the checkbox
            evt = (self._isFooter and [wxEVT_COMMAND_LIST_FOOTER_CHECKING] or [wxEVT_COMMAND_LIST_COL_CHECKING])[0]
            if self.SendListEvent(evt, pos):
                # No veto for the item checking
                if self._isFooter:
                    isChecked = colItem.IsFooterChecked()
                    colItem.CheckFooter(not isChecked)
                else:
                    isChecked = colItem.IsChecked()
                    colItem.Check(not isChecked)

                self._owner.SetColumn(column, colItem)
                evt = (self._isFooter and [wxEVT_COMMAND_LIST_FOOTER_CHECKED] or [wxEVT_COMMAND_LIST_COL_CHECKED])[0]
                self.SendListEvent(evt, pos)
                self.RefreshRect(rect)

                if self._isFooter:
                    return True

                if parent.HasAGWFlag(ULC_AUTO_CHECK_CHILD):
                    self._owner.AutoCheckChild(isChecked, self._column)
                elif parent.HasAGWFlag(ULC_AUTO_TOGGLE_CHILD):
                    self._owner.AutoToggleChild(self._column)

                return True

        return False

[docs]    def OnEnterWindow(self, event):
        """
        Handles the ``wx.EVT_ENTER_WINDOW`` event for L{UltimateListHeaderWindow}.

        :param `event`: a `wx.MouseEvent` event to be processed.
        """

        x, y = self._owner.CalcUnscrolledPosition(*self.ScreenToClient(wx.GetMousePosition()))
        column = self.HitTestColumn(x, y)

        if _VERSION_STRING < "2.9":
            leftDown = wx.GetMouseState().LeftDown()
        else:
            leftDown = wx.GetMouseState().LeftIsDown()

        self._leftDown = leftDown
        self._enter = column >= 0 and column < self._owner.GetColumnCount()
        self._currentColumn = column
        self.Refresh()

[docs]    def OnLeaveWindow(self, event):
        """
        Handles the ``wx.EVT_LEAVE_WINDOW`` event for L{UltimateListHeaderWindow}.

        :param `event`: a `wx.MouseEvent` event to be processed.
        """

        self._enter = False
        self._leftDown = False

        self._currentColumn = -1
        self.Refresh()

[docs]    def HitTestColumn(self, x, y):
        """
        HitTest method for column headers.

        :param `x`: the mouse `x` position;
        :param `y`: the mouse `y` position.

        :return: The column index if any column client rectangle contains the mouse
         position, ``wx.NOT_FOUND`` otherwise.
        """

        xOld = 0

        for i in xrange(self._owner.GetColumnCount()):
            if not self.IsColumnShown(i):
                continue

            xOld += self._owner.GetColumnWidth(i)
            if x <= xOld:
                return i

        return -1

[docs]    def OnSetFocus(self, event):
        """
        Handles the ``wx.EVT_SET_FOCUS`` event for L{UltimateListHeaderWindow}.

        :param `event`: a `wx.FocusEvent` event to be processed.
        """

        self._owner.SetFocusIgnoringChildren()
        self._owner.Update()

[docs]    def SendListEvent(self, eventType, pos):
        """
        Sends a L{UltimateListEvent} for the parent window.

        :param `eventType`: the event type;
        :param `pos`: an instance of `wx.Point`.
        """

        parent = self.GetParent()
        le = UltimateListEvent(eventType, parent.GetId())
        le.SetEventObject(parent)
        le.m_pointDrag = pos

        # the position should be relative to the parent window, not
        # this one for compatibility with MSW and common sense: the
        # user code doesn't know anything at all about this header
        # window, so why should it get positions relative to it?
        le.m_pointDrag.y -= self.GetSize().y

        le.m_col = self._column
        return (not parent.GetEventHandler().ProcessEvent(le) or le.IsAllowed())

[docs]    def GetOwner(self):
        """ Returns the header window owner, an instance of L{UltimateListCtrl}. """

        return self._owner

#-----------------------------------------------------------------------------
#  UltimateListRenameTimer (internal)
#-----------------------------------------------------------------------------

[docs]class UltimateListRenameTimer(wx.Timer):
    """ Timer used for enabling in-place edit. """

[docs]    def __init__(self, owner):
        """
        Default class constructor.
        For internal use: do not call it in your code!

        :param `owner`: an instance of L{UltimateListCtrl}.
        """

        wx.Timer.__init__(self)
        self._owner = owner

[docs]    def Notify(self):
        """ The timer has expired. """

        self._owner.OnRenameTimer()

#-----------------------------------------------------------------------------
#  UltimateListTextCtrl (internal)
#-----------------------------------------------------------------------------

[docs]class UltimateListTextCtrl(ExpandoTextCtrl):
    """
    Control used for in-place edit.

    This is a subclass of `ExpandoTextCtrl` as L{UltimateListCtrl} supports multiline
    text items.

    :note: To add a newline character in a multiline item, press ``Shift`` + ``Enter``
     as the ``Enter`` key alone is consumed by L{UltimateListCtrl} to finish
     the editing and ``Ctrl`` + ``Enter`` is consumed by the platform for tab navigation.
    """

[docs]    def __init__(self, owner, itemEdit):
        """
        Default class constructor.
        For internal use: do not call it in your code!

        :param `owner`: the control parent (an instance of L{UltimateListCtrl} );
        :param `itemEdit`: an instance of L{UltimateListItem}.
        """

        self._startValue = owner.GetItemText(itemEdit)
        self._currentValue = self._startValue

        self._itemEdited = itemEdit

        self._owner = owner
        self._finished = False
        self._aboutToFinish = False

        rectLabel = owner.GetLineLabelRect(itemEdit)
        rectLabel.x, rectLabel.y = self._owner.CalcScrolledPosition(rectLabel.x, rectLabel.y)
        xSize, ySize = rectLabel.width + 10, rectLabel.height

        expandoStyle = wx.WANTS_CHARS
        if wx.Platform in ["__WXGTK__", "__WXMAC__"]:
            expandoStyle |= wx.SIMPLE_BORDER
        else:
            expandoStyle |= wx.SUNKEN_BORDER

        ExpandoTextCtrl.__init__(self, owner, -1, self._startValue, wx.Point(rectLabel.x, rectLabel.y),
                                 wx.Size(xSize, ySize), expandoStyle)

        self.Bind(wx.EVT_CHAR, self.OnChar)
        self.Bind(wx.EVT_KEY_UP, self.OnKeyUp)
        self.Bind(wx.EVT_KILL_FOCUS, self.OnKillFocus)

[docs]    def AcceptChanges(self):
        """ Accepts/refuses the changes made by the user. """

        value = self.GetValue()

        if value == self._startValue:
            # nothing changed, always accept
            # when an item remains unchanged, the owner
            # needs to be notified that the user decided
            # not to change the tree item label, and that
            # the edit has been cancelled
            self._owner.OnRenameCancelled(self._itemEdited)
            return True

        if not self._owner.OnRenameAccept(self._itemEdited, value):
            # vetoed by the user
            return False

        # accepted, do rename the item
        self._owner.SetItemText(self._itemEdited, value)

        if value.count("\n") != self._startValue.count("\n"):
            self._owner.ResetLineDimensions()
            self._owner.Refresh()

        return True

[docs]    def Finish(self):
        """ Finish editing. """

        try:
            if not self._finished:
                self._finished = True
                self._owner.SetFocusIgnoringChildren()
                self._owner.ResetTextControl()
        except wx.PyDeadObjectError:
            return

[docs]    def OnChar(self, event):
        """
        Handles the ``wx.EVT_CHAR`` event for L{UltimateListTextCtrl}.

        :param `event`: a `wx.KeyEvent` event to be processed.
        """

        keycode = event.GetKeyCode()
        shiftDown = event.ShiftDown()

        if keycode in [wx.WXK_RETURN, wx.WXK_NUMPAD_ENTER]:
            if shiftDown:
                event.Skip()
            else:
                self._aboutToFinish = True
                self.SetValue(self._currentValue)
                # Notify the owner about the changes
                self.AcceptChanges()
                # Even if vetoed, close the control (consistent with MSW)
                wx.CallAfter(self.Finish)

        elif keycode == wx.WXK_ESCAPE:
            self.StopEditing()

        else:
            event.Skip()

[docs]    def OnKeyUp(self, event):
        """
        Handles the ``wx.EVT_KEY_UP`` event for L{UltimateListTextCtrl}.

        :param `event`: a `wx.KeyEvent` event to be processed.
        """

        if not self._finished:

            # auto-grow the textctrl:
            parentSize = self._owner.GetSize()
            myPos = self.GetPosition()
            mySize = self.GetSize()

            dc = wx.ClientDC(self)
            sx, sy, dummy = dc.GetMultiLineTextExtent(self.GetValue() + "M")

            if myPos.x + sx > parentSize.x:
                sx = parentSize.x - myPos.x
            if mySize.x > sx:
                sx = mySize.x

            self.SetSize((sx, -1))
            self._currentValue = self.GetValue()

        event.Skip()

[docs]    def OnKillFocus(self, event):
        """
        Handles the ``wx.EVT_KILL_FOCUS`` event for L{UltimateListTextCtrl}.

        :param `event`: a `wx.FocusEvent` event to be processed.
        """

        if not self._finished and not self._aboutToFinish:

            # We must finish regardless of success, otherwise we'll get
            # focus problems:

            if not self.AcceptChanges():
                self._owner.OnRenameCancelled(self._itemEdited)

        # We must let the native text control handle focus, too, otherwise
        # it could have problems with the cursor (e.g., in wxGTK).
        event.Skip()
        wx.CallAfter(self.Finish)

[docs]    def StopEditing(self):
        """ Suddenly stops the editing. """

        self._owner.OnRenameCancelled(self._itemEdited)
        self.Finish()

#-----------------------------------------------------------------------------
#  UltimateListMainWindow (internal)
#-----------------------------------------------------------------------------

[docs]class UltimateListMainWindow(wx.PyScrolledWindow):
    """
    This is the main widget implementation of L{UltimateListCtrl}.
    """

[docs]    def __init__(self, parent, id, pos=wx.DefaultPosition,
                 size=wx.DefaultSize, style=0, agwStyle=0, name="listctrlmainwindow"):
        """
        Default class constructor.

        :param `parent`: parent window. Must not be ``None``;
        :param `id`: window identifier. A value of -1 indicates a default value;
        :param `pos`: the control position. A value of (-1, -1) indicates a default position,
         chosen by either the windowing system or wxPython, depending on platform;
        :param `size`: the control size. A value of (-1, -1) indicates a default size,
         chosen by either the windowing system or wxPython, depending on platform;
        :param `style`: the underlying `wx.PyScrolledWindow` window style;
        :param `agwStyle`: the AGW-specific window style; can be almost any combination of the following
         bits:

         ===============================  =========== ====================================================================================================
         Window Styles                    Hex Value   Description
         ===============================  =========== ====================================================================================================
         ``ULC_VRULES``                           0x1 Draws light vertical rules between rows in report mode.
         ``ULC_HRULES``                           0x2 Draws light horizontal rules between rows in report mode.
         ``ULC_ICON``                             0x4 Large icon view, with optional labels.
         ``ULC_SMALL_ICON``                       0x8 Small icon view, with optional labels.
         ``ULC_LIST``                            0x10 Multicolumn list view, with optional small icons. Columns are computed automatically, i.e. you don't set columns as in ``ULC_REPORT``. In other words, the list wraps, unlike a `wx.ListBox`.
         ``ULC_REPORT``                          0x20 Single or multicolumn report view, with optional header.
         ``ULC_ALIGN_TOP``                       0x40 Icons align to the top. Win32 default, Win32 only.
         ``ULC_ALIGN_LEFT``                      0x80 Icons align to the left.
         ``ULC_AUTOARRANGE``                    0x100 Icons arrange themselves. Win32 only.
         ``ULC_VIRTUAL``                        0x200 The application provides items text on demand. May only be used with ``ULC_REPORT``.
         ``ULC_EDIT_LABELS``                    0x400 Labels are editable: the application will be notified when editing starts.
         ``ULC_NO_HEADER``                      0x800 No header in report mode.
         ``ULC_NO_SORT_HEADER``                0x1000 No Docs.
         ``ULC_SINGLE_SEL``                    0x2000 Single selection (default is multiple).
         ``ULC_SORT_ASCENDING``                0x4000 Sort in ascending order. (You must still supply a comparison callback in `wx.ListCtrl.SortItems`.)
         ``ULC_SORT_DESCENDING``               0x8000 Sort in descending order. (You must still supply a comparison callback in `wx.ListCtrl.SortItems`.)
         ``ULC_TILE``                         0x10000 Each item appears as a full-sized icon with a label of one or more lines beside it (partially implemented).
         ``ULC_NO_HIGHLIGHT``                 0x20000 No highlight when an item is selected.
         ``ULC_STICKY_HIGHLIGHT``             0x40000 Items are selected by simply hovering on them, with no need to click on them.
         ``ULC_STICKY_NOSELEVENT``            0x80000 Don't send a selection event when using ``ULC_STICKY_HIGHLIGHT`` style.
         ``ULC_SEND_LEFTCLICK``              0x100000 Send a left click event when an item is selected.
         ``ULC_HAS_VARIABLE_ROW_HEIGHT``     0x200000 The list has variable row heights.
         ``ULC_AUTO_CHECK_CHILD``            0x400000 When a column header has a checkbox associated, auto-check all the subitems in that column.
         ``ULC_AUTO_TOGGLE_CHILD``           0x800000 When a column header has a checkbox associated, toggle all the subitems in that column.
         ``ULC_AUTO_CHECK_PARENT``          0x1000000 Only meaningful foe checkbox-type items: when an item is checked/unchecked its column header item is checked/unchecked as well.
         ``ULC_SHOW_TOOLTIPS``              0x2000000 Show tooltips for ellipsized items/subitems (text too long to be shown in the available space) containing the full item/subitem text.
         ``ULC_HOT_TRACKING``               0x4000000 Enable hot tracking of items on mouse motion.
         ``ULC_BORDER_SELECT``              0x8000000 Changes border colour whan an item is selected, instead of highlighting the item.
         ``ULC_TRACK_SELECT``              0x10000000 Enables hot-track selection in a list control. Hot track selection means that an item is automatically selected when the cursor remains over the item for a certain period of time. The delay is retrieved on Windows using the `win32api` call `win32gui.SystemParametersInfo(win32con.SPI_GETMOUSEHOVERTIME)`, and is defaulted to 400ms on other platforms. This style applies to all views of `UltimateListCtrl`.
         ``ULC_HEADER_IN_ALL_VIEWS``       0x20000000 Show column headers in all view modes.
         ``ULC_NO_FULL_ROW_SELECT``        0x40000000 When an item is selected, the only the item in the first column is highlighted.
         ``ULC_FOOTER``                    0x80000000 Show a footer too (only when header is present).
         ``ULC_USER_ROW_HEIGHT``          0x100000000 Allows to set a custom row height (one value for all the items, only in report mode).
         ===============================  =========== ====================================================================================================

        :param `name`: the window name.
        """

        wx.PyScrolledWindow.__init__(self, parent, id, pos, size, style|wx.HSCROLL|wx.VSCROLL, name)

        # the list of column objects
        self._columns = []

        # the array of all line objects for a non virtual list control (for the
        # virtual list control we only ever use self._lines[0])
        self._lines = []

        # currently focused item or -1
        self._current = -1

        # the number of lines per page
        self._linesPerPage = 0

        # Automatically resized column - this column expands to fill the width of the window
        self._resizeColumn = -1
        self._resizeColMinWidth = None

        # this flag is set when something which should result in the window
        # redrawing happens (i.e. an item was added or deleted, or its appearance
        # changed) and OnPaint() doesn't redraw the window while it is set which
        # allows to minimize the number of repaintings when a lot of items are
        # being added. The real repainting occurs only after the next OnIdle()
        # call
        self._dirty = False
        self._parent = parent
        self.Init()

        self._highlightBrush = wx.Brush(wx.SystemSettings.GetColour(wx.SYS_COLOUR_HIGHLIGHT), wx.SOLID)

        btnshadow = wx.SystemSettings_GetColour(wx.SYS_COLOUR_BTNSHADOW)
        self._highlightUnfocusedBrush = wx.Brush(btnshadow, wx.SOLID)
        r, g, b = btnshadow.Red(), btnshadow.Green(), btnshadow.Blue()
        backcolour = (max((r >> 1) - 20, 0),
                      max((g >> 1) - 20, 0),
                      max((b >> 1) - 20, 0))
        backcolour = wx.Colour(backcolour[0], backcolour[1], backcolour[2])
        self._highlightUnfocusedBrush2 = wx.Brush(backcolour)

        self.SetScrollbars(0, 0, 0, 0, 0, 0)

        attr = wx.ListCtrl.GetClassDefaultAttributes()
        self.SetOwnForegroundColour(attr.colFg)
        self.SetOwnBackgroundColour(attr.colBg)
        self.SetOwnFont(attr.font)

        self.Bind(wx.EVT_PAINT, self.OnPaint)
        self.Bind(wx.EVT_ERASE_BACKGROUND, self.OnEraseBackground)
        self.Bind(wx.EVT_MOUSE_EVENTS, self.OnMouse)
        self.Bind(wx.EVT_CHILD_FOCUS, self.OnChildFocus)
        self.Bind(wx.EVT_CHAR, self.OnChar)
        self.Bind(wx.EVT_KEY_DOWN, self.OnKeyDown)
        self.Bind(wx.EVT_KEY_UP, self.OnKeyUp)
        self.Bind(wx.EVT_SET_FOCUS, self.OnSetFocus)
        self.Bind(wx.EVT_KILL_FOCUS, self.OnKillFocus)
        self.Bind(wx.EVT_SCROLLWIN, self.OnScroll)
        self.Bind(wx.EVT_TIMER, self.OnHoverTimer, self._hoverTimer)

[docs]    def Init(self):
        """ Initializes the L{UltimateListMainWindow} widget. """

        self._dirty = True
        self._countVirt = 0
        self._lineFrom = None
        self._lineTo = - 1
        self._linesPerPage = 0

        self._headerWidth = 0
        self._lineHeight = 0
        self._userLineHeight = None

        self._small_image_list = None
        self._normal_image_list = None

        self._small_spacing = 30
        self._normal_spacing = 40

        self._hasFocus = False
        self._dragCount = 0
        self._isCreated = False

        self._lastOnSame = False
        self._renameTimer = UltimateListRenameTimer(self)
        self._textctrl = None

        self._current = -1
        self._lineLastClicked = -1
        self._lineSelectSingleOnUp = -1
        self._lineBeforeLastClicked = -1

        self._dragStart = wx.Point(-1, -1)
        self._aColWidths = []

        self._selStore = SelectionStore()
        self.SetBackgroundStyle(wx.BG_STYLE_CUSTOM)

        # Background image settings
        self._backgroundImage = None
        self._imageStretchStyle = _StyleTile

        # Disabled items colour
        self._disabledColour = wx.Colour(180, 180, 180)

        # Gradient selection colours
        self._firstcolour = colour= wx.SystemSettings_GetColour(wx.SYS_COLOUR_HIGHLIGHT)
        self._secondcolour = wx.WHITE
        self._usegradients = False
        self._gradientstyle = 1   # Vertical Gradient

        # Vista Selection Styles
        self._vistaselection = False

        self.SetImageListCheck(16, 16)

        # Disabled items colour
        self._disabledColour = wx.Colour(180, 180, 180)

        # Hyperlinks things
        normalFont = wx.SystemSettings_GetFont(wx.SYS_DEFAULT_GUI_FONT)
        self._hypertextfont = wx.Font(normalFont.GetPointSize(), normalFont.GetFamily(),
                                      normalFont.GetStyle(), wx.NORMAL, True,
                                      normalFont.GetFaceName(), normalFont.GetEncoding())
        self._hypertextnewcolour = wx.BLUE
        self._hypertextvisitedcolour = wx.Colour(200, 47, 200)
        self._isonhyperlink = False

        self._itemWithWindow = []
        self._hasWindows = False
        self._shortItems = []

        self._isDragging = False
        self._cursor = wx.STANDARD_CURSOR

        image = GetdragcursorImage()

        # since this image didn't come from a .cur file, tell it where the hotspot is
        image.SetOptionInt(wx.IMAGE_OPTION_CUR_HOTSPOT_X, 1)
        image.SetOptionInt(wx.IMAGE_OPTION_CUR_HOTSPOT_Y, 1)

        # make the image into a cursor
        self._dragCursor = wx.CursorFromImage(image)
        self._dragItem = None
        self._dropTarget = None

        self._oldHotCurrent = None
        self._newHotCurrent = None

        self._waterMark = None

        self._hoverTimer = wx.Timer(self, wx.ID_ANY)
        self._hoverItem = -1

[docs]    def GetMainWindowOfCompositeControl(self):
        """ Returns the L{UltimateListMainWindow} parent. """

        return self.GetParent()

[docs]    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 wx.Size(100, 80)

[docs]    def HasAGWFlag(self, flag):
        """
        Returns ``True`` if the window has the given `flag` bit set.

        :param `flag`: the bit to check.

        :see: L{UltimateListCtrl.SetSingleStyle} for a list of valid flags.
        """

        return self._parent.HasAGWFlag(flag)

[docs]    def IsColumnShown(self, column):
        """
        Returns ``True`` if the input column is shown, ``False`` if it is hidden.

        :param `column`: an integer specifying the column index.
        """

        return self.GetColumn(column).IsShown()

    # return True if this is a virtual list control

[docs]    def IsVirtual(self):
        """ Returns ``True`` if the window has the ``ULC_VIRTUAL`` style set. """

        return self.HasAGWFlag(ULC_VIRTUAL)

    # return True if the control is in report mode

[docs]    def InReportView(self):
        """ Returns ``True`` if the window is in report mode. """

        return self.HasAGWFlag(ULC_REPORT)

[docs]    def InTileView(self):
        """
        Returns ``True`` if the window is in tile mode (partially implemented).

        :todo: Fully implement tile view for L{UltimateListCtrl}.
        """

        return self.HasAGWFlag(ULC_TILE)

    # return True if we are in single selection mode, False if multi sel

[docs]    def IsSingleSel(self):
        """ Returns ``True`` if we are in single selection mode, ``False`` if multi selection. """

        return self.HasAGWFlag(ULC_SINGLE_SEL)

[docs]    def HasFocus(self):
        """ Returns ``True`` if the window has focus. """

        return self._hasFocus

    # do we have a header window?

[docs]    def HasHeader(self):
        """ Returns ``True`` if the header window is shown. """

        if (self.InReportView() or self.InTileView()) and not self.HasAGWFlag(ULC_NO_HEADER):
            return True
        if self.HasAGWFlag(ULC_HEADER_IN_ALL_VIEWS):
            return True

        return False

    # do we have a footer window?

[docs]    def HasFooter(self):
        """ Returns ``True`` if the footer window is shown. """

        if self.HasHeader() and self.HasAGWFlag(ULC_FOOTER):
            return True

        return False

    # toggle the line state and refresh it

[docs]    def ReverseHighlight(self, line):
        """
        Toggles the line state and refreshes it.

        :param `line`: an instance of L{UltimateListLineData}.
        """

        self.HighlightLine(line, not self.IsHighlighted(line))
        self.RefreshLine(line)

[docs]    def SetUserLineHeight(self, height):
        """
        Sets a custom value for the L{UltimateListMainWindow} item height.

        :param `height`: the custom height for all the items, in pixels.

        :note: This method can be used only with ``ULC_REPORT`` and ``ULC_USER_ROW_HEIGHT`` styles set.
        """

        if self.HasAGWFlag(ULC_REPORT) and self.HasAGWFlag(ULC_USER_ROW_HEIGHT):
            self._userLineHeight = height
            return

        raise Exception("SetUserLineHeight can only be used with styles ULC_REPORT and ULC_USER_ROW_HEIGHT set.")

[docs]    def GetUserLineHeight(self):
        """
        Returns the custom value for the L{UltimateListMainWindow} item height, if previously set with
        L{SetUserLineHeight}.

        :note: This method can be used only with ``ULC_REPORT`` and ``ULC_USER_ROW_HEIGHT`` styles set.
        """

        if self.HasAGWFlag(ULC_REPORT) and self.HasAGWFlag(ULC_USER_ROW_HEIGHT):
            return self._userLineHeight

        raise Exception("GetUserLineHeight can only be used with styles ULC_REPORT and ULC_USER_ROW_HEIGHT set.")

    # get the size of the total line rect

[docs]    def GetLineSize(self, line):
        """
        Returns the size of the total line client rectangle.

        :param `line`: an instance of L{UltimateListLineData}.
        """

        return self.GetLineRect(line).GetSize()

    # bring the current item into view

[docs]    def MoveToFocus(self):
        """ Brings tyhe current item into view. """

        self.MoveToItem(self._current)

[docs]    def GetColumnCount(self):
        """ Returns the total number of columns in the L{UltimateListCtrl}. """

        return len(self._columns)

[docs]    def GetItemText(self, item):
        """
        Returns the item text.

        :param `item`: an instance of L{UltimateListItem}.
        """

        info = UltimateListItem()
        info._mask = ULC_MASK_TEXT
        info._itemId = item
        info = self.GetItem(info)

        return info._text

[docs]    def SetItemText(self, item, value):
        """
        Sets the item text.

        :param `item`: an instance of L{UltimateListItem};
        :param `value`: the new item text.
        """

        info = UltimateListItem()
        info._mask = ULC_MASK_TEXT
        info._itemId = item
        info._text = value

        self.SetItem(info)

[docs]    def IsEmpty(self):
        """ Returns ``True`` if the window has no items in it. """

        return self.GetItemCount() == 0

[docs]    def ResetCurrent(self):
        """ Resets the current item to ``None``. """

        self.ChangeCurrent(-1)

[docs]    def HasCurrent(self):
        """
        Returns ``True`` if the current item has been set, either programmatically
        or by user intervention.
        """

        return self._current != -1

    # override base class virtual to reset self._lineHeight when the font changes

[docs]    def SetFont(self, font):
        """
        Overridden base class virtual to reset the line height when the font changes.

        :param `font`: a valid `wx.Font` object.

        :note: Overridden from `wx.PyScrolledWindow`.
        """

        if not wx.PyScrolledWindow.SetFont(self, font):
            return False

        self._lineHeight = 0
        self.ResetLineDimensions()

        return True

[docs]    def ResetLineDimensions(self, force=False):
        """
        Resets the line dimensions, so that client rectangles and positions are
        recalculated.

        :param `force`: ``True`` to reset all line dimensions.
        """

        if (self.HasAGWFlag(ULC_REPORT) and self.HasAGWFlag(ULC_HAS_VARIABLE_ROW_HEIGHT) and not self.IsVirtual()) or force:
            for l in xrange(self.GetItemCount()):
                line = self.GetLine(l)
                line.ResetDimensions()

    # these are for UltimateListLineData usage only
    # get the backpointer to the list ctrl

[docs]    def GetListCtrl(self):
        """ Returns the parent widget, an instance of L{UltimateListCtrl}. """

        return self.GetParent()

    # get the brush to use for the item highlighting

[docs]    def GetHighlightBrush(self):
        """ Returns the brush to use for the item highlighting. """

        return (self._hasFocus and [self._highlightBrush] or [self._highlightUnfocusedBrush])[0]

    # get the line data for the given index

[docs]    def GetLine(self, n):
        """
        Returns the line data for the given index.

        :param `n`: the line index.
        """

        if self.IsVirtual():

            self.CacheLineData(n)
            n = 0

        return self._lines[n]

    # force us to recalculate the range of visible lines

[docs]    def ResetVisibleLinesRange(self, reset=False):
        """
        Forces us to recalculate the range of visible lines.

        :param `reset`: ``True`` to reset all line dimensions, which will then be
         recalculated.
        """

        self._lineFrom = -1
        if self.IsShownOnScreen() and reset:
            self.ResetLineDimensions()

    # Called on EVT_SIZE to resize the _resizeColumn to fill the width of the window

[docs]    def ResizeColumns(self):
        """
        If ``ULC_AUTOSIZE_FILL`` was passed to L{UltimateListCtrl.SetColumnWidth} then
        that column's width will be expanded to fill the window on a resize event.

        Called by L{UltimateListCtrl.OnSize} when the window is resized.
        """

        if not self: # Avoid PyDeadObjectErrors on Mac
            return

        if self._resizeColumn == -1:
            return

        numCols = self.GetColumnCount()
        if numCols == 0: return # Nothing to resize.

        resizeCol = self._resizeColumn

        if self._resizeColMinWidth == None:
            self._resizeColMinWidth = self.GetColumnWidth(resizeCol)

        # We're showing the vertical scrollbar -> allow for scrollbar width
        # NOTE: on GTK, the scrollbar is included in the client size, but on
        # Windows it is not included
        listWidth = self.GetClientSize().width
        if wx.Platform != '__WXMSW__':
            if self.GetItemCount() > self.GetCountPerPage():
                scrollWidth = wx.SystemSettings_GetMetric(wx.SYS_VSCROLL_X)
                listWidth = listWidth - scrollWidth

        totColWidth = 0 # Width of all columns except last one.
        for col in range(numCols):
            if col != (resizeCol) and self.IsColumnShown(col):
                totColWidth = totColWidth + self.GetColumnWidth(col)

        resizeColWidth = self.GetColumnWidth(resizeCol)

        if totColWidth + self._resizeColMinWidth > listWidth:
            # We haven't got the width to show the last column at its minimum
            # width -> set it to its minimum width and allow the horizontal
            # scrollbar to show.
            self.SetColumnWidth(resizeCol, self._resizeColMinWidth)
            return

        # Resize the last column to take up the remaining available space.
        self.SetColumnWidth(resizeCol, listWidth - totColWidth)

    # get the colour to be used for drawing the rules

[docs]    def GetRuleColour(self):
        """ Returns the colour to be used for drawing the horizontal and vertical rules. """

        return wx.SystemSettings.GetColour(wx.SYS_COLOUR_3DLIGHT)

[docs]    def SetReportView(self, inReportView):
        """
        Sets whether L{UltimateListCtrl} is in report view or not.

        :param `inReportView`: ``True`` to set L{UltimateListCtrl} in report view, ``False``
         otherwise.
        """

        for line in self._lines:
            line.SetReportView(inReportView)

[docs]    def CacheLineData(self, line):
        """
        Saves the current line attributes.

        :param `line`: an instance of L{UltimateListLineData}.

        :note: This method is used only if the L{UltimateListCtrl} has the ``ULC_VIRTUAL``
         style set.
        """

        listctrl = self.GetListCtrl()
        ld = self.GetDummyLine()

        countCol = self.GetColumnCount()
        for col in xrange(countCol):
            ld.SetText(col, listctrl.OnGetItemText(line, col))
            ld.SetToolTip(col, listctrl.OnGetItemToolTip(line, col))
            ld.SetColour(col, listctrl.OnGetItemTextColour(line, col))
            ld.SetImage(col, listctrl.OnGetItemColumnImage(line, col))
            kind = listctrl.OnGetItemColumnKind(line, col)
            ld.SetKind(col, kind)
            if kind > 0:
                ld.Check(col, listctrl.OnGetItemColumnCheck(line, col))

        ld.SetAttr(listctrl.OnGetItemAttr(line))

[docs]    def GetDummyLine(self):
        """
        Returns a dummy line.

        :note: This method is used only if the L{UltimateListCtrl} has the ``ULC_VIRTUAL``
         style set.
        """

        if self.IsEmpty():
            raise Exception("invalid line index")

        if not self.IsVirtual():
            raise Exception("GetDummyLine() shouldn't be called")

        # we need to recreate the dummy line if the number of columns in the
        # control changed as it would have the incorrect number of fields
        # otherwise
        if len(self._lines) > 0 and len(self._lines[0]._items) != self.GetColumnCount():
            self._lines = []

        if not self._lines:
            line = UltimateListLineData(self)
            self._lines.append(line)

        return self._lines[0]

# ----------------------------------------------------------------------------
# line geometry (report mode only)
# ----------------------------------------------------------------------------

[docs]    def GetLineHeight(self, item=None):
        """
        Returns the line height for a specific item.

        :param `item`: if not ``None``, an instance of L{UltimateListItem}.
        """

        # we cache the line height as calling GetTextExtent() is slow

        if self.HasAGWFlag(ULC_REPORT) and self.HasAGWFlag(ULC_USER_ROW_HEIGHT):
            if self._userLineHeight is not None:
                return self._userLineHeight

        if item is None or not self.HasAGWFlag(ULC_HAS_VARIABLE_ROW_HEIGHT):

            if not self._lineHeight:
                dc = wx.ClientDC(self)
                dc.SetFont(self.GetFont())

                dummy, y = dc.GetTextExtent("H")
                if self._small_image_list and self._small_image_list.GetImageCount():
                    iw, ih = self._small_image_list.GetSize(0)
                    y = max(y, ih)

                y += EXTRA_HEIGHT
                self._lineHeight = y + LINE_SPACING

            return self._lineHeight

        else:

            line = self.GetLine(item)
            LH = line.GetHeight()
            if LH != -1:
                return LH

            dc = wx.ClientDC(self)

            allTextY = 0

            for col, items in enumerate(line._items):

                if items.GetCustomRenderer():
                    allTextY = max(allTextY, items.GetCustomRenderer().GetLineHeight())
                    continue

                if items.HasFont():
                    dc.SetFont(items.GetFont())
                else:
                    dc.SetFont(self.GetFont())

                text_x, text_y, dummy = dc.GetMultiLineTextExtent(items.GetText())
                allTextY = max(text_y, allTextY)

                if items.GetWindow():
                    xSize, ySize = items.GetWindowSize()
                    allTextY = max(allTextY, ySize)

                if self._small_image_list and self._small_image_list.GetImageCount():
                    for img in items._image:
                        iw, ih = self._small_image_list.GetSize(img)
                        allTextY = max(allTextY, ih)

            allTextY += EXTRA_HEIGHT
            line.SetHeight(allTextY)

            return allTextY

[docs]    def GetLineY(self, line):
        """
        Returns the line `y` position.

        :param `line`: an instance of L{UltimateListLineData}.
        """

        if self.IsVirtual():
            return LINE_SPACING + line*self.GetLineHeight()

        lineItem = self.GetLine(line)
        lineY = lineItem.GetY()
        if lineY != -1:
            return lineY

        lineY = 0
        for l in xrange(line):
            lineY += self.GetLineHeight(l)

        lineItem.SetY(LINE_SPACING + lineY)
        return LINE_SPACING + lineY

[docs]    def GetLineRect(self, line):
        """
        Returns the line client rectangle.

        :param `line`: an instance of L{UltimateListLineData}.
        """

        if not self.InReportView():
            return self.GetLine(line)._gi._rectAll

        rect = wx.Rect(HEADER_OFFSET_X, self.GetLineY(line), self.GetHeaderWidth(), self.GetLineHeight(line))
        return rect

[docs]    def GetLineLabelRect(self, line, col=0):
        """
        Returns the line client rectangle for the item text only.
        Note this is the full column width unless an image or
        checkbox exists. It is not the width of the text itself

        :param `line`: an instance of L{UltimateListLineData}.
        """

        if not self.InReportView():
            return self.GetLine(line)._gi._rectLabel

        image_x = 0
        image_width = 0

        for c in range(col):
            image_x += self.GetColumnWidth(c)

        item = self.GetLine(line)
        if item.HasImage(col):
            ix, iy = self.GetImageSize(item.GetImage(col))
            image_x     += ix
            image_width  = ix

        if item.GetKind(col) in [1, 2]:
            image_x     += self.GetCheckboxImageSize()[0]
            image_width += self.GetCheckboxImageSize()[0]

        rect = wx.Rect(image_x + HEADER_OFFSET_X, self.GetLineY(line), self.GetColumnWidth(col) - image_width, self.GetLineHeight(line))
        return rect

[docs]    def GetLineIconRect(self, line):
        """
        Returns the line client rectangle for the item image only.

        :param `line`: an instance of L{UltimateListLineData}.
        """

        if not self.InReportView():
            return self.GetLine(line)._gi._rectIcon

        ld = self.GetLine(line)

        image_x = HEADER_OFFSET_X
        if ld.GetKind() in [1, 2]:
            image_x += self.GetCheckboxImageSize()[0]

        rect = wx.Rect(image_x, self.GetLineY(line), *self.GetImageSize(ld.GetImage()))
        return rect

[docs]    def GetLineCheckboxRect(self, line):
        """
        Returns the line client rectangle for the item checkbox image only.

        :param `line`: an instance of L{UltimateListLineData}.
        """

        if not self.InReportView():
            return self.GetLine(line)._gi._rectCheck

        ld = self.GetLine(line)
        LH = self.GetLineHeight(line)
        wcheck, hcheck = self.GetCheckboxImageSize()
        rect = wx.Rect(HEADER_OFFSET_X, self.GetLineY(line) + LH/2 - hcheck/2, wcheck, hcheck)
        return rect

[docs]    def GetLineHighlightRect(self, line):
        """
        Returns the line client rectangle when the line is highlighted.

        :param `line`: an instance of L{UltimateListLineData}.
        """

        return (self.InReportView() and [self.GetLineRect(line)] or [self.GetLine(line)._gi._rectHighlight])[0]

[docs]    def HitTestLine(self, line, x, y):
        """
        HitTest method for a L{UltimateListCtrl} line.

        :param `line`: an instance of L{UltimateListLineData};
        :param `x`: the mouse `x` position;
        :param `y`: the mouse `y` position.

        :return: a tuple of values, representing the item hit and a hit flag. The
         hit flag can be one of the following bits:

         =============================== ========= ================================
         HitTest Flag                    Hex Value Description
         =============================== ========= ================================
         ``ULC_HITTEST_ABOVE``                 0x1 Above the client area
         ``ULC_HITTEST_BELOW``                 0x2 Below the client area
         ``ULC_HITTEST_NOWHERE``               0x4 In the client area but below the last item
         ``ULC_HITTEST_ONITEM``              0x2a0 Anywhere on the item (text, icon, checkbox image)
         ``ULC_HITTEST_ONITEMICON``           0x20 On the bitmap associated with an item
         ``ULC_HITTEST_ONITEMLABEL``          0x80 On the label (string) associated with an item
         ``ULC_HITTEST_ONITEMRIGHT``         0x100 In the area to the right of an item
         ``ULC_HITTEST_ONITEMSTATEICON``     0x200 On the state icon for a list view item that is in a user-defined state
         ``ULC_HITTEST_TOLEFT``              0x400 To the left of the client area
         ``ULC_HITTEST_TORIGHT``             0x800 To the right of the client area
         ``ULC_HITTEST_ONITEMCHECK``        0x1000 On the item checkbox (if any)
         =============================== ========= ================================

        """

        ld = self.GetLine(line)

        if self.InReportView():# and not self.IsVirtual():

            lineY = self.GetLineY(line)
            xstart = HEADER_OFFSET_X

            for col, item in enumerate(ld._items):

                if not self.IsColumnShown(col):
                    continue

                width = self.GetColumnWidth(col)
                xOld = xstart
                xstart += width
                ix = 0

                #if (line, col) in self._shortItems:
                    #rect = wx.Rect(xOld, lineY, width, self.GetLineHeight(line))
                rect = self.GetLineLabelRect(line,col)
                if rect.Contains((x, y)):
                    newItem = self.GetParent().GetItem(line, col)
                    return newItem, ULC_HITTEST_ONITEMLABEL

                if item.GetKind() in [1, 2]:
                    # We got a checkbox-type item
                    ix, iy = self.GetCheckboxImageSize()
                    LH = self.GetLineHeight(line)
                    rect = wx.Rect(xOld, lineY + LH/2 - iy/2, ix, iy)
                    if rect.Contains((x, y)):
                        newItem = self.GetParent().GetItem(line, col)
                        return newItem, ULC_HITTEST_ONITEMCHECK

                if item.IsHyperText():
                    start, end = self.GetItemTextSize(item)
                    rect = wx.Rect(xOld+start, lineY, end, self.GetLineHeight(line))
                    if rect.Contains((x, y)):
                        newItem = self.GetParent().GetItem(line, col)
                        return newItem, ULC_HITTEST_ONITEMLABEL

                    xOld += ix

        if ld.HasImage() and self.GetLineIconRect(line).Contains((x, y)):
            return self.GetParent().GetItem(line), ULC_HITTEST_ONITEMICON

        # VS: Testing for "ld.HasText() || InReportView()" instead of
        #     "ld.HasText()" is needed to make empty lines in report view
        #     possible
        if ld.HasText() or self.InReportView():
            if self.InReportView():
                rect = self.GetLineRect(line)
            else:
                checkRect = self.GetLineCheckboxRect(line)
                if checkRect.Contains((x, y)):
                    return self.GetParent().GetItem(line), ULC_HITTEST_ONITEMCHECK

                rect = self.GetLineLabelRect(line)

        if rect.Contains((x, y)):
            return self.GetParent().GetItem(line), ULC_HITTEST_ONITEMLABEL

        rect = self.GetLineRect(line)
        if rect.Contains((x, y)):
            return self.GetParent().GetItem(line), ULC_HITTEST_ONITEM

        return None, 0

# ----------------------------------------------------------------------------
# highlight (selection) handling
# ----------------------------------------------------------------------------

[docs]    def IsHighlighted(self, line):
        """
        Returns ``True`` if the input line is highlighted.

        :param `line`: an instance of L{UltimateListLineData}.
        """

        if self.IsVirtual():

            return self._selStore.IsSelected(line)

        else: # !virtual

            ld = self.GetLine(line)
            return ld.IsHighlighted()

[docs]    def HighlightLines(self, lineFrom, lineTo, highlight=True):
        """
        Highlights a range of lines in L{UltimateListCtrl}.

        :param `lineFrom`: an integer representing the first line to highlight;
        :param `lineTo`: an integer representing the last line to highlight;
        :param `highlight`: ``True`` to highlight the lines, ``False`` otherwise.
        """

        if self.IsVirtual():
            linesChanged = self._selStore.SelectRange(lineFrom, lineTo, highlight)
            if not linesChanged:
                # many items changed state, refresh everything
                self.RefreshLines(lineFrom, lineTo)

            else: # only a few items changed state, refresh only them

                for n in xrange(len(linesChanged)):
                    self.RefreshLine(linesChanged[n])

        else: # iterate over all items in non report view

            for line in xrange(lineFrom, lineTo+1):
                if self.HighlightLine(line, highlight):
                    self.RefreshLine(line)

[docs]    def HighlightLine(self, line, highlight=True):
        """
        Highlights a line in L{UltimateListCtrl}.

        :param `line`: an instance of L{UltimateListLineData};
        :param `highlight`: ``True`` to highlight the line, ``False`` otherwise.
        """

        changed = False

        if self.IsVirtual():

            changed = self._selStore.SelectItem(line, highlight)

        else: # !virtual

            ld = self.GetLine(line)
            changed = ld.Highlight(highlight)

        dontNotify = self.HasAGWFlag(ULC_STICKY_HIGHLIGHT) and self.HasAGWFlag(ULC_STICKY_NOSELEVENT)

        if changed and not dontNotify:
            self.SendNotify(line, (highlight and [wxEVT_COMMAND_LIST_ITEM_SELECTED] or [wxEVT_COMMAND_LIST_ITEM_DESELECTED])[0])

        return changed

[docs]    def RefreshLine(self, line):
        """
        Redraws the input line.

        :param `line`: an instance of L{UltimateListLineData}.
        """

        if self.InReportView():

            visibleFrom, visibleTo = self.GetVisibleLinesRange()
            if line < visibleFrom or line > visibleTo:
                return

        rect = self.GetLineRect(line)
        rect.x, rect.y  = self.CalcScrolledPosition(rect.x, rect.y)
        self.RefreshRect(rect)

[docs]    def RefreshLines(self, lineFrom, lineTo):
        """
        Redraws a range of lines in L{UltimateListCtrl}.

        :param `lineFrom`: an integer representing the first line to refresh;
        :param `lineTo`: an integer representing the last line to refresh.
        """

        if self.InReportView():

            visibleFrom, visibleTo = self.GetVisibleLinesRange()

            if lineFrom < visibleFrom:
                lineFrom = visibleFrom
            if lineTo > visibleTo:
                lineTo = visibleTo

            rect = wx.Rect()
            rect.x = 0
            rect.y = self.GetLineY(lineFrom)
            rect.width = self.GetClientSize().x
            rect.height = self.GetLineY(lineTo) - rect.y + self.GetLineHeight(lineTo)

            rect.x, rect.y  = self.CalcScrolledPosition(rect.x, rect.y)
            self.RefreshRect(rect)

        else: # !report

            # TODO: this should be optimized...
            for line in xrange(lineFrom, lineTo+1):
                self.RefreshLine(line)

[docs]    def RefreshAfter(self, lineFrom):
        """
        Redraws all the lines after the input one.

        :param `lineFrom`: an integer representing the first line to refresh.
        """

        if self.InReportView():

            visibleFrom, visibleTo = self.GetVisibleLinesRange()

            if lineFrom < visibleFrom:
                lineFrom = visibleFrom
            elif lineFrom > visibleTo:
                return

            rect = wx.Rect()
            rect.x = 0
            rect.y = self.GetLineY(lineFrom)
            rect.x, rect.y  = self.CalcScrolledPosition(rect.x, rect.y)

            size = self.GetClientSize()
            rect.width = size.x
            # refresh till the bottom of the window
            rect.height = size.y - rect.y

            self.RefreshRect(rect)

        else: # !report

            # TODO: how to do it more efficiently?
            self._dirty = True

[docs]    def RefreshSelected(self):
        """ Redraws the selected lines. """

        if self.IsEmpty():
            return

        if self.InReportView():

            fromm, to = self.GetVisibleLinesRange()

        else: # !virtual

            fromm = 0
            to = self.GetItemCount() - 1

        if self.HasCurrent() and self._current >= fromm and self._current <= to:
            self.RefreshLine(self._current)

        for line in xrange(fromm, to+1):
            # NB: the test works as expected even if self._current == -1
            if line != self._current and self.IsHighlighted(line):
                self.RefreshLine(line)

[docs]    def HideWindows(self):
        """ Hides the windows associated to the items. Used internally. """

        for child in self._itemWithWindow:
            wnd = child.GetWindow()
            if wnd:
                wnd.Hide()

[docs]    def OnPaint(self, event):
        """
        Handles the ``wx.EVT_PAINT`` event for L{UltimateListMainWindow}.

        :param `event`: a `wx.PaintEvent` event to be processed.
        """

        # Note: a wxPaintDC must be constructed even if no drawing is
        # done (a Windows requirement).
        dc = wx.BufferedPaintDC(self)

        dc.SetBackgroundMode(wx.TRANSPARENT)

        self.PrepareDC(dc)

        dc.SetBackground(wx.Brush(self.GetBackgroundColour()))
        dc.SetPen(wx.TRANSPARENT_PEN)
        dc.Clear()

        self.TileBackground(dc)
        self.PaintWaterMark(dc)

        if self.IsEmpty():
            # nothing to draw or not the moment to draw it
            return

        if self._dirty:
            # delay the repainting until we calculate all the items positions
            self.RecalculatePositions(False)

        useVista, useGradient = self._vistaselection, self._usegradients
        dev_x, dev_y = self.CalcScrolledPosition(0, 0)

        dc.SetFont(self.GetFont())

        if self.InReportView():
            visibleFrom, visibleTo = self.GetVisibleLinesRange()

            # mrcs: draw additional items
            if visibleFrom > 0:
                visibleFrom -= 1

            if visibleTo < self.GetItemCount() - 1:
                visibleTo += 1

            xOrig = dc.LogicalToDeviceX(0)
            yOrig = dc.LogicalToDeviceY(0)

            # tell the caller cache to cache the data
            if self.IsVirtual():

                evCache = UltimateListEvent(wxEVT_COMMAND_LIST_CACHE_HINT, self.GetParent().GetId())
                evCache.SetEventObject(self.GetParent())
                evCache.m_oldItemIndex = visibleFrom
                evCache.m_itemIndex = visibleTo
                self.GetParent().GetEventHandler().ProcessEvent(evCache)

            no_highlight = self.HasAGWFlag(ULC_NO_HIGHLIGHT)

            for line in xrange(visibleFrom, visibleTo+1):
                rectLine = self.GetLineRect(line)

                if not self.IsExposed(rectLine.x + xOrig, rectLine.y + yOrig, rectLine.width, rectLine.height):
                    # don't redraw unaffected lines to avoid flicker
                    continue

                theLine = self.GetLine(line)
                enabled = theLine.GetItem(0, CreateListItem(line, 0)).IsEnabled()
                oldPN, oldBR = dc.GetPen(), dc.GetBrush()
                theLine.DrawInReportMode(dc, line, rectLine,
                                         self.GetLineHighlightRect(line),
                                         self.IsHighlighted(line) and not no_highlight,
                                         line==self._current, enabled, oldPN, oldBR)

            if self.HasAGWFlag(ULC_HRULES):
                pen = wx.Pen(self.GetRuleColour(), 1, wx.SOLID)
                clientSize = self.GetClientSize()

                # Don't draw the first one
                start = (visibleFrom > 0 and [visibleFrom] or [1])[0]

                dc.SetPen(pen)
                dc.SetBrush(wx.TRANSPARENT_BRUSH)
                for i in xrange(start, visibleTo+1):
                    lineY = self.GetLineY(i)
                    dc.DrawLine(0 - dev_x, lineY, clientSize.x - dev_x, lineY)

                # Draw last horizontal rule
                if visibleTo == self.GetItemCount() - 1:
                    lineY = self.GetLineY(visibleTo) + self.GetLineHeight(visibleTo)
                    dc.SetPen(pen)
                    dc.SetBrush(wx.TRANSPARENT_BRUSH)
                    dc.DrawLine(0 - dev_x, lineY, clientSize.x - dev_x , lineY)

            # Draw vertical rules if required
            if self.HasAGWFlag(ULC_VRULES) and not self.IsEmpty():
                pen = wx.Pen(self.GetRuleColour(), 1, wx.SOLID)

                firstItemRect = self.GetItemRect(visibleFrom)
                lastItemRect = self.GetItemRect(visibleTo)
                x = firstItemRect.GetX()
                dc.SetPen(pen)
                dc.SetBrush(wx.TRANSPARENT_BRUSH)
                for col in xrange(self.GetColumnCount()):

                    if not self.IsColumnShown(col):
                        continue

                    colWidth = self.GetColumnWidth(col)
                    x += colWidth

                    x_pos = x - dev_x
                    if col < self.GetColumnCount()-1:
                        x_pos -= 2

                    dc.DrawLine(x_pos, firstItemRect.GetY() - 1 - dev_y, x_pos, lastItemRect.GetBottom() + 1 - dev_y)

        else: # !report

            for i in xrange(self.GetItemCount()):
                self.GetLine(i).Draw(i, dc)

        if wx.Platform not in ["__WXMAC__", "__WXGTK__"]:
            # Don't draw rect outline under Mac at all.
            # Draw it elsewhere on GTK
            if self.HasCurrent():
                if self._hasFocus and not self.HasAGWFlag(ULC_NO_HIGHLIGHT) and not useVista and not useGradient \
                   and not self.HasAGWFlag(ULC_BORDER_SELECT) and not self.HasAGWFlag(ULC_NO_FULL_ROW_SELECT):
                    dc.SetPen(wx.BLACK_PEN)
                    dc.SetBrush(wx.TRANSPARENT_BRUSH)
                    dc.DrawRectangleRect(self.GetLineHighlightRect(self._current))

[docs]    def OnEraseBackground(self, event):
        """
        Handles the ``wx.EVT_ERASE_BACKGROUND`` event for L{UltimateListMainWindow}.

        :param `event`: a `wx.EraseEvent` event to be processed.

        :note: This method is intentionally empty to reduce flicker.
        """

        pass

[docs]    def TileBackground(self, dc):
        """
        Tiles the background image to fill all the available area.

        :param `dc`: an instance of `wx.DC`.

        :todo: Support background images also in stretch and centered modes.
        """

        if not self._backgroundImage:
            return

        if self._imageStretchStyle != _StyleTile:
            # Can we actually do something here (or in OnPaint()) To Handle
            # background images that are stretchable or always centered?
            # I tried but I get enormous flickering...
            return

        sz = self.GetClientSize()
        w = self._backgroundImage.GetWidth()
        h = self._backgroundImage.GetHeight()

        x = 0

        while x < sz.width:
            y = 0

            while y < sz.height:
                dc.DrawBitmap(self._backgroundImage, x, y, True)
                y = y + h

            x = x + w

[docs]    def PaintWaterMark(self, dc):
        """
        Draws a watermark at the bottom right of L{UltimateListCtrl}.

        :param `dc`: an instance of `wx.DC`.

        :todo: Better support for this is needed.
        """

        if not self._waterMark:
            return

        width, height = self.CalcUnscrolledPosition(*self.GetClientSize())

        bitmapW = self._waterMark.GetWidth()
        bitmapH = self._waterMark.GetHeight()

        x = width - bitmapW - 5
        y = height - bitmapH - 5

        dc.DrawBitmap(self._waterMark, x, y, True)

[docs]    def HighlightAll(self, on=True):
        """
        Highlights/unhighlights all the lines in L{UltimateListCtrl}.

        :param `on`: ``True`` to highlight all the lines, ``False`` to unhighlight them.
        """

        if self.IsSingleSel():

            if on:
                raise Exception("can't do this in a single sel control")

            # we just have one item to turn off
            if self.HasCurrent() and self.IsHighlighted(self._current):
                self.HighlightLine(self._current, False)
                self.RefreshLine(self._current)

        else: # multi sel
            if not self.IsEmpty():
                self.HighlightLines(0, self.GetItemCount() - 1, on)

[docs]    def OnChildFocus(self, event):
        """
        Handles the ``wx.EVT_CHILD_FOCUS`` event for L{UltimateListMainWindow}.

        :param `event`: a `wx.ChildFocusEvent` event to be processed.

        :note: This method is intentionally empty to prevent the default handler in
         `wx.PyScrolledWindow` from needlessly scrolling the window when the edit
         control is dismissed.
        """

        # Do nothing here.  This prevents the default handler in wx.PyScrolledWindow
        # from needlessly scrolling the window when the edit control is
        # dismissed.  See ticket #9563.

        pass

[docs]    def SendNotify(self, line, command, point=wx.DefaultPosition):
        """
        Actually sends a L{UltimateListEvent}.

        :param `line`: an instance of L{UltimateListLineData};
        :param `command`: the event type to send;
        :param `point`: an instance of `wx.Point`.
        """

        bRet = True
        le = UltimateListEvent(command, self.GetParent().GetId())
        le.SetEventObject(self.GetParent())
        le.m_itemIndex = line

        # set only for events which have position
        if point != wx.DefaultPosition:
            le.m_pointDrag = point

        # don't try to get the line info for virtual list controls: the main
        # program has it anyhow and if we did it would result in accessing all
        # the lines, even those which are not visible now and this is precisely
        # what we're trying to avoid
        if not self.IsVirtual():

            if line != -1:
                self.GetLine(line).GetItem(0, le.m_item)

            #else: this happens for wxEVT_COMMAND_LIST_ITEM_FOCUSED event

            #else: there may be no more such item

        self.GetParent().GetEventHandler().ProcessEvent(le)
        bRet = le.IsAllowed()

        return bRet

[docs]    def ChangeCurrent(self, current):
        """
        Changes the current line to the specified one.

        :param `current`: an integer specifying the index of the current line.
        """

        self._current = current

        # as the current item changed, we shouldn't start editing it when the
        # "slow click" timer expires as the click happened on another item
        if self._renameTimer.IsRunning():
            self._renameTimer.Stop()

        self.SendNotify(current, wxEVT_COMMAND_LIST_ITEM_FOCUSED)

[docs]    def EditLabel(self, item):
        """
        Starts editing an item label.

        :param `item`: an instance of L{UltimateListItem}.
        """

        if item < 0 or item >= self.GetItemCount():
            raise Exception("wrong index in UltimateListCtrl.EditLabel()")

        le = UltimateListEvent(wxEVT_COMMAND_LIST_BEGIN_LABEL_EDIT, self.GetParent().GetId())
        le.SetEventObject(self.GetParent())
        le.m_itemIndex = item
        data = self.GetLine(item)
        le.m_item = data.GetItem(0, le.m_item)

        self._textctrl = UltimateListTextCtrl(self, item)

        if self.GetParent().GetEventHandler().ProcessEvent(le) and not le.IsAllowed():
            # vetoed by user code
            return

        # We have to call this here because the label in question might just have
        # been added and no screen update taken place.
        if self._dirty:
            wx.SafeYield()
            # Pending events dispatched by wx.SafeYield might have changed the item
            # count
            if item >= self.GetItemCount():
                return None

        # modified
        self._textctrl.SetFocus()

        return self._textctrl

[docs]    def OnRenameTimer(self):
        """ The timer for renaming has expired. Start editing. """

        if not self.HasCurrent():
            raise Exception("unexpected rename timer")

        self.EditLabel(self._current)

[docs]    def OnRenameAccept(self, itemEdit, value):
        """
        Called by L{UltimateListTextCtrl}, to accept the changes and to send the
        ``EVT_LIST_END_LABEL_EDIT`` event.

        :param `itemEdit`: an instance of L{UltimateListItem};
        :param `value`: the new value of the item label.
        """

        le = UltimateListEvent(wxEVT_COMMAND_LIST_END_LABEL_EDIT, self.GetParent().GetId())
        le.SetEventObject(self.GetParent())
        le.m_itemIndex = itemEdit

        data = self.GetLine(itemEdit)

        le.m_item = data.GetItem(0, le.m_item)
        le.m_item._text = value

        return not self.GetParent().GetEventHandler().ProcessEvent(le) or le.IsAllowed()

[docs]    def OnRenameCancelled(self, itemEdit):
        """
        Called by L{UltimateListTextCtrl}, to cancel the changes and to send the
        ``EVT_LIST_END_LABEL_EDIT`` event.

        :param `item`: an instance of L{UltimateListItem}.
        """

        # let owner know that the edit was cancelled
        le = UltimateListEvent(wxEVT_COMMAND_LIST_END_LABEL_EDIT, self.GetParent().GetId())
        le.SetEditCanceled(True)

        le.SetEventObject(self.GetParent())
        le.m_itemIndex = itemEdit

        data = self.GetLine(itemEdit)
        le.m_item = data.GetItem(0, le.m_item)

        self.GetEventHandler().ProcessEvent(le)

[docs]    def OnMouse(self, event):
        """
        Handles the ``wx.EVT_MOUSE_EVENTS`` event for L{UltimateListMainWindow}.

        :param `event`: a `wx.MouseEvent` event to be processed.
        """

        if wx.Platform == "__WXMAC__":
            # On wxMac we can't depend on the EVT_KILL_FOCUS event to properly
            # shutdown the edit control when the mouse is clicked elsewhere on the
            # listctrl because the order of events is different (or something like
            # that,) so explicitly end the edit if it is active.
            if event.LeftDown() and self._textctrl:
                self._textctrl.AcceptChanges()
                self._textctrl.Finish()

        if event.LeftDown():
            self.SetFocusIgnoringChildren()

        event.SetEventObject(self.GetParent())
        if self.GetParent().GetEventHandler().ProcessEvent(event):
            return

        if event.GetEventType() == wx.wxEVT_MOUSEWHEEL:
            # let the base handle mouse wheel events.
            self.Refresh()
            event.Skip()
            return

        if self.IsEmpty():
            if event.RightDown():
                self.SendNotify(-1, wxEVT_COMMAND_LIST_ITEM_RIGHT_CLICK, event.GetPosition())

                evtCtx = wx.ContextMenuEvent(wx.wxEVT_CONTEXT_MENU, self.GetParent().GetId(),
                                             self.ClientToScreen(event.GetPosition()))
                evtCtx.SetEventObject(self.GetParent())
                self.GetParent().GetEventHandler().ProcessEvent(evtCtx)

            return

        if self._dirty:
            return

        if not (event.Dragging() or event.ButtonDown() or event.LeftUp() or \
                event.ButtonDClick() or event.Moving() or event.RightUp()):
            return

        x = event.GetX()
        y = event.GetY()
        x, y = self.CalcUnscrolledPosition(x, y)

        # where did we hit it (if we did)?
        hitResult = 0
        newItem = None
        count = self.GetItemCount()

        if self.InReportView():
            if not self.HasAGWFlag(ULC_HAS_VARIABLE_ROW_HEIGHT):
                current = y/self.GetLineHeight()
                if current < count:
                    newItem, hitResult = self.HitTestLine(current, x, y)
                else:
                    return
            else:
                for current in xrange(count):
                    newItem, hitResult = self.HitTestLine(current, x, y)
                    if hitResult:
                        break
        else:
            # TODO: optimize it too! this is less simple than for report view but
            #       enumerating all items is still not a way to do it!!
            for current in xrange(count):
                newItem, hitResult = self.HitTestLine(current, x, y)
                if hitResult:
                    break

        theItem = None

        if not self.IsVirtual():
            theItem = CreateListItem(current, 0)
            theItem = self.GetItem(theItem)

        if event.GetEventType() == wx.wxEVT_MOTION and not event.Dragging():

            if current >= 0 and current < count and self.HasAGWFlag(ULC_TRACK_SELECT) and not self._hoverTimer.IsRunning():
                self._hoverItem = current
                self._hoverTimer.Start(HOVER_TIME, wx.TIMER_ONE_SHOT)

            if newItem and newItem.IsHyperText() and (hitResult & ULC_HITTEST_ONITEMLABEL) and theItem and theItem.IsEnabled():
                self.SetCursor(wx.StockCursor(wx.CURSOR_HAND))
                self._isonhyperlink = True
            else:
                if self._isonhyperlink:
                    self.SetCursor(wx.StockCursor(wx.CURSOR_ARROW))
                    self._isonhyperlink = False

            if self.HasAGWFlag(ULC_STICKY_HIGHLIGHT) and hitResult:
                if not self.IsHighlighted(current):
                    self.HighlightAll(False)
                    self.ChangeCurrent(current)
                    self.ReverseHighlight(self._current)

            if self.HasAGWFlag(ULC_SHOW_TOOLTIPS):
                if newItem and hitResult & ULC_HITTEST_ONITEMLABEL:
                    r,c = (newItem._itemId, newItem._col)
                    line = self.GetLine(r)
                    tt = line.GetToolTip(c)
                    if tt and not tt == "":
                        if self.GetToolTip() and self.GetToolTip().GetTip() != tt:
                            self.SetToolTipString(tt)
                    elif (r,c) in self._shortItems: # if the text didn't fit in the column
                        text = newItem.GetText()
                        if self.GetToolTip() and self.GetToolTip().GetTip() != text:
                            self.SetToolTipString(text)
                    else:
                        self.SetToolTipString("")
                else:
                    self.SetToolTipString("")

            if self.HasAGWFlag(ULC_HOT_TRACKING):
                if hitResult:
                    if self._oldHotCurrent != current:
                        if self._oldHotCurrent is not None:
                            self.RefreshLine(self._oldHotCurrent)
                        self._newHotCurrent = current
                        self.RefreshLine(self._newHotCurrent)
                        self._oldHotCurrent = current

            event.Skip()
            return

        if event.Dragging():

            if not self._isDragging:

                if self._lineLastClicked == -1 or not hitResult or not theItem or not theItem.IsEnabled():
                    return

                if self._dragCount == 0:
                    # we have to report the raw, physical coords as we want to be
                    # able to call HitTest(event.m_pointDrag) from the user code to
                    # get the item being dragged
                    self._dragStart = event.GetPosition()

                self._dragCount += 1

                if self._dragCount != 3:
                    return

                command = (event.RightIsDown() and [wxEVT_COMMAND_LIST_BEGIN_RDRAG] or [wxEVT_COMMAND_LIST_BEGIN_DRAG])[0]
                le = UltimateListEvent(command, self.GetParent().GetId())
                le.SetEventObject(self.GetParent())
                le.m_itemIndex = self._lineLastClicked
                le.m_pointDrag = self._dragStart
                self.GetParent().GetEventHandler().ProcessEvent(le)

                # we're going to drag this item
                self._isDragging = True
                self._dragItem = current

                # remember the old cursor because we will change it while
                # dragging
                self._oldCursor = self._cursor
                self.SetCursor(self._dragCursor)

            else:

                if current != self._dropTarget:

                    self.SetCursor(self._dragCursor)
                    # unhighlight the previous drop target
                    if self._dropTarget is not None:
                        self.RefreshLine(self._dropTarget)

                    move = current
                    if self._dropTarget:
                        move = (current > self._dropTarget and [current+1] or [current-1])[0]

                    self._dropTarget = current
                    self.MoveToItem(move)

                else:

                    if self._dragItem == current:
                        self.SetCursor(wx.StockCursor(wx.CURSOR_NO_ENTRY))

            if self.HasAGWFlag(ULC_REPORT) and self._dragItem != current:
                self.DrawDnDArrow()

            return

        else:

            self._dragCount = 0

        if theItem and not theItem.IsEnabled():
            self.DragFinish(event)
            event.Skip()
            return

        if not hitResult:
            # outside of any item
            if event.RightDown():
                self.SendNotify(-1, wxEVT_COMMAND_LIST_ITEM_RIGHT_CLICK, event.GetPosition())
                evtCtx = wx.ContextMenuEvent(wx.wxEVT_CONTEXT_MENU, self.GetParent().GetId(),
                                             self.ClientToScreen(event.GetPosition()))
                evtCtx.SetEventObject(self.GetParent())
                self.GetParent().GetEventHandler().ProcessEvent(evtCtx)
            else:
                self.HighlightAll(False)
                self.DragFinish(event)

            return

        forceClick = False
        if event.ButtonDClick():
            if self._renameTimer.IsRunning():
                self._renameTimer.Stop()

            self._lastOnSame = False

            if current == self._lineLastClicked:
                self.SendNotify(current, wxEVT_COMMAND_LIST_ITEM_ACTIVATED)

                if newItem and newItem.GetKind() in [1, 2] and (hitResult & ULC_HITTEST_ONITEMCHECK):
                    self.CheckItem(newItem, not self.IsItemChecked(newItem))

                return

            else:

                # The first click was on another item, so don't interpret this as
                # a double click, but as a simple click instead
                forceClick = True

        if event.LeftUp():

            if self.DragFinish(event):
                return
            if self._lineSelectSingleOnUp != - 1:
                # select single line
                self.HighlightAll(False)
                self.ReverseHighlight(self._lineSelectSingleOnUp)

            if self._lastOnSame:
                if (current == self._current) and (hitResult == ULC_HITTEST_ONITEMLABEL) and self.HasAGWFlag(ULC_EDIT_LABELS):
                    if not self.InReportView() or self.GetLineLabelRect(current).Contains((x, y)):
                        # This wx.SYS_DCLICK_MSEC is not yet wrapped in wxPython...
                        # dclick = wx.SystemSettings.GetMetric(wx.SYS_DCLICK_MSEC)
                        # m_renameTimer->Start(dclick > 0 ? dclick : 250, True)
                        self._renameTimer.Start(250, True)

            self._lastOnSame = False
            self._lineSelectSingleOnUp = -1

        elif event.RightUp():

            if self.DragFinish(event):
                return

        else:

            # This is necessary, because after a DnD operation in
            # from and to ourself, the up event is swallowed by the
            # DnD code. So on next non-up event (which means here and
            # now) self._lineSelectSingleOnUp should be reset.
            self._lineSelectSingleOnUp = -1

        if event.RightDown():

            if self.SendNotify(current, wxEVT_COMMAND_LIST_ITEM_RIGHT_CLICK, event.GetPosition()):
                self._lineBeforeLastClicked = self._lineLastClicked
                self._lineLastClicked = current
                # If the item is already selected, do not update the selection.
                # Multi-selections should not be cleared if a selected item is clicked.

                if not self.IsHighlighted(current):
                    self.HighlightAll(False)
                    self.ChangeCurrent(current)
                    self.ReverseHighlight(self._current)

                # Allow generation of context menu event
                event.Skip()

        elif event.MiddleDown():
            self.SendNotify(current, wxEVT_COMMAND_LIST_ITEM_MIDDLE_CLICK)

        elif event.LeftDown() or forceClick:
            self._lineBeforeLastClicked = self._lineLastClicked
            self._lineLastClicked = current

            oldCurrent = self._current
            oldWasSelected = self.IsHighlighted(self._current)

            cmdModifierDown = event.CmdDown()
            if self.IsSingleSel() or not (cmdModifierDown or event.ShiftDown()):
                if self.IsSingleSel() or not self.IsHighlighted(current):
                    self.HighlightAll(False)
                    self.ChangeCurrent(current)
                    self.ReverseHighlight(self._current)

                else: # multi sel & current is highlighted & no mod keys
                    self._lineSelectSingleOnUp = current
                    self.ChangeCurrent(current) # change focus

            else: # multi sel & either ctrl or shift is down
                if cmdModifierDown:
                    self.ChangeCurrent(current)
                    self.ReverseHighlight(self._current)

                elif event.ShiftDown():
                    self.ChangeCurrent(current)
                    lineFrom, lineTo = oldCurrent, current
                    shift = 0

                    if lineTo < lineFrom:
                        lineTo = lineFrom
                        lineFrom = self._current

                        if not self.IsHighlighted(lineFrom):
                            shift = 1

                        for i in xrange(lineFrom+1, lineTo+1):
                            if self.IsHighlighted(i):
                                self.HighlightLine(i, False)
                                self.RefreshLine(i)
                                lineTo -= 1

                    self.HighlightLines(lineFrom, lineTo+shift)

                else: # !ctrl, !shift

                    # test in the enclosing if should make it impossible
                    raise Exception("how did we get here?")

            if newItem:
                if event.LeftDown():
                    if newItem.GetKind() in [1, 2] and (hitResult & ULC_HITTEST_ONITEMCHECK):
                        self.CheckItem(newItem, not self.IsItemChecked(newItem))
                    if newItem.IsHyperText():
                        self.SetItemVisited(newItem, True)
                        self.HandleHyperLink(newItem)

            if self._current != oldCurrent:
                self.RefreshLine(oldCurrent)

            # forceClick is only set if the previous click was on another item
            self._lastOnSame = not forceClick and (self._current == oldCurrent) and oldWasSelected

            if self.HasAGWFlag(ULC_STICKY_HIGHLIGHT) and self.HasAGWFlag(ULC_STICKY_NOSELEVENT) and self.HasAGWFlag(ULC_SEND_LEFTCLICK):
                self.SendNotify(current, wxEVT_COMMAND_LIST_ITEM_LEFT_CLICK, event.GetPosition())

[docs]    def DrawDnDArrow(self):
        """ Draws a drag and drop visual representation of an arrow. """

        dc = wx.ClientDC(self)
        lineY = self.GetLineY(self._dropTarget)
        width = self.GetTotalWidth()

        dc.SetPen(wx.Pen(wx.BLACK, 2))
        x, y = self.CalcScrolledPosition(HEADER_OFFSET_X, lineY+2*HEADER_OFFSET_Y)

        tri1 = [wx.Point(x+1, y-2), wx.Point(x+1, y+4), wx.Point(x+4, y+1)]
        tri2 = [wx.Point(x+width-1, y-2), wx.Point(x+width-1, y+4), wx.Point(x+width-4, y+1)]
        dc.DrawPolygon(tri1)
        dc.DrawPolygon(tri2)

        dc.DrawLine(x, y+1, width, y+1)

[docs]    def DragFinish(self, event):
        """
        A drag and drop operation has just finished.

        :param `event`: a `wx.MouseEvent` event to be processed.
        """

        if not self._isDragging:
            return False

        self._isDragging = False
        self._dragCount = 0
        self._dragItem = None
        self.SetCursor(self._oldCursor)
        self.Refresh()

        le = UltimateListEvent(wxEVT_COMMAND_LIST_END_DRAG, self.GetParent().GetId())
        le.SetEventObject(self.GetParent())
        le.m_itemIndex = self._dropTarget
        le.m_pointDrag = event.GetPosition()
        self.GetParent().GetEventHandler().ProcessEvent(le)

        return True

[docs]    def HandleHyperLink(self, item):
        """
        Handles the hyperlink items, sending the ``EVT_LIST_ITEM_HYPERLINK`` event.

        :param `item`: an instance of L{UltimateListItem}.
        """

        if self.IsItemHyperText(item):
            self.SendNotify(item._itemId, wxEVT_COMMAND_LIST_ITEM_HYPERLINK)

[docs]    def OnHoverTimer(self, event):
        """
        Handles the ``wx.EVT_TIMER`` event for L{UltimateListMainWindow}.

        :param `event`: a `wx.TimerEvent` event to be processed.
        """

        x, y = self.ScreenToClient(wx.GetMousePosition())
        x, y = self.CalcUnscrolledPosition(x, y)
        item, hitResult = self.HitTestLine(self._hoverItem, x, y)

        if item and item._itemId == self._hoverItem:
            if not self.IsHighlighted(self._hoverItem):

                dontNotify = self.HasAGWFlag(ULC_STICKY_HIGHLIGHT) and self.HasAGWFlag(ULC_STICKY_NOSELEVENT)
                if not dontNotify:
                    self.SendNotify(self._hoverItem, wxEVT_COMMAND_LIST_ITEM_SELECTED)

                self.HighlightAll(False)
                self.ChangeCurrent(self._hoverItem)
                self.ReverseHighlight(self._current)

[docs]    def MoveToItem(self, item):
        """
        Scrolls the input item into view.

        :param `item`: an instance of L{UltimateListItem}.
        """

        if item == -1:
            return

        if item >= self.GetItemCount():
            item = self.GetItemCount() - 1

        rect = self.GetLineRect(item)
        client_w, client_h = self.GetClientSize()
        hLine = self.GetLineHeight(item)

        view_x = SCROLL_UNIT_X*self.GetScrollPos(wx.HORIZONTAL)
        view_y = hLine*self.GetScrollPos(wx.VERTICAL)

        if self.InReportView():

            # the next we need the range of lines shown it might be different, so
            # recalculate it
            self.ResetVisibleLinesRange()

            if not self.HasAGWFlag(ULC_HAS_VARIABLE_ROW_HEIGHT):

                if rect.y < view_y:
                    self.Scroll(-1, rect.y/hLine)
                if rect.y+rect.height+5 > view_y+client_h:
                    self.Scroll(-1, (rect.y+rect.height-client_h+hLine)/hLine)

                if wx.Platform == "__WXMAC__":
                    # At least on Mac the visible lines value will get reset inside of
                    # Scroll *before* it actually scrolls the window because of the
                    # Update() that happens there, so it will still have the wrong value.
                    # So let's reset it again and wait for it to be recalculated in the
                    # next paint event.  I would expect this problem to show up in wxGTK
                    # too but couldn't duplicate it there.  Perhaps the order of events
                    # is different...  --Robin
                    self.ResetVisibleLinesRange()

            else:

                view_y = SCROLL_UNIT_Y*self.GetScrollPos(wx.VERTICAL)
                start_y, height = rect.y, rect.height

                if start_y < view_y:
                    while start_y > view_y:
                        start_y -= SCROLL_UNIT_Y

                    self.Scroll(-1, start_y/SCROLL_UNIT_Y)

                if start_y + height > view_y + client_h:
                    while start_y + height < view_y + client_h:
                        start_y += SCROLL_UNIT_Y

                    self.Scroll(-1, (start_y+height-client_h+SCROLL_UNIT_Y)/SCROLL_UNIT_Y)

        else: # !report

            sx = sy = -1

            if rect.x-view_x < 5:
                sx = (rect.x - 5)/SCROLL_UNIT_X
            if rect.x+rect.width-5 > view_x+client_w:
                sx = (rect.x + rect.width - client_w + SCROLL_UNIT_X)/SCROLL_UNIT_X

            if rect.y-view_y < 5:
                sy = (rect.y - 5)/hLine
            if rect.y + rect.height - 5 > view_y + client_h:
                sy = (rect.y + rect.height - client_h + hLine)/hLine

            self.Scroll(sx, sy)

# ----------------------------------------------------------------------------
# keyboard handling
# ----------------------------------------------------------------------------

[docs]    def GetNextActiveItem(self, item, down=True):
        """
        Returns the next active item. Used Internally at present.

        :param `item`: an instance of L{UltimateListItem};
        :param `down`: ``True`` to search downwards for an active item, ``False``
         to search upwards.
        """

        count = self.GetItemCount()
        initialItem = item

        while 1:
            if item >= count or item < 0:
                return initialItem

            listItem = CreateListItem(item, 0)
            listItem = self.GetItem(listItem, 0)
            if listItem.IsEnabled():
                return item

            item = (down and [item+1] or [item-1])[0]

[docs]    def OnArrowChar(self, newCurrent, event):
        """
        Handles the keyboard arrows key events.

        :param `newCurrent`: an integer specifying the new current item;
        :param `event`: a `wx.KeyEvent` event to be processed.
        """

        oldCurrent = self._current
        newCurrent = self.GetNextActiveItem(newCurrent, newCurrent > oldCurrent)

        # in single selection we just ignore Shift as we can't select several
        # items anyhow
        if event.ShiftDown() and not self.IsSingleSel():

            self.ChangeCurrent(newCurrent)

            # refresh the old focus to remove it
            self.RefreshLine(oldCurrent)

            # select all the items between the old and the new one
            if oldCurrent > newCurrent:
                newCurrent = oldCurrent
                oldCurrent = self._current

            self.HighlightLines(oldCurrent, newCurrent)

        else: # !shift

            # all previously selected items are unselected unless ctrl is held
            # in a multi-selection control
            if not event.ControlDown() or self.IsSingleSel():
                self.HighlightAll(False)

            self.ChangeCurrent(newCurrent)

            # refresh the old focus to remove it
            self.RefreshLine(oldCurrent)

            if not event.ControlDown() or self.IsSingleSel():
                self.HighlightLine(self._current, True)

        self.RefreshLine(self._current)
        self.MoveToFocus()

[docs]    def OnKeyDown(self, event):
        """
        Handles the ``wx.EVT_KEY_DOWN`` event for L{UltimateListMainWindow}.

        :param `event`: a `wx.KeyEvent` event to be processed.
        """

        parent = self.GetParent()

        # we propagate the key event upwards
        ke = wx.KeyEvent(event.GetEventType())

        ke.SetEventObject(parent)
        if parent.GetEventHandler().ProcessEvent(ke):
            event.Skip()
            return

        event.Skip()

[docs]    def OnKeyUp(self, event):
        """
        Handles the ``wx.EVT_KEY_UP`` event for L{UltimateListMainWindow}.

        :param `event`: a `wx.KeyEvent` event to be processed.
        """

        parent = self.GetParent()

        # we propagate the key event upwards
        ke = wx.KeyEvent(event.GetEventType())

        ke.SetEventObject(parent)
        if parent.GetEventHandler().ProcessEvent(ke):
            return

        event.Skip()

[docs]    def OnChar(self, event):
        """
        Handles the ``wx.EVT_CHAR`` event for L{UltimateListMainWindow}.

        :param `event`: a `wx.KeyEvent` event to be processed.
        """

        parent = self.GetParent()

        if self.IsVirtual() and self.GetItemCount() == 0:
            event.Skip()
            return

        # we send a list_key event up
        if self.HasCurrent():
            le = UltimateListEvent(wxEVT_COMMAND_LIST_KEY_DOWN, self.GetParent().GetId())
            le.m_itemIndex = self._current
            le.m_item = self.GetLine(self._current).GetItem(0, le.m_item)
            le.m_code = event.GetKeyCode()
            le.SetEventObject(parent)
            parent.GetEventHandler().ProcessEvent(le)

        keyCode = event.GetKeyCode()
        if  keyCode not in [wx.WXK_UP, wx.WXK_DOWN, wx.WXK_RIGHT, wx.WXK_LEFT, \
                            wx.WXK_PAGEUP, wx.WXK_PAGEDOWN, wx.WXK_END, wx.WXK_HOME]:

            # propagate the char event upwards
            ke = wx.KeyEvent(event.GetEventType())
            ke.SetEventObject(parent)
            if parent.GetEventHandler().ProcessEvent(ke):
                return

        if event.GetKeyCode() == wx.WXK_TAB:
            nevent = wx.NavigationKeyEvent()
            nevent.SetWindowChange(event.ControlDown())
            nevent.SetDirection(not event.ShiftDown())
            nevent.SetEventObject(self.GetParent().GetParent())
            nevent.SetCurrentFocus(self._parent)
            if self.GetParent().GetParent().GetEventHandler().ProcessEvent(nevent):
                return

        # no item . nothing to do
        if not self.HasCurrent():
            event.Skip()
            return

        keyCode = event.GetKeyCode()

        if keyCode == wx.WXK_UP:
            if self._current > 0:
                self.OnArrowChar(self._current - 1, event)
                if self.HasAGWFlag(ULC_HAS_VARIABLE_ROW_HEIGHT):
                    self._dirty = True

        elif keyCode == wx.WXK_DOWN:
            if self._current < self.GetItemCount() - 1:
                self.OnArrowChar(self._current + 1, event)
                if self.HasAGWFlag(ULC_HAS_VARIABLE_ROW_HEIGHT):
                    self._dirty = True

        elif keyCode == wx.WXK_END:
            if not self.IsEmpty():
                self.OnArrowChar(self.GetItemCount() - 1, event)
                self._dirty = True

        elif keyCode == wx.WXK_HOME:
            if not self.IsEmpty():
                self.OnArrowChar(0, event)
                self._dirty = True

        elif keyCode == wx.WXK_PRIOR:
            steps = (self.InReportView() and [self._linesPerPage - 1] or [self._current % self._linesPerPage])[0]
            index = self._current - steps

            if index < 0:
                index = 0

            self.OnArrowChar(index, event)
            self._dirty = True

        elif keyCode == wx.WXK_NEXT:

            steps = (self.InReportView() and [self._linesPerPage - 1] or [self._linesPerPage - (self._current % self._linesPerPage) - 1])[0]
            index = self._current + steps
            count = self.GetItemCount()

            if index >= count:
                index = count - 1

            self.OnArrowChar(index, event)
            self._dirty = True

        elif keyCode == wx.WXK_LEFT:
            if not self.InReportView():

                index = self._current - self._linesPerPage
                if index < 0:
                    index = 0

                self.OnArrowChar(index, event)

        elif keyCode == wx.WXK_RIGHT:
            if not self.InReportView():

                index = self._current + self._linesPerPage
                count = self.GetItemCount()

                if index >= count:
                    index = count - 1

                self.OnArrowChar(index, event)

        elif keyCode == wx.WXK_SPACE:
            if self.IsSingleSel():

                if event.ControlDown():
                    self.ReverseHighlight(self._current)
                else: # normal space press
                    self.SendNotify(self._current, wxEVT_COMMAND_LIST_ITEM_ACTIVATED)

            else:
                # select it in ReverseHighlight() below if unselected
                self.ReverseHighlight(self._current)

        elif keyCode in [wx.WXK_RETURN, wx.WXK_EXECUTE, wx.WXK_NUMPAD_ENTER]:
            self.SendNotify(self._current, wxEVT_COMMAND_LIST_ITEM_ACTIVATED)

        else:
            event.Skip()

# ----------------------------------------------------------------------------
# focus handling
# ----------------------------------------------------------------------------

[docs]    def OnSetFocus(self, event):
        """
        Handles the ``wx.EVT_SET_FOCUS`` event for L{UltimateListMainWindow}.

        :param `event`: a `wx.FocusEvent` event to be processed.
        """

        if self.GetParent():
            event = wx.FocusEvent(wx.wxEVT_SET_FOCUS, self.GetParent().GetId())
            event.SetEventObject(self.GetParent())
            if self.GetParent().GetEventHandler().ProcessEvent(event):
                return

        # wxGTK sends us EVT_SET_FOCUS events even if we had never got
        # EVT_KILL_FOCUS before which means that we finish by redrawing the items
        # which are already drawn correctly resulting in horrible flicker - avoid
        # it
        if not self._hasFocus:
            self._hasFocus = True
            self.Refresh()

[docs]    def OnKillFocus(self, event):
        """
        Handles the ``wx.EVT_KILL_FOCUS`` event for L{UltimateListMainWindow}.

        :param `event`: a `wx.FocusEvent` event to be processed.
        """

        if self.GetParent():
            event = wx.FocusEvent(wx.wxEVT_KILL_FOCUS, self.GetParent().GetId())
            event.SetEventObject(self.GetParent())
            if self.GetParent().GetEventHandler().ProcessEvent(event):
                return

        self._hasFocus = False
        self.Refresh()

[docs]    def DrawImage(self, index, dc, x, y, enabled):
        """
        Draws one of the item images.

        :param `index`: the index of the image inside the image list;
        :param `dc`: an instance of `wx.DC`;
        :param `x`: the x position where to draw the image;
        :param `y`: the y position where to draw the image;
        :param `enabled`: ``True`` if the item is enabled, ``False`` if it is disabled.
        """

        if self.HasAGWFlag(ULC_ICON) and self._normal_image_list:
            imgList = (enabled and [self._normal_image_list] or [self._normal_grayed_image_list])[0]
            imgList.Draw(index, dc, x, y, wx.IMAGELIST_DRAW_TRANSPARENT)

        elif self.HasAGWFlag(ULC_SMALL_ICON) and self._small_image_list:
            imgList = (enabled and [self._small_image_list] or [self._small_grayed_image_list])[0]
            imgList.Draw(index, dc, x, y, wx.IMAGELIST_DRAW_TRANSPARENT)

        elif self.HasAGWFlag(ULC_LIST) and self._small_image_list:
            imgList = (enabled and [self._small_image_list] or [self._small_grayed_image_list])[0]
            imgList.Draw(index, dc, x, y, wx.IMAGELIST_DRAW_TRANSPARENT)

        elif self.InReportView() and self._small_image_list:
            imgList = (enabled and [self._small_image_list] or [self._small_grayed_image_list])[0]
            imgList.Draw(index, dc, x, y, wx.IMAGELIST_DRAW_TRANSPARENT)

[docs]    def DrawCheckbox(self, dc, x, y, kind, checked, enabled):
        """
        Draws the item checkbox/radiobutton image.

        :param `dc`: an instance of `wx.DC`;
        :param `x`: the x position where to draw the image;
        :param `y`: the y position where to draw the image;
        :param `kind`: may be one of the following integers:

          =============== ==========================
          Item Kind       Description
          =============== ==========================
                 0        A normal item
                 1        A checkbox-like item
                 2        A radiobutton-type item
          =============== ==========================

        :param `checked`: ``True`` if the item is checked, ``False`` otherwise;
        :param `enabled`: ``True`` if the item is enabled, ``False`` if it is disabled.
        """

        imgList = (enabled and [self._image_list_check] or [self._grayed_check_list])[0]
        if kind == 1:
            # checkbox
            index = (checked and [0] or [1])[0]
        else:
            # radiobutton
            index = (checked and [2] or [3])[0]

        imgList.Draw(index, dc, x, y, wx.IMAGELIST_DRAW_TRANSPARENT)

[docs]    def GetCheckboxImageSize(self):
        """ Returns the checkbox/radiobutton image size. """

        bmp = self._image_list_check.GetBitmap(0)
        return bmp.GetWidth(), bmp.GetHeight()

[docs]    def GetImageSize(self, index):
        """
        Returns the image size for the item.

        :param `index`: the image index.
        """

        width = height = 0

        if self.HasAGWFlag(ULC_ICON) and self._normal_image_list:

            for indx in index:
                w, h = self._normal_image_list.GetSize(indx)
                width += w + MARGIN_BETWEEN_TEXT_AND_ICON
                height = max(height, h)

        elif self.HasAGWFlag(ULC_SMALL_ICON) and self._small_image_list:

            for indx in index:
                w, h = self._small_image_list.GetSize(indx)
                width += w + MARGIN_BETWEEN_TEXT_AND_ICON
                height = max(height, h)

        elif self.HasAGWFlag(ULC_LIST) and self._small_image_list:

            for indx in index:
                w, h = self._small_image_list.GetSize(indx)
                width += w + MARGIN_BETWEEN_TEXT_AND_ICON
                height = max(height, h)

        elif self.InReportView() and self._small_image_list:

            for indx in index:
                w, h = self._small_image_list.GetSize(indx)
                width += w + MARGIN_BETWEEN_TEXT_AND_ICON
                height = max(height, h)

        return width, height

[docs]    def GetTextLength(self, s):
        """
        Returns the text width for the input string.

        :param `s`: the string to measure.
        """

        dc = wx.ClientDC(self)
        dc.SetFont(self.GetFont())

        lw, lh, dummy = dc.GetMultiLineTextExtent(s)

        return lw + AUTOSIZE_COL_MARGIN

[docs]    def SetImageList(self, imageList, which):
        """
        Sets the image list associated with the control.

        :param `imageList`: an instance of `wx.ImageList` or an instance of L{PyImageList};
        :param `which`: one of ``wx.IMAGE_LIST_NORMAL``, ``wx.IMAGE_LIST_SMALL``,
         ``wx.IMAGE_LIST_STATE`` (the last is unimplemented).

        :note: Using L{PyImageList} enables you to have images of different size inside the
         image list. In your derived class, instead of doing this::

             imageList = wx.ImageList(16, 16)
             imageList.Add(someBitmap)
             self.SetImageList(imageList, wx.IMAGE_LIST_SMALL)

         You should do this::

             imageList = PyImageList(16, 16)
             imageList.Add(someBitmap)
             self.SetImageList(imageList, wx.IMAGE_LIST_SMALL)

        """

        self._dirty = True

        if isinstance(imageList, PyImageList):
            # We have a custom PyImageList with variable image sizes
            cls = PyImageList
        else:
            cls = wx.ImageList

        # calc the spacing from the icon size
        width = height = 0
        if imageList and imageList.GetImageCount():
            width, height = imageList.GetSize(0)

        if which == wx.IMAGE_LIST_NORMAL:
            self._normal_image_list = imageList
            self._normal_grayed_image_list = cls(width, height, True, 0)

            for ii in xrange(imageList.GetImageCount()):
                bmp = imageList.GetBitmap(ii)
                newbmp = MakeDisabledBitmap(bmp)
                self._normal_grayed_image_list.Add(newbmp)

            self._normal_spacing = width + 8

        if which == wx.IMAGE_LIST_SMALL:
            self._small_image_list = imageList
            self._small_spacing = width + 14

            self._small_grayed_image_list = cls(width, height, True, 0)

            for ii in xrange(imageList.GetImageCount()):
                bmp = imageList.GetBitmap(ii)
                newbmp = MakeDisabledBitmap(bmp)
                self._small_grayed_image_list.Add(newbmp)

        self._lineHeight = 0  # ensure that the line height will be recalc'd
        self.ResetLineDimensions()

[docs]    def SetImageListCheck(self, sizex, sizey, imglist=None):
        """
        Sets the checkbox/radiobutton image list.

        :param `sizex`: the width of the bitmaps in the `imglist`;
        :param `sizey`: the height of the bitmaps in the `imglist`;
        :param `imglist`: an instance of `wx.ImageList`.
        """

        # Image list to hold disabled versions of each control
        self._grayed_check_list = wx.ImageList(sizex, sizey, True, 0)

        if imglist is None:

            self._image_list_check = wx.ImageList(sizex, sizey)

            # Get the Checkboxes
            self._image_list_check.Add(self.GetControlBmp(checkbox=True,
                                                          checked=True,
                                                          enabled=True,
                                                          x=sizex, y=sizey))
            self._grayed_check_list.Add(self.GetControlBmp(checkbox=True,
                                                           checked=True,
                                                           enabled=False,
                                                           x=sizex, y=sizey))

            self._image_list_check.Add(self.GetControlBmp(checkbox=True,
                                                          checked=False,
                                                          enabled=True,
                                                          x=sizex, y=sizey))
            self._grayed_check_list.Add(self.GetControlBmp(checkbox=True,
                                                           checked=False,
                                                           enabled=False,
                                                           x=sizex, y=sizey))
            # Get the Radio Buttons
            self._image_list_check.Add(self.GetControlBmp(checkbox=False,
                                                          checked=True,
                                                          enabled=True,
                                                          x=sizex, y=sizey))
            self._grayed_check_list.Add(self.GetControlBmp(checkbox=False,
                                                           checked=True,
                                                           enabled=False,
                                                           x=sizex, y=sizey))

            self._image_list_check.Add(self.GetControlBmp(checkbox=False,
                                                          checked=False,
                                                          enabled=True,
                                                          x=sizex, y=sizey))
            self._grayed_check_list.Add(self.GetControlBmp(checkbox=False,
                                                           checked=False,
                                                           enabled=False,
                                                           x=sizex, y=sizey))
        else:

            sizex, sizey = imglist.GetSize(0)
            self._image_list_check = imglist

            for ii in xrange(self._image_list_check.GetImageCount()):

                bmp = self._image_list_check.GetBitmap(ii)
                newbmp = MakeDisabledBitmap(bmp)
                self._grayed_check_list.Add(newbmp)

        self._dirty = True

        if imglist:
            self.RecalculatePositions()

[docs]    def GetControlBmp(self, checkbox=True, checked=False, enabled=True, x=16, y=16):
        """
        Returns a native looking checkbox or radio button bitmap.

        :param `checkbox`: ``True`` to get a checkbox image, ``False`` for a radiobutton
         one;
        :param `checked`: ``True`` if the control is marked, ``False`` if it is not;
        :param `enabled`: ``True`` if the control is enabled, ``False`` if it is not;
        :param `x`: the width of the bitmap, in pixels;
        :param `y`: the height of the bitmap, in pixels.
        """

        bmp = wx.EmptyBitmap(x, y)
        mdc = wx.MemoryDC(bmp)
        dc = wx.GCDC(mdc)
        render = wx.RendererNative.Get()

        if checked:
            flag = wx.CONTROL_CHECKED
        else:
            flag = 0

        if not enabled:
            flag |= wx.CONTROL_DISABLED

        if checkbox:
            render.DrawCheckBox(self, mdc, (0, 0, x, y), flag)
        else:
            if _VERSION_STRING < "2.9":
                render.DrawRadioButton(self, mdc, (0, 0, x, y), flag)
            else:
                render.DrawRadioBitmap(self, mdc, (0, 0, x, y), flag)

        mdc.SelectObject(wx.NullBitmap)
        return bmp

[docs]    def SetItemSpacing(self, spacing, isSmall=False):
        """
        Sets the spacing between item texts and icons.

        :param `spacing`: the spacing between item texts and icons, in pixels;
        :param `isSmall`: ``True`` if using a ``wx.IMAGE_LIST_SMALL`` image list,
         ``False`` if using a ``wx.IMAGE_LIST_NORMAL`` image list.
        """

        self._dirty = True

        if isSmall:
            self._small_spacing = spacing
        else:
            self._normal_spacing = spacing

[docs]    def GetItemSpacing(self, isSmall=False):
        """
        Returns the spacing between item texts and icons, in pixels.

        :param `isSmall`: ``True`` if using a ``wx.IMAGE_LIST_SMALL`` image list,
         ``False`` if using a ``wx.IMAGE_LIST_NORMAL`` image list.
        """

        return (isSmall and [self._small_spacing] or [self._normal_spacing])[0]

# ----------------------------------------------------------------------------
# columns
# ----------------------------------------------------------------------------

[docs]    def SetColumn(self, col, item):
        """
        Sets information about this column.

        :param `col`: an integer specifying the column index;
        :param `item`: an instance of L{UltimateListItem}.
        """

        column = self._columns[col]

        if item._width == ULC_AUTOSIZE_USEHEADER:
            item._width = self.GetTextLength(item._text)

        column.SetItem(item)

        headerWin = self.GetListCtrl()._headerWin
        if headerWin:
            headerWin._dirty = True

        self._dirty = True

        # invalidate it as it has to be recalculated
        self._headerWidth = 0

[docs]    def SetColumnWidth(self, col, width):
        """
        Sets the column width.

        :param `width`: can be a width in pixels or ``wx.LIST_AUTOSIZE`` (-1) or
         ``wx.LIST_AUTOSIZE_USEHEADER`` (-2) or ``ULC_AUTOSIZE_FILL`` (-3).
         ``wx.LIST_AUTOSIZE`` will resize the column to the length of its longest
         item. ``wx.LIST_AUTOSIZE_USEHEADER`` will resize the column to the
         length of the header (Win32) or 80 pixels (other platforms).
         ``ULC_AUTOSIZE_FILL`` will resize the column fill the remaining width
         of the window.

        :note: In small or normal icon view, col must be -1, and the column width
         is set for all columns.
        """

        if col < 0:
            raise Exception("invalid column index")

        if not self.InReportView() and not self.InTileView() and not self.HasAGWFlag(ULC_HEADER_IN_ALL_VIEWS):
            raise Exception("SetColumnWidth() can only be called in report/tile modes or with the ULC_HEADER_IN_ALL_VIEWS flag set.")

        self._dirty = True
        headerWin = self.GetListCtrl()._headerWin
        footerWin = self.GetListCtrl()._footerWin

        if headerWin:
            headerWin._dirty = True

        if footerWin:
            footerWin._dirty = True

        column = self._columns[col]
        count = self.GetItemCount()

        if width == ULC_AUTOSIZE_FILL:

            width = self.GetColumnWidth(col)
            if width == 0:
                width = WIDTH_COL_DEFAULT
            self._resizeColumn = col

        elif width == ULC_AUTOSIZE_USEHEADER:

            width = self.GetTextLength(column.GetText())
            width += 2*EXTRA_WIDTH

            if column.GetKind() in [1, 2]:
                ix, iy = self._owner.GetCheckboxImageSize()
                width += ix + HEADER_IMAGE_MARGIN_IN_REPORT_MODE

            # check for column header's image availability
            images = column.GetImage()
            for img in images:
                if self._small_image_list:
                    ix, iy = self._small_image_list.GetSize(img)
                    width += ix + HEADER_IMAGE_MARGIN_IN_REPORT_MODE

        elif width == ULC_AUTOSIZE:

            if self.IsVirtual() or not self.InReportView():
                # TODO: determine the max width somehow...
                width = WIDTH_COL_DEFAULT

            else: # !virtual

                maxW = AUTOSIZE_COL_MARGIN

                #  if the cached column width isn't valid then recalculate it
                if self._aColWidths[col]._bNeedsUpdate:

                    for i in xrange(count):

                        line = self.GetLine(i)
                        itemData = line._items[col]
                        item = UltimateListItem()

                        item = itemData.GetItem(item)
                        itemWidth = self.GetItemWidthWithImage(item)
                        if itemWidth > maxW and not item._overFlow:
                            maxW = itemWidth

                    self._aColWidths[col]._bNeedsUpdate = False
                    self._aColWidths[col]._nMaxWidth = maxW

                maxW = self._aColWidths[col]._nMaxWidth
                width = maxW + AUTOSIZE_COL_MARGIN

        column.SetWidth(width)

        # invalidate it as it has to be recalculated
        self._headerWidth = 0
        self._footerWidth = 0

        if footerWin:
            footerWin.Refresh()

[docs]    def GetHeaderWidth(self):
        """ Returns the header window width, in pixels. """

        if not self._headerWidth:

            count = self.GetColumnCount()
            for col in xrange(count):

                if not self.IsColumnShown(col):
                    continue

                self._headerWidth += self.GetColumnWidth(col)

        if self.HasAGWFlag(ULC_FOOTER):
            self._footerWidth = self._headerWidth

        return self._headerWidth

[docs]    def GetColumn(self, col):
        """
        Returns information about this column.

        :param `col`: an integer specifying the column index.
        """

        item = UltimateListItem()
        column = self._columns[col]
        item = column.GetItem(item)

        return item

[docs]    def GetColumnWidth(self, col):
        """
        Returns the column width for the input column.

        :param `col`: an integer specifying the column index.
        """

        column = self._columns[col]
        return column.GetWidth()

[docs]    def GetTotalWidth(self):
        """ Returns the total width of the columns in L{UltimateListCtrl}. """

        width = 0
        for column in self._columns:
            width += column.GetWidth()

        return width

# ----------------------------------------------------------------------------
# item state
# ----------------------------------------------------------------------------

[docs]    def SetItem(self, item):
        """
        Sets information about the item.

        :param `item`: an instance of L{UltimateListItemData}.
        """

        id = item._itemId

        if id < 0 or id >= self.GetItemCount():
            raise Exception("invalid item index in SetItem")

        if not self.IsVirtual():

            line = self.GetLine(id)
            line.SetItem(item._col, item)

            # Set item state if user wants
            if item._mask & ULC_MASK_STATE:
                self.SetItemState(item._itemId, item._state, item._state)

            if self.InReportView():

                #  update the Max Width Cache if needed
                width = self.GetItemWidthWithImage(item)

                if width > self._aColWidths[item._col]._nMaxWidth:
                    self._aColWidths[item._col]._nMaxWidth = width
                    self._aColWidths[item._col]._bNeedsUpdate = True

        if self.HasAGWFlag(ULC_HAS_VARIABLE_ROW_HEIGHT):
            line.ResetDimensions()

        # update the item on screen
        if self.InReportView():
            rectItem = self.GetItemRect(id)
            self.RefreshRect(rectItem)

[docs]    def SetItemStateAll(self, state, stateMask):
        """
        Sets the item state flags for all the items.

        :param `state`: any combination of the following bits:

         ============================ ========= ==============================
         State Bits                   Hex Value Description
         ============================ ========= ==============================
         ``ULC_STATE_DONTCARE``             0x0 Don't care what the state is
         ``ULC_STATE_DROPHILITED``          0x1 The item is highlighted to receive a drop event
         ``ULC_STATE_FOCUSED``              0x2 The item has the focus
         ``ULC_STATE_SELECTED``             0x4 The item is selected
         ``ULC_STATE_CUT``                  0x8 The item is in the cut state
         ``ULC_STATE_DISABLED``            0x10 The item is disabled
         ``ULC_STATE_FILTERED``            0x20 The item has been filtered
         ``ULC_STATE_INUSE``               0x40 The item is in use
         ``ULC_STATE_PICKED``              0x80 The item has been picked
         ``ULC_STATE_SOURCE``             0x100 The item is a drag and drop source
         ============================ ========= ==============================

        :param `stateMask`: the bitmask for the state flag.

        :note: The valid state flags are influenced by the value of the state mask.
        """

        if self.IsEmpty():
            return

        # first deal with selection
        if stateMask & ULC_STATE_SELECTED:

            # set/clear select state
            if self.IsVirtual():

                # optimized version for virtual listctrl.
                self._selStore.SelectRange(0, self.GetItemCount() - 1, state==ULC_STATE_SELECTED)
                self.Refresh()

            elif state & ULC_STATE_SELECTED:

                count = self.GetItemCount()
                for i in xrange(count):
                    self.SetItemState(i, ULC_STATE_SELECTED, ULC_STATE_SELECTED)

            else:

                # clear for non virtual (somewhat optimized by using GetNextItem())
                i = -1
                while 1:
                    i += 1
                    if self.GetNextItem(i, ULC_NEXT_ALL, ULC_STATE_SELECTED) == -1:
                        break

                    self.SetItemState(i, 0, ULC_STATE_SELECTED)

        if self.HasCurrent() and state == 0 and stateMask & ULC_STATE_FOCUSED:

            # unfocus all: only one item can be focussed, so clearing focus for
            # all items is simply clearing focus of the focussed item.
            self.SetItemState(self._current, state, stateMask)

        #(setting focus to all items makes no sense, so it is not handled here.)

[docs]    def SetItemState(self, litem, state, stateMask):
        """
        Sets the item state flags for the input item.

        :param `litem`: the index of the item; if defaulted to -1, the state flag
         will be set for all the items;
        :param `state`: the item state flag;
        :param `stateMask`: the bitmask for the state flag.

        :see: L{SetItemStateAll} for a list of valid state flags.
        """

        if litem == -1:
            self.SetItemStateAll(state, stateMask)
            return

        if litem < 0 or litem >= self.GetItemCount():
            raise Exception("invalid item index in SetItemState")

        oldCurrent = self._current
        item = litem    # safe because of the check above

        # do we need to change the focus?
        if stateMask & ULC_STATE_FOCUSED:

            if state & ULC_STATE_FOCUSED:

                # don't do anything if this item is already focused
                if item != self._current:

                    self.ChangeCurrent(item)

                    if oldCurrent != - 1:

                        if self.IsSingleSel():

                            self.HighlightLine(oldCurrent, False)

                        self.RefreshLine(oldCurrent)

                    self.RefreshLine(self._current)

            else: # unfocus

                # don't do anything if this item is not focused
                if item == self._current:

                    self.ResetCurrent()

                    if self.IsSingleSel():

                        # we must unselect the old current item as well or we
                        # might end up with more than one selected item in a
                        # single selection control
                        self.HighlightLine(oldCurrent, False)

                    self.RefreshLine(oldCurrent)

        # do we need to change the selection state?
        if stateMask & ULC_STATE_SELECTED:

            on = (state & ULC_STATE_SELECTED) != 0

            if self.IsSingleSel():

                if on:

                    # selecting the item also makes it the focused one in the
                    # single sel mode
                    if self._current != item:

                        self.ChangeCurrent(item)

                        if oldCurrent != - 1:

                            self.HighlightLine(oldCurrent, False)
                            self.RefreshLine(oldCurrent)

                else: # off

                    # only the current item may be selected anyhow
                    if item != self._current:
                        return

            if self.HighlightLine(item, on):
                self.RefreshLine(item)

[docs]    def GetItemState(self, item, stateMask):
        """
        Returns the item state flags for the input item.

        :param `item`: the index of the item;
        :param `stateMask`: the bitmask for the state flag.

        :see: L{SetItemStateAll} for a list of valid state flags.
        """

        if item < 0 or item >= self.GetItemCount():
            raise Exception("invalid item index in GetItemState")

        ret = ULC_STATE_DONTCARE

        if stateMask & ULC_STATE_FOCUSED:
            if item == self._current:
                ret |= ULC_STATE_FOCUSED

        if stateMask & ULC_STATE_SELECTED:
            if self.IsHighlighted(item):
                ret |= ULC_STATE_SELECTED

        return ret

[docs]    def GetItem(self, item, col=0):
        """
        Returns the information about the input item.

        :param `item`: an instance of L{UltimateListItem};
        :param `col`: the column to which the item belongs to.
        """

        if item._itemId < 0 or item._itemId >= self.GetItemCount():
            raise Exception("invalid item index in GetItem")

        line = self.GetLine(item._itemId)
        item = line.GetItem(col, item)

        # Get item state if user wants it
        if item._mask & ULC_MASK_STATE:
            item._state = self.GetItemState(item._itemId, ULC_STATE_SELECTED | ULC_STATE_FOCUSED)

        return item

[docs]    def CheckItem(self, item, checked=True, sendEvent=True):
        """
        Actually checks/uncheks an item, sending (eventually) the two
        events ``EVT_LIST_ITEM_CHECKING`` / ``EVT_LIST_ITEM_CHECKED``.

        :param `item`: an instance of L{UltimateListItem};
        :param `checked`: ``True`` to check an item, ``False`` to uncheck it;
        :param `sendEvent`: ``True`` to send a {UltimateListEvent}, ``False`` otherwise.

        :note: This method is meaningful only for checkbox-like and radiobutton-like items.
        """

        # Should we raise an error here?!?
        if item.GetKind() == 0 or not item.IsEnabled():
            return

        if sendEvent:

            parent = self.GetParent()
            le = UltimateListEvent(wxEVT_COMMAND_LIST_ITEM_CHECKING, parent.GetId())
            le.m_itemIndex = item._itemId
            le.m_item = item
            le.SetEventObject(parent)

            if parent.GetEventHandler().ProcessEvent(le):
                # Blocked by user
                return

        item.Check(checked)
        self.SetItem(item)
        self.RefreshLine(item._itemId)

        if not sendEvent:
            return

        le = UltimateListEvent(wxEVT_COMMAND_LIST_ITEM_CHECKED, parent.GetId())
        le.m_itemIndex = item._itemId
        le.m_item = item
        le.SetEventObject(parent)
        parent.GetEventHandler().ProcessEvent(le)

[docs]    def AutoCheckChild(self, isChecked, column):
        """
        Checks/unchecks all the items.

        :param `isChecked`: ``True`` to check the items, ``False`` to uncheck them;
        :param `column`: the column to which the items belongs to.

        :note: This method is meaningful only for checkbox-like and radiobutton-like items.
        """

        for indx in xrange(self.GetItemCount()):
            item = CreateListItem(indx, column)
            newItem = self.GetItem(item, column)
            self.CheckItem(newItem, not isChecked, False)

[docs]    def AutoToggleChild(self, column):
        """
        Toggles all the items.

        :param `column`: the column to which the items belongs to.

        :note: This method is meaningful only for checkbox-like and radiobutton-like items.
        """

        for indx in xrange(self.GetItemCount()):
            item = CreateListItem(indx, column)
            newItem = self.GetItem(item, column)

            if newItem.GetKind() != 1:
                continue

            self.CheckItem(newItem, not item.IsChecked(), False)

[docs]    def IsItemChecked(self, item):
        """
        Returns whether an item is checked or not.

        :param `item`: an instance of L{UltimateListItem}.
        """

        item = self.GetItem(item, item._col)
        return item.IsChecked()

[docs]    def IsItemEnabled(self, item):
        """
        Returns whether an item is enabled or not.

        :param `item`: an instance of L{UltimateListItem}.
        """

        item = self.GetItem(item, item._col)
        return item.IsEnabled()

[docs]    def EnableItem(self, item, enable=True):
        """
        Enables/disables an item.

        :param `item`: an instance of L{UltimateListItem};
        :param `enable`: ``True`` to enable the item, ``False`` otherwise.
        """

        item = self.GetItem(item, 0)
        if item.IsEnabled() == enable:
            return False

        item.Enable(enable)

        wnd = item.GetWindow()
        # Handles the eventual window associated to the item
        if wnd:
            wnd.Enable(enable)

        self.SetItem(item)

        return True

[docs]    def GetItemKind(self, item):
        """
        Returns the item kind.

        :param `item`: an instance of L{UltimateListItem}.

        :see: L{SetItemKind} for a list of valid item kinds.
        """

        item = self.GetItem(item, item._col)
        return item.GetKind()

[docs]    def SetItemKind(self, item, kind):
        """
        Sets the item kind.

        :param `item`: an instance of L{UltimateListItem};
        :param `kind`: may be one of the following integers:

         =============== ==========================
         Item Kind       Description
         =============== ==========================
                0        A normal item
                1        A checkbox-like item
                2        A radiobutton-type item
         =============== ==========================

        """

        item = self.GetItem(item, item._col)
        item.SetKind(kind)
        self.SetItem(item)

        return True

[docs]    def IsItemHyperText(self, item):
        """
        Returns whether an item is hypertext or not.

        :param `item`: an instance of L{UltimateListItem}.
        """

        item = self.GetItem(item, item._col)
        return item.IsHyperText()

[docs]    def SetItemHyperText(self, item, hyper=True):
        """
        Sets whether the item is hypertext or not.

        :param `item`: an instance of L{UltimateListItem};
        :param `hyper`: ``True`` to have an item with hypertext behaviour, ``False`` otherwise.
        """

        item = self.GetItem(item, item._col)
        item.SetHyperText(hyper)
        self.SetItem(item)

        return True

[docs]    def GetHyperTextFont(self):
        """Returns the font used to render an hypertext item."""

        return self._hypertextfont

[docs]    def SetHyperTextFont(self, font):
        """
        Sets the font used to render hypertext items.

        :param `font`: a valid `wx.Font` instance.
        """

        self._hypertextfont = font
        self._dirty = True

[docs]    def SetHyperTextNewColour(self, colour):
        """
        Sets the colour used to render a non-visited hypertext item.

        :param `colour`: a valid `wx.Colour` instance.
        """

        self._hypertextnewcolour = colour
        self._dirty = True

[docs]    def GetHyperTextNewColour(self):
        """ Returns the colour used to render a non-visited hypertext item. """

        return self._hypertextnewcolour

[docs]    def SetHyperTextVisitedColour(self, colour):
        """
        Sets the colour used to render a visited hypertext item.

        :param `colour`: a valid `wx.Colour` instance.
        """

        self._hypertextvisitedcolour = colour
        self._dirty = True

[docs]    def GetHyperTextVisitedColour(self):
        """ Returns the colour used to render a visited hypertext item. """

        return self._hypertextvisitedcolour

[docs]    def SetItemVisited(self, item, visited=True):
        """
        Sets whether an hypertext item was visited.

        :param `item`: an instance of L{UltimateListItem};
        :param `visited`: ``True`` to mark an hypertext item as visited, ``False`` otherwise.
        """

        newItem = self.GetItem(item, item._col)
        newItem.SetVisited(visited)
        self.SetItem(newItem)
        self.RefreshLine(item)

        return True

[docs]    def GetItemVisited(self, item):
        """
        Returns whether an hypertext item was visited.

        :param `item`: an instance of L{UltimateListItem}.
        """

        item = self.GetItem(item, item._col)
        return item.GetVisited()

[docs]    def GetItemWindow(self, item):
        """
        Returns the window associated to the item (if any).

        :param `item`: an instance of L{UltimateListItem}.
        """

        item = self.GetItem(item, item._col)
        return item.GetWindow()

[docs]    def SetItemWindow(self, item, wnd, expand=False):
        """
        Sets the window for the given item.

        :param `item`: an instance of L{UltimateListItem};
        :param `wnd`: if not ``None``, a non-toplevel window to be displayed next to
         the item;
        :param `expand`: ``True`` to expand the column where the item/subitem lives,
         so that the window will be fully visible.
        """

        if not self.InReportView() or not self.HasAGWFlag(ULC_HAS_VARIABLE_ROW_HEIGHT):
            raise Exception("Widgets are only allowed in report mode and with the ULC_HAS_VARIABLE_ROW_HEIGHT style.")

        item = self.GetItem(item, item._col)

        if wnd is not None:
            self._hasWindows = True
            if item not in self._itemWithWindow:
                self._itemWithWindow.append(item)
            else:
                self.DeleteItemWindow(item)
        else:
            self.DeleteItemWindow(item)

        item.SetWindow(wnd, expand)
        self.SetItem(item)
        self.RecalculatePositions()
        self.Refresh()

[docs]    def DeleteItemWindow(self, item):
        """
        Deletes the window associated to an item (if any).

        :param `item`: an instance of L{UltimateListItem}.
        """

        if item.GetWindow() is None:
            return

        item.DeleteWindow()
        if item in self._itemWithWindow:
            self._itemWithWindow.remove(item)

        self.SetItem(item)
        self.RecalculatePositions()

[docs]    def GetItemWindowEnabled(self, item):
        """
        Returns whether the window associated to the item is enabled.

        :param `item`: an instance of L{UltimateListItem}.
        """

        item = self.GetItem(item, item._col)
        return item.GetWindowEnabled()

[docs]    def SetItemWindowEnabled(self, item, enable=True):
        """
        Enables/disables the window associated to the item.

        :param `item`: an instance of L{UltimateListItem};
        :param `enable`: ``True`` to enable the associated window, ``False`` to
         disable it.
        """

        item = self.GetItem(item, item._col)
        item.SetWindowEnabled(enable)
        self.SetItem(item)
        self.Refresh()

[docs]    def SetColumnCustomRenderer(self, col=0, renderer=None):
        """
        Associate a custom renderer to this column's header

        :param `col`: the column index.
        :param `renderer`: a class able to correctly render the input item.

        :note: the renderer class **must** implement the methods `DrawHeaderButton`
         and `GetForegroundColor`.
        """

        self._columns[col].SetCustomRenderer(renderer)

[docs]    def GetColumnCustomRenderer(self, col):
        """
        Returns the custom renderer used to draw the column header

        :param `col`: the column index.
        """

        return self._columns[col].GetCustomRenderer()

[docs]    def GetItemCustomRenderer(self, item):
        """
        Returns the custom renderer used to draw the input item (if any).

        :param `item`: an instance of L{UltimateListItem}.
        """

        item = self.GetItem(item, item._col)
        return item.GetCustomRenderer()

[docs]    def SetItemCustomRenderer(self, item, renderer=None):
        """
        Associate a custom renderer to this item.

        :param `item`: an instance of L{UltimateListItem};
        :param `renderer`: a class able to correctly render the item.

        :note: the renderer class **must** implement the methods `DrawSubItem`,
         `GetLineHeight` and `GetSubItemWidth`.
        """

        item = self.GetItem(item, item._col)
        item.SetCustomRenderer(renderer)
        self.SetItem(item)
        self.ResetLineDimensions()
        self.Refresh()

[docs]    def GetItemOverFlow(self, item):
        """
        Returns if the item is in the overflow state.

        An item/subitem may overwrite neighboring items/subitems if its text would
        not normally fit in the space allotted to it.

        :param `item`: an instance of L{UltimateListItem}.
        """

        item = self.GetItem(item, item._col)
        return item.GetOverFlow()

[docs]    def SetItemOverFlow(self, item, over=True):
        """
        Sets the item in the overflow/non overflow state.

        An item/subitem may overwrite neighboring items/subitems if its text would
        not normally fit in the space allotted to it.

        :param `item`: an instance of L{UltimateListItem};
        :param `over`: ``True`` to set the item in a overflow state, ``False`` otherwise.
        """

        item = self.GetItem(item, item._col)
        item.SetOverFlow(over)
        self.SetItem(item)
        self.Refresh()

# ----------------------------------------------------------------------------
# item count
# ----------------------------------------------------------------------------

[docs]    def GetItemCount(self):
        """ Returns the number of items in the L{UltimateListCtrl}. """

        return (self.IsVirtual() and [self._countVirt] or [len(self._lines)])[0]

[docs]    def SetItemCount(self, count):
        """
        This method can only be used with virtual L{UltimateListCtrl}. It is used to
        indicate to the control the number of items it contains. After calling it,
        the main program should be ready to handle calls to various item callbacks
        (such as L{UltimateListCtrl.OnGetItemText}) for all items in the range from 0 to `count`.

        :param `count`: the total number of items in L{UltimateListCtrl}.
        """

        self._selStore.SetItemCount(count)
        self._countVirt = count

        self.ResetVisibleLinesRange()

        # scrollbars must be reset
        self._dirty = True

[docs]    def GetSelectedItemCount(self):
        """ Returns the number of selected items in L{UltimateListCtrl}. """

        # deal with the quick case first
        if self.IsSingleSel():
            return (self.HasCurrent() and [self.IsHighlighted(self._current)] or [False])[0]

        # virtual controls remmebers all its selections itself
        if self.IsVirtual():
            return self._selStore.GetSelectedCount()

        # TODO: we probably should maintain the number of items selected even for
        #       non virtual controls as enumerating all lines is really slow...
        countSel = 0
        count = self.GetItemCount()
        for line in xrange(count):
            if self.GetLine(line).IsHighlighted():
                countSel += 1

        return countSel

# ----------------------------------------------------------------------------
# item position/size
# ----------------------------------------------------------------------------

[docs]    def GetViewRect(self):
        """
        Returns the rectangle taken by all items in the control. In other words,
        if the controls client size were equal to the size of this rectangle, no
        scrollbars would be needed and no free space would be left.

        :note: This function only works in the icon and small icon views, not in
         list or report views.
        """

        if self.HasAGWFlag(ULC_LIST):
            raise Exception("UltimateListCtrl.GetViewRect() not implemented for list view")

        # we need to find the longest/tallest label
        xMax = yMax = 0
        count = self.GetItemCount()

        if count:
            for i in xrange(count):
                # we need logical, not physical, coordinates here, so use
                # GetLineRect() instead of GetItemRect()
                r = self.GetLineRect(i)
                x, y = r.GetRight(), r.GetBottom()

                if x > xMax:
                    xMax = x
                if y > yMax:
                    yMax = y

        # some fudge needed to make it look prettier
        xMax += 2*EXTRA_BORDER_X
        yMax += 2*EXTRA_BORDER_Y

        # account for the scrollbars if necessary
        sizeAll = self.GetClientSize()
        if xMax > sizeAll.x:
            yMax += wx.SystemSettings.GetMetric(wx.SYS_HSCROLL_Y)
        if yMax > sizeAll.y:
            xMax += wx.SystemSettings.GetMetric(wx.SYS_VSCROLL_X)

        return wx.Rect(0, 0, xMax, yMax)

[docs]    def GetSubItemRect(self, item, subItem):
        """
        Returns the rectangle representing the size and position, in physical coordinates,
        of the given subitem, i.e. the part of the row `item` in the column `subItem`.

        :param `item`: the row in which the item lives;
        :param `subItem`: the column in which the item lives. If set equal to the special
         value ``ULC_GETSUBITEMRECT_WHOLEITEM`` the return value is the same as for
         L{GetItemRect}.

        :note: This method is only meaningful when the L{UltimateListCtrl} is in the
         report mode.
        """

        if not self.InReportView() and subItem == ULC_GETSUBITEMRECT_WHOLEITEM:
            raise Exception("GetSubItemRect only meaningful in report view")

        if item < 0 or item >= self.GetItemCount():
            raise Exception("invalid item in GetSubItemRect")

        # ensure that we're laid out, otherwise we could return nonsense
        if self._dirty:
            self.RecalculatePositions(True)

        rect = self.GetLineRect(item)

        # Adjust rect to specified column
        if subItem != ULC_GETSUBITEMRECT_WHOLEITEM:
            if subItem < 0 or subItem >= self.GetColumnCount():
                raise Exception("invalid subItem in GetSubItemRect")

            for i in xrange(subItem):
                rect.x += self.GetColumnWidth(i)

            rect.width = self.GetColumnWidth(subItem)

        rect.x, rect.y = self.CalcScrolledPosition(rect.x, rect.y)
        return rect

[docs]    def GetItemRect(self, item):
        """
        Returns the rectangle representing the item's size and position, in physical
        coordinates.

        :param `item`: the row in which the item lives.
        """

        return self.GetSubItemRect(item, ULC_GETSUBITEMRECT_WHOLEITEM)

[docs]    def GetItemPosition(self, item):
        """
        Returns the position of the item, in icon or small icon view.

        :param `item`: the row in which the item lives.
        """

        rect = self.GetItemRect(item)
        return wx.Point(rect.x, rect.y)

# ----------------------------------------------------------------------------
# geometry calculation
# ----------------------------------------------------------------------------

[docs]    def RecalculatePositions(self, noRefresh=False):
        """
        Recalculates all the items positions, and sets the scrollbars positions
        too.

        :param `noRefresh`: ``True`` to avoid calling `Refresh`, ``False`` otherwise.
        """

        count = self.GetItemCount()

        if self.HasAGWFlag(ULC_ICON) and self._normal_image_list:
            iconSpacing = self._normal_spacing
        elif self.HasAGWFlag(ULC_SMALL_ICON) and self._small_image_list:
            iconSpacing = self._small_spacing
        else:
            iconSpacing = 0

        # Note that we do not call GetClientSize() here but
        # GetSize() and subtract the border size for sunken
        # borders manually. This is technically incorrect,
        # but we need to know the client area's size WITHOUT
        # scrollbars here. Since we don't know if there are
        # any scrollbars, we use GetSize() instead. Another
        # solution would be to call SetScrollbars() here to
        # remove the scrollbars and call GetClientSize() then,
        # but this might result in flicker and - worse - will
        # reset the scrollbars to 0 which is not good at all
        # if you resize a dialog/window, but don't want to
        # reset the window scrolling. RR.
        # Furthermore, we actually do NOT subtract the border
        # width as 2 pixels is just the extra space which we
        # need around the actual content in the window. Other-
        # wise the text would e.g. touch the upper border. RR.
        clientWidth, clientHeight = self.GetSize()

        if self.InReportView():

            self.ResetVisibleLinesRange()

            if not self.HasAGWFlag(ULC_HAS_VARIABLE_ROW_HEIGHT):
                # all lines have the same height and we scroll one line per step

                lineHeight = self.GetLineHeight()
                entireHeight = count*lineHeight + LINE_SPACING
                decrement = 0
                if entireHeight > self.GetClientSize()[1]:
                    decrement = SCROLL_UNIT_X

                self._linesPerPage = clientHeight/lineHeight

                self.SetScrollbars(SCROLL_UNIT_X, lineHeight,
                                   (self.GetHeaderWidth()-decrement)/SCROLL_UNIT_X,
                                   (entireHeight + lineHeight - 1)/lineHeight,
                                   self.GetScrollPos(wx.HORIZONTAL),
                                   self.GetScrollPos(wx.VERTICAL),
                                   True)

            else:

                if count > 0:
                    entireHeight = self.GetLineY(count-1) + self.GetLineHeight(count-1) + LINE_SPACING
                    lineFrom, lineTo = self.GetVisibleLinesRange()
                    self._linesPerPage = lineTo - lineFrom + 1
                else:
                    lineHeight = self.GetLineHeight()
                    entireHeight = count*lineHeight + LINE_SPACING
                    self._linesPerPage = clientHeight/lineHeight

                decrement = 0
                if entireHeight > self.GetClientSize()[1]:
                    decrement = SCROLL_UNIT_X

                self.SetScrollbars(SCROLL_UNIT_X, SCROLL_UNIT_Y,
                                   (self.GetHeaderWidth()-decrement)/SCROLL_UNIT_X,
                                   (entireHeight + SCROLL_UNIT_Y - 1)/SCROLL_UNIT_Y,
                                   self.GetScrollPos(wx.HORIZONTAL),
                                   self.GetScrollPos(wx.VERTICAL),
                                   True)

        else: # !report

            dc = wx.ClientDC(self)
            dc.SetFont(self.GetFont())

            lineHeight = self.GetLineHeight()

            # we have 3 different layout strategies: either layout all items
            # horizontally/vertically (ULC_ALIGN_XXX styles explicitly given) or
            # to arrange them in top to bottom, left to right (don't ask me why
            # not the other way round...) order
            if self.HasAGWFlag(ULC_ALIGN_LEFT | ULC_ALIGN_TOP):

                x = EXTRA_BORDER_X
                y = EXTRA_BORDER_Y
                widthMax = 0

                for i in xrange(count):

                    line = self.GetLine(i)
                    line.CalculateSize(dc, iconSpacing)
                    line.SetPosition(x, y, iconSpacing)

                    sizeLine = self.GetLineSize(i)

                    if self.HasAGWFlag(ULC_ALIGN_TOP):

                        if sizeLine.x > widthMax:
                            widthMax = sizeLine.x

                        y += sizeLine.y

                    else: # ULC_ALIGN_LEFT

                        x += sizeLine.x + MARGIN_BETWEEN_ROWS

                if self.HasAGWFlag(ULC_ALIGN_TOP):

                    # traverse the items again and tweak their sizes so that they are
                    # all the same in a row
                    for i in xrange(count):

                        line = self.GetLine(i)
                        line._gi.ExtendWidth(widthMax)

                self.SetScrollbars(SCROLL_UNIT_X, lineHeight,
                                   (x + SCROLL_UNIT_X)/SCROLL_UNIT_X,
                                   (y + lineHeight)/lineHeight,
                                   self.GetScrollPos(wx.HORIZONTAL),
                                   self.GetScrollPos(wx.VERTICAL),
                                   True)

            else: # "flowed" arrangement, the most complicated case

                # at first we try without any scrollbars, if the items don't fit into
                # the window, we recalculate after subtracting the space taken by the
                # scrollbar

                entireWidth = 0

                for tries in xrange(2):

                    entireWidth = 2*EXTRA_BORDER_X

                    if tries == 1:

                        # Now we have decided that the items do not fit into the
                        # client area, so we need a scrollbar
                        entireWidth += SCROLL_UNIT_X

                    x = EXTRA_BORDER_X
                    y = EXTRA_BORDER_Y
                    maxWidthInThisRow = 0

                    self._linesPerPage = 0
                    currentlyVisibleLines = 0

                    for i in xrange(count):

                        currentlyVisibleLines += 1
                        line = self.GetLine(i)
                        line.CalculateSize(dc, iconSpacing)
                        line.SetPosition(x, y, iconSpacing)

                        sizeLine = self.GetLineSize(i)

                        if maxWidthInThisRow < sizeLine.x:
                            maxWidthInThisRow = sizeLine.x

                        y += sizeLine.y
                        if currentlyVisibleLines > self._linesPerPage:
                            self._linesPerPage = currentlyVisibleLines

                        if y + sizeLine.y >= clientHeight:

                            currentlyVisibleLines = 0
                            y = EXTRA_BORDER_Y
                            maxWidthInThisRow += MARGIN_BETWEEN_ROWS
                            x += maxWidthInThisRow
                            entireWidth += maxWidthInThisRow
                            maxWidthInThisRow = 0

                        # We have reached the last item.
                        if i == count - 1:
                            entireWidth += maxWidthInThisRow

                        if tries == 0 and entireWidth + SCROLL_UNIT_X > clientWidth:
                            clientHeight -= wx.SystemSettings.GetMetric(wx.SYS_HSCROLL_Y)
                            self._linesPerPage = 0
                            break

                        if i == count - 1:
                            break  # Everything fits, no second try required.

                self.SetScrollbars(SCROLL_UNIT_X, lineHeight,
                                   (entireWidth + SCROLL_UNIT_X)/SCROLL_UNIT_X,
                                   0,
                                   self.GetScrollPos(wx.HORIZONTAL),
                                   0,
                                   True)

        self._dirty = False
        if not noRefresh:
            # FIXME: why should we call it from here?
            self.UpdateCurrent()
            self.RefreshAll()

[docs]    def RefreshAll(self):
        """ Refreshes the entire L{UltimateListCtrl}. """

        self._dirty = False
        self.Refresh()

        headerWin = self.GetListCtrl()._headerWin
        if headerWin and headerWin._dirty:
            headerWin._dirty = False
            headerWin.Refresh()

[docs]    def UpdateCurrent(self):
        """ Updates the current line selection. """

        if not self.HasCurrent() and not self.IsEmpty():
            self.ChangeCurrent(0)

[docs]    def GetNextItem(self, item, geometry=ULC_NEXT_ALL, state=ULC_STATE_DONTCARE):
        """
        Searches for an item with the given `geometry` or `state`, starting from `item`
        but excluding the `item` itself.

        :param `item`: the item at which starting the search. If set to -1, the first
         item that matches the specified flags will be returned.
        :param `geometry`: can be one of:

         =================== ========= =================================
         Geometry Flag       Hex Value Description
         =================== ========= =================================
         ``ULC_NEXT_ABOVE``        0x0 Searches for an item above the specified item
         ``ULC_NEXT_ALL``          0x1 Searches for subsequent item by index
         ``ULC_NEXT_BELOW``        0x2 Searches for an item below the specified item
         ``ULC_NEXT_LEFT``         0x3 Searches for an item to the left of the specified item
         ``ULC_NEXT_RIGHT``        0x4 Searches for an item to the right of the specified item
         =================== ========= =================================

        :param `state`: any combination of the following bits:

         ============================ ========= ==============================
         State Bits                   Hex Value Description
         ============================ ========= ==============================
         ``ULC_STATE_DONTCARE``             0x0 Don't care what the state is
         ``ULC_STATE_DROPHILITED``          0x1 The item is highlighted to receive a drop event
         ``ULC_STATE_FOCUSED``              0x2 The item has the focus
         ``ULC_STATE_SELECTED``             0x4 The item is selected
         ``ULC_STATE_CUT``                  0x8 The item is in the cut state
         ``ULC_STATE_DISABLED``            0x10 The item is disabled
         ``ULC_STATE_FILTERED``            0x20 The item has been filtered
         ``ULC_STATE_INUSE``               0x40 The item is in use
         ``ULC_STATE_PICKED``              0x80 The item has been picked
         ``ULC_STATE_SOURCE``             0x100 The item is a drag and drop source
         ============================ ========= ==============================

        :return: The first item with given `state` following `item` or -1 if no such item found.

        :note: This function may be used to find all selected items in the
         control like this::

             item = -1

             while 1:
                 item = listctrl.GetNextItem(item, ULC_NEXT_ALL, ULC_STATE_SELECTED)

                 if item == -1:
                     break

                 # This item is selected - do whatever is needed with it

                 wx.LogMessage("Item %ld is selected."%item)

        """

        ret = item
        maxI = self.GetItemCount()

        # notice that we start with the next item (or the first one if item == -1)
        # and this is intentional to allow writing a simple loop to iterate over
        # all selected items
        ret += 1

        if ret == maxI:
            # this is not an error because the index was ok initially, just no
            # such item
            return -1

        if not state:
            # any will do
            return ret

        for line in xrange(ret, maxI):
            if state & ULC_STATE_FOCUSED and line == self._current:
                return line

            if state & ULC_STATE_SELECTED and self.IsHighlighted(line):
                return line

        return -1

# ----------------------------------------------------------------------------
# deleting stuff
# ----------------------------------------------------------------------------

[docs]    def DeleteItem(self, lindex):
        """
        Deletes the specified item.

        :param `lindex`: the index of the item to delete.

        :note: This function sends the ``EVT_LIST_DELETE_ITEM`` event for the item
         being deleted.
        """

        count = self.GetItemCount()
        if lindex < 0 or lindex >= self.GetItemCount():
            raise Exception("invalid item index in DeleteItem")

        # we don't need to adjust the index for the previous items
        if self.HasCurrent() and self._current >= lindex:

            # if the current item is being deleted, we want the next one to
            # become selected - unless there is no next one - so don't adjust
            # self._current in this case
            if self._current != lindex or self._current == count - 1:
                self._current -= 1

        if self.InReportView():

            #  mark the Column Max Width cache as dirty if the items in the line
            #  we're deleting contain the Max Column Width
            line = self.GetLine(lindex)
            item = UltimateListItem()

            for i in xrange(len(self._columns)):
                itemData = line._items[i]
                item = itemData.GetItem(item)
                itemWidth = self.GetItemWidthWithImage(item)

                if itemWidth >= self._aColWidths[i]._nMaxWidth:
                    self._aColWidths[i]._bNeedsUpdate = True

                if item.GetWindow():
                    self.DeleteItemWindow(item)

            self.ResetVisibleLinesRange(True)
            self._current = -1

        self.SendNotify(lindex, wxEVT_COMMAND_LIST_DELETE_ITEM)

        if self.IsVirtual():
            self._countVirt -= 1
            self._selStore.OnItemDelete(lindex)

        else:
            self._lines.pop(lindex)

        # we need to refresh the (vert) scrollbar as the number of items changed
        self._dirty = True
        self._lineHeight = 0
        self.ResetLineDimensions(True)
        self.RecalculatePositions()
        self.RefreshAfter(lindex)

[docs]    def DeleteColumn(self, col):
        """
        Deletes the specified column.

        :param `col`: the index of the column to delete.
        """

        self._columns.pop(col)
        self._dirty = True

        if not self.IsVirtual():
            # update all the items
            for i in xrange(len(self._lines)):
                line = self.GetLine(i)
                line._items.pop(col)

        if self.InReportView():   #  we only cache max widths when in Report View
            self._aColWidths.pop(col)

        # invalidate it as it has to be recalculated
        self._headerWidth = 0

[docs]    def DoDeleteAllItems(self):
        """ Actually performs the deletion of all the items. """

        if self.IsEmpty():
            # nothing to do - in particular, don't send the event
            return

        self.ResetCurrent()

        # to make the deletion of all items faster, we don't send the
        # notifications for each item deletion in this case but only one event
        # for all of them: this is compatible with wxMSW and documented in
        # DeleteAllItems() description

        event = UltimateListEvent(wxEVT_COMMAND_LIST_DELETE_ALL_ITEMS, self.GetParent().GetId())
        event.SetEventObject(self.GetParent())
        self.GetParent().GetEventHandler().ProcessEvent(event)

        if self.IsVirtual():
            self._countVirt = 0
            self._selStore.Clear()

        if self.InReportView():
            self.ResetVisibleLinesRange(True)
            for i in xrange(len(self._aColWidths)):
                self._aColWidths[i]._bNeedsUpdate = True

        for item in self._itemWithWindow:
            if item.GetWindow():
                self.DeleteItemWindow(item)

        self._lines = []
        self._itemWithWindow = []
        self._hasWindows = False

[docs]    def DeleteAllItems(self):
        """
        Deletes all items in the L{UltimateListCtrl}.

        :note: This function does not send the ``EVT_LIST_DELETE_ITEM`` event because
         deleting many items from the control would be too slow then (unlike L{DeleteItem}).
        """

        self.DoDeleteAllItems()
        self.RecalculatePositions()

[docs]    def DeleteEverything(self):
        """ Deletes all items in the L{UltimateListCtrl}, resetting column widths to zero. """

        self._columns = []
        self._aColWidths = []

        self.DeleteAllItems()

# ----------------------------------------------------------------------------
# scanning for an item
# ----------------------------------------------------------------------------

[docs]    def EnsureVisible(self, index):
        """
        Ensures this item is visible.

        :param `index`: the index of the item to scroll into view.
        """

        if index < 0 or index >= self.GetItemCount():
            raise Exception("invalid item index in EnsureVisible")

        # We have to call this here because the label in question might just have
        # been added and its position is not known yet
        if self._dirty:
            self.RecalculatePositions(True)

        self.MoveToItem(index)

[docs]    def FindItem(self, start, string, partial=False):
        """
        Find an item whose label matches this string.

        :param `start`: the starting point of the input `string` or the beginning
         if `start` is -1;
        :param `string`: the string to look for matches;
        :param `partial`: if ``True`` then this method will look for items which
         begin with `string`.

        :note: The string comparison is case insensitive.
        """

        if start < 0:
            start = 0

        str_upper = string.upper()
        count = self.GetItemCount()

        for i in xrange(start, count):
            line = self.GetLine(i)
            text = line.GetText(0)
            line_upper = text.upper()
            if not partial:
                if line_upper == str_upper:
                    return i
            else:
                if line_upper.find(str_upper) == 0:
                    return i

        return wx.NOT_FOUND

[docs]    def FindItemData(self, start, data):
        """
        Find an item whose data matches this data.

        :param `start`: the starting point of the input `data` or the beginning
         if `start` is -1;
        :param `data`: the data to look for matches.
        """

        if start < 0:
            start = 0

        count = self.GetItemCount()

        for i in xrange(start, count):
            line = self.GetLine(i)
            item = UltimateListItem()
            item = line.GetItem(0, item)

            if item._data == data:
                return i

        return wx.NOT_FOUND

[docs]    def FindItemAtPos(self, pt):
        """
        Find an item nearest this position.

        :param `pt`: an instance of `wx.Point`.
        """

        topItem, dummy = self.GetVisibleLinesRange()
        p = self.GetItemPosition(self.GetItemCount()-1)

        if p.y == 0:
            return topItem

        id = int(math.floor(pt.y*float(self.GetItemCount()-topItem-1)/p.y+topItem))

        if id >= 0 and id < self.GetItemCount():
            return id

        return wx.NOT_FOUND

[docs]    def HitTest(self, x, y):
        """
        HitTest method for a L{UltimateListCtrl}.

        :param `x`: the mouse `x` position;
        :param `y`: the mouse `y` position.

        :see: L{HitTestLine} for a list of return flags.
        """

        x, y = self.CalcUnscrolledPosition(x, y)
        count = self.GetItemCount()

        if self.InReportView():
            if not self.HasAGWFlag(ULC_HAS_VARIABLE_ROW_HEIGHT):
                current = y/self.GetLineHeight()
                if current < count:
                    newItem, flags = self.HitTestLine(current, x, y)
                    if flags:
                        return current, flags
            else:
                for current in xrange(self._lineFrom, count):
                    newItem, flags = self.HitTestLine(current, x, y)
                    if flags:
                        return current, flags

        else:
            # TODO: optimize it too! this is less simple than for report view but
            #       enumerating all items is still not a way to do it!!
            for current in xrange(count):
                newItem, flags = self.HitTestLine(current, x, y)
                if flags:
                    return current, flags

        return wx.NOT_FOUND, None

# ----------------------------------------------------------------------------
# adding stuff
# ----------------------------------------------------------------------------

[docs]    def InsertItem(self, item):
        """
        Inserts an item into L{UltimateListCtrl}.

        :param `item`: an instance of L{UltimateListItem}.
        """

        if self.IsVirtual():
            raise Exception("can't be used with virtual control")

        count = self.GetItemCount()
        if item._itemId < 0:
            raise Exception("invalid item index")

        CheckVariableRowHeight(self, item._text)

        if item._itemId > count:
            item._itemId = count

        id = item._itemId
        self._dirty = True

        if self.InReportView():
            self.ResetVisibleLinesRange(True)

            # calculate the width of the item and adjust the max column width
            pWidthInfo = self._aColWidths[item.GetColumn()]
            width = self.GetItemWidthWithImage(item)
            item.SetWidth(width)

            if width > pWidthInfo._nMaxWidth:
                pWidthInfo._nMaxWidth = width

        line = UltimateListLineData(self)
        line.SetItem(item._col, item)

        self._lines.insert(id, line)
        self._dirty = True

        # If an item is selected at or below the point of insertion, we need to
        # increment the member variables because the current row's index has gone
        # up by one
        if self.HasCurrent() and self._current >= id:
            self._current += 1

        self.SendNotify(id, wxEVT_COMMAND_LIST_INSERT_ITEM)
        self.RefreshLines(id, self.GetItemCount() - 1)

[docs]    def InsertColumn(self, col, item):
        """
        Inserts a column into L{UltimateListCtrl}.

        :param `col`: the column index at which we wish to insert a new column;
        :param `item`: an instance of L{UltimateListItem}.

        :note: This method is meaningful only if L{UltimateListCtrl} has the ``ULC_REPORT``
         or the ``ULC_TILE`` styles set.
        """

        self._dirty = True

        if self.InReportView() or self.InTileView() or self.HasAGWFlag(ULC_HEADER_IN_ALL_VIEWS):

            if item._width == ULC_AUTOSIZE_USEHEADER:
                item._width = self.GetTextLength(item._text)

            column = UltimateListHeaderData(item)
            colWidthInfo = ColWidthInfo()

            insert = (col >= 0) and (col < len(self._columns))

            if insert:
                self._columns.insert(col, column)
                self._aColWidths.insert(col, colWidthInfo)

            else:

                self._columns.append(column)
                self._aColWidths.append(colWidthInfo)

            if not self.IsVirtual():

                # update all the items
                for i in xrange(len(self._lines)):
                    line = self.GetLine(i)
                    data = UltimateListItemData(self)
                    if insert:
                        line._items.insert(col, data)
                    else:
                        line._items.append(data)

            # invalidate it as it has to be recalculated
            self._headerWidth = 0

[docs]    def GetItemWidthWithImage(self, item):
        """
        Returns the item width, in pixels, considering the item text and its images.

        :param `item`: an instance of L{UltimateListItem}.
        """

        if item.GetCustomRenderer():
            return item.GetCustomRenderer().GetSubItemWidth()

        width = 0
        dc = wx.ClientDC(self)

        if item.GetFont().IsOk():
            font = item.GetFont()
        else:
            font = self.GetFont()

        dc.SetFont(font)

        if item.GetKind() in [1, 2]:
            ix, iy = self.GetCheckboxImageSize()
            width += ix

        if item.GetImage():
            ix, iy = self.GetImageSize(item.GetImage())
            width += ix + IMAGE_MARGIN_IN_REPORT_MODE

        if item.GetText():
            w, h, dummy = dc.GetMultiLineTextExtent(item.GetText())
            width += w

        if item.GetWindow():
            width += item._windowsize.x + 5

        return width

[docs]    def GetItemTextSize(self, item):
        """
        Returns the item width, in pixels, considering only the item text.

        :param `item`: an instance of L{UltimateListItem}.
        """

        width = ix = iy = start = end = 0
        dc = wx.ClientDC(self)

        if item.HasFont():
            font = item.GetFont()
        else:
            font = self.GetFont()

        dc.SetFont(font)

        if item.GetKind() in [1, 2]:
            ix, iy = self.GetCheckboxImageSize()
            start += ix

        if item.GetImage():
            ix, iy = self.GetImageSize(item.GetImage())
            start += ix + IMAGE_MARGIN_IN_REPORT_MODE

        if item.GetText():
            w, h, dummy = dc.GetMultiLineTextExtent(item.GetText())
            end = w

        return start, end

# ----------------------------------------------------------------------------
# sorting
# ----------------------------------------------------------------------------

[docs]    def OnCompareItems(self, line1, line2):
        """
        Returns whether 2 lines have the same index.

        Override this function in the derived class to change the sort order of the items
        in the L{UltimateListCtrl}. The function should return a negative, zero or positive
        value if the first line is less than, equal to or greater than the second one.

        :param `line1`: an instance of L{UltimateListItem};
        :param `line2`: another instance of L{UltimateListItem}.

        :note: The base class version compares lines by their index.
        """

        item = UltimateListItem()
        item1 = line1.GetItem(0, item)
        item = UltimateListItem()
        item2 = line2.GetItem(0, item)

        data1 = item1._data
        data2 = item2._data

        if self.__func:
            return self.__func(data1, data2)
        else:
            return cmp(data1, data2)

[docs]    def SortItems(self, func):
        """
        Call this function to sort the items in the L{UltimateListCtrl}. Sorting is done
        using the specified function `func`. This function must have the
        following prototype::

            def OnCompareItems(self, line1, line2):

                DoSomething(line1, line2)
                # function code

        It is called each time when the two items must be compared and should return 0
        if the items are equal, negative value if the first item is less than the second
        one and positive value if the first one is greater than the second one.

        :param `func`: the method to use to sort the items. The default is to use the
         L{OnCompareItems} method.
        """

        self.HighlightAll(False)
        self.ResetCurrent()

        if self._hasWindows:
            self.HideWindows()

        if not func:
            self.__func = None
        else:
            self.__func = func

        self._lines.sort(self.OnCompareItems)

        if self.IsShownOnScreen():
            self._dirty = True
            self._lineHeight = 0
            self.ResetLineDimensions(True)

        self.RecalculatePositions(True)

# ----------------------------------------------------------------------------
# scrolling
# ----------------------------------------------------------------------------

[docs]    def OnScroll(self, event):
        """
        Handles the ``wx.EVT_SCROLLWIN`` event for L{UltimateListMainWindow}.

        :param `event`: a `wx.ScrollEvent` event to be processed.
        """

        event.Skip()

        # update our idea of which lines are shown when we redraw the window the
        # next time
        self.ResetVisibleLinesRange()

        if self.HasAGWFlag(ULC_HAS_VARIABLE_ROW_HEIGHT):
            wx.CallAfter(self.RecalculatePositions, True)

        if event.GetOrientation() == wx.HORIZONTAL:
            lc = self.GetListCtrl()

            if self.HasHeader():
                lc._headerWin.Refresh()
                lc._headerWin.Update()

            if self.HasFooter():
                lc._footerWin.Refresh()
                lc._footerWin.Update()

[docs]    def GetCountPerPage(self):
        """
        Returns the number of items that can fit vertically in the visible area
        of the L{UltimateListCtrl} (list or report view) or the total number of
        items in the list control (icon or small icon view).
        """

        if not self.HasAGWFlag(ULC_HAS_VARIABLE_ROW_HEIGHT):
            if not self._linesPerPage:
                self._linesPerPage = self.GetClientSize().y/self.GetLineHeight()

            return self._linesPerPage

        visibleFrom, visibleTo = self.GetVisibleLinesRange()
        self._linesPerPage = visibleTo - visibleFrom + 1

        return self._linesPerPage

[docs]    def GetVisibleLinesRange(self):
        """
        Returns the range of visible items on screen.

        :note: This method can be used only if L{UltimateListCtrl} has the ``ULC_REPORT``
         style set.
        """

        if not self.InReportView():
            raise Exception("this is for report mode only")

        if self._lineFrom == -1:

            count = self.GetItemCount()

            if count:

                if self.HasAGWFlag(ULC_HAS_VARIABLE_ROW_HEIGHT):

                    view_x, view_y = self.GetViewStart()
                    view_y *= SCROLL_UNIT_Y

                    for i in xrange(0, count):
                        rc = self.GetLineY(i)
                        if rc > view_y:
                            self._lineFrom = i - 1
                            break

                    if self._lineFrom < 0:
                        self._lineFrom = 0

                    self._lineTo = self._lineFrom
                    clientWidth, clientHeight = self.GetClientSize()

                    for i in xrange(self._lineFrom, count):
                        rc = self.GetLineY(i) + self.GetLineHeight(i)
                        if rc > view_y + clientHeight - 5:
                            break
                        self._lineTo += 1

                else:

                    # No variable row height
                    self._lineFrom = self.GetScrollPos(wx.VERTICAL)

                    # this may happen if SetScrollbars() hadn't been called yet
                    if self._lineFrom >= count:
                        self._lineFrom = count - 1

                    self._lineTo = self._lineFrom + self._linesPerPage

                # we redraw one extra line but this is needed to make the redrawing
                # logic work when there is a fractional number of lines on screen
                if self._lineTo >= count:
                    self._lineTo = count - 1

            else: # empty control

                self._lineFrom = -1
                self._lineTo = -1

        return self._lineFrom, self._lineTo

[docs]    def ResetTextControl(self):
        """ Called by L{UltimateListTextCtrl} when it marks itself for deletion."""

        self._textctrl.Destroy()
        self._textctrl = None

        self.RecalculatePositions()
        self.Refresh()

[docs]    def SetFirstGradientColour(self, colour=None):
        """
        Sets the first gradient colour for gradient-style selections.

        :param `colour`: if not ``None``, a valid `wx.Colour` instance. Otherwise,
         the colour is taken from the system value ``wx.SYS_COLOUR_HIGHLIGHT``.
        """

        if colour is None:
            colour = wx.SystemSettings_GetColour(wx.SYS_COLOUR_HIGHLIGHT)

        self._firstcolour = colour
        if self._usegradients:
            self.RefreshSelected()

[docs]    def SetSecondGradientColour(self, colour=None):
        """
        Sets the second gradient colour for gradient-style selections.

        :param `colour`: if not ``None``, a valid `wx.Colour` instance. Otherwise,
         the colour generated is a slightly darker version of the L{UltimateListCtrl}
         background colour.
        """

        if colour is None:
            # No colour given, generate a slightly darker from the
            # UltimateListCtrl background colour
            colour = self.GetBackgroundColour()
            r, g, b = int(colour.Red()), int(colour.Green()), int(colour.Blue())
            colour = ((r >> 1) + 20, (g >> 1) + 20, (b >> 1) + 20)
            colour = wx.Colour(colour[0], colour[1], colour[2])

        self._secondcolour = colour

        if self._usegradients:
            self.RefreshSelected()

[docs]    def GetFirstGradientColour(self):
        """ Returns the first gradient colour for gradient-style selections. """

        return self._firstcolour

[docs]    def GetSecondGradientColour(self):
        """ Returns the second gradient colour for gradient-style selections. """

        return self._secondcolour

[docs]    def EnableSelectionGradient(self, enable=True):
        """
        Globally enables/disables drawing of gradient selections.

        :param `enable`: ``True`` to enable gradient-style selections, ``False``
         to disable it.

        :note: Calling this method disables any Vista-style selection previously
         enabled.
        """

        self._usegradients = enable
        self._vistaselection = False
        self.RefreshSelected()

[docs]    def SetGradientStyle(self, vertical=0):
        """
        Sets the gradient style for gradient-style selections.

        :param `vertical`: 0 for horizontal gradient-style selections, 1 for vertical
         gradient-style selections.
        """

        # 0 = Horizontal, 1 = Vertical
        self._gradientstyle = vertical

        if self._usegradients:
            self.RefreshSelected()

[docs]    def GetGradientStyle(self):
        """
        Returns the gradient style for gradient-style selections.

        :return: 0 for horizontal gradient-style selections, 1 for vertical
         gradient-style selections.
        """

        return self._gradientstyle

[docs]    def EnableSelectionVista(self, enable=True):
        """
        Globally enables/disables drawing of Windows Vista selections.

        :param `enable`: ``True`` to enable Vista-style selections, ``False`` to
         disable it.

        :note: Calling this method disables any gradient-style selection previously
         enabled.
        """

        self._usegradients = False
        self._vistaselection = enable
        self.RefreshSelected()

[docs]    def SetBackgroundImage(self, image):
        """
        Sets the L{UltimateListCtrl} background image.

        :param `image`: if not ``None``, an instance of `wx.Bitmap`.

        :note: At present, the background image can only be used in "tile" mode.

        :todo: Support background images also in stretch and centered modes.
        """

        self._backgroundImage = image
        self.Refresh()

[docs]    def GetBackgroundImage(self):
        """
        Returns the L{UltimateListCtrl} background image (if any).

        :note: At present, the background image can only be used in "tile" mode.

        :todo: Support background images also in stretch and centered modes.
        """

        return self._backgroundImage

[docs]    def SetWaterMark(self, watermark):
        """
        Sets the L{UltimateListCtrl} watermark image to be displayed in the bottom
        right part of the window.

        :param `watermark`: if not ``None``, an instance of `wx.Bitmap`.

        :todo: Better support for this is needed.
        """

        self._waterMark = watermark
        self.Refresh()

[docs]    def GetWaterMark(self):
        """
        Returns the L{UltimateListCtrl} watermark image (if any), displayed in the
        bottom right part of the window.

        :todo: Better support for this is needed.
        """

        return self._waterMark

[docs]    def SetDisabledTextColour(self, colour):
        """
        Sets the items disabled colour.

        :param `colour`: an instance of `wx.Colour`.
        """

        # Disabled items colour
        self._disabledColour = colour
        self.Refresh()

[docs]    def GetDisabledTextColour(self):
        """ Returns the items disabled colour. """

        return self._disabledColour

[docs]    def ScrollList(self, dx, dy):
        """
        Scrolls the L{UltimateListCtrl}.

        :param `dx`: if in icon, small icon or report view mode, specifies the number
         of pixels to scroll. If in list view mode, `dx` specifies the number of
         columns to scroll.
        :param `dy`: always specifies the number of pixels to scroll vertically.
        """

        if not self.InReportView():
            # TODO: this should work in all views but is not implemented now
            return False

        top, bottom = self.GetVisibleLinesRange()

        if bottom == -1:
            return 0

        self.ResetVisibleLinesRange()

        if not self.HasAGWFlag(ULC_HAS_VARIABLE_ROW_HEIGHT):
            hLine = self.GetLineHeight()
            self.Scroll(-1, top + dy/hLine)
        else:
            self.Scroll(-1, top + dy/SCROLL_UNIT_Y)

        if wx.Platform == "__WXMAC__":
            # see comment in MoveToItem() for why we do this
            self.ResetVisibleLinesRange()

        return True

# -------------------------------------------------------------------------------------
# UltimateListCtrl
# -------------------------------------------------------------------------------------

[docs]class UltimateListCtrl(wx.PyControl):
    """
    UltimateListCtrl is a class that mimics the behaviour of `wx.ListCtrl`, with almost
    the same base functionalities plus some more enhancements. This class does
    not rely on the native control, as it is a full owner-drawn list control.
    """

[docs]    def __init__(self, parent, id=wx.ID_ANY, pos=wx.DefaultPosition, size=wx.DefaultSize,
                 style=0, agwStyle=0, validator=wx.DefaultValidator, name="UltimateListCtrl"):
        """
        Default class constructor.

        :param `parent`: parent window. Must not be ``None``;
        :param `id`: window identifier. A value of -1 indicates a default value;
        :param `pos`: the control position. A value of (-1, -1) indicates a default position,
         chosen by either the windowing system or wxPython, depending on platform;
        :param `size`: the control size. A value of (-1, -1) indicates a default size,
         chosen by either the windowing system or wxPython, depending on platform;
        :param `style`: the underlying `wx.PyControl` window style;
        :param `agwStyle`: the AGW-specific window style; can be almost any combination of the following
         bits:

         ===============================  =========== ====================================================================================================
         Window Styles                    Hex Value   Description
         ===============================  =========== ====================================================================================================
         ``ULC_VRULES``                           0x1 Draws light vertical rules between rows in report mode.
         ``ULC_HRULES``                           0x2 Draws light horizontal rules between rows in report mode.
         ``ULC_ICON``                             0x4 Large icon view, with optional labels.
         ``ULC_SMALL_ICON``                       0x8 Small icon view, with optional labels.
         ``ULC_LIST``                            0x10 Multicolumn list view, with optional small icons. Columns are computed automatically, i.e. you don't set columns as in ``ULC_REPORT``. In other words, the list wraps, unlike a `wx.ListBox`.
         ``ULC_REPORT``                          0x20 Single or multicolumn report view, with optional header.
         ``ULC_ALIGN_TOP``                       0x40 Icons align to the top. Win32 default, Win32 only.
         ``ULC_ALIGN_LEFT``                      0x80 Icons align to the left.
         ``ULC_AUTOARRANGE``                    0x100 Icons arrange themselves. Win32 only.
         ``ULC_VIRTUAL``                        0x200 The application provides items text on demand. May only be used with ``ULC_REPORT``.
         ``ULC_EDIT_LABELS``                    0x400 Labels are editable: the application will be notified when editing starts.
         ``ULC_NO_HEADER``                      0x800 No header in report mode.
         ``ULC_NO_SORT_HEADER``                0x1000 No Docs.
         ``ULC_SINGLE_SEL``                    0x2000 Single selection (default is multiple).
         ``ULC_SORT_ASCENDING``                0x4000 Sort in ascending order. (You must still supply a comparison callback in `wx.ListCtrl.SortItems`.)
         ``ULC_SORT_DESCENDING``               0x8000 Sort in descending order. (You must still supply a comparison callback in `wx.ListCtrl.SortItems`.)
         ``ULC_TILE``                         0x10000 Each item appears as a full-sized icon with a label of one or more lines beside it (partially implemented).
         ``ULC_NO_HIGHLIGHT``                 0x20000 No highlight when an item is selected.
         ``ULC_STICKY_HIGHLIGHT``             0x40000 Items are selected by simply hovering on them, with no need to click on them.
         ``ULC_STICKY_NOSELEVENT``            0x80000 Don't send a selection event when using ``ULC_STICKY_HIGHLIGHT`` style.
         ``ULC_SEND_LEFTCLICK``              0x100000 Send a left click event when an item is selected.
         ``ULC_HAS_VARIABLE_ROW_HEIGHT``     0x200000 The list has variable row heights.
         ``ULC_AUTO_CHECK_CHILD``            0x400000 When a column header has a checkbox associated, auto-check all the subitems in that column.
         ``ULC_AUTO_TOGGLE_CHILD``           0x800000 When a column header has a checkbox associated, toggle all the subitems in that column.
         ``ULC_AUTO_CHECK_PARENT``          0x1000000 Only meaningful foe checkbox-type items: when an item is checked/unchecked its column header item is checked/unchecked as well.
         ``ULC_SHOW_TOOLTIPS``              0x2000000 Show tooltips for ellipsized items/subitems (text too long to be shown in the available space) containing the full item/subitem text.
         ``ULC_HOT_TRACKING``               0x4000000 Enable hot tracking of items on mouse motion.
         ``ULC_BORDER_SELECT``              0x8000000 Changes border colour whan an item is selected, instead of highlighting the item.
         ``ULC_TRACK_SELECT``              0x10000000 Enables hot-track selection in a list control. Hot track selection means that an item is automatically selected when the cursor remains over the item for a certain period of time. The delay is retrieved on Windows using the `win32api` call `win32gui.SystemParametersInfo(win32con.SPI_GETMOUSEHOVERTIME)`, and is defaulted to 400ms on other platforms. This style applies to all views of `UltimateListCtrl`.
         ``ULC_HEADER_IN_ALL_VIEWS``       0x20000000 Show column headers in all view modes.
         ``ULC_NO_FULL_ROW_SELECT``        0x40000000 When an item is selected, the only the item in the first column is highlighted.
         ``ULC_FOOTER``                    0x80000000 Show a footer too (only when header is present).
         ``ULC_USER_ROW_HEIGHT``          0x100000000 Allows to set a custom row height (one value for all the items, only in report mode).
         ===============================  =========== ====================================================================================================

        :param `validator`: the window validator;
        :param `name`: the window name.
        """

        self._imageListNormal = None
        self._imageListSmall = None
        self._imageListState = None

        if not agwStyle & ULC_MASK_TYPE:
            raise Exception("UltimateListCtrl style should have exactly one mode bit set")

        if not (agwStyle & ULC_REPORT) and agwStyle & ULC_HAS_VARIABLE_ROW_HEIGHT:
            raise Exception("Style ULC_HAS_VARIABLE_ROW_HEIGHT can only be used in report, non-virtual mode")

        if agwStyle & ULC_STICKY_HIGHLIGHT and agwStyle & ULC_TRACK_SELECT:
            raise Exception("Styles ULC_STICKY_HIGHLIGHT and ULC_TRACK_SELECT can not be combined")

        if agwStyle & ULC_NO_HEADER and agwStyle & ULC_HEADER_IN_ALL_VIEWS:
            raise Exception("Styles ULC_NO_HEADER and ULC_HEADER_IN_ALL_VIEWS can not be combined")

        if agwStyle & ULC_USER_ROW_HEIGHT and (agwStyle & ULC_REPORT) == 0:
            raise Exception("Style ULC_USER_ROW_HEIGHT can be used only with ULC_REPORT")

        wx.PyControl.__init__(self, parent, id, pos, size, style|wx.CLIP_CHILDREN, validator, name)

        self._mainWin = None
        self._headerWin = None
        self._footerWin = None

        self._headerHeight = wx.RendererNative.Get().GetHeaderButtonHeight(self)
        self._footerHeight = self._headerHeight

        if wx.Platform == "__WXGTK__":
            style &= ~wx.BORDER_MASK
            style |= wx.BORDER_THEME
        else:
            if style & wx.BORDER_THEME:
                style -= wx.BORDER_THEME

        self._agwStyle = agwStyle
        if style & wx.SUNKEN_BORDER:
            style -= wx.SUNKEN_BORDER

        self._mainWin = UltimateListMainWindow(self, wx.ID_ANY, wx.Point(0, 0), wx.DefaultSize, style, agwStyle)

        sizer = wx.BoxSizer(wx.VERTICAL)
        sizer.Add(self._mainWin, 1, wx.GROW)
        self.SetSizer(sizer)

        self.Bind(wx.EVT_SIZE, self.OnSize)
        self.Bind(wx.EVT_SET_FOCUS, self.OnSetFocus)

        self.CreateOrDestroyHeaderWindowAsNeeded()
        self.CreateOrDestroyFooterWindowAsNeeded()

        self.SetInitialSize(size)
        wx.CallAfter(self.Layout)

[docs]    def CreateOrDestroyHeaderWindowAsNeeded(self):
        """ Creates or destroys the header window depending on the window style flags. """

        needs_header = self.HasHeader()
        has_header = self._headerWin is not None

        if needs_header == has_header:
            return

        if needs_header:

            self._headerWin = UltimateListHeaderWindow(self, wx.ID_ANY, self._mainWin,
                                                       wx.Point(0, 0),
                                                       wx.DefaultSize,
                                                       wx.TAB_TRAVERSAL, isFooter=False)

            # ----------------------------------------------------
            # How do you translate all this blah-blah to wxPython?
            # ----------------------------------------------------
            #if defined( __WXMAC__ ) && wxOSX_USE_COCOA_OR_CARBON
            #        wxFont font
            #if wxOSX_USE_ATSU_TEXT
            #        font.MacCreateFromThemeFont( kThemeSmallSystemFont )
            #else
            #        font.MacCreateFromUIFont( kCTFontSystemFontType )
            #endif
            #        m_headerWin->SetFont( font )
            #endif

            self.GetSizer().Prepend(self._headerWin, 0, wx.GROW)

        else:

            self.GetSizer().Detach(self._headerWin)
            self._headerWin.Destroy()
            self._headerWin = None

[docs]    def CreateOrDestroyFooterWindowAsNeeded(self):
        """ Creates or destroys the footer window depending on the window style flags. """

        needs_footer = self.HasFooter()
        has_footer = self._footerWin is not None

        if needs_footer == has_footer:
            return

        if needs_footer:

            self._footerWin = UltimateListHeaderWindow(self, wx.ID_ANY, self._mainWin,
                                                       wx.Point(0, 0),
                                                       wx.DefaultSize,
                                                       wx.TAB_TRAVERSAL, isFooter=True)

            # ----------------------------------------------------
            # How do you translate all this blah-blah to wxPython?
            # ----------------------------------------------------
            #if defined( __WXMAC__ ) && wxOSX_USE_COCOA_OR_CARBON
            #        wxFont font
            #if wxOSX_USE_ATSU_TEXT
            #        font.MacCreateFromThemeFont( kThemeSmallSystemFont )
            #else
            #        font.MacCreateFromUIFont( kCTFontSystemFontType )
            #endif
            #        m_headerWin->SetFont( font )
            #endif

            self.GetSizer().Add(self._footerWin, 0, wx.GROW)

        else:

            self.GetSizer().Detach(self._footerWin)
            self._footerWin.Destroy()
            self._footerWin = None

[docs]    def HasHeader(self):
        """ Returns ``True`` if L{UltimateListCtrl} has a header window. """

        return self._mainWin.HasHeader()

[docs]    def HasFooter(self):
        """ Returns ``True`` if L{UltimateListCtrl} has a footer window. """

        return self._mainWin.HasFooter()

[docs]    def GetDefaultBorder(self):
        """ Returns the default window border. """

        return wx.BORDER_THEME

[docs]    def SetSingleStyle(self, style, add=True):
        """
        Adds or removes a single window style.

        :param `style`: can be one of the following bits:

         ===============================  =========== ====================================================================================================
         Window Styles                    Hex Value   Description
         ===============================  =========== ====================================================================================================
         ``ULC_VRULES``                           0x1 Draws light vertical rules between rows in report mode.
         ``ULC_HRULES``                           0x2 Draws light horizontal rules between rows in report mode.
         ``ULC_ICON``                             0x4 Large icon view, with optional labels.
         ``ULC_SMALL_ICON``                       0x8 Small icon view, with optional labels.
         ``ULC_LIST``                            0x10 Multicolumn list view, with optional small icons. Columns are computed automatically, i.e. you don't set columns as in ``ULC_REPORT``. In other words, the list wraps, unlike a `wx.ListBox`.
         ``ULC_REPORT``                          0x20 Single or multicolumn report view, with optional header.
         ``ULC_ALIGN_TOP``                       0x40 Icons align to the top. Win32 default, Win32 only.
         ``ULC_ALIGN_LEFT``                      0x80 Icons align to the left.
         ``ULC_AUTOARRANGE``                    0x100 Icons arrange themselves. Win32 only.
         ``ULC_VIRTUAL``                        0x200 The application provides items text on demand. May only be used with ``ULC_REPORT``.
         ``ULC_EDIT_LABELS``                    0x400 Labels are editable: the application will be notified when editing starts.
         ``ULC_NO_HEADER``                      0x800 No header in report mode.
         ``ULC_NO_SORT_HEADER``                0x1000 No Docs.
         ``ULC_SINGLE_SEL``                    0x2000 Single selection (default is multiple).
         ``ULC_SORT_ASCENDING``                0x4000 Sort in ascending order. (You must still supply a comparison callback in `wx.ListCtrl.SortItems`.)
         ``ULC_SORT_DESCENDING``               0x8000 Sort in descending order. (You must still supply a comparison callback in `wx.ListCtrl.SortItems`.)
         ``ULC_TILE``                         0x10000 Each item appears as a full-sized icon with a label of one or more lines beside it (partially implemented).
         ``ULC_NO_HIGHLIGHT``                 0x20000 No highlight when an item is selected.
         ``ULC_STICKY_HIGHLIGHT``             0x40000 Items are selected by simply hovering on them, with no need to click on them.
         ``ULC_STICKY_NOSELEVENT``            0x80000 Don't send a selection event when using ``ULC_STICKY_HIGHLIGHT`` style.
         ``ULC_SEND_LEFTCLICK``              0x100000 Send a left click event when an item is selected.
         ``ULC_HAS_VARIABLE_ROW_HEIGHT``     0x200000 The list has variable row heights.
         ``ULC_AUTO_CHECK_CHILD``            0x400000 When a column header has a checkbox associated, auto-check all the subitems in that column.
         ``ULC_AUTO_TOGGLE_CHILD``           0x800000 When a column header has a checkbox associated, toggle all the subitems in that column.
         ``ULC_AUTO_CHECK_PARENT``          0x1000000 Only meaningful foe checkbox-type items: when an item is checked/unchecked its column header item is checked/unchecked as well.
         ``ULC_SHOW_TOOLTIPS``              0x2000000 Show tooltips for ellipsized items/subitems (text too long to be shown in the available space) containing the full item/subitem text.
         ``ULC_HOT_TRACKING``               0x4000000 Enable hot tracking of items on mouse motion.
         ``ULC_BORDER_SELECT``              0x8000000 Changes border colour whan an item is selected, instead of highlighting the item.
         ``ULC_TRACK_SELECT``              0x10000000 Enables hot-track selection in a list control. Hot track selection means that an item is automatically selected when the cursor remains over the item for a certain period of time. The delay is retrieved on Windows using the `win32api` call `win32gui.SystemParametersInfo(win32con.SPI_GETMOUSEHOVERTIME)`, and is defaulted to 400ms on other platforms. This style applies to all views of `UltimateListCtrl`.
         ``ULC_HEADER_IN_ALL_VIEWS``       0x20000000 Show column headers in all view modes.
         ``ULC_NO_FULL_ROW_SELECT``        0x40000000 When an item is selected, the only the item in the first column is highlighted.
         ``ULC_FOOTER``                    0x80000000 Show a footer too (only when header is present).
         ===============================  =========== ====================================================================================================

        :param `add`: ``True`` to add the window style, ``False`` to remove it.

        :note: The style ``ULC_VIRTUAL`` can not be set/unset after construction.
        """

        if style & ULC_VIRTUAL:
            raise Exception("ULC_VIRTUAL can't be [un]set")

        flag = self.GetAGWWindowStyleFlag()

        if add:

            if style & ULC_MASK_TYPE:
                flag &= ~(ULC_MASK_TYPE | ULC_VIRTUAL)
            if style & ULC_MASK_ALIGN:
                flag &= ~ULC_MASK_ALIGN
            if style & ULC_MASK_SORT:
                flag &= ~ULC_MASK_SORT

        if add:
            flag |= style
        else:
            flag &= ~style

        # some styles can be set without recreating everything (as happens in
        # SetAGWWindowStyleFlag() which calls ListMainWindow.DeleteEverything())
        if not style & ~(ULC_HRULES | ULC_VRULES):
            self.Refresh()
            self.SetAGWWindowStyleFlag(self, flag)
        else:
            self.SetAGWWindowStyleFlag(flag)

[docs]    def GetAGWWindowStyleFlag(self):
        """
        Returns the L{UltimateListCtrl} AGW-specific style flag.

        :see: L{SetAGWWindowStyleFlag} for a list of possible style flags.
        """

        return self._agwStyle

[docs]    def SetAGWWindowStyleFlag(self, style):
        """
        Sets the L{UltimateListCtrl} AGW-specific style flag.

        :param `style`: the AGW-specific window style; can be almost any combination of the following
         bits:

         ===============================  =========== ====================================================================================================
         Window Styles                    Hex Value   Description
         ===============================  =========== ====================================================================================================
         ``ULC_VRULES``                           0x1 Draws light vertical rules between rows in report mode.
         ``ULC_HRULES``                           0x2 Draws light horizontal rules between rows in report mode.
         ``ULC_ICON``                             0x4 Large icon view, with optional labels.
         ``ULC_SMALL_ICON``                       0x8 Small icon view, with optional labels.
         ``ULC_LIST``                            0x10 Multicolumn list view, with optional small icons. Columns are computed automatically, i.e. you don't set columns as in ``ULC_REPORT``. In other words, the list wraps, unlike a `wx.ListBox`.
         ``ULC_REPORT``                          0x20 Single or multicolumn report view, with optional header.
         ``ULC_ALIGN_TOP``                       0x40 Icons align to the top. Win32 default, Win32 only.
         ``ULC_ALIGN_LEFT``                      0x80 Icons align to the left.
         ``ULC_AUTOARRANGE``                    0x100 Icons arrange themselves. Win32 only.
         ``ULC_VIRTUAL``                        0x200 The application provides items text on demand. May only be used with ``ULC_REPORT``.
         ``ULC_EDIT_LABELS``                    0x400 Labels are editable: the application will be notified when editing starts.
         ``ULC_NO_HEADER``                      0x800 No header in report mode.
         ``ULC_NO_SORT_HEADER``                0x1000 No Docs.
         ``ULC_SINGLE_SEL``                    0x2000 Single selection (default is multiple).
         ``ULC_SORT_ASCENDING``                0x4000 Sort in ascending order. (You must still supply a comparison callback in `wx.ListCtrl.SortItems`.)
         ``ULC_SORT_DESCENDING``               0x8000 Sort in descending order. (You must still supply a comparison callback in `wx.ListCtrl.SortItems`.)
         ``ULC_TILE``                         0x10000 Each item appears as a full-sized icon with a label of one or more lines beside it (partially implemented).
         ``ULC_NO_HIGHLIGHT``                 0x20000 No highlight when an item is selected.
         ``ULC_STICKY_HIGHLIGHT``             0x40000 Items are selected by simply hovering on them, with no need to click on them.
         ``ULC_STICKY_NOSELEVENT``            0x80000 Don't send a selection event when using ``ULC_STICKY_HIGHLIGHT`` style.
         ``ULC_SEND_LEFTCLICK``              0x100000 Send a left click event when an item is selected.
         ``ULC_HAS_VARIABLE_ROW_HEIGHT``     0x200000 The list has variable row heights.
         ``ULC_AUTO_CHECK_CHILD``            0x400000 When a column header has a checkbox associated, auto-check all the subitems in that column.
         ``ULC_AUTO_TOGGLE_CHILD``           0x800000 When a column header has a checkbox associated, toggle all the subitems in that column.
         ``ULC_AUTO_CHECK_PARENT``          0x1000000 Only meaningful foe checkbox-type items: when an item is checked/unchecked its column header item is checked/unchecked as well.
         ``ULC_SHOW_TOOLTIPS``              0x2000000 Show tooltips for ellipsized items/subitems (text too long to be shown in the available space) containing the full item/subitem text.
         ``ULC_HOT_TRACKING``               0x4000000 Enable hot tracking of items on mouse motion.
         ``ULC_BORDER_SELECT``              0x8000000 Changes border colour whan an item is selected, instead of highlighting the item.
         ``ULC_TRACK_SELECT``              0x10000000 Enables hot-track selection in a list control. Hot track selection means that an item is automatically selected when the cursor remains over the item for a certain period of time. The delay is retrieved on Windows using the `win32api` call `win32gui.SystemParametersInfo(win32con.SPI_GETMOUSEHOVERTIME)`, and is defaulted to 400ms on other platforms. This style applies to all views of `UltimateListCtrl`.
         ``ULC_HEADER_IN_ALL_VIEWS``       0x20000000 Show column headers in all view modes.
         ``ULC_NO_FULL_ROW_SELECT``        0x40000000 When an item is selected, the only the item in the first column is highlighted.
         ``ULC_FOOTER``                    0x80000000 Show a footer too (only when header is present).
         ``ULC_USER_ROW_HEIGHT``          0x100000000 Allows to set a custom row height (one value for all the items, only in report mode).
         ===============================  =========== ====================================================================================================
         """

        if style & ULC_HAS_VARIABLE_ROW_HEIGHT and not self.HasAGWFlag(ULC_REPORT):
            raise Exception("ULC_HAS_VARIABLE_ROW_HEIGHT style can be used only in report mode")

        wasInReportView = self.HasAGWFlag(ULC_REPORT)
        self._agwStyle = style

        if self._mainWin:

            inReportView = (style & ULC_REPORT) != 0

            if inReportView != wasInReportView:
                # we need to notify the main window about this change as it must
                # update its data structures
                self._mainWin.SetReportView(inReportView)

            self.CreateOrDestroyHeaderWindowAsNeeded()
            self.CreateOrDestroyFooterWindowAsNeeded()
            self.GetSizer().Layout()

        if style & ULC_HAS_VARIABLE_ROW_HEIGHT:
            self._mainWin.ResetLineDimensions()
            self._mainWin.ResetVisibleLinesRange()

        self.Refresh()

[docs]    def HasAGWFlag(self, flag):
        """
        Returns ``True`` if the window has the given flag bit set.

        :param `flag`: the window style to check.

        :see: L{SetAGWWindowStyleFlag} for a list of valid window styles.
        """

        return self._agwStyle & flag

[docs]    def SetUserLineHeight(self, height):
        """
        Sets a custom value for the L{UltimateListCtrl} item height.

        :param `height`: the custom height for all the items, in pixels.

        :note: This method can be used only with ``ULC_REPORT`` and ``ULC_USER_ROW_HEIGHT`` styles set.
        """

        if self._mainWin:
            self._mainWin.SetUserLineHeight(height)

[docs]    def GetUserLineHeight(self):
        """
        Returns the custom value for the L{UltimateListCtrl} item height, if previously set with
        L{SetUserLineHeight}.

        :note: This method can be used only with ``ULC_REPORT`` and ``ULC_USER_ROW_HEIGHT`` styles set.
        """

        if self._mainWin:
            return self._mainWin.GetUserLineHeight()

[docs]    def GetColumn(self, col):
        """
        Returns information about this column.

        :param `col`: an integer specifying the column index.
        """

        return self._mainWin.GetColumn(col)

[docs]    def SetColumn(self, col, item):
        """
        Sets information about this column.

        :param `col`: an integer specifying the column index;
        :param `item`: an instance of L{UltimateListItem}.
        """

        self._mainWin.SetColumn(col, item)
        return True

[docs]    def GetColumnWidth(self, col):
        """
        Returns the column width for the input column.

        :param `col`: an integer specifying the column index.
        """

        return self._mainWin.GetColumnWidth(col)

[docs]    def SetColumnWidth(self, col, width):
        """
        Sets the column width.

        :param `width`: can be a width in pixels or ``wx.LIST_AUTOSIZE`` (-1) or
         ``wx.LIST_AUTOSIZE_USEHEADER`` (-2) or ``LIST_AUTOSIZE_FILL`` (-3).
         ``wx.LIST_AUTOSIZE`` will resize the column to the length of its longest
         item. ``wx.LIST_AUTOSIZE_USEHEADER`` will resize the column to the
         length of the header (Win32) or 80 pixels (other platforms).
         ``LIST_AUTOSIZE_FILL`` will resize the column fill the remaining width
         of the window.

        :note: In small or normal icon view, col must be -1, and the column width
         is set for all columns.
        """

        self._mainWin.SetColumnWidth(col, width)
        return True

[docs]    def GetCountPerPage(self):
        """
        Returns the number of items that can fit vertically in the visible area
        of the L{UltimateListCtrl} (list or report view) or the total number of
        items in the list control (icon or small icon view).
        """

        return self._mainWin.GetCountPerPage()  # different from Windows ?

[docs]    def GetItem(self, itemOrId, col=0):
        """
        Returns the information about the input item.

        :param `itemOrId`: an instance of L{UltimateListItem} or an integer specifying
         the item index;
        :param `col`: the column to which the item belongs to.
        """

        item = CreateListItem(itemOrId, col)
        return self._mainWin.GetItem(item, col)

[docs]    def SetItem(self, info):
        """
        Sets the information about the input item.

        :param `info`: an instance of L{UltimateListItem}.
        """

        self._mainWin.SetItem(info)
        return True

[docs]    def SetStringItem(self, index, col, label, imageIds=[], it_kind=0):
        """
        Sets a string or image at the given location.

        :param `index`: the item index;
        :param `col`: the column to which the item belongs to;
        :param `label`: the item text;
        :param `imageIds`: a Python list containing the image indexes for the
         images associated to this item;
        :param `it_kind`: the item kind. May be one of the following integers:

         =============== ==========================
         Item Kind       Description
         =============== ==========================
                0        A normal item
                1        A checkbox-like item
                2        A radiobutton-type item
         =============== ==========================

        """

        info = UltimateListItem()
        info._text = label
        info._mask = ULC_MASK_TEXT

        if it_kind:
            info._mask |= ULC_MASK_KIND
            info._kind = it_kind

        info._itemId = index
        info._col = col

        for ids in to_list(imageIds):
            if ids > -1:
                info._image.append(ids)

        if info._image:
            info._mask |= ULC_MASK_IMAGE

        self._mainWin.SetItem(info)
        return index

[docs]    def GetItemState(self, item, stateMask):
        """
        Returns the item state flags for the input item.

        :param `item`: the index of the item;
        :param `stateMask`: the bitmask for the state flag.

        :see: L{SetItemState} for a list of valid state flags.
        """

        return self._mainWin.GetItemState(item, stateMask)

[docs]    def SetItemState(self, item, state, stateMask):
        """
        Sets the item state flags for the input item.

        :param `item`: the index of the item; if defaulted to -1, the state flag
         will be set for all the items;
        :param `state`: any combination of the following bits:

         ============================ ========= ==============================
         State Bits                   Hex Value Description
         ============================ ========= ==============================
         ``ULC_STATE_DONTCARE``             0x0 Don't care what the state is
         ``ULC_STATE_DROPHILITED``          0x1 The item is highlighted to receive a drop event
         ``ULC_STATE_FOCUSED``              0x2 The item has the focus
         ``ULC_STATE_SELECTED``             0x4 The item is selected
         ``ULC_STATE_CUT``                  0x8 The item is in the cut state
         ``ULC_STATE_DISABLED``            0x10 The item is disabled
         ``ULC_STATE_FILTERED``            0x20 The item has been filtered
         ``ULC_STATE_INUSE``               0x40 The item is in use
         ``ULC_STATE_PICKED``              0x80 The item has been picked
         ``ULC_STATE_SOURCE``             0x100 The item is a drag and drop source
         ============================ ========= ==============================

        :param `stateMask`: the bitmask for the state flag.

        """

        self._mainWin.SetItemState(item, state, stateMask)
        return True

[docs]    def SetItemImage(self, item, image, selImage=-1):
        """
        Sets a Python list of image indexes associated with the item.

        :param `item`: an integer specifying the item index;
        :param `image`: a Python list of indexes into the image list associated
         with the L{UltimateListCtrl}. In report view, this only sets the images
         for the first column;
        :param `selImage`: not used at present.
        """

        return self.SetItemColumnImage(item, 0, image)

[docs]    def SetItemColumnImage(self, item, column, image):
        """
        Sets a Python list of image indexes associated with the item in the input
        column.

        :param `item`: an integer specifying the item index;
        :param `column`: the column to which the item belongs to;
        :param `image`: a Python list of indexes into the image list associated
         with the L{UltimateListCtrl}.
        """

        info = UltimateListItem()
        info._image = to_list(image)
        info._mask = ULC_MASK_IMAGE
        info._itemId = item
        info._col = column
        self._mainWin.SetItem(info)

        return True

[docs]    def GetItemText(self, item):
        """
        Returns the item text.

        :param `item`: an instance of L{UltimateListItem} or an integer specifying
         the item index.
        """

        return self._mainWin.GetItemText(item)

[docs]    def SetItemText(self, item, text):
        """
        Sets the item text.

        :param `item`: an instance of L{UltimateListItem} or an integer specifying
         the item index;
        :param `text`: the new item text.
        """

        self._mainWin.SetItemText(item, text)

[docs]    def GetItemData(self, item):
        """
        Gets the application-defined data associated with this item.

        :param `item`: an integer specifying the item index.
        """

        info = UltimateListItem()
        info._mask = ULC_MASK_DATA
        info._itemId = item
        self._mainWin.GetItem(info)
        return info._data

[docs]    def SetItemData(self, item, data):
        """
        Sets the application-defined data associated with this item.

        :param `item`: an integer specifying the item index;
        :param `data`: the data to be associated with the input item.

        :note: This function cannot be used to associate pointers with
         the control items, use L{SetItemPyData} instead.
        """

        info = UltimateListItem()
        info._mask = ULC_MASK_DATA
        info._itemId = item
        info._data = data
        self._mainWin.SetItem(info)
        return True

[docs]    def GetItemPyData(self, item):
        """
        Returns the data for the item, which can be any Python object.

        :param `item`: an integer specifying the item index.

        :note: Please note that Python data is associated with the item and not
         with subitems.
        """

        info = UltimateListItem()
        info._mask = ULC_MASK_PYDATA
        info._itemId = item
        self._mainWin.GetItem(info)
        return info._pyData

[docs]    def SetItemPyData(self, item, pyData):
        """
        Sets the data for the item, which can be any Python object.

        :param `item`: an integer specifying the item index;
        :param `pyData`: any Python object.

        :note: Please note that Python data is associated with the item and not
         with subitems.
        """

        info = UltimateListItem()
        info._mask = ULC_MASK_PYDATA
        info._itemId = item
        info._pyData = pyData
        self._mainWin.SetItem(info)
        return True

    SetPyData = SetItemPyData
    GetPyData = GetItemPyData

[docs]    def GetViewRect(self):
        """
        Returns the rectangle taken by all items in the control. In other words,
        if the controls client size were equal to the size of this rectangle, no
        scrollbars would be needed and no free space would be left.

        :note: This function only works in the icon and small icon views, not in
         list or report views.
        """

        return self._mainWin.GetViewRect()

[docs]    def GetItemRect(self, item, code=ULC_RECT_BOUNDS):
        """
        Returns the rectangle representing the item's size and position, in physical
        coordinates.

        :param `item`: the row in which the item lives;
        :param `code`: one of ``ULC_RECT_BOUNDS``, ``ULC_RECT_ICON``, ``ULC_RECT_LABEL``.
        """

        return self.GetSubItemRect(item, ULC_GETSUBITEMRECT_WHOLEITEM, code)

[docs]    def GetSubItemRect(self, item, subItem, code):
        """
        Returns the rectangle representing the size and position, in physical coordinates,
        of the given subitem, i.e. the part of the row `item` in the column `subItem`.

        :param `item`: the row in which the item lives;
        :param `subItem`: the column in which the item lives. If set equal to the special
         value ``ULC_GETSUBITEMRECT_WHOLEITEM`` the return value is the same as for
         L{GetItemRect};
        :param `code`: one of ``ULC_RECT_BOUNDS``, ``ULC_RECT_ICON``, ``ULC_RECT_LABEL``.

        :note: This method is only meaningful when the L{UltimateListCtrl} is in the
         report mode.
        """

        rect = self._mainWin.GetSubItemRect(item, subItem)
        if self._mainWin.HasHeader():
            rect.y += self._headerHeight + 1

        return rect

[docs]    def GetItemPosition(self, item):
        """
        Returns the position of the item, in icon or small icon view.

        :param `item`: the row in which the item lives.
        """

        return self._mainWin.GetItemPosition(item)

[docs]    def SetItemPosition(self, item, pos):
        """
        Sets the position of the item, in icon or small icon view.

        :param `item`: the row in which the item lives;
        :param `pos`: the item position.

        :note: This method is currently unimplemented and does nothing.
        """

        return False

[docs]    def GetItemCount(self):
        """ Returns the number of items in the L{UltimateListCtrl}. """

        return self._mainWin.GetItemCount()

[docs]    def GetColumnCount(self):
        """ Returns the total number of columns in the L{UltimateListCtrl}. """

        return self._mainWin.GetColumnCount()

[docs]    def SetItemSpacing(self, spacing, isSmall=False):
        """
        Sets the spacing between item texts and icons.

        :param `spacing`: the spacing between item texts and icons, in pixels;
        :param `isSmall`: ``True`` if using a ``wx.IMAGE_LIST_SMALL`` image list,
         ``False`` if using a ``wx.IMAGE_LIST_NORMAL`` image list.
        """

        self._mainWin.SetItemSpacing(spacing, isSmall)

[docs]    def GetItemSpacing(self, isSmall=False):
        """
        Returns the spacing between item texts and icons, in pixels.

        :param `isSmall`: ``True`` if using a ``wx.IMAGE_LIST_SMALL`` image list,
         ``False`` if using a ``wx.IMAGE_LIST_NORMAL`` image list.
        """

        return self._mainWin.GetItemSpacing(isSmall)

[docs]    def SetItemTextColour(self, item, col):
        """
        Sets the item text colour.

        :param `item`: the index of the item;
        :param `col`: a valid `wx.Colour` object.
        """

        info = UltimateListItem()
        info._itemId = item
        info.SetTextColour(col)
        self._mainWin.SetItem(info)

[docs]    def GetItemTextColour(self, item):
        """
        Returns the item text colour.

        :param `item`: the index of the item.
        """

        info = UltimateListItem()
        info._itemId = item
        info = self._mainWin.GetItem(info)

        return info.GetTextColour()

[docs]    def SetItemBackgroundColour(self, item, col):
        """
        Sets the item background colour.

        :param `item`: the index of the item;
        :param `col`: a valid `wx.Colour` object.
        """

        info = UltimateListItem()
        info._itemId = item
        info.SetBackgroundColour(col)
        self._mainWin.SetItem(info)

[docs]    def GetItemBackgroundColour(self, item):
        """
        Returns the item background colour.

        :param `item`: the index of the item.
        """

        info = UltimateListItem()
        info._itemId = item
        info = self._mainWin.GetItem(info)
        return info.GetBackgroundColour()

[docs]    def SetItemFont(self, item, f):
        """
        Sets the item font.

        :param `item`: the index of the item;
        :param `f`: a valid `wx.Font` object.
        """

        info = UltimateListItem()
        info._itemId = item
        info.SetFont(f)
        self._mainWin.SetItem(info)

[docs]    def GetItemFont(self, item):
        """
        Returns the item font.

        :param `item`: the index of the item.
        """

        info = UltimateListItem()
        info._itemId = item
        info = self._mainWin.GetItem(info)
        return info.GetFont()

[docs]    def GetSelectedItemCount(self):
        """ Returns the number of selected items in L{UltimateListCtrl}. """

        return self._mainWin.GetSelectedItemCount()

[docs]    def GetTextColour(self):
        """ Returns the L{UltimateListCtrl} foreground colour. """

        return self.GetForegroundColour()

[docs]    def SetTextColour(self, col):
        """
        Sets the L{UltimateListCtrl} foreground colour.

        :param `col`: a valid `wx.Colour` object.
        """

        self.SetForegroundColour(col)

[docs]    def GetTopItem(self):
        """ Gets the index of the topmost visible item when in list or report view. """

        top, dummy = self._mainWin.GetVisibleLinesRange()
        return top

[docs]    def GetNextItem(self, item, geometry=ULC_NEXT_ALL, state=ULC_STATE_DONTCARE):
        """
        Searches for an item with the given `geometry` or `state`, starting from `item`
        but excluding the `item` itself.

        :param `item`: the item at which starting the search. If set to -1, the first
         item that matches the specified flags will be returned.
        :param `geometry`: can be one of:

         =================== ========= =================================
         Geometry Flag       Hex Value Description
         =================== ========= =================================
         ``ULC_NEXT_ABOVE``        0x0 Searches for an item above the specified item
         ``ULC_NEXT_ALL``          0x1 Searches for subsequent item by index
         ``ULC_NEXT_BELOW``        0x2 Searches for an item below the specified item
         ``ULC_NEXT_LEFT``         0x3 Searches for an item to the left of the specified item
         ``ULC_NEXT_RIGHT``        0x4 Searches for an item to the right of the specified item
         =================== ========= =================================

        :param `state`: any combination of the following bits:

         ============================ ========= ==============================
         State Bits                   Hex Value Description
         ============================ ========= ==============================
         ``ULC_STATE_DONTCARE``             0x0 Don't care what the state is
         ``ULC_STATE_DROPHILITED``          0x1 The item is highlighted to receive a drop event
         ``ULC_STATE_FOCUSED``              0x2 The item has the focus
         ``ULC_STATE_SELECTED``             0x4 The item is selected
         ``ULC_STATE_CUT``                  0x8 The item is in the cut state
         ``ULC_STATE_DISABLED``            0x10 The item is disabled
         ``ULC_STATE_FILTERED``            0x20 The item has been filtered
         ``ULC_STATE_INUSE``               0x40 The item is in use
         ``ULC_STATE_PICKED``              0x80 The item has been picked
         ``ULC_STATE_SOURCE``             0x100 The item is a drag and drop source
         ============================ ========= ==============================

        :return: The first item with given `state` following `item` or -1 if no such item found.

        :note: This function may be used to find all selected items in the
         control like this::

             item = -1

             while 1:
                 item = listctrl.GetNextItem(item, ULC_NEXT_ALL, ULC_STATE_SELECTED)

                 if item == -1:
                     break

                 # This item is selected - do whatever is needed with it

                 wx.LogMessage("Item %ld is selected."%item)

        """

        return self._mainWin.GetNextItem(item, geometry, state)

[docs]    def GetImageList(self, which):
        """
        Returns the image list associated with the control.

        :param `which`: one of ``wx.IMAGE_LIST_NORMAL``, ``wx.IMAGE_LIST_SMALL``,
         ``wx.IMAGE_LIST_STATE`` (the last is unimplemented).

        :note:

         As L{UltimateListCtrl} allows you to use a standard `wx.ImageList` or
         L{PyImageList}, the returned object depends on which kind of image list you
         chose.
        """

        if which == wx.IMAGE_LIST_NORMAL:
            return self._imageListNormal

        elif which == wx.IMAGE_LIST_SMALL:
            return self._imageListSmall

        elif which == wx.IMAGE_LIST_STATE:
            return self._imageListState

        return None

[docs]    def SetImageList(self, imageList, which):
        """
        Sets the image list associated with the control.

        :param `imageList`: an instance of `wx.ImageList` or an instance of L{PyImageList};
        :param `which`: one of ``wx.IMAGE_LIST_NORMAL``, ``wx.IMAGE_LIST_SMALL``,
         ``wx.IMAGE_LIST_STATE`` (the last is unimplemented).

        :note: Using L{PyImageList} enables you to have images of different size inside the
         image list. In your derived class, instead of doing this::

             imageList = wx.ImageList(16, 16)
             imageList.Add(someBitmap)
             self.SetImageList(imageList, wx.IMAGE_LIST_SMALL)

         You should do this::

             imageList = PyImageList(16, 16)
             imageList.Add(someBitmap)
             self.SetImageList(imageList, wx.IMAGE_LIST_SMALL)

        """

        if which == wx.IMAGE_LIST_NORMAL:
            self._imageListNormal = imageList

        elif which == wx.IMAGE_LIST_SMALL:
            self._imageListSmall = imageList

        elif which == wx.IMAGE_LIST_STATE:
            self._imageListState = imageList

        self._mainWin.SetImageList(imageList, which)

[docs]    def AssignImageList(self, imageList, which):
        """
        Assigns the image list associated with the control.

        :param `imageList`: an instance of `wx.ImageList` or an instance of L{PyImageList};
        :param `which`: one of ``wx.IMAGE_LIST_NORMAL``, ``wx.IMAGE_LIST_SMALL``,
         ``wx.IMAGE_LIST_STATE`` (the last is unimplemented).

        :note: Using L{PyImageList} enables you to have images of different size inside the
         image list. In your derived class, instead of doing this::

             imageList = wx.ImageList(16, 16)
             imageList.Add(someBitmap)
             self.SetImageList(imageList, wx.IMAGE_LIST_SMALL)

         You should do this::

             imageList = PyImageList(16, 16)
             imageList.Add(someBitmap)
             self.SetImageList(imageList, wx.IMAGE_LIST_SMALL)

        """

        self.SetImageList(imageList, which)

[docs]    def Arrange(self, flag):
        """
        Arranges the items in icon or small icon view.

        :param `flag`: one of the following bits:

         ========================== ========= ===============================
         Alignment Flag             Hex Value Description
         ========================== ========= ===============================
         ``ULC_ALIGN_DEFAULT``            0x0 Default alignment
         ``ULC_ALIGN_SNAP_TO_GRID``       0x3 Snap to grid
         ========================== ========= ===============================

        :note: This method is currently unimplemented and does nothing.
        """

        return 0

[docs]    def DeleteItem(self, item):
        """
        Deletes the specified item.

        :param `item`: the index of the item to delete.

        :note: This function sends the ``EVT_LIST_DELETE_ITEM`` event for the item
         being deleted.
        """

        self._mainWin.DeleteItem(item)
        return True

[docs]    def DeleteAllItems(self):
        """
        Deletes all items in the L{UltimateListCtrl}.

        :note: This function does not send the ``EVT_LIST_DELETE_ITEM`` event because
         deleting many items from the control would be too slow then (unlike L{DeleteItem}).
        """

        self._mainWin.DeleteAllItems()
        return True

[docs]    def DeleteAllColumns(self):
        """ Deletes all the column in L{UltimateListCtrl}. """

        count = len(self._mainWin._columns)
        for n in xrange(count):
            self.DeleteColumn(0)

        return True

[docs]    def ClearAll(self):
        """ Deletes everything in L{UltimateListCtrl}. """

        self._mainWin.DeleteEverything()

[docs]    def DeleteColumn(self, col):
        """
        Deletes the specified column.

        :param `col`: the index of the column to delete.
        """

        self._mainWin.DeleteColumn(col)
        return True

[docs]    def EditLabel(self, item):
        """
        Starts editing an item label.

        :param `item`: the index of the item to edit.
        """

        self._mainWin.EditLabel(item)

[docs]    def EnsureVisible(self, item):
        """
        Ensures this item is visible.

        :param `index`: the index of the item to scroll into view.
        """

        self._mainWin.EnsureVisible(item)
        return True

[docs]    def FindItem(self, start, str, partial=False):
        """
        Find an item whose label matches this string.

        :param `start`: the starting point of the input `string` or the beginning
         if `start` is -1;
        :param `string`: the string to look for matches;
        :param `partial`: if ``True`` then this method will look for items which
         begin with `string`.

        :note: The string comparison is case insensitive.
        """

        return self._mainWin.FindItem(start, str, partial)

[docs]    def FindItemData(self, start, data):
        """
        Find an item whose data matches this data.

        :param `start`: the starting point of the input `data` or the beginning
         if `start` is -1;
        :param `data`: the data to look for matches.
        """

        return self._mainWin.FindItemData(start, data)

[docs]    def FindItemAtPos(self, start, pt):
        """
        Find an item nearest this position.

        :param `pt`: an instance of `wx.Point`.
        """

        return self._mainWin.FindItemAtPos(pt)

[docs]    def HitTest(self, pointOrTuple):
        """
        HitTest method for a L{UltimateListCtrl}.

        :param `pointOrTuple`: an instance of `wx.Point` or a tuple representing
         the mouse `x`, `y` position.

        :see: L{UltimateListMainWindow.HitTestLine} for a list of return flags.
        """

        if isinstance(pointOrTuple, wx.Point):
            x, y = pointOrTuple.x, pointOrTuple.y
        else:
            x, y = pointOrTuple

        return self._mainWin.HitTest(x, y)

[docs]    def InsertItem(self, info):
        """
        Inserts an item into L{UltimateListCtrl}.

        :param `info`: an instance of L{UltimateListItem}.
        """

        self._mainWin.InsertItem(info)
        return info._itemId

[docs]    def InsertStringItem(self, index, label, it_kind=0):
        """
        Inserts a string item at the given location.

        :param `index`: the index at which we wish to insert the item;
        :param `label`: the item text;
        :param `it_kind`: the item kind.

        :see: L{SetStringItem} for a list of valid item kinds.
        """

        info = UltimateListItem()
        info._text = label
        info._mask = ULC_MASK_TEXT

        if it_kind:
            info._mask |= ULC_MASK_KIND
            info._kind = it_kind

        info._itemId = index
        return self.InsertItem(info)

[docs]    def InsertImageItem(self, index, imageIds, it_kind=0):
        """
        Inserts an image item at the given location.

        :param `index`: the index at which we wish to insert the item;
        :param `imageIds`: a Python list containing the image indexes for the
         images associated to this item;
        :param `it_kind`: the item kind.

        :see: L{SetStringItem} for a list of valid item kinds.
        """

        info = UltimateListItem()
        info._mask = ULC_MASK_IMAGE

        if it_kind:
            info._mask |= ULC_MASK_KIND
            info._kind = it_kind

        info._image = to_list(imageIds)
        info._itemId = index

        return self.InsertItem(info)

[docs]    def InsertImageStringItem(self, index, label, imageIds, it_kind=0):
        """
        Inserts an image+string item at the given location.

        :param `index`: the index at which we wish to insert the item;
        :param `label`: the item text;
        :param `imageIds`: a Python list containing the image indexes for the
         images associated to this item;
        :param `it_kind`: the item kind.

        :see: L{SetStringItem} for a list of valid item kinds.
        """

        info = UltimateListItem()
        info._text = label
        info._image = to_list(imageIds)
        info._mask = ULC_MASK_TEXT | ULC_MASK_IMAGE

        if it_kind:
            info._mask |= ULC_MASK_KIND
            info._kind = it_kind

        info._itemId = index
        return self.InsertItem(info)

[docs]    def InsertColumnInfo(self, col, item):
        """
        Inserts a column into L{UltimateListCtrl}.

        :param `col`: the column index at which we wish to insert a column;
        :param `item`: an instance of L{UltimateListItem}.
        """

        if not self._mainWin.InReportView() and not self.HasAGWFlag(ULC_HEADER_IN_ALL_VIEWS) and \
           not self._mainWin.InTileView():
            raise Exception("Can't add column in non report/tile modes or without the ULC_HEADER_IN_ALL_VIEWS style set")

        self._mainWin.InsertColumn(col, item)
        if self._headerWin:
            self._headerWin.Refresh()

        return 0

[docs]    def InsertColumn(self, col, heading, format=ULC_FORMAT_LEFT, width=-1):
        """
        Inserts a column into L{UltimateListCtrl}.

        :param `col`: the column index at which we wish to insert a column;
        :param `heading`: the header text;
        :param `format`: the column alignment flag. This can be one of the following
         bits:

         ============================ ========= ==============================
         Alignment Bits               Hex Value Description
         ============================ ========= ==============================
         ``ULC_FORMAT_LEFT``                0x0 The item is left-aligned
         ``ULC_FORMAT_RIGHT``               0x1 The item is right-aligned
         ``ULC_FORMAT_CENTRE``              0x2 The item is centre-aligned
         ``ULC_FORMAT_CENTER``              0x2 The item is center-aligned
         ============================ ========= ==============================

        :param `width`: can be a width in pixels or ``wx.LIST_AUTOSIZE`` (-1) or
         ``wx.LIST_AUTOSIZE_USEHEADER`` (-2) or ``LIST_AUTOSIZE_FILL`` (-3).
         ``wx.LIST_AUTOSIZE`` will resize the column to the length of its longest
         item. ``wx.LIST_AUTOSIZE_USEHEADER`` will resize the column to the
         length of the header (Win32) or 80 pixels (other platforms).
         ``LIST_AUTOSIZE_FILL`` will resize the column fill the remaining width
         of the window.

        """

        item = UltimateListItem()
        item._mask = ULC_MASK_TEXT | ULC_MASK_FORMAT | ULC_MASK_FONT
        item._text = heading

        if width >= -2:
            item._mask |= ULC_MASK_WIDTH
            item._width = width

        item._format = format

        return self.InsertColumnInfo(col, item)

[docs]    def IsColumnShown(self, column):
        """
        Returns ``True`` if the input column is shown, ``False`` if it is hidden.

        :param `column`: an integer specifying the column index.
        """

        if self._headerWin:
            return self._mainWin.IsColumnShown(column)

        raise Exception("Showing/hiding columns works only with the header shown")

[docs]    def SetColumnShown(self, column, shown=True):
        """
        Sets the specified column as shown or hidden.

        :param `column`: an integer specifying the column index;
        :param `shown`: ``True`` to show the column, ``False`` to hide it.
        """

        col = self.GetColumn(column)
        col._mask |= ULC_MASK_SHOWN
        col.SetShown(shown)
        self._mainWin.SetColumn(column, col)
        self.Update()

[docs]    def ScrollList(self, dx, dy):
        """
        Scrolls the L{UltimateListCtrl}.

        :param `dx`: if in icon, small icon or report view mode, specifies the number
         of pixels to scroll. If in list view mode, `dx` specifies the number of
         columns to scroll.
        :param `dy`: always specifies the number of pixels to scroll vertically.
        """

        return self._mainWin.ScrollList(dx, dy)

# Sort items.
# The return value is a negative number if the first item should precede the second
# item, a positive number of the second item should precede the first,
# or zero if the two items are equivalent.

[docs]    def SortItems(self, func=None):
        """
        Call this function to sort the items in the L{UltimateListCtrl}. Sorting is done
        using the specified function `func`. This function must have the
        following prototype::

            def OnCompareItems(self, line1, line2):

                DoSomething(line1, line2)
                # function code

        It is called each time when the two items must be compared and should return 0
        if the items are equal, negative value if the first item is less than the second
        one and positive value if the first one is greater than the second one.

        :param `func`: the method to use to sort the items. The default is to use the
         L{UltimateListMainWindow.OnCompareItems} method.
        """

        self._mainWin.SortItems(func)
        wx.CallAfter(self.Refresh)

        return True

# ----------------------------------------------------------------------------
# event handlers
# ----------------------------------------------------------------------------

[docs]    def OnSize(self, event):
        """
        Handles the ``wx.EVT_SIZE`` event for L{UltimateListCtrl}.

        :param `event`: a `wx.SizeEvent` event to be processed.
        """

        if not self.IsShownOnScreen():
            # We don't have the proper column sizes until we are visible so
            # use CallAfter to resize the columns on the first display
            if self._mainWin:
                wx.CallAfter(self._mainWin.ResizeColumns)

        if not self._mainWin:
            return

        # We need to override OnSize so that our scrolled
        # window a) does call Layout() to use sizers for
        # positioning the controls but b) does not query
        # the sizer for their size and use that for setting
        # the scrollable area as set that ourselves by
        # calling SetScrollbar() further down.

        self.DoLayout()

[docs]    def OnSetFocus(self, event):
        """
        Handles the ``wx.EVT_SET_FOCUS`` event for L{UltimateListCtrl}.

        :param `event`: a `wx.FocusEvent` event to be processed.
        """

        if self._mainWin:
            self._mainWin.SetFocusIgnoringChildren()
            self._mainWin.Update()
            event.Skip()

[docs]    def OnInternalIdle(self):
        """
        This method is normally only used internally, but sometimes an application
        may need it to implement functionality that should not be disabled by an
        application defining an `OnIdle` handler in a derived class.

        This method may be used to do delayed painting, for example, and most
        implementations call `wx.Window.UpdateWindowUI` in order to send update events
        to the window in idle time.
        """

        wx.PyControl.OnInternalIdle(self)

        # do it only if needed
        if self._mainWin and self._mainWin._dirty:
            self._mainWin._shortItems = []
            self._mainWin.RecalculatePositions()

# ----------------------------------------------------------------------------
# font/colours
# ----------------------------------------------------------------------------

[docs]    def SetBackgroundColour(self, colour):
        """
        Changes the background colour of L{UltimateListCtrl}.

        :param `colour`: the colour to be used as the background colour, pass
         `wx.NullColour` to reset to the default colour.

        :note: The background colour is usually painted by the default `wx.EraseEvent`
         event handler function under Windows and automatically under GTK.

        :note: Setting the background colour does not cause an immediate refresh, so
         you may wish to call `wx.Window.ClearBackground` or `wx.Window.Refresh` after
         calling this function.

        :note: Overridden from `wx.PyControl`.
        """

        if self._mainWin:
            self._mainWin.SetBackgroundColour(colour)
            self._mainWin._dirty = True

        return True

[docs]    def SetForegroundColour(self, colour):
        """
        Changes the foreground colour of L{UltimateListCtrl}.

        :param `colour`: the colour to be used as the foreground colour, pass
         `wx.NullColour` to reset to the default colour.

        :note: Overridden from `wx.PyControl`.
        """

        if not wx.PyControl.SetForegroundColour(self, colour):
            return False

        if self._mainWin:
            self._mainWin.SetForegroundColour(colour)
            self._mainWin._dirty = True

        if self._headerWin:
            self._headerWin.SetForegroundColour(colour)

        return True

[docs]    def SetFont(self, font):
        """
        Sets the L{UltimateListCtrl} font.

        :param `font`: a valid `wx.Font` instance.

        :note: Overridden from `wx.PyControl`.
        """

        if not wx.PyControl.SetFont(self, font):
            return False

        if self._mainWin:
            self._mainWin.SetFont(font)
            self._mainWin._dirty = True

        if self._headerWin:
            self._headerWin.SetFont(font)

        self.Refresh()

        return True

[docs]    def GetClassDefaultAttributes(self, variant):
        """
        Returns the default font and colours which are used by the control. This is
        useful if you want to use the same font or colour in your own control as in
        a standard control -- which is a much better idea than hard coding specific
        colours or fonts which might look completely out of place on the users system,
        especially if it uses themes.

        This static method is "overridden'' in many derived classes and so calling,
        for example, `wx.Button.GetClassDefaultAttributes()` will typically return the
        values appropriate for a button which will be normally different from those
        returned by, say, `wx.ListCtrl.GetClassDefaultAttributes()`.

        :note: The `wx.VisualAttributes` structure has at least the fields `font`,
         `colFg` and `colBg`. All of them may be invalid if it was not possible to
         determine the default control appearance or, especially for the background
         colour, if the field doesn't make sense as is the case for `colBg` for the
         controls with themed background.

        :note: Overridden from `wx.PyControl`.
        """

        attr = wx.VisualAttributes()
        attr.colFg = wx.SystemSettings.GetColour(wx.SYS_COLOUR_LISTBOXTEXT)
        attr.colBg = wx.SystemSettings.GetColour(wx.SYS_COLOUR_LISTBOX)
        attr.font  = wx.SystemSettings.GetFont(wx.SYS_DEFAULT_GUI_FONT)
        return attr

[docs]    def GetScrolledWin(self):
        """ Returns the header window owner. """

        return self._headerWin.GetOwner()

# ----------------------------------------------------------------------------
# methods forwarded to self._mainWin
# ----------------------------------------------------------------------------

[docs]    def SetDropTarget(self, dropTarget):
        """
        Associates a drop target with this window.
        If the window already has a drop target, it is deleted.

        :param `dropTarget`: an instance of `wx.DropTarget`.

        :note: Overridden from `wx.PyControl`.
        """

        self._mainWin.SetDropTarget(dropTarget)

[docs]    def GetDropTarget(self):
        """
        Returns the associated drop target, which may be ``None``.

        :note: Overridden from `wx.PyControl`.
        """

        return self._mainWin.GetDropTarget()

[docs]    def SetCursor(self, cursor):
        """
        Sets the window's cursor.

        :param `cursor`: specifies the cursor that the window should normally display.
         The `cursor` may be `wx.NullCursor` in which case the window cursor will be
         reset back to default.

        :note: The window cursor also sets it for the children of the window implicitly.

        :note: Overridden from `wx.PyControl`.
        """

        return (self._mainWin and [self._mainWin.SetCursor(cursor)] or [False])[0]

[docs]    def GetBackgroundColour(self):
        """
        Returns the background colour of the window.

        :note: Overridden from `wx.PyControl`.
        """

        return (self._mainWin and [self._mainWin.GetBackgroundColour()] or [wx.NullColour])[0]

[docs]    def GetForegroundColour(self):
        """
        Returns the foreground colour of the window.

        :note: Overridden from `wx.PyControl`.
        """

        return (self._mainWin and [self._mainWin.GetForegroundColour()] or [wx.NullColour])[0]

[docs]    def PopupMenu(self, menu, pos=wx.DefaultPosition):
        """
        Pops up the given `menu` at the specified coordinates, relative to this window,
        and returns control when the user has dismissed the menu. If a menu item is
        selected, the corresponding menu event is generated and will be processed as
        usual. If the coordinates are not specified, the current mouse cursor position
        is used.

        :param `menu`: an instance of `wx.Menu` to pop up;
        :param `pos`: the position where the menu will appear.

        :note: Overridden from `wx.PyControl`.
        """

        return self._mainWin.PopupMenu(menu, pos)

[docs]    def ClientToScreen(self, pointOrTuple):
        """
        Converts to screen coordinates from coordinates relative to this window.

        :param `pointOrTuple`: an instance of `wx.Point` or a tuple representing the
         `x`, `y` coordinates for this point.

        :return: the coordinates relative to the screen.

        :note: Overridden from `wx.PyControl`.
        """

        return self._mainWin.ClientToScreen(*pointOrTuple)

[docs]    def ClientToScreenXY(self, x, y):
        """
        Converts to screen coordinates from coordinates relative to this window.

        :param `x`: an integer specifying the `x` client coordinate;
        :param `y`: an integer specifying the `y` client coordinate.

        :return: the coordinates relative to the screen.

        :note: Overridden from `wx.PyControl`.
        """

        return self._mainWin.ClientToScreen(x, y)

[docs]    def ScreenToClient(self, pointOrTuple):
        """
        Converts from screen to client window coordinates.

        :param `pointOrTuple`: an instance of `wx.Point` or a tuple representing the
         `x`, `y` coordinates for this point.

        :return: the coordinates relative to this window.

        :note: Overridden from `wx.PyControl`.
        """

        return self._mainWin.ScreenToClient(*pointOrTuple)

[docs]    def ScreenToClientXY(self, x, y):
        """
        Converts from screen to client window coordinates.

        :param `x`: an integer specifying the `x` screen coordinate;
        :param `y`: an integer specifying the `y` screen coordinate.

        :return: the coordinates relative to this window.

        :note: Overridden from `wx.PyControl`.
        """

        return self._mainWin.ScreenToClient(x, y)

[docs]    def SetFocus(self):
        """ This sets the window to receive keyboard input. """

        # The test in window.cpp fails as we are a composite
        # window, so it checks against "this", but not self._mainWin.
        if wx.Window.FindFocus() != self:
            self._mainWin.SetFocusIgnoringChildren()

[docs]    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()`.
        """

        # Something is better than nothing...
        # 100x80 is what the MSW version will get from the default
        # wx.Control.DoGetBestSize
        return wx.Size(100, 80)

# ----------------------------------------------------------------------------
# virtual list control support
# ----------------------------------------------------------------------------

[docs]    def OnGetItemText(self, item, col):
        """
        This function **must** be overloaded in the derived class for a control with
        ``ULC_VIRTUAL`` style. It should return the string containing the text of
        the given column for the specified item.

        :param `item`: an integer specifying the item index;
        :param `col`: the column index to which the item belongs to.
        """

        # this is a pure virtual function, in fact - which is not really pure
        # because the controls which are not virtual don't need to implement it
        raise Exception("UltimateListCtrl.OnGetItemText not supposed to be called")

[docs]    def OnGetItemTextColour(self, item, col):
        """
        This function **must** be overloaded in the derived class for a control with
        ``ULC_VIRTUAL`` style. It should return a `wx.Colour` object or ``None`` for
        the default color.

        :param `item`: an integer specifying the item index;
        :param `col`: the column index to which the item belongs to.
        """

        # this is a pure virtual function, in fact - which is not really pure
        # because the controls which are not virtual don't need to implement it
        raise Exception("UltimateListCtrl.OnGetItemTextColour not supposed to be called")

[docs]    def OnGetItemToolTip(self, item, col):
        """
        This function **must** be overloaded in the derived class for a control with
        ``ULC_VIRTUAL`` style. It should return the string containing the text of
        the tooltip for the specified item.

        :param `item`: an integer specifying the item index;
        :param `col`: the column index to which the item belongs to.
        """

        # this is a pure virtual function, in fact - which is not really pure
        # because the controls which are not virtual don't need to implement it
        raise Exception("UltimateListCtrl.OnGetItemToolTip not supposed to be called")

[docs]    def OnGetItemImage(self, item):
        """
        This function **must** be overloaded in the derived class for a control with
        ``ULC_VIRTUAL`` style having an image list (if the control doesn't have an
        image list, it is not necessary to overload it). It should return a Python
        list of indexes representing the images associated to the input item or an
        empty list for no images.

        :param `item`: an integer specifying the item index;

        :note: In a control with ``ULC_REPORT`` style, L{OnGetItemImage} only gets called
         for the first column of each line.

        :note: The base class version always returns an empty Python list.
        """

        if self.GetImageList(wx.IMAGE_LIST_SMALL):
            raise Exception("List control has an image list, OnGetItemImage should be overridden.")

        return []

[docs]    def OnGetItemColumnImage(self, item, column=0):
        """
        This function **must** be overloaded in the derived class for a control with
        ``ULC_VIRTUAL`` and ``ULC_REPORT`` style. It should return a Python list of
        indexes representing the images associated to the input item or an empty list
        for no images.

        :param `item`: an integer specifying the item index.

        :note: The base class version always returns an empty Python list.
        """

        if column == 0:
            return self.OnGetItemImage(item)

        return []

[docs]    def OnGetItemAttr(self, item):
        """
        This function may be overloaded in the derived class for a control with
        ``ULC_VIRTUAL`` style. It should return the attribute for the specified
        item or ``None`` to use the default appearance parameters.

        :param `item`: an integer specifying the item index.

        :note:

         L{UltimateListCtrl} will not delete the pointer or keep a reference of it.
         You can return the same L{UltimateListItemAttr} pointer for every
         L{OnGetItemAttr} call.

        :note: The base class version always returns ``None``.
        """

        if item < 0 or item > self.GetItemCount():
            raise Exception("Invalid item index in OnGetItemAttr()")

        # no attributes by default
        return None

[docs]    def OnGetItemCheck(self, item):
        """
        This function may be overloaded in the derived class for a control with
        ``ULC_VIRTUAL`` style. It should return whether a checkbox-like item or
        a radiobutton-like item is checked or unchecked.

        :param `item`: an integer specifying the item index.

        :note: The base class version always returns an empty list.
        """

        return []

[docs]    def OnGetItemColumnCheck(self, item, column=0):
        """
        This function **must** be overloaded in the derived class for a control with
        ``ULC_VIRTUAL`` and ``ULC_REPORT`` style. It should return whether a
        checkbox-like item or a radiobutton-like item in the column header is checked
        or unchecked.

        :param `item`: an integer specifying the item index.

        :note: The base class version always returns an empty Python list.
        """

        if column == 0:
            return self.OnGetItemCheck(item)

        return []

[docs]    def OnGetItemKind(self, item):
        """
        This function **must** be overloaded in the derived class for a control with
        ``ULC_VIRTUAL`` style. It should return the item kind for the input item.

        :param `item`: an integer specifying the item index.

        :note: The base class version always returns 0 (a standard item).

        :see: L{SetItemKind} for a list of valid item kinds.
        """

        return 0

[docs]    def OnGetItemColumnKind(self, item, column=0):
        """
        This function **must** be overloaded in the derived class for a control with
        ``ULC_VIRTUAL`` style. It should return the item kind for the input item in
        the header window.

        :param `item`: an integer specifying the item index;
        :param `column`: the column index.

        :note: The base class version always returns 0 (a standard item).

        :see: L{SetItemKind} for a list of valid item kinds.
        """

        if column == 0:
            return self.OnGetItemKind(item)

        return 0

[docs]    def SetItemCount(self, count):
        """
        Sets the total number of items we handle.

        :param `count`: the total number of items we handle.
        """

        if not self._mainWin.IsVirtual():
            raise Exception("This is for virtual controls only")

        self._mainWin.SetItemCount(count)

[docs]    def RefreshItem(self, item):
        """
        Redraws the given item.

        :param `item`: an integer specifying the item index;

        :note: This is only useful for the virtual list controls as without calling
         this function the displayed value of the item doesn't change even when the
         underlying data does change.
        """

        self._mainWin.RefreshLine(item)

[docs]    def RefreshItems(self, itemFrom, itemTo):
        """
        Redraws the items between `itemFrom` and `itemTo`.
        The starting item must be less than or equal to the ending one.

        Just as L{RefreshItem} this is only useful for virtual list controls

        :param `itemFrom`: the first index of the refresh range;
        :param `itemTo`: the last index of the refresh range.
        """

        self._mainWin.RefreshLines(itemFrom, itemTo)

#
# Generic UltimateListCtrl is more or less a container for two other
# windows which drawings are done upon. These are namely
# 'self._headerWin' and 'self._mainWin'.
# Here we override 'virtual wxWindow::Refresh()' to mimic the
# behaviour UltimateListCtrl has under wxMSW.
#

[docs]    def Refresh(self, eraseBackground=True, rect=None):
        """
        Causes this window, and all of its children recursively (except under wxGTK1
        where this is not implemented), to be repainted.

        :param `eraseBackground`: If ``True``, the background will be erased;
        :param `rect`: If not ``None``, only the given rectangle will be treated as damaged.

        :note: Note that repainting doesn't happen immediately but only during the next
         event loop iteration, if you need to update the window immediately you should
         use L{Update} instead.

        :note: Overridden from `wx.PyControl`.
        """

        if not rect:

            # The easy case, no rectangle specified.
            if self._headerWin:
                self._headerWin.Refresh(eraseBackground)

            if self._mainWin:
                self._mainWin.Refresh(eraseBackground)

        else:

            # Refresh the header window
            if self._headerWin:

                rectHeader = self._headerWin.GetRect()
                rectHeader.Intersect(rect)
                if rectHeader.GetWidth() and rectHeader.GetHeight():
                    x, y = self._headerWin.GetPosition()
                    rectHeader.OffsetXY(-x, -y)
                    self._headerWin.Refresh(eraseBackground, rectHeader)

            # Refresh the main window
            if self._mainWin:

                rectMain = self._mainWin.GetRect()
                rectMain.Intersect(rect)
                if rectMain.GetWidth() and rectMain.GetHeight():
                    x, y = self._mainWin.GetPosition()
                    rectMain.OffsetXY(-x, -y)
                    self._mainWin.Refresh(eraseBackground, rectMain)

[docs]    def Update(self):
        """
        Calling this method immediately repaints the invalidated area of the window
        and all of its children recursively while this would usually only happen when
        the flow of control returns to the event loop.

        :note: This function doesn't invalidate any area of the window so nothing
         happens if nothing has been invalidated (i.e. marked as requiring a redraw).
         Use L{Refresh} first if you want to immediately redraw the window unconditionally.

        :note: Overridden from `wx.PyControl`.
        """

        self._mainWin.ResetVisibleLinesRange(True)
        wx.PyControl.Update(self)

[docs]    def GetEditControl(self):
        """
        Returns a pointer to the edit L{UltimateListTextCtrl} if the item is being edited or
        ``None`` otherwise (it is assumed that no more than one item may be edited
        simultaneously).
        """

        retval = None

        if self._mainWin:
            retval = self._mainWin.GetEditControl()

        return retval

[docs]    def Select(self, idx, on=True):
        """
        Selects/deselects an item.

        :param `idx`: the index of the item to select;
        :param `on`: ``True`` to select the item, ``False`` to deselect it.
        """

        item = CreateListItem(idx, 0)
        item = self._mainWin.GetItem(item, 0)
        if not item.IsEnabled():
            return

        if on:
            state = ULC_STATE_SELECTED
        else:
            state = 0

        self.SetItemState(idx, state, ULC_STATE_SELECTED)

[docs]    def Focus(self, idx):
        """
        Focus and show the given item.

        :param `idx`: the index of the item to be focused.
        """

        self.SetItemState(idx, ULC_STATE_FOCUSED, ULC_STATE_FOCUSED)
        self.EnsureVisible(idx)

[docs]    def GetFocusedItem(self):
        """ Returns the currently focused item or -1 if none is focused. """

        return self.GetNextItem(-1, ULC_NEXT_ALL, ULC_STATE_FOCUSED)

[docs]    def GetFirstSelected(self):
        """ Return first selected item, or -1 when none is selected. """

        return self.GetNextSelected(-1)

[docs]    def GetNextSelected(self, item):
        """
        Returns subsequent selected items, or -1 when no more are selected.

        :param `item`: the index of the item.
        """

        return self.GetNextItem(item, ULC_NEXT_ALL, ULC_STATE_SELECTED)

[docs]    def IsSelected(self, idx):
        """
        Returns ``True`` if the item is selected.

        :param `idx`: the index of the item to check for selection.
        """

        return (self.GetItemState(idx, ULC_STATE_SELECTED) & ULC_STATE_SELECTED) != 0

[docs]    def IsItemChecked(self, itemOrId, col=0):
        """
        Returns whether an item is checked or not.

        :param `itemOrId`: an instance of L{UltimateListItem} or the item index;
        :param `col`: the column index to which the input item belongs to.
        """

        item = CreateListItem(itemOrId, col)
        return self._mainWin.IsItemChecked(item)

[docs]    def IsItemEnabled(self, itemOrId, col=0):
        """
        Returns whether an item is enabled or not.

        :param `itemOrId`: an instance of L{UltimateListItem} or the item index;
        :param `col`: the column index to which the input item belongs to.
        """

        item = CreateListItem(itemOrId, col)
        return self._mainWin.IsItemEnabled(item)

[docs]    def GetItemKind(self, itemOrId, col=0):
        """
        Returns the item kind.

        :param `itemOrId`: an instance of L{UltimateListItem} or the item index;
        :param `col`: the column index to which the input item belongs to.

        :see: L{SetItemKind} for a list of valid item kinds.
        """

        item = CreateListItem(itemOrId, col)
        return self._mainWin.GetItemKind(item)

[docs]    def SetItemKind(self, itemOrId, col=0, kind=0):
        """
        Sets the item kind.

        :param `itemOrId`: an instance of L{UltimateListItem} or the item index;
        :param `col`: the column index to which the input item belongs to;
        :param `kind`: may be one of the following integers:

         =============== ==========================
         Item Kind       Description
         =============== ==========================
                0        A normal item
                1        A checkbox-like item
                2        A radiobutton-type item
         =============== ==========================

        """

        item = CreateListItem(itemOrId, col)
        return self._mainWin.SetItemKind(item, kind)

[docs]    def EnableItem(self, itemOrId, col=0, enable=True):
        """
        Enables/disables an item.

        :param `itemOrId`: an instance of L{UltimateListItem} or the item index;
        :param `col`: the column index to which the input item belongs to;
        :param `enable`: ``True`` to enable the item, ``False`` otherwise.
        """

        item = CreateListItem(itemOrId, col)
        return self._mainWin.EnableItem(item, enable)

[docs]    def IsItemHyperText(self, itemOrId, col=0):
        """
        Returns whether an item is hypertext or not.

        :param `itemOrId`: an instance of L{UltimateListItem} or the item index;
        :param `col`: the column index to which the input item belongs to.
        """

        item = CreateListItem(itemOrId, col)
        return self._mainWin.IsItemHyperText(item)

[docs]    def SetItemHyperText(self, itemOrId, col=0, hyper=True):
        """
        Sets whether the item is hypertext or not.

        :param `itemOrId`: an instance of L{UltimateListItem} or the item index;
        :param `col`: the column index to which the input item belongs to;
        :param `hyper`: ``True`` to have an item with hypertext behaviour, ``False`` otherwise.
        """

        item = CreateListItem(itemOrId, col)
        return self._mainWin.SetItemHyperText(item, hyper)

[docs]    def SetColumnToolTip(self, col, tip):
        """
        Sets the tooltip for the column header

        :param `col`: the column index;
        :param `tip`: the tooltip text
        """

        item = self.GetColumn(col)
        item.SetToolTip(tip)
        self.SetColumn(col, item)

[docs]    def SetColumnImage(self, col, image):
        """
        Sets one or more images to the specified column.

        :param `col`: the column index;
        :param `image`: a Python list containing the image indexes for the
         images associated to this column item.
        """

        item = self.GetColumn(col)
        # preserve all other attributes too

        item.SetMask(ULC_MASK_STATE      |
                     ULC_MASK_TEXT       |
                     ULC_MASK_IMAGE      |
                     ULC_MASK_DATA       |
                     ULC_SET_ITEM        |
                     ULC_MASK_WIDTH      |
                     ULC_MASK_FORMAT     |
                     ULC_MASK_FONTCOLOUR |
                     ULC_MASK_FONT       |
                     ULC_MASK_BACKCOLOUR |
                     ULC_MASK_KIND       |
                     ULC_MASK_CHECK
                     )
        item.SetImage(image)
        self.SetColumn(col, item)

[docs]    def ClearColumnImage(self, col):
        """
        Clears all the images in the specified column.

        :param `col`: the column index;
        """

        self.SetColumnImage(col, -1)

[docs]    def Append(self, entry):
        """
        Append an item to the L{UltimateListCtrl}.

        :param `entry`: should be a sequence with an item for each column.
        """

        if entry:
            if wx.USE_UNICODE:
                cvtfunc = unicode
            else:
                cvtfunc = str
            pos = self.GetItemCount()
            self.InsertStringItem(pos, cvtfunc(entry[0]))
            for i in range(1, len(entry)):
                self.SetStringItem(pos, i, cvtfunc(entry[i]))

            return pos

[docs]    def SetFirstGradientColour(self, colour=None):
        """
        Sets the first gradient colour for gradient-style selections.

        :param `colour`: if not ``None``, a valid `wx.Colour` instance. Otherwise,
         the colour is taken from the system value ``wx.SYS_COLOUR_HIGHLIGHT``.
        """

        self._mainWin.SetFirstGradientColour(colour)

[docs]    def SetSecondGradientColour(self, colour=None):
        """
        Sets the second gradient colour for gradient-style selections.

        :param `colour`: if not ``None``, a valid `wx.Colour` instance. Otherwise,
         the colour generated is a slightly darker version of the L{UltimateListCtrl}
         background colour.
        """

        self._mainWin.SetSecondGradientColour(colour)

[docs]    def GetFirstGradientColour(self):
        """ Returns the first gradient colour for gradient-style selections. """

        return self._mainWin.GetFirstGradientColour()

[docs]    def GetSecondGradientColour(self):
        """ Returns the second gradient colour for gradient-style selections. """

        return self._mainWin.GetSecondGradientColour()

[docs]    def EnableSelectionGradient(self, enable=True):
        """
        Globally enables/disables drawing of gradient selections.

        :param `enable`: ``True`` to enable gradient-style selections, ``False``
         to disable it.

        :note: Calling this method disables any Vista-style selection previously
         enabled.
        """

        self._mainWin.EnableSelectionGradient(enable)

[docs]    def SetGradientStyle(self, vertical=0):
        """
        Sets the gradient style for gradient-style selections.

        :param `vertical`: 0 for horizontal gradient-style selections, 1 for vertical
         gradient-style selections.
        """

        self._mainWin.SetGradientStyle(vertical)

[docs]    def GetGradientStyle(self):
        """
        Returns the gradient style for gradient-style selections.

        :return: 0 for horizontal gradient-style selections, 1 for vertical
         gradient-style selections.
        """

        return self._mainWin.GetGradientStyle()

[docs]    def EnableSelectionVista(self, enable=True):
        """
        Globally enables/disables drawing of Windows Vista selections.

        :param `enable`: ``True`` to enable Vista-style selections, ``False`` to
         disable it.

        :note: Calling this method disables any gradient-style selection previously
         enabled.
        """

        self._mainWin.EnableSelectionVista(enable)

[docs]    def SetBackgroundImage(self, image=None):
        """
        Sets the L{UltimateListCtrl} background image.

        :param `image`: if not ``None``, an instance of `wx.Bitmap`.

        :note: At present, the background image can only be used in "tile" mode.

        :todo: Support background images also in stretch and centered modes.
        """

        self._mainWin.SetBackgroundImage(image)

[docs]    def GetBackgroundImage(self):
        """
        Returns the L{UltimateListCtrl} background image (if any).

        :note: At present, the background image can only be used in "tile" mode.

        :todo: Support background images also in stretch and centered modes.
        """

        return self._mainWin.GetBackgroundImage()

[docs]    def SetWaterMark(self, watermark=None):
        """
        Sets the L{UltimateListCtrl} watermark image to be displayed in the bottom
        right part of the window.

        :param `watermark`: if not ``None``, an instance of `wx.Bitmap`.

        :todo: Better support for this is needed.
        """

        self._mainWin.SetWaterMark(watermark)

[docs]    def GetWaterMark(self):
        """
        Returns the L{UltimateListCtrl} watermark image (if any), displayed in the
        bottom right part of the window.

        :todo: Better support for this is needed.
        """

        return self._mainWin.GetWaterMark()

[docs]    def SetDisabledTextColour(self, colour):
        """
        Sets the items disabled colour.

        :param `colour`: an instance of `wx.Colour`.
        """

        self._mainWin.SetDisabledTextColour(colour)

[docs]    def GetDisabledTextColour(self):
        """ Returns the items disabled colour. """

        return self._mainWin.GetDisabledTextColour()

[docs]    def GetHyperTextFont(self):
        """ Returns the font used to render an hypertext item. """

        return self._mainWin.GetHyperTextFont()

[docs]    def SetHyperTextFont(self, font):
        """
        Sets the font used to render hypertext items.

        :param `font`: a valid `wx.Font` instance.
        """

        self._mainWin.SetHyperTextFont(font)

[docs]    def SetHyperTextNewColour(self, colour):
        """
        Sets the colour used to render a non-visited hypertext item.

        :param `colour`: a valid `wx.Colour` instance.
        """

        self._mainWin.SetHyperTextNewColour(colour)

[docs]    def GetHyperTextNewColour(self):
        """ Returns the colour used to render a non-visited hypertext item. """

        return self._mainWin.GetHyperTextNewColour()

[docs]    def SetHyperTextVisitedColour(self, colour):
        """
        Sets the colour used to render a visited hypertext item.

        :param `colour`: a valid `wx.Colour` instance.
        """

        self._mainWin.SetHyperTextVisitedColour(colour)

[docs]    def GetHyperTextVisitedColour(self):
        """ Returns the colour used to render a visited hypertext item. """

        return self._mainWin.GetHyperTextVisitedColour()

[docs]    def SetItemVisited(self, itemOrId, col=0, visited=True):
        """
        Sets whether an hypertext item was visited or not.

        :param `itemOrId`: an instance of L{UltimateListItem} or the item index;
        :param `col`: the column index to which the input item belongs to;
        :param `visited`: ``True`` to mark an hypertext item as visited, ``False`` otherwise.
        """

        item = CreateListItem(itemOrId, col)
        return self._mainWin.SetItemVisited(item, visited)

[docs]    def GetItemVisited(self, itemOrId, col=0):
        """
        Returns whether an hypertext item was visited.

        :param `itemOrId`: an instance of L{UltimateListItem} or the item index;
        :param `col`: the column index to which the input item belongs to.
        """

        item = CreateListItem(itemOrId, col)
        return self._mainWin.GetItemVisited(item)

[docs]    def GetItemWindow(self, itemOrId, col=0):
        """
        Returns the window associated to the item (if any).

        :param `itemOrId`: an instance of L{UltimateListItem} or the item index;
        :param `col`: the column index to which the input item belongs to.
        """

        item = CreateListItem(itemOrId, col)
        return self._mainWin.GetItemWindow(item)

[docs]    def SetItemWindow(self, itemOrId, col=0, wnd=None, expand=False):
        """
        Sets the window for the given item.

        :param `itemOrId`: an instance of L{UltimateListItem} or the item index;
        :param `col`: the column index to which the input item belongs to;
        :param `wnd`: a non-toplevel window to be displayed next to the item;
        :param `expand`: ``True`` to expand the column where the item/subitem lives,
         so that the window will be fully visible.
        """

        item = CreateListItem(itemOrId, col)
        return self._mainWin.SetItemWindow(item, wnd, expand)

[docs]    def DeleteItemWindow(self, itemOrId, col=0):
        """
        Deletes the window associated to an item (if any).

        :param `itemOrId`: an instance of L{UltimateListItem} or the item index;
        :param `col`: the column index to which the input item belongs to.
        """

        item = CreateListItem(itemOrId, col)
        return self._mainWin.DeleteItemWindow(item)

[docs]    def GetItemWindowEnabled(self, itemOrId, col=0):
        """
        Returns whether the window associated to the item is enabled.

        :param `itemOrId`: an instance of L{UltimateListItem} or the item index;
        :param `col`: the column index to which the input item belongs to;
        """

        item = CreateListItem(itemOrId, col)
        return self._mainWin.GetItemWindowEnabled(item)

[docs]    def SetItemWindowEnabled(self, itemOrId, col=0, enable=True):
        """
        Enables/disables the window associated to the item.

        :param `itemOrId`: an instance of L{UltimateListItem} or the item index;
        :param `col`: the column index to which the input item belongs to;
        :param `enable`: ``True`` to enable the associated window, ``False`` to disable it.
        """

        item = CreateListItem(itemOrId, col)
        return self._mainWin.SetItemWindowEnabled(item, enable)

[docs]    def GetItemCustomRenderer(self, itemOrId, col=0):
        """
        Returns the custom renderer used to draw the input item (if any).

        :param `itemOrId`: an instance of L{UltimateListItem} or the item index;
        :param `col`: the column index to which the input item belongs to.
        """

        item = CreateListItem(itemOrId, col)
        return self._mainWin.GetItemCustomRenderer(item)

[docs]    def SetHeaderCustomRenderer(self, renderer=None):
        """
        Associate a custom renderer with the header - all columns will use it.

        :param `renderer`: a class able to correctly render header buttons

        :note: the renderer class **must** implement the methods `DrawHeaderButton`
         and `GetForegroundColor`.
        """

        if not self.HasAGWFlag(ULC_REPORT):
            raise Exception("Custom renderers can be used on with style = ULC_REPORT")

        self._headerWin.SetCustomRenderer(renderer)

[docs]    def SetFooterCustomRenderer(self, renderer=None):
        """
        Associate a custom renderer with the footer - all columns will use it.

        :param `renderer`: a class able to correctly render header buttons

        :note: the renderer class **must** implement the methods `DrawHeaderButton`
         and `GetForegroundColor`.
        """

        if not self.HasAGWFlag(ULC_REPORT) or not self.HasAGWFlag(ULC_FOOTER):
            raise Exception("Custom renderers can only be used on with style = ULC_REPORT | ULC_FOOTER")

        self._footerWin.SetCustomRenderer(renderer)

[docs]    def SetColumnCustomRenderer(self, col=0, renderer=None):
        """
        Associate a custom renderer to this column's header.

        :param `col`: the column index.
        :param `renderer`: a class able to correctly render the input item.

        :note: the renderer class **must** implement the methods `DrawHeaderButton`
         and `GetForegroundColor`.
        """

        if not self.HasAGWFlag(ULC_REPORT):
            raise Exception("Custom renderers can be used on with style = ULC_REPORT")

        return self._mainWin.SetCustomRenderer(col, renderer)

[docs]    def SetItemCustomRenderer(self, itemOrId, col=0, renderer=None):
        """
        Associate a custom renderer to this item.

        :param `itemOrId`: an instance of L{UltimateListItem} or the item index;
        :param `col`: the column index to which the input item belongs to;
        :param `renderer`: a class able to correctly render the input item.

        :note: the renderer class **must** implement the methods `DrawSubItem`,
         `GetLineHeight` and `GetSubItemWidth`.
        """

        if not self.HasAGWFlag(ULC_REPORT) or not self.HasAGWFlag(ULC_HAS_VARIABLE_ROW_HEIGHT):
            raise Exception("Custom renderers can be used on with style = ULC_REPORT | ULC_HAS_VARIABLE_ROW_HEIGHT")

        item = CreateListItem(itemOrId, col)
        return self._mainWin.SetItemCustomRenderer(item, renderer)

[docs]    def SetItemOverFlow(self, itemOrId, col=0, over=True):
        """
        Sets the item in the overflow/non overflow state.

        An item/subitem may overwrite neighboring items/subitems if its text would
        not normally fit in the space allotted to it.

        :param `itemOrId`: an instance of L{UltimateListItem} or the item index;
        :param `col`: the column index to which the input item belongs to;
        :param `over`: ``True`` to set the item in a overflow state, ``False`` otherwise.
        """

        if not self.HasAGWFlag(ULC_REPORT) or self._mainWin.IsVirtual():
            raise Exception("Overflowing items can be used only in report, non-virtual mode")

        item = CreateListItem(itemOrId, col)
        return self._mainWin.SetItemOverFlow(item, over)

[docs]    def GetItemOverFlow(self, itemOrId, col=0):
        """
        Returns if the item is in the overflow state.

        An item/subitem may overwrite neighboring items/subitems if its text would
        not normally fit in the space allotted to it.

        :param `itemOrId`: an instance of L{UltimateListItem} or the item index;
        :param `col`: the column index to which the input item belongs to.
        """

        item = CreateListItem(itemOrId, col)
        return self._mainWin.GetItemOverFlow(item)

[docs]    def IsVirtual(self):
        """ Returns ``True`` if the L{UltimateListCtrl} has the ``ULC_VIRTUAL`` style set. """

        return self._mainWin.IsVirtual()

[docs]    def GetScrollPos(self):
        """
        Returns the scrollbar position.

        :note: This method is forwarded to L{UltimateListMainWindow}.
        """

        if self._mainWin:
            return self._mainWin.GetScrollPos()

        return 0

[docs]    def SetScrollPos(self, orientation, pos, refresh=True):
        """
        Sets the scrollbar position.

        :param `orientation`: determines the scrollbar whose position is to be set.
         May be ``wx.HORIZONTAL`` or ``wx.VERTICAL``;
        :param `pos`: the scrollbar position in scroll units;
        :param `refresh`: ``True`` to redraw the scrollbar, ``False`` otherwise.

        :note: This method is forwarded to L{UltimateListMainWindow}.
        """

        if self._mainWin:
            self._mainWin.SetScrollPos(orientation, pos, refresh)

[docs]    def GetScrollThumb(self):
        """
        Returns the scrollbar size in pixels.

        :note: This method is forwarded to L{UltimateListMainWindow}.
        """

        if self._mainWin:
            return self._mainWin.GetScrollThumb()

        return 0

[docs]    def GetScrollRange(self):
        """
        Returns the scrollbar range in pixels.

        :note: This method is forwarded to L{UltimateListMainWindow}.
        """

        if self._mainWin:
            return self._mainWin.GetScrollRange()

        return 0

[docs]    def SetHeaderHeight(self, height):
        """
        Sets the L{UltimateListHeaderWindow} height, in pixels. This overrides the default
        header window size derived from `wx.RendererNative`. If `height` is ``None``, the
        default behaviour is restored.

        :param `height`: the header window height, in pixels (if it is ``None``, the default
         height obtained using `wx.RendererNative` is used).
        """

        if not self._headerWin:
            return

        if height is not None and height < 1:
            raise Exception("Invalid height passed to SetHeaderHeight: %s"%repr(height))

        self._headerWin._headerHeight = height
        self.DoLayout()

[docs]    def GetHeaderHeight(self):
        """ Returns the L{UltimateListHeaderWindow} height, in pixels. """

        if not self._headerWin:
            return -1

        return self._headerWin.GetWindowHeight()

[docs]    def SetFooterHeight(self, height):
        """
        Sets the L{UltimateListHeaderWindow} height, in pixels. This overrides the default
        footer window size derived from `wx.RendererNative`. If `height` is ``None``, the
        default behaviour is restored.

        :param `height`: the footer window height, in pixels (if it is ``None``, the default
         height obtained using `wx.RendererNative` is used).
        """

        if not self._footerWin:
            return

        if height is not None and height < 1:
            raise Exception("Invalid height passed to SetFooterHeight: %s"%repr(height))

        self._footerWin._footerHeight = height
        self.DoLayout()

[docs]    def GetFooterHeight(self):
        """ Returns the L{UltimateListHeaderWindow} height, in pixels. """

        if not self._footerWin:
            return -1

        return self._headerWin.GetWindowHeight()

[docs]    def DoLayout(self):
        """
        Layouts the header, main and footer windows. This is an auxiliary method to avoid code
        duplication.
        """

        self.Layout()

        self._mainWin.ResizeColumns()
        self._mainWin.ResetVisibleLinesRange(True)
        self._mainWin.RecalculatePositions()
        self._mainWin.AdjustScrollbars()

        if self._headerWin:
            self._headerWin.Refresh()

        if self._footerWin:
            self._footerWin.Refresh()

Navigation

  • index
  • modules |
  • Home |
  • Gallery |
  • Contents»
  • Module code »
  • ultimatelistctrl


xlsgrid

  • modules |
  • Home |
  • Gallery |
  • Contents»
  • Module code »
  • xlsgrid

Source code for xlsgrid

# --------------------------------------------------------------------------------- #
# XLSGRID wxPython IMPLEMENTATION
#
# Andrea Gavana @ 08 Aug 2011
# Latest Revision: 17 Aug 2011, 15.00 GMT
#
#
# TODO List
#
# Current todo list:
#
# 1. There is currently no support for rich text, i.e. strings containing partial
#    bold, italic and underlined text, change of font inside a string, etc... xlrd
#    supports those (from version 0.7.2 in SVN) but there is no easy way to handle
#    changing fonts/colours/formatting in the same string in wxPython;
#
# 2. XLSGrid is sufficiently efficient and fast for reasonably small Excel files.
#    There might be some improvement to be made in the code to make it work with
#    bigger files and in a faster way;
#
# 3. There is currently no support for strikethrough fonts, although xlrd correctly
#    reports this format. The issue is a bug in wxWidgets itself which doesn't
#    allow the creation of strikethrough fonts (http://trac.wxwidgets.org/ticket/9907).
#
# 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
# --------------------------------------------------------------------------------- #

"""
L{XLSGrid} is a class based on `wx.grid.Grid` that can be used to faithfully
reproduce the appearance of a Microsoft Excel spreadsheet (one worksheet per
every instance of L{XLSGrid}).

Description
===========

L{XLSGrid} is a class based on `wx.grid.Grid` that can be used to faithfully
reproduce the appearance of a Microsoft Excel spreadsheet (one worksheet per
every instance of L{XLSGrid}).

L{XLSGrid} is a completely owner-drawn control, and it relies on the power of
`wx.grid.PyGridTableBase` and `wx.grid.PyGridCellRenderer` to draw the cell
content. For this reasons (and for some others, see the TODOs section), it will
work efficiently only for relatively small Excel files.

:note:

 L{XLSGrid} **requires** the `xlrd` package from:

 http://pypi.python.org/pypi/xlrd

 Minimum version requirement for `xlrd` is 0.7.1. If you wish to have
 support for hyperlinks inside cells and rich text content, you need the
 SVN version of `xlrd`.

:note:

 On Windows, it is **strongly** recommended to install Mark Hammonds'
 `pywin32` package:

 http://sourceforge.net/projects/pywin32/

 This will allow you to perfectly reproduce the appearance of the Excel
 worksheet in your instance of L{XLSGrid}.

:warning:

 If Mark Hammonds' `pywin32` package is not available, the formatting
 capabilities of L{XLSGrid} are severely limited; for instance, you won't
 probably get the exact WYSIWYG between the Excel spreadsheet and L{XLSGrid}.

:warning:

 L{XLSGrid} can only read Excel `.xls` files, not the newer versions
 `.xlsx` generated by Office 2007/2010. If you have a `.xlsx` file, you will
 need to save it in 1997-2003 Office compatibility mode.

Currently this class provides a read-only subclass of `wx.grid.Grid`, with
the following formatting features already implemented:

* Cell background: support for any cell background colour and fill pattern
  (hatching) in the Excel default set. There currently is no support for
  gradient shading inside a cell as `xlrd` doesn't report this information.

* Cell borders: support for all the border types and colours exposed by Excel
  (left, top, bottom, right and diagonal borders, thin, double, thick, ect...
  line styles).

* Cell text: support for all kind of fonts (except strikethrough, but this is
  a bug in wxWidgets), and font colours. As a subset of text/font capabilities,
  L{XLSGrid} supports the following features found in Excel:

  - Horizontal alignment: left, right, centered, left-indented;
  - Vertical alignment: left, right, centered;
  - Text direction: left-to-right or right-to-left;
  - Text-wrapping: wrapping long texts inside a grid cell;
  - Shrink-to-fit: text font is reduced until the text can fit in a one-line
    inside the grid cell;
  - Text rotation: text can be rotated from +90 to -90 degrees.

* Cell rich text (new in version 0.2): support for strings containing partial
  bold, italic and underlined text, change of font inside a string etc...
  Cells with rich text content can not be multi-line and they will not honour
  the `shrink-to-fit` and `wrapping` settings.

* Cell text appearance: if you are using Mark Hammonds' `pywin32` package, the
  text displayed in the L{XLSGrid} cells has exactly the same appearance as in
  the Excel spreadsheet.

* Cell comments (notes): if you are using Mark Hammonds' `pywin32` package,
  cell comments (notes) are extracted and you will see a small red triangle at
  the top-right corner of any cell containing a comment. Hovering with the
  mouse on that cell will pop-up a "comment-window" displaying the comment
  text (the comment window is based on `wx.lib.agw.supertooltip`).

* Cell hyperlinks: starting from version 0.7.2 (SVN), `xlrd` is capable of
  extracting hyperlinks from Excel cells. This will be appropriately displayed
  in L{XLSGrid} with a cursor changing and a tooltip on that cell.

* Cell merging: merged cells in the Excel spreadsheet will be correctly handled
  by L{XLSGrid}.

* Columns and rows sizes: L{XLSGrid} calculates the correct rows and columns
  sizes based on the Excel reported values in characters. The calculations are
  based on the default width of the text in 1/256 of the width of the zero
  character, using default Excel font (first FONT record in the Excel file).

And a lot more. Check the demo for an almost complete review of the functionalities.

Usage
=====

Sample usage::

    import wx
    import xlrd
    import os

    import xlsgrid as XG

    class MyFrame(wx.Frame):

        def __init__(self):

            wx.Frame.__init__(self, parent, -1, "XLSGrid Demo", size=(1000, 800))

            filename = os.path.join(os.getcwd(), "Excel", "Example_1.xls")
            sheetname = "Example_1"

            book = xlrd.open_workbook(filename, formatting_info=1)

            sheet = book.sheet_by_name(sheetname)
            rows, cols = sheet.nrows, sheet.ncols

            comments, texts = XG.ReadExcelCOM(filename, sheetname, rows, cols)

            xls_grid = XG.XLSGrid(self)
            xls_grid.PopulateGrid(book, sheet, texts, comments)

    # our normal wxApp-derived class, as usual

    app = wx.PySimpleApp()

    frame = MyFrame(None)
    app.SetTopWindow(frame)
    frame.Show()

    app.MainLoop()

:note: Please note that you **have to** pass the keyword `formatting_info` to
 the method `xlrd.open_workbook` to obtain the cell formatting.

TODOs
=====

1. L{XLSGrid} is sufficiently efficient and fast for reasonably small Excel files.
   There might be some improvement to be made in the code to make it work with
   bigger files and in a faster way;
2. `wx.grid.Grid` seems to completely redraw itself at every resize event, even
   if the cell content has not changed and it has not been damaged (this seems
   to be fixed in wxPython 2.9.2.1);
3. There is currently no support for strikethrough fonts, although `xlrd` correctly
   reports this format. The issue is a bug in wxWidgets itself which doesn't
   allow the creation of strikethrough fonts (http://trac.wxwidgets.org/ticket/9907).

Supported Platforms
===================

L{XLSGrid} has been tested on the following platforms:
  * Windows (Windows Vista and 7);

Window Styles
=============

`No particular window styles are available for this class.`

Events Processing
=================

`No custom events are available for this class.`

License And Version
===================

L{XLSGrid} is distributed under the wxPython license.

Latest Revision: Andrea Gavana @ 17 Aug 2011, 15.00 GMT

Version 0.3

"""

# Version Info
__version__ = "0.3"

# Start the imports
import wx
import os

try:
    import xlrd
except ImportError:
    pass

import datetime
import string

import wx.grid as gridlib

from wx.lib.embeddedimage import PyEmbeddedImage
from wx.lib.wordwrap import wordwrap

import supertooltip as STT

from math import pi, sin, cos
from operator import attrgetter

_hasWin32 = False

if wx.Platform == "__WXMSW__":
    try:
        from win32com.client import Dispatch
        import pywintypes
        _hasWin32 = True
    except ImportError:
        pass

#----------------------------------------------------------------------
# Constants used to translate xlrd stuff into wxPython stuff
#----------------------------------------------------------------------

BOTTOM = wx.BOTTOM
TOP = wx.TOP
LEFT = wx.LEFT
RIGHT = wx.RIGHT
DIAGONAL = 2 << 7

XF_BORDER_STYLES = {"bottom": BOTTOM, "left": LEFT, "right": RIGHT,
                    "top": TOP, "diag": DIAGONAL}

HORIZONTAL_ALIGNMENTS = {0: 0, 1: 0, 2: wx.ALIGN_CENTER_HORIZONTAL, 3: wx.ALIGN_RIGHT}
VERTICAL_ALIGNMENTS   = {0: 0, 1: wx.ALIGN_CENTER_VERTICAL, 2: wx.ALIGN_BOTTOM,
                         3: wx.ALIGN_CENTER_VERTICAL, 4:wx.ALIGN_CENTER_VERTICAL}

NO_LINE = 0x0
THIN = 0x1
MEDIUM = 0x2
DASHED = 0x3
DOTTED = 0x4
THICK = 0x5
DOUBLE = 0x6
HAIR = 0x7
MEDIUM_DASHED = 0x8
THIN_DASH_DOTTED = 0x9
MEDIUM_DASH_DOTTED = 0xA
THIN_DASH_DOT_DOTTED = 0xB
MEDIUM_DASH_DOT_DOTTED = 0xC
SLANTED_MEDIUM_DASH_DOTTED = 0xD

XF_PEN_STYLES = {NO_LINE: (0, None), THIN: (1, wx.SOLID), MEDIUM: (2, wx.SOLID),
                 DASHED: (1, wx.SHORT_DASH), DOTTED: (1, wx.DOT),
                 THICK: (3, wx.SOLID), DOUBLE: (1, wx.SOLID), HAIR: (1, wx.DOT),
                 MEDIUM_DASHED: (2, wx.LONG_DASH), THIN_DASH_DOTTED: (1, wx.DOT_DASH),
                 MEDIUM_DASH_DOTTED: (2, wx.DOT_DASH), THIN_DASH_DOT_DOTTED: (1, wx.DOT_DASH),
                 MEDIUM_DASH_DOT_DOTTED: (2, wx.DOT_DASH),
                 SLANTED_MEDIUM_DASH_DOTTED: (2, wx.DOT_DASH)
                 }

XF_FONT_FAMILY = {0: wx.SWISS, 1: wx.ROMAN, 2: wx.SWISS,
                  3: wx.MODERN, 4: wx.SCRIPT, 5: wx.DECORATIVE}

# Unicode ordinals for Hebrew, Arabic and Syriac
# I don't know if there are other RTL languages
RTL_UNICODE = range(1424, 1872)

# To guess text direction we exclude digits and punctuation
USELESS_CHARS = string.punctuation + string.digits + " "

#----------------------------------------------------------------------
# Images used to draw the hatching on Excel cells background
#----------------------------------------------------------------------

_xls_background_01 = PyEmbeddedImage(
    "iVBORw0KGgoAAAANSUhEUgAAAAQAAAAECAIAAAAmkwkpAAAAA3NCSVQICAjb4U/gAAAADElE"
    "QVQImWNgIB0AAAA0AAEjQ4N1AAAAAElFTkSuQmCC")

#----------------------------------------------------------------------
_xls_background_02 = PyEmbeddedImage(
    "iVBORw0KGgoAAAANSUhEUgAAAAQAAAAECAIAAAAmkwkpAAAAA3NCSVQICAjb4U/gAAAAFklE"
    "QVQImWNgYGD4//8/lESwIAC7DABt4hfpI2a12wAAAABJRU5ErkJggg==")

#----------------------------------------------------------------------
_xls_background_03 = PyEmbeddedImage(
    "iVBORw0KGgoAAAANSUhEUgAAAAQAAAAECAIAAAAmkwkpAAAAA3NCSVQICAjb4U/gAAAAE0lE"
    "QVQImWP4//8/AxqACuGUAQBI+Qv1NTPP3AAAAABJRU5ErkJggg==")

#----------------------------------------------------------------------
_xls_background_04 = PyEmbeddedImage(
    "iVBORw0KGgoAAAANSUhEUgAAAAQAAAAECAIAAAAmkwkpAAAAA3NCSVQICAjb4U/gAAAAH0lE"
    "QVQImXXJsQ0AIAAEIc79d34LazsSwjbgPFXoOxdcCQwBh7OgqgAAAABJRU5ErkJggg==")

#----------------------------------------------------------------------
_xls_background_05 = PyEmbeddedImage(
    "iVBORw0KGgoAAAANSUhEUgAAAAQAAAAECAIAAAAmkwkpAAAAA3NCSVQICAjb4U/gAAAAFUlE"
    "QVQImWNgwAUY////D+cwIcsAAEggAwHHgMubAAAAAElFTkSuQmCC")

#----------------------------------------------------------------------
_xls_background_06 = PyEmbeddedImage(
    "iVBORw0KGgoAAAANSUhEUgAAAAQAAAAECAIAAAAmkwkpAAAAA3NCSVQICAjb4U/gAAAAG0lE"
    "QVQImWNkYGBgYGD4//8/AwMDEwMSwM0BAISAAwUnufp7AAAAAElFTkSuQmCC")

#----------------------------------------------------------------------
_xls_background_07 = PyEmbeddedImage(
    "iVBORw0KGgoAAAANSUhEUgAAAAQAAAAECAIAAAAmkwkpAAAAA3NCSVQICAjb4U/gAAAAHklE"
    "QVQImWNkYGBgYGD4//8/EgVh/P//H86HikH4APOCFO3yiGicAAAAAElFTkSuQmCC")

#----------------------------------------------------------------------
_xls_background_08 = PyEmbeddedImage(
    "iVBORw0KGgoAAAANSUhEUgAAAAQAAAAECAIAAAAmkwkpAAAAA3NCSVQICAjb4U/gAAAAHUlE"
    "QVQImWP4////////GSAAzvr//z8jmhADXCUAQSkU7eggG3gAAAAASUVORK5CYII=")

#----------------------------------------------------------------------
_xls_background_09 = PyEmbeddedImage(
    "iVBORw0KGgoAAAANSUhEUgAAAAQAAAAECAIAAAAmkwkpAAAAA3NCSVQICAjb4U/gAAAAIElE"
    "QVQImWNkYGBgYGD4//8/AwMDEwMy+P//P0QYXQYACtQI/cTE6U0AAAAASUVORK5CYII=")

#----------------------------------------------------------------------
_xls_background_10 = PyEmbeddedImage(
    "iVBORw0KGgoAAAANSUhEUgAAAAQAAAAECAIAAAAmkwkpAAAAA3NCSVQICAjb4U/gAAAAG0lE"
    "QVQImW3IsQ0AAAjAIPz/6LobGRmgclVfswpsCPmQczsGAAAAAElFTkSuQmCC")

#----------------------------------------------------------------------
_xls_background_11 = PyEmbeddedImage(
    "iVBORw0KGgoAAAANSUhEUgAAAAQAAAAECAIAAAAmkwkpAAAAA3NCSVQICAjb4U/gAAAAFklE"
    "QVQImWNgQAKM////h3OYkGVQOABvOgMD4NUKkwAAAABJRU5ErkJggg==")

#----------------------------------------------------------------------
_xls_background_12 = PyEmbeddedImage(
    "iVBORw0KGgoAAAANSUhEUgAAAAQAAAAECAIAAAAmkwkpAAAAA3NCSVQICAjb4U/gAAAAG0lE"
    "QVQImWNkYGD4//8/AwMDAwMDEwMSwM0BAI13AwWY+Mx+AAAAAElFTkSuQmCC")

#----------------------------------------------------------------------
_xls_background_13 = PyEmbeddedImage(
    "iVBORw0KGgoAAAANSUhEUgAAAAQAAAAECAIAAAAmkwkpAAAAA3NCSVQICAjb4U/gAAAAI0lE"
    "QVQImT3KsQ0AMAyAMMj/P9MhUUcLBCoAmEo9bFn7H/UBXEwMBN75abEAAAAASUVORK5CYII=")

#----------------------------------------------------------------------
_xls_background_14 = PyEmbeddedImage(
    "iVBORw0KGgoAAAANSUhEUgAAAAQAAAAECAIAAAAmkwkpAAAAA3NCSVQICAjb4U/gAAAAIElE"
    "QVQImT3KoQEAAAwCINz/P7tmI5C2QJKb2t6EYPMBOOUMBIWcMEIAAAAASUVORK5CYII=")

#----------------------------------------------------------------------
_xls_background_15 = PyEmbeddedImage(
    "iVBORw0KGgoAAAANSUhEUgAAAAQAAAAECAIAAAAmkwkpAAAAA3NCSVQICAjb4U/gAAAAGUlE"
    "QVQImWNgQAKMDAwM////h3CYkGVQOABmQwMDJpgq9gAAAABJRU5ErkJggg==")

#----------------------------------------------------------------------
_xls_background_16 = PyEmbeddedImage(
    "iVBORw0KGgoAAAANSUhEUgAAAAQAAAAECAIAAAAmkwkpAAAAA3NCSVQICAjb4U/gAAAAHklE"
    "QVQImWNgYGD4//8/lISzIAwEnxEqwMDAyMgIALKwF+2ym+hoAAAAAElFTkSuQmCC")

#----------------------------------------------------------------------
_xls_background_17 = PyEmbeddedImage(
    "iVBORw0KGgoAAAANSUhEUgAAAAQAAAAECAIAAAAmkwkpAAAAA3NCSVQICAjb4U/gAAAAIklE"
    "QVQImWNkYGD4//8/AwMDAwMDI5zFwMDABBVjZESXAQAc+AkAQ4bzDAAAAABJRU5ErkJggg==")

#----------------------------------------------------------------------
_xls_background_18 = PyEmbeddedImage(
    "iVBORw0KGgoAAAANSUhEUgAAAAgAAAAECAIAAAA8r+mnAAAAA3NCSVQICAjb4U/gAAAAH0lE"
    "QVQImWNkYGD4//8/AwZgxCrKwMDAhKKKkZGwDgA83QkAy10JvwAAAABJRU5ErkJggg==")

#----------------------------------------------------------------------

[docs]def SplitThousands(s, tSep=',', dSep='.'):
    """
    Splits a general float on thousands. GIGO on general input.

    :param `s`: can be a float or a string, representing a number;
    :param `tSep`: the character to be used as thousands separator;
    :param `dSep`: the character to be used as decimal separator.

    :returns: a string properly formatted with thousands and decimal
     separators in it.

    :note: This method is used only if Mark Hammonds' `pywin32` package is
     not available to try and format a number in an intelligent way.

    :note: This code has been obtained from the public domain:

     http://code.activestate.com/recipes/498181-add-thousands-separator-commas-to-formatted-number/#c14

    """

    if not isinstance(s, basestring):
        s = unicode(s, "utf-8", "ignore")

    cnt = 0
    numChars = dSep + '0123456789'
    ls = len(s)

    while cnt < ls and s[cnt] not in numChars:
        cnt += 1

    lhs = s[0:cnt]
    s = s[cnt:]

    if dSep == '':
        cnt = -1
    else:
        cnt = s.rfind(dSep)

    if cnt > 0:
        rhs = dSep + s[cnt+1:]
        s = s[:cnt]
    else:
        rhs = ''

    splt = ''
    while s != '':
        splt = s[-3:] + tSep + splt
        s = s[:-3]

    return lhs + splt[:-1] + rhs

[docs]def ReadExcelCOM(filename, sheetname, rows, cols):
    """
    Reads and Excel spreadsheet (a single worksheet) using Mark Hammonds' `pywin32`
    package. If this package is not available, it returns two empty nested lists.

    :param `filename`: a valid Excel `.xls` filename;
    :param `sheetname`: the worksheet name inside the Excel file (i.e., the label
     on the workbook tab at the bottom of the workbook);
    :param `rows`: the number of significant rows in the worksheet, as returned
     by `xlrd`;
    :param `cols`: the number of significant columns in the worksheet, as returned
     by `xlrd`.

    :returns: two nested lists representing the comments (notes) on every cell and
     the WYSIWYG representation of the cell content.

    :note: If Mark Hammonds' `pywin32` package is not available, this method
     returns two empty nested lists.
    """

    comments = [["" for i in range(cols)] for j in range(rows)]
    texts    = [[None for i in range(cols)] for j in range(rows)]

    if not _hasWin32:
        return comments, texts

    workbook = Excel(filename, sheetname)

    for i in xrange(1, rows+1):
        for j in xrange(1, cols+1):
            texts[i-1][j-1]    = workbook.GetText(i, j)

    comm_range = workbook.GetCommentsRange()
    if comm_range is not None:
        for comm in comm_range:
            comments[comm.Row-1][comm.Column-1] = comm.Comment.Text()

    workbook.Close()
    return comments, texts

[docs]def FontFromFont(font):
    """
    Creates a copy of the input `font`.

    :param `font`: an instance of `wx.Font`.
    """

    new_font = wx.Font(font.GetPointSize(), font.GetFamily(), font.GetStyle(),
                       font.GetWeight(), font.GetUnderlined(),
                       font.GetFaceName(), font.GetEncoding())

    return new_font

[docs]class Excel(object):
    """
    A simple class that holds a COM interface to Excel.

    By using the `win32com` module from Mark Hammonds' `pywin32` package, we
    can manipulate various workbook/worksheet methods inside this class.
    """

[docs]    def __init__(self, filename, sheetname):
        """
        Default class constructor.

        :param `filename`: a valid Excel `.xls` filename;
        :param `sheetname`: the worksheet name inside the Excel file (i.e., the label
         on the workbook tab at the bottom of the workbook).
        """

        self.xlApp = Dispatch('Excel.Application')
        self.filename = filename
        self.xlBook = self.xlApp.Workbooks.Open(filename)
        self.sheet = self.xlBook.Worksheets(sheetname)

        self.xlApp.Visible = 0

[docs]    def Close(self, save=False):
        """
        Closes the Excel workbook, interrupting the COM interface.

        :param `save`: ``True`` to save the changes you made to the workbook,
         ``False`` otherwise.
        """

        self.xlBook.Close(SaveChanges=save)
        del self.xlApp

[docs]    def GetCommentsRange(self):
        """
        Returns a range of cells containing comments, using the VBA API.

        """

        try:
            return self.sheet.Cells.SpecialCells(-4144)
        except pywintypes.com_error:
            return None

[docs]    def GetText(self, row, col):
        """
        Returns the WYSIWYG text contained in a cell.

        :param `row`: the row in which the cell lives;
        :param `col`: the column in which the cell lives.

        :note: The `row` and `col` parameters are not real Python index, as they
         use the Excel indexing mode (i.e., first index is 1 and not 0).
        """

        cell = self.sheet.Cells(row, col)

        if cell:
            return cell.Text

[docs]class XLSText(object):
    """
    This is a class which holds information about the cell content, in terms
    of actual cell value, font, text colour, alignment and formatting.
    """

[docs]    def __init__(self, book, cell, xf_index, display_text=None, hyperlink=None, default_width=10):
        """
        Default class constructor.

        :param `book`: an instance of the `xlrd.Book` class;
        :param `cell`: an instance of `xlrd.sheet.Cell` class;
        :param `xf_index`: an index into `xlrd.Book.xf_list`, which holds a
         reference to the `xlrd.sheet.Cell` class (the actual cell for `xlrd`);
        :param `display_text`: if Mark Hammonds' `pywin32` package is available,
         this is the WYSIWYG cell content;
        :param `hyperlink`: if this cell contains a hyperlink, it will be displayed
         accordingly;
        :param `default_width`: this is the default width of the text in 1/256
         of the width of the zero character, using default Excel font (first FONT
         record in the Excel file).

        :note: If you are using version 0.7.1 or lower for `xlrd`, the *hyperlink*
         parameter will always be ``None`` as this feature is available only in
         `xlrd` 0.7.2 (SVN).
        """

        XFClass = book.xf_list[xf_index]

        font = book.font_list[XFClass.font_index]
        self.font = self.CreateFont(font)

        text_colour = book.colour_map[font.colour_index]
        self.text_colour = self.CreateTextColour(text_colour)

        if display_text is not None:
            self.value = display_text
        else:
            format = book.format_map[XFClass.format_key]
            self.CreateFormat(format, cell, book.datemode)

        alignment = XFClass.alignment
        self.CreateAlignment(alignment, default_width)

        if hyperlink is not None:
            self.SetupHyperlink(hyperlink)
        else:
            self.tooltip = None

[docs]    def CreateFont(self, font):
        """
        Creates a suitable wxPython font starting from an Excel font.

        :param `font`: an instance of `xlrd.formatting.Font` class.

        :note: There is currently no support for strikethrough fonts, although
         `xlrd` correctly reports this format. The issue is a bug in wxWidgets
         itself which doesn't allow the creation of strikethrough fonts. See
         (http://trac.wxwidgets.org/ticket/9907).
        """

        style, bold, underline = wx.FONTSTYLE_NORMAL, wx.NORMAL, False
        if font.italic:
            style = wx.FONTSTYLE_ITALIC
        if font.underline_type > 0:
            underline = True
        if font.weight > 600:
            bold = wx.BOLD

        family = XF_FONT_FAMILY[font.family]
        name = font.name
        size = int(font.height/20.0)

        if font.escapement_type > 0:
            # subscript/superscript
            size = int(size*0.7)

        # No support for strike-through fonts in wxWidgets
#        if font.struck_out:
#            style = wx.FONTFLAG_DEFAULT
#            if bold:
#                style += wx.FONTFLAG_BOLD
#            if underline:
#                style += wx.FONTFLAG_UNDERLINED
#            if font.italic:
#                style += wx.FONTFLAG_ITALIC
#
#            style += wx.FONTFLAG_STRIKETHROUGH
#            self.font = wx.FFont(size, family, style, name.encode())
#        else:

        return wx.Font(size, family, style, bold, underline, name.encode())

[docs]    def CreateTextColour(self, text_colour):
        """
        Creates a suitable wxPython colour for the text starting from a `xlrd`
        tuple representing this colour.

        :param `text_colour`: a tuple representing the RGB components of the
         colour. If `text_colour` is ``None``, use the default ``wx.SYS_COLOUR_WINDOWTEXT``.
        """

        if text_colour is not None:
            text_colour = wx.Colour(*text_colour)
        else:
            text_colour = wx.SystemSettings.GetColour(wx.SYS_COLOUR_WINDOWTEXT)

        return text_colour

[docs]    def CreateAlignment(self, alignment, default_width):
        """
        Creates a suitable wxPython alignment flag for the text starting from a
        `xlrd` class representing this alignment.

        :param `alignment`: an instance of `xlrd.formatting.XFAlignment` class;
        :param `default_width`: this is the default width of the text in 1/256
         of the width of the zero character, using default Excel font (first FONT
         record in the Excel file).
        """

        hor_align, vert_align = alignment.hor_align, alignment.vert_align
        self.horizontal_alignment = HORIZONTAL_ALIGNMENTS[hor_align]
        self.vertical_alignment = VERTICAL_ALIGNMENTS[vert_align]

        self.indent_level = alignment.indent_level
        self.shrink_to_fit = alignment.shrink_to_fit
        self.text_wrapped = alignment.text_wrapped

        text_direction = 1

        if alignment.text_direction == 0:
            for char in self.value:
                if char not in USELESS_CHARS:
                    if ord(char) in RTL_UNICODE:
                        text_direction = 2
                        break

        self.text_direction = text_direction
        self.default_width = default_width

        if alignment.rotation > 90:
            self.rotation = 90 - alignment.rotation
        else:
            self.rotation = alignment.rotation

[docs]    def CreateFormat(self, format, cell, datemode):
        """
        This method tries to guess the best format to apply to the current text
        value.

        :param `format`: an instance of `xlrd.formatting.Format` class;
        :param `cell`: an instance of `xlrd.sheet.Cell` class;
        :param `datemode`: the datemode associated with this Excel workbook.

        :note: This method is used only if Mark Hammonds' `pywin32` package is
         not available to try and format the cell text in an intelligent way.

        :warning: The formatting applied by this method is severely limited; for
         instance, you won't probably get the exact WYSIWYG between the Excel
         spreadsheet and L{XLSGrid}.
        """

        ctype, value = cell.ctype, cell.value

        self.value = "%s"%value
        isDate = False

        if ctype == xlrd.XL_CELL_DATE:
            value = xlrd.xldate_as_tuple(value, datemode)
            isDate = True
        elif ctype in [xlrd.XL_CELL_EMPTY, xlrd.XL_CELL_BLANK]:
            return
        elif ctype == xlrd.XL_CELL_TEXT:
            self.value = "%s"%value
            return
        elif ctype == xlrd.XL_CELL_ERROR:
            value = xlrd.error_text_from_code(ctype)
            self.value = "%s"%value
            return

        self.FormatString(value, isDate, format.format_str)

[docs]    def FormatString(self, value, isDate, format_str):
        """
        This method tries to guess the best format to apply to the current text
        value.

        :param `value`: the actual raw cell text value;
        :param `isDate`: ``True`` if this value represents a `xlrd` date object,
         ``False`` otherwise;
        :param `format_str`: the actual formatting string as extracted from Excel.

        :note: This method is used only if Mark Hammonds' `pywin32` package is
         not available to try and format the cell text in an intelligent way.

        :warning: The formatting applied by this method is severely limited; for
         instance, you won't probably get the exact WYSIWYG between the Excel
         spreadsheet and L{XLSGrid}.
        """

        if "General" in format_str:
            self.value = "%s"%value
            return

        number_format = format_str
        currency = percentage = ""

        if not isDate:
            symbol = ""
            split = format_str.split()
            if len(split) > 1:
                # Accounting and currency shit
                currency = split[0].split(".")[0] + "."
                number_format = ".".join(split[1:])

            if "%" in number_format:
                percentage = "%"
                value = 100*value
                number_format = number_format[0:-1]

            representation = "%d"
            if "." in number_format:
                split = number_format.split(".")
                num_decimals = len(split[1])
                representation = "%0." + str(num_decimals) + "f"

            try:
                value = representation%value
            except ValueError:
                # Fall back to string
                value = unicode(value, "utf-8", "ignore")

            if "#," in number_format:
                value = SplitThousands(value)

            value = currency + value + percentage

        else:
            number_format = format_str.replace("\\", "")
            number_format = number_format.replace("-", "-%").replace("/", "/%")
            value = datetime.datetime(*value)
            try:
                value = value.strftime(number_format)
            except (ValueError, TypeError):
                value = value.strftime("%d.%m.%Y")

        self.value = value

[docs]    def SetupHyperlink(self, hyperlink):
        """
        Sets up the cell text value in case it represents a hyperlink.

        :param `hyperlink`: an instance of `xlrd.sheet.hyperlink`.

        :note: If you are using version 0.7.1 or lower for `xlrd`, the *hyperlink*
         parameter will always be ``None`` as this feature is available only in
         `xlrd` 0.7.2 (SVN).
        """

        url = (hyperlink.url_or_path and [hyperlink.url_or_path] or [hyperlink.textmark])[0]
        self.tooltip = url

[docs]    def IsHyperLink(self):
        """
        Returns whether the cell text is representing a hyperlink.

        :returns: ``True`` if the cell text represents a hyperlink, ``False``
         otherwise.
        """

        return self.tooltip is not None

[docs]    def CombineAttr(self, attr):
        """
        Combines the input attribute `attr` with the features of the L{XLSText} class.

        :param `attr`: an instance of `wx.grid.GridCellAttr`.
        """

        attr.SetAlignment(self.horizontal_alignment, self.vertical_alignment)
        attr.SetTextColour(self.text_colour)
        attr.SetFont(self.font)

[docs]    def GetValue(self):
        """ Returns the string representation of the cell text value. """

        return self.value

[docs]    def Draw(self, dc, rect):
        """
        Actually draws the text value on a grid cell.

        :param `dc`: an instance of `wx.DC`;
        :param `rect`: an instance of `wx.Rect`, representing the cell rectangle.
        """

        new_rect = wx.Rect(*rect)

        xshift = yshift = 0
        if self.rotation:
            xshift = cos(self.rotation*pi/180)
            yshift = sin(self.rotation*pi/180)

        dc.SetTextForeground(self.text_colour)
        dc.SetFont(self.font)

        value = self.value
        text_width, text_height = dc.GetTextExtent(value)

        default_width = int(round(float(self.default_width)*text_width/256.0))

        indentation = int(256.0*default_width/float(self.default_width))

        if xshift == 0 and self.indent_level:
            new_rect.SetLeft(new_rect.x + indentation)
        else:
            if self.horizontal_alignment == wx.ALIGN_LEFT:
                new_rect.SetLeft(new_rect.x + 3)
            elif self.horizontal_alignment == wx.ALIGN_RIGHT:
                new_rect.SetWidth(new_rect.width - 1)

        new_width = rect.width

        if xshift > 0:
            new_width = new_width/xshift

        if self.shrink_to_fit:

            font = FontFromFont(self.font)
            point_size = font.GetPointSize()

            while 1:
                value = wordwrap(self.value, new_width, dc)
                if "\n" not in value or point_size < 2:
                    break

                point_size -= 1
                font.SetPointSize(point_size)
                dc.SetFont(font)

        elif self.text_wrapped:

            value = wordwrap(self.value, new_width, dc)
            text_width, text_height, dummy = dc.GetMultiLineTextExtent(value)

        if self.rotation:
            if self.shrink_to_fit:
                text_width, text_height = dc.GetTextExtent(value)

            xc, yc = (rect.x+rect.width/2, rect.y+rect.height/2)
            xp = xc - (text_width/2)*xshift - (text_height/2)*yshift
            yp = yc + (text_width/2)*yshift - (text_height/2)*xshift

            dc.DrawRotatedText(value, xp, yp, self.rotation)

        else:

            dc.DrawLabel(value, new_rect, self.horizontal_alignment|self.vertical_alignment)

[docs]class XLSRichText(XLSText):
    """
    This is a class which holds information about the cell content, in terms
    of actual cell value, font, text colour, alignment and formatting. In addition
    to what L{XLSText} does, this class attempts to handle cells with rich text
    content.
    """

[docs]    def __init__(self, book, cell, xf_index, display_text=None, hyperlink=None, rich_text=None, default_width=10):
        """
        Default class constructor.

        :param `book`: an instance of the `xlrd.Book` class;
        :param `cell`: an instance of `xlrd.sheet.Cell` class;
        :param `xf_index`: an index into `xlrd.Book.xf_list`, which holds a
         reference to the `xlrd.sheet.Cell` class (the actual cell for `xlrd`);
        :param `display_text`: if Mark Hammonds' `pywin32` package is available,
         this is the WYSIWYG cell content;
        :param `hyperlink`: if this cell contains a hyperlink, it will be displayed
         accordingly;
        :param `rich_text`: if this cell contains text in rich text format, L{XLSGrid}
         will do its best to render the text as rich text;
        :param `default_width`: this is the default width of the text in 1/256
         of the width of the zero character, using default Excel font (first FONT
         record in the Excel file).

        :note: If you are using version 0.7.1 or lower for `xlrd`, the *hyperlink*
         parameter will always be ``None`` as this feature is available only in
         `xlrd` 0.7.2 (SVN).

        :note: If you are using version 0.7.1 or lower for `xlrd`, this class will
         note be used by L{XLSGrid}.

        :warning: This class currently supports only single-line non-rotated text,
         and it discards properties like `shrink-to-fit` and `wrapping`.
        """

        XLSText.__init__(self, book, cell, xf_index, display_text, hyperlink, default_width)

        self.BuildChunks(book, xf_index, rich_text)

[docs]    def BuildChunks(self, book, xf_index, rich_text):
        """
        Splits the cell content accordingly to their rich text format index.

        :param `book`: an instance of the `xlrd.Book` class;
        :param `xf_index`: an index into `xlrd.Book.xf_list`, which holds a
         reference to the `xlrd.sheet.Cell` class (the actual cell for `xlrd`);
        :param `rich_text`: if this cell contains text in rich text format, L{XLSGrid}
         will do its best to render the text as rich text.
        """

        XFClass = book.xf_list[xf_index]
        offset, index = rich_text[0]

        if offset != 0:
            new_tuple = (0, XFClass.font_index)
            rich_text.insert(0, new_tuple)

        value = self.value
        rich_text.append((len(value), rich_text[-1][1]))
        attributes = []

        for indx in xrange(len(rich_text)-1):
            offset_start, index_start = rich_text[indx]
            offset_end, index_end = rich_text[indx+1]

            chunk = value[offset_start:offset_end]

            font = book.font_list[index_start]
            ffont = self.CreateFont(font)
            text_colour = book.colour_map[font.colour_index]
            colour = self.CreateTextColour(text_colour)

            ffont.escapement = font.escapement_type
            attributes.append([chunk, ffont, colour])

        self.attributes = attributes

[docs]    def Measure(self, dc):
        """
        Convenience method to measure the maximum height and total width of all
        the chunks of text composing our rich text string.

        :param `dc`: an instance of `wx.DC`.
        """

        maxH = -1
        full_width = 0
        for chunk, font, colour in self.attributes:
            dc.SetFont(font)
            width, height, descent, leading = dc.GetFullTextExtent(chunk, font)
            maxH = max(maxH, height-leading)
            full_width += width

        return maxH, full_width

[docs]    def Draw(self, dc, rect):
        """
        Actually draws all the chunks of text on a grid cell, one by one.

        :param `dc`: an instance of `wx.DC`;
        :param `rect`: an instance of `wx.Rect`, representing the cell rectangle.
        """

        new_rect = wx.Rect(*rect)

        text_width, text_height = dc.GetTextExtent(self.value)
        default_width = int(round(float(self.default_width)*text_width/256.0))
        indentation = int(256.0*default_width/float(self.default_width))

        maxH, full_width = self.Measure(dc)

        if self.indent_level:
            new_rect.SetLeft(new_rect.x + indentation)
        else:
            if self.horizontal_alignment == wx.ALIGN_LEFT:
                new_rect.SetLeft(new_rect.x + 3)
            elif self.horizontal_alignment == wx.ALIGN_RIGHT:
                new_rect.SetLeft(new_rect.x + (new_rect.width - full_width) - 1)
            else:
                space = int((new_rect.width - full_width)/2.0)
                new_rect.SetLeft(new_rect.x + space)
                new_rect.SetWidth(full_width+space)

        if self.vertical_alignment == wx.ALIGN_TOP:
            vspace = 0
        elif self.vertical_alignment == wx.ALIGN_BOTTOM:
            vspace = (new_rect.height - maxH - 1)
        else:
            vspace = int((new_rect.height - maxH)/2.0)

        start = new_rect.x
        y = new_rect.y

        for chunk, font, colour in self.attributes:
            dc.SetTextForeground(colour)
            dc.SetFont(font)
            width, height, descent, leading = dc.GetFullTextExtent(chunk, font)
            if font.escapement > 0:
                height = height*0.7

            ypos = y-height+maxH+vspace

            if font.escapement == 1:
                ypos = ypos - maxH + height

            dc.DrawText(chunk, start, ypos)
            start += width

[docs]class XLSBackground(object):
    """
    This is a class which holds information about the cell background, in terms
    of background colour and background pattern (hatching).
    """

[docs]    def __init__(self, book, xf_index):
        """
        Default class constructor.

        :param `book`: an instance of the `xlrd.Book` class;
        :param `xf_index`: an index into `xlrd.Book.xf_list`, which holds a
         reference to the `xlrd.sheet.Cell` class (the actual cell for `xlrd`).
        """

        XFClass = book.xf_list[xf_index]

        background = XFClass.background
        background_colour = book.colour_map[background.background_colour_index]
        pattern_colour = book.colour_map[background.pattern_colour_index]
        fill_pattern = background.fill_pattern

        self.CreateBackgroundColour(background_colour, pattern_colour, fill_pattern)

[docs]    def CreateBackgroundColour(self, background_colour, pattern_colour, fill_pattern):
        """
        Creates a suitable wxPython colour for the cell background starting from
        a `xlrd` tuple representing this colour.

        :param `background_colour`: a tuple representing the RGB components of the
         cell background colour. If `background_colour` is ``None``, use the
         default ``wx.SYS_COLOUR_WINDOW``;
        :param `pattern_colour`: a tuple representing the RGB components of the
         cell pattern colour;
        :param `fill_pattern`: the pattern to use to draw hatches on top of the
         background.
        """

        if background_colour is not None:
            background_colour = wx.Colour(*background_colour)
        else:
            background_colour = wx.SystemSettings.GetColour(wx.SYS_COLOUR_WINDOW)

        if pattern_colour is not None:
            pattern_colour = wx.Colour(*pattern_colour)

        self.background_brush = wx.Brush(background_colour)
        self.background_colour = background_colour

        self.fill_brush = None

        if fill_pattern <= 0:
            return

        r, g, b = pattern_colour

        fill_image = eval("_xls_background_%02d.GetImage()"%fill_pattern)
        fill_image.Replace(0, 0, 0, r, g, b)
        r, g, b = background_colour.Red(), background_colour.Green(), background_colour.Blue()
        fill_image.Replace(255, 255, 255, r, g, b)
        fill_bitmap = fill_image.ConvertToBitmap()

        self.fill_brush = wx.BrushFromBitmap(fill_bitmap)

[docs]    def CombineAttr(self, attr):
        """
        Combines the input attribute `attr` with the features of the L{XLSBackground} class.

        :param `attr`: an instance of `wx.grid.GridCellAttr`.
        """

        attr.SetBackgroundColour(self.background_colour)
        return attr

[docs]    def Draw(self, dc, rect):
        """
        Actually draws the cell background and pattern hatching on a grid cell.

        :param `dc`: an instance of `wx.DC`;
        :param `rect`: an instance of `wx.Rect`, representing the cell rectangle.
        """

        dc.SetClippingRect(rect)

        dc.SetBackgroundMode(wx.SOLID)
        dc.SetBrush(self.background_brush)
        dc.SetPen(wx.TRANSPARENT_PEN)
        dc.DrawRectangleRect(rect)

        if self.fill_brush:

            dc.SetBrush(self.fill_brush)
            dc.SetBackgroundMode(wx.TRANSPARENT)
            dc.DrawRectangleRect(rect)

        dc.DestroyClippingRegion()

[docs]class XLSBorder(object):
    """
    This is a class which holds information about a single cell border, in terms
    of its location (top, left, bottom, right, diagonal), its colour, width and
    shape.
    """

[docs]    def __init__(self, location, line_style, border_colour, default_colour, diagonals):
        """
        Default class constructor.

        :param `location`: the actual border location (top, left, bottom, right,
         diagonal);
        :param `line_style`: the line style used by Excel to draw this border;
        :param `border_colour`: the colour used by Excel to draw this border;
        :param `default_colour`: the "magic" colour used by Excel to draw non-custom
         border lines;
        :param `diagonals`: a tuple containing whether or not to draw the up and down
         diagonal borders.
        """

        self.draw_priority = 2

        if line_style == NO_LINE:

            if border_colour == (0, 0, 0):
                self.draw_priority = 0
                border_colour = wx.Colour(*default_colour)
            else:
                self.draw_priority = 1
                border_colour = wx.BLACK

            self.pen = wx.Pen(border_colour, 1, wx.SOLID)
            pen_style = THIN

        else:

            if border_colour == (0, 0, 0):
                border_colour = wx.Colour(*default_colour)
                self.draw_priority = 2
            elif border_colour is None:
                border_colour = wx.BLACK
                self.draw_priority = 2
            else:
                border_colour = wx.Colour(*border_colour)

            pen_width, pen_style = XF_PEN_STYLES[line_style]
            if pen_width > 2:
                self.draw_priority = 4
            elif pen_width > 1:
                self.draw_priority = 3

            self.pen = wx.Pen(border_colour, pen_width, pen_style)

        self.diagonals = diagonals
        self.location = location
        self.pen_style = pen_style
        self.line_style = line_style

[docs]    def Draw(self, dc, rect):
        """
        Actually draws the cell border.

        :param `dc`: an instance of `wx.DC`;
        :param `rect`: an instance of `wx.Rect`, representing the cell rectangle.
        """

        dc.SetBackgroundMode(wx.TRANSPARENT)
        dc.SetPen(self.pen)

        if self.location == DIAGONAL:
            self.DrawDiagonals(dc, rect)
        else:
            self.DrawBorder(dc, rect)

[docs]    def DrawDiagonals(self, dc, rect):
        """
        Actually draws the cell diagonal border.

        :param `dc`: an instance of `wx.DC`;
        :param `rect`: an instance of `wx.Rect`, representing the cell rectangle.
        """

        diag_up, diag_down = self.diagonals

        if diag_down:
            xstart, ystart = rect.GetTopLeft()
            xend, yend = rect.GetBottomRight()

            if self.line_style == DOUBLE:
                dc.DrawLine(xstart+2, ystart, xend, yend-2)
                dc.DrawLine(xstart, ystart+2, xend-2, yend)
            else:
                dc.DrawLine(xstart, ystart, xend, yend)

        if diag_up:

            xstart, ystart = rect.GetBottomLeft()
            xend, yend = rect.GetTopRight()

            if self.line_style == DOUBLE:
                dc.DrawLine(xstart, ystart-2, xend-2, yend)
                dc.DrawLine(xstart+2, ystart, xend, yend+2)
            else:
                dc.DrawLine(xstart, ystart, xend, yend)

[docs]    def DrawBorder(self, dc, rect):
        """
        Actually draws the cell border (one of left, right, bottom, top).

        :param `dc`: an instance of `wx.DC`;
        :param `rect`: an instance of `wx.Rect`, representing the cell rectangle.
        """

        pen_width = self.pen.GetWidth()
        location = self.location
        new_rect = wx.Rect(*rect)

        x, y, w, h = new_rect
        line_style = self.line_style

        shift = 0
        if pen_width == 2:
            shift = pen_width - 1
        if pen_width > 2:
            shift = pen_width - 2

        if location == BOTTOM:

            if self.draw_priority < 2:
                return

            if line_style == DOUBLE:
                dc.DrawLine(x, y+h-1, x+w, y+h-1)
                dc.DrawLine(x, y+h+1, x+w, y+h+1)
            else:
                dc.DrawLine(x+1, y+h,   x+w, y+h)

        elif location == TOP:

            if line_style == DOUBLE:
                dc.DrawLine(x, y-1, x+w, y-1)
                dc.DrawLine(x, y+1, x+w, y+1)
            else:
                dc.DrawLine(x+1, y+shift,   x+w, y+shift)

        elif location == LEFT:

            if line_style == DOUBLE:
                dc.DrawLine(x-1, y, x-1, y+h)
                dc.DrawLine(x+1, y, x+1, y+h)
            else:
                dc.DrawLine(x+shift,   y+1, x+shift,   y+h)

        elif location == RIGHT:

            if self.draw_priority < 2:
                return

            if line_style == DOUBLE:
                dc.DrawLine(x+w-1, y, x+w-1, y+h)
                dc.DrawLine(x+w+1, y, x+w+1, y+h)
            else:
                dc.DrawLine(x+w+1, y+1, x+w+1, y+h)

[docs]class XLSBorderFactory(object):
    """
    This is a factory class which holds information about all the borders in a
    cell. Its implementation and use is merely to simplify the handling of the
    different cell borders (left, top, bottom, right, diagonal).
    """

[docs]    def __init__(self, book, border, default_colour):
        """
        Default class constructor.

        :param `book`: an instance of the `xlrd.Book` class;
        :param `border`: an instance of `xlrd.formatting.XFBorder` class;
        :param `default_colour`: the "magic" colour used by Excel to draw non-custom
         border lines.
        """

        borders = {}
        diagonals = border.diag_up, border.diag_down

        for label, location in XF_BORDER_STYLES.items():
            line_style = getattr(border, "%s_line_style"%label)
            colour_index = getattr(border, "%s_colour_index"%label)
            border_colour = book.colour_map[colour_index]

            border_class = XLSBorder(location, line_style, border_colour, default_colour, diagonals)
            borders[location] = border_class

        self.draw_priority = sorted(borders.values(), key=attrgetter('draw_priority'))

[docs]    def Draw(self, dc, rect):
        """
        Actually draws all the cell borders based on their drawing priority.

        :param `dc`: an instance of `wx.DC`;
        :param `rect`: an instance of `wx.Rect`, representing the cell rectangle.

        :note: The drawing priority is assigned depending on if the border is a
         custom one or not. Customized borders are drawn last.
        """

        for border in self.draw_priority:
            border.Draw(dc, rect)

[docs]class XLSComment(object):
    """
    This is a class which holds information about the content of the "comment
    window" (aka note) in Excel.

    :note: If Mark Hammonds' `pywin32` package is not available, this class can
     not be used.
    """

[docs]    def __init__(self, comment):
        """
        Default class constructor.

        :param `comment`: the actual text contained in the Excel cell comment (note).
        """

        self.comment = comment

[docs]    def Draw(self, dc, rect):
        """
        Actually draws a small red triangle in the top-right corder of the cell
        to indicate that a comment is present.

        :param `dc`: an instance of `wx.DC`;
        :param `rect`: an instance of `wx.Rect`, representing the cell rectangle.
        """

        right = rect.GetTopRight()
        points = [wx.Point(right.x-5, right.y),
                  right,
                  wx.Point(right.x, right.y+5)]

        dc.SetBrush(wx.RED_BRUSH)
        dc.SetPen(wx.RED_PEN)
        dc.DrawPolygon(points)

[docs]class XLSCell(object):
    """
    This is a class which holds information about a single cell in L{XLSGrid}.
    It stores (via auxiliary classes), all details about cell background, text,
    font, colours and borders.
    """

[docs]    def __init__(self, book, cell, xf_index, xls_text, xls_comment, hyperlink, rich_text, default_width, default_colour):
        """
        Default class constructor.

        :param `book`: an instance of the `xlrd.Book` class;
        :param `cell`: an instance of `xlrd.sheet.Cell` class;
        :param `xf_index`: an index into `xlrd.Book.xf_list`, which holds a
         reference to the `xlrd.sheet.Cell` class (the actual cell for `xlrd`);
        :param `xls_text`: the actual WYSIWYG cell text, if available;
        :param `xls_comment`: the cell comment (note), if any;
        :param `hyperlink`: an instance of `xlrd.sheet.hyperlink`;
        :param `rich_text`: if this cell contains text in rich text format, L{XLSGrid}
         will do its best to render the text as rich text;
        :param `default_width`: this is the default width of the text in 1/256
         of the width of the zero character, using default Excel font (first FONT
         record in the Excel file);
        :param `default_colour`: the "magic" colour used by Excel to draw non-custom
         border lines.

        :note: If you are using version 0.7.1 or lower for `xlrd`, the *hyperlink*
         parameter will always be ``None`` as this feature is available only in
         `xlrd` 0.7.2 (SVN).

        :note: If you are using version 0.7.1 or lower for `xlrd`, the `rich_text`
         parameter will always be ``None`` as this feature is available only in
         `xlrd` 0.7.2 (SVN).

        :note: if Mark Hammonds' `pywin32` package is not available, the `xls_text`
         parameter will almost surely not be the WYSIWYG representation of the cell
         text.

        :note: If Mark Hammonds' `pywin32` package is not available, the `xls_comment`
         parameter will always be ``None``.
        """

        self.size = 1, 1

        self.comment = None
        self.hyperlink = None

        self.SetupCell(book, cell, xf_index, xls_text, xls_comment, hyperlink, rich_text, default_width, default_colour)

[docs]    def SetupCell(self, book, cell, xf_index, xls_text, xls_comment, hyperlink, rich_text, default_width, default_colour):
        """
        Actually sets up the L{XLSCell} class. This is an auxiliary method to
        avoid cluttering the L{__init__} method.

        :param `book`: an instance of the `xlrd.Book` class;
        :param `cell`: an instance of `xlrd.sheet.Cell` class;
        :param `xf_index`: an index into `xlrd.Book.xf_list`, which holds a
         reference to the `xlrd.sheet.Cell` class (the actual cell for `xlrd`);
        :param `xls_text`: the actual WYSIWYG cell text, if available;
        :param `xls_comment`: the cell comment (note), if any;
        :param `hyperlink`: an instance of `xlrd.sheet.hyperlink`;
        :param `rich_text`: if this cell contains text in rich text format, L{XLSGrid}
         will do its best to render the text as rich text;
        :param `default_width`: this is the default width of the text in 1/256
         of the width of the zero character, using default Excel font (first FONT
         record in the Excel file);
        :param `default_colour`: the "magic" colour used by Excel to draw non-custom
         border lines.

        :note: If you are using version 0.7.1 or lower for `xlrd`, the *hyperlink*
         parameter will always be ``None`` as this feature is available only in
         `xlrd` 0.7.2 (SVN).

        :note: If you are using version 0.7.1 or lower for `xlrd`, the `rich_text`
         parameter will always be ``None`` as this feature is available only in
         `xlrd` 0.7.2 (SVN).

        :note: if Mark Hammonds' `pywin32` package is not available, the `xls_text`
         parameter will almost surely not be the WYSIWYG representation of the cell
         text.

        :note: If Mark Hammonds' `pywin32` package is not available, the `xls_comment`
         parameter will always be ``None``.
        """

        cvalue = cell.value
        self.raw_value = cvalue

        if rich_text:
            self.text = XLSRichText(book, cell, xf_index, xls_text, hyperlink, rich_text, default_width)
        else:
            self.text = XLSText(book, cell, xf_index, xls_text, hyperlink, default_width)

        self.background = XLSBackground(book, xf_index)

        XFClass = book.xf_list[xf_index]
        border = XFClass.border

        self.borders = XLSBorderFactory(book, border, default_colour)

        if xls_comment:
            self.comment = XLSComment(xls_comment)

        self.attr = None

[docs]    def GetAttr(self):
        """
        Returns the attribute to use for this specific cell.

        :returns: an instance of `wx.grid.GridCellAttr`.
        """

        if self.attr is not None:
            self.attr.IncRef()
            return self.attr

        attr = gridlib.GridCellAttr()

        attr.SetRenderer(XLSRenderer(self))

        attr.SetSize(*self.size)
        attr.SetOverflow(True)
        self.attr = attr
        self.attr.IncRef()

        return self.attr

[docs]    def GetValue(self):
        """ Returns the actual WYSIWYG representation of the cell value. """

        return self.text.GetValue()

[docs]    def SetValue(self, value):
        """
        Sets the actual WYSIWYG representation of the cell value.

        :param `value`: the current text value to insert in the cell.

        :note: This method is currently unused as everything is handled inside the L{XLSText} class.

        :see: L{GetValue}
        """

        self.value = value

[docs]    def SetCellSize(self, rows, cols):
        """
        Sets the size of the cell.

        Specifying a value of more than 1 in `rows` or `cols` will make the cell
        at (`row`, `col`) span the block of the specified size, covering the other
        cells which would be normally shown in it. Passing 1 for both arguments
        resets the cell to normal appearance.

        :param `rows`: number of rows to be occupied by this cell, must be >= 1;
        :param `cols`: number of columns to be occupied by this cell, must be >= 1.
        """

        self.size = (rows, cols)

[docs]    def GetComment(self):
        """
        Returns the cell comment, if any.

        :returns: an instance of L{XLSComment}.

        :note: If Mark Hammonds' `pywin32` package is not available, this method
         always returns ``None``.
        """

        return self.comment

[docs]class XLSRenderer(gridlib.PyGridCellRenderer):
    """
    This class is responsible for actually drawing the cell in the grid.

    """

[docs]    def __init__(self, cell):
        """
        Default class constructor.

        :param `cell`: an instance of L{XLSCell}.
        """

        gridlib.PyGridCellRenderer.__init__(self)
        self.cell = cell

[docs]    def Draw(self, grid, attr, dc, rect, row, col, isSelected):
        """
        Draw the given cell on the provided `dc` inside the given rectangle using
        default or selected state corresponding to the `isSelected` value.

        :param `grid`: an instance of `wx.grid.Grid`;
        :param `attr`: an instance of `wx.grid.GridCellAttr`;
        :param `dc`: an instance of `wx.DC`;
        :param `rect`: an instance of `wx.Rect`, representing the cell rectangle;
        :param `row`: the row in which this cell lives;
        :param `col`: the column in which this cell lives;
        :param `isSelected`: ``True`` if the cell is selected, ``False`` otherwise.
        """

        # clear the background
        dc.SetBackgroundMode(wx.SOLID)

        cell = self.cell

        cell.background.Draw(dc, rect)

        if cell.borders:
            cell.borders.Draw(dc, rect)

        cell.text.Draw(dc, rect)

        if cell.comment:
            cell.comment.Draw(dc, rect)

        if isSelected:

            gdc = wx.GCDC(dc)

            sys_colour = wx.SystemSettings.GetColour(wx.SYS_COLOUR_HIGHLIGHT)
            brush_colour = wx.Colour(sys_colour.Red(), sys_colour.Green(), sys_colour.Blue(), 90)

            gdc.SetBrush(wx.Brush(brush_colour))
            gdc.SetPen(wx.TRANSPARENT_PEN)

            gdc.DrawRectangleRect(rect)

[docs]class XLSTable(gridlib.PyGridTableBase):
    """
    The almost abstract base class for grid tables.

    A grid table is responsible for storing the grid data and, indirectly, grid
    cell attributes. The data can be stored in the way most convenient for the
    application but has to be provided in string form to `wx.grid.Grid`.
    """

[docs]    def __init__(self, grid, cells, rows, cols):
        """
        Default class constructor.

        :param `grid`: an instance of `wx.grid.Grid`;
        :param `cells`: a Python dictionary. For every key `(row, col)`, the
         corresponding value is an instance of L{XLSCell};
        :param `rows`: the number of rows in the table;
        :param `cols`: the number of columns in the table.
        """

        # The base class must be initialized *first*
        gridlib.PyGridTableBase.__init__(self)

        self.cells = cells
        self.dimens = (rows, cols)

[docs]    def GetNumberCols(self):
        """ Returns the number of columns in the table. """

        return self.dimens[1]

[docs]    def GetNumberRows(self):
        """ Returns the number of rows in the table. """

        return self.dimens[0]

[docs]    def GetValue(self, row, col):
        """
        Returns the cell content for the specified row and column.

        :param `row`: the row in which this cell lives;
        :param `col`: the column in which this cell lives.
        """

        cell = self.cells[(row, col)]
        return cell.GetValue()

[docs]    def SetValue(self, row, col, value):
        """
        sets the cell content for the specified row and column.

        :param `row`: the row in which this cell lives;
        :param `col`: the column in which this cell lives;
        :param `value`: the new value to assign to the specified cell.
        """

        cell = self.cells[(row, col)]
        cell.SetValue(value)

[docs]    def GetAttr(self, row, col, kind):
        """
        Return the attribute for the given cell.

        :param `row`: the row in which this cell lives;
        :param `col`: the column in which this cell lives;
        :param `kind`: the kind of the attribute to return.
        """

        cell = self.cells[(row, col)]
        return cell.GetAttr()

[docs]    def GetRawValue(self, row, col):
        """
        Returns the "raw" value for the cell content.

        :param `row`: the row in which this cell lives;
        :param `col`: the column in which this cell lives.
        """

        cell = self.cells[(row, col)]
        return cell.raw_value

[docs]class XLSGrid(gridlib.Grid):
    """
    L{XLSGrid} is a class based on `wx.grid.Grid` that can be used to faithfully
    reproduce the appearance of a Microsoft Excel spreadsheet (one worksheet per
    every instance of L{XLSGrid}).

    L{XLSGrid} is a completely owner-drawn control, and it relies on the power of
    `wx.grid.PyGridTableBase` and `wx.grid.PyGridCellRenderer` to draw the cell
    content. For this reasons (and for some others, see the TODOs section), it will
    work efficiently only for relatively small Excel files.
    """

[docs]    def __init__(self, parent):
        """
        Default class constructor.

        :param `parent`: the grid parent window. Must not be ``None``.
        """

        gridlib.Grid.__init__(self, parent)

        self.SetMargins(0, 0)
        self.SetDefaultCellBackgroundColour(parent.GetBackgroundColour())
        self.SetDefaultCellOverflow(True)

        self.tip_window = None
        self.tip_shown = False

[docs]    def DestroyTip(self):
        """
        If a comment window or a tooltip over a hyperlink have been created, this
        method destroys them.
        """

        if self.tip_window:
            try:
                self.tip_window.GetTipWindow().Destroy()
            except wx.PyDeadObjectError:
                pass

            del self.tip_window
            self.tip_window = None

        if self.tip_shown:
            self.GetGridWindow().SetToolTipString("")
            self.GetGridWindow().SetCursor(wx.NullCursor)
            self.tip_shown = False

[docs]    def InstallGridHint(self):
        """
        Auxiliary method used to bind a ``wx.EVT_MOTION`` event to L{XLSGrid}.
        """

        self.prev_rowcol = [None, None]

        def OnMouseMotion(event):
            """
            Handles a the ``wx.EVT_MOTION`` events for L{XLSGrid}.

            :param `event`: a `wx.MouseEvent` event to be processed.
            """

            # evt.GetRow() and evt.GetCol() would be nice to have here,
            # but as this is a mouse event, not a grid event, they are not
            # available and we need to compute them by hand.
            position = event.GetPosition()
            x, y = self.CalcUnscrolledPosition(position)
            row = self.YToRow(y)
            col = self.XToCol(x)

            if [row, col] != self.prev_rowcol and row >= 0 and col >= 0:

                self.prev_rowcol[:] = [row, col]
                self.DestroyTip()
                cell = self.cells[(row, col)]
                rect = self.CellToRect(row, col)
                comment = cell.GetComment()

                window = self.GetGridWindow()
                if cell.text.IsHyperLink():
                    window.SetCursor(wx.StockCursor(wx.CURSOR_HAND))
                    window.SetToolTipString(cell.text.tooltip)
                    self.tip_shown = True
                    if not comment:
                        return

                if comment:
                    self.tip_window = TransientPopup(window, comment, wx.GetMousePosition())
                    event.Skip()

        self.GetGridWindow().Bind(wx.EVT_MOTION, OnMouseMotion)

[docs]    def PopulateGrid(self, book, sheet, display_texts, comments):
        """
        This is the main method of this class, and it is used to actually create
        the cells, size the columns and rows, merging cells, etc...

        :param `book`: an instance of the `xlrd.Book` class;
        :param `sheet`: an instance of the `xlrd.sheet` class;
        :param `display_texts`: if Mark Hammonds' `pywin32` package is available,
         this is the WYSIWYG cell content for all the cells in the Excel worksheet;
        :param `comments`: if Mark Hammonds' `pywin32` package is available,
         this is a nested list of cell comments (notes) for all the cells in the
         Excel worksheet.
        """

        self.BeginBatch()

        nrows = sheet.nrows
        ncols = sheet.ncols

        default_width, default_height = self.GetDefaultFontData(book)
        default_colour = self.GetGridLineColour()

        hyperlinks, rich_text_list = {}, {}
        if hasattr(sheet, "hyperlink_map"):
            # New in xlrd version 0.7.2 from SVN
            hyperlinks = sheet.hyperlink_map

        if hasattr(sheet, "rich_text_runlist_map"):
            # New in xlrd version 0.7.2 from SVN
            rich_text_list = sheet.rich_text_runlist_map

        self.cells = {}

        for i in xrange(nrows):

            for j in xrange(ncols):

                hyperlink = rich_text = None

                if (i, j) in hyperlinks:
                    hyperlink = hyperlinks[(i, j)]
                if (i, j) in rich_text_list:
                    rich_text = rich_text_list[(i, j)]

                self.FormatCell(book, sheet, i, j, display_texts, comments, hyperlink, rich_text, default_width, default_colour)

        self.table = XLSTable(self, self.cells, nrows, ncols)
        self.SetTable(self.table)

        row_height = sheet.default_row_height
        col_width = sheet.defcolwidth

        for i in xrange(nrows):
            if i in sheet.rowinfo_map:
                current = sheet.rowinfo_map[i].height
            else:
                current = sheet.default_row_height

            row_height = int(round(float(default_height)*current/256.0))
            self.SetRowSize(i, row_height)

        for j in xrange(ncols):
            if j in sheet.colinfo_map:
                current = sheet.colinfo_map[j].width
            else:
                current = sheet.defcolwidth

            col_width = int(round(float(default_width)*current/256.0))
            self.SetColSize(j, col_width)

        for merged in sheet.merged_cells:
            rlo, rhi, clo, chi = merged
            if rlo >= 0 and rlo < len(self.cells) and clo >= 0:
                self.cells[(rlo, clo)].SetCellSize(rhi-rlo, chi-clo)

        self.EnableEditing(False)
        self.EnableGridLines(False)
        self.EndBatch()
        self.ForceRefresh()
        self.InstallGridHint()

[docs]    def FormatCell(self, book, sheet, row, col, display_texts, comments, hyperlink, rich_text, default_width, default_colour):
        """
        Processes the creation of a single cell (an instance of L{XLSCell}).

        :param `book`: an instance of the `xlrd.Book` class;
        :param `sheet`: an instance of the `xlrd.sheet` class;
        :param `row`: the row in which this cell lives;
        :param `col`: the column in which this cell lives;
        :param `display_texts`: if Mark Hammonds' `pywin32` package is available,
         this is the WYSIWYG cell content for all the cells in the Excel worksheet;
        :param `comments`: if Mark Hammonds' `pywin32` package is available,
         this is a nested list of cell comments (notes) for all the cells in the
         Excel worksheet;
        :param `hyperlink`: if this cell contains a hyperlink, it will be displayed
         accordingly;
        :param `rich_text`: if this cell contains text in rich text format, L{XLSGrid}
         will do its best to render the text as rich text;
        :param `default_width`: this is the default width of the text in 1/256
         of the width of the zero character, using default Excel font (first FONT
         record in the Excel file);
        :param `default_colour`: the "magic" colour used by Excel to draw non-custom
         border lines.

        :note: If you are using version 0.7.1 or lower for `xlrd`, the *hyperlink*
         parameter will always be ``None`` as this feature is available only in
         `xlrd` 0.7.2 (SVN).

        :note: If you are using version 0.7.1 or lower for `xlrd`, the `rich_text`
         parameter will always be ``None`` as this feature is available only in
         `xlrd` 0.7.2 (SVN).

        :note: If Mark Hammonds' `pywin32` package is not available, the `display_texts`
         and `comments` parameter will be two empty nested lists.
        """

        cell = sheet.cell(row, col)

        xf_index = sheet.cell_xf_index(row, col)
        xls_text, xls_comment = display_texts[row][col], comments[row][col]

        gridCell = XLSCell(book, cell, xf_index, xls_text, xls_comment, hyperlink, rich_text, default_width, default_colour)

        self.cells[(row, col)] = gridCell

[docs]    def GetDefaultFontData(self, book):
        """
        Returns suitable width and height (in pixels) starting from Excel's own
        measurements (in characters, whatever that means).

        :param `book`: an instance of the `xlrd.Book` class.

        :returns: a `default_width` and `default_height` in pixels, based on the
         default width of the text in 1/256 of the width of the zero character,
         using default Excel font (first FONT record in the Excel file).
        """

        font = book.font_list[0]
        style, bold, underline = wx.FONTSTYLE_NORMAL, wx.NORMAL, False

        if font.italic:
            style = wx.FONTSTYLE_ITALIC
        if font.underline_type > 0:
            underline = True
        if font.weight > 600:
            bold = wx.BOLD

        family = XF_FONT_FAMILY[font.family]
        name = font.name
        size = int(font.height/20.0)

        dc = wx.ClientDC(self)
        font = wx.Font(size, family, style, bold, underline, name.encode())
        dc.SetFont(font)
        width, height, descent, leading = dc.GetFullTextExtent("0", font)

        return width, height + descent - leading

[docs]class TransientPopup(STT.SuperToolTip):
    """
    This is a sublass of L{SuperToolTip} and it is used to display a
    "comment-window" on the cells containing a comment (a note).

    :note: If Mark Hammonds' `pywin32` package is not available, this class is
     never invoked.
    """

[docs]    def __init__(self, grid_window, comment, position):
        """
        Default class constructor.

        :param `grid_window`: the actual window representing the grid;
        :param `comment`: an instance of L{XLSComment}, containing the
         text for this comment;
        :param `position`: the position at which we pop up the comment
         window (currently unused).
        """

        STT.SuperToolTip.__init__(self, grid_window)

        xls_comment = comment.comment

        split = xls_comment.split(":")
        header, rest = split[0], split[1:]
        rest = ":".join(rest)

        dc = wx.ClientDC(grid_window)
        rest = wordwrap(rest, 400, dc)

        self.SetHeader(header)
        self.SetMessage(rest)
        self.SetTarget(grid_window)
        self.SetDrawHeaderLine(True)

        self.SetStartDelay(100000)
        self.SetEndDelay(100000)
        self.ApplyStyle("Office 2007 Blue")

        self.SetDropShadow(True)
        self.DoShowNow()

        grid_window.SetFocus()

Navigation

  • index
  • modules |
  • Home |
  • Gallery |
  • Contents»
  • Module code »
  • xlsgrid


zoombar

  • modules |
  • Home |
  • Gallery |
  • Contents»
  • Module code »
  • zoombar

Source code for zoombar

"""
L{ZoomBar} is a class that *appoximatively* mimics the behaviour of the Mac Dock,
inside a `wx.Panel`.

Description
===========

L{ZoomBar} is a class that *appoximatively* mimics the behaviour of the Mac Dock,
inside a `wx.Panel`.

Once you hover mouse over the L{ZoomBar} correct button will bubble up, grow to
predefined size, so you can easily see the button you are about to click and
have larger area to click. Difference this makes is amazing.

The buttons are able to be zoomed from the bottom up (bottom fixed) as well
as to zoom from a central point. Also the container is able to move the
remaining buttons around the zoomed button.

Usage
=====

Usage example::

    import os
    import random
    import glob

    import wx
    import wx.lib.agw.zoombar as ZB

    class MyFrame(wx.Frame):

        def __init__(self, parent):

            wx.Frame.__init__(self, parent, -1, "ZoomBar Demo")

            panel = wx.Panel(self)

            bar = ZB.ZoomBar(panel, -1)

            standard = glob.glob(bitmapDir + "/*96.png")
            reflections = glob.glob(bitmapDir + "/*96Flip40.png")

            separatorImage = bitmapDir + "/separator.gif"
            separatorReflection = bitmapDir + "/separatorFlip.png"
            count = 0

            for std, ref in zip(standard, reflections):
                if random.randint(0, 1) == 1 and count > 0:
                    sep1 = wx.Bitmap(separatorImage, wx.BITMAP_TYPE_GIF)
                    sep2 = wx.Bitmap(separatorReflection, wx.BITMAP_TYPE_PNG)
                    bar.AddSeparator(sep1, sep2)

                bname = os.path.split(std)[1][0:-6]
                bar.AddButton(wx.Bitmap(std, wx.BITMAP_TYPE_PNG), wx.Bitmap(ref, wx.BITMAP_TYPE_PNG), bname)
                count += 1

            bar.ResetSize()

            sizer = wx.BoxSizer(wx.HORIZONTAL)
            sizer.Add(bar, 0, wx.ALIGN_CENTER_HORIZONTAL|wx.ALIGN_CENTER_VERTICAL|wx.ALL, 15)
            panel.SetSizer(sizer)

    # our normal wxApp-derived class, as usual

    app = wx.PySimpleApp()

    frame = MyFrame(None)
    app.SetTopWindow(frame)
    frame.Show()

    app.MainLoop()

Supported Platforms
===================

L{ZoomBar} has been tested on the following platforms:
  * Windows (Windows XP).

Window Styles
=============

`No particular window styles are available for this class.`

Events Processing
=================

This class processes the following events:

============================== ==================================================
Event Name                     Description
============================== ==================================================
``EVT_ZOOMBAR``                Process a ``wxEVT_ZOOMBAR`` event, when a L{ZoomBar} button is clicked.
============================== ==================================================

License And Version
===================

L{ZoomBar} is distributed under the wxPython license.

Latest Revision: Andrea Gavana @ 17 Aug 2011, 15.00 GMT

Version 0.1

"""

import wx
import sys

from wx.lib.embeddedimage import PyEmbeddedImage

zoombackgrey = PyEmbeddedImage(
    "iVBORw0KGgoAAAANSUhEUgAAAjkAAAAyCAYAAAC+s8qHAAAABHNCSVQICAgIfAhkiAAAIABJ"
    "REFUeJzVXUuv5Udxr/O4xrzEAtvIAnYevkDAJp8piRfeeIGSsEFiY96QbUyiWRgn9reIieTx"
    "YIGsAWQZCQkJz3h83/e8s0jquG7Nr17dfeY6JR2dc/rfXVXdXY9f9f88JpPpjEbTL37+s91u"
    "tyN+EBF8XenDZPWR1yXp65rktclkAtv5tbwueU+nU5cXv9dtuq81xpLP77VcS45ci+12+8h1"
    "OQ/Jg9u9uVk6ete5fTqdXtOb5cs2a66IJ1oDqYMe662Zlpnpg3hZdjqZTGg+n9MTTzxBn/nM"
    "Z+jJJ5+k+XxO0+mUttstrVYrWiwWdHV1RVdXV7RYLGi9Xu/HTqdTmk6ntNvtaLPZ0Hq9Nm3e"
    "WhO0FtoGJGl7IPrEnuQ1zy/1uvAckH7WONTH20ePpB8TfTIPtDba7lCfaLyUhWxQjtfXrHiI"
    "rk0mE5rNZjSbzfa2wv622+1ou93Ser3ePzabDW232zDGWjYuydK5lby91jHGi1l6TXVskjEy"
    "ylloblHOQetixXbrPfJBj6QcFPu5T7RPkR8zbbdbGLPRax672WxotVrRP/7TP7c5sUGTUSDn"
    "3//tl7urqyu6uLig5XK5X0jPKNiI5GT1swVyvDHS4HW7pgzIschL7IhQsLISteyfdRivTZLc"
    "m8w4rbeXBKv66Lmidi0XtVvj9BgLECIeco4jgjSyYwly+MEgZ7fb7UHOYrGg5XJJy+XyGsjh"
    "gC4TVg/I8drlOG3HEphG4Eb6aGTfFh0C5PB4ZJMRwJF9NEBhYnDBr+WaWTJ2ux3NZrNrMvT6"
    "WglFjplOp3ugw89EtAfGDHCyIEfPHcXZ1r1ApG0lsmUiDATk+lty9HvrYY3zrmViYRTj+H3r"
    "+nogx3tvtaF2S4bsK9dytVrR5eUlnZyc0Mcff0y/ev0/hhlPN8j55av/ujs7O6PNZnMtCLOj"
    "WECGX3vo2DImvUjWdU0oMGrHQABJtyN+klCwzxi3fN1jxN44tHaRbhXgogOcBYYs3hbwQPtk"
    "va6um0w+SMdKErb6a6fnPtPplObzOR0dHe0f8iSHfUo+mJdMitvt9tpDAzRrXaXe3py8gCtl"
    "yLnp99l1HAEos4TAgbYHD/hoPnKsB16sZItsEZ1KSH2jpIVADuvAwAaBHC9max11PLWuj6Rs"
    "DEJtUkcvzqN84wE/6z2iKKZF+aMS6zLgJAtgvLllChzZzrZ3dXVFp6endHJyQicnJ3T//n26"
    "d+8eLVfrbrDTBXLefOM/d3/6059ovV7Tcrmk1WpFy+Vy7yhWwGXSziSvS0PSwMMyQs0/2hwr"
    "WOv3MkhpA9fVheXkmiww4I3NgBLrupSH9sXig0AI6ucBvgzvihN7fTPgCvGJKiVpi7yGiLhC"
    "j6oguV7z+ZxmsxkdHR3tT3Jms9n+dhX7FfsYn+SwPNZT+p0ViCygU9k377qcn+4jwRnSD7VH"
    "ySKzzxZl7APddmKybol4IMk65ZH26yVnRAh4aIAib1XJBxHtTwAlyNlsNqnYWgEz2aKvh6x1"
    "RzJ1XLdIx3wL6PA1672VB5He8jnKW61gJwIhlnzZ5oFdq5CWMYptb7FY0Pn5OV1cXNDFxQVd"
    "Xl7S8fEx/fGPf6TVetNlLPOewUT0yFG5dBZZFSCggqoFq4LQ41C7fI9IVxseaR76swZR8I0S"
    "OGrPBLSs4Vs8eZx3nCjHRqAGyc4Ak+z7zNplEzdRfIvQk5mpzryAaSWJ9XpNs9ls7zNHR0d7"
    "kLNerx8BOZyAdJCWhQWaL9LVel0Fv9Y8dXsFlGQAjtQpQ9oPrCCNQInmIdcBgZ8IxKDxaG0t"
    "OVLfKP4xYNMPBuzV0xzNm9st2XrcSJCjbcrzb/YVBCgRX+tZ+5h8Rjz0e2tNMuvSA3Iq+lb8"
    "L+KvX3Oc4gMS/rwh3wmSuf7bLzy/e+vX/91sMM0g5+47d3Z3797dV5pcYfKHh/iWlf78h3Yc"
    "y1gyYEaO4fvSGshIo8oAEwt5e1RN+LJdGnsGHESE5imdwDNwj2dFH6u//HApWicNQLyElKl8"
    "dB+0T1GlJ6myZposIM63peS17Xa7b2eQw0BH3grWwY3BDzrJyaxdxY4zRYLs49ldxjcPRUhH"
    "2a7XOPsegRfdP2rz9NDkARIJ2PjBt64Y5LBdcQxnftbn9zRvq4+mkeBGy0QxBMn0QKMlwyvG"
    "de7xxss25HNeXNQ+L+NcdV2tgqsC2CL+1rwlwJGxTRZwI6kZ5HzwwQd0enp6rQLgikAfeVqf"
    "zyHCH4KVxkP0yeJHnwrPLI4HYqJg6zm0FSCR00W8LT4tpIOkFQyzOiG+klcmOUbAryq7ErA8"
    "/hk+1pqhygyNReCDT234wZ/JIaL96SgHAH4vx8vTVHS7KgLP1rfqrP6ZdubnvdfjqzZu2ZxH"
    "USDnPh648OxOghwPWFq3wdBYiweaQxSX0EkOAx15u1Of5mT20ro2AtggnpEvWmBekvUBZLS+"
    "OnZaryP9td0iv5Pzq/he5VtXls5RLpX6Zu1Ar9Vut7sGphl4yzFf+tKX6LnnnqM7d+7Q3377"
    "hd1/vfXrJkPqvl1F5Cc25DBM2oEsg5K8NCFD86jirJoyG4uuR8kbIXqLT1VfVDFk18oLtKiC"
    "0mMsfaPKowoKEZDLzCWSkbmeSbRZUCmvS+CiP+OmT3JkUYA+S+HpZ9lehqL96QU5oys6KS8D"
    "8CMw411DIInXRH5uS4MdvmZ93sdacyuhaPJuWaEiFZ20W+9le1T8VMmLhUiWBhAW6JTfTNPk"
    "AZ0od3njrXnoMVZe9da0tVCIgE7Wbyw9JD9pZ1a8knL5s4mt1ARy7r5zZ/f222/vq8vogapL"
    "OWF+Hy2058hV4NFC2U33wAgyXtQWyY8o0oGfrWQYASrpaBayzzhj9iRABykrOEXrrtfamodH"
    "yA4yn3Gy9EOBk/0FnZLKfvIUxqu8NWVPAnT/LFUSYtRnBPH+ZuTpRGPZDuoj5egx8tREJ1nu"
    "t9lsrumWOY3w5iPnzLKtvvoDoV4Cl7wR4LC+TajnYr3PxC7dJvcN2Z9VbMp9Q7FB80I5q5K7"
    "vHnqMdn4qHVrIct+tC49udYCiBaoGkG1XxT6P3r//ffp/Pz82vG5rgJQ5SkpE4h1f0TRqYBF"
    "oysLxNfSzUvefD0KCh5ZzoxkR+M9GVHQ9fbGcxgvIMjAWtXZChqyipZV36hTDd3P22+dlPRt"
    "Be/bObqvfGTBD9LJWzPUX76vAK5DEtIBrZNOlN4D8fYSn6VXZU8QZfxQyuJEqD+krn80MOKr"
    "ZXtxJ6KKrVj+afHIgjWLh5aj/bElXmTJ8inWK7sGrYR8IjPGu6Y/E6Z/3oB/UuOJJ56gL37x"
    "i/Tcc8/Ru+++Sy88/62mSTWBHERe8tGbUdkAPc4z4iqNBDraGCx5ljNknCTrSF5ykrwqPCXv"
    "HkPPyhrlpBFVwEl1TJYQwIlkjQg46HoE8h5nUfE4wM+niRBAiooADUQisGHxRXYgv2Y+gipg"
    "oKcfyjXIxxDosdZP6x4VWSNsN1oDK+eOkmfN1yoMNC+Lv7VW3pjtdkuLxaJpXmULvvvOnd3H"
    "H38MfwocneZYR1OaMujbqrgyZG2Kl4y9zfQq3R6jywSCauKyrh+i+siCNXZO5DzoRMKT1TqH"
    "KsCJ7CFLuq83V+1D8lTUskepq37fslaenSNfik4qNQ/rlAXJbKUqn9HJ+BBUjREZm63EyV7/"
    "i/Sz5FZ5ZtokSeAg41QlOWfktFAFVBxCdpZ6i9RMjs5SGeT84Q9/2H+ryrol5R3tMsnAaS2I"
    "VXVUKt6bIs9ZtdNYycNyLu146Lp8Ru06Eekj6uzcouDn8csAW0t+y363Ok7Gniv8IiCjq0r5"
    "sPbIs6ceXT3yjvRbeVTARZVa97ylX2ac9f4Qp5gcZxkoy8/eyA+yWx9MZh5oDQ956trCO5tP"
    "srHJyjXa5zIFWYWsvOkdHEg5Lbet9NpEOjBVCz6+LTWfz/d2x7dL+cG3rL7whS/QrVu36L33"
    "3qNvv/B82SCGnEXqCeqFtsjaHM2zokfPOFQZW5v5uBKJJCv5tcpuTdatQU3bBAJ+0fiMXWne"
    "iHpAchTIWqpRVCDosVGy0fyi42yrPQs8rAKlupYIpEcgo3JMP6IqzBRa1jhrby3K2rg1Lnov"
    "AY9+aCDdGlMRRXPP7LtFlg1V9In8RcpBflEB6T3kyWlZO8Rbv5bXJaFvTUe2k4mPciyD7c1m"
    "QxcXF+U5lUDO3Xfu7I6Pj83/O0F/52AteBR4vY2qJMMqRQaUka/7ZoNspLcHsKpVsPXooWoy"
    "zYzzgkmFX0v/iE8WmEXydT9+cKXNtqRPSzUoz/CPKBsgkb5VG/J8zOtT4V/Z20y/ajzLUibu"
    "jCANTL3TuNEJvLLulk6tcr33vfyiviPn0xLfe6kaf1tlSBpp8yWQ8/vf/54uLi7Mb1VVkXgF"
    "LFSvHYoqR/TVxOIF0AzAieSPNHqm7DF7FLyzemVtpvdWSnRCMdrJUUXJcvihK2xkN5lEheRk"
    "9Ou5pVIBTyMD9EiKbAqd9uh29JrXNvovP48X0it7aqILU/ltF3Qbe6Sv6v5RnGuh6O5C5jTS"
    "8xX54WyvMGvVvep3vac5FlX3JDoUkLem5C9x61tWR0dH9PnPf55u3bpF9+7dK3/LqgRyWo4A"
    "W8Z7hAyn9QQhokwyr8ruWT+repbXWxJEzzFxhrfULeqX4XdIXb2A0htgoiCeGZu1Nyug/3+k"
    "yM97+VYJ7VM1rnkxEl3vPUHJ6ITGZOJJdK0nHkkemp/mHcWXTOxozVGV06JRIP5QcVCSB9a8"
    "05doPbIFuNxbvmV1cnJSmkMa5Nx9587u7OzskW9U6W9WWYaEnLwVpUqKnPGmq8EWY9Zzkq8r"
    "JzmjqRrsosCePYHKykNtvckhE0wr87ACpAdQd7vdtV8NRxSdBkZ6oWveWkbrmglaTFmdW0Cn"
    "R9WTx6yfjUw6LfaM4oe+nomXFh+rwBpFVRBQXW/PLzOFo7d+GVm9hE55D01ecYV8WrZXTtZ1"
    "XBjhS2mQc+/ePTo7O9sHXPS1cQ8pZxTOOo0+5n0c1CsnAile200DNY+yibxCmdMMC3D0yNZ8"
    "K/bVY4tyrLxtIfWybh2gOUS6VfxQ88nw8PZJ++6h/LcCBlrIi3MoUOs9bpFnPXv8omvoh1uJ"
    "sM21AtssjbAHLzboNiSrRQdUpLSCIouQDbWcOI2gzBysX9aWxcpkMnnkdpW8ZTWfz699y4pv"
    "Wb3//vv0/Le+mZ7ckP+uYoUtanXqyCBHJjjEJzLKXvCh5+jxjJBwb3KXc0a6ZU/ZdDLjNeRr"
    "qCLP6iifM3PJEtoH2ZbdZz33ah8OXNYaah6W7qhf5ZpHls1Gc7bmJd9HVO3fStlCRLfzHL09"
    "sa7pdssPM7w8PTOJUfoq/5eWfq95IVvV/ax1HQFskB5eP9nfWhsvJkR9on1+nMV51V8t8mxI"
    "87SKG0++Bwr59Ww2o81mQ8fHx2m9Uyc5v7n7zu78/Hz/9+jWN6q8kxwmdHSVSewRVQKlDiaW"
    "DlJXC6Uj/llCelR5sJ4t8pE+KGD07oMMklpepEOVWtfCOz3K9O3RW9qU/sNGlmdVcD1gxWvP"
    "2jcKTJ7MiH9EI5NDpnA6hNyIrPh5CB2sxO75K9pHr79lF71F4iHIK+yiogH5b6YoG0nZOHSI"
    "ta/GgApV9kJTCuS89957dHZ2du32FLpNhX4UUCqlFbUAkfd+hKNHPDJgJhovnzNyMrxa9LHW"
    "GAUkBLoySalFt4z8kZQFqa2EAHFWJ7lH1u9OyCCqx3Ef2f+QNHoNs3yqJz4t/SrxRe9BxEsD"
    "1UxBmG2vgHRNOq7L21by9sGh/6dpBGWKVp1PUH7hZ+9zcEg2EcFCxdOtup5ePtQncb02blE2"
    "b2X4RLes+L+sjo6O6HOf+xzdunWLPvjgg/QtqyE/Bhg5WIToJZ+ouhoBOg6ZQCv9I12qelbn"
    "l9G5BbxkAJUmnbCt0wrP1iwQ07PfKBlZVWkrCJVy9GvJG8nUfB5XBdlit6P3ZgRVk4tMIHrP"
    "dF+vHb2vgh2vn7XGUeLzTnb0Z3MycT2K9zdJvetN5AMX9Jr53zRQ7Fn7lvyV9f0otk6nU5rP"
    "57Rer+nBgwcpfUOQ8+5v7u74FGe1WoX/OO6hYv3aM47q8VT1eq+RtSLZKDC0JkkZdK1TAD3O"
    "O0XLnnYhnlb/qM3a+6oeGRkZ/TKyW3hZPmDZhlf1oz3w9B1VgWmZ0anE4yR0UuI9JGXW5nHN"
    "8VAAoeKj+lTA+82c1ph6iIQfFUPZ/lk5EcCsFqAtOtwUtcaTyolkD4Ug53e/+93+BwDlrxxr"
    "YJP9TE5EXrUsr+u2m9roFqDioVXUZ0TFkaEswIn6IIeuGvSoYBCdDMp+N5W8ssWAtJGo8j4E"
    "IR16AhUDc+86kn8oyoBTTvpen0q71U+vbdTeKk/2z/6fFd9KYIoKiajIyvhe1j+jflKetmO9"
    "rvyofOaUbVoXL/J99ttq0TytebXGst6iv7XvZDIJfxhQ3rL67Gc/S9/4xjfoz3/+M33rm38T"
    "TtQFOednpzv5mRtJ2UW1grEeZ50oyL4Wb0TRsVd2TKWfdTJVkeudbll9kTNZ/byHlmEl0EiO"
    "7oueo7VBshF/i09FV/TekqvXIts/S9a8rTY9z0NRBFg9e9LXPT6Somp89KO6Di1kjc8AF2+M"
    "bIuAfTR/zcPyL28uli9pnhnKrk0lsU8m8TeMvJzk2TGKPeia7KNfZ6j3QAFRRX6Pz/TEVHnL"
    "6q9//Wso3wU5b775Jj148IDW6zUtFgtaLpe0Wq1ouVxe+1FA/Q0riyIjaQl6ljPq99XNi4I1"
    "GtMy1gsg1cRtrUvWGSyjs3SwdPWc3FoHby3QdaSv7od+UwYFHd3H+j0aK1hF84z2Sl7XVZ6u"
    "PKOAaemLZHltiE8kz5J1aGrxcY9HxWYlRQDVixsZ/bJyPR7R3ukTDi0f2arm5/n/iL0akdQt"
    "IOadlFV1zvrTCOo5UR2lSwsPbU/yJEfHQ3m6c3R0RM888wydnp7SD3/wijvR8HYVCmzyvzpa"
    "qXJrJOsU6HRpxDGe1iF7HBrx8/T2+meu9RotckTvtC572tZyjJ7pEwUjL9hmgIjm22NHlv5o"
    "HT0AY/XnR8YGs341ok9Fl6xuhwRRkU1EPivb5X4g37dIxsmWUwxPd0tfJFMmHP0tqyr4y8wl"
    "e4dAUnafMjEa6ay/Oezx4v3OgNxRxYDeO6RnNDaK17qfV1hV5GoeGpBbIOf4+JheeeUVkz+R"
    "A3Iuzs92UslRn7nhiXlt1vVRBuHp3opGW/p484mqQo+XVYVW9bSSerUSGZlsM4Ev46xadqtt"
    "ZX0hA2CzwBglTKv6rs7L62/ZFlMv0NEyWviN8t9MUsz6rm7TiQiRJc/SF+nVGie17AjoaP0y"
    "5NnRaLLsNooJWi/LLjPrUI2ZHmXiYCYuZfr1FBqZ+JOx5V4yQc4bb7xBH3300f721Gq1uvbQ"
    "t6sQiuTX3rUMWQkrSuwW9QYBz6B7AIWXXHqoUsFIXbxrke7Z4BcZf2VvPZ0y61oFA9UxHvER"
    "LROqxPRv6Fhys36VAXi9viJ5HJpaiq8WvTLJxQI6aF8zYy0waQH6qNr2bCejC7KLKO7zIwMM"
    "s0VPlTwA7YHPSB+kv/V7OdzGj8rcK76N+ltFUJYyY7KgR8dmXjP9VyK6XX4Y+ZlnnqHz83P6"
    "0Q9/YC6MCXK8r4NXK+UqeUktquJbZEX82RC1E6AEmlmf7JpkQUmGRiQrRL1JJQK9lflba1xZ"
    "72z/7KmLfG8FUZRYNIjK/odQJhi3JocqWEY8Iv0t3laiQP177dybF1oDL05a4yNZFvix+Htx"
    "p+I/ElDrbxURXd9DmcQzdikTbwYQRnpG/ZAOWX2tvbX2AuUAKVO/lrrL9fSKMq+9QqNyiiS9"
    "t63FotwXBHgk0OFbVicnJ/T973/flAFBzuXF+bUVQE5pGYnlwBl02gMQLLCSqVYtnTLGEBml"
    "1c9D92gc61ShqqO0VPTZeWcosyZVwFIhXV30BhSvYtH99OsIsKEKkMdZAVf3ixJNJEvrWZGX"
    "1cGSY7VpHSIZFR2iGIL2OjOf0QkH6VSxZWuNUDK2/jC2RW41MVrXLH0QZXONnH81LkQ6VXXO"
    "gjT0+tBU8QE55pAEQc7rr79ODx8+3N+akt+qkr+Vwz8MGCFyD7h4FVgEeCJCvKzxHkDyXltV"
    "jk5MWedAzhQ5tUdZuRkZnOyywC9Dep3QJ+urfEc6TWtgy/C12pA8LxlrYIRsD5FVqfJrC9RW"
    "wbMGHB5lgUS2SBhFVZDgJZlsnByRqFrjJeKhAXQ2nlkyDuVblh4tQEe+b1lLa75ewTNqPbQ/"
    "o+tW/xYaobfOAfKBblnxac7l5SX9+Ec/hMq7X5NCG6AXzQM3clwV3bVSr+NUUfJoQmCrh08U"
    "cGV7BASrVbsnT+rYQoeyKSu5S7ktlLEpfqCfY9AOj4B2Bhxk5+CBsKx9tMjQ1z2wh+R7SbWH"
    "LDDYMl63VdczavcKOQRSrDiPblfxdZ1wKv9rlQFTEaFcpPlY/DWfDPipAh2veNfrbhXGkX5V"
    "ysb23rzTWphaD21j0u7m8zl95StfobOzM/re974HeT8Ccq4uL3ZEGMRINJyZSJTgRgQKj6pV"
    "Qzb4o6AQ0Qhg1GLsFtgZRVWdDgkQJVX1qvTv6WsBhQhUZQBKtLbW6al8Hc2tZf96g/RNj6/w"
    "a41pFkCLkk+rP8l4qIGjdWooTwpbYuBoOqTMLKipgp9Mrmwp3qICtaLXTeylpJHAjgiAnNde"
    "e40ePnxIm82GFosFXV1d7b9JJb9RJW9V8T/WImWZ0AnQoSkTFFoTVrVqsZC5xwcBFK9fRXYG"
    "8Fn9PSdE87EcGLVnqnG9fvIUIzunaM0ycrOgAO2dlSgsHeUpD6qsZT8k36piPX0y16z+Hp/q"
    "OnpVMeLTKsebj7fGVltLO5IdyWst/iwbQmTZXSWmVPWz9IpizKEpe9Kk36N5WTEarW0kz1p/"
    "T18Un0YX5NXYwQ/9QWxuQ9+yevrpp+ny8pJ+8uMfPaI8vF3lVXpSIEL7mUlYFPGxAlklgGWM"
    "pYWspIWerf4Wz5aAnV2bbHKQFB37erz0GI8snqhfRAgwZMZngk1mLzQhW5cghm8VaBnytgA6"
    "BbD2Luuj0Xxb/UfbRPSL0tY4NDci/xZND3nzQes+IlF4cTV7smC1eWAXran1v00o6Xi5wpKZ"
    "aY/iV6V/ljK2pcla5yhfZWKw1qmHPBuJYl2FqvlO9tX/lybb+DUDnPl8Ts8++yxdXFzQd7/7"
    "3Uf4XQM5i6vL3Xa7pclkAk9nsoFEO2cGSWYMKQOqsoCn6giVDRphKNVx2kEqwDPaH8lftlun"
    "S9m9RGO9xFwB1VaCsBwcHdVneFrz8q5FNmolzopNoQDjjaskZS8ge/yj/fOSQIZaiq4sT/l+"
    "RN+Iopiq+Vv+pNsqYAGRFQ8qtiD5RO1oP6197t1/xIuoDlyjWCl/DwutFyrAKvmgx/51LOzh"
    "McoHNVVz4zWQc/v2bTo9PaXlcknL5ZIWi8UjPwAov10VJRJvolHAzwTBVsoCoFagkkXmmTEj"
    "qhIkq0q6gqtUV1ZAZL7oObNHWbmZvlK2JzMz9yp4lv3RBzgtgIBsSvtcZFeZNcrMtdVeW20c"
    "zRPp3kOW704m+C8adB+kZ5YyYCkLWvX47L7qRI1+M0d/IDSK5TqOfJpI7iuTBVwtQBQV4PK1"
    "3ofMfmb8xdqDyKasfRm5T1leVozSpzryttXTTz9Ni8WCfvqTH1+b3FwzlovpOSdaCIR8uV0n"
    "NW6X15hQfyS7B2miOSCSBliVd2gnzlZvLYTWOMszu6den1EkeWZ4V3So6qr9gl/L93ySqpOB"
    "Pr5Ff4ark1IPaV69PpfVzZKj/a9i81nftU4pPD0tPhaIjvj2+olOVAgI82sZn+V1vVbb7Xaf"
    "XCTQljL0/xlW/qz5JsmzMysGorzG/TwAjPhY7zVlAW2FqnmwcpLl6ZXhxQBa2xvbGo/fbrc0"
    "n89pu93Ss88+Sx9++CF95zvfucZrb5mr5WJnAZcInVqOJMmrMC1UGaHlEQkxu3H6FMOi1kQT"
    "VXyosrL4VPjqfqgiQdWL1OlQAQsFe2v9H1dVGK1nZr2tig7xyvD4NFHW3kaOR76B7Ne67iUj"
    "T56Ui2RkY6MnR+qrqXedkV4twCQTF3VfT8ZNAqBIthdfK3aE7COrX0bHrM2MjCMRVtByH1cM"
    "24Oc27dv0/Hx8f7W1NXV1f4HAPnHAOWtKr5dZZHlROjHAxG4shLZiAq1usBZYIPmYfWN5GV1"
    "8mRWqlfdVgFGkU5aL/Rejh9JmYocJS35nE1UaP4ICFpgUVYq8oOc0l9QINF6t6xhzxxHUgtf"
    "D9BEsloAZrbA0Lp5/bPzPjQAQL6g5aLqWtqf9f9DlpzM3JCfeg85Lpqv1450t5J51fYsWd6c"
    "qjEqAjroMMHrn51T5ZQowxPFSGlr8ltWq9WKfvbTn+yV3t+uQp+QR4rzQ4MVDuToJECPl4sQ"
    "LbBsZ134Q9EyCaD+HlVQN88tSt6ecyFd9drypmUJrbHWVa+dXPcINHoBQI/N6C0NFq2Dduhs"
    "EsiAKtSG+ugKqyUJen0scM8y5/P/dcntdkuz2YwmkwltNptr/yWk/1dIjpf7y34i+3iyvXXp"
    "IeQ71YoZtfcAlJ45ZhOn/PIG34a0+uo/c7T2J3rm19ofPZ2j+MnvrW+7sK3xQ9prlBM8uZoO"
    "AaytEzjrpCUDLKzY4YElL39GIL4K8L3chOasx2RjX2VMZINsZxro8C0tvm311a9+lT788EN6"
    "+eWX92PnRETr1XJ3+/ZtiKylscrfykEGrJ8tkOMhSW+imlCS7kGdmb7e9YyxRDyjcUwtht3r"
    "DN417311/VAwaFlPvR8ZvfW1bCLNJHFt/xrMzWazvbNOp1PabDb7fdN/p8KJxALfshCx5mbN"
    "s5pM0Fpo38wGPQ94VyplNNbSE/EfBYKiteXrvNdovH7O8szGEkkREEH/3oWAAAAEp0lEQVRf"
    "7eVxEtxI+0RxH8mN6BDgO9IhsxeWfpVCKcqlTNZv0lVju6evpbPnm6hPVhcPuKHrVbueE33y"
    "rSq+TXV1dUWLxYIuLy9psVjQYrGg5XL5CLjRE7JAjH4dXR9BkUNlQU42+GcMxKPKplUNCc21"
    "h0flfWZeXnBHfVEy8vTJgCRLbgVwonFWgNKVG1cqs9ls/56rcQ/kWPNleWit0Hro117CtwCM"
    "Bm/6um7zSMv3gA9a66jvIShKiKiv3AdvvNU36ofea4qSvdxX9JslTPoUR/7W0wigc8i9yxQD"
    "Xjta40phpdfHypVRPo3m4+mf7YPsw5oTj6sCnkyhI+2Rv2E1m83oqaeeouPjY/r5z366+7u/"
    "/4fJXE+GA+pyubwGeFar1bWg6W2C5zTepqEJZcFItBgjAZTkq197yd1KHig5RFVlNKaV0JpH"
    "DhAFggrAawWIVQBjJV10281L4HKsNSbjuOywm81m76wS5HACkb86rqs6vW+Zk5wKqKskykz1"
    "GpFe8xFAB1HPWMRHvvfsOQIqXlsEYizwFJEXu9lG+TXfTpXrJ09wJOCx+FttPTQazEp+nr9E"
    "+6cJxSAEZCIQWvlNu0gn73rWp3v9ycIFkq+8Lr9GPpvN6Gtf+xrdv3+fXnrpJSIimvOtKjbK"
    "xWJBZ2dndHZ2RpeXl/u/dZAfNPYMNYM2ZRsnA2sCSE60SYcANIgqiaLV6SqJRY+proNnWJEu"
    "1vWeiiFDLfzQew/EWHKrCdvzG04Ws9lsD3Tk13Y5YcgP/ltH11JeJthV1x/5rMdfz9Vr89Z1"
    "ZNFzSMqua9QPgRmvHb22xkeJ02pnntPplNbr9SO3rPQvduvfU8vKPTShPOIVK5U448XMbDzn"
    "1x6AQXnUmkcU37I5KwN0dFyIdLP4WLInk8m1E8JIx/mrr75K9+/fp5OTE3rw4AEdHx/TxcXF"
    "/ttUqBpEAS569l5nJjkySI2o9ioG4AUXz4ksvpYRj6ieM/JRW8Z5UILyAnSkd1Uva/0jnpZs"
    "z3EtAGDtnf65cn7NDs0JQwIcDWJ0oZApFrIgNAMCI9/I+L/Ht0KVSjbD3xsj110nuhYb9cbz"
    "nnl8W5JsZCt6vP4BQCYNciTwQXKs95b/jwCoEbDOghqr3dt7r13riA4OPD/K7mFGj4yOUZHj"
    "Uc8pj9fOvvHlL3+ZHj58SP/yi5/v5svlkv7yl7/QRx99tAc4y+XykUDpLWZm0SsbkFmAStCN"
    "+HgG3VLhozbU3pLELYqA0iGATva6Nf8Kn8patACXnj4ZkJMF7xLgyJMc69srzAMl4eyJiDe3"
    "EUnFoyrYyYDfSM6h5yRlVJIlX4vGegBIt3uAB1HWTtGD++kTHQS6szHfSu6H3MMIwCIdDuFP"
    "Uo/oA8feay2/FzzyfvfmFO/wBPXzZMo4OZlM6Otf/zo9fPiQXnzxRZr/9re/pbfeeotOT0/3"
    "t6ZQgOw5ZqouRuviRcgSnSSMoh4QMFoXKW8k79ZA0xOQRgezx5HgKoTW00pk1a/k3gSxjXjJ"
    "YXRw/LRQa2LLjIv8rgXY9xJK8jrRZm3007qnEd1EPDnkej5OMCmpchoeEcfP9XpNRET/Ax6j"
    "kIck2UJrAAAAAElFTkSuQmCC")

# ----------------------------------------------------------------------------
# ZoomBar events and binding for handling them
# ----------------------------------------------------------------------------

wxEVT_ZOOMBAR = wx.NewEventType()
EVT_ZOOMBAR = wx.PyEventBinder(wxEVT_ZOOMBAR, 1)
""" Process a `wxEVT_ZOOMBAR` event, when a L{ZoomBar} button is clicked. """

# ----------------------------------------------------------------------------

[docs]def MakeDisabledBitmap(original):
    """
    Creates a disabled-looking bitmap starting from the input one.

    :param `original`: an instance of `wx.Bitmap` to be greyed-out.
    """

    img = original.ConvertToImage()
    return wx.BitmapFromImage(img.ConvertToGreyscale())

# ----------------------------------------------------------------------------

[docs]class ZoomBarImage(object):
    """
    This simple class holds information about a L{ZoomBar} button, such as normal
    bitmaps, disabled bitmap, button label, etc...
    """

[docs]    def __init__(self, parent, bitmap, disabledBmp=wx.NullBitmap, label=""):
        """
        Default class constructor.

        :param `parent`: the main L{ZoomBar} window;
        :param `bitmap`: the button bitmap, an instance of `wx.Bitmap`;
        :param `disabledBmp`: the button bitmap when the button is in a disabled
         state;
        :param `label`: the button label.
        """

        self._parent = parent
        self._bitmap = bitmap

        if not disabledBmp.IsOk():
            disabledBmp = MakeDisabledBitmap(bitmap)

        self._disabledBmp = disabledBmp
        self._label = label

        self._height = 36
        self._width = 36

        self._oldnx = 0
        self._oldLeft = 0
        self._oldTop = 0
        self._oldWidth = 0
        self._oldBottom = 0
        self._oldHeight = 0
        self._vCenter = 0
        self._hCenter = 0
        self._oldInc = -sys.maxint
        self._isSeparator = False
        self._enabled = True

        # Larger number gives a greater zoom effect
        self._zoomFactor = 3

        # Whether this is a reflection or not
        self._isAReflection = False

        self._cachedBitmaps = {}
        self._cachedDisabledBitmaps = {}

[docs]    def SetZoomFactor(self, zoom):
        """
        Sets the zoom factor for the button. Larger number gives a greater zoom
        effect.

        :param `zoom`: a floating point number, greater than or equal to 1.0.
        """

        self._zoomFactor = zoom

[docs]    def SetCenterZoom(self, center=True):
        """
        Sets to zoom from the center.

        :param `center`: if ``True`` button zooms upwards.
        """

        self._centerZoom = center

[docs]    def ZoomImage(self, nxcoord):
        """
        Zooms the button bitmap depending on the mouse x position.

        :param `nxcoord`: the mouse x position relative to the button center.
        """

        if nxcoord < self._vCenter:
            inc = int(((nxcoord - self._oldLeft)*10.0)/(self._oldWidth/2.0)) + 1
        else:
            inc = int(((self._oldLeft + self._oldWidth - nxcoord)*10.0)/(self._oldWidth/2)) + 1

        if self._isSeparator:
            return False

        if abs(inc - self._oldInc) < 2:
            return False

        self._oldInc = inc

        if not self._isAReflection:
            # original button
            inc = inc*self._zoomFactor
            self._width = self._oldWidth + inc
            self._left = self._vCenter - self._width/2
            self._height = self._oldHeight + inc
            self._top = self._oldBottom - self._height

        else:
            # the reflection
            self._height = self._oldHeight + inc
            self._width = self._oldWidth + inc
            self._top = self._top + self._height

        self._oldnx = nxcoord
        return True

[docs]    def SetSize(self, width, height):
        """
        Sets the button size.

        :param `width`: the button width;
        :param `height`: the button height.
        """

        self._width = width
        self._height = height

[docs]    def GetPosition(self):
        """ Returns the button position. """

        return wx.Point(self._left, self._top)

[docs]    def GetSize(self):
        """ Returns the button size. """

        return wx.Size(self._width, self._height)

[docs]    def GetBitmap(self):
        """
        Returns the button bitmap, which may be a scaled up version of the original
        bitmap is the button is being zoomed.
        """

        if self._isAReflection:
            return self._paintBitmap

        if self._enabled:
            return self._cachedBitmaps[self._width]

        return self._cachedDisabledBitmaps[self._width]

[docs]    def SetupProps(self, buttonSize):
        """
        Set up the button position and size.

        :param `buttonSize`: the button original size (not zoomed), in pixels.
        """

        self._width = self._oldWidth = buttonSize
        self._height = self._oldHeight = buttonSize

        self._oldLeft = self._left
        self._oldTop = self._top
        self._vCenter = self._oldLeft + int(self._oldWidth/2.0)
        self._hCenter = self._oldTop + int(self._oldHeight/2.0)
        self._oldBottom = self._top + self._height

        if self._isAReflection:
            img = self._bitmap.ConvertToImage()
            img = img.Scale(self._width, self._height, wx.IMAGE_QUALITY_HIGH)
            self._paintBitmap = img.ConvertToBitmap()

[docs]    def GetLabel(self):
        """ Returns the button label (if any). """

        return self._label

[docs]    def SetLabel(self, label):
        """
        Sets the button label.

        :param `label`: a string specifying the button label. May be an empty string
         for no label.
        """

        self._label = label

[docs]    def IsZoomed(self):
        """ Returns ``True`` if the button is zoomed, ``False`` otherwise. """

        return self._width/float(self._oldWidth) >= 1.25

[docs]    def LoopScales(self, size):
        """
        Caches the bitmaps at various zoom levels to avoid calling every time
        `image.Scale` on the button bitmap.

        :param `size`: the original button size, in pixels.
        """

        if self._isAReflection:
            return

        for scale in range(size-10*self._zoomFactor, size+15*self._zoomFactor, self._zoomFactor):
            if scale in self._cachedBitmaps or scale <= 0:
                continue

            img = self._bitmap.ConvertToImage()
            img = img.Scale(scale, scale, wx.IMAGE_QUALITY_HIGH)
            bmp = img.ConvertToBitmap()
            self._cachedBitmaps[scale] = bmp

            img = self._disabledBmp.ConvertToImage()
            img = img.Scale(scale, scale, wx.IMAGE_QUALITY_HIGH)
            bmp = img.ConvertToBitmap()
            self._cachedDisabledBitmaps[scale] = bmp

[docs]    def Enable(self, enable=True):
        """
        Enables/disables a button.

        :param `enable`: ``True`` to enable a button, ``False`` to disable it.
        """

        self._enabled = enable

[docs]    def IsEnabled(self):
        """ Returns ``True`` if the button is enabled, ``False`` otherwise. """

        return self._enabled

[docs]class ImageBar(object):
    """ This class holds the background button bar on which the buttons float. """

[docs]    def __init__(self, bitmap=None):
        """
        Default class constructor.

        :param `bitmap`: if not ``None``, the bitmap to use as a background button
         bar on which the buttons float. It should be an instance of `wx.Image`.
        """

        if bitmap and bitmap.IsOk():
            self._bitmap = bitmap
            self._hasBitmap = bitmap
        else:
            self._bitmap = zoombackgrey.GetImage()
            self._hasBitmap = None

        self._left = 23
        self._top = 53
        self._startColour = wx.Colour(97, 97, 97)
        self._endColour = wx.Colour(97, 97, 97)

[docs]    def GetPosition(self):
        """ Returns the position of L{ImageBar}, as a `wx.Point`. """

        return wx.Point(self._left, self._top)

[docs]    def GetSize(self):
        """ Returns the size of L{ImageBar}, as a `wx.Size`. """

        return wx.Size(self._bitmap.GetWidth(), self._bitmap.GetHeight())

[docs]    def GetBitmap(self):
        """ Returns the background button bar on which the buttons float. """

        return self._bitmap

[docs]    def SetPosition(self, xpos, ypos):
        """
        Sets the position of L{ImageBar}.

        :param `xpos`: the `x` position of the bar;
        :param `ypos`: the `y` position of the bar.
        """

        self._left = xpos
        self._top = ypos

[docs]    def SetSize(self, xSize, ySize):
        """
        Sets the size of L{ImageBar}.

        :param `xSize`: the width of the bar, in pixels;
        :param `ySize`: the height of the bar, in pixels.
        """

        self.SetBarColour(self._startColour, xSize, ySize)

[docs]    def SetBarColour(self, colour, xSize=None, ySize=None):
        """
        Sets the background button bar colour.

        :param `colour`: an instance of `wx.Colour`;
        :param `xSize`: if not ``None``, the new L{ImageBar} width;
        :param `ySize`: if not ``None``, the new L{ImageBar} height.
        """

        if not isinstance(colour, wx.Colour):
            colour = wx.NamedColour(colour)

        if self._hasBitmap:
            bitmap = self._hasBitmap
        else:
            bitmap = zoombackgrey.GetImage()

        if xSize is not None:
            self._size = wx.Size(xSize, ySize)

        bitmap.Rescale(self._size.width, self._size.height/2)

        r1, g1, b1 = self._startColour.Red(), self._startColour.Green(), self._startColour.Blue()
        r2, g2, b2 = colour.Red(), colour.Green(), colour.Blue()

        fr = (r1 > 0 and [float(r2)/r1] or [0])[0]
        fg = (g1 > 0 and [float(g2)/g1] or [0])[0]
        fb = (b1 > 0 and [float(b2)/b1] or [0])[0]

        bitmap = bitmap.AdjustChannels(fr, fg, fb, 1)
        self._bitmap = bitmap.ConvertToBitmap()
        self._endColour = colour

[docs]    def GetBarColour(self):
        """ Returns the background button bar colour. """

        return self._endColour

[docs]class ZoomBarEvent(wx.PyCommandEvent):
    """ Event sent from the L{ZoomBar} when a button is activated. """

[docs]    def __init__(self, eventType, eventId=1):
        """
        Default class constructor.

        :param `eventType`: the event type;
        :param `eventId`: the event identifier.
        """

        wx.PyCommandEvent.__init__(self, eventType, eventId)
        self._eventType = eventType

[docs]    def SetSelection(self, selection):
        """
        Sets the index of the selected button.

        :param `selection`: an integer indicating the current selected button.
        """

        self._selection = selection

[docs]    def GetSelection(self):
        """ Returns the index of the selected button. """

        return self._selection

[docs]    def GetLabel(self):
        """ Returns the text label of the selected button. """

        return self._label

[docs]    def SetLabel(self, label):
        """
        Sets the text label of the selected button.

        :param `label`: the text label of the selected button.
        """

        self._label = label

[docs]class ZoomBar(wx.PyControl):
    """
    L{ZoomBar} is a class that *appoximatively* mimics the behaviour of the Mac Dock,
    inside a `wx.Panel`.

    This is the main class implementation.
    """

[docs]    def __init__(self, parent, id=wx.ID_ANY, pos=wx.DefaultPosition, size=wx.DefaultSize,
                 name="ZoomBar"):
        """
        Default class constructor.

        :param `parent`: the L{ZoomBar} parent. Must not be ``None``;
        :param `id`: window identifier. A value of -1 indicates a default value;
        :param `pos`: the control position. A value of (-1, -1) indicates a default position,
         chosen by either the windowing system or wxPython, depending on platform;
        :param `size`: the control size. A value of (-1, -1) indicates a default size,
         chosen by either the windowing system or wxPython, depending on platform;
        :param `name`: the window name.
        """

        wx.PyControl.__init__(self, parent, id, pos, size, style=wx.BORDER_THEME)

        # Zoom from the center. If True button zooms upwards.
        self._centerZoom = False
        # Whether you want reflections or not
        self._showReflections = True
        # Allows us to nudge a reflection closer to original
        self._nudgeReflection = 0
        # Extension of the reflection. BMP or PNG etc.
        # Initial size of the buttons
        self._buttonSize = 48
        # Show labels on hovering
        self._showLabels = True
        # used internally
        self._noResize = False
        self._buttons = []
        self._reflectionButtons = []

        self._imgBar = ImageBar()
        self._previousHit = -1
        self._currentHit = -1

        wx.CallLater(200, self.OnLeaveWindow, None)

        self.Bind(wx.EVT_PAINT, self.OnPaint)
        self.Bind(wx.EVT_ERASE_BACKGROUND, self.OnEraseBackground)
        self.Bind(wx.EVT_SIZE, self.OnSize)
        self.Bind(wx.EVT_MOTION, self.OnMotion)
        self.Bind(wx.EVT_LEAVE_WINDOW, self.OnLeaveWindow)
        self.Bind(wx.EVT_LEFT_DOWN, self.OnLeftDown)
        self.Bind(wx.EVT_LEFT_UP, self.OnLeftUp)

        if wx.Platform == "__WXMSW__":
            self.Bind(wx.EVT_LEFT_DCLICK, self.OnLeftDown)

        self.SetBackgroundStyle(wx.BG_STYLE_CUSTOM)

[docs]    def DoGetBestSize(self):
        """
        Gets the size which best suits the window: for a control, it would be the
        minimal size which doesn't truncate the control, for a panel - the same size
        as it would have after a call to `Fit()`.

        :note: Overridden from `wx.PyControl`.
        """

        xSize = self._buttonSize*len(self._buttons) + len(self._buttons) + self._buttonSize
        ySize = self._buttonSize*2
        if self._showLabels:
            dc = wx.ClientDC(self)
            dummy, yextent = dc.GetTextExtent("Ajgt")
            ySize += yextent

        return wx.Size(xSize+50, ySize+20)

    # reposition the buttons

[docs]    def Reposition(self, toButton):
        """
        Repositions all the buttons inside the L{ZoomBar}.

        :param `toButton`: the button currently hovered by the mouse (and hence zoomed).
        """

        nLeft = toButton._left
        nRight = toButton._left + toButton._width + 1
        nButton = self._buttons.index(toButton)

        # do any buttons on the right
        for n in xrange(nButton + 1, len(self._buttons)):
            oButton = self._buttons[n]
            oButton._left = nRight

            if self._showReflections:
                oButtonR = self._reflectionButtons[n]
                oButtonR._left = nRight

            nRight = nRight + oButton._width + 1

        # Reset
        nLeft = toButton._left

        # now to the left
        if nButton > 0:
            # only for 2nd and more
            for n in xrange(nButton-1, -1, -1):
                oButton = self._buttons[n]
                oButton._left = nLeft - (oButton._width + 1)
                if self._showReflections:
                    oButtonR = self._reflectionButtons[n]
                    oButtonR._left = oButton._left

                nLeft = oButton._left

    # method to add required buttons

[docs]    def AddButton(self, normalBmp, reflectionBmp=wx.NullBitmap, label="", disabledBmp=wx.NullBitmap,
                  disabledReflectionBmp=wx.NullBitmap):
        """
        Adds a button to L{ZoomBar}.

        :param `normalBmp`: the button main bitmap, an instance of `wx.Bitmap`;
        :param `reflectionBmp`: a bitmap representing a reflection of the main bitmap,
         an instance of `wx.Bitmap`;
        :param `label`: the button label;
        :param `disabledBmp`: the button main bitmap when the button is in a disabled
         state, an instance of `wx.Bitmap`;
        :param `disabledReflectionBmp`: a bitmap representing a reflection of the main bitmap,
         when the button is in a disabled state, an instance of `wx.Bitmap`.
        """

        button = ZoomBarImage(self, normalBmp, disabledBmp, label)

        button.SetSize(self._buttonSize, self._buttonSize)
        button._centerZoom = (self._showReflections and [False] or [self._centerZoom])[0]
        self._buttons.append(button)

        self.InitialReposition()

        if self._showReflections and reflectionBmp.IsOk():

            rbutton = ZoomBarImage(self, reflectionBmp, disabledReflectionBmp)
            rbutton.SetSize(self._buttonSize, self._buttonSize)
            rbutton._centerzoom = False
            rbutton._isAReflection = True
            self._reflectionButtons.append(rbutton)

        return button

[docs]    def AddSeparator(self, normalBmp, reflectionBmp=wx.NullBitmap):
        """
        Adds a separator to L{ZoomBar}.

        :param `normalBmp`: the separator main bitmap, an instance of `wx.Bitmap`;
        :param `reflectionBmp`: a bitmap representing a reflection of the main bitmap,
         an instance of `wx.Bitmap`.
        """

        button = self.AddButton(normalBmp, reflectionBmp)
        button._isSeparator = True

[docs]    def SetZoomFactor(self, zoom):
        """
        Sets the zoom factor for all the buttons. Larger number gives a greater zoom
        effect.

        :param `zoom`: a floating point number, greater than or equal to 1.0.
        """

        if zoom < 1:
            raise Exception("The zoom factor must be greater or equal to 1")

        for button in self._buttons:
            button._zoomFactor = zoom

        self._zoomFactor = zoom
        self.DoLayout()

[docs]    def GetZoomFactor(self):
        """ Returns the current zoom factor. """

        return self._zoomFactor

[docs]    def SetCenterZoom(self, center=True):
        """
        Sets to zoom from the center.

        :param `center`: if ``True`` button zooms upwards.
        """

        self._centerZoom = center

        for button in self._buttons:
            button._centerZoom = (self._showReflections and [False] or [self._centerZoom])[0]

        self.DoLayout()

[docs]    def GetCenterZoom(self):
        """ Returns ``True`` if buttons zoom upwards. """

        return self._centerZoom

[docs]    def SetShowReflections(self, show):
        """
        Sets whether to show reflections or not.

        :param `show`: ``True`` to show reflections, ``False`` otherwise.
        """

        self._showReflections = show
        self.DoLayout()

[docs]    def GetShowReflections(self):
        """ Returns ``True`` if reflections bitmap are currently shown. """

        return self._showReflections

[docs]    def SetShowLabels(self, show):
        """
        Sets whether to show button labels or not.

        :param `show`: ``True`` to show button labels, ``False`` otherwise.
        """

        self._showLabels = show
        self.DoLayout()

[docs]    def GetShowLabels(self):
        """ Returns ``True`` if button labels are currently shown. """

        return self._showLabels

[docs]    def SetBarColour(self, colour):
        """
        Sets the background button bar colour.

        :param `colour`: an instance of `wx.Colour`;
        """

        self._imgBar.SetBarColour(colour)
        self.Refresh()

[docs]    def GetBarColour(self):
        """ Returns the background button bar colour. """

        return self._imgBar.GetBarColour()

[docs]    def SetButtonSize(self, size):
        """
        Sets the original button size.

        :param `size`: the new (not-zoomed) button size, in pixels.
        """

        self._buttonSize = size
        self.DoLayout()

[docs]    def GetButtonSize(self):
        """ Returns the original (not zoomed) button size, in pixels. """

        return self._buttonSize

[docs]    def EnableButton(self, index, enable=True):
        """
        Enables/disables the button at position `index`.

        :param `index`: the index of the button to enable/disable;
        :param `enable`: ``True`` to enable the button, ``False`` to disable it.
        """

        if index < 0 or index >= len(self._buttons):
            return False

        self._buttons[index].Enable(enable)
        self.Refresh()

        return True

[docs]    def IsButtonEnabled(self, index):
        """
        Returns ``True`` if the button at position `index` is enabled, ``False``
        otherwise.

        :param `index`: the index of the button to check.
        """

        if index < 0 or index >= len(self._buttons):
            return False

        return self._buttons[index].IsEnabled()

[docs]    def DoLayout(self):
        """ Common method to re-layout L{ZoomBar}. """

        self.ResetSize()
        self.GetContainingSizer().Layout()
        self.Refresh()

[docs]    def ResetSize(self):
        """
        Resets all the button sizes and positions, recalculating the optimal L{ZoomBar}
        size.
        """

        xSize = self._buttonSize*len(self._buttons) + len(self._buttons) + self._buttonSize
        ySize = self._buttonSize*2

        self._imgBar.SetSize(xSize+self._buttonSize, ySize)

        for button in self._buttons:
            button.LoopScales(self._buttonSize)

        if self._showLabels:
            dc = wx.ClientDC(self)
            dummy, yextent = dc.GetTextExtent("Ajgt")
            ySize += yextent

        if self._showReflections:
            ySize += self._buttonSize/2
        if self._centerZoom:
            ySize += self._buttonSize

        size = wx.Size(xSize+50, ySize)
        self.SetInitialSize(size)
        self.SnapToBottom(size)

    # Sets up the initial buttons and sizes them from the center

[docs]    def InitialReposition(self):
        """
        Sets up the initial buttons and sizes them from the center.
        """

        # repositions the button centrally
        # odd buttons one is central - even, half by half

        if not self._buttons:
            return

        size = self.GetSize()
        oButton = self._buttons[0]
        totalWidth = oButton._width*len(self._buttons) + len(self._buttons)
        center = size.GetWidth()/2
        nbCenter = totalWidth/2
        nLeft = center - nbCenter

        if self._showReflections:
            nTop = self._imgBar._top - (oButton._height/2)
        else:
            if self._centerZoom:
                nTop = size.height/2 - oButton._height/2
            else:
                nTop = size.height - oButton._height - 5

        for oButton in self._buttons:
            oButton._left = nLeft
            oButton._top = nTop
            oButton.SetupProps(self._buttonSize)
            nLeft = nLeft + oButton._width+1

        # And the reflection if any
        if self._showReflections:
            nLeft = center - nbCenter
            nudge = self._nudgeReflection
            for oButton in self._reflectionButtons:
                oButton._left = nLeft
                oButton._top = (nTop + oButton._height - 2) - nudge
                oButton.SetupProps(self._buttonSize)
                nLeft = nLeft + oButton._width + 1

[docs]    def OnLeaveWindow(self, event):
        """
        Handles the ``wx.EVT_LEAVE_WINDOW`` event for L{ZoomBar}.

        :param `event`: a `wx.MouseEvent` event to be processed.
        """

        if self.GetScreenRect().Contains(wx.GetMousePosition()):
            return

        for button in self._buttons:
            button.SetSize(self._buttonSize, self._buttonSize)

        self.InitialReposition()
        self.Refresh()

[docs]    def OnSize(self, event):
        """
        Handles the ``wx.EVT_SIZE`` event for L{ZoomBar}.

        :param `event`: a `wx.SizeEvent` event to be processed.
        """

        self.SnapToBottom(event.GetSize())
        self.Refresh()
        event.Skip()

[docs]    def SnapToBottom(self, size):
        """
        Snaps the background button bar bitmap and all the buttons to the bottom
        of L{ZoomBar}.

        :param `size`: the current L{ZoomBar} size.
        """

        backgroundSize = self._imgBar.GetSize()
        xPos = (size.width - backgroundSize.width)/2
        yPos = (size.height - backgroundSize.height)

        self._imgBar.SetPosition(xPos, yPos)
        self.InitialReposition()

[docs]    def OnPaint(self, event):
        """
        Handles the ``wx.EVT_PAINT`` event for L{ZoomBar}.

        :param `event`: a `wx.PaintEvent` event to be processed.
        """

        dc = wx.AutoBufferedPaintDC(self)

        dc.SetBackground(wx.WHITE_BRUSH)
        dc.Clear()

        background = self._imgBar.GetBitmap()
        pos = self._imgBar.GetPosition()

        dc.DrawBitmap(background, pos.x, pos.y, True)

        if not self._buttons:
            return

        self.DrawButtons(dc)
        self.DrawReflections(dc)
        self.DrawLabels(dc)

[docs]    def DrawButtons(self, dc):
        """
        Draws all the main button bitmaps on the L{ZoomBar} client window.

        :param `dc`: an instance of `wx.DC`.
        """

        for button in self._buttons:
            pos = button.GetPosition()
            bitmap = button.GetBitmap()

            dc.DrawBitmap(bitmap, pos.x, pos.y, True)

[docs]    def DrawReflections(self, dc):
        """
        Draws all the reflection button bitmaps on the L{ZoomBar} client window.

        :param `dc`: an instance of `wx.DC`.
        """

        if self._showReflections:
            for button in self._reflectionButtons:
                pos = button.GetPosition()
                bitmap = button.GetBitmap()

                dc.DrawBitmap(bitmap, pos.x, pos.y, True)

[docs]    def DrawLabels(self, dc):
        """
        Draws all the button labels on the L{ZoomBar} client window.

        :param `dc`: an instance of `wx.DC`.
        """

        if not self._showLabels:
            return

        dc.SetBrush(wx.WHITE_BRUSH)
        dc.SetPen(wx.BLACK_PEN)

        for button in self._buttons:
            if not button.IsZoomed():
                continue
            label = button.GetLabel()
            if not label:
                continue

            textWidth, textHeight = dc.GetTextExtent(label)
            buttonPos = button.GetPosition()
            buttonSize = button.GetSize()
            xpos = buttonPos.x + (buttonSize.width - textWidth)/2
            ypos = buttonPos.y - textHeight - 2

            dc.DrawRectangle(xpos-2, ypos-1, textWidth+4, textHeight+2)
            dc.DrawText(label, xpos, ypos)

[docs]    def OnEraseBackground(self, event):
        """
        Handles the ``wx.EVT_ERASE_BACKGROUND`` event for L{ZoomBar}.

        :param `event`: a `wx.EraseEvent` event to be processed.

        :note: This method is intentionally empty to avoid flicker.
        """

        pass

[docs]    def OnMotion(self, event):
        """
        Handles the ``wx.EVT_MOTION`` event for L{ZoomBar}.

        :param `event`: a `wx.MouseEvent` event to be processed.
        """

        pos = event.GetPosition()
        hit = self.HitTest(pos)

        if hit >= 0:
            button = self._buttons[hit]
            if not button.ZoomImage(pos.x):
                return

            self.Reposition(button)
        else:

            if self._previousHit < 0:
                return

            for button in self._buttons:
                button.SetSize(self._buttonSize, self._buttonSize)

            self.InitialReposition()

        self._previousHit = hit
        self.Refresh()

[docs]    def OnLeftDown(self, event):
        """
        Handles the ``wx.EVT_LEFT_DOWN`` and ``wx.EVT_LEFT_DCLICK`` events for L{ZoomBar}.

        :param `event`: a `wx.MouseEvent` event to be processed.
        """

        self._currentHit = self.HitTest(event.GetPosition())

[docs]    def OnLeftUp(self, event):
        """
        Handles the ``wx.EVT_LEFT_UP`` event for L{ZoomBar}.

        :param `event`: a `wx.MouseEvent` event to be processed.
        """

        if self.HitTest(event.GetPosition()) != self._currentHit:
            return

        if not self.IsButtonEnabled(self._currentHit):
            return

        eventOut = ZoomBarEvent(wxEVT_ZOOMBAR, self.GetId())
        eventOut.SetSelection(self._currentHit)
        eventOut.SetLabel(self._buttons[self._currentHit].GetLabel())
        eventOut.SetEventObject(self)
        self.GetEventHandler().ProcessEvent(eventOut)

[docs]    def HitTest(self, pos):
        """
        HitTest method for L{ZoomBar}.

        :param `pos`: the current mouse position.

        :return: an index representing the button on which the mouse is hovering,
         or ``wx.NOT_FOUND`` if no button has been hit.
        """

        for index, button in enumerate(self._buttons):
            buttonPos = button.GetPosition()
            if pos.x >= buttonPos.x and pos.x <= buttonPos.x + button._width:
                return index

        return wx.NOT_FOUND

Navigation

  • index
  • modules |
  • Home |
  • Gallery |
  • Contents»
  • Module code »
  • zoombar


aui.aui_switcherdialog

  • modules |
  • Home |
  • Gallery |
  • Contents»
  • Module code »
  • aui.aui_switcherdialog

Source code for aui.aui_switcherdialog

"""
Description
===========

The idea of `SwitcherDialog` is to make it easier to implement keyboard
navigation in AUI and other applications that have multiple panes and
tabs.

A key combination with a modifier (such as ``Ctrl`` + ``Tab``) shows the
dialog, and the user holds down the modifier whilst navigating with
``Tab`` and arrow keys before releasing the modifier to dismiss the dialog
and activate the selected pane.

The switcher dialog is a multi-column menu with no scrolling, implemented
by the `MultiColumnListCtrl` class. You can have headings for your items
for logical grouping, and you can force a column break if you need to.

The modifier used for invoking and dismissing the dialog can be customised,
as can the colours, number of rows, and the key used for cycling through
the items. So you can use different keys on different platforms if
required (especially since ``Ctrl`` + ``Tab`` is reserved on some platforms).

Items are shown as names and optional 16x16 images.

Base Functionalities
====================

To use the dialog, you set up the items in a `SwitcherItems` object,
before passing this to the `SwitcherDialog` instance.

Call L{SwitcherItems.AddItem} and optionally L{SwitcherItems.AddGroup} to add items and headings. These
functions take a label (to be displayed to the user), an identifying name,
an integer id, and a bitmap. The name and id are purely for application-defined
identification. You may also set a description to be displayed when each
item is selected; and you can set a window pointer for convenience when
activating the desired window after the dialog returns.

Have created the dialog, you call `ShowModal()`, and if the return value is
``wx.ID_OK``, retrieve the selection from the dialog and activate the pane.

The sample code below shows a generic method of finding panes and notebook
tabs within the current L{AuiManager}, and using the pane name or notebook
tab position to display the pane.

The only other code to add is a menu item with the desired accelerator,
whose modifier matches the one you pass to L{SwitcherDialog.SetModifierKey}
(the default being ``wx.WXK_CONTROL``).

Usage
=====

Menu item::

    if wx.Platform == "__WXMAC__":
        switcherAccel = "Alt+Tab"
    elif wx.Platform == "__WXGTK__":
        switcherAccel = "Ctrl+/"
    else:
        switcherAccel = "Ctrl+Tab"

    view_menu.Append(ID_SwitchPane, _("S&witch Window...") + "\t" + switcherAccel)

Event handler::

    def OnSwitchPane(self, event):

        items = SwitcherItems()
        items.SetRowCount(12)

        # Add the main windows and toolbars, in two separate columns
        # We'll use the item 'id' to store the notebook selection, or -1 if not a page

        for k in xrange(2):
            if k == 0:
                items.AddGroup(_("Main Windows"), "mainwindows")
            else:
                items.AddGroup(_("Toolbars"), "toolbars").BreakColumn()

            for pane in self._mgr.GetAllPanes():
                name = pane.name
                caption = pane.caption

                toolbar = isinstance(info.window, wx.ToolBar) or isinstance(info.window, aui.AuiToolBar)
                if caption and (toolBar  and k == 1) or (not toolBar and k == 0):
                    items.AddItem(caption, name, -1).SetWindow(pane.window)

        # Now add the wxAuiNotebook pages

        items.AddGroup(_("Notebook Pages"), "pages").BreakColumn()

        for pane in self._mgr.GetAllPanes():
            nb = pane.window
            if isinstance(nb, aui.AuiNotebook):
                for j in xrange(nb.GetPageCount()):

                    name = nb.GetPageText(j)
                    win = nb.GetPage(j)

                    items.AddItem(name, name, j, nb.GetPageBitmap(j)).SetWindow(win)

        # Select the focused window

        idx = items.GetIndexForFocus()
        if idx != wx.NOT_FOUND:
            items.SetSelection(idx)

        if wx.Platform == "__WXMAC__":
            items.SetBackgroundColour(wx.WHITE)

        # Show the switcher dialog

        dlg = SwitcherDialog(items, wx.GetApp().GetTopWindow())

        # In GTK+ we can't use Ctrl+Tab; we use Ctrl+/ instead and tell the switcher
        # to treat / in the same was as tab (i.e. cycle through the names)

        if wx.Platform == "__WXGTK__":
            dlg.SetExtraNavigationKey(wxT('/'))

        if wx.Platform == "__WXMAC__":
            dlg.SetBackgroundColour(wx.WHITE)
            dlg.SetModifierKey(wx.WXK_ALT)

        ans = dlg.ShowModal()

        if ans == wx.ID_OK and dlg.GetSelection() != -1:
            item = items.GetItem(dlg.GetSelection())

            if item.GetId() == -1:
                info = self._mgr.GetPane(item.GetName())
                info.Show()
                self._mgr.Update()
                info.window.SetFocus()

            else:
                nb = item.GetWindow().GetParent()
                win = item.GetWindow();
                if isinstance(nb, aui.AuiNotebook):
                    nb.SetSelection(item.GetId())
                    win.SetFocus()

"""

import wx

import auibook
from aui_utilities import FindFocusDescendant
from aui_constants import SWITCHER_TEXT_MARGIN_X, SWITCHER_TEXT_MARGIN_Y

# Define a translation function
_ = wx.GetTranslation

[docs]class SwitcherItem(object):
    """ An object containing information about one item. """

[docs]    def __init__(self, item=None):
        """ Default class constructor. """

        self._id = 0
        self._isGroup = False
        self._breakColumn = False
        self._rowPos = 0
        self._colPos = 0
        self._window = None
        self._description = ""

        self._textColour = wx.NullColour
        self._bitmap = wx.NullBitmap
        self._font = wx.NullFont

        if item:
            self.Copy(item)

[docs]    def Copy(self, item):
        """
        Copy operator between 2 L{SwitcherItem} instances.

        :param `item`: another instance of L{SwitcherItem}.
        """

        self._id = item._id
        self._name = item._name
        self._title = item._title
        self._isGroup = item._isGroup
        self._breakColumn = item._breakColumn
        self._rect = item._rect
        self._font = item._font
        self._textColour = item._textColour
        self._bitmap = item._bitmap
        self._description = item._description
        self._rowPos = item._rowPos
        self._colPos = item._colPos
        self._window = item._window

[docs]    def SetTitle(self, title):

        self._title = title
        return self

[docs]    def GetTitle(self):

        return self._title

[docs]    def SetName(self, name):

        self._name = name
        return self

[docs]    def GetName(self):

        return self._name

[docs]    def SetDescription(self, descr):

        self._description = descr
        return self

[docs]    def GetDescription(self):

        return self._description

[docs]    def SetId(self, id):

        self._id = id
        return self

[docs]    def GetId(self):

        return self._id

[docs]    def SetIsGroup(self, isGroup):

        self._isGroup = isGroup
        return self

[docs]    def GetIsGroup(self):

        return self._isGroup

[docs]    def BreakColumn(self, breakCol=True):

        self._breakColumn = breakCol
        return self

[docs]    def GetBreakColumn(self):

        return self._breakColumn

[docs]    def SetRect(self, rect):

        self._rect = rect
        return self

[docs]    def GetRect(self):

        return self._rect

[docs]    def SetTextColour(self, colour):

        self._textColour = colour
        return self

[docs]    def GetTextColour(self):

        return self._textColour

[docs]    def SetFont(self, font):

        self._font = font
        return self

[docs]    def GetFont(self):

        return self._font

[docs]    def SetBitmap(self, bitmap):

        self._bitmap = bitmap
        return self

[docs]    def GetBitmap(self):

        return self._bitmap

[docs]    def SetRowPos(self, pos):

        self._rowPos = pos
        return self

[docs]    def GetRowPos(self):

        return self._rowPos

[docs]    def SetColPos(self, pos):

        self._colPos = pos
        return self

[docs]    def GetColPos(self):

        return self._colPos

[docs]    def SetWindow(self, win):

        self._window = win
        return self

[docs]    def GetWindow(self):

        return self._window

[docs]class SwitcherItems(object):
    """ An object containing switcher items. """

[docs]    def __init__(self, items=None):
        """ Default class constructor. """

        self._selection = -1
        self._rowCount = 10
        self._columnCount = 0

        self._backgroundColour = wx.NullColour
        self._textColour = wx.NullColour
        self._selectionColour = wx.NullColour
        self._selectionOutlineColour = wx.NullColour
        self._itemFont = wx.NullFont

        self._items = []

        if wx.Platform == "__WXMSW__":
            # If on Windows XP/Vista, use more appropriate colours
            self.SetSelectionOutlineColour(wx.Colour(49, 106, 197))
            self.SetSelectionColour(wx.Colour(193, 210, 238))

        if items:
            self.Copy(items)

[docs]    def Copy(self, items):
        """
        Copy operator between 2 L{SwitcherItems}.

        :param `items`: another instance of L{SwitcherItems}.
        """

        self.Clear()

        for item in items._items:
            self._items.append(item)

        self._selection = items._selection
        self._rowCount = items._rowCount
        self._columnCount = items._columnCount

        self._backgroundColour = items._backgroundColour
        self._textColour = items._textColour
        self._selectionColour = items._selectionColour
        self._selectionOutlineColour = items._selectionOutlineColour
        self._itemFont = items._itemFont

[docs]    def AddItem(self, titleOrItem, name=None, id=0, bitmap=wx.NullBitmap):

        if isinstance(titleOrItem, SwitcherItem):
            self._items.append(titleOrItem)
            return self._items[-1]

        item = SwitcherItem()
        item.SetTitle(titleOrItem)
        item.SetName(name)
        item.SetId(id)
        item.SetBitmap(bitmap)

        self._items.append(item)
        return self._items[-1]

[docs]    def AddGroup(self, title, name, id=0, bitmap=wx.NullBitmap):

        item = self.AddItem(title, name, id, bitmap)
        item.SetIsGroup(True)

        return item

[docs]    def Clear(self):

        self._items = []

[docs]    def FindItemByName(self, name):

        for i in xrange(len(self._items)):
            if self._items[i].GetName() == name:
                return i

        return wx.NOT_FOUND

[docs]    def FindItemById(self, id):

        for i in xrange(len(self._items)):
            if self._items[i].GetId() == id:
                return i

        return wx.NOT_FOUND

[docs]    def SetSelection(self, sel):

        self._selection = sel

[docs]    def SetSelectionByName(self, name):

        idx = self.FindItemByName(name)
        if idx != wx.NOT_FOUND:
            self.SetSelection(idx)

[docs]    def GetSelection(self):

        return self._selection

[docs]    def GetItem(self, i):

        return self._items[i]

[docs]    def GetItemCount(self):

        return len(self._items)

[docs]    def SetRowCount(self, rows):

        self._rowCount = rows

[docs]    def GetRowCount(self):

        return self._rowCount

[docs]    def SetColumnCount(self, cols):

        self._columnCount = cols

[docs]    def GetColumnCount(self):

        return self._columnCount

[docs]    def SetBackgroundColour(self, colour):

        self._backgroundColour = colour

[docs]    def GetBackgroundColour(self):

        return self._backgroundColour

[docs]    def SetTextColour(self, colour):

        self._textColour = colour

[docs]    def GetTextColour(self):

        return self._textColour

[docs]    def SetSelectionColour(self, colour):

        self._selectionColour = colour

[docs]    def GetSelectionColour(self):

        return self._selectionColour

[docs]    def SetSelectionOutlineColour(self, colour):

        self._selectionOutlineColour = colour

[docs]    def GetSelectionOutlineColour(self):

        return self._selectionOutlineColour

[docs]    def SetItemFont(self, font):

        self._itemFont = font

[docs]    def GetItemFont(self):

        return self._itemFont

[docs]    def PaintItems(self, dc, win):

        backgroundColour = wx.SystemSettings.GetColour(wx.SYS_COLOUR_3DFACE)
        standardTextColour = wx.SystemSettings.GetColour(wx.SYS_COLOUR_WINDOWTEXT)
        selectionColour = wx.SystemSettings.GetColour(wx.SYS_COLOUR_HIGHLIGHT)
        selectionOutlineColour = wx.SystemSettings.GetColour(wx.SYS_COLOUR_WINDOWTEXT)
        standardFont = wx.SystemSettings.GetFont(wx.SYS_DEFAULT_GUI_FONT)
        groupFont = wx.SystemSettings.GetFont(wx.SYS_DEFAULT_GUI_FONT)
        groupFont.SetWeight(wx.BOLD)

        if self.GetBackgroundColour().IsOk():
            backgroundColour = self.GetBackgroundColour()

        if self.GetTextColour().IsOk():
            standardTextColour = self.GetTextColour()

        if self.GetSelectionColour().IsOk():
            selectionColour = self.GetSelectionColour()

        if self.GetSelectionOutlineColour().IsOk():
            selectionOutlineColour = self.GetSelectionOutlineColour()

        if self.GetItemFont().IsOk():

            standardFont = self.GetItemFont()
            groupFont = wx.Font(standardFont.GetPointSize(), standardFont.GetFamily(), standardFont.GetStyle(),
                                wx.BOLD, standardFont.GetUnderlined(), standardFont.GetFaceName())

        textMarginX = SWITCHER_TEXT_MARGIN_X

        dc.SetLogicalFunction(wx.COPY)
        dc.SetBrush(wx.Brush(backgroundColour))
        dc.SetPen(wx.TRANSPARENT_PEN)
        dc.DrawRectangleRect(win.GetClientRect())
        dc.SetBackgroundMode(wx.TRANSPARENT)

        for i in xrange(len(self._items)):
            item = self._items[i]
            if i == self._selection:
                dc.SetPen(wx.Pen(selectionOutlineColour))
                dc.SetBrush(wx.Brush(selectionColour))
                dc.DrawRectangleRect(item.GetRect())

            clippingRect = wx.Rect(*item.GetRect())
            clippingRect.Deflate(1, 1)

            dc.SetClippingRect(clippingRect)

            if item.GetTextColour().IsOk():
                dc.SetTextForeground(item.GetTextColour())
            else:
                dc.SetTextForeground(standardTextColour)

            if item.GetFont().IsOk():
                dc.SetFont(item.GetFont())
            else:
                if item.GetIsGroup():
                    dc.SetFont(groupFont)
                else:
                    dc.SetFont(standardFont)

            w, h = dc.GetTextExtent(item.GetTitle())
            x = item.GetRect().x

            x += textMarginX

            if not item.GetIsGroup():
                if item.GetBitmap().IsOk() and item.GetBitmap().GetWidth() <= 16 \
                   and item.GetBitmap().GetHeight() <= 16:
                    x -= textMarginX
                    dc.DrawBitmap(item.GetBitmap(), x, item.GetRect().y + \
                                  (item.GetRect().height - item.GetBitmap().GetHeight())/2,
                                  True)
                    x += 16 + textMarginX
                #x += textMarginX

            y = item.GetRect().y + (item.GetRect().height - h)/2
            dc.DrawText(item.GetTitle(), x, y)
            dc.DestroyClippingRegion()

[docs]    def CalculateItemSize(self, dc):

        # Start off allowing for an icon
        sz = wx.Size(150, 16)
        standardFont = wx.SystemSettings.GetFont(wx.SYS_DEFAULT_GUI_FONT)
        groupFont = wx.SystemSettings.GetFont(wx.SYS_DEFAULT_GUI_FONT)
        groupFont.SetWeight(wx.BOLD)

        textMarginX = SWITCHER_TEXT_MARGIN_X
        textMarginY = SWITCHER_TEXT_MARGIN_Y
        maxWidth = 300
        maxHeight = 40

        if self.GetItemFont().IsOk():
            standardFont = self.GetItemFont()

        for item in self._items:
            if item.GetFont().IsOk():
                dc.SetFont(item.GetFont())
            else:
                if item.GetIsGroup():
                    dc.SetFont(groupFont)
                else:
                    dc.SetFont(standardFont)

            w, h = dc.GetTextExtent(item.GetTitle())
            w += 16 + 2*textMarginX

            if w > sz.x:
                sz.x = min(w, maxWidth)
            if h > sz.y:
                sz.y = min(h, maxHeight)

        if sz == wx.Size(16, 16):
            sz = wx.Size(100, 25)
        else:
            sz.x += textMarginX*2
            sz.y += textMarginY*2

        return sz

[docs]    def GetIndexForFocus(self):

        for i, item in enumerate(self._items):
            if item.GetWindow():

                if FindFocusDescendant(item.GetWindow()):
                    return i

        return wx.NOT_FOUND

[docs]class MultiColumnListCtrl(wx.PyControl):
    """ A control for displaying several columns (not scrollable). """

[docs]    def __init__(self, parent, aui_manager, id=wx.ID_ANY, pos=wx.DefaultPosition, size=wx.DefaultSize,
                 style=0, validator=wx.DefaultValidator, name="MultiColumnListCtrl"):

        wx.PyControl.__init__(self, parent, id, pos, size, style, validator, name)

        self._overallSize = wx.Size(200, 100)
        self._modifierKey = wx.WXK_CONTROL
        self._extraNavigationKey = 0
        self._aui_manager = aui_manager

        self.SetInitialSize(size)
        self.SetBackgroundStyle(wx.BG_STYLE_CUSTOM)

        self.Bind(wx.EVT_PAINT, self.OnPaint)
        self.Bind(wx.EVT_ERASE_BACKGROUND, self.OnEraseBackground)
        self.Bind(wx.EVT_MOUSE_EVENTS, self.OnMouseEvent)
        self.Bind(wx.EVT_CHAR, self.OnChar)
        self.Bind(wx.EVT_KEY_DOWN, self.OnKey)
        self.Bind(wx.EVT_KEY_UP, self.OnKey)

    def __del__(self):

        self._aui_manager.HideHint()

[docs]    def DoGetBestSize(self):

        return self._overallSize

[docs]    def OnEraseBackground(self, event):

        pass

[docs]    def OnPaint(self, event):

        dc = wx.AutoBufferedPaintDC(self)
        rect = self.GetClientRect()

        if self._items.GetColumnCount() == 0:
            self.CalculateLayout(dc)

        if self._items.GetColumnCount() == 0:
            return

        self._items.PaintItems(dc, self)

[docs]    def OnMouseEvent(self, event):

        if event.LeftDown():
            self.SetFocus()

[docs]    def OnChar(self, event):

        event.Skip()

[docs]    def OnKey(self, event):

        if event.GetEventType() == wx.wxEVT_KEY_UP:
            if event.GetKeyCode() == self.GetModifierKey():
                topLevel = wx.GetTopLevelParent(self)
                closeEvent = wx.CloseEvent(wx.wxEVT_CLOSE_WINDOW, topLevel.GetId())
                closeEvent.SetEventObject(topLevel)
                closeEvent.SetCanVeto(False)

                topLevel.GetEventHandler().ProcessEvent(closeEvent)
                return

            event.Skip()
            return

        keyCode = event.GetKeyCode()

        if keyCode in [wx.WXK_ESCAPE, wx.WXK_RETURN]:
            if keyCode == wx.WXK_ESCAPE:
                self._items.SetSelection(-1)

            topLevel = wx.GetTopLevelParent(self)
            closeEvent = wx.CloseEvent(wx.wxEVT_CLOSE_WINDOW, topLevel.GetId())
            closeEvent.SetEventObject(topLevel)
            closeEvent.SetCanVeto(False)

            topLevel.GetEventHandler().ProcessEvent(closeEvent)
            return

        elif keyCode in [wx.WXK_TAB, self.GetExtraNavigationKey()]:
            if event.ShiftDown():

                self._items.SetSelection(self._items.GetSelection() - 1)
                if self._items.GetSelection() < 0:
                    self._items.SetSelection(self._items.GetItemCount() - 1)

                self.AdvanceToNextSelectableItem(-1)

            else:

                self._items.SetSelection(self._items.GetSelection() + 1)
                if self._items.GetSelection() >= self._items.GetItemCount():
                    self._items.SetSelection(0)

                self.AdvanceToNextSelectableItem(1)

            self.GenerateSelectionEvent()
            self.Refresh()

        elif keyCode in [wx.WXK_DOWN, wx.WXK_NUMPAD_DOWN]:
            self._items.SetSelection(self._items.GetSelection() + 1)
            if self._items.GetSelection() >= self._items.GetItemCount():
                self._items.SetSelection(0)

            self.AdvanceToNextSelectableItem(1)
            self.GenerateSelectionEvent()
            self.Refresh()

        elif keyCode in [wx.WXK_UP, wx.WXK_NUMPAD_UP]:
            self._items.SetSelection(self._items.GetSelection() - 1)
            if self._items.GetSelection() < 0:
                self._items.SetSelection(self._items.GetItemCount() - 1)

            self.AdvanceToNextSelectableItem(-1)
            self.GenerateSelectionEvent()
            self.Refresh()

        elif keyCode in [wx.WXK_HOME, wx.WXK_NUMPAD_HOME]:
            self._items.SetSelection(0)
            self.AdvanceToNextSelectableItem(1)
            self.GenerateSelectionEvent()
            self.Refresh()

        elif keyCode in [wx.WXK_END, wx.WXK_NUMPAD_END]:
            self._items.SetSelection(self._items.GetItemCount() - 1)
            self.AdvanceToNextSelectableItem(-1)
            self.GenerateSelectionEvent()
            self.Refresh()

        elif keyCode in [wx.WXK_LEFT, wx.WXK_NUMPAD_LEFT]:
            item = self._items.GetItem(self._items.GetSelection())

            row = item.GetRowPos()
            newCol = item.GetColPos() - 1
            if newCol < 0:
                newCol = self._items.GetColumnCount() - 1

            # Find the first item from the end whose row matches and whose column is equal or lower
            for i in xrange(self._items.GetItemCount()-1, -1, -1):
                item2 = self._items.GetItem(i)
                if item2.GetColPos() == newCol and item2.GetRowPos() <= row:
                    self._items.SetSelection(i)
                    break

            self.AdvanceToNextSelectableItem(-1)
            self.GenerateSelectionEvent()
            self.Refresh()

        elif keyCode in [wx.WXK_RIGHT, wx.WXK_NUMPAD_RIGHT]:
            item = self._items.GetItem(self._items.GetSelection())

            row = item.GetRowPos()
            newCol = item.GetColPos() + 1
            if newCol >= self._items.GetColumnCount():
                newCol = 0

            # Find the first item from the end whose row matches and whose column is equal or lower
            for i in xrange(self._items.GetItemCount()-1, -1, -1):
                item2 = self._items.GetItem(i)
                if item2.GetColPos() == newCol and item2.GetRowPos() <= row:
                    self._items.SetSelection(i)
                    break

            self.AdvanceToNextSelectableItem(1)
            self.GenerateSelectionEvent()
            self.Refresh()

        else:
            event.Skip()

[docs]    def AdvanceToNextSelectableItem(self, direction):

        if self._items.GetItemCount() < 2:
            return

        if self._items.GetSelection() == -1:
            self._items.SetSelection(0)

        oldSel = self._items.GetSelection()

        while 1:

            if self._items.GetItem(self._items.GetSelection()).GetIsGroup():

                self._items.SetSelection(self._items.GetSelection() + direction)
                if self._items.GetSelection() == -1:
                    self._items.SetSelection(self._items.GetItemCount()-1)
                elif self._items.GetSelection() == self._items.GetItemCount():
                    self._items.SetSelection(0)
                if self._items.GetSelection() == oldSel:
                    break

            else:
                break

        self.SetTransparency()
        selection = self._items.GetItem(self._items.GetSelection()).GetWindow()
        pane = self._aui_manager.GetPane(selection)

        if not pane.IsOk():
            if isinstance(selection.GetParent(), auibook.AuiNotebook):
                self.SetTransparency(selection)
                self._aui_manager.ShowHint(selection.GetScreenRect())
                wx.CallAfter(self.SetFocus)
                self.SetFocus()
                return
            else:
                self._aui_manager.HideHint()
                return
        if not pane.IsShown():
            self._aui_manager.HideHint()
            return

        self.SetTransparency(selection)
        self._aui_manager.ShowHint(selection.GetScreenRect())
        # NOTE: this is odd but it is the only way for the focus to
        #       work correctly on wxMac...
        wx.CallAfter(self.SetFocus)
        self.SetFocus()

[docs]    def SetTransparency(self, selection=None):

        if not self.GetParent().CanSetTransparent():
            return

        if selection is not None:
            intersects = False
            if selection.GetScreenRect().Intersects(self.GetParent().GetScreenRect()):
                intersects = True
                self.GetParent().SetTransparent(200)
                return

        self.GetParent().SetTransparent(255)

[docs]    def GenerateSelectionEvent(self):

        event = wx.CommandEvent(wx.wxEVT_COMMAND_LISTBOX_SELECTED, self.GetId())
        event.SetEventObject(self)
        event.SetInt(self._items.GetSelection())
        self.GetEventHandler().ProcessEvent(event)

[docs]    def CalculateLayout(self, dc=None):

        if dc is None:
            dc = wx.ClientDC(self)

        if self._items.GetSelection() == -1:
            self._items.SetSelection(0)

        columnCount = 1

        # Spacing between edge of window or between columns
        xMargin = 4
        yMargin = 4

        # Inter-row spacing
        rowSpacing = 2

        itemSize = self._items.CalculateItemSize(dc)
        self._overallSize = wx.Size(350, 200)

        currentRow = 0
        x = xMargin
        y = yMargin

        breaking = False
        i = 0

        while 1:

            oldOverallSize = self._overallSize
            item = self._items.GetItem(i)

            item.SetRect(wx.Rect(x, y, itemSize.x, itemSize.y))
            item.SetColPos(columnCount-1)
            item.SetRowPos(currentRow)

            if item.GetRect().GetBottom() > self._overallSize.y:
                self._overallSize.y = item.GetRect().GetBottom() + yMargin

            if item.GetRect().GetRight() > self._overallSize.x:
                self._overallSize.x = item.GetRect().GetRight() + xMargin

            currentRow += 1

            y += rowSpacing + itemSize.y
            stopBreaking = breaking

            if currentRow > self._items.GetRowCount() or (item.GetBreakColumn() and not breaking and currentRow != 1):
                currentRow = 0
                columnCount += 1
                x += xMargin + itemSize.x
                y = yMargin

                # Make sure we don't orphan a group
                if item.GetIsGroup() or (item.GetBreakColumn() and not breaking):
                    self._overallSize = oldOverallSize

                    if item.GetBreakColumn():
                        breaking = True

                    # Repeat the last item, in the next column
                    i -= 1

            if stopBreaking:
                breaking = False

            i += 1

            if i >= self._items.GetItemCount():
                break

        self._items.SetColumnCount(columnCount)
        self.InvalidateBestSize()

[docs]    def SetItems(self, items):

        self._items = items

[docs]    def GetItems(self):

        return self._items

[docs]    def SetExtraNavigationKey(self, keyCode):
        """
        Set an extra key that can be used to cycle through items,
        in case not using the ``Ctrl`` + ``Tab`` combination.
        """

        self._extraNavigationKey = keyCode

[docs]    def GetExtraNavigationKey(self):

        return self._extraNavigationKey

[docs]    def SetModifierKey(self, modifierKey):
        """
        Set the modifier used to invoke the dialog, and therefore to test for
        release.
        """

        self._modifierKey = modifierKey

[docs]    def GetModifierKey(self):

        return self._modifierKey

[docs]class SwitcherDialog(wx.Dialog):
    """
    SwitcherDialog shows a L{MultiColumnListCtrl} with a list of panes
    and tabs for the user to choose. ``Ctrl`` + ``Tab`` cycles through them.
    """

[docs]    def __init__(self, items, parent, aui_manager, id=wx.ID_ANY, title=_("Pane Switcher"), pos=wx.DefaultPosition,
                 size=wx.DefaultSize, style=wx.STAY_ON_TOP|wx.DIALOG_NO_PARENT|wx.BORDER_SIMPLE):
        """ Default class constructor. """

        self._switcherBorderStyle = (style & wx.BORDER_MASK)
        if self._switcherBorderStyle == wx.BORDER_NONE:
            self._switcherBorderStyle = wx.BORDER_SIMPLE

        style &= wx.BORDER_MASK
        style |= wx.BORDER_NONE

        wx.Dialog.__init__(self, parent, id, title, pos, size, style)

        self._listCtrl = MultiColumnListCtrl(self, aui_manager,
                                             style=wx.WANTS_CHARS|wx.NO_BORDER)
        self._listCtrl.SetItems(items)
        self._listCtrl.CalculateLayout()

        self._descriptionCtrl = wx.html.HtmlWindow(self, size=(-1, 100), style=wx.BORDER_NONE)
        self._descriptionCtrl.SetBackgroundColour(self.GetBackgroundColour())

        if wx.Platform == "__WXGTK__":
            fontSize = 11
            self._descriptionCtrl.SetStandardFonts(fontSize)

        sizer = wx.BoxSizer(wx.VERTICAL)
        self.SetSizer(sizer)
        sizer.Add(self._listCtrl, 1, wx.ALL|wx.EXPAND, 10)
        sizer.Add(self._descriptionCtrl, 0, wx.ALL|wx.EXPAND, 10)
        sizer.SetSizeHints(self)

        self._listCtrl.SetFocus()

        self.Centre(wx.BOTH)

        if self._listCtrl.GetItems().GetSelection() == -1:
            self._listCtrl.GetItems().SetSelection(0)

        self._listCtrl.AdvanceToNextSelectableItem(1)

        self.ShowDescription(self._listCtrl.GetItems().GetSelection())

        self.Bind(wx.EVT_CLOSE, self.OnCloseWindow)
        self.Bind(wx.EVT_ACTIVATE, self.OnActivate)
        self.Bind(wx.EVT_LISTBOX, self.OnSelectItem)
        self.Bind(wx.EVT_PAINT, self.OnPaint)

        # Attributes
        self._closing = False
        if wx.Platform == "__WXMSW__":
            self._borderColour = wx.Colour(49, 106, 197)
        else:
            self._borderColour = wx.BLACK

        self._aui_manager = aui_manager

[docs]    def OnCloseWindow(self, event):

        if self._closing:
            return

        if self.IsModal():
            self._closing = True

            if self.GetSelection() == -1:
                self.EndModal(wx.ID_CANCEL)
            else:
                self.EndModal(wx.ID_OK)

        self._aui_manager.HideHint()

[docs]    def GetSelection(self):

        return self._listCtrl.GetItems().GetSelection()

[docs]    def OnActivate(self, event):

        if not event.GetActive():
            if not self._closing:
                self._closing = True
                self.EndModal(wx.ID_CANCEL)

[docs]    def OnPaint(self, event):

        dc = wx.PaintDC(self)

        if self._switcherBorderStyle == wx.BORDER_SIMPLE:

            dc.SetPen(wx.Pen(self._borderColour))
            dc.SetBrush(wx.TRANSPARENT_BRUSH)

            rect = self.GetClientRect()
            dc.DrawRectangleRect(rect)

            # Draw border around the HTML control
            rect = wx.Rect(*self._descriptionCtrl.GetRect())
            rect.Inflate(1, 1)
            dc.DrawRectangleRect(rect)

[docs]    def OnSelectItem(self, event):

        self.ShowDescription(event.GetSelection())

# Convert a colour to a 6-digit hex string

[docs]    def ColourToHexString(self, col):

        hx = '%02x%02x%02x' % tuple([int(c) for c in col])
        return hx

[docs]    def ShowDescription(self, i):

        item = self._listCtrl.GetItems().GetItem(i)
        colour = self._listCtrl.GetItems().GetBackgroundColour()

        if not colour.IsOk():
            colour = self.GetBackgroundColour()

        backgroundColourHex = self.ColourToHexString(colour)
        html = _("<body bgcolor=\"#") + backgroundColourHex + _("\"><b>") + item.GetTitle() + _("</b>")

        if item.GetDescription():
            html += _("<p>")
            html += item.GetDescription()

        html += _("</body>")
        self._descriptionCtrl.SetPage(html)

[docs]    def SetExtraNavigationKey(self, keyCode):

        self._extraNavigationKey = keyCode
        if self._listCtrl:
            self._listCtrl.SetExtraNavigationKey(keyCode)

[docs]    def GetExtraNavigationKey(self):

        return self._extraNavigationKey

[docs]    def SetModifierKey(self, modifierKey):

        self._modifierKey = modifierKey
        if self._listCtrl:
            self._listCtrl.SetModifierKey(modifierKey)

[docs]    def GetModifierKey(self):

        return self._modifierKey

[docs]    def SetBorderColour(self, colour):

        self._borderColour = colour

Navigation

  • index
  • modules |
  • Home |
  • Gallery |
  • Contents»
  • Module code »
  • aui.aui_switcherdialog


aui.aui_utilities

  • modules |
  • Home |
  • Gallery |
  • Contents»
  • Module code »
  • aui.aui_utilities

Source code for aui.aui_utilities

"""
This module contains some common functions used by wxPython-AUI to
manipulate colours, bitmaps, text, gradient shadings and custom
dragging images for AuiNotebook tabs.
"""

__author__ = "Andrea Gavana <andrea.gavana@gmail.com>"
__date__ = "31 March 2009"

import wx

from aui_constants import *

if wx.Platform == "__WXMAC__":
    import Carbon.Appearance

[docs]def BlendColour(fg, bg, alpha):
    """
    Blends the two colour component `fg` and `bg` into one colour component, adding
    an optional alpha channel.

    :param `fg`: the first colour component;
    :param `bg`: the second colour component;
    :param `alpha`: an optional transparency value.
    """

    result = bg + (alpha*(fg - bg))

    if result < 0.0:
        result = 0.0
    if result > 255:
        result = 255

    return result

[docs]def StepColour(c, ialpha):
    """
    Darken/lighten the input colour `c`.

    :param `c`: a colour to darken/lighten;
    :param `ialpha`: a transparency value.
    """

    if ialpha == 100:
        return c

    r, g, b = c.Red(), c.Green(), c.Blue()

    # ialpha is 0..200 where 0 is completely black
    # and 200 is completely white and 100 is the same
    # convert that to normal alpha 0.0 - 1.0
    ialpha = min(ialpha, 200)
    ialpha = max(ialpha, 0)
    alpha = (ialpha - 100.0)/100.0

    if ialpha > 100:

        # blend with white
        bg = 255
        alpha = 1.0 - alpha  # 0 = transparent fg 1 = opaque fg

    else:

        # blend with black
        bg = 0
        alpha = 1.0 + alpha  # 0 = transparent fg 1 = opaque fg

    r = BlendColour(r, bg, alpha)
    g = BlendColour(g, bg, alpha)
    b = BlendColour(b, bg, alpha)

    return wx.Colour(r, g, b)

[docs]def LightContrastColour(c):
    """
    Creates a new, lighter colour based on the input colour `c`.

    :param `c`: the input colour to analyze.
    """

    amount = 120

    # if the colour is especially dark, then
    # make the contrast even lighter
    if c.Red() < 128 and c.Green() < 128 and c.Blue() < 128:
        amount = 160

    return StepColour(c, amount)

[docs]def ChopText(dc, text, max_size):
    """
    Chops the input `text` if its size does not fit in `max_size`, by cutting the
    text and adding ellipsis at the end.

    :param `dc`: a `wx.DC` device context;
    :param `text`: the text to chop;
    :param `max_size`: the maximum size in which the text should fit.
    """

    # first check if the text fits with no problems
    x, y, dummy = dc.GetMultiLineTextExtent(text)

    if x <= max_size:
        return text

    textLen = len(text)
    last_good_length = 0

    for i in xrange(textLen, -1, -1):
        s = text[0:i]
        s += "..."

        x, y = dc.GetTextExtent(s)
        last_good_length = i

        if x < max_size:
            break

    ret = text[0:last_good_length] + "..."
    return ret

[docs]def BitmapFromBits(bits, w, h, colour):
    """
    BitmapFromBits() is a utility function that creates a
    masked bitmap from raw bits (XBM format).

    :param `bits`: a string containing the raw bits of the bitmap;
    :param `w`: the bitmap width;
    :param `h`: the bitmap height;
    :param `colour`: the colour which will replace all white pixels in the
     raw bitmap.
    """

    img = wx.BitmapFromBits(bits, w, h).ConvertToImage()
    img.Replace(0, 0, 0, 123, 123, 123)
    img.Replace(255, 255, 255, colour.Red(), colour.Green(), colour.Blue())
    img.SetMaskColour(123, 123, 123)
    return wx.BitmapFromImage(img)

[docs]def IndentPressedBitmap(rect, button_state):
    """
    Indents the input rectangle `rect` based on the value of `button_state`.

    :param `rect`: an instance of `wx.Rect`;
    :param `button_state`: an L{AuiNotebook} button state.
    """

    if button_state == AUI_BUTTON_STATE_PRESSED:
        rect.x += 1
        rect.y += 1

    return rect

[docs]def GetBaseColour():
    """
    Returns the face shading colour on push buttons/backgrounds, mimicking as closely
    as possible the platform UI colours.
    """

    if wx.Platform == "__WXMAC__":

        if hasattr(wx, 'MacThemeColour'):
            base_colour = wx.MacThemeColour(Carbon.Appearance.kThemeBrushToolbarBackground)
        else:
            brush = wx.Brush(wx.BLACK)
            brush.MacSetTheme(Carbon.Appearance.kThemeBrushToolbarBackground)
            base_colour = brush.GetColour()

    else:

        base_colour = wx.SystemSettings.GetColour(wx.SYS_COLOUR_3DFACE)

    # the base_colour is too pale to use as our base colour,
    # so darken it a bit
    if ((255-base_colour.Red()) +
        (255-base_colour.Green()) +
        (255-base_colour.Blue()) < 60):

        base_colour = StepColour(base_colour, 92)

    return base_colour

[docs]def MakeDisabledBitmap(bitmap):
    """
    Convert the given image (in place) to a grayed-out version,
    appropriate for a 'disabled' appearance.

    :param `bitmap`: the bitmap to gray-out.
    """

    anImage = bitmap.ConvertToImage()
    factor = 0.7        # 0 < f < 1.  Higher Is Grayer

    if anImage.HasMask():
        maskColour = (anImage.GetMaskRed(), anImage.GetMaskGreen(), anImage.GetMaskBlue())
    else:
        maskColour = None

    data = map(ord, list(anImage.GetData()))

    for i in range(0, len(data), 3):

        pixel = (data[i], data[i+1], data[i+2])
        pixel = MakeGray(pixel, factor, maskColour)

        for x in range(3):
            data[i+x] = pixel[x]

    anImage.SetData(''.join(map(chr, data)))

    return anImage.ConvertToBitmap()

[docs]def MakeGray(rgbTuple, factor, maskColour):
    """
    Make a pixel grayed-out. If the pixel matches the `maskColour`, it won't be
    changed.

    :param `rgbTuple`: a tuple representing a pixel colour;
    :param `factor`: a graying-out factor;
    :param `maskColour`: a colour mask.
    """

    if rgbTuple != maskColour:
        r, g, b = rgbTuple
        return map(lambda x: int((230 - x) * factor) + x, (r, g, b))
    else:
        return rgbTuple

[docs]def Clip(a, b, c):
    """
    Clips the value in `a` based on the extremes `b` and `c`.

    :param `a`: the value to analyze;
    :param `b`: a minimum value;
    :param `c`: a maximum value.
    """

    return ((a < b and [b]) or [(a > c and [c] or [a])[0]])[0]

[docs]def LightColour(colour, percent):
    """
    Brighten input `colour` by `percent`.

    :param `colour`: the colour to be brightened;
    :param `percent`: brightening percentage.
    """

    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)

[docs]def PaneCreateStippleBitmap():
    """
    Creates a stipple bitmap to be used in a `wx.Brush`.
    This is used to draw sash resize hints.
    """

    data = [0, 0, 0, 192, 192, 192, 192, 192, 192, 0, 0, 0]
    img = wx.EmptyImage(2, 2)
    counter = 0

    for ii in xrange(2):
        for jj in xrange(2):
            img.SetRGB(ii, jj, data[counter], data[counter+1], data[counter+2])
            counter = counter + 3

    return img.ConvertToBitmap()

[docs]def DrawMACCloseButton(colour, backColour=None):
    """
    Draws the wxMAC tab close button using `wx.GraphicsContext`.

    :param `colour`: the colour to use to draw the circle;
    :param `backColour`: the optional background colour for the circle.
    """

    bmp = wx.EmptyBitmapRGBA(16, 16)
    dc = wx.MemoryDC()
    dc.SelectObject(bmp)

    gc = wx.GraphicsContext.Create(dc)
    gc.SetBrush(wx.Brush(colour))
    path = gc.CreatePath()
    path.AddCircle(6.5, 7, 6.5)
    path.CloseSubpath()
    gc.FillPath(path)

    path = gc.CreatePath()
    if backColour is not None:
        pen = wx.Pen(backColour, 2)
    else:
        pen = wx.Pen("white", 2)

    pen.SetCap(wx.CAP_BUTT)
    pen.SetJoin(wx.JOIN_BEVEL)
    gc.SetPen(pen)
    path.MoveToPoint(3.5, 4)
    path.AddLineToPoint(9.5, 10)
    path.MoveToPoint(3.5, 10)
    path.AddLineToPoint(9.5, 4)
    path.CloseSubpath()
    gc.DrawPath(path)

    dc.SelectObject(wx.NullBitmap)
    return bmp

[docs]def DarkenBitmap(bmp, caption_colour, new_colour):
    """
    Darkens the input bitmap on wxMAC using the input colour.

    :param `bmp`: the bitmap to be manipulated;
    :param `caption_colour`: the colour of the pane caption;
    :param `new_colour`: the colour used to darken the bitmap.
    """

    image = bmp.ConvertToImage()
    red = caption_colour.Red()/float(new_colour.Red())
    green = caption_colour.Green()/float(new_colour.Green())
    blue = caption_colour.Blue()/float(new_colour.Blue())
    image = image.AdjustChannels(red, green, blue)
    return image.ConvertToBitmap()

[docs]def DrawGradientRectangle(dc, rect, start_colour, end_colour, direction, offset=0, length=0):
    """
    Draws a gradient-shaded rectangle.

    :param `dc`: a `wx.DC` device context;
    :param `rect`: the rectangle in which to draw the gradient;
    :param `start_colour`: the first colour of the gradient;
    :param `end_colour`: the second colour of the gradient;
    :param `direction`: the gradient direction (horizontal or vertical).
    """

    if direction == AUI_GRADIENT_VERTICAL:
        dc.GradientFillLinear(rect, start_colour, end_colour, wx.SOUTH)
    else:
        dc.GradientFillLinear(rect, start_colour, end_colour, wx.EAST)

[docs]def FindFocusDescendant(ancestor):
    """
    Find a window with the focus, that is also a descendant of the given window.
    This is used to determine the window to initially send commands to.

    :param `ancestor`: the window to check for ancestry.
    """

    # Process events starting with the window with the focus, if any.
    focusWin = wx.Window.FindFocus()
    win = focusWin

    # Check if this is a descendant of this frame.
    # If not, win will be set to NULL.
    while win:
        if win == ancestor:
            break
        else:
            win = win.GetParent()

    if win is None:
        focusWin = None

    return focusWin

[docs]def GetLabelSize(dc, label, vertical):
    """
    Returns the L{AuiToolBar} item label size.

    :param `label`: the toolbar tool label;
    :param `vertical`: whether the toolbar tool orientation is vertical or not.
    """

    text_width = text_height = 0

    # get the text height
    dummy, text_height = dc.GetTextExtent("ABCDHgj")
    # get the text width
    if label.strip():
        text_width, dummy = dc.GetTextExtent(label)

    if vertical:
        tmp = text_height
        text_height = text_width
        text_width = tmp

    return wx.Size(text_width, text_height)

#---------------------------------------------------------------------------
# TabDragImage implementation
# This class handles the creation of a custom image when dragging
# AuiNotebook tabs
#---------------------------------------------------------------------------

[docs]class TabDragImage(wx.DragImage):
    """
    This class handles the creation of a custom image in case of drag and
    drop of a notebook tab.
    """

[docs]    def __init__(self, notebook, page, button_state, tabArt):
        """
        Default class constructor.

        For internal use: do not call it in your code!

        :param `notebook`: an instance of L{AuiNotebook};
        :param `page`: the dragged L{AuiNotebook} page;
        :param `button_state`: the state of the close button on the tab;
        :param `tabArt`: an instance of L{AuiDefaultTabArt} or one of its derivations.
        """

        self._backgroundColour = wx.NamedColour("pink")
        self._bitmap = self.CreateBitmap(notebook, page, button_state, tabArt)
        wx.DragImage.__init__(self, self._bitmap)

[docs]    def CreateBitmap(self, notebook, page, button_state, tabArt):
        """
        Actually creates the drag and drop bitmap.

        :param `notebook`: an instance of L{AuiNotebook};
        :param `page`: the dragged L{AuiNotebook} page;
        :param `button_state`: the state of the close button on the tab;
        :param `tabArt`: an instance of L{AuiDefaultTabArt} or one of its derivations.
        """

        control = page.control
        memory = wx.MemoryDC(wx.EmptyBitmap(1, 1))

        tab_size, x_extent = tabArt.GetTabSize(memory, notebook, page.caption, page.bitmap, page.active,
                                               button_state, control)

        tab_width, tab_height = tab_size
        rect = wx.Rect(0, 0, tab_width, tab_height)

        bitmap = wx.EmptyBitmap(tab_width+1, tab_height+1)
        memory.SelectObject(bitmap)

        if wx.Platform == "__WXMAC__":
            memory.SetBackground(wx.TRANSPARENT_BRUSH)
        else:
            memory.SetBackground(wx.Brush(self._backgroundColour))

        memory.SetBackgroundMode(wx.TRANSPARENT)
        memory.Clear()

        paint_control = wx.Platform != "__WXMAC__"
        tabArt.DrawTab(memory, notebook, page, rect, button_state, paint_control=paint_control)

        memory.SetBrush(wx.TRANSPARENT_BRUSH)
        memory.SetPen(wx.BLACK_PEN)
        memory.DrawRoundedRectangle(0, 0, tab_width+1, tab_height+1, 2)

        memory.SelectObject(wx.NullBitmap)

        # Gtk and Windows unfortunatly don't do so well with transparent
        # drawing so this hack corrects the image to have a transparent
        # background.
        if wx.Platform != '__WXMAC__':
            timg = bitmap.ConvertToImage()
            if not timg.HasAlpha():
                timg.InitAlpha()
            for y in xrange(timg.GetHeight()):
                for x in xrange(timg.GetWidth()):
                    pix = wx.Colour(timg.GetRed(x, y),
                                    timg.GetGreen(x, y),
                                    timg.GetBlue(x, y))
                    if pix == self._backgroundColour:
                        timg.SetAlpha(x, y, 0)
            bitmap = timg.ConvertToBitmap()
        return bitmap

[docs]def GetDockingImage(direction, useAero, center):
    """
    Returns the correct name of the docking bitmap depending on the input parameters.

    :param `useAero`: whether L{AuiManager} is using Aero-style or Whidbey-style docking
     images or not;
    :param `center`: whether we are looking for the center diamond-shaped bitmap or not.
    """

    suffix = (center and [""] or ["_single"])[0]
    prefix = ""
    if useAero == 2:
        # Whidbey docking guides
        prefix = "whidbey_"
    elif useAero == 1:
        # Aero docking style
        prefix = "aero_"

    if direction == wx.TOP:
        bmp_unfocus = eval("%sup%s"%(prefix, suffix)).GetBitmap()
        bmp_focus = eval("%sup_focus%s"%(prefix, suffix)).GetBitmap()
    elif direction == wx.BOTTOM:
        bmp_unfocus = eval("%sdown%s"%(prefix, suffix)).GetBitmap()
        bmp_focus = eval("%sdown_focus%s"%(prefix, suffix)).GetBitmap()
    elif direction == wx.LEFT:
        bmp_unfocus = eval("%sleft%s"%(prefix, suffix)).GetBitmap()
        bmp_focus = eval("%sleft_focus%s"%(prefix, suffix)).GetBitmap()
    elif direction == wx.RIGHT:
        bmp_unfocus = eval("%sright%s"%(prefix, suffix)).GetBitmap()
        bmp_focus = eval("%sright_focus%s"%(prefix, suffix)).GetBitmap()
    else:
        bmp_unfocus = eval("%stab%s"%(prefix, suffix)).GetBitmap()
        bmp_focus = eval("%stab_focus%s"%(prefix, suffix)).GetBitmap()

    return bmp_unfocus, bmp_focus

[docs]def TakeScreenShot(rect):
    """
    Takes a screenshot of the screen at given position and size (rect).

    :param `rect`: the screen rectangle for which we want to take a screenshot.
    """

    # Create a DC for the whole screen area
    dcScreen = wx.ScreenDC()

    # Create a Bitmap that will later on hold the screenshot image
    # Note that the Bitmap must have a size big enough to hold the screenshot
    # -1 means using the current default colour depth
    bmp = wx.EmptyBitmap(rect.width, rect.height)

    # Create a memory DC that will be used for actually taking the screenshot
    memDC = wx.MemoryDC()

    # Tell the memory DC to use our Bitmap
    # all drawing action on the memory DC will go to the Bitmap now
    memDC.SelectObject(bmp)

    # Blit (in this case copy) the actual screen on the memory DC
    # and thus the Bitmap
    memDC.Blit( 0,            # Copy to this X coordinate
                0,            # Copy to this Y coordinate
                rect.width,   # Copy this width
                rect.height,  # Copy this height
                dcScreen,     # From where do we copy?
                rect.x,       # What's the X offset in the original DC?
                rect.y        # What's the Y offset in the original DC?
                )

    # Select the Bitmap out of the memory DC by selecting a new
    # uninitialized Bitmap
    memDC.SelectObject(wx.NullBitmap)

    return bmp

[docs]def RescaleScreenShot(bmp, thumbnail_size=200):
    """
    Rescales a bitmap to be 300 pixels wide (or tall) at maximum.

    :param `bmp`: the bitmap to rescale;
    :param `thumbnail_size`: the maximum size of every page thumbnail.
    """

    bmpW, bmpH = bmp.GetWidth(), bmp.GetHeight()
    img = bmp.ConvertToImage()

    newW, newH = bmpW, bmpH

    if bmpW > bmpH:
        if bmpW > thumbnail_size:
            ratio = bmpW/float(thumbnail_size)
            newW, newH = int(bmpW/ratio), int(bmpH/ratio)
            img.Rescale(newW, newH, wx.IMAGE_QUALITY_HIGH)
    else:
        if bmpH > thumbnail_size:
            ratio = bmpH/float(thumbnail_size)
            newW, newH = int(bmpW/ratio), int(bmpH/ratio)
            img.Rescale(newW, newH, wx.IMAGE_QUALITY_HIGH)

    newBmp = img.ConvertToBitmap()
    otherBmp = wx.EmptyBitmap(newW+5, newH+5)

    memDC = wx.MemoryDC()
    memDC.SelectObject(otherBmp)
    memDC.SetBackground(wx.WHITE_BRUSH)
    memDC.Clear()

    memDC.SetPen(wx.TRANSPARENT_PEN)

    pos = 0
    for i in xrange(5, 0, -1):
        brush = wx.Brush(wx.Colour(50*i, 50*i, 50*i))
        memDC.SetBrush(brush)
        memDC.DrawRoundedRectangle(0, 0, newW+5-pos, newH+5-pos, 2)
        pos += 1

    memDC.DrawBitmap(newBmp, 0, 0, True)

    # Select the Bitmap out of the memory DC by selecting a new
    # uninitialized Bitmap
    memDC.SelectObject(wx.NullBitmap)

    return otherBmp

[docs]def GetSlidingPoints(rect, size, direction):
    """
    Returns the point at which the sliding in and out of a minimized pane begins.

    :param `rect`: the L{AuiToolBar} tool screen rectangle;
    :param `size`: the pane window size;
    :param `direction`: the pane docking direction.
    """

    if direction == AUI_DOCK_LEFT:
        startX, startY = rect.x + rect.width + 2, rect.y
    elif direction == AUI_DOCK_TOP:
        startX, startY = rect.x, rect.y + rect.height + 2
    elif direction == AUI_DOCK_RIGHT:
        startX, startY = rect.x - size.x - 2, rect.y
    elif direction == AUI_DOCK_BOTTOM:
        startX, startY = rect.x, rect.y - size.y - 2
    else:
        raise Exception("How did we get here?")

    caption_height = wx.SystemSettings.GetMetric(wx.SYS_CAPTION_Y)
    frame_border_x = wx.SystemSettings.GetMetric(wx.SYS_FRAMESIZE_X)
    frame_border_y = wx.SystemSettings.GetMetric(wx.SYS_FRAMESIZE_Y)

    stopX = size.x + caption_height + frame_border_x
    stopY = size.x + frame_border_y

    return startX, startY, stopX, stopY

[docs]def CopyAttributes(newArt, oldArt):
    """
    Copies pens, brushes, colours and fonts from the old tab art to the new one.

    :param `newArt`: the new instance of L{AuiDefaultTabArt};
    :param `oldArt`: the old instance of L{AuiDefaultTabArt}.
    """

    attrs = dir(oldArt)

    for attr in attrs:
        if attr.startswith("_") and (attr.endswith("_colour") or attr.endswith("_font") or \
                                     attr.endswith("_font") or attr.endswith("_brush") or \
                                     attr.endswith("Pen") or attr.endswith("_pen")):
            setattr(newArt, attr, getattr(oldArt, attr))

    return newArt

Navigation

  • index
  • modules |
  • Home |
  • Gallery |
  • Contents»
  • Module code »
  • aui.aui_utilities


aui.auibar

  • modules |
  • Home |
  • Gallery |
  • Contents»
  • Module code »
  • aui.auibar

Source code for aui.auibar

"""
auibar contains an implementation of L{AuiToolBar}, which is a completely owner-drawn
toolbar perfectly integrated with the AUI layout system. This allows drag and drop of
toolbars, docking/floating behaviour and the possibility to define "overflow" items
in the toolbar itself.

The default theme that is used is L{AuiDefaultToolBarArt}, which provides a modern,
glossy look and feel. The theme can be changed by calling L{AuiToolBar.SetArtProvider}.
"""

__author__ = "Andrea Gavana <andrea.gavana@gmail.com>"
__date__ = "31 March 2009"

import wx
import types

from aui_utilities import BitmapFromBits, StepColour, GetLabelSize
from aui_utilities import GetBaseColour, MakeDisabledBitmap

import framemanager
from aui_constants import *

# wxPython version string
_VERSION_STRING = wx.VERSION_STRING

# AuiToolBar events
wxEVT_COMMAND_AUITOOLBAR_TOOL_DROPDOWN = wx.NewEventType()
wxEVT_COMMAND_AUITOOLBAR_OVERFLOW_CLICK = wx.NewEventType()
wxEVT_COMMAND_AUITOOLBAR_RIGHT_CLICK = wx.NewEventType()
wxEVT_COMMAND_AUITOOLBAR_MIDDLE_CLICK = wx.NewEventType()
wxEVT_COMMAND_AUITOOLBAR_BEGIN_DRAG = wx.NewEventType()

EVT_AUITOOLBAR_TOOL_DROPDOWN = wx.PyEventBinder(wxEVT_COMMAND_AUITOOLBAR_TOOL_DROPDOWN, 1)
""" A dropdown `AuiToolBarItem` is being shown. """
EVT_AUITOOLBAR_OVERFLOW_CLICK = wx.PyEventBinder(wxEVT_COMMAND_AUITOOLBAR_OVERFLOW_CLICK, 1)
""" The user left-clicked on the overflow button in `AuiToolBar`. """
EVT_AUITOOLBAR_RIGHT_CLICK = wx.PyEventBinder(wxEVT_COMMAND_AUITOOLBAR_RIGHT_CLICK, 1)
""" Fires an event when the user right-clicks on a `AuiToolBarItem`. """
EVT_AUITOOLBAR_MIDDLE_CLICK = wx.PyEventBinder(wxEVT_COMMAND_AUITOOLBAR_MIDDLE_CLICK, 1)
""" Fires an event when the user middle-clicks on a `AuiToolBarItem`. """
EVT_AUITOOLBAR_BEGIN_DRAG = wx.PyEventBinder(wxEVT_COMMAND_AUITOOLBAR_BEGIN_DRAG, 1)
""" A drag operation involving a toolbar item has started. """

# ----------------------------------------------------------------------

[docs]class CommandToolBarEvent(wx.PyCommandEvent):
    """ A specialized command event class for events sent by L{AuiToolBar}. """

[docs]    def __init__(self, command_type, win_id):
        """
        Default class constructor.

        :param `command_type`: the event kind or an instance of `wx.PyCommandEvent`.
        :param `win_id`: the window identification number.
        """

        if type(command_type) == types.IntType:
            wx.PyCommandEvent.__init__(self, command_type, win_id)
        else:
            wx.PyCommandEvent.__init__(self, command_type.GetEventType(), command_type.GetId())

        self.is_dropdown_clicked = False
        self.click_pt = wx.Point(-1, -1)
        self.rect = wx.Rect(-1, -1, 0, 0)
        self.tool_id = -1

[docs]    def IsDropDownClicked(self):
        """ Returns whether the drop down menu has been clicked. """

        return self.is_dropdown_clicked

[docs]    def SetDropDownClicked(self, c):
        """
        Sets whether the drop down menu has been clicked.

        :param `c`: ``True`` to set the drop down as clicked, ``False`` otherwise.
        """

        self.is_dropdown_clicked = c

[docs]    def GetClickPoint(self):
        """ Returns the point where the user clicked with the mouse. """

        return self.click_pt

[docs]    def SetClickPoint(self, p):
        """
        Sets the clicking point.

        :param `p`: a `wx.Point` object.
        """

        self.click_pt = p

[docs]    def GetItemRect(self):
        """ Returns the L{AuiToolBarItem} rectangle. """

        return self.rect

[docs]    def SetItemRect(self, r):
        """
        Sets the L{AuiToolBarItem} rectangle.

        :param `r`: an instance of `wx.Rect`.
        """

        self.rect = r

[docs]    def GetToolId(self):
        """ Returns the L{AuiToolBarItem} identifier. """

        return self.tool_id

[docs]    def SetToolId(self, id):
        """
        Sets the L{AuiToolBarItem} identifier.

        :param `id`: the toolbar item identifier.
        """

        self.tool_id = id

# ----------------------------------------------------------------------

[docs]class AuiToolBarEvent(CommandToolBarEvent):
    """ A specialized command event class for events sent by L{AuiToolBar}. """

[docs]    def __init__(self, command_type=None, win_id=0):
        """
        Default class constructor.

        :param `command_type`: the event kind or an instance of `wx.PyCommandEvent`.
        :param `win_id`: the window identification number.
        """

        CommandToolBarEvent.__init__(self, command_type, win_id)

        if type(command_type) == types.IntType:
            self.notify = wx.NotifyEvent(command_type, win_id)
        else:
            self.notify = wx.NotifyEvent(command_type.GetEventType(), command_type.GetId())

[docs]    def GetNotifyEvent(self):
        """ Returns the actual `wx.NotifyEvent`. """

        return self.notify

[docs]    def IsAllowed(self):
        """ Returns whether the event is allowed or not. """

        return self.notify.IsAllowed()

[docs]    def Veto(self):
        """
        Prevents the change announced by this event from happening.

        It is in general a good idea to notify the user about the reasons for
        vetoing the change because otherwise the applications behaviour (which
        just refuses to do what the user wants) might be quite surprising.
        """

        self.notify.Veto()

[docs]    def Allow(self):
        """
        This is the opposite of L{Veto}: it explicitly allows the event to be
        processed. For most events it is not necessary to call this method as the
        events are allowed anyhow but some are forbidden by default (this will
        be mentioned in the corresponding event description).
        """

        self.notify.Allow()

# ----------------------------------------------------------------------

[docs]class ToolbarCommandCapture(wx.PyEvtHandler):
    """ A class to handle the dropdown window menu. """

[docs]    def __init__(self):
        """ Default class constructor. """

        wx.PyEvtHandler.__init__(self)
        self._last_id = 0

[docs]    def GetCommandId(self):
        """ Returns the event command identifier. """

        return self._last_id

[docs]    def ProcessEvent(self, event):
        """
        Processes an event, searching event tables and calling zero or more suitable
        event handler function(s).

        :param `event`: the event to process.

        :note: Normally, your application would not call this function: it is called
         in the wxPython implementation to dispatch incoming user interface events
         to the framework (and application).
         However, you might need to call it if implementing new functionality (such as
         a new control) where you define new event types, as opposed to allowing the
         user to override functions.

         An instance where you might actually override the L{ProcessEvent} function is where
         you want to direct event processing to event handlers not normally noticed by
         wxPython. For example, in the document/view architecture, documents and views
         are potential event handlers. When an event reaches a frame, L{ProcessEvent} will
         need to be called on the associated document and view in case event handler
         functions are associated with these objects.

         The normal order of event table searching is as follows:

         1. If the object is disabled (via a call to `SetEvtHandlerEnabled`) the function
            skips to step (6).
         2. If the object is a `wx.Window`, L{ProcessEvent} is recursively called on the window's
            `wx.Validator`. If this returns ``True``, the function exits.
         3. wxWidgets `SearchEventTable` is called for this event handler. If this fails, the
            base class table is tried, and so on until no more tables exist or an appropriate
            function was found, in which case the function exits.
         4. The search is applied down the entire chain of event handlers (usually the chain
            has a length of one). If this succeeds, the function exits.
         5. If the object is a `wx.Window` and the event is a `wx.CommandEvent`, L{ProcessEvent} is
            recursively applied to the parent window's event handler. If this returns ``True``,
            the function exits.
         6. Finally, L{ProcessEvent} is called on the `wx.App` object.
        """

        if event.GetEventType() == wx.wxEVT_COMMAND_MENU_SELECTED:
            self._last_id = event.GetId()
            return True

        if self.GetNextHandler():
            return self.GetNextHandler().ProcessEvent(event)

        return False

# ----------------------------------------------------------------------

[docs]class AuiToolBarItem(object):
    """
    AuiToolBarItem is a toolbar element.

    It has a unique id (except for the separators which always have id = -1), the
    style (telling whether it is a normal button, separator or a control), the
    state (toggled or not, enabled or not) and short and long help strings. The
    default implementations use the short help string for the tooltip text which
    is popped up when the mouse pointer enters the tool and the long help string
    for the applications status bar.
    """

[docs]    def __init__(self, item=None):
        """
        Default class constructor.

        :param `item`: another instance of L{AuiToolBarItem}.
        """

        if item:
            self.Assign(item)
            return

        self.window = None
        self.clockwisebmp = wx.NullBitmap
        self.counterclockwisebmp = wx.NullBitmap
        self.clockwisedisbmp = wx.NullBitmap
        self.counterclockwisedisbmp = wx.NullBitmap
        self.sizer_item = None
        self.spacer_pixels = 0
        self.id = 0
        self.kind = ITEM_NORMAL
        self.state = 0   # normal, enabled
        self.proportion = 0
        self.active = True
        self.dropdown = True
        self.sticky = True
        self.user_data = 0

        self.label = ""
        self.bitmap = wx.NullBitmap
        self.disabled_bitmap = wx.NullBitmap
        self.hover_bitmap = wx.NullBitmap
        self.short_help = ""
        self.long_help = ""
        self.target = None
        self.min_size = wx.Size(-1, -1)
        self.alignment = wx.ALIGN_CENTER
        self.orientation = AUI_TBTOOL_HORIZONTAL

[docs]    def Assign(self, c):
        """
        Assigns the properties of the L{AuiToolBarItem} `c` to `self`.

        :param `c`: another instance of L{AuiToolBarItem}.
        """

        self.window = c.window
        self.label = c.label
        self.bitmap = c.bitmap
        self.disabled_bitmap = c.disabled_bitmap
        self.hover_bitmap = c.hover_bitmap
        self.short_help = c.short_help
        self.long_help = c.long_help
        self.sizer_item = c.sizer_item
        self.min_size = c.min_size
        self.spacer_pixels = c.spacer_pixels
        self.id = c.id
        self.kind = c.kind
        self.state = c.state
        self.proportion = c.proportion
        self.active = c.active
        self.dropdown = c.dropdown
        self.sticky = c.sticky
        self.user_data = c.user_data
        self.alignment = c.alignment
        self.orientation = c.orientation
        self.target = c.target

[docs]    def SetWindow(self, w):
        """
        Assigns a window to the toolbar item.

        :param `w`: an instance of `wx.Window`.
        """

        self.window = w

[docs]    def GetWindow(self):
        """ Returns window associated to the toolbar item. """

        return self.window

[docs]    def SetId(self, new_id):
        """
        Sets the toolbar item identifier.

        :param `new_id`: the new tool id.
        """

        self.id = new_id

[docs]    def GetId(self):
        """ Returns the toolbar item identifier. """

        return self.id

[docs]    def SetKind(self, new_kind):
        """
        Sets the L{AuiToolBarItem} kind.

        :param `new_kind`: can be one of the following items:

         ========================  =============================
         Item Kind                 Description
         ========================  =============================
         ``ITEM_CONTROL``          The item in the `AuiToolBar` is a control
         ``ITEM_LABEL``            The item in the `AuiToolBar` is a text label
         ``ITEM_SPACER``           The item in the `AuiToolBar` is a spacer
         ``ITEM_SEPARATOR``        The item in the `AuiToolBar` is a separator
         ``ITEM_CHECK``            The item in the `AuiToolBar` is a toolbar check item
         ``ITEM_NORMAL``           The item in the `AuiToolBar` is a standard toolbar item
         ``ITEM_RADIO``            The item in the `AuiToolBar` is a toolbar radio item
         ========================  =============================
        """

        self.kind = new_kind

[docs]    def GetKind(self):
        """ Returns the toolbar item kind. See L{SetKind} for more details. """

        return self.kind

[docs]    def SetState(self, new_state):
        """
        Sets the toolbar item state.

        :param `new_state`: can be one of the following states:

         ============================================  ======================================
         Button State Constant                         Description
         ============================================  ======================================
         ``AUI_BUTTON_STATE_NORMAL``                   Normal button state
         ``AUI_BUTTON_STATE_HOVER``                    Hovered button state
         ``AUI_BUTTON_STATE_PRESSED``                  Pressed button state
         ``AUI_BUTTON_STATE_DISABLED``                 Disabled button state
         ``AUI_BUTTON_STATE_HIDDEN``                   Hidden button state
         ``AUI_BUTTON_STATE_CHECKED``                  Checked button state
         ============================================  ======================================

        """

        self.state = new_state

[docs]    def GetState(self):
        """
        Returns the toolbar item state. See L{SetState} for more details.

        :see: L{SetState}
        """

        return self.state

[docs]    def SetSizerItem(self, s):
        """
        Associates a sizer item to this toolbar item.

        :param `s`: an instance of `wx.SizerItem`.
        """

        self.sizer_item = s

[docs]    def GetSizerItem(self):
        """ Returns the associated sizer item. """

        return self.sizer_item

[docs]    def SetLabel(self, s):
        """
        Sets the toolbar item label.

        :param `s`: a string specifying the toolbar item label.
        """

        self.label = s

[docs]    def GetLabel(self):
        """ Returns the toolbar item label. """

        return self.label

[docs]    def SetBitmap(self, bmp):
        """
        Sets the toolbar item bitmap.

        :param `bmp`: an instance of `wx.Bitmap`.
        """

        self.bitmap = bmp

[docs]    def GetBitmap(self):
        """ Returns the toolbar item bitmap. """

        return self.GetRotatedBitmap(False)

[docs]    def SetDisabledBitmap(self, bmp):
        """
        Sets the toolbar item disabled bitmap.

        :param `bmp`: an instance of `wx.Bitmap`.
        """

        self.disabled_bitmap = bmp

[docs]    def GetDisabledBitmap(self):
        """ Returns the toolbar item disabled bitmap. """

        return self.GetRotatedBitmap(True)

[docs]    def SetHoverBitmap(self, bmp):
        """
        Sets the toolbar item hover bitmap.

        :param `bmp`: an instance of `wx.Bitmap`.
        """

        self.hover_bitmap = bmp

[docs]    def SetOrientation(self, a):
        """
        Sets the toolbar tool orientation.

        :param `a`: one of ``AUI_TBTOOL_HORIZONTAL``, ``AUI_TBTOOL_VERT_CLOCKWISE`` or
         ``AUI_TBTOOL_VERT_COUNTERCLOCKWISE``.
        """

        self.orientation = a

[docs]    def GetOrientation(self):
        """ Returns the toolbar tool orientation. """

        return self.orientation

[docs]    def GetHoverBitmap(self):
        """ Returns the toolbar item hover bitmap. """

        return self.hover_bitmap

[docs]    def GetRotatedBitmap(self, disabled):
        """
        Returns the correct bitmap depending on the tool orientation.

        :param `disabled`: whether to return the disabled bitmap or not.
        """

        bitmap_to_rotate = (disabled and [self.disabled_bitmap] or [self.bitmap])[0]
        if not bitmap_to_rotate.IsOk() or self.orientation == AUI_TBTOOL_HORIZONTAL:
            return bitmap_to_rotate

        rotated_bitmap = wx.NullBitmap
        clockwise = True
        if self.orientation == AUI_TBTOOL_VERT_CLOCKWISE:
            rotated_bitmap = (disabled and [self.clockwisedisbmp] or [self.clockwisebmp])[0]

        elif self.orientation == AUI_TBTOOL_VERT_COUNTERCLOCKWISE:
            rotated_bitmap = (disabled and [self.counterclockwisedisbmp] or [self.counterclockwisebmp])[0]
            clockwise = False

        if not rotated_bitmap.IsOk():
            rotated_bitmap = wx.BitmapFromImage(bitmap_to_rotate.ConvertToImage().Rotate90(clockwise))

        return rotated_bitmap

[docs]    def SetShortHelp(self, s):
        """
        Sets the short help string for the L{AuiToolBarItem}, to be displayed in a
        `wx.ToolTip` when the mouse hover over the toolbar item.

        :param `s`: the tool short help string.
        """

        self.short_help = s

[docs]    def GetShortHelp(self):
        """ Returns the short help string for the L{AuiToolBarItem}. """

        return self.short_help

[docs]    def SetLongHelp(self, s):
        """
        Sets the long help string for the toolbar item. This string is shown in the
        statusbar (if any) of the parent frame when the mouse pointer is inside the
        tool.

        :param `s`: the tool long help string.
        """

        self.long_help = s

[docs]    def GetLongHelp(self):
        """ Returns the long help string for the L{AuiToolBarItem}. """

        return self.long_help

[docs]    def SetMinSize(self, s):
        """
        Sets the toolbar item minimum size.

        :param `s`: an instance of `wx.Size`.
        """

        self.min_size = wx.Size(*s)

[docs]    def GetMinSize(self):
        """ Returns the toolbar item minimum size. """

        return self.min_size

[docs]    def SetSpacerPixels(self, s):
        """
        Sets the number of pixels for a toolbar item with kind = ``ITEM_SEPARATOR``.

        :param `s`: number of pixels.
        """

        self.spacer_pixels = s

[docs]    def GetSpacerPixels(self):
        """ Returns the number of pixels for a toolbar item with kind = ``ITEM_SEPARATOR``. """

        return self.spacer_pixels

[docs]    def SetProportion(self, p):
        """
        Sets the L{AuiToolBarItem} proportion in the toolbar.

        :param `p`: the item proportion.
        """

        self.proportion = p

[docs]    def GetProportion(self):
        """ Returns the L{AuiToolBarItem} proportion in the toolbar. """

        return self.proportion

[docs]    def SetActive(self, b):
        """
        Activates/deactivates the toolbar item.

        :param `b`: ``True`` to activate the item, ``False`` to deactivate it.
        """

        self.active = b

[docs]    def IsActive(self):
        """ Returns whether the toolbar item is active or not. """

        return self.active

[docs]    def SetHasDropDown(self, b):
        """
        Sets whether the toolbar item has an associated dropdown menu.

        :param `b`: ``True`` to set a dropdown menu, ``False`` otherwise.
        """

        self.dropdown = b

[docs]    def HasDropDown(self):
        """ Returns whether the toolbar item has an associated dropdown menu or not. """

        return self.dropdown

[docs]    def SetSticky(self, b):
        """
        Sets whether the toolbar item is sticky (permanent highlight after mouse enter)
        or not.

        :param `b`: ``True`` to set the item as sticky, ``False`` otherwise.
        """

        self.sticky = b

[docs]    def IsSticky(self):
        """ Returns whether the toolbar item has a sticky behaviour or not. """

        return self.sticky

[docs]    def SetUserData(self, l):
        """
        Associates some kind of user data to the toolbar item.

        :param `l`: a Python object.

        :note: The user data can be any Python object.
        """

        self.user_data = l

[docs]    def GetUserData(self):
        """ Returns the associated user data. """

        return self.user_data

[docs]    def SetAlignment(self, l):
        """
        Sets the toolbar item alignment.

        :param `l`: the item alignment, which can be one of the available `wx.Sizer`
         alignments.
        """

        self.alignment = l

[docs]    def GetAlignment(self):
        """ Returns the toolbar item alignment. """

        return self.alignment

# ----------------------------------------------------------------------

[docs]class AuiDefaultToolBarArt(object):
    """
    Toolbar art provider code - a tab provider provides all drawing functionality to
    the L{AuiToolBar}. This allows the L{AuiToolBar} to have a plugable look-and-feel.

    By default, a L{AuiToolBar} uses an instance of this class called L{AuiDefaultToolBarArt}
    which provides bitmap art and a colour scheme that is adapted to the major platforms'
    look. You can either derive from that class to alter its behaviour or write a
    completely new tab art class. Call L{AuiToolBar.SetArtProvider} to make use this
    new tab art.
    """

[docs]    def __init__(self):
        """ Default class constructor. """

        self.SetDefaultColours()

        self._agwFlags = 0
        self._text_orientation = AUI_TBTOOL_TEXT_BOTTOM
        self._highlight_colour = wx.SystemSettings.GetColour(wx.SYS_COLOUR_HIGHLIGHT)

        self._separator_size = 7
        self._orientation = AUI_TBTOOL_HORIZONTAL
        self._gripper_size = 7
        self._overflow_size = 16

        button_dropdown_bits = "\xe0\xf1\xfb"
        overflow_bits = "\x80\xff\x80\xc1\xe3\xf7"

        self._button_dropdown_bmp = BitmapFromBits(button_dropdown_bits, 5, 3, wx.BLACK)
        self._disabled_button_dropdown_bmp = BitmapFromBits(button_dropdown_bits, 5, 3,
                                                            wx.Colour(128, 128, 128))
        self._overflow_bmp = BitmapFromBits(overflow_bits, 7, 6, wx.BLACK)
        self._disabled_overflow_bmp = BitmapFromBits(overflow_bits, 7, 6, wx.Colour(128, 128, 128))

        self._font = wx.SystemSettings.GetFont(wx.SYS_DEFAULT_GUI_FONT)

[docs]    def SetDefaultColours(self, base_colour=None):
        """
        Sets the default colours, which are calculated from the given base colour.

        :param `base_colour`: an instance of `wx.Colour`. If defaulted to ``None``, a colour
         is generated accordingly to the platform and theme.
        """

        if base_colour is None:
            self._base_colour = GetBaseColour()
        else:
            self._base_colour = base_colour

        darker3_colour = StepColour(self._base_colour, 60)
        darker5_colour = StepColour(self._base_colour, 40)

        self._gripper_pen1 = wx.Pen(darker5_colour)
        self._gripper_pen2 = wx.Pen(darker3_colour)
        self._gripper_pen3 = wx.WHITE_PEN

[docs]    def Clone(self):
        """ Clones the L{AuiToolBar} art. """

        return AuiDefaultToolBarArt()

[docs]    def SetAGWFlags(self, agwFlags):
        """
        Sets the toolbar art flags.

        :param `agwFlags`: a combination of the following values:

         ==================================== ==================================
         Flag name                            Description
         ==================================== ==================================
         ``AUI_TB_TEXT``                      Shows the text in the toolbar buttons; by default only icons are shown
         ``AUI_TB_NO_TOOLTIPS``               Don't show tooltips on `AuiToolBar` items
         ``AUI_TB_NO_AUTORESIZE``             Do not auto-resize the `AuiToolBar`
         ``AUI_TB_GRIPPER``                   Shows a gripper on the `AuiToolBar`
         ``AUI_TB_OVERFLOW``                  The `AuiToolBar` can contain overflow items
         ``AUI_TB_VERTICAL``                  The `AuiToolBar` is vertical
         ``AUI_TB_HORZ_LAYOUT``               Shows the text and the icons alongside, not vertically stacked. This style must be used with ``AUI_TB_TEXT``
         ``AUI_TB_PLAIN_BACKGROUND``          Don't draw a gradient background on the toolbar
         ``AUI_TB_HORZ_TEXT``                 Combination of ``AUI_TB_HORZ_LAYOUT`` and ``AUI_TB_TEXT``
         ==================================== ==================================

        """

        self._agwFlags = agwFlags

[docs]    def GetAGWFlags(self):
        """
        Returns the L{AuiDefaultToolBarArt} flags. See L{SetAGWFlags} for more
        details.

        :see: L{SetAGWFlags}
        """

        return self._agwFlags

[docs]    def SetFont(self, font):
        """
        Sets the L{AuiDefaultToolBarArt} font.

        :param `font`: a `wx.Font` object.
        """

        self._font = font

[docs]    def SetTextOrientation(self, orientation):
        """
        Sets the text orientation.

        :param `orientation`: can be one of the following constants:

         ==================================== ==================================
         Orientation Switches                 Description
         ==================================== ==================================
         ``AUI_TBTOOL_TEXT_LEFT``             Text in `AuiToolBar` items is aligned left
         ``AUI_TBTOOL_TEXT_RIGHT``            Text in `AuiToolBar` items is aligned right
         ``AUI_TBTOOL_TEXT_TOP``              Text in `AuiToolBar` items is aligned top
         ``AUI_TBTOOL_TEXT_BOTTOM``           Text in `AuiToolBar` items is aligned bottom
         ==================================== ==================================

        """

        self._text_orientation = orientation

[docs]    def GetFont(self):
        """ Returns the L{AuiDefaultToolBarArt} font. """

        return self._font

[docs]    def GetTextOrientation(self):
        """
        Returns the L{AuiDefaultToolBarArt} text orientation. See
        L{SetTextOrientation} for more details.

        :see: L{SetTextOrientation}
        """

        return self._text_orientation

[docs]    def SetOrientation(self, orientation):
        """
        Sets the toolbar tool orientation.

        :param `orientation`: one of ``AUI_TBTOOL_HORIZONTAL``, ``AUI_TBTOOL_VERT_CLOCKWISE`` or
         ``AUI_TBTOOL_VERT_COUNTERCLOCKWISE``.
        """

        self._orientation = orientation

[docs]    def GetOrientation(self):
        """ Returns the toolbar orientation. """

        return self._orientation

[docs]    def DrawBackground(self, dc, wnd, _rect, horizontal=True):
        """
        Draws a toolbar background with a gradient shading.

        :param `dc`: a `wx.DC` device context;
        :param `wnd`: a `wx.Window` derived window;
        :param `_rect`: the L{AuiToolBar} rectangle;
        :param `horizontal`: ``True`` if the toolbar is horizontal, ``False`` if it is vertical.
        """

        rect = wx.Rect(*_rect)

        start_colour = StepColour(self._base_colour, 180)
        end_colour = StepColour(self._base_colour, 85)
        reflex_colour = StepColour(self._base_colour, 95)

        dc.GradientFillLinear(rect, start_colour, end_colour,
                              (horizontal and [wx.SOUTH] or [wx.EAST])[0])

        left = rect.GetLeft()
        right = rect.GetRight()
        top = rect.GetTop()
        bottom = rect.GetBottom()

        dc.SetPen(wx.Pen(reflex_colour))
        if horizontal:
            dc.DrawLine(left, bottom, right+1, bottom)
        else:
            dc.DrawLine(right, top, right, bottom+1)

[docs]    def DrawPlainBackground(self, dc, wnd, _rect):
        """
        Draws a toolbar background with a plain colour.

        This method contrasts with the default behaviour of the L{AuiToolBar} that
        draws a background gradient and this break the window design when putting
        it within a control that has margin between the borders and the toolbar
        (example: put L{AuiToolBar} within a `wx.StaticBoxSizer` that has a plain background).

        :param `dc`: a `wx.DC` device context;
        :param `wnd`: a `wx.Window` derived window;
        :param `_rect`: the L{AuiToolBar} rectangle.
        """

        rect = wx.Rect(*_rect)
        rect.height += 1

        dc.SetBrush(wx.Brush(wx.SystemSettings.GetColour(wx.SYS_COLOUR_3DFACE)))
        dc.DrawRectangle(rect.x - 1, rect.y - 1, rect.width + 2, rect.height + 1)

[docs]    def DrawLabel(self, dc, wnd, item, rect):
        """
        Draws a toolbar item label.

        :param `dc`: a `wx.DC` device context;
        :param `wnd`: a `wx.Window` derived window;
        :param `item`: an instance of L{AuiToolBarItem};
        :param `rect`: the L{AuiToolBarItem} rectangle.
        """

        dc.SetFont(self._font)

        if item.state & AUI_BUTTON_STATE_DISABLED:
            dc.SetTextForeground(wx.SystemSettings.GetColour(wx.SYS_COLOUR_GRAYTEXT))
        else:
            dc.SetTextForeground(wx.SystemSettings.GetColour(wx.SYS_COLOUR_BTNTEXT))

        orient = item.GetOrientation()

        horizontal = orient == AUI_TBTOOL_HORIZONTAL
        # we only care about the text height here since the text
        # will get cropped based on the width of the item
        label_size = GetLabelSize(dc, item.GetLabel(), not horizontal)
        text_width = label_size.GetWidth()
        text_height = label_size.GetHeight()

        if orient == AUI_TBTOOL_HORIZONTAL:
            text_x = rect.x
            text_y = rect.y + (rect.height-text_height)/2
            dc.DrawText(item.GetLabel(), text_x, text_y)

        elif orient == AUI_TBTOOL_VERT_CLOCKWISE:
            text_x = rect.x + (rect.width+text_width)/2
            text_y = rect.y
            dc.DrawRotatedText(item.GetLabel(), text_x, text_y, 270)

        elif AUI_TBTOOL_VERT_COUNTERCLOCKWISE:
            text_x = rect.x + (rect.width-text_width)/2
            text_y = rect.y + text_height
            dc.DrawRotatedText(item.GetLabel(), text_x, text_y, 90)

[docs]    def DrawButton(self, dc, wnd, item, rect):
        """
        Draws a toolbar item button.

        :param `dc`: a `wx.DC` device context;
        :param `wnd`: a `wx.Window` derived window;
        :param `item`: an instance of L{AuiToolBarItem};
        :param `rect`: the L{AuiToolBarItem} rectangle.
        """

        bmp_rect, text_rect = self.GetToolsPosition(dc, item, rect)

        if not item.GetState() & AUI_BUTTON_STATE_DISABLED:

            if item.GetState() & AUI_BUTTON_STATE_PRESSED:

                dc.SetPen(wx.Pen(self._highlight_colour))
                dc.SetBrush(wx.Brush(StepColour(self._highlight_colour, 150)))
                dc.DrawRectangleRect(rect)

            elif item.GetState() & AUI_BUTTON_STATE_HOVER or item.IsSticky():

                dc.SetPen(wx.Pen(self._highlight_colour))
                dc.SetBrush(wx.Brush(StepColour(self._highlight_colour, 170)))

                # draw an even lighter background for checked item hovers (since
                # the hover background is the same colour as the check background)
                if item.GetState() & AUI_BUTTON_STATE_CHECKED:
                    dc.SetBrush(wx.Brush(StepColour(self._highlight_colour, 180)))

                dc.DrawRectangleRect(rect)

            elif item.GetState() & AUI_BUTTON_STATE_CHECKED:

                # it's important to put this code in an else statment after the
                # hover, otherwise hovers won't draw properly for checked items
                dc.SetPen(wx.Pen(self._highlight_colour))
                dc.SetBrush(wx.Brush(StepColour(self._highlight_colour, 170)))
                dc.DrawRectangleRect(rect)

        if item.GetState() & AUI_BUTTON_STATE_DISABLED:
            bmp = item.GetDisabledBitmap()
        else:
            bmp = item.GetBitmap()

        if bmp.IsOk():
            dc.DrawBitmap(bmp, bmp_rect.x, bmp_rect.y, True)

        # set the item's text colour based on if it is disabled
        dc.SetTextForeground(wx.BLACK)
        if item.GetState() & AUI_BUTTON_STATE_DISABLED:
            dc.SetTextForeground(DISABLED_TEXT_COLOUR)

        if self._agwFlags & AUI_TB_TEXT and item.GetLabel() != "":
            self.DrawLabel(dc, wnd, item, text_rect)

[docs]    def DrawDropDownButton(self, dc, wnd, item, rect):
        """
        Draws a toolbar dropdown button.

        :param `dc`: a `wx.DC` device context;
        :param `wnd`: a `wx.Window` derived window;
        :param `item`: an instance of L{AuiToolBarItem};
        :param `rect`: the L{AuiToolBarItem} rectangle.
        """

        dropbmp_x = dropbmp_y = 0

        button_rect = wx.Rect(rect.x, rect.y, rect.width-BUTTON_DROPDOWN_WIDTH, rect.height)
        dropdown_rect = wx.Rect(rect.x+rect.width-BUTTON_DROPDOWN_WIDTH-1, rect.y, BUTTON_DROPDOWN_WIDTH+1, rect.height)

        horizontal = item.GetOrientation() == AUI_TBTOOL_HORIZONTAL

        if horizontal:
            button_rect = wx.Rect(rect.x, rect.y, rect.width-BUTTON_DROPDOWN_WIDTH, rect.height)
            dropdown_rect = wx.Rect(rect.x+rect.width-BUTTON_DROPDOWN_WIDTH-1, rect.y, BUTTON_DROPDOWN_WIDTH+1, rect.height)
        else:
            button_rect = wx.Rect(rect.x, rect.y, rect.width, rect.height-BUTTON_DROPDOWN_WIDTH)
            dropdown_rect = wx.Rect(rect.x, rect.y+rect.height-BUTTON_DROPDOWN_WIDTH-1, rect.width, BUTTON_DROPDOWN_WIDTH+1)

        dropbmp_width = self._button_dropdown_bmp.GetWidth()
        dropbmp_height = self._button_dropdown_bmp.GetHeight()
        if not horizontal:
            tmp = dropbmp_width
            dropbmp_width = dropbmp_height
            dropbmp_height = tmp

        dropbmp_x = dropdown_rect.x + (dropdown_rect.width/2) - dropbmp_width/2
        dropbmp_y = dropdown_rect.y + (dropdown_rect.height/2) - dropbmp_height/2

        bmp_rect, text_rect = self.GetToolsPosition(dc, item, button_rect)

        if item.GetState() & AUI_BUTTON_STATE_PRESSED:

            dc.SetPen(wx.Pen(self._highlight_colour))
            dc.SetBrush(wx.Brush(StepColour(self._highlight_colour, 140)))
            dc.DrawRectangleRect(button_rect)
            dc.DrawRectangleRect(dropdown_rect)

        elif item.GetState() & AUI_BUTTON_STATE_HOVER or item.IsSticky():

            dc.SetPen(wx.Pen(self._highlight_colour))
            dc.SetBrush(wx.Brush(StepColour(self._highlight_colour, 170)))
            dc.DrawRectangleRect(button_rect)
            dc.DrawRectangleRect(dropdown_rect)

        elif item.GetState() & AUI_BUTTON_STATE_CHECKED:
            # it's important to put this code in an else statment after the
            # hover, otherwise hovers won't draw properly for checked items
            dc.SetPen(wx.Pen(self._highlight_colour))
            dc.SetBrush(wx.Brush(StepColour(self._highlight_colour, 170)))
            dc.DrawRectangle(button_rect)
            dc.DrawRectangle(dropdown_rect)

        if item.GetState() & AUI_BUTTON_STATE_DISABLED:

            bmp = item.GetDisabledBitmap()
            dropbmp = self._disabled_button_dropdown_bmp

        else:

            bmp = item.GetBitmap()
            dropbmp = self._button_dropdown_bmp

        if not bmp.IsOk():
            return

        dc.DrawBitmap(bmp, bmp_rect.x, bmp_rect.y, True)
        if horizontal:
            dc.DrawBitmap(dropbmp, dropbmp_x, dropbmp_y, True)
        else:
            dc.DrawBitmap(wx.BitmapFromImage(dropbmp.ConvertToImage().Rotate90(item.GetOrientation() == AUI_TBTOOL_VERT_CLOCKWISE)),
                          dropbmp_x, dropbmp_y, True)

        # set the item's text colour based on if it is disabled
        dc.SetTextForeground(wx.BLACK)
        if item.GetState() & AUI_BUTTON_STATE_DISABLED:
            dc.SetTextForeground(DISABLED_TEXT_COLOUR)

        if self._agwFlags & AUI_TB_TEXT and item.GetLabel() != "":
            self.DrawLabel(dc, wnd, item, text_rect)

[docs]    def DrawControlLabel(self, dc, wnd, item, rect):
        """
        Draws a label for a toolbar control.

        :param `dc`: a `wx.DC` device context;
        :param `wnd`: a `wx.Window` derived window;
        :param `item`: an instance of L{AuiToolBarItem};
        :param `rect`: the L{AuiToolBarItem} rectangle.
        """

        label_size = GetLabelSize(dc, item.GetLabel(), item.GetOrientation() != AUI_TBTOOL_HORIZONTAL)
        text_height = label_size.GetHeight()
        text_width = label_size.GetWidth()

        dc.SetFont(self._font)

        if self._agwFlags & AUI_TB_TEXT:

            tx, text_height = dc.GetTextExtent("ABCDHgj")

        text_width, ty = dc.GetTextExtent(item.GetLabel())

        # don't draw the label if it is wider than the item width
        if text_width > rect.width:
            return

        # set the label's text colour
        dc.SetTextForeground(wx.BLACK)

        text_x = rect.x + (rect.width/2) - (text_width/2) + 1
        text_y = rect.y + rect.height - text_height - 1

        if self._agwFlags & AUI_TB_TEXT and item.GetLabel() != "":
            dc.DrawText(item.GetLabel(), text_x, text_y)

[docs]    def GetLabelSize(self, dc, wnd, item):
        """
        Returns the label size for a toolbar item.

        :param `dc`: a `wx.DC` device context;
        :param `wnd`: a `wx.Window` derived window;
        :param `item`: an instance of L{AuiToolBarItem}.
        """

        dc.SetFont(self._font)
        label_size = GetLabelSize(dc, item.GetLabel(), self._orientation != AUI_TBTOOL_HORIZONTAL)

        return wx.Size(item.GetMinSize().GetWidth(), label_size.GetHeight())

[docs]    def GetToolSize(self, dc, wnd, item):
        """
        Returns the toolbar item size.

        :param `dc`: a `wx.DC` device context;
        :param `wnd`: a `wx.Window` derived window;
        :param `item`: an instance of L{AuiToolBarItem}.
        """

        if not item.GetBitmap().IsOk() and not self._agwFlags & AUI_TB_TEXT:
            return wx.Size(16, 16)

        width = item.GetBitmap().GetWidth()
        height = item.GetBitmap().GetHeight()

        if self._agwFlags & AUI_TB_TEXT:

            dc.SetFont(self._font)
            label_size = GetLabelSize(dc, item.GetLabel(), self.GetOrientation() != AUI_TBTOOL_HORIZONTAL)
            padding = 6

            if self._text_orientation == AUI_TBTOOL_TEXT_BOTTOM:

                if self.GetOrientation() != AUI_TBTOOL_HORIZONTAL:
                    height += 3   # space between top border and bitmap
                    height += 3   # space between bitmap and text
                    padding = 0

                height += label_size.GetHeight()

                if item.GetLabel() != "":
                    width = max(width, label_size.GetWidth()+padding)

            elif self._text_orientation == AUI_TBTOOL_TEXT_RIGHT and item.GetLabel() != "":

                if self.GetOrientation() == AUI_TBTOOL_HORIZONTAL:

                    width += 3  # space between left border and bitmap
                    width += 3  # space between bitmap and text
                    padding = 0

                width += label_size.GetWidth()
                height = max(height, label_size.GetHeight()+padding)

        # if the tool has a dropdown button, add it to the width
        if item.HasDropDown():
            if item.GetOrientation() == AUI_TBTOOL_HORIZONTAL:
                width += BUTTON_DROPDOWN_WIDTH+4
            else:
                height += BUTTON_DROPDOWN_WIDTH+4

        return wx.Size(width, height)

[docs]    def DrawSeparator(self, dc, wnd, _rect):
        """
        Draws a toolbar separator.

        :param `dc`: a `wx.DC` device context;
        :param `wnd`: a `wx.Window` derived window;
        :param `_rect`: the L{AuiToolBarItem} rectangle.
        """

        horizontal = True
        if self._agwFlags & AUI_TB_VERTICAL:
            horizontal = False

        rect = wx.Rect(*_rect)

        if horizontal:

            rect.x += (rect.width/2)
            rect.width = 1
            new_height = (rect.height*3)/4
            rect.y += (rect.height/2) - (new_height/2)
            rect.height = new_height

        else:

            rect.y += (rect.height/2)
            rect.height = 1
            new_width = (rect.width*3)/4
            rect.x += (rect.width/2) - (new_width/2)
            rect.width = new_width

        start_colour = StepColour(self._base_colour, 80)
        end_colour = StepColour(self._base_colour, 80)
        dc.GradientFillLinear(rect, start_colour, end_colour, (horizontal and [wx.SOUTH] or [wx.EAST])[0])

[docs]    def DrawGripper(self, dc, wnd, rect):
        """
        Draws the toolbar gripper.

        :param `dc`: a `wx.DC` device context;
        :param `wnd`: a `wx.Window` derived window;
        :param `rect`: the L{AuiToolBar} rectangle.
        """

        i = 0
        while 1:

            if self._agwFlags & AUI_TB_VERTICAL:

                x = rect.x + (i*4) + 4
                y = rect.y + 3
                if x > rect.GetWidth() - 4:
                    break

            else:

                x = rect.x + 3
                y = rect.y + (i*4) + 4
                if y > rect.GetHeight() - 4:
                    break

            dc.SetPen(self._gripper_pen1)
            dc.DrawPoint(x, y)
            dc.SetPen(self._gripper_pen2)
            dc.DrawPoint(x, y+1)
            dc.DrawPoint(x+1, y)
            dc.SetPen(self._gripper_pen3)
            dc.DrawPoint(x+2, y+1)
            dc.DrawPoint(x+2, y+2)
            dc.DrawPoint(x+1, y+2)

            i += 1

[docs]    def DrawOverflowButton(self, dc, wnd, rect, state):
        """
        Draws the overflow button for the L{AuiToolBar}.

        :param `dc`: a `wx.DC` device context;
        :param `wnd`: a `wx.Window` derived window;
        :param `rect`: the L{AuiToolBar} rectangle;
        :param `state`: the overflow button state.
        """

        if state & AUI_BUTTON_STATE_HOVER or  state & AUI_BUTTON_STATE_PRESSED:

            cli_rect = wnd.GetClientRect()
            light_gray_bg = StepColour(self._highlight_colour, 170)

            if self._agwFlags & AUI_TB_VERTICAL:

                dc.SetPen(wx.Pen(self._highlight_colour))
                dc.DrawLine(rect.x, rect.y, rect.x+rect.width, rect.y)
                dc.SetPen(wx.Pen(light_gray_bg))
                dc.SetBrush(wx.Brush(light_gray_bg))
                dc.DrawRectangle(rect.x, rect.y+1, rect.width, rect.height)

            else:

                dc.SetPen(wx.Pen(self._highlight_colour))
                dc.DrawLine(rect.x, rect.y, rect.x, rect.y+rect.height)
                dc.SetPen(wx.Pen(light_gray_bg))
                dc.SetBrush(wx.Brush(light_gray_bg))
                dc.DrawRectangle(rect.x+1, rect.y, rect.width, rect.height)

        x = rect.x + 1 + (rect.width-self._overflow_bmp.GetWidth())/2
        y = rect.y + 1 + (rect.height-self._overflow_bmp.GetHeight())/2
        dc.DrawBitmap(self._overflow_bmp, x, y, True)

[docs]    def GetElementSize(self, element_id):
        """
        Returns the size of a UI element in the L{AuiToolBar}.

        :param `element_id`: can be one of the following:

         ==================================== ==================================
         Element Identifier                   Description
         ==================================== ==================================
         ``AUI_TBART_SEPARATOR_SIZE``         Separator size in `AuiToolBar`
         ``AUI_TBART_GRIPPER_SIZE``           Gripper size in `AuiToolBar`
         ``AUI_TBART_OVERFLOW_SIZE``          Overflow button size in `AuiToolBar`
         ==================================== ==================================
        """

        if element_id == AUI_TBART_SEPARATOR_SIZE:
            return self._separator_size
        elif element_id == AUI_TBART_GRIPPER_SIZE:
            return self._gripper_size
        elif element_id == AUI_TBART_OVERFLOW_SIZE:
            return self._overflow_size

        return 0

[docs]    def SetElementSize(self, element_id, size):
        """
        Sets the size of a UI element in the L{AuiToolBar}.

        :param `element_id`: can be one of the following:

         ==================================== ==================================
         Element Identifier                   Description
         ==================================== ==================================
         ``AUI_TBART_SEPARATOR_SIZE``         Separator size in `AuiToolBar`
         ``AUI_TBART_GRIPPER_SIZE``           Gripper size in `AuiToolBar`
         ``AUI_TBART_OVERFLOW_SIZE``          Overflow button size in `AuiToolBar`
         ==================================== ==================================

        :param `size`: the new size of the UI element.
        """

        if element_id == AUI_TBART_SEPARATOR_SIZE:
            self._separator_size = size
        elif element_id == AUI_TBART_GRIPPER_SIZE:
            self._gripper_size = size
        elif element_id == AUI_TBART_OVERFLOW_SIZE:
            self._overflow_size = size

[docs]    def ShowDropDown(self, wnd, items):
        """
        Shows the drop down window menu for overflow items.

        :param `wnd`: an instance of `wx.Window`;
        :param `items`: the overflow toolbar items (a Python list).
        """

        menuPopup = wx.Menu()
        items_added = 0

        for item in items:

            if item.GetKind() not in [ITEM_SEPARATOR, ITEM_SPACER, ITEM_CONTROL]:

                text = item.GetShortHelp()
                if text == "":
                    text = item.GetLabel()
                if text == "":
                    text = " "

                kind = item.GetKind()
                m = wx.MenuItem(menuPopup, item.GetId(), text, item.GetShortHelp(), kind)
                orientation = item.GetOrientation()
                item.SetOrientation(AUI_TBTOOL_HORIZONTAL)

                if kind not in [ITEM_CHECK, ITEM_RADIO]:
                    m.SetBitmap(item.GetBitmap())

                item.SetOrientation(orientation)

                menuPopup.AppendItem(m)
                if kind in [ITEM_CHECK, ITEM_RADIO]:
                    state = (item.state & AUI_BUTTON_STATE_CHECKED and [True] or [False])[0]
                    m.Check(state)

                items_added += 1

            else:

                if items_added > 0 and item.GetKind() == ITEM_SEPARATOR:
                    menuPopup.AppendSeparator()

        # find out where to put the popup menu of window items
        pt = wx.GetMousePosition()
        pt = wnd.ScreenToClient(pt)

        # find out the screen coordinate at the bottom of the tab ctrl
        cli_rect = wnd.GetClientRect()
        pt.y = cli_rect.y + cli_rect.height

        cc = ToolbarCommandCapture()
        wnd.PushEventHandler(cc)

        # Adjustments to get slightly better menu placement
        if wx.Platform == "__WXMAC__":
            pt.y += 5
            pt.x -= 5

        wnd.PopupMenu(menuPopup, pt)
        command = cc.GetCommandId()
        wnd.PopEventHandler(True)

        return command

[docs]    def GetToolsPosition(self, dc, item, rect):
        """
        Returns the bitmap and text rectangles for a toolbar item.

        :param `dc`: a `wx.DC` device context;
        :param `item`: an instance of L{AuiToolBarItem};
        :param `rect`: the tool rect.
        """

        text_width = text_height = 0
        horizontal = self._orientation == AUI_TBTOOL_HORIZONTAL
        text_bottom = self._text_orientation == AUI_TBTOOL_TEXT_BOTTOM
        text_right = self._text_orientation == AUI_TBTOOL_TEXT_RIGHT
        bmp_width = item.GetBitmap().GetWidth()
        bmp_height = item.GetBitmap().GetHeight()

        if self._agwFlags & AUI_TB_TEXT:
            dc.SetFont(self._font)
            label_size = GetLabelSize(dc, item.GetLabel(), not horizontal)
            text_height = label_size.GetHeight()
            text_width = label_size.GetWidth()

        bmp_x = bmp_y = text_x = text_y = 0

        if horizontal and text_bottom:
            bmp_x = rect.x + (rect.width/2) - (bmp_width/2)
            bmp_y = rect.y + 3
            text_x = rect.x + (rect.width/2) - (text_width/2)
            text_y = rect.y + ((bmp_y - rect.y) * 2) + bmp_height

        elif horizontal and text_right:
            bmp_x = rect.x + 3
            bmp_y = rect.y + (rect.height/2) - (bmp_height / 2)
            text_x = rect.x + ((bmp_x - rect.x) * 2) + bmp_width
            text_y = rect.y + (rect.height/2) - (text_height/2)

        elif not horizontal and text_bottom:
            bmp_x = rect.x + (rect.width / 2) - (bmp_width / 2)
            bmp_y = rect.y + 3
            text_x = rect.x + (rect.width / 2) - (text_width / 2)
            text_y = rect.y + ((bmp_y - rect.y) * 2) + bmp_height

        bmp_rect = wx.Rect(bmp_x, bmp_y, bmp_width, bmp_height)
        text_rect = wx.Rect(text_x, text_y, text_width, text_height)

        return bmp_rect, text_rect

[docs]class AuiToolBar(wx.PyControl):
    """
    AuiToolBar is a completely owner-drawn toolbar perfectly integrated with the
    AUI layout system. This allows drag and drop of toolbars, docking/floating
    behaviour and the possibility to define "overflow" items in the toolbar itself.

    The default theme that is used is L{AuiDefaultToolBarArt}, which provides a modern,
    glossy look and feel. The theme can be changed by calling L{AuiToolBar.SetArtProvider}.
    """

[docs]    def __init__(self, parent, id=wx.ID_ANY, pos=wx.DefaultPosition,
                 size=wx.DefaultSize, style=0, agwStyle=AUI_TB_DEFAULT_STYLE):
        """
        Default class constructor.

        :param `parent`: the L{AuiToolBar} parent;
        :param `id`: an identifier for the control: a value of -1 is taken to mean a default;
        :param `pos`: the control position. A value of (-1, -1) indicates a default position,
         chosen by either the windowing system or wxPython, depending on platform;
        :param `size`: the control size. A value of (-1, -1) indicates a default size,
         chosen by either the windowing system or wxPython, depending on platform;
        :param `style`: the control window style;
        :param `agwStyle`: the AGW-specific window style. This can be a combination of the
         following bits:

         ==================================== ==================================
         Flag name                            Description
         ==================================== ==================================
         ``AUI_TB_TEXT``                      Shows the text in the toolbar buttons; by default only icons are shown
         ``AUI_TB_NO_TOOLTIPS``               Don't show tooltips on `AuiToolBar` items
         ``AUI_TB_NO_AUTORESIZE``             Do not auto-resize the `AuiToolBar`
         ``AUI_TB_GRIPPER``                   Shows a gripper on the `AuiToolBar`
         ``AUI_TB_OVERFLOW``                  The `AuiToolBar` can contain overflow items
         ``AUI_TB_VERTICAL``                  The `AuiToolBar` is vertical
         ``AUI_TB_HORZ_LAYOUT``               Shows the text and the icons alongside, not vertically stacked. This style must be used with ``AUI_TB_TEXT``
         ``AUI_TB_PLAIN_BACKGROUND``          Don't draw a gradient background on the toolbar
         ``AUI_TB_HORZ_TEXT``                 Combination of ``AUI_TB_HORZ_LAYOUT`` and ``AUI_TB_TEXT``
         ==================================== ==================================

         The default value for `agwStyle` is: ``AUI_TB_DEFAULT_STYLE`` = 0

        """

        wx.PyControl.__init__(self, parent, id, pos, size, style|wx.BORDER_NONE)

        self._sizer = wx.BoxSizer(wx.HORIZONTAL)
        self.SetSizer(self._sizer)
        self._button_width = -1
        self._button_height = -1
        self._sizer_element_count = 0
        self._action_pos = wx.Point(-1, -1)
        self._action_item = None
        self._tip_item = None
        self._art = AuiDefaultToolBarArt()
        self._tool_packing = 2
        self._tool_border_padding = 3
        self._tool_text_orientation = AUI_TBTOOL_TEXT_BOTTOM
        self._tool_orientation = AUI_TBTOOL_HORIZONTAL
        self._tool_alignment = wx.EXPAND
        self._gripper_sizer_item = None
        self._overflow_sizer_item = None
        self._dragging = False

        self._agwStyle = self._originalStyle = agwStyle

        self._gripper_visible = (self._agwStyle & AUI_TB_GRIPPER and [True] or [False])[0]
        self._overflow_visible = (self._agwStyle & AUI_TB_OVERFLOW and [True] or [False])[0]
        self._overflow_state = 0
        self._custom_overflow_prepend = []
        self._custom_overflow_append = []

        self._items = []

        self.SetMargins(5, 5, 2, 2)
        self.SetFont(wx.NORMAL_FONT)
        self._art.SetAGWFlags(self._agwStyle)
        self.SetExtraStyle(wx.WS_EX_PROCESS_IDLE)

        if agwStyle & AUI_TB_HORZ_LAYOUT:
            self.SetToolTextOrientation(AUI_TBTOOL_TEXT_RIGHT)
        elif agwStyle & AUI_TB_VERTICAL:
            if agwStyle & AUI_TB_CLOCKWISE:
                self.SetToolOrientation(AUI_TBTOOL_VERT_CLOCKWISE)
            elif agwStyle & AUI_TB_COUNTERCLOCKWISE:
                self.SetToolOrientation(AUI_TBTOOL_VERT_COUNTERCLOCKWISE)

        self.SetBackgroundStyle(wx.BG_STYLE_CUSTOM)

        self.Bind(wx.EVT_SIZE, self.OnSize)
        self.Bind(wx.EVT_IDLE, self.OnIdle)
        self.Bind(wx.EVT_ERASE_BACKGROUND, self.OnEraseBackground)
        self.Bind(wx.EVT_PAINT, self.OnPaint)
        self.Bind(wx.EVT_LEFT_DOWN, self.OnLeftDown)
        self.Bind(wx.EVT_LEFT_DCLICK, self.OnLeftDown)
        self.Bind(wx.EVT_LEFT_UP, self.OnLeftUp)
        self.Bind(wx.EVT_RIGHT_DOWN, self.OnRightDown)
        self.Bind(wx.EVT_RIGHT_DCLICK, self.OnRightDown)
        self.Bind(wx.EVT_RIGHT_UP, self.OnRightUp)
        self.Bind(wx.EVT_MIDDLE_DOWN, self.OnMiddleDown)
        self.Bind(wx.EVT_MIDDLE_DCLICK, self.OnMiddleDown)
        self.Bind(wx.EVT_MIDDLE_UP, self.OnMiddleUp)
        self.Bind(wx.EVT_MOTION, self.OnMotion)
        self.Bind(wx.EVT_LEAVE_WINDOW, self.OnLeaveWindow)
        self.Bind(wx.EVT_SET_CURSOR, self.OnSetCursor)

[docs]    def SetWindowStyleFlag(self, style):
        """
        Sets the style of the window.

        :param `style`: the new window style.

        :note: Please note that some styles cannot be changed after the window
         creation and that `Refresh` might need to be be called after changing the
         others for the change to take place immediately.

        :note: Overridden from `wx.PyControl`.
        """

        wx.PyControl.SetWindowStyleFlag(self, style|wx.BORDER_NONE)

[docs]    def SetAGWWindowStyleFlag(self, agwStyle):
        """
        Sets the AGW-specific style of the window.

        :param `agwStyle`: the new window style. This can be a combination of the
         following bits:

         ==================================== ==================================
         Flag name                            Description
         ==================================== ==================================
         ``AUI_TB_TEXT``                      Shows the text in the toolbar buttons; by default only icons are shown
         ``AUI_TB_NO_TOOLTIPS``               Don't show tooltips on `AuiToolBar` items
         ``AUI_TB_NO_AUTORESIZE``             Do not auto-resize the `AuiToolBar`
         ``AUI_TB_GRIPPER``                   Shows a gripper on the `AuiToolBar`
         ``AUI_TB_OVERFLOW``                  The `AuiToolBar` can contain overflow items
         ``AUI_TB_VERTICAL``                  The `AuiToolBar` is vertical
         ``AUI_TB_HORZ_LAYOUT``               Shows the text and the icons alongside, not vertically stacked. This style must be used with ``AUI_TB_TEXT``
         ``AUI_TB_PLAIN_BACKGROUND``          Don't draw a gradient background on the toolbar
         ``AUI_TB_HORZ_TEXT``                 Combination of ``AUI_TB_HORZ_LAYOUT`` and ``AUI_TB_TEXT``
         ==================================== ==================================

        :note: Please note that some styles cannot be changed after the window
         creation and that `Refresh` might need to be be called after changing the
         others for the change to take place immediately.
        """

        self._agwStyle = self._originalStyle = agwStyle

        if self._art:
            self._art.SetAGWFlags(self._agwStyle)

        if agwStyle & AUI_TB_GRIPPER:
            self._gripper_visible = True
        else:
            self._gripper_visible = False

        if agwStyle & AUI_TB_OVERFLOW:
            self._overflow_visible = True
        else:
            self._overflow_visible = False

        if agwStyle & AUI_TB_HORZ_LAYOUT:
            self.SetToolTextOrientation(AUI_TBTOOL_TEXT_RIGHT)
        else:
            self.SetToolTextOrientation(AUI_TBTOOL_TEXT_BOTTOM)

        if agwStyle & AUI_TB_VERTICAL:
            if agwStyle & AUI_TB_CLOCKWISE:
                self.SetToolOrientation(AUI_TBTOOL_VERT_CLOCKWISE)
            elif agwStyle & AUI_TB_COUNTERCLOCKWISE:
                self.SetToolOrientation(AUI_TBTOOL_VERT_COUNTERCLOCKWISE)

[docs]    def GetAGWWindowStyleFlag(self):
        """
        Returns the AGW-specific window style flag.

        :see: L{SetAGWWindowStyleFlag} for an explanation of various AGW-specific style.
        """

        return self._agwStyle

[docs]    def SetArtProvider(self, art):
        """
        Instructs L{AuiToolBar} to use art provider specified by parameter `art`
        for all drawing calls. This allows plugable look-and-feel features.

        :param `art`: an art provider.

        :note: The previous art provider object, if any, will be deleted by L{AuiToolBar}.
        """

        del self._art
        self._art = art

        if self._art:
            self._art.SetAGWFlags(self._agwStyle)
            self._art.SetTextOrientation(self._tool_text_orientation)
            self._art.SetOrientation(self._tool_orientation)

[docs]    def GetArtProvider(self):
        """ Returns the current art provider being used. """

        return self._art

[docs]    def AddSimpleTool(self, tool_id, label, bitmap, short_help_string="", kind=ITEM_NORMAL, target=None):
        """
        Adds a tool to the toolbar. This is the simplest method you can use to
        ass an item to the L{AuiToolBar}.

        :param `tool_id`: an integer by which the tool may be identified in subsequent operations;
        :param `label`: the toolbar tool label;
        :param `bitmap`: the primary tool bitmap;
        :param `short_help_string`: this string is used for the tools tooltip;
        :param `kind`: the item kind. Can be one of the following:

         ========================  =============================
         Item Kind                 Description
         ========================  =============================
         ``ITEM_CONTROL``          The item in the `AuiToolBar` is a control
         ``ITEM_LABEL``            The item in the `AuiToolBar` is a text label
         ``ITEM_SPACER``           The item in the `AuiToolBar` is a spacer
         ``ITEM_SEPARATOR``        The item in the `AuiToolBar` is a separator
         ``ITEM_CHECK``            The item in the `AuiToolBar` is a toolbar check item
         ``ITEM_NORMAL``           The item in the `AuiToolBar` is a standard toolbar item
         ``ITEM_RADIO``            The item in the `AuiToolBar` is a toolbar radio item
         ========================  =============================

        :param `target`: a custom string indicating that an instance of L{framemanager.AuiPaneInfo}
         has been minimized into this toolbar.
        """

        return self.AddTool(tool_id, label, bitmap, wx.NullBitmap, kind, short_help_string, "", None, target)

[docs]    def AddToggleTool(self, tool_id, bitmap, disabled_bitmap, toggle=False, client_data=None, short_help_string="", long_help_string=""):
        """
        Adds a toggle tool to the toolbar.

        :param `tool_id`: an integer by which the tool may be identified in subsequent operations;
        :param `bitmap`: the primary tool bitmap;
        :param `disabled_bitmap`: the bitmap to use when the tool is disabled. If it is equal to
         `wx.NullBitmap`, the disabled bitmap is automatically generated by greing the normal one;
        :param `client_data`: whatever Python object to associate with the toolbar item;
        :param `short_help_string`: this string is used for the tools tooltip;
        :param `long_help_string`: this string is shown in the statusbar (if any) of the parent
         frame when the mouse pointer is inside the tool.
        """

        kind = (toggle and [ITEM_CHECK] or [ITEM_NORMAL])[0]
        return self.AddTool(tool_id, "", bitmap, disabled_bitmap, kind, short_help_string, long_help_string, client_data)

[docs]    def AddTool(self, tool_id, label, bitmap, disabled_bitmap, kind, short_help_string='', long_help_string='', client_data=None, target=None):
        """
        Adds a tool to the toolbar. This is the full feature version of L{AddTool}.

        :param `tool_id`: an integer by which the tool may be identified in subsequent operations;
        :param `label`: the toolbar tool label;
        :param `bitmap`: the primary tool bitmap;
        :param `disabled_bitmap`: the bitmap to use when the tool is disabled. If it is equal to
         `wx.NullBitmap`, the disabled bitmap is automatically generated by greing the normal one;
        :param `kind`: the item kind. Can be one of the following:

         ========================  =============================
         Item Kind                 Description
         ========================  =============================
         ``ITEM_CONTROL``          The item in the `AuiToolBar` is a control
         ``ITEM_LABEL``            The item in the `AuiToolBar` is a text label
         ``ITEM_SPACER``           The item in the `AuiToolBar` is a spacer
         ``ITEM_SEPARATOR``        The item in the `AuiToolBar` is a separator
         ``ITEM_CHECK``            The item in the `AuiToolBar` is a toolbar check item
         ``ITEM_NORMAL``           The item in the `AuiToolBar` is a standard toolbar item
         ``ITEM_RADIO``            The item in the `AuiToolBar` is a toolbar radio item
         ========================  =============================

        :param `short_help_string`: this string is used for the tools tooltip;
        :param `long_help_string`: this string is shown in the statusbar (if any) of the parent
         frame when the mouse pointer is inside the tool.
        :param `client_data`: whatever Python object to associate with the toolbar item.
        :param `target`: a custom string indicating that an instance of L{framemanager.AuiPaneInfo}
         has been minimized into this toolbar.
        """

        item = AuiToolBarItem()
        item.window = None
        item.label = label
        item.bitmap = bitmap
        item.disabled_bitmap = disabled_bitmap
        item.short_help = short_help_string
        item.long_help = long_help_string
        item.target = target
        item.active = True
        item.dropdown = False
        item.spacer_pixels = 0

        if tool_id == wx.ID_ANY:
            tool_id = wx.NewId()

        item.id = tool_id
        item.state = 0
        item.proportion = 0
        item.kind = kind
        item.sizer_item = None
        item.min_size = wx.Size(-1, -1)
        item.user_data = 0
        item.sticky = False
        item.orientation = self._tool_orientation

        if not item.disabled_bitmap.IsOk():
            # no disabled bitmap specified, we need to make one
            if item.bitmap.IsOk():
                item.disabled_bitmap = MakeDisabledBitmap(item.bitmap)

        self._items.append(item)
        return self._items[-1]

[docs]    def AddCheckTool(self, tool_id, label, bitmap, disabled_bitmap, short_help_string="", long_help_string="", client_data=None):
        """
        Adds a new check (or toggle) tool to the L{AuiToolBar}.

        :see: L{AddTool}.
        """

        return self.AddTool(tool_id, label, bitmap, disabled_bitmap, ITEM_CHECK, short_help_string, long_help_string, client_data)

[docs]    def AddRadioTool(self, tool_id, label, bitmap, disabled_bitmap, short_help_string="", long_help_string="", client_data=None):
        """
        Adds a new radio tool to the toolbar.

        Consecutive radio tools form a radio group such that exactly one button
        in the group is pressed at any moment, in other words whenever a button
        in the group is pressed the previously pressed button is automatically
        released. You should avoid having the radio groups of only one element
        as it would be impossible for the user to use such button.

        :note: By default, the first button in the radio group is initially pressed,
         the others are not.

        :see: L{AddTool}.
        """

        return self.AddTool(tool_id, label, bitmap, disabled_bitmap, ITEM_RADIO, short_help_string, long_help_string, client_data)

[docs]    def AddControl(self, control, label=""):
        """
        Adds any control to the toolbar, typically e.g. a combobox.

        :param `control`: the control to be added;
        :param `label`: the label which appears if the control goes into the
         overflow items in the toolbar.
        """

        item = AuiToolBarItem()
        item.window = control
        item.label = label
        item.bitmap = wx.NullBitmap
        item.disabled_bitmap = wx.NullBitmap
        item.active = True
        item.dropdown = False
        item.spacer_pixels = 0
        item.id = control.GetId()
        item.state = 0
        item.proportion = 0
        item.kind = ITEM_CONTROL
        item.sizer_item = None
        item.min_size = control.GetEffectiveMinSize()
        item.user_data = 0
        item.sticky = False
        item.orientation = self._tool_orientation

        self._items.append(item)
        return self._items[-1]

[docs]    def AddLabel(self, tool_id, label="", width=0):
        """
        Adds a label tool to the L{AuiToolBar}.

        :param `tool_id`: an integer by which the tool may be identified in subsequent operations;
        :param `label`: the toolbar tool label;
        :param `width`: the tool width.
        """

        min_size = wx.Size(-1, -1)

        if width != -1:
            min_size.x = width

        item = AuiToolBarItem()
        item.window = None
        item.label = label
        item.bitmap = wx.NullBitmap
        item.disabled_bitmap = wx.NullBitmap
        item.active = True
        item.dropdown = False
        item.spacer_pixels = 0

        if tool_id == wx.ID_ANY:
            tool_id = wx.NewId()

        item.id = tool_id
        item.state = 0
        item.proportion = 0
        item.kind = ITEM_LABEL
        item.sizer_item = None
        item.min_size = min_size
        item.user_data = 0
        item.sticky = False
        item.orientation = self._tool_orientation

        self._items.append(item)
        return self._items[-1]

[docs]    def AddSeparator(self):
        """ Adds a separator for spacing groups of tools. """

        item = AuiToolBarItem()
        item.window = None
        item.label = ""
        item.bitmap = wx.NullBitmap
        item.disabled_bitmap = wx.NullBitmap
        item.active = True
        item.dropdown = False
        item.id = -1
        item.state = 0
        item.proportion = 0
        item.kind = ITEM_SEPARATOR
        item.sizer_item = None
        item.min_size = wx.Size(-1, -1)
        item.user_data = 0
        item.sticky = False
        item.orientation = self._tool_orientation

        self._items.append(item)
        return self._items[-1]

[docs]    def AddSpacer(self, pixels):
        """
        Adds a spacer for spacing groups of tools.

        :param `pixels`: the width of the spacer.
        """

        item = AuiToolBarItem()
        item.window = None
        item.label = ""
        item.bitmap = wx.NullBitmap
        item.disabled_bitmap = wx.NullBitmap
        item.active = True
        item.dropdown = False
        item.spacer_pixels = pixels
        item.id = -1
        item.state = 0
        item.proportion = 0
        item.kind = ITEM_SPACER
        item.sizer_item = None
        item.min_size = wx.Size(-1, -1)
        item.user_data = 0
        item.sticky = False
        item.orientation = self._tool_orientation

        self._items.append(item)
        return self._items[-1]

[docs]    def AddStretchSpacer(self, proportion=1):
        """
        Adds a stretchable spacer for spacing groups of tools.

        :param `proportion`: the stretchable spacer proportion.
        """

        item = AuiToolBarItem()
        item.window = None
        item.label = ""
        item.bitmap = wx.NullBitmap
        item.disabled_bitmap = wx.NullBitmap
        item.active = True
        item.dropdown = False
        item.spacer_pixels = 0
        item.id = -1
        item.state = 0
        item.proportion = proportion
        item.kind = ITEM_SPACER
        item.sizer_item = None
        item.min_size = wx.Size(-1, -1)
        item.user_data = 0
        item.sticky = False
        item.orientation = self._tool_orientation

        self._items.append(item)
        return self._items[-1]

[docs]    def Clear(self):
        """ Deletes all the tools in the L{AuiToolBar}. """

        self._items = []
        self._sizer_element_count = 0

[docs]    def ClearTools(self):
        """ Deletes all the tools in the L{AuiToolBar}. """

        self.Clear()

[docs]    def DeleteTool(self, tool_id):
        """
        Removes the specified tool from the toolbar and deletes it.

        :param `tool_id`: the L{AuiToolBarItem} identifier.

        :returns: ``True`` if the tool was deleted, ``False`` otherwise.

        :note: Note that it is unnecessary to call L{Realize} for the change to
         take place, it will happen immediately.
        """

        idx = self.GetToolIndex(tool_id)

        if idx >= 0 and idx < len(self._items):
            self._items.pop(idx)
            self.Realize()
            return True

        return False

[docs]    def DeleteToolByPos(self, pos):
        """
        This function behaves like L{DeleteTool} but it deletes the tool at the
        specified position and not the one with the given id.

        :param `pos`: the tool position.

        :see: L{DeleteTool}
        """

        if pos >= 0 and pos < len(self._items):

            self._items.pop(pos)
            self.Realize()
            return True

        return False

[docs]    def FindControl(self, id):
        """
        Returns a pointer to the control identified by `id` or ``None`` if no corresponding
        control is found.

        :param `id`: the control identifier.
        """

        wnd = self.FindWindow(id)
        return wnd

[docs]    def FindTool(self, tool_id):
        """
        Finds a tool for the given tool id.

        :param `tool_id`: the L{AuiToolBarItem} identifier.
        """

        for item in self._items:
            if item.id == tool_id:
                return item

        return None

[docs]    def FindToolByLabel(self, label):
        """
        Finds a tool for the given label.

        :param `tool_id`: the L{AuiToolBarItem} label.
        """

        for item in self._items:
            if item.label == label:
                return item

        return None

[docs]    def FindToolForPosition(self, x, y):
        """
        Finds a tool for the given mouse position.

        :param `x`: mouse `x` position;
        :param `y`: mouse `y` position.

        :returns: a pointer to a L{AuiToolBarItem} if a tool is found, or ``None`` otherwise.
        """

        for i, item in enumerate(self._items):
            if not item.sizer_item:
                continue

            rect = item.sizer_item.GetRect()
            if rect.Contains((x,y)):

                # if the item doesn't fit on the toolbar, return None
                if not self.GetToolFitsByIndex(i):
                    return None

                return item

        return None

[docs]    def HitTest(self, x, y):
        """
        Finds a tool for the given mouse position.

        :param `x`: mouse `x` position;
        :param `y`: mouse `y` position.

        :returns: a pointer to a L{AuiToolBarItem} if a tool is found, or ``None`` otherwise.

        :note: This method is similar to L{FindToolForPosition} but it works with absolute coordinates.
        """

        return self.FindToolForPosition(*self.ScreenToClient((x,y)))

[docs]    def FindToolForPositionWithPacking(self, x, y):
        """
        Finds a tool for the given mouse position, taking into account also the
        tool packing.

        :param `x`: mouse `x` position;
        :param `y`: mouse `y` position.

        :returns: a pointer to a L{AuiToolBarItem} if a tool is found, or ``None`` otherwise.
        """

        count = len(self._items)

        for i, item in enumerate(self._items):
            if not item.sizer_item:
                continue

            rect = item.sizer_item.GetRect()

            # apply tool packing
            if i+1 < count:
                rect.width += self._tool_packing

            if rect.Contains((x,y)):

                # if the item doesn't fit on the toolbar, return None
                if not self.GetToolFitsByIndex(i):
                    return None

                return item

        return None

[docs]    def FindToolByIndex(self, pos):
        """
        Finds a tool for the given tool position in the L{AuiToolBar}.

        :param `pos`: the tool position in the toolbar.

        :returns: a pointer to a L{AuiToolBarItem} if a tool is found, or ``None`` otherwise.
        """

        if pos < 0 or pos >= len(self._items):
            return None

        return self._items[pos]

[docs]    def SetToolBitmapSize(self, size):
        """
        Sets the default size of each tool bitmap. The default bitmap size is
        16 by 15 pixels.

        :param `size`: the size of the bitmaps in the toolbar.

        :note: This should be called to tell the toolbar what the tool bitmap
         size is. Call it before you add tools.

        :note: Note that this is the size of the bitmap you pass to L{AddTool},
         and not the eventual size of the tool button.

        :todo: Add `wx.ToolBar` compatibility, actually implementing this method.
        """

        # TODO: wx.ToolBar compatibility
        pass

[docs]    def GetToolBitmapSize(self):
        """
        Returns the size of bitmap that the toolbar expects to have. The default
        bitmap size is 16 by 15 pixels.

        :note: Note that this is the size of the bitmap you pass to L{AddTool},
         and not the eventual size of the tool button.

        :todo: Add `wx.ToolBar` compatibility, actually implementing this method.
        """

        # TODO: wx.ToolBar compatibility
        return wx.Size(16, 15)

[docs]    def SetToolProportion(self, tool_id, proportion):
        """
        Sets the tool proportion in the toolbar.

        :param `tool_id`: the L{AuiToolBarItem} identifier;
        :param `proportion`: the tool proportion in the toolbar.
        """

        item = self.FindTool(tool_id)
        if not item:
            return

        item.proportion = proportion

[docs]    def GetToolProportion(self, tool_id):
        """
        Returns the tool proportion in the toolbar.

        :param `tool_id`: the L{AuiToolBarItem} identifier.
        """

        item = self.FindTool(tool_id)
        if not item:
            return

        return item.proportion

[docs]    def SetToolSeparation(self, separation):
        """
        Sets the separator size for the toolbar.

        :param `separation`: the separator size in pixels.
        """

        if self._art:
            self._art.SetElementSize(AUI_TBART_SEPARATOR_SIZE, separation)

[docs]    def GetToolSeparation(self):
        """ Returns the separator size for the toolbar, in pixels. """

        if self._art:
            return self._art.GetElementSize(AUI_TBART_SEPARATOR_SIZE)

        return 5

[docs]    def SetToolDropDown(self, tool_id, dropdown):
        """
        Assigns a drop down window menu to the toolbar item.

        :param `tool_id`: the L{AuiToolBarItem} identifier;
        :param `dropdown`: whether to assign a drop down menu or not.
        """

        item = self.FindTool(tool_id)
        if not item:
            return

        item.dropdown = dropdown

[docs]    def GetToolDropDown(self, tool_id):
        """
        Returns whether the toolbar item identified by `tool_id` has an associated
        drop down window menu or not.

        :param `tool_id`: the L{AuiToolBarItem} identifier.
        """

        item = self.FindTool(tool_id)
        if not item:
            return

        return item.dropdown

[docs]    def SetToolSticky(self, tool_id, sticky):
        """
        Sets the toolbar item as sticky or non-sticky.

        :param `tool_id`: the L{AuiToolBarItem} identifier;
        :param `sticky`: whether the tool should be sticky or not.
        """

        # ignore separators
        if tool_id == -1:
            return

        item = self.FindTool(tool_id)
        if not item:
            return

        if item.sticky == sticky:
            return

        item.sticky = sticky

        self.Refresh(False)
        self.Update()

[docs]    def GetToolSticky(self, tool_id):
        """
        Returns whether the toolbar item identified by `tool_id` has a sticky
        behaviour or not.

        :param `tool_id`: the L{AuiToolBarItem} identifier.
        """

        item = self.FindTool(tool_id)
        if not item:
            return

        return item.sticky

[docs]    def SetToolBorderPadding(self, padding):
        """
        Sets the padding between the tool border and the label.

        :param `padding`: the padding in pixels.
        """

        self._tool_border_padding = padding

[docs]    def GetToolBorderPadding(self):
        """ Returns the padding between the tool border and the label, in pixels. """

        return self._tool_border_padding

[docs]    def SetToolTextOrientation(self, orientation):
        """
        Sets the label orientation for the toolbar items.

        :param `orientation`: the L{AuiToolBarItem} label orientation.
        """

        self._tool_text_orientation = orientation

        if self._art:
            self._art.SetTextOrientation(orientation)

[docs]    def GetToolTextOrientation(self):
        """ Returns the label orientation for the toolbar items. """

        return self._tool_text_orientation

[docs]    def SetToolOrientation(self, orientation):
        """
        Sets the tool orientation for the toolbar items.

        :param `orientation`: the L{AuiToolBarItem} orientation.
        """

        self._tool_orientation = orientation
        if self._art:
            self._art.SetOrientation(orientation)

[docs]    def GetToolOrientation(self):
        """ Returns the orientation for the toolbar items. """

        return self._tool_orientation

[docs]    def SetToolPacking(self, packing):
        """
        Sets the value used for spacing tools. The default value is 1 pixel.

        :param `packing`: the value for packing.
        """

        self._tool_packing = packing

[docs]    def GetToolPacking(self):
        """ Returns the value used for spacing tools. The default value is 1 pixel. """

        return self._tool_packing

[docs]    def SetOrientation(self, orientation):
        """
        Sets the toolbar orientation.

        :param `orientation`: either ``wx.VERTICAL`` or ``wx.HORIZONTAL``.

        :note: This can be temporarily overridden by L{AuiManager} when floating and
         docking a L{AuiToolBar}.
        """

        pass

[docs]    def SetMargins(self, left=-1, right=-1, top=-1, bottom=-1):
        """
        Set the values to be used as margins for the toolbar.

        :param `left`: the left toolbar margin;
        :param `right`: the right toolbar margin;
        :param `top`: the top toolbar margin;
        :param `bottom`: the bottom toolbar margin.
        """

        if left != -1:
            self._left_padding = left
        if right != -1:
            self._right_padding = right
        if top != -1:
            self._top_padding = top
        if bottom != -1:
            self._bottom_padding = bottom

[docs]    def SetMarginsSize(self, size):
        """
        Set the values to be used as margins for the toolbar.

        :param `size`: the margin size (an instance of `wx.Size`).
        """

        self.SetMargins(size.x, size.x, size.y, size.y)

[docs]    def SetMarginsXY(self, x, y):
        """
        Set the values to be used as margins for the toolbar.

        :param `x`: left margin, right margin and inter-tool separation value;
        :param `y`: top margin, bottom margin and inter-tool separation value.
        """

        self.SetMargins(x, x, y, y)

[docs]    def GetGripperVisible(self):
        """ Returns whether the toolbar gripper is visible or not. """

        return self._gripper_visible

[docs]    def SetGripperVisible(self, visible):
        """
        Sets whether the toolbar gripper is visible or not.

        :param `visible`: ``True`` for a visible gripper, ``False`` otherwise.
        """

        self._gripper_visible = visible
        if visible:
            self._agwStyle |= AUI_TB_GRIPPER
        else:
            self._agwStyle &= ~AUI_TB_GRIPPER

        self.Realize()
        self.Refresh(False)

[docs]    def GetOverflowVisible(self):
        """ Returns whether the overflow button is visible or not. """

        return self._overflow_visible

[docs]    def SetOverflowVisible(self, visible):
        """
        Sets whether the overflow button is visible or not.

        :param `visible`: ``True`` for a visible overflow button, ``False`` otherwise.
        """

        self._overflow_visible = visible
        if visible:
            self._agwStyle |= AUI_TB_OVERFLOW
        else:
            self._agwStyle &= ~AUI_TB_OVERFLOW

        self.Refresh(False)

[docs]    def SetFont(self, font):
        """
        Sets the L{AuiToolBar} font.

        :param `font`: a `wx.Font` object.

        :note: Overridden from `wx.PyControl`.
        """

        res = wx.PyControl.SetFont(self, font)

        if self._art:
            self._art.SetFont(font)

        return res

[docs]    def SetHoverItem(self, pitem):
        """
        Sets a toolbar item to be currently hovered by the mouse.

        :param `pitem`: an instance of L{AuiToolBarItem}.
        """

        former_hover = None

        for item in self._items:

            if item.state & AUI_BUTTON_STATE_HOVER:
                former_hover = item

            item.state &= ~AUI_BUTTON_STATE_HOVER

        if pitem:
            pitem.state |= AUI_BUTTON_STATE_HOVER

        if former_hover != pitem:
            self.Refresh(False)
            self.Update()

[docs]    def SetPressedItem(self, pitem):
        """
        Sets a toolbar item to be currently in a "pressed" state.

        :param `pitem`: an instance of L{AuiToolBarItem}.
        """

        former_item = None

        for item in self._items:

            if item.state & AUI_BUTTON_STATE_PRESSED:
                former_item = item

            item.state &= ~AUI_BUTTON_STATE_PRESSED

        if pitem:
            pitem.state &= ~AUI_BUTTON_STATE_HOVER
            pitem.state |= AUI_BUTTON_STATE_PRESSED

        if former_item != pitem:
            self.Refresh(False)
            self.Update()

[docs]    def RefreshOverflowState(self):
        """ Refreshes the overflow button. """

        if not self._overflow_sizer_item:
            self._overflow_state = 0
            return

        overflow_state = 0
        overflow_rect = self.GetOverflowRect()

        # find out the mouse's current position
        pt = wx.GetMousePosition()
        pt = self.ScreenToClient(pt)

        # find out if the mouse cursor is inside the dropdown rectangle
        if overflow_rect.Contains((pt.x, pt.y)):

            if _VERSION_STRING < "2.9":
                leftDown = wx.GetMouseState().LeftDown()
            else:
                leftDown = wx.GetMouseState().LeftIsDown()

            if leftDown:
                overflow_state = AUI_BUTTON_STATE_PRESSED
            else:
                overflow_state = AUI_BUTTON_STATE_HOVER

        if overflow_state != self._overflow_state:
            self._overflow_state = overflow_state
            self.Refresh(False)
            self.Update()

        self._overflow_state = overflow_state

[docs]    def ToggleTool(self, tool_id, state):
        """
        Toggles a tool on or off. This does not cause any event to get emitted.

        :param `tool_id`: tool in question.
        :param `state`: if ``True``, toggles the tool on, otherwise toggles it off.

        :note: This only applies to a tool that has been specified as a toggle tool.
        """

        tool = self.FindTool(tool_id)

        if tool:
            if tool.kind not in [ITEM_CHECK, ITEM_RADIO]:
                return

            if tool.kind == ITEM_RADIO:
                idx = self.GetToolIndex(tool_id)
                if idx >= 0 and idx < len(self._items):
                    for i in xrange(idx, len(self._items)):
                        tool = self.FindToolByIndex(i)
                        if tool.kind != ITEM_RADIO:
                            break
                        tool.state &= ~AUI_BUTTON_STATE_CHECKED

                    for i in xrange(idx, -1, -1):
                        tool = self.FindToolByIndex(i)
                        if tool.kind != ITEM_RADIO:
                            break
                        tool.state &= ~AUI_BUTTON_STATE_CHECKED

                    tool = self.FindTool(tool_id)
                    tool.state |= AUI_BUTTON_STATE_CHECKED
            else:
                if state == True:
                    tool.state |= AUI_BUTTON_STATE_CHECKED
                else:
                    tool.state &= ~AUI_BUTTON_STATE_CHECKED

[docs]    def GetToolToggled(self, tool_id):
        """
        Returns whether a tool is toggled or not.

        :param `tool_id`: the toolbar item identifier.

        :note: This only applies to a tool that has been specified as a toggle tool.
        """

        tool = self.FindTool(tool_id)

        if tool:
            if tool.kind not in [ITEM_CHECK, ITEM_RADIO]:
                return False

            return (tool.state & AUI_BUTTON_STATE_CHECKED and [True] or [False])[0]

        return False

[docs]    def EnableTool(self, tool_id, state):
        """
        Enables or disables the tool.

        :param `tool_id`: identifier for the tool to enable or disable.
        :param `state`: if ``True``, enables the tool, otherwise disables it.
        """

        tool = self.FindTool(tool_id)

        if tool:

            if state == True:
                tool.state &= ~AUI_BUTTON_STATE_DISABLED
            else:
                tool.state |= AUI_BUTTON_STATE_DISABLED

[docs]    def GetToolEnabled(self, tool_id):
        """
        Returns whether the tool identified by `tool_id` is enabled or not.

        :param `tool_id`: the tool identifier.
        """

        tool = self.FindTool(tool_id)

        if tool:
            return (tool.state & AUI_BUTTON_STATE_DISABLED and [False] or [True])[0]

        return False

[docs]    def GetToolLabel(self, tool_id):
        """
        Returns the tool label for the tool identified by `tool_id`.

        :param `tool_id`: the tool identifier.
        """

        tool = self.FindTool(tool_id)
        if not tool:
            return ""

        return tool.label

[docs]    def SetToolLabel(self, tool_id, label):
        """
        Sets the tool label for the tool identified by `tool_id`.

        :param `tool_id`: the tool identifier;
        :param `label`: the new toolbar item label.
        """

        tool = self.FindTool(tool_id)
        if tool:
            tool.label = label

[docs]    def GetToolBitmap(self, tool_id):
        """
        Returns the tool bitmap for the tool identified by `tool_id`.

        :param `tool_id`: the tool identifier.
        """

        tool = self.FindTool(tool_id)
        if not tool:
            return wx.NullBitmap

        return tool.bitmap

[docs]    def SetToolBitmap(self, tool_id, bitmap):
        """
        Sets the tool bitmap for the tool identified by `tool_id`.

        :param `tool_id`: the tool identifier;
        :param `bitmap`: the new bitmap for the toolbar item (an instance of `wx.Bitmap`).
        """

        tool = self.FindTool(tool_id)
        if tool:
            tool.bitmap = bitmap

[docs]    def SetToolNormalBitmap(self, tool_id, bitmap):
        """
        Sets the tool bitmap for the tool identified by `tool_id`.

        :param `tool_id`: the tool identifier;
        :param `bitmap`: the new bitmap for the toolbar item (an instance of `wx.Bitmap`).
        """

        self.SetToolBitmap(tool_id, bitmap)

[docs]    def SetToolDisabledBitmap(self, tool_id, bitmap):
        """
        Sets the tool disabled bitmap for the tool identified by `tool_id`.

        :param `tool_id`: the tool identifier;
        :param `bitmap`: the new disabled bitmap for the toolbar item (an instance of `wx.Bitmap`).
        """

        tool = self.FindTool(tool_id)
        if tool:
            tool.disabled_bitmap = bitmap

[docs]    def GetToolShortHelp(self, tool_id):
        """
        Returns the short help for the given tool.

        :param `tool_id`: the tool identifier.
        """

        tool = self.FindTool(tool_id)
        if not tool:
            return ""

        return tool.short_help

[docs]    def SetToolShortHelp(self, tool_id, help_string):
        """
        Sets the short help for the given tool.

        :param `tool_id`: the tool identifier;
        :param `help_string`: the string for the short help.
        """

        tool = self.FindTool(tool_id)
        if tool:
            tool.short_help = help_string

[docs]    def GetToolLongHelp(self, tool_id):
        """
        Returns the long help for the given tool.

        :param `tool_id`: the tool identifier.
        """

        tool = self.FindTool(tool_id)
        if not tool:
            return ""

        return tool.long_help

[docs]    def SetToolAlignment(self, alignment=wx.EXPAND):
        """
        This sets the alignment for all of the tools within the
        toolbar (only has an effect when the toolbar is expanded).

        :param `alignment`: `wx.Sizer` alignment value
         (``wx.ALIGN_CENTER_HORIZONTAL`` or ``wx.ALIGN_CENTER_VERTICAL``).
        """

        self._tool_alignment = alignment

[docs]    def SetToolLongHelp(self, tool_id, help_string):
        """
        Sets the long help for the given tool.

        :param `tool_id`: the tool identifier;
        :param `help_string`: the string for the long help.
        """

        tool = self.FindTool(tool_id)
        if tool:
            tool.long_help = help_string

[docs]    def SetCustomOverflowItems(self, prepend, append):
        """
        Sets the two lists `prepend` and `append` as custom overflow items.

        :param `prepend`: a list of L{AuiToolBarItem} to be prepended;
        :param `append`: a list of L{AuiToolBarItem} to be appended.
        """

        self._custom_overflow_prepend = prepend
        self._custom_overflow_append = append

[docs]    def GetToolCount(self):
        """ Returns the number of tools in the L{AuiToolBar}. """

        return len(self._items)

[docs]    def GetToolIndex(self, tool_id):
        """
        Returns the position of the tool in the toolbar given its identifier.

        :param `tool_id`: the toolbar item identifier.
        """

        # this will prevent us from returning the index of the
        # first separator in the toolbar since its id is equal to -1
        if tool_id == -1:
            return wx.NOT_FOUND

        for i, item in enumerate(self._items):
            if item.id == tool_id:
                return i

        return wx.NOT_FOUND

[docs]    def GetToolPos(self, tool_id):
        """
        Returns the position of the tool in the toolbar given its identifier.

        :param `tool_id`: the toolbar item identifier.
        """

        return self.GetToolIndex(tool_id)

[docs]    def GetToolFitsByIndex(self, tool_id):
        """
        Returns whether the tool identified by `tool_id` fits into the toolbar or not.

        :param `tool_id`: the toolbar item identifier.
        """

        if tool_id < 0 or tool_id >= len(self._items):
            return False

        if not self._items[tool_id].sizer_item:
            return False

        cli_w, cli_h = self.GetClientSize()
        rect = self._items[tool_id].sizer_item.GetRect()

        if self._agwStyle & AUI_TB_VERTICAL:
            # take the dropdown size into account
            if self._overflow_visible:
                cli_h -= self._overflow_sizer_item.GetSize().y

            if rect.y+rect.height < cli_h:
                return True

        else:

            # take the dropdown size into account
            if self._overflow_visible:
                cli_w -= self._overflow_sizer_item.GetSize().x

            if rect.x+rect.width < cli_w:
                return True

        return False

[docs]    def GetToolFits(self, tool_id):
        """
        Returns whether the tool identified by `tool_id` fits into the toolbar or not.

        :param `tool_id`: the toolbar item identifier.
        """

        return self.GetToolFitsByIndex(self.GetToolIndex(tool_id))

[docs]    def GetToolRect(self, tool_id):
        """
        Returns the toolbar item rectangle

        :param `tool_id`: the toolbar item identifier.
        """

        tool = self.FindTool(tool_id)
        if tool and tool.sizer_item:
            return tool.sizer_item.GetRect()

        return wx.Rect()

[docs]    def GetToolBarFits(self):
        """ Returns whether the L{AuiToolBar} size fits in a specified size. """

        if len(self._items) == 0:
            # empty toolbar always 'fits'
            return True

        # entire toolbar content fits if the last tool fits
        return self.GetToolFitsByIndex(len(self._items) - 1)

[docs]    def Realize(self):
        """ Realizes the toolbar. This function should be called after you have added tools. """

        dc = wx.ClientDC(self)

        if not dc.IsOk():
            return False

        horizontal = True
        if self._agwStyle & AUI_TB_VERTICAL:
            horizontal = False

        # create the new sizer to add toolbar elements to
        sizer = wx.BoxSizer((horizontal and [wx.HORIZONTAL] or [wx.VERTICAL])[0])

        # add gripper area
        separator_size = self._art.GetElementSize(AUI_TBART_SEPARATOR_SIZE)
        gripper_size = self._art.GetElementSize(AUI_TBART_GRIPPER_SIZE)

        if gripper_size > 0 and self._gripper_visible:
            if horizontal:
                self._gripper_sizer_item = sizer.Add((gripper_size, 1), 0, wx.EXPAND)
            else:
                self._gripper_sizer_item = sizer.Add((1, gripper_size), 0, wx.EXPAND)
        else:
            self._gripper_sizer_item = None

        # add "left" padding
        if self._left_padding > 0:
            if horizontal:
                sizer.Add((self._left_padding, 1))
            else:
                sizer.Add((1, self._left_padding))

        count = len(self._items)
        for i, item in enumerate(self._items):

            sizer_item = None
            kind = item.kind

            if kind == ITEM_LABEL:

                size = self._art.GetLabelSize(dc, self, item)
                sizer_item = sizer.Add((size.x + (self._tool_border_padding*2),
                                        size.y + (self._tool_border_padding*2)),
                                       item.proportion,
                                       item.alignment)
                if i+1 < count:
                    sizer.AddSpacer(self._tool_packing)

            elif kind in [ITEM_CHECK, ITEM_NORMAL, ITEM_RADIO]:

                size = self._art.GetToolSize(dc, self, item)
                sizer_item = sizer.Add((size.x + (self._tool_border_padding*2),
                                        size.y + (self._tool_border_padding*2)),
                                       0,
                                       item.alignment)
                # add tool packing
                if i+1 < count:
                    sizer.AddSpacer(self._tool_packing)

            elif kind == ITEM_SEPARATOR:

                if horizontal:
                    sizer_item = sizer.Add((separator_size, 1), 0, wx.EXPAND)
                else:
                    sizer_item = sizer.Add((1, separator_size), 0, wx.EXPAND)

                # add tool packing
                if i+1 < count:
                    sizer.AddSpacer(self._tool_packing)

            elif kind == ITEM_SPACER:

                if item.proportion > 0:
                    sizer_item = sizer.AddStretchSpacer(item.proportion)
                else:
                    sizer_item = sizer.Add((item.spacer_pixels, 1))

            elif kind == ITEM_CONTROL:

                vert_sizer = wx.BoxSizer(wx.VERTICAL)
                vert_sizer.AddStretchSpacer(1)
                ctrl_sizer_item = vert_sizer.Add(item.window, 0, wx.EXPAND)
                vert_sizer.AddStretchSpacer(1)

                if self._agwStyle & AUI_TB_TEXT and \
                    self._tool_text_orientation == AUI_TBTOOL_TEXT_BOTTOM and \
                    item.GetLabel() != "":

                    s = self.GetLabelSize(item.GetLabel())
                    vert_sizer.Add((1, s.y))

                sizer_item = sizer.Add(vert_sizer, item.proportion, wx.EXPAND)
                min_size = item.min_size

                # proportional items will disappear from the toolbar if
                # their min width is not set to something really small
                if item.proportion != 0:
                    min_size.x = 1

                if min_size.IsFullySpecified():
                    sizer.SetItemMinSize(vert_sizer, min_size)
                    vert_sizer.SetItemMinSize(item.window, min_size)

                # add tool packing
                if i+1 < count:
                    sizer.AddSpacer(self._tool_packing)

            item.sizer_item = sizer_item

        # add "right" padding
        if self._right_padding > 0:
            if horizontal:
                sizer.Add((self._right_padding, 1))
            else:
                sizer.Add((1, self._right_padding))

        # add drop down area
        self._overflow_sizer_item = None

        if self._agwStyle & AUI_TB_OVERFLOW:

            overflow_size = self._art.GetElementSize(AUI_TBART_OVERFLOW_SIZE)
            if overflow_size > 0 and self._overflow_visible:

                if horizontal:
                    self._overflow_sizer_item = sizer.Add((overflow_size, 1), 0, wx.EXPAND)
                else:
                    self._overflow_sizer_item = sizer.Add((1, overflow_size), 0, wx.EXPAND)

            else:

                self._overflow_sizer_item = None

        # the outside sizer helps us apply the "top" and "bottom" padding
        outside_sizer = wx.BoxSizer((horizontal and [wx.VERTICAL] or [wx.HORIZONTAL])[0])

        # add "top" padding
        if self._top_padding > 0:

            if horizontal:
                outside_sizer.Add((1, self._top_padding))
            else:
                outside_sizer.Add((self._top_padding, 1))

        # add the sizer that contains all of the toolbar elements
        outside_sizer.Add(sizer, 1, self._tool_alignment)

        # add "bottom" padding
        if self._bottom_padding > 0:

            if horizontal:
                outside_sizer.Add((1, self._bottom_padding))
            else:
                outside_sizer.Add((self._bottom_padding, 1))

        del self._sizer # remove old sizer
        self._sizer = outside_sizer
        self.SetSizer(outside_sizer)

        # calculate the rock-bottom minimum size
        for item in self._items:

            if item.sizer_item and item.proportion > 0 and item.min_size.IsFullySpecified():
                item.sizer_item.SetMinSize((0, 0))

        self._absolute_min_size = self._sizer.GetMinSize()

        # reset the min sizes to what they were
        for item in self._items:

            if item.sizer_item and item.proportion > 0 and item.min_size.IsFullySpecified():
                item.sizer_item.SetMinSize(item.min_size)

        # set control size
        size = self._sizer.GetMinSize()
        self.SetMinSize(size)
        self._minWidth = size.x
        self._minHeight = size.y

        if self._agwStyle & AUI_TB_NO_AUTORESIZE == 0:

            cur_size = self.GetClientSize()
            new_size = self.GetMinSize()

            if new_size != cur_size:

                self.SetClientSize(new_size)

            else:

                self._sizer.SetDimension(0, 0, cur_size.x, cur_size.y)

        else:

            cur_size = self.GetClientSize()
            self._sizer.SetDimension(0, 0, cur_size.x, cur_size.y)

        self.Refresh(False)
        return True

[docs]    def GetOverflowState(self):
        """ Returns the state of the overflow button. """

        return self._overflow_state

[docs]    def GetOverflowRect(self):
        """ Returns the rectangle of the overflow button. """

        cli_rect = wx.RectPS(wx.Point(0, 0), self.GetClientSize())
        overflow_rect = wx.Rect(*self._overflow_sizer_item.GetRect())
        overflow_size = self._art.GetElementSize(AUI_TBART_OVERFLOW_SIZE)

        if self._agwStyle & AUI_TB_VERTICAL:

            overflow_rect.y = cli_rect.height - overflow_size
            overflow_rect.x = 0
            overflow_rect.width = cli_rect.width
            overflow_rect.height = overflow_size

        else:

            overflow_rect.x = cli_rect.width - overflow_size
            overflow_rect.y = 0
            overflow_rect.width = overflow_size
            overflow_rect.height = cli_rect.height

        return overflow_rect

[docs]    def GetLabelSize(self, label):
        """
        Returns the standard size of a toolbar item.

        :param `label`: a test label.
        """

        dc = wx.ClientDC(self)
        dc.SetFont(self._font)

        return GetLabelSize(dc, label, self._tool_orientation != AUI_TBTOOL_HORIZONTAL)

[docs]    def GetAuiManager(self):
        """ Returns the L{AuiManager} which manages the toolbar. """

        try:
            return self._auiManager
        except AttributeError:
            return False

[docs]    def SetAuiManager(self, auiManager):
        """ Sets the L{AuiManager} which manages the toolbar. """

        self._auiManager = auiManager

[docs]    def DoIdleUpdate(self):
        """ Updates the toolbar during idle times. """

        handler = self.GetEventHandler()
        if not handler:
            return

        need_refresh = False

        for item in self._items:

            if item.id == -1:
                continue

            evt = wx.UpdateUIEvent(item.id)
            evt.SetEventObject(self)

            if handler.ProcessEvent(evt):

                if evt.GetSetEnabled():

                    if item.window:
                        is_enabled = item.window.IsEnabled()
                    else:
                        is_enabled = (item.state & AUI_BUTTON_STATE_DISABLED and [False] or [True])[0]

                    new_enabled = evt.GetEnabled()
                    if new_enabled != is_enabled:

                        if item.window:
                            item.window.Enable(new_enabled)
                        else:
                            if new_enabled:
                                item.state &= ~AUI_BUTTON_STATE_DISABLED
                            else:
                                item.state |= AUI_BUTTON_STATE_DISABLED

                        need_refresh = True

                if evt.GetSetChecked():

                    # make sure we aren't checking an item that can't be
                    if item.kind != ITEM_CHECK and item.kind != ITEM_RADIO:
                        continue

                    is_checked = (item.state & AUI_BUTTON_STATE_CHECKED and [True] or [False])[0]
                    new_checked = evt.GetChecked()

                    if new_checked != is_checked:

                        if new_checked:
                            item.state |= AUI_BUTTON_STATE_CHECKED
                        else:
                            item.state &= ~AUI_BUTTON_STATE_CHECKED

                        need_refresh = True

        if need_refresh:
            self.Refresh(False)

[docs]    def OnSize(self, event):
        """
        Handles the ``wx.EVT_SIZE`` event for L{AuiToolBar}.

        :param `event`: a `wx.SizeEvent` event to be processed.
        """

        x, y = self.GetClientSize()
        realize = False

        if x > y:
            self.SetOrientation(wx.HORIZONTAL)
        else:
            self.SetOrientation(wx.VERTICAL)

        if (x >= y and self._absolute_min_size.x > x) or (y > x and self._absolute_min_size.y > y):

            # hide all flexible items
            for item in self._items:
                if item.sizer_item and item.proportion > 0 and item.sizer_item.IsShown():
                    item.sizer_item.Show(False)
                    item.sizer_item.SetProportion(0)

            if self._originalStyle & AUI_TB_OVERFLOW:
                if not self.GetOverflowVisible():
                    self.SetOverflowVisible(True)
                    realize = True

        else:

            if self._originalStyle & AUI_TB_OVERFLOW and not self._custom_overflow_append and \
               not self._custom_overflow_prepend:
                if self.GetOverflowVisible():
                    self.SetOverflowVisible(False)
                    realize = True

            # show all flexible items
            for item in self._items:
                if item.sizer_item and item.proportion > 0 and not item.sizer_item.IsShown():
                    item.sizer_item.Show(True)
                    item.sizer_item.SetProportion(item.proportion)

        self._sizer.SetDimension(0, 0, x, y)

        if realize:
            self.Realize()
        else:
            self.Refresh(False)

        self.Update()

[docs]    def DoSetSize(self, x, y, width, height, sizeFlags=wx.SIZE_AUTO):
        """
        Sets the position and size of the window in pixels. The `sizeFlags`
        parameter indicates the interpretation of the other params if they are
        equal to -1.

        :param `x`: the window `x` position;
        :param `y`: the window `y` position;
        :param `width`: the window width;
        :param `height`: the window height;
        :param `sizeFlags`: may have one of this bit set:

         ===================================  ======================================
         Size Flags                           Description
         ===================================  ======================================
         ``wx.SIZE_AUTO``                     A -1 indicates that a class-specific default should be used.
         ``wx.SIZE_AUTO_WIDTH``               A -1 indicates that a class-specific default should be used for the width.
         ``wx.SIZE_AUTO_HEIGHT``              A -1 indicates that a class-specific default should be used for the height.
         ``wx.SIZE_USE_EXISTING``             Existing dimensions should be used if -1 values are supplied.
         ``wx.SIZE_ALLOW_MINUS_ONE``          Allow dimensions of -1 and less to be interpreted as real dimensions, not default values.
         ``wx.SIZE_FORCE``                    Normally, if the position and the size of the window are already the same as the parameters of this function, nothing is done. but with this flag a window resize may be forced even in this case (supported in wx 2.6.2 and later and only implemented for MSW and ignored elsewhere currently)
         ===================================  ======================================

        :note: Overridden from `wx.PyControl`.
        """

        parent_size = self.GetParent().GetClientSize()
        if x + width > parent_size.x:
            width = max(0, parent_size.x - x)
        if y + height > parent_size.y:
            height = max(0, parent_size.y - y)

        wx.PyControl.DoSetSize(self, x, y, width, height, sizeFlags)

[docs]    def OnIdle(self, event):
        """
        Handles the ``wx.EVT_IDLE`` event for L{AuiToolBar}.

        :param `event`: a `wx.IdleEvent` event to be processed.
        """

        self.DoIdleUpdate()
        event.Skip()

[docs]    def DoGetBestSize(self):
        """
        Gets the size which best suits the window: for a control, it would be the
        minimal size which doesn't truncate the control, for a panel - the same
        size as it would have after a call to `Fit()`.

        :note: Overridden from `wx.PyControl`.
        """

        return self._absolute_min_size

[docs]    def OnPaint(self, event):
        """
        Handles the ``wx.EVT_PAINT`` event for L{AuiToolBar}.

        :param `event`: a `wx.PaintEvent` event to be processed.
        """

        dc = wx.AutoBufferedPaintDC(self)
        cli_rect = wx.RectPS(wx.Point(0, 0), self.GetClientSize())

        horizontal = True
        if self._agwStyle & AUI_TB_VERTICAL:
            horizontal = False

        if self._agwStyle & AUI_TB_PLAIN_BACKGROUND:
            self._art.DrawPlainBackground(dc, self, cli_rect)
        else:
            self._art.DrawBackground(dc, self, cli_rect, horizontal)

        gripper_size = self._art.GetElementSize(AUI_TBART_GRIPPER_SIZE)
        dropdown_size = self._art.GetElementSize(AUI_TBART_OVERFLOW_SIZE)

        # paint the gripper
        if self._agwStyle & AUI_TB_GRIPPER and gripper_size > 0 and self._gripper_sizer_item:
            gripper_rect = wx.Rect(*self._gripper_sizer_item.GetRect())
            if horizontal:
                gripper_rect.width = gripper_size
            else:
                gripper_rect.height = gripper_size

            self._art.DrawGripper(dc, self, gripper_rect)

        # calculated how far we can draw items
        if horizontal:
            last_extent = cli_rect.width
        else:
            last_extent = cli_rect.height

        if self._overflow_visible:
            last_extent -= dropdown_size

        # paint each individual tool
        for item in self._items:

            if not item.sizer_item:
                continue

            item_rect = wx.Rect(*item.sizer_item.GetRect())

            if (horizontal and item_rect.x + item_rect.width >= last_extent) or \
               (not horizontal and item_rect.y + item_rect.height >= last_extent):

                break

            if item.kind == ITEM_SEPARATOR:
                # draw a separator
                self._art.DrawSeparator(dc, self, item_rect)

            elif item.kind == ITEM_LABEL:
                # draw a text label only
                self._art.DrawLabel(dc, self, item, item_rect)

            elif item.kind == ITEM_NORMAL:
                # draw a regular button or dropdown button
                if not item.dropdown:
                    self._art.DrawButton(dc, self, item, item_rect)
                else:
                    self._art.DrawDropDownButton(dc, self, item, item_rect)

            elif item.kind == ITEM_CHECK:
                # draw a regular toggle button or a dropdown one
                if not item.dropdown:
                    self._art.DrawButton(dc, self, item, item_rect)
                else:
                    self._art.DrawDropDownButton(dc, self, item, item_rect)

            elif item.kind == ITEM_RADIO:
                # draw a toggle button
                self._art.DrawButton(dc, self, item, item_rect)

            elif item.kind == ITEM_CONTROL:
                # draw the control's label
                self._art.DrawControlLabel(dc, self, item, item_rect)

            # fire a signal to see if the item wants to be custom-rendered
            self.OnCustomRender(dc, item, item_rect)

        # paint the overflow button
        if dropdown_size > 0 and self._overflow_sizer_item:
            dropdown_rect = self.GetOverflowRect()
            self._art.DrawOverflowButton(dc, self, dropdown_rect, self._overflow_state)

[docs]    def OnEraseBackground(self, event):
        """
        Handles the ``wx.EVT_ERASE_BACKGROUND`` event for L{AuiToolBar}.

        :param `event`: a `wx.EraseEvent` event to be processed.

        :note: This is intentionally empty, to reduce flicker.
        """

        pass

[docs]    def OnLeftDown(self, event):
        """
        Handles the ``wx.EVT_LEFT_DOWN`` event for L{AuiToolBar}.

        :param `event`: a `wx.MouseEvent` event to be processed.
        """

        cli_rect = wx.RectPS(wx.Point(0, 0), self.GetClientSize())
        self.StopPreviewTimer()

        if self._gripper_sizer_item:

            gripper_rect = wx.Rect(*self._gripper_sizer_item.GetRect())
            if gripper_rect.Contains(event.GetPosition()):

                # find aui manager
                manager = self.GetAuiManager()
                if not manager:
                    return

                x_drag_offset = event.GetX() - gripper_rect.GetX()
                y_drag_offset = event.GetY() - gripper_rect.GetY()

                clientPt = wx.Point(*event.GetPosition())
                screenPt = self.ClientToScreen(clientPt)
                managedWindow = manager.GetManagedWindow()
                managerClientPt = managedWindow.ScreenToClient(screenPt)

                # gripper was clicked
                manager.OnGripperClicked(self, managerClientPt, wx.Point(x_drag_offset, y_drag_offset))
                return

        if self._overflow_sizer_item:
            overflow_rect = self.GetOverflowRect()

            if self._art and self._overflow_visible and overflow_rect.Contains(event.GetPosition()):

                e = AuiToolBarEvent(wxEVT_COMMAND_AUITOOLBAR_OVERFLOW_CLICK, -1)
                e.SetEventObject(self)
                e.SetToolId(-1)
                e.SetClickPoint(event.GetPosition())
                processed = self.ProcessEvent(e)

                if processed:
                    self.DoIdleUpdate()
                else:
                    overflow_items = []

                    # add custom overflow prepend items, if any
                    count = len(self._custom_overflow_prepend)
                    for i in xrange(count):
                        overflow_items.append(self._custom_overflow_prepend[i])

                    # only show items that don't fit in the dropdown
                    count = len(self._items)
                    for i in xrange(count):

                        if not self.GetToolFitsByIndex(i):
                            overflow_items.append(self._items[i])

                    # add custom overflow append items, if any
                    count = len(self._custom_overflow_append)
                    for i in xrange(count):
                        overflow_items.append(self._custom_overflow_append[i])

                    res = self._art.ShowDropDown(self, overflow_items)
                    self._overflow_state = 0
                    self.Refresh(False)
                    if res != -1:
                        e = wx.CommandEvent(wx.wxEVT_COMMAND_MENU_SELECTED, res)
                        e.SetEventObject(self)
                        if not self.GetParent().ProcessEvent(e):
                            tool = self.FindTool(res)
                            if tool:
                                state = (tool.state & AUI_BUTTON_STATE_CHECKED and [True] or [False])[0]
                                self.ToggleTool(res, not state)

                return

        self._dragging = False
        self._action_pos = wx.Point(*event.GetPosition())
        self._action_item = self.FindToolForPosition(*event.GetPosition())

        if self._action_item:

            if self._action_item.state & AUI_BUTTON_STATE_DISABLED:

                self._action_pos = wx.Point(-1, -1)
                self._action_item = None
                return

            self.SetPressedItem(self._action_item)

            # fire the tool dropdown event
            e = AuiToolBarEvent(wxEVT_COMMAND_AUITOOLBAR_TOOL_DROPDOWN, self._action_item.id)
            e.SetEventObject(self)
            e.SetToolId(self._action_item.id)
            e.SetDropDownClicked(False)

            mouse_x, mouse_y = event.GetX(), event.GetY()
            rect = wx.Rect(*self._action_item.sizer_item.GetRect())

            if self._action_item.dropdown:
                if (self._action_item.orientation == AUI_TBTOOL_HORIZONTAL and \
                    mouse_x >= (rect.x+rect.width-BUTTON_DROPDOWN_WIDTH-1) and \
                    mouse_x < (rect.x+rect.width)) or \
                    (self._action_item.orientation != AUI_TBTOOL_HORIZONTAL and \
                     mouse_y >= (rect.y+rect.height-BUTTON_DROPDOWN_WIDTH-1) and \
                     mouse_y < (rect.y+rect.height)):

                    e.SetDropDownClicked(True)

            e.SetClickPoint(event.GetPosition())
            e.SetItemRect(rect)
            self.ProcessEvent(e)
            self.DoIdleUpdate()

[docs]    def OnLeftUp(self, event):
        """
        Handles the ``wx.EVT_LEFT_UP`` event for L{AuiToolBar}.

        :param `event`: a `wx.MouseEvent` event to be processed.
        """

        self.SetPressedItem(None)

        hit_item = self.FindToolForPosition(*event.GetPosition())

        if hit_item and not hit_item.state & AUI_BUTTON_STATE_DISABLED:
            self.SetHoverItem(hit_item)

        if self._dragging:
            # reset drag and drop member variables
            self._dragging = False
            self._action_pos = wx.Point(-1, -1)
            self._action_item = None

        else:

            if self._action_item and hit_item == self._action_item:
                self.SetToolTipString("")

                if hit_item.kind in [ITEM_CHECK, ITEM_RADIO]:
                    toggle = not (self._action_item.state & AUI_BUTTON_STATE_CHECKED)
                    self.ToggleTool(self._action_item.id, toggle)

                    # repaint immediately
                    self.Refresh(False)
                    self.Update()

                    e = wx.CommandEvent(wx.wxEVT_COMMAND_MENU_SELECTED, self._action_item.id)
                    e.SetEventObject(self)
                    e.SetInt(toggle)
                    self._action_pos = wx.Point(-1, -1)
                    self._action_item = None

                    self.ProcessEvent(e)
                    self.DoIdleUpdate()

                else:

                    if self._action_item.id == ID_RESTORE_FRAME:
                        # find aui manager
                        manager = self.GetAuiManager()

                        if not manager:
                            return

                        if self._action_item.target:
                            pane = manager.GetPane(self._action_item.target)
                        else:
                            pane = manager.GetPane(self)

                        e = framemanager.AuiManagerEvent(framemanager.wxEVT_AUI_PANE_MIN_RESTORE)

                        e.SetManager(manager)
                        e.SetPane(pane)

                        manager.ProcessEvent(e)
                        self.DoIdleUpdate()

                    else:

                        e = wx.CommandEvent(wx.wxEVT_COMMAND_MENU_SELECTED, self._action_item.id)
                        e.SetEventObject(self)
                        self.ProcessEvent(e)
                        self.DoIdleUpdate()

        # reset drag and drop member variables
        self._dragging = False
        self._action_pos = wx.Point(-1, -1)
        self._action_item = None

[docs]    def OnRightDown(self, event):
        """
        Handles the ``wx.EVT_RIGHT_DOWN`` event for L{AuiToolBar}.

        :param `event`: a `wx.MouseEvent` event to be processed.
        """

        cli_rect = wx.RectPS(wx.Point(0, 0), self.GetClientSize())

        if self._gripper_sizer_item:
            gripper_rect = self._gripper_sizer_item.GetRect()
            if gripper_rect.Contains(event.GetPosition()):
                return

        if self._overflow_sizer_item:

            dropdown_size = self._art.GetElementSize(AUI_TBART_OVERFLOW_SIZE)
            if dropdown_size > 0 and event.GetX() > cli_rect.width - dropdown_size and \
               event.GetY() >= 0 and event.GetY() < cli_rect.height and self._art:
                return

        self._action_pos = wx.Point(*event.GetPosition())
        self._action_item = self.FindToolForPosition(*event.GetPosition())

        if self._action_item:
            if self._action_item.state & AUI_BUTTON_STATE_DISABLED:

                self._action_pos = wx.Point(-1, -1)
                self._action_item = None
                return

[docs]    def OnRightUp(self, event):
        """
        Handles the ``wx.EVT_RIGHT_UP`` event for L{AuiToolBar}.

        :param `event`: a `wx.MouseEvent` event to be processed.
        """

        hit_item = self.FindToolForPosition(*event.GetPosition())

        if self._action_item and hit_item == self._action_item:

            e = AuiToolBarEvent(wxEVT_COMMAND_AUITOOLBAR_RIGHT_CLICK, self._action_item.id)
            e.SetEventObject(self)
            e.SetToolId(self._action_item.id)
            e.SetClickPoint(self._action_pos)
            self.ProcessEvent(e)
            self.DoIdleUpdate()

        else:

            # right-clicked on the invalid area of the toolbar
            e = AuiToolBarEvent(wxEVT_COMMAND_AUITOOLBAR_RIGHT_CLICK, -1)
            e.SetEventObject(self)
            e.SetToolId(-1)
            e.SetClickPoint(self._action_pos)
            self.ProcessEvent(e)
            self.DoIdleUpdate()

        # reset member variables
        self._action_pos = wx.Point(-1, -1)
        self._action_item = None

[docs]    def OnMiddleDown(self, event):
        """
        Handles the ``wx.EVT_MIDDLE_DOWN`` event for L{AuiToolBar}.

        :param `event`: a `wx.MouseEvent` event to be processed.
        """

        cli_rect = wx.RectPS(wx.Point(0, 0), self.GetClientSize())

        if self._gripper_sizer_item:

            gripper_rect = self._gripper_sizer_item.GetRect()
            if gripper_rect.Contains(event.GetPosition()):
                return

        if self._overflow_sizer_item:

            dropdown_size = self._art.GetElementSize(AUI_TBART_OVERFLOW_SIZE)
            if dropdown_size > 0 and event.GetX() > cli_rect.width - dropdown_size and \
               event.GetY() >= 0 and event.GetY() < cli_rect.height and self._art:
                return

        self._action_pos = wx.Point(*event.GetPosition())
        self._action_item = self.FindToolForPosition(*event.GetPosition())

        if self._action_item:
            if self._action_item.state & AUI_BUTTON_STATE_DISABLED:

                self._action_pos = wx.Point(-1, -1)
                self._action_item = None
                return

[docs]    def OnMiddleUp(self, event):
        """
        Handles the ``wx.EVT_MIDDLE_UP`` event for L{AuiToolBar}.

        :param `event`: a `wx.MouseEvent` event to be processed.
        """

        hit_item = self.FindToolForPosition(*event.GetPosition())

        if self._action_item and hit_item == self._action_item:
            if hit_item.kind == ITEM_NORMAL:

                e = AuiToolBarEvent(wxEVT_COMMAND_AUITOOLBAR_MIDDLE_CLICK, self._action_item.id)
                e.SetEventObject(self)
                e.SetToolId(self._action_item.id)
                e.SetClickPoint(self._action_pos)
                self.ProcessEvent(e)
                self.DoIdleUpdate()

        # reset member variables
        self._action_pos = wx.Point(-1, -1)
        self._action_item = None

[docs]    def OnMotion(self, event):
        """
        Handles the ``wx.EVT_MOTION`` event for L{AuiToolBar}.

        :param `event`: a `wx.MouseEvent` event to be processed.
        """

        # start a drag event
        if not self._dragging and self._action_item != None and self._action_pos != wx.Point(-1, -1) and \
           abs(event.GetX() - self._action_pos.x) + abs(event.GetY() - self._action_pos.y) > 5:

            self.SetToolTipString("")
            self._dragging = True

            e = AuiToolBarEvent(wxEVT_COMMAND_AUITOOLBAR_BEGIN_DRAG, self.GetId())
            e.SetEventObject(self)
            e.SetToolId(self._action_item.id)
            self.ProcessEvent(e)
            self.DoIdleUpdate()
            return

        hit_item = self.FindToolForPosition(*event.GetPosition())

        if hit_item:
            if not hit_item.state & AUI_BUTTON_STATE_DISABLED:
                self.SetHoverItem(hit_item)
            else:
                self.SetHoverItem(None)

        else:
            # no hit item, remove any hit item
            self.SetHoverItem(hit_item)

        # figure out tooltips
        packing_hit_item = self.FindToolForPositionWithPacking(*event.GetPosition())

        if packing_hit_item:

            if packing_hit_item != self._tip_item:
                self._tip_item = packing_hit_item

                if packing_hit_item.short_help != "":
                    self.StartPreviewTimer()
                    self.SetToolTipString(packing_hit_item.short_help)
                else:
                    self.SetToolTipString("")
                    self.StopPreviewTimer()

        else:

            self.SetToolTipString("")
            self._tip_item = None
            self.StopPreviewTimer()

        # if we've pressed down an item and we're hovering
        # over it, make sure it's state is set to pressed
        if self._action_item:

            if self._action_item == hit_item:
                self.SetPressedItem(self._action_item)
            else:
                self.SetPressedItem(None)

        # figure out the dropdown button state (are we hovering or pressing it?)
        self.RefreshOverflowState()

[docs]    def OnLeaveWindow(self, event):
        """
        Handles the ``wx.EVT_LEAVE_WINDOW`` event for L{AuiToolBar}.

        :param `event`: a `wx.MouseEvent` event to be processed.
        """

        self.RefreshOverflowState()
        self.SetHoverItem(None)
        self.SetPressedItem(None)

        self._tip_item = None
        self.StopPreviewTimer()

[docs]    def OnSetCursor(self, event):
        """
        Handles the ``wx.EVT_SET_CURSOR`` event for L{AuiToolBar}.

        :param `event`: a `wx.SetCursorEvent` event to be processed.
        """

        cursor = wx.NullCursor

        if self._gripper_sizer_item:

            gripper_rect = self._gripper_sizer_item.GetRect()
            if gripper_rect.Contains((event.GetX(), event.GetY())):
                cursor = wx.StockCursor(wx.CURSOR_SIZING)

        event.SetCursor(cursor)

[docs]    def OnCustomRender(self, dc, item, rect):
        """
        Handles custom render for single L{AuiToolBar} items.

        :param `dc`: a `wx.DC` device context;
        :param `item`: an instance of L{AuiToolBarItem};
        :param `rect`: the toolbar item rect.

        :note: This method must be overridden to provide custom rendering of items.
        """

        pass

[docs]    def IsPaneMinimized(self):
        """ Returns whether this L{AuiToolBar} contains a minimized pane tool. """

        manager = self.GetAuiManager()
        if not manager:
            return False

        if manager.GetAGWFlags() & AUI_MGR_PREVIEW_MINIMIZED_PANES == 0:
            # No previews here
            return False

        self_name = manager.GetPane(self).name

        if not self_name.endswith("_min"):
            # Wrong tool name
            return False

        return self_name[0:-4]

[docs]    def StartPreviewTimer(self):
        """ Starts a timer in L{AuiManager} to slide-in/slide-out the minimized pane. """

        self_name = self.IsPaneMinimized()
        if not self_name:
            return

        manager = self.GetAuiManager()
        manager.StartPreviewTimer(self)

[docs]    def StopPreviewTimer(self):
        """ Stops a timer in L{AuiManager} to slide-in/slide-out the minimized pane. """

        self_name = self.IsPaneMinimized()
        if not self_name:
            return

        manager = self.GetAuiManager()
        manager.StopPreviewTimer()

Navigation

  • index
  • modules |
  • Home |
  • Gallery |
  • Contents»
  • Module code »
  • aui.auibar


aui.auibook

  • modules |
  • Home |
  • Gallery |
  • Contents»
  • Module code »
  • aui.auibook

Source code for aui.auibook

"""
auibook contains a notebook control which implements many features common in
applications with dockable panes. Specifically, L{AuiNotebook} implements functionality
which allows the user to rearrange tab order via drag-and-drop, split the tab window
into many different splitter configurations, and toggle through different themes to
customize the control's look and feel.

An effort has been made to try to maintain an API as similar to that of `wx.Notebook`.

The default theme that is used is L{AuiDefaultTabArt}, which provides a modern, glossy
look and feel. The theme can be changed by calling L{AuiNotebook.SetArtProvider}.
"""

__author__ = "Andrea Gavana <andrea.gavana@gmail.com>"
__date__ = "31 March 2009"

import wx
import types
import datetime

from wx.lib.expando import ExpandoTextCtrl

import framemanager
import tabart as TA

from aui_utilities import LightColour, MakeDisabledBitmap, TabDragImage
from aui_utilities import TakeScreenShot, RescaleScreenShot

from aui_constants import *

# AuiNotebook events
wxEVT_COMMAND_AUINOTEBOOK_PAGE_CLOSE = wx.NewEventType()
wxEVT_COMMAND_AUINOTEBOOK_PAGE_CLOSED = wx.NewEventType()
wxEVT_COMMAND_AUINOTEBOOK_PAGE_CHANGED = wx.NewEventType()
wxEVT_COMMAND_AUINOTEBOOK_PAGE_CHANGING = wx.NewEventType()
wxEVT_COMMAND_AUINOTEBOOK_BUTTON = wx.NewEventType()
wxEVT_COMMAND_AUINOTEBOOK_BEGIN_DRAG = wx.NewEventType()
wxEVT_COMMAND_AUINOTEBOOK_END_DRAG = wx.NewEventType()
wxEVT_COMMAND_AUINOTEBOOK_DRAG_MOTION = wx.NewEventType()
wxEVT_COMMAND_AUINOTEBOOK_ALLOW_DND = wx.NewEventType()
wxEVT_COMMAND_AUINOTEBOOK_DRAG_DONE = wx.NewEventType()
wxEVT_COMMAND_AUINOTEBOOK_TAB_MIDDLE_DOWN = wx.NewEventType()
wxEVT_COMMAND_AUINOTEBOOK_TAB_MIDDLE_UP = wx.NewEventType()
wxEVT_COMMAND_AUINOTEBOOK_TAB_RIGHT_DOWN = wx.NewEventType()
wxEVT_COMMAND_AUINOTEBOOK_TAB_RIGHT_UP = wx.NewEventType()
wxEVT_COMMAND_AUINOTEBOOK_TAB_DCLICK = wx.NewEventType()
wxEVT_COMMAND_AUINOTEBOOK_BG_MIDDLE_DOWN = wx.NewEventType()
wxEVT_COMMAND_AUINOTEBOOK_BG_MIDDLE_UP = wx.NewEventType()
wxEVT_COMMAND_AUINOTEBOOK_BG_RIGHT_DOWN = wx.NewEventType()
wxEVT_COMMAND_AUINOTEBOOK_BG_RIGHT_UP = wx.NewEventType()
wxEVT_COMMAND_AUINOTEBOOK_BG_DCLICK = wx.NewEventType()

# Define a new event for a drag cancelled
wxEVT_COMMAND_AUINOTEBOOK_CANCEL_DRAG = wx.NewEventType()

# Define events for editing a tab label
wxEVT_COMMAND_AUINOTEBOOK_BEGIN_LABEL_EDIT = wx.NewEventType()
wxEVT_COMMAND_AUINOTEBOOK_END_LABEL_EDIT = wx.NewEventType()

# Create event binders
EVT_AUINOTEBOOK_PAGE_CLOSE = wx.PyEventBinder(wxEVT_COMMAND_AUINOTEBOOK_PAGE_CLOSE, 1)
""" A tab in `AuiNotebook` is being closed. Can be vetoed by calling `Veto()`. """
EVT_AUINOTEBOOK_PAGE_CLOSED = wx.PyEventBinder(wxEVT_COMMAND_AUINOTEBOOK_PAGE_CLOSED, 1)
""" A tab in `AuiNotebook` has been closed. """
EVT_AUINOTEBOOK_PAGE_CHANGED = wx.PyEventBinder(wxEVT_COMMAND_AUINOTEBOOK_PAGE_CHANGED, 1)
""" The page selection was changed. """
EVT_AUINOTEBOOK_PAGE_CHANGING = wx.PyEventBinder(wxEVT_COMMAND_AUINOTEBOOK_PAGE_CHANGING, 1)
""" The page selection is being changed. """
EVT_AUINOTEBOOK_BUTTON = wx.PyEventBinder(wxEVT_COMMAND_AUINOTEBOOK_BUTTON, 1)
""" The user clicked on a button in the `AuiNotebook` tab area. """
EVT_AUINOTEBOOK_BEGIN_DRAG = wx.PyEventBinder(wxEVT_COMMAND_AUINOTEBOOK_BEGIN_DRAG, 1)
""" A drag-and-drop operation on a notebook tab has started. """
EVT_AUINOTEBOOK_END_DRAG = wx.PyEventBinder(wxEVT_COMMAND_AUINOTEBOOK_END_DRAG, 1)
""" A drag-and-drop operation on a notebook tab has finished. """
EVT_AUINOTEBOOK_DRAG_MOTION = wx.PyEventBinder(wxEVT_COMMAND_AUINOTEBOOK_DRAG_MOTION, 1)
""" A drag-and-drop operation on a notebook tab is ongoing. """
EVT_AUINOTEBOOK_ALLOW_DND = wx.PyEventBinder(wxEVT_COMMAND_AUINOTEBOOK_ALLOW_DND, 1)
""" Fires an event asking if it is OK to drag and drop a tab. """
EVT_AUINOTEBOOK_DRAG_DONE = wx.PyEventBinder(wxEVT_COMMAND_AUINOTEBOOK_DRAG_DONE, 1)
""" A drag-and-drop operation on a notebook tab has finished. """
EVT_AUINOTEBOOK_TAB_MIDDLE_DOWN = wx.PyEventBinder(wxEVT_COMMAND_AUINOTEBOOK_TAB_MIDDLE_DOWN, 1)
""" The user clicked with the middle mouse button on a tab. """
EVT_AUINOTEBOOK_TAB_MIDDLE_UP = wx.PyEventBinder(wxEVT_COMMAND_AUINOTEBOOK_TAB_MIDDLE_UP, 1)
""" The user clicked with the middle mouse button on a tab. """
EVT_AUINOTEBOOK_TAB_RIGHT_DOWN = wx.PyEventBinder(wxEVT_COMMAND_AUINOTEBOOK_TAB_RIGHT_DOWN, 1)
""" The user clicked with the right mouse button on a tab. """
EVT_AUINOTEBOOK_TAB_RIGHT_UP = wx.PyEventBinder(wxEVT_COMMAND_AUINOTEBOOK_TAB_RIGHT_UP, 1)
""" The user clicked with the right mouse button on a tab. """
EVT_AUINOTEBOOK_BG_MIDDLE_DOWN = wx.PyEventBinder(wxEVT_COMMAND_AUINOTEBOOK_BG_MIDDLE_DOWN, 1)
""" The user middle-clicked in the tab area but not over a tab or a button. """
EVT_AUINOTEBOOK_BG_MIDDLE_UP = wx.PyEventBinder(wxEVT_COMMAND_AUINOTEBOOK_BG_MIDDLE_UP, 1)
""" The user middle-clicked in the tab area but not over a tab or a button. """
EVT_AUINOTEBOOK_BG_RIGHT_DOWN = wx.PyEventBinder(wxEVT_COMMAND_AUINOTEBOOK_BG_RIGHT_DOWN, 1)
""" The user right-clicked in the tab area but not over a tab or a button. """
EVT_AUINOTEBOOK_BG_RIGHT_UP = wx.PyEventBinder(wxEVT_COMMAND_AUINOTEBOOK_BG_RIGHT_UP, 1)
""" The user right-clicked in the tab area but not over a tab or a button. """
EVT_AUINOTEBOOK_BG_DCLICK = wx.PyEventBinder(wxEVT_COMMAND_AUINOTEBOOK_BG_DCLICK, 1)
""" The user left-clicked on the tab area not occupied by `AuiNotebook` tabs. """
EVT_AUINOTEBOOK_CANCEL_DRAG = wx.PyEventBinder(wxEVT_COMMAND_AUINOTEBOOK_CANCEL_DRAG, 1)
""" A drag and drop operation has been cancelled. """
EVT_AUINOTEBOOK_TAB_DCLICK = wx.PyEventBinder(wxEVT_COMMAND_AUINOTEBOOK_TAB_DCLICK, 1)
""" The user double-clicked with the left mouse button on a tab. """
EVT_AUINOTEBOOK_BEGIN_LABEL_EDIT = wx.PyEventBinder(wxEVT_COMMAND_AUINOTEBOOK_BEGIN_LABEL_EDIT, 1)
""" The user double-clicked with the left mouse button on a tab which text is editable. """
EVT_AUINOTEBOOK_END_LABEL_EDIT = wx.PyEventBinder(wxEVT_COMMAND_AUINOTEBOOK_END_LABEL_EDIT, 1)
""" The user finished editing a tab label. """

# -----------------------------------------------------------------------------
# Auxiliary class: TabTextCtrl
# This is the temporary ExpandoTextCtrl created when you edit the text of a tab
# -----------------------------------------------------------------------------

[docs]class TabTextCtrl(ExpandoTextCtrl):
    """ Control used for in-place edit. """

[docs]    def __init__(self, owner, tab, page_index):
        """
        Default class constructor.
        For internal use: do not call it in your code!

        :param `owner`: the L{AuiTabCtrl} owning the tab;
        :param `tab`: the actual L{AuiNotebookPage} tab;
        :param `page_index`: the L{AuiNotebook} page index for the tab.
        """

        self._owner = owner
        self._tabEdited = tab
        self._pageIndex = page_index
        self._startValue = tab.caption
        self._finished = False
        self._aboutToFinish = False
        self._currentValue = self._startValue

        x, y, w, h = self._tabEdited.rect

        wnd = self._tabEdited.control
        if wnd:
            x += wnd.GetSize()[0] + 2
            h = 0

        image_h = 0
        image_w = 0

        image = tab.bitmap

        if image.IsOk():
            image_w, image_h = image.GetWidth(), image.GetHeight()
            image_w += 6

        dc = wx.ClientDC(self._owner)
        h = max(image_h, dc.GetMultiLineTextExtent(tab.caption)[1])
        h = h + 2

        # FIXME: what are all these hardcoded 4, 8 and 11s really?
        x += image_w
        w -= image_w + 4

        y = (self._tabEdited.rect.height - h)/2 + 1

        expandoStyle = wx.WANTS_CHARS
        if wx.Platform in ["__WXGTK__", "__WXMAC__"]:
            expandoStyle |= wx.SIMPLE_BORDER
            xSize, ySize = w + 2, h
        else:
            expandoStyle |= wx.SUNKEN_BORDER
            xSize, ySize = w + 2, h+2

        ExpandoTextCtrl.__init__(self, self._owner, wx.ID_ANY, self._startValue,
                                 wx.Point(x, y), wx.Size(xSize, ySize),
                                 expandoStyle)

        if wx.Platform == "__WXMAC__":
            self.SetFont(owner.GetFont())
            bs = self.GetBestSize()
            self.SetSize((-1, bs.height))

        self.Bind(wx.EVT_CHAR, self.OnChar)
        self.Bind(wx.EVT_KEY_UP, self.OnKeyUp)
        self.Bind(wx.EVT_KILL_FOCUS, self.OnKillFocus)

[docs]    def AcceptChanges(self):
        """ Accepts/refuses the changes made by the user. """

        value = self.GetValue()
        notebook = self._owner.GetParent()

        if value == self._startValue:
            # nothing changed, always accept
            # when an item remains unchanged, the owner
            # needs to be notified that the user decided
            # not to change the tree item label, and that
            # the edit has been cancelled
            notebook.OnRenameCancelled(self._pageIndex)
            return True

        if not notebook.OnRenameAccept(self._pageIndex, value):
            # vetoed by the user
            return False

        # accepted, do rename the item
        notebook.SetPageText(self._pageIndex, value)

        return True

[docs]    def Finish(self):
        """ Finish editing. """

        if not self._finished:

            notebook = self._owner.GetParent()

            self._finished = True
            self._owner.SetFocus()
            notebook.ResetTextControl()

[docs]    def OnChar(self, event):
        """
        Handles the ``wx.EVT_CHAR`` event for L{TabTextCtrl}.

        :param `event`: a `wx.KeyEvent` event to be processed.
        """

        keycode = event.GetKeyCode()
        shiftDown = event.ShiftDown()

        if keycode == wx.WXK_RETURN:
            if shiftDown and self._tabEdited.IsMultiline():
                event.Skip()
            else:
                self._aboutToFinish = True
                self.SetValue(self._currentValue)
                # Notify the owner about the changes
                self.AcceptChanges()
                # Even if vetoed, close the control (consistent with MSW)
                wx.CallAfter(self.Finish)

        elif keycode == wx.WXK_ESCAPE:
            self.StopEditing()

        else:
            event.Skip()

[docs]    def OnKeyUp(self, event):
        """
        Handles the ``wx.EVT_KEY_UP`` event for L{TabTextCtrl}.

        :param `event`: a `wx.KeyEvent` event to be processed.
        """

        if not self._finished:

            # auto-grow the textctrl:
            mySize = self.GetSize()

            dc = wx.ClientDC(self)
            sx, sy, dummy = dc.GetMultiLineTextExtent(self.GetValue() + "M")

            self.SetSize((sx, -1))
            self._currentValue = self.GetValue()

        event.Skip()

[docs]    def OnKillFocus(self, event):
        """
        Handles the ``wx.EVT_KILL_FOCUS`` event for L{TabTextCtrl}.

        :param `event`: a `wx.FocusEvent` event to be processed.
        """

        if not self._finished and not self._aboutToFinish:

            # We must finish regardless of success, otherwise we'll get
            # focus problems:
            if not self.AcceptChanges():
                self._owner.GetParent().OnRenameCancelled(self._pageIndex)

        # We must let the native text control handle focus, too, otherwise
        # it could have problems with the cursor (e.g., in wxGTK).
        event.Skip()
        wx.CallAfter(self._owner.GetParent().ResetTextControl)

[docs]    def StopEditing(self):
        """ Suddenly stops the editing. """

        self._owner.GetParent().OnRenameCancelled(self._pageIndex)
        self.Finish()

[docs]    def item(self):
        """ Returns the item currently edited. """

        return self._tabEdited

# ----------------------------------------------------------------------

[docs]class AuiNotebookPage(object):
    """
    A simple class which holds information about tab captions, bitmaps and
    colours.
    """

[docs]    def __init__(self):
        """
        Default class constructor.
        Used internally, do not call it in your code!
        """

        self.window = None              # page's associated window
        self.caption = ""               # caption displayed on the tab
        self.bitmap = wx.NullBitmap     # tab's bitmap
        self.dis_bitmap = wx.NullBitmap # tab's disabled bitmap
        self.rect = wx.Rect()           # tab's hit rectangle
        self.active = False             # True if the page is currently active
        self.enabled = True             # True if the page is currently enabled
        self.hasCloseButton = True      # True if the page has a close button using the style
                                        # AUI_NB_CLOSE_ON_ALL_TABS
        self.control = None             # A control can now be inside a tab
        self.renamable = False          # If True, a tab can be renamed by a left double-click

        self.text_colour = wx.SystemSettings.GetColour(wx.SYS_COLOUR_BTNTEXT)

        self.access_time = datetime.datetime.now() # Last time this page was selected

[docs]    def IsMultiline(self):
        """ Returns whether the tab contains multiline text. """

        return "\n" in self.caption

# ----------------------------------------------------------------------

[docs]class AuiTabContainerButton(object):
    """
    A simple class which holds information about tab buttons and their state.
    """

[docs]    def __init__(self):
        """
        Default class constructor.
        Used internally, do not call it in your code!
        """

        self.id = -1                                      # button's id
        self.cur_state = AUI_BUTTON_STATE_NORMAL          # current state (normal, hover, pressed, etc.)
        self.location = wx.LEFT                           # buttons location (wxLEFT, wxRIGHT, or wxCENTER)
        self.bitmap = wx.NullBitmap                       # button's hover bitmap
        self.dis_bitmap = wx.NullBitmap                   # button's disabled bitmap
        self.rect = wx.Rect()                             # button's hit rectangle

# ----------------------------------------------------------------------

[docs]class CommandNotebookEvent(wx.PyCommandEvent):
    """ A specialized command event class for events sent by L{AuiNotebook} . """

[docs]    def __init__(self, command_type=None, win_id=0):
        """
        Default class constructor.

        :param `command_type`: the event kind or an instance of `wx.PyCommandEvent`.
        :param `win_id`: the window identification number.
        """

        if type(command_type) == types.IntType:
            wx.PyCommandEvent.__init__(self, command_type, win_id)
        else:
            wx.PyCommandEvent.__init__(self, command_type.GetEventType(), command_type.GetId())

        self.old_selection = -1
        self.selection = -1
        self.drag_source = None
        self.dispatched = 0
        self.label = ""
        self.editCancelled = False
        self.page = None

[docs]    def SetSelection(self, s):
        """
        Sets the selection member variable.

        :param `s`: the new selection.
        """

        self.selection = s
        self._commandInt = s

[docs]    def GetSelection(self):
        """ Returns the currently selected page, or -1 if none was selected. """

        return self.selection

[docs]    def SetOldSelection(self, s):
        """
        Sets the id of the page selected before the change.

        :param `s`: the old selection.
        """

        self.old_selection = s

[docs]    def GetOldSelection(self):
        """
        Returns the page that was selected before the change, or -1 if none was
        selected.
        """

        return self.old_selection

[docs]    def SetDragSource(self, s):
        """
        Sets the drag and drop source.

        :param `s`: the drag source.
        """

        self.drag_source = s

[docs]    def GetDragSource(self):
        """ Returns the drag and drop source. """

        return self.drag_source

[docs]    def SetDispatched(self, b):
        """
        Sets the event as dispatched (used for automatic L{AuiNotebook} ).

        :param `b`: whether the event was dispatched or not.
        """

        self.dispatched = b

[docs]    def GetDispatched(self):
        """ Returns whether the event was dispatched (used for automatic L{AuiNotebook} ). """

        return self.dispatched

[docs]    def IsEditCancelled(self):
        """ Returns the edit cancel flag (for ``EVT_AUINOTEBOOK_BEGIN`` | ``END_LABEL_EDIT`` only)."""

        return self.editCancelled

[docs]    def SetEditCanceled(self, editCancelled):
        """
        Sets the edit cancel flag (for ``EVT_AUINOTEBOOK_BEGIN`` | ``END_LABEL_EDIT`` only).

        :param `editCancelled`: whether the editing action has been cancelled or not.
        """

        self.editCancelled = editCancelled

[docs]    def GetLabel(self):
        """Returns the label-itemtext (for ``EVT_AUINOTEBOOK_BEGIN`` | ``END_LABEL_EDIT`` only)."""

        return self.label

[docs]    def SetLabel(self, label):
        """
        Sets the label. Useful only for ``EVT_AUINOTEBOOK_END_LABEL_EDIT``.

        :param `label`: the new label.
        """

        self.label = label

    Page      = property(lambda self: self.page,
                         lambda self, page: setattr(self, 'page', page))
    Selection = property(lambda self: self.GetSelection(), lambda self, sel: self.SetSelection(sel))

# ----------------------------------------------------------------------

[docs]class AuiNotebookEvent(CommandNotebookEvent):
    """ A specialized command event class for events sent by L{AuiNotebook}. """

[docs]    def __init__(self, command_type=None, win_id=0):
        """
        Default class constructor.

        :param `command_type`: the event kind or an instance of `wx.PyCommandEvent`.
        :param `win_id`: the window identification number.
        """

        CommandNotebookEvent.__init__(self, command_type, win_id)

        if type(command_type) == types.IntType:
            self.notify = wx.NotifyEvent(command_type, win_id)
        else:
            self.notify = wx.NotifyEvent(command_type.GetEventType(), command_type.GetId())

[docs]    def GetNotifyEvent(self):
        """ Returns the actual `wx.NotifyEvent`. """

        return self.notify

[docs]    def IsAllowed(self):
        """ Returns whether the event is allowed or not. """

        return self.notify.IsAllowed()

[docs]    def Veto(self):
        """
        Prevents the change announced by this event from happening.

        It is in general a good idea to notify the user about the reasons for
        vetoing the change because otherwise the applications behaviour (which
        just refuses to do what the user wants) might be quite surprising.
        """

        self.notify.Veto()

[docs]    def Allow(self):
        """
        This is the opposite of L{Veto}: it explicitly allows the event to be
        processed. For most events it is not necessary to call this method as the
        events are allowed anyhow but some are forbidden by default (this will
        be mentioned in the corresponding event description).
        """

        self.notify.Allow()

# ---------------------------------------------------------------------------- #
# Class TabNavigatorProps
# ---------------------------------------------------------------------------- #

[docs]class TabNavigatorProps(object):
    """
    Data storage class for managing and providing access to L{TabNavigatorWindow}.
    properties.
    """

[docs]    def __init__(self):
        """ Default class constructor. """

        super(TabNavigatorProps, self).__init__()

        # Attributes
        self._icon = wx.NullBitmap
        self._font = wx.NullFont
        self._minsize = wx.DefaultSize

    # Accessors

    Icon = property(lambda self: self._icon,
                    lambda self, icon: setattr(self, '_icon', icon),
                    doc='Sets/Gets the icon for the L{TabNavigatorWindow}, an instance of `wx.Bitmap`.')
    Font = property(lambda self: self._font,
                    lambda self, font: setattr(self, '_font', font),
                    doc='Sets/Gets the font for the L{TabNavigatorWindow}, an instance of `wx.Font`.')
    MinSize = property(lambda self: self._minsize,
                       lambda self, size: setattr(self, '_minsize', size),
                       doc='Sets/Gets the minimum size for the L{TabNavigatorWindow}, an instance of `wx.Size`.')

# ---------------------------------------------------------------------------- #
# Class TabNavigatorWindow
# ---------------------------------------------------------------------------- #

[docs]class TabNavigatorWindow(wx.Dialog):
    """
    This class is used to create a modal dialog that enables "Smart Tabbing",
    similar to what you would get by hitting ``Alt`` + ``Tab`` on Windows.
    """

[docs]    def __init__(self, parent, props):
        """
        Default class constructor. Used internally.

        :param `parent`: the L{TabNavigatorWindow} parent;
        :param `props`: the L{TabNavigatorProps} object.
        """

        wx.Dialog.__init__(self, parent, wx.ID_ANY, "", size=props.MinSize, style=0)

        self._selectedItem = -1
        self._indexMap = []
        self._props = props

        if not self._props.Icon.IsOk():
            self._props.Icon = Mondrian.GetBitmap()

        if props.Icon.GetSize() != (16, 16):
            img = self._props.Icon.ConvertToImage()
            img.Rescale(16, 16, wx.IMAGE_QUALITY_HIGH)
            self._props.Icon = wx.BitmapFromImage(img)

        if self._props.Font.IsOk():
            self.Font = self._props.Font

        sz = wx.BoxSizer(wx.VERTICAL)

        self._listBox = wx.ListBox(self, wx.ID_ANY,
                                   wx.DefaultPosition,
                                   wx.Size(200, 150), [],
                                   wx.LB_SINGLE | wx.NO_BORDER)

        mem_dc = wx.MemoryDC()
        mem_dc.SelectObject(wx.EmptyBitmap(1,1))
        font = wx.SystemSettings_GetFont(wx.SYS_DEFAULT_GUI_FONT)
        font.SetWeight(wx.BOLD)
        mem_dc.SetFont(font)

        panelHeight = mem_dc.GetCharHeight()
        panelHeight += 4 # Place a spacer of 2 pixels

        # Out signpost bitmap is 24 pixels
        if panelHeight < 24:
            panelHeight = 24

        self._panel = wx.Panel(self, wx.ID_ANY, wx.DefaultPosition,
                               wx.Size(-1, panelHeight))

        sz.Add(self._panel, 0, wx.EXPAND)
        sz.Add(self._listBox, 1, wx.EXPAND)

        self.SetSizer(sz)

        # Connect events to the list box
        self._listBox.Bind(wx.EVT_KEY_UP, self.OnKeyUp)
        self._listBox.Bind(wx.EVT_NAVIGATION_KEY, self.OnNavigationKey)
        self._listBox.Bind(wx.EVT_LISTBOX_DCLICK, self.OnItemSelected)

        # Connect paint event to the panel
        self._panel.Bind(wx.EVT_PAINT, self.OnPanelPaint)
        self._panel.Bind(wx.EVT_ERASE_BACKGROUND, self.OnPanelEraseBg)

        self.SetBackgroundColour(wx.SystemSettings_GetColour(wx.SYS_COLOUR_3DFACE))
        self._listBox.SetBackgroundColour(wx.SystemSettings_GetColour(wx.SYS_COLOUR_3DFACE))
        self.PopulateListControl(parent)

        self.SetInitialSize(props.MinSize)
        self.Centre()

        # Set focus on the list box to avoid having to click on it to change
        # the tab selection under GTK.
        self._listBox.SetFocus()

[docs]    def OnKeyUp(self, event):
        """
        Handles the ``wx.EVT_KEY_UP`` for the L{TabNavigatorWindow}.

        :param `event`: a `wx.KeyEvent` event to be processed.
        """

        if event.GetKeyCode() == wx.WXK_CONTROL:
            self.CloseDialog()

[docs]    def OnNavigationKey(self, event):
        """
        Handles the ``wx.EVT_NAVIGATION_KEY`` for the L{TabNavigatorWindow}.

        :param `event`: a `wx.NavigationKeyEvent` event to be processed.
        """

        selected = self._listBox.GetSelection()
        bk = self.GetParent()
        maxItems = bk.GetPageCount()

        if event.GetDirection():

            # Select next page
            if selected == maxItems - 1:
                itemToSelect = 0
            else:
                itemToSelect = selected + 1

        else:

            # Previous page
            if selected == 0:
                itemToSelect = maxItems - 1
            else:
                itemToSelect = selected - 1

        self._listBox.SetSelection(itemToSelect)

[docs]    def PopulateListControl(self, book):
        """
        Populates the L{TabNavigatorWindow} listbox with a list of tabs.

        :param `book`: the actual L{AuiNotebook}.
        """
        # Index of currently selected page
        selection = book.GetSelection()
        # Total number of pages
        count = book.GetPageCount()
        # List of (index, AuiNotebookPage)
        pages = list(enumerate(book.GetTabContainer().GetPages()))
        if book.GetAGWWindowStyleFlag() & AUI_NB_ORDER_BY_ACCESS:
            # Sort pages using last access time. Most recently used is the
            # first in line
            pages.sort(
                key = lambda element: element[1].access_time,
                reverse = True
            )
        else:
            # Manually add the current selection as first item
            # Remaining ones are added in the next loop
            del pages[selection]
            self._listBox.Append(book.GetPageText(selection))
            self._indexMap.append(selection)

        for (index, page) in pages:
            self._listBox.Append(book.GetPageText(index))
            self._indexMap.append(index)

        # Select the next entry after the current selection
        self._listBox.SetSelection(0)
        dummy = wx.NavigationKeyEvent()
        dummy.SetDirection(True)
        self.OnNavigationKey(dummy)

[docs]    def OnItemSelected(self, event):
        """
        Handles the ``wx.EVT_LISTBOX_DCLICK`` event for the `wx.ListBox` inside L{TabNavigatorWindow}.

        :param `event`: a `wx.ListEvent` event to be processed.
        """

        self.CloseDialog()

[docs]    def CloseDialog(self):
        """ Closes the L{TabNavigatorWindow} dialog, setting selection in L{AuiNotebook}. """

        bk = self.GetParent()
        self._selectedItem = self._listBox.GetSelection()
        self.EndModal(wx.ID_OK)

[docs]    def GetSelectedPage(self):
        """ Gets the page index that was selected when the dialog was closed. """

        return self._indexMap[self._selectedItem]

[docs]    def OnPanelPaint(self, event):
        """
        Handles the ``wx.EVT_PAINT`` event for L{TabNavigatorWindow} top panel.

        :param `event`: a `wx.PaintEvent` event to be processed.
        """

        dc = wx.PaintDC(self._panel)
        rect = self._panel.GetClientRect()

        bmp = wx.EmptyBitmap(rect.width, rect.height)

        mem_dc = wx.MemoryDC()
        mem_dc.SelectObject(bmp)

        endColour = wx.SystemSettings_GetColour(wx.SYS_COLOUR_BTNSHADOW)
        startColour = LightColour(endColour, 50)
        mem_dc.GradientFillLinear(rect, startColour, endColour, wx.SOUTH)

        # Draw the caption title and place the bitmap
        # get the bitmap optimal position, and draw it
        bmpPt, txtPt = wx.Point(), wx.Point()
        bmpPt.y = (rect.height - self._props.Icon.GetHeight())/2
        bmpPt.x = 3
        mem_dc.DrawBitmap(self._props.Icon, bmpPt.x, bmpPt.y, True)

        # get the text position, and draw it
        font = wx.SystemSettings_GetFont(wx.SYS_DEFAULT_GUI_FONT)
        font.SetWeight(wx.BOLD)
        mem_dc.SetFont(font)
        fontHeight = mem_dc.GetCharHeight()

        txtPt.x = bmpPt.x + self._props.Icon.GetWidth() + 4
        txtPt.y = (rect.height - fontHeight)/2
        mem_dc.SetTextForeground(wx.WHITE)
        mem_dc.DrawText("Opened tabs:", txtPt.x, txtPt.y)
        mem_dc.SelectObject(wx.NullBitmap)

        dc.DrawBitmap(bmp, 0, 0)

[docs]    def OnPanelEraseBg(self, event):
        """
        Handles the ``wx.EVT_ERASE_BACKGROUND`` event for L{TabNavigatorWindow} top panel.

        :param `event`: a `wx.EraseEvent` event to be processed.

        :note: This is intentionally empty, to reduce flicker.
        """

        pass

# ----------------------------------------------------------------------
# -- AuiTabContainer class implementation --

[docs]class AuiTabContainer(object):
    """
    AuiTabContainer is a class which contains information about each
    tab. It also can render an entire tab control to a specified DC.
    It's not a window class itself, because this code will be used by
    the L{AuiManager}, where it is disadvantageous to have separate
    windows for each tab control in the case of "docked tabs".

    A derived class, L{AuiTabCtrl}, is an actual `wx.Window` - derived window
    which can be used as a tab control in the normal sense.
    """

[docs]    def __init__(self, auiNotebook):
        """
        Default class constructor.
        Used internally, do not call it in your code!

        :param `auiNotebook`: the parent L{AuiNotebook} window.
        """

        self._tab_offset = 0
        self._agwFlags = 0
        self._art = TA.AuiDefaultTabArt()

        self._buttons = []
        self._pages = []
        self._tab_close_buttons = []

        self._rect = wx.Rect()
        self._auiNotebook = auiNotebook

        self.AddButton(AUI_BUTTON_LEFT, wx.LEFT)
        self.AddButton(AUI_BUTTON_RIGHT, wx.RIGHT)
        self.AddButton(AUI_BUTTON_WINDOWLIST, wx.RIGHT)
        self.AddButton(AUI_BUTTON_CLOSE, wx.RIGHT)

[docs]    def SetArtProvider(self, art):
        """
        Instructs L{AuiTabContainer} to use art provider specified by parameter `art`
        for all drawing calls. This allows plugable look-and-feel features.

        :param `art`: an art provider.

        :note: The previous art provider object, if any, will be deleted by L{AuiTabContainer}.
        """

        del self._art
        self._art = art

        if self._art:
            self._art.SetAGWFlags(self._agwFlags)

[docs]    def GetArtProvider(self):
        """ Returns the current art provider being used. """

        return self._art

[docs]    def SetAGWFlags(self, agwFlags):
        """
        Sets the tab art flags.

        :param `agwFlags`: a combination of the following values:

         ==================================== ==================================
         Flag name                            Description
         ==================================== ==================================
         ``AUI_NB_TOP``                       With this style, tabs are drawn along the top of the notebook
         ``AUI_NB_LEFT``                      With this style, tabs are drawn along the left of the notebook. Not implemented yet
         ``AUI_NB_RIGHT``                     With this style, tabs are drawn along the right of the notebook. Not implemented yet
         ``AUI_NB_BOTTOM``                    With this style, tabs are drawn along the bottom of the notebook
         ``AUI_NB_TAB_SPLIT``                 Allows the tab control to be split by dragging a tab
         ``AUI_NB_TAB_MOVE``                  Allows a tab to be moved horizontally by dragging
         ``AUI_NB_TAB_EXTERNAL_MOVE``         Allows a tab to be moved to another tab control
         ``AUI_NB_TAB_FIXED_WIDTH``           With this style, all tabs have the same width
         ``AUI_NB_SCROLL_BUTTONS``            With this style, left and right scroll buttons are displayed
         ``AUI_NB_WINDOWLIST_BUTTON``         With this style, a drop-down list of windows is available
         ``AUI_NB_CLOSE_BUTTON``              With this style, a close button is available on the tab bar
         ``AUI_NB_CLOSE_ON_ACTIVE_TAB``       With this style, a close button is available on the active tab
         ``AUI_NB_CLOSE_ON_ALL_TABS``         With this style, a close button is available on all tabs
         ``AUI_NB_MIDDLE_CLICK_CLOSE``        Allows to close L{AuiNotebook} tabs by mouse middle button click
         ``AUI_NB_SUB_NOTEBOOK``              This style is used by L{AuiManager} to create automatic AuiNotebooks
         ``AUI_NB_HIDE_ON_SINGLE_TAB``        Hides the tab window if only one tab is present
         ``AUI_NB_SMART_TABS``                Use Smart Tabbing, like ``Alt`` + ``Tab`` on Windows
         ``AUI_NB_USE_IMAGES_DROPDOWN``       Uses images on dropdown window list menu instead of check items
         ``AUI_NB_CLOSE_ON_TAB_LEFT``         Draws the tab close button on the left instead of on the right (a la Camino browser)
         ``AUI_NB_TAB_FLOAT``                 Allows the floating of single tabs. Known limitation: when the notebook is more or less full screen, tabs cannot be dragged far enough outside of the notebook to become floating pages
         ``AUI_NB_DRAW_DND_TAB``              Draws an image representation of a tab while dragging (on by default)
         ``AUI_NB_ORDER_BY_ACCESS``           Tab navigation order by last access time for the tabs
         ``AUI_NB_NO_TAB_FOCUS``              Don't draw tab focus rectangle
         ==================================== ==================================

        :todo: Implementation of flags ``AUI_NB_RIGHT`` and ``AUI_NB_LEFT``.

        """

        self._agwFlags = agwFlags

        # check for new close button settings
        self.RemoveButton(AUI_BUTTON_LEFT)
        self.RemoveButton(AUI_BUTTON_RIGHT)
        self.RemoveButton(AUI_BUTTON_WINDOWLIST)
        self.RemoveButton(AUI_BUTTON_CLOSE)

        if agwFlags & AUI_NB_SCROLL_BUTTONS:
            self.AddButton(AUI_BUTTON_LEFT, wx.LEFT)
            self.AddButton(AUI_BUTTON_RIGHT, wx.RIGHT)

        if agwFlags & AUI_NB_WINDOWLIST_BUTTON:
            self.AddButton(AUI_BUTTON_WINDOWLIST, wx.RIGHT)

        if agwFlags & AUI_NB_CLOSE_BUTTON:
            self.AddButton(AUI_BUTTON_CLOSE, wx.RIGHT)

        if self._art:
            self._art.SetAGWFlags(self._agwFlags)

[docs]    def GetAGWFlags(self):
        """
        Returns the tab art flags.

        See L{SetAGWFlags} for a list of possible return values.

        :see: L{SetAGWFlags}
        """

        return self._agwFlags

[docs]    def SetNormalFont(self, font):
        """
        Sets the normal font for drawing tab labels.

        :param `font`: a `wx.Font` object.
        """

        self._art.SetNormalFont(font)

[docs]    def SetSelectedFont(self, font):
        """
        Sets the selected tab font for drawing tab labels.

        :param `font`: a `wx.Font` object.
        """

        self._art.SetSelectedFont(font)

[docs]    def SetMeasuringFont(self, font):
        """
        Sets the font for calculating text measurements.

        :param `font`: a `wx.Font` object.
        """

        self._art.SetMeasuringFont(font)

[docs]    def SetTabRect(self, rect):
        """
        Sets the tab area rectangle.

        :param `rect`: an instance of `wx.Rect`, specifying the available area for L{AuiTabContainer}.
        """

        self._rect = rect

        if self._art:
            minMaxTabWidth = self._auiNotebook.GetMinMaxTabWidth()
            self._art.SetSizingInfo(rect.GetSize(), len(self._pages), minMaxTabWidth)

[docs]    def AddPage(self, page, info):
        """
        Adds a page to the tab control.

        :param `page`: the window associated with this tab;
        :param `info`: an instance of L{AuiNotebookPage}.
        """

        page_info = info
        page_info.window = page

        self._pages.append(page_info)

        # let the art provider know how many pages we have
        if self._art:
            minMaxTabWidth = self._auiNotebook.GetMinMaxTabWidth()
            self._art.SetSizingInfo(self._rect.GetSize(), len(self._pages), minMaxTabWidth)

        return True

[docs]    def InsertPage(self, page, info, idx):
        """
        Inserts a page in the tab control in the position specified by `idx`.

        :param `page`: the window associated with this tab;
        :param `info`: an instance of L{AuiNotebookPage};
        :param `idx`: the page insertion index.
        """

        page_info = info
        page_info.window = page

        if idx >= len(self._pages):
            self._pages.append(page_info)
        else:
            self._pages.insert(idx, page_info)

        # let the art provider know how many pages we have
        if self._art:
            minMaxTabWidth = self._auiNotebook.GetMinMaxTabWidth()
            self._art.SetSizingInfo(self._rect.GetSize(), len(self._pages), minMaxTabWidth)

        return True

[docs]    def MovePage(self, page, new_idx):
        """
        Moves a page in a new position specified by `new_idx`.

        :param `page`: the window associated with this tab;
        :param `new_idx`: the new page position.
        """

        idx = self.GetIdxFromWindow(page)
        if idx == -1:
            return False

        # get page entry, make a copy of it
        p = self.GetPage(idx)

        # remove old page entry
        self.RemovePage(page)

        # insert page where it should be
        self.InsertPage(page, p, new_idx)

        return True

[docs]    def RemovePage(self, wnd):
        """
        Removes a page from the tab control.

        :param `wnd`: an instance of `wx.Window`, a window associated with this tab.
        """

        minMaxTabWidth = self._auiNotebook.GetMinMaxTabWidth()

        for page in self._pages:
            if page.window == wnd:
                self._pages.remove(page)
                self._tab_offset = min(self._tab_offset, len(self._pages) - 1)

                # let the art provider know how many pages we have
                if self._art:
                    self._art.SetSizingInfo(self._rect.GetSize(), len(self._pages), minMaxTabWidth)

                return True

        return False

[docs]    def SetActivePage(self, wndOrInt):
        """
        Sets the L{AuiTabContainer} active page.

        :param `wndOrInt`: an instance of `wx.Window` or an integer specifying a tab index.
        """

        if type(wndOrInt) == types.IntType:

            if wndOrInt >= len(self._pages):
                return False

            wnd = self._pages[wndOrInt].window

        else:
            wnd = wndOrInt

        found = False

        for indx, page in enumerate(self._pages):
            if page.window == wnd:
                page.active = True
                found = True
            else:
                page.active = False

        return found

[docs]    def SetNoneActive(self):
        """ Sets all the tabs as inactive (non-selected). """

        for page in self._pages:
            page.active = False

[docs]    def GetActivePage(self):
        """ Returns the current selected tab or ``wx.NOT_FOUND`` if none is selected. """

        for indx, page in enumerate(self._pages):
            if page.active:
                return indx

        return wx.NOT_FOUND

[docs]    def GetWindowFromIdx(self, idx):
        """
        Returns the window associated with the tab with index `idx`.

        :param `idx`: the tab index.
        """

        if idx >= len(self._pages):
            return None

        return self._pages[idx].window

[docs]    def GetIdxFromWindow(self, wnd):
        """
        Returns the tab index based on the window `wnd` associated with it.

        :param `wnd`: an instance of `wx.Window`.
        """

        for indx, page in enumerate(self._pages):
            if page.window == wnd:
                return indx

        return wx.NOT_FOUND

[docs]    def GetPage(self, idx):
        """
        Returns the page specified by the given index.

        :param `idx`: the tab index.
        """

        if idx < 0 or idx >= len(self._pages):
            raise Exception("Invalid Page index")

        return self._pages[idx]

[docs]    def GetPages(self):
        """ Returns a list of all the pages in this L{AuiTabContainer}. """

        return self._pages

[docs]    def GetPageCount(self):
        """ Returns the number of pages in the L{AuiTabContainer}. """

        return len(self._pages)

[docs]    def GetEnabled(self, idx):
        """
        Returns whether a tab is enabled or not.

        :param `idx`: the tab index.
        """

        if idx < 0 or idx >= len(self._pages):
            return False

        return self._pages[idx].enabled

[docs]    def EnableTab(self, idx, enable=True):
        """
        Enables/disables a tab in the L{AuiTabContainer}.

        :param `idx`: the tab index;
        :param `enable`: ``True`` to enable a tab, ``False`` to disable it.
        """

        if idx < 0 or idx >= len(self._pages):
            raise Exception("Invalid Page index")

        self._pages[idx].enabled = enable
        wnd = self.GetWindowFromIdx(idx)
        wnd.Enable(enable)

[docs]    def AddButton(self, id, location, normal_bitmap=wx.NullBitmap, disabled_bitmap=wx.NullBitmap):
        """
        Adds a button in the tab area.

        :param `id`: the button identifier. This can be one of the following:

         ==============================  =================================
         Button Identifier               Description
         ==============================  =================================
         ``AUI_BUTTON_CLOSE``            Shows a close button on the tab area
         ``AUI_BUTTON_WINDOWLIST``       Shows a window list button on the tab area
         ``AUI_BUTTON_LEFT``             Shows a left button on the tab area
         ``AUI_BUTTON_RIGHT``            Shows a right button on the tab area
         ==============================  =================================

        :param `location`: the button location. Can be ``wx.LEFT`` or ``wx.RIGHT``;
        :param `normal_bitmap`: the bitmap for an enabled tab;
        :param `disabled_bitmap`: the bitmap for a disabled tab.
        """

        button = AuiTabContainerButton()
        button.id = id
        button.bitmap = normal_bitmap
        button.dis_bitmap = disabled_bitmap
        button.location = location
        button.cur_state = AUI_BUTTON_STATE_NORMAL

        self._buttons.append(button)

[docs]    def CloneButtons(self):
        """
        Clones the tab area buttons when the L{AuiNotebook} is being split.

        :see: L{AddButton}

        :note: Standard buttons for L{AuiNotebook} are not cloned, only custom ones.
        """

        singleton_list = [AUI_BUTTON_CLOSE, AUI_BUTTON_WINDOWLIST, AUI_BUTTON_LEFT, AUI_BUTTON_RIGHT]
        clones = []

        for button in self._buttons:
            if button.id not in singleton_list:
                new_button = AuiTabContainerButton()
                new_button.id = button.id
                new_button.bitmap = button.bitmap
                new_button.dis_bitmap = button.dis_bitmap
                new_button.location = button.location
                clones.append(new_button)

        return clones

[docs]    def RemoveButton(self, id):
        """
        Removes a button from the tab area.

        :param `id`: the button identifier. See L{AddButton} for a list of button identifiers.

        :see: L{AddButton}
        """

        for button in self._buttons:
            if button.id == id:
                self._buttons.remove(button)
                return

[docs]    def GetTabOffset(self):
        """ Returns the tab offset. """

        return self._tab_offset

[docs]    def SetTabOffset(self, offset):
        """
        Sets the tab offset.

        :param `offset`: the tab offset.
        """

        self._tab_offset = offset

[docs]    def MinimizeTabOffset(self, dc, wnd, max_width):
        """
        Minimize `self._tab_offset` to fit as many tabs as possible in the available space.

        :param `dc`: a `wx.DC` device context;
        :param `wnd`: an instance of `wx.Window`;
        :param `max_width`: the maximum available width for the tabs.
        """

        total_width = 0

        for i, page in reversed(list(enumerate(self._pages))):

            tab_button = self._tab_close_buttons[i]
            (tab_width, tab_height), x_extent = self._art.GetTabSize(dc, wnd, page.caption, page.bitmap, page.active, tab_button.cur_state, page.control)
            total_width += tab_width

            if total_width > max_width:

                tab_offset = i + 1

                if tab_offset < self._tab_offset and tab_offset < len(self._pages):
                    self._tab_offset = tab_offset

                break

        if i == 0:
            self._tab_offset = 0

[docs]    def Render(self, raw_dc, wnd):
        """
        Renders the tab catalog to the specified `wx.DC`.

        It is a virtual function and can be overridden to provide custom drawing
        capabilities.

        :param `raw_dc`: a `wx.DC` device context;
        :param `wnd`: an instance of `wx.Window`.
        """

        if not raw_dc or not raw_dc.IsOk():
            return

        dc = wx.MemoryDC()

        # use the same layout direction as the window DC uses to ensure that the
        # text is rendered correctly
        dc.SetLayoutDirection(raw_dc.GetLayoutDirection())

        page_count = len(self._pages)
        button_count = len(self._buttons)

        # create off-screen bitmap
        bmp = wx.EmptyBitmap(self._rect.GetWidth(), self._rect.GetHeight())
        dc.SelectObject(bmp)

        if not dc.IsOk():
            return

        # find out if size of tabs is larger than can be
        # afforded on screen
        total_width = visible_width = 0

        for i in xrange(page_count):
            page = self._pages[i]

            # determine if a close button is on this tab
            close_button = False
            if (self._agwFlags & AUI_NB_CLOSE_ON_ALL_TABS and page.hasCloseButton) or \
               (self._agwFlags & AUI_NB_CLOSE_ON_ACTIVE_TAB and page.active and page.hasCloseButton):

                close_button = True

            control = page.control
            if control:
                try:
                    control.GetSize()
                except wx.PyDeadObjectError:
                    page.control = None

            size, x_extent = self._art.GetTabSize(dc, wnd, page.caption, page.bitmap, page.active,
                                                  (close_button and [AUI_BUTTON_STATE_NORMAL] or \
                                                   [AUI_BUTTON_STATE_HIDDEN])[0], page.control)

            if i+1 < page_count:
                total_width += x_extent
            else:
                total_width += size[0]

            if i >= self._tab_offset:
                if i+1 < page_count:
                    visible_width += x_extent
                else:
                    visible_width += size[0]

        buttons_width = 0

        for button in self._buttons:
            if not (button.cur_state & AUI_BUTTON_STATE_HIDDEN):
                buttons_width += button.rect.GetWidth()

        total_width += buttons_width

        if (total_width > self._rect.GetWidth() and page_count > 1) or self._tab_offset != 0:

            # show left/right buttons
            for button in self._buttons:
                if button.id == AUI_BUTTON_LEFT or \
                   button.id == AUI_BUTTON_RIGHT:

                    button.cur_state &= ~AUI_BUTTON_STATE_HIDDEN

        else:

            # hide left/right buttons
            for button in self._buttons:
                if button.id == AUI_BUTTON_LEFT or \
                   button.id == AUI_BUTTON_RIGHT:

                    button.cur_state |= AUI_BUTTON_STATE_HIDDEN

        # determine whether left button should be enabled
        for button in self._buttons:
            if button.id == AUI_BUTTON_LEFT:
                if self._tab_offset == 0:
                    button.cur_state |= AUI_BUTTON_STATE_DISABLED
                else:
                    button.cur_state &= ~AUI_BUTTON_STATE_DISABLED

            if button.id == AUI_BUTTON_RIGHT:
                if visible_width < self._rect.GetWidth() - buttons_width:
                    button.cur_state |= AUI_BUTTON_STATE_DISABLED
                else:
                    button.cur_state &= ~AUI_BUTTON_STATE_DISABLED

        # draw background
        self._art.DrawBackground(dc, wnd, self._rect)

        # draw buttons
        left_buttons_width = 0
        right_buttons_width = 0

        # draw the buttons on the right side
        offset = self._rect.x + self._rect.width

        for i in xrange(button_count):
            button = self._buttons[button_count - i - 1]

            if button.location != wx.RIGHT:
                continue
            if button.cur_state & AUI_BUTTON_STATE_HIDDEN:
                continue

            button_rect = wx.Rect(*self._rect)
            button_rect.SetY(1)
            button_rect.SetWidth(offset)

            button.rect = self._art.DrawButton(dc, wnd, button_rect, button, wx.RIGHT)

            offset -= button.rect.GetWidth()
            right_buttons_width += button.rect.GetWidth()

        offset = 0

        # draw the buttons on the left side
        for i in xrange(button_count):
            button = self._buttons[button_count - i - 1]

            if button.location != wx.LEFT:
                continue
            if button.cur_state & AUI_BUTTON_STATE_HIDDEN:
                continue

            button_rect = wx.Rect(offset, 1, 1000, self._rect.height)

            button.rect = self._art.DrawButton(dc, wnd, button_rect, button, wx.LEFT)

            offset += button.rect.GetWidth()
            left_buttons_width += button.rect.GetWidth()

        offset = left_buttons_width

        if offset == 0:
            offset += self._art.GetIndentSize()

        # prepare the tab-close-button array
        # make sure tab button entries which aren't used are marked as hidden
        for i in xrange(page_count, len(self._tab_close_buttons)):
            self._tab_close_buttons[i].cur_state = AUI_BUTTON_STATE_HIDDEN

        # make sure there are enough tab button entries to accommodate all tabs
        while len(self._tab_close_buttons) < page_count:
            tempbtn = AuiTabContainerButton()
            tempbtn.id = AUI_BUTTON_CLOSE
            tempbtn.location = wx.CENTER
            tempbtn.cur_state = AUI_BUTTON_STATE_HIDDEN
            self._tab_close_buttons.append(tempbtn)

        # buttons before the tab offset must be set to hidden
        for i in xrange(self._tab_offset):
            self._tab_close_buttons[i].cur_state = AUI_BUTTON_STATE_HIDDEN
            if self._pages[i].control:
                if self._pages[i].control.IsShown():
                    self._pages[i].control.Hide()

        self.MinimizeTabOffset(dc, wnd, self._rect.GetWidth() - right_buttons_width - offset - 2)

        # draw tab before tab offset
        if self._tab_offset > 0:
            page = self._pages[self._tab_offset - 1]
            tab_button = self._tab_close_buttons[self._tab_offset - 1]
            size, x_extent = self._art.GetTabSize(dc, wnd, page.caption, page.bitmap, page.active, tab_button.cur_state, page.control)

            rect = wx.Rect(offset - x_extent, 0, self._rect.width - right_buttons_width - offset - x_extent - 2, self._rect.height)
            clip_rect = wx.Rect(*self._rect)
            clip_rect.x = offset

            dc.SetClippingRect(clip_rect)
            self._art.DrawTab(dc, wnd, page, rect, tab_button.cur_state)
            dc.DestroyClippingRegion()

        # draw the tabs
        active = 999
        active_offset = 0

        rect = wx.Rect(*self._rect)
        rect.y = 0
        rect.height = self._rect.height

        for i in xrange(self._tab_offset, page_count):

            page = self._pages[i]
            tab_button = self._tab_close_buttons[i]

            # determine if a close button is on this tab
            if (self._agwFlags & AUI_NB_CLOSE_ON_ALL_TABS and page.hasCloseButton) or \
               (self._agwFlags & AUI_NB_CLOSE_ON_ACTIVE_TAB and page.active and page.hasCloseButton):

                if tab_button.cur_state == AUI_BUTTON_STATE_HIDDEN:

                    tab_button.id = AUI_BUTTON_CLOSE
                    tab_button.cur_state = AUI_BUTTON_STATE_NORMAL
                    tab_button.location = wx.CENTER

            else:

                tab_button.cur_state = AUI_BUTTON_STATE_HIDDEN

            rect.x = offset
            rect.width = self._rect.width - right_buttons_width - offset - 2

            if rect.width <= 0:
                break

            page.rect, tab_button.rect, x_extent = self._art.DrawTab(dc, wnd, page, rect, tab_button.cur_state)

            if page.active:
                active = i
                active_offset = offset
                active_rect = wx.Rect(*rect)

            offset += x_extent

        lenPages = len(self._pages)
        # make sure to deactivate buttons which are off the screen to the right
        for j in xrange(i+1, len(self._tab_close_buttons)):
            self._tab_close_buttons[j].cur_state = AUI_BUTTON_STATE_HIDDEN
            if j > 0 and j <= lenPages:
                if self._pages[j-1].control:
                    if self._pages[j-1].control.IsShown():
                        self._pages[j-1].control.Hide()

        # draw the active tab again so it stands in the foreground
        if active >= self._tab_offset and active < len(self._pages):

            page = self._pages[active]
            tab_button = self._tab_close_buttons[active]

            rect.x = active_offset
            dummy = self._art.DrawTab(dc, wnd, page, active_rect, tab_button.cur_state)

        raw_dc.Blit(self._rect.x, self._rect.y, self._rect.GetWidth(), self._rect.GetHeight(), dc, 0, 0)

[docs]    def IsTabVisible(self, tabPage, tabOffset, dc, wnd):
        """
        Returns whether a tab is visible or not.

        :param `tabPage`: the tab index;
        :param `tabOffset`: the tab offset;
        :param `dc`: a `wx.DC` device context;
        :param `wnd`: an instance of `wx.Window` derived window.
        """

        if not dc or not dc.IsOk():
            return False

        page_count = len(self._pages)
        button_count = len(self._buttons)
        self.Render(dc, wnd)

        # Hasn't been rendered yet assume it's visible
        if len(self._tab_close_buttons) < page_count:
            return True

        if self._agwFlags & AUI_NB_SCROLL_BUTTONS:
            # First check if both buttons are disabled - if so, there's no need to
            # check further for visibility.
            arrowButtonVisibleCount = 0
            for i in xrange(button_count):

                button = self._buttons[i]
                if button.id == AUI_BUTTON_LEFT or \
                   button.id == AUI_BUTTON_RIGHT:

                    if button.cur_state & AUI_BUTTON_STATE_HIDDEN == 0:
                        arrowButtonVisibleCount += 1

            # Tab must be visible
            if arrowButtonVisibleCount == 0:
                return True

        # If tab is less than the given offset, it must be invisible by definition
        if tabPage < tabOffset:
            return False

        # draw buttons
        left_buttons_width = 0
        right_buttons_width = 0

        offset = 0

        # calculate size of the buttons on the right side
        offset = self._rect.x + self._rect.width

        for i in xrange(button_count):
            button = self._buttons[button_count - i - 1]

            if button.location != wx.RIGHT:
                continue
            if button.cur_state & AUI_BUTTON_STATE_HIDDEN:
                continue

            offset -= button.rect.GetWidth()
            right_buttons_width += button.rect.GetWidth()

        offset = 0

        # calculate size of the buttons on the left side
        for i in xrange(button_count):
            button = self._buttons[button_count - i - 1]

            if button.location != wx.LEFT:
                continue
            if button.cur_state & AUI_BUTTON_STATE_HIDDEN:
                continue

            offset += button.rect.GetWidth()
            left_buttons_width += button.rect.GetWidth()

        offset = left_buttons_width

        if offset == 0:
            offset += self._art.GetIndentSize()

        rect = wx.Rect(*self._rect)
        rect.y = 0
        rect.height = self._rect.height

        # See if the given page is visible at the given tab offset (effectively scroll position)
        for i in xrange(tabOffset, page_count):

            page = self._pages[i]
            tab_button = self._tab_close_buttons[i]

            rect.x = offset
            rect.width = self._rect.width - right_buttons_width - offset - 2

            if rect.width <= 0:
                return False # haven't found the tab, and we've run out of space, so return False

            size, x_extent = self._art.GetTabSize(dc, wnd, page.caption, page.bitmap, page.active, tab_button.cur_state, page.control)
            offset += x_extent

            if i == tabPage:

                # If not all of the tab is visible, and supposing there's space to display it all,
                # we could do better so we return False.
                if (self._rect.width - right_buttons_width - offset - 2) <= 0 and (self._rect.width - right_buttons_width - left_buttons_width) > x_extent:
                    return False
                else:
                    return True

        # Shouldn't really get here, but if it does, assume the tab is visible to prevent
        # further looping in calling code.
        return True

[docs]    def MakeTabVisible(self, tabPage, win):
        """
        Make the tab visible if it wasn't already.

        :param `tabPage`: the tab index;
        :param `win`: an instance of `wx.Window` derived window.
        """

        dc = wx.ClientDC(win)

        if not self.IsTabVisible(tabPage, self.GetTabOffset(), dc, win):
            for i in xrange(len(self._pages)):
                if self.IsTabVisible(tabPage, i, dc, win):
                    self.SetTabOffset(i)
                    win.Refresh()
                    return

[docs]    def TabHitTest(self, x, y):
        """
        TabHitTest() tests if a tab was hit, passing the window pointer
        back if that condition was fulfilled.

        :param `x`: the mouse `x` position;
        :param `y`: the mouse `y` position.
        """

        if not self._rect.Contains((x,y)):
            return None

        btn = self.ButtonHitTest(x, y)
        if btn:
            if btn in self._buttons:
                return None

        for i in xrange(self._tab_offset, len(self._pages)):
            page = self._pages[i]
            if page.rect.Contains((x,y)):
                return page.window

        return None

[docs]    def ButtonHitTest(self, x, y):
        """
        Tests if a button was hit.

        :param `x`: the mouse `x` position;
        :param `y`: the mouse `y` position.

        :returns: and instance of L{AuiTabContainerButton} if a button was hit, ``None`` otherwise.
        """

        if not self._rect.Contains((x,y)):
            return None

        for button in self._buttons:
            if button.rect.Contains((x,y)) and \
               (button.cur_state & (AUI_BUTTON_STATE_HIDDEN|AUI_BUTTON_STATE_DISABLED)) == 0:
                return button

        for button in self._tab_close_buttons:
            if button.rect.Contains((x,y)) and \
               (button.cur_state & (AUI_BUTTON_STATE_HIDDEN|AUI_BUTTON_STATE_DISABLED)) == 0:
                return button

        return None

[docs]    def DoShowHide(self):
        """
        This function shows the active window, then hides all of the other windows
        (in that order).
        """

        pages = self.GetPages()

        # show new active page first
        for page in pages:
            if page.active:
                page.window.Show(True)
                break

        # hide all other pages
        for page in pages:
            if not page.active:
                page.window.Show(False)

# ----------------------------------------------------------------------
# -- AuiTabCtrl class implementation --

[docs]class AuiTabCtrl(wx.PyControl, AuiTabContainer):
    """
    This is an actual `wx.Window` - derived window which can be used as a tab
    control in the normal sense.
    """

[docs]    def __init__(self, parent, id=wx.ID_ANY, pos=wx.DefaultPosition, size=wx.DefaultSize,
                 style=wx.NO_BORDER|wx.WANTS_CHARS|wx.TAB_TRAVERSAL):
        """
        Default class constructor.
        Used internally, do not call it in your code!

        :param `parent`: the L{AuiTabCtrl} parent;
        :param `id`: an identifier for the control: a value of -1 is taken to mean a default;
        :param `pos`: the control position. A value of (-1, -1) indicates a default position,
         chosen by either the windowing system or wxPython, depending on platform;
        :param `size`: the control size. A value of (-1, -1) indicates a default size,
         chosen by either the windowing system or wxPython, depending on platform;
        :param `style`: the window style.
        """

        wx.PyControl.__init__(self, parent, id, pos, size, style, name="AuiTabCtrl")
        AuiTabContainer.__init__(self, parent)

        self._click_pt = wx.Point(-1, -1)
        self._is_dragging = False
        self._hover_button = None
        self._pressed_button = None
        self._drag_image = None
        self._drag_img_offset = (0, 0)
        self._on_button = False

        self.Bind(wx.EVT_PAINT, self.OnPaint)
        self.Bind(wx.EVT_ERASE_BACKGROUND, self.OnEraseBackground)
        self.Bind(wx.EVT_SIZE, self.OnSize)
        self.Bind(wx.EVT_LEFT_DOWN, self.OnLeftDown)
        self.Bind(wx.EVT_LEFT_DCLICK, self.OnLeftDClick)
        self.Bind(wx.EVT_LEFT_UP, self.OnLeftUp)
        self.Bind(wx.EVT_MIDDLE_DOWN, self.OnMiddleDown)
        self.Bind(wx.EVT_MIDDLE_UP, self.OnMiddleUp)
        self.Bind(wx.EVT_RIGHT_DOWN, self.OnRightDown)
        self.Bind(wx.EVT_RIGHT_UP, self.OnRightUp)
        self.Bind(wx.EVT_SET_FOCUS, self.OnSetFocus)
        self.Bind(wx.EVT_KILL_FOCUS, self.OnKillFocus)
        self.Bind(wx.EVT_KEY_DOWN, self.OnKeyDown)
        self.Bind(wx.EVT_MOUSE_CAPTURE_LOST, self.OnCaptureLost)
        self.Bind(wx.EVT_MOTION, self.OnMotion)
        self.Bind(wx.EVT_LEAVE_WINDOW, self.OnLeaveWindow)
        self.Bind(EVT_AUINOTEBOOK_BUTTON, self.OnButton)

[docs]    def IsDragging(self):
        """ Returns whether the user is dragging a tab with the mouse or not. """

        return self._is_dragging

[docs]    def GetDefaultBorder(self):
        """ Returns the default border style for L{AuiTabCtrl}. """

        return wx.BORDER_NONE

[docs]    def OnPaint(self, event):
        """
        Handles the ``wx.EVT_PAINT`` event for L{AuiTabCtrl}.

        :param `event`: a `wx.PaintEvent` event to be processed.
        """

        dc = wx.PaintDC(self)
        dc.SetFont(self.GetFont())

        if self.GetPageCount() > 0:
            self.Render(dc, self)

[docs]    def OnEraseBackground(self, event):
        """
        Handles the ``wx.EVT_ERASE_BACKGROUND`` event for L{AuiTabCtrl}.

        :param `event`: a `wx.EraseEvent` event to be processed.

        :note: This is intentionally empty, to reduce flicker.
        """

        pass

[docs]    def DoGetBestSize(self):
        """
        Gets the size which best suits the window: for a control, it would be the
        minimal size which doesn't truncate the control, for a panel - the same
        size as it would have after a call to `Fit()`.

        :note: Overridden from `wx.PyControl`.
        """

        return wx.Size(self._rect.width, self._rect.height)

[docs]    def OnSize(self, event):
        """
        Handles the ``wx.EVT_SIZE`` event for L{AuiTabCtrl}.

        :param `event`: a `wx.SizeEvent` event to be processed.
        """

        s = event.GetSize()
        self.SetTabRect(wx.Rect(0, 0, s.GetWidth(), s.GetHeight()))

[docs]    def OnLeftDown(self, event):
        """
        Handles the ``wx.EVT_LEFT_DOWN`` event for L{AuiTabCtrl}.

        :param `event`: a `wx.MouseEvent` event to be processed.
        """

        if not self.HasCapture():
            self.CaptureMouse()

        self._click_pt = wx.Point(-1, -1)
        self._is_dragging = False
        self._click_tab = None
        self._pressed_button = None

        wnd = self.TabHitTest(event.GetX(), event.GetY())

        if wnd is not None:
            new_selection = self.GetIdxFromWindow(wnd)

            # AuiNotebooks always want to receive this event
            # even if the tab is already active, because they may
            # have multiple tab controls
            if new_selection != self.GetActivePage() or isinstance(self.GetParent(), AuiNotebook):

                e = AuiNotebookEvent(wxEVT_COMMAND_AUINOTEBOOK_PAGE_CHANGING, self.GetId())
                e.SetSelection(new_selection)
                e.SetOldSelection(self.GetActivePage())
                e.SetEventObject(self)
                self.GetEventHandler().ProcessEvent(e)

            self._click_pt.x = event.GetX()
            self._click_pt.y = event.GetY()
            self._click_tab = wnd

            wnd.SetFocus()
        else:
            page_index = self.GetActivePage()
            if page_index != wx.NOT_FOUND:
                self.GetWindowFromIdx(page_index).SetFocus()

            self._hover_button = self.ButtonHitTest(event.GetX(), event.GetY())

            if self._hover_button:
                self._pressed_button = self._hover_button
                self._pressed_button.cur_state = AUI_BUTTON_STATE_PRESSED
                self._on_button = True

                self.Refresh()
                self.Update()

[docs]    def OnCaptureLost(self, event):
        """
        Handles the ``wx.EVT_MOUSE_CAPTURE_LOST`` event for L{AuiTabCtrl}.

        :param `event`: a `wx.MouseCaptureLostEvent` event to be processed.
        """

        if self._is_dragging:
            self._is_dragging = False
            self._on_button = False

            if self._drag_image:
                self._drag_image.EndDrag()
                del self._drag_image
                self._drag_image = None

            event = AuiNotebookEvent(wxEVT_COMMAND_AUINOTEBOOK_CANCEL_DRAG, self.GetId())
            event.SetSelection(self.GetIdxFromWindow(self._click_tab))
            event.SetOldSelection(event.GetSelection())
            event.SetEventObject(self)
            self.GetEventHandler().ProcessEvent(event)

[docs]    def OnLeftUp(self, event):
        """
        Handles the ``wx.EVT_LEFT_UP`` event for L{AuiTabCtrl}.

        :param `event`: a `wx.MouseEvent` event to be processed.
        """

        self._on_button = False

        if self._is_dragging:

            if self.HasCapture():
                self.ReleaseMouse()

            self._is_dragging = False
            if self._drag_image:
                self._drag_image.EndDrag()
                del self._drag_image
                self._drag_image = None
                self.GetParent().Refresh()

            evt = AuiNotebookEvent(wxEVT_COMMAND_AUINOTEBOOK_END_DRAG, self.GetId())
            evt.SetSelection(self.GetIdxFromWindow(self._click_tab))
            evt.SetOldSelection(evt.GetSelection())
            evt.SetEventObject(self)
            self.GetEventHandler().ProcessEvent(evt)

            return

        self.GetParent()._mgr.HideHint()

        if self.HasCapture():
            self.ReleaseMouse()

        if self._hover_button:
            self._pressed_button = self._hover_button
            self._hover_button.cur_state = AUI_BUTTON_STATE_NORMAL

        if self._pressed_button:

            # make sure we're still clicking the button
            button = self.ButtonHitTest(event.GetX(), event.GetY())

            if button is None:
                return

            if button != self._pressed_button:
                self._pressed_button = None
                return

            self.Refresh()
            self.Update()

            if self._pressed_button.cur_state & AUI_BUTTON_STATE_DISABLED == 0:

                evt = AuiNotebookEvent(wxEVT_COMMAND_AUINOTEBOOK_BUTTON, self.GetId())
                evt.SetSelection(self.GetIdxFromWindow(self._click_tab))
                evt.SetInt(self._pressed_button.id)
                evt.SetEventObject(self)
                eventHandler = self.GetEventHandler()

                if eventHandler is not None:
                    eventHandler.ProcessEvent(evt)

            self._pressed_button = None

        self._click_pt = wx.Point(-1, -1)
        self._is_dragging = False
        self._click_tab = None

[docs]    def OnMiddleUp(self, event):
        """
        Handles the ``wx.EVT_MIDDLE_UP`` event for L{AuiTabCtrl}.

        :param `event`: a `wx.MouseEvent` event to be processed.
        """

        eventHandler = self.GetEventHandler()
        if not isinstance(eventHandler, AuiTabCtrl):
            event.Skip()
            return

        x, y = event.GetX(), event.GetY()
        wnd = self.TabHitTest(x, y)

        if wnd:
            e = AuiNotebookEvent(wxEVT_COMMAND_AUINOTEBOOK_TAB_MIDDLE_UP, self.GetId())
            e.SetEventObject(self)
            e.Page = wnd
            e.SetSelection(self.GetIdxFromWindow(wnd))
            self.GetEventHandler().ProcessEvent(e)
        elif not self.ButtonHitTest(x, y):
            e = AuiNotebookEvent(wxEVT_COMMAND_AUINOTEBOOK_BG_MIDDLE_UP, self.GetId())
            e.SetEventObject(self)
            self.GetEventHandler().ProcessEvent(e)

[docs]    def OnMiddleDown(self, event):
        """
        Handles the ``wx.EVT_MIDDLE_DOWN`` event for L{AuiTabCtrl}.

        :param `event`: a `wx.MouseEvent` event to be processed.
        """

        eventHandler = self.GetEventHandler()
        if not isinstance(eventHandler, AuiTabCtrl):
            event.Skip()
            return

        x, y = event.GetX(), event.GetY()
        wnd = self.TabHitTest(x, y)

        if wnd:
            e = AuiNotebookEvent(wxEVT_COMMAND_AUINOTEBOOK_TAB_MIDDLE_DOWN, self.GetId())
            e.SetEventObject(self)
            e.Page = wnd
            e.SetSelection(self.GetIdxFromWindow(wnd))
            self.GetEventHandler().ProcessEvent(e)
        elif not self.ButtonHitTest(x, y):
            e = AuiNotebookEvent(wxEVT_COMMAND_AUINOTEBOOK_BG_MIDDLE_DOWN, self.GetId())
            e.SetEventObject(self)
            self.GetEventHandler().ProcessEvent(e)

[docs]    def OnRightUp(self, event):
        """
        Handles the ``wx.EVT_RIGHT_UP`` event for L{AuiTabCtrl}.

        :param `event`: a `wx.MouseEvent` event to be processed.
        """

        x, y = event.GetX(), event.GetY()
        wnd = self.TabHitTest(x, y)

        if wnd:
            e = AuiNotebookEvent(wxEVT_COMMAND_AUINOTEBOOK_TAB_RIGHT_UP, self.GetId())
            e.SetEventObject(self)
            e.Selection = self.GetIdxFromWindow(wnd)
            e.Page = wnd
            self.GetEventHandler().ProcessEvent(e)
        elif not self.ButtonHitTest(x, y):
            e = AuiNotebookEvent(wxEVT_COMMAND_AUINOTEBOOK_BG_RIGHT_UP, self.GetId())
            e.SetEventObject(self)
            self.GetEventHandler().ProcessEvent(e)

[docs]    def OnRightDown(self, event):
        """
        Handles the ``wx.EVT_RIGHT_DOWN`` event for L{AuiTabCtrl}.

        :param `event`: a `wx.MouseEvent` event to be processed.
        """

        x, y = event.GetX(), event.GetY()
        wnd = self.TabHitTest(x, y)

        if wnd:
            e = AuiNotebookEvent(wxEVT_COMMAND_AUINOTEBOOK_TAB_RIGHT_DOWN, self.GetId())
            e.SetEventObject(self)
            e.SetSelection(self.GetIdxFromWindow(wnd))
            e.Page = wnd
            self.GetEventHandler().ProcessEvent(e)
        elif not self.ButtonHitTest(x, y):
            e = AuiNotebookEvent(wxEVT_COMMAND_AUINOTEBOOK_BG_RIGHT_DOWN, self.GetId())
            e.SetEventObject(self)
            self.GetEventHandler().ProcessEvent(e)

[docs]    def OnLeftDClick(self, event):
        """
        Handles the ``wx.EVT_LEFT_DCLICK`` event for L{AuiTabCtrl}.

        :param `event`: a `wx.MouseEvent` event to be processed.
        """

        x, y = event.GetX(), event.GetY()
        wnd = self.TabHitTest(x, y)

        if wnd:
            e = AuiNotebookEvent(wxEVT_COMMAND_AUINOTEBOOK_TAB_DCLICK, self.GetId())
            e.SetEventObject(self)
            e.SetSelection(self.GetIdxFromWindow(wnd))
            e.Page = wnd
            self.GetEventHandler().ProcessEvent(e)
        elif not self.ButtonHitTest(x, y):
            e = AuiNotebookEvent(wxEVT_COMMAND_AUINOTEBOOK_BG_DCLICK, self.GetId())
            e.SetEventObject(self)
            self.GetEventHandler().ProcessEvent(e)

[docs]    def OnMotion(self, event):
        """
        Handles the ``wx.EVT_MOTION`` event for L{AuiTabCtrl}.

        :param `event`: a `wx.MouseEvent` event to be processed.
        """

        pos = event.GetPosition()

        # check if the mouse is hovering above a button

        button = self.ButtonHitTest(pos.x, pos.y)
        wnd = self.TabHitTest(pos.x, pos.y)

        if wnd is not None:
            mouse_tab = self.GetIdxFromWindow(wnd)
            if not self._pages[mouse_tab].enabled:
                self._hover_button = None
                return

        if self._on_button:
            return

        if button:

            if self._hover_button and button != self._hover_button:
                self._hover_button.cur_state = AUI_BUTTON_STATE_NORMAL
                self._hover_button = None
                self.Refresh()
                self.Update()

            if button.cur_state != AUI_BUTTON_STATE_HOVER:
                button.cur_state = AUI_BUTTON_STATE_HOVER
                self.Refresh()
                self.Update()
                self._hover_button = button
                return

        else:

            if self._hover_button:
                self._hover_button.cur_state = AUI_BUTTON_STATE_NORMAL
                self._hover_button = None
                self.Refresh()
                self.Update()

        if not event.LeftIsDown() or self._click_pt == wx.Point(-1, -1):
            return

        if not self.HasCapture():
            return

        wnd = self.TabHitTest(pos.x, pos.y)

        if not self._is_dragging:

            drag_x_threshold = wx.SystemSettings.GetMetric(wx.SYS_DRAG_X)
            drag_y_threshold = wx.SystemSettings.GetMetric(wx.SYS_DRAG_Y)

            if abs(pos.x - self._click_pt.x) > drag_x_threshold or \
               abs(pos.y - self._click_pt.y) > drag_y_threshold:

                self._is_dragging = True

                if self._drag_image:
                    self._drag_image.EndDrag()
                    del self._drag_image
                    self._drag_image = None

                if self._agwFlags & AUI_NB_DRAW_DND_TAB:
                    # Create the custom draw image from the icons and the text of the item
                    mouse_tab = self.GetIdxFromWindow(wnd)
                    page = self._pages[mouse_tab]
                    tab_button = self._tab_close_buttons[mouse_tab]
                    self._drag_image = TabDragImage(self, page, tab_button.cur_state, self._art)

                    if self._agwFlags & AUI_NB_TAB_FLOAT:
                        self._drag_image.BeginDrag(wx.Point(0,0), self, fullScreen=True)
                    else:
                        self._drag_image.BeginDragBounded(wx.Point(0,0), self, self.GetParent())

                    # Capture the mouse cursor position offset relative to
                    # The tab image location
                    self._drag_img_offset = (pos[0] - page.rect.x,
                                             pos[1] - page.rect.y)

                    self._drag_image.Show()

        if not wnd:
            evt2 = AuiNotebookEvent(wxEVT_COMMAND_AUINOTEBOOK_BEGIN_DRAG, self.GetId())
            evt2.SetSelection(self.GetIdxFromWindow(self._click_tab))
            evt2.SetOldSelection(evt2.GetSelection())
            evt2.SetEventObject(self)
            self.GetEventHandler().ProcessEvent(evt2)
            if evt2.GetDispatched():
                return

        evt3 = AuiNotebookEvent(wxEVT_COMMAND_AUINOTEBOOK_DRAG_MOTION, self.GetId())
        evt3.SetSelection(self.GetIdxFromWindow(self._click_tab))
        evt3.SetOldSelection(evt3.GetSelection())
        evt3.SetEventObject(self)
        self.GetEventHandler().ProcessEvent(evt3)

        if self._drag_image:
            # Apply the drag images offset
            pos -= self._drag_img_offset
            self._drag_image.Move(pos)

[docs]    def OnLeaveWindow(self, event):
        """
        Handles the ``wx.EVT_LEAVE_WINDOW`` event for L{AuiTabCtrl}.

        :param `event`: a `wx.MouseEvent` event to be processed.
        """

        if self._hover_button:
            self._hover_button.cur_state = AUI_BUTTON_STATE_NORMAL
            self._hover_button = None
            self.Refresh()
            self.Update()

[docs]    def OnButton(self, event):
        """
        Handles the ``EVT_AUINOTEBOOK_BUTTON`` event for L{AuiTabCtrl}.

        :param `event`: a L{AuiNotebookEvent} event to be processed.
        """

        button = event.GetInt()

        if button == AUI_BUTTON_LEFT or button == AUI_BUTTON_RIGHT:
            if button == AUI_BUTTON_LEFT:
                if self.GetTabOffset() > 0:

                    self.SetTabOffset(self.GetTabOffset()-1)
                    self.Refresh()
                    self.Update()
            else:
                self.SetTabOffset(self.GetTabOffset()+1)
                self.Refresh()
                self.Update()

        elif button == AUI_BUTTON_WINDOWLIST:
            idx = self.GetArtProvider().ShowDropDown(self, self._pages, self.GetActivePage())

            if idx != -1:

                e = AuiNotebookEvent(wxEVT_COMMAND_AUINOTEBOOK_PAGE_CHANGING, self.GetId())
                e.SetSelection(idx)
                e.SetOldSelection(self.GetActivePage())
                e.SetEventObject(self)
                self.GetEventHandler().ProcessEvent(e)

        else:
            event.Skip()

[docs]    def OnSetFocus(self, event):
        """
        Handles the ``wx.EVT_SET_FOCUS`` event for L{AuiTabCtrl}.

        :param `event`: a `wx.FocusEvent` event to be processed.
        """

        self.Refresh()

[docs]    def OnKillFocus(self, event):
        """
        Handles the ``wx.EVT_KILL_FOCUS`` event for L{AuiTabCtrl}.

        :param `event`: a `wx.FocusEvent` event to be processed.
        """

        self.Refresh()

[docs]    def OnKeyDown(self, event):
        """
        Handles the ``wx.EVT_KEY_DOWN`` event for L{AuiTabCtrl}.

        :param `event`: a `wx.KeyEvent` event to be processed.
        """

        key = event.GetKeyCode()
        nb = self.GetParent()

        if key == wx.WXK_LEFT:
            nb.AdvanceSelection(False)
            self.SetFocus()

        elif key == wx.WXK_RIGHT:
            nb.AdvanceSelection(True)
            self.SetFocus()

        elif key == wx.WXK_HOME:
            newPage = 0
            nb.SetSelection(newPage)
            self.SetFocus()

        elif key == wx.WXK_END:
            newPage = nb.GetPageCount() - 1
            nb.SetSelection(newPage)
            self.SetFocus()

        elif key == wx.WXK_TAB:
            if not event.ControlDown():
                flags = 0
                if not event.ShiftDown(): flags |= wx.NavigationKeyEvent.IsForward
                if event.CmdDown():       flags |= wx.NavigationKeyEvent.WinChange
                self.Navigate(flags)
            else:

                if not nb or not isinstance(nb, AuiNotebook):
                    event.Skip()
                    return

                bForward = bWindowChange = 0
                if not event.ShiftDown(): bForward |= wx.NavigationKeyEvent.IsForward
                if event.CmdDown():       bWindowChange |= wx.NavigationKeyEvent.WinChange

                keyEvent = wx.NavigationKeyEvent()
                keyEvent.SetDirection(bForward)
                keyEvent.SetWindowChange(bWindowChange)
                keyEvent.SetFromTab(True)
                keyEvent.SetEventObject(nb)

                if not nb.GetEventHandler().ProcessEvent(keyEvent):

                    # Not processed? Do an explicit tab into the page.
                    win = self.GetWindowFromIdx(self.GetActivePage())
                    if win:
                        win.SetFocus()

                self.SetFocus()

                return

        else:
            event.Skip()

[docs]    def OnKeyDown2(self, event):
        """
        Deprecated.

        Handles the ``wx.EVT_KEY_DOWN`` event for L{AuiTabCtrl}.

        :param `event`: a `wx.KeyEvent` event to be processed.

        :warning: This method implementation is now deprecated. Refer to L{OnKeyDown}
         for the correct one.
        """

        if self.GetActivePage() == -1:
            event.Skip()
            return

        # We can't leave tab processing to the system on Windows, tabs and keys
        # get eaten by the system and not processed properly if we specify both
        # wxTAB_TRAVERSAL and wxWANTS_CHARS. And if we specify just wxTAB_TRAVERSAL,
        # we don't key arrow key events.

        key = event.GetKeyCode()

        if key == wx.WXK_NUMPAD_PAGEUP:
            key = wx.WXK_PAGEUP
        if key == wx.WXK_NUMPAD_PAGEDOWN:
            key = wx.WXK_PAGEDOWN
        if key == wx.WXK_NUMPAD_HOME:
            key = wx.WXK_HOME
        if key == wx.WXK_NUMPAD_END:
            key = wx.WXK_END
        if key == wx.WXK_NUMPAD_LEFT:
            key = wx.WXK_LEFT
        if key == wx.WXK_NUMPAD_RIGHT:
            key = wx.WXK_RIGHT

        if key == wx.WXK_TAB or key == wx.WXK_PAGEUP or key == wx.WXK_PAGEDOWN:

            bCtrlDown = event.ControlDown()
            bShiftDown = event.ShiftDown()

            bForward = (key == wx.WXK_TAB and not bShiftDown) or (key == wx.WXK_PAGEDOWN)
            bWindowChange = (key == wx.WXK_PAGEUP) or (key == wx.WXK_PAGEDOWN) or bCtrlDown
            bFromTab = (key == wx.WXK_TAB)

            nb = self.GetParent()
            if not nb or not isinstance(nb, AuiNotebook):
                event.Skip()
                return

            keyEvent = wx.NavigationKeyEvent()
            keyEvent.SetDirection(bForward)
            keyEvent.SetWindowChange(bWindowChange)
            keyEvent.SetFromTab(bFromTab)
            keyEvent.SetEventObject(nb)

            if not nb.GetEventHandler().ProcessEvent(keyEvent):

                # Not processed? Do an explicit tab into the page.
                win = self.GetWindowFromIdx(self.GetActivePage())
                if win:
                    win.SetFocus()

            return

        if len(self._pages) < 2:
            event.Skip()
            return

        newPage = -1

        if self.GetLayoutDirection() == wx.Layout_RightToLeft:
            forwardKey = wx.WXK_LEFT
            backwardKey = wx.WXK_RIGHT
        else:
            forwardKey = wx.WXK_RIGHT
            backwardKey = wx.WXK_LEFT

        if key == forwardKey:
            if self.GetActivePage() == -1:
                newPage = 0
            elif self.GetActivePage() < len(self._pages) - 1:
                newPage = self.GetActivePage() + 1

        elif key == backwardKey:
            if self.GetActivePage() == -1:
                newPage = len(self._pages) - 1
            elif self.GetActivePage() > 0:
                newPage = self.GetActivePage() - 1

        elif key == wx.WXK_HOME:
            newPage = 0

        elif key == wx.WXK_END:
            newPage = len(self._pages) - 1

        else:
            event.Skip()

        if newPage != -1:
            e = AuiNotebookEvent(wxEVT_COMMAND_AUINOTEBOOK_PAGE_CHANGING, self.GetId())
            e.SetSelection(newPage)
            e.SetOldSelection(newPage)
            e.SetEventObject(self)
            self.GetEventHandler().ProcessEvent(e)

        else:
            event.Skip()

# ----------------------------------------------------------------------

[docs]class TabFrame(wx.PyWindow):
    """
    TabFrame is an interesting case. It's important that all child pages
    of the multi-notebook control are all actually children of that control
    (and not grandchildren). TabFrame facilitates this. There is one
    instance of TabFrame for each tab control inside the multi-notebook.

    It's important to know that TabFrame is not a real window, but it merely
    used to capture the dimensions/positioning of the internal tab control and
    it's managed page windows.
    """

[docs]    def __init__(self, parent):
        """
        Default class constructor.
        Used internally, do not call it in your code!
        """

        pre = wx.PrePyWindow()

        self._tabs = None
        self._rect = wx.Rect(0, 0, 200, 200)
        self._tab_ctrl_height = 20
        self._tab_rect = wx.Rect()
        self._parent = parent

        self.PostCreate(pre)

[docs]    def SetTabCtrlHeight(self, h):
        """
        Sets the tab control height.

        :param `h`: the tab area height.
        """

        self._tab_ctrl_height = h

[docs]    def DoSetSize(self, x, y, width, height, flags=wx.SIZE_AUTO):
        """
        Sets the position and size of the window in pixels. The `flags`
        parameter indicates the interpretation of the other params if they are
        equal to -1.

        :param `x`: the window `x` position;
        :param `y`: the window `y` position;
        :param `width`: the window width;
        :param `height`: the window height;
        :param `flags`: may have one of this bit set:

         ===================================  ======================================
         Size Flags                           Description
         ===================================  ======================================
         ``wx.SIZE_AUTO``                     A -1 indicates that a class-specific default should be used.
         ``wx.SIZE_AUTO_WIDTH``               A -1 indicates that a class-specific default should be used for the width.
         ``wx.SIZE_AUTO_HEIGHT``              A -1 indicates that a class-specific default should be used for the height.
         ``wx.SIZE_USE_EXISTING``             Existing dimensions should be used if -1 values are supplied.
         ``wx.SIZE_ALLOW_MINUS_ONE``          Allow dimensions of -1 and less to be interpreted as real dimensions, not default values.
         ``wx.SIZE_FORCE``                    Normally, if the position and the size of the window are already the same as the parameters of this function, nothing is done. but with this flag a window resize may be forced even in this case (supported in wx 2.6.2 and later and only implemented for MSW and ignored elsewhere currently)
         ===================================  ======================================

        :note: Overridden from `wx.PyControl`.
        """

        self._rect = wx.Rect(x, y, max(1, width), max(1, height))
        self.DoSizing()

[docs]    def DoGetSize(self):
        """
        Returns the window size.

        :note: Overridden from `wx.PyControl`.
        """

        return self._rect.width, self._rect.height

[docs]    def DoGetClientSize(self):
        """
        Returns the window client size.

        :note: Overridden from `wx.PyControl`.
        """

        return self._rect.width, self._rect.height

[docs]    def Show(self, show=True):
        """
        Shows/hides the window.

        :param `show`: ``True`` to show the window, ``False`` otherwise.

        :note:

         Overridden from `wx.PyControl`, this method always returns ``False`` as
         L{TabFrame} should never be phisically shown on screen.
        """

        return False

[docs]    def DoSizing(self):
        """ Does the actual sizing of the tab control. """

        if not self._tabs:
            return

        hideOnSingle = ((self._tabs.GetAGWFlags() & AUI_NB_HIDE_ON_SINGLE_TAB) and \
                        self._tabs.GetPageCount() <= 1)

        if not hideOnSingle and not self._parent._hide_tabs:
            tab_height = self._tab_ctrl_height

            self._tab_rect = wx.Rect(self._rect.x, self._rect.y, self._rect.width, self._tab_ctrl_height)

            if self._tabs.GetAGWFlags() & AUI_NB_BOTTOM:
                self._tab_rect = wx.Rect(self._rect.x, self._rect.y + self._rect.height - tab_height,
                                         self._rect.width, tab_height)
                self._tabs.SetDimensions(self._rect.x, self._rect.y + self._rect.height - tab_height,
                                         self._rect.width, tab_height)
                self._tabs.SetTabRect(wx.Rect(0, 0, self._rect.width, tab_height))

            else:

                self._tab_rect = wx.Rect(self._rect.x, self._rect.y, self._rect.width, tab_height)
                self._tabs.SetDimensions(self._rect.x, self._rect.y, self._rect.width, tab_height)
                self._tabs.SetTabRect(wx.Rect(0, 0, self._rect.width, tab_height))

            # TODO: elif (GetAGWFlags() & AUI_NB_LEFT)
            # TODO: elif (GetAGWFlags() & AUI_NB_RIGHT)

            self._tabs.Refresh()
            self._tabs.Update()

        else:

            tab_height = 0
            self._tabs.SetDimensions(self._rect.x, self._rect.y, self._rect.width, tab_height)
            self._tabs.SetTabRect(wx.Rect(0, 0, self._rect.width, tab_height))

        pages = self._tabs.GetPages()

        for page in pages:

            height = self._rect.height - tab_height

            if height < 0:
                # avoid passing negative height to wx.Window.SetSize(), this
                # results in assert failures/GTK+ warnings
                height = 0

            if self._tabs.GetAGWFlags() & AUI_NB_BOTTOM:
                page.window.SetDimensions(self._rect.x, self._rect.y, self._rect.width, height)

            else:
                page.window.SetDimensions(self._rect.x, self._rect.y + tab_height,
                                          self._rect.width, height)

            # TODO: elif (GetAGWFlags() & AUI_NB_LEFT)
            # TODO: elif (GetAGWFlags() & AUI_NB_RIGHT)

            if repr(page.window.__class__).find("AuiMDIChildFrame") >= 0:
                page.window.ApplyMDIChildFrameRect()

[docs]    def Update(self):
        """
        Calling this method immediately repaints the invalidated area of the window
        and all of its children recursively while this would usually only happen when
        the flow of control returns to the event loop.

        :note: Notice that this function doesn't invalidate any area of the window so
         nothing happens if nothing has been invalidated (i.e. marked as requiring a redraw).
         Use `Refresh` first if you want to immediately redraw the window unconditionally.

        :note: Overridden from `wx.PyControl`.
        """

        # does nothing
        pass

# ----------------------------------------------------------------------
# -- AuiNotebook class implementation --

[docs]class AuiNotebook(wx.PyPanel):
    """
    AuiNotebook is a notebook control which implements many features common in
    applications with dockable panes. Specifically, AuiNotebook implements functionality
    which allows the user to rearrange tab order via drag-and-drop, split the tab window
    into many different splitter configurations, and toggle through different themes to
    customize the control's look and feel.

    An effort has been made to try to maintain an API as similar to that of `wx.Notebook`.

    The default theme that is used is L{AuiDefaultTabArt}, which provides a modern, glossy
    look and feel. The theme can be changed by calling L{AuiNotebook.SetArtProvider}.
    """

[docs]    def __init__(self, parent, id=wx.ID_ANY, pos=wx.DefaultPosition, size=wx.DefaultSize,
                 style=0, agwStyle=AUI_NB_DEFAULT_STYLE, name="AuiNotebook"):
        """
        Default class constructor.

        :param `parent`: the L{AuiNotebook} parent;
        :param `id`: an identifier for the control: a value of -1 is taken to mean a default;
        :param `pos`: the control position. A value of (-1, -1) indicates a default position,
         chosen by either the windowing system or wxPython, depending on platform;
        :param `size`: the control size. A value of (-1, -1) indicates a default size,
         chosen by either the windowing system or wxPython, depending on platform;
        :param `style`: the underlying `wx.PyPanel` window style;
        :param `agwStyle`: the AGW-specific window style. This can be a combination of the following bits:

         ==================================== ==================================
         Flag name                            Description
         ==================================== ==================================
         ``AUI_NB_TOP``                       With this style, tabs are drawn along the top of the notebook
         ``AUI_NB_LEFT``                      With this style, tabs are drawn along the left of the notebook. Not implemented yet.
         ``AUI_NB_RIGHT``                     With this style, tabs are drawn along the right of the notebook. Not implemented yet.
         ``AUI_NB_BOTTOM``                    With this style, tabs are drawn along the bottom of the notebook
         ``AUI_NB_TAB_SPLIT``                 Allows the tab control to be split by dragging a tab
         ``AUI_NB_TAB_MOVE``                  Allows a tab to be moved horizontally by dragging
         ``AUI_NB_TAB_EXTERNAL_MOVE``         Allows a tab to be moved to another tab control
         ``AUI_NB_TAB_FIXED_WIDTH``           With this style, all tabs have the same width
         ``AUI_NB_SCROLL_BUTTONS``            With this style, left and right scroll buttons are displayed
         ``AUI_NB_WINDOWLIST_BUTTON``         With this style, a drop-down list of windows is available
         ``AUI_NB_CLOSE_BUTTON``              With this style, a close button is available on the tab bar
         ``AUI_NB_CLOSE_ON_ACTIVE_TAB``       With this style, a close button is available on the active tab
         ``AUI_NB_CLOSE_ON_ALL_TABS``         With this style, a close button is available on all tabs
         ``AUI_NB_MIDDLE_CLICK_CLOSE``        Allows to close L{AuiNotebook} tabs by mouse middle button click
         ``AUI_NB_SUB_NOTEBOOK``              This style is used by L{AuiManager} to create automatic AuiNotebooks
         ``AUI_NB_HIDE_ON_SINGLE_TAB``        Hides the tab window if only one tab is present
         ``AUI_NB_SMART_TABS``                Use Smart Tabbing, like ``Alt`` + ``Tab`` on Windows
         ``AUI_NB_USE_IMAGES_DROPDOWN``       Uses images on dropdown window list menu instead of check items
         ``AUI_NB_CLOSE_ON_TAB_LEFT``         Draws the tab close button on the left instead of on the right (a la Camino browser)
         ``AUI_NB_TAB_FLOAT``                 Allows the floating of single tabs. Known limitation: when the notebook is more or less full screen, tabs cannot be dragged far enough outside of the notebook to become floating pages
         ``AUI_NB_DRAW_DND_TAB``              Draws an image representation of a tab while dragging (on by default)
         ``AUI_NB_ORDER_BY_ACCESS``           Tab navigation order by last access time for the tabs
         ``AUI_NB_NO_TAB_FOCUS``              Don't draw tab focus rectangle
         ==================================== ==================================

         Default value for `agwStyle` is:
         ``AUI_NB_DEFAULT_STYLE`` = ``AUI_NB_TOP`` | ``AUI_NB_TAB_SPLIT`` | ``AUI_NB_TAB_MOVE`` | ``AUI_NB_SCROLL_BUTTONS`` | ``AUI_NB_CLOSE_ON_ACTIVE_TAB`` | ``AUI_NB_MIDDLE_CLICK_CLOSE`` | ``AUI_NB_DRAW_DND_TAB``

        :param `name`: the window name.
        """

        self._curpage = -1
        self._tab_id_counter = AuiBaseTabCtrlId
        self._dummy_wnd = None
        self._hide_tabs = False
        self._sash_dclick_unsplit = False
        self._tab_ctrl_height = 20
        self._requested_bmp_size = wx.Size(-1, -1)
        self._requested_tabctrl_height = -1
        self._textCtrl = None
        self._tabBounds = (-1, -1)
        self._click_tab = None

        wx.PyPanel.__init__(self, parent, id, pos, size, style|wx.BORDER_NONE|wx.TAB_TRAVERSAL, name=name)
        self._mgr = framemanager.AuiManager()
        self._tabs = AuiTabContainer(self)

        self.InitNotebook(agwStyle)

    NavigatorProps = property(lambda self: self._navProps)

[docs]    def Destroy(self):
        """
        Destroys the window safely.

        Use this function instead of the `del` operator, since different window
        classes can be destroyed differently. Frames and dialogs are not destroyed
        immediately when this function is called -- they are added to a list of
        windows to be deleted on idle time, when all the window's events have been
        processed. This prevents problems with events being sent to non-existent windows.

        :return: ``True`` if the window has either been successfully deleted, or
         it has been added to the list of windows pending real deletion.
        """

        self._mgr.UnInit()
        return wx.PyPanel.Destroy(self)

[docs]    def GetTabContainer(self):
        """ Returns the instance of L{AuiTabContainer}. """

        return self._tabs

[docs]    def InitNotebook(self, agwStyle):
        """
        Contains common initialization code called by all constructors.

        :param `agwStyle`: the notebook style.

        :see: L{__init__}
        """

        self._agwFlags = agwStyle

        self._popupWin = None
        self._imageList = None
        self._navProps = TabNavigatorProps()
        self._last_drag_x = 0

        self._normal_font = wx.SystemSettings.GetFont(wx.SYS_DEFAULT_GUI_FONT)
        self._selected_font = wx.SystemSettings.GetFont(wx.SYS_DEFAULT_GUI_FONT)
        self._selected_font.SetWeight(wx.BOLD)

        self.SetArtProvider(TA.AuiDefaultTabArt())

        self._dummy_wnd = wx.Window(self, wx.ID_ANY, wx.Point(0, 0), wx.Size(0, 0))
        self._dummy_wnd.SetSize((200, 200))
        self._dummy_wnd.Show(False)

        self._mgr.SetManagedWindow(self)
        self._mgr.SetAGWFlags(AUI_MGR_DEFAULT)
        self._mgr.SetDockSizeConstraint(1.0, 1.0) # no dock size constraint

        self._mgr.AddPane(self._dummy_wnd, framemanager.AuiPaneInfo().Name("dummy").Bottom().CaptionVisible(False).Show(False))
        self._mgr.Update()

        self.Bind(wx.EVT_SIZE, self.OnSize)
        self.Bind(wx.EVT_CHILD_FOCUS, self.OnChildFocusNotebook)
        self.Bind(EVT_AUINOTEBOOK_PAGE_CHANGING, self.OnTabClicked,
                  id=AuiBaseTabCtrlId, id2=AuiBaseTabCtrlId+500)
        self.Bind(EVT_AUINOTEBOOK_BEGIN_DRAG, self.OnTabBeginDrag,
                  id=AuiBaseTabCtrlId, id2=AuiBaseTabCtrlId+500)
        self.Bind(EVT_AUINOTEBOOK_END_DRAG, self.OnTabEndDrag,
                  id=AuiBaseTabCtrlId, id2=AuiBaseTabCtrlId+500)
        self.Bind(EVT_AUINOTEBOOK_DRAG_MOTION, self.OnTabDragMotion,
                  id=AuiBaseTabCtrlId, id2=AuiBaseTabCtrlId+500)
        self.Bind(EVT_AUINOTEBOOK_CANCEL_DRAG, self.OnTabCancelDrag,
                  id=AuiBaseTabCtrlId, id2=AuiBaseTabCtrlId+500)
        self.Bind(EVT_AUINOTEBOOK_BUTTON, self.OnTabButton,
                  id=AuiBaseTabCtrlId, id2=AuiBaseTabCtrlId+500)
        self.Bind(EVT_AUINOTEBOOK_TAB_MIDDLE_DOWN, self.OnTabMiddleDown,
                  id=AuiBaseTabCtrlId, id2=AuiBaseTabCtrlId+500)
        self.Bind(EVT_AUINOTEBOOK_TAB_MIDDLE_UP, self.OnTabMiddleUp,
                  id=AuiBaseTabCtrlId, id2=AuiBaseTabCtrlId+500)
        self.Bind(EVT_AUINOTEBOOK_TAB_RIGHT_DOWN, self.OnTabRightDown,
                  id=AuiBaseTabCtrlId, id2=AuiBaseTabCtrlId+500)
        self.Bind(EVT_AUINOTEBOOK_TAB_RIGHT_UP, self.OnTabRightUp,
                  id=AuiBaseTabCtrlId, id2=AuiBaseTabCtrlId+500)
        self.Bind(EVT_AUINOTEBOOK_BG_DCLICK, self.OnTabBgDClick,
                  id=AuiBaseTabCtrlId, id2=AuiBaseTabCtrlId+500)
        self.Bind(EVT_AUINOTEBOOK_TAB_DCLICK, self.OnTabDClick,
                  id=AuiBaseTabCtrlId, id2=AuiBaseTabCtrlId+500)

        self.Bind(wx.EVT_NAVIGATION_KEY, self.OnNavigationKeyNotebook)

[docs]    def SetArtProvider(self, art):
        """
        Sets the art provider to be used by the notebook.

        :param `art`: an art provider.
        """

        self._tabs.SetArtProvider(art)
        self.UpdateTabCtrlHeight(force=True)

[docs]    def SavePerspective(self):
        """
        Saves the entire user interface layout into an encoded string, which can then
        be stored by the application (probably using `wx.Config`). When a perspective
        is restored using L{LoadPerspective}, the entire user interface will return
        to the state it was when the perspective was saved.
        """

        # Build list of panes/tabs
        tabs = ""
        all_panes = self._mgr.GetAllPanes()

        for pane in all_panes:

            if pane.name == "dummy":
                continue

            tabframe = pane.window

            if tabs:
                tabs += "|"

            tabs += pane.name + "="

            # add tab id's
            page_count = tabframe._tabs.GetPageCount()

            for p in xrange(page_count):

                page = tabframe._tabs.GetPage(p)
                page_idx = self._tabs.GetIdxFromWindow(page.window)

                if p:
                    tabs += ","

                if p == tabframe._tabs.GetActivePage():
                    tabs += "+"
                elif page_idx == self._curpage:
                    tabs += "*"

                tabs += "%u"%page_idx

        tabs += "@"

        # Add frame perspective
        tabs += self._mgr.SavePerspective()

        return tabs

[docs]    def LoadPerspective(self, layout):
        """
        Loads a layout which was saved with L{SavePerspective}.

        :param `layout`: a string which contains a saved L{AuiNotebook} layout.
        """

        # Remove all tab ctrls (but still keep them in main index)
        tab_count = self._tabs.GetPageCount()
        for i in xrange(tab_count):
            wnd = self._tabs.GetWindowFromIdx(i)

            # find out which onscreen tab ctrl owns this tab
            ctrl, ctrl_idx = self.FindTab(wnd)
            if not ctrl:
                return False

            # remove the tab from ctrl
            if not ctrl.RemovePage(wnd):
                return False

        self.RemoveEmptyTabFrames()

        sel_page = 0
        tabs = layout[0:layout.index("@")]
        to_break1 = False

        while 1:

            if "|" not in tabs:
                to_break1 = True
                tab_part = tabs
            else:
                tab_part = tabs[0:tabs.index('|')]

            if "=" not in tab_part:
                # No pages in this perspective...
                return False

            # Get pane name
            pane_name = tab_part[0:tab_part.index("=")]

            # create a new tab frame
            new_tabs = TabFrame(self)
            self._tab_id_counter += 1
            new_tabs._tabs = AuiTabCtrl(self, self._tab_id_counter)
            new_tabs._tabs.SetArtProvider(self._tabs.GetArtProvider().Clone())
            new_tabs.SetTabCtrlHeight(self._tab_ctrl_height)
            new_tabs._tabs.SetAGWFlags(self._agwFlags)
            dest_tabs = new_tabs._tabs

            # create a pane info structure with the information
            # about where the pane should be added
            pane_info = framemanager.AuiPaneInfo().Name(pane_name).Bottom().CaptionVisible(False)
            self._mgr.AddPane(new_tabs, pane_info)

            # Get list of tab id's and move them to pane
            tab_list = tab_part[tab_part.index("=")+1:]
            to_break2, active_found = False, False

            while 1:
                if "," not in tab_list:
                    to_break2 = True
                    tab = tab_list
                else:
                    tab = tab_list[0:tab_list.index(",")]
                    tab_list = tab_list[tab_list.index(",")+1:]

                # Check if this page has an 'active' marker
                c = tab[0]
                if c in ['+', '*']:
                    tab = tab[1:]

                tab_idx = int(tab)
                if tab_idx >= self.GetPageCount():
                    to_break1 = True
                    break

                # Move tab to pane
                page = self._tabs.GetPage(tab_idx)
                newpage_idx = dest_tabs.GetPageCount()
                dest_tabs.InsertPage(page.window, page, newpage_idx)

                if c == '+':
                    dest_tabs.SetActivePage(newpage_idx)
                    active_found = True
                elif c == '*':
                    sel_page = tab_idx

                if to_break2:
                    break

            if not active_found:
                dest_tabs.SetActivePage(0)

            new_tabs.DoSizing()
            dest_tabs.DoShowHide()
            dest_tabs.Refresh()

            if to_break1:
                break

            tabs = tabs[tabs.index('|')+1:]

        # Load the frame perspective
        frames = layout[layout.index('@')+1:]
        self._mgr.LoadPerspective(frames)

        # Force refresh of selection
        self._curpage = -1
        self.SetSelection(sel_page)

        return True

[docs]    def SetTabCtrlHeight(self, height):
        """
        Sets the tab height.

        By default, the tab control height is calculated by measuring the text
        height and bitmap sizes on the tab captions.

        Calling this method will override that calculation and set the tab control
        to the specified height parameter. A call to this method will override
        any call to L{SetUniformBitmapSize}. Specifying -1 as the height will
        return the control to its default auto-sizing behaviour.

        :param `height`: the tab control area height.
        """

        self._requested_tabctrl_height = height

        # if window is already initialized, recalculate the tab height
        if self._dummy_wnd:
            self.UpdateTabCtrlHeight()

[docs]    def SetUniformBitmapSize(self, size):
        """
        Ensures that all tabs will have the same height, even if some tabs
        don't have bitmaps. Passing ``wx.DefaultSize`` to this
        function will instruct the control to use dynamic tab height, which is
        the default behaviour. Under the default behaviour, when a tab with a
        large bitmap is added, the tab control's height will automatically
        increase to accommodate the larger bitmap.

        :param `size`: an instance of `wx.Size` specifying the tab bitmap size.
        """

        self._requested_bmp_size = wx.Size(*size)

        # if window is already initialized, recalculate the tab height
        if self._dummy_wnd:
            self.UpdateTabCtrlHeight()

[docs]    def UpdateTabCtrlHeight(self, force=False):
        """
        UpdateTabCtrlHeight() does the actual tab resizing. It's meant
        to be used interally.

        :param `force`: ``True`` to force the tab art to repaint.
        """

        # get the tab ctrl height we will use
        height = self.CalculateTabCtrlHeight()

        # if the tab control height needs to change, update
        # all of our tab controls with the new height
        if self._tab_ctrl_height != height or force:
            art = self._tabs.GetArtProvider()

            self._tab_ctrl_height = height

            all_panes = self._mgr.GetAllPanes()
            for pane in all_panes:

                if pane.name == "dummy":
                    continue

                tab_frame = pane.window
                tabctrl = tab_frame._tabs
                tab_frame.SetTabCtrlHeight(self._tab_ctrl_height)
                tabctrl.SetArtProvider(art.Clone())
                tab_frame.DoSizing()

[docs]    def UpdateHintWindowSize(self):
        """ Updates the L{AuiManager} hint window size. """

        size = self.CalculateNewSplitSize()

        # the placeholder hint window should be set to this size
        info = self._mgr.GetPane("dummy")

        if info.IsOk():
            info.MinSize(size)
            info.BestSize(size)
            self._dummy_wnd.SetSize(size)

[docs]    def CalculateNewSplitSize(self):
        """ Calculates the size of the new split. """

        # count number of tab controls
        tab_ctrl_count = 0
        all_panes = self._mgr.GetAllPanes()

        for pane in all_panes:
            if pane.name == "dummy":
                continue

            tab_ctrl_count += 1

        # if there is only one tab control, the first split
        # should happen around the middle
        if tab_ctrl_count < 2:
            new_split_size = self.GetClientSize()
            new_split_size.x /= 2
            new_split_size.y /= 2

        else:

            # this is in place of a more complicated calculation
            # that needs to be implemented
            new_split_size = wx.Size(180, 180)

        return new_split_size

[docs]    def CalculateTabCtrlHeight(self):
        """ Calculates the tab control area height. """

        # if a fixed tab ctrl height is specified,
        # just return that instead of calculating a
        # tab height
        if self._requested_tabctrl_height != -1:
            return self._requested_tabctrl_height

        # find out new best tab height
        art = self._tabs.GetArtProvider()

        return art.GetBestTabCtrlSize(self, self._tabs.GetPages(), self._requested_bmp_size)

[docs]    def GetArtProvider(self):
        """ Returns the associated art provider. """

        return self._tabs.GetArtProvider()

[docs]    def SetAGWWindowStyleFlag(self, agwStyle):
        """
        Sets the AGW-specific style of the window.

        :param `agwStyle`: the new window style. This can be a combination of the following bits:

         ==================================== ==================================
         Flag name                            Description
         ==================================== ==================================
         ``AUI_NB_TOP``                       With this style, tabs are drawn along the top of the notebook
         ``AUI_NB_LEFT``                      With this style, tabs are drawn along the left of the notebook. Not implemented yet.
         ``AUI_NB_RIGHT``                     With this style, tabs are drawn along the right of the notebook. Not implemented yet.
         ``AUI_NB_BOTTOM``                    With this style, tabs are drawn along the bottom of the notebook
         ``AUI_NB_TAB_SPLIT``                 Allows the tab control to be split by dragging a tab
         ``AUI_NB_TAB_MOVE``                  Allows a tab to be moved horizontally by dragging
         ``AUI_NB_TAB_EXTERNAL_MOVE``         Allows a tab to be moved to another tab control
         ``AUI_NB_TAB_FIXED_WIDTH``           With this style, all tabs have the same width
         ``AUI_NB_SCROLL_BUTTONS``            With this style, left and right scroll buttons are displayed
         ``AUI_NB_WINDOWLIST_BUTTON``         With this style, a drop-down list of windows is available
         ``AUI_NB_CLOSE_BUTTON``              With this style, a close button is available on the tab bar
         ``AUI_NB_CLOSE_ON_ACTIVE_TAB``       With this style, a close button is available on the active tab
         ``AUI_NB_CLOSE_ON_ALL_TABS``         With this style, a close button is available on all tabs
         ``AUI_NB_MIDDLE_CLICK_CLOSE``        Allows to close L{AuiNotebook} tabs by mouse middle button click
         ``AUI_NB_SUB_NOTEBOOK``              This style is used by L{AuiManager} to create automatic AuiNotebooks
         ``AUI_NB_HIDE_ON_SINGLE_TAB``        Hides the tab window if only one tab is present
         ``AUI_NB_SMART_TABS``                Use Smart Tabbing, like ``Alt`` + ``Tab`` on Windows
         ``AUI_NB_USE_IMAGES_DROPDOWN``       Uses images on dropdown window list menu instead of check items
         ``AUI_NB_CLOSE_ON_TAB_LEFT``         Draws the tab close button on the left instead of on the right (a la Camino browser)
         ``AUI_NB_TAB_FLOAT``                 Allows the floating of single tabs. Known limitation: when the notebook is more or less full screen, tabs cannot be dragged far enough outside of the notebook to become floating pages
         ``AUI_NB_DRAW_DND_TAB``              Draws an image representation of a tab while dragging (on by default)
         ``AUI_NB_ORDER_BY_ACCESS``           Tab navigation order by last access time for the tabs
         ``AUI_NB_NO_TAB_FOCUS``              Don't draw tab focus rectangle
         ==================================== ==================================

        :note: Please note that some styles cannot be changed after the window
         creation and that `Refresh` might need to be be called after changing the
         others for the change to take place immediately.

        :todo: Implementation of flags ``AUI_NB_RIGHT`` and ``AUI_NB_LEFT``.
        """

        self._agwFlags = agwStyle

        # if the control is already initialized
        if self._mgr.GetManagedWindow() == self:

            # let all of the tab children know about the new style

            all_panes = self._mgr.GetAllPanes()
            for pane in all_panes:
                if pane.name == "dummy":
                    continue

                tabframe = pane.window
                tabctrl = tabframe._tabs
                tabctrl.SetAGWFlags(self._agwFlags)
                tabframe.DoSizing()
                tabctrl.Refresh()
                tabctrl.Update()

[docs]    def GetAGWWindowStyleFlag(self):
        """
        Returns the AGW-specific style of the window.

        :see: L{SetAGWWindowStyleFlag} for a list of possible AGW-specific window styles.
        """

        return self._agwFlags

[docs]    def AddPage(self, page, caption, select=False, bitmap=wx.NullBitmap, disabled_bitmap=wx.NullBitmap, control=None):
        """
        Adds a page. If the `select` parameter is ``True``, calling this will generate a
        page change event.

        :param `page`: the page to be added;
        :param `caption`: specifies the text for the new page;
        :param `select`: specifies whether the page should be selected;
        :param `bitmap`: the `wx.Bitmap` to display in the enabled tab;
        :param `disabled_bitmap`: the `wx.Bitmap` to display in the disabled tab;
        :param `control`: a `wx.Window` instance inside a tab (or ``None``).
        """

        return self.InsertPage(self.GetPageCount(), page, caption, select, bitmap, disabled_bitmap, control)

[docs]    def InsertPage(self, page_idx, page, caption, select=False, bitmap=wx.NullBitmap, disabled_bitmap=wx.NullBitmap,
                   control=None):
        """
        This is similar to L{AddPage}, but allows the ability to specify the insert location.

        :param `page_idx`: specifies the position for the new page;
        :param `page`: the page to be added;
        :param `caption`: specifies the text for the new page;
        :param `select`: specifies whether the page should be selected;
        :param `bitmap`: the `wx.Bitmap` to display in the enabled tab;
        :param `disabled_bitmap`: the `wx.Bitmap` to display in the disabled tab;
        :param `control`: a `wx.Window` instance inside a tab (or ``None``).
        """

        if not page:
            return False

        page.Reparent(self)
        info = AuiNotebookPage()
        info.window = page
        info.caption = caption
        info.bitmap = bitmap
        info.active = False
        info.control = control

        originalPaneMgr = framemanager.GetManager(page)
        if originalPaneMgr:
            originalPane = originalPaneMgr.GetPane(page)

            if originalPane:
                info.hasCloseButton = originalPane.HasCloseButton()

        if bitmap.IsOk() and not disabled_bitmap.IsOk():
            disabled_bitmap = MakeDisabledBitmap(bitmap)

        info.dis_bitmap = disabled_bitmap

        # if there are currently no tabs, the first added
        # tab must be active
        if self._tabs.GetPageCount() == 0:
            info.active = True

        self._tabs.InsertPage(page, info, page_idx)

        # if that was the first page added, even if
        # select is False, it must become the "current page"
        # (though no select events will be fired)
        if not select and self._tabs.GetPageCount() == 1:
            select = True

        active_tabctrl = self.GetActiveTabCtrl()
        if page_idx >= active_tabctrl.GetPageCount():
            active_tabctrl.AddPage(page, info)
        else:
            active_tabctrl.InsertPage(page, info, page_idx)

        force = False
        if control:
            force = True
            control.Reparent(active_tabctrl)
            control.Show()

        self.UpdateTabCtrlHeight(force=force)
        self.DoSizing()
        active_tabctrl.DoShowHide()

        # adjust selected index
        if self._curpage >= page_idx:
            self._curpage += 1

        if select:
            self.SetSelectionToWindow(page)

        return True

[docs]    def DeletePage(self, page_idx):
        """
        Deletes a page at the given index. Calling this method will generate a page
        change event.

        :param `page_idx`: the page index to be deleted.

        :note:

         L{DeletePage} removes a tab from the multi-notebook, and destroys the window as well.

        :see: L{RemovePage}
        """

        if page_idx >= self._tabs.GetPageCount():
            return False

        wnd = self._tabs.GetWindowFromIdx(page_idx)
        # hide the window in advance, as this will
        # prevent flicker
        wnd.Show(False)

        self.RemoveControlFromPage(page_idx)

        if not self.RemovePage(page_idx):
            return False

        wnd.Destroy()

        return True

[docs]    def RemovePage(self, page_idx):
        """
        Removes a page, without deleting the window pointer.

        :param `page_idx`: the page index to be removed.

        :note:

         L{RemovePage} removes a tab from the multi-notebook, but does not destroy the window.

        :see: L{DeletePage}
        """

        # save active window pointer
        active_wnd = None
        if self._curpage >= 0:
            active_wnd = self._tabs.GetWindowFromIdx(self._curpage)

        # save pointer of window being deleted
        wnd = self._tabs.GetWindowFromIdx(page_idx)
        new_active = None

        # make sure we found the page
        if not wnd:
            return False

        # find out which onscreen tab ctrl owns this tab
        ctrl, ctrl_idx = self.FindTab(wnd)
        if not ctrl:
            return False

        currentPage = ctrl.GetPage(ctrl_idx)
        is_curpage = (self._curpage == page_idx)
        is_active_in_split = currentPage.active

        # remove the tab from main catalog
        if not self._tabs.RemovePage(wnd):
            return False

        # remove the tab from the onscreen tab ctrl
        ctrl.RemovePage(wnd)

        if is_active_in_split:

            ctrl_new_page_count = ctrl.GetPageCount()

            if ctrl_idx >= ctrl_new_page_count:
                ctrl_idx = ctrl_new_page_count - 1

            if ctrl_idx >= 0 and ctrl_idx < ctrl.GetPageCount():

                ctrl_idx = self.FindNextActiveTab(ctrl_idx, ctrl)

                # set new page as active in the tab split
                ctrl.SetActivePage(ctrl_idx)

                # if the page deleted was the current page for the
                # entire tab control, then record the window
                # pointer of the new active page for activation
                if is_curpage:
                    new_active = ctrl.GetWindowFromIdx(ctrl_idx)

        else:

            # we are not deleting the active page, so keep it the same
            new_active = active_wnd

        if not new_active:

            # we haven't yet found a new page to active,
            # so select the next page from the main tab
            # catalogue

            if 0 <= page_idx < self._tabs.GetPageCount():
                new_active = self._tabs.GetPage(page_idx).window
            if not new_active and self._tabs.GetPageCount() > 0:
                new_active = self._tabs.GetPage(0).window

        self.RemoveEmptyTabFrames()

        # set new active pane
        if new_active:
            if not self.IsBeingDeleted():
                self._curpage = -1
                self.SetSelectionToWindow(new_active)
        else:
            self._curpage = -1
            self._tabs.SetNoneActive()

        return True

[docs]    def FindNextActiveTab(self, ctrl_idx, ctrl):
        """
        Finds the next active tab (used mainly when L{AuiNotebook} has inactive/disabled
        tabs in it).

        :param `ctrl_idx`: the index of the first (most obvious) tab to check for active status;
        :param `ctrl`: an instance of L{AuiTabCtrl}.
        """

        if self.GetEnabled(ctrl_idx):
            return ctrl_idx

        for indx in xrange(ctrl_idx, ctrl.GetPageCount()):
            if self.GetEnabled(indx):
                return indx

        for indx in xrange(ctrl_idx, -1, -1):
            if self.GetEnabled(indx):
                return indx

        return 0

[docs]    def HideAllTabs(self, hidden=True):
        """
        Hides all tabs on the L{AuiNotebook} control.

        :param `hidden`: if ``True`` hides all tabs.
        """

        self._hide_tabs = hidden

[docs]    def SetSashDClickUnsplit(self, unsplit=True):
        """
        Sets whether to unsplit a splitted L{AuiNotebook} when double-clicking on a sash.

        :param `unsplit`: ``True`` to unsplit on sash double-clicking, ``False`` otherwise.
        """

        self._sash_dclick_unsplit = unsplit

[docs]    def GetSashDClickUnsplit(self):
        """
        Returns whether a splitted L{AuiNotebook} can be unsplitted by double-clicking
        on the splitter sash.
        """

        return self._sash_dclick_unsplit

[docs]    def SetMinMaxTabWidth(self, minTabWidth, maxTabWidth):
        """
        Sets the minimum and/or the maximum tab widths for L{AuiNotebook} when the
        ``AUI_NB_TAB_FIXED_WIDTH`` style is defined.

        Pass -1 to either `minTabWidth` or `maxTabWidth` to reset to the default tab
        width behaviour for L{AuiNotebook}.

        :param `minTabWidth`: the minimum allowed tab width, in pixels;
        :param `maxTabWidth`: the maximum allowed tab width, in pixels.

        :note: Minimum and maximum tabs widths are used only when the ``AUI_NB_TAB_FIXED_WIDTH``
         style is present.
        """

        if minTabWidth > maxTabWidth:
            raise Exception("Minimum tab width must be less or equal than maximum tab width")

        self._tabBounds = (minTabWidth, maxTabWidth)
        self.SetAGWWindowStyleFlag(self._agwFlags)

[docs]    def GetMinMaxTabWidth(self):
        """
        Returns the minimum and the maximum tab widths for L{AuiNotebook} when the
        ``AUI_NB_TAB_FIXED_WIDTH`` style is defined.

        :note: Minimum and maximum tabs widths are used only when the ``AUI_NB_TAB_FIXED_WIDTH``
         style is present.

        :see: L{SetMinMaxTabWidth} for more information.
        """

        return self._tabBounds

[docs]    def GetPageIndex(self, page_wnd):
        """
        Returns the page index for the specified window. If the window is not
        found in the notebook, ``wx.NOT_FOUND`` is returned.
        """

        return self._tabs.GetIdxFromWindow(page_wnd)

[docs]    def SetPageText(self, page_idx, text):
        """
        Sets the tab label for the page.

        :param `page_idx`: the page index;
        :param `text`: the new tab label.
        """

        if page_idx >= self._tabs.GetPageCount():
            return False

        # update our own tab catalog
        page_info = self._tabs.GetPage(page_idx)
        should_refresh = page_info.caption != text
        page_info.caption = text

        # update what's on screen
        ctrl, ctrl_idx = self.FindTab(page_info.window)
        if not ctrl:
            return False

        info = ctrl.GetPage(ctrl_idx)
        should_refresh = should_refresh or info.caption != text
        info.caption = text

        if should_refresh:
            ctrl.Refresh()
            ctrl.Update()

        self.UpdateTabCtrlHeight(force=True)

        return True

[docs]    def GetPageText(self, page_idx):
        """
        Returns the tab label for the page.

        :param `page_idx`: the page index.
        """

        if page_idx >= self._tabs.GetPageCount():
            return ""

        # update our own tab catalog
        page_info = self._tabs.GetPage(page_idx)
        return page_info.caption

[docs]    def SetPageBitmap(self, page_idx, bitmap):
        """
        Sets the tab bitmap for the page.

        :param `page_idx`: the page index;
        :param `bitmap`: an instance of `wx.Bitmap`.
        """

        if page_idx >= self._tabs.GetPageCount():
            return False

        # update our own tab catalog
        page_info = self._tabs.GetPage(page_idx)
        should_refresh = page_info.bitmap is not bitmap
        page_info.bitmap = bitmap
        if bitmap.IsOk() and not page_info.dis_bitmap.IsOk():
            page_info.dis_bitmap = MakeDisabledBitmap(bitmap)

        # tab height might have changed
        self.UpdateTabCtrlHeight()

        # update what's on screen
        ctrl, ctrl_idx = self.FindTab(page_info.window)
        if not ctrl:
            return False

        info = ctrl.GetPage(ctrl_idx)
        should_refresh = should_refresh or info.bitmap is not bitmap
        info.bitmap = bitmap
        info.dis_bitmap = page_info.dis_bitmap
        if should_refresh:
            ctrl.Refresh()
            ctrl.Update()

        return True

[docs]    def GetPageBitmap(self, page_idx):
        """
        Returns the tab bitmap for the page.

        :param `page_idx`: the page index.
        """

        if page_idx >= self._tabs.GetPageCount():
            return wx.NullBitmap

        # update our own tab catalog
        page_info = self._tabs.GetPage(page_idx)
        return page_info.bitmap

[docs]    def SetImageList(self, imageList):
        """
        Sets the image list for the L{AuiNotebook} control.

        :param `imageList`: an instance of `wx.ImageList`.
        """

        self._imageList = imageList

[docs]    def AssignImageList(self, imageList):
        """
        Sets the image list for the L{AuiNotebook} control.

        :param `imageList`: an instance of `wx.ImageList`.
        """

        self.SetImageList(imageList)

[docs]    def GetImageList(self):
        """ Returns the associated image list (if any). """

        return self._imageList

[docs]    def SetPageImage(self, page, image):
        """
        Sets the image index for the given page.

        :param `page`: the page index;
        :param `image`: an index into the image list which was set with L{SetImageList}.
        """

        if page >= self._tabs.GetPageCount():
            return False

        if not isinstance(image, types.IntType):
            raise Exception("The image parameter must be an integer, you passed " \
                            "%s"%repr(image))

        if not self._imageList:
            raise Exception("To use SetPageImage you need to associate an image list " \
                            "Using SetImageList or AssignImageList")

        if image >= self._imageList.GetImageCount():
            raise Exception("Invalid image index (%d), the image list contains only" \
                            " (%d) bitmaps"%(image, self._imageList.GetImageCount()))

        if image == -1:
            self.SetPageBitmap(page, wx.NullBitmap)
            return

        bitmap = self._imageList.GetBitmap(image)
        self.SetPageBitmap(page, bitmap)

[docs]    def GetPageImage(self, page):
        """
        Returns the image index for the given page.

        :param `page`: the given page for which to retrieve the image index.
        """

        if page >= self._tabs.GetPageCount():
            return wx.NOT_FOUND

        bitmap = self.GetPageBitmap(page)
        bmpData1 = bitmap.ConvertToImage().GetData()

        for indx in xrange(self._imageList.GetImageCount()):
            imgListBmp = self._imageList.GetBitmap(indx)
            bmpData2 = imgListBmp.ConvertToImage().GetData()
            if bmpData1 == bmpData2:
                return indx

        return wx.NOT_FOUND

[docs]    def SetPageTextColour(self, page_idx, colour):
        """
        Sets the tab text colour for the page.

        :param `page_idx`: the page index;
        :param `colour`: an instance of `wx.Colour`.
        """

        if page_idx >= self._tabs.GetPageCount():
            return False

        # update our own tab catalog
        page_info = self._tabs.GetPage(page_idx)
        should_refresh = page_info.text_colour != colour
        page_info.text_colour = colour

        # update what's on screen
        ctrl, ctrl_idx = self.FindTab(page_info.window)
        if not ctrl:
            return False

        info = ctrl.GetPage(ctrl_idx)
        should_refresh = should_refresh or info.text_colour != colour
        info.text_colour = page_info.text_colour

        if should_refresh:
            ctrl.Refresh()
            ctrl.Update()

        return True

[docs]    def GetPageTextColour(self, page_idx):
        """
        Returns the tab text colour for the page.

        :param `page_idx`: the page index.
        """

        if page_idx >= self._tabs.GetPageCount():
            return wx.NullColour

        # update our own tab catalog
        page_info = self._tabs.GetPage(page_idx)
        return page_info.text_colour

[docs]    def AddControlToPage(self, page_idx, control):
        """
        Adds a control inside a tab (not in the tab area).

        :param `page_idx`: the page index;
        :param `control`: an instance of `wx.Window`.
        """

        if page_idx >= self._tabs.GetPageCount():
            return False

        # update our own tab catalog
        page_info = self._tabs.GetPage(page_idx)
        page_info.control = control

        # tab height might have changed
        self.UpdateTabCtrlHeight(force=True)

        # update what's on screen
        ctrl, ctrl_idx = self.FindTab(page_info.window)
        if not ctrl:
            return False

        control.Reparent(ctrl)

        info = ctrl.GetPage(ctrl_idx)
        info.control = control
        ctrl.Refresh()
        ctrl.Update()

        return True

[docs]    def RemoveControlFromPage(self, page_idx):
        """
        Removes a control from a tab (not from the tab area).

        :param `page_idx`: the page index.
        """

        if page_idx >= self._tabs.GetPageCount():
            return False

        page_info = self._tabs.GetPage(page_idx)
        if page_info.control is None:
            return False

        page_info.control.Destroy()
        page_info.control = None

        # tab height might have changed
        self.UpdateTabCtrlHeight(force=True)

        # update what's on screen
        ctrl, ctrl_idx = self.FindTab(page_info.window)
        if not ctrl:
            return False

        info = ctrl.GetPage(ctrl_idx)
        info.control = None
        ctrl.Refresh()
        ctrl.Update()

        return True

[docs]    def SetCloseButton(self, page_idx, hasCloseButton):
        """
        Sets whether a tab should display a close button or not.

        :param `page_idx`: the page index;
        :param `hasCloseButton`: ``True`` if the page displays a close button.

        :note: This can only be called if ``AUI_NB_CLOSE_ON_ALL_TABS`` is specified.
        """

        if page_idx >= self._tabs.GetPageCount():
            return False

        if self._agwFlags & AUI_NB_CLOSE_ON_ALL_TABS == 0:
            raise Exception("SetCloseButton can only be used with AUI_NB_CLOSE_ON_ALL_TABS style.")

        # update our own tab catalog
        page_info = self._tabs.GetPage(page_idx)
        page_info.hasCloseButton = hasCloseButton

        # update what's on screen
        ctrl, ctrl_idx = self.FindTab(page_info.window)
        if not ctrl:
            return False

        info = ctrl.GetPage(ctrl_idx)
        info.hasCloseButton = page_info.hasCloseButton
        ctrl.Refresh()
        ctrl.Update()

        return True

[docs]    def HasCloseButton(self, page_idx):
        """
        Returns whether a tab displays a close button or not.

        :param `page_idx`: the page index.

        :note: This can only be called if ``AUI_NB_CLOSE_ON_ALL_TABS`` is specified.
        """

        if page_idx >= self._tabs.GetPageCount():
            return False

        page_info = self._tabs.GetPage(page_idx)
        return page_info.hasCloseButton

[docs]    def GetSelection(self):
        """ Returns the index of the currently active page, or -1 if none was selected. """

        return self._curpage

[docs]    def GetCurrentPage(self):
        """ Returns the currently active page (not the index), or ``None`` if none was selected. """

        if self._curpage >= 0 and self._curpage < self._tabs.GetPageCount():
            return self.GetPage(self._curpage)

        return None

[docs]    def EnsureVisible(self, indx):
        """
        Ensures the input page index `indx` is visible.

        :param `indx`: the page index.
        """

        self._tabs.MakeTabVisible(indx, self)

[docs]    def SetSelection(self, new_page, force=False):
        """
        Sets the page selection. Calling this method will generate a page change event.

        :param `new_page`: the index of the new selection;
        :param `force`: whether to force the selection or not.
        """
        wnd = self._tabs.GetWindowFromIdx(new_page)

        #Update page access time
        self._tabs.GetPages()[new_page].access_time = datetime.datetime.now()

        if not wnd or not self.GetEnabled(new_page):
            return self._curpage

        # don't change the page unless necessary
        # however, clicking again on a tab should give it the focus.
        if new_page == self._curpage and not force:

            ctrl, ctrl_idx = self.FindTab(wnd)
            if wx.Window.FindFocus() != ctrl:
                ctrl.SetFocus()

            return self._curpage

        evt = AuiNotebookEvent(wxEVT_COMMAND_AUINOTEBOOK_PAGE_CHANGING, self.GetId())
        evt.SetSelection(new_page)
        evt.SetOldSelection(self._curpage)
        evt.SetEventObject(self)

        if not self.GetEventHandler().ProcessEvent(evt) or evt.IsAllowed():

            old_curpage = self._curpage
            self._curpage = new_page

            # program allows the page change
            evt.SetEventType(wxEVT_COMMAND_AUINOTEBOOK_PAGE_CHANGED)
            self.GetEventHandler().ProcessEvent(evt)

            if not evt.IsAllowed(): # event is no longer allowed after handler
                return self._curpage

            ctrl, ctrl_idx = self.FindTab(wnd)

            if ctrl:
                self._tabs.SetActivePage(wnd)
                ctrl.SetActivePage(ctrl_idx)
                self.DoSizing()
                ctrl.DoShowHide()
                ctrl.MakeTabVisible(ctrl_idx, ctrl)

                # set fonts
                all_panes = self._mgr.GetAllPanes()
                for pane in all_panes:
                    if pane.name == "dummy":
                        continue

                    tabctrl = pane.window._tabs
                    if tabctrl != ctrl:
                        tabctrl.SetSelectedFont(self._normal_font)
                    else:
                        tabctrl.SetSelectedFont(self._selected_font)

                    tabctrl.Refresh()
                    tabctrl.Update()

                # Set the focus to the page if we're not currently focused on the tab.
                # This is Firefox-like behaviour.
                if wnd.IsShownOnScreen() and wx.Window.FindFocus() != ctrl:
                    wnd.SetFocus()

                return old_curpage

        return self._curpage

[docs]    def SetSelectionToWindow(self, win):
        """
        Sets the selection based on the input window `win`.

        :param `win`: a `wx.Window` derived window.
        """

        idx = self._tabs.GetIdxFromWindow(win)

        if idx == wx.NOT_FOUND:
            raise Exception("invalid notebook page")

        if not self.GetEnabled(idx):
            return

        # since a tab was clicked, let the parent know that we received
        # the focus, even if we will assign that focus immediately
        # to the child tab in the SetSelection call below
        # (the child focus event will also let AuiManager, if any,
        # know that the notebook control has been activated)

        parent = self.GetParent()
        if parent:
            eventFocus = wx.ChildFocusEvent(self)
            parent.GetEventHandler().ProcessEvent(eventFocus)

        self.SetSelection(idx)

[docs]    def SetSelectionToPage(self, page):
        """
        Sets the selection based on the input page.

        :param `page`: an instance of L{AuiNotebookPage}.
        """

        self.SetSelectionToWindow(page.window)

[docs]    def GetPageCount(self):
        """ Returns the number of pages in the notebook. """

        return self._tabs.GetPageCount()

[docs]    def GetPage(self, page_idx):
        """
        Returns the page specified by the given index.

        :param `page_idx`: the page index.
        """

        if page_idx >= self._tabs.GetPageCount():
            raise Exception("invalid notebook page")

        return self._tabs.GetWindowFromIdx(page_idx)

[docs]    def GetPageInfo(self, page_idx):
        """
        Returns the L{AuiNotebookPage} info structure specified by the given index.

        :param `page_idx`: the page index.
        """

        if page_idx >= self._tabs.GetPageCount():
            raise Exception("invalid notebook page")

        return self._tabs.GetPage(page_idx)

[docs]    def GetEnabled(self, page_idx):
        """
        Returns whether the page specified by the index `page_idx` is enabled.

        :param `page_idx`: the page index.
        """

        return self._tabs.GetEnabled(page_idx)

[docs]    def EnableTab(self, page_idx, enable=True):
        """
        Enables/disables a page in the notebook.

        :param `page_idx`: the page index;
        :param `enable`: ``True`` to enable the page, ``False`` to disable it.
        """

        self._tabs.EnableTab(page_idx, enable)
        self.Refresh()

[docs]    def DoSizing(self):
        """ Performs all sizing operations in each tab control. """

        all_panes = self._mgr.GetAllPanes()
        for pane in all_panes:
            if pane.name == "dummy":
                continue

            tabframe = pane.window
            tabframe.DoSizing()

[docs]    def GetAuiManager(self):
        """ Returns the associated L{AuiManager}. """

        return self._mgr

[docs]    def GetActiveTabCtrl(self):
        """
        Returns the active tab control. It is called to determine which control
        gets new windows being added.
        """

        if self._curpage >= 0 and self._curpage < self._tabs.GetPageCount():

            # find the tab ctrl with the current page
            ctrl, idx = self.FindTab(self._tabs.GetPage(self._curpage).window)
            if ctrl:
                return ctrl

        # no current page, just find the first tab ctrl
        all_panes = self._mgr.GetAllPanes()
        for pane in all_panes:
            if pane.name == "dummy":
                continue

            tabframe = pane.window
            return tabframe._tabs

        # If there is no tabframe at all, create one
        tabframe = TabFrame(self)
        tabframe.SetTabCtrlHeight(self._tab_ctrl_height)
        self._tab_id_counter += 1
        tabframe._tabs = AuiTabCtrl(self, self._tab_id_counter)

        tabframe._tabs.SetAGWFlags(self._agwFlags)
        tabframe._tabs.SetArtProvider(self._tabs.GetArtProvider().Clone())
        self._mgr.AddPane(tabframe, framemanager.AuiPaneInfo().Center().CaptionVisible(False).
                          PaneBorder((self._agwFlags & AUI_NB_SUB_NOTEBOOK) == 0))

        self._mgr.Update()

        return tabframe._tabs

[docs]    def FindTab(self, page):
        """
        Finds the tab control that currently contains the window as well
        as the index of the window in the tab control. It returns ``True`` if the
        window was found, otherwise ``False``.

        :param `page`: an instance of L{AuiNotebookPage}.
        """

        all_panes = self._mgr.GetAllPanes()
        for pane in all_panes:
            if pane.name == "dummy":
                continue

            tabframe = pane.window

            page_idx = tabframe._tabs.GetIdxFromWindow(page)

            if page_idx != -1:

                ctrl = tabframe._tabs
                idx = page_idx
                return ctrl, idx

        return None, wx.NOT_FOUND

[docs]    def Split(self, page, direction):
        """
        Performs a split operation programmatically.

        :param `page`: indicates the page that will be split off. This page will also become
         the active page after the split.
        :param `direction`: specifies where the pane should go, it should be one of the
         following: ``wx.TOP``, ``wx.BOTTOM``, ``wx.LEFT``, or ``wx.RIGHT``.
        """

        cli_size = self.GetClientSize()

        # get the page's window pointer
        wnd = self.GetPage(page)
        if not wnd:
            return

        # notebooks with 1 or less pages can't be split
        if self.GetPageCount() < 2:
            return

        # find out which tab control the page currently belongs to

        src_tabs, src_idx = self.FindTab(wnd)
        if not src_tabs:
            return

        # choose a split size
        if self.GetPageCount() > 2:
            split_size = self.CalculateNewSplitSize()
        else:
            # because there are two panes, always split them
            # equally
            split_size = self.GetClientSize()
            split_size.x /= 2
            split_size.y /= 2

        # create a new tab frame
        new_tabs = TabFrame(self)
        new_tabs._rect = wx.RectPS(wx.Point(0, 0), split_size)
        new_tabs.SetTabCtrlHeight(self._tab_ctrl_height)
        self._tab_id_counter += 1
        new_tabs._tabs = AuiTabCtrl(self, self._tab_id_counter)

        new_tabs._tabs.SetArtProvider(self._tabs.GetArtProvider().Clone())
        new_tabs._tabs.SetAGWFlags(self._agwFlags)
        dest_tabs = new_tabs._tabs

        page_info = src_tabs.GetPage(src_idx)
        if page_info.control:
            self.ReparentControl(page_info.control, dest_tabs)

        cloned_buttons = self.CloneTabAreaButtons()
        for clone in cloned_buttons:
            dest_tabs.AddButton(clone.id, clone.location, clone.bitmap, clone.dis_bitmap)
        # create a pane info structure with the information
        # about where the pane should be added
        pane_info = framemanager.AuiPaneInfo().Bottom().CaptionVisible(False)

        if direction == wx.LEFT:

            pane_info.Left()
            mouse_pt = wx.Point(0, cli_size.y/2)

        elif direction == wx.RIGHT:

            pane_info.Right()
            mouse_pt = wx.Point(cli_size.x, cli_size.y/2)

        elif direction == wx.TOP:

            pane_info.Top()
            mouse_pt = wx.Point(cli_size.x/2, 0)

        elif direction == wx.BOTTOM:

            pane_info.Bottom()
            mouse_pt = wx.Point(cli_size.x/2, cli_size.y)

        self._mgr.AddPane(new_tabs, pane_info, mouse_pt)
        self._mgr.Update()

        # remove the page from the source tabs
        page_info.active = False

        src_tabs.RemovePage(page_info.window)

        if src_tabs.GetPageCount() > 0:
            src_tabs.SetActivePage(0)
            src_tabs.DoShowHide()
            src_tabs.Refresh()

        # add the page to the destination tabs
        dest_tabs.InsertPage(page_info.window, page_info, 0)

        if src_tabs.GetPageCount() == 0:
            self.RemoveEmptyTabFrames()

        self.DoSizing()
        dest_tabs.DoShowHide()
        dest_tabs.Refresh()

        # force the set selection function reset the selection
        self._curpage = -1

        # set the active page to the one we just split off
        self.SetSelectionToPage(page_info)

        self.UpdateHintWindowSize()

[docs]    def UnSplit(self):
        """ Restores original view after a tab split. """

        self.Freeze()

        # remember the tab now selected
        nowSelected = self.GetSelection()
        # select first tab as destination
        self.SetSelection(0)
        # iterate all other tabs
        for idx in xrange(1, self.GetPageCount()):
            # get win reference
            win = self.GetPage(idx)
            # get tab title
            title = self.GetPageText(idx)
            # get page bitmap
            bmp = self.GetPageBitmap(idx)
            # remove from notebook
            self.RemovePage(idx)
            # re-add in the same position so it will tab
            self.InsertPage(idx, win, title, False, bmp)
        # restore orignial selected tab
        self.SetSelection(nowSelected)

        self.Thaw()

[docs]    def ReparentControl(self, control, dest_tabs):
        """
        Reparents a control added inside a tab.

        :param `control`: an instance of `wx.Window`;
        :param `dest_tabs`: the destination L{AuiTabCtrl}.
        """

        control.Hide()
        control.Reparent(dest_tabs)

[docs]    def UnsplitDClick(self, part, sash_size, pos):
        """
        Unsplit the L{AuiNotebook} on sash double-click.

        :param `part`: an UI part representing the sash;
        :param `sash_size`: the sash size;
        :param `pos`: the double-click mouse position.

        :warning: Due to a bug on MSW, for disabled pages `wx.FindWindowAtPoint`
         returns the wrong window. See http://trac.wxwidgets.org/ticket/2942
        """

        if not self._sash_dclick_unsplit:
            # Unsplit not allowed
            return

        pos1 = wx.Point(*pos)
        pos2 = wx.Point(*pos)
        if part.orientation == wx.HORIZONTAL:
            pos1.y -= 2*sash_size
            pos2.y += 2*sash_size + self.GetTabCtrlHeight()
        elif part.orientation == wx.VERTICAL:
            pos1.x -= 2*sash_size
            pos2.x += 2*sash_size
        else:
            raise Exception("Invalid UI part orientation")

        pos1, pos2 = self.ClientToScreen(pos1), self.ClientToScreen(pos2)
        win1, win2 = wx.FindWindowAtPoint(pos1), wx.FindWindowAtPoint(pos2)

        if isinstance(win1, wx.ScrollBar):
            # Hopefully it will work
            pos1 = wx.Point(*pos)
            shift = wx.SystemSettings.GetMetric(wx.SYS_VSCROLL_X) + 2*(sash_size+1)
            if part.orientation == wx.HORIZONTAL:
                pos1.y -= shift
            else:
                pos1.x -= shift

            pos1 = self.ClientToScreen(pos1)
            win1 = wx.FindWindowAtPoint(pos1)

        if isinstance(win2, wx.ScrollBar):
            pos2 = wx.Point(*pos)
            shift = wx.SystemSettings.GetMetric(wx.SYS_VSCROLL_X) + 2*(sash_size+1)
            if part.orientation == wx.HORIZONTAL:
                pos2.y += shift
            else:
                pos2.x += shift

            pos2 = self.ClientToScreen(pos2)
            win2 = wx.FindWindowAtPoint(pos2)

        if not win1 or not win2:
            # How did we get here?
            return

        if isinstance(win1, AuiNotebook) or isinstance(win2, AuiNotebook):
            # This is a bug on MSW, for disabled pages wx.FindWindowAtPoint
            # returns the wrong window.
            # See http://trac.wxwidgets.org/ticket/2942
            return

        tab_frame1, tab_frame2 = self.GetTabFrameFromWindow(win1), self.GetTabFrameFromWindow(win2)

        if not tab_frame1 or not tab_frame2:
            return

        tab_ctrl_1, tab_ctrl_2 = tab_frame1._tabs, tab_frame2._tabs

        if tab_ctrl_1.GetPageCount() > tab_ctrl_2.GetPageCount():
            src_tabs = tab_ctrl_2
            dest_tabs = tab_ctrl_1
        else:
            src_tabs = tab_ctrl_1
            dest_tabs = tab_ctrl_2

        selection = -1
        page_count = dest_tabs.GetPageCount()

        for page in xrange(src_tabs.GetPageCount()-1, -1, -1):
            # remove the page from the source tabs
            page_info = src_tabs.GetPage(page)
            if page_info.active:
                selection = page_count + page
            src_tabs.RemovePage(page_info.window)

            # add the page to the destination tabs
            dest_tabs.AddPage(page_info.window, page_info)
            if page_info.control:
                self.ReparentControl(page_info.control, dest_tabs)

        self.RemoveEmptyTabFrames()

        dest_tabs.DoShowHide()
        self.DoSizing()
        dest_tabs.Refresh()
        self._mgr.Update()
        if selection > 0:
            wx.CallAfter(dest_tabs.MakeTabVisible, selection, self)

[docs]    def OnSize(self, event):
        """
        Handles the ``wx.EVT_SIZE`` event for L{AuiNotebook}.

        :param `event`: a `wx.SizeEvent` event to be processed.
        """

        self.UpdateHintWindowSize()
        event.Skip()

[docs]    def OnTabClicked(self, event):
        """
        Handles the ``EVT_AUINOTEBOOK_PAGE_CHANGING`` event for L{AuiNotebook}.

        :param `event`: a L{AuiNotebookEvent} event to be processed.
        """

        if self._textCtrl is not None:
            self._textCtrl.StopEditing()

        ctrl = event.GetEventObject()
        assert ctrl != None

        wnd = ctrl.GetWindowFromIdx(event.GetSelection())
        assert wnd != None

        self.SetSelectionToWindow(wnd)

[docs]    def OnTabBgDClick(self, event):
        """
        Handles the ``EVT_AUINOTEBOOK_BG_DCLICK`` event for L{AuiNotebook}.

        :param `event`: a L{AuiNotebookEvent} event to be processed.
        """

        if self._textCtrl is not None:
            self._textCtrl.StopEditing()

        # notify owner that the tabbar background has been double-clicked
        e = AuiNotebookEvent(wxEVT_COMMAND_AUINOTEBOOK_BG_DCLICK, self.GetId())
        e.SetEventObject(self)
        self.GetEventHandler().ProcessEvent(e)

[docs]    def OnTabDClick(self, event):
        """
        Handles the ``EVT_AUINOTEBOOK_TAB_DCLICK`` event for L{AuiNotebook}.

        :param `event`: a L{AuiNotebookEvent} event to be processed.
        """

        # notify owner that the tabbar background has been double-clicked
        e = AuiNotebookEvent(wxEVT_COMMAND_AUINOTEBOOK_TAB_DCLICK, self.GetId())
        e.SetEventObject(self)
        self.GetEventHandler().ProcessEvent(e)

        tabs = event.GetEventObject()
        if not tabs.GetEnabled(event.GetSelection()):
            return

        if not self.IsRenamable(event.GetSelection()):
            return

        self.EditTab(event.GetSelection())

[docs]    def OnTabBeginDrag(self, event):
        """
        Handles the ``EVT_AUINOTEBOOK_BEGIN_DRAG`` event for L{AuiNotebook}.

        :param `event`: a L{AuiNotebookEvent} event to be processed.
        """

        tabs = event.GetEventObject()
        if not tabs.GetEnabled(event.GetSelection()):
            return

        self._last_drag_x = 0

[docs]    def OnTabDragMotion(self, event):
        """
        Handles the ``EVT_AUINOTEBOOK_DRAG_MOTION`` event for L{AuiNotebook}.

        :param `event`: a L{AuiNotebookEvent} event to be processed.
        """

        self._curpage = event.GetSelection()

        tabs = event.GetEventObject()
        if not tabs.GetEnabled(event.GetSelection()):
            return

        if self._textCtrl is not None:
            self._textCtrl.StopEditing()

        screen_pt = wx.GetMousePosition()
        client_pt = self.ScreenToClient(screen_pt)
        zero = wx.Point(0, 0)

        src_tabs = event.GetEventObject()
        dest_tabs = self.GetTabCtrlFromPoint(client_pt)

        if dest_tabs == src_tabs:

            # always hide the hint for inner-tabctrl drag
            self._mgr.HideHint()

            # if tab moving is not allowed, leave
            if not self._agwFlags & AUI_NB_TAB_MOVE:
                return

            pt = dest_tabs.ScreenToClient(screen_pt)

            # this is an inner-tab drag/reposition
            dest_location_tab = dest_tabs.TabHitTest(pt.x, pt.y)

            if dest_location_tab:

                src_idx = event.GetSelection()
                dest_idx = dest_tabs.GetIdxFromWindow(dest_location_tab)

                # prevent jumpy drag
                if (src_idx == dest_idx) or dest_idx == -1 or \
                   (src_idx > dest_idx and self._last_drag_x <= pt.x) or \
                   (src_idx < dest_idx and self._last_drag_x >= pt.x):

                    self._last_drag_x = pt.x
                    return

                src_tab = dest_tabs.GetWindowFromIdx(src_idx)
                dest_tabs.MovePage(src_tab, dest_idx)
                self._tabs.MovePage(self._tabs.GetPage(src_idx).window, dest_idx)
                dest_tabs.SetActivePage(dest_idx)
                dest_tabs.DoShowHide()
                dest_tabs.Refresh()
                self._last_drag_x = pt.x

            return

        # if external drag is allowed, check if the tab is being dragged
        # over a different AuiNotebook control
        if self._agwFlags & AUI_NB_TAB_EXTERNAL_MOVE:

            tab_ctrl = wx.FindWindowAtPoint(screen_pt)

            # if we aren't over any window, stop here
            if not tab_ctrl:
                if self._agwFlags & AUI_NB_TAB_FLOAT:
                    if self.IsMouseWellOutsideWindow():
                        hintRect = wx.RectPS(screen_pt, (400, 300))
                        # Use CallAfter so we overwrite the hint that might be
                        # shown by our superclass:
                        wx.CallAfter(self._mgr.ShowHint, hintRect)
                return

            # make sure we are not over the hint window
            if not isinstance(tab_ctrl, wx.Frame):
                while tab_ctrl:
                    if isinstance(tab_ctrl, AuiTabCtrl):
                        break

                    tab_ctrl = tab_ctrl.GetParent()

                if tab_ctrl:
                    nb = tab_ctrl.GetParent()

                    if nb != self:

                        hint_rect = tab_ctrl.GetClientRect()
                        hint_rect.x, hint_rect.y = tab_ctrl.ClientToScreenXY(hint_rect.x, hint_rect.y)
                        self._mgr.ShowHint(hint_rect)
                        return

            else:

                if not dest_tabs:
                    # we are either over a hint window, or not over a tab
                    # window, and there is no where to drag to, so exit
                    return

        if self._agwFlags & AUI_NB_TAB_FLOAT:
            if self.IsMouseWellOutsideWindow():
                hintRect = wx.RectPS(screen_pt, (400, 300))
                # Use CallAfter so we overwrite the hint that might be
                # shown by our superclass:
                wx.CallAfter(self._mgr.ShowHint, hintRect)
                return

        # if there are less than two panes, split can't happen, so leave
        if self._tabs.GetPageCount() < 2:
            return

        # if tab moving is not allowed, leave
        if not self._agwFlags & AUI_NB_TAB_SPLIT:
            return

        if dest_tabs:

            hint_rect = dest_tabs.GetRect()
            hint_rect.x, hint_rect.y = self.ClientToScreenXY(hint_rect.x, hint_rect.y)
            self._mgr.ShowHint(hint_rect)

        else:
            rect = self._mgr.CalculateHintRect(self._dummy_wnd, client_pt, zero)
            if rect.IsEmpty():
                self._mgr.HideHint()
                return

            hit_wnd = wx.FindWindowAtPoint(screen_pt)
            if hit_wnd and not isinstance(hit_wnd, AuiNotebook):
                tab_frame = self.GetTabFrameFromWindow(hit_wnd)
                if tab_frame:
                    hint_rect = wx.Rect(*tab_frame._rect)
                    hint_rect.x, hint_rect.y = self.ClientToScreenXY(hint_rect.x, hint_rect.y)
                    rect.Intersect(hint_rect)
                    self._mgr.ShowHint(rect)
                else:
                    self._mgr.DrawHintRect(self._dummy_wnd, client_pt, zero)
            else:
                self._mgr.DrawHintRect(self._dummy_wnd, client_pt, zero)

[docs]    def OnTabEndDrag(self, event):
        """
        Handles the ``EVT_AUINOTEBOOK_END_DRAG`` event for L{AuiNotebook}.

        :param `event`: a L{AuiNotebookEvent} event to be processed.
        """

        tabs = event.GetEventObject()
        if not tabs.GetEnabled(event.GetSelection()):
            return

        self._mgr.HideHint()

        src_tabs = event.GetEventObject()
        if not src_tabs:
            raise Exception("no source object?")

        # get the mouse position, which will be used to determine the drop point
        mouse_screen_pt = wx.GetMousePosition()
        mouse_client_pt = self.ScreenToClient(mouse_screen_pt)

        # check for an external move
        if self._agwFlags & AUI_NB_TAB_EXTERNAL_MOVE:
            tab_ctrl = wx.FindWindowAtPoint(mouse_screen_pt)

            while tab_ctrl:

                if isinstance(tab_ctrl, AuiTabCtrl):
                    break

                tab_ctrl = tab_ctrl.GetParent()

            if tab_ctrl:

                nb = tab_ctrl.GetParent()

                if nb != self:

                    # find out from the destination control
                    # if it's ok to drop this tab here
                    e = AuiNotebookEvent(wxEVT_COMMAND_AUINOTEBOOK_ALLOW_DND, self.GetId())
                    e.SetSelection(event.GetSelection())
                    e.SetOldSelection(event.GetSelection())
                    e.SetEventObject(self)
                    e.SetDragSource(self)
                    e.Veto() # dropping must be explicitly approved by control owner

                    nb.GetEventHandler().ProcessEvent(e)

                    if not e.IsAllowed():

                        # no answer or negative answer
                        self._mgr.HideHint()
                        return

                    # drop was allowed
                    src_idx = event.GetSelection()
                    src_page = src_tabs.GetWindowFromIdx(src_idx)

                    # Check that it's not an impossible parent relationship
                    p = nb
                    while p and not p.IsTopLevel():
                        if p == src_page:
                            return

                        p = p.GetParent()

                    # get main index of the page
                    main_idx = self._tabs.GetIdxFromWindow(src_page)
                    if main_idx == wx.NOT_FOUND:
                        raise Exception("no source page?")

                    # make a copy of the page info
                    page_info = self._tabs.GetPage(main_idx)

                    # remove the page from the source notebook
                    self.RemovePage(main_idx)

                    # reparent the page
                    src_page.Reparent(nb)

                    # Reparent the control in a tab (if any)
                    if page_info.control:
                        self.ReparentControl(page_info.control, tab_ctrl)

                    # find out the insert idx
                    dest_tabs = tab_ctrl
                    pt = dest_tabs.ScreenToClient(mouse_screen_pt)

                    target = dest_tabs.TabHitTest(pt.x, pt.y)
                    insert_idx = -1
                    if target:
                        insert_idx = dest_tabs.GetIdxFromWindow(target)

                    # add the page to the new notebook
                    if insert_idx == -1:
                        insert_idx = dest_tabs.GetPageCount()

                    dest_tabs.InsertPage(page_info.window, page_info, insert_idx)
                    nb._tabs.AddPage(page_info.window, page_info)

                    nb.DoSizing()
                    dest_tabs.DoShowHide()
                    dest_tabs.Refresh()

                    # set the selection in the destination tab control
                    nb.SetSelectionToPage(page_info)

                    # notify owner that the tab has been dragged
                    e2 = AuiNotebookEvent(wxEVT_COMMAND_AUINOTEBOOK_DRAG_DONE, self.GetId())
                    e2.SetSelection(event.GetSelection())
                    e2.SetOldSelection(event.GetSelection())
                    e2.SetEventObject(self)
                    self.GetEventHandler().ProcessEvent(e2)

                    # notify the target notebook that the tab has been dragged
                    e3 = AuiNotebookEvent(wxEVT_COMMAND_AUINOTEBOOK_DRAG_DONE, nb.GetId())
                    e3.SetSelection(insert_idx)
                    e3.SetOldSelection(insert_idx)
                    e3.SetEventObject(nb)
                    nb.GetEventHandler().ProcessEvent(e3)

                    return

        if self._agwFlags & AUI_NB_TAB_FLOAT:
            self._mgr.HideHint()
            if self.IsMouseWellOutsideWindow():
                # Use CallAfter so we our superclass can deal with the event first
                wx.CallAfter(self.FloatPage, self.GetSelection())
                event.Skip()
                return

        # only perform a tab split if it's allowed
        dest_tabs = None

        if self._agwFlags & AUI_NB_TAB_SPLIT and self._tabs.GetPageCount() >= 2:

            # If the pointer is in an existing tab frame, do a tab insert
            hit_wnd = wx.FindWindowAtPoint(mouse_screen_pt)
            tab_frame = self.GetTabFrameFromTabCtrl(hit_wnd)
            insert_idx = -1

            if tab_frame:

                dest_tabs = tab_frame._tabs

                if dest_tabs == src_tabs:
                    return

                pt = dest_tabs.ScreenToClient(mouse_screen_pt)
                target = dest_tabs.TabHitTest(pt.x, pt.y)

                if target:
                    insert_idx = dest_tabs.GetIdxFromWindow(target)

            else:

                zero = wx.Point(0, 0)
                rect = self._mgr.CalculateHintRect(self._dummy_wnd, mouse_client_pt, zero)

                if rect.IsEmpty():
                    # there is no suitable drop location here, exit out
                    return

                # If there is no tabframe at all, create one
                new_tabs = TabFrame(self)
                new_tabs._rect = wx.RectPS(wx.Point(0, 0), self.CalculateNewSplitSize())
                new_tabs.SetTabCtrlHeight(self._tab_ctrl_height)
                self._tab_id_counter += 1
                new_tabs._tabs = AuiTabCtrl(self, self._tab_id_counter)
                new_tabs._tabs.SetArtProvider(self._tabs.GetArtProvider().Clone())
                new_tabs._tabs.SetAGWFlags(self._agwFlags)

                self._mgr.AddPane(new_tabs, framemanager.AuiPaneInfo().Bottom().CaptionVisible(False), mouse_client_pt)
                self._mgr.Update()
                dest_tabs = new_tabs._tabs

                cloned_buttons = self.CloneTabAreaButtons()
                for clone in cloned_buttons:
                    dest_tabs.AddButton(clone.id, clone.location, clone.bitmap, clone.dis_bitmap)
            # remove the page from the source tabs
            page_info = src_tabs.GetPage(event.GetSelection())

            if page_info.control:
                self.ReparentControl(page_info.control, dest_tabs)

            page_info.active = False
            src_tabs.RemovePage(page_info.window)

            if src_tabs.GetPageCount() > 0:
                src_tabs.SetActivePage(0)
                src_tabs.DoShowHide()
                src_tabs.Refresh()

            # add the page to the destination tabs
            if insert_idx == -1:
                insert_idx = dest_tabs.GetPageCount()

            dest_tabs.InsertPage(page_info.window, page_info, insert_idx)

            if src_tabs.GetPageCount() == 0:
                self.RemoveEmptyTabFrames()

            self.DoSizing()
            dest_tabs.DoShowHide()
            dest_tabs.Refresh()

            # force the set selection function reset the selection
            self._curpage = -1

            # set the active page to the one we just split off
            self.SetSelectionToPage(page_info)

            self.UpdateHintWindowSize()

        # notify owner that the tab has been dragged
        e = AuiNotebookEvent(wxEVT_COMMAND_AUINOTEBOOK_DRAG_DONE, self.GetId())
        e.SetSelection(event.GetSelection())
        e.SetOldSelection(event.GetSelection())
        e.SetEventObject(self)
        self.GetEventHandler().ProcessEvent(e)

[docs]    def OnTabCancelDrag(self, event):
        """
        Handles the ``EVT_AUINOTEBOOK_CANCEL_DRAG`` event for L{AuiNotebook}.

        :param `event`: a L{AuiNotebookEvent} event to be processed.
        """

        tabs = event.GetEventObject()
        if not tabs.GetEnabled(event.GetSelection()):
            return

        self._mgr.HideHint()

        src_tabs = event.GetEventObject()
        if not src_tabs:
            raise Exception("no source object?")

[docs]    def IsMouseWellOutsideWindow(self):
        """ Returns whether the mouse is well outside the L{AuiNotebook} screen rectangle. """

        screen_rect = self.GetScreenRect()
        screen_rect.Inflate(50, 50)

        return not screen_rect.Contains(wx.GetMousePosition())

[docs]    def FloatPage(self, page_index):
        """
        Float the page in `page_index` by reparenting it to a floating frame.

        :param `page_index`: the index of the page to be floated.

        :warning: When the notebook is more or less full screen, tabs cannot be dragged far
         enough outside of the notebook to become floating pages.
        """

        root_manager = framemanager.GetManager(self)
        page_title = self.GetPageText(page_index)
        page_contents = self.GetPage(page_index)
        page_bitmap = self.GetPageBitmap(page_index)
        text_colour = self.GetPageTextColour(page_index)
        info = self.GetPageInfo(page_index)

        if root_manager and root_manager != self._mgr:
            root_manager = framemanager.GetManager(self)

            if hasattr(page_contents, "__floating_size__"):
                floating_size = wx.Size(*page_contents.__floating_size__)
            else:
                floating_size = page_contents.GetBestSize()
                if floating_size == wx.DefaultSize:
                    floating_size = wx.Size(300, 200)

            page_contents.__page_index__ = page_index
            page_contents.__aui_notebook__ = self
            page_contents.__text_colour__ = text_colour
            page_contents.__control__ = info.control

            if info.control:
                info.control.Reparent(page_contents)
                info.control.Hide()
                info.control = None

            self.RemovePage(page_index)
            self.RemoveEmptyTabFrames()

            pane_info = framemanager.AuiPaneInfo().Float().FloatingPosition(wx.GetMousePosition()). \
                        FloatingSize(floating_size).BestSize(floating_size).Name("__floating__%s"%page_title). \
                        Caption(page_title).Icon(page_bitmap)
            root_manager.AddPane(page_contents, pane_info)
            root_manager.Bind(framemanager.EVT_AUI_PANE_CLOSE, self.OnCloseFloatingPage)
            self.GetActiveTabCtrl().DoShowHide()
            self.DoSizing()
            root_manager.Update()

        else:
            frame = wx.Frame(self, title=page_title,
                             style=wx.DEFAULT_FRAME_STYLE|wx.FRAME_TOOL_WINDOW|
                                   wx.FRAME_FLOAT_ON_PARENT | wx.FRAME_NO_TASKBAR)

            if info.control:
                info.control.Reparent(frame)
                info.control.Hide()

            frame.bitmap = page_bitmap
            frame.page_index = page_index
            frame.text_colour = text_colour
            frame.control = info.control
            page_contents.Reparent(frame)
            frame.Bind(wx.EVT_CLOSE, self.OnCloseFloatingPage)
            frame.Move(wx.GetMousePosition())
            frame.Show()
            self.RemovePage(page_index)

            self.RemoveEmptyTabFrames()

        wx.CallAfter(self.RemoveEmptyTabFrames)

[docs]    def OnCloseFloatingPage(self, event):
        """
        Handles the ``wx.EVT_CLOSE`` event for a floating page in L{AuiNotebook}.

        :param `event`: a `wx.CloseEvent` event to be processed.
        """

        root_manager = framemanager.GetManager(self)
        if root_manager and root_manager != self._mgr:
            pane = event.pane
            if pane.name.startswith("__floating__"):
                self.ReDockPage(pane)
                return

            event.Skip()
        else:
            event.Skip()
            frame = event.GetEventObject()
            page_title = frame.GetTitle()
            page_contents = list(frame.GetChildren())[-1]
            page_contents.Reparent(self)
            self.InsertPage(frame.page_index, page_contents, page_title, select=True, bitmap=frame.bitmap, control=frame.control)

            if frame.control:
                src_tabs, idx = self.FindTab(page_contents)
                frame.control.Reparent(src_tabs)
                frame.control.Hide()
                frame.control = None

            self.SetPageTextColour(frame.page_index, frame.text_colour)

[docs]    def ReDockPage(self, pane):
        """
        Re-docks a floating L{AuiNotebook} tab in the original position, when possible.

        :param `pane`: an instance of L{framemanager.AuiPaneInfo}.
        """

        root_manager = framemanager.GetManager(self)

        pane.window.__floating_size__ = wx.Size(*pane.floating_size)
        page_index = pane.window.__page_index__
        text_colour = pane.window.__text_colour__
        control = pane.window.__control__

        root_manager.DetachPane(pane.window)
        self.InsertPage(page_index, pane.window, pane.caption, True, pane.icon, control=control)

        self.SetPageTextColour(page_index, text_colour)
        self.GetActiveTabCtrl().DoShowHide()
        self.DoSizing()
        if control:
            self.UpdateTabCtrlHeight(force=True)

        self._mgr.Update()
        root_manager.Update()

[docs]    def GetTabCtrlFromPoint(self, pt):
        """
        Returns the tab control at the specified point.

        :param `pt`: a `wx.Point` object.
        """

        # if we've just removed the last tab from the source
        # tab set, the remove the tab control completely
        all_panes = self._mgr.GetAllPanes()
        for pane in all_panes:
            if pane.name == "dummy":
                continue

            tabframe = pane.window
            if tabframe._tab_rect.Contains(pt):
                return tabframe._tabs

        return None

[docs]    def GetTabFrameFromTabCtrl(self, tab_ctrl):
        """
        Returns the tab frame associated with a tab control.

        :param `tab_ctrl`: an instance of L{AuiTabCtrl}.
        """

        # if we've just removed the last tab from the source
        # tab set, the remove the tab control completely
        all_panes = self._mgr.GetAllPanes()
        for pane in all_panes:
            if pane.name == "dummy":
                continue

            tabframe = pane.window
            if tabframe._tabs == tab_ctrl:
                return tabframe

        return None

[docs]    def GetTabFrameFromWindow(self, wnd):
        """
        Returns the tab frame associated with a window.

        :param `wnd`: an instance of `wx.Window`.
        """

        all_panes = self._mgr.GetAllPanes()
        for pane in all_panes:
            if pane.name == "dummy":
                continue

            tabframe = pane.window
            for page in tabframe._tabs.GetPages():
                if wnd == page.window:
                    return tabframe

        return None

[docs]    def RemoveEmptyTabFrames(self):
        """ Removes all the empty tab frames. """

        # if we've just removed the last tab from the source
        # tab set, the remove the tab control completely
        all_panes = self._mgr.GetAllPanes()

        for indx in xrange(len(all_panes)-1, -1, -1):
            pane = all_panes[indx]
            if pane.name == "dummy":
                continue

            tab_frame = pane.window
            if tab_frame._tabs.GetPageCount() == 0:
                self._mgr.DetachPane(tab_frame)
                tab_frame._tabs.Destroy()
                tab_frame._tabs = None
                del tab_frame

        # check to see if there is still a center pane
        # if there isn't, make a frame the center pane
        first_good = None
        center_found = False

        all_panes = self._mgr.GetAllPanes()
        for pane in all_panes:
            if pane.name == "dummy":
                continue

            if pane.dock_direction == AUI_DOCK_CENTRE:
                center_found = True
            if not first_good:
                first_good = pane.window

        if not center_found and first_good:
            self._mgr.GetPane(first_good).Centre()

        if not self.IsBeingDeleted():
            self._mgr.Update()

[docs]    def OnChildFocusNotebook(self, event):
        """
        Handles the ``wx.EVT_CHILD_FOCUS`` event for L{AuiNotebook}.

        :param `event`: a `wx.ChildFocusEvent` event to be processed.
        """

        # if we're dragging a tab, don't change the current selection.
        # This code prevents a bug that used to happen when the hint window
        # was hidden.  In the bug, the focus would return to the notebook
        # child, which would then enter this handler and call
        # SetSelection, which is not desired turn tab dragging.

        event.Skip()

        all_panes = self._mgr.GetAllPanes()
        for pane in all_panes:
            if pane.name == "dummy":
                continue
            tabframe = pane.window
            if tabframe._tabs.IsDragging():
                return

##        # change the tab selection to the child
##        # which was focused
##        idx = self._tabs.GetIdxFromWindow(event.GetWindow())
##        if idx != -1 and idx != self._curpage:
##            self.SetSelection(idx)

[docs]    def SetNavigatorIcon(self, bmp):
        """
        Sets the icon used by the L{TabNavigatorWindow}.

        :param `bmp`: an instance of `wx.Bitmap`.
        """

        if isinstance(bmp, wx.Bitmap) and bmp.IsOk():
            self.NavigatorProps.Icon = bmp
        else:
            raise TypeError, "SetNavigatorIcon requires a valid bitmap"

[docs]    def OnNavigationKeyNotebook(self, event):
        """
        Handles the ``wx.EVT_NAVIGATION_KEY`` event for L{AuiNotebook}.

        :param `event`: a `wx.NavigationKeyEvent` event to be processed.
        """

        if event.IsWindowChange():
            if self._agwFlags & AUI_NB_SMART_TABS:
                if not self._popupWin:
                    self._popupWin = TabNavigatorWindow(self, self.NavigatorProps)
                    self._popupWin.SetReturnCode(wx.ID_OK)
                    self._popupWin.ShowModal()
                    idx = self._popupWin.GetSelectedPage()
                    self._popupWin.Destroy()
                    self._popupWin = None
                    # Need to do CallAfter so that the selection and its
                    # associated events get processed outside the context of
                    # this key event. Not doing so causes odd issues with the
                    # window focus under certain use cases on Windows.
                    wx.CallAfter(self.SetSelection, idx, True)
                else:
                    # a dialog is already opened
                    self._popupWin.OnNavigationKey(event)
                    return
            else:
                # change pages
                # FIXME: the problem with this is that if we have a split notebook,
                # we selection may go all over the place.
                self.AdvanceSelection(event.GetDirection())

        else:
            # we get this event in 3 cases
            #
            # a) one of our pages might have generated it because the user TABbed
            # out from it in which case we should propagate the event upwards and
            # our parent will take care of setting the focus to prev/next sibling
            #
            # or
            #
            # b) the parent panel wants to give the focus to us so that we
            # forward it to our selected page. We can't deal with this in
            # OnSetFocus() because we don't know which direction the focus came
            # from in this case and so can't choose between setting the focus to
            # first or last panel child
            #
            # or
            #
            # c) we ourselves (see MSWTranslateMessage) generated the event
            #
            parent = self.GetParent()

            # the wxObject* casts are required to avoid MinGW GCC 2.95.3 ICE
            isFromParent = event.GetEventObject() == parent
            isFromSelf = event.GetEventObject() == self

            if isFromParent or isFromSelf:

                # no, it doesn't come from child, case (b) or (c): forward to a
                # page but only if direction is backwards (TAB) or from ourselves,
                if self.GetSelection() != wx.NOT_FOUND and (not event.GetDirection() or isFromSelf):

                    # so that the page knows that the event comes from it's parent
                    # and is being propagated downwards
                    event.SetEventObject(self)

                    page = self.GetPage(self.GetSelection())
                    if not page.GetEventHandler().ProcessEvent(event):
                        page.SetFocus()

                    #else: page manages focus inside it itself

                else: # otherwise set the focus to the notebook itself

                    self.SetFocus()

            else:

                # send this event back for the 'wraparound' focus.
                winFocus = event.GetCurrentFocus()

                if winFocus:
                    event.SetEventObject(self)
                    winFocus.GetEventHandler().ProcessEvent(event)

[docs]    def OnTabButton(self, event):
        """
        Handles the ``EVT_AUINOTEBOOK_BUTTON`` event for L{AuiNotebook}.

        :param `event`: a L{AuiNotebookEvent} event to be processed.
        """

        tabs = event.GetEventObject()
        button_id = event.GetInt()

        if button_id == AUI_BUTTON_CLOSE:

            selection = event.GetSelection()

            if selection == -1:

                # if the close button is to the right, use the active
                # page selection to determine which page to close
                selection = tabs.GetActivePage()

            if selection == -1 or not tabs.GetEnabled(selection):
                return

            if selection != -1:

                close_wnd = tabs.GetWindowFromIdx(selection)

                if close_wnd.GetName() == "__fake__page__":
                    # This is a notebook preview
                    previous_active, page_status = close_wnd.__previousStatus
                    for page, status in zip(tabs.GetPages(), page_status):
                        page.enabled = status

                    main_idx = self._tabs.GetIdxFromWindow(close_wnd)
                    self.DeletePage(main_idx)

                    if previous_active >= 0:
                        tabs.SetActivePage(previous_active)
                        page_count = tabs.GetPageCount()
                        selection = -1

                        for page in xrange(page_count):
                            # remove the page from the source tabs
                            page_info = tabs.GetPage(page)
                            if page_info.active:
                                selection = page
                                break

                        tabs.DoShowHide()
                        self.DoSizing()
                        tabs.Refresh()

                        if selection >= 0:
                            wx.CallAfter(tabs.MakeTabVisible, selection, self)

                    # Don't fire the event
                    return

                # ask owner if it's ok to close the tab
                e = AuiNotebookEvent(wxEVT_COMMAND_AUINOTEBOOK_PAGE_CLOSE, self.GetId())
                idx = self._tabs.GetIdxFromWindow(close_wnd)
                e.SetSelection(idx)
                e.SetOldSelection(event.GetSelection())
                e.SetEventObject(self)
                self.GetEventHandler().ProcessEvent(e)
                if not e.IsAllowed():
                    return

                if repr(close_wnd.__class__).find("AuiMDIChildFrame") >= 0:
                    close_wnd.Close()

                else:
                    main_idx = self._tabs.GetIdxFromWindow(close_wnd)
                    self.DeletePage(main_idx)

                # notify owner that the tab has been closed
                e2 = AuiNotebookEvent(wxEVT_COMMAND_AUINOTEBOOK_PAGE_CLOSED, self.GetId())
                e2.SetSelection(idx)
                e2.SetEventObject(self)
                self.GetEventHandler().ProcessEvent(e2)

                if self.GetPageCount() == 0:
                    mgr = self.GetAuiManager()
                    win = mgr.GetManagedWindow()
                    win.SendSizeEvent()

[docs]    def OnTabMiddleDown(self, event):
        """
        Handles the ``EVT_AUINOTEBOOK_TAB_MIDDLE_DOWN`` event for L{AuiNotebook}.

        :param `event`: a L{AuiNotebookEvent} event to be processed.
        """

        tabs = event.GetEventObject()
        if not tabs.GetEnabled(event.GetSelection()):
            return

        # patch event through to owner
        wnd = tabs.GetWindowFromIdx(event.GetSelection())

        e = AuiNotebookEvent(wxEVT_COMMAND_AUINOTEBOOK_TAB_MIDDLE_DOWN, self.GetId())
        e.SetSelection(self._tabs.GetIdxFromWindow(wnd))
        e.SetEventObject(self)
        self.GetEventHandler().ProcessEvent(e)

[docs]    def OnTabMiddleUp(self, event):
        """
        Handles the ``EVT_AUINOTEBOOK_TAB_MIDDLE_UP`` event for L{AuiNotebook}.

        :param `event`: a L{AuiNotebookEvent} event to be processed.
        """

        tabs = event.GetEventObject()
        if not tabs.GetEnabled(event.GetSelection()):
            return

        # if the AUI_NB_MIDDLE_CLICK_CLOSE is specified, middle
        # click should act like a tab close action.  However, first
        # give the owner an opportunity to handle the middle up event
        # for custom action

        wnd = tabs.GetWindowFromIdx(event.GetSelection())

        e = AuiNotebookEvent(wxEVT_COMMAND_AUINOTEBOOK_TAB_MIDDLE_UP, self.GetId())
        e.SetSelection(self._tabs.GetIdxFromWindow(wnd))
        e.SetEventObject(self)
        if self.GetEventHandler().ProcessEvent(e):
            return
        if not e.IsAllowed():
            return

        # check if we are supposed to close on middle-up
        if self._agwFlags & AUI_NB_MIDDLE_CLICK_CLOSE == 0:
            return

        # simulate the user pressing the close button on the tab
        event.SetInt(AUI_BUTTON_CLOSE)
        self.OnTabButton(event)

[docs]    def OnTabRightDown(self, event):
        """
        Handles the ``EVT_AUINOTEBOOK_TAB_RIGHT_DOWN`` event for L{AuiNotebook}.

        :param `event`: a L{AuiNotebookEvent} event to be processed.
        """

        tabs = event.GetEventObject()
        if not tabs.GetEnabled(event.GetSelection()):
            return

        # patch event through to owner
        wnd = tabs.GetWindowFromIdx(event.GetSelection())

        e = AuiNotebookEvent(wxEVT_COMMAND_AUINOTEBOOK_TAB_RIGHT_DOWN, self.GetId())
        e.SetSelection(self._tabs.GetIdxFromWindow(wnd))
        e.SetEventObject(self)
        self.GetEventHandler().ProcessEvent(e)

[docs]    def OnTabRightUp(self, event):
        """
        Handles the ``EVT_AUINOTEBOOK_TAB_RIGHT_UP`` event for L{AuiNotebook}.

        :param `event`: a L{AuiNotebookEvent} event to be processed.
        """

        tabs = event.GetEventObject()
        if not tabs.GetEnabled(event.GetSelection()):
            return

        # patch event through to owner
        wnd = tabs.GetWindowFromIdx(event.GetSelection())

        e = AuiNotebookEvent(wxEVT_COMMAND_AUINOTEBOOK_TAB_RIGHT_UP, self.GetId())
        e.SetSelection(self._tabs.GetIdxFromWindow(wnd))
        e.SetEventObject(self)
        self.GetEventHandler().ProcessEvent(e)

[docs]    def SetNormalFont(self, font):
        """
        Sets the normal font for drawing tab labels.

        :param `font`: a `wx.Font` object.
        """

        self._normal_font = font
        self.GetArtProvider().SetNormalFont(font)

[docs]    def SetSelectedFont(self, font):
        """
        Sets the selected tab font for drawing tab labels.

        :param `font`: a `wx.Font` object.
        """

        self._selected_font = font
        self.GetArtProvider().SetSelectedFont(font)

[docs]    def SetMeasuringFont(self, font):
        """
        Sets the font for calculating text measurements.

        :param `font`: a `wx.Font` object.
        """

        self.GetArtProvider().SetMeasuringFont(font)

[docs]    def SetFont(self, font):
        """
        Sets the tab font.

        :param `font`: a `wx.Font` object.

        :note: Overridden from `wx.PyPanel`.
        """

        wx.PyPanel.SetFont(self, font)

        selectedFont = wx.Font(font.GetPointSize(), font.GetFamily(),
                               font.GetStyle(), wx.BOLD, font.GetUnderlined(),
                               font.GetFaceName(), font.GetEncoding())

        self.SetNormalFont(font)
        self.SetSelectedFont(selectedFont)
        self.SetMeasuringFont(selectedFont)

        # Recalculate tab container size based on new font
        self.UpdateTabCtrlHeight(force=False)
        self.DoSizing()

        return True

[docs]    def GetTabCtrlHeight(self):
        """ Returns the tab control height. """

        return self._tab_ctrl_height

[docs]    def GetHeightForPageHeight(self, pageHeight):
        """
        Gets the height of the notebook for a given page height.

        :param `pageHeight`: the given page height.
        """

        self.UpdateTabCtrlHeight()

        tabCtrlHeight = self.GetTabCtrlHeight()
        decorHeight = 2
        return tabCtrlHeight + pageHeight + decorHeight

[docs]    def AdvanceSelection(self, forward=True, wrap=True):
        """
        Cycles through the tabs.

        :param `forward`: whether to advance forward or backward;
        :param `wrap`: ``True`` to return to the first tab if we reach the last tab.

        :note: The call to this function generates the page changing events.
        """

        tabCtrl = self.GetActiveTabCtrl()
        newPage = -1

        focusWin = tabCtrl.FindFocus()
        activePage = tabCtrl.GetActivePage()
        lenPages = len(tabCtrl.GetPages())

        if lenPages == 1:
            return False

        if forward:
            if lenPages > 1:

                if activePage == -1 or activePage == lenPages - 1:
                    if not wrap:
                        return False

                    newPage = 0

                elif activePage < lenPages - 1:
                    newPage = activePage + 1

        else:

            if lenPages > 1:
                if activePage == -1 or activePage == 0:
                    if not wrap:
                        return False

                    newPage = lenPages - 1

                elif activePage > 0:
                    newPage = activePage - 1

        if newPage != -1:
            if not self.GetEnabled(newPage):
                return False

            e = AuiNotebookEvent(wxEVT_COMMAND_AUINOTEBOOK_PAGE_CHANGING, tabCtrl.GetId())
            e.SetSelection(newPage)
            e.SetOldSelection(activePage)
            e.SetEventObject(tabCtrl)
            self.GetEventHandler().ProcessEvent(e)

##        if focusWin:
##            focusWin.SetFocus()

        return True

[docs]    def ShowWindowMenu(self):
        """
        Shows the window menu for the active tab control associated with this
        notebook, and returns ``True`` if a selection was made.
        """

        tabCtrl = self.GetActiveTabCtrl()
        idx = tabCtrl.GetArtProvider().ShowDropDown(tabCtrl, tabCtrl.GetPages(), tabCtrl.GetActivePage())

        if not self.GetEnabled(idx):
            return False

        if idx != -1:
            e = AuiNotebookEvent(wxEVT_COMMAND_AUINOTEBOOK_PAGE_CHANGING, tabCtrl.GetId())
            e.SetSelection(idx)
            e.SetOldSelection(tabCtrl.GetActivePage())
            e.SetEventObject(tabCtrl)
            self.GetEventHandler().ProcessEvent(e)

            return True

        else:

            return False

[docs]    def AddTabAreaButton(self, id, location, normal_bitmap=wx.NullBitmap, disabled_bitmap=wx.NullBitmap):
        """
        Adds a button in the tab area.

        :param `id`: the button identifier. This can be one of the following:

         ==============================  =================================
         Button Identifier               Description
         ==============================  =================================
         ``AUI_BUTTON_CLOSE``            Shows a close button on the tab area
         ``AUI_BUTTON_WINDOWLIST``       Shows a window list button on the tab area
         ``AUI_BUTTON_LEFT``             Shows a left button on the tab area
         ``AUI_BUTTON_RIGHT``            Shows a right button on the tab area
         ==============================  =================================

        :param `location`: the button location. Can be ``wx.LEFT`` or ``wx.RIGHT``;
        :param `normal_bitmap`: the bitmap for an enabled tab;
        :param `disabled_bitmap`: the bitmap for a disabled tab.
        """

        active_tabctrl = self.GetActiveTabCtrl()
        active_tabctrl.AddButton(id, location, normal_bitmap, disabled_bitmap)

[docs]    def RemoveTabAreaButton(self, id):
        """
        Removes a button from the tab area.

        :param `id`: the button identifier. See L{AddTabAreaButton} for a list of button identifiers.

        :see: L{AddTabAreaButton}
        """

        active_tabctrl = self.GetActiveTabCtrl()
        active_tabctrl.RemoveButton(id)

[docs]    def CloneTabAreaButtons(self):
        """
        Clones the tab area buttons when the L{AuiNotebook} is being split.

        :see: L{AddTabAreaButton}

        :note: Standard buttons for L{AuiNotebook} are not cloned, only custom ones.
        """

        active_tabctrl = self.GetActiveTabCtrl()
        clones = active_tabctrl.CloneButtons()

        return clones

[docs]    def HasMultiplePages(self):
        """
        This method should be overridden to return ``True`` if this window has multiple pages. All
        standard class with multiple pages such as `wx.Notebook`, `wx.Listbook` and `wx.Treebook`
        already override it to return ``True`` and user-defined classes with similar behaviour
        should do it as well to allow the library to handle such windows appropriately.

        :note: Overridden from `wx.PyPanel`.
        """

        return True

[docs]    def GetDefaultBorder(self):
        """ Returns the default border style for L{AuiNotebook}. """

        return wx.BORDER_NONE

[docs]    def NotebookPreview(self, thumbnail_size=200):
        """
        Generates a preview of all the pages in the notebook (MSW and GTK only).

        :param `thumbnail_size`: the maximum size of every page thumbnail.

        :note: this functionality is currently unavailable on wxMac.
        """

        if wx.Platform == "__WXMAC__":
            return False

        tabCtrl = self.GetActiveTabCtrl()
        activePage = tabCtrl.GetActivePage()
        pages = tabCtrl.GetPages()

        pageStatus, pageText = [], []

        for indx, page in enumerate(pages):

            pageStatus.append(page.enabled)

            if not page.enabled:
                continue

            self.SetSelectionToPage(page)
            pageText.append(page.caption)

            rect = page.window.GetScreenRect()
            bmp = RescaleScreenShot(TakeScreenShot(rect), thumbnail_size)

            page.enabled = False
            if indx == 0:
                il = wx.ImageList(bmp.GetWidth(), bmp.GetHeight(), True)

            il.Add(bmp)

        # create the list control
        listCtrl = wx.ListCtrl(self, style=wx.LC_ICON|wx.LC_AUTOARRANGE|wx.LC_HRULES|wx.LC_VRULES,
                               name="__fake__page__")

        # assign the image list to it
        listCtrl.AssignImageList(il, wx.IMAGE_LIST_NORMAL)
        listCtrl.__previousStatus = [activePage, pageStatus]

        # create some items for the list
        for indx, text in enumerate(pageText):
            listCtrl.InsertImageStringItem(10000, text, indx)

        self.AddPage(listCtrl, "AuiNotebook Preview", True, bitmap=auinotebook_preview.GetBitmap(), disabled_bitmap=wx.NullBitmap)
        return True

[docs]    def SetRenamable(self, page_idx, renamable):
        """
        Sets whether a tab can be renamed via a left double-click or not.

        :param `page_idx`: the page index;
        :param `renamable`: ``True`` if the page can be renamed.
        """

        if page_idx >= self._tabs.GetPageCount():
            return False

        # update our own tab catalog
        page_info = self._tabs.GetPage(page_idx)
        page_info.renamable = renamable

        # update what's on screen
        ctrl, ctrl_idx = self.FindTab(page_info.window)
        if not ctrl:
            return False

        info = ctrl.GetPage(ctrl_idx)
        info.renamable = page_info.renamable

        return True

[docs]    def IsRenamable(self, page_idx):
        """
        Returns whether a tab can be renamed or not.

        :param `page_idx`: the page index.

        :returns: ``True`` is a page can be renamed, ``False`` otherwise.
        """

        if page_idx >= self._tabs.GetPageCount():
            return False

        page_info = self._tabs.GetPage(page_idx)
        return page_info.renamable

[docs]    def OnRenameCancelled(self, page_index):
        """
        Called by L{TabTextCtrl}, to cancel the changes and to send the
        `EVT_AUINOTEBOOK_END_LABEL_EDIT` event.

        :param `page_index`: the page index in the notebook.
        """

        # let owner know that the edit was cancelled
        evt = AuiNotebookEvent(wxEVT_COMMAND_AUINOTEBOOK_END_LABEL_EDIT, self.GetId())

        evt.SetSelection(page_index)
        evt.SetEventObject(self)
        evt.SetLabel("")
        evt.SetEditCanceled(True)
        self.GetEventHandler().ProcessEvent(evt)

[docs]    def OnRenameAccept(self, page_index, value):
        """
        Called by L{TabTextCtrl}, to accept the changes and to send the
        `EVT_AUINOTEBOOK_END_LABEL_EDIT` event.

        :param `page_index`: the page index in the notebook;
        :param `value`: the new label for the tab.
        """

        evt = AuiNotebookEvent(wxEVT_COMMAND_AUINOTEBOOK_END_LABEL_EDIT, self.GetId())
        evt.SetSelection(page_index)
        evt.SetEventObject(self)
        evt.SetLabel(value)
        evt.SetEditCanceled(False)

        return not self.GetEventHandler().ProcessEvent(evt) or evt.IsAllowed()

[docs]    def ResetTextControl(self):
        """ Called by L{TabTextCtrl} when it marks itself for deletion. """

        if not self._textCtrl:
            return

        self._textCtrl.Destroy()
        self._textCtrl = None

        # tab height might have changed
        self.UpdateTabCtrlHeight(force=True)

[docs]    def EditTab(self, page_index):
        """
        Starts the editing of an item label, sending a `EVT_AUINOTEBOOK_BEGIN_LABEL_EDIT` event.

        :param `page_index`: the page index we want to edit.
        """

        if page_index >= self._tabs.GetPageCount():
            return False

        if not self.IsRenamable(page_index):
            return False

        page_info = self._tabs.GetPage(page_index)
        ctrl, ctrl_idx = self.FindTab(page_info.window)
        if not ctrl:
            return False

        evt = AuiNotebookEvent(wxEVT_COMMAND_AUINOTEBOOK_BEGIN_LABEL_EDIT, self.GetId())
        evt.SetSelection(page_index)
        evt.SetEventObject(self)
        if self.GetEventHandler().ProcessEvent(evt) and not evt.IsAllowed():
            # vetoed by user
            return False

        if self._textCtrl is not None and page_info != self._textCtrl.item():
            self._textCtrl.StopEditing()

        self._textCtrl = TabTextCtrl(ctrl, page_info, page_index)
        self._textCtrl.SetFocus()

        return True

Navigation

  • index
  • modules |
  • Home |
  • Gallery |
  • Contents»
  • Module code »
  • aui.auibook


aui.dockart

  • modules |
  • Home |
  • Gallery |
  • Contents»
  • Module code »
  • aui.dockart

Source code for aui.dockart

"""
Dock art provider code - a dock provider provides all drawing functionality to
the AUI dock manager. This allows the dock manager to have a plugable look-and-feel.

By default, a L{AuiManager} uses an instance of this class called L{AuiDefaultDockArt}
which provides bitmap art and a colour scheme that is adapted to the major platforms'
look. You can either derive from that class to alter its behaviour or write a
completely new dock art class. Call L{AuiManager.SetArtProvider} to make use this
new dock art.
"""

__author__ = "Andrea Gavana <andrea.gavana@gmail.com>"
__date__ = "31 March 2009"

import wx
import types

from aui_utilities import BitmapFromBits, StepColour, ChopText, GetBaseColour
from aui_utilities import DrawGradientRectangle, DrawMACCloseButton
from aui_utilities import DarkenBitmap, LightContrastColour
from aui_constants import *

optionActive = 2**14

_ctypes = False

# Try to import winxptheme for ModernDockArt
if wx.Platform == "__WXMSW__":
    try:
        import ctypes
        import winxptheme
        _ctypes = True
    except ImportError:
        pass

# -- AuiDefaultDockArt class implementation --

[docs]class AuiDefaultDockArt(object):
    """
    Dock art provider code - a dock provider provides all drawing functionality
    to the AUI dock manager. This allows the dock manager to have a plugable
    look-and-feel.

    By default, a L{AuiManager} uses an instance of this class called L{AuiDefaultDockArt}
    which provides bitmap art and a colour scheme that is adapted to the major
    platforms' look. You can either derive from that class to alter its behaviour or
    write a completely new dock art class.

    Call L{AuiManager.SetArtProvider} to make use this new dock art.

    **Metric Ordinals**

    These are the possible pane dock art settings for L{AuiManager}:

    ================================================  ======================================
    Metric Ordinal Constant                           Description
    ================================================  ======================================
    ``AUI_DOCKART_SASH_SIZE``                         Customizes the sash size
    ``AUI_DOCKART_CAPTION_SIZE``                      Customizes the caption size
    ``AUI_DOCKART_GRIPPER_SIZE``                      Customizes the gripper size
    ``AUI_DOCKART_PANE_BORDER_SIZE``                  Customizes the pane border size
    ``AUI_DOCKART_PANE_BUTTON_SIZE``                  Customizes the pane button size
    ``AUI_DOCKART_BACKGROUND_COLOUR``                 Customizes the background colour
    ``AUI_DOCKART_BACKGROUND_GRADIENT_COLOUR``        Customizes the background gradient colour
    ``AUI_DOCKART_SASH_COLOUR``                       Customizes the sash colour
    ``AUI_DOCKART_ACTIVE_CAPTION_COLOUR``             Customizes the active caption colour
    ``AUI_DOCKART_ACTIVE_CAPTION_GRADIENT_COLOUR``    Customizes the active caption gradient colour
    ``AUI_DOCKART_INACTIVE_CAPTION_COLOUR``           Customizes the inactive caption colour
    ``AUI_DOCKART_INACTIVE_CAPTION_GRADIENT_COLOUR``  Customizes the inactive gradient caption colour
    ``AUI_DOCKART_ACTIVE_CAPTION_TEXT_COLOUR``        Customizes the active caption text colour
    ``AUI_DOCKART_INACTIVE_CAPTION_TEXT_COLOUR``      Customizes the inactive caption text colour
    ``AUI_DOCKART_BORDER_COLOUR``                     Customizes the border colour
    ``AUI_DOCKART_GRIPPER_COLOUR``                    Customizes the gripper colour
    ``AUI_DOCKART_CAPTION_FONT``                      Customizes the caption font
    ``AUI_DOCKART_GRADIENT_TYPE``                     Customizes the gradient type (no gradient, vertical or horizontal)
    ``AUI_DOCKART_DRAW_SASH_GRIP``                    Draw a sash grip on the sash
    ================================================  ======================================

    **Gradient Types**

    These are the possible gradient dock art settings for L{AuiManager}:

    ============================================  ======================================
    Gradient Constant                             Description
    ============================================  ======================================
    ``AUI_GRADIENT_NONE``                         No gradient on the captions
    ``AUI_GRADIENT_VERTICAL``                     Vertical gradient on the captions
    ``AUI_GRADIENT_HORIZONTAL``                   Horizontal gradient on the captions
    ============================================  ======================================

    **Button States**

    These are the possible pane button / L{AuiNotebook} button / L{AuiToolBar} button states:

    ============================================  ======================================
    Button State Constant                         Description
    ============================================  ======================================
    ``AUI_BUTTON_STATE_NORMAL``                   Normal button state
    ``AUI_BUTTON_STATE_HOVER``                    Hovered button state
    ``AUI_BUTTON_STATE_PRESSED``                  Pressed button state
    ``AUI_BUTTON_STATE_DISABLED``                 Disabled button state
    ``AUI_BUTTON_STATE_HIDDEN``                   Hidden button state
    ``AUI_BUTTON_STATE_CHECKED``                  Checked button state
    ============================================  ======================================

    **Button Identifiers**

    These are the possible pane button / L{AuiNotebook} button / L{AuiToolBar} button identifiers:

    ============================================  ======================================
    Button Identifier                             Description
    ============================================  ======================================
    ``AUI_BUTTON_CLOSE``                          Shows a close button on the pane
    ``AUI_BUTTON_MAXIMIZE_RESTORE``               Shows a maximize/restore button on the pane
    ``AUI_BUTTON_MINIMIZE``                       Shows a minimize button on the pane
    ``AUI_BUTTON_PIN``                            Shows a pin button on the pane
    ``AUI_BUTTON_OPTIONS``                        Shows an option button on the pane (not implemented)
    ``AUI_BUTTON_WINDOWLIST``                     Shows a window list button on the pane (for L{AuiNotebook})
    ``AUI_BUTTON_LEFT``                           Shows a left button on the pane (for L{AuiNotebook})
    ``AUI_BUTTON_RIGHT``                          Shows a right button on the pane (for L{AuiNotebook})
    ``AUI_BUTTON_UP``                             Shows an up button on the pane (not implemented)
    ``AUI_BUTTON_DOWN``                           Shows a down button on the pane (not implemented)
    ``AUI_BUTTON_CUSTOM1``                        Shows a custom button on the pane (not implemented)
    ``AUI_BUTTON_CUSTOM2``                        Shows a custom button on the pane (not implemented)
    ``AUI_BUTTON_CUSTOM3``                        Shows a custom button on the pane (not implemented)
    ============================================  ======================================

    """

[docs]    def __init__(self):
        """ Default class constructor. """

        self.Init()

        isMac = wx.Platform == "__WXMAC__"

        if isMac:
            self._caption_font = wx.SMALL_FONT
        else:
            self._caption_font = wx.Font(8, wx.DEFAULT, wx.NORMAL, wx.NORMAL, False)

        self.SetDefaultPaneBitmaps(isMac)
        self._restore_bitmap = wx.BitmapFromXPMData(restore_xpm)

        # default metric values
        self._sash_size = 4

        if isMac:
            # This really should be implemented in wx.SystemSettings
            # There is no way to do this that I am aware outside of using
            # the cocoa python bindings. 8 pixels looks correct on my system
            # so hard coding it for now.

            # How do I translate this?!? Not sure of the below implementation...
            # SInt32 height;
            # GetThemeMetric( kThemeMetricSmallPaneSplitterHeight , &height );
            # self._sash_size = height;

            self._sash_size = 8 # Carbon.Appearance.kThemeMetricPaneSplitterHeight

        elif wx.Platform == "__WXGTK__":
            self._sash_size = wx.RendererNative.Get().GetSplitterParams(wx.GetTopLevelWindows()[0]).widthSash

        else:
            self._sash_size = 4

        self._caption_size = 19
        self._border_size = 1
        self._button_size = 14
        self._gripper_size = 9
        self._gradient_type = AUI_GRADIENT_VERTICAL
        self._draw_sash = False

[docs]    def Init(self):
        """ Initializes the dock art. """

        self.SetDefaultColours()

        isMac = wx.Platform == "__WXMAC__"

        if isMac:
            self._active_caption_colour = wx.SystemSettings.GetColour(wx.SYS_COLOUR_HIGHLIGHT)
        else:
            self._active_caption_colour = wx.SystemSettings.GetColour(wx.SYS_COLOUR_ACTIVECAPTION)

        self._active_caption_gradient_colour = LightContrastColour(wx.SystemSettings.GetColour(wx.SYS_COLOUR_HIGHLIGHT))
        self._active_caption_text_colour = wx.SystemSettings.GetColour(wx.SYS_COLOUR_HIGHLIGHTTEXT)
        self._inactive_caption_text_colour = wx.BLACK

[docs]    def SetDefaultColours(self, base_colour=None):
        """
        Sets the default colours, which are calculated from the given base colour.

        :param `base_colour`: an instance of `wx.Colour`. If defaulted to ``None``, a colour
         is generated accordingly to the platform and theme.
        """

        if base_colour is None:
            base_colour = GetBaseColour()

        darker1_colour = StepColour(base_colour, 85)
        darker2_colour = StepColour(base_colour, 75)
        darker3_colour = StepColour(base_colour, 60)
        darker4_colour = StepColour(base_colour, 40)

        self._background_colour = base_colour
        self._background_gradient_colour = StepColour(base_colour, 180)

        self._inactive_caption_colour = darker1_colour
        self._inactive_caption_gradient_colour = StepColour(base_colour, 97)

        self._sash_brush = wx.Brush(base_colour)
        self._background_brush = wx.Brush(base_colour)
        self._border_pen = wx.Pen(darker2_colour)
        self._gripper_brush = wx.Brush(base_colour)
        self._gripper_pen1 = wx.Pen(darker4_colour)
        self._gripper_pen2 = wx.Pen(darker3_colour)
        self._gripper_pen3 = wx.WHITE_PEN

[docs]    def GetMetric(self, id):
        """
        Gets the value of a certain setting.

        :param `id`: can be one of the size values in `Metric Ordinals`.
        """

        if id == AUI_DOCKART_SASH_SIZE:
            return self._sash_size
        elif id == AUI_DOCKART_CAPTION_SIZE:
            return self._caption_size
        elif id == AUI_DOCKART_GRIPPER_SIZE:
            return self._gripper_size
        elif id == AUI_DOCKART_PANE_BORDER_SIZE:
            return self._border_size
        elif id == AUI_DOCKART_PANE_BUTTON_SIZE:
            return self._button_size
        elif id == AUI_DOCKART_GRADIENT_TYPE:
            return self._gradient_type
        elif id == AUI_DOCKART_DRAW_SASH_GRIP:
            return self._draw_sash
        else:
            raise Exception("Invalid Metric Ordinal.")

[docs]    def SetMetric(self, id, new_val):
        """
        Sets the value of a certain setting using `new_val`

        :param `id`: can be one of the size values in `Metric Ordinals`;
        :param `new_val`: the new value of the setting.
        """

        if id == AUI_DOCKART_SASH_SIZE:
            self._sash_size = new_val
        elif id == AUI_DOCKART_CAPTION_SIZE:
            self._caption_size = new_val
        elif id == AUI_DOCKART_GRIPPER_SIZE:
            self._gripper_size = new_val
        elif id == AUI_DOCKART_PANE_BORDER_SIZE:
            self._border_size = new_val
        elif id == AUI_DOCKART_PANE_BUTTON_SIZE:
            self._button_size = new_val
        elif id == AUI_DOCKART_GRADIENT_TYPE:
            self._gradient_type = new_val
        elif id == AUI_DOCKART_DRAW_SASH_GRIP:
            self._draw_sash = new_val
        else:
            raise Exception("Invalid Metric Ordinal.")

[docs]    def GetColor(self, id):
        """
        Gets the colour of a certain setting.

        :param `id`: can be one of the colour values in `Metric Ordinals`.
        """

        if id == AUI_DOCKART_BACKGROUND_COLOUR:
            return self._background_brush.GetColour()
        elif id == AUI_DOCKART_BACKGROUND_GRADIENT_COLOUR:
            return self._background_gradient_colour
        elif id == AUI_DOCKART_SASH_COLOUR:
            return self._sash_brush.GetColour()
        elif id == AUI_DOCKART_INACTIVE_CAPTION_COLOUR:
            return self._inactive_caption_colour
        elif id == AUI_DOCKART_INACTIVE_CAPTION_GRADIENT_COLOUR:
            return self._inactive_caption_gradient_colour
        elif id == AUI_DOCKART_INACTIVE_CAPTION_TEXT_COLOUR:
            return self._inactive_caption_text_colour
        elif id == AUI_DOCKART_ACTIVE_CAPTION_COLOUR:
            return self._active_caption_colour
        elif id == AUI_DOCKART_ACTIVE_CAPTION_GRADIENT_COLOUR:
            return self._active_caption_gradient_colour
        elif id == AUI_DOCKART_ACTIVE_CAPTION_TEXT_COLOUR:
            return self._active_caption_text_colour
        elif id == AUI_DOCKART_BORDER_COLOUR:
            return self._border_pen.GetColour()
        elif id == AUI_DOCKART_GRIPPER_COLOUR:
            return self._gripper_brush.GetColour()
        else:
            raise Exception("Invalid Colour Ordinal.")

[docs]    def SetColor(self, id, colour):
        """
        Sets the colour of a certain setting.

        :param `id`: can be one of the colour values in `Metric Ordinals`;
        :param `colour`: the new value of the setting.
        """

        if isinstance(colour, basestring):
            colour = wx.NamedColour(colour)
        elif isinstance(colour, types.TupleType):
            colour = wx.Colour(*colour)
        elif isinstance(colour, types.IntType):
            colour = wx.ColourRGB(colour)

        if id == AUI_DOCKART_BACKGROUND_COLOUR:
            self._background_brush.SetColour(colour)
        elif id == AUI_DOCKART_BACKGROUND_GRADIENT_COLOUR:
            self._background_gradient_colour = colour
        elif id == AUI_DOCKART_SASH_COLOUR:
            self._sash_brush.SetColour(colour)
        elif id == AUI_DOCKART_INACTIVE_CAPTION_COLOUR:
            self._inactive_caption_colour = colour
            if not self._custom_pane_bitmaps and wx.Platform == "__WXMAC__":
                # No custom bitmaps for the pane close button
                # Change the MAC close bitmap colour
                self._inactive_close_bitmap = DrawMACCloseButton(wx.WHITE, colour)

        elif id == AUI_DOCKART_INACTIVE_CAPTION_GRADIENT_COLOUR:
            self._inactive_caption_gradient_colour = colour
        elif id == AUI_DOCKART_INACTIVE_CAPTION_TEXT_COLOUR:
            self._inactive_caption_text_colour = colour
        elif id == AUI_DOCKART_ACTIVE_CAPTION_COLOUR:
            self._active_caption_colour = colour
            if not self._custom_pane_bitmaps and wx.Platform == "__WXMAC__":
                # No custom bitmaps for the pane close button
                # Change the MAC close bitmap colour
                self._active_close_bitmap = DrawMACCloseButton(wx.WHITE, colour)

        elif id == AUI_DOCKART_ACTIVE_CAPTION_GRADIENT_COLOUR:
            self._active_caption_gradient_colour = colour
        elif id == AUI_DOCKART_ACTIVE_CAPTION_TEXT_COLOUR:
            self._active_caption_text_colour = colour
        elif id == AUI_DOCKART_BORDER_COLOUR:
            self._border_pen.SetColour(colour)
        elif id == AUI_DOCKART_GRIPPER_COLOUR:
            self._gripper_brush.SetColour(colour)
            self._gripper_pen1.SetColour(StepColour(colour, 40))
            self._gripper_pen2.SetColour(StepColour(colour, 60))
        else:
            raise Exception("Invalid Colour Ordinal.")

    GetColour = GetColor
    SetColour = SetColor

[docs]    def SetFont(self, id, font):
        """
        Sets a font setting.

        :param `id`: must be ``AUI_DOCKART_CAPTION_FONT``;
        :param `font`: an instance of `wx.Font`.
        """

        if id == AUI_DOCKART_CAPTION_FONT:
            self._caption_font = font

[docs]    def GetFont(self, id):
        """
        Gets a font setting.

        :param `id`: must be ``AUI_DOCKART_CAPTION_FONT``, otherwise `wx.NullFont` is returned.
        """

        if id == AUI_DOCKART_CAPTION_FONT:
            return self._caption_font

        return wx.NullFont

[docs]    def DrawSash(self, dc, window, orient, rect):
        """
        Draws a sash between two windows.

        :param `dc`: a `wx.DC` device context;
        :param `window`: an instance of `wx.Window`;
        :param `orient`: the sash orientation;
        :param `rect`: the sash rectangle.
        """

        # AG: How do we make this work?!?
        # RendererNative does not use the sash_brush chosen by the user
        # and the rect.GetSize() is ignored as the sash is always drawn
        # 3 pixel wide
        # wx.RendererNative.Get().DrawSplitterSash(window, dc, rect.GetSize(), pos, orient)

        dc.SetPen(wx.TRANSPARENT_PEN)
        dc.SetBrush(self._sash_brush)
        dc.DrawRectangle(rect.x, rect.y, rect.width, rect.height)

        draw_sash = self.GetMetric(AUI_DOCKART_DRAW_SASH_GRIP)
        if draw_sash:
            self.DrawSashGripper(dc, orient, rect)

[docs]    def DrawBackground(self, dc, window, orient, rect):
        """
        Draws a background.

        :param `dc`: a `wx.DC` device context;
        :param `window`: an instance of `wx.Window`;
        :param `orient`: the gradient (if any) orientation;
        :param `rect`: the background rectangle.
        """

        dc.SetPen(wx.TRANSPARENT_PEN)
        if wx.Platform == "__WXMAC__":
            # we have to clear first, otherwise we are drawing a light striped pattern
            # over an already darker striped background
            dc.SetBrush(wx.WHITE_BRUSH)
            dc.DrawRectangle(rect.x, rect.y, rect.width, rect.height)

        DrawGradientRectangle(dc, rect, self._background_brush.GetColour(),
                              self._background_gradient_colour,
                              AUI_GRADIENT_HORIZONTAL, rect.x, 700)

[docs]    def DrawBorder(self, dc, window, rect, pane):
        """
        Draws the pane border.

        :param `dc`: a `wx.DC` device context;
        :param `window`: an instance of `wx.Window`;
        :param `rect`: the border rectangle;
        :param `pane`: the pane for which the border is drawn.
        """

        drect = wx.Rect(*rect)

        dc.SetPen(self._border_pen)
        dc.SetBrush(wx.TRANSPARENT_BRUSH)

        border_width = self.GetMetric(AUI_DOCKART_PANE_BORDER_SIZE)

        if pane.IsToolbar():

            for ii in xrange(0, border_width):

                dc.SetPen(wx.WHITE_PEN)
                dc.DrawLine(drect.x, drect.y, drect.x+drect.width, drect.y)
                dc.DrawLine(drect.x, drect.y, drect.x, drect.y+drect.height)
                dc.SetPen(self._border_pen)
                dc.DrawLine(drect.x, drect.y+drect.height-1,
                            drect.x+drect.width, drect.y+drect.height-1)
                dc.DrawLine(drect.x+drect.width-1, drect.y,
                            drect.x+drect.width-1, drect.y+drect.height)
                drect.Deflate(1, 1)

        else:

            for ii in xrange(0, border_width):

                dc.DrawRectangle(drect.x, drect.y, drect.width, drect.height)
                drect.Deflate(1, 1)

[docs]    def DrawCaptionBackground(self, dc, rect, pane):
        """
        Draws the text caption background in the pane.

        :param `dc`: a `wx.DC` device context;
        :param `rect`: the text caption rectangle;
        :param `pane`: the pane for which the text background is drawn.
        """

        active = pane.state & optionActive

        if self._gradient_type == AUI_GRADIENT_NONE:
            if active:
                dc.SetBrush(wx.Brush(self._active_caption_colour))
            else:
                dc.SetBrush(wx.Brush(self._inactive_caption_colour))

            dc.DrawRectangle(rect.x, rect.y, rect.width, rect.height)

        else:

            switch_gradient = pane.HasCaptionLeft()
            gradient_type = self._gradient_type
            if switch_gradient:
                gradient_type = (self._gradient_type == AUI_GRADIENT_HORIZONTAL and [AUI_GRADIENT_VERTICAL] or \
                                 [AUI_GRADIENT_HORIZONTAL])[0]

            if active:
                if wx.Platform == "__WXMAC__":
                    DrawGradientRectangle(dc, rect, self._active_caption_colour,
                                          self._active_caption_gradient_colour,
                                          gradient_type)
                else:
                    DrawGradientRectangle(dc, rect, self._active_caption_gradient_colour,
                                          self._active_caption_colour,
                                          gradient_type)
            else:
                if wx.Platform == "__WXMAC__":
                    DrawGradientRectangle(dc, rect, self._inactive_caption_gradient_colour,
                                          self._inactive_caption_colour,
                                          gradient_type)
                else:
                    DrawGradientRectangle(dc, rect, self._inactive_caption_colour,
                                          self._inactive_caption_gradient_colour,
                                          gradient_type)

[docs]    def DrawIcon(self, dc, rect, pane):
        """
        Draws the icon in the pane caption area.

        :param `dc`: a `wx.DC` device context;
        :param `rect`: the pane caption rectangle;
        :param `pane`: the pane for which the icon is drawn.
        """

        # Draw the icon centered vertically
        if pane.icon.Ok():
            if pane.HasCaptionLeft():
                bmp = wx.ImageFromBitmap(pane.icon).Rotate90(clockwise=False)
                dc.DrawBitmap(bmp.ConvertToBitmap(), rect.x+(rect.width-pane.icon.GetWidth())/2, rect.y+rect.height-2-pane.icon.GetHeight(), True)
            else:
                dc.DrawBitmap(pane.icon, rect.x+2, rect.y+(rect.height-pane.icon.GetHeight())/2, True)

[docs]    def DrawCaption(self, dc, window, text, rect, pane):
        """
        Draws the text in the pane caption.

        :param `dc`: a `wx.DC` device context;
        :param `window`: an instance of `wx.Window`;
        :param `text`: the text to be displayed;
        :param `rect`: the pane caption rectangle;
        :param `pane`: the pane for which the text is drawn.
        """

        dc.SetPen(wx.TRANSPARENT_PEN)
        dc.SetFont(self._caption_font)

        self.DrawCaptionBackground(dc, rect, pane)

        if pane.state & optionActive:
            dc.SetTextForeground(self._active_caption_text_colour)
        else:
            dc.SetTextForeground(self._inactive_caption_text_colour)

        w, h = dc.GetTextExtent("ABCDEFHXfgkj")

        clip_rect = wx.Rect(*rect)
        btns = pane.CountButtons()

        captionLeft = pane.HasCaptionLeft()
        variable = (captionLeft and [rect.height] or [rect.width])[0]

        variable -= 3      # text offset
        variable -= 2      # button padding

        caption_offset = 0
        if pane.icon:
            if captionLeft:
                caption_offset += pane.icon.GetHeight() + 3
            else:
                caption_offset += pane.icon.GetWidth() + 3

            self.DrawIcon(dc, rect, pane)

        variable -= caption_offset
        variable -= btns*(self._button_size + self._border_size)
        draw_text = ChopText(dc, text, variable)

        if captionLeft:
            dc.DrawRotatedText(draw_text, rect.x+(rect.width/2)-(h/2)-1, rect.y+rect.height-3-caption_offset, 90)
        else:
            dc.DrawText(draw_text, rect.x+3+caption_offset, rect.y+(rect.height/2)-(h/2)-1)

[docs]    def RequestUserAttention(self, dc, window, text, rect, pane):
        """
        Requests the user attention by intermittently highlighting the pane caption.

        :param `dc`: a `wx.DC` device context;
        :param `window`: an instance of `wx.Window`;
        :param `text`: the text to be displayed;
        :param `rect`: the pane caption rectangle;
        :param `pane`: the pane for which the text is drawn.
        """

        state = pane.state
        pane.state &= ~optionActive

        for indx in xrange(6):
            active = (indx%2 == 0 and [True] or [False])[0]
            if active:
                pane.state |= optionActive
            else:
                pane.state &= ~optionActive

            self.DrawCaptionBackground(dc, rect, pane)
            self.DrawCaption(dc, window, text, rect, pane)
            wx.SafeYield()
            wx.MilliSleep(350)

        pane.state = state

[docs]    def DrawGripper(self, dc, window, rect, pane):
        """
        Draws a gripper on the pane.

        :param `dc`: a `wx.DC` device context;
        :param `window`: an instance of `wx.Window`;
        :param `rect`: the pane caption rectangle;
        :param `pane`: the pane for which the gripper is drawn.
        """

        dc.SetPen(wx.TRANSPARENT_PEN)
        dc.SetBrush(self._gripper_brush)

        dc.DrawRectangle(rect.x, rect.y, rect.width, rect.height)

        if not pane.HasGripperTop():
            y = 4
            while 1:
                dc.SetPen(self._gripper_pen1)
                dc.DrawPoint(rect.x+3, rect.y+y)
                dc.SetPen(self._gripper_pen2)
                dc.DrawPoint(rect.x+3, rect.y+y+1)
                dc.DrawPoint(rect.x+4, rect.y+y)
                dc.SetPen(self._gripper_pen3)
                dc.DrawPoint(rect.x+5, rect.y+y+1)
                dc.DrawPoint(rect.x+5, rect.y+y+2)
                dc.DrawPoint(rect.x+4, rect.y+y+2)
                y = y + 4
                if y > rect.GetHeight() - 4:
                    break
        else:
            x = 4
            while 1:
                dc.SetPen(self._gripper_pen1)
                dc.DrawPoint(rect.x+x, rect.y+3)
                dc.SetPen(self._gripper_pen2)
                dc.DrawPoint(rect.x+x+1, rect.y+3)
                dc.DrawPoint(rect.x+x, rect.y+4)
                dc.SetPen(self._gripper_pen3)
                dc.DrawPoint(rect.x+x+1, rect.y+5)
                dc.DrawPoint(rect.x+x+2, rect.y+5)
                dc.DrawPoint(rect.x+x+2, rect.y+4)
                x = x + 4
                if x > rect.GetWidth() - 4:
                    break

[docs]    def DrawPaneButton(self, dc, window, button, button_state, _rect, pane):
        """
        Draws a pane button in the pane caption area.

        :param `dc`: a `wx.DC` device context;
        :param `window`: an instance of `wx.Window`;
        :param `button`: the button to be drawn;
        :param `button_state`: the pane button state;
        :param `_rect`: the pane caption rectangle;
        :param `pane`: the pane for which the button is drawn.
        """

        if not pane:
            return

        if button == AUI_BUTTON_CLOSE:
            if pane.state & optionActive:
                bmp = self._active_close_bitmap
            else:
                bmp = self._inactive_close_bitmap

        elif button == AUI_BUTTON_PIN:
            if pane.state & optionActive:
                bmp = self._active_pin_bitmap
            else:
                bmp = self._inactive_pin_bitmap

        elif button == AUI_BUTTON_MAXIMIZE_RESTORE:
            if pane.IsMaximized():
                if pane.state & optionActive:
                    bmp = self._active_restore_bitmap
                else:
                    bmp = self._inactive_restore_bitmap
            else:
                if pane.state & optionActive:
                    bmp = self._active_maximize_bitmap
                else:
                    bmp = self._inactive_maximize_bitmap

        elif button == AUI_BUTTON_MINIMIZE:
            if pane.state & optionActive:
                bmp = self._active_minimize_bitmap
            else:
                bmp = self._inactive_minimize_bitmap

        isVertical = pane.HasCaptionLeft()

        rect = wx.Rect(*_rect)

        if isVertical:
            old_x = rect.x
            rect.x = rect.x + (rect.width/2) - (bmp.GetWidth()/2)
            rect.width = old_x + rect.width - rect.x - 1
        else:
            old_y = rect.y
            rect.y = rect.y + (rect.height/2) - (bmp.GetHeight()/2)
            rect.height = old_y + rect.height - rect.y - 1

        if button_state == AUI_BUTTON_STATE_PRESSED:
            rect.x += 1
            rect.y += 1

        if button_state in [AUI_BUTTON_STATE_HOVER, AUI_BUTTON_STATE_PRESSED]:

            if pane.state & optionActive:

                dc.SetBrush(wx.Brush(StepColour(self._active_caption_colour, 120)))
                dc.SetPen(wx.Pen(StepColour(self._active_caption_colour, 70)))

            else:

                dc.SetBrush(wx.Brush(StepColour(self._inactive_caption_colour, 120)))
                dc.SetPen(wx.Pen(StepColour(self._inactive_caption_colour, 70)))

            if wx.Platform != "__WXMAC__":
                # draw the background behind the button
                dc.DrawRectangle(rect.x, rect.y, 15, 15)
            else:
                # Darker the bitmap a bit
                bmp = DarkenBitmap(bmp, self._active_caption_colour, StepColour(self._active_caption_colour, 110))

        if isVertical:
            bmp = wx.ImageFromBitmap(bmp).Rotate90(clockwise=False).ConvertToBitmap()

        # draw the button itself
        dc.DrawBitmap(bmp, rect.x, rect.y, True)

[docs]    def DrawSashGripper(self, dc, orient, rect):
        """
        Draws a sash gripper on a sash between two windows.

        :param `dc`: a `wx.DC` device context;
        :param `orient`: the sash orientation;
        :param `rect`: the sash rectangle.
        """

        dc.SetBrush(self._gripper_brush)

        if orient == wx.HORIZONTAL:  # horizontal sash

            x = rect.x + int((1.0/4.0)*rect.width)
            xend = rect.x + int((3.0/4.0)*rect.width)
            y = rect.y + (rect.height/2) - 1

            while 1:
                dc.SetPen(self._gripper_pen3)
                dc.DrawRectangle(x, y, 2, 2)
                dc.SetPen(self._gripper_pen2)
                dc.DrawPoint(x+1, y+1)
                x = x + 5

                if x >= xend:
                    break

        else:

            y = rect.y + int((1.0/4.0)*rect.height)
            yend = rect.y + int((3.0/4.0)*rect.height)
            x = rect.x + (rect.width/2) - 1

            while 1:
                dc.SetPen(self._gripper_pen3)
                dc.DrawRectangle(x, y, 2, 2)
                dc.SetPen(self._gripper_pen2)
                dc.DrawPoint(x+1, y+1)
                y = y + 5

                if y >= yend:
                    break

[docs]    def SetDefaultPaneBitmaps(self, isMac):
        """
        Assigns the default pane bitmaps.

        :param `isMac`: whether we are on wxMAC or not.
        """

        if isMac:
            self._inactive_close_bitmap = DrawMACCloseButton(wx.WHITE, self._inactive_caption_colour)
            self._active_close_bitmap = DrawMACCloseButton(wx.WHITE, self._active_caption_colour)
        else:
            self._inactive_close_bitmap = BitmapFromBits(close_bits, 16, 16, self._inactive_caption_text_colour)
            self._active_close_bitmap = BitmapFromBits(close_bits, 16, 16, self._active_caption_text_colour)

        if isMac:
            self._inactive_maximize_bitmap = BitmapFromBits(max_bits, 16, 16, wx.WHITE)
            self._active_maximize_bitmap = BitmapFromBits(max_bits, 16, 16, wx.WHITE)
        else:
            self._inactive_maximize_bitmap = BitmapFromBits(max_bits, 16, 16, self._inactive_caption_text_colour)
            self._active_maximize_bitmap = BitmapFromBits(max_bits, 16, 16, self._active_caption_text_colour)

        if isMac:
            self._inactive_restore_bitmap = BitmapFromBits(restore_bits, 16, 16, wx.WHITE)
            self._active_restore_bitmap = BitmapFromBits(restore_bits, 16, 16, wx.WHITE)
        else:
            self._inactive_restore_bitmap = BitmapFromBits(restore_bits, 16, 16, self._inactive_caption_text_colour)
            self._active_restore_bitmap = BitmapFromBits(restore_bits, 16, 16, self._active_caption_text_colour)

        if isMac:
            self._inactive_minimize_bitmap = BitmapFromBits(minimize_bits, 16, 16, wx.WHITE)
            self._active_minimize_bitmap = BitmapFromBits(minimize_bits, 16, 16, wx.WHITE)
        else:
            self._inactive_minimize_bitmap = BitmapFromBits(minimize_bits, 16, 16, self._inactive_caption_text_colour)
            self._active_minimize_bitmap = BitmapFromBits(minimize_bits, 16, 16, self._active_caption_text_colour)

        self._inactive_pin_bitmap = BitmapFromBits(pin_bits, 16, 16, self._inactive_caption_text_colour)
        self._active_pin_bitmap = BitmapFromBits(pin_bits, 16, 16, self._active_caption_text_colour)

        self._custom_pane_bitmaps = False

[docs]    def SetCustomPaneBitmap(self, bmp, button, active, maximize=False):
        """
        Sets a custom button bitmap for the pane button.

        :param `bmp`: the actual bitmap to set;
        :param `button`: the button identifier;
        :param `active`: whether it is the bitmap for the active button or not;
        :param `maximize`: used to distinguish between the maximize and restore bitmaps.
        """

        if bmp.GetWidth() > 16 or bmp.GetHeight() > 16:
            raise Exception("The input bitmap is too big")

        if button == AUI_BUTTON_CLOSE:
            if active:
                self._active_close_bitmap = bmp
            else:
                self._inactive_close_bitmap = bmp

            if wx.Platform == "__WXMAC__":
                self._custom_pane_bitmaps = True

        elif button == AUI_BUTTON_PIN:
            if active:
                self._active_pin_bitmap = bmp
            else:
                self._inactive_pin_bitmap = bmp

        elif button == AUI_BUTTON_MAXIMIZE_RESTORE:
            if maximize:
                if active:
                    self._active_maximize_bitmap = bmp
                else:
                    self._inactive_maximize_bitmap = bmp
            else:
                if active:
                    self._active_restore_bitmap = bmp
                else:
                    self._inactive_restore_bitmap = bmp

        elif button == AUI_BUTTON_MINIMIZE:
            if active:
                self._active_minimize_bitmap = bmp
            else:
                self._inactive_minimize_bitmap = bmp

if _ctypes:
    class RECT(ctypes.Structure):
        """ Used to handle L{ModernDockArt} on Windows XP/Vista/7. """
        _fields_ = [('left', ctypes.c_ulong),('top', ctypes.c_ulong),('right', ctypes.c_ulong),('bottom', ctypes.c_ulong)]

        def dump(self):
            """ Dumps `self` as a `wx.Rect`. """
            return map(int, (self.left, self.top, self.right, self.bottom))

    class SIZE(ctypes.Structure):
        """ Used to handle L{ModernDockArt} on Windows XP/Vista/7. """
        _fields_ = [('x', ctypes.c_long),('y', ctypes.c_long)]

[docs]class ModernDockArt(AuiDefaultDockArt):
    """
    ModernDockArt is a custom `AuiDockArt` class, that implements a look similar to
    Firefox and other recents applications.

    Is uses the `winxptheme` module and XP themes whenever possible, so it should
    look good even if the user has a custom theme.

    :note: This dock art is Windows only and will only work if you have installed
     Mark Hammond's `pywin32` module (http://sourceforge.net/projects/pywin32/).
    """

[docs]    def __init__(self, win):
        """
        Default class constructor.

        :param `win`: the window managed by L{AuiManager}.
        """

        AuiDefaultDockArt.__init__(self)

        self.win = win

        # Get the size of a small close button (themed)
        hwnd = self.win.GetHandle()
        self.usingTheme = False

        if _ctypes:
            self.hTheme1 = winxptheme.OpenThemeData(hwnd, "Window")
            self.usingTheme = True

        if not self.hTheme1:
            self.usingTheme = False

        self._button_size = 13

        self._button_border_size = 3
        self._caption_text_indent = 6
        self._caption_size = 22

        # We only highlight the active pane with the caption text being in bold.
        # So we do not want a special colour for active elements.
        self._active_close_bitmap = self._inactive_close_bitmap

        self.Init()

[docs]    def Init(self):
        """ Initializes the dock art. """

        AuiDefaultDockArt.Init(self)

        self._active_caption_colour = self._inactive_caption_colour
        self._active_caption_text_colour = wx.SystemSettings.GetColour(wx.SYS_COLOUR_CAPTIONTEXT)
        self._inactive_caption_text_colour = self._active_caption_text_colour

[docs]    def DrawCaption(self, dc, window, text, rect, pane):
        """
        Draws the text in the pane caption.

        :param `dc`: a `wx.DC` device context;
        :param `window`: an instance of `wx.Window`;
        :param `text`: the text to be displayed;
        :param `rect`: the pane caption rectangle;
        :param `pane`: the pane for which the text is drawn.
        """

        dc.SetPen(wx.TRANSPARENT_PEN)
        self.DrawCaptionBackground(dc, rect, pane)

        active = ((pane.state & optionActive) and [True] or [False])[0]

        self._caption_font.SetWeight(wx.FONTWEIGHT_BOLD)
        dc.SetFont(self._caption_font)

        if active:
            dc.SetTextForeground(self._active_caption_text_colour)
        else:
            dc.SetTextForeground(self._inactive_caption_text_colour)

        w, h = dc.GetTextExtent("ABCDEFHXfgkj")

        clip_rect = wx.Rect(*rect)
        btns = pane.CountButtons()

        captionLeft = pane.HasCaptionLeft()
        variable = (captionLeft and [rect.height] or [rect.width])[0]

        variable -= 3      # text offset
        variable -= 2      # button padding

        caption_offset = 0
        if pane.icon:
            if captionLeft:
                caption_offset += pane.icon.GetHeight() + 3
            else:
                caption_offset += pane.icon.GetWidth() + 3

            self.DrawIcon(dc, rect, pane)

        diff = -2
        if self.usingTheme:
            diff = -1

        variable -= caption_offset
        variable -= btns*(self._button_size + self._button_border_size)
        draw_text = ChopText(dc, text, variable)

        if captionLeft:
            dc.DrawRotatedText(draw_text, rect.x+(rect.width/2)-(h/2)-diff, rect.y+rect.height-3-caption_offset, 90)
        else:
            dc.DrawText(draw_text, rect.x+3+caption_offset, rect.y+(rect.height/2)-(h/2)-diff)

[docs]    def DrawCaptionBackground(self, dc, rect, pane):
        """
        Draws the text caption background in the pane.

        :param `dc`: a `wx.DC` device context;
        :param `rect`: the text caption rectangle;
        :param `pane`: the pane for which we are drawing the caption background.
        """

        dc.SetBrush(self._background_brush)
        dc.DrawRectangle(rect.x, rect.y, rect.width, rect.height)

        active = ((pane.state & optionActive) and [True] or [False])[0]

        if self.usingTheme:

            rectangle = wx.Rect()

            rc = RECT(rectangle.x, rectangle.y, rectangle.width, rectangle.height)

            # If rect x/y values are negative rc.right/bottom values will overflow and winxptheme.DrawThemeBackground
            # will raise a TypeError. Ensure they are never negative.
            rect.x = max(0, rect.x)
            rect.y = max(0, rect.y)

            rc.top = rect.x
            rc.left = rect.y
            rc.right = rect.x + rect.width
            rc.bottom = rect.y + rect.height

            if active:
                winxptheme.DrawThemeBackground(self.hTheme1, dc.GetHDC(), 5, 1, (rc.top, rc.left, rc.right, rc.bottom), None)
            else:
                winxptheme.DrawThemeBackground(self.hTheme1, dc.GetHDC(), 5, 2, (rc.top, rc.left, rc.right, rc.bottom), None)

        else:

            AuiDefaultDockArt.DrawCaptionBackground(self, dc, rect, pane)

[docs]    def RequestUserAttention(self, dc, window, text, rect, pane):
        """
        Requests the user attention by intermittently highlighting the pane caption.

        :param `dc`: a `wx.DC` device context;
        :param `window`: an instance of `wx.Window`;
        :param `text`: the text to be displayed;
        :param `rect`: the pane caption rectangle;
        :param `pane`: the pane for which the text is drawn.
        """

        state = pane.state
        pane.state &= ~optionActive

        for indx in xrange(6):
            active = (indx%2 == 0 and [True] or [False])[0]
            if active:
                pane.state |= optionActive
            else:
                pane.state &= ~optionActive

            self.DrawCaptionBackground(dc, rect, pane)
            self.DrawCaption(dc, window, text, rect, pane)
            wx.SafeYield()
            wx.MilliSleep(350)

        pane.state = state

[docs]    def DrawPaneButton(self, dc, window, button, button_state, rect, pane):
        """
        Draws a pane button in the pane caption area.

        :param `dc`: a `wx.DC` device context;
        :param `window`: an instance of `wx.Window`;
        :param `button`: the button to be drawn;
        :param `button_state`: the pane button state;
        :param `rect`: the pane caption rectangle;
        :param `pane`: the pane for which the button is drawn.
        """

        if self.usingTheme:

            hTheme = self.hTheme1

            # Get the real button position (compensating for borders)
            drect = wx.Rect(rect.x, rect.y, self._button_size, self._button_size)

            # Draw the themed close button
            rc = RECT(0, 0, 0, 0)
            if pane.HasCaptionLeft():
                rc.top = rect.x + self._button_border_size
                rc.left = int(rect.y + 1.5*self._button_border_size)
                rc.right = rect.x + self._button_size + self._button_border_size
                rc.bottom = int(rect.y + self._button_size + 1.5*self._button_border_size)
            else:
                rc.top = rect.x - self._button_border_size
                rc.left = int(rect.y + 1.5*self._button_border_size)
                rc.right = rect.x + self._button_size- self._button_border_size
                rc.bottom = int(rect.y + self._button_size + 1.5*self._button_border_size)

            if button == AUI_BUTTON_CLOSE:
                btntype = 19

            elif button == AUI_BUTTON_PIN:
                btntype = 23

            elif button == AUI_BUTTON_MAXIMIZE_RESTORE:
                if not pane.IsMaximized():
                    btntype = 17
                else:
                    btntype = 21
            else:
                btntype = 15

            state = 4 # CBS_DISABLED

            if pane.state & optionActive:

                if button_state == AUI_BUTTON_STATE_NORMAL:
                    state = 1 # CBS_NORMAL

                elif button_state == AUI_BUTTON_STATE_HOVER:
                    state = 2 # CBS_HOT

                elif button_state == AUI_BUTTON_STATE_PRESSED:
                    state = 3 # CBS_PUSHED

                else:
                    raise Exception("ERROR: Unknown State.")

            else: # inactive pane

                if button_state == AUI_BUTTON_STATE_NORMAL:
                    state = 5 # CBS_NORMAL

                elif button_state == AUI_BUTTON_STATE_HOVER:
                    state = 6 # CBS_HOT

                elif button_state == AUI_BUTTON_STATE_PRESSED:
                    state = 7 # CBS_PUSHED

                else:
                    raise Exception("ERROR: Unknown State.")

            try:
                winxptheme.DrawThemeBackground(hTheme, dc.GetHDC(), btntype, state, (rc.top, rc.left, rc.right, rc.bottom), None)
            except TypeError:
                return

        else:

            # Fallback to default closebutton if themes are not enabled
            rect2 = wx.Rect(rect.x-4, rect.y+2, rect.width, rect.height)
            AuiDefaultDockArt.DrawPaneButton(self, dc, window, button, button_state, rect2, pane)

Navigation

  • index
  • modules |
  • Home |
  • Gallery |
  • Contents»
  • Module code »
  • aui.dockart


aui.framemanager

  • modules |
  • Home |
  • Gallery |
  • Contents»
  • Module code »
  • aui.framemanager

Source code for aui.framemanager

# --------------------------------------------------------------------------- #
# AUI Library wxPython IMPLEMENTATION
#
# Original C++ Code From Kirix (wxAUI). You Can Find It At:
#
#    License: wxWidgets license
#
# http:#www.kirix.com/en/community/opensource/wxaui/about_wxaui.html
#
# Current wxAUI Version Tracked: wxWidgets 2.9.0 SVN HEAD
#
#
# Python Code By:
#
# Andrea Gavana, @ 23 Dec 2005
# Latest Revision: 07 Mar 2012, 21.00 GMT
#
# 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
# --------------------------------------------------------------------------- #

"""
Description
===========

`framemanager.py` is the central module of the AUI class framework.

L{AuiManager} manages the panes associated with it for a particular `wx.Frame`, using
a pane's L{AuiPaneInfo} information to determine each pane's docking and floating
behavior. AuiManager uses wxPython' sizer mechanism to plan the layout of each frame.
It uses a replaceable dock art class to do all drawing, so all drawing is localized
in one area, and may be customized depending on an application's specific needs.

AuiManager works as follows: the programmer adds panes to the class, or makes
changes to existing pane properties (dock position, floating state, show state, etc...).
To apply these changes, AuiManager's L{AuiManager.Update} function is called. This batch
processing can be used to avoid flicker, by modifying more than one pane at a time,
and then "committing" all of the changes at once by calling `Update()`.

Panes can be added quite easily::

    text1 = wx.TextCtrl(self, -1)
    text2 = wx.TextCtrl(self, -1)
    self._mgr.AddPane(text1, AuiPaneInfo().Left().Caption("Pane Number One"))
    self._mgr.AddPane(text2, AuiPaneInfo().Bottom().Caption("Pane Number Two"))

    self._mgr.Update()

Later on, the positions can be modified easily. The following will float an
existing pane in a tool window::

    self._mgr.GetPane(text1).Float()

Layers, Rows and Directions, Positions
======================================

Inside AUI, the docking layout is figured out by checking several pane parameters.
Four of these are important for determining where a pane will end up.

**Direction** - Each docked pane has a direction, `Top`, `Bottom`, `Left`, `Right`, or `Center`.
This is fairly self-explanatory. The pane will be placed in the location specified
by this variable.

**Position** - More than one pane can be placed inside of a "dock". Imagine two panes
being docked on the left side of a window. One pane can be placed over another.
In proportionally managed docks, the pane position indicates it's sequential position,
starting with zero. So, in our scenario with two panes docked on the left side, the
top pane in the dock would have position 0, and the second one would occupy position 1.

**Row** - A row can allow for two docks to be placed next to each other. One of the most
common places for this to happen is in the toolbar. Multiple toolbar rows are allowed,
the first row being in row 0, and the second in row 1. Rows can also be used on
vertically docked panes.

**Layer** - A layer is akin to an onion. Layer 0 is the very center of the managed pane.
Thus, if a pane is in layer 0, it will be closest to the center window (also sometimes
known as the "content window"). Increasing layers "swallow up" all layers of a lower
value. This can look very similar to multiple rows, but is different because all panes
in a lower level yield to panes in higher levels. The best way to understand layers
is by running the AUI sample (`AUI.py`).
"""

__author__ = "Andrea Gavana <andrea.gavana@gmail.com>"
__date__ = "31 March 2009"

import wx
import time
import types
import warnings

import auibar
import auibook
import tabmdi
import dockart
import tabart

from aui_utilities import Clip, PaneCreateStippleBitmap, GetDockingImage, GetSlidingPoints

from aui_constants import *

# Define this as a translation function
_ = wx.GetTranslation

_winxptheme = False
if wx.Platform == "__WXMSW__":
    try:
        import winxptheme
        _winxptheme = True
    except ImportError:
        pass

# wxPython version string
_VERSION_STRING = wx.VERSION_STRING

# AUI Events
wxEVT_AUI_PANE_BUTTON = wx.NewEventType()
wxEVT_AUI_PANE_CLOSE = wx.NewEventType()
wxEVT_AUI_PANE_MAXIMIZE = wx.NewEventType()
wxEVT_AUI_PANE_RESTORE = wx.NewEventType()
wxEVT_AUI_RENDER = wx.NewEventType()
wxEVT_AUI_FIND_MANAGER = wx.NewEventType()
wxEVT_AUI_PANE_MINIMIZE = wx.NewEventType()
wxEVT_AUI_PANE_MIN_RESTORE = wx.NewEventType()
wxEVT_AUI_PANE_FLOATING = wx.NewEventType()
wxEVT_AUI_PANE_FLOATED = wx.NewEventType()
wxEVT_AUI_PANE_DOCKING = wx.NewEventType()
wxEVT_AUI_PANE_DOCKED = wx.NewEventType()
wxEVT_AUI_PANE_ACTIVATED = wx.NewEventType()
wxEVT_AUI_PERSPECTIVE_CHANGED = wx.NewEventType()

EVT_AUI_PANE_BUTTON = wx.PyEventBinder(wxEVT_AUI_PANE_BUTTON, 0)
""" Fires an event when the user left-clicks on a pane button. """
EVT_AUI_PANE_CLOSE = wx.PyEventBinder(wxEVT_AUI_PANE_CLOSE, 0)
""" A pane in `AuiManager` has been closed. """
EVT_AUI_PANE_MAXIMIZE = wx.PyEventBinder(wxEVT_AUI_PANE_MAXIMIZE, 0)
""" A pane in `AuiManager` has been maximized. """
EVT_AUI_PANE_RESTORE = wx.PyEventBinder(wxEVT_AUI_PANE_RESTORE, 0)
""" A pane in `AuiManager` has been restored from a maximized state. """
EVT_AUI_RENDER = wx.PyEventBinder(wxEVT_AUI_RENDER, 0)
""" Fires an event every time the AUI frame is being repainted. """
EVT_AUI_FIND_MANAGER = wx.PyEventBinder(wxEVT_AUI_FIND_MANAGER, 0)
""" Used to find which AUI manager is controlling a certain pane. """
EVT_AUI_PANE_MINIMIZE = wx.PyEventBinder(wxEVT_AUI_PANE_MINIMIZE, 0)
""" A pane in `AuiManager` has been minimized. """
EVT_AUI_PANE_MIN_RESTORE = wx.PyEventBinder(wxEVT_AUI_PANE_MIN_RESTORE, 0)
""" A pane in `AuiManager` has been restored from a minimized state. """
EVT_AUI_PANE_FLOATING = wx.PyEventBinder(wxEVT_AUI_PANE_FLOATING, 0)
""" A pane in `AuiManager` is about to be floated. """
EVT_AUI_PANE_FLOATED = wx.PyEventBinder(wxEVT_AUI_PANE_FLOATED, 0)
""" A pane in `AuiManager` has been floated. """
EVT_AUI_PANE_DOCKING = wx.PyEventBinder(wxEVT_AUI_PANE_DOCKING, 0)
""" A pane in `AuiManager` is about to be docked. """
EVT_AUI_PANE_DOCKED = wx.PyEventBinder(wxEVT_AUI_PANE_DOCKED, 0)
""" A pane in `AuiManager` has been docked. """
EVT_AUI_PANE_ACTIVATED = wx.PyEventBinder(wxEVT_AUI_PANE_ACTIVATED, 0)
""" A pane in `AuiManager` has been activated. """
EVT_AUI_PERSPECTIVE_CHANGED = wx.PyEventBinder(wxEVT_AUI_PERSPECTIVE_CHANGED, 0)
""" The layout in `AuiManager` has been changed. """

# ---------------------------------------------------------------------------- #

[docs]class AuiDockInfo(object):
    """ A class to store all properties of a dock. """

[docs]    def __init__(self):
        """
        Default class constructor.
        Used internally, do not call it in your code!
        """

        object.__init__(self)

        self.dock_direction = 0
        self.dock_layer = 0
        self.dock_row = 0
        self.size = 0
        self.min_size = 0
        self.resizable = True
        self.fixed = False
        self.toolbar = False
        self.rect = wx.Rect()
        self.panes = []

[docs]    def IsOk(self):
        """
        Returns whether a dock is valid or not.

        In order to be valid, a dock needs to have a non-zero `dock_direction`.
        """

        return self.dock_direction != 0

[docs]    def IsHorizontal(self):
        """ Returns whether the dock is horizontal or not. """

        return self.dock_direction in [AUI_DOCK_TOP, AUI_DOCK_BOTTOM]

[docs]    def IsVertical(self):
        """ Returns whether the dock is vertical or not. """

        return self.dock_direction in [AUI_DOCK_LEFT, AUI_DOCK_RIGHT, AUI_DOCK_CENTER]

# ---------------------------------------------------------------------------- #

[docs]class AuiDockingGuideInfo(object):
    """ A class which holds information about VS2005 docking guide windows. """

[docs]    def __init__(self, other=None):
        """
        Default class constructor.
        Used internally, do not call it in your code!

        :param `other`: another instance of L{AuiDockingGuideInfo}.
        """

        if other:
            self.Assign(other)
        else:
            # window representing the docking target
            self.host = None
            # dock direction (top, bottom, left, right, center)
            self.dock_direction = AUI_DOCK_NONE

[docs]    def Assign(self, other):
        """
        Assigns the properties of the `other` L{AuiDockingGuideInfo} to `self`.

        :param `other`: another instance of L{AuiDockingGuideInfo}.
        """

        self.host = other.host
        self.dock_direction = other.dock_direction

[docs]    def Host(self, h):
        """
        Hosts a docking guide window.

        :param `h`: an instance of L{AuiSingleDockingGuide} or L{AuiCenterDockingGuide}.
        """

        self.host = h
        return self

[docs]    def Left(self):
        """ Sets the guide window to left docking. """

        self.dock_direction = AUI_DOCK_LEFT
        return self

[docs]    def Right(self):
        """ Sets the guide window to right docking. """

        self.dock_direction = AUI_DOCK_RIGHT
        return self

[docs]    def Top(self):
        """ Sets the guide window to top docking. """

        self.dock_direction = AUI_DOCK_TOP
        return self

[docs]    def Bottom(self):
        """ Sets the guide window to bottom docking. """

        self.dock_direction = AUI_DOCK_BOTTOM
        return self

[docs]    def Center(self):
        """ Sets the guide window to center docking. """

        self.dock_direction = AUI_DOCK_CENTER
        return self

[docs]    def Centre(self):
        """ Sets the guide window to centre docking. """

        self.dock_direction = AUI_DOCK_CENTRE
        return self

# ---------------------------------------------------------------------------- #

[docs]class AuiDockUIPart(object):
    """ A class which holds attributes for a UI part in the interface. """

    typeCaption = 0
    typeGripper = 1
    typeDock = 2
    typeDockSizer = 3
    typePane = 4
    typePaneSizer = 5
    typeBackground = 6
    typePaneBorder = 7
    typePaneButton = 8

[docs]    def __init__(self):
        """
        Default class constructor.
        Used internally, do not call it in your code!
        """

        self.orientation = wx.VERTICAL
        self.type = 0
        self.rect = wx.Rect()

# ---------------------------------------------------------------------------- #

[docs]class AuiPaneButton(object):
    """ A simple class which describes the caption pane button attributes. """

[docs]    def __init__(self, button_id):
        """
        Default class constructor.
        Used internally, do not call it in your code!

        :param `button_id`: the pane button identifier.
        """

        self.button_id = button_id

# ---------------------------------------------------------------------------- #

# event declarations/classes

[docs]class AuiManagerEvent(wx.PyCommandEvent):
    """ A specialized command event class for events sent by L{AuiManager}. """

[docs]    def __init__(self, eventType, id=1):
        """
        Default class constructor.

        :param `eventType`: the event kind;
        :param `id`: the event identification number.
        """

        wx.PyCommandEvent.__init__(self, eventType, id)

        self.manager = None
        self.pane = None
        self.button = 0
        self.veto_flag = False
        self.canveto_flag = True
        self.dc = None

[docs]    def SetManager(self, mgr):
        """
        Associates a L{AuiManager} to the current event.

        :param `mgr`: an instance of L{AuiManager}.
        """

        self.manager = mgr

[docs]    def SetDC(self, pdc):
        """
        Associates a `wx.DC` device context to this event.

        :param `pdc`: a `wx.DC` device context object.
        """

        self.dc = pdc

[docs]    def SetPane(self, p):
        """
        Associates a L{AuiPaneInfo} instance to this event.

        :param `p`: a L{AuiPaneInfo} instance.
        """

        self.pane = p

[docs]    def SetButton(self, b):
        """
        Associates a L{AuiPaneButton} instance to this event.

        :param `b`: a L{AuiPaneButton} instance.
        """

        self.button = b

[docs]    def GetManager(self):
        """ Returns the associated L{AuiManager} (if any). """

        return self.manager

[docs]    def GetDC(self):
        """ Returns the associated `wx.DC` device context (if any). """

        return self.dc

[docs]    def GetPane(self):
        """ Returns the associated L{AuiPaneInfo} structure (if any). """

        return self.pane

[docs]    def GetButton(self):
        """ Returns the associated L{AuiPaneButton} instance (if any). """

        return self.button

[docs]    def Veto(self, veto=True):
        """
        Prevents the change announced by this event from happening.

        It is in general a good idea to notify the user about the reasons for
        vetoing the change because otherwise the applications behaviour (which
        just refuses to do what the user wants) might be quite surprising.

        :param `veto`: ``True`` to veto the event, ``False`` otherwise.
        """

        self.veto_flag = veto

[docs]    def GetVeto(self):
        """ Returns whether the event has been vetoed or not. """

        return self.veto_flag

[docs]    def SetCanVeto(self, can_veto):
        """
        Sets whether the event can be vetoed or not.

        :param `can_veto`: a bool flag. ``True`` if the event can be vetoed, ``False`` otherwise.
        """

        self.canveto_flag = can_veto

[docs]    def CanVeto(self):
        """ Returns whether the event can be vetoed and has been vetoed. """

        return  self.canveto_flag and self.veto_flag

# ---------------------------------------------------------------------------- #

[docs]class AuiPaneInfo(object):
    """
    AuiPaneInfo specifies all the parameters for a pane. These parameters specify where
    the pane is on the screen, whether it is docked or floating, or hidden. In addition,
    these parameters specify the pane's docked position, floating position, preferred
    size, minimum size, caption text among many other parameters.
    """

    optionFloating         = 2**0
    optionHidden           = 2**1
    optionLeftDockable     = 2**2
    optionRightDockable    = 2**3
    optionTopDockable      = 2**4
    optionBottomDockable   = 2**5
    optionFloatable        = 2**6
    optionMovable          = 2**7
    optionResizable        = 2**8
    optionPaneBorder       = 2**9
    optionCaption          = 2**10
    optionGripper          = 2**11
    optionDestroyOnClose   = 2**12
    optionToolbar          = 2**13
    optionActive           = 2**14
    optionGripperTop       = 2**15
    optionMaximized        = 2**16
    optionDockFixed        = 2**17
    optionNotebookDockable = 2**18
    optionMinimized        = 2**19
    optionLeftSnapped      = 2**20
    optionRightSnapped     = 2**21
    optionTopSnapped       = 2**22
    optionBottomSnapped    = 2**23
    optionFlyOut           = 2**24
    optionCaptionLeft      = 2**25

    buttonClose            = 2**26
    buttonMaximize         = 2**27
    buttonMinimize         = 2**28
    buttonPin              = 2**29

    buttonCustom1          = 2**30
    buttonCustom2          = 2**31
    buttonCustom3          = 2**32

    savedHiddenState       = 2**33    # used internally
    actionPane             = 2**34    # used internally
    wasMaximized           = 2**35    # used internally
    needsRestore           = 2**36    # used internally

[docs]    def __init__(self):
        """ Default class constructor. """

        self.window = None
        self.frame = None
        self.state = 0
        self.dock_direction = AUI_DOCK_LEFT
        self.dock_layer = 0
        self.dock_row = 0
        self.dock_pos = 0
        self.minimize_mode = AUI_MINIMIZE_POS_SMART
        self.floating_pos = wx.Point(-1, -1)
        self.floating_size = wx.Size(-1, -1)
        self.best_size = wx.Size(-1, -1)
        self.min_size = wx.Size(-1, -1)
        self.max_size = wx.Size(-1, -1)
        self.dock_proportion = 0
        self.caption = ""
        self.buttons = []
        self.name = ""
        self.icon = wx.NullIcon
        self.rect = wx.Rect()
        self.notebook_id = -1
        self.transparent = 255
        self.needsTransparency = False
        self.previousDockPos = None
        self.previousDockSize = 0
        self.snapped = 0
        self.minimize_target = None

        self.DefaultPane()

[docs]    def dock_direction_get(self):
        """
        Getter for the `dock_direction`.

        :see: L{dock_direction_set} for a set of valid docking directions.
        """

        if self.IsMaximized():
            return AUI_DOCK_CENTER
        else:
            return self._dock_direction

[docs]    def dock_direction_set(self, value):
        """
        Setter for the `dock_direction`.

        :param `value`: the docking direction. This cab ne one of the following bits:

        ============================ ======= =============================================
        Dock Flag                     Value  Description
        ============================ ======= =============================================
        ``AUI_DOCK_NONE``                  0 No docking direction.
        ``AUI_DOCK_TOP``                   1 Top docking direction.
        ``AUI_DOCK_RIGHT``                 2 Right docking direction.
        ``AUI_DOCK_BOTTOM``                3 Bottom docking direction.
        ``AUI_DOCK_LEFT``                  4 Left docking direction.
        ``AUI_DOCK_CENTER``                5 Center docking direction.
        ``AUI_DOCK_CENTRE``                5 Centre docking direction.
        ``AUI_DOCK_NOTEBOOK_PAGE``         6 Automatic AuiNotebooks docking style.
        ============================ ======= =============================================

        """

        self._dock_direction = value

    dock_direction = property(dock_direction_get, dock_direction_set)

[docs]    def IsOk(self):
        """
        Returns ``True`` if the L{AuiPaneInfo} structure is valid.

        :note: A pane structure is valid if it has an associated window.
        """

        return self.window != None

[docs]    def IsMaximized(self):
        """ Returns ``True`` if the pane is maximized. """

        return self.HasFlag(self.optionMaximized)

[docs]    def IsMinimized(self):
        """ Returns ``True`` if the pane is minimized. """

        return self.HasFlag(self.optionMinimized)

[docs]    def IsFixed(self):
        """ Returns ``True`` if the pane cannot be resized. """

        return not self.HasFlag(self.optionResizable)

[docs]    def IsResizeable(self):
        """ Returns ``True`` if the pane can be resized. """

        return self.HasFlag(self.optionResizable)

[docs]    def IsShown(self):
        """ Returns ``True`` if the pane is currently shown. """

        return not self.HasFlag(self.optionHidden)

[docs]    def IsFloating(self):
        """ Returns ``True`` if the pane is floating. """

        return self.HasFlag(self.optionFloating)

[docs]    def IsDocked(self):
        """ Returns ``True`` if the pane is docked. """

        return not self.HasFlag(self.optionFloating)

[docs]    def IsToolbar(self):
        """ Returns ``True`` if the pane contains a toolbar. """

        return self.HasFlag(self.optionToolbar)

[docs]    def IsTopDockable(self):
        """
        Returns ``True`` if the pane can be docked at the top
        of the managed frame.
        """

        return self.HasFlag(self.optionTopDockable)

[docs]    def IsBottomDockable(self):
        """
        Returns ``True`` if the pane can be docked at the bottom
        of the managed frame.
        """

        return self.HasFlag(self.optionBottomDockable)

[docs]    def IsLeftDockable(self):
        """
        Returns ``True`` if the pane can be docked at the left
        of the managed frame.
        """

        return self.HasFlag(self.optionLeftDockable)

[docs]    def IsRightDockable(self):
        """
        Returns ``True`` if the pane can be docked at the right
        of the managed frame.
        """

        return self.HasFlag(self.optionRightDockable)

[docs]    def IsDockable(self):
        """ Returns ``True`` if the pane can be docked. """

        return self.IsTopDockable() or self.IsBottomDockable() or self.IsLeftDockable() or \
               self.IsRightDockable() or self.IsNotebookDockable()

[docs]    def IsFloatable(self):
        """
        Returns ``True`` if the pane can be undocked and displayed as a
        floating window.
        """

        return self.HasFlag(self.optionFloatable)

[docs]    def IsMovable(self):
        """
        Returns ``True`` if the docked frame can be undocked or moved to
        another dock position.
        """

        return self.HasFlag(self.optionMovable)

[docs]    def IsDestroyOnClose(self):
        """
        Returns ``True`` if the pane should be destroyed when it is closed.

        Normally a pane is simply hidden when the close button is clicked. Calling L{DestroyOnClose}
        with a ``True`` input parameter will cause the window to be destroyed when the user clicks
        the pane's close button.
        """

        return self.HasFlag(self.optionDestroyOnClose)

[docs]    def IsNotebookDockable(self):
        """
        Returns ``True`` if a pane can be docked on top to another to create a
        L{AuiNotebook}.
        """

        return self.HasFlag(self.optionNotebookDockable)

[docs]    def IsTopSnappable(self):
        """ Returns ``True`` if the pane can be snapped at the top of the managed frame. """

        return self.HasFlag(self.optionTopSnapped)

[docs]    def IsBottomSnappable(self):
        """ Returns ``True`` if the pane can be snapped at the bottom of the managed frame. """

        return self.HasFlag(self.optionBottomSnapped)

[docs]    def IsLeftSnappable(self):
        """ Returns ``True`` if the pane can be snapped on the left of the managed frame. """

        return self.HasFlag(self.optionLeftSnapped)

[docs]    def IsRightSnappable(self):
        """ Returns ``True`` if the pane can be snapped on the right of the managed frame. """

        return self.HasFlag(self.optionRightSnapped)

[docs]    def IsSnappable(self):
        """ Returns ``True`` if the pane can be snapped. """

        return self.IsTopSnappable() or self.IsBottomSnappable() or self.IsLeftSnappable() or \
               self.IsRightSnappable()

[docs]    def IsFlyOut(self):
        """ Returns ``True`` if the floating pane has a "fly-out" effect. """

        return self.HasFlag(self.optionFlyOut)

[docs]    def HasCaption(self):
        """ Returns ``True`` if the pane displays a caption. """

        return self.HasFlag(self.optionCaption)

[docs]    def HasCaptionLeft(self):
        """ Returns ``True`` if the pane displays a caption on the left (rotated by 90 degrees). """

        return self.HasFlag(self.optionCaptionLeft)

[docs]    def HasGripper(self):
        """ Returns ``True`` if the pane displays a gripper. """

        return self.HasFlag(self.optionGripper)

[docs]    def HasBorder(self):
        """ Returns ``True`` if the pane displays a border. """

        return self.HasFlag(self.optionPaneBorder)

[docs]    def HasCloseButton(self):
        """ Returns ``True`` if the pane displays a button to close the pane. """

        return self.HasFlag(self.buttonClose)

[docs]    def HasMaximizeButton(self):
        """ Returns ``True`` if the pane displays a button to maximize the pane. """

        return self.HasFlag(self.buttonMaximize)

[docs]    def HasMinimizeButton(self):
        """ Returns ``True`` if the pane displays a button to minimize the pane. """

        return self.HasFlag(self.buttonMinimize)

[docs]    def GetMinimizeMode(self):
        """
        Returns the minimization style for this pane.

        Possible return values are:

        ============================== ========= ==============================
        Minimize Mode Flag             Hex Value Description
        ============================== ========= ==============================
        ``AUI_MINIMIZE_POS_SMART``          0x01 Minimizes the pane on the closest tool bar
        ``AUI_MINIMIZE_POS_TOP``            0x02 Minimizes the pane on the top tool bar
        ``AUI_MINIMIZE_POS_LEFT``           0x03 Minimizes the pane on its left tool bar
        ``AUI_MINIMIZE_POS_RIGHT``          0x04 Minimizes the pane on its right tool bar
        ``AUI_MINIMIZE_POS_BOTTOM``         0x05 Minimizes the pane on its bottom tool bar
        ``AUI_MINIMIZE_POS_TOOLBAR``        0x06 Minimizes the pane on a target L{AuiToolBar}
        ``AUI_MINIMIZE_POS_MASK``           0x17 Mask to filter the position flags
        ``AUI_MINIMIZE_CAPT_HIDE``           0x0 Hides the caption of the minimized pane
        ``AUI_MINIMIZE_CAPT_SMART``         0x08 Displays the caption in the best rotation (horizontal or clockwise)
        ``AUI_MINIMIZE_CAPT_HORZ``          0x10 Displays the caption horizontally
        ``AUI_MINIMIZE_CAPT_MASK``          0x18 Mask to filter the caption flags
        ============================== ========= ==============================

        The flags can be filtered with the following masks:

        ============================== ========= ==============================
        Minimize Mask Flag             Hex Value Description
        ============================== ========= ==============================
        ``AUI_MINIMIZE_POS_MASK``           0x17 Filters the position flags
        ``AUI_MINIMIZE_CAPT_MASK``          0x18 Filters the caption flags
        ============================== ========= ==============================

        """

        return self.minimize_mode

[docs]    def HasPinButton(self):
        """ Returns ``True`` if the pane displays a button to float the pane. """

        return self.HasFlag(self.buttonPin)

[docs]    def HasGripperTop(self):
        """ Returns ``True`` if the pane displays a gripper at the top. """

        return self.HasFlag(self.optionGripperTop)

[docs]    def Window(self, w):
        """
        Associate a `wx.Window` derived window to this pane.

        This normally does not need to be specified, as the window pointer is
        automatically assigned to the L{AuiPaneInfo} structure as soon as it is
        added to the manager.

        :param `w`: a `wx.Window` derived window.
        """

        self.window = w
        return self

[docs]    def Name(self, name):
        """
        Sets the name of the pane so it can be referenced in lookup functions.

        If a name is not specified by the user, a random name is assigned to the pane
        when it is added to the manager.

        :param `name`: a string specifying the pane name.

        :warning: If you are using L{AuiManager.SavePerspective} and L{AuiManager.LoadPerspective}, you will have
         to specify a name for your pane using L{Name}, as randomly generated names can
         not be properly restored.
        """

        self.name = name
        return self

[docs]    def Caption(self, caption):
        """
        Sets the caption of the pane.

        :param `caption`: a string specifying the pane caption.
        """

        self.caption = caption
        return self

[docs]    def Left(self):
        """
        Sets the pane dock position to the left side of the frame.

        :note: This is the same thing as calling L{Direction} with ``AUI_DOCK_LEFT`` as
         parameter.
        """

        self.dock_direction = AUI_DOCK_LEFT
        return self

[docs]    def Right(self):
        """
        Sets the pane dock position to the right side of the frame.

        :note: This is the same thing as calling L{Direction} with ``AUI_DOCK_RIGHT`` as
         parameter.
        """

        self.dock_direction = AUI_DOCK_RIGHT
        return self

[docs]    def Top(self):
        """
        Sets the pane dock position to the top of the frame.

        :note: This is the same thing as calling L{Direction} with ``AUI_DOCK_TOP`` as
         parameter.
        """

        self.dock_direction = AUI_DOCK_TOP
        return self

[docs]    def Bottom(self):
        """
        Sets the pane dock position to the bottom of the frame.

        :note: This is the same thing as calling L{Direction} with ``AUI_DOCK_BOTTOM`` as
         parameter.
        """

        self.dock_direction = AUI_DOCK_BOTTOM
        return self

[docs]    def Center(self):
        """
        Sets the pane to the center position of the frame.

        The centre pane is the space in the middle after all border panes (left, top,
        right, bottom) are subtracted from the layout.

        :note: This is the same thing as calling L{Direction} with ``AUI_DOCK_CENTER`` as
         parameter.
        """

        self.dock_direction = AUI_DOCK_CENTER
        return self

[docs]    def Centre(self):
        """
        Sets the pane to the center position of the frame.

        The centre pane is the space in the middle after all border panes (left, top,
        right, bottom) are subtracted from the layout.

        :note: This is the same thing as calling L{Direction} with ``AUI_DOCK_CENTRE`` as
         parameter.
        """

        self.dock_direction = AUI_DOCK_CENTRE
        return self

[docs]    def Direction(self, direction):
        """
        Determines the direction of the docked pane. It is functionally the
        same as calling L{Left}, L{Right}, L{Top} or L{Bottom}, except that docking direction
        may be specified programmatically via the parameter `direction`.

        :param `direction`: the direction of the docked pane.

        :see: L{dock_direction_set} for a list of valid docking directions.
        """

        self.dock_direction = direction
        return self

[docs]    def Layer(self, layer):
        """
        Determines the layer of the docked pane.

        The dock layer is similar to an onion, the inner-most layer being layer 0. Each
        shell moving in the outward direction has a higher layer number. This allows for
        more complex docking layout formation.

        :param `layer`: the layer of the docked pane.
        """

        self.dock_layer = layer
        return self

[docs]    def Row(self, row):
        """
        Determines the row of the docked pane.

        :param `row`: the row of the docked pane.
        """

        self.dock_row = row
        return self

[docs]    def Position(self, pos):
        """
        Determines the position of the docked pane.

        :param `pos`: the position of the docked pane.
        """

        self.dock_pos = pos
        return self

[docs]    def MinSize(self, arg1=None, arg2=None):
        """
        Sets the minimum size of the pane.

        This method is split in 2 versions depending on the input type. If `arg1` is
        a `wx.Size` object, then L{MinSize1} is called. Otherwise, L{MinSize2} is called.

        :param `arg1`: a `wx.Size` object, a (x, y) tuple or or a `x` coordinate.
        :param `arg2`: a `y` coordinate (only if `arg1` is a `x` coordinate, otherwise unused).
        """

        if isinstance(arg1, wx.Size):
            ret = self.MinSize1(arg1)
        elif isinstance(arg1, types.TupleType):
            ret = self.MinSize1(wx.Size(*arg1))
        elif isinstance(arg1, types.IntType) and arg2 is not None:
            ret = self.MinSize2(arg1, arg2)
        else:
            raise Exception("Invalid argument passed to `MinSize`: arg1=%s, arg2=%s"%(repr(arg1), repr(arg2)))

        return ret

[docs]    def MinSize1(self, size):
        """
        Sets the minimum size of the pane.

        :see: L{MinSize} for an explanation of input parameters.
        """
        self.min_size = size
        return self

[docs]    def MinSize2(self, x, y):
        """
        Sets the minimum size of the pane.

        :see: L{MinSize} for an explanation of input parameters.
        """

        self.min_size = wx.Size(x, y)
        return self

[docs]    def MaxSize(self, arg1=None, arg2=None):
        """
        Sets the maximum size of the pane.

        This method is split in 2 versions depending on the input type. If `arg1` is
        a `wx.Size` object, then L{MaxSize1} is called. Otherwise, L{MaxSize2} is called.

        :param `arg1`: a `wx.Size` object, a (x, y) tuple or a `x` coordinate.
        :param `arg2`: a `y` coordinate (only if `arg1` is a `x` coordinate, otherwise unused).
        """

        if isinstance(arg1, wx.Size):
            ret = self.MaxSize1(arg1)
        elif isinstance(arg1, types.TupleType):
            ret = self.MaxSize1(wx.Size(*arg1))
        elif isinstance(arg1, types.IntType) and arg2 is not None:
            ret = self.MaxSize2(arg1, arg2)
        else:
            raise Exception("Invalid argument passed to `MaxSize`: arg1=%s, arg2=%s"%(repr(arg1), repr(arg2)))

        return ret

[docs]    def MaxSize1(self, size):
        """
        Sets the maximum size of the pane.

        :see: L{MaxSize} for an explanation of input parameters.
        """

        self.max_size = size
        return self

[docs]    def MaxSize2(self, x, y):
        """
        Sets the maximum size of the pane.

        :see: L{MaxSize} for an explanation of input parameters.
        """

        self.max_size.Set(x,y)
        return self

[docs]    def BestSize(self, arg1=None, arg2=None):
        """
        Sets the ideal size for the pane. The docking manager will attempt to use
        this size as much as possible when docking or floating the pane.

        This method is split in 2 versions depending on the input type. If `arg1` is
        a `wx.Size` object, then L{BestSize1} is called. Otherwise, L{BestSize2} is called.

        :param `arg1`: a `wx.Size` object, a (x, y) tuple or a `x` coordinate.
        :param `arg2`: a `y` coordinate (only if `arg1` is a `x` coordinate, otherwise unused).
        """

        if isinstance(arg1, wx.Size):
            ret = self.BestSize1(arg1)
        elif isinstance(arg1, types.TupleType):
            ret = self.BestSize1(wx.Size(*arg1))
        elif isinstance(arg1, types.IntType) and arg2 is not None:
            ret = self.BestSize2(arg1, arg2)
        else:
            raise Exception("Invalid argument passed to `BestSize`: arg1=%s, arg2=%s"%(repr(arg1), repr(arg2)))

        return ret

[docs]    def BestSize1(self, size):
        """
        Sets the best size of the pane.

        :see: L{BestSize} for an explanation of input parameters.
        """

        self.best_size = size
        return self

[docs]    def BestSize2(self, x, y):
        """
        Sets the best size of the pane.

        :see: L{BestSize} for an explanation of input parameters.
        """

        self.best_size.Set(x,y)
        return self

[docs]    def FloatingPosition(self, pos):
        """
        Sets the position of the floating pane.

        :param `pos`: a `wx.Point` or a tuple indicating the pane floating position.
        """

        self.floating_pos = wx.Point(*pos)
        return self

[docs]    def FloatingSize(self, size):
        """
        Sets the size of the floating pane.

        :param `size`: a `wx.Size` or a tuple indicating the pane floating size.
        """

        self.floating_size = wx.Size(*size)
        return self

[docs]    def Maximize(self):
        """ Makes the pane take up the full area."""

        return self.SetFlag(self.optionMaximized, True)

[docs]    def Minimize(self):
        """
        Makes the pane minimized in a L{AuiToolBar}.

        Clicking on the minimize button causes a new L{AuiToolBar} to be created
        and added to the frame manager, (currently the implementation is such that
        panes at West will have a toolbar at the right, panes at South will have
        toolbars at the bottom etc...) and the pane is hidden in the manager.

        Clicking on the restore button on the newly created toolbar will result in the
        toolbar being removed and the original pane being restored.
        """

        return self.SetFlag(self.optionMinimized, True)

[docs]    def MinimizeMode(self, mode):
        """
        Sets the expected minimized mode if the MinimizeButton() is visible.

        The minimized pane can have a specific position in the work space:

        ============================== ========= ==============================
        Minimize Mode Flag             Hex Value Description
        ============================== ========= ==============================
        ``AUI_MINIMIZE_POS_SMART``          0x01 Minimizes the pane on the closest tool bar
        ``AUI_MINIMIZE_POS_TOP``            0x02 Minimizes the pane on the top tool bar
        ``AUI_MINIMIZE_POS_LEFT``           0x03 Minimizes the pane on its left tool bar
        ``AUI_MINIMIZE_POS_RIGHT``          0x04 Minimizes the pane on its right tool bar
        ``AUI_MINIMIZE_POS_BOTTOM``         0x05 Minimizes the pane on its bottom tool bar
        ``AUI_MINIMIZE_POS_TOOLBAR``        0x06 Minimizes the pane on a target L{AuiToolBar}
        ============================== ========= ==============================

        The caption of the minimized pane can be displayed in different modes:

        ============================== ========= ==============================
        Caption Mode Flag              Hex Value Description
        ============================== ========= ==============================
        ``AUI_MINIMIZE_CAPT_HIDE``           0x0 Hides the caption of the minimized pane
        ``AUI_MINIMIZE_CAPT_SMART``         0x08 Displays the caption in the best rotation (horizontal in the top and in the bottom tool bar or clockwise in the right and in the left tool bar)
        ``AUI_MINIMIZE_CAPT_HORZ``          0x10 Displays the caption horizontally
        ============================== ========= ==============================

        :note: In order to use the ``AUI_MINIMIZE_POS_TOOLBAR`` flag, the instance of L{AuiPaneInfo}
         you pass as an input for L{MinimizeTarget} **must** have a real name and not the randomly
         generated one. Remember to set the L{Name} property of the toolbar pane before calling this method.
        """

        self.minimize_mode = mode
        return self

[docs]    def MinimizeTarget(self, toolbarPane):
        """
        Minimizes the panes using a L{AuiPaneInfo} as a target. As L{AuiPaneInfo} properties
        need to be copied back and forth every time the perspective has changed, we
        only store the toobar **name**.

        :param `toolbarPane`: an instance of L{AuiPaneInfo}, containing a L{AuiToolBar}.

        :note: In order to use this functionality (and with the ``AUI_MINIMIZE_POS_TOOLBAR``
         flag set), the instance of L{AuiPaneInfo} you pass as an input **must** have a real
         name and not the randomly generated one. Remember to set the L{Name} property of
         the toolbar pane before calling this method.
        """

        self.minimize_target = toolbarPane.name
        return self

[docs]    def Restore(self):
        """ Is the reverse of L{Maximize} and L{Minimize}."""

        return self.SetFlag(self.optionMaximized or self.optionMinimized, False)

[docs]    def Fixed(self):
        """
        Forces a pane to be fixed size so that it cannot be resized.
        After calling L{Fixed}, L{IsFixed} will return ``True``.
        """

        return self.SetFlag(self.optionResizable, False)

[docs]    def Resizable(self, resizable=True):
        """
        Allows a pane to be resizable if `resizable` is ``True``, and forces
        it to be a fixed size if `resizeable` is ``False``.

        If `resizable` is ``False``, this is simply an antonym for L{Fixed}.

        :param `resizable`: whether the pane will be resizeable or not.
        """

        return self.SetFlag(self.optionResizable, resizable)

[docs]    def Transparent(self, alpha):
        """
        Makes the pane transparent when floating.

        :param `alpha`: an integer value between 0 and 255 for pane transparency.
        """

        if alpha < 0 or alpha > 255:
            raise Exception("Invalid transparency value (%s)"%repr(alpha))

        self.transparent = alpha
        self.needsTransparency = True

[docs]    def Dock(self):
        """
        Indicates that a pane should be docked. It is the opposite of L{Float}.
        """

        if self.IsNotebookPage():
            self.notebook_id = -1
            self.dock_direction = AUI_DOCK_NONE

        return self.SetFlag(self.optionFloating, False)

[docs]    def Float(self):
        """
        Indicates that a pane should be floated. It is the opposite of L{Dock}.
        """

        if self.IsNotebookPage():
            self.notebook_id = -1
            self.dock_direction = AUI_DOCK_NONE

        return self.SetFlag(self.optionFloating, True)

[docs]    def Hide(self):
        """
        Indicates that a pane should be hidden.

        Calling L{Show} (``False``) achieve the same effect.
        """

        return self.SetFlag(self.optionHidden, True)

[docs]    def Show(self, show=True):
        """
        Indicates that a pane should be shown.

        :param `show`: whether the pane should be shown or not.
        """

        return self.SetFlag(self.optionHidden, not show)

    # By defaulting to 1000, the tab will get placed at the end

[docs]    def NotebookPage(self, id, tab_position=1000):
        """
        Forces a pane to be a notebook page, so that the pane can be
        docked on top to another to create a L{AuiNotebook}.

        :param `id`: the notebook id;
        :param `tab_position`: the tab number of the pane once docked in a notebook.
        """

        # Remove any floating frame
        self.Dock()
        self.notebook_id = id
        self.dock_pos = tab_position
        self.dock_row = 0
        self.dock_layer = 0
        self.dock_direction = AUI_DOCK_NOTEBOOK_PAGE

        return self

[docs]    def NotebookControl(self, id):
        """
        Forces a pane to be a notebook control (L{AuiNotebook}).

        :param `id`: the notebook id.
        """

        self.notebook_id = id
        self.window = None
        self.buttons = []

        if self.dock_direction == AUI_DOCK_NOTEBOOK_PAGE:
            self.dock_direction = AUI_DOCK_NONE

        return self

[docs]    def HasNotebook(self):
        """ Returns whether a pane has a L{AuiNotebook} or not. """

        return self.notebook_id >= 0

[docs]    def IsNotebookPage(self):
        """ Returns whether the pane is a notebook page in a L{AuiNotebook}. """

        return self.notebook_id >= 0 and self.dock_direction == AUI_DOCK_NOTEBOOK_PAGE

[docs]    def IsNotebookControl(self):
        """ Returns whether the pane is a notebook control (L{AuiNotebook}). """

        return not self.IsNotebookPage() and self.HasNotebook()

[docs]    def SetNameFromNotebookId(self):
        """ Sets the pane name once docked in a L{AuiNotebook} using the notebook id. """

        if self.notebook_id >= 0:
            self.name = "__notebook_%d"%self.notebook_id

        return self

[docs]    def CaptionVisible(self, visible=True, left=False):
        """
        Indicates that a pane caption should be visible. If `visible` is ``False``, no pane
        caption is drawn.

        :param `visible`: whether the caption should be visible or not;
        :param `left`: whether the caption should be drawn on the left (rotated by 90 degrees) or not.
        """

        if left:
            self.SetFlag(self.optionCaption, False)
            return self.SetFlag(self.optionCaptionLeft, visible)

        self.SetFlag(self.optionCaptionLeft, False)
        return self.SetFlag(self.optionCaption, visible)

[docs]    def PaneBorder(self, visible=True):
        """
        Indicates that a border should be drawn for the pane.

        :param `visible`: whether the pane border should be visible or not.
        """

        return self.SetFlag(self.optionPaneBorder, visible)

[docs]    def Gripper(self, visible=True):
        """
        Indicates that a gripper should be drawn for the pane.

        :param `visible`: whether the gripper should be visible or not.
        """

        return self.SetFlag(self.optionGripper, visible)

[docs]    def GripperTop(self, attop=True):
        """
        Indicates that a gripper should be drawn at the top of the pane.

        :param `attop`: whether the gripper should be drawn at the top or not.
        """

        return self.SetFlag(self.optionGripperTop, attop)

[docs]    def CloseButton(self, visible=True):
        """
        Indicates that a close button should be drawn for the pane.

        :param `visible`: whether the close button should be visible or not.
        """

        return self.SetFlag(self.buttonClose, visible)

[docs]    def MaximizeButton(self, visible=True):
        """
        Indicates that a maximize button should be drawn for the pane.

        :param `visible`: whether the maximize button should be visible or not.
        """

        return self.SetFlag(self.buttonMaximize, visible)

[docs]    def MinimizeButton(self, visible=True):
        """
        Indicates that a minimize button should be drawn for the pane.

        :param `visible`: whether the minimize button should be visible or not.
        """

        return self.SetFlag(self.buttonMinimize, visible)

[docs]    def PinButton(self, visible=True):
        """
        Indicates that a pin button should be drawn for the pane.

        :param `visible`: whether the pin button should be visible or not.
        """

        return self.SetFlag(self.buttonPin, visible)

[docs]    def DestroyOnClose(self, b=True):
        """
        Indicates whether a pane should be destroyed when it is closed.

        Normally a pane is simply hidden when the close button is clicked. Setting
        `b` to ``True`` will cause the window to be destroyed when the user clicks
        the pane's close button.

        :param `b`: whether the pane should be destroyed when it is closed or not.
        """

        return self.SetFlag(self.optionDestroyOnClose, b)

[docs]    def TopDockable(self, b=True):
        """
        Indicates whether a pane can be docked at the top of the frame.

        :param `b`: whether the pane can be docked at the top or not.
        """

        return self.SetFlag(self.optionTopDockable, b)

[docs]    def BottomDockable(self, b=True):
        """
        Indicates whether a pane can be docked at the bottom of the frame.

        :param `b`: whether the pane can be docked at the bottom or not.
        """

        return self.SetFlag(self.optionBottomDockable, b)

[docs]    def LeftDockable(self, b=True):
        """
        Indicates whether a pane can be docked on the left of the frame.

        :param `b`: whether the pane can be docked at the left or not.
        """

        return self.SetFlag(self.optionLeftDockable, b)

[docs]    def RightDockable(self, b=True):
        """
        Indicates whether a pane can be docked on the right of the frame.

        :param `b`: whether the pane can be docked at the right or not.
        """

        return self.SetFlag(self.optionRightDockable, b)

[docs]    def Floatable(self, b=True):
        """
        Sets whether the user will be able to undock a pane and turn it
        into a floating window.

        :param `b`: whether the pane can be floated or not.
        """

        return self.SetFlag(self.optionFloatable, b)

[docs]    def Movable(self, b=True):
        """
        Indicates whether a pane can be moved.

        :param `b`: whether the pane can be moved or not.
        """

        return self.SetFlag(self.optionMovable, b)

[docs]    def NotebookDockable(self, b=True):
        """
        Indicates whether a pane can be docked in an automatic L{AuiNotebook}.

        :param `b`: whether the pane can be docked in a notebook or not.
        """

        return self.SetFlag(self.optionNotebookDockable, b)

[docs]    def DockFixed(self, b=True):
        """
        Causes the containing dock to have no resize sash. This is useful
        for creating panes that span the entire width or height of a dock, but should
        not be resizable in the other direction.

        :param `b`: whether the pane will have a resize sash or not.
        """

        return self.SetFlag(self.optionDockFixed, b)

[docs]    def Dockable(self, b=True):
        """
        Specifies whether a frame can be docked or not. It is the same as specifying
        L{TopDockable} . L{BottomDockable} . L{LeftDockable} . L{RightDockable} .

        :param `b`: whether the frame can be docked or not.
        """

        return self.TopDockable(b).BottomDockable(b).LeftDockable(b).RightDockable(b)

[docs]    def TopSnappable(self, b=True):
        """
        Indicates whether a pane can be snapped at the top of the main frame.

        :param `b`: whether the pane can be snapped at the top of the main frame or not.
        """

        return self.SetFlag(self.optionTopSnapped, b)

[docs]    def BottomSnappable(self, b=True):
        """
        Indicates whether a pane can be snapped at the bottom of the main frame.

        :param `b`: whether the pane can be snapped at the bottom of the main frame or not.
        """

        return self.SetFlag(self.optionBottomSnapped, b)

[docs]    def LeftSnappable(self, b=True):
        """
        Indicates whether a pane can be snapped on the left of the main frame.

        :param `b`: whether the pane can be snapped at the left of the main frame or not.
        """

        return self.SetFlag(self.optionLeftSnapped, b)

[docs]    def RightSnappable(self, b=True):
        """
        Indicates whether a pane can be snapped on the right of the main frame.

        :param `b`: whether the pane can be snapped at the right of the main frame or not.
        """

        return self.SetFlag(self.optionRightSnapped, b)

[docs]    def Snappable(self, b=True):
        """
        Indicates whether a pane can be snapped on the main frame. This is
        equivalent as calling L{TopSnappable} . L{BottomSnappable} . L{LeftSnappable} . L{RightSnappable} .

        :param `b`: whether the pane can be snapped on the main frame or not.
        """

        return self.TopSnappable(b).BottomSnappable(b).LeftSnappable(b).RightSnappable(b)

[docs]    def FlyOut(self, b=True):
        """
        Indicates whether a pane, when floating, has a "fly-out" effect
        (i.e., floating panes which only show themselves when moused over).

        :param `b`: whether the pane can be snapped on the main frame or not.
        """

        return self.SetFlag(self.optionFlyOut, b)

    # Copy over the members that pertain to docking position

[docs]    def SetDockPos(self, source):
        """
        Copies the `source` pane members that pertain to docking position to `self`.

        :param `source`: the source pane from where to copy the attributes.
        """

        self.dock_direction = source.dock_direction
        self.dock_layer = source.dock_layer
        self.dock_row = source.dock_row
        self.dock_pos = source.dock_pos
        self.dock_proportion = source.dock_proportion
        self.floating_pos = wx.Point(*source.floating_pos)
        self.floating_size = wx.Size(*source.floating_size)
        self.rect = wx.Rect(*source.rect)

        return self

[docs]    def DefaultPane(self):
        """ Specifies that the pane should adopt the default pane settings. """

        state = self.state
        state |= self.optionTopDockable | self.optionBottomDockable | \
                 self.optionLeftDockable | self.optionRightDockable | \
                 self.optionNotebookDockable | \
                 self.optionFloatable | self.optionMovable | self.optionResizable | \
                 self.optionCaption | self.optionPaneBorder | self.buttonClose

        self.state = state
        return self

[docs]    def CentrePane(self):
        """
        Specifies that the pane should adopt the default center pane settings.

        Centre panes usually do not have caption bars. This function provides an easy way of
        preparing a pane to be displayed in the center dock position.
        """

        return self.CenterPane()

[docs]    def CenterPane(self):
        """
        Specifies that the pane should adopt the default center pane settings.

        Centre panes usually do not have caption bars. This function provides an easy way of
        preparing a pane to be displayed in the center dock position.
        """

        self.state = 0
        return self.Center().PaneBorder().Resizable()

[docs]    def ToolbarPane(self):
        """ Specifies that the pane should adopt the default toolbar pane settings. """

        self.DefaultPane()
        state = self.state

        state |= (self.optionToolbar | self.optionGripper)
        state &= ~(self.optionResizable | self.optionCaption | self.optionCaptionLeft)

        if self.dock_layer == 0:
            self.dock_layer = 10

        self.state = state

        return self

[docs]    def Icon(self, icon):
        """
        Specifies whether an icon is drawn on the left of the caption text when
        the pane is docked. If `icon` is ``None`` or `wx.NullIcon`, no icon is drawn on
        the caption space.

        :param icon: an icon to draw on the caption space, or ``None``.
        """

        if icon is None:
            icon = wx.NullIcon

        self.icon = icon
        return self

[docs]    def SetFlag(self, flag, option_state):
        """
        Turns the property given by `flag` on or off with the `option_state`
        parameter.

        :param `flag`: the property to set;
        :param `option_state`: either ``True`` or ``False``.
        """

        state = self.state

        if option_state:
            state |= flag
        else:
            state &= ~flag

        self.state = state

        if flag in [self.buttonClose, self.buttonMaximize, self.buttonMinimize, self.buttonPin]:
            self.ResetButtons()

        return self

[docs]    def HasFlag(self, flag):
        """
        Returns ``True`` if the the property specified by flag is active for the pane.

        :param `flag`: the property to check for activity.
        """

        return (self.state & flag and [True] or [False])[0]

[docs]    def ResetButtons(self):
        """
        Resets all the buttons and recreates them from scratch depending on the
        L{AuiPaneInfo} flags.
        """

        floating = self.HasFlag(self.optionFloating)
        self.buttons = []

        if not floating and self.HasMinimizeButton():
            button = AuiPaneButton(AUI_BUTTON_MINIMIZE)
            self.buttons.append(button)

        if not floating and self.HasMaximizeButton():
            button = AuiPaneButton(AUI_BUTTON_MAXIMIZE_RESTORE)
            self.buttons.append(button)

        if not floating and self.HasPinButton():
            button = AuiPaneButton(AUI_BUTTON_PIN)
            self.buttons.append(button)

        if self.HasCloseButton():
            button = AuiPaneButton(AUI_BUTTON_CLOSE)
            self.buttons.append(button)

[docs]    def CountButtons(self):
        """ Returns the number of visible buttons in the docked pane. """

        n = 0

        if self.HasCaption() or self.HasCaptionLeft():
            if isinstance(wx.GetTopLevelParent(self.window), AuiFloatingFrame):
                return 1

            if self.HasCloseButton():
                n += 1
            if self.HasMaximizeButton():
                n += 1
            if self.HasMinimizeButton():
                n += 1
            if self.HasPinButton():
                n += 1

        return n

[docs]    def IsHorizontal(self):
        """ Returns ``True`` if the pane `dock_direction` is horizontal. """

        return self.dock_direction in [AUI_DOCK_TOP, AUI_DOCK_BOTTOM]

[docs]    def IsVertical(self):
        """ Returns ``True`` if the pane `dock_direction` is vertical. """

        return self.dock_direction in [AUI_DOCK_LEFT, AUI_DOCK_RIGHT]

# Null AuiPaneInfo reference

NonePaneInfo = AuiPaneInfo()

# ---------------------------------------------------------------------------- #

[docs]class AuiDockingGuide(wx.Frame):
    """ Base class for L{AuiCenterDockingGuide} and L{AuiSingleDockingGuide}."""

[docs]    def __init__(self, parent, id=wx.ID_ANY, title="", pos=wx.DefaultPosition,
                 size=wx.DefaultSize, style=wx.FRAME_TOOL_WINDOW | wx.STAY_ON_TOP |
                 wx.FRAME_NO_TASKBAR | wx.NO_BORDER, name="AuiDockingGuide"):
        """
        Default class constructor. Used internally, do not call it in your code!

        :param `parent`: the L{AuiDockingGuide} parent;
        :param `id`: the window identifier. It may take a value of -1 to indicate a default value.
        :param `title`: the caption to be displayed on the frame's title bar.
        :param `pos`: the window position. A value of (-1, -1) indicates a default position,
         chosen by either the windowing system or wxPython, depending on platform.
        :param `size`: the window size. A value of (-1, -1) indicates a default size, chosen by
         either the windowing system or wxPython, depending on platform.
        :param `style`: the window style.
        :param `name`: the name of the window. This parameter is used to associate a name with the
         item, allowing the application user to set Motif resource values for individual windows.
        """

        wx.Frame.__init__(self, parent, id, title, pos, size, style, name=name)

[docs]    def HitTest(self, x, y):
        """
        To be overridden by parent classes.

        :param `x`: the `x` mouse position;
        :param `y`: the `y` mouse position.
        """

        return 0

[docs]    def ValidateNotebookDocking(self, valid):
        """
        To be overridden by parent classes.

        :param `valid`: whether a pane can be docked on top to another to form an automatic
         L{AuiNotebook}.
        """

        return 0

# ============================================================================
# implementation
# ============================================================================

# ---------------------------------------------------------------------------
# AuiDockingGuideWindow
# ---------------------------------------------------------------------------

[docs]class AuiDockingGuideWindow(wx.Window):
    """ Target class for L{AuiSingleDockingGuide} and L{AuiCenterDockingGuide}. """

[docs]    def __init__(self, parent, rect, direction=0, center=False, useAero=False):
        """
        Default class constructor. Used internally, do not call it in your code!

        :param `parent`: the L{AuiDockingGuideWindow} parent;
        :param `rect`: the window rect;
        :param `direction`: one of ``wx.TOP``, ``wx.BOTTOM``, ``wx.LEFT``, ``wx.RIGHT``,
         ``wx.CENTER``;
        :param `center`: whether the calling class is a L{AuiCenterDockingGuide};
        :param `useAero`: whether to use the new Aero-style bitmaps or Whidbey-style bitmaps
         for the docking guide.
        """

        wx.Window.__init__(self, parent, -1, rect.GetPosition(), rect.GetSize(), wx.NO_BORDER)

        self._direction = direction
        self._center = center
        self._valid = True
        self._useAero = useAero

        self._bmp_unfocus, self._bmp_focus = GetDockingImage(direction, useAero, center)

        self._currentImage = self._bmp_unfocus
        self.SetBackgroundStyle(wx.BG_STYLE_CUSTOM)

        self.Bind(wx.EVT_ERASE_BACKGROUND, self.OnEraseBackground)
        self.Bind(wx.EVT_PAINT, self.OnPaint)

[docs]    def SetValid(self, valid):
        """
        Sets the docking direction as valid or invalid.

        :param `valid`: whether the docking direction is allowed or not.
        """

        self._valid = valid

[docs]    def IsValid(self):
        """ Returns whether the docking direction is valid. """

        return self._valid

[docs]    def OnEraseBackground(self, event):
        """
        Handles the ``wx.EVT_ERASE_BACKGROUND`` event for L{AuiDockingGuideWindow}.

        :param `event`: a `wx.EraseEvent` to be processed.

        :note: This is intentionally empty to reduce flickering while drawing.
        """

        pass

[docs]    def DrawBackground(self, dc):
        """
        Draws the docking guide background.

        :param `dc`: a `wx.DC` device context object.
        """

        rect = self.GetClientRect()

        dc.SetPen(wx.TRANSPARENT_PEN)
        dc.SetBrush(wx.Brush(colourTargetBackground))
        dc.DrawRectangleRect(rect)

        dc.SetPen(wx.Pen(colourTargetBorder))

        left = rect.GetLeft()
        top = rect.GetTop()
        right = rect.GetRight()
        bottom = rect.GetBottom()

        if self._direction != wx.CENTER:

            if not self._center or self._direction != wx.BOTTOM:
                dc.DrawLine(left, top, right+1, top)
            if not self._center or self._direction != wx.RIGHT:
                dc.DrawLine(left, top, left, bottom+1)
            if not self._center or self._direction != wx.LEFT:
                dc.DrawLine(right, top, right, bottom+1)
            if not self._center or self._direction != wx.TOP:
                dc.DrawLine(left, bottom, right+1, bottom)

            dc.SetPen(wx.Pen(colourTargetShade))

            if self._direction != wx.RIGHT:
                dc.DrawLine(left + 1, top + 1, left + 1, bottom)
            if self._direction != wx.BOTTOM:
                dc.DrawLine(left + 1, top + 1, right, top + 1)

[docs]    def DrawDottedLine(self, dc, point, length, vertical):
        """
        Draws a dotted line (not used if the docking guide images are ok).

        :param `dc`: a `wx.DC` device context object;
        :param `point`: a `wx.Point` where to start drawing the dotted line;
        :param `length`: the length of the dotted line;
        :param `vertical`: whether it is a vertical docking guide window or not.
        """

        for i in xrange(0, length, 2):
            dc.DrawPoint(point.x, point.y)
            if vertical:
                point.y += 2
            else:
                point.x += 2

[docs]    def DrawIcon(self, dc):
        """
        Draws the docking guide icon (not used if the docking guide images are ok).

        :param `dc`: a `wx.DC` device context object.
        """

        rect = wx.Rect(*self.GetClientRect())
        point = wx.Point()
        length = 0

        rect.Deflate(4, 4)
        dc.SetPen(wx.Pen(colourIconBorder))
        dc.SetBrush(wx.Brush(colourIconBackground))
        dc.DrawRectangleRect(rect)

        right1 = rect.GetRight() + 1
        bottom1 = rect.GetBottom() + 1

        dc.SetPen(wx.Pen(colourIconShadow))
        dc.DrawLine(rect.x + 1, bottom1, right1 + 1, bottom1)
        dc.DrawLine(right1, rect.y + 1, right1, bottom1 + 1)

        rect.Deflate(1, 1)

        if self._direction == wx.TOP:
            rect.height -= rect.height / 2
            point = rect.GetBottomLeft()
            length = rect.width

        elif self._direction == wx.LEFT:
            rect.width -= rect.width / 2
            point = rect.GetTopRight()
            length = rect.height

        elif self._direction == wx.RIGHT:
            rect.x += rect.width / 2
            rect.width -= rect.width / 2
            point = rect.GetTopLeft()
            length = rect.height

        elif self._direction == wx.BOTTOM:
            rect.y += rect.height / 2
            rect.height -= rect.height / 2
            point = rect.GetTopLeft()
            length = rect.width

        elif self._direction == wx.CENTER:
            rect.Deflate(1, 1)
            point = rect.GetTopLeft()
            length = rect.width

        dc.GradientFillLinear(rect, colourIconDockingPart1,
                              colourIconDockingPart2, self._direction)

        dc.SetPen(wx.Pen(colourIconBorder))

        if self._direction == wx.CENTER:
            self.DrawDottedLine(dc, rect.GetTopLeft(), rect.width, False)
            self.DrawDottedLine(dc, rect.GetTopLeft(), rect.height, True)
            self.DrawDottedLine(dc, rect.GetBottomLeft(), rect.width, False)
            self.DrawDottedLine(dc, rect.GetTopRight(), rect.height, True)

        elif self._direction in [wx.TOP, wx.BOTTOM]:
            self.DrawDottedLine(dc, point, length, False)

        else:
            self.DrawDottedLine(dc, point, length, True)

[docs]    def DrawArrow(self, dc):
        """
        Draws the docking guide arrow icon (not used if the docking guide images are ok).

        :param `dc`: a `wx.DC` device context object.
        """

        rect = self.GetClientRect()
        point = wx.Point()

        point.x = (rect.GetLeft() + rect.GetRight()) / 2
        point.y = (rect.GetTop() + rect.GetBottom()) / 2
        rx, ry = wx.Size(), wx.Size()

        if self._direction == wx.TOP:
            rx = wx.Size(1, 0)
            ry = wx.Size(0, 1)

        elif self._direction == wx.LEFT:
            rx = wx.Size(0, -1)
            ry = wx.Size(1, 0)

        elif self._direction == wx.RIGHT:
            rx = wx.Size(0, 1)
            ry = wx.Size(-1, 0)

        elif self._direction == wx.BOTTOM:
            rx = wx.Size(-1, 0)
            ry = wx.Size(0, -1)

        point.x += ry.x*3
        point.y += ry.y*3

        dc.SetPen(wx.Pen(colourIconArrow))

        for i in xrange(4):
            pt1 = wx.Point(point.x - rx.x*i, point.y - rx.y*i)
            pt2 = wx.Point(point.x + rx.x*(i+1), point.y + rx.y*(i+1))
            dc.DrawLinePoint(pt1, pt2)
            point.x += ry.x
            point.y += ry.y

[docs]    def OnPaint(self, event):
        """
        Handles the ``wx.EVT_PAINT`` event for L{AuiDockingGuideWindow}.

        :param `event`: a `wx.PaintEvent` to be processed.
        """

        dc = wx.AutoBufferedPaintDC(self)
        if self._currentImage.IsOk() and self._valid:
            dc.DrawBitmap(self._currentImage, 0, 0, True)
        else:
            self.Draw(dc)

[docs]    def Draw(self, dc):
        """
        Draws the whole docking guide window (not used if the docking guide images are ok).

        :param `dc`: a `wx.DC` device context object.
        """

        self.DrawBackground(dc)

        if self._valid:
            self.DrawIcon(dc)
            self.DrawArrow(dc)

[docs]    def UpdateDockGuide(self, pos):
        """
        Updates the docking guide images depending on the mouse position, using focused
        images if the mouse is inside the docking guide or unfocused images if it is
        outside.

        :param `pos`: a `wx.Point` mouse position.
        """

        inside = self.GetScreenRect().Contains(pos)

        if inside:
            image = self._bmp_focus
        else:
            image = self._bmp_unfocus

        if image != self._currentImage:
            self._currentImage = image
            self.Refresh()
            self.Update()

# ---------------------------------------------------------------------------
# AuiSingleDockingGuide
# ---------------------------------------------------------------------------

[docs]class AuiSingleDockingGuide(AuiDockingGuide):
    """ A docking guide window for single docking hint (not diamond-shaped HUD). """

[docs]    def __init__(self, parent, direction=0):
        """
        Default class constructor. Used internally, do not call it in your code!

        :param `parent`: the L{AuiSingleDockingGuide} parent;
        :param `direction`: one of ``wx.TOP``, ``wx.BOTTOM``, ``wx.LEFT``, ``wx.RIGHT``.
        """

        self._direction = direction

        style = wx.FRAME_TOOL_WINDOW | wx.STAY_ON_TOP | \
                wx.FRAME_NO_TASKBAR | wx.NO_BORDER

        # Use of FRAME_SHAPED on wxMac causes the frame to be visible
        # breaking the docking hints.
        if wx.Platform != '__WXMAC__':
            style |= wx.FRAME_SHAPED

        AuiDockingGuide.__init__(self, parent, style=style, name="auiSingleDockTarget")

        self.Hide()

        useAero = GetManager(self.GetParent()).GetAGWFlags() & AUI_MGR_AERO_DOCKING_GUIDES
        useWhidbey = GetManager(self.GetParent()).GetAGWFlags() & AUI_MGR_WHIDBEY_DOCKING_GUIDES

        self._useAero = useAero or useWhidbey
        self._valid = True

        if useAero:
            sizeX, sizeY = aeroguideSizeX, aeroguideSizeY
        elif useWhidbey:
            sizeX, sizeY = whidbeySizeX, whidbeySizeY
        else:
            sizeX, sizeY = guideSizeX, guideSizeY

        if direction not in [wx.TOP, wx.BOTTOM]:
            sizeX, sizeY = sizeY, sizeX

        if self._useAero:
            self.CreateShapesWithStyle(useWhidbey)

            if wx.Platform == "__WXGTK__":
                self.Bind(wx.EVT_WINDOW_CREATE, self.SetGuideShape)
            else:
                self.SetGuideShape()

            self.SetSize(self.region.GetBox().GetSize())
        else:
            self.SetSize((sizeX, sizeY))

        self.rect = wx.Rect(0, 0, sizeX, sizeY)

        if self._useAero:
            useAero = (useWhidbey and [2] or [1])[0]
        else:
            useAero = 0

        self.target = AuiDockingGuideWindow(self, self.rect, direction, False, useAero)

[docs]    def CreateShapesWithStyle(self, useWhidbey):
        """
        Creates the docking guide window shape based on which docking bitmaps are used.

        :param `useWhidbey`: if ``True``, use Whidbey-style bitmaps; if ``False``, use the
         Aero-style bitmaps.
         """

        sizeX, sizeY = aeroguideSizeX, aeroguideSizeY
        if useWhidbey:
            sizeX, sizeY = whidbeySizeX, whidbeySizeY

        if self._direction not in [wx.TOP, wx.BOTTOM]:
            sizeX, sizeY = sizeY, sizeX

        useAero = (useWhidbey and [2] or [1])[0]
        bmp, dummy = GetDockingImage(self._direction, useAero, False)
        region = wx.RegionFromBitmap(bmp)

        self.region = region

[docs]    def AeroMove(self, pos):
        """
        Moves the docking window to the new position. Overridden in children classes.

        :param `pos`: the new docking guide position.
        """

        pass

[docs]    def SetGuideShape(self, event=None):
        """
        Sets the correct shape for the docking guide window.

        :param `event`: on wxGTK, a `wx.WindowCreateEvent` event to process.
        """

        self.SetShape(self.region)

        if event is not None:
            # Skip the event on wxGTK
            event.Skip()
            wx.CallAfter(wx.SafeYield, self, True)

[docs]    def SetShape(self, region):
        """
        If the platform supports it, sets the shape of the window to that depicted by `region`.
        The system will not display or respond to any mouse event for the pixels that lie
        outside of the region. To reset the window to the normal rectangular shape simply call
        L{SetShape} again with an empty region.

        :param `region`: the shape of the frame.

        :note: Overridden for wxMac.
        """

        if wx.Platform == '__WXMAC__':
            # HACK so we don't crash when SetShape is called
            return
        else:
            super(AuiSingleDockingGuide, self).SetShape(region)

[docs]    def SetValid(self, valid):
        """
        Sets the docking direction as valid or invalid.

        :param `valid`: whether the docking direction is allowed or not.
        """

        self._valid = valid

[docs]    def IsValid(self):
        """ Returns whether the docking direction is valid. """

        return self._valid

[docs]    def UpdateDockGuide(self, pos):
        """
        Updates the docking guide images depending on the mouse position, using focused
        images if the mouse is inside the docking guide or unfocused images if it is
        outside.

        :param `pos`: a `wx.Point` mouse position.
        """

        self.target.UpdateDockGuide(pos)

[docs]    def HitTest(self, x, y):
        """
        Checks if the mouse position is inside the target window rect.

        :param `x`: the `x` mouse position;
        :param `y`: the `y` mouse position.
        """

        if self.target.GetScreenRect().Contains((x, y)):
            return wx.ALL

        return -1

# ---------------------------------------------------------------------------
# AuiCenterDockingGuide
# ---------------------------------------------------------------------------

[docs]class AuiCenterDockingGuide(AuiDockingGuide):
    """ A docking guide window for multiple docking hint (diamond-shaped HUD). """

[docs]    def __init__(self, parent):
        """
        Default class constructor.
        Used internally, do not call it in your code!

        :param `parent`: the L{AuiCenterDockingGuide} parent.
        """

        AuiDockingGuide.__init__(self, parent, style=wx.FRAME_TOOL_WINDOW | wx.STAY_ON_TOP |
                                 wx.FRAME_NO_TASKBAR | wx.NO_BORDER | wx.FRAME_SHAPED,
                                 name="auiCenterDockTarget")

        self.Hide()

        self.CreateShapesWithStyle()
        self.SetBackgroundStyle(wx.BG_STYLE_CUSTOM)

        if wx.Platform == "__WXGTK__":
            self.Bind(wx.EVT_WINDOW_CREATE, self.SetGuideShape)
        else:
            self.SetGuideShape()

        self.SetSize(self.region.GetBox().GetSize())

        self.Bind(wx.EVT_ERASE_BACKGROUND, self.OnEraseBackground)
        self.Bind(wx.EVT_PAINT, self.OnPaint)

[docs]    def CreateShapesWithStyle(self):
        """ Creates the docking guide window shape based on which docking bitmaps are used. """

        useAero = (GetManager(self.GetParent()).GetAGWFlags() & AUI_MGR_AERO_DOCKING_GUIDES) != 0
        useWhidbey = (GetManager(self.GetParent()).GetAGWFlags() & AUI_MGR_WHIDBEY_DOCKING_GUIDES) != 0

        self._useAero = 0
        if useAero:
            self._useAero = 1
        elif useWhidbey:
            self._useAero = 2

        if useAero:
            sizeX, sizeY = aeroguideSizeX, aeroguideSizeY
        elif useWhidbey:
            sizeX, sizeY = whidbeySizeX, whidbeySizeY
        else:
            sizeX, sizeY = guideSizeX, guideSizeY

        rectLeft = wx.Rect(0, sizeY, sizeY, sizeX)
        rectTop = wx.Rect(sizeY, 0, sizeX, sizeY)
        rectRight = wx.Rect(sizeY+sizeX, sizeY, sizeY, sizeX)
        rectBottom = wx.Rect(sizeY, sizeX + sizeY, sizeX, sizeY)
        rectCenter = wx.Rect(sizeY, sizeY, sizeX, sizeX)

        if not self._useAero:

            self.targetLeft = AuiDockingGuideWindow(self, rectLeft, wx.LEFT, True, useAero)
            self.targetTop = AuiDockingGuideWindow(self, rectTop, wx.TOP, True, useAero)
            self.targetRight = AuiDockingGuideWindow(self, rectRight, wx.RIGHT, True, useAero)
            self.targetBottom = AuiDockingGuideWindow(self, rectBottom, wx.BOTTOM, True, useAero)
            self.targetCenter = AuiDockingGuideWindow(self, rectCenter, wx.CENTER, True, useAero)

            # top-left diamond
            tld = [wx.Point(rectTop.x, rectTop.y+rectTop.height-8),
                   wx.Point(rectLeft.x+rectLeft.width-8, rectLeft.y),
                   rectTop.GetBottomLeft()]
            # bottom-left diamond
            bld = [wx.Point(rectLeft.x+rectLeft.width-8, rectLeft.y+rectLeft.height),
                   wx.Point(rectBottom.x, rectBottom.y+8),
                   rectBottom.GetTopLeft()]
            # top-right diamond
            trd = [wx.Point(rectTop.x+rectTop.width, rectTop.y+rectTop.height-8),
                   wx.Point(rectRight.x+8, rectRight.y),
                   rectRight.GetTopLeft()]
            # bottom-right diamond
            brd = [wx.Point(rectRight.x+8, rectRight.y+rectRight.height),
                   wx.Point(rectBottom.x+rectBottom.width, rectBottom.y+8),
                   rectBottom.GetTopRight()]

            self._triangles = [tld[0:2], bld[0:2],
                               [wx.Point(rectTop.x+rectTop.width-1, rectTop.y+rectTop.height-8),
                                wx.Point(rectRight.x+7, rectRight.y)],
                               [wx.Point(rectRight.x+7, rectRight.y+rectRight.height),
                                wx.Point(rectBottom.x+rectBottom.width-1, rectBottom.y+8)]]

            region = wx.Region()
            region.UnionRect(rectLeft)
            region.UnionRect(rectTop)
            region.UnionRect(rectRight)
            region.UnionRect(rectBottom)
            region.UnionRect(rectCenter)
            region.UnionRegion(wx.RegionFromPoints(tld))
            region.UnionRegion(wx.RegionFromPoints(bld))
            region.UnionRegion(wx.RegionFromPoints(trd))
            region.UnionRegion(wx.RegionFromPoints(brd))

        elif useAero:

            self._aeroBmp = aero_dock_pane.GetBitmap()
            region = wx.RegionFromBitmap(self._aeroBmp)

            self._allAeroBmps = [aero_dock_pane_left.GetBitmap(), aero_dock_pane_top.GetBitmap(),
                                 aero_dock_pane_right.GetBitmap(), aero_dock_pane_bottom.GetBitmap(),
                                 aero_dock_pane_center.GetBitmap(), aero_dock_pane.GetBitmap()]
            self._deniedBitmap = aero_denied.GetBitmap()
            self._aeroRects = [rectLeft, rectTop, rectRight, rectBottom, rectCenter]
            self._valid = True

        elif useWhidbey:

            self._aeroBmp = whidbey_dock_pane.GetBitmap()
            region = wx.RegionFromBitmap(self._aeroBmp)

            self._allAeroBmps = [whidbey_dock_pane_left.GetBitmap(), whidbey_dock_pane_top.GetBitmap(),
                                 whidbey_dock_pane_right.GetBitmap(), whidbey_dock_pane_bottom.GetBitmap(),
                                 whidbey_dock_pane_center.GetBitmap(), whidbey_dock_pane.GetBitmap()]
            self._deniedBitmap = whidbey_denied.GetBitmap()
            self._aeroRects = [rectLeft, rectTop, rectRight, rectBottom, rectCenter]
            self._valid = True

        self.region = region

[docs]    def SetGuideShape(self, event=None):
        """
        Sets the correct shape for the docking guide window.

        :param `event`: on wxGTK, a `wx.WindowCreateEvent` event to process.
        """

        self.SetShape(self.region)

        if event is not None:
            # Skip the event on wxGTK
            event.Skip()
            wx.CallAfter(wx.SafeYield, self, True)

[docs]    def UpdateDockGuide(self, pos):
        """
        Updates the docking guides images depending on the mouse position, using focused
        images if the mouse is inside the docking guide or unfocused images if it is
        outside.

        :param `pos`: a `wx.Point` mouse position.
        """

        if not self._useAero:
            for target in self.GetChildren():
                target.UpdateDockGuide(pos)
        else:
            lenRects = len(self._aeroRects)
            for indx, rect in enumerate(self._aeroRects):
                if rect.Contains(pos):
                    if self._allAeroBmps[indx] != self._aeroBmp:
                        if indx < lenRects - 1 or (indx == lenRects - 1 and self._valid):
                            self._aeroBmp = self._allAeroBmps[indx]
                            self.Refresh()
                        else:
                            self._aeroBmp = self._allAeroBmps[-1]
                            self.Refresh()

                    return

            if self._aeroBmp != self._allAeroBmps[-1]:
                self._aeroBmp = self._allAeroBmps[-1]
                self.Refresh()

[docs]    def HitTest(self, x, y):
        """
        Checks if the mouse position is inside the target windows rect.

        :param `x`: the `x` mouse position;
        :param `y`: the `y` mouse position.
        """

        if not self._useAero:
            if self.targetLeft.GetScreenRect().Contains((x, y)):
                return wx.LEFT
            if self.targetTop.GetScreenRect().Contains((x, y)):
                return wx.UP
            if self.targetRight.GetScreenRect().Contains((x, y)):
                return wx.RIGHT
            if self.targetBottom.GetScreenRect().Contains((x, y)):
                return wx.DOWN
            if self.targetCenter.IsValid() and self.targetCenter.GetScreenRect().Contains((x, y)):
                return wx.CENTER
        else:
            constants = [wx.LEFT, wx.UP, wx.RIGHT, wx.DOWN, wx.CENTER]
            lenRects = len(self._aeroRects)
            for indx, rect in enumerate(self._aeroRects):
                if rect.Contains((x, y)):
                    if indx < lenRects or (indx == lenRects-1 and self._valid):
                        return constants[indx]

        return -1

[docs]    def ValidateNotebookDocking(self, valid):
        """
        Sets whether a pane can be docked on top of another to create an automatic
        L{AuiNotebook}.

        :param `valid`: whether a pane can be docked on top to another to form an automatic
         L{AuiNotebook}.
        """

        if not self._useAero:
            if self.targetCenter.IsValid() != valid:
                self.targetCenter.SetValid(valid)
                self.targetCenter.Refresh()
        else:
            if self._valid != valid:
                self._valid = valid
                self.Refresh()

[docs]    def AeroMove(self, pos):
        """
        Moves the docking guide window to the new position.

        :param `pos`: the new docking guide position.
        """

        if not self._useAero:
            return

        useWhidbey = (GetManager(self.GetParent()).GetAGWFlags() & AUI_MGR_WHIDBEY_DOCKING_GUIDES) != 0

        if useWhidbey:
            sizeX, sizeY = whidbeySizeX, whidbeySizeY
        else:
            sizeX, sizeY = aeroguideSizeX, aeroguideSizeY

        size = self.GetSize()

        leftRect, topRect, rightRect, bottomRect, centerRect = self._aeroRects
        thePos = pos + wx.Point((size.x-sizeY)/2, (size.y-sizeX)/2)

        centerRect.SetPosition(thePos)

        leftRect.SetPosition(thePos + wx.Point(-sizeY, 0))
        topRect.SetPosition(thePos + wx.Point(0, -sizeY))
        rightRect.SetPosition(thePos + wx.Point(sizeX, 0))
        bottomRect.SetPosition(thePos + wx.Point(0, sizeX))

[docs]    def OnEraseBackground(self, event):
        """
        Handles the ``wx.EVT_ERASE_BACKGROUND`` event for L{AuiCenterDockingGuide}.

        :param `event`: `wx.EraseEvent` to be processed.

        :note: This is intentionally empty to reduce flickering while drawing.
        """

        pass

[docs]    def OnPaint(self, event):
        """
        Handles the ``wx.EVT_PAINT`` event for L{AuiCenterDockingGuide}.

        :param `event`: a `wx.PaintEvent` to be processed.
        """

        dc = wx.AutoBufferedPaintDC(self)

        if self._useAero:
            dc.SetBrush(wx.TRANSPARENT_BRUSH)
            dc.SetPen(wx.TRANSPARENT_PEN)
        else:
            dc.SetBrush(wx.Brush(colourTargetBackground))
            dc.SetPen(wx.Pen(colourTargetBorder))

        rect = self.GetClientRect()
        dc.DrawRectangle(rect.x, rect.y, rect.width, rect.height)

        if self._useAero:
            dc.DrawBitmap(self._aeroBmp, 0, 0, True)
            if not self._valid:
                diff = (self._useAero == 2 and [1] or [0])[0]
                bmpX, bmpY = self._deniedBitmap.GetWidth(), self._deniedBitmap.GetHeight()
                xPos, yPos = (rect.x + (rect.width)/2 - bmpX/2), (rect.y + (rect.height)/2 - bmpY/2)
                dc.DrawBitmap(self._deniedBitmap, xPos+1, yPos+diff, True)

            return

        dc.SetPen(wx.Pen(colourTargetBorder, 2))
        for pts in self._triangles:
            dc.DrawLinePoint(pts[0], pts[1])

# ----------------------------------------------------------------------------
# AuiDockingHintWindow
# ----------------------------------------------------------------------------

[docs]class AuiDockingHintWindow(wx.Frame):
    """ The original wxAUI docking window hint. """

[docs]    def __init__(self, parent, id=wx.ID_ANY, title="", pos=wx.DefaultPosition,
                 size=wx.Size(1, 1), style=wx.FRAME_TOOL_WINDOW | wx.FRAME_FLOAT_ON_PARENT |
                 wx.FRAME_NO_TASKBAR | wx.NO_BORDER | wx.FRAME_SHAPED,
                 name="auiHintWindow"):
        """
        Default class constructor. Used internally, do not call it in your code!

        :param `parent`: the L{AuiDockingGuide} parent;
        :param `id`: the window identifier. It may take a value of -1 to indicate a default value.
        :param `title`: the caption to be displayed on the frame's title bar;
        :param `pos`: the window position. A value of (-1, -1) indicates a default position,
         chosen by either the windowing system or wxPython, depending on platform;
        :param `size`: the window size. A value of (-1, -1) indicates a default size, chosen by
         either the windowing system or wxPython, depending on platform;
        :param `style`: the window style;
        :param `name`: the name of the window. This parameter is used to associate a name with the
         item, allowing the application user to set Motif resource values for individual windows.
        """
        if wx.Platform == '__WXMAC__' and style & wx.FRAME_SHAPED:
            # Having the shaped frame causes the frame to not be visible
            # with the transparent style hints.
            style -= wx.FRAME_SHAPED

        wx.Frame.__init__(self, parent, id, title, pos, size, style, name=name)

        self._blindMode = False
        self.SetBackgroundColour(colourHintBackground)

        # Can't set background colour on a frame on wxMac
        # so add a panel to set the colour on.
        if wx.Platform == '__WXMAC__':
            sizer = wx.BoxSizer(wx.HORIZONTAL)
            self.panel = wx.Panel(self)
            sizer.Add(self.panel, 1, wx.EXPAND)
            self.SetSizer(sizer)
            self.panel.SetBackgroundColour(colourHintBackground)

        self.Bind(wx.EVT_SIZE, self.OnSize)

[docs]    def MakeVenetianBlinds(self):
        """
        Creates the "venetian blind" effect if L{AuiManager} has the ``AUI_MGR_VENETIAN_BLINDS_HINT``
        flag set.
        """

        amount = 128
        size = self.GetClientSize()
        region = wx.Region(0, 0, size.x, 1)

        for y in xrange(size.y):

            # Reverse the order of the bottom 4 bits
            j = (y & 8 and [1] or [0])[0] | (y & 4 and [2] or [0])[0] | \
                (y & 2 and [4] or [0])[0] | (y & 1 and [8] or [0])[0]

            if 16*j+8 < amount:
                region.Union(0, y, size.x, 1)

        self.SetShape(region)

[docs]    def SetBlindMode(self, agwFlags):
        """
        Sets whether venetian blinds or transparent hints will be shown as docking hint.
        This depends on the L{AuiManager} flags.

        :param `agwFlags`: the L{AuiManager} flags.
        """

        self._blindMode = (agwFlags & AUI_MGR_VENETIAN_BLINDS_HINT) != 0

        if self._blindMode or not self.CanSetTransparent():
            self.MakeVenetianBlinds()
            self.SetTransparent(255)

        else:
            self.SetShape(wx.Region())
            if agwFlags & AUI_MGR_HINT_FADE == 0:
                self.SetTransparent(80)
            else:
                self.SetTransparent(0)

[docs]    def SetShape(self, region):
        """
        If the platform supports it, sets the shape of the window to that depicted by `region`.
        The system will not display or respond to any mouse event for the pixels that lie
        outside of the region. To reset the window to the normal rectangular shape simply call
        L{SetShape} again with an empty region.

        :param `region`: the shape of the frame (an instance of `wx.Region`).

        :note: Overridden for wxMac.
        """

        if wx.Platform == '__WXMAC__':
            # HACK so we don't crash when SetShape is called
            return
        else:
            super(AuiDockingHintWindow, self).SetShape(region)

[docs]    def Show(self, show=True):
        """
        Show the hint window.

        :param `show`: whether to show or hide the hint docking window.
        """

        super(AuiDockingHintWindow, self).Show(show)
        if wx.Platform == '__WXMAC__':
            # Need to manually do layout since its a borderless frame.
            self.Layout()

[docs]    def OnSize(self, event):
        """
        Handles the ``wx.EVT_SIZE`` event for L{AuiDockingHintWindow}.

        :param `event`: a `wx.SizeEvent` to be processed.
        """

        if self._blindMode or not self.CanSetTransparent():
            self.MakeVenetianBlinds()

# ---------------------------------------------------------------------------- #

# -- AuiFloatingFrame class implementation --

[docs]class AuiFloatingFrame(wx.MiniFrame):
    """ AuiFloatingFrame is the frame class that holds floating panes. """

[docs]    def __init__(self, parent, owner_mgr, pane=None, id=wx.ID_ANY, title="",
                 style=wx.FRAME_TOOL_WINDOW | wx.FRAME_FLOAT_ON_PARENT |
                 wx.FRAME_NO_TASKBAR | wx.CLIP_CHILDREN):
        """
        Default class constructor. Used internally, do not call it in your code!

        :param `parent`: the L{AuiFloatingFrame} parent;
        :param `owner_mgr`: the L{AuiManager} that manages the floating pane;
        :param `pane`: the L{AuiPaneInfo} pane that is about to float;
        :param `id`: the window identifier. It may take a value of -1 to indicate a default value.
        :param `title`: the caption to be displayed on the frame's title bar.
        :param `style`: the window style.
        """

        if pane and pane.IsResizeable():
            style += wx.RESIZE_BORDER
        if pane:
            self._is_toolbar = pane.IsToolbar()

        self._useNativeMiniframes = False
        if AuiManager_UseNativeMiniframes(owner_mgr):
            # On wxMac we always use native miniframes
            self._useNativeMiniframes = True
            style += wx.CAPTION + wx.SYSTEM_MENU
            if pane.HasCloseButton():
                style += wx.CLOSE_BOX
            if pane.HasMaximizeButton():
                style += wx.MAXIMIZE_BOX
            if pane.HasMinimizeButton():
                style += wx.MINIMIZE_BOX

        wx.MiniFrame.__init__(self, parent, id, title, pos=pane.floating_pos,
                              size=pane.floating_size, style=style, name="auiFloatingFrame")

        self._fly_timer = wx.Timer(self, wx.ID_ANY)
        self._check_fly_timer = wx.Timer(self, wx.ID_ANY)

        self.Bind(wx.EVT_CLOSE, self.OnClose)
        self.Bind(wx.EVT_SIZE, self.OnSize)
        self.Bind(wx.EVT_ACTIVATE, self.OnActivate)
        self.Bind(wx.EVT_TIMER, self.OnCheckFlyTimer, self._check_fly_timer)
        self.Bind(wx.EVT_TIMER, self.OnFlyTimer, self._fly_timer)
        self.Bind(EVT_AUI_FIND_MANAGER, self.OnFindManager)

        if self._useNativeMiniframes:
            self.Bind(wx.EVT_MOVE, self.OnMoveEvent)
            self.Bind(wx.EVT_MOVING, self.OnMoveEvent)
            self.Bind(wx.EVT_IDLE, self.OnIdle)
            self._useNativeMiniframes = True
            self.SetExtraStyle(wx.WS_EX_PROCESS_IDLE)
        else:
            self.Bind(wx.EVT_MOVE, self.OnMove)

        self._fly = False
        self._send_size = True
        self._alpha_amount = 255

        self._owner_mgr = owner_mgr
        self._moving = False
        self._lastDirection = None
        self._transparent = 255

        self._last_rect = wx.Rect()
        self._last2_rect = wx.Rect()
        self._last3_rect = wx.Rect()

        self._mgr = AuiManager()
        self._mgr.SetManagedWindow(self)
        self._mgr.SetArtProvider(owner_mgr.GetArtProvider())
        self._mgr.SetAGWFlags(owner_mgr.GetAGWFlags())

[docs]    def CopyAttributes(self, pane):
        """
        Copies all the attributes of the input `pane` into another L{AuiPaneInfo}.

        :param `pane`: the source L{AuiPaneInfo} from where to copy attributes.
        """

        contained_pane = AuiPaneInfo()

        contained_pane.name = pane.name
        contained_pane.caption = pane.caption
        contained_pane.window = pane.window
        contained_pane.frame = pane.frame
        contained_pane.state = pane.state
        contained_pane.dock_direction = pane.dock_direction
        contained_pane.dock_layer = pane.dock_layer
        contained_pane.dock_row = pane.dock_row
        contained_pane.dock_pos = pane.dock_pos
        contained_pane.best_size = wx.Size(*pane.best_size)
        contained_pane.min_size = wx.Size(*pane.min_size)
        contained_pane.max_size = wx.Size(*pane.max_size)
        contained_pane.floating_pos = wx.Point(*pane.floating_pos)
        contained_pane.floating_size = wx.Size(*pane.floating_size)
        contained_pane.dock_proportion = pane.dock_proportion
        contained_pane.buttons = pane.buttons
        contained_pane.rect = wx.Rect(*pane.rect)
        contained_pane.icon = pane.icon
        contained_pane.notebook_id = pane.notebook_id
        contained_pane.transparent = pane.transparent
        contained_pane.snapped = pane.snapped
        contained_pane.minimize_mode = pane.minimize_mode
        contained_pane.minimize_target = pane.minimize_target

        return contained_pane

[docs]    def SetPaneWindow(self, pane):
        """
        Sets all the properties of a pane.

        :param `pane`: the L{AuiPaneInfo} to analyze.
        """

        self._is_toolbar = pane.IsToolbar()
        self._pane_window = pane.window

        if isinstance(pane.window, auibar.AuiToolBar):
            pane.window.SetAuiManager(self._mgr)

        self._pane_window.Reparent(self)

        contained_pane = self.CopyAttributes(pane)

        contained_pane.Dock().Center().Show(). \
                       CaptionVisible(False). \
                       PaneBorder(False). \
                       Layer(0).Row(0).Position(0)

        if not contained_pane.HasGripper() and not self._useNativeMiniframes:
            contained_pane.CaptionVisible(True)

        indx = self._owner_mgr._panes.index(pane)

        # Carry over the minimum size
        pane_min_size = pane.window.GetMinSize()

        # if the best size is smaller than the min size
        # then set the min size to the best size as well
        pane_best_size = contained_pane.best_size
        if pane_best_size.IsFullySpecified() and (pane_best_size.x < pane_min_size.x or \
                                                  pane_best_size.y < pane_min_size.y):

            pane_min_size = pane_best_size
            self._pane_window.SetMinSize(pane_min_size)

        # if the frame window's max size is greater than the min size
        # then set the max size to the min size as well
        cur_max_size = self.GetMaxSize()
        if cur_max_size.IsFullySpecified() and  (cur_max_size.x < pane_min_size.x or \
                                                 cur_max_size.y < pane_min_size.y):
            self.SetMaxSize(pane_min_size)

        art_provider = self._mgr.GetArtProvider()
        caption_size = art_provider.GetMetric(AUI_DOCKART_CAPTION_SIZE)
        button_size = art_provider.GetMetric(AUI_DOCKART_PANE_BUTTON_SIZE) + \
                      4*art_provider.GetMetric(AUI_DOCKART_PANE_BORDER_SIZE)

        min_size = pane.window.GetMinSize()

        if min_size.y < caption_size or min_size.x < button_size:
            new_x, new_y = min_size.x, min_size.y
            if min_size.y < caption_size:
                new_y = (pane.IsResizeable() and [2*wx.SystemSettings.GetMetric(wx.SYS_EDGE_Y)+caption_size] or [1])[0]
            if min_size.x < button_size:
                new_x = (pane.IsResizeable() and [2*wx.SystemSettings.GetMetric(wx.SYS_EDGE_X)+button_size] or [1])[0]

            self.SetMinSize((new_x, new_y))
        else:
            self.SetMinSize(min_size)

        self._mgr.AddPane(self._pane_window, contained_pane)
        self._mgr.Update()

        if pane.min_size.IsFullySpecified():
            # because SetSizeHints() calls Fit() too (which sets the window
            # size to its minimum allowed), we keep the size before calling
            # SetSizeHints() and reset it afterwards...
            tmp = self.GetSize()
            self.GetSizer().SetSizeHints(self)
            self.SetSize(tmp)

        self.SetTitle(pane.caption)

        if pane.floating_size != wx.Size(-1, -1):
            self.SetSize(pane.floating_size)
        else:
            size = pane.best_size
            if size == wx.Size(-1, -1):
                size = pane.min_size
            if size == wx.Size(-1, -1):
                size = self._pane_window.GetSize()
            if self._owner_mgr and pane.HasGripper():
                if pane.HasGripperTop():
                    size.y += self._owner_mgr._art.GetMetric(AUI_DOCKART_GRIPPER_SIZE)
                else:
                    size.x += self._owner_mgr._art.GetMetric(AUI_DOCKART_GRIPPER_SIZE)

            if not self._useNativeMiniframes:
                size.y += self._owner_mgr._art.GetMetric(AUI_DOCKART_CAPTION_SIZE)

            pane.floating_size = size

            self.SetClientSize(size)

        self._owner_mgr._panes[indx] = pane

        self._fly_step = abs(pane.floating_size.y - \
                             (caption_size + 2*wx.SystemSettings.GetMetric(wx.SYS_EDGE_Y)))/10

        self._floating_size = wx.Size(*self.GetSize())

        if pane.IsFlyOut():
            self._check_fly_timer.Start(50)

[docs]    def GetOwnerManager(self):
        """ Returns the L{AuiManager} that manages the pane. """

        return self._owner_mgr

[docs]    def OnSize(self, event):
        """
        Handles the ``wx.EVT_SIZE`` event for L{AuiFloatingFrame}.

        :param `event`: a `wx.SizeEvent` to be processed.
        """

        if self._owner_mgr and self._send_size:
            self._owner_mgr.OnFloatingPaneResized(self._pane_window, event.GetSize())

[docs]    def OnClose(self, event):
        """
        Handles the ``wx.EVT_CLOSE`` event for L{AuiFloatingFrame}.

        :param `event`: a `wx.CloseEvent` to be processed.
        """

        if self._owner_mgr:
            self._owner_mgr.OnFloatingPaneClosed(self._pane_window, event)

        if not event.GetVeto():
            self._mgr.DetachPane(self._pane_window)

            if isinstance(self._pane_window, auibar.AuiToolBar):
                self._pane_window.SetAuiManager(self._owner_mgr)

            # if we do not do this, then we can crash...
            if self._owner_mgr and self._owner_mgr._action_window == self:
                self._owner_mgr._action_window = None

            self.Destroy()

[docs]    def OnActivate(self, event):
        """
        Handles the ``wx.EVT_ACTIVATE`` event for L{AuiFloatingFrame}.

        :param `event`: a `wx.ActivateEvent` to be processed.
        """

        if self._owner_mgr and event.GetActive():
            self._owner_mgr.OnFloatingPaneActivated(self._pane_window)

[docs]    def OnMove(self, event):
        """
        Handles the ``wx.EVT_MOVE`` event for L{AuiFloatingFrame}.

        :param `event`: a `wx.MoveEvent` to be processed.

        :note: This event is not processed on wxMAC or if L{AuiManager} is not using the
         ``AUI_MGR_USE_NATIVE_MINIFRAMES`` style.
        """

        if self._owner_mgr:
            self._owner_mgr.OnFloatingPaneMoved(self._pane_window, event)

[docs]    def OnMoveEvent(self, event):
        """
        Handles the ``wx.EVT_MOVE`` and ``wx.EVT_MOVING`` events for L{AuiFloatingFrame}.

        :param `event`: a `wx.MoveEvent` to be processed.

        :note: This event is only processed on wxMAC or if L{AuiManager} is using the
         ``AUI_MGR_USE_NATIVE_MINIFRAMES`` style.
        """

        win_rect = self.GetRect()

        if win_rect == self._last_rect:
            return

        # skip the first move event
        if self._last_rect.IsEmpty():
            self._last_rect = wx.Rect(*win_rect)
            return

        # skip if moving too fast to avoid massive redraws and
        # jumping hint windows
        if abs(win_rect.x - self._last_rect.x) > 3 or abs(win_rect.y - self._last_rect.y) > 3:
            self._last3_rect = wx.Rect(*self._last2_rect)
            self._last2_rect = wx.Rect(*self._last_rect)
            self._last_rect = wx.Rect(*win_rect)
            return

        # prevent frame redocking during resize
        if self._last_rect.GetSize() != win_rect.GetSize():
            self._last3_rect = wx.Rect(*self._last2_rect)
            self._last2_rect = wx.Rect(*self._last_rect)
            self._last_rect = wx.Rect(*win_rect)
            return

        self._last3_rect = wx.Rect(*self._last2_rect)
        self._last2_rect = wx.Rect(*self._last_rect)
        self._last_rect = wx.Rect(*win_rect)

        if _VERSION_STRING < "2.9":
            leftDown = wx.GetMouseState().LeftDown()
        else:
            leftDown = wx.GetMouseState().LeftIsDown()

        if not leftDown:
            return

        if not self._moving:
            self.OnMoveStart(event)
            self._moving = True

        if self._last3_rect.IsEmpty():
            return

        self.OnMoving(event)

[docs]    def OnIdle(self, event):
        """
        Handles the ``wx.EVT_IDLE`` event for L{AuiFloatingFrame}.

        :param `event`: a `wx.IdleEvent` event to be processed.

        :note: This event is only processed on wxMAC or if L{AuiManager} is using the
         ``AUI_MGR_USE_NATIVE_MINIFRAMES`` style.
        """

        if self._moving:
            if _VERSION_STRING < "2.9":
                leftDown = wx.GetMouseState().LeftDown()
            else:
                leftDown = wx.GetMouseState().LeftIsDown()

            if not leftDown:
                self._moving = False
                self.OnMoveFinished()
            else:
                event.RequestMore()

[docs]    def OnMoveStart(self, event):
        """
        The user has just started moving the floating pane.

        :param `event`: an instance of `wx.MouseEvent`.

        :note: This method is used only on wxMAC or if L{AuiManager} is using the
         ``AUI_MGR_USE_NATIVE_MINIFRAMES`` style.
        """

        # notify the owner manager that the pane has started to move
        if self._owner_mgr:
            if self._owner_mgr._from_move:
                return
            self._owner_mgr._action_window = self._pane_window
            point = wx.GetMousePosition()
            action_offset = point - self.GetPosition()

            if self._is_toolbar:
                self._owner_mgr._toolbar_action_offset = action_offset
                self._owner_mgr.OnMotion_DragToolbarPane(point)
            else:
                self._owner_mgr._action_offset = action_offset
                self._owner_mgr.OnMotion_DragFloatingPane(point)

[docs]    def OnMoving(self, event):
        """
        The user is moving the floating pane.

        :param `event`: an instance of `wx.MouseEvent`.

        :note: This method is used only on wxMAC or if L{AuiManager} is using the
         ``AUI_MGR_USE_NATIVE_MINIFRAMES`` style.
        """

        # notify the owner manager that the pane is moving
        self.OnMoveStart(event)

[docs]    def OnMoveFinished(self):
        """
        The user has just finished moving the floating pane.

        :note: This method is used only on wxMAC or if L{AuiManager} is using the
         ``AUI_MGR_USE_NATIVE_MINIFRAMES`` style.
        """

        # notify the owner manager that the pane has finished moving
        if self._owner_mgr:
            self._owner_mgr._action_window = self._pane_window
            point = wx.GetMousePosition()
            if self._is_toolbar:
                self._owner_mgr.OnLeftUp_DragToolbarPane(point)
            else:
                self._owner_mgr.OnLeftUp_DragFloatingPane(point)

            self._owner_mgr.OnFloatingPaneMoved(self._pane_window, point)

[docs]    def OnCheckFlyTimer(self, event):
        """
        Handles the ``wx.EVT_TIMER`` event for L{AuiFloatingFrame}.

        :param `event`: a `wx.TimerEvent` to be processed.

        :note: This is used solely for "fly-out" panes.
        """

        if self._owner_mgr:
            pane = self._mgr.GetPane(self._pane_window)
            if pane.IsFlyOut():
                if self.IsShownOnScreen():
                    self.FlyOut()

[docs]    def OnFindManager(self, event):
        """
        Handles the ``EVT_AUI_FIND_MANAGER`` event for L{AuiFloatingFrame}.

        :param `event`: a L{AuiManagerEvent} event to be processed.
        """

        event.SetManager(self._owner_mgr)

[docs]    def FlyOut(self):
        """ Starts the flying in and out of a floating pane. """

        if self._fly_timer.IsRunning():
            return

        if _VERSION_STRING < "2.9":
            leftDown = wx.GetMouseState().LeftDown()
        else:
            leftDown = wx.GetMouseState().LeftIsDown()

        if leftDown:
            return

        rect = wx.Rect(*self.GetScreenRect())
        rect.Inflate(10, 10)

        if rect.Contains(wx.GetMousePosition()):
            if not self._fly:
                return
            self._send_size = False
            self._fly_timer.Start(5)
        else:
            if self._fly:
                return
            self._send_size = False
            self._fly_timer.Start(5)

[docs]    def OnFlyTimer(self, event):
        """
        Handles the ``wx.EVT_TIMER`` event for L{AuiFloatingFrame}.

        :param `event`: a `wx.TimerEvent` to be processed.
        """

        current_size = self.GetClientSize()
        floating_size = wx.Size(*self._owner_mgr.GetPane(self._pane_window).floating_size)

        if floating_size.y == -1:
            floating_size = self._floating_size

        if not self._fly:
            min_size = self._mgr.GetArtProvider().GetMetric(AUI_DOCKART_CAPTION_SIZE)

            if wx.Platform != "__WXMSW__":
                min_size += 2*wx.SystemSettings.GetMetric(wx.SYS_EDGE_Y)

            if current_size.y - self._fly_step <= min_size:
                self.SetClientSize((current_size.x, min_size))
                self._fly = True
                self._fly_timer.Stop()
                self._send_size = True
            else:
                self.SetClientSize((current_size.x, current_size.y-self._fly_step))

        else:
            if current_size.y + self._fly_step >= floating_size.y:
                self.SetClientSize((current_size.x, floating_size.y))
                self._fly = False
                self._fly_timer.Stop()
                self._send_size = True
            else:
                self.SetClientSize((current_size.x, current_size.y+self._fly_step))

        self.Update()
        self.Refresh()

[docs]    def FadeOut(self):
        """ Actually starts the fading out of the floating pane. """

        while 1:
            self._alpha_amount -= 10
            if self._alpha_amount <= 0:
                self._alpha_amount = 255
                return

            self.SetTransparent(self._alpha_amount)
            wx.SafeYield()
            wx.MilliSleep(15)

# -- static utility functions --

[docs]def DrawResizeHint(dc, rect):
    """
    Draws a resize hint while a sash is dragged.

    :param `rect`: a `wx.Rect` rectangle which specifies the sash dimensions.
    """

    if wx.Platform == "__WXMSW__" and wx.App.GetComCtl32Version() >= 600:
        if wx.GetOsVersion()[1] > 5:
            # Windows Vista
            dc.SetPen(wx.Pen("black", 2, wx.SOLID))
            dc.SetBrush(wx.TRANSPARENT_BRUSH)
        else:
            # Draw the nice XP style splitter
            dc.SetPen(wx.TRANSPARENT_PEN)
            dc.SetBrush(wx.BLACK_BRUSH)
        dc.SetLogicalFunction(wx.INVERT)
        dc.DrawRectangleRect(rect)
        dc.SetLogicalFunction(wx.COPY)
    else:
        stipple = PaneCreateStippleBitmap()
        brush = wx.BrushFromBitmap(stipple)
        dc.SetBrush(brush)
        dc.SetPen(wx.TRANSPARENT_PEN)

        dc.SetLogicalFunction(wx.XOR)
        dc.DrawRectangleRect(rect)

[docs]def CopyDocksAndPanes(src_docks, src_panes):
    """
    This utility function creates shallow copies of
    the dock and pane info. L{AuiDockInfo} usually contain pointers
    to L{AuiPaneInfo} classes, thus this function is necessary to reliably
    reconstruct that relationship in the new dock info and pane info arrays.

    :param `src_docks`: a list of L{AuiDockInfo} classes;
    :param `src_panes`: a list of L{AuiPaneInfo} classes.
    """

    dest_docks = src_docks
    dest_panes = src_panes

    for ii in xrange(len(dest_docks)):
        dock = dest_docks[ii]
        for jj in xrange(len(dock.panes)):
            for kk in xrange(len(src_panes)):
                if dock.panes[jj] == src_panes[kk]:
                    dock.panes[jj] = dest_panes[kk]

    return dest_docks, dest_panes

[docs]def CopyDocksAndPanes2(src_docks, src_panes):
    """
    This utility function creates full copies of
    the dock and pane info. L{AuiDockInfo} usually contain pointers
    to L{AuiPaneInfo} classes, thus this function is necessary to reliably
    reconstruct that relationship in the new dock info and pane info arrays.

    :param `src_docks`: a list of L{AuiDockInfo} classes;
    :param `src_panes`: a list of L{AuiPaneInfo} classes.
    """

    dest_docks = []

    for ii in xrange(len(src_docks)):
        dest_docks.append(AuiDockInfo())
        dest_docks[ii].dock_direction = src_docks[ii].dock_direction
        dest_docks[ii].dock_layer = src_docks[ii].dock_layer
        dest_docks[ii].dock_row = src_docks[ii].dock_row
        dest_docks[ii].size = src_docks[ii].size
        dest_docks[ii].min_size = src_docks[ii].min_size
        dest_docks[ii].resizable = src_docks[ii].resizable
        dest_docks[ii].fixed = src_docks[ii].fixed
        dest_docks[ii].toolbar = src_docks[ii].toolbar
        dest_docks[ii].panes = src_docks[ii].panes
        dest_docks[ii].rect = wx.Rect(*src_docks[ii].rect)

    dest_panes = []

    for ii in xrange(len(src_panes)):
        dest_panes.append(AuiPaneInfo())
        dest_panes[ii].name = src_panes[ii].name
        dest_panes[ii].caption = src_panes[ii].caption
        dest_panes[ii].window = src_panes[ii].window
        dest_panes[ii].frame = src_panes[ii].frame
        dest_panes[ii].state = src_panes[ii].state
        dest_panes[ii].dock_direction = src_panes[ii].dock_direction
        dest_panes[ii].dock_layer = src_panes[ii].dock_layer
        dest_panes[ii].dock_row = src_panes[ii].dock_row
        dest_panes[ii].dock_pos = src_panes[ii].dock_pos
        dest_panes[ii].best_size = wx.Size(*src_panes[ii].best_size)
        dest_panes[ii].min_size = wx.Size(*src_panes[ii].min_size)
        dest_panes[ii].max_size = wx.Size(*src_panes[ii].max_size)
        dest_panes[ii].floating_pos = wx.Point(*src_panes[ii].floating_pos)
        dest_panes[ii].floating_size = wx.Size(*src_panes[ii].floating_size)
        dest_panes[ii].dock_proportion = src_panes[ii].dock_proportion
        dest_panes[ii].buttons = src_panes[ii].buttons
        dest_panes[ii].rect = wx.Rect(*src_panes[ii].rect)
        dest_panes[ii].icon = src_panes[ii].icon
        dest_panes[ii].notebook_id = src_panes[ii].notebook_id
        dest_panes[ii].transparent = src_panes[ii].transparent
        dest_panes[ii].snapped = src_panes[ii].snapped
        dest_panes[ii].minimize_mode = src_panes[ii].minimize_mode
        dest_panes[ii].minimize_target = src_panes[ii].minimize_target

    for ii in xrange(len(dest_docks)):
        dock = dest_docks[ii]
        for jj in xrange(len(dock.panes)):
            for kk in xrange(len(src_panes)):
                if dock.panes[jj] == src_panes[kk]:
                    dock.panes[jj] = dest_panes[kk]

        dest_docks[ii] = dock

    return dest_docks, dest_panes

[docs]def GetMaxLayer(docks, dock_direction):
    """
    This is an internal function which returns
    the highest layer inside the specified dock.

    :param `docks`: a list of L{AuiDockInfo};
    :param `dock_direction`: the L{AuiDockInfo} docking direction to analyze.
    """

    max_layer = 0

    for dock in docks:
        if dock.dock_direction == dock_direction and dock.dock_layer > max_layer and not dock.fixed:
            max_layer = dock.dock_layer

    return max_layer

[docs]def GetMaxRow(panes, dock_direction, dock_layer):
    """
    This is an internal function which returns
    the highest layer inside the specified dock.

    :param `panes`: a list of L{AuiPaneInfo};
    :param `dock_direction`: the L{AuiPaneInfo} docking direction to analyze;
    :param `dock_layer`: the L{AuiPaneInfo} layer to analyze.
    """

    max_row = 0

    for pane in panes:
        if pane.dock_direction == dock_direction and pane.dock_layer == dock_layer and \
           pane.dock_row > max_row:
            max_row = pane.dock_row

    return max_row

[docs]def DoInsertDockLayer(panes, dock_direction, dock_layer):
    """
    This is an internal function that inserts a new dock
    layer by incrementing all existing dock layer values by one.

    :param `panes`: a list of L{AuiPaneInfo};
    :param `dock_direction`: the L{AuiPaneInfo} docking direction to analyze;
    :param `dock_layer`: the L{AuiPaneInfo} layer to analyze.
    """

    for ii in xrange(len(panes)):
        pane = panes[ii]
        if not pane.IsFloating() and pane.dock_direction == dock_direction and pane.dock_layer >= dock_layer:
            pane.dock_layer = pane.dock_layer + 1

        panes[ii] = pane

    return panes

[docs]def DoInsertDockRow(panes, dock_direction, dock_layer, dock_row):
    """
    This is an internal function that inserts a new dock
    row by incrementing all existing dock row values by one.

    :param `panes`: a list of L{AuiPaneInfo};
    :param `dock_direction`: the L{AuiPaneInfo} docking direction to analyze;
    :param `dock_layer`: the L{AuiPaneInfo} layer to analyze;
    :param `dock_row`: the L{AuiPaneInfo} row to analyze.
    """

    for pane in panes:
        if not pane.IsFloating() and pane.dock_direction == dock_direction and \
           pane.dock_layer == dock_layer and pane.dock_row >= dock_row:
            pane.dock_row += 1

    return panes

[docs]def DoInsertPane(panes, dock_direction, dock_layer, dock_row, dock_pos):
    """
    This is an internal function that inserts a new pane
    by incrementing all existing dock position values by one.

    :param `panes`: a list of L{AuiPaneInfo};
    :param `dock_direction`: the L{AuiPaneInfo} docking direction to analyze;
    :param `dock_layer`: the L{AuiPaneInfo} layer to analyze;
    :param `dock_row`: the L{AuiPaneInfo} row to analyze;
    :param `dock_pos`: the L{AuiPaneInfo} row to analyze.
    """

    for ii in xrange(len(panes)):
        pane = panes[ii]
        if not pane.IsFloating() and pane.dock_direction == dock_direction and \
           pane.dock_layer == dock_layer and  pane.dock_row == dock_row and \
           pane.dock_pos >= dock_pos:
            pane.dock_pos = pane.dock_pos + 1

        panes[ii] = pane

    return panes

[docs]def FindDocks(docks, dock_direction, dock_layer=-1, dock_row=-1, reverse=False):
    """
    This is an internal function that returns a list of docks which meet
    the specified conditions in the parameters and returns a sorted array
    (sorted by layer and then row).

    :param `docks`: a list of L{AuiDockInfo};
    :param `dock_direction`: the L{AuiDockInfo} docking direction to analyze;
    :param `dock_layer`: the L{AuiDockInfo} layer to analyze;
    :param `dock_row`: the L{AuiDockInfo} row to analyze;
    """

    matchDocks = [(d.dock_layer, d.dock_row, d.dock_direction, d) for d in docks if \
                  (dock_direction == -1 or dock_direction == d.dock_direction) and \
                  ((dock_layer == -1 or dock_layer == d.dock_layer) and \
                  (dock_row == -1 or dock_row == d.dock_row))]

    arr = [x[-1] for x in sorted(matchDocks, reverse=reverse)]

    return arr

[docs]def FindOppositeDocks(docks, dock_direction):
    """
    This is an internal function that returns a list of docks
    which is related to the opposite direction.

    :param `docks`: a list of L{AuiDockInfo};
    :param `dock_direction`: the L{AuiDockInfo} docking direction to analyze;
    """

    if dock_direction == AUI_DOCK_LEFT:
        arr = FindDocks(docks, AUI_DOCK_RIGHT, -1, -1)
    elif dock_direction == AUI_DOCK_TOP:
        arr = FindDocks(docks, AUI_DOCK_BOTTOM, -1, -1)
    elif dock_direction == AUI_DOCK_RIGHT:
        arr = FindDocks(docks, AUI_DOCK_LEFT, -1, -1)
    elif dock_direction == AUI_DOCK_BOTTOM:
        arr = FindDocks(docks, AUI_DOCK_TOP, -1, -1)

    return arr

[docs]def FindPaneInDock(dock, window):
    """
    This method looks up a specified window pointer inside a dock.
    If found, the corresponding L{AuiPaneInfo} pointer is returned, otherwise ``None``.

    :param `dock`: a L{AuiDockInfo} structure;
    :param `window`: a `wx.Window` derived window (associated to a pane).
    """

    for p in dock.panes:
        if p.window == window:
            return p

    return None

[docs]def GetToolBarDockOffsets(docks):
    """
    Returns the toolbar dock offsets (top-left and bottom-right).

    :param `docks`: a list of L{AuiDockInfo} to analyze.
    """

    top_left = wx.Size(0, 0)
    bottom_right = wx.Size(0, 0)

    for dock in docks:
        if dock.toolbar:
            dock_direction = dock.dock_direction
            if dock_direction == AUI_DOCK_LEFT:
                top_left.x += dock.rect.width
                bottom_right.x += dock.rect.width

            elif dock_direction == AUI_DOCK_TOP:
                top_left.y += dock.rect.height
                bottom_right.y += dock.rect.height

            elif dock_direction == AUI_DOCK_RIGHT:
                bottom_right.x += dock.rect.width

            elif dock_direction == AUI_DOCK_BOTTOM:
                bottom_right.y += dock.rect.height

    return top_left, bottom_right

[docs]def GetInternalFrameRect(window, docks):
    """
    Returns the window rectangle excluding toolbars.

    :param `window`: a `wx.Window` derived window;
    :param `docks`: a list of L{AuiDockInfo} structures.
    """

    frameRect = wx.Rect()

    frameRect.SetTopLeft(window.ClientToScreen(window.GetClientAreaOrigin()))
    frameRect.SetSize(window.GetClientSize())

    top_left, bottom_right = GetToolBarDockOffsets(docks)

    # make adjustments for toolbars
    frameRect.x += top_left.x
    frameRect.y += top_left.y
    frameRect.width -= bottom_right.x
    frameRect.height -= bottom_right.y

    return frameRect

[docs]def CheckOutOfWindow(window, pt):
    """
    Checks if a point is outside the window rectangle.

    :param `window`: a `wx.Window` derived window;
    :param `pt`: a `wx.Point` object.
    """

    auiWindowMargin = 30
    marginRect = wx.Rect(*window.GetClientRect())
    marginRect.Inflate(auiWindowMargin, auiWindowMargin)

    return not marginRect.Contains(pt)

[docs]def CheckEdgeDrop(window, docks, pt):
    """
    Checks on which edge of a window the drop action has taken place.

    :param `window`: a `wx.Window` derived window;
    :param `docks`: a list of L{AuiDockInfo} structures;
    :param `pt`: a `wx.Point` object.
    """

    screenPt = window.ClientToScreen(pt)
    clientSize = window.GetClientSize()
    frameRect = GetInternalFrameRect(window, docks)

    if screenPt.y >= frameRect.GetTop() and screenPt.y < frameRect.GetBottom():
        if pt.x < auiLayerInsertOffset and pt.x > auiLayerInsertOffset - auiLayerInsertPixels:
            return wx.LEFT

        if pt.x >= clientSize.x - auiLayerInsertOffset and \
           pt.x < clientSize.x - auiLayerInsertOffset + auiLayerInsertPixels:
            return wx.RIGHT

    if screenPt.x >= frameRect.GetLeft() and screenPt.x < frameRect.GetRight():
        if pt.y < auiLayerInsertOffset and pt.y > auiLayerInsertOffset - auiLayerInsertPixels:
            return wx.TOP

        if pt.y >= clientSize.y - auiLayerInsertOffset and \
           pt.y < clientSize.y - auiLayerInsertOffset + auiLayerInsertPixels:
            return wx.BOTTOM

    return -1

[docs]def RemovePaneFromDocks(docks, pane, exc=None):
    """
    Removes a pane window from all docks
    with a possible exception specified by parameter `exc`.

    :param `docks`: a list of L{AuiDockInfo} structures;
    :param `pane`: the L{AuiPaneInfo} pane to be removed;
    :param `exc`: the possible pane exception.
    """

    for ii in xrange(len(docks)):
        d = docks[ii]
        if d == exc:
            continue
        pi = FindPaneInDock(d, pane.window)
        if pi:
            d.panes.remove(pi)

        docks[ii] = d

    return docks

[docs]def RenumberDockRows(docks):
    """
    Takes a dock and assigns sequential numbers
    to existing rows.  Basically it takes out the gaps so if a
    dock has rows with numbers 0, 2, 5, they will become 0, 1, 2.

    :param `docks`: a list of L{AuiDockInfo} structures.
    """

    for ii in xrange(len(docks)):
        dock = docks[ii]
        dock.dock_row = ii
        for jj in xrange(len(dock.panes)):
            dock.panes[jj].dock_row = ii

        docks[ii] = dock

    return docks

[docs]def SetActivePane(panes, active_pane):
    """
    Sets the active pane, as well as cycles through
    every other pane and makes sure that all others' active flags
    are turned off.

    :param `panes`: a list of L{AuiPaneInfo} structures;
    :param `active_pane`: the pane to be made active (if found).
    """

    for pane in panes:
        pane.state &= ~AuiPaneInfo.optionActive

    for pane in panes:
        if pane.window == active_pane and not pane.IsNotebookPage():
            pane.state |= AuiPaneInfo.optionActive
            return True, panes

    return False, panes

[docs]def ShowDockingGuides(guides, show):
    """
    Shows or hide the docking guide windows.

    :param `guides`: a list of L{AuiDockingGuideInfo} classes;
    :param `show`: whether to show or hide the docking guide windows.
    """

    for target in guides:

        if show and not target.host.IsShown():
            target.host.Show()
            target.host.Update()

        elif not show and target.host.IsShown():
            target.host.Hide()

[docs]def RefreshDockingGuides(guides):
    """
    Refreshes the docking guide windows.

    :param `guides`: a list of L{AuiDockingGuideInfo} classes;
    """

    for target in guides:
        if target.host.IsShown():
            target.host.Refresh()

[docs]def PaneSortFunc(p1, p2):
    """
    This function is used to sort panes by dock position.

    :param `p1`: a L{AuiPaneInfo} instance;
    :param `p2`: another L{AuiPaneInfo} instance.
    """

    return (p1.dock_pos < p2.dock_pos and [-1] or [1])[0]

[docs]def GetNotebookRoot(panes, notebook_id):
    """
    Returns the L{AuiPaneInfo} which has the specified `notebook_id`.

    :param `panes`: a list of L{AuiPaneInfo} instances;
    :param `notebook_id`: the target notebook id.
    """

    for paneInfo in panes:
        if paneInfo.IsNotebookControl() and paneInfo.notebook_id == notebook_id:
            return paneInfo

    return None

[docs]def EscapeDelimiters(s):
    """
    Changes ``;`` into ``\`` and ``|`` into ``\|`` in the input string.

    :param `s`: the string to be analyzed.

    :note: This is an internal functions which is used for saving perspectives.
    """

    result = s.replace(";", "\\")
    result = result.replace("|", "|\\")

    return result

[docs]def IsDifferentDockingPosition(pane1, pane2):
    """
    Returns whether `pane1` and `pane2` are in a different docking position
    based on pane status, docking direction, docking layer and docking row.

    :param `pane1`: a L{AuiPaneInfo} instance;
    :param `pane2`: another L{AuiPaneInfo} instance.
    """

    return pane1.IsFloating() != pane2.IsFloating() or \
           pane1.dock_direction != pane2.dock_direction or \
           pane1.dock_layer != pane2.dock_layer or \
           pane1.dock_row != pane2.dock_row

# Convenience function

[docs]def AuiManager_HasLiveResize(manager):
    """
    Static function which returns if the input `manager` should have "live resize"
    behaviour.

    :param `manager`: an instance of L{AuiManager}.

    :note: This method always returns ``True`` on wxMac as this platform doesn't have
     the ability to use `wx.ScreenDC` to draw sashes.
    """

    # With Core Graphics on Mac, it's not possible to show sash feedback,
    # so we'll always use live update instead.

    if wx.Platform == "__WXMAC__":
        return True
    else:
        return (manager.GetAGWFlags() & AUI_MGR_LIVE_RESIZE) == AUI_MGR_LIVE_RESIZE

# Convenience function

[docs]def AuiManager_UseNativeMiniframes(manager):
    """
    Static function which returns if the input `manager` should use native `wx.MiniFrame` as
    floating panes.

    :param `manager`: an instance of L{AuiManager}.

    :note: This method always returns ``True`` on wxMac as this platform doesn't have
     the ability to use custom drawn miniframes.
    """

    # With Core Graphics on Mac, it's not possible to show sash feedback,
    # so we'll always use live update instead.

    if wx.Platform == "__WXMAC__":
        return True
    else:
        return (manager.GetAGWFlags() & AUI_MGR_USE_NATIVE_MINIFRAMES) == AUI_MGR_USE_NATIVE_MINIFRAMES

[docs]def GetManager(window):
    """
    This function will return the aui manager for a given window.

    :param `window`: this parameter should be any child window or grand-child
     window (and so on) of the frame/window managed by L{AuiManager}. The window
     does not need to be managed by the manager itself, nor does it even need
     to be a child or sub-child of a managed window. It must however be inside
     the window hierarchy underneath the managed window.
    """

    if not isinstance(wx.GetTopLevelParent(window), AuiFloatingFrame):
        if isinstance(window, auibar.AuiToolBar):
            return window.GetAuiManager()

    evt = AuiManagerEvent(wxEVT_AUI_FIND_MANAGER)
    evt.SetManager(None)
    evt.ResumePropagation(wx.EVENT_PROPAGATE_MAX)

    if not window.GetEventHandler().ProcessEvent(evt):
        return None

    return evt.GetManager()

# ---------------------------------------------------------------------------- #

[docs]class AuiManager(wx.EvtHandler):
    """
    AuiManager manages the panes associated with it for a particular `wx.Frame`,
    using a pane's L{AuiPaneInfo} information to determine each pane's docking and
    floating behavior. L{AuiManager} uses wxPython's sizer mechanism to plan the
    layout of each frame. It uses a replaceable dock art class to do all drawing,
    so all drawing is localized in one area, and may be customized depending on an
    applications' specific needs.

    L{AuiManager} works as follows: the programmer adds panes to the class, or makes
    changes to existing pane properties (dock position, floating state, show state, etc...).
    To apply these changes, the L{AuiManager.Update} function is called. This batch
    processing can be used to avoid flicker, by modifying more than one pane at a time,
    and then "committing" all of the changes at once by calling `Update()`.

    Panes can be added quite easily::

        text1 = wx.TextCtrl(self, -1)
        text2 = wx.TextCtrl(self, -1)
        self._mgr.AddPane(text1, AuiPaneInfo().Left().Caption("Pane Number One"))
        self._mgr.AddPane(text2, AuiPaneInfo().Bottom().Caption("Pane Number Two"))

        self._mgr.Update()

    Later on, the positions can be modified easily. The following will float an
    existing pane in a tool window::

        self._mgr.GetPane(text1).Float()

    **Layers, Rows and Directions, Positions:**

    Inside AUI, the docking layout is figured out by checking several pane parameters.
    Four of these are important for determining where a pane will end up.

    **Direction** - Each docked pane has a direction, `Top`, `Bottom`, `Left`, `Right`, or `Center`.
    This is fairly self-explanatory. The pane will be placed in the location specified
    by this variable.

    **Position** - More than one pane can be placed inside of a "dock". Imagine two panes
    being docked on the left side of a window. One pane can be placed over another.
    In proportionally managed docks, the pane position indicates it's sequential position,
    starting with zero. So, in our scenario with two panes docked on the left side, the
    top pane in the dock would have position 0, and the second one would occupy position 1.

    **Row** - A row can allow for two docks to be placed next to each other. One of the most
    common places for this to happen is in the toolbar. Multiple toolbar rows are allowed,
    the first row being in row 0, and the second in row 1. Rows can also be used on
    vertically docked panes.

    **Layer** - A layer is akin to an onion. Layer 0 is the very center of the managed pane.
    Thus, if a pane is in layer 0, it will be closest to the center window (also sometimes
    known as the "content window"). Increasing layers "swallow up" all layers of a lower
    value. This can look very similar to multiple rows, but is different because all panes
    in a lower level yield to panes in higher levels. The best way to understand layers
    is by running the AUI sample (`AUI.py`).
    """

[docs]    def __init__(self, managed_window=None, agwFlags=None):
        """
        Default class constructor.

        :param `managed_window`: specifies the window which should be managed;
        :param `agwFlags`: specifies options which allow the frame management behavior to be
         modified. `agwFlags` can be a combination of the following style bits:

         ==================================== ==================================
         Flag name                            Description
         ==================================== ==================================
         ``AUI_MGR_ALLOW_FLOATING``           Allow floating of panes
         ``AUI_MGR_ALLOW_ACTIVE_PANE``        If a pane becomes active, "highlight" it in the interface
         ``AUI_MGR_TRANSPARENT_DRAG``         If the platform supports it, set transparency on a floating pane while it is dragged by the user
         ``AUI_MGR_TRANSPARENT_HINT``         If the platform supports it, show a transparent hint window when the user is about to dock a floating pane
         ``AUI_MGR_VENETIAN_BLINDS_HINT``     Show a "venetian blind" effect when the user is about to dock a floating pane
         ``AUI_MGR_RECTANGLE_HINT``           Show a rectangle hint effect when the user is about to dock a floating pane
         ``AUI_MGR_HINT_FADE``                If the platform supports it, the hint window will fade in and out
         ``AUI_MGR_NO_VENETIAN_BLINDS_FADE``  Disables the "venetian blind" fade in and out
         ``AUI_MGR_LIVE_RESIZE``              Live resize when the user drag a sash
         ``AUI_MGR_ANIMATE_FRAMES``           Fade-out floating panes when they are closed (all platforms which support frames transparency) and show a moving rectangle when they are docked (Windows < Vista and GTK only)
         ``AUI_MGR_AERO_DOCKING_GUIDES``      Use the new Aero-style bitmaps as docking guides
         ``AUI_MGR_PREVIEW_MINIMIZED_PANES``  Slide in and out minimized panes to preview them
         ``AUI_MGR_WHIDBEY_DOCKING_GUIDES``   Use the new Whidbey-style bitmaps as docking guides
         ``AUI_MGR_SMOOTH_DOCKING``           Performs a "smooth" docking of panes (a la PyQT)
         ``AUI_MGR_USE_NATIVE_MINIFRAMES``    Use miniframes with native caption bar as floating panes instead or custom drawn caption bars (forced on wxMac)
         ``AUI_MGR_AUTONB_NO_CAPTION``        Panes that merge into an automatic notebook will not have the pane caption visible
         ==================================== ==================================

         Default value for `agwFlags` is:
         ``AUI_MGR_DEFAULT`` = ``AUI_MGR_ALLOW_FLOATING`` | ``AUI_MGR_TRANSPARENT_HINT`` | ``AUI_MGR_HINT_FADE`` | ``AUI_MGR_NO_VENETIAN_BLINDS_FADE``

         :note:

          If using the ``AUI_MGR_USE_NATIVE_MINIFRAMES``, double-clicking on a
          floating pane caption will not re-dock the pane, but simply maximize it (if
          L{AuiPaneInfo.MaximizeButton} has been set to ``True``) or do nothing.
        """

        wx.EvtHandler.__init__(self)

        self._action = actionNone
        self._action_window = None
        self._hover_button = None
        self._art = dockart.AuiDefaultDockArt()
        self._hint_window = None
        self._active_pane = None
        self._has_maximized = False
        self._has_minimized = False

        self._frame = None
        self._dock_constraint_x = 0.3
        self._dock_constraint_y = 0.3
        self._reserved = None

        self._panes = []
        self._docks = []
        self._uiparts = []

        self._guides = []
        self._notebooks = []

        self._masterManager = None
        self._currentDragItem = -1
        self._lastknowndocks = {}

        self._hint_fadetimer = wx.Timer(self, wx.ID_ANY)
        self._hint_fademax = 50
        self._last_hint = wx.Rect()

        self._from_move = False
        self._last_rect = wx.Rect()

        if agwFlags is None:
            agwFlags = AUI_MGR_DEFAULT

        self._agwFlags = agwFlags
        self._is_docked = (False, wx.RIGHT, wx.TOP, 0)
        self._snap_limits = (15, 15)

        if wx.Platform == "__WXMSW__":
            self._animation_step = 30.0
        else:
            self._animation_step = 5.0

        self._hint_rect = wx.Rect()

        self._preview_timer = wx.Timer(self, wx.ID_ANY)
        self._sliding_frame = None

        self._autoNBTabArt = tabart.AuiDefaultTabArt()
        self._autoNBStyle = AUI_NB_DEFAULT_STYLE | AUI_NB_BOTTOM | \
                            AUI_NB_SUB_NOTEBOOK | AUI_NB_TAB_EXTERNAL_MOVE
        self._autoNBStyle -= AUI_NB_DRAW_DND_TAB

        if managed_window:
            self.SetManagedWindow(managed_window)

        self.Bind(wx.EVT_PAINT, self.OnPaint)
        self.Bind(wx.EVT_ERASE_BACKGROUND, self.OnEraseBackground)
        self.Bind(wx.EVT_SIZE, self.OnSize)
        self.Bind(wx.EVT_SET_CURSOR, self.OnSetCursor)
        self.Bind(wx.EVT_LEFT_DOWN, self.OnLeftDown)
        self.Bind(wx.EVT_LEFT_DCLICK, self.OnLeftDClick)
        self.Bind(wx.EVT_LEFT_UP, self.OnLeftUp)
        self.Bind(wx.EVT_MOTION, self.OnMotion)
        self.Bind(wx.EVT_LEAVE_WINDOW, self.OnLeaveWindow)
        self.Bind(wx.EVT_CHILD_FOCUS, self.OnChildFocus)
        self.Bind(wx.EVT_MOUSE_CAPTURE_LOST, self.OnCaptureLost)
        self.Bind(wx.EVT_TIMER, self.OnHintFadeTimer, self._hint_fadetimer)
        self.Bind(wx.EVT_TIMER, self.SlideIn, self._preview_timer)

        self.Bind(wx.EVT_MOVE, self.OnMove)
        self.Bind(wx.EVT_SYS_COLOUR_CHANGED, self.OnSysColourChanged)

        self.Bind(EVT_AUI_PANE_BUTTON, self.OnPaneButton)
        self.Bind(EVT_AUI_RENDER, self.OnRender)
        self.Bind(EVT_AUI_FIND_MANAGER, self.OnFindManager)
        self.Bind(EVT_AUI_PANE_MIN_RESTORE, self.OnRestoreMinimizedPane)
        self.Bind(EVT_AUI_PANE_DOCKED, self.OnPaneDocked)

        self.Bind(auibook.EVT_AUINOTEBOOK_BEGIN_DRAG, self.OnTabBeginDrag)
        self.Bind(auibook.EVT_AUINOTEBOOK_PAGE_CLOSE, self.OnTabPageClose)
        self.Bind(auibook.EVT_AUINOTEBOOK_PAGE_CHANGED, self.OnTabSelected)

[docs]    def CreateFloatingFrame(self, parent, pane_info):
        """
        Creates a floating frame for the windows.

        :param `parent`: the floating frame parent;
        :param `pane_info`: the L{AuiPaneInfo} class with all the pane's information.
        """

        return AuiFloatingFrame(parent, self, pane_info)

[docs]    def CanDockPanel(self, p):
        """
        Returns whether a pane can be docked or not.

        :param `p`: the L{AuiPaneInfo} class with all the pane's information.
        """

        # is the pane dockable?
        if not p.IsDockable():
            return False

        # if a key modifier is pressed while dragging the frame,
        # don't dock the window
        return not (wx.GetKeyState(wx.WXK_CONTROL) or wx.GetKeyState(wx.WXK_ALT))

[docs]    def GetPaneByWidget(self, window):
        """
        This version of L{GetPane} looks up a pane based on a
        'pane window'.

        :param `window`: a `wx.Window` derived window.

        :see: L{GetPane}
        """

        for p in self._panes:
            if p.window == window:
                return p

        return NonePaneInfo

[docs]    def GetPaneByName(self, name):
        """
        This version of L{GetPane} looks up a pane based on a
        'pane name'.

        :param `name`: the pane name.

        :see: L{GetPane}
        """

        for p in self._panes:
            if p.name == name:
                return p

        return NonePaneInfo

[docs]    def GetPane(self, item):
        """
        Looks up a L{AuiPaneInfo} structure based
        on the supplied window pointer. Upon failure, L{GetPane}
        returns an empty L{AuiPaneInfo}, a condition which can be checked
        by calling L{AuiPaneInfo.IsOk}.

        The pane info's structure may then be modified. Once a pane's
        info is modified, L{Update} must be called to
        realize the changes in the UI.

        :param `item`: either a pane name or a `wx.Window`.
        """

        if isinstance(item, basestring):
            return self.GetPaneByName(item)
        else:
            return self.GetPaneByWidget(item)

[docs]    def GetAllPanes(self):
        """ Returns a reference to all the pane info structures. """

        return self._panes

[docs]    def ShowPane(self, window, show):
        """
        Shows or hides a pane based on the window passed as input.

        :param `window`: a `wx.Window` derived window;
        :param `show`: ``True`` to show the pane, ``False`` otherwise.
        """

        p = self.GetPane(window)

        if p.IsOk():
            if p.IsNotebookPage():
                if show:

                    notebook = self._notebooks[p.notebook_id]
                    id = notebook.GetPageIndex(p.window)
                    if id >= 0:
                        notebook.SetSelection(id)
                    self.ShowPane(notebook, True)

            else:
                p.Show(show)

            if p.frame:
                p.frame.Raise()

            self.Update()

[docs]    def HitTest(self, x, y):
        """
        This is an internal function which determines
        which UI item the specified coordinates are over.

        :param `x`: specifies a x position in client coordinates;
        :param `y`: specifies a y position in client coordinates.
        """

        result = None

        for item in self._uiparts:
            # we are not interested in typeDock, because this space
            # isn't used to draw anything, just for measurements
            # besides, the entire dock area is covered with other
            # rectangles, which we are interested in.
            if item.type == AuiDockUIPart.typeDock:
                continue

            # if we already have a hit on a more specific item, we are not
            # interested in a pane hit.  If, however, we don't already have
            # a hit, returning a pane hit is necessary for some operations
            if item.type in [AuiDockUIPart.typePane, AuiDockUIPart.typePaneBorder] and result:
                continue

            # if the point is inside the rectangle, we have a hit
            if item.rect.Contains((x, y)):
                result = item

        return result

[docs]    def PaneHitTest(self, panes, pt):
        """
        Similar to L{HitTest}, but it checks in which L{AuiPaneInfo} rectangle the
        input point belongs to.

        :param `panes`: a list of L{AuiPaneInfo} instances;
        :param `pt`: a `wx.Point` object.
        """

        for paneInfo in panes:
            if paneInfo.IsDocked() and paneInfo.IsShown() and paneInfo.rect.Contains(pt):
                return paneInfo

        return NonePaneInfo

    # SetAGWFlags() and GetAGWFlags() allow the owner to set various
    # options which are global to AuiManager

[docs]    def SetAGWFlags(self, agwFlags):
        """
        This method is used to specify L{AuiManager}'s settings flags.

        :param `agwFlags`: specifies options which allow the frame management behavior
         to be modified. `agwFlags` can be one of the following style bits:

         ==================================== ==================================
         Flag name                            Description
         ==================================== ==================================
         ``AUI_MGR_ALLOW_FLOATING``           Allow floating of panes
         ``AUI_MGR_ALLOW_ACTIVE_PANE``        If a pane becomes active, "highlight" it in the interface
         ``AUI_MGR_TRANSPARENT_DRAG``         If the platform supports it, set transparency on a floating pane while it is dragged by the user
         ``AUI_MGR_TRANSPARENT_HINT``         If the platform supports it, show a transparent hint window when the user is about to dock a floating pane
         ``AUI_MGR_VENETIAN_BLINDS_HINT``     Show a "venetian blind" effect when the user is about to dock a floating pane
         ``AUI_MGR_RECTANGLE_HINT``           Show a rectangle hint effect when the user is about to dock a floating pane
         ``AUI_MGR_HINT_FADE``                If the platform supports it, the hint window will fade in and out
         ``AUI_MGR_NO_VENETIAN_BLINDS_FADE``  Disables the "venetian blind" fade in and out
         ``AUI_MGR_LIVE_RESIZE``              Live resize when the user drag a sash
         ``AUI_MGR_ANIMATE_FRAMES``           Fade-out floating panes when they are closed (all platforms which support frames transparency) and show a moving rectangle when they are docked (Windows < Vista and GTK only)
         ``AUI_MGR_AERO_DOCKING_GUIDES``      Use the new Aero-style bitmaps as docking guides
         ``AUI_MGR_PREVIEW_MINIMIZED_PANES``  Slide in and out minimized panes to preview them
         ``AUI_MGR_WHIDBEY_DOCKING_GUIDES``   Use the new Whidbey-style bitmaps as docking guides
         ``AUI_MGR_SMOOTH_DOCKING``           Performs a "smooth" docking of panes (a la PyQT)
         ``AUI_MGR_USE_NATIVE_MINIFRAMES``    Use miniframes with native caption bar as floating panes instead or custom drawn caption bars (forced on wxMac)
         ``AUI_MGR_AUTONB_NO_CAPTION``        Panes that merge into an automatic notebook will not have the pane caption visible
         ==================================== ==================================

         :note:

          If using the ``AUI_MGR_USE_NATIVE_MINIFRAMES``, double-clicking on a
          floating pane caption will not re-dock the pane, but simply maximize it (if
          L{AuiPaneInfo.MaximizeButton} has been set to ``True``) or do nothing.

        """

        self._agwFlags = agwFlags

        if len(self._guides) > 0:
            self.CreateGuideWindows()

        if self._hint_window and agwFlags & AUI_MGR_RECTANGLE_HINT == 0:
            self.CreateHintWindow()

[docs]    def GetAGWFlags(self):
        """
        Returns the current manager's flags.

        :see: L{SetAGWFlags} for a list of possible L{AuiManager} flags.
        """

        return self._agwFlags

[docs]    def SetManagedWindow(self, managed_window):
        """
        Called to specify the frame or window which is to be managed by L{AuiManager}.
        Frame management is not restricted to just frames. Child windows or custom
        controls are also allowed.

        :param `managed_window`: specifies the window which should be managed by
         the AUI manager.
        """

        if not managed_window:
            raise Exception("Specified managed window must be non-null. ")

        self._frame = managed_window
        self._frame.PushEventHandler(self)

        # if the owner is going to manage an MDI parent frame,
        # we need to add the MDI client window as the default
        # center pane

        if isinstance(self._frame, wx.MDIParentFrame):
            mdi_frame = self._frame
            client_window = mdi_frame.GetClientWindow()

            if not client_window:
                raise Exception("Client window is None!")

            self.AddPane(client_window, AuiPaneInfo().Name("mdiclient").
                         CenterPane().PaneBorder(False))

        elif isinstance(self._frame, tabmdi.AuiMDIParentFrame):

            mdi_frame = self._frame
            client_window = mdi_frame.GetClientWindow()

            if not client_window:
                raise Exception("Client window is None!")

            self.AddPane(client_window, AuiPaneInfo().Name("mdiclient").
                         CenterPane().PaneBorder(False))

[docs]    def GetManagedWindow(self):
        """ Returns the window being managed by L{AuiManager}. """

        return self._frame

[docs]    def SetFrame(self, managed_window):
        """
        Called to specify the frame or window which is to be managed by L{AuiManager}.
        Frame management is not restricted to just frames. Child windows or custom
        controls are also allowed.

        :param `managed_window`: specifies the window which should be managed by
         the AUI manager.

        :warning: This method is now deprecated, use L{SetManagedWindow} instead.
        """

        DeprecationWarning("This method is deprecated, use SetManagedWindow instead.")
        return self.SetManagedWindow(managed_window)

[docs]    def GetFrame(self):
        """
        Returns the window being managed by L{AuiManager}.

        :warning: This method is now deprecated, use L{GetManagedWindow} instead.
        """

        DeprecationWarning("This method is deprecated, use GetManagedWindow instead.")
        return self._frame

[docs]    def CreateGuideWindows(self):
        """ Creates the VS2005 HUD guide windows. """

        self.DestroyGuideWindows()

        self._guides.append(AuiDockingGuideInfo().Left().
                            Host(AuiSingleDockingGuide(self._frame, wx.LEFT)))
        self._guides.append(AuiDockingGuideInfo().Top().
                            Host(AuiSingleDockingGuide(self._frame, wx.TOP)))
        self._guides.append(AuiDockingGuideInfo().Right().
                            Host(AuiSingleDockingGuide(self._frame, wx.RIGHT)))
        self._guides.append(AuiDockingGuideInfo().Bottom().
                            Host(AuiSingleDockingGuide(self._frame, wx.BOTTOM)))
        self._guides.append(AuiDockingGuideInfo().Centre().
                            Host(AuiCenterDockingGuide(self._frame)))

[docs]    def DestroyGuideWindows(self):
        """ Destroys the VS2005 HUD guide windows. """

        for guide in self._guides:
            if guide.host:
                guide.host.Destroy()

        self._guides = []

[docs]    def CreateHintWindow(self):
        """ Creates the standard wxAUI hint window. """

        self.DestroyHintWindow()

        self._hint_window = AuiDockingHintWindow(self._frame)
        self._hint_window.SetBlindMode(self._agwFlags)

[docs]    def DestroyHintWindow(self):
        """ Destroys the standard wxAUI hint window. """

        if self._hint_window:

            self._hint_window.Destroy()
            self._hint_window = None

[docs]    def UnInit(self):
        """
        Uninitializes the framework and should be called before a managed frame or
        window is destroyed. L{UnInit} is usually called in the managed `wx.Frame` / `wx.Window`
        destructor.

        It is necessary to call this function before the managed frame or window is
        destroyed, otherwise the manager cannot remove its custom event handlers
        from a window.
        """

        if not self._frame:
            self.Destroy()
            return

        for klass in [self._frame] + list(self._frame.GetChildren()):
            handler = klass.GetEventHandler()
            if klass is not handler:
                if isinstance(handler, AuiManager):
                    klass.PopEventHandler(True)

[docs]    def GetArtProvider(self):
        """ Returns the current art provider being used. """

        return self._art

[docs]    def ProcessMgrEvent(self, event):
        """
        Process the AUI events sent to the manager.

        :param `event`: the event to process, an instance of L{AuiManagerEvent}.
        """

        # first, give the owner frame a chance to override
        if self._frame:
            if self._frame.GetEventHandler().ProcessEvent(event):
                return

        self.ProcessEvent(event)

[docs]    def FireEvent(self, evtType, pane, canVeto=False):
        """
        Fires one of the ``EVT_AUI_PANE_FLOATED``/``FLOATING``/``DOCKING``/``DOCKED``/``ACTIVATED`` event.

        :param `evtType`: one of the aforementioned events;
        :param `pane`: the L{AuiPaneInfo} instance associated to this event;
        :param `canVeto`: whether the event can be vetoed or not.
        """

        event = AuiManagerEvent(evtType)
        event.SetPane(pane)
        event.SetCanVeto(canVeto)
        self.ProcessMgrEvent(event)

        return event

[docs]    def CanUseModernDockArt(self):
        """
        Returns whether L{ModernDockArt} can be used (Windows XP / Vista / 7 only,
        requires Mark Hammonds's `pywin32` package).
        """

        if not _winxptheme:
            return False

        # Get the size of a small close button (themed)
        hwnd = self._frame.GetHandle()
        hTheme = winxptheme.OpenThemeData(hwnd, "Window")

        if not hTheme:
            return False

        return True

[docs]    def SetArtProvider(self, art_provider):
        """
        Instructs L{AuiManager} to use art provider specified by the parameter
        `art_provider` for all drawing calls. This allows plugable look-and-feel
        features.

        :param `art_provider`: a AUI dock art provider.

        :note: The previous art provider object, if any, will be deleted by L{AuiManager}.
        """

        # delete the last art provider, if any
        del self._art

        # assign the new art provider
        self._art = art_provider

        for pane in self.GetAllPanes():
            if pane.IsFloating() and pane.frame:
                pane.frame._mgr.SetArtProvider(art_provider)
                pane.frame._mgr.Update()

[docs]    def AddPane(self, window, arg1=None, arg2=None, target=None):
        """
        Tells the frame manager to start managing a child window. There
        are four versions of this function. The first verison allows the full spectrum
        of pane parameter possibilities (L{AddPane1}). The second version is used for
        simpler user interfaces which do not require as much configuration (L{AddPane2}).
        The L{AddPane3} version allows a drop position to be specified, which will determine
        where the pane will be added. The L{AddPane4} version allows to turn the target
        L{AuiPaneInfo} pane into a notebook and the added pane into a page.

        In wxPython, simply call L{AddPane}.

        :param `window`: the child window to manage;
        :param `arg1`: a L{AuiPaneInfo} or an integer value (direction);
        :param `arg2`: a L{AuiPaneInfo} or a `wx.Point` (drop position);
        :param `target`: a L{AuiPaneInfo} to be turned into a notebook
         and new pane added to it as a page. (additionally, target can be any pane in
         an existing notebook)
         """

        if target in self._panes:
            return self.AddPane4(window, arg1, target)

        if type(arg1) == type(1):
            # This Is Addpane2
            if arg1 is None:
                arg1 = wx.LEFT
            if arg2 is None:
                arg2 = ""
            return self.AddPane2(window, arg1, arg2)
        else:
            if isinstance(arg2, wx.Point):
                return self.AddPane3(window, arg1, arg2)
            else:
                return self.AddPane1(window, arg1)

[docs]    def AddPane1(self, window, pane_info):
        """ See comments on L{AddPane}. """

        # check if the pane has a valid window
        if not window:
            return False

        # check if the pane already exists
        if self.GetPane(pane_info.window).IsOk():
            return False

        # check if the pane name already exists, this could reveal a
        # bug in the library user's application
        already_exists = False
        if pane_info.name != "" and self.GetPane(pane_info.name).IsOk():
            warnings.warn("A pane with the name '%s' already exists in the manager!"%pane_info.name)
            already_exists = True

        # if the new pane is docked then we should undo maximize
        if pane_info.IsDocked():
            self.RestoreMaximizedPane()

        self._panes.append(pane_info)
        pinfo = self._panes[-1]

        # set the pane window
        pinfo.window = window

        # if the pane's name identifier is blank, create a random string
        if pinfo.name == "" or already_exists:
            pinfo.name = ("%s%08x%08x%08x")%(pinfo.window.GetName(), time.time(),
                                             time.clock(), len(self._panes))

        # set initial proportion (if not already set)
        if pinfo.dock_proportion == 0:
            pinfo.dock_proportion = 100000

        floating = isinstance(self._frame, AuiFloatingFrame)

        pinfo.buttons = []

        if not floating and pinfo.HasMinimizeButton():
            button = AuiPaneButton(AUI_BUTTON_MINIMIZE)
            pinfo.buttons.append(button)

        if not floating and pinfo.HasMaximizeButton():
            button = AuiPaneButton(AUI_BUTTON_MAXIMIZE_RESTORE)
            pinfo.buttons.append(button)

        if not floating and pinfo.HasPinButton():
            button = AuiPaneButton(AUI_BUTTON_PIN)
            pinfo.buttons.append(button)

        if pinfo.HasCloseButton():
            button = AuiPaneButton(AUI_BUTTON_CLOSE)
            pinfo.buttons.append(button)

        if pinfo.HasGripper():
            if isinstance(pinfo.window, auibar.AuiToolBar):
                # prevent duplicate gripper -- both AuiManager and AuiToolBar
                # have a gripper control.  The toolbar's built-in gripper
                # meshes better with the look and feel of the control than ours,
                # so turn AuiManager's gripper off, and the toolbar's on.

                tb = pinfo.window
                pinfo.SetFlag(AuiPaneInfo.optionGripper, False)
                tb.SetGripperVisible(True)

        if pinfo.window:
            if pinfo.best_size == wx.Size(-1, -1):
                pinfo.best_size = pinfo.window.GetClientSize()

            if isinstance(pinfo.window, wx.ToolBar):
                # GetClientSize() doesn't get the best size for
                # a toolbar under some newer versions of wxWidgets,
                # so use GetBestSize()
                pinfo.best_size = pinfo.window.GetBestSize()

                # this is needed for Win2000 to correctly fill toolbar backround
                # it should probably be repeated once system colour change happens
                if wx.Platform == "__WXMSW__" and pinfo.window.UseBgCol():
                    pinfo.window.SetBackgroundColour(self.GetArtProvider().GetColour(AUI_DOCKART_BACKGROUND_COLOUR))

            if pinfo.min_size != wx.Size(-1, -1):
                if pinfo.best_size.x < pinfo.min_size.x:
                    pinfo.best_size.x = pinfo.min_size.x
                if pinfo.best_size.y < pinfo.min_size.y:
                    pinfo.best_size.y = pinfo.min_size.y

        self._panes[-1] = pinfo
        if isinstance(window, auibar.AuiToolBar):
            window.SetAuiManager(self)

        return True

[docs]    def AddPane2(self, window, direction, caption):
        """ See comments on L{AddPane}. """

        pinfo = AuiPaneInfo()
        pinfo.Caption(caption)

        if direction == wx.TOP:
            pinfo.Top()
        elif direction == wx.BOTTOM:
            pinfo.Bottom()
        elif direction == wx.LEFT:
            pinfo.Left()
        elif direction == wx.RIGHT:
            pinfo.Right()
        elif direction == wx.CENTER:
            pinfo.CenterPane()

        return self.AddPane(window, pinfo)

[docs]    def AddPane3(self, window, pane_info, drop_pos):
        """ See comments on L{AddPane}. """

        if not self.AddPane(window, pane_info):
            return False

        pane = self.GetPane(window)
        indx = self._panes.index(pane)

        ret, pane = self.DoDrop(self._docks, self._panes, pane, drop_pos, wx.Point(0, 0))
        self._panes[indx] = pane

        return True

[docs]    def AddPane4(self, window, pane_info, target):
        """ See comments on L{AddPane}. """

        if not self.AddPane(window, pane_info):
            return False

        paneInfo = self.GetPane(window)

        if not paneInfo.IsNotebookDockable():
            return self.AddPane1(window, pane_info)
        if not target.IsNotebookDockable() and not target.IsNotebookControl():
            return self.AddPane1(window, pane_info)

        if not target.HasNotebook():
            self.CreateNotebookBase(self._panes, target)

        # Add new item to notebook
        paneInfo.NotebookPage(target.notebook_id)

        # we also want to remove our captions sometimes
        self.RemoveAutoNBCaption(paneInfo)
        self.UpdateNotebook()

        return True

[docs]    def InsertPane(self, window, pane_info, insert_level=AUI_INSERT_PANE):
        """
        This method is used to insert either a previously unmanaged pane window
        into the frame manager, or to insert a currently managed pane somewhere else.
        L{InsertPane} will push all panes, rows, or docks aside and insert the window
        into the position specified by `pane_info`.

        Because `pane_info` can specify either a pane, dock row, or dock layer, the
        `insert_level` parameter is used to disambiguate this. The parameter `insert_level`
        can take a value of ``AUI_INSERT_PANE``, ``AUI_INSERT_ROW`` or ``AUI_INSERT_DOCK``.

        :param `window`: the window to be inserted and managed;
        :param `pane_info`: the insert location for the new window;
        :param `insert_level`: the insertion level of the new pane.
        """

        if not window:
            raise Exception("Invalid window passed to InsertPane.")

        # shift the panes around, depending on the insert level
        if insert_level == AUI_INSERT_PANE:
            self._panes = DoInsertPane(self._panes, pane_info.dock_direction,
                                       pane_info.dock_layer, pane_info.dock_row,
                                       pane_info.dock_pos)

        elif insert_level == AUI_INSERT_ROW:
            self._panes = DoInsertDockRow(self._panes, pane_info.dock_direction,
                                          pane_info.dock_layer, pane_info.dock_row)

        elif insert_level == AUI_INSERT_DOCK:
            self._panes = DoInsertDockLayer(self._panes, pane_info.dock_direction,
                                            pane_info.dock_layer)

        # if the window already exists, we are basically just moving/inserting the
        # existing window.  If it doesn't exist, we need to add it and insert it
        existing_pane = self.GetPane(window)
        indx = self._panes.index(existing_pane)

        if not existing_pane.IsOk():

            return self.AddPane(window, pane_info)

        else:

            if pane_info.IsFloating():
                existing_pane.Float()
                if pane_info.floating_pos != wx.Point(-1, -1):
                    existing_pane.FloatingPosition(pane_info.floating_pos)
                if pane_info.floating_size != wx.Size(-1, -1):
                    existing_pane.FloatingSize(pane_info.floating_size)
            else:
                # if the new pane is docked then we should undo maximize
                self.RestoreMaximizedPane()

                existing_pane.Direction(pane_info.dock_direction)
                existing_pane.Layer(pane_info.dock_layer)
                existing_pane.Row(pane_info.dock_row)
                existing_pane.Position(pane_info.dock_pos)

            self._panes[indx] = existing_pane

        return True

[docs]    def DetachPane(self, window):
        """
        Tells the L{AuiManager} to stop managing the pane specified
        by `window`. The window, if in a floated frame, is reparented to the frame
        managed by L{AuiManager}.

        :param `window`: the window to be un-managed.
        """

        for p in self._panes:
            if p.window == window:
                if p.frame:
                    # we have a floating frame which is being detached. We need to
                    # reparent it to self._frame and destroy the floating frame

                    # reduce flicker
                    p.window.SetSize((1, 1))
                    if p.frame.IsShown():
                        p.frame.Show(False)

                    if self._action_window == p.frame:
                        self._action_window = None

                    # reparent to self._frame and destroy the pane
                    p.window.Reparent(self._frame)
                    p.frame.SetSizer(None)
                    p.frame.Destroy()
                    p.frame = None

                elif p.IsNotebookPage():
                    notebook = self._notebooks[p.notebook_id]
                    id = notebook.GetPageIndex(p.window)
                    notebook.RemovePage(id)

                # make sure there are no references to this pane in our uiparts,
                # just in case the caller doesn't call Update() immediately after
                # the DetachPane() call.  This prevets obscure crashes which would
                # happen at window repaint if the caller forgets to call Update()
                counter = 0
                for pi in xrange(len(self._uiparts)):
                    part = self._uiparts[counter]
                    if part.pane == p:
                        self._uiparts.pop(counter)
                        counter -= 1

                    counter += 1

                self._panes.remove(p)
                return True

        return False

[docs]    def ClosePane(self, pane_info):
        """
        Destroys or hides the pane depending on its flags.

        :param `pane_info`: a L{AuiPaneInfo} instance.
        """

        # if we were maximized, restore
        if pane_info.IsMaximized():
            self.RestorePane(pane_info)

        if pane_info.frame:
            if self._agwFlags & AUI_MGR_ANIMATE_FRAMES:
                pane_info.frame.FadeOut()

        # first, hide the window
        if pane_info.window and pane_info.window.IsShown():
            pane_info.window.Show(False)

        # make sure that we are the parent of this window
        if pane_info.window and pane_info.window.GetParent() != self._frame:
            pane_info.window.Reparent(self._frame)

        # if we have a frame, destroy it
        if pane_info.frame:
            pane_info.frame.Destroy()
            pane_info.frame = None

        elif pane_info.IsNotebookPage():
            # if we are a notebook page, remove ourselves...
            # the  code would index out of bounds
            # if the last page of a sub-notebook was closed
            # because the notebook would be deleted, before this
            # code is executed.
            # This code just prevents an out-of bounds error.
            if self._notebooks:
                nid = pane_info.notebook_id
                if nid >= 0 and nid < len(self._notebooks):
                    notebook = self._notebooks[nid]
                    page_idx = notebook.GetPageIndex(pane_info.window)
                    if page_idx >= 0:
                        notebook.RemovePage(page_idx)

        # now we need to either destroy or hide the pane
        to_destroy = 0
        if pane_info.IsDestroyOnClose():
            to_destroy = pane_info.window
            self.DetachPane(to_destroy)
        else:
            if isinstance(pane_info.window, auibar.AuiToolBar) and pane_info.IsFloating():
                tb = pane_info.window
                if pane_info.dock_direction in [AUI_DOCK_LEFT, AUI_DOCK_RIGHT]:
                    tb.SetAGWWindowStyleFlag(tb.GetAGWWindowStyleFlag() | AUI_TB_VERTICAL)

            pane_info.Dock().Hide()

        if pane_info.IsNotebookControl():

            notebook = self._notebooks[pane_info.notebook_id]
            while notebook.GetPageCount():
                window = notebook.GetPage(0)
                notebook.RemovePage(0)
                info = self.GetPane(window)
                if info.IsOk():
                    info.notebook_id = -1
                    info.dock_direction = AUI_DOCK_NONE
                    # Note: this could change our paneInfo reference ...
                    self.ClosePane(info)

        if to_destroy:
            to_destroy.Destroy()

[docs]    def MaximizePane(self, pane_info, savesizes=True):
        """
        Maximizes the input pane.

        :param `pane_info`: a L{AuiPaneInfo} instance.
        :param `savesizes`: whether to save previous dock sizes.
        """

        if savesizes:
            self.SavePreviousDockSizes(pane_info)

        for p in self._panes:

            # save hidden state
            p.SetFlag(p.savedHiddenState, p.HasFlag(p.optionHidden))

            if not p.IsToolbar() and not p.IsFloating():
                p.Restore()

                # hide the pane, because only the newly
                # maximized pane should show
                p.Hide()

        pane_info.previousDockPos = pane_info.dock_pos

        # mark ourselves maximized
        pane_info.Maximize()
        pane_info.Show()
        self._has_maximized = True

        # last, show the window
        if pane_info.window and not pane_info.window.IsShown():
            pane_info.window.Show(True)

[docs]    def SavePreviousDockSizes(self, pane_info):
        """
        Stores the previous dock sizes, to be used in a "restore" action later.

        :param `pane_info`: a L{AuiPaneInfo} instance.
        """

        for d in self._docks:
            if not d.toolbar:
                for p in d.panes:
                    p.previousDockSize = d.size
                    if pane_info is not p:
                        p.SetFlag(p.needsRestore, True)

[docs]    def RestorePane(self, pane_info):
        """
        Restores the input pane from a previous maximized or minimized state.

        :param `pane_info`: a L{AuiPaneInfo} instance.
        """

        # restore all the panes
        for p in self._panes:
            if not p.IsToolbar():
                p.SetFlag(p.optionHidden, p.HasFlag(p.savedHiddenState))

        pane_info.SetFlag(pane_info.needsRestore, True)

        # mark ourselves non-maximized
        pane_info.Restore()
        self._has_maximized = False
        self._has_minimized = False

        # last, show the window
        if pane_info.window and not pane_info.window.IsShown():
            pane_info.window.Show(True)

[docs]    def RestoreMaximizedPane(self):
        """ Restores the current maximized pane (if any). """

        # restore all the panes
        for p in self._panes:
            if p.IsMaximized():
                self.RestorePane(p)
                break

[docs]    def ActivatePane(self, window):
        """
        Activates the pane to which `window` is associated.

        :param `window`: a `wx.Window` derived window.
        """

        if self.GetAGWFlags() & AUI_MGR_ALLOW_ACTIVE_PANE:
            while window:
                ret, self._panes = SetActivePane(self._panes, window)
                if ret:
                    break

                window = window.GetParent()

            self.RefreshCaptions()
            self.FireEvent(wxEVT_AUI_PANE_ACTIVATED, window, canVeto=False)

[docs]    def CreateNotebook(self):
        """
        Creates an automatic L{AuiNotebook} when a pane is docked on
        top of another pane.
        """

        notebook = auibook.AuiNotebook(self._frame, -1, wx.Point(0, 0), wx.Size(0, 0), agwStyle=self._autoNBStyle)

        # This is so we can get the tab-drag event.
        notebook.GetAuiManager().SetMasterManager(self)
        notebook.SetArtProvider(self._autoNBTabArt.Clone())
        self._notebooks.append(notebook)

        return notebook

[docs]    def SetAutoNotebookTabArt(self, art):
        """
        Sets the default tab art provider for automatic notebooks.

        :param `art`: a tab art provider.
        """

        for nb in self._notebooks:
            nb.SetArtProvider(art.Clone())
            nb.Refresh()
            nb.Update()

        self._autoNBTabArt = art

[docs]    def GetAutoNotebookTabArt(self):
        """ Returns the default tab art provider for automatic notebooks. """

        return self._autoNBTabArt

[docs]    def SetAutoNotebookStyle(self, agwStyle):
        """
        Sets the default AGW-specific window style for automatic notebooks.

        :param `agwStyle`: the underlying L{AuiNotebook} window style.
         This can be a combination of the following bits:

         ==================================== ==================================
         Flag name                            Description
         ==================================== ==================================
         ``AUI_NB_TOP``                       With this style, tabs are drawn along the top of the notebook
         ``AUI_NB_LEFT``                      With this style, tabs are drawn along the left of the notebook. Not implemented yet.
         ``AUI_NB_RIGHT``                     With this style, tabs are drawn along the right of the notebook. Not implemented yet.
         ``AUI_NB_BOTTOM``                    With this style, tabs are drawn along the bottom of the notebook
         ``AUI_NB_TAB_SPLIT``                 Allows the tab control to be split by dragging a tab
         ``AUI_NB_TAB_MOVE``                  Allows a tab to be moved horizontally by dragging
         ``AUI_NB_TAB_EXTERNAL_MOVE``         Allows a tab to be moved to another tab control
         ``AUI_NB_TAB_FIXED_WIDTH``           With this style, all tabs have the same width
         ``AUI_NB_SCROLL_BUTTONS``            With this style, left and right scroll buttons are displayed
         ``AUI_NB_WINDOWLIST_BUTTON``         With this style, a drop-down list of windows is available
         ``AUI_NB_CLOSE_BUTTON``              With this style, a close button is available on the tab bar
         ``AUI_NB_CLOSE_ON_ACTIVE_TAB``       With this style, a close button is available on the active tab
         ``AUI_NB_CLOSE_ON_ALL_TABS``         With this style, a close button is available on all tabs
         ``AUI_NB_MIDDLE_CLICK_CLOSE``        Allows to close L{AuiNotebook} tabs by mouse middle button click
         ``AUI_NB_SUB_NOTEBOOK``              This style is used by {AuiManager} to create automatic AuiNotebooks
         ``AUI_NB_HIDE_ON_SINGLE_TAB``        Hides the tab window if only one tab is present
         ``AUI_NB_SMART_TABS``                Use Smart Tabbing, like ``Alt`` + ``Tab`` on Windows
         ``AUI_NB_USE_IMAGES_DROPDOWN``       Uses images on dropdown window list menu instead of check items
         ``AUI_NB_CLOSE_ON_TAB_LEFT``         Draws the tab close button on the left instead of on the right (a la Camino browser)
         ``AUI_NB_TAB_FLOAT``                 Allows the floating of single tabs. Known limitation: when the notebook is more or less full screen, tabs cannot be dragged far enough outside of the notebook to become floating pages
         ``AUI_NB_DRAW_DND_TAB``              Draws an image representation of a tab while dragging (on by default)
         ==================================== ==================================

        """

        for nb in self._notebooks:
            nb.SetAGWWindowStyleFlag(agwStyle)
            nb.Refresh()
            nb.Update()

        self._autoNBStyle = agwStyle

[docs]    def GetAutoNotebookStyle(self):
        """
        Returns the default AGW-specific window style for automatic notebooks.

        :see: L{SetAutoNotebookStyle} method for a list of possible styles.
        """

        return self._autoNBStyle

[docs]    def SavePaneInfo(self, pane):
        """
        This method is similar to L{SavePerspective}, with the exception
        that it only saves information about a single pane. It is used in
        combination with L{LoadPaneInfo}.

        :param `pane`: a L{AuiPaneInfo} instance to save.
        """

        result = "name=" + EscapeDelimiters(pane.name) + ";"
        result += "caption=" + EscapeDelimiters(pane.caption) + ";"

        result += "state=%u;"%pane.state
        result += "dir=%d;"%pane.dock_direction
        result += "layer=%d;"%pane.dock_layer
        result += "row=%d;"%pane.dock_row
        result += "pos=%d;"%pane.dock_pos
        result += "prop=%d;"%pane.dock_proportion
        result += "bestw=%d;"%pane.best_size.x
        result += "besth=%d;"%pane.best_size.y
        result += "minw=%d;"%pane.min_size.x
        result += "minh=%d;"%pane.min_size.y
        result += "maxw=%d;"%pane.max_size.x
        result += "maxh=%d;"%pane.max_size.y
        result += "floatx=%d;"%pane.floating_pos.x
        result += "floaty=%d;"%pane.floating_pos.y
        result += "floatw=%d;"%pane.floating_size.x
        result += "floath=%d;"%pane.floating_size.y
        result += "notebookid=%d;"%pane.notebook_id
        result += "transparent=%d"%pane.transparent

        return result

[docs]    def LoadPaneInfo(self, pane_part, pane):
        """
        This method is similar to to L{LoadPerspective}, with the exception that
        it only loads information about a single pane. It is used in combination
        with L{SavePaneInfo}.

        :param `pane_part`: the string to analyze;
        :param `pane`: the L{AuiPaneInfo} structure in which to load `pane_part`.
        """

        # replace escaped characters so we can
        # split up the string easily
        pane_part = pane_part.replace("\\|", "\a")
        pane_part = pane_part.replace("\\;", "\b")

        options = pane_part.split(";")
        for items in options:

            val_name, value = items.split("=")
            val_name = val_name.strip()

            if val_name == "name":
                pane.name = value
            elif val_name == "caption":
                pane.caption = value
            elif val_name == "state":
                pane.state = int(value)
            elif val_name == "dir":
                pane.dock_direction = int(value)
            elif val_name == "layer":
                pane.dock_layer = int(value)
            elif val_name == "row":
                pane.dock_row = int(value)
            elif val_name == "pos":
                pane.dock_pos = int(value)
            elif val_name == "prop":
                pane.dock_proportion = int(value)
            elif val_name == "bestw":
                pane.best_size.x = int(value)
            elif val_name == "besth":
                pane.best_size.y = int(value)
                pane.best_size = wx.Size(pane.best_size.x, pane.best_size.y)
            elif val_name == "minw":
                pane.min_size.x = int(value)
            elif val_name == "minh":
                pane.min_size.y = int(value)
                pane.min_size = wx.Size(pane.min_size.x, pane.min_size.y)
            elif val_name == "maxw":
                pane.max_size.x = int(value)
            elif val_name == "maxh":
                pane.max_size.y = int(value)
                pane.max_size = wx.Size(pane.max_size.x, pane.max_size.y)
            elif val_name == "floatx":
                pane.floating_pos.x = int(value)
            elif val_name == "floaty":
                pane.floating_pos.y = int(value)
                pane.floating_pos = wx.Point(pane.floating_pos.x, pane.floating_pos.y)
            elif val_name == "floatw":
                pane.floating_size.x = int(value)
            elif val_name == "floath":
                pane.floating_size.y = int(value)
                pane.floating_size = wx.Size(pane.floating_size.x, pane.floating_size.y)
            elif val_name == "notebookid":
                pane.notebook_id = int(value)
            elif val_name == "transparent":
                pane.transparent = int(value)
            else:
                raise Exception("Bad perspective string")

        # replace escaped characters so we can
        # split up the string easily
        pane.name = pane.name.replace("\a", "|")
        pane.name = pane.name.replace("\b", ";")
        pane.caption = pane.caption.replace("\a", "|")
        pane.caption = pane.caption.replace("\b", ";")
        pane_part = pane_part.replace("\a", "|")
        pane_part = pane_part.replace("\b", ";")

        return pane

[docs]    def SavePerspective(self):
        """
        Saves the entire user interface layout into an encoded string, which can then
        be stored by the application (probably using `wx.Config`).

        When a perspective is restored using L{LoadPerspective}, the entire user
        interface will return to the state it was when the perspective was saved.
        """

        result = "layout2|"

        for pane in self._panes:
            result += self.SavePaneInfo(pane) + "|"

        for dock in self._docks:
            result = result + ("dock_size(%d,%d,%d)=%d|")%(dock.dock_direction,
                                                           dock.dock_layer,
                                                           dock.dock_row,
                                                           dock.size)
        return result

[docs]    def LoadPerspective(self, layout, update=True):
        """
        Loads a layout which was saved with L{SavePerspective}.

        If the `update` flag parameter is ``True``, L{Update} will be
        automatically invoked, thus realizing the saved perspective on screen.

        :param `layout`: a string which contains a saved AUI layout;
        :param `update`: whether to update immediately the window or not.
        """

        input = layout

        # check layout string version
        #    'layout1' = wxAUI 0.9.0 - wxAUI 0.9.2
        #    'layout2' = wxAUI 0.9.2 (wxWidgets 2.8)
        index = input.find("|")
        part = input[0:index].strip()
        input = input[index+1:]

        if part != "layout2":
            return False

        # mark all panes currently managed as docked and hidden
        for pane in self._panes:
            pane.Dock().Hide()

        # clear out the dock array; this will be reconstructed
        self._docks = []

        # replace escaped characters so we can
        # split up the string easily
        input = input.replace("\\|", "\a")
        input = input.replace("\\;", "\b")

        while 1:

            pane = AuiPaneInfo()
            index = input.find("|")
            pane_part = input[0:index].strip()
            input = input[index+1:]

            # if the string is empty, we're done parsing
            if pane_part == "":
                break

            if pane_part[0:9] == "dock_size":
                index = pane_part.find("=")
                val_name = pane_part[0:index]
                value = pane_part[index+1:]

                index = val_name.find("(")
                piece = val_name[index+1:]
                index = piece.find(")")
                piece = piece[0:index]

                vals = piece.split(",")
                dir = int(vals[0])
                layer = int(vals[1])
                row = int(vals[2])
                size = int(value)

                dock = AuiDockInfo()
                dock.dock_direction = dir
                dock.dock_layer = layer
                dock.dock_row = row
                dock.size = size
                self._docks.append(dock)

                continue

            # Undo our escaping as LoadPaneInfo needs to take an unescaped
            # name so it can be called by external callers
            pane_part = pane_part.replace("\a", "|")
            pane_part = pane_part.replace("\b", ";")

            pane = self.LoadPaneInfo(pane_part, pane)

            p = self.GetPane(pane.name)

            if not p.IsOk():
                if pane.IsNotebookControl():
                    # notebook controls - auto add...
                    self._panes.append(pane)
                    indx = self._panes.index(pane)
                else:
                    # the pane window couldn't be found
                    # in the existing layout -- skip it
                    continue

            else:
                indx = self._panes.index(p)
            pane.window = p.window
            pane.frame = p.frame
            pane.buttons = p.buttons
            self._panes[indx] = pane

            if isinstance(pane.window, auibar.AuiToolBar) and (pane.IsFloatable() or pane.IsDockable()):
                pane.window.SetGripperVisible(True)

        if update:
            self.Update()

        return True

[docs]    def GetPanePositionsAndSizes(self, dock):
        """
        Returns all the panes positions and sizes in a dock.

        :param `dock`: a L{AuiDockInfo} instance.
        """

        caption_size = self._art.GetMetric(AUI_DOCKART_CAPTION_SIZE)
        pane_border_size = self._art.GetMetric(AUI_DOCKART_PANE_BORDER_SIZE)
        gripper_size = self._art.GetMetric(AUI_DOCKART_GRIPPER_SIZE)

        positions = []
        sizes = []

        action_pane = -1
        pane_count = len(dock.panes)

        # find the pane marked as our action pane
        for pane_i in xrange(pane_count):
            pane = dock.panes[pane_i]
            if pane.HasFlag(AuiPaneInfo.actionPane):
                if action_pane != -1:
                    raise Exception("Too many action panes!")
                action_pane = pane_i

        # set up each panes default position, and
        # determine the size (width or height, depending
        # on the dock's orientation) of each pane
        for pane in dock.panes:
            positions.append(pane.dock_pos)
            size = 0

            if pane.HasBorder():
                size += pane_border_size*2

            if dock.IsHorizontal():
                if pane.HasGripper() and not pane.HasGripperTop():
                    size += gripper_size

                if pane.HasCaptionLeft():
                    size += caption_size

                size += pane.best_size.x

            else:
                if pane.HasGripper() and pane.HasGripperTop():
                    size += gripper_size

                if pane.HasCaption() and not pane.HasCaptionLeft():
                    size += caption_size

                size += pane.best_size.y

            sizes.append(size)

        # if there is no action pane, just return the default
        # positions (as specified in pane.pane_pos)
        if action_pane == -1:
            return positions, sizes

        offset = 0
        for pane_i in xrange(action_pane-1, -1, -1):
            amount = positions[pane_i+1] - (positions[pane_i] + sizes[pane_i])
            if amount >= 0:
                offset += amount
            else:
                positions[pane_i] -= -amount

            offset += sizes[pane_i]

        # if the dock mode is fixed, make sure none of the panes
        # overlap we will bump panes that overlap
        offset = 0
        for pane_i in xrange(action_pane, pane_count):
            amount = positions[pane_i] - offset
            if amount >= 0:
                offset += amount
            else:
                positions[pane_i] += -amount

            offset += sizes[pane_i]

        return positions, sizes

[docs]    def LayoutAddPane(self, cont, dock, pane, uiparts, spacer_only):
        """
        Adds a pane into the existing layout (in an existing dock).

        :param `cont`: a `wx.Sizer` object;
        :param `dock`: the L{AuiDockInfo} structure in which to add the pane;
        :param `pane`: the L{AuiPaneInfo} instance to add to the dock;
        :param `uiparts`: a list of UI parts in the interface;
        :param `spacer_only`: whether to add a simple spacer or a real window.
        """

        sizer_item = wx.SizerItem()
        caption_size = self._art.GetMetric(AUI_DOCKART_CAPTION_SIZE)
        gripper_size = self._art.GetMetric(AUI_DOCKART_GRIPPER_SIZE)
        pane_border_size = self._art.GetMetric(AUI_DOCKART_PANE_BORDER_SIZE)
        pane_button_size = self._art.GetMetric(AUI_DOCKART_PANE_BUTTON_SIZE)

        # find out the orientation of the item (orientation for panes
        # is the same as the dock's orientation)

        if dock.IsHorizontal():
            orientation = wx.HORIZONTAL
        else:
            orientation = wx.VERTICAL

        # this variable will store the proportion
        # value that the pane will receive
        pane_proportion = pane.dock_proportion

        horz_pane_sizer = wx.BoxSizer(wx.HORIZONTAL)
        vert_pane_sizer = wx.BoxSizer(wx.VERTICAL)

        if pane.HasGripper():

            part = AuiDockUIPart()
            if pane.HasGripperTop():
                sizer_item = vert_pane_sizer.Add((1, gripper_size), 0, wx.EXPAND)
            else:
                sizer_item = horz_pane_sizer.Add((gripper_size, 1), 0, wx.EXPAND)

            part.type = AuiDockUIPart.typeGripper
            part.dock = dock
            part.pane = pane
            part.button = None
            part.orientation = orientation
            part.cont_sizer = horz_pane_sizer
            part.sizer_item = sizer_item
            uiparts.append(part)

        button_count = len(pane.buttons)
        button_width_total = button_count*pane_button_size
        if button_count >= 1:
            button_width_total += 3

        caption, captionLeft = pane.HasCaption(), pane.HasCaptionLeft()
        button_count = len(pane.buttons)

        if captionLeft:
            caption_sizer = wx.BoxSizer(wx.VERTICAL)

            # add pane buttons to the caption
            dummy_parts = []
            for btn_id in xrange(len(pane.buttons)-1, -1, -1):
                sizer_item = caption_sizer.Add((caption_size, pane_button_size), 0, wx.EXPAND)
                part = AuiDockUIPart()
                part.type = AuiDockUIPart.typePaneButton
                part.dock = dock
                part.pane = pane
                part.button = pane.buttons[btn_id]
                part.orientation = orientation
                part.cont_sizer = caption_sizer
                part.sizer_item = sizer_item
                dummy_parts.append(part)

            sizer_item = caption_sizer.Add((caption_size, 1), 1, wx.EXPAND)
            vert_pane_sizer = wx.BoxSizer(wx.HORIZONTAL)

            # create the caption sizer
            part = AuiDockUIPart()

            part.type = AuiDockUIPart.typeCaption
            part.dock = dock
            part.pane = pane
            part.button = None
            part.orientation = orientation
            part.cont_sizer = vert_pane_sizer
            part.sizer_item = sizer_item
            caption_part_idx = len(uiparts)
            uiparts.append(part)
            uiparts.extend(dummy_parts)

        elif caption:

            caption_sizer = wx.BoxSizer(wx.HORIZONTAL)
            sizer_item = caption_sizer.Add((1, caption_size), 1, wx.EXPAND)

            # create the caption sizer
            part = AuiDockUIPart()

            part.type = AuiDockUIPart.typeCaption
            part.dock = dock
            part.pane = pane
            part.button = None
            part.orientation = orientation
            part.cont_sizer = vert_pane_sizer
            part.sizer_item = sizer_item
            caption_part_idx = len(uiparts)
            uiparts.append(part)

            # add pane buttons to the caption
            for button in pane.buttons:
                sizer_item = caption_sizer.Add((pane_button_size, caption_size), 0, wx.EXPAND)
                part = AuiDockUIPart()
                part.type = AuiDockUIPart.typePaneButton
                part.dock = dock
                part.pane = pane
                part.button = button
                part.orientation = orientation
                part.cont_sizer = caption_sizer
                part.sizer_item = sizer_item
                uiparts.append(part)

        if caption or captionLeft:
            # if we have buttons, add a little space to the right
            # of them to ease visual crowding
            if button_count >= 1:
                if captionLeft:
                    caption_sizer.Add((caption_size, 3), 0, wx.EXPAND)
                else:
                    caption_sizer.Add((3, caption_size), 0, wx.EXPAND)

            # add the caption sizer
            sizer_item = vert_pane_sizer.Add(caption_sizer, 0, wx.EXPAND)
            uiparts[caption_part_idx].sizer_item = sizer_item

        # add the pane window itself
        if spacer_only or not pane.window:
            sizer_item = vert_pane_sizer.Add((1, 1), 1, wx.EXPAND)
        else:
            sizer_item = vert_pane_sizer.Add(pane.window, 1, wx.EXPAND)
            vert_pane_sizer.SetItemMinSize(pane.window, (1, 1))

        part = AuiDockUIPart()
        part.type = AuiDockUIPart.typePane
        part.dock = dock
        part.pane = pane
        part.button = None
        part.orientation = orientation
        part.cont_sizer = vert_pane_sizer
        part.sizer_item = sizer_item
        uiparts.append(part)

        # determine if the pane should have a minimum size if the pane is
        # non-resizable (fixed) then we must set a minimum size. Alternatively,
        # if the pane.min_size is set, we must use that value as well

        min_size = pane.min_size
        if pane.IsFixed():
            if min_size == wx.Size(-1, -1):
                min_size = pane.best_size
                pane_proportion = 0

        if min_size != wx.Size(-1, -1):
            vert_pane_sizer.SetItemMinSize(len(vert_pane_sizer.GetChildren())-1, (min_size.x, min_size.y))

        # add the vertical/horizontal sizer (caption, pane window) to the
        # horizontal sizer (gripper, vertical sizer)
        horz_pane_sizer.Add(vert_pane_sizer, 1, wx.EXPAND)

        # finally, add the pane sizer to the dock sizer
        if pane.HasBorder():
            # allowing space for the pane's border
            sizer_item = cont.Add(horz_pane_sizer, pane_proportion,
                                  wx.EXPAND | wx.ALL, pane_border_size)
            part = AuiDockUIPart()
            part.type = AuiDockUIPart.typePaneBorder
            part.dock = dock
            part.pane = pane
            part.button = None
            part.orientation = orientation
            part.cont_sizer = cont
            part.sizer_item = sizer_item
            uiparts.append(part)
        else:
            sizer_item = cont.Add(horz_pane_sizer, pane_proportion, wx.EXPAND)

        return uiparts

[docs]    def LayoutAddDock(self, cont, dock, uiparts, spacer_only):
        """
        Adds a dock into the existing layout.

        :param `cont`: a `wx.Sizer` object;
        :param `dock`: the L{AuiDockInfo} structure to add to the layout;
        :param `uiparts`: a list of UI parts in the interface;
        :param `spacer_only`: whether to add a simple spacer or a real window.
        """

        sizer_item = wx.SizerItem()
        part = AuiDockUIPart()

        sash_size = self._art.GetMetric(AUI_DOCKART_SASH_SIZE)
        orientation = (dock.IsHorizontal() and [wx.HORIZONTAL] or [wx.VERTICAL])[0]

        # resizable bottom and right docks have a sash before them
        if not self._has_maximized and not dock.fixed and \
           dock.dock_direction in [AUI_DOCK_BOTTOM, AUI_DOCK_RIGHT]:

            sizer_item = cont.Add((sash_size, sash_size), 0, wx.EXPAND)

            part.type = AuiDockUIPart.typeDockSizer
            part.orientation = orientation
            part.dock = dock
            part.pane = None
            part.button = None
            part.cont_sizer = cont
            part.sizer_item = sizer_item
            uiparts.append(part)

        # create the sizer for the dock
        dock_sizer = wx.BoxSizer(orientation)

        # add each pane to the dock
        has_maximized_pane = False
        pane_count = len(dock.panes)

        if dock.fixed:

            # figure out the real pane positions we will
            # use, without modifying the each pane's pane_pos member
            pane_positions, pane_sizes = self.GetPanePositionsAndSizes(dock)

            offset = 0
            for pane_i in xrange(pane_count):

                pane = dock.panes[pane_i]
                pane_pos = pane_positions[pane_i]

                if pane.IsMaximized():
                    has_maximized_pane = True

                amount = pane_pos - offset
                if amount > 0:

                    if dock.IsVertical():
                        sizer_item = dock_sizer.Add((1, amount), 0, wx.EXPAND)
                    else:
                        sizer_item = dock_sizer.Add((amount, 1), 0, wx.EXPAND)

                    part = AuiDockUIPart()
                    part.type = AuiDockUIPart.typeBackground
                    part.dock = dock
                    part.pane = None
                    part.button = None
                    part.orientation = (orientation==wx.HORIZONTAL and \
                                        [wx.VERTICAL] or [wx.HORIZONTAL])[0]
                    part.cont_sizer = dock_sizer
                    part.sizer_item = sizer_item
                    uiparts.append(part)

                    offset = offset + amount

                uiparts = self.LayoutAddPane(dock_sizer, dock, pane, uiparts, spacer_only)

                offset = offset + pane_sizes[pane_i]

            # at the end add a very small stretchable background area
            sizer_item = dock_sizer.Add((0, 0), 1, wx.EXPAND)
            part = AuiDockUIPart()
            part.type = AuiDockUIPart.typeBackground
            part.dock = dock
            part.pane = None
            part.button = None
            part.orientation = orientation
            part.cont_sizer = dock_sizer
            part.sizer_item = sizer_item
            uiparts.append(part)

        else:

            for pane_i in xrange(pane_count):

                pane = dock.panes[pane_i]

                if pane.IsMaximized():
                    has_maximized_pane = True

                # if this is not the first pane being added,
                # we need to add a pane sizer
                if not self._has_maximized and pane_i > 0:
                    sizer_item = dock_sizer.Add((sash_size, sash_size), 0, wx.EXPAND)
                    part = AuiDockUIPart()
                    part.type = AuiDockUIPart.typePaneSizer
                    part.dock = dock
                    part.pane = dock.panes[pane_i-1]
                    part.button = None
                    part.orientation = (orientation==wx.HORIZONTAL and \
                                        [wx.VERTICAL] or [wx.HORIZONTAL])[0]
                    part.cont_sizer = dock_sizer
                    part.sizer_item = sizer_item
                    uiparts.append(part)

                uiparts = self.LayoutAddPane(dock_sizer, dock, pane, uiparts, spacer_only)

        if dock.dock_direction == AUI_DOCK_CENTER or has_maximized_pane:
            sizer_item = cont.Add(dock_sizer, 1, wx.EXPAND)
        else:
            sizer_item = cont.Add(dock_sizer, 0, wx.EXPAND)

        part = AuiDockUIPart()
        part.type = AuiDockUIPart.typeDock
        part.dock = dock
        part.pane = None
        part.button = None
        part.orientation = orientation
        part.cont_sizer = cont
        part.sizer_item = sizer_item
        uiparts.append(part)

        if dock.IsHorizontal():
            cont.SetItemMinSize(dock_sizer, (0, dock.size))
        else:
            cont.SetItemMinSize(dock_sizer, (dock.size, 0))

        #  top and left docks have a sash after them
        if not self._has_maximized and not dock.fixed and \
           dock.dock_direction in [AUI_DOCK_TOP, AUI_DOCK_LEFT]:

            sizer_item = cont.Add((sash_size, sash_size), 0, wx.EXPAND)

            part = AuiDockUIPart()
            part.type = AuiDockUIPart.typeDockSizer
            part.dock = dock
            part.pane = None
            part.button = None
            part.orientation = orientation
            part.cont_sizer = cont
            part.sizer_item = sizer_item
            uiparts.append(part)

        return uiparts

[docs]    def LayoutAll(self, panes, docks, uiparts, spacer_only=False, oncheck=True):
        """
        Layouts all the UI structures in the interface.

        :param `panes`: a list of L{AuiPaneInfo} instances;
        :param `docks`: a list of L{AuiDockInfo} classes;
        :param `uiparts`: a list of UI parts in the interface;
        :param `spacer_only`: whether to add a simple spacer or a real window;
        :param `oncheck`: whether to store the results in a class member or not.
        """

        container = wx.BoxSizer(wx.VERTICAL)

        pane_border_size = self._art.GetMetric(AUI_DOCKART_PANE_BORDER_SIZE)
        caption_size = self._art.GetMetric(AUI_DOCKART_CAPTION_SIZE)
        cli_size = self._frame.GetClientSize()

        # empty all docks out
        for dock in docks:
            dock.panes = []
            if dock.fixed:
                # always reset fixed docks' sizes, because
                # the contained windows may have been resized
                dock.size = 0

        dock_count = len(docks)

        # iterate through all known panes, filing each
        # of them into the appropriate dock. If the
        # pane does not exist in the dock, add it
        for p in panes:

            # don't layout hidden panes.
            if p.IsShown():

                # find any docks with the same dock direction, dock layer, and
                # dock row as the pane we are working on
                arr = FindDocks(docks, p.dock_direction, p.dock_layer, p.dock_row)

                if arr:
                    dock = arr[0]

                else:
                    # dock was not found, so we need to create a new one
                    d = AuiDockInfo()
                    d.dock_direction = p.dock_direction
                    d.dock_layer = p.dock_layer
                    d.dock_row = p.dock_row
                    docks.append(d)
                    dock = docks[-1]

                    if p.HasFlag(p.needsRestore) and not p.HasFlag(p.wasMaximized):

                        isHor = dock.IsHorizontal()
                        sashSize = self._art.GetMetric(AUI_DOCKART_SASH_SIZE)

                        # get the sizes of any docks that might
                        # overlap with our restored dock

                        # make list of widths or heights from the size in the dock rects
                        sizes = [d.rect[2:][isHor] for \
                                 d in docks if d.IsOk() and \
                                 (d.IsHorizontal() == isHor) and \
                                 not d.toolbar and \
                                 d.dock_direction != AUI_DOCK_CENTER]

                        frameRect = GetInternalFrameRect(self._frame, self._docks)

                        # set max size allowing for sashes and absolute minimum
                        maxsize = frameRect[2:][isHor] - sum(sizes) - (len(sizes)*10) - (sashSize*len(sizes))
                        dock.size = min(p.previousDockSize,maxsize)

                    else:
                        dock.size = 0

                if p.HasFlag(p.wasMaximized):
                    self.MaximizePane(p, savesizes=False)
                    p.SetFlag(p.wasMaximized, False)

                if p.HasFlag(p.needsRestore):
                    if p.previousDockPos is not None:
                        DoInsertPane(dock.panes, dock.dock_direction, dock.dock_layer, dock.dock_row, p.previousDockPos)
                        p.dock_pos = p.previousDockPos
                        p.previousDockPos = None
                    p.SetFlag(p.needsRestore, False)

                if p.IsDocked():
                    # remove the pane from any existing docks except this one
                    docks = RemovePaneFromDocks(docks, p, dock)

                    # pane needs to be added to the dock,
                    # if it doesn't already exist
                    if not FindPaneInDock(dock, p.window):
                        dock.panes.append(p)
                else:
                    # remove the pane from any existing docks
                    docks = RemovePaneFromDocks(docks, p)

        # remove any empty docks
        docks = [dock for dock in docks if dock.panes]

        dock_count = len(docks)
        # configure the docks further
        for ii, dock in enumerate(docks):
            # sort the dock pane array by the pane's
            # dock position (dock_pos), in ascending order
            dock.panes.sort(PaneSortFunc)
            dock_pane_count = len(dock.panes)

            # for newly created docks, set up their initial size
            if dock.size == 0:
                size = 0
                for pane in dock.panes:
                    pane_size = pane.best_size
                    if pane_size == wx.Size(-1, -1):
                        pane_size = pane.min_size
                    if pane_size == wx.Size(-1, -1) and pane.window:
                        pane_size = pane.window.GetSize()
                    if dock.IsHorizontal():
                        size = max(pane_size.y, size)
                    else:
                        size = max(pane_size.x, size)

                # add space for the border (two times), but only
                # if at least one pane inside the dock has a pane border
                for pane in dock.panes:
                    if pane.HasBorder():
                        size = size + pane_border_size*2
                        break

                # if pane is on the top or bottom, add the caption height,
                # but only if at least one pane inside the dock has a caption
                if dock.IsHorizontal():
                    for pane in dock.panes:
                        if pane.HasCaption() and not pane.HasCaptionLeft():
                            size = size + caption_size
                            break
                else:
                    for pane in dock.panes:
                        if pane.HasCaptionLeft() and not pane.HasCaption():
                            size = size + caption_size
                            break

                # new dock's size may not be more than the dock constraint
                # parameter specifies.  See SetDockSizeConstraint()
                max_dock_x_size = int(self._dock_constraint_x*float(cli_size.x))
                max_dock_y_size = int(self._dock_constraint_y*float(cli_size.y))
                if cli_size <= wx.Size(20, 20):
                    max_dock_x_size = 10000
                    max_dock_y_size = 10000

                if dock.IsHorizontal():
                    size = min(size, max_dock_y_size)
                else:
                    size = min(size, max_dock_x_size)

                # absolute minimum size for a dock is 10 pixels
                if size < 10:
                    size = 10

                dock.size = size

            # determine the dock's minimum size
            plus_border = False
            plus_caption = False
            plus_caption_left = False
            dock_min_size = 0
            for pane in dock.panes:
                if pane.min_size != wx.Size(-1, -1):
                    if pane.HasBorder():
                        plus_border = True
                    if pane.HasCaption():
                        plus_caption = True
                    if pane.HasCaptionLeft():
                        plus_caption_left = True
                    if dock.IsHorizontal():
                        if pane.min_size.y > dock_min_size:
                            dock_min_size = pane.min_size.y
                    else:
                        if pane.min_size.x > dock_min_size:
                            dock_min_size = pane.min_size.x

            if plus_border:
                dock_min_size += pane_border_size*2
            if plus_caption and dock.IsHorizontal():
                dock_min_size += caption_size
            if plus_caption_left and dock.IsVertical():
                dock_min_size += caption_size

            dock.min_size = dock_min_size

            # if the pane's current size is less than it's
            # minimum, increase the dock's size to it's minimum
            if dock.size < dock.min_size:
                dock.size = dock.min_size

            # determine the dock's mode (fixed or proportional)
            # determine whether the dock has only toolbars
            action_pane_marked = False
            dock.fixed = True
            dock.toolbar = True
            for pane in dock.panes:
                if not pane.IsFixed():
                    dock.fixed = False
                if not pane.IsToolbar():
                    dock.toolbar = False
                if pane.HasFlag(AuiPaneInfo.optionDockFixed):
                    dock.fixed = True
                if pane.HasFlag(AuiPaneInfo.actionPane):
                    action_pane_marked = True

            # if the dock mode is proportional and not fixed-pixel,
            # reassign the dock_pos to the sequential 0, 1, 2, 3
            # e.g. remove gaps like 1, 2, 30, 500
            if not dock.fixed:
                for jj in xrange(dock_pane_count):
                    pane = dock.panes[jj]
                    pane.dock_pos = jj

            # if the dock mode is fixed, and none of the panes
            # are being moved right now, make sure the panes
            # do not overlap each other.  If they do, we will
            # adjust the panes' positions
            if dock.fixed and not action_pane_marked:
                pane_positions, pane_sizes = self.GetPanePositionsAndSizes(dock)
                offset = 0
                for jj in xrange(dock_pane_count):
                    pane = dock.panes[jj]
                    pane.dock_pos = pane_positions[jj]
                    amount = pane.dock_pos - offset
                    if amount >= 0:
                        offset += amount
                    else:
                        pane.dock_pos += -amount

                    offset += pane_sizes[jj]
                    dock.panes[jj] = pane

            if oncheck:
                self._docks[ii] = dock

        # shrink docks if needed
##        docks = self.SmartShrink(docks, AUI_DOCK_TOP)
##        docks = self.SmartShrink(docks, AUI_DOCK_LEFT)

        if oncheck:
            self._docks = docks

        # discover the maximum dock layer
        max_layer = 0
        dock_count = len(docks)

        for ii in xrange(dock_count):
            max_layer = max(max_layer, docks[ii].dock_layer)

        # clear out uiparts
        uiparts = []

        # create a bunch of box sizers,
        # from the innermost level outwards.
        cont = None
        middle = None

        if oncheck:
            docks = self._docks

        for layer in xrange(max_layer+1):
            # find any docks in this layer
            arr = FindDocks(docks, -1, layer, -1)
            # if there aren't any, skip to the next layer
            if not arr:
                continue

            old_cont = cont

            # create a container which will hold this layer's
            # docks (top, bottom, left, right)
            cont = wx.BoxSizer(wx.VERTICAL)

            # find any top docks in this layer
            arr = FindDocks(docks, AUI_DOCK_TOP, layer, -1)
            for row in arr:
                uiparts = self.LayoutAddDock(cont, row, uiparts, spacer_only)

            # fill out the middle layer (which consists
            # of left docks, content area and right docks)

            middle = wx.BoxSizer(wx.HORIZONTAL)

            # find any left docks in this layer
            arr = FindDocks(docks, AUI_DOCK_LEFT, layer, -1)
            for row in arr:
                uiparts = self.LayoutAddDock(middle, row, uiparts, spacer_only)

            # add content dock (or previous layer's sizer
            # to the middle
            if not old_cont:
                # find any center docks
                arr = FindDocks(docks, AUI_DOCK_CENTER, -1, -1)
                if arr:
                    for row in arr:
                       uiparts = self.LayoutAddDock(middle, row, uiparts, spacer_only)

                elif not self._has_maximized:
                    # there are no center docks, add a background area
                    sizer_item = middle.Add((1, 1), 1, wx.EXPAND)
                    part = AuiDockUIPart()
                    part.type = AuiDockUIPart.typeBackground
                    part.pane = None
                    part.dock = None
                    part.button = None
                    part.cont_sizer = middle
                    part.sizer_item = sizer_item
                    uiparts.append(part)
            else:
                middle.Add(old_cont, 1, wx.EXPAND)

            # find any right docks in this layer
            arr = FindDocks(docks, AUI_DOCK_RIGHT, layer, -1, reverse=True)
            for row in arr:
                uiparts = self.LayoutAddDock(middle, row, uiparts, spacer_only)

            if len(middle.GetChildren()) > 0:
                cont.Add(middle, 1, wx.EXPAND)

            # find any bottom docks in this layer
            arr = FindDocks(docks, AUI_DOCK_BOTTOM, layer, -1, reverse=True)
            for row in arr:
                    uiparts = self.LayoutAddDock(cont, row, uiparts, spacer_only)

        if not cont:
            # no sizer available, because there are no docks,
            # therefore we will create a simple background area
            cont = wx.BoxSizer(wx.VERTICAL)
            sizer_item = cont.Add((1, 1), 1, wx.EXPAND)
            part = AuiDockUIPart()
            part.type = AuiDockUIPart.typeBackground
            part.pane = None
            part.dock = None
            part.button = None
            part.cont_sizer = middle
            part.sizer_item = sizer_item
            uiparts.append(part)

        if oncheck:
            self._uiparts = uiparts
            self._docks = docks

        container.Add(cont, 1, wx.EXPAND)

        if oncheck:
            return container
        else:
            return container, panes, docks, uiparts

[docs]    def SetDockSizeConstraint(self, width_pct, height_pct):
        """
        When a user creates a new dock by dragging a window into a docked position,
        often times the large size of the window will create a dock that is unwieldly
        large.

        L{AuiManager} by default limits the size of any new dock to 1/3 of the window
        size. For horizontal docks, this would be 1/3 of the window height. For vertical
        docks, 1/3 of the width. Calling this function will adjust this constraint value.

        The numbers must be between 0.0 and 1.0. For instance, calling L{SetDockSizeConstraint}
        with (0.5, 0.5) will cause new docks to be limited to half of the size of the entire
        managed window.

        :param `width_pct`: a float number representing the x dock size constraint;
        :param `width_pct`: a float number representing the y dock size constraint.
        """

        self._dock_constraint_x = max(0.0, min(1.0, width_pct))
        self._dock_constraint_y = max(0.0, min(1.0, height_pct))

[docs]    def GetDockSizeConstraint(self):
        """
        Returns the current dock constraint values.

        :see: L{SetDockSizeConstraint}
        """

        return self._dock_constraint_x, self._dock_constraint_y

[docs]    def Update(self):
        """
        This method is called after any number of changes are made to any of the
        managed panes. L{Update} must be invoked after L{AddPane} or L{InsertPane} are
        called in order to "realize" or "commit" the changes.

        In addition, any number of changes may be made to L{AuiPaneInfo} structures
        (retrieved with L{GetPane}), but to realize the changes, L{Update}
        must be called. This construction allows pane flicker to be avoided by updating
        the whole layout at one time.
        """

        self._hover_button = None
        self._action_part = None

        # destroy floating panes which have been
        # redocked or are becoming non-floating
        for p in self._panes:
            if p.IsFloating() or not p.frame:
                continue

            # because the pane is no longer in a floating, we need to
            # reparent it to self._frame and destroy the floating frame
            # reduce flicker
            p.window.SetSize((1, 1))

            # the following block is a workaround for bug #1531361
            # (see wxWidgets sourceforge page).  On wxGTK (only), when
            # a frame is shown/hidden, a move event unfortunately
            # also gets fired.  Because we may be dragging around
            # a pane, we need to cancel that action here to prevent
            # a spurious crash.
            if self._action_window == p.frame:
                if self._frame.HasCapture():
                    self._frame.ReleaseMouse()
                self._action = actionNone
                self._action_window = None

            # hide the frame
            if p.frame.IsShown():
                p.frame.Show(False)

            if self._action_window == p.frame:
                self._action_window = None

            # reparent to self._frame and destroy the pane
            p.window.Reparent(self._frame)
            if isinstance(p.window, auibar.AuiToolBar):
                p.window.SetAuiManager(self)

            if p.frame:
                p.frame.SetSizer(None)
                p.frame.Destroy()
            p.frame = None

        # Only the master manager should create/destroy notebooks...
        if not self._masterManager:
            self.UpdateNotebook()

        # delete old sizer first
        self._frame.SetSizer(None)

        # create a layout for all of the panes
        sizer = self.LayoutAll(self._panes, self._docks, self._uiparts, False)

        # hide or show panes as necessary,
        # and float panes as necessary

        pane_count = len(self._panes)

        for ii in xrange(pane_count):
            p = self._panes[ii]
            pFrame = p.frame

            if p.IsFloating():
                if pFrame is None:
                    # we need to create a frame for this
                    # pane, which has recently been floated
                    frame = self.CreateFloatingFrame(self._frame, p)

                    # on MSW and Mac, if the owner desires transparent dragging, and
                    # the dragging is happening right now, then the floating
                    # window should have this style by default
                    if self._action in [actionDragFloatingPane, actionDragToolbarPane] and \
                       self._agwFlags & AUI_MGR_TRANSPARENT_DRAG:
                        frame.SetTransparent(150)

                    if p.IsToolbar():
                        bar = p.window
                        if isinstance(bar, auibar.AuiToolBar):
                            bar.SetGripperVisible(False)
                            agwStyle = bar.GetAGWWindowStyleFlag()
                            bar.SetAGWWindowStyleFlag(agwStyle & ~AUI_TB_VERTICAL)
                            bar.Realize()

                        s = p.window.GetMinSize()
                        p.BestSize(s)
                        p.FloatingSize(wx.DefaultSize)

                    frame.SetPaneWindow(p)
                    p.needsTransparency = True
                    p.frame = pFrame = frame
                    if p.IsShown() and not frame.IsShown():
                        frame.Show()
                        frame.Update()
                else:

                    # frame already exists, make sure it's position
                    # and size reflect the information in AuiPaneInfo
                    if pFrame.GetPosition() != p.floating_pos or pFrame.GetSize() != p.floating_size:
                        pFrame.SetDimensions(p.floating_pos.x, p.floating_pos.y,
                                             p.floating_size.x, p.floating_size.y, wx.SIZE_USE_EXISTING)

                    # update whether the pane is resizable or not
                    style = p.frame.GetWindowStyleFlag()
                    if p.IsFixed():
                        style &= ~wx.RESIZE_BORDER
                    else:
                        style |= wx.RESIZE_BORDER

                    p.frame.SetWindowStyleFlag(style)

                    if pFrame.IsShown() != p.IsShown():
                        p.needsTransparency = True
                        pFrame.Show(p.IsShown())

                if pFrame.GetTitle() != p.caption:
                    pFrame.SetTitle(p.caption)
                if p.icon.IsOk():
                    pFrame.SetIcon(wx.IconFromBitmap(p.icon))

            else:

                if p.IsToolbar():
#                    self.SwitchToolBarOrientation(p)
                    p.best_size = p.window.GetBestSize()

                if p.window and not p.IsNotebookPage() and p.window.IsShown() != p.IsShown():
                    p.window.Show(p.IsShown())

            if pFrame and p.needsTransparency:
                if pFrame.IsShown() and pFrame._transparent != p.transparent:
                    pFrame.SetTransparent(p.transparent)
                    pFrame._transparent = p.transparent

                p.needsTransparency = False

            # if "active panes" are no longer allowed, clear
            # any optionActive values from the pane states
            if self._agwFlags & AUI_MGR_ALLOW_ACTIVE_PANE == 0:
                p.state &= ~AuiPaneInfo.optionActive

            self._panes[ii] = p

        old_pane_rects = []
        pane_count = len(self._panes)

        for p in self._panes:
            r = wx.Rect()
            if p.window and p.IsShown() and p.IsDocked():
                r = p.rect

            old_pane_rects.append(r)

        # apply the new sizer
        self._frame.SetSizer(sizer)
        self._frame.SetAutoLayout(False)
        self.DoFrameLayout()

        # now that the frame layout is done, we need to check
        # the new pane rectangles against the old rectangles that
        # we saved a few lines above here.  If the rectangles have
        # changed, the corresponding panes must also be updated
        for ii in xrange(pane_count):
            p = self._panes[ii]
            if p.window and p.IsShown() and p.IsDocked():
                if p.rect != old_pane_rects[ii]:
                    p.window.Refresh()
                    p.window.Update()

        if wx.Platform == "__WXMAC__":
            self._frame.Refresh()
        else:
            self.Repaint()

        if not self._masterManager:
            e = self.FireEvent(wxEVT_AUI_PERSPECTIVE_CHANGED, None, canVeto=False)

[docs]    def UpdateNotebook(self):
        """ Updates the automatic L{AuiNotebook} in the layout (if any exists). """

        # Workout how many notebooks we need.
        max_notebook = -1

        # destroy floating panes which have been
        # redocked or are becoming non-floating
        for paneInfo in self._panes:
            if max_notebook < paneInfo.notebook_id:
                max_notebook = paneInfo.notebook_id

        # We are the master of our domain
        extra_notebook = len(self._notebooks)
        max_notebook += 1

        for i in xrange(extra_notebook, max_notebook):
            self.CreateNotebook()

        # Remove pages from notebooks that no-longer belong there ...
        for nb, notebook in enumerate(self._notebooks):
            pages = notebook.GetPageCount()
            pageCounter, allPages = 0, pages

            # Check each tab ...
            for page in xrange(pages):

                if page >= allPages:
                    break

                window = notebook.GetPage(pageCounter)
                paneInfo = self.GetPane(window)
                if paneInfo.IsOk() and paneInfo.notebook_id != nb:
                    notebook.RemovePage(pageCounter)
                    window.Hide()
                    window.Reparent(self._frame)
                    pageCounter -= 1
                    allPages -= 1

                pageCounter += 1

            notebook.DoSizing()

        # Add notebook pages that aren't there already...
        for paneInfo in self._panes:
            if paneInfo.IsNotebookPage():

                title = (paneInfo.caption == "" and [paneInfo.name] or [paneInfo.caption])[0]

                notebook = self._notebooks[paneInfo.notebook_id]
                page_id = notebook.GetPageIndex(paneInfo.window)

                if page_id < 0:

                    paneInfo.window.Reparent(notebook)
                    notebook.AddPage(paneInfo.window, title, True, paneInfo.icon)

                # Update title and icon ...
                else:

                    notebook.SetPageText(page_id, title)
                    notebook.SetPageBitmap(page_id, paneInfo.icon)

                notebook.DoSizing()

            # Wire-up newly created notebooks
            elif paneInfo.IsNotebookControl() and not paneInfo.window:
                paneInfo.window = self._notebooks[paneInfo.notebook_id]

        # Delete empty notebooks, and convert notebooks with 1 page to
        # normal panes...
        remap_ids = [-1]*len(self._notebooks)
        nb_idx = 0

        for nb, notebook in enumerate(self._notebooks):
            if notebook.GetPageCount() == 1:

                # Convert notebook page to pane...
                window = notebook.GetPage(0)
                child_pane = self.GetPane(window)
                notebook_pane = self.GetPane(notebook)
                if child_pane.IsOk() and notebook_pane.IsOk():

                    child_pane.SetDockPos(notebook_pane)
                    child_pane.window.Hide()
                    child_pane.window.Reparent(self._frame)
                    child_pane.frame = None
                    child_pane.notebook_id = -1
                    if notebook_pane.IsFloating():
                        child_pane.Float()

                    self.DetachPane(notebook)

                    notebook.RemovePage(0)
                    notebook.Destroy()

                else:

                    raise Exception("Odd notebook docking")

            elif notebook.GetPageCount() == 0:

                self.DetachPane(notebook)
                notebook.Destroy()

            else:

                # Correct page ordering. The original wxPython code
                # for this did not work properly, and would misplace
                # windows causing errors.
                notebook.Freeze()
                self._notebooks[nb_idx] = notebook
                pages = notebook.GetPageCount()
                selected = notebook.GetPage(notebook.GetSelection())

                # Take each page out of the notebook, group it with
                # its current pane, and sort the list by pane.dock_pos
                # order
                pages_and_panes = []
                for idx in reversed(range(pages)):
                    page = notebook.GetPage(idx)
                    pane = self.GetPane(page)
                    pages_and_panes.append((page, pane))
                    notebook.RemovePage(idx)
                sorted_pnp = sorted(pages_and_panes, key=lambda tup: tup[1].dock_pos)

                # Grab the attributes from the panes which are ordered
                # correctly, and copy those attributes to the original
                # panes. (This avoids having to change the ordering
                # of self._panes) Then, add the page back into the notebook
                sorted_attributes = [self.GetAttributes(tup[1])
                                     for tup in sorted_pnp]
                for attrs, tup in zip(sorted_attributes, pages_and_panes):
                    pane = tup[1]
                    self.SetAttributes(pane, attrs)
                    notebook.AddPage(pane.window, pane.caption)

                notebook.SetSelection(notebook.GetPageIndex(selected), True)
                notebook.DoSizing()
                notebook.Thaw()

                # It's a keeper.
                remap_ids[nb] = nb_idx
                nb_idx += 1

        # Apply remap...
        nb_count = len(self._notebooks)

        if nb_count != nb_idx:

            self._notebooks = self._notebooks[0:nb_idx]
            for p in self._panes:
                if p.notebook_id >= 0:
                    p.notebook_id = remap_ids[p.notebook_id]
                    if p.IsNotebookControl():
                        p.SetNameFromNotebookId()

        # Make sure buttons are correct ...
        for notebook in self._notebooks:
            want_max = True
            want_min = True
            want_close = True

            pages = notebook.GetPageCount()
            for page in xrange(pages):

                win = notebook.GetPage(page)
                pane = self.GetPane(win)
                if pane.IsOk():

                    if not pane.HasCloseButton():
                        want_close = False
                    if not pane.HasMaximizeButton():
                        want_max = False
                    if not pane.HasMinimizeButton():
                        want_min = False

            notebook_pane = self.GetPane(notebook)
            if notebook_pane.IsOk():
                if notebook_pane.HasMinimizeButton() != want_min:
                    if want_min:
                        button = AuiPaneButton(AUI_BUTTON_MINIMIZE)
                        notebook_pane.state |= AuiPaneInfo.buttonMinimize
                        notebook_pane.buttons.append(button)

                    # todo: remove min/max

                if notebook_pane.HasMaximizeButton() != want_max:
                    if want_max:
                        button = AuiPaneButton(AUI_BUTTON_MAXIMIZE_RESTORE)
                        notebook_pane.state |= AuiPaneInfo.buttonMaximize
                        notebook_pane.buttons.append(button)

                    # todo: remove min/max

                if notebook_pane.HasCloseButton() != want_close:
                    if want_close:
                        button = AuiPaneButton(AUI_BUTTON_CLOSE)
                        notebook_pane.state |= AuiPaneInfo.buttonClose
                        notebook_pane.buttons.append(button)

                    # todo: remove close

[docs]    def SmartShrink(self, docks, direction):
        """
        Used to intelligently shrink the docks' size (if needed).

        :param `docks`: a list of L{AuiDockInfo} instances;
        :param `direction`: the direction in which to shrink.
        """

        sashSize = self._art.GetMetric(AUI_DOCKART_SASH_SIZE)
        caption_size = self._art.GetMetric(AUI_DOCKART_CAPTION_SIZE)
        clientSize = self._frame.GetClientSize()
        ourDocks = FindDocks(docks, direction, -1, -1)
        oppositeDocks = FindOppositeDocks(docks, direction)
        oppositeSize = self.GetOppositeDockTotalSize(docks, direction)
        ourSize = 0

        for dock in ourDocks:
            ourSize += dock.size

            if not dock.toolbar:
                ourSize += sashSize

        shrinkSize = ourSize + oppositeSize

        if direction == AUI_DOCK_TOP or direction == AUI_DOCK_BOTTOM:
            shrinkSize -= clientSize.y
        else:
            shrinkSize -= clientSize.x

        if shrinkSize <= 0:
            return docks

        # Combine arrays
        for dock in oppositeDocks:
            ourDocks.append(dock)

        oppositeDocks = []

        for dock in ourDocks:
            if dock.toolbar or not dock.resizable:
                continue

            dockRange = dock.size - dock.min_size

            if dock.min_size == 0:
                dockRange -= sashSize
                if direction == AUI_DOCK_TOP or direction == AUI_DOCK_BOTTOM:
                    dockRange -= caption_size

            if dockRange >= shrinkSize:

                dock.size -= shrinkSize
                return docks

            else:

                dock.size -= dockRange
                shrinkSize -= dockRange

        return docks

[docs]    def UpdateDockingGuides(self, paneInfo):
        """
        Updates the docking guide windows positions and appearance.

        :param `paneInfo`: a L{AuiPaneInfo} instance.
        """

        if len(self._guides) == 0:
            self.CreateGuideWindows()

        captionSize = self._art.GetMetric(AUI_DOCKART_CAPTION_SIZE)
        frameRect = GetInternalFrameRect(self._frame, self._docks)
        mousePos = wx.GetMousePosition()

        for indx, guide in enumerate(self._guides):

            pt = wx.Point()
            guide_size = guide.host.GetSize()
            if not guide.host:
                raise Exception("Invalid docking host")

            direction = guide.dock_direction

            if direction == AUI_DOCK_LEFT:
                pt.x = frameRect.x + guide_size.x / 2 + 16
                pt.y = frameRect.y + frameRect.height / 2

            elif direction == AUI_DOCK_TOP:
                pt.x = frameRect.x + frameRect.width / 2
                pt.y = frameRect.y + guide_size.y / 2 + 16

            elif direction == AUI_DOCK_RIGHT:
                pt.x = frameRect.x + frameRect.width - guide_size.x / 2 - 16
                pt.y = frameRect.y + frameRect.height / 2

            elif direction == AUI_DOCK_BOTTOM:
                pt.x = frameRect.x + frameRect.width / 2
                pt.y = frameRect.y + frameRect.height - guide_size.y / 2 - 16

            elif direction == AUI_DOCK_CENTER:
                rc = paneInfo.window.GetScreenRect()
                pt.x = rc.x + rc.width / 2
                pt.y = rc.y + rc.height / 2
                if paneInfo.HasCaption():
                    pt.y -= captionSize / 2
                elif paneInfo.HasCaptionLeft():
                    pt.x -= captionSize / 2

            # guide will be centered around point 'pt'
            targetPosition = wx.Point(pt.x - guide_size.x / 2, pt.y - guide_size.y / 2)

            if guide.host.GetPosition() != targetPosition:
                guide.host.Move(targetPosition)

            guide.host.AeroMove(targetPosition)

            if guide.dock_direction == AUI_DOCK_CENTER:
                guide.host.ValidateNotebookDocking(paneInfo.IsNotebookDockable())

            guide.host.UpdateDockGuide(mousePos)

        paneInfo.window.Lower()

[docs]    def DoFrameLayout(self):
        """
        This is an internal function which invokes `wx.Sizer.Layout`
        on the frame's main sizer, then measures all the various UI items
        and updates their internal rectangles.

        :note: This should always be called instead of calling
         `self._managed_window.Layout()` directly.
        """

        self._frame.Layout()

        for part in self._uiparts:
            # get the rectangle of the UI part
            # originally, this code looked like this:
            #    part.rect = wx.Rect(part.sizer_item.GetPosition(),
            #                       part.sizer_item.GetSize())
            # this worked quite well, with one exception: the mdi
            # client window had a "deferred" size variable
            # that returned the wrong size.  It looks like
            # a bug in wx, because the former size of the window
            # was being returned.  So, we will retrieve the part's
            # rectangle via other means

            part.rect = part.sizer_item.GetRect()
            flag = part.sizer_item.GetFlag()
            border = part.sizer_item.GetBorder()

            if flag & wx.TOP:
                part.rect.y -= border
                part.rect.height += border
            if flag & wx.LEFT:
                part.rect.x -= border
                part.rect.width += border
            if flag & wx.BOTTOM:
                part.rect.height += border
            if flag & wx.RIGHT:
                part.rect.width += border

            if part.type == AuiDockUIPart.typeDock:
                part.dock.rect = part.rect
            if part.type == AuiDockUIPart.typePane:
                part.pane.rect = part.rect

[docs]    def GetPanePart(self, wnd):
        """
        Looks up the pane border UI part of the
        pane specified. This allows the caller to get the exact rectangle
        of the pane in question, including decorations like caption and border.

        :param `wnd`: the window to which the pane border belongs to.
        """

        for part in self._uiparts:
            if part.type == AuiDockUIPart.typePaneBorder and \
               part.pane and part.pane.window == wnd:
                return part

        for part in self._uiparts:
            if part.type == AuiDockUIPart.typePane and \
               part.pane and part.pane.window == wnd:
                return part

        return None

[docs]    def GetDockPixelOffset(self, test):
        """
        This is an internal function which returns
        a dock's offset in pixels from the left side of the window
        (for horizontal docks) or from the top of the window (for
        vertical docks).

        This value is necessary for calculating fixed-pane/toolbar offsets
        when they are dragged.

        :param `test`: a fake L{AuiPaneInfo} for testing purposes.
        """

        # the only way to accurately calculate the dock's
        # offset is to actually run a theoretical layout
        docks, panes = CopyDocksAndPanes2(self._docks, self._panes)
        panes.append(test)

        sizer, panes, docks, uiparts = self.LayoutAll(panes, docks, [], True, False)
        client_size = self._frame.GetClientSize()
        sizer.SetDimension(0, 0, client_size.x, client_size.y)
        sizer.Layout()

        for part in uiparts:
            pos = part.sizer_item.GetPosition()
            size = part.sizer_item.GetSize()
            part.rect = wx.RectPS(pos, size)
            if part.type == AuiDockUIPart.typeDock:
                part.dock.rect = part.rect

        sizer.Destroy()

        for dock in docks:
            if test.dock_direction == dock.dock_direction and \
               test.dock_layer == dock.dock_layer and  \
               test.dock_row == dock.dock_row:

                if dock.IsVertical():
                    return dock.rect.y
                else:
                    return dock.rect.x

        return 0

[docs]    def GetPartnerDock(self, dock):
        """
        Returns the partner dock for the input dock.

        :param `dock`: a L{AuiDockInfo} instance.
        """

        for layer in xrange(dock.dock_layer, -1, -1):

            bestDock = None

            for tmpDock in self._docks:

                if tmpDock.dock_layer != layer:
                    continue

                if tmpDock.dock_direction != dock.dock_direction:
                    continue

                if tmpDock.dock_layer < dock.dock_layer:

                    if not bestDock or tmpDock.dock_row < bestDock.dock_row:
                        bestDock = tmpDock

                elif tmpDock.dock_row > dock.dock_row:

                    if not bestDock or tmpDock.dock_row > bestDock.dock_row:
                        bestDock = tmpDock

            if bestDock:
                return bestDock

        return None

[docs]    def GetPartnerPane(self, dock, pane):
        """
        Returns the partner pane for the input pane. They both need to live
        in the same L{AuiDockInfo}.

        :param `dock`: a L{AuiDockInfo} instance;
        :param `pane`: a L{AuiPaneInfo} class.
        """

        panePosition = -1

        for i, tmpPane in enumerate(dock.panes):
            if tmpPane.window == pane.window:
                panePosition = i
            elif not tmpPane.IsFixed() and panePosition != -1:
                return tmpPane

        return None

[docs]    def GetTotalPixSizeAndProportion(self, dock):
        """
        Returns the dimensions and proportion of the input dock.

        :param `dock`: the L{AuiDockInfo} structure to analyze.
        """

        totalPixsize = 0
        totalProportion = 0

        # determine the total proportion of all resizable panes,
        # and the total size of the dock minus the size of all
        # the fixed panes
        for tmpPane in dock.panes:

            if tmpPane.IsFixed():
                continue

            totalProportion += tmpPane.dock_proportion

            if dock.IsHorizontal():
                totalPixsize += tmpPane.rect.width
            else:
                totalPixsize += tmpPane.rect.height

##            if tmpPane.min_size.IsFullySpecified():
##
##                if dock.IsHorizontal():
##                    totalPixsize -= tmpPane.min_size.x
##                else:
##                    totalPixsize -= tmpPane.min_size.y

        return totalPixsize, totalProportion

[docs]    def GetOppositeDockTotalSize(self, docks, direction):
        """
        Returns the dimensions of the dock which lives opposite of the input dock.

        :param `docks`: a list of L{AuiDockInfo} structures to analyze;
        :param `direction`: the direction in which to look for the opposite dock.
        """

        sash_size = self._art.GetMetric(AUI_DOCKART_SASH_SIZE)
        caption_size = self._art.GetMetric(AUI_DOCKART_CAPTION_SIZE)
        pane_border_size = self._art.GetMetric(AUI_DOCKART_PANE_BORDER_SIZE)
        minSizeMax = 0
        result = sash_size
        vertical = False

        if direction in [AUI_DOCK_TOP, AUI_DOCK_BOTTOM]:
            vertical = True

        # Get minimum size of the most inner area
        for tmpDock in docks:

            if tmpDock.dock_layer != 0:
                continue

            if tmpDock.dock_direction != AUI_DOCK_CENTER and tmpDock.IsVertical() != vertical:
                continue

            for tmpPane in tmpDock.panes:

                minSize = pane_border_size*2 - sash_size

                if vertical:
                    minSize += tmpPane.min_size.y + caption_size
                else:
                    minSize += tmpPane.min_size.x

                if minSize > minSizeMax:
                    minSizeMax = minSize

        result += minSizeMax

        # Get opposite docks
        oppositeDocks = FindOppositeDocks(docks, direction)

        # Sum size of the opposite docks and their sashes
        for dock in oppositeDocks:
            result += dock.size
            # if it's not a toolbar add the sash_size too
            if not dock.toolbar:
                result += sash_size

        return result

[docs]    def CalculateDockSizerLimits(self, dock):
        """
        Calculates the minimum and maximum sizes allowed for the input dock.

        :param `dock`: the L{AuiDockInfo} structure to analyze.
        """

        docks, panes = CopyDocksAndPanes2(self._docks, self._panes)

        sash_size = self._art.GetMetric(AUI_DOCKART_SASH_SIZE)
        caption_size = self._art.GetMetric(AUI_DOCKART_CAPTION_SIZE)
        opposite_size = self.GetOppositeDockTotalSize(docks, dock.dock_direction)

        for tmpDock in docks:

            if tmpDock.dock_direction == dock.dock_direction and \
               tmpDock.dock_layer == dock.dock_layer and \
               tmpDock.dock_row == dock.dock_row:

                tmpDock.size = 1
                break

        sizer, panes, docks, uiparts = self.LayoutAll(panes, docks, [], True, False)
        client_size = self._frame.GetClientSize()
        sizer.SetDimension(0, 0, client_size.x, client_size.y)
        sizer.Layout()

        for part in uiparts:

            part.rect = wx.RectPS(part.sizer_item.GetPosition(), part.sizer_item.GetSize())
            if part.type == AuiDockUIPart.typeDock:
                part.dock.rect = part.rect

        sizer.Destroy()
        new_dock = None

        for tmpDock in docks:
            if tmpDock.dock_direction == dock.dock_direction and \
               tmpDock.dock_layer == dock.dock_layer and \
               tmpDock.dock_row == dock.dock_row:

                new_dock = tmpDock
                break

        partnerDock = self.GetPartnerDock(dock)

        if partnerDock:
            partnerRange = partnerDock.size - partnerDock.min_size
            if partnerDock.min_size == 0:
                partnerRange -= sash_size
                if dock.IsHorizontal():
                    partnerRange -= caption_size

            direction = dock.dock_direction

            if direction == AUI_DOCK_LEFT:
                minPix = new_dock.rect.x + new_dock.rect.width
                maxPix = dock.rect.x + dock.rect.width
                maxPix += partnerRange

            elif direction == AUI_DOCK_TOP:
                minPix = new_dock.rect.y + new_dock.rect.height
                maxPix = dock.rect.y + dock.rect.height
                maxPix += partnerRange

            elif direction == AUI_DOCK_RIGHT:
                minPix = dock.rect.x - partnerRange - sash_size
                maxPix = new_dock.rect.x - sash_size

            elif direction == AUI_DOCK_BOTTOM:
                minPix = dock.rect.y - partnerRange - sash_size
                maxPix = new_dock.rect.y - sash_size

            return minPix, maxPix

        direction = new_dock.dock_direction

        if direction == AUI_DOCK_LEFT:
            minPix = new_dock.rect.x + new_dock.rect.width
            maxPix = client_size.x - opposite_size - sash_size

        elif direction == AUI_DOCK_TOP:
            minPix = new_dock.rect.y + new_dock.rect.height
            maxPix = client_size.y - opposite_size - sash_size

        elif direction == AUI_DOCK_RIGHT:
            minPix = opposite_size
            maxPix = new_dock.rect.x - sash_size

        elif direction == AUI_DOCK_BOTTOM:
            minPix = opposite_size
            maxPix = new_dock.rect.y - sash_size

        return minPix, maxPix

[docs]    def CalculatePaneSizerLimits(self, dock, pane):
        """
        Calculates the minimum and maximum sizes allowed for the input pane.

        :param `dock`: the L{AuiDockInfo} structure to which `pane` belongs to;
        :param `pane`: a L{AuiPaneInfo} class for which calculation are requested.
        """

        if pane.IsFixed():
            if dock.IsHorizontal():
                minPix = maxPix = pane.rect.x + 1 + pane.rect.width
            else:
                minPix = maxPix = pane.rect.y + 1 + pane.rect.height

            return minPix, maxPix

        totalPixsize, totalProportion = self.GetTotalPixSizeAndProportion(dock)
        partnerPane = self.GetPartnerPane(dock, pane)

        if dock.IsHorizontal():

            minPix = pane.rect.x + 1
            maxPix = pane.rect.x + 1 + pane.rect.width

            if pane.min_size.IsFullySpecified():
                minPix += pane.min_size.x
            else:
                minPix += 1

            if partnerPane:
                maxPix += partnerPane.rect.width

                if partnerPane.min_size.IsFullySpecified():
                    maxPix -= partnerPane.min_size.x - 1

            else:
                minPix = maxPix

        else:

            minPix = pane.rect.y + 1
            maxPix = pane.rect.y + 1 + pane.rect.height

            if pane.min_size.IsFullySpecified():
                minPix += pane.min_size.y
            else:
                minPix += 1

            if partnerPane:
                maxPix += partnerPane.rect.height

                if partnerPane.min_size.IsFullySpecified():
                    maxPix -= partnerPane.min_size.y - 1

            else:
                minPix = maxPix

        return minPix, maxPix

[docs]    def CheckMovableSizer(self, part):
        """
        Checks if a UI part can be actually resized.

        :param `part`: a UI part.
        """

        # a dock may not be resized if it has a single
        # pane which is not resizable
        if part.type == AuiDockUIPart.typeDockSizer and part.dock and \
           len(part.dock.panes) == 1 and part.dock.panes[0].IsFixed():

            return False

        if part.pane:

            # panes that may not be resized should be ignored here
            minPix, maxPix = self.CalculatePaneSizerLimits(part.dock, part.pane)

            if minPix == maxPix:
                return False

        return True

[docs]    def PaneFromTabEvent(self, event):
        """
        Returns a L{AuiPaneInfo} from a L{AuiNotebookEvent} event.

        :param `event`: a L{AuiNotebookEvent} event.
        """

        obj = event.GetEventObject()

        if obj and isinstance(obj, auibook.AuiTabCtrl):

            page_idx = obj.GetActivePage()

            if page_idx >= 0:
                page = obj.GetPage(page_idx)
                window = page.window
                if window:
                    return self.GetPane(window)

        elif obj and isinstance(obj, auibook.AuiNotebook):

            page_idx = event.GetSelection()

            if page_idx >= 0:
                window = obj.GetPage(page_idx)
                if window:
                    return self.GetPane(window)

        return NonePaneInfo

[docs]    def OnTabBeginDrag(self, event):
        """
        Handles the ``EVT_AUINOTEBOOK_BEGIN_DRAG`` event.

        :param `event`: a L{AuiNotebookEvent} event to be processed.
        """

        if self._masterManager:
            self._masterManager.OnTabBeginDrag(event)

        else:
            paneInfo = self.PaneFromTabEvent(event)

            if paneInfo.IsOk():

                # It's one of ours!
                self._action = actionDragFloatingPane
                mouse = wx.GetMousePosition()

                # set initial float position - may have to think about this
                # offset a bit more later ...
                self._action_offset = wx.Point(20, 10)
                self._toolbar_action_offset = wx.Point(20, 10)

                paneInfo.floating_pos = mouse - self._action_offset
                paneInfo.dock_pos = AUI_DOCK_NONE
                paneInfo.notebook_id = -1

                tab = event.GetEventObject()

                if tab.HasCapture():
                    tab.ReleaseMouse()

                # float the window
                if paneInfo.IsMaximized():
                    self.RestorePane(paneInfo)
                paneInfo.Float()
                self.Update()

                self._action_window = paneInfo.window

                self._frame.CaptureMouse()
                event.SetDispatched(True)

            else:

                # not our window
                event.Skip()

[docs]    def OnTabPageClose(self, event):
        """
        Handles the ``EVT_AUINOTEBOOK_PAGE_CLOSE`` event.

        :param `event`: a L{AuiNotebookEvent} event to be processed.
        """

        if self._masterManager:
            self._masterManager.OnTabPageClose(event)

        else:

            p = self.PaneFromTabEvent(event)
            if p.IsOk():

                # veto it because we will call "RemovePage" ourselves
                event.Veto()

                # Now ask the app if they really want to close...
                # fire pane close event
                e = AuiManagerEvent(wxEVT_AUI_PANE_CLOSE)
                e.SetPane(p)
                e.SetCanVeto(True)
                self.ProcessMgrEvent(e)

                if e.GetVeto():
                    return

                self.ClosePane(p)
                self.Update()
            else:
                event.Skip()

[docs]    def OnTabSelected(self, event):
        """
        Handles the ``EVT_AUINOTEBOOK_PAGE_CHANGED`` event.

        :param `event`: a L{AuiNotebookEvent} event to be processed.
        """

        if self._masterManager:
            self._masterManager.OnTabSelected(event)
            return

        obj = event.GetEventObject()

        if obj and isinstance(obj, auibook.AuiNotebook):

            notebook = obj
            page = notebook.GetPage(event.GetSelection())
            paneInfo = self.GetPane(page)

            if paneInfo.IsOk():
                notebookRoot = GetNotebookRoot(self._panes, paneInfo.notebook_id)
                if notebookRoot:

                    notebookRoot.Caption(paneInfo.caption)
                    self.RefreshCaptions()

        event.Skip()

[docs]    def GetNotebooks(self):
        """ Returns all the automatic L{AuiNotebook} in the L{AuiManager}. """

        if self._masterManager:
            return self._masterManager.GetNotebooks()

        return self._notebooks

[docs]    def SetMasterManager(self, manager):
        """
        Sets the master manager for an automatic L{AuiNotebook}.

        :param `manager`: an instance of L{AuiManager}.
        """

        self._masterManager = manager

[docs]    def ProcessDockResult(self, target, new_pos):
        """
        This is a utility function used by L{DoDrop} - it checks
        if a dock operation is allowed, the new dock position is copied into
        the target info. If the operation was allowed, the function returns ``True``.

        :param `target`: the L{AuiPaneInfo} instance to be docked;
        :param `new_pos`: the new docking position if the docking operation is allowed.
        """

        allowed = False
        direction = new_pos.dock_direction

        if direction == AUI_DOCK_TOP:
            allowed = target.IsTopDockable()
        elif direction == AUI_DOCK_BOTTOM:
            allowed = target.IsBottomDockable()
        elif direction == AUI_DOCK_LEFT:
            allowed = target.IsLeftDockable()
        elif direction == AUI_DOCK_RIGHT:
            allowed = target.IsRightDockable()

        if allowed:
            target = new_pos

            if target.IsToolbar():
                self.SwitchToolBarOrientation(target)

        return allowed, target

[docs]    def SwitchToolBarOrientation(self, pane):
        """
        Switches the toolbar orientation from vertical to horizontal and vice-versa.
        This is especially useful for vertical docked toolbars once they float.

        :param `pane`: an instance of L{AuiPaneInfo}, which may have a L{AuiToolBar}
         window associated with it.
        """

        if not isinstance(pane.window, auibar.AuiToolBar):
            return pane

        if pane.IsFloating():
            return pane

        toolBar = pane.window
        direction = pane.dock_direction
        vertical = direction in [AUI_DOCK_LEFT, AUI_DOCK_RIGHT]

        agwStyle = toolBar.GetAGWWindowStyleFlag()
        new_agwStyle = agwStyle

        if vertical:
            new_agwStyle |= AUI_TB_VERTICAL
        else:
            new_agwStyle &= ~(AUI_TB_VERTICAL)

        if agwStyle != new_agwStyle:
            toolBar.SetAGWWindowStyleFlag(new_agwStyle)
        if not toolBar.GetGripperVisible():
            toolBar.SetGripperVisible(True)

        s = pane.window.GetMinSize()
        pane.BestSize(s)

        if new_agwStyle != agwStyle:
            toolBar.Realize()

        return pane

[docs]    def DoDrop(self, docks, panes, target, pt, offset=wx.Point(0, 0)):
        """
        This is an important function. It basically takes a mouse position,
        and determines where the panes new position would be. If the pane is to be
        dropped, it performs the drop operation using the specified dock and pane
        arrays. By specifying copy dock and pane arrays when calling, a "what-if"
        scenario can be performed, giving precise coordinates for drop hints.

        :param `docks`: a list of L{AuiDockInfo} classes;
        :param `panes`: a list of L{AuiPaneInfo} instances;
        :param `pt`: a mouse position to check for a drop operation;
        :param `offset`: a possible offset from the input point `pt`.
        """

        if target.IsToolbar():
            return self.DoDropToolbar(docks, panes, target, pt, offset)
        elif target.IsFloating():
            return self.DoDropFloatingPane(docks, panes, target, pt)
        else:
            return self.DoDropNonFloatingPane(docks, panes, target, pt)

[docs]    def CopyTarget(self, target):
        """
        Copies all the attributes of the input `target` into another L{AuiPaneInfo}.

        :param `target`: the source L{AuiPaneInfo} from where to copy attributes.
        """

        drop = AuiPaneInfo()
        drop.name = target.name
        drop.caption = target.caption
        drop.window = target.window
        drop.frame = target.frame
        drop.state = target.state
        drop.dock_direction = target.dock_direction
        drop.dock_layer = target.dock_layer
        drop.dock_row = target.dock_row
        drop.dock_pos = target.dock_pos
        drop.best_size = wx.Size(*target.best_size)
        drop.min_size = wx.Size(*target.min_size)
        drop.max_size = wx.Size(*target.max_size)
        drop.floating_pos = wx.Point(*target.floating_pos)
        drop.floating_size = wx.Size(*target.floating_size)
        drop.dock_proportion = target.dock_proportion
        drop.buttons = target.buttons
        drop.rect = wx.Rect(*target.rect)
        drop.icon = target.icon
        drop.notebook_id = target.notebook_id
        drop.transparent = target.transparent
        drop.snapped = target.snapped
        drop.minimize_mode = target.minimize_mode
        drop.minimize_target = target.minimize_target

        return drop

[docs]    def DoDropToolbar(self, docks, panes, target, pt, offset):
        """
        Handles the situation in which the dropped pane contains a toolbar.

        :param `docks`: a list of L{AuiDockInfo} classes;
        :param `panes`: a list of L{AuiPaneInfo} instances;
        :param `target`: the target pane containing the toolbar;
        :param `pt`: a mouse position to check for a drop operation;
        :param `offset`: a possible offset from the input point `pt`.
        """

        drop = self.CopyTarget(target)

        # The result should always be shown
        drop.Show()

        # Check to see if the toolbar has been dragged out of the window
        if CheckOutOfWindow(self._frame, pt):
            if self._agwFlags & AUI_MGR_ALLOW_FLOATING and drop.IsFloatable():
                drop.Float()

            return self.ProcessDockResult(target, drop)

        # Allow directional change when the cursor leaves this rect
        safeRect = wx.Rect(*target.rect)
        if target.IsHorizontal():
            safeRect.Inflate(100, 50)
        else:
            safeRect.Inflate(50, 100)

        # Check to see if the toolbar has been dragged to edge of the frame
        dropDir = CheckEdgeDrop(self._frame, docks, pt)

        if dropDir != -1:

            if dropDir == wx.LEFT:
                drop.Dock().Left().Layer(auiToolBarLayer).Row(0). \
                    Position(pt.y - self.GetDockPixelOffset(drop) - offset.y)

            elif dropDir == wx.RIGHT:
                drop.Dock().Right().Layer(auiToolBarLayer).Row(0). \
                    Position(pt.y - self.GetDockPixelOffset(drop) - offset.y)

            elif dropDir == wx.TOP:
                drop.Dock().Top().Layer(auiToolBarLayer).Row(0). \
                    Position(pt.x - self.GetDockPixelOffset(drop) - offset.x)

            elif dropDir == wx.BOTTOM:
                drop.Dock().Bottom().Layer(auiToolBarLayer).Row(0). \
                    Position(pt.x - self.GetDockPixelOffset(drop) - offset.x)

            if not target.IsFloating() and safeRect.Contains(pt) and \
               target.dock_direction != drop.dock_direction:
                return False, target

            return self.ProcessDockResult(target, drop)

        # If the windows is floating and out of the client area, do nothing
        if drop.IsFloating() and not self._frame.GetClientRect().Contains(pt):
            return False, target

        # Ok, can't drop on edge - check internals ...

        clientSize = self._frame.GetClientSize()
        x = Clip(pt.x, 0, clientSize.x - 1)
        y = Clip(pt.y, 0, clientSize.y - 1)
        part = self.HitTest(x, y)

        if not part or not part.dock:
            return False, target

        dock = part.dock

        # toolbars may only be moved in and to fixed-pane docks,
        # otherwise we will try to float the pane.  Also, the pane
        # should float if being dragged over center pane windows
        if not dock.fixed or dock.dock_direction == AUI_DOCK_CENTER:

            if (self._agwFlags & AUI_MGR_ALLOW_FLOATING and drop.IsFloatable()) or \
               dock.dock_direction not in [AUI_DOCK_CENTER, AUI_DOCK_NONE]:
                if drop.IsFloatable():
                    drop.Float()

            return self.ProcessDockResult(target, drop)

        # calculate the offset from where the dock begins
        # to the point where the user dropped the pane
        dockDropOffset = 0
        if dock.IsHorizontal():
            dockDropOffset = pt.x - dock.rect.x - offset.x
        else:
            dockDropOffset = pt.y - dock.rect.y - offset.y

        drop.Dock().Direction(dock.dock_direction).Layer(dock.dock_layer). \
            Row(dock.dock_row).Position(dockDropOffset)

        if (pt.y <= dock.rect.GetTop() + 2 and dock.IsHorizontal()) or \
           (pt.x <= dock.rect.GetLeft() + 2 and dock.IsVertical()):

            if dock.dock_direction in [AUI_DOCK_TOP, AUI_DOCK_LEFT]:
                row = drop.dock_row
                panes = DoInsertDockRow(panes, dock.dock_direction, dock.dock_layer, dock.dock_row)
                drop.dock_row = row

            else:
                panes = DoInsertDockRow(panes, dock.dock_direction, dock.dock_layer, dock.dock_row+1)
                drop.dock_row = dock.dock_row + 1

        if (pt.y >= dock.rect.GetBottom() - 2 and dock.IsHorizontal()) or \
           (pt.x >= dock.rect.GetRight() - 2 and dock.IsVertical()):

            if dock.dock_direction in [AUI_DOCK_TOP, AUI_DOCK_LEFT]:
                panes = DoInsertDockRow(panes, dock.dock_direction, dock.dock_layer, dock.dock_row+1)
                drop.dock_row = dock.dock_row+1

            else:
                row = drop.dock_row
                panes = DoInsertDockRow(panes, dock.dock_direction, dock.dock_layer, dock.dock_row)
                drop.dock_row = row

        if not target.IsFloating() and safeRect.Contains(pt) and \
           target.dock_direction != drop.dock_direction:
            return False, target

        return self.ProcessDockResult(target, drop)

[docs]    def DoDropFloatingPane(self, docks, panes, target, pt):
        """
        Handles the situation in which the dropped pane contains a normal window.

        :param `docks`: a list of L{AuiDockInfo} classes;
        :param `panes`: a list of L{AuiPaneInfo} instances;
        :param `target`: the target pane containing the window;
        :param `pt`: a mouse position to check for a drop operation.
        """

        screenPt = self._frame.ClientToScreen(pt)
        paneInfo = self.PaneHitTest(panes, pt)

        if paneInfo.IsMaximized():
            return False, target

        if paneInfo.window is None:
            return False, target

        # search the dock guides.
        # reverse order to handle the center first.
        for i in xrange(len(self._guides)-1, -1, -1):
            guide = self._guides[i]

            # do hit testing on the guide
            dir = guide.host.HitTest(screenPt.x, screenPt.y)

            if dir == -1:  # point was outside of the dock guide
                continue

            if dir == wx.ALL:   # target is a single dock guide
                return self.DoDropLayer(docks, target, guide.dock_direction)

            elif dir == wx.CENTER:

                if not target.IsNotebookDockable():
                    continue
                if not paneInfo.IsNotebookDockable() and not paneInfo.IsNotebookControl():
                    continue

                if not paneInfo.HasNotebook():

                    # Add a new notebook pane with the original as a tab...
                    self.CreateNotebookBase(panes, paneInfo)

                # Add new item to notebook
                target.NotebookPage(paneInfo.notebook_id)

            else:

                drop_pane = False
                drop_row = False

                insert_dir = paneInfo.dock_direction
                insert_layer = paneInfo.dock_layer
                insert_row = paneInfo.dock_row
                insert_pos = paneInfo.dock_pos

                if insert_dir == AUI_DOCK_CENTER:

                    insert_layer = 0
                    if dir == wx.LEFT:
                        insert_dir = AUI_DOCK_LEFT
                    elif dir == wx.UP:
                        insert_dir = AUI_DOCK_TOP
                    elif dir == wx.RIGHT:
                        insert_dir = AUI_DOCK_RIGHT
                    elif dir == wx.DOWN:
                        insert_dir = AUI_DOCK_BOTTOM

                if insert_dir == AUI_DOCK_LEFT:

                    drop_pane = (dir == wx.UP   or dir == wx.DOWN)
                    drop_row  = (dir == wx.LEFT or dir == wx.RIGHT)
                    if dir == wx.RIGHT:
                        insert_row += 1
                    elif dir == wx.DOWN:
                        insert_pos += 1

                elif insert_dir == AUI_DOCK_RIGHT:

                    drop_pane = (dir == wx.UP   or dir == wx.DOWN)
                    drop_row  = (dir == wx.LEFT or dir == wx.RIGHT)
                    if dir == wx.LEFT:
                        insert_row += 1
                    elif dir == wx.DOWN:
                        insert_pos += 1

                elif insert_dir == AUI_DOCK_TOP:

                    drop_pane = (dir == wx.LEFT or dir == wx.RIGHT)
                    drop_row  = (dir == wx.UP   or dir == wx.DOWN)
                    if dir == wx.DOWN:
                        insert_row += 1
                    elif dir == wx.RIGHT:
                        insert_pos += 1

                elif insert_dir == AUI_DOCK_BOTTOM:

                    drop_pane = (dir == wx.LEFT or dir == wx.RIGHT)
                    drop_row  = (dir == wx.UP   or dir == wx.DOWN)
                    if dir == wx.UP:
                        insert_row += 1
                    elif dir == wx.RIGHT:
                        insert_pos += 1

                if paneInfo.dock_direction == AUI_DOCK_CENTER:
                    insert_row = GetMaxRow(panes, insert_dir, insert_layer) + 1

                if drop_pane:
                    return self.DoDropPane(panes, target, insert_dir, insert_layer, insert_row, insert_pos)

                if drop_row:
                    return self.DoDropRow(panes, target, insert_dir, insert_layer, insert_row)

            return True, target

        return False, target

[docs]    def DoDropNonFloatingPane(self, docks, panes, target, pt):
        """
        Handles the situation in which the dropped pane is not floating.

        :param `docks`: a list of L{AuiDockInfo} classes;
        :param `panes`: a list of L{AuiPaneInfo} instances;
        :param `target`: the target pane containing the toolbar;
        :param `pt`: a mouse position to check for a drop operation.
        """

        screenPt = self._frame.ClientToScreen(pt)
        clientSize = self._frame.GetClientSize()
        frameRect = GetInternalFrameRect(self._frame, self._docks)

        drop = self.CopyTarget(target)

        # The result should always be shown
        drop.Show()

        part = self.HitTest(pt.x, pt.y)

        if not part:
            return False, target

        if part.type == AuiDockUIPart.typeDockSizer:

            if len(part.dock.panes) != 1:
                return False, target

            part = self.GetPanePart(part.dock.panes[0].window)
            if not part:
                return False, target

        if not part.pane:
            return False, target

        part = self.GetPanePart(part.pane.window)
        if not part:
            return False, target

        insert_dock_row = False
        insert_row = part.pane.dock_row
        insert_dir = part.pane.dock_direction
        insert_layer = part.pane.dock_layer

        direction = part.pane.dock_direction

        if direction == AUI_DOCK_TOP:
            if pt.y >= part.rect.y and pt.y < part.rect.y+auiInsertRowPixels:
                insert_dock_row = True

        elif direction == AUI_DOCK_BOTTOM:
            if pt.y > part.rect.y+part.rect.height-auiInsertRowPixels and \
               pt.y <= part.rect.y + part.rect.height:
                insert_dock_row = True

        elif direction == AUI_DOCK_LEFT:
            if pt.x >= part.rect.x and pt.x < part.rect.x+auiInsertRowPixels:
                insert_dock_row = True

        elif direction == AUI_DOCK_RIGHT:
            if pt.x > part.rect.x+part.rect.width-auiInsertRowPixels and \
               pt.x <= part.rect.x+part.rect.width:
                insert_dock_row = True

        elif direction == AUI_DOCK_CENTER:

                # "new row pixels" will be set to the default, but
                # must never exceed 20% of the window size
                new_row_pixels_x = auiNewRowPixels
                new_row_pixels_y = auiNewRowPixels

                if new_row_pixels_x > (part.rect.width*20)/100:
                    new_row_pixels_x = (part.rect.width*20)/100

                if new_row_pixels_y > (part.rect.height*20)/100:
                    new_row_pixels_y = (part.rect.height*20)/100

                # determine if the mouse pointer is in a location that
                # will cause a new row to be inserted.  The hot spot positions
                # are along the borders of the center pane

                insert_layer = 0
                insert_dock_row = True
                pr = part.rect

                if pt.x >= pr.x and pt.x < pr.x + new_row_pixels_x:
                    insert_dir = AUI_DOCK_LEFT
                elif pt.y >= pr.y and pt.y < pr.y + new_row_pixels_y:
                    insert_dir = AUI_DOCK_TOP
                elif pt.x >= pr.x + pr.width - new_row_pixels_x and pt.x < pr.x + pr.width:
                    insert_dir = AUI_DOCK_RIGHT
                elif pt.y >= pr.y+ pr.height - new_row_pixels_y and pt.y < pr.y + pr.height:
                    insert_dir = AUI_DOCK_BOTTOM
                else:
                    return False, target

                insert_row = GetMaxRow(panes, insert_dir, insert_layer) + 1

        if insert_dock_row:

            panes = DoInsertDockRow(panes, insert_dir, insert_layer, insert_row)
            drop.Dock().Direction(insert_dir).Layer(insert_layer). \
                Row(insert_row).Position(0)

            return self.ProcessDockResult(target, drop)

        # determine the mouse offset and the pane size, both in the
        # direction of the dock itself, and perpendicular to the dock

        if part.orientation == wx.VERTICAL:

            offset = pt.y - part.rect.y
            size = part.rect.GetHeight()

        else:

            offset = pt.x - part.rect.x
            size = part.rect.GetWidth()

        drop_position = part.pane.dock_pos

        # if we are in the top/left part of the pane,
        # insert the pane before the pane being hovered over
        if offset <= size/2:

            drop_position = part.pane.dock_pos
            panes = DoInsertPane(panes,
                                 part.pane.dock_direction,
                                 part.pane.dock_layer,
                                 part.pane.dock_row,
                                 part.pane.dock_pos)

        # if we are in the bottom/right part of the pane,
        # insert the pane before the pane being hovered over
        if offset > size/2:

            drop_position = part.pane.dock_pos+1
            panes = DoInsertPane(panes,
                                 part.pane.dock_direction,
                                 part.pane.dock_layer,
                                 part.pane.dock_row,
                                 part.pane.dock_pos+1)

        drop.Dock(). \
                     Direction(part.dock.dock_direction). \
                     Layer(part.dock.dock_layer).Row(part.dock.dock_row). \
                     Position(drop_position)

        return self.ProcessDockResult(target, drop)

[docs]    def DoDropLayer(self, docks, target, dock_direction):
        """
        Handles the situation in which `target` is a single dock guide.

        :param `docks`: a list of L{AuiDockInfo} classes;
        :param `target`: the target pane;
        :param `dock_direction`: the docking direction.
        """

        drop = self.CopyTarget(target)

        if dock_direction == AUI_DOCK_LEFT:
            drop.Dock().Left()
            drop_new_layer = max(max(GetMaxLayer(docks, AUI_DOCK_LEFT),
                                     GetMaxLayer(docks, AUI_DOCK_BOTTOM)),
                                 GetMaxLayer(docks, AUI_DOCK_TOP)) + 1

        elif dock_direction == AUI_DOCK_TOP:
            drop.Dock().Top()
            drop_new_layer = max(max(GetMaxLayer(docks, AUI_DOCK_TOP),
                                     GetMaxLayer(docks, AUI_DOCK_LEFT)),
                                 GetMaxLayer(docks, AUI_DOCK_RIGHT)) + 1

        elif dock_direction == AUI_DOCK_RIGHT:
            drop.Dock().Right()
            drop_new_layer = max(max(GetMaxLayer(docks, AUI_DOCK_RIGHT),
                                     GetMaxLayer(docks, AUI_DOCK_TOP)),
                                 GetMaxLayer(docks, AUI_DOCK_BOTTOM)) + 1

        elif dock_direction == AUI_DOCK_BOTTOM:
            drop.Dock().Bottom()
            drop_new_layer = max(max(GetMaxLayer(docks, AUI_DOCK_BOTTOM),
                                     GetMaxLayer(docks, AUI_DOCK_LEFT)),
                                 GetMaxLayer(docks, AUI_DOCK_RIGHT)) + 1

        else:
            return False, target

        drop.Dock().Layer(drop_new_layer)
        return self.ProcessDockResult(target, drop)

[docs]    def DoDropPane(self, panes, target, dock_direction, dock_layer, dock_row, dock_pos):
        """
        Drop a pane in the interface.

        :param `panes`: a list of L{AuiPaneInfo} classes;
        :param `target`: the target pane;
        :param `dock_direction`: the docking direction;
        :param `dock_layer`: the docking layer;
        :param `dock_row`: the docking row;
        :param `dock_pos`: the docking position.
        """

        drop = self.CopyTarget(target)
        panes = DoInsertPane(panes, dock_direction, dock_layer, dock_row, dock_pos)

        drop.Dock().Direction(dock_direction).Layer(dock_layer).Row(dock_row).Position(dock_pos)
        return self.ProcessDockResult(target, drop)

[docs]    def DoDropRow(self, panes, target, dock_direction, dock_layer, dock_row):
        """
        Insert a row in the interface before dropping.

        :param `panes`: a list of L{AuiPaneInfo} classes;
        :param `target`: the target pane;
        :param `dock_direction`: the docking direction;
        :param `dock_layer`: the docking layer;
        :param `dock_row`: the docking row.
        """

        drop = self.CopyTarget(target)
        panes = DoInsertDockRow(panes, dock_direction, dock_layer, dock_row)

        drop.Dock().Direction(dock_direction).Layer(dock_layer).Row(dock_row).Position(0)
        return self.ProcessDockResult(target, drop)

[docs]    def ShowHint(self, rect):
        """
        Shows the AUI hint window.

        :param `rect`: the hint rect calculated in advance.
        """

        if rect == self._last_hint:
            return

        if self._agwFlags & AUI_MGR_RECTANGLE_HINT and wx.Platform != "__WXMAC__":

            if self._last_hint != rect:
                # remove the last hint rectangle
                self._last_hint = wx.Rect(*rect)
                self._frame.Refresh()
                self._frame.Update()

            screendc = wx.ScreenDC()
            clip = wx.Region(1, 1, 10000, 10000)

            # clip all floating windows, so we don't draw over them
            for pane in self._panes:
                if pane.IsFloating() and pane.frame.IsShown():

                    rect2 = wx.Rect(*pane.frame.GetRect())
                    if wx.Platform == "__WXGTK__":
                        # wxGTK returns the client size, not the whole frame size
                        rect2.width += 15
                        rect2.height += 35
                        rect2.Inflate(5, 5)

                    clip.SubtractRect(rect2)

            # As we can only hide the hint by redrawing the managed window, we
            # need to clip the region to the managed window too or we get
            # nasty redrawn problems.
            clip.IntersectRect(self._frame.GetRect())
            screendc.SetClippingRegionAsRegion(clip)

            stipple = PaneCreateStippleBitmap()
            brush = wx.BrushFromBitmap(stipple)
            screendc.SetBrush(brush)
            screendc.SetPen(wx.TRANSPARENT_PEN)
            screendc.DrawRectangle(rect.x, rect.y, 5, rect.height)
            screendc.DrawRectangle(rect.x+5, rect.y, rect.width-10, 5)
            screendc.DrawRectangle(rect.x+rect.width-5, rect.y, 5, rect.height)
            screendc.DrawRectangle(rect.x+5, rect.y+rect.height-5, rect.width-10, 5)
            RefreshDockingGuides(self._guides)

            return

        if not self._hint_window:
            self.CreateHintWindow()

        if self._hint_window:
            self._hint_window.SetRect(rect)
            self._hint_window.Show()

        self._hint_fadeamt = self._hint_fademax

        if self._agwFlags & AUI_MGR_HINT_FADE:
            self._hint_fadeamt = 0
            self._hint_window.SetTransparent(self._hint_fadeamt)

        if self._action == actionDragFloatingPane and self._action_window:
            self._action_window.SetFocus()

        if self._hint_fadeamt != self._hint_fademax: #  Only fade if we need to
            # start fade in timer
            self._hint_fadetimer.Start(5)

        self._last_hint = wx.Rect(*rect)

[docs]    def HideHint(self):
        """ Hides a transparent window hint if there is one. """

        # hides a transparent window hint if there is one
        if self._hint_window:
            self._hint_window.Hide()

        self._hint_fadetimer.Stop()
        self._last_hint = wx.Rect()

[docs]    def IsPaneButtonVisible(self, part):
        """
        Returns whether a pane button in the pane caption is visible.

        :param `part`: the UI part to analyze.
        """

        captionRect = wx.Rect()

        for temp_part in self._uiparts:
            if temp_part.pane == part.pane and \
               temp_part.type == AuiDockUIPart.typeCaption:
                captionRect = temp_part.rect
                break

        return captionRect.ContainsRect(part.rect)

[docs]    def DrawPaneButton(self, dc, part, pt):
        """
        Draws a pane button in the caption (convenience function).

        :param `dc`: a `wx.DC` device context object;
        :param `part`: the UI part to analyze;
        :param `pt`: a `wx.Point` object, specifying the mouse location.
        """

        if not self.IsPaneButtonVisible(part):
            return

        state = AUI_BUTTON_STATE_NORMAL

        if part.rect.Contains(pt):

            if _VERSION_STRING < "2.9":
                leftDown = wx.GetMouseState().LeftDown()
            else:
                leftDown = wx.GetMouseState().LeftIsDown()

            if leftDown:
                state = AUI_BUTTON_STATE_PRESSED
            else:
                state = AUI_BUTTON_STATE_HOVER

        self._art.DrawPaneButton(dc, self._frame, part.button.button_id,
                                 state, part.rect, part.pane)

[docs]    def RefreshButton(self, part):
        """
        Refreshes a pane button in the caption.

        :param `part`: the UI part to analyze.
        """

        rect = wx.Rect(*part.rect)
        rect.Inflate(2, 2)
        self._frame.Refresh(True, rect)
        self._frame.Update()

[docs]    def RefreshCaptions(self):
        """ Refreshes all pane captions. """

        for part in self._uiparts:
            if part.type == AuiDockUIPart.typeCaption:
                self._frame.Refresh(True, part.rect)
                self._frame.Update()

[docs]    def CalculateHintRect(self, pane_window, pt, offset):
        """
        Calculates the drop hint rectangle.

        The method first calls L{DoDrop} to determine the exact position the pane would
        be at were if dropped. If the pane would indeed become docked at the
        specified drop point, the the rectangle hint will be returned in
        screen coordinates. Otherwise, an empty rectangle is returned.

        :param `pane_window`: it is the window pointer of the pane being dragged;
        :param `pt`: is the mouse position, in client coordinates;
        :param `offset`: describes the offset that the mouse is from the upper-left
         corner of the item being dragged.
        """

        # we need to paint a hint rectangle to find out the exact hint rectangle,
        # we will create a new temporary layout and then measure the resulting
        # rectangle we will create a copy of the docking structures (self._docks)
        # so that we don't modify the real thing on screen

        rect = wx.Rect()
        pane = self.GetPane(pane_window)

        attrs = self.GetAttributes(pane)
        hint = AuiPaneInfo()
        hint = self.SetAttributes(hint, attrs)

        if hint.name != "__HINT__":
            self._oldname = hint.name

        hint.name = "__HINT__"
        hint.PaneBorder(True)
        hint.Show()

        if not hint.IsOk():
            hint.name = self._oldname
            return rect

        docks, panes = CopyDocksAndPanes2(self._docks, self._panes)

        # remove any pane already there which bears the same window
        # this happens when you are moving a pane around in a dock
        for ii in xrange(len(panes)):
            if panes[ii].window == pane_window:
                docks = RemovePaneFromDocks(docks, panes[ii])
                panes.pop(ii)
                break

        # find out where the new pane would be
        allow, hint = self.DoDrop(docks, panes, hint, pt, offset)

        if not allow:
            return rect

        panes.append(hint)

        sizer, panes, docks, uiparts = self.LayoutAll(panes, docks, [], True, False)

        client_size = self._frame.GetClientSize()
        sizer.SetDimension(0, 0, client_size.x, client_size.y)
        sizer.Layout()

        sought = "__HINT__"

        # For a notebook page, actually look for the noteboot itself.
        if hint.IsNotebookPage():
            id = hint.notebook_id
            for pane in panes:
                if pane.IsNotebookControl() and pane.notebook_id==id:
                    sought = pane.name
                    break

        for part in uiparts:
            if part.pane and part.pane.name == sought:
                rect.Union(wx.RectPS(part.sizer_item.GetPosition(),
                                     part.sizer_item.GetSize()))

        sizer.Destroy()

        # check for floating frame ...
        if rect.IsEmpty():
            for p in panes:
                if p.name == sought and p.IsFloating():
                    return wx.RectPS(p.floating_pos, p.floating_size)

        if rect.IsEmpty():
            return rect

        # actually show the hint rectangle on the screen
        rect.x, rect.y = self._frame.ClientToScreen((rect.x, rect.y))
        if self._frame.GetLayoutDirection() == wx.Layout_RightToLeft:
            # Mirror rectangle in RTL mode
            rect.x -= rect.GetWidth()

        return rect

[docs]    def DrawHintRect(self, pane_window, pt, offset):
        """
        Calculates the hint rectangle by calling
        L{CalculateHintRect}. If there is a rectangle, it shows it
        by calling L{ShowHint}, otherwise it hides any hint
        rectangle currently shown.

        :param `pane_window`: it is the window pointer of the pane being dragged;
        :param `pt`: is the mouse position, in client coordinates;
        :param `offset`: describes the offset that the mouse is from the upper-left
         corner of the item being dragged.
        """

        rect = self.CalculateHintRect(pane_window, pt, offset)

        if rect.IsEmpty():
            self.HideHint()
            self._hint_rect = wx.Rect()
        else:
            self.ShowHint(rect)
            self._hint_rect = wx.Rect(*rect)

[docs]    def GetPartSizerRect(self, uiparts):
        """
        Returns the rectangle surrounding the specified UI parts.

        :param `uiparts`: UI parts.
        """

        rect = wx.Rect()

        for part in self._uiparts:
            if part.pane and part.pane.name == "__HINT__":
                rect.Union(wx.RectPS(part.sizer_item.GetPosition(),
                                     part.sizer_item.GetSize()))

        return rect

[docs]    def GetAttributes(self, pane):
        """
        Returns all the attributes of a L{AuiPaneInfo}.

        :param `pane`: a L{AuiPaneInfo} instance.
        """

        attrs = []
        attrs.extend([pane.window, pane.frame, pane.state, pane.dock_direction,
                      pane.dock_layer, pane.dock_pos, pane.dock_row, pane.dock_proportion,
                      pane.floating_pos, pane.floating_size, pane.best_size,
                      pane.min_size, pane.max_size, pane.caption, pane.name,
                      pane.buttons, pane.rect, pane.icon, pane.notebook_id,
                      pane.transparent, pane.snapped, pane.minimize_mode, pane.minimize_target])

        return attrs

[docs]    def SetAttributes(self, pane, attrs):
        """
        Sets all the attributes contained in `attrs` to a L{AuiPaneInfo}.

        :param `pane`: a L{AuiPaneInfo} instance;
        :param `attrs`: a list of attributes.
        """

        pane.window = attrs[0]
        pane.frame = attrs[1]
        pane.state = attrs[2]
        pane.dock_direction = attrs[3]
        pane.dock_layer = attrs[4]
        pane.dock_pos = attrs[5]
        pane.dock_row = attrs[6]
        pane.dock_proportion = attrs[7]
        pane.floating_pos = attrs[8]
        pane.floating_size = attrs[9]
        pane.best_size = attrs[10]
        pane.min_size = attrs[11]
        pane.max_size = attrs[12]
        pane.caption = attrs[13]
        pane.name = attrs[14]
        pane.buttons = attrs[15]
        pane.rect = attrs[16]
        pane.icon = attrs[17]
        pane.notebook_id = attrs[18]
        pane.transparent = attrs[19]
        pane.snapped = attrs[20]
        pane.minimize_mode = attrs[21]
        pane.minimize_target = attrs[22]

        return pane

[docs]    def OnFloatingPaneResized(self, wnd, size):
        """
        Handles the resizing of a floating pane.

        :param `wnd`: a `wx.Window` derived window, managed by the pane;
        :param `size`: a `wx.Size` object, specifying the new pane floating size.
        """

        # try to find the pane
        pane = self.GetPane(wnd)
        if not pane.IsOk():
            raise Exception("Pane window not found")

        if pane.frame:
            indx = self._panes.index(pane)
            pane.floating_pos = pane.frame.GetPosition()
            pane.floating_size = size
            self._panes[indx] = pane
            if pane.IsSnappable():
                self.SnapPane(pane, pane.floating_pos, pane.floating_size, True)

[docs]    def OnFloatingPaneClosed(self, wnd, event):
        """
        Handles the close event of a floating pane.

        :param `wnd`: a `wx.Window` derived window, managed by the pane;
        :param `event`: a `wx.CloseEvent` to be processed.
        """

        # try to find the pane
        pane = self.GetPane(wnd)
        if not pane.IsOk():
            raise Exception("Pane window not found")

        # fire pane close event
        e = AuiManagerEvent(wxEVT_AUI_PANE_CLOSE)
        e.SetPane(pane)
        e.SetCanVeto(event.CanVeto())
        self.ProcessMgrEvent(e)

        if e.GetVeto():
            event.Veto()
            return
        else:
            # close the pane, but check that it
            # still exists in our pane array first
            # (the event handler above might have removed it)

            check = self.GetPane(wnd)
            if check.IsOk():
                self.ClosePane(pane)

[docs]    def OnFloatingPaneActivated(self, wnd):
        """
        Handles the activation event of a floating pane.

        :param `wnd`: a `wx.Window` derived window, managed by the pane.
        """

        pane = self.GetPane(wnd)
        if not pane.IsOk():
            raise Exception("Pane window not found")

        if self.GetAGWFlags() & AUI_MGR_ALLOW_ACTIVE_PANE:
            ret, self._panes = SetActivePane(self._panes, wnd)
            self.RefreshCaptions()
            self.FireEvent(wxEVT_AUI_PANE_ACTIVATED, wnd, canVeto=False)

[docs]    def OnFloatingPaneMoved(self, wnd, eventOrPt):
        """
        Handles the move event of a floating pane.

        :param `wnd`: a `wx.Window` derived window, managed by the pane;
        :param `eventOrPt`: a `wx.MoveEvent` to be processed or an instance of `wx.Point`.
        """

        pane = self.GetPane(wnd)
        if not pane.IsOk():
            raise Exception("Pane window not found")

        if not pane.IsSnappable():
            return

        if isinstance(eventOrPt, wx.Point):
            pane_pos = wx.Point(*eventOrPt)
        else:
            pane_pos = eventOrPt.GetPosition()

        pane_size = pane.floating_size

        self.SnapPane(pane, pane_pos, pane_size, False)

[docs]    def SnapPane(self, pane, pane_pos, pane_size, toSnap=False):
        """
        Snaps a floating pane to one of the main frame sides.

        :param `pane`: a L{AuiPaneInfo} instance;
        :param `pane_pos`: the new pane floating position;
        :param `pane_size`: the new pane floating size;
        :param `toSnap`: a bool variable to check if L{SnapPane} was called from
         a move event.
        """

        if self._from_move:
            return

        managed_window = self.GetManagedWindow()
        wnd_pos = managed_window.GetPosition()
        wnd_size = managed_window.GetSize()
        snapX, snapY = self._snap_limits

        if not toSnap:
            pane.snapped = 0
            if pane.IsLeftSnappable():
                # Check if we can snap to the left
                diff = wnd_pos.x - (pane_pos.x + pane_size.x)
                if -snapX <= diff <= snapX:
                    pane.snapped = wx.LEFT
                    pane.floating_pos = wx.Point(wnd_pos.x-pane_size.x, pane_pos.y)
            elif pane.IsTopSnappable():
                # Check if we can snap to the top
                diff = wnd_pos.y - (pane_pos.y + pane_size.y)
                if -snapY <= diff <= snapY:
                    pane.snapped = wx.TOP
                    pane.floating_pos = wx.Point(pane_pos.x, wnd_pos.y-pane_size.y)
            elif pane.IsRightSnappable():
                # Check if we can snap to the right
                diff = pane_pos.x - (wnd_pos.x + wnd_size.x)
                if -snapX <= diff <= snapX:
                    pane.snapped = wx.RIGHT
                    pane.floating_pos = wx.Point(wnd_pos.x + wnd_size.x, pane_pos.y)
            elif pane.IsBottomSnappable():
                # Check if we can snap to the bottom
                diff = pane_pos.y - (wnd_pos.y + wnd_size.y)
                if -snapY <= diff <= snapY:
                    pane.snapped = wx.BOTTOM
                    pane.floating_pos = wx.Point(pane_pos.x, wnd_pos.y + wnd_size.y)

        self.RepositionPane(pane, wnd_pos, wnd_size)

[docs]    def RepositionPane(self, pane, wnd_pos, wnd_size):
        """
        Repositions a pane after the main frame has been moved/resized.

        :param `pane`: a L{AuiPaneInfo} instance;
        :param `wnd_pos`: the main frame position;
        :param `wnd_size`: the main frame size.
        """

        pane_pos = pane.floating_pos
        pane_size = pane.floating_size

        snap = pane.snapped
        if snap == wx.LEFT:
            floating_pos = wx.Point(wnd_pos.x - pane_size.x, pane_pos.y)
        elif snap == wx.TOP:
            floating_pos = wx.Point(pane_pos.x, wnd_pos.y - pane_size.y)
        elif snap == wx.RIGHT:
            floating_pos = wx.Point(wnd_pos.x + wnd_size.x, pane_pos.y)
        elif snap == wx.BOTTOM:
            floating_pos = wx.Point(pane_pos.x, wnd_pos.y + wnd_size.y)

        if snap:
            if pane_pos != floating_pos:
                pane.floating_pos = floating_pos
                self._from_move = True
                pane.frame.SetPosition(pane.floating_pos)
                self._from_move = False

[docs]    def OnGripperClicked(self, pane_window, start, offset):
        """
        Handles the mouse click on the pane gripper.

        :param `pane_window`: a `wx.Window` derived window, managed by the pane;
        :param `start`: a `wx.Point` object, specifying the clicking position;
        :param `offset`: an offset point from the `start` position.
        """

        # try to find the pane
        paneInfo = self.GetPane(pane_window)

        if not paneInfo.IsOk():
            raise Exception("Pane window not found")

        if self.GetAGWFlags() & AUI_MGR_ALLOW_ACTIVE_PANE:
            # set the caption as active
            ret, self._panes = SetActivePane(self._panes, pane_window)
            self.RefreshCaptions()
            self.FireEvent(wxEVT_AUI_PANE_ACTIVATED, pane_window, canVeto=False)

        self._action_part = None
        self._action_pane = paneInfo
        self._action_window = pane_window
        self._action_start = start
        self._action_offset = offset
        self._toolbar_action_offset = wx.Point(*self._action_offset)

        self._frame.CaptureMouse()

        if paneInfo.IsDocked():
            self._action = actionClickCaption
        else:
            if paneInfo.IsToolbar():
                self._action = actionDragToolbarPane
            else:
                self._action = actionDragFloatingPane

            if paneInfo.frame:

                windowPt = paneInfo.frame.GetRect().GetTopLeft()
                originPt = paneInfo.frame.ClientToScreen(wx.Point())
                self._action_offset += originPt - windowPt
                self._toolbar_action_offset = wx.Point(*self._action_offset)

                if self._agwFlags & AUI_MGR_TRANSPARENT_DRAG:
                    paneInfo.frame.SetTransparent(150)

            if paneInfo.IsToolbar():
                self._frame.SetCursor(wx.StockCursor(wx.CURSOR_SIZING))

[docs]    def OnRender(self, event):
        """
        Draws all of the pane captions, sashes,
        backgrounds, captions, grippers, pane borders and buttons.
        It renders the entire user interface. It binds the ``EVT_AUI_RENDER`` event.

        :param `event`: an instance of L{AuiManagerEvent}.
        """

        # if the frame is about to be deleted, don't bother
        if not self._frame or self._frame.IsBeingDeleted():
            return

        if not self._frame.GetSizer():
            return

        mouse = wx.GetMouseState()
        mousePos = wx.Point(mouse.GetX(), mouse.GetY())
        point = self._frame.ScreenToClient(mousePos)
        art = self._art

        dc = event.GetDC()

        for part in self._uiparts:

            # don't draw hidden pane items or items that aren't windows
            if part.sizer_item and ((not part.sizer_item.IsWindow() and \
                                     not part.sizer_item.IsSpacer() and \
                                     not part.sizer_item.IsSizer()) or \
                                    not part.sizer_item.IsShown()):

                continue

            ptype = part.type

            if ptype in [AuiDockUIPart.typeDockSizer, AuiDockUIPart.typePaneSizer]:
                art.DrawSash(dc, self._frame, part.orientation, part.rect)

            elif ptype == AuiDockUIPart.typeBackground:
                art.DrawBackground(dc, self._frame, part.orientation, part.rect)

            elif ptype == AuiDockUIPart.typeCaption:
                art.DrawCaption(dc, self._frame, part.pane.caption, part.rect, part.pane)

            elif ptype == AuiDockUIPart.typeGripper:
                art.DrawGripper(dc, self._frame, part.rect, part.pane)

            elif ptype == AuiDockUIPart.typePaneBorder:
                art.DrawBorder(dc, self._frame, part.rect, part.pane)

            elif ptype == AuiDockUIPart.typePaneButton:
                self.DrawPaneButton(dc, part, point)

[docs]    def Repaint(self, dc=None):
        """
        Repaints the entire frame decorations (sashes, borders, buttons and so on).
        It renders the entire user interface.

        :param `dc`: if not ``None``, an instance of `wx.PaintDC`.
        """

        w, h = self._frame.GetClientSize()

        # Figure out which dc to use; if one
        # has been specified, use it, otherwise
        # make a client dc
        if dc is None:
            client_dc = wx.ClientDC(self._frame)
            dc = client_dc

        # If the frame has a toolbar, the client area
        # origin will not be (0, 0).
        pt = self._frame.GetClientAreaOrigin()
        if pt.x != 0 or pt.y != 0:
            dc.SetDeviceOrigin(pt.x, pt.y)

        # Render all the items
        self.Render(dc)

[docs]    def Render(self, dc):
        """
        Fires a render event, which is normally handled by
        L{OnRender}. This allows the render function to
        be overridden via the render event.

        This can be useful for painting custom graphics in the main window.
        Default behavior can be invoked in the overridden function by calling
        L{OnRender}.

        :param `dc`: a `wx.DC` device context object.
        """

        e = AuiManagerEvent(wxEVT_AUI_RENDER)
        e.SetManager(self)
        e.SetDC(dc)
        self.ProcessMgrEvent(e)

[docs]    def OnCaptionDoubleClicked(self, pane_window):
        """
        Handles the mouse double click on the pane caption.

        :param `pane_window`: a `wx.Window` derived window, managed by the pane.
        """

        # try to find the pane
        paneInfo = self.GetPane(pane_window)
        if not paneInfo.IsOk():
            raise Exception("Pane window not found")

        if not paneInfo.IsFloatable() or not paneInfo.IsDockable() or \
           self._agwFlags & AUI_MGR_ALLOW_FLOATING == 0:
            return

        indx = self._panes.index(paneInfo)
        win_rect = None

        if paneInfo.IsFloating():
            if paneInfo.name.startswith("__floating__"):
                # It's a floating tab from a AuiNotebook
                notebook = paneInfo.window.__aui_notebook__
                notebook.ReDockPage(paneInfo)
                self.Update()
                return
            else:

                e = self.FireEvent(wxEVT_AUI_PANE_DOCKING, paneInfo, canVeto=True)
                if e.GetVeto():
                    self.HideHint()
                    ShowDockingGuides(self._guides, False)
                    return

                win_rect = paneInfo.frame.GetRect()
                paneInfo.Dock()
                if paneInfo.IsToolbar():
                    paneInfo = self.SwitchToolBarOrientation(paneInfo)

                e = self.FireEvent(wxEVT_AUI_PANE_DOCKED, paneInfo, canVeto=False)

        else:

            e = self.FireEvent(wxEVT_AUI_PANE_FLOATING, paneInfo, canVeto=True)
            if e.GetVeto():
                return

            # float the window
            if paneInfo.IsMaximized():
                self.RestorePane(paneInfo)

            if paneInfo.floating_pos == wx.Point(-1, -1):
                captionSize = self._art.GetMetric(AUI_DOCKART_CAPTION_SIZE)
                paneInfo.floating_pos = pane_window.GetScreenPosition()
                paneInfo.floating_pos.y -= captionSize

            paneInfo.Float()
            e = self.FireEvent(wxEVT_AUI_PANE_FLOATED, paneInfo, canVeto=False)

        self._panes[indx] = paneInfo
        self.Update()

        if win_rect and self._agwFlags & AUI_MGR_ANIMATE_FRAMES:
            paneInfo = self.GetPane(pane_window)
            pane_rect = paneInfo.window.GetScreenRect()
            self.AnimateDocking(win_rect, pane_rect)

[docs]    def OnPaint(self, event):
        """
        Handles the ``wx.EVT_PAINT`` event for L{AuiManager}.

        :param `event`: an instance of `wx.PaintEvent` to be processed.
        """

        dc = wx.PaintDC(self._frame)
        self.Repaint(dc)

[docs]    def OnEraseBackground(self, event):
        """
        Handles the ``wx.EVT_ERASE_BACKGROUND`` event for L{AuiManager}.

        :param `event`: `wx.EraseEvent` to be processed.

        :note: This is intentionally empty (excluding wxMAC) to reduce
         flickering while drawing.
        """

        if wx.Platform == "__WXMAC__":
            event.Skip()

[docs]    def OnSize(self, event):
        """
        Handles the ``wx.EVT_SIZE`` event for L{AuiManager}.

        :param `event`: a `wx.SizeEvent` to be processed.
        """

        skipped = False
        if isinstance(self._frame, AuiFloatingFrame) and self._frame.IsShownOnScreen():
            skipped = True
            event.Skip()

        if self._frame:

            self.DoFrameLayout()
            if wx.Platform == "__WXMAC__":
                self._frame.Refresh()
            else:
                self.Repaint()

            if isinstance(self._frame, wx.MDIParentFrame) or isinstance(self._frame, tabmdi.AuiMDIClientWindow) \
               or isinstance(self._frame, tabmdi.AuiMDIParentFrame):
                # for MDI parent frames, this event must not
                # be "skipped".  In other words, the parent frame
                # must not be allowed to resize the client window
                # after we are finished processing sizing changes
                return

        if not skipped:
            event.Skip()

        # For the snap to screen...
        self.OnMove(None)

[docs]    def OnFindManager(self, event):
        """
        Handles the ``EVT_AUI_FIND_MANAGER`` event for L{AuiManager}.

        :param `event`: a L{AuiManagerEvent} event to be processed.
        """

        # Initialize to None
        event.SetManager(None)

        if not self._frame:
            return

        # See it this window wants to overwrite
        self._frame.ProcessEvent(event)

        # if no, it must be us
        if not event.GetManager():
           event.SetManager(self)

[docs]    def OnSetCursor(self, event):
        """
        Handles the ``wx.EVT_SET_CURSOR`` event for L{AuiManager}.

        :param `event`: a `wx.SetCursorEvent` to be processed.
        """

        # determine cursor
        part = self.HitTest(event.GetX(), event.GetY())
        cursor = wx.NullCursor

        if part:
            if part.type in [AuiDockUIPart.typeDockSizer, AuiDockUIPart.typePaneSizer]:

                if not self.CheckMovableSizer(part):
                    return

                if part.orientation == wx.VERTICAL:
                    cursor = wx.StockCursor(wx.CURSOR_SIZEWE)
                else:
                    cursor = wx.StockCursor(wx.CURSOR_SIZENS)

            elif part.type == AuiDockUIPart.typeGripper:
                cursor = wx.StockCursor(wx.CURSOR_SIZING)

        event.SetCursor(cursor)

[docs]    def UpdateButtonOnScreen(self, button_ui_part, event):
        """
        Updates/redraws the UI part containing a pane button.

        :param `button_ui_part`: the UI part the button belongs to;
        :param `event`: a `wx.MouseEvent` to be processed.
        """

        hit_test = self.HitTest(*event.GetPosition())

        if not hit_test or not button_ui_part:
            return

        state = AUI_BUTTON_STATE_NORMAL

        if hit_test == button_ui_part:
            if event.LeftDown():
                state = AUI_BUTTON_STATE_PRESSED
            else:
                state = AUI_BUTTON_STATE_HOVER
        else:
            if event.LeftDown():
                state = AUI_BUTTON_STATE_HOVER

        # now repaint the button with hover state
        cdc = wx.ClientDC(self._frame)

        # if the frame has a toolbar, the client area
        # origin will not be (0,0).
        pt = self._frame.GetClientAreaOrigin()
        if pt.x != 0 or pt.y != 0:
            cdc.SetDeviceOrigin(pt.x, pt.y)

        if hit_test.pane:
            self._art.DrawPaneButton(cdc, self._frame,
                      button_ui_part.button.button_id,
                      state,
                      button_ui_part.rect, hit_test.pane)

[docs]    def OnLeftDown(self, event):
        """
        Handles the ``wx.EVT_LEFT_DOWN`` event for L{AuiManager}.

        :param `event`: a `wx.MouseEvent` to be processed.
        """

        part = self.HitTest(*event.GetPosition())

        if not part:
            event.Skip()
            return

        self._currentDragItem = -1

        if part.type in [AuiDockUIPart.typeDockSizer, AuiDockUIPart.typePaneSizer]:

            if not self.CheckMovableSizer(part):
                return

            self._action = actionResize
            self._action_part = part
            self._action_pane = None
            self._action_rect = wx.Rect()
            self._action_start = wx.Point(event.GetX(), event.GetY())
            self._action_offset = wx.Point(event.GetX() - part.rect.x,
                                           event.GetY() - part.rect.y)

            # draw the resize hint
            rect = wx.RectPS(self._frame.ClientToScreen(part.rect.GetPosition()),
                             part.rect.GetSize())

            self._action_rect = wx.Rect(*rect)

            if not AuiManager_HasLiveResize(self):
                if wx.Platform == "__WXMAC__":
                    dc = wx.ClientDC(self._frame)
                else:
                    dc = wx.ScreenDC()

                DrawResizeHint(dc, rect)

            self._frame.CaptureMouse()

        elif part.type == AuiDockUIPart.typePaneButton:
            if self.IsPaneButtonVisible(part):
                self._action = actionClickButton
                self._action_part = part
                self._action_pane = None
                self._action_start = wx.Point(*event.GetPosition())
                self._frame.CaptureMouse()

                self.RefreshButton(part)

        elif part.type in [AuiDockUIPart.typeCaption, AuiDockUIPart.typeGripper]:

            # if we are managing a AuiFloatingFrame window, then
            # we are an embedded AuiManager inside the AuiFloatingFrame.
            # We want to initiate a toolbar drag in our owner manager
            if isinstance(part.pane.window.GetParent(), AuiFloatingFrame):
                rootManager = GetManager(part.pane.window)
            else:
                rootManager = self

            offset = wx.Point(event.GetX() - part.rect.x, event.GetY() - part.rect.y)
            rootManager.OnGripperClicked(part.pane.window, event.GetPosition(), offset)

        if wx.Platform != "__WXMAC__":
            event.Skip()

[docs]    def OnLeftDClick(self, event):
        """
        Handles the ``wx.EVT_LEFT_DCLICK`` event for L{AuiManager}.

        :param `event`: a `wx.MouseEvent` to be processed.
        """

        part = self.HitTest(event.GetX(), event.GetY())

        if part and part.type == AuiDockUIPart.typeCaption:
            if isinstance(part.pane.window.GetParent(), AuiFloatingFrame):
                rootManager = GetManager(part.pane.window)
            else:
                rootManager = self

            rootManager.OnCaptionDoubleClicked(part.pane.window)

        elif part and part.type in [AuiDockUIPart.typeDockSizer, AuiDockUIPart.typePaneSizer]:
            # Handles double click on AuiNotebook sashes to unsplit
            sash_size = self._art.GetMetric(AUI_DOCKART_SASH_SIZE)
            for child in part.cont_sizer.GetChildren():
                if child.IsSizer():
                    win = child.GetSizer().GetContainingWindow()
                    if isinstance(win, auibook.AuiNotebook):
                        win.UnsplitDClick(part, sash_size, event.GetPosition())
                        break

        event.Skip()

[docs]    def DoEndResizeAction(self, event):
        """
        Ends a resize action, or for live update, resizes the sash.

        :param `event`: a `wx.MouseEvent` to be processed.
        """

        clientPt = event.GetPosition()
        screenPt = self._frame.ClientToScreen(clientPt)

        return self.RestrictResize(clientPt, screenPt, createDC=False)

[docs]    def RestrictResize(self, clientPt, screenPt, createDC):
        """ Common method between L{DoEndResizeAction} and L{OnLeftUp_Resize}. """

        dock = self._action_part.dock
        pane = self._action_part.pane

        if createDC:
            if wx.Platform == "__WXMAC__":
                dc = wx.ClientDC(self._frame)
            else:
                dc = wx.ScreenDC()

            DrawResizeHint(dc, self._action_rect)
            self._action_rect = wx.Rect()

        newPos = clientPt - self._action_offset

        if self._action_part.type == AuiDockUIPart.typeDockSizer:
            minPix, maxPix = self.CalculateDockSizerLimits(dock)
        else:
            if not self._action_part.pane:
                return
            minPix, maxPix = self.CalculatePaneSizerLimits(dock, pane)

        if self._action_part.orientation == wx.HORIZONTAL:
            newPos.y = Clip(newPos.y, minPix, maxPix)
        else:
            newPos.x = Clip(newPos.x, minPix, maxPix)

        if self._action_part.type == AuiDockUIPart.typeDockSizer:

            partnerDock = self.GetPartnerDock(dock)
            sash_size = self._art.GetMetric(AUI_DOCKART_SASH_SIZE)
            new_dock_size = 0
            direction = dock.dock_direction

            if direction == AUI_DOCK_LEFT:
                new_dock_size = newPos.x - dock.rect.x

            elif direction == AUI_DOCK_TOP:
                new_dock_size = newPos.y - dock.rect.y

            elif direction == AUI_DOCK_RIGHT:
                new_dock_size = dock.rect.x + dock.rect.width - newPos.x - sash_size

            elif direction == AUI_DOCK_BOTTOM:
                new_dock_size = dock.rect.y + dock.rect.height - newPos.y - sash_size

            deltaDockSize = new_dock_size - dock.size

            if partnerDock:
                if deltaDockSize > partnerDock.size - sash_size:
                    deltaDockSize = partnerDock.size - sash_size

                partnerDock.size -= deltaDockSize

            dock.size += deltaDockSize
            self.Update()

        else:

            # determine the new pixel size that the user wants
            # this will help us recalculate the pane's proportion
            if dock.IsHorizontal():
                oldPixsize = pane.rect.width
                newPixsize = oldPixsize + newPos.x - self._action_part.rect.x

            else:
                oldPixsize = pane.rect.height
                newPixsize = oldPixsize + newPos.y - self._action_part.rect.y

            totalPixsize, totalProportion = self.GetTotalPixSizeAndProportion(dock)
            partnerPane = self.GetPartnerPane(dock, pane)

            # prevent division by zero
            if totalPixsize <= 0 or totalProportion <= 0 or not partnerPane:
                return

            # adjust for the surplus
            while (oldPixsize > 0 and totalPixsize > 10 and \
                  oldPixsize*totalProportion/totalPixsize < pane.dock_proportion):

                totalPixsize -= 1

            # calculate the new proportion of the pane

            newProportion = newPixsize*totalProportion/totalPixsize
            newProportion = Clip(newProportion, 1, totalProportion)
            deltaProp = newProportion - pane.dock_proportion

            if partnerPane.dock_proportion - deltaProp < 1:
                deltaProp = partnerPane.dock_proportion - 1
                newProportion = pane.dock_proportion + deltaProp

            # borrow the space from our neighbor pane to the
            # right or bottom (depending on orientation)
            partnerPane.dock_proportion -= deltaProp
            pane.dock_proportion = newProportion

            self.Update()

        return True

[docs]    def OnLeftUp(self, event):
        """
        Handles the ``wx.EVT_LEFT_UP`` event for L{AuiManager}.

        :param `event`: a `wx.MouseEvent` to be processed.
        """

        if self._action == actionResize:
##            self._frame.Freeze()
            self.OnLeftUp_Resize(event)
##            self._frame.Thaw()

        elif self._action == actionClickButton:
            self.OnLeftUp_ClickButton(event)

        elif self._action == actionDragFloatingPane:
            self.OnLeftUp_DragFloatingPane(event)

        elif self._action == actionDragToolbarPane:
            self.OnLeftUp_DragToolbarPane(event)

        else:
            event.Skip()

        if self._frame.HasCapture():
            self._frame.ReleaseMouse()

        self._action = actionNone

[docs]    def OnMotion(self, event):
        """
        Handles the ``wx.EVT_MOTION`` event for L{AuiManager}.

        :param `event`: a `wx.MouseEvent` to be processed.
        """

        if self._action == actionResize:
            self.OnMotion_Resize(event)

        elif self._action == actionClickCaption:
            self.OnMotion_ClickCaption(event)

        elif self._action == actionDragFloatingPane:
            self.OnMotion_DragFloatingPane(event)

        elif self._action == actionDragToolbarPane:
            self.OnMotion_DragToolbarPane(event)

        else:
            self.OnMotion_Other(event)

[docs]    def OnLeaveWindow(self, event):
        """
        Handles the ``wx.EVT_LEAVE_WINDOW`` event for L{AuiManager}.

        :param `event`: a `wx.MouseEvent` to be processed.
        """

        if self._hover_button:
            self.RefreshButton(self._hover_button)
            self._hover_button = None

[docs]    def OnCaptureLost(self, event):
        """
        Handles the ``wx.EVT_MOUSE_CAPTURE_LOST`` event for L{AuiManager}.

        :param `event`: a `wx.MouseCaptureLostEvent` to be processed.
        """

        # cancel the operation in progress, if any
        if self._action != actionNone:
            self._action = actionNone
            self.HideHint()

[docs]    def OnHintFadeTimer(self, event):
        """
        Handles the ``wx.EVT_TIMER`` event for L{AuiManager}.

        :param `event`: a `wx.TimerEvent` to be processed.
        """

        if not self._hint_window or self._hint_fadeamt >= self._hint_fademax:
            self._hint_fadetimer.Stop()
            return

        self._hint_fadeamt += 4
        self._hint_window.SetTransparent(self._hint_fadeamt)

[docs]    def OnMove(self, event):
        """
        Handles the ``wx.EVT_MOVE`` event for L{AuiManager}.

        :param `event`: a `wx.MoveEvent` to be processed.
        """

        if event is not None:
            event.Skip()

        if isinstance(self._frame, AuiFloatingFrame) and self._frame.IsShownOnScreen():
            return

        docked, hAlign, vAlign, monitor = self._is_docked
        if docked:
            self.Snap()

        for pane in self._panes:
            if pane.IsSnappable():
                if pane.IsFloating() and pane.IsShown():
                    self.SnapPane(pane, pane.floating_pos, pane.floating_size, True)

[docs]    def OnSysColourChanged(self, event):
        """
        Handles the ``wx.EVT_SYS_COLOUR_CHANGED`` event for L{AuiManager}.

        :param `event`: a `wx.SysColourChangedEvent` to be processed.
        """

        # This event is probably triggered by a theme change
        # so we have to re-init the art provider.
        if self._art:
            self._art.Init()

        if self._frame:
            self.Update()
            self._frame.Refresh()

[docs]    def OnChildFocus(self, event):
        """
        Handles the ``wx.EVT_CHILD_FOCUS`` event for L{AuiManager}.

        :param `event`: a `wx.ChildFocusEvent` to be processed.
        """

        # when a child pane has it's focus set, we should change the
        # pane's active state to reflect this. (this is only true if
        # active panes are allowed by the owner)

        window = event.GetWindow()
        if isinstance(window, wx.Dialog):
            # Ignore EVT_CHILD_FOCUS events originating from dialogs not
            # managed by AUI
            rootManager = None
        elif isinstance(window.GetParent(), AuiFloatingFrame):
            rootManager = GetManager(window)
        else:
            rootManager = self

        if rootManager:
            rootManager.ActivatePane(window)

        event.Skip()

[docs]    def OnMotion_ClickCaption(self, event):
        """
        Sub-handler for the L{OnMotion} event.

        :param `event`: a `wx.MouseEvent` to be processed.
        """

        clientPt = event.GetPosition()
        screenPt = self._frame.ClientToScreen(clientPt)

        drag_x_threshold = wx.SystemSettings.GetMetric(wx.SYS_DRAG_X)
        drag_y_threshold = wx.SystemSettings.GetMetric(wx.SYS_DRAG_Y)

        if not self._action_pane:
            return

        # we need to check if the mouse is now being dragged
        if not (abs(clientPt.x - self._action_start.x) > drag_x_threshold or \
                abs(clientPt.y - self._action_start.y) > drag_y_threshold):

            return

        # dragged -- we need to change the mouse action to 'drag'
        if self._action_pane.IsToolbar():
            self._action = actionDragToolbarPane
            self._action_window = self._action_pane.window

        elif self._action_pane.IsFloatable() and self._agwFlags & AUI_MGR_ALLOW_FLOATING:

            e = self.FireEvent(wxEVT_AUI_PANE_FLOATING, self._action_pane, canVeto=True)
            if e.GetVeto():
                return

            self._action = actionDragFloatingPane

            # set initial float position
            self._action_pane.floating_pos = screenPt - self._action_offset

            # float the window
            if self._action_pane.IsMaximized():
                self.RestorePane(self._action_pane)

            self._action_pane.Hide()
            self._action_pane.Float()
            if wx.Platform == "__WXGTK__":
                self._action_pane.Show()

            e = self.FireEvent(wxEVT_AUI_PANE_FLOATED, self._action_pane, canVeto=False)

            if not self._action_pane.frame:
                self.Update()

            self._action_window = self._action_pane.window

            # adjust action offset for window frame
            windowPt = self._action_pane.frame.GetRect().GetTopLeft()
            originPt = self._action_pane.frame.ClientToScreen(wx.Point())
            self._toolbar_action_offset = originPt - windowPt

            if self._agwFlags & AUI_MGR_USE_NATIVE_MINIFRAMES:
                originPt = windowPt + wx.Point(3, 3)

            self._action_offset += originPt - windowPt

            # action offset is used here to make it feel "natural" to the user
            # to drag a docked pane and suddenly have it become a floating frame.
            # Sometimes, however, the offset where the user clicked on the docked
            # caption is bigger than the width of the floating frame itself, so
            # in that case we need to set the action offset to a sensible value
            frame_size = self._action_pane.frame.GetSize()
            if self._action_offset.x > frame_size.x * 2 / 3:
                self._action_offset.x = frame_size.x / 2
            if self._action_offset.y > frame_size.y * 2 / 3:
                self._action_offset.y = frame_size.y / 2

            self.OnMotion_DragFloatingPane(event)
            if wx.Platform != "__WXGTK__":
                self._action_pane.Show()

            self.Update()

[docs]    def OnMotion_Resize(self, event):
        """
        Sub-handler for the L{OnMotion} event.

        :param `event`: a `wx.MouseEvent` to be processed.
        """

        if AuiManager_HasLiveResize(self):
            if self._currentDragItem != -1:
                self._action_part = self._uiparts[self._currentDragItem]
            else:
                self._currentDragItem = self._uiparts.index(self._action_part)

            if self._frame.HasCapture():
                self._frame.ReleaseMouse()

            self.DoEndResizeAction(event)
            self._frame.CaptureMouse()
            return

        if not self._action_part or not self._action_part.dock or not self._action_part.orientation:
            return

        clientPt = event.GetPosition()
        screenPt = self._frame.ClientToScreen(clientPt)

        dock = self._action_part.dock
        pos = self._action_part.rect.GetPosition()

        if self._action_part.type == AuiDockUIPart.typeDockSizer:
            minPix, maxPix = self.CalculateDockSizerLimits(dock)
        else:
            if not self._action_part.pane:
                return

            pane = self._action_part.pane
            minPix, maxPix = self.CalculatePaneSizerLimits(dock, pane)

        if self._action_part.orientation == wx.HORIZONTAL:
            pos.y = Clip(clientPt.y - self._action_offset.y, minPix, maxPix)
        else:
            pos.x = Clip(clientPt.x - self._action_offset.x, minPix, maxPix)

        hintrect = wx.RectPS(self._frame.ClientToScreen(pos), self._action_part.rect.GetSize())

        if hintrect != self._action_rect:

            if wx.Platform == "__WXMAC__":
                dc = wx.ClientDC(self._frame)
            else:
                dc = wx.ScreenDC()

            DrawResizeHint(dc, self._action_rect)
            DrawResizeHint(dc, hintrect)
            self._action_rect = wx.Rect(*hintrect)

[docs]    def OnLeftUp_Resize(self, event):
        """
        Sub-handler for the L{OnLeftUp} event.

        :param `event`: a `wx.MouseEvent` to be processed.
        """

        if self._currentDragItem != -1 and AuiManager_HasLiveResize(self):
            self._action_part = self._uiparts[self._currentDragItem]

            if self._frame.HasCapture():
                self._frame.ReleaseMouse()

            self.DoEndResizeAction(event)
            self._currentDragItem = -1
            return

        if not self._action_part or not self._action_part.dock:
            return

        clientPt = event.GetPosition()
        screenPt = self._frame.ClientToScreen(clientPt)

        return self.RestrictResize(clientPt, screenPt, createDC=True)

[docs]    def OnLeftUp_ClickButton(self, event):
        """
        Sub-handler for the L{OnLeftUp} event.

        :param `event`: a `wx.MouseEvent` to be processed.
        """

        self._hover_button = None

        if self._action_part:
            self.RefreshButton(self._action_part)

            # make sure we're still over the item that was originally clicked
            if self._action_part == self.HitTest(*event.GetPosition()):

                # fire button-click event
                e = AuiManagerEvent(wxEVT_AUI_PANE_BUTTON)
                e.SetManager(self)
                e.SetPane(self._action_part.pane)
                e.SetButton(self._action_part.button.button_id)
                self.ProcessMgrEvent(e)

[docs]    def CheckPaneMove(self, pane):
        """
        Checks if a pane has moved by a visible amount.

        :param `pane`: an instance of L{AuiPaneInfo}.
        """

        win_rect = pane.frame.GetRect()
        win_rect.x, win_rect.y = pane.floating_pos

        if win_rect == self._last_rect:
            return False

        # skip the first move event
        if self._last_rect.IsEmpty():
            self._last_rect = wx.Rect(*win_rect)
            return False

        # skip if moving too fast to avoid massive redraws and
        # jumping hint windows
        if abs(win_rect.x - self._last_rect.x) > 10 or \
           abs(win_rect.y - self._last_rect.y) > 10:
            self._last_rect = wx.Rect(*win_rect)
            return False

        return True

[docs]    def OnMotion_DragFloatingPane(self, eventOrPt):
        """
        Sub-handler for the L{OnMotion} event.

        :param `event`: a `wx.MouseEvent` to be processed.
        """

        isPoint = False
        if isinstance(eventOrPt, wx.Point):
            clientPt = self._frame.ScreenToClient(eventOrPt)
            screenPt = wx.Point(*eventOrPt)
            isPoint = True
        else:
            clientPt = eventOrPt.GetPosition()
            screenPt = self._frame.ClientToScreen(clientPt)

        framePos = wx.Point()

        # try to find the pane
        pane = self.GetPane(self._action_window)
        if not pane.IsOk():
            raise Exception("Pane window not found")

        # update floating position
        if pane.IsFloating():
            diff = pane.floating_pos - (screenPt - self._action_offset)
            pane.floating_pos = screenPt - self._action_offset

        framePos = pane.floating_pos

        # Move the pane window
        if pane.frame:

            if diff.x != 0 or diff.y != 0:
                if wx.Platform == "__WXMSW__" and (self._agwFlags & AUI_MGR_TRANSPARENT_DRAG) == 0: # and not self.CheckPaneMove(pane):
                    # return
                    # HACK: Terrible hack on wxMSW (!)
                    pane.frame.SetTransparent(254)

                self._from_move = True
                pane.frame.Move(pane.floating_pos)
                self._from_move = False

            if self._agwFlags & AUI_MGR_TRANSPARENT_DRAG:
                pane.frame.SetTransparent(150)

        # calculate the offset from the upper left-hand corner
        # of the frame to the mouse pointer
        action_offset = screenPt - framePos

        # is the pane dockable?
        if not self.CanDockPanel(pane):
            self.HideHint()
            ShowDockingGuides(self._guides, False)
            return

        for paneInfo in self._panes:

            if not paneInfo.IsDocked() or not paneInfo.IsShown():
                continue
            if paneInfo.IsToolbar() or paneInfo.IsNotebookControl():
                continue
            if paneInfo.IsMaximized():
                continue

            if paneInfo.IsNotebookPage():

                notebookRoot = GetNotebookRoot(self._panes, paneInfo.notebook_id)

                if not notebookRoot or not notebookRoot.IsDocked():
                    continue

            rc = paneInfo.window.GetScreenRect()
            if rc.Contains(screenPt):
                if rc.height < 20 or rc.width < 20:
                    return

                self.UpdateDockingGuides(paneInfo)
                ShowDockingGuides(self._guides, True)
                break

        self.DrawHintRect(pane.window, clientPt, action_offset)

[docs]    def OnLeftUp_DragFloatingPane(self, eventOrPt):
        """
        Sub-handler for the L{OnLeftUp} event.

        :param `event`: a `wx.MouseEvent` to be processed.
        """

        if isinstance(eventOrPt, wx.Point):
            clientPt = self._frame.ScreenToClient(eventOrPt)
            screenPt = wx.Point(*eventOrPt)
        else:
            clientPt = eventOrPt.GetPosition()
            screenPt = self._frame.ClientToScreen(clientPt)

        # try to find the pane
        paneInfo = self.GetPane(self._action_window)
        if not paneInfo.IsOk():
            raise Exception("Pane window not found")

        ret = False

        if paneInfo.frame:

            # calculate the offset from the upper left-hand corner
            # of the frame to the mouse pointer
            framePos = paneInfo.frame.GetPosition()
            action_offset = screenPt - framePos

            # is the pane dockable?
            if self.CanDockPanel(paneInfo):
                # do the drop calculation
                indx = self._panes.index(paneInfo)
                ret, paneInfo = self.DoDrop(self._docks, self._panes, paneInfo, clientPt, action_offset)

                if ret:
                    e = self.FireEvent(wxEVT_AUI_PANE_DOCKING, paneInfo, canVeto=True)
                    if e.GetVeto():
                        self.HideHint()
                        ShowDockingGuides(self._guides, False)
                        return

                    e = self.FireEvent(wxEVT_AUI_PANE_DOCKED, paneInfo, canVeto=False)

                    if self._agwFlags & AUI_MGR_SMOOTH_DOCKING:
                        self.SmoothDock(paneInfo)

                self._panes[indx] = paneInfo

        # if the pane is still floating, update it's floating
        # position (that we store)
        if paneInfo.IsFloating():
            paneInfo.floating_pos = paneInfo.frame.GetPosition()
            if paneInfo.frame._transparent != paneInfo.transparent or self._agwFlags & AUI_MGR_TRANSPARENT_DRAG:
                paneInfo.frame.SetTransparent(paneInfo.transparent)
                paneInfo.frame._transparent = paneInfo.transparent

        elif self._has_maximized:
            self.RestoreMaximizedPane()

        # reorder for dropping to a new notebook
        # (caution: this code breaks the reference!)
        tempPaneInfo = self.CopyTarget(paneInfo)
        self._panes.remove(paneInfo)
        self._panes.append(tempPaneInfo)

        if ret:
            self.Update()

        self.HideHint()
        ShowDockingGuides(self._guides, False)

[docs]    def OnMotion_DragToolbarPane(self, eventOrPt):
        """
        Sub-handler for the L{OnMotion} event.

        :param `event`: a `wx.MouseEvent` to be processed.
        """

        isPoint = False
        if isinstance(eventOrPt, wx.Point):
            clientPt = self._frame.ScreenToClient(eventOrPt)
            screenPt = wx.Point(*eventOrPt)
            isPoint = True
        else:
            clientPt = eventOrPt.GetPosition()
            screenPt = self._frame.ClientToScreen(clientPt)

        pane = self.GetPane(self._action_window)
        if not pane.IsOk():
            raise Exception("Pane window not found")

        pane.state |= AuiPaneInfo.actionPane
        indx = self._panes.index(pane)

        ret = False
        wasFloating = pane.IsFloating()
        # is the pane dockable?
        if self.CanDockPanel(pane):
            # do the drop calculation
            ret, pane = self.DoDrop(self._docks, self._panes, pane, clientPt, self._action_offset)

        # update floating position
        if pane.IsFloating():
            pane.floating_pos = screenPt - self._toolbar_action_offset

        # move the pane window
        if pane.frame:
            if wx.Platform == "__WXMSW__" and (self._agwFlags & AUI_MGR_TRANSPARENT_DRAG) == 0: # and not self.CheckPaneMove(pane):
                # return
                # HACK: Terrible hack on wxMSW (!)
                pane.frame.SetTransparent(254)

            self._from_move = True
            pane.frame.Move(pane.floating_pos)
            self._from_move = False

            if self._agwFlags & AUI_MGR_TRANSPARENT_DRAG:
                pane.frame.SetTransparent(150)

        self._panes[indx] = pane
        if ret and wasFloating != pane.IsFloating() or (ret and not wasFloating):
            wx.CallAfter(self.Update)

        # when release the button out of the window.
        # TODO: a better fix is needed.

        if _VERSION_STRING < "2.9":
            leftDown = wx.GetMouseState().LeftDown()
        else:
            leftDown = wx.GetMouseState().LeftIsDown()

        if not leftDown:
            self._action = actionNone
            self.OnLeftUp_DragToolbarPane(eventOrPt)

[docs]    def OnMotion_Other(self, event):
        """
        Sub-handler for the L{OnMotion} event.

        :param `event`: a `wx.MouseEvent` to be processed.
        """

        part = self.HitTest(*event.GetPosition())

        if part and part.type == AuiDockUIPart.typePaneButton \
           and self.IsPaneButtonVisible(part):
            if part != self._hover_button:

                if self._hover_button:
                    self.RefreshButton(self._hover_button)

                self._hover_button = part
                self.RefreshButton(part)

        else:

            if self._hover_button:
                self.RefreshButton(self._hover_button)
            else:
                event.Skip()

            self._hover_button = None

[docs]    def OnLeftUp_DragToolbarPane(self, eventOrPt):
        """
        Sub-handler for the L{OnLeftUp} event.

        :param `event`: a `wx.MouseEvent` to be processed.
        """

        isPoint = False
        if isinstance(eventOrPt, wx.Point):
            clientPt = self._frame.ScreenToClient(eventOrPt)
            screenPt = wx.Point(*eventOrPt)
            isPoint = True
        else:
            clientPt = eventOrPt.GetPosition()
            screenPt = self._frame.ClientToScreen(clientPt)

        # try to find the pane
        pane = self.GetPane(self._action_window)
        if not pane.IsOk():
            raise Exception("Pane window not found")

        if pane.IsFloating():
            pane.floating_pos = pane.frame.GetPosition()
            if pane.frame._transparent != pane.transparent or self._agwFlags & AUI_MGR_TRANSPARENT_DRAG:
                pane.frame.SetTransparent(pane.transparent)
                pane.frame._transparent = pane.transparent

        # save the new positions
        docks = FindDocks(self._docks, pane.dock_direction, pane.dock_layer, pane.dock_row)
        if len(docks) == 1:
            dock = docks[0]
            pane_positions, pane_sizes = self.GetPanePositionsAndSizes(dock)

            for i in xrange(len(dock.panes)):
                dock.panes[i].dock_pos = pane_positions[i]

        pane.state &= ~AuiPaneInfo.actionPane
        self.Update()

[docs]    def OnPaneButton(self, event):
        """
        Handles the ``EVT_AUI_PANE_BUTTON`` event for L{AuiManager}.

        :param `event`: a L{AuiManagerEvent} event to be processed.
        """

        if not event.pane:
            raise Exception("Pane Info passed to AuiManager.OnPaneButton must be non-null")

        pane = event.pane

        if event.button == AUI_BUTTON_CLOSE:

            if isinstance(pane.window.GetParent(), AuiFloatingFrame):
                rootManager = GetManager(pane.window)
            else:
                rootManager = self

            if rootManager != self:
                self._frame.Close()
                return

            # fire pane close event
            e = AuiManagerEvent(wxEVT_AUI_PANE_CLOSE)
            e.SetManager(self)
            e.SetPane(event.pane)
            self.ProcessMgrEvent(e)

            if not e.GetVeto():

                # close the pane, but check that it
                # still exists in our pane array first
                # (the event handler above might have removed it)

                check = self.GetPane(pane.window)
                if check.IsOk():
                    self.ClosePane(pane)

                self.Update()

        # mn this performs the minimizing of a pane
        elif event.button == AUI_BUTTON_MINIMIZE:
            e = AuiManagerEvent(wxEVT_AUI_PANE_MINIMIZE)
            e.SetManager(self)
            e.SetPane(event.pane)
            self.ProcessMgrEvent(e)

            if not e.GetVeto():
                self.MinimizePane(pane)

        elif event.button == AUI_BUTTON_MAXIMIZE_RESTORE and not pane.IsMaximized():

            # fire pane close event
            e = AuiManagerEvent(wxEVT_AUI_PANE_MAXIMIZE)
            e.SetManager(self)
            e.SetPane(event.pane)
            self.ProcessMgrEvent(e)

            if not e.GetVeto():

                self.MaximizePane(pane)
                self.Update()

        elif event.button == AUI_BUTTON_MAXIMIZE_RESTORE and pane.IsMaximized():

            # fire pane close event
            e = AuiManagerEvent(wxEVT_AUI_PANE_RESTORE)
            e.SetManager(self)
            e.SetPane(event.pane)
            self.ProcessMgrEvent(e)

            if not e.GetVeto():

                self.RestorePane(pane)
                self.Update()

        elif event.button == AUI_BUTTON_PIN:

            if self._agwFlags & AUI_MGR_ALLOW_FLOATING and pane.IsFloatable():
                e = self.FireEvent(wxEVT_AUI_PANE_FLOATING, pane, canVeto=True)
                if e.GetVeto():
                    return

                pane.Float()
                e = self.FireEvent(wxEVT_AUI_PANE_FLOATED, pane, canVeto=False)

            self.Update()

[docs]    def MinimizePane(self, paneInfo):
        """
        Minimizes a pane in a newly and automatically created L{AuiToolBar}.

        Clicking on the minimize button causes a new L{AuiToolBar} to be created
        and added to the frame manager (currently the implementation is such that
        panes at West will have a toolbar at the right, panes at South will have
        toolbars at the bottom etc...) and the pane is hidden in the manager.

        Clicking on the restore button on the newly created toolbar will result in the
        toolbar being removed and the original pane being restored.

        :param `paneInfo`: a L{AuiPaneInfo} instance for the pane to be minimized.
        """

        if not paneInfo.IsToolbar():

            if paneInfo.IsMinimized():
                # We are already minimized
                return

            # Basically the idea is this.
            #
            # 1) create a toolbar, with a restore button
            #
            # 2) place the new toolbar in the toolbar area representative of the location of the pane
            #  (NORTH/SOUTH/EAST/WEST, central area always to the right)
            #
            # 3) Hide the minimizing pane

            # personalize the toolbar style

            tbStyle = AUI_TB_DEFAULT_STYLE
            posMask = paneInfo.minimize_mode & AUI_MINIMIZE_POS_MASK
            captMask = paneInfo.minimize_mode & AUI_MINIMIZE_CAPT_MASK
            dockDirection = paneInfo.dock_direction
            if captMask != 0:
                tbStyle |= AUI_TB_TEXT

            if posMask == AUI_MINIMIZE_POS_TOOLBAR:
                minimize_toolbar = self.GetPane(paneInfo.minimize_target)
                if not minimize_toolbar.IsOk():
                    posMask = AUI_MINIMIZE_POS_SMART
                    if paneInfo.dock_direction in [AUI_DOCK_TOP, AUI_DOCK_BOTTOM]:
                        tbStyle |= AUI_TB_HORZ_LAYOUT

                    elif paneInfo.dock_direction in [AUI_DOCK_LEFT, AUI_DOCK_RIGHT, AUI_DOCK_CENTER]:
                        tbStyle |= AUI_TB_VERTICAL
                        if captMask == AUI_MINIMIZE_CAPT_SMART:
                            tbStyle |= AUI_TB_CLOCKWISE
                else:
                    minimize_toolbar = minimize_toolbar.window

            elif posMask == AUI_MINIMIZE_POS_SMART:
                if paneInfo.dock_direction in [AUI_DOCK_TOP, AUI_DOCK_BOTTOM]:
                    tbStyle |= AUI_TB_HORZ_LAYOUT

                elif paneInfo.dock_direction in [AUI_DOCK_LEFT, AUI_DOCK_RIGHT, AUI_DOCK_CENTER]:
                    tbStyle |= AUI_TB_VERTICAL
                    if captMask == AUI_MINIMIZE_CAPT_SMART:
                        tbStyle |= AUI_TB_CLOCKWISE

            elif posMask in [AUI_MINIMIZE_POS_TOP, AUI_MINIMIZE_POS_BOTTOM]:
                tbStyle |= AUI_TB_HORZ_LAYOUT
                if posMask == AUI_MINIMIZE_POS_TOP:
                    dockDirection = AUI_DOCK_TOP
                else:
                    dockDirection = AUI_DOCK_BOTTOM

            else:
                tbStyle |= AUI_TB_VERTICAL
                if captMask == AUI_MINIMIZE_CAPT_SMART:
                    tbStyle |= AUI_TB_CLOCKWISE
                if posMask == AUI_MINIMIZE_POS_LEFT:
                    dockDirection = AUI_DOCK_LEFT
                elif posMask == AUI_MINIMIZE_POS_RIGHT:
                    dockDirection = AUI_DOCK_RIGHT
                elif posMask == AUI_MINIMIZE_POS_BOTTOM:
                    dockDirection = AUI_DOCK_BOTTOM

            # Create a new toolbar
            # give it the same name as the minimized pane with _min appended

            win_rect = paneInfo.window.GetScreenRect()

            if posMask != AUI_MINIMIZE_POS_TOOLBAR:
                minimize_toolbar = auibar.AuiToolBar(self.GetManagedWindow(), agwStyle=tbStyle)
                minimize_toolbar.Hide()
                minimize_toolbar.SetToolBitmapSize(wx.Size(16, 16))

            if paneInfo.icon and paneInfo.icon.IsOk():
                restore_bitmap = paneInfo.icon
            else:
                restore_bitmap = self._art._restore_bitmap

            if posMask == AUI_MINIMIZE_POS_TOOLBAR:
                xsize, ysize = minimize_toolbar.GetToolBitmapSize()
                if xsize != restore_bitmap.GetWidth():
                    img = restore_bitmap.ConvertToImage()
                    img.Rescale(xsize, ysize, wx.IMAGE_QUALITY_HIGH)
                    restore_bitmap = img.ConvertToBitmap()

            target = None
            if posMask == AUI_MINIMIZE_POS_TOOLBAR:
                target = paneInfo.name

            minimize_toolbar.AddSimpleTool(ID_RESTORE_FRAME, paneInfo.caption, restore_bitmap,
                                           _(u"Restore %s")%paneInfo.caption, target=target)
            minimize_toolbar.SetAuiManager(self)
            minimize_toolbar.Realize()
            toolpanelname = paneInfo.name + "_min"

            if paneInfo.IsMaximized():
                paneInfo.SetFlag(paneInfo.wasMaximized, True)

            if posMask != AUI_MINIMIZE_POS_TOOLBAR:

                if dockDirection == AUI_DOCK_TOP:
                    self.AddPane(minimize_toolbar, AuiPaneInfo(). \
                        Name(toolpanelname).Caption(paneInfo.caption). \
                        ToolbarPane().Top().BottomDockable(False). \
                        LeftDockable(False).RightDockable(False).DestroyOnClose())

                elif dockDirection == AUI_DOCK_BOTTOM:
                    self.AddPane(minimize_toolbar, AuiPaneInfo(). \
                        Name(toolpanelname).Caption(paneInfo.caption). \
                        ToolbarPane().Bottom().TopDockable(False). \
                        LeftDockable(False).RightDockable(False).DestroyOnClose())

                elif dockDirection == AUI_DOCK_LEFT:
                    self.AddPane(minimize_toolbar, AuiPaneInfo(). \
                        Name(toolpanelname).Caption(paneInfo.caption). \
                        ToolbarPane().Left().TopDockable(False). \
                        BottomDockable(False).RightDockable(False).DestroyOnClose())

                elif dockDirection in [AUI_DOCK_RIGHT, AUI_DOCK_CENTER]:
                    self.AddPane(minimize_toolbar, AuiPaneInfo(). \
                        Name(toolpanelname).Caption(paneInfo.caption). \
                        ToolbarPane().Right().TopDockable(False). \
                        LeftDockable(False).BottomDockable(False).DestroyOnClose())

            arr = FindDocks(self._docks, paneInfo.dock_direction, paneInfo.dock_layer, paneInfo.dock_row)

            if arr:
                dock = arr[0]
                paneInfo.previousDockSize = dock.size

            paneInfo.previousDockPos = paneInfo.dock_pos

            # mark ourselves minimized
            paneInfo.Minimize()
            paneInfo.Show(False)
            self._has_minimized = True
            # last, hide the window
            if paneInfo.window and paneInfo.window.IsShown():
                paneInfo.window.Show(False)

            minimize_toolbar.Show()
            self.Update()
            if self._agwFlags & AUI_MGR_ANIMATE_FRAMES:
                self.AnimateDocking(win_rect, minimize_toolbar.GetScreenRect())

[docs]    def OnRestoreMinimizedPane(self, event):
        """
        Handles the ``EVT_AUI_PANE_MIN_RESTORE`` event for L{AuiManager}.

        :param `event`: an instance of L{AuiManagerEvent} to be processed.
        """

        self.RestoreMinimizedPane(event.pane)

[docs]    def OnPaneDocked(self, event):
        """
        Handles the ``EVT_AUI_PANE_DOCKED`` event for L{AuiManager}.

        :param `event`: an instance of L{AuiManagerEvent} to be processed.
        """

        event.Skip()
        self.RemoveAutoNBCaption(event.GetPane())

[docs]    def CreateNotebookBase(self, panes, paneInfo):
        """
        Creates an auto-notebook base from a pane, and then add that pane as a page.

        :param `panes`: Set of panes to append new notebook base pane to
        :param `paneInfo`: L{AuiPaneInfo} instance to convert to new notebook.
        """

        # Create base notebook pane ...
        nbid = len(self._notebooks)

        baseInfo = AuiPaneInfo()
        baseInfo.SetDockPos(paneInfo).NotebookControl(nbid). \
            CloseButton(False).SetNameFromNotebookId(). \
            NotebookDockable(False).Floatable(paneInfo.IsFloatable())
        baseInfo.best_size = paneInfo.best_size
        panes.append(baseInfo)

        # add original pane as tab ...
        paneInfo.NotebookPage(nbid)

[docs]    def RemoveAutoNBCaption(self, pane):
        """
        Removes the caption on newly created automatic notebooks.

        :param `pane`: an instance of L{AuiPaneInfo} (the target notebook).
        """

        if self._agwFlags & AUI_MGR_AUTONB_NO_CAPTION == 0:
            return False

        def RemoveCaption():
            """ Sub-function used to remove the pane caption on automatic notebooks. """

            if pane.HasNotebook():
                notebook = self._notebooks[pane.notebook_id]
                self.GetPane(notebook).CaptionVisible(False).PaneBorder(False)
                self.Update()

        # it seems the notebook isnt created by this stage, so remove
        # the caption a moment later
        wx.CallAfter(RemoveCaption)
        return True

[docs]    def RestoreMinimizedPane(self, paneInfo):
        """
        Restores a previously minimized pane.

        :param `paneInfo`: a L{AuiPaneInfo} instance for the pane to be restored.
        """

        panename = paneInfo.name

        if paneInfo.minimize_mode & AUI_MINIMIZE_POS_TOOLBAR:
            pane = self.GetPane(panename)
            hasTarget = True
        else:
            panename = panename[0:-4]
            hasTarget = False

        pane = self.GetPane(panename)
        pane.SetFlag(pane.needsRestore, True)

        if not pane.IsOk():
            panename = paneInfo.name
            pane = self.GetPane(panename)
            paneInfo = self.GetPane(panename + "_min")
            if not paneInfo.IsOk():
                # Already minimized
                return

        if pane.IsOk():
            if not pane.IsMinimized():
                return

            if pane.HasFlag(pane.wasMaximized):
                self.SavePreviousDockSizes(pane)

            self.ShowPane(pane.window, True)
            pane.Show(True)
            self._has_minimized = False
            pane.SetFlag(pane.optionMinimized, False)

            if hasTarget:
                targetName = pane.minimize_target
                toolbarPane = self.GetPane(targetName)
                toolbar = toolbarPane.window
                item = toolbar.FindToolByLabel(pane.caption)
                toolbar.DeleteTool(item.id)
            else:
                paneInfo.window.Show(False)
                self.DetachPane(paneInfo.window)
                paneInfo.Show(False)
                paneInfo.Hide()

            self.Update()

[docs]    def AnimateDocking(self, win_rect, pane_rect):
        """
        Animates the minimization/docking of a pane a la Eclipse, using a `wx.ScreenDC`
        to draw a "moving docking rectangle" on the screen.

        :param `win_rect`: the original pane screen rectangle;
        :param `pane_rect`: the newly created toolbar/pane screen rectangle.

        :note: This functionality is not available on wxMAC as this platform doesn't have
         the ability to use `wx.ScreenDC` to draw on-screen and on Windows > Vista.
        """

        if wx.Platform == "__WXMAC__":
            # No wx.ScreenDC on the Mac...
            return
        if wx.Platform == "__WXMSW__" and wx.GetOsVersion()[1] > 5:
            # No easy way to handle this on Vista...
            return

        xstart, ystart = win_rect.x, win_rect.y
        xend, yend = pane_rect.x, pane_rect.y

        step = self.GetAnimationStep()

        wstep = int(abs(win_rect.width - pane_rect.width)/step)
        hstep = int(abs(win_rect.height - pane_rect.height)/step)
        xstep = int(win_rect.x - pane_rect.x)/step
        ystep = int(win_rect.y - pane_rect.y)/step

        dc = wx.ScreenDC()
        dc.SetLogicalFunction(wx.INVERT)
        dc.SetBrush(wx.TRANSPARENT_BRUSH)
        dc.SetPen(wx.LIGHT_GREY_PEN)

        for i in xrange(int(step)):
            width, height = win_rect.width - i*wstep, win_rect.height - i*hstep
            x, y = xstart - i*xstep, ystart - i*ystep
            new_rect = wx.Rect(x, y, width, height)
            dc.DrawRoundedRectangleRect(new_rect, 3)
            wx.SafeYield()
            wx.MilliSleep(10)
            dc.DrawRoundedRectangleRect(new_rect, 3)

[docs]    def SmoothDock(self, paneInfo):
        """
        This method implements a smooth docking effect for floating panes, similar to
        what the PyQT library does with its floating windows.

        :param `paneInfo`: an instance of L{AuiPaneInfo}.

        :note: The smooth docking effect can only be used if you set the ``AUI_MGR_SMOOTH_DOCKING``
         style to L{AuiManager}.
        """

        if paneInfo.IsToolbar():
            return

        if not paneInfo.frame or self._hint_rect.IsEmpty():
            return

        hint_rect = self._hint_rect
        win_rect = paneInfo.frame.GetScreenRect()

        xstart, ystart = win_rect.x, win_rect.y
        xend, yend = hint_rect.x, hint_rect.y

        step = self.GetAnimationStep()/3

        wstep = int((win_rect.width - hint_rect.width)/step)
        hstep = int((win_rect.height - hint_rect.height)/step)
        xstep = int((win_rect.x - hint_rect.x))/step
        ystep = int((win_rect.y - hint_rect.y))/step

        for i in xrange(int(step)):
            width, height = win_rect.width - i*wstep, win_rect.height - i*hstep
            x, y = xstart - i*xstep, ystart - i*ystep
            new_rect = wx.Rect(x, y, width, height)
            paneInfo.frame.SetRect(new_rect)
            wx.MilliSleep(10)

[docs]    def SetSnapLimits(self, x, y):
        """
        Modifies the snap limits used when snapping the `managed_window` to the screen
        (using L{SnapToScreen}) or when snapping the floating panes to one side of the
        `managed_window` (using L{SnapPane}).

        To change the limit after which the `managed_window` or the floating panes are
        automatically stickled to the screen border (or to the `managed_window` side),
        set these two variables. Default values are 15 pixels.

        :param `x`: the minimum horizontal distance below which the snap occurs;
        :param `y`: the minimum vertical distance below which the snap occurs.
        """

        self._snap_limits = (x, y)
        self.Snap()

[docs]    def Snap(self):
        """
        Snaps the main frame to specified position on the screen.

        :see: L{SnapToScreen}
        """

        snap, hAlign, vAlign, monitor = self._is_docked
        if not snap:
            return

        managed_window = self.GetManagedWindow()
        snap_pos = self.GetSnapPosition()
        wnd_pos = managed_window.GetPosition()
        snapX, snapY = self._snap_limits

        if abs(snap_pos.x - wnd_pos.x) < snapX and abs(snap_pos.y - wnd_pos.y) < snapY:
            managed_window.SetPosition(snap_pos)

[docs]    def SnapToScreen(self, snap=True, monitor=0, hAlign=wx.RIGHT, vAlign=wx.TOP):
        """
        Snaps the main frame to specified position on the screen.

        :param `snap`: whether to snap the main frame or not;
        :param `monitor`: the monitor display in which snapping the window;
        :param `hAlign`: the horizontal alignment of the snapping position;
        :param `vAlign`: the vertical alignment of the snapping position.
        """

        if not snap:
            self._is_docked = (False, wx.RIGHT, wx.TOP, 0)
            return

        displayCount = wx.Display.GetCount()
        if monitor > displayCount:
            raise Exception("Invalid monitor selected: you only have %d monitors"%displayCount)

        self._is_docked = (True, hAlign, vAlign, monitor)
        self.GetManagedWindow().SetPosition(self.GetSnapPosition())

[docs]    def GetSnapPosition(self):
        """ Returns the main frame snapping position. """

        snap, hAlign, vAlign, monitor = self._is_docked

        display = wx.Display(monitor)
        area = display.GetClientArea()
        size = self.GetManagedWindow().GetSize()

        pos = wx.Point()
        if hAlign == wx.LEFT:
            pos.x = area.x
        elif hAlign == wx.CENTER:
            pos.x = area.x + (area.width - size.x)/2
        else:
            pos.x = area.x + area.width - size.x

        if vAlign == wx.TOP:
            pos.y = area.y
        elif vAlign == wx.CENTER:
            pos.y = area.y + (area.height - size.y)/2
        else:
            pos.y = area.y + area.height - size.y

        return pos

[docs]    def GetAnimationStep(self):
        """ Returns the animation step speed (a float) to use in L{AnimateDocking}. """

        return self._animation_step

[docs]    def SetAnimationStep(self, step):
        """
        Sets the animation step speed (a float) to use in L{AnimateDocking}.

        :param `step`: a floating point value for the animation speed.
        """

        self._animation_step = float(step)

[docs]    def RequestUserAttention(self, pane_window):
        """
        Requests the user attention by intermittently highlighting the pane caption.

        :param `pane_window`: a `wx.Window` derived window, managed by the pane.
        """

        # try to find the pane
        paneInfo = self.GetPane(pane_window)
        if not paneInfo.IsOk():
            raise Exception("Pane window not found")

        dc = wx.ClientDC(self._frame)

        # if the frame is about to be deleted, don't bother
        if not self._frame or self._frame.IsBeingDeleted():
            return

        if not self._frame.GetSizer():
            return

        for part in self._uiparts:
            if part.pane == paneInfo:
                self._art.RequestUserAttention(dc, self._frame, part.pane.caption, part.rect, part.pane)
                self._frame.RefreshRect(part.rect, True)
                break

[docs]    def StartPreviewTimer(self, toolbar):
        """
        Starts a timer for sliding in and out a minimized pane.

        :param `toolbar`: the L{AuiToolBar} containing the minimized pane tool.
        """

        toolbar_pane = self.GetPane(toolbar)
        toolbar_name = toolbar_pane.name

        pane_name = toolbar_name[0:-4]

        self._sliding_pane = self.GetPane(pane_name)
        self._sliding_rect = toolbar.GetScreenRect()
        self._sliding_direction = toolbar_pane.dock_direction
        self._sliding_frame = None

        self._preview_timer.Start(1000, wx.TIMER_ONE_SHOT)

[docs]    def StopPreviewTimer(self):
        """ Stops a timer for sliding in and out a minimized pane. """

        if self._preview_timer.IsRunning():
            self._preview_timer.Stop()

        self.SlideOut()
        self._sliding_pane = None

[docs]    def SlideIn(self, event):
        """
        Handles the ``wx.EVT_TIMER`` event for L{AuiManager}.

        :param `event`: a `wx.TimerEvent` to be processed.

        :note: This is used solely for sliding in and out minimized panes.
        """

        window = self._sliding_pane.window
        self._sliding_frame = wx.MiniFrame(None, -1, title=_("Pane Preview"),
                                           style=wx.FRAME_TOOL_WINDOW | wx.STAY_ON_TOP |
                                           wx.FRAME_NO_TASKBAR | wx.CAPTION)
        window.Reparent(self._sliding_frame)
        self._sliding_frame.SetSize((0, 0))
        window.Show()
        self._sliding_frame.Show()

        size = window.GetBestSize()

        startX, startY, stopX, stopY = GetSlidingPoints(self._sliding_rect, size, self._sliding_direction)

        step = stopX/10
        window_size = 0

        for i in xrange(0, stopX, step):
            window_size = i
            self._sliding_frame.SetDimensions(startX, startY, window_size, stopY)
            self._sliding_frame.Refresh()
            self._sliding_frame.Update()
            wx.MilliSleep(10)

        self._sliding_frame.SetDimensions(startX, startY, stopX, stopY)
        self._sliding_frame.Refresh()
        self._sliding_frame.Update()

[docs]    def SlideOut(self):
        """
        Slides out a preview of a minimized pane.

        :note: This is used solely for sliding in and out minimized panes.
        """

        if not self._sliding_frame:
            return

        window = self._sliding_frame.GetChildren()[0]
        size = window.GetBestSize()

        startX, startY, stopX, stopY = GetSlidingPoints(self._sliding_rect, size, self._sliding_direction)

        step = stopX/10
        window_size = 0

        for i in xrange(stopX, 0, -step):
            window_size = i
            self._sliding_frame.SetDimensions(startX, startY, window_size, stopY)
            self._sliding_frame.Refresh()
            self._sliding_frame.Update()
            self._frame.RefreshRect(wx.Rect(startX+window_size, startY, step, stopY))
            self._frame.Update()
            wx.MilliSleep(10)

        self._sliding_frame.SetDimensions(startX, startY, 0, stopY)

        window.Hide()
        window.Reparent(self._frame)

        self._sliding_frame.Hide()
        self._sliding_frame.Destroy()
        self._sliding_frame = None
        self._sliding_pane = None

[docs]class AuiManager_DCP(AuiManager):
    """
    A class similar to L{AuiManager} but with a Dummy Center Pane (**DCP**).
    The code for this class is still flickery due to the call to `wx.CallAfter`
    and the double-update call.
    """

[docs]    def __init__(self, *args, **keys):

        AuiManager.__init__(self, *args, **keys)
        self.hasDummyPane = False

    def _createDummyPane(self):
        """ Creates a Dummy Center Pane (**DCP**). """

        if self.hasDummyPane:
            return

        self.hasDummyPane = True
        dummy = wx.Panel(self.GetManagedWindow())
        info = AuiPaneInfo().CenterPane().NotebookDockable(True).Name('dummyCenterPane').DestroyOnClose(True)
        self.AddPane(dummy, info)

    def _destroyDummyPane(self):
        """ Destroys the Dummy Center Pane (**DCP**). """

        if not self.hasDummyPane:
            return

        self.hasDummyPane = False
        self.ClosePane(self.GetPane('dummyCenterPane'))

[docs]    def Update(self):
        """
        This method is called after any number of changes are made to any of the
        managed panes. L{Update} must be invoked after L{AuiManager.AddPane} or L{AuiManager.InsertPane} are
        called in order to "realize" or "commit" the changes.

        In addition, any number of changes may be made to L{AuiPaneInfo} structures
        (retrieved with L{AuiManager.GetPane}), but to realize the changes, L{Update}
        must be called. This construction allows pane flicker to be avoided by updating
        the whole layout at one time.
        """

        AuiManager.Update(self)

        # check if there's already a center pane (except our dummy pane)
        dummyCenterPane = self.GetPane('dummyCenterPane')
        haveCenterPane = any((pane != dummyCenterPane) and (pane.dock_direction == AUI_DOCK_CENTER) and
                             not pane.IsFloating() and pane.IsShown() for pane in self.GetAllPanes())
        if haveCenterPane:
            if self.hasDummyPane:
                # there's our dummy pane and also another center pane, therefor let's remove our dummy
                def do():
                    self._destroyDummyPane()
                    self.Update()
                wx.CallAfter(do)
        else:
            # if we get here, there's no center pane, create our dummy
            if not self.hasDummyPane:
                self._createDummyPane()

Navigation

  • index
  • modules |
  • Home |
  • Gallery |
  • Contents»
  • Module code »
  • aui.framemanager


aui.tabart

  • modules |
  • Home |
  • Gallery |
  • Contents»
  • Module code »
  • aui.tabart

Source code for aui.tabart

"""
Tab art provider code - a tab provider provides all drawing functionality to
the L{AuiNotebook}. This allows the L{AuiNotebook} to have a plugable look-and-feel.

By default, a L{AuiNotebook} uses an instance of this class called L{AuiDefaultTabArt}
which provides bitmap art and a colour scheme that is adapted to the major platforms'
look. You can either derive from that class to alter its behaviour or write a
completely new tab art class. Call L{AuiNotebook.SetArtProvider} to make use this
new tab art.
"""

__author__ = "Andrea Gavana <andrea.gavana@gmail.com>"
__date__ = "31 March 2009"

import wx

if wx.Platform == '__WXMAC__':
    import Carbon.Appearance

from aui_utilities import BitmapFromBits, StepColour, IndentPressedBitmap, ChopText
from aui_utilities import GetBaseColour, DrawMACCloseButton, LightColour, TakeScreenShot
from aui_utilities import CopyAttributes

from aui_constants import *

# -- GUI helper classes and functions --

[docs]class AuiCommandCapture(wx.PyEvtHandler):
    """ A class to handle the dropdown window menu. """

[docs]    def __init__(self):
        """ Default class constructor. """

        wx.PyEvtHandler.__init__(self)
        self._last_id = 0

[docs]    def GetCommandId(self):
        """ Returns the event command identifier. """

        return self._last_id

[docs]    def ProcessEvent(self, event):
        """
        Processes an event, searching event tables and calling zero or more suitable
        event handler function(s).

        :param `event`: the event to process.

        :note: Normally, your application would not call this function: it is called
         in the wxPython implementation to dispatch incoming user interface events
         to the framework (and application).
         However, you might need to call it if implementing new functionality (such as
         a new control) where you define new event types, as opposed to allowing the
         user to override functions.

         An instance where you might actually override the L{ProcessEvent} function is where
         you want to direct event processing to event handlers not normally noticed by
         wxPython. For example, in the document/view architecture, documents and views
         are potential event handlers. When an event reaches a frame, L{ProcessEvent} will
         need to be called on the associated document and view in case event handler
         functions are associated with these objects.

         The normal order of event table searching is as follows:

         1. If the object is disabled (via a call to `SetEvtHandlerEnabled`) the function
            skips to step (6).
         2. If the object is a `wx.Window`, L{ProcessEvent} is recursively called on the window's
            `wx.Validator`. If this returns ``True``, the function exits.
         3. wxWidgets `SearchEventTable` is called for this event handler. If this fails, the
            base class table is tried, and so on until no more tables exist or an appropriate
            function was found, in which case the function exits.
         4. The search is applied down the entire chain of event handlers (usually the chain
            has a length of one). If this succeeds, the function exits.
         5. If the object is a `wx.Window` and the event is a `wx.CommandEvent`, L{ProcessEvent} is
            recursively applied to the parent window's event handler. If this returns ``True``,
            the function exits.
         6. Finally, L{ProcessEvent} is called on the `wx.App` object.
        """

        if event.GetEventType() == wx.wxEVT_COMMAND_MENU_SELECTED:
            self._last_id = event.GetId()
            return True

        if self.GetNextHandler():
            return self.GetNextHandler().ProcessEvent(event)

        return False

[docs]class AuiDefaultTabArt(object):
    """
    Tab art provider code - a tab provider provides all drawing functionality to
    the L{AuiNotebook}. This allows the L{AuiNotebook} to have a plugable look-and-feel.

    By default, a L{AuiNotebook} uses an instance of this class called L{AuiDefaultTabArt}
    which provides bitmap art and a colour scheme that is adapted to the major platforms'
    look. You can either derive from that class to alter its behaviour or write a
    completely new tab art class. Call L{AuiNotebook.SetArtProvider} to make use this
    new tab art.
    """

[docs]    def __init__(self):
        """ Default class constructor. """

        self._normal_font = wx.SystemSettings_GetFont(wx.SYS_DEFAULT_GUI_FONT)
        self._selected_font = wx.SystemSettings_GetFont(wx.SYS_DEFAULT_GUI_FONT)
        self._selected_font.SetWeight(wx.BOLD)
        self._measuring_font = self._selected_font

        self._fixed_tab_width = 100
        self._tab_ctrl_height = 0
        self._buttonRect = wx.Rect()

        self.SetDefaultColours()

        if wx.Platform == "__WXMAC__":
            bmp_colour = wx.SystemSettings.GetColour(wx.SYS_COLOUR_3DDKSHADOW)
            self._active_close_bmp = DrawMACCloseButton(bmp_colour)
            self._disabled_close_bmp = DrawMACCloseButton(wx.Colour(128, 128, 128))
        else:
            self._active_close_bmp = BitmapFromBits(nb_close_bits, 16, 16, wx.BLACK)
            self._disabled_close_bmp = BitmapFromBits(nb_close_bits, 16, 16, wx.Colour(128, 128, 128))

        self._hover_close_bmp = self._active_close_bmp
        self._pressed_close_bmp = self._active_close_bmp

        self._active_left_bmp = BitmapFromBits(nb_left_bits, 16, 16, wx.BLACK)
        self._disabled_left_bmp = BitmapFromBits(nb_left_bits, 16, 16, wx.Colour(128, 128, 128))

        self._active_right_bmp = BitmapFromBits(nb_right_bits, 16, 16, wx.BLACK)
        self._disabled_right_bmp = BitmapFromBits(nb_right_bits, 16, 16, wx.Colour(128, 128, 128))

        self._active_windowlist_bmp = BitmapFromBits(nb_list_bits, 16, 16, wx.BLACK)
        self._disabled_windowlist_bmp = BitmapFromBits(nb_list_bits, 16, 16, wx.Colour(128, 128, 128))

        if wx.Platform == "__WXMAC__":
            # Get proper highlight colour for focus rectangle from the
            # current Mac theme.  kThemeBrushFocusHighlight is
            # available on Mac OS 8.5 and higher
            if hasattr(wx, 'MacThemeColour'):
                c = wx.MacThemeColour(Carbon.Appearance.kThemeBrushFocusHighlight)
            else:
                brush = wx.Brush(wx.BLACK)
                brush.MacSetTheme(Carbon.Appearance.kThemeBrushFocusHighlight)
                c = brush.GetColour()
            self._focusPen = wx.Pen(c, 2, wx.SOLID)
        else:
            self._focusPen = wx.Pen(wx.BLACK, 1, wx.USER_DASH)
            self._focusPen.SetDashes([1, 1])
            self._focusPen.SetCap(wx.CAP_BUTT)

[docs]    def SetBaseColour(self, base_colour):
        """
        Sets a new base colour.

        :param `base_colour`: an instance of `wx.Colour`.
        """

        self._base_colour = base_colour
        self._base_colour_pen = wx.Pen(self._base_colour)
        self._base_colour_brush = wx.Brush(self._base_colour)

[docs]    def SetDefaultColours(self, base_colour=None):
        """
        Sets the default colours, which are calculated from the given base colour.

        :param `base_colour`: an instance of `wx.Colour`. If defaulted to ``None``, a colour
         is generated accordingly to the platform and theme.
        """

        if base_colour is None:
            base_colour = GetBaseColour()

        self.SetBaseColour( base_colour )
        self._border_colour = StepColour(base_colour, 75)
        self._border_pen = wx.Pen(self._border_colour)

        self._background_top_colour = StepColour(self._base_colour, 90)
        self._background_bottom_colour = StepColour(self._base_colour, 170)

        self._tab_top_colour = self._base_colour
        self._tab_bottom_colour = wx.WHITE
        self._tab_gradient_highlight_colour = wx.WHITE

        self._tab_inactive_top_colour = self._base_colour
        self._tab_inactive_bottom_colour = StepColour(self._tab_inactive_top_colour, 160)

        self._tab_text_colour = lambda page: page.text_colour
        self._tab_disabled_text_colour = wx.SystemSettings.GetColour(wx.SYS_COLOUR_GRAYTEXT)

[docs]    def Clone(self):
        """ Clones the art object. """

        art = type(self)()
        art.SetNormalFont(self.GetNormalFont())
        art.SetSelectedFont(self.GetSelectedFont())
        art.SetMeasuringFont(self.GetMeasuringFont())

        art = CopyAttributes(art, self)
        return art

[docs]    def SetAGWFlags(self, agwFlags):
        """
        Sets the tab art flags.

        :param `agwFlags`: a combination of the following values:

         ==================================== ==================================
         Flag name                            Description
         ==================================== ==================================
         ``AUI_NB_TOP``                       With this style, tabs are drawn along the top of the notebook
         ``AUI_NB_LEFT``                      With this style, tabs are drawn along the left of the notebook. Not implemented yet.
         ``AUI_NB_RIGHT``                     With this style, tabs are drawn along the right of the notebook. Not implemented yet.
         ``AUI_NB_BOTTOM``                    With this style, tabs are drawn along the bottom of the notebook
         ``AUI_NB_TAB_SPLIT``                 Allows the tab control to be split by dragging a tab
         ``AUI_NB_TAB_MOVE``                  Allows a tab to be moved horizontally by dragging
         ``AUI_NB_TAB_EXTERNAL_MOVE``         Allows a tab to be moved to another tab control
         ``AUI_NB_TAB_FIXED_WIDTH``           With this style, all tabs have the same width
         ``AUI_NB_SCROLL_BUTTONS``            With this style, left and right scroll buttons are displayed
         ``AUI_NB_WINDOWLIST_BUTTON``         With this style, a drop-down list of windows is available
         ``AUI_NB_CLOSE_BUTTON``              With this style, a close button is available on the tab bar
         ``AUI_NB_CLOSE_ON_ACTIVE_TAB``       With this style, a close button is available on the active tab
         ``AUI_NB_CLOSE_ON_ALL_TABS``         With this style, a close button is available on all tabs
         ``AUI_NB_MIDDLE_CLICK_CLOSE``        Allows to close L{AuiNotebook} tabs by mouse middle button click
         ``AUI_NB_SUB_NOTEBOOK``              This style is used by L{AuiManager} to create automatic AuiNotebooks
         ``AUI_NB_HIDE_ON_SINGLE_TAB``        Hides the tab window if only one tab is present
         ``AUI_NB_SMART_TABS``                Use Smart Tabbing, like ``Alt`` + ``Tab`` on Windows
         ``AUI_NB_USE_IMAGES_DROPDOWN``       Uses images on dropdown window list menu instead of check items
         ``AUI_NB_CLOSE_ON_TAB_LEFT``         Draws the tab close button on the left instead of on the right (a la Camino browser)
         ``AUI_NB_TAB_FLOAT``                 Allows the floating of single tabs. Known limitation: when the notebook is more or less full screen, tabs cannot be dragged far enough outside of the notebook to become floating pages
         ``AUI_NB_DRAW_DND_TAB``              Draws an image representation of a tab while dragging (on by default)
         ``AUI_NB_ORDER_BY_ACCESS``           Tab navigation order by last access time for the tabs
         ``AUI_NB_NO_TAB_FOCUS``              Don't draw tab focus rectangle
         ==================================== ==================================

        """

        self._agwFlags = agwFlags

[docs]    def GetAGWFlags(self):
        """
        Returns the tab art flags.

        :see: L{SetAGWFlags} for a list of possible return values.
        """

        return self._agwFlags

[docs]    def SetSizingInfo(self, tab_ctrl_size, tab_count, minMaxTabWidth):
        """
        Sets the tab sizing information.

        :param `tab_ctrl_size`: the size of the tab control area;
        :param `tab_count`: the number of tabs;
        :param `minMaxTabWidth`: a tuple containing the minimum and maximum tab widths
         to be used when the ``AUI_NB_TAB_FIXED_WIDTH`` style is active.
        """

        self._fixed_tab_width = 100
        minTabWidth, maxTabWidth = minMaxTabWidth

        tot_width = tab_ctrl_size.x - self.GetIndentSize() - 4
        agwFlags = self.GetAGWFlags()

        if agwFlags & AUI_NB_CLOSE_BUTTON:
            tot_width -= self._active_close_bmp.GetWidth()
        if agwFlags & AUI_NB_WINDOWLIST_BUTTON:
            tot_width -= self._active_windowlist_bmp.GetWidth()

        if tab_count > 0:
            self._fixed_tab_width = tot_width/tab_count

        if self._fixed_tab_width < 100:
            self._fixed_tab_width = 100

        if self._fixed_tab_width > tot_width/2:
            self._fixed_tab_width = tot_width/2

        if self._fixed_tab_width > 220:
            self._fixed_tab_width = 220

        if minTabWidth > -1:
            self._fixed_tab_width = max(self._fixed_tab_width, minTabWidth)
        if maxTabWidth > -1:
            self._fixed_tab_width = min(self._fixed_tab_width, maxTabWidth)

        self._tab_ctrl_height = tab_ctrl_size.y

[docs]    def DrawBackground(self, dc, wnd, rect):
        """
        Draws the tab area background.

        :param `dc`: a `wx.DC` device context;
        :param `wnd`: a `wx.Window` instance object;
        :param `rect`: the tab control rectangle.
        """

        self._buttonRect = wx.Rect()

        # draw background
        agwFlags = self.GetAGWFlags()
        if agwFlags & AUI_NB_BOTTOM:
            r = wx.Rect(rect.x, rect.y, rect.width+2, rect.height)

        # TODO: else if (agwFlags & AUI_NB_LEFT)
        # TODO: else if (agwFlags & AUI_NB_RIGHT)
        else: #for AUI_NB_TOP
            r = wx.Rect(rect.x, rect.y, rect.width+2, rect.height-3)

        dc.GradientFillLinear(r, self._background_top_colour, self._background_bottom_colour, wx.SOUTH)

        # draw base lines

        dc.SetPen(self._border_pen)
        y = rect.GetHeight()
        w = rect.GetWidth()

        if agwFlags & AUI_NB_BOTTOM:
            dc.SetBrush(wx.Brush(self._background_bottom_colour))
            dc.DrawRectangle(-1, 0, w+2, 4)

        # TODO: else if (agwFlags & AUI_NB_LEFT)
        # TODO: else if (agwFlags & AUI_NB_RIGHT)

        else: # for AUI_NB_TOP
            dc.SetBrush(self._base_colour_brush)
            dc.DrawRectangle(-1, y-4, w+2, 4)

[docs]    def DrawTab(self, dc, wnd, page, in_rect, close_button_state, paint_control=False):
        """
        Draws a single tab.

        :param `dc`: a `wx.DC` device context;
        :param `wnd`: a `wx.Window` instance object;
        :param `page`: the tab control page associated with the tab;
        :param `in_rect`: rectangle the tab should be confined to;
        :param `close_button_state`: the state of the close button on the tab;
        :param `paint_control`: whether to draw the control inside a tab (if any) on a `wx.MemoryDC`.
        """

        # if the caption is empty, measure some temporary text
        caption = page.caption
        if not caption:
            caption = "Xj"

        dc.SetFont(self._selected_font)
        selected_textx, selected_texty, dummy = dc.GetMultiLineTextExtent(caption)

        dc.SetFont(self._normal_font)
        normal_textx, normal_texty, dummy = dc.GetMultiLineTextExtent(caption)

        control = page.control

        # figure out the size of the tab
        tab_size, x_extent = self.GetTabSize(dc, wnd, page.caption, page.bitmap,
                                             page.active, close_button_state, control)

        tab_height = self._tab_ctrl_height - 3
        tab_width = tab_size[0]
        tab_x = in_rect.x
        tab_y = in_rect.y + in_rect.height - tab_height

        caption = page.caption

        # select pen, brush and font for the tab to be drawn

        if page.active:

            dc.SetFont(self._selected_font)
            textx, texty = selected_textx, selected_texty

        else:

            dc.SetFont(self._normal_font)
            textx, texty = normal_textx, normal_texty

        if not page.enabled:
            dc.SetTextForeground(self._tab_disabled_text_colour)
            pagebitmap = page.dis_bitmap
        else:
            dc.SetTextForeground(self._tab_text_colour(page))
            pagebitmap = page.bitmap

        # create points that will make the tab outline

        clip_width = tab_width
        if tab_x + clip_width > in_rect.x + in_rect.width:
            clip_width = in_rect.x + in_rect.width - tab_x

        # since the above code above doesn't play well with WXDFB or WXCOCOA,
        # we'll just use a rectangle for the clipping region for now --
        dc.SetClippingRegion(tab_x, tab_y, clip_width+1, tab_height-3)

        border_points = [wx.Point() for i in xrange(6)]
        agwFlags = self.GetAGWFlags()

        if agwFlags & AUI_NB_BOTTOM:

            border_points[0] = wx.Point(tab_x,             tab_y)
            border_points[1] = wx.Point(tab_x,             tab_y+tab_height-6)
            border_points[2] = wx.Point(tab_x+2,           tab_y+tab_height-4)
            border_points[3] = wx.Point(tab_x+tab_width-2, tab_y+tab_height-4)
            border_points[4] = wx.Point(tab_x+tab_width,   tab_y+tab_height-6)
            border_points[5] = wx.Point(tab_x+tab_width,   tab_y)

        else: #if (agwFlags & AUI_NB_TOP)

            border_points[0] = wx.Point(tab_x,             tab_y+tab_height-4)
            border_points[1] = wx.Point(tab_x,             tab_y+2)
            border_points[2] = wx.Point(tab_x+2,           tab_y)
            border_points[3] = wx.Point(tab_x+tab_width-2, tab_y)
            border_points[4] = wx.Point(tab_x+tab_width,   tab_y+2)
            border_points[5] = wx.Point(tab_x+tab_width,   tab_y+tab_height-4)

        # TODO: else if (agwFlags & AUI_NB_LEFT)
        # TODO: else if (agwFlags & AUI_NB_RIGHT)

        drawn_tab_yoff = border_points[1].y
        drawn_tab_height = border_points[0].y - border_points[1].y

        if page.active:

            # draw active tab

            # draw base background colour
            r = wx.Rect(tab_x, tab_y, tab_width, tab_height)
            dc.SetPen(self._base_colour_pen)
            dc.SetBrush(self._base_colour_brush)
            dc.DrawRectangle(r.x+1, r.y+1, r.width-1, r.height-4)

            # this white helps fill out the gradient at the top of the tab
            dc.SetPen( wx.Pen(self._tab_gradient_highlight_colour) )
            dc.SetBrush( wx.Brush(self._tab_gradient_highlight_colour) )
            dc.DrawRectangle(r.x+2, r.y+1, r.width-3, r.height-4)

            # these two points help the rounded corners appear more antialiased
            dc.SetPen(self._base_colour_pen)
            dc.DrawPoint(r.x+2, r.y+1)
            dc.DrawPoint(r.x+r.width-2, r.y+1)

            # set rectangle down a bit for gradient drawing
            r.SetHeight(r.GetHeight()/2)
            r.x += 2
            r.width -= 2
            r.y += r.height
            r.y -= 2

            # draw gradient background
            top_colour = self._tab_bottom_colour
            bottom_colour = self._tab_top_colour
            dc.GradientFillLinear(r, bottom_colour, top_colour, wx.NORTH)

        else:

            # draw inactive tab

            r = wx.Rect(tab_x, tab_y+1, tab_width, tab_height-3)

            # start the gradent up a bit and leave the inside border inset
            # by a pixel for a 3D look.  Only the top half of the inactive
            # tab will have a slight gradient
            r.x += 3
            r.y += 1
            r.width -= 4
            r.height /= 2
            r.height -= 1

            # -- draw top gradient fill for glossy look
            top_colour = self._tab_inactive_top_colour
            bottom_colour = self._tab_inactive_bottom_colour
            dc.GradientFillLinear(r, bottom_colour, top_colour, wx.NORTH)

            r.y += r.height
            r.y -= 1

            # -- draw bottom fill for glossy look
            top_colour = self._tab_inactive_bottom_colour
            bottom_colour = self._tab_inactive_bottom_colour
            dc.GradientFillLinear(r, top_colour, bottom_colour, wx.SOUTH)

        # draw tab outline
        dc.SetPen(self._border_pen)
        dc.SetBrush(wx.TRANSPARENT_BRUSH)
        dc.DrawPolygon(border_points)

        # there are two horizontal grey lines at the bottom of the tab control,
        # this gets rid of the top one of those lines in the tab control
        if page.active:

            if agwFlags & AUI_NB_BOTTOM:
                dc.SetPen(wx.Pen(self._background_bottom_colour))

            # TODO: else if (agwFlags & AUI_NB_LEFT)
            # TODO: else if (agwFlags & AUI_NB_RIGHT)
            else: # for AUI_NB_TOP
                dc.SetPen(self._base_colour_pen)

            dc.DrawLine(border_points[0].x+1,
                        border_points[0].y,
                        border_points[5].x,
                        border_points[5].y)

        text_offset = tab_x + 8
        close_button_width = 0

        if close_button_state != AUI_BUTTON_STATE_HIDDEN:
            close_button_width = self._active_close_bmp.GetWidth()

            if agwFlags & AUI_NB_CLOSE_ON_TAB_LEFT:
                text_offset += close_button_width - 5

        bitmap_offset = 0

        if pagebitmap.IsOk():

            bitmap_offset = tab_x + 8
            if agwFlags & AUI_NB_CLOSE_ON_TAB_LEFT and close_button_width:
                bitmap_offset += close_button_width - 5

            # draw bitmap
            dc.DrawBitmap(pagebitmap,
                          bitmap_offset,
                          drawn_tab_yoff + (drawn_tab_height/2) - (pagebitmap.GetHeight()/2),
                          True)

            text_offset = bitmap_offset + pagebitmap.GetWidth()
            text_offset += 3 # bitmap padding

        else:

            if agwFlags & AUI_NB_CLOSE_ON_TAB_LEFT == 0 or not close_button_width:
                text_offset = tab_x + 8

        draw_text = ChopText(dc, caption, tab_width - (text_offset-tab_x) - close_button_width)

        ypos = drawn_tab_yoff + (drawn_tab_height)/2 - (texty/2) - 1

        offset_focus = text_offset
        if control is not None:
            if control.GetPosition() != wx.Point(text_offset+1, ypos):
                control.SetPosition(wx.Point(text_offset+1, ypos))

            if not control.IsShown():
                control.Show()

            if paint_control:
                bmp = TakeScreenShot(control.GetScreenRect())
                dc.DrawBitmap(bmp, text_offset+1, ypos, True)

            controlW, controlH = control.GetSize()
            text_offset += controlW + 4
            textx += controlW + 4

        # draw tab text
        rectx, recty, dummy = dc.GetMultiLineTextExtent(draw_text)
        dc.DrawLabel(draw_text, wx.Rect(text_offset, ypos, rectx, recty))

        # draw focus rectangle
        if (agwFlags & AUI_NB_NO_TAB_FOCUS) == 0:
            self.DrawFocusRectangle(dc, page, wnd, draw_text, offset_focus, bitmap_offset, drawn_tab_yoff, drawn_tab_height, rectx, recty)

        out_button_rect = wx.Rect()

        # draw close button if necessary
        if close_button_state != AUI_BUTTON_STATE_HIDDEN:

            bmp = self._disabled_close_bmp

            if close_button_state == AUI_BUTTON_STATE_HOVER:
                bmp = self._hover_close_bmp
            elif close_button_state == AUI_BUTTON_STATE_PRESSED:
                bmp = self._pressed_close_bmp

            shift = (agwFlags & AUI_NB_BOTTOM and [1] or [0])[0]

            if agwFlags & AUI_NB_CLOSE_ON_TAB_LEFT:
                rect = wx.Rect(tab_x + 4, tab_y + (tab_height - bmp.GetHeight())/2 - shift,
                               close_button_width, tab_height)
            else:
                rect = wx.Rect(tab_x + tab_width - close_button_width - 1,
                               tab_y + (tab_height - bmp.GetHeight())/2 - shift,
                               close_button_width, tab_height)

            rect = IndentPressedBitmap(rect, close_button_state)
            dc.DrawBitmap(bmp, rect.x, rect.y, True)

            out_button_rect = rect

        out_tab_rect = wx.Rect(tab_x, tab_y, tab_width, tab_height)

        dc.DestroyClippingRegion()

        return out_tab_rect, out_button_rect, x_extent

[docs]    def SetCustomButton(self, bitmap_id, button_state, bmp):
        """
        Sets a custom bitmap for the close, left, right and window list
        buttons.

        :param `bitmap_id`: the button identifier;
        :param `button_state`: the button state;
        :param `bmp`: the custom bitmap to use for the button.
        """

        if bitmap_id == AUI_BUTTON_CLOSE:
            if button_state == AUI_BUTTON_STATE_NORMAL:
                self._active_close_bmp = bmp
                self._hover_close_bmp = self._active_close_bmp
                self._pressed_close_bmp = self._active_close_bmp
                self._disabled_close_bmp = self._active_close_bmp

            elif button_state == AUI_BUTTON_STATE_HOVER:
                self._hover_close_bmp = bmp
            elif button_state == AUI_BUTTON_STATE_PRESSED:
                self._pressed_close_bmp = bmp
            else:
                self._disabled_close_bmp = bmp

        elif bitmap_id == AUI_BUTTON_LEFT:
            if button_state & AUI_BUTTON_STATE_DISABLED:
                self._disabled_left_bmp = bmp
            else:
                self._active_left_bmp = bmp

        elif bitmap_id == AUI_BUTTON_RIGHT:
            if button_state & AUI_BUTTON_STATE_DISABLED:
                self._disabled_right_bmp = bmp
            else:
                self._active_right_bmp = bmp

        elif bitmap_id == AUI_BUTTON_WINDOWLIST:
            if button_state & AUI_BUTTON_STATE_DISABLED:
                self._disabled_windowlist_bmp = bmp
            else:
                self._active_windowlist_bmp = bmp

[docs]    def GetIndentSize(self):
        """ Returns the tabs indent size. """

        return 5

[docs]    def GetTabSize(self, dc, wnd, caption, bitmap, active, close_button_state, control=None):
        """
        Returns the tab size for the given caption, bitmap and button state.

        :param `dc`: a `wx.DC` device context;
        :param `wnd`: a `wx.Window` instance object;
        :param `caption`: the tab text caption;
        :param `bitmap`: the bitmap displayed on the tab;
        :param `active`: whether the tab is selected or not;
        :param `close_button_state`: the state of the close button on the tab;
        :param `control`: a `wx.Window` instance inside a tab (or ``None``).
        """

        dc.SetFont(self._measuring_font)
        measured_textx, measured_texty, dummy = dc.GetMultiLineTextExtent(caption)

        # add padding around the text
        tab_width = measured_textx
        tab_height = measured_texty

        # if the close button is showing, add space for it
        if close_button_state != AUI_BUTTON_STATE_HIDDEN:
            tab_width += self._active_close_bmp.GetWidth() + 3

        # if there's a bitmap, add space for it
        if bitmap.IsOk():
            tab_width += bitmap.GetWidth()
            tab_width += 3 # right side bitmap padding
            tab_height = max(tab_height, bitmap.GetHeight())

        # add padding
        tab_width += 16
        tab_height += 10

        agwFlags = self.GetAGWFlags()
        if agwFlags & AUI_NB_TAB_FIXED_WIDTH:
            tab_width = self._fixed_tab_width

        if control is not None:
            tab_width += control.GetSize().GetWidth() + 4

        x_extent = tab_width

        return (tab_width, tab_height), x_extent

[docs]    def DrawButton(self, dc, wnd, in_rect, button, orientation):
        """
        Draws a button on the tab or on the tab area, depending on the button identifier.

        :param `dc`: a `wx.DC` device context;
        :param `wnd`: a `wx.Window` instance object;
        :param `in_rect`: rectangle the tab should be confined to;
        :param `button`: an instance of the button class;
        :param `orientation`: the tab orientation.
        """

        bitmap_id, button_state = button.id, button.cur_state

        if bitmap_id == AUI_BUTTON_CLOSE:
            if button_state & AUI_BUTTON_STATE_DISABLED:
                bmp = self._disabled_close_bmp
            elif button_state & AUI_BUTTON_STATE_HOVER:
                bmp = self._hover_close_bmp
            elif button_state & AUI_BUTTON_STATE_PRESSED:
                bmp = self._pressed_close_bmp
            else:
                bmp = self._active_close_bmp

        elif bitmap_id == AUI_BUTTON_LEFT:
            if button_state & AUI_BUTTON_STATE_DISABLED:
                bmp = self._disabled_left_bmp
            else:
                bmp = self._active_left_bmp

        elif bitmap_id == AUI_BUTTON_RIGHT:
            if button_state & AUI_BUTTON_STATE_DISABLED:
                bmp = self._disabled_right_bmp
            else:
                bmp = self._active_right_bmp

        elif bitmap_id == AUI_BUTTON_WINDOWLIST:
            if button_state & AUI_BUTTON_STATE_DISABLED:
                bmp = self._disabled_windowlist_bmp
            else:
                bmp = self._active_windowlist_bmp

        else:
            if button_state & AUI_BUTTON_STATE_DISABLED:
                bmp = button.dis_bitmap
            else:
                bmp = button.bitmap

        if not bmp.IsOk():
            return

        rect = wx.Rect(*in_rect)

        if orientation == wx.LEFT:

            rect.SetX(in_rect.x)
            rect.SetY(((in_rect.y + in_rect.height)/2) - (bmp.GetHeight()/2))
            rect.SetWidth(bmp.GetWidth())
            rect.SetHeight(bmp.GetHeight())

        else:

            rect = wx.Rect(in_rect.x + in_rect.width - bmp.GetWidth(),
                           ((in_rect.y + in_rect.height)/2) - (bmp.GetHeight()/2),
                           bmp.GetWidth(), bmp.GetHeight())

        rect = IndentPressedBitmap(rect, button_state)
        dc.DrawBitmap(bmp, rect.x, rect.y, True)

        out_rect = rect

        if bitmap_id == AUI_BUTTON_RIGHT:
            self._buttonRect = wx.Rect(rect.x, rect.y, 30, rect.height)

        return out_rect

[docs]    def DrawFocusRectangle(self, dc, page, wnd, draw_text, text_offset, bitmap_offset, drawn_tab_yoff, drawn_tab_height, textx, texty):
        """
        Draws the focus rectangle on a tab.

        :param `dc`: a `wx.DC` device context;
        :param `page`: the page associated with the tab;
        :param `wnd`: a `wx.Window` instance object;
        :param `draw_text`: the text that has been drawn on the tab;
        :param `text_offset`: the text offset on the tab;
        :param `bitmap_offset`: the bitmap offset on the tab;
        :param `drawn_tab_yoff`: the y offset of the tab text;
        :param `drawn_tab_height`: the height of the tab;
        :param `textx`: the x text extent;
        :param `texty`: the y text extent.
        """

        if self.GetAGWFlags() & AUI_NB_NO_TAB_FOCUS:
            return

        if page.active and wx.Window.FindFocus() == wnd:

            focusRectText = wx.Rect(text_offset, (drawn_tab_yoff + (drawn_tab_height)/2 - (texty/2)),
                                    textx, texty)

            if page.bitmap.IsOk():
                focusRectBitmap = wx.Rect(bitmap_offset, drawn_tab_yoff + (drawn_tab_height/2) - (page.bitmap.GetHeight()/2),
                                          page.bitmap.GetWidth(), page.bitmap.GetHeight())

            if page.bitmap.IsOk() and draw_text == "":
                focusRect = wx.Rect(*focusRectBitmap)
            elif not page.bitmap.IsOk() and draw_text != "":
                focusRect = wx.Rect(*focusRectText)
            elif page.bitmap.IsOk() and draw_text != "":
                focusRect = focusRectText.Union(focusRectBitmap)

            focusRect.Inflate(2, 2)

            dc.SetBrush(wx.TRANSPARENT_BRUSH)
            dc.SetPen(self._focusPen)
            dc.DrawRoundedRectangleRect(focusRect, 2)

[docs]    def GetBestTabCtrlSize(self, wnd, pages, required_bmp_size):
        """
        Returns the best tab control size.

        :param `wnd`: a `wx.Window` instance object;
        :param `pages`: the pages associated with the tabs;
        :param `required_bmp_size`: the size of the bitmap on the tabs.
        """

        dc = wx.ClientDC(wnd)
        dc.SetFont(self._measuring_font)

        # sometimes a standard bitmap size needs to be enforced, especially
        # if some tabs have bitmaps and others don't.  This is important because
        # it prevents the tab control from resizing when tabs are added.

        measure_bmp = wx.NullBitmap

        if required_bmp_size.IsFullySpecified():
            measure_bmp = wx.EmptyBitmap(required_bmp_size.x,
                                         required_bmp_size.y)

        max_y = 0

        for page in pages:

            if measure_bmp.IsOk():
                bmp = measure_bmp
            else:
                bmp = page.bitmap

            # we don't use the caption text because we don't
            # want tab heights to be different in the case
            # of a very short piece of text on one tab and a very
            # tall piece of text on another tab
            s, x_ext = self.GetTabSize(dc, wnd, page.caption, bmp, True, AUI_BUTTON_STATE_HIDDEN, None)
            max_y = max(max_y, s[1])

            if page.control:
                controlW, controlH = page.control.GetSize()
                max_y = max(max_y, controlH+4)

        return max_y + 2

[docs]    def SetNormalFont(self, font):
        """
        Sets the normal font for drawing tab labels.

        :param `font`: a `wx.Font` object.
        """

        self._normal_font = font

[docs]    def SetSelectedFont(self, font):
        """
        Sets the selected tab font for drawing tab labels.

        :param `font`: a `wx.Font` object.
        """

        self._selected_font = font

[docs]    def SetMeasuringFont(self, font):
        """
        Sets the font for calculating text measurements.

        :param `font`: a `wx.Font` object.
        """

        self._measuring_font = font

[docs]    def GetNormalFont(self):
        """ Returns the normal font for drawing tab labels. """

        return self._normal_font

[docs]    def GetSelectedFont(self):
        """ Returns the selected tab font for drawing tab labels. """

        return self._selected_font

[docs]    def GetMeasuringFont(self):
        """ Returns the font for calculating text measurements. """

        return self._measuring_font

[docs]    def ShowDropDown(self, wnd, pages, active_idx):
        """
        Shows the drop-down window menu on the tab area.

        :param `wnd`: a `wx.Window` derived window instance;
        :param `pages`: the pages associated with the tabs;
        :param `active_idx`: the active tab index.
        """

        useImages = self.GetAGWFlags() & AUI_NB_USE_IMAGES_DROPDOWN
        menuPopup = wx.Menu()

        longest = 0
        for i, page in enumerate(pages):

            caption = page.caption

            # if there is no caption, make it a space.  This will prevent
            # an assert in the menu code.
            if caption == "":
                caption = " "

            # Save longest caption width for calculating menu width with
            width = wnd.GetTextExtent(caption)[0]
            if width > longest:
                longest = width

            if useImages:
                menuItem = wx.MenuItem(menuPopup, 1000+i, caption)
                if page.bitmap:
                    menuItem.SetBitmap(page.bitmap)

                menuPopup.AppendItem(menuItem)

            else:

                menuPopup.AppendCheckItem(1000+i, caption)

            menuPopup.Enable(1000+i, page.enabled)

        if active_idx != -1 and not useImages:

            menuPopup.Check(1000+active_idx, True)

        # find out the screen coordinate at the bottom of the tab ctrl
        cli_rect = wnd.GetClientRect()

        # Calculate the approximate size of the popupmenu for setting the
        # position of the menu when its shown.
        # Account for extra padding on left/right of text on mac menus
        if wx.Platform in ['__WXMAC__', '__WXMSW__']:
            longest += 32

        # Bitmap/Checkmark width + padding
        longest += 20

        if self.GetAGWFlags() & AUI_NB_CLOSE_BUTTON:
            longest += 16

        pt = wx.Point(cli_rect.x + cli_rect.GetWidth() - longest,
                     cli_rect.y + cli_rect.height)

        cc = AuiCommandCapture()
        wnd.PushEventHandler(cc)
        wnd.PopupMenu(menuPopup, pt)
        command = cc.GetCommandId()
        wnd.PopEventHandler(True)

        if command >= 1000:
            return command - 1000

        return -1

[docs]class AuiSimpleTabArt(object):
    """ A simple-looking implementation of a tab art. """

[docs]    def __init__(self):
        """ Default class constructor. """

        self._normal_font = wx.SystemSettings.GetFont(wx.SYS_DEFAULT_GUI_FONT)
        self._selected_font = wx.SystemSettings.GetFont(wx.SYS_DEFAULT_GUI_FONT)
        self._selected_font.SetWeight(wx.BOLD)
        self._measuring_font = self._selected_font

        self._agwFlags = 0
        self._fixed_tab_width = 100

        base_colour = wx.SystemSettings.GetColour(wx.SYS_COLOUR_3DFACE)

        background_colour = base_colour
        normaltab_colour = base_colour
        selectedtab_colour = wx.WHITE

        self._bkbrush = wx.Brush(background_colour)
        self._normal_bkbrush = wx.Brush(normaltab_colour)
        self._normal_bkpen = wx.Pen(normaltab_colour)
        self._selected_bkbrush = wx.Brush(selectedtab_colour)
        self._selected_bkpen = wx.Pen(selectedtab_colour)

        self._active_close_bmp = BitmapFromBits(nb_close_bits, 16, 16, wx.BLACK)
        self._disabled_close_bmp = BitmapFromBits(nb_close_bits, 16, 16, wx.Colour(128, 128, 128))

        self._active_left_bmp = BitmapFromBits(nb_left_bits, 16, 16, wx.BLACK)
        self._disabled_left_bmp = BitmapFromBits(nb_left_bits, 16, 16, wx.Colour(128, 128, 128))

        self._active_right_bmp = BitmapFromBits(nb_right_bits, 16, 16, wx.BLACK)
        self._disabled_right_bmp = BitmapFromBits(nb_right_bits, 16, 16, wx.Colour(128, 128, 128))

        self._active_windowlist_bmp = BitmapFromBits(nb_list_bits, 16, 16, wx.BLACK)
        self._disabled_windowlist_bmp = BitmapFromBits(nb_list_bits, 16, 16, wx.Colour(128, 128, 128))

[docs]    def Clone(self):
        """ Clones the art object. """

        art = type(self)()
        art.SetNormalFont(self.GetNormalFont())
        art.SetSelectedFont(self.GetSelectedFont())
        art.SetMeasuringFont(self.GetMeasuringFont())

        art = CopyAttributes(art, self)
        return art

[docs]    def SetAGWFlags(self, agwFlags):
        """
        Sets the tab art flags.

        :param `agwFlags`: a combination of the following values:

         ==================================== ==================================
         Flag name                            Description
         ==================================== ==================================
         ``AUI_NB_TOP``                       With this style, tabs are drawn along the top of the notebook
         ``AUI_NB_LEFT``                      With this style, tabs are drawn along the left of the notebook. Not implemented yet.
         ``AUI_NB_RIGHT``                     With this style, tabs are drawn along the right of the notebook. Not implemented yet.
         ``AUI_NB_BOTTOM``                    With this style, tabs are drawn along the bottom of the notebook
         ``AUI_NB_TAB_SPLIT``                 Allows the tab control to be split by dragging a tab
         ``AUI_NB_TAB_MOVE``                  Allows a tab to be moved horizontally by dragging
         ``AUI_NB_TAB_EXTERNAL_MOVE``         Allows a tab to be moved to another tab control
         ``AUI_NB_TAB_FIXED_WIDTH``           With this style, all tabs have the same width
         ``AUI_NB_SCROLL_BUTTONS``            With this style, left and right scroll buttons are displayed
         ``AUI_NB_WINDOWLIST_BUTTON``         With this style, a drop-down list of windows is available
         ``AUI_NB_CLOSE_BUTTON``              With this style, a close button is available on the tab bar
         ``AUI_NB_CLOSE_ON_ACTIVE_TAB``       With this style, a close button is available on the active tab
         ``AUI_NB_CLOSE_ON_ALL_TABS``         With this style, a close button is available on all tabs
         ``AUI_NB_MIDDLE_CLICK_CLOSE``        Allows to close L{AuiNotebook} tabs by mouse middle button click
         ``AUI_NB_SUB_NOTEBOOK``              This style is used by L{AuiManager} to create automatic AuiNotebooks
         ``AUI_NB_HIDE_ON_SINGLE_TAB``        Hides the tab window if only one tab is present
         ``AUI_NB_SMART_TABS``                Use Smart Tabbing, like ``Alt`` + ``Tab`` on Windows
         ``AUI_NB_USE_IMAGES_DROPDOWN``       Uses images on dropdown window list menu instead of check items
         ``AUI_NB_CLOSE_ON_TAB_LEFT``         Draws the tab close button on the left instead of on the right (a la Camino browser)
         ``AUI_NB_TAB_FLOAT``                 Allows the floating of single tabs. Known limitation: when the notebook is more or less full screen, tabs cannot be dragged far enough outside of the notebook to become floating pages
         ``AUI_NB_DRAW_DND_TAB``              Draws an image representation of a tab while dragging (on by default)
         ``AUI_NB_ORDER_BY_ACCESS``           Tab navigation order by last access time for the tabs
         ``AUI_NB_NO_TAB_FOCUS``              Don't draw tab focus rectangle
         ==================================== ==================================

        """

        self._agwFlags = agwFlags

[docs]    def GetAGWFlags(self):
        """
        Returns the tab art flags.

        :see: L{SetAGWFlags} for a list of possible return values.
        """

        return self._agwFlags

[docs]    def SetSizingInfo(self, tab_ctrl_size, tab_count, minMaxTabWidth):
        """
        Sets the tab sizing information.

        :param `tab_ctrl_size`: the size of the tab control area;
        :param `tab_count`: the number of tabs;
        :param `minMaxTabWidth`: a tuple containing the minimum and maximum tab widths
         to be used when the ``AUI_NB_TAB_FIXED_WIDTH`` style is active.
        """

        self._fixed_tab_width = 100
        minTabWidth, maxTabWidth = minMaxTabWidth

        tot_width = tab_ctrl_size.x - self.GetIndentSize() - 4

        if self._agwFlags & AUI_NB_CLOSE_BUTTON:
            tot_width -= self._active_close_bmp.GetWidth()
        if self._agwFlags & AUI_NB_WINDOWLIST_BUTTON:
            tot_width -= self._active_windowlist_bmp.GetWidth()

        if tab_count > 0:
            self._fixed_tab_width = tot_width/tab_count

        if self._fixed_tab_width < 100:
            self._fixed_tab_width = 100

        if self._fixed_tab_width > tot_width/2:
            self._fixed_tab_width = tot_width/2

        if self._fixed_tab_width > 220:
            self._fixed_tab_width = 220

        if minTabWidth > -1:
            self._fixed_tab_width = max(self._fixed_tab_width, minTabWidth)
        if maxTabWidth > -1:
            self._fixed_tab_width = min(self._fixed_tab_width, maxTabWidth)

        self._tab_ctrl_height = tab_ctrl_size.y

[docs]    def DrawBackground(self, dc, wnd, rect):
        """
        Draws the tab area background.

        :param `dc`: a `wx.DC` device context;
        :param `wnd`: a `wx.Window` instance object;
        :param `rect`: the tab control rectangle.
        """

        # draw background
        dc.SetBrush(self._bkbrush)
        dc.SetPen(wx.TRANSPARENT_PEN)
        dc.DrawRectangle(-1, -1, rect.GetWidth()+2, rect.GetHeight()+2)

        # draw base line
        dc.SetPen(wx.GREY_PEN)
        dc.DrawLine(0, rect.GetHeight()-1, rect.GetWidth(), rect.GetHeight()-1)

[docs]    def DrawTab(self, dc, wnd, page, in_rect, close_button_state, paint_control=False):
        """
        Draws a single tab.

        :param `dc`: a `wx.DC` device context;
        :param `wnd`: a `wx.Window` instance object;
        :param `page`: the tab control page associated with the tab;
        :param `in_rect`: rectangle the tab should be confined to;
        :param `close_button_state`: the state of the close button on the tab;
        :param `paint_control`: whether to draw the control inside a tab (if any) on a `wx.MemoryDC`.
        """

        # if the caption is empty, measure some temporary text
        caption = page.caption
        if caption == "":
            caption = "Xj"

        agwFlags = self.GetAGWFlags()

        dc.SetFont(self._selected_font)
        selected_textx, selected_texty, dummy = dc.GetMultiLineTextExtent(caption)

        dc.SetFont(self._normal_font)
        normal_textx, normal_texty, dummy = dc.GetMultiLineTextExtent(caption)

        control = page.control

        # figure out the size of the tab
        tab_size, x_extent = self.GetTabSize(dc, wnd, page.caption, page.bitmap,
                                             page.active, close_button_state, control)

        tab_height = tab_size[1]
        tab_width = tab_size[0]
        tab_x = in_rect.x
        tab_y = in_rect.y + in_rect.height - tab_height

        caption = page.caption
        # select pen, brush and font for the tab to be drawn

        if page.active:

            dc.SetPen(self._selected_bkpen)
            dc.SetBrush(self._selected_bkbrush)
            dc.SetFont(self._selected_font)
            textx = selected_textx
            texty = selected_texty

        else:

            dc.SetPen(self._normal_bkpen)
            dc.SetBrush(self._normal_bkbrush)
            dc.SetFont(self._normal_font)
            textx = normal_textx
            texty = normal_texty

        if not page.enabled:
            dc.SetTextForeground(wx.SystemSettings.GetColour(wx.SYS_COLOUR_GRAYTEXT))
        else:
            dc.SetTextForeground(page.text_colour)

        # -- draw line --

        points = [wx.Point() for i in xrange(7)]
        points[0].x = tab_x
        points[0].y = tab_y + tab_height - 1
        points[1].x = tab_x + tab_height - 3
        points[1].y = tab_y + 2
        points[2].x = tab_x + tab_height + 3
        points[2].y = tab_y
        points[3].x = tab_x + tab_width - 2
        points[3].y = tab_y
        points[4].x = tab_x + tab_width
        points[4].y = tab_y + 2
        points[5].x = tab_x + tab_width
        points[5].y = tab_y + tab_height - 1
        points[6] = points[0]

        dc.SetClippingRect(in_rect)
        dc.DrawPolygon(points)

        dc.SetPen(wx.GREY_PEN)
        dc.DrawLines(points)

        close_button_width = 0

        if close_button_state != AUI_BUTTON_STATE_HIDDEN:

            close_button_width = self._active_close_bmp.GetWidth()
            if agwFlags & AUI_NB_CLOSE_ON_TAB_LEFT:
                if control:
                    text_offset = tab_x + (tab_height/2) + close_button_width - (textx/2) - 2
                else:
                    text_offset = tab_x + (tab_height/2) + ((tab_width+close_button_width)/2) - (textx/2) - 2
            else:
                if control:
                    text_offset = tab_x + (tab_height/2) + close_button_width - (textx/2)
                else:
                    text_offset = tab_x + (tab_height/2) + ((tab_width-close_button_width)/2) - (textx/2)

        else:

            text_offset = tab_x + (tab_height/3) + (tab_width/2) - (textx/2)
            if control:
                if agwFlags & AUI_NB_CLOSE_ON_TAB_LEFT:
                    text_offset = tab_x + (tab_height/3) - (textx/2) + close_button_width + 2
                else:
                    text_offset = tab_x + (tab_height/3) - (textx/2)

        # set minimum text offset
        if text_offset < tab_x + tab_height:
            text_offset = tab_x + tab_height

        # chop text if necessary
        if agwFlags & AUI_NB_CLOSE_ON_TAB_LEFT:
            draw_text = ChopText(dc, caption, tab_width - (text_offset-tab_x))
        else:
            draw_text = ChopText(dc, caption,
                                 tab_width - (text_offset-tab_x) - close_button_width)

        ypos = (tab_y + tab_height)/2 - (texty/2) + 1

        if control is not None:
            if control.GetPosition() != wx.Point(text_offset+1, ypos):
                control.SetPosition(wx.Point(text_offset+1, ypos))

            if not control.IsShown():
                control.Show()

            if paint_control:
                bmp = TakeScreenShot(control.GetScreenRect())
                dc.DrawBitmap(bmp, text_offset+1, ypos, True)

            controlW, controlH = control.GetSize()
            text_offset += controlW + 4

        # draw tab text
        rectx, recty, dummy = dc.GetMultiLineTextExtent(draw_text)
        dc.DrawLabel(draw_text, wx.Rect(text_offset, ypos, rectx, recty))

        # draw focus rectangle
        if page.active and wx.Window.FindFocus() == wnd and (agwFlags & AUI_NB_NO_TAB_FOCUS) == 0:

            focusRect = wx.Rect(text_offset, ((tab_y + tab_height)/2 - (texty/2) + 1),
                                selected_textx, selected_texty)

            focusRect.Inflate(2, 2)
            # TODO:
            # This should be uncommented when DrawFocusRect will become
            # available in wxPython
            # wx.RendererNative.Get().DrawFocusRect(wnd, dc, focusRect, 0)

        out_button_rect = wx.Rect()
        # draw close button if necessary
        if close_button_state != AUI_BUTTON_STATE_HIDDEN:

            if page.active:
                bmp = self._active_close_bmp
            else:
                bmp = self._disabled_close_bmp

            if agwFlags & AUI_NB_CLOSE_ON_TAB_LEFT:
                rect = wx.Rect(tab_x + tab_height - 2,
                               tab_y + (tab_height/2) - (bmp.GetHeight()/2) + 1,
                               close_button_width, tab_height - 1)
            else:
                rect = wx.Rect(tab_x + tab_width - close_button_width - 1,
                               tab_y + (tab_height/2) - (bmp.GetHeight()/2) + 1,
                               close_button_width, tab_height - 1)

            self.DrawButtons(dc, rect, bmp, wx.WHITE, close_button_state)
            out_button_rect = wx.Rect(*rect)

        out_tab_rect = wx.Rect(tab_x, tab_y, tab_width, tab_height)
        dc.DestroyClippingRegion()

        return out_tab_rect, out_button_rect, x_extent

[docs]    def DrawButtons(self, dc, _rect, bmp, bkcolour, button_state):
        """
        Convenience method to draw tab buttons.

        :param `dc`: a `wx.DC` device context;
        :param `_rect`: the tab rectangle;
        :param `bmp`: the tab bitmap;
        :param `bkcolour`: the tab background colour;
        :param `button_state`: the state of the tab button.
        """

        rect = wx.Rect(*_rect)

        if button_state == AUI_BUTTON_STATE_PRESSED:
            rect.x += 1
            rect.y += 1

        if button_state in [AUI_BUTTON_STATE_HOVER, AUI_BUTTON_STATE_PRESSED]:
            dc.SetBrush(wx.Brush(StepColour(bkcolour, 120)))
            dc.SetPen(wx.Pen(StepColour(bkcolour, 75)))

            # draw the background behind the button
            dc.DrawRectangle(rect.x, rect.y, 15, 15)

        # draw the button itself
        dc.DrawBitmap(bmp, rect.x, rect.y, True)

[docs]    def GetIndentSize(self):
        """ Returns the tabs indent size. """

        return 0

[docs]    def GetTabSize(self, dc, wnd, caption, bitmap, active, close_button_state, control=None):
        """
        Returns the tab size for the given caption, bitmap and button state.

        :param `dc`: a `wx.DC` device context;
        :param `wnd`: a `wx.Window` instance object;
        :param `caption`: the tab text caption;
        :param `bitmap`: the bitmap displayed on the tab;
        :param `active`: whether the tab is selected or not;
        :param `close_button_state`: the state of the close button on the tab;
        :param `control`: a `wx.Window` instance inside a tab (or ``None``).
        """

        dc.SetFont(self._measuring_font)
        measured_textx, measured_texty, dummy = dc.GetMultiLineTextExtent(caption)

        tab_height = measured_texty + 4
        tab_width = measured_textx + tab_height + 5

        if close_button_state != AUI_BUTTON_STATE_HIDDEN:
            tab_width += self._active_close_bmp.GetWidth()

        if self._agwFlags & AUI_NB_TAB_FIXED_WIDTH:
            tab_width = self._fixed_tab_width

        if control is not None:
            controlW, controlH = control.GetSize()
            tab_width += controlW + 4

        x_extent = tab_width - (tab_height/2) - 1

        return (tab_width, tab_height), x_extent

[docs]    def DrawButton(self, dc, wnd, in_rect, button, orientation):
        """
        Draws a button on the tab or on the tab area, depending on the button identifier.

        :param `dc`: a `wx.DC` device context;
        :param `wnd`: a `wx.Window` instance object;
        :param `in_rect`: rectangle the tab should be confined to;
        :param `button`: an instance of the button class;
        :param `orientation`: the tab orientation.
        """

        bitmap_id, button_state = button.id, button.cur_state

        if bitmap_id == AUI_BUTTON_CLOSE:
            if button_state & AUI_BUTTON_STATE_DISABLED:
                bmp = self._disabled_close_bmp
            else:
                bmp = self._active_close_bmp

        elif bitmap_id == AUI_BUTTON_LEFT:
            if button_state & AUI_BUTTON_STATE_DISABLED:
                bmp = self._disabled_left_bmp
            else:
                bmp = self._active_left_bmp

        elif bitmap_id == AUI_BUTTON_RIGHT:
            if button_state & AUI_BUTTON_STATE_DISABLED:
                bmp = self._disabled_right_bmp
            else:
                bmp = self._active_right_bmp

        elif bitmap_id == AUI_BUTTON_WINDOWLIST:
            if button_state & AUI_BUTTON_STATE_DISABLED:
                bmp = self._disabled_windowlist_bmp
            else:
                bmp = self._active_windowlist_bmp

        else:
            if button_state & AUI_BUTTON_STATE_DISABLED:
                bmp = button.dis_bitmap
            else:
                bmp = button.bitmap

        if not bmp.IsOk():
            return

        rect = wx.Rect(*in_rect)

        if orientation == wx.LEFT:

            rect.SetX(in_rect.x)
            rect.SetY(((in_rect.y + in_rect.height)/2) - (bmp.GetHeight()/2))
            rect.SetWidth(bmp.GetWidth())
            rect.SetHeight(bmp.GetHeight())

        else:

            rect = wx.Rect(in_rect.x + in_rect.width - bmp.GetWidth(),
                           ((in_rect.y + in_rect.height)/2) - (bmp.GetHeight()/2),
                           bmp.GetWidth(), bmp.GetHeight())

        self.DrawButtons(dc, rect, bmp, wx.WHITE, button_state)

        out_rect = wx.Rect(*rect)
        return out_rect

[docs]    def ShowDropDown(self, wnd, pages, active_idx):
        """
        Shows the drop-down window menu on the tab area.

        :param `wnd`: a `wx.Window` derived window instance;
        :param `pages`: the pages associated with the tabs;
        :param `active_idx`: the active tab index.
        """

        menuPopup = wx.Menu()
        useImages = self.GetAGWFlags() & AUI_NB_USE_IMAGES_DROPDOWN

        for i, page in enumerate(pages):

            if useImages:
                menuItem = wx.MenuItem(menuPopup, 1000+i, page.caption)
                if page.bitmap:
                    menuItem.SetBitmap(page.bitmap)

                menuPopup.AppendItem(menuItem)

            else:

                menuPopup.AppendCheckItem(1000+i, page.caption)

            menuPopup.Enable(1000+i, page.enabled)

        if active_idx != -1 and not useImages:
            menuPopup.Check(1000+active_idx, True)

        # find out where to put the popup menu of window
        # items.  Subtract 100 for now to center the menu
        # a bit, until a better mechanism can be implemented
        pt = wx.GetMousePosition()
        pt = wnd.ScreenToClient(pt)

        if pt.x < 100:
            pt.x = 0
        else:
            pt.x -= 100

        # find out the screen coordinate at the bottom of the tab ctrl
        cli_rect = wnd.GetClientRect()
        pt.y = cli_rect.y + cli_rect.height

        cc = AuiCommandCapture()
        wnd.PushEventHandler(cc)
        wnd.PopupMenu(menuPopup, pt)
        command = cc.GetCommandId()
        wnd.PopEventHandler(True)

        if command >= 1000:
            return command-1000

        return -1

[docs]    def GetBestTabCtrlSize(self, wnd, pages, required_bmp_size):
        """
        Returns the best tab control size.

        :param `wnd`: a `wx.Window` instance object;
        :param `pages`: the pages associated with the tabs;
        :param `required_bmp_size`: the size of the bitmap on the tabs.
        """

        dc = wx.ClientDC(wnd)
        dc.SetFont(self._measuring_font)
        s, x_extent = self.GetTabSize(dc, wnd, "ABCDEFGHIj", wx.NullBitmap, True,
                                      AUI_BUTTON_STATE_HIDDEN, None)

        max_y = s[1]

        for page in pages:
            if page.control:
                controlW, controlH = page.control.GetSize()
                max_y = max(max_y, controlH+4)

            textx, texty, dummy = dc.GetMultiLineTextExtent(page.caption)
            max_y = max(max_y, texty)

        return max_y + 3

[docs]    def SetNormalFont(self, font):
        """
        Sets the normal font for drawing tab labels.

        :param `font`: a `wx.Font` object.
        """

        self._normal_font = font

[docs]    def SetSelectedFont(self, font):
        """
        Sets the selected tab font for drawing tab labels.

        :param `font`: a `wx.Font` object.
        """

        self._selected_font = font

[docs]    def SetMeasuringFont(self, font):
        """
        Sets the font for calculating text measurements.

        :param `font`: a `wx.Font` object.
        """

        self._measuring_font = font

[docs]    def GetNormalFont(self):
        """ Returns the normal font for drawing tab labels. """

        return self._normal_font

[docs]    def GetSelectedFont(self):
        """ Returns the selected tab font for drawing tab labels. """

        return self._selected_font

[docs]    def GetMeasuringFont(self):
        """ Returns the font for calculating text measurements. """

        return self._measuring_font

[docs]    def SetCustomButton(self, bitmap_id, button_state, bmp):
        """
        Sets a custom bitmap for the close, left, right and window list
        buttons.

        :param `bitmap_id`: the button identifier;
        :param `button_state`: the button state;
        :param `bmp`: the custom bitmap to use for the button.
        """

        if bitmap_id == AUI_BUTTON_CLOSE:
            if button_state == AUI_BUTTON_STATE_NORMAL:
                self._active_close_bmp = bmp
                self._hover_close_bmp = self._active_close_bmp
                self._pressed_close_bmp = self._active_close_bmp
                self._disabled_close_bmp = self._active_close_bmp

            elif button_state == AUI_BUTTON_STATE_HOVER:
                self._hover_close_bmp = bmp
            elif button_state == AUI_BUTTON_STATE_PRESSED:
                self._pressed_close_bmp = bmp
            else:
                self._disabled_close_bmp = bmp

        elif bitmap_id == AUI_BUTTON_LEFT:
            if button_state & AUI_BUTTON_STATE_DISABLED:
                self._disabled_left_bmp = bmp
            else:
                self._active_left_bmp = bmp

        elif bitmap_id == AUI_BUTTON_RIGHT:
            if button_state & AUI_BUTTON_STATE_DISABLED:
                self._disabled_right_bmp = bmp
            else:
                self._active_right_bmp = bmp

        elif bitmap_id == AUI_BUTTON_WINDOWLIST:
            if button_state & AUI_BUTTON_STATE_DISABLED:
                self._disabled_windowlist_bmp = bmp
            else:
                self._active_windowlist_bmp = bmp

[docs]class VC71TabArt(AuiDefaultTabArt):
    """ A class to draw tabs using the Visual Studio 2003 (VC71) style. """

[docs]    def __init__(self):
        """ Default class constructor. """

        AuiDefaultTabArt.__init__(self)

[docs]    def Clone(self):
        """ Clones the art object. """

        art = type(self)()
        art.SetNormalFont(self.GetNormalFont())
        art.SetSelectedFont(self.GetSelectedFont())
        art.SetMeasuringFont(self.GetMeasuringFont())

        art = CopyAttributes(art, self)
        return art

[docs]    def DrawTab(self, dc, wnd, page, in_rect, close_button_state, paint_control=False):
        """
        Draws a single tab.

        :param `dc`: a `wx.DC` device context;
        :param `wnd`: a `wx.Window` instance object;
        :param `page`: the tab control page associated with the tab;
        :param `in_rect`: rectangle the tab should be confined to;
        :param `close_button_state`: the state of the close button on the tab;
        :param `paint_control`: whether to draw the control inside a tab (if any) on a `wx.MemoryDC`.
        """

        # Visual studio 7.1 style
        # This code is based on the renderer included in FlatNotebook

        # figure out the size of the tab

        control = page.control
        tab_size, x_extent = self.GetTabSize(dc, wnd, page.caption, page.bitmap, page.active,
                                             close_button_state, control)

        tab_height = self._tab_ctrl_height - 3
        tab_width = tab_size[0]
        tab_x = in_rect.x
        tab_y = in_rect.y + in_rect.height - tab_height
        clip_width = tab_width

        if tab_x + clip_width > in_rect.x + in_rect.width - 4:
            clip_width = (in_rect.x + in_rect.width) - tab_x - 4

        dc.SetClippingRegion(tab_x, tab_y, clip_width + 1, tab_height - 3)
        agwFlags = self.GetAGWFlags()

        if agwFlags & AUI_NB_BOTTOM:
            tab_y -= 1

        dc.SetPen((page.active and [wx.Pen(wx.SystemSettings.GetColour(wx.SYS_COLOUR_3DHIGHLIGHT))] or \
                   [wx.Pen(wx.SystemSettings.GetColour(wx.SYS_COLOUR_3DSHADOW))])[0])
        dc.SetBrush((page.active and [wx.Brush(wx.SystemSettings.GetColour(wx.SYS_COLOUR_3DFACE))] or \
                     [wx.TRANSPARENT_BRUSH])[0])

        if page.active:

            tabH = tab_height - 2
            dc.DrawRectangle(tab_x, tab_y, tab_width, tabH)

            rightLineY1 = (agwFlags & AUI_NB_BOTTOM and [vertical_border_padding - 2] or \
                           [vertical_border_padding - 1])[0]
            rightLineY2 = tabH + 3
            dc.SetPen(wx.Pen(wx.SystemSettings.GetColour(wx.SYS_COLOUR_3DSHADOW)))
            dc.DrawLine(tab_x + tab_width - 1, rightLineY1 + 1, tab_x + tab_width - 1, rightLineY2)

            if agwFlags & AUI_NB_BOTTOM:
                dc.DrawLine(tab_x + 1, rightLineY2 - 3 , tab_x + tab_width - 1, rightLineY2 - 3)

            dc.SetPen(wx.Pen(wx.SystemSettings.GetColour(wx.SYS_COLOUR_3DDKSHADOW)))
            dc.DrawLine(tab_x + tab_width, rightLineY1, tab_x + tab_width, rightLineY2)

            if agwFlags & AUI_NB_BOTTOM:
                dc.DrawLine(tab_x, rightLineY2 - 2, tab_x + tab_width, rightLineY2 - 2)

        else:

            # We dont draw a rectangle for non selected tabs, but only
            # vertical line on the right
            blackLineY1 = (agwFlags & AUI_NB_BOTTOM and [vertical_border_padding + 2] or \
                           [vertical_border_padding + 1])[0]
            blackLineY2 = tab_height - 5
            dc.DrawLine(tab_x + tab_width, blackLineY1, tab_x + tab_width, blackLineY2)

        border_points = [0, 0]

        if agwFlags & AUI_NB_BOTTOM:

            border_points[0] = wx.Point(tab_x, tab_y)
            border_points[1] = wx.Point(tab_x, tab_y + tab_height - 6)

        else: # if (agwFlags & AUI_NB_TOP)

            border_points[0] = wx.Point(tab_x, tab_y + tab_height - 4)
            border_points[1] = wx.Point(tab_x, tab_y + 2)

        drawn_tab_yoff = border_points[1].y
        drawn_tab_height = border_points[0].y - border_points[1].y

        text_offset = tab_x + 8
        close_button_width = 0

        if close_button_state != AUI_BUTTON_STATE_HIDDEN:
            close_button_width = self._active_close_bmp.GetWidth()
            if agwFlags & AUI_NB_CLOSE_ON_TAB_LEFT:
                text_offset += close_button_width - 5

        if not page.enabled:
            dc.SetTextForeground(wx.SystemSettings.GetColour(wx.SYS_COLOUR_GRAYTEXT))
            pagebitmap = page.dis_bitmap
        else:
            dc.SetTextForeground(page.text_colour)
            pagebitmap = page.bitmap

        shift = 0
        if agwFlags & AUI_NB_BOTTOM:
            shift = (page.active and [1] or [2])[0]

        bitmap_offset = 0
        if pagebitmap.IsOk():
            bitmap_offset = tab_x + 8
            if agwFlags & AUI_NB_CLOSE_ON_TAB_LEFT and close_button_width:
                bitmap_offset += close_button_width - 5

            # draw bitmap
            dc.DrawBitmap(pagebitmap, bitmap_offset,
                          drawn_tab_yoff + (drawn_tab_height/2) - (pagebitmap.GetHeight()/2) + shift,
                          True)

            text_offset = bitmap_offset + pagebitmap.GetWidth()
            text_offset += 3 # bitmap padding

        else:
            if agwFlags & AUI_NB_CLOSE_ON_TAB_LEFT == 0 or not close_button_width:
                text_offset = tab_x + 8

        # if the caption is empty, measure some temporary text
        caption = page.caption

        if caption == "":
            caption = "Xj"

        if page.active:
            dc.SetFont(self._selected_font)
            textx, texty, dummy = dc.GetMultiLineTextExtent(caption)
        else:
            dc.SetFont(self._normal_font)
            textx, texty, dummy = dc.GetMultiLineTextExtent(caption)

        draw_text = ChopText(dc, caption, tab_width - (text_offset-tab_x) - close_button_width)

        ypos = drawn_tab_yoff + (drawn_tab_height)/2 - (texty/2) - 1 + shift

        offset_focus = text_offset

        if control is not None:
            if control.GetPosition() != wx.Point(text_offset+1, ypos):
                control.SetPosition(wx.Point(text_offset+1, ypos))

            if not control.IsShown():
                control.Show()

            if paint_control:
                bmp = TakeScreenShot(control.GetScreenRect())
                dc.DrawBitmap(bmp, text_offset+1, ypos, True)

            controlW, controlH = control.GetSize()
            text_offset += controlW + 4
            textx += controlW + 4

        # draw tab text
        rectx, recty, dummy = dc.GetMultiLineTextExtent(draw_text)
        dc.DrawLabel(draw_text, wx.Rect(text_offset, ypos, rectx, recty))

        out_button_rect = wx.Rect()

        # draw focus rectangle
        if (agwFlags & AUI_NB_NO_TAB_FOCUS) == 0:
            self.DrawFocusRectangle(dc, page, wnd, draw_text, offset_focus, bitmap_offset, drawn_tab_yoff+shift,
                                    drawn_tab_height+shift, rectx, recty)

        # draw 'x' on tab (if enabled)
        if close_button_state != AUI_BUTTON_STATE_HIDDEN:
            close_button_width = self._active_close_bmp.GetWidth()

            bmp = self._disabled_close_bmp

            if close_button_state == AUI_BUTTON_STATE_HOVER:
                bmp = self._hover_close_bmp
            elif close_button_state == AUI_BUTTON_STATE_PRESSED:
                bmp = self._pressed_close_bmp

            if agwFlags & AUI_NB_CLOSE_ON_TAB_LEFT:
                rect = wx.Rect(tab_x + 4,
                               drawn_tab_yoff + (drawn_tab_height / 2) - (bmp.GetHeight() / 2) + shift,
                               close_button_width, tab_height)
            else:
                rect = wx.Rect(tab_x + tab_width - close_button_width - 3,
                               drawn_tab_yoff + (drawn_tab_height / 2) - (bmp.GetHeight() / 2) + shift,
                               close_button_width, tab_height)

            # Indent the button if it is pressed down:
            rect = IndentPressedBitmap(rect, close_button_state)
            dc.DrawBitmap(bmp, rect.x, rect.y, True)

            out_button_rect = rect

        out_tab_rect = wx.Rect(tab_x, tab_y, tab_width, tab_height)
        dc.DestroyClippingRegion()

        return out_tab_rect, out_button_rect, x_extent

[docs]class FF2TabArt(AuiDefaultTabArt):
    """ A class to draw tabs using the Firefox 2 (FF2) style. """

[docs]    def __init__(self):
        """ Default class constructor. """

        AuiDefaultTabArt.__init__(self)

[docs]    def Clone(self):
        """ Clones the art object. """

        art = type(self)()
        art.SetNormalFont(self.GetNormalFont())
        art.SetSelectedFont(self.GetSelectedFont())
        art.SetMeasuringFont(self.GetMeasuringFont())

        art = CopyAttributes(art, self)
        return art

[docs]    def GetTabSize(self, dc, wnd, caption, bitmap, active, close_button_state, control):
        """
        Returns the tab size for the given caption, bitmap and button state.

        :param `dc`: a `wx.DC` device context;
        :param `wnd`: a `wx.Window` instance object;
        :param `caption`: the tab text caption;
        :param `bitmap`: the bitmap displayed on the tab;
        :param `active`: whether the tab is selected or not;
        :param `close_button_state`: the state of the close button on the tab;
        :param `control`: a `wx.Window` instance inside a tab (or ``None``).
        """

        tab_size, x_extent = AuiDefaultTabArt.GetTabSize(self, dc, wnd, caption, bitmap,
                                                         active, close_button_state, control)

        tab_width, tab_height = tab_size

        # add some vertical padding
        tab_height += 2

        return (tab_width, tab_height), x_extent

[docs]    def DrawTab(self, dc, wnd, page, in_rect, close_button_state, paint_control=False):
        """
        Draws a single tab.

        :param `dc`: a `wx.DC` device context;
        :param `wnd`: a `wx.Window` instance object;
        :param `page`: the tab control page associated with the tab;
        :param `in_rect`: rectangle the tab should be confined to;
        :param `close_button_state`: the state of the close button on the tab;
        :param `paint_control`: whether to draw the control inside a tab (if any) on a `wx.MemoryDC`.
        """

        # Firefox 2 style

        control = page.control

        # figure out the size of the tab
        tab_size, x_extent = self.GetTabSize(dc, wnd, page.caption, page.bitmap,
                                             page.active, close_button_state, control)

        tab_height = self._tab_ctrl_height - 2
        tab_width = tab_size[0]
        tab_x = in_rect.x
        tab_y = in_rect.y + in_rect.height - tab_height

        clip_width = tab_width
        if tab_x + clip_width > in_rect.x + in_rect.width - 4:
            clip_width = (in_rect.x + in_rect.width) - tab_x - 4

        dc.SetClippingRegion(tab_x, tab_y, clip_width + 1, tab_height - 3)

        tabPoints = [wx.Point() for i in xrange(7)]

        adjust = 0
        if not page.active:
            adjust = 1

        agwFlags = self.GetAGWFlags()

        tabPoints[0].x = tab_x + 3
        tabPoints[0].y = (agwFlags & AUI_NB_BOTTOM and [3] or [tab_height - 2])[0]

        tabPoints[1].x = tabPoints[0].x
        tabPoints[1].y = (agwFlags & AUI_NB_BOTTOM and [tab_height - (vertical_border_padding + 2) - adjust] or \
                          [(vertical_border_padding + 2) + adjust])[0]

        tabPoints[2].x = tabPoints[1].x+2
        tabPoints[2].y = (agwFlags & AUI_NB_BOTTOM and [tab_height - vertical_border_padding - adjust] or \
                          [vertical_border_padding + adjust])[0]

        tabPoints[3].x = tab_x + tab_width - 2
        tabPoints[3].y = tabPoints[2].y

        tabPoints[4].x = tabPoints[3].x + 2
        tabPoints[4].y = tabPoints[1].y

        tabPoints[5].x = tabPoints[4].x
        tabPoints[5].y = tabPoints[0].y

        tabPoints[6].x = tabPoints[0].x
        tabPoints[6].y = tabPoints[0].y

        rr = wx.RectPP(tabPoints[2], tabPoints[5])
        self.DrawTabBackground(dc, rr, page.active, (agwFlags & AUI_NB_BOTTOM) == 0)

        dc.SetBrush(wx.TRANSPARENT_BRUSH)
        dc.SetPen(wx.Pen(wx.SystemSettings_GetColour(wx.SYS_COLOUR_BTNSHADOW)))

        # Draw the tab as rounded rectangle
        dc.DrawPolygon(tabPoints)

        if page.active:
            dc.DrawLine(tabPoints[0].x + 1, tabPoints[0].y, tabPoints[5].x , tabPoints[0].y)

        drawn_tab_yoff = tabPoints[1].y
        drawn_tab_height = tabPoints[0].y - tabPoints[2].y

        text_offset = tab_x + 8
        close_button_width = 0
        if close_button_state != AUI_BUTTON_STATE_HIDDEN:
            close_button_width = self._active_close_bmp.GetWidth()
            if agwFlags & AUI_NB_CLOSE_ON_TAB_LEFT:
                text_offset += close_button_width - 4

        if not page.enabled:
            dc.SetTextForeground(wx.SystemSettings.GetColour(wx.SYS_COLOUR_GRAYTEXT))
            pagebitmap = page.dis_bitmap
        else:
            dc.SetTextForeground(page.text_colour)
            pagebitmap = page.bitmap

        shift = -1
        if agwFlags & AUI_NB_BOTTOM:
            shift = 2

        bitmap_offset = 0
        if pagebitmap.IsOk():
            bitmap_offset = tab_x + 8
            if agwFlags & AUI_NB_CLOSE_ON_TAB_LEFT and close_button_width:
                bitmap_offset += close_button_width - 4

            # draw bitmap
            dc.DrawBitmap(pagebitmap, bitmap_offset,
                          drawn_tab_yoff + (drawn_tab_height/2) - (pagebitmap.GetHeight()/2) + shift,
                          True)

            text_offset = bitmap_offset + pagebitmap.GetWidth()
            text_offset += 3 # bitmap padding

        else:

            if agwFlags & AUI_NB_CLOSE_ON_TAB_LEFT == 0 or not close_button_width:
                text_offset = tab_x + 8

        # if the caption is empty, measure some temporary text
        caption = page.caption
        if caption == "":
            caption = "Xj"

        if page.active:
            dc.SetFont(self._selected_font)
            textx, texty, dummy = dc.GetMultiLineTextExtent(caption)
        else:
            dc.SetFont(self._normal_font)
            textx, texty, dummy = dc.GetMultiLineTextExtent(caption)

        if agwFlags & AUI_NB_CLOSE_ON_TAB_LEFT:
            draw_text = ChopText(dc, caption, tab_width - (text_offset-tab_x) - close_button_width + 1)
        else:
            draw_text = ChopText(dc, caption, tab_width - (text_offset-tab_x) - close_button_width)

        ypos = drawn_tab_yoff + drawn_tab_height/2 - texty/2 - 1 + shift

        offset_focus = text_offset

        if control is not None:
            if control.GetPosition() != wx.Point(text_offset+1, ypos):
                control.SetPosition(wx.Point(text_offset+1, ypos))

            if not control.IsShown():
                control.Show()

            if paint_control:
                bmp = TakeScreenShot(control.GetScreenRect())
                dc.DrawBitmap(bmp, text_offset+1, ypos, True)

            controlW, controlH = control.GetSize()
            text_offset += controlW + 4
            textx += controlW + 4

        # draw tab text
        rectx, recty, dummy = dc.GetMultiLineTextExtent(draw_text)
        dc.DrawLabel(draw_text, wx.Rect(text_offset, ypos, rectx, recty))

        # draw focus rectangle
        if (agwFlags & AUI_NB_NO_TAB_FOCUS) == 0:
            self.DrawFocusRectangle(dc, page, wnd, draw_text, offset_focus, bitmap_offset, drawn_tab_yoff+shift,
                                    drawn_tab_height, rectx, recty)

        out_button_rect = wx.Rect()
        # draw 'x' on tab (if enabled)
        if close_button_state != AUI_BUTTON_STATE_HIDDEN:

            close_button_width = self._active_close_bmp.GetWidth()
            bmp = self._disabled_close_bmp

            if close_button_state == AUI_BUTTON_STATE_HOVER:
                bmp = self._hover_close_bmp
            elif close_button_state == AUI_BUTTON_STATE_PRESSED:
                bmp = self._pressed_close_bmp

            if agwFlags & AUI_NB_CLOSE_ON_TAB_LEFT:
                rect = wx.Rect(tab_x + 5,
                               drawn_tab_yoff + (drawn_tab_height / 2) - (bmp.GetHeight() / 2) + shift,
                               close_button_width, tab_height)
            else:
                rect = wx.Rect(tab_x + tab_width - close_button_width - 3,
                               drawn_tab_yoff + (drawn_tab_height / 2) - (bmp.GetHeight() / 2) + shift,
                               close_button_width, tab_height)

            # Indent the button if it is pressed down:
            rect = IndentPressedBitmap(rect, close_button_state)
            dc.DrawBitmap(bmp, rect.x, rect.y, True)
            out_button_rect = rect

        out_tab_rect = wx.Rect(tab_x, tab_y, tab_width, tab_height)
        dc.DestroyClippingRegion()

        return out_tab_rect, out_button_rect, x_extent

[docs]    def DrawTabBackground(self, dc, rect, focus, upperTabs):
        """
        Draws the tab background for the Firefox 2 style.
        This is more consistent with L{FlatNotebook} than before.

        :param `dc`: a `wx.DC` device context;
        :param `rect`: rectangle the tab should be confined to;
        :param `focus`: whether the tab has focus or not;
        :param `upperTabs`: whether the style is ``AUI_NB_TOP`` or ``AUI_NB_BOTTOM``.
        """

        # Define the rounded rectangle base on the given rect
        # we need an array of 9 points for it
        regPts = [wx.Point() for indx in xrange(9)]

        if focus:
            if upperTabs:
                leftPt = wx.Point(rect.x, rect.y + (rect.height / 10)*8)
                rightPt = wx.Point(rect.x + rect.width - 2, rect.y + (rect.height / 10)*8)
            else:
                leftPt = wx.Point(rect.x, rect.y + (rect.height / 10)*5)
                rightPt = wx.Point(rect.x + rect.width - 2, rect.y + (rect.height / 10)*5)
        else:
            leftPt = wx.Point(rect.x, rect.y + (rect.height / 2))
            rightPt = wx.Point(rect.x + rect.width - 2, rect.y + (rect.height / 2))

        # Define the top region
        top = wx.RectPP(rect.GetTopLeft(), rightPt)
        bottom = wx.RectPP(leftPt, rect.GetBottomRight())

        topStartColour = wx.WHITE

        if not focus:
            topStartColour = LightColour(wx.SystemSettings_GetColour(wx.SYS_COLOUR_3DFACE), 50)

        topEndColour = wx.SystemSettings_GetColour(wx.SYS_COLOUR_3DFACE)
        bottomStartColour = topEndColour
        bottomEndColour = topEndColour

        # Incase we use bottom tabs, switch the colours
        if upperTabs:
            if focus:
                dc.GradientFillLinear(top, topStartColour, topEndColour, wx.SOUTH)
                dc.GradientFillLinear(bottom, bottomStartColour, bottomEndColour, wx.SOUTH)
            else:
                dc.GradientFillLinear(top, topEndColour , topStartColour, wx.SOUTH)
                dc.GradientFillLinear(bottom, bottomStartColour, bottomEndColour, wx.SOUTH)

        else:
            if focus:
                dc.GradientFillLinear(bottom, topEndColour, bottomEndColour, wx.SOUTH)
                dc.GradientFillLinear(top, topStartColour, topStartColour, wx.SOUTH)
            else:
                dc.GradientFillLinear(bottom, bottomStartColour, bottomEndColour, wx.SOUTH)
                dc.GradientFillLinear(top, topEndColour, topStartColour, wx.SOUTH)

        dc.SetBrush(wx.TRANSPARENT_BRUSH)

[docs]class VC8TabArt(AuiDefaultTabArt):
    """ A class to draw tabs using the Visual Studio 2005 (VC8) style. """

[docs]    def __init__(self):
        """ Default class constructor. """

        AuiDefaultTabArt.__init__(self)

[docs]    def Clone(self):
        """ Clones the art object. """

        art = type(self)()
        art.SetNormalFont(self.GetNormalFont())
        art.SetSelectedFont(self.GetSelectedFont())
        art.SetMeasuringFont(self.GetMeasuringFont())

        art = CopyAttributes(art, self)
        return art

[docs]    def SetSizingInfo(self, tab_ctrl_size, tab_count, minMaxTabWidth):
        """
        Sets the tab sizing information.

        :param `tab_ctrl_size`: the size of the tab control area;
        :param `tab_count`: the number of tabs;
        :param `minMaxTabWidth`: a tuple containing the minimum and maximum tab widths
         to be used when the ``AUI_NB_TAB_FIXED_WIDTH`` style is active.
        """

        AuiDefaultTabArt.SetSizingInfo(self, tab_ctrl_size, tab_count, minMaxTabWidth)

        minTabWidth, maxTabWidth = minMaxTabWidth
        if minTabWidth > -1:
            self._fixed_tab_width = max(self._fixed_tab_width, minTabWidth)
        if maxTabWidth > -1:
            self._fixed_tab_width = min(self._fixed_tab_width, maxTabWidth)

        self._fixed_tab_width -= 5

[docs]    def GetTabSize(self, dc, wnd, caption, bitmap, active, close_button_state, control=None):
        """
        Returns the tab size for the given caption, bitmap and button state.

        :param `dc`: a `wx.DC` device context;
        :param `wnd`: a `wx.Window` instance object;
        :param `caption`: the tab text caption;
        :param `bitmap`: the bitmap displayed on the tab;
        :param `active`: whether the tab is selected or not;
        :param `close_button_state`: the state of the close button on the tab;
        :param `control`: a `wx.Window` instance inside a tab (or ``None``).
        """

        tab_size, x_extent = AuiDefaultTabArt.GetTabSize(self, dc, wnd, caption, bitmap,
                                                         active, close_button_state, control)

        tab_width, tab_height = tab_size

        # add some padding
        tab_width += 10

        if not bitmap.IsOk():
            tab_width += 5

        tab_height += 2

        return (tab_width, tab_height), x_extent

[docs]    def DrawTab(self, dc, wnd, page, in_rect, close_button_state, paint_control=False):
        """
        Draws a single tab.

        :param `dc`: a `wx.DC` device context;
        :param `wnd`: a `wx.Window` instance object;
        :param `page`: the tab control page associated with the tab;
        :param `in_rect`: rectangle the tab should be confined to;
        :param `close_button_state`: the state of the close button on the tab;
        :param `paint_control`: whether to draw the control inside a tab (if any) on a `wx.MemoryDC`.
        """

        # Visual Studio 8 style

        control = page.control

        # figure out the size of the tab
        tab_size, x_extent = self.GetTabSize(dc, wnd, page.caption, page.bitmap,
                                             page.active, close_button_state, control)

        tab_height = self._tab_ctrl_height - 1
        tab_width = tab_size[0]
        tab_x = in_rect.x
        tab_y = in_rect.y + in_rect.height - tab_height

        clip_width = tab_width + 3
        if tab_x + clip_width > in_rect.x + in_rect.width - 4:
            clip_width = (in_rect.x + in_rect.width) - tab_x - 4

        tabPoints = [wx.Point() for i in xrange(8)]

        # If we draw the first tab or the active tab,
        # we draw a full tab, else we draw a truncated tab
        #
        #             X(2)                  X(3)
        #        X(1)                            X(4)
        #
        #                                           X(5)
        #
        # X(0),(7)                                  X(6)
        #
        #

        adjust = 0
        if not page.active:
            adjust = 1

        agwFlags = self.GetAGWFlags()
        tabPoints[0].x = (agwFlags & AUI_NB_BOTTOM and [tab_x] or [tab_x + adjust])[0]
        tabPoints[0].y = (agwFlags & AUI_NB_BOTTOM and [2] or [tab_height - 3])[0]

        tabPoints[1].x = tabPoints[0].x + tab_height - vertical_border_padding - 3 - adjust
        tabPoints[1].y = (agwFlags & AUI_NB_BOTTOM and [tab_height - (vertical_border_padding+2)] or \
                          [(vertical_border_padding+2)])[0]

        tabPoints[2].x = tabPoints[1].x + 4
        tabPoints[2].y = (agwFlags & AUI_NB_BOTTOM and [tab_height - vertical_border_padding] or \
                          [vertical_border_padding])[0]

        tabPoints[3].x = tabPoints[2].x + tab_width - tab_height + vertical_border_padding
        tabPoints[3].y = (agwFlags & AUI_NB_BOTTOM and [tab_height - vertical_border_padding] or \
                          [vertical_border_padding])[0]

        tabPoints[4].x = tabPoints[3].x + 1
        tabPoints[4].y = (agwFlags & AUI_NB_BOTTOM and [tabPoints[3].y - 1] or [tabPoints[3].y + 1])[0]

        tabPoints[5].x = tabPoints[4].x + 1
        tabPoints[5].y = (agwFlags & AUI_NB_BOTTOM and [(tabPoints[4].y - 1)] or [tabPoints[4].y + 1])[0]

        tabPoints[6].x = tabPoints[2].x + tab_width - tab_height + 2 + vertical_border_padding
        tabPoints[6].y = tabPoints[0].y

        tabPoints[7].x = tabPoints[0].x
        tabPoints[7].y = tabPoints[0].y

        self.FillVC8GradientColour(dc, tabPoints, page.active)

        dc.SetBrush(wx.TRANSPARENT_BRUSH)

        dc.SetPen(wx.Pen(wx.SystemSettings.GetColour(wx.SYS_COLOUR_BTNSHADOW)))
        dc.DrawPolygon(tabPoints)

        if page.active:
            # Delete the bottom line (or the upper one, incase we use wxBOTTOM)
            dc.SetPen(wx.WHITE_PEN)
            dc.DrawLine(tabPoints[0].x, tabPoints[0].y, tabPoints[6].x, tabPoints[6].y)

        dc.SetClippingRegion(tab_x, tab_y, clip_width + 2, tab_height - 3)

        drawn_tab_yoff = tabPoints[1].y
        drawn_tab_height = tabPoints[0].y - tabPoints[2].y

        text_offset = tab_x + 20
        close_button_width = 0
        if close_button_state != AUI_BUTTON_STATE_HIDDEN:
            close_button_width = self._active_close_bmp.GetWidth()
            if agwFlags & AUI_NB_CLOSE_ON_TAB_LEFT:
                text_offset += close_button_width

        if not page.enabled:
            dc.SetTextForeground(wx.SystemSettings.GetColour(wx.SYS_COLOUR_GRAYTEXT))
            pagebitmap = page.dis_bitmap
        else:
            dc.SetTextForeground(page.text_colour)
            pagebitmap = page.bitmap

        shift = 0
        if agwFlags & AUI_NB_BOTTOM:
            shift = (page.active and [1] or [2])[0]

        bitmap_offset = 0
        if pagebitmap.IsOk():
            bitmap_offset = tab_x + 20
            if agwFlags & AUI_NB_CLOSE_ON_TAB_LEFT and close_button_width:
                bitmap_offset += close_button_width

            # draw bitmap
            dc.DrawBitmap(pagebitmap, bitmap_offset,
                          drawn_tab_yoff + (drawn_tab_height/2) - (pagebitmap.GetHeight()/2) + shift,
                          True)

            text_offset = bitmap_offset + pagebitmap.GetWidth()
            text_offset += 3 # bitmap padding

        else:
            if agwFlags & AUI_NB_CLOSE_ON_TAB_LEFT == 0 or not close_button_width:
                text_offset = tab_x + tab_height

        # if the caption is empty, measure some temporary text
        caption = page.caption
        if caption == "":
            caption = "Xj"

        if page.active:
            dc.SetFont(self._selected_font)
            textx, texty, dummy = dc.GetMultiLineTextExtent(caption)
        else:
            dc.SetFont(self._normal_font)
            textx, texty, dummy = dc.GetMultiLineTextExtent(caption)

        if agwFlags & AUI_NB_CLOSE_ON_TAB_LEFT:
            draw_text = ChopText(dc, caption, tab_width - (text_offset-tab_x))
        else:
            draw_text = ChopText(dc, caption, tab_width - (text_offset-tab_x) - close_button_width)

        ypos = drawn_tab_yoff + drawn_tab_height/2 - texty/2 - 1 + shift

        offset_focus = text_offset

        if control is not None:
            if control.GetPosition() != wx.Point(text_offset+1, ypos):
                control.SetPosition(wx.Point(text_offset+1, ypos))

            if not control.IsShown():
                control.Show()

            if paint_control:
                bmp = TakeScreenShot(control.GetScreenRect())
                dc.DrawBitmap(bmp, text_offset+1, ypos, True)

            controlW, controlH = control.GetSize()
            text_offset += controlW + 4
            textx += controlW + 4

        # draw tab text
        rectx, recty, dummy = dc.GetMultiLineTextExtent(draw_text)
        dc.DrawLabel(draw_text, wx.Rect(text_offset, ypos, rectx, recty))

        # draw focus rectangle
        if (agwFlags & AUI_NB_NO_TAB_FOCUS) == 0:
            self.DrawFocusRectangle(dc, page, wnd, draw_text, offset_focus, bitmap_offset, drawn_tab_yoff+shift,
                                    drawn_tab_height+shift, rectx, recty)

        out_button_rect = wx.Rect()
        # draw 'x' on tab (if enabled)
        if close_button_state != AUI_BUTTON_STATE_HIDDEN:

            close_button_width = self._active_close_bmp.GetWidth()
            bmp = self._disabled_close_bmp

            if close_button_state == AUI_BUTTON_STATE_HOVER:
                bmp = self._hover_close_bmp
            elif close_button_state == AUI_BUTTON_STATE_PRESSED:
                bmp = self._pressed_close_bmp

            if page.active:
                xpos = tab_x + tab_width - close_button_width + 3
            else:
                xpos = tab_x + tab_width - close_button_width - 5

            if agwFlags & AUI_NB_CLOSE_ON_TAB_LEFT:
                rect = wx.Rect(tab_x + 20,
                               drawn_tab_yoff + (drawn_tab_height / 2) - (bmp.GetHeight() / 2) + shift,
                               close_button_width, tab_height)
            else:
                rect = wx.Rect(xpos,
                               drawn_tab_yoff + (drawn_tab_height / 2) - (bmp.GetHeight() / 2) + shift,
                               close_button_width, tab_height)

            # Indent the button if it is pressed down:
            rect = IndentPressedBitmap(rect, close_button_state)
            dc.DrawBitmap(bmp, rect.x, rect.y, True)
            out_button_rect = rect

        out_tab_rect = wx.Rect(tab_x, tab_y, x_extent, tab_height)
        dc.DestroyClippingRegion()

        return out_tab_rect, out_button_rect, x_extent

[docs]    def FillVC8GradientColour(self, dc, tabPoints, active):
        """
        Fills the tab with the Visual Studio 2005 gradient background.

        :param `dc`: a `wx.DC` device context;
        :param `tabPoints`: a list of `wx.Point` objects describing the tab shape;
        :param `active`: whether the tab is selected or not.
        """

        xList = [pt.x for pt in tabPoints]
        yList = [pt.y for pt in tabPoints]

        minx, maxx = min(xList), max(xList)
        miny, maxy = min(yList), max(yList)

        rect = wx.Rect(minx, maxy, maxx-minx, miny-maxy+1)
        region = wx.RegionFromPoints(tabPoints)

        if self._buttonRect.width > 0:
            buttonRegion = wx.Region(*self._buttonRect)
            region.XorRegion(buttonRegion)

        dc.SetClippingRegionAsRegion(region)

        if active:
            bottom_colour = top_colour = wx.WHITE
        else:
            bottom_colour = StepColour(self._base_colour, 90)
            top_colour = StepColour(self._base_colour, 170)

        dc.GradientFillLinear(rect, top_colour, bottom_colour, wx.SOUTH)
        dc.DestroyClippingRegion()

[docs]class ChromeTabArt(AuiDefaultTabArt):
    """
    A class to draw tabs using the Google Chrome browser style.
    It uses custom bitmap to render the tabs, so that the look and feel is as close
    as possible to the Chrome style.
    """

[docs]    def __init__(self):
        """ Default class constructor. """

        AuiDefaultTabArt.__init__(self)

        self.SetBitmaps(mirror=False)

        closeBmp = tab_close.GetBitmap()
        closeHBmp = tab_close_h.GetBitmap()
        closePBmp = tab_close_p.GetBitmap()

        self.SetCustomButton(AUI_BUTTON_CLOSE, AUI_BUTTON_STATE_NORMAL, closeBmp)
        self.SetCustomButton(AUI_BUTTON_CLOSE, AUI_BUTTON_STATE_HOVER, closeHBmp)
        self.SetCustomButton(AUI_BUTTON_CLOSE, AUI_BUTTON_STATE_PRESSED, closePBmp)

[docs]    def SetAGWFlags(self, agwFlags):
        """
        Sets the tab art flags.

        :param `agwFlags`: a combination of the following values:

         ==================================== ==================================
         Flag name                            Description
         ==================================== ==================================
         ``AUI_NB_TOP``                       With this style, tabs are drawn along the top of the notebook
         ``AUI_NB_LEFT``                      With this style, tabs are drawn along the left of the notebook. Not implemented yet.
         ``AUI_NB_RIGHT``                     With this style, tabs are drawn along the right of the notebook. Not implemented yet.
         ``AUI_NB_BOTTOM``                    With this style, tabs are drawn along the bottom of the notebook
         ``AUI_NB_TAB_SPLIT``                 Allows the tab control to be split by dragging a tab
         ``AUI_NB_TAB_MOVE``                  Allows a tab to be moved horizontally by dragging
         ``AUI_NB_TAB_EXTERNAL_MOVE``         Allows a tab to be moved to another tab control
         ``AUI_NB_TAB_FIXED_WIDTH``           With this style, all tabs have the same width
         ``AUI_NB_SCROLL_BUTTONS``            With this style, left and right scroll buttons are displayed
         ``AUI_NB_WINDOWLIST_BUTTON``         With this style, a drop-down list of windows is available
         ``AUI_NB_CLOSE_BUTTON``              With this style, a close button is available on the tab bar
         ``AUI_NB_CLOSE_ON_ACTIVE_TAB``       With this style, a close button is available on the active tab
         ``AUI_NB_CLOSE_ON_ALL_TABS``         With this style, a close button is available on all tabs
         ``AUI_NB_MIDDLE_CLICK_CLOSE``        Allows to close L{AuiNotebook} tabs by mouse middle button click
         ``AUI_NB_SUB_NOTEBOOK``              This style is used by L{AuiManager} to create automatic AuiNotebooks
         ``AUI_NB_HIDE_ON_SINGLE_TAB``        Hides the tab window if only one tab is present
         ``AUI_NB_SMART_TABS``                Use Smart Tabbing, like ``Alt`` + ``Tab`` on Windows
         ``AUI_NB_USE_IMAGES_DROPDOWN``       Uses images on dropdown window list menu instead of check items
         ``AUI_NB_CLOSE_ON_TAB_LEFT``         Draws the tab close button on the left instead of on the right (a la Camino browser)
         ``AUI_NB_TAB_FLOAT``                 Allows the floating of single tabs. Known limitation: when the notebook is more or less full screen, tabs cannot be dragged far enough outside of the notebook to become floating pages
         ``AUI_NB_DRAW_DND_TAB``              Draws an image representation of a tab while dragging (on by default)
         ``AUI_NB_ORDER_BY_ACCESS``           Tab navigation order by last access time for the tabs
         ``AUI_NB_NO_TAB_FOCUS``              Don't draw tab focus rectangle
         ==================================== ==================================

        :note: Overridden from L{AuiDefaultTabArt}.
        """

        if agwFlags & AUI_NB_TOP:
            self.SetBitmaps(mirror=False)
        elif agwFlags & AUI_NB_BOTTOM:
            self.SetBitmaps(mirror=True)

        AuiDefaultTabArt.SetAGWFlags(self, agwFlags)

[docs]    def SetBitmaps(self, mirror):
        """
        Assigns the tab custom bitmaps

        :param `mirror`: whether to vertically mirror the bitmap or not.
        """

        bmps = [tab_active_left.GetBitmap(), tab_active_center.GetBitmap(),
                tab_active_right.GetBitmap(), tab_inactive_left.GetBitmap(),
                tab_inactive_center.GetBitmap(), tab_inactive_right.GetBitmap()]

        if mirror:
            for indx, bmp in enumerate(bmps):
                img = bmp.ConvertToImage()
                img = img.Mirror(horizontally=False)
                bmps[indx] = img.ConvertToBitmap()

        self._leftActiveBmp = bmps[0]
        self._centerActiveBmp = bmps[1]
        self._rightActiveBmp = bmps[2]
        self._leftInactiveBmp = bmps[3]
        self._centerInactiveBmp = bmps[4]
        self._rightInactiveBmp = bmps[5]

[docs]    def Clone(self):
        """ Clones the art object. """

        art = type(self)()
        art.SetNormalFont(self.GetNormalFont())
        art.SetSelectedFont(self.GetSelectedFont())
        art.SetMeasuringFont(self.GetMeasuringFont())

        art = CopyAttributes(art, self)
        return art

[docs]    def SetSizingInfo(self, tab_ctrl_size, tab_count, minMaxTabWidth):
        """
        Sets the tab sizing information.

        :param `tab_ctrl_size`: the size of the tab control area;
        :param `tab_count`: the number of tabs;
        :param `minMaxTabWidth`: a tuple containing the minimum and maximum tab widths
         to be used when the ``AUI_NB_TAB_FIXED_WIDTH`` style is active.
        """

        AuiDefaultTabArt.SetSizingInfo(self, tab_ctrl_size, tab_count, minMaxTabWidth)

        minTabWidth, maxTabWidth = minMaxTabWidth
        if minTabWidth > -1:
            self._fixed_tab_width = max(self._fixed_tab_width, minTabWidth)
        if maxTabWidth > -1:
            self._fixed_tab_width = min(self._fixed_tab_width, maxTabWidth)

        self._fixed_tab_width -= 5

[docs]    def GetTabSize(self, dc, wnd, caption, bitmap, active, close_button_state, control=None):
        """
        Returns the tab size for the given caption, bitmap and button state.

        :param `dc`: a `wx.DC` device context;
        :param `wnd`: a `wx.Window` instance object;
        :param `caption`: the tab text caption;
        :param `bitmap`: the bitmap displayed on the tab;
        :param `active`: whether the tab is selected or not;
        :param `close_button_state`: the state of the close button on the tab;
        :param `control`: a `wx.Window` instance inside a tab (or ``None``).
        """

        tab_size, x_extent = AuiDefaultTabArt.GetTabSize(self, dc, wnd, caption, bitmap,
                                                         active, close_button_state, control)

        tab_width, tab_height = tab_size

        # add some padding
        tab_width += self._leftActiveBmp.GetWidth()
        tab_height += 2

        tab_height = max(tab_height, self._centerActiveBmp.GetHeight())

        return (tab_width, tab_height), x_extent

[docs]    def DrawTab(self, dc, wnd, page, in_rect, close_button_state, paint_control=False):
        """
        Draws a single tab.

        :param `dc`: a `wx.DC` device context;
        :param `wnd`: a `wx.Window` instance object;
        :param `page`: the tab control page associated with the tab;
        :param `in_rect`: rectangle the tab should be confined to;
        :param `close_button_state`: the state of the close button on the tab;
        :param `paint_control`: whether to draw the control inside a tab (if any) on a `wx.MemoryDC`.
        """

        # Chrome tab style

        control = page.control
        # figure out the size of the tab
        tab_size, x_extent = self.GetTabSize(dc, wnd, page.caption, page.bitmap, page.active,
                                             close_button_state, control)

        agwFlags = self.GetAGWFlags()

        tab_height = self._tab_ctrl_height - 1
        tab_width = tab_size[0]
        tab_x = in_rect.x
        tab_y = in_rect.y + in_rect.height - tab_height
        clip_width = tab_width

        if tab_x + clip_width > in_rect.x + in_rect.width - 4:
            clip_width = (in_rect.x + in_rect.width) - tab_x - 4

        dc.SetClippingRegion(tab_x, tab_y, clip_width + 1, tab_height - 3)
        drawn_tab_yoff = 1

        if page.active:
            left = self._leftActiveBmp
            center = self._centerActiveBmp
            right = self._rightActiveBmp
        else:
            left = self._leftInactiveBmp
            center = self._centerInactiveBmp
            right = self._rightInactiveBmp

        dc.DrawBitmap(left, tab_x, tab_y)
        leftw = left.GetWidth()
        centerw = center.GetWidth()
        rightw = right.GetWidth()

        available = tab_x + tab_width - rightw
        posx = tab_x + leftw

        while 1:
            if posx >= available:
                break
            dc.DrawBitmap(center, posx, tab_y)
            posx += centerw

        dc.DrawBitmap(right, posx, tab_y)

        drawn_tab_height = center.GetHeight()
        text_offset = tab_x + leftw

        close_button_width = 0
        if close_button_state != AUI_BUTTON_STATE_HIDDEN:
            close_button_width = self._active_close_bmp.GetWidth()
            if agwFlags & AUI_NB_CLOSE_ON_TAB_LEFT:
                text_offset += close_button_width

        if not page.enabled:
            dc.SetTextForeground(wx.SystemSettings.GetColour(wx.SYS_COLOUR_GRAYTEXT))
            pagebitmap = page.dis_bitmap
        else:
            dc.SetTextForeground(page.text_colour)
            pagebitmap = page.bitmap

        bitmap_offset = 0
        if pagebitmap.IsOk():
            bitmap_offset = tab_x + leftw
            if agwFlags & AUI_NB_CLOSE_ON_TAB_LEFT and close_button_width:
                bitmap_offset += close_button_width

            # draw bitmap
            dc.DrawBitmap(pagebitmap, bitmap_offset,
                          drawn_tab_yoff + (drawn_tab_height/2) - (pagebitmap.GetHeight()/2),
                          True)

            text_offset = bitmap_offset + pagebitmap.GetWidth()
            text_offset += 3 # bitmap padding

        else:

            if agwFlags & AUI_NB_CLOSE_ON_TAB_LEFT == 0 or not close_button_width:
                text_offset = tab_x + leftw

        # if the caption is empty, measure some temporary text
        caption = page.caption
        if caption == "":
            caption = "Xj"

        if page.active:
            dc.SetFont(self._selected_font)
            textx, texty, dummy = dc.GetMultiLineTextExtent(caption)
        else:
            dc.SetFont(self._normal_font)
            textx, texty, dummy = dc.GetMultiLineTextExtent(caption)

        if agwFlags & AUI_NB_CLOSE_ON_TAB_LEFT:
            draw_text = ChopText(dc, caption, tab_width - (text_offset-tab_x) - leftw)
        else:
            draw_text = ChopText(dc, caption, tab_width - (text_offset-tab_x) - close_button_width - leftw)

        ypos = drawn_tab_yoff + drawn_tab_height/2 - texty/2 - 1

        if control is not None:
            if control.GetPosition() != wx.Point(text_offset+1, ypos):
                control.SetPosition(wx.Point(text_offset+1, ypos))

            if not control.IsShown():
                control.Show()

            if paint_control:
                bmp = TakeScreenShot(control.GetScreenRect())
                dc.DrawBitmap(bmp, text_offset+1, ypos, True)

            controlW, controlH = control.GetSize()
            text_offset += controlW + 4

        # draw tab text
        rectx, recty, dummy = dc.GetMultiLineTextExtent(draw_text)
        dc.DrawLabel(draw_text, wx.Rect(text_offset, ypos, rectx, recty))

        out_button_rect = wx.Rect()
        # draw 'x' on tab (if enabled)
        if close_button_state != AUI_BUTTON_STATE_HIDDEN:

            close_button_width = self._active_close_bmp.GetWidth()
            bmp = self._disabled_close_bmp

            if close_button_state == AUI_BUTTON_STATE_HOVER:
                bmp = self._hover_close_bmp
            elif close_button_state == AUI_BUTTON_STATE_PRESSED:
                bmp = self._pressed_close_bmp

            if agwFlags & AUI_NB_CLOSE_ON_TAB_LEFT:
                rect = wx.Rect(tab_x + leftw - 2,
                               drawn_tab_yoff + (drawn_tab_height / 2) - (bmp.GetHeight() / 2) + 1,
                               close_button_width, tab_height)
            else:
                rect = wx.Rect(tab_x + tab_width - close_button_width - rightw + 2,
                               drawn_tab_yoff + (drawn_tab_height / 2) - (bmp.GetHeight() / 2) + 1,
                               close_button_width, tab_height)

            if agwFlags & AUI_NB_BOTTOM:
                rect.y -= 1

            # Indent the button if it is pressed down:
            rect = IndentPressedBitmap(rect, close_button_state)
            dc.DrawBitmap(bmp, rect.x, rect.y, True)
            out_button_rect = rect

        out_tab_rect = wx.Rect(tab_x, tab_y, tab_width, tab_height)
        dc.DestroyClippingRegion()

        return out_tab_rect, out_button_rect, x_extent

Navigation

  • index
  • modules |
  • Home |
  • Gallery |
  • Contents»
  • Module code »
  • aui.tabart


persist.persist_handlers

  • modules |
  • Home |
  • Gallery |
  • Contents»
  • Module code »
  • persist.persist_handlers

Source code for persist.persist_handlers

# -*- coding: utf-8 -*-#
#!/usr/bin/env python
"""
This module contains different classes which handle different kind of saving/restoring
actions depending on the widget kind.
"""

import wx
import types
import datetime

import wx.aui
import wx.combo
import wx.calendar as calendar
import wx.gizmos
import wx.media

import wx.lib.scrolledpanel as scrolled
import wx.lib.expando as expando
import wx.lib.buttons as buttons
import wx.lib.masked as masked
import wx.lib.colourselect as csel

import wx.lib.agw.aui as AUI
import wx.lib.agw.cubecolourdialog as CCD
import wx.lib.agw.customtreectrl as CT
import wx.lib.agw.flatmenu as FM
import wx.lib.agw.flatnotebook as FNB
import wx.lib.agw.floatspin as FS
import wx.lib.agw.foldpanelbar as FPB
import wx.lib.agw.hypertreelist as HTL
import wx.lib.agw.knobctrl as KC
import wx.lib.agw.labelbook as LBK

try:
    import wx.lib.agw.shapedbutton as SB
    hasSB = True
except:
    hasSB = False
    pass

import wx.lib.agw.ultimatelistctrl as ULC

import persistencemanager as PM

from persist_constants import *

[docs]def PyDate2wxDate(date):
    """
    Transforms a datetime.date object into a `wx.DateTime` one.

    :param `date`: a `datetime.date` object.
    """

    tt = date.timetuple()
    dmy = (tt[2], tt[1]-1, tt[0])
    return wx.DateTimeFromDMY(*dmy)

[docs]def wxDate2PyDate(date):
    """
    Transforms a `wx.DateTime` object into a `datetime.date` one.

    :param date: a `wx.DateTime` object.
    """

    if date.IsValid():
        ymd = map(int, date.FormatISODate().split('-'))
        return datetime.date(*ymd)
    else:
        return None

[docs]def CreateFont(font):
    """
    Creates a tuple of 7 `wx.Font` attributes from the `font` input parameter.

    :param `font`: a `wx.Font` instance.

    :returns: A tuple of 7 `wx.Font` attributes from the `font` input parameter.
    """

    return font.GetPointSize(), font.GetFamily(), font.GetStyle(), font.GetWeight(), \
           font.GetUnderlined(), font.GetFaceName(), font.GetEncoding()

# ----------------------------------------------------------------------------------- #

[docs]class AbstractHandler(object):
    """
    Base class for persistent windows, uses the window name as persistent name by
    default and automatically reacts to the window destruction.

    :note: This is an abstract class. If you wish to add another (custom) handler
           for your widgets, you should derive from L{AbstractHandler} and override
           the L{AbstractHandler.Save}, L{AbstractHandler.Restore} and L{AbstractHandler.GetKind}
           methods.
    """

[docs]    def __init__(self, pObject):
        """
        Default class constructor.

        :param `pObject`: a L{PersistentObject} containing information about the
         persistent widget.
        """

        object.__init__(self)
        self._pObject = pObject
        self._window = pObject.GetWindow()

[docs]    def Save(self):
        """
        Saves the widget's settings by calling L{PersistentObject.SaveValue}, which in
        turns calls L{PersistenceManager.SaveValue}.

        :note: This method must be overridden in derived classes.
        """

        pass

[docs]    def Restore(self):
        """
        Restores the widget's settings by calling L{PersistentObject.RestoreValue}, which in
        turns calls L{PersistenceManager.RestoreValue}.

        :note: This method must be overridden in derived classes.
        """

        pass

[docs]    def GetKind(self):
        """
        Returns a short and meaningful *string* description of your widget.

        :note: This method must be overridden in derived classes.
        """

        pass

# ----------------------------------------------------------------------------------- #

[docs]class BookHandler(AbstractHandler):
    """
    Supports saving/restoring book control selection.

    This class handles the following wxPython widgets:

    - `wx.Toolbook`;
    - `wx.Choicebook`;
    - `wx.Listbook`;
    - `wx.Treebook` (except for opened tree branches, see L{TreebookHandler} for this);
    - `wx.Notebook`;
    - `wx.aui.AuiNotebook`;
    - L{auibook.AuiNotebook};
    - L{flatnotebook.FlatNotebook};
    - L{labelbook.LabelBook};
    - L{labelbook.FlatImageBook}.

    """

[docs]    def __init__(self, pObject):

        AbstractHandler.__init__(self, pObject)

    def Save(self):

        book, obj = self._window, self._pObject
        obj.SaveValue(PERSIST_BOOK_SELECTION, book.GetSelection())

        if issubclass(book.__class__, AUI.AuiNotebook):
            manager = PM.PersistenceManager.Get()
            if manager.GetManagerStyle() & PM_SAVE_RESTORE_AUI_PERSPECTIVES:
                # Allowed to save and restore perspectives
                perspective = book.SavePerspective()
                obj.SaveValue(PERSIST_BOOK_AGW_AUI_PERSPECTIVE, perspective)

    def Restore(self):

        book, obj = self._window, self._pObject
        sel = obj.RestoreValue(PERSIST_BOOK_SELECTION)

        retVal = True
        if issubclass(book.__class__, AUI.AuiNotebook):
            manager = PM.PersistenceManager.Get()
            if manager.GetManagerStyle() & PM_SAVE_RESTORE_AUI_PERSPECTIVES:
                retVal = False
                # Allowed to save and restore perspectives
                perspective = obj.RestoreValue(PERSIST_BOOK_AGW_AUI_PERSPECTIVE)
                if perspective is not None:
                    retVal = book.LoadPerspective(perspective)
                    wx.CallAfter(book.Refresh)

        if sel is not None:
            if sel >= 0 and sel < book.GetPageCount():
                book.SetSelection(sel)
                return True and retVal

        return False

    def GetKind(self):

        return PERSIST_BOOK_KIND

# ----------------------------------------------------------------------------------- #

[docs]class TreebookHandler(BookHandler):
    """
    Supports saving/restoring open tree branches.

    This class handles the following wxPython widgets:

    - `wx.Treebook` (except for page selection, see L{BookHandler} for this).

    """

[docs]    def __init__(self, pObject):

        BookHandler.__init__(self, pObject)

    def Save(self):

        book, obj = self._window, self._pObject

        expanded = ""
        for page in xrange(book.GetPageCount()):
            if book.IsNodeExpanded(page):
                if expanded:
                    expanded += PERSIST_SEP

                expanded += "%u"%page

        obj.SaveValue(PERSIST_TREEBOOK_EXPANDED_BRANCHES, expanded)

        return BookHandler.Save(self)

    def Restore(self):

        book, obj = self._window, self._pObject

        expanded = obj.RestoreValue(PERSIST_TREEBOOK_EXPANDED_BRANCHES)

        if expanded:
            indices = expanded.split(PERSIST_SEP)
            pageCount = book.GetPageCount()

            for indx in indices:
                idx = int(indx)
                if idx >= 0 and idx < pageCount:
                    book.ExpandNode(idx)

        return BookHandler.Restore(self)

    def GetKind(self):

        return PERSIST_TREEBOOK_KIND

# ----------------------------------------------------------------------------------- #

[docs]class AUIHandler(AbstractHandler):
    """
    Supports saving/restoring `wx.aui.AuiManager` and L{framemanager.AuiManager}
    perspectives.
    """

[docs]    def __init__(self, pObject):

        AbstractHandler.__init__(self, pObject)

    def Save(self):

        # Save the AUI perspectives if PersistenceManager allows it
        eventHandler = self._window.GetEventHandler()

        isAGWAui = isinstance(eventHandler, AUI.AuiManager)
        isAui = isinstance(eventHandler, wx.aui.AuiManager)
        if not isAui and not isAGWAui:
            return True

        manager = PM.PersistenceManager.Get()
        if manager.GetManagerStyle() & PM_SAVE_RESTORE_AUI_PERSPECTIVES:
            # Allowed to save and restore perspectives
            perspective = eventHandler.SavePerspective()
            if isAGWAui:
                name = PERSIST_AGW_AUI_PERSPECTIVE
            else:
                name = PERSIST_AUI_PERSPECTIVE

            self._pObject.SaveValue(name, perspective)

        return True

    def Restore(self):

        # Restore the AUI perspectives if PersistenceManager allows it
        eventHandler = self._window.GetEventHandler()

        isAGWAui = isinstance(eventHandler, AUI.AuiManager)
        isAui = isinstance(eventHandler, wx.aui.AuiManager)
        if not isAui and not isAGWAui:
            return True

        manager = PM.PersistenceManager.Get()
        if manager.GetManagerStyle() & PM_SAVE_RESTORE_AUI_PERSPECTIVES:
            # Allowed to save and restore perspectives
            if isAGWAui:
                name = PERSIST_AGW_AUI_PERSPECTIVE
            else:
                name = PERSIST_AUI_PERSPECTIVE

            perspective = self._pObject.RestoreValue(name)
            if perspective is not None:
                eventHandler.LoadPerspective(perspective)
                return False

        return True

    def GetKind(self):

        return PERSIST_AUIPERSPECTIVE_KIND

# ----------------------------------------------------------------------------------- #

[docs]class TLWHandler(AUIHandler):
    """
    Supports saving/restoring window position and size as well as
    maximized/iconized/restore state for toplevel windows.

    This class handles the following wxPython widgets:

    - All `wx.Frame` derived classes;
    - All `wx.Dialog` derived classes.

    |

    In addition, if the toplevel window has an associated AuiManager (whether it is
    `wx.aui.AuiManager` or L{framemanager.AuiManager} and L{PersistenceManager}
    has the ``PM_SAVE_RESTORE_AUI_PERSPECTIVES`` style set (the default), this class
    will also save and restore AUI perspectives using the underlying L{AUIHandler}
    class.

    """

[docs]    def __init__(self, pObject):

        AUIHandler.__init__(self, pObject)

    def Save(self):

        tlw, obj = self._window, self._pObject

        pos = tlw.GetScreenPosition()
        obj.SaveValue(PERSIST_TLW_X, pos.x)
        obj.SaveValue(PERSIST_TLW_Y, pos.y)

        # Notice that we use GetSize() here and not GetClientSize() because
        # the latter doesn't return correct results for the minimized windows
        # (at least not under Windows)
        #
        # Of course, it shouldn't matter anyhow usually, the client size
        # should be preserved as well unless the size of the decorations
        # changed between the runs
        size = tlw.GetSize()
        obj.SaveValue(PERSIST_TLW_W, size.x)
        obj.SaveValue(PERSIST_TLW_H, size.y)

        obj.SaveValue(PERSIST_TLW_MAXIMIZED, tlw.IsMaximized())
        obj.SaveValue(PERSIST_TLW_ICONIZED, tlw.IsIconized())

        return AUIHandler.Save(self)

    def Restore(self):

        tlw, obj = self._window, self._pObject

        x, y = obj.RestoreValue(PERSIST_TLW_X), obj.RestoreValue(PERSIST_TLW_Y)
        w, h = obj.RestoreValue(PERSIST_TLW_W), obj.RestoreValue(PERSIST_TLW_H)

        hasPos = x is not None and y is not None
        hasSize = w is not None and h is not None

        if hasPos:
            # To avoid making the window completely invisible if it had been
            # shown on a monitor which was disconnected since the last run
            # (this is pretty common for notebook with external displays)
            #
            # NB: we should allow window position to be (slightly) off screen,
            #     it's not uncommon to position the window so that its upper
            #     left corner has slightly negative coordinate
            if wx.Display.GetFromPoint(wx.Point(x, y)) != wx.NOT_FOUND or \
               (hasSize and wx.Display.GetFromPoint(wx.Point(x+w, y+h)) != wx.NOT_FOUND):
                tlw.Move(wx.Point(x, y), wx.SIZE_ALLOW_MINUS_ONE)

            # else: should we try to adjust position/size somehow?

        if hasSize:
            tlw.SetSize((w, h))

        # Note that the window can be both maximized and iconized
        maximized = obj.RestoreValue(PERSIST_TLW_MAXIMIZED)
        if maximized:
            tlw.Maximize()

        iconized = obj.RestoreValue(PERSIST_TLW_ICONIZED)
        if iconized:
            tlw.Iconize()

        # The most important property of the window that we restore is its
        # size, so disregard the value of hasPos here
        return (hasSize and AUIHandler.Restore(self))

    def GetKind(self):

        return PERSIST_TLW_KIND

# ----------------------------------------------------------------------------------- #

[docs]class CheckBoxHandler(AbstractHandler):
    """
    Supports saving/restoring a `wx.CheckBox` state.

    This class handles the following wxPython widgets:

    - `wx.CheckBox`.

    """

[docs]    def __init__(self, pObject):

        AbstractHandler.__init__(self, pObject)

    def Save(self):

        check, obj = self._window, self._pObject

        if check.Is3State():
            obj.SaveCtrlValue(PERSIST_CHECKBOX_3STATE, check.Get3StateValue())
        else:
            obj.SaveCtrlValue(PERSIST_CHECKBOX, check.GetValue())

        return True

    def Restore(self):

        check, obj = self._window, self._pObject

        if check.Is3State():
            value = obj.RestoreCtrlValue(PERSIST_CHECKBOX_3STATE)
            if value is not None:
                check.Set3StateValue(value)
                return True
        else:
            value = obj.RestoreCtrlValue(PERSIST_CHECKBOX)
            if value is not None:
                check.SetValue(value)
                return True

        return False

    def GetKind(self):

        return PERSIST_CHECKBOX_KIND

# ----------------------------------------------------------------------------------- #

[docs]class ListBoxHandler(AbstractHandler):
    """
    Supports saving/restoring selected items in `wx.ListBox`, `wx.ListCtrl`, `wx.ListView`,
    `wx.VListBox`, `wx.HtmlListBox`, `wx.SimpleHtmlListBox`, `wx.gizmos.EditableListBox`.

    This class handles the following wxPython widgets:

    - `wx.ListBox`;
    - `wx.ListCtrl` (only for selected items. For column sizes see L{ListCtrlHandler});
    - `wx.ListView` (only for selected items. For column sizes see L{ListCtrlHandler});
    - `wx.VListBox`;
    - `wx.HtmlListBox`;
    - `wx.SimpleHtmlListBox`;
    - `wx.gizmos.EditableListBox`.

    """

[docs]    def __init__(self, pObject):

        AbstractHandler.__init__(self, pObject)

[docs]    def GetSelections(self, listBox):
        """
        Returns a list of selected items for `wx.ListBox`, `wx.ListCtrl`, `wx.ListView`,
        `wx.VListBox`, `wx.HtmlListBox`, `wx.SimpleHtmlListBox`, `wx.gizmos.EditableListBox`.

        :param `listBox`: an instance of `wx.ListBox`, `wx.ListCtrl`, `wx.ListView`,
         `wx.VListBox`, `wx.HtmlListBox`, `wx.SimpleHtmlListBox`, `wx.gizmos.EditableListBox`..
        """

        indices = []
        if isinstance(listBox, (wx.HtmlListBox, wx.SimpleHtmlListBox)):
            if listBox.GetSelectedCount() == 0:
                return indices
        else:
            if listBox.GetSelectedItemCount() == 0:
                return indices

        isVirtual = issubclass(listBox.__class__, wx.VListBox)

        if isVirtual:
            # This includes wx.SimpleHtmlListBox and wx.HtmlListBox
            if listBox.GetWindowStyleFlag() & wx.LB_SINGLE:
                selection = listBox.GetSelection()
                return (selection >= 0 and [selection] or [indices])[0]
        else:
            # wx.ListCtrl
            if listBox.GetWindowStyleFlag() & wx.LC_SINGLE_SEL:
                selection = listBox.GetSelection()
                return (selection >= 0 and [selection] or [indices])[0]

        if isVirtual:
            item, cookie = listBox.GetFirstSelected()
            while item != wx.NOT_FOUND:
                indices.append(item)
                item, cookie = listBox.GetNextSelected(cookie)

            return indices

        lastFound = -1
        # Loop until told to stop
        while 1:
            index = listBox.GetNextItem(lastFound, wx.LIST_NEXT_ALL, wx.LIST_STATE_SELECTED)
            if index == wx.NOT_FOUND:
                # No item selected
                break
            else:
                # Found one item, append to the list of condemned
                lastFound = index
                indices.append(index)

        return indices

    def Save(self):

        manager = PM.PersistenceManager.Get()
        if manager.GetManagerStyle() & PM_SAVE_RESTORE_TREE_LIST_SELECTIONS == 0:
            # We don't want to save selected items
            return True

        listBox, obj = self._window, self._pObject

        if issubclass(listBox.__class__, wx.ListBox):
            selections = listBox.GetSelections()
        else:
            selections = self.GetSelections(listBox)

        obj.SaveValue(PERSIST_LISTBOX_SELECTIONS, selections)
        return True

    def Restore(self):

        manager = PM.PersistenceManager.Get()
        if manager.GetManagerStyle() & PM_SAVE_RESTORE_TREE_LIST_SELECTIONS == 0:
            # We don't want to save selected items
            return True

        listBox, obj = self._window, self._pObject

        isVirtual = issubclass(listBox.__class__, wx.VListBox) or isinstance(listBox, wx.CheckListBox)
        isHtml = isinstance(listBox, wx.HtmlListBox)
        if isVirtual and not isHtml:
            count = listBox.GetCount()
        else:
            count = listBox.GetItemCount()

        selections = obj.RestoreValue(PERSIST_LISTBOX_SELECTIONS)

        if selections is not None:
            for index in selections:
                if index < count:
                    listBox.Select(index)

            return True

        return False

    def GetKind(self):

        return PERSIST_LISTBOX_KIND

# ----------------------------------------------------------------------------------- #

[docs]class ListCtrlHandler(ListBoxHandler):
    """
    Supports saving/restoring selected items and column sizes in `wx.ListCtrl`.

    This class handles the following wxPython widgets:

    - `wx.ListCtrl` (only for column sizes. For selected items see L{ListBoxHandler});
    - `wx.ListView` (only for column sizes. For selected items see L{ListBoxHandler}).
    """

[docs]    def __init__(self, pObject):

        ListBoxHandler.__init__(self, pObject)

    def Save(self):

        listCtrl, obj = self._window, self._pObject

        retVal = ListBoxHandler.Save(self)

        if not listCtrl.InReportView():
            return retVal

        colSizes = []
        for col in xrange(listCtrl.GetColumnCount()):
            colSizes.append(listCtrl.GetColumnWidth(col))

        obj.SaveValue(PERSIST_LISTCTRL_COLWIDTHS, colSizes)

        return retVal

    def Restore(self):

        listCtrl, obj = self._window, self._pObject

        retVal = ListBoxHandler.Restore(self)

        if not listCtrl.InReportView():
            return retVal

        colSizes = obj.RestoreValue(PERSIST_LISTCTRL_COLWIDTHS)
        if colSizes is None:
            return False

        count = listCtrl.GetColumnCount()
        for col, size in enumerate(colSizes):
            if col < count:
                listCtrl.SetColumnWidth(col, size)

        return retVal

    def GetKind(self):

        return PERSIST_LISTCTRL_KIND

# ----------------------------------------------------------------------------------- #

[docs]class CheckListBoxHandler(ListBoxHandler):
    """
    Supports saving/restoring checked and selected items in `wx.CheckListBox`.

    This class handles the following wxPython widgets:

    - `wx.CheckListBox` (only for checked items. For selected items see L{ListBoxHandler}).

    """

[docs]    def __init__(self, pObject):

        ListBoxHandler.__init__(self, pObject)

    def Save(self):

        checkList, obj = self._window, self._pObject

        checked = []
        for index in xrange(checkList.GetCount()):
            if checkList.IsChecked(index):
                checked.append(index)

        obj.SaveValue(PERSIST_CHECKLIST_CHECKED, checked)

        return ListBoxHandler.Save(self)

    def Restore(self):

        checkList, obj = self._window, self._pObject

        checked = obj.RestoreValue(PERSIST_CHECKLIST_CHECKED)
        count = checkList.GetCount()
        if checked is not None:
            for index in checked:
                if index < count:
                    checkList.Check(index)

        return ListBoxHandler.Restore(self)

    def GetKind(self):

        return PERSIST_CHECKLISTBOX_KIND

# ----------------------------------------------------------------------------------- #

[docs]class ChoiceComboHandler(AbstractHandler):
    """
    Supports saving/restoring `wx.Choice`, `wx.ComboBox` and `wx.combo.OwnerDrawnComboBox`
    selection.

    This class handles the following wxPython widgets:

    - `wx.Choice`;
    - `wx.ComboBox`;
    - `wx.combo.OwnerDrawnComboBox`.

    """

[docs]    def __init__(self, pObject):

        AbstractHandler.__init__(self, pObject)

    def Save(self):

        combo, obj = self._window, self._pObject

        value = combo.GetStringSelection()
        obj.SaveCtrlValue(PERSIST_CHOICECOMBO_SELECTION, value)
        return True

    def Restore(self):

        combo, obj = self._window, self._pObject

        value = obj.RestoreCtrlValue(PERSIST_CHOICECOMBO_SELECTION)
        if value is not None:
            if value in combo.GetStrings():
                combo.SetStringSelection(value)

            return True

        return False

    def GetKind(self):

        return PERSIST_CHOICECOMBO_KIND

# ----------------------------------------------------------------------------------- #

[docs]class FoldPanelBarHandler(AbstractHandler):
    """
    Supports saving/restoring of L{foldpanelbar.FoldPanelBar}.

    This class handles the following wxPython widgets

    - L{foldpanelbar.FoldPanelBar
    """

[docs]    def __init__(self, pObject):

        AbstractHandler.__init__(self, pObject)

    def Save(self):

        fpb, obj = self._window, self._pObject
        expanded = [fpb.GetFoldPanel(i).IsExpanded() for i in xrange(fpb.GetCount())]
        obj.SaveValue(PERSIST_FOLDPANELBAR_EXPANDED, expanded)

        return True

    def Restore(self):

        fpb, obj = self._window, self._pObject
        expanded = obj.RestoreValue(PERSIST_FOLDPANELBAR_EXPANDED)

        if expanded is None:
            return False
        else:
            for idx, expand in enumerate(expanded):
                panel = fpb.GetFoldPanel(idx)
                if expand:
                    fpb.Expand(panel)
                else:
                    fpb.Collapse(panel)

            return True

    def GetKind(self):

        return PERSIST_FOLDPANELBAR_KIND

# ----------------------------------------------------------------------------------- #

[docs]class RadioBoxHandler(AbstractHandler):
    """
    Supports saving/restoring a `wx.RadioBox` state.

    This class handles the following wxPython widgets:

    - `wx.RadioBox`.

    """

[docs]    def __init__(self, pObject):

        AbstractHandler.__init__(self, pObject)

    def Save(self):

        radio, obj = self._window, self._pObject
        obj.SaveCtrlValue(PERSIST_RADIOBOX_SELECTION, radio.GetSelection())
        return True

    def Restore(self):

        radio, obj = self._window, self._pObject
        value = obj.RestoreCtrlValue(PERSIST_RADIOBOX_SELECTION)
        if value is not None:
            if value < radio.GetCount():
                radio.SetSelection(value)
                return True

        return False

    def GetKind(self):

        return PERSIST_RADIOBOX_KIND

# ----------------------------------------------------------------------------------- #

[docs]class RadioButtonHandler(AbstractHandler):
    """
    Supports saving/restoring a `wx.RadioButton` state.

    This class handles the following wxPython widgets:

    - `wx.RadioButton`.

    """

[docs]    def __init__(self, pObject):

        AbstractHandler.__init__(self, pObject)

    def Save(self):

        radio, obj = self._window, self._pObject
        obj.SaveCtrlValue(PERSIST_RADIOBUTTON_VALUE, radio.GetValue())
        return True

    def Restore(self):

        radio, obj = self._window, self._pObject
        value = obj.RestoreCtrlValue(PERSIST_RADIOBUTTON_VALUE)
        if value is not None:
            radio.SetValue(value)
            return True

        return False

    def GetKind(self):

        return PERSIST_RADIOBUTTON_KIND

# ----------------------------------------------------------------------------------- #

[docs]class ScrolledWindowHandler(AbstractHandler):
    """
    Supports saving/restoring a `wx.ScrolledWindow` / `wx.lib.scrolledpanel.ScrolledPanel`
    scroll position.

    This class handles the following wxPython widgets:

    - `wx.ScrolledWindow`;
    - `wx.lib.scrolledpanel.ScrolledPanel`.

    """

[docs]    def __init__(self, pObject):

        AbstractHandler.__init__(self, pObject)

    def Save(self):

        scroll, obj = self._window, self._pObject

        scrollPos = scroll.GetScrollPos(wx.HORIZONTAL)
        obj.SaveValue(PERSIST_SCROLLEDWINDOW_POS_H, scrollPos)
        scrollPos = scroll.GetScrollPos(wx.VERTICAL)
        obj.SaveValue(PERSIST_SCROLLEDWINDOW_POS_V, scrollPos)
        return True

    def Restore(self):

        scroll, obj = self._window, self._pObject
        hpos = obj.RestoreValue(PERSIST_SCROLLEDWINDOW_POS_H)
        vpos = obj.RestoreValue(PERSIST_SCROLLEDWINDOW_POS_V)

        if hpos:
            scroll.SetScrollPos(wx.HORIZONTAL, hpos)
        if vpos:
            scroll.SetScrollPos(wx.VERTICAL, vpos, True)

    def GetKind(self):

        return PERSIST_SCROLLEDWINDOW_KIND

# ----------------------------------------------------------------------------------- #

[docs]class SliderHandler(AbstractHandler):
    """
    Supports saving/restoring a `wx.Slider` / L{knobctrl.KnobCtrl} thumb position.

    This class handles the following wxPython widgets:

    - `wx.Slider`;
    - L{knobctrl.KnobCtrl}.

    """

[docs]    def __init__(self, pObject):

        AbstractHandler.__init__(self, pObject)

    def Save(self):

        slider, obj = self._window, self._pObject
        obj.SaveCtrlValue(PERSIST_SLIDER_VALUE, slider.GetValue())
        return True

    def Restore(self):

        slider, obj = self._window, self._pObject
        value = obj.RestoreCtrlValue(PERSIST_SLIDER_VALUE)

        if issubclass(slider.__class__, wx.Slider):
            minVal, maxVal = slider.GetMin(), slider.GetMax()
        else:
            # KnobCtrl
            minVal, maxVal = slider.GetMinValue(), slider.GetMaxValue()

        if value is not None:
            if value >= minVal and value <= maxVal:
                slider.SetValue(value)
                return True

        return False

    def GetKind(self):

        return PERSIST_SLIDER_KIND

# ----------------------------------------------------------------------------------- #

[docs]class SpinHandler(AbstractHandler):
    """
    Supports saving/restoring a `wx.SpinButton` / `wx.SpinCtrl` value.

    This class handles the following wxPython widgets:

    - `wx.SpinCtrl`;
    - `wx.SpinButton`.
    """

[docs]    def __init__(self, pObject):

        AbstractHandler.__init__(self, pObject)

    def Save(self):

        spin, obj = self._window, self._pObject
        obj.SaveCtrlValue(PERSIST_SPIN_VALUE, spin.GetValue())
        return True

    def Restore(self):

        spin, obj = self._window, self._pObject
        value = obj.RestoreCtrlValue(PERSIST_SPIN_VALUE)

        if value is not None:
            minVal, maxVal = spin.GetMin(), spin.GetMax()
            if value >= minVal and value <= maxVal:
                spin.SetValue(value)
                return True

        return False

    def GetKind(self):

        return PERSIST_SPIN_KIND

# ----------------------------------------------------------------------------------- #

[docs]class SplitterHandler(AbstractHandler):
    """
    Supports saving/restoring a `wx.SplitterWindow` splitter position.

    This class handles the following wxPython widgets:

    - `wx.SplitterWindow`.

    """

[docs]    def __init__(self, pObject):

        AbstractHandler.__init__(self, pObject)

    def Save(self):

        splitter, obj = self._window, self._pObject
        obj.SaveValue(PERSIST_SPLITTER_POSITION, splitter.GetSashPosition())
        print 'sash on save: %s' % splitter.GetSashPosition()
        return True

    def Restore(self):

        splitter, obj = self._window, self._pObject
        value = obj.RestoreValue(PERSIST_SPLITTER_POSITION)

        print 'sash on restore: %s' % value
        if value is None:
            return False

        if not splitter.IsSplit():
            return False

        width, height = splitter.GetClientSize()
        minPaneSize = splitter.GetMinimumPaneSize()
        direction = splitter.GetSplitMode()

        if direction == wx.SPLIT_HORIZONTAL:
            # Top and bottom panes
            if value > height - minPaneSize:
                return False
        else:
            # Left and right panes
            if value > width - minPaneSize:
                return False

        print 'sash on restore 2: %s' % value
        splitter.SetSashPosition(value)
        return True

    def GetKind(self):

        return PERSIST_SPLITTER_KIND

# ----------------------------------------------------------------------------------- #

[docs]class TextCtrlHandler(AbstractHandler):
    """
    Supports saving/restoring a `wx.TextCtrl` entered string.

    This class handles the following wxPython widgets:

    - `wx.TextCtrl`;
    - `wx.SearchCtrl`;
    - `wx.lib.expando.ExpandoTextCtrl`;
    - `wx.lib.masked.TextCtrl`;
    - `wx.lib.masked.ComboBox`;
    - `wx.lib.masked.IpAddrCtrl`;
    - `wx.lib.masked.TimeCtrl`;
    - `wx.lib.masked.NumCtrl`;

    """

[docs]    def __init__(self, pObject):

        AbstractHandler.__init__(self, pObject)

    def Save(self):

        text, obj = self._window, self._pObject
        obj.SaveCtrlValue(PERSIST_TEXTCTRL_VALUE, text.GetValue())
        return True

    def Restore(self):

        text, obj = self._window, self._pObject
        value = obj.RestoreCtrlValue(PERSIST_TEXTCTRL_VALUE)

        if value is not None:
            text.ChangeValue(value)
            return True

        return False

    def GetKind(self):

        return PERSIST_TEXTCTRL_KIND

# ----------------------------------------------------------------------------------- #

[docs]class ToggleButtonHandler(AbstractHandler):
    """
    Supports saving/restoring a `wx.ToggleButton` and friends state.

    This class handles the following wxPython widgets:

    - `wx.ToggleButton`;
    - `wx.lib.buttons.GenToggleButton`;
    - `wx.lib.buttons.GenBitmapToggleButton`;
    - `wx.lib.buttons.GenBitmapTextToggleButton`;
    - L{shapedbutton.SToggleButton};
    - L{shapedbutton.SBitmapToggleButton};
    - L{shapedbutton.SBitmapTextToggleButton}.

    """

[docs]    def __init__(self, pObject):

        AbstractHandler.__init__(self, pObject)

    def Save(self):

        toggle, obj = self._window, self._pObject
        obj.SaveValue(PERSIST_TOGGLEBUTTON_TOGGLED, toggle.GetValue())
        return True

    def Restore(self):

        toggle, obj = self._window, self._pObject
        value = obj.RestoreValue(PERSIST_TOGGLEBUTTON_TOGGLED)

        if value is not None:
            toggle.SetValue(value)
            return True

        return False

    def GetKind(self):

        return PERSIST_TOGGLEBUTTON_KIND

# ----------------------------------------------------------------------------------- #

[docs]class TreeCtrlHandler(AbstractHandler):
    """
    Supports saving/restoring a `wx.TreeCtrl` expansion state, selections and
    checked items state (meaningful only for L{customtreectrl.CustomTreeCtrl}).

    This class handles the following wxPython widgets:

    - `wx.TreeCtrl`;
    - `wx.GenericDirCtrl`;
    - L{customtreectrl.CustomTreeCtrl};
    - L{hypertreelist.HyperTreeList};

    """

[docs]    def __init__(self, pObject):

        AbstractHandler.__init__(self, pObject)
        self._isTreeList = isinstance(pObject.GetWindow(), wx.gizmos.TreeListCtrl)

[docs]    def GetItemChildren(self, item=None, recursively=False):
        """
        Return the children of item as a list.

        :param `item`: a `wx.TreeCtrl` item or a L{customtreectrl.CustomTreeCtrl} item;
        :param `recursively`: whether to recurse into the item hierarchy or not.
        """

        if not item:
            item = self._window.GetRootItem()
            if not item:
                return []

        children = []
        child, cookie = self._window.GetFirstChild(item)

        while child and child.IsOk():
            children.append(child)
            if recursively:
                children.extend(self.GetItemChildren(child, True))
            child, cookie = self._window.GetNextChild(item, cookie)

        return children

[docs]    def GetIndexOfItem(self, item):
        """
        Return the index of item.

        :param `item`: a `wx.TreeCtrl` item or a L{customtreectrl.CustomTreeCtrl} item;
        """

        parent = self._window.GetItemParent(item)
        if parent:
            parentIndices = self.GetIndexOfItem(parent)
            ownIndex = self.GetItemChildren(parent).index(item)
            return parentIndices + (ownIndex,)
        else:
            return ()

[docs]    def GetItemIdentity(self, item):
        """
        Return a hashable object that represents the identity of the
        item. By default this returns the position of the item in the
        tree. You may want to override this to return the item label
        (if you know that labels are unique and don't change), or return
        something that represents the underlying domain object, e.g.
        a database key.

        :param `item`: a `wx.TreeCtrl` item or a L{customtreectrl.CustomTreeCtrl} item;
        """

        return self.GetIndexOfItem(item)

[docs]    def GetExpansionState(self):
        """
        Returns list of expanded items. Expanded items are coded as determined by
        the result of L{TreeCtrlHandler.GetItemIdentity}.
        """

        root = self._window.GetRootItem()
        if not root:
            return []
        if self._window.HasFlag(wx.TR_HIDE_ROOT):
            return self.GetExpansionStateOfChildren(root)
        else:
            return self.GetExpansionStateOfItem(root)

[docs]    def SetExpansionState(self, listOfExpandedItems):
        """
        Expands all tree items whose identity, as determined by L{TreeCtrlHandler.GetItemIdentity},
        is present in the list and collapses all other tree items.

        :param `listOfExpandedItems`: a list of expanded `wx.TreeCtrl` or
         L{customtreectrl.CustomTreeCtrl} items.
        """

        root = self._window.GetRootItem()
        if not root:
            return
        if self._window.HasFlag(wx.TR_HIDE_ROOT):
            self.SetExpansionStateOfChildren(listOfExpandedItems, root)
        else:
            self.SetExpansionStateOfItem(listOfExpandedItems, root)

[docs]    def GetSelectionState(self):
        """
        Returns a list of selected items. Selected items are coded as determined by
        the result of L{TreeCtrlHandler.GetItemIdentity}.
        """

        root = self._window.GetRootItem()
        if not root:
            return []
        if self._window.HasFlag(wx.TR_HIDE_ROOT):
            return self.GeSelectionStateOfChildren(root)
        else:
            return self.GetSelectionStateOfItem(root)

[docs]    def SetSelectionState(self, listOfSelectedItems):
        """
        Selects all tree items whose identity, as determined by L{TreeCtrlHandler.GetItemIdentity},
        is present in the list and unselects all other tree items.

        :param `listOfSelectedItems`: a list of selected `wx.TreeCtrl` or
         L{customtreectrl.CustomTreeCtrl} items.
        """

        root = self._window.GetRootItem()
        if not root:
            return
        if self._window.HasFlag(wx.TR_HIDE_ROOT):
            self.SetSelectedStateOfChildren(listOfSelectedItems, root)
        else:
            self.SetSelectedStateOfItem(listOfSelectedItems, root)

[docs]    def GetCheckedState(self):
        """
        Returns a list of checked items. Checked items are coded as determined by
        the result of L{TreeCtrlHandler.GetItemIdentity}.

        :note:

         This is meaningful only for L{customtreectrl.CustomTreeCtrl} and
         L{hypertreelist.HyperTreeList}.
        """

        root = self._window.GetRootItem()
        if not root:
            return []
        if self._window.HasFlag(wx.TR_HIDE_ROOT):
            return self.GetCheckedStateOfChildren(root)
        else:
            return self.GetCheckedStateOfItem(root)

[docs]    def SetCheckedState(self, listOfCheckedItems):
        """
        Checks all tree items whose identity, as determined by L{TreeCtrlHandler.GetItemIdentity}, is present
        in the list and unchecks all other tree items.

        :param `listOfCheckedItems`: a list of checked L{customtreectrl.CustomTreeCtrl} items.

        :note:

         This is meaningful only for L{customtreectrl.CustomTreeCtrl} and
         L{hypertreelist.HyperTreeList}.
        """

        root = self._window.GetRootItem()
        if not root:
            return
        if self._window.HasFlag(wx.TR_HIDE_ROOT):
            self.SetCheckedStateOfChildren(listOfCheckedItems, root)
        else:
            self.SetCheckedStateOfItem(listOfCheckedItems, root)

[docs]    def GetExpansionStateOfItem(self, item):
        """
        Returns the expansion state of a tree item.

        :param `item`: a `wx.TreeCtrl` item or a L{customtreectrl.CustomTreeCtrl} item.
        """

        listOfExpandedItems = []
        if self._window.IsExpanded(item):
            listOfExpandedItems.append(self.GetItemIdentity(item))
            listOfExpandedItems.extend(self.GetExpansionStateOfChildren(item))

        return listOfExpandedItems

[docs]    def GetExpansionStateOfChildren(self, item):
        """
        Returns the expansion state of the children of a tree item.

        :param `item`: a `wx.TreeCtrl` item or a L{customtreectrl.CustomTreeCtrl} item.
        """

        listOfExpandedItems = []
        for child in self.GetItemChildren(item):
            listOfExpandedItems.extend(self.GetExpansionStateOfItem(child))

        return listOfExpandedItems

[docs]    def GetCheckedStateOfItem(self, item):
        """
        Returns the checked/unchecked state of a tree item.

        :param `item`: a L{customtreectrl.CustomTreeCtrl} item.
        """

        listOfCheckedItems = []
        if self._window.IsChecked(item):
            listOfCheckedItems.append(self.GetItemIdentity(item))

        listOfCheckedItems.extend(self.GetCheckedStateOfChildren(item))

        return listOfCheckedItems

[docs]    def GetCheckedStateOfChildren(self, item):
        """
        Returns the checked/unchecked state of the children of a tree item.

        :param `item`: a L{customtreectrl.CustomTreeCtrl} item.
        """

        listOfCheckedItems = []
        for child in self.GetItemChildren(item):
            listOfCheckedItems.extend(self.GetCheckedStateOfItem(child))

        return listOfCheckedItems

[docs]    def GetSelectionStateOfItem(self, item):
        """
        Returns the selection state of a tree item.

        :param `item`: a `wx.TreeCtrl` item or a L{customtreectrl.CustomTreeCtrl} item.
        """

        listOfSelectedItems = []
        if self._window.IsSelected(item):
            listOfSelectedItems.append(self.GetItemIdentity(item))

        listOfSelectedItems.extend(self.GetSelectionStateOfChildren(item))

        return listOfSelectedItems

[docs]    def GetSelectionStateOfChildren(self, item):
        """
        Returns the selection state of the children of a tree item.

        :param `item`: a `wx.TreeCtrl` item or a L{customtreectrl.CustomTreeCtrl} item.
        """

        listOfSelectedItems = []
        for child in self.GetItemChildren(item):
            listOfSelectedItems.extend(self.GetSelectionStateOfItem(child))

        return listOfSelectedItems

[docs]    def SetExpansionStateOfItem(self, listOfExpandedItems, item):
        """
        Sets the expansion state of a tree item (expanded or collapsed).

        :param `listOfExpandedItems`: a list of expanded `wx.TreeCtrl` or
         L{customtreectrl.CustomTreeCtrl} items;
        :param `item`: a `wx.TreeCtrl` item or a L{customtreectrl.CustomTreeCtrl} item.
        """

        if self.GetItemIdentity(item) in listOfExpandedItems:
            self._window.Expand(item)
            self.SetExpansionStateOfChildren(listOfExpandedItems, item)
        else:
            self._window.Collapse(item)

[docs]    def SetExpansionStateOfChildren(self, listOfExpandedItems, item):
        """
        Sets the expansion state of the children of a tree item (expanded or collapsed).

        :param `listOfExpandedItems`: a list of expanded `wx.TreeCtrl` or
         L{customtreectrl.CustomTreeCtrl} items;
        :param `item`: a `wx.TreeCtrl` item or a L{customtreectrl.CustomTreeCtrl} item.
        """

        for child in self.GetItemChildren(item):
            self.SetExpansionStateOfItem(listOfExpandedItems, child)

[docs]    def SetCheckedStateOfItem(self, listOfCheckedItems, item):
        """
        Sets the checked/unchecked state of a tree item.

        :param `listOfCheckedItems`: a list of checked L{customtreectrl.CustomTreeCtrl} items;
        :param `item`: a L{customtreectrl.CustomTreeCtrl} item.
        """

        if self.GetItemIdentity(item) in listOfCheckedItems:
            self._window.CheckItem2(item, True)
        else:
            self._window.CheckItem2(item, False)

        self.SetCheckedStateOfChildren(listOfCheckedItems, item)

[docs]    def SetCheckedStateOfChildren(self, listOfCheckedItems, item):
        """
        Sets the checked/unchecked state of the children of a tree item.

        :param `listOfCheckedItems`: a list of checked L{customtreectrl.CustomTreeCtrl} items;
        :param `item`: a L{customtreectrl.CustomTreeCtrl} item.
        """

        for child in self.GetItemChildren(item):
            self.SetCheckedStateOfItem(listOfCheckedItems, child)

[docs]    def SetSelectedStateOfItem(self, listOfSelectedItems, item):
        """
        Sets the selection state of a tree item.

        :param `listOfSelectedItems`: a list of selected `wx.TreeCtrl` or
         L{customtreectrl.CustomTreeCtrl} items;
        :param `item`: a `wx.TreeCtrl` item or a L{customtreectrl.CustomTreeCtrl} item.
        """

        if self.GetItemIdentity(item) in listOfSelectedItems:
            if self._isTreeList:
                self._window.SelectItem(item, unselect_others=False)
            else:
                self._window.SelectItem(item)

        self.SetSelectedStateOfChildren(listOfSelectedItems, item)

[docs]    def SetSelectedStateOfChildren(self, listOfSelectedItems, item):
        """
        Sets the selection state of the children of a tree item.

        :param `listOfSelectedItems`: a list of selected `wx.TreeCtrl` or
         L{customtreectrl.CustomTreeCtrl} items;
        :param `item`: a `wx.TreeCtrl` item or a L{customtreectrl.CustomTreeCtrl} item.
        """

        for child in self.GetItemChildren(item):
            self.SetSelectedStateOfItem(listOfSelectedItems, child)

    def Save(self):

        tree, obj = self._window, self._pObject

        obj.SaveCtrlValue(PERSIST_TREECTRL_EXPANSION, self.GetExpansionState())

        if issubclass(tree.__class__, (HTL.HyperTreeList, CT.CustomTreeCtrl)):
            obj.SaveCtrlValue(PERSIST_TREECTRL_CHECKED_ITEMS, self.GetCheckedState())

        manager = PM.PersistenceManager.Get()
        if manager.GetManagerStyle() & PM_SAVE_RESTORE_TREE_LIST_SELECTIONS == 0:
            # We don't want to save selected items
            return True

        obj.SaveCtrlValue(PERSIST_TREECTRL_SELECTIONS, self.GetSelectionState())
        return True

    def Restore(self):

        tree, obj = self._window, self._pObject
        expansion = obj.RestoreCtrlValue(PERSIST_TREECTRL_EXPANSION)
        selections = obj.RestoreCtrlValue(PERSIST_TREECTRL_SELECTIONS)

        if expansion is not None:
            self.SetExpansionState(expansion)

        manager = PM.PersistenceManager.Get()
        if manager.GetManagerStyle() & PM_SAVE_RESTORE_TREE_LIST_SELECTIONS:
            # We want to restore selected items
            if selections is not None:
                self.SetSelectionState(selections)

        if not issubclass(tree.__class__, (HTL.HyperTreeList, CT.CustomTreeCtrl)):
            return (expansion is not None and selections is not None)

        checked = obj.RestoreCtrlValue(PERSIST_TREECTRL_CHECKED_ITEMS)
        if checked is not None:
            self.SetCheckedState(checked)

        return (expansion is not None and selections is not None and checked is not None)

    def GetKind(self):

        return PERSIST_TREECTRL_KIND

# ----------------------------------------------------------------------------------- #

[docs]class TreeListCtrlHandler(TreeCtrlHandler):
    """
    Supports saving/restoring a `wx.gizmos.TreeListCtrl` / L{hypertreelist.HyperTreeList} expansion state,
    selections, column widths and checked items state (meaningful only for L{hypertreelist.HyperTreeList}).

    This class handles the following wxPython widgets:

    - `wx.gizmos.TreeListCtrl`;
    - L{hypertreelist.HyperTreeList}.

    """

[docs]    def __init__(self, pObject):

        TreeCtrlHandler.__init__(self, pObject)

    def Save(self):

        treeList, obj = self._window, self._pObject

        colSizes = []
        for col in xrange(treeList.GetColumnCount()):
            colSizes.append(treeList.GetColumnWidth(col))

        obj.SaveValue(PERSIST_TREELISTCTRL_COLWIDTHS, colSizes)

        return TreeCtrlHandler.Save(self)

    def Restore(self):

        treeList, obj = self._window, self._pObject
        colSizes = obj.RestoreValue(PERSIST_TREELISTCTRL_COLWIDTHS)
        retVal = False

        count = treeList.GetColumnCount()
        if colSizes is not None:
            retVal = True
            for col, size in enumerate(colSizes):
                if col < count:
                    treeList.SetColumnWidth(col, size)

        return (retVal and TreeCtrlHandler.Restore(self))

    def GetKind(self):

        return PERSIST_TREELISTCTRL_KIND

# ----------------------------------------------------------------------------------- #

[docs]class CalendarCtrlHandler(AbstractHandler):
    """
    Supports saving/restoring a `wx.calendar.CalendarCtrl` date.

    This class handles the following wxPython widgets:

    - `wx.lib.calendar.CalendarCtrl`.

    """

[docs]    def __init__(self, pObject):

        AbstractHandler.__init__(self, pObject)

    def Save(self):

        calend, obj = self._window, self._pObject
        obj.SaveCtrlValue(PERSIST_CALENDAR_DATE, wxDate2PyDate(calend.GetDate()))
        return True

    def Restore(self):

        calend, obj = self._window, self._pObject
        value = obj.RestoreCtrlValue(PERSIST_CALENDAR_DATE)

        if value is not None:
            calend.SetDate(PyDate2wxDate(value))
            return True

        return False

    def GetKind(self):

        return PERSIST_CALENDAR_KIND

# ----------------------------------------------------------------------------------- #

[docs]class CollapsiblePaneHandler(AbstractHandler):
    """
    Supports saving/restoring a `wx.CollapsiblePane` state.

    This class handles the following wxPython widgets:

    - `wx.CollapsiblePane`.

    """

[docs]    def __init__(self, pObject):

        AbstractHandler.__init__(self, pObject)

    def Save(self):

        collPane, obj = self._window, self._pObject
        obj.SaveValue(PERSIST_COLLAPSIBLE_STATE, collPane.IsCollapsed())
        return True

    def Restore(self):

        collPane, obj = self._window, self._pObject
        value = obj.RestoreValue(PERSIST_COLLAPSIBLE_STATE)

        if value is not None:
            collPane.Collapse(value)
            return True

        return False

    def GetKind(self):

        return PERSIST_COLLAPSIBLE_KIND

# ----------------------------------------------------------------------------------- #

[docs]class DatePickerHandler(AbstractHandler):
    """
    Supports saving/restoring a `wx.DatePickerCtrl` / `wx.GenericDatePickerCtrl` date.

    This class handles the following wxPython widgets:

    - `wx.DatePickerCtrl`;
    - `wx.GenericDatePickerCtrl`.

    """

[docs]    def __init__(self, pObject):

        AbstractHandler.__init__(self, pObject)

    def Save(self):

        datePicker, obj = self._window, self._pObject
        obj.SaveCtrlValue(PERSIST_DATEPICKER_DATE, wxDate2PyDate(datePicker.GetValue()))
        return True

    def Restore(self):

        datePicker, obj = self._window, self._pObject
        value = obj.RestoreCtrlValue(PERSIST_DATEPICKER_DATE)

        if value is not None:
            datePicker.SetValue(PyDate2wxDate(value))
            return True

        return False

    def GetKind(self):

        return PERSIST_DATEPICKER_KIND

# ----------------------------------------------------------------------------------- #

[docs]class MediaCtrlHandler(AbstractHandler):
    """
    Supports saving/restoring a `wx.media.MediaCtrl` movie position, volume and playback
    rate.

    This class handles the following wxPython widgets:

    - `wx.media.MediaCtrl`.

    """

[docs]    def __init__(self, pObject):

        AbstractHandler.__init__(self, pObject)

    def Save(self):

        mediaCtrl, obj = self._window, self._pObject
        obj.SaveValue(PERSIST_MEDIA_POS, mediaCtrl.Tell())
        obj.SaveValue(PERSIST_MEDIA_VOLUME, mediaCtrl.GetVolume())
        obj.SaveValue(PERSIST_MEDIA_RATE, mediaCtrl.GetPlaybackRate())
        return True

    def Restore(self):

        mediaCtrl, obj = self._window, self._pObject
        position = obj.RestoreValue(PERSIST_MEDIA_POS)
        volume = obj.RestoreValue(PERSIST_MEDIA_VOLUME)
        rate = obj.RestoreValue(PERSIST_MEDIA_RATE)

        if position is not None:
            mediaCtrl.Seek(position)

        if volume is not None:
            mediaCtrl.SetVolume(volume)

        if rate is not None:
            mediaCtrl.SetPlaybackRate(rate)

        return (osition is not None and volume is not None and rate is not None)

    def GetKind(self):

        return PERSIST_MEDIA_KIND

# ----------------------------------------------------------------------------------- #

[docs]class ColourPickerHandler(AbstractHandler):
    """
    Supports saving/restoring a `wx.ColourPickerCtrl` / `wx.lib.colourselect.ColourSelect` colour.

    This class handles the following wxPython widgets:

    - `wx.ColourPickerCtrl`;
    - `wx.lib.colourselect.ColourSelect`.

    """

[docs]    def __init__(self, pObject):

        AbstractHandler.__init__(self, pObject)

    def Save(self):

        colPicker, obj = self._window, self._pObject
        obj.SaveValue(PERSIST_COLOURPICKER_COLOUR, colPicker.GetColour().Get(includeAlpha=True))
        return True

    def Restore(self):

        colPicker, obj = self._window, self._pObject
        value = obj.RestoreValue(PERSIST_COLOURPICKER_COLOUR)

        if value is not None:
            colPicker.SetColour(wx.Colour(*value))
            return True

        return False

    def GetKind(self):

        return PERSIST_COLOURPICKER_KIND

# ----------------------------------------------------------------------------------- #

[docs]class FileDirPickerHandler(AbstractHandler):
    """
    Supports saving/restoring a `wx.FilePickerCtrl` / `wx.DirPickerCtrl` path.

    This class handles the following wxPython widgets:

    - `wx.FilePickerCtrl`;
    - `wx.DirPickerCtrl`.

    """

[docs]    def __init__(self, pObject):

        AbstractHandler.__init__(self, pObject)

    def Save(self):

        picker, obj = self._window, self._pObject

        path = picker.GetPath()
        if issubclass(picker.__class__, wx.FileDialog):
            if picker.GetWindowStyleFlag() & wx.FD_MULTIPLE:
                path = picker.GetPaths()

        obj.SaveValue(PERSIST_FILEDIRPICKER_PATH, path)
        return True

    def Restore(self):

        picker, obj = self._window, self._pObject
        value = obj.RestoreValue(PERSIST_FILEDIRPICKER_PATH)

        if value is not None:
            if issubclass(picker.__class__, wx.FileDialog):
                if type(value) == types.ListType:
                    value = value[-1]

            picker.SetPath(value)
            return True

        return False

    def GetKind(self):

        return PERSIST_FILEDIRPICKER_KIND

# ----------------------------------------------------------------------------------- #

[docs]class FontPickerHandler(AbstractHandler):
    """
    Supports saving/restoring a `wx.FontPickerCtrl` font.

    This class handles the following wxPython widgets:

    - `wx.FontPickerCtrl`.

    """

[docs]    def __init__(self, pObject):

        AbstractHandler.__init__(self, pObject)

    def Save(self):

        picker, obj = self._window, self._pObject

        font = picker.GetSelectedFont()
        if not font.IsOk():
            return False

        fontData = CreateFont(font)
        obj.SaveValue(PERSIST_FONTPICKER_FONT, fontData)
        return True

    def Restore(self):

        picker, obj = self._window, self._pObject
        value = obj.RestoreValue(PERSIST_FONTPICKER_FONT)

        if value is not None:
            font = wx.Font(*value)
            if font.IsOk():
                picker.SetSelectedFont(font)
                return True

        return False

    def GetKind(self):

        return PERSIST_FONTPICKER_KIND

# ----------------------------------------------------------------------------------- #

[docs]class FileHistoryHandler(AbstractHandler):
    """
    Supports saving/restoring a `wx.FileHistory` list of file names.

    This class handles the following wxPython widgets:

    - `wx.FileHistory`.

    """

[docs]    def __init__(self, pObject):

        AbstractHandler.__init__(self, pObject)

    def Save(self):

        history, obj = self._window, self._pObject

        paths = []
        for indx in xrange(history.GetCount()):
            paths.append(history.GetHistoryFile(indx))

        obj.SaveValue(PERSIST_FILEHISTORY_PATHS, paths)
        return True

    def Restore(self):

        history, obj = self._window, self._pObject
        value = obj.RestoreValue(PERSIST_FILEHISTORY_PATHS)

        if value is not None:
            count = history.GetMaxFiles()
            for indx, path in enumerate(value):
                if indx < count:
                    history.AddFileToHistory(path)
            return True

        return False

    def GetKind(self):

        return PERSIST_FILEHISTORY_KIND

# ----------------------------------------------------------------------------------- #

[docs]class MenuBarHandler(AbstractHandler):
    """
    Supports saving/restoring the `wx.MenuBar` and L{flatmenu.FlatMenuBar} items state.

    This class handles the following wxPython widgets:

    - `wx.MenuBar`;
    - L{flatmenu.FlatMenuBar}.

    """

[docs]    def __init__(self, pObject):

        AbstractHandler.__init__(self, pObject)

    def Save(self):

        bar, obj = self._window, self._pObject
        menuCount = bar.GetMenuCount()

        if menuCount == 0:
            # Nothing to save
            return False

        checkRadioItems = {}
        for indx in xrange(menuCount):
            menu = bar.GetMenu(indx)
            for item in menu.GetMenuItems():
                if item.GetKind() in [wx.ITEM_CHECK, wx.ITEM_RADIO]:
                    checkRadioItems[item.GetId()] = item.IsChecked()

        obj.SaveValue(PERSIST_MENUBAR_CHECKRADIO_ITEMS, checkRadioItems)
        return True

    def Restore(self):

        bar, obj = self._window, self._pObject
        menuCount = bar.GetMenuCount()

        if menuCount == 0:
            # Nothing to restore
            return False

        checkRadioItems = obj.RestoreValue(PERSIST_MENUBAR_CHECKRADIO_ITEMS)

        if checkRadioItems is None:
            return False

        retVal = True
        for indx in xrange(menuCount):
            menu = bar.GetMenu(indx)
            for item in menu.GetMenuItems():
                if item.GetKind() in [wx.ITEM_CHECK, wx.ITEM_RADIO]:
                    itemId = item.GetId()
                    if itemId in checkRadioItems:
                        item.Check(checkRadioItems[itemId])
                    else:
                        retVal = False

        return retVal

    def GetKind(self):

        return PERSIST_MENUBAR_KIND

# ----------------------------------------------------------------------------------- #

[docs]class ToolBarHandler(AbstractHandler):
    """
    Supports saving/restoring the L{auibar.AuiToolBar} items state.

    This class handles the following wxPython widgets:

    - L{auibar.AuiToolBar}.

    :todo: Find a way to handle `wx.ToolBar` UI settings as it has been done for L{auibar.AuiToolBar}: currently `wx.ToolBar` doesn't seem to have easy access to the underlying toolbar tools.
    """

[docs]    def __init__(self, pObject):

        AbstractHandler.__init__(self, pObject)

    def Save(self):

        bar, obj = self._window, self._pObject
        toolCount = bar.GetToolCount()

        if toolCount == 0:
            # Nothing to save
            return False

        checkRadioItems = {}
        for indx in xrange(toolCount):
            tool = bar.FindToolByIndex(indx)
            if tool is not None:
                if tool.GetKind() in [AUI.ITEM_CHECK, AUI.ITEM_RADIO]:
                    checkRadioItems[tool.GetId()] = tool.GetState() & AUI.AUI_BUTTON_STATE_CHECKED

        obj.SaveValue(PERSIST_TOOLBAR_CHECKRADIO_ITEMS, checkRadioItems)
        return True

    def Restore(self):

        bar, obj = self._window, self._pObject
        toolCount = bar.GetToolCount()

        if toolCount == 0:
            # Nothing to save
            return False

        checkRadioItems = obj.RestoreValue(PERSIST_TOOLBAR_CHECKRADIO_ITEMS)

        if checkRadioItems is None:
            return False

        for indx in xrange(toolCount):
            tool = bar.FindToolByIndex(indx)
            if tool is not None:
                toolId = tool.GetId()
                if toolId in checkRadioItems:
                    if tool.GetKind() in [AUI.ITEM_CHECK, AUI.ITEM_RADIO]:
                        state = checkRadioItems[toolId]
                        if state & AUI.AUI_BUTTON_STATE_CHECKED:
                            tool.SetState(tool.GetState() | AUI.AUI_BUTTON_STATE_CHECKED)
                        else:
                            tool.SetState(tool.GetState() & ~AUI.AUI_BUTTON_STATE_CHECKED)

        return True

    def GetKind(self):

        return PERSIST_TOOLBAR_KIND

# ----------------------------------------------------------------------------------- #

[docs]class FileDirDialogHandler(TLWHandler, FileDirPickerHandler):
    """
    Supports saving/restoring a `wx.DirDialog` / `wx.FileDialog` path.

    This class handles the following wxPython widgets:

    - `wx.DirDialog`;
    - `wx.FileDialog`.
    """

[docs]    def __init__(self, pObject):

        TLWHandler.__init__(self, pObject)
        FileDirPickerHandler.__init__(self, pObject)

    def Save(self):

        tlw = TLWHandler.Save(self)
        fdp = FileDirPickerHandler.Save(self)

        return (tlw and fdp)

    def Restore(self):

        tlw = TLWHandler.Restore(self)
        fdp = FileDirPickerHandler.Restore(self)
        return (tlw and fdp)

    def GetKind(self):

        return PERSIST_FILEDIRPICKER_KIND

# ----------------------------------------------------------------------------------- #

[docs]class FindReplaceHandler(TLWHandler):
    """
    Supports saving/restoring a `wx.FindReplaceDialog` data (search string, replace string
    and flags).

    This class handles the following wxPython widgets:

    - `wx.FindReplaceDialog`.

    :todo: Find a way to properly save and restore dialog data (`wx.ColourDialog`, `wx.FontDialog` etc...).

    """

[docs]    def __init__(self, pObject):

        TLWHandler.__init__(self, pObject)

    def Save(self):

        findDialog, obj = self._window, self._pObject
        data = findDialog.GetData()

        obj.SaveValue(PERSIST_FINDREPLACE_FLAGS, data.GetFlags())
        obj.SaveValue(PERSIST_FINDREPLACE_SEARCH, data.GetFindString())
        obj.SaveValue(PERSIST_FINDREPLACE_REPLACE, data.GetReplaceString())

        return TLWHandler.Save(self)

    def Restore(self):

        findDialog, obj = self._window, self._pObject

        flags = obj.RestoreValue(PERSIST_FINDREPLACE_FLAGS)
        search = obj.RestoreValue(PERSIST_FINDREPLACE_SEARCH)
        replace = obj.RestoreValue(PERSIST_FINDREPLACE_REPLACE)

        data = findDialog.GetData()
        if flags is not None:
            data.SetFlags(flags)
        if search is not None:
            data.SetFindString(search)
        if replace is not None:
            data.SetReplaceString(replace)

        retVal = TLWHandler.Restore(self)

        return (flags is not None and search is not None and replace is not None and retVal)

    def GetKind(self):

        return PERSIST_FINDREPLACE_KIND

# ----------------------------------------------------------------------------------- #

[docs]class FontDialogHandler(TLWHandler):
    """
    Supports saving/restoring a `wx.FontDialog` data (effects, symbols, colour, font, help).

    This class handles the following wxPython widgets:

    - `wx.FontDialog`.

    :todo: Find a way to properly save and restore dialog data (`wx.ColourDialog`, `wx.FontDialog` etc...).

    """

[docs]    def __init__(self, pObject):

        TLWHandler.__init__(self, pObject)

    def Save(self):

        fontDialog, obj = self._window, self._pObject
        data = fontDialog.GetFontData()

        obj.SaveValue(PERSIST_FONTDIALOG_EFFECTS, data.GetEnableEffects())
        obj.SaveValue(PERSIST_FONTDIALOG_SYMBOLS, data.GetAllowSymbols())
        obj.SaveValue(PERSIST_FONTDIALOG_COLOUR, data.GetColour().Get(includeAlpha=True))
        obj.SaveValue(PERSIST_FONTDIALOG_FONT, CreateFont(data.GetChosenFont()))
        obj.SaveValue(PERSIST_FONTDIALOG_HELP, data.GetShowHelp())

        return TLWHandler.Save(self)

    def Restore(self):

        fontDialog, obj = self._window, self._pObject
        data = fontDialog.GetFontData()

        effects = obj.RestoreValue(PERSIST_FONTDIALOG_EFFECTS)
        symbols = obj.RestoreValue(PERSIST_FONTDIALOG_SYMBOLS)
        colour = obj.RestoreValue(PERSIST_FONTDIALOG_COLOUR)
        font = obj.RestoreValue(PERSIST_FONTDIALOG_FONT)
        help = obj.RestoreValue(PERSIST_FONTDIALOG_HELP)

        if effects is not None:
            data.EnableEffects(effects)
        if symbols is not None:
            data.SetAllowSymbols(symbols)
        if colour is not None:
            data.SetColour(wx.Colour(*colour))
        if font is not None:
            data.SetInitialFont(wx.Font(*font))
        if help is not None:
            data.SetShowHelp(help)

        return (effects is not None and symbols is not None and colour is not None and \
                font is not None and help is not None and TLWHandler.Restore(self))

    def GetKind(self):

        return PERSIST_FONTDIALOG_KIND

# ----------------------------------------------------------------------------------- #

[docs]class ColourDialogHandler(TLWHandler):
    """
    Supports saving/restoring a `wx.ColourDialog` data (colour, custom colours and full
    choice in the dialog).

    This class handles the following wxPython widgets:

    - `wx.ColourDialog`;
    - L{cubecolourdialog.CubeColourDialog}.

    :todo: Find a way to properly save and restore dialog data (`wx.ColourDialog`, `wx.FontDialog` etc...).

    """

[docs]    def __init__(self, pObject):

        TLWHandler.__init__(self, pObject)

    def Save(self):

        colDialog, obj = self._window, self._pObject
        data = colDialog.GetColourData()

        obj.SaveValue(PERSIST_COLOURDIALOG_COLOUR, data.GetColour().Get(includeAlpha=True))
        obj.SaveValue(PERSIST_COLOURDIALOG_CHOOSEFULL, data.GetChooseFull())

        customColours = []
        for indx in xrange(15):
            colour = data.GetCustomColour(indx)
            if not colour.IsOk() or colour == wx.WHITE:
                break

            customColours.append(colour.Get(includeAlpha=True))

        obj.SaveValue(PERSIST_COLOURDIALOG_CUSTOMCOLOURS, customColours)

        return TLWHandler.Save(self)

    def Restore(self):

        colDialog, obj = self._window, self._pObject
        data = colDialog.GetColourData()

        colour = obj.RestoreValue(PERSIST_COLOURDIALOG_COLOUR)
        chooseFull = obj.RestoreValue(PERSIST_COLOURDIALOG_CHOOSEFULL)
        customColours = obj.RestoreValue(PERSIST_COLOURDIALOG_CUSTOMCOLOURS)

        if colour is not None:
            data.SetColour(wx.Colour(*colour))
        if chooseFull is not None:
            data.SetChooseFull(chooseFull)
        if customColours is not None:
            for indx, colour in enumerate(customColours):
                data.SetCustomColour(indx, colour)

        return (colour is not None and chooseFull is not None and customColours is not None \
                and TLWHandler.Restore(self))

    def GetKind(self):

        return PERSIST_COLOURDIALOG_KIND

# ----------------------------------------------------------------------------------- #

[docs]class ChoiceDialogHandler(TLWHandler):
    """
    Supports saving/restoring a `wx.MultiChoiceDialog` / `wx.SingleChoiceDialog` choices.

    This class handles the following wxPython widgets:

    - `wx.SingleChoiceDialog`;
    - `wx.MultiChoiceDialog`.
    """

[docs]    def __init__(self, pObject):

        TLWHandler.__init__(self, pObject)

    def Save(self):

        dialog, obj = self._window, self._pObject

        if issubclass(dialog.__class__, wx.SingleChoiceDialog):
            selections = dialog.GetSelection()
            selections = (selections >= 0 and [selections] or [[]])[0]
        else:
            selections = dialog.GetSelections()

        obj.SaveValue(PERSIST_CHOICEDIALOG_SELECTIONS, selections)
        return True

    def Restore(self):

        dialog, obj = self._window, self._pObject
        selections = obj.RestoreValue(PERSIST_CHOICEDIALOG_SELECTIONS)

        if selections is None:
            return False

        if issubclass(dialog.__class__, wx.SingleChoiceDialog):
            if selections:
                dialog.SetSelection(selections[-1])
        else:
            dialog.SetSelections(selections)

        return True

    def GetKind(self):

        return PERSIST_CHOICEDIALOG_KIND

# ----------------------------------------------------------------------------------- #

[docs]class TextEntryHandler(TLWHandler, TextCtrlHandler):
    """
    Supports saving/restoring a `wx.TextEntryDialog` string.

    This class handles the following wxPython widgets:

    - `wx.TextEntryDialog`;
    - `wx.PasswordEntryDialog`.
    """

[docs]    def __init__(self, pObject):

        TLWHandler.__init__(self, pObject)
        TextCtrlHandler.__init__(self, pObject)

    def Save(self):

        tlw = TLWHandler.Save(self)
        txt = TextCtrlHandler.Save(self)
        return (tlw and txt)

    def Restore(self):

        tlw = TLWHandler.Restore(self)
        txt = TextCtrlHandler.Restore(self)
        return (tlw and txt)

    def GetKind(self):

        return PERSIST_TLW_KIND

# ----------------------------------------------------------------------------------- #

HANDLERS = {
    "BookHandler": (wx.BookCtrlBase, wx.aui.AuiNotebook, AUI.AuiNotebook, FNB.FlatNotebook,
                    LBK.LabelBook, LBK.FlatImageBook),
    "TLWHandler": (wx.TopLevelWindow, ),
    "CheckBoxHandler": (wx.CheckBox, ),
    "ListBoxHandler": (wx.ListBox, wx.VListBox, wx.HtmlListBox, wx.SimpleHtmlListBox,
                       wx.gizmos.EditableListBox),
    "ListCtrlHandler": (wx.ListCtrl, wx.ListView), #ULC.UltimateListCtrl (later)
    "ChoiceComboHandler": (wx.Choice, wx.ComboBox, wx.combo.OwnerDrawnComboBox),
    "RadioBoxHandler": (wx.RadioBox, ),
    "RadioButtonHandler": (wx.RadioButton, ),
    "ScrolledWindowHandler": (wx.ScrolledWindow, scrolled.ScrolledPanel),
    "SliderHandler": (wx.Slider, KC.KnobCtrl),
    "SpinHandler": (wx.SpinButton, wx.SpinCtrl, FS.FloatSpin),
    "SplitterHandler": (wx.SplitterWindow, ),
    "TextCtrlHandler": (wx.TextCtrl, wx.SearchCtrl, expando.ExpandoTextCtrl, masked.TextCtrl,
                        masked.ComboBox, masked.IpAddrCtrl, masked.TimeCtrl, masked.NumCtrl),
    "ToggleButtonHandler": (wx.ToggleButton, buttons.GenToggleButton,
                            buttons.GenBitmapToggleButton, buttons.GenBitmapTextToggleButton),
    "TreeCtrlHandler": (wx.TreeCtrl, wx.GenericDirCtrl, CT.CustomTreeCtrl),
    "TreeListCtrlHandler": (HTL.HyperTreeList, wx.gizmos.TreeListCtrl),
    "CalendarCtrlHandler": (calendar.CalendarCtrl, ),
    "CollapsiblePaneHandler": (wx.CollapsiblePane, ),
    "DatePickerHandler": (wx.DatePickerCtrl, wx.GenericDatePickerCtrl),
    "MediaCtrlHandler": (wx.media.MediaCtrl, ),
    "ColourPickerHandler": (wx.ColourPickerCtrl, csel.ColourSelect),
    "FileDirPickerHandler": (wx.FilePickerCtrl, wx.DirPickerCtrl),
    "FontPickerHandler": (wx.FontPickerCtrl, ),
    "FileHistoryHandler": (wx.FileHistory, ),
    "MenuBarHandler": (wx.MenuBar, FM.FlatMenuBar),
    "ToolBarHandler": (AUI.AuiToolBar, )
    }

STANDALONE_HANDLERS = {
    "TreebookHandler": (wx.Treebook, ),
    "CheckListBoxHandler": (wx.CheckListBox, ),
    "FileDirDialogHandler": (wx.DirDialog, wx.FileDialog),
    "FindReplaceHandler": (wx.FindReplaceDialog, ),
    "FontDialogHandler": (wx.FontDialog, ),
    "ColourDialogHandler": (wx.ColourDialog, CCD.CubeColourDialog),
    "ChoiceDialogHandler": (wx.SingleChoiceDialog, wx.MultiChoiceDialog),
    "TextEntryHandler": (wx.TextEntryDialog, wx.PasswordEntryDialog),
    }

if hasSB:
    HANDLERS["ToggleButtonHandler"] += (SB.SToggleButton, SB.SBitmapToggleButton, SB.SBitmapTextToggleButton)

# ----------------------------------------------------------------------------------- #

[docs]def FindHandler(pObject):
    """
    Finds a suitable handler for the input Persistent Object depending on the
    widget kind.

    :param `pObject`: an instance of L{persistencemanager.PersistentObject} class.
    """

    window = pObject.GetWindow()
    klass = window.__class__

    if hasattr(window, "_persistentHandler"):
        # if control has a handler, just return it
        return window._persistentHandler

    for handler, subclasses in STANDALONE_HANDLERS.items():
        for subclass in subclasses:
            if issubclass(klass, subclass):
                return eval(handler)(pObject)

    for handler, subclasses in HANDLERS.items():
        for subclass in subclasses:
            if issubclass(klass, subclass):
                return eval(handler)(pObject)

    raise Exception("Unsupported persistent handler (class=%s, name=%s)"%(klass, window.GetName()))

# ----------------------------------------------------------------------------------- #

[docs]def HasCtrlHandler(control):
    """
    Is there a suitable handler for this control

    :param `control`: the control instance to check if a handler for it exists.
    """

    klass = control.__class__

    if hasattr(control, "_persistentHandler"):
        # if control has a handler, just return it
        return True

    for handler, subclasses in STANDALONE_HANDLERS.items():
        for subclass in subclasses:
            if issubclass(klass, subclass):
                return True

    for handler, subclasses in HANDLERS.items():
        for subclass in subclasses:
            if issubclass(klass, subclass):
                return True

    return False

Navigation

  • index
  • modules |
  • Home |
  • Gallery |
  • Contents»
  • Module code »
  • persist.persist_handlers


persist.persistencemanager

  • modules |
  • Home |
  • Gallery |
  • Contents»
  • Module code »
  • persist.persistencemanager

Source code for persist.persistencemanager

# -*- coding: utf-8 -*-#
#!/usr/bin/env python
# --------------------------------------------------------------------------- #
# PersistentControls Library wxPython IMPLEMENTATION
#
# Inspired by the wxWidgets implementation by Vadim Zeitlin.
#
# License: wxWidgets license
#
# Python Code By:
#
# Andrea Gavana, @ 16 Nov 2009
# Latest Revision: 24 Oct 2011, 21.00 GMT
#
# 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
# --------------------------------------------------------------------------- #

"""
This module contains the definitions of `PersistentObject` and `PersistenceManager` objects.
"""

import wx
import os
import warnings
import datetime

import wx.gizmos

from persist_handlers import FindHandler, HasCtrlHandler

from persist_constants import BAD_DEFAULT_NAMES, CONFIG_PATH_SEPARATOR
from persist_constants import PM_DEFAULT_STYLE, PM_PERSIST_CONTROL_VALUE

# ----------------------------------------------------------------------------------- #

[docs]class PersistentObject(object):
    """
    L{PersistentObject}: ABC for anything persistent.

    This is the base class for persistent object adapters.
    wxPython persistence framework is non-intrusive, i.e. can work with the
    classes which have no relationship to nor knowledge of it. To allow this,
    an intermediate persistence adapter is used: this is just a simple object
    which provides the methods used by L{PersistenceManager} to save and restore
    the object properties and implements them using the concrete class methods.

    You may derive your own classes from L{PersistentObject} to implement persistence
    support for your common classes, see :ref:`persistent-windows` in the
    `__init__.py` file.
    """

[docs]    def __init__(self, window, persistenceHandler=None):
        """
        Default class constructor.

        :param `window`: an instance of `wx.Window`;
        :param `persistenceHandler`: if not ``None``, this should a custom handler derived
         from L{persist_handlers.AbstractHandler}.
        """

        self._name = window.GetName()

        if not self._name.strip():
            raise Exception("Persistent windows should be named! (class=%s)"%window.__class__)

        klass = window.__class__
        if issubclass(klass, wx.GenericDirCtrl):
            self._window = window.GetTreeCtrl()
        elif issubclass(klass, wx.gizmos.EditableListBox):
            self._window = window.GetListCtrl()
        else:
            self._window = window

        if persistenceHandler is not None:
            self._persistentHandler = persistenceHandler(self)
        else:
            self._persistentHandler = FindHandler(self)

        if self._name in BAD_DEFAULT_NAMES:
            warnings.warn("Window names should not be defaulted! (class=%s, name=%s)"%(window.__class__, window.GetName()))

[docs]    def GetName(self):
        """
        Returns the string uniquely identifying the window we're associated with
        among all the other objects of the same type.

        :note: This method is used together with L{GetKind} to construct the unique
         full name of the object in e.g. a configuration file.
        """

        return self._name

[docs]    def GetWindow(self):
        """ Returns the actual associated window. """

        return self._window

[docs]    def GetKind(self):
        """
        Returns the string uniquely identifying the objects supported by this adapter.

        :note: This method is called from L{SaveValue} and L{RestoreValue} and normally
         returns some short (but not too cryptic) strings, e.g. "Checkbox".
        """

        return self._persistentHandler.GetKind()

[docs]    def Save(self):
        """
        Saves the corresponding window settings.

        :note: This method shouldn't be used directly as it doesn't respect the
         global L{PersistenceManager.DisableSaving} settings, use L{PersistenceManager}
         methods with the same name instead.
        """

        self._persistentHandler.Save()

[docs]    def Restore(self):
        """
        Restores the corresponding window settings.

        :note: This method shouldn't be used directly as it doesn't respect the
         global L{PersistenceManager.DisableRestoring} settings, use L{PersistenceManager}
         methods with the same name instead.
        """

        self._persistentHandler.Restore()

[docs]    def SaveValue(self, name, value):
        """
        Save the specified value using the given name.

        :param `name`: the name of the value in the configuration file;
        :param `value`: the value to save.

        :returns: ``True`` if the value was saved or ``False`` if an error occurred.
        """

        return PersistenceManager.Get().SaveValue(self, name, value)

[docs]    def SaveCtrlValue(self, name, value):
        """
        Save the specified value using the given name, should be used only for
        controls data value.

        :param `name`: the name of the value in the configuration file;
        :param `value`: the value to save.

        :returns: ``True`` if the value was saved or ``False`` if an error occurred.
        """

        return PersistenceManager.Get().SaveCtrlValue(self, name, value)

[docs]    def RestoreValue(self, name):
        """
        Restore the value saved by L{SaveValue}.

        :param `name`: the same name as was used by L{SaveValue}.

        :returns: ``True`` if the value was successfully read or ``False`` if
         it was not found or an error occurred.
        """

        return PersistenceManager.Get().RestoreValue(self, name)

[docs]    def RestoreCtrlValue(self, name):
        """
        Restore the value saved by L{SaveCtrlValue}, should be used only for
        controls data value.

        :param `name`: the same name as was used by L{SaveCtrlValue}.

        :returns: ``True`` if the value was successfully read or ``False`` if
         it was not found or an error occurred.
        """

        return PersistenceManager.Get().RestoreCtrlValue(self, name)

# ----------------------------------------------------------------------------------- #

[docs]class PersistenceManager(object):
    """
    L{PersistenceManager}: global aspects of persistent windows.

    Provides support for automatically saving and restoring object properties
    to persistent storage.

    This class is the central element of wxPython persistence framework, see
    the :ref:`persistent-overview` in the `__init__.py` file for its overview.

    This is a singleton class and its unique instance can be retrieved using L{PersistenceManager.Get}
    method.
    """

[docs]    def __init__(self):
        """
        Default class constructor.

        This method should **not** be called directly: you should use the object
        obtained by L{PersistenceManager.Get} and assign manager styles, custom
        configuration files and custom configuration handlers using the appropriate
        methods in this class.

        Interesting attributes you can set for this class are:

        - `configFile`: the persistent configuration file for L{PersistenceManager},
          a custom file name to which `wx.FileConfig` will access to store and
          retrieve UI settings;
        - `configKey`: the persistent key name inside the configuration file for
          L{PersistenceManager};
        - `customConfigHandler`: the persistent configuration handler for L{PersistenceManager};
          this attribute is an object capable of saving/restoring UI settings. This
          can be a cPickle object or a ConfigObj one, for example.
        - `style`: a combination of the following values:

          ======================================== ==================================
          Flag name                                Description
          ======================================== ==================================
          ``PM_SAVE_RESTORE_AUI_PERSPECTIVES``     If a toplevel window has an AUI manager associated, the manager will save and restore its AUI perspective
          ``PM_SAVE_RESTORE_TREE_LIST_SELECTIONS`` If set, the manager will save items selections in list and tree controls
          ``PM_PERSIST_CONTROL_VALUE``             If set, control values will be persisted. This is handy for e.g. applications using a database, where the data (control value) is persisted in the database and persisting it with PM again would only cause confusion.
          ``PM_DEFAULT_STYLE``                     Same as ``PM_SAVE_RESTORE_AUI_PERSPECTIVES``
          ======================================== ==================================

        :note: UI settings are stored as dictionaries key <=> tuple: the tuple value
         contains two items. The first is the value *type* (i.e., float, int, bool etc...)
         while the second is the actual key value.

        """

        object.__init__(self)

        # Specifies custom wx.Config object to use (i.e., custom file names)
        self._configFile = None

        # Specifies custom key in the wx.Config object to use
        self._configKey = None

        # Specifies whether a custom config handler exists, so that we will not use
        # wx.FileConfig (i.e., ConfigObj, ConfigParser etc...)
        self._customConfigHandler = None

        # Specifies the PersistenceManager style
        self._style = PM_DEFAULT_STYLE

        # Set these values to True if we should restore/save the settings (it doesn't
        # make much sense to use this class when both of them are False but setting
        # one of them to False may make sense in some situations)
        self._doSave = True
        self._doRestore = True

        # map with the registered objects as keys and associated
        # PersistentObjects as values
        self._persistentObjects = {}

[docs]    def Get(self):
        """ Accessor to the unique persistence manager object. """

        if not hasattr(self, "_instance"):
            self._instance = PersistenceManager()

        return self._instance

    Get = classmethod(Get)

[docs]    def Free(self):
        """ Destructor for the unique persistence manager object. """

        if hasattr(self, "_instance"):
            del self._instance

    Free = classmethod(Free)

[docs]    def GetManagerStyle(self):
        """
        Returns the L{PersistenceManager} style.

        :see: L{SetManagerStyle} for a list of possible styles.
        """

        return self._style

[docs]    def SetManagerStyle(self, style):
        """
        Sets the L{PersistenceManager} style.

        :param `style`: a combination of the following values:

        ======================================== ==================================
        Flag name                                Description
        ======================================== ==================================
        ``PM_SAVE_RESTORE_AUI_PERSPECTIVES``     If a toplevel window has an AUI manager associated, the manager will save and restore its AUI perspective
        ``PM_SAVE_RESTORE_TREE_LIST_SELECTIONS`` If set, the manager will save items selections in list and tree controls
        ``PM_PERSIST_CONTROL_VALUE``             If set, control values will be persisted. This is handy for e.g. applications using a database, where the data (control value) is persisted in the database and persisting it with PM again would only cause confusion.
        ``PM_DEFAULT_STYLE``                     Same as ``PM_SAVE_RESTORE_AUI_PERSPECTIVES``.
        ======================================== ==================================
        """

        self._style = style

[docs]    def SetPersistenceKey(self, key):
        """
        Sets the persistent key name inside the configuration file for L{PersistenceManager}.

        :param `key`: a short meaningful name for your unique preferences key.

        :note: Calling this method has no influence if you are using your own
         custom configuration handler (i.e., by using ConfigObj/ConfigParser/cPickle etc...).
        """

        self._configKey = key

[docs]    def GetPersistenceKey(self):
        """
        Returns the persistent key name inside the configuration file for L{PersistenceManager}.

        :note: The return value of this method is not used if you are using your own
         custom configuration handler (i.e., by using ConfigObj/ConfigParser/cPickle etc...).
        """

        return self._configKey

[docs]    def SetPersistenceFile(self, fileName):
        """
        Sets the persistent configuration file for L{PersistenceManager}.

        :param `fileName`: the file name where to store the persistent options.

        :note: Calling this method has no influence if you are using your own
         custom configuration handler (i.e., by using ConfigObj/ConfigParser/cPickle etc...).
        """

        self._configFile = fileName

[docs]    def GetPersistenceFile(self):
        """
        Returns the persistent configuration file for L{PersistenceManager}.

        :note: The return value of this method is not used if you are using your own
         custom configuration handler (i.e., by using ConfigObj/ConfigParser/cPickle etc...).
        """

        if self._configFile is not None:
            persistenceDir, fileName = os.path.split(self._configFile)
            fileName = self._configFile
        else:
            persistenceDir = self.GetPersistenceDirectory()
            fileName = "Persistence_Options"

        fileName = os.path.join(persistenceDir, fileName)

        if not os.path.exists(persistenceDir):
            # Create the data folder, it still doesn't exist
            os.makedirs(persistenceDir)

        config = wx.FileConfig(localFilename=fileName)
        return config

[docs]    def SetConfigurationHandler(self, handler):
        """
        Sets the persistent configuration handler for L{PersistenceManager}.

        :param `handler`: an object capable of saving/restoring UI settings. This
         can be a cPickle object or a ConfigObj one, for example.

        :note: UI settings are stored as dictionaries key <=> tuple: the tuple value
         contains two items. The first is the value *type* (i.e., float, int, bool etc...)
         while the second is the actual key value.
        """

        self._customConfigHandler = handler

[docs]    def GetConfigurationHandler(self):
        """
        Returns the persistent configuration handler for L{PersistenceManager}.
        """

        return self._customConfigHandler

[docs]    def GetPersistenceDirectory(self):
        """
        Returns a default persistent option directory for L{PersistenceManager}.

        :note: The return value of this method is not used if you are using your own
         custom configuration handler (i.e., by using ConfigObj/ConfigParser/cPickle etc...)
         or if you have specified a custom configuration file to use with `wx.FileConfig`.
        """

        sp = wx.StandardPaths.Get()
        return sp.GetUserDataDir()

[docs]    def Find(self, window):
        """
        Checks if the object is registered and return the associated L{PersistentObject}
        if it is or ``None`` otherwise.

        :param `window`: an instance of `wx.Window`.
        """

        if window.GetName() in self._persistentObjects:
            return window

[docs]    def Register(self, window, persistenceHandler=None):
        """
        Register an object with the manager.

        :param `window`: an instance of `wx.Window`;
        :param `persistenceHandler`: if not ``None``, this should a custom handler derived
         from L{persist_handlers.AbstractHandler}.

        :note:

         Note that registering the object doesn't do anything except allowing to call
         L{Restore} for it later. If you want to register the object and restore its
         properties, use L{RegisterAndRestore}.

        :note: The manager takes ownership of the L{PersistentObject} and will delete it when
         it is unregistered.
        """

        if self.Find(window):
            raise Exception("Object (class=%s, name=%s) is already registered"%(window.__class__, window.GetName()))

        name = window.GetName()
        self._persistentObjects[name] = PersistentObject(window, persistenceHandler)

        return True

[docs]    def Unregister(self, window):
        """
        Unregister the object, this is called by L{PersistentObject} itself so there is
        usually no need to do it explicitly.

        :param `window`: an instance of `wx.Window`, which must have been previously
         registered with L{Register}.

        :note: For the persistent windows this is done automatically (via L{SaveAndUnregister})
         when the window is destroyed so you only need to call this function explicitly if you
         are using custom persistent objects or if you want to prevent the object properties
         from being saved.

        :note: This deletes the associated L{PersistentObject}.
        """

        if not self.Find(window):
            return False

        name = window.GetName()
        self._persistentObjects.pop(name)

        return True

[docs]    def Save(self, window):
        """
        Saves the state of an object.

        :param `window`: an instance of `wx.Window`.

        :note: This methods does nothing if L{DisableSaving} was called.
        """

        if not self._doSave:
            return False

        if not self.Find(window):
            return False

        name = window.GetName()
        self._persistentObjects[name].Save()

        return True

[docs]    def Restore(self, window):
        """
        Restores the state of an object.

        :param `window`: an instance of `wx.Window`.

        :returns: ``True`` if the object properties were restored or ``False`` if nothing
         was found to restore or the saved settings were invalid.

        :note: This methods does nothing if L{DisableRestoring} was called.
        """

        if not self._doRestore:
            return False

        if not self.Find(window):
            return False

        name = window.GetName()
        self._persistentObjects[name].Restore()

        return True

[docs]    def DisableSaving(self):
        """
        Globally disables saving the persistent properties (enabled by default).

        :note: By default, saving properties in L{Save} is enabled but the program
         may wish to disable if, for example, it detects that it is running on a
         system which shouldn't be modified in any way and so configuration file
         (or Windows registry) shouldn't be written to.
        """

        self._doSave = False

[docs]    def DisableRestoring(self):
        """
        Globally disables restoring the persistent properties (enabled by default).

        :note: By default, restoring properties in L{Restore} is enabled but this
         function allows to disable it. This is mostly useful for testing.
        """

        self._doRestore = False

[docs]    def EnableSaving(self):
        """
        Globally enables saving the persistent properties (enabled by default).

        :note: By default, saving properties in L{Save} is enabled but the program
         may wish to disable if, for example, it detects that it is running on a
         system which shouldn't be modified in any way and so configuration file
         (or Windows registry) shouldn't be written to.
        """

        self._doSave = True

[docs]    def EnableRestoring(self):
        """
        Globally enables restoring the persistent properties (enabled by default).

        :note: By default, restoring properties in L{Restore} is enabled but this
         function allows to disable it. This is mostly useful for testing.
        """

        self._doRestore = True

[docs]    def SaveAndUnregister(self, window=None):
        """
        Combines both L{Save} and L{Unregister} calls.

        :param `window`: an instance of `wx.Window`. If it is ``None``, all the
         windows previously registered are saved and then unregistered.
        """

        if window is None:
            for name, obj in self._persistentObjects.items():
                self.SaveAndUnregister(obj.GetWindow())

            return

        self.Save(window)
        self.Unregister(window)

[docs]    def RegisterAndRestore(self, window):
        """
        Combines both L{Register} and L{Restore} calls.

        :param `window`: an instance of `wx.Window`.
        """

        return self.Register(window) and self.Restore(window)

[docs]    def RegisterAndRestoreAll(self, window, children=None):
        """
        Recursively registers and restore the state of the input `window` and of
        all of its children.

        :param `window`: an instance of `wx.Window`;
        :param `children`: list of children of the input `window`, on first call it is equal to ``None``.
        """

        if children is None:
            if HasCtrlHandler(window):
                # Control has persist support
                self.RegisterAndRestore(window)
            children = window.GetChildren()

        for child in children:
            name = child.GetName()

            if name not in BAD_DEFAULT_NAMES:
                if HasCtrlHandler(child):
                    # Control has persist support
                    self.RegisterAndRestore(child)

            self.RegisterAndRestoreAll(window, child.GetChildren())

[docs]    def GetKey(self, obj, keyName):
        """
        Returns a correctly formatted key name for the object `obj` and `keyName` parameters.

        :param `obj`: an instance of L{PersistentObject};
        :param `keyName`: a string specifying the key name.
        """

        key = (self._configKey is None and ["Persistence_Options"] or [self._configKey])[0]

        key += CONFIG_PATH_SEPARATOR + obj.GetKind()
        key += CONFIG_PATH_SEPARATOR + obj.GetName()
        key += CONFIG_PATH_SEPARATOR + keyName

        return key

[docs]    def SaveCtrlValue(self, obj, keyName, value):
        """
        Check if we persist the widget value, if so pass it to L{DoSaveValue}.

        :param `obj`: an instance of L{PersistentObject};
        :param `keyName`: a string specifying the key name;
        :param `value`: the value to store in the configuration file.
        """

        if self._style & PM_PERSIST_CONTROL_VALUE:
            return self.DoSaveValue(obj, keyName, value)

[docs]    def SaveValue(self, obj, keyName, value):
        """
        Convenience method, all the action is done in L{DoSaveValue}.

        :param `obj`: an instance of L{PersistentObject};
        :param `keyName`: a string specifying the key name;
        :param `value`: the value to store in the configuration file.
        """

        return self.DoSaveValue(obj, keyName, value)

[docs]    def DoSaveValue(self, obj, keyName, value):
        """
        Method used by the persistent objects to save the data.

        By default this method simply use `wx.FileConfig` but this behaviour may be
        overridden by passing a custom configuration handler in the L{PersistenceManager}
        constructor.

        :param `obj`: an instance of L{PersistentObject};
        :param `keyName`: a string specifying the key name;
        :param `value`: the value to store in the configuration file.
        """

        kind = repr(value.__class__).split("'")[1]

        if self._customConfigHandler is not None:
            result = self._customConfigHandler.SaveValue(self.GetKey(obj, keyName), repr((kind, str(value))))
        else:
            config = self.GetPersistenceFile()
            result = config.Write(self.GetKey(obj, keyName), repr((kind, str(value))))
            config.Flush()

        return result

[docs]    def RestoreCtrlValue(self, obj, keyName):
        """
        Check if we persist the widget value, if so pass it to L{DoRestoreValue}.

        :param `obj`: an instance of L{PersistentObject};
        :param `keyName`: a string specifying the key name.
        """

        if self._style & PM_PERSIST_CONTROL_VALUE:
            return self.DoRestoreValue(obj, keyName)

[docs]    def RestoreValue(self, obj, keyName):
        """
        Convenience method, all the action is done in L{DoRestoreValue}.

        :param `obj`: an instance of L{PersistentObject};
        :param `keyName`: a string specifying the key name.
        """

        return self.DoRestoreValue(obj, keyName)

[docs]    def DoRestoreValue(self, obj, keyName):
        """
        Method used by the persistent objects to restore the data.

        By default this method simply use `wx.FileConfig` but this behaviour may be
        overridden by passing a custom config handler in the PersistenceManager
        constructor.

        :param `obj`: an instance of L{PersistentObject};
        :param `keyName`: a string specifying the key name.
        """

        if self._customConfigHandler is not None:
            result = self._customConfigHandler.RestoreValue(self.GetKey(obj, keyName))
        else:
            config = self.GetPersistenceFile()
            result = config.Read(self.GetKey(obj, keyName))

        if result:
            kind, result = eval(result)
            if kind in ("unicode", "str"):
                return result
            elif kind == "datetime.date":
                y, m, d = result.split("-")
                result = datetime.date(int(y), int(m), int(d))
                return result

            return eval(result)

[docs]    def AddBadDefaultName(self, name):
        """
        Adds a name to the ``BAD_DEFAULT_NAMES`` constant.

        :param `name`: a string specifying the control's default name.
        """

        global BAD_DEFAULT_NAMES
        BAD_DEFAULT_NAMES.append(name)

Navigation

  • index
  • modules |
  • Home |
  • Gallery |
  • Contents»
  • Module code »
  • persist.persistencemanager


ribbon.art_aui

  • modules |
  • Home |
  • Gallery |
  • Contents»
  • Module code »
  • ribbon.art_aui

Source code for ribbon.art_aui

"""
L{RibbonAUIArtProvider} is responsible for drawing all the components of the ribbon
interface using an AUI-compatible appearance.

Description
===========

This allows a ribbon bar to have a pluggable look-and-feel, while retaining the same
underlying behaviour. As a single art provider is used for all ribbon components, a
ribbon bar usually has a consistent (though unique) appearance.

By default, a L{RibbonBar} uses an instance of a class called `RibbonDefaultArtProvider`,
which resolves to `RibbonAUIArtProvider`, `RibbonMSWArtProvider`, or `RibbonOSXArtProvider`
- whichever is most appropriate to the current platform. These art providers are all
slightly configurable with regard to colours and fonts, but for larger modifications,
you can derive from one of these classes, or write a completely new art provider class.

Call L{RibbonBar.SetArtProvider} to change the art provider being used.

See Also
========

L{RibbonBar}
"""

import wx

from math import cos
from math import pi as M_PI

from art_msw import RibbonMSWArtProvider
from art_internal import RibbonHSLColour, RibbonShiftLuminance, RibbonInterpolateColour

import bar as BAR, panel as PANEL

from art import *

if wx.Platform == "__WXMAC__":
    import Carbon.Appearance

[docs]def FontFromFont(original):

    newFont = wx.Font(original.GetPointSize(), original.GetFamily(),
                      original.GetStyle(), original.GetWeight(), original.GetUnderlined(),
                      original.GetFaceName(), original.GetEncoding())

    return newFont

[docs]class RibbonAUIArtProvider(RibbonMSWArtProvider):

[docs]    def __init__(self):

        RibbonMSWArtProvider.__init__(self)

        if wx.Platform == "__WXMAC__":

            if hasattr(wx, 'MacThemeColour'):
                base_colour = wx.MacThemeColour(Carbon.Appearance.kThemeBrushToolbarBackground)
            else:
                brush = wx.Brush(wx.BLACK)
                brush.MacSetTheme(Carbon.Appearance.kThemeBrushToolbarBackground)
                base_colour = brush.GetColour()
        else:

            base_colour = wx.SystemSettings.GetColour(wx.SYS_COLOUR_3DFACE)

        self.SetColourScheme(base_colour, wx.SystemSettings.GetColour(wx.SYS_COLOUR_HIGHLIGHT),
                             wx.SystemSettings.GetColour(wx.SYS_COLOUR_HIGHLIGHTTEXT))

        self._tab_active_label_font = FontFromFont(self._tab_label_font)
        self._tab_active_label_font.SetWeight(wx.FONTWEIGHT_BOLD)

        self._page_border_left = 1
        self._page_border_right = 1
        self._page_border_top = 1
        self._page_border_bottom = 2
        self._tab_separation_size = 0

        self._gallery_bitmap_padding_left_size = 3
        self._gallery_bitmap_padding_right_size = 3
        self._gallery_bitmap_padding_top_size = 3
        self._gallery_bitmap_padding_bottom_size = 3

[docs]    def Clone(self):
        """
        Create a new art provider which is a clone of this one.
        """

        copy = RibbonAUIArtProvider()
        self.CloneTo(copy)

        copy._tab_ctrl_background_colour = self._tab_ctrl_background_colour
        copy._tab_ctrl_background_gradient_colour = self._tab_ctrl_background_gradient_colour
        copy._panel_label_background_colour = self._panel_label_background_colour
        copy._panel_label_background_gradient_colour = self._panel_label_background_gradient_colour
        copy._panel_hover_label_background_colour = self._panel_hover_label_background_colour
        copy._panel_hover_label_background_gradient_colour = self._panel_hover_label_background_gradient_colour

        copy._background_brush = self._background_brush
        copy._tab_active_top_background_brush = self._tab_active_top_background_brush
        copy._tab_hover_background_brush = self._tab_hover_background_brush
        copy._button_bar_hover_background_brush = self._button_bar_hover_background_brush
        copy._button_bar_active_background_brush = self._button_bar_active_background_brush
        copy._gallery_button_active_background_brush = self._gallery_button_active_background_brush
        copy._gallery_button_hover_background_brush = self._gallery_button_hover_background_brush
        copy._gallery_button_disabled_background_brush = self._gallery_button_disabled_background_brush

        copy._toolbar_hover_borden_pen = self._toolbar_hover_borden_pen
        copy._tool_hover_background_brush = self._tool_hover_background_brush
        copy._tool_active_background_brush = self._tool_active_background_brush

        return copy

[docs]    def SetFont(self, id, font):
        """
        Set the value of a certain font setting to the value.

        can be one of the font values of `RibbonArtSetting`.

        :param `id`: the font id;
        :param `font`: MISSING DESCRIPTION.

        """

        RibbonMSWArtProvider.SetFont(self, id, font)

        if id == RIBBON_ART_TAB_LABEL_FONT:
            self._tab_active_label_font = FontFromFont(self._tab_label_font)
            self._tab_active_label_font.SetWeight(wx.FONTWEIGHT_BOLD)

[docs]    def GetColour(self, id):
        """
        Get the value of a certain colour setting.

        can be one of the colour values of `RibbonArtSetting`.

        :param `id`: the colour id.

        """

        if id in [RIBBON_ART_PAGE_BACKGROUND_COLOUR, RIBBON_ART_PAGE_BACKGROUND_GRADIENT_COLOUR]:
            return self._background_brush.GetColour()
        elif id == RIBBON_ART_TAB_CTRL_BACKGROUND_COLOUR:
            return self._tab_ctrl_background_colour
        elif id == RIBBON_ART_TAB_CTRL_BACKGROUND_GRADIENT_COLOUR:
            return self._tab_ctrl_background_gradient_colour
        elif id in [RIBBON_ART_TAB_ACTIVE_BACKGROUND_TOP_COLOUR, RIBBON_ART_TAB_ACTIVE_BACKGROUND_TOP_GRADIENT_COLOUR]:
            return self._tab_active_top_background_brush.GetColour()
        elif id in [RIBBON_ART_TAB_HOVER_BACKGROUND_COLOUR, RIBBON_ART_TAB_HOVER_BACKGROUND_GRADIENT_COLOUR]:
            return self._tab_hover_background_brush.GetColour()
        elif id == RIBBON_ART_PANEL_LABEL_BACKGROUND_COLOUR:
            return self._panel_label_background_colour
        elif id == RIBBON_ART_PANEL_LABEL_BACKGROUND_GRADIENT_COLOUR:
            return self._panel_label_background_gradient_colour
        elif id == RIBBON_ART_PANEL_HOVER_LABEL_BACKGROUND_COLOUR:
            return self._panel_hover_label_background_colour
        elif id == RIBBON_ART_PANEL_HOVER_LABEL_BACKGROUND_GRADIENT_COLOUR:
            return self._panel_hover_label_background_gradient_colour
        elif id in [RIBBON_ART_BUTTON_BAR_HOVER_BACKGROUND_COLOUR, RIBBON_ART_BUTTON_BAR_HOVER_BACKGROUND_GRADIENT_COLOUR]:
            return self._button_bar_hover_background_brush.GetColour()
        elif id in [RIBBON_ART_GALLERY_BUTTON_HOVER_BACKGROUND_COLOUR, RIBBON_ART_GALLERY_BUTTON_HOVER_BACKGROUND_GRADIENT_COLOUR]:
            return self._gallery_button_hover_background_brush.GetColour()
        elif id in [RIBBON_ART_GALLERY_BUTTON_ACTIVE_BACKGROUND_COLOUR, RIBBON_ART_GALLERY_BUTTON_ACTIVE_BACKGROUND_GRADIENT_COLOUR]:
            return self._gallery_button_active_background_brush.GetColour()
        elif id in [RIBBON_ART_GALLERY_BUTTON_DISABLED_BACKGROUND_COLOUR, RIBBON_ART_GALLERY_BUTTON_DISABLED_BACKGROUND_GRADIENT_COLOUR]:
            return self._gallery_button_disabled_background_brush.GetColour()
        else:
            return RibbonMSWArtProvider.GetColour(self, id)

[docs]    def SetColour(self, id, colour):
        """
        Set the value of a certain colour setting to the value.

        can be one of the colour values of `RibbonArtSetting`, though not all colour
        settings will have an affect on every art provider.

        :param `id`: the colour id;
        :param `colour`: MISSING DESCRIPTION.

        :see: L{SetColourScheme}
        """

        if id in [RIBBON_ART_PAGE_BACKGROUND_COLOUR, RIBBON_ART_PAGE_BACKGROUND_GRADIENT_COLOUR]:
            self._background_brush.SetColour(colour)
        elif id == RIBBON_ART_TAB_CTRL_BACKGROUND_COLOUR:
            self._tab_ctrl_background_colour = colour
        elif id == RIBBON_ART_TAB_CTRL_BACKGROUND_GRADIENT_COLOUR:
            self._tab_ctrl_background_gradient_colour = colour
        elif id in [RIBBON_ART_TAB_ACTIVE_BACKGROUND_TOP_COLOUR, RIBBON_ART_TAB_ACTIVE_BACKGROUND_TOP_GRADIENT_COLOUR]:
            self._tab_active_top_background_brush.SetColour(colour)
        elif id in [RIBBON_ART_TAB_HOVER_BACKGROUND_COLOUR, RIBBON_ART_TAB_HOVER_BACKGROUND_GRADIENT_COLOUR]:
            self._tab_hover_background_brush.SetColour(colour)
        elif id == RIBBON_ART_PANEL_LABEL_BACKGROUND_COLOUR:
            self._panel_label_background_colour = colour
        elif id == RIBBON_ART_PANEL_LABEL_BACKGROUND_GRADIENT_COLOUR:
            self._panel_label_background_gradient_colour = colour
        elif id in [RIBBON_ART_BUTTON_BAR_HOVER_BACKGROUND_COLOUR, RIBBON_ART_BUTTON_BAR_HOVER_BACKGROUND_GRADIENT_COLOUR]:
            self._button_bar_hover_background_brush.SetColour(colour)
        elif id in [RIBBON_ART_GALLERY_BUTTON_HOVER_BACKGROUND_COLOUR, RIBBON_ART_GALLERY_BUTTON_HOVER_BACKGROUND_GRADIENT_COLOUR]:
            self._gallery_button_hover_background_brush.SetColour(colour)
        elif id in [RIBBON_ART_GALLERY_BUTTON_ACTIVE_BACKGROUND_COLOUR, RIBBON_ART_GALLERY_BUTTON_ACTIVE_BACKGROUND_GRADIENT_COLOUR]:
            self._gallery_button_active_background_brush.SetColour(colour)
        elif id in [RIBBON_ART_GALLERY_BUTTON_DISABLED_BACKGROUND_COLOUR, RIBBON_ART_GALLERY_BUTTON_DISABLED_BACKGROUND_GRADIENT_COLOUR]:
            self._gallery_button_disabled_background_brush.SetColour(colour)
        else:
            RibbonMSWArtProvider.SetColour(self, id, colour)

[docs]    def SetColourScheme(self, primary, secondary, tertiary):
        """
        Set all applicable colour settings from a few base colours.

        Uses any or all of the three given colours to create a colour scheme, and then
        sets all colour settings which are relevant to the art provider using that
        scheme. Note that some art providers may not use the tertiary colour for
        anything, and some may not use the secondary colour either.

        :param `primary`: MISSING DESCRIPTION;
        :param `secondary`: MISSING DESCRIPTION;
        :param `tertiary`: MISSING DESCRIPTION.

        :see: L{SetColour}, L{RibbonMSWArtProvider.GetColourScheme}
        """

        primary_hsl = RibbonHSLColour(primary)
        secondary_hsl = RibbonHSLColour(secondary)
        tertiary_hsl = RibbonHSLColour(tertiary)

        # Map primary & secondary luminance from [0, 1] to [0.15, 0.85]
        primary_hsl.luminance = cos(primary_hsl.luminance * M_PI) * -0.35 + 0.5
        secondary_hsl.luminance = cos(secondary_hsl.luminance * M_PI) * -0.35 + 0.5

        # TODO: Remove next line once this provider stops piggybacking MSW
        RibbonMSWArtProvider.SetColourScheme(self, primary, secondary, tertiary)

        self._tab_ctrl_background_colour = RibbonShiftLuminance(primary_hsl, 0.9).ToRGB()
        self._tab_ctrl_background_gradient_colour = RibbonShiftLuminance(primary_hsl, 1.7).ToRGB()
        self._tab_border_pen = wx.Pen(RibbonShiftLuminance(primary_hsl, 0.75).ToRGB())
        self._tab_label_colour = RibbonShiftLuminance(primary_hsl, 0.1).ToRGB()
        self._tab_hover_background_top_colour =  primary_hsl.ToRGB()
        self._tab_hover_background_top_gradient_colour = RibbonShiftLuminance(primary_hsl, 1.6).ToRGB()
        self._tab_hover_background_brush = wx.Brush(self._tab_hover_background_top_colour)
        self._tab_active_background_colour = self._tab_ctrl_background_gradient_colour
        self._tab_active_background_gradient_colour = primary_hsl.ToRGB()
        self._tab_active_top_background_brush = wx.Brush(self._tab_active_background_colour)
        self._panel_label_colour = self._tab_label_colour
        self._panel_minimised_label_colour = self._panel_label_colour
        self._panel_hover_label_colour = tertiary_hsl.ToRGB()
        self._page_border_pen = self._tab_border_pen
        self._panel_border_pen = self._tab_border_pen
        self._background_brush = wx.Brush(primary_hsl.ToRGB())
        self._page_hover_background_colour = RibbonShiftLuminance(primary_hsl, 1.5).ToRGB()
        self._page_hover_background_gradient_colour = RibbonShiftLuminance(primary_hsl, 0.9).ToRGB()
        self._panel_label_background_colour = RibbonShiftLuminance(primary_hsl, 0.85).ToRGB()
        self._panel_label_background_gradient_colour = RibbonShiftLuminance(primary_hsl, 0.97).ToRGB()
        self._panel_hover_label_background_gradient_colour = secondary_hsl.ToRGB()
        self._panel_hover_label_background_colour = secondary_hsl.Lighter(0.2).ToRGB()
        self._button_bar_hover_border_pen = wx.Pen(secondary_hsl.ToRGB())
        self._button_bar_hover_background_brush = wx.Brush(RibbonShiftLuminance(secondary_hsl, 1.7).ToRGB())
        self._button_bar_active_background_brush = wx.Brush(RibbonShiftLuminance(secondary_hsl, 1.4).ToRGB())
        self._button_bar_label_colour = self._tab_label_colour
        self._gallery_border_pen = self._tab_border_pen
        self._gallery_item_border_pen = self._button_bar_hover_border_pen
        self._gallery_hover_background_brush = wx.Brush(RibbonShiftLuminance(primary_hsl, 1.2).ToRGB())
        self._gallery_button_background_colour = self._page_hover_background_colour
        self._gallery_button_background_gradient_colour = self._page_hover_background_gradient_colour
        self._gallery_button_hover_background_brush = self._button_bar_hover_background_brush
        self._gallery_button_active_background_brush = self._button_bar_active_background_brush
        self._gallery_button_disabled_background_brush = wx.Brush(primary_hsl.Desaturated(0.15).ToRGB())
        self.SetColour(RIBBON_ART_GALLERY_BUTTON_FACE_COLOUR, RibbonShiftLuminance(primary_hsl, 0.1).ToRGB())
        self.SetColour(RIBBON_ART_GALLERY_BUTTON_DISABLED_FACE_COLOUR, wx.Colour(128, 128, 128))
        self.SetColour(RIBBON_ART_GALLERY_BUTTON_ACTIVE_FACE_COLOUR, RibbonShiftLuminance(secondary_hsl, 0.1).ToRGB())
        self.SetColour(RIBBON_ART_GALLERY_BUTTON_HOVER_FACE_COLOUR, RibbonShiftLuminance(secondary_hsl, 0.1).ToRGB())
        self._toolbar_border_pen = self._tab_border_pen
        self.SetColour(RIBBON_ART_TOOLBAR_FACE_COLOUR, RibbonShiftLuminance(primary_hsl, 0.1).ToRGB())
        self._tool_background_colour = self._page_hover_background_colour
        self._tool_background_gradient_colour = self._page_hover_background_gradient_colour
        self._toolbar_hover_borden_pen = self._button_bar_hover_border_pen
        self._tool_hover_background_brush = self._button_bar_hover_background_brush
        self._tool_active_background_brush = self._button_bar_active_background_brush

[docs]    def DrawTabCtrlBackground(self, dc, wnd, rect):
        """
        Draw the background of the tab region of a ribbon bar.

        :param `dc`: The device context to draw onto;
        :param `wnd`: The window which is being drawn onto;
        :param `rect`: The rectangle within which to draw.

        """

        gradient_rect = wx.Rect(*rect)
        gradient_rect.height -= 1
        dc.GradientFillLinear(gradient_rect, self._tab_ctrl_background_colour, self._tab_ctrl_background_gradient_colour, wx.SOUTH)
        dc.SetPen(self._tab_border_pen)
        dc.DrawLine(rect.x, rect.GetBottom(), rect.GetRight()+1, rect.GetBottom())

[docs]    def GetTabCtrlHeight(self, dc, wnd, pages):
        """
        Calculate the height (in pixels) of the tab region of a ribbon bar.

        Note that as the tab region can contain scroll buttons, the height should be
        greater than or equal to the minimum height for a tab scroll button.

        :param `dc`: A device context to use when one is required for size calculations;
        :param `wnd`: The window onto which the tabs will eventually be drawn;
        :param `pages`: The tabs which will acquire the returned height.

        """

        text_height = 0
        icon_height = 0

        if len(pages) <= 1 and (self._flags & RIBBON_BAR_ALWAYS_SHOW_TABS) == 0:
            # To preserve space, a single tab need not be displayed. We still need
            # one pixel of border though.
            return 1

        if self._flags & RIBBON_BAR_SHOW_PAGE_LABELS:
            dc.SetFont(self._tab_active_label_font)
            text_height = dc.GetTextExtent("ABCDEFXj")[1]

        if self._flags & RIBBON_BAR_SHOW_PAGE_ICONS:
            for info in pages:
                if info.page.GetIcon().IsOk():
                    icon_height = max(icon_height, info.page.GetIcon().GetHeight())

        return max(text_height, icon_height) + 10

[docs]    def DrawTab(self, dc, wnd, tab):
        """
        Draw a single tab in the tab region of a ribbon bar.

        :param `dc`: The device context to draw onto;
        :param `wnd`: The window which is being drawn onto (not the L{RibbonPage}
         associated with the tab being drawn);
        :param `tab`: The rectangle within which to draw, and also the tab label,
         icon, and state (active and/or hovered). The drawing rectangle will be
         entirely within a rectangle on the same device context previously painted
         with L{DrawTabCtrlBackground}. The rectangle's width will be at least the
         minimum value returned by L{GetBarTabWidth}, and height will be the value
         returned by L{GetTabCtrlHeight}.

        """

        if tab.rect.height <= 1:
            return

        dc.SetFont(self._tab_label_font)
        dc.SetPen(wx.TRANSPARENT_PEN)

        if tab.active or tab.hovered:
            if tab.active:
                dc.SetFont(self._tab_active_label_font)
                dc.SetBrush(self._background_brush)
                dc.DrawRectangle(tab.rect.x, tab.rect.y + tab.rect.height - 1, tab.rect.width - 1, 1)

            grad_rect = wx.Rect(*tab.rect)
            grad_rect.height -= 4
            grad_rect.width -= 1
            grad_rect.height /= 2
            grad_rect.y = grad_rect.y + tab.rect.height - grad_rect.height - 1
            dc.SetBrush(self._tab_active_top_background_brush)
            dc.DrawRectangle(tab.rect.x, tab.rect.y + 3, tab.rect.width - 1, grad_rect.y - tab.rect.y - 3)
            dc.GradientFillLinear(grad_rect, self._tab_active_background_colour, self._tab_active_background_gradient_colour, wx.SOUTH)

        else:

            btm_rect = wx.Rect(*tab.rect)
            btm_rect.height -= 4
            btm_rect.width -= 1
            btm_rect.height /= 2
            btm_rect.y = btm_rect.y + tab.rect.height - btm_rect.height - 1
            dc.SetBrush(self._tab_hover_background_brush)
            dc.DrawRectangle(btm_rect.x, btm_rect.y, btm_rect.width, btm_rect.height)
            grad_rect = wx.Rect(*tab.rect)
            grad_rect.width -= 1
            grad_rect.y += 3
            grad_rect.height = btm_rect.y - grad_rect.y
            dc.GradientFillLinear(grad_rect, self._tab_hover_background_top_colour, self._tab_hover_background_top_gradient_colour, wx.SOUTH)

        border_points = [wx.Point() for i in xrange(5)]
        border_points[0] = wx.Point(0, 3)
        border_points[1] = wx.Point(1, 2)
        border_points[2] = wx.Point(tab.rect.width - 3, 2)
        border_points[3] = wx.Point(tab.rect.width - 1, 4)
        border_points[4] = wx.Point(tab.rect.width - 1, tab.rect.height - 1)

        dc.SetPen(self._tab_border_pen)
        dc.DrawLines(border_points, tab.rect.x, tab.rect.y)

        old_clip = dc.GetClippingRect()
        is_first_tab = False

        bar = tab.page.GetParent()
        icon = wx.NullBitmap

        if isinstance(bar, BAR.RibbonBar) and bar.GetPage(0) == tab.page:
            is_first_tab = True

        if self._flags & RIBBON_BAR_SHOW_PAGE_ICONS:
            icon = tab.page.GetIcon()
            if self._flags & RIBBON_BAR_SHOW_PAGE_LABELS == 0:
                if icon.IsOk():
                    x = tab.rect.x + (tab.rect.width - icon.GetWidth()) / 2
                    dc.DrawBitmap(icon, x, tab.rect.y + 1 + (tab.rect.height - 1 - icon.GetHeight()) / 2, True)

        if self._flags & RIBBON_BAR_SHOW_PAGE_LABELS:
            label = tab.page.GetLabel()

            if label.strip():
                dc.SetTextForeground(self._tab_label_colour)
                dc.SetBackgroundMode(wx.TRANSPARENT)

                offset = 0

                if icon.IsOk():
                    offset += icon.GetWidth() + 2

                text_width, text_height = dc.GetTextExtent(label)
                x = (tab.rect.width - 2 - text_width - offset) / 2
                if x > 8:
                    x = 8
                elif x < 1:
                    x = 1

                width = tab.rect.width - x - 2
                x += tab.rect.x + offset
                y = tab.rect.y + (tab.rect.height - text_height) / 2

                if icon.IsOk():
                    dc.DrawBitmap(icon, x - offset, tab.rect.y + (tab.rect.height - icon.GetHeight()) / 2, True)

                dc.SetClippingRegion(x, tab.rect.y, width, tab.rect.height)
                dc.DrawText(label, x, y)

        # Draw the left hand edge of the tab only for the first tab (subsequent
        # tabs use the right edge of the prior tab as their left edge). As this is
        # outside the rectangle for the tab, only draw it if the leftmost part of
        # the tab is within the clip rectangle (the clip region has to be cleared
        # to draw outside the tab).
        if is_first_tab and old_clip.x <= tab.rect.x and tab.rect.x < old_clip.x + old_clip.width:
            dc.DestroyClippingRegion()
            dc.DrawLine(tab.rect.x - 1, tab.rect.y + 4, tab.rect.x - 1, tab.rect.y + tab.rect.height - 1)

[docs]    def GetBarTabWidth(self, dc, wnd, label, bitmap, ideal=None, small_begin_need_separator=None,
                       small_must_have_separator=None, minimum=None):
        """
        Calculate the ideal and minimum width (in pixels) of a tab in a ribbon bar.

        :param `dc`: A device context to use when one is required for size calculations;
        :param `wnd`: The window onto which the tab will eventually be drawn;
        :param `label`: The tab's label (or an empty string if it has none);
        :param `bitmap`: The tab's icon (or `wx.NullBitmap` if it has none);
        :param `ideal`: The ideal width (in pixels) of the tab;
        :param `small_begin_need_separator`: A size less than the size, at which a tab
         separator should begin to be drawn (i.e. drawn, but still fairly transparent);
        :param `small_must_have_separator`: A size less than the size, at which a tab
         separator must be drawn (i.e. drawn at full opacity);
        :param `minimum`: A size less than the size, and greater than or equal to zero,
         which is the minimum pixel width for the tab.

        """

        width = mini = 0

        if self._flags & RIBBON_BAR_SHOW_PAGE_LABELS and label.strip():
            dc.SetFont(self._tab_active_label_font)
            width += dc.GetTextExtent(label)[0]
            mini += min(30, width) # enough for a few chars

            if bitmap.IsOk():
                # gap between label and bitmap
                width += 4
                mini += 2

        if self._flags & RIBBON_BAR_SHOW_PAGE_ICONS and bitmap.IsOk():
            width += bitmap.GetWidth()
            mini += bitmap.GetWidth()

        ideal = width + 16
        small_begin_need_separator = mini
        small_must_have_separator = mini
        minimum = mini

        return ideal, small_begin_need_separator, small_must_have_separator, minimum

[docs]    def DrawTabSeparator(self, dc, wnd, rect, visibility):
        """
        Draw a separator between two tabs in a ribbon bar.

        :param `dc`: The device context to draw onto;
        :param `wnd`: The window which is being drawn onto;
        :param `rect`: The rectangle within which to draw, which will be entirely
         within a rectangle on the same device context previously painted with
         L{DrawTabCtrlBackground};
        :param `visibility`: The opacity with which to draw the separator. Values
         are in the range [0, 1], with 0 being totally transparent, and 1 being totally
         opaque.

        """

        # No explicit separators between tabs
        pass

[docs]    def DrawPageBackground(self, dc, wnd, rect):
        """
        Draw the background of a ribbon page.

        :param `dc`: The device context to draw onto;
        :param `wnd`: The window which is being drawn onto (which is commonly the
         L{RibbonPage} whose background is being drawn, but doesn't have to be);
        :param `rect`: The rectangle within which to draw.

        :see: L{RibbonMSWArtProvider.GetPageBackgroundRedrawArea}
        """

        dc.SetPen(wx.TRANSPARENT_PEN)
        dc.SetBrush(self._background_brush)
        dc.DrawRectangle(rect.x + 1, rect.y, rect.width - 2, rect.height - 1)

        dc.SetPen(self._page_border_pen)
        dc.DrawLine(rect.x, rect.y, rect.x, rect.y + rect.height)
        dc.DrawLine(rect.GetRight(), rect.y, rect.GetRight(), rect.y +rect.height)
        dc.DrawLine(rect.x, rect.GetBottom(), rect.GetRight()+1, rect.GetBottom())

[docs]    def GetScrollButtonMinimumSize(self, dc, wnd, style):
        """
        Calculate the minimum size (in pixels) of a scroll button.

        :param `dc`: A device context to use when one is required for size calculations;
        :param `wnd`: The window onto which the scroll button will eventually be drawn;
        :param `style`: A combination of flags from `RibbonScrollButtonStyle`, including
         a direction, and a for flag (state flags may be given too, but should be ignored,
         as a button should retain a constant size, regardless of its state).

        """

        return wx.Size(11, 11)

[docs]    def DrawScrollButton(self, dc, wnd, rect, style):
        """
        Draw a ribbon-style scroll button.

        :param `dc`: The device context to draw onto;
        :param `wnd`: The window which is being drawn onto;
        :param `rect`: The rectangle within which to draw. The size of this rectangle
         will be at least the size returned by L{GetScrollButtonMinimumSize} for a
         scroll button with the same style. For tab scroll buttons, this rectangle
         will be entirely within a rectangle on the same device context previously
         painted with L{DrawTabCtrlBackground}, but this is not guaranteed for other
         types of button (for example, page scroll buttons will not be painted on
         an area previously painted with L{DrawPageBackground});
        :param `style`: A combination of flags from `RibbonScrollButtonStyle`,
         including a direction, a for flag, and one or more states.

        """

        true_rect = wx.Rect(*rect)
        arrow_points = [wx.Point() for i in xrange(3)]

        if style & RIBBON_SCROLL_BTN_FOR_MASK == RIBBON_SCROLL_BTN_FOR_TABS:
            true_rect.y += 2
            true_rect.height -= 2
            dc.SetPen(self._tab_border_pen)
        else:
            dc.SetPen(wx.TRANSPARENT_PEN)
            dc.SetBrush(self._background_brush)
            dc.DrawRectangle(rect.x, rect.y, rect.width, rect.height)
            dc.SetPen(self._page_border_pen)

        result = style & RIBBON_SCROLL_BTN_DIRECTION_MASK

        if result == RIBBON_SCROLL_BTN_LEFT:
            dc.DrawLine(true_rect.GetRight(), true_rect.y, true_rect.GetRight(), true_rect.y + true_rect.height)
            arrow_points[0] = wx.Point(rect.width / 2 - 2, rect.height / 2)
            arrow_points[1] = arrow_points[0] + wx.Point(5, -5)
            arrow_points[2] = arrow_points[0] + wx.Point(5,  5)

        elif result == RIBBON_SCROLL_BTN_RIGHT:
            dc.DrawLine(true_rect.x, true_rect.y, true_rect.x, true_rect.y + true_rect.height)
            arrow_points[0] = wx.Point(rect.width / 2 + 3, rect.height / 2)
            arrow_points[1] = arrow_points[0] - wx.Point(5, -5)
            arrow_points[2] = arrow_points[0] - wx.Point(5,  5)

        elif result == RIBBON_SCROLL_BTN_DOWN:
            dc.DrawLine(true_rect.x, true_rect.y, true_rect.x + true_rect.width, true_rect.y)
            arrow_points[0] = wx.Point(rect.width / 2, rect.height / 2 + 3)
            arrow_points[1] = arrow_points[0] - wx.Point( 5, 5)
            arrow_points[2] = arrow_points[0] - wx.Point(-5, 5)

        elif result == RIBBON_SCROLL_BTN_UP:
            dc.DrawLine(true_rect.x, true_rect.GetBottom(), true_rect.x + true_rect.width, true_rect.GetBottom())
            arrow_points[0] = wx.Point(rect.width / 2, rect.height / 2 - 2)
            arrow_points[1] = arrow_points[0] + wx.Point( 5, 5)
            arrow_points[2] = arrow_points[0] + wx.Point(-5, 5)

        else:
            return

        x = rect.x
        y = rect.y

        if style & RIBBON_SCROLL_BTN_ACTIVE:
            x += 1
            y += 1

        dc.SetPen(wx.TRANSPARENT_PEN)
        B = wx.Brush(self._tab_label_colour)
        dc.SetBrush(B)
        dc.DrawPolygon(arrow_points, x, y)

[docs]    def GetPanelSize(self, dc, wnd, client_size, client_offset=None):
        """
        Calculate the size of a panel for a given client size.

        This should increment the given size by enough to fit the panel label and other
        chrome.

        :param `dc`: A device context to use if one is required for size calculations;
        :param `wnd`: The ribbon panel in question;
        :param `client_size`: The client size;
        :param `client_offset`: The offset where the client rectangle begins within
         the panel (may be ``None``).

        :see: L{GetPanelClientSize}
        """

        dc.SetFont(self._panel_label_font)
        label_size = wx.Size(*dc.GetTextExtent(wnd.GetLabel()))
        label_height = label_size.GetHeight() + 5

        if self._flags & RIBBON_BAR_FLOW_VERTICAL:
            client_size.IncBy(4, label_height + 6)
            if client_offset is not None:
                client_offset = wx.Point(2, label_height + 3)

        else:
            client_size.IncBy(6, label_height + 4)
            if client_offset is not None:
                client_offset = wx.Point(3, label_height + 2)

        return client_size

[docs]    def GetPanelClientSize(self, dc, wnd, size, client_offset=None):
        """
        Calculate the client size of a panel for a given overall size.

        This should act as the inverse to L{GetPanelSize}, and decrement the given size
        by enough to fit the panel label and other chrome.

        :param `dc`: A device context to use if one is required for size calculations;
        :param `wnd`: The ribbon panel in question;
        :param `size`: The overall size to calculate client size for;
        :param `client_offset`: The offset where the returned client size begins within
         the given (may be ``None``).

        :see: L{GetPanelSize}
        """

        dc.SetFont(self._panel_label_font)
        label_size = wx.Size(*dc.GetTextExtent(wnd.GetLabel()))
        label_height = label_size.GetHeight() + 5

        if self._flags & RIBBON_BAR_FLOW_VERTICAL:
            size.DecBy(4, label_height + 6)
            if client_offset is not None:
                client_offset = wx.Point(2, label_height + 3)

        else:
            size.DecBy(6, label_height + 4)
            if client_offset is not None:
                client_offset = wx.Point(3, label_height + 2)

        if size.x < 0:
            size.x = 0
        if size.y < 0:
            size.y = 0

        return size, client_offset

[docs]    def DrawPanelBackground(self, dc, wnd, rect):
        """
        Draw the background and chrome for a ribbon panel.

        This should draw the border, background, label, and any other items of a panel
        which are outside the client area of a panel. Note that when a panel is
        minimised, this function is not called - only L{DrawMinimisedPanel} is called,
        so a background should be explicitly painted by that if required.

        :param `dc`: The device context to draw onto;
        :param `wnd`: The window which is being drawn onto, which is always the panel
         whose background and chrome is being drawn. The panel label and other panel
         attributes can be obtained by querying this;
        :param `rect`: The rectangle within which to draw.

        """

        dc.SetPen(wx.TRANSPARENT_PEN)
        dc.SetBrush(self._background_brush)
        dc.DrawRectangle(rect.x, rect.y, rect.width, rect.height)

        true_rect = wx.Rect(*rect)
        true_rect = self.RemovePanelPadding(true_rect)

        dc.SetPen(self._panel_border_pen)
        dc.SetBrush(wx.TRANSPARENT_BRUSH)
        dc.DrawRectangle(true_rect.x, true_rect.y, true_rect.width, true_rect.height)

        true_rect.x += 1
        true_rect.width -= 2
        true_rect.y += 1

        dc.SetFont(self._panel_label_font)
        label_size = wx.Size(*dc.GetTextExtent(wnd.GetLabel()))
        label_height = label_size.GetHeight() + 5
        label_rect = wx.Rect(*true_rect)
        label_rect.height = label_height - 1

        dc.DrawLine(label_rect.x, label_rect.y + label_rect.height, label_rect.x + label_rect.width, label_rect.y + label_rect.height)

        label_bg_colour = self._panel_label_background_colour
        label_bg_grad_colour = self._panel_label_background_gradient_colour

        if wnd.IsHovered():
            label_bg_colour = self._panel_hover_label_background_colour
            label_bg_grad_colour = self._panel_hover_label_background_gradient_colour
            dc.SetTextForeground(self._panel_hover_label_colour)
        else:
            dc.SetTextForeground(self._panel_label_colour)

        if wx.Platform == "__WXMAC__":
            dc.GradientFillLinear(label_rect, label_bg_grad_colour, label_bg_colour, wx.SOUTH)
        else:
            dc.GradientFillLinear(label_rect, label_bg_colour, label_bg_grad_colour, wx.SOUTH)

        dc.SetFont(self._panel_label_font)
        dc.DrawText(wnd.GetLabel(), label_rect.x + 3, label_rect.y + 2)

        if wnd.IsHovered():

            gradient_rect = wx.Rect(*true_rect)
            gradient_rect.y += label_rect.height + 1
            gradient_rect.height = true_rect.height - label_rect.height - 3
            if wx.Platform == "__WXMAC__":
                colour = self._page_hover_background_gradient_colour
                gradient = self._page_hover_background_colour
            else:
                colour = self._page_hover_background_colour
                gradient = self._page_hover_background_gradient_colour

            dc.GradientFillLinear(gradient_rect, colour, gradient, wx.SOUTH)

[docs]    def DrawMinimisedPanel(self, dc, wnd, rect, bitmap):
        """
        Draw a minimised ribbon panel.

        :param `dc`: The device context to draw onto;
        :param `wnd`: The window which is being drawn onto, which is always the panel
         which is minimised. The panel label can be obtained from this window. The
         minimised icon obtained from querying the window may not be the size requested
         by L{RibbonMSWArtProvider.GetMinimisedPanelMinimumSize} - the argument contains the icon in the
         requested size;
        :param `rect`: The rectangle within which to draw. The size of the rectangle
         will be at least the size returned by L{RibbonMSWArtProvider.GetMinimisedPanelMinimumSize};
        :param `bitmap`: A copy of the panel's minimised bitmap rescaled to the size
         returned by L{RibbonMSWArtProvider.GetMinimisedPanelMinimumSize}.

        """

        dc.SetPen(wx.TRANSPARENT_PEN)
        dc.SetBrush(self._background_brush)
        dc.DrawRectangle(rect.x, rect.y, rect.width, rect.height)

        true_rect = wx.Rect(*rect)
        true_rect = self.RemovePanelPadding(true_rect)

        dc.SetPen(self._panel_border_pen)
        dc.SetBrush(wx.TRANSPARENT_BRUSH)
        dc.DrawRectangle(true_rect.x, true_rect.y, true_rect.width, true_rect.height)
        true_rect.Deflate(1, 1)

        if wnd.IsHovered() or wnd.GetExpandedPanel():
            colour = self._page_hover_background_colour
            gradient = self._page_hover_background_gradient_colour
            if (wx.Platform == "__WXMAC__" and not wnd.GetExpandedPanel()) or \
               (wx.Platform != "__WXMAC__" and wnd.GetExpandedPanel()):
                temp = colour
                colour = gradient
                gradient = temp

            dc.GradientFillLinear(true_rect, colour, gradient, wx.SOUTH)

        preview = self.DrawMinimisedPanelCommon(dc, wnd, true_rect)

        dc.SetPen(self._panel_border_pen)
        dc.SetBrush(wx.TRANSPARENT_BRUSH)
        dc.DrawRectangle(preview.x, preview.y, preview.width, preview.height)
        preview.Deflate(1, 1)

        preview_caption_rect = wx.Rect(*preview)
        preview_caption_rect.height = 7
        preview.y += preview_caption_rect.height
        preview.height -= preview_caption_rect.height

        if wx.Platform == "__WXMAC__":
            dc.GradientFillLinear(preview_caption_rect, self._panel_hover_label_background_gradient_colour,
                                  self._panel_hover_label_background_colour, wx.SOUTH)
            dc.GradientFillLinear(preview, self._page_hover_background_gradient_colour,
                                  self._page_hover_background_colour, wx.SOUTH)
        else:
            dc.GradientFillLinear(preview_caption_rect, self._panel_hover_label_background_colour,
                                  self._panel_hover_label_background_gradient_colour, wx.SOUTH)
            dc.GradientFillLinear(preview, self._page_hover_background_colour,
                                  self._page_hover_background_gradient_colour, wx.SOUTH)

        if bitmap.IsOk():
            dc.DrawBitmap(bitmap, preview.x + (preview.width - bitmap.GetWidth()) / 2,
                          preview.y + (preview.height - bitmap.GetHeight()) / 2, True)

[docs]    def DrawPartialPanelBackground(self, dc, wnd, rect):

        dc.SetPen(wx.TRANSPARENT_PEN)
        dc.SetBrush(self._background_brush)
        dc.DrawRectangle(rect.x, rect.y, rect.width, rect.height)

        offset = wx.Point(*wnd.GetPosition())
        parent = wnd.GetParent()
        panel = None

        while 1:
            panel = parent
            if isinstance(panel, PANEL.RibbonPanel):
                if not panel.IsHovered():
                    return
                break

            offset += parent.GetPosition()
            parent = panel.GetParent()

        if panel is None:
            return

        background = wx.Rect(0, 0, *panel.GetSize())
        background = self.RemovePanelPadding(background)

        background.x += 1
        background.width -= 2
        dc.SetFont(self._panel_label_font)
        caption_height = dc.GetTextExtent(panel.GetLabel())[1] + 7
        background.y += caption_height - 1
        background.height -= caption_height

        paint_rect = wx.Rect(*rect)
        paint_rect.x += offset.x
        paint_rect.y += offset.y

        if wx.Platform == "__WXMAC__":
            bg_grad_clr = self._page_hover_background_colour
            bg_clr = self._page_hover_background_gradient_colour
        else:
            bg_clr = self._page_hover_background_colour
            bg_grad_clr = self._page_hover_background_gradient_colour

        paint_rect.Intersect(background)

        if not paint_rect.IsEmpty():
            starting_colour = RibbonInterpolateColour(bg_clr, bg_grad_clr, paint_rect.y, background.y, background.y + background.height)
            ending_colour = RibbonInterpolateColour(bg_clr, bg_grad_clr, paint_rect.y + paint_rect.height, background.y, background.y + background.height)
            paint_rect.x -= offset.x
            paint_rect.y -= offset.y
            dc.GradientFillLinear(paint_rect, starting_colour, ending_colour, wx.SOUTH)

[docs]    def DrawGalleryBackground(self, dc, wnd, rect):
        """
        Draw the background and chrome for a L{RibbonGallery} control.

        This should draw the border, brackground, scroll buttons, extension button, and
        any other UI elements which are not attached to a specific gallery item.

        :param `dc`: The device context to draw onto;
        :param `wnd`: The window which is being drawn onto, which is always the gallery
         whose background and chrome is being drawn. Attributes used during drawing like
         the gallery hover state and individual button states can be queried from this
         parameter by L{RibbonGallery.IsHovered}, L{RibbonGallery.GetExtensionButtonState},
         L{RibbonGallery.GetUpButtonState}, and L{RibbonGallery.GetDownButtonState};
        :param `rect`: The rectangle within which to draw. This rectangle is the entire
         area of the gallery control, not just the client rectangle.

        """

        self.DrawPartialPanelBackground(dc, wnd, rect)

        if wnd.IsHovered():
            dc.SetPen(wx.TRANSPARENT_PEN)
            dc.SetBrush(self._gallery_hover_background_brush)

            if self._flags & RIBBON_BAR_FLOW_VERTICAL:
                dc.DrawRectangle(rect.x + 1, rect.y + 1, rect.width - 2, rect.height - 16)
            else:
                dc.DrawRectangle(rect.x + 1, rect.y + 1, rect.width - 16, rect.height - 2)

        dc.SetPen(self._gallery_border_pen)
        dc.SetBrush(wx.TRANSPARENT_BRUSH)
        dc.DrawRectangle(rect.x, rect.y, rect.width, rect.height)

        self.DrawGalleryBackgroundCommon(dc, wnd, rect)

[docs]    def DrawGalleryButton(self, dc, rect, state, bitmaps):

        extra_height = 0
        extra_width = 0
        reduced_rect = wx.Rect(*rect)
        reduced_rect.Deflate(1, 1)

        if self._flags & RIBBON_BAR_FLOW_VERTICAL:
            reduced_rect.width += 1
            extra_width = 1
        else:
            reduced_rect.height += 1
            extra_height = 1

        if state == RIBBON_GALLERY_BUTTON_NORMAL:
            dc.GradientFillLinear(reduced_rect, self._gallery_button_background_colour, self._gallery_button_background_gradient_colour, wx.SOUTH)
            btn_bitmap = bitmaps[0]

        elif state == RIBBON_GALLERY_BUTTON_HOVERED:
            dc.SetPen(self._gallery_item_border_pen)
            dc.SetBrush(self._gallery_button_hover_background_brush)
            dc.DrawRectangle(rect.x, rect.y, rect.width + extra_width, rect.height + extra_height)
            btn_bitmap = bitmaps[1]

        elif state == RIBBON_GALLERY_BUTTON_ACTIVE:
            dc.SetPen(self._gallery_item_border_pen)
            dc.SetBrush(self._gallery_button_active_background_brush)
            dc.DrawRectangle(rect.x, rect.y, rect.width + extra_width, rect.height + extra_height)
            btn_bitmap = bitmaps[2]

        elif state == RIBBON_GALLERY_BUTTON_DISABLED:
            dc.SetPen(wx.TRANSPARENT_PEN)
            dc.SetBrush(self._gallery_button_disabled_background_brush)
            dc.DrawRectangle(reduced_rect.x, reduced_rect.y, reduced_rect.width, reduced_rect.height)
            btn_bitmap = bitmaps[3]

        dc.DrawBitmap(btn_bitmap, reduced_rect.x + reduced_rect.width / 2 - 2, (rect.y + rect.height / 2) - 2, True)

[docs]    def DrawGalleryItemBackground(self, dc, wnd, rect, item):
        """
        Draw the background of a single item in a L{RibbonGallery} control.

        This is painted on top of a gallery background, and behind the items bitmap.
        Unlike L{DrawButtonBarButton} and L{DrawTool}, it is not expected to draw the
        item bitmap - that is done by the gallery control itself.

        :param `dc`: The device context to draw onto;
        :param `wnd`: The window which is being drawn onto, which is always the gallery
         which contains the item being drawn;
        :param `rect`: The rectangle within which to draw. The size of this rectangle
         will be the size of the item's bitmap, expanded by gallery item padding values
         (``RIBBON_ART_GALLERY_BITMAP_PADDING_LEFT_SIZE``, ``RIBBON_ART_GALLERY_BITMAP_PADDING_RIGHT_SIZE``,
         ``RIBBON_ART_GALLERY_BITMAP_PADDING_TOP_SIZE``, and ``RIBBON_ART_GALLERY_BITMAP_PADDING_BOTTOM_SIZE``).
         The drawing rectangle will be entirely within a rectangle on the same device
         context previously painted with L{DrawGalleryBackground};
        :param `item`: The item whose background is being painted. Typically the
         background will vary if the item is hovered, active, or selected;
         L{RibbonGallery.GetSelection}, L{RibbonGallery.GetActiveItem}, and
         L{RibbonGallery.GetHoveredItem} can be called to test if the given item is in one of these states.

        """

        if wnd.GetHoveredItem() != item and wnd.GetActiveItem() != item and wnd.GetSelection() != item:
            return

        dc.SetPen(self._gallery_item_border_pen)

        if wnd.GetActiveItem() == item or wnd.GetSelection() == item:
            dc.SetBrush(self._gallery_button_active_background_brush)
        else:
            dc.SetBrush(self._gallery_button_hover_background_brush)

        dc.DrawRectangle(rect.x, rect.y, rect.width, rect.height)

[docs]    def DrawButtonBarBackground(self, dc, wnd, rect):
        """
        Draw the background for a L{bar.RibbonButtonBar} control.

        :param `dc`: The device context to draw onto;
        :param `wnd`: The window which is being drawn onto (which will typically
         be the button bar itself, though this is not guaranteed);
        :param `rect`: The rectangle within which to draw.

        """

        self.DrawPartialPanelBackground(dc, wnd, rect)

[docs]    def DrawButtonBarButton(self, dc, wnd, rect, kind, state, label, bitmap_large, bitmap_small):
        """
        Draw a single button for a L{bar.RibbonButtonBar} control.

        :param `dc`: The device context to draw onto;
        :param `wnd`: The window which is being drawn onto;
        :param `rect`: The rectangle within which to draw. The size of this rectangle
         will be a size previously returned by L{RibbonMSWArtProvider.GetButtonBarButtonSize}, and the
         rectangle will be entirely within a rectangle on the same device context
         previously painted with L{DrawButtonBarBackground};
        :param `kind`: The kind of button to draw (normal, dropdown or hybrid);
        :param `state`: Combination of a size flag and state flags from the
         `RibbonButtonBarButtonState` enumeration;
        :param `label`: The label of the button;
        :param `bitmap_large`: The large bitmap of the button (or the large disabled
         bitmap when ``RIBBON_BUTTONBAR_BUTTON_DISABLED`` is set in );
        :param `bitmap_small`: The small bitmap of the button (or the small disabled
         bitmap when ``RIBBON_BUTTONBAR_BUTTON_DISABLED`` is set in ).

        """

        if kind == RIBBON_BUTTON_TOGGLE:
            kind = RIBBON_BUTTON_NORMAL
            if state & RIBBON_BUTTONBAR_BUTTON_TOGGLED:
                state ^= RIBBON_BUTTONBAR_BUTTON_ACTIVE_MASK

        if state & (RIBBON_BUTTONBAR_BUTTON_HOVER_MASK | RIBBON_BUTTONBAR_BUTTON_ACTIVE_MASK):
            dc.SetPen(self._button_bar_hover_border_pen)
            bg_rect = wx.Rect(*rect)
            bg_rect.Deflate(1, 1)

            if kind == RIBBON_BUTTON_HYBRID:
                result = state & RIBBON_BUTTONBAR_BUTTON_SIZE_MASK

                if result == RIBBON_BUTTONBAR_BUTTON_LARGE:
                    iYBorder = rect.y + bitmap_large.GetHeight() + 4
                    partial_bg = wx.Rect(*rect)

                    if state & RIBBON_BUTTONBAR_BUTTON_NORMAL_HOVERED:
                        partial_bg.SetBottom(iYBorder - 1)
                    else:
                        partial_bg.height -= (iYBorder - partial_bg.y + 1)
                        partial_bg.y = iYBorder + 1

                    dc.DrawLine(rect.x, iYBorder, rect.x + rect.width, iYBorder)
                    bg_rect.Intersect(partial_bg)

                elif result == RIBBON_BUTTONBAR_BUTTON_MEDIUM:
                    iArrowWidth = 9

                    if state & RIBBON_BUTTONBAR_BUTTON_NORMAL_HOVERED:
                        bg_rect.width -= iArrowWidth
                        dc.DrawLine(bg_rect.x + bg_rect.width, rect.y, bg_rect.x + bg_rect.width, rect.y + rect.height)
                    else:
                        iArrowWidth -= 1
                        bg_rect.x += bg_rect.width - iArrowWidth
                        bg_rect.width = iArrowWidth
                        dc.DrawLine(bg_rect.x - 1, rect.y, bg_rect.x - 1, rect.y + rect.height)

            dc.SetBrush(wx.TRANSPARENT_BRUSH)
            dc.DrawRectangle(rect.x, rect.y, rect.width, rect.height)

            dc.SetPen(wx.TRANSPARENT_PEN)

            if state & RIBBON_BUTTONBAR_BUTTON_ACTIVE_MASK:
                dc.SetBrush(self._button_bar_active_background_brush)
            else:
                dc.SetBrush(self._button_bar_hover_background_brush)

            dc.DrawRectangle(bg_rect.x, bg_rect.y, bg_rect.width, bg_rect.height)

        dc.SetFont(self._button_bar_label_font)
        dc.SetTextForeground(self._button_bar_label_colour)
        self.DrawButtonBarButtonForeground(dc, rect, kind, state, label, bitmap_large, bitmap_small)

[docs]    def DrawToolBarBackground(self, dc, wnd, rect):
        """
        Draw the background for a L{RibbonToolBar} control.

        :param `dc`: The device context to draw onto;
        :param `wnd`: The which is being drawn onto. In most cases this will be
         a L{RibbonToolBar}, but it doesn't have to be;
        :param `rect`: The rectangle within which to draw. Some of this rectangle
         will later be drawn over using L{DrawToolGroupBackground} and L{DrawTool},
         but not all of it will (unless there is only a single group of tools).

        """

        self.DrawPartialPanelBackground(dc, wnd, rect)

[docs]    def DrawToolGroupBackground(self, dc, wnd, rect):
        """
        Draw the background for a group of tools on a L{RibbonToolBar} control.

        :param `dc`: The device context to draw onto;
        :param `wnd`: The window which is being drawn onto. In most cases this will
         be a L{RibbonToolBar}, but it doesn't have to be;
        :param `rect`: The rectangle within which to draw. This rectangle is a union
         of the individual tools' rectangles. As there are no gaps between tools, this
         rectangle will be painted over exactly once by calls to L{DrawTool}. The
         group background could therefore be painted by L{DrawTool}, though it can be
         conceptually easier and more efficient to draw it all at once here. The
         rectangle will be entirely within a rectangle on the same device context
         previously painted with L{DrawToolBarBackground}.

        """

        dc.SetPen(self._toolbar_border_pen)
        dc.SetBrush(wx.TRANSPARENT_BRUSH)
        dc.DrawRectangle(rect.x, rect.y, rect.width, rect.height)
        bg_rect = wx.Rect(*rect)
        bg_rect.Deflate(1, 1)
        dc.GradientFillLinear(bg_rect, self._tool_background_colour, self._tool_background_gradient_colour, wx.SOUTH)

[docs]    def DrawTool(self, dc, wnd, rect, bitmap, kind, state):
        """
        Draw a single tool (for a L{RibbonToolBar} control).

        :param `dc`: The device context to draw onto;
        :param `wnd`: The window which is being drawn onto. In most cases this will
         be a L{RibbonToolBar}, but it doesn't have to be;
        :param `rect`: The rectangle within which to draw. The size of this rectangle
         will at least the size returned by L{RibbonMSWArtProvider.GetToolSize}, and the height of it will
         be equal for all tools within the same group. The rectangle will be entirely
         within a rectangle on the same device context previously painted with
         L{DrawToolGroupBackground};
        :param `bitmap`: The bitmap to use as the tool's foreground. If the tool is a
         hybrid or dropdown tool, then the foreground should also contain a standard
         dropdown button;
        :param `kind`: The kind of tool to draw (normal, dropdown, or hybrid);
        :param `state`: A combination of `RibbonToolBarToolState` flags giving the
         state of the tool and it's relative position within a tool group.

        """

        bg_rect = wx.Rect(*rect)
        bg_rect.Deflate(1, 1)

        if state & RIBBON_TOOLBAR_TOOL_LAST == 0:
            bg_rect.width += 1

        is_custom_bg = (state & (RIBBON_TOOLBAR_TOOL_HOVER_MASK | RIBBON_TOOLBAR_TOOL_ACTIVE_MASK)) != 0
        is_split_hybrid = kind == RIBBON_BUTTON_HYBRID and is_custom_bg

        # Background
        if is_custom_bg:
            dc.SetPen(wx.TRANSPARENT_PEN)
            dc.SetBrush(self._tool_hover_background_brush)
            dc.DrawRectangle(bg_rect.x, bg_rect.y, bg_rect.width, bg_rect.height)

            if state & RIBBON_TOOLBAR_TOOL_ACTIVE_MASK:
                active_rect = wx.Rect(*bg_rect)

                if kind == RIBBON_BUTTON_HYBRID:
                    active_rect.width -= 8

                    if state & RIBBON_TOOLBAR_TOOL_DROPDOWN_ACTIVE:
                        active_rect.x += active_rect.width
                        active_rect.width = 8

                dc.SetBrush(self._tool_active_background_brush)
                dc.DrawRectangle(active_rect.x, active_rect.y, active_rect.width, active_rect.height)

        # Border
        if is_custom_bg:
            dc.SetPen(self._toolbar_hover_borden_pen)
        else:
            dc.SetPen(self._toolbar_border_pen)

        if state & RIBBON_TOOLBAR_TOOL_FIRST == 0:
            existing = dc.GetPixel(rect.x, rect.y + 1)

            if existing == wx.NullColour or existing != self._toolbar_hover_borden_pen.GetColour():
                dc.DrawLine(rect.x, rect.y + 1, rect.x, rect.y + rect.height - 1)

        if is_custom_bg:
            border_rect = wx.Rect(*bg_rect)
            border_rect.Inflate(1, 1)
            dc.SetBrush(wx.TRANSPARENT_BRUSH)
            dc.DrawRectangle(border_rect.x, border_rect.y, border_rect.width, border_rect.height)

        # Foreground
        avail_width = bg_rect.GetWidth()

        if kind != RIBBON_BUTTON_NORMAL:
            avail_width -= 8
            if is_split_hybrid:
                dc.DrawLine(rect.x + avail_width + 1, rect.y, rect.x + avail_width + 1, rect.y + rect.height)

            dc.DrawBitmap(self._toolbar_drop_bitmap, bg_rect.x + avail_width + 2, bg_rect.y + (bg_rect.height / 2) - 2, True)

        dc.DrawBitmap(bitmap, bg_rect.x + (avail_width - bitmap.GetWidth()) / 2, bg_rect.y + (bg_rect.height - bitmap.GetHeight()) / 2, True)

Navigation

  • index
  • modules |
  • Home |
  • Gallery |
  • Contents»
  • Module code »
  • ribbon.art_aui


ribbon.art_internal

  • modules |
  • Home |
  • Gallery |
  • Contents»
  • Module code »
  • ribbon.art_internal

Source code for ribbon.art_internal

"""
This module contains methods used throughout the L{RibbonBar} library.
"""

import wx
import math

[docs]def RibbonInterpolateColour(start_colour, end_colour, position, start_position, end_position):

    if position <= start_position:
        return start_colour

    if position >= end_position:
        return end_colour

    position -= start_position
    end_position -= start_position
    r = end_colour.Red() - start_colour.Red()
    g = end_colour.Green() - start_colour.Green()
    b = end_colour.Blue() - start_colour.Blue()
    r = start_colour.Red()   + (((r * position * 100) / end_position) / 100)
    g = start_colour.Green() + (((g * position * 100) / end_position) / 100)
    b = start_colour.Blue()  + (((b * position * 100) / end_position) / 100)

    return wx.Colour(r, g, b)

[docs]def RibbonShiftLuminance(colour, amount):

    if amount <= 1.0:
        return colour.Darker(colour.luminance * (1.0 - amount))
    else:
        return colour.Lighter((1.0 - colour.luminance) * (amount - 1.0))

[docs]def RibbonCanLabelBreakAtPosition(label, pos):

    return label[pos] == ' '

[docs]def RibbonDrawParallelGradientLines(dc, nlines, line_origins, stepx, stepy, numsteps, offset_x,
                                    offset_y, start_colour, end_colour):

    rd = end_colour.Red() - start_colour.Red()
    gd = end_colour.Green() - start_colour.Green()
    bd = end_colour.Blue() - start_colour.Blue()

    for step in xrange(numsteps):
        r = start_colour.Red() + (((step*rd*100)/numsteps)/100)
        g = start_colour.Green() + (((step*gd*100)/numsteps)/100)
        b = start_colour.Blue() + (((step*bd*100)/numsteps)/100)

        p = wx.Pen(wx.Colour(r, g, b))
        dc.SetPen(p)

        for n in xrange(nlines):
            dc.DrawLine(offset_x + line_origins[n].x, offset_y + line_origins[n].y,
                        offset_x + line_origins[n].x + stepx, offset_y + line_origins[n].y + stepy)

        offset_x += stepx
        offset_y += stepy

[docs]def RibbonLoadPixmap(bits, fore):

    xpm = wx.BitmapFromXPMData(bits).ConvertToImage()
    xpm.Replace(255, 0, 255, fore.Red(), fore.Green(), fore.Blue())
    return wx.BitmapFromImage(xpm)

[docs]class RibbonHSLColour(object):

[docs]    def __init__(self, h=0.0, s=0.0, l=0.0):

        if isinstance(h, wx.Colour):

            red, green, blue = h.Red()/255.0, h.Green()/255.0, h.Blue()/255.0
            Min = min(red, min(green, blue))
            Max = max(red, max(green, blue))
            luminance = 0.5 * (Max + Min)

            if Min == Max:
                # colour is a shade of grey
                hue = 0.0
                saturation = 0.0

            else:
                if luminance <= 0.5:
                    saturation = (Max - Min) / (Max + Min)
                else:
                    saturation = (Max - Min) / (2.0 - (Max + Min))

                if Max == red:
                    hue = 60.0 * (green - blue) / (Max - Min)
                    if hue < 0.0:
                        hue += 360.0

                elif Max == green:
                    hue = 60.0 * (blue - red) / (Max - Min)
                    hue += 120.0

                else: # Max == blue

                    hue = 60.0 * (red - green) / (Max - Min)
                    hue += 240.0

            self.hue = hue
            self.saturation = saturation
            self.luminance = luminance

        else:

            self.hue = h
            self.saturation = s
            self.luminance = l

[docs]    def ToRGB(self):

        _hue = (self.hue - math.floor(self.hue / 360.0) * 360.0)
        _saturation = self.saturation
        _luminance = self.luminance

        if _saturation > 1.0:
            _saturation = 1.0
        if _saturation < 0.0:
            _saturation = 0.0
        if _luminance > 1.0:
            _luminance = 1.0
        if _luminance < 0.0:
            _luminance = 0.0

        if _saturation == 0.0:
            # colour is a shade of grey
            red = blue = green = _luminance

        else:

            tmp2 = (_luminance < 0.5 and [_luminance*(1.0 + _saturation)] or [(_luminance+_saturation) - (_luminance*_saturation)])[0]
            tmp1 = 2.0 * _luminance - tmp2
            tmp3R = _hue + 120.0

            if tmp3R > 360.0:
                tmp3R -= 360.0
            if tmp3R < 60.0:
                red = tmp1 + (tmp2 - tmp1) * tmp3R / 60.0
            elif tmp3R < 180.0:
                red = tmp2
            elif tmp3R < 240.0:
                red = tmp1 + (tmp2 - tmp1) * (240.0 - tmp3R) / 60.0
            else:
                red = tmp1

            tmp3G = _hue

            if tmp3G > 360.0:
                tmp3G -= 360.0
            if tmp3G < 60.0:
                green = tmp1 + (tmp2 - tmp1) * tmp3G / 60.0
            elif tmp3G < 180.0:
                green = tmp2
            elif tmp3G < 240.0:
                green = tmp1 + (tmp2 - tmp1) * (240.0 - tmp3G) / 60.0
            else:
                green = tmp1

            tmp3B = _hue + 240.0

            if tmp3B > 360.0:
                tmp3B -= 360.0
            if tmp3B < 60.0:
                blue = tmp1 + (tmp2 - tmp1) * tmp3B / 60.0
            elif tmp3B < 180.0:
                blue = tmp2
            elif tmp3B < 240.0:
                blue = tmp1 + (tmp2 - tmp1) * (240.0 - tmp3B) / 60.0
            else:
                blue = tmp1

        return wx.Colour(red * 255.0, green * 255.0, blue * 255.0)

[docs]    def Darker(self, delta):

        return self.Lighter(-delta)

[docs]    def MakeDarker(self, delta):

        self.luminance -= delta
        return self

[docs]    def Lighter(self, delta):

        return RibbonHSLColour(self.hue, self.saturation, self.luminance + delta)

[docs]    def Saturated(self, delta):

        return RibbonHSLColour(self.hue, self.saturation + delta, self.luminance)

[docs]    def Desaturated(self, delta):

        return self.Saturated(-delta)

[docs]    def ShiftHue(self, delta):

        return RibbonHSLColour(self.hue + delta, self.saturation, self.luminance)

[docs]class RibbonPageTabInfo(object):

[docs]    def __init__(self):

        self.page = -1
        self.active = False
        self.hovererd = False
        self.rect = wx.Rect()
        self.ideal_width = 0
        self.small_begin_need_separator_width = 0
        self.small_must_have_separator_width = 0
        self.minimum_width = 0

Navigation

  • index
  • modules |
  • Home |
  • Gallery |
  • Contents»
  • Module code »
  • ribbon.art_internal


ribbon.art_msw

  • modules |
  • Home |
  • Gallery |
  • Contents»
  • Module code »
  • ribbon.art_msw

Source code for ribbon.art_msw

"""
L{RibbonMSWArtProvider} is responsible for drawing all the components of the ribbon
interface using a Windows appearance.

Description
===========

This allows a ribbon bar to have a pluggable look-and-feel, while retaining the same
underlying behaviour. As a single art provider is used for all ribbon components, a
ribbon bar usually has a consistent (though unique) appearance.

By default, a L{RibbonBar} uses an instance of a class called `RibbonDefaultArtProvider`,
which resolves to `RibbonAUIArtProvider`, `RibbonMSWArtProvider`, or `RibbonOSXArtProvider`
- whichever is most appropriate to the current platform. These art providers are all
slightly configurable with regard to colours and fonts, but for larger modifications,
you can derive from one of these classes, or write a completely new art provider class.

Call L{RibbonBar.SetArtProvider} to change the art provider being used.

See Also
========

L{RibbonBar}
"""

import wx
import types

from math import cos
from math import pi as M_PI

import panel as PANEL
import page as PAGE

from art_internal import RibbonLoadPixmap, RibbonInterpolateColour, RibbonDrawParallelGradientLines
from art_internal import RibbonCanLabelBreakAtPosition
from art_internal import RibbonHSLColour

from art import *

gallery_up_xpm = ["5 5 2 1", "  c None", "x c #FF00FF", "     ", "  x  ", " xxx ", "xxxxx", "     "]
gallery_down_xpm = ["5 5 2 1", "  c None", "x c #FF00FF", "     ", "xxxxx", " xxx ", "  x  ", "     "]
gallery_left_xpm = ["5 5 2 1", "  c None", "x c #FF00FF", "   x ", "  xx ", " xxx ", "  xx ", "   x "]
gallery_right_xpm = ["5 5 2 1", "  c None", "x c #FF00FF", " x   ", " xx  ", " xxx ", " xx  ", " x   "]
gallery_extension_xpm = ["5 5 2 1", "  c None", "x c #FF00FF", "xxxxx", "     ", "xxxxx", " xxx ", "  x  "]

[docs]def LikePrimary(primary_hsl, is_gray, h, s, l):

    return primary_hsl.ShiftHue(h).Saturated((is_gray and [0] or [s])[0]).Lighter(l).ToRGB()

[docs]def LikeSecondary(secondary_hsl, is_gray, h, s, l):

    return secondary_hsl.ShiftHue(h).Saturated((is_gray and [0] or [s])[0]).Lighter(l).ToRGB()

[docs]def SingleLine(dc, rect, start, finish):

    dc.DrawLine(start.x + rect.x, start.y + rect.y, finish.x + rect.x, finish.y + rect.y)

[docs]class RibbonMSWArtProvider(object):

[docs]    def __init__(self, set_colour_scheme=True):

        self._flags = 0
        self._tab_label_font = wx.NORMAL_FONT
        self._button_bar_label_font = wx.NORMAL_FONT
        self._panel_label_font = wx.NORMAL_FONT

        self._gallery_up_bitmap = [wx.NullBitmap for i in xrange(4)]
        self._gallery_down_bitmap = [wx.NullBitmap for i in xrange(4)]
        self._gallery_extension_bitmap = [wx.NullBitmap for i in xrange(4)]

        if set_colour_scheme:
            self.SetColourScheme(wx.Colour(194, 216, 241), wx.Colour(255, 223, 114), wx.Colour(0, 0, 0))

        self._cached_tab_separator_visibility = -10.0 # valid visibilities are in range [0, 1]
        self._tab_separation_size = 3
        self._page_border_left = 2
        self._page_border_top = 1
        self._page_border_right = 2
        self._page_border_bottom = 3
        self._panel_x_separation_size = 1
        self._panel_y_separation_size = 1
        self._tool_group_separation_size = 3
        self._gallery_bitmap_padding_left_size = 4
        self._gallery_bitmap_padding_right_size = 4
        self._gallery_bitmap_padding_top_size = 4
        self._gallery_bitmap_padding_bottom__size = 4
        self._cached_tab_separator = wx.NullBitmap

[docs]    def GetColourScheme(self, primary, secondary, tertiary):
        """
        Get the current colour scheme.

        Returns three colours such that if L{SetColourScheme} were called with them, the
        colour scheme would be restored to what it was when L{SetColourScheme} was last
        called. In practice, this usually means that the returned values are the three
        colours given in the last call to L{SetColourScheme}, however if
        L{SetColourScheme} performs an idempotent operation upon the colours it is given
        (like clamping a component of the colour), then the returned values may not be
        the three colours given in the last call to L{SetColourScheme}.

        If L{SetColourScheme} has not been called, then the returned values should result
        in a colour scheme similar to, if not identical to, the default colours of the
        art provider. Note that if L{SetColour} is called, then L{GetColourScheme} does
        not try and return a colour scheme similar to colours being used - it's return
        values are dependant upon the last values given to L{SetColourScheme}, as
        described above.

        :param `primary`: Pointer to a location to store the primary colour, or ``None``;
        :param `secondary`: Pointer to a location to store the secondary colour, or ``None``;
        :param `tertiary`: Pointer to a location to store the tertiary colour, or ``None``.

        """

        if primary != None:
            primary = self._primary_scheme_colour
        if secondary != None:
            secondary = self._secondary_scheme_colour
        if tertiary != None:
            tertiary = self._tertiary_scheme_colour

        return primary, secondary, tertiary

[docs]    def SetColourScheme(self, primary, secondary, tertiary):
        """
        Set all applicable colour settings from a few base colours.

        Uses any or all of the three given colours to create a colour scheme, and then
        sets all colour settings which are relevant to the art provider using that
        scheme. Note that some art providers may not use the tertiary colour for
        anything, and some may not use the secondary colour either.

        :param `primary`: MISSING DESCRIPTION;
        :param `secondary`: MISSING DESCRIPTION;
        :param `tertiary`: MISSING DESCRIPTION.

        :see: L{SetColour}, L{GetColourScheme}
        """

        self._primary_scheme_colour = primary
        self._secondary_scheme_colour = secondary
        self._tertiary_scheme_colour = tertiary

        primary_hsl = RibbonHSLColour(primary)
        secondary_hsl = RibbonHSLColour(secondary)
        # tertiary not used for anything

        # Map primary saturation from [0, 1] to [.25, .75]
        primary_is_gray = False
        gray_saturation_threshold = 0.01

        if primary_hsl.saturation <= gray_saturation_threshold:
            primary_is_gray = True
        else:
            primary_hsl.saturation = cos(primary_hsl.saturation * M_PI) * -0.25 + 0.5

        # Map primary luminance from [0, 1] to [.23, .83]
        primary_hsl.luminance = cos(primary_hsl.luminance * M_PI) * -0.3 + 0.53

        # Map secondary saturation from [0, 1] to [0.16, 0.84]
        secondary_is_gray = False

        if secondary_hsl.saturation <= gray_saturation_threshold:
            secondary_is_gray = True
        else:
            secondary_hsl.saturation = cos(secondary_hsl.saturation * M_PI) * -0.34 + 0.5

        # Map secondary luminance from [0, 1] to [0.1, 0.9]
        secondary_hsl.luminance = cos(secondary_hsl.luminance * M_PI) * -0.4 + 0.5

        self._page_border_pen = wx.Pen(LikePrimary(primary_hsl, primary_is_gray, 1.4, 0.00, -0.08))
        self._page_background_top_colour = LikePrimary(primary_hsl, primary_is_gray, -0.1, -0.03, 0.12)
        self._page_hover_background_top_colour = LikePrimary(primary_hsl, primary_is_gray, -2.8, 0.27, 0.17)
        self._page_background_top_gradient_colour = LikePrimary(primary_hsl, primary_is_gray, 0.1, -0.10, 0.08)
        self._page_hover_background_top_gradient_colour = LikePrimary(primary_hsl, primary_is_gray, 3.2, 0.16, 0.13)
        self._page_background_colour = LikePrimary(primary_hsl, primary_is_gray, 0.4, -0.09, 0.05)
        self._page_hover_background_colour = LikePrimary(primary_hsl, primary_is_gray, 0.1, 0.19, 0.10)
        self._page_background_gradient_colour = LikePrimary(primary_hsl, primary_is_gray, -3.2, 0.27, 0.10)
        self._page_hover_background_gradient_colour = LikePrimary(primary_hsl, primary_is_gray, 1.8, 0.01, 0.15)

        self._tab_active_background_colour = LikePrimary(primary_hsl, primary_is_gray, -0.1, -0.31, 0.16)
        self._tab_active_background_gradient_colour = LikePrimary(primary_hsl, primary_is_gray, -0.1, -0.03, 0.12)
        self._tab_separator_colour = LikePrimary(primary_hsl, primary_is_gray, 0.9, 0.24, 0.05)
        self._tab_ctrl_background_brush = wx.Brush(LikePrimary(primary_hsl, primary_is_gray, 1.0, 0.39, 0.07))
        self._tab_hover_background_colour = LikePrimary(primary_hsl, primary_is_gray, 1.3, 0.15, 0.10)
        self._tab_hover_background_top_colour = LikePrimary(primary_hsl, primary_is_gray, 1.4, 0.36, 0.08)
        self._tab_border_pen = wx.Pen(LikePrimary(primary_hsl, primary_is_gray, 1.4, 0.03, -0.05)  )
        self._tab_separator_gradient_colour = LikePrimary(primary_hsl, primary_is_gray, 1.7, -0.15, -0.18)
        self._tab_hover_background_top_gradient_colour = LikePrimary(primary_hsl, primary_is_gray, 1.8, 0.34, 0.13)
        self._tab_label_colour = LikePrimary(primary_hsl, primary_is_gray, 4.3, 0.13, -0.49)
        self._tab_hover_background_gradient_colour = LikeSecondary(primary_hsl, secondary_is_gray, -1.5, -0.34, 0.01)

        self._panel_minimised_border_gradient_pen = wx.Pen(LikePrimary(primary_hsl, primary_is_gray, -6.9, -0.17, -0.09))
        self._panel_minimised_border_pen = wx.Pen(LikePrimary(primary_hsl, primary_is_gray, -5.3, -0.24, -0.06))
        self._panel_border_gradient_pen = wx.Pen(LikePrimary(primary_hsl, primary_is_gray, -5.2, -0.15, -0.06))
        self._panel_border_pen = wx.Pen(LikePrimary(primary_hsl, primary_is_gray, -2.8, -0.32, 0.02))
        self._panel_label_background_brush = wx.Brush(LikePrimary(primary_hsl, primary_is_gray, -1.5, 0.03, 0.05))
        self._panel_active_background_gradient_colour = LikePrimary(primary_hsl, primary_is_gray, 0.5, 0.34, 0.05)
        self._panel_hover_label_background_brush = wx.Brush(LikePrimary(primary_hsl, primary_is_gray, 1.0, 0.30, 0.09))
        self._panel_active_background_top_gradient_colour = LikePrimary(primary_hsl, primary_is_gray, 1.4, -0.17, -0.13)
        self._panel_active_background_colour = LikePrimary(primary_hsl, primary_is_gray, 1.6, -0.18, -0.18)
        self._panel_active_background_top_colour = LikePrimary(primary_hsl, primary_is_gray, 1.7, -0.20, -0.03)
        self._panel_label_colour = LikePrimary(primary_hsl, primary_is_gray, 2.8, -0.14, -0.35)
        self._panel_hover_label_colour = self._panel_label_colour
        self._panel_minimised_label_colour = self._tab_label_colour

        self._gallery_button_disabled_background_colour = LikePrimary(primary_hsl, primary_is_gray, -2.8, -0.46, 0.09)
        self._gallery_button_disabled_background_top_brush = wx.Brush(LikePrimary(primary_hsl, primary_is_gray, -2.8, -0.36, 0.15))
        self._gallery_hover_background_brush = wx.Brush(LikePrimary(primary_hsl, primary_is_gray, -0.8, 0.05, 0.15))
        self._gallery_border_pen = wx.Pen(LikePrimary(primary_hsl, primary_is_gray, 0.7, -0.02, 0.03))
        self._gallery_button_background_top_brush = wx.Brush(LikePrimary(primary_hsl, primary_is_gray, 0.8, 0.34, 0.13))
        self._gallery_button_background_colour = LikePrimary(primary_hsl, primary_is_gray, 1.3, 0.10, 0.08)

        # SetColour used so that the relevant bitmaps are generated
        self.SetColour(RIBBON_ART_GALLERY_BUTTON_FACE_COLOUR, LikePrimary(primary_hsl, primary_is_gray, 1.4, -0.21, -0.23))
        self.SetColour(RIBBON_ART_GALLERY_BUTTON_HOVER_FACE_COLOUR, LikePrimary(primary_hsl, primary_is_gray, 1.5, -0.24, -0.29))
        self.SetColour(RIBBON_ART_GALLERY_BUTTON_ACTIVE_FACE_COLOUR, LikePrimary(primary_hsl, primary_is_gray, 1.5, -0.24, -0.29))
        self.SetColour(RIBBON_ART_GALLERY_BUTTON_DISABLED_FACE_COLOUR, LikePrimary(primary_hsl, primary_is_gray, 0.0, -1.0, 0.0))
        self._gallery_button_disabled_background_gradient_colour = LikePrimary(primary_hsl, primary_is_gray, 1.5, -0.43, 0.12)
        self._gallery_button_background_gradient_colour = LikePrimary(primary_hsl, primary_is_gray, 1.7, 0.11, 0.09)
        self._gallery_item_border_pen = wx.Pen(LikeSecondary(secondary_hsl, secondary_is_gray, -3.9, -0.16, -0.14))
        self._gallery_button_hover_background_colour = LikeSecondary(secondary_hsl, secondary_is_gray, -0.9, 0.16, -0.07)
        self._gallery_button_hover_background_gradient_colour = LikeSecondary(secondary_hsl, secondary_is_gray, 0.1, 0.12, 0.03)
        self._gallery_button_hover_background_top_brush = wx.Brush(LikeSecondary(secondary_hsl, secondary_is_gray, 4.3, 0.16, 0.17))

        self._gallery_button_active_background_colour = LikeSecondary(secondary_hsl, secondary_is_gray, -9.9, 0.03, -0.22)
        self._gallery_button_active_background_gradient_colour = LikeSecondary(secondary_hsl, secondary_is_gray, -9.5, 0.14, -0.11)
        self._gallery_button_active_background_top_brush = wx.Brush(LikeSecondary(secondary_hsl, secondary_is_gray, -9.0, 0.15, -0.08))

        self._button_bar_label_colour = self._tab_label_colour
        self._button_bar_hover_border_pen = wx.Pen(LikeSecondary(secondary_hsl, secondary_is_gray, -6.2, -0.47, -0.14))
        self._button_bar_hover_background_gradient_colour = LikeSecondary(secondary_hsl, secondary_is_gray, -0.6, 0.16, 0.04)
        self._button_bar_hover_background_colour = LikeSecondary(secondary_hsl, secondary_is_gray, -0.2, 0.16, -0.10)
        self._button_bar_hover_background_top_gradient_colour = LikeSecondary(secondary_hsl, secondary_is_gray, 0.2, 0.16, 0.03)
        self._button_bar_hover_background_top_colour = LikeSecondary(secondary_hsl, secondary_is_gray, 8.8, 0.16, 0.17)
        self._button_bar_active_border_pen = wx.Pen(LikeSecondary(secondary_hsl, secondary_is_gray, -6.2, -0.47, -0.25))
        self._button_bar_active_background_top_colour = LikeSecondary(secondary_hsl, secondary_is_gray, -8.4, 0.08, 0.06)
        self._button_bar_active_background_top_gradient_colour = LikeSecondary(secondary_hsl, secondary_is_gray, -9.7, 0.13, -0.07)
        self._button_bar_active_background_colour = LikeSecondary(secondary_hsl, secondary_is_gray, -9.9, 0.14, -0.14)
        self._button_bar_active_background_gradient_colour = LikeSecondary(secondary_hsl, secondary_is_gray, -8.7, 0.17, -0.03)

        self._toolbar_border_pen = wx.Pen(LikePrimary(primary_hsl, primary_is_gray, 1.4, -0.21, -0.16))
        self.SetColour(RIBBON_ART_TOOLBAR_FACE_COLOUR, LikePrimary(primary_hsl, primary_is_gray, 1.4, -0.17, -0.22))
        self._tool_background_top_colour = LikePrimary(primary_hsl, primary_is_gray, -1.9, -0.07, 0.06)
        self._tool_background_top_gradient_colour = LikePrimary(primary_hsl, primary_is_gray, 1.4, 0.12, 0.08)
        self._tool_background_colour = LikePrimary(primary_hsl, primary_is_gray, 1.4, -0.09, 0.03)
        self._tool_background_gradient_colour = LikePrimary(primary_hsl, primary_is_gray, 1.9, 0.11, 0.09)
        self._tool_hover_background_top_colour = LikeSecondary(secondary_hsl, secondary_is_gray, 3.4, 0.11, 0.16)
        self._tool_hover_background_top_gradient_colour = LikeSecondary(secondary_hsl, secondary_is_gray, -1.4, 0.04, 0.08)
        self._tool_hover_background_colour = LikeSecondary(secondary_hsl, secondary_is_gray, -1.8, 0.16, -0.12)
        self._tool_hover_background_gradient_colour = LikeSecondary(secondary_hsl, secondary_is_gray, -2.6, 0.16, 0.05)
        self._tool_active_background_top_colour = LikeSecondary(secondary_hsl, secondary_is_gray, -9.9, -0.12, -0.09)
        self._tool_active_background_top_gradient_colour = LikeSecondary(secondary_hsl, secondary_is_gray, -8.5, 0.16, -0.12)
        self._tool_active_background_colour = LikeSecondary(secondary_hsl, secondary_is_gray, -7.9, 0.16, -0.20)
        self._tool_active_background_gradient_colour = LikeSecondary(secondary_hsl, secondary_is_gray, -6.6, 0.16, -0.10)

        # Invalidate cached tab separator
        self._cached_tab_separator_visibility = -1.0

[docs]    def Clone(self):
        """
        Create a new art provider which is a clone of this one.
        """

        copy = RibbonMSWArtProvider()
        self.CloneTo(copy)
        return copy

[docs]    def CloneTo(self, copy):

        for i in xrange(4):
            copy._gallery_up_bitmap[i] = self._gallery_up_bitmap[i]
            copy._gallery_down_bitmap[i] = self._gallery_down_bitmap[i]
            copy._gallery_extension_bitmap[i] = self._gallery_extension_bitmap[i]

        copy._toolbar_drop_bitmap = self._toolbar_drop_bitmap

        copy._primary_scheme_colour = self._primary_scheme_colour
        copy._secondary_scheme_colour = self._secondary_scheme_colour
        copy._tertiary_scheme_colour = self._tertiary_scheme_colour

        copy._button_bar_label_colour = self._button_bar_label_colour
        copy._tab_label_colour = self._tab_label_colour
        copy._tab_separator_colour = self._tab_separator_colour
        copy._tab_separator_gradient_colour = self._tab_separator_gradient_colour
        copy._tab_active_background_colour = self._tab_hover_background_colour
        copy._tab_active_background_gradient_colour = self._tab_hover_background_gradient_colour
        copy._tab_hover_background_colour = self._tab_hover_background_colour
        copy._tab_hover_background_gradient_colour = self._tab_hover_background_gradient_colour
        copy._tab_hover_background_top_colour = self._tab_hover_background_top_colour
        copy._tab_hover_background_top_gradient_colour = self._tab_hover_background_top_gradient_colour
        copy._panel_label_colour = self._panel_label_colour
        copy._panel_hover_label_colour = self._panel_hover_label_colour
        copy._panel_minimised_label_colour = self._panel_minimised_label_colour
        copy._panel_active_background_colour = self._panel_active_background_colour
        copy._panel_active_background_gradient_colour = self._panel_active_background_gradient_colour
        copy._panel_active_background_top_colour = self._panel_active_background_top_colour
        copy._panel_active_background_top_gradient_colour = self._panel_active_background_top_gradient_colour
        copy._page_background_colour = self._page_background_colour
        copy._page_background_gradient_colour = self._page_background_gradient_colour
        copy._page_background_top_colour = self._page_background_top_colour
        copy._page_background_top_gradient_colour = self._page_background_top_gradient_colour
        copy._page_hover_background_colour = self._page_hover_background_colour
        copy._page_hover_background_gradient_colour = self._page_hover_background_gradient_colour
        copy._page_hover_background_top_colour = self._page_hover_background_top_colour
        copy._page_hover_background_top_gradient_colour = self._page_hover_background_top_gradient_colour
        copy._button_bar_hover_background_colour = self._button_bar_hover_background_colour
        copy._button_bar_hover_background_gradient_colour = self._button_bar_hover_background_gradient_colour
        copy._button_bar_hover_background_top_colour = self._button_bar_hover_background_top_colour
        copy._button_bar_hover_background_top_gradient_colour = self._button_bar_hover_background_top_gradient_colour
        copy._button_bar_active_background_colour = self._button_bar_active_background_colour
        copy._button_bar_active_background_gradient_colour = self._button_bar_active_background_gradient_colour
        copy._button_bar_active_background_top_colour = self._button_bar_active_background_top_colour
        copy._button_bar_active_background_top_gradient_colour = self._button_bar_active_background_top_gradient_colour
        copy._gallery_button_background_colour = self._gallery_button_background_colour
        copy._gallery_button_background_gradient_colour = self._gallery_button_background_gradient_colour
        copy._gallery_button_hover_background_colour = self._gallery_button_hover_background_colour
        copy._gallery_button_hover_background_gradient_colour = self._gallery_button_hover_background_gradient_colour
        copy._gallery_button_active_background_colour = self._gallery_button_active_background_colour
        copy._gallery_button_active_background_gradient_colour = self._gallery_button_active_background_gradient_colour
        copy._gallery_button_disabled_background_colour = self._gallery_button_disabled_background_colour
        copy._gallery_button_disabled_background_gradient_colour = self._gallery_button_disabled_background_gradient_colour
        copy._gallery_button_face_colour = self._gallery_button_face_colour
        copy._gallery_button_hover_face_colour = self._gallery_button_hover_face_colour
        copy._gallery_button_active_face_colour = self._gallery_button_active_face_colour
        copy._gallery_button_disabled_face_colour = self._gallery_button_disabled_face_colour

        copy._tab_ctrl_background_brush = self._tab_ctrl_background_brush
        copy._panel_label_background_brush = self._panel_label_background_brush
        copy._panel_hover_label_background_brush = self._panel_hover_label_background_brush
        copy._gallery_hover_background_brush = self._gallery_hover_background_brush
        copy._gallery_button_background_top_brush = self._gallery_button_background_top_brush
        copy._gallery_button_hover_background_top_brush = self._gallery_button_hover_background_top_brush
        copy._gallery_button_active_background_top_brush = self._gallery_button_active_background_top_brush
        copy._gallery_button_disabled_background_top_brush = self._gallery_button_disabled_background_top_brush

        copy._tab_label_font = self._tab_label_font
        copy._button_bar_label_font = self._button_bar_label_font
        copy._panel_label_font = self._panel_label_font

        copy._page_border_pen = self._page_border_pen
        copy._panel_border_pen = self._panel_border_pen
        copy._panel_border_gradient_pen = self._panel_border_gradient_pen
        copy._panel_minimised_border_pen = self._panel_minimised_border_pen
        copy._panel_minimised_border_gradient_pen = self._panel_minimised_border_gradient_pen
        copy._tab_border_pen = self._tab_border_pen
        copy._gallery_border_pen = self._gallery_border_pen
        copy._button_bar_hover_border_pen = self._button_bar_hover_border_pen
        copy._button_bar_active_border_pen = self._button_bar_active_border_pen
        copy._gallery_item_border_pen = self._gallery_item_border_pen
        copy._toolbar_border_pen = self._toolbar_border_pen

        copy._flags = self._flags
        copy._tab_separation_size = self._tab_separation_size
        copy._page_border_left = self._page_border_left
        copy._page_border_top = self._page_border_top
        copy._page_border_right = self._page_border_right
        copy._page_border_bottom = self._page_border_bottom
        copy._panel_x_separation_size = self._panel_x_separation_size
        copy._panel_y_separation_size = self._panel_y_separation_size
        copy._gallery_bitmap_padding_left_size = self._gallery_bitmap_padding_left_size
        copy._gallery_bitmap_padding_right_size = self._gallery_bitmap_padding_right_size
        copy._gallery_bitmap_padding_top_size = self._gallery_bitmap_padding_top_size
        copy._gallery_bitmap_padding_bottom__size = self._gallery_bitmap_padding_bottom__size

[docs]    def GetFlags(self):
        """
        Get the previously set style flags.
        """

        return self._flags

[docs]    def SetFlags(self, flags):
        """
        Set the style flags.

        Normally called automatically by L{RibbonBar.SetArtProvider} with the ribbon
        bar's style flags, so that the art provider has the same flags as the bar which
        it is serving.

        :param `flags`: MISSING DESCRIPTION.

        """

        if (flags ^ self._flags) & RIBBON_BAR_FLOW_VERTICAL:
            if flags & RIBBON_BAR_FLOW_VERTICAL:
                self._page_border_left += 1
                self._page_border_right += 1
                self._page_border_top -= 1
                self._page_border_bottom -= 1
            else:
                self._page_border_left -= 1
                self._page_border_right -= 1
                self._page_border_top += 1
                self._page_border_bottom += 1

        self._flags = flags

        # Need to reload some bitmaps when flags change
        self.Reload(RIBBON_ART_GALLERY_BUTTON_FACE_COLOUR)
        self.Reload(RIBBON_ART_GALLERY_BUTTON_HOVER_FACE_COLOUR)
        self.Reload(RIBBON_ART_GALLERY_BUTTON_ACTIVE_FACE_COLOUR)
        self.Reload(RIBBON_ART_GALLERY_BUTTON_DISABLED_FACE_COLOUR)

[docs]    def Reload(self, setting):

        self.SetColour(setting, self.GetColour(setting))

[docs]    def GetMetric(self, id):
        """
        Get the value of a certain integer setting.

        can be one of the size values of `RibbonArtSetting`.

        :param `id`: a metric id.

        """

        if id == RIBBON_ART_TAB_SEPARATION_SIZE:
            return self._tab_separation_size
        elif id == RIBBON_ART_PAGE_BORDER_LEFT_SIZE:
            return self._page_border_left
        elif id == RIBBON_ART_PAGE_BORDER_TOP_SIZE:
            return self._page_border_top
        elif id == RIBBON_ART_PAGE_BORDER_RIGHT_SIZE:
            return self._page_border_right
        elif id == RIBBON_ART_PAGE_BORDER_BOTTOM_SIZE:
            return self._page_border_bottom
        elif id == RIBBON_ART_PANEL_X_SEPARATION_SIZE:
            return self._panel_x_separation_size
        elif id == RIBBON_ART_PANEL_Y_SEPARATION_SIZE:
            return self._panel_y_separation_size
        elif id == RIBBON_ART_TOOL_GROUP_SEPARATION_SIZE:
            return self._tool_group_separation_size
        elif id == RIBBON_ART_GALLERY_BITMAP_PADDING_LEFT_SIZE:
            return self._gallery_bitmap_padding_left_size
        elif id == RIBBON_ART_GALLERY_BITMAP_PADDING_RIGHT_SIZE:
            return self._gallery_bitmap_padding_right_size
        elif id == RIBBON_ART_GALLERY_BITMAP_PADDING_TOP_SIZE:
            return self._gallery_bitmap_padding_top_size
        elif id == RIBBON_ART_GALLERY_BITMAP_PADDING_BOTTOM_SIZE:
            return self._gallery_bitmap_padding_bottom__size
        else:
            raise Exception("Invalid Metric Ordinal")

[docs]    def SetMetric(self, id, new_val):
        """
        Set the value of a certain integer setting to the value.

        can be one of the size values of `RibbonArtSetting`.

        :param `id`: a metric id;
        :param `new_val`: the new value of the metric setting.

        """

        if id == RIBBON_ART_TAB_SEPARATION_SIZE:
            self._tab_separation_size = new_val
        elif id == RIBBON_ART_PAGE_BORDER_LEFT_SIZE:
            self._page_border_left = new_val
        elif id == RIBBON_ART_PAGE_BORDER_TOP_SIZE:
            self._page_border_top = new_val
        elif id == RIBBON_ART_PAGE_BORDER_RIGHT_SIZE:
            self._page_border_right = new_val
        elif id == RIBBON_ART_PAGE_BORDER_BOTTOM_SIZE:
            self._page_border_bottom = new_val
        elif id == RIBBON_ART_PANEL_X_SEPARATION_SIZE:
            self._panel_x_separation_size = new_val
        elif id == RIBBON_ART_PANEL_Y_SEPARATION_SIZE:
            self._panel_y_separation_size = new_val
        elif id == RIBBON_ART_TOOL_GROUP_SEPARATION_SIZE:
            self._tool_group_separation_size = new_val
        elif id == RIBBON_ART_GALLERY_BITMAP_PADDING_LEFT_SIZE:
            self._gallery_bitmap_padding_left_size = new_val
        elif id == RIBBON_ART_GALLERY_BITMAP_PADDING_RIGHT_SIZE:
            self._gallery_bitmap_padding_right_size = new_val
        elif id == RIBBON_ART_GALLERY_BITMAP_PADDING_TOP_SIZE:
            self._gallery_bitmap_padding_top_size = new_val
        elif id == RIBBON_ART_GALLERY_BITMAP_PADDING_BOTTOM_SIZE:
            self._gallery_bitmap_padding_bottom__size = new_val
        else:
            raise Exception("Invalid Metric Ordinal")

[docs]    def SetFont(self, id, font):
        """
        Set the value of a certain font setting to the value.

        can be one of the font values of `RibbonArtSetting`.

        :param `id`: a font id;
        :param `font`: the new font.

        """

        if id == RIBBON_ART_TAB_LABEL_FONT:
            self._tab_label_font = font
        elif id == RIBBON_ART_BUTTON_BAR_LABEL_FONT:
            self._button_bar_label_font = font
        elif id == RIBBON_ART_PANEL_LABEL_FONT:
            self._panel_label_font = font
        else:
            raise Exception("Invalid Font Ordinal")

[docs]    def GetFont(self, id):
        """
        Get the value of a certain font setting.

        can be one of the font values of `RibbonArtSetting`.

        :param `id`: the font id.

        """

        if id == RIBBON_ART_TAB_LABEL_FONT:
            return self._tab_label_font
        elif id == RIBBON_ART_BUTTON_BAR_LABEL_FONT:
            return self._button_bar_label_font
        elif id == RIBBON_ART_PANEL_LABEL_FONT:
            return self._panel_label_font
        else:
            raise Exception("Invalid Font Ordinal")

[docs]    def GetColour(self, id):
        """
        Get the value of a certain colour setting.

        can be one of the colour values of `RibbonArtSetting`.

        :param `id`: the colour id.

        """

        if id == RIBBON_ART_BUTTON_BAR_LABEL_COLOUR:
            return self._button_bar_label_colour
        elif id == RIBBON_ART_BUTTON_BAR_HOVER_BORDER_COLOUR:
            return self._button_bar_hover_border_pen.GetColour()
        elif id == RIBBON_ART_BUTTON_BAR_HOVER_BACKGROUND_TOP_COLOUR:
            return self._button_bar_hover_background_top_colour
        elif id == RIBBON_ART_BUTTON_BAR_HOVER_BACKGROUND_TOP_GRADIENT_COLOUR:
            return self._button_bar_hover_background_top_gradient_colour
        elif id == RIBBON_ART_BUTTON_BAR_HOVER_BACKGROUND_COLOUR:
            return self._button_bar_hover_background_colour
        elif id == RIBBON_ART_BUTTON_BAR_HOVER_BACKGROUND_GRADIENT_COLOUR:
            return self._button_bar_hover_background_gradient_colour
        elif id == RIBBON_ART_BUTTON_BAR_ACTIVE_BORDER_COLOUR:
            return self._button_bar_active_border_pen.GetColour()
        elif id == RIBBON_ART_BUTTON_BAR_ACTIVE_BACKGROUND_TOP_COLOUR:
            return self._button_bar_active_background_top_colour
        elif id == RIBBON_ART_BUTTON_BAR_ACTIVE_BACKGROUND_TOP_GRADIENT_COLOUR:
            return self._button_bar_active_background_top_gradient_colour
        elif id == RIBBON_ART_BUTTON_BAR_ACTIVE_BACKGROUND_COLOUR:
            return self._button_bar_active_background_colour
        elif id == RIBBON_ART_BUTTON_BAR_ACTIVE_BACKGROUND_GRADIENT_COLOUR:
            return self._button_bar_active_background_gradient_colour
        elif id == RIBBON_ART_GALLERY_BORDER_COLOUR:
            return self._gallery_border_pen.GetColour()
        elif id == RIBBON_ART_GALLERY_HOVER_BACKGROUND_COLOUR:
            return self._gallery_hover_background_brush.GetColour()
        elif id == RIBBON_ART_GALLERY_BUTTON_BACKGROUND_COLOUR:
            return self._gallery_button_background_colour
        elif id == RIBBON_ART_GALLERY_BUTTON_BACKGROUND_GRADIENT_COLOUR:
            return self._gallery_button_background_gradient_colour
        elif id == RIBBON_ART_GALLERY_BUTTON_BACKGROUND_TOP_COLOUR:
            return self._gallery_button_background_top_brush.GetColour()
        elif id == RIBBON_ART_GALLERY_BUTTON_FACE_COLOUR:
            return self._gallery_button_face_colour
        elif id == RIBBON_ART_GALLERY_BUTTON_HOVER_BACKGROUND_COLOUR:
            return self._gallery_button_hover_background_colour
        elif id == RIBBON_ART_GALLERY_BUTTON_HOVER_BACKGROUND_GRADIENT_COLOUR:
            return self._gallery_button_hover_background_gradient_colour
        elif id == RIBBON_ART_GALLERY_BUTTON_HOVER_BACKGROUND_TOP_COLOUR:
            return self._gallery_button_hover_background_top_brush.GetColour()
        elif id == RIBBON_ART_GALLERY_BUTTON_HOVER_FACE_COLOUR:
            return self._gallery_button_face_colour
        elif id == RIBBON_ART_GALLERY_BUTTON_ACTIVE_BACKGROUND_COLOUR:
            return self._gallery_button_active_background_colour
        elif id == RIBBON_ART_GALLERY_BUTTON_ACTIVE_BACKGROUND_GRADIENT_COLOUR:
            return self._gallery_button_active_background_gradient_colour
        elif id == RIBBON_ART_GALLERY_BUTTON_ACTIVE_BACKGROUND_TOP_COLOUR:
            return self._gallery_button_background_top_brush.GetColour()
        elif id == RIBBON_ART_GALLERY_BUTTON_ACTIVE_FACE_COLOUR:
            return self._gallery_button_active_face_colour
        elif id == RIBBON_ART_GALLERY_BUTTON_DISABLED_BACKGROUND_COLOUR:
            return self._gallery_button_disabled_background_colour
        elif id == RIBBON_ART_GALLERY_BUTTON_DISABLED_BACKGROUND_GRADIENT_COLOUR:
            return self._gallery_button_disabled_background_gradient_colour
        elif id == RIBBON_ART_GALLERY_BUTTON_DISABLED_BACKGROUND_TOP_COLOUR:
            return self._gallery_button_disabled_background_top_brush.GetColour()
        elif id == RIBBON_ART_GALLERY_BUTTON_DISABLED_FACE_COLOUR:
            return self._gallery_button_disabled_face_colour
        elif id == RIBBON_ART_GALLERY_ITEM_BORDER_COLOUR:
            return self._gallery_item_border_pen.GetColour()
        elif id in [RIBBON_ART_TAB_CTRL_BACKGROUND_COLOUR, RIBBON_ART_TAB_CTRL_BACKGROUND_GRADIENT_COLOUR]:
            return self._tab_ctrl_background_brush.GetColour()
        elif id == RIBBON_ART_TAB_LABEL_COLOUR:
            return self._tab_label_colour
        elif id == RIBBON_ART_TAB_SEPARATOR_COLOUR:
            return self._tab_separator_colour
        elif id == RIBBON_ART_TAB_SEPARATOR_GRADIENT_COLOUR:
            return self._tab_separator_gradient_colour
        elif id in [RIBBON_ART_TAB_ACTIVE_BACKGROUND_TOP_COLOUR, RIBBON_ART_TAB_ACTIVE_BACKGROUND_TOP_GRADIENT_COLOUR]:
            return wx.Colour(0, 0, 0)
        elif id == RIBBON_ART_TAB_ACTIVE_BACKGROUND_COLOUR:
            return self._tab_active_background_colour
        elif id == RIBBON_ART_TAB_ACTIVE_BACKGROUND_GRADIENT_COLOUR:
            return self._tab_active_background_gradient_colour
        elif id == RIBBON_ART_TAB_HOVER_BACKGROUND_TOP_COLOUR:
            return self._tab_hover_background_top_colour
        elif id == RIBBON_ART_TAB_HOVER_BACKGROUND_TOP_GRADIENT_COLOUR:
            return self._tab_hover_background_top_gradient_colour
        elif id == RIBBON_ART_TAB_HOVER_BACKGROUND_COLOUR:
            return self._tab_hover_background_colour
        elif id == RIBBON_ART_TAB_HOVER_BACKGROUND_GRADIENT_COLOUR:
            return self._tab_hover_background_gradient_colour
        elif id == RIBBON_ART_TAB_BORDER_COLOUR:
            return self._tab_border_pen.GetColour()
        elif id == RIBBON_ART_PANEL_BORDER_COLOUR:
            return self._panel_border_pen.GetColour()
        elif id == RIBBON_ART_PANEL_BORDER_GRADIENT_COLOUR:
            return self._panel_border_gradient_pen.GetColour()
        elif id == RIBBON_ART_PANEL_MINIMISED_BORDER_COLOUR:
            return self._panel_minimised_border_pen.GetColour()
        elif id == RIBBON_ART_PANEL_MINIMISED_BORDER_GRADIENT_COLOUR:
            return self._panel_minimised_border_gradient_pen.GetColour()
        elif id in [RIBBON_ART_PANEL_LABEL_BACKGROUND_COLOUR, RIBBON_ART_PANEL_LABEL_BACKGROUND_GRADIENT_COLOUR]:
            return self._panel_label_background_brush.GetColour()
        elif id == RIBBON_ART_PANEL_LABEL_COLOUR:
            return self._panel_label_colour
        elif id == RIBBON_ART_PANEL_MINIMISED_LABEL_COLOUR:
            return self._panel_minimised_label_colour
        elif id in [RIBBON_ART_PANEL_HOVER_LABEL_BACKGROUND_COLOUR, RIBBON_ART_PANEL_HOVER_LABEL_BACKGROUND_GRADIENT_COLOUR]:
            return self._panel_hover_label_background_brush.GetColour()
        elif id == RIBBON_ART_PANEL_HOVER_LABEL_COLOUR:
            return self._panel_hover_label_colour
        elif id == RIBBON_ART_PANEL_ACTIVE_BACKGROUND_TOP_COLOUR:
            return self._panel_active_background_top_colour
        elif id == RIBBON_ART_PANEL_ACTIVE_BACKGROUND_TOP_GRADIENT_COLOUR:
            return self._panel_active_background_top_gradient_colour
        elif id == RIBBON_ART_PANEL_ACTIVE_BACKGROUND_COLOUR:
            return self._panel_active_background_colour
        elif id == RIBBON_ART_PANEL_ACTIVE_BACKGROUND_GRADIENT_COLOUR:
            return self._panel_active_background_gradient_colour
        elif id == RIBBON_ART_PAGE_BORDER_COLOUR:
            return self._page_border_pen.GetColour()
        elif id == RIBBON_ART_PAGE_BACKGROUND_TOP_COLOUR:
            return self._page_background_top_colour
        elif id == RIBBON_ART_PAGE_BACKGROUND_TOP_GRADIENT_COLOUR:
            return self._page_background_top_gradient_colour
        elif id == RIBBON_ART_PAGE_BACKGROUND_COLOUR:
            return self._page_background_colour
        elif id == RIBBON_ART_PAGE_BACKGROUND_GRADIENT_COLOUR:
            return self._page_background_gradient_colour
        elif id == RIBBON_ART_PAGE_HOVER_BACKGROUND_TOP_COLOUR:
            return self._page_hover_background_top_colour
        elif id == RIBBON_ART_PAGE_HOVER_BACKGROUND_TOP_GRADIENT_COLOUR:
            return self._page_hover_background_top_gradient_colour
        elif id == RIBBON_ART_PAGE_HOVER_BACKGROUND_COLOUR:
            return self._page_hover_background_colour
        elif id == RIBBON_ART_PAGE_HOVER_BACKGROUND_GRADIENT_COLOUR:
            return self._page_hover_background_gradient_colour
        elif id in [RIBBON_ART_TOOLBAR_BORDER_COLOUR, RIBBON_ART_TOOLBAR_HOVER_BORDER_COLOUR]:
            return self._toolbar_border_pen.GetColour()
        elif id == RIBBON_ART_TOOLBAR_FACE_COLOUR:
            return self._tool_face_colour
        else:
            raise Exception("Invalid Colour Ordinal")

[docs]    def SetColour(self, id, colour):
        """
        Set the value of a certain colour setting to the value.

        can be one of the colour values of `RibbonArtSetting`, though not all colour
        settings will have an affect on every art provider.

        :param `id`: the colour id;
        :param `colour`: the colour.

        :see: L{SetColourScheme}
        """

        if id == RIBBON_ART_BUTTON_BAR_LABEL_COLOUR:
            self._button_bar_label_colour = colour
        elif id == RIBBON_ART_BUTTON_BAR_HOVER_BORDER_COLOUR:
            self._button_bar_hover_border_pen.SetColour(colour)
        elif id == RIBBON_ART_BUTTON_BAR_HOVER_BACKGROUND_TOP_COLOUR:
            self._button_bar_hover_background_top_colour = colour
        elif id == RIBBON_ART_BUTTON_BAR_HOVER_BACKGROUND_TOP_GRADIENT_COLOUR:
            self._button_bar_hover_background_top_gradient_colour = colour
        elif id == RIBBON_ART_BUTTON_BAR_HOVER_BACKGROUND_COLOUR:
            self._button_bar_hover_background_colour = colour
        elif id == RIBBON_ART_BUTTON_BAR_HOVER_BACKGROUND_GRADIENT_COLOUR:
            self._button_bar_hover_background_gradient_colour = colour
        elif id == RIBBON_ART_BUTTON_BAR_ACTIVE_BORDER_COLOUR:
            self._button_bar_active_border_pen.SetColour(colour)
        elif id == RIBBON_ART_BUTTON_BAR_ACTIVE_BACKGROUND_TOP_COLOUR:
            self._button_bar_active_background_top_colour = colour
        elif id == RIBBON_ART_BUTTON_BAR_ACTIVE_BACKGROUND_TOP_GRADIENT_COLOUR:
            self._button_bar_active_background_top_gradient_colour = colour
        elif id == RIBBON_ART_BUTTON_BAR_ACTIVE_BACKGROUND_COLOUR:
            self._button_bar_active_background_colour = colour
        elif id == RIBBON_ART_BUTTON_BAR_ACTIVE_BACKGROUND_GRADIENT_COLOUR:
            self._button_bar_active_background_gradient_colour = colour
        elif id == RIBBON_ART_GALLERY_BORDER_COLOUR:
            self._gallery_border_pen.SetColour(colour)
        elif id == RIBBON_ART_GALLERY_HOVER_BACKGROUND_COLOUR:
            self._gallery_hover_background_brush.SetColour(colour)
        elif id == RIBBON_ART_GALLERY_BUTTON_BACKGROUND_COLOUR:
            self._gallery_button_background_colour = colour
        elif id == RIBBON_ART_GALLERY_BUTTON_BACKGROUND_GRADIENT_COLOUR:
            self._gallery_button_background_gradient_colour = colour
        elif id == RIBBON_ART_GALLERY_BUTTON_BACKGROUND_TOP_COLOUR:
            self._gallery_button_background_top_brush.SetColour(colour)
        elif id == RIBBON_ART_GALLERY_BUTTON_FACE_COLOUR:
            self._gallery_button_face_colour = colour

            if self._flags & RIBBON_BAR_FLOW_VERTICAL:
                self._gallery_up_bitmap[0] = RibbonLoadPixmap(gallery_left_xpm, colour)
                self._gallery_down_bitmap[0] = RibbonLoadPixmap(gallery_right_xpm, colour)
            else:
                self._gallery_up_bitmap[0] = RibbonLoadPixmap(gallery_up_xpm, colour)
                self._gallery_down_bitmap[0] = RibbonLoadPixmap(gallery_down_xpm, colour)

            self._gallery_extension_bitmap[0] = RibbonLoadPixmap(gallery_extension_xpm, colour)

        elif id == RIBBON_ART_GALLERY_BUTTON_HOVER_BACKGROUND_COLOUR:
            self._gallery_button_hover_background_colour = colour
        elif id == RIBBON_ART_GALLERY_BUTTON_HOVER_BACKGROUND_GRADIENT_COLOUR:
            self._gallery_button_hover_background_gradient_colour = colour
        elif id == RIBBON_ART_GALLERY_BUTTON_HOVER_BACKGROUND_TOP_COLOUR:
            self._gallery_button_hover_background_top_brush.SetColour(colour)
        elif id == RIBBON_ART_GALLERY_BUTTON_HOVER_FACE_COLOUR:
            self._gallery_button_hover_face_colour = colour

            if self._flags & RIBBON_BAR_FLOW_VERTICAL:
                self._gallery_up_bitmap[1] = RibbonLoadPixmap(gallery_left_xpm, colour)
                self._gallery_down_bitmap[1] = RibbonLoadPixmap(gallery_right_xpm, colour)
            else:
                self._gallery_up_bitmap[1] = RibbonLoadPixmap(gallery_up_xpm, colour)
                self._gallery_down_bitmap[1] = RibbonLoadPixmap(gallery_down_xpm, colour)

            self._gallery_extension_bitmap[1] = RibbonLoadPixmap(gallery_extension_xpm, colour)

        elif id == RIBBON_ART_GALLERY_BUTTON_ACTIVE_BACKGROUND_COLOUR:
            self._gallery_button_active_background_colour = colour
        elif id == RIBBON_ART_GALLERY_BUTTON_ACTIVE_BACKGROUND_GRADIENT_COLOUR:
            self._gallery_button_active_background_gradient_colour = colour
        elif id == RIBBON_ART_GALLERY_BUTTON_ACTIVE_BACKGROUND_TOP_COLOUR:
            self._gallery_button_background_top_brush.SetColour(colour)
        elif id == RIBBON_ART_GALLERY_BUTTON_ACTIVE_FACE_COLOUR:
            self._gallery_button_active_face_colour = colour

            if self._flags & RIBBON_BAR_FLOW_VERTICAL:
                self._gallery_up_bitmap[2] = RibbonLoadPixmap(gallery_left_xpm, colour)
                self._gallery_down_bitmap[2] = RibbonLoadPixmap(gallery_right_xpm, colour)
            else:
                self._gallery_up_bitmap[2] = RibbonLoadPixmap(gallery_up_xpm, colour)
                self._gallery_down_bitmap[2] = RibbonLoadPixmap(gallery_down_xpm, colour)

            self._gallery_extension_bitmap[2] = RibbonLoadPixmap(gallery_extension_xpm, colour)

        elif id == RIBBON_ART_GALLERY_BUTTON_DISABLED_BACKGROUND_COLOUR:
            self._gallery_button_disabled_background_colour = colour
        elif id == RIBBON_ART_GALLERY_BUTTON_DISABLED_BACKGROUND_GRADIENT_COLOUR:
            self._gallery_button_disabled_background_gradient_colour = colour
        elif id == RIBBON_ART_GALLERY_BUTTON_DISABLED_BACKGROUND_TOP_COLOUR:
            self._gallery_button_disabled_background_top_brush.SetColour(colour)
        elif id == RIBBON_ART_GALLERY_BUTTON_DISABLED_FACE_COLOUR:
            self._gallery_button_disabled_face_colour = colour

            if self._flags & RIBBON_BAR_FLOW_VERTICAL:
                self._gallery_up_bitmap[3] = RibbonLoadPixmap(gallery_left_xpm, colour)
                self._gallery_down_bitmap[3] = RibbonLoadPixmap(gallery_right_xpm, colour)
            else:
                self._gallery_up_bitmap[3] = RibbonLoadPixmap(gallery_up_xpm, colour)
                self._gallery_down_bitmap[3] = RibbonLoadPixmap(gallery_down_xpm, colour)

            self._gallery_extension_bitmap[3] = RibbonLoadPixmap(gallery_extension_xpm, colour)

        elif id == RIBBON_ART_GALLERY_ITEM_BORDER_COLOUR:
            self._gallery_item_border_pen.SetColour(colour)

        elif id in [RIBBON_ART_TAB_CTRL_BACKGROUND_COLOUR, RIBBON_ART_TAB_CTRL_BACKGROUND_GRADIENT_COLOUR]:
            self._tab_ctrl_background_brush.SetColour(colour)
            self._cached_tab_separator_visibility = -1.0
        elif id == RIBBON_ART_TAB_LABEL_COLOUR:
            self._tab_label_colour = colour
        elif id == RIBBON_ART_TAB_SEPARATOR_COLOUR:
            self._tab_separator_colour = colour
            self._cached_tab_separator_visibility = -1.0
        elif id == RIBBON_ART_TAB_SEPARATOR_GRADIENT_COLOUR:
            self._tab_separator_gradient_colour = colour
            self._cached_tab_separator_visibility = -1.0
        elif id in [RIBBON_ART_TAB_ACTIVE_BACKGROUND_TOP_COLOUR, RIBBON_ART_TAB_ACTIVE_BACKGROUND_TOP_GRADIENT_COLOUR]:
            pass
        elif id == RIBBON_ART_TAB_ACTIVE_BACKGROUND_COLOUR:
            self._tab_active_background_colour = colour
        elif id == RIBBON_ART_TAB_ACTIVE_BACKGROUND_GRADIENT_COLOUR:
            self._tab_active_background_gradient_colour = colour
        elif id == RIBBON_ART_TAB_HOVER_BACKGROUND_TOP_COLOUR:
            self._tab_hover_background_top_colour = colour
        elif id == RIBBON_ART_TAB_HOVER_BACKGROUND_TOP_GRADIENT_COLOUR:
            self._tab_hover_background_top_gradient_colour = colour
        elif id == RIBBON_ART_TAB_HOVER_BACKGROUND_COLOUR:
            self._tab_hover_background_colour = colour
        elif id == RIBBON_ART_TAB_HOVER_BACKGROUND_GRADIENT_COLOUR:
            self._tab_hover_background_gradient_colour = colour
        elif id == RIBBON_ART_TAB_BORDER_COLOUR:
            self._tab_border_pen.SetColour(colour)
        elif id == RIBBON_ART_PANEL_BORDER_COLOUR:
            self._panel_border_pen.SetColour(colour)
        elif id == RIBBON_ART_PANEL_BORDER_GRADIENT_COLOUR:
            self._panel_border_gradient_pen.SetColour(colour)
        elif id == RIBBON_ART_PANEL_MINIMISED_BORDER_COLOUR:
            self._panel_minimised_border_pen.SetColour(colour)
        elif id == RIBBON_ART_PANEL_MINIMISED_BORDER_GRADIENT_COLOUR:
            self._panel_minimised_border_gradient_pen.SetColour(colour)
        elif id in [RIBBON_ART_PANEL_LABEL_BACKGROUND_COLOUR, RIBBON_ART_PANEL_LABEL_BACKGROUND_GRADIENT_COLOUR]:
            self._panel_label_background_brush.SetColour(colour)
        elif id == RIBBON_ART_PANEL_LABEL_COLOUR:
            self._panel_label_colour = colour
        elif id in [RIBBON_ART_PANEL_HOVER_LABEL_BACKGROUND_COLOUR, RIBBON_ART_PANEL_HOVER_LABEL_BACKGROUND_GRADIENT_COLOUR]:
            self._panel_hover_label_background_brush.SetColour(colour)
        elif id == RIBBON_ART_PANEL_HOVER_LABEL_COLOUR:
            self._panel_hover_label_colour = colour
        elif id == RIBBON_ART_PANEL_MINIMISED_LABEL_COLOUR:
            self._panel_minimised_label_colour = colour
        elif id == RIBBON_ART_PANEL_ACTIVE_BACKGROUND_TOP_COLOUR:
            self._panel_active_background_top_colour = colour
        elif id == RIBBON_ART_PANEL_ACTIVE_BACKGROUND_TOP_GRADIENT_COLOUR:
            self._panel_active_background_top_gradient_colour = colour
        elif id == RIBBON_ART_PANEL_ACTIVE_BACKGROUND_COLOUR:
            self._panel_active_background_colour = colour
        elif id == RIBBON_ART_PANEL_ACTIVE_BACKGROUND_GRADIENT_COLOUR:
            self._panel_active_background_gradient_colour = colour
        elif id == RIBBON_ART_PAGE_BORDER_COLOUR:
            self._page_border_pen.SetColour(colour)
        elif id == RIBBON_ART_PAGE_BACKGROUND_TOP_COLOUR:
            self._page_background_top_colour = colour
        elif id == RIBBON_ART_PAGE_BACKGROUND_TOP_GRADIENT_COLOUR:
            self._page_background_top_gradient_colour = colour
        elif id == RIBBON_ART_PAGE_BACKGROUND_COLOUR:
            self._page_background_colour = colour
        elif id == RIBBON_ART_PAGE_BACKGROUND_GRADIENT_COLOUR:
            self._page_background_gradient_colour = colour
        elif id == RIBBON_ART_PAGE_HOVER_BACKGROUND_TOP_COLOUR:
            self._page_hover_background_top_colour = colour
        elif id == RIBBON_ART_PAGE_HOVER_BACKGROUND_TOP_GRADIENT_COLOUR:
            self._page_hover_background_top_gradient_colour = colour
        elif id == RIBBON_ART_PAGE_HOVER_BACKGROUND_COLOUR:
            self._page_hover_background_colour = colour
        elif id == RIBBON_ART_PAGE_HOVER_BACKGROUND_GRADIENT_COLOUR:
            self._page_hover_background_gradient_colour = colour
        elif id in [RIBBON_ART_TOOLBAR_BORDER_COLOUR, RIBBON_ART_TOOLBAR_HOVER_BORDER_COLOUR]:
            self._toolbar_border_pen.SetColour(colour)
        elif id == RIBBON_ART_TOOLBAR_FACE_COLOUR:
            self._tool_face_colour = colour
            self._toolbar_drop_bitmap = RibbonLoadPixmap(gallery_down_xpm, colour)
        else:
            raise Exception("Invalid Colour Ordinal")

[docs]    def DrawTabCtrlBackground(self, dc, wnd, rect):
        """
        Draw the background of the tab region of a ribbon bar.

        :param `dc`: The device context to draw onto;
        :param `wnd`: The window which is being drawn onto;
        :param `rect`: The rectangle within which to draw.

        """

        dc.SetPen(wx.TRANSPARENT_PEN)

        dc.SetBrush(self._tab_ctrl_background_brush)
        dc.DrawRectangle(rect.x, rect.y, rect.width, rect.height)

        dc.SetPen(self._page_border_pen)

        if rect.width > 6:
            dc.DrawLine(rect.x + 3, rect.y + rect.height - 1, rect.x + rect.width - 3, rect.y + rect.height - 1)
        else:
            dc.DrawLine(rect.x, rect.y + rect.height - 1, rect.x + rect.width, rect.y + rect.height - 1)

[docs]    def DrawTab(self, dc, wnd, tab):
        """
        Draw a single tab in the tab region of a ribbon bar.

        :param `dc`: The device context to draw onto;
        :param `wnd`: The window which is being drawn onto (not the L{RibbonPage} associated
         with the tab being drawn);
        :param `tab`: The rectangle within which to draw, and also the tab label, icon, and
         state (active and/or hovered). The drawing rectangle will be entirely within a
         rectangle on the same device context previously painted with L{DrawTabCtrlBackground}.
         The rectangle's width will be at least the minimum value returned by L{GetBarTabWidth},
         and height will be the value returned by L{GetTabCtrlHeight}.

        """

        if tab.rect.height <= 2:
            return

        if tab.active or tab.hovered:
            if tab.active:
                background = wx.Rect(*tab.rect)
                background.x += 2
                background.y += 2
                background.width -= 4
                background.height -= 2

                dc.GradientFillLinear(background, self._tab_active_background_colour,
                                      self._tab_active_background_gradient_colour, wx.SOUTH)

                # TODO: active and hovered

            elif tab.hovered:
                background = wx.Rect(*tab.rect)
                background.x += 2
                background.y += 2
                background.width -= 4
                background.height -= 3
                h = background.height
                background.height /= 2
                dc.GradientFillLinear(background, self._tab_hover_background_top_colour,
                                      self._tab_hover_background_top_gradient_colour, wx.SOUTH)

                background.y += background.height
                background.height = h - background.height
                dc.GradientFillLinear(background, self._tab_hover_background_colour,
                                      self._tab_hover_background_gradient_colour, wx.SOUTH)

            border_points = [wx.Point() for i in xrange(6)]
            border_points[0] = wx.Point(1, tab.rect.height - 2)
            border_points[1] = wx.Point(1, 3)
            border_points[2] = wx.Point(3, 1)
            border_points[3] = wx.Point(tab.rect.width - 4, 1)
            border_points[4] = wx.Point(tab.rect.width - 2, 3)
            border_points[5] = wx.Point(tab.rect.width - 2, tab.rect.height - 1)

            dc.SetPen(self._tab_border_pen)
            dc.DrawLines(border_points, tab.rect.x, tab.rect.y)

            if tab.active:
                # Give the tab a curved outward border at the bottom
                dc.DrawPoint(tab.rect.x, tab.rect.y + tab.rect.height - 2)
                dc.DrawPoint(tab.rect.x + tab.rect.width - 1, tab.rect.y + tab.rect.height - 2)

                p = wx.Pen(self._tab_active_background_gradient_colour)
                dc.SetPen(p)

                # Technically the first two points are the wrong colour, but they're near enough
                dc.DrawPoint(tab.rect.x + 1, tab.rect.y + tab.rect.height - 2)
                dc.DrawPoint(tab.rect.x + tab.rect.width - 2, tab.rect.y + tab.rect.height - 2)
                dc.DrawPoint(tab.rect.x + 1, tab.rect.y + tab.rect.height - 1)
                dc.DrawPoint(tab.rect.x, tab.rect.y + tab.rect.height - 1)
                dc.DrawPoint(tab.rect.x + tab.rect.width - 2, tab.rect.y + tab.rect.height - 1)
                dc.DrawPoint(tab.rect.x + tab.rect.width - 1, tab.rect.y + tab.rect.height - 1)

        if self._flags & RIBBON_BAR_SHOW_PAGE_ICONS:
            icon = tab.page.GetIcon()

            if icon.IsOk():
                x = tab.rect.x + 4
                if self._flags & RIBBON_BAR_SHOW_PAGE_LABELS == 0:
                    x = tab.rect.x + (tab.rect.width - icon.GetWidth()) / 2

                dc.DrawBitmap(icon, x, tab.rect.y + 1 + (tab.rect.height - 1 - icon.GetHeight()) / 2, True)

        if self._flags & RIBBON_BAR_SHOW_PAGE_LABELS:
            label = tab.page.GetLabel()
            if label.strip():
                dc.SetFont(self._tab_label_font)
                dc.SetTextForeground(self._tab_label_colour)
                dc.SetBackgroundMode(wx.TRANSPARENT)

                text_width, text_height = dc.GetTextExtent(label)
                width = tab.rect.width - 5
                x = tab.rect.x + 3

                if self._flags & RIBBON_BAR_SHOW_PAGE_ICONS:
                    x += 3 + tab.page.GetIcon().GetWidth()
                    width -= 3 + tab.page.GetIcon().GetWidth()

                y = tab.rect.y + (tab.rect.height - text_height) / 2

                if width <= text_width:
                    dc.SetClippingRegion(x, tab.rect.y, width, tab.rect.height)
                    dc.DrawText(label, x, y)
                else:
                    dc.DrawText(label, x + (width - text_width) / 2 + 1, y)

[docs]    def DrawTabSeparator(self, dc, wnd, rect, visibility):
        """
        Draw a separator between two tabs in a ribbon bar.

        :param `dc`: The device context to draw onto;
        :param `wnd`: The window which is being drawn onto;
        :param `rect`: The rectangle within which to draw, which will be entirely
         within a rectangle on the same device context previously painted with
         L{DrawTabCtrlBackground};
        :param `visibility`: The opacity with which to draw the separator. Values
         are in the range [0, 1], with 0 being totally transparent, and 1 being totally
         opaque.

        """

        if visibility <= 0.0:
            return

        if visibility > 1.0:
            visibility = 1.0

        # The tab separator is relatively expensive to draw (for its size), and is
        # usually drawn multiple times sequentially (in different positions), so it
        # makes sense to draw it once and cache it.
        if not self._cached_tab_separator.IsOk() or self._cached_tab_separator.GetSize() != rect.GetSize() or \
           visibility != self._cached_tab_separator_visibility:

            size = wx.Rect(0, 0, *rect.GetSize())
            self.ReallyDrawTabSeparator(wnd, size, visibility)

        dc.DrawBitmap(self._cached_tab_separator, rect.x, rect.y, False)

[docs]    def ReallyDrawTabSeparator(self, wnd, rect, visibility):

        if not self._cached_tab_separator.IsOk() or self._cached_tab_separator.GetSize() != rect.GetSize():
            self._cached_tab_separator = wx.EmptyBitmap(*rect.GetSize())

        dc = wx.MemoryDC(self._cached_tab_separator)
        self.DrawTabCtrlBackground(dc, wnd, rect)

        x = rect.x + rect.width / 2
        h = float(rect.height - 1)

        r1 = self._tab_ctrl_background_brush.GetColour().Red() * (1.0 - visibility) + 0.5
        g1 = self._tab_ctrl_background_brush.GetColour().Green() * (1.0 - visibility) + 0.5
        b1 = self._tab_ctrl_background_brush.GetColour().Blue() * (1.0 - visibility) + 0.5
        r2 = self._tab_separator_colour.Red()
        g2 = self._tab_separator_colour.Green()
        b2 = self._tab_separator_colour.Blue()
        r3 = self._tab_separator_gradient_colour.Red()
        g3 = self._tab_separator_gradient_colour.Green()
        b3 = self._tab_separator_gradient_colour.Blue()

        for i in xrange(rect.height-1):

            p = float(i)/h

            r = (p * r3 + (1.0 - p) * r2) * visibility + r1
            g = (p * g3 + (1.0 - p) * g2) * visibility + g1
            b = (p * b3 + (1.0 - p) * b2) * visibility + b1

            P = wx.Pen(wx.Colour(r, g, b))
            dc.SetPen(P)
            dc.DrawPoint(x, rect.y + i)

        self._cached_tab_separator_visibility = visibility

[docs]    def DrawPartialPageBackground(self, dc, wnd, rect, allow_hovered_or_page=True, offset=None, hovered=False):

        if isinstance(allow_hovered_or_page, types.BooleanType):
            self.DrawPartialPageBackground2(dc, wnd, rect, allow_hovered_or_page)
        else:
            self.DrawPartialPageBackground1(dc, wnd, rect, allow_hovered_or_page, offset, hovered)

[docs]    def DrawPartialPageBackground1(self, dc, wnd, rect, page, offset, hovered=False):

        background = wx.Rect(0, 0, *page.GetSize())
        background = page.AdjustRectToIncludeScrollButtons(background)
        background.height -= 2

        # Page background isn't dependant upon the width of the page
        # (at least not the part of it intended to be painted by this
        # function). Set to wider than the page itself for when externally
        # expanded panels need a background - the expanded panel can be wider
        # than the bar.

        background.x = 0
        background.width = 10000

        # upper_rect, lower_rect, paint_rect are all in page co-ordinates
        upper_rect = wx.Rect(*background)
        upper_rect.height /= 5

        lower_rect = wx.Rect(*background)
        lower_rect.y += upper_rect.height
        lower_rect.height -= upper_rect.height

        paint_rect = wx.Rect(*rect)
        paint_rect.x += offset.x
        paint_rect.y += offset.y

        if hovered:
            bg_top = self._page_hover_background_top_colour
            bg_top_grad = self._page_hover_background_top_gradient_colour
            bg_btm = self._page_hover_background_colour
            bg_btm_grad = self._page_hover_background_gradient_colour
        else:
            bg_top = self._page_background_top_colour
            bg_top_grad = self._page_background_top_gradient_colour
            bg_btm = self._page_background_colour
            bg_btm_grad = self._page_background_gradient_colour

        if paint_rect.Intersects(upper_rect):
            rect = wx.Rect(*upper_rect)
            rect.Intersect(paint_rect)
            rect.x -= offset.x
            rect.y -= offset.y
            starting_colour = RibbonInterpolateColour(bg_top, bg_top_grad,
                                                      paint_rect.y, upper_rect.y,
                                                      upper_rect.y + upper_rect.height)
            ending_colour = RibbonInterpolateColour(bg_top, bg_top_grad,
                                                    paint_rect.y + paint_rect.height, upper_rect.y,
                                                    upper_rect.y + upper_rect.height)
            dc.GradientFillLinear(rect, starting_colour, ending_colour, wx.SOUTH)

        if paint_rect.Intersects(lower_rect):
            rect = wx.Rect(*lower_rect)
            rect.Intersect(paint_rect)
            rect.x -= offset.x
            rect.y -= offset.y
            starting_colour = RibbonInterpolateColour(bg_btm, bg_btm_grad,
                                                      paint_rect.y, lower_rect.y,
                                                      lower_rect.y + lower_rect.height)
            ending_colour = RibbonInterpolateColour(bg_btm, bg_btm_grad,
                                                    paint_rect.y + paint_rect.height,
                                                    lower_rect.y, lower_rect.y + lower_rect.height)

            dc.GradientFillLinear(rect, starting_colour, ending_colour, wx.SOUTH)

[docs]    def DrawPageBackground(self, dc, wnd, rect):
        """
        Draw the background of a ribbon page.

        :param `dc`: The device context to draw onto;
        :param `wnd`: The window which is being drawn onto (which is commonly the
         L{RibbonPage} whose background is being drawn, but doesn't have to be);
        :param `rect`: The rectangle within which to draw.

        :see: L{GetPageBackgroundRedrawArea}
        """

        dc.SetPen(wx.TRANSPARENT_PEN)
        dc.SetBrush(self._tab_ctrl_background_brush)

        edge = wx.Rect(*rect)

        edge.width = 2
        dc.DrawRectangle(edge.x, edge.y, edge.width, edge.height)

        edge.x += rect.width - 2
        dc.DrawRectangle(edge.x, edge.y, edge.width, edge.height)

        edge = wx.Rect(*rect)
        edge.height = 2
        edge.y += (rect.height - edge.height)
        dc.DrawRectangle(edge.x, edge.y, edge.width, edge.height)

        background = wx.Rect(*rect)
        background.x += 2
        background.width -= 4
        background.height -= 2

        background.height /= 5
        dc.GradientFillLinear(background, self._page_background_top_colour,
                              self._page_background_top_gradient_colour, wx.SOUTH)

        background.y += background.height
        background.height = rect.height - 2 - background.height
        dc.GradientFillLinear(background, self._page_background_colour,
                              self._page_background_gradient_colour, wx.SOUTH)

        border_points = [wx.Point() for i in xrange(8)]
        border_points[0] = wx.Point(2, 0)
        border_points[1] = wx.Point(1, 1)
        border_points[2] = wx.Point(1, rect.height - 4)
        border_points[3] = wx.Point(3, rect.height - 2)
        border_points[4] = wx.Point(rect.width - 4, rect.height - 2)
        border_points[5] = wx.Point(rect.width - 2, rect.height - 4)
        border_points[6] = wx.Point(rect.width - 2, 1)
        border_points[7] = wx.Point(rect.width - 4, -1)

        dc.SetPen(self._page_border_pen)
        dc.DrawLines(border_points, rect.x, rect.y)

[docs]    def DrawScrollButton(self, dc, wnd, rect_, style):
        """
        Draw a ribbon-style scroll button.

        :param `dc`: The device context to draw onto;
        :param `wnd`: The window which is being drawn onto;
        :param `rect`: The rectangle within which to draw. The size of this rectangle
         will be at least the size returned by L{GetScrollButtonMinimumSize} for a
         scroll button with the same style. For tab scroll buttons, this rectangle
         will be entirely within a rectangle on the same device context previously
         painted with L{DrawTabCtrlBackground}, but this is not guaranteed for other
         types of button (for example, page scroll buttons will not be painted on an
         area previously painted with L{DrawPageBackground} );
        :param `style`: A combination of flags from `RibbonScrollButtonStyle`,
         including a direction, a for flag, and one or more states.

        """

        rect = wx.Rect(*rect_)

        if (style & RIBBON_SCROLL_BTN_FOR_MASK) == RIBBON_SCROLL_BTN_FOR_PAGE:

            # Page scroll buttons do not have the luxury of rendering on top of anything
            # else, and their size includes some padding, hence the background painting
            # and size adjustment.
            dc.SetPen(wx.TRANSPARENT_PEN)
            dc.SetBrush(self._tab_ctrl_background_brush)
            dc.DrawRectangleRect(rect)
            dc.SetClippingRect(rect)

            result = style & RIBBON_SCROLL_BTN_DIRECTION_MASK

            if result == RIBBON_SCROLL_BTN_LEFT:
                rect.x += 1
            elif result == RIBBON_SCROLL_BTN_RIGHT:
                rect.y -= 1
                rect.width -= 1
            elif result == RIBBON_SCROLL_BTN_UP:
                rect.x += 1
                rect.y -= 1
                rect.width -= 2
                rect.height += 1
            elif result == RIBBON_SCROLL_BTN_DOWN:
                rect.x += 1
                rect.width -= 2
                rect.height -= 1

        background = wx.Rect(*rect)
        background.x += 1
        background.y += 1
        background.width -= 2
        background.height -= 2

        if style & RIBBON_SCROLL_BTN_UP:
            background.height /= 2
        else:
            background.height /= 5

        dc.GradientFillLinear(background, self._page_background_top_colour,
                              self._page_background_top_gradient_colour, wx.SOUTH)

        background.y += background.height
        background.height = rect.height - 2 - background.height
        dc.GradientFillLinear(background, self._page_background_colour,
                              self._page_background_gradient_colour, wx.SOUTH)

        border_points = [wx.Point() for i in xrange(7)]
        result = style & RIBBON_SCROLL_BTN_DIRECTION_MASK

        if result == RIBBON_SCROLL_BTN_LEFT:
            border_points[0] = wx.Point(2, 0)
            border_points[1] = wx.Point(rect.width - 1, 0)
            border_points[2] = wx.Point(rect.width - 1, rect.height - 1)
            border_points[3] = wx.Point(2, rect.height - 1)
            border_points[4] = wx.Point(0, rect.height - 3)
            border_points[5] = wx.Point(0, 2)

        elif result == RIBBON_SCROLL_BTN_RIGHT:
            border_points[0] = wx.Point(0, 0)
            border_points[1] = wx.Point(rect.width - 3, 0)
            border_points[2] = wx.Point(rect.width - 1, 2)
            border_points[3] = wx.Point(rect.width - 1, rect.height - 3)
            border_points[4] = wx.Point(rect.width - 3, rect.height - 1)
            border_points[5] = wx.Point(0, rect.height - 1)

        elif result == RIBBON_SCROLL_BTN_UP:
            border_points[0] = wx.Point(2, 0)
            border_points[1] = wx.Point(rect.width - 3, 0)
            border_points[2] = wx.Point(rect.width - 1, 2)
            border_points[3] = wx.Point(rect.width - 1, rect.height - 1)
            border_points[4] = wx.Point(0, rect.height - 1)
            border_points[5] = wx.Point(0, 2)

        elif result == RIBBON_SCROLL_BTN_DOWN:
            border_points[0] = wx.Point(0, 0)
            border_points[1] = wx.Point(rect.width - 1, 0)
            border_points[2] = wx.Point(rect.width - 1, rect.height - 3)
            border_points[3] = wx.Point(rect.width - 3, rect.height - 1)
            border_points[4] = wx.Point(2, rect.height - 1)
            border_points[5] = wx.Point(0, rect.height - 3)

        border_points[6] = border_points[0]

        dc.SetPen(self._page_border_pen)
        dc.DrawLines(border_points, rect.x, rect.y)

        # NB: Code for handling hovered/active state is temporary
        arrow_points = [wx.Point() for i in xrange(3)]
        result = style & RIBBON_SCROLL_BTN_DIRECTION_MASK

        if result == RIBBON_SCROLL_BTN_LEFT:
            arrow_points[0] = wx.Point(rect.width / 2 - 2, rect.height / 2)
            if style & RIBBON_SCROLL_BTN_ACTIVE:
                arrow_points[0].y += 1
            arrow_points[1] = arrow_points[0] + wx.Point(3, -3)
            arrow_points[2] = arrow_points[0] + wx.Point(3,  3)

        elif result == RIBBON_SCROLL_BTN_RIGHT:
            arrow_points[0] = wx.Point(rect.width / 2 + 2, rect.height / 2)
            if style & RIBBON_SCROLL_BTN_ACTIVE:
                arrow_points[0].y += 1
            arrow_points[1] = arrow_points[0] - wx.Point(3,  3)
            arrow_points[2] = arrow_points[0] - wx.Point(3, -3)

        elif result == RIBBON_SCROLL_BTN_UP:
            arrow_points[0] = wx.Point(rect.width / 2, rect.height / 2 - 2)
            if style & RIBBON_SCROLL_BTN_ACTIVE:
                arrow_points[0].y += 1
            arrow_points[1] = arrow_points[0] + wx.Point( 3, 3)
            arrow_points[2] = arrow_points[0] + wx.Point(-3, 3)

        elif result == RIBBON_SCROLL_BTN_DOWN:
            arrow_points[0] = wx.Point(rect.width / 2, rect.height / 2 + 2)
            if style & RIBBON_SCROLL_BTN_ACTIVE:
                arrow_points[0].y += 1
            arrow_points[1] = arrow_points[0] - wx.Point( 3, 3)
            arrow_points[2] = arrow_points[0] - wx.Point(-3, 3)

        dc.SetPen(wx.TRANSPARENT_PEN)
        B = wx.Brush((style & RIBBON_SCROLL_BTN_HOVERED and [self._tab_active_background_colour] or [self._tab_label_colour])[0])
        dc.SetBrush(B)
        dc.DrawPolygon(arrow_points, rect.x, rect.y)

[docs]    def DrawDropdownArrow(self, dc, x, y, colour):

        arrow_points = [wx.Point() for i in xrange(3)]
        brush = wx.Brush(colour)
        arrow_points[0] = wx.Point(1, 2)
        arrow_points[1] = arrow_points[0] + wx.Point(-3, -3)
        arrow_points[2] = arrow_points[0] + wx.Point( 3, -3)
        dc.SetPen(wx.TRANSPARENT_PEN)
        dc.SetBrush(brush)
        dc.DrawPolygon(arrow_points, x, y)

[docs]    def RemovePanelPadding(self, rect):

        if self._flags & RIBBON_BAR_FLOW_VERTICAL:
            rect.y += 1
            rect.height -= 2
        else:
            rect.x += 1
            rect.width -= 2

        return rect

[docs]    def DrawPanelBackground(self, dc, wnd, rect):
        """
        Draw the background and chrome for a ribbon panel.

        This should draw the border, background, label, and any other items of a panel
        which are outside the client area of a panel. Note that when a panel is
        minimised, this function is not called - only L{DrawMinimisedPanel} is called,
        so a background should be explicitly painted by that if required.

        :param `dc`: The device context to draw onto;
        :param `wnd`: The window which is being drawn onto, which is always the panel
         whose background and chrome is being drawn. The panel label and other panel
         attributes can be obtained by querying this;
        :param `rect`: The rectangle within which to draw.

        """

        self.DrawPartialPageBackground(dc, wnd, rect, False)

        true_rect = wx.Rect(*rect)
        true_rect = self.RemovePanelPadding(true_rect)

        dc.SetFont(self._panel_label_font)
        dc.SetPen(wx.TRANSPARENT_PEN)

        if wnd.IsHovered():
            dc.SetBrush(self._panel_hover_label_background_brush)
            dc.SetTextForeground(self._panel_hover_label_colour)
        else:
            dc.SetBrush(self._panel_label_background_brush)
            dc.SetTextForeground(self._panel_label_colour)

        label_rect = wx.Rect(*true_rect)
        label = wnd.GetLabel().strip()
        clip_label = False
        label_size = wx.Size(*dc.GetTextExtent(label))

        label_rect.SetX(label_rect.GetX() + 1)
        label_rect.SetWidth(label_rect.GetWidth() - 2)
        label_rect.SetHeight(label_size.GetHeight() + 2)
        label_rect.SetY(true_rect.GetBottom() - label_rect.GetHeight())
        label_height = label_rect.GetHeight()

        if label_size.GetWidth() > label_rect.GetWidth():
            # Test if there is enough length for 3 letters and ...
            new_label = label[0:3] + "..."
            label_size = wx.Size(*dc.GetTextExtent(new_label))

            if label_size.GetWidth() > label_rect.GetWidth():
                # Not enough room for three characters and ...
                # Display the entire label and just crop it
                clip_label = True
            else:
                # Room for some characters and ...
                # Display as many characters as possible and append ...
                for l in xrange(len(label)-1, 3, -1):
                    new_label = label[0:l] + "..."
                    label_size = wx.Size(*dc.GetTextExtent(new_label))
                    if label_size.GetWidth() <= label_rect.GetWidth():
                        label = new_label
                        break

        dc.DrawRectangleRect(label_rect)

        if clip_label:
            clip = wx.DCClipper(dc, label_rect)
            dc.DrawText(label, label_rect.x, label_rect.y + (label_rect.GetHeight() - label_size.GetHeight()) / 2)
        else:
            dc.DrawText(label, label_rect.x + (label_rect.GetWidth() - label_size.GetWidth()) / 2,
                        label_rect.y + (label_rect.GetHeight() - label_size.GetHeight()) / 2)

        if wnd.IsHovered():
            client_rect = wx.Rect(*true_rect)
            client_rect.x += 1
            client_rect.width -= 2
            client_rect.y += 1
            client_rect.height -= 2 + label_height
            self.DrawPartialPageBackground(dc, wnd, client_rect, True)

        self.DrawPanelBorder(dc, true_rect, self._panel_border_pen, self._panel_border_gradient_pen)

[docs]    def DrawGalleryBackground(self, dc, wnd, rect):
        """
        Draw the background and chrome for a L{RibbonGallery} control.

        This should draw the border, brackground, scroll buttons, extension button, and
        any other UI elements which are not attached to a specific gallery item.

        :param `dc`: The device context to draw onto;
        :param `wnd`: The window which is being drawn onto, which is always the gallery
         whose background and chrome is being drawn. Attributes used during drawing like
         the gallery hover state and individual button states can be queried from this
         parameter by L{RibbonGallery.IsHovered}, L{RibbonGallery.GetExtensionButtonState},
         L{RibbonGallery.GetUpButtonState}, and L{RibbonGallery.GetDownButtonState};
        :param `rect`: The rectangle within which to draw. This rectangle is the entire
         area of the gallery control, not just the client rectangle.

        """

        self.DrawPartialPageBackground(dc, wnd, rect)

        if wnd.IsHovered():
            dc.SetPen(wx.TRANSPARENT_PEN)
            dc.SetBrush(self._gallery_hover_background_brush)
            if self._flags & RIBBON_BAR_FLOW_VERTICAL:
                dc.DrawRectangle(rect.x + 1, rect.y + 1, rect.width - 2, rect.height - 16)
            else:
                dc.DrawRectangle(rect.x + 1, rect.y + 1, rect.width - 16, rect.height - 2)

        dc.SetPen(self._gallery_border_pen)
        # Outline
        dc.DrawLine(rect.x + 1, rect.y, rect.x + rect.width - 1, rect.y)
        dc.DrawLine(rect.x, rect.y + 1, rect.x, rect.y + rect.height - 1)
        dc.DrawLine(rect.x + 1, rect.y + rect.height - 1, rect.x + rect.width - 1, rect.y + rect.height - 1)
        dc.DrawLine(rect.x + rect.width - 1, rect.y + 1, rect.x + rect.width - 1, rect.y + rect.height - 1)

        self.DrawGalleryBackgroundCommon(dc, wnd, rect)

[docs]    def DrawGalleryBackgroundCommon(self, dc, wnd, rect):

        if self._flags & RIBBON_BAR_FLOW_VERTICAL:
            # Divider between items and buttons
            dc.DrawLine(rect.x, rect.y + rect.height - 15, rect.x + rect.width, rect.y + rect.height - 15)

            up_btn = wx.Rect(rect.x, rect.y + rect.height - 15, rect.width / 3, 15)
            down_btn = wx.Rect(up_btn.GetRight() + 1, up_btn.GetTop(), up_btn.GetWidth(), up_btn.GetHeight())
            dc.DrawLine(down_btn.GetLeft(), down_btn.GetTop(), down_btn.GetLeft(), down_btn.GetBottom())
            ext_btn = wx.Rect(down_btn.GetRight() + 1, up_btn.GetTop(), rect.width - up_btn.GetWidth() - down_btn.GetWidth() - 1, up_btn.GetHeight())
            dc.DrawLine(ext_btn.GetLeft(), ext_btn.GetTop(), ext_btn.GetLeft(), ext_btn.GetBottom())

        else:
            # Divider between items and buttons
            dc.DrawLine(rect.x + rect.width - 15, rect.y, rect.x + rect.width - 15, rect.y + rect.height)

            up_btn = wx.Rect(rect.x + rect.width - 15, rect.y, 15, rect.height / 3)
            down_btn = wx.Rect(up_btn.GetLeft(), up_btn.GetBottom() + 1, up_btn.GetWidth(), up_btn.GetHeight())
            dc.DrawLine(down_btn.GetLeft(), down_btn.GetTop(), down_btn.GetRight(), down_btn.GetTop())
            ext_btn = wx.Rect(up_btn.GetLeft(), down_btn.GetBottom() + 1, up_btn.GetWidth(), rect.height - up_btn.GetHeight() - down_btn.GetHeight() - 1)
            dc.DrawLine(ext_btn.GetLeft(), ext_btn.GetTop(), ext_btn.GetRight(), ext_btn.GetTop())

        self.DrawGalleryButton(dc, up_btn, wnd.GetUpButtonState(), self._gallery_up_bitmap)
        self.DrawGalleryButton(dc, down_btn, wnd.GetDownButtonState(), self._gallery_down_bitmap)
        self.DrawGalleryButton(dc, ext_btn, wnd.GetExtensionButtonState(), self._gallery_extension_bitmap)

[docs]    def DrawGalleryButton(self, dc, rect, state, bitmaps):

        if state == RIBBON_GALLERY_BUTTON_NORMAL:
            btn_top_brush = self._gallery_button_background_top_brush
            btn_colour = self._gallery_button_background_colour
            btn_grad_colour = self._gallery_button_background_gradient_colour
            btn_bitmap = bitmaps[0]
        elif state == RIBBON_GALLERY_BUTTON_HOVERED:
            btn_top_brush = self._gallery_button_hover_background_top_brush
            btn_colour = self._gallery_button_hover_background_colour
            btn_grad_colour = self._gallery_button_hover_background_gradient_colour
            btn_bitmap = bitmaps[1]
        elif state == RIBBON_GALLERY_BUTTON_ACTIVE:
            btn_top_brush = self._gallery_button_active_background_top_brush
            btn_colour = self._gallery_button_active_background_colour
            btn_grad_colour = self._gallery_button_active_background_gradient_colour
            btn_bitmap = bitmaps[2]
        elif state == RIBBON_GALLERY_BUTTON_DISABLED:
            btn_top_brush = self._gallery_button_disabled_background_top_brush
            btn_colour = self._gallery_button_disabled_background_colour
            btn_grad_colour = self._gallery_button_disabled_background_gradient_colour
            btn_bitmap = bitmaps[3]

        rect.x += 1
        rect.y += 1

        if self._flags & RIBBON_BAR_FLOW_VERTICAL:
            rect.width -= 1
            rect.height -= 2
        else:
            rect.width -= 2
            rect.height -= 1

        dc.SetPen(wx.TRANSPARENT_PEN)
        dc.SetBrush(btn_top_brush)
        dc.DrawRectangle(rect.x, rect.y, rect.width, rect.height / 2)

        lower = wx.Rect(*rect)
        lower.height = (lower.height + 1) / 2
        lower.y += rect.height - lower.height
        dc.GradientFillLinear(lower, btn_colour, btn_grad_colour, wx.SOUTH)

        dc.DrawBitmap(btn_bitmap, rect.x + rect.width / 2 - 2, lower.y - 2, True)

[docs]    def DrawGalleryItemBackground(self, dc, wnd, rect, item):
        """
        Draw the background of a single item in a L{RibbonGallery} control.

        This is painted on top of a gallery background, and behind the items bitmap.
        Unlike L{DrawButtonBarButton} and L{DrawTool}, it is not expected to draw the
        item bitmap - that is done by the gallery control itself.

        :param `dc`: The device context to draw onto;
        :param `wnd`: The window which is being drawn onto, which is always the gallery
         which contains the item being drawn;
        :param `rect`: The rectangle within which to draw. The size of this rectangle
         will be the size of the item's bitmap, expanded by gallery item padding values
         (``RIBBON_ART_GALLERY_BITMAP_PADDING_LEFT_SIZE``, ``RIBBON_ART_GALLERY_BITMAP_PADDING_RIGHT_SIZE``,
         ``RIBBON_ART_GALLERY_BITMAP_PADDING_TOP_SIZE``, and ``RIBBON_ART_GALLERY_BITMAP_PADDING_BOTTOM_SIZE``).
         The drawing rectangle will be entirely within a rectangle on the same device
         context previously painted with L{DrawGalleryBackground};
        :param `item`: The item whose background is being painted. Typically the background
         will vary if the item is hovered, active, or selected; L{RibbonGallery.GetSelection},
         L{RibbonGallery.GetActiveItem}, and L{RibbonGallery.GetHoveredItem} can be
         called to test if the given item is in one of these states.

        """

        if wnd.GetHoveredItem() != item and wnd.GetActiveItem() != item and \
           wnd.GetSelection() != item:
            return

        dc.SetPen(self._gallery_item_border_pen)
        dc.DrawLine(rect.x + 1, rect.y, rect.x + rect.width - 1, rect.y)
        dc.DrawLine(rect.x, rect.y + 1, rect.x, rect.y + rect.height - 1)
        dc.DrawLine(rect.x + 1, rect.y + rect.height - 1, rect.x + rect.width - 1, rect.y + rect.height - 1)
        dc.DrawLine(rect.x + rect.width - 1, rect.y + 1, rect.x + rect.width - 1, rect.y + rect.height - 1)

        if wnd.GetActiveItem() == item or wnd.GetSelection() == item:
            top_brush = self._gallery_button_active_background_top_brush
            bg_colour = self._gallery_button_active_background_colour
            bg_gradient_colour = self._gallery_button_active_background_gradient_colour
        else:
            top_brush = self._gallery_button_hover_background_top_brush
            bg_colour = self._gallery_button_hover_background_colour
            bg_gradient_colour = self._gallery_button_hover_background_gradient_colour

        upper = wx.Rect(*rect)
        upper.x += 1
        upper.width -= 2
        upper.y += 1
        upper.height /= 3
        dc.SetPen(wx.TRANSPARENT_PEN)
        dc.SetBrush(top_brush)
        dc.DrawRectangle(upper.x, upper.y, upper.width, upper.height)

        lower = wx.Rect(*upper)
        lower.y += lower.height
        lower.height = rect.height - 2 - lower.height
        dc.GradientFillLinear(lower, bg_colour, bg_gradient_colour, wx.SOUTH)

[docs]    def DrawPanelBorder(self, dc, rect, primary_colour, secondary_colour):

        border_points = [wx.Point() for i in xrange(9)]
        border_points[0] = wx.Point(2, 0)
        border_points[1] = wx.Point(rect.width - 3, 0)
        border_points[2] = wx.Point(rect.width - 1, 2)
        border_points[3] = wx.Point(rect.width - 1, rect.height - 3)
        border_points[4] = wx.Point(rect.width - 3, rect.height - 1)
        border_points[5] = wx.Point(2, rect.height - 1)
        border_points[6] = wx.Point(0, rect.height - 3)
        border_points[7] = wx.Point(0, 2)

        if primary_colour.GetColour() == secondary_colour.GetColour():
            border_points[8] = border_points[0]
            dc.SetPen(primary_colour)
            dc.DrawLines(border_points, rect.x, rect.y)
        else:
            dc.SetPen(primary_colour)
            dc.DrawLines(border_points[0:3], rect.x, rect.y)

            SingleLine(dc, rect, border_points[0], border_points[7])
            dc.SetPen(secondary_colour)
            dc.DrawLines(border_points[4:7], rect.x, rect.y)
            SingleLine(dc, rect, border_points[4], border_points[3])

            border_points[6] = border_points[2]
            RibbonDrawParallelGradientLines(dc, 2, border_points[6:8], 0, 1,
                                            border_points[3].y - border_points[2].y + 1, rect.x, rect.y,
                                            primary_colour.GetColour(), secondary_colour.GetColour())

[docs]    def DrawMinimisedPanel(self, dc, wnd, rect, bitmap):
        """
        Draw a minimised ribbon panel.

        :param `dc`: The device context to draw onto;
        :param `wnd`: The window which is being drawn onto, which is always the panel
         which is minimised. The panel label can be obtained from this window. The
         minimised icon obtained from querying the window may not be the size requested
         by L{GetMinimisedPanelMinimumSize} - the argument contains the icon in the
         requested size;
        :param `rect`: The rectangle within which to draw. The size of the rectangle
         will be at least the size returned by L{GetMinimisedPanelMinimumSize};
        :param `bitmap`: A copy of the panel's minimised bitmap rescaled to the size
         returned by L{GetMinimisedPanelMinimumSize}.

        """

        self.DrawPartialPageBackground(dc, wnd, rect, False)

        true_rect = wx.Rect(*rect)
        true_rect = self.RemovePanelPadding(true_rect)

        if wnd.GetExpandedPanel() != None:
            client_rect = wx.Rect(*true_rect)
            client_rect.x += 1
            client_rect.width -= 2
            client_rect.y += 1
            client_rect.height = (rect.y + rect.height / 5) - client_rect.x
            dc.GradientFillLinear(client_rect,
                                  self._panel_active_background_top_colour,
                                  self._panel_active_background_top_gradient_colour, wx.SOUTH)

            client_rect.y += client_rect.height
            client_rect.height = (true_rect.y + true_rect.height) - client_rect.y
            dc.GradientFillLinear(client_rect,
                                  self._panel_active_background_colour,
                                  self._panel_active_background_gradient_colour, wx.SOUTH)

        elif wnd.IsHovered():
            client_rect = wx.Rect(*true_rect)
            client_rect.x += 1
            client_rect.width -= 2
            client_rect.y += 1
            client_rect.height -= 2
            self.DrawPartialPageBackground(dc, wnd, client_rect, True)

        preview = self.DrawMinimisedPanelCommon(dc, wnd, true_rect)

        dc.SetBrush(self._panel_hover_label_background_brush)
        dc.SetPen(wx.TRANSPARENT_PEN)
        dc.DrawRectangle(preview.x + 1, preview.y + preview.height - 8, preview.width - 2, 7)

        mid_pos = rect.y + rect.height / 5 - preview.y

        if mid_pos < 0 or mid_pos >= preview.height:
            full_rect = wx.Rect(*preview)
            full_rect.x += 1
            full_rect.y += 1
            full_rect.width -= 2
            full_rect.height -= 9
            if mid_pos < 0:
                dc.GradientFillLinear(full_rect, self._page_hover_background_colour,
                                      self._page_hover_background_gradient_colour, wx.SOUTH)
            else:
                dc.GradientFillLinear(full_rect, self._page_hover_background_top_colour,
                                      self._page_hover_background_top_gradient_colour, wx.SOUTH)

        else:
            top_rect = wx.Rect(*preview)
            top_rect.x += 1
            top_rect.y += 1
            top_rect.width -= 2
            top_rect.height = mid_pos
            dc.GradientFillLinear(top_rect, self._page_hover_background_top_colour,
                                  self._page_hover_background_top_gradient_colour, wx.SOUTH)

            btm_rect = wx.Rect(*top_rect)
            btm_rect.y = preview.y + mid_pos
            btm_rect.height = preview.y + preview.height - 7 - btm_rect.y
            dc.GradientFillLinear(btm_rect, self._page_hover_background_colour,
                                  self._page_hover_background_gradient_colour, wx.SOUTH)

        if bitmap.IsOk():
            dc.DrawBitmap(bitmap, preview.x + (preview.width - bitmap.GetWidth()) / 2,
                          preview.y + (preview.height - 7 - bitmap.GetHeight()) / 2, True)

        self.DrawPanelBorder(dc, preview, self._panel_border_pen, self._panel_border_gradient_pen)
        self.DrawPanelBorder(dc, true_rect, self._panel_minimised_border_pen, self._panel_minimised_border_gradient_pen)

[docs]    def DrawMinimisedPanelCommon(self, dc, wnd, true_rect):

        preview = wx.Rect(0, 0, 32, 32)

        if self._flags & RIBBON_BAR_FLOW_VERTICAL:
            preview.x = true_rect.x + 4
            preview.y = true_rect.y + (true_rect.height - preview.height) / 2
        else:
            preview.x = true_rect.x + (true_rect.width - preview.width) / 2
            preview.y = true_rect.y + 4

        dc.SetFont(self._panel_label_font)
        label_width, label_height = dc.GetTextExtent(wnd.GetLabel())

        xpos = true_rect.x + (true_rect.width - label_width + 1) / 2
        ypos = preview.y + preview.height + 5

        if self._flags & RIBBON_BAR_FLOW_VERTICAL:
            xpos = preview.x + preview.width + 5
            ypos = true_rect.y + (true_rect.height - label_height) / 2

        dc.SetTextForeground(self._panel_minimised_label_colour)
        dc.DrawText(wnd.GetLabel(), xpos, ypos)

        arrow_points = [wx.Point() for i in xrange(3)]

        if self._flags & RIBBON_BAR_FLOW_VERTICAL:
            xpos += label_width
            arrow_points[0] = wx.Point(xpos + 5, ypos + label_height / 2)
            arrow_points[1] = arrow_points[0] + wx.Point(-3,  3)
            arrow_points[2] = arrow_points[0] + wx.Point(-3, -3)
        else:
            ypos += label_height
            arrow_points[0] = wx.Point(true_rect.width / 2, ypos + 5)
            arrow_points[1] = arrow_points[0] + wx.Point(-3, -3)
            arrow_points[2] = arrow_points[0] + wx.Point( 3, -3)

        dc.SetPen(wx.TRANSPARENT_PEN)
        B = wx.Brush(self._panel_minimised_label_colour)
        dc.SetBrush(B)
        dc.DrawPolygon(arrow_points, true_rect.x, true_rect.y)

        return preview

[docs]    def DrawButtonBarBackground(self, dc, wnd, rect):
        """
        Draw the background for a L{RibbonButtonBar} control.

        :param `dc`: The device context to draw onto;
        :param `wnd`: The window which is being drawn onto (which will typically be
         the button bar itself, though this is not guaranteed);
        :param `rect`: The rectangle within which to draw.

        """

        self.DrawPartialPageBackground(dc, wnd, rect, True)

[docs]    def DrawPartialPageBackground2(self, dc, wnd, rect, allow_hovered=True):

        # Assume the window is a child of a ribbon page, and also check for a
        # hovered panel somewhere between the window and the page, as it causes
        # the background to change.
        offset = wx.Point(*wnd.GetPosition())
        page = None
        parent = wnd.GetParent()
        hovered = False
        panel = None

        if isinstance(wnd, PANEL.RibbonPanel):
            panel = wnd
            hovered = allow_hovered and panel.IsHovered()
            if panel.GetExpandedDummy() != None:
                offset = panel.GetExpandedDummy().GetPosition()
                parent = panel.GetExpandedDummy().GetParent()

        while 1:

            if panel is None:
                panel = parent
                if isinstance(panel, PANEL.RibbonPanel):
                    hovered = allow_hovered and panel.IsHovered()
                    if panel.GetExpandedDummy() != None:
                        parent = panel.GetExpandedDummy()

            page = parent
            if isinstance(page, PAGE.RibbonPage):
                break

            offset += parent.GetPosition()
            parent = parent.GetParent()
            if parent is None:
                break

        if page != None:
            self.DrawPartialPageBackground(dc, wnd, rect, page, offset, hovered)
            return

        # No page found - fallback to painting with a stock brush
        dc.SetBrush(wx.WHITE_BRUSH)
        dc.SetPen(wx.TRANSPARENT_PEN)
        dc.DrawRectangle(rect.x, rect.y, rect.width, rect.height)

[docs]    def DrawButtonBarButton(self, dc, wnd, rect, kind, state, label, bitmap_large, bitmap_small):
        """
        Draw a single button for a L{RibbonButtonBar} control.

        :param `dc`: The device context to draw onto;
        :param `wnd`: The window which is being drawn onto;
        :param `rect`: The rectangle within which to draw. The size of this rectangle
         will be a size previously returned by L{GetButtonBarButtonSize}, and the
         rectangle will be entirely within a rectangle on the same device context
         previously painted with L{DrawButtonBarBackground};
        :param `kind`: The kind of button to draw (normal, dropdown or hybrid);
        :param `state`: Combination of a size flag and state flags from the
         `RibbonButtonBarButtonState` enumeration;
        :param `label`: The label of the button;
        :param `bitmap_large`: The large bitmap of the button (or the large disabled
         bitmap when ``RIBBON_BUTTONBAR_BUTTON_DISABLED`` is set in );
        :param `bitmap_small`: The small bitmap of the button (or the small disabled
         bitmap when ``RIBBON_BUTTONBAR_BUTTON_DISABLED`` is set in ).

        """

        if kind == RIBBON_BUTTON_TOGGLE:
            kind = RIBBON_BUTTON_NORMAL
            if state & RIBBON_BUTTONBAR_BUTTON_TOGGLED:
                state ^= RIBBON_BUTTONBAR_BUTTON_ACTIVE_MASK

        if state & (RIBBON_BUTTONBAR_BUTTON_HOVER_MASK | RIBBON_BUTTONBAR_BUTTON_ACTIVE_MASK):
            if state & RIBBON_BUTTONBAR_BUTTON_ACTIVE_MASK:
                dc.SetPen(self._button_bar_active_border_pen)
            else:
                dc.SetPen(self._button_bar_hover_border_pen)

            bg_rect = wx.Rect(*rect)
            bg_rect.x += 1
            bg_rect.y += 1
            bg_rect.width -= 2
            bg_rect.height -= 2

            bg_rect_top = wx.Rect(*bg_rect)
            bg_rect_top.height /= 3
            bg_rect.y += bg_rect_top.height
            bg_rect.height -= bg_rect_top.height

            if kind == RIBBON_BUTTON_HYBRID:

                result = state & RIBBON_BUTTONBAR_BUTTON_SIZE_MASK

                if result == RIBBON_BUTTONBAR_BUTTON_LARGE:
                    iYBorder = rect.y + bitmap_large.GetHeight() + 4
                    partial_bg = wx.Rect(*rect)

                    if state & RIBBON_BUTTONBAR_BUTTON_NORMAL_HOVERED:
                        partial_bg.SetBottom(iYBorder - 1)
                    else:
                        partial_bg.height -= (iYBorder - partial_bg.y + 1)
                        partial_bg.y = iYBorder + 1

                    dc.DrawLine(rect.x, iYBorder, rect.x + rect.width, iYBorder)
                    bg_rect.Intersect(partial_bg)
                    bg_rect_top.Intersect(partial_bg)

                elif result == RIBBON_BUTTONBAR_BUTTON_MEDIUM:
                    iArrowWidth = 9

                    if state & RIBBON_BUTTONBAR_BUTTON_NORMAL_HOVERED:
                        bg_rect.width -= iArrowWidth
                        bg_rect_top.width -= iArrowWidth
                        dc.DrawLine(bg_rect_top.x + bg_rect_top.width, rect.y, bg_rect_top.x + bg_rect_top.width,
                                    rect.y + rect.height)
                    else:
                        iArrowWidth -= 1
                        bg_rect.x += bg_rect.width - iArrowWidth
                        bg_rect_top.x += bg_rect_top.width - iArrowWidth
                        bg_rect.width = iArrowWidth
                        bg_rect_top.width = iArrowWidth
                        dc.DrawLine(bg_rect_top.x - 1, rect.y, bg_rect_top.x - 1, rect.y + rect.height)

            if state & RIBBON_BUTTONBAR_BUTTON_ACTIVE_MASK:

                dc.GradientFillLinear(bg_rect_top, self._button_bar_active_background_top_colour,
                                      self._button_bar_active_background_top_gradient_colour, wx.SOUTH)
                dc.GradientFillLinear(bg_rect, self._button_bar_active_background_colour,
                                      self._button_bar_active_background_gradient_colour, wx.SOUTH)

            else:
                dc.GradientFillLinear(bg_rect_top, self._button_bar_hover_background_top_colour,
                                      self._button_bar_hover_background_top_gradient_colour, wx.SOUTH)
                dc.GradientFillLinear(bg_rect, self._button_bar_hover_background_colour,
                                      self._button_bar_hover_background_gradient_colour, wx.SOUTH)

            border_points = [wx.Point() for i in xrange(9)]
            border_points[0] = wx.Point(2, 0)
            border_points[1] = wx.Point(rect.width - 3, 0)
            border_points[2] = wx.Point(rect.width - 1, 2)
            border_points[3] = wx.Point(rect.width - 1, rect.height - 3)
            border_points[4] = wx.Point(rect.width - 3, rect.height - 1)
            border_points[5] = wx.Point(2, rect.height - 1)
            border_points[6] = wx.Point(0, rect.height - 3)
            border_points[7] = wx.Point(0, 2)
            border_points[8] = border_points[0]

            dc.DrawLines(border_points, rect.x, rect.y)

        dc.SetFont(self._button_bar_label_font)
        dc.SetTextForeground(self._button_bar_label_colour)
        self.DrawButtonBarButtonForeground(dc, rect, kind, state, label, bitmap_large, bitmap_small)

[docs]    def DrawButtonBarButtonForeground(self, dc, rect, kind, state, label, bitmap_large, bitmap_small):

        result = state & RIBBON_BUTTONBAR_BUTTON_SIZE_MASK

        if result == RIBBON_BUTTONBAR_BUTTON_LARGE:

            padding = 2
            dc.DrawBitmap(bitmap_large, rect.x + (rect.width - bitmap_large.GetWidth()) / 2,
                          rect.y + padding, True)
            ypos = rect.y + padding + bitmap_large.GetHeight() + padding
            arrow_width = (kind == RIBBON_BUTTON_NORMAL and [0] or [8])[0]

            label_w, label_h = dc.GetTextExtent(label)

            if label_w + 2 * padding <= rect.width:

                dc.DrawText(label, rect.x + (rect.width - label_w) / 2, ypos)
                if arrow_width != 0:
                    self.DrawDropdownArrow(dc, rect.x + rect.width / 2,
                                           ypos + (label_h * 3) / 2,
                                           self._button_bar_label_colour)
            else:
                breaki = len(label)

                while breaki > 0:
                    breaki -= 1
                    if RibbonCanLabelBreakAtPosition(label, breaki):
                        label_top = label[0:breaki]
                        label_w, label_h = dc.GetTextExtent(label_top)

                        if label_w + 2 * padding <= rect.width:
                            dc.DrawText(label_top, rect.x + (rect.width - label_w) / 2, ypos)
                            ypos += label_h
                            label_bottom = label[breaki:]
                            label_w, label_h = dc.GetTextExtent(label_bottom)
                            label_w += arrow_width
                            iX = rect.x + (rect.width - label_w) / 2
                            dc.DrawText(label_bottom, iX, ypos)

                            if arrow_width != 0:
                                self.DrawDropdownArrow(dc, iX + 2 +label_w - arrow_width,
                                                       ypos + label_h / 2 + 1,
                                                       self._button_bar_label_colour)

                            break

        elif result == RIBBON_BUTTONBAR_BUTTON_MEDIUM:

            x_cursor = rect.x + 2
            dc.DrawBitmap(bitmap_small, x_cursor, rect.y + (rect.height - bitmap_small.GetHeight())/2, True)
            x_cursor += bitmap_small.GetWidth() + 2
            label_w, label_h = dc.GetTextExtent(label)
            dc.DrawText(label, x_cursor, rect.y + (rect.height - label_h) / 2)
            x_cursor += label_w + 3

            if kind != RIBBON_BUTTON_NORMAL:
                self.DrawDropdownArrow(dc, x_cursor, rect.y + rect.height / 2,
                                       self._button_bar_label_colour)

        else:
            # TODO
            pass

[docs]    def DrawToolBarBackground(self, dc, wnd, rect):
        """
        Draw the background for a L{RibbonToolBar} control.

        :param `dc`: The device context to draw onto;
        :param `wnd`: The which is being drawn onto. In most cases this will be a
         L{RibbonToolBar}, but it doesn't have to be;
        :param `rect`: The rectangle within which to draw. Some of this rectangle
         will later be drawn over using L{DrawToolGroupBackground} and L{DrawTool},
         but not all of it will (unless there is only a single group of tools).

        """

        self.DrawPartialPageBackground(dc, wnd, rect)

[docs]    def DrawToolGroupBackground(self, dc, wnd, rect):
        """
        Draw the background for a group of tools on a L{RibbonToolBar} control.

        :param `dc`: The device context to draw onto;
        :param `wnd`: The window which is being drawn onto. In most cases this will
         be a L{RibbonToolBar}, but it doesn't have to be;
        :param `rect`: The rectangle within which to draw. This rectangle is a union
         of the individual tools' rectangles. As there are no gaps between tools,
         this rectangle will be painted over exactly once by calls to L{DrawTool}.
         The group background could therefore be painted by L{DrawTool}, though it
         can be conceptually easier and more efficient to draw it all at once here.
         The rectangle will be entirely within a rectangle on the same device context
         previously painted with L{DrawToolBarBackground}.

        """

        dc.SetPen(self._toolbar_border_pen)
        outline = [wx.Point() for i in xrange(9)]
        outline[0] = wx.Point(2, 0)
        outline[1] = wx.Point(rect.width - 3, 0)
        outline[2] = wx.Point(rect.width - 1, 2)
        outline[3] = wx.Point(rect.width - 1, rect.height - 3)
        outline[4] = wx.Point(rect.width - 3, rect.height - 1)
        outline[5] = wx.Point(2, rect.height - 1)
        outline[6] = wx.Point(0, rect.height - 3)
        outline[7] = wx.Point(0, 2)
        outline[8] = outline[0]

        dc.DrawLines(outline, rect.x, rect.y)

[docs]    def DrawTool(self, dc, wnd, rect, bitmap, kind, state):
        """
        Draw a single tool (for a L{RibbonToolBar} control).

        :param `dc`: The device context to draw onto;
        :param `wnd`: The window which is being drawn onto. In most cases this will
         be a L{RibbonToolBar}, but it doesn't have to be;
        :param `rect`: The rectangle within which to draw. The size of this rectangle
         will at least the size returned by L{GetToolSize}, and the height of it will
         be equal for all tools within the same group. The rectangle will be entirely
         within a rectangle on the same device context previously painted with
         L{DrawToolGroupBackground};
        :param `bitmap`: The bitmap to use as the tool's foreground. If the tool is a
         hybrid or dropdown tool, then the foreground should also contain a standard
         dropdown button;
        :param `kind`: The kind of tool to draw (normal, dropdown, or hybrid);
        :param `state`: A combination of `RibbonToolBarToolState` flags giving the
         state of the tool and it's relative position within a tool group.

        """

        bg_rect = wx.Rect(*rect)
        bg_rect.Deflate(1, 1)

        if state & RIBBON_TOOLBAR_TOOL_LAST == 0:
            bg_rect.width += 1

        is_split_hybrid = (kind == RIBBON_BUTTON_HYBRID and (state & (RIBBON_TOOLBAR_TOOL_HOVER_MASK | RIBBON_TOOLBAR_TOOL_ACTIVE_MASK)))

        # Background
        bg_rect_top = wx.Rect(*bg_rect)
        bg_rect_top.height = (bg_rect_top.height * 2) / 5
        bg_rect_btm = wx.Rect(*bg_rect)
        bg_rect_btm.y += bg_rect_top.height
        bg_rect_btm.height -= bg_rect_top.height

        bg_top_colour = self._tool_background_top_colour
        bg_top_grad_colour = self._tool_background_top_gradient_colour
        bg_colour = self._tool_background_colour
        bg_grad_colour = self._tool_background_gradient_colour

        if state & RIBBON_TOOLBAR_TOOL_ACTIVE_MASK:
            bg_top_colour = self._tool_active_background_top_colour
            bg_top_grad_colour = self._tool_active_background_top_gradient_colour
            bg_colour = self._tool_active_background_colour
            bg_grad_colour = self._tool_active_background_gradient_colour

        elif state & RIBBON_TOOLBAR_TOOL_HOVER_MASK:
            bg_top_colour = self._tool_hover_background_top_colour
            bg_top_grad_colour = self._tool_hover_background_top_gradient_colour
            bg_colour = self._tool_hover_background_colour
            bg_grad_colour = self._tool_hover_background_gradient_colour

        dc.GradientFillLinear(bg_rect_top, bg_top_colour, bg_top_grad_colour, wx.SOUTH)
        dc.GradientFillLinear(bg_rect_btm, bg_colour, bg_grad_colour, wx.SOUTH)

        if is_split_hybrid:
            nonrect = wx.Rect(*bg_rect)
            if state & (RIBBON_TOOLBAR_TOOL_DROPDOWN_HOVERED | RIBBON_TOOLBAR_TOOL_DROPDOWN_ACTIVE):
                nonrect.width -= 8
            else:
                nonrect.x += nonrect.width - 8
                nonrect.width = 8

            B = wx.Brush(self._tool_hover_background_top_colour)
            dc.SetPen(wx.TRANSPARENT_PEN)
            dc.SetBrush(B)
            dc.DrawRectangle(nonrect.x, nonrect.y, nonrect.width, nonrect.height)

        # Border
        dc.SetPen(self._toolbar_border_pen)

        if state & RIBBON_TOOLBAR_TOOL_FIRST:
            dc.DrawPoint(rect.x + 1, rect.y + 1)
            dc.DrawPoint(rect.x + 1, rect.y + rect.height - 2)
        else:
            dc.DrawLine(rect.x, rect.y + 1, rect.x, rect.y + rect.height - 1)

        if state & RIBBON_TOOLBAR_TOOL_LAST:
            dc.DrawPoint(rect.x + rect.width - 2, rect.y + 1)
            dc.DrawPoint(rect.x + rect.width - 2, rect.y + rect.height - 2)

        # Foreground
        avail_width = bg_rect.GetWidth()

        if kind != RIBBON_BUTTON_NORMAL:
            avail_width -= 8
            if is_split_hybrid:
                dc.DrawLine(rect.x + avail_width + 1, rect.y, rect.x + avail_width + 1, rect.y + rect.height)

            dc.DrawBitmap(self._toolbar_drop_bitmap, bg_rect.x + avail_width + 2,
                          bg_rect.y + (bg_rect.height / 2) - 2, True)

        dc.DrawBitmap(bitmap, bg_rect.x + (avail_width - bitmap.GetWidth()) / 2,
                      bg_rect.y + (bg_rect.height - bitmap.GetHeight()) / 2, True)

[docs]    def GetBarTabWidth(self, dc, wnd, label, bitmap, ideal=None, small_begin_need_separator=None,
                       small_must_have_separator=None, minimum=None):

        """
        Calculate the ideal and minimum width (in pixels) of a tab in a ribbon bar.

        :param `dc`: A device context to use when one is required for size calculations;
        :param `wnd`: The window onto which the tab will eventually be drawn;
        :param `label`: The tab's label (or "" if it has none);
        :param `bitmap`: The tab's icon (or `wx.NullBitmap` if it has none);
        :param `ideal`: The ideal width (in pixels) of the tab;
        :param `small_begin_need_separator`: A size less than the size, at which a
         tab separator should begin to be drawn (i.e. drawn, but still fairly transparent);
        :param `small_must_have_separator`: A size less than the size, at which a
         tab separator must be drawn (i.e. drawn at full opacity);
        :param `minimum`: A size less than the size, and greater than or equal to
         zero, which is the minimum pixel width for the tab.

        """

        width = 0
        mini = 0

        if (self._flags & RIBBON_BAR_SHOW_PAGE_LABELS) and label.strip():
            dc.SetFont(self._tab_label_font)
            width += dc.GetTextExtent(label)[0]
            mini += min(25, width) # enough for a few chars

            if bitmap.IsOk():
                # gap between label and bitmap
                width += 4
                mini += 2

        if (self._flags & RIBBON_BAR_SHOW_PAGE_ICONS) and bitmap.IsOk():
            width += bitmap.GetWidth()
            mini += bitmap.GetWidth()

        ideal = width + 30
        small_begin_need_separator = width + 20
        small_must_have_separator = width + 10
        minimum = mini

        return ideal, small_begin_need_separator, small_must_have_separator, minimum

[docs]    def GetTabCtrlHeight(self, dc, wnd, pages):
        """
        Calculate the height (in pixels) of the tab region of a ribbon bar.

        Note that as the tab region can contain scroll buttons, the height should be
        greater than or equal to the minimum height for a tab scroll button.

        :param `dc`: A device context to use when one is required for size calculations;
        :param `wnd`: The window onto which the tabs will eventually be drawn;
        :param `pages`: The tabs which will acquire the returned height.

        """

        text_height = 0
        icon_height = 0

        if len(pages) <= 1 and (self._flags & RIBBON_BAR_ALWAYS_SHOW_TABS) == 0:
            # To preserve space, a single tab need not be displayed. We still need
            # two pixels of border / padding though.
            return 2

        if self._flags & RIBBON_BAR_SHOW_PAGE_LABELS:
            dc.SetFont(self._tab_label_font)
            text_height = dc.GetTextExtent("ABCDEFXj")[1] + 10

        if self._flags & RIBBON_BAR_SHOW_PAGE_ICONS:
            for info in pages:
                if info.page.GetIcon().IsOk():
                    icon_height = max(icon_height, info.page.GetIcon().GetHeight() + 4)

        return max(text_height, icon_height)

[docs]    def GetScrollButtonMinimumSize(self, dc, wnd, style):
        """
        Calculate the minimum size (in pixels) of a scroll button.

        :param `dc`: A device context to use when one is required for size calculations;
        :param `wnd`: The window onto which the scroll button will eventually be drawn;
        :param `style`: A combination of flags from `RibbonScrollButtonStyle`, including
         a direction, and a for flag (state flags may be given too, but should be ignored,
         as a button should retain a constant size, regardless of its state).

        """

        return wx.Size(12, 12)

[docs]    def GetPanelSize(self, dc, wnd, client_size, client_offset=None):
        """
        Calculate the size of a panel for a given client size.

        This should increment the given size by enough to fit the panel label and other
        chrome.

        :param `dc`: A device context to use if one is required for size calculations;
        :param `wnd`: The ribbon panel in question;
        :param `client_size`: The client size;
        :param `client_offset`: The offset where the client rectangle begins within the
         panel (may be ``None``).

        :see: L{GetPanelClientSize}
        """

        dc.SetFont(self._panel_label_font)
        label_size = wx.Size(*dc.GetTextExtent(wnd.GetLabel()))

        client_size.IncBy(0, label_size.GetHeight())

        if self._flags & RIBBON_BAR_FLOW_VERTICAL:
            client_size.IncBy(4, 8)
        else:
            client_size.IncBy(6, 6)

        if client_offset != None:
            if self._flags & RIBBON_BAR_FLOW_VERTICAL:
                client_offset = wx.Point(2, 3)
            else:
                client_offset = wx.Point(3, 2)

        return client_size

[docs]    def GetPanelClientSize(self, dc, wnd, size, client_offset=None):
        """
        Calculate the client size of a panel for a given overall size.

        This should act as the inverse to L{GetPanelSize}, and decrement the given size
        by enough to fit the panel label and other chrome.

        :param `dc`: A device context to use if one is required for size calculations;
        :param `wnd`: The ribbon panel in question;
        :param `size`: The overall size to calculate client size for;
        :param `client_offset`: The offset where the returned client size begins within
         the given (may be ``None``).

        :see: L{GetPanelSize}
        """

        dc.SetFont(self._panel_label_font)
        label_size = wx.Size(*dc.GetTextExtent(wnd.GetLabel()))

        size.DecBy(0, label_size.GetHeight())

        if self._flags & RIBBON_BAR_FLOW_VERTICAL:
            size.DecBy(4, 8)
        else:
            size.DecBy(6, 6)

        if client_offset != None:
            if self._flags & RIBBON_BAR_FLOW_VERTICAL:
                client_offset = wx.Point(2, 3)
            else:
                client_offset = wx.Point(3, 2)

        if size.x < 0:
            size.x = 0
        if size.y < 0:
            size.y = 0

        return size, client_offset

[docs]    def GetGallerySize(self, dc, wnd, client_size):
        """
        Calculate the size of a L{RibbonGallery} control for a given client size.

        This should increment the given size by enough to fit the gallery border,
        buttons, and any other chrome.

        :param `dc`: A device context to use if one is required for size calculations;
        :param `wnd`: The gallery in question;
        :param `client_size`: The client size.

        :see: L{GetGalleryClientSize}
        """

        client_size.IncBy(2, 1) # Left / top padding

        if self._flags & RIBBON_BAR_FLOW_VERTICAL:
            client_size.IncBy(1, 16) # Right / bottom padding
        else:
            client_size.IncBy(16, 1) # Right / bottom padding

        return client_size

[docs]    def GetGalleryClientSize(self, dc, wnd, size, client_offset=None, scroll_up_button=None,
                             scroll_down_button=None, extension_button=None):

        """
        Calculate the client size of a L{RibbonGallery} control for a given size.

        This should act as the inverse to L{GetGallerySize}, and decrement the given
        size by enough to fir the gallery border, buttons, and other chrome.

        :param `dc`: A device context to use if one is required for size calculations;
        :param `wnd`: The gallery in question;
        :param `size`: The overall size to calculate the client size for;
        :param `client_offset`: The position within the given size at which the
         returned client size begins;
        :param `scroll_up_button`: The rectangle within the given size which the
         scroll up button occupies;
        :param `scroll_down_button`: The rectangle within the given size which the
         scroll down button occupies;
        :param `extension_button`: The rectangle within the given size which the
         extension button occupies.

        """

        scroll_up = wx.Rect()
        scroll_down = wx.Rect()
        extension = wx.Rect()

        if self._flags & RIBBON_BAR_FLOW_VERTICAL:
            # Flow is vertical - put buttons on bottom
            scroll_up.y = size.GetHeight() - 15
            scroll_up.height = 15
            scroll_up.x = 0
            scroll_up.width = (size.GetWidth() + 2) / 3
            scroll_down.y = scroll_up.y
            scroll_down.height = scroll_up.height
            scroll_down.x = scroll_up.x + scroll_up.width
            scroll_down.width = scroll_up.width
            extension.y = scroll_down.y
            extension.height = scroll_down.height
            extension.x = scroll_down.x + scroll_down.width
            extension.width = size.GetWidth() - scroll_up.width - scroll_down.width
            size.DecBy(1, 16)
            size.DecBy(2, 1)

        else:
            # Flow is horizontal - put buttons on right
            scroll_up.x = size.GetWidth() - 15
            scroll_up.width = 15
            scroll_up.y = 0
            scroll_up.height = (size.GetHeight() + 2) / 3
            scroll_down.x = scroll_up.x
            scroll_down.width = scroll_up.width
            scroll_down.y = scroll_up.y + scroll_up.height
            scroll_down.height = scroll_up.height
            extension.x = scroll_down.x
            extension.width = scroll_down.width
            extension.y = scroll_down.y + scroll_down.height
            extension.height = size.GetHeight() - scroll_up.height - scroll_down.height
            size.DecBy(16, 1)
            size.DecBy( 2, 1)

        client_offset = wx.Point(2, 1)
        scroll_up_button = scroll_up
        scroll_down_button = scroll_down
        extension_button = extension

        return size, client_offset, scroll_up_button, scroll_down_button, extension_button

[docs]    def GetPageBackgroundRedrawArea(self, dc, wnd, page_old_size, page_new_size):
        """
        Calculate the portion of a page background which needs to be redrawn when a page
        is resized.

        To optimise the drawing of page backgrounds, as small an area as possible should
        be returned. Of couse, if the way in which a background is drawn means that the
        entire background needs to be repainted on resize, then the entire new size
        should be returned.

        :param `dc`: A device context to use when one is required for size calculations;
        :param `wnd`: The page which is being resized;
        :param `page_old_size`: The size of the page prior to the resize (which has
         already been painted);
        :param `page_new_size`: The size of the page after the resize.

        """

        if page_new_size.GetWidth() != page_old_size.GetWidth():
            if page_new_size.GetHeight() != page_old_size.GetHeight():
                # Width and height both changed - redraw everything
                return wx.Rect(0, 0, *page_new_size)
            else:
                # Only width changed - redraw right hand side
                right_edge_width = 4
                new_rect = wx.Rect(page_new_size.GetWidth() - right_edge_width, 0, right_edge_width, page_new_size.GetHeight())
                old_rect = wx.Rect(page_old_size.GetWidth() - right_edge_width, 0, right_edge_width, page_old_size.GetHeight())

        else:
            if page_new_size.GetHeight() == page_old_size.GetHeight():
                # Nothing changed (should never happen) - redraw nothing
                return wx.Rect(0, 0, 0, 0)
            else:
                # Height changed - need to redraw everything (as the background
                # gradient is done vertically).
                return wx.Rect(0, 0, *page_new_size)

        new_rect.Union(old_rect)
        new_rect.Intersect(wx.Rect(0, 0, *page_new_size))
        return new_rect

[docs]    def GetButtonBarButtonSize(self, dc, wnd, kind, size, label, bitmap_size_large, bitmap_size_small,
                               button_size=None, normal_region=None, dropdown_region=None):
        """
        Calculate the size of a button within a L{RibbonButtonBar}.

        :param `dc`: A device context to use when one is required for size calculations;
        :param `wnd`: The window onto which the button will eventually be drawn
         (which is normally a L{RibbonButtonBar}, though this is not guaranteed);
        :param `kind`: The kind of button;
        :param `size`: The size-class to calculate the size for. Buttons on a button
         bar can have three distinct sizes: ``RIBBON_BUTTONBAR_BUTTON_SMALL``,
         ``RIBBON_BUTTONBAR_BUTTON_MEDIUM``, and ``RIBBON_BUTTONBAR_BUTTON_LARGE``.
         If the requested size-class is not applicable, then ``False`` should be returned;
        :param `label`: The label of the button;
        :param `bitmap_size_large`: The size of all "large" bitmaps on the button bar;
        :param `bitmap_size_small`: The size of all "small" bitmaps on the button bar;
        :param `button_size`: The size, in pixels, of the button;
        :param `normal_region`: The region of the button which constitutes the normal button;
        :param `dropdown_region`: The region of the button which constitutes the dropdown button.

        :returns: ``True`` if a size exists for the button, ``False`` otherwise.
        """

        drop_button_width = 8

        normal_region = wx.Rect()
        dropdown_region = wx.Rect()

        dc.SetFont(self._button_bar_label_font)
        result = size & RIBBON_BUTTONBAR_BUTTON_SIZE_MASK

        if result == RIBBON_BUTTONBAR_BUTTON_SMALL:
            # Small bitmap, no label
            button_size = bitmap_size_small + wx.Size(6, 4)

            if kind in [RIBBON_BUTTON_NORMAL, RIBBON_BUTTON_TOGGLE]:
                normal_region = wx.Rect(0, 0, *button_size)
                dropdown_region = wx.Rect(0, 0, 0, 0)

            elif kind == RIBBON_BUTTON_DROPDOWN:
                button_size += wx.Size(drop_button_width, 0)
                dropdown_region = wx.Rect(0, 0, *button_size)
                normal_region = wx.Rect(0, 0, 0, 0)

            elif kind == RIBBON_BUTTON_HYBRID:
                normal_region = wx.Rect(0, 0, *button_size)
                dropdown_region = wx.Rect(button_size.GetWidth(), 0, drop_button_width, button_size.GetHeight())
                button_size += wx.Size(drop_button_width, 0)

        elif result == RIBBON_BUTTONBAR_BUTTON_MEDIUM:
            # Small bitmap, with label to the right
            is_supported, button_size, normal_region, dropdown_region = self.GetButtonBarButtonSize(dc, wnd, kind,
                                                                                RIBBON_BUTTONBAR_BUTTON_SMALL,
                                                                                label, bitmap_size_large,
                                                                                bitmap_size_small)
            text_size = dc.GetTextExtent(label)[0]
            button_size.SetWidth(button_size.GetWidth() + text_size)

            if kind == RIBBON_BUTTON_DROPDOWN:
                dropdown_region.SetWidth(dropdown_region.GetWidth() + text_size)

            elif kind == RIBBON_BUTTON_HYBRID:
                dropdown_region.SetX(dropdown_region.GetX() + text_size)
                normal_region.SetWidth(normal_region.GetWidth() + text_size)
                # no break
            elif kind in [RIBBON_BUTTON_NORMAL, RIBBON_BUTTON_TOGGLE]:
                normal_region.SetWidth(normal_region.GetWidth() + text_size)

        elif result == RIBBON_BUTTONBAR_BUTTON_LARGE:
            # Large bitmap, with label below (possibly split over 2 lines)

            icon_size = wx.Size(*bitmap_size_large)
            icon_size += wx.Size(4, 4)
            best_width, label_height = dc.GetTextExtent(label)
            last_line_extra_width = 0

            if kind not in [RIBBON_BUTTON_NORMAL, RIBBON_BUTTON_TOGGLE]:
                last_line_extra_width += 8

            for i in xrange(0, len(label)):
                if RibbonCanLabelBreakAtPosition(label, i):

                    width = max(dc.GetTextExtent(label[0:i])[0],
                                dc.GetTextExtent(label[i+1:])[0] + last_line_extra_width)
                    if width < best_width:
                        best_width = width

            label_height *= 2 # Assume two lines even when only one is used
                              # (to give all buttons a consistent height)
            icon_size.SetWidth(max(icon_size.GetWidth(), best_width) + 6)
            icon_size.SetHeight(icon_size.GetHeight() + label_height)
            button_size = wx.Size(*icon_size)

            if kind == RIBBON_BUTTON_DROPDOWN:
                dropdown_region = wx.Rect(0, 0, *icon_size)
            elif kind == RIBBON_BUTTON_HYBRID:
                normal_region = wx.Rect(0, 0, *icon_size)
                normal_region.height -= 2 + label_height
                dropdown_region.x = 0
                dropdown_region.y = normal_region.height
                dropdown_region.width = icon_size.GetWidth()
                dropdown_region.height = icon_size.GetHeight() - normal_region.height
            elif kind in [RIBBON_BUTTON_NORMAL, RIBBON_BUTTON_TOGGLE]:
                normal_region = wx.Rect(0, 0, *icon_size)

        return True, button_size, normal_region, dropdown_region

[docs]    def GetMinimisedPanelMinimumSize(self, dc, wnd, desired_bitmap_size=None, expanded_panel_direction=None):
        """
        Calculate the size of a minimised ribbon panel.

        :param `dc`: A device context to use when one is required for size calculations;
        :param `wnd`: The ribbon panel in question. Attributes like the panel label can
         be queried from this;
        :param `desired_bitmap_size`: MISSING DESCRIPTION;
        :param `expanded_panel_direction`: MISSING DESCRIPTION.

        """

        if desired_bitmap_size != None:
            desired_bitmap_size = wx.Size(16, 16)

        if expanded_panel_direction != None:
            if self._flags & RIBBON_BAR_FLOW_VERTICAL:
                expanded_panel_direction = wx.EAST
            else:
                expanded_panel_direction = wx.SOUTH

        base_size = wx.Size(42, 42)

        dc.SetFont(self._panel_label_font)
        label_size = wx.Size(*dc.GetTextExtent(wnd.GetLabel()))
        label_size.IncBy(2, 2) # Allow for differences between this DC and a paint DC
        label_size.IncBy(6, 0) # Padding
        label_size.y *= 2 # Second line for dropdown button

        if self._flags & RIBBON_BAR_FLOW_VERTICAL:
            # Label alongside icon
            return wx.Size(base_size.x + label_size.x, max(base_size.y, label_size.y)), \
                   desired_bitmap_size, expanded_panel_direction
        else:
            # Label beneath icon
            return wx.Size(max(base_size.x, label_size.x), base_size.y + label_size.y), \
                   desired_bitmap_size, expanded_panel_direction

[docs]    def GetToolSize(self, dc, wnd, bitmap_size, kind, is_first, is_last, dropdown_region=None):
        """
        Calculate the size of a tool within a L{RibbonToolBar}.

        :param `dc`: A device context to use when one is required for size calculations;
        :param `wnd`: The window onto which the tool will eventually be drawn;
        :param `bitmap_size`: The size of the tool's foreground bitmap;
        :param `kind`: The kind of tool (normal, dropdown, or hybrid);
        :param `is_first`: ``True`` if the tool is the first within its group. ``False``
         otherwise;
        :param `is_last`: ``True`` if the tool is the last within its group. ``False``
         otherwise;
        :param `dropdown_region`: For dropdown and hybrid tools, the region within the
         returned size which counts as the dropdown part.
        """

        size = wx.Size(*bitmap_size)
        size.IncBy(7, 6)

        if is_last:
            size.IncBy(1, 0)

        if kind != RIBBON_BUTTON_NORMAL:
            size.IncBy(8, 0)
            if kind == RIBBON_BUTTON_DROPDOWN:
                dropdown_region = wx.Rect(0, 0, *size)
            else:
                dropdown_region = wx.Rect(size.GetWidth() - 8, 0, 8, size.GetHeight())
        else:
            dropdown_region = wx.Rect(0, 0, 0, 0)

        return size, dropdown_region

Navigation

  • index
  • modules |
  • Home |
  • Gallery |
  • Contents»
  • Module code »
  • ribbon.art_msw


ribbon.bar

  • modules |
  • Home |
  • Gallery |
  • Contents»
  • Module code »
  • ribbon.bar

Source code for ribbon.bar

# --------------------------------------------------------------------------- #
# RIBBONBAR Library wxPython IMPLEMENTATION
#
# Original C++ Code From Peter Cawley.
#
# Current wxRibbon Version Tracked: wxWidgets 2.9.0 SVN HEAD
#
#
# Python Code By:
#
# Andrea Gavana, @ 15 Oct 2009
# Latest Revision: 17 Aug 2011, 15.00 GMT
#
# 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
# --------------------------------------------------------------------------- #

"""
Top-level control in a ribbon user interface.

Description
===========

Serves as a tabbed container for L{RibbonPage} - a ribbon user interface typically
has a ribbon bar, which contains one or more RibbonPages, which in turn each contains
one or more RibbonPanels, which in turn contain controls. While a L{RibbonBar} has
tabs similar to a `wx.Notebook`, it does not follow the same API for adding pages.
Containers like `wx.Notebook` can contain any type of window as a page, hence the
normal procedure is to create the sub-window and then call `wx.BookCtrlBase.AddPage()`.

As L{RibbonBar} can only have L{RibbonPage} as children (and a L{RibbonPage} can only
have a L{RibbonBar} as parent), when a page is created, it is automatically added to
the bar - there is no `AddPage` equivalent to call.

After all pages have been created, and all controls and panels placed on those pages,
L{Realize} must be called.

Window Styles
=============

This class supports the following window styles:

========================================== =========== ==========================================
Window Styles                              Hex Value   Description
========================================== =========== ==========================================
``RIBBON_BAR_DEFAULT_STYLE``                       0x9 Defined as ``RIBBON_BAR_FLOW_HORIZONTAL`` | ``RIBBON_BAR_SHOW_PAGE_LABELS`` | ``RIBBON_BAR_SHOW_PANEL_EXT_BUTTONS``
``RIBBON_BAR_FOLDBAR_STYLE``                      0x1e Defined as ``RIBBON_BAR_FLOW_VERTICAL`` | ``RIBBON_BAR_SHOW_PAGE_ICONS`` | ``RIBBON_BAR_SHOW_PANEL_EXT_BUTTONS`` | ``RIBBON_BAR_SHOW_PANEL_MINIMISE_BUTTONS``
``RIBBON_BAR_SHOW_PAGE_LABELS``                    0x1 Causes labels to be shown on the tabs in the ribbon bar.
``RIBBON_BAR_SHOW_PAGE_ICONS``                     0x2 Causes icons to be shown on the tabs in the ribbon bar.
``RIBBON_BAR_FLOW_HORIZONTAL``                     0x0 Causes panels within pages to stack horizontally.
``RIBBON_BAR_FLOW_VERTICAL``                       0x4 Causes panels within pages to stack vertically.
``RIBBON_BAR_SHOW_PANEL_EXT_BUTTONS``              0x8 Causes extension buttons to be shown on panels (where the panel has such a button).
``RIBBON_BAR_SHOW_PANEL_MINIMISE_BUTTONS``        0x10 Causes minimise buttons to be shown on panels (where the panel has such a button).
========================================== =========== ==========================================

Events Processing
=================

This class processes the following events:

================================= =================================
Event Name                        Description
================================= =================================
``EVT_RIBBONBAR_PAGE_CHANGED``    Triggered after the transition from one page being active to a different page being active.
``EVT_RIBBONBAR_PAGE_CHANGING``   Triggered prior to the transition from one page being active to a different page being active, and can veto the change.
``EVT_RIBBONBAR_TAB_MIDDLE_DOWN`` Triggered when the middle mouse button is pressed on a tab.
``EVT_RIBBONBAR_TAB_MIDDLE_UP``   Triggered when the middle mouse button is released on a tab.
``EVT_RIBBONBAR_TAB_RIGHT_DOWN``  Triggered when the right mouse button is pressed on a tab.
``EVT_RIBBONBAR_TAB_RIGHT_UP``    Triggered when the right mouse button is released on a tab.
``EVT_RIBBONBAR_TAB_LEFT_DCLICK`` Triggered when the user double-clicks on a tab.
================================= =================================

See Also
========

L{RibbonPage}, L{RibbonPanel}
"""

import wx
import types

from control import RibbonControl

from art_internal import RibbonPageTabInfo
from art_msw import RibbonMSWArtProvider
from art import *

wxEVT_COMMAND_RIBBONBAR_PAGE_CHANGED = wx.NewEventType()
wxEVT_COMMAND_RIBBONBAR_PAGE_CHANGING = wx.NewEventType()
wxEVT_COMMAND_RIBBONBAR_TAB_MIDDLE_DOWN = wx.NewEventType()
wxEVT_COMMAND_RIBBONBAR_TAB_MIDDLE_UP = wx.NewEventType()
wxEVT_COMMAND_RIBBONBAR_TAB_RIGHT_DOWN = wx.NewEventType()
wxEVT_COMMAND_RIBBONBAR_TAB_RIGHT_UP = wx.NewEventType()
wxEVT_COMMAND_RIBBONBAR_TAB_LEFT_DCLICK = wx.NewEventType()

EVT_RIBBONBAR_PAGE_CHANGED = wx.PyEventBinder(wxEVT_COMMAND_RIBBONBAR_PAGE_CHANGED, 1)
EVT_RIBBONBAR_PAGE_CHANGING = wx.PyEventBinder(wxEVT_COMMAND_RIBBONBAR_PAGE_CHANGING, 1)
EVT_RIBBONBAR_TAB_MIDDLE_DOWN = wx.PyEventBinder(wxEVT_COMMAND_RIBBONBAR_TAB_MIDDLE_DOWN, 1)
EVT_RIBBONBAR_TAB_MIDDLE_UP = wx.PyEventBinder(wxEVT_COMMAND_RIBBONBAR_TAB_MIDDLE_UP, 1)
EVT_RIBBONBAR_TAB_RIGHT_DOWN = wx.PyEventBinder(wxEVT_COMMAND_RIBBONBAR_TAB_RIGHT_DOWN, 1)
EVT_RIBBONBAR_TAB_RIGHT_UP = wx.PyEventBinder(wxEVT_COMMAND_RIBBONBAR_TAB_RIGHT_UP, 1)
EVT_RIBBONBAR_TAB_LEFT_DCLICK = wx.PyEventBinder(wxEVT_COMMAND_RIBBONBAR_TAB_LEFT_DCLICK, 1)

[docs]def SET_FLAG(variable, flag):

    refresh_tabs = False
    if variable & flag != flag:
        variable |= flag
        refresh_tabs = True

    return variable, refresh_tabs

[docs]def UNSET_FLAG(variable, flag):

    refresh_tabs = False
    if variable & flag:
        variable &= ~flag
        refresh_tabs = True

    return variable, refresh_tabs

[docs]class RibbonBarEvent(wx.NotifyEvent):
    """
    Event used to indicate various actions relating to a L{RibbonBar}.

    See L{RibbonBar} for available event types.
    """

[docs]    def __init__(self, command_type=None, win_id=0, page=None):

        wx.NotifyEvent.__init__(self, command_type, win_id)
        self._page = page

        self._isAllowed = True

[docs]    def GetPage(self):
        """
        Returns the page being changed to, or being clicked on.
        """

        return self._page

[docs]    def SetPage(self, page):
        """
        Sets the page relating to this event.

        :param `page`: MISSING DESCRIPTION.

        """

        self._page = page

[docs]    def Allow(self):

        self._isAllowed = True

[docs]    def Veto(self):

        self._isAllowed = False

[docs]    def IsAllowed(self):

        return self._isAllowed

[docs]class RibbonBar(RibbonControl):

[docs]    def __init__(self, parent, id=wx.ID_ANY, pos=wx.DefaultPosition, size=wx.DefaultSize, agwStyle=RIBBON_BAR_DEFAULT_STYLE,
                 validator=wx.DefaultValidator, name="RibbonBar"):
        """
        Default constructor.

        :param `parent`: Pointer to a parent window;
        :param `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;
        :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;
        :param `agwStyle`: the AGW-specific window style. This can be a combination of the
         following bits:

         ========================================== =========== ==========================================
         Window Styles                              Hex Value   Description
         ========================================== =========== ==========================================
         ``RIBBON_BAR_DEFAULT_STYLE``                       0x9 Defined as ``RIBBON_BAR_FLOW_HORIZONTAL`` | ``RIBBON_BAR_SHOW_PAGE_LABELS`` | ``RIBBON_BAR_SHOW_PANEL_EXT_BUTTONS``
         ``RIBBON_BAR_FOLDBAR_STYLE``                      0x1e Defined as ``RIBBON_BAR_FLOW_VERTICAL`` | ``RIBBON_BAR_SHOW_PAGE_ICONS`` | ``RIBBON_BAR_SHOW_PANEL_EXT_BUTTONS`` | ``RIBBON_BAR_SHOW_PANEL_MINIMISE_BUTTONS``
         ``RIBBON_BAR_SHOW_PAGE_LABELS``                    0x1 Causes labels to be shown on the tabs in the ribbon bar.
         ``RIBBON_BAR_SHOW_PAGE_ICONS``                     0x2 Causes icons to be shown on the tabs in the ribbon bar.
         ``RIBBON_BAR_FLOW_HORIZONTAL``                     0x0 Causes panels within pages to stack horizontally.
         ``RIBBON_BAR_FLOW_VERTICAL``                       0x4 Causes panels within pages to stack vertically.
         ``RIBBON_BAR_SHOW_PANEL_EXT_BUTTONS``              0x8 Causes extension buttons to be shown on panels (where the panel has such a button).
         ``RIBBON_BAR_SHOW_PANEL_MINIMISE_BUTTONS``        0x10 Causes minimise buttons to be shown on panels (where the panel has such a button).
         ========================================== =========== ==========================================

        :param `validator`: the window validator;
        :param `name`: the window name.

        """

        RibbonControl.__init__(self, parent, id, pos, size, style=wx.NO_BORDER)

        self._flags = 0
        self._tabs_total_width_ideal = 0
        self._tabs_total_width_minimum = 0
        self._tab_margin_left = 0
        self._tab_margin_right = 0
        self._tab_height = 0
        self._tab_scroll_amount = 0
        self._current_page = -1
        self._current_hovered_page = -1
        self._tab_scroll_left_button_state = RIBBON_SCROLL_BTN_NORMAL
        self._tab_scroll_right_button_state = RIBBON_SCROLL_BTN_NORMAL
        self._tab_scroll_buttons_shown = False
        self._arePanelsShown = True
        self._pages = []

        self.Bind(wx.EVT_ERASE_BACKGROUND, self.OnEraseBackground)
        self.Bind(wx.EVT_LEAVE_WINDOW, self.OnMouseLeave)
        self.Bind(wx.EVT_LEFT_DOWN, self.OnMouseLeftDown)
        self.Bind(wx.EVT_LEFT_DCLICK, self.OnMouseDoubleClick)
        self.Bind(wx.EVT_LEFT_UP, self.OnMouseLeftUp)
        self.Bind(wx.EVT_MIDDLE_DOWN, self.OnMouseMiddleDown)
        self.Bind(wx.EVT_MIDDLE_UP, self.OnMouseMiddleUp)
        self.Bind(wx.EVT_MOTION, self.OnMouseMove)
        self.Bind(wx.EVT_PAINT, self.OnPaint)
        self.Bind(wx.EVT_RIGHT_DOWN, self.OnMouseRightDown)
        self.Bind(wx.EVT_RIGHT_UP, self.OnMouseRightUp)
        self.Bind(wx.EVT_SIZE, self.OnSize)

        self.CommonInit(agwStyle)

[docs]    def AddPage(self, page):

        info = RibbonPageTabInfo()

        info.page = page
        info.active = False
        info.hovered = False
        # info.rect not set (intentional)

        dcTemp = wx.ClientDC(self)
        label = ""
        if self._flags & RIBBON_BAR_SHOW_PAGE_LABELS:
            label = page.GetLabel()

        icon = wx.NullBitmap
        if self._flags & RIBBON_BAR_SHOW_PAGE_ICONS:
            icon = page.GetIcon()

        info.ideal_width, info.small_begin_need_separator_width, \
        info.small_must_have_separator_width, info.minimum_width = self._art.GetBarTabWidth(dcTemp, self, label, icon, info.ideal_width,
                                                                                info.small_begin_need_separator_width,
                                                                                info.small_must_have_separator_width, info.minimum_width)

        if not self._pages:
            self._tabs_total_width_ideal = info.ideal_width
            self._tabs_total_width_minimum = info.minimum_width
        else:
            sep = self._art.GetMetric(RIBBON_ART_TAB_SEPARATION_SIZE)
            self._tabs_total_width_ideal += sep + info.ideal_width
            self._tabs_total_width_minimum += sep + info.minimum_width

        self._pages.append(info)

        page.Hide() # Most likely case is that self new page is not the active tab
        page.SetArtProvider(self._art)

        if len(self._pages) == 1:
            self.SetActivePage(0)

[docs]    def DismissExpandedPanel(self):
        """
        Dismiss the expanded panel of the currently active page.

        Calls and returns the value from L{RibbonPage.DismissExpandedPanel} for the
        currently active page, or ``False`` if there is no active page.
        """

        if self._current_page == -1:
            return False

        return self._pages[self._current_page].page.DismissExpandedPanel()

[docs]    def ShowPanels(self, show=True):
        """
        Shows or hides the panels inside L{RibbonBar}.

        :param `show`: ``True`` to show the panels, ``False`` to hide them.
        """

        self._arePanelsShown = show
        self.SetMinSize(wx.Size(self.GetSize().GetWidth(), self.DoGetBestSize().GetHeight()))
        self.Realise()
        self.GetParent().Layout()

[docs]    def SetAGWWindowStyleFlag(self, agwStyle):
        """
        Sets the window style for L{RibbonBar}.

        :param `agwStyle`: can be a combination of the following bits:

         ========================================== =========== ==========================================
         Window Styles                              Hex Value   Description
         ========================================== =========== ==========================================
         ``RIBBON_BAR_DEFAULT_STYLE``                       0x9 Defined as ``RIBBON_BAR_FLOW_HORIZONTAL`` | ``RIBBON_BAR_SHOW_PAGE_LABELS`` | ``RIBBON_BAR_SHOW_PANEL_EXT_BUTTONS``
         ``RIBBON_BAR_FOLDBAR_STYLE``                      0x1e Defined as ``RIBBON_BAR_FLOW_VERTICAL`` | ``RIBBON_BAR_SHOW_PAGE_ICONS`` | ``RIBBON_BAR_SHOW_PANEL_EXT_BUTTONS`` | ``RIBBON_BAR_SHOW_PANEL_MINIMISE_BUTTONS``
         ``RIBBON_BAR_SHOW_PAGE_LABELS``                    0x1 Causes labels to be shown on the tabs in the ribbon bar.
         ``RIBBON_BAR_SHOW_PAGE_ICONS``                     0x2 Causes icons to be shown on the tabs in the ribbon bar.
         ``RIBBON_BAR_FLOW_HORIZONTAL``                     0x0 Causes panels within pages to stack horizontally.
         ``RIBBON_BAR_FLOW_VERTICAL``                       0x4 Causes panels within pages to stack vertically.
         ``RIBBON_BAR_SHOW_PANEL_EXT_BUTTONS``              0x8 Causes extension buttons to be shown on panels (where the panel has such a button).
         ``RIBBON_BAR_SHOW_PANEL_MINIMISE_BUTTONS``        0x10 Causes minimise buttons to be shown on panels (where the panel has such a button).
         ========================================== =========== ==========================================

        :note: Please note that some styles cannot be changed after the window creation
         and that `Refresh()` might need to be be called after changing the others for
         the change to take place immediately.
        """

        self._flags = agwStyle

        if self._art:
            self._art.SetFlags(agwStyle)

[docs]    def GetAGWWindowStyleFlag(self):
        """
        Returns the L{RibbonBar} window style flag.

        :see: L{SetAGWWindowStyleFlag} for a list of valid window styles.
        """

        return self._flags

[docs]    def Realize(self):
        """
        Perform initial layout and size calculations of the bar and its children.

        This must be called after all of the bar's children have been created (and their
        children created, etc.) - if it is not, then windows may not be laid out or
        sized correctly. Also calls L{RibbonPage.Realize} on each child page.

        Reimplemented from L{RibbonControl}.

        """

        status = True

        dcTemp = wx.ClientDC(self)
        sep = self._art.GetMetric(RIBBON_ART_TAB_SEPARATION_SIZE)
        numtabs = len(self._pages)

        for i, info in enumerate(self._pages):

            self.RepositionPage(info.page)
            if not info.page.Realize():
                status = False

            label = ""
            if self._flags & RIBBON_BAR_SHOW_PAGE_LABELS:
                label = info.page.GetLabel()

            icon = wx.NullBitmap
            if self._flags & RIBBON_BAR_SHOW_PAGE_ICONS:
                icon = info.page.GetIcon()

            info.ideal_width, info.small_begin_need_separator_width, \
                              info.small_must_have_separator_width, \
                              info.minimum_width = self._art.GetBarTabWidth(dcTemp, self, label, icon, info.ideal_width,
                                                                            info.small_begin_need_separator_width, info.small_must_have_separator_width,
                                                                            info.minimum_width)

            if i == 0:
                self._tabs_total_width_ideal = info.ideal_width
                self._tabs_total_width_minimum = info.minimum_width
            else:
                self._tabs_total_width_ideal += sep + info.ideal_width
                self._tabs_total_width_minimum += sep + info.minimum_width

        self._tab_height = self._art.GetTabCtrlHeight(dcTemp, self, self._pages)

        self.RecalculateMinSize()
        self.RecalculateTabSizes()
        self.Refresh()

        return status

[docs]    def OnMouseMove(self, event):

        x, y = event.GetX(), event.GetY()
        hovered_page = -1
        refresh_tabs = False

        if y < self._tab_height:
            # It is quite likely that the mouse moved a small amount and is still over the same tab
            if self._current_hovered_page != -1 and self._pages[self._current_hovered_page].rect.Contains((x, y)):
                hovered_page = self._current_hovered_page
                # But be careful, if tabs can be scrolled, then parts of the tab rect may not be valid
                if self._tab_scroll_buttons_shown:
                    if x >= self._tab_scroll_right_button_rect.GetX() or x < self._tab_scroll_left_button_rect.GetRight():
                        hovered_page = -1

            else:

                hovered_page, dummy = self.HitTestTabs(event.GetPosition())

        if hovered_page != self._current_hovered_page:
            if self._current_hovered_page != -1:
                self._pages[self._current_hovered_page].hovered = False

            self._current_hovered_page = hovered_page
            if self._current_hovered_page != -1:
                self._pages[self._current_hovered_page].hovered = True

            refresh_tabs = True

        if self._tab_scroll_buttons_shown:
            if self._tab_scroll_left_button_rect.Contains((x, y)):
                self._tab_scroll_left_button_state, refresh_tabs = SET_FLAG(self._tab_scroll_left_button_state, RIBBON_SCROLL_BTN_HOVERED)
            else:
                self._tab_scroll_left_button_state, refresh_tabs = UNSET_FLAG(self._tab_scroll_left_button_state, RIBBON_SCROLL_BTN_HOVERED)

            if self._tab_scroll_right_button_rect.Contains((x, y)):
                self._tab_scroll_right_button_state, refresh_tabs = SET_FLAG(self._tab_scroll_right_button_state, RIBBON_SCROLL_BTN_HOVERED)
            else:
                self._tab_scroll_right_button_state, refresh_tabs = UNSET_FLAG(self._tab_scroll_right_button_state, RIBBON_SCROLL_BTN_HOVERED)

        if refresh_tabs:
            self.RefreshTabBar()

[docs]    def OnMouseLeave(self, event):

        # The ribbon bar is (usually) at the top of a window, and at least on MSW, the mouse
        # can leave the window quickly and leave a tab in the hovered state.
        refresh_tabs = False

        if self._current_hovered_page != -1:
            self._pages[self._current_hovered_page].hovered = False
            self._current_hovered_page = -1
            refresh_tabs = True

        if self._tab_scroll_left_button_state & RIBBON_SCROLL_BTN_HOVERED:
            self._tab_scroll_left_button_state &= ~RIBBON_SCROLL_BTN_HOVERED
            refresh_tabs = True

        if self._tab_scroll_right_button_state & RIBBON_SCROLL_BTN_HOVERED:
            self._tab_scroll_right_button_state &= ~RIBBON_SCROLL_BTN_HOVERED
            refresh_tabs = True

        if refresh_tabs:
            self.RefreshTabBar()

[docs]    def GetPage(self, n):
        """
        Get a page by index.

        ``None`` will be returned if the given index is out of range.

        :param `n`: MISSING DESCRIPTION.

        """

        if n < 0 or n >= len(self._pages):
            return 0

        return self._pages[n].page

[docs]    def SetActivePageByIndex(self, page):
        """
        Set the active page by index, without triggering any events.

        :param `page`: The zero-based index of the page to activate.

        :returns: ``True`` if the specified page is now active, ``False`` if it could
         not be activated (for example because the page index is invalid).
        """

        if self._current_page == page:
            return True

        if page >= len(self._pages):
            return False

        if self._current_page != -1:
            self._pages[self._current_page].active = False
            self._pages[self._current_page].page.Hide()

        self._current_page = page
        self._pages[page].active = True

        wnd = self._pages[page].page
        self.RepositionPage(wnd)
        wnd.Layout()
        wnd.Show()

        self.Refresh()

        return True

[docs]    def SetActivePageByPage(self, page):
        """
        Set the active page, without triggering any events.

        :param `page`: The page to activate.

        :returns: ``True`` if the specified page is now active, ``False`` if it could
         not be activated (for example because the given page is not a child of the
         ribbon bar).

        """

        for i in xrange(len(self._pages)):
            if self._pages[i].page == page:
                return self.SetActivePageByIndex(i)

        return False

[docs]    def SetActivePage(self, page):
        """ See comments on L{SetActivePageByIndex} and L{SetActivePageByPage}. """

        if isinstance(page, types.IntType):
            return self.SetActivePageByIndex(page)

        return self.SetActivePageByPage(page)

[docs]    def GetActivePage(self):
        """
        Get the index of the active page.

        In the rare case of no page being active, -1 is returned.
        """

        return self._current_page

[docs]    def SetTabCtrlMargins(self, left, right):
        """
        Set the margin widths (in pixels) on the left and right sides of the tab bar
        region of the ribbon bar.

        These margins will be painted with the tab background, but tabs and scroll
        buttons will never be painted in the margins. The left margin could be used for
        rendering something equivalent to the "Office Button", though this is not
        currently implemented. The right margin could be used for rendering a help
        button, and/or MDI buttons, but again, this is not currently implemented.

        :param `left`: MISSING DESCRIPTION;
        :param `right`: MISSING DESCRIPTION.

        """

        self._tab_margin_left = left
        self._tab_margin_right = right

        self.RecalculateTabSizes()

[docs]    def OrderPageTabInfoBySmallWidthAsc(self, first, second):

        return first.small_must_have_separator_width - second.small_must_have_separator_width

[docs]    def RecalculateTabSizes(self):

        numtabs = len(self._pages)

        if numtabs == 0:
            return

        width = self.GetSize().GetWidth() - self._tab_margin_left - self._tab_margin_right
        tabsep = self._art.GetMetric(RIBBON_ART_TAB_SEPARATION_SIZE)
        x = self._tab_margin_left
        y = 0

        if width >= self._tabs_total_width_ideal:
            # Simple case: everything at ideal width
            for info in self._pages:
                info.rect.x = x
                info.rect.y = y
                info.rect.width = info.ideal_width
                info.rect.height = self._tab_height
                x += info.rect.width + tabsep

            self._tab_scroll_buttons_shown = False
            self._tab_scroll_left_button_rect.SetWidth(0)
            self._tab_scroll_right_button_rect.SetWidth(0)

        elif width < self._tabs_total_width_minimum:
            # Simple case: everything minimum with scrollbar
            for info in self._pages:
                info.rect.x = x
                info.rect.y = y
                info.rect.width = info.minimum_width
                info.rect.height = self._tab_height
                x += info.rect.width + tabsep

            if not self._tab_scroll_buttons_shown:
                self._tab_scroll_left_button_state = RIBBON_SCROLL_BTN_NORMAL
                self._tab_scroll_right_button_state = RIBBON_SCROLL_BTN_NORMAL
                self._tab_scroll_buttons_shown = True

            temp_dc = wx.ClientDC(self)
            self._tab_scroll_left_button_rect.SetWidth(self._art.GetScrollButtonMinimumSize(temp_dc, self,
                                                                                RIBBON_SCROLL_BTN_LEFT | RIBBON_SCROLL_BTN_NORMAL |
                                                                                RIBBON_SCROLL_BTN_FOR_TABS).GetWidth())
            self._tab_scroll_left_button_rect.SetHeight(self._tab_height)
            self._tab_scroll_left_button_rect.SetX(self._tab_margin_left)
            self._tab_scroll_left_button_rect.SetY(0)
            self._tab_scroll_right_button_rect.SetWidth(self._art.GetScrollButtonMinimumSize(temp_dc, self,
                                                                                RIBBON_SCROLL_BTN_RIGHT | RIBBON_SCROLL_BTN_NORMAL |
                                                                                RIBBON_SCROLL_BTN_FOR_TABS).GetWidth())
            self._tab_scroll_right_button_rect.SetHeight(self._tab_height)
            self._tab_scroll_right_button_rect.SetX(self.GetClientSize().GetWidth() - self._tab_margin_right - self._tab_scroll_right_button_rect.GetWidth())
            self._tab_scroll_right_button_rect.SetY(0)

            if self._tab_scroll_amount == 0:
                self._tab_scroll_left_button_rect.SetWidth(0)

            elif self._tab_scroll_amount + width >= self._tabs_total_width_minimum:
                self._tab_scroll_amount = self._tabs_total_width_minimum - width
                self._tab_scroll_right_button_rect.SetX(self._tab_scroll_right_button_rect.GetX() + self._tab_scroll_right_button_rect.GetWidth())
                self._tab_scroll_right_button_rect.SetWidth(0)

            for info in self._pages:
                info.rect.x -= self._tab_scroll_amount

        else:
            self._tab_scroll_buttons_shown = False
            self._tab_scroll_left_button_rect.SetWidth(0)
            self._tab_scroll_right_button_rect.SetWidth(0)
            # Complex case: everything sized such that: minimum <= width < ideal
            #
            #   Strategy:
            #     1) Uniformly reduce all tab widths from ideal to small_must_have_separator_width
            #     2) Reduce the largest tab by 1 pixel, repeating until all tabs are same width (or at minimum)
            #     3) Uniformly reduce all tabs down to their minimum width
            #
            smallest_tab_width = 10000
            total_small_width = tabsep * (numtabs - 1)

            for info in self._pages:
                if info.small_must_have_separator_width < smallest_tab_width:
                    smallest_tab_width = info.small_must_have_separator_width

                total_small_width += info.small_must_have_separator_width

            if width >= total_small_width:
                # Do (1)
                total_delta = self._tabs_total_width_ideal - total_small_width
                total_small_width -= tabsep*(numtabs - 1)
                width -= tabsep*(numtabs - 1)
                for info in self._pages:
                    delta = info.ideal_width - info.small_must_have_separator_width
                    info.rect.x = x
                    info.rect.y = y
                    info.rect.width = info.small_must_have_separator_width + delta*(width - total_small_width)/total_delta
                    info.rect.height = self._tab_height

                    x += info.rect.width + tabsep
                    total_delta -= delta
                    total_small_width -= info.small_must_have_separator_width
                    width -= info.rect.width

            else:

                total_small_width = tabsep*(numtabs - 1)
                for info in self._pages:
                    if info.minimum_width < smallest_tab_width:
                        total_small_width += smallest_tab_width
                    else:
                        total_small_width += info.minimum_width

                if width >= total_small_width:
                    # Do (2)
                    sorted_pages = []
                    for info in self._pages:
                        # Sneaky obj array trickery to not copy the tab descriptors
                        sorted_pages.append(info)

                    sorted_pages.sort(self.OrderPageTabInfoBySmallWidthAsc)
                    width -= tabsep*(numtabs - 1)

                    for i, info in enumerate(self._pages):
                        if info.small_must_have_separator_width*(numtabs - i) <= width:
                            info.rect.width = info.small_must_have_separator_width
                        else:
                            info.rect.width = width/(numtabs - i)

                        width -= info.rect.width

                    for i, info in enumerate(self._pages):
                        info.rect.x = x
                        info.rect.y = y
                        info.rect.height = self._tab_height
                        x += info.rect.width + tabsep
                        sorted_pages.pop(numtabs - (i + 1))

                else:

                    # Do (3)
                    total_small_width = (smallest_tab_width + tabsep)*numtabs - tabsep
                    total_delta = total_small_width - self._tabs_total_width_minimum
                    total_small_width = self._tabs_total_width_minimum - tabsep*(numtabs - 1)
                    width -= tabsep*(numtabs - 1)

                    for info in self._pages:
                        delta = smallest_tab_width - info.minimum_width
                        info.rect.x = x
                        info.rect.y = y
                        info.rect.width = info.minimum_width + delta*(width - total_small_width)/total_delta
                        info.rect.height = self._tab_height

                        x += info.rect.width + tabsep
                        total_delta -= delta
                        total_small_width -= info.minimum_width
                        width -= info.rect.width

[docs]    def CommonInit(self, agwStyle):

        self.SetName("RibbonBar")

        self._flags = agwStyle
        self._tabs_total_width_ideal = 0
        self._tabs_total_width_minimum = 0
        self._tab_margin_left = 50
        self._tab_margin_right = 20
        self._tab_height = 20 # initial guess
        self._tab_scroll_amount = 0
        self._current_page = -1
        self._current_hovered_page = -1
        self._tab_scroll_left_button_state = RIBBON_SCROLL_BTN_NORMAL
        self._tab_scroll_right_button_state = RIBBON_SCROLL_BTN_NORMAL
        self._tab_scroll_buttons_shown = False
        self._arePanelsShown = True
        self._tab_scroll_left_button_rect = wx.Rect()
        self._tab_scroll_right_button_rect = wx.Rect()

        if not self._art:
            self.SetArtProvider(RibbonMSWArtProvider())

        self.SetBackgroundStyle(wx.BG_STYLE_CUSTOM)

[docs]    def SetArtProvider(self, art):
        """
        Set the art provider to be used be the ribbon bar.

        Also sets the art provider on all current L{RibbonPage} children, and any
        L{RibbonPage} children added in the future.

        Note that unlike most other ribbon controls, the ribbon bar creates a default
        art provider when initialised, so an explicit call to L{SetArtProvider} is
        not required if the default art provider is sufficient. Also unlike other
        ribbon controls, the ribbon bar takes ownership of the given pointer, and
        will delete it when the art provider is changed or the bar is destroyed.

        If this behaviour is not desired, then clone the art provider before setting
        it.

        Reimplemented from L{RibbonControl}.

        :param `art`: MISSING DESCRIPTION.

        """

        self._art = art

        if art:
            art.SetFlags(self._flags)

        for info in self._pages:
            if info.page.GetArtProvider() != art:
                info.page.SetArtProvider(art)

[docs]    def OnPaint(self, event):

        dc = wx.AutoBufferedPaintDC(self)

        if not self.GetUpdateRegion().ContainsRect(wx.Rect(0, 0, self.GetClientSize().GetWidth(), self._tab_height)):
            # Nothing to do in the tab area, and the page area is handled by the active page
            return

        self.DoEraseBackground(dc)

        numtabs = len(self._pages)
        sep_visibility = 0.0
        draw_sep = False
        tabs_rect = wx.Rect(self._tab_margin_left, 0, self.GetClientSize().GetWidth() - self._tab_margin_left - self._tab_margin_right, self._tab_height)

        if self._tab_scroll_buttons_shown:
            tabs_rect.x += self._tab_scroll_left_button_rect.GetWidth()
            tabs_rect.width -= self._tab_scroll_left_button_rect.GetWidth() + self._tab_scroll_right_button_rect.GetWidth()

        for info in self._pages:
            dc.DestroyClippingRegion()
            if self._tab_scroll_buttons_shown:
                if not tabs_rect.Intersects(info.rect):
                    continue
                dc.SetClippingRect(tabs_rect)

            dc.SetClippingRect(info.rect)
            self._art.DrawTab(dc, self, info)

            if info.rect.width < info.small_begin_need_separator_width:
                draw_sep = True
                if info.rect.width < info.small_must_have_separator_width:
                    sep_visibility += 1.0
                else:
                    sep_visibility += float(info.small_begin_need_separator_width - info.rect.width)/ \
                                      float(info.small_begin_need_separator_width - info.small_must_have_separator_width)

        if draw_sep:

            rect = wx.Rect(*self._pages[0].rect)
            rect.width = self._art.GetMetric(RIBBON_ART_TAB_SEPARATION_SIZE)
            sep_visibility /= float(numtabs)

            for i in xrange(0, numtabs-1):
                info = self._pages[i]
                rect.x = info.rect.x + info.rect.width

                if self._tab_scroll_buttons_shown and not tabs_rect.Intersects(rect):
                    continue

                dc.DestroyClippingRegion()
                dc.SetClippingRect(rect)
                self._art.DrawTabSeparator(dc, self, rect, sep_visibility)

        if self._tab_scroll_buttons_shown:
            dc.DestroyClippingRegion()
            if self._tab_scroll_left_button_rect.GetWidth() != 0:
                self._art.DrawScrollButton(dc, self, self._tab_scroll_left_button_rect, RIBBON_SCROLL_BTN_LEFT |
                                           self._tab_scroll_left_button_state | RIBBON_SCROLL_BTN_FOR_TABS)

            if self._tab_scroll_right_button_rect.GetWidth() != 0:
                self._art.DrawScrollButton(dc, self, self._tab_scroll_right_button_rect, RIBBON_SCROLL_BTN_RIGHT |
                                           self._tab_scroll_right_button_state | RIBBON_SCROLL_BTN_FOR_TABS)

[docs]    def OnEraseBackground(self, event):

        # Background painting done in main paint handler to reduce screen flicker
        pass

[docs]    def DoEraseBackground(self, dc):

        tabs = wx.Rect(0, 0, *self.GetSize())
        tabs.height = self._tab_height
        self._art.DrawTabCtrlBackground(dc, self, tabs)

[docs]    def OnSize(self, event):

        self.RecalculateTabSizes()
        if self._current_page != -1:
            self.RepositionPage(self._pages[self._current_page].page)

        self.RefreshTabBar()
        event.Skip()

[docs]    def RepositionPage(self, page):

        w, h = self.GetSize()
        page.SetSizeWithScrollButtonAdjustment(0, self._tab_height, w, h - self._tab_height)

[docs]    def HitTestTabs(self, position):

        tabs_rect = wx.Rect(self._tab_margin_left, 0, self.GetClientSize().GetWidth() - self._tab_margin_left - self._tab_margin_right, self._tab_height)

        if self._tab_scroll_buttons_shown:
            tabs_rect.SetX(tabs_rect.GetX() + self._tab_scroll_left_button_rect.GetWidth())
            tabs_rect.SetWidth(tabs_rect.GetWidth() - self._tab_scroll_left_button_rect.GetWidth() - self._tab_scroll_right_button_rect.GetWidth())

        if tabs_rect.Contains(position):
            for i, info in enumerate(self._pages):
                if info.rect.Contains(position):
                    return i, info

        return -1, None

[docs]    def OnMouseLeftDown(self, event):

        index, tab = self.HitTestTabs(event.GetPosition())
        if tab and tab != self._pages[self._current_page]:
            query = RibbonBarEvent(wxEVT_COMMAND_RIBBONBAR_PAGE_CHANGING, self.GetId(), tab.page)
            query.SetEventObject(self)
            self.GetEventHandler().ProcessEvent(query)

            if query.IsAllowed():
                self.SetActivePage(query.GetPage())
                notification = RibbonBarEvent(wxEVT_COMMAND_RIBBONBAR_PAGE_CHANGED, self.GetId(), self._pages[self._current_page].page)
                notification.SetEventObject(self)
                self.GetEventHandler().ProcessEvent(notification)

        elif tab == None:
            if self._tab_scroll_left_button_rect.Contains(event.GetPosition()):
                self._tab_scroll_left_button_state |= RIBBON_SCROLL_BTN_ACTIVE | RIBBON_SCROLL_BTN_HOVERED
                self.RefreshTabBar()

            elif self._tab_scroll_right_button_rect.Contains(event.GetPosition()):
                self._tab_scroll_right_button_state |= RIBBON_SCROLL_BTN_ACTIVE | RIBBON_SCROLL_BTN_HOVERED
                self.RefreshTabBar()

[docs]    def OnMouseDoubleClick(self, event):

        self.DoMouseButtonCommon(event, wxEVT_COMMAND_RIBBONBAR_TAB_LEFT_DCLICK)

[docs]    def OnMouseLeftUp(self, event):

        if not self._tab_scroll_buttons_shown:
            return

        amount = 0

        if self._tab_scroll_left_button_state & RIBBON_SCROLL_BTN_ACTIVE:
            amount = -1

        elif self._tab_scroll_right_button_state & RIBBON_SCROLL_BTN_ACTIVE:
            amount = 1

        if amount != 0:
            self._tab_scroll_left_button_state &= ~RIBBON_SCROLL_BTN_ACTIVE
            self._tab_scroll_right_button_state &= ~RIBBON_SCROLL_BTN_ACTIVE
            self.ScrollTabBar(amount*8)

[docs]    def ScrollTabBar(self, amount):

        show_left = True
        show_right = True

        if self._tab_scroll_amount + amount <= 0:
            amount = -self._tab_scroll_amount
            show_left = False

        elif self._tab_scroll_amount + amount + (self.GetClientSize().GetWidth() - \
                                                 self._tab_margin_left - self._tab_margin_right) >= \
                                                 self._tabs_total_width_minimum:
            amount = self._tabs_total_width_minimum - self._tab_scroll_amount - \
                     (self.GetClientSize().GetWidth() - self._tab_margin_left - self._tab_margin_right)
            show_right = False

        if amount == 0:
            return

        self._tab_scroll_amount += amount
        for info in self._pages:
            info.rect.SetX(info.rect.GetX() - amount)

        if show_right != (self._tab_scroll_right_button_rect.GetWidth() != 0) or \
           show_left != (self._tab_scroll_left_button_rect.GetWidth() != 0):

            temp_dc = wx.ClientDC(self)

            if show_left:
                self._tab_scroll_left_button_rect.SetWidth(self._art.GetScrollButtonMinimumSize(temp_dc, self, RIBBON_SCROLL_BTN_LEFT |
                                                                                RIBBON_SCROLL_BTN_NORMAL |
                                                                                RIBBON_SCROLL_BTN_FOR_TABS).GetWidth())
            else:
                self._tab_scroll_left_button_rect.SetWidth(0)

            if show_right:
                if self._tab_scroll_right_button_rect.GetWidth() == 0:
                    self._tab_scroll_right_button_rect.SetWidth(self._art.GetScrollButtonMinimumSize(temp_dc, self,
                                                                                RIBBON_SCROLL_BTN_RIGHT |
                                                                                RIBBON_SCROLL_BTN_NORMAL |
                                                                                RIBBON_SCROLL_BTN_FOR_TABS).GetWidth())
                    self._tab_scroll_right_button_rect.SetX(self._tab_scroll_right_button_rect.GetX() - self._tab_scroll_right_button_rect.GetWidth())
            else:

                if self._tab_scroll_right_button_rect.GetWidth() != 0:
                    self._tab_scroll_right_button_rect.SetX(self._tab_scroll_right_button_rect.GetX() + self._tab_scroll_right_button_rect.GetWidth())
                    self._tab_scroll_right_button_rect.SetWidth(0)

        self.RefreshTabBar()

[docs]    def RefreshTabBar(self):

        tab_rect = wx.Rect(0, 0, self.GetClientSize().GetWidth(), self._tab_height)
        self.Refresh(False, tab_rect)

[docs]    def OnMouseMiddleDown(self, event):

        self.DoMouseButtonCommon(event, wxEVT_COMMAND_RIBBONBAR_TAB_MIDDLE_DOWN)

[docs]    def OnMouseMiddleUp(self, event):

        self.DoMouseButtonCommon(event, wxEVT_COMMAND_RIBBONBAR_TAB_MIDDLE_UP)

[docs]    def OnMouseRightDown(self, event):

        self.DoMouseButtonCommon(event, wxEVT_COMMAND_RIBBONBAR_TAB_RIGHT_DOWN)

[docs]    def OnMouseRightUp(self, event):

        self.DoMouseButtonCommon(event, wxEVT_COMMAND_RIBBONBAR_TAB_RIGHT_UP)

[docs]    def DoMouseButtonCommon(self, event, tab_event_type):

        index, tab = self.HitTestTabs(event.GetPosition())

        if tab:
            notification = RibbonBarEvent(tab_event_type, self.GetId(), tab.page)
            notification.SetEventObject(self)
            self.GetEventHandler().ProcessEvent(notification)

[docs]    def RecalculateMinSize(self):

        min_size = wx.Size(-1, -1)
        numtabs = len(self._pages)

        if numtabs != 0:
            min_size = wx.Size(*self._pages[0].page.GetMinSize())

            for info in self._pages:
                page_min = info.page.GetMinSize()
                min_size.x = max(min_size.x, page_min.x)
                min_size.y = max(min_size.y, page_min.y)

        if min_size.y != -1:
            # TODO: Decide on best course of action when min height is unspecified
            # - should we specify it to the tab minimum, or leave it unspecified?
            min_size.IncBy(0, self._tab_height)

        self._minWidth = min_size.GetWidth()
        self._minHeight = (self._arePanelsShown and [min_size.GetHeight()] or [self._tab_height])[0]

[docs]    def DoGetBestSize(self):

        best = wx.Size(0, 0)

        if self._current_page != -1:
            best = wx.Size(*self._pages[self._current_page].page.GetBestSize())

        if best.GetHeight() == -1:
            best.SetHeight(self._tab_height)
        else:
            best.IncBy(0, self._tab_height)

        if not self._arePanelsShown:
            best.SetHeight(self._tab_height)

        return best

[docs]    def HasMultiplePages(self):

        return True

[docs]    def GetDefaultBorder(self):

        return wx.BORDER_NONE

Navigation

  • index
  • modules |
  • Home |
  • Gallery |
  • Contents»
  • Module code »
  • ribbon.bar


ribbon.buttonbar

  • modules |
  • Home |
  • Gallery |
  • Contents»
  • Module code »
  • ribbon.buttonbar

Source code for ribbon.buttonbar

"""
A ribbon button bar is similar to a traditional toolbar.

Description
===========

It contains one or more buttons (button bar buttons, not `wx.Button`), each of which
has a label and an icon. It differs from a L{RibbonToolBar} 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. L{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)

[docs]class RibbonButtonBarButtonSizeInfo(object):

[docs]    def __init__(self):

        self.is_supported = True
        self.size = wx.Size()
        self.normal_region = wx.Rect()
        self.dropdown_region = wx.Rect()

[docs]class RibbonButtonBarButtonInstance(object):

[docs]    def __init__(self):

        self.position = wx.Point()
        self.base = None
        self.size = wx.Size()

[docs]class RibbonButtonBarButtonBase(object):

[docs]    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

[docs]    def NewInstance(self):

        i = RibbonButtonBarButtonInstance()
        i.base = self
        return i

[docs]    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

[docs]    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

[docs]class RibbonButtonBarLayout(object):

[docs]    def __init__(self):

        self.overall_size = wx.Size()
        self.buttons = []

[docs]    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)

[docs]    def FindSimilarInstance(self, inst):

        if inst is None:
            return None

        for instance in self.buttons:
            if instance.base == inst.base:
                return instance

        return None

[docs]class RibbonButtonBarEvent(wx.PyCommandEvent):
    """
    Event used to indicate various actions relating to a button on a L{RibbonButtonBar}.

    See L{RibbonButtonBar} for available event types.
    """

[docs]    def __init__(self, command_type=None, win_id=0, bar=None):

        wx.PyCommandEvent.__init__(self, command_type, win_id)
        self._bar = bar

[docs]    def GetBar(self):
        """
        Returns the bar which contains the button which the event relates to.
        """

        return self._bar

[docs]    def SetBar(self, bar):
        """
        Sets the button bar relating to this event.

        :param `bar`: MISSING DESCRIPTION.

        """

        self._bar = bar

[docs]    def PopupMenu(self, menu):
        """
        Display a popup menu as a result of this (dropdown clicked) event.

        :param `menu`: MISSING DESCRIPTION.

        """

        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)

[docs]class RibbonButtonBar(RibbonControl):

[docs]    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;
        :param `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;
        :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;
        :param `agwStyle`: the AGW-specific window style.

        """

        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)

[docs]    def AddSimpleButton(self, button_id, label, bitmap, help_string, kind=RIBBON_BUTTON_NORMAL):
        """
        Add a button to the button bar (simple version).

        :param `button_id`: ID of the button;
        :param `label`: label of the new button;
        :param `bitmap`: large bitmap of the new button. Must be the same size as
         all other large bitmaps used on the button bar;
        :param `help_string`: the UI help string to associate with the new button;
        :param `kind`: The kind of button to add.

        """

        return self.AddButton(button_id, label, bitmap, wx.NullBitmap, wx.NullBitmap,
                              wx.NullBitmap, kind, help_string)

[docs]    def AddDropdownButton(self, button_id, label, bitmap, help_string=""):
        """
        Add a dropdown button to the button bar (simple version).

        :param `button_id`: ID of the button;
        :param `label`: label of the new button;
        :param `bitmap`: large bitmap of the new button. Must be the same size as
         all other large bitmaps used on the button bar;
        :param `help_string`: the UI help string to associate with the new button.

        :see: L{AddButton}
        """

        return self.AddSimpleButton(button_id, label, bitmap, help_string, RIBBON_BUTTON_DROPDOWN)

[docs]    def AddHybridButton(self, button_id, label, bitmap, help_string=""):
        """
        Add a hybrid button to the button bar (simple version).

        :param `button_id`: ID of the button;
        :param `label`: label of the new button;
        :param `bitmap`: large bitmap of the new button. Must be the same size as
         all other large bitmaps used on the button bar;
        :param `help_string`: the UI help string to associate with the new button.

        :see: L{AddButton}
        """

        return self.AddSimpleButton(button_id, label, bitmap, help_string, RIBBON_BUTTON_HYBRID)

[docs]    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 `button_id`: ID of the new button (used for event callbacks);
        :param `label`: label of the new button;
        :param `bitmap`: large bitmap of the new button. Must be the same size as
         all other large bitmaps used on the button bar;
        :param `bitmap_small`: small bitmap of the new button. If left as ``None``,
         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.
         If left as ``None``, then a bitmap will be automatically generated from `bitmap`;
        :param `bitmap_small_disabled`: small bitmap of the new button when it is disabled.
         If left as ``None``, then a bitmap will be automatically generated from `bitmap_small`;
        :param `kind`: the kind of button to add;
        :param `help_string`: the UI help string to associate with the new button;
        :param `client_data`: client data to associate with the new button.

        :returns: An opaque pointer which can be used only with other button bar methods.

        :see: L{AddDropdownButton}, L{AddHybridButton}
        """

        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)

        # TODO
        self._buttons.append(base)
        self._layouts_valid = False

        return base

[docs]    def AddToggleButton(self, button_id, label, bitmap, help_string=""):
        """
        Add a toggle button to the button bar.

        :param `button_id`: ID of the button;
        :param `label`: label of the new button;
        :param `bitmap`: large bitmap of the new button. Must be the same size as
         all other large bitmaps used on the button bar;
        :param `help_string`: the UI help string to associate with the new button.

        :see: L{AddButton}
        """

        return self.AddButton(button_id, label, bitmap, help_string, RIBBON_BUTTON_TOGGLE)

[docs]    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

[docs]    def MakeResizedBitmap(self, original, size):

        img = original.ConvertToImage()
        img.Rescale(size.GetWidth(), size.GetHeight(), wx.IMAGE_QUALITY_HIGH)
        return wx.BitmapFromImage(img)

[docs]    def MakeDisabledBitmap(self, original):

        img = original.ConvertToImage()
        return wx.BitmapFromImage(img.ConvertToGreyscale())

[docs]    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 L{RibbonBar.Realize} is called.

        :note: Reimplemented from L{RibbonControl}.
        """

        if not self._layouts_valid:
            self.MakeLayouts()
            self._layouts_valid = True

        return True

[docs]    def ClearButtons(self):
        """
        Delete all buttons from the button bar.

        :see: L{DeleteButton}
        """

        self._layouts_valid = False
        self._buttons = []
        self.Realize()

[docs]    def DeleteButton(self, button_id):
        """
        Delete a single button from the button bar.

        :param `button_id`: ID of the button to delete.

        :see: L{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

[docs]    def EnableButton(self, button_id, enable=True):
        """
        Enable or disable a single button on the bar.

        :param `button_id`: ID of the button to enable or disable;
        :param `enable`: ``True`` to enable the button, ``False`` to disable it.
        """

        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

[docs]    def ToggleButton(self, button_id, checked=True):
        """
        Toggles/untoggles a L{RibbonButtonBar} toggle button.

        :param `button_id`: ID of the button to be toggles/untoggled;
        :param `checked`: ``True`` to toggle the button, ``False`` to untoggle it.
        """

        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

[docs]    def IsButtonEnabled(self, button_id):
        """
        Returns whether a button in the bar is enabled or not.

        :param `button_id`: ID of the button to check.
        """

        for button in self._buttons:
            if button.id == button_id:
                if button.state & RIBBON_BUTTONBAR_BUTTON_DISABLED:
                    return False
                return True

[docs]    def SetArtProvider(self, art):

        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()

[docs]    def IsSizingContinuous(self):

        return False

[docs]    def DoGetNextSmallerSize(self, direction, _result):

        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

[docs]    def DoGetNextLargerSize(self, direction, _result):

        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

[docs]    def OnEraseBackground(self, event):

        # All painting done in main paint handler to minimise flicker
        pass

[docs]    def OnPaint(self, event):

        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)

[docs]    def OnSize(self, event):

        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()

[docs]    def CommonInit(self, agwStyle):

        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)

[docs]    def GetMinSize(self):

        return wx.Size(*self._layouts[-1].overall_size)

[docs]    def DoGetBestSize(self):

        return wx.Size(*self._layouts[0].overall_size)

[docs]    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

[docs]    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

[docs]    def OnMouseMove(self, event):

        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)

[docs]    def OnMouseDown(self, event):

        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

[docs]    def OnMouseUp(self, event):

        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()

[docs]    def OnMouseEnter(self, event):

        if self._active_button and not event.LeftIsDown():
            self._active_button = None

[docs]    def OnMouseLeave(self, event):

        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)

[docs]    def GetDefaultBorder(self):

        return wx.BORDER_NONE

Navigation

  • index
  • modules |
  • Home |
  • Gallery |
  • Contents»
  • Module code »
  • ribbon.buttonbar


ribbon.control

  • modules |
  • Home |
  • Gallery |
  • Contents»
  • Module code »
  • ribbon.control

Source code for ribbon.control

"""
L{RibbonControl} serves as a base class for all controls which share the ribbon
charactertics of having a ribbon art provider, and (optionally) non-continous
resizing.

Description
===========

Despite what the name may imply, it is not the top-level control for creating a
ribbon interface - that is L{RibbonBar}. Ribbon controls often have a region which
is "transparent", and shows the contents of the ribbon page or panel behind it.

If implementing a new ribbon control, then it may be useful to realise that this
effect is done by the art provider when painting the background of the control,
and hence in the paint handler for the new control, you should call a draw background
method on the art provider (L{RibbonMSWArtProvider.DrawButtonBarBackground} and
L{RibbonMSWArtProvider.DrawToolBarBackground} typically just redraw what is behind the
rectangle being painted) if you want transparent regions.

"""

import wx

[docs]class RibbonControl(wx.PyControl):

[docs]    def __init__(self, parent, id=wx.ID_ANY, pos=wx.DefaultPosition, size=wx.DefaultSize, style=0,
                 validator=wx.DefaultValidator, name="RibbonControl"):

        wx.PyControl.__init__(self, parent, id, pos, size, style, validator, name)
        self._art = None

        if isinstance(parent, RibbonControl):
            self._art = parent.GetArtProvider()

[docs]    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 L{RibbonControl}. In most cases, controls will not
        take ownership of the given pointer, with the notable exception being
        L{RibbonBar.SetArtProvider}.

        :param `art`: MISSING DESCRIPTION.

        """

        self._art = art

[docs]    def GetArtProvider(self):
        """
        Get the art provider to be used.

        Note that until an art provider has been set in some way, this function may
        return ``None``.

        """

        return self._art

[docs]    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: L{GetNextSmallerSize}, L{GetNextLargerSize}
        """

        return True

[docs]    def DoGetNextSmallerSize(self, direction, size):
        """
        Implementation of L{GetNextSmallerSize}.

        Controls which have non-continuous sizing must override this virtual function
        rather than L{GetNextSmallerSize}.

        :param `direction`: MISSING DESCRIPTION;
        :param `relative_to`: MISSING DESCRIPTION.

        """

        # Dummy implementation for code which doesn't check for IsSizingContinuous() == true
        minimum = self.GetMinSize()

        if direction & wx.HORIZONTAL and size.x > minimum.x:
            size.x -= 1
        if direction & wx.VERTICAL and size.y > minimum.y:
            size.y -= 1

        return size

[docs]    def DoGetNextLargerSize(self, direction, size):
        """
        Implementation of L{GetNextLargerSize}.

        Controls which have non-continuous sizing must override this virtual function
        rather than L{GetNextLargerSize}.

        :param `direction`: MISSING DESCRIPTION;
        :param `relative_to`: MISSING DESCRIPTION.

        """

        # Dummy implementation for code which doesn't check for IsSizingContinuous() == true
        if direction & wx.HORIZONTAL:
            size.x += 1
        if direction & wx.VERTICAL:
            size.y += 1

        return size

[docs]    def GetNextSmallerSize(self, direction, relative_to=None):
        """
        If sizing is not continuous, then return a suitable size for the control which
        is smaller than the given size.

        :param `direction`: The direction(s) in which the size should reduce;
        :param `relative_to`: The size for which a smaller size should be found.

        :returns: if there is no smaller size, otherwise a suitable size which is smaller
         in the given direction(s), and the same as in the other direction (if any).

        :see: L{IsSizingContinuous}, L{DoGetNextSmallerSize}
        """

        if relative_to is not None:
            return self.DoGetNextSmallerSize(direction, relative_to)

        return self.DoGetNextSmallerSize(direction, self.GetSize())

[docs]    def GetNextLargerSize(self, direction, relative_to=None):
        """
        If sizing is not continuous, then return a suitable size for the control which
        is larger then the given size.

        :param `direction`: The direction(s) in which the size should increase;
        :param `relative_to`: The size for which a larger size should be found.

        :returns: if there is no larger size, otherwise a suitable size which is larger
         in the given direction(s), and the same as in the other direction (if any).

        :see: L{IsSizingContinuous}, L{DoGetNextLargerSize}
        """

        if relative_to is not None:
            return self.DoGetNextLargerSize(direction, relative_to)

        return self.DoGetNextLargerSize(direction, self.GetSize())

[docs]    def Realize(self):
        """
        Perform initial size and layout calculations after children have been added,
        and/or realize children.
        """

        pass

[docs]    def Realise(self):
        """
        Alias for L{Realize}.
        """

        pass

Navigation

  • index
  • modules |
  • Home |
  • Gallery |
  • Contents»
  • Module code »
  • ribbon.control


ribbon.gallery

  • modules |
  • Home |
  • Gallery |
  • Contents»
  • Module code »
  • ribbon.gallery

Source code for ribbon.gallery

"""
A ribbon gallery is like a `wx.ListBox`, but for bitmaps rather than strings.

Description
===========

It displays a collection of bitmaps arranged in a grid and allows the user to
choose one. As there are typically more bitmaps in a gallery than can be displayed
in the space used for a ribbon, a gallery always has scroll buttons to allow the
user to navigate through the entire gallery.

It also has an "extension" button, the behaviour of which is outside the scope of
the gallery control itself, though it typically displays some kind of dialog related
to the gallery.

Events Processing
=================

This class processes the following events:

=================================== ===================================
Event Name                          Description
=================================== ===================================
``EVT_RIBBONGALLERY_SELECTED``      Triggered when the user selects an item from the gallery. Note that the ID is that of the gallery, not of the item.
``EVT_RIBBONGALLERY_HOVER_CHANGED`` Triggered when the item being hovered over by the user changes. The item in the event will be the new item being hovered, or ``None`` if there is no longer an item being hovered. Note that the ID is that of the gallery, not of the item.
``EVT_RIBBONGALLERY_CLICKED``       Triggered when the user clicks on an item in the gallery.
``EVT_BUTTON``                      Triggered when the "extension" button of the gallery is pressed.
=================================== ===================================
"""

import wx

from control import RibbonControl
from art import *

wxEVT_COMMAND_RIBBONGALLERY_HOVER_CHANGED = wx.NewEventType()
wxEVT_COMMAND_RIBBONGALLERY_SELECTED = wx.NewEventType()
wxEVT_COMMAND_RIBBONGALLERY_CLICKED = wx.NewEventType()

EVT_RIBBONGALLERY_HOVER_CHANGED = wx.PyEventBinder(wxEVT_COMMAND_RIBBONGALLERY_HOVER_CHANGED, 1)
EVT_RIBBONGALLERY_SELECTED = wx.PyEventBinder(wxEVT_COMMAND_RIBBONGALLERY_SELECTED, 1)
EVT_RIBBONGALLERY_CLICKED = wx.PyEventBinder(wxEVT_COMMAND_RIBBONGALLERY_CLICKED, 1)

[docs]class RibbonGalleryEvent(wx.PyCommandEvent):

[docs]    def __init__(self, command_type=None, win_id=0, gallery=None, item=None):

        wx.PyCommandEvent.__init__(self, command_type, win_id)
        self._gallery = gallery
        self._item = item

[docs]    def GetGallery(self):

        return self._gallery

[docs]    def GetGalleryItem(self):

        return self._item

[docs]    def SetGallery(self, gallery):

        self._gallery = gallery

[docs]    def SetGalleryItem(self, item):

        self._item = item

[docs]class RibbonGalleryItem(object):

[docs]    def __init__(self):

        self._id = 0
        self._is_visible = False
        self._client_data = None
        self._position = wx.Rect()

[docs]    def SetId(self, id):

        self._id = id

[docs]    def SetBitmap(self, bitmap):

        self._bitmap = bitmap

[docs]    def GetBitmap(self):

        return self._bitmap

[docs]    def SetIsVisible(self, visible):

        self._is_visible = visible

[docs]    def SetPosition(self, x, y, size):

        self._position = wx.RectPS(wx.Point(x, y), size)

[docs]    def IsVisible(self):

        return self._is_visible

[docs]    def GetPosition(self):

        return self._position

[docs]    def SetClientData(self, data):

        self._client_data = data

[docs]    def GetClientData(self):

        return self._client_data

[docs]class RibbonGallery(RibbonControl):

[docs]    def __init__(self, parent, id=wx.ID_ANY, pos=wx.DefaultPosition, size=wx.DefaultSize, agwStyle=0,
                 name="RibbonGallery"):

        """
        Default class constructor.

        :param `parent`: Pointer to a parent window;
        :param `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;
        :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;
        :param `agwStyle`: the AGW-specific window style;
        :param `name`: the window name.

        """

        RibbonControl.__init__(self, parent, id, pos, size, style=wx.BORDER_NONE, name=name)

        self.CommonInit(agwStyle)

        self.Bind(wx.EVT_ENTER_WINDOW, self.OnMouseEnter)
        self.Bind(wx.EVT_ERASE_BACKGROUND, self.OnEraseBackground)
        self.Bind(wx.EVT_LEAVE_WINDOW, self.OnMouseLeave)
        self.Bind(wx.EVT_LEFT_DOWN, self.OnMouseDown)
        self.Bind(wx.EVT_LEFT_UP, self.OnMouseUp)
        self.Bind(wx.EVT_LEFT_DCLICK, self.OnMouseDClick)
        self.Bind(wx.EVT_MOTION, self.OnMouseMove)
        self.Bind(wx.EVT_PAINT, self.OnPaint)
        self.Bind(wx.EVT_SIZE, self.OnSize)

[docs]    def CommonInit(self, agwStyle):

        self._selected_item = None
        self._hovered_item = None
        self._active_item = None
        self._scroll_up_button_rect = wx.Rect(0, 0, 0, 0)
        self._scroll_down_button_rect = wx.Rect(0, 0, 0, 0)
        self._extension_button_rect = wx.Rect(0, 0, 0, 0)
        self._mouse_active_rect = None
        self._bitmap_size = wx.Size(64, 32)
        self._bitmap_padded_size = self._bitmap_size
        self._item_separation_x = 0
        self._item_separation_y = 0
        self._scroll_amount = 0
        self._scroll_limit = 0
        self._up_button_state = RIBBON_GALLERY_BUTTON_DISABLED
        self._down_button_state = RIBBON_GALLERY_BUTTON_NORMAL
        self._extension_button_state = RIBBON_GALLERY_BUTTON_NORMAL
        self._hovered = False
        self._items = []

        self.SetBackgroundStyle(wx.BG_STYLE_CUSTOM)

[docs]    def OnMouseEnter(self, event):

        self._hovered = True

        if self._mouse_active_rect is not None and not event.LeftIsDown():
            self._mouse_active_rect = None
            self._active_item = None

        self.Refresh(False)

[docs]    def OnMouseMove(self, event):

        refresh = False
        pos = event.GetPosition()

        result1, self._up_button_state = self.TestButtonHover(self._scroll_up_button_rect, pos, self._up_button_state)
        result2, self._down_button_state = self.TestButtonHover(self._scroll_down_button_rect, pos, self._down_button_state)
        result3, self._extension_button_state = self.TestButtonHover(self._extension_button_rect, pos, self._extension_button_state)

        if result1 or result2 or result3:
            refresh = True

        hovered_item = active_item = None

        if self._client_rect.Contains(pos):

            if self._art and self._art.GetFlags() & RIBBON_BAR_FLOW_VERTICAL:
                pos.x += self._scroll_amount
            else:
                pos.y += self._scroll_amount

            item_count = len(self._items)

            for item in self._items:
                if not item.IsVisible():
                    continue

                if item.GetPosition().Contains(pos):
                    if self._mouse_active_rect == item.GetPosition():
                        active_item = item
                    hovered_item = item
                    break

        if active_item != self._active_item:
            self._active_item = active_item
            refresh = True

        if hovered_item != self._hovered_item:
            self._hovered_item = hovered_item
            notification = RibbonGalleryEvent(wxEVT_COMMAND_RIBBONGALLERY_HOVER_CHANGED, self.GetId())
            notification.SetEventObject(self)
            notification.SetGallery(self)
            notification.SetGalleryItem(hovered_item)
            self.GetEventHandler().ProcessEvent(notification)
            refresh = True

        if refresh:
            self.Refresh(False)

[docs]    def TestButtonHover(self, rect, pos, state):

        if state == RIBBON_GALLERY_BUTTON_DISABLED:
            return False, state

        if rect.Contains(pos):
            if self._mouse_active_rect == rect:
                new_state = RIBBON_GALLERY_BUTTON_ACTIVE
            else:
                new_state = RIBBON_GALLERY_BUTTON_HOVERED
        else:
            new_state = RIBBON_GALLERY_BUTTON_NORMAL

        if new_state != state:
            return True, new_state
        else:
            return False, state

[docs]    def OnMouseLeave(self, event):

        self._hovered = False
        self._active_item = None

        if self._up_button_state != RIBBON_GALLERY_BUTTON_DISABLED:
            self._up_button_state = RIBBON_GALLERY_BUTTON_NORMAL
        if self._down_button_state != RIBBON_GALLERY_BUTTON_DISABLED:
            self._down_button_state = RIBBON_GALLERY_BUTTON_NORMAL
        if self._extension_button_state != RIBBON_GALLERY_BUTTON_DISABLED:
            self._extension_button_state = RIBBON_GALLERY_BUTTON_NORMAL
        if self._hovered_item != None:
            self._hovered_item = None
            notification = RibbonGalleryEvent(wxEVT_COMMAND_RIBBONGALLERY_HOVER_CHANGED, self.GetId())
            notification.SetEventObject(self)
            notification.SetGallery(self)
            self.GetEventHandler().ProcessEvent(notification)

        self.Refresh(False)

[docs]    def OnMouseDown(self, event):

        pos = event.GetPosition()
        self._mouse_active_rect = None

        if self._client_rect.Contains(pos):
            if self._art and self._art.GetFlags() & RIBBON_BAR_FLOW_VERTICAL:
                pos.x += self._scroll_amount
            else:
                pos.y += self._scroll_amount

            for item in self._items:
                if not item.IsVisible():
                    continue

                rect = item.GetPosition()
                if rect.Contains(pos):
                    self._active_item = item
                    self._mouse_active_rect = rect
                    break

        elif self._scroll_up_button_rect.Contains(pos):
            if self._up_button_state != RIBBON_GALLERY_BUTTON_DISABLED:
                self._mouse_active_rect = wx.Rect(*self._scroll_up_button_rect)
                self._up_button_state = RIBBON_GALLERY_BUTTON_ACTIVE

        elif self._scroll_down_button_rect.Contains(pos):
            if self._down_button_state != RIBBON_GALLERY_BUTTON_DISABLED:
                self._mouse_active_rect = wx.Rect(*self._scroll_down_button_rect)
                self._down_button_state = RIBBON_GALLERY_BUTTON_ACTIVE

        elif self._extension_button_rect.Contains(pos):
            if self._extension_button_state != RIBBON_GALLERY_BUTTON_DISABLED:
                self._mouse_active_rect = wx.Rect(*self._extension_button_rect)
                self._extension_button_state = RIBBON_GALLERY_BUTTON_ACTIVE

        if self._mouse_active_rect != None:
            self.Refresh(False)

[docs]    def OnMouseUp(self, event):

        if self._mouse_active_rect != None:
            pos = event.GetPosition()

            if self._active_item:
                if self._art and self._art.GetFlags() & RIBBON_BAR_FLOW_VERTICAL:
                    pos.x += self._scroll_amount
                else:
                    pos.y += self._scroll_amount

            if self._mouse_active_rect.Contains(pos):
                if self._mouse_active_rect == self._scroll_up_button_rect:
                    self._up_button_state = RIBBON_GALLERY_BUTTON_HOVERED
                    self.ScrollLines(-1)

                elif self._mouse_active_rect == self._scroll_down_button_rect:
                    self._down_button_state = RIBBON_GALLERY_BUTTON_HOVERED
                    self.ScrollLines(1)

                elif self._mouse_active_rect == self._extension_button_rect:
                    self._extension_button_state = RIBBON_GALLERY_BUTTON_HOVERED
                    notification = wx.CommandEvent(wx.wxEVT_COMMAND_BUTTON_CLICKED, self.GetId())
                    notification.SetEventObject(self)
                    self.GetEventHandler().ProcessEvent(notification)

                elif self._active_item != None:
                    if self._selected_item != self._active_item:
                        self._selected_item = self._active_item
                        notification = RibbonGalleryEvent(wxEVT_COMMAND_RIBBONGALLERY_SELECTED, self.GetId())
                        notification.SetEventObject(self)
                        notification.SetGallery(self)
                        notification.SetGalleryItem(self._selected_item)
                        self.GetEventHandler().ProcessEvent(notification)

                    notification = RibbonGalleryEvent(wxEVT_COMMAND_RIBBONGALLERY_CLICKED, self.GetId())
                    notification.SetEventObject(self)
                    notification.SetGallery(self)
                    notification.SetGalleryItem(self._selected_item)
                    self.GetEventHandler().ProcessEvent(notification)

            self._mouse_active_rect = None
            self._active_item = None
            self.Refresh(False)

[docs]    def OnMouseDClick(self, event):

        # The 2nd click of a double-click should be handled as a click in the
        # same way as the 1st click of the double-click. This is useful for
        # scrolling through the gallery.
        self.OnMouseDown(event)
        self.OnMouseUp(event)

[docs]    def SetItemClientData(self, item, data):
        """
        Set the client data associated with a gallery item.

        :param `item`: MISSING DESCRIPTION;
        :param `data`: MISSING DESCRIPTION.

        """

        item.SetClientData(data)

[docs]    def GetItemClientData(self, item):
        """
        Get the client data associated with a gallery item.

        :param `item`: MISSING DESCRIPTION.

        """

        return item.GetClientData()

[docs]    def ScrollLines(self, lines):
        """
        Scroll the gallery contents by some amount.

        Reimplemented from `wx.Window`.

        :param `lines`: Positive values scroll toward the end of the gallery, while
         negative values scroll toward the start.

        :returns: ``True`` if the gallery scrolled at least one pixel in the given
         direction, ``False`` if it did not scroll.
        """

        if self._scroll_limit == 0 or self._art == None:
            return False

        line_size = self._bitmap_padded_size.GetHeight()
        if self._art.GetFlags() & RIBBON_BAR_FLOW_VERTICAL:
            line_size = self._bitmap_padded_size.GetWidth()

        if lines < 0:
            if self._scroll_amount > 0:
                self._scroll_amount += lines*line_size

                if self._scroll_amount <= 0:
                    self._scroll_amount = 0
                    self._up_button_state = RIBBON_GALLERY_BUTTON_DISABLED

                elif self._up_button_state == RIBBON_GALLERY_BUTTON_DISABLED:
                    self._up_button_state = RIBBON_GALLERY_BUTTON_NORMAL

                if self._down_button_state == RIBBON_GALLERY_BUTTON_DISABLED:
                    self._down_button_state = RIBBON_GALLERY_BUTTON_NORMAL

                return True

        elif lines > 0:
            if self._scroll_amount < self._scroll_limit:
                self._scroll_amount += lines * line_size

                if self._scroll_amount >= self._scroll_limit:
                    self._scroll_amount = self._scroll_limit
                    self._down_button_state = RIBBON_GALLERY_BUTTON_DISABLED

                elif self._down_button_state == RIBBON_GALLERY_BUTTON_DISABLED:
                    self._down_button_state = RIBBON_GALLERY_BUTTON_NORMAL

                if self._up_button_state == RIBBON_GALLERY_BUTTON_DISABLED:
                    self._up_button_state = RIBBON_GALLERY_BUTTON_NORMAL

                return True

        return False

[docs]    def EnsureVisible(self, item):
        """
        Scroll the gallery to ensure that the given item is visible.

        :param `item`: MISSING DESCRIPTION.

        """

        if item is None or not item.IsVisible() or self.IsEmpty():
            return

        y = item.GetPosition().GetTop()
        base_y = self._items[0].GetPosition().GetTop()
        delta = y - base_y - self._scroll_amount
        self.ScrollLines(delta/self._bitmap_padded_size.GetHeight())

[docs]    def IsHovered(self):
        """
        Query is the mouse is currently hovered over the gallery.

        :returns: ``True`` if the cursor is within the bounds of the gallery (not
         just hovering over an item), ``False`` otherwise.
        """

        return self._hovered

[docs]    def OnEraseBackground(self, event):

        # All painting done in main paint handler to minimise flicker
        pass

[docs]    def OnPaint(self, event):

        dc = wx.AutoBufferedPaintDC(self)

        if self._art == None:
            return

        self._art.DrawGalleryBackground(dc, self, wx.Rect(0, 0, *self.GetSize()))

        padding_top = self._art.GetMetric(RIBBON_ART_GALLERY_BITMAP_PADDING_TOP_SIZE)
        padding_left = self._art.GetMetric(RIBBON_ART_GALLERY_BITMAP_PADDING_LEFT_SIZE)

        dc.SetClippingRect(self._client_rect)

        offset_vertical = True

        if self._art.GetFlags() & RIBBON_BAR_FLOW_VERTICAL:
            offset_vertical = False

        for item in self._items:
            if not item.IsVisible():
                continue

            pos = item.GetPosition()
            offset_pos = wx.Rect(*pos)

            if offset_vertical:
                offset_pos.SetTop(offset_pos.GetTop() - self._scroll_amount)
            else:
                offset_pos.SetLeft(offset_pos.GetLeft() - self._scroll_amount)

            self._art.DrawGalleryItemBackground(dc, self, offset_pos, item)
            dc.DrawBitmap(item.GetBitmap(), offset_pos.GetLeft() + padding_left, offset_pos.GetTop() + padding_top)

[docs]    def OnSize(self, event):

        self.Layout()

[docs]    def Append(self, bitmap, id, clientData=None):
        """
        Add an item to the gallery (with complex client data).

        :param `bitmap`: The bitmap to display for the item. Note that all items must
         have equally sized bitmaps;
        :param `id`: ID number to associate with the item. Not currently used for
         anything important;
        :param `clientData`: An object which contains data to associate with the item.
         The item takes ownership of this pointer, and will delete it when the item
         client data is changed to something else, or when the item is destroyed.

        """

        if not bitmap.IsOk():
            raise Exception("exception")

        if not self._items:
            self._bitmap_size = bitmap.GetSize()
            self.CalculateMinSize()
        else:
            if bitmap.GetSize() != self._bitmap_size:
                raise Exception("exception")

        item = RibbonGalleryItem()
        item.SetId(id)
        item.SetBitmap(bitmap)
        self._items.append(item)

        item.SetClientData(clientData)

        return item

[docs]    def Clear(self):
        """
        Remove all items from the gallery.
        """

        self._items = []

[docs]    def IsSizingContinuous(self):

        return False

[docs]    def CalculateMinSize(self):

        if self._art == None or not self._bitmap_size.IsFullySpecified():
            self.SetMinSize(wx.Size(20, 20))
        else:
            self._bitmap_padded_size = wx.Size(*self._bitmap_size)
            self._bitmap_padded_size.IncBy(self._art.GetMetric(RIBBON_ART_GALLERY_BITMAP_PADDING_LEFT_SIZE) +
                                           self._art.GetMetric(RIBBON_ART_GALLERY_BITMAP_PADDING_RIGHT_SIZE),
                                           self._art.GetMetric(RIBBON_ART_GALLERY_BITMAP_PADDING_TOP_SIZE) +
                                           self._art.GetMetric(RIBBON_ART_GALLERY_BITMAP_PADDING_BOTTOM_SIZE))

            dc = wx.MemoryDC()
            self.SetMinSize(self._art.GetGallerySize(dc, self, wx.Size(*self._bitmap_padded_size)))

            # The best size is displaying several items
            self._best_size = wx.Size(*self._bitmap_padded_size)
            self._best_size.x *= 3
            self._best_size = self._art.GetGallerySize(dc, self, wx.Size(*self._best_size))

[docs]    def Realize(self):

        self.CalculateMinSize()
        return self.Layout()

[docs]    def Layout(self):

        if self._art == None:
            return False

        dc = wx.MemoryDC()
        origin = wx.Point()

        client_size, origin, self._scroll_up_button_rect, self._scroll_down_button_rect, self._extension_button_rect = \
                     self._art.GetGalleryClientSize(dc, self, wx.Size(*self.GetSize()))

        self._client_rect = wx.RectPS(origin, client_size)

        x_cursor = y_cursor = 0
        art_flags = self._art.GetFlags()

        for indx, item in enumerate(self._items):

            item.SetIsVisible(True)

            if art_flags & RIBBON_BAR_FLOW_VERTICAL:
                if y_cursor + self._bitmap_padded_size.y > client_size.GetHeight():
                    if y_cursor == 0:
                        break

                    y_cursor = 0
                    x_cursor += self._bitmap_padded_size.x

                item.SetPosition(origin.x + x_cursor, origin.y + y_cursor, self._bitmap_padded_size)
                y_cursor += self._bitmap_padded_size.y

            else:
                if x_cursor + self._bitmap_padded_size.x > client_size.GetWidth():
                    if x_cursor == 0:
                        break

                    x_cursor = 0
                    y_cursor += self._bitmap_padded_size.y

                item.SetPosition(origin.x + x_cursor, origin.y + y_cursor, self._bitmap_padded_size)
                x_cursor += self._bitmap_padded_size.x

        for item in self._items[indx:]:
            item.SetIsVisible(False)

        if art_flags & RIBBON_BAR_FLOW_VERTICAL:
            self._scroll_limit = x_cursor
        else:
            self._scroll_limit = y_cursor

        if self._scroll_amount >= self._scroll_limit:
            self._scroll_amount = self._scroll_limit
            self._down_button_state = RIBBON_GALLERY_BUTTON_DISABLED

        elif self._down_button_state == RIBBON_GALLERY_BUTTON_DISABLED:
            self._down_button_state = RIBBON_GALLERY_BUTTON_NORMAL

        if self._scroll_amount <= 0:
            self._scroll_amount = 0
            self._up_button_state = RIBBON_GALLERY_BUTTON_DISABLED

        elif self._up_button_state == RIBBON_GALLERY_BUTTON_DISABLED:
            self._up_button_state = RIBBON_GALLERY_BUTTON_NORMAL

        return True

[docs]    def DoGetBestSize(self):

        return self._best_size

[docs]    def DoGetNextSmallerSize(self, direction, relative_to):

        if self._art == None:
            return relative_to

        dc = wx.MemoryDC()
        client, d1, d2, d3, d4 = self._art.GetGalleryClientSize(dc, self, wx.Size(*relative_to))

        if direction == wx.HORIZONTAL:
            client.DecBy(1, 0)
        elif direction == wx.VERTICAL:
            client.DecBy(0, 1)
        elif direction == wx.BOTH:
            client.DecBy(1, 1)

        if client.GetWidth() < 0 or client.GetHeight() < 0:
            return relative_to

        client.x = (client.x / self._bitmap_padded_size.x) * self._bitmap_padded_size.x
        client.y = (client.y / self._bitmap_padded_size.y) * self._bitmap_padded_size.y

        size = self._art.GetGallerySize(dc, self, wx.Size(*client))
        minimum = self.GetMinSize()

        if size.GetWidth() < minimum.GetWidth() or size.GetHeight() < minimum.GetHeight():
            return relative_to

        if direction == wx.HORIZONTAL:
            size.SetHeight(relative_to.GetHeight())
        elif direction == wx.VERTICAL:
            size.SetWidth(relative_to.GetWidth())

        return size

[docs]    def DoGetNextLargerSize(self, direction, relative_to):

        if self._art == None:
            return relative_to

        dc = wx.MemoryDC()
        client, d1, d2, d3, d4 = self._art.GetGalleryClientSize(dc, self, wx.Size(*relative_to))

        # No need to grow if the given size can already display every item
        nitems = (client.GetWidth()/self._bitmap_padded_size.x)*(client.GetHeight()/self._bitmap_padded_size.y)

        if nitems >= len(self._items):
            return relative_to

        if direction == wx.HORIZONTAL:
            client.IncBy(self._bitmap_padded_size.x, 0)
        elif direction == wx.VERTICAL:
            client.IncBy(0, self._bitmap_padded_size.y)
        elif direction == wx.BOTH:
            client.IncBy(self._bitmap_padded_size)

        client.x = (client.x / self._bitmap_padded_size.x) * self._bitmap_padded_size.x
        client.y = (client.y / self._bitmap_padded_size.y) * self._bitmap_padded_size.y

        size = self._art.GetGallerySize(dc, self, wx.Size(*client))
        minimum = self.GetMinSize()

        if size.GetWidth() < minimum.GetWidth() or size.GetHeight() < minimum.GetHeight():
            return relative_to

        if direction == wx.HORIZONTAL:
            size.SetHeight(relative_to.GetHeight())
        if direction == wx.VERTICAL:
            size.SetWidth(relative_to.GetWidth())

        return size

[docs]    def IsEmpty(self):
        """
        Query if the gallery has no items in it.
        """

        return len(self._items) == 0

[docs]    def GetCount(self):
        """
        Get the number of items in the gallery.
        """

        return len(self._items)

[docs]    def GetItem(self, n):
        """
        Get an item by index.

        :param `n`: MISSING DESCRIPTION.

        """

        if n >= self.GetCount():
            return None

        return self._items[n]

[docs]    def SetSelection(self, item):
        """
        Set the selection to the given item, or removes the selection if `item` == ``None``.

        Note that this not cause any events to be emitted.

        :param `item`: MISSING DESCRIPTION.

        """

        if item != self._selected_item:
            self._selected_item = item
            self.Refresh(False)

[docs]    def GetSelection(self):
        """
        Get the currently selected item, or ``None`` if there is none.

        The selected item is set by L{SetSelection}, or by the user clicking on an item.

        """

        return self._selected_item

[docs]    def GetHoveredItem(self):
        """
        Get the currently hovered item, or ``None`` if there is none.

        The hovered item is the item underneath the mouse cursor.

        """

        return self._hovered_item

[docs]    def GetActiveItem(self):
        """
        Get the currently active item, or ``None`` if there is none.

        The active item is the item being pressed by the user, and will thus become the
        selected item if the user releases the mouse button.

        """

        return self._active_item

[docs]    def GetUpButtonState(self):
        """
        Get the state of the scroll up button.
        """

        return self._up_button_state

[docs]    def GetDownButtonState(self):
        """
        Get the state of the scroll down button.
        """

        return self._down_button_state

[docs]    def GetExtensionButtonState(self):
        """
        Get the state of the "extension" button.
        """

        return self._extension_button_state

[docs]    def GetDefaultBorder(self):

        return wx.BORDER_NONE

Navigation

  • index
  • modules |
  • Home |
  • Gallery |
  • Contents»
  • Module code »
  • ribbon.gallery


ribbon.page

  • modules |
  • Home |
  • Gallery |
  • Contents»
  • Module code »
  • ribbon.page

Source code for ribbon.page

"""
Description
===========

Container for related ribbon panels, and a tab within a ribbon bar.

See Also
========

L{RibbonBar}, L{RibbonPanel}

"""

import wx

from control import RibbonControl
from panel import RibbonPanel

from art import *

# As scroll buttons need to be rendered on top of a page's child windows, the
# buttons themselves have to be proper child windows (rather than just painted
# onto the page). In order to get proper clipping of a page's children (with
# regard to the scroll button), the scroll buttons are created as children of
# the ribbon bar rather than children of the page. This could not have been
# achieved by creating buttons as children of the page and then doing some Z-order
# manipulation, as self causes problems on win32 due to ribbon panels having the
# transparent flag set.

[docs]def GetSizeInOrientation(size, orientation):

    if orientation == wx.HORIZONTAL:
        return size.GetWidth()
    elif orientation == wx.VERTICAL:
        return size.GetHeight()
    elif orientation == wx.BOTH:
        return size.GetWidth() * size.GetHeight()

    return 0

[docs]class RibbonPageScrollButton(RibbonControl):

[docs]    def __init__(self, sibling, id=wx.ID_ANY, pos=wx.DefaultPosition, size=wx.DefaultSize, style=0):

        RibbonControl.__init__(self, sibling.GetParent(), id, pos, size, style=wx.BORDER_NONE)

        self.SetBackgroundStyle(wx.BG_STYLE_CUSTOM)
        self._sibling = sibling
        self._flags = (style & RIBBON_SCROLL_BTN_DIRECTION_MASK) | RIBBON_SCROLL_BTN_FOR_PAGE

        self.Bind(wx.EVT_ENTER_WINDOW, self.OnMouseEnter)
        self.Bind(wx.EVT_ERASE_BACKGROUND, self.OnEraseBackground)
        self.Bind(wx.EVT_LEAVE_WINDOW, self.OnMouseLeave)
        self.Bind(wx.EVT_LEFT_DOWN, self.OnMouseDown)
        self.Bind(wx.EVT_LEFT_UP, self.OnMouseUp)
        self.Bind(wx.EVT_PAINT, self.OnPaint)

[docs]    def OnEraseBackground(self, event):

        # Do nothing - all painting done in main paint handler
        pass

[docs]    def OnPaint(self, event):

        dc = wx.AutoBufferedPaintDC(self)

        if self._art:
            self._art.DrawScrollButton(dc, self, wx.Rect(0, 0, *self.GetSize()), self._flags)

[docs]    def OnMouseEnter(self, event):

        self._flags |= RIBBON_SCROLL_BTN_HOVERED
        self.Refresh(False)

[docs]    def OnMouseLeave(self, event):

        self._flags &= ~RIBBON_SCROLL_BTN_HOVERED
        self._flags &= ~RIBBON_SCROLL_BTN_ACTIVE
        self.Refresh(False)

[docs]    def OnMouseDown(self, event):

        self._flags |= RIBBON_SCROLL_BTN_ACTIVE
        self.Refresh(False)

[docs]    def OnMouseUp(self, event):

        if self._flags & RIBBON_SCROLL_BTN_ACTIVE:

            self._flags &= ~RIBBON_SCROLL_BTN_ACTIVE
            self.Refresh(False)
            result = self._flags & RIBBON_SCROLL_BTN_DIRECTION_MASK

            if result in [RIBBON_SCROLL_BTN_DOWN, RIBBON_SCROLL_BTN_RIGHT]:
                self._sibling.ScrollLines(1)
            elif result in [RIBBON_SCROLL_BTN_UP, RIBBON_SCROLL_BTN_LEFT]:
                self._sibling.ScrollLines(-1)

[docs]class RibbonPage(RibbonControl):

[docs]    def __init__(self, parent, id=wx.ID_ANY, label="", icon=wx.NullBitmap, style=0):
        """
        Default class constructor.

        :param `parent`: Pointer to a parent window;
        :param `id`: Window identifier. If ``wx.ID_ANY``, will automatically create an identifier;
        :param `label`: Label of the new button;
        :param `icon`: the icon used for the page in the ribbon bar tab area;
        :param `style`: Window style.

        """

        RibbonControl.__init__(self, parent, id, wx.DefaultPosition, wx.DefaultSize, wx.BORDER_NONE)

        self.CommonInit(label, icon)

        self.Bind(wx.EVT_ERASE_BACKGROUND, self.OnEraseBackground)
        self.Bind(wx.EVT_PAINT, self.OnPaint)
        self.Bind(wx.EVT_SIZE, self.OnSize)

[docs]    def CommonInit(self, label, icon):

        self.SetName(label)
        self.SetLabel(label)

        self._old_size = wx.Size(0, 0)
        self._icon = icon
        self._scroll_left_btn = None
        self._scroll_right_btn = None
        self._size_calc_array = None
        self._size_calc_array_size = 0
        self._scroll_amount = 0
        self._scroll_buttons_visible = False
        self._collapse_stack = []

        self.SetBackgroundStyle(wx.BG_STYLE_CUSTOM)

        self.GetParent().AddPage(self)

[docs]    def SetArtProvider(self, art):
        """
        Set the art provider to be used.

        Normally called automatically by L{RibbonBar} when the page is created, or the
        art provider changed on the bar. The new art provider will be propagated to the
        children of the page.

        Reimplemented from L{RibbonControl}.

        :param `art`: MISSING DESCRIPTION.

        """

        self._art = art
        for child in self.GetChildren():
            if isinstance(child, RibbonControl):
                child.SetArtProvider(art)

[docs]    def AdjustRectToIncludeScrollButtons(self, rect):
        """
        Expand a rectangle of the page to include external scroll buttons (if any).

        When no scroll buttons are shown, has no effect.

        :param `rect`: The rectangle to adjust. The width and height will not be
         reduced, and the x and y will not be increased.

        """

        if self._scroll_buttons_visible:
            if self.GetMajorAxis() == wx.VERTICAL:
                if self._scroll_left_btn:
                    rect.SetY(rect.GetY() - self._scroll_left_btn.GetSize().GetHeight())
                    rect.SetHeight(rect.GetHeight() + self._scroll_left_btn.GetSize().GetHeight())

                if self._scroll_right_btn:
                    rect.SetHeight(rect.GetHeight() + self._scroll_right_btn.GetSize().GetHeight())

            else:
                if self._scroll_left_btn:
                    rect.SetX(rect.GetX() - self._scroll_left_btn.GetSize().GetWidth())
                    rect.SetWidth(rect.GetWidth() + self._scroll_left_btn.GetSize().GetWidth())

                if self._scroll_right_btn:
                    rect.SetWidth(rect.GetWidth() + self._scroll_right_btn.GetSize().GetWidth())

        return rect

[docs]    def OnEraseBackground(self, event):

        # All painting done in main paint handler to minimise flicker
        pass

[docs]    def OnPaint(self, event):

        # No foreground painting done by the page itself, but a paint DC
        # must be created anyway.
        dc = wx.AutoBufferedPaintDC(self)
        rect = wx.Rect(0, 0, *self.GetSize())
        rect = self.AdjustRectToIncludeScrollButtons(rect)
        self._art.DrawPageBackground(dc, self, rect)

[docs]    def GetMajorAxis(self):
        """
        Get the direction in which ribbon panels are stacked within the page.

        This is controlled by the style of the containing L{RibbonBar}, meaning that all
        pages within a bar will have the same major axis. As well as being the direction
        in which panels are stacked, it is also the axis in which scrolling will occur
        (when required).

        :returns: ``wx.HORIZONTAL`` or ``wx.VERTICAL`` (never ``wx.BOTH``).
        """

        if self._art and (self._art.GetFlags() & RIBBON_BAR_FLOW_VERTICAL):
            return wx.VERTICAL
        else:
            return wx.HORIZONTAL

[docs]    def ScrollLines(self, lines):
        """
        Scroll the page by some amount up / down / left / right.

        When the page's children are too big to fit in the onscreen area given to the
        page, scroll buttons will appear, and the page can be programatically scrolled.
        Positive values of will scroll right or down, while negative values will scroll
        up or left (depending on the direction in which panels are stacked). A line is
        equivalent to a constant number of pixels.

        Reimplemented from `wx.Window`.

        :param `lines`: MISSING DESCRIPTION.

        :returns: ``True`` if the page scrolled at least one pixel in the given direction,
         ``False`` if it did not scroll.

        :see: L{GetMajorAxis}, L{ScrollPixels}
        """

        return self.ScrollPixels(lines * 8)

[docs]    def ScrollPixels(self, pixels):
        """
        Scroll the page by a set number of pixels up / down / left / right.

        When the page's children are too big to fit in the onscreen area given to the
        page, scroll buttons will appear, and the page can be programatically scrolled.
        Positive values of will scroll right or down, while negative values will scroll
        up or left (depending on the direction in which panels are stacked).

        :param `pixels`: MISSING DESCRIPTION.

        :returns: ``True`` if the page scrolled at least one pixel in the given direction,
         ``False`` if it did not scroll.

        :see: L{GetMajorAxis}, L{ScrollLines}
        """

        if pixels < 0:
            if self._scroll_amount == 0:
                return False

            if self._scroll_amount < -pixels:
                pixels = -self._scroll_amount

        elif pixels > 0:
            if self._scroll_amount == self._scroll_amount_limit:
                return False

            if self._scroll_amount + pixels > self._scroll_amount_limit:
                pixels = self._scroll_amount_limit - self._scroll_amount

        else:
            return False

        self._scroll_amount += pixels

        for child in self.GetChildren():
            x, y = child.GetPosition()
            if self.GetMajorAxis() == wx.HORIZONTAL:
                x -= pixels
            else:
                y -= pixels

            child.SetPosition(wx.Point(x, y))

        self.ShowScrollButtons()
        self.Refresh()
        return True

[docs]    def SetSizeWithScrollButtonAdjustment(self, x, y, width, height):
        """
        Set the size of the page and the external scroll buttons (if any).

        When a page is too small to display all of its children, scroll buttons will
        appear (and if the page is sized up enough, they will disappear again). Slightly
        counter-intuively, these buttons are created as siblings of the page rather than
        children of the page (to achieve correct cropping and paint ordering of the
        children and the buttons).

        When there are no scroll buttons, this function behaves the same as `SetSize`,
        however when there are scroll buttons, it positions them at the edges of the
        given area, and then calls `SetSize` with the remaining area. This is provided
        as a separate function to `SetSize` rather than within the implementation
        of `SetSize`, as iteracting algorithms may not expect `SetSize` to also
        set the size of siblings.

        :param `x`: MISSING DESCRIPTION;
        :param `y`: MISSING DESCRIPTION;
        :param `width`: MISSING DESCRIPTION;
        :param `height`: MISSING DESCRIPTION.

        """

        if self._scroll_buttons_visible:
            if self.GetMajorAxis() == wx.HORIZONTAL:
                if self._scroll_left_btn:
                    w = self._scroll_left_btn.GetSize().GetWidth()
                    self._scroll_left_btn.SetPosition(wx.Point(x, y))
                    x += w
                    width -= w

                if self._scroll_right_btn:
                    w = self._scroll_right_btn.GetSize().GetWidth()
                    width -= w
                    self._scroll_right_btn.SetPosition(wx.Point(x + width, y))

            else:
                if self._scroll_left_btn:
                    h = self._scroll_left_btn.GetSize().GetHeight()
                    self._scroll_left_btn.SetPosition(wx.Point(x, y))
                    y += h
                    height -= h

                if self._scroll_right_btn:
                    h = self._scroll_right_btn.GetSize().GetHeight()
                    height -= h
                    self._scroll_right_btn.SetPosition(wx.Point(x, y + height))

        if width < 0:
            width = 0
        if height < 0:
            height = 0

        self.SetDimensions(x, y, width, height)

[docs]    def DoSetSize(self, x, y, width, height, sizeFlags=wx.SIZE_AUTO):

        # When a resize triggers the scroll buttons to become visible, the page is resized.
        # This resize from within a resize event can cause (MSW) wxWidgets some confusion,
        # and report the 1st size to the 2nd size event. Hence the most recent size is
        # remembered internally and used in Layout() where appropiate.

        if self.GetMajorAxis() == wx.HORIZONTAL:
            self._size_in_major_axis_for_children = width
        else:
            self._size_in_major_axis_for_children = height

        RibbonControl.DoSetSize(self, x, y, width, height, sizeFlags)

[docs]    def OnSize(self, event):

        new_size = event.GetSize()

        temp_dc = wx.MemoryDC()
        invalid_rect = self._art.GetPageBackgroundRedrawArea(temp_dc, self, self._old_size, new_size)
        self.Refresh(True, invalid_rect)

        self._old_size = wx.Size(*new_size)
        x, y = new_size

        if x > 0 and y > 0:
            self.Layout()
        else:
            # Simplify other calculations by pretending new size is zero in both
            # X and Y
            new_size = wx.Size(0, 0)
            # When size == 0, no point in doing any layout

        event.Skip()

[docs]    def RemoveChild(self, child):

        # Remove all references to the child from the collapse stack

        try:
            self._collapse_stack.remove(child)
        except ValueError:
            pass

        # ... and then proceed as normal
        RibbonControl.RemoveChild(self, child)

[docs]    def Realize(self):
        """
        Perform a full re-layout of all panels on the page.

        Should be called after panels are added to the page, or the sizing behaviour of
        a panel on the page changes (i.e. due to children being added to it). Usually
        called automatically when L{RibbonBar.Realize} is called. Will invoke
        L{RibbonPanel.Realize} for all child panels.

        Reimplemented from L{RibbonControl}.

        """

        status = True
        self._collapse_stack = []

        for child in self.GetChildren():
            if not isinstance(child, RibbonControl):
                continue

            if not child.Realize():
                status = False

            child.SetSize(wx.Size(*child.GetMinSize()))

        x, y = self.GetSize()
        if x > 0 and y > 0:
            status = self.Layout() and status

        return status

[docs]    def Layout(self):

        if len(self.GetChildren()) == 0:
            return True

        origin_ = wx.Point(self._art.GetMetric(RIBBON_ART_PAGE_BORDER_LEFT_SIZE), self._art.GetMetric(RIBBON_ART_PAGE_BORDER_TOP_SIZE))
        major_axis = self.GetMajorAxis()

        if self._scroll_buttons_visible:
            if major_axis == wx.HORIZONTAL:
                origin_.x -= self._scroll_amount
                if self._scroll_left_btn:
                    origin_.x -= self._scroll_left_btn.GetSize().GetWidth()
            else:
                origin_.y -= self._scroll_amount
                if self._scroll_left_btn:
                    origin_.y -= self._scroll_left_btn.GetSize().GetHeight()

        origin = wx.Point(*origin_)

        if major_axis == wx.HORIZONTAL:
            gap = self._art.GetMetric(RIBBON_ART_PANEL_X_SEPARATION_SIZE)
            minor_axis_size = self.GetSize().GetHeight() - origin.y - self._art.GetMetric(RIBBON_ART_PAGE_BORDER_BOTTOM_SIZE)
        else:
            gap = self._art.GetMetric(RIBBON_ART_PANEL_Y_SEPARATION_SIZE)
            minor_axis_size = self.GetSize().GetWidth() - origin.x - self._art.GetMetric(RIBBON_ART_PAGE_BORDER_RIGHT_SIZE)

        for iteration in xrange(1, 3):

            for child in self.GetChildren():
                w, h = child.GetSize()
                if major_axis == wx.HORIZONTAL:
                    child.SetDimensions(origin.x, origin.y, w, minor_axis_size)
                    origin.x += w + gap
                else:
                    child.SetDimensions(origin.x, origin.y, minor_axis_size, h)
                    origin.y += h + gap

            if iteration == 1:
                if major_axis == wx.HORIZONTAL:
                    available_space = self._size_in_major_axis_for_children - self._art.GetMetric(RIBBON_ART_PAGE_BORDER_RIGHT_SIZE) - origin.x + gap
                else:
                    available_space = self._size_in_major_axis_for_children - self._art.GetMetric(RIBBON_ART_PAGE_BORDER_BOTTOM_SIZE) - origin.y + gap

                if self._scroll_buttons_visible:
                    available_space -= self._scroll_amount
                    if self._scroll_right_btn != None:
                        available_space += GetSizeInOrientation(self._scroll_right_btn.GetSize(), major_axis)

                if available_space > 0:
                    if self._scroll_buttons_visible:
                        self.HideScrollButtons()
                        break

                    result = self.ExpandPanels(major_axis, available_space)
                    if not result:
                        break

                elif available_space < 0:
                    if self._scroll_buttons_visible:
                        # Scroll buttons already visible - not going to be able to downsize any more
                        self._scroll_amount_limit = -available_space
                        if self._scroll_amount > self._scroll_amount_limit:
                            self.ScrollPixels(self._scroll_amount_limit - self._scroll_amount)
                    else:
                        result = self.CollapsePanels(major_axis, -available_space)
                        if not result:
                            self._scroll_amount = 0
                            self._scroll_amount_limit = -available_space
                            self.ShowScrollButtons()
                            break

                else:
                    break

            origin = wx.Point(*origin_) # Reset the origin

        return True

[docs]    def Show(self, show=True):

        if self._scroll_left_btn:
            self._scroll_left_btn.Show(show)
        if self._scroll_right_btn:
            self._scroll_right_btn.Show(show)

        return RibbonControl.Show(self, show)

[docs]    def GetIcon(self):
        """
        Get the icon used for the page in the ribbon bar tab area (only displayed if the
        ribbon bar is actually showing icons).
        """

        return self._icon

[docs]    def HideScrollButtons(self):

        self._scroll_amount = 0
        self._scroll_amount_limit = 0
        self.ShowScrollButtons()

[docs]    def ShowScrollButtons(self):

        show_left = True
        show_right = True
        reposition = False

        if self._scroll_amount == 0:
            show_left = False

        if self._scroll_amount >= self._scroll_amount_limit:
            show_right = False
            self._scroll_amount = self._scroll_amount_limit

        self._scroll_buttons_visible = show_left or show_right

        if show_left:
            if self._scroll_left_btn == None:

                temp_dc = wx.MemoryDC()

                if self.GetMajorAxis() == wx.HORIZONTAL:
                    direction = RIBBON_SCROLL_BTN_LEFT
                    size = self._art.GetScrollButtonMinimumSize(temp_dc, self.GetParent(), direction)
                    size.SetHeight(self.GetSize().GetHeight())
                else:
                    direction = RIBBON_SCROLL_BTN_UP
                    size = self._art.GetScrollButtonMinimumSize(temp_dc, self.GetParent(), direction)
                    size.SetWidth(self.GetSize().GetWidth())

                self._scroll_left_btn = RibbonPageScrollButton(self, -1, self.GetPosition(), size, direction)
                if not self.IsShown():
                    self._scroll_left_btn.Hide()

                reposition = True

        else:
            if self._scroll_left_btn != None:
                self._scroll_left_btn.Destroy()
                self._scroll_left_btn = None
                reposition = True

        if show_right:
            if self._scroll_right_btn == None:

                temp_dc = wx.MemoryDC()

                if self.GetMajorAxis() == wx.HORIZONTAL:
                    direction = RIBBON_SCROLL_BTN_RIGHT
                    size = self._art.GetScrollButtonMinimumSize(temp_dc, self.GetParent(), direction)
                    size.SetHeight(self.GetSize().GetHeight())
                else:
                    direction = RIBBON_SCROLL_BTN_DOWN
                    size = self._art.GetScrollButtonMinimumSize(temp_dc, self.GetParent(), direction)
                    size.SetWidth(self.GetSize().GetWidth())

                initial_pos = self.GetPosition() + wx.Point(*self.GetSize()) - wx.Point(*size)
                self._scroll_right_btn = RibbonPageScrollButton(self, -1, initial_pos, size, direction)
                if not self.IsShown():
                    self._scroll_right_btn.Hide()

                reposition = True

        else:
            if self._scroll_right_btn != None:
                self._scroll_right_btn.Destroy()
                self._scroll_right_btn = None
                reposition = True

        if reposition:
            self.GetParent().RepositionPage(self)

[docs]    def ExpandPanels(self, direction, maximum_amount):

        expanded_something = False

        while maximum_amount > 0:
            smallest_size = 10000
            smallest_panel = None

            for panel in self.GetChildren():

                if not isinstance(panel, RibbonPanel):
                    continue

                if panel.IsSizingContinuous():
                    size = GetSizeInOrientation(panel.GetSize(), direction)
                    if size < smallest_size:
                        smallest_size = size
                        smallest_panel = panel
                else:
                    current = panel.GetSize()
                    size = GetSizeInOrientation(current, direction)
                    if size < smallest_size:
                        larger = panel.GetNextLargerSize(direction)
                        if larger != current and GetSizeInOrientation(larger, direction) > size:
                            smallest_size = size
                            smallest_panel = panel

            if smallest_panel != None:
                if smallest_panel.IsSizingContinuous():
                    size = wx.Size(*smallest_panel.GetSize())
                    amount = maximum_amount

                    if amount > 32:
                        # For "large" growth, grow self panel a bit, and then re-allocate
                        # the remainder (which may come to self panel again anyway)
                        amount = 32

                    if direction & wx.HORIZONTAL:
                        size.x += amount

                    if direction & wx.VERTICAL:
                        size.y += amount

                    smallest_panel.SetSize(size)
                    maximum_amount -= amount
                    self._collapse_stack.append(smallest_panel)
                    expanded_something = True

                else:
                    current = smallest_panel.GetSize()
                    larger = smallest_panel.GetNextLargerSize(direction)
                    delta = larger - current
                    if GetSizeInOrientation(delta, direction) <= maximum_amount:
                        smallest_panel.SetSize(wx.Size(*larger))
                        maximum_amount -= GetSizeInOrientation(delta, direction)
                        self._collapse_stack.append(smallest_panel)
                        expanded_something = True
                    else:
                        break

            else:
                break

        if expanded_something:
            self.Refresh()
            return True
        else:
            return False

[docs]    def CollapsePanels(self, direction, minimum_amount):

        collapsed_something = False

        while minimum_amount > 0:
            largest_size = 0
            largest_panel = None

            if self._collapse_stack:
                # For a more consistent panel layout, try to collapse panels which
                # were recently expanded.
                largest_panel = self._collapse_stack[-1]
                self._collapse_stack.pop(len(self._collapse_stack)-1)
            else:
                for panel in self.GetChildren():
                    if not isinstance(panel, RibbonPanel):
                        continue

                    if panel.IsSizingContinuous():
                        size = GetSizeInOrientation(panel.GetSize(), direction)
                        if size > largest_size:
                            largest_size = size
                            largest_panel = panel
                    else:
                        current = panel.GetSize()
                        size = GetSizeInOrientation(current, direction)
                        if size > largest_size:
                            smaller = panel.GetNextSmallerSize(direction)
                            if smaller != current and GetSizeInOrientation(smaller, direction) < size:
                                largest_size = size
                                largest_panel = panel

            if largest_panel != None:
                if largest_panel.IsSizingContinuous():
                    size = largest_panel.GetSize()
                    amount = minimum_amount

                    if amount > 32:
                        # For "large" contraction, reduce self panel a bit, and
                        # then re-allocate the remainder of the quota (which may
                        # come to this panel again anyway)
                        amount = 32

                    if direction & wx.HORIZONTAL:
                        size.x -= amount

                    if direction & wx.VERTICAL:
                        size.y -= amount

                    largest_panel.SetSize(size)
                    minimum_amount -= amount
                    collapsed_something = True

                else:
                    current = largest_panel.GetSize()
                    smaller = largest_panel.GetNextSmallerSize(direction)
                    delta = current - smaller
                    largest_panel.SetSize(smaller)
                    minimum_amount -= GetSizeInOrientation(delta, direction)
                    collapsed_something = True

            else:
                break

        if collapsed_something:
            self.Refresh()
            return True
        else:
            return False

[docs]    def DismissExpandedPanel(self):
        """
        Dismiss the current externally expanded panel, if there is one.

        When a ribbon panel automatically minimises, it can be externally expanded into
        a floating window. When the user clicks a button in such a panel, the panel
        should generally re-minimise. Event handlers for buttons on ribbon panels should
        call this method to achieve this behaviour.

        :returns: ``True`` if a panel was minimised, ``False`` otherwise.
        """

        for panel in self.GetChildren():
            if not isinstance(panel, RibbonPanel):
                continue

            if panel.GetExpandedPanel() != None:
                return panel.HideExpanded()

        return False

[docs]    def GetMinSize(self):

        minSize = wx.Size(-1, -1)

        for child in self.GetChildren():
            child_min = child.GetMinSize()
            minSize.x = max(minSize.x, child_min.x)
            minSize.y = max(minSize.y, child_min.y)

        if self.GetMajorAxis() == wx.HORIZONTAL:
            minSize.x = -1
            if minSize.y != -1:
                minSize.y += self._art.GetMetric(RIBBON_ART_PAGE_BORDER_TOP_SIZE) + self._art.GetMetric(RIBBON_ART_PAGE_BORDER_BOTTOM_SIZE)

        else:
            if minSize.x != -1:
                minSize.x += self._art.GetMetric(RIBBON_ART_PAGE_BORDER_LEFT_SIZE) + self._art.GetMetric(RIBBON_ART_PAGE_BORDER_RIGHT_SIZE)

            minSize.y = -1

        return minSize

[docs]    def DoGetBestSize(self):

        best = wx.Size(0, 0)
        count = 0

        if self.GetMajorAxis() == wx.HORIZONTAL:
            best.y = -1

            for child in self.GetChildren():
                child_best = child.GetBestSize()
                if child_best.x != -1:
                    best.IncBy(child_best.x, 0)

                best.y = max(best.y, child_best.y)
                count += 1

            if count > 1:
                best.IncBy((count - 1) * self._art.GetMetric(RIBBON_ART_PANEL_X_SEPARATION_SIZE), 0)

        else:
            best.x = -1

            for child in self.GetChildren():
                child_best = child.GetBestSize()
                best.x = max(best.x, child_best.x)

                if child_best.y != -1:
                    best.IncBy(0, child_best.y)

                count += 1

            if count > 1:
                best.IncBy(0, (count - 1) * self._art.GetMetric(RIBBON_ART_PANEL_Y_SEPARATION_SIZE))

        if best.x != -1:
            best.x += self._art.GetMetric(RIBBON_ART_PAGE_BORDER_LEFT_SIZE) + self._art.GetMetric(RIBBON_ART_PAGE_BORDER_RIGHT_SIZE)

        if best.y != -1:
            best.y += self._art.GetMetric(RIBBON_ART_PAGE_BORDER_TOP_SIZE) + self._art.GetMetric(RIBBON_ART_PAGE_BORDER_BOTTOM_SIZE)

        return best

[docs]    def GetDefaultBorder(self):

        return wx.BORDER_NONE

Navigation

  • index
  • modules |
  • Home |
  • Gallery |
  • Contents»
  • Module code »
  • ribbon.page


ribbon.panel

  • modules |
  • Home |
  • Gallery |
  • Contents»
  • Module code »
  • ribbon.panel

Source code for ribbon.panel

"""
Serves as a container for a group of (ribbon) controls.

Description
===========

A L{RibbonPage} will typically have panels for children, with the controls for that
page placed on the panels. A panel adds a border and label to a group of controls,
and can be minimised (either automatically to conserve space, or manually by the user).

Window Styles
=============

This class supports the following window styles:

================================= =========== =================================
Window Styles                     Hex Value   Description
================================= =========== =================================
``RIBBON_PANEL_DEFAULT_STYLE``            0x0 Defined as no other flags set.
``RIBBON_PANEL_NO_AUTO_MINIMISE``         0x1 Prevents the panel from automatically minimising to conserve screen space.
``RIBBON_PANEL_EXT_BUTTON``               0x8 Causes an extension button to be shown in the panel's chrome (if the bar in which it is contained has ``RIBBON_BAR_SHOW_PANEL_EXT_BUTTONS`` set). The behaviour of this button is application controlled, but typically will show an extended drop-down menu relating to the panel.
``RIBBON_PANEL_MINIMISE_BUTTON``         0x10 Causes a (de)minimise button to be shown in the panel's chrome (if the bar in which it is contained has the ``RIBBON_BAR_SHOW_PANEL_MINIMISE_BUTTONS`` style set). This flag is typically combined with ``RIBBON_PANEL_NO_AUTO_MINIMISE`` to make a panel which the user always has manual control over when it minimises.
================================= =========== =================================

See Also
========

L{RibbonPage}

"""

import wx

from control import RibbonControl
from art import *

[docs]def IsAncestorOf(ancestor, window):

    while window is not None:
        parent = window.GetParent()
        if parent == ancestor:
            return True
        else:
            window = parent

    return False

[docs]class RibbonPanel(RibbonControl):
    """ This is the main implementation of L{RibbonPanel}. """

[docs]    def __init__(self, parent, id=wx.ID_ANY, label="", minimised_icon=wx.NullBitmap,
                 pos=wx.DefaultPosition, size=wx.DefaultSize, agwStyle=RIBBON_PANEL_DEFAULT_STYLE,
                 name="RibbonPanel"):
        """
        Default class constructor.

        :param `parent`: Pointer to a parent window;
        :param `id`: Window identifier. If ``wx.ID_ANY``, will automatically create
         an identifier;
        :param `label`: Label of the new button;
        :param `minimised_icon`: the bitmap to be used in place of the panel children
         when it is minimised;
        :param `pos`: Window position. ``wx.DefaultPosition`` indicates that wxPython
         should generate a default position for the window;
        :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;
        :param `agwStyle`: the AGW-specific window style. This can be one of the following
         bits:

         ================================= =========== =================================
         Window Styles                     Hex Value   Description
         ================================= =========== =================================
         ``RIBBON_PANEL_DEFAULT_STYLE``            0x0 Defined as no other flags set.
         ``RIBBON_PANEL_NO_AUTO_MINIMISE``         0x1 Prevents the panel from automatically minimising to conserve screen space.
         ``RIBBON_PANEL_EXT_BUTTON``               0x8 Causes an extension button to be shown in the panel's chrome (if the bar in which it is contained has ``RIBBON_BAR_SHOW_PANEL_EXT_BUTTONS`` set). The behaviour of this button is application controlled, but typically will show an extended drop-down menu relating to the panel.
         ``RIBBON_PANEL_MINIMISE_BUTTON``         0x10 Causes a (de)minimise button to be shown in the panel's chrome (if the bar in which it is contained has the ``RIBBON_BAR_SHOW_PANEL_MINIMISE_BUTTONS`` style set). This flag is typically combined with ``RIBBON_PANEL_NO_AUTO_MINIMISE`` to make a panel which the user always has manual control over when it minimises.
         ================================= =========== =================================

        :param `name`: the window name.
        """

        RibbonControl.__init__(self, parent, id, pos, size, wx.BORDER_NONE, name=name)
        self.CommonInit(label, minimised_icon, agwStyle)

        self.Bind(wx.EVT_ENTER_WINDOW, self.OnMouseEnter)
        self.Bind(wx.EVT_ERASE_BACKGROUND, self.OnEraseBackground)
        self.Bind(wx.EVT_KILL_FOCUS, self.OnKillFocus)
        self.Bind(wx.EVT_LEAVE_WINDOW, self.OnMouseLeave)
        self.Bind(wx.EVT_LEFT_DOWN, self.OnMouseClick)
        self.Bind(wx.EVT_PAINT, self.OnPaint)
        self.Bind(wx.EVT_SIZE, self.OnSize)

    def __del__(self):

        if self._expanded_panel:
            self._expanded_panel._expanded_dummy = None
            self._expanded_panel.GetParent().Destroy()

[docs]    def SetArtProvider(self, art):
        """
        Set the art provider to be used.

        Normally called automatically by L{RibbonPage} when the panel is created, or the
        art provider changed on the page. The new art provider will be propagated to the
        children of the panel.

        Reimplemented from L{RibbonControl}.

        :param `art`: MISSING DESCRIPTION.

        """

        self._art = art
        for child in self.GetChildren():
            if isinstance(child, RibbonControl):
                child.SetArtProvider(art)

        if self._expanded_panel:
            self._expanded_panel.SetArtProvider(art)

[docs]    def CommonInit(self, label, icon, agwStyle):

        self.SetName(label)
        self.SetLabel(label)

        self._minimised_size = wx.Size(-1, -1) # Unknown / none
        self._smallest_unminimised_size = wx.Size(-1, -1) # Unknown / none
        self._preferred_expand_direction = wx.SOUTH
        self._expanded_dummy = None
        self._expanded_panel = None
        self._flags = agwStyle
        self._minimised_icon = icon
        self._minimised = False
        self._hovered = False

        if self._art == None:
            parent = self.GetParent()
            if isinstance(parent, RibbonControl):
                self._art = parent.GetArtProvider()

        self.SetAutoLayout(True)
        self.SetBackgroundStyle(wx.BG_STYLE_CUSTOM)
        self.SetMinSize(wx.Size(20, 20))

[docs]    def IsMinimised(self, at_size=None):
        """
        Query if the panel would be minimised at a given size.

        :param `at_size`: MISSING DESCRIPTION.

        """

        if at_size is None:
            return self.IsMinimised1()

        return self.IsMinimised2(wx.Size(*at_size))

[docs]    def IsMinimised1(self):
        """ Query if the panel is currently minimised. """

        return self._minimised

[docs]    def IsHovered(self):
        """
        Query is the mouse is currently hovered over the panel.

        :returns: ``True`` if the cursor is within the bounds of the panel (i.e.
         hovered over the panel or one of its children), ``False`` otherwise.
        """

        return self._hovered

[docs]    def OnMouseEnter(self, event):

        self.TestPositionForHover(event.GetPosition())

[docs]    def OnMouseEnterChild(self, event):

        pos = event.GetPosition()
        child = event.GetEventObject()

        if child:
            pos += child.GetPosition()
            self.TestPositionForHover(pos)

        event.Skip()

[docs]    def OnMouseLeave(self, event):

        self.TestPositionForHover(event.GetPosition())

[docs]    def OnMouseLeaveChild(self, event):

        pos = event.GetPosition()
        child = event.GetEventObject()

        if child:
            pos += child.GetPosition()
            self.TestPositionForHover(pos)

        event.Skip()

[docs]    def TestPositionForHover(self, pos):

        hovered = False

        if pos.x >= 0 and pos.y >= 0:
            size = self.GetSize()
            if pos.x < size.GetWidth() and pos.y < size.GetHeight():
                hovered = True

        if hovered != self._hovered:
            self._hovered = hovered
            self.Refresh(False)

[docs]    def AddChild(self, child):

        RibbonControl.AddChild(self, child)

        # Window enter / leave events count for only the window in question, not
        # for children of the window. The panel wants to be in the hovered state
        # whenever the mouse cursor is within its boundary, so the events need to
        # be attached to children too.
        child.Bind(wx.EVT_ENTER_WINDOW, self.OnMouseEnterChild)
        child.Bind(wx.EVT_LEAVE_WINDOW, self.OnMouseLeaveChild)

[docs]    def RemoveChild(self, child):

        child.Bind(wx.EVT_ENTER_WINDOW, None)
        child.Bind(wx.EVT_LEAVE_WINDOW, None)

        RibbonControl.RemoveChild(self, child)

[docs]    def OnSize(self, event):

        if self.GetAutoLayout():
            self.Layout()

        event.Skip()

[docs]    def DoSetSize(self, x, y, width, height, sizeFlags=wx.SIZE_AUTO):

        # At least on MSW, changing the size of a window will cause GetSize() to
        # report the new size, but a size event may not be handled immediately.
        # If self minimised check was performed in the OnSize handler, then
        # GetSize() could return a size much larger than the minimised size while
        # IsMinimised() returns True. This would then affect layout, as the panel
        # will refuse to grow any larger while in limbo between minimised and non.

        minimised = (self._flags & RIBBON_PANEL_NO_AUTO_MINIMISE) == 0 and self.IsMinimised(wx.Size(width, height))

        if minimised != self._minimised:
            self._minimised = minimised

            for child in self.GetChildren():
                child.Show(not minimised)

            self.Refresh()

        RibbonControl.DoSetSize(self, x, y, width, height, sizeFlags)

[docs]    def IsMinimised2(self, at_size):
        """
        Query if the panel would be minimised at a given size.

        :param `at_size`: MISSING DESCRIPTION.

        """

        if self.GetSizer():
            # we have no information on size change direction
            # so check both
            size = self.GetMinNotMinimisedSize()
            if size.x > at_size.x or size.y > at_size.y:
                return True

            return False

        if not self._minimised_size.IsFullySpecified():
            return False

        return (at_size.x <= self._minimised_size.x and \
                at_size.y <= self._minimised_size.y) or \
                at_size.x < self._smallest_unminimised_size.x or \
                at_size.y < self._smallest_unminimised_size.y

[docs]    def OnEraseBackground(self, event):

        # All painting done in main paint handler to minimise flicker
        pass

[docs]    def OnPaint(self, event):

        dc = wx.AutoBufferedPaintDC(self)

        if self._art != None:
            if self.IsMinimised():
                self._art.DrawMinimisedPanel(dc, self, wx.Rect(0, 0, *self.GetSize()), self._minimised_icon_resized)
            else:
                self._art.DrawPanelBackground(dc, self, wx.Rect(0, 0, *self.GetSize()))

[docs]    def IsSizingContinuous(self):

        # A panel never sizes continuously, even if all of its children can,
        # as it would appear out of place along side non-continuous panels.
        return False

[docs]    def DoGetNextSmallerSize(self, direction, relative_to):

        if self._expanded_panel != None:
            # Next size depends upon children, who are currently in the
            # expanded panel
            return self._expanded_panel.DoGetNextSmallerSize(direction, relative_to)

        if self._art is not None:

            dc = wx.ClientDC(self)
            child_relative, dummy = self._art.GetPanelClientSize(dc, self, wx.Size(*relative_to), None)
            smaller = wx.Size(-1, -1)
            minimise = False

            if self.GetSizer():

                # Get smallest non minimised size
                smaller = self.GetMinSize()

                # and adjust to child_relative for parent page
                if self._art.GetFlags() & RIBBON_BAR_FLOW_VERTICAL:
                     minimise = child_relative.y <= smaller.y
                     if smaller.x < child_relative.x:
                        smaller.x = child_relative.x
                else:
                    minimise = child_relative.x <= smaller.x
                    if smaller.y < child_relative.y:
                        smaller.y = child_relative.y

            elif len(self.GetChildren()) == 1:

                # Simple (and common) case of single ribbon child or Sizer
                ribbon_child = self.GetChildren()[0]
                if isinstance(ribbon_child, RibbonControl):
                    smaller = ribbon_child.GetNextSmallerSize(direction, child_relative)
                    minimise = smaller == child_relative

            if minimise:
                if self.CanAutoMinimise():
                    minimised = wx.Size(*self._minimised_size)

                    if direction == wx.HORIZONTAL:
                        minimised.SetHeight(relative_to.GetHeight())
                    elif direction == wx.VERTICAL:
                        minimised.SetWidth(relative_to.GetWidth())

                    return minimised

                else:
                    return relative_to

            elif smaller.IsFullySpecified(): # Use fallback if !(sizer/child = 1)
                return self._art.GetPanelSize(dc, self, wx.Size(*smaller), None)

        # Fallback: Decrease by 20% (or minimum size, whichever larger)
        current = wx.Size(*relative_to)
        minimum = wx.Size(*self.GetMinSize())

        if direction & wx.HORIZONTAL:
            current.x = (current.x * 4) / 5
            if current.x < minimum.x:
                current.x = minimum.x

        if direction & wx.VERTICAL:
            current.y = (current.y * 4) / 5
            if current.y < minimum.y:
                current.y = minimum.y

        return current

[docs]    def DoGetNextLargerSize(self, direction, relative_to):

        if self._expanded_panel != None:
            # Next size depends upon children, who are currently in the
            # expanded panel
            return self._expanded_panel.DoGetNextLargerSize(direction, relative_to)

        if self.IsMinimised(relative_to):
            current = wx.Size(*relative_to)
            min_size = wx.Size(*self.GetMinNotMinimisedSize())

            if direction == wx.HORIZONTAL:
                if min_size.x > current.x and min_size.y == current.y:
                    return min_size

            elif direction == wx.VERTICAL:
                if min_size.x == current.x and min_size.y > current.y:
                    return min_size

            elif direction == wx.BOTH:
                if min_size.x > current.x and min_size.y > current.y:
                    return min_size

        if self._art is not None:

            dc = wx.ClientDC(self)
            child_relative, dummy = self._art.GetPanelClientSize(dc, self, wx.Size(*relative_to), None)
            larger = wx.Size(-1, -1)

            if self.GetSizer():

                # We could just let the sizer expand in flow direction but see comment
                # in IsSizingContinuous()
                larger = self.GetPanelSizerBestSize()

                # and adjust for page in non flow direction
                if self._art.GetFlags() & RIBBON_BAR_FLOW_VERTICAL:
                     if larger.x != child_relative.x:
                        larger.x = child_relative.x

                elif larger.y != child_relative.y:
                    larger.y = child_relative.y

            elif len(self.GetChildren()) == 1:

                # Simple (and common) case of single ribbon child
                ribbon_child = self.GetChildren()[0]
                if isinstance(ribbon_child, RibbonControl):
                    larger = ribbon_child.GetNextLargerSize(direction, child_relative)

            if larger.IsFullySpecified(): # Use fallback if !(sizer/child = 1)
                if larger == child_relative:
                    return relative_to
                else:
                    return self._art.GetPanelSize(dc, self, wx.Size(*larger), None)

        # Fallback: Increase by 25% (equal to a prior or subsequent 20% decrease)
        # Note that due to rounding errors, this increase may not exactly equal a
        # matching decrease - an ideal solution would not have these errors, but
        # avoiding them is non-trivial unless an increase is by 100% rather than
        # a fractional amount. This would then be non-ideal as the resizes happen
        # at very large intervals.
        current = wx.Size(*relative_to)

        if direction & wx.HORIZONTAL:
            current.x = (current.x * 5 + 3) / 4

        if direction & wx.VERTICAL:
            current.y = (current.y * 5 + 3) / 4

        return current

[docs]    def CanAutoMinimise(self):
        """ Query if the panel can automatically minimise itself at small sizes. """

        return (self._flags & RIBBON_PANEL_NO_AUTO_MINIMISE) == 0 \
               and self._minimised_size.IsFullySpecified()

[docs]    def GetMinSize(self):

        if self._expanded_panel != None:
            # Minimum size depends upon children, who are currently in the
            # expanded panel
            return self._expanded_panel.GetMinSize()

        if self.CanAutoMinimise():
            return wx.Size(*self._minimised_size)
        else:
            return self.GetMinNotMinimisedSize()

[docs]    def GetMinNotMinimisedSize(self):

        # Ask sizer if present
        if self.GetSizer():
            dc = wx.ClientDC(self)
            return self._art.GetPanelSize(dc, self, wx.Size(*self.GetPanelSizerMinSize()), None)

        # Common case of no sizer and single child taking up the entire panel
        elif len(self.GetChildren()) == 1:
            child = self.GetChildren()[0]
            dc = wx.ClientDC(self)
            return self._art.GetPanelSize(dc, self, wx.Size(*child.GetMinSize()), None)

        return wx.Size(*RibbonControl.GetMinSize(self))

[docs]    def GetPanelSizerMinSize(self):

        # Called from Realize() to set self._smallest_unminimised_size and from other
        # functions to get the minimum size.
        # The panel will be invisible when minimised and sizer calcs will be 0
        # Uses self._smallest_unminimised_size in preference to self.GetSizer().CalcMin()
        # to eliminate flicker.

        # Check if is visible and not previously calculated
        if self.IsShown() and not self._smallest_unminimised_size.IsFullySpecified():
             return self.GetSizer().CalcMin()

        # else use previously calculated self._smallest_unminimised_size
        dc = wx.ClientDC(self)
        return self._art.GetPanelClientSize(dc, self, wx.Size(*self._smallest_unminimised_size), None)[0]

[docs]    def GetPanelSizerBestSize(self):

        size = self.GetPanelSizerMinSize()
        # TODO allow panel to increase its size beyond minimum size
        # by steps similarly to ribbon control panels (preferred for aesthetics)
        # or continuously.
        return size

[docs]    def DoGetBestSize(self):

        # Ask sizer if present
        if self.GetSizer():
            dc = wx.ClientDC(self)
            return self._art.GetPanelSize(dc, self, wx.Size(*self.GetPanelSizerBestSize()), None)

        # Common case of no sizer and single child taking up the entire panel
        elif len(self.GetChildren()) == 1:
            child = self.GetChildren()[0]
            dc = wx.ClientDC(self)
            return self._art.GetPanelSize(dc, self, wx.Size(*child.GetBestSize()), None)

        return wx.Size(*RibbonControl.DoGetBestSize(self))

[docs]    def Realize(self):
        """
        Realize all children of the panel.

        Reimplemented from L{RibbonControl}.
        """

        status = True
        children = self.GetChildren()

        for child in children:
            if not isinstance(child, RibbonControl):
                continue

            if not child.Realize():
                status = False

        minimum_children_size = wx.Size(0, 0)

        # Ask sizer if there is one present
        if self.GetSizer():
            minimum_children_size = wx.Size(*self.GetPanelSizerMinSize())
        elif len(children) == 1:
            minimum_children_size = wx.Size(*children[0].GetMinSize())

        if self._art != None:
            temp_dc = wx.ClientDC(self)
            self._smallest_unminimised_size = self._art.GetPanelSize(temp_dc, self, wx.Size(*minimum_children_size), None)

            panel_min_size = self.GetMinNotMinimisedSize()
            self._minimised_size, bitmap_size, self._preferred_expand_direction = self._art.GetMinimisedPanelMinimumSize(temp_dc, self, 1, 1)

            if self._minimised_icon.IsOk() and self._minimised_icon.GetSize() != bitmap_size:
                img = self._minimised_icon.ConvertToImage()
                img.Rescale(bitmap_size.GetWidth(), bitmap_size.GetHeight(), wx.IMAGE_QUALITY_HIGH)
                self._minimised_icon_resized = wx.BitmapFromImage(img)
            else:
                self._minimised_icon_resized = self._minimised_icon

            if self._minimised_size.x > panel_min_size.x and self._minimised_size.y > panel_min_size.y:
                # No point in having a minimised size which is larger than the
                # minimum size which the children can go to.
                self._minimised_size = wx.Size(-1, -1)
            else:
                if self._art.GetFlags() & RIBBON_BAR_FLOW_VERTICAL:
                    self._minimised_size.x = panel_min_size.x
                else:
                    self._minimised_size.y = panel_min_size.y

        else:
            self._minimised_size = wx.Size(-1, -1)

        return self.Layout() and status

[docs]    def Layout(self):

        if self.IsMinimised():
            # Children are all invisible when minimised
            return True

        dc = wx.ClientDC(self)
        size, position = self._art.GetPanelClientSize(dc, self, wx.Size(*self.GetSize()), wx.Point())

        children = self.GetChildren()

        if self.GetSizer():
            self.GetSizer().SetDimension(position.x, position.y, size.x, size.y) # SetSize and Layout()
        elif len(children) == 1:
           # Common case of no sizer and single child taking up the entire panel
             children[0].SetDimensions(position.x, position.y, size.GetWidth(), size.GetHeight())

        return True

[docs]    def OnMouseClick(self, event):

        if self.IsMinimised():
            if self._expanded_panel != None:
                self.HideExpanded()
            else:
                self.ShowExpanded()

[docs]    def GetExpandedDummy(self):
        """
        Get the dummy panel of an expanded panel.

        :note: This should be called on an expanded panel to get the dummy associated
         with it - it will return ``None`` when called on the dummy itself.

        :see: L{ShowExpanded}, L{GetExpandedPanel}
        """

        return self._expanded_dummy

[docs]    def GetExpandedPanel(self):
        """
        Get the expanded panel of a dummy panel.

        :note: This should be called on a dummy panel to get the expanded panel
         associated with it - it will return ``None`` when called on the expanded panel
         itself.

        :see: L{ShowExpanded}, L{GetExpandedDummy}
        """

        return self._expanded_panel

[docs]    def ShowExpanded(self):
        """
        Show the panel externally expanded.

        When a panel is minimised, it can be shown full-size in a pop-out window, which
        is refered to as being (externally) expanded.

        :returns: ``True`` if the panel was expanded, ``False`` if it was not (possibly
         due to it not being minimised, or already being expanded).

        :note: When a panel is expanded, there exist two panels - the original panel
         (which is refered to as the dummy panel) and the expanded panel. The original
         is termed a dummy as it sits in the ribbon bar doing nothing, while the expanded
         panel holds the panel children.

        :see: L{HideExpanded}, L{GetExpandedPanel}
        """

        if not self.IsMinimised():
            return False

        if self._expanded_dummy != None or self._expanded_panel != None:
            return False

        size = self.GetBestSize()
        pos = self.GetExpandedPosition(wx.RectPS(self.GetScreenPosition(), self.GetSize()), size, self._preferred_expand_direction).GetTopLeft()

        # Need a top-level frame to contain the expanded panel
        container = wx.Frame(None, wx.ID_ANY, self.GetLabel(), pos, size, wx.FRAME_NO_TASKBAR | wx.BORDER_NONE)

        self._expanded_panel = RibbonPanel(container, wx.ID_ANY, self.GetLabel(), self._minimised_icon, wx.Point(0, 0), size, self._flags)
        self._expanded_panel.SetArtProvider(self._art)
        self._expanded_panel._expanded_dummy = self

        # Move all children to the new panel.
        # Conceptually it might be simpler to reparent self entire panel to the
        # container and create a new panel to sit in its place while expanded.
        # This approach has a problem though - when the panel is reinserted into
        # its original parent, it'll be at a different position in the child list
        # and thus assume a new position.
        # NB: Children iterators not used as behaviour is not well defined
        # when iterating over a container which is being emptied

        for child in self.GetChildren():
            child.Reparent(self._expanded_panel)
            child.Show()

        # Move sizer to new panel
        if self.GetSizer():
            sizer = self.GetSizer()
            self.SetSizer(None, False)
            self._expanded_panel.SetSizer(sizer)

        self._expanded_panel.Realize()
        self.Refresh()
        container.Show()
        self._expanded_panel.SetFocus()

        return True

[docs]    def ShouldSendEventToDummy(self, event):

        # For an expanded panel, filter events between being sent up to the
        # floating top level window or to the dummy panel sitting in the ribbon
        # bar.

        # Child focus events should not be redirected, as the child would not be a
        # child of the window the event is redirected to. All other command events
        # seem to be suitable for redirecting.
        return event.IsCommandEvent() and event.GetEventType() != wx.wxEVT_CHILD_FOCUS

[docs]    def TryAfter(self, event):

        if self._expanded_dummy and self.ShouldSendEventToDummy(event):
            propagateOnce = wx.PropagateOnce(event)
            return self._expanded_dummy.GetEventHandler().ProcessEvent(event)
        else:
            return RibbonControl.TryAfter(self, event)

[docs]    def OnKillFocus(self, event):

        if self._expanded_dummy:
            receiver = event.GetWindow()

            if IsAncestorOf(self, receiver):
                self._child_with_focus = receiver
                receiver.Bind(wx.EVT_KILL_FOCUS, self.OnChildKillFocus)

            elif receiver is None or receiver != self._expanded_dummy:
                self.HideExpanded()

[docs]    def OnChildKillFocus(self, event):

        if self._child_with_focus == None:
            return # Should never happen, but a check can't hurt

        self._child_with_focus.Bind(wx.EVT_KILL_FOCUS, None)
        self._child_with_focus = None

        receiver = event.GetWindow()
        if receiver == self or IsAncestorOf(self, receiver):
            self._child_with_focus = receiver
            receiver.Bind(wx.EVT_KILL_FOCUS, self.OnChildKillFocus)
            event.Skip()

        elif receiver == None or receiver != self._expanded_dummy:
            self.HideExpanded()
            # Do not skip event, as the panel has been de-expanded, causing the
            # child with focus to be reparented (and hidden). If the event
            # continues propogation then bad things happen.

        else:
            event.Skip()

[docs]    def HideExpanded(self):
        """
        Hide the panel's external expansion.

        :returns: ``True`` if the panel was un-expanded, ``False`` if it was not
         (normally due to it not being expanded in the first place).

        :see: L{HideExpanded}, L{GetExpandedPanel}
        """

        if self._expanded_dummy == None:
            if self._expanded_panel:
                return self._expanded_panel.HideExpanded()
            else:
                return False

        # Move children back to original panel
        # NB: Children iterators not used as behaviour is not well defined
        # when iterating over a container which is being emptied
        for child in self.GetChildren():
            child.Reparent(self._expanded_dummy)
            child.Hide()

        # TODO: Move sizer back
        self._expanded_dummy._expanded_panel = None
        self._expanded_dummy.Realize()
        self._expanded_dummy.Refresh()
        parent = self.GetParent()
        self.Destroy()
        parent.Destroy()

        return True

[docs]    def GetExpandedPosition(self, panel, expanded_size, direction):

        # Strategy:
        # 1) Determine primary position based on requested direction
        # 2) Move the position so that it sits entirely within a display
        #    (for single monitor systems, this moves it into the display region,
        #     but for multiple monitors, it does so without splitting it over
        #     more than one display)
        # 2.1) Move in the primary axis
        # 2.2) Move in the secondary axis

        primary_x = False
        secondary_x = secondary_y = 0
        pos = wx.Point()

        if direction == wx.NORTH:
            pos.x = panel.GetX() + (panel.GetWidth() - expanded_size.GetWidth()) / 2
            pos.y = panel.GetY() - expanded_size.GetHeight()
            primary_x = True
            secondary_y = 1

        elif direction == wx.EAST:
            pos.x = panel.GetRight()
            pos.y = panel.GetY() + (panel.GetHeight() - expanded_size.GetHeight()) / 2
            secondary_x = -1

        elif direction == wx.SOUTH:
            pos.x = panel.GetX() + (panel.GetWidth() - expanded_size.GetWidth()) / 2
            pos.y = panel.GetBottom()
            primary_x = True
            secondary_y = -1

        else:
            pos.x = panel.GetX() - expanded_size.GetWidth()
            pos.y = panel.GetY() + (panel.GetHeight() - expanded_size.GetHeight()) / 2
            secondary_x = 1

        expanded = wx.RectPS(pos, expanded_size)
        best = wx.Rect(*expanded)
        best_distance = 10000

        display_n = wx.Display.GetCount()

        for display_i in xrange(display_n):
            display = wx.Display(display_i).GetGeometry()
            if display.ContainsRect(expanded):
                return expanded

            elif display.Intersects(expanded):
                new_rect = wx.Rect(*expanded)
                distance = 0

                if primary_x:
                    if expanded.GetRight() > display.GetRight():
                        distance = expanded.GetRight() - display.GetRight()
                        new_rect.x -= distance

                    elif expanded.GetLeft() < display.GetLeft():
                        distance = display.GetLeft() - expanded.GetLeft()
                        new_rect.x += distance

                else:
                    if expanded.GetBottom() > display.GetBottom():
                        distance = expanded.GetBottom() - display.GetBottom()
                        new_rect.y -= distance

                    elif expanded.GetTop() < display.GetTop():
                        distance = display.GetTop() - expanded.GetTop()
                        new_rect.y += distance

                if not display.Contains(new_rect):
                    # Tried moving in primary axis, but failed.
                    # Hence try moving in the secondary axis.
                    dx = secondary_x * (panel.GetWidth() + expanded_size.GetWidth())
                    dy = secondary_y * (panel.GetHeight() + expanded_size.GetHeight())
                    new_rect.x += dx
                    new_rect.y += dy

                    # Squaring makes secondary moves more expensive (and also
                    # prevents a negative cost)
                    distance += dx * dx + dy * dy

                if display.Contains(new_rect) and distance < best_distance:
                    best = new_rect
                    best_distance = distance

        return best

[docs]    def GetMinimisedIcon(self):
        """
        Get the bitmap to be used in place of the panel children when it is minimised.
        """

        return self._minimised_icon

[docs]    def GetDefaultBorder(self):

        return wx.BORDER_NONE

Navigation

  • index
  • modules |
  • Home |
  • Gallery |
  • Contents»
  • Module code »
  • ribbon.panel


ribbon.toolbar

  • modules |
  • Home |
  • Gallery |
  • Contents»
  • Module code »
  • ribbon.toolbar

Source code for ribbon.toolbar

"""
A ribbon tool bar is similar to a traditional toolbar which has no labels.

Description
===========

It contains one or more tool groups, each of which contains one or more tools.
Each tool is represented by a (generally small, i.e. 16x15) bitmap.

Events Processing
=================

This class processes the following events:

====================================== ======================================
Event Name                             Description
====================================== ======================================
``EVT_RIBBONTOOLBAR_CLICKED``          Triggered when the normal (non-dropdown) region of a tool on the tool bar is clicked.
``EVT_RIBBONTOOLBAR_DROPDOWN_CLICKED`` Triggered when the dropdown region of a tool on the tool bar is clicked. L{RibbonToolBarEvent.PopupMenu} should be called by the event handler if it wants to display a popup menu (which is what most dropdown tools should be doing).
====================================== ======================================

"""

import wx

from control import RibbonControl
from art import *

wxEVT_COMMAND_RIBBONTOOL_CLICKED = wx.NewEventType()
wxEVT_COMMAND_RIBBONTOOL_DROPDOWN_CLICKED = wx.NewEventType()

EVT_RIBBONTOOLBAR_CLICKED = wx.PyEventBinder(wxEVT_COMMAND_RIBBONTOOL_CLICKED, 1)
EVT_RIBBONTOOLBAR_DROPDOWN_CLICKED = wx.PyEventBinder(wxEVT_COMMAND_RIBBONTOOL_DROPDOWN_CLICKED, 1)

[docs]def GetSizeInOrientation(size, orientation):

    if orientation == wx.HORIZONTAL:
        return size.GetWidth()

    if orientation == wx.VERTICAL:
        return size.GetHeight()

    if orientation == wx.BOTH:
        return size.GetWidth() * size.GetHeight()

    return 0

[docs]class RibbonToolBarEvent(wx.PyCommandEvent):

[docs]    def __init__(self, command_type=None, win_id=0, bar=None):

        wx.PyCommandEvent.__init__(self, command_type, win_id)
        self._bar = bar

[docs]    def GetBar(self):

        return self._bar

[docs]    def SetBar(self, bar):

        self._bar = bar

[docs]    def PopupMenu(self, menu):

        pos = wx.Point()

        if self._bar._active_tool:
            # Find the group which contains the tool
            group_count = len(self._bar._groups)
            tobreak = False

            for g in xrange(group_count):
                group = self._bar._groups[g]
                tool_count = len(group.tools)

                for t in xrange(tool_count):
                    tool = group.tools[t]
                    if tool == self._bar._active_tool:
                        pos = wx.Point(*group.position)
                        pos += tool.position
                        pos.y += tool.size.GetHeight()
                        g = group_count
                        tobreak = True
                        break

                if tobreak:
                    break

        return self._bar.PopupMenu(menu, pos)

[docs]class RibbonToolBarToolBase(object):

[docs]    def __init__(self):

        self.help_string = ""
        self.bitmap = wx.NullBitmap
        self.bitmap_disabled = wx.NullBitmap
        self.dropdown = wx.Rect()
        self.position = wx.Point()
        self.size = wx.Size()
        self.client_data = None
        self.id = -1
        self.kind = RIBBON_BUTTON_NORMAL
        self.state = None

[docs]class RibbonToolBarToolGroup(object):

[docs]    def __init__(self):

        # To identify the group as a wxRibbonToolBarToolBase*
        self.dummy_tool = None

        self.tools = []
        self.position = wx.Point()
        self.size = wx.Size()

[docs]class RibbonToolBar(RibbonControl):

[docs]    def __init__(self, parent, id=wx.ID_ANY, pos=wx.DefaultPosition, size=wx.DefaultSize, style=0,
                 name="RibbonToolbar"):

        """
        Default class constructor.

        :param `parent`: Pointer to a parent window;
        :param `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;
        :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;
        :param `style`: Window style;
        :param `name`: the window name.

        """

        RibbonControl.__init__(self, parent, id, pos, size, wx.BORDER_NONE, name=name)

        self.Bind(wx.EVT_ENTER_WINDOW, self.OnMouseEnter)
        self.Bind(wx.EVT_ERASE_BACKGROUND, self.OnEraseBackground)
        self.Bind(wx.EVT_LEAVE_WINDOW, self.OnMouseLeave)
        self.Bind(wx.EVT_LEFT_DOWN, self.OnMouseDown)
        self.Bind(wx.EVT_LEFT_UP, self.OnMouseUp)
        self.Bind(wx.EVT_MOTION, self.OnMouseMove)
        self.Bind(wx.EVT_PAINT, self.OnPaint)
        self.Bind(wx.EVT_SIZE, self.OnSize)

        self.CommonInit(style)

[docs]    def CommonInit(self, style):

        self._groups = []

        self.AppendGroup()
        self._hover_tool = None
        self._active_tool = None
        self._nrows_min = 1
        self._nrows_max = 1
        self._sizes = [wx.Size(0, 0)]
        self.SetBackgroundStyle(wx.BG_STYLE_CUSTOM)

[docs]    def AddSimpleTool(self, tool_id, bitmap, help_string, kind=RIBBON_BUTTON_NORMAL):
        """
        Add a tool to the tool bar (simple version).

        :param `tool_id`: ID of the new tool (used for event callbacks);
        :param `bitmap`: Large bitmap of the new button. Must be the same size as all
         other large bitmaps used on the button bar;
        :param `help_string`: The UI help string to associate with the new button;
        :param `kind`: The kind of button to add.

        :see: L{AddDropdownTool}, L{AddHybridTool}, L{AddTool}

        """

        return self.AddTool(tool_id, bitmap, wx.NullBitmap, help_string, kind, None)

[docs]    def AddDropdownTool(self, tool_id, bitmap, help_string=""):
        """
        Add a dropdown tool to the tool bar (simple version).

        :param `tool_id`: ID of the new tool (used for event callbacks);
        :param `bitmap`: Large bitmap of the new button. Must be the same size as all
         other large bitmaps used on the button bar;
        :param `help_string`: The UI help string to associate with the new button.

        :see: L{AddTool}
        """

        return self.AddTool(tool_id, bitmap, wx.NullBitmap, help_string, RIBBON_BUTTON_DROPDOWN, None)

[docs]    def AddHybridTool(self,  tool_id, bitmap, help_string=""):
        """
        Add a hybrid tool to the tool bar (simple version).

        :param `tool_id`: ID of the new tool (used for event callbacks);
        :param `bitmap`: Large bitmap of the new button. Must be the same size as all
         other large bitmaps used on the button bar;
        :param `help_string`: The UI help string to associate with the new button.

        :see: L{AddTool}
        """

        return self.AddTool(tool_id, bitmap, wx.NullBitmap, help_string, RIBBON_BUTTON_HYBRID, None)

[docs]    def AddTool(self, tool_id, bitmap, bitmap_disabled=wx.NullBitmap, help_string="", kind=RIBBON_BUTTON_NORMAL, client_data=None):
        """
        Add a tool to the tool bar.

        :param `tool_id`: ID of the new tool (used for event callbacks);
        :param `bitmap`: Bitmap to use as the foreground for the new tool. Does not
         have to be the same size as other tool bitmaps, but should be similar as
         otherwise it will look visually odd;
        :param `bitmap_disabled`: Bitmap to use when the tool is disabled. If left
         as `wx.NullBitmap`, then a bitmap will be automatically generated from `bitmap`;
        :param `help_string`: The UI help string to associate with the new tool;
        :param `kind`: The kind of tool to add;
        :param `client_data`: Client data to associate with the new tool.

        :returns: An opaque pointer which can be used only with other tool bar methods.

        :see: L{AddDropdownTool}, L{AddHybridTool}, L{AddSeparator}
        """

        if not bitmap.IsOk():
            raise Exception("Exception")

        tool = RibbonToolBarToolBase()
        tool.id = tool_id
        tool.bitmap = bitmap

        if bitmap_disabled.IsOk():
            if bitmap.GetSize() != bitmap_disabled.GetSize():
                raise Exception("Exception")

            tool.bitmap_disabled = bitmap_disabled
        else:
            tool.bitmap_disabled = self.MakeDisabledBitmap(bitmap)

        tool.help_string = help_string
        tool.kind = kind
        tool.client_data = client_data
        tool.position = wx.Point(0, 0)
        tool.size = wx.Size(0, 0)
        tool.state = 0

        self._groups[-1].tools.append(tool)
        return tool

[docs]    def AddSeparator(self):
        """
        Add a separator to the tool bar.

        Separators are used to separate tools into groups. As such, a separator is not
        explicity drawn, but is visually seen as the gap between tool groups.

        """

        if not self._groups[-1].tools:
            return None

        self.AppendGroup()
        return self._groups[-1].dummy_tool

[docs]    def MakeDisabledBitmap(self, original):

        img = original.ConvertToImage()
        return wx.BitmapFromImage(img.ConvertToGreyscale())

[docs]    def AppendGroup(self):

        group = RibbonToolBarToolGroup()
        group.position = wx.Point(0, 0)
        group.size = wx.Size(0, 0)
        self._groups.append(group)

[docs]    def IsSizingContinuous(self):

        return False

[docs]    def DoGetNextSmallerSize(self, direction, relative_to):

        result = wx.Size(*relative_to)
        area = 0
        tobreak = False

        for nrows in xrange(self._nrows_max, self._nrows_min-1, -1):

            size = wx.Size(*self._sizes[nrows - self._nrows_min])
            original = wx.Size(*size)

            if direction == wx.HORIZONTAL:
                if size.GetWidth() < relative_to.GetWidth() and size.GetHeight() <= relative_to.GetHeight():
                    size.SetHeight(relative_to.GetHeight())
                    tobreak = True

            elif direction == wx.VERTICAL:
                if size.GetWidth() <= relative_to.GetWidth() and size.GetHeight() < relative_to.GetHeight():
                    size.SetWidth(relative_to.GetWidth())
                    tobreak = True

            elif direction == wx.BOTH:
                if size.GetWidth() < relative_to.GetWidth() and size.GetHeight() < relative_to.GetHeight():
                    pass

            if GetSizeInOrientation(original, direction) > area:
                result = wx.Size(*size)
                area = GetSizeInOrientation(original, direction)
                if tobreak:
                    break

        return result

[docs]    def DoGetNextLargerSize(self, direction, relative_to):

        # Pick the smallest of our sizes which are larger than the given size
        result = wx.Size(*relative_to)
        area = 10000
        tobreak = False

        for nrows in xrange(self._nrows_min, self._nrows_max+1):

            size = wx.Size(*self._sizes[nrows - self._nrows_min])
            original = wx.Size(*size)

            if direction == wx.HORIZONTAL:
                if size.GetWidth() > relative_to.GetWidth() and size.GetHeight() <= relative_to.GetHeight():
                    size.SetHeight(relative_to.GetHeight())
                    tobreak = True

            elif direction == wx.VERTICAL:
                if size.GetWidth() <= relative_to.GetWidth() and size.GetHeight() > relative_to.GetHeight():
                    size.SetWidth(relative_to.GetWidth())
                    tobreak = True

            elif direction == wx.BOTH:
                if size.GetWidth() > relative_to.GetWidth() and size.GetHeight() > relative_to.GetHeight():
                    tobreak = True

            if GetSizeInOrientation(original, direction) < area:
                result = wx.Size(*size)
                area = GetSizeInOrientation(original, direction)
                if tobreak:
                    break

        return result

[docs]    def SetRows(self, nMin, nMax):
        """
        Set the number of rows to distribute tool groups over.

        Tool groups can be distributed over a variable number of rows. The way in which
        groups are assigned to rows is not specificed, and the order of groups may
        change, but they will be distributed in such a way as to minimise the overall
        size of the tool bar.

        :param `nMin`: The minimum number of rows to use;
        :param `nMax`: The maximum number of rows to use (defaults to `nMin`).

        """

        if nMax == -1:
            nMax = nMin

        if nMin < 1:
            raise Exception("Exception")
        if nMin > nMax:
            raise Exception("Exception")

        self._nrows_min = nMin
        self._nrows_max = nMax

        self._sizes = []
        self._sizes = [wx.Size(0, 0) for i in xrange(self._nrows_min, self._nrows_max + 1)]

        self.Realize()

[docs]    def Realize(self):

        if self._art == None:
            return False

        # Calculate the size of each group and the position/size of each tool
        temp_dc = wx.MemoryDC()
        group_count = len(self._groups)

        for group in self._groups:

            prev = None
            tool_count = len(group.tools)
            tallest = 0

            for t, tool in enumerate(group.tools):

                tool.size, tool.dropdown = self._art.GetToolSize(temp_dc, self, tool.bitmap.GetSize(), tool.kind, t==0, t==(tool_count-1))
                tool.state = tool.state & ~RIBBON_TOOLBAR_TOOL_DISABLED
                if t == 0:
                    tool.state |= RIBBON_TOOLBAR_TOOL_FIRST
                if t == tool_count - 1:
                    tool.state |= RIBBON_TOOLBAR_TOOL_LAST
                if tool.size.GetHeight() > tallest:
                    tallest = tool.size.GetHeight()
                if prev:
                    tool.position = wx.Point(*prev.position)
                    tool.position.x += prev.size.x
                else:
                    tool.position = wx.Point(0, 0)

                prev = tool

            if tool_count == 0:
                group.size = wx.Size(0, 0)
            else:
                group.size = wx.Size(prev.position.x + prev.size.x, tallest)
                for tool in group.tools:
                    tool.size.SetHeight(tallest)

        # Calculate the minimum size for each possible number of rows
        sep = self._art.GetMetric(RIBBON_ART_TOOL_GROUP_SEPARATION_SIZE)
        smallest_area = 10000
        row_sizes = [wx.Size(0, 0) for i in xrange(self._nrows_max)]
        major_axis = ((self._art.GetFlags() & RIBBON_BAR_FLOW_VERTICAL) and [wx.VERTICAL] or [wx.HORIZONTAL])[0]
        self.SetMinSize(wx.Size(0, 0))

        for nrows in xrange(self._nrows_min, self._nrows_max+1):

            for r in xrange(nrows):
                row_sizes[r] = wx.Size(0, 0)

            for g in xrange(group_count):

                group = self._groups[g]
                shortest_row = 0

                for r in xrange(1, nrows):
                    if row_sizes[r].GetWidth() < row_sizes[shortest_row].GetWidth():
                        shortest_row = r

                row_sizes[shortest_row].x += group.size.x + sep
                if group.size.y > row_sizes[shortest_row].y:
                    row_sizes[shortest_row].y = group.size.y

            size = wx.Size(0, 0)

            for r in xrange(nrows):
                if row_sizes[r].GetWidth() != 0:
                    row_sizes[r].DecBy(sep, 0)
                if row_sizes[r].GetWidth() > size.GetWidth():
                    size.SetWidth(row_sizes[r].GetWidth())

                size.IncBy(0, row_sizes[r].y)

            self._sizes[nrows - self._nrows_min] = size

            if GetSizeInOrientation(size, major_axis) < smallest_area:
                self.SetMinSize(size)
                smallest_area = GetSizeInOrientation(size, major_axis)

        # Position the groups
        dummy_event = wx.SizeEvent(self.GetSize())
        self.OnSize(dummy_event)

        return True

[docs]    def OnSize(self, event):

        if self._art == None:
            return

        # Choose row count with largest possible area
        size = event.GetSize()
        row_count = self._nrows_max
        major_axis = (self._art.GetFlags() & RIBBON_BAR_FLOW_VERTICAL and [wx.VERTICAL] or [wx.HORIZONTAL])[0]

        if self._nrows_max != self._nrows_min:
            area = 0
            for i in xrange(self._nrows_max - self._nrows_min + 1):
                if self._sizes[i].x <= size.x and self._sizes[i].y <= size.y and \
                   GetSizeInOrientation(self._sizes[i], major_axis) > area:
                    area = GetSizeInOrientation(self._sizes[i], major_axis)
                    row_count = self._nrows_min + i

        # Assign groups to rows and calculate row widths
        row_sizes = [wx.Size(0, 0) for i in xrange(row_count)]
        sep = self._art.GetMetric(RIBBON_ART_TOOL_GROUP_SEPARATION_SIZE)

        group_count = len(self._groups)
        for group in self._groups:
            shortest_row = 0
            for r in xrange(1, row_count):
                if row_sizes[r].GetWidth() < row_sizes[shortest_row].GetWidth():
                    shortest_row = r

            group.position = wx.Point(row_sizes[shortest_row].x, shortest_row)
            row_sizes[shortest_row].x += group.size.x + sep
            if group.size.y > row_sizes[shortest_row].y:
                row_sizes[shortest_row].y = group.size.y

        # Calculate row positions
        total_height = 0
        for r in xrange(row_count):
            total_height += row_sizes[r].GetHeight()

        rowsep = (size.GetHeight() - total_height) / (row_count + 1)
        rowypos = [0]*row_count
        rowypos[0] = rowsep
        for r in xrange(1, row_count):
            rowypos[r] = rowypos[r - 1] + row_sizes[r - 1].GetHeight() + rowsep

        # Set group y positions
        for group in self._groups:
            group.position.y = rowypos[group.position.y]

[docs]    def DoGetBestSize(self):

        return self.GetMinSize()

[docs]    def OnEraseBackground(self, event):

        # All painting done in main paint handler to minimise flicker
        pass

[docs]    def OnPaint(self, event):

        dc = wx.AutoBufferedPaintDC(self)

        if self._art == None:
            return

        self._art.DrawToolBarBackground(dc, self, wx.Rect(0, 0, *self.GetSize()))

        for group in self._groups:
            tool_count = len(group.tools)

            if tool_count != 0:
                self._art.DrawToolGroupBackground(dc, self, wx.RectPS(group.position, group.size))

                for tool in group.tools:
                    rect = wx.RectPS(group.position + tool.position, tool.size)
                    self._art.DrawTool(dc, self, rect, tool.bitmap, tool.kind, tool.state)

[docs]    def OnMouseMove(self, event):

        pos = event.GetPosition()
        new_hover = None

        for group in self._groups:

            if group.position.x <= pos.x and pos.x < group.position.x + group.size.x \
               and group.position.y <= pos.y and pos.y < group.position.y + group.size.y:
                pos -= group.position

                for tool in group.tools:
                    if tool.position.x <= pos.x and pos.x < tool.position.x + tool.size.x \
                       and tool.position.y <= pos.y and pos.y < tool.position.y + tool.size.y:
                        pos -= tool.position
                        new_hover = tool
                        break
                break

        if new_hover and new_hover != self._hover_tool:
            self.SetToolTipString(new_hover.help_string)
        elif self.GetToolTip() and new_hover != self._hover_tool:
            self.SetToolTipString("")

        if new_hover != self._hover_tool:
            if self._hover_tool:
                self._hover_tool.state &= ~(RIBBON_TOOLBAR_TOOL_HOVER_MASK | RIBBON_TOOLBAR_TOOL_ACTIVE_MASK)

            self._hover_tool = new_hover

            if new_hover:
                what = RIBBON_TOOLBAR_TOOL_NORMAL_HOVERED
                if new_hover.dropdown.Contains(pos):
                    what = RIBBON_TOOLBAR_TOOL_DROPDOWN_HOVERED

                new_hover.state |= what

                if new_hover == self._active_tool:

                    new_hover.state &= ~RIBBON_TOOLBAR_TOOL_ACTIVE_MASK
                    new_hover.state |= (what << 2)

            self.Refresh(False)

        elif self._hover_tool and self._hover_tool.kind == RIBBON_BUTTON_HYBRID:
            newstate = self._hover_tool.state & ~RIBBON_TOOLBAR_TOOL_HOVER_MASK
            what = RIBBON_TOOLBAR_TOOL_NORMAL_HOVERED

            if self._hover_tool.dropdown.Contains(pos):
                what = RIBBON_TOOLBAR_TOOL_DROPDOWN_HOVERED

            newstate |= what

            if newstate != self._hover_tool.state:
                self._hover_tool.state = newstate
                if self._hover_tool == self._active_tool:
                    self._hover_tool.state &= ~RIBBON_TOOLBAR_TOOL_ACTIVE_MASK
                    self._hover_tool.state |= (what << 2)

                self.Refresh(False)

[docs]    def OnMouseDown(self, event):

        self.OnMouseMove(event)

        if self._hover_tool:
            self._active_tool = self._hover_tool
            self._active_tool.state |= (self._active_tool.state & RIBBON_TOOLBAR_TOOL_HOVER_MASK) << 2
            self.Refresh(False)

[docs]    def OnMouseLeave(self, event):

        if self._hover_tool:
            self._hover_tool.state &= ~RIBBON_TOOLBAR_TOOL_HOVER_MASK
            self._hover_tool = None
            self.Refresh(False)

[docs]    def OnMouseUp(self, event):

        if self._active_tool:
            if self._active_tool.state & RIBBON_TOOLBAR_TOOL_ACTIVE_MASK:
                evt_type = wxEVT_COMMAND_RIBBONTOOL_CLICKED
                if self._active_tool.state & RIBBON_TOOLBAR_TOOL_DROPDOWN_ACTIVE:
                    evt_type = wxEVT_COMMAND_RIBBONTOOL_DROPDOWN_CLICKED

                notification = RibbonToolBarEvent(evt_type, self._active_tool.id)
                notification.SetEventObject(self)
                notification.SetBar(self)
                self.ProcessEvent(notification)

            # Notice that m_active_tool could have been reset by the event handler
            # above so we need to test it again.
            if self._active_tool:
                self._active_tool.state &= ~RIBBON_TOOLBAR_TOOL_ACTIVE_MASK
                self._active_tool = None
                self.Refresh(False)

[docs]    def OnMouseEnter(self, event):

        if self._active_tool and not event.LeftIsDown():
            self._active_tool = None

[docs]    def GetDefaultBorder(self):

        return wx.BORDER_NONE

Navigation

  • index
  • modules |
  • Home |
  • Gallery |
  • Contents»
  • Module code »
  • ribbon.toolbar