<commit_before>#------------------------------------------------------------------------------
# Copyright (c) 2007, Riverbank Computing Limited
# All rights reserved.
#
# This software is provided without warranty under the terms of the BSD license.
# However, when used with the GPL version of PyQt the additional terms described in the PyQt GPL exception also apply

#
# Author: Riverbank Computing Limited
#------------------------------------------------------------------------------

"""Defines the base class for the PyQt-based Traits UI modal and non-modal
   dialogs.
"""


from PyQt4 import QtCore, QtGui

from enthought.traits.api \
    import HasStrictTraits, HasPrivateTraits, Instance, List, Event

from enthought.traits.ui.api \
    import UI

from enthought.traits.ui.menu \
    import Action

from constants \
    import DefaultTitle

from editor \
    import Editor

from helper \
    import restore_window, save_window


#-------------------------------------------------------------------------------
#  Constants:
#-------------------------------------------------------------------------------

# List of all predefined system button names:
SystemButtons = ['Undo', 'Redo', 'Apply', 'Revert', 'OK', 'Cancel', 'Help']

#-------------------------------------------------------------------------------
#  'RadioGroup' class:
#-------------------------------------------------------------------------------

class RadioGroup ( HasStrictTraits ):
    """ A group of mutually-exclusive menu or toolbar actions.
    """
    # List of menu or tool bar items
    items = List  

    #---------------------------------------------------------------------------
    #  Handles a menu item in the group being checked:
    #---------------------------------------------------------------------------

    def menu_checked ( self, menu_item ):
        """ Handles a menu item in the group being checked.
        """
        for item in self.items:
            if item is not menu_item:
                item.control.Check( False )
                item.item.action.checked = False

    #---------------------------------------------------------------------------
    #  Handles a tool bar item in the group being checked:
    #---------------------------------------------------------------------------

    def toolbar_checked ( self, toolbar_item ):
        """ Handles a tool bar item in the group being checked.
        """
        for item in self.items:
            if item is not toolbar_item:
                item.tool_bar.ToggleTool( item.control_id, False )
                item.item.action.checked = False

#-------------------------------------------------------------------------------
#  'ButtonEditor' class:
#-------------------------------------------------------------------------------

class ButtonEditor(Editor):
    """ Editor for buttons.
    """
    #---------------------------------------------------------------------------
    #  Trait definitions:
    #---------------------------------------------------------------------------

    # Action associated with the button
    action = Instance(Action)

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

    def __init__(self, **traits):
        self.set(**traits)

    #---------------------------------------------------------------------------
    #  Handles the associated button being clicked:
    #---------------------------------------------------------------------------

    def perform(self):
        """Handles the associated button being clicked."""
        self.ui.do_undoable(self._perform, None)

    def _perform(self, event):
        method_name = self.action.action
        if method_name == '':
            method_name = '_%s_clicked' % self.action.name.lower()

        method = getattr(self.ui.handler, method_name, None)
        if method is not None:
            method(self.ui.info)
        else:
            self.action.perform(event)


