示例#1
0
class HeadingText(MHeadingText, LayoutWidget):
    """ The Wx-specific implementation of a HeadingText.
    """

    # 'IHeadingText' interface ---------------------------------------------

    #: Background image.  This is deprecated and no-longer used.
    image = Image(ImageResource("heading_level_1"))

    # ------------------------------------------------------------------------
    # 'IWidget' interface.
    # ------------------------------------------------------------------------

    def _create_control(self, parent):
        """ Create the toolkit-specific control that represents the widget. """
        control = wx.StaticText(parent)
        return control

    # ------------------------------------------------------------------------
    # Private interface.
    # ------------------------------------------------------------------------

    def _set_control_text(self, text):
        """ Set the text on the toolkit specific widget. """
        # Bold the text. Wx supports a limited subset of HTML for rich text.
        text = f"<b>{text}</b>"
        self.control.SetLabelMarkup(text)

    def _get_control_text(self):
        """ Get the text on the toolkit specific widget. """
        return self.control.GetLabelText()
示例#2
0
class ISplashScreen(IWindow):
    """ The interface for a splash screen. """

    # 'ISplashScreen' interface --------------------------------------------

    #: The image to display on the splash screen.
    image = Image()

    #: If log messages are to be displayed then this is the logging level. See
    #: the Python documentation for the 'logging' module for more details.
    log_level = Int(logging.DEBUG)

    #: Should the splash screen display log messages in the splash text?
    show_log_messages = Bool(True)

    #: Optional text to display on top of the splash image.
    text = Str()

    #: The text color.
    # FIXME v3: When TraitsUI supports PyQt then change this to 'Color',
    # (unless that needs the toolkit to be selected too soon, in which case it
    # may need to stay as Any - or Str?)
    # text_color = WxColor('black')
    text_color = Any()

    #: The text font.
    # FIXME v3: When TraitsUI supports PyQt then change this back to
    # 'Font(None)' with the actual default being toolkit specific.
    # text_font = Font(None)
    text_font = Any()

    #: The x, y location where the text will be drawn.
    # FIXME v3: Remove this.
    text_location = Tuple(5, 5)
示例#3
0
class IConfirmationDialog(IDialog):
    """ The interface for a dialog that prompts the user for confirmation. """

    # 'IConfirmationDialog' interface -------------------------------------#

    #: Should the cancel button be displayed?
    cancel = Bool(False)

    #: The default button.
    default = Enum(NO, YES, CANCEL)

    #: The image displayed with the message.  The default is toolkit specific.
    image = Image()

    #: The message displayed in the body of the dialog (use the inherited
    #: 'title' trait to set the title of the dialog itself).
    message = Str()

    #: Some informative text to display below the main message
    informative = Str()

    #: Some additional details that can be exposed by the user
    detail = Str()

    #: The label for the 'no' button.  The default is toolkit specific.
    no_label = Str()

    #: The label for the 'yes' button.  The default is toolkit specific.
    yes_label = Str()
示例#4
0
class SplashScreen(MSplashScreen, Window):
    """ The toolkit specific implementation of a SplashScreen.  See the
    ISplashScreen interface for the API documentation.
    """

    # 'ISplashScreen' interface --------------------------------------------

    image = Image(ImageResource("splash"))

    log_level = Int(DEBUG)

    show_log_messages = Bool(True)

    text = Str()

    text_color = Any()

    text_font = Any()

    text_location = Tuple(5, 5)

    # ------------------------------------------------------------------------
    # Protected 'IWidget' interface.
    # ------------------------------------------------------------------------

    def _create_control(self, parent):
        splash_screen = QtGui.QSplashScreen(self.image.create_image())
        self._qt4_show_message(splash_screen)

        return splash_screen

    # ------------------------------------------------------------------------
    # Private interface.
    # ------------------------------------------------------------------------

    def _text_changed(self):
        """ Called when the splash screen text has been changed. """

        if self.control is not None:
            self._qt4_show_message(self.control)

    def _qt4_show_message(self, control):
        """ Set the message text for a splash screen control. """

        if self.text_font is not None:
            control.setFont(self.text_font)

        if self.text_color is None:
            text_color = QtCore.Qt.GlobalColor.black
        else:
            # Until we get the type of this trait finalised (ie. when TraitsUI
            # supports PyQt) convert it explcitly to a colour.
            text_color = QtGui.QColor(self.text_color)

        control.showMessage(self.text, QtCore.Qt.AlignmentFlag.AlignLeft,
                            text_color)
示例#5
0
class IHeadingText(Interface):
    """ A widget which shows heading text in a panel. """

    # 'IHeadingText' interface ---------------------------------------------

    #: Heading level.  This is currently unused.
    level = Int(1)

    #: The heading text.
    text = Str("Default")

    #: The background image.
    image = Image()
示例#6
0
class IAboutDialog(IDialog):
    """ The interface for a simple 'About' dialog. """

    # 'IAboutDialog' interface ---------------------------------------------

    #: Additional strings to be added to the dialog.
    additions = List(Str)

    #: Additional copyright strings to be added above the standard ones.
    copyrights = List(Str)

    #: The image displayed in the dialog.
    image = Image()
示例#7
0
class CustomEditor(SimpleEditor):
    """ Custom style editor for a button, which can contain an image.
    """
    #: The button image
    image = Image()

    def init(self, parent):
        """ Finishes initializing the editor by creating the underlying toolkit
            widget.
        """
        from pyface.ui.wx.image_button import ImageButton

        factory = self.factory
        if self.factory.label:
            label = self.factory.label
        else:
            label = self.item.get_label(self.ui)

        self._control = ImageButton(
            parent,
            label=self.string_value(label),
            image=factory.image,
            style=factory.style,
            orientation=factory.orientation,
            width_padding=factory.width_padding,
            height_padding=factory.height_padding,
        )
        self.control = self._control.control
        self._control.on_trait_change(self.update_object,
                                      "clicked",
                                      dispatch="ui")
        self.sync_value(self.factory.label_value, "label", "from")
        self.sync_value(self.factory.image_value, "image", "from")
        self.set_tooltip()

    def _label_changed(self, label):
        self._control.label = self.string_value(label)

    @observe("image")
    def _image_updated(self, event):
        image = event.new
        self._control.image = image

    def dispose(self):
        """ Disposes of the contents of an editor.
        """
        self._control.on_trait_change(self.update_object,
                                      "clicked",
                                      remove=True)

        super().dispose()
示例#8
0
class IToggleField(IField):
    """ The toggle field interface.

    This is for a toggle between two states, represented by a boolean value.
    """

    #: The current value of the toggle.
    value = Bool()

    #: The text to display in the toggle.
    text = Str()

    #: The icon to display with the toggle.
    icon = Image()
示例#9
0
class ButtonTextEdit(HasTraits):

    play_button = Button("Play")

    play_button_label = Str("I'm a play button")

    play_button_image = Image(ImageResource("run", [traitsui.extras]))

    values = List()

    button_enabled = Bool(True)

    traits_view = View(
        Item("play_button", style="simple"),
        Item("play_button", style="custom"),
        Item("play_button", style="readonly"),
        Item("play_button", style="text"),
    )
示例#10
0
class AboutDialog(MAboutDialog, Dialog):
    """ The toolkit specific implementation of an AboutDialog.  See the
    IAboutDialog interface for the API documentation.
    """

    # 'IAboutDialog' interface ---------------------------------------------

    additions = List(Str)

    copyrights = List(Str)

    image = Image(ImageResource("about"))

    # Private interface ---------------------------------------------------#

    #: A list of connected Qt signals to be removed before destruction.
    #: First item in the tuple is the Qt signal. The second item is the event
    #: handler.
    _connections_to_remove = List(Tuple(Any, Callable))

    # -------------------------------------------------------------------------
    # 'IWidget' interface.
    # -------------------------------------------------------------------------

    def destroy(self):
        while self._connections_to_remove:
            signal, handler = self._connections_to_remove.pop()
            signal.disconnect(handler)

        super().destroy()

    # ------------------------------------------------------------------------
    # Protected 'IDialog' interface.
    # ------------------------------------------------------------------------

    def _create_contents(self, parent):
        label = QtGui.QLabel()

        if self.title == "":
            if parent.parent() is not None:
                title = parent.parent().windowTitle()
            else:
                title = ""

            # Set the title.
            self.title = "About %s" % title

        # Set the page contents.
        label.setText(self._create_html())

        # Create the button.
        buttons = QtGui.QDialogButtonBox()

        if self.ok_label:
            buttons.addButton(self.ok_label, QtGui.QDialogButtonBox.ButtonRole.AcceptRole)
        else:
            buttons.addButton(QtGui.QDialogButtonBox.StandardButton.Ok)

        buttons.accepted.connect(parent.accept)
        self._connections_to_remove.append((buttons.accepted, parent.accept))

        lay = QtGui.QVBoxLayout()
        lay.addWidget(label)
        lay.addWidget(buttons)

        parent.setLayout(lay)

    def _create_html(self):
        # Load the image to be displayed in the about box.
        path = self.image.absolute_path

        # The additional strings.
        additions = "<br />".join(self.additions)

        # Get the version numbers.
        py_version = platform.python_version()
        qt_version = QtCore.__version__

        # The additional copyright strings.
        copyrights = "<br />".join(
            ["Copyright &copy; %s" % line for line in self.copyrights]
        )

        return _DIALOG_TEXT % (
            path,
            additions,
            py_version,
            qt_version,
            copyrights,
        )
