示例#1
0
class PythonShellTask(Task):
    """
    A task which provides a simple Python Shell to the user.
    """

    # Task Interface

    id = "pyface.tasks.contrib.python_shell"
    name = "Python Shell"

    # The list of bindings for the shell
    bindings = List(Dict)

    # The list of commands to run on shell startup
    commands = List(Str)

    # the IPythonShell instance that we are interacting with
    pane = Instance(PythonShellPane)

    # Task Interface

    menu_bar = SMenuBar(
        SMenu(
            TaskAction(name="Open...", method="open", accelerator="Ctrl+O"),
            id="File",
            name="&File",
        ),
        SMenu(id="View", name="&View"),
    )

    def create_central_pane(self):
        """ Create a view pane with a Python shell
        """
        logger.debug("Creating Python shell pane in central pane")
        self.pane = PythonShellPane(bindings=self.bindings,
                                    commands=self.commands)
        return self.pane

    # PythonShellTask API

    def open(self):
        """ Shows a dialog to open a file.
        """
        logger.debug("PythonShellTask: opening file")
        dialog = FileDialog(parent=self.window.control, wildcard="*.py")
        if dialog.open() == OK:
            self._open_file(dialog.path)

    # Private API

    def _open_file(self, path):
        """ Execute the selected file in the editor's interpreter
        """
        logger.debug('PythonShellTask: executing file "%s"' % path)
        self.pane.editor.execute_file(path)
示例#2
0
class SecondTask(ExampleTask):
    """ A simple task for opening a blank editor.
    """

    # Task interface -------------------------------------------------------

    id = "example.second_task"
    name = "Second Multi-Tab Editor"

    menu_bar = SMenuBar(
        SMenu(
            TaskAction(name="New", method="new", accelerator="Ctrl+N"),
            id="File",
            name="&File",
        ),
        SMenu(
            DockPaneToggleGroup(), TaskToggleGroup(), id="View", name="&View"
        ),
    )

    tool_bars = [
        SToolBar(
            TaskAction(
                method="new",
                tooltip="New file",
                image=ImageResource("document_new"),
            ),
            image_size=(32, 32),
        )
    ]

    # ------------------------------------------------------------------------
    # 'Task' interface.
    # ------------------------------------------------------------------------

    def _default_layout_default(self):
        return TaskLayout(
            left=VSplitter(
                HSplitter(
                    PaneItem("steps.pane1"),
                    PaneItem("steps.pane2"),
                    PaneItem("steps.pane3"),
                ),
                HSplitter(
                    PaneItem("steps.pane4"),
                    PaneItem("steps.pane5"),
                    PaneItem("steps.pane6"),
                ),
            )
        )
示例#3
0
 def _menu_bar_default(self):
     return SMenuBar(
         SMenu(
             TaskAction(name="New", method="new", accelerator="Ctrl+N"),
             id="File",
             name="&File",
         ),
         SMenu(
             DockPaneToggleGroup(),
             TaskToggleGroup(),
             id="View",
             name="&View",
         ),
     )
示例#4
0
    def _extra_actions_default(self):
        """ Extra application-wide menu items

        This adds a collection of standard Tasks application menu items and
        groups to a Task's set of menus.  Whether or not they actually appear
        depends on whether the appropriate menus are provided by the Task.

        These default additions assume that the window will hold an editor pane
        so that Ctrl-N and Ctrl-W will be bound to creating/closing new editors
        rather than new task windows.
        """
        from pyface.action.api import (
            AboutAction,
            CloseActiveWindowAction,
            ExitAction,
        )
        from pyface.action.schema.api import SMenu, SchemaAddition
        from pyface.tasks.action.api import (
            CreateTaskWindowAction,
            TaskWindowToggleGroup,
        )

        return [
            SchemaAddition(
                factory=CreateTaskWindowAction.factory(
                    application=self, accelerator="Ctrl+Shift+N"
                ),
                path="MenuBar/File/new_group",
            ),
            SchemaAddition(
                id="close_action",
                factory=CloseActiveWindowAction.factory(
                    application=self, accelerator="Ctrl+Shift+W"
                ),
                path="MenuBar/File/close_group",
            ),
            SchemaAddition(
                id="exit_action",
                factory=ExitAction.factory(application=self),
                path="MenuBar/File/close_group",
                absolute_position="last",
            ),
            SchemaAddition(
                # id='Window',
                factory=lambda: SMenu(
                    TaskWindowToggleGroup(application=self),
                    id="Window",
                    name="&Window",
                ),
                path="MenuBar",
                after="View",
                before="Help",
            ),
            SchemaAddition(
                id="about_action",
                factory=AboutAction.factory(application=self),
                path="MenuBar/Help",
                absolute_position="first",
            ),
        ]