class BasePanel(object):
    """Base class for Traits UI panels.
    """

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

    def perform ( self, action ):
        """ Performs the action described by a specified Action object.
        """
        self.ui.do_undoable( self._perform, action )

    def _perform ( self, action ):
        method = getattr( self.ui.handler, action.action, None )
        if method is not None:
            method( self.ui.info )
        else:
            action.perform()

    #---------------------------------------------------------------------------
    #  Check to see if a specified 'system' button is in the buttons list, and
    # add it if it is not:
    #---------------------------------------------------------------------------

    def check_button ( self, buttons, action ):
        """ Adds *action* to the system buttons list for this dialog, if it is
        not already in the list.
        """
        name = action.name
        for button in buttons:
            if self.is_button( button, name ):
                return
        buttons.append( action )

    #---------------------------------------------------------------------------
    #  Check to see if a specified Action button is a 'system' button:
    #---------------------------------------------------------------------------

    def is_button ( self, action, name ):
        """ Returns whether a specified action button is a system button.
        """
        if isinstance(action, basestring):
            return (action == name)
        return (action.name == name)

    #---------------------------------------------------------------------------
    #  Coerces a string to an Action if necessary:
    #---------------------------------------------------------------------------

    def coerce_button ( self, action ):
        """ Coerces a string to an Action if necessary.
        """
        if isinstance(action, basestring):
            return Action( name   = action,
                           action = '?'[ (not action in SystemButtons): ] )
        return action

    #---------------------------------------------------------------------------
    #  Creates a user specified button:
    #---------------------------------------------------------------------------

    def add_button ( self, action, bbox, role, method=None, enabled=True, name=None ):
        """ Creates a button.
        """
        ui = self.ui
        if ((action.defined_when != '') and
            (not ui.eval_when( action.defined_when ))):
            return None

        if name is None:
            name = action.name
        id     = action.id
        button = bbox.addButton(name, role)
        button.setAutoDefault(False)
        button.setEnabled(enabled)
        if (method is None) or (action.enabled_when != '') or (id != ''):
            editor = ButtonEditor( ui      = ui,
                                   action  = action,
                                   control = button )
            if id != '':
                ui.info.bind( id, editor )
            if action.visible_when != '':
                ui.add_visible( action.visible_when, editor )
            if action.enabled_when != '':
                ui.add_enabled( action.enabled_when, editor )
            if method is None:
                method = editor.perform

        if method is not None:
            button.connect(button, QtCore.SIGNAL('clicked()'), method)

        if action.tooltip != '':
            button.setToolTip(action.tooltip)

        return button

    def _on_help(self):
        """Handles the user clicking the Help button.
        """
        # FIXME: Needs porting to PyQt.
        self.ui.handler.show_help(self.ui.info, event.GetEventObject())

    def _on_undo(self):
        """Handles a request to undo a change.
        """
        self.ui.history.undo()

    def _on_undoable(self, state):
        """Handles a change to the "undoable" state of the undo history
        """
        self.undo.setEnabled(state)

    def _on_redo(self):
        """Handles a request to redo a change.
        """
        self.ui.history.redo()

    def _on_redoable(self, state):
        """Handles a change to the "redoable" state of the undo history.
        """
        self.redo.setEnabled(state)

    def _on_revert(self):
        """Handles a request to revert all changes.
        """
        ui = self.ui
        if ui.history is not None:
            ui.history.revert()
        ui.handler.revert(ui.info)

    def _on_revertable(self, state):
        """ Handles a change to the "revert" state.
        """
        self.revert.setEnabled(state)


class _StickyDialog(QtGui.QDialog):
    """A QDialog that will only close if the traits handler allows it."""

    def __init__(self, ui, parent):
        """Initialise the dialog."""

        QtGui.QDialog.__init__(self, parent)

        # Create the main window so we can add toolbars etc.
        self._mw = QtGui.QMainWindow()
        layout = QtGui.QVBoxLayout()
        layout.setMargin(0)
        layout.addWidget(self._mw)
        self.setLayout(layout)

        # Set the dialog's window flags and properties.
        if ui.view.resizable:
            flags = QtCore.Qt.Window
        else:
            flags = QtCore.Qt.Dialog | QtCore.Qt.WindowSystemMenuHint
            layout.setSizeConstraint(QtGui.QLayout.SetFixedSize)
        try:
            flags |= QtCore.Qt.WindowCloseButtonHint
        except AttributeError:
            # Either PyQt or Qt is too old.
            pass
        self.setWindowFlags(flags)

        self._ui = ui
        self._result = None

    def closeEvent(self, e):
        """Reimplemented to check when the clicks the window close button.
        (Note that QDialog doesn't get a close event when the dialog is closed
        in any other way.)"""

        if self._ok_to_close():
            QtGui.QDialog.closeEvent(self, e)
        else:
            # Ignore the event thereby keeping the dialog open.
            e.ignore()

    def keyPressEvent(self, e):
        """Reimplemented to ignore the Escape key if appropriate, and always
        ignore the Enter key because it will trigger a button if any are
        present in the dialog."""
<commit_msg>BUG: Make sure we have the minimize and maximize buttons on resizable UIs.<commit_after>#------------------------------------------------------------------------------
# Copyright (c) 2007, Riverbank Computing Limited
# All rights reserved.
#
# This software is provided without warranty under the terms of the BSD license.
# However, when used with the GPL version of PyQt the additional terms described in the PyQt GPL exception also apply