示例#11
0
class ConfirmationDialog(MConfirmationDialog, Dialog):
    """ The toolkit specific implementation of a ConfirmationDialog.  See the
    IConfirmationDialog interface for the API documentation.
    """

    # 'IConfirmationDialog' interface -------------------------------------#

    cancel = Bool(False)

    default = Enum(NO, YES, CANCEL)

    image = Image()

    message = Str()

    informative = Str()

    detail = Str()

    no_label = Str()

    yes_label = Str()

    # ------------------------------------------------------------------------
    # Protected 'IDialog' interface.
    # ------------------------------------------------------------------------

    def _create_buttons(self, parent):
        sizer = wx.StdDialogButtonSizer()

        # 'YES' button.
        if self.yes_label:
            label = self.yes_label
        else:
            label = "Yes"

        self._yes = yes = wx.Button(parent, wx.ID_YES, label)
        if self.default == YES:
            yes.SetDefault()
        parent.Bind(wx.EVT_BUTTON, self._on_yes, yes)
        sizer.AddButton(yes)

        # 'NO' button.
        if self.no_label:
            label = self.no_label
        else:
            label = "No"

        self._no = no = wx.Button(parent, wx.ID_NO, label)
        if self.default == NO:
            no.SetDefault()
        parent.Bind(wx.EVT_BUTTON, self._on_no, no)
        sizer.AddButton(no)

        if self.cancel:
            # 'Cancel' button.
            if self.no_label:
                label = self.cancel_label
            else:
                label = "Cancel"

            self._cancel = cancel = wx.Button(parent, wx.ID_CANCEL, label)
            if self.default == CANCEL:
                cancel.SetDefault()

            parent.Bind(wx.EVT_BUTTON, self._wx_on_cancel, cancel)
            sizer.AddButton(cancel)

        sizer.Realize()
        return sizer

    def _create_dialog_area(self, parent):
        panel = wx.Panel(parent, -1)
        sizer = wx.BoxSizer(wx.HORIZONTAL)
        panel.SetSizer(sizer)
        panel.SetAutoLayout(True)

        # The image.
        if self.image is None:
            image_rc = ImageResource("warning")
        else:
            image_rc = self.image

        image = wx.StaticBitmap(panel, -1, image_rc.create_bitmap())
        sizer.Add(image, 0, wx.EXPAND | wx.ALL, 10)

        # The message.
        if self.informative:
            message = self.message + "\n\n" + self.informative
        else:
            message = self.message
        message = wx.StaticText(panel, -1, message)
        sizer.Add(message, 1, wx.EXPAND | wx.TOP, 15)

        # Resize the panel to match the sizer.
        sizer.Fit(panel)

        return panel

    # ------------------------------------------------------------------------
    # Private interface.
    # ------------------------------------------------------------------------

    # wx event handlers ----------------------------------------------------

    def _on_yes(self, event):
        """ Called when the 'Yes' button is pressed. """

        self.control.EndModal(wx.ID_YES)

    def _on_no(self, event):
        """ Called when the 'No' button is pressed. """

        self.control.EndModal(wx.ID_NO)
示例#12
0
class ExpandableHeader(Widget):
    """ A header for an entry in a collection of expandables.

    The header provides a visual indicator of the current state, a text label,
    and a 'remove' button.
    """

    #: The title of the panel.
    title = Str("Panel")

    #: The carat image to show when the panel is collapsed.
    collapsed_carat_image = Image(ImageResource("carat_closed"))

    #: The carat image to show when the panel is expanded.
    expanded_carat_image = Image(ImageResource("carat_open"))

    #: The backing header image when the mouse is elsewhere
    #: This is not used and deprecated.
    header_bar_image = Image(ImageResource("panel_gradient"))

    #: The backing header image when the mouse is over
    #: This is not used and deprecated.
    header_mouseover_image = Image(ImageResource("panel_gradient_over"))

    #: The image to use for the close button.
    #: This is not used and deprecated.
    remove_image = Image(ImageResource("close"))

    #: Represents the current state of the panel. True means expanded.
    state = Bool(False)

    # Events ----

    #: The panel has been expanded or collapsed
    panel_expanded = Event()

    #: The panel has been closed
    panel_closed = Event()

    _CARAT_X = 4
    _CARAT_Y = 4
    _TEXT_Y = 0
    _TEXT_X_OFFSET = 10

    # ------------------------------------------------------------------------
    # 'object' interface.
    # ------------------------------------------------------------------------

    def __init__(self, parent=None, container=None, **traits):
        """ Creates the panel. """

        if container is not None:
            warnings.warn(
                "the container parameter is deprecated and will be "
                "removed in a future Pyface release",
                DeprecationWarning,
            )
            self.observe(
                lambda event: container.remove_panel(event.new),
                "panel_closed",
            )
        create = traits.pop("create", True)

        # Base class constructor.
        super().__init__(parent=parent, **traits)

        # Create the toolkit-specific control that represents the widget.
        if create:
            self.create()
            warnings.warn(
                "automatic widget creation is deprecated and will be removed "
                "in a future Pyface version, use create=False and explicitly "
                "call create() for future behaviour",
                PendingDeprecationWarning,
            )

    # ------------------------------------------------------------------------
    # Private interface.
    # ------------------------------------------------------------------------

    def _create_control(self, parent):
        """ Create the toolkit-specific control that represents the widget. """

        collapsed_carat = self.collapsed_carat_image.create_image()
        self._collapsed_bmp = collapsed_carat.ConvertToBitmap()
        self._carat_w = self._collapsed_bmp.GetWidth()

        expanded_carat = self.expanded_carat_image.create_image()
        self._expanded_bmp = expanded_carat.ConvertToBitmap()

        # create our panel and initialize it appropriately
        sizer = wx.BoxSizer(wx.VERTICAL)
        panel = wx.Panel(parent, -1, style=wx.CLIP_CHILDREN | wx.BORDER_SIMPLE)
        panel.SetSizer(sizer)
        panel.SetAutoLayout(True)

        # create the remove button
        remove = wx.BitmapButton.NewCloseButton(panel, -1)
        sizer.Add(remove, 0, wx.ALIGN_RIGHT, 5)

        # Create a suitable font.
        self._font = new_font_like(
            wx.NORMAL_FONT, point_size=wx.NORMAL_FONT.GetPointSize() - 1
        )

        height = self._get_preferred_height(parent, self.title, self._font)
        panel.SetMinSize((-1, height+2))

        panel.Bind(wx.EVT_PAINT, self._on_paint)
        panel.Bind(wx.EVT_LEFT_DOWN, self._on_down)
        panel.Bind(wx.EVT_BUTTON, self._on_remove)

        return panel

    def _get_preferred_height(self, parent, text, font):
        """ Calculates the preferred height of the widget. """

        dc = wx.MemoryDC()

        dc.SetFont(font)
        metrics = dc.GetFontMetrics()
        text_h = metrics.height + 2 * self._TEXT_Y

        # add in height of buttons
        carat_h = self._collapsed_bmp.GetHeight() + 2 * self._CARAT_Y

        return max(text_h, carat_h)

    def _draw_carat_button(self, dc):
        """ Draws the button at the correct coordinates. """

        if self.state:
            bmp = self._expanded_bmp
        else:
            bmp = self._collapsed_bmp

        dc.DrawBitmap(bmp, self._CARAT_X, self._CARAT_Y, True)

    def _draw_title(self, dc):
        """ Draws the text label for the header. """
        dc.SetFont(self._font)

        # Render the text.
        dc.DrawText(
            self.title, self._carat_w + self._TEXT_X_OFFSET, self._TEXT_Y
        )

    def _draw(self, dc):
        """ Draws the control. """

        # Draw the title text
        self._draw_title(dc)

        # Draw the carat button
        self._draw_carat_button(dc)

    # ------------------------------------------------------------------------
    # wx event handlers.
    # ------------------------------------------------------------------------

    def _on_paint(self, event):
        """ Called when the background of the panel is erased. """

        # print('ImageButton._on_erase_background')
        dc = wx.PaintDC(self.control)
        self._draw(dc)

    def _on_down(self, event):
        """ Called when button is pressed. """

        self.state = not self.state
        self.control.Refresh()

        # fire an event so any listeners can pick up the change
        self.panel_expanded = self
        event.Skip()

    def _on_remove(self, event):
        """ Called when remove button is pressed. """
        self.panel_closed = self
示例#13
0
class IApplicationWindow(IWindow):
    """ The interface for a top-level application window.

    The application window has support for a menu bar, tool bar and a status
    bar (all of which are optional).

    Usage
    -----

    Create a sub-class of this class and override the
    :py:meth:`._create_contents` method.
    """

    # 'IApplicationWindow' interface ---------------------------------------

    #: The window icon.  The default is toolkit specific.
    icon = Image()

    #: The menu bar manager (None iff there is no menu bar).
    menu_bar_manager = Instance(MenuBarManager)

    #: The status bar manager (None iff there is no status bar).
    status_bar_manager = Instance(StatusBarManager)

    #: The tool bar manager (None iff there is no tool bar).
    tool_bar_manager = Instance(ToolBarManager)

    #: If the underlying toolkit supports multiple toolbars, you can use this
    #: list instead of the single ToolBarManager instance above.
    tool_bar_managers = List(ToolBarManager)

    # ------------------------------------------------------------------------
    # Protected 'IApplicationWindow' interface.
    # ------------------------------------------------------------------------

    def _create_contents(self, parent):
        """ Create and return the window's contents.

        Parameters
        ----------
        parent : toolkit control
            The window's toolkit control to be used as the parent for
            widgets in the contents.

        Returns
        -------
        control : toolkit control
            A control to be used for contents of the window.
        """

    def _create_menu_bar(self, parent):
        """ Creates the menu bar (if required).

        Parameters
        ----------
        parent : toolkit control
            The window's toolkit control.
        """

    def _create_status_bar(self, parent):
        """ Creates the status bar (if required).

        Parameters
        ----------
        parent : toolkit control
            The window's toolkit control.
        """

    def _create_tool_bar(self, parent):
        """ Creates the tool bar (if required).

        Parameters
        ----------
        parent : toolkit control
            The window's toolkit control.
        """

    def _create_trim_widgets(self, parent):
        """ Creates the 'trim' widgets (the widgets around the window).

        Parameters
        ----------
        parent : toolkit control
            The window's toolkit control.
        """

    def _set_window_icon(self):
        """ Sets the window icon (if required). """