示例#5
0
    def _menu_bar_default(self):
        menu_bar = SMenuBar(
            SMenu(
                SGroup(
                    group_factory=DockPaneToggleGroup,
                    id="tests.bogus_task.DockPaneToggleGroup",
                ),
                id="View",
                name="&View",
            )
        )

        return menu_bar
示例#6
0
class DialogWithSchema(HasTraits):
    """Test dialog with toolbar and menu schemas."""

    action_successful = Bool(False)

    def test_clicked(self):
        self.action_successful = True

    menubar = SMenuBar(
        SMenu(
            SGroup(
                ActionSchema(
                    action_factory=lambda **traits: TestAction,
                ),
            ),
            name="&Test menu",
        ),
    )

    toolbar = SToolBar(
        SGroup(
            ActionSchema(
                action_factory=lambda **traits: TestAction,
            ),
        ),
    )

    traits_view = View(
        Item(
            label="Click the button on the toolbar or the menu item.\n"
            "The 'Action successful' element should turn to True."
        ),
        Item("action_successful", style="readonly"),
        menubar=menubar,
        toolbar=toolbar,
        buttons=[TestAction, "OK"],
    )
示例#7
0
文件: step8.py 项目: enthought/pyface
class ExampleTask(Task):
    """ A simple task for opening a blank editor.
    """

    # Task interface -------------------------------------------------------

    id = "example.example_task"
    name = "Multi-Tab Editor"

    active_editor = Property(Instance(IEditor),
                             observe="editor_area.active_editor")

    editor_area = Instance(IEditorAreaPane)

    menu_bar = SMenuBar(
        SMenu(
            TaskAction(name="New", method="new", accelerator="Ctrl+N"),
            TaskAction(name="Add Task",
                       method="add_task",
                       accelerator="Ctrl+A"),
            TaskAction(name="Remove Task",
                       method="remove_task",
                       accelerator="Ctrl+R"),
            id="File",
            name="&File",
        ),
        SMenu(DockPaneToggleGroup(),
              TaskToggleGroup(),
              id="View",
              name="&View"),
    )

    tool_bars = [
        SToolBar(
            TaskAction(
                method="new",
                tooltip="New file",
                image=ImageResource("document_new"),
            ),
            image_size=(32, 32),
        )
    ]

    # ------------------------------------------------------------------------
    # 'Task' interface.
    # ------------------------------------------------------------------------

    def _default_layout_default(self):
        return TaskLayout(top=VSplitter(
            HSplitter(PaneItem("steps.pane1"), PaneItem("steps.pane2"))))

    def create_central_pane(self):
        """ Create the central pane: the script editor.
        """
        self.editor_area = EditorAreaPane()
        return self.editor_area

    def create_dock_panes(self):
        """ Create the file browser and connect to its double click event.
        """
        return [Pane1(), Pane2()]

    # ------------------------------------------------------------------------
    # 'ExampleTask' interface.
    # ------------------------------------------------------------------------

    def new(self):
        """ Opens a new empty window
        """
        editor = Editor()
        self.editor_area.add_editor(editor)
        self.editor_area.activate_editor(editor)
        self.activated()

    def add_task(self):
        """ Opens a new empty window
        """
        task3 = ThirdTask()
        self.window.add_task(task3)
        self.window.activate_task(task3)

    def remove_task(self):
        """ Opens a new empty window
        """
        task = self.window.tasks[0]
        window = self.window
        window.remove_task(self)
        window.activate_task(task)

    # Trait property getter/setters ----------------------------------------

    def _get_active_editor(self):
        if self.editor_area is not None:
            return self.editor_area.active_editor
        return None