#
# Author: Riverbank Computing Limited
#------------------------------------------------------------------------------

"""Defines the base class for the PyQt-based Traits UI modal and non-modal
   dialogs.
"""


from PyQt4 import QtCore, QtGui

from enthought.traits.api \
    import HasStrictTraits, HasPrivateTraits, Instance, List, Event

from enthought.traits.ui.api \
    import UI

from enthought.traits.ui.menu \
    import Action

from constants \
    import DefaultTitle

from editor \
    import Editor

from helper \
    import restore_window, save_window


#-------------------------------------------------------------------------------
#  Constants:
#-------------------------------------------------------------------------------

# List of all predefined system button names:
SystemButtons = ['Undo', 'Redo', 'Apply', 'Revert', 'OK', 'Cancel', 'Help']

#-------------------------------------------------------------------------------
#  'RadioGroup' class:
#-------------------------------------------------------------------------------

class RadioGroup ( HasStrictTraits ):
    """ A group of mutually-exclusive menu or toolbar actions.
    """
    # List of menu or tool bar items
    items = List  

    #---------------------------------------------------------------------------
    #  Handles a menu item in the group being checked:
    #---------------------------------------------------------------------------

    def menu_checked ( self, menu_item ):
        """ Handles a menu item in the group being checked.
        """
        for item in self.items:
            if item is not menu_item:
                item.control.Check( False )
                item.item.action.checked = False

    #---------------------------------------------------------------------------
    #  Handles a tool bar item in the group being checked:
    #---------------------------------------------------------------------------

    def toolbar_checked ( self, toolbar_item ):
        """ Handles a tool bar item in the group being checked.
        """
        for item in self.items:
            if item is not toolbar_item:
                item.tool_bar.ToggleTool( item.control_id, False )
                item.item.action.checked = False

#-------------------------------------------------------------------------------
#  'ButtonEditor' class:
#-------------------------------------------------------------------------------

class ButtonEditor(Editor):
    """ Editor for buttons.
    """
    #---------------------------------------------------------------------------
    #  Trait definitions:
    #---------------------------------------------------------------------------

    # Action associated with the button
    action = Instance(Action)

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

    def __init__(self, **traits):
        self.set(**traits)

    #---------------------------------------------------------------------------
    #  Handles the associated button being clicked:
    #---------------------------------------------------------------------------

    def perform(self):
        """Handles the associated button being clicked."""
        self.ui.do_undoable(self._perform, None)

    def _perform(self, event):
        method_name = self.action.action
        if method_name == '':
            method_name = '_%s_clicked' % self.action.name.lower()

        method = getattr(self.ui.handler, method_name, None)
        if method is not None:
            method(self.ui.info)
        else:
            self.action.perform(event)