示例#14
0
class SplashScreen(MSplashScreen, Window):
    """ The toolkit specific implementation of a SplashScreen.  See the
    ISplashScreen interface for the API documentation.
    """

    # 'ISplashScreen' interface --------------------------------------------

    image = Image(ImageResource("splash"))

    log_level = Int(DEBUG)

    show_log_messages = Bool(True)

    text = Str()

    text_color = Any()

    text_font = Any()

    text_location = Tuple(5, 5)

    # ------------------------------------------------------------------------
    # Protected 'IWidget' interface.
    # ------------------------------------------------------------------------

    def _create_control(self, parent):
        # Get the splash screen image.
        image = self.image.create_image()

        splash_screen = wx.adv.SplashScreen(
            # The bitmap to display on the splash screen.
            image.ConvertToBitmap(),
            # Splash Style.
            wx.adv.SPLASH_NO_TIMEOUT | wx.adv.SPLASH_CENTRE_ON_SCREEN,
            # Timeout in milliseconds (we don't currently timeout!).
            0,
            # The parent of the splash screen.
            parent,
            # wx Id.
            -1,
            # Window style.
            style=wx.SIMPLE_BORDER | wx.FRAME_NO_TASKBAR,
        )

        # By default we create a font slightly bigger and slightly more italic
        # than the normal system font ;^)  The font is used inside the event
        # handler for 'EVT_PAINT'.
        self._wx_default_text_font = new_font_like(
            wx.NORMAL_FONT,
            point_size=wx.NORMAL_FONT.GetPointSize() + 1,
            style=wx.ITALIC,
        )

        # This allows us to write status text on the splash screen.
        splash_screen.Bind(wx.EVT_PAINT, self._on_paint)

        return splash_screen

    # ------------------------------------------------------------------------
    # Private interface.
    # ------------------------------------------------------------------------

    def _text_changed(self):
        """ Called when the splash screen text has been changed. """

        # Passing 'False' to 'Refresh' means "do not erase the background".
        if self.control is not None:
            self.control.Refresh(False)
            self.control.Update()
        wx.GetApp().Yield(True)

    def _on_paint(self, event):
        """ Called when the splash window is being repainted. """

        if self.control is not None:
            # Get the window that the splash image is drawn in.
            window = self.control  # .GetSplashWindow()

            dc = wx.PaintDC(window)

            if self.text_font is None:
                text_font = self._wx_default_text_font
            else:
                text_font = self.text_font

            dc.SetFont(text_font)

            if self.text_color is None:
                text_color = "black"
            else:
                text_color = self.text_color

            dc.SetTextForeground(text_color)

            x, y = self.text_location
            dc.DrawText(self.text, x, y)

        # Let the normal wx paint handling do its stuff.
        event.Skip()
示例#15
0
class MDIApplicationWindow(ApplicationWindow):
    """ An MDI top-level application window.

    The application window has support for a menu bar, tool bar and a status
    bar (all of which are optional).

    Usage: Create a sub-class of this class and override the protected
    '_create_contents' method.

    """

    # 'MDIApplicationWindow' interface -------------------------------------

    # The workarea background image.
    background_image = Image(ImageResource("background"))

    # Should we tile the workarea  background image?  The alternative is to
    # scale it.  Be warned that scaling the image allows for 'pretty' images,
    # but is MUCH slower than tiling.
    tile_background_image = Bool(True)

    # WX HACK FIXME
    # UPDATE: wx 2.6.1 does NOT fix this issue.
    _wx_offset = Tuple(Int, Int)

    # ------------------------------------------------------------------------
    # 'MDIApplicationWindow' interface.
    # ------------------------------------------------------------------------

    def create_child_window(self, title=None, is_mdi=True, float=True):
        """ Create a child window. """
        if title is None:
            title = self.title

        if is_mdi:
            return wx.MDIChildFrame(self.control, -1, title)
        else:
            if float:
                style = wx.DEFAULT_FRAME_STYLE | wx.FRAME_FLOAT_ON_PARENT
            else:
                style = wx.DEFAULT_FRAME_STYLE
            return wx.Frame(self.control, -1, title, style=style)

    # ------------------------------------------------------------------------
    # Protected 'Window' interface.
    # ------------------------------------------------------------------------

    def _create_contents(self, parent):
        """ Create the contents of the MDI window. """

        # Create the 'trim' widgets (menu, tool and status bars etc).
        self._create_trim_widgets(self.control)

        # The work-area background image (it can be tiled or scaled).
        self._image = self.background_image.create_image()
        self._bmp = self._image.ConvertToBitmap()

        # Frame events.
        #
        # We respond to size events to layout windows around the MDI frame.
        self.control.Bind(wx.EVT_SIZE, self._on_size)

        # Client window events.
        client_window = self.control.GetClientWindow()
        client_window.Bind(wx.EVT_ERASE_BACKGROUND, self._on_erase_background)
        try:
            self._wx_offset = client_window.GetPosition().Get()
        except:
            self._wx_offset = (0, 0)

        if AUI:
            # Let the AUI manager look after the frame.
            self._aui_manager.SetManagedWindow(self.control)

        contents = super()._create_contents(parent)

        return contents

    def _create_control(self, parent):
        """ Create the toolkit-specific control that represents the window. """

        control = wx.MDIParentFrame(
            parent,
            -1,
            self.title,
            style=wx.DEFAULT_FRAME_STYLE,
            size=self.size,
            pos=self.position,
        )

        return control

    # ------------------------------------------------------------------------
    # Private interface.
    # ------------------------------------------------------------------------

    def _tile_background_image(self, dc, width, height):
        """ Tiles the background image. """

        w = self._bmp.GetWidth()
        h = self._bmp.GetHeight()

        x = 0
        while x < width:
            y = 0
            while y < height:
                dc.DrawBitmap(self._bmp, x, y)
                y = y + h

            x = x + w

    def _scale_background_image(self, dc, width, height):
        """ Scales the background image. """

        # Scale the image (if necessary).
        image = self._image
        if image.GetWidth() != width or image.GetHeight() != height:
            image = self._image.Copy()
            image.Rescale(width, height)

        # Convert it to a bitmap and draw it.
        dc.DrawBitmap(image.ConvertToBitmap(), 0, 0)

        return

    ## wx event handlers ---------------------------------------------------

    def _on_size(self, event):
        """ Called when the frame is resized. """

        wx.adv.LayoutAlgorithm().LayoutMDIFrame(self.control)
        event.Skip()

    def _on_erase_background(self, event):
        """ Called when the background of the MDI client window is erased. """

        # fixme: Close order...
        if self.control is None:
            return

        frame = self.control

        dc = event.GetDC()
        if not dc:
            dc = wx.ClientDC(frame.GetClientWindow())

        size = frame.GetClientSize()

        # Currently you have two choices, tile the image or scale it.  Be
        # warned that scaling is MUCH slower than tiling.
        if self.tile_background_image:
            self._tile_background_image(dc, size.width, size.height)

        else:
            self._scale_background_image(dc, size.width, size.height)
示例#16
0
class MToggleField(HasTraits):
    """ The toggle field mixin class.

    This is for a toggle between two states, represented by a boolean value.
    """

    #: The current value of the toggle.
    value = Bool()

    #: The text to display in the toggle.
    text = Str()

    #: The icon to display with the toggle.
    icon = Image()

    # ------------------------------------------------------------------------
    # Private interface
    # ------------------------------------------------------------------------

    def _initialize_control(self):
        super()._initialize_control()
        self._set_control_text(self.text)
        self._set_control_icon(self.icon)

    def _add_event_listeners(self):
        """ Set up toolkit-specific bindings for events """
        super()._add_event_listeners()
        self.observe(self._text_updated, "text", dispatch="ui")
        self.observe(self._icon_updated, "icon", dispatch="ui")
        if self.control is not None:
            self._observe_control_value()

    def _remove_event_listeners(self):
        """ Remove toolkit-specific bindings for events """
        if self.control is not None:
            self._observe_control_value(remove=True)
        self.observe(self._text_updated, "text", dispatch="ui", remove=True)
        self.observe(self._icon_updated, "icon", dispatch="ui", remove=True)
        super()._remove_event_listeners()

    # Toolkit control interface ---------------------------------------------

    def _get_control_text(self):
        """ Toolkit specific method to set the control's text. """
        raise NotImplementedError()

    def _set_control_text(self, text):
        """ Toolkit specific method to set the control's text. """
        raise NotImplementedError()

    def _set_control_icon(self, icon):
        """ Toolkit specific method to set the control's icon. """
        raise NotImplementedError()

    # Trait change handlers -------------------------------------------------

    def _text_updated(self, event):
        if self.control is not None:
            self._set_control_text(self.text)

    def _icon_updated(self, event):
        if self.control is not None:
            self._set_control_icon(self.icon)
示例#17
0
class ExpandablePanel(LayoutWidget):
    """ An expandable panel. """

    # The default style.
    STYLE = wx.CLIP_CHILDREN

    collapsed_image = Image(ImageResource("mycarat1"))
    expanded_image = Image(ImageResource("mycarat2"))

    _layers = Dict(Str)

    _headers = Dict(Str)

    # ------------------------------------------------------------------------
    # 'object' interface.
    # ------------------------------------------------------------------------

    def __init__(self, parent=None, **traits):
        """ Creates a new LayeredPanel. """

        create = traits.pop("create", True)

        # Base class constructor.
        super().__init__(parent=parent, **traits)

        # Create the toolkit-specific control that represents the widget.
        if create:
            self.create()
            warnings.warn(
                "automatic widget creation is deprecated and will be removed "
                "in a future Pyface version, use create=False and explicitly "
                "call create() for future behaviour",
                PendingDeprecationWarning,
            )
    # ------------------------------------------------------------------------
    # 'Expandale' interface.
    # ------------------------------------------------------------------------

    def add_panel(self, name, layer):
        """ Adds a layer with the specified name.

        All layers are hidden when they are added.  Use 'show_layer' to make a
        layer visible.

        """

        parent = self.control
        sizer = self.control.GetSizer()

        # Add the heading text.
        header = self._create_header(parent, text=name)
        sizer.Add(header, 0, wx.EXPAND)

        # Add the layer to our sizer.
        sizer.Add(layer, 1, wx.EXPAND)

        # All layers are hidden when they are added.  Use 'show_layer' to make
        # a layer visible.
        sizer.Show(layer, False)

        # fixme: Should we warn if a layer is being overridden?
        self._layers[name] = layer

        return layer

    def remove_panel(self, name):
        """ Removes a layer and its header from the container."""

        if name not in self._layers:
            return

        sizer = self.control.GetSizer()
        panel = self._layers[name]
        header = self._headers[name]
        # sizer.Remove(panel)
        panel.Destroy()
        # sizer.Remove(header)
        header.Destroy()

        sizer.Layout()

    # ------------------------------------------------------------------------
    # Private interface.
    # ------------------------------------------------------------------------

    def _create_control(self, parent):
        """ Create the toolkit-specific control that represents the widget. """

        panel = wx.Panel(parent, -1, style=self.STYLE)
        sizer = wx.BoxSizer(wx.VERTICAL)
        panel.SetSizer(sizer)
        panel.SetAutoLayout(True)

        return panel

    def _create_header(self, parent, text):
        """ Creates a panel header. """

        sizer = wx.BoxSizer(wx.HORIZONTAL)
        panel = wx.Panel(parent, -1, style=wx.CLIP_CHILDREN)
        panel.SetSizer(sizer)
        panel.SetAutoLayout(True)

        # Add the panel header.
        heading = ExpandableHeader(panel, title=text, create=False)
        heading.create()
        sizer.Add(heading.control, 1, wx.EXPAND)

        # connect observers
        heading.observe(self._on_button, "panel_expanded")
        heading.observe(self._on_panel_closed, "panel_closed")

        # Resize the panel to match the sizer's minimum size.
        sizer.Fit(panel)

        # hang onto it for when we destroy
        self._headers[text] = panel

        return panel

    # event handlers ----------------------------------------------------

    def _on_button(self, event):
        """ called when one of the expand/contract buttons is pressed. """

        header = event.new
        name = header.title
        visible = header.state

        sizer = self.control.GetSizer()
        sizer.Show(self._layers[name], visible)
        sizer.Layout()

        # fixme: Errrr, maybe we can NOT do this!
        w, h = self.control.GetSize().Get()
        self.control.SetSize((w + 1, h + 1))
        self.control.SetSize((w, h))

    def _on_panel_closed(self, event):
        """ Called when the close button is clicked in a header. """

        header = event.new
        name = header.title
        self.remove_panel(name)