示例#8
0
class PythonEditorTask(Task):
    """ A simple task for editing Python code.
    """

    # 'Task' traits -----------------------------------------------------------

    #: The unique id of the task.
    id = "example.python_editor_task"

    #: The human-readable name of the task.
    name = "Python Editor"

    #: The currently active editor in the editor area, if any.
    active_editor = Property(
        Instance(IEditor), observe="editor_area.active_editor"
    )

    #: The editor area for this task.
    editor_area = Instance(IEditorAreaPane)

    #: The menu bar for the task.
    menu_bar = SMenuBar(
        SMenu(
            SGroup(
                TaskAction(name="New", method="new", accelerator="Ctrl+N"),
                id="new_group",
            ),
            SGroup(
                TaskAction(
                    name="Open...", method="open", accelerator="Ctrl+O"
                ),
                id="open_group",
            ),
            SGroup(
                TaskAction(
                    name="Save",
                    method="save",
                    accelerator="Ctrl+S",
                    enabled_name="active_editor.dirty",
                ),
                TaskAction(
                    name="Save As...",
                    method="save_as",
                    accelerator="Ctrl+Shift+S",
                ),
                id="save_group",
            ),
            SGroup(
                TaskAction(
                    name="Close Editor",
                    method="close_editor",
                    accelerator="Ctrl+W",
                ),
                id="close_group",
            ),
            id="File",
            name="&File",
        ),
        SMenu(
            SGroup(
                EditorAction(
                    name="Undo",
                    method="undo",
                    enabled_name="can_undo",
                    accelerator="Ctrl+Z",
                ),
                EditorAction(
                    name="Redo",
                    method="redo",
                    enabled_name="can_redo",
                    accelerator="Ctrl+Shift+Z",
                ),
                id="undo_group",
            ),
            SGroup(
                EditorAction(
                    name="Go to Line...",
                    method="go_to_line",
                    accelerator="Ctrl+G",
                ),
                id="search_group",
            ),
            id="Edit",
            name="&Edit",
        ),
        SMenu(DockPaneToggleGroup(), id="View", name="&View"),
        SMenu(
            SGroup(
                OpenURLAction(
                    name="Python Documentation",
                    id="python_docs",
                    url=PYTHON_DOCS,
                ),
                id="documentation_group",
            ),
            id="Help",
            name="&Help",
        ),
    )

    #: The tool bars for the task.
    tool_bars = [
        SToolBar(
            TaskAction(
                method="new",
                tooltip="New file",
                image=ImageResource("document_new"),
            ),
            TaskAction(
                method="open",
                tooltip="Open a file",
                image=ImageResource("document_open"),
            ),
            TaskAction(
                method="save",
                tooltip="Save the current file",
                image=ImageResource("document_save"),
                enabled_name="active_editor.dirty",
            ),
            image_size=(16, 16),
            show_tool_names=False,
        )
    ]

    #: The status bar for the window when this task is active.
    status_bar = Instance(StatusBarManager, ())

    # -------------------------------------------------------------------------
    # 'PythonEditorTask' interface.
    # -------------------------------------------------------------------------

    def create_editor(self, path=""):
        """ Create a new editor in the editor pane.

        Parameters
        ----------
        path : path or ''
            The path to the file to edit, or '' for an empty editor.
        """
        if path:
            path = os.path.abspath(path)
        use_existing = path != ""
        self.editor_area.edit(
            path, factory=PythonEditor, use_existing=use_existing
        )
        if path:
            self.active_editor.load()

    def close_editor(self):
        """ Close the active editor, or if no editors, close the Task window.
        """
        if self.editor_area.active_editor is not None:
            self.editor_area.remove_editor(self.editor_area.active_editor)
        else:
            self.window.close()

    def new(self):
        """ Open a new empty window
        """
        self.create_editor()

    def open(self):
        """ Shows a dialog to open a Python file.
        """
        dialog = FileDialog(parent=self.window.control, wildcard="*.py")
        if dialog.open() == OK:
            self.create_editor(dialog.path)

    def save(self):
        """ Save the current file.

        If needed, this code prompts for a path.

        Returns
        -------
        saved : bool
            Whether or not the file was saved.
        """
        editor = self.active_editor
        try:
            editor.save()
        except IOError:
            # If you are trying to save to a file that doesn't exist, open up a
            # FileDialog with a 'save as' action.
            dialog = FileDialog(
                parent=self.window.control, action="save as", wildcard="*.py"
            )
            if dialog.open() == OK:
                editor.save(dialog.path)
            else:
                return False
        return True

    # -------------------------------------------------------------------------
    # 'Task' interface.
    # -------------------------------------------------------------------------

    def _default_layout_default(self):
        """ The default layout with the browser pane on the left.
        """
        return TaskLayout(
            left=PaneItem("example.python_browser_pane", width=200)
        )

    def create_central_pane(self):
        """ Create the central pane: the script editor.
        """
        self.editor_area = EditorAreaPane()
        return self.editor_area

    def create_dock_panes(self):
        """ Create the file browser and connect to its double click event.
        """
        browser = PythonBrowserPane()

        def handler(event):
            path = event.new
            if os.path.isfile(path):
                return self.create_editor(path)

        browser.observe(handler, "activated")
        return [browser]

    # -------------------------------------------------------------------------
    # Protected interface.
    # -------------------------------------------------------------------------

    def _prompt_for_save(self):
        """ Prompts the user to save if necessary. Returns whether the dialog
            was cancelled.
        """
        dirty_editors = {
            editor.name: editor
            for editor in self.editor_area.editors
            if editor.dirty and (editor.obj or editor.code)
        }
        if not dirty_editors:
            return True

        message = "You have unsaved files. Would you like to save them?"
        dialog = ConfirmationDialog(
            parent=self.window.control,
            message=message,
            cancel=True,
            default=CANCEL,
            title="Save Changes?",
        )
        result = dialog.open()
        if result == CANCEL:
            return False
        elif result == YES:
            for name, editor in dirty_editors.items():
                editor.save(editor.path)
        return True

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

    @observe("window:closing")
    def _prompt_on_close(self, event):
        """ Prompt the user to save when exiting.
        """
        close = self._prompt_for_save()
        window = event.new
        window.veto = not close

    @observe("active_editor.name")
    def _change_title(self, event):
        """ Update the window title when the active editor changes.
        """
        if self.window.active_task == self:
            if self.active_editor is not None:
                self.window.title = self.active_editor.name
            else:
                self.window.title = self.name

    @observe("active_editor.[line,column,selection_length]")
    def _update_status(self, event):
        if self.active_editor is not None:
            editor = self.active_editor
            if editor.selection_length:
                self.status_bar.messages = [
                    "Ln {}, Col {} ({} selected)".format(
                        editor.line, editor.column, editor.selection_length
                    )
                ]
            else:
                self.status_bar.messages = [
                    "Ln {}, Col {}".format(editor.line, editor.column)
                ]
        else:
            self.status_bar.messages = []

    # Trait property getter/setters ------------------------------------------

    @cached_property
    def _get_active_editor(self):
        if self.editor_area is not None:
            return self.editor_area.active_editor
        return None
