# --------------------------------------------------------------------------- #
# 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]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 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