示例#18
0
class ApplicationWindow(MApplicationWindow, Window):
    """ The toolkit specific implementation of an ApplicationWindow.  See the
    IApplicationWindow interface for the API documentation.
    """

    # 'IApplicationWindow' interface ---------------------------------------

    icon = Image()

    menu_bar_manager = Instance(MenuBarManager)

    status_bar_manager = Instance(StatusBarManager)

    tool_bar_manager = Instance(ToolBarManager)

    # If the underlying toolkit supports multiple toolbars then you can use
    # this list instead.
    tool_bar_managers = List(ToolBarManager)

    # 'IWindow' interface -------------------------------------------------#

    # fixme: We can't set the default value of the actual 'size' trait here as
    # in the toolkit-specific event handlers for window size and position
    # changes, we set the value of the shadow '_size' trait. The problem is
    # that by doing that traits never knows that the trait has been set and
    # hence always returns the default value! Using a trait initializer method
    # seems to work however (e.g. 'def _size_default'). Hmmmm....
    ##     size = (800, 600)

    title = Str("Pyface")

    # ------------------------------------------------------------------------
    # Protected 'IApplicationWindow' interface.
    # ------------------------------------------------------------------------

    def _create_contents(self, parent):
        panel = wx.Panel(parent, -1, name="ApplicationWindow")
        panel.SetBackgroundColour("blue")
        return panel

    def _create_menu_bar(self, parent):
        if self.menu_bar_manager is not None:
            menu_bar = self.menu_bar_manager.create_menu_bar(parent)
            self.control.SetMenuBar(menu_bar)

    def _create_status_bar(self, parent):
        if self.status_bar_manager is not None:
            status_bar = self.status_bar_manager.create_status_bar(parent)
            self.control.SetStatusBar(status_bar)

    def _create_tool_bar(self, parent):
        tool_bar_managers = self._get_tool_bar_managers()
        if len(tool_bar_managers) > 0:
            for tool_bar_manager in reversed(tool_bar_managers):
                tool_bar = tool_bar_manager.create_tool_bar(parent, aui=True)
                self._add_toolbar_to_aui_manager(tool_bar)
            self._aui_manager.Update()

    def _set_window_icon(self):
        if self.icon is None:
            icon = ImageResource("application.ico")
        else:
            icon = self.icon

        if self.control is not None:
            self.control.SetIcon(icon.create_icon())

    # ------------------------------------------------------------------------
    # 'Window' interface.
    # ------------------------------------------------------------------------

    def _size_default(self):
        """ Trait initialiser. """
        return (800, 600)

    # ------------------------------------------------------------------------
    # Protected 'IWidget' interface.
    # ------------------------------------------------------------------------

    def _create(self):

        super()._create()

        self._aui_manager = PyfaceAuiManager()
        self._aui_manager.SetManagedWindow(self.control)

        # Keep a reference to the AUI Manager in the control because Panes
        # will need to access it in order to lay themselves out
        self.control._aui_manager = self._aui_manager

        contents = self._create_contents(self.control)
        self._aui_manager.AddPane(contents, aui.AuiPaneInfo().CenterPane())

        self._create_trim_widgets(self.control)

        # Updating the AUI manager actually commits all of the pane's added
        # to it (this allows batch updates).
        self._aui_manager.Update()

    def _create_control(self, parent):

        style = (
            wx.DEFAULT_FRAME_STYLE | wx.FRAME_NO_WINDOW_MENU | wx.CLIP_CHILDREN
        )

        control = wx.Frame(
            parent,
            -1,
            self.title,
            style=style,
            size=self.size,
            pos=self.position,
        )

        # Mac/Win needs this, otherwise background color is black
        attr = control.GetDefaultAttributes()
        control.SetBackgroundColour(attr.colBg)

        return control

    def destroy(self):
        if self.control:
            self._aui_manager.UnInit()
        super().destroy()

    # ------------------------------------------------------------------------
    # Private interface.
    # ------------------------------------------------------------------------

    def _add_toolbar_to_aui_manager(self, tool_bar):
        """ Add a toolbar to the AUI manager. """

        info = self._get_tool_bar_pane_info(tool_bar)
        self._aui_manager.AddPane(tool_bar, info)

    def _get_tool_bar_pane_info(self, tool_bar):
        info = aui.AuiPaneInfo()
        info.Caption(tool_bar.tool_bar_manager.name)
        info.LeftDockable(False)
        info.Name(tool_bar.tool_bar_manager.id)
        info.RightDockable(False)
        info.ToolbarPane()
        info.Top()

        return info

    def _get_tool_bar_managers(self):
        """ Return all tool bar managers specified for the window. """

        # fixme: V3 remove the old-style single toolbar option!
        if self.tool_bar_manager is not None:
            tool_bar_managers = [self.tool_bar_manager]

        else:
            tool_bar_managers = self.tool_bar_managers

        return tool_bar_managers

    def _wx_enable_tool_bar(self, tool_bar, enabled):
        """ Enable/Disablea tool bar. """

        # AUI toolbars cannot be enabled/disabled.

    def _wx_show_tool_bar(self, tool_bar, visible):
        """ Hide/Show a tool bar. """

        pane = self._aui_manager.GetPane(tool_bar.tool_bar_manager.id)

        if visible:
            pane.Show()

        else:
            # Without this workaround, toolbars know the sizes of other
            # hidden toolbars and leave gaps in the toolbar dock
            pane.window.Show(False)
            self._aui_manager.DetachPane(pane.window)
            info = self._get_tool_bar_pane_info(pane.window)
            info.Hide()
            self._aui_manager.AddPane(pane.window, info)

        self._aui_manager.Update()

        return

    # Trait change handlers ------------------------------------------------

    def _menu_bar_manager_changed(self):
        if self.control is not None:
            self._create_menu_bar(self.control)

    def _status_bar_manager_changed(self, old, new):
        if self.control is not None:
            if old is not None:
                self.control.SetStatusBar(None)
                old.destroy(self.control)
            self._create_status_bar(self.control)

    @observe("tool_bar_manager, tool_bar_managers.items")
    def _update_tool_bar_managers(self, event):
        if self.control is not None:
            self._create_tool_bar(self.control)

    def _icon_changed(self):
        self._set_window_icon()
示例#19
0
class ConfirmationDialog(MConfirmationDialog, Dialog):
    """ The toolkit specific implementation of a ConfirmationDialog.  See the
    IConfirmationDialog interface for the API documentation.
    """

    # 'IConfirmationDialog' interface -------------------------------------#

    cancel = Bool(False)

    default = Enum(NO, YES, CANCEL)

    image = Image()

    message = Str()

    informative = Str()

    detail = Str()

    no_label = Str()

    yes_label = Str()

    # If we create custom buttons with the various roles, then we need to
    # keep track of the buttons so we can see what the user clicked.  It's
    # not correct nor sufficient to check the return result from QMessageBox.exec_().
    # (As of Qt 4.5.1, even clicking a button with the YesRole would lead to
    # exec_() returning QDialog.DialogCode.Rejected.
    _button_result_map = Dict()

    # ------------------------------------------------------------------------
    # Protected 'IDialog' interface.
    # ------------------------------------------------------------------------

    def _create_contents(self, parent):
        # In PyQt this is a canned dialog.
        pass

    # ------------------------------------------------------------------------
    # Protected 'IWidget' interface.
    # ------------------------------------------------------------------------

    def _create_control(self, parent):
        dlg = QtGui.QMessageBox(parent)

        dlg.setWindowTitle(self.title)
        dlg.setText(self.message)
        dlg.setInformativeText(self.informative)
        dlg.setDetailedText(self.detail)

        if self.size != (-1, -1):
            dlg.resize(*self.size)

        if self.position != (-1, -1):
            dlg.move(*self.position)

        if self.image is None:
            dlg.setIcon(QtGui.QMessageBox.Icon.Warning)
        else:
            dlg.setIconPixmap(self.image.create_image())

        # The 'Yes' button.
        if self.yes_label:
            btn = dlg.addButton(self.yes_label,
                                QtGui.QMessageBox.ButtonRole.YesRole)
        else:
            btn = dlg.addButton(QtGui.QMessageBox.StandardButton.Yes)
        self._button_result_map[btn] = YES

        if self.default == YES:
            dlg.setDefaultButton(btn)

        # The 'No' button.
        if self.no_label:
            btn = dlg.addButton(self.no_label,
                                QtGui.QMessageBox.ButtonRole.NoRole)
        else:
            btn = dlg.addButton(QtGui.QMessageBox.StandardButton.No)
        self._button_result_map[btn] = NO

        if self.default == NO:
            dlg.setDefaultButton(btn)

        # The 'Cancel' button.
        if self.cancel:
            if self.cancel_label:
                btn = dlg.addButton(self.cancel_label,
                                    QtGui.QMessageBox.ButtonRole.RejectRole)
            else:
                btn = dlg.addButton(QtGui.QMessageBox.StandardButton.Cancel)

            self._button_result_map[btn] = CANCEL

            if self.default == CANCEL:
                dlg.setDefaultButton(btn)

        return dlg

    def _show_modal(self):
        self.control.setWindowModality(
            QtCore.Qt.WindowModality.ApplicationModal)
        retval = self.control.exec_()
        if self.control is None:
            # dialog window closed
            if self.cancel:
                # if cancel is available, close is Cancel
                return CANCEL
            return self.default
        clicked_button = self.control.clickedButton()
        if clicked_button in self._button_result_map:
            retval = self._button_result_map[clicked_button]
        else:
            retval = _RESULT_MAP[retval]
        return retval