示例#9
0
class ExampleTask(Task):
    """ A simple task for editing Python code.
    """

    # Task interface -------------------------------------------------------

    id = "example.example_task"
    name = "Multi-Tab Editor"

    active_editor = Property(Instance(IEditor),
                             observe="editor_area.active_editor")

    editor_area = Instance(IEditorAreaPane)

    menu_bar = SMenuBar(
        SMenu(
            TaskAction(name="New", method="new", accelerator="Ctrl+N"),
            TaskAction(name="Open...", method="open", accelerator="Ctrl+O"),
            TaskAction(name="Save", method="save", accelerator="Ctrl+S"),
            id="File",
            name="&File",
        ),
        SMenu(DockPaneToggleGroup(), id="View", name="&View"),
    )

    tool_bars = [
        SToolBar(
            TaskAction(
                method="new",
                tooltip="New file",
                image=ImageResource("document_new"),
            ),
            TaskAction(
                method="open",
                tooltip="Open a file",
                image=ImageResource("document_open"),
            ),
            TaskAction(
                method="save",
                tooltip="Save the current file",
                image=ImageResource("document_save"),
            ),
            image_size=(32, 32),
            show_tool_names=False,
        )
    ]

    # ------------------------------------------------------------------------
    # 'Task' interface.
    # ------------------------------------------------------------------------

    def _default_layout_default(self):
        return TaskLayout(left=PaneItem("example.python_script_browser_pane"))

    def activated(self):
        """ Overriden to set the window's title.
        """
        return
        filename = self.active_editor.path if self.active_editor else ""
        self.window.title = filename if filename else "Untitled"

    def create_central_pane(self):
        """ Create the central pane: the script editor.
        """
        self.editor_area = EditorAreaPane()
        return self.editor_area

    def create_dock_panes(self):
        """ Create the file browser and connect to its double click event.
        """
        browser = PythonScriptBrowserPane()
        handler = lambda _: self._open_file(browser.selected_file)
        browser.observe(handler, "activated")
        return [browser]

    # ------------------------------------------------------------------------
    # 'ExampleTask' interface.
    # ------------------------------------------------------------------------

    def new(self):
        """ Opens a new empty window
        """
        editor = PythonEditor()
        self.editor_area.add_editor(editor)
        self.editor_area.activate_editor(editor)
        self.activated()

    def open(self):
        """ Shows a dialog to open a file.
        """
        dialog = FileDialog(parent=self.window.control, wildcard="*.py")
        if dialog.open() == OK:
            self._open_file(dialog.path)

    def save(self):
        """ Attempts to save the current file, prompting for a path if
            necessary. Returns whether the file was saved.
        """
        editor = self.active_editor
        try:
            editor.save()
        except IOError:
            # If you are trying to save to a file that doesn't exist, open up a
            # FileDialog with a 'save as' action.
            dialog = FileDialog(parent=self.window.control,
                                action="save as",
                                wildcard="*.py")
            if dialog.open() == OK:
                editor.save(dialog.path)
            else:
                return False
        return True

    # ------------------------------------------------------------------------
    # Protected interface.
    # ------------------------------------------------------------------------

    def _open_file(self, filename):
        """ Opens the file at the specified path in the editor.
        """
        editor = PythonEditor(path=filename)
        self.editor_area.add_editor(editor)
        self.editor_area.activate_editor(editor)
        self.activated()

    def _prompt_for_save(self):
        """ Prompts the user to save if necessary. Returns whether the dialog
            was cancelled.
        """
        dirty_editors = dict([(editor.name, editor)
                              for editor in self.editor_area.editors
                              if editor.dirty])
        if not dirty_editors.keys():
            return True
        message = "You have unsaved files. Would you like to save them?"
        dialog = ConfirmationDialog(
            parent=self.window.control,
            message=message,
            cancel=True,
            default=CANCEL,
            title="Save Changes?",
        )
        result = dialog.open()
        if result == CANCEL:
            return False
        elif result == YES:
            for name, editor in dirty_editors.items():
                editor.save(editor.path)
        return True

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

    @observe("window:closing")
    def _prompt_on_close(self, event):
        """ Prompt the user to save when exiting.
        """
        close = self._prompt_for_save()
        window = event.new
        window.veto = not close

    # Trait property getter/setters ----------------------------------------

    def _get_active_editor(self):
        if self.editor_area is not None:
            return self.editor_area.active_editor
        return None