class BasePanel(object):
    """Base class for Traits UI panels.
    """

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

    def perform ( self, action ):
        """ Performs the action described by a specified Action object.
        """
        self.ui.do_undoable( self._perform, action )

    def _perform ( self, action ):
        method = getattr( self.ui.handler, action.action, None )
        if method is not None:
            method( self.ui.info )
        else:
            action.perform()

    #---------------------------------------------------------------------------
    #  Check to see if a specified 'system' button is in the buttons list, and
    # add it if it is not:
    #---------------------------------------------------------------------------

    def check_button ( self, buttons, action ):
        """ Adds *action* to the system buttons list for this dialog, if it is
        not already in the list.
        """
        name = action.name
        for button in buttons:
            if self.is_button( button, name ):
                return
        buttons.append( action )

    #---------------------------------------------------------------------------
    #  Check to see if a specified Action button is a 'system' button:
    #---------------------------------------------------------------------------

    def is_button ( self, action, name ):
        """ Returns whether a specified action button is a system button.
        """
        if isinstance(action, basestring):
            return (action == name)
        return (action.name == name)

    #---------------------------------------------------------------------------
    #  Coerces a string to an Action if necessary:
    #---------------------------------------------------------------------------

    def coerce_button ( self, action ):
        """ Coerces a string to an Action if necessary.
        """
        if isinstance(action, basestring):
            return Action( name   = action,
                           action = '?'[ (not action in SystemButtons): ] )
        return action

    #---------------------------------------------------------------------------
    #  Creates a user specified button:
    #---------------------------------------------------------------------------

    def add_button ( self, action, bbox, role, method=None, enabled=True, name=None ):
        """ Creates a button.
        """
        ui = self.ui
        if ((action.defined_when != '') and
            (not ui.eval_when( action.defined_when ))):
            return None

        if name is None:
            name = action.name
        id     = action.id
        button = bbox.addButton(name, role)
        button.setAutoDefault(False)
        button.setEnabled(enabled)
        if (method is None) or (action.enabled_when != '') or (id != ''):
            editor = ButtonEditor( ui      = ui,
                                   action  = action,
                                   control = button )
            if id != '':
                ui.info.bind( id, editor )
            if action.visible_when != '':
                ui.add_visible( action.visible_when, editor )
            if action.enabled_when != '':
                ui.add_enabled( action.enabled_when, editor )
            if method is None:
                method = editor.perform

        if method is not None:
            button.connect(button, QtCore.SIGNAL('clicked()'), method)

        if action.tooltip != '':
            button.setToolTip(action.tooltip)

        return button

    def _on_help(self):
        """Handles the user clicking the Help button.
        """
        # FIXME: Needs porting to PyQt.
        self.ui.handler.show_help(self.ui.info, event.GetEventObject())

    def _on_undo(self):
        """Handles a request to undo a change.
        """
        self.ui.history.undo()

    def _on_undoable(self, state):
        """Handles a change to the "undoable" state of the undo history
        """
        self.undo.setEnabled(state)

    def _on_redo(self):
        """Handles a request to redo a change.
        """
        self.ui.history.redo()

    def _on_redoable(self, state):
        """Handles a change to the "redoable" state of the undo history.
        """
        self.redo.setEnabled(state)

    def _on_revert(self):
        """Handles a request to revert all changes.
        """
        ui = self.ui
        if ui.history is not None:
            ui.history.revert()
        ui.handler.revert(ui.info)

    def _on_revertable(self, state):
        """ Handles a change to the "revert" state.
        """
        self.revert.setEnabled(state)


class _StickyDialog(QtGui.QDialog):
    """A QDialog that will only close if the traits handler allows it."""

    def __init__(self, ui, parent):
        """Initialise the dialog."""

        QtGui.QDialog.__init__(self, parent)

        # Create the main window so we can add toolbars etc.
        self._mw = QtGui.QMainWindow()
        layout = QtGui.QVBoxLayout()
        layout.setMargin(0)
        layout.addWidget(self._mw)
        self.setLayout(layout)

        # Set the dialog's window flags and properties.
        if ui.view.resizable:
            flags = QtCore.Qt.Window
        else:
            flags = QtCore.Qt.Dialog | QtCore.Qt.WindowSystemMenuHint
            layout.setSizeConstraint(QtGui.QLayout.SetFixedSize)
        try:
            flags |= QtCore.Qt.WindowCloseButtonHint
            if ui.view.resizable:
                flags |= QtCore.Qt.WindowMinimizeButtonHint | Qtcore.Qt.WindowMaximizeButtonHint
        except AttributeError:
            # Either PyQt or Qt is too old.
            pass
        self.setWindowFlags(flags)

        self._ui = ui
        self._result = None

    def closeEvent(self, e):
        """Reimplemented to check when the clicks the window close button.
        (Note that QDialog doesn't get a close event when the dialog is closed
        in any other way.)"""

        if self._ok_to_close():
            QtGui.QDialog.closeEvent(self, e)
        else:
            # Ignore the event thereby keeping the dialog open.
            e.ignore()

    def keyPressEvent(self, e):
        """Reimplemented to ignore the Escape key if appropriate, and always
        ignore the Enter key because it will trigger a button if any are
        present in the dialog."""

{'fraction_non_alphanumeric': 0.2753623188405797, 'fraction_numerical': 0.000564652738565782, 'mean_word_length': 1.1246626012196341, 'pattern_counts': {'":': 0, '<': 3, '<?xml version=': 0, '>': 3, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 4, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '4991902', 'n_tokens_mistral': 4913, 'n_tokens_neox': 4748, 'n_words': 1569}