示例#20
0
class ApplicationWindow(MApplicationWindow, Window):
    """ The toolkit specific implementation of an ApplicationWindow.  See the
    IApplicationWindow interface for the API documentation.
    """

    # 'IApplicationWindow' interface ---------------------------------------

    #: The icon to display in the application window title bar.
    icon = Image()

    #: The menu bar manager for the window.
    menu_bar_manager = Instance(MenuBarManager)

    #: The status bar manager for the window.
    status_bar_manager = Instance(StatusBarManager)

    #: DEPRECATED: The tool bar manager for the window.
    tool_bar_manager = Instance(ToolBarManager)

    #: The collection of tool bar managers for the window.
    tool_bar_managers = List(ToolBarManager)

    # 'IWindow' interface -------------------------------------------------#

    #: The window title.
    title = Str("Pyface")

    # ------------------------------------------------------------------------
    # Protected 'IApplicationWindow' interface.
    # ------------------------------------------------------------------------

    def _create_contents(self, parent):
        panel = QtGui.QWidget(parent)

        palette = QtGui.QPalette(panel.palette())
        palette.setColor(QtGui.QPalette.ColorRole.Window, QtGui.QColor("blue"))
        panel.setPalette(palette)
        panel.setAutoFillBackground(True)

        return panel

    def _create_menu_bar(self, parent):
        if self.menu_bar_manager is not None:
            menu_bar = self.menu_bar_manager.create_menu_bar(parent)
            self.control.setMenuBar(menu_bar)

    def _create_status_bar(self, parent):
        if self.status_bar_manager is not None:
            status_bar = self.status_bar_manager.create_status_bar(parent)

            # QMainWindow automatically makes the status bar visible, but we
            # have delegated this responsibility to the status bar manager.
            self.control.setStatusBar(status_bar)
            status_bar.setVisible(self.status_bar_manager.visible)

    def _create_tool_bar(self, parent):
        tool_bar_managers = self._get_tool_bar_managers()
        visible = self.control.isVisible()
        for tool_bar_manager in tool_bar_managers:
            # Add the tool bar and make sure it is visible.
            tool_bar = tool_bar_manager.create_tool_bar(parent)
            self.control.addToolBar(tool_bar)
            tool_bar.show()

            # Make sure that the tool bar has a name so its state can be saved.
            if len(tool_bar.objectName()) == 0:
                tool_bar.setObjectName(tool_bar_manager.name)

        if sys.platform == "darwin":
            # Work around bug in Qt on OS X where creating a tool bar with a
            # QMainWindow parent hides the window. See
            # http://bugreports.qt.nokia.com/browse/QTBUG-5069 for more info.
            self.control.setVisible(visible)

    def _set_window_icon(self):
        if self.icon is None:
            icon = ImageResource("application.png")
        else:
            icon = self.icon
        if self.control is not None:
            self.control.setWindowIcon(icon.create_icon())

    # ------------------------------------------------------------------------
    # 'Window' interface.
    # ------------------------------------------------------------------------

    def _size_default(self):
        """ Trait initialiser. """

        return (800, 600)

    # ------------------------------------------------------------------------
    # Protected 'IWidget' interface.
    # ------------------------------------------------------------------------

    def _create(self):
        super()._create()

        contents = self._create_contents(self.control)
        self.control.setCentralWidget(contents)

        self._create_trim_widgets(self.control)

    def _create_control(self, parent):
        control = super()._create_control(parent)
        control.setObjectName("ApplicationWindow")

        control.setAnimated(False)
        control.setDockNestingEnabled(True)

        return control

    # ------------------------------------------------------------------------
    # Private interface.
    # ------------------------------------------------------------------------

    def _get_tool_bar_managers(self):
        """ Return all tool bar managers specified for the window. """

        # fixme: V3 remove the old-style single toolbar option!
        if self.tool_bar_manager is not None:
            tool_bar_managers = [self.tool_bar_manager]

        else:
            tool_bar_managers = self.tool_bar_managers

        return tool_bar_managers

    # Trait change handlers ------------------------------------------------

    # QMainWindow takes ownership of the menu bar and the status bar upon
    # assignment. For this reason, it is unnecessary to delete the old controls
    # in the following two handlers.

    @observe("menu_bar_manager")
    def _menu_bar_manager_updated(self, event):
        if self.control is not None:
            self._create_menu_bar(self.control)

    @observe("status_bar_manager")
    def _status_bar_manager_updated(self, event):
        if self.control is not None:
            if event.old is not None:
                event.old.destroy()
            self._create_status_bar(self.control)

    @observe("tool_bar_manager, tool_bar_managers.items")
    def _update_tool_bar_managers(self, event):
        if self.control is not None:
            # Remove the old toolbars.
            for child in self.control.children():
                if isinstance(child, QtGui.QToolBar):
                    self.control.removeToolBar(child)
                    child.deleteLater()

            # Add the new toolbars.
            self._create_tool_bar(self.control)

    @observe("icon")
    def _icon_updated(self, event):
        self._set_window_icon()