示例#10
0
文件: step2.py 项目: enthought/pyface
class ExampleTask(Task):
    """ A simple task for opening a blank editor.
    """

    # Task interface -------------------------------------------------------

    id = "example.example_task"
    name = "Multi-Tab Editor"

    active_editor = Property(
        Instance(IEditor), observe="editor_area.active_editor"
    )

    editor_area = Instance(IEditorAreaPane)

    menu_bar = SMenuBar(
        SMenu(
            TaskAction(name="New", method="new", accelerator="Ctrl+N"),
            id="File",
            name="&File",
        ),
        SMenu(DockPaneToggleGroup(), id="View", name="&View"),
    )

    tool_bars = [
        SToolBar(
            TaskAction(
                method="new",
                tooltip="New file",
                image=ImageResource("document_new"),
            ),
            image_size=(32, 32),
        )
    ]

    # ------------------------------------------------------------------------
    # 'Task' interface.
    # ------------------------------------------------------------------------

    def create_central_pane(self):
        """ Create the central pane: the script editor.
        """
        self.editor_area = EditorAreaPane()
        return self.editor_area

    # ------------------------------------------------------------------------
    # 'ExampleTask' interface.
    # ------------------------------------------------------------------------

    def new(self):
        """ Opens a new empty window
        """
        editor = Editor()
        self.editor_area.add_editor(editor)
        self.editor_area.activate_editor(editor)
        self.activated()

    # Trait property getter/setters ----------------------------------------

    def _get_active_editor(self):
        if self.editor_area is not None:
            return self.editor_area.active_editor
        return None