示例#21
0
class DockWindowFeature(HasPrivateTraits):
    """ Implements "features" on DockWindows.

    See "The DockWindowFeature Feature of DockWindows" document (.doc or .pdf)
    in pyface.doc for details on using this class.

    Traits are defined on each feature instance. One or more feature instances
    are created for each application component that a feature class applies to.
    A given feature class might or might not apply to a specific application
    component. The feature class determines whether it applies to an application
    component when the feature is activated, or when a new application
    component is added to the DockWindow (and the feature is already active).
    """

    # ---------------------------------------------------------------------------
    #  Class variables:
    # ---------------------------------------------------------------------------

    # A string value that is the user interface name of the feature as it
    # should appear in the DockWindow Features sub-menu (e.g., 'Connect'). An
    # empty string (the default) means that the feature does not appear in the
    # Features sub-menu and cannot be enabled or disabled by the user. Avoid
    # feature names that conflict with other, known features.
    feature_name = ""

    # An integer that specifies th current state of the feature
    # (0 = uninstalled, 1 = active, 2 = disabled). Usually you do not need to
    # change this value explicitly; DockWindows normally manages the value
    # automatically, setting it when the user enables or disables the feature.
    state = 0

    # List of weak references to all current instances.
    instances = []

    # ---------------------------------------------------------------------------
    #  Trait definitions:
    # ---------------------------------------------------------------------------

    # -- Public Traits --------------------------------------------------------------

    # The DockControl instance associated with this feature. Note that features
    # not directly associated with application components, and instead are
    # associated with the DockControl object that manages an application
    # component. The DockControl object provides the feature with access to
    # information about the parent DockWindow object, other DockControl objects
    # contained within the same DockWindow, as well as the application
    # component. This trait is automatically set by the DockWindow when the
    # feature instance is created and associated with an application component.
    dock_control = Instance(DockControl)

    # -- Public Traits (new defaults can be defined by subclasses) ------------------

    # The image (icon) to display on the feature bar. If **None**, no image
    # is displayed. For images that never change, the value can be declared
    # statically in the class definition. However, the feature is free to
    # change the value at any time. Changing the value to a new
    # **ImageResource** object causes the associated image to be updated on the
    # feature bar. Setting the value to **None** removes the image from the
    # feature bar.
    image = Image()

    # The tooltip to display when the pointer hovers over the image. The value
    # can be changed dynamically to reflect changes in the feature's state.
    tooltip = Str()

    # The x-coordinate of a pointer event that occurred over the feature's
    # image. This can be used in cases where the event-handling for a feature is
    # sensitive to the position of the pointer relative to the feature image.
    # This is not normally the case, but the information is available if it is
    # needed.
    x = Int()

    # The y-coordinate of a pointer event that occurred over the feature's
    # image.
    y = Int()

    # A boolean value that specifies whether the shift key was being held down
    # when a mouse event occurred.
    shift_down = Bool(False)

    # A boolean value that specifies whether the control key was being held down
    # when a mouse event occurred.
    control_down = Bool(False)

    # A boolean value that specifies whether the alt key was being held down
    # when a mouse event occurred.
    alt_down = Bool(False)

    # -- Private Traits -------------------------------------------------------------

    # The current bitmap to display on the feature bar.
    bitmap = Property

    # -- Overridable Public Methods -------------------------------------------------

    # ---------------------------------------------------------------------------
    #  Handles the user left clicking on the feature image:
    # ---------------------------------------------------------------------------

    def click(self):
        """ Handles the user left-clicking on a feature image.

        This method is designed to be overridden by subclasses. The default
        implementation attempts to perform a 'quick drag' operation (see the
        'quick_drag' method). Returns nothing.
        """
        self.quick_drag()

    # ---------------------------------------------------------------------------
    #  Handles the user right clicking on the feature image:
    # ---------------------------------------------------------------------------

    def right_click(self):
        """ Handles the user right-clicking on a feature image.

        This method is designed to be overridden by subclasses. The default
        implementation attempts to perform a 'quick drag' operation (see the
        'quick_right_drag' method). Returns nothing. Typically, you override
        this method to display the feature's shortcut menu.
        """
        self.quick_right_drag()

    # ---------------------------------------------------------------------------
    #  Returns the object to be dragged when the user drags the feature image:
    # ---------------------------------------------------------------------------

    def drag(self):
        """ Returns the object to be dragged when the user drags a feature
        image.

        This method can be overridden by subclasses. If dragging is supported
        by the feature, then the method returns the object to be dragged;
        otherwise it returns **None**. The default implementation returns
        **None**.
        """
        return None

    # ---------------------------------------------------------------------------
    #  Returns the object to be dragged when the user drags the feature image
    #  while holding down the 'Ctrl' key:
    # ---------------------------------------------------------------------------

    def control_drag(self):
        """ Returns the object to be dragged when the user drags a feature
        image while pressing the 'Ctrl' key.

        This method is designed to be overridden by subclasses. If
        control-dragging is supported by the feature, then the method returns
        the object to be dragged; otherwise it returns **None**. The default
        implementation returns **None**.
        """
        return None

    # ---------------------------------------------------------------------------
    #  Returns the object to be dragged when the user drags the feature image
    #  while holding down the 'Shift' key:
    # ---------------------------------------------------------------------------

    def shift_drag(self):
        """ Returns the object to be dragged when the user drags a feature
        image while pressing the 'Shift' key.

        This method is designed to be overridden by subclasses. If
        shift-dragging is supported by the feature, then the method returns
        the object to be dragged; otherwise it returns **None**. The default
        implementation returns **None**.

        """
        return None

    # ---------------------------------------------------------------------------
    #  Returns the object to be dragged when the user drags the feature image
    #  while holding down the 'Alt' key:
    # ---------------------------------------------------------------------------

    def alt_drag(self):
        """ Returns the object to be dragged when the user drags a feature
        image while pressing the 'Alt' key.

        This method is designed to be overridden by subclasses. If
        Alt-dragging is supported by the feature, then the method returns
        the object to be dragged; otherwise it returns **None**. The default
        implementation returns **None**.

        """
        return None

    # ---------------------------------------------------------------------------
    #  Returns the object to be dragged when the user right mouse button drags
    #  the feature image:
    # ---------------------------------------------------------------------------

    def right_drag(self):
        """ Returns the object to be dragged when the user right mouse button
        drags a feature image.

        This method can be overridden by subclasses. If right dragging is
        supported by the feature, then the method returns the object to be
        dragged; otherwise it returns **None**. The default implementation
        returns **None**.
        """
        return None

    # ---------------------------------------------------------------------------
    #  Returns the object to be dragged when the user right mouse button drags
    #  the feature image while holding down the 'Ctrl' key:
    # ---------------------------------------------------------------------------

    def control_right_drag(self):
        """ Returns the object to be dragged when the user right mouse button
        drags a feature image while pressing the 'Ctrl' key.

        This method is designed to be overridden by subclasses. If
        right control-dragging is supported by the feature, then the method
        returns the object to be dragged; otherwise it returns **None**. The
        default implementation returns **None**.
        """
        return None

    # ---------------------------------------------------------------------------
    #  Returns the object to be dragged when the user right mouse button drags
    #  the feature image while holding down the 'Shift' key:
    # ---------------------------------------------------------------------------

    def shift_control_drag(self):
        """ Returns the object to be dragged when the user right mouse button
        drags a feature image while pressing the 'Shift' key.

        This method is designed to be overridden by subclasses. If right
        shift-dragging is supported by the feature, then the method returns
        the object to be dragged; otherwise it returns **None**. The default
        implementation returns **None**.

        """
        return None

    # ---------------------------------------------------------------------------
    #  Returns the object to be dragged when the user right mouse button drags
    #  the feature image while holding down the 'Alt' key:
    # ---------------------------------------------------------------------------

    def alt_right_drag(self):
        """ Returns the object to be dragged when the user right mouse button
        drags a feature image while pressing the 'Alt' key.

        This method is designed to be overridden by subclasses. If right
        Alt-dragging is supported by the feature, then the method returns
        the object to be dragged; otherwise it returns **None**. The default
        implementation returns **None**.

        """
        return None

    # ---------------------------------------------------------------------------
    #  Handles the user dropping a specified object on the feature image:
    # ---------------------------------------------------------------------------

    def drop(self, object):
        """ Handles the user dropping a specified object on a feature image.

        Parameters
        ----------
        object : any object
            The object being dropped onto the feature image

        Returns
        -------
        Nothing.

        Description
        -----------
        This method is designed to be overridden by subclasses. It is called
        whenever the user drops an object on the feature's tab or drag bar
        image. This method can be called only if a previous call to
        **can_drop()** for the same object returned **True**. The default
        implementation does nothing.
        """
        return

    # ---------------------------------------------------------------------------
    #  Returns whether a specified object can be dropped on the feature image:
    # ---------------------------------------------------------------------------

    def can_drop(self, object):
        """ Returns whether a specified object can be dropped on a feature
        image.

        Parameters
        ----------
        object : any object
            The object being dragged onto the feature image

        Returns
        -------
        **True** if *object* is a valid object for the feature to process;
        **False** otherwise.

        Description
        -----------
        This method is designed to be overridden by subclasses. It is called
        whenever the user drags an icon over the feature's tab or drag bar
        image. The method does not perform any processing on *object*; it only
        examines it. Processing of the object occurs in the **drop()** method,
        which is called when the user release the object over the feature's
        image, which typically occurs after the **can_drop()** method has
        indicated that the feature can process the object, by returning
        **True**. The default implementation returns **False**, indicating that
        the feature does not accept any objects for dropping.
        """
        return False

    # ---------------------------------------------------------------------------
    #  Performs any clean-up needed when the feature is being removed:
    # ---------------------------------------------------------------------------

    def dispose(self):
        """ Performs any clean-up needed when the feature is removed from its
        associated application component (for example, when the user disables
        the feature).

        This method is designed to be overridden by subclasses. The method
        performs any clean-up actions needed by the feature, such as closing
        files, removing trait listeners, and so on. The method does not return
        a result. The default implementation does nothing.
        """
        pass

    # -- Public Methods -------------------------------------------------------------

    # ---------------------------------------------------------------------------
    #  Displays a pop-up menu:
    # ---------------------------------------------------------------------------

    def popup_menu(self, menu):
        """ Displays a shortcut menu.

        Parameters
        ----------
        menu : traitsui.menu.Menu object
            The menu to be displayed

        Returns
        -------
        Nothing.

        Description
        -----------
        This helper method displays the shortcut menu specified by *menu* at a
        point near the feature object's current (x,y) value, as specified by
        the **x** and **y** traits. Normally, the (x,y) value contains the
        screen location where the user clicked on the feature's tab or drag
        bar image. The effect is that the menu is displayed near the feature's
        icon, with the pointer directly over the top menu option.
        """
        window = self.dock_control.control.GetParent()
        wx, wy = window.GetScreenPosition()
        window.PopupMenu(menu.create_menu(window, self), self.x - wx - 10,
                         self.y - wy - 10)

    # ---------------------------------------------------------------------------
    #  Refreshes the display of the feature image:
    # ---------------------------------------------------------------------------

    def refresh(self):
        """ Refreshes the display of the feature image.

        Returns
        -------
        Nothing.

        Description
        -----------
        This helper method requests the containing DockWindow to refresh the
        feature bar.
        """
        self.dock_control.feature_changed = True

    # ---------------------------------------------------------------------------
    #  Disables the feature:
    # ---------------------------------------------------------------------------

    def disable(self):
        """ Disables the feature.

        Returns
        -------
        Nothing.

        Description
        -----------
        This helper method temporarily disables the feature for the associated
        application component. The feature can be re-enabled by calling the
        **enable()** method. Disabling the feature removes the feature's icon
        from the feature bar, without actually deleting the feature (i.e., the
        **dispose()** method is not called).
        """
        self._image = self.image
        self.image = None
        if self._image is not None:
            self.dock_control.feature_changed = True

    # ---------------------------------------------------------------------------
    #  Enables the feature:
    # ---------------------------------------------------------------------------

    def enable(self):
        """ Enables the feature.

        Returns
        -------
        Nothing.

        Description
        -----------
        This helper method re-enables a previously disabled feature for its
        associated application component. Enabling a feature restores the
        feature bar icon that the feature displayed at the time it was disabled.
        """
        self.image = self._image
        self._image = None
        if self.image is not None:
            self.dock_control.feature_changed = True

    # ---------------------------------------------------------------------------
    #  Performs a quick drag and drop operation by displaying a pop-up menu
    #  containing all targets that the feature's xxx_drag() method can be
    #  dropped on. Selecting an item drops the item on the selected target.
    # ---------------------------------------------------------------------------

    def quick_drag(self):
        """ Performs a quick drag and drop operation by displaying a pop-up menu
            containing all targets that the feature's xxx_drag() method can be
            dropped on. Selecting an item drops the item on the selected target.
        """
        # Get the object that would have been dragged:
        if self.control_down:
            object = self.control_drag()
        elif self.alt_down:
            object = self.alt_drag()
        elif self.shift_down:
            object = self.shift_drag()
        else:
            object = self.drag()

        # If there is an object, pop up the menu:
        if object is not None:
            self._quick_drag_menu(object)

    # ---------------------------------------------------------------------------
    #  Performs a quick drag and drop operation with the right mouse button by
    #  displaying a pop-up menu containing all targets that the feature's
    #  xxx_right_drag() method can be dropped on. Selecting an item drops the
    #  item on the selected target.
    # ---------------------------------------------------------------------------

    def quick_right_drag(self):
        """ Performs a quick drag and drop operation with the right mouse button
            by displaying a pop-up menu containing all targets that the
            feature's xxx_right_drag() method can be dropped on. Selecting an
            item drops the item on the selected target.
        """
        # Get the object that would have been dragged:
        if self.control_down:
            object = self.control_right_drag()
        elif self.alt_down:
            object = self.alt_right_drag()
        elif self.shift_down:
            object = self.shift_right_drag()
        else:
            object = self.right_drag()

        # If there is an object, pop up the menu:
        if object is not None:
            self._quick_drag_menu(object)

    # -- Overridable Class Methods ---------------------------------------------------

    # ---------------------------------------------------------------------------
    #  Returns a single new feature object or list of new feature objects for a
    #  specified DockControl (or None if the feature does not apply to it):
    # ---------------------------------------------------------------------------

    @classmethod
    def feature_for(cls, dock_control):
        """ Returns a single new feature object or list of new feature objects
        for a specified DockControl.

        Parameters
        ----------
        dock_control : pyface.dock.api.DockControl
            The DockControl object that corresponds to the application
            component being added, or for which the feature is being enabled.

        Returns
        -------
        An instance or list of instances of this class that will be associated
        with the application component; **None** if the feature does not apply
        to the application component.

        Description
        -----------
        This class method is designed to be overridden by subclasses. Normally,
        a feature class determines whether it applies to an application
        component by examining the component to see if it is an instance of a
        certain class, supports a specified interface, or has trait attributes
        with certain types of metadata. The application component is available
        through the *dock_control.object* trait attribute. Note that it is
        possible for *dock_control.object* to be **None**.

        The default implementation for this method calls the
        **is_feature_for()** class method to determine whether the feature
        applies to the specified DockControl. If it does, it calls the
        **new_feature()** class method to create the feature instances to be
        returned. If it does not, it simply returns **None**.
        """
        if cls.is_feature_for(dock_control):
            return cls.new_feature(dock_control)

        return None

    # ---------------------------------------------------------------------------
    #  Returns a new feature instance for a specified DockControl:
    # ---------------------------------------------------------------------------

    @classmethod
    def new_feature(cls, dock_control):
        """ Returns a new feature instance for a specified DockControl.

        Parameters
        ----------
        dock_control : pyface.dock.api.DockControl
            The DockControl object that corresponds to the application
            component being added, or for which the feature is being enabled.

        Returns
        -------
        An instance or list of instances of this class to be associated
        with the application component; it can also return **None**.

        Description
        -----------
        This method is designed to be overridden by subclasses. This method is
        called by the default implementation of the **feature_for()** class
        method to create the feature instances to be associated with the
        application component specified by *dock_control*. The default
        implementation returns the result of calling the class constructor as
        follows::

            cls( dock_control=dock_control )

        """
        return cls(dock_control=dock_control)

    # ---------------------------------------------------------------------------
    #  Returns whether or not the DockWindowFeature is a valid feature for a
    #  specified DockControl:
    # ---------------------------------------------------------------------------

    @classmethod
    def is_feature_for(self, dock_control):
        """ Returns whether this class is a valid feature for the application
        object corresponding to a specified DockControl.

        Parameters
        ----------
        dock_control : pyface.dock.api.DockControl
            The DockControl object that corresponds to the application
            component being added, or for which the feature is being enabled.

        Returns
        -------
        **True** if the feature applies to the application object associated
        with the *dock_control*; **False** otherwise.

        Description
        -----------
        This class method is designed to be overridden by subclasses. It is
        called by the default implementation of the **feature_for()** class
        method to determine whether the feature applies to the application
        object specified by *dock_control*. The default implementation always
        returns **True**.
        """
        return True

    # -- Private Methods ------------------------------------------------------------

    # ---------------------------------------------------------------------------
    #  Sets the feature's 'event' traits for a specified mouse 'event':
    # ---------------------------------------------------------------------------

    def _set_event(self, event):
        """ Sets the feature's 'event' traits for a specified mouse 'event'.
        """
        x, y = event.GetEventObject().GetScreenPosition()
        self.trait_set(
            x=event.GetX() + x,
            y=event.GetY() + y,
            shift_down=event.ShiftDown(),
            control_down=event.ControlDown(),
            alt_down=event.AltDown(),
        )

    # ---------------------------------------------------------------------------
    #  Displays the quick drag menu for a specified drag object:
    # ---------------------------------------------------------------------------

    def _quick_drag_menu(self, object):
        """ Displays the quick drag menu for a specified drag object.
        """

        # Get all the features it could be dropped on:
        feature_lists = []
        if isinstance(object, IFeatureTool):
            msg = "Apply to"
            for dc in self.dock_control.dock_controls:
                if dc.visible and (
                        object.feature_can_drop_on(dc.object)
                        or object.feature_can_drop_on_dock_control(dc)):
                    from .feature_tool import FeatureTool

                    feature_lists.append([FeatureTool(dock_control=dc)])
        else:
            msg = "Send to"
            for dc in self.dock_control.dock_controls:
                if dc.visible:
                    allowed = [
                        f for f in dc.features
                        if (f.feature_name != "") and f.can_drop(object)
                    ]
                    if len(allowed) > 0:
                        feature_lists.append(allowed)

        # If there are any compatible features:
        if len(feature_lists) > 0:
            # Create the pop-up menu:
            features = []
            actions = []
            for list in feature_lists:
                if len(list) > 1:
                    sub_actions = []
                    for feature in list:
                        sub_actions.append(
                            Action(
                                name="%s Feature" % feature.feature_name,
                                action="self._drop_on(%d)" % len(features),
                            ))
                        features.append(feature)
                    actions.append(
                        Menu(name="%s the %s" %
                             (msg, feature.dock_control.name),
                             *sub_actions))
                else:
                    actions.append(
                        Action(
                            name="%s %s" % (msg, list[0].dock_control.name),
                            action="self._drop_on(%d)" % len(features),
                        ))
                    features.append(list[0])

            # Display the pop-up menu:
            self._object = object
            self._features = features
            self.popup_menu(Menu(name="popup", *actions))
            self._object = self._features = None

    # ---------------------------------------------------------------------------
    #  Drops the current object on the feature selected by the user (used by
    #  the 'quick_drag' method:
    # ---------------------------------------------------------------------------

    def _drop_on(self, index):
        """ Drops the current object on the feature selected by the user.
        """
        object = self._object
        if isinstance(object, IFeatureTool):
            dc = self._features[index].dock_control
            object.feature_dropped_on(dc.object)
            object.feature_dropped_on_dock_control(dc)
        else:
            self._features[index].drop(object)

    # -- Public Class Methods -------------------------------------------------------

    # ---------------------------------------------------------------------------
    #  Returns a feature object for use with the specified DockControl (or None
    #  if the feature does not apply to the DockControl object):
    # ---------------------------------------------------------------------------

    @classmethod
    def new_feature_for(cls, dock_control):
        """ Returns a feature object for use with the specified DockControl (or
        **None** if the feature does not apply to the DockControl object).

        """
        result = cls.feature_for(dock_control)
        if result is not None:
            cls.instances = [
                aref for aref in cls.instances if aref() is not None
            ]
            if isinstance(result, DockWindowFeature):
                result = [result]
            cls.instances.extend([ref(feature) for feature in result])

        return result

    # ---------------------------------------------------------------------------
    #  Toggles the feature on/off:
    # ---------------------------------------------------------------------------

    @classmethod
    def toggle_feature(cls, event):
        """ Toggles the feature on or off.
        """
        if cls.state == 0:
            cls.state = 1
            add_feature(cls)
            for control in event.window.control.GetChildren():
                window = getattr(control, "owner", None)
                if isinstance(window, DockWindow):
                    do_later(window.update_layout)
        else:
            method = "disable"
            cls.state = 3 - cls.state
            if cls.state == 1:
                method = "enable"
            cls.instances = [
                aref for aref in cls.instances if aref() is not None
            ]
            for aref in cls.instances:
                feature = aref()
                if feature is not None:
                    getattr(feature, method)()

    # -- Event Handlers -------------------------------------------------------------

    # ---------------------------------------------------------------------------
    #  Handles the 'image' trait being changed:
    # ---------------------------------------------------------------------------

    @observe('image')
    def _reset_bitmap(self, event):
        self._bitmap = None

    # -- Property Implementations ---------------------------------------------------

    def _get_bitmap(self):
        if (self._bitmap is None) and (self.image is not None):
            self._bitmap = self.image.create_image().ConvertToBitmap()

        return self._bitmap

    # -- Pyface menu interface implementation ---------------------------------------

    # ---------------------------------------------------------------------------
    #  Adds a menu item to the menu bar being constructed:
    # ---------------------------------------------------------------------------

    def add_to_menu(self, menu_item):
        """ Adds a menu item to the menu bar being constructed.
        """
        pass

    # ---------------------------------------------------------------------------
    #  Adds a tool bar item to the tool bar being constructed:
    # ---------------------------------------------------------------------------

    def add_to_toolbar(self, toolbar_item):
        """ Adds a tool bar item to the tool bar being constructed.
        """
        pass

    # ---------------------------------------------------------------------------
    #  Returns whether the menu action should be defined in the user interface:
    # ---------------------------------------------------------------------------

    def can_add_to_menu(self, action):
        """ Returns whether the action should be defined in the user interface.
        """
        return True

    # ---------------------------------------------------------------------------
    #  Returns whether the toolbar action should be defined in the user
    #  interface:
    # ---------------------------------------------------------------------------

    def can_add_to_toolbar(self, action):
        """ Returns whether the toolbar action should be defined in the user
            interface.
        """
        return True

    # ---------------------------------------------------------------------------
    #  Performs the action described by a specified Action object:
    # ---------------------------------------------------------------------------

    def perform(self, action):
        """ Performs the action described by a specified Action object.
        """
        action = action.action
        if action[:5] == "self.":
            eval(action, globals(), {"self": self})
        else:
            getattr(self, action)()
示例#22
0
class AboutDialog(MAboutDialog, Dialog):
    """ The toolkit specific implementation of an AboutDialog.  See the
    IAboutDialog interface for the API documentation.
    """

    # 'IAboutDialog' interface ---------------------------------------------

    additions = List(Str)

    copyrights = List(Str)

    image = Image(ImageResource("about"))

    # ------------------------------------------------------------------------
    # Protected 'IDialog' interface.
    # ------------------------------------------------------------------------

    def _create_contents(self, parent):
        if parent.GetParent() is not None:
            title = parent.GetParent().GetTitle()

        else:
            title = ""

        # Set the title.
        self.title = "About %s" % title

        # Load the image to be displayed in the about box.
        image = self.image.create_image()

        # The width of a wx HTML window is fixed (and  is given in the
        # constructor). We set it to the width of the image plus a fudge
        # factor! The height of the window depends on the content.
        width = image.GetWidth() + 80
        html = wx.html.HtmlWindow(parent, -1, size=(width, -1))

        # Set the page contents.
        html.SetPage(self._create_html())

        # Make the 'OK' button the default button.
        ok_button = parent.FindWindowById(
            wx.ID_OK
        )  # html.Window.FindWindowById(wx.ID_OK)
        ok_button.SetDefault()

        # Set the height of the HTML window to match the height of the content.
        internal = html.GetInternalRepresentation()
        html.SetSize((-1, internal.GetHeight()))

        # Make the dialog client area big enough to display the HTML window.
        # We add a fudge factor to the height here, although I'm not sure why
        # it should be necessary, the HTML window should report its required
        # size!?!
        width, height = html.GetSize().Get()
        parent.SetClientSize((width, height + 10))

    def _create_html(self):
        # Load the image to be displayed in the about box.
        path = self.image.absolute_path

        # The additional strings.
        additions = "<br />".join(self.additions)

        # Get the version numbers.
        py_version = sys.version[0:sys.version.find("(")]
        wx_version = wx.VERSION_STRING

        # The additional copyright strings.
        copyrights = "<br />".join(
            ["Copyright &copy; %s" % line for line in self.copyrights]
        )

        # Get the text of the OK button.
        if self.ok_label is None:
            ok = "OK"
        else:
            ok = self.ok_label

        return _DIALOG_TEXT % (
            path,
            additions,
            py_version,
            wx_version,
            copyrights,
            ok,
        )