示例#11
0
class ExampleTask(Task):
    """ A simple task for editing Python code.
    """

    # Task interface -------------------------------------------------------

    id = "example.example_task"
    name = "Python Script Editor"

    # default_layout = TaskLayout(
    #    left=PaneItem('example.python_script_browser_pane'))

    menu_bar = SMenuBar(
        SMenu(
            TaskAction(name="Open...", method="open", accelerator="Ctrl+O"),
            TaskAction(name="Save", method="save", accelerator="Ctrl+S"),
            id="File",
            name="&File",
        ),
        SMenu(DockPaneToggleGroup(), id="View", name="&View"),
    )

    tool_bars = [
        SToolBar(
            TaskAction(
                method="open",
                tooltip="Open a file",
                image=ImageResource("document_open"),
            ),
            TaskAction(
                method="save",
                tooltip="Save the current file",
                image=ImageResource("document_save"),
            ),
        )
    ]

    # ------------------------------------------------------------------------
    # 'Task' interface.
    # ------------------------------------------------------------------------

    def _default_layout_default(self):
        return TaskLayout(left=PaneItem("example.python_script_browser_pane"))

    def activated(self):
        """ Overriden to set the window's title.
        """
        filename = self.window.central_pane.editor.path
        self.window.title = filename if filename else "Untitled"

    def create_central_pane(self):
        """ Create the central pane: the script editor.
        """
        return PythonEditorPane()

    def create_dock_panes(self):
        """ Create the file browser and connect to its double click event.
        """
        browser = PythonScriptBrowserPane()
        handler = lambda _: self._open_file(browser.selected_file)
        browser.observe(handler, "activated")
        return [browser]

    # ------------------------------------------------------------------------
    # 'ExampleTask' interface.
    # ------------------------------------------------------------------------

    def open(self):
        """ Shows a dialog to open a file.
        """
        dialog = FileDialog(parent=self.window.control, wildcard="*.py")
        if dialog.open() == OK:
            self._open_file(dialog.path)

    def save(self):
        """ Attempts to save the current file, prompting for a path if
            necessary. Returns whether the file was saved.
        """
        editor = self.window.central_pane.editor
        try:
            editor.save()
        except IOError:
            # If you are trying to save to a file that doesn't exist, open up a
            # FileDialog with a 'save as' action.
            dialog = FileDialog(parent=self.window.control,
                                action="save as",
                                wildcard="*.py")
            if dialog.open() == OK:
                editor.save(dialog.path)
            else:
                return False
        return True

    # ------------------------------------------------------------------------
    # Protected interface.
    # ------------------------------------------------------------------------

    def _open_file(self, filename):
        """ Opens the file at the specified path in the editor.
        """
        if self._prompt_for_save():
            self.window.central_pane.editor.path = filename
            self.activated()

    def _prompt_for_save(self):
        """ Prompts the user to save if necessary. Returns whether the dialog
            was cancelled.
        """
        if self.window.central_pane.editor.dirty:
            message = ("The current file has unsaved changes. "
                       "Do you want to save your changes?")
            dialog = ConfirmationDialog(
                parent=self.window.control,
                message=message,
                cancel=True,
                default=CANCEL,
                title="Save Changes?",
            )
            result = dialog.open()
            if result == CANCEL:
                return False
            elif result == YES:
                if not self.save():
                    return self._prompt_for_save()
        return True

    @observe("window:closing")
    def _prompt_on_close(self, event):
        """ Prompt the user to save when exiting.
        """
        window = event.new
        if not self._prompt_for_save():
            window.veto = True