示例#23
0
class ConstantValue(AbstractValueType):
    """ A value type that does not depend on the underlying data model.

    This value type is not editable, but the other data channels it
    provides can be modified by changing the appropriate trait on the
    value type.
    """

    #: The text value to display.
    text = Str(update_value_type=True)

    #: The color value to display or None if no color.
    color = Union(None, PyfaceColor)

    #: The image value to display.
    image = Image(update_value_type=True)

    #: The tooltip value to display.
    tooltip = Str(update_value_type=True)

    def has_editor_value(self, model, row, column):
        return False

    def get_text(self, model, row, column):
        return self.text

    def has_color(self, model, row, column):
        """ Whether or not the value has color data.

        Returns true if the supplied color is not None.

        Parameters
        ----------
        model : AbstractDataModel
            The data model holding the data.
        row : sequence of int
            The row in the data model being queried.
        column : sequence of int
            The column in the data model being queried.

        Returns
        -------
        has_color : bool
            Whether or not the value has data-associated color
            values.
        """
        return self.color is not None

    def get_color(self, model, row, column):
        """ Get data-associated colour values for the given item.

        The default implementation returns white.

        Parameters
        ----------
        model : AbstractDataModel
            The data model holding the data.
        row : sequence of int
            The row in the data model being queried.
        column : sequence of int
            The column in the data model being queried.

        Returns
        -------
        color : Color instance
            The color associated with the cell.
        """
        return self.color

    def has_image(self, model, row, column):
        return self.image is not None

    def get_image(self, model, row, column):
        if self.image is not None:
            return self.image
        return super().get_image(model, row, column)

    def get_tooltip(self, model, row, column):
        return self.tooltip

    @observe('color.rgba')
    def _color_updated(self, event):
        self.updated = True
示例#24
0
class ImageButton(LayoutWidget):
    """ An image and text-based control that can be used as a normal, radio or
        toolbar button.
    """

    # Pens used to draw the 'selection' marker:
    _selectedPenDark = wx.Pen(
        wx.SystemSettings.GetColour(wx.SYS_COLOUR_3DSHADOW), 1, wx.SOLID)

    _selectedPenLight = wx.Pen(
        wx.SystemSettings.GetColour(wx.SYS_COLOUR_3DHIGHLIGHT), 1, wx.SOLID)

    # ---------------------------------------------------------------------------
    #  Trait definitions:
    # ---------------------------------------------------------------------------

    # The image:
    image = Image()

    # The (optional) label:
    label = Str()

    # Extra padding to add to both the left and right sides:
    width_padding = Range(0, 31, 7)

    # Extra padding to add to both the top and bottom sides:
    height_padding = Range(0, 31, 5)

    # Presentation style:
    style = Enum("button", "radio", "toolbar", "checkbox")

    # Orientation of the text relative to the image:
    orientation = Orientation()

    # Is the control selected ('radio' or 'checkbox' style)?
    selected = Bool(False)

    # Fired when a 'button' or 'toolbar' style control is clicked:
    clicked = Event()

    _image = Any()

    # ---------------------------------------------------------------------------
    #  Initializes the object:
    # ---------------------------------------------------------------------------

    def __init__(self, parent, **traits):
        """ Creates a new image control.
        """
        create = traits.pop("create", True)

        super().__init__(parent=parent, **traits)

        if create:
            self.create()
            warnings.warn(
                "automatic widget creation is deprecated and will be removed "
                "in a future Pyface version, use create=False and explicitly "
                "call create() for future behaviour",
                PendingDeprecationWarning,
            )

    def _create_control(self, parent):
        self._recalc_size()

        control = wx.Window(parent, -1, size=wx.Size(self._dx, self._dy))
        control._owner = self
        self._mouse_over = self._button_down = False

        # Set up mouse event handlers:
        control.Bind(wx.EVT_ENTER_WINDOW, self._on_enter_window)
        control.Bind(wx.EVT_LEAVE_WINDOW, self._on_leave_window)
        control.Bind(wx.EVT_LEFT_DOWN, self._on_left_down)
        control.Bind(wx.EVT_LEFT_UP, self._on_left_up)
        control.Bind(wx.EVT_PAINT, self._on_paint)

        return control

    def _recalc_size(self):
        # Calculate the size of the button:
        idx = idy = tdx = tdy = 0
        if self._image is not None:
            idx = self._image.GetWidth()
            idy = self._image.GetHeight()

        if self.label != "":
            dc = wx.ScreenDC()
            dc.SetFont(wx.NORMAL_FONT)
            tdx, tdy = dc.GetTextExtent(self.label)

        wp2 = self.width_padding + 2
        hp2 = self.height_padding + 2
        if self.orientation == "horizontal":
            self._ix = wp2
            spacing = (idx > 0) * (tdx > 0) * 4
            self._tx = self._ix + idx + spacing
            dx = idx + tdx + spacing
            dy = max(idy, tdy)
            self._iy = hp2 + ((dy - idy) // 2)
            self._ty = hp2 + ((dy - tdy) // 2)
        else:
            self._iy = hp2
            spacing = (idy > 0) * (tdy > 0) * 2
            self._ty = self._iy + idy + spacing
            dx = max(idx, tdx)
            dy = idy + tdy + spacing
            self._ix = wp2 + ((dx - idx) // 2)
            self._tx = wp2 + ((dx - tdx) // 2)

        # Create the toolkit-specific control:
        self._dx = dx + wp2 + wp2
        self._dy = dy + hp2 + hp2

    # ---------------------------------------------------------------------------
    #  Handles the 'image' trait being changed:
    # ---------------------------------------------------------------------------

    def _image_changed(self, image):
        self._image = self._mono_image = None
        if image is not None:
            self._img = image.create_image()
            self._image = self._img.ConvertToBitmap()

        self._recalc_size()
        self.control.SetSize(wx.Size(self._dx, self._dy))

        if self.control is not None:
            self.control.Refresh()

    # ---------------------------------------------------------------------------
    #  Handles the 'selected' trait being changed:
    # ---------------------------------------------------------------------------

    def _selected_changed(self, selected):
        """ Handles the 'selected' trait being changed.
        """
        if selected and (self.style == "radio"):
            for control in self.control.GetParent().GetChildren():
                owner = getattr(control, "_owner", None)
                if (isinstance(owner, ImageButton) and owner.selected
                        and (owner is not self)):
                    owner.selected = False
                    break

        self.control.Refresh()

    # -- wx event handlers ----------------------------------------------------------

    def _on_enter_window(self, event):
        """ Called when the mouse enters the widget. """

        if self.style != "button":
            self._mouse_over = True
            self.control.Refresh()

    def _on_leave_window(self, event):
        """ Called when the mouse leaves the widget. """

        if self._mouse_over:
            self._mouse_over = False
            self.control.Refresh()

    def _on_left_down(self, event):
        """ Called when the left mouse button goes down on the widget. """
        self._button_down = True
        self.control.CaptureMouse()
        self.control.Refresh()

    def _on_left_up(self, event):
        """ Called when the left mouse button goes up on the widget. """
        control = self.control
        control.ReleaseMouse()
        self._button_down = False
        wdx, wdy = control.GetClientSize().Get()
        x, y = event.GetX(), event.GetY()
        control.Refresh()
        if (0 <= x < wdx) and (0 <= y < wdy):
            if self.style == "radio":
                self.selected = True
            elif self.style == "checkbox":
                self.selected = not self.selected
            else:
                self.clicked = True

    def _on_paint(self, event):
        """ Called when the widget needs repainting.
        """
        wdc = wx.PaintDC(self.control)
        wdx, wdy = self.control.GetClientSize().Get()
        ox = (wdx - self._dx) / 2
        oy = (wdy - self._dy) / 2

        disabled = not self.control.IsEnabled()
        if self._image is not None:
            image = self._image
            if disabled:
                if self._mono_image is None:
                    img = self._img
                    data = reshape(frombuffer(img.GetData(), dtype("uint8")),
                                   (-1, 3)) * array([[0.297, 0.589, 0.114]])
                    g = data[:, 0] + data[:, 1] + data[:, 2]
                    data[:, 0] = data[:, 1] = data[:, 2] = g
                    img.SetData(ravel(data.astype(dtype("uint8"))).tostring())
                    img.SetMaskColour(0, 0, 0)
                    self._mono_image = img.ConvertToBitmap()
                    self._img = None
                image = self._mono_image
            wdc.DrawBitmap(image, ox + self._ix, oy + self._iy, True)

        if self.label != "":
            if disabled:
                wdc.SetTextForeground(DisabledTextColor)
            wdc.SetFont(wx.NORMAL_FONT)
            wdc.DrawText(self.label, ox + self._tx, oy + self._ty)
        pens = [self._selectedPenLight, self._selectedPenDark]
        bd = self._button_down
        style = self.style
        is_rc = style in ("radio", "checkbox")
        if bd or (style == "button") or (is_rc and self.selected):
            if is_rc:
                bd = 1 - bd
            wdc.SetBrush(wx.TRANSPARENT_BRUSH)
            wdc.SetPen(pens[bd])
            wdc.DrawLine(1, 1, wdx - 1, 1)
            wdc.DrawLine(1, 1, 1, wdy - 1)
            wdc.DrawLine(2, 2, wdx - 2, 2)
            wdc.DrawLine(2, 2, 2, wdy - 2)
            wdc.SetPen(pens[1 - bd])
            wdc.DrawLine(wdx - 2, 2, wdx - 2, wdy - 1)
            wdc.DrawLine(2, wdy - 2, wdx - 2, wdy - 2)
            wdc.DrawLine(wdx - 3, 3, wdx - 3, wdy - 2)
            wdc.DrawLine(3, wdy - 3, wdx - 3, wdy - 3)

        elif self._mouse_over and (not self.selected):
            wdc.SetBrush(wx.TRANSPARENT_BRUSH)
            wdc.SetPen(pens[bd])
            wdc.DrawLine(0, 0, wdx, 0)
            wdc.DrawLine(0, 1, 0, wdy)
            wdc.SetPen(pens[1 - bd])
            wdc.DrawLine(wdx - 1, 1, wdx - 1, wdy)
            wdc.DrawLine(1, wdy - 1, wdx - 1, wdy - 1)